lang
stringclasses
2 values
license
stringclasses
13 values
stderr
stringlengths
0
343
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
6
87.7k
new_contents
stringlengths
0
6.23M
new_file
stringlengths
3
311
old_contents
stringlengths
0
6.23M
message
stringlengths
6
9.1k
old_file
stringlengths
3
311
subject
stringlengths
0
4k
git_diff
stringlengths
0
6.31M
Java
apache-2.0
06e512dad9e458ebf517ea7e50f283febd552cfc
0
Netflix-Skunkworks/WSPerfLab,Netflix-Skunkworks/WSPerfLab,Netflix-Skunkworks/WSPerfLab
package perf.test.netty.client; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.GenericFutureListener; import io.netty.util.concurrent.Promise; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import perf.test.netty.PropertyNames; import java.util.concurrent.atomic.AtomicInteger; /** * @author Nitesh Kant ([email protected]) */ public class ClientHandler extends SimpleChannelInboundHandler<FullHttpResponse> { private final Logger logger = LoggerFactory.getLogger(ClientHandler.class); public static final int MAX_RETRIES = 3; private final long id; private final DedicatedClientPool<FullHttpResponse, FullHttpRequest> pool; public ClientHandler(DedicatedClientPool<FullHttpResponse, FullHttpRequest> pool, long id) { this.pool = pool; this.id = id; } @Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse response) throws Exception { AtomicInteger retries = ctx.channel().attr(DedicatedClientPool.RETRY_COUNT_KEY).get(); if (logger.isDebugEnabled()) { logger.debug("Response completed after {} retries", null == retries ? 0 : retries); } if (PropertyNames.ServerTraceRequests.getValueAsBoolean()) { checkpoint(ctx, "Response completed after retries: " + retries); } retries.set(0); // Response received so reset retry. Promise<FullHttpResponse> completionPromise = ctx.channel().attr(pool.getProcessingCompletePromiseKey()).get(); response.content().retain(); if (!completionPromise.trySuccess(response)) { logger.warn("Promise finished before response arrived. Response code: " + response.getStatus().code() + ". Promise result: " + completionPromise.getNow()); } if (PropertyNames.ServerTraceRequests.getValueAsBoolean()) { checkpoint(ctx, "Promise completed."); } } @Override public void exceptionCaught(final ChannelHandlerContext ctx, Throwable cause) throws Exception { // Handlers are thread-safe i.e. they do not get invoked concurrently by netty, so you can safely assume that // error & success do not happen concurrently. final int retryCount = ctx.channel().attr(DedicatedClientPool.RETRY_COUNT_KEY).get().incrementAndGet(); logger.error("Client id: " + id + ". Client handler got an error. Retry count: " + retryCount, cause); if (PropertyNames.ServerTraceRequests.getValueAsBoolean()) { checkpoint(ctx, "Exception on client handler" + cause); } final RequestExecutionPromise<FullHttpResponse> completionPromise = ctx.channel().attr(pool.getProcessingCompletePromiseKey()).get(); if (null == completionPromise) { logger.error("No completion promise available, nothing can be done now. Retry: " + retryCount + ", channel active? " + ctx.channel().isActive()); pool.onUnhandledRequest(); return; } if (retryCount > MAX_RETRIES) { if (PropertyNames.ServerTraceRequests.getValueAsBoolean()) { checkpoint(ctx, "Retries exhausted."); } pool.onRetryExhausted(cause, retryCount); completionPromise.setFailure(cause); return; } Future<DedicatedHttpClient<FullHttpResponse, FullHttpRequest>> clientGetFuture = pool.getClient(ctx.executor()); clientGetFuture.addListener( new GenericFutureListener<Future<DedicatedHttpClient<FullHttpResponse, FullHttpRequest>>>() { @Override public void operationComplete(Future<DedicatedHttpClient<FullHttpResponse, FullHttpRequest>> future) throws Exception { if (future.isSuccess()) { future.get().retry(ctx, retryCount, completionPromise); } else { completionPromise.setFailure(future.cause()); } } }); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { if (PropertyNames.ServerTraceRequests.getValueAsBoolean()) { checkpoint(ctx, "Channel Inactive."); } } private void checkpoint(ChannelHandlerContext ctx, String checkpoint) { checkpoint = "ClientId: " + id + ' ' + checkpoint; final GenericFutureListener<Future<FullHttpResponse>> responseHandler = ctx.channel().attr( pool.getResponseHandlerKey()).get(); if (null != responseHandler && DedicatedHttpClient.ResponseHandlerWrapper.class.isAssignableFrom(responseHandler.getClass())) { @SuppressWarnings("rawtypes") DedicatedHttpClient.ResponseHandlerWrapper wrapper = (DedicatedHttpClient.ResponseHandlerWrapper) responseHandler; wrapper.getProcessingFinishPromise().checkpoint(checkpoint); } } }
ws-impls/ws-java-netty/src/main/java/perf/test/netty/client/ClientHandler.java
package perf.test.netty.client; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.GenericFutureListener; import io.netty.util.concurrent.Promise; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import perf.test.netty.PropertyNames; import java.util.concurrent.atomic.AtomicInteger; /** * @author Nitesh Kant ([email protected]) */ public class ClientHandler extends SimpleChannelInboundHandler<FullHttpResponse> { private final Logger logger = LoggerFactory.getLogger(ClientHandler.class); public static final int MAX_RETRIES = 3; private final long id; private final DedicatedClientPool<FullHttpResponse, FullHttpRequest> pool; public ClientHandler(DedicatedClientPool<FullHttpResponse, FullHttpRequest> pool, long id) { this.pool = pool; this.id = id; } @Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse response) throws Exception { AtomicInteger retries = ctx.channel().attr(DedicatedClientPool.RETRY_COUNT_KEY).get(); if (logger.isDebugEnabled()) { logger.debug("Response completed after {} retries", null == retries ? 0 : retries); } if (PropertyNames.ServerTraceRequests.getValueAsBoolean()) { checkpoint(ctx, "Response completed after retries: " + retries); } retries.set(0); // Response received so reset retry. Promise<FullHttpResponse> completionPromise = ctx.channel().attr(pool.getProcessingCompletePromiseKey()).get(); response.content().retain(); completionPromise.setSuccess(response); if (PropertyNames.ServerTraceRequests.getValueAsBoolean()) { checkpoint(ctx, "Promise completed."); } } @Override public void exceptionCaught(final ChannelHandlerContext ctx, Throwable cause) throws Exception { // Handlers are thread-safe i.e. they do not get invoked concurrently by netty, so you can safely assume that // error & success do not happen concurrently. final int retryCount = ctx.channel().attr(DedicatedClientPool.RETRY_COUNT_KEY).get().incrementAndGet(); logger.error("Client id: " + id + ". Client handler got an error. Retry count: " + retryCount, cause); if (PropertyNames.ServerTraceRequests.getValueAsBoolean()) { checkpoint(ctx, "Exception on client handler" + cause); } final RequestExecutionPromise<FullHttpResponse> completionPromise = ctx.channel().attr(pool.getProcessingCompletePromiseKey()).get(); if (null == completionPromise) { logger.error("No completion promise available, nothing can be done now. Retry: " + retryCount + ", channel active? " + ctx.channel().isActive()); pool.onUnhandledRequest(); return; } if (retryCount > MAX_RETRIES) { if (PropertyNames.ServerTraceRequests.getValueAsBoolean()) { checkpoint(ctx, "Retries exhausted."); } pool.onRetryExhausted(cause, retryCount); completionPromise.setFailure(cause); return; } Future<DedicatedHttpClient<FullHttpResponse, FullHttpRequest>> clientGetFuture = pool.getClient(ctx.executor()); clientGetFuture.addListener( new GenericFutureListener<Future<DedicatedHttpClient<FullHttpResponse, FullHttpRequest>>>() { @Override public void operationComplete(Future<DedicatedHttpClient<FullHttpResponse, FullHttpRequest>> future) throws Exception { if (future.isSuccess()) { future.get().retry(ctx, retryCount, completionPromise); } else { completionPromise.setFailure(future.cause()); } } }); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { if (PropertyNames.ServerTraceRequests.getValueAsBoolean()) { checkpoint(ctx, "Channel Inactive."); } } private void checkpoint(ChannelHandlerContext ctx, String checkpoint) { checkpoint = "ClientId: " + id + ' ' + checkpoint; final GenericFutureListener<Future<FullHttpResponse>> responseHandler = ctx.channel().attr( pool.getResponseHandlerKey()).get(); if (null != responseHandler && DedicatedHttpClient.ResponseHandlerWrapper.class.isAssignableFrom(responseHandler.getClass())) { @SuppressWarnings("rawtypes") DedicatedHttpClient.ResponseHandlerWrapper wrapper = (DedicatedHttpClient.ResponseHandlerWrapper) responseHandler; wrapper.getProcessingFinishPromise().checkpoint(checkpoint); } } }
Bug fix
ws-impls/ws-java-netty/src/main/java/perf/test/netty/client/ClientHandler.java
Bug fix
<ide><path>s-impls/ws-java-netty/src/main/java/perf/test/netty/client/ClientHandler.java <ide> <ide> Promise<FullHttpResponse> completionPromise = ctx.channel().attr(pool.getProcessingCompletePromiseKey()).get(); <ide> response.content().retain(); <del> completionPromise.setSuccess(response); <add> if (!completionPromise.trySuccess(response)) { <add> logger.warn("Promise finished before response arrived. Response code: " + response.getStatus().code() <add> + ". Promise result: " + completionPromise.getNow()); <add> } <ide> if (PropertyNames.ServerTraceRequests.getValueAsBoolean()) { <ide> checkpoint(ctx, "Promise completed."); <ide> }
Java
apache-2.0
6a262ebd9a2bb3a14d44790a751aa474f1c0b02f
0
claudiu-stanciu/kylo,Teradata/kylo,peter-gergely-horvath/kylo,rashidaligee/kylo,Teradata/kylo,claudiu-stanciu/kylo,Teradata/kylo,Teradata/kylo,claudiu-stanciu/kylo,rashidaligee/kylo,peter-gergely-horvath/kylo,claudiu-stanciu/kylo,peter-gergely-horvath/kylo,rashidaligee/kylo,rashidaligee/kylo,Teradata/kylo,peter-gergely-horvath/kylo,claudiu-stanciu/kylo
package com.thinkbiganalytics.feedmgr.config; /*- * #%L * thinkbig-feed-manager-controller * %% * Copyright (C) 2017 ThinkBig Analytics * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import com.thinkbiganalytics.feedmgr.nifi.NifiConnectionService; import com.thinkbiganalytics.feedmgr.nifi.NifiFlowCache; import com.thinkbiganalytics.feedmgr.nifi.PropertyExpressionResolver; import com.thinkbiganalytics.feedmgr.nifi.SpringEnvironmentProperties; import com.thinkbiganalytics.feedmgr.rest.Model; import com.thinkbiganalytics.feedmgr.service.AccessControlledEntityTransform; import com.thinkbiganalytics.feedmgr.service.EncryptionService; import com.thinkbiganalytics.feedmgr.service.MetadataService; import com.thinkbiganalytics.feedmgr.service.category.CategoryModelTransform; import com.thinkbiganalytics.feedmgr.service.category.FeedManagerCategoryService; import com.thinkbiganalytics.feedmgr.service.category.InMemoryFeedManagerCategoryService; import com.thinkbiganalytics.feedmgr.service.feed.FeedManagerFeedService; import com.thinkbiganalytics.feedmgr.service.feed.FeedModelTransform; import com.thinkbiganalytics.feedmgr.service.feed.InMemoryFeedManagerFeedService; import com.thinkbiganalytics.feedmgr.service.template.FeedManagerTemplateService; import com.thinkbiganalytics.feedmgr.service.template.InMemoryFeedManagerTemplateService; import com.thinkbiganalytics.feedmgr.service.template.RegisteredTemplateService; import com.thinkbiganalytics.feedmgr.service.template.RegisteredTemplateUtil; import com.thinkbiganalytics.feedmgr.service.template.TemplateModelTransform; import com.thinkbiganalytics.feedmgr.sla.ServiceLevelAgreementModelTransform; import com.thinkbiganalytics.feedmgr.sla.ServiceLevelAgreementService; import com.thinkbiganalytics.hive.service.HiveService; import com.thinkbiganalytics.kerberos.KerberosTicketConfiguration; import com.thinkbiganalytics.metadata.api.MetadataAccess; import com.thinkbiganalytics.metadata.api.MetadataAction; import com.thinkbiganalytics.metadata.api.MetadataCommand; import com.thinkbiganalytics.metadata.api.MetadataExecutionException; import com.thinkbiganalytics.metadata.api.MetadataRollbackAction; import com.thinkbiganalytics.metadata.api.MetadataRollbackCommand; import com.thinkbiganalytics.metadata.api.category.CategoryProvider; import com.thinkbiganalytics.metadata.api.datasource.DatasourceProvider; import com.thinkbiganalytics.metadata.api.feed.FeedProvider; import com.thinkbiganalytics.metadata.api.security.HadoopSecurityGroupProvider; import com.thinkbiganalytics.metadata.api.sla.FeedServiceLevelAgreementProvider; import com.thinkbiganalytics.metadata.api.template.FeedManagerTemplateProvider; import com.thinkbiganalytics.metadata.core.dataset.InMemoryDatasourceProvider; import com.thinkbiganalytics.metadata.core.feed.InMemoryFeedProvider; import com.thinkbiganalytics.metadata.modeshape.JcrMetadataAccess; import com.thinkbiganalytics.metadata.modeshape.MetadataJcrConfigurator; import com.thinkbiganalytics.metadata.sla.api.ServiceLevelAgreement; import com.thinkbiganalytics.metadata.sla.spi.ServiceLevelAgreementProvider; import com.thinkbiganalytics.metadata.sla.spi.ServiceLevelAgreementScheduler; import com.thinkbiganalytics.metadata.sla.spi.core.InMemorySLAProvider; import com.thinkbiganalytics.nifi.rest.client.LegacyNifiRestClient; import com.thinkbiganalytics.nifi.rest.client.NiFiRestClient; import com.thinkbiganalytics.nifi.rest.client.NifiRestClientConfig; import com.thinkbiganalytics.nifi.rest.model.NiFiPropertyDescriptorTransform; import com.thinkbiganalytics.nifi.v1.rest.client.NiFiRestClientV1; import com.thinkbiganalytics.nifi.v1.rest.model.NiFiPropertyDescriptorTransformV1; import com.thinkbiganalytics.security.AccessController; import com.thinkbiganalytics.security.rest.controller.SecurityModelTransform; import com.thinkbiganalytics.security.service.user.UserService; import org.mockito.Mockito; import org.modeshape.jcr.ModeShapeEngine; import org.modeshape.jcr.api.txn.TransactionManagerLookup; import org.springframework.cloud.config.server.encryption.EncryptionController; import org.springframework.cloud.config.server.encryption.SingleTextEncryptorLocator; import org.springframework.cloud.config.server.encryption.TextEncryptorLocator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.jdbc.core.JdbcTemplate; import java.security.Principal; import java.util.Properties; import javax.jcr.Credentials; import javax.jcr.Repository; /** */ @Configuration public class TestSpringConfiguration { @Bean public static PropertySourcesPlaceholderConfigurer properties() throws Exception { final PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer(); Properties properties = new Properties(); properties.setProperty("nifi.remove.inactive.versioned.feeds", "true"); propertySourcesPlaceholderConfigurer.setProperties(properties); return propertySourcesPlaceholderConfigurer; } @Bean public AccessController accessController() { return Mockito.mock(AccessController.class); } @Bean public FeedServiceLevelAgreementProvider feedServiceLevelAgreementProvider() { return Mockito.mock(FeedServiceLevelAgreementProvider.class); } @Bean public ServiceLevelAgreementService serviceLevelAgreementService() { return new ServiceLevelAgreementService(); } @Bean public ServiceLevelAgreementProvider serviceLevelAgreementProvider() { return new InMemorySLAProvider(); } @Bean public NifiFlowCache nifiFlowCache() { return new NifiFlowCache(); } @Bean public ModeShapeEngine modeShapeEngine() { return Mockito.mock(ModeShapeEngine.class); } @Bean public MetadataJcrConfigurator metadataJcrConfigurator() { return Mockito.mock(MetadataJcrConfigurator.class); } @Bean public MetadataService metadataService() { return Mockito.mock(MetadataService.class); } @Bean public NifiConnectionService nifiConnectionService() { return new NifiConnectionService(); } @Bean public ServiceLevelAgreementScheduler serviceLevelAgreementScheduler() { return new ServiceLevelAgreementScheduler() { @Override public void scheduleServiceLevelAgreement(ServiceLevelAgreement sla) { } @Override public void enableServiceLevelAgreement(ServiceLevelAgreement sla) { } @Override public void disableServiceLevelAgreement(ServiceLevelAgreement sla) { } @Override public boolean unscheduleServiceLevelAgreement(ServiceLevelAgreement.ID slaId) { return false; } @Override public boolean unscheduleServiceLevelAgreement(ServiceLevelAgreement sla) { return false; } }; } @Bean FeedProvider feedProvider() { return new InMemoryFeedProvider(); } @Bean(name = "metadataJcrRepository") public Repository repository() { return Mockito.mock(Repository.class); } @Bean public TransactionManagerLookup txnLookup() { return Mockito.mock(TransactionManagerLookup.class); } @Bean public JcrMetadataAccess jcrMetadataAccess() { // Transaction behavior not enforced in memory-only mode; return new JcrMetadataAccess() { @Override public <R> R commit(MetadataCommand<R> cmd, Principal... principals) { try { return cmd.execute(); } catch (Exception e) { throw new MetadataExecutionException(e); } } @Override public <R> R read(MetadataCommand<R> cmd, Principal... principals) { try { return cmd.execute(); } catch (Exception e) { throw new MetadataExecutionException(e); } } @Override public <R> R commit(Credentials creds, MetadataCommand<R> cmd) { try { return cmd.execute(); } catch (Exception e) { throw new MetadataExecutionException(e); } } @Override public <R> R commit(MetadataCommand<R> cmd, MetadataRollbackCommand rollbackCmd, Principal... principals) { return commit(cmd, principals); } @Override public void commit(MetadataAction action, MetadataRollbackAction rollbackAction, Principal... principals) { commit(action, principals); } @Override public <R> R read(Credentials creds, MetadataCommand<R> cmd) { try { return cmd.execute(); } catch (Exception e) { throw new MetadataExecutionException(e); } } }; } @Bean MetadataAccess metadataAccess() { // Transaction behavior not enforced in memory-only mode; return new MetadataAccess() { @Override public <R> R commit(MetadataCommand<R> cmd, Principal... principals) { try { return cmd.execute(); } catch (Exception e) { throw new MetadataExecutionException(e); } } @Override public <R> R read(MetadataCommand<R> cmd, Principal... principals) { try { return cmd.execute(); } catch (Exception e) { throw new MetadataExecutionException(e); } } @Override public void commit(MetadataAction action, Principal... principals) { try { action.execute(); } catch (Exception e) { throw new MetadataExecutionException(e); } } @Override public <R> R commit(MetadataCommand<R> cmd, MetadataRollbackCommand rollbackCmd, Principal... principals) { return commit(cmd, principals); } @Override public void commit(MetadataAction action, MetadataRollbackAction rollbackAction, Principal... principals) { commit(action, principals); } @Override public void read(MetadataAction cmd, Principal... principals) { try { cmd.execute(); } catch (Exception e) { throw new MetadataExecutionException(e); } } }; } @Bean public DatasourceProvider datasetProvider() { return new InMemoryDatasourceProvider(); } @Bean public FeedManagerFeedService feedManagerFeedService() { return new InMemoryFeedManagerFeedService(); } @Bean public FeedManagerCategoryService feedManagerCategoryService() { return new InMemoryFeedManagerCategoryService(); } @Bean FeedManagerTemplateService feedManagerTemplateService() { return new InMemoryFeedManagerTemplateService(); } @Bean NifiRestClientConfig nifiRestClientConfig() { return new NifiRestClientConfig(); } @Bean PropertyExpressionResolver propertyExpressionResolver() { return new PropertyExpressionResolver(); } @Bean SpringEnvironmentProperties springEnvironmentProperties() { return new SpringEnvironmentProperties(); } @Bean public LegacyNifiRestClient legacyNifiRestClient() { return new LegacyNifiRestClient(); } @Bean NiFiRestClient niFiRestClient() { return new NiFiRestClientV1(nifiRestClientConfig()); } @Bean NiFiPropertyDescriptorTransform propertyDescriptorTransform() { return new NiFiPropertyDescriptorTransformV1(); } @Bean RegisteredTemplateUtil registeredTemplateUtil() { return new RegisteredTemplateUtil(); } @Bean RegisteredTemplateService registeredTemplateService() { return new RegisteredTemplateService(); } @Bean FeedModelTransform feedModelTransform() { return new FeedModelTransform(); } @Bean CategoryModelTransform categoryModelTransform() { return new CategoryModelTransform(); } @Bean CategoryProvider feedManagerCategoryProvider() { return new Mockito().mock(CategoryProvider.class); } @Bean FeedManagerTemplateProvider feedManagerTemplateProvider() { return new Mockito().mock(FeedManagerTemplateProvider.class); } @Bean(name = "hiveJdbcTemplate") JdbcTemplate hiveJdbcTemplate() { return new Mockito().mock(JdbcTemplate.class); } @Bean(name = "kerberosHiveConfiguration") KerberosTicketConfiguration kerberosHiveConfiguration() { return new KerberosTicketConfiguration(); } @Bean HadoopSecurityGroupProvider hadoopSecurityGroupProvider() { return new Mockito().mock(HadoopSecurityGroupProvider.class); } @Bean HiveService hiveService() { return new Mockito().mock(HiveService.class); } @Bean TemplateModelTransform templateModelTransform() { return new TemplateModelTransform(); } @Bean EncryptionService encryptionService() { return new EncryptionService(); } @Bean TextEncryptorLocator textEncryptorLocator() { return new SingleTextEncryptorLocator(null); } @Bean EncryptionController encryptionController() { return new EncryptionController(textEncryptorLocator()); } @Bean ServiceLevelAgreementModelTransform serviceLevelAgreementModelTransform() { return new ServiceLevelAgreementModelTransform(Mockito.mock(Model.class)); } @Bean AccessControlledEntityTransform accessControlledEntityTransform() { return Mockito.mock(AccessControlledEntityTransform.class); } @Bean SecurityModelTransform actionsTransform() { return Mockito.mock(SecurityModelTransform.class); } @Bean UserService userService() { return Mockito.mock(UserService.class); } }
services/feed-manager-service/feed-manager-controller/src/test/java/com/thinkbiganalytics/feedmgr/config/TestSpringConfiguration.java
package com.thinkbiganalytics.feedmgr.config; /*- * #%L * thinkbig-feed-manager-controller * %% * Copyright (C) 2017 ThinkBig Analytics * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import com.thinkbiganalytics.feedmgr.nifi.NifiConnectionService; import com.thinkbiganalytics.feedmgr.nifi.NifiFlowCache; import com.thinkbiganalytics.feedmgr.nifi.PropertyExpressionResolver; import com.thinkbiganalytics.feedmgr.nifi.SpringEnvironmentProperties; import com.thinkbiganalytics.feedmgr.rest.Model; import com.thinkbiganalytics.feedmgr.service.EncryptionService; import com.thinkbiganalytics.feedmgr.service.MetadataService; import com.thinkbiganalytics.feedmgr.service.category.CategoryModelTransform; import com.thinkbiganalytics.feedmgr.service.category.FeedManagerCategoryService; import com.thinkbiganalytics.feedmgr.service.category.InMemoryFeedManagerCategoryService; import com.thinkbiganalytics.feedmgr.service.feed.FeedManagerFeedService; import com.thinkbiganalytics.feedmgr.service.feed.FeedModelTransform; import com.thinkbiganalytics.feedmgr.service.feed.InMemoryFeedManagerFeedService; import com.thinkbiganalytics.feedmgr.service.template.FeedManagerTemplateService; import com.thinkbiganalytics.feedmgr.service.template.InMemoryFeedManagerTemplateService; import com.thinkbiganalytics.feedmgr.service.template.RegisteredTemplateService; import com.thinkbiganalytics.feedmgr.service.template.RegisteredTemplateUtil; import com.thinkbiganalytics.feedmgr.service.template.TemplateModelTransform; import com.thinkbiganalytics.feedmgr.sla.ServiceLevelAgreementModelTransform; import com.thinkbiganalytics.feedmgr.sla.ServiceLevelAgreementService; import com.thinkbiganalytics.hive.service.HiveService; import com.thinkbiganalytics.kerberos.KerberosTicketConfiguration; import com.thinkbiganalytics.metadata.api.MetadataAccess; import com.thinkbiganalytics.metadata.api.MetadataAction; import com.thinkbiganalytics.metadata.api.MetadataCommand; import com.thinkbiganalytics.metadata.api.MetadataExecutionException; import com.thinkbiganalytics.metadata.api.MetadataRollbackAction; import com.thinkbiganalytics.metadata.api.MetadataRollbackCommand; import com.thinkbiganalytics.metadata.api.category.CategoryProvider; import com.thinkbiganalytics.metadata.api.datasource.DatasourceProvider; import com.thinkbiganalytics.metadata.api.feed.FeedProvider; import com.thinkbiganalytics.metadata.api.security.HadoopSecurityGroupProvider; import com.thinkbiganalytics.metadata.api.sla.FeedServiceLevelAgreementProvider; import com.thinkbiganalytics.metadata.api.template.FeedManagerTemplateProvider; import com.thinkbiganalytics.metadata.core.dataset.InMemoryDatasourceProvider; import com.thinkbiganalytics.metadata.core.feed.InMemoryFeedProvider; import com.thinkbiganalytics.metadata.modeshape.JcrMetadataAccess; import com.thinkbiganalytics.metadata.modeshape.MetadataJcrConfigurator; import com.thinkbiganalytics.metadata.sla.api.ServiceLevelAgreement; import com.thinkbiganalytics.metadata.sla.spi.ServiceLevelAgreementProvider; import com.thinkbiganalytics.metadata.sla.spi.ServiceLevelAgreementScheduler; import com.thinkbiganalytics.metadata.sla.spi.core.InMemorySLAProvider; import com.thinkbiganalytics.nifi.rest.client.LegacyNifiRestClient; import com.thinkbiganalytics.nifi.rest.client.NiFiRestClient; import com.thinkbiganalytics.nifi.rest.client.NifiRestClientConfig; import com.thinkbiganalytics.nifi.rest.model.NiFiPropertyDescriptorTransform; import com.thinkbiganalytics.nifi.v1.rest.client.NiFiRestClientV1; import com.thinkbiganalytics.nifi.v1.rest.model.NiFiPropertyDescriptorTransformV1; import com.thinkbiganalytics.security.AccessController; import org.mockito.Mockito; import org.modeshape.jcr.ModeShapeEngine; import org.modeshape.jcr.api.txn.TransactionManagerLookup; import org.springframework.cloud.config.server.encryption.EncryptionController; import org.springframework.cloud.config.server.encryption.SingleTextEncryptorLocator; import org.springframework.cloud.config.server.encryption.TextEncryptorLocator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.jdbc.core.JdbcTemplate; import java.security.Principal; import java.util.Properties; import javax.jcr.Credentials; import javax.jcr.Repository; /** */ @Configuration public class TestSpringConfiguration { @Bean public static PropertySourcesPlaceholderConfigurer properties() throws Exception { final PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer(); Properties properties = new Properties(); properties.setProperty("nifi.remove.inactive.versioned.feeds", "true"); propertySourcesPlaceholderConfigurer.setProperties(properties); return propertySourcesPlaceholderConfigurer; } @Bean public AccessController accessController() { return Mockito.mock(AccessController.class); } @Bean public FeedServiceLevelAgreementProvider feedServiceLevelAgreementProvider() { return Mockito.mock(FeedServiceLevelAgreementProvider.class); } @Bean public ServiceLevelAgreementService serviceLevelAgreementService() { return new ServiceLevelAgreementService(); } @Bean public ServiceLevelAgreementProvider serviceLevelAgreementProvider() { return new InMemorySLAProvider(); } @Bean public NifiFlowCache nifiFlowCache() { return new NifiFlowCache(); } @Bean public ModeShapeEngine modeShapeEngine() { return Mockito.mock(ModeShapeEngine.class); } @Bean public MetadataJcrConfigurator metadataJcrConfigurator() { return Mockito.mock(MetadataJcrConfigurator.class); } @Bean public MetadataService metadataService() { return Mockito.mock(MetadataService.class); } @Bean public NifiConnectionService nifiConnectionService() { return new NifiConnectionService(); } @Bean public ServiceLevelAgreementScheduler serviceLevelAgreementScheduler() { return new ServiceLevelAgreementScheduler() { @Override public void scheduleServiceLevelAgreement(ServiceLevelAgreement sla) { } @Override public void enableServiceLevelAgreement(ServiceLevelAgreement sla) { } @Override public void disableServiceLevelAgreement(ServiceLevelAgreement sla) { } @Override public boolean unscheduleServiceLevelAgreement(ServiceLevelAgreement.ID slaId) { return false; } @Override public boolean unscheduleServiceLevelAgreement(ServiceLevelAgreement sla) { return false; } }; } @Bean FeedProvider feedProvider() { return new InMemoryFeedProvider(); } @Bean(name = "metadataJcrRepository") public Repository repository() { return Mockito.mock(Repository.class); } @Bean public TransactionManagerLookup txnLookup() { return Mockito.mock(TransactionManagerLookup.class); } @Bean public JcrMetadataAccess jcrMetadataAccess() { // Transaction behavior not enforced in memory-only mode; return new JcrMetadataAccess() { @Override public <R> R commit(MetadataCommand<R> cmd, Principal... principals) { try { return cmd.execute(); } catch (Exception e) { throw new MetadataExecutionException(e); } } @Override public <R> R read(MetadataCommand<R> cmd, Principal... principals) { try { return cmd.execute(); } catch (Exception e) { throw new MetadataExecutionException(e); } } @Override public <R> R commit(Credentials creds, MetadataCommand<R> cmd) { try { return cmd.execute(); } catch (Exception e) { throw new MetadataExecutionException(e); } } @Override public <R> R commit(MetadataCommand<R> cmd, MetadataRollbackCommand rollbackCmd, Principal... principals) { return commit(cmd, principals); } @Override public void commit(MetadataAction action, MetadataRollbackAction rollbackAction, Principal... principals) { commit(action, principals); } @Override public <R> R read(Credentials creds, MetadataCommand<R> cmd) { try { return cmd.execute(); } catch (Exception e) { throw new MetadataExecutionException(e); } } }; } @Bean MetadataAccess metadataAccess() { // Transaction behavior not enforced in memory-only mode; return new MetadataAccess() { @Override public <R> R commit(MetadataCommand<R> cmd, Principal... principals) { try { return cmd.execute(); } catch (Exception e) { throw new MetadataExecutionException(e); } } @Override public <R> R read(MetadataCommand<R> cmd, Principal... principals) { try { return cmd.execute(); } catch (Exception e) { throw new MetadataExecutionException(e); } } @Override public void commit(MetadataAction action, Principal... principals) { try { action.execute(); } catch (Exception e) { throw new MetadataExecutionException(e); } } @Override public <R> R commit(MetadataCommand<R> cmd, MetadataRollbackCommand rollbackCmd, Principal... principals) { return commit(cmd, principals); } @Override public void commit(MetadataAction action, MetadataRollbackAction rollbackAction, Principal... principals) { commit(action, principals); } @Override public void read(MetadataAction cmd, Principal... principals) { try { cmd.execute(); } catch (Exception e) { throw new MetadataExecutionException(e); } } }; } @Bean public DatasourceProvider datasetProvider() { return new InMemoryDatasourceProvider(); } @Bean public FeedManagerFeedService feedManagerFeedService() { return new InMemoryFeedManagerFeedService(); } @Bean public FeedManagerCategoryService feedManagerCategoryService() { return new InMemoryFeedManagerCategoryService(); } @Bean FeedManagerTemplateService feedManagerTemplateService() { return new InMemoryFeedManagerTemplateService(); } @Bean NifiRestClientConfig nifiRestClientConfig() { return new NifiRestClientConfig(); } @Bean PropertyExpressionResolver propertyExpressionResolver() { return new PropertyExpressionResolver(); } @Bean SpringEnvironmentProperties springEnvironmentProperties() { return new SpringEnvironmentProperties(); } @Bean public LegacyNifiRestClient legacyNifiRestClient() { return new LegacyNifiRestClient(); } @Bean NiFiRestClient niFiRestClient() { return new NiFiRestClientV1(nifiRestClientConfig()); } @Bean NiFiPropertyDescriptorTransform propertyDescriptorTransform() { return new NiFiPropertyDescriptorTransformV1(); } @Bean RegisteredTemplateUtil registeredTemplateUtil() { return new RegisteredTemplateUtil(); } @Bean RegisteredTemplateService registeredTemplateService() { return new RegisteredTemplateService(); } @Bean FeedModelTransform feedModelTransform() { return new FeedModelTransform(); } @Bean CategoryModelTransform categoryModelTransform() { return new CategoryModelTransform(); } @Bean CategoryProvider feedManagerCategoryProvider() { return new Mockito().mock(CategoryProvider.class); } @Bean FeedManagerTemplateProvider feedManagerTemplateProvider() { return new Mockito().mock(FeedManagerTemplateProvider.class); } @Bean(name = "hiveJdbcTemplate") JdbcTemplate hiveJdbcTemplate() { return new Mockito().mock(JdbcTemplate.class); } @Bean(name = "kerberosHiveConfiguration") KerberosTicketConfiguration kerberosHiveConfiguration() { return new KerberosTicketConfiguration(); } @Bean HadoopSecurityGroupProvider hadoopSecurityGroupProvider() { return new Mockito().mock(HadoopSecurityGroupProvider.class); } @Bean HiveService hiveService() { return new Mockito().mock(HiveService.class); } @Bean TemplateModelTransform templateModelTransform() { return new TemplateModelTransform(); } @Bean EncryptionService encryptionService() { return new EncryptionService(); } @Bean TextEncryptorLocator textEncryptorLocator() { return new SingleTextEncryptorLocator(null); } @Bean EncryptionController encryptionController() { return new EncryptionController(textEncryptorLocator()); } @Bean ServiceLevelAgreementModelTransform serviceLevelAgreementModelTransform() { return new ServiceLevelAgreementModelTransform(Mockito.mock(Model.class)); } }
Fixed autowiring for SLA tests.
services/feed-manager-service/feed-manager-controller/src/test/java/com/thinkbiganalytics/feedmgr/config/TestSpringConfiguration.java
Fixed autowiring for SLA tests.
<ide><path>ervices/feed-manager-service/feed-manager-controller/src/test/java/com/thinkbiganalytics/feedmgr/config/TestSpringConfiguration.java <ide> import com.thinkbiganalytics.feedmgr.nifi.PropertyExpressionResolver; <ide> import com.thinkbiganalytics.feedmgr.nifi.SpringEnvironmentProperties; <ide> import com.thinkbiganalytics.feedmgr.rest.Model; <add>import com.thinkbiganalytics.feedmgr.service.AccessControlledEntityTransform; <ide> import com.thinkbiganalytics.feedmgr.service.EncryptionService; <ide> import com.thinkbiganalytics.feedmgr.service.MetadataService; <ide> import com.thinkbiganalytics.feedmgr.service.category.CategoryModelTransform; <ide> import com.thinkbiganalytics.nifi.v1.rest.client.NiFiRestClientV1; <ide> import com.thinkbiganalytics.nifi.v1.rest.model.NiFiPropertyDescriptorTransformV1; <ide> import com.thinkbiganalytics.security.AccessController; <add>import com.thinkbiganalytics.security.rest.controller.SecurityModelTransform; <add>import com.thinkbiganalytics.security.service.user.UserService; <ide> <ide> import org.mockito.Mockito; <ide> import org.modeshape.jcr.ModeShapeEngine; <ide> ServiceLevelAgreementModelTransform serviceLevelAgreementModelTransform() { <ide> return new ServiceLevelAgreementModelTransform(Mockito.mock(Model.class)); <ide> } <add> <add> @Bean <add> AccessControlledEntityTransform accessControlledEntityTransform() { <add> return Mockito.mock(AccessControlledEntityTransform.class); <add> } <add> <add> @Bean <add> SecurityModelTransform actionsTransform() { <add> return Mockito.mock(SecurityModelTransform.class); <add> } <add> <add> @Bean <add> UserService userService() { <add> return Mockito.mock(UserService.class); <add> } <ide> }
Java
lgpl-2.1
bab8f32acc5e50f13986f38a5d071fd66eaf72af
0
victos/opencms-core,sbonoc/opencms-core,MenZil/opencms-core,mediaworx/opencms-core,alkacon/opencms-core,it-tavis/opencms-core,mediaworx/opencms-core,sbonoc/opencms-core,MenZil/opencms-core,gallardo/opencms-core,victos/opencms-core,victos/opencms-core,mediaworx/opencms-core,ggiudetti/opencms-core,sbonoc/opencms-core,alkacon/opencms-core,alkacon/opencms-core,alkacon/opencms-core,mediaworx/opencms-core,MenZil/opencms-core,it-tavis/opencms-core,gallardo/opencms-core,sbonoc/opencms-core,gallardo/opencms-core,ggiudetti/opencms-core,victos/opencms-core,ggiudetti/opencms-core,it-tavis/opencms-core,MenZil/opencms-core,it-tavis/opencms-core,ggiudetti/opencms-core,gallardo/opencms-core
/* * File : $Source$ * Date : $Date$ * Version: $Revision$ * * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (C) 2002 - 2009 Alkacon Software (http://www.alkacon.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * For further information about Alkacon Software, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.opencms.search.solr; import org.opencms.file.CmsObject; import org.opencms.file.CmsResource; import org.opencms.main.CmsLog; import org.opencms.main.OpenCms; import org.opencms.relations.CmsCategory; import org.opencms.search.I_CmsSearchDocument; import org.opencms.search.documents.CmsDocumentDependency; import org.opencms.search.fields.CmsSearchField; import org.opencms.util.CmsStringUtil; import org.opencms.util.CmsUUID; import java.nio.ByteBuffer; import java.text.ParseException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Locale; import org.apache.commons.logging.Log; import org.apache.solr.client.solrj.util.ClientUtils; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrException; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.schema.DateField; import org.apache.solr.schema.FieldType; import org.apache.solr.schema.IndexSchema; import org.apache.solr.schema.SchemaField; /** * A search document implementation for Solr indexes.<p> * * @since 8.5.0 */ public class CmsSolrDocument implements I_CmsSearchDocument { /** The log object for this class. */ private static final Log LOG = CmsLog.getLog(CmsSolrDocument.class); /** The Solr document. */ private SolrInputDocument m_doc; /** Holds the score for this document. */ private float m_score; /** * Public constructor to create a encapsulate a Solr document.<p> * * @param doc the Solr document */ public CmsSolrDocument(SolrDocument doc) { m_doc = ClientUtils.toSolrInputDocument(doc); } /** * Public constructor to create a encapsulate a Solr document.<p> * * @param doc the Solr document */ public CmsSolrDocument(SolrInputDocument doc) { m_doc = doc; } /** * @see org.opencms.search.I_CmsSearchDocument#addCategoryField(java.util.List) */ public void addCategoryField(List<CmsCategory> categories) { if ((categories != null) && (categories.size() > 0)) { for (CmsCategory category : categories) { m_doc.addField(CmsSearchField.FIELD_CATEGORY, category.getPath()); } } } /** * @see org.opencms.search.I_CmsSearchDocument#addContentField(byte[]) */ public void addContentField(byte[] data) { m_doc.setField(CmsSearchField.FIELD_CONTENT_BLOB, ByteBuffer.wrap(data)); } /** * @see org.opencms.search.I_CmsSearchDocument#addContentLocales(java.util.List) */ public void addContentLocales(List<Locale> locales) { if ((locales != null) && !locales.isEmpty()) { for (Locale locale : locales) { m_doc.addField(CmsSearchField.FIELD_CONTENT_LOCALES, locale.toString()); } } } /** * @see org.opencms.search.I_CmsSearchDocument#addDateField(java.lang.String, long, boolean) */ public void addDateField(String name, long time, boolean analyzed) { String dateValue = DateField.formatExternal(new Date(time)); m_doc.addField(name, dateValue); if (analyzed) { m_doc.addField(name + CmsSearchField.FIELD_DATE_LOOKUP_SUFFIX, dateValue); } } /** * Adds the given document dependency to this document.<p> * * @param cms the current CmsObject * @param resDeps the dependency */ public void addDocumentDependency(CmsObject cms, CmsDocumentDependency resDeps) { if (resDeps != null) { m_doc.addField(CmsSearchField.FIELD_DEPENDENCY_TYPE, resDeps.getType()); if ((resDeps.getMainDocument() != null) && (resDeps.getType() != null)) { m_doc.addField( CmsSearchField.FIELD_PREFIX_DEPENDENCY + resDeps.getType().toString(), resDeps.getMainDocument().toDependencyString(cms)); } for (CmsDocumentDependency dep : resDeps.getVariants()) { m_doc.addField( CmsSearchField.FIELD_PREFIX_DEPENDENCY + dep.getType().toString(), dep.toDependencyString(cms)); } for (CmsDocumentDependency dep : resDeps.getAttachments()) { m_doc.addField( CmsSearchField.FIELD_PREFIX_DEPENDENCY + dep.getType().toString(), dep.toDependencyString(cms)); } } } /** * @see org.opencms.search.I_CmsSearchDocument#addFileSizeField(int) */ public void addFileSizeField(int length) { if (OpenCms.getSearchManager().getSolrServerConfiguration().getSolrSchema().hasExplicitField( CmsSearchField.FIELD_SIZE)) { m_doc.addField(CmsSearchField.FIELD_SIZE, new Integer(length)); } } /** * Adds a multi-valued field.<p> * * @param fieldName the field name to put the values in * @param values the values to put in the field */ public void addMultiValuedField(String fieldName, List<String> values) { if ((values != null) && (values.size() > 0)) { for (String value : values) { m_doc.addField(fieldName, value); } } } /** * @see org.opencms.search.I_CmsSearchDocument#addPathField(java.lang.String) */ public void addPathField(String rootPath) { String folderName = CmsResource.getFolderPath(rootPath); for (int i = 0; i < folderName.length(); i++) { char c = folderName.charAt(i); if (c == '/') { m_doc.addField(CmsSearchField.FIELD_PARENT_FOLDERS, folderName.substring(0, i + 1)); } } } /** * @see org.opencms.search.I_CmsSearchDocument#addResourceLocales(java.util.List) */ public void addResourceLocales(List<Locale> locales) { if ((locales != null) && !locales.isEmpty()) { for (Locale locale : locales) { m_doc.addField(CmsSearchField.FIELD_RESOURCE_LOCALES, locale.toString()); } } } /** * @see org.opencms.search.I_CmsSearchDocument#addRootPathField(java.lang.String) */ public void addRootPathField(String rootPath) { m_doc.addField(CmsSearchField.FIELD_PATH, rootPath); } /** * @see org.opencms.search.I_CmsSearchDocument#addSearchField(org.opencms.search.fields.CmsSearchField, java.lang.String) */ public void addSearchField(CmsSearchField sfield, String value) { CmsSolrField field = (CmsSolrField)sfield; List<String> fieldsToAdd = new ArrayList<String>(Collections.singletonList(field.getName())); if ((field.getCopyFields() != null) && !field.getCopyFields().isEmpty()) { fieldsToAdd.addAll(field.getCopyFields()); } IndexSchema schema = OpenCms.getSearchManager().getSolrServerConfiguration().getSolrSchema(); for (String fieldName : fieldsToAdd) { try { List<String> splitedValues = new ArrayList<String>(); boolean multi = false; try { SchemaField f = schema.getField(fieldName); if ((f != null) && (!field.getName().startsWith(CmsSearchField.FIELD_CONTENT))) { multi = f.multiValued(); } } catch (SolrException e) { LOG.warn(Messages.get().getBundle().key(Messages.LOG_SOLR_FIELD_NOT_FOUND_1, field.toString())); } FieldType type = schema.getFieldType(fieldName); if (multi) { splitedValues = CmsStringUtil.splitAsList(value.toString(), "\n"); } else { splitedValues.add(value); } for (String val : splitedValues) { if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(val)) { try { if (type instanceof DateField) { val = DateField.formatExternal(new Date(new Long(val).longValue())); } } catch (SolrException e) { LOG.debug(e.getMessage(), e); throw new RuntimeException(e); } if (fieldName.endsWith(CmsSearchField.FIELD_EXCERPT)) { // TODO: make the length and the area configurable val = CmsStringUtil.trimToSize(val, 1000, 50, ""); } if (schema.hasExplicitField(fieldName)) { m_doc.addField(fieldName, val); } else { m_doc.addField(fieldName, val, field.getBoost()); } } } } catch (SolrException e) { LOG.error(e.getMessage(), e); } catch (RuntimeException e) { // noop } } } /** * @see org.opencms.search.I_CmsSearchDocument#addSuffixField(java.lang.String) */ public void addSuffixField(String suffix) { m_doc.addField(CmsSearchField.FIELD_SUFFIX, suffix); } /** * @see org.opencms.search.I_CmsSearchDocument#addTypeField(java.lang.String) */ public void addTypeField(String type) { m_doc.addField(CmsSearchField.FIELD_TYPE, type); } /** * @see org.opencms.search.I_CmsSearchDocument#getContentBlob() */ public byte[] getContentBlob() { Object o = m_doc.getFieldValue(CmsSearchField.FIELD_CONTENT_BLOB); if (o != null) { if (o instanceof byte[]) { return (byte[])o; } return o.toString().getBytes(); } return null; } /** * @see org.opencms.search.I_CmsSearchDocument#getDocument() */ public Object getDocument() { return m_doc; } /** * @see org.opencms.search.I_CmsSearchDocument#getFieldNames() */ public List<String> getFieldNames() { return new ArrayList<String>(m_doc.getFieldNames()); } /** * @see org.opencms.search.I_CmsSearchDocument#getFieldValueAsDate(java.lang.String) */ public Date getFieldValueAsDate(String fieldName) { Object o = m_doc.getFieldValue(fieldName); if (o instanceof Date) { return (Date)o; } if (o != null) { try { return DateField.parseDate(o.toString()); } catch (ParseException e) { // ignore: not a valid date format LOG.debug(e); } } return null; } /** * @see org.opencms.search.I_CmsSearchDocument#getFieldValueAsString(java.lang.String) */ public String getFieldValueAsString(String fieldName) { List<String> values = getMultivaluedFieldAsStringList(fieldName); if ((values != null) && !values.isEmpty()) { return CmsStringUtil.listAsString(values, "\n"); } else { Object o = m_doc.getFieldValue(fieldName); if (o != null) { return o.toString(); } } return null; } /** * @see org.opencms.search.I_CmsSearchDocument#getMultivaluedFieldAsStringList(java.lang.String) */ public List<String> getMultivaluedFieldAsStringList(String fieldName) { List<String> result = new ArrayList<String>(); Collection<Object> coll = m_doc.getFieldValues(fieldName); if (coll != null) { for (Object o : coll) { if (o != null) { result.add(o.toString()); } } return result; } return null; } /** * @see org.opencms.search.I_CmsSearchDocument#getPath() */ public String getPath() { return getFieldValueAsString(CmsSearchField.FIELD_PATH); } /** * @see org.opencms.search.I_CmsSearchDocument#getScore() */ public float getScore() { Float score = (Float)getSolrDocument().getFirstValue(CmsSearchField.FIELD_SCORE); if (score != null) { m_score = score.floatValue(); return m_score; } return 0F; } /** * Returns the Solr document.<p> * * @return the Solr document */ public SolrDocument getSolrDocument() { return ClientUtils.toSolrDocument(m_doc); } /** * @see org.opencms.search.I_CmsSearchDocument#getType() */ public String getType() { return getFieldValueAsString(CmsSearchField.FIELD_TYPE); } /** * @see org.opencms.search.I_CmsSearchDocument#setBoost(float) */ public void setBoost(float boost) { m_doc.setDocumentBoost(boost); } /** * Sets the id of this document.<p> * * @param structureId the structure id to use */ public void setId(CmsUUID structureId) { m_doc.addField(CmsSearchField.FIELD_ID, structureId); } /** * @see org.opencms.search.I_CmsSearchDocument#setScore(float) */ public void setScore(float score) { m_score = score; } /** * @see java.lang.Object#toString() */ @Override public String toString() { return getFieldValueAsString(CmsSearchField.FIELD_PATH); } }
src/org/opencms/search/solr/CmsSolrDocument.java
/* * File : $Source$ * Date : $Date$ * Version: $Revision$ * * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (C) 2002 - 2009 Alkacon Software (http://www.alkacon.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * For further information about Alkacon Software, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.opencms.search.solr; import org.opencms.file.CmsObject; import org.opencms.file.CmsResource; import org.opencms.main.CmsLog; import org.opencms.main.OpenCms; import org.opencms.relations.CmsCategory; import org.opencms.search.I_CmsSearchDocument; import org.opencms.search.documents.CmsDocumentDependency; import org.opencms.search.fields.CmsSearchField; import org.opencms.util.CmsStringUtil; import org.opencms.util.CmsUUID; import java.nio.ByteBuffer; import java.text.ParseException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Locale; import org.apache.commons.logging.Log; import org.apache.solr.client.solrj.util.ClientUtils; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrException; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.schema.DateField; import org.apache.solr.schema.FieldType; import org.apache.solr.schema.IndexSchema; import org.apache.solr.schema.SchemaField; /** * A search document implementation for Solr indexes.<p> * * @since 8.5.0 */ public class CmsSolrDocument implements I_CmsSearchDocument { /** The log object for this class. */ private static final Log LOG = CmsLog.getLog(CmsSolrDocument.class); /** The Solr document. */ private SolrInputDocument m_doc; /** Holds the score for this document. */ private float m_score; /** * Public constructor to create a encapsulate a Solr document.<p> * * @param doc the Solr document */ public CmsSolrDocument(SolrDocument doc) { m_doc = ClientUtils.toSolrInputDocument(doc); } /** * Public constructor to create a encapsulate a Solr document.<p> * * @param doc the Solr document */ public CmsSolrDocument(SolrInputDocument doc) { m_doc = doc; } /** * @see org.opencms.search.I_CmsSearchDocument#addCategoryField(java.util.List) */ public void addCategoryField(List<CmsCategory> categories) { if ((categories != null) && (categories.size() > 0)) { for (CmsCategory category : categories) { m_doc.addField(CmsSearchField.FIELD_CATEGORY, category.getPath()); } } } /** * @see org.opencms.search.I_CmsSearchDocument#addContentField(byte[]) */ public void addContentField(byte[] data) { m_doc.setField(CmsSearchField.FIELD_CONTENT_BLOB, ByteBuffer.wrap(data)); } /** * @see org.opencms.search.I_CmsSearchDocument#addContentLocales(java.util.List) */ public void addContentLocales(List<Locale> locales) { if ((locales != null) && !locales.isEmpty()) { for (Locale locale : locales) { m_doc.addField(CmsSearchField.FIELD_CONTENT_LOCALES, locale.toString()); } } } /** * @see org.opencms.search.I_CmsSearchDocument#addDateField(java.lang.String, long, boolean) */ public void addDateField(String name, long time, boolean analyzed) { String dateValue = DateField.formatExternal(new Date(time)); m_doc.addField(name, dateValue); if (analyzed) { m_doc.addField(name + CmsSearchField.FIELD_DATE_LOOKUP_SUFFIX, dateValue); } } /** * Adds the given document dependency to this document.<p> * * @param cms the current CmsObject * @param resDeps the dependency */ public void addDocumentDependency(CmsObject cms, CmsDocumentDependency resDeps) { if (resDeps != null) { m_doc.addField(CmsSearchField.FIELD_DEPENDENCY_TYPE, resDeps.getType()); if ((resDeps.getMainDocument() != null) && (resDeps.getType() != null)) { m_doc.addField( CmsSearchField.FIELD_PREFIX_DEPENDENCY + resDeps.getType().toString(), resDeps.getMainDocument().toDependencyString(cms)); } for (CmsDocumentDependency dep : resDeps.getVariants()) { m_doc.addField( CmsSearchField.FIELD_PREFIX_DEPENDENCY + dep.getType().toString(), dep.toDependencyString(cms)); } for (CmsDocumentDependency dep : resDeps.getAttachments()) { m_doc.addField( CmsSearchField.FIELD_PREFIX_DEPENDENCY + dep.getType().toString(), dep.toDependencyString(cms)); } } } /** * @see org.opencms.search.I_CmsSearchDocument#addFileSizeField(int) */ public void addFileSizeField(int length) { m_doc.addField(CmsSearchField.FIELD_SIZE, new Integer(length)); } /** * Adds a multi-valued field.<p> * * @param fieldName the field name to put the values in * @param values the values to put in the field */ public void addMultiValuedField(String fieldName, List<String> values) { if ((values != null) && (values.size() > 0)) { for (String value : values) { m_doc.addField(fieldName, value); } } } /** * @see org.opencms.search.I_CmsSearchDocument#addPathField(java.lang.String) */ public void addPathField(String rootPath) { String folderName = CmsResource.getFolderPath(rootPath); for (int i = 0; i < folderName.length(); i++) { char c = folderName.charAt(i); if (c == '/') { m_doc.addField(CmsSearchField.FIELD_PARENT_FOLDERS, folderName.substring(0, i + 1)); } } } /** * @see org.opencms.search.I_CmsSearchDocument#addResourceLocales(java.util.List) */ public void addResourceLocales(List<Locale> locales) { if ((locales != null) && !locales.isEmpty()) { for (Locale locale : locales) { m_doc.addField(CmsSearchField.FIELD_RESOURCE_LOCALES, locale.toString()); } } } /** * @see org.opencms.search.I_CmsSearchDocument#addRootPathField(java.lang.String) */ public void addRootPathField(String rootPath) { m_doc.addField(CmsSearchField.FIELD_PATH, rootPath); } /** * @see org.opencms.search.I_CmsSearchDocument#addSearchField(org.opencms.search.fields.CmsSearchField, java.lang.String) */ public void addSearchField(CmsSearchField sfield, String value) { CmsSolrField field = (CmsSolrField)sfield; List<String> fieldsToAdd = new ArrayList<String>(Collections.singletonList(field.getName())); if ((field.getCopyFields() != null) && !field.getCopyFields().isEmpty()) { fieldsToAdd.addAll(field.getCopyFields()); } IndexSchema schema = OpenCms.getSearchManager().getSolrServerConfiguration().getSolrSchema(); for (String fieldName : fieldsToAdd) { try { List<String> splitedValues = new ArrayList<String>(); boolean multi = false; try { SchemaField f = schema.getField(fieldName); if ((f != null) && (!field.getName().startsWith(CmsSearchField.FIELD_CONTENT))) { multi = f.multiValued(); } } catch (SolrException e) { LOG.warn(Messages.get().getBundle().key(Messages.LOG_SOLR_FIELD_NOT_FOUND_1, field.toString())); } FieldType type = schema.getFieldType(fieldName); if (multi) { splitedValues = CmsStringUtil.splitAsList(value.toString(), "\n"); } else { splitedValues.add(value); } for (String val : splitedValues) { if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(val)) { try { if (type instanceof DateField) { val = DateField.formatExternal(new Date(new Long(val).longValue())); } } catch (SolrException e) { LOG.debug(e.getMessage(), e); throw new RuntimeException(e); } if (fieldName.endsWith(CmsSearchField.FIELD_EXCERPT)) { // TODO: make the length and the area configurable val = CmsStringUtil.trimToSize(val, 1000, 50, ""); } if (schema.hasExplicitField(fieldName)) { m_doc.addField(fieldName, val); } else { m_doc.addField(fieldName, val, field.getBoost()); } } } } catch (SolrException e) { LOG.error(e.getMessage(), e); } catch (RuntimeException e) { // noop } } } /** * @see org.opencms.search.I_CmsSearchDocument#addSuffixField(java.lang.String) */ public void addSuffixField(String suffix) { m_doc.addField(CmsSearchField.FIELD_SUFFIX, suffix); } /** * @see org.opencms.search.I_CmsSearchDocument#addTypeField(java.lang.String) */ public void addTypeField(String type) { m_doc.addField(CmsSearchField.FIELD_TYPE, type); } /** * @see org.opencms.search.I_CmsSearchDocument#getContentBlob() */ public byte[] getContentBlob() { Object o = m_doc.getFieldValue(CmsSearchField.FIELD_CONTENT_BLOB); if (o != null) { if (o instanceof byte[]) { return (byte[])o; } return o.toString().getBytes(); } return null; } /** * @see org.opencms.search.I_CmsSearchDocument#getDocument() */ public Object getDocument() { return m_doc; } /** * @see org.opencms.search.I_CmsSearchDocument#getFieldNames() */ public List<String> getFieldNames() { return new ArrayList<String>(m_doc.getFieldNames()); } /** * @see org.opencms.search.I_CmsSearchDocument#getFieldValueAsDate(java.lang.String) */ public Date getFieldValueAsDate(String fieldName) { Object o = m_doc.getFieldValue(fieldName); if (o instanceof Date) { return (Date)o; } if (o != null) { try { return DateField.parseDate(o.toString()); } catch (ParseException e) { // ignore: not a valid date format LOG.debug(e); } } return null; } /** * @see org.opencms.search.I_CmsSearchDocument#getFieldValueAsString(java.lang.String) */ public String getFieldValueAsString(String fieldName) { List<String> values = getMultivaluedFieldAsStringList(fieldName); if ((values != null) && !values.isEmpty()) { return CmsStringUtil.listAsString(values, "\n"); } else { Object o = m_doc.getFieldValue(fieldName); if (o != null) { return o.toString(); } } return null; } /** * @see org.opencms.search.I_CmsSearchDocument#getMultivaluedFieldAsStringList(java.lang.String) */ public List<String> getMultivaluedFieldAsStringList(String fieldName) { List<String> result = new ArrayList<String>(); Collection<Object> coll = m_doc.getFieldValues(fieldName); if (coll != null) { for (Object o : coll) { if (o != null) { result.add(o.toString()); } } return result; } return null; } /** * @see org.opencms.search.I_CmsSearchDocument#getPath() */ public String getPath() { return getFieldValueAsString(CmsSearchField.FIELD_PATH); } /** * @see org.opencms.search.I_CmsSearchDocument#getScore() */ public float getScore() { Float score = (Float)getSolrDocument().getFirstValue(CmsSearchField.FIELD_SCORE); if (score != null) { m_score = score.floatValue(); return m_score; } return 0F; } /** * Returns the Solr document.<p> * * @return the Solr document */ public SolrDocument getSolrDocument() { return ClientUtils.toSolrDocument(m_doc); } /** * @see org.opencms.search.I_CmsSearchDocument#getType() */ public String getType() { return getFieldValueAsString(CmsSearchField.FIELD_TYPE); } /** * @see org.opencms.search.I_CmsSearchDocument#setBoost(float) */ public void setBoost(float boost) { m_doc.setDocumentBoost(boost); } /** * Sets the id of this document.<p> * * @param structureId the structure id to use */ public void setId(CmsUUID structureId) { m_doc.addField(CmsSearchField.FIELD_ID, structureId); } /** * @see org.opencms.search.I_CmsSearchDocument#setScore(float) */ public void setScore(float score) { m_score = score; } /** * @see java.lang.Object#toString() */ @Override public String toString() { return getFieldValueAsString(CmsSearchField.FIELD_PATH); } }
Check if the field "size" exists before adding it.
src/org/opencms/search/solr/CmsSolrDocument.java
Check if the field "size" exists before adding it.
<ide><path>rc/org/opencms/search/solr/CmsSolrDocument.java <ide> */ <ide> public void addFileSizeField(int length) { <ide> <del> m_doc.addField(CmsSearchField.FIELD_SIZE, new Integer(length)); <add> if (OpenCms.getSearchManager().getSolrServerConfiguration().getSolrSchema().hasExplicitField( <add> CmsSearchField.FIELD_SIZE)) { <add> m_doc.addField(CmsSearchField.FIELD_SIZE, new Integer(length)); <add> } <ide> } <ide> <ide> /**
Java
mit
5c281a923628ba4cbfc299c4e785b5fc487a263f
0
Nithanaroy/patient-healthcare-portal,Nithanaroy/patient-healthcare-portal,Nithanaroy/patient-healthcare-portal
package edu.asu.se.helpers; import java.io.IOException; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import edu.asu.se.model.LoginDAO; import edu.asu.se.utils.ICommand; public class Authentication implements ICommand{ public void execute (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { LoginDAO ldao = new LoginDAO(); String userName=request.getParameter("uname"); String password = request.getParameter("pwd"); String userType=ldao.valdateUser(userName,password); HttpSession session=request.getSession(); //System.out.println(userType); if(userType==null) { session.setAttribute("flag", 1); request.getRequestDispatcher("/views/login.jsp").forward(request,response); } try{ if(userType.equals("staff")) { //System.out.println("instaff"); session.setAttribute("userType", userType); session.setAttribute("userName", userName); request.getRequestDispatcher("/views/doctor.jsp").forward(request,response); } if(userType.equals("patient")) { session.setAttribute("userType", userType); session.setAttribute("userName", userName); request.getRequestDispatcher("/views/patient.jsp").forward(request,response); } } catch(NullPointerException e) { System.err.println("Wrong credentials"); } } }
src/edu/asu/se/helpers/Authentication.java
package edu.asu.se.helpers; import java.io.IOException; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import edu.asu.se.model.LoginDAO; import edu.asu.se.utils.ICommand; public class Authentication implements ICommand{ public void execute (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { LoginDAO ldao = new LoginDAO(); String userName=request.getParameter("uname"); String password = request.getParameter("pwd"); String userType=ldao.valdateUser(userName,password); HttpSession session=request.getSession(); session.setAttribute("userType", userType); //System.out.println(userType); if(userType==null) { session.setAttribute("flag", 1); request.getRequestDispatcher("/views/login.jsp").forward(request,response); } try{ if(userType.equals("staff")) { //System.out.println("instaff"); request.getRequestDispatcher("/views/doctor.jsp").forward(request,response); } if(userType.equals("patient")) { request.getRequestDispatcher("/views/patient.jsp").forward(request,response); } } catch(NullPointerException e) { System.err.println("Wrong credentials"); } } }
added username to session object
src/edu/asu/se/helpers/Authentication.java
added username to session object
<ide><path>rc/edu/asu/se/helpers/Authentication.java <ide> String password = request.getParameter("pwd"); <ide> <ide> String userType=ldao.valdateUser(userName,password); <del> <ide> HttpSession session=request.getSession(); <del> session.setAttribute("userType", userType); <ide> //System.out.println(userType); <ide> if(userType==null) <ide> { <ide> if(userType.equals("staff")) <ide> { <ide> //System.out.println("instaff"); <add> <add> session.setAttribute("userType", userType); <add> session.setAttribute("userName", userName); <ide> request.getRequestDispatcher("/views/doctor.jsp").forward(request,response); <ide> } <ide> <ide> if(userType.equals("patient")) <ide> { <add> <add> session.setAttribute("userType", userType); <add> session.setAttribute("userName", userName); <ide> request.getRequestDispatcher("/views/patient.jsp").forward(request,response); <ide> <ide> }
JavaScript
mit
ae4b0856035ae9191818334c6f7cb8379511bb64
0
BigstickCarpet/swagger-parser,BigstickCarpet/swagger-parser
describe('Real-world APIs', function () { 'use strict'; var realWorldAPIs = []; var apiIndex = 0; before(function (done) { // Download a list of over 200 real-world Swagger APIs from apis.guru superagent.get('https://api.apis.guru/v2/list.json') .end(function (err, res) { if (err || !res.ok) { return done(err || new Error('Unable to downlaod real-world APIs from apis.guru')); } // Remove certain APIs that are known to cause problems var apis = res.body; delete apis['citrixonline.com:scim']; // special characters in the URL cause problems delete apis['googleapis.com:adsense']; // GitHub's CORS policy blocks this delete apis['versioneye.com']; // Fails validation due to incorrect content type delete apis['clarify.io']; // Contains an invalid $ref delete apis['bungie.net']; // https://github.com/BigstickCarpet/json-schema-ref-parser/issues/56 // https://github.com/APIs-guru/openapi-directory/issues/351 delete apis['azure.com:network-applicationGateway']; delete apis['azure.com:network-expressRouteCircuit']; delete apis['azure.com:network-networkInterface']; delete apis['azure.com:network-networkSecurityGroup']; delete apis['azure.com:network-publicIpAddress']; delete apis['azure.com:network-routeFilter']; delete apis['azure.com:network-routeTable']; delete apis['azure.com:network-virtualNetwork']; // Transform the list into an array of {name: string, url: string} realWorldAPIs = []; Object.keys(apis).forEach(function (apiName) { Object.keys(apis[apiName].versions).forEach(function (version) { var fullName = apiName + ' ' + (version[0] === 'v' ? version : 'v' + version); var url = apis[apiName].versions[version].swaggerYamlUrl; realWorldAPIs.push({ name: fullName, url: url }); }); }); done(); }); }); beforeEach(function () { // Some of these APIs are vary large, so we need to increase the timouts // to allow time for them to be downloaded, dereferenced, and validated. // so we need to increase the timeouts to allow for that this.currentTest.timeout(30000); this.currentTest.slow(5000); }); // Mocha requires us to create our tests synchronously. But the list of APIs is downloaded asynchronously. // So, we just create 1,500 placeholder tests, and then rename them later to reflect which API they're testing. for (var i = 1; i <= 1500; i++) { it(i + ') ', testNextAPI); } function testNextAPI (done) { // Get the next API to test var api = realWorldAPIs[apiIndex++]; if (api) { this.test.title += api.name; // Validate this API SwaggerParser.validate(api.url) .then(function () { done(); }) .catch(function (err) { done(err); }); } else { // There are no more APIs to test this.test.title += 'more APIs coming soon...'; done(); } } });
test/specs/real-world/real-world.spec.js
describe('Real-world APIs', function () { 'use strict'; var realWorldAPIs = []; var apiIndex = 0; before(function (done) { // Download a list of over 200 real-world Swagger APIs from apis.guru superagent.get('https://api.apis.guru/v2/list.json') .end(function (err, res) { if (err || !res.ok) { return done(err || new Error('Unable to downlaod real-world APIs from apis.guru')); } // Remove certain APIs that are known to cause problems var apis = res.body; delete apis['citrixonline.com:scim']; // special characters in the URL cause problems delete apis['googleapis.com:adsense']; // GitHub's CORS policy blocks this delete apis['versioneye.com']; // Fails validation due to incorrect content type delete apis['clarify.io']; // Contains an invalid $ref delete apis['bungie.net']; // https://github.com/BigstickCarpet/json-schema-ref-parser/issues/56 // https://github.com/APIs-guru/openapi-directory/issues/351 delete apis['azure.com:network-applicationGateway']; delete apis['azure.com:network-expressRouteCircuit']; delete apis['azure.com:network-networkInterface']; delete apis['azure.com:network-networkSecurityGroup']; delete apis['azure.com:network-publicIpAddress']; delete apis['azure.com:network-routeFilter']; delete apis['azure.com:network-routeTable']; delete apis['azure.com:network-virtualNetwork']; // Transform the list into an array of {name: string, url: string} realWorldAPIs = []; Object.keys(apis).forEach(function (apiName) { Object.keys(apis[apiName].versions).forEach(function (version) { var fullName = apiName + ' ' + (version[0] === 'v' ? version : 'v' + version); var url = apis[apiName].versions[version].swaggerYamlUrl; realWorldAPIs.push({ name: fullName, url: url }); }); }); done(); }); }); beforeEach(function () { // Some of these APIs are vary large, so we need to increase the timouts // to allow time for them to be downloaded, dereferenced, and validated. // so we need to increase the timeouts to allow for that this.currentTest.timeout(30000); this.currentTest.slow(5000); }); // Mocha requires us to create our tests synchronously. But the list of APIs is downloaded asynchronously. // So, we just create 1,000 placeholder tests, and then rename them later to reflect which API they're testing. for (var i = 1; i <= 1000; i++) { it(i + ') ', testNextAPI); } function testNextAPI (done) { // Get the next API to test var api = realWorldAPIs[apiIndex++]; if (api) { this.test.title += api.name; // Validate this API SwaggerParser.validate(api.url) .then(function () { done(); }) .catch(function (err) { done(err); }); } else { // There are no more APIs to test this.test.title += 'more APIs coming soon...'; done(); } } });
Increased the number of real-world tests
test/specs/real-world/real-world.spec.js
Increased the number of real-world tests
<ide><path>est/specs/real-world/real-world.spec.js <ide> }); <ide> <ide> // Mocha requires us to create our tests synchronously. But the list of APIs is downloaded asynchronously. <del> // So, we just create 1,000 placeholder tests, and then rename them later to reflect which API they're testing. <del> for (var i = 1; i <= 1000; i++) { <add> // So, we just create 1,500 placeholder tests, and then rename them later to reflect which API they're testing. <add> for (var i = 1; i <= 1500; i++) { <ide> it(i + ') ', testNextAPI); <ide> } <ide>
Java
apache-2.0
282883fac74a592ab86f2538e18d81dbf77af18c
0
gxa/gxa,gxa/gxa,gxa/gxa,gxa/gxa,gxa/gxa
/* * Copyright 2008-2011 Microarray Informatics Team, EMBL-European Bioinformatics Institute * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * * For further details of the Gene Expression Atlas project, including source code, * downloads and documentation, please see: * * http://gxa.github.com/gxa */ package uk.ac.ebi.gxa.utils; import org.apache.commons.codec.binary.Hex; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Comparator; import java.util.List; import static com.google.common.io.Closeables.closeQuietly; import static java.util.Arrays.asList; import static java.util.Collections.sort; import static uk.ac.ebi.gxa.exceptions.LogUtil.createUnexpected; /** */ public class DigestUtil { private static final byte[] SEPARATOR = {(byte) 0xA3, (byte) 141}; private static final String ALGORITHM = "SHA1"; private static final Charset CHARSET = Charset.forName("UTF-8"); public static byte[] digest(File... files) throws IOException { return digest(asList(files)); } public static byte[] digest(List<File> files) throws IOException { MessageDigest digest = getDigestInstance(); sort(files, new Comparator<File>() { @Override public int compare(File o1, File o2) { try { return o1.getCanonicalPath().compareTo(o2.getCanonicalPath()); } catch (IOException e) { throw createUnexpected("Cannot get canonical path", e); } } }); for (File f : files) { update(digest, f); putSeparator(digest); } return digest.digest(); } public static MessageDigest getDigestInstance() { try { return MessageDigest.getInstance(ALGORITHM); } catch (NoSuchAlgorithmException e) { throw createUnexpected("Cannot get a digester", e); } } public static void update(MessageDigest complete, File f) throws IOException { InputStream fis = null; try { fis = new FileInputStream(f); byte[] buffer = new byte[1024]; int numRead; do { numRead = fis.read(buffer); if (numRead > 0) { complete.update(buffer, 0, numRead); } } while (numRead != -1); } finally { closeQuietly(fis); } } public static void update(MessageDigest digest, String s) { if (s != null) digest.update(s.getBytes(CHARSET)); putSeparator(digest); } private static void putSeparator(MessageDigest digest) { digest.update(SEPARATOR); } /** * Converts byte array into a hex string * * @param bytes bytes to format * @return formatted hex string (lowercase) */ public static String toHex(byte[] bytes) { return new String(Hex.encodeHex(bytes)); } }
atlas-utils/src/main/java/uk/ac/ebi/gxa/utils/DigestUtil.java
/* * Copyright 2008-2011 Microarray Informatics Team, EMBL-European Bioinformatics Institute * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * * For further details of the Gene Expression Atlas project, including source code, * downloads and documentation, please see: * * http://gxa.github.com/gxa */ package uk.ac.ebi.gxa.utils; import org.apache.commons.codec.binary.Hex; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Comparator; import java.util.List; import static com.google.common.io.Closeables.closeQuietly; import static java.util.Arrays.asList; import static java.util.Collections.sort; import static uk.ac.ebi.gxa.exceptions.LogUtil.createUnexpected; /** */ public class DigestUtil { private static final byte[] SEPARATOR = {(byte) 0xA3, (byte) 141}; private static final String ALGORITHM = "MD5"; private static final Charset CHARSET = Charset.forName("UTF-8"); public static byte[] digest(File... files) throws IOException { return digest(asList(files)); } public static byte[] digest(List<File> files) throws IOException { MessageDigest digest = getDigestInstance(); sort(files, new Comparator<File>() { @Override public int compare(File o1, File o2) { try { return o1.getCanonicalPath().compareTo(o2.getCanonicalPath()); } catch (IOException e) { throw createUnexpected("Cannot get canonical path", e); } } }); for (File f : files) { update(digest, f); putSeparator(digest); } return digest.digest(); } public static MessageDigest getDigestInstance() { try { return MessageDigest.getInstance(ALGORITHM); } catch (NoSuchAlgorithmException e) { throw createUnexpected("Cannot get a digester", e); } } public static void update(MessageDigest complete, File f) throws IOException { InputStream fis = null; try { fis = new FileInputStream(f); byte[] buffer = new byte[1024]; int numRead; do { numRead = fis.read(buffer); if (numRead > 0) { complete.update(buffer, 0, numRead); } } while (numRead != -1); } finally { closeQuietly(fis); } } public static void update(MessageDigest digest, String s) { if (s != null) digest.update(s.getBytes(CHARSET)); putSeparator(digest); } private static void putSeparator(MessageDigest digest) { digest.update(SEPARATOR); } /** * Converts byte array into a hex string * * @param bytes bytes to format * @return formatted hex string (lowercase) */ public static String toHex(byte[] bytes) { return new String(Hex.encodeHex(bytes)); } }
Trac 2978 SHA1 apparently is fast enough
atlas-utils/src/main/java/uk/ac/ebi/gxa/utils/DigestUtil.java
Trac 2978 SHA1 apparently is fast enough
<ide><path>tlas-utils/src/main/java/uk/ac/ebi/gxa/utils/DigestUtil.java <ide> */ <ide> public class DigestUtil { <ide> private static final byte[] SEPARATOR = {(byte) 0xA3, (byte) 141}; <del> private static final String ALGORITHM = "MD5"; <add> private static final String ALGORITHM = "SHA1"; <ide> private static final Charset CHARSET = Charset.forName("UTF-8"); <ide> <ide> public static byte[] digest(File... files) throws IOException {
Java
lgpl-2.1
9a899d4d1ac2a7da52acc70994597e4d2e40acc2
0
spotbugs/spotbugs,KengoTODA/spotbugs,sewe/spotbugs,KengoTODA/spotbugs,johnscancella/spotbugs,johnscancella/spotbugs,johnscancella/spotbugs,spotbugs/spotbugs,sewe/spotbugs,spotbugs/spotbugs,KengoTODA/spotbugs,sewe/spotbugs,sewe/spotbugs,spotbugs/spotbugs,johnscancella/spotbugs,KengoTODA/spotbugs,spotbugs/spotbugs
/* * FindBugs - Find Bugs in Java programs * Copyright (C) 2003-2008 University of Maryland * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.umd.cs.findbugs.cloud; import java.awt.GraphicsEnvironment; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.Timer; import java.util.TimerTask; import java.util.TreeSet; import java.util.concurrent.CountDownLatch; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.prefs.Preferences; import java.util.regex.Pattern; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import javax.swing.JOptionPane; import edu.umd.cs.findbugs.BugAnnotation; import edu.umd.cs.findbugs.BugCollection; import edu.umd.cs.findbugs.BugDesignation; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugRanker; import edu.umd.cs.findbugs.ClassAnnotation; import edu.umd.cs.findbugs.FindBugs; import edu.umd.cs.findbugs.I18N; import edu.umd.cs.findbugs.PackageStats; import edu.umd.cs.findbugs.PluginLoader; import edu.umd.cs.findbugs.ProjectPackagePrefixes; import edu.umd.cs.findbugs.ProjectStats; import edu.umd.cs.findbugs.SortedBugCollection; import edu.umd.cs.findbugs.SourceLineAnnotation; import edu.umd.cs.findbugs.StartTime; import edu.umd.cs.findbugs.SystemProperties; import edu.umd.cs.findbugs.Version; import edu.umd.cs.findbugs.ba.AnalysisContext; import edu.umd.cs.findbugs.ba.SourceFile; import edu.umd.cs.findbugs.gui2.MainFrame; import edu.umd.cs.findbugs.gui2.ViewFilter; import edu.umd.cs.findbugs.internalAnnotations.SlashedClassName; import edu.umd.cs.findbugs.util.Multiset; import edu.umd.cs.findbugs.util.Util; /** * @author pwilliam */ public class DBCloud extends AbstractCloud { static final boolean THROW_EXCEPTION_IF_CANT_CONNECT = false; /** * */ private static final String USER_NAME = "user.name"; Mode mode = Mode.COMMUNAL; public Mode getMode() { return mode; } public void setMode(Mode mode) { this.mode = mode; } class BugData { final String instanceHash; public BugData(String instanceHash) { this.instanceHash = instanceHash; } int id; boolean inDatabase; long firstSeen; String bugLink = NONE; String filedBy; String bugStatus; String bugAssignedTo; String bugComponentName; long bugFiled = Long.MAX_VALUE; SortedSet<BugDesignation> designations = new TreeSet<BugDesignation>(); Collection<BugInstance> bugs = new LinkedHashSet<BugInstance>(); long lastSeen; @CheckForNull BugDesignation getPrimaryDesignation() { for (BugDesignation bd : designations) if (findbugsUser.equals(bd.getUser())) return bd; return null; } @CheckForNull BugDesignation getUserDesignation() { for(BugDesignation d : designations) if (findbugsUser.equals(d.getUser())) return new BugDesignation(d); return null; } Collection<BugDesignation> getUniqueDesignations() { if (designations.isEmpty()) return Collections.emptyList(); HashSet<String> reviewers = new HashSet<String>(); ArrayList<BugDesignation> result = new ArrayList<BugDesignation>(designations.size()); for(BugDesignation d : designations) if (reviewers.add(d.getUser())) result.add(d); return result; } Set<String> getReviewers() { HashSet<String> reviewers = new HashSet<String>(); for(BugDesignation bd : designations) reviewers.add(bd.getUser()); reviewers.remove(""); reviewers.remove(null); return reviewers; } boolean isClaimed() { for(BugDesignation bd : getUniqueDesignations()) { if (bd.getDesignationKey().equals(UserDesignation.I_WILL_FIX.name())) return true; } return false; } BugDesignation getNonnullUserDesignation() { BugDesignation d = getUserDesignation(); if (d != null) return d; d = new BugDesignation(UserDesignation.UNCLASSIFIED.name(), System.currentTimeMillis(), "", findbugsUser); return d; } public boolean canSeeCommentsByOthers() { switch(mode) { case SECRET: return false; case COMMUNAL : return true; case VOTING : return hasVoted(); } throw new IllegalStateException(); } public boolean hasVoted() { for(BugDesignation bd : designations) if (findbugsUser.equals(bd.getUser())) return true; return false; } } int updatesSentToDatabase; Date lastUpdate = new Date(); Date resync; Date attemptedResync; int resyncCount; Map<String, BugData> instanceMap = new HashMap<String, BugData>(); Map<Integer, BugData> idMap = new HashMap<Integer, BugData>(); IdentityHashMap<BugDesignation, Integer> bugDesignationId = new IdentityHashMap<BugDesignation, Integer>(); BugData getBugData(String instanceHash) { BugData bd = instanceMap.get(instanceHash); if (bd == null) { bd = new BugData(instanceHash); instanceMap.put(instanceHash, bd); } return bd; } BugData getBugData(BugInstance bug) { try { initialSyncDone.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } BugData bugData = getBugData(bug.getInstanceHash()); bugData.bugs.add(bug); return bugData; } void loadDatabaseInfo(String hash, int id, long firstSeen, long lastSeen) { BugData bd = instanceMap.get(hash); if (bd == null) return; if (idMap.containsKey(id)) { assert bd == idMap.get(id); assert bd.id == id; assert bd.firstSeen == firstSeen; } else { bd.id = id; bd.firstSeen = firstSeen; bd.lastSeen = lastSeen; bd.inDatabase = true; idMap.put(id, bd); } } DBCloud(BugCollection bugs) { super(bugs); } static final Pattern FORBIDDEN_PACKAGE_PREFIXES = Pattern.compile(SystemProperties.getProperty("findbugs.forbiddenPackagePrefixes", " none ").replace(',','|')); static final boolean PROMPT_FOR_USER_NAME = SystemProperties.getBoolean("findbugs.db.promptForUserName", false); int sessionId = -1; final CountDownLatch initialSyncDone = new CountDownLatch(1); public void bugsPopulated() { queue.add(new PopulateBugs(true)); } private static final long LAST_SEEN_UPDATE_WINDOW = TimeUnit.MILLISECONDS.convert(7*24*3600, TimeUnit.SECONDS); long boundDuration(long milliseconds) { if (milliseconds < 0) return 0; if (milliseconds > 1000*1000) return 1000*1000; return milliseconds; } static boolean invocationRecorded; class PopulateBugs implements Update { final boolean performFullLoad; PopulateBugs(boolean performFullLoad) { this.performFullLoad = performFullLoad; } public void execute(DatabaseSyncTask t) throws SQLException { if (startShutdown) return; String commonPrefix = null; int updates = 0; if (performFullLoad) { for (BugInstance b : bugCollection.getCollection()) if (!skipBug(b)) { commonPrefix = Util.commonPrefix(commonPrefix, b.getPrimaryClass().getClassName()); getBugData(b.getInstanceHash()).bugs.add(b); } if (commonPrefix == null) commonPrefix = "<no bugs>"; else if (commonPrefix.length() > 128) commonPrefix = commonPrefix.substring(0, 128); } try { long startTime = System.currentTimeMillis(); Connection c = getConnection(); PreparedStatement ps; ResultSet rs; if (performFullLoad) { ps = c.prepareStatement("SELECT id, hash, firstSeen, lastSeen FROM findbugs_issue"); rs = ps.executeQuery(); while (rs.next()) { int col = 1; int id = rs.getInt(col++); String hash = rs.getString(col++); Timestamp firstSeen = rs.getTimestamp(col++); Timestamp lastSeen = rs.getTimestamp(col++); loadDatabaseInfo(hash, id, firstSeen.getTime(), lastSeen.getTime()); } rs.close(); ps.close(); } if (startShutdown) return; ps = c.prepareStatement("SELECT id, issueId, who, designation, comment, time FROM findbugs_evaluation"); rs = ps.executeQuery(); while (rs.next()) { int col = 1; int id = rs.getInt(col++); int issueId = rs.getInt(col++); String who = rs.getString(col++); String designation = rs.getString(col++); String comment = rs.getString(col++); Timestamp when = rs.getTimestamp(col++); BugData data = idMap.get(issueId); if (data != null) { BugDesignation bd = new BugDesignation(designation, when.getTime(), comment, who); if (data.designations.add(bd)) { bugDesignationId.put(bd, id); updates++; for(BugInstance bug : data.bugs) { updatedIssue(bug); } } } } rs.close(); ps.close(); if (startShutdown) return; ps = c.prepareStatement("SELECT hash, bugReportId, whoFiled, whenFiled, status, assignedTo, componentName FROM findbugs_bugreport"); rs = ps.executeQuery(); while (rs.next()) { int col = 1; String hash = rs.getString(col++); String bugReportId = rs.getString(col++); String whoFiled = rs.getString(col++); Timestamp whenFiled = rs.getTimestamp(col++); String status = rs.getString(col++); String assignedTo = rs.getString(col++); String componentName = rs.getString(col++); BugData data = instanceMap.get(hash); if (data != null) { if (Util.nullSafeEquals(data.bugLink, bugReportId) && Util.nullSafeEquals(data.filedBy, whoFiled) && data.bugFiled == whenFiled.getTime() && Util.nullSafeEquals(data.bugAssignedTo, assignedTo) && Util.nullSafeEquals(data.bugStatus, status) && Util.nullSafeEquals(data.bugComponentName, componentName)) continue; data.bugLink = bugReportId; data.filedBy = whoFiled; data.bugFiled = whenFiled.getTime(); data.bugAssignedTo = assignedTo; data.bugStatus = status; data.bugComponentName = componentName; updates++; for(BugInstance bug : data.bugs) { updatedIssue(bug); } } } rs.close(); ps.close(); if (startShutdown) return; if (!invocationRecorded) { long jvmStartTime = StartTime.START_TIME - StartTime.VM_START_TIME; SortedBugCollection sbc = (SortedBugCollection) bugCollection; long findbugsStartTime = sbc.getTimeStartedLoading() - StartTime.START_TIME; URL findbugsURL = PluginLoader.getCoreResource("findbugs.xml"); String loadURL = findbugsURL == null ? "" : findbugsURL.toString(); long initialLoadTime = sbc.getTimeFinishedLoading() - sbc.getTimeStartedLoading(); long lostTime = startTime - sbc.getTimeStartedLoading(); long initialSyncTime = System.currentTimeMillis() - sbc.getTimeFinishedLoading(); String os = SystemProperties.getProperty("os.name", ""); String osVersion = SystemProperties.getProperty("os.version"); String jvmVersion = SystemProperties.getProperty("java.runtime.version"); if (osVersion != null) os = os +" " + osVersion; PreparedStatement insertSession = c .prepareStatement( "INSERT INTO findbugs_invocation (who, entryPoint, dataSource, fbVersion, os, jvmVersion, jvmLoadTime, findbugsLoadTime, analysisLoadTime, initialSyncTime, numIssues, startTime, commonPrefix)" + " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS); Timestamp now = new Timestamp(startTime); int col = 1; insertSession.setString(col++, findbugsUser); insertSession.setString(col++, limitToMaxLength(loadURL, 128)); insertSession.setString(col++, limitToMaxLength(sbc.getDataSource(), 128)); insertSession.setString(col++, Version.RELEASE); insertSession.setString(col++, limitToMaxLength(os,128)); insertSession.setString(col++, limitToMaxLength(jvmVersion,64)); insertSession.setLong(col++, boundDuration(jvmStartTime)); insertSession.setLong(col++, boundDuration(findbugsStartTime)); insertSession.setLong(col++, boundDuration(initialLoadTime)); insertSession.setLong(col++, boundDuration(initialSyncTime)); insertSession.setInt(col++, bugCollection.getCollection().size()); insertSession.setTimestamp(col++, now); insertSession.setString(col++, commonPrefix); int rowCount = insertSession.executeUpdate(); rs = insertSession.getGeneratedKeys(); if (rs.next()) { sessionId = rs.getInt(1); } insertSession.close(); rs.close(); invocationRecorded = true; } c.close(); } catch (Exception e) { e.printStackTrace(); displayMessage("problem bulk loading database", e); } if (startShutdown) return; if (!performFullLoad) { attemptedResync = new Date(); if (updates > 0) { resync = attemptedResync; resyncCount = updates; } } else { long stillPresentAt = bugCollection.getTimestamp(); for (BugInstance b : bugCollection.getCollection()) if (!skipBug(b)) { BugData bd = getBugData(b.getInstanceHash()); if (!bd.inDatabase) { storeNewBug(b, stillPresentAt); } else { long firstVersion = b.getFirstVersion(); long firstSeen = bugCollection.getAppVersionFromSequenceNumber(firstVersion).getTimestamp(); if (FindBugs.validTimestamp(firstSeen) && (firstSeen < bd.firstSeen || !FindBugs.validTimestamp(bd.firstSeen))) { bd.firstSeen = firstSeen; storeFirstSeen(bd); } else if (FindBugs.validTimestamp(stillPresentAt) && stillPresentAt > bd.lastSeen + LAST_SEEN_UPDATE_WINDOW) { storeLastSeen(bd, stillPresentAt); } BugDesignation designation = bd.getPrimaryDesignation(); if (designation != null) b.setUserDesignation(new BugDesignation(designation)); } } initialSyncDone.countDown(); assert !scheduled; if (startShutdown) return; long delay = 10*60*1000; // 10 minutes if (!scheduled) { try { resyncTimer.schedule(new TimerTask() { @Override public void run() { if (attemptedResync == null || lastUpdate.after(attemptedResync) || numSkipped++ > 6) { numSkipped = 0; queue.add(new PopulateBugs(false)); } }}, delay, delay); } catch (Exception e) { AnalysisContext.logError("Error scheduling resync", e); } } scheduled = true; } updatedStatus(); } } boolean scheduled = false; int numSkipped = 0; private static String limitToMaxLength(String s, int maxLength) { if (s.length() <= maxLength) return s; return s.substring(0, maxLength); } private String getProperty(String propertyName) { return SystemProperties.getProperty("findbugs.jdbc." + propertyName); } final static int MAX_DB_RANK = SystemProperties.getInt("findbugs.db.maxrank", 12); String url, dbUser, dbPassword, findbugsUser, dbName; @CheckForNull Pattern sourceFileLinkPattern; String sourceFileLinkFormat; String sourceFileLinkFormatWithLine; String sourceFileLinkToolTip; ProjectPackagePrefixes projectMapping = new ProjectPackagePrefixes(); Map<String,String> prefixBugComponentMapping = new HashMap<String,String>(); Connection getConnection() throws SQLException { return DriverManager.getConnection(url, dbUser, dbPassword); } public boolean initialize() { String mode = getProperty("votingmode"); if (mode != null) setMode(Mode.valueOf(mode.toUpperCase())); String sp = SystemProperties.getProperty("findbugs.sourcelink.pattern"); String sf = SystemProperties.getProperty("findbugs.sourcelink.format"); String sfwl = SystemProperties.getProperty("findbugs.sourcelink.formatWithLine"); String stt = SystemProperties.getProperty("findbugs.sourcelink.tooltip"); if (sp != null && sf != null) { try { this.sourceFileLinkPattern = Pattern.compile(sp); this.sourceFileLinkFormat = sf; this.sourceFileLinkToolTip = stt; this.sourceFileLinkFormatWithLine = sfwl; } catch (RuntimeException e) { AnalysisContext.logError("Could not compile pattern " + sp, e); if (THROW_EXCEPTION_IF_CANT_CONNECT) throw e; } } String sqlDriver = getProperty("dbDriver"); url = getProperty("dbUrl"); dbName = getProperty("dbName"); dbUser = getProperty("dbUser"); dbPassword = getProperty("dbPassword"); findbugsUser = getProperty("findbugsUser"); if (sqlDriver == null || dbUser == null || url == null || dbPassword == null) { if (THROW_EXCEPTION_IF_CANT_CONNECT) throw new RuntimeException("Unable to load database properties"); return false; } if (findbugsUser == null) { if (PROMPT_FOR_USER_NAME) { Preferences prefs = Preferences.userNodeForPackage(DBCloud.class); findbugsUser = prefs.get(USER_NAME, null); findbugsUser = bugCollection.getProject().getGuiCallback().showQuestionDialog( "Name/handle/email for recording your evaluations?\n" + "(sorry, no authentication or confidentiality currently provided)", "Name for recording your evaluations", findbugsUser == null ? "" : findbugsUser); if (findbugsUser != null) prefs.put(USER_NAME, findbugsUser); } else if (findbugsUser == null) findbugsUser = System.getProperty(USER_NAME, ""); if (findbugsUser == null) { if (THROW_EXCEPTION_IF_CANT_CONNECT) throw new RuntimeException("Unable to get reviewer user name for database"); return false; } } loadBugComponents(); try { Class.forName(sqlDriver); Connection c = getConnection(); Statement stmt = c.createStatement(); ResultSet rs = stmt.executeQuery("SELECT COUNT(*) from findbugs_issue"); boolean result = false; if (rs.next()) { int count = rs.getInt(1); result = true; } rs.close(); stmt.close(); c.close(); if (result) { runnerThread.setDaemon(true); runnerThread.start(); return true; } else if (THROW_EXCEPTION_IF_CANT_CONNECT) { throw new RuntimeException("Unable to get database results"); } else return false; } catch (RuntimeException e) { displayMessage("Unable to connect to " + dbName, e); if (THROW_EXCEPTION_IF_CANT_CONNECT) throw e; return false; } catch (Exception e) { displayMessage("Unable to connect to " + dbName, e); if (THROW_EXCEPTION_IF_CANT_CONNECT) throw new RuntimeException("Unable to connect to database", e); return false; } } private String getBugComponent(@SlashedClassName String className) { int longestMatch = -1; String result = null; for(Map.Entry<String,String> e : prefixBugComponentMapping.entrySet()) { String key = e.getKey(); if (className.startsWith(key) && longestMatch < key.length()) { longestMatch = key.length(); result = e.getValue(); } } return result; } private void loadBugComponents(){ try { URL u = PluginLoader.getCoreResource("bugComponents.properties"); if (u != null) { BufferedReader in = new BufferedReader(new InputStreamReader(u.openStream())); while(true) { String s = in.readLine(); if (s == null) break; if (s.trim().length() == 0) continue; int x = s.indexOf(' '); if (x == -1) { if (!prefixBugComponentMapping.containsKey("")) prefixBugComponentMapping.put("", s); } else { String prefix = s.substring(x+1); if (!prefixBugComponentMapping.containsKey(prefix)) prefixBugComponentMapping.put(prefix, s.substring(0,x)); } } in.close(); } } catch (IOException e) { AnalysisContext.logError("Unable to load bug component properties", e); } } final LinkedBlockingQueue<Update> queue = new LinkedBlockingQueue<Update>(); volatile boolean shutdown = false; volatile boolean startShutdown = false; final DatabaseSyncTask runner = new DatabaseSyncTask(); final Thread runnerThread = new Thread(runner, "Database synchronization thread"); final Timer resyncTimer = new Timer("Resync scheduler", true); @Override public void shutdown() { try { startShutdown = true; resyncTimer.cancel(); queue.add(new ShutdownTask()); try { Connection c = getConnection(); PreparedStatement setEndTime = c.prepareStatement("UPDATE findbugs_invocation SET endTime = ? WHERE id = ?"); Timestamp date = new Timestamp(System.currentTimeMillis()); int col = 1; setEndTime.setTimestamp(col++, date); setEndTime.setInt(col++, sessionId); setEndTime.execute(); setEndTime.close(); c.close(); } catch (Throwable e) { // we're in shutdown mode, not going to complain assert true; } if (!queue.isEmpty() && runnerThread.isAlive()) { setErrorMsg("waiting for synchronization to complete before shutdown"); for (int i = 0; i < 100; i++) { if (queue.isEmpty() || !runnerThread.isAlive()) break; try { Thread.sleep(30); } catch (InterruptedException e) { break; } } } } finally { shutdown = true; runnerThread.interrupt(); } } private RuntimeException shutdownException = new RuntimeException("DBCloud shutdown"); private void checkForShutdown() { if (!shutdown) return; IllegalStateException e = new IllegalStateException("DBCloud has already been shutdown"); e.initCause(shutdownException); throw e; } public void storeNewBug(BugInstance bug, long analysisTime) { checkForShutdown(); queue.add(new StoreNewBug(bug, analysisTime)); } public void storeFirstSeen(final BugData bd) { checkForShutdown(); queue.add(new Update(){ public void execute(DatabaseSyncTask t) throws SQLException { t.storeFirstSeen(bd); }}); } public void storeLastSeen(final BugData bd, final long timestamp) { checkForShutdown(); queue.add(new Update(){ public void execute(DatabaseSyncTask t) throws SQLException { t.storeLastSeen(bd, timestamp); }}); } public void storeUserAnnotation(BugData data, BugDesignation bd) { checkForShutdown(); queue.add(new StoreUserAnnotation(data, bd)); updatedStatus(); if (firstTimeDoing(HAS_CLASSIFIED_ISSUES)) { String msg = "Classification and comments have been sent to database.\n" + "You'll only see this message the first time your classifcations/comments are sent\n" + "to the database."; if (mode == Mode.VOTING) msg += "\nOnce you've classified an issue, you can see how others have classified it."; msg += "\nYour classification and comments are independent from filing a bug using an external\n" + "bug reporting system."; bugCollection.getProject().getGuiCallback().showMessageDialog(msg); } } private static final String HAS_SKIPPED_BUG = "has_skipped_bugs"; private boolean skipBug(BugInstance bug) { boolean result = bug.getBugPattern().getCategory().equals("NOISE") || bug.isDead() || BugRanker.findRank(bug) > MAX_DB_RANK; if (result && firstTimeDoing(HAS_SKIPPED_BUG)) { bugCollection.getProject().getGuiCallback().showMessageDialog( "To limit database load, some issues are not persisted to database.\n" + "For example, issues with rank greater than " + MAX_DB_RANK + " are not stored in the db.\n" + "One of more of the issues you are reviewing will not be persisted,\n" + "and you will not be able to record an evalution of those issues.\n" + "As we scale up the database, we hope to relax these restrictions"); } return result; } public static final String PENDING = "-- pending --"; public static final String NONE = "none"; class DatabaseSyncTask implements Runnable { int handled; Connection c; public void establishConnection() throws SQLException { if (c != null) return; c = getConnection(); } public void closeConnection() throws SQLException { if (c == null) return; c.close(); c = null; } public void run() { try { while (!shutdown) { Update u = queue.poll(10, TimeUnit.SECONDS); if (u == null) { closeConnection(); continue; } establishConnection(); u.execute(this); if ((handled++) % 100 == 0 || queue.isEmpty()) { updatedStatus(); } } } catch (DatabaseSyncShutdownException e) { assert true; } catch (RuntimeException e) { displayMessage("Runtime exception; database connection shutdown", e); } catch (SQLException e) { displayMessage("SQL exception; database connection shutdown", e); } catch (InterruptedException e) { assert true; } try { closeConnection(); } catch (SQLException e) { } } public void newEvaluation(BugData data, BugDesignation bd) { if (!data.inDatabase) return; try { data.designations.add(bd); if (bd.getUser() == null) bd.setUser(findbugsUser); if (bd.getAnnotationText() == null) bd.setAnnotationText(""); PreparedStatement insertEvaluation = c.prepareStatement("INSERT INTO findbugs_evaluation (issueId, who, designation, comment, time) VALUES (?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS); Timestamp date = new Timestamp(bd.getTimestamp()); int col = 1; insertEvaluation.setInt(col++, data.id); insertEvaluation.setString(col++, bd.getUser()); insertEvaluation.setString(col++, bd.getDesignationKey()); insertEvaluation.setString(col++, bd.getAnnotationText()); insertEvaluation.setTimestamp(col++, date); insertEvaluation.executeUpdate(); ResultSet rs = insertEvaluation.getGeneratedKeys(); if (rs.next()) { int id = rs.getInt(1); bugDesignationId.put(bd, id); } rs.close(); } catch (Exception e) { displayMessage("Problems looking up user annotations", e); } lastUpdate = new Date(); updatesSentToDatabase++; } public void newBug(BugInstance b) { try { BugData bug = getBugData(b.getInstanceHash()); if (bug.inDatabase) return; PreparedStatement insertBugData = c.prepareStatement("INSERT INTO findbugs_issue (firstSeen, lastSeen, hash, bugPattern, priority, primaryClass) VALUES (?,?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS); int col = 1; insertBugData.setTimestamp(col++, new Timestamp(bug.firstSeen)); insertBugData.setTimestamp(col++, new Timestamp(bug.lastSeen)); insertBugData.setString(col++, bug.instanceHash); insertBugData.setString(col++, b.getBugPattern().getType()); insertBugData.setInt(col++, b.getPriority()); insertBugData.setString(col++, b.getPrimaryClass().getClassName()); insertBugData.executeUpdate(); ResultSet rs = insertBugData.getGeneratedKeys(); if (rs.next()) { bug.id = rs.getInt(1); bug.inDatabase = true; } rs.close(); insertBugData.close(); } catch (Exception e) { displayMessage("Problems looking up user annotations", e); } } public void storeFirstSeen(BugData bug) { try { PreparedStatement insertBugData = c.prepareStatement("UPDATE findbugs_issue SET firstSeen = ? WHERE id = ?"); Timestamp date = new Timestamp(bug.firstSeen); int col = 1; insertBugData.setTimestamp(col++, date); insertBugData.setInt(col++, bug.id); insertBugData.executeUpdate(); insertBugData.close(); } catch (Exception e) { displayMessage("Problems looking up user annotations", e); } } public void storeLastSeen(BugData bug, long timestamp) { try { PreparedStatement insertBugData = c.prepareStatement("UPDATE findbugs_issue SET lastSeen = ? WHERE id = ?"); Timestamp date = new Timestamp(timestamp); int col = 1; insertBugData.setTimestamp(col++, date); insertBugData.setInt(col++, bug.id); insertBugData.executeUpdate(); insertBugData.close(); } catch (Exception e) { displayMessage("Problems looking up user annotations", e); } } /** * @param bd */ public void fileBug(BugData bug) { try { insertPendingRecord(c, bug, bug.bugFiled, bug.filedBy); } catch (Exception e) { displayMessage("Problem filing bug", e); } lastUpdate = new Date(); updatesSentToDatabase++; } } /** * @param bug * @return * @throws SQLException */ private void insertPendingRecord(Connection c, BugData bug, long when, String who) throws SQLException { int pendingId = -1; PreparedStatement query = c .prepareStatement("SELECT id, bugReportId, whoFiled, whenFiled FROM findbugs_bugreport where hash=?"); query.setString(1, bug.instanceHash); ResultSet rs = query.executeQuery(); boolean needsUpdate = false; try { while (rs.next()) { int col = 1; int id = rs.getInt(col++); String bugReportId = rs.getString(col++); String whoFiled = rs.getString(col++); Timestamp whenFiled = rs.getTimestamp(col++); if (!bugReportId.equals(PENDING) || !who.equals(whoFiled) && !pendingStatusHasExpired(whenFiled.getTime())) { rs.close(); query.close(); throw new IllegalArgumentException(whoFiled + " already filed bug report " + bugReportId + " for " + bug.instanceHash); } pendingId = id; needsUpdate = !who.equals(whoFiled); } } catch (SQLException e) { String msg = "Problem inserting pending record for " + bug.instanceHash; AnalysisContext.logError(msg, e); System.out.println(msg); e.printStackTrace(); return; } finally { rs.close(); query.close(); } if (pendingId == -1) { PreparedStatement insert = c .prepareStatement("INSERT INTO findbugs_bugreport (hash, bugReportId, whoFiled, whenFiled)" + " VALUES (?, ?, ?, ?)"); Timestamp date = new Timestamp(when); int col = 1; insert.setString(col++, bug.instanceHash); insert.setString(col++, PENDING); insert.setString(col++, who); insert.setTimestamp(col++, date); insert.executeUpdate(); insert.close(); } else if (needsUpdate) { PreparedStatement updateBug = c .prepareStatement("UPDATE findbugs_bugreport SET whoFiled = ? and whenFiled = ? WHERE id = ?"); int col = 1; updateBug.setString(col++, bug.filedBy); updateBug.setTimestamp(col++, new Timestamp(bug.bugFiled)); updateBug.setInt(col++, pendingId); updateBug.executeUpdate(); updateBug.close(); } } static interface Update { void execute(DatabaseSyncTask t) throws SQLException; } static class ShutdownTask implements Update { public void execute(DatabaseSyncTask t) { throw new DatabaseSyncShutdownException(); } } static class DatabaseSyncShutdownException extends RuntimeException { } boolean bugAlreadyFiled(BugInstance b) { BugData bd = getBugData(b.getInstanceHash()); if (bd == null || !bd.inDatabase) throw new IllegalArgumentException(); return bd.bugLink != null && !bd.bugLink.equals(NONE) && !bd.bugLink.equals(PENDING); } class FileBug implements Update { public FileBug(BugInstance bug) { this.bd = getBugData(bug.getInstanceHash()); if (bd == null || !bd.inDatabase) throw new IllegalArgumentException(); bd.bugFiled = System.currentTimeMillis(); bd.bugLink = PENDING; bd.filedBy = findbugsUser; } final BugData bd; public void execute(DatabaseSyncTask t) throws SQLException { t.fileBug(bd); } } class StoreNewBug implements Update { public StoreNewBug(BugInstance bug, long analysisTime) { this.bug = bug; this.analysisTime = analysisTime; } final BugInstance bug; final long analysisTime; public void execute(DatabaseSyncTask t) throws SQLException { BugData data = getBugData(bug.getInstanceHash()); if (data.lastSeen < analysisTime && FindBugs.validTimestamp(analysisTime)) data.lastSeen = analysisTime; long timestamp = bugCollection.getAppVersionFromSequenceNumber(bug.getFirstVersion()).getTimestamp(); data.firstSeen = timestamp; if (data.inDatabase) return; t.newBug(bug); data.inDatabase = true; } } static class StoreUserAnnotation implements Update { public StoreUserAnnotation(BugData data, BugDesignation designation) { super(); this.data = data; this.designation = designation; } public void execute(DatabaseSyncTask t) throws SQLException { t.newEvaluation(data, new BugDesignation(designation)); } final BugData data; final BugDesignation designation; } private void displayMessage(String msg, Exception e) { AnalysisContext.logError(msg, e); if (bugCollection != null && bugCollection.getProject().isGuiAvaliable()) { StringWriter stackTraceWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stackTraceWriter); e.printStackTrace(printWriter); bugCollection.getProject().getGuiCallback().showMessageDialog( String.format("%s - %s\n%s", msg, e.getMessage(), stackTraceWriter.toString())); } else { System.err.println(msg); e.printStackTrace(System.err); } } private void displayMessage(String msg) { if (!GraphicsEnvironment.isHeadless() && bugCollection.getProject().isGuiAvaliable()) { bugCollection.getProject().getGuiCallback().showMessageDialog(msg); } else { System.err.println(msg); } } public String getUser() { return findbugsUser; } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#getFirstSeen(edu.umd.cs.findbugs.BugInstance) */ public long getFirstSeen(BugInstance b) { return getBugData(b).firstSeen; } @Override public boolean overallClassificationIsNotAProblem(BugInstance b) { BugData bd = getBugData(b); if (bd == null) return false; int isAProblem = 0; int notAProblem = 0; for(BugDesignation d : bd.getUniqueDesignations() ) switch(UserDesignation.valueOf(d.getDesignationKey())) { case I_WILL_FIX: case MUST_FIX: case SHOULD_FIX: isAProblem++; break; case BAD_ANALYSIS: case NOT_A_BUG: case MOSTLY_HARMLESS: case OBSOLETE_CODE: notAProblem++; break; } return notAProblem > isAProblem; } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#getUser() */ public UserDesignation getUserDesignation(BugInstance b) { BugDesignation bd = getBugData(b).getPrimaryDesignation(); if (bd == null) return UserDesignation.UNCLASSIFIED; return UserDesignation.valueOf(bd.getDesignationKey()); } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#getUserEvaluation(edu.umd.cs.findbugs.BugInstance) */ public String getUserEvaluation(BugInstance b) { BugDesignation bd = getBugData(b).getPrimaryDesignation(); if (bd == null) return ""; String result = bd.getAnnotationText(); if (result == null) return ""; return result; } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#getUserTimestamp(edu.umd.cs.findbugs.BugInstance) */ public long getUserTimestamp(BugInstance b) { BugDesignation bd = getBugData(b).getPrimaryDesignation(); if (bd == null) return Long.MAX_VALUE; return bd.getTimestamp(); } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#setUserDesignation(edu.umd.cs.findbugs.BugInstance, edu.umd.cs.findbugs.cloud.UserDesignation, long) */ public void setUserDesignation(BugInstance b, UserDesignation u, long timestamp) { BugData data = getBugData(b); BugDesignation bd = data.getUserDesignation(); if (bd == null) { if (u == UserDesignation.UNCLASSIFIED) return; bd = data.getNonnullUserDesignation(); } bd.setDesignationKey(u.name()); if (bd.isDirty()) { bd.setTimestamp(timestamp); storeUserAnnotation(data, bd); } } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#setUserEvaluation(edu.umd.cs.findbugs.BugInstance, java.lang.String, long) */ public void setUserEvaluation(BugInstance b, String e, long timestamp) { BugData data = getBugData(b); BugDesignation bd = data.getUserDesignation(); if (bd == null) { if (e.length() == 0) return; bd = data.getNonnullUserDesignation(); } bd.setAnnotationText(e); if (bd.isDirty()) { bd.setTimestamp(timestamp); storeUserAnnotation(data, bd); } } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#setUserTimestamp(edu.umd.cs.findbugs.BugInstance, long) */ public void setUserTimestamp(BugInstance b, long timestamp) { BugData data = getBugData(b); if (data == null) return; BugDesignation bd = data.getNonnullUserDesignation(); bd.setTimestamp(timestamp); storeUserAnnotation(data, bd); } static final String BUG_NOTE = SystemProperties.getProperty("findbugs.bugnote"); String getBugReportHead(BugInstance b) { StringWriter stringWriter = new StringWriter(); PrintWriter out = new PrintWriter(stringWriter); out.println("Bug report generated from FindBugs"); out.println(b.getMessageWithoutPrefix()); out.println(); ClassAnnotation primaryClass = b.getPrimaryClass(); for (BugAnnotation a : b.getAnnotations()) { if (a == primaryClass) out.println(a); else out.println(" " + a.toString(primaryClass)); } URL link = getSourceLink(b); if (link != null) { out.println(); out.println(sourceFileLinkToolTip + ": " + link); out.println(); } if (BUG_NOTE != null) { out.println(BUG_NOTE); if (POSTMORTEM_NOTE != null && BugRanker.findRank(b) <= POSTMORTEM_RANK && !overallClassificationIsNotAProblem(b)) out.println(POSTMORTEM_NOTE); out.println(); } Collection<String> projects = projectMapping.getProjects(primaryClass.getClassName()); if (projects != null && !projects.isEmpty()) { String projectList = projects.toString(); projectList = projectList.substring(1, projectList.length() - 1); out.println("Possibly part of: " + projectList); out.println(); } out.close(); return stringWriter.toString(); } String getBugPatternExplanation(BugInstance b) { String detailPlainText = b.getBugPattern().getDetailPlainText(); return "Bug pattern explanation:\n" + detailPlainText + "\n\n"; } String getBugPatternExplanationLink(BugInstance b) { return "Bug pattern explanation: http://findbugs.sourceforge.net/bugDescriptions.html#" + b.getBugPattern().getType() + "\n"; } private String getLineTerminatedUserEvaluation(BugInstance b) { UserDesignation designation = getUserDesignation(b); String result; if (designation != UserDesignation.UNCLASSIFIED) result = "Classified as: " + designation.toString() + "\n"; else result = ""; String eval = getUserEvaluation(b).trim(); if (eval.length() > 0) result = result + eval + "\n"; return result; } String getBugReport(BugInstance b) { return getBugReportHead(b) + getBugReportSourceCode(b) + getLineTerminatedUserEvaluation(b) + getBugPatternExplanation(b) + getBugReportTail(b); } String getBugReportShorter(BugInstance b) { return getBugReportHead(b) + getBugReportSourceCode(b) + getLineTerminatedUserEvaluation(b) + getBugPatternExplanationLink(b) + getBugReportTail(b); } String getBugReportAbridged(BugInstance b) { return getBugReportHead(b) + getBugPatternExplanationLink(b) + getBugReportTail(b); } String getBugReportSourceCode(BugInstance b) { if (!MainFrame.isAvailable()) return ""; StringWriter stringWriter = new StringWriter(); PrintWriter out = new PrintWriter(stringWriter); ClassAnnotation primaryClass = b.getPrimaryClass(); int firstLine = Integer.MAX_VALUE; int lastLine = Integer.MIN_VALUE; for (BugAnnotation a : b.getAnnotations()) if (a instanceof SourceLineAnnotation) { SourceLineAnnotation s = (SourceLineAnnotation) a; if (s.getClassName().equals(primaryClass.getClassName()) && s.getStartLine() > 0) { firstLine = Math.min(firstLine, s.getStartLine()); lastLine = Math.max(lastLine, s.getEndLine()); } } SourceLineAnnotation primarySource = primaryClass.getSourceLines(); if (primarySource.isSourceFileKnown() && firstLine >= 1 && firstLine <= lastLine && lastLine - firstLine < 50) { try { SourceFile sourceFile = MainFrame.getInstance().getSourceFinder().findSourceFile(primarySource); BufferedReader in = new BufferedReader(new InputStreamReader(sourceFile.getInputStream())); int lineNumber = 1; String commonWhiteSpace = null; List<SourceLine> source = new ArrayList<SourceLine>(); while (lineNumber <= lastLine + 4) { String txt = in.readLine(); if (txt == null) break; if (lineNumber >= firstLine - 4) { String trimmed = txt.trim(); if (trimmed.length() == 0) { if (lineNumber > lastLine) break; txt = trimmed; } source.add(new SourceLine(lineNumber, txt)); commonWhiteSpace = commonLeadingWhitespace(commonWhiteSpace, txt); } lineNumber++; } in.close(); out.println("\nRelevant source code:"); for(SourceLine s : source) { if (s.text.length() == 0) out.printf("%5d: \n", s.line); else out.printf("%5d: %s\n", s.line, s.text.substring(commonWhiteSpace.length())); } out.println(); } catch (IOException e) { assert true; } out.close(); String result = stringWriter.toString(); return result; } return ""; } String commonLeadingWhitespace(String soFar, String txt) { if (txt.length() == 0) return soFar; if (soFar == null) return txt; soFar = Util.commonPrefix(soFar, txt); for(int i = 0; i < soFar.length(); i++) { if (!Character.isWhitespace(soFar.charAt(i))) return soFar.substring(0,i); } return soFar; } static class SourceLine { public SourceLine(int line, String text) { this.line = line; this.text = text; } final int line; final String text; } String getBugReportTail(BugInstance b) { return "\nFindBugs issue identifier (do not modify or remove): " + b.getInstanceHash(); } static String urlEncode(String s) { try { return URLEncoder.encode(s, "UTF-8"); } catch (UnsupportedEncodingException e) { assert false; return "No utf-8 encoding"; } } @Override public int getNumberReviewers(BugInstance b) { BugData bd = getBugData(b); if (bd == null) return 0; Collection<BugDesignation> uniqueDesignations = bd.getUniqueDesignations(); return uniqueDesignations.size(); } @Override public double getClassificationScore(BugInstance b) { BugData bd = getBugData(b); if (bd == null) return 0; Collection<BugDesignation> uniqueDesignations = bd.getUniqueDesignations(); double total = 0; int count = 0; for(BugDesignation d : uniqueDesignations) { UserDesignation designation = UserDesignation.valueOf(d.getDesignationKey()); if (nonVoting(designation)) continue; total += designation.score(); count++; } return total / count++; } /** * @param designation * @return */ private boolean nonVoting(UserDesignation designation) { return designation == UserDesignation.OBSOLETE_CODE || designation == UserDesignation.NEEDS_STUDY || designation == UserDesignation.UNCLASSIFIED; } @Override public double getPortionObsoleteClassifications(BugInstance b) { BugData bd = getBugData(b); if (bd == null) return 0; int count = 0; Collection<BugDesignation> uniqueDesignations = bd.getUniqueDesignations(); for(BugDesignation d : uniqueDesignations) if (UserDesignation.valueOf(d.getDesignationKey()) == UserDesignation.OBSOLETE_CODE) count++; return ((double)count)/uniqueDesignations.size(); } @Override public double getClassificationVariance(BugInstance b) { BugData bd = getBugData(b); if (bd == null) return 0; Collection<BugDesignation> uniqueDesignations = bd.getUniqueDesignations(); double total = 0; double totalSquares = 0; int count = 0; for(BugDesignation d : uniqueDesignations) { UserDesignation designation = UserDesignation.valueOf(d.getDesignationKey()); if (nonVoting(designation)) continue; int score = designation.score(); total += score; totalSquares += score*score; count++; } double average = total/count; return totalSquares / count - average*average; } @Override public double getClassificationDisagreement(BugInstance b) { BugData bd = getBugData(b); if (bd == null) return 0; Collection<BugDesignation> uniqueDesignations = bd.getUniqueDesignations(); int shouldFix = 0; int dontFix = 0; for(BugDesignation d : uniqueDesignations) { UserDesignation designation = UserDesignation.valueOf(d.getDesignationKey()); if (nonVoting(designation)) continue; int score = designation.score(); if (score > 0) shouldFix++; else dontFix++; } return Math.min(shouldFix, dontFix) / (double) (shouldFix + dontFix); } public Set<String> getReviewers(BugInstance b) { BugData bd = getBugData(b); if (bd == null) return Collections.emptySet(); return bd.getReviewers(); } public boolean isClaimed(BugInstance b) { BugData bd = getBugData(b); if (bd == null) return false; return bd.isClaimed(); } static final int MAX_URL_LENGTH = 1999; private static final String HAS_FILED_BUGS = "has_filed_bugs"; private static final String HAS_CLASSIFIED_ISSUES = "has_classified_issues"; private static boolean firstTimeDoing(String activity) { Preferences prefs = Preferences.userNodeForPackage(DBCloud.class); if (!prefs.getBoolean(activity, false)) { prefs.putBoolean(activity, true); return true; } return false; } private static void alreadyDone(String activity) { Preferences prefs = Preferences.userNodeForPackage(DBCloud.class); prefs.putBoolean(activity, true); } private boolean firstBugRequest = true; static final String POSTMORTEM_NOTE = SystemProperties.getProperty("findbugs.postmortem.note"); static final int POSTMORTEM_RANK = SystemProperties.getInt("findbugs.postmortem.maxRank", 4); static final String BUG_LINK_FORMAT = SystemProperties.getProperty("findbugs.filebug.link"); static final String BUG_LOGIN_LINK = SystemProperties.getProperty("findbugs.filebug.login"); static final String BUG_LOGIN_MSG = SystemProperties.getProperty("findbugs.filebug.loginMsg"); static final String COMPONENT_FOR_BAD_ANALYSIS = SystemProperties.getProperty("findbugs.filebug.badAnalysisComponent"); @Override @CheckForNull public URL getBugLink(BugInstance b) { BugData bd = getBugData(b); String bugNumber = bd.bugLink; BugFilingStatus status = getBugLinkStatus(b); if (status == BugFilingStatus.VIEW_BUG) return getBugViewLink(bugNumber); Connection c = null; try { c = getConnection(); PreparedStatement ps = c .prepareStatement("SELECT bugReportId, whoFiled, whenFiled, status, assignedTo, componentName FROM findbugs_bugreport WHERE hash=?"); ps.setString(1, b.getInstanceHash()); ResultSet rs = ps.executeQuery(); rs = ps.executeQuery(); Timestamp pendingFiledAt = null; while (rs.next()) { int col = 1; String bugReportId = rs.getString(col++); String whoFiled = rs.getString(col++); Timestamp whenFiled = rs.getTimestamp(col++); String statusString = rs.getString(col++); String assignedTo = rs.getString(col++); String componentName = rs.getString(col++); if (bugReportId.equals(PENDING)) { if (!findbugsUser.equals(whoFiled) && !pendingStatusHasExpired(whenFiled.getTime())) pendingFiledAt = whenFiled; continue; } if (bugReportId.equals(NONE)) continue; rs.close(); ps.close(); bd.bugLink = bugReportId; bd.filedBy = whoFiled; bd.bugFiled = whenFiled.getTime(); bd.bugAssignedTo = assignedTo; bd.bugStatus = statusString; bd.bugComponentName = componentName; int answer = getBugCollection().getProject().getGuiCallback().showConfirmDialog( "Sorry, but since the time we last received updates from the database,\n" + "someone else already filed a bug report. Would you like to view the bug report?", "Someone else already filed a bug report", JOptionPane.YES_NO_OPTION); if (answer == JOptionPane.NO_OPTION) return null; return getBugViewLink(bugReportId); } rs.close(); ps.close(); if (pendingFiledAt != null) { bd.bugLink = PENDING; bd.bugFiled = pendingFiledAt.getTime(); getBugCollection().getProject().getGuiCallback().showMessageDialog( "Sorry, but since the time we last received updates from the database,\n" + "someone else already has started a bug report for this issue. "); return null; } // OK, not in database if (status == BugFilingStatus.FILE_BUG) { URL u = getBugFilingLink(b); if (u != null && firstTimeDoing(HAS_FILED_BUGS)) { String bugFilingNote = String.format(SystemProperties.getProperty("findbugs.filebug.note", "")); int response = bugCollection.getProject().getGuiCallback().showConfirmDialog( "This looks like the first time you've filed a bug from this machine. Please:\n" + " * Please check the component the issue is assigned to; we sometimes get it wrong.\n" + " * Try to figure out the right person to assign it to.\n" + " * Provide the information needed to understand the issue.\n" + bugFilingNote + "Note that classifying an issue is distinct from (and lighter weight than) filing a bug.", "Do you want to file a bug report", JOptionPane.YES_NO_OPTION); if (response != JOptionPane.YES_OPTION) return null; } if (u != null) insertPendingRecord(c, bd, System.currentTimeMillis(), findbugsUser); return u; } else { assert status == BugFilingStatus.FILE_AGAIN; alreadyDone(HAS_FILED_BUGS); URL u = getBugFilingLink(b); if (u != null) insertPendingRecord(c, bd, System.currentTimeMillis(), findbugsUser); return u; } } catch (MalformedURLException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { Util.closeSilently(c); } return null; } /** * @param bugNumber * @return * @throws MalformedURLException */ private @CheckForNull URL getBugViewLink(String bugNumber) { String viewLinkPattern = SystemProperties.getProperty("findbugs.viewbug.link"); if (viewLinkPattern == null) return null; firstBugRequest = false; String u = String.format(viewLinkPattern, bugNumber); try { return new URL(u); } catch (MalformedURLException e) { return null; } } /** * @param b * @return * @throws MalformedURLException */ private URL getBugFilingLink(BugInstance b) throws MalformedURLException { { if (BUG_LINK_FORMAT == null) return null; String report = getBugReport(b); String component; if (getUserDesignation(b) == UserDesignation.BAD_ANALYSIS && COMPONENT_FOR_BAD_ANALYSIS != null) component = COMPONENT_FOR_BAD_ANALYSIS; else component = getBugComponent(b.getPrimaryClass().getClassName().replace('.', '/')); String summary = b.getMessageWithoutPrefix() + " in " + b.getPrimaryClass().getSourceFileName(); int maxURLLength = MAX_URL_LENGTH; if (firstBugRequest) { if (BUG_LOGIN_LINK != null && BUG_LOGIN_MSG != null) { URL u = new URL(String.format(BUG_LOGIN_LINK)); if (!bugCollection.getProject().getGuiCallback().showDocument(u)) return null; int r = bugCollection.getProject().getGuiCallback().showConfirmDialog(BUG_LOGIN_MSG, "Logging into bug tracker...", JOptionPane.OK_CANCEL_OPTION); if (r == JOptionPane.CANCEL_OPTION) return null; } else maxURLLength = maxURLLength *2/3; } firstBugRequest = false; String u = String.format(BUG_LINK_FORMAT, component, urlEncode(summary), urlEncode(report)); if (u.length() > MAX_URL_LENGTH) { report = getBugReportShorter(b); u = String.format(BUG_LINK_FORMAT, component, urlEncode(summary), urlEncode(report)); if (u.length() > MAX_URL_LENGTH) { report = getBugReportAbridged(b); u = String.format(BUG_LINK_FORMAT, component, urlEncode(summary), urlEncode(report)); String supplemental = "[Can't squeeze this information into the URL used to prepopulate the bug entry\n" +" please cut and paste into the bug report as appropriate]\n\n" + getBugReportSourceCode(b) + getLineTerminatedUserEvaluation(b) + getBugPatternExplanation(b); bugCollection.getProject().getGuiCallback().displayNonmodelMessage( "Cut and paste as needed into bug entry", supplemental); } } return new URL(u); } } @Override public boolean supportsCloudReports() { return true; } @Override public boolean supportsBugLinks() { return BUG_LINK_FORMAT != null; } @Override public String getCloudReport(BugInstance b) { SimpleDateFormat format = new SimpleDateFormat("MM/dd, yyyy"); StringBuilder builder = new StringBuilder(); BugData bd = getBugData(b); long firstSeen = bd.firstSeen; if (firstSeen < Long.MAX_VALUE) { builder.append(String.format("First seen %s\n", format.format(new Timestamp(firstSeen)))); } I18N i18n = I18N.instance(); boolean canSeeCommentsByOthers = bd.canSeeCommentsByOthers(); if (canSeeCommentsByOthers) { if (bd.bugStatus != null) { builder.append(bd.bugComponentName); if (bd.bugAssignedTo == null) builder.append("\nBug status is " + bd.bugStatus); else builder.append("\nBug assigned to " + bd.bugAssignedTo + ", status is " + bd.bugStatus); builder.append("\n\n"); } } for(BugDesignation d : bd.getUniqueDesignations()) if (findbugsUser.equals(d.getUser())|| canSeeCommentsByOthers ) { builder.append(String.format("%s @ %s: %s\n", d.getUser(), format.format(new Timestamp(d.getTimestamp())), i18n.getUserDesignation(d.getDesignationKey()))); if (d.getAnnotationText().length() > 0) { builder.append(d.getAnnotationText()); builder.append("\n\n"); } } return builder.toString(); } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#storeUserAnnotation(edu.umd.cs.findbugs.BugInstance) */ public void storeUserAnnotation(BugInstance bugInstance) { storeUserAnnotation(getBugData(bugInstance), bugInstance.getNonnullUserDesignation()); updatedIssue(bugInstance); } @Override public boolean supportsSourceLinks() { return sourceFileLinkPattern != null; } @Override public @CheckForNull URL getSourceLink(BugInstance b) { if (sourceFileLinkPattern == null) return null; SourceLineAnnotation src = b.getPrimarySourceLineAnnotation(); String fileName = src.getSourcePath(); int startLine = src.getStartLine(); java.util.regex.Matcher m = sourceFileLinkPattern.matcher(fileName); boolean isMatch = m.matches(); if (isMatch) try { URL link; if (startLine > 0) link = new URL(String.format(sourceFileLinkFormatWithLine, m.group(1), startLine, startLine - 10)); else link = new URL(String.format(sourceFileLinkFormat, m.group(1))); return link; } catch (MalformedURLException e) { AnalysisContext.logError("Error generating source link for " + src, e); } return null; } @Override public String getSourceLinkToolTip(BugInstance b) { return sourceFileLinkToolTip; } @Override public BugFilingStatus getBugLinkStatus(BugInstance b) { BugData bd = getBugData(b); String link = bd.bugLink; if (link == null || link.length() == 0 || link.equals(NONE)) return BugFilingStatus.FILE_BUG; if (link.equals(PENDING)) { if (findbugsUser.equals(bd.filedBy)) return BugFilingStatus.FILE_AGAIN; else { long whenFiled = bd.bugFiled; if (pendingStatusHasExpired(whenFiled)) return BugFilingStatus.FILE_BUG; else return BugFilingStatus.BUG_PENDING; } } try { Integer.parseInt(link); return BugFilingStatus.VIEW_BUG; } catch (RuntimeException e) { assert true; } return BugFilingStatus.NA; } /** * @param whenFiled * @return */ private boolean pendingStatusHasExpired(long whenFiled) { return System.currentTimeMillis() - whenFiled > 60*60*1000L; } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#bugFiled(edu.umd.cs.findbugs.BugInstance, java.lang.Object) */ public void bugFiled(BugInstance b, Object bugLink) { checkForShutdown(); if (bugAlreadyFiled(b)) { BugData bd = getBugData(b.getInstanceHash()); return; } queue.add(new FileBug(b)); updatedStatus(); } String errorMsg; long errorTime = 0; void setErrorMsg(String msg) { errorMsg = msg; errorTime = System.currentTimeMillis(); updatedStatus(); } void clearErrorMsg() { errorMsg = null; updatedStatus(); } @Override public String getStatusMsg() { if (errorMsg != null) { if (errorTime + 2 * 60 * 1000 > System.currentTimeMillis()) { errorMsg = null; } else return errorMsg +"; " + getStatusMsg0(); } return getStatusMsg0(); } public String getStatusMsg0() { SimpleDateFormat format = new SimpleDateFormat("h:mm a"); int numToSync = queue.size(); if (numToSync > 0) return String.format("%d remain to be synchronized", numToSync); else if (resync != null && resync.after(lastUpdate)) return String.format("%d updates received from db at %s", resyncCount, format.format(resync)); else if (updatesSentToDatabase == 0) return String.format("%d issues synchronized with database", idMap.size()); else return String.format("%d classifications/bug filings sent to db, last updated at %s", updatesSentToDatabase, format.format(lastUpdate)); } @Override public void printCloudSummary(PrintWriter w, Iterable<BugInstance> bugs, String[] packagePrefixes) { Multiset<String> evaluations = new Multiset<String>(); Multiset<String> designations = new Multiset<String>(); Multiset<String> bugStatus = new Multiset<String>(); int issuesWithThisManyReviews [] = new int[100]; I18N i18n = I18N.instance(); Set<String> hashCodes = new HashSet<String>(); for(BugInstance b : bugs) { hashCodes.add(b.getInstanceHash()); } int packageCount = 0; int classCount = 0; int ncss = 0; ProjectStats projectStats = bugCollection.getProjectStats(); for(PackageStats ps : projectStats.getPackageStats()) if (ViewFilter.matchedPrefixes(packagePrefixes, ps.getPackageName()) && ps.size() > 0 && ps.getNumClasses() > 0) { packageCount++; ncss += ps.size(); classCount += ps.getNumClasses(); } if (packagePrefixes != null && packagePrefixes.length > 0) { String lst = Arrays.asList(packagePrefixes).toString(); w.println("Code analyzed in " + lst.substring(1, lst.length()-1)); } else w.println("Code analyzed"); if (classCount == 0) w.println("No classes were analyzed"); else w.printf("%,7d packages\n%,7d classes\n%,7d thousands of lines of non-commenting source statements\n", packageCount, classCount, (ncss+999)/1000); w.println(); int count = 0; int notInCloud = 0; for(String hash : hashCodes) { BugData bd = instanceMap.get(hash); if (bd == null) { notInCloud++; continue; } count++; HashSet<String> reviewers = new HashSet<String>(); if (bd.bugStatus != null) bugStatus.add(bd.bugStatus); for(BugDesignation d : bd.designations) if (reviewers.add(d.getUser())) { evaluations.add(d.getUser()); designations.add(i18n.getUserDesignation(d.getDesignationKey())); } int numReviews = Math.min( reviewers.size(), issuesWithThisManyReviews.length -1); issuesWithThisManyReviews[numReviews]++; } if (count == 0) { w.printf("None of the %d issues in the current view are in the cloud\n\n", notInCloud); return; } if (notInCloud == 0) { w.printf("Summary for %d issues that are in the current view\n\n", count); }else { w.printf("Summary for %d issues that are in the current view and cloud (%d not in cloud)\n\n", count, notInCloud); } w.println("People who have performed the most reviews"); printLeaderBoard(w, evaluations, 9, findbugsUser, true, "reviewer"); w.println("\nDistribution of evaluations"); printLeaderBoard(w, designations, 100, " --- ", false, "designation"); w.println("\nDistribution of bug status"); printLeaderBoard(w, bugStatus, 100, " --- ", false, "status of filed bug"); w.println("\nDistribution of number of reviews"); for(int i = 0; i < issuesWithThisManyReviews.length; i++) if (issuesWithThisManyReviews[i] > 0) { w.printf("%4d with %3d review", issuesWithThisManyReviews[i], i); if (i != 1) w.print("s"); w.println(); } } /** * @param w * @param evaluations * @param listRank TODO * @param title TODO */ static void printLeaderBoard(PrintWriter w, Multiset<String> evaluations, int maxRows, String alwaysPrint, boolean listRank, String title) { if (listRank) w.printf("%3s %4s %s\n", "rnk", "num", title); else w.printf("%4s %s\n", "num", title); printLeaderBoard2(w, evaluations, maxRows, alwaysPrint, listRank ? "%3d %4d %s\n" : "%2$4d %3$s\n" , title); } static final String LEADERBOARD_BLACKLIST = SystemProperties.getProperty("findbugs.leaderboard.blacklist"); static final Pattern LEADERBOARD_BLACKLIST_PATTERN; static { Pattern p = null; if (LEADERBOARD_BLACKLIST != null) try { p = Pattern.compile(LEADERBOARD_BLACKLIST.replace(',', '|')); } catch (Exception e) { assert true; } LEADERBOARD_BLACKLIST_PATTERN = p; } /** * @param w * @param evaluations * @param maxRows * @param alwaysPrint * @param listRank * @param title */ static void printLeaderBoard2(PrintWriter w, Multiset<String> evaluations, int maxRows, String alwaysPrint, String format, String title) { int row = 1; int position = 0; int previousScore = -1; boolean foundAlwaysPrint = false; for(Map.Entry<String,Integer> e : evaluations.entriesInDecreasingFrequency()) { int num = e.getValue(); if (num != previousScore) { position = row; previousScore = num; } String key = e.getKey(); if (LEADERBOARD_BLACKLIST_PATTERN != null && LEADERBOARD_BLACKLIST_PATTERN.matcher(key).matches()) continue; boolean shouldAlwaysPrint = key.equals(alwaysPrint); if (row <= maxRows || shouldAlwaysPrint) w.printf(format, position, num, key); if (shouldAlwaysPrint) foundAlwaysPrint = true; row++; if (row >= maxRows) { if (alwaysPrint == null) break; if (foundAlwaysPrint) { w.printf("Total of %d %ss\n", evaluations.numKeys(), title); break; } } } } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#getIWillFix(edu.umd.cs.findbugs.BugInstance) */ @Override public boolean getIWillFix(BugInstance b) { if (super.getIWillFix(b)) return true; BugData bd = getBugData(b); return bd != null && findbugsUser.equals(bd.bugAssignedTo); } public boolean getBugIsUnassigned(BugInstance b) { BugData bd = getBugData(b); return bd != null && bd.inDatabase && getBugLinkStatus(b) == BugFilingStatus.VIEW_BUG && ("NEW".equals(bd.bugStatus) || bd.bugAssignedTo == null || bd.bugAssignedTo.length() == 0); } public boolean getWillNotBeFixed(BugInstance b) { BugData bd = getBugData(b); return bd != null && bd.inDatabase && getBugLinkStatus(b) == BugFilingStatus.VIEW_BUG && "WILL_NOT_FIX".equals(bd.bugStatus); } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#supportsCloudSummaries() */ @Override public boolean supportsCloudSummaries() { return true; } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#canStoreUserAnnotation(edu.umd.cs.findbugs.BugInstance) */ @Override public boolean canStoreUserAnnotation(BugInstance bugInstance) { return !skipBug(bugInstance); } @Override public @CheckForNull String claimedBy(BugInstance b) { BugData bd = getBugData(b); if (bd == null) return null; for(BugDesignation designation : bd.getUniqueDesignations()) { if ("I_WILL_FIX".equals(designation.getDesignationKey())) return designation.getUser(); } return null; } }
findbugs/src/java/edu/umd/cs/findbugs/cloud/DBCloud.java
/* * FindBugs - Find Bugs in Java programs * Copyright (C) 2003-2008 University of Maryland * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.umd.cs.findbugs.cloud; import java.awt.GraphicsEnvironment; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.Timer; import java.util.TimerTask; import java.util.TreeSet; import java.util.concurrent.CountDownLatch; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.prefs.Preferences; import java.util.regex.Pattern; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import javax.swing.JOptionPane; import edu.umd.cs.findbugs.BugAnnotation; import edu.umd.cs.findbugs.BugCollection; import edu.umd.cs.findbugs.BugDesignation; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugRanker; import edu.umd.cs.findbugs.ClassAnnotation; import edu.umd.cs.findbugs.FindBugs; import edu.umd.cs.findbugs.I18N; import edu.umd.cs.findbugs.PackageStats; import edu.umd.cs.findbugs.PluginLoader; import edu.umd.cs.findbugs.ProjectPackagePrefixes; import edu.umd.cs.findbugs.ProjectStats; import edu.umd.cs.findbugs.SortedBugCollection; import edu.umd.cs.findbugs.SourceLineAnnotation; import edu.umd.cs.findbugs.StartTime; import edu.umd.cs.findbugs.SystemProperties; import edu.umd.cs.findbugs.Version; import edu.umd.cs.findbugs.ba.AnalysisContext; import edu.umd.cs.findbugs.ba.SourceFile; import edu.umd.cs.findbugs.gui2.MainFrame; import edu.umd.cs.findbugs.gui2.ViewFilter; import edu.umd.cs.findbugs.internalAnnotations.SlashedClassName; import edu.umd.cs.findbugs.util.Multiset; import edu.umd.cs.findbugs.util.Util; /** * @author pwilliam */ public class DBCloud extends AbstractCloud { static final boolean THROW_EXCEPTION_IF_CANT_CONNECT = false; /** * */ private static final String USER_NAME = "user.name"; Mode mode = Mode.COMMUNAL; public Mode getMode() { return mode; } public void setMode(Mode mode) { this.mode = mode; } class BugData { final String instanceHash; public BugData(String instanceHash) { this.instanceHash = instanceHash; } int id; boolean inDatabase; long firstSeen; String bugLink = NONE; String filedBy; String bugStatus; String bugAssignedTo; String bugComponentName; long bugFiled = Long.MAX_VALUE; SortedSet<BugDesignation> designations = new TreeSet<BugDesignation>(); Collection<BugInstance> bugs = new LinkedHashSet<BugInstance>(); long lastSeen; @CheckForNull BugDesignation getPrimaryDesignation() { for (BugDesignation bd : designations) if (findbugsUser.equals(bd.getUser())) return bd; return null; } @CheckForNull BugDesignation getUserDesignation() { for(BugDesignation d : designations) if (findbugsUser.equals(d.getUser())) return new BugDesignation(d); return null; } Collection<BugDesignation> getUniqueDesignations() { if (designations.isEmpty()) return Collections.emptyList(); HashSet<String> reviewers = new HashSet<String>(); ArrayList<BugDesignation> result = new ArrayList<BugDesignation>(designations.size()); for(BugDesignation d : designations) if (reviewers.add(d.getUser())) result.add(d); return result; } Set<String> getReviewers() { HashSet<String> reviewers = new HashSet<String>(); for(BugDesignation bd : designations) reviewers.add(bd.getUser()); reviewers.remove(""); reviewers.remove(null); return reviewers; } boolean isClaimed() { for(BugDesignation bd : getUniqueDesignations()) { if (bd.getDesignationKey().equals(UserDesignation.I_WILL_FIX.name())) return true; } return false; } BugDesignation getNonnullUserDesignation() { BugDesignation d = getUserDesignation(); if (d != null) return d; d = new BugDesignation(UserDesignation.UNCLASSIFIED.name(), System.currentTimeMillis(), "", findbugsUser); return d; } public boolean canSeeCommentsByOthers() { switch(mode) { case SECRET: return false; case COMMUNAL : return true; case VOTING : return hasVoted(); } throw new IllegalStateException(); } public boolean hasVoted() { for(BugDesignation bd : designations) if (findbugsUser.equals(bd.getUser())) return true; return false; } } int updatesSentToDatabase; Date lastUpdate = new Date(); Date resync; Date attemptedResync; int resyncCount; Map<String, BugData> instanceMap = new HashMap<String, BugData>(); Map<Integer, BugData> idMap = new HashMap<Integer, BugData>(); IdentityHashMap<BugDesignation, Integer> bugDesignationId = new IdentityHashMap<BugDesignation, Integer>(); BugData getBugData(String instanceHash) { BugData bd = instanceMap.get(instanceHash); if (bd == null) { bd = new BugData(instanceHash); instanceMap.put(instanceHash, bd); } return bd; } BugData getBugData(BugInstance bug) { try { initialSyncDone.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } BugData bugData = getBugData(bug.getInstanceHash()); bugData.bugs.add(bug); return bugData; } void loadDatabaseInfo(String hash, int id, long firstSeen, long lastSeen) { BugData bd = instanceMap.get(hash); if (bd == null) return; if (idMap.containsKey(id)) { assert bd == idMap.get(id); assert bd.id == id; assert bd.firstSeen == firstSeen; } else { bd.id = id; bd.firstSeen = firstSeen; bd.lastSeen = lastSeen; bd.inDatabase = true; idMap.put(id, bd); } } DBCloud(BugCollection bugs) { super(bugs); } static final Pattern FORBIDDEN_PACKAGE_PREFIXES = Pattern.compile(SystemProperties.getProperty("findbugs.forbiddenPackagePrefixes", " none ").replace(',','|')); static final boolean PROMPT_FOR_USER_NAME = SystemProperties.getBoolean("findbugs.db.promptForUserName", false); int sessionId = -1; final CountDownLatch initialSyncDone = new CountDownLatch(1); public void bugsPopulated() { queue.add(new PopulateBugs(true)); } private static final long LAST_SEEN_UPDATE_WINDOW = TimeUnit.MILLISECONDS.convert(7*24*3600, TimeUnit.SECONDS); long boundDuration(long milliseconds) { if (milliseconds < 0) return 0; if (milliseconds > 1000*1000) return 1000*1000; return milliseconds; } static boolean invocationRecorded; class PopulateBugs implements Update { final boolean performFullLoad; PopulateBugs(boolean performFullLoad) { this.performFullLoad = performFullLoad; } public void execute(DatabaseSyncTask t) throws SQLException { if (startShutdown) return; String commonPrefix = null; int updates = 0; if (performFullLoad) { for (BugInstance b : bugCollection.getCollection()) if (!skipBug(b)) { commonPrefix = Util.commonPrefix(commonPrefix, b.getPrimaryClass().getClassName()); getBugData(b.getInstanceHash()).bugs.add(b); } if (commonPrefix == null) commonPrefix = "<no bugs>"; else if (commonPrefix.length() > 128) commonPrefix = commonPrefix.substring(0, 128); } try { long startTime = System.currentTimeMillis(); Connection c = getConnection(); PreparedStatement ps; ResultSet rs; if (performFullLoad) { ps = c.prepareStatement("SELECT id, hash, firstSeen, lastSeen FROM findbugs_issue"); rs = ps.executeQuery(); while (rs.next()) { int col = 1; int id = rs.getInt(col++); String hash = rs.getString(col++); Timestamp firstSeen = rs.getTimestamp(col++); Timestamp lastSeen = rs.getTimestamp(col++); loadDatabaseInfo(hash, id, firstSeen.getTime(), lastSeen.getTime()); } rs.close(); ps.close(); } if (startShutdown) return; ps = c.prepareStatement("SELECT id, issueId, who, designation, comment, time FROM findbugs_evaluation"); rs = ps.executeQuery(); while (rs.next()) { int col = 1; int id = rs.getInt(col++); int issueId = rs.getInt(col++); String who = rs.getString(col++); String designation = rs.getString(col++); String comment = rs.getString(col++); Timestamp when = rs.getTimestamp(col++); BugData data = idMap.get(issueId); if (data != null) { BugDesignation bd = new BugDesignation(designation, when.getTime(), comment, who); if (data.designations.add(bd)) { bugDesignationId.put(bd, id); updates++; for(BugInstance bug : data.bugs) { updatedIssue(bug); } } } } rs.close(); ps.close(); if (startShutdown) return; ps = c.prepareStatement("SELECT hash, bugReportId, whoFiled, whenFiled, status, assignedTo, componentName FROM findbugs_bugreport"); rs = ps.executeQuery(); while (rs.next()) { int col = 1; String hash = rs.getString(col++); String bugReportId = rs.getString(col++); String whoFiled = rs.getString(col++); Timestamp whenFiled = rs.getTimestamp(col++); String status = rs.getString(col++); String assignedTo = rs.getString(col++); String componentName = rs.getString(col++); BugData data = instanceMap.get(hash); if (data != null) { if (Util.nullSafeEquals(data.bugLink, bugReportId) && Util.nullSafeEquals(data.filedBy, whoFiled) && data.bugFiled == whenFiled.getTime() && Util.nullSafeEquals(data.bugAssignedTo, assignedTo) && Util.nullSafeEquals(data.bugStatus, status) && Util.nullSafeEquals(data.bugComponentName, componentName)) continue; data.bugLink = bugReportId; data.filedBy = whoFiled; data.bugFiled = whenFiled.getTime(); data.bugAssignedTo = assignedTo; data.bugStatus = status; data.bugComponentName = componentName; updates++; for(BugInstance bug : data.bugs) { updatedIssue(bug); } } } rs.close(); ps.close(); if (startShutdown) return; if (!invocationRecorded) { long jvmStartTime = StartTime.START_TIME - StartTime.VM_START_TIME; SortedBugCollection sbc = (SortedBugCollection) bugCollection; long findbugsStartTime = sbc.getTimeStartedLoading() - StartTime.START_TIME; URL findbugsURL = PluginLoader.getCoreResource("findbugs.xml"); String loadURL = findbugsURL == null ? "" : findbugsURL.toString(); long initialLoadTime = sbc.getTimeFinishedLoading() - sbc.getTimeStartedLoading(); long lostTime = startTime - sbc.getTimeStartedLoading(); long initialSyncTime = System.currentTimeMillis() - sbc.getTimeFinishedLoading(); String os = SystemProperties.getProperty("os.name", ""); String osVersion = SystemProperties.getProperty("os.version"); String jvmVersion = SystemProperties.getProperty("java.runtime.version"); if (osVersion != null) os = os +" " + osVersion; PreparedStatement insertSession = c .prepareStatement( "INSERT INTO findbugs_invocation (who, entryPoint, dataSource, fbVersion, os, jvmVersion, jvmLoadTime, findbugsLoadTime, analysisLoadTime, initialSyncTime, numIssues, startTime, commonPrefix)" + " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS); Timestamp now = new Timestamp(startTime); int col = 1; insertSession.setString(col++, findbugsUser); insertSession.setString(col++, limitToMaxLength(loadURL, 128)); insertSession.setString(col++, limitToMaxLength(sbc.getDataSource(), 128)); insertSession.setString(col++, Version.RELEASE); insertSession.setString(col++, limitToMaxLength(os,128)); insertSession.setString(col++, limitToMaxLength(jvmVersion,64)); insertSession.setLong(col++, boundDuration(jvmStartTime)); insertSession.setLong(col++, boundDuration(findbugsStartTime)); insertSession.setLong(col++, boundDuration(initialLoadTime)); insertSession.setLong(col++, boundDuration(initialSyncTime)); insertSession.setInt(col++, bugCollection.getCollection().size()); insertSession.setTimestamp(col++, now); insertSession.setString(col++, commonPrefix); int rowCount = insertSession.executeUpdate(); rs = insertSession.getGeneratedKeys(); if (rs.next()) { sessionId = rs.getInt(1); } insertSession.close(); rs.close(); invocationRecorded = true; } c.close(); } catch (Exception e) { e.printStackTrace(); displayMessage("problem bulk loading database", e); } if (startShutdown) return; if (!performFullLoad) { attemptedResync = new Date(); if (updates > 0) { resync = attemptedResync; resyncCount = updates; } } else { long stillPresentAt = bugCollection.getTimestamp(); for (BugInstance b : bugCollection.getCollection()) if (!skipBug(b)) { BugData bd = getBugData(b.getInstanceHash()); if (!bd.inDatabase) { storeNewBug(b, stillPresentAt); } else { long firstVersion = b.getFirstVersion(); long firstSeen = bugCollection.getAppVersionFromSequenceNumber(firstVersion).getTimestamp(); if (FindBugs.validTimestamp(firstSeen) && (firstSeen < bd.firstSeen || !FindBugs.validTimestamp(bd.firstSeen))) { bd.firstSeen = firstSeen; storeFirstSeen(bd); } else if (FindBugs.validTimestamp(stillPresentAt) && stillPresentAt > bd.lastSeen + LAST_SEEN_UPDATE_WINDOW) { storeLastSeen(bd, stillPresentAt); } BugDesignation designation = bd.getPrimaryDesignation(); if (designation != null) b.setUserDesignation(new BugDesignation(designation)); } } initialSyncDone.countDown(); assert !scheduled; if (startShutdown) return; long delay = 10*60*1000; // 10 minutes if (!scheduled) { try { resyncTimer.schedule(new TimerTask() { @Override public void run() { if (attemptedResync == null || lastUpdate.after(attemptedResync) || numSkipped++ > 6) { numSkipped = 0; queue.add(new PopulateBugs(false)); } }}, delay, delay); } catch (Exception e) { AnalysisContext.logError("Error scheduling resync", e); } } scheduled = true; } updatedStatus(); } } boolean scheduled = false; int numSkipped = 0; private static String limitToMaxLength(String s, int maxLength) { if (s.length() <= maxLength) return s; return s.substring(0, maxLength); } private String getProperty(String propertyName) { return SystemProperties.getProperty("findbugs.jdbc." + propertyName); } final static int MAX_DB_RANK = SystemProperties.getInt("findbugs.db.maxrank", 12); String url, dbUser, dbPassword, findbugsUser, dbName; @CheckForNull Pattern sourceFileLinkPattern; String sourceFileLinkFormat; String sourceFileLinkFormatWithLine; String sourceFileLinkToolTip; ProjectPackagePrefixes projectMapping = new ProjectPackagePrefixes(); Map<String,String> prefixBugComponentMapping = new HashMap<String,String>(); Connection getConnection() throws SQLException { return DriverManager.getConnection(url, dbUser, dbPassword); } public boolean initialize() { String mode = getProperty("votingmode"); if (mode != null) setMode(Mode.valueOf(mode.toUpperCase())); String sp = SystemProperties.getProperty("findbugs.sourcelink.pattern"); String sf = SystemProperties.getProperty("findbugs.sourcelink.format"); String sfwl = SystemProperties.getProperty("findbugs.sourcelink.formatWithLine"); String stt = SystemProperties.getProperty("findbugs.sourcelink.tooltip"); if (sp != null && sf != null) { try { this.sourceFileLinkPattern = Pattern.compile(sp); this.sourceFileLinkFormat = sf; this.sourceFileLinkToolTip = stt; this.sourceFileLinkFormatWithLine = sfwl; } catch (RuntimeException e) { AnalysisContext.logError("Could not compile pattern " + sp, e); if (THROW_EXCEPTION_IF_CANT_CONNECT) throw e; } } String sqlDriver = getProperty("dbDriver"); url = getProperty("dbUrl"); dbName = getProperty("dbName"); dbUser = getProperty("dbUser"); dbPassword = getProperty("dbPassword"); findbugsUser = getProperty("findbugsUser"); if (sqlDriver == null || dbUser == null || url == null || dbPassword == null) { if (THROW_EXCEPTION_IF_CANT_CONNECT) throw new RuntimeException("Unable to load database properties"); return false; } if (findbugsUser == null) { if (PROMPT_FOR_USER_NAME) { Preferences prefs = Preferences.userNodeForPackage(DBCloud.class); findbugsUser = prefs.get(USER_NAME, null); findbugsUser = bugCollection.getProject().getGuiCallback().showQuestionDialog( "Name/handle/email for recording your evaluations?\n" + "(sorry, no authentication or confidentiality currently provided)", "Name for recording your evaluations", findbugsUser == null ? "" : findbugsUser); if (findbugsUser != null) prefs.put(USER_NAME, findbugsUser); } else if (findbugsUser == null) findbugsUser = System.getProperty(USER_NAME, ""); if (findbugsUser == null) { if (THROW_EXCEPTION_IF_CANT_CONNECT) throw new RuntimeException("Unable to get reviewer user name for database"); return false; } } loadBugComponents(); try { Class.forName(sqlDriver); Connection c = getConnection(); Statement stmt = c.createStatement(); ResultSet rs = stmt.executeQuery("SELECT COUNT(*) from findbugs_issue"); boolean result = false; if (rs.next()) { int count = rs.getInt(1); result = true; } rs.close(); stmt.close(); c.close(); if (result) { runnerThread.setDaemon(true); runnerThread.start(); return true; } else if (THROW_EXCEPTION_IF_CANT_CONNECT) { throw new RuntimeException("Unable to get database results"); } else return false; } catch (RuntimeException e) { displayMessage("Unable to connect to " + dbName, e); if (THROW_EXCEPTION_IF_CANT_CONNECT) throw e; return false; } catch (Exception e) { displayMessage("Unable to connect to " + dbName, e); if (THROW_EXCEPTION_IF_CANT_CONNECT) throw new RuntimeException("Unable to connect to database", e); return false; } } private String getBugComponent(@SlashedClassName String className) { int longestMatch = -1; String result = null; for(Map.Entry<String,String> e : prefixBugComponentMapping.entrySet()) { String key = e.getKey(); if (className.startsWith(key) && longestMatch < key.length()) { longestMatch = key.length(); result = e.getValue(); } } return result; } private void loadBugComponents(){ try { URL u = PluginLoader.getCoreResource("bugComponents.properties"); if (u != null) { BufferedReader in = new BufferedReader(new InputStreamReader(u.openStream())); while(true) { String s = in.readLine(); if (s == null) break; if (s.trim().length() == 0) continue; int x = s.indexOf(' '); if (x == -1) { if (!prefixBugComponentMapping.containsKey("")) prefixBugComponentMapping.put("", s); } else { String prefix = s.substring(x+1); if (!prefixBugComponentMapping.containsKey(prefix)) prefixBugComponentMapping.put(prefix, s.substring(0,x)); } } in.close(); } } catch (IOException e) { AnalysisContext.logError("Unable to load bug component properties", e); } } final LinkedBlockingQueue<Update> queue = new LinkedBlockingQueue<Update>(); volatile boolean shutdown = false; volatile boolean startShutdown = false; final DatabaseSyncTask runner = new DatabaseSyncTask(); final Thread runnerThread = new Thread(runner, "Database synchronization thread"); final Timer resyncTimer = new Timer("Resync scheduler", true); @Override public void shutdown() { try { startShutdown = true; resyncTimer.cancel(); queue.add(new ShutdownTask()); try { Connection c = getConnection(); PreparedStatement setEndTime = c.prepareStatement("UPDATE findbugs_invocation SET endTime = ? WHERE id = ?"); Timestamp date = new Timestamp(System.currentTimeMillis()); int col = 1; setEndTime.setTimestamp(col++, date); setEndTime.setInt(col++, sessionId); setEndTime.execute(); setEndTime.close(); c.close(); } catch (Throwable e) { // we're in shutdown mode, not going to complain assert true; } if (!queue.isEmpty() && runnerThread.isAlive()) { setErrorMsg("waiting for synchronization to complete before shutdown"); for (int i = 0; i < 100; i++) { if (queue.isEmpty() || !runnerThread.isAlive()) break; try { Thread.sleep(30); } catch (InterruptedException e) { break; } } } } finally { shutdown = true; runnerThread.interrupt(); } } private RuntimeException shutdownException = new RuntimeException("DBCloud shutdown"); private void checkForShutdown() { if (!shutdown) return; IllegalStateException e = new IllegalStateException("DBCloud has already been shutdown"); e.initCause(shutdownException); throw e; } public void storeNewBug(BugInstance bug, long analysisTime) { checkForShutdown(); queue.add(new StoreNewBug(bug, analysisTime)); } public void storeFirstSeen(final BugData bd) { checkForShutdown(); queue.add(new Update(){ public void execute(DatabaseSyncTask t) throws SQLException { t.storeFirstSeen(bd); }}); } public void storeLastSeen(final BugData bd, final long timestamp) { checkForShutdown(); queue.add(new Update(){ public void execute(DatabaseSyncTask t) throws SQLException { t.storeLastSeen(bd, timestamp); }}); } public void storeUserAnnotation(BugData data, BugDesignation bd) { checkForShutdown(); queue.add(new StoreUserAnnotation(data, bd)); updatedStatus(); if (firstTimeDoing(HAS_CLASSIFIED_ISSUES)) { String msg = "Classification and comments have been sent to database.\n" + "You'll only see this message the first time your classifcations/comments are sent\n" + "to the database."; if (mode == Mode.VOTING) msg += "\nOnce you've classified an issue, you can see how others have classified it."; msg += "\nYour classification and comments are independent from filing a bug using an external\n" + "bug reporting system."; bugCollection.getProject().getGuiCallback().showMessageDialog(msg); } } private static final String HAS_SKIPPED_BUG = "has_skipped_bugs"; private boolean skipBug(BugInstance bug) { boolean result = bug.getBugPattern().getCategory().equals("NOISE") || bug.isDead() || BugRanker.findRank(bug) > MAX_DB_RANK; if (result && firstTimeDoing(HAS_SKIPPED_BUG)) { bugCollection.getProject().getGuiCallback().showMessageDialog( "To limit database load, some issues are not persisted to database.\n" + "For example, issues with rank greater than " + MAX_DB_RANK + " are not stored in the db.\n" + "One of more of the issues you are reviewing will not be persisted,\n" + "and you will not be able to record an evalution of those issues.\n" + "As we scale up the database, we hope to relax these restrictions"); } return result; } public static final String PENDING = "-- pending --"; public static final String NONE = "none"; class DatabaseSyncTask implements Runnable { int handled; Connection c; public void establishConnection() throws SQLException { if (c != null) return; c = getConnection(); } public void closeConnection() throws SQLException { if (c == null) return; c.close(); c = null; } public void run() { try { while (!shutdown) { Update u = queue.poll(10, TimeUnit.SECONDS); if (u == null) { closeConnection(); continue; } establishConnection(); u.execute(this); if ((handled++) % 100 == 0 || queue.isEmpty()) { updatedStatus(); } } } catch (DatabaseSyncShutdownException e) { assert true; } catch (RuntimeException e) { displayMessage("Runtime exception; database connection shutdown", e); } catch (SQLException e) { displayMessage("SQL exception; database connection shutdown", e); } catch (InterruptedException e) { assert true; } try { closeConnection(); } catch (SQLException e) { } } public void newEvaluation(BugData data, BugDesignation bd) { if (!data.inDatabase) return; try { data.designations.add(bd); if (bd.getUser() == null) bd.setUser(findbugsUser); if (bd.getAnnotationText() == null) bd.setAnnotationText(""); PreparedStatement insertEvaluation = c.prepareStatement("INSERT INTO findbugs_evaluation (issueId, who, designation, comment, time) VALUES (?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS); Timestamp date = new Timestamp(bd.getTimestamp()); int col = 1; insertEvaluation.setInt(col++, data.id); insertEvaluation.setString(col++, bd.getUser()); insertEvaluation.setString(col++, bd.getDesignationKey()); insertEvaluation.setString(col++, bd.getAnnotationText()); insertEvaluation.setTimestamp(col++, date); insertEvaluation.executeUpdate(); ResultSet rs = insertEvaluation.getGeneratedKeys(); if (rs.next()) { int id = rs.getInt(1); bugDesignationId.put(bd, id); } rs.close(); } catch (Exception e) { displayMessage("Problems looking up user annotations", e); } lastUpdate = new Date(); updatesSentToDatabase++; } public void newBug(BugInstance b) { try { BugData bug = getBugData(b.getInstanceHash()); if (bug.inDatabase) return; PreparedStatement insertBugData = c.prepareStatement("INSERT INTO findbugs_issue (firstSeen, lastSeen, hash, bugPattern, priority, primaryClass) VALUES (?,?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS); int col = 1; insertBugData.setTimestamp(col++, new Timestamp(bug.firstSeen)); insertBugData.setTimestamp(col++, new Timestamp(bug.lastSeen)); insertBugData.setString(col++, bug.instanceHash); insertBugData.setString(col++, b.getBugPattern().getType()); insertBugData.setInt(col++, b.getPriority()); insertBugData.setString(col++, b.getPrimaryClass().getClassName()); insertBugData.executeUpdate(); ResultSet rs = insertBugData.getGeneratedKeys(); if (rs.next()) { bug.id = rs.getInt(1); bug.inDatabase = true; } rs.close(); insertBugData.close(); } catch (Exception e) { displayMessage("Problems looking up user annotations", e); } } public void storeFirstSeen(BugData bug) { try { PreparedStatement insertBugData = c.prepareStatement("UPDATE findbugs_issue SET firstSeen = ? WHERE id = ?"); Timestamp date = new Timestamp(bug.firstSeen); int col = 1; insertBugData.setTimestamp(col++, date); insertBugData.setInt(col++, bug.id); insertBugData.executeUpdate(); insertBugData.close(); } catch (Exception e) { displayMessage("Problems looking up user annotations", e); } } public void storeLastSeen(BugData bug, long timestamp) { try { PreparedStatement insertBugData = c.prepareStatement("UPDATE findbugs_issue SET lastSeen = ? WHERE id = ?"); Timestamp date = new Timestamp(timestamp); int col = 1; insertBugData.setTimestamp(col++, date); insertBugData.setInt(col++, bug.id); insertBugData.executeUpdate(); insertBugData.close(); } catch (Exception e) { displayMessage("Problems looking up user annotations", e); } } /** * @param bd */ public void fileBug(BugData bug) { try { insertPendingRecord(c, bug, bug.bugFiled, bug.filedBy); } catch (Exception e) { displayMessage("Problem filing bug", e); } lastUpdate = new Date(); updatesSentToDatabase++; } } /** * @param bug * @return * @throws SQLException */ private void insertPendingRecord(Connection c, BugData bug, long when, String who) throws SQLException { int count; int pendingId = -1; PreparedStatement query = c .prepareStatement("SELECT id, bugReportId, whoFiled, whenFiled FROM findbugs_bugreport where hash=?"); query.setString(1, bug.instanceHash); ResultSet rs = query.executeQuery(); boolean needsUpdate = false; while (rs.next()) { int col = 1; int id = rs.getInt(col++); String bugReportId = rs.getString(col++); String whoFiled = rs.getString(col++); Timestamp whenFiled = rs.getTimestamp(col++); if (!bugReportId.equals(PENDING) || !who.equals(whoFiled) && !pendingStatusHasExpired(whenFiled.getTime())) { rs.close(); query.close(); throw new IllegalArgumentException(whoFiled + " already filed bug report " + bugReportId + " for " + bug.instanceHash); } pendingId = id; needsUpdate = !who.equals(whoFiled); } rs.close(); query.close(); if (pendingId == -1) { PreparedStatement insert = c .prepareStatement("INSERT INTO findbugs_bugreport (hash, bugReportId, whoFiled, whenFiled)" + " VALUES (?, ?, ?, ?)"); Timestamp date = new Timestamp(when); int col = 1; insert.setString(col++, bug.instanceHash); insert.setString(col++, PENDING); insert.setString(col++, who); insert.setTimestamp(col++, date); count = insert.executeUpdate(); insert.close(); } else if (needsUpdate) { PreparedStatement updateBug = c .prepareStatement("UPDATE findbugs_bugreport SET whoFiled = ? and whenFiled = ? WHERE id = ?"); int col = 1; updateBug.setString(col++, bug.filedBy); updateBug.setTimestamp(col++, new Timestamp(bug.bugFiled)); updateBug.setInt(col++, pendingId); count = updateBug.executeUpdate(); updateBug.close(); } } static interface Update { void execute(DatabaseSyncTask t) throws SQLException; } static class ShutdownTask implements Update { public void execute(DatabaseSyncTask t) { throw new DatabaseSyncShutdownException(); } } static class DatabaseSyncShutdownException extends RuntimeException { } boolean bugAlreadyFiled(BugInstance b) { BugData bd = getBugData(b.getInstanceHash()); if (bd == null || !bd.inDatabase) throw new IllegalArgumentException(); return bd.bugLink != null && !bd.bugLink.equals(NONE) && !bd.bugLink.equals(PENDING); } class FileBug implements Update { public FileBug(BugInstance bug) { this.bd = getBugData(bug.getInstanceHash()); if (bd == null || !bd.inDatabase) throw new IllegalArgumentException(); bd.bugFiled = System.currentTimeMillis(); bd.bugLink = PENDING; bd.filedBy = findbugsUser; } final BugData bd; public void execute(DatabaseSyncTask t) throws SQLException { t.fileBug(bd); } } class StoreNewBug implements Update { public StoreNewBug(BugInstance bug, long analysisTime) { this.bug = bug; this.analysisTime = analysisTime; } final BugInstance bug; final long analysisTime; public void execute(DatabaseSyncTask t) throws SQLException { BugData data = getBugData(bug.getInstanceHash()); if (data.lastSeen < analysisTime && FindBugs.validTimestamp(analysisTime)) data.lastSeen = analysisTime; long timestamp = bugCollection.getAppVersionFromSequenceNumber(bug.getFirstVersion()).getTimestamp(); data.firstSeen = timestamp; if (data.inDatabase) return; t.newBug(bug); data.inDatabase = true; } } static class StoreUserAnnotation implements Update { public StoreUserAnnotation(BugData data, BugDesignation designation) { super(); this.data = data; this.designation = designation; } public void execute(DatabaseSyncTask t) throws SQLException { t.newEvaluation(data, new BugDesignation(designation)); } final BugData data; final BugDesignation designation; } private void displayMessage(String msg, Exception e) { AnalysisContext.logError(msg, e); if (bugCollection != null && bugCollection.getProject().isGuiAvaliable()) { StringWriter stackTraceWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stackTraceWriter); e.printStackTrace(printWriter); bugCollection.getProject().getGuiCallback().showMessageDialog( String.format("%s - %s\n%s", msg, e.getMessage(), stackTraceWriter.toString())); } else { System.err.println(msg); e.printStackTrace(System.err); } } private void displayMessage(String msg) { if (!GraphicsEnvironment.isHeadless() && bugCollection.getProject().isGuiAvaliable()) { bugCollection.getProject().getGuiCallback().showMessageDialog(msg); } else { System.err.println(msg); } } public String getUser() { return findbugsUser; } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#getFirstSeen(edu.umd.cs.findbugs.BugInstance) */ public long getFirstSeen(BugInstance b) { return getBugData(b).firstSeen; } @Override public boolean overallClassificationIsNotAProblem(BugInstance b) { BugData bd = getBugData(b); if (bd == null) return false; int isAProblem = 0; int notAProblem = 0; for(BugDesignation d : bd.getUniqueDesignations() ) switch(UserDesignation.valueOf(d.getDesignationKey())) { case I_WILL_FIX: case MUST_FIX: case SHOULD_FIX: isAProblem++; break; case BAD_ANALYSIS: case NOT_A_BUG: case MOSTLY_HARMLESS: case OBSOLETE_CODE: notAProblem++; break; } return notAProblem > isAProblem; } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#getUser() */ public UserDesignation getUserDesignation(BugInstance b) { BugDesignation bd = getBugData(b).getPrimaryDesignation(); if (bd == null) return UserDesignation.UNCLASSIFIED; return UserDesignation.valueOf(bd.getDesignationKey()); } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#getUserEvaluation(edu.umd.cs.findbugs.BugInstance) */ public String getUserEvaluation(BugInstance b) { BugDesignation bd = getBugData(b).getPrimaryDesignation(); if (bd == null) return ""; String result = bd.getAnnotationText(); if (result == null) return ""; return result; } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#getUserTimestamp(edu.umd.cs.findbugs.BugInstance) */ public long getUserTimestamp(BugInstance b) { BugDesignation bd = getBugData(b).getPrimaryDesignation(); if (bd == null) return Long.MAX_VALUE; return bd.getTimestamp(); } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#setUserDesignation(edu.umd.cs.findbugs.BugInstance, edu.umd.cs.findbugs.cloud.UserDesignation, long) */ public void setUserDesignation(BugInstance b, UserDesignation u, long timestamp) { BugData data = getBugData(b); BugDesignation bd = data.getUserDesignation(); if (bd == null) { if (u == UserDesignation.UNCLASSIFIED) return; bd = data.getNonnullUserDesignation(); } bd.setDesignationKey(u.name()); if (bd.isDirty()) { bd.setTimestamp(timestamp); storeUserAnnotation(data, bd); } } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#setUserEvaluation(edu.umd.cs.findbugs.BugInstance, java.lang.String, long) */ public void setUserEvaluation(BugInstance b, String e, long timestamp) { BugData data = getBugData(b); BugDesignation bd = data.getUserDesignation(); if (bd == null) { if (e.length() == 0) return; bd = data.getNonnullUserDesignation(); } bd.setAnnotationText(e); if (bd.isDirty()) { bd.setTimestamp(timestamp); storeUserAnnotation(data, bd); } } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#setUserTimestamp(edu.umd.cs.findbugs.BugInstance, long) */ public void setUserTimestamp(BugInstance b, long timestamp) { BugData data = getBugData(b); if (data == null) return; BugDesignation bd = data.getNonnullUserDesignation(); bd.setTimestamp(timestamp); storeUserAnnotation(data, bd); } static final String BUG_NOTE = SystemProperties.getProperty("findbugs.bugnote"); String getBugReportHead(BugInstance b) { StringWriter stringWriter = new StringWriter(); PrintWriter out = new PrintWriter(stringWriter); out.println("Bug report generated from FindBugs"); out.println(b.getMessageWithoutPrefix()); out.println(); ClassAnnotation primaryClass = b.getPrimaryClass(); for (BugAnnotation a : b.getAnnotations()) { if (a == primaryClass) out.println(a); else out.println(" " + a.toString(primaryClass)); } URL link = getSourceLink(b); if (link != null) { out.println(); out.println(sourceFileLinkToolTip + ": " + link); out.println(); } if (BUG_NOTE != null) { out.println(BUG_NOTE); if (POSTMORTEM_NOTE != null && BugRanker.findRank(b) <= POSTMORTEM_RANK && !overallClassificationIsNotAProblem(b)) out.println(POSTMORTEM_NOTE); out.println(); } Collection<String> projects = projectMapping.getProjects(primaryClass.getClassName()); if (projects != null && !projects.isEmpty()) { String projectList = projects.toString(); projectList = projectList.substring(1, projectList.length() - 1); out.println("Possibly part of: " + projectList); out.println(); } out.close(); return stringWriter.toString(); } String getBugPatternExplanation(BugInstance b) { String detailPlainText = b.getBugPattern().getDetailPlainText(); return "Bug pattern explanation:\n" + detailPlainText + "\n\n"; } String getBugPatternExplanationLink(BugInstance b) { return "Bug pattern explanation: http://findbugs.sourceforge.net/bugDescriptions.html#" + b.getBugPattern().getType() + "\n"; } private String getLineTerminatedUserEvaluation(BugInstance b) { UserDesignation designation = getUserDesignation(b); String result; if (designation != UserDesignation.UNCLASSIFIED) result = "Classified as: " + designation.toString() + "\n"; else result = ""; String eval = getUserEvaluation(b).trim(); if (eval.length() > 0) result = result + eval + "\n"; return result; } String getBugReport(BugInstance b) { return getBugReportHead(b) + getBugReportSourceCode(b) + getLineTerminatedUserEvaluation(b) + getBugPatternExplanation(b) + getBugReportTail(b); } String getBugReportShorter(BugInstance b) { return getBugReportHead(b) + getBugReportSourceCode(b) + getLineTerminatedUserEvaluation(b) + getBugPatternExplanationLink(b) + getBugReportTail(b); } String getBugReportAbridged(BugInstance b) { return getBugReportHead(b) + getBugPatternExplanationLink(b) + getBugReportTail(b); } String getBugReportSourceCode(BugInstance b) { if (!MainFrame.isAvailable()) return ""; StringWriter stringWriter = new StringWriter(); PrintWriter out = new PrintWriter(stringWriter); ClassAnnotation primaryClass = b.getPrimaryClass(); int firstLine = Integer.MAX_VALUE; int lastLine = Integer.MIN_VALUE; for (BugAnnotation a : b.getAnnotations()) if (a instanceof SourceLineAnnotation) { SourceLineAnnotation s = (SourceLineAnnotation) a; if (s.getClassName().equals(primaryClass.getClassName()) && s.getStartLine() > 0) { firstLine = Math.min(firstLine, s.getStartLine()); lastLine = Math.max(lastLine, s.getEndLine()); } } SourceLineAnnotation primarySource = primaryClass.getSourceLines(); if (primarySource.isSourceFileKnown() && firstLine >= 1 && firstLine <= lastLine && lastLine - firstLine < 50) { try { SourceFile sourceFile = MainFrame.getInstance().getSourceFinder().findSourceFile(primarySource); BufferedReader in = new BufferedReader(new InputStreamReader(sourceFile.getInputStream())); int lineNumber = 1; String commonWhiteSpace = null; List<SourceLine> source = new ArrayList<SourceLine>(); while (lineNumber <= lastLine + 4) { String txt = in.readLine(); if (txt == null) break; if (lineNumber >= firstLine - 4) { String trimmed = txt.trim(); if (trimmed.length() == 0) { if (lineNumber > lastLine) break; txt = trimmed; } source.add(new SourceLine(lineNumber, txt)); commonWhiteSpace = commonLeadingWhitespace(commonWhiteSpace, txt); } lineNumber++; } in.close(); out.println("\nRelevant source code:"); for(SourceLine s : source) { if (s.text.length() == 0) out.printf("%5d: \n", s.line); else out.printf("%5d: %s\n", s.line, s.text.substring(commonWhiteSpace.length())); } out.println(); } catch (IOException e) { assert true; } out.close(); String result = stringWriter.toString(); return result; } return ""; } String commonLeadingWhitespace(String soFar, String txt) { if (txt.length() == 0) return soFar; if (soFar == null) return txt; soFar = Util.commonPrefix(soFar, txt); for(int i = 0; i < soFar.length(); i++) { if (!Character.isWhitespace(soFar.charAt(i))) return soFar.substring(0,i); } return soFar; } static class SourceLine { public SourceLine(int line, String text) { this.line = line; this.text = text; } final int line; final String text; } String getBugReportTail(BugInstance b) { return "\nFindBugs issue identifier (do not modify or remove): " + b.getInstanceHash(); } static String urlEncode(String s) { try { return URLEncoder.encode(s, "UTF-8"); } catch (UnsupportedEncodingException e) { assert false; return "No utf-8 encoding"; } } @Override public int getNumberReviewers(BugInstance b) { BugData bd = getBugData(b); if (bd == null) return 0; Collection<BugDesignation> uniqueDesignations = bd.getUniqueDesignations(); return uniqueDesignations.size(); } @Override public double getClassificationScore(BugInstance b) { BugData bd = getBugData(b); if (bd == null) return 0; Collection<BugDesignation> uniqueDesignations = bd.getUniqueDesignations(); double total = 0; int count = 0; for(BugDesignation d : uniqueDesignations) { UserDesignation designation = UserDesignation.valueOf(d.getDesignationKey()); if (nonVoting(designation)) continue; total += designation.score(); count++; } return total / count++; } /** * @param designation * @return */ private boolean nonVoting(UserDesignation designation) { return designation == UserDesignation.OBSOLETE_CODE || designation == UserDesignation.NEEDS_STUDY || designation == UserDesignation.UNCLASSIFIED; } @Override public double getPortionObsoleteClassifications(BugInstance b) { BugData bd = getBugData(b); if (bd == null) return 0; int count = 0; Collection<BugDesignation> uniqueDesignations = bd.getUniqueDesignations(); for(BugDesignation d : uniqueDesignations) if (UserDesignation.valueOf(d.getDesignationKey()) == UserDesignation.OBSOLETE_CODE) count++; return ((double)count)/uniqueDesignations.size(); } @Override public double getClassificationVariance(BugInstance b) { BugData bd = getBugData(b); if (bd == null) return 0; Collection<BugDesignation> uniqueDesignations = bd.getUniqueDesignations(); double total = 0; double totalSquares = 0; int count = 0; for(BugDesignation d : uniqueDesignations) { UserDesignation designation = UserDesignation.valueOf(d.getDesignationKey()); if (nonVoting(designation)) continue; int score = designation.score(); total += score; totalSquares += score*score; count++; } double average = total/count; return totalSquares / count - average*average; } @Override public double getClassificationDisagreement(BugInstance b) { BugData bd = getBugData(b); if (bd == null) return 0; Collection<BugDesignation> uniqueDesignations = bd.getUniqueDesignations(); int shouldFix = 0; int dontFix = 0; for(BugDesignation d : uniqueDesignations) { UserDesignation designation = UserDesignation.valueOf(d.getDesignationKey()); if (nonVoting(designation)) continue; int score = designation.score(); if (score > 0) shouldFix++; else dontFix++; } return Math.min(shouldFix, dontFix) / (double) (shouldFix + dontFix); } public Set<String> getReviewers(BugInstance b) { BugData bd = getBugData(b); if (bd == null) return Collections.emptySet(); return bd.getReviewers(); } public boolean isClaimed(BugInstance b) { BugData bd = getBugData(b); if (bd == null) return false; return bd.isClaimed(); } static final int MAX_URL_LENGTH = 1999; private static final String HAS_FILED_BUGS = "has_filed_bugs"; private static final String HAS_CLASSIFIED_ISSUES = "has_classified_issues"; private static boolean firstTimeDoing(String activity) { Preferences prefs = Preferences.userNodeForPackage(DBCloud.class); if (!prefs.getBoolean(activity, false)) { prefs.putBoolean(activity, true); return true; } return false; } private static void alreadyDone(String activity) { Preferences prefs = Preferences.userNodeForPackage(DBCloud.class); prefs.putBoolean(activity, true); } private boolean firstBugRequest = true; static final String POSTMORTEM_NOTE = SystemProperties.getProperty("findbugs.postmortem.note"); static final int POSTMORTEM_RANK = SystemProperties.getInt("findbugs.postmortem.maxRank", 4); static final String BUG_LINK_FORMAT = SystemProperties.getProperty("findbugs.filebug.link"); static final String BUG_LOGIN_LINK = SystemProperties.getProperty("findbugs.filebug.login"); static final String BUG_LOGIN_MSG = SystemProperties.getProperty("findbugs.filebug.loginMsg"); static final String COMPONENT_FOR_BAD_ANALYSIS = SystemProperties.getProperty("findbugs.filebug.badAnalysisComponent"); @Override @CheckForNull public URL getBugLink(BugInstance b) { BugData bd = getBugData(b); String bugNumber = bd.bugLink; BugFilingStatus status = getBugLinkStatus(b); if (status == BugFilingStatus.VIEW_BUG) return getBugViewLink(bugNumber); Connection c = null; try { c = getConnection(); PreparedStatement ps = c .prepareStatement("SELECT bugReportId, whoFiled, whenFiled, status, assignedTo, componentName FROM findbugs_bugreport WHERE hash=?"); ps.setString(1, b.getInstanceHash()); ResultSet rs = ps.executeQuery(); rs = ps.executeQuery(); Timestamp pendingFiledAt = null; while (rs.next()) { int col = 1; String bugReportId = rs.getString(col++); String whoFiled = rs.getString(col++); Timestamp whenFiled = rs.getTimestamp(col++); String statusString = rs.getString(col++); String assignedTo = rs.getString(col++); String componentName = rs.getString(col++); if (bugReportId.equals(PENDING)) { if (!findbugsUser.equals(whoFiled) && !pendingStatusHasExpired(whenFiled.getTime())) pendingFiledAt = whenFiled; continue; } if (bugReportId.equals(NONE)) continue; rs.close(); ps.close(); bd.bugLink = bugReportId; bd.filedBy = whoFiled; bd.bugFiled = whenFiled.getTime(); bd.bugAssignedTo = assignedTo; bd.bugStatus = statusString; bd.bugComponentName = componentName; int answer = getBugCollection().getProject().getGuiCallback().showConfirmDialog( "Sorry, but since the time we last received updates from the database,\n" + "someone else already filed a bug report. Would you like to view the bug report?", "Someone else already filed a bug report", JOptionPane.YES_NO_OPTION); if (answer == JOptionPane.NO_OPTION) return null; return getBugViewLink(bugReportId); } rs.close(); ps.close(); if (pendingFiledAt != null) { bd.bugLink = PENDING; bd.bugFiled = pendingFiledAt.getTime(); getBugCollection().getProject().getGuiCallback().showMessageDialog( "Sorry, but since the time we last received updates from the database,\n" + "someone else already has started a bug report for this issue. "); return null; } // OK, not in database if (status == BugFilingStatus.FILE_BUG) { URL u = getBugFilingLink(b); if (u != null && firstTimeDoing(HAS_FILED_BUGS)) { String bugFilingNote = String.format(SystemProperties.getProperty("findbugs.filebug.note", "")); int response = bugCollection.getProject().getGuiCallback().showConfirmDialog( "This looks like the first time you've filed a bug from this machine. Please:\n" + " * Please check the component the issue is assigned to; we sometimes get it wrong.\n" + " * Try to figure out the right person to assign it to.\n" + " * Provide the information needed to understand the issue.\n" + bugFilingNote + "Note that classifying an issue is distinct from (and lighter weight than) filing a bug.", "Do you want to file a bug report", JOptionPane.YES_NO_OPTION); if (response != JOptionPane.YES_OPTION) return null; } if (u != null) insertPendingRecord(c, bd, System.currentTimeMillis(), findbugsUser); return u; } else { assert status == BugFilingStatus.FILE_AGAIN; alreadyDone(HAS_FILED_BUGS); URL u = getBugFilingLink(b); if (u != null) insertPendingRecord(c, bd, System.currentTimeMillis(), findbugsUser); return u; } } catch (MalformedURLException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { Util.closeSilently(c); } return null; } /** * @param bugNumber * @return * @throws MalformedURLException */ private @CheckForNull URL getBugViewLink(String bugNumber) { String viewLinkPattern = SystemProperties.getProperty("findbugs.viewbug.link"); if (viewLinkPattern == null) return null; firstBugRequest = false; String u = String.format(viewLinkPattern, bugNumber); try { return new URL(u); } catch (MalformedURLException e) { return null; } } /** * @param b * @return * @throws MalformedURLException */ private URL getBugFilingLink(BugInstance b) throws MalformedURLException { { if (BUG_LINK_FORMAT == null) return null; String report = getBugReport(b); String component; if (getUserDesignation(b) == UserDesignation.BAD_ANALYSIS && COMPONENT_FOR_BAD_ANALYSIS != null) component = COMPONENT_FOR_BAD_ANALYSIS; else component = getBugComponent(b.getPrimaryClass().getClassName().replace('.', '/')); String summary = b.getMessageWithoutPrefix() + " in " + b.getPrimaryClass().getSourceFileName(); int maxURLLength = MAX_URL_LENGTH; if (firstBugRequest) { if (BUG_LOGIN_LINK != null && BUG_LOGIN_MSG != null) { URL u = new URL(String.format(BUG_LOGIN_LINK)); if (!bugCollection.getProject().getGuiCallback().showDocument(u)) return null; int r = bugCollection.getProject().getGuiCallback().showConfirmDialog(BUG_LOGIN_MSG, "Logging into bug tracker...", JOptionPane.OK_CANCEL_OPTION); if (r == JOptionPane.CANCEL_OPTION) return null; } else maxURLLength = maxURLLength *2/3; } firstBugRequest = false; String u = String.format(BUG_LINK_FORMAT, component, urlEncode(summary), urlEncode(report)); if (u.length() > MAX_URL_LENGTH) { report = getBugReportShorter(b); u = String.format(BUG_LINK_FORMAT, component, urlEncode(summary), urlEncode(report)); if (u.length() > MAX_URL_LENGTH) { report = getBugReportAbridged(b); u = String.format(BUG_LINK_FORMAT, component, urlEncode(summary), urlEncode(report)); String supplemental = "[Can't squeeze this information into the URL used to prepopulate the bug entry\n" +" please cut and paste into the bug report as appropriate]\n\n" + getBugReportSourceCode(b) + getLineTerminatedUserEvaluation(b) + getBugPatternExplanation(b); bugCollection.getProject().getGuiCallback().displayNonmodelMessage( "Cut and paste as needed into bug entry", supplemental); } } return new URL(u); } } @Override public boolean supportsCloudReports() { return true; } @Override public boolean supportsBugLinks() { return BUG_LINK_FORMAT != null; } @Override public String getCloudReport(BugInstance b) { SimpleDateFormat format = new SimpleDateFormat("MM/dd, yyyy"); StringBuilder builder = new StringBuilder(); BugData bd = getBugData(b); long firstSeen = bd.firstSeen; if (firstSeen < Long.MAX_VALUE) { builder.append(String.format("First seen %s\n", format.format(new Timestamp(firstSeen)))); } I18N i18n = I18N.instance(); boolean canSeeCommentsByOthers = bd.canSeeCommentsByOthers(); if (canSeeCommentsByOthers) { if (bd.bugStatus != null) { builder.append(bd.bugComponentName); if (bd.bugAssignedTo == null) builder.append("\nBug status is " + bd.bugStatus); else builder.append("\nBug assigned to " + bd.bugAssignedTo + ", status is " + bd.bugStatus); builder.append("\n\n"); } } for(BugDesignation d : bd.getUniqueDesignations()) if (findbugsUser.equals(d.getUser())|| canSeeCommentsByOthers ) { builder.append(String.format("%s @ %s: %s\n", d.getUser(), format.format(new Timestamp(d.getTimestamp())), i18n.getUserDesignation(d.getDesignationKey()))); if (d.getAnnotationText().length() > 0) { builder.append(d.getAnnotationText()); builder.append("\n\n"); } } return builder.toString(); } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#storeUserAnnotation(edu.umd.cs.findbugs.BugInstance) */ public void storeUserAnnotation(BugInstance bugInstance) { storeUserAnnotation(getBugData(bugInstance), bugInstance.getNonnullUserDesignation()); updatedIssue(bugInstance); } @Override public boolean supportsSourceLinks() { return sourceFileLinkPattern != null; } @Override public @CheckForNull URL getSourceLink(BugInstance b) { if (sourceFileLinkPattern == null) return null; SourceLineAnnotation src = b.getPrimarySourceLineAnnotation(); String fileName = src.getSourcePath(); int startLine = src.getStartLine(); java.util.regex.Matcher m = sourceFileLinkPattern.matcher(fileName); boolean isMatch = m.matches(); if (isMatch) try { URL link; if (startLine > 0) link = new URL(String.format(sourceFileLinkFormatWithLine, m.group(1), startLine, startLine - 10)); else link = new URL(String.format(sourceFileLinkFormat, m.group(1))); return link; } catch (MalformedURLException e) { AnalysisContext.logError("Error generating source link for " + src, e); } return null; } @Override public String getSourceLinkToolTip(BugInstance b) { return sourceFileLinkToolTip; } @Override public BugFilingStatus getBugLinkStatus(BugInstance b) { BugData bd = getBugData(b); String link = bd.bugLink; if (link == null || link.length() == 0 || link.equals(NONE)) return BugFilingStatus.FILE_BUG; if (link.equals(PENDING)) { if (findbugsUser.equals(bd.filedBy)) return BugFilingStatus.FILE_AGAIN; else { long whenFiled = bd.bugFiled; if (pendingStatusHasExpired(whenFiled)) return BugFilingStatus.FILE_BUG; else return BugFilingStatus.BUG_PENDING; } } try { Integer.parseInt(link); return BugFilingStatus.VIEW_BUG; } catch (RuntimeException e) { assert true; } return BugFilingStatus.NA; } /** * @param whenFiled * @return */ private boolean pendingStatusHasExpired(long whenFiled) { return System.currentTimeMillis() - whenFiled > 60*60*1000L; } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#bugFiled(edu.umd.cs.findbugs.BugInstance, java.lang.Object) */ public void bugFiled(BugInstance b, Object bugLink) { checkForShutdown(); if (bugAlreadyFiled(b)) { BugData bd = getBugData(b.getInstanceHash()); return; } queue.add(new FileBug(b)); updatedStatus(); } String errorMsg; long errorTime = 0; void setErrorMsg(String msg) { errorMsg = msg; errorTime = System.currentTimeMillis(); updatedStatus(); } void clearErrorMsg() { errorMsg = null; updatedStatus(); } @Override public String getStatusMsg() { if (errorMsg != null) { if (errorTime + 2 * 60 * 1000 > System.currentTimeMillis()) { errorMsg = null; } else return errorMsg +"; " + getStatusMsg0(); } return getStatusMsg0(); } public String getStatusMsg0() { SimpleDateFormat format = new SimpleDateFormat("h:mm a"); int numToSync = queue.size(); if (numToSync > 0) return String.format("%d remain to be synchronized", numToSync); else if (resync != null && resync.after(lastUpdate)) return String.format("%d updates received from db at %s", resyncCount, format.format(resync)); else if (updatesSentToDatabase == 0) return String.format("%d issues synchronized with database", idMap.size()); else return String.format("%d classifications/bug filings sent to db, last updated at %s", updatesSentToDatabase, format.format(lastUpdate)); } @Override public void printCloudSummary(PrintWriter w, Iterable<BugInstance> bugs, String[] packagePrefixes) { Multiset<String> evaluations = new Multiset<String>(); Multiset<String> designations = new Multiset<String>(); Multiset<String> bugStatus = new Multiset<String>(); int issuesWithThisManyReviews [] = new int[100]; I18N i18n = I18N.instance(); Set<String> hashCodes = new HashSet<String>(); for(BugInstance b : bugs) { hashCodes.add(b.getInstanceHash()); } int packageCount = 0; int classCount = 0; int ncss = 0; ProjectStats projectStats = bugCollection.getProjectStats(); for(PackageStats ps : projectStats.getPackageStats()) if (ViewFilter.matchedPrefixes(packagePrefixes, ps.getPackageName()) && ps.size() > 0 && ps.getNumClasses() > 0) { packageCount++; ncss += ps.size(); classCount += ps.getNumClasses(); } if (packagePrefixes != null && packagePrefixes.length > 0) { String lst = Arrays.asList(packagePrefixes).toString(); w.println("Code analyzed in " + lst.substring(1, lst.length()-1)); } else w.println("Code analyzed"); if (classCount == 0) w.println("No classes were analyzed"); else w.printf("%,7d packages\n%,7d classes\n%,7d thousands of lines of non-commenting source statements\n", packageCount, classCount, (ncss+999)/1000); w.println(); int count = 0; int notInCloud = 0; for(String hash : hashCodes) { BugData bd = instanceMap.get(hash); if (bd == null) { notInCloud++; continue; } count++; HashSet<String> reviewers = new HashSet<String>(); if (bd.bugStatus != null) bugStatus.add(bd.bugStatus); for(BugDesignation d : bd.designations) if (reviewers.add(d.getUser())) { evaluations.add(d.getUser()); designations.add(i18n.getUserDesignation(d.getDesignationKey())); } int numReviews = Math.min( reviewers.size(), issuesWithThisManyReviews.length -1); issuesWithThisManyReviews[numReviews]++; } if (count == 0) { w.printf("None of the %d issues in the current view are in the cloud\n\n", notInCloud); return; } if (notInCloud == 0) { w.printf("Summary for %d issues that are in the current view\n\n", count); }else { w.printf("Summary for %d issues that are in the current view and cloud (%d not in cloud)\n\n", count, notInCloud); } w.println("People who have performed the most reviews"); printLeaderBoard(w, evaluations, 9, findbugsUser, true, "reviewer"); w.println("\nDistribution of evaluations"); printLeaderBoard(w, designations, 100, " --- ", false, "designation"); w.println("\nDistribution of bug status"); printLeaderBoard(w, bugStatus, 100, " --- ", false, "status of filed bug"); w.println("\nDistribution of number of reviews"); for(int i = 0; i < issuesWithThisManyReviews.length; i++) if (issuesWithThisManyReviews[i] > 0) { w.printf("%4d with %3d review", issuesWithThisManyReviews[i], i); if (i != 1) w.print("s"); w.println(); } } /** * @param w * @param evaluations * @param listRank TODO * @param title TODO */ static void printLeaderBoard(PrintWriter w, Multiset<String> evaluations, int maxRows, String alwaysPrint, boolean listRank, String title) { if (listRank) w.printf("%3s %4s %s\n", "rnk", "num", title); else w.printf("%4s %s\n", "num", title); printLeaderBoard2(w, evaluations, maxRows, alwaysPrint, listRank ? "%3d %4d %s\n" : "%2$4d %3$s\n" , title); } static final String LEADERBOARD_BLACKLIST = SystemProperties.getProperty("findbugs.leaderboard.blacklist"); static final Pattern LEADERBOARD_BLACKLIST_PATTERN; static { Pattern p = null; if (LEADERBOARD_BLACKLIST != null) try { p = Pattern.compile(LEADERBOARD_BLACKLIST.replace(',', '|')); } catch (Exception e) { assert true; } LEADERBOARD_BLACKLIST_PATTERN = p; } /** * @param w * @param evaluations * @param maxRows * @param alwaysPrint * @param listRank * @param title */ static void printLeaderBoard2(PrintWriter w, Multiset<String> evaluations, int maxRows, String alwaysPrint, String format, String title) { int row = 1; int position = 0; int previousScore = -1; boolean foundAlwaysPrint = false; for(Map.Entry<String,Integer> e : evaluations.entriesInDecreasingFrequency()) { int num = e.getValue(); if (num != previousScore) { position = row; previousScore = num; } String key = e.getKey(); if (LEADERBOARD_BLACKLIST_PATTERN != null && LEADERBOARD_BLACKLIST_PATTERN.matcher(key).matches()) continue; boolean shouldAlwaysPrint = key.equals(alwaysPrint); if (row <= maxRows || shouldAlwaysPrint) w.printf(format, position, num, key); if (shouldAlwaysPrint) foundAlwaysPrint = true; row++; if (row >= maxRows) { if (alwaysPrint == null) break; if (foundAlwaysPrint) { w.printf("Total of %d %ss\n", evaluations.numKeys(), title); break; } } } } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#getIWillFix(edu.umd.cs.findbugs.BugInstance) */ @Override public boolean getIWillFix(BugInstance b) { if (super.getIWillFix(b)) return true; BugData bd = getBugData(b); return bd != null && findbugsUser.equals(bd.bugAssignedTo); } public boolean getBugIsUnassigned(BugInstance b) { BugData bd = getBugData(b); return bd != null && bd.inDatabase && getBugLinkStatus(b) == BugFilingStatus.VIEW_BUG && ("NEW".equals(bd.bugStatus) || bd.bugAssignedTo == null || bd.bugAssignedTo.length() == 0); } public boolean getWillNotBeFixed(BugInstance b) { BugData bd = getBugData(b); return bd != null && bd.inDatabase && getBugLinkStatus(b) == BugFilingStatus.VIEW_BUG && "WILL_NOT_FIX".equals(bd.bugStatus); } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#supportsCloudSummaries() */ @Override public boolean supportsCloudSummaries() { return true; } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#canStoreUserAnnotation(edu.umd.cs.findbugs.BugInstance) */ @Override public boolean canStoreUserAnnotation(BugInstance bugInstance) { return !skipBug(bugInstance); } @Override public @CheckForNull String claimedBy(BugInstance b) { BugData bd = getBugData(b); if (bd == null) return null; for(BugDesignation designation : bd.getUniqueDesignations()) { if ("I_WILL_FIX".equals(designation.getDesignationKey())) return designation.getUser(); } return null; } }
add additional error checking git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@11367 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3
findbugs/src/java/edu/umd/cs/findbugs/cloud/DBCloud.java
add additional error checking
<ide><path>indbugs/src/java/edu/umd/cs/findbugs/cloud/DBCloud.java <ide> * @throws SQLException <ide> */ <ide> private void insertPendingRecord(Connection c, BugData bug, long when, String who) throws SQLException { <del> int count; <ide> int pendingId = -1; <ide> PreparedStatement query = c <ide> .prepareStatement("SELECT id, bugReportId, whoFiled, whenFiled FROM findbugs_bugreport where hash=?"); <ide> ResultSet rs = query.executeQuery(); <ide> boolean needsUpdate = false; <ide> <add> try { <ide> while (rs.next()) { <ide> int col = 1; <ide> int id = rs.getInt(col++); <ide> pendingId = id; <ide> needsUpdate = !who.equals(whoFiled); <ide> } <add> } catch (SQLException e) { <add> String msg = "Problem inserting pending record for " + bug.instanceHash; <add> AnalysisContext.logError(msg, e); <add> System.out.println(msg); <add> e.printStackTrace(); <add> return; <add> } finally { <ide> rs.close(); <ide> query.close(); <add> } <ide> <ide> if (pendingId == -1) { <ide> PreparedStatement insert = c <ide> insert.setString(col++, PENDING); <ide> insert.setString(col++, who); <ide> insert.setTimestamp(col++, date); <del> count = insert.executeUpdate(); <add> insert.executeUpdate(); <ide> insert.close(); <ide> } <ide> <ide> updateBug.setString(col++, bug.filedBy); <ide> updateBug.setTimestamp(col++, new Timestamp(bug.bugFiled)); <ide> updateBug.setInt(col++, pendingId); <del> count = updateBug.executeUpdate(); <add> updateBug.executeUpdate(); <ide> updateBug.close(); <ide> } <ide> }
Java
apache-2.0
882ca3c7bbcfdf1f9f1ff83c53559b421f852f10
0
linkedin/ambry,linkedin/ambry,daniellitoc/ambry-Research,xiahome/ambry,cgtz/ambry,nsivabalan/ambry,nsivabalan/ambry,linkedin/ambry,pnarayanan/ambry,cgtz/ambry,cgtz/ambry,vgkholla/ambry,xiahome/ambry,pnarayanan/ambry,vgkholla/ambry,cgtz/ambry,daniellitoc/ambry-Research,linkedin/ambry
package com.github.ambry.store; import com.codahale.metrics.Counter; import com.codahale.metrics.Gauge; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.Timer; /** * Metrics for the store */ public class StoreMetrics { public final Timer getResponse; public final Timer putResponse; public final Timer deleteResponse; public final Timer findEntriesSinceResponse; public final Timer findMissingKeysResponse; public final Timer isKeyDeletedResponse; public final Timer storeStartTime; public final Counter overflowWriteError; public final Counter overflowReadError; public final Timer recoveryTime; public final Timer findTime; public final Timer indexFlushTime; public final Counter nonzeroMessageRecovery; public final Counter bloomPositiveCount; public final Counter bloomFalsePositiveCount; public Gauge<Long> currentCapacityUsed; public Gauge<Double> percentageUsedCapacity; private final MetricRegistry registry; private final String name; public StoreMetrics(String name, MetricRegistry registry) { this.registry = registry; this.name = name; getResponse = registry.timer(MetricRegistry.name(BlobStore.class, name + "-storeGetResponse")); putResponse = registry.timer(MetricRegistry.name(BlobStore.class, name + "-storePutResponse")); deleteResponse = registry.timer(MetricRegistry.name(BlobStore.class, name + "-storeDeleteResponse")); findEntriesSinceResponse = registry.timer(MetricRegistry.name(BlobStore.class, name + "-storeFindEntriesSinceResponse")); findMissingKeysResponse = registry.timer(MetricRegistry.name(BlobStore.class, name + "-storeFindMissingKeyResponse")); isKeyDeletedResponse = registry.timer(MetricRegistry.name(BlobStore.class, name + "-isKeyDeletedResponse")); storeStartTime = registry.timer(MetricRegistry.name(BlobStore.class, name + "-storeStartTime")); overflowWriteError = registry.counter(MetricRegistry.name(Log.class, name + "-overflowWriteError")); overflowReadError = registry.counter(MetricRegistry.name(Log.class, name + "-overflowReadError")); recoveryTime = registry.timer(MetricRegistry.name(PersistentIndex.class, name + "-indexRecoveryTime")); findTime = registry.timer(MetricRegistry.name(PersistentIndex.class, name + "-indexFindTime")); indexFlushTime = registry.timer(MetricRegistry.name(PersistentIndex.class, name + "-indexFlushTime")); nonzeroMessageRecovery = registry.counter(MetricRegistry.name(PersistentIndex.class, name + "-nonZeroMessageRecovery")); bloomPositiveCount = registry.counter(MetricRegistry.name(IndexSegment.class, name + "-bloomPositiveCount")); bloomFalsePositiveCount = registry.counter(MetricRegistry.name(IndexSegment.class, name + "-bloomFalsePositiveCount")); } public void initializeCapacityUsedMetric(final Log log, final long capacityInBytes) { currentCapacityUsed = new Gauge<Long>() { @Override public Long getValue() { return log.getLogEndOffset(); } }; registry.register(MetricRegistry.name(Log.class, name + "-currentCapacityUsed"), currentCapacityUsed); percentageUsedCapacity = new Gauge<Double>() { @Override public Double getValue() { return ((double) log.getLogEndOffset() / capacityInBytes) * 100; } }; registry.register(MetricRegistry.name(Log.class, name + "-percentageUsedCapacity"), percentageUsedCapacity); } }
ambry-store/src/main/java/com.github.ambry.store/StoreMetrics.java
package com.github.ambry.store; import com.codahale.metrics.Counter; import com.codahale.metrics.Gauge; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.Timer; /** * Metrics for the store */ public class StoreMetrics { public final Timer getResponse; public final Timer putResponse; public final Timer deleteResponse; public final Timer findEntriesSinceResponse; public final Timer findMissingKeysResponse; public final Timer isKeyDeletedResponse; public final Timer storeStartTime; public final Counter overflowWriteError; public final Counter overflowReadError; public final Timer recoveryTime; public final Timer findTime; public final Timer indexFlushTime; public final Counter nonzeroMessageRecovery; public final Counter bloomPositiveCount; public final Counter bloomFalsePositiveCount; public Gauge<Long> currentCapacityUsed; public Gauge<Double> precentageUsedCapacity; private final MetricRegistry registry; private final String name; public StoreMetrics(String name, MetricRegistry registry) { this.registry = registry; this.name = name; getResponse = registry.timer(MetricRegistry.name(BlobStore.class, name + "-storeGetResponse")); putResponse = registry.timer(MetricRegistry.name(BlobStore.class, name + "-storePutResponse")); deleteResponse = registry.timer(MetricRegistry.name(BlobStore.class, name + "-storeDeleteResponse")); findEntriesSinceResponse = registry.timer(MetricRegistry.name(BlobStore.class, name + "-storeFindEntriesSinceResponse")); findMissingKeysResponse = registry.timer(MetricRegistry.name(BlobStore.class, name + "-storeFindMissingKeyResponse")); isKeyDeletedResponse = registry.timer(MetricRegistry.name(BlobStore.class, name + "-isKeyDeletedResponse")); storeStartTime = registry.timer(MetricRegistry.name(BlobStore.class, name + "-storeStartTime")); overflowWriteError = registry.counter(MetricRegistry.name(Log.class, name + "-overflowWriteError")); overflowReadError = registry.counter(MetricRegistry.name(Log.class, name + "-overflowReadError")); recoveryTime = registry.timer(MetricRegistry.name(PersistentIndex.class, name + "-indexRecoveryTime")); findTime = registry.timer(MetricRegistry.name(PersistentIndex.class, name + "-indexFindTime")); indexFlushTime = registry.timer(MetricRegistry.name(PersistentIndex.class, name + "-indexFlushTime")); nonzeroMessageRecovery = registry.counter(MetricRegistry.name(PersistentIndex.class, name + "-nonZeroMessageRecovery")); bloomPositiveCount = registry.counter(MetricRegistry.name(IndexSegment.class, name + "-bloomPositiveCount")); bloomFalsePositiveCount = registry.counter(MetricRegistry.name(IndexSegment.class, name + "-bloomFalsePositiveCount")); } public void initializeCapacityUsedMetric(final Log log, final long capacityInBytes) { currentCapacityUsed = new Gauge<Long>() { @Override public Long getValue() { return log.getLogEndOffset(); } }; registry.register(MetricRegistry.name(Log.class, name + "-currentCapacityUsed"), currentCapacityUsed); precentageUsedCapacity = new Gauge<Double>() { @Override public Double getValue() { return ((double) log.getLogEndOffset() / capacityInBytes) * 100; } }; registry.register(MetricRegistry.name(Log.class, name + "-precentageUsedCapacity"), precentageUsedCapacity); } }
fixing typo
ambry-store/src/main/java/com.github.ambry.store/StoreMetrics.java
fixing typo
<ide><path>mbry-store/src/main/java/com.github.ambry.store/StoreMetrics.java <ide> public final Counter bloomPositiveCount; <ide> public final Counter bloomFalsePositiveCount; <ide> public Gauge<Long> currentCapacityUsed; <del> public Gauge<Double> precentageUsedCapacity; <add> public Gauge<Double> percentageUsedCapacity; <ide> private final MetricRegistry registry; <ide> private final String name; <ide> <ide> } <ide> }; <ide> registry.register(MetricRegistry.name(Log.class, name + "-currentCapacityUsed"), currentCapacityUsed); <del> precentageUsedCapacity = new Gauge<Double>() { <add> percentageUsedCapacity = new Gauge<Double>() { <ide> @Override <ide> public Double getValue() { <ide> return ((double) log.getLogEndOffset() / capacityInBytes) * 100; <ide> } <ide> }; <del> registry.register(MetricRegistry.name(Log.class, name + "-precentageUsedCapacity"), precentageUsedCapacity); <add> registry.register(MetricRegistry.name(Log.class, name + "-percentageUsedCapacity"), percentageUsedCapacity); <ide> } <ide> }
Java
apache-2.0
335b3a1bd0baf8d2060042f292a3e650c988d9fa
0
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
// Copyright 2020 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.hosted.controller.restapi.application; import ai.vespa.hosted.api.Signatures; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableSet; import com.google.inject.Inject; import com.yahoo.component.Version; import com.yahoo.config.application.api.DeploymentSpec; import com.yahoo.config.provision.ApplicationId; import com.yahoo.config.provision.ApplicationName; import com.yahoo.config.provision.ClusterResources; import com.yahoo.config.provision.ClusterSpec; import com.yahoo.config.provision.Environment; import com.yahoo.config.provision.HostName; import com.yahoo.config.provision.InstanceName; import com.yahoo.config.provision.NodeResources; import com.yahoo.config.provision.TenantName; import com.yahoo.config.provision.zone.RoutingMethod; import com.yahoo.config.provision.zone.ZoneId; import com.yahoo.container.handler.metrics.JsonResponse; import com.yahoo.container.jdisc.HttpRequest; import com.yahoo.container.jdisc.HttpResponse; import com.yahoo.container.jdisc.LoggingRequestHandler; import com.yahoo.io.IOUtils; import com.yahoo.restapi.ErrorResponse; import com.yahoo.restapi.MessageResponse; import com.yahoo.restapi.Path; import com.yahoo.restapi.ResourceResponse; import com.yahoo.restapi.SlimeJsonResponse; import com.yahoo.security.KeyUtils; import com.yahoo.slime.Cursor; import com.yahoo.slime.Inspector; import com.yahoo.slime.JsonParseException; import com.yahoo.slime.Slime; import com.yahoo.slime.SlimeUtils; import com.yahoo.vespa.hosted.controller.Application; import com.yahoo.vespa.hosted.controller.Controller; import com.yahoo.vespa.hosted.controller.Instance; import com.yahoo.vespa.hosted.controller.LockedTenant; import com.yahoo.vespa.hosted.controller.NotExistsException; import com.yahoo.vespa.hosted.controller.api.application.v4.EnvironmentResource; import com.yahoo.vespa.hosted.controller.api.application.v4.model.EndpointStatus; import com.yahoo.vespa.hosted.controller.api.application.v4.model.ProtonMetrics; import com.yahoo.vespa.hosted.controller.api.application.v4.model.configserverbindings.RefeedAction; import com.yahoo.vespa.hosted.controller.api.application.v4.model.configserverbindings.RestartAction; import com.yahoo.vespa.hosted.controller.api.application.v4.model.configserverbindings.ServiceInfo; import com.yahoo.vespa.hosted.controller.api.identifiers.DeploymentId; import com.yahoo.vespa.hosted.controller.api.identifiers.TenantId; import com.yahoo.vespa.hosted.controller.api.integration.aws.TenantRoles; import com.yahoo.vespa.hosted.controller.api.integration.billing.Quota; import com.yahoo.vespa.hosted.controller.api.integration.configserver.ApplicationReindexing; import com.yahoo.vespa.hosted.controller.api.integration.configserver.Cluster; import com.yahoo.vespa.hosted.controller.api.integration.configserver.ConfigServerException; import com.yahoo.vespa.hosted.controller.api.integration.configserver.Log; import com.yahoo.vespa.hosted.controller.api.integration.configserver.Node; import com.yahoo.vespa.hosted.controller.api.integration.deployment.ApplicationVersion; import com.yahoo.vespa.hosted.controller.api.integration.deployment.JobId; import com.yahoo.vespa.hosted.controller.api.integration.deployment.JobType; import com.yahoo.vespa.hosted.controller.api.integration.deployment.RunId; import com.yahoo.vespa.hosted.controller.api.integration.deployment.SourceRevision; import com.yahoo.vespa.hosted.controller.api.integration.noderepository.RestartFilter; import com.yahoo.vespa.hosted.controller.api.integration.resource.MeteringData; import com.yahoo.vespa.hosted.controller.api.integration.resource.ResourceAllocation; import com.yahoo.vespa.hosted.controller.api.integration.resource.ResourceSnapshot; import com.yahoo.vespa.hosted.controller.api.integration.secrets.TenantSecretStore; import com.yahoo.vespa.hosted.controller.api.role.Role; import com.yahoo.vespa.hosted.controller.api.role.RoleDefinition; import com.yahoo.vespa.hosted.controller.api.role.SecurityContext; import com.yahoo.vespa.hosted.controller.application.ActivateResult; import com.yahoo.vespa.hosted.controller.application.ApplicationPackage; import com.yahoo.vespa.hosted.controller.application.AssignedRotation; import com.yahoo.vespa.hosted.controller.application.Change; import com.yahoo.vespa.hosted.controller.application.Deployment; import com.yahoo.vespa.hosted.controller.application.DeploymentMetrics; import com.yahoo.vespa.hosted.controller.application.Endpoint; import com.yahoo.vespa.hosted.controller.application.EndpointList; import com.yahoo.vespa.hosted.controller.application.QuotaUsage; import com.yahoo.vespa.hosted.controller.application.SystemApplication; import com.yahoo.vespa.hosted.controller.application.TenantAndApplicationId; import com.yahoo.vespa.hosted.controller.auditlog.AuditLoggingRequestHandler; import com.yahoo.vespa.hosted.controller.deployment.DeploymentStatus; import com.yahoo.vespa.hosted.controller.deployment.DeploymentSteps; import com.yahoo.vespa.hosted.controller.deployment.DeploymentTrigger; import com.yahoo.vespa.hosted.controller.deployment.DeploymentTrigger.ChangesToCancel; import com.yahoo.vespa.hosted.controller.deployment.JobStatus; import com.yahoo.vespa.hosted.controller.deployment.Run; import com.yahoo.vespa.hosted.controller.deployment.TestConfigSerializer; import com.yahoo.vespa.hosted.controller.notification.Notification; import com.yahoo.vespa.hosted.controller.notification.NotificationSource; import com.yahoo.vespa.hosted.controller.persistence.SupportAccessSerializer; import com.yahoo.vespa.hosted.controller.rotation.RotationId; import com.yahoo.vespa.hosted.controller.rotation.RotationState; import com.yahoo.vespa.hosted.controller.rotation.RotationStatus; import com.yahoo.vespa.hosted.controller.routing.GlobalRouting; import com.yahoo.vespa.hosted.controller.security.AccessControlRequests; import com.yahoo.vespa.hosted.controller.security.Credentials; import com.yahoo.vespa.hosted.controller.support.access.SupportAccess; import com.yahoo.vespa.hosted.controller.tenant.AthenzTenant; import com.yahoo.vespa.hosted.controller.tenant.CloudTenant; import com.yahoo.vespa.hosted.controller.tenant.LastLoginInfo; import com.yahoo.vespa.hosted.controller.tenant.Tenant; import com.yahoo.vespa.hosted.controller.tenant.TenantInfo; import com.yahoo.vespa.hosted.controller.tenant.TenantInfoAddress; import com.yahoo.vespa.hosted.controller.tenant.TenantInfoBillingContact; import com.yahoo.vespa.hosted.controller.versions.VersionStatus; import com.yahoo.vespa.hosted.controller.versions.VespaVersion; import com.yahoo.vespa.serviceview.bindings.ApplicationView; import com.yahoo.yolean.Exceptions; import javax.ws.rs.ForbiddenException; import javax.ws.rs.InternalServerErrorException; import javax.ws.rs.NotAuthorizedException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.net.URISyntaxException; import java.security.DigestInputStream; import java.security.Principal; import java.security.PublicKey; import java.time.DayOfWeek; import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.Arrays; import java.util.Base64; import java.util.Comparator; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.OptionalLong; import java.util.Scanner; import java.util.StringJoiner; import java.util.logging.Level; import java.util.stream.Collectors; import java.util.stream.Stream; import static com.yahoo.jdisc.Response.Status.BAD_REQUEST; import static com.yahoo.jdisc.Response.Status.CONFLICT; import static java.util.Map.Entry.comparingByKey; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toUnmodifiableList; /** * This implements the application/v4 API which is used to deploy and manage applications * on hosted Vespa. * * @author bratseth * @author mpolden */ @SuppressWarnings("unused") // created by injection public class ApplicationApiHandler extends AuditLoggingRequestHandler { private static final ObjectMapper jsonMapper = new ObjectMapper(); private final Controller controller; private final AccessControlRequests accessControlRequests; private final TestConfigSerializer testConfigSerializer; @Inject public ApplicationApiHandler(LoggingRequestHandler.Context parentCtx, Controller controller, AccessControlRequests accessControlRequests) { super(parentCtx, controller.auditLogger()); this.controller = controller; this.accessControlRequests = accessControlRequests; this.testConfigSerializer = new TestConfigSerializer(controller.system()); } @Override public Duration getTimeout() { return Duration.ofMinutes(20); // deploys may take a long time; } @Override public HttpResponse auditAndHandle(HttpRequest request) { try { Path path = new Path(request.getUri()); switch (request.getMethod()) { case GET: return handleGET(path, request); case PUT: return handlePUT(path, request); case POST: return handlePOST(path, request); case PATCH: return handlePATCH(path, request); case DELETE: return handleDELETE(path, request); case OPTIONS: return handleOPTIONS(); default: return ErrorResponse.methodNotAllowed("Method '" + request.getMethod() + "' is not supported"); } } catch (ForbiddenException e) { return ErrorResponse.forbidden(Exceptions.toMessageString(e)); } catch (NotAuthorizedException e) { return ErrorResponse.unauthorized(Exceptions.toMessageString(e)); } catch (NotExistsException e) { return ErrorResponse.notFoundError(Exceptions.toMessageString(e)); } catch (IllegalArgumentException e) { return ErrorResponse.badRequest(Exceptions.toMessageString(e)); } catch (ConfigServerException e) { switch (e.code()) { case NOT_FOUND: return ErrorResponse.notFoundError(Exceptions.toMessageString(e)); case ACTIVATION_CONFLICT: return new ErrorResponse(CONFLICT, e.code().name(), Exceptions.toMessageString(e)); case INTERNAL_SERVER_ERROR: return ErrorResponse.internalServerError(Exceptions.toMessageString(e)); default: return new ErrorResponse(BAD_REQUEST, e.code().name(), Exceptions.toMessageString(e)); } } catch (RuntimeException e) { log.log(Level.WARNING, "Unexpected error handling '" + request.getUri() + "'", e); return ErrorResponse.internalServerError(Exceptions.toMessageString(e)); } } private HttpResponse handleGET(Path path, HttpRequest request) { if (path.matches("/application/v4/")) return root(request); if (path.matches("/application/v4/tenant")) return tenants(request); if (path.matches("/application/v4/tenant/{tenant}")) return tenant(path.get("tenant"), request); if (path.matches("/application/v4/tenant/{tenant}/info")) return tenantInfo(path.get("tenant"), request); if (path.matches("/application/v4/tenant/{tenant}/notifications")) return notifications(path.get("tenant"), request); if (path.matches("/application/v4/tenant/{tenant}/secret-store/{name}/validate")) return validateSecretStore(path.get("tenant"), path.get("name"), request); if (path.matches("/application/v4/tenant/{tenant}/application")) return applications(path.get("tenant"), Optional.empty(), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return application(path.get("tenant"), path.get("application"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/compile-version")) return compileVersion(path.get("tenant"), path.get("application")); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deployment")) return JobControllerApiHandlerHelper.overviewResponse(controller, TenantAndApplicationId.from(path.get("tenant"), path.get("application")), request.getUri()); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/package")) return applicationPackage(path.get("tenant"), path.get("application"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying")) return deploying(path.get("tenant"), path.get("application"), "default", request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/pin")) return deploying(path.get("tenant"), path.get("application"), "default", request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/metering")) return metering(path.get("tenant"), path.get("application"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance")) return applications(path.get("tenant"), Optional.of(path.get("application")), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return instance(path.get("tenant"), path.get("application"), path.get("instance"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying")) return deploying(path.get("tenant"), path.get("application"), path.get("instance"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/pin")) return deploying(path.get("tenant"), path.get("application"), path.get("instance"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job")) return JobControllerApiHandlerHelper.jobTypeResponse(controller, appIdFromPath(path), request.getUri()); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}")) return JobControllerApiHandlerHelper.runResponse(controller.jobController().runs(appIdFromPath(path), jobTypeFromPath(path)), request.getUri()); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/package")) return devApplicationPackage(appIdFromPath(path), jobTypeFromPath(path)); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/test-config")) return testConfig(appIdFromPath(path), jobTypeFromPath(path)); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/run/{number}")) return JobControllerApiHandlerHelper.runDetailsResponse(controller.jobController(), runIdFromPath(path), request.getProperty("after")); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}")) return deployment(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/reindexing")) return getReindexing(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/suspended")) return suspended(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/service")) return services(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/service/{service}/{*}")) return service(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), path.get("service"), path.getRest(), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/nodes")) return nodes(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region")); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/clusters")) return clusters(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region")); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/content/{*}")) return content(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), path.getRest(), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/logs")) return logs(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request.propertyMap()); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/access/support")) return supportAccess(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request.propertyMap()); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/metrics")) return metrics(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region")); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation")) return rotationStatus(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), Optional.ofNullable(request.getProperty("endpointId"))); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation/override")) return getGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region")); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deployment(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deployment(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/suspended")) return suspended(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/service")) return services(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/service/{service}/{*}")) return service(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), path.get("service"), path.getRest(), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/nodes")) return nodes(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region")); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/clusters")) return clusters(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region")); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/logs")) return logs(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request.propertyMap()); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation")) return rotationStatus(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), Optional.ofNullable(request.getProperty("endpointId"))); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation/override")) return getGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region")); return ErrorResponse.notFoundError("Nothing at " + path); } private HttpResponse handlePUT(Path path, HttpRequest request) { if (path.matches("/application/v4/tenant/{tenant}")) return updateTenant(path.get("tenant"), request); if (path.matches("/application/v4/tenant/{tenant}/info")) return updateTenantInfo(path.get("tenant"), request); if (path.matches("/application/v4/tenant/{tenant}/archive-access")) return allowArchiveAccess(path.get("tenant"), request); if (path.matches("/application/v4/tenant/{tenant}/secret-store/{name}")) return addSecretStore(path.get("tenant"), path.get("name"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), false, request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), false, request); return ErrorResponse.notFoundError("Nothing at " + path); } private HttpResponse handlePOST(Path path, HttpRequest request) { if (path.matches("/application/v4/tenant/{tenant}")) return createTenant(path.get("tenant"), request); if (path.matches("/application/v4/tenant/{tenant}/key")) return addDeveloperKey(path.get("tenant"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return createApplication(path.get("tenant"), path.get("application"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/platform")) return deployPlatform(path.get("tenant"), path.get("application"), "default", false, request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/pin")) return deployPlatform(path.get("tenant"), path.get("application"), "default", true, request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/application")) return deployApplication(path.get("tenant"), path.get("application"), "default", request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/key")) return addDeployKey(path.get("tenant"), path.get("application"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/submit")) return submit(path.get("tenant"), path.get("application"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return createInstance(path.get("tenant"), path.get("application"), path.get("instance"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploy/{jobtype}")) return jobDeploy(appIdFromPath(path), jobTypeFromPath(path), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/platform")) return deployPlatform(path.get("tenant"), path.get("application"), path.get("instance"), false, request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/pin")) return deployPlatform(path.get("tenant"), path.get("application"), path.get("instance"), true, request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/application")) return deployApplication(path.get("tenant"), path.get("application"), path.get("instance"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/submit")) return submit(path.get("tenant"), path.get("application"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}")) return trigger(appIdFromPath(path), jobTypeFromPath(path), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/pause")) return pause(appIdFromPath(path), jobTypeFromPath(path)); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/deploy")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request); // legacy synonym of the above if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/reindex")) return reindex(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/reindexing")) return enableReindexing(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/restart")) return restart(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/suspend")) return suspend(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), true); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/access/support")) return allowSupportAccess(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/deploy")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request); // legacy synonym of the above if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/restart")) return restart(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request); return ErrorResponse.notFoundError("Nothing at " + path); } private HttpResponse handlePATCH(Path path, HttpRequest request) { if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return patchApplication(path.get("tenant"), path.get("application"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return patchApplication(path.get("tenant"), path.get("application"), request); return ErrorResponse.notFoundError("Nothing at " + path); } private HttpResponse handleDELETE(Path path, HttpRequest request) { if (path.matches("/application/v4/tenant/{tenant}")) return deleteTenant(path.get("tenant"), request); if (path.matches("/application/v4/tenant/{tenant}/key")) return removeDeveloperKey(path.get("tenant"), request); if (path.matches("/application/v4/tenant/{tenant}/archive-access")) return removeArchiveAccess(path.get("tenant")); if (path.matches("/application/v4/tenant/{tenant}/secret-store/{name}")) return deleteSecretStore(path.get("tenant"), path.get("name"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return deleteApplication(path.get("tenant"), path.get("application"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deployment")) return removeAllProdDeployments(path.get("tenant"), path.get("application")); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying")) return cancelDeploy(path.get("tenant"), path.get("application"), "default", "all"); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/{choice}")) return cancelDeploy(path.get("tenant"), path.get("application"), "default", path.get("choice")); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/key")) return removeDeployKey(path.get("tenant"), path.get("application"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return deleteInstance(path.get("tenant"), path.get("application"), path.get("instance"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying")) return cancelDeploy(path.get("tenant"), path.get("application"), path.get("instance"), "all"); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/{choice}")) return cancelDeploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("choice")); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}")) return JobControllerApiHandlerHelper.abortJobResponse(controller.jobController(), appIdFromPath(path), jobTypeFromPath(path)); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/pause")) return resume(appIdFromPath(path), jobTypeFromPath(path)); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}")) return deactivate(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/reindexing")) return disableReindexing(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/suspend")) return suspend(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), false); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), true, request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/access/support")) return disallowSupportAccess(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deactivate(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), true, request); return ErrorResponse.notFoundError("Nothing at " + path); } private HttpResponse handleOPTIONS() { // We implement this to avoid redirect loops on OPTIONS requests from browsers, but do not really bother // spelling out the methods supported at each path, which we should EmptyResponse response = new EmptyResponse(); response.headers().put("Allow", "GET,PUT,POST,PATCH,DELETE,OPTIONS"); return response; } private HttpResponse recursiveRoot(HttpRequest request) { Slime slime = new Slime(); Cursor tenantArray = slime.setArray(); List<Application> applications = controller.applications().asList(); for (Tenant tenant : controller.tenants().asList()) toSlime(tenantArray.addObject(), tenant, applications.stream().filter(app -> app.id().tenant().equals(tenant.name())).collect(toList()), request); return new SlimeJsonResponse(slime); } private HttpResponse root(HttpRequest request) { return recurseOverTenants(request) ? recursiveRoot(request) : new ResourceResponse(request, "tenant"); } private HttpResponse tenants(HttpRequest request) { Slime slime = new Slime(); Cursor response = slime.setArray(); for (Tenant tenant : controller.tenants().asList()) tenantInTenantsListToSlime(tenant, request.getUri(), response.addObject()); return new SlimeJsonResponse(slime); } private HttpResponse tenant(String tenantName, HttpRequest request) { return controller.tenants().get(TenantName.from(tenantName)) .map(tenant -> tenant(tenant, request)) .orElseGet(() -> ErrorResponse.notFoundError("Tenant '" + tenantName + "' does not exist")); } private HttpResponse tenant(Tenant tenant, HttpRequest request) { Slime slime = new Slime(); toSlime(slime.setObject(), tenant, controller.applications().asList(tenant.name()), request); return new SlimeJsonResponse(slime); } private HttpResponse tenantInfo(String tenantName, HttpRequest request) { return controller.tenants().get(TenantName.from(tenantName)) .filter(tenant -> tenant.type() == Tenant.Type.cloud) .map(tenant -> tenantInfo(((CloudTenant)tenant).info(), request)) .orElseGet(() -> ErrorResponse.notFoundError("Tenant '" + tenantName + "' does not exist or does not support this")); } private SlimeJsonResponse tenantInfo(TenantInfo info, HttpRequest request) { Slime slime = new Slime(); Cursor infoCursor = slime.setObject(); if (!info.isEmpty()) { infoCursor.setString("name", info.name()); infoCursor.setString("email", info.email()); infoCursor.setString("website", info.website()); infoCursor.setString("invoiceEmail", info.invoiceEmail()); infoCursor.setString("contactName", info.contactName()); infoCursor.setString("contactEmail", info.contactEmail()); toSlime(info.address(), infoCursor); toSlime(info.billingContact(), infoCursor); } return new SlimeJsonResponse(slime); } private void toSlime(TenantInfoAddress address, Cursor parentCursor) { if (address.isEmpty()) return; Cursor addressCursor = parentCursor.setObject("address"); addressCursor.setString("addressLines", address.addressLines()); addressCursor.setString("postalCodeOrZip", address.postalCodeOrZip()); addressCursor.setString("city", address.city()); addressCursor.setString("stateRegionProvince", address.stateRegionProvince()); addressCursor.setString("country", address.country()); } private void toSlime(TenantInfoBillingContact billingContact, Cursor parentCursor) { if (billingContact.isEmpty()) return; Cursor addressCursor = parentCursor.setObject("billingContact"); addressCursor.setString("name", billingContact.name()); addressCursor.setString("email", billingContact.email()); addressCursor.setString("phone", billingContact.phone()); toSlime(billingContact.address(), addressCursor); } private HttpResponse updateTenantInfo(String tenantName, HttpRequest request) { return controller.tenants().get(TenantName.from(tenantName)) .filter(tenant -> tenant.type() == Tenant.Type.cloud) .map(tenant -> updateTenantInfo(((CloudTenant)tenant), request)) .orElseGet(() -> ErrorResponse.notFoundError("Tenant '" + tenantName + "' does not exist or does not support this")); } private String getString(Inspector field, String defaultVale) { return field.valid() ? field.asString() : defaultVale; } private SlimeJsonResponse updateTenantInfo(CloudTenant tenant, HttpRequest request) { TenantInfo oldInfo = tenant.info(); // Merge info from request with the existing info Inspector insp = toSlime(request.getData()).get(); TenantInfo mergedInfo = TenantInfo.EMPTY .withName(getString(insp.field("name"), oldInfo.name())) .withEmail(getString(insp.field("email"), oldInfo.email())) .withWebsite(getString(insp.field("website"), oldInfo.email())) .withInvoiceEmail(getString(insp.field("invoiceEmail"), oldInfo.invoiceEmail())) .withContactName(getString(insp.field("contactName"), oldInfo.contactName())) .withContactEmail(getString(insp.field("contactEmail"), oldInfo.contactName())) .withAddress(updateTenantInfoAddress(insp.field("address"), oldInfo.address())) .withBillingContact(updateTenantInfoBillingContact(insp.field("billingContact"), oldInfo.billingContact())); // Store changes controller.tenants().lockOrThrow(tenant.name(), LockedTenant.Cloud.class, lockedTenant -> { lockedTenant = lockedTenant.withInfo(mergedInfo); controller.tenants().store(lockedTenant); }); return new MessageResponse("Tenant info updated"); } private TenantInfoAddress updateTenantInfoAddress(Inspector insp, TenantInfoAddress oldAddress) { if (!insp.valid()) return oldAddress; return TenantInfoAddress.EMPTY .withCountry(getString(insp.field("country"), oldAddress.country())) .withStateRegionProvince(getString(insp.field("stateRegionProvince"), oldAddress.stateRegionProvince())) .withCity(getString(insp.field("city"), oldAddress.city())) .withPostalCodeOrZip(getString(insp.field("postalCodeOrZip"), oldAddress.postalCodeOrZip())) .withAddressLines(getString(insp.field("addressLines"), oldAddress.addressLines())); } private TenantInfoBillingContact updateTenantInfoBillingContact(Inspector insp, TenantInfoBillingContact oldContact) { if (!insp.valid()) return oldContact; return TenantInfoBillingContact.EMPTY .withName(getString(insp.field("name"), oldContact.name())) .withEmail(getString(insp.field("email"), oldContact.email())) .withPhone(getString(insp.field("phone"), oldContact.phone())) .withAddress(updateTenantInfoAddress(insp.field("address"), oldContact.address())); } private HttpResponse notifications(String tenantName, HttpRequest request) { NotificationSource notificationSource = new NotificationSource(TenantName.from(tenantName), Optional.ofNullable(request.getProperty("application")).map(ApplicationName::from), Optional.ofNullable(request.getProperty("instance")).map(InstanceName::from), Optional.empty(), Optional.empty(), Optional.empty(), OptionalLong.empty()); Slime slime = new Slime(); Cursor notificationsArray = slime.setObject().setArray("notifications"); controller.notificationsDb().listNotifications(notificationSource, showOnlyProductionInstances(request)) .forEach(notification -> toSlime(notificationsArray.addObject(), notification)); return new SlimeJsonResponse(slime); } private static void toSlime(Cursor cursor, Notification notification) { cursor.setLong("at", notification.at().toEpochMilli()); cursor.setString("level", notificationLevelAsString(notification.level())); cursor.setString("type", notificationTypeAsString(notification.type())); Cursor messagesArray = cursor.setArray("messages"); notification.messages().forEach(messagesArray::addString); notification.source().application().ifPresent(application -> cursor.setString("application", application.value())); notification.source().instance().ifPresent(instance -> cursor.setString("instance", instance.value())); notification.source().zoneId().ifPresent(zoneId -> { cursor.setString("environment", zoneId.environment().value()); cursor.setString("region", zoneId.region().value()); }); notification.source().clusterId().ifPresent(clusterId -> cursor.setString("clusterId", clusterId.value())); notification.source().jobType().ifPresent(jobType -> cursor.setString("jobName", jobType.jobName())); notification.source().runNumber().ifPresent(runNumber -> cursor.setLong("runNumber", runNumber)); } private static String notificationTypeAsString(Notification.Type type) { switch (type) { case applicationPackage: return "applicationPackage"; case deployment: return "deployment"; case feedBlock: return "feedBlock"; default: throw new IllegalArgumentException("No serialization defined for notification type " + type); } } private static String notificationLevelAsString(Notification.Level level) { switch (level) { case warning: return "warning"; case error: return "error"; default: throw new IllegalArgumentException("No serialization defined for notification level " + level); } } private HttpResponse applications(String tenantName, Optional<String> applicationName, HttpRequest request) { TenantName tenant = TenantName.from(tenantName); if (controller.tenants().get(tenantName).isEmpty()) return ErrorResponse.notFoundError("Tenant '" + tenantName + "' does not exist"); Slime slime = new Slime(); Cursor applicationArray = slime.setArray(); for (Application application : controller.applications().asList(tenant)) { if (applicationName.map(application.id().application().value()::equals).orElse(true)) { Cursor applicationObject = applicationArray.addObject(); applicationObject.setString("tenant", application.id().tenant().value()); applicationObject.setString("application", application.id().application().value()); applicationObject.setString("url", withPath("/application/v4" + "/tenant/" + application.id().tenant().value() + "/application/" + application.id().application().value(), request.getUri()).toString()); Cursor instanceArray = applicationObject.setArray("instances"); for (InstanceName instance : showOnlyProductionInstances(request) ? application.productionInstances().keySet() : application.instances().keySet()) { Cursor instanceObject = instanceArray.addObject(); instanceObject.setString("instance", instance.value()); instanceObject.setString("url", withPath("/application/v4" + "/tenant/" + application.id().tenant().value() + "/application/" + application.id().application().value() + "/instance/" + instance.value(), request.getUri()).toString()); } } } return new SlimeJsonResponse(slime); } private HttpResponse devApplicationPackage(ApplicationId id, JobType type) { if ( ! type.environment().isManuallyDeployed()) throw new IllegalArgumentException("Only manually deployed zones have dev packages"); ZoneId zone = type.zone(controller.system()); byte[] applicationPackage = controller.applications().applicationStore().getDev(id, zone); return new ZipResponse(id.toFullString() + "." + zone.value() + ".zip", applicationPackage); } private HttpResponse applicationPackage(String tenantName, String applicationName, HttpRequest request) { var tenantAndApplication = TenantAndApplicationId.from(tenantName, applicationName); var applicationId = ApplicationId.from(tenantName, applicationName, InstanceName.defaultName().value()); long buildNumber; var requestedBuild = Optional.ofNullable(request.getProperty("build")).map(build -> { try { return Long.parseLong(build); } catch (NumberFormatException e) { throw new IllegalArgumentException("Invalid build number", e); } }); if (requestedBuild.isEmpty()) { // Fall back to latest build var application = controller.applications().requireApplication(tenantAndApplication); var latestBuild = application.latestVersion().map(ApplicationVersion::buildNumber).orElse(OptionalLong.empty()); if (latestBuild.isEmpty()) { throw new NotExistsException("No application package has been submitted for '" + tenantAndApplication + "'"); } buildNumber = latestBuild.getAsLong(); } else { buildNumber = requestedBuild.get(); } var applicationPackage = controller.applications().applicationStore().find(tenantAndApplication.tenant(), tenantAndApplication.application(), buildNumber); var filename = tenantAndApplication + "-build" + buildNumber + ".zip"; if (applicationPackage.isEmpty()) { throw new NotExistsException("No application package found for '" + tenantAndApplication + "' with build number " + buildNumber); } return new ZipResponse(filename, applicationPackage.get()); } private HttpResponse application(String tenantName, String applicationName, HttpRequest request) { Slime slime = new Slime(); toSlime(slime.setObject(), getApplication(tenantName, applicationName), request); return new SlimeJsonResponse(slime); } private HttpResponse compileVersion(String tenantName, String applicationName) { Slime slime = new Slime(); slime.setObject().setString("compileVersion", compileVersion(TenantAndApplicationId.from(tenantName, applicationName)).toFullString()); return new SlimeJsonResponse(slime); } private HttpResponse instance(String tenantName, String applicationName, String instanceName, HttpRequest request) { Slime slime = new Slime(); toSlime(slime.setObject(), getInstance(tenantName, applicationName, instanceName), controller.jobController().deploymentStatus(getApplication(tenantName, applicationName)), request); return new SlimeJsonResponse(slime); } private HttpResponse addDeveloperKey(String tenantName, HttpRequest request) { if (controller.tenants().require(TenantName.from(tenantName)).type() != Tenant.Type.cloud) throw new IllegalArgumentException("Tenant '" + tenantName + "' is not a cloud tenant"); Principal user = request.getJDiscRequest().getUserPrincipal(); String pemDeveloperKey = toSlime(request.getData()).get().field("key").asString(); PublicKey developerKey = KeyUtils.fromPemEncodedPublicKey(pemDeveloperKey); Slime root = new Slime(); controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, tenant -> { tenant = tenant.withDeveloperKey(developerKey, user); toSlime(root.setObject().setArray("keys"), tenant.get().developerKeys()); controller.tenants().store(tenant); }); return new SlimeJsonResponse(root); } private HttpResponse validateSecretStore(String tenantName, String secretStoreName, HttpRequest request) { var awsRegion = request.getProperty("aws-region"); var parameterName = request.getProperty("parameter-name"); var applicationId = ApplicationId.fromFullString(request.getProperty("application-id")); var zoneId = ZoneId.from(request.getProperty("zone")); var deploymentId = new DeploymentId(applicationId, zoneId); var tenant = controller.tenants().require(applicationId.tenant(), CloudTenant.class); var tenantSecretStore = tenant.tenantSecretStores() .stream() .filter(secretStore -> secretStore.getName().equals(secretStoreName)) .findFirst(); if (tenantSecretStore.isEmpty()) return ErrorResponse.notFoundError("No secret store '" + secretStoreName + "' configured for tenant '" + tenantName + "'"); var response = controller.serviceRegistry().configServer().validateSecretStore(deploymentId, tenantSecretStore.get(), awsRegion, parameterName); try { var responseRoot = new Slime(); var responseCursor = responseRoot.setObject(); responseCursor.setString("target", deploymentId.toString()); var responseResultCursor = responseCursor.setObject("result"); var responseSlime = SlimeUtils.jsonToSlime(response); SlimeUtils.copyObject(responseSlime.get(), responseResultCursor); return new SlimeJsonResponse(responseRoot); } catch (JsonParseException e) { return ErrorResponse.internalServerError(response); } } private HttpResponse removeDeveloperKey(String tenantName, HttpRequest request) { if (controller.tenants().require(TenantName.from(tenantName)).type() != Tenant.Type.cloud) throw new IllegalArgumentException("Tenant '" + tenantName + "' is not a cloud tenant"); String pemDeveloperKey = toSlime(request.getData()).get().field("key").asString(); PublicKey developerKey = KeyUtils.fromPemEncodedPublicKey(pemDeveloperKey); Principal user = controller.tenants().require(TenantName.from(tenantName), CloudTenant.class).developerKeys().get(developerKey); Slime root = new Slime(); controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, tenant -> { tenant = tenant.withoutDeveloperKey(developerKey); toSlime(root.setObject().setArray("keys"), tenant.get().developerKeys()); controller.tenants().store(tenant); }); return new SlimeJsonResponse(root); } private void toSlime(Cursor keysArray, Map<PublicKey, Principal> keys) { keys.forEach((key, principal) -> { Cursor keyObject = keysArray.addObject(); keyObject.setString("key", KeyUtils.toPem(key)); keyObject.setString("user", principal.getName()); }); } private HttpResponse addDeployKey(String tenantName, String applicationName, HttpRequest request) { String pemDeployKey = toSlime(request.getData()).get().field("key").asString(); PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey); Slime root = new Slime(); controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application -> { application = application.withDeployKey(deployKey); application.get().deployKeys().stream() .map(KeyUtils::toPem) .forEach(root.setObject().setArray("keys")::addString); controller.applications().store(application); }); return new SlimeJsonResponse(root); } private HttpResponse removeDeployKey(String tenantName, String applicationName, HttpRequest request) { String pemDeployKey = toSlime(request.getData()).get().field("key").asString(); PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey); Slime root = new Slime(); controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application -> { application = application.withoutDeployKey(deployKey); application.get().deployKeys().stream() .map(KeyUtils::toPem) .forEach(root.setObject().setArray("keys")::addString); controller.applications().store(application); }); return new SlimeJsonResponse(root); } private HttpResponse addSecretStore(String tenantName, String name, HttpRequest request) { if (controller.tenants().require(TenantName.from(tenantName)).type() != Tenant.Type.cloud) throw new IllegalArgumentException("Tenant '" + tenantName + "' is not a cloud tenant"); var data = toSlime(request.getData()).get(); var awsId = mandatory("awsId", data).asString(); var externalId = mandatory("externalId", data).asString(); var role = mandatory("role", data).asString(); var tenant = controller.tenants().require(TenantName.from(tenantName), CloudTenant.class); var tenantSecretStore = new TenantSecretStore(name, awsId, role); if (!tenantSecretStore.isValid()) { return ErrorResponse.badRequest("Secret store " + tenantSecretStore + " is invalid"); } if (tenant.tenantSecretStores().contains(tenantSecretStore)) { return ErrorResponse.badRequest("Secret store " + tenantSecretStore + " is already configured"); } controller.serviceRegistry().roleService().createTenantPolicy(TenantName.from(tenantName), name, awsId, role); controller.serviceRegistry().tenantSecretService().addSecretStore(tenant.name(), tenantSecretStore, externalId); // Store changes controller.tenants().lockOrThrow(tenant.name(), LockedTenant.Cloud.class, lockedTenant -> { lockedTenant = lockedTenant.withSecretStore(tenantSecretStore); controller.tenants().store(lockedTenant); }); tenant = controller.tenants().require(TenantName.from(tenantName), CloudTenant.class); var slime = new Slime(); toSlime(slime.setObject(), tenant.tenantSecretStores()); return new SlimeJsonResponse(slime); } private HttpResponse deleteSecretStore(String tenantName, String name, HttpRequest request) { var tenant = controller.tenants().require(TenantName.from(tenantName), CloudTenant.class); var optionalSecretStore = tenant.tenantSecretStores().stream() .filter(secretStore -> secretStore.getName().equals(name)) .findFirst(); if (optionalSecretStore.isEmpty()) return ErrorResponse.notFoundError("Could not delete secret store '" + name + "': Secret store not found"); var tenantSecretStore = optionalSecretStore.get(); controller.serviceRegistry().tenantSecretService().deleteSecretStore(tenant.name(), tenantSecretStore); controller.serviceRegistry().roleService().deleteTenantPolicy(tenant.name(), tenantSecretStore.getName(), tenantSecretStore.getRole()); controller.tenants().lockOrThrow(tenant.name(), LockedTenant.Cloud.class, lockedTenant -> { lockedTenant = lockedTenant.withoutSecretStore(tenantSecretStore); controller.tenants().store(lockedTenant); }); tenant = controller.tenants().require(TenantName.from(tenantName), CloudTenant.class); var slime = new Slime(); toSlime(slime.setObject(), tenant.tenantSecretStores()); return new SlimeJsonResponse(slime); } private HttpResponse allowArchiveAccess(String tenantName, HttpRequest request) { if (controller.tenants().require(TenantName.from(tenantName)).type() != Tenant.Type.cloud) throw new IllegalArgumentException("Tenant '" + tenantName + "' is not a cloud tenant"); var data = toSlime(request.getData()).get(); var role = mandatory("role", data).asString(); if (role.isBlank()) { return ErrorResponse.badRequest("Archive access role can't be whitespace only"); } controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, lockedTenant -> { lockedTenant = lockedTenant.withArchiveAccessRole(Optional.of(role)); controller.tenants().store(lockedTenant); }); return new MessageResponse("Archive access role set to '" + role + "' for tenant " + tenantName + "."); } private HttpResponse removeArchiveAccess(String tenantName) { if (controller.tenants().require(TenantName.from(tenantName)).type() != Tenant.Type.cloud) throw new IllegalArgumentException("Tenant '" + tenantName + "' is not a cloud tenant"); controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, lockedTenant -> { lockedTenant = lockedTenant.withArchiveAccessRole(Optional.empty()); controller.tenants().store(lockedTenant); }); return new MessageResponse("Archive access role removed for tenant " + tenantName + "."); } private HttpResponse patchApplication(String tenantName, String applicationName, HttpRequest request) { Inspector requestObject = toSlime(request.getData()).get(); StringJoiner messageBuilder = new StringJoiner("\n").setEmptyValue("No applicable changes."); controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application -> { Inspector majorVersionField = requestObject.field("majorVersion"); if (majorVersionField.valid()) { Integer majorVersion = majorVersionField.asLong() == 0 ? null : (int) majorVersionField.asLong(); application = application.withMajorVersion(majorVersion); messageBuilder.add("Set major version to " + (majorVersion == null ? "empty" : majorVersion)); } // TODO jonmv: Remove when clients are updated. Inspector pemDeployKeyField = requestObject.field("pemDeployKey"); if (pemDeployKeyField.valid()) { String pemDeployKey = pemDeployKeyField.asString(); PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey); application = application.withDeployKey(deployKey); messageBuilder.add("Added deploy key " + pemDeployKey); } controller.applications().store(application); }); return new MessageResponse(messageBuilder.toString()); } private Application getApplication(String tenantName, String applicationName) { TenantAndApplicationId applicationId = TenantAndApplicationId.from(tenantName, applicationName); return controller.applications().getApplication(applicationId) .orElseThrow(() -> new NotExistsException(applicationId + " not found")); } private Instance getInstance(String tenantName, String applicationName, String instanceName) { ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName); return controller.applications().getInstance(applicationId) .orElseThrow(() -> new NotExistsException(applicationId + " not found")); } private HttpResponse nodes(String tenantName, String applicationName, String instanceName, String environment, String region) { ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName); ZoneId zone = requireZone(environment, region); List<Node> nodes = controller.serviceRegistry().configServer().nodeRepository().list(zone, id); Slime slime = new Slime(); Cursor nodesArray = slime.setObject().setArray("nodes"); for (Node node : nodes) { Cursor nodeObject = nodesArray.addObject(); nodeObject.setString("hostname", node.hostname().value()); nodeObject.setString("state", valueOf(node.state())); node.reservedTo().ifPresent(tenant -> nodeObject.setString("reservedTo", tenant.value())); nodeObject.setString("orchestration", valueOf(node.serviceState())); nodeObject.setString("version", node.currentVersion().toString()); nodeObject.setString("flavor", node.flavor()); toSlime(node.resources(), nodeObject); nodeObject.setString("clusterId", node.clusterId()); nodeObject.setString("clusterType", valueOf(node.clusterType())); nodeObject.setBool("down", node.history().stream().anyMatch(event -> "down".equals(event.getEvent()))); nodeObject.setBool("retired", node.retired() || node.wantToRetire()); nodeObject.setBool("restarting", node.wantedRestartGeneration() > node.restartGeneration()); nodeObject.setBool("rebooting", node.wantedRebootGeneration() > node.rebootGeneration()); } return new SlimeJsonResponse(slime); } private HttpResponse clusters(String tenantName, String applicationName, String instanceName, String environment, String region) { ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName); ZoneId zone = requireZone(environment, region); com.yahoo.vespa.hosted.controller.api.integration.configserver.Application application = controller.serviceRegistry().configServer().nodeRepository().getApplication(zone, id); Slime slime = new Slime(); Cursor clustersObject = slime.setObject().setObject("clusters"); for (Cluster cluster : application.clusters().values()) { Cursor clusterObject = clustersObject.setObject(cluster.id().value()); clusterObject.setString("type", cluster.type().name()); toSlime(cluster.min(), clusterObject.setObject("min")); toSlime(cluster.max(), clusterObject.setObject("max")); toSlime(cluster.current(), clusterObject.setObject("current")); if (cluster.target().isPresent() && ! cluster.target().get().justNumbers().equals(cluster.current().justNumbers())) toSlime(cluster.target().get(), clusterObject.setObject("target")); cluster.suggested().ifPresent(suggested -> toSlime(suggested, clusterObject.setObject("suggested"))); utilizationToSlime(cluster.utilization(), clusterObject.setObject("utilization")); scalingEventsToSlime(cluster.scalingEvents(), clusterObject.setArray("scalingEvents")); clusterObject.setString("autoscalingStatus", cluster.autoscalingStatus()); clusterObject.setLong("scalingDuration", cluster.scalingDuration().toMillis()); clusterObject.setDouble("maxQueryGrowthRate", cluster.maxQueryGrowthRate()); clusterObject.setDouble("currentQueryFractionOfMax", cluster.currentQueryFractionOfMax()); } return new SlimeJsonResponse(slime); } private static String valueOf(Node.State state) { switch (state) { case failed: return "failed"; case parked: return "parked"; case dirty: return "dirty"; case ready: return "ready"; case active: return "active"; case inactive: return "inactive"; case reserved: return "reserved"; case provisioned: return "provisioned"; default: throw new IllegalArgumentException("Unexpected node state '" + state + "'."); } } static String valueOf(Node.ServiceState state) { switch (state) { case expectedUp: return "expectedUp"; case allowedDown: return "allowedDown"; case permanentlyDown: return "permanentlyDown"; case unorchestrated: return "unorchestrated"; case unknown: break; } return "unknown"; } private static String valueOf(Node.ClusterType type) { switch (type) { case admin: return "admin"; case content: return "content"; case container: return "container"; case combined: return "combined"; default: throw new IllegalArgumentException("Unexpected node cluster type '" + type + "'."); } } private static String valueOf(NodeResources.DiskSpeed diskSpeed) { switch (diskSpeed) { case fast : return "fast"; case slow : return "slow"; case any : return "any"; default: throw new IllegalArgumentException("Unknown disk speed '" + diskSpeed.name() + "'"); } } private static String valueOf(NodeResources.StorageType storageType) { switch (storageType) { case remote : return "remote"; case local : return "local"; case any : return "any"; default: throw new IllegalArgumentException("Unknown storage type '" + storageType.name() + "'"); } } private HttpResponse logs(String tenantName, String applicationName, String instanceName, String environment, String region, Map<String, String> queryParameters) { ApplicationId application = ApplicationId.from(tenantName, applicationName, instanceName); ZoneId zone = requireZone(environment, region); DeploymentId deployment = new DeploymentId(application, zone); InputStream logStream = controller.serviceRegistry().configServer().getLogs(deployment, queryParameters); return new HttpResponse(200) { @Override public void render(OutputStream outputStream) throws IOException { try (logStream) { logStream.transferTo(outputStream); } } }; } private HttpResponse supportAccess(String tenantName, String applicationName, String instanceName, String environment, String region, Map<String, String> queryParameters) { DeploymentId deployment = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName), requireZone(environment, region)); SupportAccess supportAccess = controller.supportAccess().forDeployment(deployment); return new SlimeJsonResponse(SupportAccessSerializer.toSlime(supportAccess, false, Optional.ofNullable(controller.clock().instant()))); } // TODO support access: only let tenants (not operators!) allow access // TODO support access: configurable period of access? private HttpResponse allowSupportAccess(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) { DeploymentId deployment = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName), requireZone(environment, region)); Principal principal = requireUserPrincipal(request); SupportAccess allowed = controller.supportAccess().allow(deployment, Instant.now().plus(7, ChronoUnit.DAYS), principal.getName()); return new SlimeJsonResponse(SupportAccessSerializer.toSlime(allowed, false, Optional.ofNullable(controller.clock().instant()))); } private HttpResponse disallowSupportAccess(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) { DeploymentId deployment = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName), requireZone(environment, region)); Principal principal = requireUserPrincipal(request); SupportAccess disallowed = controller.supportAccess().disallow(deployment, principal.getName()); return new SlimeJsonResponse(SupportAccessSerializer.toSlime(disallowed, false, Optional.ofNullable(controller.clock().instant()))); } private HttpResponse metrics(String tenantName, String applicationName, String instanceName, String environment, String region) { ApplicationId application = ApplicationId.from(tenantName, applicationName, instanceName); ZoneId zone = requireZone(environment, region); DeploymentId deployment = new DeploymentId(application, zone); List<ProtonMetrics> protonMetrics = controller.serviceRegistry().configServer().getProtonMetrics(deployment); return buildResponseFromProtonMetrics(protonMetrics); } private JsonResponse buildResponseFromProtonMetrics(List<ProtonMetrics> protonMetrics) { try { var jsonObject = jsonMapper.createObjectNode(); var jsonArray = jsonMapper.createArrayNode(); for (ProtonMetrics metrics : protonMetrics) { jsonArray.add(metrics.toJson()); } jsonObject.set("metrics", jsonArray); return new JsonResponse(200, jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject)); } catch (JsonProcessingException e) { log.log(Level.WARNING, "Unable to build JsonResponse with Proton data: " + e.getMessage(), e); return new JsonResponse(500, ""); } } private HttpResponse trigger(ApplicationId id, JobType type, HttpRequest request) { Inspector requestObject = toSlime(request.getData()).get(); boolean requireTests = ! requestObject.field("skipTests").asBool(); boolean reTrigger = requestObject.field("reTrigger").asBool(); String triggered = reTrigger ? controller.applications().deploymentTrigger() .reTrigger(id, type).type().jobName() : controller.applications().deploymentTrigger() .forceTrigger(id, type, request.getJDiscRequest().getUserPrincipal().getName(), requireTests) .stream().map(job -> job.type().jobName()).collect(joining(", ")); return new MessageResponse(triggered.isEmpty() ? "Job " + type.jobName() + " for " + id + " not triggered" : "Triggered " + triggered + " for " + id); } private HttpResponse pause(ApplicationId id, JobType type) { Instant until = controller.clock().instant().plus(DeploymentTrigger.maxPause); controller.applications().deploymentTrigger().pauseJob(id, type, until); return new MessageResponse(type.jobName() + " for " + id + " paused for " + DeploymentTrigger.maxPause); } private HttpResponse resume(ApplicationId id, JobType type) { controller.applications().deploymentTrigger().resumeJob(id, type); return new MessageResponse(type.jobName() + " for " + id + " resumed"); } private void toSlime(Cursor object, Application application, HttpRequest request) { object.setString("tenant", application.id().tenant().value()); object.setString("application", application.id().application().value()); object.setString("deployments", withPath("/application/v4" + "/tenant/" + application.id().tenant().value() + "/application/" + application.id().application().value() + "/job/", request.getUri()).toString()); DeploymentStatus status = controller.jobController().deploymentStatus(application); application.latestVersion().ifPresent(version -> toSlime(version, object.setObject("latestVersion"))); application.projectId().ifPresent(id -> object.setLong("projectId", id)); // TODO jonmv: Remove this when users are updated. application.instances().values().stream().findFirst().ifPresent(instance -> { // Currently deploying change if ( ! instance.change().isEmpty()) toSlime(object.setObject("deploying"), instance.change()); // Outstanding change if ( ! status.outstandingChange(instance.name()).isEmpty()) toSlime(object.setObject("outstandingChange"), status.outstandingChange(instance.name())); }); application.majorVersion().ifPresent(majorVersion -> object.setLong("majorVersion", majorVersion)); Cursor instancesArray = object.setArray("instances"); for (Instance instance : showOnlyProductionInstances(request) ? application.productionInstances().values() : application.instances().values()) toSlime(instancesArray.addObject(), status, instance, application.deploymentSpec(), request); application.deployKeys().stream().map(KeyUtils::toPem).forEach(object.setArray("pemDeployKeys")::addString); // Metrics Cursor metricsObject = object.setObject("metrics"); metricsObject.setDouble("queryServiceQuality", application.metrics().queryServiceQuality()); metricsObject.setDouble("writeServiceQuality", application.metrics().writeServiceQuality()); // Activity Cursor activity = object.setObject("activity"); application.activity().lastQueried().ifPresent(instant -> activity.setLong("lastQueried", instant.toEpochMilli())); application.activity().lastWritten().ifPresent(instant -> activity.setLong("lastWritten", instant.toEpochMilli())); application.activity().lastQueriesPerSecond().ifPresent(value -> activity.setDouble("lastQueriesPerSecond", value)); application.activity().lastWritesPerSecond().ifPresent(value -> activity.setDouble("lastWritesPerSecond", value)); application.ownershipIssueId().ifPresent(issueId -> object.setString("ownershipIssueId", issueId.value())); application.owner().ifPresent(owner -> object.setString("owner", owner.username())); application.deploymentIssueId().ifPresent(issueId -> object.setString("deploymentIssueId", issueId.value())); } // TODO: Eliminate duplicated code in this and toSlime(Cursor, Instance, DeploymentStatus, HttpRequest) private void toSlime(Cursor object, DeploymentStatus status, Instance instance, DeploymentSpec deploymentSpec, HttpRequest request) { object.setString("instance", instance.name().value()); if (deploymentSpec.instance(instance.name()).isPresent()) { // Jobs sorted according to deployment spec List<JobStatus> jobStatus = controller.applications().deploymentTrigger() .steps(deploymentSpec.requireInstance(instance.name())) .sortedJobs(status.instanceJobs(instance.name()).values()); if ( ! instance.change().isEmpty()) toSlime(object.setObject("deploying"), instance.change()); // Outstanding change if ( ! status.outstandingChange(instance.name()).isEmpty()) toSlime(object.setObject("outstandingChange"), status.outstandingChange(instance.name())); // Change blockers Cursor changeBlockers = object.setArray("changeBlockers"); deploymentSpec.instance(instance.name()).ifPresent(spec -> spec.changeBlocker().forEach(changeBlocker -> { Cursor changeBlockerObject = changeBlockers.addObject(); changeBlockerObject.setBool("versions", changeBlocker.blocksVersions()); changeBlockerObject.setBool("revisions", changeBlocker.blocksRevisions()); changeBlockerObject.setString("timeZone", changeBlocker.window().zone().getId()); Cursor days = changeBlockerObject.setArray("days"); changeBlocker.window().days().stream().map(DayOfWeek::getValue).forEach(days::addLong); Cursor hours = changeBlockerObject.setArray("hours"); changeBlocker.window().hours().forEach(hours::addLong); })); } // Global endpoints globalEndpointsToSlime(object, instance); // Deployments sorted according to deployment spec List<Deployment> deployments = deploymentSpec.instance(instance.name()) .map(spec -> new DeploymentSteps(spec, controller::system)) .map(steps -> steps.sortedDeployments(instance.deployments().values())) .orElse(List.copyOf(instance.deployments().values())); Cursor deploymentsArray = object.setArray("deployments"); for (Deployment deployment : deployments) { Cursor deploymentObject = deploymentsArray.addObject(); // Rotation status for this deployment if (deployment.zone().environment() == Environment.prod && ! instance.rotations().isEmpty()) toSlime(instance.rotations(), instance.rotationStatus(), deployment, deploymentObject); if (recurseOverDeployments(request)) // List full deployment information when recursive. toSlime(deploymentObject, new DeploymentId(instance.id(), deployment.zone()), deployment, request); else { deploymentObject.setString("environment", deployment.zone().environment().value()); deploymentObject.setString("region", deployment.zone().region().value()); deploymentObject.setString("url", withPath(request.getUri().getPath() + "/instance/" + instance.name().value() + "/environment/" + deployment.zone().environment().value() + "/region/" + deployment.zone().region().value(), request.getUri()).toString()); } } } // TODO(mpolden): Remove once legacy dashboard and integration tests stop expecting these fields private void globalEndpointsToSlime(Cursor object, Instance instance) { var globalEndpointUrls = new LinkedHashSet<String>(); // Add global endpoints backed by rotations controller.routing().endpointsOf(instance.id()) .requiresRotation() .not().legacy() // Hide legacy names .asList().stream() .map(Endpoint::url) .map(URI::toString) .forEach(globalEndpointUrls::add); var globalRotationsArray = object.setArray("globalRotations"); globalEndpointUrls.forEach(globalRotationsArray::addString); // Legacy field. Identifies the first assigned rotation, if any. instance.rotations().stream() .map(AssignedRotation::rotationId) .findFirst() .ifPresent(rotation -> object.setString("rotationId", rotation.asString())); } private void toSlime(Cursor object, Instance instance, DeploymentStatus status, HttpRequest request) { Application application = status.application(); object.setString("tenant", instance.id().tenant().value()); object.setString("application", instance.id().application().value()); object.setString("instance", instance.id().instance().value()); object.setString("deployments", withPath("/application/v4" + "/tenant/" + instance.id().tenant().value() + "/application/" + instance.id().application().value() + "/instance/" + instance.id().instance().value() + "/job/", request.getUri()).toString()); application.latestVersion().ifPresent(version -> { sourceRevisionToSlime(version.source(), object.setObject("source")); version.sourceUrl().ifPresent(url -> object.setString("sourceUrl", url)); version.commit().ifPresent(commit -> object.setString("commit", commit)); }); application.projectId().ifPresent(id -> object.setLong("projectId", id)); if (application.deploymentSpec().instance(instance.name()).isPresent()) { // Jobs sorted according to deployment spec List<JobStatus> jobStatus = controller.applications().deploymentTrigger() .steps(application.deploymentSpec().requireInstance(instance.name())) .sortedJobs(status.instanceJobs(instance.name()).values()); if ( ! instance.change().isEmpty()) toSlime(object.setObject("deploying"), instance.change()); // Outstanding change if ( ! status.outstandingChange(instance.name()).isEmpty()) toSlime(object.setObject("outstandingChange"), status.outstandingChange(instance.name())); // Change blockers Cursor changeBlockers = object.setArray("changeBlockers"); application.deploymentSpec().instance(instance.name()).ifPresent(spec -> spec.changeBlocker().forEach(changeBlocker -> { Cursor changeBlockerObject = changeBlockers.addObject(); changeBlockerObject.setBool("versions", changeBlocker.blocksVersions()); changeBlockerObject.setBool("revisions", changeBlocker.blocksRevisions()); changeBlockerObject.setString("timeZone", changeBlocker.window().zone().getId()); Cursor days = changeBlockerObject.setArray("days"); changeBlocker.window().days().stream().map(DayOfWeek::getValue).forEach(days::addLong); Cursor hours = changeBlockerObject.setArray("hours"); changeBlocker.window().hours().forEach(hours::addLong); })); } application.majorVersion().ifPresent(majorVersion -> object.setLong("majorVersion", majorVersion)); // Global endpoint globalEndpointsToSlime(object, instance); // Deployments sorted according to deployment spec List<Deployment> deployments = application.deploymentSpec().instance(instance.name()) .map(spec -> new DeploymentSteps(spec, controller::system)) .map(steps -> steps.sortedDeployments(instance.deployments().values())) .orElse(List.copyOf(instance.deployments().values())); Cursor instancesArray = object.setArray("instances"); for (Deployment deployment : deployments) { Cursor deploymentObject = instancesArray.addObject(); // Rotation status for this deployment if (deployment.zone().environment() == Environment.prod) { // 0 rotations: No fields written // 1 rotation : Write legacy field and endpointStatus field // >1 rotation : Write only endpointStatus field if (instance.rotations().size() == 1) { // TODO(mpolden): Stop writing this field once clients stop expecting it toSlime(instance.rotationStatus().of(instance.rotations().get(0).rotationId(), deployment), deploymentObject); } if ( ! recurseOverDeployments(request) && ! instance.rotations().isEmpty()) { // TODO jonmv: clean up when clients have converged. toSlime(instance.rotations(), instance.rotationStatus(), deployment, deploymentObject); } } if (recurseOverDeployments(request)) // List full deployment information when recursive. toSlime(deploymentObject, new DeploymentId(instance.id(), deployment.zone()), deployment, request); else { deploymentObject.setString("environment", deployment.zone().environment().value()); deploymentObject.setString("region", deployment.zone().region().value()); deploymentObject.setString("instance", instance.id().instance().value()); // pointless deploymentObject.setString("url", withPath(request.getUri().getPath() + "/environment/" + deployment.zone().environment().value() + "/region/" + deployment.zone().region().value(), request.getUri()).toString()); } } // Add dummy values for not-yet-existent prod deployments. status.jobSteps().keySet().stream() .filter(job -> job.application().instance().equals(instance.name())) .filter(job -> job.type().isProduction() && job.type().isDeployment()) .map(job -> job.type().zone(controller.system())) .filter(zone -> ! instance.deployments().containsKey(zone)) .forEach(zone -> { Cursor deploymentObject = instancesArray.addObject(); deploymentObject.setString("environment", zone.environment().value()); deploymentObject.setString("region", zone.region().value()); }); // TODO jonmv: Remove when clients are updated application.deployKeys().stream().findFirst().ifPresent(key -> object.setString("pemDeployKey", KeyUtils.toPem(key))); application.deployKeys().stream().map(KeyUtils::toPem).forEach(object.setArray("pemDeployKeys")::addString); // Metrics Cursor metricsObject = object.setObject("metrics"); metricsObject.setDouble("queryServiceQuality", application.metrics().queryServiceQuality()); metricsObject.setDouble("writeServiceQuality", application.metrics().writeServiceQuality()); // Activity Cursor activity = object.setObject("activity"); application.activity().lastQueried().ifPresent(instant -> activity.setLong("lastQueried", instant.toEpochMilli())); application.activity().lastWritten().ifPresent(instant -> activity.setLong("lastWritten", instant.toEpochMilli())); application.activity().lastQueriesPerSecond().ifPresent(value -> activity.setDouble("lastQueriesPerSecond", value)); application.activity().lastWritesPerSecond().ifPresent(value -> activity.setDouble("lastWritesPerSecond", value)); application.ownershipIssueId().ifPresent(issueId -> object.setString("ownershipIssueId", issueId.value())); application.owner().ifPresent(owner -> object.setString("owner", owner.username())); application.deploymentIssueId().ifPresent(issueId -> object.setString("deploymentIssueId", issueId.value())); } private HttpResponse deployment(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) { ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName); Instance instance = controller.applications().getInstance(id) .orElseThrow(() -> new NotExistsException(id + " not found")); DeploymentId deploymentId = new DeploymentId(instance.id(), requireZone(environment, region)); Deployment deployment = instance.deployments().get(deploymentId.zoneId()); if (deployment == null) throw new NotExistsException(instance + " is not deployed in " + deploymentId.zoneId()); Slime slime = new Slime(); toSlime(slime.setObject(), deploymentId, deployment, request); return new SlimeJsonResponse(slime); } private void toSlime(Cursor object, Change change) { change.platform().ifPresent(version -> object.setString("version", version.toString())); change.application() .filter(version -> !version.isUnknown()) .ifPresent(version -> toSlime(version, object.setObject("revision"))); } private void toSlime(Endpoint endpoint, Cursor object) { object.setString("cluster", endpoint.cluster().value()); object.setBool("tls", endpoint.tls()); object.setString("url", endpoint.url().toString()); object.setString("scope", endpointScopeString(endpoint.scope())); object.setString("routingMethod", routingMethodString(endpoint.routingMethod())); object.setBool("legacy", endpoint.legacy()); } private void toSlime(Cursor response, DeploymentId deploymentId, Deployment deployment, HttpRequest request) { response.setString("tenant", deploymentId.applicationId().tenant().value()); response.setString("application", deploymentId.applicationId().application().value()); response.setString("instance", deploymentId.applicationId().instance().value()); // pointless response.setString("environment", deploymentId.zoneId().environment().value()); response.setString("region", deploymentId.zoneId().region().value()); var application = controller.applications().requireApplication(TenantAndApplicationId.from(deploymentId.applicationId())); // Add zone endpoints boolean legacyEndpoints = request.getBooleanProperty("includeLegacyEndpoints"); var endpointArray = response.setArray("endpoints"); EndpointList zoneEndpoints = controller.routing().endpointsOf(deploymentId) .scope(Endpoint.Scope.zone); if (!legacyEndpoints) { zoneEndpoints = zoneEndpoints.not().legacy(); } for (var endpoint : controller.routing().directEndpoints(zoneEndpoints, deploymentId.applicationId())) { toSlime(endpoint, endpointArray.addObject()); } // Add global endpoints EndpointList globalEndpoints = controller.routing().endpointsOf(application, deploymentId.applicationId().instance()) .targets(deploymentId.zoneId()); if (!legacyEndpoints) { globalEndpoints = globalEndpoints.not().legacy(); } for (var endpoint : controller.routing().directEndpoints(globalEndpoints, deploymentId.applicationId())) { toSlime(endpoint, endpointArray.addObject()); } response.setString("clusters", withPath(toPath(deploymentId) + "/clusters", request.getUri()).toString()); response.setString("nodes", withPathAndQuery("/zone/v2/" + deploymentId.zoneId().environment() + "/" + deploymentId.zoneId().region() + "/nodes/v2/node/", "recursive=true&application=" + deploymentId.applicationId().tenant() + "." + deploymentId.applicationId().application() + "." + deploymentId.applicationId().instance(), request.getUri()).toString()); response.setString("yamasUrl", monitoringSystemUri(deploymentId).toString()); response.setString("version", deployment.version().toFullString()); response.setString("revision", deployment.applicationVersion().id()); response.setLong("deployTimeEpochMs", deployment.at().toEpochMilli()); controller.zoneRegistry().getDeploymentTimeToLive(deploymentId.zoneId()) .ifPresent(deploymentTimeToLive -> response.setLong("expiryTimeEpochMs", deployment.at().plus(deploymentTimeToLive).toEpochMilli())); DeploymentStatus status = controller.jobController().deploymentStatus(application); application.projectId().ifPresent(i -> response.setString("screwdriverId", String.valueOf(i))); sourceRevisionToSlime(deployment.applicationVersion().source(), response); var instance = application.instances().get(deploymentId.applicationId().instance()); if (instance != null) { if (!instance.rotations().isEmpty() && deployment.zone().environment() == Environment.prod) toSlime(instance.rotations(), instance.rotationStatus(), deployment, response); JobType.from(controller.system(), deployment.zone()) .map(type -> new JobId(instance.id(), type)) .map(status.jobSteps()::get) .ifPresent(stepStatus -> { JobControllerApiHandlerHelper.applicationVersionToSlime( response.setObject("applicationVersion"), deployment.applicationVersion()); if (!status.jobsToRun().containsKey(stepStatus.job().get())) response.setString("status", "complete"); else if (stepStatus.readyAt(instance.change()).map(controller.clock().instant()::isBefore).orElse(true)) response.setString("status", "pending"); else response.setString("status", "running"); }); } controller.archiveBucketDb().archiveUriFor(deploymentId.zoneId(), deploymentId.applicationId().tenant()) .ifPresent(archiveUri -> response.setString("archiveUri", archiveUri.toString())); Cursor activity = response.setObject("activity"); deployment.activity().lastQueried().ifPresent(instant -> activity.setLong("lastQueried", instant.toEpochMilli())); deployment.activity().lastWritten().ifPresent(instant -> activity.setLong("lastWritten", instant.toEpochMilli())); deployment.activity().lastQueriesPerSecond().ifPresent(value -> activity.setDouble("lastQueriesPerSecond", value)); deployment.activity().lastWritesPerSecond().ifPresent(value -> activity.setDouble("lastWritesPerSecond", value)); // Metrics DeploymentMetrics metrics = deployment.metrics(); Cursor metricsObject = response.setObject("metrics"); metricsObject.setDouble("queriesPerSecond", metrics.queriesPerSecond()); metricsObject.setDouble("writesPerSecond", metrics.writesPerSecond()); metricsObject.setDouble("documentCount", metrics.documentCount()); metricsObject.setDouble("queryLatencyMillis", metrics.queryLatencyMillis()); metricsObject.setDouble("writeLatencyMillis", metrics.writeLatencyMillis()); metrics.instant().ifPresent(instant -> metricsObject.setLong("lastUpdated", instant.toEpochMilli())); } private void toSlime(ApplicationVersion applicationVersion, Cursor object) { if ( ! applicationVersion.isUnknown()) { object.setLong("buildNumber", applicationVersion.buildNumber().getAsLong()); object.setString("hash", applicationVersion.id()); sourceRevisionToSlime(applicationVersion.source(), object.setObject("source")); applicationVersion.sourceUrl().ifPresent(url -> object.setString("sourceUrl", url)); applicationVersion.commit().ifPresent(commit -> object.setString("commit", commit)); } } private void sourceRevisionToSlime(Optional<SourceRevision> revision, Cursor object) { if (revision.isEmpty()) return; object.setString("gitRepository", revision.get().repository()); object.setString("gitBranch", revision.get().branch()); object.setString("gitCommit", revision.get().commit()); } private void toSlime(RotationState state, Cursor object) { Cursor bcpStatus = object.setObject("bcpStatus"); bcpStatus.setString("rotationStatus", rotationStateString(state)); } private void toSlime(List<AssignedRotation> rotations, RotationStatus status, Deployment deployment, Cursor object) { var array = object.setArray("endpointStatus"); for (var rotation : rotations) { var statusObject = array.addObject(); var targets = status.of(rotation.rotationId()); statusObject.setString("endpointId", rotation.endpointId().id()); statusObject.setString("rotationId", rotation.rotationId().asString()); statusObject.setString("clusterId", rotation.clusterId().value()); statusObject.setString("status", rotationStateString(status.of(rotation.rotationId(), deployment))); statusObject.setLong("lastUpdated", targets.lastUpdated().toEpochMilli()); } } private URI monitoringSystemUri(DeploymentId deploymentId) { return controller.zoneRegistry().getMonitoringSystemUri(deploymentId); } /** * Returns a non-broken, released version at least as old as the oldest platform the given application is on. * * If no known version is applicable, the newest version at least as old as the oldest platform is selected, * among all versions released for this system. If no such versions exists, throws an IllegalStateException. */ private Version compileVersion(TenantAndApplicationId id) { Version oldestPlatform = controller.applications().oldestInstalledPlatform(id); VersionStatus versionStatus = controller.readVersionStatus(); return versionStatus.versions().stream() .filter(version -> version.confidence().equalOrHigherThan(VespaVersion.Confidence.low)) .filter(VespaVersion::isReleased) .map(VespaVersion::versionNumber) .filter(version -> ! version.isAfter(oldestPlatform)) .max(Comparator.naturalOrder()) .orElseGet(() -> controller.mavenRepository().metadata().versions().stream() .filter(version -> ! version.isAfter(oldestPlatform)) .filter(version -> ! versionStatus.versions().stream() .map(VespaVersion::versionNumber) .collect(Collectors.toSet()).contains(version)) .max(Comparator.naturalOrder()) .orElseThrow(() -> new IllegalStateException("No available releases of " + controller.mavenRepository().artifactId()))); } private HttpResponse setGlobalRotationOverride(String tenantName, String applicationName, String instanceName, String environment, String region, boolean inService, HttpRequest request) { Instance instance = controller.applications().requireInstance(ApplicationId.from(tenantName, applicationName, instanceName)); ZoneId zone = requireZone(environment, region); Deployment deployment = instance.deployments().get(zone); if (deployment == null) { throw new NotExistsException(instance + " has no deployment in " + zone); } // The order here matters because setGlobalRotationStatus involves an external request that may fail. // TODO(mpolden): Set only one of these when only one kind of global endpoints are supported per zone. var deploymentId = new DeploymentId(instance.id(), zone); setGlobalRotationStatus(deploymentId, inService, request); setGlobalEndpointStatus(deploymentId, inService, request); return new MessageResponse(String.format("Successfully set %s in %s %s service", instance.id().toShortString(), zone, inService ? "in" : "out of")); } /** Set the global endpoint status for given deployment. This only applies to global endpoints backed by a cloud service */ private void setGlobalEndpointStatus(DeploymentId deployment, boolean inService, HttpRequest request) { var agent = isOperator(request) ? GlobalRouting.Agent.operator : GlobalRouting.Agent.tenant; var status = inService ? GlobalRouting.Status.in : GlobalRouting.Status.out; controller.routing().policies().setGlobalRoutingStatus(deployment, status, agent); } /** Set the global rotation status for given deployment. This only applies to global endpoints backed by a rotation */ private void setGlobalRotationStatus(DeploymentId deployment, boolean inService, HttpRequest request) { var requestData = toSlime(request.getData()).get(); var reason = mandatory("reason", requestData).asString(); var agent = isOperator(request) ? GlobalRouting.Agent.operator : GlobalRouting.Agent.tenant; long timestamp = controller.clock().instant().getEpochSecond(); var status = inService ? EndpointStatus.Status.in : EndpointStatus.Status.out; var endpointStatus = new EndpointStatus(status, reason, agent.name(), timestamp); controller.routing().setGlobalRotationStatus(deployment, endpointStatus); } private HttpResponse getGlobalRotationOverride(String tenantName, String applicationName, String instanceName, String environment, String region) { DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName), requireZone(environment, region)); Slime slime = new Slime(); Cursor array = slime.setObject().setArray("globalrotationoverride"); controller.routing().globalRotationStatus(deploymentId) .forEach((endpoint, status) -> { array.addString(endpoint.upstreamIdOf(deploymentId)); Cursor statusObject = array.addObject(); statusObject.setString("status", status.getStatus().name()); statusObject.setString("reason", status.getReason() == null ? "" : status.getReason()); statusObject.setString("agent", status.getAgent() == null ? "" : status.getAgent()); statusObject.setLong("timestamp", status.getEpoch()); }); return new SlimeJsonResponse(slime); } private HttpResponse rotationStatus(String tenantName, String applicationName, String instanceName, String environment, String region, Optional<String> endpointId) { ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName); Instance instance = controller.applications().requireInstance(applicationId); ZoneId zone = requireZone(environment, region); RotationId rotation = findRotationId(instance, endpointId); Deployment deployment = instance.deployments().get(zone); if (deployment == null) { throw new NotExistsException(instance + " has no deployment in " + zone); } Slime slime = new Slime(); Cursor response = slime.setObject(); toSlime(instance.rotationStatus().of(rotation, deployment), response); return new SlimeJsonResponse(slime); } private HttpResponse metering(String tenant, String application, HttpRequest request) { Slime slime = new Slime(); Cursor root = slime.setObject(); MeteringData meteringData = controller.serviceRegistry() .meteringService() .getMeteringData(TenantName.from(tenant), ApplicationName.from(application)); ResourceAllocation currentSnapshot = meteringData.getCurrentSnapshot(); Cursor currentRate = root.setObject("currentrate"); currentRate.setDouble("cpu", currentSnapshot.getCpuCores()); currentRate.setDouble("mem", currentSnapshot.getMemoryGb()); currentRate.setDouble("disk", currentSnapshot.getDiskGb()); ResourceAllocation thisMonth = meteringData.getThisMonth(); Cursor thismonth = root.setObject("thismonth"); thismonth.setDouble("cpu", thisMonth.getCpuCores()); thismonth.setDouble("mem", thisMonth.getMemoryGb()); thismonth.setDouble("disk", thisMonth.getDiskGb()); ResourceAllocation lastMonth = meteringData.getLastMonth(); Cursor lastmonth = root.setObject("lastmonth"); lastmonth.setDouble("cpu", lastMonth.getCpuCores()); lastmonth.setDouble("mem", lastMonth.getMemoryGb()); lastmonth.setDouble("disk", lastMonth.getDiskGb()); Map<ApplicationId, List<ResourceSnapshot>> history = meteringData.getSnapshotHistory(); Cursor details = root.setObject("details"); Cursor detailsCpu = details.setObject("cpu"); Cursor detailsMem = details.setObject("mem"); Cursor detailsDisk = details.setObject("disk"); history.forEach((applicationId, resources) -> { String instanceName = applicationId.instance().value(); Cursor detailsCpuApp = detailsCpu.setObject(instanceName); Cursor detailsMemApp = detailsMem.setObject(instanceName); Cursor detailsDiskApp = detailsDisk.setObject(instanceName); Cursor detailsCpuData = detailsCpuApp.setArray("data"); Cursor detailsMemData = detailsMemApp.setArray("data"); Cursor detailsDiskData = detailsDiskApp.setArray("data"); resources.forEach(resourceSnapshot -> { Cursor cpu = detailsCpuData.addObject(); cpu.setLong("unixms", resourceSnapshot.getTimestamp().toEpochMilli()); cpu.setDouble("value", resourceSnapshot.getCpuCores()); Cursor mem = detailsMemData.addObject(); mem.setLong("unixms", resourceSnapshot.getTimestamp().toEpochMilli()); mem.setDouble("value", resourceSnapshot.getMemoryGb()); Cursor disk = detailsDiskData.addObject(); disk.setLong("unixms", resourceSnapshot.getTimestamp().toEpochMilli()); disk.setDouble("value", resourceSnapshot.getDiskGb()); }); }); return new SlimeJsonResponse(slime); } private HttpResponse deploying(String tenantName, String applicationName, String instanceName, HttpRequest request) { Instance instance = controller.applications().requireInstance(ApplicationId.from(tenantName, applicationName, instanceName)); Slime slime = new Slime(); Cursor root = slime.setObject(); if ( ! instance.change().isEmpty()) { instance.change().platform().ifPresent(version -> root.setString("platform", version.toString())); instance.change().application().ifPresent(applicationVersion -> root.setString("application", applicationVersion.id())); root.setBool("pinned", instance.change().isPinned()); } return new SlimeJsonResponse(slime); } private HttpResponse suspended(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) { DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName), requireZone(environment, region)); boolean suspended = controller.applications().isSuspended(deploymentId); Slime slime = new Slime(); Cursor response = slime.setObject(); response.setBool("suspended", suspended); return new SlimeJsonResponse(slime); } private HttpResponse services(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) { ApplicationView applicationView = controller.getApplicationView(tenantName, applicationName, instanceName, environment, region); ZoneId zone = requireZone(environment, region); ServiceApiResponse response = new ServiceApiResponse(zone, new ApplicationId.Builder().tenant(tenantName).applicationName(applicationName).instanceName(instanceName).build(), List.of(controller.zoneRegistry().getConfigServerVipUri(zone)), request.getUri()); response.setResponse(applicationView); return response; } private HttpResponse service(String tenantName, String applicationName, String instanceName, String environment, String region, String serviceName, String restPath, HttpRequest request) { DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName), requireZone(environment, region)); if ("container-clustercontroller".equals((serviceName)) && restPath.contains("/status/")) { String[] parts = restPath.split("/status/"); String result = controller.serviceRegistry().configServer().getClusterControllerStatus(deploymentId, parts[0], parts[1]); return new HtmlResponse(result); } Map<?,?> result = controller.serviceRegistry().configServer().getServiceApiResponse(deploymentId, serviceName, restPath); ServiceApiResponse response = new ServiceApiResponse(deploymentId.zoneId(), deploymentId.applicationId(), List.of(controller.zoneRegistry().getConfigServerVipUri(deploymentId.zoneId())), request.getUri()); response.setResponse(result, serviceName, restPath); return response; } private HttpResponse content(String tenantName, String applicationName, String instanceName, String environment, String region, String restPath, HttpRequest request) { DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName), requireZone(environment, region)); return controller.serviceRegistry().configServer().getApplicationPackageContent(deploymentId, "/" + restPath, request.getUri()); } private HttpResponse updateTenant(String tenantName, HttpRequest request) { getTenantOrThrow(tenantName); TenantName tenant = TenantName.from(tenantName); Inspector requestObject = toSlime(request.getData()).get(); controller.tenants().update(accessControlRequests.specification(tenant, requestObject), accessControlRequests.credentials(tenant, requestObject, request.getJDiscRequest())); return tenant(controller.tenants().require(TenantName.from(tenantName)), request); } private HttpResponse createTenant(String tenantName, HttpRequest request) { TenantName tenant = TenantName.from(tenantName); Inspector requestObject = toSlime(request.getData()).get(); controller.tenants().create(accessControlRequests.specification(tenant, requestObject), accessControlRequests.credentials(tenant, requestObject, request.getJDiscRequest())); return tenant(controller.tenants().require(TenantName.from(tenantName)), request); } private HttpResponse createApplication(String tenantName, String applicationName, HttpRequest request) { Inspector requestObject = toSlime(request.getData()).get(); TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName); Credentials credentials = accessControlRequests.credentials(id.tenant(), requestObject, request.getJDiscRequest()); Application application = controller.applications().createApplication(id, credentials); Slime slime = new Slime(); toSlime(id, slime.setObject(), request); return new SlimeJsonResponse(slime); } // TODO jonmv: Remove when clients are updated. private HttpResponse createInstance(String tenantName, String applicationName, String instanceName, HttpRequest request) { TenantAndApplicationId applicationId = TenantAndApplicationId.from(tenantName, applicationName); if (controller.applications().getApplication(applicationId).isEmpty()) createApplication(tenantName, applicationName, request); controller.applications().createInstance(applicationId.instance(instanceName)); Slime slime = new Slime(); toSlime(applicationId.instance(instanceName), slime.setObject(), request); return new SlimeJsonResponse(slime); } /** Trigger deployment of the given Vespa version if a valid one is given, e.g., "7.8.9". */ private HttpResponse deployPlatform(String tenantName, String applicationName, String instanceName, boolean pin, HttpRequest request) { String versionString = readToString(request.getData()); ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName); StringBuilder response = new StringBuilder(); controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application -> { Version version = Version.fromString(versionString); VersionStatus versionStatus = controller.readVersionStatus(); if (version.equals(Version.emptyVersion)) version = controller.systemVersion(versionStatus); if (!versionStatus.isActive(version)) throw new IllegalArgumentException("Cannot trigger deployment of version '" + version + "': " + "Version is not active in this system. " + "Active versions: " + versionStatus.versions() .stream() .map(VespaVersion::versionNumber) .map(Version::toString) .collect(joining(", "))); Change change = Change.of(version); if (pin) change = change.withPin(); controller.applications().deploymentTrigger().forceChange(id, change); response.append("Triggered ").append(change).append(" for ").append(id); }); return new MessageResponse(response.toString()); } /** Trigger deployment to the last known application package for the given application. */ private HttpResponse deployApplication(String tenantName, String applicationName, String instanceName, HttpRequest request) { ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName); StringBuilder response = new StringBuilder(); controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application -> { Change change = Change.of(application.get().latestVersion().get()); controller.applications().deploymentTrigger().forceChange(id, change); response.append("Triggered ").append(change).append(" for ").append(id); }); return new MessageResponse(response.toString()); } /** Cancel ongoing change for given application, e.g., everything with {"cancel":"all"} */ private HttpResponse cancelDeploy(String tenantName, String applicationName, String instanceName, String choice) { ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName); StringBuilder response = new StringBuilder(); controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application -> { Change change = application.get().require(id.instance()).change(); if (change.isEmpty()) { response.append("No deployment in progress for ").append(id).append(" at this time"); return; } ChangesToCancel cancel = ChangesToCancel.valueOf(choice.toUpperCase()); controller.applications().deploymentTrigger().cancelChange(id, cancel); response.append("Changed deployment from '").append(change).append("' to '").append(controller.applications().requireInstance(id).change()).append("' for ").append(id); }); return new MessageResponse(response.toString()); } /** Schedule reindexing of an application, or a subset of clusters, possibly on a subset of documents. */ private HttpResponse reindex(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) { ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName); ZoneId zone = requireZone(environment, region); List<String> clusterNames = Optional.ofNullable(request.getProperty("clusterId")).stream() .flatMap(clusters -> Stream.of(clusters.split(","))) .filter(cluster -> ! cluster.isBlank()) .collect(toUnmodifiableList()); List<String> documentTypes = Optional.ofNullable(request.getProperty("documentType")).stream() .flatMap(types -> Stream.of(types.split(","))) .filter(type -> ! type.isBlank()) .collect(toUnmodifiableList()); controller.applications().reindex(id, zone, clusterNames, documentTypes, request.getBooleanProperty("indexedOnly")); return new MessageResponse("Requested reindexing of " + id + " in " + zone + (clusterNames.isEmpty() ? "" : ", on clusters " + String.join(", ", clusterNames) + (documentTypes.isEmpty() ? "" : ", for types " + String.join(", ", documentTypes)))); } /** Gets reindexing status of an application in a zone. */ private HttpResponse getReindexing(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) { ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName); ZoneId zone = requireZone(environment, region); ApplicationReindexing reindexing = controller.applications().applicationReindexing(id, zone); Slime slime = new Slime(); Cursor root = slime.setObject(); root.setBool("enabled", reindexing.enabled()); Cursor clustersArray = root.setArray("clusters"); reindexing.clusters().entrySet().stream().sorted(comparingByKey()) .forEach(cluster -> { Cursor clusterObject = clustersArray.addObject(); clusterObject.setString("name", cluster.getKey()); Cursor pendingArray = clusterObject.setArray("pending"); cluster.getValue().pending().entrySet().stream().sorted(comparingByKey()) .forEach(pending -> { Cursor pendingObject = pendingArray.addObject(); pendingObject.setString("type", pending.getKey()); pendingObject.setLong("requiredGeneration", pending.getValue()); }); Cursor readyArray = clusterObject.setArray("ready"); cluster.getValue().ready().entrySet().stream().sorted(comparingByKey()) .forEach(ready -> { Cursor readyObject = readyArray.addObject(); readyObject.setString("type", ready.getKey()); setStatus(readyObject, ready.getValue()); }); }); return new SlimeJsonResponse(slime); } void setStatus(Cursor statusObject, ApplicationReindexing.Status status) { status.readyAt().ifPresent(readyAt -> statusObject.setLong("readyAtMillis", readyAt.toEpochMilli())); status.startedAt().ifPresent(startedAt -> statusObject.setLong("startedAtMillis", startedAt.toEpochMilli())); status.endedAt().ifPresent(endedAt -> statusObject.setLong("endedAtMillis", endedAt.toEpochMilli())); status.state().map(ApplicationApiHandler::toString).ifPresent(state -> statusObject.setString("state", state)); status.message().ifPresent(message -> statusObject.setString("message", message)); status.progress().ifPresent(progress -> statusObject.setDouble("progress", progress)); } private static String toString(ApplicationReindexing.State state) { switch (state) { case PENDING: return "pending"; case RUNNING: return "running"; case FAILED: return "failed"; case SUCCESSFUL: return "successful"; default: return null; } } /** Enables reindexing of an application in a zone. */ private HttpResponse enableReindexing(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) { ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName); ZoneId zone = requireZone(environment, region); controller.applications().enableReindexing(id, zone); return new MessageResponse("Enabled reindexing of " + id + " in " + zone); } /** Disables reindexing of an application in a zone. */ private HttpResponse disableReindexing(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) { ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName); ZoneId zone = requireZone(environment, region); controller.applications().disableReindexing(id, zone); return new MessageResponse("Disabled reindexing of " + id + " in " + zone); } /** Schedule restart of deployment, or specific host in a deployment */ private HttpResponse restart(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) { DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName), requireZone(environment, region)); RestartFilter restartFilter = new RestartFilter() .withHostName(Optional.ofNullable(request.getProperty("hostname")).map(HostName::from)) .withClusterType(Optional.ofNullable(request.getProperty("clusterType")).map(ClusterSpec.Type::from)) .withClusterId(Optional.ofNullable(request.getProperty("clusterId")).map(ClusterSpec.Id::from)); controller.applications().restart(deploymentId, restartFilter); return new MessageResponse("Requested restart of " + deploymentId); } /** Set suspension status of the given deployment. */ private HttpResponse suspend(String tenantName, String applicationName, String instanceName, String environment, String region, boolean suspend) { DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName), requireZone(environment, region)); controller.applications().setSuspension(deploymentId, suspend); return new MessageResponse((suspend ? "Suspended" : "Resumed") + " orchestration of " + deploymentId); } private HttpResponse jobDeploy(ApplicationId id, JobType type, HttpRequest request) { if ( ! type.environment().isManuallyDeployed() && ! isOperator(request)) throw new IllegalArgumentException("Direct deployments are only allowed to manually deployed environments."); Map<String, byte[]> dataParts = parseDataParts(request); if ( ! dataParts.containsKey("applicationZip")) throw new IllegalArgumentException("Missing required form part 'applicationZip'"); ApplicationPackage applicationPackage = new ApplicationPackage(dataParts.get(EnvironmentResource.APPLICATION_ZIP)); controller.applications().verifyApplicationIdentityConfiguration(id.tenant(), Optional.of(id.instance()), Optional.of(type.zone(controller.system())), applicationPackage, Optional.of(requireUserPrincipal(request))); Optional<Version> version = Optional.ofNullable(dataParts.get("deployOptions")) .map(json -> SlimeUtils.jsonToSlime(json).get()) .flatMap(options -> optional("vespaVersion", options)) .map(Version::fromString); controller.jobController().deploy(id, type, version, applicationPackage); RunId runId = controller.jobController().last(id, type).get().id(); Slime slime = new Slime(); Cursor rootObject = slime.setObject(); rootObject.setString("message", "Deployment started in " + runId + ". This may take about 15 minutes the first time."); rootObject.setLong("run", runId.number()); return new SlimeJsonResponse(slime); } private HttpResponse deploy(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) { ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName); ZoneId zone = requireZone(environment, region); // Get deployOptions Map<String, byte[]> dataParts = parseDataParts(request); if ( ! dataParts.containsKey("deployOptions")) return ErrorResponse.badRequest("Missing required form part 'deployOptions'"); Inspector deployOptions = SlimeUtils.jsonToSlime(dataParts.get("deployOptions")).get(); // Resolve system application Optional<SystemApplication> systemApplication = SystemApplication.matching(applicationId); if (systemApplication.isEmpty() || !systemApplication.get().hasApplicationPackage()) { return ErrorResponse.badRequest("Deployment of " + applicationId + " is not supported through this API"); } // Make it explicit that version is not yet supported here String vespaVersion = deployOptions.field("vespaVersion").asString(); if (!vespaVersion.isEmpty() && !vespaVersion.equals("null")) { return ErrorResponse.badRequest("Specifying version for " + applicationId + " is not permitted"); } // To avoid second guessing the orchestrated upgrades of system applications // we don't allow to deploy these during an system upgrade (i.e when new vespa is being rolled out) VersionStatus versionStatus = controller.readVersionStatus(); if (versionStatus.isUpgrading()) { throw new IllegalArgumentException("Deployment of system applications during a system upgrade is not allowed"); } Optional<VespaVersion> systemVersion = versionStatus.systemVersion(); if (systemVersion.isEmpty()) { throw new IllegalArgumentException("Deployment of system applications is not permitted until system version is determined"); } ActivateResult result = controller.applications() .deploySystemApplicationPackage(systemApplication.get(), zone, systemVersion.get().versionNumber()); return new SlimeJsonResponse(toSlime(result)); } private HttpResponse deleteTenant(String tenantName, HttpRequest request) { Optional<Tenant> tenant = controller.tenants().get(tenantName); if (tenant.isEmpty()) return ErrorResponse.notFoundError("Could not delete tenant '" + tenantName + "': Tenant not found"); controller.tenants().delete(tenant.get().name(), accessControlRequests.credentials(tenant.get().name(), toSlime(request.getData()).get(), request.getJDiscRequest())); // TODO: Change to a message response saying the tenant was deleted return tenant(tenant.get(), request); } private HttpResponse deleteApplication(String tenantName, String applicationName, HttpRequest request) { TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName); Credentials credentials = accessControlRequests.credentials(id.tenant(), toSlime(request.getData()).get(), request.getJDiscRequest()); controller.applications().deleteApplication(id, credentials); return new MessageResponse("Deleted application " + id); } private HttpResponse deleteInstance(String tenantName, String applicationName, String instanceName, HttpRequest request) { TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName); controller.applications().deleteInstance(id.instance(instanceName)); if (controller.applications().requireApplication(id).instances().isEmpty()) { Credentials credentials = accessControlRequests.credentials(id.tenant(), toSlime(request.getData()).get(), request.getJDiscRequest()); controller.applications().deleteApplication(id, credentials); } return new MessageResponse("Deleted instance " + id.instance(instanceName).toFullString()); } private HttpResponse deactivate(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) { DeploymentId id = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName), requireZone(environment, region)); // Attempt to deactivate application even if the deployment is not known by the controller controller.applications().deactivate(id.applicationId(), id.zoneId()); return new MessageResponse("Deactivated " + id); } /** Returns test config for indicated job, with production deployments of the default instance. */ private HttpResponse testConfig(ApplicationId id, JobType type) { // TODO jonmv: Support non-default instances as well; requires API change in clients. ApplicationId defaultInstanceId = TenantAndApplicationId.from(id).defaultInstance(); HashSet<DeploymentId> deployments = controller.applications() .getInstance(defaultInstanceId).stream() .flatMap(instance -> instance.productionDeployments().keySet().stream()) .map(zone -> new DeploymentId(defaultInstanceId, zone)) .collect(Collectors.toCollection(HashSet::new)); var testedZone = type.zone(controller.system()); // If a production job is specified, the production deployment of the _default instance_ is the relevant one, // as user instances should not exist in prod. TODO jonmv: Remove this when multiple instances are supported (above). if ( ! type.isProduction()) deployments.add(new DeploymentId(id, testedZone)); return new SlimeJsonResponse(testConfigSerializer.configSlime(id, type, false, controller.routing().zoneEndpointsOf(deployments), controller.applications().reachableContentClustersByZone(deployments))); } private static SourceRevision toSourceRevision(Inspector object) { if (!object.field("repository").valid() || !object.field("branch").valid() || !object.field("commit").valid()) { throw new IllegalArgumentException("Must specify \"repository\", \"branch\", and \"commit\"."); } return new SourceRevision(object.field("repository").asString(), object.field("branch").asString(), object.field("commit").asString()); } private Tenant getTenantOrThrow(String tenantName) { return controller.tenants().get(tenantName) .orElseThrow(() -> new NotExistsException(new TenantId(tenantName))); } private void toSlime(Cursor object, Tenant tenant, List<Application> applications, HttpRequest request) { object.setString("tenant", tenant.name().value()); object.setString("type", tenantType(tenant)); switch (tenant.type()) { case athenz: AthenzTenant athenzTenant = (AthenzTenant) tenant; object.setString("athensDomain", athenzTenant.domain().getName()); object.setString("property", athenzTenant.property().id()); athenzTenant.propertyId().ifPresent(id -> object.setString("propertyId", id.toString())); athenzTenant.contact().ifPresent(c -> { object.setString("propertyUrl", c.propertyUrl().toString()); object.setString("contactsUrl", c.url().toString()); object.setString("issueCreationUrl", c.issueTrackerUrl().toString()); Cursor contactsArray = object.setArray("contacts"); c.persons().forEach(persons -> { Cursor personArray = contactsArray.addArray(); persons.forEach(personArray::addString); }); }); break; case cloud: { CloudTenant cloudTenant = (CloudTenant) tenant; cloudTenant.creator().ifPresent(creator -> object.setString("creator", creator.getName())); Cursor pemDeveloperKeysArray = object.setArray("pemDeveloperKeys"); cloudTenant.developerKeys().forEach((key, user) -> { Cursor keyObject = pemDeveloperKeysArray.addObject(); keyObject.setString("key", KeyUtils.toPem(key)); keyObject.setString("user", user.getName()); }); // TODO: remove this once console is updated toSlime(object, cloudTenant.tenantSecretStores()); toSlime(object.setObject("integrations").setObject("aws"), controller.serviceRegistry().roleService().getTenantRole(tenant.name()), cloudTenant.tenantSecretStores()); var tenantQuota = controller.serviceRegistry().billingController().getQuota(tenant.name()); var usedQuota = applications.stream() .map(Application::quotaUsage) .reduce(QuotaUsage.none, QuotaUsage::add); toSlime(tenantQuota, usedQuota, object.setObject("quota")); cloudTenant.archiveAccessRole().ifPresent(role -> object.setString("archiveAccessRole", role)); break; } default: throw new IllegalArgumentException("Unexpected tenant type '" + tenant.type() + "'."); } // TODO jonmv: This should list applications, not instances. Cursor applicationArray = object.setArray("applications"); for (Application application : applications) { DeploymentStatus status = null; for (Instance instance : showOnlyProductionInstances(request) ? application.productionInstances().values() : application.instances().values()) if (recurseOverApplications(request)) { if (status == null) status = controller.jobController().deploymentStatus(application); toSlime(applicationArray.addObject(), instance, status, request); } else { toSlime(instance.id(), applicationArray.addObject(), request); } } tenantMetaDataToSlime(tenant, applications, object.setObject("metaData")); } private void toSlime(Quota quota, QuotaUsage usage, Cursor object) { quota.budget().ifPresentOrElse( budget -> object.setDouble("budget", budget.doubleValue()), () -> object.setNix("budget") ); object.setDouble("budgetUsed", usage.rate()); // TODO: Retire when we no longer use maxClusterSize as a meaningful limit quota.maxClusterSize().ifPresent(maxClusterSize -> object.setLong("clusterSize", maxClusterSize)); } private void toSlime(ClusterResources resources, Cursor object) { object.setLong("nodes", resources.nodes()); object.setLong("groups", resources.groups()); toSlime(resources.nodeResources(), object.setObject("nodeResources")); // Divide cost by 3 in non-public zones to show approx. AWS equivalent cost double costDivisor = controller.zoneRegistry().system().isPublic() ? 1.0 : 3.0; object.setDouble("cost", Math.round(resources.nodes() * resources.nodeResources().cost() * 100.0 / costDivisor) / 100.0); } private void utilizationToSlime(Cluster.Utilization utilization, Cursor utilizationObject) { utilizationObject.setDouble("cpu", utilization.cpu()); utilizationObject.setDouble("idealCpu", utilization.idealCpu()); utilizationObject.setDouble("currentCpu", utilization.currentCpu()); utilizationObject.setDouble("memory", utilization.memory()); utilizationObject.setDouble("idealMemory", utilization.idealMemory()); utilizationObject.setDouble("currentMemory", utilization.currentMemory()); utilizationObject.setDouble("disk", utilization.disk()); utilizationObject.setDouble("idealDisk", utilization.idealDisk()); utilizationObject.setDouble("currentDisk", utilization.currentDisk()); } private void scalingEventsToSlime(List<Cluster.ScalingEvent> scalingEvents, Cursor scalingEventsArray) { for (Cluster.ScalingEvent scalingEvent : scalingEvents) { Cursor scalingEventObject = scalingEventsArray.addObject(); toSlime(scalingEvent.from(), scalingEventObject.setObject("from")); toSlime(scalingEvent.to(), scalingEventObject.setObject("to")); scalingEventObject.setLong("at", scalingEvent.at().toEpochMilli()); scalingEvent.completion().ifPresent(completion -> scalingEventObject.setLong("completion", completion.toEpochMilli())); } } private void toSlime(NodeResources resources, Cursor object) { object.setDouble("vcpu", resources.vcpu()); object.setDouble("memoryGb", resources.memoryGb()); object.setDouble("diskGb", resources.diskGb()); object.setDouble("bandwidthGbps", resources.bandwidthGbps()); object.setString("diskSpeed", valueOf(resources.diskSpeed())); object.setString("storageType", valueOf(resources.storageType())); } // A tenant has different content when in a list ... antipattern, but not solvable before application/v5 private void tenantInTenantsListToSlime(Tenant tenant, URI requestURI, Cursor object) { object.setString("tenant", tenant.name().value()); Cursor metaData = object.setObject("metaData"); metaData.setString("type", tenantType(tenant)); switch (tenant.type()) { case athenz: AthenzTenant athenzTenant = (AthenzTenant) tenant; metaData.setString("athensDomain", athenzTenant.domain().getName()); metaData.setString("property", athenzTenant.property().id()); break; case cloud: break; default: throw new IllegalArgumentException("Unexpected tenant type '" + tenant.type() + "'."); } object.setString("url", withPath("/application/v4/tenant/" + tenant.name().value(), requestURI).toString()); } private void tenantMetaDataToSlime(Tenant tenant, List<Application> applications, Cursor object) { Optional<Instant> lastDev = applications.stream() .flatMap(application -> application.instances().values().stream()) .flatMap(instance -> instance.deployments().values().stream()) .filter(deployment -> deployment.zone().environment() == Environment.dev) .map(Deployment::at) .max(Comparator.naturalOrder()) .or(() -> applications.stream() .flatMap(application -> application.instances().values().stream()) .flatMap(instance -> JobType.allIn(controller.system()).stream() .filter(job -> job.environment() == Environment.dev) .flatMap(jobType -> controller.jobController().last(instance.id(), jobType).stream())) .map(Run::start) .max(Comparator.naturalOrder())); Optional<Instant> lastSubmission = applications.stream() .flatMap(app -> app.latestVersion().flatMap(ApplicationVersion::buildTime).stream()) .max(Comparator.naturalOrder()); object.setLong("createdAtMillis", tenant.createdAt().toEpochMilli()); lastDev.ifPresent(instant -> object.setLong("lastDeploymentToDevMillis", instant.toEpochMilli())); lastSubmission.ifPresent(instant -> object.setLong("lastSubmissionToProdMillis", instant.toEpochMilli())); tenant.lastLoginInfo().get(LastLoginInfo.UserLevel.user) .ifPresent(instant -> object.setLong("lastLoginByUserMillis", instant.toEpochMilli())); tenant.lastLoginInfo().get(LastLoginInfo.UserLevel.developer) .ifPresent(instant -> object.setLong("lastLoginByDeveloperMillis", instant.toEpochMilli())); tenant.lastLoginInfo().get(LastLoginInfo.UserLevel.administrator) .ifPresent(instant -> object.setLong("lastLoginByAdministratorMillis", instant.toEpochMilli())); } /** Returns a copy of the given URI with the host and port from the given URI, the path set to the given path and the query set to given query*/ private URI withPathAndQuery(String newPath, String newQuery, URI uri) { try { return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), newPath, newQuery, null); } catch (URISyntaxException e) { throw new RuntimeException("Will not happen", e); } } /** Returns a copy of the given URI with the host and port from the given URI and the path set to the given path */ private URI withPath(String newPath, URI uri) { return withPathAndQuery(newPath, null, uri); } private String toPath(DeploymentId id) { return path("/application", "v4", "tenant", id.applicationId().tenant(), "application", id.applicationId().application(), "instance", id.applicationId().instance(), "environment", id.zoneId().environment(), "region", id.zoneId().region()); } private long asLong(String valueOrNull, long defaultWhenNull) { if (valueOrNull == null) return defaultWhenNull; try { return Long.parseLong(valueOrNull); } catch (NumberFormatException e) { throw new IllegalArgumentException("Expected an integer but got '" + valueOrNull + "'"); } } private void toSlime(Run run, Cursor object) { object.setLong("id", run.id().number()); object.setString("version", run.versions().targetPlatform().toFullString()); if ( ! run.versions().targetApplication().isUnknown()) toSlime(run.versions().targetApplication(), object.setObject("revision")); object.setString("reason", "unknown reason"); object.setLong("at", run.end().orElse(run.start()).toEpochMilli()); } private Slime toSlime(InputStream jsonStream) { try { byte[] jsonBytes = IOUtils.readBytes(jsonStream, 1000 * 1000); return SlimeUtils.jsonToSlime(jsonBytes); } catch (IOException e) { throw new RuntimeException(); } } private static Principal requireUserPrincipal(HttpRequest request) { Principal principal = request.getJDiscRequest().getUserPrincipal(); if (principal == null) throw new InternalServerErrorException("Expected a user principal"); return principal; } private Inspector mandatory(String key, Inspector object) { if ( ! object.field(key).valid()) throw new IllegalArgumentException("'" + key + "' is missing"); return object.field(key); } private Optional<String> optional(String key, Inspector object) { return SlimeUtils.optionalString(object.field(key)); } private static String path(Object... elements) { return Joiner.on("/").join(elements); } private void toSlime(TenantAndApplicationId id, Cursor object, HttpRequest request) { object.setString("tenant", id.tenant().value()); object.setString("application", id.application().value()); object.setString("url", withPath("/application/v4" + "/tenant/" + id.tenant().value() + "/application/" + id.application().value(), request.getUri()).toString()); } private void toSlime(ApplicationId id, Cursor object, HttpRequest request) { object.setString("tenant", id.tenant().value()); object.setString("application", id.application().value()); object.setString("instance", id.instance().value()); object.setString("url", withPath("/application/v4" + "/tenant/" + id.tenant().value() + "/application/" + id.application().value() + "/instance/" + id.instance().value(), request.getUri()).toString()); } private Slime toSlime(ActivateResult result) { Slime slime = new Slime(); Cursor object = slime.setObject(); object.setString("revisionId", result.revisionId().id()); object.setLong("applicationZipSize", result.applicationZipSizeBytes()); Cursor logArray = object.setArray("prepareMessages"); if (result.prepareResponse().log != null) { for (Log logMessage : result.prepareResponse().log) { Cursor logObject = logArray.addObject(); logObject.setLong("time", logMessage.time); logObject.setString("level", logMessage.level); logObject.setString("message", logMessage.message); } } Cursor changeObject = object.setObject("configChangeActions"); Cursor restartActionsArray = changeObject.setArray("restart"); for (RestartAction restartAction : result.prepareResponse().configChangeActions.restartActions) { Cursor restartActionObject = restartActionsArray.addObject(); restartActionObject.setString("clusterName", restartAction.clusterName); restartActionObject.setString("clusterType", restartAction.clusterType); restartActionObject.setString("serviceType", restartAction.serviceType); serviceInfosToSlime(restartAction.services, restartActionObject.setArray("services")); stringsToSlime(restartAction.messages, restartActionObject.setArray("messages")); } Cursor refeedActionsArray = changeObject.setArray("refeed"); for (RefeedAction refeedAction : result.prepareResponse().configChangeActions.refeedActions) { Cursor refeedActionObject = refeedActionsArray.addObject(); refeedActionObject.setString("name", refeedAction.name); refeedActionObject.setString("documentType", refeedAction.documentType); refeedActionObject.setString("clusterName", refeedAction.clusterName); serviceInfosToSlime(refeedAction.services, refeedActionObject.setArray("services")); stringsToSlime(refeedAction.messages, refeedActionObject.setArray("messages")); } return slime; } private void serviceInfosToSlime(List<ServiceInfo> serviceInfoList, Cursor array) { for (ServiceInfo serviceInfo : serviceInfoList) { Cursor serviceInfoObject = array.addObject(); serviceInfoObject.setString("serviceName", serviceInfo.serviceName); serviceInfoObject.setString("serviceType", serviceInfo.serviceType); serviceInfoObject.setString("configId", serviceInfo.configId); serviceInfoObject.setString("hostName", serviceInfo.hostName); } } private void stringsToSlime(List<String> strings, Cursor array) { for (String string : strings) array.addString(string); } private void toSlime(Cursor object, List<TenantSecretStore> tenantSecretStores) { Cursor secretStore = object.setArray("secretStores"); tenantSecretStores.forEach(store -> { toSlime(secretStore.addObject(), store); }); } private void toSlime(Cursor object, TenantRoles tenantRoles, List<TenantSecretStore> tenantSecretStores) { object.setString("tenantRole", tenantRoles.containerRole()); var stores = object.setArray("accounts"); tenantSecretStores.forEach(secretStore -> { toSlime(stores.addObject(), secretStore); }); } private void toSlime(Cursor object, TenantSecretStore secretStore) { object.setString("name", secretStore.getName()); object.setString("awsId", secretStore.getAwsId()); object.setString("role", secretStore.getRole()); } private String readToString(InputStream stream) { Scanner scanner = new Scanner(stream).useDelimiter("\\A"); if ( ! scanner.hasNext()) return null; return scanner.next(); } private static boolean recurseOverTenants(HttpRequest request) { return recurseOverApplications(request) || "tenant".equals(request.getProperty("recursive")); } private static boolean recurseOverApplications(HttpRequest request) { return recurseOverDeployments(request) || "application".equals(request.getProperty("recursive")); } private static boolean recurseOverDeployments(HttpRequest request) { return ImmutableSet.of("all", "true", "deployment").contains(request.getProperty("recursive")); } private static boolean showOnlyProductionInstances(HttpRequest request) { return "true".equals(request.getProperty("production")); } private static String tenantType(Tenant tenant) { switch (tenant.type()) { case athenz: return "ATHENS"; case cloud: return "CLOUD"; default: throw new IllegalArgumentException("Unknown tenant type: " + tenant.getClass().getSimpleName()); } } private static ApplicationId appIdFromPath(Path path) { return ApplicationId.from(path.get("tenant"), path.get("application"), path.get("instance")); } private static JobType jobTypeFromPath(Path path) { return JobType.fromJobName(path.get("jobtype")); } private static RunId runIdFromPath(Path path) { long number = Long.parseLong(path.get("number")); return new RunId(appIdFromPath(path), jobTypeFromPath(path), number); } private HttpResponse submit(String tenant, String application, HttpRequest request) { Map<String, byte[]> dataParts = parseDataParts(request); Inspector submitOptions = SlimeUtils.jsonToSlime(dataParts.get(EnvironmentResource.SUBMIT_OPTIONS)).get(); long projectId = Math.max(1, submitOptions.field("projectId").asLong()); // Absence of this means it's not a prod app :/ Optional<String> repository = optional("repository", submitOptions); Optional<String> branch = optional("branch", submitOptions); Optional<String> commit = optional("commit", submitOptions); Optional<SourceRevision> sourceRevision = repository.isPresent() && branch.isPresent() && commit.isPresent() ? Optional.of(new SourceRevision(repository.get(), branch.get(), commit.get())) : Optional.empty(); Optional<String> sourceUrl = optional("sourceUrl", submitOptions); Optional<String> authorEmail = optional("authorEmail", submitOptions); sourceUrl.map(URI::create).ifPresent(url -> { if (url.getHost() == null || url.getScheme() == null) throw new IllegalArgumentException("Source URL must include scheme and host"); }); ApplicationPackage applicationPackage = new ApplicationPackage(dataParts.get(EnvironmentResource.APPLICATION_ZIP), true); controller.applications().verifyApplicationIdentityConfiguration(TenantName.from(tenant), Optional.empty(), Optional.empty(), applicationPackage, Optional.of(requireUserPrincipal(request))); return JobControllerApiHandlerHelper.submitResponse(controller.jobController(), tenant, application, sourceRevision, authorEmail, sourceUrl, projectId, applicationPackage, dataParts.get(EnvironmentResource.APPLICATION_TEST_ZIP)); } private HttpResponse removeAllProdDeployments(String tenant, String application) { JobControllerApiHandlerHelper.submitResponse(controller.jobController(), tenant, application, Optional.empty(), Optional.empty(), Optional.empty(), 1, ApplicationPackage.deploymentRemoval(), new byte[0]); return new MessageResponse("All deployments removed"); } private ZoneId requireZone(String environment, String region) { ZoneId zone = ZoneId.from(environment, region); // TODO(mpolden): Find a way to not hardcode this. Some APIs allow this "virtual" zone, e.g. /logs if (zone.environment() == Environment.prod && zone.region().value().equals("controller")) { return zone; } if (!controller.zoneRegistry().hasZone(zone)) { throw new IllegalArgumentException("Zone " + zone + " does not exist in this system"); } return zone; } private static Map<String, byte[]> parseDataParts(HttpRequest request) { String contentHash = request.getHeader("X-Content-Hash"); if (contentHash == null) return new MultipartParser().parse(request); DigestInputStream digester = Signatures.sha256Digester(request.getData()); var dataParts = new MultipartParser().parse(request.getHeader("Content-Type"), digester, request.getUri()); if ( ! Arrays.equals(digester.getMessageDigest().digest(), Base64.getDecoder().decode(contentHash))) throw new IllegalArgumentException("Value of X-Content-Hash header does not match computed content hash"); return dataParts; } private static RotationId findRotationId(Instance instance, Optional<String> endpointId) { if (instance.rotations().isEmpty()) { throw new NotExistsException("global rotation does not exist for " + instance); } if (endpointId.isPresent()) { return instance.rotations().stream() .filter(r -> r.endpointId().id().equals(endpointId.get())) .map(AssignedRotation::rotationId) .findFirst() .orElseThrow(() -> new NotExistsException("endpoint " + endpointId.get() + " does not exist for " + instance)); } else if (instance.rotations().size() > 1) { throw new IllegalArgumentException(instance + " has multiple rotations. Query parameter 'endpointId' must be given"); } return instance.rotations().get(0).rotationId(); } private static String rotationStateString(RotationState state) { switch (state) { case in: return "IN"; case out: return "OUT"; } return "UNKNOWN"; } private static String endpointScopeString(Endpoint.Scope scope) { switch (scope) { case region: return "region"; case global: return "global"; case zone: return "zone"; } throw new IllegalArgumentException("Unknown endpoint scope " + scope); } private static String routingMethodString(RoutingMethod method) { switch (method) { case exclusive: return "exclusive"; case shared: return "shared"; case sharedLayer4: return "sharedLayer4"; } throw new IllegalArgumentException("Unknown routing method " + method); } private static <T> T getAttribute(HttpRequest request, String attributeName, Class<T> cls) { return Optional.ofNullable(request.getJDiscRequest().context().get(attributeName)) .filter(cls::isInstance) .map(cls::cast) .orElseThrow(() -> new IllegalArgumentException("Attribute '" + attributeName + "' was not set on request")); } /** Returns whether given request is by an operator */ private static boolean isOperator(HttpRequest request) { var securityContext = getAttribute(request, SecurityContext.ATTRIBUTE_NAME, SecurityContext.class); return securityContext.roles().stream() .map(Role::definition) .anyMatch(definition -> definition == RoleDefinition.hostedOperator); } }
controller-server/src/main/java/com/yahoo/vespa/hosted/controller/restapi/application/ApplicationApiHandler.java
// Copyright 2020 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.hosted.controller.restapi.application; import ai.vespa.hosted.api.Signatures; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableSet; import com.google.inject.Inject; import com.yahoo.component.Version; import com.yahoo.config.application.api.DeploymentSpec; import com.yahoo.config.provision.ApplicationId; import com.yahoo.config.provision.ApplicationName; import com.yahoo.config.provision.ClusterResources; import com.yahoo.config.provision.ClusterSpec; import com.yahoo.config.provision.Environment; import com.yahoo.config.provision.HostName; import com.yahoo.config.provision.InstanceName; import com.yahoo.config.provision.NodeResources; import com.yahoo.config.provision.TenantName; import com.yahoo.config.provision.zone.RoutingMethod; import com.yahoo.config.provision.zone.ZoneId; import com.yahoo.container.handler.metrics.JsonResponse; import com.yahoo.container.jdisc.HttpRequest; import com.yahoo.container.jdisc.HttpResponse; import com.yahoo.container.jdisc.LoggingRequestHandler; import com.yahoo.io.IOUtils; import com.yahoo.restapi.ErrorResponse; import com.yahoo.restapi.MessageResponse; import com.yahoo.restapi.Path; import com.yahoo.restapi.ResourceResponse; import com.yahoo.restapi.SlimeJsonResponse; import com.yahoo.security.KeyUtils; import com.yahoo.slime.Cursor; import com.yahoo.slime.Inspector; import com.yahoo.slime.JsonParseException; import com.yahoo.slime.Slime; import com.yahoo.slime.SlimeUtils; import com.yahoo.vespa.hosted.controller.Application; import com.yahoo.vespa.hosted.controller.Controller; import com.yahoo.vespa.hosted.controller.Instance; import com.yahoo.vespa.hosted.controller.LockedTenant; import com.yahoo.vespa.hosted.controller.NotExistsException; import com.yahoo.vespa.hosted.controller.api.application.v4.EnvironmentResource; import com.yahoo.vespa.hosted.controller.api.application.v4.model.EndpointStatus; import com.yahoo.vespa.hosted.controller.api.application.v4.model.ProtonMetrics; import com.yahoo.vespa.hosted.controller.api.application.v4.model.configserverbindings.RefeedAction; import com.yahoo.vespa.hosted.controller.api.application.v4.model.configserverbindings.RestartAction; import com.yahoo.vespa.hosted.controller.api.application.v4.model.configserverbindings.ServiceInfo; import com.yahoo.vespa.hosted.controller.api.identifiers.DeploymentId; import com.yahoo.vespa.hosted.controller.api.identifiers.TenantId; import com.yahoo.vespa.hosted.controller.api.integration.aws.TenantRoles; import com.yahoo.vespa.hosted.controller.api.integration.billing.Quota; import com.yahoo.vespa.hosted.controller.api.integration.configserver.ApplicationReindexing; import com.yahoo.vespa.hosted.controller.api.integration.configserver.Cluster; import com.yahoo.vespa.hosted.controller.api.integration.configserver.ConfigServerException; import com.yahoo.vespa.hosted.controller.api.integration.configserver.Log; import com.yahoo.vespa.hosted.controller.api.integration.configserver.Node; import com.yahoo.vespa.hosted.controller.api.integration.deployment.ApplicationVersion; import com.yahoo.vespa.hosted.controller.api.integration.deployment.JobId; import com.yahoo.vespa.hosted.controller.api.integration.deployment.JobType; import com.yahoo.vespa.hosted.controller.api.integration.deployment.RunId; import com.yahoo.vespa.hosted.controller.api.integration.deployment.SourceRevision; import com.yahoo.vespa.hosted.controller.api.integration.noderepository.RestartFilter; import com.yahoo.vespa.hosted.controller.api.integration.resource.MeteringData; import com.yahoo.vespa.hosted.controller.api.integration.resource.ResourceAllocation; import com.yahoo.vespa.hosted.controller.api.integration.resource.ResourceSnapshot; import com.yahoo.vespa.hosted.controller.api.integration.secrets.TenantSecretStore; import com.yahoo.vespa.hosted.controller.api.role.Role; import com.yahoo.vespa.hosted.controller.api.role.RoleDefinition; import com.yahoo.vespa.hosted.controller.api.role.SecurityContext; import com.yahoo.vespa.hosted.controller.application.ActivateResult; import com.yahoo.vespa.hosted.controller.application.ApplicationPackage; import com.yahoo.vespa.hosted.controller.application.AssignedRotation; import com.yahoo.vespa.hosted.controller.application.Change; import com.yahoo.vespa.hosted.controller.application.Deployment; import com.yahoo.vespa.hosted.controller.application.DeploymentMetrics; import com.yahoo.vespa.hosted.controller.application.Endpoint; import com.yahoo.vespa.hosted.controller.application.EndpointList; import com.yahoo.vespa.hosted.controller.application.QuotaUsage; import com.yahoo.vespa.hosted.controller.application.SystemApplication; import com.yahoo.vespa.hosted.controller.application.TenantAndApplicationId; import com.yahoo.vespa.hosted.controller.auditlog.AuditLoggingRequestHandler; import com.yahoo.vespa.hosted.controller.deployment.DeploymentStatus; import com.yahoo.vespa.hosted.controller.deployment.DeploymentSteps; import com.yahoo.vespa.hosted.controller.deployment.DeploymentTrigger; import com.yahoo.vespa.hosted.controller.deployment.DeploymentTrigger.ChangesToCancel; import com.yahoo.vespa.hosted.controller.deployment.JobStatus; import com.yahoo.vespa.hosted.controller.deployment.Run; import com.yahoo.vespa.hosted.controller.deployment.TestConfigSerializer; import com.yahoo.vespa.hosted.controller.notification.Notification; import com.yahoo.vespa.hosted.controller.notification.NotificationSource; import com.yahoo.vespa.hosted.controller.persistence.SupportAccessSerializer; import com.yahoo.vespa.hosted.controller.rotation.RotationId; import com.yahoo.vespa.hosted.controller.rotation.RotationState; import com.yahoo.vespa.hosted.controller.rotation.RotationStatus; import com.yahoo.vespa.hosted.controller.routing.GlobalRouting; import com.yahoo.vespa.hosted.controller.security.AccessControlRequests; import com.yahoo.vespa.hosted.controller.security.Credentials; import com.yahoo.vespa.hosted.controller.support.access.SupportAccess; import com.yahoo.vespa.hosted.controller.tenant.AthenzTenant; import com.yahoo.vespa.hosted.controller.tenant.CloudTenant; import com.yahoo.vespa.hosted.controller.tenant.LastLoginInfo; import com.yahoo.vespa.hosted.controller.tenant.Tenant; import com.yahoo.vespa.hosted.controller.tenant.TenantInfo; import com.yahoo.vespa.hosted.controller.tenant.TenantInfoAddress; import com.yahoo.vespa.hosted.controller.tenant.TenantInfoBillingContact; import com.yahoo.vespa.hosted.controller.versions.VersionStatus; import com.yahoo.vespa.hosted.controller.versions.VespaVersion; import com.yahoo.vespa.serviceview.bindings.ApplicationView; import com.yahoo.yolean.Exceptions; import javax.ws.rs.ForbiddenException; import javax.ws.rs.InternalServerErrorException; import javax.ws.rs.NotAuthorizedException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.net.URISyntaxException; import java.security.DigestInputStream; import java.security.Principal; import java.security.PublicKey; import java.time.DayOfWeek; import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.Arrays; import java.util.Base64; import java.util.Comparator; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.OptionalLong; import java.util.Scanner; import java.util.StringJoiner; import java.util.logging.Level; import java.util.stream.Collectors; import java.util.stream.Stream; import static com.yahoo.jdisc.Response.Status.BAD_REQUEST; import static com.yahoo.jdisc.Response.Status.CONFLICT; import static java.util.Map.Entry.comparingByKey; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toUnmodifiableList; /** * This implements the application/v4 API which is used to deploy and manage applications * on hosted Vespa. * * @author bratseth * @author mpolden */ @SuppressWarnings("unused") // created by injection public class ApplicationApiHandler extends AuditLoggingRequestHandler { private static final ObjectMapper jsonMapper = new ObjectMapper(); private final Controller controller; private final AccessControlRequests accessControlRequests; private final TestConfigSerializer testConfigSerializer; @Inject public ApplicationApiHandler(LoggingRequestHandler.Context parentCtx, Controller controller, AccessControlRequests accessControlRequests) { super(parentCtx, controller.auditLogger()); this.controller = controller; this.accessControlRequests = accessControlRequests; this.testConfigSerializer = new TestConfigSerializer(controller.system()); } @Override public Duration getTimeout() { return Duration.ofMinutes(20); // deploys may take a long time; } @Override public HttpResponse auditAndHandle(HttpRequest request) { try { Path path = new Path(request.getUri()); switch (request.getMethod()) { case GET: return handleGET(path, request); case PUT: return handlePUT(path, request); case POST: return handlePOST(path, request); case PATCH: return handlePATCH(path, request); case DELETE: return handleDELETE(path, request); case OPTIONS: return handleOPTIONS(); default: return ErrorResponse.methodNotAllowed("Method '" + request.getMethod() + "' is not supported"); } } catch (ForbiddenException e) { return ErrorResponse.forbidden(Exceptions.toMessageString(e)); } catch (NotAuthorizedException e) { return ErrorResponse.unauthorized(Exceptions.toMessageString(e)); } catch (NotExistsException e) { return ErrorResponse.notFoundError(Exceptions.toMessageString(e)); } catch (IllegalArgumentException e) { return ErrorResponse.badRequest(Exceptions.toMessageString(e)); } catch (ConfigServerException e) { switch (e.code()) { case NOT_FOUND: return ErrorResponse.notFoundError(Exceptions.toMessageString(e)); case ACTIVATION_CONFLICT: return new ErrorResponse(CONFLICT, e.code().name(), Exceptions.toMessageString(e)); case INTERNAL_SERVER_ERROR: return ErrorResponse.internalServerError(Exceptions.toMessageString(e)); default: return new ErrorResponse(BAD_REQUEST, e.code().name(), Exceptions.toMessageString(e)); } } catch (RuntimeException e) { log.log(Level.WARNING, "Unexpected error handling '" + request.getUri() + "'", e); return ErrorResponse.internalServerError(Exceptions.toMessageString(e)); } } private HttpResponse handleGET(Path path, HttpRequest request) { if (path.matches("/application/v4/")) return root(request); if (path.matches("/application/v4/tenant")) return tenants(request); if (path.matches("/application/v4/tenant/{tenant}")) return tenant(path.get("tenant"), request); if (path.matches("/application/v4/tenant/{tenant}/info")) return tenantInfo(path.get("tenant"), request); if (path.matches("/application/v4/tenant/{tenant}/notifications")) return notifications(path.get("tenant"), request); if (path.matches("/application/v4/tenant/{tenant}/secret-store/{name}/validate")) return validateSecretStore(path.get("tenant"), path.get("name"), request); if (path.matches("/application/v4/tenant/{tenant}/application")) return applications(path.get("tenant"), Optional.empty(), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return application(path.get("tenant"), path.get("application"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/compile-version")) return compileVersion(path.get("tenant"), path.get("application")); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deployment")) return JobControllerApiHandlerHelper.overviewResponse(controller, TenantAndApplicationId.from(path.get("tenant"), path.get("application")), request.getUri()); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/package")) return applicationPackage(path.get("tenant"), path.get("application"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying")) return deploying(path.get("tenant"), path.get("application"), "default", request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/pin")) return deploying(path.get("tenant"), path.get("application"), "default", request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/metering")) return metering(path.get("tenant"), path.get("application"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance")) return applications(path.get("tenant"), Optional.of(path.get("application")), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return instance(path.get("tenant"), path.get("application"), path.get("instance"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying")) return deploying(path.get("tenant"), path.get("application"), path.get("instance"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/pin")) return deploying(path.get("tenant"), path.get("application"), path.get("instance"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job")) return JobControllerApiHandlerHelper.jobTypeResponse(controller, appIdFromPath(path), request.getUri()); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}")) return JobControllerApiHandlerHelper.runResponse(controller.jobController().runs(appIdFromPath(path), jobTypeFromPath(path)), request.getUri()); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/package")) return devApplicationPackage(appIdFromPath(path), jobTypeFromPath(path)); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/test-config")) return testConfig(appIdFromPath(path), jobTypeFromPath(path)); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/run/{number}")) return JobControllerApiHandlerHelper.runDetailsResponse(controller.jobController(), runIdFromPath(path), request.getProperty("after")); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}")) return deployment(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/reindexing")) return getReindexing(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/suspended")) return suspended(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/service")) return services(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/service/{service}/{*}")) return service(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), path.get("service"), path.getRest(), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/nodes")) return nodes(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region")); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/clusters")) return clusters(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region")); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/content/{*}")) return content(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), path.getRest(), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/logs")) return logs(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request.propertyMap()); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/access/support")) return supportAccess(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request.propertyMap()); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/metrics")) return metrics(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region")); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation")) return rotationStatus(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), Optional.ofNullable(request.getProperty("endpointId"))); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation/override")) return getGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region")); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deployment(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deployment(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/suspended")) return suspended(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/service")) return services(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/service/{service}/{*}")) return service(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), path.get("service"), path.getRest(), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/nodes")) return nodes(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region")); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/clusters")) return clusters(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region")); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/logs")) return logs(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request.propertyMap()); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation")) return rotationStatus(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), Optional.ofNullable(request.getProperty("endpointId"))); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation/override")) return getGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region")); return ErrorResponse.notFoundError("Nothing at " + path); } private HttpResponse handlePUT(Path path, HttpRequest request) { if (path.matches("/application/v4/tenant/{tenant}")) return updateTenant(path.get("tenant"), request); if (path.matches("/application/v4/tenant/{tenant}/info")) return updateTenantInfo(path.get("tenant"), request); if (path.matches("/application/v4/tenant/{tenant}/archive-access")) return allowArchiveAccess(path.get("tenant"), request); if (path.matches("/application/v4/tenant/{tenant}/secret-store/{name}")) return addSecretStore(path.get("tenant"), path.get("name"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), false, request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), false, request); return ErrorResponse.notFoundError("Nothing at " + path); } private HttpResponse handlePOST(Path path, HttpRequest request) { if (path.matches("/application/v4/tenant/{tenant}")) return createTenant(path.get("tenant"), request); if (path.matches("/application/v4/tenant/{tenant}/key")) return addDeveloperKey(path.get("tenant"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return createApplication(path.get("tenant"), path.get("application"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/platform")) return deployPlatform(path.get("tenant"), path.get("application"), "default", false, request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/pin")) return deployPlatform(path.get("tenant"), path.get("application"), "default", true, request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/application")) return deployApplication(path.get("tenant"), path.get("application"), "default", request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/key")) return addDeployKey(path.get("tenant"), path.get("application"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/submit")) return submit(path.get("tenant"), path.get("application"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return createInstance(path.get("tenant"), path.get("application"), path.get("instance"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploy/{jobtype}")) return jobDeploy(appIdFromPath(path), jobTypeFromPath(path), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/platform")) return deployPlatform(path.get("tenant"), path.get("application"), path.get("instance"), false, request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/pin")) return deployPlatform(path.get("tenant"), path.get("application"), path.get("instance"), true, request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/application")) return deployApplication(path.get("tenant"), path.get("application"), path.get("instance"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/submit")) return submit(path.get("tenant"), path.get("application"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}")) return trigger(appIdFromPath(path), jobTypeFromPath(path), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/pause")) return pause(appIdFromPath(path), jobTypeFromPath(path)); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/deploy")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request); // legacy synonym of the above if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/reindex")) return reindex(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/reindexing")) return enableReindexing(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/restart")) return restart(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/suspend")) return suspend(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), true); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/access/support")) return allowSupportAccess(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/deploy")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request); // legacy synonym of the above if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/restart")) return restart(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request); return ErrorResponse.notFoundError("Nothing at " + path); } private HttpResponse handlePATCH(Path path, HttpRequest request) { if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return patchApplication(path.get("tenant"), path.get("application"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return patchApplication(path.get("tenant"), path.get("application"), request); return ErrorResponse.notFoundError("Nothing at " + path); } private HttpResponse handleDELETE(Path path, HttpRequest request) { if (path.matches("/application/v4/tenant/{tenant}")) return deleteTenant(path.get("tenant"), request); if (path.matches("/application/v4/tenant/{tenant}/key")) return removeDeveloperKey(path.get("tenant"), request); if (path.matches("/application/v4/tenant/{tenant}/archive-access")) return removeArchiveAccess(path.get("tenant")); if (path.matches("/application/v4/tenant/{tenant}/secret-store/{name}")) return deleteSecretStore(path.get("tenant"), path.get("name"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return deleteApplication(path.get("tenant"), path.get("application"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deployment")) return removeAllProdDeployments(path.get("tenant"), path.get("application")); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying")) return cancelDeploy(path.get("tenant"), path.get("application"), "default", "all"); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/{choice}")) return cancelDeploy(path.get("tenant"), path.get("application"), "default", path.get("choice")); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/key")) return removeDeployKey(path.get("tenant"), path.get("application"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return deleteInstance(path.get("tenant"), path.get("application"), path.get("instance"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying")) return cancelDeploy(path.get("tenant"), path.get("application"), path.get("instance"), "all"); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/{choice}")) return cancelDeploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("choice")); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}")) return JobControllerApiHandlerHelper.abortJobResponse(controller.jobController(), appIdFromPath(path), jobTypeFromPath(path)); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/pause")) return resume(appIdFromPath(path), jobTypeFromPath(path)); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}")) return deactivate(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/reindexing")) return disableReindexing(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/suspend")) return suspend(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), false); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), true, request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/access/support")) return disallowSupportAccess(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deactivate(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request); if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), true, request); return ErrorResponse.notFoundError("Nothing at " + path); } private HttpResponse handleOPTIONS() { // We implement this to avoid redirect loops on OPTIONS requests from browsers, but do not really bother // spelling out the methods supported at each path, which we should EmptyResponse response = new EmptyResponse(); response.headers().put("Allow", "GET,PUT,POST,PATCH,DELETE,OPTIONS"); return response; } private HttpResponse recursiveRoot(HttpRequest request) { Slime slime = new Slime(); Cursor tenantArray = slime.setArray(); List<Application> applications = controller.applications().asList(); for (Tenant tenant : controller.tenants().asList()) toSlime(tenantArray.addObject(), tenant, applications.stream().filter(app -> app.id().tenant().equals(tenant.name())).collect(toList()), request); return new SlimeJsonResponse(slime); } private HttpResponse root(HttpRequest request) { return recurseOverTenants(request) ? recursiveRoot(request) : new ResourceResponse(request, "tenant"); } private HttpResponse tenants(HttpRequest request) { Slime slime = new Slime(); Cursor response = slime.setArray(); for (Tenant tenant : controller.tenants().asList()) tenantInTenantsListToSlime(tenant, request.getUri(), response.addObject()); return new SlimeJsonResponse(slime); } private HttpResponse tenant(String tenantName, HttpRequest request) { return controller.tenants().get(TenantName.from(tenantName)) .map(tenant -> tenant(tenant, request)) .orElseGet(() -> ErrorResponse.notFoundError("Tenant '" + tenantName + "' does not exist")); } private HttpResponse tenant(Tenant tenant, HttpRequest request) { Slime slime = new Slime(); toSlime(slime.setObject(), tenant, controller.applications().asList(tenant.name()), request); return new SlimeJsonResponse(slime); } private HttpResponse tenantInfo(String tenantName, HttpRequest request) { return controller.tenants().get(TenantName.from(tenantName)) .filter(tenant -> tenant.type() == Tenant.Type.cloud) .map(tenant -> tenantInfo(((CloudTenant)tenant).info(), request)) .orElseGet(() -> ErrorResponse.notFoundError("Tenant '" + tenantName + "' does not exist or does not support this")); } private SlimeJsonResponse tenantInfo(TenantInfo info, HttpRequest request) { Slime slime = new Slime(); Cursor infoCursor = slime.setObject(); if (!info.isEmpty()) { infoCursor.setString("name", info.name()); infoCursor.setString("email", info.email()); infoCursor.setString("website", info.website()); infoCursor.setString("invoiceEmail", info.invoiceEmail()); infoCursor.setString("contactName", info.contactName()); infoCursor.setString("contactEmail", info.contactEmail()); toSlime(info.address(), infoCursor); toSlime(info.billingContact(), infoCursor); } return new SlimeJsonResponse(slime); } private void toSlime(TenantInfoAddress address, Cursor parentCursor) { if (address.isEmpty()) return; Cursor addressCursor = parentCursor.setObject("address"); addressCursor.setString("addressLines", address.addressLines()); addressCursor.setString("postalCodeOrZip", address.postalCodeOrZip()); addressCursor.setString("city", address.city()); addressCursor.setString("stateRegionProvince", address.stateRegionProvince()); addressCursor.setString("country", address.country()); } private void toSlime(TenantInfoBillingContact billingContact, Cursor parentCursor) { if (billingContact.isEmpty()) return; Cursor addressCursor = parentCursor.setObject("billingContact"); addressCursor.setString("name", billingContact.name()); addressCursor.setString("email", billingContact.email()); addressCursor.setString("phone", billingContact.phone()); toSlime(billingContact.address(), addressCursor); } private HttpResponse updateTenantInfo(String tenantName, HttpRequest request) { return controller.tenants().get(TenantName.from(tenantName)) .filter(tenant -> tenant.type() == Tenant.Type.cloud) .map(tenant -> updateTenantInfo(((CloudTenant)tenant), request)) .orElseGet(() -> ErrorResponse.notFoundError("Tenant '" + tenantName + "' does not exist or does not support this")); } private String getString(Inspector field, String defaultVale) { return field.valid() ? field.asString() : defaultVale; } private SlimeJsonResponse updateTenantInfo(CloudTenant tenant, HttpRequest request) { TenantInfo oldInfo = tenant.info(); // Merge info from request with the existing info Inspector insp = toSlime(request.getData()).get(); TenantInfo mergedInfo = TenantInfo.EMPTY .withName(getString(insp.field("name"), oldInfo.name())) .withEmail(getString(insp.field("email"), oldInfo.email())) .withWebsite(getString(insp.field("website"), oldInfo.email())) .withInvoiceEmail(getString(insp.field("invoiceEmail"), oldInfo.invoiceEmail())) .withContactName(getString(insp.field("contactName"), oldInfo.contactName())) .withContactEmail(getString(insp.field("contactEmail"), oldInfo.contactName())) .withAddress(updateTenantInfoAddress(insp.field("address"), oldInfo.address())) .withBillingContact(updateTenantInfoBillingContact(insp.field("billingContact"), oldInfo.billingContact())); // Store changes controller.tenants().lockOrThrow(tenant.name(), LockedTenant.Cloud.class, lockedTenant -> { lockedTenant = lockedTenant.withInfo(mergedInfo); controller.tenants().store(lockedTenant); }); return new MessageResponse("Tenant info updated"); } private TenantInfoAddress updateTenantInfoAddress(Inspector insp, TenantInfoAddress oldAddress) { if (!insp.valid()) return oldAddress; return TenantInfoAddress.EMPTY .withCountry(getString(insp.field("country"), oldAddress.country())) .withStateRegionProvince(getString(insp.field("stateRegionProvince"), oldAddress.stateRegionProvince())) .withCity(getString(insp.field("city"), oldAddress.city())) .withPostalCodeOrZip(getString(insp.field("postalCodeOrZip"), oldAddress.postalCodeOrZip())) .withAddressLines(getString(insp.field("addressLines"), oldAddress.addressLines())); } private TenantInfoBillingContact updateTenantInfoBillingContact(Inspector insp, TenantInfoBillingContact oldContact) { if (!insp.valid()) return oldContact; return TenantInfoBillingContact.EMPTY .withName(getString(insp.field("name"), oldContact.name())) .withEmail(getString(insp.field("email"), oldContact.email())) .withPhone(getString(insp.field("phone"), oldContact.phone())) .withAddress(updateTenantInfoAddress(insp.field("address"), oldContact.address())); } private HttpResponse notifications(String tenantName, HttpRequest request) { NotificationSource notificationSource = new NotificationSource(TenantName.from(tenantName), Optional.ofNullable(request.getProperty("application")).map(ApplicationName::from), Optional.ofNullable(request.getProperty("instance")).map(InstanceName::from), Optional.empty(), Optional.empty(), Optional.empty(), OptionalLong.empty()); Slime slime = new Slime(); Cursor notificationsArray = slime.setObject().setArray("notifications"); controller.notificationsDb().listNotifications(notificationSource, showOnlyProductionInstances(request)) .forEach(notification -> toSlime(notificationsArray.addObject(), notification)); return new SlimeJsonResponse(slime); } private static void toSlime(Cursor cursor, Notification notification) { cursor.setLong("at", notification.at().toEpochMilli()); cursor.setString("level", notificationLevelAsString(notification.level())); cursor.setString("type", notificationTypeAsString(notification.type())); Cursor messagesArray = cursor.setArray("messages"); notification.messages().forEach(messagesArray::addString); notification.source().application().ifPresent(application -> cursor.setString("application", application.value())); notification.source().instance().ifPresent(instance -> cursor.setString("instance", instance.value())); notification.source().zoneId().ifPresent(zoneId -> { cursor.setString("environment", zoneId.environment().value()); cursor.setString("region", zoneId.region().value()); }); notification.source().clusterId().ifPresent(clusterId -> cursor.setString("clusterId", clusterId.value())); notification.source().jobType().ifPresent(jobType -> cursor.setString("jobName", jobType.jobName())); notification.source().runNumber().ifPresent(runNumber -> cursor.setLong("runNumber", runNumber)); } private static String notificationTypeAsString(Notification.Type type) { switch (type) { case applicationPackage: return "applicationPackage"; case deployment: return "deployment"; case feedBlock: return "feedBlock"; default: throw new IllegalArgumentException("No serialization defined for notification type " + type); } } private static String notificationLevelAsString(Notification.Level level) { switch (level) { case warning: return "warning"; case error: return "error"; default: throw new IllegalArgumentException("No serialization defined for notification level " + level); } } private HttpResponse applications(String tenantName, Optional<String> applicationName, HttpRequest request) { TenantName tenant = TenantName.from(tenantName); if (controller.tenants().get(tenantName).isEmpty()) return ErrorResponse.notFoundError("Tenant '" + tenantName + "' does not exist"); Slime slime = new Slime(); Cursor applicationArray = slime.setArray(); for (Application application : controller.applications().asList(tenant)) { if (applicationName.map(application.id().application().value()::equals).orElse(true)) { Cursor applicationObject = applicationArray.addObject(); applicationObject.setString("tenant", application.id().tenant().value()); applicationObject.setString("application", application.id().application().value()); applicationObject.setString("url", withPath("/application/v4" + "/tenant/" + application.id().tenant().value() + "/application/" + application.id().application().value(), request.getUri()).toString()); Cursor instanceArray = applicationObject.setArray("instances"); for (InstanceName instance : showOnlyProductionInstances(request) ? application.productionInstances().keySet() : application.instances().keySet()) { Cursor instanceObject = instanceArray.addObject(); instanceObject.setString("instance", instance.value()); instanceObject.setString("url", withPath("/application/v4" + "/tenant/" + application.id().tenant().value() + "/application/" + application.id().application().value() + "/instance/" + instance.value(), request.getUri()).toString()); } } } return new SlimeJsonResponse(slime); } private HttpResponse devApplicationPackage(ApplicationId id, JobType type) { if ( ! type.environment().isManuallyDeployed()) throw new IllegalArgumentException("Only manually deployed zones have dev packages"); ZoneId zone = type.zone(controller.system()); byte[] applicationPackage = controller.applications().applicationStore().getDev(id, zone); return new ZipResponse(id.toFullString() + "." + zone.value() + ".zip", applicationPackage); } private HttpResponse applicationPackage(String tenantName, String applicationName, HttpRequest request) { var tenantAndApplication = TenantAndApplicationId.from(tenantName, applicationName); var applicationId = ApplicationId.from(tenantName, applicationName, InstanceName.defaultName().value()); long buildNumber; var requestedBuild = Optional.ofNullable(request.getProperty("build")).map(build -> { try { return Long.parseLong(build); } catch (NumberFormatException e) { throw new IllegalArgumentException("Invalid build number", e); } }); if (requestedBuild.isEmpty()) { // Fall back to latest build var application = controller.applications().requireApplication(tenantAndApplication); var latestBuild = application.latestVersion().map(ApplicationVersion::buildNumber).orElse(OptionalLong.empty()); if (latestBuild.isEmpty()) { throw new NotExistsException("No application package has been submitted for '" + tenantAndApplication + "'"); } buildNumber = latestBuild.getAsLong(); } else { buildNumber = requestedBuild.get(); } var applicationPackage = controller.applications().applicationStore().find(tenantAndApplication.tenant(), tenantAndApplication.application(), buildNumber); var filename = tenantAndApplication + "-build" + buildNumber + ".zip"; if (applicationPackage.isEmpty()) { throw new NotExistsException("No application package found for '" + tenantAndApplication + "' with build number " + buildNumber); } return new ZipResponse(filename, applicationPackage.get()); } private HttpResponse application(String tenantName, String applicationName, HttpRequest request) { Slime slime = new Slime(); toSlime(slime.setObject(), getApplication(tenantName, applicationName), request); return new SlimeJsonResponse(slime); } private HttpResponse compileVersion(String tenantName, String applicationName) { Slime slime = new Slime(); slime.setObject().setString("compileVersion", compileVersion(TenantAndApplicationId.from(tenantName, applicationName)).toFullString()); return new SlimeJsonResponse(slime); } private HttpResponse instance(String tenantName, String applicationName, String instanceName, HttpRequest request) { Slime slime = new Slime(); toSlime(slime.setObject(), getInstance(tenantName, applicationName, instanceName), controller.jobController().deploymentStatus(getApplication(tenantName, applicationName)), request); return new SlimeJsonResponse(slime); } private HttpResponse addDeveloperKey(String tenantName, HttpRequest request) { if (controller.tenants().require(TenantName.from(tenantName)).type() != Tenant.Type.cloud) throw new IllegalArgumentException("Tenant '" + tenantName + "' is not a cloud tenant"); Principal user = request.getJDiscRequest().getUserPrincipal(); String pemDeveloperKey = toSlime(request.getData()).get().field("key").asString(); PublicKey developerKey = KeyUtils.fromPemEncodedPublicKey(pemDeveloperKey); Slime root = new Slime(); controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, tenant -> { tenant = tenant.withDeveloperKey(developerKey, user); toSlime(root.setObject().setArray("keys"), tenant.get().developerKeys()); controller.tenants().store(tenant); }); return new SlimeJsonResponse(root); } private HttpResponse validateSecretStore(String tenantName, String secretStoreName, HttpRequest request) { var awsRegion = request.getProperty("aws-region"); var parameterName = request.getProperty("parameter-name"); var applicationId = ApplicationId.fromFullString(request.getProperty("application-id")); var zoneId = ZoneId.from(request.getProperty("zone")); var deploymentId = new DeploymentId(applicationId, zoneId); var tenant = controller.tenants().require(applicationId.tenant(), CloudTenant.class); var tenantSecretStore = tenant.tenantSecretStores() .stream() .filter(secretStore -> secretStore.getName().equals(secretStoreName)) .findFirst(); if (tenantSecretStore.isEmpty()) return ErrorResponse.notFoundError("No secret store '" + secretStoreName + "' configured for tenant '" + tenantName + "'"); var response = controller.serviceRegistry().configServer().validateSecretStore(deploymentId, tenantSecretStore.get(), awsRegion, parameterName); try { var responseRoot = new Slime(); var responseCursor = responseRoot.setObject(); responseCursor.setString("target", deploymentId.toString()); var responseResultCursor = responseCursor.setObject("result"); var responseSlime = SlimeUtils.jsonToSlime(response); SlimeUtils.copyObject(responseSlime.get(), responseResultCursor); return new SlimeJsonResponse(responseRoot); } catch (JsonParseException e) { return ErrorResponse.internalServerError(response); } } private HttpResponse removeDeveloperKey(String tenantName, HttpRequest request) { if (controller.tenants().require(TenantName.from(tenantName)).type() != Tenant.Type.cloud) throw new IllegalArgumentException("Tenant '" + tenantName + "' is not a cloud tenant"); String pemDeveloperKey = toSlime(request.getData()).get().field("key").asString(); PublicKey developerKey = KeyUtils.fromPemEncodedPublicKey(pemDeveloperKey); Principal user = controller.tenants().require(TenantName.from(tenantName), CloudTenant.class).developerKeys().get(developerKey); Slime root = new Slime(); controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, tenant -> { tenant = tenant.withoutDeveloperKey(developerKey); toSlime(root.setObject().setArray("keys"), tenant.get().developerKeys()); controller.tenants().store(tenant); }); return new SlimeJsonResponse(root); } private void toSlime(Cursor keysArray, Map<PublicKey, Principal> keys) { keys.forEach((key, principal) -> { Cursor keyObject = keysArray.addObject(); keyObject.setString("key", KeyUtils.toPem(key)); keyObject.setString("user", principal.getName()); }); } private HttpResponse addDeployKey(String tenantName, String applicationName, HttpRequest request) { String pemDeployKey = toSlime(request.getData()).get().field("key").asString(); PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey); Slime root = new Slime(); controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application -> { application = application.withDeployKey(deployKey); application.get().deployKeys().stream() .map(KeyUtils::toPem) .forEach(root.setObject().setArray("keys")::addString); controller.applications().store(application); }); return new SlimeJsonResponse(root); } private HttpResponse removeDeployKey(String tenantName, String applicationName, HttpRequest request) { String pemDeployKey = toSlime(request.getData()).get().field("key").asString(); PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey); Slime root = new Slime(); controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application -> { application = application.withoutDeployKey(deployKey); application.get().deployKeys().stream() .map(KeyUtils::toPem) .forEach(root.setObject().setArray("keys")::addString); controller.applications().store(application); }); return new SlimeJsonResponse(root); } private HttpResponse addSecretStore(String tenantName, String name, HttpRequest request) { if (controller.tenants().require(TenantName.from(tenantName)).type() != Tenant.Type.cloud) throw new IllegalArgumentException("Tenant '" + tenantName + "' is not a cloud tenant"); var data = toSlime(request.getData()).get(); var awsId = mandatory("awsId", data).asString(); var externalId = mandatory("externalId", data).asString(); var role = mandatory("role", data).asString(); var tenant = controller.tenants().require(TenantName.from(tenantName), CloudTenant.class); var tenantSecretStore = new TenantSecretStore(name, awsId, role); if (!tenantSecretStore.isValid()) { return ErrorResponse.badRequest("Secret store " + tenantSecretStore + " is invalid"); } if (tenant.tenantSecretStores().contains(tenantSecretStore)) { return ErrorResponse.badRequest("Secret store " + tenantSecretStore + " is already configured"); } controller.serviceRegistry().roleService().createTenantPolicy(TenantName.from(tenantName), name, awsId, role); controller.serviceRegistry().tenantSecretService().addSecretStore(tenant.name(), tenantSecretStore, externalId); // Store changes controller.tenants().lockOrThrow(tenant.name(), LockedTenant.Cloud.class, lockedTenant -> { lockedTenant = lockedTenant.withSecretStore(tenantSecretStore); controller.tenants().store(lockedTenant); }); tenant = controller.tenants().require(TenantName.from(tenantName), CloudTenant.class); var slime = new Slime(); toSlime(slime.setObject(), tenant.tenantSecretStores()); return new SlimeJsonResponse(slime); } private HttpResponse deleteSecretStore(String tenantName, String name, HttpRequest request) { var tenant = controller.tenants().require(TenantName.from(tenantName), CloudTenant.class); var optionalSecretStore = tenant.tenantSecretStores().stream() .filter(secretStore -> secretStore.getName().equals(name)) .findFirst(); if (optionalSecretStore.isEmpty()) return ErrorResponse.notFoundError("Could not delete secret store '" + name + "': Secret store not found"); var tenantSecretStore = optionalSecretStore.get(); controller.serviceRegistry().tenantSecretService().deleteSecretStore(tenant.name(), tenantSecretStore); controller.serviceRegistry().roleService().deleteTenantPolicy(tenant.name(), tenantSecretStore.getName(), tenantSecretStore.getRole()); controller.tenants().lockOrThrow(tenant.name(), LockedTenant.Cloud.class, lockedTenant -> { lockedTenant = lockedTenant.withoutSecretStore(tenantSecretStore); controller.tenants().store(lockedTenant); }); tenant = controller.tenants().require(TenantName.from(tenantName), CloudTenant.class); var slime = new Slime(); toSlime(slime.setObject(), tenant.tenantSecretStores()); return new SlimeJsonResponse(slime); } private HttpResponse allowArchiveAccess(String tenantName, HttpRequest request) { if (controller.tenants().require(TenantName.from(tenantName)).type() != Tenant.Type.cloud) throw new IllegalArgumentException("Tenant '" + tenantName + "' is not a cloud tenant"); var data = toSlime(request.getData()).get(); var role = mandatory("role", data).asString(); if (role.isBlank()) { return ErrorResponse.badRequest("Archive access role can't be whitespace only"); } controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, lockedTenant -> { lockedTenant = lockedTenant.withArchiveAccessRole(Optional.of(role)); controller.tenants().store(lockedTenant); }); return new MessageResponse("Archive access role set to '" + role + "' for tenant " + tenantName + "."); } private HttpResponse removeArchiveAccess(String tenantName) { if (controller.tenants().require(TenantName.from(tenantName)).type() != Tenant.Type.cloud) throw new IllegalArgumentException("Tenant '" + tenantName + "' is not a cloud tenant"); controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, lockedTenant -> { lockedTenant = lockedTenant.withArchiveAccessRole(Optional.empty()); controller.tenants().store(lockedTenant); }); return new MessageResponse("Archive access role removed for tenant " + tenantName + "."); } private HttpResponse patchApplication(String tenantName, String applicationName, HttpRequest request) { Inspector requestObject = toSlime(request.getData()).get(); StringJoiner messageBuilder = new StringJoiner("\n").setEmptyValue("No applicable changes."); controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application -> { Inspector majorVersionField = requestObject.field("majorVersion"); if (majorVersionField.valid()) { Integer majorVersion = majorVersionField.asLong() == 0 ? null : (int) majorVersionField.asLong(); application = application.withMajorVersion(majorVersion); messageBuilder.add("Set major version to " + (majorVersion == null ? "empty" : majorVersion)); } // TODO jonmv: Remove when clients are updated. Inspector pemDeployKeyField = requestObject.field("pemDeployKey"); if (pemDeployKeyField.valid()) { String pemDeployKey = pemDeployKeyField.asString(); PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey); application = application.withDeployKey(deployKey); messageBuilder.add("Added deploy key " + pemDeployKey); } controller.applications().store(application); }); return new MessageResponse(messageBuilder.toString()); } private Application getApplication(String tenantName, String applicationName) { TenantAndApplicationId applicationId = TenantAndApplicationId.from(tenantName, applicationName); return controller.applications().getApplication(applicationId) .orElseThrow(() -> new NotExistsException(applicationId + " not found")); } private Instance getInstance(String tenantName, String applicationName, String instanceName) { ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName); return controller.applications().getInstance(applicationId) .orElseThrow(() -> new NotExistsException(applicationId + " not found")); } private HttpResponse nodes(String tenantName, String applicationName, String instanceName, String environment, String region) { ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName); ZoneId zone = requireZone(environment, region); List<Node> nodes = controller.serviceRegistry().configServer().nodeRepository().list(zone, id); Slime slime = new Slime(); Cursor nodesArray = slime.setObject().setArray("nodes"); for (Node node : nodes) { Cursor nodeObject = nodesArray.addObject(); nodeObject.setString("hostname", node.hostname().value()); nodeObject.setString("state", valueOf(node.state())); node.reservedTo().ifPresent(tenant -> nodeObject.setString("reservedTo", tenant.value())); nodeObject.setString("orchestration", valueOf(node.serviceState())); nodeObject.setString("version", node.currentVersion().toString()); nodeObject.setString("flavor", node.flavor()); toSlime(node.resources(), nodeObject); nodeObject.setString("clusterId", node.clusterId()); nodeObject.setString("clusterType", valueOf(node.clusterType())); nodeObject.setBool("down", node.history().stream().anyMatch(event -> "down".equals(event.getEvent()))); nodeObject.setBool("retired", node.retired() || node.wantToRetire()); nodeObject.setBool("restarting", node.wantedRestartGeneration() > node.restartGeneration()); nodeObject.setBool("rebooting", node.wantedRebootGeneration() > node.rebootGeneration()); } return new SlimeJsonResponse(slime); } private HttpResponse clusters(String tenantName, String applicationName, String instanceName, String environment, String region) { ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName); ZoneId zone = requireZone(environment, region); com.yahoo.vespa.hosted.controller.api.integration.configserver.Application application = controller.serviceRegistry().configServer().nodeRepository().getApplication(zone, id); Slime slime = new Slime(); Cursor clustersObject = slime.setObject().setObject("clusters"); for (Cluster cluster : application.clusters().values()) { Cursor clusterObject = clustersObject.setObject(cluster.id().value()); clusterObject.setString("type", cluster.type().name()); toSlime(cluster.min(), clusterObject.setObject("min")); toSlime(cluster.max(), clusterObject.setObject("max")); toSlime(cluster.current(), clusterObject.setObject("current")); if (cluster.target().isPresent() && ! cluster.target().get().justNumbers().equals(cluster.current().justNumbers())) toSlime(cluster.target().get(), clusterObject.setObject("target")); cluster.suggested().ifPresent(suggested -> toSlime(suggested, clusterObject.setObject("suggested"))); utilizationToSlime(cluster.utilization(), clusterObject.setObject("utilization")); scalingEventsToSlime(cluster.scalingEvents(), clusterObject.setArray("scalingEvents")); clusterObject.setString("autoscalingStatus", cluster.autoscalingStatus()); clusterObject.setLong("scalingDuration", cluster.scalingDuration().toMillis()); clusterObject.setDouble("maxQueryGrowthRate", cluster.maxQueryGrowthRate()); clusterObject.setDouble("currentQueryFractionOfMax", cluster.currentQueryFractionOfMax()); } return new SlimeJsonResponse(slime); } private static String valueOf(Node.State state) { switch (state) { case failed: return "failed"; case parked: return "parked"; case dirty: return "dirty"; case ready: return "ready"; case active: return "active"; case inactive: return "inactive"; case reserved: return "reserved"; case provisioned: return "provisioned"; default: throw new IllegalArgumentException("Unexpected node state '" + state + "'."); } } static String valueOf(Node.ServiceState state) { switch (state) { case expectedUp: return "expectedUp"; case allowedDown: return "allowedDown"; case permanentlyDown: return "permanentlyDown"; case unorchestrated: return "unorchestrated"; case unknown: break; } return "unknown"; } private static String valueOf(Node.ClusterType type) { switch (type) { case admin: return "admin"; case content: return "content"; case container: return "container"; case combined: return "combined"; default: throw new IllegalArgumentException("Unexpected node cluster type '" + type + "'."); } } private static String valueOf(NodeResources.DiskSpeed diskSpeed) { switch (diskSpeed) { case fast : return "fast"; case slow : return "slow"; case any : return "any"; default: throw new IllegalArgumentException("Unknown disk speed '" + diskSpeed.name() + "'"); } } private static String valueOf(NodeResources.StorageType storageType) { switch (storageType) { case remote : return "remote"; case local : return "local"; case any : return "any"; default: throw new IllegalArgumentException("Unknown storage type '" + storageType.name() + "'"); } } private HttpResponse logs(String tenantName, String applicationName, String instanceName, String environment, String region, Map<String, String> queryParameters) { ApplicationId application = ApplicationId.from(tenantName, applicationName, instanceName); ZoneId zone = requireZone(environment, region); DeploymentId deployment = new DeploymentId(application, zone); InputStream logStream = controller.serviceRegistry().configServer().getLogs(deployment, queryParameters); return new HttpResponse(200) { @Override public void render(OutputStream outputStream) throws IOException { logStream.transferTo(outputStream); } }; } private HttpResponse supportAccess(String tenantName, String applicationName, String instanceName, String environment, String region, Map<String, String> queryParameters) { DeploymentId deployment = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName), requireZone(environment, region)); SupportAccess supportAccess = controller.supportAccess().forDeployment(deployment); return new SlimeJsonResponse(SupportAccessSerializer.toSlime(supportAccess, false, Optional.ofNullable(controller.clock().instant()))); } // TODO support access: only let tenants (not operators!) allow access // TODO support access: configurable period of access? private HttpResponse allowSupportAccess(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) { DeploymentId deployment = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName), requireZone(environment, region)); Principal principal = requireUserPrincipal(request); SupportAccess allowed = controller.supportAccess().allow(deployment, Instant.now().plus(7, ChronoUnit.DAYS), principal.getName()); return new SlimeJsonResponse(SupportAccessSerializer.toSlime(allowed, false, Optional.ofNullable(controller.clock().instant()))); } private HttpResponse disallowSupportAccess(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) { DeploymentId deployment = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName), requireZone(environment, region)); Principal principal = requireUserPrincipal(request); SupportAccess disallowed = controller.supportAccess().disallow(deployment, principal.getName()); return new SlimeJsonResponse(SupportAccessSerializer.toSlime(disallowed, false, Optional.ofNullable(controller.clock().instant()))); } private HttpResponse metrics(String tenantName, String applicationName, String instanceName, String environment, String region) { ApplicationId application = ApplicationId.from(tenantName, applicationName, instanceName); ZoneId zone = requireZone(environment, region); DeploymentId deployment = new DeploymentId(application, zone); List<ProtonMetrics> protonMetrics = controller.serviceRegistry().configServer().getProtonMetrics(deployment); return buildResponseFromProtonMetrics(protonMetrics); } private JsonResponse buildResponseFromProtonMetrics(List<ProtonMetrics> protonMetrics) { try { var jsonObject = jsonMapper.createObjectNode(); var jsonArray = jsonMapper.createArrayNode(); for (ProtonMetrics metrics : protonMetrics) { jsonArray.add(metrics.toJson()); } jsonObject.set("metrics", jsonArray); return new JsonResponse(200, jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject)); } catch (JsonProcessingException e) { log.log(Level.WARNING, "Unable to build JsonResponse with Proton data: " + e.getMessage(), e); return new JsonResponse(500, ""); } } private HttpResponse trigger(ApplicationId id, JobType type, HttpRequest request) { Inspector requestObject = toSlime(request.getData()).get(); boolean requireTests = ! requestObject.field("skipTests").asBool(); boolean reTrigger = requestObject.field("reTrigger").asBool(); String triggered = reTrigger ? controller.applications().deploymentTrigger() .reTrigger(id, type).type().jobName() : controller.applications().deploymentTrigger() .forceTrigger(id, type, request.getJDiscRequest().getUserPrincipal().getName(), requireTests) .stream().map(job -> job.type().jobName()).collect(joining(", ")); return new MessageResponse(triggered.isEmpty() ? "Job " + type.jobName() + " for " + id + " not triggered" : "Triggered " + triggered + " for " + id); } private HttpResponse pause(ApplicationId id, JobType type) { Instant until = controller.clock().instant().plus(DeploymentTrigger.maxPause); controller.applications().deploymentTrigger().pauseJob(id, type, until); return new MessageResponse(type.jobName() + " for " + id + " paused for " + DeploymentTrigger.maxPause); } private HttpResponse resume(ApplicationId id, JobType type) { controller.applications().deploymentTrigger().resumeJob(id, type); return new MessageResponse(type.jobName() + " for " + id + " resumed"); } private void toSlime(Cursor object, Application application, HttpRequest request) { object.setString("tenant", application.id().tenant().value()); object.setString("application", application.id().application().value()); object.setString("deployments", withPath("/application/v4" + "/tenant/" + application.id().tenant().value() + "/application/" + application.id().application().value() + "/job/", request.getUri()).toString()); DeploymentStatus status = controller.jobController().deploymentStatus(application); application.latestVersion().ifPresent(version -> toSlime(version, object.setObject("latestVersion"))); application.projectId().ifPresent(id -> object.setLong("projectId", id)); // TODO jonmv: Remove this when users are updated. application.instances().values().stream().findFirst().ifPresent(instance -> { // Currently deploying change if ( ! instance.change().isEmpty()) toSlime(object.setObject("deploying"), instance.change()); // Outstanding change if ( ! status.outstandingChange(instance.name()).isEmpty()) toSlime(object.setObject("outstandingChange"), status.outstandingChange(instance.name())); }); application.majorVersion().ifPresent(majorVersion -> object.setLong("majorVersion", majorVersion)); Cursor instancesArray = object.setArray("instances"); for (Instance instance : showOnlyProductionInstances(request) ? application.productionInstances().values() : application.instances().values()) toSlime(instancesArray.addObject(), status, instance, application.deploymentSpec(), request); application.deployKeys().stream().map(KeyUtils::toPem).forEach(object.setArray("pemDeployKeys")::addString); // Metrics Cursor metricsObject = object.setObject("metrics"); metricsObject.setDouble("queryServiceQuality", application.metrics().queryServiceQuality()); metricsObject.setDouble("writeServiceQuality", application.metrics().writeServiceQuality()); // Activity Cursor activity = object.setObject("activity"); application.activity().lastQueried().ifPresent(instant -> activity.setLong("lastQueried", instant.toEpochMilli())); application.activity().lastWritten().ifPresent(instant -> activity.setLong("lastWritten", instant.toEpochMilli())); application.activity().lastQueriesPerSecond().ifPresent(value -> activity.setDouble("lastQueriesPerSecond", value)); application.activity().lastWritesPerSecond().ifPresent(value -> activity.setDouble("lastWritesPerSecond", value)); application.ownershipIssueId().ifPresent(issueId -> object.setString("ownershipIssueId", issueId.value())); application.owner().ifPresent(owner -> object.setString("owner", owner.username())); application.deploymentIssueId().ifPresent(issueId -> object.setString("deploymentIssueId", issueId.value())); } // TODO: Eliminate duplicated code in this and toSlime(Cursor, Instance, DeploymentStatus, HttpRequest) private void toSlime(Cursor object, DeploymentStatus status, Instance instance, DeploymentSpec deploymentSpec, HttpRequest request) { object.setString("instance", instance.name().value()); if (deploymentSpec.instance(instance.name()).isPresent()) { // Jobs sorted according to deployment spec List<JobStatus> jobStatus = controller.applications().deploymentTrigger() .steps(deploymentSpec.requireInstance(instance.name())) .sortedJobs(status.instanceJobs(instance.name()).values()); if ( ! instance.change().isEmpty()) toSlime(object.setObject("deploying"), instance.change()); // Outstanding change if ( ! status.outstandingChange(instance.name()).isEmpty()) toSlime(object.setObject("outstandingChange"), status.outstandingChange(instance.name())); // Change blockers Cursor changeBlockers = object.setArray("changeBlockers"); deploymentSpec.instance(instance.name()).ifPresent(spec -> spec.changeBlocker().forEach(changeBlocker -> { Cursor changeBlockerObject = changeBlockers.addObject(); changeBlockerObject.setBool("versions", changeBlocker.blocksVersions()); changeBlockerObject.setBool("revisions", changeBlocker.blocksRevisions()); changeBlockerObject.setString("timeZone", changeBlocker.window().zone().getId()); Cursor days = changeBlockerObject.setArray("days"); changeBlocker.window().days().stream().map(DayOfWeek::getValue).forEach(days::addLong); Cursor hours = changeBlockerObject.setArray("hours"); changeBlocker.window().hours().forEach(hours::addLong); })); } // Global endpoints globalEndpointsToSlime(object, instance); // Deployments sorted according to deployment spec List<Deployment> deployments = deploymentSpec.instance(instance.name()) .map(spec -> new DeploymentSteps(spec, controller::system)) .map(steps -> steps.sortedDeployments(instance.deployments().values())) .orElse(List.copyOf(instance.deployments().values())); Cursor deploymentsArray = object.setArray("deployments"); for (Deployment deployment : deployments) { Cursor deploymentObject = deploymentsArray.addObject(); // Rotation status for this deployment if (deployment.zone().environment() == Environment.prod && ! instance.rotations().isEmpty()) toSlime(instance.rotations(), instance.rotationStatus(), deployment, deploymentObject); if (recurseOverDeployments(request)) // List full deployment information when recursive. toSlime(deploymentObject, new DeploymentId(instance.id(), deployment.zone()), deployment, request); else { deploymentObject.setString("environment", deployment.zone().environment().value()); deploymentObject.setString("region", deployment.zone().region().value()); deploymentObject.setString("url", withPath(request.getUri().getPath() + "/instance/" + instance.name().value() + "/environment/" + deployment.zone().environment().value() + "/region/" + deployment.zone().region().value(), request.getUri()).toString()); } } } // TODO(mpolden): Remove once legacy dashboard and integration tests stop expecting these fields private void globalEndpointsToSlime(Cursor object, Instance instance) { var globalEndpointUrls = new LinkedHashSet<String>(); // Add global endpoints backed by rotations controller.routing().endpointsOf(instance.id()) .requiresRotation() .not().legacy() // Hide legacy names .asList().stream() .map(Endpoint::url) .map(URI::toString) .forEach(globalEndpointUrls::add); var globalRotationsArray = object.setArray("globalRotations"); globalEndpointUrls.forEach(globalRotationsArray::addString); // Legacy field. Identifies the first assigned rotation, if any. instance.rotations().stream() .map(AssignedRotation::rotationId) .findFirst() .ifPresent(rotation -> object.setString("rotationId", rotation.asString())); } private void toSlime(Cursor object, Instance instance, DeploymentStatus status, HttpRequest request) { Application application = status.application(); object.setString("tenant", instance.id().tenant().value()); object.setString("application", instance.id().application().value()); object.setString("instance", instance.id().instance().value()); object.setString("deployments", withPath("/application/v4" + "/tenant/" + instance.id().tenant().value() + "/application/" + instance.id().application().value() + "/instance/" + instance.id().instance().value() + "/job/", request.getUri()).toString()); application.latestVersion().ifPresent(version -> { sourceRevisionToSlime(version.source(), object.setObject("source")); version.sourceUrl().ifPresent(url -> object.setString("sourceUrl", url)); version.commit().ifPresent(commit -> object.setString("commit", commit)); }); application.projectId().ifPresent(id -> object.setLong("projectId", id)); if (application.deploymentSpec().instance(instance.name()).isPresent()) { // Jobs sorted according to deployment spec List<JobStatus> jobStatus = controller.applications().deploymentTrigger() .steps(application.deploymentSpec().requireInstance(instance.name())) .sortedJobs(status.instanceJobs(instance.name()).values()); if ( ! instance.change().isEmpty()) toSlime(object.setObject("deploying"), instance.change()); // Outstanding change if ( ! status.outstandingChange(instance.name()).isEmpty()) toSlime(object.setObject("outstandingChange"), status.outstandingChange(instance.name())); // Change blockers Cursor changeBlockers = object.setArray("changeBlockers"); application.deploymentSpec().instance(instance.name()).ifPresent(spec -> spec.changeBlocker().forEach(changeBlocker -> { Cursor changeBlockerObject = changeBlockers.addObject(); changeBlockerObject.setBool("versions", changeBlocker.blocksVersions()); changeBlockerObject.setBool("revisions", changeBlocker.blocksRevisions()); changeBlockerObject.setString("timeZone", changeBlocker.window().zone().getId()); Cursor days = changeBlockerObject.setArray("days"); changeBlocker.window().days().stream().map(DayOfWeek::getValue).forEach(days::addLong); Cursor hours = changeBlockerObject.setArray("hours"); changeBlocker.window().hours().forEach(hours::addLong); })); } application.majorVersion().ifPresent(majorVersion -> object.setLong("majorVersion", majorVersion)); // Global endpoint globalEndpointsToSlime(object, instance); // Deployments sorted according to deployment spec List<Deployment> deployments = application.deploymentSpec().instance(instance.name()) .map(spec -> new DeploymentSteps(spec, controller::system)) .map(steps -> steps.sortedDeployments(instance.deployments().values())) .orElse(List.copyOf(instance.deployments().values())); Cursor instancesArray = object.setArray("instances"); for (Deployment deployment : deployments) { Cursor deploymentObject = instancesArray.addObject(); // Rotation status for this deployment if (deployment.zone().environment() == Environment.prod) { // 0 rotations: No fields written // 1 rotation : Write legacy field and endpointStatus field // >1 rotation : Write only endpointStatus field if (instance.rotations().size() == 1) { // TODO(mpolden): Stop writing this field once clients stop expecting it toSlime(instance.rotationStatus().of(instance.rotations().get(0).rotationId(), deployment), deploymentObject); } if ( ! recurseOverDeployments(request) && ! instance.rotations().isEmpty()) { // TODO jonmv: clean up when clients have converged. toSlime(instance.rotations(), instance.rotationStatus(), deployment, deploymentObject); } } if (recurseOverDeployments(request)) // List full deployment information when recursive. toSlime(deploymentObject, new DeploymentId(instance.id(), deployment.zone()), deployment, request); else { deploymentObject.setString("environment", deployment.zone().environment().value()); deploymentObject.setString("region", deployment.zone().region().value()); deploymentObject.setString("instance", instance.id().instance().value()); // pointless deploymentObject.setString("url", withPath(request.getUri().getPath() + "/environment/" + deployment.zone().environment().value() + "/region/" + deployment.zone().region().value(), request.getUri()).toString()); } } // Add dummy values for not-yet-existent prod deployments. status.jobSteps().keySet().stream() .filter(job -> job.application().instance().equals(instance.name())) .filter(job -> job.type().isProduction() && job.type().isDeployment()) .map(job -> job.type().zone(controller.system())) .filter(zone -> ! instance.deployments().containsKey(zone)) .forEach(zone -> { Cursor deploymentObject = instancesArray.addObject(); deploymentObject.setString("environment", zone.environment().value()); deploymentObject.setString("region", zone.region().value()); }); // TODO jonmv: Remove when clients are updated application.deployKeys().stream().findFirst().ifPresent(key -> object.setString("pemDeployKey", KeyUtils.toPem(key))); application.deployKeys().stream().map(KeyUtils::toPem).forEach(object.setArray("pemDeployKeys")::addString); // Metrics Cursor metricsObject = object.setObject("metrics"); metricsObject.setDouble("queryServiceQuality", application.metrics().queryServiceQuality()); metricsObject.setDouble("writeServiceQuality", application.metrics().writeServiceQuality()); // Activity Cursor activity = object.setObject("activity"); application.activity().lastQueried().ifPresent(instant -> activity.setLong("lastQueried", instant.toEpochMilli())); application.activity().lastWritten().ifPresent(instant -> activity.setLong("lastWritten", instant.toEpochMilli())); application.activity().lastQueriesPerSecond().ifPresent(value -> activity.setDouble("lastQueriesPerSecond", value)); application.activity().lastWritesPerSecond().ifPresent(value -> activity.setDouble("lastWritesPerSecond", value)); application.ownershipIssueId().ifPresent(issueId -> object.setString("ownershipIssueId", issueId.value())); application.owner().ifPresent(owner -> object.setString("owner", owner.username())); application.deploymentIssueId().ifPresent(issueId -> object.setString("deploymentIssueId", issueId.value())); } private HttpResponse deployment(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) { ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName); Instance instance = controller.applications().getInstance(id) .orElseThrow(() -> new NotExistsException(id + " not found")); DeploymentId deploymentId = new DeploymentId(instance.id(), requireZone(environment, region)); Deployment deployment = instance.deployments().get(deploymentId.zoneId()); if (deployment == null) throw new NotExistsException(instance + " is not deployed in " + deploymentId.zoneId()); Slime slime = new Slime(); toSlime(slime.setObject(), deploymentId, deployment, request); return new SlimeJsonResponse(slime); } private void toSlime(Cursor object, Change change) { change.platform().ifPresent(version -> object.setString("version", version.toString())); change.application() .filter(version -> !version.isUnknown()) .ifPresent(version -> toSlime(version, object.setObject("revision"))); } private void toSlime(Endpoint endpoint, Cursor object) { object.setString("cluster", endpoint.cluster().value()); object.setBool("tls", endpoint.tls()); object.setString("url", endpoint.url().toString()); object.setString("scope", endpointScopeString(endpoint.scope())); object.setString("routingMethod", routingMethodString(endpoint.routingMethod())); object.setBool("legacy", endpoint.legacy()); } private void toSlime(Cursor response, DeploymentId deploymentId, Deployment deployment, HttpRequest request) { response.setString("tenant", deploymentId.applicationId().tenant().value()); response.setString("application", deploymentId.applicationId().application().value()); response.setString("instance", deploymentId.applicationId().instance().value()); // pointless response.setString("environment", deploymentId.zoneId().environment().value()); response.setString("region", deploymentId.zoneId().region().value()); var application = controller.applications().requireApplication(TenantAndApplicationId.from(deploymentId.applicationId())); // Add zone endpoints boolean legacyEndpoints = request.getBooleanProperty("includeLegacyEndpoints"); var endpointArray = response.setArray("endpoints"); EndpointList zoneEndpoints = controller.routing().endpointsOf(deploymentId) .scope(Endpoint.Scope.zone); if (!legacyEndpoints) { zoneEndpoints = zoneEndpoints.not().legacy(); } for (var endpoint : controller.routing().directEndpoints(zoneEndpoints, deploymentId.applicationId())) { toSlime(endpoint, endpointArray.addObject()); } // Add global endpoints EndpointList globalEndpoints = controller.routing().endpointsOf(application, deploymentId.applicationId().instance()) .targets(deploymentId.zoneId()); if (!legacyEndpoints) { globalEndpoints = globalEndpoints.not().legacy(); } for (var endpoint : controller.routing().directEndpoints(globalEndpoints, deploymentId.applicationId())) { toSlime(endpoint, endpointArray.addObject()); } response.setString("clusters", withPath(toPath(deploymentId) + "/clusters", request.getUri()).toString()); response.setString("nodes", withPathAndQuery("/zone/v2/" + deploymentId.zoneId().environment() + "/" + deploymentId.zoneId().region() + "/nodes/v2/node/", "recursive=true&application=" + deploymentId.applicationId().tenant() + "." + deploymentId.applicationId().application() + "." + deploymentId.applicationId().instance(), request.getUri()).toString()); response.setString("yamasUrl", monitoringSystemUri(deploymentId).toString()); response.setString("version", deployment.version().toFullString()); response.setString("revision", deployment.applicationVersion().id()); response.setLong("deployTimeEpochMs", deployment.at().toEpochMilli()); controller.zoneRegistry().getDeploymentTimeToLive(deploymentId.zoneId()) .ifPresent(deploymentTimeToLive -> response.setLong("expiryTimeEpochMs", deployment.at().plus(deploymentTimeToLive).toEpochMilli())); DeploymentStatus status = controller.jobController().deploymentStatus(application); application.projectId().ifPresent(i -> response.setString("screwdriverId", String.valueOf(i))); sourceRevisionToSlime(deployment.applicationVersion().source(), response); var instance = application.instances().get(deploymentId.applicationId().instance()); if (instance != null) { if (!instance.rotations().isEmpty() && deployment.zone().environment() == Environment.prod) toSlime(instance.rotations(), instance.rotationStatus(), deployment, response); JobType.from(controller.system(), deployment.zone()) .map(type -> new JobId(instance.id(), type)) .map(status.jobSteps()::get) .ifPresent(stepStatus -> { JobControllerApiHandlerHelper.applicationVersionToSlime( response.setObject("applicationVersion"), deployment.applicationVersion()); if (!status.jobsToRun().containsKey(stepStatus.job().get())) response.setString("status", "complete"); else if (stepStatus.readyAt(instance.change()).map(controller.clock().instant()::isBefore).orElse(true)) response.setString("status", "pending"); else response.setString("status", "running"); }); } controller.archiveBucketDb().archiveUriFor(deploymentId.zoneId(), deploymentId.applicationId().tenant()) .ifPresent(archiveUri -> response.setString("archiveUri", archiveUri.toString())); Cursor activity = response.setObject("activity"); deployment.activity().lastQueried().ifPresent(instant -> activity.setLong("lastQueried", instant.toEpochMilli())); deployment.activity().lastWritten().ifPresent(instant -> activity.setLong("lastWritten", instant.toEpochMilli())); deployment.activity().lastQueriesPerSecond().ifPresent(value -> activity.setDouble("lastQueriesPerSecond", value)); deployment.activity().lastWritesPerSecond().ifPresent(value -> activity.setDouble("lastWritesPerSecond", value)); // Metrics DeploymentMetrics metrics = deployment.metrics(); Cursor metricsObject = response.setObject("metrics"); metricsObject.setDouble("queriesPerSecond", metrics.queriesPerSecond()); metricsObject.setDouble("writesPerSecond", metrics.writesPerSecond()); metricsObject.setDouble("documentCount", metrics.documentCount()); metricsObject.setDouble("queryLatencyMillis", metrics.queryLatencyMillis()); metricsObject.setDouble("writeLatencyMillis", metrics.writeLatencyMillis()); metrics.instant().ifPresent(instant -> metricsObject.setLong("lastUpdated", instant.toEpochMilli())); } private void toSlime(ApplicationVersion applicationVersion, Cursor object) { if ( ! applicationVersion.isUnknown()) { object.setLong("buildNumber", applicationVersion.buildNumber().getAsLong()); object.setString("hash", applicationVersion.id()); sourceRevisionToSlime(applicationVersion.source(), object.setObject("source")); applicationVersion.sourceUrl().ifPresent(url -> object.setString("sourceUrl", url)); applicationVersion.commit().ifPresent(commit -> object.setString("commit", commit)); } } private void sourceRevisionToSlime(Optional<SourceRevision> revision, Cursor object) { if (revision.isEmpty()) return; object.setString("gitRepository", revision.get().repository()); object.setString("gitBranch", revision.get().branch()); object.setString("gitCommit", revision.get().commit()); } private void toSlime(RotationState state, Cursor object) { Cursor bcpStatus = object.setObject("bcpStatus"); bcpStatus.setString("rotationStatus", rotationStateString(state)); } private void toSlime(List<AssignedRotation> rotations, RotationStatus status, Deployment deployment, Cursor object) { var array = object.setArray("endpointStatus"); for (var rotation : rotations) { var statusObject = array.addObject(); var targets = status.of(rotation.rotationId()); statusObject.setString("endpointId", rotation.endpointId().id()); statusObject.setString("rotationId", rotation.rotationId().asString()); statusObject.setString("clusterId", rotation.clusterId().value()); statusObject.setString("status", rotationStateString(status.of(rotation.rotationId(), deployment))); statusObject.setLong("lastUpdated", targets.lastUpdated().toEpochMilli()); } } private URI monitoringSystemUri(DeploymentId deploymentId) { return controller.zoneRegistry().getMonitoringSystemUri(deploymentId); } /** * Returns a non-broken, released version at least as old as the oldest platform the given application is on. * * If no known version is applicable, the newest version at least as old as the oldest platform is selected, * among all versions released for this system. If no such versions exists, throws an IllegalStateException. */ private Version compileVersion(TenantAndApplicationId id) { Version oldestPlatform = controller.applications().oldestInstalledPlatform(id); VersionStatus versionStatus = controller.readVersionStatus(); return versionStatus.versions().stream() .filter(version -> version.confidence().equalOrHigherThan(VespaVersion.Confidence.low)) .filter(VespaVersion::isReleased) .map(VespaVersion::versionNumber) .filter(version -> ! version.isAfter(oldestPlatform)) .max(Comparator.naturalOrder()) .orElseGet(() -> controller.mavenRepository().metadata().versions().stream() .filter(version -> ! version.isAfter(oldestPlatform)) .filter(version -> ! versionStatus.versions().stream() .map(VespaVersion::versionNumber) .collect(Collectors.toSet()).contains(version)) .max(Comparator.naturalOrder()) .orElseThrow(() -> new IllegalStateException("No available releases of " + controller.mavenRepository().artifactId()))); } private HttpResponse setGlobalRotationOverride(String tenantName, String applicationName, String instanceName, String environment, String region, boolean inService, HttpRequest request) { Instance instance = controller.applications().requireInstance(ApplicationId.from(tenantName, applicationName, instanceName)); ZoneId zone = requireZone(environment, region); Deployment deployment = instance.deployments().get(zone); if (deployment == null) { throw new NotExistsException(instance + " has no deployment in " + zone); } // The order here matters because setGlobalRotationStatus involves an external request that may fail. // TODO(mpolden): Set only one of these when only one kind of global endpoints are supported per zone. var deploymentId = new DeploymentId(instance.id(), zone); setGlobalRotationStatus(deploymentId, inService, request); setGlobalEndpointStatus(deploymentId, inService, request); return new MessageResponse(String.format("Successfully set %s in %s %s service", instance.id().toShortString(), zone, inService ? "in" : "out of")); } /** Set the global endpoint status for given deployment. This only applies to global endpoints backed by a cloud service */ private void setGlobalEndpointStatus(DeploymentId deployment, boolean inService, HttpRequest request) { var agent = isOperator(request) ? GlobalRouting.Agent.operator : GlobalRouting.Agent.tenant; var status = inService ? GlobalRouting.Status.in : GlobalRouting.Status.out; controller.routing().policies().setGlobalRoutingStatus(deployment, status, agent); } /** Set the global rotation status for given deployment. This only applies to global endpoints backed by a rotation */ private void setGlobalRotationStatus(DeploymentId deployment, boolean inService, HttpRequest request) { var requestData = toSlime(request.getData()).get(); var reason = mandatory("reason", requestData).asString(); var agent = isOperator(request) ? GlobalRouting.Agent.operator : GlobalRouting.Agent.tenant; long timestamp = controller.clock().instant().getEpochSecond(); var status = inService ? EndpointStatus.Status.in : EndpointStatus.Status.out; var endpointStatus = new EndpointStatus(status, reason, agent.name(), timestamp); controller.routing().setGlobalRotationStatus(deployment, endpointStatus); } private HttpResponse getGlobalRotationOverride(String tenantName, String applicationName, String instanceName, String environment, String region) { DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName), requireZone(environment, region)); Slime slime = new Slime(); Cursor array = slime.setObject().setArray("globalrotationoverride"); controller.routing().globalRotationStatus(deploymentId) .forEach((endpoint, status) -> { array.addString(endpoint.upstreamIdOf(deploymentId)); Cursor statusObject = array.addObject(); statusObject.setString("status", status.getStatus().name()); statusObject.setString("reason", status.getReason() == null ? "" : status.getReason()); statusObject.setString("agent", status.getAgent() == null ? "" : status.getAgent()); statusObject.setLong("timestamp", status.getEpoch()); }); return new SlimeJsonResponse(slime); } private HttpResponse rotationStatus(String tenantName, String applicationName, String instanceName, String environment, String region, Optional<String> endpointId) { ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName); Instance instance = controller.applications().requireInstance(applicationId); ZoneId zone = requireZone(environment, region); RotationId rotation = findRotationId(instance, endpointId); Deployment deployment = instance.deployments().get(zone); if (deployment == null) { throw new NotExistsException(instance + " has no deployment in " + zone); } Slime slime = new Slime(); Cursor response = slime.setObject(); toSlime(instance.rotationStatus().of(rotation, deployment), response); return new SlimeJsonResponse(slime); } private HttpResponse metering(String tenant, String application, HttpRequest request) { Slime slime = new Slime(); Cursor root = slime.setObject(); MeteringData meteringData = controller.serviceRegistry() .meteringService() .getMeteringData(TenantName.from(tenant), ApplicationName.from(application)); ResourceAllocation currentSnapshot = meteringData.getCurrentSnapshot(); Cursor currentRate = root.setObject("currentrate"); currentRate.setDouble("cpu", currentSnapshot.getCpuCores()); currentRate.setDouble("mem", currentSnapshot.getMemoryGb()); currentRate.setDouble("disk", currentSnapshot.getDiskGb()); ResourceAllocation thisMonth = meteringData.getThisMonth(); Cursor thismonth = root.setObject("thismonth"); thismonth.setDouble("cpu", thisMonth.getCpuCores()); thismonth.setDouble("mem", thisMonth.getMemoryGb()); thismonth.setDouble("disk", thisMonth.getDiskGb()); ResourceAllocation lastMonth = meteringData.getLastMonth(); Cursor lastmonth = root.setObject("lastmonth"); lastmonth.setDouble("cpu", lastMonth.getCpuCores()); lastmonth.setDouble("mem", lastMonth.getMemoryGb()); lastmonth.setDouble("disk", lastMonth.getDiskGb()); Map<ApplicationId, List<ResourceSnapshot>> history = meteringData.getSnapshotHistory(); Cursor details = root.setObject("details"); Cursor detailsCpu = details.setObject("cpu"); Cursor detailsMem = details.setObject("mem"); Cursor detailsDisk = details.setObject("disk"); history.forEach((applicationId, resources) -> { String instanceName = applicationId.instance().value(); Cursor detailsCpuApp = detailsCpu.setObject(instanceName); Cursor detailsMemApp = detailsMem.setObject(instanceName); Cursor detailsDiskApp = detailsDisk.setObject(instanceName); Cursor detailsCpuData = detailsCpuApp.setArray("data"); Cursor detailsMemData = detailsMemApp.setArray("data"); Cursor detailsDiskData = detailsDiskApp.setArray("data"); resources.forEach(resourceSnapshot -> { Cursor cpu = detailsCpuData.addObject(); cpu.setLong("unixms", resourceSnapshot.getTimestamp().toEpochMilli()); cpu.setDouble("value", resourceSnapshot.getCpuCores()); Cursor mem = detailsMemData.addObject(); mem.setLong("unixms", resourceSnapshot.getTimestamp().toEpochMilli()); mem.setDouble("value", resourceSnapshot.getMemoryGb()); Cursor disk = detailsDiskData.addObject(); disk.setLong("unixms", resourceSnapshot.getTimestamp().toEpochMilli()); disk.setDouble("value", resourceSnapshot.getDiskGb()); }); }); return new SlimeJsonResponse(slime); } private HttpResponse deploying(String tenantName, String applicationName, String instanceName, HttpRequest request) { Instance instance = controller.applications().requireInstance(ApplicationId.from(tenantName, applicationName, instanceName)); Slime slime = new Slime(); Cursor root = slime.setObject(); if ( ! instance.change().isEmpty()) { instance.change().platform().ifPresent(version -> root.setString("platform", version.toString())); instance.change().application().ifPresent(applicationVersion -> root.setString("application", applicationVersion.id())); root.setBool("pinned", instance.change().isPinned()); } return new SlimeJsonResponse(slime); } private HttpResponse suspended(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) { DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName), requireZone(environment, region)); boolean suspended = controller.applications().isSuspended(deploymentId); Slime slime = new Slime(); Cursor response = slime.setObject(); response.setBool("suspended", suspended); return new SlimeJsonResponse(slime); } private HttpResponse services(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) { ApplicationView applicationView = controller.getApplicationView(tenantName, applicationName, instanceName, environment, region); ZoneId zone = requireZone(environment, region); ServiceApiResponse response = new ServiceApiResponse(zone, new ApplicationId.Builder().tenant(tenantName).applicationName(applicationName).instanceName(instanceName).build(), List.of(controller.zoneRegistry().getConfigServerVipUri(zone)), request.getUri()); response.setResponse(applicationView); return response; } private HttpResponse service(String tenantName, String applicationName, String instanceName, String environment, String region, String serviceName, String restPath, HttpRequest request) { DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName), requireZone(environment, region)); if ("container-clustercontroller".equals((serviceName)) && restPath.contains("/status/")) { String[] parts = restPath.split("/status/"); String result = controller.serviceRegistry().configServer().getClusterControllerStatus(deploymentId, parts[0], parts[1]); return new HtmlResponse(result); } Map<?,?> result = controller.serviceRegistry().configServer().getServiceApiResponse(deploymentId, serviceName, restPath); ServiceApiResponse response = new ServiceApiResponse(deploymentId.zoneId(), deploymentId.applicationId(), List.of(controller.zoneRegistry().getConfigServerVipUri(deploymentId.zoneId())), request.getUri()); response.setResponse(result, serviceName, restPath); return response; } private HttpResponse content(String tenantName, String applicationName, String instanceName, String environment, String region, String restPath, HttpRequest request) { DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName), requireZone(environment, region)); return controller.serviceRegistry().configServer().getApplicationPackageContent(deploymentId, "/" + restPath, request.getUri()); } private HttpResponse updateTenant(String tenantName, HttpRequest request) { getTenantOrThrow(tenantName); TenantName tenant = TenantName.from(tenantName); Inspector requestObject = toSlime(request.getData()).get(); controller.tenants().update(accessControlRequests.specification(tenant, requestObject), accessControlRequests.credentials(tenant, requestObject, request.getJDiscRequest())); return tenant(controller.tenants().require(TenantName.from(tenantName)), request); } private HttpResponse createTenant(String tenantName, HttpRequest request) { TenantName tenant = TenantName.from(tenantName); Inspector requestObject = toSlime(request.getData()).get(); controller.tenants().create(accessControlRequests.specification(tenant, requestObject), accessControlRequests.credentials(tenant, requestObject, request.getJDiscRequest())); return tenant(controller.tenants().require(TenantName.from(tenantName)), request); } private HttpResponse createApplication(String tenantName, String applicationName, HttpRequest request) { Inspector requestObject = toSlime(request.getData()).get(); TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName); Credentials credentials = accessControlRequests.credentials(id.tenant(), requestObject, request.getJDiscRequest()); Application application = controller.applications().createApplication(id, credentials); Slime slime = new Slime(); toSlime(id, slime.setObject(), request); return new SlimeJsonResponse(slime); } // TODO jonmv: Remove when clients are updated. private HttpResponse createInstance(String tenantName, String applicationName, String instanceName, HttpRequest request) { TenantAndApplicationId applicationId = TenantAndApplicationId.from(tenantName, applicationName); if (controller.applications().getApplication(applicationId).isEmpty()) createApplication(tenantName, applicationName, request); controller.applications().createInstance(applicationId.instance(instanceName)); Slime slime = new Slime(); toSlime(applicationId.instance(instanceName), slime.setObject(), request); return new SlimeJsonResponse(slime); } /** Trigger deployment of the given Vespa version if a valid one is given, e.g., "7.8.9". */ private HttpResponse deployPlatform(String tenantName, String applicationName, String instanceName, boolean pin, HttpRequest request) { String versionString = readToString(request.getData()); ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName); StringBuilder response = new StringBuilder(); controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application -> { Version version = Version.fromString(versionString); VersionStatus versionStatus = controller.readVersionStatus(); if (version.equals(Version.emptyVersion)) version = controller.systemVersion(versionStatus); if (!versionStatus.isActive(version)) throw new IllegalArgumentException("Cannot trigger deployment of version '" + version + "': " + "Version is not active in this system. " + "Active versions: " + versionStatus.versions() .stream() .map(VespaVersion::versionNumber) .map(Version::toString) .collect(joining(", "))); Change change = Change.of(version); if (pin) change = change.withPin(); controller.applications().deploymentTrigger().forceChange(id, change); response.append("Triggered ").append(change).append(" for ").append(id); }); return new MessageResponse(response.toString()); } /** Trigger deployment to the last known application package for the given application. */ private HttpResponse deployApplication(String tenantName, String applicationName, String instanceName, HttpRequest request) { ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName); StringBuilder response = new StringBuilder(); controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application -> { Change change = Change.of(application.get().latestVersion().get()); controller.applications().deploymentTrigger().forceChange(id, change); response.append("Triggered ").append(change).append(" for ").append(id); }); return new MessageResponse(response.toString()); } /** Cancel ongoing change for given application, e.g., everything with {"cancel":"all"} */ private HttpResponse cancelDeploy(String tenantName, String applicationName, String instanceName, String choice) { ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName); StringBuilder response = new StringBuilder(); controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application -> { Change change = application.get().require(id.instance()).change(); if (change.isEmpty()) { response.append("No deployment in progress for ").append(id).append(" at this time"); return; } ChangesToCancel cancel = ChangesToCancel.valueOf(choice.toUpperCase()); controller.applications().deploymentTrigger().cancelChange(id, cancel); response.append("Changed deployment from '").append(change).append("' to '").append(controller.applications().requireInstance(id).change()).append("' for ").append(id); }); return new MessageResponse(response.toString()); } /** Schedule reindexing of an application, or a subset of clusters, possibly on a subset of documents. */ private HttpResponse reindex(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) { ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName); ZoneId zone = requireZone(environment, region); List<String> clusterNames = Optional.ofNullable(request.getProperty("clusterId")).stream() .flatMap(clusters -> Stream.of(clusters.split(","))) .filter(cluster -> ! cluster.isBlank()) .collect(toUnmodifiableList()); List<String> documentTypes = Optional.ofNullable(request.getProperty("documentType")).stream() .flatMap(types -> Stream.of(types.split(","))) .filter(type -> ! type.isBlank()) .collect(toUnmodifiableList()); controller.applications().reindex(id, zone, clusterNames, documentTypes, request.getBooleanProperty("indexedOnly")); return new MessageResponse("Requested reindexing of " + id + " in " + zone + (clusterNames.isEmpty() ? "" : ", on clusters " + String.join(", ", clusterNames) + (documentTypes.isEmpty() ? "" : ", for types " + String.join(", ", documentTypes)))); } /** Gets reindexing status of an application in a zone. */ private HttpResponse getReindexing(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) { ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName); ZoneId zone = requireZone(environment, region); ApplicationReindexing reindexing = controller.applications().applicationReindexing(id, zone); Slime slime = new Slime(); Cursor root = slime.setObject(); root.setBool("enabled", reindexing.enabled()); Cursor clustersArray = root.setArray("clusters"); reindexing.clusters().entrySet().stream().sorted(comparingByKey()) .forEach(cluster -> { Cursor clusterObject = clustersArray.addObject(); clusterObject.setString("name", cluster.getKey()); Cursor pendingArray = clusterObject.setArray("pending"); cluster.getValue().pending().entrySet().stream().sorted(comparingByKey()) .forEach(pending -> { Cursor pendingObject = pendingArray.addObject(); pendingObject.setString("type", pending.getKey()); pendingObject.setLong("requiredGeneration", pending.getValue()); }); Cursor readyArray = clusterObject.setArray("ready"); cluster.getValue().ready().entrySet().stream().sorted(comparingByKey()) .forEach(ready -> { Cursor readyObject = readyArray.addObject(); readyObject.setString("type", ready.getKey()); setStatus(readyObject, ready.getValue()); }); }); return new SlimeJsonResponse(slime); } void setStatus(Cursor statusObject, ApplicationReindexing.Status status) { status.readyAt().ifPresent(readyAt -> statusObject.setLong("readyAtMillis", readyAt.toEpochMilli())); status.startedAt().ifPresent(startedAt -> statusObject.setLong("startedAtMillis", startedAt.toEpochMilli())); status.endedAt().ifPresent(endedAt -> statusObject.setLong("endedAtMillis", endedAt.toEpochMilli())); status.state().map(ApplicationApiHandler::toString).ifPresent(state -> statusObject.setString("state", state)); status.message().ifPresent(message -> statusObject.setString("message", message)); status.progress().ifPresent(progress -> statusObject.setDouble("progress", progress)); } private static String toString(ApplicationReindexing.State state) { switch (state) { case PENDING: return "pending"; case RUNNING: return "running"; case FAILED: return "failed"; case SUCCESSFUL: return "successful"; default: return null; } } /** Enables reindexing of an application in a zone. */ private HttpResponse enableReindexing(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) { ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName); ZoneId zone = requireZone(environment, region); controller.applications().enableReindexing(id, zone); return new MessageResponse("Enabled reindexing of " + id + " in " + zone); } /** Disables reindexing of an application in a zone. */ private HttpResponse disableReindexing(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) { ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName); ZoneId zone = requireZone(environment, region); controller.applications().disableReindexing(id, zone); return new MessageResponse("Disabled reindexing of " + id + " in " + zone); } /** Schedule restart of deployment, or specific host in a deployment */ private HttpResponse restart(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) { DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName), requireZone(environment, region)); RestartFilter restartFilter = new RestartFilter() .withHostName(Optional.ofNullable(request.getProperty("hostname")).map(HostName::from)) .withClusterType(Optional.ofNullable(request.getProperty("clusterType")).map(ClusterSpec.Type::from)) .withClusterId(Optional.ofNullable(request.getProperty("clusterId")).map(ClusterSpec.Id::from)); controller.applications().restart(deploymentId, restartFilter); return new MessageResponse("Requested restart of " + deploymentId); } /** Set suspension status of the given deployment. */ private HttpResponse suspend(String tenantName, String applicationName, String instanceName, String environment, String region, boolean suspend) { DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName), requireZone(environment, region)); controller.applications().setSuspension(deploymentId, suspend); return new MessageResponse((suspend ? "Suspended" : "Resumed") + " orchestration of " + deploymentId); } private HttpResponse jobDeploy(ApplicationId id, JobType type, HttpRequest request) { if ( ! type.environment().isManuallyDeployed() && ! isOperator(request)) throw new IllegalArgumentException("Direct deployments are only allowed to manually deployed environments."); Map<String, byte[]> dataParts = parseDataParts(request); if ( ! dataParts.containsKey("applicationZip")) throw new IllegalArgumentException("Missing required form part 'applicationZip'"); ApplicationPackage applicationPackage = new ApplicationPackage(dataParts.get(EnvironmentResource.APPLICATION_ZIP)); controller.applications().verifyApplicationIdentityConfiguration(id.tenant(), Optional.of(id.instance()), Optional.of(type.zone(controller.system())), applicationPackage, Optional.of(requireUserPrincipal(request))); Optional<Version> version = Optional.ofNullable(dataParts.get("deployOptions")) .map(json -> SlimeUtils.jsonToSlime(json).get()) .flatMap(options -> optional("vespaVersion", options)) .map(Version::fromString); controller.jobController().deploy(id, type, version, applicationPackage); RunId runId = controller.jobController().last(id, type).get().id(); Slime slime = new Slime(); Cursor rootObject = slime.setObject(); rootObject.setString("message", "Deployment started in " + runId + ". This may take about 15 minutes the first time."); rootObject.setLong("run", runId.number()); return new SlimeJsonResponse(slime); } private HttpResponse deploy(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) { ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName); ZoneId zone = requireZone(environment, region); // Get deployOptions Map<String, byte[]> dataParts = parseDataParts(request); if ( ! dataParts.containsKey("deployOptions")) return ErrorResponse.badRequest("Missing required form part 'deployOptions'"); Inspector deployOptions = SlimeUtils.jsonToSlime(dataParts.get("deployOptions")).get(); // Resolve system application Optional<SystemApplication> systemApplication = SystemApplication.matching(applicationId); if (systemApplication.isEmpty() || !systemApplication.get().hasApplicationPackage()) { return ErrorResponse.badRequest("Deployment of " + applicationId + " is not supported through this API"); } // Make it explicit that version is not yet supported here String vespaVersion = deployOptions.field("vespaVersion").asString(); if (!vespaVersion.isEmpty() && !vespaVersion.equals("null")) { return ErrorResponse.badRequest("Specifying version for " + applicationId + " is not permitted"); } // To avoid second guessing the orchestrated upgrades of system applications // we don't allow to deploy these during an system upgrade (i.e when new vespa is being rolled out) VersionStatus versionStatus = controller.readVersionStatus(); if (versionStatus.isUpgrading()) { throw new IllegalArgumentException("Deployment of system applications during a system upgrade is not allowed"); } Optional<VespaVersion> systemVersion = versionStatus.systemVersion(); if (systemVersion.isEmpty()) { throw new IllegalArgumentException("Deployment of system applications is not permitted until system version is determined"); } ActivateResult result = controller.applications() .deploySystemApplicationPackage(systemApplication.get(), zone, systemVersion.get().versionNumber()); return new SlimeJsonResponse(toSlime(result)); } private HttpResponse deleteTenant(String tenantName, HttpRequest request) { Optional<Tenant> tenant = controller.tenants().get(tenantName); if (tenant.isEmpty()) return ErrorResponse.notFoundError("Could not delete tenant '" + tenantName + "': Tenant not found"); controller.tenants().delete(tenant.get().name(), accessControlRequests.credentials(tenant.get().name(), toSlime(request.getData()).get(), request.getJDiscRequest())); // TODO: Change to a message response saying the tenant was deleted return tenant(tenant.get(), request); } private HttpResponse deleteApplication(String tenantName, String applicationName, HttpRequest request) { TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName); Credentials credentials = accessControlRequests.credentials(id.tenant(), toSlime(request.getData()).get(), request.getJDiscRequest()); controller.applications().deleteApplication(id, credentials); return new MessageResponse("Deleted application " + id); } private HttpResponse deleteInstance(String tenantName, String applicationName, String instanceName, HttpRequest request) { TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName); controller.applications().deleteInstance(id.instance(instanceName)); if (controller.applications().requireApplication(id).instances().isEmpty()) { Credentials credentials = accessControlRequests.credentials(id.tenant(), toSlime(request.getData()).get(), request.getJDiscRequest()); controller.applications().deleteApplication(id, credentials); } return new MessageResponse("Deleted instance " + id.instance(instanceName).toFullString()); } private HttpResponse deactivate(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) { DeploymentId id = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName), requireZone(environment, region)); // Attempt to deactivate application even if the deployment is not known by the controller controller.applications().deactivate(id.applicationId(), id.zoneId()); return new MessageResponse("Deactivated " + id); } /** Returns test config for indicated job, with production deployments of the default instance. */ private HttpResponse testConfig(ApplicationId id, JobType type) { // TODO jonmv: Support non-default instances as well; requires API change in clients. ApplicationId defaultInstanceId = TenantAndApplicationId.from(id).defaultInstance(); HashSet<DeploymentId> deployments = controller.applications() .getInstance(defaultInstanceId).stream() .flatMap(instance -> instance.productionDeployments().keySet().stream()) .map(zone -> new DeploymentId(defaultInstanceId, zone)) .collect(Collectors.toCollection(HashSet::new)); var testedZone = type.zone(controller.system()); // If a production job is specified, the production deployment of the _default instance_ is the relevant one, // as user instances should not exist in prod. TODO jonmv: Remove this when multiple instances are supported (above). if ( ! type.isProduction()) deployments.add(new DeploymentId(id, testedZone)); return new SlimeJsonResponse(testConfigSerializer.configSlime(id, type, false, controller.routing().zoneEndpointsOf(deployments), controller.applications().reachableContentClustersByZone(deployments))); } private static SourceRevision toSourceRevision(Inspector object) { if (!object.field("repository").valid() || !object.field("branch").valid() || !object.field("commit").valid()) { throw new IllegalArgumentException("Must specify \"repository\", \"branch\", and \"commit\"."); } return new SourceRevision(object.field("repository").asString(), object.field("branch").asString(), object.field("commit").asString()); } private Tenant getTenantOrThrow(String tenantName) { return controller.tenants().get(tenantName) .orElseThrow(() -> new NotExistsException(new TenantId(tenantName))); } private void toSlime(Cursor object, Tenant tenant, List<Application> applications, HttpRequest request) { object.setString("tenant", tenant.name().value()); object.setString("type", tenantType(tenant)); switch (tenant.type()) { case athenz: AthenzTenant athenzTenant = (AthenzTenant) tenant; object.setString("athensDomain", athenzTenant.domain().getName()); object.setString("property", athenzTenant.property().id()); athenzTenant.propertyId().ifPresent(id -> object.setString("propertyId", id.toString())); athenzTenant.contact().ifPresent(c -> { object.setString("propertyUrl", c.propertyUrl().toString()); object.setString("contactsUrl", c.url().toString()); object.setString("issueCreationUrl", c.issueTrackerUrl().toString()); Cursor contactsArray = object.setArray("contacts"); c.persons().forEach(persons -> { Cursor personArray = contactsArray.addArray(); persons.forEach(personArray::addString); }); }); break; case cloud: { CloudTenant cloudTenant = (CloudTenant) tenant; cloudTenant.creator().ifPresent(creator -> object.setString("creator", creator.getName())); Cursor pemDeveloperKeysArray = object.setArray("pemDeveloperKeys"); cloudTenant.developerKeys().forEach((key, user) -> { Cursor keyObject = pemDeveloperKeysArray.addObject(); keyObject.setString("key", KeyUtils.toPem(key)); keyObject.setString("user", user.getName()); }); // TODO: remove this once console is updated toSlime(object, cloudTenant.tenantSecretStores()); toSlime(object.setObject("integrations").setObject("aws"), controller.serviceRegistry().roleService().getTenantRole(tenant.name()), cloudTenant.tenantSecretStores()); var tenantQuota = controller.serviceRegistry().billingController().getQuota(tenant.name()); var usedQuota = applications.stream() .map(Application::quotaUsage) .reduce(QuotaUsage.none, QuotaUsage::add); toSlime(tenantQuota, usedQuota, object.setObject("quota")); cloudTenant.archiveAccessRole().ifPresent(role -> object.setString("archiveAccessRole", role)); break; } default: throw new IllegalArgumentException("Unexpected tenant type '" + tenant.type() + "'."); } // TODO jonmv: This should list applications, not instances. Cursor applicationArray = object.setArray("applications"); for (Application application : applications) { DeploymentStatus status = null; for (Instance instance : showOnlyProductionInstances(request) ? application.productionInstances().values() : application.instances().values()) if (recurseOverApplications(request)) { if (status == null) status = controller.jobController().deploymentStatus(application); toSlime(applicationArray.addObject(), instance, status, request); } else { toSlime(instance.id(), applicationArray.addObject(), request); } } tenantMetaDataToSlime(tenant, applications, object.setObject("metaData")); } private void toSlime(Quota quota, QuotaUsage usage, Cursor object) { quota.budget().ifPresentOrElse( budget -> object.setDouble("budget", budget.doubleValue()), () -> object.setNix("budget") ); object.setDouble("budgetUsed", usage.rate()); // TODO: Retire when we no longer use maxClusterSize as a meaningful limit quota.maxClusterSize().ifPresent(maxClusterSize -> object.setLong("clusterSize", maxClusterSize)); } private void toSlime(ClusterResources resources, Cursor object) { object.setLong("nodes", resources.nodes()); object.setLong("groups", resources.groups()); toSlime(resources.nodeResources(), object.setObject("nodeResources")); // Divide cost by 3 in non-public zones to show approx. AWS equivalent cost double costDivisor = controller.zoneRegistry().system().isPublic() ? 1.0 : 3.0; object.setDouble("cost", Math.round(resources.nodes() * resources.nodeResources().cost() * 100.0 / costDivisor) / 100.0); } private void utilizationToSlime(Cluster.Utilization utilization, Cursor utilizationObject) { utilizationObject.setDouble("cpu", utilization.cpu()); utilizationObject.setDouble("idealCpu", utilization.idealCpu()); utilizationObject.setDouble("currentCpu", utilization.currentCpu()); utilizationObject.setDouble("memory", utilization.memory()); utilizationObject.setDouble("idealMemory", utilization.idealMemory()); utilizationObject.setDouble("currentMemory", utilization.currentMemory()); utilizationObject.setDouble("disk", utilization.disk()); utilizationObject.setDouble("idealDisk", utilization.idealDisk()); utilizationObject.setDouble("currentDisk", utilization.currentDisk()); } private void scalingEventsToSlime(List<Cluster.ScalingEvent> scalingEvents, Cursor scalingEventsArray) { for (Cluster.ScalingEvent scalingEvent : scalingEvents) { Cursor scalingEventObject = scalingEventsArray.addObject(); toSlime(scalingEvent.from(), scalingEventObject.setObject("from")); toSlime(scalingEvent.to(), scalingEventObject.setObject("to")); scalingEventObject.setLong("at", scalingEvent.at().toEpochMilli()); scalingEvent.completion().ifPresent(completion -> scalingEventObject.setLong("completion", completion.toEpochMilli())); } } private void toSlime(NodeResources resources, Cursor object) { object.setDouble("vcpu", resources.vcpu()); object.setDouble("memoryGb", resources.memoryGb()); object.setDouble("diskGb", resources.diskGb()); object.setDouble("bandwidthGbps", resources.bandwidthGbps()); object.setString("diskSpeed", valueOf(resources.diskSpeed())); object.setString("storageType", valueOf(resources.storageType())); } // A tenant has different content when in a list ... antipattern, but not solvable before application/v5 private void tenantInTenantsListToSlime(Tenant tenant, URI requestURI, Cursor object) { object.setString("tenant", tenant.name().value()); Cursor metaData = object.setObject("metaData"); metaData.setString("type", tenantType(tenant)); switch (tenant.type()) { case athenz: AthenzTenant athenzTenant = (AthenzTenant) tenant; metaData.setString("athensDomain", athenzTenant.domain().getName()); metaData.setString("property", athenzTenant.property().id()); break; case cloud: break; default: throw new IllegalArgumentException("Unexpected tenant type '" + tenant.type() + "'."); } object.setString("url", withPath("/application/v4/tenant/" + tenant.name().value(), requestURI).toString()); } private void tenantMetaDataToSlime(Tenant tenant, List<Application> applications, Cursor object) { Optional<Instant> lastDev = applications.stream() .flatMap(application -> application.instances().values().stream()) .flatMap(instance -> instance.deployments().values().stream()) .filter(deployment -> deployment.zone().environment() == Environment.dev) .map(Deployment::at) .max(Comparator.naturalOrder()) .or(() -> applications.stream() .flatMap(application -> application.instances().values().stream()) .flatMap(instance -> JobType.allIn(controller.system()).stream() .filter(job -> job.environment() == Environment.dev) .flatMap(jobType -> controller.jobController().last(instance.id(), jobType).stream())) .map(Run::start) .max(Comparator.naturalOrder())); Optional<Instant> lastSubmission = applications.stream() .flatMap(app -> app.latestVersion().flatMap(ApplicationVersion::buildTime).stream()) .max(Comparator.naturalOrder()); object.setLong("createdAtMillis", tenant.createdAt().toEpochMilli()); lastDev.ifPresent(instant -> object.setLong("lastDeploymentToDevMillis", instant.toEpochMilli())); lastSubmission.ifPresent(instant -> object.setLong("lastSubmissionToProdMillis", instant.toEpochMilli())); tenant.lastLoginInfo().get(LastLoginInfo.UserLevel.user) .ifPresent(instant -> object.setLong("lastLoginByUserMillis", instant.toEpochMilli())); tenant.lastLoginInfo().get(LastLoginInfo.UserLevel.developer) .ifPresent(instant -> object.setLong("lastLoginByDeveloperMillis", instant.toEpochMilli())); tenant.lastLoginInfo().get(LastLoginInfo.UserLevel.administrator) .ifPresent(instant -> object.setLong("lastLoginByAdministratorMillis", instant.toEpochMilli())); } /** Returns a copy of the given URI with the host and port from the given URI, the path set to the given path and the query set to given query*/ private URI withPathAndQuery(String newPath, String newQuery, URI uri) { try { return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), newPath, newQuery, null); } catch (URISyntaxException e) { throw new RuntimeException("Will not happen", e); } } /** Returns a copy of the given URI with the host and port from the given URI and the path set to the given path */ private URI withPath(String newPath, URI uri) { return withPathAndQuery(newPath, null, uri); } private String toPath(DeploymentId id) { return path("/application", "v4", "tenant", id.applicationId().tenant(), "application", id.applicationId().application(), "instance", id.applicationId().instance(), "environment", id.zoneId().environment(), "region", id.zoneId().region()); } private long asLong(String valueOrNull, long defaultWhenNull) { if (valueOrNull == null) return defaultWhenNull; try { return Long.parseLong(valueOrNull); } catch (NumberFormatException e) { throw new IllegalArgumentException("Expected an integer but got '" + valueOrNull + "'"); } } private void toSlime(Run run, Cursor object) { object.setLong("id", run.id().number()); object.setString("version", run.versions().targetPlatform().toFullString()); if ( ! run.versions().targetApplication().isUnknown()) toSlime(run.versions().targetApplication(), object.setObject("revision")); object.setString("reason", "unknown reason"); object.setLong("at", run.end().orElse(run.start()).toEpochMilli()); } private Slime toSlime(InputStream jsonStream) { try { byte[] jsonBytes = IOUtils.readBytes(jsonStream, 1000 * 1000); return SlimeUtils.jsonToSlime(jsonBytes); } catch (IOException e) { throw new RuntimeException(); } } private static Principal requireUserPrincipal(HttpRequest request) { Principal principal = request.getJDiscRequest().getUserPrincipal(); if (principal == null) throw new InternalServerErrorException("Expected a user principal"); return principal; } private Inspector mandatory(String key, Inspector object) { if ( ! object.field(key).valid()) throw new IllegalArgumentException("'" + key + "' is missing"); return object.field(key); } private Optional<String> optional(String key, Inspector object) { return SlimeUtils.optionalString(object.field(key)); } private static String path(Object... elements) { return Joiner.on("/").join(elements); } private void toSlime(TenantAndApplicationId id, Cursor object, HttpRequest request) { object.setString("tenant", id.tenant().value()); object.setString("application", id.application().value()); object.setString("url", withPath("/application/v4" + "/tenant/" + id.tenant().value() + "/application/" + id.application().value(), request.getUri()).toString()); } private void toSlime(ApplicationId id, Cursor object, HttpRequest request) { object.setString("tenant", id.tenant().value()); object.setString("application", id.application().value()); object.setString("instance", id.instance().value()); object.setString("url", withPath("/application/v4" + "/tenant/" + id.tenant().value() + "/application/" + id.application().value() + "/instance/" + id.instance().value(), request.getUri()).toString()); } private Slime toSlime(ActivateResult result) { Slime slime = new Slime(); Cursor object = slime.setObject(); object.setString("revisionId", result.revisionId().id()); object.setLong("applicationZipSize", result.applicationZipSizeBytes()); Cursor logArray = object.setArray("prepareMessages"); if (result.prepareResponse().log != null) { for (Log logMessage : result.prepareResponse().log) { Cursor logObject = logArray.addObject(); logObject.setLong("time", logMessage.time); logObject.setString("level", logMessage.level); logObject.setString("message", logMessage.message); } } Cursor changeObject = object.setObject("configChangeActions"); Cursor restartActionsArray = changeObject.setArray("restart"); for (RestartAction restartAction : result.prepareResponse().configChangeActions.restartActions) { Cursor restartActionObject = restartActionsArray.addObject(); restartActionObject.setString("clusterName", restartAction.clusterName); restartActionObject.setString("clusterType", restartAction.clusterType); restartActionObject.setString("serviceType", restartAction.serviceType); serviceInfosToSlime(restartAction.services, restartActionObject.setArray("services")); stringsToSlime(restartAction.messages, restartActionObject.setArray("messages")); } Cursor refeedActionsArray = changeObject.setArray("refeed"); for (RefeedAction refeedAction : result.prepareResponse().configChangeActions.refeedActions) { Cursor refeedActionObject = refeedActionsArray.addObject(); refeedActionObject.setString("name", refeedAction.name); refeedActionObject.setString("documentType", refeedAction.documentType); refeedActionObject.setString("clusterName", refeedAction.clusterName); serviceInfosToSlime(refeedAction.services, refeedActionObject.setArray("services")); stringsToSlime(refeedAction.messages, refeedActionObject.setArray("messages")); } return slime; } private void serviceInfosToSlime(List<ServiceInfo> serviceInfoList, Cursor array) { for (ServiceInfo serviceInfo : serviceInfoList) { Cursor serviceInfoObject = array.addObject(); serviceInfoObject.setString("serviceName", serviceInfo.serviceName); serviceInfoObject.setString("serviceType", serviceInfo.serviceType); serviceInfoObject.setString("configId", serviceInfo.configId); serviceInfoObject.setString("hostName", serviceInfo.hostName); } } private void stringsToSlime(List<String> strings, Cursor array) { for (String string : strings) array.addString(string); } private void toSlime(Cursor object, List<TenantSecretStore> tenantSecretStores) { Cursor secretStore = object.setArray("secretStores"); tenantSecretStores.forEach(store -> { toSlime(secretStore.addObject(), store); }); } private void toSlime(Cursor object, TenantRoles tenantRoles, List<TenantSecretStore> tenantSecretStores) { object.setString("tenantRole", tenantRoles.containerRole()); var stores = object.setArray("accounts"); tenantSecretStores.forEach(secretStore -> { toSlime(stores.addObject(), secretStore); }); } private void toSlime(Cursor object, TenantSecretStore secretStore) { object.setString("name", secretStore.getName()); object.setString("awsId", secretStore.getAwsId()); object.setString("role", secretStore.getRole()); } private String readToString(InputStream stream) { Scanner scanner = new Scanner(stream).useDelimiter("\\A"); if ( ! scanner.hasNext()) return null; return scanner.next(); } private static boolean recurseOverTenants(HttpRequest request) { return recurseOverApplications(request) || "tenant".equals(request.getProperty("recursive")); } private static boolean recurseOverApplications(HttpRequest request) { return recurseOverDeployments(request) || "application".equals(request.getProperty("recursive")); } private static boolean recurseOverDeployments(HttpRequest request) { return ImmutableSet.of("all", "true", "deployment").contains(request.getProperty("recursive")); } private static boolean showOnlyProductionInstances(HttpRequest request) { return "true".equals(request.getProperty("production")); } private static String tenantType(Tenant tenant) { switch (tenant.type()) { case athenz: return "ATHENS"; case cloud: return "CLOUD"; default: throw new IllegalArgumentException("Unknown tenant type: " + tenant.getClass().getSimpleName()); } } private static ApplicationId appIdFromPath(Path path) { return ApplicationId.from(path.get("tenant"), path.get("application"), path.get("instance")); } private static JobType jobTypeFromPath(Path path) { return JobType.fromJobName(path.get("jobtype")); } private static RunId runIdFromPath(Path path) { long number = Long.parseLong(path.get("number")); return new RunId(appIdFromPath(path), jobTypeFromPath(path), number); } private HttpResponse submit(String tenant, String application, HttpRequest request) { Map<String, byte[]> dataParts = parseDataParts(request); Inspector submitOptions = SlimeUtils.jsonToSlime(dataParts.get(EnvironmentResource.SUBMIT_OPTIONS)).get(); long projectId = Math.max(1, submitOptions.field("projectId").asLong()); // Absence of this means it's not a prod app :/ Optional<String> repository = optional("repository", submitOptions); Optional<String> branch = optional("branch", submitOptions); Optional<String> commit = optional("commit", submitOptions); Optional<SourceRevision> sourceRevision = repository.isPresent() && branch.isPresent() && commit.isPresent() ? Optional.of(new SourceRevision(repository.get(), branch.get(), commit.get())) : Optional.empty(); Optional<String> sourceUrl = optional("sourceUrl", submitOptions); Optional<String> authorEmail = optional("authorEmail", submitOptions); sourceUrl.map(URI::create).ifPresent(url -> { if (url.getHost() == null || url.getScheme() == null) throw new IllegalArgumentException("Source URL must include scheme and host"); }); ApplicationPackage applicationPackage = new ApplicationPackage(dataParts.get(EnvironmentResource.APPLICATION_ZIP), true); controller.applications().verifyApplicationIdentityConfiguration(TenantName.from(tenant), Optional.empty(), Optional.empty(), applicationPackage, Optional.of(requireUserPrincipal(request))); return JobControllerApiHandlerHelper.submitResponse(controller.jobController(), tenant, application, sourceRevision, authorEmail, sourceUrl, projectId, applicationPackage, dataParts.get(EnvironmentResource.APPLICATION_TEST_ZIP)); } private HttpResponse removeAllProdDeployments(String tenant, String application) { JobControllerApiHandlerHelper.submitResponse(controller.jobController(), tenant, application, Optional.empty(), Optional.empty(), Optional.empty(), 1, ApplicationPackage.deploymentRemoval(), new byte[0]); return new MessageResponse("All deployments removed"); } private ZoneId requireZone(String environment, String region) { ZoneId zone = ZoneId.from(environment, region); // TODO(mpolden): Find a way to not hardcode this. Some APIs allow this "virtual" zone, e.g. /logs if (zone.environment() == Environment.prod && zone.region().value().equals("controller")) { return zone; } if (!controller.zoneRegistry().hasZone(zone)) { throw new IllegalArgumentException("Zone " + zone + " does not exist in this system"); } return zone; } private static Map<String, byte[]> parseDataParts(HttpRequest request) { String contentHash = request.getHeader("X-Content-Hash"); if (contentHash == null) return new MultipartParser().parse(request); DigestInputStream digester = Signatures.sha256Digester(request.getData()); var dataParts = new MultipartParser().parse(request.getHeader("Content-Type"), digester, request.getUri()); if ( ! Arrays.equals(digester.getMessageDigest().digest(), Base64.getDecoder().decode(contentHash))) throw new IllegalArgumentException("Value of X-Content-Hash header does not match computed content hash"); return dataParts; } private static RotationId findRotationId(Instance instance, Optional<String> endpointId) { if (instance.rotations().isEmpty()) { throw new NotExistsException("global rotation does not exist for " + instance); } if (endpointId.isPresent()) { return instance.rotations().stream() .filter(r -> r.endpointId().id().equals(endpointId.get())) .map(AssignedRotation::rotationId) .findFirst() .orElseThrow(() -> new NotExistsException("endpoint " + endpointId.get() + " does not exist for " + instance)); } else if (instance.rotations().size() > 1) { throw new IllegalArgumentException(instance + " has multiple rotations. Query parameter 'endpointId' must be given"); } return instance.rotations().get(0).rotationId(); } private static String rotationStateString(RotationState state) { switch (state) { case in: return "IN"; case out: return "OUT"; } return "UNKNOWN"; } private static String endpointScopeString(Endpoint.Scope scope) { switch (scope) { case region: return "region"; case global: return "global"; case zone: return "zone"; } throw new IllegalArgumentException("Unknown endpoint scope " + scope); } private static String routingMethodString(RoutingMethod method) { switch (method) { case exclusive: return "exclusive"; case shared: return "shared"; case sharedLayer4: return "sharedLayer4"; } throw new IllegalArgumentException("Unknown routing method " + method); } private static <T> T getAttribute(HttpRequest request, String attributeName, Class<T> cls) { return Optional.ofNullable(request.getJDiscRequest().context().get(attributeName)) .filter(cls::isInstance) .map(cls::cast) .orElseThrow(() -> new IllegalArgumentException("Attribute '" + attributeName + "' was not set on request")); } /** Returns whether given request is by an operator */ private static boolean isOperator(HttpRequest request) { var securityContext = getAttribute(request, SecurityContext.ATTRIBUTE_NAME, SecurityContext.class); return securityContext.roles().stream() .map(Role::definition) .anyMatch(definition -> definition == RoleDefinition.hostedOperator); } }
Close closeable
controller-server/src/main/java/com/yahoo/vespa/hosted/controller/restapi/application/ApplicationApiHandler.java
Close closeable
<ide><path>ontroller-server/src/main/java/com/yahoo/vespa/hosted/controller/restapi/application/ApplicationApiHandler.java <ide> return new HttpResponse(200) { <ide> @Override <ide> public void render(OutputStream outputStream) throws IOException { <del> logStream.transferTo(outputStream); <add> try (logStream) { <add> logStream.transferTo(outputStream); <add> } <ide> } <ide> }; <ide> }
JavaScript
mit
9ac0e3b46fedba6caca07a1743a530d090c25b1a
0
RamiBououni/Portfolio,RamiBououni/Portfolio
//I just kept a copy of this so I can play with it later and practice more, especially after finishing the 301 and later on need a refresher on how to do certain things // 'use strict' // // var portfolioObjets = [ // { // title: 'about me', // image: '<img src="img/website1.jpg">', // link: 'https://github.com/RamiBououni/about_me', // description: '<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>' // }, // { // title: 'cookie stand', // image: '<img src="img/website2.jpg">', // link: 'https://github.com/RamiBououni/cookie-stand', // description: '<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>' // }, // { // title: 'bus mall', // image: '<img src="img/website3.jpg">', // link: 'https://github.com/RamiBououni/bus-mall', // description: '<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>' // } // ];
js/objects.js
// 'use strict' // // var portfolioObjets = [ // { // title: 'about me', // image: '<img src="img/website1.jpg">', // link: 'https://github.com/RamiBououni/about_me', // description: '<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>' // }, // { // title: 'cookie stand', // image: '<img src="img/website2.jpg">', // link: 'https://github.com/RamiBououni/cookie-stand', // description: '<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>' // }, // { // title: 'bus mall', // image: '<img src="img/website3.jpg">', // link: 'https://github.com/RamiBououni/bus-mall', // description: '<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>' // } // ];
added a comment to object.js, code working properly
js/objects.js
added a comment to object.js, code working properly
<ide><path>s/objects.js <del>// 'use strict' <add> <add> <add> <add> <add>//I just kept a copy of this so I can play with it later and practice more, especially after finishing the 301 and later on need a refresher on how to do certain things <add> <add> <add> <add> <add> <add> <add> <add> <add> <add> <add> // 'use strict' <ide> // <ide> // var portfolioObjets = [ <ide> // {
Java
bsd-3-clause
7aaa130a934a023fe4ad04a0726817443b924832
0
NCIP/cadsr-semantic-tools,NCIP/cadsr-semantic-tools
package gov.nih.nci.ncicb.cadsr.loader.ui; import gov.nih.nci.ncicb.cadsr.domain.*; import gov.nih.nci.ncicb.cadsr.loader.event.*; import gov.nih.nci.ncicb.cadsr.loader.ui.event.NavigationEvent; import gov.nih.nci.ncicb.cadsr.loader.ui.event.NavigationListener; import gov.nih.nci.ncicb.cadsr.loader.ui.tree.*; import gov.nih.nci.ncicb.cadsr.loader.util.*; import gov.nih.nci.ncicb.cadsr.loader.*; import gov.nih.nci.ncicb.cadsr.loader.ui.util.UIUtil; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeEvent; import java.awt.event.ItemEvent; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.swing.*; import java.awt.*; import java.awt.event.*; import javax.swing.event.*; public class UMLElementViewPanel extends JPanel implements //ActionListener, KeyListener //, ItemListener, //UserPreferencesListener, NavigationListener { private UMLElementViewPanel _this = this; private List<NavigationListener> navigationListeners = new ArrayList<NavigationListener>(); private ConceptEditorPanel conceptEditorPanel; private ButtonPanel buttonPanel; // initialize once the mode in which we're running public UMLElementViewPanel(UMLNode node) { conceptEditorPanel = new ConceptEditorPanel(node); buttonPanel = new ButtonPanel(conceptEditorPanel); conceptEditorPanel.addPropertyChangeListener(buttonPanel); initUI(); } private void initUI() { conceptEditorPanel.initUI(); setLayout(new BorderLayout()); this.add(conceptEditorPanel, BorderLayout.CENTER); this.add(buttonPanel, BorderLayout.SOUTH); } //new public void updateNode(UMLNode node) { conceptEditorPanel.updateNode(node); } //new public void apply(boolean value) { conceptEditorPanel.apply(value); } public void navigate(NavigationEvent evt) { // for(NavigationListener nl : navigationListeners) // nl.navigate(evt); buttonPanel.navigate(evt); } public void addReviewListener(ReviewListener listener) { buttonPanel.addReviewListener(listener); } public void addNavigationListener(NavigationListener listener) { // navigationListeners.add(listener); buttonPanel.addNavigationListener(listener); } public void addElementChangeListener(ElementChangeListener listener) { conceptEditorPanel.addElementChangeListener(listener); } public void addPropertyChangeListener(PropertyChangeListener l) { conceptEditorPanel.addPropertyChangeListener(l); buttonPanel.addPropertyChangeListener(l); } }
src/gov/nih/nci/ncicb/cadsr/loader/ui/UMLElementViewPanel.java
package gov.nih.nci.ncicb.cadsr.loader.ui; import gov.nih.nci.ncicb.cadsr.domain.*; import gov.nih.nci.ncicb.cadsr.loader.event.*; import gov.nih.nci.ncicb.cadsr.loader.ui.event.NavigationEvent; import gov.nih.nci.ncicb.cadsr.loader.ui.event.NavigationListener; import gov.nih.nci.ncicb.cadsr.loader.ui.tree.*; import gov.nih.nci.ncicb.cadsr.loader.util.*; import gov.nih.nci.ncicb.cadsr.loader.*; import gov.nih.nci.ncicb.cadsr.loader.ui.util.UIUtil; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeEvent; import java.awt.event.ItemEvent; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.swing.*; import java.awt.*; import java.awt.event.*; import javax.swing.event.*; public class UMLElementViewPanel extends JPanel implements ActionListener, KeyListener , ItemListener, UserPreferencesListener, NavigationListener { private Concept[] concepts; private ConceptUI[] conceptUIs; private UMLElementViewPanel _this = this; private UMLNode node; private boolean remove = false, orderChanged = false; private static final String ADD = "ADD", DELETE = "DELETE", SAVE = "APPLY", PREVIOUS = "PREVIOUS", NEXT = "NEXT"; private JButton addButton, deleteButton, saveButton; private JButton previousButton, nextButton; private JCheckBox reviewButton; private JLabel conceptLabel = new JLabel(); private JLabel nameLabel = new JLabel(); private List<ReviewListener> reviewListeners = new ArrayList<ReviewListener>(); private List<ElementChangeListener> changeListeners = new ArrayList<ElementChangeListener>(); private List<NavigationListener> navigationListeners = new ArrayList<NavigationListener>(); private List<PropertyChangeListener> propChangeListeners = new ArrayList<PropertyChangeListener>(); private JPanel gridPanel; private JScrollPane scrollPane; // initialize once the mode in which we're running private static boolean editable = false; static { UserSelections selections = UserSelections.getInstance(); editable = selections.getProperty("MODE").equals(RunMode.Curator); } private UserPreferences prefs = UserPreferences.getInstance(); private static EvsDialog evsDialog; public UMLElementViewPanel(UMLNode node) { this.node = node; initConcepts(); initUI(); } public void navigate(NavigationEvent evt) { if(saveButton.isEnabled()) { if(JOptionPane.showConfirmDialog(_this, "There are unsaved changes in this concept, would you like to apply the changes now?", "Unsaved Changes", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) apply(false); } } public void addReviewListener(ReviewListener listener) { reviewListeners.add(listener); } public void addElementChangeListener(ElementChangeListener listener) { changeListeners.add(listener); } public void addNavigationListener(NavigationListener listener) { navigationListeners.add(listener); } public void addPropertyChangeListener(PropertyChangeListener l) { propChangeListeners.add(l); } public void updateNode(UMLNode node) { this.node = node; initConcepts(); updateConcepts(concepts); } public void apply(boolean toAll) { boolean update = remove; remove = false; Concept[] newConcepts = new Concept[concepts.length]; for(int i = 0; i<concepts.length; i++) { newConcepts[i] = concepts[i]; // concept code has not changed if(conceptUIs[i].code.getText().equals(concepts[i].getPreferredName())) { concepts[i].setLongName(conceptUIs[i].name.getText()); concepts[i].setPreferredDefinition(conceptUIs[i].def.getText()); concepts[i].setDefinitionSource(conceptUIs[i].defSource.getText()); } else { // concept code has changed Concept concept = DomainObjectFactory.newConcept(); concept.setPreferredName(conceptUIs[i].code.getText()); concept.setLongName(conceptUIs[i].name.getText()); concept.setPreferredDefinition(conceptUIs[i].def.getText()); concept.setDefinitionSource(conceptUIs[i].defSource.getText()); newConcepts[i] = concept; update = true; } } update = orderChanged | update; if(update) { if(toAll) { Object o = node.getUserObject(); if(o instanceof DataElement) { DataElement de = (DataElement)o; ObjectUpdater.updateByAltName(de.getDataElementConcept().getProperty().getLongName(), concepts, newConcepts); } } else ObjectUpdater.update((AdminComponent)node.getUserObject(), concepts, newConcepts); concepts = newConcepts; } orderChanged = false; setSaveButtonState(false); addButton.setEnabled(true); reviewButton.setEnabled(true); fireElementChangeEvent(new ElementChangeEvent(node)); } private void initConcepts() { concepts = NodeUtil.getConceptsFromNode(node); } private void updateConcepts(Concept[] concepts) { this.concepts = concepts; this.removeAll(); initUI(); this.updateUI(); } private void initUI() { prefs.addUserPreferencesListener(this); this.setLayout(new BorderLayout()); JPanel summaryPanel = new JPanel(new GridBagLayout()); JLabel summaryTitle = new JLabel("UML Concept Code Summary: "); JLabel summaryNameTitle = new JLabel("UML Concept Name Summary: "); insertInBag(summaryPanel, summaryTitle, 0, 0); insertInBag(summaryPanel, conceptLabel, 1, 0); insertInBag(summaryPanel, summaryNameTitle, 0, 1); insertInBag(summaryPanel, nameLabel, 1, 1); this.add(summaryPanel,BorderLayout.NORTH); initViewPanel(); initButtonPanel(); } private void initViewPanel() { gridPanel = new JPanel(new GridBagLayout()); scrollPane = new JScrollPane(gridPanel); conceptUIs = new ConceptUI[concepts.length]; JPanel[] conceptPanels = new JPanel[concepts.length]; if(prefs.getUmlDescriptionOrder().equals("first")) insertInBag(gridPanel, createDescriptionPanel(), 0, 0); for(int i = 0; i<concepts.length; i++) { conceptUIs[i] = new ConceptUI(concepts[i]); String title = i == 0?"Primary Concept":"Qualifier Concept" +" #" + (i); conceptPanels[i] = new JPanel(); conceptPanels[i].setBorder (BorderFactory.createTitledBorder(title)); conceptPanels[i].setLayout(new BorderLayout()); JPanel mainPanel = new JPanel(new GridBagLayout()); insertInBag(mainPanel, conceptUIs[i].labels[0], 0, 0); insertInBag(mainPanel, conceptUIs[i].labels[1], 0, 1); insertInBag(mainPanel, conceptUIs[i].labels[2], 0, 2); insertInBag(mainPanel, conceptUIs[i].labels[3], 0, 3); insertInBag(mainPanel, conceptUIs[i].code, 1, 0, 2, 1); insertInBag(mainPanel, conceptUIs[i].name, 1, 1, 2, 1); insertInBag(mainPanel, conceptUIs[i].defScrollPane, 1, 2, 2, 1); insertInBag(mainPanel, conceptUIs[i].defSource, 1, 3,1, 1); JButton evsButton = new JButton("Evs Link"); insertInBag(mainPanel, evsButton, 2, 3); JButton upButton = new JButton(new ImageIcon(Thread.currentThread().getContextClassLoader().getResource("up-arrow.gif"))); JButton downButton = new JButton(new ImageIcon(Thread.currentThread().getContextClassLoader().getResource("down-arrow.gif"))); upButton.setPreferredSize(new Dimension(28, 35)); downButton.setPreferredSize(new Dimension(28, 35)); JPanel arrowPanel = new JPanel(new GridBagLayout()); insertInBag(arrowPanel, upButton, 0, 0); insertInBag(arrowPanel, downButton, 0, 6); conceptPanels[i].add(mainPanel, BorderLayout.CENTER); conceptPanels[i].add(arrowPanel, BorderLayout.EAST); insertInBag(gridPanel, conceptPanels[i], 0, conceptPanels.length - i); conceptUIs[i].code.addKeyListener(this); conceptUIs[i].name.addKeyListener(this); conceptUIs[i].def.addKeyListener(this); conceptUIs[i].defSource.addKeyListener(this); final int index = i; if(index == 0) downButton.setVisible(false); if(index == concepts.length-1) upButton.setVisible(false); downButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { Concept temp = concepts[index-1]; concepts[index-1] = concepts[index]; concepts[index] = temp; updateConcepts(concepts); orderChanged = true; setSaveButtonState(areAllFieldEntered()); reviewButton.setEnabled(false); addButton.setEnabled(false); } }); upButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { Concept temp = concepts[index]; concepts[index] = concepts[index+1]; concepts[index+1] = temp; updateConcepts(concepts); orderChanged = true; setSaveButtonState(areAllFieldEntered()); reviewButton.setEnabled(false); addButton.setEnabled(false); } }); evsButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { if (evsDialog == null) evsDialog = new EvsDialog(); UIUtil.putToCenter(evsDialog); if(prefs.getEvsAutoSearch()) evsDialog.startSearch(conceptUIs[index].name.getText()); evsDialog.setVisible(true); Concept c = evsDialog.getConcept(); if(c != null) { conceptUIs[index].code.setText(c.getPreferredName()); conceptUIs[index].name.setText(c.getLongName()); conceptUIs[index].def.setText(c.getPreferredDefinition()); conceptUIs[index].defSource.setText(c.getDefinitionSource()); if(areAllFieldEntered()) { setSaveButtonState(true); // addButton.setEnabled(true); } else { setSaveButtonState(false); // addButton.setEnabled(false); } reviewButton.setEnabled(false); } } }); } updateHeaderLabels(); if(prefs.getUmlDescriptionOrder().equals("last")) insertInBag(gridPanel, createDescriptionPanel(), 0, concepts.length + 1); this.add(scrollPane, BorderLayout.CENTER); } private void updateHeaderLabels() { String s = ""; for(int i = 0; i < concepts.length; i++) { s = conceptUIs[i].code.getText() + " " + s; } conceptLabel.setText(s); s = ""; for(int i = 0; i < concepts.length; i++) { s = conceptUIs[i].name.getText() + " " + s; } nameLabel.setText(s); } private JPanel createDescriptionPanel() { JPanel umlPanel = new JPanel(); String s = "UML Class Documentation"; Object o = node.getUserObject(); if(node instanceof AttributeNode) { s = "UML Attribute Description"; } umlPanel.setBorder (BorderFactory.createTitledBorder(s)); umlPanel.setLayout(new BorderLayout()); JTextArea descriptionArea = new JTextArea(5, 54); JScrollPane descScrollPane = new JScrollPane(descriptionArea); if(node instanceof ClassNode) { ObjectClass oc = (ObjectClass) node.getUserObject(); descriptionArea.setText(oc.getPreferredDefinition()); } else if(node instanceof AttributeNode) { DataElement de = (DataElement) node.getUserObject(); for(Definition def : (List<Definition>) de.getDefinitions()) { descriptionArea.setText(def.getDefinition()); break; } } descriptionArea.setLineWrap(true); descriptionArea.setEditable(false); if(StringUtil.isEmpty(descriptionArea.getText())) { umlPanel.setVisible(false); } umlPanel.add(descScrollPane, BorderLayout.CENTER); return umlPanel; } private void initButtonPanel() { addButton = new JButton("Add"); deleteButton = new JButton("Remove"); saveButton = new JButton("Apply"); reviewButton = new JCheckBox("<html>Human<br>Verified</html>"); previousButton = new JButton("Previous"); nextButton = new JButton("Next"); reviewButton.setSelected(((ReviewableUMLNode)node).isReviewed()); addButton.setActionCommand(ADD); deleteButton.setActionCommand(DELETE); saveButton.setActionCommand(SAVE); previousButton.setActionCommand(PREVIOUS); nextButton.setActionCommand(NEXT); addButton.addActionListener(this); deleteButton.addActionListener(this); saveButton.addActionListener(this); reviewButton.addItemListener(this); previousButton.addActionListener(this); nextButton.addActionListener(this); if(concepts.length < 2) deleteButton.setEnabled(false); if(areAllFieldEntered()) { reviewButton.setEnabled(true); addButton.setEnabled(true); } else { addButton.setEnabled(false); reviewButton.setEnabled(false); } setSaveButtonState(false); if(concepts.length == 0) reviewButton.setEnabled(false); JPanel buttonPanel = new JPanel(); buttonPanel.add(addButton); buttonPanel.add(deleteButton); buttonPanel.add(saveButton); buttonPanel.add(reviewButton); buttonPanel.add(previousButton); buttonPanel.add(nextButton); this.add(buttonPanel, BorderLayout.SOUTH); } private void setSaveButtonState(boolean b) { saveButton.setEnabled(b); PropertyChangeEvent evt = new PropertyChangeEvent(this, SAVE, null, b); firePropertyChangeEvent(evt); } private boolean areAllFieldEntered() { for(int i=0; i < conceptUIs.length; i++) { if(conceptUIs[i].code.getText().trim().equals("") | conceptUIs[i].name.getText().trim().equals("") | conceptUIs[i].defSource.getText().trim().equals("") | conceptUIs[i].def.getText().trim().equals("")) { return false; } } return true; } public void keyTyped(KeyEvent evt) {} public void keyPressed(KeyEvent evt) {} /** * Text Change Use Case. */ public void keyReleased(KeyEvent evt) { if(areAllFieldEntered()) { // addButton.setEnabled(true); setSaveButtonState(true); } else { // addButton.setEnabled(false); setSaveButtonState(false); } reviewButton.setEnabled(false); updateHeaderLabels(); } public void preferenceChange(UserPreferencesEvent event) { if(event.getTypeOfEvent() == UserPreferencesEvent.UML_DESCRIPTION) { _this.remove(scrollPane); initViewPanel(); } } public void actionPerformed(ActionEvent evt) { JButton button = (JButton)evt.getSource(); if(button.getActionCommand().equals(SAVE)) { updateHeaderLabels(); apply(false); } else if(button.getActionCommand().equals(ADD)) { Concept[] newConcepts = new Concept[concepts.length + 1]; for(int i = 0; i<concepts.length; i++) { newConcepts[i] = concepts[i]; } Concept concept = DomainObjectFactory.newConcept(); concept.setPreferredName(""); concept.setLongName(""); concept.setDefinitionSource(""); concept.setPreferredDefinition(""); newConcepts[newConcepts.length - 1] = concept; concepts = newConcepts; this.remove(scrollPane); initViewPanel(); this.updateUI(); if(concepts.length > 1) deleteButton.setEnabled(true); if(areAllFieldEntered()) { setSaveButtonState(true); } else { setSaveButtonState(false); } addButton.setEnabled(false); reviewButton.setEnabled(false); } else if(button.getActionCommand().equals(DELETE)) { Concept[] newConcepts = new Concept[concepts.length - 1]; for(int i = 0; i<newConcepts.length; i++) { newConcepts[i] = concepts[i]; } concepts = newConcepts; _this.remove(scrollPane); initViewPanel(); if(areAllFieldEntered()) { setSaveButtonState(true); } else { setSaveButtonState(false); } addButton.setEnabled(false); reviewButton.setEnabled(false); if(concepts.length < 2) deleteButton.setEnabled(false); this.updateUI(); remove = true; } else if(button.getActionCommand().equals(PREVIOUS)) { NavigationEvent event = new NavigationEvent(NavigationEvent.NAVIGATE_PREVIOUS); fireNavigationEvent(event); remove = false; } else if(button.getActionCommand().equals(NEXT)) { NavigationEvent event = new NavigationEvent(NavigationEvent.NAVIGATE_NEXT); fireNavigationEvent(event); remove = false; } } private void firePropertyChangeEvent(PropertyChangeEvent evt) { for(PropertyChangeListener l : propChangeListeners) l.propertyChange(evt); } private void fireNavigationEvent(NavigationEvent event) { for(NavigationListener l : navigationListeners) l.navigate(event); } public void itemStateChanged(ItemEvent e) { if(e.getStateChange() == ItemEvent.SELECTED || e.getStateChange() == ItemEvent.DESELECTED ) { ReviewEvent event = new ReviewEvent(); event.setUserObject(node); event.setReviewed(ItemEvent.SELECTED == e.getStateChange()); fireReviewEvent(event); //if item is reviewed go to next item in the tree if(e.getStateChange() == ItemEvent.SELECTED) { NavigationEvent goToNext = new NavigationEvent(NavigationEvent.NAVIGATE_NEXT); fireNavigationEvent(goToNext); } } } private void fireReviewEvent(ReviewEvent event) { for(ReviewListener l : reviewListeners) l.reviewChanged(event); } private void fireElementChangeEvent(ElementChangeEvent event) { for(ElementChangeListener l : changeListeners) l.elementChanged(event); } private void insertInBag(JPanel bagComp, Component comp, int x, int y) { insertInBag(bagComp, comp, x, y, 1, 1); } private void insertInBag(JPanel bagComp, Component comp, int x, int y, int width, int height) { JPanel p = new JPanel(); p.add(comp); bagComp.add(p, new GridBagConstraints(x, y, width, height, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); } } class ConceptUI { // initialize once the mode in which we're running private static boolean editable = false; static { UserSelections selections = UserSelections.getInstance(); editable = selections.getProperty("MODE").equals(RunMode.Curator); } JLabel[] labels = new JLabel[] { new JLabel("Concept Code"), new JLabel("Concept Preferred Name"), new JLabel("Concept Definition"), new JLabel("Concept Definition Source") }; JTextField code = new JTextField(10); JTextField name = new JTextField(20); JTextArea def = new JTextArea(); JTextField defSource = new JTextField(10); JScrollPane defScrollPane; public ConceptUI(Concept concept) { initUI(concept); } private void initUI(Concept concept) { def.setFont(new Font("Serif", Font.ITALIC, 16)); def.setLineWrap(true); def.setWrapStyleWord(true); defScrollPane = new JScrollPane(def); defScrollPane .setVerticalScrollBarPolicy (JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); defScrollPane.setPreferredSize(new Dimension(400, 100)); code.setText(concept.getPreferredName()); name.setText(concept.getLongName()); def.setText(concept.getPreferredDefinition()); defSource.setText(concept.getDefinitionSource()); // if(!editable) { // code.setEnabled(false); // name.setEnabled(false); // def.setEnabled(false); // defSource.setEnabled(false); // } } }
Redesigned UMLElementViewPanel SVN-Revision: 670
src/gov/nih/nci/ncicb/cadsr/loader/ui/UMLElementViewPanel.java
Redesigned UMLElementViewPanel
<ide><path>rc/gov/nih/nci/ncicb/cadsr/loader/ui/UMLElementViewPanel.java <ide> import javax.swing.event.*; <ide> <ide> public class UMLElementViewPanel extends JPanel <del> implements ActionListener, KeyListener <del> , ItemListener, <del> UserPreferencesListener, NavigationListener { <del> <del> private Concept[] concepts; <del> private ConceptUI[] conceptUIs; <add> implements //ActionListener, KeyListener <add> //, ItemListener, <add> //UserPreferencesListener, <add> NavigationListener { <ide> <ide> private UMLElementViewPanel _this = this; <del> <del> private UMLNode node; <del> private boolean remove = false, <del> orderChanged = false; <del> <del> private static final String ADD = "ADD", <del> DELETE = "DELETE", <del> SAVE = "APPLY", <del> PREVIOUS = "PREVIOUS", <del> NEXT = "NEXT"; <del> <del> private JButton addButton, deleteButton, saveButton; <del> private JButton previousButton, nextButton; <del> private JCheckBox reviewButton; <del> private JLabel conceptLabel = new JLabel(); <del> private JLabel nameLabel = new JLabel(); <del> <del> private List<ReviewListener> reviewListeners <del> = new ArrayList<ReviewListener>(); <del> <del> private List<ElementChangeListener> changeListeners <del> = new ArrayList<ElementChangeListener>(); <ide> <ide> private List<NavigationListener> navigationListeners <ide> = new ArrayList<NavigationListener>(); <ide> <del> private List<PropertyChangeListener> propChangeListeners <del> = new ArrayList<PropertyChangeListener>(); <del> <del> private JPanel gridPanel; <del> private JScrollPane scrollPane; <add> private ConceptEditorPanel conceptEditorPanel; <add> private ButtonPanel buttonPanel; <ide> <ide> // initialize once the mode in which we're running <del> private static boolean editable = false; <del> static { <del> UserSelections selections = UserSelections.getInstance(); <del> editable = selections.getProperty("MODE").equals(RunMode.Curator); <add> <add> public UMLElementViewPanel(UMLNode node) <add> { <add> <add> conceptEditorPanel = new ConceptEditorPanel(node); <add> buttonPanel = new ButtonPanel(conceptEditorPanel); <add> conceptEditorPanel.addPropertyChangeListener(buttonPanel); <add> initUI(); <ide> } <ide> <del> private UserPreferences prefs = UserPreferences.getInstance(); <add> private void initUI() { <ide> <del> private static EvsDialog evsDialog; <add> conceptEditorPanel.initUI(); <add> <add> setLayout(new BorderLayout()); <add> this.add(conceptEditorPanel, BorderLayout.CENTER); <add> this.add(buttonPanel, BorderLayout.SOUTH); <add> <add> } <ide> <del> public UMLElementViewPanel(UMLNode node) <add> //new <add> public void updateNode(UMLNode node) <ide> { <del> this.node = node; <del> initConcepts(); <del> initUI(); <add> conceptEditorPanel.updateNode(node); <add> } <add> <add> //new <add> public void apply(boolean value) <add> { <add> conceptEditorPanel.apply(value); <ide> } <ide> <del> public void navigate(NavigationEvent evt) { <del> if(saveButton.isEnabled()) { <del> if(JOptionPane.showConfirmDialog(_this, "There are unsaved changes in this concept, would you like to apply the changes now?", "Unsaved Changes", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) <del> apply(false); <del> } <add> public void navigate(NavigationEvent evt) { <add>// for(NavigationListener nl : navigationListeners) <add>// nl.navigate(evt); <add> buttonPanel.navigate(evt); <ide> } <ide> <ide> public void addReviewListener(ReviewListener listener) { <del> reviewListeners.add(listener); <del> } <del> <del> public void addElementChangeListener(ElementChangeListener listener) { <del> changeListeners.add(listener); <add> buttonPanel.addReviewListener(listener); <ide> } <ide> <ide> public void addNavigationListener(NavigationListener listener) <ide> { <del> navigationListeners.add(listener); <add>// navigationListeners.add(listener); <add> buttonPanel.addNavigationListener(listener); <add> } <add> <add> public void addElementChangeListener(ElementChangeListener listener) { <add> conceptEditorPanel.addElementChangeListener(listener); <ide> } <ide> <ide> public void addPropertyChangeListener(PropertyChangeListener l) { <del> propChangeListeners.add(l); <del> } <del> <del> public void updateNode(UMLNode node) <del> { <del> this.node = node; <del> initConcepts(); <del> updateConcepts(concepts); <del> } <del> <del> public void apply(boolean toAll) { <del> boolean update = remove; <del> remove = false; <del> Concept[] newConcepts = new Concept[concepts.length]; <del> <del> for(int i = 0; i<concepts.length; i++) { <del> newConcepts[i] = concepts[i]; <del> // concept code has not changed <del> if(conceptUIs[i].code.getText().equals(concepts[i].getPreferredName())) { <del> concepts[i].setLongName(conceptUIs[i].name.getText()); <del> concepts[i].setPreferredDefinition(conceptUIs[i].def.getText()); <del> concepts[i].setDefinitionSource(conceptUIs[i].defSource.getText()); <del> } else { // concept code has changed <del> Concept concept = DomainObjectFactory.newConcept(); <del> concept.setPreferredName(conceptUIs[i].code.getText()); <del> concept.setLongName(conceptUIs[i].name.getText()); <del> concept.setPreferredDefinition(conceptUIs[i].def.getText()); <del> concept.setDefinitionSource(conceptUIs[i].defSource.getText()); <del> newConcepts[i] = concept; <del> update = true; <del> } <del> } <del> <del> update = orderChanged | update; <del> <del> if(update) { <del> if(toAll) { <del> Object o = node.getUserObject(); <del> if(o instanceof DataElement) { <del> DataElement de = (DataElement)o; <del> ObjectUpdater.updateByAltName(de.getDataElementConcept().getProperty().getLongName(), concepts, newConcepts); <del> } <del> } else <del> ObjectUpdater.update((AdminComponent)node.getUserObject(), concepts, newConcepts); <del> <del> concepts = newConcepts; <del> } <del> <del> orderChanged = false; <del> <del> setSaveButtonState(false); <del> addButton.setEnabled(true); <del> reviewButton.setEnabled(true); <del> <del> fireElementChangeEvent(new ElementChangeEvent(node)); <del> } <del> <del> private void initConcepts() <del> { <del> concepts = NodeUtil.getConceptsFromNode(node); <del> } <del> <del> private void updateConcepts(Concept[] concepts) { <del> this.concepts = concepts; <del> this.removeAll(); <del> initUI(); <del> this.updateUI(); <del> } <del> <del> private void initUI() { <del> prefs.addUserPreferencesListener(this); <del> this.setLayout(new BorderLayout()); <del> <del> JPanel summaryPanel = new JPanel(new GridBagLayout()); <del> JLabel summaryTitle = new JLabel("UML Concept Code Summary: "); <del> <del> JLabel summaryNameTitle = new JLabel("UML Concept Name Summary: "); <del> <del> insertInBag(summaryPanel, summaryTitle, 0, 0); <del> insertInBag(summaryPanel, conceptLabel, 1, 0); <del> insertInBag(summaryPanel, summaryNameTitle, 0, 1); <del> insertInBag(summaryPanel, nameLabel, 1, 1); <del> <del> this.add(summaryPanel,BorderLayout.NORTH); <del> <del> initViewPanel(); <del> initButtonPanel(); <del> } <del> <del> private void initViewPanel() { <del> <del> gridPanel = new JPanel(new GridBagLayout()); <del> <del> scrollPane = new JScrollPane(gridPanel); <del> <del> conceptUIs = new ConceptUI[concepts.length]; <del> JPanel[] conceptPanels = new JPanel[concepts.length]; <del> <del> if(prefs.getUmlDescriptionOrder().equals("first")) <del> insertInBag(gridPanel, createDescriptionPanel(), 0, 0); <del> <del> for(int i = 0; i<concepts.length; i++) { <del> conceptUIs[i] = new ConceptUI(concepts[i]); <del> <del> String title = i == 0?"Primary Concept":"Qualifier Concept" +" #" + (i); <del> <del> conceptPanels[i] = new JPanel(); <del> conceptPanels[i].setBorder <del> (BorderFactory.createTitledBorder(title)); <del> <del> conceptPanels[i].setLayout(new BorderLayout()); <del> <del> JPanel mainPanel = new JPanel(new GridBagLayout()); <del> <del> insertInBag(mainPanel, conceptUIs[i].labels[0], 0, 0); <del> insertInBag(mainPanel, conceptUIs[i].labels[1], 0, 1); <del> insertInBag(mainPanel, conceptUIs[i].labels[2], 0, 2); <del> insertInBag(mainPanel, conceptUIs[i].labels[3], 0, 3); <del> <del> insertInBag(mainPanel, conceptUIs[i].code, 1, 0, 2, 1); <del> insertInBag(mainPanel, conceptUIs[i].name, 1, 1, 2, 1); <del> insertInBag(mainPanel, conceptUIs[i].defScrollPane, 1, 2, 2, 1); <del> insertInBag(mainPanel, conceptUIs[i].defSource, 1, 3,1, 1); <del> <del> JButton evsButton = new JButton("Evs Link"); <del> insertInBag(mainPanel, evsButton, 2, 3); <del> <del> JButton upButton = new JButton(new ImageIcon(Thread.currentThread().getContextClassLoader().getResource("up-arrow.gif"))); <del> JButton downButton = new JButton(new ImageIcon(Thread.currentThread().getContextClassLoader().getResource("down-arrow.gif"))); <del> <del> upButton.setPreferredSize(new Dimension(28, 35)); <del> downButton.setPreferredSize(new Dimension(28, 35)); <del> <del> JPanel arrowPanel = new JPanel(new GridBagLayout()); <del> insertInBag(arrowPanel, upButton, 0, 0); <del> insertInBag(arrowPanel, downButton, 0, 6); <del> <del> conceptPanels[i].add(mainPanel, BorderLayout.CENTER); <del> conceptPanels[i].add(arrowPanel, BorderLayout.EAST); <del> <del> insertInBag(gridPanel, conceptPanels[i], 0, conceptPanels.length - i); <del> <del> conceptUIs[i].code.addKeyListener(this); <del> conceptUIs[i].name.addKeyListener(this); <del> conceptUIs[i].def.addKeyListener(this); <del> conceptUIs[i].defSource.addKeyListener(this); <del> <del> final int index = i; <del> if(index == 0) <del> downButton.setVisible(false); <del> if(index == concepts.length-1) <del> upButton.setVisible(false); <del> <del> downButton.addActionListener(new ActionListener() { <del> public void actionPerformed(ActionEvent event) { <del> Concept temp = concepts[index-1]; <del> concepts[index-1] = concepts[index]; <del> concepts[index] = temp; <del> updateConcepts(concepts); <del> <del> orderChanged = true; <del> <del> setSaveButtonState(areAllFieldEntered()); <del> reviewButton.setEnabled(false); <del> addButton.setEnabled(false); <del> } <del> }); <del> <del> upButton.addActionListener(new ActionListener() { <del> public void actionPerformed(ActionEvent event) { <del> Concept temp = concepts[index]; <del> concepts[index] = concepts[index+1]; <del> concepts[index+1] = temp; <del> updateConcepts(concepts); <del> <del> orderChanged = true; <del> <del> setSaveButtonState(areAllFieldEntered()); <del> reviewButton.setEnabled(false); <del> addButton.setEnabled(false); <del> } <del> }); <del> <del> <del> evsButton.addActionListener(new ActionListener() { <del> public void actionPerformed(ActionEvent event) { <del> if (evsDialog == null) <del> evsDialog = new EvsDialog(); <del> <del> UIUtil.putToCenter(evsDialog); <del> <del> if(prefs.getEvsAutoSearch()) <del> evsDialog.startSearch(conceptUIs[index].name.getText()); <del> evsDialog.setVisible(true); <del> <del> Concept c = evsDialog.getConcept(); <del> <del> if(c != null) { <del> conceptUIs[index].code.setText(c.getPreferredName()); <del> conceptUIs[index].name.setText(c.getLongName()); <del> conceptUIs[index].def.setText(c.getPreferredDefinition()); <del> conceptUIs[index].defSource.setText(c.getDefinitionSource()); <del> <del> if(areAllFieldEntered()) { <del> setSaveButtonState(true); <del> // addButton.setEnabled(true); <del> } else { <del> setSaveButtonState(false); <del> // addButton.setEnabled(false); <del> } <del> reviewButton.setEnabled(false); <del> } <del> } <del> }); <del> <del> } <del> <del> updateHeaderLabels(); <del> <del> if(prefs.getUmlDescriptionOrder().equals("last")) <del> insertInBag(gridPanel, createDescriptionPanel(), 0, concepts.length + 1); <del> <del> this.add(scrollPane, BorderLayout.CENTER); <del> <del> } <del> <del> private void updateHeaderLabels() <del> { <del> String s = ""; <del> for(int i = 0; i < concepts.length; i++) { <del> s = conceptUIs[i].code.getText() + " " + s; <del> } <del> conceptLabel.setText(s); <del> <del> s = ""; <del> for(int i = 0; i < concepts.length; i++) { <del> s = conceptUIs[i].name.getText() + " " + s; <del> } <del> nameLabel.setText(s); <del> } <del> <del> private JPanel createDescriptionPanel() { <del> JPanel umlPanel = new JPanel(); <del> <del> <del> String s = "UML Class Documentation"; <del> Object o = node.getUserObject(); <del> if(node instanceof AttributeNode) { <del> s = "UML Attribute Description"; <del> } <del> <del> umlPanel.setBorder <del> (BorderFactory.createTitledBorder(s)); <del> umlPanel.setLayout(new BorderLayout()); <del> <del> JTextArea descriptionArea = new JTextArea(5, 54); <del> JScrollPane descScrollPane = new JScrollPane(descriptionArea); <del> <del> if(node instanceof ClassNode) { <del> ObjectClass oc = (ObjectClass) node.getUserObject(); <del> descriptionArea.setText(oc.getPreferredDefinition()); <del> } else if(node instanceof AttributeNode) { <del> DataElement de = (DataElement) node.getUserObject(); <del> <del> for(Definition def : (List<Definition>) de.getDefinitions()) { <del> descriptionArea.setText(def.getDefinition()); <del> break; <del> } <del> <del> } <del> <del> descriptionArea.setLineWrap(true); <del> descriptionArea.setEditable(false); <del> <del> if(StringUtil.isEmpty(descriptionArea.getText())) <del> { <del> umlPanel.setVisible(false); <del> } <del> <del> umlPanel.add(descScrollPane, BorderLayout.CENTER); <del> <del> return umlPanel; <del> <del> } <del> <del> private void initButtonPanel() { <del> addButton = new JButton("Add"); <del> deleteButton = new JButton("Remove"); <del> saveButton = new JButton("Apply"); <del> reviewButton = new JCheckBox("<html>Human<br>Verified</html>"); <del> previousButton = new JButton("Previous"); <del> nextButton = new JButton("Next"); <del> <del> reviewButton.setSelected(((ReviewableUMLNode)node).isReviewed()); <del> addButton.setActionCommand(ADD); <del> deleteButton.setActionCommand(DELETE); <del> saveButton.setActionCommand(SAVE); <del> previousButton.setActionCommand(PREVIOUS); <del> nextButton.setActionCommand(NEXT); <del> addButton.addActionListener(this); <del> deleteButton.addActionListener(this); <del> saveButton.addActionListener(this); <del> reviewButton.addItemListener(this); <del> previousButton.addActionListener(this); <del> nextButton.addActionListener(this); <del> <del> if(concepts.length < 2) <del> deleteButton.setEnabled(false); <del> <del> if(areAllFieldEntered()) { <del> reviewButton.setEnabled(true); <del> addButton.setEnabled(true); <del> } else { <del> addButton.setEnabled(false); <del> reviewButton.setEnabled(false); <del> } <del> setSaveButtonState(false); <del> <del> if(concepts.length == 0) <del> reviewButton.setEnabled(false); <del> <del> <del> JPanel buttonPanel = new JPanel(); <del> buttonPanel.add(addButton); <del> buttonPanel.add(deleteButton); <del> buttonPanel.add(saveButton); <del> buttonPanel.add(reviewButton); <del> buttonPanel.add(previousButton); <del> buttonPanel.add(nextButton); <del> <del> this.add(buttonPanel, BorderLayout.SOUTH); <del> } <del> <del> private void setSaveButtonState(boolean b) { <del> saveButton.setEnabled(b); <del> <del> PropertyChangeEvent evt = new PropertyChangeEvent(this, SAVE, null, b); <del> firePropertyChangeEvent(evt); <del> } <del> <del> private boolean areAllFieldEntered() { <del> for(int i=0; i < conceptUIs.length; i++) { <del> if(conceptUIs[i].code.getText().trim().equals("") <del> | conceptUIs[i].name.getText().trim().equals("") <del> | conceptUIs[i].defSource.getText().trim().equals("") <del> | conceptUIs[i].def.getText().trim().equals("")) { <del> return false; <del> } <del> } <del> return true; <del> } <del> <del> public void keyTyped(KeyEvent evt) {} <del> public void keyPressed(KeyEvent evt) {} <del> <del> /** <del> * Text Change Use Case. <del> */ <del> public void keyReleased(KeyEvent evt) { <del> if(areAllFieldEntered()) { <del>// addButton.setEnabled(true); <del> setSaveButtonState(true); <del> } else { <del>// addButton.setEnabled(false); <del> setSaveButtonState(false); <del> } <del> reviewButton.setEnabled(false); <del> updateHeaderLabels(); <add> conceptEditorPanel.addPropertyChangeListener(l); <add> buttonPanel.addPropertyChangeListener(l); <ide> } <ide> <ide> <del> public void preferenceChange(UserPreferencesEvent event) <del> { <del> if(event.getTypeOfEvent() == UserPreferencesEvent.UML_DESCRIPTION) <del> { <del> _this.remove(scrollPane); <del> initViewPanel(); <del> } <del> } <ide> <ide> <del> public void actionPerformed(ActionEvent evt) { <del> JButton button = (JButton)evt.getSource(); <del> if(button.getActionCommand().equals(SAVE)) { <del> updateHeaderLabels(); <del> apply(false); <del> <del> } else if(button.getActionCommand().equals(ADD)) { <del> Concept[] newConcepts = new Concept[concepts.length + 1]; <del> for(int i = 0; i<concepts.length; i++) { <del> newConcepts[i] = concepts[i]; <del> } <del> Concept concept = DomainObjectFactory.newConcept(); <del> concept.setPreferredName(""); <del> concept.setLongName(""); <del> concept.setDefinitionSource(""); <del> concept.setPreferredDefinition(""); <del> newConcepts[newConcepts.length - 1] = concept; <del> concepts = newConcepts; <ide> <del> this.remove(scrollPane); <del> initViewPanel(); <del> this.updateUI(); <ide> <del> if(concepts.length > 1) <del> deleteButton.setEnabled(true); <ide> <del> if(areAllFieldEntered()) { <del> setSaveButtonState(true); <del> } else { <del> setSaveButtonState(false); <del> } <del> addButton.setEnabled(false); <del> reviewButton.setEnabled(false); <del> } else if(button.getActionCommand().equals(DELETE)) { <del> Concept[] newConcepts = new Concept[concepts.length - 1]; <del> for(int i = 0; i<newConcepts.length; i++) { <del> newConcepts[i] = concepts[i]; <del> } <del> concepts = newConcepts; <del> <del> _this.remove(scrollPane); <del> initViewPanel(); <del> <del> if(areAllFieldEntered()) { <del> setSaveButtonState(true); <del> } else { <del> setSaveButtonState(false); <del> } <del> addButton.setEnabled(false); <del> reviewButton.setEnabled(false); <del> <del> if(concepts.length < 2) <del> deleteButton.setEnabled(false); <del> this.updateUI(); <ide> <del> remove = true; <ide> <del> } else if(button.getActionCommand().equals(PREVIOUS)) { <del> NavigationEvent event = new NavigationEvent(NavigationEvent.NAVIGATE_PREVIOUS); <del> fireNavigationEvent(event); <del> remove = false; <del> } else if(button.getActionCommand().equals(NEXT)) { <del> NavigationEvent event = new NavigationEvent(NavigationEvent.NAVIGATE_NEXT); <del> fireNavigationEvent(event); <del> remove = false; <del> } <del> <del> } <del> <del> private void firePropertyChangeEvent(PropertyChangeEvent evt) { <del> for(PropertyChangeListener l : propChangeListeners) <del> l.propertyChange(evt); <del> } <del> <del> private void fireNavigationEvent(NavigationEvent event) <del> { <del> for(NavigationListener l : navigationListeners) <del> l.navigate(event); <del> } <del> <del> <del> public void itemStateChanged(ItemEvent e) { <del> if(e.getStateChange() == ItemEvent.SELECTED <del> || e.getStateChange() == ItemEvent.DESELECTED <del> ) { <del> ReviewEvent event = new ReviewEvent(); <del> event.setUserObject(node); <del> <del> event.setReviewed(ItemEvent.SELECTED == e.getStateChange()); <del> <del> fireReviewEvent(event); <del> <del> //if item is reviewed go to next item in the tree <del> if(e.getStateChange() == ItemEvent.SELECTED) <del> { <del> NavigationEvent goToNext = new NavigationEvent(NavigationEvent.NAVIGATE_NEXT); <del> fireNavigationEvent(goToNext); <del> } <del> <del> } <del> } <del> <del> private void fireReviewEvent(ReviewEvent event) { <del> for(ReviewListener l : reviewListeners) <del> l.reviewChanged(event); <del> } <del> <del> private void fireElementChangeEvent(ElementChangeEvent event) { <del> for(ElementChangeListener l : changeListeners) <del> l.elementChanged(event); <del> } <ide> <ide> <del> private void insertInBag(JPanel bagComp, Component comp, int x, int y) { <ide> <del> insertInBag(bagComp, comp, x, y, 1, 1); <ide> <del> } <ide> <del> private void insertInBag(JPanel bagComp, Component comp, int x, int y, int width, int height) { <del> JPanel p = new JPanel(); <del> p.add(comp); <ide> <del> bagComp.add(p, new GridBagConstraints(x, y, width, height, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); <del> } <add> <add> <add> <add> <add> <add> <add> <add> <add> <add> <add> <add> <add> <add> <add> <add> <add> <add> <add> <add> <add> <add> <add> <add> <add> <add> <ide> <ide> } <ide> <del>class ConceptUI { <del> // initialize once the mode in which we're running <del> private static boolean editable = false; <del> static { <del> UserSelections selections = UserSelections.getInstance(); <del> editable = selections.getProperty("MODE").equals(RunMode.Curator); <del> } <del> <del> JLabel[] labels = new JLabel[] { <del> new JLabel("Concept Code"), <del> new JLabel("Concept Preferred Name"), <del> new JLabel("Concept Definition"), <del> new JLabel("Concept Definition Source") <del> }; <del> <del> JTextField code = new JTextField(10); <del> JTextField name = new JTextField(20); <del> JTextArea def = new JTextArea(); <del> JTextField defSource = new JTextField(10); <del> <del> JScrollPane defScrollPane; <del> <del> public ConceptUI(Concept concept) { <del> initUI(concept); <del> } <del> <del> private void initUI(Concept concept) { <del> def.setFont(new Font("Serif", Font.ITALIC, 16)); <del> def.setLineWrap(true); <del> def.setWrapStyleWord(true); <del> defScrollPane = new JScrollPane(def); <del> defScrollPane <del> .setVerticalScrollBarPolicy <del> (JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); <del> defScrollPane.setPreferredSize(new Dimension(400, 100)); <del> <del> code.setText(concept.getPreferredName()); <del> name.setText(concept.getLongName()); <del> def.setText(concept.getPreferredDefinition()); <del> defSource.setText(concept.getDefinitionSource()); <del> <del>// if(!editable) { <del>// code.setEnabled(false); <del>// name.setEnabled(false); <del>// def.setEnabled(false); <del>// defSource.setEnabled(false); <del>// } <del> <del> } <del> <del> <del> <del>} <add>
Java
lgpl-2.1
43a903c31c0f587ffb6501f67f2401d26c5863bc
0
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
// // $Id$ // // Narya library - tools for developing networked games // Copyright (C) 2002-2004 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/narya/ // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.parlor.card.client; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.Iterator; import javax.swing.event.MouseInputAdapter; import com.samskivert.util.ObserverList; import com.samskivert.util.QuickSort; import com.threerings.media.FrameManager; import com.threerings.media.VirtualMediaPanel; import com.threerings.media.image.Mirage; import com.threerings.media.sprite.PathAdapter; import com.threerings.media.sprite.Sprite; import com.threerings.media.util.LinePath; import com.threerings.media.util.Path; import com.threerings.media.util.PathSequence; import com.threerings.media.util.Pathable; import com.threerings.parlor.card.Log; import com.threerings.parlor.card.data.Card; import com.threerings.parlor.card.data.CardCodes; import com.threerings.parlor.card.data.Deck; import com.threerings.parlor.card.data.Hand; /** * Extends VirtualMediaPanel to provide services specific to rendering * and manipulating playing cards. */ public abstract class CardPanel extends VirtualMediaPanel implements CardCodes { /** The selection mode in which cards are not selectable. */ public static final int NONE = 0; /** The selection mode in which the user can select a single card. */ public static final int SINGLE = 2; /** The selection mode in which the user can select multiple cards. */ public static final int MULTIPLE = 3; /** * A predicate class for {@link CardSprite}s. Provides control over which * cards are selectable, playable, etc. */ public static interface CardSpritePredicate { /** * Evaluates the specified sprite. */ public boolean evaluate (CardSprite sprite); } /** * A listener for card selection/deselection. */ public static interface CardSelectionObserver { /** * Called when a card has been selected. */ public void cardSpriteSelected (CardSprite sprite); /** * Called when a card has been deselected. */ public void cardSpriteDeselected (CardSprite sprite); } /** * Constructor. * * @param frameManager the frame manager */ public CardPanel (FrameManager frameManager) { super(frameManager); // add a listener for mouse events CardListener cl = new CardListener(); addMouseListener(cl); addMouseMotionListener(cl); } /** * Returns the full-sized image for the back of a playing card. */ public abstract Mirage getCardBackImage (); /** * Returns the full-sized image for the front of the specified card. */ public abstract Mirage getCardImage (Card card); /** * Returns the small-sized image for the back of a playing card. */ public abstract Mirage getMicroCardBackImage (); /** * Returns the small-sized image for the front of the specified card. */ public abstract Mirage getMicroCardImage (Card card); /** * Sets the location of the hand (the location of the center of the hand's * upper edge). */ public void setHandLocation (int x, int y) { _handLocation.setLocation(x, y); } /** * Sets the horizontal spacing between cards in the hand. */ public void setHandSpacing (int spacing) { _handSpacing = spacing; } /** * Sets the vertical distance to offset cards that are selectable or * playable. */ public void setSelectableCardOffset (int offset) { _selectableCardOffset = offset; } /** * Sets the vertical distance to offset cards that are selected. */ public void setSelectedCardOffset (int offset) { _selectedCardOffset = offset; } /** * Sets the selection mode for the hand (NONE, PLAY_SINGLE, SINGLE, * or MULTIPLE). Changing the selection mode does not change the * current selection. */ public void setHandSelectionMode (int mode) { _handSelectionMode = mode; // update the offsets of all cards in the hand updateHandOffsets(); } /** * Sets the selection predicate that determines which cards from the hand * may be selected (if null, all cards may be selected). Changing the * predicate does not change the current selection. */ public void setHandSelectionPredicate (CardSpritePredicate pred) { _handSelectionPredicate = pred; // update the offsets of all cards in the hand updateHandOffsets(); } /** * Returns the currently selected hand sprite (null if no sprites are * selected, the first sprite if multiple sprites are selected). */ public CardSprite getSelectedHandSprite () { return _selectedHandSprites.size() == 0 ? null : (CardSprite)_selectedHandSprites.get(0); } /** * Returns an array containing the currently selected hand sprites * (returns an empty array if no sprites are selected). */ public CardSprite[] getSelectedHandSprites () { return (CardSprite[])_selectedHandSprites.toArray( new CardSprite[_selectedHandSprites.size()]); } /** * Programmatically selects a sprite in the hand. */ public void selectHandSprite (final CardSprite sprite) { // make sure it's not already selected if (_selectedHandSprites.contains(sprite)) { return; } // if in single card mode and there's another card selected, // deselect it if (_handSelectionMode == SINGLE) { CardSprite oldSprite = getSelectedHandSprite(); if (oldSprite != null) { deselectHandSprite(oldSprite); } } // add to list and update offset _selectedHandSprites.add(sprite); sprite.setLocation(sprite.getX(), getHandY(sprite)); // notify the observers ObserverList.ObserverOp op = new ObserverList.ObserverOp() { public boolean apply (Object obs) { ((CardSelectionObserver)obs).cardSpriteSelected(sprite); return true; } }; _handSelectionObservers.apply(op); } /** * Programmatically deselects a sprite in the hand. */ public void deselectHandSprite (final CardSprite sprite) { // make sure it's selected if (!_selectedHandSprites.contains(sprite)) { return; } // remove from list and update offset _selectedHandSprites.remove(sprite); sprite.setLocation(sprite.getX(), getHandY(sprite)); // notify the observers ObserverList.ObserverOp op = new ObserverList.ObserverOp() { public boolean apply (Object obs) { ((CardSelectionObserver)obs).cardSpriteDeselected(sprite); return true; } }; _handSelectionObservers.apply(op); } /** * Clears any existing hand sprite selection. */ public void clearHandSelection () { CardSprite[] sprites = getSelectedHandSprites(); for (int i = 0; i < sprites.length; i++) { deselectHandSprite(sprites[i]); } } /** * Adds an object to the list of observers to notify when cards in the * hand are selected/deselected. */ public void addHandSelectionObserver (CardSelectionObserver obs) { _handSelectionObservers.add(obs); } /** * Removes an object from the hand selection observer list. */ public void removeHandSelectionObserver (CardSelectionObserver obs) { _handSelectionObservers.remove(obs); } /** * Fades a hand of cards in. * * @param hand the hand of cards * @param fadeDuration the amount of time to spend fading in * the entire hand */ public void setHand (Hand hand, long fadeDuration) { // make sure no cards are hanging around clearHand(); // create the sprites int size = hand.size(); for (int i = 0; i < size; i++) { CardSprite cs = new CardSprite(this, (Card)hand.get(i)); _handSprites.add(cs); } // sort them QuickSort.sort(_handSprites); // fade them in at proper locations and layers long cardDuration = fadeDuration / size; for (int i = 0; i < size; i++) { CardSprite cs = (CardSprite)_handSprites.get(i); cs.setLocation(getHandX(size, i), _handLocation.y); cs.setRenderOrder(i); cs.addSpriteObserver(_handSpriteObserver); addSprite(cs); cs.fadeIn(i * cardDuration, cardDuration); } // make sure we have the right card sprite active updateActiveCardSprite(); } /** * Fades a hand of cards in face-down. * * @param size the size of the hand * @param fadeDuration the amount of time to spend fading in * each card */ public void setHand (int size, long fadeDuration) { // fill hand will null entries to signify unknown cards Hand hand = new Hand(); for (int i = 0; i < size; i++) { hand.add(null); } setHand(hand, fadeDuration); } /** * Shows a hand that was previous set face-down. * * @param hand the hand of cards */ public void showHand (Hand hand) { // sort the hand QuickSort.sort(hand); // set the sprites int len = Math.min(_handSprites.size(), hand.size()); for (int i = 0; i < len; i++) { CardSprite cs = (CardSprite)_handSprites.get(i); cs.setCard((Card)hand.get(i)); } } /** * Returns the first sprite in the hand that corresponds to the * specified card, or null if the card is not in the hand. */ public CardSprite getHandSprite (Card card) { return getCardSprite(_handSprites, card); } /** * Clears all cards from the hand. */ public void clearHand () { clearHandSelection(); clearSprites(_handSprites); } /** * Clears all cards from the board. */ public void clearBoard () { clearSprites(_boardSprites); } /** * Flies a set of cards from the hand into the ether. Clears any selected * cards. * * @param cards the card sprites to remove from the hand * @param dest the point to fly the cards to * @param flightDuration the duration of the cards' flight * @param fadePortion the amount of time to spend fading out * as a proportion of the flight duration */ public void flyFromHand (CardSprite[] cards, Point dest, long flightDuration, float fadePortion) { // fly each sprite over, removing it from the hand immediately and // from the board when it finishes its path for (int i = 0; i < cards.length; i++) { removeFromHand(cards[i]); LinePath flight = new LinePath(dest, flightDuration); cards[i].addSpriteObserver(_pathEndRemover); cards[i].moveAndFadeOut(flight, flightDuration, fadePortion); } // adjust the hand to cover the hole adjustHand(flightDuration, false); } /** * Flies a set of cards from the ether into the hand. Clears any selected * cards. The cards will first fly to the selected card offset, pause for * the specified duration, and then drop into the hand. * * @param cards the cards to add to the hand * @param src the point to fly the cards from * @param flightDuration the duration of the cards' flight * @param pauseDuration the duration of the pause before dropping into the * hand * @param dropDuration the duration of the cards' drop into the * hand * @param fadePortion the amount of time to spend fading in * as a proportion of the flight duration */ public void flyIntoHand (Card[] cards, Point src, long flightDuration, long pauseDuration, long dropDuration, float fadePortion) { // first create the sprites and add them to the list CardSprite[] sprites = new CardSprite[cards.length]; for (int i = 0; i < cards.length; i++) { sprites[i] = new CardSprite(this, cards[i]); _handSprites.add(sprites[i]); } // settle the hand adjustHand(flightDuration, true); // then set the layers and fly the cards in int size = _handSprites.size(); for (int i = 0; i < sprites.length; i++) { int idx = _handSprites.indexOf(sprites[i]); sprites[i].setLocation(src.x, src.y); sprites[i].setRenderOrder(idx); sprites[i].addSpriteObserver(_handSpriteObserver); addSprite(sprites[i]); // create a path sequence containing flight, pause, and drop ArrayList paths = new ArrayList(); Point hp2 = new Point(getHandX(size, idx), _handLocation.y), hp1 = new Point(hp2.x, hp2.y - _selectedCardOffset); paths.add(new LinePath(hp1, flightDuration)); paths.add(new LinePath(hp1, pauseDuration)); paths.add(new LinePath(hp2, dropDuration)); sprites[i].moveAndFadeIn(new PathSequence(paths), flightDuration + pauseDuration + dropDuration, fadePortion); } } /** * Flies a set of cards from the ether into the ether. * * @param cards the cards to fly across * @param src the point to fly the cards from * @param dest the point to fly the cards to * @param flightDuration the duration of the cards' flight * @param cardDelay the amount of time to wait between cards * @param fadePortion the amount of time to spend fading in and out * as a proportion of the flight duration */ public void flyAcross (Card[] cards, Point src, Point dest, long flightDuration, long cardDelay, float fadePortion) { for (int i = 0; i < cards.length; i++) { // add on top of all board sprites CardSprite cs = new CardSprite(this, cards[i]); cs.setRenderOrder(getHighestBoardLayer() + 1 + i); cs.setLocation(src.x, src.y); addSprite(cs); // prepend an initial delay to all cards after the first Path path; long pathDuration; LinePath flight = new LinePath(dest, flightDuration); if (i > 0) { long delayDuration = cardDelay * i; LinePath delay = new LinePath(src, delayDuration); path = new PathSequence(delay, flight); pathDuration = delayDuration + flightDuration; } else { path = flight; pathDuration = flightDuration; } cs.addSpriteObserver(_pathEndRemover); cs.moveAndFadeInAndOut(path, pathDuration, fadePortion); } } /** * Flies a set of cards from the ether into the ether face-down. * * @param number the number of cards to fly across * @param src the point to fly the cards from * @param dest the point to fly the cards to * @param flightDuration the duration of the cards' flight * @param cardDelay the amount of time to wait between cards * @param fadePortion the amount of time to spend fading in and out * as a proportion of the flight duration */ public void flyAcross (int number, Point src, Point dest, long flightDuration, long cardDelay, float fadePortion) { // use null values to signify unknown cards flyAcross(new Card[number], src, dest, flightDuration, cardDelay, fadePortion); } /** * Flies a card from the hand onto the board. Clears any cards selected. * * @param card the sprite to remove from the hand * @param dest the point to fly the card to * @param flightDuration the duration of the card's flight */ public void flyFromHandToBoard (CardSprite card, Point dest, long flightDuration) { // fly it over LinePath flight = new LinePath(dest, flightDuration); card.move(flight); // lower the board so that the card from hand is on top lowerBoardSprites(card.getRenderOrder() - 1); // move from one list to the other removeFromHand(card); _boardSprites.add(card); // adjust the hand to cover the hole adjustHand(flightDuration, false); } /** * Flies a card from the ether onto the board. * * @param card the card to add to the board * @param src the point to fly the card from * @param dest the point to fly the card to * @param flightDuration the duration of the card's flight * @param fadePortion the amount of time to spend fading in as a * proportion of the flight duration */ public void flyToBoard (Card card, Point src, Point dest, long flightDuration, float fadePortion) { // add it on top of the existing cards CardSprite cs = new CardSprite(this, card); cs.setRenderOrder(getHighestBoardLayer() + 1); cs.setLocation(src.x, src.y); addSprite(cs); _boardSprites.add(cs); // and fly it over LinePath flight = new LinePath(dest, flightDuration); cs.moveAndFadeIn(flight, flightDuration, fadePortion); } /** * Adds a card to the board immediately. * * @param card the card to add to the board * @param dest the point at which to add the card */ public void addToBoard (Card card, Point dest) { CardSprite cs = new CardSprite(this, card); cs.setRenderOrder(getHighestBoardLayer() + 1); cs.setLocation(dest.x, dest.y); addSprite(cs); _boardSprites.add(cs); } /** * Flies a set of cards from the board into the ether. * * @param cards the cards to remove from the board * @param dest the point to fly the cards to * @param flightDuration the duration of the cards' flight * @param fadePortion the amount of time to spend fading out as a * proportion of the flight duration */ public void flyFromBoard (CardSprite[] cards, Point dest, long flightDuration, float fadePortion) { for (int i = 0; i < cards.length; i++) { LinePath flight = new LinePath(dest, flightDuration); cards[i].addSpriteObserver(_pathEndRemover); cards[i].moveAndFadeOut(flight, flightDuration, fadePortion); _boardSprites.remove(cards[i]); } } // documentation inherited protected void paintBehind (Graphics2D gfx, Rectangle dirtyRect) { gfx.setColor(DEFAULT_BACKGROUND); gfx.fill(dirtyRect); super.paintBehind(gfx, dirtyRect); } /** * Flies a set of cards from the board into the ether through an * intermediate point. * * @param cards the cards to remove from the board * @param dest1 the first point to fly the cards to * @param dest2 the final destination of the cards * @param flightDuration the duration of the cards' flight * @param fadePortion the amount of time to spend fading out as a * proportion of the flight duration */ public void flyFromBoard (CardSprite[] cards, Point dest1, Point dest2, long flightDuration, float fadePortion) { for (int i = 0; i < cards.length; i++) { PathSequence flight = new PathSequence( new LinePath(dest1, flightDuration/2), new LinePath(dest1, dest2, flightDuration/2)); cards[i].addSpriteObserver(_pathEndRemover); cards[i].moveAndFadeOut(flight, flightDuration, fadePortion); _boardSprites.remove(cards[i]); } } /** * Returns the first card sprite in the specified list that represents * the specified card, or null if there is no such sprite in the list. */ protected CardSprite getCardSprite (ArrayList list, Card card) { for (int i = 0; i < list.size(); i++) { CardSprite cs = (CardSprite)list.get(i); if (card.equals(cs.getCard())) { return cs; } } return null; } /** * Expands or collapses the hand to accommodate new cards or cover the * space left by removed cards. Skips unmanaged sprites. Clears out * any selected cards. * * @param adjustDuration the amount of time to spend settling the cards * into their new locations * @param updateLayers whether or not to update the layers of the cards */ protected void adjustHand (long adjustDuration, boolean updateLayers) { // clear out selected cards clearHandSelection(); // Sort the hand QuickSort.sort(_handSprites); // Move each card to its proper position (and, optionally, layer) int size = _handSprites.size(); for (int i = 0; i < size; i++) { CardSprite cs = (CardSprite)_handSprites.get(i); if (!isManaged(cs)) { continue; } if (updateLayers) { removeSprite(cs); cs.setRenderOrder(i); addSprite(cs); } LinePath adjust = new LinePath(new Point(getHandX(size, i), _handLocation.y), adjustDuration); cs.move(adjust); } } /** * Removes a card from the hand. */ protected void removeFromHand (CardSprite card) { _selectedHandSprites.remove(card); _handSprites.remove(card); } /** * Updates the offsets of all the cards in the hand. If there is only * one selectable card, that card will always be raised slightly. */ protected void updateHandOffsets () { // make active card sprite is up-to-date updateActiveCardSprite(); int size = _handSprites.size(); for (int i = 0; i < size; i++) { CardSprite cs = (CardSprite)_handSprites.get(i); if (!cs.isMoving()) { cs.setLocation(cs.getX(), getHandY(cs)); } } } /** * Given the location and spacing of the hand, returns the x location of * the card at the specified index within a hand of the specified size. */ protected int getHandX (int size, int idx) { // get the card width from the image if not yet known if (_cardWidth == 0) { _cardWidth = getCardBackImage().getWidth(); } // first compute the width of the entire hand, then use that to // determine the centered location int width = (size - 1) * _handSpacing + _cardWidth; return (_handLocation.x - width/2) + idx * _handSpacing; } /** * Determines the y location of the specified card sprite, given its * selection state. */ protected int getHandY (CardSprite sprite) { if (_selectedHandSprites.contains(sprite)) { return _handLocation.y - _selectedCardOffset; } else if (isSelectable(sprite) && (sprite == _activeCardSprite || isOnlySelectable(sprite))) { return _handLocation.y - _selectableCardOffset; } else { return _handLocation.y; } } /** * Given the current selection mode and predicate, determines if the * specified sprite is selectable. */ protected boolean isSelectable (CardSprite sprite) { return _handSelectionMode != NONE && (_handSelectionPredicate == null || _handSelectionPredicate.evaluate(sprite)); } /** * Determines whether the specified sprite is the only selectable sprite * in the hand according to the selection predicate. */ protected boolean isOnlySelectable (CardSprite sprite) { // if there's no predicate, last remaining card is only selectable if (_handSelectionPredicate == null) { return _handSprites.size() == 1 && _handSprites.contains(sprite); } // otherwise, look for a sprite that fits the predicate and isn't the // parameter int size = _handSprites.size(); for (int i = 0; i < size; i++) { CardSprite cs = (CardSprite)_handSprites.get(i); if (cs != sprite && _handSelectionPredicate.evaluate(cs)) { return false; } } return true; } /** * Lowers all board sprites so that they are rendered at or below the * specified layer. */ protected void lowerBoardSprites (int layer) { // see if they're already lower int highest = getHighestBoardLayer(); if (highest <= layer) { return; } // lower them just enough int size = _boardSprites.size(), adjustment = layer - highest; for (int i = 0; i < size; i++) { CardSprite cs = (CardSprite)_boardSprites.get(i); removeSprite(cs); cs.setRenderOrder(cs.getRenderOrder() + adjustment); addSprite(cs); } } /** * Returns the highest render order of any sprite on the board. */ protected int getHighestBoardLayer () { // must be at least zero, because that's the lowest number we can push // the sprites down to (the layer of the first card in the hand) int size = _boardSprites.size(), highest = 0; for (int i = 0; i < size; i++) { highest = Math.max(highest, ((CardSprite)_boardSprites.get(i)).getRenderOrder()); } return highest; } /** * Clears an array of sprites from the specified list and from the panel. */ protected void clearSprites (ArrayList sprites) { for (Iterator it = sprites.iterator(); it.hasNext(); ) { removeSprite((CardSprite)it.next()); it.remove(); } } /** * Updates the active card sprite based on the location of the mouse * pointer. */ protected void updateActiveCardSprite () { // can't do anything if we don't know where the mouse pointer is if (_mouseEvent == null) { return; } Sprite newHighestHit = _spritemgr.getHighestHitSprite( _mouseEvent.getX(), _mouseEvent.getY()); CardSprite newActiveCardSprite = (newHighestHit instanceof CardSprite ? (CardSprite)newHighestHit : null); if (_activeCardSprite != newActiveCardSprite) { if (_activeCardSprite != null && isManaged(_activeCardSprite)) { _activeCardSprite.queueNotification( new CardSpriteExitedOp(_activeCardSprite, _mouseEvent) ); } _activeCardSprite = newActiveCardSprite; if (_activeCardSprite != null) { _activeCardSprite.queueNotification( new CardSpriteEnteredOp(_activeCardSprite, _mouseEvent) ); } } } /** The width of the playing cards. */ protected int _cardWidth; /** The last motion/entrance/exit event received from the mouse. */ protected MouseEvent _mouseEvent; /** The currently active card sprite (the one that the mouse is over). */ protected CardSprite _activeCardSprite; /** The sprites for cards within the hand. */ protected ArrayList _handSprites = new ArrayList(); /** The sprites for cards within the hand that have been selected. */ protected ArrayList _selectedHandSprites = new ArrayList(); /** The current selection mode for the hand. */ protected int _handSelectionMode; /** The predicate that determines which cards are selectable (if null, all * cards are selectable). */ protected CardSpritePredicate _handSelectionPredicate; /** Observers of hand card selection/deselection. */ protected ObserverList _handSelectionObservers = new ObserverList( ObserverList.FAST_UNSAFE_NOTIFY); /** The location of the center of the hand's upper edge. */ protected Point _handLocation = new Point(); /** The horizontal distance between cards in the hand. */ protected int _handSpacing; /** The vertical distance to offset cards that are selectable. */ protected int _selectableCardOffset; /** The vertical distance to offset cards that are selected. */ protected int _selectedCardOffset; /** The sprites for cards on the board. */ protected ArrayList _boardSprites = new ArrayList(); /** The hand sprite observer instance. */ protected HandSpriteObserver _handSpriteObserver = new HandSpriteObserver(); /** A path observer that removes the sprite at the end of its path. */ protected PathAdapter _pathEndRemover = new PathAdapter() { public void pathCompleted (Sprite sprite, Path path, long when) { removeSprite(sprite); } }; /** Listens for interactions with cards in hand. */ protected class HandSpriteObserver extends PathAdapter implements CardSpriteObserver { public void pathCompleted (Sprite sprite, Path path, long when) { updateActiveCardSprite(); maybeUpdateOffset((CardSprite)sprite); } public void cardSpriteClicked (CardSprite sprite, MouseEvent me) { // select, deselect, or play card in hand if (_selectedHandSprites.contains(sprite) && _handSelectionMode != NONE) { deselectHandSprite(sprite); } else if (_handSprites.contains(sprite) && isSelectable(sprite)) { selectHandSprite(sprite); } } public void cardSpriteEntered (CardSprite sprite, MouseEvent me) { maybeUpdateOffset(sprite); } public void cardSpriteExited (CardSprite sprite, MouseEvent me) { maybeUpdateOffset(sprite); } public void cardSpriteDragged (CardSprite sprite, MouseEvent me) {} protected void maybeUpdateOffset (CardSprite sprite) { // update the offset if it's in the hand and isn't moving if (_handSprites.contains(sprite) && !sprite.isMoving()) { sprite.setLocation(sprite.getX(), getHandY(sprite)); } } }; /** Listens for mouse interactions with cards. */ protected class CardListener extends MouseInputAdapter { public void mousePressed (MouseEvent me) { if (_activeCardSprite != null && isManaged(_activeCardSprite)) { _handleX = _activeCardSprite.getX() - me.getX(); _handleY = _activeCardSprite.getY() - me.getY(); _hasBeenDragged = false; } } public void mouseReleased (MouseEvent me) { if (_activeCardSprite != null && isManaged(_activeCardSprite) && _hasBeenDragged) { _activeCardSprite.queueNotification( new CardSpriteDraggedOp(_activeCardSprite, me) ); } } public void mouseClicked (MouseEvent me) { if (_activeCardSprite != null && isManaged(_activeCardSprite)) { _activeCardSprite.queueNotification( new CardSpriteClickedOp(_activeCardSprite, me) ); } } public void mouseMoved (MouseEvent me) { _mouseEvent = me; updateActiveCardSprite(); } public void mouseDragged (MouseEvent me) { _mouseEvent = me; if (_activeCardSprite != null && isManaged(_activeCardSprite) && _activeCardSprite.isDraggable()) { _activeCardSprite.setLocation( me.getX() + _handleX, me.getY() + _handleY ); _hasBeenDragged = true; } else { updateActiveCardSprite(); } } public void mouseEntered (MouseEvent me) { _mouseEvent = me; } public void mouseExited (MouseEvent me) { _mouseEvent = me; } protected int _handleX, _handleY; protected boolean _hasBeenDragged; } /** Calls CardSpriteObserver.cardSpriteClicked. */ protected static class CardSpriteClickedOp implements ObserverList.ObserverOp { public CardSpriteClickedOp (CardSprite sprite, MouseEvent me) { _sprite = sprite; _me = me; } public boolean apply (Object observer) { if (observer instanceof CardSpriteObserver) { ((CardSpriteObserver)observer).cardSpriteClicked(_sprite, _me); } return true; } protected CardSprite _sprite; protected MouseEvent _me; } /** Calls CardSpriteObserver.cardSpriteEntered. */ protected static class CardSpriteEnteredOp implements ObserverList.ObserverOp { public CardSpriteEnteredOp (CardSprite sprite, MouseEvent me) { _sprite = sprite; _me = me; } public boolean apply (Object observer) { if (observer instanceof CardSpriteObserver) { ((CardSpriteObserver)observer).cardSpriteEntered(_sprite, _me); } return true; } protected CardSprite _sprite; protected MouseEvent _me; } /** Calls CardSpriteObserver.cardSpriteExited. */ protected static class CardSpriteExitedOp implements ObserverList.ObserverOp { public CardSpriteExitedOp (CardSprite sprite, MouseEvent me) { _sprite = sprite; _me = me; } public boolean apply (Object observer) { if (observer instanceof CardSpriteObserver) { ((CardSpriteObserver)observer).cardSpriteExited(_sprite, _me); } return true; } protected CardSprite _sprite; protected MouseEvent _me; } /** Calls CardSpriteObserver.cardSpriteDragged. */ protected static class CardSpriteDraggedOp implements ObserverList.ObserverOp { public CardSpriteDraggedOp (CardSprite sprite, MouseEvent me) { _sprite = sprite; _me = me; } public boolean apply (Object observer) { if (observer instanceof CardSpriteObserver) { ((CardSpriteObserver)observer).cardSpriteDragged(_sprite, _me); } return true; } protected CardSprite _sprite; protected MouseEvent _me; } /** A nice default green card table background color. */ protected static Color DEFAULT_BACKGROUND = new Color(0x326D36); }
src/java/com/threerings/parlor/card/client/CardPanel.java
// // $Id$ // // Narya library - tools for developing networked games // Copyright (C) 2002-2004 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/narya/ // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.parlor.card.client; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.Iterator; import javax.swing.event.MouseInputAdapter; import com.samskivert.util.ObserverList; import com.samskivert.util.QuickSort; import com.threerings.media.FrameManager; import com.threerings.media.VirtualMediaPanel; import com.threerings.media.image.Mirage; import com.threerings.media.sprite.PathAdapter; import com.threerings.media.sprite.Sprite; import com.threerings.media.util.LinePath; import com.threerings.media.util.Path; import com.threerings.media.util.PathSequence; import com.threerings.media.util.Pathable; import com.threerings.parlor.card.Log; import com.threerings.parlor.card.data.Card; import com.threerings.parlor.card.data.CardCodes; import com.threerings.parlor.card.data.Deck; import com.threerings.parlor.card.data.Hand; /** * Extends VirtualMediaPanel to provide services specific to rendering * and manipulating playing cards. */ public abstract class CardPanel extends VirtualMediaPanel implements CardCodes { /** The selection mode in which cards are not selectable. */ public static final int NONE = 0; /** The selection mode in which the user can play a single card. */ public static final int PLAY_SINGLE = 1; /** The selection mode in which the user can select a single card. */ public static final int SELECT_SINGLE = 2; /** The selection mode in which the user can select multiple cards. */ public static final int SELECT_MULTIPLE = 3; /** * A predicate class for {@link CardSprite}s. Provides control over which * cards are selectable, playable, etc. */ public static interface CardSpritePredicate { /** * Evaluates the specified sprite. */ public boolean evaluate (CardSprite sprite); } /** * A listener for card selection/deselection. */ public static interface CardSelectionObserver { /** * Called when a card has been played. */ public void cardSpritePlayed (CardSprite sprite); /** * Called when a card has been selected. */ public void cardSpriteSelected (CardSprite sprite); /** * Called when a card has been deselected. */ public void cardSpriteDeselected (CardSprite sprite); } /** * Constructor. * * @param frameManager the frame manager */ public CardPanel (FrameManager frameManager) { super(frameManager); // add a listener for mouse events CardListener cl = new CardListener(); addMouseListener(cl); addMouseMotionListener(cl); } /** * Returns the full-sized image for the back of a playing card. */ public abstract Mirage getCardBackImage (); /** * Returns the full-sized image for the front of the specified card. */ public abstract Mirage getCardImage (Card card); /** * Returns the small-sized image for the back of a playing card. */ public abstract Mirage getMicroCardBackImage (); /** * Returns the small-sized image for the front of the specified card. */ public abstract Mirage getMicroCardImage (Card card); /** * Sets the location of the hand (the location of the center of the hand's * upper edge). */ public void setHandLocation (int x, int y) { _handLocation.setLocation(x, y); } /** * Sets the horizontal spacing between cards in the hand. */ public void setHandSpacing (int spacing) { _handSpacing = spacing; } /** * Sets the vertical distance to offset cards that are selectable or * playable. */ public void setSelectableCardOffset (int offset) { _selectableCardOffset = offset; } /** * Sets the vertical distance to offset cards that are selected. */ public void setSelectedCardOffset (int offset) { _selectedCardOffset = offset; } /** * Sets the selection mode for the hand (NONE, PLAY_SINGLE, SELECT_SINGLE, * or SELECT_MULTIPLE). Changing the selection mode does not change the * current selection. */ public void setHandSelectionMode (int mode) { _handSelectionMode = mode; // update the offsets of all cards in the hand updateHandOffsets(); } /** * Sets the selection predicate that determines which cards from the hand * may be selected (if null, all cards may be selected). Changing the * predicate does not change the current selection. */ public void setHandSelectionPredicate (CardSpritePredicate pred) { _handSelectionPredicate = pred; // update the offsets of all cards in the hand updateHandOffsets(); } /** * Returns the currently selected hand sprite (null if no sprites are * selected, the first sprite if multiple sprites are selected). */ public CardSprite getSelectedHandSprite () { return _selectedHandSprites.size() == 0 ? null : (CardSprite)_selectedHandSprites.get(0); } /** * Returns an array containing the currently selected hand sprites * (returns an empty array if no sprites are selected). */ public CardSprite[] getSelectedHandSprites () { return (CardSprite[])_selectedHandSprites.toArray( new CardSprite[_selectedHandSprites.size()]); } /** * Programmatically plays a sprite in the hand. */ public void playHandSprite (final CardSprite sprite) { // notify the observers ObserverList.ObserverOp op = new ObserverList.ObserverOp() { public boolean apply (Object obs) { ((CardSelectionObserver)obs).cardSpritePlayed(sprite); return true; } }; _handSelectionObservers.apply(op); } /** * Programmatically selects a sprite in the hand. */ public void selectHandSprite (final CardSprite sprite) { // make sure it's not already selected if (_selectedHandSprites.contains(sprite)) { return; } // if in single card mode and there's another card selected, // deselect it if (_handSelectionMode == SELECT_SINGLE) { CardSprite oldSprite = getSelectedHandSprite(); if (oldSprite != null) { deselectHandSprite(oldSprite); } } // add to list and update offset _selectedHandSprites.add(sprite); sprite.setLocation(sprite.getX(), getHandY(sprite)); // notify the observers ObserverList.ObserverOp op = new ObserverList.ObserverOp() { public boolean apply (Object obs) { ((CardSelectionObserver)obs).cardSpriteSelected(sprite); return true; } }; _handSelectionObservers.apply(op); } /** * Programmatically deselects a sprite in the hand. */ public void deselectHandSprite (final CardSprite sprite) { // make sure it's selected if (!_selectedHandSprites.contains(sprite)) { return; } // remove from list and update offset _selectedHandSprites.remove(sprite); sprite.setLocation(sprite.getX(), getHandY(sprite)); // notify the observers ObserverList.ObserverOp op = new ObserverList.ObserverOp() { public boolean apply (Object obs) { ((CardSelectionObserver)obs).cardSpriteDeselected(sprite); return true; } }; _handSelectionObservers.apply(op); } /** * Clears any existing hand sprite selection. */ public void clearHandSelection () { CardSprite[] sprites = getSelectedHandSprites(); for (int i = 0; i < sprites.length; i++) { deselectHandSprite(sprites[i]); } } /** * Adds an object to the list of observers to notify when cards in the * hand are selected/deselected. */ public void addHandSelectionObserver (CardSelectionObserver obs) { _handSelectionObservers.add(obs); } /** * Removes an object from the hand selection observer list. */ public void removeHandSelectionObserver (CardSelectionObserver obs) { _handSelectionObservers.remove(obs); } /** * Fades a hand of cards in. * * @param hand the hand of cards * @param fadeDuration the amount of time to spend fading in * the entire hand */ public void setHand (Hand hand, long fadeDuration) { // make sure no cards are hanging around clearHand(); // create the sprites int size = hand.size(); for (int i = 0; i < size; i++) { CardSprite cs = new CardSprite(this, (Card)hand.get(i)); _handSprites.add(cs); } // sort them QuickSort.sort(_handSprites); // fade them in at proper locations and layers long cardDuration = fadeDuration / size; for (int i = 0; i < size; i++) { CardSprite cs = (CardSprite)_handSprites.get(i); cs.setLocation(getHandX(size, i), _handLocation.y); cs.setRenderOrder(i); cs.addSpriteObserver(_handSpriteObserver); addSprite(cs); cs.fadeIn(i * cardDuration, cardDuration); } // make sure we have the right card sprite active updateActiveCardSprite(); } /** * Fades a hand of cards in face-down. * * @param size the size of the hand * @param fadeDuration the amount of time to spend fading in * each card */ public void setHand (int size, long fadeDuration) { // fill hand will null entries to signify unknown cards Hand hand = new Hand(); for (int i = 0; i < size; i++) { hand.add(null); } setHand(hand, fadeDuration); } /** * Shows a hand that was previous set face-down. * * @param hand the hand of cards */ public void showHand (Hand hand) { // sort the hand QuickSort.sort(hand); // set the sprites int len = Math.min(_handSprites.size(), hand.size()); for (int i = 0; i < len; i++) { CardSprite cs = (CardSprite)_handSprites.get(i); cs.setCard((Card)hand.get(i)); } } /** * Returns the first sprite in the hand that corresponds to the * specified card, or null if the card is not in the hand. */ public CardSprite getHandSprite (Card card) { return getCardSprite(_handSprites, card); } /** * Clears all cards from the hand. */ public void clearHand () { clearHandSelection(); clearSprites(_handSprites); } /** * Clears all cards from the board. */ public void clearBoard () { clearSprites(_boardSprites); } /** * Flies a set of cards from the hand into the ether. Clears any selected * cards. * * @param cards the card sprites to remove from the hand * @param dest the point to fly the cards to * @param flightDuration the duration of the cards' flight * @param fadePortion the amount of time to spend fading out * as a proportion of the flight duration */ public void flyFromHand (CardSprite[] cards, Point dest, long flightDuration, float fadePortion) { // fly each sprite over, removing it from the hand immediately and // from the board when it finishes its path for (int i = 0; i < cards.length; i++) { removeFromHand(cards[i]); LinePath flight = new LinePath(dest, flightDuration); cards[i].addSpriteObserver(_pathEndRemover); cards[i].moveAndFadeOut(flight, flightDuration, fadePortion); } // adjust the hand to cover the hole adjustHand(flightDuration, false); } /** * Flies a set of cards from the ether into the hand. Clears any selected * cards. The cards will first fly to the selected card offset, pause for * the specified duration, and then drop into the hand. * * @param cards the cards to add to the hand * @param src the point to fly the cards from * @param flightDuration the duration of the cards' flight * @param pauseDuration the duration of the pause before dropping into the * hand * @param dropDuration the duration of the cards' drop into the * hand * @param fadePortion the amount of time to spend fading in * as a proportion of the flight duration */ public void flyIntoHand (Card[] cards, Point src, long flightDuration, long pauseDuration, long dropDuration, float fadePortion) { // first create the sprites and add them to the list CardSprite[] sprites = new CardSprite[cards.length]; for (int i = 0; i < cards.length; i++) { sprites[i] = new CardSprite(this, cards[i]); _handSprites.add(sprites[i]); } // settle the hand adjustHand(flightDuration, true); // then set the layers and fly the cards in int size = _handSprites.size(); for (int i = 0; i < sprites.length; i++) { int idx = _handSprites.indexOf(sprites[i]); sprites[i].setLocation(src.x, src.y); sprites[i].setRenderOrder(idx); sprites[i].addSpriteObserver(_handSpriteObserver); addSprite(sprites[i]); // create a path sequence containing flight, pause, and drop ArrayList paths = new ArrayList(); Point hp2 = new Point(getHandX(size, idx), _handLocation.y), hp1 = new Point(hp2.x, hp2.y - _selectedCardOffset); paths.add(new LinePath(hp1, flightDuration)); paths.add(new LinePath(hp1, pauseDuration)); paths.add(new LinePath(hp2, dropDuration)); sprites[i].moveAndFadeIn(new PathSequence(paths), flightDuration + pauseDuration + dropDuration, fadePortion); } } /** * Flies a set of cards from the ether into the ether. * * @param cards the cards to fly across * @param src the point to fly the cards from * @param dest the point to fly the cards to * @param flightDuration the duration of the cards' flight * @param cardDelay the amount of time to wait between cards * @param fadePortion the amount of time to spend fading in and out * as a proportion of the flight duration */ public void flyAcross (Card[] cards, Point src, Point dest, long flightDuration, long cardDelay, float fadePortion) { for (int i = 0; i < cards.length; i++) { // add on top of all board sprites CardSprite cs = new CardSprite(this, cards[i]); cs.setRenderOrder(getHighestBoardLayer() + 1 + i); cs.setLocation(src.x, src.y); addSprite(cs); // prepend an initial delay to all cards after the first Path path; long pathDuration; LinePath flight = new LinePath(dest, flightDuration); if (i > 0) { long delayDuration = cardDelay * i; LinePath delay = new LinePath(src, delayDuration); path = new PathSequence(delay, flight); pathDuration = delayDuration + flightDuration; } else { path = flight; pathDuration = flightDuration; } cs.addSpriteObserver(_pathEndRemover); cs.moveAndFadeInAndOut(path, pathDuration, fadePortion); } } /** * Flies a set of cards from the ether into the ether face-down. * * @param number the number of cards to fly across * @param src the point to fly the cards from * @param dest the point to fly the cards to * @param flightDuration the duration of the cards' flight * @param cardDelay the amount of time to wait between cards * @param fadePortion the amount of time to spend fading in and out * as a proportion of the flight duration */ public void flyAcross (int number, Point src, Point dest, long flightDuration, long cardDelay, float fadePortion) { // use null values to signify unknown cards flyAcross(new Card[number], src, dest, flightDuration, cardDelay, fadePortion); } /** * Flies a card from the hand onto the board. Clears any cards selected. * * @param card the sprite to remove from the hand * @param dest the point to fly the card to * @param flightDuration the duration of the card's flight */ public void flyFromHandToBoard (CardSprite card, Point dest, long flightDuration) { // fly it over LinePath flight = new LinePath(dest, flightDuration); card.move(flight); // lower the board so that the card from hand is on top lowerBoardSprites(card.getRenderOrder() - 1); // move from one list to the other removeFromHand(card); _boardSprites.add(card); // adjust the hand to cover the hole adjustHand(flightDuration, false); } /** * Flies a card from the ether onto the board. * * @param card the card to add to the board * @param src the point to fly the card from * @param dest the point to fly the card to * @param flightDuration the duration of the card's flight * @param fadePortion the amount of time to spend fading in as a * proportion of the flight duration */ public void flyToBoard (Card card, Point src, Point dest, long flightDuration, float fadePortion) { // add it on top of the existing cards CardSprite cs = new CardSprite(this, card); cs.setRenderOrder(getHighestBoardLayer() + 1); cs.setLocation(src.x, src.y); addSprite(cs); _boardSprites.add(cs); // and fly it over LinePath flight = new LinePath(dest, flightDuration); cs.moveAndFadeIn(flight, flightDuration, fadePortion); } /** * Adds a card to the board immediately. * * @param card the card to add to the board * @param dest the point at which to add the card */ public void addToBoard (Card card, Point dest) { CardSprite cs = new CardSprite(this, card); cs.setRenderOrder(getHighestBoardLayer() + 1); cs.setLocation(dest.x, dest.y); addSprite(cs); _boardSprites.add(cs); } /** * Flies a set of cards from the board into the ether. * * @param cards the cards to remove from the board * @param dest the point to fly the cards to * @param flightDuration the duration of the cards' flight * @param fadePortion the amount of time to spend fading out as a * proportion of the flight duration */ public void flyFromBoard (CardSprite[] cards, Point dest, long flightDuration, float fadePortion) { for (int i = 0; i < cards.length; i++) { LinePath flight = new LinePath(dest, flightDuration); cards[i].addSpriteObserver(_pathEndRemover); cards[i].moveAndFadeOut(flight, flightDuration, fadePortion); _boardSprites.remove(cards[i]); } } // documentation inherited protected void paintBehind (Graphics2D gfx, Rectangle dirtyRect) { gfx.setColor(DEFAULT_BACKGROUND); gfx.fill(dirtyRect); super.paintBehind(gfx, dirtyRect); } /** * Flies a set of cards from the board into the ether through an * intermediate point. * * @param cards the cards to remove from the board * @param dest1 the first point to fly the cards to * @param dest2 the final destination of the cards * @param flightDuration the duration of the cards' flight * @param fadePortion the amount of time to spend fading out as a * proportion of the flight duration */ public void flyFromBoard (CardSprite[] cards, Point dest1, Point dest2, long flightDuration, float fadePortion) { for (int i = 0; i < cards.length; i++) { PathSequence flight = new PathSequence( new LinePath(dest1, flightDuration/2), new LinePath(dest1, dest2, flightDuration/2)); cards[i].addSpriteObserver(_pathEndRemover); cards[i].moveAndFadeOut(flight, flightDuration, fadePortion); _boardSprites.remove(cards[i]); } } /** * Returns the first card sprite in the specified list that represents * the specified card, or null if there is no such sprite in the list. */ protected CardSprite getCardSprite (ArrayList list, Card card) { for (int i = 0; i < list.size(); i++) { CardSprite cs = (CardSprite)list.get(i); if (card.equals(cs.getCard())) { return cs; } } return null; } /** * Expands or collapses the hand to accommodate new cards or cover the * space left by removed cards. Skips unmanaged sprites. Clears out * any selected cards. * * @param adjustDuration the amount of time to spend settling the cards * into their new locations * @param updateLayers whether or not to update the layers of the cards */ protected void adjustHand (long adjustDuration, boolean updateLayers) { // clear out selected cards clearHandSelection(); // Sort the hand QuickSort.sort(_handSprites); // Move each card to its proper position (and, optionally, layer) int size = _handSprites.size(); for (int i = 0; i < size; i++) { CardSprite cs = (CardSprite)_handSprites.get(i); if (!isManaged(cs)) { continue; } if (updateLayers) { removeSprite(cs); cs.setRenderOrder(i); addSprite(cs); } LinePath adjust = new LinePath(new Point(getHandX(size, i), _handLocation.y), adjustDuration); cs.move(adjust); } } /** * Removes a card from the hand. */ protected void removeFromHand (CardSprite card) { _selectedHandSprites.remove(card); _handSprites.remove(card); } /** * Updates the offsets of all the cards in the hand. If there is only * one selectable card, that card will always be raised slightly. */ protected void updateHandOffsets () { // make active card sprite is up-to-date updateActiveCardSprite(); int size = _handSprites.size(); for (int i = 0; i < size; i++) { CardSprite cs = (CardSprite)_handSprites.get(i); if (!cs.isMoving()) { cs.setLocation(cs.getX(), getHandY(cs)); } } } /** * Given the location and spacing of the hand, returns the x location of * the card at the specified index within a hand of the specified size. */ protected int getHandX (int size, int idx) { // get the card width from the image if not yet known if (_cardWidth == 0) { _cardWidth = getCardBackImage().getWidth(); } // first compute the width of the entire hand, then use that to // determine the centered location int width = (size - 1) * _handSpacing + _cardWidth; return (_handLocation.x - width/2) + idx * _handSpacing; } /** * Determines the y location of the specified card sprite, given its * selection state. */ protected int getHandY (CardSprite sprite) { if (_selectedHandSprites.contains(sprite)) { return _handLocation.y - _selectedCardOffset; } else if (isSelectable(sprite) && (sprite == _activeCardSprite || isOnlySelectable(sprite))) { return _handLocation.y - _selectableCardOffset; } else { return _handLocation.y; } } /** * Given the current selection mode and predicate, determines if the * specified sprite is selectable. */ protected boolean isSelectable (CardSprite sprite) { return _handSelectionMode != NONE && (_handSelectionPredicate == null || _handSelectionPredicate.evaluate(sprite)); } /** * Determines whether the specified sprite is the only selectable sprite * in the hand according to the selection predicate. */ protected boolean isOnlySelectable (CardSprite sprite) { // if there's no predicate, last remaining card is only selectable if (_handSelectionPredicate == null) { return _handSprites.size() == 1 && _handSprites.contains(sprite); } // otherwise, look for a sprite that fits the predicate and isn't the // parameter int size = _handSprites.size(); for (int i = 0; i < size; i++) { CardSprite cs = (CardSprite)_handSprites.get(i); if (cs != sprite && _handSelectionPredicate.evaluate(cs)) { return false; } } return true; } /** * Lowers all board sprites so that they are rendered at or below the * specified layer. */ protected void lowerBoardSprites (int layer) { // see if they're already lower int highest = getHighestBoardLayer(); if (highest <= layer) { return; } // lower them just enough int size = _boardSprites.size(), adjustment = layer - highest; for (int i = 0; i < size; i++) { CardSprite cs = (CardSprite)_boardSprites.get(i); removeSprite(cs); cs.setRenderOrder(cs.getRenderOrder() + adjustment); addSprite(cs); } } /** * Returns the highest render order of any sprite on the board. */ protected int getHighestBoardLayer () { // must be at least zero, because that's the lowest number we can push // the sprites down to (the layer of the first card in the hand) int size = _boardSprites.size(), highest = 0; for (int i = 0; i < size; i++) { highest = Math.max(highest, ((CardSprite)_boardSprites.get(i)).getRenderOrder()); } return highest; } /** * Clears an array of sprites from the specified list and from the panel. */ protected void clearSprites (ArrayList sprites) { for (Iterator it = sprites.iterator(); it.hasNext(); ) { removeSprite((CardSprite)it.next()); it.remove(); } } /** * Updates the active card sprite based on the location of the mouse * pointer. */ protected void updateActiveCardSprite () { // can't do anything if we don't know where the mouse pointer is if (_mouseEvent == null) { return; } Sprite newHighestHit = _spritemgr.getHighestHitSprite( _mouseEvent.getX(), _mouseEvent.getY()); CardSprite newActiveCardSprite = (newHighestHit instanceof CardSprite ? (CardSprite)newHighestHit : null); if (_activeCardSprite != newActiveCardSprite) { if (_activeCardSprite != null && isManaged(_activeCardSprite)) { _activeCardSprite.queueNotification( new CardSpriteExitedOp(_activeCardSprite, _mouseEvent) ); } _activeCardSprite = newActiveCardSprite; if (_activeCardSprite != null) { _activeCardSprite.queueNotification( new CardSpriteEnteredOp(_activeCardSprite, _mouseEvent) ); } } } /** The width of the playing cards. */ protected int _cardWidth; /** The last motion/entrance/exit event received from the mouse. */ protected MouseEvent _mouseEvent; /** The currently active card sprite (the one that the mouse is over). */ protected CardSprite _activeCardSprite; /** The sprites for cards within the hand. */ protected ArrayList _handSprites = new ArrayList(); /** The sprites for cards within the hand that have been selected. */ protected ArrayList _selectedHandSprites = new ArrayList(); /** The current selection mode for the hand. */ protected int _handSelectionMode; /** The predicate that determines which cards are selectable (if null, all * cards are selectable). */ protected CardSpritePredicate _handSelectionPredicate; /** Observers of hand card selection/deselection. */ protected ObserverList _handSelectionObservers = new ObserverList( ObserverList.FAST_UNSAFE_NOTIFY); /** The location of the center of the hand's upper edge. */ protected Point _handLocation = new Point(); /** The horizontal distance between cards in the hand. */ protected int _handSpacing; /** The vertical distance to offset cards that are selectable. */ protected int _selectableCardOffset; /** The vertical distance to offset cards that are selected. */ protected int _selectedCardOffset; /** The sprites for cards on the board. */ protected ArrayList _boardSprites = new ArrayList(); /** The hand sprite observer instance. */ protected HandSpriteObserver _handSpriteObserver = new HandSpriteObserver(); /** A path observer that removes the sprite at the end of its path. */ protected PathAdapter _pathEndRemover = new PathAdapter() { public void pathCompleted (Sprite sprite, Path path, long when) { removeSprite(sprite); } }; /** Listens for interactions with cards in hand. */ protected class HandSpriteObserver extends PathAdapter implements CardSpriteObserver { public void pathCompleted (Sprite sprite, Path path, long when) { updateActiveCardSprite(); maybeUpdateOffset((CardSprite)sprite); } public void cardSpriteClicked (CardSprite sprite, MouseEvent me) { // select, deselect, or play card in hand if (_selectedHandSprites.contains(sprite) && _handSelectionMode != NONE) { deselectHandSprite(sprite); } else if (_handSprites.contains(sprite) && isSelectable(sprite)) { if (_handSelectionMode == PLAY_SINGLE) { playHandSprite(sprite); } else { selectHandSprite(sprite); } } } public void cardSpriteEntered (CardSprite sprite, MouseEvent me) { maybeUpdateOffset(sprite); } public void cardSpriteExited (CardSprite sprite, MouseEvent me) { maybeUpdateOffset(sprite); } public void cardSpriteDragged (CardSprite sprite, MouseEvent me) {} protected void maybeUpdateOffset (CardSprite sprite) { // update the offset if it's in the hand and isn't moving if (_handSprites.contains(sprite) && !sprite.isMoving()) { sprite.setLocation(sprite.getX(), getHandY(sprite)); } } }; /** Listens for mouse interactions with cards. */ protected class CardListener extends MouseInputAdapter { public void mousePressed (MouseEvent me) { if (_activeCardSprite != null && isManaged(_activeCardSprite)) { _handleX = _activeCardSprite.getX() - me.getX(); _handleY = _activeCardSprite.getY() - me.getY(); _hasBeenDragged = false; } } public void mouseReleased (MouseEvent me) { if (_activeCardSprite != null && isManaged(_activeCardSprite) && _hasBeenDragged) { _activeCardSprite.queueNotification( new CardSpriteDraggedOp(_activeCardSprite, me) ); } } public void mouseClicked (MouseEvent me) { if (_activeCardSprite != null && isManaged(_activeCardSprite)) { _activeCardSprite.queueNotification( new CardSpriteClickedOp(_activeCardSprite, me) ); } } public void mouseMoved (MouseEvent me) { _mouseEvent = me; updateActiveCardSprite(); } public void mouseDragged (MouseEvent me) { _mouseEvent = me; if (_activeCardSprite != null && isManaged(_activeCardSprite) && _activeCardSprite.isDraggable()) { _activeCardSprite.setLocation( me.getX() + _handleX, me.getY() + _handleY ); _hasBeenDragged = true; } else { updateActiveCardSprite(); } } public void mouseEntered (MouseEvent me) { _mouseEvent = me; } public void mouseExited (MouseEvent me) { _mouseEvent = me; } protected int _handleX, _handleY; protected boolean _hasBeenDragged; } /** Calls CardSpriteObserver.cardSpriteClicked. */ protected static class CardSpriteClickedOp implements ObserverList.ObserverOp { public CardSpriteClickedOp (CardSprite sprite, MouseEvent me) { _sprite = sprite; _me = me; } public boolean apply (Object observer) { if (observer instanceof CardSpriteObserver) { ((CardSpriteObserver)observer).cardSpriteClicked(_sprite, _me); } return true; } protected CardSprite _sprite; protected MouseEvent _me; } /** Calls CardSpriteObserver.cardSpriteEntered. */ protected static class CardSpriteEnteredOp implements ObserverList.ObserverOp { public CardSpriteEnteredOp (CardSprite sprite, MouseEvent me) { _sprite = sprite; _me = me; } public boolean apply (Object observer) { if (observer instanceof CardSpriteObserver) { ((CardSpriteObserver)observer).cardSpriteEntered(_sprite, _me); } return true; } protected CardSprite _sprite; protected MouseEvent _me; } /** Calls CardSpriteObserver.cardSpriteExited. */ protected static class CardSpriteExitedOp implements ObserverList.ObserverOp { public CardSpriteExitedOp (CardSprite sprite, MouseEvent me) { _sprite = sprite; _me = me; } public boolean apply (Object observer) { if (observer instanceof CardSpriteObserver) { ((CardSpriteObserver)observer).cardSpriteExited(_sprite, _me); } return true; } protected CardSprite _sprite; protected MouseEvent _me; } /** Calls CardSpriteObserver.cardSpriteDragged. */ protected static class CardSpriteDraggedOp implements ObserverList.ObserverOp { public CardSpriteDraggedOp (CardSprite sprite, MouseEvent me) { _sprite = sprite; _me = me; } public boolean apply (Object observer) { if (observer instanceof CardSpriteObserver) { ((CardSpriteObserver)observer).cardSpriteDragged(_sprite, _me); } return true; } protected CardSprite _sprite; protected MouseEvent _me; } /** A nice default green card table background color. */ protected static Color DEFAULT_BACKGROUND = new Color(0x326D36); }
Eliminated the hacky "play card" selection mode, since it's no longer necessary. git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@3537 542714f4-19e9-0310-aa3c-eee0fc999fb1
src/java/com/threerings/parlor/card/client/CardPanel.java
Eliminated the hacky "play card" selection mode, since it's no longer necessary.
<ide><path>rc/java/com/threerings/parlor/card/client/CardPanel.java <ide> /** The selection mode in which cards are not selectable. */ <ide> public static final int NONE = 0; <ide> <del> /** The selection mode in which the user can play a single card. */ <del> public static final int PLAY_SINGLE = 1; <del> <ide> /** The selection mode in which the user can select a single card. */ <del> public static final int SELECT_SINGLE = 2; <add> public static final int SINGLE = 2; <ide> <ide> /** The selection mode in which the user can select multiple cards. */ <del> public static final int SELECT_MULTIPLE = 3; <add> public static final int MULTIPLE = 3; <ide> <ide> /** <ide> * A predicate class for {@link CardSprite}s. Provides control over which <ide> public static interface CardSelectionObserver <ide> { <ide> /** <del> * Called when a card has been played. <del> */ <del> public void cardSpritePlayed (CardSprite sprite); <del> <del> /** <ide> * Called when a card has been selected. <ide> */ <ide> public void cardSpriteSelected (CardSprite sprite); <ide> } <ide> <ide> /** <del> * Sets the selection mode for the hand (NONE, PLAY_SINGLE, SELECT_SINGLE, <del> * or SELECT_MULTIPLE). Changing the selection mode does not change the <add> * Sets the selection mode for the hand (NONE, PLAY_SINGLE, SINGLE, <add> * or MULTIPLE). Changing the selection mode does not change the <ide> * current selection. <ide> */ <ide> public void setHandSelectionMode (int mode) <ide> } <ide> <ide> /** <del> * Programmatically plays a sprite in the hand. <del> */ <del> public void playHandSprite (final CardSprite sprite) <del> { <del> // notify the observers <del> ObserverList.ObserverOp op = new ObserverList.ObserverOp() { <del> public boolean apply (Object obs) { <del> ((CardSelectionObserver)obs).cardSpritePlayed(sprite); <del> return true; <del> } <del> }; <del> _handSelectionObservers.apply(op); <del> } <del> <del> /** <ide> * Programmatically selects a sprite in the hand. <ide> */ <ide> public void selectHandSprite (final CardSprite sprite) <ide> <ide> // if in single card mode and there's another card selected, <ide> // deselect it <del> if (_handSelectionMode == SELECT_SINGLE) { <add> if (_handSelectionMode == SINGLE) { <ide> CardSprite oldSprite = getSelectedHandSprite(); <ide> if (oldSprite != null) { <ide> deselectHandSprite(oldSprite); <ide> deselectHandSprite(sprite); <ide> <ide> } else if (_handSprites.contains(sprite) && isSelectable(sprite)) { <del> if (_handSelectionMode == PLAY_SINGLE) { <del> playHandSprite(sprite); <del> <del> } else { <del> selectHandSprite(sprite); <del> } <add> selectHandSprite(sprite); <ide> } <ide> } <ide>
JavaScript
mit
cc59c955c75ee59488b71400c53b26e00780d838
0
TryGhost/Ignition
var uuid = require('uuid'), util = require('util'), each = require('lodash/each'), utils = require('./utils'), merge = require('lodash/merge'), isString = require('lodash/isString'); function IgnitionError(options) { options = options || {}; var self = this; if (isString(options)) { throw new Error('Please instantiate Errors with the option pattern. e.g. new errors.IgnitionError({message: ...})'); } Error.call(this); Error.captureStackTrace(this, IgnitionError); /** * defaults */ this.statusCode = 500; this.errorType = 'InternalServerError'; this.level = 'normal'; this.message = 'The server has encountered an error.'; this.id = uuid.v1(); /** * custom overrides */ this.id = options.id || this.id; this.statusCode = options.statusCode || this.statusCode; this.level = options.level || this.level; this.context = options.context || this.context; this.help = options.help || this.help; this.errorType = this.name = options.errorType || this.errorType; this.errorDetails = options.errorDetails; this.code = options.code || null; this.property = options.property || null; this.redirect = options.redirect || null; this.message = options.message || this.message; this.hideStack = options.hideStack; // error to inherit from, override! // nested objects are getting copied over in one piece (can be changed, but not needed right now) // support err as string (it happens that third party libs return a string instead of an error instance) if (options.err) { if (isString(options.err)) { options.err = new Error(options.err); } Object.getOwnPropertyNames(options.err).forEach(function (property) { if (['errorType', 'name', 'statusCode', 'message', 'level'].indexOf(property) !== -1) { return; } // CASE: `code` should put options as priority over err if (property === 'code') { self[property] = self[property] || options.err[property]; } if (property === 'stack') { self[property] += '\n\n' + options.err[property]; return; } self[property] = options.err[property] || self[property]; }); } } // jscs:disable var errors = { InternalServerError: function InternalServerError(options) { IgnitionError.call(this, merge({ statusCode: 500, level: 'critical', errorType: 'InternalServerError', message: 'The server has encountered an error.' }, options)); }, IncorrectUsageError: function IncorrectUsageError(options) { IgnitionError.call(this, merge({ statusCode: 400, level: 'critical', errorType: 'IncorrectUsageError', message: 'We detected a misuse. Please read the stack trace.' }, options)); }, NotFoundError: function NotFoundError(options) { IgnitionError.call(this, merge({ statusCode: 404, errorType: 'NotFoundError', message: 'Resource could not be found.' }, options)); }, BadRequestError: function BadRequestError(options) { IgnitionError.call(this, merge({ statusCode: 400, errorType: 'BadRequestError', message: 'The request could not be understood.' }, options)); }, UnauthorizedError: function UnauthorizedError(options) { IgnitionError.call(this, merge({ statusCode: 401, errorType: 'UnauthorizedError', message: 'You are not authorised to make this request.' }, options)); }, NoPermissionError: function NoPermissionError(options) { IgnitionError.call(this, merge({ statusCode: 403, errorType: 'NoPermissionError', message: 'You do not have permission to perform this request.' }, options)); }, ValidationError: function ValidationError(options) { IgnitionError.call(this, merge({ statusCode: 422, errorType: 'ValidationError', message: 'The request failed validation.' }, options)); }, UnsupportedMediaTypeError: function UnsupportedMediaTypeError(options) { IgnitionError.call(this, merge({ statusCode: 415, errorType: 'UnsupportedMediaTypeError', message: 'The media in the request is not supported by the server.' }, options)); }, TooManyRequestsError: function TooManyRequestsError(options) { IgnitionError.call(this, merge({ statusCode: 429, errorType: 'TooManyRequestsError', message: 'Server has received too many similar requests in a short space of time.' }, options)); }, MaintenanceError: function MaintenanceError(options) { IgnitionError.call(this, merge({ statusCode: 503, errorType: 'MaintenanceError', message: 'The server is temporarily down for maintenance.' }, options)); }, MethodNotAllowedError: function MethodNotAllowedError(options) { IgnitionError.call(this, merge({ statusCode: 405, errorType: 'MethodNotAllowedError', message: 'Method not allowed for resource.' }, options)); }, RequestEntityTooLargeError: function RequestEntityTooLargeError(options) { IgnitionError.call(this, merge({ statusCode: 413, errorType: 'RequestEntityTooLargeError', message: 'Request was too big for the server to handle.' }, options)); }, TokenRevocationError: function TokenRevocationError(options) { IgnitionError.call(this, merge({ statusCode: 503, errorType: 'TokenRevocationError', message: 'Token is no longer available.' }, options)); }, VersionMismatchError: function VersionMismatchError(options) { IgnitionError.call(this, merge({ statusCode: 400, errorType: 'VersionMismatchError', message: 'Requested version does not match server version.' }, options)); } }; util.inherits(IgnitionError, Error); each(errors, function (error) { util.inherits(error, IgnitionError); }); module.exports = errors; module.exports.IgnitionError = IgnitionError; module.exports.utils = { serialize: utils.serialize.bind(errors), deserialize: utils.deserialize.bind(errors), isIgnitionError: utils.isIgnitionError.bind(errors) };
lib/errors/index.js
var uuid = require('uuid'), util = require('util'), each = require('lodash/each'), utils = require('./utils'), merge = require('lodash/merge'), isString = require('lodash/isString'); function IgnitionError(options) { options = options || {}; var self = this; if (isString(options)) { throw new Error('Please instantiate Errors with the option pattern. e.g. new errors.IgnitionError({message: ...})'); } Error.call(this); Error.captureStackTrace(this, IgnitionError); /** * defaults */ this.statusCode = 500; this.errorType = 'InternalServerError'; this.level = 'normal'; this.message = 'The server has encountered an error.'; this.id = uuid.v1(); /** * custom overrides */ this.id = options.id || this.id; this.statusCode = options.statusCode || this.statusCode; this.level = options.level || this.level; this.context = options.context || this.context; this.help = options.help || this.help; this.errorType = this.name = options.errorType || this.errorType; this.errorDetails = options.errorDetails; this.code = options.code || null; this.property = options.property || null; this.redirect = options.redirect || null; this.message = options.message || this.message; this.hideStack = options.hideStack; // error to inherit from, override! // nested objects are getting copied over in one piece (can be changed, but not needed right now) // support err as string (it happens that third party libs return a string instead of an error instance) if (options.err) { if (isString(options.err)) { options.err = new Error(options.err); } Object.getOwnPropertyNames(options.err).forEach(function (property) { if (['errorType', 'name', 'statusCode', 'message', 'level'].indexOf(property) !== -1) { return; } if (property === 'stack') { self[property] += '\n\n' + options.err[property]; return; } self[property] = options.err[property] || self[property]; }); } } // jscs:disable var errors = { InternalServerError: function InternalServerError(options) { IgnitionError.call(this, merge({ statusCode: 500, level: 'critical', errorType: 'InternalServerError', message: 'The server has encountered an error.' }, options)); }, IncorrectUsageError: function IncorrectUsageError(options) { IgnitionError.call(this, merge({ statusCode: 400, level: 'critical', errorType: 'IncorrectUsageError', message: 'We detected a misuse. Please read the stack trace.' }, options)); }, NotFoundError: function NotFoundError(options) { IgnitionError.call(this, merge({ statusCode: 404, errorType: 'NotFoundError', message: 'Resource could not be found.' }, options)); }, BadRequestError: function BadRequestError(options) { IgnitionError.call(this, merge({ statusCode: 400, errorType: 'BadRequestError', message: 'The request could not be understood.' }, options)); }, UnauthorizedError: function UnauthorizedError(options) { IgnitionError.call(this, merge({ statusCode: 401, errorType: 'UnauthorizedError', message: 'You are not authorised to make this request.' }, options)); }, NoPermissionError: function NoPermissionError(options) { IgnitionError.call(this, merge({ statusCode: 403, errorType: 'NoPermissionError', message: 'You do not have permission to perform this request.' }, options)); }, ValidationError: function ValidationError(options) { IgnitionError.call(this, merge({ statusCode: 422, errorType: 'ValidationError', message: 'The request failed validation.' }, options)); }, UnsupportedMediaTypeError: function UnsupportedMediaTypeError(options) { IgnitionError.call(this, merge({ statusCode: 415, errorType: 'UnsupportedMediaTypeError', message: 'The media in the request is not supported by the server.' }, options)); }, TooManyRequestsError: function TooManyRequestsError(options) { IgnitionError.call(this, merge({ statusCode: 429, errorType: 'TooManyRequestsError', message: 'Server has received too many similar requests in a short space of time.' }, options)); }, MaintenanceError: function MaintenanceError(options) { IgnitionError.call(this, merge({ statusCode: 503, errorType: 'MaintenanceError', message: 'The server is temporarily down for maintenance.' }, options)); }, MethodNotAllowedError: function MethodNotAllowedError(options) { IgnitionError.call(this, merge({ statusCode: 405, errorType: 'MethodNotAllowedError', message: 'Method not allowed for resource.' }, options)); }, RequestEntityTooLargeError: function RequestEntityTooLargeError(options) { IgnitionError.call(this, merge({ statusCode: 413, errorType: 'RequestEntityTooLargeError', message: 'Request was too big for the server to handle.' }, options)); }, TokenRevocationError: function TokenRevocationError(options) { IgnitionError.call(this, merge({ statusCode: 503, errorType: 'TokenRevocationError', message: 'Token is no longer available.' }, options)); }, VersionMismatchError: function VersionMismatchError(options) { IgnitionError.call(this, merge({ statusCode: 400, errorType: 'VersionMismatchError', message: 'Requested version does not match server version.' }, options)); } }; util.inherits(IgnitionError, Error); each(errors, function (error) { util.inherits(error, IgnitionError); }); module.exports = errors; module.exports.IgnitionError = IgnitionError; module.exports.utils = { serialize: utils.serialize.bind(errors), deserialize: utils.deserialize.bind(errors), isIgnitionError: utils.isIgnitionError.bind(errors) };
Removed override of error code property (#68) refs https://github.com/TryGhost/Ghost/pull/10415 refs https://github.com/TryGhost/Ghost/issues/10181 refs https://github.com/TryGhost/Ghost/issues/10421 When supplying a code to an ignition error, if you pass an error with a code, the error's code takes precedence rather than the explicit code you pass.
lib/errors/index.js
Removed override of error code property (#68)
<ide><path>ib/errors/index.js <ide> Object.getOwnPropertyNames(options.err).forEach(function (property) { <ide> if (['errorType', 'name', 'statusCode', 'message', 'level'].indexOf(property) !== -1) { <ide> return; <add> } <add> <add> // CASE: `code` should put options as priority over err <add> if (property === 'code') { <add> self[property] = self[property] || options.err[property]; <ide> } <ide> <ide> if (property === 'stack') {
Java
agpl-3.0
a51bb77cea45011b49bcd3c0bec8266aad4c160e
0
printedheart/opennars,printedheart/opennars,printedheart/opennars,printedheart/opennars,printedheart/opennars,printedheart/opennars
/* * Concept.java * * Copyright (C) 2008 Pei Wang * * This file is part of Open-NARS. * * Open-NARS is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * Open-NARS is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Open-NARS. If not, see <http://www.gnu.org/licenses/>. */ package nars.entity; import nars.core.control.NAL; import java.util.ArrayList; import java.util.List; import nars.core.Events.BeliefSelect; import nars.core.Events.ConceptBeliefAdd; import nars.core.Events.ConceptBeliefRemove; import nars.core.Events.ConceptGoalAdd; import nars.core.Events.ConceptGoalRemove; import nars.core.Events.ConceptQuestionAdd; import nars.core.Events.ConceptQuestionRemove; import nars.core.Events.TaskLinkAdd; import nars.core.Events.TaskLinkRemove; import nars.core.Events.TermLinkAdd; import nars.core.Events.TermLinkRemove; import nars.core.Events.UnexecutableGoal; import nars.core.Memory; import nars.core.NARRun; import static nars.inference.BudgetFunctions.distributeAmongLinks; import static nars.inference.BudgetFunctions.rankBelief; import nars.inference.Executive; import static nars.inference.LocalRules.revisible; import static nars.inference.LocalRules.revision; import static nars.inference.LocalRules.trySolution; import static nars.inference.TemporalRules.concurrent; import static nars.inference.TemporalRules.solutionQuality; import static nars.inference.UtilityFunctions.or; import nars.io.Symbols; import nars.language.CompoundTerm; import nars.language.Term; import nars.storage.Bag; import nars.storage.Bag.MemoryAware; public class Concept extends Item<Term> { /** * The term is the unique ID of the concept */ public final Term term; /** * Task links for indirect processing */ public final Bag<TaskLink,Task> taskLinks; /** * Term links between the term and its components and compounds; beliefs */ public final Bag<TermLink,TermLink> termLinks; /** * Link templates of TermLink, only in concepts with CompoundTerm Templates * are used to improve the efficiency of TermLink building */ private final List<TermLink> termLinkTemplates; /** * Pending Question directly asked about the term * * Note: since this is iterated frequently, an array should be used. To * avoid iterator allocation, use .get(n) in a for-loop */ public final List<Task> questions; /** * Pending Quests to be answered by new desire values */ public final ArrayList<Task> quests; /** * Judgments directly made about the term Use ArrayList because of access * and insertion in the middle */ public final ArrayList<Sentence> beliefs; /** * Desire values on the term, similar to the above one */ public final ArrayList<Sentence> desires; /** * Reference to the memory to which the Concept belongs */ public final Memory memory; /** * The display window */ /* ---------- constructor and initialization ---------- */ /** * Constructor, called in Memory.getConcept only * * @param tm A term corresponding to the concept * @param memory A reference to the memory */ public Concept(final BudgetValue b, final Term tm, Bag<TaskLink,Task> taskLinks, Bag<TermLink,TermLink> termLinks, final Memory memory) { super(b); this.term = tm; this.memory = memory; this.questions = new ArrayList<>(); this.beliefs = new ArrayList<>(); this.quests = new ArrayList<>(); this.desires = new ArrayList<>(); this.taskLinks = taskLinks; this.termLinks = termLinks; if (taskLinks instanceof MemoryAware) ((MemoryAware)taskLinks).setMemory(memory); if (termLinks instanceof MemoryAware) ((MemoryAware)termLinks).setMemory(memory); if (tm instanceof CompoundTerm) { this.termLinkTemplates = ((CompoundTerm) tm).prepareComponentLinks(); } else { this.termLinkTemplates = null; } } // @Override public int hashCode() { // return term.hashCode(); // } // // @Override public boolean equals(final Object obj) { // if (this == obj) return true; // if (obj instanceof Concept) { // Concept t = (Concept)obj; // return (t.term.equals(term)); // } // return false; // } // @Override public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof Concept)) return false; return ((Concept)obj).name().equals(name()); } @Override public int hashCode() { return name().hashCode(); } @Override public Term name() { return term; } /* ---------- direct processing of tasks ---------- */ /** * Directly process a new task. Called exactly once on each task. Using * local information and finishing in a constant time. Provide feedback in * the taskBudget value of the task. * <p> * called in Memory.immediateProcess only * * @param task The task to be processed * @return whether it was processed */ public boolean directProcess(final NAL nal, final Task task) { char type = task.sentence.punctuation; switch (type) { case Symbols.JUDGMENT_MARK: memory.logic.JUDGMENT_PROCESS.commit(); processJudgment(nal, task); break; case Symbols.GOAL_MARK: memory.logic.GOAL_PROCESS.commit(); processGoal(nal, task); break; case Symbols.QUESTION_MARK: case Symbols.QUEST_MARK: memory.logic.QUESTION_PROCESS.commit(); processQuestion(nal, task); break; default: return false; } if (task.aboveThreshold()) { // still need to be processed memory.logic.LINK_TO_TASK.commit(); linkToTask(task); } return true; } /** * To accept a new judgment as belief, and check for revisions and solutions * * @param judg The judgment to be accepted * @param task The task to be processed * @return Whether to continue the processing of the task */ protected void processJudgment(final NAL nal, final Task task) { final Sentence judg = task.sentence; final Sentence oldBelief = selectCandidate(judg, beliefs); // only revise with the strongest -- how about projection? if (oldBelief != null) { final Stamp newStamp = judg.stamp; final Stamp oldStamp = oldBelief.stamp; if (newStamp.equals(oldStamp,false,false,true,true)) { if (task.getParentTask() != null && task.getParentTask().sentence.isJudgment()) { //task.budget.decPriority(0); // duplicated task } // else: activated belief memory.removeTask(task, "Duplicated"); return; } else if (revisible(judg, oldBelief)) { nal.setTheNewStamp(newStamp, oldStamp, memory.time()); // if (nal.setTheNewStamp( //temporarily removed // /* // if (equalBases(first.getBase(), second.getBase())) { // return null; // do not merge identical bases // } // */ // // if (first.baseLength() > second.baseLength()) { // new Stamp(newStamp, oldStamp, memory.time()) // keep the order for projection // // } else { // // return new Stamp(second, first, time); // // } // ) != null) { Sentence projectedBelief = oldBelief.projection(newStamp.getOccurrenceTime(), memory.time()); if (projectedBelief.getOccurenceTime()!=oldBelief.getOccurenceTime()) { nal.singlePremiseTask(projectedBelief, task.budget); } nal.setCurrentBelief(projectedBelief); revision(judg, projectedBelief, false, nal); // } } if (task.aboveThreshold()) { int nnq = questions.size(); for (int i = 0; i < nnq; i++) { trySolution(judg, questions.get(i), nal); } addToTable(task, judg, beliefs, memory.param.conceptBeliefsMax.get(), ConceptBeliefAdd.class, ConceptBeliefRemove.class); } } protected void addToTable(final Task task, final Sentence newSentence, final ArrayList<Sentence> table, final int max, final Class eventAdd, final Class eventRemove, final Object... extraEventArguments) { int preSize = table.size(); Sentence removed; synchronized (table) { removed = addToTable(newSentence, table, max); } if (removed != null) { memory.event.emit(eventRemove, this, removed, task, extraEventArguments); } if ((preSize != table.size()) || (removed != null)) { memory.event.emit(eventAdd, this, newSentence, task, extraEventArguments); } } /** * To accept a new goal, and check for revisions and realization, then * decide whether to actively pursue it * * @param judg The judgment to be accepted * @param task The task to be processed * @return Whether to continue the processing of the task */ protected void processGoal(final NAL nal, final Task task) { final Sentence goal = task.sentence; final Sentence oldGoal = selectCandidate(goal, desires); // revise with the existing desire values if (oldGoal != null) { final Stamp newStamp = goal.stamp; final Stamp oldStamp = oldGoal.stamp; if (newStamp.equals(oldStamp,false,false,true,true)) { return; //duplicate } else if (revisible(goal, oldGoal)) { nal.setTheNewStamp(newStamp, oldStamp, memory.time()); boolean success=revision(goal,oldGoal,false,nal); if(success) { //it is revised, so there is a new task for which this function will be called return; //with higher/lower desire } } } if (task.aboveThreshold()) { final Sentence belief = selectCandidate(goal, beliefs); // check if the Goal is already satisfied if (belief != null) { trySolution(belief, task, nal); // check if the Goal is already satisfied } // still worth pursuing? if (task.aboveThreshold()) { addToTable(task, goal, desires, memory.param.conceptGoalsMax.get(), ConceptGoalAdd.class, ConceptGoalRemove.class); if (!Executive.isExecutableTerm(task.sentence.content)) { memory.emit(UnexecutableGoal.class, task, this, nal); } else { memory.executive.decisionMaking(task, this); } } } } /** * To answer a question by existing beliefs * * @param task The task to be processed * @return Whether to continue the processing of the task */ protected void processQuestion(final NAL nal, final Task task) { Sentence ques = task.sentence; boolean newQuestion = true; for (final Task t : questions) { final Sentence q = t.sentence; if (q.equalsContent(ques)) { ques = q; newQuestion = false; break; } } if (newQuestion) { if (questions.size() + 1 > memory.param.conceptQuestionsMax.get()) { Task removed = questions.remove(0); // FIFO memory.event.emit(ConceptQuestionRemove.class, this, removed); } questions.add(task); memory.event.emit(ConceptQuestionAdd.class, this, task); } final Sentence newAnswer = (ques.isQuestion()) ? selectCandidate(ques, beliefs) : selectCandidate(ques, desires); if (newAnswer != null) { trySolution(newAnswer, task, nal); } } /** * Link to a new task from all relevant concepts for continued processing in * the near future for unspecified time. * <p> * The only method that calls the TaskLink constructor. * * @param task The task to be linked * @param content The content of the task */ public void linkToTask(final Task task) { final BudgetValue taskBudget = task.budget; insertTaskLink(new TaskLink(task, null, taskBudget, memory.param.termLinkRecordLength.get())); // link type: SELF if (term instanceof CompoundTerm) { if (!termLinkTemplates.isEmpty()) { final BudgetValue subBudget = distributeAmongLinks(taskBudget, termLinkTemplates.size()); if (subBudget.aboveThreshold()) { for (int t = 0; t < termLinkTemplates.size(); t++) { TermLink termLink = termLinkTemplates.get(t); // if (!(task.isStructural() && (termLink.getType() == TermLink.TRANSFORM))) { // avoid circular transform Term componentTerm = termLink.target; Concept componentConcept = memory.conceptualize(subBudget, componentTerm); if (componentConcept != null) { componentConcept.insertTaskLink( new TaskLink(task, termLink, subBudget, memory.param.termLinkRecordLength.get())); } // } } buildTermLinks(taskBudget); // recursively insert TermLink } } } } /** * Add a new belief (or goal) into the table Sort the beliefs/desires by * rank, and remove redundant or low rank one * * @param newSentence The judgment to be processed * @param table The table to be revised * @param capacity The capacity of the table * @return whether table was modified */ private static Sentence addToTable(final Sentence newSentence, final List<Sentence> table, final int capacity) { final float rank1 = rankBelief(newSentence); // for the new isBelief float rank2; int i; for (i = 0; i < table.size(); i++) { Sentence judgment2 = table.get(i); rank2 = rankBelief(judgment2); if (rank1 >= rank2) { if (newSentence.equivalentTo(judgment2)) { //System.out.println(" ---------- Equivalent Belief: " + newSentence + " == " + judgment2); return null; } table.add(i, newSentence); break; } } if (table.size() >= capacity) { if (table.size() > capacity) { Sentence removed = table.remove(table.size() - 1); return removed; } } else if (i == table.size()) { table.add(newSentence); } return null; } /** * Select a belief value or desire value for a given query * * @param query The query to be processed * @param list The list of beliefs or desires to be used * @return The best candidate selected */ private Sentence selectCandidate(final Sentence query, final List<Sentence> list) { // if (list == null) { // return null; // } float currentBest = 0; float beliefQuality; Sentence candidate = null; synchronized (list) { for (int i = 0; i < list.size(); i++) { Sentence judg = list.get(i); beliefQuality = solutionQuality(query, judg, memory); if (beliefQuality > currentBest) { currentBest = beliefQuality; candidate = judg; } } } return candidate; } /* ---------- insert Links for indirect processing ---------- */ /** * Insert a TaskLink into the TaskLink bag * <p> * called only from Memory.continuedProcess * * @param taskLink The termLink to be inserted */ protected boolean insertTaskLink(final TaskLink taskLink) { TaskLink removed = taskLinks.putIn(taskLink); if (removed!=null) { if (removed == taskLink) { memory.emit(TaskLinkRemove.class, taskLink, this); return false; } else { memory.emit(TaskLinkRemove.class, removed, this); } } memory.emit(TaskLinkAdd.class, taskLink, this); return true; } /** * Recursively build TermLinks between a compound and its components * <p> * called only from Memory.continuedProcess * * @param taskBudget The BudgetValue of the task */ public void buildTermLinks(final BudgetValue taskBudget) { if (termLinkTemplates.size() > 0) { BudgetValue subBudget = distributeAmongLinks(taskBudget, termLinkTemplates.size()); if (subBudget.aboveThreshold()) { for (final TermLink template : termLinkTemplates) { if (template.type != TermLink.TRANSFORM) { Term target = template.target; final Concept concept = memory.conceptualize(taskBudget, target); if (concept != null) { // this termLink to that insertTermLink(new TermLink(target, template, subBudget)); // that termLink to this concept.insertTermLink(new TermLink(term, template, subBudget)); if (target instanceof CompoundTerm) { concept.buildTermLinks(subBudget); } } } } } } } /** * Insert a TermLink into the TermLink bag * <p> * called from buildTermLinks only * * @param termLink The termLink to be inserted */ public boolean insertTermLink(final TermLink termLink) { TermLink removed = termLinks.putIn(termLink); if (removed!=null) { if (removed == termLink) { memory.emit(TermLinkRemove.class, termLink, this); return false; } else { memory.emit(TermLinkRemove.class, removed, this); } } memory.emit(TermLinkAdd.class, termLink, this); return true; } /** * Return a string representation of the concept, called in ConceptBag only * * @return The concept name, with taskBudget in the full version */ @Override public String toString() { // called from concept bag //return (super.toStringBrief() + " " + key); return super.toStringExternal(); } /** * called from {@link NARRun} */ @Override public String toStringLong() { String res = toStringExternal() + " " + term.name() + toStringIfNotNull(termLinks.size(), "termLinks") + toStringIfNotNull(taskLinks.size(), "taskLinks") + toStringIfNotNull(beliefs.size(), "beliefs") + toStringIfNotNull(desires.size(), "desires") + toStringIfNotNull(questions.size(), "questions") + toStringIfNotNull(quests.size(), "quests"); //+ toStringIfNotNull(null, "questions"); /*for (Task t : questions) { res += t.toString(); }*/ // TODO other details? return res; } private String toStringIfNotNull(final Object item, final String title) { if (item == null) { return ""; } final String itemString = item.toString(); return new StringBuilder(2 + title.length() + itemString.length() + 1). append(" ").append(title).append(':').append(itemString).toString(); } /** * Recalculate the quality of the concept [to be refined to show * extension/intension balance] * * @return The quality value */ @Override public float getQuality() { float linkPriority = termLinks.getAveragePriority(); float termComplexityFactor = 1.0f / term.getComplexity(); float result = or(linkPriority, termComplexityFactor); if (result < 0) { throw new RuntimeException("Concept.getQuality < 0: result=" + result + ", linkPriority=" + linkPriority + " ,termComplexityFactor=" + termComplexityFactor + ", termLinks.size=" + termLinks.size()); } return result; } /** * Return the templates for TermLinks, only called in * Memory.continuedProcess * * @return The template get */ public List<TermLink> getTermLinkTemplates() { return termLinkTemplates; } /** * Select a isBelief to interact with the given task in inference * <p> * get the first qualified one * <p> * only called in RuleTables.reason * * @param task The selected task * @return The selected isBelief */ public Sentence getBelief(final NAL nal, final Task task) { final Stamp taskStamp = task.sentence.stamp; final long currentTime = memory.time(); for (final Sentence belief : beliefs) { nal.emit(BeliefSelect.class, belief); nal.setTheNewStamp(taskStamp, belief.stamp, currentTime); //// if (memory.newStamp != null) { // return belief.projection(taskStamp.getOccurrenceTime(), currentTime); //// } Sentence projectedBelief = belief.projection(taskStamp.getOccurrenceTime(), memory.time()); if (projectedBelief.getOccurenceTime()!=belief.getOccurenceTime()) { nal.singlePremiseTask(projectedBelief, task.budget); } return projectedBelief; // return the first satisfying belief } return null; } /** * Get the current overall desire value. TODO to be refined */ public TruthValue getDesire() { if (desires.isEmpty()) { return null; } TruthValue topValue = desires.get(0).truth; return topValue; } @Override public void end() { //empty bags and lists for (Task t : questions) t.end(); questions.clear(); for (Task t : quests) t.end(); quests.clear(); termLinks.clear(); taskLinks.clear(); beliefs.clear(); } /** * Collect direct isBelief, questions, and desires for display * * @return String representation of direct content */ public String displayContent() { final StringBuilder buffer = new StringBuilder(18); buffer.append("\n Beliefs:\n"); if (!beliefs.isEmpty()) { for (Sentence s : beliefs) { buffer.append(s).append('\n'); } } if (!questions.isEmpty()) { buffer.append("\n Question:\n"); for (Task t : questions) { buffer.append(t).append('\n'); } } return buffer.toString(); } /** * Replace default to prevent repeated inference, by checking TaskLink * * @param taskLink The selected TaskLink * @param time The current time * @return The selected TermLink */ public TermLink selectTermLink(final TaskLink taskLink, final long time) { int toMatch = memory.param.termLinkMaxMatched.get(); //Math.min(memory.param.termLinkMaxMatched.get(), termLinks.size()); for (int i = 0; (i < toMatch) && (termLinks.size() > 0); i++) { final TermLink termLink = termLinks.takeNext(); if (termLink==null) break; if (taskLink.novel(termLink, time)) { //return, will be re-inserted in caller method when finished processing it return termLink; } returnTermLink(termLink); } return null; } public void returnTermLink(TermLink termLink) { termLinks.putBack(termLink, memory.param.cycles(memory.param.beliefForgetDurations), memory); } /** * Return the questions, called in ComposionalRules in * dedConjunctionByQuestion only */ public List<Task> getQuestions() { return questions; } public void discountConfidence(final boolean onBeliefs) { if (onBeliefs) { for (final Sentence s : beliefs) { s.discountConfidence(); } } else { for (final Sentence s : desires) { s.discountConfidence(); } } } /** get a random belief, weighted by their sentences confidences */ public Sentence getBeliefRandomByConfidence() { if (beliefs.isEmpty()) return null; float totalConfidence = getBeliefConfidenceSum(); float r = Memory.randomNumber.nextFloat() * totalConfidence; Sentence s = null; for (int i = 0; i < beliefs.size(); i++) { s = beliefs.get(i); r -= s.truth.getConfidence(); if (r < 0) return s; } return s; } public float getBeliefConfidenceSum() { float t = 0; for (final Sentence s : beliefs) t += s.truth.getConfidence(); return t; } public float getBeliefFrequencyMean() { if (beliefs.isEmpty()) return 0.5f; float t = 0; for (final Sentence s : beliefs) t += s.truth.getFrequency(); return t / beliefs.size(); } public CharSequence getBeliefsSummary() { if (beliefs.isEmpty()) return "0 beliefs"; StringBuilder sb = new StringBuilder(); for (Sentence s : beliefs) sb.append(s.toString()).append('\n'); return sb; } public CharSequence getDesiresSummary() { if (desires.isEmpty()) return "0 desires"; StringBuilder sb = new StringBuilder(); for (Sentence s : desires) sb.append(s.toString()).append('\n'); return sb; } }
nars_java/nars/entity/Concept.java
/* * Concept.java * * Copyright (C) 2008 Pei Wang * * This file is part of Open-NARS. * * Open-NARS is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * Open-NARS is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Open-NARS. If not, see <http://www.gnu.org/licenses/>. */ package nars.entity; import nars.core.control.NAL; import java.util.ArrayList; import java.util.List; import nars.core.Events.BeliefSelect; import nars.core.Events.ConceptBeliefAdd; import nars.core.Events.ConceptBeliefRemove; import nars.core.Events.ConceptGoalAdd; import nars.core.Events.ConceptGoalRemove; import nars.core.Events.ConceptQuestionAdd; import nars.core.Events.ConceptQuestionRemove; import nars.core.Events.TaskLinkAdd; import nars.core.Events.TaskLinkRemove; import nars.core.Events.TermLinkAdd; import nars.core.Events.TermLinkRemove; import nars.core.Events.UnexecutableGoal; import nars.core.Memory; import nars.core.NARRun; import static nars.inference.BudgetFunctions.distributeAmongLinks; import static nars.inference.BudgetFunctions.rankBelief; import nars.inference.Executive; import static nars.inference.LocalRules.revisible; import static nars.inference.LocalRules.revision; import static nars.inference.LocalRules.trySolution; import static nars.inference.TemporalRules.concurrent; import static nars.inference.TemporalRules.solutionQuality; import static nars.inference.UtilityFunctions.or; import nars.io.Symbols; import nars.language.CompoundTerm; import nars.language.Term; import nars.storage.Bag; import nars.storage.Bag.MemoryAware; public class Concept extends Item<Term> { /** * The term is the unique ID of the concept */ public final Term term; /** * Task links for indirect processing */ public final Bag<TaskLink,Task> taskLinks; /** * Term links between the term and its components and compounds; beliefs */ public final Bag<TermLink,TermLink> termLinks; /** * Link templates of TermLink, only in concepts with CompoundTerm Templates * are used to improve the efficiency of TermLink building */ private final List<TermLink> termLinkTemplates; /** * Pending Question directly asked about the term * * Note: since this is iterated frequently, an array should be used. To * avoid iterator allocation, use .get(n) in a for-loop */ public final List<Task> questions; /** * Pending Quests to be answered by new desire values */ public final ArrayList<Task> quests; /** * Judgments directly made about the term Use ArrayList because of access * and insertion in the middle */ public final ArrayList<Sentence> beliefs; /** * Desire values on the term, similar to the above one */ public final ArrayList<Sentence> desires; /** * Reference to the memory to which the Concept belongs */ public final Memory memory; /** * The display window */ /* ---------- constructor and initialization ---------- */ /** * Constructor, called in Memory.getConcept only * * @param tm A term corresponding to the concept * @param memory A reference to the memory */ public Concept(final BudgetValue b, final Term tm, Bag<TaskLink,Task> taskLinks, Bag<TermLink,TermLink> termLinks, final Memory memory) { super(b); this.term = tm; this.memory = memory; this.questions = new ArrayList<>(); this.beliefs = new ArrayList<>(); this.quests = new ArrayList<>(); this.desires = new ArrayList<>(); this.taskLinks = taskLinks; this.termLinks = termLinks; if (taskLinks instanceof MemoryAware) ((MemoryAware)taskLinks).setMemory(memory); if (termLinks instanceof MemoryAware) ((MemoryAware)termLinks).setMemory(memory); if (tm instanceof CompoundTerm) { this.termLinkTemplates = ((CompoundTerm) tm).prepareComponentLinks(); } else { this.termLinkTemplates = null; } } // @Override public int hashCode() { // return term.hashCode(); // } // // @Override public boolean equals(final Object obj) { // if (this == obj) return true; // if (obj instanceof Concept) { // Concept t = (Concept)obj; // return (t.term.equals(term)); // } // return false; // } // @Override public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof Concept)) return false; return ((Concept)obj).name().equals(name()); } @Override public int hashCode() { return name().hashCode(); } @Override public Term name() { return term; } /* ---------- direct processing of tasks ---------- */ /** * Directly process a new task. Called exactly once on each task. Using * local information and finishing in a constant time. Provide feedback in * the taskBudget value of the task. * <p> * called in Memory.immediateProcess only * * @param task The task to be processed * @return whether it was processed */ public boolean directProcess(final NAL nal, final Task task) { char type = task.sentence.punctuation; switch (type) { case Symbols.JUDGMENT_MARK: memory.logic.JUDGMENT_PROCESS.commit(); processJudgment(nal, task); break; case Symbols.GOAL_MARK: memory.logic.GOAL_PROCESS.commit(); processGoal(nal, task); break; case Symbols.QUESTION_MARK: case Symbols.QUEST_MARK: memory.logic.QUESTION_PROCESS.commit(); processQuestion(nal, task); break; default: return false; } if (task.aboveThreshold()) { // still need to be processed memory.logic.LINK_TO_TASK.commit(); linkToTask(task); } return true; } /** * To accept a new judgment as belief, and check for revisions and solutions * * @param judg The judgment to be accepted * @param task The task to be processed * @return Whether to continue the processing of the task */ protected void processJudgment(final NAL nal, final Task task) { final Sentence judg = task.sentence; final Sentence oldBelief = selectCandidate(judg, beliefs); // only revise with the strongest -- how about projection? if (oldBelief != null) { final Stamp newStamp = judg.stamp; final Stamp oldStamp = oldBelief.stamp; if (newStamp.equals(oldStamp,false,true,true,true)) { if (task.getParentTask() != null && task.getParentTask().sentence.isJudgment()) { //task.budget.decPriority(0); // duplicated task } // else: activated belief memory.removeTask(task, "Duplicated"); return; } else if (revisible(judg, oldBelief)) { nal.setTheNewStamp(newStamp, oldStamp, memory.time()); // if (nal.setTheNewStamp( //temporarily removed // /* // if (equalBases(first.getBase(), second.getBase())) { // return null; // do not merge identical bases // } // */ // // if (first.baseLength() > second.baseLength()) { // new Stamp(newStamp, oldStamp, memory.time()) // keep the order for projection // // } else { // // return new Stamp(second, first, time); // // } // ) != null) { Sentence projectedBelief = oldBelief.projection(newStamp.getOccurrenceTime(), memory.time()); if (projectedBelief.getOccurenceTime()!=oldBelief.getOccurenceTime()) { nal.singlePremiseTask(projectedBelief, task.budget); } nal.setCurrentBelief(projectedBelief); revision(judg, projectedBelief, false, nal); // } } if (task.aboveThreshold()) { int nnq = questions.size(); for (int i = 0; i < nnq; i++) { trySolution(judg, questions.get(i), nal); } addToTable(task, judg, beliefs, memory.param.conceptBeliefsMax.get(), ConceptBeliefAdd.class, ConceptBeliefRemove.class); } } protected void addToTable(final Task task, final Sentence newSentence, final ArrayList<Sentence> table, final int max, final Class eventAdd, final Class eventRemove, final Object... extraEventArguments) { int preSize = table.size(); Sentence removed; synchronized (table) { removed = addToTable(newSentence, table, max); } if (removed != null) { memory.event.emit(eventRemove, this, removed, task, extraEventArguments); } if ((preSize != table.size()) || (removed != null)) { memory.event.emit(eventAdd, this, newSentence, task, extraEventArguments); } } /** * To accept a new goal, and check for revisions and realization, then * decide whether to actively pursue it * * @param judg The judgment to be accepted * @param task The task to be processed * @return Whether to continue the processing of the task */ protected void processGoal(final NAL nal, final Task task) { final Sentence goal = task.sentence; final Sentence oldGoal = selectCandidate(goal, desires); // revise with the existing desire values if (oldGoal != null) { final Stamp newStamp = goal.stamp; final Stamp oldStamp = oldGoal.stamp; if (newStamp.equals(oldStamp,false,false,true,true)) { return; //duplicate } else if (revisible(goal, oldGoal)) { nal.setTheNewStamp(newStamp, oldStamp, memory.time()); boolean success=revision(goal,oldGoal,false,nal); if(success) { //it is revised, so there is a new task for which this function will be called return; //with higher/lower desire } } } if (task.aboveThreshold()) { final Sentence belief = selectCandidate(goal, beliefs); // check if the Goal is already satisfied if (belief != null) { trySolution(belief, task, nal); // check if the Goal is already satisfied } // still worth pursuing? if (task.aboveThreshold()) { addToTable(task, goal, desires, memory.param.conceptGoalsMax.get(), ConceptGoalAdd.class, ConceptGoalRemove.class); if (!Executive.isExecutableTerm(task.sentence.content)) { memory.emit(UnexecutableGoal.class, task, this, nal); } else { memory.executive.decisionMaking(task, this); } } } } /** * To answer a question by existing beliefs * * @param task The task to be processed * @return Whether to continue the processing of the task */ protected void processQuestion(final NAL nal, final Task task) { Sentence ques = task.sentence; boolean newQuestion = true; for (final Task t : questions) { final Sentence q = t.sentence; if (q.equalsContent(ques)) { ques = q; newQuestion = false; break; } } if (newQuestion) { if (questions.size() + 1 > memory.param.conceptQuestionsMax.get()) { Task removed = questions.remove(0); // FIFO memory.event.emit(ConceptQuestionRemove.class, this, removed); } questions.add(task); memory.event.emit(ConceptQuestionAdd.class, this, task); } final Sentence newAnswer = (ques.isQuestion()) ? selectCandidate(ques, beliefs) : selectCandidate(ques, desires); if (newAnswer != null) { trySolution(newAnswer, task, nal); } } /** * Link to a new task from all relevant concepts for continued processing in * the near future for unspecified time. * <p> * The only method that calls the TaskLink constructor. * * @param task The task to be linked * @param content The content of the task */ public void linkToTask(final Task task) { final BudgetValue taskBudget = task.budget; insertTaskLink(new TaskLink(task, null, taskBudget, memory.param.termLinkRecordLength.get())); // link type: SELF if (term instanceof CompoundTerm) { if (!termLinkTemplates.isEmpty()) { final BudgetValue subBudget = distributeAmongLinks(taskBudget, termLinkTemplates.size()); if (subBudget.aboveThreshold()) { for (int t = 0; t < termLinkTemplates.size(); t++) { TermLink termLink = termLinkTemplates.get(t); // if (!(task.isStructural() && (termLink.getType() == TermLink.TRANSFORM))) { // avoid circular transform Term componentTerm = termLink.target; Concept componentConcept = memory.conceptualize(subBudget, componentTerm); if (componentConcept != null) { componentConcept.insertTaskLink( new TaskLink(task, termLink, subBudget, memory.param.termLinkRecordLength.get())); } // } } buildTermLinks(taskBudget); // recursively insert TermLink } } } } /** * Add a new belief (or goal) into the table Sort the beliefs/desires by * rank, and remove redundant or low rank one * * @param newSentence The judgment to be processed * @param table The table to be revised * @param capacity The capacity of the table * @return whether table was modified */ private static Sentence addToTable(final Sentence newSentence, final List<Sentence> table, final int capacity) { final float rank1 = rankBelief(newSentence); // for the new isBelief float rank2; int i; for (i = 0; i < table.size(); i++) { Sentence judgment2 = table.get(i); rank2 = rankBelief(judgment2); if (rank1 >= rank2) { if (newSentence.equivalentTo(judgment2)) { //System.out.println(" ---------- Equivalent Belief: " + newSentence + " == " + judgment2); return null; } table.add(i, newSentence); break; } } if (table.size() >= capacity) { if (table.size() > capacity) { Sentence removed = table.remove(table.size() - 1); return removed; } } else if (i == table.size()) { table.add(newSentence); } return null; } /** * Select a belief value or desire value for a given query * * @param query The query to be processed * @param list The list of beliefs or desires to be used * @return The best candidate selected */ private Sentence selectCandidate(final Sentence query, final List<Sentence> list) { // if (list == null) { // return null; // } float currentBest = 0; float beliefQuality; Sentence candidate = null; synchronized (list) { for (int i = 0; i < list.size(); i++) { Sentence judg = list.get(i); beliefQuality = solutionQuality(query, judg, memory); if (beliefQuality > currentBest) { currentBest = beliefQuality; candidate = judg; } } } return candidate; } /* ---------- insert Links for indirect processing ---------- */ /** * Insert a TaskLink into the TaskLink bag * <p> * called only from Memory.continuedProcess * * @param taskLink The termLink to be inserted */ protected boolean insertTaskLink(final TaskLink taskLink) { TaskLink removed = taskLinks.putIn(taskLink); if (removed!=null) { if (removed == taskLink) { memory.emit(TaskLinkRemove.class, taskLink, this); return false; } else { memory.emit(TaskLinkRemove.class, removed, this); } } memory.emit(TaskLinkAdd.class, taskLink, this); return true; } /** * Recursively build TermLinks between a compound and its components * <p> * called only from Memory.continuedProcess * * @param taskBudget The BudgetValue of the task */ public void buildTermLinks(final BudgetValue taskBudget) { if (termLinkTemplates.size() > 0) { BudgetValue subBudget = distributeAmongLinks(taskBudget, termLinkTemplates.size()); if (subBudget.aboveThreshold()) { for (final TermLink template : termLinkTemplates) { if (template.type != TermLink.TRANSFORM) { Term target = template.target; final Concept concept = memory.conceptualize(taskBudget, target); if (concept != null) { // this termLink to that insertTermLink(new TermLink(target, template, subBudget)); // that termLink to this concept.insertTermLink(new TermLink(term, template, subBudget)); if (target instanceof CompoundTerm) { concept.buildTermLinks(subBudget); } } } } } } } /** * Insert a TermLink into the TermLink bag * <p> * called from buildTermLinks only * * @param termLink The termLink to be inserted */ public boolean insertTermLink(final TermLink termLink) { TermLink removed = termLinks.putIn(termLink); if (removed!=null) { if (removed == termLink) { memory.emit(TermLinkRemove.class, termLink, this); return false; } else { memory.emit(TermLinkRemove.class, removed, this); } } memory.emit(TermLinkAdd.class, termLink, this); return true; } /** * Return a string representation of the concept, called in ConceptBag only * * @return The concept name, with taskBudget in the full version */ @Override public String toString() { // called from concept bag //return (super.toStringBrief() + " " + key); return super.toStringExternal(); } /** * called from {@link NARRun} */ @Override public String toStringLong() { String res = toStringExternal() + " " + term.name() + toStringIfNotNull(termLinks.size(), "termLinks") + toStringIfNotNull(taskLinks.size(), "taskLinks") + toStringIfNotNull(beliefs.size(), "beliefs") + toStringIfNotNull(desires.size(), "desires") + toStringIfNotNull(questions.size(), "questions") + toStringIfNotNull(quests.size(), "quests"); //+ toStringIfNotNull(null, "questions"); /*for (Task t : questions) { res += t.toString(); }*/ // TODO other details? return res; } private String toStringIfNotNull(final Object item, final String title) { if (item == null) { return ""; } final String itemString = item.toString(); return new StringBuilder(2 + title.length() + itemString.length() + 1). append(" ").append(title).append(':').append(itemString).toString(); } /** * Recalculate the quality of the concept [to be refined to show * extension/intension balance] * * @return The quality value */ @Override public float getQuality() { float linkPriority = termLinks.getAveragePriority(); float termComplexityFactor = 1.0f / term.getComplexity(); float result = or(linkPriority, termComplexityFactor); if (result < 0) { throw new RuntimeException("Concept.getQuality < 0: result=" + result + ", linkPriority=" + linkPriority + " ,termComplexityFactor=" + termComplexityFactor + ", termLinks.size=" + termLinks.size()); } return result; } /** * Return the templates for TermLinks, only called in * Memory.continuedProcess * * @return The template get */ public List<TermLink> getTermLinkTemplates() { return termLinkTemplates; } /** * Select a isBelief to interact with the given task in inference * <p> * get the first qualified one * <p> * only called in RuleTables.reason * * @param task The selected task * @return The selected isBelief */ public Sentence getBelief(final NAL nal, final Task task) { final Stamp taskStamp = task.sentence.stamp; final long currentTime = memory.time(); for (final Sentence belief : beliefs) { nal.emit(BeliefSelect.class, belief); nal.setTheNewStamp(taskStamp, belief.stamp, currentTime); //// if (memory.newStamp != null) { // return belief.projection(taskStamp.getOccurrenceTime(), currentTime); //// } Sentence projectedBelief = belief.projection(taskStamp.getOccurrenceTime(), memory.time()); if (projectedBelief.getOccurenceTime()!=belief.getOccurenceTime()) { nal.singlePremiseTask(projectedBelief, task.budget); } return projectedBelief; // return the first satisfying belief } return null; } /** * Get the current overall desire value. TODO to be refined */ public TruthValue getDesire() { if (desires.isEmpty()) { return null; } TruthValue topValue = desires.get(0).truth; return topValue; } @Override public void end() { //empty bags and lists for (Task t : questions) t.end(); questions.clear(); for (Task t : quests) t.end(); quests.clear(); termLinks.clear(); taskLinks.clear(); beliefs.clear(); } /** * Collect direct isBelief, questions, and desires for display * * @return String representation of direct content */ public String displayContent() { final StringBuilder buffer = new StringBuilder(18); buffer.append("\n Beliefs:\n"); if (!beliefs.isEmpty()) { for (Sentence s : beliefs) { buffer.append(s).append('\n'); } } if (!questions.isEmpty()) { buffer.append("\n Question:\n"); for (Task t : questions) { buffer.append(t).append('\n'); } } return buffer.toString(); } /** * Replace default to prevent repeated inference, by checking TaskLink * * @param taskLink The selected TaskLink * @param time The current time * @return The selected TermLink */ public TermLink selectTermLink(final TaskLink taskLink, final long time) { int toMatch = memory.param.termLinkMaxMatched.get(); //Math.min(memory.param.termLinkMaxMatched.get(), termLinks.size()); for (int i = 0; (i < toMatch) && (termLinks.size() > 0); i++) { final TermLink termLink = termLinks.takeNext(); if (termLink==null) break; if (taskLink.novel(termLink, time)) { //return, will be re-inserted in caller method when finished processing it return termLink; } returnTermLink(termLink); } return null; } public void returnTermLink(TermLink termLink) { termLinks.putBack(termLink, memory.param.cycles(memory.param.beliefForgetDurations), memory); } /** * Return the questions, called in ComposionalRules in * dedConjunctionByQuestion only */ public List<Task> getQuestions() { return questions; } public void discountConfidence(final boolean onBeliefs) { if (onBeliefs) { for (final Sentence s : beliefs) { s.discountConfidence(); } } else { for (final Sentence s : desires) { s.discountConfidence(); } } } /** get a random belief, weighted by their sentences confidences */ public Sentence getBeliefRandomByConfidence() { if (beliefs.isEmpty()) return null; float totalConfidence = getBeliefConfidenceSum(); float r = Memory.randomNumber.nextFloat() * totalConfidence; Sentence s = null; for (int i = 0; i < beliefs.size(); i++) { s = beliefs.get(i); r -= s.truth.getConfidence(); if (r < 0) return s; } return s; } public float getBeliefConfidenceSum() { float t = 0; for (final Sentence s : beliefs) t += s.truth.getConfidence(); return t; } public float getBeliefFrequencyMean() { if (beliefs.isEmpty()) return 0.5f; float t = 0; for (final Sentence s : beliefs) t += s.truth.getFrequency(); return t / beliefs.size(); } public CharSequence getBeliefsSummary() { if (beliefs.isEmpty()) return "0 beliefs"; StringBuilder sb = new StringBuilder(); for (Sentence s : beliefs) sb.append(s.toString()).append('\n'); return sb; } public CharSequence getDesiresSummary() { if (desires.isEmpty()) return "0 desires"; StringBuilder sb = new StringBuilder(); for (Sentence s : desires) sb.append(s.toString()).append('\n'); return sb; } }
adjustment
nars_java/nars/entity/Concept.java
adjustment
<ide><path>ars_java/nars/entity/Concept.java <ide> if (oldBelief != null) { <ide> final Stamp newStamp = judg.stamp; <ide> final Stamp oldStamp = oldBelief.stamp; <del> if (newStamp.equals(oldStamp,false,true,true,true)) { <add> if (newStamp.equals(oldStamp,false,false,true,true)) { <ide> if (task.getParentTask() != null && task.getParentTask().sentence.isJudgment()) { <ide> //task.budget.decPriority(0); // duplicated task <ide> } // else: activated belief
Java
mit
971c0884f1975023da0052f3eb3c742c3f680fd5
0
elBukkit/MagicLib,elBukkit/MagicPlugin,elBukkit/MagicPlugin,elBukkit/MagicPlugin
package com.elmakers.mine.bukkit.spell; import com.elmakers.mine.bukkit.action.ActionHandler; import com.elmakers.mine.bukkit.api.block.MaterialBrush; import com.elmakers.mine.bukkit.api.spell.SpellResult; import com.elmakers.mine.bukkit.utility.Target; import org.bukkit.Location; import org.bukkit.configuration.ConfigurationSection; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; public class ActionSpell extends BrushSpell { private Map<String, ActionHandler> actions = new HashMap<String, ActionHandler>(); private boolean undoable = false; private boolean requiresBuildPermission = false; private ActionHandler currentHandler = null; private int workThreshold = 500; @Override protected void processResult(SpellResult result, ConfigurationSection castParameters) { if (!result.isSuccess()) { ActionHandler handler = actions.get(result.name().toLowerCase()); if (handler != null) { handler.start(currentCast, castParameters); } } super.processResult(result, castParameters); } @Override public SpellResult onCast(ConfigurationSection parameters) { currentCast.setWorkAllowed(workThreshold); SpellResult result = SpellResult.CAST; currentHandler = actions.get("cast"); ActionHandler downHandler = actions.get("alternate_down"); ActionHandler upHandler = actions.get("alternate_up"); ActionHandler sneakHandler = actions.get("alternate_sneak"); workThreshold = parameters.getInt("work_threshold", 500); if (downHandler != null && isLookingDown()) { result = SpellResult.ALTERNATE_DOWN; currentHandler = downHandler; } else if (upHandler != null && isLookingUp()) { result = SpellResult.ALTERNATE_UP; currentHandler = upHandler; } else if (sneakHandler != null && mage.isSneaking()) { result = SpellResult.ALTERNATE_SNEAK; currentHandler = sneakHandler; } if (isUndoable()) { getMage().prepareForUndo(getUndoList()); } target(); if (currentHandler != null) { try { result = result.max(currentHandler.start(currentCast, parameters)); } catch (Exception ex) { controller.getLogger().log(Level.WARNING, "Spell cast failed", ex); result = SpellResult.FAIL; try { currentHandler.finish(currentCast); } catch (Exception finishException) { controller.getLogger().log(Level.WARNING, "Failed to clean up failed spell", finishException); } } } return result; } @Override public void load(ConfigurationSection data) { super.load(data); for (ActionHandler handler : actions.values()) { handler.loadData(getMage(), data); } } @Override public void save(ConfigurationSection data) { super.save(data); for (ActionHandler handler : actions.values()) { handler.saveData(getMage(), data); } } @Override protected void loadTemplate(ConfigurationSection template) { usesBrush = false; undoable = false; requiresBuildPermission = false; castOnNoTarget = true; if (template.contains("actions")) { ConfigurationSection parameters = template.getConfigurationSection("parameters"); ConfigurationSection actionsNode = template.getConfigurationSection("actions"); Collection<String> actionKeys = actionsNode.getKeys(false); for (String actionKey : actionKeys) { ActionHandler handler = new ActionHandler(); handler.load(actionsNode, actionKey); handler.initialize(parameters); usesBrush = usesBrush || handler.usesBrush(); undoable = undoable || handler.isUndoable(); requiresBuildPermission = requiresBuildPermission || handler.requiresBuildPermission(); actions.put(actionKey, handler); } } undoable = template.getBoolean("undoable", undoable); super.loadTemplate(template); } @Override public boolean isUndoable() { return undoable; } @Override public void getParameters(Collection<String> parameters) { super.getParameters(parameters); for (ActionHandler handler : actions.values()) { handler.getParameterNames(parameters); } } @Override public void getParameterOptions(Collection<String> examples, String parameterKey) { super.getParameterOptions(examples, parameterKey); for (ActionHandler handler : actions.values()) { handler.getParameterOptions(examples, parameterKey); } } @Override public String getMessage(String messageKey, String def) { String message = super.getMessage(messageKey, def); if (currentHandler != null) { message = currentHandler.transformMessage(message); } return message; } @Override public boolean requiresBuildPermission() { return requiresBuildPermission; } }
src/main/java/com/elmakers/mine/bukkit/spell/ActionSpell.java
package com.elmakers.mine.bukkit.spell; import com.elmakers.mine.bukkit.action.ActionHandler; import com.elmakers.mine.bukkit.api.block.MaterialBrush; import com.elmakers.mine.bukkit.api.spell.SpellResult; import com.elmakers.mine.bukkit.utility.Target; import org.bukkit.Location; import org.bukkit.configuration.ConfigurationSection; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; public class ActionSpell extends BrushSpell { private Map<String, ActionHandler> actions = new HashMap<String, ActionHandler>(); private boolean undoable = false; private boolean requiresBuildPermission = false; private ActionHandler currentHandler = null; private int workThreshold = 500; @Override protected void processResult(SpellResult result, ConfigurationSection castParameters) { if (!result.isSuccess()) { ActionHandler handler = actions.get(result.name().toLowerCase()); if (handler != null) { handler.start(currentCast, castParameters); } } super.processResult(result, castParameters); } @Override public SpellResult onCast(ConfigurationSection parameters) { currentCast.setWorkAllowed(workThreshold); SpellResult result = SpellResult.CAST; currentHandler = actions.get("cast"); ActionHandler downHandler = actions.get("alternate_down"); ActionHandler upHandler = actions.get("alternate_up"); ActionHandler sneakHandler = actions.get("alternate_sneak"); workThreshold = parameters.getInt("work_threshold", 500); if (downHandler != null && isLookingDown()) { result = SpellResult.ALTERNATE_DOWN; currentHandler = downHandler; } else if (upHandler != null && isLookingUp()) { result = SpellResult.ALTERNATE_UP; currentHandler = upHandler; } else if (sneakHandler != null && mage.isSneaking()) { result = SpellResult.ALTERNATE_SNEAK; currentHandler = sneakHandler; } target(); if (currentHandler != null) { try { result = result.max(currentHandler.start(currentCast, parameters)); } catch (Exception ex) { controller.getLogger().log(Level.WARNING, "Spell cast failed", ex); result = SpellResult.FAIL; try { currentHandler.finish(currentCast); } catch (Exception finishException) { controller.getLogger().log(Level.WARNING, "Failed to clean up failed spell", finishException); } } } return result; } @Override public void load(ConfigurationSection data) { super.load(data); for (ActionHandler handler : actions.values()) { handler.loadData(getMage(), data); } } @Override public void save(ConfigurationSection data) { super.save(data); for (ActionHandler handler : actions.values()) { handler.saveData(getMage(), data); } } @Override protected void loadTemplate(ConfigurationSection template) { usesBrush = false; undoable = false; requiresBuildPermission = false; castOnNoTarget = true; if (template.contains("actions")) { ConfigurationSection parameters = template.getConfigurationSection("parameters"); ConfigurationSection actionsNode = template.getConfigurationSection("actions"); Collection<String> actionKeys = actionsNode.getKeys(false); for (String actionKey : actionKeys) { ActionHandler handler = new ActionHandler(); handler.load(actionsNode, actionKey); handler.initialize(parameters); usesBrush = usesBrush || handler.usesBrush(); undoable = undoable || handler.isUndoable(); requiresBuildPermission = requiresBuildPermission || handler.requiresBuildPermission(); actions.put(actionKey, handler); } } undoable = template.getBoolean("undoable", undoable); super.loadTemplate(template); } @Override public boolean isUndoable() { return undoable; } @Override public void getParameters(Collection<String> parameters) { super.getParameters(parameters); for (ActionHandler handler : actions.values()) { handler.getParameterNames(parameters); } } @Override public void getParameterOptions(Collection<String> examples, String parameterKey) { super.getParameterOptions(examples, parameterKey); for (ActionHandler handler : actions.values()) { handler.getParameterOptions(examples, parameterKey); } } @Override public String getMessage(String messageKey, String def) { String message = super.getMessage(messageKey, def); if (currentHandler != null) { message = currentHandler.transformMessage(message); } return message; } @Override public boolean requiresBuildPermission() { return requiresBuildPermission; } }
Pre-register undo lists on ActionSpell cast
src/main/java/com/elmakers/mine/bukkit/spell/ActionSpell.java
Pre-register undo lists on ActionSpell cast
<ide><path>rc/main/java/com/elmakers/mine/bukkit/spell/ActionSpell.java <ide> { <ide> result = SpellResult.ALTERNATE_SNEAK; <ide> currentHandler = sneakHandler; <add> } <add> <add> if (isUndoable()) <add> { <add> getMage().prepareForUndo(getUndoList()); <ide> } <ide> <ide> target();
Java
apache-2.0
49054ece9f18a5af3bfaf4446fc282596ae048be
0
orientechnologies/orientdb,orientechnologies/orientdb,orientechnologies/orientdb,orientechnologies/orientdb
/* * * * Copyright 2010-2016 OrientDB LTD (http://orientdb.com) * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * * * For more information: http://orientdb.com * */ package com.orientechnologies.orient.core.storage.disk; import com.orientechnologies.common.collection.closabledictionary.OClosableLinkedContainer; import com.orientechnologies.common.directmemory.OByteBufferPool; import com.orientechnologies.common.exception.OException; import com.orientechnologies.common.io.OFileUtils; import com.orientechnologies.common.io.OIOUtils; import com.orientechnologies.common.log.OLogManager; import com.orientechnologies.common.parser.OSystemVariableResolver; import com.orientechnologies.common.serialization.types.OStringSerializer; import com.orientechnologies.common.thread.OThreadPoolExecutorWithLogging; import com.orientechnologies.orient.core.command.OCommandOutputListener; import com.orientechnologies.orient.core.compression.impl.OZIPCompressionUtil; import com.orientechnologies.orient.core.config.OContextConfiguration; import com.orientechnologies.orient.core.config.OGlobalConfiguration; import com.orientechnologies.orient.core.engine.local.OEngineLocalPaginated; import com.orientechnologies.orient.core.exception.OStorageException; import com.orientechnologies.orient.core.index.engine.v1.OCellBTreeMultiValueIndexEngine; import com.orientechnologies.orient.core.storage.OChecksumMode; import com.orientechnologies.orient.core.storage.cache.OReadCache; import com.orientechnologies.orient.core.storage.cache.local.OWOWCache; import com.orientechnologies.orient.core.storage.cache.local.twoq.O2QCache; import com.orientechnologies.orient.core.storage.cluster.OClusterPositionMap; import com.orientechnologies.orient.core.storage.config.OClusterBasedStorageConfiguration; import com.orientechnologies.orient.core.storage.fs.OFileClassic; import com.orientechnologies.orient.core.storage.impl.local.OAbstractPaginatedStorage; import com.orientechnologies.orient.core.storage.impl.local.OStorageConfigurationSegment; import com.orientechnologies.orient.core.storage.impl.local.OStorageVariableParser; import com.orientechnologies.orient.core.storage.impl.local.paginated.OPaginatedStorageDirtyFlag; import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.OLogSequenceNumber; import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.OWriteAheadLog; import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.cas.OCASDiskWriteAheadLog; import com.orientechnologies.orient.core.storage.index.engine.OHashTableIndexEngine; import com.orientechnologies.orient.core.storage.index.engine.OSBTreeIndexEngine; import com.orientechnologies.orient.core.storage.ridbag.sbtree.OIndexRIDContainer; import com.orientechnologies.orient.core.storage.ridbag.sbtree.OSBTreeCollectionManagerShared; import net.jpountz.xxhash.XXHash64; import net.jpountz.xxhash.XXHashFactory; import java.io.*; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.SecureRandom; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicReference; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * @author Andrey Lomakin (a.lomakin-at-orientdb.com) * @since 28.03.13 */ public class OLocalPaginatedStorage extends OAbstractPaginatedStorage { private static final long IV_SEED = 234120934; private static final String IV_EXT = ".iv"; private static final String IV_NAME = "data" + IV_EXT; private static final String[] ALL_FILE_EXTENSIONS = { ".cm", ".ocf", ".pls", ".pcl", ".oda", ".odh", ".otx", ".ocs", ".oef", ".oem", ".oet", ".fl", IV_EXT, OCASDiskWriteAheadLog.WAL_SEGMENT_EXTENSION, OCASDiskWriteAheadLog.MASTER_RECORD_EXTENSION, OHashTableIndexEngine.BUCKET_FILE_EXTENSION, OHashTableIndexEngine.METADATA_FILE_EXTENSION, OHashTableIndexEngine.TREE_FILE_EXTENSION, OHashTableIndexEngine.NULL_BUCKET_FILE_EXTENSION, OClusterPositionMap.DEF_EXTENSION, OSBTreeIndexEngine.DATA_FILE_EXTENSION, OIndexRIDContainer.INDEX_FILE_EXTENSION, OSBTreeCollectionManagerShared.DEFAULT_EXTENSION, OSBTreeIndexEngine.NULL_BUCKET_FILE_EXTENSION, O2QCache.CACHE_STATISTIC_FILE_EXTENSION, OClusterBasedStorageConfiguration.MAP_FILE_EXTENSION, OClusterBasedStorageConfiguration.DATA_FILE_EXTENSION, OClusterBasedStorageConfiguration.TREE_DATA_FILE_EXTENSION, OClusterBasedStorageConfiguration.TREE_NULL_FILE_EXTENSION, OCellBTreeMultiValueIndexEngine.DATA_FILE_EXTENSION, OCellBTreeMultiValueIndexEngine.M_CONTAINER_EXTENSION }; private static final int ONE_KB = 1024; private static final OThreadPoolExecutorWithLogging segmentAdderExecutor; static { segmentAdderExecutor = new OThreadPoolExecutorWithLogging(0, 1, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), new SegmentAppenderFactory()); } private final int deleteMaxRetries; private final int deleteWaitTime; private final OStorageVariableParser variableParser; private final OPaginatedStorageDirtyFlag dirtyFlag; private final Path storagePath; private final OClosableLinkedContainer<Long, OFileClassic> files; private Future<?> fuzzyCheckpointTask; private final long walMaxSegSize; private final AtomicReference<Future<Void>> segmentAppender = new AtomicReference<>(); private volatile byte[] iv; public OLocalPaginatedStorage(final String name, final String filePath, final String mode, final int id, final OReadCache readCache, final OClosableLinkedContainer<Long, OFileClassic> files, final long walMaxSegSize) { super(name, filePath, mode, id); this.walMaxSegSize = walMaxSegSize; this.files = files; this.readCache = readCache; final String sp = OSystemVariableResolver.resolveSystemVariables(OFileUtils.getPath(new File(url).getPath())); storagePath = Paths.get(OIOUtils.getPathFromDatabaseName(sp)); variableParser = new OStorageVariableParser(storagePath); deleteMaxRetries = OGlobalConfiguration.FILE_DELETE_RETRY.getValueAsInteger(); deleteWaitTime = OGlobalConfiguration.FILE_DELETE_DELAY.getValueAsInteger(); dirtyFlag = new OPaginatedStorageDirtyFlag(storagePath.resolve("dirty.fl")); } @SuppressWarnings("CanBeFinal") @Override public void create(final OContextConfiguration contextConfiguration) { try { stateLock.acquireWriteLock(); try { final Path storageFolder = storagePath; if (!Files.exists(storageFolder)) Files.createDirectories(storageFolder); super.create(contextConfiguration); } finally { stateLock.releaseWriteLock(); } } catch (final RuntimeException e) { throw logAndPrepareForRethrow(e); } catch (final Error e) { throw logAndPrepareForRethrow(e); } catch (final Throwable t) { throw logAndPrepareForRethrow(t); } } @Override protected final String normalizeName(final String name) { final int firstIndexOf = name.lastIndexOf('/'); final int secondIndexOf = name.lastIndexOf(File.separator); if (firstIndexOf >= 0 || secondIndexOf >= 0) return name.substring(Math.max(firstIndexOf, secondIndexOf) + 1); else return name; } @Override public final boolean exists() { try { if (status == STATUS.OPEN) return true; return exists(storagePath); } catch (final RuntimeException e) { throw logAndPrepareForRethrow(e); } catch (final Error e) { throw logAndPrepareForRethrow(e); } catch (final Throwable t) { throw logAndPrepareForRethrow(t); } } @Override public String getURL() { return OEngineLocalPaginated.NAME + ":" + url; } public final Path getStoragePath() { return storagePath; } public OStorageVariableParser getVariableParser() { return variableParser; } @Override public String getType() { return OEngineLocalPaginated.NAME; } @Override public final List<String> backup(final OutputStream out, final Map<String, Object> options, final Callable<Object> callable, final OCommandOutputListener iOutput, final int compressionLevel, final int bufferSize) { try { if (out == null) throw new IllegalArgumentException("Backup output is null"); freeze(false); try { if (callable != null) try { callable.call(); } catch (final Exception e) { OLogManager.instance().error(this, "Error on callback invocation during backup", e); } OLogSequenceNumber freezeLSN = null; if (writeAheadLog != null) { freezeLSN = writeAheadLog.begin(); writeAheadLog.addCutTillLimit(freezeLSN); } try { final OutputStream bo = bufferSize > 0 ? new BufferedOutputStream(out, bufferSize) : out; try { try (final ZipOutputStream zos = new ZipOutputStream(bo)) { zos.setComment("OrientDB Backup executed on " + new Date()); zos.setLevel(compressionLevel); final List<String> names = OZIPCompressionUtil.compressDirectory(storagePath.toString(), zos, new String[] { ".fl", O2QCache.CACHE_STATISTIC_FILE_EXTENSION, ".lock" }, iOutput); OPaginatedStorageDirtyFlag.addFileToArchive(zos, "dirty.fl"); names.add("dirty.fl"); return names; } } finally { if (bufferSize > 0) { bo.flush(); bo.close(); } } } finally { if (freezeLSN != null) { writeAheadLog.removeCutTillLimit(freezeLSN); } } } finally { release(); } } catch (final RuntimeException e) { throw logAndPrepareForRethrow(e); } catch (final Error e) { throw logAndPrepareForRethrow(e); } catch (final Throwable t) { throw logAndPrepareForRethrow(t); } } @Override public final void restore(final InputStream in, final Map<String, Object> options, final Callable<Object> callable, final OCommandOutputListener iListener) { try { if (!isClosed()) close(true, false); try { stateLock.acquireWriteLock(); final File dbDir = new File(OIOUtils.getPathFromDatabaseName(OSystemVariableResolver.resolveSystemVariables(url))); final File[] storageFiles = dbDir.listFiles(); if (storageFiles != null) { // TRY TO DELETE ALL THE FILES for (final File f : storageFiles) { // DELETE ONLY THE SUPPORTED FILES for (final String ext : ALL_FILE_EXTENSIONS) if (f.getPath().endsWith(ext)) { //noinspection ResultOfMethodCallIgnored f.delete(); break; } } } OZIPCompressionUtil.uncompressDirectory(in, storagePath.toString(), iListener); final Path cacheStateFile = storagePath.resolve(O2QCache.CACHE_STATE_FILE); if (Files.exists(cacheStateFile)) { String message = "the cache state file (" + O2QCache.CACHE_STATE_FILE + ") is found in the backup, deleting the file"; OLogManager.instance().warn(this, message); if (iListener != null) iListener.onMessage('\n' + message); try { Files.deleteIfExists(cacheStateFile); // delete it, if it still exists } catch (final IOException e) { message = "unable to delete the backed up cache state file (" + O2QCache.CACHE_STATE_FILE + "), please delete it manually"; OLogManager.instance().warn(this, message, e); if (iListener != null) iListener.onMessage('\n' + message); } } if (callable != null) try { callable.call(); } catch (final Exception e) { OLogManager.instance().error(this, "Error on calling callback on database restore", e); } } finally { stateLock.releaseWriteLock(); } open(null, null, new OContextConfiguration()); } catch (final RuntimeException e) { throw logAndPrepareForRethrow(e); } catch (final Error e) { throw logAndPrepareForRethrow(e); } catch (final Throwable t) { throw logAndPrepareForRethrow(t); } } @Override protected OLogSequenceNumber copyWALToIncrementalBackup(final ZipOutputStream zipOutputStream, final long startSegment) throws IOException { File[] nonActiveSegments; OLogSequenceNumber lastLSN; final long freezeId = getAtomicOperationsManager().freezeAtomicOperations(null, null); try { lastLSN = writeAheadLog.end(); writeAheadLog.flush(); writeAheadLog.appendNewSegment(); nonActiveSegments = writeAheadLog.nonActiveSegments(startSegment); } finally { getAtomicOperationsManager().releaseAtomicOperations(freezeId); } for (final File nonActiveSegment : nonActiveSegments) { try (final FileInputStream fileInputStream = new FileInputStream(nonActiveSegment)) { try (final BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream)) { final ZipEntry entry = new ZipEntry(nonActiveSegment.getName()); zipOutputStream.putNextEntry(entry); try { final byte[] buffer = new byte[4096]; int br; while ((br = bufferedInputStream.read(buffer)) >= 0) { zipOutputStream.write(buffer, 0, br); } } finally { zipOutputStream.closeEntry(); } } } } return lastLSN; } @Override protected File createWalTempDirectory() { final File walDirectory = new File(storagePath.toFile(), "walIncrementalBackupRestoreDirectory"); if (walDirectory.exists()) { OFileUtils.deleteRecursively(walDirectory); } if (!walDirectory.mkdirs()) throw new OStorageException("Can not create temporary directory to store files created during incremental backup"); return walDirectory; } @Override protected void addFileToDirectory(final String name, final InputStream stream, final File directory) throws IOException { final byte[] buffer = new byte[4096]; int rb = -1; int bl = 0; final File walBackupFile = new File(directory, name); try (final FileOutputStream outputStream = new FileOutputStream(walBackupFile)) { try (final BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream)) { do { while (bl < buffer.length && (rb = stream.read(buffer, bl, buffer.length - bl)) > -1) { bl += rb; } bufferedOutputStream.write(buffer, 0, bl); bl = 0; } while (rb >= 0); } } } @Override protected OWriteAheadLog createWalFromIBUFiles(final File directory, final OContextConfiguration contextConfiguration, final Locale locale) throws IOException { final String aesKeyEncoded = contextConfiguration.getValueAsString(OGlobalConfiguration.STORAGE_ENCRYPTION_KEY); final byte[] aesKey = aesKeyEncoded == null ? null : Base64.getDecoder().decode(aesKeyEncoded); return new OCASDiskWriteAheadLog(name, storagePath, directory.toPath(), contextConfiguration.getValueAsInteger(OGlobalConfiguration.WAL_CACHE_SIZE), contextConfiguration.getValueAsInteger(OGlobalConfiguration.WAL_BUFFER_SIZE), aesKey, iv, contextConfiguration.getValueAsLong(OGlobalConfiguration.WAL_SEGMENTS_INTERVAL) * 60 * 1_000_000_000L, contextConfiguration.getValueAsInteger(OGlobalConfiguration.WAL_MAX_SEGMENT_SIZE) * 1024 * 1024L, 10, true, locale, OGlobalConfiguration.WAL_MAX_SIZE.getValueAsLong() * 1024 * 1024, OGlobalConfiguration.DISK_CACHE_FREE_SPACE_LIMIT.getValueAsLong() * 1024 * 1024, contextConfiguration.getValueAsInteger(OGlobalConfiguration.WAL_COMMIT_TIMEOUT), contextConfiguration.getValueAsBoolean(OGlobalConfiguration.WAL_ALLOW_DIRECT_IO), contextConfiguration.getValueAsBoolean(OGlobalConfiguration.STORAGE_CALL_FSYNC), contextConfiguration.getValueAsBoolean(OGlobalConfiguration.STORAGE_PRINT_WAL_PERFORMANCE_STATISTICS), contextConfiguration.getValueAsInteger(OGlobalConfiguration.STORAGE_PRINT_WAL_PERFORMANCE_INTERVAL)); } @Override protected void checkIfStorageDirty() throws IOException { if (dirtyFlag.exists()) dirtyFlag.open(); else { dirtyFlag.create(); dirtyFlag.makeDirty(); } } @Override protected void initConfiguration(final OContextConfiguration contextConfiguration) throws IOException { if (!OClusterBasedStorageConfiguration.exists(writeCache) && Files.exists(storagePath.resolve("database.ocf"))) { final OStorageConfigurationSegment oldConfig = new OStorageConfigurationSegment(this); oldConfig.load(contextConfiguration); final OClusterBasedStorageConfiguration atomicConfiguration = new OClusterBasedStorageConfiguration(this); atomicConfiguration.create(contextConfiguration, oldConfig); configuration = atomicConfiguration; oldConfig.close(); Files.deleteIfExists(storagePath.resolve("database.ocf")); } if (configuration == null) { configuration = new OClusterBasedStorageConfiguration(this); ((OClusterBasedStorageConfiguration) configuration).load(contextConfiguration); } } @Override protected Map<String, Object> preCloseSteps() { final Map<String, Object> params = super.preCloseSteps(); if (fuzzyCheckpointTask != null) { fuzzyCheckpointTask.cancel(false); } return params; } @Override protected void postCloseStepsAfterLock(final Map<String, Object> params) { super.postCloseStepsAfterLock(params); } @Override protected void preCreateSteps() throws IOException { dirtyFlag.create(); } @Override protected void postCloseSteps(final boolean onDelete, final boolean jvmError) throws IOException { if (onDelete) { dirtyFlag.delete(); } else { if (!jvmError) { dirtyFlag.clearDirty(); } dirtyFlag.close(); } } @Override protected void postDeleteSteps() { String databasePath = OIOUtils.getPathFromDatabaseName(OSystemVariableResolver.resolveSystemVariables(url)); deleteFilesFromDisc(name, deleteMaxRetries, deleteWaitTime, databasePath); } public static void deleteFilesFromDisc(String name, int maxRetries, int waitTime, String databaseDirectory) { File dbDir;// GET REAL DIRECTORY dbDir = new File(databaseDirectory); if (!dbDir.exists() || !dbDir.isDirectory()) dbDir = dbDir.getParentFile(); // RETRIES for (int i = 0; i < maxRetries; ++i) { if (dbDir != null && dbDir.exists() && dbDir.isDirectory()) { int notDeletedFiles = 0; final File[] storageFiles = dbDir.listFiles(); if (storageFiles == null) continue; // TRY TO DELETE ALL THE FILES for (final File f : storageFiles) { // DELETE ONLY THE SUPPORTED FILES for (final String ext : ALL_FILE_EXTENSIONS) if (f.getPath().endsWith(ext)) { if (!f.delete()) { notDeletedFiles++; } break; } } if (notDeletedFiles == 0) { // TRY TO DELETE ALSO THE DIRECTORY IF IT'S EMPTY if (!dbDir.delete()) OLogManager.instance().error(OLocalPaginatedStorage.class, "Cannot delete storage directory with path " + dbDir.getAbsolutePath() + " because directory is not empty. Files: " + Arrays.toString(dbDir.listFiles()), null); return; } } else return; OLogManager.instance().debug(OLocalPaginatedStorage.class, "Cannot delete database files because they are still locked by the OrientDB process: waiting %d ms and retrying %d/%d...", waitTime, i, maxRetries); } throw new OStorageException("Cannot delete database '" + name + "' located in: " + dbDir + ". Database files seem locked"); } @Override protected void makeStorageDirty() throws IOException { dirtyFlag.makeDirty(); } @Override protected void clearStorageDirty() throws IOException { dirtyFlag.clearDirty(); } @Override protected boolean isDirty() { return dirtyFlag.isDirty(); } @Override protected boolean isWriteAllowedDuringIncrementalBackup() { return true; } @Override protected void initIv() throws IOException { try (final RandomAccessFile ivFile = new RandomAccessFile(storagePath.resolve(IV_NAME).toAbsolutePath().toFile(), "rw")) { final byte[] iv = new byte[16]; final SecureRandom random = new SecureRandom(); random.nextBytes(iv); final XXHashFactory hashFactory = XXHashFactory.fastestInstance(); final XXHash64 hash64 = hashFactory.hash64(); final long hash = hash64.hash(iv, 0, iv.length, IV_SEED); ivFile.write(iv); ivFile.writeLong(hash); ivFile.getFD().sync(); this.iv = iv; } } @Override protected void readIv() throws IOException { final Path ivPath = storagePath.resolve(IV_NAME).toAbsolutePath(); if (!Files.exists(ivPath)) { OLogManager.instance().info(this, "IV file is absent, will create new one."); initIv(); return; } try (final RandomAccessFile ivFile = new RandomAccessFile(ivPath.toFile(), "r")) { final byte[] iv = new byte[16]; ivFile.read(iv); final long storedHash = ivFile.readLong(); final XXHashFactory hashFactory = XXHashFactory.fastestInstance(); final XXHash64 hash64 = hashFactory.hash64(); final long expectedHash = hash64.hash(iv, 0, iv.length, IV_SEED); if (storedHash != expectedHash) { throw new OStorageException("iv data are broken"); } this.iv = iv; } } @Override protected byte[] getIv() { return iv; } @Override protected void initWalAndDiskCache(final OContextConfiguration contextConfiguration) throws IOException, InterruptedException { final String aesKeyEncoded = contextConfiguration.getValueAsString(OGlobalConfiguration.STORAGE_ENCRYPTION_KEY); final byte[] aesKey = aesKeyEncoded == null ? null : Base64.getDecoder().decode(aesKeyEncoded); if (contextConfiguration.getValueAsBoolean(OGlobalConfiguration.USE_WAL)) { fuzzyCheckpointTask = fuzzyCheckpointExecutor.scheduleWithFixedDelay(new PeriodicFuzzyCheckpoint(), contextConfiguration.getValueAsInteger(OGlobalConfiguration.WAL_FUZZY_CHECKPOINT_INTERVAL), contextConfiguration.getValueAsInteger(OGlobalConfiguration.WAL_FUZZY_CHECKPOINT_INTERVAL), TimeUnit.SECONDS); final String configWalPath = contextConfiguration.getValueAsString(OGlobalConfiguration.WAL_LOCATION); final Path walPath; if (configWalPath == null) { walPath = null; } else { walPath = Paths.get(configWalPath); } final OCASDiskWriteAheadLog diskWriteAheadLog = new OCASDiskWriteAheadLog(name, storagePath, walPath, contextConfiguration.getValueAsInteger(OGlobalConfiguration.WAL_CACHE_SIZE), contextConfiguration.getValueAsInteger(OGlobalConfiguration.WAL_BUFFER_SIZE), aesKey, iv, contextConfiguration.getValueAsLong(OGlobalConfiguration.WAL_SEGMENTS_INTERVAL) * 60 * 1_000_000_000L, walMaxSegSize, 10, true, Locale.getDefault(), contextConfiguration.getValueAsLong(OGlobalConfiguration.WAL_MAX_SIZE) * 1024 * 1024, contextConfiguration.getValueAsLong(OGlobalConfiguration.DISK_CACHE_FREE_SPACE_LIMIT) * 1024 * 1024, contextConfiguration.getValueAsInteger(OGlobalConfiguration.WAL_COMMIT_TIMEOUT), contextConfiguration.getValueAsBoolean(OGlobalConfiguration.WAL_ALLOW_DIRECT_IO), contextConfiguration.getValueAsBoolean(OGlobalConfiguration.STORAGE_CALL_FSYNC), contextConfiguration.getValueAsBoolean(OGlobalConfiguration.STORAGE_PRINT_WAL_PERFORMANCE_STATISTICS), contextConfiguration.getValueAsInteger(OGlobalConfiguration.STORAGE_PRINT_WAL_PERFORMANCE_INTERVAL)); diskWriteAheadLog.addLowDiskSpaceListener(this); writeAheadLog = diskWriteAheadLog; writeAheadLog.addFullCheckpointListener(this); diskWriteAheadLog.addSegmentOverflowListener((segment) -> { if (status != STATUS.OPEN) { return; } final Future<Void> oldAppender = segmentAppender.get(); if (oldAppender == null || oldAppender.isDone()) { final Future<Void> appender = segmentAdderExecutor.submit(new SegmentAdder(segment, diskWriteAheadLog)); if (segmentAppender.compareAndSet(oldAppender, appender)) { return; } appender.cancel(false); } }); } else { writeAheadLog = null; } final int pageSize = contextConfiguration.getValueAsInteger(OGlobalConfiguration.DISK_CACHE_PAGE_SIZE) * ONE_KB; final long diskCacheSize = contextConfiguration.getValueAsLong(OGlobalConfiguration.DISK_CACHE_SIZE) * 1024 * 1024; final long writeCacheSize = (long) (contextConfiguration.getValueAsInteger(OGlobalConfiguration.DISK_WRITE_CACHE_PART) / 100.0 * diskCacheSize); final boolean printCacheStatistics = contextConfiguration .getValueAsBoolean(OGlobalConfiguration.DISK_CACHE_PRINT_CACHE_STATISTICS); final int statisticsPrintInterval = contextConfiguration.getValueAsInteger(OGlobalConfiguration.DISK_CACHE_STATISTICS_INTERVAL); final OWOWCache wowCache = new OWOWCache(pageSize, OByteBufferPool.instance(null), writeAheadLog, contextConfiguration.getValueAsInteger(OGlobalConfiguration.DISK_WRITE_CACHE_PAGE_FLUSH_INTERVAL), contextConfiguration.getValueAsInteger(OGlobalConfiguration.WAL_SHUTDOWN_TIMEOUT), writeCacheSize, storagePath, getName(), OStringSerializer.INSTANCE, files, getId(), contextConfiguration.getValueAsEnum(OGlobalConfiguration.STORAGE_CHECKSUM_MODE, OChecksumMode.class), iv, aesKey, contextConfiguration.getValueAsBoolean(OGlobalConfiguration.STORAGE_CALL_FSYNC), printCacheStatistics, statisticsPrintInterval); wowCache.addLowDiskSpaceListener(this); wowCache.loadRegisteredFiles(); wowCache.addBackgroundExceptionListener(this); wowCache.addPageIsBrokenListener(this); writeCache = wowCache; } public static boolean exists(final Path path) { try { final boolean[] exists = new boolean[1]; if (Files.exists(path)) { try (final DirectoryStream<Path> stream = Files.newDirectoryStream(path)) { stream.forEach((p) -> { final String fileName = p.getFileName().toString(); if (fileName.equals("database.ocf") || (fileName.startsWith("config") && fileName.endsWith(".bd"))) { exists[0] = true; } }); } return exists[0]; } return false; } catch (final IOException e) { throw OException.wrapException(new OStorageException("Error during fetching list of files"), e); } } private class PeriodicFuzzyCheckpoint implements Runnable { @Override public final void run() { try { makeFuzzyCheckpoint(); } catch (final RuntimeException e) { OLogManager.instance().error(this, "Error during fuzzy checkpoint", e); } } } private final class SegmentAdder implements Callable<Void> { private final long segment; private final OCASDiskWriteAheadLog wal; SegmentAdder(final long segment, final OCASDiskWriteAheadLog wal) { this.segment = segment; this.wal = wal; } @Override public Void call() { try { if (status != STATUS.OPEN) { return null; } stateLock.acquireReadLock(); try { if (status != STATUS.OPEN) { return null; } final long freezeId = atomicOperationsManager.freezeAtomicOperations(null, null); try { wal.appendSegment(segment + 1); } finally { atomicOperationsManager.releaseAtomicOperations(freezeId); } } finally { stateLock.releaseReadLock(); } } catch (final Exception e) { OLogManager.instance().errorNoDb(this, "Error during addition of new segment in storage %s.", e, getName()); throw e; } return null; } } private static final class SegmentAppenderFactory implements ThreadFactory { SegmentAppenderFactory() { } @Override public Thread newThread(final Runnable r) { return new Thread(OAbstractPaginatedStorage.storageThreadGroup, r, "Segment adder thread"); } } }
core/src/main/java/com/orientechnologies/orient/core/storage/disk/OLocalPaginatedStorage.java
/* * * * Copyright 2010-2016 OrientDB LTD (http://orientdb.com) * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * * * For more information: http://orientdb.com * */ package com.orientechnologies.orient.core.storage.disk; import com.orientechnologies.common.collection.closabledictionary.OClosableLinkedContainer; import com.orientechnologies.common.directmemory.OByteBufferPool; import com.orientechnologies.common.exception.OException; import com.orientechnologies.common.io.OFileUtils; import com.orientechnologies.common.io.OIOUtils; import com.orientechnologies.common.log.OLogManager; import com.orientechnologies.common.parser.OSystemVariableResolver; import com.orientechnologies.common.serialization.types.OStringSerializer; import com.orientechnologies.common.thread.OThreadPoolExecutorWithLogging; import com.orientechnologies.orient.core.command.OCommandOutputListener; import com.orientechnologies.orient.core.compression.impl.OZIPCompressionUtil; import com.orientechnologies.orient.core.config.OContextConfiguration; import com.orientechnologies.orient.core.config.OGlobalConfiguration; import com.orientechnologies.orient.core.engine.local.OEngineLocalPaginated; import com.orientechnologies.orient.core.exception.OStorageException; import com.orientechnologies.orient.core.index.engine.v1.OCellBTreeMultiValueIndexEngine; import com.orientechnologies.orient.core.storage.OChecksumMode; import com.orientechnologies.orient.core.storage.cache.OReadCache; import com.orientechnologies.orient.core.storage.cache.local.OWOWCache; import com.orientechnologies.orient.core.storage.cache.local.twoq.O2QCache; import com.orientechnologies.orient.core.storage.cluster.OClusterPositionMap; import com.orientechnologies.orient.core.storage.config.OClusterBasedStorageConfiguration; import com.orientechnologies.orient.core.storage.fs.OFileClassic; import com.orientechnologies.orient.core.storage.impl.local.OAbstractPaginatedStorage; import com.orientechnologies.orient.core.storage.impl.local.OStorageConfigurationSegment; import com.orientechnologies.orient.core.storage.impl.local.OStorageVariableParser; import com.orientechnologies.orient.core.storage.impl.local.paginated.OPaginatedStorageDirtyFlag; import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.OLogSequenceNumber; import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.OWriteAheadLog; import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.cas.OCASDiskWriteAheadLog; import com.orientechnologies.orient.core.storage.index.engine.OHashTableIndexEngine; import com.orientechnologies.orient.core.storage.index.engine.OSBTreeIndexEngine; import com.orientechnologies.orient.core.storage.ridbag.sbtree.OIndexRIDContainer; import com.orientechnologies.orient.core.storage.ridbag.sbtree.OSBTreeCollectionManagerShared; import net.jpountz.xxhash.XXHash64; import net.jpountz.xxhash.XXHashFactory; import java.io.*; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.SecureRandom; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicReference; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * @author Andrey Lomakin (a.lomakin-at-orientdb.com) * @since 28.03.13 */ public class OLocalPaginatedStorage extends OAbstractPaginatedStorage { private static final long IV_SEED = 234120934; private static final String IV_EXT = ".iv"; private static final String IV_NAME = "data" + IV_EXT; private static final String[] ALL_FILE_EXTENSIONS = { ".cm", ".ocf", ".pls", ".pcl", ".oda", ".odh", ".otx", ".ocs", ".oef", ".oem", ".oet", ".fl", IV_EXT, OCASDiskWriteAheadLog.WAL_SEGMENT_EXTENSION, OCASDiskWriteAheadLog.MASTER_RECORD_EXTENSION, OHashTableIndexEngine.BUCKET_FILE_EXTENSION, OHashTableIndexEngine.METADATA_FILE_EXTENSION, OHashTableIndexEngine.TREE_FILE_EXTENSION, OHashTableIndexEngine.NULL_BUCKET_FILE_EXTENSION, OClusterPositionMap.DEF_EXTENSION, OSBTreeIndexEngine.DATA_FILE_EXTENSION, OIndexRIDContainer.INDEX_FILE_EXTENSION, OSBTreeCollectionManagerShared.DEFAULT_EXTENSION, OSBTreeIndexEngine.NULL_BUCKET_FILE_EXTENSION, O2QCache.CACHE_STATISTIC_FILE_EXTENSION, OClusterBasedStorageConfiguration.MAP_FILE_EXTENSION, OClusterBasedStorageConfiguration.DATA_FILE_EXTENSION, OClusterBasedStorageConfiguration.TREE_DATA_FILE_EXTENSION, OClusterBasedStorageConfiguration.TREE_NULL_FILE_EXTENSION, OCellBTreeMultiValueIndexEngine.DATA_FILE_EXTENSION, OCellBTreeMultiValueIndexEngine.M_CONTAINER_EXTENSION }; private static final int ONE_KB = 1024; private static final OThreadPoolExecutorWithLogging segmentAdderExecutor; static { segmentAdderExecutor = new OThreadPoolExecutorWithLogging(0, 1, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), new SegmentAppenderFactory()); } private final int deleteMaxRetries; private final int deleteWaitTime; private final OStorageVariableParser variableParser; private final OPaginatedStorageDirtyFlag dirtyFlag; private final Path storagePath; private final OClosableLinkedContainer<Long, OFileClassic> files; private Future<?> fuzzyCheckpointTask; private final long walMaxSegSize; private final AtomicReference<Future<Void>> segmentAppender = new AtomicReference<>(); private volatile byte[] iv; public OLocalPaginatedStorage(final String name, final String filePath, final String mode, final int id, final OReadCache readCache, final OClosableLinkedContainer<Long, OFileClassic> files, final long walMaxSegSize) { super(name, filePath, mode, id); this.walMaxSegSize = walMaxSegSize; this.files = files; this.readCache = readCache; final String sp = OSystemVariableResolver.resolveSystemVariables(OFileUtils.getPath(new File(url).getPath())); storagePath = Paths.get(OIOUtils.getPathFromDatabaseName(sp)); variableParser = new OStorageVariableParser(storagePath); deleteMaxRetries = OGlobalConfiguration.FILE_DELETE_RETRY.getValueAsInteger(); deleteWaitTime = OGlobalConfiguration.FILE_DELETE_DELAY.getValueAsInteger(); dirtyFlag = new OPaginatedStorageDirtyFlag(storagePath.resolve("dirty.fl")); } @SuppressWarnings("CanBeFinal") @Override public void create(final OContextConfiguration contextConfiguration) { try { stateLock.acquireWriteLock(); try { final Path storageFolder = storagePath; if (!Files.exists(storageFolder)) Files.createDirectories(storageFolder); super.create(contextConfiguration); } finally { stateLock.releaseWriteLock(); } } catch (final RuntimeException e) { throw logAndPrepareForRethrow(e); } catch (final Error e) { throw logAndPrepareForRethrow(e); } catch (final Throwable t) { throw logAndPrepareForRethrow(t); } } @Override protected final String normalizeName(final String name) { final int firstIndexOf = name.lastIndexOf('/'); final int secondIndexOf = name.lastIndexOf(File.separator); if (firstIndexOf >= 0 || secondIndexOf >= 0) return name.substring(Math.max(firstIndexOf, secondIndexOf) + 1); else return name; } @Override public final boolean exists() { try { if (status == STATUS.OPEN) return true; return exists(storagePath); } catch (final RuntimeException e) { throw logAndPrepareForRethrow(e); } catch (final Error e) { throw logAndPrepareForRethrow(e); } catch (final Throwable t) { throw logAndPrepareForRethrow(t); } } @Override public String getURL() { return OEngineLocalPaginated.NAME + ":" + url; } public final Path getStoragePath() { return storagePath; } public OStorageVariableParser getVariableParser() { return variableParser; } @Override public String getType() { return OEngineLocalPaginated.NAME; } @Override public final List<String> backup(final OutputStream out, final Map<String, Object> options, final Callable<Object> callable, final OCommandOutputListener iOutput, final int compressionLevel, final int bufferSize) { try { if (out == null) throw new IllegalArgumentException("Backup output is null"); freeze(false); try { if (callable != null) try { callable.call(); } catch (final Exception e) { OLogManager.instance().error(this, "Error on callback invocation during backup", e); } OLogSequenceNumber freezeLSN = null; if (writeAheadLog != null) { freezeLSN = writeAheadLog.begin(); writeAheadLog.addCutTillLimit(freezeLSN); } try { final OutputStream bo = bufferSize > 0 ? new BufferedOutputStream(out, bufferSize) : out; try { try (final ZipOutputStream zos = new ZipOutputStream(bo)) { zos.setComment("OrientDB Backup executed on " + new Date()); zos.setLevel(compressionLevel); final List<String> names = OZIPCompressionUtil.compressDirectory(storagePath.toString(), zos, new String[] { ".fl", O2QCache.CACHE_STATISTIC_FILE_EXTENSION, ".lock" }, iOutput); OPaginatedStorageDirtyFlag.addFileToArchive(zos, "dirty.fl"); names.add("dirty.fl"); return names; } } finally { if (bufferSize > 0) { bo.flush(); bo.close(); } } } finally { if (freezeLSN != null) { writeAheadLog.removeCutTillLimit(freezeLSN); } } } finally { release(); } } catch (final RuntimeException e) { throw logAndPrepareForRethrow(e); } catch (final Error e) { throw logAndPrepareForRethrow(e); } catch (final Throwable t) { throw logAndPrepareForRethrow(t); } } @Override public final void restore(final InputStream in, final Map<String, Object> options, final Callable<Object> callable, final OCommandOutputListener iListener) { try { if (!isClosed()) close(true, false); try { stateLock.acquireWriteLock(); final File dbDir = new File(OIOUtils.getPathFromDatabaseName(OSystemVariableResolver.resolveSystemVariables(url))); final File[] storageFiles = dbDir.listFiles(); if (storageFiles != null) { // TRY TO DELETE ALL THE FILES for (final File f : storageFiles) { // DELETE ONLY THE SUPPORTED FILES for (final String ext : ALL_FILE_EXTENSIONS) if (f.getPath().endsWith(ext)) { //noinspection ResultOfMethodCallIgnored f.delete(); break; } } } OZIPCompressionUtil.uncompressDirectory(in, storagePath.toString(), iListener); final Path cacheStateFile = storagePath.resolve(O2QCache.CACHE_STATE_FILE); if (Files.exists(cacheStateFile)) { String message = "the cache state file (" + O2QCache.CACHE_STATE_FILE + ") is found in the backup, deleting the file"; OLogManager.instance().warn(this, message); if (iListener != null) iListener.onMessage('\n' + message); try { Files.deleteIfExists(cacheStateFile); // delete it, if it still exists } catch (final IOException e) { message = "unable to delete the backed up cache state file (" + O2QCache.CACHE_STATE_FILE + "), please delete it manually"; OLogManager.instance().warn(this, message, e); if (iListener != null) iListener.onMessage('\n' + message); } } if (callable != null) try { callable.call(); } catch (final Exception e) { OLogManager.instance().error(this, "Error on calling callback on database restore", e); } } finally { stateLock.releaseWriteLock(); } open(null, null, new OContextConfiguration()); } catch (final RuntimeException e) { throw logAndPrepareForRethrow(e); } catch (final Error e) { throw logAndPrepareForRethrow(e); } catch (final Throwable t) { throw logAndPrepareForRethrow(t); } } @Override protected OLogSequenceNumber copyWALToIncrementalBackup(final ZipOutputStream zipOutputStream, final long startSegment) throws IOException { File[] nonActiveSegments; OLogSequenceNumber lastLSN; final long freezeId = getAtomicOperationsManager().freezeAtomicOperations(null, null); try { lastLSN = writeAheadLog.end(); writeAheadLog.flush(); writeAheadLog.appendNewSegment(); nonActiveSegments = writeAheadLog.nonActiveSegments(startSegment); } finally { getAtomicOperationsManager().releaseAtomicOperations(freezeId); } for (final File nonActiveSegment : nonActiveSegments) { try (final FileInputStream fileInputStream = new FileInputStream(nonActiveSegment)) { try (final BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream)) { final ZipEntry entry = new ZipEntry(nonActiveSegment.getName()); zipOutputStream.putNextEntry(entry); try { final byte[] buffer = new byte[4096]; int br; while ((br = bufferedInputStream.read(buffer)) >= 0) { zipOutputStream.write(buffer, 0, br); } } finally { zipOutputStream.closeEntry(); } } } } return lastLSN; } @Override protected File createWalTempDirectory() { final File walDirectory = new File(storagePath.toFile(), "walIncrementalBackupRestoreDirectory"); if (walDirectory.exists()) { OFileUtils.deleteRecursively(walDirectory); } if (!walDirectory.mkdirs()) throw new OStorageException("Can not create temporary directory to store files created during incremental backup"); return walDirectory; } @Override protected void addFileToDirectory(final String name, final InputStream stream, final File directory) throws IOException { final byte[] buffer = new byte[4096]; int rb = -1; int bl = 0; final File walBackupFile = new File(directory, name); try (final FileOutputStream outputStream = new FileOutputStream(walBackupFile)) { try (final BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream)) { do { while (bl < buffer.length && (rb = stream.read(buffer, bl, buffer.length - bl)) > -1) { bl += rb; } bufferedOutputStream.write(buffer, 0, bl); bl = 0; } while (rb >= 0); } } } @Override protected OWriteAheadLog createWalFromIBUFiles(final File directory, final OContextConfiguration contextConfiguration, final Locale locale) throws IOException { final String aesKeyEncoded = contextConfiguration.getValueAsString(OGlobalConfiguration.STORAGE_ENCRYPTION_KEY); final byte[] aesKey = aesKeyEncoded == null ? null : Base64.getDecoder().decode(aesKeyEncoded); return new OCASDiskWriteAheadLog(name, storagePath, directory.toPath(), contextConfiguration.getValueAsInteger(OGlobalConfiguration.WAL_CACHE_SIZE), contextConfiguration.getValueAsInteger(OGlobalConfiguration.WAL_BUFFER_SIZE), aesKey, iv, contextConfiguration.getValueAsLong(OGlobalConfiguration.WAL_SEGMENTS_INTERVAL) * 60 * 1_000_000_000L, contextConfiguration.getValueAsInteger(OGlobalConfiguration.WAL_MAX_SEGMENT_SIZE) * 1024 * 1024L, 10, true, locale, OGlobalConfiguration.WAL_MAX_SIZE.getValueAsLong() * 1024 * 1024, OGlobalConfiguration.DISK_CACHE_FREE_SPACE_LIMIT.getValueAsLong() * 1024 * 1024, contextConfiguration.getValueAsInteger(OGlobalConfiguration.WAL_COMMIT_TIMEOUT), contextConfiguration.getValueAsBoolean(OGlobalConfiguration.WAL_ALLOW_DIRECT_IO), contextConfiguration.getValueAsBoolean(OGlobalConfiguration.STORAGE_CALL_FSYNC), contextConfiguration.getValueAsBoolean(OGlobalConfiguration.STORAGE_PRINT_WAL_PERFORMANCE_STATISTICS), contextConfiguration.getValueAsInteger(OGlobalConfiguration.STORAGE_PRINT_WAL_PERFORMANCE_INTERVAL)); } @Override protected void checkIfStorageDirty() throws IOException { if (dirtyFlag.exists()) dirtyFlag.open(); else { dirtyFlag.create(); dirtyFlag.makeDirty(); } } @Override protected void initConfiguration(final OContextConfiguration contextConfiguration) throws IOException { if (!OClusterBasedStorageConfiguration.exists(writeCache) && Files.exists(storagePath.resolve("database.ocf"))) { final OStorageConfigurationSegment oldConfig = new OStorageConfigurationSegment(this); oldConfig.load(contextConfiguration); final OClusterBasedStorageConfiguration atomicConfiguration = new OClusterBasedStorageConfiguration(this); atomicConfiguration.create(contextConfiguration, oldConfig); configuration = atomicConfiguration; oldConfig.close(); Files.deleteIfExists(storagePath.resolve("database.ocf")); } if (configuration == null) { configuration = new OClusterBasedStorageConfiguration(this); ((OClusterBasedStorageConfiguration) configuration).load(contextConfiguration); } } @Override protected Map<String, Object> preCloseSteps() { final Map<String, Object> params = super.preCloseSteps(); if (fuzzyCheckpointTask != null) { fuzzyCheckpointTask.cancel(false); } return params; } @Override protected void postCloseStepsAfterLock(final Map<String, Object> params) { super.postCloseStepsAfterLock(params); } @Override protected void preCreateSteps() throws IOException { dirtyFlag.create(); } @Override protected void postCloseSteps(final boolean onDelete, final boolean jvmError) throws IOException { if (onDelete) { dirtyFlag.delete(); } else { if (!jvmError) { dirtyFlag.clearDirty(); } dirtyFlag.close(); } } @Override protected void postDeleteSteps() { String databasePath = OIOUtils.getPathFromDatabaseName(OSystemVariableResolver.resolveSystemVariables(url)); deleteFilesFromDisc(name, deleteMaxRetries, deleteWaitTime, databasePath); } public static void deleteFilesFromDisc(String name, int maxRetries, int waitTime, String databaseDirectory) { File dbDir;// GET REAL DIRECTORY dbDir = new File(databaseDirectory); if (!dbDir.exists() || !dbDir.isDirectory()) dbDir = dbDir.getParentFile(); // RETRIES for (int i = 0; i < maxRetries; ++i) { if (dbDir != null && dbDir.exists() && dbDir.isDirectory()) { int notDeletedFiles = 0; final File[] storageFiles = dbDir.listFiles(); if (storageFiles == null) continue; // TRY TO DELETE ALL THE FILES for (final File f : storageFiles) { // DELETE ONLY THE SUPPORTED FILES for (final String ext : ALL_FILE_EXTENSIONS) if (f.getPath().endsWith(ext)) { if (!f.delete()) { notDeletedFiles++; } break; } } if (notDeletedFiles == 0) { // TRY TO DELETE ALSO THE DIRECTORY IF IT'S EMPTY if (!dbDir.delete()) OLogManager.instance().error(OLocalPaginatedStorage.class, "Cannot delete storage directory with path " + dbDir.getAbsolutePath() + " because directory is not empty. Files: " + Arrays.toString(dbDir.listFiles()), null); return; } } else return; OLogManager.instance().debug(OLocalPaginatedStorage.class, "Cannot delete database files because they are still locked by the OrientDB process: waiting %d ms and retrying %d/%d...", waitTime, i, maxRetries); } throw new OStorageException("Cannot delete database '" + name + "' located in: " + dbDir + ". Database files seem locked"); } @Override protected void makeStorageDirty() throws IOException { dirtyFlag.makeDirty(); } @Override protected void clearStorageDirty() throws IOException { dirtyFlag.clearDirty(); } @Override protected boolean isDirty() { return dirtyFlag.isDirty(); } @Override protected boolean isWriteAllowedDuringIncrementalBackup() { return true; } @Override protected void initIv() throws IOException { try (final RandomAccessFile ivFile = new RandomAccessFile(storagePath.resolve(IV_NAME).toAbsolutePath().toFile(), "rw")) { final byte[] iv = new byte[16]; final SecureRandom random = new SecureRandom(); random.nextBytes(iv); final XXHashFactory hashFactory = XXHashFactory.fastestInstance(); final XXHash64 hash64 = hashFactory.hash64(); final long hash = hash64.hash(iv, 0, iv.length, IV_SEED); ivFile.write(iv); ivFile.writeLong(hash); ivFile.getFD().sync(); this.iv = iv; } } @Override protected void readIv() throws IOException { final Path ivPath = storagePath.resolve(IV_NAME).toAbsolutePath(); if (!Files.exists(ivPath)) { initIv(); return; } try (final RandomAccessFile ivFile = new RandomAccessFile(ivPath.toFile(), "r")) { final byte[] iv = new byte[16]; ivFile.read(iv); final long storedHash = ivFile.readLong(); final XXHashFactory hashFactory = XXHashFactory.fastestInstance(); final XXHash64 hash64 = hashFactory.hash64(); final long expectedHash = hash64.hash(iv, 0, iv.length, IV_SEED); if (storedHash != expectedHash) { throw new OStorageException("iv data are broken"); } this.iv = iv; } } @Override protected byte[] getIv() { return iv; } @Override protected void initWalAndDiskCache(final OContextConfiguration contextConfiguration) throws IOException, InterruptedException { final String aesKeyEncoded = contextConfiguration.getValueAsString(OGlobalConfiguration.STORAGE_ENCRYPTION_KEY); final byte[] aesKey = aesKeyEncoded == null ? null : Base64.getDecoder().decode(aesKeyEncoded); if (contextConfiguration.getValueAsBoolean(OGlobalConfiguration.USE_WAL)) { fuzzyCheckpointTask = fuzzyCheckpointExecutor.scheduleWithFixedDelay(new PeriodicFuzzyCheckpoint(), contextConfiguration.getValueAsInteger(OGlobalConfiguration.WAL_FUZZY_CHECKPOINT_INTERVAL), contextConfiguration.getValueAsInteger(OGlobalConfiguration.WAL_FUZZY_CHECKPOINT_INTERVAL), TimeUnit.SECONDS); final String configWalPath = contextConfiguration.getValueAsString(OGlobalConfiguration.WAL_LOCATION); final Path walPath; if (configWalPath == null) { walPath = null; } else { walPath = Paths.get(configWalPath); } final OCASDiskWriteAheadLog diskWriteAheadLog = new OCASDiskWriteAheadLog(name, storagePath, walPath, contextConfiguration.getValueAsInteger(OGlobalConfiguration.WAL_CACHE_SIZE), contextConfiguration.getValueAsInteger(OGlobalConfiguration.WAL_BUFFER_SIZE), aesKey, iv, contextConfiguration.getValueAsLong(OGlobalConfiguration.WAL_SEGMENTS_INTERVAL) * 60 * 1_000_000_000L, walMaxSegSize, 10, true, Locale.getDefault(), contextConfiguration.getValueAsLong(OGlobalConfiguration.WAL_MAX_SIZE) * 1024 * 1024, contextConfiguration.getValueAsLong(OGlobalConfiguration.DISK_CACHE_FREE_SPACE_LIMIT) * 1024 * 1024, contextConfiguration.getValueAsInteger(OGlobalConfiguration.WAL_COMMIT_TIMEOUT), contextConfiguration.getValueAsBoolean(OGlobalConfiguration.WAL_ALLOW_DIRECT_IO), contextConfiguration.getValueAsBoolean(OGlobalConfiguration.STORAGE_CALL_FSYNC), contextConfiguration.getValueAsBoolean(OGlobalConfiguration.STORAGE_PRINT_WAL_PERFORMANCE_STATISTICS), contextConfiguration.getValueAsInteger(OGlobalConfiguration.STORAGE_PRINT_WAL_PERFORMANCE_INTERVAL)); diskWriteAheadLog.addLowDiskSpaceListener(this); writeAheadLog = diskWriteAheadLog; writeAheadLog.addFullCheckpointListener(this); diskWriteAheadLog.addSegmentOverflowListener((segment) -> { if (status != STATUS.OPEN) { return; } final Future<Void> oldAppender = segmentAppender.get(); if (oldAppender == null || oldAppender.isDone()) { final Future<Void> appender = segmentAdderExecutor.submit(new SegmentAdder(segment, diskWriteAheadLog)); if (segmentAppender.compareAndSet(oldAppender, appender)) { return; } appender.cancel(false); } }); } else { writeAheadLog = null; } final int pageSize = contextConfiguration.getValueAsInteger(OGlobalConfiguration.DISK_CACHE_PAGE_SIZE) * ONE_KB; final long diskCacheSize = contextConfiguration.getValueAsLong(OGlobalConfiguration.DISK_CACHE_SIZE) * 1024 * 1024; final long writeCacheSize = (long) (contextConfiguration.getValueAsInteger(OGlobalConfiguration.DISK_WRITE_CACHE_PART) / 100.0 * diskCacheSize); final boolean printCacheStatistics = contextConfiguration .getValueAsBoolean(OGlobalConfiguration.DISK_CACHE_PRINT_CACHE_STATISTICS); final int statisticsPrintInterval = contextConfiguration.getValueAsInteger(OGlobalConfiguration.DISK_CACHE_STATISTICS_INTERVAL); final OWOWCache wowCache = new OWOWCache(pageSize, OByteBufferPool.instance(null), writeAheadLog, contextConfiguration.getValueAsInteger(OGlobalConfiguration.DISK_WRITE_CACHE_PAGE_FLUSH_INTERVAL), contextConfiguration.getValueAsInteger(OGlobalConfiguration.WAL_SHUTDOWN_TIMEOUT), writeCacheSize, storagePath, getName(), OStringSerializer.INSTANCE, files, getId(), contextConfiguration.getValueAsEnum(OGlobalConfiguration.STORAGE_CHECKSUM_MODE, OChecksumMode.class), iv, aesKey, contextConfiguration.getValueAsBoolean(OGlobalConfiguration.STORAGE_CALL_FSYNC), printCacheStatistics, statisticsPrintInterval); wowCache.addLowDiskSpaceListener(this); wowCache.loadRegisteredFiles(); wowCache.addBackgroundExceptionListener(this); wowCache.addPageIsBrokenListener(this); writeCache = wowCache; } public static boolean exists(final Path path) { try { final boolean[] exists = new boolean[1]; if (Files.exists(path)) { try (final DirectoryStream<Path> stream = Files.newDirectoryStream(path)) { stream.forEach((p) -> { final String fileName = p.getFileName().toString(); if (fileName.equals("database.ocf") || (fileName.startsWith("config") && fileName.endsWith(".bd"))) { exists[0] = true; } }); } return exists[0]; } return false; } catch (final IOException e) { throw OException.wrapException(new OStorageException("Error during fetching list of files"), e); } } private class PeriodicFuzzyCheckpoint implements Runnable { @Override public final void run() { try { makeFuzzyCheckpoint(); } catch (final RuntimeException e) { OLogManager.instance().error(this, "Error during fuzzy checkpoint", e); } } } private final class SegmentAdder implements Callable<Void> { private final long segment; private final OCASDiskWriteAheadLog wal; SegmentAdder(final long segment, final OCASDiskWriteAheadLog wal) { this.segment = segment; this.wal = wal; } @Override public Void call() { try { if (status != STATUS.OPEN) { return null; } stateLock.acquireReadLock(); try { if (status != STATUS.OPEN) { return null; } final long freezeId = atomicOperationsManager.freezeAtomicOperations(null, null); try { wal.appendSegment(segment + 1); } finally { atomicOperationsManager.releaseAtomicOperations(freezeId); } } finally { stateLock.releaseReadLock(); } } catch (final Exception e) { OLogManager.instance().errorNoDb(this, "Error during addition of new segment in storage %s.", e, getName()); throw e; } return null; } } private static final class SegmentAppenderFactory implements ThreadFactory { SegmentAppenderFactory() { } @Override public Thread newThread(final Runnable r) { return new Thread(OAbstractPaginatedStorage.storageThreadGroup, r, "Segment adder thread"); } } }
Backward compatibility support was added.
core/src/main/java/com/orientechnologies/orient/core/storage/disk/OLocalPaginatedStorage.java
Backward compatibility support was added.
<ide><path>ore/src/main/java/com/orientechnologies/orient/core/storage/disk/OLocalPaginatedStorage.java <ide> protected void readIv() throws IOException { <ide> final Path ivPath = storagePath.resolve(IV_NAME).toAbsolutePath(); <ide> if (!Files.exists(ivPath)) { <add> OLogManager.instance().info(this, "IV file is absent, will create new one."); <ide> initIv(); <ide> return; <ide> }
JavaScript
apache-2.0
4be85451b0ce32a15557e2b711ea4441a5fe51fe
0
open-orchestra/open-orchestra,alavieille/open-orchestra,open-orchestra/open-orchestra,alavieille/open-orchestra,alavieille/open-orchestra,open-orchestra/open-orchestra,open-orchestra/open-orchestra,alavieille/open-orchestra,alavieille/open-orchestra
module.exports = function(grunt) { grunt.loadNpmTasks('grunt-contrib-symlink'); grunt.loadNpmTasks('grunt-contrib-less'); grunt.loadNpmTasks('grunt-contrib-cssmin'); grunt.loadNpmTasks('grunt-contrib-coffee'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-commands'); var filesLess = {}, filesCoffee = {}; // Configuration grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), symlink: { // BOWER COMPONENT fontawesome_font_otf: { src: 'bower_components/font-awesome/fonts/FontAwesome.otf', dest: 'web/fonts/FontAwesome.otf' }, fontawesome_font_eot: { src: 'bower_components/font-awesome/fonts/fontawesome-webfont.eot', dest: 'web/fonts/fontawesome-webfont.eot' }, fontawesome_font_svg: { src: 'bower_components/font-awesome/fonts/fontawesome-webfont.svg', dest: 'web/fonts/fontawesome-webfont.svg' }, fontawesome_font_ttf: { src: 'bower_components/font-awesome/fonts/fontawesome-webfont.ttf', dest: 'web/fonts/fontawesome-webfont.ttf' }, fontawesome_font_woff: { src: 'bower_components/font-awesome/fonts/fontawesome-webfont.woff', dest: 'web/fonts/fontawesome-webfont.woff' }, bootstrap_font_eot: { src: 'bower_components/bootstrap/dist/fonts/glyphicons-halflings-regular.eot', dest: 'web/fonts/glyphicons-halflings-regular.eot' }, bootstrap_font_svg: { src: 'bower_components/bootstrap/dist/fonts/glyphicons-halflings-regular.svg', dest: 'web/fonts/glyphicons-halflings-regular.svg' }, bootstrap_font_ttf: { src: 'bower_components/bootstrap/dist/fonts/glyphicons-halflings-regular.ttf', dest: 'web/fonts/glyphicons-halflings-regular.ttf' }, bootstrap_font_woff: { src: 'bower_components/bootstrap/dist/fonts/glyphicons-halflings-regular.woff', dest: 'web/fonts/glyphicons-halflings-regular.woff' }, datatable_img_sort_asc: { src: 'bower_components/datatables/media/images/sort_asc.png', dest: 'web/images/sort_asc.png' }, datatable_img_sort_both: { src: 'bower_components/datatables/media/images/sort_both.png', dest: 'web/images/sort_both.png' }, datatable_img_sort_desc: { src: 'bower_components/datatables/media/images/sort_desc.png', dest: 'web/images/sort_desc.png' }, pace_js: { src: 'bower_components/pace/pace.min.js', dest: 'web/js/pace.min.js' }, jcrop_gif: { src: 'bower_components/jcrop/css/Jcrop.gif', dest: 'web/img/jcrop/Jcrop.gif' }, // SMARTADMIN ASSETS smartadmin_bg: { src: 'web/bundles/phporchestrabackoffice/smartadmin/img/mybg.png', dest: 'web/img/mybg.png' }, smartadmin_flags: { src: 'web/bundles/phporchestrabackoffice/smartadmin/img/flags/flags.png', dest: 'web/img/flags/flags.png' }, select2_gif: { src: 'web/bundles/phporchestrabackoffice/smartadmin/img/select2-spinner.gif', dest: 'web/img/select2-spinner.gif' }, // ORCHESTRA ASSET no_image: { src: 'web/bundles/phporchestrabackoffice/images/no_image_available.jpg', dest: 'web/img/no_image_available.jpg' } }, clean: { built: ["web/built"] }, less: { bundles: { files: filesLess } }, cssmin: { minify: { expand: true, src: ['web/css/all.css'], ext: '.min.css' } }, coffee: { compileBare: { options: { bare: true }, files: filesCoffee } }, uglify: { dist: { files: { 'web/js/all.min.js': ['web/js/all.js'] } } }, concat: { smartadminjs: { src: [ 'bower_components/jquery/dist/jquery.js', 'bower_components/jquery-ui/jquery-ui.js', 'web/bundles/phporchestrabackoffice/smartadmin/js/app.config.js', 'bower_components/bootstrap/dist/js/bootstrap.js', 'bower_components/jcrop/js/jquery.Jcrop.js', 'bower_components/select2/select2.js', 'web/bundles/phporchestrabackoffice/smartadmin/js/notification/SmartNotification.min.js', 'web/bundles/phporchestrabackoffice/smartadmin/js/smartwidgets/jarvis.widget.min.js', 'web/bundles/phporchestrabackoffice/smartadmin/js/app.min.js' ], dest: 'web/built/smartadmin.js' }, libjs: { src: [ 'bower_components/underscore/underscore.js', 'bower_components/backbone/backbone.js', 'bower_components/angular/angular.js', 'bower_components/datatables/media/js/jquery.dataTables.js', 'bower_components/jquery-form/jquery.form.js', 'web/bundles/phporchestrabackoffice/js/latinise.js', 'web/bundles/phporchestrabackoffice/js/jQuery.DOMNodeAppear.js', 'web/bundles/phporchestrabackoffice/js/underscoreTemplateLoader.js' ], dest: 'web/built/lib.js' }, orchestrajs: { src: [ 'web/built/phporchestrabackoffice/js/orchestraLib.js', 'web/built/phporchestrabackoffice/js/orchestraListeners.js', // MISC 'web/built/phporchestrabackoffice/js/OrchestraView.js', 'web/built/phporchestrabackoffice/js/addPrototype.js', 'web/built/phporchestrabackoffice/js/modelBackbone.js', 'web/built/phporchestrabackoffice/js/adminFormView.js', 'web/built/phporchestrabackoffice/js/generateAlias.js', 'web/built/phporchestrabackoffice/js/generateContentTypeId.js', 'web/built/phporchestrabackoffice/js/page/makeSortable.js', 'web/built/phporchestrabackoffice/js/page/areaView.js', 'web/built/phporchestrabackoffice/js/page/blockView.js', 'web/built/phporchestrabackoffice/js/page/nodeView.js', 'web/built/phporchestrabackoffice/js/VersionView.js', 'web/built/phporchestrabackoffice/js/LanguageView.js', 'web/built/phporchestrabackoffice/js/page/previewLinkView.js', 'web/built/phporchestrabackoffice/js/page/pageConfigurationButtonView.js', 'web/built/phporchestrabackoffice/js/table/TableviewView.js', 'web/built/phporchestrabackoffice/js/table/TableviewCollectionView.js', 'web/built/phporchestrabackoffice/js/FullPageFormView.js', 'web/built/phporchestrabackoffice/js/ContentTypeChangeTypeListener.js', 'web/built/phporchestrabackoffice/js/page/templateView.js', 'web/built/phporchestrabackoffice/js/page/showNode.js', 'web/built/phporchestrabackoffice/js/page/showTemplate.js', 'web/built/phporchestrabackoffice/js/table/tableviewLoader.js', 'web/built/phporchestrabackoffice/js/page/nodeConstructor.js', 'web/built/phporchestrabackoffice/js/treeAjaxDelete.js', 'web/built/phporchestrabackoffice/js/configurableContentFormListener.js', 'web/built/phporchestrabackoffice/js/page/blocksPanel.js', 'web/built/phporchestrabackoffice/js/security.js', // MEDIATHEQUE 'web/built/phporchestrabackoffice/js/mediatheque/*.js', // INDEXATION 'web/bundles/phporchestraindexation/js/*.js', // LEXIKTRANSLATION 'web/bundles/lexiktranslation/ng-table/ng-table.min.js', 'web/built/phporchestratranslation/js/translationView.js', // BACKBONE ROUTER 'web/bundles/phporchestrabackoffice/js/backboneRouter.js' ], dest: 'web/built/orchestra.js' }, js: { src: [ 'web/built/smartadmin.js', 'web/built/lib.js', 'web/built/orchestra.js' ], dest: 'web/js/all.js' }, smartadmincss: { src: [ // SMARTADMIN PACKAGE // 'bower_components/bootstrap/dist/css/bootstrap.min.css', 'web/bundles/phporchestrabackoffice/smartadmin/css/bootstrap.min.css', 'bower_components/font-awesome/css/font-awesome.min.css', 'web/bundles/phporchestrabackoffice/smartadmin/css/smartadmin-production-plugins.min.css', 'web/bundles/phporchestrabackoffice/smartadmin/css/smartadmin-production.min.css', 'web/bundles/phporchestrabackoffice/smartadmin/css/smartadmin-skins.min.css', 'web/bundles/phporchestrabackoffice/smartadmin/css/smartadmin-rtl.min.css', // ORCHESTRA SMARTADMIN PATCHES 'web/built/phporchestrabackoffice/css/smartadminPatches/flags.css', 'web/built/phporchestrabackoffice/css/smartadminPatches/title.css', 'web/built/phporchestrabackoffice/css/smartadminPatches/modal.css', 'web/built/phporchestrabackoffice/css/smartadminPatches/widget.css', 'web/built/phporchestrabackoffice/css/smartadminPatches/checkbox.css', 'web/built/phporchestrabackoffice/css/smartadminPatches/tab.css', 'web/built/phporchestrabackoffice/css/smartadminPatches/form.css', // TINYMCE PATCHES 'web/built/phporchestrabackoffice/css/tinyMCEPatches/floatPanel.css' ], dest: 'web/built/smartadmin.css' }, libcss: { src: [ 'bower_components/jquery-ui/themes/base/all.css', 'bower_components/datatables/media/css/jquery.dataTables.css' ], dest: 'web/built/lib.css' }, orchestracss: { src: [ 'web/built/phporchestrabackoffice/css/phporchestra.css', 'web/built/phporchestrabackoffice/css/mediatheque.css', 'web/built/phporchestrabackoffice/css/template.css', 'web/built/phporchestrabackoffice/css/blocksPanel.css', 'web/built/phporchestrabackoffice/css/blocksIcon.css', 'web/built/phporchestrabackoffice/css/mediaModal.css', 'web/bundles/lexiktranslation/ng-table/ng-table.min.css', 'web/built/phporchestrabackoffice/css/loginPage.css', 'web/built/phporchestrabackoffice/css/editTable.css', 'web/built/phporchestrabackoffice/css/node.css' ], dest: 'web/built/orchestra.css' }, css: { src: [ 'web/built/smartadmin.css', 'web/built/lib.css', 'web/built/orchestra.css' ], dest: 'web/css/all.css' } }, watch: { css: { files: ['web/bundles/*/less/*.less'], tasks: ['css', 'command:assetic_dump'] }, javascript: { files: ['web/bundles/*/coffee/*.coffee'], tasks: ['javascript', 'command:assetic_dump'] } }, command : { assets_install: { cmd : 'php app/console assets:install --symlink' }, assetic_dump: { cmd : 'php app/console assetic:dump' } } }); // Default task(s). grunt.registerTask('default', ['clean', 'command:assets_install', 'symlink', 'css', 'javascript', 'javascriptProd', 'command:assetic_dump']); grunt.registerTask('css', ['less:discovering', 'less', 'concat:smartadmincss', 'concat:libcss', 'concat:orchestracss', 'concat:css', 'cssmin']); grunt.registerTask('javascript', ['coffee:discovering', 'coffee', 'concat:smartadminjs', 'concat:libjs', 'concat:orchestrajs', 'concat:js']); grunt.registerTask('javascriptProd', ['uglify']); grunt.registerTask('less:discovering', 'This is a function', function() { // LESS Files management // Source LESS files are located inside : bundles/[bundle]/less/ // Destination CSS files are located inside : built/[bundle]/css/ var mappingFileLess = grunt.file.expandMapping( ['*/less/*.less', '*/less/*/*.less'], 'web/built/', { cwd: 'web/bundles/', rename: function(dest, matchedSrcPath, options) { return dest + matchedSrcPath.replace(/less/g, 'css'); } }); grunt.util._.each(mappingFileLess, function(value) { // Why value.src is an array ?? filesLess[value.dest] = value.src[0]; }); }); grunt.registerTask('coffee:discovering', 'This is a function', function() { // COFFEE Files management // Source COFFEE files are located inside : bundles/[bundle]/coffee/ // Destination JS files are located inside : built/[bundle]/js/ var mappingFileCoffee = grunt.file.expandMapping( ['*/coffee/*.coffee', '*/coffee/*/*.coffee'], 'web/built/', { cwd: 'web/bundles/', rename: function(dest, matchedSrcPath, options) { return dest + matchedSrcPath.replace(/coffee/g, 'js'); } }); grunt.util._.each(mappingFileCoffee, function(value) { // Why value.src is an array ?? filesCoffee[value.dest] = value.src[0]; }); }); };
Gruntfile.js
module.exports = function(grunt) { grunt.loadNpmTasks('grunt-contrib-symlink'); grunt.loadNpmTasks('grunt-contrib-less'); grunt.loadNpmTasks('grunt-contrib-cssmin'); grunt.loadNpmTasks('grunt-contrib-coffee'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-commands'); var filesLess = {}, filesCoffee = {}; // Configuration grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), symlink: { // BOWER COMPONENT fontawesome_font_otf: { src: 'bower_components/font-awesome/fonts/FontAwesome.otf', dest: 'web/fonts/FontAwesome.otf' }, fontawesome_font_eot: { src: 'bower_components/font-awesome/fonts/fontawesome-webfont.eot', dest: 'web/fonts/fontawesome-webfont.eot' }, fontawesome_font_svg: { src: 'bower_components/font-awesome/fonts/fontawesome-webfont.svg', dest: 'web/fonts/fontawesome-webfont.svg' }, fontawesome_font_ttf: { src: 'bower_components/font-awesome/fonts/fontawesome-webfont.ttf', dest: 'web/fonts/fontawesome-webfont.ttf' }, fontawesome_font_woff: { src: 'bower_components/font-awesome/fonts/fontawesome-webfont.woff', dest: 'web/fonts/fontawesome-webfont.woff' }, bootstrap_font_eot: { src: 'bower_components/bootstrap/dist/fonts/glyphicons-halflings-regular.eot', dest: 'web/fonts/glyphicons-halflings-regular.eot' }, bootstrap_font_svg: { src: 'bower_components/bootstrap/dist/fonts/glyphicons-halflings-regular.svg', dest: 'web/fonts/glyphicons-halflings-regular.svg' }, bootstrap_font_ttf: { src: 'bower_components/bootstrap/dist/fonts/glyphicons-halflings-regular.ttf', dest: 'web/fonts/glyphicons-halflings-regular.ttf' }, bootstrap_font_woff: { src: 'bower_components/bootstrap/dist/fonts/glyphicons-halflings-regular.woff', dest: 'web/fonts/glyphicons-halflings-regular.woff' }, datatable_img_sort_asc: { src: 'bower_components/datatables/media/images/sort_asc.png', dest: 'web/images/sort_asc.png' }, datatable_img_sort_both: { src: 'bower_components/datatables/media/images/sort_both.png', dest: 'web/images/sort_both.png' }, datatable_img_sort_desc: { src: 'bower_components/datatables/media/images/sort_desc.png', dest: 'web/images/sort_desc.png' }, pace_js: { src: 'bower_components/pace/pace.min.js', dest: 'web/js/pace.min.js' }, jcrop_gif: { src: 'bower_components/jcrop/css/Jcrop.gif', dest: 'web/img/jcrop/Jcrop.gif' }, // SMARTADMIN ASSETS smartadmin_bg: { src: 'web/bundles/phporchestrabackoffice/smartadmin/img/mybg.png', dest: 'web/img/mybg.png' }, smartadmin_flags: { src: 'web/bundles/phporchestrabackoffice/smartadmin/img/flags/flags.png', dest: 'web/img/flags/flags.png' }, select2_gif: { src: 'web/bundles/phporchestrabackoffice/smartadmin/img/select2-spinner.gif', dest: 'web/img/select2-spinner.gif' }, // ORCHESTRA ASSET no_image: { src: 'web/bundles/phporchestrabackoffice/images/no_image_available.jpg', dest: 'web/img/no_image_available.jpg' } }, clean: { built: ["web/built"] }, less: { bundles: { files: filesLess } }, cssmin: { minify: { expand: true, src: ['web/css/all.css'], ext: '.min.css' } }, coffee: { compileBare: { options: { bare: true }, files: filesCoffee } }, uglify: { dist: { files: { 'web/js/all.min.js': ['web/js/all.js'] } } }, concat: { smartadminjs: { src: [ 'bower_components/jquery/dist/jquery.js', 'bower_components/jquery-ui/jquery-ui.js', 'web/bundles/phporchestrabackoffice/smartadmin/js/app.config.js', 'bower_components/bootstrap/dist/js/bootstrap.js', 'bower_components/jcrop/js/jquery.Jcrop.js', 'bower_components/select2/select2.js', 'web/bundles/phporchestrabackoffice/smartadmin/js/notification/SmartNotification.min.js', 'web/bundles/phporchestrabackoffice/smartadmin/js/smartwidgets/jarvis.widget.min.js', 'web/bundles/phporchestrabackoffice/smartadmin/js/app.min.js' ], dest: 'web/built/smartadmin.js' }, libjs: { src: [ 'bower_components/underscore/underscore.js', 'bower_components/backbone/backbone.js', 'bower_components/angular/angular.js', 'bower_components/datatables/media/js/jquery.dataTables.js', 'bower_components/jquery-form/jquery.form.js', 'web/bundles/phporchestrabackoffice/js/latinise.js', 'web/bundles/phporchestrabackoffice/js/jQuery.DOMNodeAppear.js', 'web/bundles/phporchestrabackoffice/js/underscoreTemplateLoader.js' ], dest: 'web/built/lib.js' }, orchestrajs: { src: [ 'web/built/phporchestrabackoffice/js/orchestraLib.js', 'web/built/phporchestrabackoffice/js/orchestraListeners.js', // MISC 'web/built/phporchestrabackoffice/js/OrchestraView.js', 'web/built/phporchestrabackoffice/js/addPrototype.js', 'web/built/phporchestrabackoffice/js/modelBackbone.js', 'web/built/phporchestrabackoffice/js/adminFormView.js', 'web/built/phporchestrabackoffice/js/generateAlias.js', 'web/built/phporchestrabackoffice/js/generateContentTypeId.js', 'web/built/phporchestrabackoffice/js/page/makeSortable.js', 'web/built/phporchestrabackoffice/js/page/areaView.js', 'web/built/phporchestrabackoffice/js/page/blockView.js', 'web/built/phporchestrabackoffice/js/page/nodeView.js', 'web/built/phporchestrabackoffice/js/page/NodeVersionView.js', 'web/built/phporchestrabackoffice/js/LanguageView.js', 'web/built/phporchestrabackoffice/js/page/previewLinkView.js', 'web/built/phporchestrabackoffice/js/page/pageConfigurationButtonView.js', 'web/built/phporchestrabackoffice/js/table/TableviewView.js', 'web/built/phporchestrabackoffice/js/table/TableviewCollectionView.js', 'web/built/phporchestrabackoffice/js/FullPageFormView.js', 'web/built/phporchestrabackoffice/js/ContentTypeChangeTypeListener.js', 'web/built/phporchestrabackoffice/js/page/templateView.js', 'web/built/phporchestrabackoffice/js/page/showNode.js', 'web/built/phporchestrabackoffice/js/page/showTemplate.js', 'web/built/phporchestrabackoffice/js/table/tableviewLoader.js', 'web/built/phporchestrabackoffice/js/page/nodeConstructor.js', 'web/built/phporchestrabackoffice/js/treeAjaxDelete.js', 'web/built/phporchestrabackoffice/js/configurableContentFormListener.js', 'web/built/phporchestrabackoffice/js/page/blocksPanel.js', 'web/built/phporchestrabackoffice/js/security.js', // MEDIATHEQUE 'web/built/phporchestrabackoffice/js/mediatheque/*.js', // INDEXATION 'web/bundles/phporchestraindexation/js/*.js', // LEXIKTRANSLATION 'web/bundles/lexiktranslation/ng-table/ng-table.min.js', 'web/built/phporchestratranslation/js/translationView.js', // BACKBONE ROUTER 'web/bundles/phporchestrabackoffice/js/backboneRouter.js' ], dest: 'web/built/orchestra.js' }, js: { src: [ 'web/built/smartadmin.js', 'web/built/lib.js', 'web/built/orchestra.js' ], dest: 'web/js/all.js' }, smartadmincss: { src: [ // SMARTADMIN PACKAGE // 'bower_components/bootstrap/dist/css/bootstrap.min.css', 'web/bundles/phporchestrabackoffice/smartadmin/css/bootstrap.min.css', 'bower_components/font-awesome/css/font-awesome.min.css', 'web/bundles/phporchestrabackoffice/smartadmin/css/smartadmin-production-plugins.min.css', 'web/bundles/phporchestrabackoffice/smartadmin/css/smartadmin-production.min.css', 'web/bundles/phporchestrabackoffice/smartadmin/css/smartadmin-skins.min.css', 'web/bundles/phporchestrabackoffice/smartadmin/css/smartadmin-rtl.min.css', // ORCHESTRA SMARTADMIN PATCHES 'web/built/phporchestrabackoffice/css/smartadminPatches/flags.css', 'web/built/phporchestrabackoffice/css/smartadminPatches/title.css', 'web/built/phporchestrabackoffice/css/smartadminPatches/modal.css', 'web/built/phporchestrabackoffice/css/smartadminPatches/widget.css', 'web/built/phporchestrabackoffice/css/smartadminPatches/checkbox.css', 'web/built/phporchestrabackoffice/css/smartadminPatches/tab.css', 'web/built/phporchestrabackoffice/css/smartadminPatches/form.css', // TINYMCE PATCHES 'web/built/phporchestrabackoffice/css/tinyMCEPatches/floatPanel.css' ], dest: 'web/built/smartadmin.css' }, libcss: { src: [ 'bower_components/jquery-ui/themes/base/all.css', 'bower_components/datatables/media/css/jquery.dataTables.css' ], dest: 'web/built/lib.css' }, orchestracss: { src: [ 'web/built/phporchestrabackoffice/css/phporchestra.css', 'web/built/phporchestrabackoffice/css/mediatheque.css', 'web/built/phporchestrabackoffice/css/template.css', 'web/built/phporchestrabackoffice/css/blocksPanel.css', 'web/built/phporchestrabackoffice/css/blocksIcon.css', 'web/built/phporchestrabackoffice/css/mediaModal.css', 'web/bundles/lexiktranslation/ng-table/ng-table.min.css', 'web/built/phporchestrabackoffice/css/loginPage.css', 'web/built/phporchestrabackoffice/css/editTable.css', 'web/built/phporchestrabackoffice/css/node.css' ], dest: 'web/built/orchestra.css' }, css: { src: [ 'web/built/smartadmin.css', 'web/built/lib.css', 'web/built/orchestra.css' ], dest: 'web/css/all.css' } }, watch: { css: { files: ['web/bundles/*/less/*.less'], tasks: ['css', 'command:assetic_dump'] }, javascript: { files: ['web/bundles/*/coffee/*.coffee'], tasks: ['javascript', 'command:assetic_dump'] } }, command : { assets_install: { cmd : 'php app/console assets:install --symlink' }, assetic_dump: { cmd : 'php app/console assetic:dump' } } }); // Default task(s). grunt.registerTask('default', ['clean', 'command:assets_install', 'symlink', 'css', 'javascript', 'javascriptProd', 'command:assetic_dump']); grunt.registerTask('css', ['less:discovering', 'less', 'concat:smartadmincss', 'concat:libcss', 'concat:orchestracss', 'concat:css', 'cssmin']); grunt.registerTask('javascript', ['coffee:discovering', 'coffee', 'concat:smartadminjs', 'concat:libjs', 'concat:orchestrajs', 'concat:js']); grunt.registerTask('javascriptProd', ['uglify']); grunt.registerTask('less:discovering', 'This is a function', function() { // LESS Files management // Source LESS files are located inside : bundles/[bundle]/less/ // Destination CSS files are located inside : built/[bundle]/css/ var mappingFileLess = grunt.file.expandMapping( ['*/less/*.less', '*/less/*/*.less'], 'web/built/', { cwd: 'web/bundles/', rename: function(dest, matchedSrcPath, options) { return dest + matchedSrcPath.replace(/less/g, 'css'); } }); grunt.util._.each(mappingFileLess, function(value) { // Why value.src is an array ?? filesLess[value.dest] = value.src[0]; }); }); grunt.registerTask('coffee:discovering', 'This is a function', function() { // COFFEE Files management // Source COFFEE files are located inside : bundles/[bundle]/coffee/ // Destination JS files are located inside : built/[bundle]/js/ var mappingFileCoffee = grunt.file.expandMapping( ['*/coffee/*.coffee', '*/coffee/*/*.coffee'], 'web/built/', { cwd: 'web/bundles/', rename: function(dest, matchedSrcPath, options) { return dest + matchedSrcPath.replace(/coffee/g, 'js'); } }); grunt.util._.each(mappingFileCoffee, function(value) { // Why value.src is an array ?? filesCoffee[value.dest] = value.src[0]; }); }); };
extract multiversion
Gruntfile.js
extract multiversion
<ide><path>runtfile.js <ide> 'web/built/phporchestrabackoffice/js/page/areaView.js', <ide> 'web/built/phporchestrabackoffice/js/page/blockView.js', <ide> 'web/built/phporchestrabackoffice/js/page/nodeView.js', <del> 'web/built/phporchestrabackoffice/js/page/NodeVersionView.js', <add> 'web/built/phporchestrabackoffice/js/VersionView.js', <ide> 'web/built/phporchestrabackoffice/js/LanguageView.js', <ide> 'web/built/phporchestrabackoffice/js/page/previewLinkView.js', <ide> 'web/built/phporchestrabackoffice/js/page/pageConfigurationButtonView.js',
Java
apache-2.0
6444c6a914ac7a546a3237af0720b1fa45f6a7d8
0
jackeychens/CircleImageView,applegrew/CircleImageView,moltak/CircleImageView,lovecc0923/CircleImageView,murat8505/CircleImageView,jarrahwu/CircleImageView,Cryhelyxx/CircleImageView,gouravd/CircleImageView,hai8108/CircleImageView,Jaeandroid/CircleImageView,yswheye/CircleImageView,dmitrykolesnikovich/CircleImageView,msdgwzhy6/CircleImageView,MoskalenkoViktor/CircleImageView,HappyYang/CircleImageView,tks-dp/CircleImageView,hanhailong/CircleImageView,ewrfedf/CircleImageView,maitho/CircleImageView,jiyiren/CircleImageView,MaTriXy/CircleImageView,ctrannik/circleIMG,msandroid/CircleImageView,Jonss/CircleImageView,lFaustus/CircleImageView,leokemp/CircleImageView,TigranSarkisian/CircleImageView,sausiliu/CircleImageView,takatost/CircleImageView,YlJava110/CircleImageView,stronglee/CircleImageView,hdodenhof/CircleImageView,jglchen/CircleImageView,wswenyue/CircleImageView,NewComerBH/CircleImageView,StarRain/CircleImageView,rajtufan/materialDrawer,rvacoder/CircleImageView,bianwl/CircleImageView,AdrianHsu/CircleImageView,emanuelet/CircleImageView,LeonardoPhysh/CircleImageView,luiz04nl/CircleImageView,yoslabs/CircleImageView,chwnFlyPig/CircleImageView,YuzurihaInori/CircleImageView,Ringares/CircleImageView,Mozhuowen/CircleImageView,onlynight/CircleImageView,rafahells/CircleImageView,200694133/CircleImageView,hgl888/CircleImageView,kongx73/CircleImageView,net19880504/CircleImageView
package de.hdodenhof.circleimageview; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.RectF; import android.graphics.Shader; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.util.AttributeSet; import android.widget.ImageView; public class CircleImageView extends ImageView { private static final ScaleType SCALE_TYPE = ScaleType.CENTER_CROP; private static final Bitmap.Config BITMAP_CONFIG = Bitmap.Config.ARGB_8888; private static final int COLORDRAWABLE_DIMENSION = 1; private static final int DEFAULT_BORDER_WIDTH = 0; private static final int DEFAULT_BORDER_COLOR = Color.BLACK; private final RectF mDrawableRect = new RectF(); private final RectF mBorderRect = new RectF(); private final Matrix mShaderMatrix = new Matrix(); private final Paint mBitmapPaint = new Paint(); private final Paint mBorderPaint = new Paint(); private int mBorderColor = DEFAULT_BORDER_COLOR; private int mBorderWidth = DEFAULT_BORDER_WIDTH; private Bitmap mBitmap; private BitmapShader mBitmapShader; private int mBitmapWidth; private int mBitmapHeight; private float mDrawableRadius; private float mBorderRadius; private boolean mReady; private boolean mSetupPending; public CircleImageView(Context context) { super(context); init(); } public CircleImageView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public CircleImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleImageView, defStyle, 0); mBorderWidth = a.getDimensionPixelSize(R.styleable.CircleImageView_border_width, DEFAULT_BORDER_WIDTH); mBorderColor = a.getColor(R.styleable.CircleImageView_border_color, DEFAULT_BORDER_COLOR); a.recycle(); init(); } private void init() { super.setScaleType(SCALE_TYPE); mReady = true; if (mSetupPending) { setup(); mSetupPending = false; } } @Override public ScaleType getScaleType() { return SCALE_TYPE; } @Override public void setScaleType(ScaleType scaleType) { if (scaleType != SCALE_TYPE) { throw new IllegalArgumentException(String.format("ScaleType %s not supported.", scaleType)); } } @Override protected void onDraw(Canvas canvas) { if (getDrawable() == null) { return; } canvas.drawCircle(getWidth() / 2, getHeight() / 2, mDrawableRadius, mBitmapPaint); if (mBorderWidth != 0) { canvas.drawCircle(getWidth() / 2, getHeight() / 2, mBorderRadius, mBorderPaint); } } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); setup(); } public int getBorderColor() { return mBorderColor; } public void setBorderColor(int borderColor) { if (borderColor == mBorderColor) { return; } mBorderColor = borderColor; mBorderPaint.setColor(mBorderColor); invalidate(); } public int getBorderWidth() { return mBorderWidth; } public void setBorderWidth(int borderWidth) { if (borderWidth == mBorderWidth) { return; } mBorderWidth = borderWidth; setup(); } @Override public void setImageBitmap(Bitmap bm) { super.setImageBitmap(bm); mBitmap = bm; setup(); } @Override public void setImageDrawable(Drawable drawable) { super.setImageDrawable(drawable); mBitmap = getBitmapFromDrawable(drawable); setup(); } @Override public void setImageResource(int resId) { super.setImageResource(resId); mBitmap = getBitmapFromDrawable(getDrawable()); setup(); } @Override public void setImageURI(Uri uri) { super.setImageURI(uri); mBitmap = getBitmapFromDrawable(getDrawable()); setup(); } private Bitmap getBitmapFromDrawable(Drawable drawable) { if (drawable == null) { return null; } if (drawable instanceof BitmapDrawable) { return ((BitmapDrawable) drawable).getBitmap(); } try { Bitmap bitmap; if (drawable instanceof ColorDrawable) { bitmap = Bitmap.createBitmap(COLORDRAWABLE_DIMENSION, COLORDRAWABLE_DIMENSION, BITMAP_CONFIG); } else { bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), BITMAP_CONFIG); } Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); return bitmap; } catch (OutOfMemoryError e) { return null; } } private void setup() { if (!mReady) { mSetupPending = true; return; } if (mBitmap == null) { return; } mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); mBitmapPaint.setAntiAlias(true); mBitmapPaint.setShader(mBitmapShader); mBorderPaint.setStyle(Paint.Style.STROKE); mBorderPaint.setAntiAlias(true); mBorderPaint.setColor(mBorderColor); mBorderPaint.setStrokeWidth(mBorderWidth); mBitmapHeight = mBitmap.getHeight(); mBitmapWidth = mBitmap.getWidth(); mBorderRect.set(0, 0, getWidth(), getHeight()); mBorderRadius = Math.min((mBorderRect.height() - mBorderWidth) / 2, (mBorderRect.width() - mBorderWidth) / 2); mDrawableRect.set(mBorderWidth, mBorderWidth, mBorderRect.width() - mBorderWidth, mBorderRect.height() - mBorderWidth); mDrawableRadius = Math.min(mDrawableRect.height() / 2, mDrawableRect.width() / 2); updateShaderMatrix(); invalidate(); } private void updateShaderMatrix() { float scale; float dx = 0; float dy = 0; mShaderMatrix.set(null); if (mBitmapWidth * mDrawableRect.height() > mDrawableRect.width() * mBitmapHeight) { scale = mDrawableRect.height() / (float) mBitmapHeight; dx = (mDrawableRect.width() - mBitmapWidth * scale) * 0.5f; } else { scale = mDrawableRect.width() / (float) mBitmapWidth; dy = (mDrawableRect.height() - mBitmapHeight * scale) * 0.5f; } mShaderMatrix.setScale(scale, scale); mShaderMatrix.postTranslate((int) (dx + 0.5f) + mBorderWidth, (int) (dy + 0.5f) + mBorderWidth); mBitmapShader.setLocalMatrix(mShaderMatrix); } }
circleimageview/src/main/java/de/hdodenhof/circleimageview/CircleImageView.java
package de.hdodenhof.circleimageview; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.RectF; import android.graphics.Shader; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.widget.ImageView; public class CircleImageView extends ImageView { private static final ScaleType SCALE_TYPE = ScaleType.CENTER_CROP; private static final Bitmap.Config BITMAP_CONFIG = Bitmap.Config.ARGB_8888; private static final int COLORDRAWABLE_DIMENSION = 1; private static final int DEFAULT_BORDER_WIDTH = 0; private static final int DEFAULT_BORDER_COLOR = Color.BLACK; private final RectF mDrawableRect = new RectF(); private final RectF mBorderRect = new RectF(); private final Matrix mShaderMatrix = new Matrix(); private final Paint mBitmapPaint = new Paint(); private final Paint mBorderPaint = new Paint(); private int mBorderColor = DEFAULT_BORDER_COLOR; private int mBorderWidth = DEFAULT_BORDER_WIDTH; private Bitmap mBitmap; private BitmapShader mBitmapShader; private int mBitmapWidth; private int mBitmapHeight; private float mDrawableRadius; private float mBorderRadius; private boolean mReady; private boolean mSetupPending; public CircleImageView(Context context) { super(context); init(); } public CircleImageView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public CircleImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleImageView, defStyle, 0); mBorderWidth = a.getDimensionPixelSize(R.styleable.CircleImageView_border_width, DEFAULT_BORDER_WIDTH); mBorderColor = a.getColor(R.styleable.CircleImageView_border_color, DEFAULT_BORDER_COLOR); a.recycle(); init(); } private void init() { super.setScaleType(SCALE_TYPE); mReady = true; if (mSetupPending) { setup(); mSetupPending = false; } } @Override public ScaleType getScaleType() { return SCALE_TYPE; } @Override public void setScaleType(ScaleType scaleType) { if (scaleType != SCALE_TYPE) { throw new IllegalArgumentException(String.format("ScaleType %s not supported.", scaleType)); } } @Override protected void onDraw(Canvas canvas) { if (getDrawable() == null) { return; } canvas.drawCircle(getWidth() / 2, getHeight() / 2, mDrawableRadius, mBitmapPaint); if (mBorderWidth != 0) { canvas.drawCircle(getWidth() / 2, getHeight() / 2, mBorderRadius, mBorderPaint); } } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); setup(); } public int getBorderColor() { return mBorderColor; } public void setBorderColor(int borderColor) { if (borderColor == mBorderColor) { return; } mBorderColor = borderColor; mBorderPaint.setColor(mBorderColor); invalidate(); } public int getBorderWidth() { return mBorderWidth; } public void setBorderWidth(int borderWidth) { if (borderWidth == mBorderWidth) { return; } mBorderWidth = borderWidth; setup(); } @Override public void setImageBitmap(Bitmap bm) { super.setImageBitmap(bm); mBitmap = bm; setup(); } @Override public void setImageDrawable(Drawable drawable) { super.setImageDrawable(drawable); mBitmap = getBitmapFromDrawable(drawable); setup(); } @Override public void setImageResource(int resId) { super.setImageResource(resId); mBitmap = getBitmapFromDrawable(getDrawable()); setup(); } private Bitmap getBitmapFromDrawable(Drawable drawable) { if (drawable == null) { return null; } if (drawable instanceof BitmapDrawable) { return ((BitmapDrawable) drawable).getBitmap(); } try { Bitmap bitmap; if (drawable instanceof ColorDrawable) { bitmap = Bitmap.createBitmap(COLORDRAWABLE_DIMENSION, COLORDRAWABLE_DIMENSION, BITMAP_CONFIG); } else { bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), BITMAP_CONFIG); } Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); return bitmap; } catch (OutOfMemoryError e) { return null; } } private void setup() { if (!mReady) { mSetupPending = true; return; } if (mBitmap == null) { return; } mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); mBitmapPaint.setAntiAlias(true); mBitmapPaint.setShader(mBitmapShader); mBorderPaint.setStyle(Paint.Style.STROKE); mBorderPaint.setAntiAlias(true); mBorderPaint.setColor(mBorderColor); mBorderPaint.setStrokeWidth(mBorderWidth); mBitmapHeight = mBitmap.getHeight(); mBitmapWidth = mBitmap.getWidth(); mBorderRect.set(0, 0, getWidth(), getHeight()); mBorderRadius = Math.min((mBorderRect.height() - mBorderWidth) / 2, (mBorderRect.width() - mBorderWidth) / 2); mDrawableRect.set(mBorderWidth, mBorderWidth, mBorderRect.width() - mBorderWidth, mBorderRect.height() - mBorderWidth); mDrawableRadius = Math.min(mDrawableRect.height() / 2, mDrawableRect.width() / 2); updateShaderMatrix(); invalidate(); } private void updateShaderMatrix() { float scale; float dx = 0; float dy = 0; mShaderMatrix.set(null); if (mBitmapWidth * mDrawableRect.height() > mDrawableRect.width() * mBitmapHeight) { scale = mDrawableRect.height() / (float) mBitmapHeight; dx = (mDrawableRect.width() - mBitmapWidth * scale) * 0.5f; } else { scale = mDrawableRect.width() / (float) mBitmapWidth; dy = (mDrawableRect.height() - mBitmapHeight * scale) * 0.5f; } mShaderMatrix.setScale(scale, scale); mShaderMatrix.postTranslate((int) (dx + 0.5f) + mBorderWidth, (int) (dy + 0.5f) + mBorderWidth); mBitmapShader.setLocalMatrix(mShaderMatrix); } }
Add support for setImageURI
circleimageview/src/main/java/de/hdodenhof/circleimageview/CircleImageView.java
Add support for setImageURI
<ide><path>ircleimageview/src/main/java/de/hdodenhof/circleimageview/CircleImageView.java <ide> import android.graphics.drawable.BitmapDrawable; <ide> import android.graphics.drawable.ColorDrawable; <ide> import android.graphics.drawable.Drawable; <add>import android.net.Uri; <ide> import android.util.AttributeSet; <ide> import android.widget.ImageView; <ide> <ide> @Override <ide> public void setImageResource(int resId) { <ide> super.setImageResource(resId); <add> mBitmap = getBitmapFromDrawable(getDrawable()); <add> setup(); <add> } <add> <add> @Override <add> public void setImageURI(Uri uri) { <add> super.setImageURI(uri); <ide> mBitmap = getBitmapFromDrawable(getDrawable()); <ide> setup(); <ide> }
Java
mit
936da09b580bcd09ac8c5ff89a31f79352dcadaa
0
missytoy/GuessTheWord
package layout; import android.app.Activity; import android.content.Context; import android.graphics.Color; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.AsyncTask; import android.os.Bundle; import android.os.CountDownTimer; import android.support.v4.app.Fragment; import android.util.Log; import android.view.GestureDetector; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.example.miss.temp.R; import java.util.AbstractSet; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Random; import data.DataAccess; import helpers.MySoundManager; import models.Game; import models.Player; /** * A simple {@link Fragment} subclass. */ public class GamePage extends Fragment implements View.OnClickListener, SensorEventListener { private static final Random random = new Random(); SensorEventListener listener; private float x1, x2; static final int MIN_DISTANCE = 150; private static final int PLAYER_TURN_TIME = 10000; private SensorManager senSensorManager; private Sensor senAccelerometer; private long lastUpdate = 0; private float last_x, last_y, last_z; private static final int SHAKE_THRESHOLD = 600; private List<String> wordsToGuess; private List<Player> players; private Integer currentCategoryId; private Integer currentPlayerIndex; private HashSet<String> usedWords; private String address; private String city; private String place; private Boolean isLocationChecked; TextView timerTextView; TextView randomWord; RelativeLayout randomWordAndTimer; RelativeLayout currentUserInfo; RelativeLayout playerFirstPage; Button nextPlayerButton; TextView playerScoreView; public Long timerStep; private OnGameOver onGameOver; Button correctButton; Button wrongButton; Button startWithFirstPlayerButton; public GamePage() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_game_page, container, false); wordsToGuess = new ArrayList<String>(); usedWords = new HashSet<String>(); Bundle args = this.getArguments(); isLocationChecked = args.getBoolean("is_checked"); currentCategoryId = args.getInt("category_id"); address = args.getString("location"); city = args.getString("city"); players = new ArrayList<Player>((List<Player>) args.getSerializable("players_list")); currentPlayerIndex = 0; new GetWordsTask().execute((DataAccess) args.getSerializable("data")); startWithFirstPlayerButton = (Button) view.findViewById(R.id.first_player_play_btn); String firstPlayerName = players.get(currentPlayerIndex).getName(); startWithFirstPlayerButton.setText(firstPlayerName + "'s turn"); startWithFirstPlayerButton.setOnClickListener(this); timerTextView = (TextView) view.findViewById(R.id.timer_textview_id); randomWord = (TextView) view.findViewById(R.id.random_word_textview_id); randomWordAndTimer = (RelativeLayout) view.findViewById(R.id.random_word_and_timer_Layout); currentUserInfo = (RelativeLayout) view.findViewById(R.id.current_user_info); playerFirstPage = (RelativeLayout) view.findViewById(R.id.fist_player_layout); nextPlayerButton = (Button) view.findViewById(R.id.next_player_button); nextPlayerButton.setOnClickListener(this); playerScoreView = (TextView) view.findViewById(R.id.player_score_view); correctButton = (Button) view.findViewById(R.id.correct_btn); correctButton.setOnClickListener(this); wrongButton = (Button) view.findViewById(R.id.wrong_btn); wrongButton.setOnClickListener(this); startWithFirstPlayerButton = (Button) view.findViewById(R.id.first_player_play_btn); startWithFirstPlayerButton.setOnClickListener(this); final GestureDetector gesture = new GestureDetector(getActivity(), new GestureDetector.SimpleOnGestureListener() { @Override public boolean onDown(MotionEvent e) { return true; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { final int SWIPE_MIN_DISTANCE = 120; final int SWIPE_MAX_OFF_PATH = 250; final int SWIPE_THRESHOLD_VELOCITY = 200; try { if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH) return false; if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { if (playerFirstPage.getVisibility() != View.VISIBLE) { handleSwipeLeft(); } } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { if (playerFirstPage.getVisibility() != View.VISIBLE) { handleSwipeRight(); } } } catch (Exception e) { // nothing } return super.onFling(e1, e2, velocityX, velocityY); } }); view.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return gesture.onTouchEvent(event); } }); senSensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE); senAccelerometer = senSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); senSensorManager.registerListener(this, senAccelerometer, SensorManager.SENSOR_DELAY_NORMAL); listener = this; return view; } @Override public void onClick(View v) { if (v.getId() == nextPlayerButton.getId()) { MySoundManager.playButtonSound(getContext()); randomWordAndTimer.setVisibility(View.VISIBLE); currentUserInfo.setVisibility(View.INVISIBLE); usedWords.clear(); int indexOfRandomWord = random.nextInt(wordsToGuess.size() - 1 + 1); randomWord.setText(wordsToGuess.get(indexOfRandomWord)); playerTimer(); } else if (v.getId() == correctButton.getId()) { MySoundManager.playCorrectTone(getContext()); Player currentPlayer = players.get(currentPlayerIndex); int currentScore = currentPlayer.getScore(); currentPlayer.setScore(currentScore + 1); int indexOfRandomWord = random.nextInt(wordsToGuess.size() - 1 + 1); String wordToGuess = wordsToGuess.get(indexOfRandomWord); while (usedWords.contains(wordToGuess)) { indexOfRandomWord = random.nextInt(wordsToGuess.size() - 1 + 1); wordToGuess = wordsToGuess.get(indexOfRandomWord); } randomWord.setText(wordToGuess); usedWords.add(wordToGuess); } else if (v.getId() == wrongButton.getId()) { MySoundManager.playNextWordTone(getContext()); int indexOfRandomWord = random.nextInt(wordsToGuess.size() - 1 + 1); String wordToGuess = wordsToGuess.get(indexOfRandomWord); while (usedWords.contains(wordToGuess)) { indexOfRandomWord = random.nextInt(wordsToGuess.size() - 1 + 1); wordToGuess = wordsToGuess.get(indexOfRandomWord); } randomWord.setText(wordToGuess); usedWords.add(wordToGuess); } else if (v.getId() == startWithFirstPlayerButton.getId()) { int indexOfRandomWord = random.nextInt(wordsToGuess.size() - 1 + 1); String wordToGuess = wordsToGuess.get(indexOfRandomWord); randomWord.setText(wordToGuess); usedWords.add(wordToGuess); playerFirstPage.setVisibility(View.GONE); randomWordAndTimer.setVisibility(View.VISIBLE); playerTimer(); } } public void playerTimer() { CountDownTimer waitTimer; //TODO: set timer to 60000 senSensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE); senAccelerometer = senSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); senSensorManager.registerListener(this, senAccelerometer, SensorManager.SENSOR_DELAY_NORMAL); listener = this; waitTimer = new CountDownTimer(PLAYER_TURN_TIME, 1000) { public void onTick(long millisUntilFinished) { timerStep = millisUntilFinished / 1000; timerTextView.setText(timerStep.toString()); } public void onFinish() { timerTextView.setText("0"); senSensorManager.unregisterListener(listener); if (currentPlayerIndex == players.size() - 1) { Collections.sort(players); String[] playerScores = new String[players.size()]; for (int i = 0; i < players.size(); i++) { String playerScoreInfo = String.format("%d. %s (%d points)", i + 1, players.get(i).getName(), players.get(i).getScore()); playerScores[i] = playerScoreInfo; } // Make async task that saves the game object to the database - here or in activity see how to do it. new SaveGameObjectAndPlayersToBaseTask().execute((DataAccess) getArguments().getSerializable("data")); onGameOver.onGameEnding(playerScores); } else { randomWordAndTimer.setVisibility(View.INVISIBLE); currentUserInfo.setVisibility(View.VISIBLE); String playerScoreText = String.format("%s has %d points.", players.get(currentPlayerIndex).getName(), players.get(currentPlayerIndex).getScore()); String nextButtonPlayerText = String.format("%s's turn", players.get(currentPlayerIndex + 1).getName()); playerScoreView.setText(playerScoreText); nextPlayerButton.setText(nextButtonPlayerText); currentPlayerIndex++; } } }.start(); } @Override public void onSensorChanged(SensorEvent sensorEvent) { Sensor mySensor = sensorEvent.sensor; // if (randomWordAndTimer.getVisibility() == View.VISIBLE) { // senSensorManager.unregisterListener(this); if (mySensor.getType() == Sensor.TYPE_ACCELEROMETER) { float x = sensorEvent.values[0]; float y = sensorEvent.values[1]; float z = sensorEvent.values[2]; long curTime = System.currentTimeMillis(); if ((curTime - lastUpdate) > 1000) { long diffTime = (curTime - lastUpdate); lastUpdate = curTime; float speed = Math.abs(x + y + z - last_x - last_y - last_z) / diffTime * 50000; if (speed > SHAKE_THRESHOLD) { } if (z > 3 && y < 5 && x < 0) { //x>0 // Log.d("pingosvam","z > 3 && y<3 gore"); // MySoundManager.playCorrectTone(getContext()); if (playerFirstPage.getVisibility() != View.VISIBLE) { handleSwipeLeft(); } } Log.d("pingosvam x", String.valueOf(x)); // if (z < -5 && y>3 && x>1){ // Log.d("ping","normalno"); // // } if (z < -3 && y < 3 && x < 1) { // Log.d("ping", "dolu"); // MySoundManager.playNextWordTone(getContext()); if (playerFirstPage.getVisibility() != View.VISIBLE) { handleSwipeRight(); } } last_x = x; last_y = y; last_z = z; } } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } public interface OnGameOver { void onGameEnding(String[] playersScores); } public void handleSwipeLeft() { MySoundManager.playCorrectTone(getContext()); Player currentPlayer = players.get(currentPlayerIndex); int currentScore = currentPlayer.getScore(); currentPlayer.setScore(currentScore + 1); int indexOfRandomWord = random.nextInt(wordsToGuess.size() - 1 + 1); String wordToGuess = wordsToGuess.get(indexOfRandomWord); while (usedWords.contains(wordToGuess)) { indexOfRandomWord = random.nextInt(wordsToGuess.size() - 1 + 1); wordToGuess = wordsToGuess.get(indexOfRandomWord); } randomWord.setText(wordToGuess); usedWords.add(wordToGuess); } public void handleSwipeRight() { MySoundManager.playNextWordTone(getContext()); int indexOfRandomWord = random.nextInt(wordsToGuess.size() - 1 + 1); String wordToGuess = wordsToGuess.get(indexOfRandomWord); while (usedWords.contains(wordToGuess)) { indexOfRandomWord = random.nextInt(wordsToGuess.size() - 1 + 1); wordToGuess = wordsToGuess.get(indexOfRandomWord); } randomWord.setText(wordToGuess); usedWords.add(wordToGuess); } @Override public void onAttach(Context context) { super.onAttach(context); Activity activity = (Activity) context; // This makes sure that the container activity has implemented // the callback interface. If not, it throws an exception try { onGameOver = (OnGameOver) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnGameOver"); } } private class GetWordsTask extends AsyncTask<DataAccess, Void, AbstractSet<String>> { @Override protected AbstractSet<String> doInBackground(DataAccess... params) { AbstractSet<String> words = params[0].getAllWordsContentByCategory(currentCategoryId); return words; } @Override protected void onPostExecute(AbstractSet<String> words) { if (words.size() > 0) { for (String word : words) { wordsToGuess.add(word); } } else { randomWord.setText("No words in category"); Toast toast = Toast.makeText(getContext(), "Go back and ad some words to this category", Toast.LENGTH_SHORT); LinearLayout toastLayout = (LinearLayout) toast.getView(); TextView toastTV = (TextView) toastLayout.getChildAt(0); toastTV.setTextSize(20); toastTV.setTextColor(Color.WHITE); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } } } private class SaveGameObjectAndPlayersToBaseTask extends AsyncTask<DataAccess, Void, Void> { @Override protected Void doInBackground(DataAccess... params) { Game gameModel = new Game(); gameModel.setCategoryId(currentCategoryId); gameModel.setPlayedOn(new Date()); if (isLocationChecked) { place = city + ", " + address; gameModel.setLocation(place); } int gameId = (int) params[0].createGame(gameModel); for (Player pl : players) { pl.setGameId(gameId); params[0].createPlayer(pl); } Collections.sort(players); return null; } } }
WhatsTheWord/app/src/main/java/layout/GamePage.java
package layout; import android.app.Activity; import android.content.Context; import android.graphics.Color; import android.os.AsyncTask; import android.os.Bundle; import android.os.CountDownTimer; import android.support.v4.app.Fragment; import android.view.GestureDetector; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.example.miss.temp.R; import java.util.AbstractSet; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Random; import data.DataAccess; import helpers.MySoundManager; import models.Game; import models.Player; /** * A simple {@link Fragment} subclass. */ public class GamePage extends Fragment implements View.OnClickListener { private static final Random random = new Random(); private float x1, x2; static final int MIN_DISTANCE = 150; private static final int PLAYER_TURN_TIME = 1000; private List<String> wordsToGuess; private List<Player> players; private Integer currentCategoryId; private Integer currentPlayerIndex; private HashSet<String> usedWords; private String address; private String city; private String place; private Boolean isLocationChecked; TextView timerTextView; TextView randomWord; RelativeLayout randomWordAndTimer; RelativeLayout currentUserInfo; RelativeLayout playerFirstPage; Button nextPlayerButton; TextView playerScoreView; public Long timerStep; private OnGameOver onGameOver; Button correctButton; Button wrongButton; Button startWithFirstPlayerButton; public GamePage() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_game_page, container, false); wordsToGuess = new ArrayList<String>(); usedWords = new HashSet<String>(); Bundle args = this.getArguments(); isLocationChecked = args.getBoolean("is_checked"); currentCategoryId = args.getInt("category_id"); address = args.getString("location"); city = args.getString("city"); players = new ArrayList<Player>((List<Player>) args.getSerializable("players_list")); currentPlayerIndex = 0; new GetWordsTask().execute((DataAccess) args.getSerializable("data")); startWithFirstPlayerButton = (Button) view.findViewById(R.id.first_player_play_btn); String firstPlayerName = players.get(currentPlayerIndex).getName(); startWithFirstPlayerButton.setText(firstPlayerName + "'s turn"); startWithFirstPlayerButton.setOnClickListener(this); timerTextView = (TextView) view.findViewById(R.id.timer_textview_id); randomWord = (TextView) view.findViewById(R.id.random_word_textview_id); randomWordAndTimer = (RelativeLayout) view.findViewById(R.id.random_word_and_timer_Layout); currentUserInfo = (RelativeLayout) view.findViewById(R.id.current_user_info); playerFirstPage = (RelativeLayout) view.findViewById(R.id.fist_player_layout); nextPlayerButton = (Button) view.findViewById(R.id.next_player_button); nextPlayerButton.setOnClickListener(this); playerScoreView = (TextView) view.findViewById(R.id.player_score_view); correctButton = (Button) view.findViewById(R.id.correct_btn); correctButton.setOnClickListener(this); wrongButton = (Button) view.findViewById(R.id.wrong_btn); wrongButton.setOnClickListener(this); startWithFirstPlayerButton = (Button) view.findViewById(R.id.first_player_play_btn); startWithFirstPlayerButton.setOnClickListener(this); final GestureDetector gesture = new GestureDetector(getActivity(), new GestureDetector.SimpleOnGestureListener() { @Override public boolean onDown(MotionEvent e) { return true; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { final int SWIPE_MIN_DISTANCE = 120; final int SWIPE_MAX_OFF_PATH = 250; final int SWIPE_THRESHOLD_VELOCITY = 200; try { if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH) return false; if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { if (playerFirstPage.getVisibility() != View.VISIBLE){ handleSwipeLeft(); } } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { if (playerFirstPage.getVisibility() != View.VISIBLE){ handleSwipeRight(); } } } catch (Exception e) { // nothing } return super.onFling(e1, e2, velocityX, velocityY); } }); view.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return gesture.onTouchEvent(event); } }); return view; } @Override public void onClick(View v) { if (v.getId() == nextPlayerButton.getId()) { MySoundManager.playButtonSound(getContext()); randomWordAndTimer.setVisibility(View.VISIBLE); currentUserInfo.setVisibility(View.INVISIBLE); usedWords.clear(); int indexOfRandomWord = random.nextInt(wordsToGuess.size() - 1 + 1); randomWord.setText(wordsToGuess.get(indexOfRandomWord)); playerTimer(); } else if (v.getId() == correctButton.getId()) { MySoundManager.playCorrectTone(getContext()); Player currentPlayer = players.get(currentPlayerIndex); int currentScore = currentPlayer.getScore(); currentPlayer.setScore(currentScore + 1); int indexOfRandomWord = random.nextInt(wordsToGuess.size() - 1 + 1); String wordToGuess = wordsToGuess.get(indexOfRandomWord); while (usedWords.contains(wordToGuess)) { indexOfRandomWord = random.nextInt(wordsToGuess.size() - 1 + 1); wordToGuess = wordsToGuess.get(indexOfRandomWord); } randomWord.setText(wordToGuess); usedWords.add(wordToGuess); } else if (v.getId() == wrongButton.getId()) { MySoundManager.playNextWordTone(getContext()); int indexOfRandomWord = random.nextInt(wordsToGuess.size() - 1 + 1); String wordToGuess = wordsToGuess.get(indexOfRandomWord); while (usedWords.contains(wordToGuess)) { indexOfRandomWord = random.nextInt(wordsToGuess.size() - 1 + 1); wordToGuess = wordsToGuess.get(indexOfRandomWord); } randomWord.setText(wordToGuess); usedWords.add(wordToGuess); } else if (v.getId() == startWithFirstPlayerButton.getId()) { int indexOfRandomWord = random.nextInt(wordsToGuess.size() - 1 + 1); String wordToGuess = wordsToGuess.get(indexOfRandomWord); randomWord.setText(wordToGuess); usedWords.add(wordToGuess); playerFirstPage.setVisibility(View.GONE); randomWordAndTimer.setVisibility(View.VISIBLE); playerTimer(); } } public void playerTimer() { CountDownTimer waitTimer; //TODO: set timer to 60000 waitTimer = new CountDownTimer(PLAYER_TURN_TIME, 1000) { public void onTick(long millisUntilFinished) { timerStep = millisUntilFinished / 1000; timerTextView.setText(timerStep.toString()); } public void onFinish() { timerTextView.setText("0"); if (currentPlayerIndex == players.size() - 1) { Collections.sort(players); String[] playerScores = new String[players.size()]; for (int i = 0; i < players.size(); i++) { String playerScoreInfo = String.format("%d. %s (%d points)", i + 1, players.get(i).getName(), players.get(i).getScore()); playerScores[i] = playerScoreInfo; } // Make async task that saves the game object to the database - here or in activity see how to do it. new SaveGameObjectAndPlayersToBaseTask().execute((DataAccess) getArguments().getSerializable("data")); onGameOver.onGameEnding(playerScores); } else { randomWordAndTimer.setVisibility(View.INVISIBLE); currentUserInfo.setVisibility(View.VISIBLE); String playerScoreText = String.format("%s has %d points.", players.get(currentPlayerIndex).getName(), players.get(currentPlayerIndex).getScore()); String nextButtonPlayerText = String.format("%s's turn", players.get(currentPlayerIndex + 1).getName()); playerScoreView.setText(playerScoreText); nextPlayerButton.setText(nextButtonPlayerText); currentPlayerIndex++; } } }.start(); } public interface OnGameOver { void onGameEnding(String[] playersScores); } public void handleSwipeLeft() { MySoundManager.playCorrectTone(getContext()); Player currentPlayer = players.get(currentPlayerIndex); int currentScore = currentPlayer.getScore(); currentPlayer.setScore(currentScore + 1); int indexOfRandomWord = random.nextInt(wordsToGuess.size() - 1 + 1); String wordToGuess = wordsToGuess.get(indexOfRandomWord); while (usedWords.contains(wordToGuess)) { indexOfRandomWord = random.nextInt(wordsToGuess.size() - 1 + 1); wordToGuess = wordsToGuess.get(indexOfRandomWord); } randomWord.setText(wordToGuess); usedWords.add(wordToGuess); } public void handleSwipeRight() { MySoundManager.playNextWordTone(getContext()); int indexOfRandomWord = random.nextInt(wordsToGuess.size() - 1 + 1); String wordToGuess = wordsToGuess.get(indexOfRandomWord); while (usedWords.contains(wordToGuess)) { indexOfRandomWord = random.nextInt(wordsToGuess.size() - 1 + 1); wordToGuess = wordsToGuess.get(indexOfRandomWord); } randomWord.setText(wordToGuess); usedWords.add(wordToGuess); } @Override public void onAttach(Context context) { super.onAttach(context); Activity activity = (Activity) context; // This makes sure that the container activity has implemented // the callback interface. If not, it throws an exception try { onGameOver = (OnGameOver) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnGameOver"); } } private class GetWordsTask extends AsyncTask<DataAccess, Void, AbstractSet<String>> { @Override protected AbstractSet<String> doInBackground(DataAccess... params) { AbstractSet<String> words = params[0].getAllWordsContentByCategory(currentCategoryId); return words; } @Override protected void onPostExecute(AbstractSet<String> words) { if (words.size() > 0) { for (String word : words) { wordsToGuess.add(word); } } else { randomWord.setText("No words in category"); Toast toast = Toast.makeText(getContext(), "Go back and ad some words to this category", Toast.LENGTH_SHORT); LinearLayout toastLayout = (LinearLayout) toast.getView(); TextView toastTV = (TextView) toastLayout.getChildAt(0); toastTV.setTextSize(20); toastTV.setTextColor(Color.WHITE); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } } } private class SaveGameObjectAndPlayersToBaseTask extends AsyncTask<DataAccess, Void, Void> { @Override protected Void doInBackground(DataAccess... params) { Game gameModel = new Game(); gameModel.setCategoryId(currentCategoryId); gameModel.setPlayedOn(new Date()); if (isLocationChecked){ place = city+ ", " + address; gameModel.setLocation(place); } int gameId = (int) params[0].createGame(gameModel); for (Player pl : players) { pl.setGameId(gameId); params[0].createPlayer(pl); } Collections.sort(players); return null; } } }
accelerometer added on next word and correct answer
WhatsTheWord/app/src/main/java/layout/GamePage.java
accelerometer added on next word and correct answer
<ide><path>hatsTheWord/app/src/main/java/layout/GamePage.java <ide> import android.app.Activity; <ide> import android.content.Context; <ide> import android.graphics.Color; <add>import android.hardware.Sensor; <add>import android.hardware.SensorEvent; <add>import android.hardware.SensorEventListener; <add>import android.hardware.SensorManager; <ide> import android.os.AsyncTask; <ide> import android.os.Bundle; <ide> import android.os.CountDownTimer; <ide> import android.support.v4.app.Fragment; <add>import android.util.Log; <ide> import android.view.GestureDetector; <ide> import android.view.Gravity; <ide> import android.view.LayoutInflater; <ide> /** <ide> * A simple {@link Fragment} subclass. <ide> */ <del>public class GamePage extends Fragment implements View.OnClickListener { <add>public class GamePage extends Fragment implements View.OnClickListener, SensorEventListener { <ide> private static final Random random = new Random(); <add> <add> SensorEventListener listener; <ide> <ide> private float x1, x2; <ide> static final int MIN_DISTANCE = 150; <del> private static final int PLAYER_TURN_TIME = 1000; <add> private static final int PLAYER_TURN_TIME = 10000; <add> <add> private SensorManager senSensorManager; <add> private Sensor senAccelerometer; <add> private long lastUpdate = 0; <add> private float last_x, last_y, last_z; <add> private static final int SHAKE_THRESHOLD = 600; <ide> <ide> private List<String> wordsToGuess; <ide> private List<Player> players; <ide> private HashSet<String> usedWords; <ide> private String address; <ide> private String city; <del> private String place; <add> private String place; <ide> private Boolean isLocationChecked; <ide> <ide> TextView timerTextView; <ide> return false; <ide> if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE <ide> && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { <del> if (playerFirstPage.getVisibility() != View.VISIBLE){ <add> if (playerFirstPage.getVisibility() != View.VISIBLE) { <ide> <ide> handleSwipeLeft(); <ide> } <ide> } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE <ide> && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { <del> if (playerFirstPage.getVisibility() != View.VISIBLE){ <add> if (playerFirstPage.getVisibility() != View.VISIBLE) { <ide> <ide> handleSwipeRight(); <ide> } <ide> } <ide> }); <ide> <add> senSensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE); <add> senAccelerometer = senSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); <add> senSensorManager.registerListener(this, senAccelerometer, SensorManager.SENSOR_DELAY_NORMAL); <add> listener = this; <ide> return view; <ide> } <ide> <ide> public void playerTimer() { <ide> CountDownTimer waitTimer; <ide> //TODO: set timer to 60000 <add> senSensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE); <add> senAccelerometer = senSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); <add> senSensorManager.registerListener(this, senAccelerometer, SensorManager.SENSOR_DELAY_NORMAL); <add> listener = this; <ide> waitTimer = new CountDownTimer(PLAYER_TURN_TIME, 1000) { <ide> <ide> public void onTick(long millisUntilFinished) { <ide> <ide> public void onFinish() { <ide> timerTextView.setText("0"); <add> senSensorManager.unregisterListener(listener); <ide> if (currentPlayerIndex == players.size() - 1) { <ide> Collections.sort(players); <ide> String[] playerScores = new String[players.size()]; <ide> new SaveGameObjectAndPlayersToBaseTask().execute((DataAccess) getArguments().getSerializable("data")); <ide> onGameOver.onGameEnding(playerScores); <ide> } else { <add> <ide> randomWordAndTimer.setVisibility(View.INVISIBLE); <ide> currentUserInfo.setVisibility(View.VISIBLE); <ide> <ide> } <ide> } <ide> }.start(); <add> } <add> <add> @Override <add> public void onSensorChanged(SensorEvent sensorEvent) { <add> Sensor mySensor = sensorEvent.sensor; <add> <add>// if (randomWordAndTimer.getVisibility() == View.VISIBLE) { <add>// senSensorManager.unregisterListener(this); <add> <add> <add> if (mySensor.getType() == Sensor.TYPE_ACCELEROMETER) { <add> float x = sensorEvent.values[0]; <add> float y = sensorEvent.values[1]; <add> float z = sensorEvent.values[2]; <add> <add> long curTime = System.currentTimeMillis(); <add> <add> if ((curTime - lastUpdate) > 1000) { <add> long diffTime = (curTime - lastUpdate); <add> lastUpdate = curTime; <add> <add> float speed = Math.abs(x + y + z - last_x - last_y - last_z) / diffTime * 50000; <add> <add> if (speed > SHAKE_THRESHOLD) { <add> <add> } <add> <add> if (z > 3 && y < 5 && x < 0) { //x>0 <add> // Log.d("pingosvam","z > 3 && y<3 gore"); <add> // MySoundManager.playCorrectTone(getContext()); <add> if (playerFirstPage.getVisibility() != View.VISIBLE) { <add> <add> handleSwipeLeft(); <add> } <add> <add> } <add> Log.d("pingosvam x", String.valueOf(x)); <add> <add>// if (z < -5 && y>3 && x>1){ <add>// Log.d("ping","normalno"); <add>// <add>// } <add> <add> <add> if (z < -3 && y < 3 && x < 1) { <add> // Log.d("ping", "dolu"); <add> // MySoundManager.playNextWordTone(getContext()); <add> if (playerFirstPage.getVisibility() != View.VISIBLE) { <add> <add> handleSwipeRight(); <add> } <add> } <add> <add> last_x = x; <add> last_y = y; <add> last_z = z; <add> } <add> } <add> <add> } <add> <add> @Override <add> public void onAccuracyChanged(Sensor sensor, int accuracy) { <add> <ide> } <ide> <ide> public interface OnGameOver { <ide> gameModel.setPlayedOn(new Date()); <ide> <ide> <del> if (isLocationChecked){ <del> place = city+ ", " + address; <add> if (isLocationChecked) { <add> place = city + ", " + address; <ide> gameModel.setLocation(place); <ide> } <ide>
Java
mit
06591698a734604fbb811a024159b293fbf530c6
0
markovandooren/rejuse,markovandooren/rejuse
package be.kuleuven.cs.distrinet.rejuse.association; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList.Builder; import be.kuleuven.cs.distrinet.rejuse.action.Action; import be.kuleuven.cs.distrinet.rejuse.java.collections.Visitor; import be.kuleuven.cs.distrinet.rejuse.predicate.SafePredicate; /** * <p>A class of Relation components for implementing a binding in which the object of * the Reference has a relation with N other objects. This component behaves as a set.</p> * * <center><img src="doc-files/ReferenceSet.png"/></center> * * <p>In UML this class is used for implementing multiplicity n:</p> * * <center><img src="doc-files/referenceset_uml.png"/></center> * * <p>In Java, you get the following situation.</p> * <center><img src="doc-files/referenceset_java.png"/></center> * * <p>Note that the question mark is represented by a <code>Relation</code> object since * we don't know its multiplicity. The double binding between the <code>ReferenceSet</code> * object and <code>A</code> is made by passing <code>this</code> to the constructor of * ReferenceSet.</p> * * <p>This is actually a lightweight version of the APSet class. * of the <a href="http://www.beedra.org">Beedra</a> framework of Jan Dockx.</p> * * <p>This class is typically using in the following way. * <pre><code> *public class A { * * public A() { * _b= new ReferenceSet(this); * } * * public List getBs() { * return _b.getOtherEnds(); * } * * // public Set getBs() { * // return new TreeSet(_b.getOtherEnds()); * // } * * public void addB(B b) { * _b.add(b.getALink()); * } * * public void removeB(B b) { * _b.remove(b.getALink()); * } * * private ReferenceSet _b; *} * </code></pre> * * <p>The other class must have a method <code>getALink()</code>, which returns a * <a href="Relation.html"><code>Relation</code></a> object that represents the other side * of the bi-directional binding. In case the two classes are not in the same package that means * that <code>getALink()</code> must be <code>public</code> there, but that is also the case when * not working with these components. Note that if the binding should not be mutable from class * <code>A</code> the <code>addB()</code> may be removed. Similarly, <code>getBLink()</code> may * be removed if the binding is not mutable from class <code>B</code>.</p> * * <p>If <code>getBs()</code> must return a Set, you should add the result of <code>_b.getOtherEnds()</code> * to a new Set (e.g. TreeSet). The general method <code>getOtherEnds()</code> must return a <code>List</code> * because in some bindings the order may be important.</p> * * @path $Source$ * @version $Revision$ * @date $Date$ * @state $State$ * @author Marko van Dooren * @release $Name$ */ public class OrderedMultiAssociation<FROM,TO> extends AbstractMultiAssociation<FROM,TO> { /* The revision of this class */ public final static String CVS_REVISION ="$Revision$"; //@ public invariant contains(null) == false; //@ public invariant getObject() != null; /*@ @ public invariant (\forall Relation e; contains(e); @ e.contains(this)); @*/ /** * Initialize an empty ReferenceSet for the given object. * * @param object * The object on this side of the binding */ /*@ @ public behavior @ @ pre object != null; @ @ post getObject() == object; @ post (\forall Relation r;; !contains(r)); @*/ public OrderedMultiAssociation(FROM object) { super(object); } public OrderedMultiAssociation(FROM object, int initialSize) { super(object); _initialSize = initialSize; } private int _initialSize; private void initElement() { _elements = new ArrayList<Association<? extends TO,? super FROM>>(_initialSize); } /** * {@inheritDoc} */ public void remove(Association<? extends TO,? super FROM> other) { checkLock(); checkLock(other); if (contains(other)) { other.unregister(this); // Skip a redundant contains check. unregisterPrivate(other); } } @Override public /*@ pure @*/ List<TO> getOtherEnds() { if(isCaching()) { if(_cache == null) { if(_elements != null) { Builder<TO> builder = ImmutableList.<TO>builder(); for(Association<? extends TO,? super FROM> element: _elements) { builder.add(element.getObject()); } _cache = builder.build(); } else { _cache = Collections.EMPTY_LIST; } } return _cache; } else { return doGetOtherEnds(); } } protected /*@ pure @*/ List<TO> doGetOtherEnds() { List<TO> result = new ArrayList<TO>(size()); addOtherEndsTo(result); // increase(); return result; } /** * {@inheritDoc} */ public void clear() { checkLock(); Collection<Association<? extends TO,? super FROM>> rels = new ArrayList<Association<? extends TO,? super FROM>>(_elements); for(Association<? extends TO,? super FROM> rel : rels) { checkLock(rel); } for(Association<? extends TO,? super FROM> rel : rels) { remove(rel); } } /** * {@inheritDoc} */ public void add(Association<? extends TO,? super FROM> element) { if(! contains(element)) { checkLock(); checkLock(element); if(element != null) { element.register(this); // Skip a redundant contains check. registerPrivate(element); } } } /** * {@inheritDoc} */ public void addInFront(Association<? extends TO,? super FROM> element) { if(! contains(element)) { checkLock(); checkLock(element); if(element != null) { element.register(this); // Skip a redundant contains check. registerInFrontPrivate(element); } } } /** * @element the element to be added * @index the base-1 index */ public void addAtIndex(Association<? extends TO,? super FROM> element, int baseOneIndex) { if(! contains(element)) { checkLock(); checkLock(element); if(element != null) { element.register(this); // Skip a redundant contains check. registerAtIndexPrivate(element, baseOneIndex); } } } public void addBefore(TO existing, Association<? extends TO,? super FROM> toBeAdded) { addAtIndex(toBeAdded, indexOf(existing)); } public void addAfter(TO existing, Association<? extends TO,? super FROM> toBeAdded) { addAtIndex(toBeAdded, indexOf(existing)+1); } /** * Replace the given element with a new element */ /*@ @ public behavior @ @ pre element != null; @ pre newElement != null; @ @ post replaced(\old(getOtherRelations()), oldAssociation, newAssociation); @ post oldAssociation.unregistered(\old(other.getOtherAssociations()), this); @ post newAssociation.registered(\old(oldAssociation.getOtherAssociations()),this); @*/ public void replace(Association<? extends TO,? super FROM> oldAssociation, Association<? extends TO,? super FROM> newAssociation) { if(_elements != null) { int index = _elements.indexOf(oldAssociation); if(index != -1) { checkLock(); checkLock(oldAssociation); checkLock(newAssociation); _elements.set(index, newAssociation); newAssociation.register(this); oldAssociation.unregister(this); fireElementReplaced(oldAssociation.getObject(), newAssociation.getObject()); } } } public void addOtherEndsTo(Collection<? super TO> collection) { if(_elements != null) { for(Association<? extends TO,? super FROM> element: _elements) { collection.add(element.getObject()); } } } public TO lastElement() { int size = size(); if(size > 0) { return _elements.get(size-1).getObject(); } else { return null; } } /** * Return the index-th element of this association. The indices start at 1. */ public TO elementAt(int baseOneIndex) { if(baseOneIndex < 1 || baseOneIndex > size()) { throw new IllegalArgumentException(); } // No check needed, if _elements is null, the size is 0 // so the check above will pass and an exception is thrown. return _elements.get(baseOneIndex-1).getObject(); } /** * Return the index of the given element. Indices start at 1. Return -1 if the element is not present in this association. */ /*@ @ public behavior @ @ post elementAt(\result).equals(element); @*/ public int indexOf(TO element) { int index = -1; if(_elements != null) { for(int i = 0; i < _elements.size(); i++) { if(_elements.get(i).getObject().equals(element)) { index = i+1; break; } } } return index; } /** * Return a set containing the Relations at the * other side of this binding. */ /*@ @ also public behavior @ @ post (\forall Relation s;; @ contains(s) <==> \result.contains(s)); @ post \result != null; @*/ public /*@ pure @*/ List<Association<? extends TO,? super FROM>> getOtherAssociations() { return new ArrayList<Association<? extends TO,? super FROM>>(_elements); } @Override protected List<Association<? extends TO, ? super FROM>> internalAssociations() { return _elements; } @Override protected void unregister(Association<? extends TO,? super FROM> association) { // if(contains(association)) { unregisterPrivate(association); // } } private void unregisterPrivate(Association<? extends TO, ? super FROM> association) { if(_elements != null) { boolean removed = _elements.remove(association); if(removed) { fireElementRemoved(association.getObject()); } } } @Override protected void register(Association<? extends TO,? super FROM> association) { if(! contains(association)) { registerPrivate(association); } } private void registerPrivate(Association<? extends TO, ? super FROM> association) { elements().add(association); fireElementAdded(association.getObject()); } private void registerInFrontPrivate(Association<? extends TO, ? super FROM> association) { elements().add(0,association); fireElementAdded(association.getObject()); } private void registerAtIndexPrivate(Association<? extends TO, ? super FROM> association,int index) { elements().add(index-1,association); fireElementAdded(association.getObject()); } private List<Association<? extends TO,? super FROM>> elements() { if(_elements == null) { initElement(); } return _elements; } /*@ @ also public behavior @ @ post \result == (contains(registered)) && @ (\forall Relation r; r != registered; @ oldConnections.contains(r) == contains(r) @ ); @ //TODO: order @*/ public /*@ pure @*/ boolean registered(List<Association<? extends TO,? super FROM>> oldConnections, Association<? extends TO,? super FROM> registered) { boolean result = (oldConnections != null) && (contains(registered)) && (_elements != null); if(result) { for(Association<? extends TO,? super FROM> o: _elements) { if(! contains(o)) { result = false; break; } } } return result; } /*@ @ also public behavior @ @ post \result == (oldConnections.contains(unregistered)) && @ (! contains(unregistered)) && @ (\forall Relation r; r != unregistered; @ oldConnections.contains(r) == contains(r)); @ // TODO: order @*/ public /*@ pure @*/ boolean unregistered(List<Association<? extends TO,? super FROM>> oldConnections, final Association<? extends TO,? super FROM> unregistered) { // FIXME : implementation is not correct return (oldConnections != null) && (oldConnections.contains(unregistered)) && (! contains(unregistered)) && new SafePredicate<Association<? extends TO,? super FROM>>() { public boolean eval(Association<? extends TO,? super FROM> o) { return (o == unregistered) || contains(o); } }.forAll(oldConnections); } /*@ @ also protected behavior @ @ post \result == (relation != null); @*/ protected /*@ pure @*/ boolean isValidElement(Association<? extends TO,? super FROM> relation) { return (relation != null); } /** * Return the size of the ReferenceSet */ /*@ @ public behavior @ @ post \result == getOtherRelations().size(); @*/ public /*@ pure @*/ int size() { return _elements == null ? 0 :_elements.size(); } /** * Check whether or not the given element is connected to * this ReferenceSet. * * @param element * The element of which one wants to know if it is in * this ReferenceSet. */ public /*@ pure @*/ boolean contains(Association<? extends TO,? super FROM> element) { return _elements == null ? false : _elements.contains(element); } /** * The set containing the StructureElements at the n side of the 1-n binding. */ /*@ @ private invariant ! _elements.contains(null); @ private invariant (\forall Object o; _elements.contains(o); @ o instanceof Relation); @*/ private ArrayList<Association<? extends TO,? super FROM>> _elements; @Override public <E extends Exception> void apply(Action<? super TO, E> action) throws E { if(_elements != null) { for(Association<? extends TO,? super FROM> element: _elements) { action.perform(element.getObject()); } } } private List<TO> _cache; public void flushCache() { _cache = null; } }
src/be/kuleuven/cs/distrinet/rejuse/association/OrderedMultiAssociation.java
package be.kuleuven.cs.distrinet.rejuse.association; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList.Builder; import be.kuleuven.cs.distrinet.rejuse.action.Action; import be.kuleuven.cs.distrinet.rejuse.java.collections.Visitor; import be.kuleuven.cs.distrinet.rejuse.predicate.SafePredicate; /** * <p>A class of Relation components for implementing a binding in which the object of * the Reference has a relation with N other objects. This component behaves as a set.</p> * * <center><img src="doc-files/ReferenceSet.png"/></center> * * <p>In UML this class is used for implementing multiplicity n:</p> * * <center><img src="doc-files/referenceset_uml.png"/></center> * * <p>In Java, you get the following situation.</p> * <center><img src="doc-files/referenceset_java.png"/></center> * * <p>Note that the question mark is represented by a <code>Relation</code> object since * we don't know its multiplicity. The double binding between the <code>ReferenceSet</code> * object and <code>A</code> is made by passing <code>this</code> to the constructor of * ReferenceSet.</p> * * <p>This is actually a lightweight version of the APSet class. * of the <a href="http://www.beedra.org">Beedra</a> framework of Jan Dockx.</p> * * <p>This class is typically using in the following way. * <pre><code> *public class A { * * public A() { * _b= new ReferenceSet(this); * } * * public List getBs() { * return _b.getOtherEnds(); * } * * // public Set getBs() { * // return new TreeSet(_b.getOtherEnds()); * // } * * public void addB(B b) { * _b.add(b.getALink()); * } * * public void removeB(B b) { * _b.remove(b.getALink()); * } * * private ReferenceSet _b; *} * </code></pre> * * <p>The other class must have a method <code>getALink()</code>, which returns a * <a href="Relation.html"><code>Relation</code></a> object that represents the other side * of the bi-directional binding. In case the two classes are not in the same package that means * that <code>getALink()</code> must be <code>public</code> there, but that is also the case when * not working with these components. Note that if the binding should not be mutable from class * <code>A</code> the <code>addB()</code> may be removed. Similarly, <code>getBLink()</code> may * be removed if the binding is not mutable from class <code>B</code>.</p> * * <p>If <code>getBs()</code> must return a Set, you should add the result of <code>_b.getOtherEnds()</code> * to a new Set (e.g. TreeSet). The general method <code>getOtherEnds()</code> must return a <code>List</code> * because in some bindings the order may be important.</p> * * @path $Source$ * @version $Revision$ * @date $Date$ * @state $State$ * @author Marko van Dooren * @release $Name$ */ public class OrderedMultiAssociation<FROM,TO> extends AbstractMultiAssociation<FROM,TO> { /* The revision of this class */ public final static String CVS_REVISION ="$Revision$"; //@ public invariant contains(null) == false; //@ public invariant getObject() != null; /*@ @ public invariant (\forall Relation e; contains(e); @ e.contains(this)); @*/ /** * Initialize an empty ReferenceSet for the given object. * * @param object * The object on this side of the binding */ /*@ @ public behavior @ @ pre object != null; @ @ post getObject() == object; @ post (\forall Relation r;; !contains(r)); @*/ public OrderedMultiAssociation(FROM object) { super(object); } public OrderedMultiAssociation(FROM object, int initialSize) { super(object); _initialSize = initialSize; } private int _initialSize; private void initElement() { _elements = new ArrayList<Association<? extends TO,? super FROM>>(_initialSize); } /** * {@inheritDoc} */ public void remove(Association<? extends TO,? super FROM> other) { checkLock(); checkLock(other); if (contains(other)) { other.unregister(this); // Skip a redundant contains check. unregisterPrivate(other); } } @Override public /*@ pure @*/ List<TO> getOtherEnds() { if(isCaching()) { if(_cache == null) { if(_elements != null) { Builder<TO> builder = ImmutableList.<TO>builder(); for(Association<? extends TO,? super FROM> element: _elements) { builder.add(element.getObject()); } _cache = builder.build(); } else { _cache = Collections.EMPTY_LIST; } } return _cache; } else { return doGetOtherEnds(); } } protected /*@ pure @*/ List<TO> doGetOtherEnds() { List<TO> result = new ArrayList<TO>(); addOtherEndsTo(result); // increase(); return result; } /** * {@inheritDoc} */ public void clear() { checkLock(); Collection<Association<? extends TO,? super FROM>> rels = new ArrayList<Association<? extends TO,? super FROM>>(_elements); for(Association<? extends TO,? super FROM> rel : rels) { checkLock(rel); } for(Association<? extends TO,? super FROM> rel : rels) { remove(rel); } } /** * {@inheritDoc} */ public void add(Association<? extends TO,? super FROM> element) { if(! contains(element)) { checkLock(); checkLock(element); if(element != null) { element.register(this); // Skip a redundant contains check. registerPrivate(element); } } } /** * {@inheritDoc} */ public void addInFront(Association<? extends TO,? super FROM> element) { if(! contains(element)) { checkLock(); checkLock(element); if(element != null) { element.register(this); // Skip a redundant contains check. registerInFrontPrivate(element); } } } /** * @element the element to be added * @index the base-1 index */ public void addAtIndex(Association<? extends TO,? super FROM> element, int baseOneIndex) { if(! contains(element)) { checkLock(); checkLock(element); if(element != null) { element.register(this); // Skip a redundant contains check. registerAtIndexPrivate(element, baseOneIndex); } } } public void addBefore(TO existing, Association<? extends TO,? super FROM> toBeAdded) { addAtIndex(toBeAdded, indexOf(existing)); } public void addAfter(TO existing, Association<? extends TO,? super FROM> toBeAdded) { addAtIndex(toBeAdded, indexOf(existing)+1); } /** * Replace the given element with a new element */ /*@ @ public behavior @ @ pre element != null; @ pre newElement != null; @ @ post replaced(\old(getOtherRelations()), oldAssociation, newAssociation); @ post oldAssociation.unregistered(\old(other.getOtherAssociations()), this); @ post newAssociation.registered(\old(oldAssociation.getOtherAssociations()),this); @*/ public void replace(Association<? extends TO,? super FROM> oldAssociation, Association<? extends TO,? super FROM> newAssociation) { if(_elements != null) { int index = _elements.indexOf(oldAssociation); if(index != -1) { checkLock(); checkLock(oldAssociation); checkLock(newAssociation); _elements.set(index, newAssociation); newAssociation.register(this); oldAssociation.unregister(this); fireElementReplaced(oldAssociation.getObject(), newAssociation.getObject()); } } } public void addOtherEndsTo(Collection<? super TO> collection) { if(_elements != null) { for(Association<? extends TO,? super FROM> element: _elements) { collection.add(element.getObject()); } } } public TO lastElement() { int size = size(); if(size > 0) { return _elements.get(size-1).getObject(); } else { return null; } } /** * Return the index-th element of this association. The indices start at 1. */ public TO elementAt(int baseOneIndex) { if(baseOneIndex < 1 || baseOneIndex > size()) { throw new IllegalArgumentException(); } // No check needed, if _elements is null, the size is 0 // so the check above will pass and an exception is thrown. return _elements.get(baseOneIndex-1).getObject(); } /** * Return the index of the given element. Indices start at 1. Return -1 if the element is not present in this association. */ /*@ @ public behavior @ @ post elementAt(\result).equals(element); @*/ public int indexOf(TO element) { int index = -1; if(_elements != null) { for(int i = 0; i < _elements.size(); i++) { if(_elements.get(i).getObject().equals(element)) { index = i+1; break; } } } return index; } /** * Return a set containing the Relations at the * other side of this binding. */ /*@ @ also public behavior @ @ post (\forall Relation s;; @ contains(s) <==> \result.contains(s)); @ post \result != null; @*/ public /*@ pure @*/ List<Association<? extends TO,? super FROM>> getOtherAssociations() { return new ArrayList<Association<? extends TO,? super FROM>>(_elements); } @Override protected List<Association<? extends TO, ? super FROM>> internalAssociations() { return _elements; } @Override protected void unregister(Association<? extends TO,? super FROM> association) { // if(contains(association)) { unregisterPrivate(association); // } } private void unregisterPrivate(Association<? extends TO, ? super FROM> association) { if(_elements != null) { boolean removed = _elements.remove(association); if(removed) { fireElementRemoved(association.getObject()); } } } @Override protected void register(Association<? extends TO,? super FROM> association) { if(! contains(association)) { registerPrivate(association); } } private void registerPrivate(Association<? extends TO, ? super FROM> association) { elements().add(association); fireElementAdded(association.getObject()); } private void registerInFrontPrivate(Association<? extends TO, ? super FROM> association) { elements().add(0,association); fireElementAdded(association.getObject()); } private void registerAtIndexPrivate(Association<? extends TO, ? super FROM> association,int index) { elements().add(index-1,association); fireElementAdded(association.getObject()); } private List<Association<? extends TO,? super FROM>> elements() { if(_elements == null) { initElement(); } return _elements; } /*@ @ also public behavior @ @ post \result == (contains(registered)) && @ (\forall Relation r; r != registered; @ oldConnections.contains(r) == contains(r) @ ); @ //TODO: order @*/ public /*@ pure @*/ boolean registered(List<Association<? extends TO,? super FROM>> oldConnections, Association<? extends TO,? super FROM> registered) { boolean result = (oldConnections != null) && (contains(registered)) && (_elements != null); if(result) { for(Association<? extends TO,? super FROM> o: _elements) { if(! contains(o)) { result = false; break; } } } return result; } /*@ @ also public behavior @ @ post \result == (oldConnections.contains(unregistered)) && @ (! contains(unregistered)) && @ (\forall Relation r; r != unregistered; @ oldConnections.contains(r) == contains(r)); @ // TODO: order @*/ public /*@ pure @*/ boolean unregistered(List<Association<? extends TO,? super FROM>> oldConnections, final Association<? extends TO,? super FROM> unregistered) { // FIXME : implementation is not correct return (oldConnections != null) && (oldConnections.contains(unregistered)) && (! contains(unregistered)) && new SafePredicate<Association<? extends TO,? super FROM>>() { public boolean eval(Association<? extends TO,? super FROM> o) { return (o == unregistered) || contains(o); } }.forAll(oldConnections); } /*@ @ also protected behavior @ @ post \result == (relation != null); @*/ protected /*@ pure @*/ boolean isValidElement(Association<? extends TO,? super FROM> relation) { return (relation != null); } /** * Return the size of the ReferenceSet */ /*@ @ public behavior @ @ post \result == getOtherRelations().size(); @*/ public /*@ pure @*/ int size() { return _elements == null ? 0 :_elements.size(); } /** * Check whether or not the given element is connected to * this ReferenceSet. * * @param element * The element of which one wants to know if it is in * this ReferenceSet. */ public /*@ pure @*/ boolean contains(Association<? extends TO,? super FROM> element) { return _elements == null ? false : _elements.contains(element); } /** * The set containing the StructureElements at the n side of the 1-n binding. */ /*@ @ private invariant ! _elements.contains(null); @ private invariant (\forall Object o; _elements.contains(o); @ o instanceof Relation); @*/ private ArrayList<Association<? extends TO,? super FROM>> _elements; @Override public <E extends Exception> void apply(Action<? super TO, E> action) throws E { if(_elements != null) { for(Association<? extends TO,? super FROM> element: _elements) { action.perform(element.getObject()); } } } private List<TO> _cache; public void flushCache() { _cache = null; } }
create a list of the correct size
src/be/kuleuven/cs/distrinet/rejuse/association/OrderedMultiAssociation.java
create a list of the correct size
<ide><path>rc/be/kuleuven/cs/distrinet/rejuse/association/OrderedMultiAssociation.java <ide> } <ide> <ide> protected /*@ pure @*/ List<TO> doGetOtherEnds() { <del> List<TO> result = new ArrayList<TO>(); <add> List<TO> result = new ArrayList<TO>(size()); <ide> addOtherEndsTo(result); <ide> // increase(); <ide> return result;
JavaScript
mit
04146df57c3cc0f4e7cbe09238ae63cae95e7162
0
zimmen/gulp-twig,zimmen/gulp-twig
var map = require('map-stream'); var rext = require('replace-ext'); var log = require('fancy-log'); var PluginError = require('plugin-error'); const PLUGIN_NAME = 'gulp-twig'; module.exports = function (options) { 'use strict'; options = Object.assign({}, { changeExt: true, extname: '.html' }, options || {}); function modifyContents(file, cb) { var data = file.data || options.data || {}; if (file.isNull()) { return cb(null, file); } if (file.isStream()) { return cb(new PluginError(PLUGIN_NAME, 'Streaming not supported!')); } data._file = file; if(options.changeExt === false || options.extname === true){ data._target = { path: file.path, relative: file.relative } }else{ data._target = { path: rext(file.path, options.extname || ''), relative: rext(file.relative, options.extname || '') } } var Twig = require('twig'), twig = Twig.twig, twigOpts = { path: file.path, async: false }, template; if (options.debug !== undefined) { twigOpts.debug = options.debug; } if (options.trace !== undefined) { twigOpts.trace = options.trace; } if (options.base !== undefined) { twigOpts.base = options.base; } if (options.namespaces !== undefined) { twigOpts.namespaces = options.namespaces; } if (options.cache !== true) { Twig.cache(false); } if (options.functions) { options.functions.forEach(function (func) { Twig.extendFunction(func.name, func.func); }); } if (options.filters) { options.filters.forEach(function (filter) { Twig.extendFilter(filter.name, filter.func); }); } if(options.extend) { Twig.extend(options.extend); delete options.extend; } template = twig(twigOpts); try { file.contents = new Buffer(template.render(data)); }catch(e){ if (options.errorLogToConsole) { log(PLUGIN_NAME + ' ' + e); return cb(); } if (typeof options.onError === 'function') { options.onError(e); return cb(); } return cb(new PluginError(PLUGIN_NAME, e)); } file.path = data._target.path; cb(null, file); } return map(modifyContents); };
index.js
var map = require('map-stream'); var rext = require('replace-ext'); var fancyLog = require('fancy-log'); var PluginError = require('plugin-error'); const PLUGIN_NAME = 'gulp-twig'; module.exports = function (options) { 'use strict'; options = Object.assign({}, { changeExt: true, extname: '.html' }, options || {}); function modifyContents(file, cb) { var data = file.data || options.data || {}; if (file.isNull()) { return cb(null, file); } if (file.isStream()) { return cb(new PluginError(PLUGIN_NAME, 'Streaming not supported!')); } data._file = file; if(options.changeExt === false || options.extname === true){ data._target = { path: file.path, relative: file.relative } }else{ data._target = { path: rext(file.path, options.extname || ''), relative: rext(file.relative, options.extname || '') } } var Twig = require('twig'), twig = Twig.twig, twigOpts = { path: file.path, async: false }, template; if (options.debug !== undefined) { twigOpts.debug = options.debug; } if (options.trace !== undefined) { twigOpts.trace = options.trace; } if (options.base !== undefined) { twigOpts.base = options.base; } if (options.namespaces !== undefined) { twigOpts.namespaces = options.namespaces; } if (options.cache !== true) { Twig.cache(false); } if (options.functions) { options.functions.forEach(function (func) { Twig.extendFunction(func.name, func.func); }); } if (options.filters) { options.filters.forEach(function (filter) { Twig.extendFilter(filter.name, filter.func); }); } if(options.extend) { Twig.extend(options.extend); delete options.extend; } template = twig(twigOpts); try { file.contents = new Buffer(template.render(data)); }catch(e){ if (options.errorLogToConsole) { fancyLog(PLUGIN_NAME + ' ' + e); return cb(); } if (typeof options.onError === 'function') { options.onError(e); return cb(); } return cb(new PluginError(PLUGIN_NAME, e)); } file.path = data._target.path; cb(null, file); } return map(modifyContents); };
Fix variable name
index.js
Fix variable name
<ide><path>ndex.js <ide> var map = require('map-stream'); <ide> var rext = require('replace-ext'); <del>var fancyLog = require('fancy-log'); <add>var log = require('fancy-log'); <ide> var PluginError = require('plugin-error'); <ide> <ide> const PLUGIN_NAME = 'gulp-twig'; <ide> file.contents = new Buffer(template.render(data)); <ide> }catch(e){ <ide> if (options.errorLogToConsole) { <del> fancyLog(PLUGIN_NAME + ' ' + e); <add> log(PLUGIN_NAME + ' ' + e); <ide> return cb(); <ide> } <ide>
Java
mit
3f299c47e28338bc139777cf0134b0ee7d650661
0
ngageoint/geopackage-core-java,boundlessgeo/geopackage-core-java
package mil.nga.giat.geopackage.projection; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; /** * Retrieves the proj4 projection parameter string for an EPSG code * * @author osbornb */ public class ProjectionRetriever { /** * Logger */ private static final Logger log = Logger .getLogger(ProjectionRetriever.class.getName()); /** * Projections property file name */ public static final String PROJECTIONS_PROPERTY_FILE = "projections.properties"; /** * Properties */ private static Properties mProperties; /** * Get the proj4 projection string for the EPSG code * * @param epsg * @return */ public static synchronized String getProjection(long epsg) { if (mProperties == null) { mProperties = initializeConfigurationProperties(); } String value = mProperties.getProperty(String.valueOf(epsg)); if (value == null) { value = mProperties.getProperty(String .valueOf(ProjectionConstants.EPSG_WORLD_GEODETIC_SYSTEM)); } return value; } /** * Initialize the configuration properties * * @return */ private static Properties initializeConfigurationProperties() { Properties properties = new Properties(); Thread.currentThread().setContextClassLoader(ProjectionRetriever.class.getClassLoader()); InputStream in = Thread.currentThread().getContextClassLoader() .getResourceAsStream(PROJECTIONS_PROPERTY_FILE); if (in != null) { try { properties.load(in); } catch (Exception e) { log.log(Level.SEVERE, "Failed to load projections properties file: " + PROJECTIONS_PROPERTY_FILE, e); } finally { try { in.close(); } catch (IOException e) { log.log(Level.WARNING, "Failed to close projections properties file: " + PROJECTIONS_PROPERTY_FILE, e); } } } else { log.log(Level.SEVERE, "Failed to load projections properties, file not found: " + PROJECTIONS_PROPERTY_FILE); } return properties; } }
src/main/java/mil/nga/giat/geopackage/projection/ProjectionRetriever.java
package mil.nga.giat.geopackage.projection; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; /** * Retrieves the proj4 projection parameter string for an EPSG code * * @author osbornb */ public class ProjectionRetriever { /** * Logger */ private static final Logger log = Logger .getLogger(ProjectionRetriever.class.getName()); /** * Projections property file name */ public static final String PROJECTIONS_PROPERTY_FILE = "projections.properties"; /** * Properties */ private static Properties mProperties; /** * Get the proj4 projection string for the EPSG code * * @param epsg * @return */ public static synchronized String getProjection(long epsg) { if (mProperties == null) { mProperties = initializeConfigurationProperties(); } String value = mProperties.getProperty(String.valueOf(epsg)); if (value == null) { value = mProperties.getProperty(String .valueOf(ProjectionConstants.EPSG_WORLD_GEODETIC_SYSTEM)); } return value; } /** * Initialize the configuration properties * * @return */ private static Properties initializeConfigurationProperties() { Properties properties = new Properties(); InputStream in = Thread.currentThread().getContextClassLoader() .getResourceAsStream(PROJECTIONS_PROPERTY_FILE); if (in != null) { try { properties.load(in); } catch (Exception e) { log.log(Level.SEVERE, "Failed to load projections properties file: " + PROJECTIONS_PROPERTY_FILE, e); } finally { try { in.close(); } catch (IOException e) { log.log(Level.WARNING, "Failed to close projections properties file: " + PROJECTIONS_PROPERTY_FILE, e); } } } else { log.log(Level.SEVERE, "Failed to load projections properties, file not found: " + PROJECTIONS_PROPERTY_FILE); } return properties; } }
Set class loader to fix Android issue on some phones
src/main/java/mil/nga/giat/geopackage/projection/ProjectionRetriever.java
Set class loader to fix Android issue on some phones
<ide><path>rc/main/java/mil/nga/giat/geopackage/projection/ProjectionRetriever.java <ide> private static Properties initializeConfigurationProperties() { <ide> Properties properties = new Properties(); <ide> <add> Thread.currentThread().setContextClassLoader(ProjectionRetriever.class.getClassLoader()); <ide> InputStream in = Thread.currentThread().getContextClassLoader() <ide> .getResourceAsStream(PROJECTIONS_PROPERTY_FILE); <ide> if (in != null) {
Java
apache-2.0
f0532a273031f71e75110276833164156c768a6f
0
Akylas/zxing,mig1098/zxing,zilaiyedaren/zxing,tks-dp/zxing,iris-iriswang/zxing,DONIKAN/zxing,1yvT0s/zxing,graug/zxing,DavidLDawes/zxing,ForeverLucky/zxing,Luise-li/zxing,FloatingGuy/zxing,ren545457803/zxing,irfanah/zxing,YongHuiLuo/zxing,wirthandrel/zxing,eight-pack-abdominals/ZXing,keqingyuan/zxing,1shawn/zxing,917386389/zxing,ouyangkongtong/zxing,Akylas/zxing,slayerlp/zxing,sysujzh/zxing,SriramRamesh/zxing,daverix/zxing,finch0219/zxing,daverix/zxing,ChanJLee/zxing,slayerlp/zxing,huopochuan/zxing,10045125/zxing,jianwoo/zxing,Peter32/zxing,gank0326/zxing,easycold/zxing,lijian17/zxing,Akylas/zxing,kailIII/zxing,Kabele/zxing,irfanah/zxing,JerryChin/zxing,reidwooten99/zxing,zxing/zxing,iris-iriswang/zxing,wangxd1213/zxing,bittorrent/zxing,Yi-Kun/zxing,huangzl233/zxing,kharohiy/zxing,Luise-li/zxing,roadrunner1987/zxing,liuchaoya/zxing,freakynit/zxing,irwinai/zxing,geeklain/zxing,1yvT0s/zxing,cnbin/zxing,shixingxing/zxing,wangjun/zxing,Kabele/zxing,ssakitha/sakisolutions,ssakitha/QR-Code-Reader,angrilove/zxing,ale13jo/zxing,qingsong-xu/zxing,fhchina/zxing,sitexa/zxing,catalindavid/zxing,danielZhang0601/zxing,qingsong-xu/zxing,wangxd1213/zxing,yuanhuihui/zxing,daverix/zxing,ZhernakovMikhail/zxing,Akylas/zxing,bestwpw/zxing,meixililu/zxing,rustemferreira/zxing-projectx,huihui4045/zxing,yuanhuihui/zxing,layeka/zxing,rustemferreira/zxing-projectx,zzhui1988/zxing,Peter32/zxing,loaf/zxing,hgl888/zxing,juoni/zxing,ptrnov/zxing,ikenneth/zxing,erbear/zxing,todotobe1/zxing,juoni/zxing,andyao/zxing,nickperez1285/zxing,andyao/zxing,erbear/zxing,liuchaoya/zxing,layeka/zxing,zxing/zxing,catalindavid/zxing,roadrunner1987/zxing,wirthandrel/zxing,wangjun/zxing,DavidLDawes/zxing,hgl888/zxing,RatanPaul/zxing,YuYongzhi/zxing,zjcscut/zxing,BraveAction/zxing,ChristingKim/zxing,l-dobrev/zxing,ctoliver/zxing,praveen062/zxing,qianchenglenger/zxing,cncomer/zxing,ssakitha/QR-Code-Reader,joni1408/zxing,finch0219/zxing,roudunyy/zxing,micwallace/webscanner,ctoliver/zxing,ForeverLucky/zxing,zonamovil/zxing,eddyb/zxing,RatanPaul/zxing,Kevinsu917/zxing,wangdoubleyan/zxing,zjcscut/zxing,ouyangkongtong/zxing,bittorrent/zxing,projectocolibri/zxing,ptrnov/zxing,andyshao/zxing,ikenneth/zxing,GeekHades/zxing,wangdoubleyan/zxing,irwinai/zxing,zhangyihao/zxing,keqingyuan/zxing,eddyb/zxing,geeklain/zxing,t123yh/zxing,OnecloudVideo/zxing,Solvoj/zxing,BraveAction/zxing,1shawn/zxing,allenmo/zxing,danielZhang0601/zxing,t123yh/zxing,fhchina/zxing,meixililu/zxing,lijian17/zxing,HiWong/zxing,daverix/zxing,jianwoo/zxing,DONIKAN/zxing,shwethamallya89/zxing,projectocolibri/zxing,Yi-Kun/zxing,Kevinsu917/zxing,liboLiao/zxing,loaf/zxing,ZhernakovMikhail/zxing,tanelihuuskonen/zxing,saif-hmk/zxing,huihui4045/zxing,befairyliu/zxing,zilaiyedaren/zxing,TestSmirk/zxing,ale13jo/zxing,east119/zxing,angrilove/zxing,tanelihuuskonen/zxing,Fedhaier/zxing,manl1100/zxing,huangsongyan/zxing,HiWong/zxing,mecury/zxing,krishnanMurali/zxing,daverix/zxing,YLBFDEV/zxing,Akylas/zxing,hiagodotme/zxing,roudunyy/zxing,menglifei/zxing,menglifei/zxing,mig1098/zxing,huangsongyan/zxing,huangzl233/zxing,nickperez1285/zxing,ssakitha/sakisolutions,freakynit/zxing,YongHuiLuo/zxing,huopochuan/zxing,micwallace/webscanner,WB-ZZ-TEAM/zxing,sunil1989/zxing,mecury/zxing,kharohiy/zxing,graug/zxing,whycode/zxing,Solvoj/zxing,qianchenglenger/zxing,OnecloudVideo/zxing,917386389/zxing,krishnanMurali/zxing,YLBFDEV/zxing,Akylas/zxing,sitexa/zxing,befairyliu/zxing,MonkeyZZZZ/Zxing,hiagodotme/zxing,JasOXIII/zxing,whycode/zxing,JasOXIII/zxing,TestSmirk/zxing,ChanJLee/zxing,joni1408/zxing,easycold/zxing,micwallace/webscanner,l-dobrev/zxing,GeekHades/zxing,mayfourth/zxing,reidwooten99/zxing,ChristingKim/zxing,WB-ZZ-TEAM/zxing,praveen062/zxing,tks-dp/zxing,zhangyihao/zxing,sysujzh/zxing,andyshao/zxing,zonamovil/zxing,saif-hmk/zxing,GeorgeMe/zxing,shwethamallya89/zxing,zzhui1988/zxing,YuYongzhi/zxing,MonkeyZZZZ/Zxing,liboLiao/zxing,JerryChin/zxing,sunil1989/zxing,GeorgeMe/zxing,Akylas/zxing,Fedhaier/zxing,geeklain/zxing,shixingxing/zxing,ren545457803/zxing,lvbaosong/zxing,cncomer/zxing,eight-pack-abdominals/ZXing,kyosho81/zxing,wanjingyan001/zxing,kailIII/zxing,east119/zxing,wanjingyan001/zxing,SriramRamesh/zxing,FloatingGuy/zxing,mayfourth/zxing,todotobe1/zxing,lvbaosong/zxing,bestwpw/zxing,manl1100/zxing,kyosho81/zxing,allenmo/zxing,cnbin/zxing
/* * Copyright 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.oned; import com.google.zxing.BarcodeFormat; import com.google.zxing.ChecksumException; import com.google.zxing.DecodeHintType; import com.google.zxing.FormatException; import com.google.zxing.NotFoundException; import com.google.zxing.Result; import com.google.zxing.ResultPoint; import com.google.zxing.common.BitArray; import java.util.Arrays; import java.util.Map; /** * <p>Decodes Code 39 barcodes. This does not support "Full ASCII Code 39" yet.</p> * * @author Sean Owen * @see Code93Reader */ public final class Code39Reader extends OneDReader { static final String ALPHABET_STRING = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. *$/+%"; private static final char[] ALPHABET = ALPHABET_STRING.toCharArray(); /** * These represent the encodings of characters, as patterns of wide and narrow bars. * The 9 least-significant bits of each int correspond to the pattern of wide and narrow, * with 1s representing "wide" and 0s representing narrow. */ static final int[] CHARACTER_ENCODINGS = { 0x034, 0x121, 0x061, 0x160, 0x031, 0x130, 0x070, 0x025, 0x124, 0x064, // 0-9 0x109, 0x049, 0x148, 0x019, 0x118, 0x058, 0x00D, 0x10C, 0x04C, 0x01C, // A-J 0x103, 0x043, 0x142, 0x013, 0x112, 0x052, 0x007, 0x106, 0x046, 0x016, // K-T 0x181, 0x0C1, 0x1C0, 0x091, 0x190, 0x0D0, 0x085, 0x184, 0x0C4, 0x094, // U-* 0x0A8, 0x0A2, 0x08A, 0x02A // $-% }; private static final int ASTERISK_ENCODING = CHARACTER_ENCODINGS[39]; private final boolean usingCheckDigit; private final boolean extendedMode; private final StringBuilder decodeRowResult; private final int[] counters; /** * Creates a reader that assumes all encoded data is data, and does not treat the final * character as a check digit. It will not decoded "extended Code 39" sequences. */ public Code39Reader() { this(false); } /** * Creates a reader that can be configured to check the last character as a check digit. * It will not decoded "extended Code 39" sequences. * * @param usingCheckDigit if true, treat the last data character as a check digit, not * data, and verify that the checksum passes. */ public Code39Reader(boolean usingCheckDigit) { this(usingCheckDigit, false); } /** * Creates a reader that can be configured to check the last character as a check digit, * or optionally attempt to decode "extended Code 39" sequences that are used to encode * the full ASCII character set. * * @param usingCheckDigit if true, treat the last data character as a check digit, not * data, and verify that the checksum passes. * @param extendedMode if true, will attempt to decode extended Code 39 sequences in the * text. */ public Code39Reader(boolean usingCheckDigit, boolean extendedMode) { this.usingCheckDigit = usingCheckDigit; this.extendedMode = extendedMode; decodeRowResult = new StringBuilder(20); counters = new int[9]; } @Override public Result decodeRow(int rowNumber, BitArray row, Map<DecodeHintType,?> hints) throws NotFoundException, ChecksumException, FormatException { int[] theCounters = counters; Arrays.fill(theCounters, 0); StringBuilder result = decodeRowResult; result.setLength(0); int[] start = findAsteriskPattern(row, theCounters); // Read off white space int nextStart = row.getNextSet(start[1]); int end = row.getSize(); char decodedChar; int lastStart; do { recordPattern(row, nextStart, theCounters); int pattern = toNarrowWidePattern(theCounters); if (pattern < 0) { throw NotFoundException.getNotFoundInstance(); } decodedChar = patternToChar(pattern); result.append(decodedChar); lastStart = nextStart; for (int counter : theCounters) { nextStart += counter; } // Read off white space nextStart = row.getNextSet(nextStart); } while (decodedChar != '*'); result.setLength(result.length() - 1); // remove asterisk // Look for whitespace after pattern: int lastPatternSize = 0; for (int counter : theCounters) { lastPatternSize += counter; } int whiteSpaceAfterEnd = nextStart - lastStart - lastPatternSize; // If 50% of last pattern size, following last pattern, is not whitespace, fail // (but if it's whitespace to the very end of the image, that's OK) if (nextStart != end && (whiteSpaceAfterEnd << 1) < lastPatternSize) { throw NotFoundException.getNotFoundInstance(); } if (usingCheckDigit) { int max = result.length() - 1; int total = 0; for (int i = 0; i < max; i++) { total += ALPHABET_STRING.indexOf(decodeRowResult.charAt(i)); } if (result.charAt(max) != ALPHABET[total % 43]) { throw ChecksumException.getChecksumInstance(); } result.setLength(max); } if (result.length() == 0) { // false positive throw NotFoundException.getNotFoundInstance(); } String resultString; if (extendedMode) { resultString = decodeExtended(result); } else { resultString = result.toString(); } float left = (float) (start[1] + start[0]) / 2.0f; float right = lastStart + lastPatternSize / 2.0f; return new Result( resultString, null, new ResultPoint[]{ new ResultPoint(left, (float) rowNumber), new ResultPoint(right, (float) rowNumber)}, BarcodeFormat.CODE_39); } private static int[] findAsteriskPattern(BitArray row, int[] counters) throws NotFoundException { int width = row.getSize(); int rowOffset = row.getNextSet(0); int counterPosition = 0; int patternStart = rowOffset; boolean isWhite = false; int patternLength = counters.length; for (int i = rowOffset; i < width; i++) { if (row.get(i) ^ isWhite) { counters[counterPosition]++; } else { if (counterPosition == patternLength - 1) { // Look for whitespace before start pattern, >= 50% of width of start pattern if (toNarrowWidePattern(counters) == ASTERISK_ENCODING && row.isRange(Math.max(0, patternStart - ((i - patternStart) >> 1)), patternStart, false)) { return new int[]{patternStart, i}; } patternStart += counters[0] + counters[1]; System.arraycopy(counters, 2, counters, 0, patternLength - 2); counters[patternLength - 2] = 0; counters[patternLength - 1] = 0; counterPosition--; } else { counterPosition++; } counters[counterPosition] = 1; isWhite = !isWhite; } } throw NotFoundException.getNotFoundInstance(); } // For efficiency, returns -1 on failure. Not throwing here saved as many as 700 exceptions // per image when using some of our blackbox images. private static int toNarrowWidePattern(int[] counters) { int numCounters = counters.length; int maxNarrowCounter = 0; int wideCounters; do { int minCounter = Integer.MAX_VALUE; for (int counter : counters) { if (counter < minCounter && counter > maxNarrowCounter) { minCounter = counter; } } maxNarrowCounter = minCounter; wideCounters = 0; int totalWideCountersWidth = 0; int pattern = 0; for (int i = 0; i < numCounters; i++) { int counter = counters[i]; if (counter > maxNarrowCounter) { pattern |= 1 << (numCounters - 1 - i); wideCounters++; totalWideCountersWidth += counter; } } if (wideCounters == 3) { // Found 3 wide counters, but are they close enough in width? // We can perform a cheap, conservative check to see if any individual // counter is more than 1.5 times the average: for (int i = 0; i < numCounters && wideCounters > 0; i++) { int counter = counters[i]; if (counter > maxNarrowCounter) { wideCounters--; // totalWideCountersWidth = 3 * average, so this checks if counter >= 3/2 * average if ((counter << 1) >= totalWideCountersWidth) { return -1; } } } return pattern; } } while (wideCounters > 3); return -1; } private static char patternToChar(int pattern) throws NotFoundException { for (int i = 0; i < CHARACTER_ENCODINGS.length; i++) { if (CHARACTER_ENCODINGS[i] == pattern) { return ALPHABET[i]; } } throw NotFoundException.getNotFoundInstance(); } private static String decodeExtended(CharSequence encoded) throws FormatException { int length = encoded.length(); StringBuilder decoded = new StringBuilder(length); for (int i = 0; i < length; i++) { char c = encoded.charAt(i); if (c == '+' || c == '$' || c == '%' || c == '/') { char next = encoded.charAt(i + 1); char decodedChar = '\0'; switch (c) { case '+': // +A to +Z map to a to z if (next >= 'A' && next <= 'Z') { decodedChar = (char) (next + 32); } else { throw FormatException.getFormatInstance(); } break; case '$': // $A to $Z map to control codes SH to SB if (next >= 'A' && next <= 'Z') { decodedChar = (char) (next - 64); } else { throw FormatException.getFormatInstance(); } break; case '%': // %A to %E map to control codes ESC to US if (next >= 'A' && next <= 'E') { decodedChar = (char) (next - 38); } else if (next >= 'F' && next <= 'W') { decodedChar = (char) (next - 11); } else { throw FormatException.getFormatInstance(); } break; case '/': // /A to /O map to ! to , and /Z maps to : if (next >= 'A' && next <= 'O') { decodedChar = (char) (next - 32); } else if (next == 'Z') { decodedChar = ':'; } else { throw FormatException.getFormatInstance(); } break; } decoded.append(decodedChar); // bump up i again since we read two characters i++; } else { decoded.append(c); } } return decoded.toString(); } }
core/src/main/java/com/google/zxing/oned/Code39Reader.java
/* * Copyright 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.oned; import com.google.zxing.BarcodeFormat; import com.google.zxing.ChecksumException; import com.google.zxing.DecodeHintType; import com.google.zxing.FormatException; import com.google.zxing.NotFoundException; import com.google.zxing.Result; import com.google.zxing.ResultPoint; import com.google.zxing.common.BitArray; import java.util.Arrays; import java.util.Map; /** * <p>Decodes Code 39 barcodes. This does not support "Full ASCII Code 39" yet.</p> * * @author Sean Owen * @see Code93Reader */ public final class Code39Reader extends OneDReader { static final String ALPHABET_STRING = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. *$/+%"; private static final char[] ALPHABET = ALPHABET_STRING.toCharArray(); /** * These represent the encodings of characters, as patterns of wide and narrow bars. * The 9 least-significant bits of each int correspond to the pattern of wide and narrow, * with 1s representing "wide" and 0s representing narrow. */ static final int[] CHARACTER_ENCODINGS = { 0x034, 0x121, 0x061, 0x160, 0x031, 0x130, 0x070, 0x025, 0x124, 0x064, // 0-9 0x109, 0x049, 0x148, 0x019, 0x118, 0x058, 0x00D, 0x10C, 0x04C, 0x01C, // A-J 0x103, 0x043, 0x142, 0x013, 0x112, 0x052, 0x007, 0x106, 0x046, 0x016, // K-T 0x181, 0x0C1, 0x1C0, 0x091, 0x190, 0x0D0, 0x085, 0x184, 0x0C4, 0x094, // U-* 0x0A8, 0x0A2, 0x08A, 0x02A // $-% }; private static final int ASTERISK_ENCODING = CHARACTER_ENCODINGS[39]; private final boolean usingCheckDigit; private final boolean extendedMode; private final StringBuilder decodeRowResult; private final int[] counters; /** * Creates a reader that assumes all encoded data is data, and does not treat the final * character as a check digit. It will not decoded "extended Code 39" sequences. */ public Code39Reader() { this(false); } /** * Creates a reader that can be configured to check the last character as a check digit. * It will not decoded "extended Code 39" sequences. * * @param usingCheckDigit if true, treat the last data character as a check digit, not * data, and verify that the checksum passes. */ public Code39Reader(boolean usingCheckDigit) { this(usingCheckDigit, false); } /** * Creates a reader that can be configured to check the last character as a check digit, * or optionally attempt to decode "extended Code 39" sequences that are used to encode * the full ASCII character set. * * @param usingCheckDigit if true, treat the last data character as a check digit, not * data, and verify that the checksum passes. * @param extendedMode if true, will attempt to decode extended Code 39 sequences in the * text. */ public Code39Reader(boolean usingCheckDigit, boolean extendedMode) { this.usingCheckDigit = usingCheckDigit; this.extendedMode = extendedMode; decodeRowResult = new StringBuilder(20); counters = new int[9]; } @Override public Result decodeRow(int rowNumber, BitArray row, Map<DecodeHintType,?> hints) throws NotFoundException, ChecksumException, FormatException { int[] theCounters = counters; Arrays.fill(theCounters, 0); StringBuilder result = decodeRowResult; result.setLength(0); int[] start = findAsteriskPattern(row, theCounters); // Read off white space int nextStart = row.getNextSet(start[1]); int end = row.getSize(); char decodedChar; int lastStart; do { recordPattern(row, nextStart, theCounters); int pattern = toNarrowWidePattern(theCounters); if (pattern < 0) { throw NotFoundException.getNotFoundInstance(); } decodedChar = patternToChar(pattern); result.append(decodedChar); lastStart = nextStart; for (int counter : theCounters) { nextStart += counter; } // Read off white space nextStart = row.getNextSet(nextStart); } while (decodedChar != '*'); result.setLength(result.length() - 1); // remove asterisk // Look for whitespace after pattern: int lastPatternSize = 0; for (int counter : theCounters) { lastPatternSize += counter; } int whiteSpaceAfterEnd = nextStart - lastStart - lastPatternSize; // If 50% of last pattern size, following last pattern, is not whitespace, fail // (but if it's whitespace to the very end of the image, that's OK) if (nextStart != end && (whiteSpaceAfterEnd >> 1) < lastPatternSize) { throw NotFoundException.getNotFoundInstance(); } if (usingCheckDigit) { int max = result.length() - 1; int total = 0; for (int i = 0; i < max; i++) { total += ALPHABET_STRING.indexOf(decodeRowResult.charAt(i)); } if (result.charAt(max) != ALPHABET[total % 43]) { throw ChecksumException.getChecksumInstance(); } result.setLength(max); } if (result.length() == 0) { // false positive throw NotFoundException.getNotFoundInstance(); } String resultString; if (extendedMode) { resultString = decodeExtended(result); } else { resultString = result.toString(); } float left = (float) (start[1] + start[0]) / 2.0f; float right = lastStart + lastPatternSize / 2.0f; return new Result( resultString, null, new ResultPoint[]{ new ResultPoint(left, (float) rowNumber), new ResultPoint(right, (float) rowNumber)}, BarcodeFormat.CODE_39); } private static int[] findAsteriskPattern(BitArray row, int[] counters) throws NotFoundException { int width = row.getSize(); int rowOffset = row.getNextSet(0); int counterPosition = 0; int patternStart = rowOffset; boolean isWhite = false; int patternLength = counters.length; for (int i = rowOffset; i < width; i++) { if (row.get(i) ^ isWhite) { counters[counterPosition]++; } else { if (counterPosition == patternLength - 1) { // Look for whitespace before start pattern, >= 50% of width of start pattern if (toNarrowWidePattern(counters) == ASTERISK_ENCODING && row.isRange(Math.max(0, patternStart - ((i - patternStart) >> 1)), patternStart, false)) { return new int[]{patternStart, i}; } patternStart += counters[0] + counters[1]; System.arraycopy(counters, 2, counters, 0, patternLength - 2); counters[patternLength - 2] = 0; counters[patternLength - 1] = 0; counterPosition--; } else { counterPosition++; } counters[counterPosition] = 1; isWhite = !isWhite; } } throw NotFoundException.getNotFoundInstance(); } // For efficiency, returns -1 on failure. Not throwing here saved as many as 700 exceptions // per image when using some of our blackbox images. private static int toNarrowWidePattern(int[] counters) { int numCounters = counters.length; int maxNarrowCounter = 0; int wideCounters; do { int minCounter = Integer.MAX_VALUE; for (int counter : counters) { if (counter < minCounter && counter > maxNarrowCounter) { minCounter = counter; } } maxNarrowCounter = minCounter; wideCounters = 0; int totalWideCountersWidth = 0; int pattern = 0; for (int i = 0; i < numCounters; i++) { int counter = counters[i]; if (counter > maxNarrowCounter) { pattern |= 1 << (numCounters - 1 - i); wideCounters++; totalWideCountersWidth += counter; } } if (wideCounters == 3) { // Found 3 wide counters, but are they close enough in width? // We can perform a cheap, conservative check to see if any individual // counter is more than 1.5 times the average: for (int i = 0; i < numCounters && wideCounters > 0; i++) { int counter = counters[i]; if (counter > maxNarrowCounter) { wideCounters--; // totalWideCountersWidth = 3 * average, so this checks if counter >= 3/2 * average if ((counter << 1) >= totalWideCountersWidth) { return -1; } } } return pattern; } } while (wideCounters > 3); return -1; } private static char patternToChar(int pattern) throws NotFoundException { for (int i = 0; i < CHARACTER_ENCODINGS.length; i++) { if (CHARACTER_ENCODINGS[i] == pattern) { return ALPHABET[i]; } } throw NotFoundException.getNotFoundInstance(); } private static String decodeExtended(CharSequence encoded) throws FormatException { int length = encoded.length(); StringBuilder decoded = new StringBuilder(length); for (int i = 0; i < length; i++) { char c = encoded.charAt(i); if (c == '+' || c == '$' || c == '%' || c == '/') { char next = encoded.charAt(i + 1); char decodedChar = '\0'; switch (c) { case '+': // +A to +Z map to a to z if (next >= 'A' && next <= 'Z') { decodedChar = (char) (next + 32); } else { throw FormatException.getFormatInstance(); } break; case '$': // $A to $Z map to control codes SH to SB if (next >= 'A' && next <= 'Z') { decodedChar = (char) (next - 64); } else { throw FormatException.getFormatInstance(); } break; case '%': // %A to %E map to control codes ESC to US if (next >= 'A' && next <= 'E') { decodedChar = (char) (next - 38); } else if (next >= 'F' && next <= 'W') { decodedChar = (char) (next - 11); } else { throw FormatException.getFormatInstance(); } break; case '/': // /A to /O map to ! to , and /Z maps to : if (next >= 'A' && next <= 'O') { decodedChar = (char) (next - 32); } else if (next == 'Z') { decodedChar = ':'; } else { throw FormatException.getFormatInstance(); } break; } decoded.append(decodedChar); // bump up i again since we read two characters i++; } else { decoded.append(c); } } return decoded.toString(); } }
Issue #86 : Fix logic error in Code 39 that was requiring too much quiet zone
core/src/main/java/com/google/zxing/oned/Code39Reader.java
Issue #86 : Fix logic error in Code 39 that was requiring too much quiet zone
<ide><path>ore/src/main/java/com/google/zxing/oned/Code39Reader.java <ide> int whiteSpaceAfterEnd = nextStart - lastStart - lastPatternSize; <ide> // If 50% of last pattern size, following last pattern, is not whitespace, fail <ide> // (but if it's whitespace to the very end of the image, that's OK) <del> if (nextStart != end && (whiteSpaceAfterEnd >> 1) < lastPatternSize) { <add> if (nextStart != end && (whiteSpaceAfterEnd << 1) < lastPatternSize) { <ide> throw NotFoundException.getNotFoundInstance(); <ide> } <ide>
Java
mit
e735bdd276fed57aa2c014ab0b3ed7b6d505884e
0
sodash/open-code,sodash/open-code,sodash/open-code,sodash/open-code,sodash/open-code,sodash/open-code
package com.winterwell.bob.wwjobs; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import com.winterwell.bob.Bob; import com.winterwell.bob.BuildTask; import com.winterwell.bob.tasks.BigJarTask; import com.winterwell.bob.tasks.CompileTask; import com.winterwell.bob.tasks.CopyTask; import com.winterwell.bob.tasks.EclipseClasspath; import com.winterwell.bob.tasks.GitTask; import com.winterwell.bob.tasks.JUnitTask; import com.winterwell.bob.tasks.JarTask; import com.winterwell.bob.tasks.MavenDependencyTask; import com.winterwell.bob.tasks.SCPTask; import com.winterwell.bob.tasks.SyncEclipseClasspathTask; import com.winterwell.bob.tasks.WinterwellProjectFinder; import com.winterwell.utils.FailureException; import com.winterwell.utils.StrUtils; import com.winterwell.utils.Utils; import com.winterwell.utils.containers.ArraySet; import com.winterwell.utils.containers.Containers; import com.winterwell.utils.io.FileUtils; import com.winterwell.utils.log.Log; import com.winterwell.utils.time.Time; import com.winterwell.utils.web.WebUtils2; /** * Build & copy into code/lib * @author daniel * */ public class BuildWinterwellProject extends BuildTask { /** * @deprecated Is this used?? */ private static final String DEPENDENCIES_ALL = "lib"; protected boolean makeFatJar; private String mainClass; private File fatJar; @Override protected String getTaskName() { return super.getTaskName()+"-"+getProjectName(); } /** * {@inheritDoc} * * Uses Eclipse .classpath file to find projects. * Returns a fresh ArrayList which can be modified safely. */ @Override public List<BuildTask> getDependencies() { ArraySet deps = new ArraySet(); // what projects does Eclipse specify? EclipseClasspath ec = new EclipseClasspath(projectDir); List<String> projects = ec.getReferencedProjects(); for (String pname : projects) { WinterwellProjectFinder pf = new WinterwellProjectFinder(); getDependency2_project(deps, pname, pf); } return new ArrayList(deps); } private void getDependency2_project(ArraySet deps, String pname, WinterwellProjectFinder pf) { File pdir = pf.apply(pname); if (pdir==null || ! pdir.isDirectory()) { return; } File bfile = Bob.findBuildScript2(pdir, null); if (bfile != null) { // Use a forked Bob to pull in dependencies?? // or a WW task?? String builderClass = FileUtils.getRelativePath(bfile, pdir); // HACK: pop the first folder?? usually builder/ int slashi = builderClass.indexOf('/'); if (slashi > 0) { builderClass = builderClass.substring(slashi+1, builderClass.length()); } // make file path into package name builderClass = builderClass.replace('/', '.').substring(0, builderClass.length()-5); // make a WWDep task WWDependencyTask wwdt = new WWDependencyTask(pname, builderClass); deps.add(wwdt); } else { // HACK look in wwjobs try { String pname2 = pname.replace("winterwell.", ""); String cname = BuildUtils.class.getPackage().getName()+".Build"+StrUtils.toTitleCase(pname2); Class<?> bt = Class.forName(cname); deps.add(bt.newInstance()); } catch(Throwable ex) { // oh well Log.d("BuildWinterwellProject", "skip dep for project "+pname); } } } protected boolean isCompile() { return compile; } protected File doFatJar() { Collection<File> jars = new ArraySet(); // this projects jar! jars.add(getJar()); // lib File libs = new File(projectDir, DEPENDENCIES_ALL); if (libs.isDirectory()) { List<File> jars2 = FileUtils.find(libs, ".*\\.jar"); jars.addAll(jars2); } // maven deps File deps = new File(projectDir, MavenDependencyTask.MAVEN_DEPENDENCIES_FOLDER); if (deps.isDirectory()) { List<File> jars2 = FileUtils.find(deps, ".*\\.jar"); jars.addAll(jars2); } // eclipse deps EclipseClasspath ec = new EclipseClasspath(projectDir); ec.setIncludeProjectJars(true); List<String> projects = ec.getReferencedProjects(); Set<File> ecjars = ec.getCollectedLibs(); jars.addAll(ecjars); // bundle File fatjar = new File(projectName+"-all.jar"); // System.out.println(Printer.toString(jars,"\n\t")); BigJarTask jt = new BigJarTask(fatjar, jars); setJarManifest(jt, projectDir, projectDir.getName()+" fat-jar (c) Winterwell. All rights reserved."); jt.run(); jt.close(); // done report.put("fat-jar", jt.getJar().getAbsolutePath()); this.fatJar = jt.getJar(); return jt.getJar(); } /** * @return the jar file (after building!) */ public File getJar() { if (jarFile==null) { jarFile = new File(getOutputDir(), projectName+ ".jar"); } return jarFile; } /** * This is normally auto-set. * Use this only if you need to give the jar a special name. * @param _jarFile */ public void setJar(File _jarFile) { this.jarFile = _jarFile; } private File getOutputDir() { if (outDir==null) { return projectDir; } return outDir; } /** * null by default. If set, put output files into here */ protected File outDir; /** * null by default. If set, put output files into here */ public void setOutDir(File outDir) { this.outDir = outDir; } /** * @deprecated This creates a build-time dependency on a *compiled* version of the main class. * Which probably blocks command-line invocation. Use the String version instead * @param mainClass */ public void setMainClass(Class mainClass) { setMainClass(mainClass.getCanonicalName()); } public void setMainClass(String mainClass) { this.mainClass = mainClass; } public final File projectDir; protected boolean incSrc; private File jarFile; private String version; private boolean compile = true; protected boolean scpToWW; protected String projectName; public String getProjectName() { return projectName; } public BuildWinterwellProject setScpToWW(boolean scpToWW) { this.scpToWW = scpToWW; return this; } /** * true by default. If false, dont run the compiler * @param compile * @return */ public BuildWinterwellProject setCompile(boolean compile) { this.compile = compile; return this; } public BuildWinterwellProject setVersion(String version) { this.version = version; return this; } public BuildWinterwellProject setIncSrc(boolean incSrc) { this.incSrc = incSrc; return this; } /** * HACK try a few "standard" places to find the project * @param projectName */ public BuildWinterwellProject(String projectName) { this(guessProjectDir(projectName), projectName); } /** * TODO refactor with {@link EclipseClasspath} so they share code. * @see WinterwellProjectFinder * @param _projectName * @return */ private static File guessProjectDir(String _projectName) { WinterwellProjectFinder wpg = new WinterwellProjectFinder(); return wpg.apply(_projectName); } public BuildWinterwellProject(File projectDir, String projectName) { assert projectDir != null : projectName; this.projectDir = projectDir; assert projectDir.isDirectory() : projectDir+" "+this; if (projectName==null) projectName = projectDir.getName(); this.projectName = projectName; } public BuildWinterwellProject(File projectDir) { this(projectDir, null); } @Override public void doTask() throws Exception { File srcDir = getJavaSrcDir(); File binDir = getBinDir(); binDir.mkdir(); assert binDir.isDirectory() : binDir.getAbsoluteFile(); // compile doTask2_compile(srcDir, binDir); // Jar File tempJar = File.createTempFile("temp", ".jar"); JarTask jar = new JarTask(tempJar, getBinDir()); jar.setAppend(false); setJarManifest(jar, srcDir, projectDir.getName()+" library (c) Winterwell. All rights reserved."); jar.run(); if ( ! tempJar.isFile()) throw new FailureException("make jar failed?! "+this+" "+getJar()); // replace the old jar FileUtils.move(tempJar, getJar()); report.put("jar", getJar().getAbsolutePath()); // source code? if (incSrc) { JarTask jar2 = new JarTask(getJar(), new File(projectDir, "src")); jar2.setAppend(true); jar2.run(); } // fat jar? if (makeFatJar) { doFatJar(); } // attempt to upload (but don't block) doSCP(); // update classpath? HACK (we could prob run this more but safer to do less often) List<MavenDependencyTask> mdts = Containers.filterByClass(getDependencies(), MavenDependencyTask.class); if ( ! mdts.isEmpty()) { boolean isClean = mdts.get(0).isCleanOutputDirectory(); boolean skipped = mdts.get(0).isSkipFlag(); if (isClean && ! skipped) { SyncEclipseClasspathTask sync = new SyncEclipseClasspathTask(projectDir); try { sync.run(); } catch(Exception ex) { // allow failure eg file permissions as this is a nicety not a vital build step Log.w(LOGTAG, ex); } } } } private void setJarManifest(JarTask jar, File projectDir, String title) { jar.setManifestProperty(JarTask.MANIFEST_TITLE, title); if (mainClass!=null) { // TODO itd be nice to test after whether the mainClass is in the jar jar.setManifestProperty(JarTask.MANIFEST_MAIN_CLASS, mainClass); } // Version String gitiv = null, by = null; try { // go up until we're in git or fail File repo = projectDir; while(repo!=null) { if (new File(repo, ".git").exists()) break; repo = repo.getParentFile(); } if (repo!=null) { Map<String, Object> gitInfo = GitTask.getLastCommitInfo(repo); Object branch = gitInfo.get("branch"); gitiv = "git: "+gitInfo.get("hash") +" "+gitInfo.get("subject") // non-master branch (master is not worth stating) + (branch!=null && ! "master".equals(branch)? " "+branch : "") ; } // Git details as their own property e.g. "branch"? No this upsets IntelliJ // So we pack them into version. by = "by: "+WebUtils2.hostname(); } catch(Throwable ex) { Log.w(LOGTAG, this+" "+ex); } // include version, time, and a unique nonce jar.setManifestProperty(JarTask.MANIFEST_IMPLEMENTATION_VERSION, StrUtils.joinWithSkip(" ", version, new Time().ddMMyyyy(), "nonce_"+Utils.getRandomString(4), gitiv, by )); // vendor jar.setManifestProperty("Implementation-Vendor", "Winterwell"); } private void doSCP() { if ( ! scpToWW) return; { String remoteJar = "/home/winterwell/public-software/"+getJar().getName(); SCPTask scp = new SCPTask(getJar(), "[email protected]", remoteJar); // this is online at: https://www.winterwell.com/software/downloads scp.setMkdirTask(false); scp.runInThread(); report.put("scp to remote", "winterwell.com:"+remoteJar); } if (makeFatJar && getFatJar()!=null) { String remoteJar = "/home/winterwell/public-software/"+getFatJar().getName(); SCPTask scp = new SCPTask(getFatJar(), "[email protected]", remoteJar); // this is online at: https://www.winterwell.com/software/downloads scp.setMkdirTask(false); scp.runInThread(); report.put("scp to remote", "winterwell.com:"+remoteJar); } // also scp maven file? // Hm -- transitive dependencies?? // Maybe the best solution is for WWDepProject to try and checkout from git?? // { // String remoteJar = "/home/winterwell/public-software/pom.bob."+getProjectName()+".xml"; // SCPTask scp = new SCPTask(pom, "[email protected]", remoteJar); // // this is online at: https://www.winterwell.com/software/downloads // scp.setMkdirTask(false); // scp.runInThread(); // report.put("scp pom to remote", "winterwell.com:"+remoteJar); // } } public File getFatJar() { return fatJar; } protected File getBinDir() { return new File(projectDir, "bin"); } /** * * @return the Java source directory */ protected File getJavaSrcDir() { // flat /src or maven-style src/java? File s = new File(projectDir, "src/java"); if (s.isDirectory()) { return s; } s = new File(projectDir, "src"); return s; } protected void doTask2_compile(File srcDir, File binDir) { // FIXME Compile seeing errors in Windows re XStream dependency! // FIXME Compile seeing errors on Linux when run from JUnit but not when bob is run from the command line ?! Nov 2018 if (compile) { try { assert projectDir != null : this; CompileTask compile = new CompileTask(srcDir, binDir); // classpath EclipseClasspath ec = new EclipseClasspath(projectDir); ec.setIncludeProjectJars(true); Set<File> libs = ec.getCollectedLibs(); compile.setClasspath(libs); // compile.setSrcJavaVersion("1.9"); compile.setOutputJavaVersion("11"); // Java 11 jars compile.setDebug(true); compile.run(); compile.close(); } catch(Exception ex) { Log.e(ex); // :'( Dec 2018 Why?? } } // also copy any resources across?? CopyTask nonJava = new CopyTask(srcDir, binDir); nonJava.setResolveSymLinks(true); nonJava.setNegativeFilter(".*\\.java"); nonJava.setIncludeHiddenFiles(false); // nonJava.setVerbosity(Level.ALL); nonJava.run(); } /** * TODO this finds no tests?? maybe cos we have to compile the tests dir too. Dunno -- parking for now. * @return */ public int doTest() { // if (true) return 0; // FIXME File outputFile = new File(projectDir, "test-output/unit-tests-report.html"); JUnitTask junit = new JUnitTask( null, getTestBinDir(), outputFile); junit.run(); int good = junit.getSuccessCount(); int bad = junit.getFailureCount(); return bad; } protected File getTestBinDir() { // NB not all projects are set to use this (yet) return new File(projectDir, "bin.test"); } public BuildWinterwellProject setMakeFatJar(boolean b) { makeFatJar = b; return this; } @Override public String toString() { return getClass().getSimpleName()+"[projectName=" + projectName + "]"; } }
winterwell.bob/src/com/winterwell/bob/wwjobs/BuildWinterwellProject.java
package com.winterwell.bob.wwjobs; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import com.winterwell.bob.Bob; import com.winterwell.bob.BuildTask; import com.winterwell.bob.tasks.BigJarTask; import com.winterwell.bob.tasks.CompileTask; import com.winterwell.bob.tasks.CopyTask; import com.winterwell.bob.tasks.EclipseClasspath; import com.winterwell.bob.tasks.GitTask; import com.winterwell.bob.tasks.JUnitTask; import com.winterwell.bob.tasks.JarTask; import com.winterwell.bob.tasks.MavenDependencyTask; import com.winterwell.bob.tasks.SCPTask; import com.winterwell.bob.tasks.SyncEclipseClasspathTask; import com.winterwell.bob.tasks.WinterwellProjectFinder; import com.winterwell.utils.FailureException; import com.winterwell.utils.StrUtils; import com.winterwell.utils.Utils; import com.winterwell.utils.containers.ArraySet; import com.winterwell.utils.containers.Containers; import com.winterwell.utils.io.FileUtils; import com.winterwell.utils.log.Log; import com.winterwell.utils.time.Time; import com.winterwell.utils.web.WebUtils2; /** * Build & copy into code/lib * @author daniel * */ public class BuildWinterwellProject extends BuildTask { /** * @deprecated Is this used?? */ private static final String DEPENDENCIES_ALL = "lib"; protected boolean makeFatJar; private String mainClass; private File fatJar; @Override protected String getTaskName() { return super.getTaskName()+"-"+getProjectName(); } /** * {@inheritDoc} * * Uses Eclipse .classpath file to find projects. * Returns a fresh ArrayList which can be modified safely. */ @Override public List<BuildTask> getDependencies() { ArraySet deps = new ArraySet(); // what projects does Eclipse specify? EclipseClasspath ec = new EclipseClasspath(projectDir); List<String> projects = ec.getReferencedProjects(); for (String pname : projects) { WinterwellProjectFinder pf = new WinterwellProjectFinder(); getDependency2_project(deps, pname, pf); } return new ArrayList(deps); } private void getDependency2_project(ArraySet deps, String pname, WinterwellProjectFinder pf) { File pdir = pf.apply(pname); if (pdir==null || ! pdir.isDirectory()) { return; } File bfile = Bob.findBuildScript2(pdir, null); if (bfile != null) { // Use a forked Bob to pull in dependencies?? // or a WW task?? String builderClass = FileUtils.getRelativePath(bfile, pdir); // HACK: pop the first folder?? usually builder/ int slashi = builderClass.indexOf('/'); if (slashi > 0) { builderClass = builderClass.substring(slashi+1, builderClass.length()); } // make file path into package name builderClass = builderClass.replace('/', '.').substring(0, builderClass.length()-5); // make a WWDep task WWDependencyTask wwdt = new WWDependencyTask(pname, builderClass); deps.add(wwdt); } else { // HACK look in wwjobs try { String pname2 = pname.replace("winterwell.", ""); String cname = BuildUtils.class.getPackage().getName()+".Build"+StrUtils.toTitleCase(pname2); Class<?> bt = Class.forName(cname); deps.add(bt.newInstance()); } catch(Throwable ex) { // oh well Log.d("BuildWinterwellProject", "skip dep for project "+pname); } } } protected boolean isCompile() { return compile; } protected File doFatJar() { Collection<File> jars = new ArraySet(); // this projects jar! jars.add(getJar()); // lib File libs = new File(projectDir, DEPENDENCIES_ALL); if (libs.isDirectory()) { List<File> jars2 = FileUtils.find(libs, ".*\\.jar"); jars.addAll(jars2); } // maven deps File deps = new File(projectDir, MavenDependencyTask.MAVEN_DEPENDENCIES_FOLDER); if (deps.isDirectory()) { List<File> jars2 = FileUtils.find(deps, ".*\\.jar"); jars.addAll(jars2); } // eclipse deps EclipseClasspath ec = new EclipseClasspath(projectDir); ec.setIncludeProjectJars(true); List<String> projects = ec.getReferencedProjects(); Set<File> ecjars = ec.getCollectedLibs(); jars.addAll(ecjars); // bundle File fatjar = new File(projectName+"-all.jar"); // System.out.println(Printer.toString(jars,"\n\t")); BigJarTask jt = new BigJarTask(fatjar, jars); setJarManifest(jt, projectDir, projectDir.getName()+" fat-jar (c) Winterwell. All rights reserved."); jt.run(); jt.close(); // done report.put("fat-jar", jt.getJar().getAbsolutePath()); this.fatJar = jt.getJar(); return jt.getJar(); } /** * @return the jar file (after building!) */ public File getJar() { if (jarFile==null) { jarFile = new File(getOutputDir(), projectName+ ".jar"); } return jarFile; } /** * This is normally auto-set. * Use this only if you need to give the jar a special name. * @param _jarFile */ public void setJar(File _jarFile) { this.jarFile = _jarFile; } private File getOutputDir() { if (outDir==null) { return projectDir; } return outDir; } /** * null by default. If set, put output files into here */ protected File outDir; /** * null by default. If set, put output files into here */ public void setOutDir(File outDir) { this.outDir = outDir; } /** * @deprecated This creates a build-time dependency on a *compiled* version of the main class. * Which probably blocks command-line invocation. Use the String version instead * @param mainClass */ public void setMainClass(Class mainClass) { setMainClass(mainClass.getCanonicalName()); } public void setMainClass(String mainClass) { this.mainClass = mainClass; } public final File projectDir; protected boolean incSrc; private File jarFile; private String version; private boolean compile = true; protected boolean scpToWW; protected String projectName; public String getProjectName() { return projectName; } public BuildWinterwellProject setScpToWW(boolean scpToWW) { this.scpToWW = scpToWW; return this; } /** * true by default. If false, dont run the compiler * @param compile * @return */ public BuildWinterwellProject setCompile(boolean compile) { this.compile = compile; return this; } public BuildWinterwellProject setVersion(String version) { this.version = version; return this; } public BuildWinterwellProject setIncSrc(boolean incSrc) { this.incSrc = incSrc; return this; } /** * HACK try a few "standard" places to find the project * @param projectName */ public BuildWinterwellProject(String projectName) { this(guessProjectDir(projectName), projectName); } /** * TODO refactor with {@link EclipseClasspath} so they share code. * @see WinterwellProjectFinder * @param _projectName * @return */ private static File guessProjectDir(String _projectName) { WinterwellProjectFinder wpg = new WinterwellProjectFinder(); return wpg.apply(_projectName); } public BuildWinterwellProject(File projectDir, String projectName) { assert projectDir != null : projectName; this.projectDir = projectDir; assert projectDir.isDirectory() : projectDir+" "+this; if (projectName==null) projectName = projectDir.getName(); this.projectName = projectName; } public BuildWinterwellProject(File projectDir) { this(projectDir, null); } @Override public void doTask() throws Exception { File srcDir = getJavaSrcDir(); File binDir = getBinDir(); binDir.mkdir(); assert binDir.isDirectory() : binDir.getAbsoluteFile(); // compile doTask2_compile(srcDir, binDir); // Jar File tempJar = File.createTempFile("temp", ".jar"); JarTask jar = new JarTask(tempJar, getBinDir()); jar.setAppend(false); setJarManifest(jar, srcDir, projectDir.getName()+" library (c) Winterwell. All rights reserved."); jar.run(); if ( ! tempJar.isFile()) throw new FailureException("make jar failed?! "+this+" "+getJar()); // replace the old jar FileUtils.move(tempJar, getJar()); report.put("jar", getJar().getAbsolutePath()); // source code? if (incSrc) { JarTask jar2 = new JarTask(getJar(), new File(projectDir, "src")); jar2.setAppend(true); jar2.run(); } // fat jar? if (makeFatJar) { doFatJar(); } // attempt to upload (but don't block) doSCP(); // update classpath? HACK (we could prob run this more but safer to do less often) List<MavenDependencyTask> mdts = Containers.filterByClass(getDependencies(), MavenDependencyTask.class); if ( ! mdts.isEmpty()) { boolean isClean = mdts.get(0).isCleanOutputDirectory(); boolean skipped = mdts.get(0).isSkipFlag(); if (isClean && ! skipped) { SyncEclipseClasspathTask sync = new SyncEclipseClasspathTask(projectDir); try { sync.run(); } catch(Exception ex) { // allow failure eg file permissions as this is a nicety not a vital build step Log.w(LOGTAG, ex); } } } } private void setJarManifest(JarTask jar, File projectDir, String title) { jar.setManifestProperty(JarTask.MANIFEST_TITLE, title); if (mainClass!=null) { // TODO itd be nice to test after whether the mainClass is in the jar jar.setManifestProperty(JarTask.MANIFEST_MAIN_CLASS, mainClass); } // Version String gitiv = "", by = ""; try { // go up until we're in git or fail File repo = projectDir; while(repo!=null) { if (new File(repo, ".git").exists()) break; repo = repo.getParentFile(); } if (repo!=null) { Map<String, Object> gitInfo = GitTask.getLastCommitInfo(repo); Object branch = gitInfo.get("branch"); gitiv = " git: "+gitInfo.get("hash") +" "+gitInfo.get("subject") // non-master branch (master is not worth stating) + (branch!=null && ! "master".equals(branch)? " "+branch : "") ; } // Git details as their own property e.g. "branch"? No this upsets IntelliJ // So we pack them into version. by = " by: "+WebUtils2.hostname(); } catch(Throwable ex) { Log.w(LOGTAG, this+" "+ex); } // include version, time, and a unique nonce jar.setManifestProperty(JarTask.MANIFEST_IMPLEMENTATION_VERSION, "version: "+StrUtils.joinWithSkip(" ", version, new Time().ddMMyyyy(), "nonce"+Utils.getRandomString(4)) +gitiv+by); // vendor jar.setManifestProperty("Implementation-Vendor", "Winterwell"); } private void doSCP() { if ( ! scpToWW) return; { String remoteJar = "/home/winterwell/public-software/"+getJar().getName(); SCPTask scp = new SCPTask(getJar(), "[email protected]", remoteJar); // this is online at: https://www.winterwell.com/software/downloads scp.setMkdirTask(false); scp.runInThread(); report.put("scp to remote", "winterwell.com:"+remoteJar); } if (makeFatJar && getFatJar()!=null) { String remoteJar = "/home/winterwell/public-software/"+getFatJar().getName(); SCPTask scp = new SCPTask(getFatJar(), "[email protected]", remoteJar); // this is online at: https://www.winterwell.com/software/downloads scp.setMkdirTask(false); scp.runInThread(); report.put("scp to remote", "winterwell.com:"+remoteJar); } // also scp maven file? // Hm -- transitive dependencies?? // Maybe the best solution is for WWDepProject to try and checkout from git?? // { // String remoteJar = "/home/winterwell/public-software/pom.bob."+getProjectName()+".xml"; // SCPTask scp = new SCPTask(pom, "[email protected]", remoteJar); // // this is online at: https://www.winterwell.com/software/downloads // scp.setMkdirTask(false); // scp.runInThread(); // report.put("scp pom to remote", "winterwell.com:"+remoteJar); // } } public File getFatJar() { return fatJar; } protected File getBinDir() { return new File(projectDir, "bin"); } /** * * @return the Java source directory */ protected File getJavaSrcDir() { // flat /src or maven-style src/java? File s = new File(projectDir, "src/java"); if (s.isDirectory()) { return s; } s = new File(projectDir, "src"); return s; } protected void doTask2_compile(File srcDir, File binDir) { // FIXME Compile seeing errors in Windows re XStream dependency! // FIXME Compile seeing errors on Linux when run from JUnit but not when bob is run from the command line ?! Nov 2018 if (compile) { try { assert projectDir != null : this; CompileTask compile = new CompileTask(srcDir, binDir); // classpath EclipseClasspath ec = new EclipseClasspath(projectDir); ec.setIncludeProjectJars(true); Set<File> libs = ec.getCollectedLibs(); compile.setClasspath(libs); // compile.setSrcJavaVersion("1.9"); compile.setOutputJavaVersion("11"); // Java 11 jars compile.setDebug(true); compile.run(); compile.close(); } catch(Exception ex) { Log.e(ex); // :'( Dec 2018 Why?? } } // also copy any resources across?? CopyTask nonJava = new CopyTask(srcDir, binDir); nonJava.setResolveSymLinks(true); nonJava.setNegativeFilter(".*\\.java"); nonJava.setIncludeHiddenFiles(false); // nonJava.setVerbosity(Level.ALL); nonJava.run(); } /** * TODO this finds no tests?? maybe cos we have to compile the tests dir too. Dunno -- parking for now. * @return */ public int doTest() { // if (true) return 0; // FIXME File outputFile = new File(projectDir, "test-output/unit-tests-report.html"); JUnitTask junit = new JUnitTask( null, getTestBinDir(), outputFile); junit.run(); int good = junit.getSuccessCount(); int bad = junit.getFailureCount(); return bad; } protected File getTestBinDir() { // NB not all projects are set to use this (yet) return new File(projectDir, "bin.test"); } public BuildWinterwellProject setMakeFatJar(boolean b) { makeFatJar = b; return this; } @Override public String toString() { return getClass().getSimpleName()+"[projectName=" + projectName + "]"; } }
jar-versions
winterwell.bob/src/com/winterwell/bob/wwjobs/BuildWinterwellProject.java
jar-versions
<ide><path>interwell.bob/src/com/winterwell/bob/wwjobs/BuildWinterwellProject.java <ide> jar.setManifestProperty(JarTask.MANIFEST_MAIN_CLASS, mainClass); <ide> } <ide> // Version <del> String gitiv = "", by = ""; <add> String gitiv = null, by = null; <ide> try { <ide> // go up until we're in git or fail <ide> File repo = projectDir; <ide> if (repo!=null) { <ide> Map<String, Object> gitInfo = GitTask.getLastCommitInfo(repo); <ide> Object branch = gitInfo.get("branch"); <del> gitiv = " git: "+gitInfo.get("hash") <add> gitiv = "git: "+gitInfo.get("hash") <ide> +" "+gitInfo.get("subject") <ide> // non-master branch (master is not worth stating) <ide> + (branch!=null && ! "master".equals(branch)? " "+branch : "") <ide> } <ide> // Git details as their own property e.g. "branch"? No this upsets IntelliJ <ide> // So we pack them into version. <del> by = " by: "+WebUtils2.hostname(); <add> by = "by: "+WebUtils2.hostname(); <ide> } catch(Throwable ex) { <ide> Log.w(LOGTAG, this+" "+ex); <ide> } <ide> // include version, time, and a unique nonce <ide> jar.setManifestProperty(JarTask.MANIFEST_IMPLEMENTATION_VERSION, <del> "version: "+StrUtils.joinWithSkip(" ", version, new Time().ddMMyyyy(), "nonce"+Utils.getRandomString(4)) <del> +gitiv+by); <add> StrUtils.joinWithSkip(" ", <add> version, new Time().ddMMyyyy(), "nonce_"+Utils.getRandomString(4), gitiv, by <add> )); <ide> // vendor <ide> jar.setManifestProperty("Implementation-Vendor", "Winterwell"); <ide> }
Java
apache-2.0
5c962325f5d9e0b21b1b3e5b065d5c06f824ce05
0
babble/babble,babble/babble,babble/babble,babble/babble,babble/babble,babble/babble
// PyJSArrayWrapper.java /** * Copyright (C) 2008 10gen Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ed.lang.python; import java.util.*; import org.python.core.*; import org.python.expose.*; import ed.js.*; import ed.js.engine.*; import static ed.lang.python.Python.*; @ExposedType(name = "jsarraywrapper") public class PyJSArrayWrapper extends PyList { public static final PyType TYPE = Python.exposeClass(PyJSArrayWrapper.class); public PyJSArrayWrapper( JSArray jsA ){ super( TYPE ); _js = jsA; if ( _js == null ) throw new NullPointerException( "don't think you should create a PyJSObjectWrapper for null" ); } public PyObject pyget(int index){ return toPython(_js.getInt(index)); } protected PyObject getslice(int start, int stop, int step){ throw new RuntimeException("not implemented yet"); } protected PyObject repeat(int count){ throw new RuntimeException("not implemented yet"); } protected void set(int index, PyObject value){ _js.setInt(index, toJS(value)); } protected void setslice(int start, int stop, int step, PyObject value){ throw new RuntimeException("not implemented yet"); } protected void del(int i){ _js.remove( i ); } protected void delRange(int start, int stop, int step){ throw new RuntimeException("not implemented yet"); } public int __len__(){ return _js.size(); } @ExposedMethod public PyObject jsarraywrapper___iter__(){ return new PySequenceIter( this ); } @ExposedMethod(names={"__str__", "__repr__"}) public PyObject jsarraywrapper___repr__(){ return new PyString(toString()); } public String toString(){ StringBuilder foo = new StringBuilder(); int n = __len__(); int count = 0; foo.append("["); for(int i = 0; i < n-1; ++i){ PyObject p = toPython(_js.getInt(i)); PyObject repr = p.__repr__(); foo.append(repr.toString()); foo.append(", "); } PyObject p = toPython(_js.getInt(n-1)); PyObject repr = p.__repr__(); foo.append(repr.toString()); foo.append("]"); return foo.toString(); } @ExposedMethod() public PyObject jsarraywrapper_append(PyObject value){ _js.add(toJS(value)); return Py.None; } public int count(PyObject o){ return jsarraywrapper_count(o); } @ExposedMethod() final public int jsarraywrapper_count(PyObject value){ Object jval = toJS(value); int n = __len__(); int count = 0; for(int i = 0; i < n; ++i){ if(_js.getInt(i).equals(jval)) count++; } return count; } @ExposedMethod() public PyObject jsarraywrapper_insert(PyObject index, PyObject value){ if( ! index.isIndex() ){ throw Py.TypeError("an integer is required"); } int i = fixindex(index.asIndex(Py.IndexError)); _js.add(i, toJS(value)); return Py.None; } @ExposedMethod(defaults="null") public PyObject jsarraywrapper_pop(PyObject index){ if( index == null ){ return toPython( _js.remove( _js.size() - 1 ) ); } if( ! index.isIndex() ){ throw Py.TypeError("an integer is required"); } int i = fixindex(index.asIndex(Py.IndexError)); return toPython( _js.remove( i ) ); } @ExposedMethod public PyObject jsarraywrapper_extend(PyObject extra){ throw new RuntimeException("not implemented yet"); } @ExposedMethod public PyObject jsarraywrapper_index(PyObject x){ throw new RuntimeException("not implemented yet"); } @ExposedMethod public PyObject jsarraywrapper_remove(PyObject x){ throw new RuntimeException("not implemented yet"); } @ExposedMethod public PyObject jsarraywrapper_reverse(){ throw new RuntimeException("not implemented yet"); } @ExposedMethod public PyObject jsarraywrapper_sort(PyObject[] args, String[] keywords){ // key seems to take precedence over cmp throw new RuntimeException("not implemented yet"); } // eq, ne, lt, le, gt, ge, cmp // finditem, setitem, getslice, delslice -- handled for us? final JSArray _js; }
src/main/ed/lang/python/PyJSArrayWrapper.java
// PyJSArrayWrapper.java /** * Copyright (C) 2008 10gen Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ed.lang.python; import java.util.*; import org.python.core.*; import org.python.expose.*; import ed.js.*; import ed.js.engine.*; import static ed.lang.python.Python.*; @ExposedType(name = "jsarraywrapper") public class PyJSArrayWrapper extends PyList { public static final PyType TYPE = Python.exposeClass(PyJSArrayWrapper.class); public PyJSArrayWrapper( JSArray jsA ){ super( TYPE ); _js = jsA; if ( _js == null ) throw new NullPointerException( "don't think you should create a PyJSObjectWrapper for null" ); } public PyObject pyget(int index){ return toPython(_js.getInt(index)); } protected PyObject getslice(int start, int stop, int step){ throw new RuntimeException("not implemented yet"); } protected PyObject repeat(int count){ throw new RuntimeException("not implemented yet"); } protected void set(int index, PyObject value){ _js.setInt(index, toJS(value)); } protected void setslice(int start, int stop, int step, PyObject value){ throw new RuntimeException("not implemented yet"); } protected void del(int i){ _js.remove( i ); } protected void delRange(int start, int stop, int step){ throw new RuntimeException("not implemented yet"); } public int __len__(){ return _js.size(); } @ExposedMethod public PyObject jsarraywrapper___iter__(){ return new PySequenceIter( this ); } @ExposedMethod(names={"__str__", "__repr__"}) public PyObject jsarraywrapper___repr__(){ return new PyString(toString()); } public String toString(){ StringBuilder foo = new StringBuilder(); int n = __len__(); int count = 0; foo.append("["); for(int i = 0; i < n-1; ++i){ PyObject p = toPython(_js.getInt(i)); PyObject repr = p.__repr__(); foo.append(repr.toString()); foo.append(", "); } PyObject p = toPython(_js.getInt(n-1)); PyObject repr = p.__repr__(); foo.append(repr.toString()); foo.append("]"); return foo.toString(); } @ExposedMethod() public PyObject jsarraywrapper_append(PyObject value){ _js.add(toJS(value)); return Py.None; } public int count(PyObject o){ return jsarraywrapper_count(o); } @ExposedMethod() final public int jsarraywrapper_count(PyObject value){ Object jval = toJS(value); int n = __len__(); int count = 0; for(int i = 0; i < n; ++i){ if(_js.getInt(i).equals(jval)) count++; } return count; } @ExposedMethod() public PyObject jsarraywrapper_insert(PyObject index, PyObject value){ if( ! index.isIndex() ){ throw Py.TypeError("an integer is required"); } int i = fixindex(index.asIndex(Py.IndexError)); _js.add(i, toJS(value)); return Py.None; } @ExposedMethod(defaults="null") public PyObject jsarraywrapper_pop(PyObject index){ if( index == null ){ return toPython( _js.remove( _js.size() - 1 ) ); } if( ! index.isIndex() ){ throw Py.TypeError("an integer is required"); } int i = fixindex(index.asIndex(Py.IndexError)); return toPython( _js.remove( i ) ); } // eq, ne, lt, le, gt, ge, cmp // finditem, setitem, getslice, delslice -- handled for us? final JSArray _js; }
Mark as not implemented.
src/main/ed/lang/python/PyJSArrayWrapper.java
Mark as not implemented.
<ide><path>rc/main/ed/lang/python/PyJSArrayWrapper.java <ide> return toPython( _js.remove( i ) ); <ide> } <ide> <add> @ExposedMethod <add> public PyObject jsarraywrapper_extend(PyObject extra){ <add> throw new RuntimeException("not implemented yet"); <add> } <add> <add> @ExposedMethod <add> public PyObject jsarraywrapper_index(PyObject x){ <add> throw new RuntimeException("not implemented yet"); <add> } <add> <add> @ExposedMethod <add> public PyObject jsarraywrapper_remove(PyObject x){ <add> throw new RuntimeException("not implemented yet"); <add> } <add> <add> @ExposedMethod <add> public PyObject jsarraywrapper_reverse(){ <add> throw new RuntimeException("not implemented yet"); <add> } <add> <add> @ExposedMethod <add> public PyObject jsarraywrapper_sort(PyObject[] args, String[] keywords){ <add> // key seems to take precedence over cmp <add> throw new RuntimeException("not implemented yet"); <add> } <add> <ide> // eq, ne, lt, le, gt, ge, cmp <ide> // finditem, setitem, getslice, delslice -- handled for us? <ide> final JSArray _js;
Java
mit
78cb45df890ad0391d2426e882c50c71817c36c1
0
aaomidi/JustSkyblock
package com.aaomidi.justskyblock.storage.mysql; import com.aaomidi.justskyblock.JustSkyblock; import com.jolbox.bonecp.BoneCP; import com.jolbox.bonecp.BoneCPConfig; import org.apache.commons.lang.StringUtils; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; /** * @author aaomidi */ public class MySQLConnector { private final JustSkyblock instance; private final String host; private final int port; private final String username; private final String password; private final String database; private final int minPoolSize; private final int maxPoolSize; private BoneCP boneCP; private Connection connection; public MySQLConnector(JustSkyblock instance, String host, int port, String username, String password, String database, int minPoolSize, int maxPoolSize) { this.instance = instance; this.host = host; this.port = port; this.username = username; this.password = password; this.database = database; this.minPoolSize = minPoolSize; this.maxPoolSize = maxPoolSize; this.createBoneCP(); } private void createBoneCP() { try { BoneCPConfig config = new BoneCPConfig(); config.setJdbcUrl(String.format("jdbc:mysql://%s:%d/%s", this.host, this.port, this.database)); config.setUsername(this.username); config.setPassword(this.password); config.setPartitionCount(2); config.setMinConnectionsPerPartition(this.minPoolSize); config.setMaxConnectionsPerPartition(this.maxPoolSize); boneCP = new BoneCP(config); this.createConnection(); } catch (Exception ex) { throw new Error("Unrecoverable error when creating the BoneCP object.", ex); } } private void createConnection() { try { connection = boneCP.getConnection(); } catch (Exception ex) { throw new Error("Unrecoverable error when creating the connection.", ex); } } private boolean isConnected() { return (this.connection != null); } private Connection getConnection() { if (isConnected()) { return this.connection; } this.createConnection(); return this.connection; } public ResultSet executeQuery(String query, Object... parameters) { int parameterCount = (parameters == null) ? 0 : parameters.length; if (StringUtils.countMatches(query, "?") != parameterCount) { this.instance.getLogger().warning("Error whilst preparing SQL query: Incorrect number of parameters!"); return null; } Connection connection = this.getConnection(); try { PreparedStatement statement = connection.prepareStatement(query); Object parameter; for (int i = 0, j = 1; i < parameterCount; i++, j++) { parameter = parameters[i]; if (parameter instanceof String) { statement.setString(j, (String) parameter); } else if (parameter instanceof Integer) { statement.setInt(j, (Integer) parameter); } else if (parameter instanceof Double) { statement.setDouble(j, (Double) parameter); } else if (parameter instanceof Float) { statement.setFloat(j, (Float) parameter); } else if (parameter instanceof Boolean) { statement.setBoolean(j, (Boolean) parameter); } else { statement.setObject(j, parameter); } } return statement.executeQuery(); } catch (SQLException ex) { throw new RuntimeException("Problem when executing query.", ex); } } public int executeUpdate(String query, Object... parameters) { int parameterCount = (parameters == null) ? 0 : parameters.length; if (StringUtils.countMatches(query, "?") != parameterCount) { this.instance.getLogger().warning("Error whilst preparing SQL query: Incorrect number of parameters!"); return -1; } Connection connection = this.getConnection(); try { PreparedStatement statement = connection.prepareStatement(query); Object parameter; for (int i = 0, j = 1; i < parameterCount; i++, j++) { parameter = parameters[i]; if (parameter instanceof String) { statement.setString(j, (String) parameter); } else if (parameter instanceof Integer) { statement.setInt(j, (Integer) parameter); } else if (parameter instanceof Double) { statement.setDouble(j, (Double) parameter); } else if (parameter instanceof Float) { statement.setFloat(j, (Float) parameter); } else if (parameter instanceof Boolean) { statement.setBoolean(j, (Boolean) parameter); } else { statement.setObject(j, parameter); } } return statement.executeUpdate(); } catch (SQLException ex) { throw new RuntimeException("Problem when executing update!", ex); } } public void disconnect() { try { connection.close(); } catch (SQLException ex) { throw new RuntimeException(ex); } } }
src/main/java/com/aaomidi/justskyblock/storage/mysql/MySQLConnector.java
package com.aaomidi.justskyblock.storage.mysql; /** * @author aaomidi */ public class MySQLConnector { }
MySQL Connector+API
src/main/java/com/aaomidi/justskyblock/storage/mysql/MySQLConnector.java
MySQL Connector+API
<ide><path>rc/main/java/com/aaomidi/justskyblock/storage/mysql/MySQLConnector.java <ide> package com.aaomidi.justskyblock.storage.mysql; <add> <add>import com.aaomidi.justskyblock.JustSkyblock; <add>import com.jolbox.bonecp.BoneCP; <add>import com.jolbox.bonecp.BoneCPConfig; <add>import org.apache.commons.lang.StringUtils; <add> <add>import java.sql.Connection; <add>import java.sql.PreparedStatement; <add>import java.sql.ResultSet; <add>import java.sql.SQLException; <ide> <ide> /** <ide> * @author aaomidi <ide> */ <ide> public class MySQLConnector { <add> private final JustSkyblock instance; <add> private final String host; <add> private final int port; <add> private final String username; <add> private final String password; <add> private final String database; <add> private final int minPoolSize; <add> private final int maxPoolSize; <add> private BoneCP boneCP; <add> private Connection connection; <add> <add> public MySQLConnector(JustSkyblock instance, String host, int port, String username, String password, String database, int minPoolSize, int maxPoolSize) { <add> this.instance = instance; <add> this.host = host; <add> this.port = port; <add> this.username = username; <add> this.password = password; <add> this.database = database; <add> this.minPoolSize = minPoolSize; <add> this.maxPoolSize = maxPoolSize; <add> this.createBoneCP(); <add> } <add> <add> private void createBoneCP() { <add> try { <add> BoneCPConfig config = new BoneCPConfig(); <add> config.setJdbcUrl(String.format("jdbc:mysql://%s:%d/%s", this.host, this.port, this.database)); <add> config.setUsername(this.username); <add> config.setPassword(this.password); <add> config.setPartitionCount(2); <add> config.setMinConnectionsPerPartition(this.minPoolSize); <add> config.setMaxConnectionsPerPartition(this.maxPoolSize); <add> boneCP = new BoneCP(config); <add> this.createConnection(); <add> } catch (Exception ex) { <add> throw new Error("Unrecoverable error when creating the BoneCP object.", ex); <add> } <add> } <add> <add> private void createConnection() { <add> try { <add> connection = boneCP.getConnection(); <add> } catch (Exception ex) { <add> throw new Error("Unrecoverable error when creating the connection.", ex); <add> } <add> } <add> <add> private boolean isConnected() { <add> return (this.connection != null); <add> <add> } <add> <add> private Connection getConnection() { <add> if (isConnected()) { <add> return this.connection; <add> } <add> this.createConnection(); <add> return this.connection; <add> } <add> <add> public ResultSet executeQuery(String query, Object... parameters) { <add> int parameterCount = (parameters == null) ? 0 : parameters.length; <add> if (StringUtils.countMatches(query, "?") != parameterCount) { <add> this.instance.getLogger().warning("Error whilst preparing SQL query: Incorrect number of parameters!"); <add> return null; <add> } <add> Connection connection = this.getConnection(); <add> try { <add> PreparedStatement statement = connection.prepareStatement(query); <add> Object parameter; <add> for (int i = 0, j = 1; i < parameterCount; i++, j++) { <add> parameter = parameters[i]; <add> if (parameter instanceof String) { <add> statement.setString(j, (String) parameter); <add> } else if (parameter instanceof Integer) { <add> statement.setInt(j, (Integer) parameter); <add> } else if (parameter instanceof Double) { <add> statement.setDouble(j, (Double) parameter); <add> } else if (parameter instanceof Float) { <add> statement.setFloat(j, (Float) parameter); <add> } else if (parameter instanceof Boolean) { <add> statement.setBoolean(j, (Boolean) parameter); <add> } else { <add> statement.setObject(j, parameter); <add> } <add> } <add> return statement.executeQuery(); <add> } catch (SQLException ex) { <add> throw new RuntimeException("Problem when executing query.", ex); <add> } <add> } <add> <add> public int executeUpdate(String query, Object... parameters) { <add> int parameterCount = (parameters == null) ? 0 : parameters.length; <add> if (StringUtils.countMatches(query, "?") != parameterCount) { <add> this.instance.getLogger().warning("Error whilst preparing SQL query: Incorrect number of parameters!"); <add> return -1; <add> } <add> Connection connection = this.getConnection(); <add> try { <add> PreparedStatement statement = connection.prepareStatement(query); <add> Object parameter; <add> for (int i = 0, j = 1; i < parameterCount; i++, j++) { <add> parameter = parameters[i]; <add> if (parameter instanceof String) { <add> statement.setString(j, (String) parameter); <add> } else if (parameter instanceof Integer) { <add> statement.setInt(j, (Integer) parameter); <add> } else if (parameter instanceof Double) { <add> statement.setDouble(j, (Double) parameter); <add> } else if (parameter instanceof Float) { <add> statement.setFloat(j, (Float) parameter); <add> } else if (parameter instanceof Boolean) { <add> statement.setBoolean(j, (Boolean) parameter); <add> } else { <add> statement.setObject(j, parameter); <add> } <add> } <add> return statement.executeUpdate(); <add> } catch (SQLException ex) { <add> throw new RuntimeException("Problem when executing update!", ex); <add> } <add> } <add> <add> public void disconnect() { <add> try { <add> connection.close(); <add> } catch (SQLException ex) { <add> throw new RuntimeException(ex); <add> } <add> } <add> <ide> }
Java
mit
9821334acd6e2034b91215f9631d97c09a98c88f
0
Semx11/Autotip
package me.semx11.autotip.util; import static me.semx11.autotip.util.ReflectionUtil.getClazz; import static me.semx11.autotip.util.ReflectionUtil.getConstructor; import static me.semx11.autotip.util.ReflectionUtil.getEnum; import static me.semx11.autotip.util.ReflectionUtil.getField; import static me.semx11.autotip.util.ReflectionUtil.getMethod; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.net.SocketAddress; import me.semx11.autotip.Autotip; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraftforge.client.event.ClientChatReceivedEvent; import net.minecraftforge.common.ForgeVersion; import net.minecraftforge.fml.common.network.FMLNetworkEvent.ClientConnectedToServerEvent; public class UniversalUtil { public static String getMinecraftVersion() { try { Field f = getField(ForgeVersion.class, "mcVersion"); if (f != null) { return (String) f.get(null); } else { return "1.8"; } } catch (IllegalAccessException e) { e.printStackTrace(); return "1.8"; } } public static SocketAddress getRemoteAddress(ClientConnectedToServerEvent event) { SocketAddress address = null; try { Object networkManager = null; switch (Autotip.MC_VERSION) { case V1_8: case V1_8_8: case V1_8_9: networkManager = getField(ClientConnectedToServerEvent.class, "manager").get(event); break; case V1_9: case V1_9_4: case V1_10: case V1_10_2: case V1_11: case V1_11_2: case V1_12: networkManager = getMethod(ClientConnectedToServerEvent.class, new String[]{"getManager"}).invoke(event); break; } // Original method name: getRemoteAddress address = (SocketAddress) getMethod(networkManager.getClass(), new String[]{"func_74430_c", "getRemoteAddress"}).invoke(networkManager); } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } return address; } public static String getUnformattedText(ClientChatReceivedEvent event) { String msg = ""; try { Object component = null; switch (Autotip.MC_VERSION) { case V1_8: case V1_8_8: case V1_8_9: component = getField(ClientChatReceivedEvent.class, "message").get(event); break; case V1_9: case V1_9_4: case V1_10: case V1_10_2: case V1_11: case V1_11_2: case V1_12: component = getMethod(ClientChatReceivedEvent.class, new String[]{"getMessage"}) .invoke(event); break; } // Original method name: getUnformattedText msg = (String) getMethod(component.getClass(), new String[]{"getUnformattedText", "func_150260_c"}) .invoke(component); } catch (InvocationTargetException | IllegalAccessException e) { e.printStackTrace(); } return msg; } static void chatMessage(String text) { chatMessage(createComponent(text)); } static void chatMessage(String text, String url, String hoverText) { chatMessage(createComponent(text, url, hoverText)); } private static void chatMessage(Object component) { EntityPlayerSP thePlayer = Minecraft.getMinecraft().thePlayer; try { switch (Autotip.MC_VERSION) { case V1_8: case V1_8_8: case V1_8_9: // Original method name: addChatMessage getMethod( EntityPlayerSP.class, new String[]{"func_145747_a", "addChatMessage"}, getClazz("net.minecraft.util.IChatComponent") ).invoke(thePlayer, component); break; case V1_9: case V1_9_4: case V1_10: case V1_10_2: // Original method name: addChatComponentMessage getMethod( EntityPlayerSP.class, new String[]{"func_146105_b", "addChatComponentMessage"}, getClazz("net.minecraft.util.text.ITextComponent") ).invoke(thePlayer, component); break; case V1_11: case V1_11_2: case V1_12: // Original method name: addChatMessage / sendMessage getMethod( EntityPlayerSP.class, new String[]{"func_145747_a", "sendMessage", "addChatMessage"}, getClazz("net.minecraft.util.text.ITextComponent") ).invoke(thePlayer, component); break; } } catch (InvocationTargetException | IllegalAccessException e) { e.printStackTrace(); } } private static Object createComponent(String text) { try { switch (Autotip.MC_VERSION) { case V1_8: case V1_8_8: case V1_8_9: return getConstructor( getClazz("net.minecraft.util.ChatComponentText"), String.class ).newInstance(text); case V1_9: case V1_9_4: case V1_10: case V1_10_2: case V1_11: case V1_11_2: case V1_12: return getConstructor( getClazz("net.minecraft.util.text.TextComponentString"), String.class ).newInstance(text); default: return null; } } catch (InvocationTargetException | IllegalAccessException | InstantiationException e) { e.printStackTrace(); return null; } } // Don't try this at home. private static Object createComponent(String text, String url, String hoverText) { try { switch (Autotip.MC_VERSION) { case V1_8: case V1_8_8: case V1_8_9: Object chatClickEvent = null; Object chatHoverEvent = null; if (url != null && !url.equals("")) { chatClickEvent = getConstructor( getClazz("net.minecraft.event.ClickEvent"), getClazz("net.minecraft.event.ClickEvent$Action"), String.class ).newInstance( getEnum(getClazz("net.minecraft.event.ClickEvent$Action"), "OPEN_URL"), url ); } if (hoverText != null && !hoverText.equals("")) { chatHoverEvent = getConstructor( getClazz("net.minecraft.event.HoverEvent"), getClazz("net.minecraft.event.HoverEvent$Action"), getClazz("net.minecraft.util.IChatComponent") ).newInstance( getEnum(getClazz("net.minecraft.event.HoverEvent$Action"), "SHOW_TEXT"), createComponent(hoverText) ); } Object chatStyle = getConstructor( getClazz("net.minecraft.util.ChatStyle") ).newInstance(); // Original method name: setChatClickEvent if (url != null && !url.equals("")) { getMethod( getClazz("net.minecraft.util.ChatStyle"), new String[]{"func_150241_a", "setChatClickEvent"}, getClazz("net.minecraft.event.ClickEvent") ).invoke(chatStyle, chatClickEvent); } // Original method name: setChatHoverEvent if (hoverText != null && !hoverText.equals("")) { getMethod( getClazz("net.minecraft.util.ChatStyle"), new String[]{"func_150209_a", "setChatHoverEvent"}, getClazz("net.minecraft.event.HoverEvent") ).invoke(chatStyle, chatHoverEvent); } Object chatComponent = createComponent(text); // Original method name: setChatStyle return getMethod( getClazz("net.minecraft.util.ChatComponentText"), new String[]{"func_150255_a", "setChatStyle"}, getClazz("net.minecraft.util.ChatStyle") ).invoke(chatComponent, chatStyle); case V1_9: case V1_9_4: case V1_10: case V1_10_2: case V1_11: case V1_11_2: case V1_12: Object clickEvent = null; Object hoverEvent = null; if (url != null && !url.equals("")) { clickEvent = getConstructor( getClazz("net.minecraft.util.text.event.ClickEvent"), getClazz("net.minecraft.util.text.event.ClickEvent$Action"), String.class ).newInstance( getEnum(getClazz("net.minecraft.util.text.event.ClickEvent$Action"), "OPEN_URL"), url ); } if (hoverText != null && !hoverText.equals("")) { hoverEvent = getConstructor( getClazz("net.minecraft.util.text.event.HoverEvent"), getClazz("net.minecraft.util.text.event.HoverEvent$Action"), getClazz("net.minecraft.util.text.ITextComponent") ).newInstance( getEnum(getClazz("net.minecraft.util.text.event.HoverEvent$Action"), "SHOW_TEXT"), createComponent(hoverText) ); } Object style = getConstructor( getClazz("net.minecraft.util.text.Style") ).newInstance(); // Original method name: setChatClickEvent if (url != null && !url.equals("")) { getMethod( getClazz("net.minecraft.util.text.Style"), new String[]{"func_150241_a", "setChatClickEvent"}, getClazz("net.minecraft.util.text.event.ClickEvent") ).invoke(style, clickEvent); } // Original method name: setChatHoverEvent if (hoverText != null && !hoverText.equals("")) { getMethod( getClazz("net.minecraft.util.text.Style"), new String[]{"func_150209_a", "setChatHoverEvent"}, getClazz("net.minecraft.util.text.event.HoverEvent") ).invoke(style, hoverEvent); } Object textComponent = createComponent(text); // Original method name: setChatStyle return getMethod( getClazz("net.minecraft.util.text.TextComponentString"), new String[]{"func_150255_a", "setChatStyle"}, getClazz("net.minecraft.util.text.Style") ).invoke(textComponent, style); default: return null; } } catch (IllegalAccessException | InvocationTargetException | InstantiationException e) { e.printStackTrace(); return null; } } }
src/main/java/me/semx11/autotip/util/UniversalUtil.java
package me.semx11.autotip.util; import static me.semx11.autotip.util.ReflectionUtil.getClazz; import static me.semx11.autotip.util.ReflectionUtil.getConstructor; import static me.semx11.autotip.util.ReflectionUtil.getEnum; import static me.semx11.autotip.util.ReflectionUtil.getField; import static me.semx11.autotip.util.ReflectionUtil.getMethod; import static net.minecraftforge.fml.relauncher.ReflectionHelper.findMethod; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.net.SocketAddress; import me.semx11.autotip.Autotip; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraftforge.client.event.ClientChatReceivedEvent; import net.minecraftforge.common.ForgeVersion; import net.minecraftforge.fml.common.network.FMLNetworkEvent.ClientConnectedToServerEvent; import net.minecraftforge.fml.relauncher.ReflectionHelper; public class UniversalUtil { public static String getMinecraftVersion() { try { Field f = getField(ForgeVersion.class, "mcVersion"); if (f != null) { return (String) f.get(null); } else { return "1.8"; } } catch (IllegalAccessException e) { e.printStackTrace(); return "1.8"; } } public static SocketAddress getRemoteAddress(ClientConnectedToServerEvent event) { SocketAddress address = null; try { Object networkManager = null; switch (Autotip.MC_VERSION) { case V1_8: case V1_8_8: case V1_8_9: networkManager = getField(ClientConnectedToServerEvent.class, "manager").get(event); break; case V1_9: case V1_9_4: case V1_10: case V1_10_2: case V1_11: case V1_11_2: networkManager = getMethod(ClientConnectedToServerEvent.class, new String[]{"getManager"}).invoke(event); break; } // Original method name: getRemoteAddress address = (SocketAddress) getMethod(networkManager.getClass(), new String[]{"func_74430_c", "getRemoteAddress"}).invoke(networkManager); } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } return address; } public static String getUnformattedText(ClientChatReceivedEvent event) { String msg = ""; try { Object component = null; switch (Autotip.MC_VERSION) { case V1_8: case V1_8_8: case V1_8_9: component = getField(ClientChatReceivedEvent.class, "message").get(event); break; case V1_9: case V1_9_4: case V1_10: case V1_10_2: case V1_11: case V1_11_2: component = getMethod(ClientChatReceivedEvent.class, new String[]{"getMessage"}) .invoke(event); break; } // Original method name: getUnformattedText msg = (String) getMethod(component.getClass(), new String[]{"getUnformattedText", "func_150260_c"}) .invoke(component); } catch (InvocationTargetException | IllegalAccessException e) { e.printStackTrace(); } return msg; } static void chatMessage(String text) { chatMessage(createComponent(text)); } static void chatMessage(String text, String url, String hoverText) { chatMessage(createComponent(text, url, hoverText)); } private static void chatMessage(Object component) { EntityPlayerSP thePlayer = Minecraft.getMinecraft().thePlayer; try { switch (Autotip.MC_VERSION) { case V1_8: case V1_8_8: case V1_8_9: // Original method name: addChatMessage getMethod( EntityPlayerSP.class, new String[]{"func_145747_a", "addChatMessage"}, getClazz("net.minecraft.util.IChatComponent") ).invoke(thePlayer, component); break; case V1_9: case V1_9_4: case V1_10: case V1_10_2: // Original method name: addChatComponentMessage getMethod( EntityPlayerSP.class, new String[]{"func_146105_b", "addChatComponentMessage"}, getClazz("net.minecraft.util.text.ITextComponent") ).invoke(thePlayer, component); break; case V1_11: case V1_11_2: // Original method name: addChatMessage / sendMessage getMethod( EntityPlayerSP.class, new String[]{"func_145747_a", "addChatMessage", "sendMessage"}, getClazz("net.minecraft.util.text.ITextComponent") ).invoke(thePlayer, component); break; } } catch (InvocationTargetException | IllegalAccessException e) { e.printStackTrace(); } } private static Object createComponent(String text) { try { switch (Autotip.MC_VERSION) { case V1_8: case V1_8_8: case V1_8_9: return getConstructor( getClazz("net.minecraft.util.ChatComponentText"), String.class ).newInstance(text); case V1_9: case V1_9_4: case V1_10: case V1_10_2: case V1_11: case V1_11_2: return getConstructor( getClazz("net.minecraft.util.text.TextComponentString"), String.class ).newInstance(text); default: return null; } } catch (InvocationTargetException | IllegalAccessException | InstantiationException e) { e.printStackTrace(); return null; } } // Don't try this at home. private static Object createComponent(String text, String url, String hoverText) { try { switch (Autotip.MC_VERSION) { case V1_8: case V1_8_8: case V1_8_9: Object chatClickEvent = null; Object chatHoverEvent = null; if (url != null && !url.equals("")) { chatClickEvent = getConstructor( getClazz("net.minecraft.event.ClickEvent"), getClazz("net.minecraft.event.ClickEvent$Action"), String.class ).newInstance( getEnum(getClazz("net.minecraft.event.ClickEvent$Action"), "OPEN_URL"), url ); } if (hoverText != null && !hoverText.equals("")) { chatHoverEvent = getConstructor( getClazz("net.minecraft.event.HoverEvent"), getClazz("net.minecraft.event.HoverEvent$Action"), getClazz("net.minecraft.util.IChatComponent") ).newInstance( getEnum(getClazz("net.minecraft.event.HoverEvent$Action"), "SHOW_TEXT"), createComponent(hoverText) ); } Object chatStyle = getConstructor( getClazz("net.minecraft.util.ChatStyle") ).newInstance(); // Original method name: setChatClickEvent if (url != null && !url.equals("")) { getMethod( getClazz("net.minecraft.util.ChatStyle"), new String[]{"func_150241_a", "setChatClickEvent"}, getClazz("net.minecraft.event.ClickEvent") ).invoke(chatStyle, chatClickEvent); } // Original method name: setChatHoverEvent if (hoverText != null && !hoverText.equals("")) { getMethod( getClazz("net.minecraft.util.ChatStyle"), new String[]{"func_150209_a", "setChatHoverEvent"}, getClazz("net.minecraft.event.HoverEvent") ).invoke(chatStyle, chatHoverEvent); } Object chatComponent = createComponent(text); // Original method name: setChatStyle return getMethod( getClazz("net.minecraft.util.ChatComponentText"), new String[]{"func_150255_a", "setChatStyle"}, getClazz("net.minecraft.util.ChatStyle") ).invoke(chatComponent, chatStyle); case V1_9: case V1_9_4: case V1_10: case V1_10_2: case V1_11: case V1_11_2: Object clickEvent = null; Object hoverEvent = null; if (url != null && !url.equals("")) { clickEvent = getConstructor( getClazz("net.minecraft.util.text.event.ClickEvent"), getClazz("net.minecraft.util.text.event.ClickEvent$Action"), String.class ).newInstance( getEnum(getClazz("net.minecraft.util.text.event.ClickEvent$Action"), "OPEN_URL"), url ); } if (hoverText != null && !hoverText.equals("")) { hoverEvent = getConstructor( getClazz("net.minecraft.util.text.event.HoverEvent"), getClazz("net.minecraft.util.text.event.HoverEvent$Action"), getClazz("net.minecraft.util.text.ITextComponent") ).newInstance( getEnum(getClazz("net.minecraft.util.text.event.HoverEvent$Action"), "SHOW_TEXT"), createComponent(hoverText) ); } Object style = getConstructor( getClazz("net.minecraft.util.text.Style") ).newInstance(); // Original method name: setChatClickEvent if (url != null && !url.equals("")) { getMethod( getClazz("net.minecraft.util.text.Style"), new String[]{"func_150241_a", "setChatClickEvent"}, getClazz("net.minecraft.util.text.event.ClickEvent") ).invoke(style, clickEvent); } // Original method name: setChatHoverEvent if (hoverText != null && !hoverText.equals("")) { getMethod( getClazz("net.minecraft.util.text.Style"), new String[]{"func_150209_a", "setChatHoverEvent"}, getClazz("net.minecraft.util.text.event.HoverEvent") ).invoke(style, hoverEvent); } Object textComponent = createComponent(text); // Original method name: setChatStyle return getMethod( getClazz("net.minecraft.util.text.TextComponentString"), new String[]{"func_150255_a", "setChatStyle"}, getClazz("net.minecraft.util.text.Style") ).invoke(textComponent, style); default: return null; } } catch (IllegalAccessException | InvocationTargetException | InstantiationException e) { e.printStackTrace(); return null; } } }
1.12 support test
src/main/java/me/semx11/autotip/util/UniversalUtil.java
1.12 support test
<ide><path>rc/main/java/me/semx11/autotip/util/UniversalUtil.java <ide> import static me.semx11.autotip.util.ReflectionUtil.getEnum; <ide> import static me.semx11.autotip.util.ReflectionUtil.getField; <ide> import static me.semx11.autotip.util.ReflectionUtil.getMethod; <del>import static net.minecraftforge.fml.relauncher.ReflectionHelper.findMethod; <ide> <ide> import java.lang.reflect.Field; <ide> import java.lang.reflect.InvocationTargetException; <ide> import net.minecraftforge.client.event.ClientChatReceivedEvent; <ide> import net.minecraftforge.common.ForgeVersion; <ide> import net.minecraftforge.fml.common.network.FMLNetworkEvent.ClientConnectedToServerEvent; <del>import net.minecraftforge.fml.relauncher.ReflectionHelper; <ide> <ide> public class UniversalUtil { <ide> <ide> case V1_10_2: <ide> case V1_11: <ide> case V1_11_2: <add> case V1_12: <ide> networkManager = getMethod(ClientConnectedToServerEvent.class, <ide> new String[]{"getManager"}).invoke(event); <ide> break; <ide> } <ide> // Original method name: getRemoteAddress <del> address = (SocketAddress) getMethod(networkManager.getClass(), new String[]{"func_74430_c", "getRemoteAddress"}).invoke(networkManager); <add> address = (SocketAddress) getMethod(networkManager.getClass(), <add> new String[]{"func_74430_c", "getRemoteAddress"}).invoke(networkManager); <ide> } catch (IllegalAccessException | InvocationTargetException e) { <ide> e.printStackTrace(); <ide> } <ide> case V1_10_2: <ide> case V1_11: <ide> case V1_11_2: <add> case V1_12: <ide> component = getMethod(ClientChatReceivedEvent.class, new String[]{"getMessage"}) <ide> .invoke(event); <ide> break; <ide> } <ide> // Original method name: getUnformattedText <del> msg = (String) getMethod(component.getClass(), new String[]{"getUnformattedText", "func_150260_c"}) <add> msg = (String) getMethod(component.getClass(), <add> new String[]{"getUnformattedText", "func_150260_c"}) <ide> .invoke(component); <ide> } catch (InvocationTargetException | IllegalAccessException e) { <ide> e.printStackTrace(); <ide> break; <ide> case V1_11: <ide> case V1_11_2: <add> case V1_12: <ide> // Original method name: addChatMessage / sendMessage <ide> getMethod( <ide> EntityPlayerSP.class, <del> new String[]{"func_145747_a", "addChatMessage", "sendMessage"}, <add> new String[]{"func_145747_a", "sendMessage", "addChatMessage"}, <ide> getClazz("net.minecraft.util.text.ITextComponent") <ide> ).invoke(thePlayer, component); <ide> break; <ide> case V1_10_2: <ide> case V1_11: <ide> case V1_11_2: <add> case V1_12: <ide> return getConstructor( <ide> getClazz("net.minecraft.util.text.TextComponentString"), <ide> String.class <ide> case V1_10_2: <ide> case V1_11: <ide> case V1_11_2: <add> case V1_12: <ide> Object clickEvent = null; <ide> Object hoverEvent = null; <ide>
JavaScript
bsd-3-clause
460d1e9e853e8f081a041930474083cc9dbdfc23
0
aplazame/aplazame-js,aplazame/aplazame-js,aplazame/aplazame-js
'use strict'; module.exports = function (aplazame) { var _ = aplazame._, $q = require('parole'), Events = require('azazel'), api = require('../core/api'), isMobile = window.matchMedia('( max-width: 767px )'), each = Array.prototype.forEach, log = require('../tools/log'); function getQty (qtySelector) { if( !_.isString(qtySelector) ) { log('warning: data-qty should be an string. pe: form#article .final-price '); return 1; } var qtyElement; try { qtyElement = document.querySelector(qtySelector); } catch(err) { log(err.message + '\ndata-qty should be an string. pe: form#article .final-price '); return 1; } switch( qtyElement.nodeName.toLowerCase() ) { case 'input': return Number( qtyElement.value ); case 'select': return qtyElement.querySelector('option[selected]') && Number( qtyElement.querySelector('option[selected]').value ) || 1; default: return Number( qtyElement.textContent.trim() ); } } var cmsPriceSelector = [ 'form#product_addtocart_form .special-price .price', // magento 'form#product_addtocart_form .regular-price .price', // magento '#product-info .special-price .price', // magento '#product-info .regular-price .price', // magento 'form#buy_block #our_price_display', // prestashop '#main [itemtype="http://schema.org/Product"] [itemtype="http://schema.org/Offer"] .price ins .amount', // woocommerce '#main [itemtype="http://schema.org/Product"] [itemtype="http://schema.org/Offer"] .price .amount', // woocommerce '#main [itemtype="http://schema.org/Product"] .single_variation_wrap .amount', // woocommerce '[itemtype="http://schema.org/Product"] [itemtype="http://schema.org/Offer"] [itemprop="price"]' // Schema.org ], cmsQtySelector = [ 'form#product_addtocart_form input[name="qty"]', // magento 'form#buy_block input[name="qty"]', // prestashop '#quantity_wanted', // prestashop 'form#product-options-form button[data-id=qty]', // custom '#main [itemtype="http://schema.org/Product"] form.cart input[name="quantity"]' // woocommerce ]; function matchSelector (selector) { return document.querySelector(selector); } function amountGetter (widgetElement) { var priceSelector = widgetElement.getAttribute('data-price'), qtySelector = widgetElement.getAttribute('data-qty'), autoDiscovered = false; if( priceSelector ) { // try{ // document.querySelector(priceSelector); // } catch(err) { // priceSelector = null; // } if( qtySelector ) { try{ document.querySelector(qtySelector); } catch(err) { qtySelector = null; log(err.message); } } } else { priceSelector = _.find(cmsPriceSelector, matchSelector); if( priceSelector ) { qtySelector = _.find(cmsQtySelector, matchSelector); autoDiscovered = true; log('auto-discovered price selector', priceSelector, qtySelector); } } var getter = priceSelector ? function () { var priceElement; try { priceElement = document.querySelector( priceSelector ); } catch(err) {} var amount = priceElement ? priceElement.value : '0'; if( typeof amount === 'undefined' ) { if( !/\d+[,.]\d+/.test(priceElement.textContent) && priceElement.children && priceElement.children.length ) { amount = ''; var part = priceElement.firstChild, matched; while( part ) { if( /[,.]/.test(amount) ) { return; } matched = ( part.toString() === '[object Text]' ? part.data : part.textContent ).match(/[\d,.]+/); if( matched ) { amount += (amount && !/^[,.]/.test(matched[0]) ? '.' : '') + matched[0]; } part = part.nextSibling; } } else if( priceElement.textContent ) { amount = priceElement.textContent; } else if( priceElement.getAttribute('content') ) { amount = priceElement.getAttribute('content'); } } return amount && _.parsePrice( amount ); } : function () { // return Number( widgetElement.getAttribute('data-amount') ); return; }; getter.priceSelector = priceSelector; getter.qtySelector = qtySelector; getter.autoDiscovered = autoDiscovered; return getter; } function Iframe (url) { var el = _.getIFrame({ width: '100%', height: '40px' }), iframe = this; this.el = el; this.el.src = url; new Events(this); this.onload = function () { this.emit('load', null, this); }; _.onMessage('simulator', function (e, message) { if( e.source === el.contentWindow ) { iframe.emit('message:' + message.event, [message], this); } }); this.on('message:resize', function (_e, message) { el.style.height = message.height + 'px'; }); } Iframe.prototype.message = function (eventName, data) { var _data = _.extend({ aplazame: 'simulator', event: eventName, mobile: isMobile.matches }, data || {}); if( this.el.contentWindow ) { this.el.contentWindow.postMessage(_data, '*'); } else { log('iframe contentWindow missing', this); } }; function maxInstalments (prev, choice) { if( prev === null ) { return choice; } else { return choice.num_instalments > prev.num_instalments ? choice : prev; } } function getWidget (meta) { if( !meta.options.widget ) { return; } getWidget.serial = getWidget.serial ? getWidget.serial + 1 : 1; var widget, id = getWidget.serial; if( meta.options.widget.type === 'button' ) { widget = new Iframe( api.staticUrl + 'widgets/simulator/simulator.html?' + _.now() + '&simulator=' + id ); widget.render = function () { widget.message('choices', { amount: meta.amount, currency: meta.currency, country: meta.country, choice: meta.choices.reduce(maxInstalments, null), choices: meta.choices, options: meta.options }); }; widget.on('choices.updating', function (_e) { widget.message('loading'); }); } else { widget = { el: document.createElement('div') }; new Events(widget); widget.on('choices.updating', function (_e) { widget.el.style.opacity = 0.5; }); widget.render = function () { widget.el.style.opacity = null; widget.el.innerHTML = require('../../.tmp/simulator/templates/widget-raw.tmpl')({ getAmount: _.getAmount, amount: meta.amount, currency: meta.currency, country: meta.country, choice: meta.choices.reduce(maxInstalments, null), choices: meta.choices, options: meta.options }); }; widget.el.addEventListener('click', function () { window.postMessage({ aplazame: 'modal', event: 'open', name: 'instalments', data: { size: 'lg', card: { className: 'modal-instalments-info' }, template: require('../../.tmp/simulator/templates/modal-instalments.tmpl')({ selectedChoice: meta.choices.reduce(maxInstalments, null), choices: meta.choices, currency: meta.currency, country: meta.country, getAmount: _.getAmount, months: function (m) { return m > 1 ? 'meses' : 'mes'; } }) } }, '*'); }); } widget.render(); widget.on('message:require.choices choices.update', function (_e, message) { if( message && message.simulatorId && message.simulatorId !== id ) { return; } widget.render(); }); widget.id = id; return widget; } function placeWidget (widget, widgetWrapper, selector) { if( !selector ) { widgetWrapper.appendChild(widget.el); return; } var pseudoLocator; selector = selector.trim().replace(/:(\w+?)$/, function (_matched, locator) { pseudoLocator = locator; return ''; }); var el = document.querySelector(selector); if( el ) { if( pseudoLocator ) { switch( pseudoLocator ) { case 'after': if( el.nextElementSibling ) { el.parentElement.insertBefore(widget.el, el.nextElementSibling); } else { el.parentElement.appendChild(widget.el); } break; case 'before': el.parentElement.insertBefore(widget.el, el); break; default: throw new Error('pseudoLocator ' + pseudoLocator + ' not defined'); } } else { el.appendChild(widget.el); } } } function evalWidget (widgetWrapper) { var meta, updateData = false, detectedAmount, simulatorOptions = {}; if( widgetWrapper.__apz_widget__ ) { meta = widgetWrapper.__apz_widget__; detectedAmount = meta.getAmount(); if( detectedAmount && meta.amount !== detectedAmount ) { updateData = true; meta.amount = meta.getAmount(); } } else { meta = { getAmount: amountGetter(widgetWrapper) }; meta.amount = widgetWrapper.getAttribute('data-amount') ? Number(widgetWrapper.getAttribute('data-amount')) : meta.getAmount(); updateData = true; if( meta.getAmount.qtySelector ) { meta.qty = getQty(meta.getAmount.qtySelector) || 1; meta.watchQty = setInterval(function () { if( !document.body.contains(widgetWrapper) ) { clearInterval(meta.watchQty); return; } var qty = getQty(meta.getAmount.qtySelector); if( qty !== meta.qty ) { meta.qty = qty; evalWidget(widgetWrapper); } }, 250); } } if( widgetWrapper.getAttribute('data-view') ) { simulatorOptions.view = widgetWrapper.getAttribute('data-view'); } if( meta.amount && meta.getAmount.qtySelector ) { meta.amount *= ( getQty(meta.getAmount.qtySelector) || 1 ); } if( meta.amount && updateData ) { // if( meta.widget && meta.widget.message ) { if( meta.widget ) { // meta.widget.message('loading'); meta.widget.emit('choices.updating'); } aplazame.simulator( meta.amount, simulatorOptions, function (_choices, _options) { if ( widgetWrapper.getAttribute('data-options') ) { _options = _.merge( _options, JSON.parse( widgetWrapper.getAttribute('data-options') ) ); } _options.widget = _options.widget || {}; if( _options.widget.disabled ) { return; } meta.choices = _choices; meta.options = _options; meta.currency = widgetWrapper.getAttribute('data-currency') || 'EUR'; meta.country = widgetWrapper.getAttribute('data-country') || 'ES'; meta.widget = meta.widget || getWidget(meta); if( meta.widget && !document.body.contains(meta.widget.el) ) { placeWidget(meta.widget, widgetWrapper, widgetWrapper.getAttribute('data-location') || _options.widget.location ); } meta.widget.emit('choices.update'); }, function () { if( meta.widget && meta.widget.message ) { meta.widget.message('abort'); } if( meta.widget && document.body.contains(meta.widget.el) ) { var parent = meta.widget.el.parentElement; parent.removeChild(meta.widget.el); } }); } widgetWrapper.__apz_widget__ = meta; } function widgetsLookup () { var promises = []; each.call(document.querySelectorAll('[data-aplazame-simulator]'), evalWidget ); return promises.length ? $q.all(promises) : $q.resolve(); } widgetsLookup().then(function () { _.liveDOM.subscribe(widgetsLookup); }); return widgetsLookup; };
src/loaders/data-simulator.js
'use strict'; module.exports = function (aplazame) { var _ = aplazame._, $q = require('parole'), Events = require('azazel'), api = require('../core/api'), isMobile = window.matchMedia('( max-width: 767px )'), each = Array.prototype.forEach, log = require('../tools/log'); function getQty (qtySelector) { if( !_.isString(qtySelector) ) { log('warning: data-qty should be an string. pe: form#article .final-price '); return 1; } var qtyElement; try { qtyElement = document.querySelector(qtySelector); } catch(err) { log(err.message + '\ndata-qty should be an string. pe: form#article .final-price '); return 1; } switch( qtyElement.nodeName.toLowerCase() ) { case 'input': return Number( qtyElement.value ); case 'select': return qtyElement.querySelector('option[selected]') && Number( qtyElement.querySelector('option[selected]').value ) || 1; default: return Number( qtyElement.textContent.trim() ); } } var cmsPriceSelector = [ 'form#product_addtocart_form .special-price .price', // magento 'form#product_addtocart_form .regular-price .price', // magento '#product-info .special-price .price', // magento '#product-info .regular-price .price', // magento 'form#buy_block #our_price_display', // prestashop '#main [itemtype="http://schema.org/Product"] [itemtype="http://schema.org/Offer"] .price ins .amount', // woocommerce '#main [itemtype="http://schema.org/Product"] [itemtype="http://schema.org/Offer"] .price .amount', // woocommerce '#main [itemtype="http://schema.org/Product"] .single_variation_wrap .amount', // woocommerce '[itemtype="http://schema.org/Product"] [itemtype="http://schema.org/Offer"] [itemprop="price"]' // Schema.org ], cmsQtySelector = [ 'form#product_addtocart_form input[name="qty"]', // magento 'form#buy_block input[name="qty"]', // prestashop '#quantity_wanted', // prestashop 'form#product-options-form button[data-id=qty]', // custom '#main [itemtype="http://schema.org/Product"] form.cart input[name="quantity"]' // woocommerce ]; function matchSelector (selector) { return document.querySelector(selector); } function amountGetter (widgetElement) { var priceSelector = widgetElement.getAttribute('data-price'), qtySelector = widgetElement.getAttribute('data-qty'), autoDiscovered = false; if( priceSelector ) { // try{ // document.querySelector(priceSelector); // } catch(err) { // priceSelector = null; // } if( qtySelector ) { try{ document.querySelector(qtySelector); } catch(err) { qtySelector = null; log(err.message); } } } else { priceSelector = _.find(cmsPriceSelector, matchSelector); if( priceSelector ) { qtySelector = _.find(cmsQtySelector, matchSelector); autoDiscovered = true; log('auto-discovered price selector', priceSelector, qtySelector); } } var getter = priceSelector ? function () { var priceElement; try { priceElement = document.querySelector( priceSelector ); } catch(err) {} var amount = priceElement ? priceElement.value : '0'; if( typeof amount === 'undefined' ) { if( !/\d+[,.]\d+/.test(priceElement.textContent) && priceElement.children && priceElement.children.length ) { amount = ''; var part = priceElement.firstChild, matched; while( part ) { if( /[,.]/.test(amount) ) { return; } matched = ( part.toString() === '[object Text]' ? part.data : part.textContent ).match(/[\d,.]+/); if( matched ) { amount += (amount && !/^[,.]/.test(matched[0]) ? '.' : '') + matched[0]; } part = part.nextSibling; } } else if( priceElement.textContent ) { amount = priceElement.textContent; } else if( priceElement.getAttribute('content') ) { amount = priceElement.getAttribute('content'); } } return amount && _.parsePrice( amount ); } : function () { // return Number( widgetElement.getAttribute('data-amount') ); return; }; getter.priceSelector = priceSelector; getter.qtySelector = qtySelector; getter.autoDiscovered = autoDiscovered; return getter; } function Iframe (url) { var el = _.getIFrame({ width: '100%', height: '40px' }), iframe = this; this.el = el; this.el.src = url; new Events(this); this.onload = function () { this.emit('load', null, this); }; _.onMessage('simulator', function (e, message) { if( e.source === el.contentWindow ) { iframe.emit('message:' + message.event, [message], this); } }); this.on('message:resize', function (_e, message) { el.style.height = message.height + 'px'; }); } Iframe.prototype.message = function (eventName, data) { var _data = _.extend({ aplazame: 'simulator', event: eventName, mobile: isMobile.matches }, data || {}); if( this.el.contentWindow ) { this.el.contentWindow.postMessage(_data, '*'); } else { log('iframe contentWindow missing', this); } }; function maxInstalments (prev, choice) { if( prev === null ) { return choice; } else { return choice.num_instalments > prev.num_instalments ? choice : prev; } } function getWidget (meta) { if( !meta.options.widget ) { return; } getWidget.serial = getWidget.serial ? getWidget.serial + 1 : 1; var widget, id = getWidget.serial; if( meta.options.widget.type === 'button' ) { widget = new Iframe( api.staticUrl + 'widgets/simulator/simulator.html?' + _.now() + '&simulator=' + id ); widget.render = function () { widget.message('choices', { amount: meta.amount, currency: meta.currency, country: meta.country, choice: meta.choices.reduce(maxInstalments, null), choices: meta.choices, options: meta.options }); }; widget.on('choices.updating', function (_e) { widget.message('loading'); }); } else { widget = { el: document.createElement('div') }; new Events(widget); widget.on('choices.updating', function (_e) { widget.el.style.opacity = 0.5; }); widget.render = function () { widget.el.style.opacity = null; widget.el.innerHTML = require('../../.tmp/simulator/templates/widget-raw.tmpl')({ getAmount: _.getAmount, amount: meta.amount, currency: meta.currency, country: meta.country, choice: meta.choices.reduce(maxInstalments, null), choices: meta.choices, options: meta.options }); }; widget.el.addEventListener('click', function () { window.postMessage({ aplazame: 'modal', event: 'open', name: 'instalments', data: { size: 'lg', card: { className: 'modal-instalments-info' }, template: require('../../.tmp/simulator/templates/modal-instalments.tmpl')({ selectedChoice: meta.choices.reduce(maxInstalments, null), choices: meta.choices, currency: meta.currency, country: meta.country, getAmount: _.getAmount, months: function (m) { return m > 1 ? 'meses' : 'mes'; } }) } }, '*'); }); } widget.render(); widget.on('message:require.choices choices.update', function (_e, message) { if( message && message.simulatorId && message.simulatorId !== id ) { return; } widget.render(); }); widget.id = id; return widget; } function placeWidget (widget, widgetWrapper, selector) { if( !selector ) { widgetWrapper.appendChild(widget.el); return; } var pseudoLocator; selector = selector.trim().replace(/:(\w+?)$/, function (_matched, locator) { pseudoLocator = locator; return ''; }); var el = document.querySelector(selector); if( el ) { if( pseudoLocator ) { switch( pseudoLocator ) { case 'after': if( el.nextElementSibling ) { el.parentElement.insertBefore(widget.el, el.nextElementSibling); } else { el.parentElement.appendChild(widget.el); } break; case 'before': el.parentElement.insertBefore(widget.el, el); break; default: throw new Error('pseudoLocator ' + pseudoLocator + ' not defined'); } } else { el.appendChild(widget.el); } } } function evalWidget (widgetWrapper) { var meta, updateData = false, detectedAmount, simulatorOptions = {}; if( widgetWrapper.__apz_widget__ ) { meta = widgetWrapper.__apz_widget__; detectedAmount = meta.getAmount(); if( detectedAmount && meta.amount !== detectedAmount ) { updateData = true; meta.amount = meta.getAmount(); } } else { meta = { getAmount: amountGetter(widgetWrapper) }; meta.amount = widgetWrapper.getAttribute('data-amount') ? Number(widgetWrapper.getAttribute('data-amount')) : meta.getAmount(); updateData = true; if( meta.getAmount.qtySelector ) { meta.qty = getQty(meta.getAmount.qtySelector) || 1; meta.watchQty = setInterval(function () { if( !document.body.contains(widgetWrapper) ) { clearInterval(meta.watchQty); return; } var qty = getQty(meta.getAmount.qtySelector); if( qty !== meta.qty ) { meta.qty = qty; evalWidget(widgetWrapper); } }, 250); } } if( widgetWrapper.getAttribute('data-view') ) { simulatorOptions.view = widgetWrapper.getAttribute('data-view'); } if( meta.amount && meta.getAmount.qtySelector ) { meta.amount *= ( getQty(meta.getAmount.qtySelector) || 1 ); } if( meta.amount && updateData ) { // if( meta.widget && meta.widget.message ) { if( meta.widget ) { // meta.widget.message('loading'); meta.widget.emit('choices.updating'); } aplazame.simulator( meta.amount, simulatorOptions, function (_choices, _options) { _options.widget = _options.widget || {}; if( _options.widget.disabled ) { return; } meta.choices = _choices; meta.options = _options; meta.currency = widgetWrapper.getAttribute('data-currency') || 'EUR'; meta.country = widgetWrapper.getAttribute('data-country') || 'ES'; meta.widget = meta.widget || getWidget(meta); if( meta.widget && !document.body.contains(meta.widget.el) ) { placeWidget(meta.widget, widgetWrapper, widgetWrapper.getAttribute('data-location') || _options.widget.location ); } meta.widget.emit('choices.update'); }, function () { if( meta.widget && meta.widget.message ) { meta.widget.message('abort'); } if( meta.widget && document.body.contains(meta.widget.el) ) { var parent = meta.widget.el.parentElement; parent.removeChild(meta.widget.el); } }); } widgetWrapper.__apz_widget__ = meta; } function widgetsLookup () { var promises = []; each.call(document.querySelectorAll('[data-aplazame-simulator]'), evalWidget ); return promises.length ? $q.all(promises) : $q.resolve(); } widgetsLookup().then(function () { _.liveDOM.subscribe(widgetsLookup); }); return widgetsLookup; };
Allow override remote options with local settings
src/loaders/data-simulator.js
Allow override remote options with local settings
<ide><path>rc/loaders/data-simulator.js <ide> meta.widget.emit('choices.updating'); <ide> } <ide> aplazame.simulator( meta.amount, simulatorOptions, function (_choices, _options) { <add> if ( widgetWrapper.getAttribute('data-options') ) { <add> _options = _.merge( _options, JSON.parse( widgetWrapper.getAttribute('data-options') ) ); <add> } <add> <ide> _options.widget = _options.widget || {}; <ide> if( _options.widget.disabled ) { <ide> return;
Java
apache-2.0
47869daa01679e3b318a885b571bceb8bbd8b475
0
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.fileChooser.ex; import com.intellij.ide.presentation.VirtualFilePresentation; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.fileChooser.FileChooserDescriptor; import com.intellij.openapi.fileChooser.FileSystemTree; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.openapi.vfs.newvfs.RefreshQueue; import com.intellij.util.PlatformIcons; import com.intellij.util.SystemProperties; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.io.File; import java.util.ArrayList; import java.util.List; public class LocalFsFinder implements FileLookup.Finder, FileLookup { private File myBaseDir = new File(SystemProperties.getUserHome()); @Override public LookupFile find(@NotNull final String path) { final VirtualFile byUrl = VirtualFileManager.getInstance().findFileByUrl(path); if (byUrl != null) { return new VfsFile(this, byUrl); } String toFind = normalize(path); if (toFind.length() == 0) { File[] roots = File.listRoots(); if (roots.length > 0) { toFind = roots[0].getAbsolutePath(); } } final File file = new File(toFind); // '..' and '.' path components will be eliminated VirtualFile vFile = LocalFileSystem.getInstance().findFileByIoFile(file); if (vFile != null) { return new VfsFile(this, vFile); } else if (file.isAbsolute()) { return new IoFile(new File(path)); } return null; } @Override public String normalize(@NotNull String path) { path = FileUtil.expandUserHome(path); final File file = new File(path); if (file.isAbsolute()) return file.getAbsolutePath(); if (myBaseDir != null) { return new File(myBaseDir, path).getAbsolutePath(); } return path; } @Override public String getSeparator() { return File.separator; } public void setBaseDir(@Nullable File baseDir) { myBaseDir = baseDir; } public static class FileChooserFilter implements LookupFilter { private final FileChooserDescriptor myDescriptor; private final Computable<Boolean> myShowHidden; public FileChooserFilter(final FileChooserDescriptor descriptor, boolean showHidden) { myShowHidden = new Computable.PredefinedValueComputable<>(showHidden); myDescriptor = descriptor; } public FileChooserFilter(final FileChooserDescriptor descriptor, final FileSystemTree tree) { myDescriptor = descriptor; myShowHidden = () -> tree.areHiddensShown(); } @Override public boolean isAccepted(final LookupFile file) { VirtualFile vFile = ((VfsFile)file).getFile(); if (vFile == null) return false; return myDescriptor.isFileVisible(vFile, myShowHidden.compute()); } } public static class VfsFile implements LookupFile { private final VirtualFile myFile; private final LocalFsFinder myFinder; private String myMacro; public VfsFile(LocalFsFinder finder, final VirtualFile file) { myFinder = finder; myFile = file; if (file != null) RefreshQueue.getInstance().refresh(true, false, null, ModalityState.any(), file); } @Override public String getName() { if (myFile.getParent() == null && myFile.getName().length() == 0) return "/"; return myFile.getName(); } @Override public boolean isDirectory() { return myFile != null && myFile.isDirectory(); } @Override public void setMacro(final String macro) { myMacro = macro; } @Override public String getMacro() { return myMacro; } @Override public LookupFile getParent() { return myFile != null && myFile.getParent() != null ? new VfsFile(myFinder, myFile.getParent()) : null; } @Override public String getAbsolutePath() { if (myFile.getParent() == null && myFile.getName().length() == 0) return "/"; return myFile.getPresentableUrl(); } @Override public List<LookupFile> getChildren(final LookupFilter filter) { List<LookupFile> result = new ArrayList<>(); if (myFile == null) return result; VirtualFile[] kids = myFile.getChildren(); for (VirtualFile each : kids) { LookupFile eachFile = new VfsFile(myFinder, each); if (filter.isAccepted(eachFile)) { result.add(eachFile); } } result.sort((o1, o2) -> FileUtil.comparePaths(o1.getName(), o2.getName())); return result; } public VirtualFile getFile() { return myFile; } @Override public boolean exists() { return myFile.exists(); } @Override @Nullable public Icon getIcon() { return myFile != null ? (myFile.isDirectory() ? PlatformIcons.FOLDER_ICON : VirtualFilePresentation.getIcon(myFile)) : null; } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final VfsFile vfsFile = (VfsFile)o; if (myFile != null ? !myFile.equals(vfsFile.myFile) : vfsFile.myFile != null) return false; return true; } @Override public int hashCode() { return (myFile != null ? myFile.hashCode() : 0); } } public static class IoFile extends VfsFile { private final File myIoFile; public IoFile(final File ioFile) { super(null, null); myIoFile = ioFile; } @Override public String getName() { return myIoFile.getName(); } @Override public boolean isDirectory() { return myIoFile != null && myIoFile.isDirectory(); } @Override public LookupFile getParent() { return myIoFile != null && myIoFile.getParentFile() != null ? new IoFile(myIoFile.getParentFile()) : null; } @Override public String getAbsolutePath() { return myIoFile.getAbsolutePath(); } @Override public List<LookupFile> getChildren(final LookupFilter filter) { List<LookupFile> result = new ArrayList<>(); File[] files = myIoFile.listFiles(pathname -> filter.isAccepted(new IoFile(pathname))); if (files == null) return result; for (File each : files) { result.add(new IoFile(each)); } result.sort((o1, o2) -> FileUtil.comparePaths(o1.getName(), o2.getName())); return result; } @Override public boolean exists() { return myIoFile.exists(); } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final IoFile ioFile = (IoFile)o; if (myIoFile != null ? !myIoFile.equals(ioFile.myIoFile) : ioFile.myIoFile != null) return false; return true; } @Override public int hashCode() { return (myIoFile != null ? myIoFile.hashCode() : 0); } } }
platform/platform-impl/src/com/intellij/openapi/fileChooser/ex/LocalFsFinder.java
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.fileChooser.ex; import com.intellij.ide.presentation.VirtualFilePresentation; import com.intellij.openapi.fileChooser.FileChooserDescriptor; import com.intellij.openapi.fileChooser.FileSystemTree; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.util.PlatformIcons; import com.intellij.util.SystemProperties; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.io.File; import java.util.ArrayList; import java.util.List; public class LocalFsFinder implements FileLookup.Finder, FileLookup { private File myBaseDir = new File(SystemProperties.getUserHome()); @Override public LookupFile find(@NotNull final String path) { final VirtualFile byUrl = VirtualFileManager.getInstance().findFileByUrl(path); if (byUrl != null) { return new VfsFile(this, byUrl); } String toFind = normalize(path); if (toFind.length() == 0) { File[] roots = File.listRoots(); if (roots.length > 0) { toFind = roots[0].getAbsolutePath(); } } final File file = new File(toFind); // '..' and '.' path components will be eliminated VirtualFile vFile = LocalFileSystem.getInstance().findFileByIoFile(file); if (vFile != null) { return new VfsFile(this, vFile); } else if (file.isAbsolute()) { return new IoFile(new File(path)); } return null; } @Override public String normalize(@NotNull String path) { path = FileUtil.expandUserHome(path); final File file = new File(path); if (file.isAbsolute()) return file.getAbsolutePath(); if (myBaseDir != null) { return new File(myBaseDir, path).getAbsolutePath(); } return path; } @Override public String getSeparator() { return File.separator; } public void setBaseDir(@Nullable File baseDir) { myBaseDir = baseDir; } public static class FileChooserFilter implements LookupFilter { private final FileChooserDescriptor myDescriptor; private final Computable<Boolean> myShowHidden; public FileChooserFilter(final FileChooserDescriptor descriptor, boolean showHidden) { myShowHidden = new Computable.PredefinedValueComputable<>(showHidden); myDescriptor = descriptor; } public FileChooserFilter(final FileChooserDescriptor descriptor, final FileSystemTree tree) { myDescriptor = descriptor; myShowHidden = () -> tree.areHiddensShown(); } @Override public boolean isAccepted(final LookupFile file) { VirtualFile vFile = ((VfsFile)file).getFile(); if (vFile == null) return false; return myDescriptor.isFileVisible(vFile, myShowHidden.compute()); } } public static class VfsFile implements LookupFile { private final VirtualFile myFile; private final LocalFsFinder myFinder; private String myMacro; public VfsFile(LocalFsFinder finder, final VirtualFile file) { myFinder = finder; myFile = file; } @Override public String getName() { if (myFile.getParent() == null && myFile.getName().length() == 0) return "/"; return myFile.getName(); } @Override public boolean isDirectory() { return myFile != null && myFile.isDirectory(); } @Override public void setMacro(final String macro) { myMacro = macro; } @Override public String getMacro() { return myMacro; } @Override public LookupFile getParent() { return myFile != null && myFile.getParent() != null ? new VfsFile(myFinder, myFile.getParent()) : null; } @Override public String getAbsolutePath() { if (myFile.getParent() == null && myFile.getName().length() == 0) return "/"; return myFile.getPresentableUrl(); } @Override public List<LookupFile> getChildren(final LookupFilter filter) { List<LookupFile> result = new ArrayList<>(); if (myFile == null) return result; VirtualFile[] kids = myFile.getChildren(); for (VirtualFile each : kids) { LookupFile eachFile = new VfsFile(myFinder, each); if (filter.isAccepted(eachFile)) { result.add(eachFile); } } result.sort((o1, o2) -> FileUtil.comparePaths(o1.getName(), o2.getName())); return result; } public VirtualFile getFile() { return myFile; } @Override public boolean exists() { return myFile.exists(); } @Override @Nullable public Icon getIcon() { return myFile != null ? (myFile.isDirectory() ? PlatformIcons.FOLDER_ICON : VirtualFilePresentation.getIcon(myFile)) : null; } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final VfsFile vfsFile = (VfsFile)o; if (myFile != null ? !myFile.equals(vfsFile.myFile) : vfsFile.myFile != null) return false; return true; } @Override public int hashCode() { return (myFile != null ? myFile.hashCode() : 0); } } public static class IoFile extends VfsFile { private final File myIoFile; public IoFile(final File ioFile) { super(null, null); myIoFile = ioFile; } @Override public String getName() { return myIoFile.getName(); } @Override public boolean isDirectory() { return myIoFile != null && myIoFile.isDirectory(); } @Override public LookupFile getParent() { return myIoFile != null && myIoFile.getParentFile() != null ? new IoFile(myIoFile.getParentFile()) : null; } @Override public String getAbsolutePath() { return myIoFile.getAbsolutePath(); } @Override public List<LookupFile> getChildren(final LookupFilter filter) { List<LookupFile> result = new ArrayList<>(); File[] files = myIoFile.listFiles(pathname -> filter.isAccepted(new IoFile(pathname))); if (files == null) return result; for (File each : files) { result.add(new IoFile(each)); } result.sort((o1, o2) -> FileUtil.comparePaths(o1.getName(), o2.getName())); return result; } @Override public boolean exists() { return myIoFile.exists(); } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final IoFile ioFile = (IoFile)o; if (myIoFile != null ? !myIoFile.equals(ioFile.myIoFile) : ioFile.myIoFile != null) return false; return true; } @Override public int hashCode() { return (myIoFile != null ? myIoFile.hashCode() : 0); } } }
IDEA-236854: refresh virtual file before requesting its children GitOrigin-RevId: fd6d2d70c85214a3710ed8950ca574387c0207ac
platform/platform-impl/src/com/intellij/openapi/fileChooser/ex/LocalFsFinder.java
IDEA-236854: refresh virtual file before requesting its children
<ide><path>latform/platform-impl/src/com/intellij/openapi/fileChooser/ex/LocalFsFinder.java <ide> package com.intellij.openapi.fileChooser.ex; <ide> <ide> import com.intellij.ide.presentation.VirtualFilePresentation; <add>import com.intellij.openapi.application.ModalityState; <ide> import com.intellij.openapi.fileChooser.FileChooserDescriptor; <ide> import com.intellij.openapi.fileChooser.FileSystemTree; <ide> import com.intellij.openapi.util.Computable; <ide> import com.intellij.openapi.vfs.LocalFileSystem; <ide> import com.intellij.openapi.vfs.VirtualFile; <ide> import com.intellij.openapi.vfs.VirtualFileManager; <add>import com.intellij.openapi.vfs.newvfs.RefreshQueue; <ide> import com.intellij.util.PlatformIcons; <ide> import com.intellij.util.SystemProperties; <ide> import org.jetbrains.annotations.NotNull; <ide> public VfsFile(LocalFsFinder finder, final VirtualFile file) { <ide> myFinder = finder; <ide> myFile = file; <add> if (file != null) RefreshQueue.getInstance().refresh(true, false, null, ModalityState.any(), file); <ide> } <ide> <ide> @Override
Java
apache-2.0
015ebbe871fd8120cc199fe2003598f67689ce05
0
jackygurui/redisson,zhoffice/redisson,mrniko/redisson,ContaAzul/redisson,redisson/redisson
/** * Copyright 2016 Nikita Koksharov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.redisson.cache; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.concurrent.atomic.AtomicLong; /** * LRU (least recently used) cache. * * @author Nikita Koksharov * * @param <K> key * @param <V> value */ public class LRUCacheMap<K, V> extends AbstractCacheMap<K, V> { private final AtomicLong index = new AtomicLong(); private final List<Collection<CachedValue<K, V>>> queues = new ArrayList<Collection<CachedValue<K, V>>>(Runtime.getRuntime().availableProcessors()*2); public LRUCacheMap(int size, long timeToLiveInMillis, long maxIdleInMillis) { super(size, timeToLiveInMillis, maxIdleInMillis); for (int i = 0; i < Runtime.getRuntime().availableProcessors()*2; i++) { Set<CachedValue<K, V>> instance = Collections.synchronizedSet(new LinkedHashSet<CachedValue<K, V>>()); queues.add(instance); } } @Override protected void onValueCreate(CachedValue<K, V> value) { Collection<CachedValue<K, V>> queue = getQueue(value); queue.add(value); } private Collection<CachedValue<K, V>> getQueue(CachedValue<K, V> value) { return queues.get(value.hashCode() % queues.size()); } @Override protected void onValueRemove(CachedValue<K, V> value) { Collection<CachedValue<K, V>> queue = getQueue(value); queue.remove(value); } @Override protected void onValueRead(CachedValue<K, V> value) { Collection<CachedValue<K, V>> queue = getQueue(value); // move value to tail of queue if (queue.remove(value)) { queue.add(value); } } @Override protected void onMapFull() { Collection<CachedValue<K, V>> queue = queues.get((int)Math.abs(index.incrementAndGet() % queues.size())); synchronized (queue) { Iterator<CachedValue<K, V>> iter = queue.iterator(); if (iter.hasNext()) { CachedValue<K, V> value = iter.next(); iter.remove(); map.remove(value.getKey(), value); } } } @Override public void clear() { for (Collection<CachedValue<K, V>> collection : queues) { collection.clear(); } super.clear(); } }
redisson/src/main/java/org/redisson/cache/LRUCacheMap.java
/** * Copyright 2016 Nikita Koksharov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.redisson.cache; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; /** * LRU (least recently used) cache. * * @author Nikita Koksharov * * @param <K> key * @param <V> value */ public class LRUCacheMap<K, V> extends AbstractCacheMap<K, V> { private final Queue<CachedValue> queue = new ConcurrentLinkedQueue<CachedValue>(); public LRUCacheMap(int size, long timeToLiveInMillis, long maxIdleInMillis) { super(size, timeToLiveInMillis, maxIdleInMillis); } @Override protected void onValueCreate(CachedValue value) { queue.add(value); } @Override protected void onValueRemove(CachedValue value) { queue.remove(value); } @Override protected void onValueRead(CachedValue value) { // move value to tail of queue if (queue.remove(value)) { queue.add(value); } } @Override protected void onMapFull() { CachedValue value = queue.poll(); if (value != null) { map.remove(value.getKey(), value); } } @Override public void clear() { queue.clear(); super.clear(); } }
LRUCacheMap optimization.
redisson/src/main/java/org/redisson/cache/LRUCacheMap.java
LRUCacheMap optimization.
<ide><path>edisson/src/main/java/org/redisson/cache/LRUCacheMap.java <ide> */ <ide> package org.redisson.cache; <ide> <del>import java.util.Queue; <del>import java.util.concurrent.ConcurrentLinkedQueue; <add>import java.util.ArrayList; <add>import java.util.Collection; <add>import java.util.Collections; <add>import java.util.Iterator; <add>import java.util.LinkedHashSet; <add>import java.util.List; <add>import java.util.Set; <add>import java.util.concurrent.atomic.AtomicLong; <ide> <ide> /** <ide> * LRU (least recently used) cache. <ide> */ <ide> public class LRUCacheMap<K, V> extends AbstractCacheMap<K, V> { <ide> <del> private final Queue<CachedValue> queue = new ConcurrentLinkedQueue<CachedValue>(); <add> private final AtomicLong index = new AtomicLong(); <add> private final List<Collection<CachedValue<K, V>>> queues = <add> new ArrayList<Collection<CachedValue<K, V>>>(Runtime.getRuntime().availableProcessors()*2); <ide> <ide> public LRUCacheMap(int size, long timeToLiveInMillis, long maxIdleInMillis) { <ide> super(size, timeToLiveInMillis, maxIdleInMillis); <add> <add> for (int i = 0; i < Runtime.getRuntime().availableProcessors()*2; i++) { <add> Set<CachedValue<K, V>> instance = Collections.synchronizedSet(new LinkedHashSet<CachedValue<K, V>>()); <add> queues.add(instance); <add> } <ide> } <ide> <ide> @Override <del> protected void onValueCreate(CachedValue value) { <add> protected void onValueCreate(CachedValue<K, V> value) { <add> Collection<CachedValue<K, V>> queue = getQueue(value); <ide> queue.add(value); <add> } <add> <add> private Collection<CachedValue<K, V>> getQueue(CachedValue<K, V> value) { <add> return queues.get(value.hashCode() % queues.size()); <ide> } <ide> <ide> @Override <del> protected void onValueRemove(CachedValue value) { <add> protected void onValueRemove(CachedValue<K, V> value) { <add> Collection<CachedValue<K, V>> queue = getQueue(value); <ide> queue.remove(value); <ide> } <ide> <ide> @Override <del> protected void onValueRead(CachedValue value) { <add> protected void onValueRead(CachedValue<K, V> value) { <add> Collection<CachedValue<K, V>> queue = getQueue(value); <ide> // move value to tail of queue <ide> if (queue.remove(value)) { <ide> queue.add(value); <ide> <ide> @Override <ide> protected void onMapFull() { <del> CachedValue value = queue.poll(); <del> if (value != null) { <del> map.remove(value.getKey(), value); <add> Collection<CachedValue<K, V>> queue = queues.get((int)Math.abs(index.incrementAndGet() % queues.size())); <add> synchronized (queue) { <add> Iterator<CachedValue<K, V>> iter = queue.iterator(); <add> if (iter.hasNext()) { <add> CachedValue<K, V> value = iter.next(); <add> iter.remove(); <add> map.remove(value.getKey(), value); <add> } <ide> } <ide> } <ide> <ide> @Override <ide> public void clear() { <del> queue.clear(); <add> for (Collection<CachedValue<K, V>> collection : queues) { <add> collection.clear(); <add> } <ide> super.clear(); <ide> } <ide>
Java
apache-2.0
44c81acceba0c56032316cc936b2f828cebce6dd
0
tmpgit/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,signed/intellij-community,apixandru/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,orekyuu/intellij-community,asedunov/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,caot/intellij-community,Lekanich/intellij-community,semonte/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,allotria/intellij-community,petteyg/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,dslomov/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,asedunov/intellij-community,apixandru/intellij-community,apixandru/intellij-community,xfournet/intellij-community,izonder/intellij-community,hurricup/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,hurricup/intellij-community,jagguli/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,da1z/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,retomerz/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,consulo/consulo,apixandru/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,allotria/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,da1z/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,caot/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,da1z/intellij-community,asedunov/intellij-community,jagguli/intellij-community,hurricup/intellij-community,adedayo/intellij-community,xfournet/intellij-community,fitermay/intellij-community,amith01994/intellij-community,retomerz/intellij-community,jagguli/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,consulo/consulo,akosyakov/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,caot/intellij-community,allotria/intellij-community,ryano144/intellij-community,caot/intellij-community,slisson/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,ibinti/intellij-community,FHannes/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,diorcety/intellij-community,tmpgit/intellij-community,samthor/intellij-community,suncycheng/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,caot/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,diorcety/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,samthor/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,kdwink/intellij-community,allotria/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,amith01994/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,caot/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,clumsy/intellij-community,izonder/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,hurricup/intellij-community,jagguli/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,supersven/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,ernestp/consulo,gnuhub/intellij-community,clumsy/intellij-community,clumsy/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,robovm/robovm-studio,izonder/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,salguarnieri/intellij-community,caot/intellij-community,clumsy/intellij-community,slisson/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,caot/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,kool79/intellij-community,allotria/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,da1z/intellij-community,retomerz/intellij-community,izonder/intellij-community,robovm/robovm-studio,ibinti/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,izonder/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,allotria/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,retomerz/intellij-community,xfournet/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,slisson/intellij-community,asedunov/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,kool79/intellij-community,vladmm/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,supersven/intellij-community,orekyuu/intellij-community,ernestp/consulo,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,dslomov/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,suncycheng/intellij-community,holmes/intellij-community,robovm/robovm-studio,hurricup/intellij-community,vladmm/intellij-community,kdwink/intellij-community,holmes/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,allotria/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,consulo/consulo,dslomov/intellij-community,TangHao1987/intellij-community,caot/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,retomerz/intellij-community,da1z/intellij-community,nicolargo/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,allotria/intellij-community,supersven/intellij-community,youdonghai/intellij-community,ernestp/consulo,orekyuu/intellij-community,petteyg/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,hurricup/intellij-community,petteyg/intellij-community,signed/intellij-community,holmes/intellij-community,adedayo/intellij-community,da1z/intellij-community,signed/intellij-community,ryano144/intellij-community,signed/intellij-community,semonte/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,adedayo/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,ernestp/consulo,blademainer/intellij-community,suncycheng/intellij-community,ernestp/consulo,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,diorcety/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,consulo/consulo,kdwink/intellij-community,semonte/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,holmes/intellij-community,asedunov/intellij-community,ryano144/intellij-community,ryano144/intellij-community,da1z/intellij-community,holmes/intellij-community,ibinti/intellij-community,slisson/intellij-community,clumsy/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,FHannes/intellij-community,retomerz/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,signed/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,holmes/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,signed/intellij-community,youdonghai/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,fnouama/intellij-community,ibinti/intellij-community,signed/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,jagguli/intellij-community,ryano144/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,samthor/intellij-community,allotria/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,amith01994/intellij-community,dslomov/intellij-community,holmes/intellij-community,ryano144/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,samthor/intellij-community,blademainer/intellij-community,jagguli/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,dslomov/intellij-community,kool79/intellij-community,fitermay/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,fitermay/intellij-community,adedayo/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,fnouama/intellij-community,kool79/intellij-community,clumsy/intellij-community,kool79/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,petteyg/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,da1z/intellij-community,slisson/intellij-community,petteyg/intellij-community,apixandru/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,robovm/robovm-studio,dslomov/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,semonte/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,slisson/intellij-community,jagguli/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,diorcety/intellij-community,fnouama/intellij-community,petteyg/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,ernestp/consulo,Distrotech/intellij-community,supersven/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,fitermay/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,fnouama/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,consulo/consulo,blademainer/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,consulo/consulo,apixandru/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,semonte/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,caot/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,Distrotech/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,blademainer/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,kool79/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,ahb0327/intellij-community
/* * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.ide.actions; import com.intellij.ide.IdeBundle; import com.intellij.ide.impl.ProjectUtil; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.PlatformDataKeys; import com.intellij.openapi.application.ApplicationNamesInfo; import com.intellij.openapi.fileChooser.FileChooser; import com.intellij.openapi.fileChooser.FileChooserDescriptor; import com.intellij.openapi.fileChooser.FileElement; import com.intellij.openapi.fileChooser.PathChooserDialog; import com.intellij.openapi.fileChooser.impl.FileChooserUtil; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileEditor.OpenFileDescriptor; import com.intellij.openapi.fileEditor.ex.FileEditorProviderManager; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.ex.FileTypeChooser; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.platform.PlatformProjectOpenProcessor; import com.intellij.projectImport.ProjectAttachProcessor; import com.intellij.util.Consumer; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; public class OpenFileAction extends AnAction implements DumbAware { public void actionPerformed(AnActionEvent e) { @Nullable final Project project = PlatformDataKeys.PROJECT.getData(e.getDataContext()); final boolean showFiles = project != null || PlatformProjectOpenProcessor.getInstanceIfItExists() != null; final FileChooserDescriptor descriptor = new OpenProjectFileChooserDescriptor(true) { @Override public boolean isFileSelectable(VirtualFile file) { if (super.isFileSelectable(file)) { return true; } if (file.isDirectory()) { return false; } return showFiles && !FileElement.isArchive(file); } @Override public boolean isFileVisible(VirtualFile file, boolean showHiddenFiles) { if (!file.isDirectory() && isFileSelectable(file)) { if (!showHiddenFiles && FileElement.isFileHidden(file)) return false; return true; } return super.isFileVisible(file, showHiddenFiles); } @Override public boolean isChooseMultiple() { return showFiles; } }; descriptor.setTitle(showFiles ? "Open File or Project" : "Open Project"); VirtualFile userHomeDir = null; if (SystemInfo.isUnix) { userHomeDir = VfsUtil.getUserHomeDir(); } descriptor.putUserData(PathChooserDialog.PREFER_LAST_OVER_EXPLICIT, Boolean.TRUE); FileChooser.chooseFiles(descriptor, project, userHomeDir, new Consumer<List<VirtualFile>>() { @Override public void consume(final List<VirtualFile> files) { for (VirtualFile file : files) { if (!descriptor.isFileSelectable(file)) { // on Mac, it could be selected anyway Messages.showInfoMessage(project, file.getPresentableUrl() + " contains no " + ApplicationNamesInfo.getInstance().getFullProductName() + " project", "Cannot Open Project"); return; } } doOpenFile(project, files); } }); } private static void doOpenFile(@Nullable final Project project, @NotNull final List<VirtualFile> result) { for (final VirtualFile file : result) { if (file.isDirectory()) { Project openedProject; if (ProjectAttachProcessor.canAttachToProject()) { openedProject = PlatformProjectOpenProcessor.doOpenProject(file, project, false, -1, null, false); } else { openedProject = ProjectUtil.openOrImport(file.getPath(), project, false); } FileChooserUtil.setLastOpenedFile(openedProject, file); return; } if (OpenProjectFileChooserDescriptor.isProjectFile(file)) { int answer = Messages.showYesNoDialog(project, IdeBundle.message("message.open.file.is.project", file.getName()), IdeBundle.message("title.open.project"), Messages.getQuestionIcon()); if (answer == 0) { FileChooserUtil.setLastOpenedFile(ProjectUtil.openOrImport(file.getPath(), project, false), file); return; } } FileType type = FileTypeChooser.getKnownFileTypeOrAssociate(file, project); if (type == null) return; if (project != null) { openFile(file, project); } else { PlatformProjectOpenProcessor processor = PlatformProjectOpenProcessor.getInstanceIfItExists(); if (processor != null) { processor.doOpenProject(file, null, false); } } } } public static void openFile(final String filePath, final Project project) { final VirtualFile file = LocalFileSystem.getInstance().findFileByPath(filePath); if (file != null && file.isValid()) { openFile(file, project); } } public static void openFile(final VirtualFile virtualFile, final Project project) { FileEditorProviderManager editorProviderManager = FileEditorProviderManager.getInstance(); if (editorProviderManager.getProviders(project, virtualFile).length == 0) { Messages.showMessageDialog(project, IdeBundle.message("error.files.of.this.type.cannot.be.opened", ApplicationNamesInfo.getInstance().getProductName()), IdeBundle.message("title.cannot.open.file"), Messages.getErrorIcon()); return; } OpenFileDescriptor descriptor = new OpenFileDescriptor(project, virtualFile); FileEditorManager.getInstance(project).openTextEditor(descriptor, true); } }
platform/platform-impl/src/com/intellij/ide/actions/OpenFileAction.java
/* * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.ide.actions; import com.intellij.ide.IdeBundle; import com.intellij.ide.impl.ProjectUtil; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.PlatformDataKeys; import com.intellij.openapi.application.ApplicationNamesInfo; import com.intellij.openapi.fileChooser.FileChooser; import com.intellij.openapi.fileChooser.FileChooserDescriptor; import com.intellij.openapi.fileChooser.FileElement; import com.intellij.openapi.fileChooser.PathChooserDialog; import com.intellij.openapi.fileChooser.impl.FileChooserUtil; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileEditor.OpenFileDescriptor; import com.intellij.openapi.fileEditor.ex.FileEditorProviderManager; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.ex.FileTypeChooser; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.platform.PlatformProjectOpenProcessor; import com.intellij.util.Consumer; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; public class OpenFileAction extends AnAction implements DumbAware { public void actionPerformed(AnActionEvent e) { @Nullable final Project project = PlatformDataKeys.PROJECT.getData(e.getDataContext()); final boolean showFiles = project != null || PlatformProjectOpenProcessor.getInstanceIfItExists() != null; final FileChooserDescriptor descriptor = new OpenProjectFileChooserDescriptor(true) { @Override public boolean isFileSelectable(VirtualFile file) { if (super.isFileSelectable(file)) { return true; } if (file.isDirectory()) { return false; } return showFiles && !FileElement.isArchive(file); } @Override public boolean isFileVisible(VirtualFile file, boolean showHiddenFiles) { if (!file.isDirectory() && isFileSelectable(file)) { if (!showHiddenFiles && FileElement.isFileHidden(file)) return false; return true; } return super.isFileVisible(file, showHiddenFiles); } @Override public boolean isChooseMultiple() { return showFiles; } }; descriptor.setTitle(showFiles ? "Open File or Project" : "Open Project"); VirtualFile userHomeDir = null; if (SystemInfo.isUnix) { userHomeDir = VfsUtil.getUserHomeDir(); } descriptor.putUserData(PathChooserDialog.PREFER_LAST_OVER_EXPLICIT, Boolean.TRUE); FileChooser.chooseFiles(descriptor, project, userHomeDir, new Consumer<List<VirtualFile>>() { @Override public void consume(final List<VirtualFile> files) { for (VirtualFile file : files) { if (!descriptor.isFileSelectable(file)) { // on Mac, it could be selected anyway Messages.showInfoMessage(project, file.getPresentableUrl() + " contains no " + ApplicationNamesInfo.getInstance().getFullProductName() + " project", "Cannot Open Project"); return; } } doOpenFile(project, files); } }); } private static void doOpenFile(@Nullable final Project project, @NotNull final List<VirtualFile> result) { for (final VirtualFile file : result) { if (file.isDirectory()) { FileChooserUtil.setLastOpenedFile(ProjectUtil.openOrImport(file.getPath(), project, false), file); return; } if (OpenProjectFileChooserDescriptor.isProjectFile(file)) { int answer = Messages.showYesNoDialog(project, IdeBundle.message("message.open.file.is.project", file.getName()), IdeBundle.message("title.open.project"), Messages.getQuestionIcon()); if (answer == 0) { FileChooserUtil.setLastOpenedFile(ProjectUtil.openOrImport(file.getPath(), project, false), file); return; } } FileType type = FileTypeChooser.getKnownFileTypeOrAssociate(file, project); if (type == null) return; if (project != null) { openFile(file, project); } else { PlatformProjectOpenProcessor processor = PlatformProjectOpenProcessor.getInstanceIfItExists(); if (processor != null) { processor.doOpenProject(file, null, false); } } } } public static void openFile(final String filePath, final Project project) { final VirtualFile file = LocalFileSystem.getInstance().findFileByPath(filePath); if (file != null && file.isValid()) { openFile(file, project); } } public static void openFile(final VirtualFile virtualFile, final Project project) { FileEditorProviderManager editorProviderManager = FileEditorProviderManager.getInstance(); if (editorProviderManager.getProviders(project, virtualFile).length == 0) { Messages.showMessageDialog(project, IdeBundle.message("error.files.of.this.type.cannot.be.opened", ApplicationNamesInfo.getInstance().getProductName()), IdeBundle.message("title.cannot.open.file"), Messages.getErrorIcon()); return; } OpenFileDescriptor descriptor = new OpenFileDescriptor(project, virtualFile); FileEditorManager.getInstance(project).openTextEditor(descriptor, true); } }
ask for attach when the "open file" is used to open project (PY-7830)
platform/platform-impl/src/com/intellij/ide/actions/OpenFileAction.java
ask for attach when the "open file" is used to open project (PY-7830)
<ide><path>latform/platform-impl/src/com/intellij/ide/actions/OpenFileAction.java <ide> import com.intellij.openapi.vfs.VfsUtil; <ide> import com.intellij.openapi.vfs.VirtualFile; <ide> import com.intellij.platform.PlatformProjectOpenProcessor; <add>import com.intellij.projectImport.ProjectAttachProcessor; <ide> import com.intellij.util.Consumer; <ide> import org.jetbrains.annotations.NotNull; <ide> import org.jetbrains.annotations.Nullable; <ide> @NotNull final List<VirtualFile> result) { <ide> for (final VirtualFile file : result) { <ide> if (file.isDirectory()) { <del> FileChooserUtil.setLastOpenedFile(ProjectUtil.openOrImport(file.getPath(), project, false), file); <add> Project openedProject; <add> if (ProjectAttachProcessor.canAttachToProject()) { <add> openedProject = PlatformProjectOpenProcessor.doOpenProject(file, project, false, -1, null, false); <add> } <add> else { <add> openedProject = ProjectUtil.openOrImport(file.getPath(), project, false); <add> } <add> FileChooserUtil.setLastOpenedFile(openedProject, file); <ide> return; <ide> } <ide>
JavaScript
mit
dcb58826928614d0fa6f36970c7696e680f6ad12
0
panpawn/Gold-Server,panpawn/Pokemon-Showdown,Gold-Solox/Pokemon-Showdown,Tesarand/Pokemon-Showdown,panpawn/Gold-Server,Tesarand/Pokemon-Showdown,Tesarand/Pokemon-Showdown,panpawn/Pokemon-Showdown,BuzzyOG/Pokemon-Showdown,BuzzyOG/Pokemon-Showdown,Gold-Solox/Pokemon-Showdown,panpawn/Gold-Server,Git-Worm/City-PS,BuzzyOG/Pokemon-Showdown,Git-Worm/City-PS
/** * Commands * Pokemon Showdown - https://pokemonshowdown.com/ * * These are commands. For instance, you can define the command 'whois' * here, then use it by typing /whois into Pokemon Showdown. * * A command can be in the form: * ip: 'whois', * This is called an alias: it makes it so /ip does the same thing as * /whois. * * But to actually define a command, it's a function: * * allowchallenges: function (target, room, user) { * user.blockChallenges = false; * this.sendReply("You are available for challenges from now on."); * } * * Commands are actually passed five parameters: * function (target, room, user, connection, cmd, message) * Most of the time, you only need the first three, though. * * target = the part of the message after the command * room = the room object the message was sent to * The room name is room.id * user = the user object that sent the message * The user's name is user.name * connection = the connection that the message was sent from * cmd = the name of the command * message = the entire message sent by the user * * If a user types in "/msg zarel, hello" * target = "zarel, hello" * cmd = "msg" * message = "/msg zarel, hello" * * Commands return the message the user should say. If they don't * return anything or return something falsy, the user won't say * anything. * * Commands have access to the following functions: * * this.sendReply(message) * Sends a message back to the room the user typed the command into. * * this.sendReplyBox(html) * Same as sendReply, but shows it in a box, and you can put HTML in * it. * * this.popupReply(message) * Shows a popup in the window the user typed the command into. * * this.add(message) * Adds a message to the room so that everyone can see it. * This is like this.sendReply, except everyone in the room gets it, * instead of just the user that typed the command. * * this.send(message) * Sends a message to the room so that everyone can see it. * This is like this.add, except it's not logged, and users who join * the room later won't see it in the log, and if it's a battle, it * won't show up in saved replays. * You USUALLY want to use this.add instead. * * this.logEntry(message) * Log a message to the room's log without sending it to anyone. This * is like this.add, except no one will see it. * * this.addModCommand(message) * Like this.add, but also logs the message to the moderator log * which can be seen with /modlog. * * this.logModCommand(message) * Like this.addModCommand, except users in the room won't see it. * * this.can(permission) * this.can(permission, targetUser) * Checks if the user has the permission to do something, or if a * targetUser is passed, check if the user has permission to do * it to that user. Will automatically give the user an "Access * denied" message if the user doesn't have permission: use * user.can() if you don't want that message. * * Should usually be near the top of the command, like: * if (!this.can('potd')) return false; * * this.canBroadcast() * Signifies that a message can be broadcast, as long as the user * has permission to. This will check to see if the user used * "!command" instead of "/command". If so, it will check to see * if the user has permission to broadcast (by default, voice+ can), * and return false if not. Otherwise, it will add the message to * the room, and turn on the flag this.broadcasting, so that * this.sendReply and this.sendReplyBox will broadcast to the room * instead of just the user that used the command. * * Should usually be near the top of the command, like: * if (!this.canBroadcast()) return false; * * this.canBroadcast(suppressMessage) * Functionally the same as this.canBroadcast(). However, it * will look as if the user had written the text suppressMessage. * * this.canTalk() * Checks to see if the user can speak in the room. Returns false * if the user can't speak (is muted, the room has modchat on, etc), * or true otherwise. * * Should usually be near the top of the command, like: * if (!this.canTalk()) return false; * * this.canTalk(message, room) * Checks to see if the user can say the message in the room. * If a room is not specified, it will default to the current one. * If it has a falsy value, the check won't be attached to any room. * In addition to running the checks from this.canTalk(), it also * checks to see if the message has any banned words, is too long, * or was just sent by the user. Returns the filtered message, or a * falsy value if the user can't speak. * * Should usually be near the top of the command, like: * target = this.canTalk(target); * if (!target) return false; * * this.parse(message) * Runs the message as if the user had typed it in. * * Mostly useful for giving help messages, like for commands that * require a target: * if (!target) return this.parse('/help msg'); * * After 10 levels of recursion (calling this.parse from a command * called by this.parse from a command called by this.parse etc) * we will assume it's a bug in your command and error out. * * this.targetUserOrSelf(target, exactName) * If target is blank, returns the user that sent the message. * Otherwise, returns the user with the username in target, or * a falsy value if no user with that username exists. * By default, this will track users across name changes. However, * if exactName is true, it will enforce exact matches. * * this.getLastIdOf(user) * Returns the last userid of an specified user. * * this.splitTarget(target, exactName) * Splits a target in the form "user, message" into its * constituent parts. Returns message, and sets this.targetUser to * the user, and this.targetUsername to the username. * By default, this will track users across name changes. However, * if exactName is true, it will enforce exact matches. * * Remember to check if this.targetUser exists before going further. * * Unless otherwise specified, these functions will return undefined, * so you can return this.sendReply or something to send a reply and * stop the command there. * * @license MIT license */ var fs = require('fs'); var badges = fs.createWriteStream('badges.txt',{'flags':'a'}); var commands = exports.commands = { ip: 'whois', rooms: 'whois', alt: 'whois', alts: 'whois', whois: function (target, room, user) { var targetUser = this.targetUserOrSelf(target, user.group === ' '); if (!targetUser) { return this.sendReply("User " + this.targetUsername + " not found."); } this.sendReply("User: " + targetUser.name); if (user.can('alts', targetUser)) { var alts = targetUser.getAlts(true); var output = Object.keys(targetUser.prevNames).join(", "); if (output) this.sendReply("Previous names: " + output); for (var j = 0; j < alts.length; ++j) { var targetAlt = Users.get(alts[j]); if (!targetAlt.named && !targetAlt.connected) continue; if (targetAlt.group === '~' && user.group !== '~') continue; this.sendReply("Alt: " + targetAlt.name); output = Object.keys(targetAlt.prevNames).join(", "); if (output) this.sendReply("Previous names: " + output); } if (targetUser.locked) { this.sendReply("Locked under the username: " + targetUser.locked); } } if (Config.groups[targetUser.group] && Config.groups[targetUser.group].name) { this.sendReply("Group: " + Config.groups[targetUser.group].name + " (" + targetUser.group + ")"); } if (targetUser.goldDev) { this.sendReply('(Gold Development Staff)'); } if (targetUser.goldVip) { this.sendReply('|html|(<font color="gold">VIP</font> User)'); } if (targetUser.isSysop) { this.sendReply("(Pok\xE9mon Showdown System Operator)"); } if (!targetUser.authenticated) { this.sendReply("(Unregistered)"); } if (!this.broadcasting && (user.can('ip', targetUser) || user === targetUser)) { var ips = Object.keys(targetUser.ips); this.sendReply("IP" + ((ips.length > 1) ? "s" : "") + ": " + ips.join(", ") + (user.group !== ' ' && targetUser.latestHost ? "\nHost: " + targetUser.latestHost : "")); } if (targetUser.canCustomSymbol || targetUser.canCustomAvatar || targetUser.canAnimatedAvatar || targetUser.canChatRoom || targetUser.canTrainerCard || targetUser.canFixItem || targetUser.canDecAdvertise || targetUser.canBadge || targetUser.canPOTD || targetUser.canForcerename || targetUser.canMusicBox || targetUser.canCustomEmote) { var i = ''; if (targetUser.canCustomSymbol) i += ' Custom Symbol'; if (targetUser.canCustomAvatar) i += ' Custom Avatar'; if (targetUser.canCustomEmote) i += ' Custom Emote' if (targetUser.canAnimatedAvatar) i += ' Animated Avatar'; if (targetUser.canChatRoom) i += ' Chat Room'; if (targetUser.canTrainerCard) i += ' Trainer Card'; if (targetUser.canFixItem) i += ' Alter card/avatar/music box'; if (targetUser.canDecAdvertise) i += ' Declare Advertise'; if (targetUser.canBadge) i += ' VIP Badge / Global Voice'; if (targetUser.canMusicBox) i += ' Music Box'; if (targetUser.canPOTD) i += ' POTD'; if (targetUser.canForcerename) i += ' Forcerename' this.sendReply('Eligible for: ' + i); } var output = "In rooms: "; var first = true; for (var i in targetUser.roomCount) { if (i === 'global' || Rooms.get(i).isPrivate) continue; if (!first) output += " | "; first = false; output += '<a href="/' + i + '" room="' + i + '">' + i + '</a>'; } if (!targetUser.connected || targetUser.isAway) { this.sendReply('|raw|This user is ' + ((!targetUser.connected) ? '<font color = "red">offline</font>.' : '<font color = "orange">away</font>.')); } this.sendReply('|raw|' + output); }, aip: 'inprivaterooms', awhois: 'inprivaterooms', allrooms: 'inprivaterooms', prooms: 'inprivaterooms', adminwhois: 'inprivaterooms', inprivaterooms: function(target, room, user) { if (!this.can('seeprivaterooms')) return false; var targetUser = this.targetUserOrSelf(target); if (!targetUser) { return this.sendReply('User '+this.targetUsername+' not found.'); } this.sendReply('User: '+targetUser.name); if (user.can('seeprivaterooms',targetUser)) { var alts = targetUser.getAlts(); var output = ''; for (var i in targetUser.prevNames) { if (output) output += ", "; output += targetUser.prevNames[i]; } if (output) this.sendReply('Previous names: '+output); for (var j=0; j<alts.length; j++) { var targetAlt = Users.get(alts[j]); if (!targetAlt.named && !targetAlt.connected) continue; this.sendReply('Alt: '+targetAlt.name); output = ''; for (var i in targetAlt.prevNames) { if (output) output += ", "; output += targetAlt.prevNames[i]; } if (output) this.sendReply('Previous names: '+output); } } if (config.groups[targetUser.group] && config.groups[targetUser.group].name) { this.sendReply('Group: ' + config.groups[targetUser.group].name + ' (' + targetUser.group + ')'); } if (targetUser.isSysop) { this.sendReply('(Pok\xE9mon Showdown System Operator)'); } if (targetUser.goldDev) { this.sendReply('(Gold Development Staff)'); } if (!targetUser.authenticated) { this.sendReply('(Unregistered)'); } if (!this.broadcasting && (user.can('ip', targetUser) || user === targetUser)) { var ips = Object.keys(targetUser.ips); this.sendReply('IP' + ((ips.length > 1) ? 's' : '') + ': ' + ips.join(', ')); } var output = 'In all rooms: '; var first = false; for (var i in targetUser.roomCount) { if (i === 'global' || Rooms.get(i).isPublic) continue; if (!first) output += ' | '; first = false; output += '<a href="/'+i+'" room="'+i+'">'+i+'</a>'; } this.sendReply('|raw|'+output); }, tiertest: function(target, room, user) { if (!this.canBroadcast()) return; var targetId = toId(target); var newTargets = Tools.dataSearch(target); if (newTargets && newTargets.length) { for (var i = 0; i < newTargets.length; i++) { var template = Tools.getTemplate(newTargets[i].species); return this.sendReplyBox("" + template.name + " is in the " + template.tier + " tier."); } } else { return this.sendReplyBox("No Pokemon named '" + target + "' was found."); } }, aotdtest: function (target, room, user) { if (room.id !== 'thestudio') return this.sendReply("This command can only be used in The Studio."); if (!target) { if (!this.canBroadcast()) return; this.sendReplyBox("The current Artist of the Day is: <b>" + Tools.escapeHTML(room.aotd) + "</b>"); return; } if (!this.canTalk()) return; if (target.length > 25) { return this.sendReply("This Artist\'s name is too long; it cannot exceed 25 characters."); } if (!this.can('ban', null, room)) return; room.aotd = target; Rooms.rooms.thestudio.addRaw( '<div class=\"broadcast-green\"><font size="2"><b>The Artist of the Day is now </font><b><font color="black" size="2">' + Tools.escapeHTML(target) + '</font></b><br />' + '(Set by ' + Tools.escapeHTML(user.name) + '.)<br />' + 'This Artist will be posted on our <a href="http://thepsstudioroom.weebly.com/artist-of-the-day.html">Artist of the Day page</a>.</div>' ); room.aotdOn = false; this.logModCommand("The Artist of the Day was changed to " + Tools.escapeHTML(target) + " by " + Tools.escapeHTML(user.name) + "."); }, ipsearch: function (target, room, user) { if (!this.can('rangeban')) return; var atLeastOne = false; this.sendReply("Users with IP " + target + ":"); for (var userid in Users.users) { var curUser = Users.users[userid]; if (curUser.latestIp === target) { this.sendReply((curUser.connected ? " + " : "-") + " " + curUser.name); atLeastOne = true; } } if (!atLeastOne) this.sendReply("No results found."); }, gdeclarered: 'gdeclare', gdeclaregreen: 'gdeclare', gdeclare: function(target, room, user, connection, cmd) { if (!target) return this.parse('/help gdeclare'); if (!this.can('lockdown')) return false; var roomName = (room.isPrivate)? 'a private room' : room.id; if (cmd === 'gdeclare'){ for (var id in Rooms.rooms) { if (id !== 'global') Rooms.rooms[id].addRaw('<div class="broadcast-blue"><b><font size=1><i>Global declare from '+roomName+'<br /></i></font size>'+target+'</b></div>'); } } if (cmd === 'gdeclarered'){ for (var id in Rooms.rooms) { if (id !== 'global') Rooms.rooms[id].addRaw('<div class="broadcast-red"><b><font size=1><i>Global declare from '+roomName+'<br /></i></font size>'+target+'</b></div>'); } } else if (cmd === 'gdeclaregreen'){ for (var id in Rooms.rooms) { if (id !== 'global') Rooms.rooms[id].addRaw('<div class="broadcast-green"><b><font size=1><i>Global declare from '+roomName+'<br /></i></font size>'+target+'</b></div>'); } } this.logEntry(user.name + ' used /gdeclare'); }, declaregreen: 'declarered', declarered: function(target, room, user, connection, cmd) { if (!target) return this.parse('/help declare'); if (!this.can('declare', null, room)) return false; if (!this.canTalk()) return; if (cmd === 'declarered'){ this.add('|raw|<div class="broadcast-red"><b>'+target+'</b></div>'); } else if (cmd === 'declaregreen'){ this.add('|raw|<div class="broadcast-green"><b>'+target+'</b></div>'); } this.logModCommand(user.name+' declared '+target); }, declaregreen: 'declarered', declarered: function(target, room, user, connection, cmd) { if (!target) return this.parse('/help declare'); if (!this.can('declare', null, room)) return false; if (!this.canTalk()) return; if (cmd === 'declarered'){ this.add('|raw|<div class="broadcast-red"><b>'+target+'</b></div>'); } else if (cmd === 'declaregreen'){ this.add('|raw|<div class="broadcast-green"><b>'+target+'</b></div>'); } this.logModCommand(user.name+' declared '+target); }, pdeclare: function(target, room, user, connection, cmd) { if (!target) return this.parse('/help declare'); if (!this.can('declare', null, room)) return false; if (!this.canTalk()) return; if (cmd === 'pdeclare'){ this.add('|raw|<div class="broadcast-purple"><b>'+target+'</b></div>'); } else if (cmd === 'pdeclare'){ this.add('|raw|<div class="broadcast-purple"><b>'+target+'</b></div>'); } this.logModCommand(user.name+' declared '+target); }, k: 'kick', aura: 'kick', kick: function(target, room, user){ if (!this.can('lock')) return false; if (!target) return this.sendReply('/help kick'); if (!this.canTalk()) return false; target = this.splitTarget(target); var targetUser = this.targetUser; if (!targetUser || !targetUser.connected) { return this.sendReply('User '+this.targetUsername+' not found.'); } if (!this.can('lock', targetUser, room)) return false; this.addModCommand(targetUser.name+' was kicked from the room by '+user.name+'.'); targetUser.popup('You were kicked from '+room.id+' by '+user.name+'.'); targetUser.leaveRoom(room.id); }, dm: 'daymute', daymute: function(target, room, user) { if (!target) return this.parse('/help daymute'); if (!this.canTalk()) return false; target = this.splitTarget(target); var targetUser = this.targetUser; if (!targetUser) { return this.sendReply('User '+this.targetUsername+' not found.'); } if (!this.can('mute', targetUser, room)) return false; if (((targetUser.mutedRooms[room.id] && (targetUser.muteDuration[room.id]||0) >= 50*60*1000) || targetUser.locked) && !target) { var problem = ' but was already '+(!targetUser.connected ? 'offline' : targetUser.locked ? 'locked' : 'muted'); return this.privateModCommand('('+targetUser.name+' would be muted by '+user.name+problem+'.)'); } targetUser.popup(user.name+' has muted you for 24 hours. '+target); this.addModCommand(''+targetUser.name+' was muted by '+user.name+' for 24 hours.' + (target ? " (" + target + ")" : "")); var alts = targetUser.getAlts(); if (alts.length) this.addModCommand(""+targetUser.name+"'s alts were also muted: "+alts.join(", ")); targetUser.mute(room.id, 24*60*60*1000, true); }, flogout: 'forcelogout', forcelogout: function(target, room, user) { if(!user.can('hotpatch')) return; if (!this.canTalk()) return false; if (!target) return this.sendReply('/forcelogout [username], [reason] OR /flogout [username], [reason] - You do not have to add a reason'); target = this.splitTarget(target); var targetUser = this.targetUser; if (!targetUser) { return this.sendReply('User '+this.targetUsername+' not found.'); } if (targetUser.can('hotpatch')) return this.sendReply('You cannot force logout another Admin - nice try. Chump.'); this.addModCommand(''+targetUser.name+' was forcibly logged out by '+user.name+'.' + (target ? " (" + target + ")" : "")); targetUser.resetName(); }, declaregreen: 'declarered', declarered: function(target, room, user, connection, cmd) { if (!target) return this.parse('/help declare'); if (!this.can('declare', null, room)) return false; if (!this.canTalk()) return; if (cmd === 'declarered'){ this.add('|raw|<div class="broadcast-red"><b>'+target+'</b></div>'); } else if (cmd === 'declaregreen'){ this.add('|raw|<div class="broadcast-green"><b>'+target+'</b></div>'); } this.logModCommand(user.name+' declared '+target); }, gdeclarered: 'gdeclare', gdeclaregreen: 'gdeclare', gdeclare: function(target, room, user, connection, cmd) { if (!target) return this.parse('/help gdeclare'); if (!this.can('lockdown')) return false; var roomName = (room.isPrivate)? 'a private room' : room.id; if (cmd === 'gdeclare'){ for (var id in Rooms.rooms) { if (id !== 'global') Rooms.rooms[id].addRaw('<div class="broadcast-blue"><b><font size=1><i>Global declare from '+roomName+'<br /></i></font size>'+target+'</b></div>'); } } if (cmd === 'gdeclarered'){ for (var id in Rooms.rooms) { if (id !== 'global') Rooms.rooms[id].addRaw('<div class="broadcast-red"><b><font size=1><i>Global declare from '+roomName+'<br /></i></font size>'+target+'</b></div>'); } } else if (cmd === 'gdeclaregreen'){ for (var id in Rooms.rooms) { if (id !== 'global') Rooms.rooms[id].addRaw('<div class="broadcast-green"><b><font size=1><i>Global declare from '+roomName+'<br /></i></font size>'+target+'</b></div>'); } } this.logModCommand(user.name+' globally declared '+target); }, sd: 'declaremod', staffdeclare: 'declaremod', modmsg: 'declaremod', moddeclare: 'declaremod', declaremod: function(target, room, user) { if (!target) return this.sendReply('/declaremod [message] - Also /moddeclare and /modmsg'); if (!this.can('declare', null, room)) return false; if (!this.canTalk()) return; this.privateModCommand('|raw|<div class="broadcast-red"><b><font size=1><i>Private Auth (Driver +) declare from '+user.name+'<br /></i></font size>'+target+'</b></div>'); this.logModCommand(user.name+' mod declared '+target); }, /********************************************************* * Shortcuts *********************************************************/ invite: function (target, room, user) { target = this.splitTarget(target); if (!this.targetUser) { return this.sendReply("User " + this.targetUsername + " not found."); } var targetRoom = (target ? Rooms.search(target) : room); if (!targetRoom) { return this.sendReply("Room " + target + " not found."); } return this.parse('/msg ' + this.targetUsername + ', /invite ' + targetRoom.id); }, /********************************************************* * Informational commands *********************************************************/ pstats: 'data', stats: 'data', dex: 'data', pokedex: 'data', details: 'data', dt: 'data', data: function (target, room, user, connection, cmd) { if (!this.canBroadcast()) return; var buffer = ''; var targetId = toId(target); if (targetId === '' + parseInt(targetId)) { for (var p in Tools.data.Pokedex) { var pokemon = Tools.getTemplate(p); if (pokemon.num === parseInt(target)) { target = pokemon.species; targetId = pokemon.id; break; } } } var newTargets = Tools.dataSearch(target); var showDetails = (cmd === 'dt' || cmd === 'details'); if (newTargets && newTargets.length) { for (var i = 0; i < newTargets.length; ++i) { if (newTargets[i].id !== targetId && !Tools.data.Aliases[targetId] && !i) { buffer = "No Pokemon, item, move, ability or nature named '" + target + "' was found. Showing the data of '" + newTargets[0].name + "' instead.\n"; } if (newTargets[i].searchType === 'nature') { buffer += "" + newTargets[i].name + " nature: "; if (newTargets[i].plus) { var statNames = {'atk': "Attack", 'def': "Defense", 'spa': "Special Attack", 'spd': "Special Defense", 'spe': "Speed"}; buffer += "+10% " + statNames[newTargets[i].plus] + ", -10% " + statNames[newTargets[i].minus] + "."; } else { buffer += "No effect."; } return this.sendReply(buffer); } else { buffer += '|c|~|/data-' + newTargets[i].searchType + ' ' + newTargets[i].name + '\n'; } } } else { return this.sendReply("No Pokemon, item, move, ability or nature named '" + target + "' was found. (Check your spelling?)"); } if (showDetails) { var details; if (newTargets[0].searchType === 'pokemon') { var pokemon = Tools.getTemplate(newTargets[0].name); var weighthit = 20; if (pokemon.weightkg >= 200) { weighthit = 120; } else if (pokemon.weightkg >= 100) { weighthit = 100; } else if (pokemon.weightkg >= 50) { weighthit = 80; } else if (pokemon.weightkg >= 25) { weighthit = 60; } else if (pokemon.weightkg >= 10) { weighthit = 40; } details = { "Dex#": pokemon.num, "Height": pokemon.heightm + " m", "Weight": pokemon.weightkg + " kg <em>(" + weighthit + " BP)</em>", "Dex Colour": pokemon.color, "Egg Group(s)": pokemon.eggGroups.join(", ") }; if (!pokemon.evos.length) { details["<font color=#585858>Does Not Evolve</font>"] = ""; // this line exists on main } else { details["Evolution"] = pokemon.evos.map(function (evo) { evo = Tools.getTemplate(evo); return evo.name + " (" + evo.evoLevel + ")"; }).join(", "); } } else if (newTargets[0].searchType === 'move') { var move = Tools.getMove(newTargets[0].name); details = { "Priority": move.priority }; if (move.secondary || move.secondaries) details["<font color=black>&#10003; Secondary Effect</font>"] = ""; if (move.isContact) details["<font color=black>&#10003; Contact</font>"] = ""; if (move.isSoundBased) details["<font color=black>&#10003; Sound</font>"] = ""; if (move.isBullet) details["<font color=black>&#10003; Bullet</font>"] = ""; if (move.isPulseMove) details["<font color=black>&#10003; Pulse</font>"] = ""; details["Target"] = { 'normal': "Adjacent Pokemon", 'self': "Self", 'adjacentAlly': "Single Ally", 'allAdjacentFoes': "Adjacent Foes", 'foeSide': "All Foes", 'allySide': "All Allies", 'allAdjacent': "All Adjacent Pokemon", 'any': "Any Pokemon", 'all': "All Pokemon" }[move.target] || "Unknown"; } else if (newTargets[0].searchType === 'item') { var item = Tools.getItem(newTargets[0].name); details = {}; if (item.fling) { details["Fling Base Power"] = item.fling.basePower; if (item.fling.status) details["Fling Effect"] = item.fling.status; if (item.fling.volatileStatus) details["Fling Effect"] = item.fling.volatileStatus; if (item.isBerry) details["Fling Effect"] = "Activates effect of berry on target."; if (item.id === 'whiteherb') details["Fling Effect"] = "Removes all negative stat levels on the target."; if (item.id === 'mentalherb') details["Fling Effect"] = "Removes the effects of infatuation, Taunt, Encore, Torment, Disable, and Cursed Body on the target."; } if (!item.fling) details["Fling"] = "This item cannot be used with Fling"; if (item.naturalGift) { details["Natural Gift Type"] = item.naturalGift.type; details["Natural Gift BP"] = item.naturalGift.basePower; } } else { details = {}; } buffer += '|raw|<font size="1">' + Object.keys(details).map(function (detail) { return '<font color=#585858>' + detail + (details[detail] !== '' ? ':</font> ' + details[detail] : '</font>'); }).join("&nbsp;|&ThickSpace;") + '</font>'; } this.sendReply(buffer); }, ds: 'dexsearch', dsearch: 'dexsearch', dexsearch: function (target, room, user) { if (!this.canBroadcast()) return; if (!target) return this.parse('/help dexsearch'); var targets = target.split(','); var searches = {}; var allTiers = {'uber':1, 'ou':1, 'uu':1, 'lc':1, 'cap':1, 'bl':1, 'bl2':1, 'ru':1, 'bl3':1, 'nu':1, 'pu':1}; var allColours = {'green':1, 'red':1, 'blue':1, 'white':1, 'brown':1, 'yellow':1, 'purple':1, 'pink':1, 'gray':1, 'black':1}; var showAll = false; var megaSearch = null; var feSearch = null; // search for fully evolved pokemon only var recoverySearch = null; var output = 10; for (var i in targets) { var isNotSearch = false; target = targets[i].trim().toLowerCase(); if (target.slice(0, 1) === '!') { isNotSearch = true; target = target.slice(1); } var targetAbility = Tools.getAbility(targets[i]); if (targetAbility.exists) { if (!searches['ability']) searches['ability'] = {}; if (Object.count(searches['ability'], true) === 1 && !isNotSearch) return this.sendReplyBox("Specify only one ability."); if ((searches['ability'][targetAbility.name] && isNotSearch) || (searches['ability'][targetAbility.name] === false && !isNotSearch)) return this.sendReplyBox("A search cannot both exclude and include an ability."); searches['ability'][targetAbility.name] = !isNotSearch; continue; } if (target in allTiers) { if (!searches['tier']) searches['tier'] = {}; if ((searches['tier'][target] && isNotSearch) || (searches['tier'][target] === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include a tier.'); searches['tier'][target] = !isNotSearch; continue; } if (target in allColours) { if (!searches['color']) searches['color'] = {}; if ((searches['color'][target] && isNotSearch) || (searches['color'][target] === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include a color.'); searches['color'][target] = !isNotSearch; continue; } var targetInt = parseInt(target); if (0 < targetInt && targetInt < 7) { if (!searches['gen']) searches['gen'] = {}; if ((searches['gen'][target] && isNotSearch) || (searches['gen'][target] === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include a generation.'); searches['gen'][target] = !isNotSearch; continue; } if (target === 'all') { if (this.broadcasting) { return this.sendReplyBox("A search with the parameter 'all' cannot be broadcast."); } showAll = true; continue; } if (target === 'megas' || target === 'mega') { if ((megaSearch && isNotSearch) || (megaSearch === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include Mega Evolutions.'); megaSearch = !isNotSearch; continue; } if (target === 'fe' || target === 'fullyevolved' || target === 'nfe' || target === 'notfullyevolved') { if (target === 'nfe' || target === 'notfullyevolved') isNotSearch = !isNotSearch; if ((feSearch && isNotSearch) || (feSearch === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include fully evolved Pokémon.'); feSearch = !isNotSearch; continue; } if (target === 'recovery') { if ((recoverySearch && isNotSearch) || (recoverySearch === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and recovery moves.'); if (!searches['recovery']) searches['recovery'] = {}; recoverySearch = !isNotSearch; continue; } var targetMove = Tools.getMove(target); if (targetMove.exists) { if (!searches['moves']) searches['moves'] = {}; if (Object.count(searches['moves'], true) === 4 && !isNotSearch) return this.sendReplyBox("Specify a maximum of 4 moves."); if ((searches['moves'][targetMove.name] && isNotSearch) || (searches['moves'][targetMove.name] === false && !isNotSearch)) return this.sendReplyBox("A search cannot both exclude and include a move."); searches['moves'][targetMove.name] = !isNotSearch; continue; } if (target.indexOf(' type') > -1) { target = target.charAt(0).toUpperCase() + target.slice(1, target.indexOf(' type')); if (target in Tools.data.TypeChart) { if (!searches['types']) searches['types'] = {}; if (Object.count(searches['types'], true) === 2 && !isNotSearch) return this.sendReplyBox("Specify a maximum of two types."); if ((searches['types'][target] && isNotSearch) || (searches['types'][target] === false && !isNotSearch)) return this.sendReplyBox("A search cannot both exclude and include a type."); searches['types'][target] = !isNotSearch; continue; } } return this.sendReplyBox("'" + Tools.escapeHTML(target) + "' could not be found in any of the search categories."); } if (showAll && Object.size(searches) === 0 && megaSearch === null && feSearch === null) return this.sendReplyBox("No search parameters other than 'all' were found. Try '/help dexsearch' for more information on this command."); var dex = {}; for (var pokemon in Tools.data.Pokedex) { var template = Tools.getTemplate(pokemon); var megaSearchResult = (megaSearch === null || (megaSearch === true && template.isMega) || (megaSearch === false && !template.isMega)); var feSearchResult = (feSearch === null || (feSearch === true && !template.evos.length) || (feSearch === false && template.evos.length)); if (template.tier !== 'Unreleased' && template.tier !== 'Illegal' && (template.tier !== 'CAP' || (searches['tier'] && searches['tier']['cap'])) && megaSearchResult && feSearchResult) { dex[pokemon] = template; } } for (var search in {'moves':1, 'recovery':1, 'types':1, 'ability':1, 'tier':1, 'gen':1, 'color':1}) { if (!searches[search]) continue; switch (search) { case 'types': for (var mon in dex) { if (Object.count(searches[search], true) === 2) { if (!(searches[search][dex[mon].types[0]]) || !(searches[search][dex[mon].types[1]])) delete dex[mon]; } else { if (searches[search][dex[mon].types[0]] === false || searches[search][dex[mon].types[1]] === false || (Object.count(searches[search], true) > 0 && (!(searches[search][dex[mon].types[0]]) && !(searches[search][dex[mon].types[1]])))) delete dex[mon]; } } break; case 'tier': for (var mon in dex) { if ('lc' in searches[search]) { // some LC legal Pokemon are stored in other tiers (Ferroseed/Murkrow etc) // this checks for LC legality using the going criteria, instead of dex[mon].tier var isLC = (dex[mon].evos && dex[mon].evos.length > 0) && !dex[mon].prevo && Tools.data.Formats['lc'].banlist.indexOf(dex[mon].species) === -1; if ((searches[search]['lc'] && !isLC) || (!searches[search]['lc'] && isLC)) { delete dex[mon]; continue; } } if (searches[search][String(dex[mon][search]).toLowerCase()] === false) { delete dex[mon]; } else if (Object.count(searches[search], true) > 0 && !searches[search][String(dex[mon][search]).toLowerCase()]) delete dex[mon]; } break; case 'gen': case 'color': for (var mon in dex) { if (searches[search][String(dex[mon][search]).toLowerCase()] === false) { delete dex[mon]; } else if (Object.count(searches[search], true) > 0 && !searches[search][String(dex[mon][search]).toLowerCase()]) delete dex[mon]; } break; case 'ability': for (var mon in dex) { for (var ability in searches[search]) { var needsAbility = searches[search][ability]; var hasAbility = Object.count(dex[mon].abilities, ability) > 0; if (hasAbility !== needsAbility) { delete dex[mon]; break; } } } break; case 'moves': for (var mon in dex) { var template = Tools.getTemplate(dex[mon].id); if (!template.learnset) template = Tools.getTemplate(template.baseSpecies); if (!template.learnset) continue; for (var i in searches[search]) { var move = Tools.getMove(i); if (!move.exists) return this.sendReplyBox("'" + move + "' is not a known move."); var prevoTemp = Tools.getTemplate(template.id); while (prevoTemp.prevo && prevoTemp.learnset && !(prevoTemp.learnset[move.id])) { prevoTemp = Tools.getTemplate(prevoTemp.prevo); } var canLearn = (prevoTemp.learnset.sketch && !(move.id in {'chatter':1, 'struggle':1, 'magikarpsrevenge':1})) || prevoTemp.learnset[move.id]; if ((!canLearn && searches[search][i]) || (searches[search][i] === false && canLearn)) delete dex[mon]; } } break; case 'recovery': for (var mon in dex) { var template = Tools.getTemplate(dex[mon].id); if (!template.learnset) template = Tools.getTemplate(template.baseSpecies); if (!template.learnset) continue; var recoveryMoves = ["recover", "roost", "moonlight", "morningsun", "synthesis", "milkdrink", "slackoff", "softboiled", "wish", "healorder"]; var canLearn = false; for (var i = 0; i < recoveryMoves.length; i++) { var prevoTemp = Tools.getTemplate(template.id); while (prevoTemp.prevo && prevoTemp.learnset && !(prevoTemp.learnset[recoveryMoves[i]])) { prevoTemp = Tools.getTemplate(prevoTemp.prevo); } canLearn = (prevoTemp.learnset.sketch) || prevoTemp.learnset[recoveryMoves[i]]; if (canLearn) break; } if ((!canLearn && searches[search]) || (searches[search] === false && canLearn)) delete dex[mon]; } break; default: return this.sendReplyBox("Something broke! PM TalkTakesTime here or on the Smogon forums with the command you tried."); } } var results = Object.keys(dex).map(function (speciesid) {return dex[speciesid].species;}); results = results.filter(function (species) { var template = Tools.getTemplate(species); return !(species !== template.baseSpecies && results.indexOf(template.baseSpecies) > -1); }); var resultsStr = ""; if (results.length > 0) { if (showAll || results.length <= output) { results.sort(); resultsStr = results.join(", "); } else { results.randomize(); resultsStr = results.slice(0, 10).join(", ") + ", and " + string(results.length - output) + " more. Redo the search with 'all' as a search parameter to show all results."; } } else { resultsStr = "No Pokémon found."; } return this.sendReplyBox(resultsStr); }, learnset: 'learn', learnall: 'learn', learn5: 'learn', g6learn: 'learn', learn: function (target, room, user, connection, cmd) { if (!target) return this.parse('/help learn'); if (!this.canBroadcast()) return; var lsetData = {set:{}}; var targets = target.split(','); var template = Tools.getTemplate(targets[0]); var move = {}; var problem; var all = (cmd === 'learnall'); if (cmd === 'learn5') lsetData.set.level = 5; if (cmd === 'g6learn') lsetData.format = {noPokebank: true}; if (!template.exists) { return this.sendReply("Pokemon '" + template.id + "' not found."); } if (targets.length < 2) { return this.sendReply("You must specify at least one move."); } for (var i = 1, len = targets.length; i < len; ++i) { move = Tools.getMove(targets[i]); if (!move.exists) { return this.sendReply("Move '" + move.id + "' not found."); } problem = TeamValidator.checkLearnsetSync(null, move, template, lsetData); if (problem) break; } var buffer = template.name + (problem ? " <span class=\"message-learn-cannotlearn\">can't</span> learn " : " <span class=\"message-learn-canlearn\">can</span> learn ") + (targets.length > 2 ? "these moves" : move.name); if (!problem) { var sourceNames = {E:"egg", S:"event", D:"dream world"}; if (lsetData.sources || lsetData.sourcesBefore) buffer += " only when obtained from:<ul class=\"message-learn-list\">"; if (lsetData.sources) { var sources = lsetData.sources.sort(); var prevSource; var prevSourceType; var prevSourceCount = 0; for (var i = 0, len = sources.length; i < len; ++i) { var source = sources[i]; if (source.substr(0, 2) === prevSourceType) { if (prevSourceCount < 0) { buffer += ": " + source.substr(2); } else if (all || prevSourceCount < 3) { buffer += ", " + source.substr(2); } else if (prevSourceCount === 3) { buffer += ", ..."; } ++prevSourceCount; continue; } prevSourceType = source.substr(0, 2); prevSourceCount = source.substr(2) ? 0 : -1; buffer += "<li>gen " + source.substr(0, 1) + " " + sourceNames[source.substr(1, 1)]; if (prevSourceType === '5E' && template.maleOnlyHidden) buffer += " (cannot have hidden ability)"; if (source.substr(2)) buffer += ": " + source.substr(2); } } if (lsetData.sourcesBefore) buffer += "<li>any generation before " + (lsetData.sourcesBefore + 1); buffer += "</ul>"; } this.sendReplyBox(buffer); }, weak: 'weakness', resist: 'weakness', weakness: function (target, room, user) { if (!this.canBroadcast()) return; var targets = target.split(/[ ,\/]/); var pokemon = Tools.getTemplate(target); var type1 = Tools.getType(targets[0]); var type2 = Tools.getType(targets[1]); if (pokemon.exists) { target = pokemon.species; } else if (type1.exists && type2.exists) { pokemon = {types: [type1.id, type2.id]}; target = type1.id + "/" + type2.id; } else if (type1.exists) { pokemon = {types: [type1.id]}; target = type1.id; } else { return this.sendReplyBox("" + Tools.escapeHTML(target) + " isn't a recognized type or pokemon."); } var weaknesses = []; var resistances = []; var immunities = []; Object.keys(Tools.data.TypeChart).forEach(function (type) { var notImmune = Tools.getImmunity(type, pokemon); if (notImmune) { var typeMod = Tools.getEffectiveness(type, pokemon); switch (typeMod) { case 1: weaknesses.push(type); break; case 2: weaknesses.push("<b>" + type + "</b>"); break; case -1: resistances.push(type); break; case -2: resistances.push("<b>" + type + "</b>"); break; } } else { immunities.push(type); } }); var buffer = []; buffer.push(pokemon.exists ? "" + target + ' (ignoring abilities):' : '' + target + ':'); buffer.push('<span class=\"message-effect-weak\">Weaknesses</span>: ' + (weaknesses.join(', ') || 'None')); buffer.push('<span class=\"message-effect-resist\">Resistances</span>: ' + (resistances.join(', ') || 'None')); buffer.push('<span class=\"message-effect-immune\">Immunities</span>: ' + (immunities.join(', ') || 'None')); this.sendReplyBox(buffer.join('<br>')); }, eff: 'effectiveness', type: 'effectiveness', matchup: 'effectiveness', effectiveness: function (target, room, user) { var targets = target.split(/[,/]/).slice(0, 2); if (targets.length !== 2) return this.sendReply("Attacker and defender must be separated with a comma."); var searchMethods = {'getType':1, 'getMove':1, 'getTemplate':1}; var sourceMethods = {'getType':1, 'getMove':1}; var targetMethods = {'getType':1, 'getTemplate':1}; var source; var defender; var foundData; var atkName; var defName; for (var i = 0; i < 2; ++i) { var method; for (method in searchMethods) { foundData = Tools[method](targets[i]); if (foundData.exists) break; } if (!foundData.exists) return this.parse('/help effectiveness'); if (!source && method in sourceMethods) { if (foundData.type) { source = foundData; atkName = foundData.name; } else { source = foundData.id; atkName = foundData.id; } searchMethods = targetMethods; } else if (!defender && method in targetMethods) { if (foundData.types) { defender = foundData; defName = foundData.species + " (not counting abilities)"; } else { defender = {types: [foundData.id]}; defName = foundData.id; } searchMethods = sourceMethods; } } if (!this.canBroadcast()) return; var factor = 0; if (Tools.getImmunity(source.type || source, defender)) { if (source.effectType !== 'Move' || source.basePower || source.basePowerCallback) { factor = Math.pow(2, Tools.getEffectiveness(source, defender)); } else { factor = 1; } } this.sendReplyBox("" + atkName + " is " + factor + "x effective against " + defName + "."); }, uptime: (function(){ function formatUptime(uptime) { if (uptime > 24*60*60) { var uptimeText = ""; var uptimeDays = Math.floor(uptime/(24*60*60)); uptimeText = uptimeDays + " " + (uptimeDays == 1 ? "day" : "days"); var uptimeHours = Math.floor(uptime/(60*60)) - uptimeDays*24; if (uptimeHours) uptimeText += ", " + uptimeHours + " " + (uptimeHours == 1 ? "hour" : "hours"); return uptimeText; } else { return uptime.seconds().duration(); } } return function(target, room, user) { if (!this.canBroadcast()) return; var uptime = process.uptime(); this.sendReplyBox("Uptime: <b>" + formatUptime(uptime) + "</b>" + (global.uptimeRecord ? "<br /><font color=\"green\">Record: <b>" + formatUptime(global.uptimeRecord) + "</b></font>" : "")); }; })(), groups: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox( "+ <b>Voice</b> - They can use ! commands like !groups, and talk during moderated chat<br />" + "% <b>Driver</b> - The above, and they can mute. Global % can also lock users and check for alts<br />" + "@ <b>Moderator</b> - The above, and they can ban users<br />" + "&amp; <b>Leader</b> - The above, and they can promote to moderator and force ties<br />" + "# <b>Room Owner</b> - They are leaders of the room and can almost totally control it<br />" + "~ <b>Administrator</b> - They can do anything, like change what this message says" ); }, staff: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('The staff forums can be found <a href="https://groups.google.com/forum/#!forum/gold-staff">here</a>.'); }, whosgotthemoneyz: 'richestuser', richestuser: function(target, room, user) { if (!this.canBroadcast()) return; var data = fs.readFileSync('config/money.csv','utf8'); var row = (''+data).split("\n"); var userids = {id:[],money:[]}; var highest = {id:[],money:[]}; var size = 0; var amounts = []; for (var i = row.length; i > -1; i--) { if (!row[i]) continue; var parts = row[i].split(","); userids.id[i] = parts[0]; userids.money[i] = Number(parts[1]); size++; if (isNaN(parts[1]) || parts[1] === 'Infinity') userids.money[i] = 0; } for (var i=0; i<10;i++) { var tempHighest = 0; for (var x=0;x<size;x++) { if (userids.money[x] > tempHighest) tempHighest = userids.money[x]; } for (var x=0;x<size;x++) { var found = false; if (userids.money[x] === tempHighest && !found) { highest.id[i] = userids.id[x]; highest.money[i] = userids.money[x]; userids.id[x]; userids.money[x] = 0; found = true; } } } return this.sendReplyBox('<b>The richest users are:</b>' + '<br>1. ' + highest.id[0] + ': ' + highest.money[0] + '<br>2. ' + highest.id[1] + ': ' + highest.money[1] + '<br>3. ' + highest.id[2] + ': ' + highest.money[2] + '<br>4. ' + highest.id[3] + ': ' + highest.money[3] + '<br>5. ' + highest.id[4] + ': ' + highest.money[4] + '<br>6. ' + highest.id[5] + ': ' + highest.money[5] + '<br>7. ' + highest.id[6] + ': ' + highest.money[6] + '<br>8. ' + highest.id[7] + ': ' + highest.money[7] + '<br>9. ' + highest.id[8] + ': ' + highest.money[8] + '<br>10. ' + highest.id[9] + ': ' + highest.money[9]); }, pus: 'pmupperstaff', pmupperstaff: function (target, room, user) { if (!target) return this.sendReply('/pmupperstaff [message] - Sends a PM to every upper staff'); if (!this.can('pban')) return false; for (var u in Users.users) { if (Users.users[u].group == '~' || Users.users[u].group == '&') { Users.users[u].send('|pm|~Upper Staff PM|'+Users.users[u].group+Users.users[u].name+'| '+target+' (PM from '+user.name+')'); } } }, staff: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox("<a href=\"https://www.smogon.com/sim/staff_list\">Pokemon Showdown Staff List</a>"); }, beno: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://fc06.deviantart.net/fs29/f/2008/092/4/c/NOT_MY_MUDKIP_by_joeywaii.jpg" width="250">' + '<img src="http://images.fanpop.com/images/image_uploads/Mudkip-mudkip-marshtomp-and-swampert-432906_461_421.jpg" width="250" height="240""><br />' + '<b>Ace: </b>That sad moment when life gave you lemons but you\'re to lazy to make the lemonade.<br />' + '<button name="send" value="/transferbucks elitefourbeno, 5">Donate 5 bucks for a cookie</button></center>'); }, sand2: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/0dwzNX7.gif"><br />' + '<img src="http://media.giphy.com/media/FvtOorPNV09Og/giphy.gif" width="270" height="200">' + '<img src="http://media.giphy.com/media/O7UKZP7lMuZm8/giphy.gif" width="270" height="200"><br />' + 'I don\'t like it, the dark circles under my eyes will come back and I don\'t know how to deal with the dark circles</center>'); }, showtan: function (target, room, user) { if (room.id !== 'showderp') return this.sendReply("The command '/showtan' was unrecognized. To send a message starting with '/showtan', type '//showtan'."); if (!this.can('modchat', null, room)) return; target = this.splitTarget(target); if (!this.targetUser) return this.sendReply("User not found"); if (!room.users[this.targetUser.userid]) return this.sendReply("Not a showderper"); this.targetUser.avatar = '#showtan'; room.add("" + user.name + " applied showtan to affected area of " + this.targetUser.name); }, showtan: function (target, room, user) { if (room.id !== 'showderp') return this.sendReply("The command '/showtan' was unrecognized. To send a message starting with '/showtan', type '//showtan'."); if (!this.can('modchat', null, room)) return; target = this.splitTarget(target); if (!this.targetUser) return this.sendReply("User not found"); if (!room.users[this.targetUser.userid]) return this.sendReply("Not a showderper"); this.targetUser.avatar = '#showtan'; room.add("" + user.name + " applied showtan to affected area of " + this.targetUser.name); }, jlp: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/cmacyYX.gif" width="300">' + '<img src="http://i.imgur.com/J0B59PM.gif" height="200"><br />' + '<img src="http://i.imgur.com/u5Wd4Uf.gif"></center>'); }, nollid: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/0dwzNX7.gif"><br />' + '<img src="http://25.media.tumblr.com/f58fe4414fc7e71aa3e97b1da0d06c9b/tumblr_mf3kcgAp2k1r3ifxzo1_500.gif" width="260" height="200">' + '<img src="http://media.tumblr.com/50996a160cc5d34905ff35da5821d323/tumblr_inline_n5jcpzJd4p1suiunx.gif" width="260" height="200"><br />' + 'Thumbtacks in my shoes would stick into my feet whenever I tried to walk. It would hurt. I don\'t think I could deal with that really.</center>'); }, tesarand: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><b><font size="6" color="purple">Tesarand</b></font><br />' + '<img src="http://www.bonappetit.com/wp-content/uploads/2013/03/james-deen-646.jpg" height="200" width="300"><br />' + '<b>Ace: Dragonite<br />' + '"It tastes like glitter.... Rad.”</b><br></center>'); }, shrew: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/0dwzNX7.gif"><br />' + '<img src="http://i.imgur.com/tMGx5fT.gif" width="280" height="200"><br />' + '<img src="http://media.giphy.com/media/BPmdagBjYS6sM/giphy.gif" width="280" height="200"><br />' + 'I bet dead people are easier to get along with.</center>'); }, dildo: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/KpRmFDT.gif"><br />' + '<img src="http://i.imgur.com/4FwBKa4.gif" width="270">' + '<img src="http://i.imgur.com/JG2UXZd.gif" width="270"><br />' + 'The doors only open one way. They open inward.</center>'); }, cap: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox( "An introduction to the Create-A-Pokemon project:<br />" + "- <a href=\"https://www.smogon.com/cap/\">CAP project website and description</a><br />" + "- <a href=\"https://www.smogon.com/forums/showthread.php?t=48782\">What Pokemon have been made?</a><br />" + "- <a href=\"https://www.smogon.com/forums/forums/311\">Talk about the metagame here</a><br />" + "- <a href=\"https://www.smogon.com/forums/threads/3512318/#post-5594694\">Sample XY CAP teams</a>" ); }, hrey: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/RSOIh2j.gif"><br />' + '<img src="http://i.imgur.com/EsfjH9A.gif"><br />' + 'if we legalize pot, METH and THE MOLLYS will be legalized shortly after #420NO</center>'); }, shrewed: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/3scS0w5.gif"><br />' + '<img src="http://i.imgur.com/TS5dYjU.gif" width="270" height="160">' + '<img src="http://i.imgur.com/Dp5P3Bu.gif" width="270" height="160"><br />' + 'There are stars and planets floating around me. I don\'t think I can handle astronomy right now.</center>'); }, fork: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/HrDUGmr.png" width="75" height="100">'); }, dillon: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/PNy1HEf.gif"><br />' + '<img src="http://media.tumblr.com/tumblr_lz1xhpgIcY1qbnaro.gif" width="270">' + '<img src="http://img4.wikia.nocookie.net/__cb20130826213452/powerlisting/images/3/3a/Shadow_Dragon%27s_Roar.gif" width="270"><br />' + 'The loneliest people are the kindest. The saddest people smile the brightest. The most damaged people are the wisest. All because they don\'t wish to see anyone else suffer the way they did.</center>'); }, supersonic: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://img3.wikia.nocookie.net/__cb20120528125001/sonic/images/f/fc/Hyper_sonic.gif"><br />' + 'Gotta go fast much?</center>'); }, terlor: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/EEcZ4J2.png" width="350"><br />' + '<img src="http://i.imgur.com/bjVsAsj.png"><br />' + '"Why problem make when you no problem have you dont want to make."</center>'); }, saago: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/v3wWa5Z.jpg"><br />' + 'Everything you\'ve ever wanted is on the other side of fear.</center>'); }, sexykricketune: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/VPcZ1rC.png"><br />' + '<img src="https://fbcdn-sphotos-h-a.akamaihd.net/hphotos-ak-xpa1/v/t34.0-12/10537833_1479515712290994_1126670309_n.jpg?oh=52eb7d293765697c3c9e0a6ee235dd7d&oe=53BD3B02&__gda__=1404931411_57a9e1bbf14ec5949be27acfae62bf5f" width="500"><br />' + 'What, were you expecting something?</center>'); }, shikuthezorua: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://th01.deviantart.net/fs70/150/i/2013/147/5/1/zorua_by_andreehxd-d66umkw.png"><br />' + 'I may be cute, but I could make you fall off a cliff without anyone seeing it.</center>'); }, stone: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="https://i.imgur.com/DPy0OdR.gif" width="500"><br />' + '<img src="http://pldh.net/media/pokemon/gen6/xy-animated-shiny/376.gif"><br />' + '<b><font color="gold">Ace: Metagross</b></font><br />' + '<font color="gold">The secret to winning is to open your heart to pokemon and connect them to show how much you love your pokemon. Forcing them to attack every single time makes them lose energy & lose trust in you. So loving your pokemon and treating it well</font></center>'); }, dsuc: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><b><Font color="#FF0000">D</Font><Font color="#FF6000">e</Font><Font color="#FFC000">m</Font><Font color="#FFff00">o</Font><Font color="#9Fff00">n</Font><Font color="#3Fff00">i</Font><Font color="#00ff00">c</Font> ' + '<Font color="#00ffC0">S</Font><Font color="#00ffff">u</Font><Font color="#00C0ff">c</Font><Font color="#0060ff">c</Font><Font color="#0000ff">u</Font><Font color="#3F00ff">b</Font><Font color="#9F00ff">u</Font><Font color="#FF00ff">s</Font></b><br />' + '<img src="http://fc06.deviantart.net/fs70/i/2011/139/d/1/dcp_succubus_class_by_black_cat_mew-d3gqhbi.png" width="150"><br />' + 'Won\'t you be my pet?'); }, jacktr: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/X8Qshnz.gif"><br />' + 'With my bare hands I took back my life, now I\'ll take yours'); }, goal: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://cdn.bulbagarden.net/upload/thumb/4/47/181Ampharos.png/250px-181Ampharos.png">' + '<img src="http://lucien0maverick.files.wordpress.com/2014/05/tails-prower.png" width="200"><br />' + 'The Ultimate Team Combo</center>'); }, tailz: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/qO72kmo.png"><br />' + '<img src="http://37.media.tumblr.com/cc5c32483f12ae8866fda48d084f3861/tumblr_mww5peDTd71qkwzzdo1_400.gif"><br />' + '<i>Play Time Is Ogre</i>'); }, silver: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://img3.wikia.nocookie.net/__cb20091211143347/sonic/images/thumb/5/5d/Super_silver_final.png/150px-Super_silver_final.png"><br />' + '<img src="http://img1.wikia.nocookie.net/__cb20111024112339/sonic/images/thumb/3/34/Sonic_Channel_-_Silver_The_Hedgehog_2011.png/120px-Sonic_Channel_-_Silver_The_Hedgehog_2011.png"><br />' + 'Ace: Its no use!<br />'); }, gene: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/NO1PFB2.png"><br />' + '<img src="http://static2.wikia.nocookie.net/__cb20131130005232/bleedmancomics/images/6/66/Klefki_XY.gif"><br />' + '<b><font color="red">Ace:</b> Monopoly</font><br />' + '<font color="purple"> Romanticism is the expression of man\'s urge to rise above reason and common sense, just as rationalism is the expression of his urge to rise above theology and ion. Riot\'s suck, I love noodles.</font></center>'); }, hag: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://fc06.deviantart.net/fs70/f/2014/243/b/f/godzilla_vs_smaug_by_rumper1-d7xeyzt.png" width=500 height=500><br />' + 'What my battles are like</center>'); }, wrath: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/csloC44.gif"><br />' + '<img src="http://i.imgur.com/GS0kfMW.png"><br />' + 'No being an asshat. Asshats will face the Wrath of Espurr.</center>'); }, windy: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/CwmuZVJ.png"><br />' + '<img src="http://i.imgur.com/qOMMI3O.gif"><br />' + 'Show Your Victory!</center>'); }, coolasian: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/HbZN3Jm.png"><br />' + '<img src="http://i.imgur.com/PxPKnUs.jpg"><br />' + 'Scavenge. Slay. Survive.</center>'); }, aphrodisia: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/7SAR6FI.png"><br />' + '<img src="http://img2.wikia.nocookie.net/__cb20140319085812/pokemon/images/7/72/Pikachu_XY.gif"><br />' + 'Ace: Crumbster<br />' + '<font color=yellow> <b>If you want to find the secrets of the universe, think in terms of energy, frequency and vibration.</b></font></center>'); }, solox: 'solstice', equinox: 'solstice', solstice: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/6WcNxO9.gif">' + '<img src="http://i.imgur.com/vAsLJda.png"><br />' + '<img src="http://i.imgur.com/FnAsxKa.png"><br />' + 'Is what I\'ve done too much to take,<br />' + 'Or are you scared of being nothing?</center>'); }, typhozzz: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://th08.deviantart.net/fs70/PRE/i/2011/111/e/5/typhlosion_by_sharkjaw-d3ehtqh.jpg" height="100" width="100">' + '<img src="http://i.imgur.com/eDS32pU.gif">' + '<img src="http://i.imgur.com/UTfUkBW.png"><br />' + '<b>Ace: <font color="red"> Typhlosion</font></b><br />' + 'There ain\'t a soul or a person or thing that can stop me :]</center>'); }, cyllage: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/AUTOlch.png"><br />' + '<img src="http://i.imgur.com/Pyev2QI.jpg"><br />' + '<img src="http://i.imgur.com/02Y8dAA.png"><br />' + 'Ace: Volcarona<br />' + 'Catch phrase: Kindness is a virtue that should be expressed by everyone.</center>'); }, pan: 'panpawn', panpawn: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/BYTR6Fj.gif width="80" height="80">' + '<img src="http://i.imgur.com/xzfPeaL.gif">' + '<img src="http://107.161.19.43:8000/avatars/panpawn.gif"><br />' + '<b><font color="#4F86F7">Ace:</font></b> <font color="red">C<font color="orange">y<font color="red">n<font color="orange">d<font color="red">a<font color="orange">q<font color="red">u<font color="orange">i<font color="red">l</font><br />' + '<font color="black">"Don\'t touch me when I\'m sleeping."</font></center>'); }, mrbug: 'bug', bug: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><font size="5" color="darkgreen">Mr. Bug</font><br />' + '<img src="http://media.pocketmonsters.net/characters/2127.png" width="40%" align="left">'+ '<img src="https://1-media-cdn.foolz.us/ffuuka/board/vp/thumb/1379/30/1379304844529s.jpg" width="40%" align="right"><br />' + '<img src="http://fc01.deviantart.net/fs70/i/2011/341/9/8/kricketot_by_nami_tsuki-d4if7lr.png" width="35%"><br />' + '"delelele woooooop"<br />' + 'Ace: kriketot</center>'); }, comet: 'sunako', cometstorm: 'sunako', sunako: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/3uyLxHC.png"><br />' + '<font color="0F055C"><b><i>I came from the storm.</center>'); }, popcorn: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/jQwJOwk.gif"></center>'); }, sand: 'sandshrewed', sandshrewed: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/4kyR3d1.jpg" width="100%"><br />' + '<img src="http://i.imgur.com/lgNPrpK.png"><br />' + 'Ace: Gengar<br />' + '<font color=66CCFF>Don\'t need luck, got skill</font></center>'); }, destiny: 'itsdestiny', itsdestiny: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><font size="4" color="green"><b>It$de$tiny</b></font><br />' + '<img src="http://www.icleiusa.org/blog/library/images-phase1-051308/landscape/blog-images-90.jpg" width="55%"><img src="http://mindmillion.com/images/money/money-background-seamless-fill-bluesky.jpg" width="35%"><br />' + 'It ain\'t luck, it\'s destiny.</center>'); }, miah: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><font size="3" color="orange"><b>Miah</font></b><br />' + '<img src="https://i.imgur.com/2RHOuPi.gif" width="50%"><img src="https://fbcdn-sphotos-c-a.akamaihd.net/hphotos-ak-frc1/t1.0-9/1511712_629640560439158_8415184400256062344_n.jpg" width="50%"><br />' + 'Ace: Gliscor<br>Catch phrase: Adding Euphemisms to Pokemon</center>'); }, drag: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><font size="5" color="red">Akely</font><br />' + '<img src="http://gamesloveres.com/wp-content/uploads/2014/03/cute-pokemon-charmandercharmander-by-inversidom-riot-on-deviantart-llfutuct.png" width="25%"><br />' + 'Ace: Charizard<br />' + '"Real mens can cry but real mens doesn\'t give up."</center>'); }, kricketune: 'kriсketunе', kriсketunе: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/VPcZ1rC.png"><br />' + '<img src="http://i.imgur.com/NKGYqpn.png" width="50%"><br />' + 'Ace: Donnatello<br />' + '"At day I own the streets, but at night I own the closet..."</center>'); }, crowt: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><div class="infobox"><img src="http://i.imgur.com/BYTR6Fj.gif width="80" height="80" align="left">' + '<img src="http://i.imgur.com/czMd1X5.gif" border="6" align="center">' + '<img src="http://50.62.73.114:8000/avatars/crowt.png" align="right"><br clear="all" /></div>' + '<blink><font color="red">~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~</font></blink><br />' + '<div class="infobox"><b><font color="#4F86F7" size="3">Ace:</font></b> <font color="blue" size="3">G</font><font color="black" size="3">r</font><font color="blue" size="3">e</font><font color="black" size="3">n</font><font color="blue" size="3">i</font><font color="black" size="3">n</font><font color="blue" size="3">j</font><font color="black" size="3">a</font></font><br />' + '<font color="black">"It takes a great deal of <b>bravery</b> to <b>stand up to</b> our <b>enemies</b>, but just as much to stand up to our <b>friends</b>." - Dumbledore</font></center></div>'); }, ransu: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/kWaZd66.jpg" width="40%"><br />' + 'Develop a passion for learning. If you do, you will never cease to grow.</center>'); }, jessie: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/420CAz0.png"><br />' + '<img src="http://i.imgur.com/9ERgTNi.png"><br />' + 'Catch phrase: I\'m from Jakarta ah ah</center>'); }, berry: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://blog.flamingtext.com/blog/2014/04/02/flamingtext_com_1396402375_186122138.png" width="50%"><br />' + '<img src="http://50.62.73.114:8000/avatars/theberrymaster.gif"><br />' + 'Cherrim-Sunshine<br />' + 'I don\'t care what I end up being as long as I\'m a legend.</center>'); }, moist: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://fc04.deviantart.net/fs70/i/2010/338/6/3/moister_by_arvalis-d347xgw.jpg" width="50%"></center>'); }, spydreigon: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/57drGn3.jpg" width="75%"><br />' + '<img src="http://fc00.deviantart.net/fs70/f/2013/102/8/3/hydreigon___draco_meteor_by_ishmam-d61irtz.png" width="75%"><br />' + 'You wish you were as badass as me</center>'); }, mushy: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><font size="3" color=#8E019D>Mushy</font><br />' + '<img src="http://www.wall321.com/thumbnails/detail/20120504/angels%20army%20diablo%20armor%20tyrael%20swords%201920x1080%20wallpaper_www.wall321.com_75.jpg" width=400 height=225><br />' + '"Why do people hope for things that they know are near impossible?" "Because sometimes, hope is all you have."</center>'); }, panic: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/sGq1qy9.gif"></center>'); }, furgo: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/0qJzTgP.gif" width="25%"><br />' + '<font color="red">Ace:</font><br />' + '<img src="http://amethyst.xiaotai.org:2000/avatars/furgo.gif"><br />' + 'When I\'m sleeping, do not poke me. :I</center>'); }, blazingflareon: 'bf', bf: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/h3ZTk9u.gif"><br />' + '<img src="http://fc08.deviantart.net/fs71/i/2012/251/3/f/flareon_coloured_lineart_by_noel_tf-d5e166e.jpg" width="25%"><br />' + '<font size="3" color="red"><u><b><i>DARE TO DREAM</font></u></i></b></center>'); }, mikado: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/oS2jnht.gif"><br />' + '<img src="http://i.imgur.com/oKEA0Om.png"></center>'); }, dsg:'darkshinygiratina', darkshinygiratina: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><font size="4" color="blue" face="arial">DarkShinyGiratina</font><br />' + '<img src="http://i.imgur.com/sBIqMv8.gif"><br />' + 'I\'m gonna use Shadow Force on you!</center>'); }, archbisharp: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/ibC46tQ.png"><br />' + '<img src="http://fc07.deviantart.net/fs70/f/2012/294/f/c/bisharp_by_xdarkblaze-d5ijnsf.gif" width="350" hieght="350"><br />' + '<b>Ruling you with an Iron Head.</b></center>'); }, chimplup: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><b>Chimplup</b> - The almighty ruler of chimchars and piplups alike, also likes pie.</center>'); }, shephard: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><b>Shephard</b> - King Of Water and Ground types.</center>'); }, logic: 'psychological', psychological: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/c4j9EdJ.png?1">' + '<img src="http://i.imgur.com/tRRas7O.gif" width="200">' + '<img src="http://i.imgur.com/TwpGsh3.png?1"><br />' + '<img src="http://i.imgur.com/1MH0mJM.png" height="90">' + '<img src="http://i.imgur.com/TSEXdOm.gif" width="300">' + '<img src="http://i.imgur.com/4XlnMPZ.png" height="90"><br />' + 'If it isn\'t logical, it\'s probably Psychological.</center>'); }, seed: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><b>Seed</b> - /me plant and water</center>'); }, auraburst: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/9guvnD7.jpg">' + '<font color="orange"><font size="2"><b>Aura Butt</b> - Nick Cage.</font>' + '<img src="http://i.imgur.com/9guvnD7.jpg"></center>'); }, leo: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><b>Leonardo DiCaprio</b> - Mirror mirror on the wall, who is the chillest of them all?</center>'); }, kupo: 'moogle', moogle: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><font size="7" color="#AE8119"><b>kupo</font</b><br />' + '<img src="http://107.191.104.240:8000/avatars/kupo.png"><br />' + '<img src="http://th03.deviantart.net/fs70/PRE/i/2013/193/f/1/chocobo_and_moogle_by_judeydey-d6d629x.png" width="25%"><br />' + 'abc! O3O!</center>'); }, starmaster: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><b>Starmaster</b> - Well what were you expecting. Master of stars. Duh</center>'); }, ryun: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><b>Ryun</b> - Will fuck your shit up with his army of Gloom, Chimecho, Duosion, Dunsparce, Plusle and Mr. Mime</center>'); }, miikasa: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://fc06.deviantart.net/fs70/f/2010/330/2/0/cirno_neutral_special_by_generalcirno-d33ndj0.gif"><br />' + '<font color="purple"><font size="2"><b>Miikasa</b></font>' + '<font color="purple"><font size="2"> - There are no buses in Gensokyo.</center></font>'); }, poliii: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/GsI3Y75.jpg"><br />' + '<font color="blue"><font size="2"><b>Poliii</b></font>' + '<font color="blue"><font size="2"> - Greninja is behind you.</font></center>'); }, frozengrace: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><b>FrozenGrace</b> - The gentle wind blows as the song birds sing of her vibrant radiance. The vibrant flowers and luscious petals dance in the serenading wind, welcoming her arrival for the epitome of all things beautiful. Bow down to her majesty for she is the Queen. Let her bestow upon you as she graces you with her elegance. FrozenGrace, eternal serenity.</center>'); }, awk: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><b>Awk</b> - I have nothing to say to that!</center>'); }, screamingmilotic: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><b>ScreamingMilotic</b> - The shiny Milotic that wants to take over the world.</center>'); }, aikenka: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://fc05.deviantart.net/fs70/f/2010/004/3/4/Go_MAGIKARP_use_your_Splash_by_JoshR691.gif">' + '<b><font size="2"><font color="blue">Aikenká</b><font size="2"></font>' + '<font color="blue"> - The Master of the imp.</font>' + '<img src="http://fc05.deviantart.net/fs70/f/2010/004/3/4/Go_MAGIKARP_use_your_Splash_by_JoshR691.gif"></center>'); }, ipad: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/miLUHTz.png"><br><b>iPood</b><br />' + 'A total <font color="brown">pos</font> that panpawn will ban.<br />' + '<img src="http://i.imgur.com/miLUHTz.png"></center>'); }, rhan: 'rohansound', rohansound: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><font color="orange"><font size="2"><b>Rohansound</b>' + '<font size="orange"><font size="2"> - The master of the Snivy!</center>'); }, alittlepaw: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://fc00.deviantart.net/fs71/f/2013/025/5/d/wolf_dance_by_windwolf13-d5sq93d.gif"><br />' + '<font color="green"><font size="3"><b>ALittlePaw</b> - Fenrir would be proud.</center>'); }, smashbrosbrawl: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><b>SmashBrosBrawl</b> - Christian Bale</center>'); }, w00per: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/i3FYyoG.gif"><br />' + '<font size="2"><font color="brown"><b>W00per</b>' + '<font size="2"><font color="brown"> - "I CAME IN LIKE `EM WRECKIN` BALLZ!</center>'); }, empoleonxv: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/IHd5yRT.gif"><br />' + '<img src="http://i.imgur.com/sfQsRlH.gif"><br />' + '<b><font color="33FFFF"><big>Smiling and Waving can\'t make you more cute than me!</b></center>'); }, foe: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://s21.postimg.org/durjqji4z/aaaaa.gif"><br />' + '<font size="2"><b>Foe</b><font size="2"> - Not a friend.</center>'); }, op: 'orangepoptarts', orangepoptarts: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://www.jeboavatars.com/images/avatars/192809169066sunsetbeach.jpg"><br />' + '<b><font size="2">Orange Poptarts</b><font size="2"> - "Pop, who so you" ~ ALittlePaw</center>'); }, darkhanekawa: 'jackzero', v: 'jackzero', jack: 'jackzero', jackzero: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><font size="4" color="#1AACBC"><b>JackZero</b><br/></font>' + '<img src="http://i.imgur.com/wUqmPZz.gif" height="250"><br/>' + '<font size="2"><i>I stopped fighting my inner demons. We are on the same side now.</i></font></center>'); }, wd: 'windoge', windoge: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/qYTABJC.jpg" width="400"></center>'); }, party: 'dance', dance: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://collegecandy.files.wordpress.com/2013/05/tumblr_inline_mhv5qyiqvk1qz4rgp1.gif" width="400"></center>'); }, kayo: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><font size="2"><b>Kayo</b><br />' + 'By the Beard of Zeus that Ghost was Fat<br />' + '<img src="http://i.imgur.com/rPe9hBa.png"></center>'); }, saburo: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><font color="red" size="5"><b>Saburo</font></b><br />' + '<img src="http://i.imgur.com/pYUt8Hf.gif"><br>The god of dance.</center>'); }, gara: 'garazan', nub: 'garazan', garazan: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><font size="6" face="comic sans ms"><font color="red">G<font color="orange">a<font color="yellow">r<font color="tan">a<font color="violet">z<font color="purple">a<font color="blue">n</font><br />' + '<img src="http://www.quickmeme.com/img/3b/3b2ef0437a963f22d89b81bf7a8ef9d46f8770414ec98f3d25db4badbbe5f19c.jpg" width="150" height="150"></center>'); }, scizornician: 'sciz', sciz: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<div class="broadcast-blue"><center><font color="#A80000" size ="3"><b>Scizornician</b></font><br />' + '<b>Quote:</b> "It\'s all shits and giggles until someone giggles and shits."</font><br />' + '<b>Quote:</b> "Light travels faster than sound, that\'s why some people appear bright before they speak."</font><br />' + '<img src="http://107.191.104.240:8000/avatars/sciz.gif"></center></div>'); }, d3adm3owth: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><font color=#0E30AA size=3>d3adm3owth</font><br />' + '<img src="http://img2.wikia.nocookie.net/__cb20140120230002/pokemon/images/1/1b/OI015.jpg" width=320 height 240><br />' + 'Ace: Meowth<br />' + '...in accordance with the dictates of reason.</center>'); }, ashbloodthief: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><font size="5"><font color="#140391">ashbloodthief</font></font></center> <center><img src="http://107.191.104.240:8000/avatars/ashbloodthief.gif" width=100 height=100></center> <center><img src="http://fc04.deviantart.net/fs71/f/2013/259/f/f/mega_lucario_by_henshingeneration-d6mihft.jpg" width=270 height=200></center><br /> <center><font size="3"> Ace: Mega Lucario</font></center> <center><font size="3"> I\'m a being pure as energy! You can\'t stop me!</font></center>'); }, chaotic: function(target, room, user) { if (!this.canBroadCast()) return; this.sendReplayBox("<center><img src=\"http://i.imgur.com/NVEZJG1.png\" title=\"Hosted by imgur.com\" width=\"400\" height=\"100\"> </a><br><img src=\"http://media0.giphy.com/media/DCp4s7Z1FizZe/giphy.gif\" width=\"250\" height=\"250\"><img src=\"http://i269.photobucket.com/albums/jj77/YandereGIFs/Durarara%20GIFs/IzayaScared.gif\" width=\"250\" height=\"250\"> <br><center><b>\"A Caterpie may change into a Butterfree, but the heart that beats inside remains the same.\"</b>"); }, //***********************Music Boxes*************************** //View Music box command to reduce lobby spam vmb: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center>Click <button name="send" value="/'+ target + '" class="blackbutton" title="View musicbox!"><font color="white"><b>here</button></b></font> to view <b>' + target + '!</b></center>'); }, tailzbox: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<b>Tailz\'s Music Box!</b><br />' + '1. <a href="https://www.youtube.com/watch?v=zxof7Lh1u3c"><button>Nano - Savior Of Song</a></button><br />' + '2. <a href="https://www.youtube.com/watch?v=3ZckiELrRLU"><button>Nano - Black Board</a></button><br />' + '3. <a href="https://www.youtube.com/watch?v=P829PgxKxuM"><button>A Day To Remember - If It Means A Lot To You</a></button><br />' + '4. <a href="https://www.youtube.com/watch?v=QgFHL2R8m6s"><button>HollyWood Undead - Lion</a></button><br />' + '5. <a href="https://www.youtube.com/watch?v=fBocMs7EyOg"><button>Nano - Just Be Friends</a></button><br />' + '6. <a href="https://www.youtube.com/watch?v=Om5uXsD-aVo"><button>Rise Against - Satellite</a></button><br />' + '7. <a href="https://www.youtube.com/watch?v=YDJXr-Tzbqw"><button>Sora Amamiya - Skyreach</a></button><br />' + '8. <a href="https://www.youtube.com/watch?v=Ypl0gPtk0tA"><button>Three Days Grace - The High Road</a></button><br />' + '9. <a href="https://www.youtube.com/watch?v=xZ2yP7iUDeg"><button>Crown The Empire - Millenia</a></button><br /></center>' ); }, terbox: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<b>Sir Terlor\'s Music Box!</b><br />' + '1. <a href="https://www.youtube.com/watch?v=lL2ZwXj1tXM"><button>Three Days Grace - Never Too Late</a></button><br />' + '2. <a href="https://www.youtube.com/watch?v=JpDPOs-rddM"><button>Sonata Arctica - Mary Lou</a></button><br />' + '3. <a href="https://www.youtube.com/watch?v=IbOd8yf1ElI"><button>Hollywood Undead - The Diary</a></button><br />' + '4. <a href="https://www.youtube.com/watch?v=JCT5uTdPRgs"><button>Black Sabbath - N.I.B</a></button><br />' + '5. <a href="https://www.youtube.com/watch?v=as7p6VwnR5s"><button>Vexento - Praeclara</a></button><br />' + '6. <a href="https://www.youtube.com/watch?v=G5zdal1MKf0"><button>Volbeat - Doc Holiday</a></button><br />' + '7. <a href="https://www.youtube.com/watch?v=VRFCMM3bra8"><button>Billy Talent - Viking Death March</a></button></center>' ); }, silrbox: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<b>Silver\'s Music Box!</b><br />' + '1. <a href="https://www.youtube.com/watch?v=GEEYhzaeNus"><button>Union J - Carry You</a></button><br />' + '2. <a href="https://www.youtube.com/watch?v=cmSbXsFE3l8"><button>Anna Kendrick - Cups</a></button><br />' + '3. <a href="https://www.youtube.com/watch?v=iKaSbac2roQ"><button>Vacation - Vitamin C</a></button><br />' + '4. <a href="https://www.youtube.com/watch?v=LiaYDPRedWQ"><button>Avril Lavigne - Hello Kitty</a></button><br />'); }, sandbox: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<b>Sandshrewed\'s Music Box!</b><br />' + '1. <a href="https://www.youtube.com/watch?v=vN0I4b5YdOc"><button title="RAP Done It All - Iniquity Rhymes">RAP Done It All - Iniquity Rhymes</a></button><br />' + '2. <a href="https://www.youtube.com/watch?v=n3QmHNd0HWo"><button title="Metal Gear Rising: Revengeance ~ The Only Thing I Know For Real">Metal Gear Rising: Revengeance ~ The Only Thing I Know For Real</a></button><br />' + '3. <a href="https://www.youtube.com/watch?v=hV5sB5rRsGI"><button title="New Boyz - Colors">New Boyz - Colors</a></button><br />' + '4. <a href="https://www.youtube.com/watch?v=A1A0mIqlPiI"><button title="Young Cash feat. Shawn Jay (Field Mob) - Stress Free">Young Cash feat. Shawn Jay (Field Mob) - Stress Free</a></button><br />' + '5. <a href="https://www.youtube.com/watch?v=ULQgMntenO8"><button title="Metal Gear Rising, Monsoon\'s theme- Stains of Time">Metal Gear Rising, Monsoon\'s theme- Stains of Time</a></button><br />' + '6. <a href="https://www.youtube.com/watch?v=P4PgrY33-UA"><button title="Drop That NaeNae">Drop That NaeNae</a></button><br />' ); }, ampharosbox: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<b>AmpharosTheBeast\'s Music Box!</b><br />' + '1. <a href="https://www.youtube.com/watch?v=RRGSHvlu9Ss"><button title="Linkin Park - Castle of Glass">Linkin Park - Castle of Glass</a></button><br />' + '2. <a href="https://www.youtube.com/watch?v=ie1wU9BLGn8"><button title="Rixton - Me and My Broken Heart">Rixton - Me and My Broken Heart</a></button><br />' + '3. <a href="https://www.youtube.com/watch?v=psuRGfAaju4"><button title="Owl City - Fireflies">Owl City - Fireflies</a></button><br />' + '4. <a href="https://www.youtube.com/watch?v=hT_nvWreIhg"><button title="OneRepublic - Counting Stars">OneRepublic - Counting Stars</a></button><br />' + '5. <a href="https://www.youtube.com/watch?v=VDvr08sCPOc"><button title="Fort Minor - Remember The Name">Fort Minor - Remember The Name</a></button><br />' + '6. <a href="https://www.youtube.com/watch?v=JPCv5rubXhU"><button title="Pokemon Bank A Parody of Bad Day">Pokemon Bank A Parody of Bad Day</a></button>'); }, legitbox: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<b>Legit Buttons\'s Music Box!</b><br />' + '1. <a href="https://www.youtube.com/watch?v=y6Sxv-sUYtM"><button title="Pharrell Williams - Happy">Pharrell Williams - Happy</a></button><br />' + '2. <a href="https://www.youtube.com/watch?v=hT_nvWreIhg"><button title="OneRepublic - Counting Stars">OneRepublic - Counting Stars</a></button><br />' + '3. <a href="https://www.youtube.com/watch?v=6Cp6mKbRTQY"><button title="Avicii - Hey Brother">Avicii - Hey Brother</a></button><br />' + '4. <a href="https://www.youtube.com/watch?v=hHUbLv4ThOo"><button title="Pitbull - Timber ft. Ke$ha">Pitbull - Timber ft. Ke$ha</a></button><br />' ); }, riotbox: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<b>Jack Skellington\'s Music Box!</b><br />' + '1. <a href="https://www.youtube.com/watch?v=ubiZDYU7mv0"><button title="Metal Gear Rising: Revengeance - The Only Thing I Know for Real ">Metal Gear Rising: Revengeance - The Only Thing I Know for Real </a></button><br />' + '2. <a href="https://www.youtube.com/watch?v=ye0XhDdbFs4"><button title="A Day to Remember - You Had Me at Hello">A Day to Remember - You Had Me at Hello</a></button><br />' + '3. <a href="https://www.youtube.com/watch?v=vc6vs-l5dkc"><button title="Panic! At The Disco - I Write Sins Not Tragedies">Panic! At The Disco: I Write Sins Not Tragedies</a></button><br />' + '4. <a href="https://www.youtube.com/watch?v=FukeNR1ydOA"><button title="Suicide Silence - Disengage">Suicide Silence - Disengage</a></button><br />' + '5. <a href="https://www.youtube.com/watch?v=xyW9KknfwLU"><button title="A Day to Remember - Sometimes You\'re The Hammer, Sometimes You\'re The Nail">A Day to Remember - Sometimes You\'re The Hammer, Sometimes You\'re The Nail</a></button><br />' + '6. <a href="https://www.youtube.com/watch?v=sA5hj7wuJLQ"><button title="Bring Me The Horizon - Empire (Let Them Sing)">Bring Me The Horizon - Empire (Let Them Sing)</a></button><br />' ); }, berrybox: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<b>The Berry Master\'s Music Box!</b><br />' + '1. <a href="https://www.youtube.com/watch?v=fJ9rUzIMcZQ"><button title="Queen - Bohemian Rhapsody">Queen - Bohemian Rhapsody</a></button><br />' + '2. <a href="https://www.youtube.com/watch?v=xDMNHvnIxic"><button title="Hamster on a Piano">Hamster on a Piano</a></button><br />' + '3. <a href="https://www.youtube.com/watch?v=BuO5Jiqn9q4"><button title="The Ink Spots - Making Believe">The Ink Spots - Making Believe</a></button><br />' + '4. <a href="https://www.youtube.com/watch?v=ws8X31TTB5E"><button title="Cowboy Bebop OST 3 Blue - Adieu">Cowboy Bebop OST 3 Blue - Adieu</a></button><br />' + '5. <a href="https://www.youtube.com/watch?v=CnDJizJsMJg"><button title="ENTER SHIKARI - MOTHERSTEP/MOTHERSHIP">ENTER SHIKARI - MOTHERSTEP/MOTHERSHIP</a></button><br />' + '6. <a href="https://www.youtube.com/watch?v=-osNFEyI3vw"><button title="Gungor - Crags And Clay">Gungor - Crags And Clay</a></button><br />' ); }, sphealbox: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<b>Super Spheal Bros\'s Music Box!</b><br />' + '1. <a href="https://www.youtube.com/watch?v=85XM_Nl7_oo"><button title="Mother 1 (EarthBound Zero) Music - Eight Melodies">Mother 1 (EarthBound Zero) Music - Eight Melodies</a></button><br />' + '2. <a href="https://www.youtube.com/watch?v=oOy7cJowbQs"><button title="Pokemon Black & White 2 OST Kanto Gym Leader Battle Music">Pokemon Black & White 2 OST Kanto Gym Leader Battle Music</a></button><br />' + '3. <a href="https://www.youtube.com/watch?v=XEEceynk-mg"><button title="Sonic the Hedgehog Starlight Zone Music">Sonic the Hedgehog Starlight Zone Music</a></button><br />' + '4. <a href="https://www.youtube.com/watch?v=jofNR_WkoCE"><button title="Ylvis - The Fox (What Does The Fox Say?)">Ylvis - The Fox (What Does The Fox Say?)</a></button><br />' + '5. <a href="https://www.youtube.com/watch?v=EAwWPadFsOA"><button title="Mortal Kombat Theme Song">Mortal Kombat Theme Song</a></button><br />' + '6. <a href="https://www.youtube.com/watch?v=QH2-TGUlwu4"><button title="Nyan Cat">Nyan Cat</a></button><br />'); }, boxofdestiny: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<b>itsdestny\'s Music Box!</b><br />' + '1. <a href="https://www.youtube.com/watch?v=pucnAvLsgyI"><button title="Megaman Battle Network 5 Hero Theme">Megaman Battle Network 5 Hero Theme</a></button><br />' + '2. <a href="https://www.youtube.com/watch?v=ckNRHPlLBcU"><button title="Gospel - Monsters University">Gospel - Monsters University</a></button><br />' + '3. <a href="https://www.youtube.com/watch?v=sLgyd2HHvMc"><button title="Princess Kenny Theme Song">Princess Kenny Theme Song</a></button><br />' + '4. <a href="https://www.youtube.com/watch?v=9bZkp7q19f0"><button title="Psy - Gangnam Style">Psy - Gangnam Style</a></button><br />' + '5. <a href="https://www.youtube.com/watch?v=x4JdySEXrg8"><button title="Frozen - Let It Go">Frozen - Let It Go</a></button><br />'); }, cbox: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<b>Cyllage\'s Music Box!</b><br />' + '1. <a href="https://www.youtube.com/watch?v=SRvCvsRp5ho"><button title="Bon Jovi - Wanted Dead Or Alive">Bon Jovi - Wanted Dead Or Alive</a></button><br />' + '2. <a href="https://www.youtube.com/watch?v=c901NUazf3g"><button title="Muse - Exogenesis Symphony">Muse - Exogenesis Symphony</a></button><br />' + '3. <a href="https://www.youtube.com/watch?v=4MjLKjPc7q8"><button title="Rise Against - Audience Of One">Rise Against - Audience Of One</a></button><br />' + '4. <a href="https://www.youtube.com/watch?v=gxEPV4kolz0"><button title="Billy Joel - Piano Man">Billy Joel - Piano Man</a></button><br />' + '5. <a href="https://www.youtube.com/watch?v=IwdJYdDyKUw"><button title="Griffin Village - Spring">Griffin Village - Spring</a></button><br />'); }, spybox: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<b>Spydreigon\'s Music Box!</b><br />' + '1. <a href="https://www.youtube.com/watch?v=gL-ZIbF6J6s"><button title="Pursuit - Cornered">Pursuit - Cornered</a></button><br />' + '2. <a href="https://www.youtube.com/watch?v=qgP1yc1PpoU"><button title="Mega Man 10 - Abandoned Memory">Mega Man 10 - Abandoned Memory</a></button><br />' + '3. <a href="https://www.youtube.com/watch?v=yW6ECMHrGcI"><button title="Super Training! 8 Bit - Pokemon X/Y">Super Training! 8 Bit - Pokemon X/Y</a></button><br />' + '4. <a href="https://www.youtube.com/watch?v=NWYJYcpSpCs"><button title="Mighty No. 9 Theme 8 Bit">Mighty No. 9 Theme 8 Bit</a></button><br />' + '5. <a href="https://www.youtube.com/watch?v=NwaCMbfHwmQ"><button title="Mega Man X5 - X vs Zero">Mega Man X5 - X vs Zero</a></button><br />'); }, solstereo: 'solbox', solbox: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<b>The Sol Box</b><br />' + '1. <a href="https://www.youtube.com/watch?v=VIop055eJhU"><button title="Touhou 6 - EoSD - U.N. Owen was her?"> Touhou 6 - EoSD - U.N. Owen was her?</a></button><br />' + '2. <a href="https://www.youtube.com/watch?v=BwpLSiplyYc"><button title="Kirby 64: The Crystal Shards - Zero Two">Kirby 64: The Crystal Shards - Zero Two</a></button><br />' + '3. <a href="https://www.youtube.com/watch?v=EzCKrwOme2U"><button title="Muse - Butterflies and Hurricanes">Muse - Butterflies and Hurricanes</a></button><br />' + '4. <a href="https://www.youtube.com/watch?v=EqGs36oPpLQ"><button title="Last Dinosaurs - Zoom">Last Dinosaurs - Zoom</a></button><br />' + '5. <a href="https://www.youtube.com/watch?v=p9Y-r-rs9W8"><button title="Green Day - Welcome to Paradise">Green Day - Welcome to Paradise</a></button><br />' + '6. <a href="https://www.youtube.com/watch?v=aWxBrI0g1kE"><button title="Disturbed - Indestructible">Disturbed - Indestructible</a></button><br />' + '7. <a href="https://www.youtube.com/watch?v=Fi_GN1pHCVc"><button title="Avenged Sevenfold - Almost Easy">Avenged Sevenfold - Almost Easy</a></button><br />' + '8. <a href="https://www.youtube.com/watch?v=71CvlYX1Bqc"><button title="Linkin Park - Across The Line">Linkin Park - Across The Line</a></button><br />' + '9. <a href="https://www.youtube.com/watch?v=gMzSpvibN7A"><button title="30 Seconds To Mars - Hurricane (Nightcore)">30 Seconds To Mars - Hurricane (Nightcore)</a></button>'); }, vbox: 'jackbox', jackbox: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<b>Jacks\'s Music Box!</b><br />' + '1. <a href="https://www.youtube.com/watch?v=m0DMfaCh4aA"><button title="Attack on Titan - DOA">Attack on Titan - DOA</a></button><br />' + '2. <a href="https://www.youtube.com/watch?v=c-M34ZRM120"><button title=" ADTR - You be Tails, I\'ll be Sonic"> ADTR - You be Tails, I\'ll be Sonic</a></button><br />' + '3. <a href="https://www.youtube.com/watch?v=0B-xRO-vPPo"><button title="Papercut massacre - Lose my life">Papercut massacre - Lose my life</a></button><br />' + '4. <a href="https://www.youtube.com/watch?v=Qg_TRaiWj4o"><button title="The Who - Behind blue eyes">The Who - Behind blue eyes</a></button><br />' + '5. <a href="https://www.youtube.com/watch?v=0m9QUoW5KnY"><button title="Starbomb - It\'s dangerous to go alone">Starbomb - It\'s dangerous to go alone</a></button><br />' + '6. <a href="https://www.youtube.com/watch?v=Tt10gb8yf88"><button title="12 Stones - Psycho">12 Stones - Psycho</a></button><br />'); }, panbox: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<b>Panpawn\'s Music Box!</b><br />' + '1. <a href="https://www.youtube.com/watch?v=EJR5A2dttp8"><button title="Let It Go - Connie Talbot cover">Let It Go - Connie Talbot cover</a></button><br />' + '2. <a href="https://www.youtube.com/watch?v=Y2Ta0qCG8No"><button title="Crocodile Rock - Elton John">Crocodile Rock - Elton John</a></button><br />' + '3. <a href="https://www.youtube.com/watch?v=ZA3vZwxnKnE"><button title="My Angel Gabriel - Lamb">My Angel Gabriel - Lamb</a></button><br />' + '4. <a href="https://www.youtube.com/watch?v=y8AWFf7EAc4"><button title="Hallelujah - Jeff Buckley">Hallelujah - Jeff Buckley</a></button><br />' + '5. <a href="https://www.youtube.com/watch?v=aFIApXs0_Nw"><button title="Better Off Dead - Elton John">Better Off Dead - Elton John</a></button><br />' + '6. <a href="https://www.youtube.com/watch?v=eJLTGHEwaR8"><button title="Your Song - Carly Rose Sonenclar cover">Your Song - Carly Rose Sonenclar cover</a></button><br />' + '7. <a href="https://www.youtube.com/watch?v=DAJYk1jOhzk"><button title="Let It Go - Frozen - Alex Boyé">Let It Go - Frozen - Alex Boyé</a></button><br />' + '8. <a href="https://www.youtube.com/watch?v=8S-jdXJ0H4w"><button title="Elton John - Indian Sunset">Elton John-Indian Sunset</a></button><br />' + '9. <a href="https://www.youtube.com/watch?v=cnK_tfqHQnU"><button title="New York State Of Mind - Billy Joel">New York State Of Mind - Billy Joel</a></button><br />' + '10. <a href="https://www.youtube.com/watch?v=0KDjzP84sVA"><button title="Counting Stars - Cimorelli">Counting Stars - Cimorelli</a></button><br />' + '11. <a href="https://www.youtube.com/watch?v=PpntEOQLpzI"><button title="Stay - Christina Grimmie">Stay - Christina Grimmie</a></button><br />' + '12. <a href="https://www.youtube.com/watch?v=JiBKfl-xhI0"><button title="Carly Rose Sonenclar - Feeling Good">Carly Rose Sonenclar - Feeling Good</a></button><br />' + '13. <a href="https://www.youtube.com/watch?v=Gj-ntawOBw4"><button title="Shake It Out - Choral">Shake It Out - Choral</a></button><br />' + '14. <a href="https://www.youtube.com/watch?v=n7wQQGtM-Hc"><button title="Elton John Sixty Years On Royal Opera House">Elton John Sixty Years On Royal Opera House</a></button><br />' + '15. <a href="https://www.youtube.com/watch?v=Izma0gpiLBQ"><button title="Elton John - Oceans Away">Elton John - Oceans Away</a></button><br />' + '16. <a href="https://www.youtube.com/watch?v=hOpK1Euwu5U"><button title="JennaAnne: I\'m Coming Home">JennaAnne: I\'m Coming Home</a></button>'); }, cabox: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<b>CoolAsian\'s Music Box!</b><br />' + '1. <a href="http://youtu.be/UU8xKUoH_lU"><button title="Parkway Drive - Wild Eyes [Lyrics] [HD]">Parkway Drive - Wild Eyes [Lyrics] [HD]</a></button><br />' + '2. <a href="http://youtu.be/fOLqEOK_wLc"><button title="System Of A Down - B.Y.O.B.">System Of A Down - B.Y.O.B.</a></button><br />' + '3. <a href="http://youtu.be/312Sb-2PovA"><button title="SUICIDE SILENCE - You Only Live Once">SUICIDE SILENCE - You Only Live Once</a></button><br />' + '4. <a href="http://youtu.be/pUA-4WCXn5o"><button title="Atreyu - Demonology and Heartache">Atreyu - Demonology and Heartache</a></button><br />' + '5. <a href="http://youtu.be/zUq8I4JTOZU"><button title="Muse - Assassin (Grand Omega Bosses Edit)">Muse - Assassin (Grand Omega Bosses Edit)</a></button><br />' + '6. <a href="http://youtu.be/a89Shp0YhR8"><button title="A Day to Remember - I\'m Made of Wax, Larry, What Are You Made Of?">A Day to Remember - I\'m Made of Wax, Larry, What Are You Made Of?</a></button>'); }, lazerbox: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<b>lazerbeam\'s Music Box!</b><br />' + '1. <a href="https://www.youtube.com/watch?v=fJ9rUzIMcZQ"><button title="Bohemian Rhapsody - Queen">Bohemian Rhapsody - Queen</a></button><br />' + '2. <a href="https://www.youtube.com/watch?v=ZNaA7fVXB28"><button title="Against the Wind - Bob Seger">Against the Wind - Bob Seger</a></button><br />' + '3. <a href="https://www.youtube.com/watch?v=TuCGiV-EVjA"><button title="Livin\' on the Edge - Aerosmith">Livin\' on the Edge - Aerosmith</a></button><br />' + '4. <a href="https://www.youtube.com/watch?v=QZ_kYEDZVno"><button title="Rock and Roll Never Forgets - Bob Seger">Rock and Roll Never Forgets - Bob Seger</a></button><br />' + '5. <a href="https://www.youtube.com/watch?v=GHjKEwV2-ZM"><button title="Jaded - Aerosmith">Jaded - Aerosmith</a></button>'); }, //End Music Boxes. avatars: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox("Your avatar can be changed using the Options menu (it looks like a gear) in the upper right of Pokemon Showdown. Custom avatars are only obtainable by staff."); }, git: 'opensource', opensource: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('Pokemon Showdown is open source:<br />- Language: JavaScript (Node.js)<br />'+ '- <a href="https://github.com/Zarel/Pokemon-Showdown" target="_blank">Pokemon Showdown Source Code / How to create a PS server</a><br />'+ '- <a href="https://github.com/Zarel/Pokemon-Showdown-Client" target="_blank">Client Source Code</a><br />'+ '- <a href="https://github.com/panpawn/Pokemon-Showdown">Gold Source Code</a>'); }, events: 'activities', activities: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><font size="3" face="comic sans ms">Gold Activities:</font></center></br>' + '★ <b>Tournaments</b> - Here on Gold, we have a tournaments script that allows users to partake in several different tiers. For a list of tour commands do /th. Ask in the lobby for a voice (+) or up to start one of these if you\'re interesrted!<br>' + '★ <b>Hangmans</b> - We have a hangans script that allows users to partake in a "hangmans" sort of a game. For a list of hangmans commands, do /hh. As a voice (+) or up in the lobby to start one of these if interested.<br>' + '★ <b>Leagues</b> - If you click the "join room page" to the upper right (+), it will display a list of rooms we have. Several of these rooms are 3rd party leagues of Gold; join them to learn more about each one!<br>' + '★ <b>Battle</b> - By all means, invite your friends on here so that you can battle with each other! Here on Gold, we are always up to date on our formats, so we\'re a great place to battle on!<br>' + '★ <b>Chat</b> - Gold is full of great people in it\'s community and we\'d love to have you be apart of it!<br>' + '★ <b>Learn</b> - Are you new to Pokemon? If so, then feel FREE to ask the lobby any questions you might have!<br>' + '★ <b>Shop</b> - Do /shop to learn about where your Gold Bucks can go! <br>' + '★ <b>Plug.dj</b> - Come listen to music with us! Click <a href="http://plug.dj/gold-server/">here</a> to start!<br>' + '<i>--PM staff (%, @, &, ~) any questions you might have!</i>'); }, showtan: function (target, room, user) { if (room.id !== 'showderp') return this.sendReply("The command '/showtan' was unrecognized. To send a message starting with '/showtan', type '//showtan'."); if (!this.can('modchat', null, room)) return; target = this.splitTarget(target); if (!this.targetUser) return this.sendReply('user not found'); if (!room.users[this.targetUser.userid]) return this.sendReply('not a showderper'); this.targetUser.avatar = '#showtan'; room.add(user.name+' applied showtan to affected area of '+this.targetUser.name); }, introduction: 'intro', intro: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox( "New to competitive pokemon?<br />" + "- <a href=\"https://www.smogon.com/sim/ps_guide\">Beginner's Guide to Pokémon Showdown</a><br />" + "- <a href=\"https://www.smogon.com/dp/articles/intro_comp_pokemon\">An introduction to competitive Pokémon</a><br />" + "- <a href=\"https://www.smogon.com/bw/articles/bw_tiers\">What do 'OU', 'UU', etc mean?</a><br />" + "- <a href=\"https://www.smogon.com/xyhub/tiers\">What are the rules for each format? What is 'Sleep Clause'?</a>" ); }, support: 'donate', donate: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox( "<center>Like this server and want to keep it going? If so, you can make a paypal donation to Gold! You can choose the amount.<br />" + '<hr width="85%">' + "- Donations will help Gold to upgrade the VPS so we can do more and hold more users!<br />" + "- For donations <b>$5 or over</b>, you can get: 200 bucks, a custom avatar, a custom trainer card, a custom symbol, and a custom music box!<br />" + "- For donations <b>$10 and over</b>, it will get you: (the above), 600 bucks (in addition to the above 200, making 800 total) and VIP status along with a VIP badge!<br />" + "- Refer to the /shop command for a more detailed description of these prizes. After donating, PM panpawn.<br />" + '<hr width="85%">' + "Click the button below to donate!<br />" + '<a href="https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=FBZBA7MJNMG7J&lc=US&item_name=Gold%20Server&currency_code=USD&bn=PP%2dDonationsBF%3abtn_donate_LG%2egif%3aNonHosted"><img src="https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif" title=Donate now!">' ); }, links: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox( "<div class=\"broadcast-black\">Here are some helpful server related links:<b><br />" + "- <a href=\"http://goldserver.weebly.com/rules.html\"><font color=\"#FF0066\">Rules</a></font><br />" + "- <a href=\"http://w11.zetaboards.com/Goldserverps/index/\"><font color=\"#FF00\">Forums</a></font><br />" + "- <a href=\"http://goldserver.weebly.com\"><font color=\"#56600FF\">Website</a></font><br />" + "- <a href=\"http://plug.dj/gold-server/\"><font color=\"#FFFF\">Plug.dj</a></font><br />" + "- <a href=\"https://github.com/panpawn/Pokemon-Showdown\"><font color=\"#39FF14\">GitHub</a></font><br />" + "- <a href=\"http://goldserver.weebly.com/news.html\"><font color=\"#BFFF00\">News</a></font><br />" + "- <a href=\"http://goldserver.weebly.com/faqs.html\"><font color=\"#DA9D01\">FAQs</a></font><br />" + "- <a href=\"http://goldserver.weebly.com/discipline-appeals.html\"><font color=\"#12C418\">Discipline Appeals</a></font>" + "</b></div>" ); }, mentoring: 'smogintro', smogonintro: 'smogintro', smogintro: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox( "Welcome to Smogon's official simulator! Here are some useful links to <a href=\"https://www.smogon.com/mentorship/\">Smogon\'s Mentorship Program</a> to help you get integrated into the community:<br />" + "- <a href=\"https://www.smogon.com/mentorship/primer\">Smogon Primer: A brief introduction to Smogon's subcommunities</a><br />" + "- <a href=\"https://www.smogon.com/mentorship/introductions\">Introduce yourself to Smogon!</a><br />" + "- <a href=\"https://www.smogon.com/mentorship/profiles\">Profiles of current Smogon Mentors</a><br />" + "- <a href=\"http://mibbit.com/#[email protected]\">#mentor: the Smogon Mentorship IRC channel</a>" ); }, calculator: 'calc', calc: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox( "Pokemon Showdown! damage calculator. (Courtesy of Honko)<br />" + "- <a href=\"https://pokemonshowdown.com/damagecalc/\">Damage Calculator</a>" ); }, cap: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox( "An introduction to the Create-A-Pokemon project:<br />" + "- <a href=\"https://www.smogon.com/cap/\">CAP project website and description</a><br />" + "- <a href=\"https://www.smogon.com/forums/showthread.php?t=48782\">What Pokemon have been made?</a><br />" + "- <a href=\"https://www.smogon.com/forums/showthread.php?t=3464513\">Talk about the metagame here</a><br />" + "- <a href=\"https://www.smogon.com/forums/showthread.php?t=3466826\">Practice BW CAP teams</a>" ); }, gennext: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox( "NEXT (also called Gen-NEXT) is a mod that makes changes to the game:<br />" + "- <a href=\"https://github.com/Zarel/Pokemon-Showdown/blob/master/mods/gennext/README.md\">README: overview of NEXT</a><br />" + "Example replays:<br />" + "- <a href=\"https://replay.pokemonshowdown.com/gennextou-120689854\">Zergo vs Mr Weegle Snarf</a><br />" + "- <a href=\"https://replay.pokemonshowdown.com/gennextou-130756055\">NickMP vs Khalogie</a>" ); }, om: 'othermetas', othermetas: function (target, room, user) { if (!this.canBroadcast()) return; target = toId(target); var buffer = ""; var matched = false; if (!target) { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/forums/206/\">Other Metagames Forum</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3505031/\">Other Metagames Index</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3507466/\">Sample teams for entering Other Metagames</a><br />"; } if (target === 'smogondoublesuu' || target === 'doublesuu') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3516968/\">Doubles UU</a><br />"; } if (target === 'smogontriples' || target === 'triples') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3511522/\">Smogon Triples</a><br />"; } if (target === 'omofthemonth' || target === 'omotm' || target === 'month') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3481155/\">OM of the Month</a><br />"; } if (target === 'pokemonthrowback' || target === 'throwback') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3510401/\">Pokémon Throwback</a><br />"; } if (target === 'balancedhackmons' || target === 'bh') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3489849/\">Balanced Hackmons</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3499973/\">Balanced Hackmons Mentoring Program</a><br />"; } if (target === '1v1') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3496773/\">1v1</a><br />"; } if (target === 'monotype') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3493087/\">Monotype</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3517737/\">Monotype Viability Rankings</a><br />"; } if (target === 'tiershift' || target === 'ts') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3508369/\">Tier Shift</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3514386/\">Tier Shift Viability Rankings</a><br />"; } if (target === 'pu') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3513882/\">PU</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3517353/\">PU Viability Rankings</a><br />"; } if (target === 'lcuu') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3516967/\">LC UU</a><br />"; } if (target === 'almostanyability' || target === 'aaa') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3517022/\">Almost Any Ability</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3508794/\">Almost Any Ability Viability Rankings</a><br />"; } if (target === 'stabmons') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3493081/\">STABmons</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3512215/\">STABmons Viability Rankings</a><br />"; } if (target === 'hiddentype') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3516349/\">Hidden Type</a><br />"; } if (target === 'skybattles' || target === 'skybattle') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3493601/\">Sky Battles</a><br />"; } if (target === 'inversebattle' || target === 'inverse') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3518146/\">Inverse Battle</a><br />"; } if (target === '350cup') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3512945/\">350 Cup</a><br />"; } if (target === 'averagemons') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3495527/\">Averagemons</a><br />"; } if (target === 'hackmons' || target === 'purehackmons' || target === 'classichackmons') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3500418/\">Hackmons</a><br />"; } if (target === 'middlecup' || target === 'mc') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3494887/\">Middle Cup</a><br />"; } if (target === 'mashup') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3518763/\">OM Mashup</a><br />"; } if (target === 'glitchmons') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3467120/\">Glitchmons</a><br />"; } if (!matched) { return this.sendReply("The Other Metas entry '" + target + "' was not found. Try /othermetas or /om for general help."); } this.sendReplyBox(buffer); }, /*formats: 'formathelp', formatshelp: 'formathelp', formathelp: function (target, room, user) { if (!this.canBroadcast()) return; if (this.broadcasting && (room.id === 'lobby' || room.battle)) return this.sendReply("This command is too spammy to broadcast in lobby/battles"); var buf = []; var showAll = (target === 'all'); for (var id in Tools.data.Formats) { var format = Tools.data.Formats[id]; if (!format) continue; if (format.effectType !== 'Format') continue; if (!format.challengeShow) continue; if (!showAll && !format.searchShow) continue; buf.push({ name: format.name, gameType: format.gameType || 'singles', mod: format.mod, searchShow: format.searchShow, desc: format.desc || 'No description.' }); } this.sendReplyBox( "Available Formats: (<strong>Bold</strong> formats are on ladder.)<br />" + buf.map(function (data) { var str = ""; // Bold = Ladderable. str += (data.searchShow ? "<strong>" + data.name + "</strong>" : data.name) + ": "; str += "(" + (!data.mod || data.mod === 'base' ? "" : data.mod + " ") + data.gameType + " format) "; str += data.desc; return str; }).join("<br />") ); },*/ roomhelp: function (target, room, user) { if (room.id === 'lobby' || room.battle) return this.sendReply("This command is too spammy for lobby/battles."); if (!this.canBroadcast()) return; this.sendReplyBox('Room drivers (%) can use:<br />' + '- /warn OR /k <em>username</em>: warn a user and show the Pokemon Showdown rules<br />' + '- /mute OR /m <em>username</em>: 7 minute mute<br />' + '- /hourmute OR /hm <em>username</em>: 60 minute mute<br />' + '- /unmute <em>username</em>: unmute<br />' + '- /announce OR /wall <em>message</em>: make an announcement<br />' + '- /modlog <em>username</em>: search the moderator log of the room<br />' + '<br />' + 'Room moderators (@) can also use:<br />' + '- /roomban OR /rb <em>username</em>: bans user from the room<br />' + '- /roomunban <em>username</em>: unbans user from the room<br />' + '- /roomvoice <em>username</em>: appoint a room voice<br />' + '- /roomdevoice <em>username</em>: remove a room voice<br />' + '- /modchat <em>[off/autoconfirmed/+]</em>: set modchat level<br />' + '<br />' + 'Room owners (#) can also use:<br />' + '- /roomdesc <em>description</em>: set the room description on the room join page<br />' + '- /rules <em>rules link</em>: set the room rules link seen when using /rules<br />' + '- /roommod, /roomdriver <em>username</em>: appoint a room moderator/driver<br />' + '- /roomdemod, /roomdedriver <em>username</em>: remove a room moderator/driver<br />' + '- /modchat <em>[%/@/#]</em>: set modchat level<br />' + '- /declare <em>message</em>: make a room declaration<br /><br>' + 'The room founder can also use:<br />' + '- /roomowner <em>username</em><br />' + '- /roomdeowner <em>username</em><br />' + '</div>'); }, restarthelp: function (target, room, user) { if (room.id === 'lobby' && !this.can('lockdown')) return false; if (!this.canBroadcast()) return; this.sendReplyBox('The server is restarting. Things to know:<br />' + '- We wait a few minutes before restarting so people can finish up their battles<br />' + '- The restart itself will take a few seconds<br />' + '- Your ladder ranking and teams will not change<br />' + '- We are restarting to update Gold to a newer version' + '</div>'); }, tc: 'tourhelp', th: 'tourhelp', tourhelp: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<b><font size="4"><font color="green">Tournament Commands List:</font></b><br>' + '<b>/tpoll</b> - Starts a poll asking what tier users want. Requires: +, %, @, &, ~. <br>' + '<b>/tour [tier], [number of people or xminutes]</b> Requires: +, %, @, &, ~.<br>' + '<b>/endtour</b> - Ends the current tournement. Requires: +, %, @, &, ~.<br>' + '<b>/replace [replacee], [replacement]</b> Requires: +, %, @, &, ~.<br>' + '<b>/dq [username]</b> - Disqualifies a user from the tournement. Requires: +, %, @, &, ~.<br>' + '<b>/fj [user]</b> - Forcibily joins a user into the tournement in the sign up phase. Requires: +, %, @, &, ~.<br>' + '<b>/fl [username]</b> - Forcibily makes a user leave the tournement in the sign up phase. Requires: +, %, @, &, ~.<br>' + '<b>/vr</b> - Views the current round in the tournement of whose won and whose lost and who hasn\'t started yet.<br>' + '<b>/toursize [number]</b> - Changes the tour size if you started it with a number instead of a time limit during the sign up phase.<br>' + '<b>/tourtime [xminutes]</b> - Changes the tour time if you started it with a time limit instead of a number during the sign up phase.<br>' + '<b><font size="2"><font color="green">Polls Commands List:</b></font><br>' + '<b>/poll [title], [option],[option], exc...</b> - Starts a poll. Requires: +, %, @, &, ~.<br>' + '<b>/pr</b> - Reminds you of what the current poll is.<br>' + '<b>/endpoll</b> - Ends the current poll. Requires: +, %, @, &, ~.<br>' + '<b>/vote [opinion]</b> - votes for an option of the current poll.<br><br>' + '<i>--Just ask in the lobby if you\'d like a voice or up to start a tourney!</i>'); }, rule: 'rules', rules: function (target, room, user) { if (!target) { if (!this.canBroadcast()) return; this.sendReplyBox("Please follow the rules:<br />" + (room.rulesLink ? "- <a href=\"" + Tools.escapeHTML(room.rulesLink) + "\">" + Tools.escapeHTML(room.title) + " room rules</a><br />" : "") + "- <a href=\"http://goldserver.weebly.com/rules.html\">" + (room.rulesLink ? "Global rules" : "Rules") + "</a>"); return; } if (!this.can('roommod', null, room)) return; if (target.length > 80) { return this.sendReply("Error: Room rules link is too long (must be under 80 characters). You can use a URL shortener to shorten the link."); } room.rulesLink = target.trim(); this.sendReply("(The room rules link is now: " + target + ")"); if (room.chatRoomData) { room.chatRoomData.rulesLink = room.rulesLink; Rooms.global.writeChatRoomData(); } }, faq: function (target, room, user) { if (!this.canBroadcast()) return; target = target.toLowerCase(); var buffer = ""; var matched = false; if (!target || target === 'all') { matched = true; buffer += "<a href=\"https://www.smogon.com/sim/faq\">Frequently Asked Questions</a><br />"; } if (target === 'deviation') { matched = true; buffer += "<a href=\"https://www.smogon.com/sim/faq#deviation\">Why did this user gain or lose so many points?</a><br />"; } if (target === 'doubles' || target === 'triples' || target === 'rotation') { matched = true; buffer += "<a href=\"https://www.smogon.com/sim/faq#doubles\">Can I play doubles/triples/rotation battles here?</a><br />"; } if (target === 'randomcap') { matched = true; buffer += "<a href=\"https://www.smogon.com/sim/faq#randomcap\">What is this fakemon and what is it doing in my random battle?</a><br />"; } if (target === 'restarts') { matched = true; buffer += "<a href=\"https://www.smogon.com/sim/faq#restarts\">Why is the server restarting?</a><br />"; } if (target === 'all' || target === 'star' || target === 'player') { matched = true; buffer += '<a href="http://www.smogon.com/sim/faq#star">Why is there this star (&starf;) in front of my username?</a><br />'; } if (target === 'staff') { matched = true; buffer += '<a href="http://goldserver.weebly.com/how-do-i-get-a-rank.html">Staff FAQ</a><br />'; } if (target === 'autoconfirmed' || target === 'ac') { matched = true; buffer += "A user is autoconfirmed when they have won at least one rated battle and have been registered for a week or longer.<br />"; } if (target === 'all' || target === 'customsymbol' || target === 'cs') { matched = true; buffer += 'A custom symbol will bring your name up to the top of the userlist with a custom symbol next to it. These reset after the server restarts.<br />'; } if (target === 'all' || target === 'league') { matched = true; buffer += 'Welcome to Gold! So, you\'re interested in making or moving a league here? If so, read <a href="http://goldserver.weebly.com/making-a-league.html">this</a> and write down your answers on a <a href="http://pastebin.com">Pastebin</a> and PM it to an admin. Good luck!<br />'; } if (!matched) { return this.sendReply("The FAQ entry '" + target + "' was not found. Try /faq for general help."); } this.sendReplyBox(buffer); }, banlists: 'tiers', tier: 'tiers', tiers: function (target, room, user) { if (!this.canBroadcast()) return; target = toId(target); var buffer = ""; var matched = false; if (!target || target === 'all') { matched = true; buffer += "- <a href=\"https://www.smogon.com/tiers/\">Smogon Tiers</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/tiering-faq.3498332/\">Tiering FAQ</a><br />"; buffer += "- <a href=\"https://www.smogon.com/xyhub/tiers\">The banlists for each tier</a><br />"; } if (target === 'overused' || target === 'ou') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3514144/\">np: OU Stage 6</a><br />"; buffer += "- <a href=\"https://www.smogon.com/dex/xy/tags/ou/\">OU Banlist</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3515714/\">OU Viability Rankings</a><br />"; } if (target === 'ubers' || target === 'uber') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3513127/\">np: XY Ubers Gengarite Suspect Test</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3496305/\">Ubers Viability Rankings</a><br />"; } if (target === 'underused' || target === 'uu') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3516640/\">np: UU Stage 3</a><br />"; buffer += "- <a href=\"https://www.smogon.com/dex/xy/tags/uu/\">UU Banlist</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3516418/\">UU Viability Rankings</a><br />"; } if (target === 'rarelyused' || target === 'ru') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3515615/\">np: RU Stage 4</a><br />"; buffer += "- <a href=\"https://www.smogon.com/dex/xy/tags/ru/\">RU Banlist</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3516783/\">RU Viability Rankings</a><br />"; } if (target === 'neverused' || target === 'nu') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3516675/\">np: NU Stage 2</a><br />"; buffer += "- <a href=\"https://www.smogon.com/dex/xy/tags/nu/\">NU Banlist</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3509494/\">NU Viability Rankings</a><br />"; } if (target === 'littlecup' || target === 'lc') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3496013/\">LC Viability Rankings</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3490462/\">Official LC Banlist</a><br />"; } if (target === 'smogondoubles' || target === 'doubles') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3509279/\">np: Doubles Stage 3.5</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3498688/\">Doubles Banlist</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3496306/\">Doubles Viability Rankings</a><br />"; } if (!matched) { return this.sendReply("The Tiers entry '" + target + "' was not found. Try /tiers for general help."); } this.sendReplyBox(buffer); }, analysis: 'smogdex', strategy: 'smogdex', smogdex: function (target, room, user) { if (!this.canBroadcast()) return; var targets = target.split(','); if (toId(targets[0]) === 'previews') return this.sendReplyBox("<a href=\"https://www.smogon.com/forums/threads/sixth-generation-pokemon-analyses-index.3494918/\">Generation 6 Analyses Index</a>, brought to you by <a href=\"https://www.smogon.com\">Smogon University</a>"); var pokemon = Tools.getTemplate(targets[0]); var item = Tools.getItem(targets[0]); var move = Tools.getMove(targets[0]); var ability = Tools.getAbility(targets[0]); var atLeastOne = false; var generation = (targets[1] || 'xy').trim().toLowerCase(); var genNumber = 6; // var doublesFormats = {'vgc2012':1, 'vgc2013':1, 'vgc2014':1, 'doubles':1}; var doublesFormats = {}; var doublesFormat = (!targets[2] && generation in doublesFormats)? generation : (targets[2] || '').trim().toLowerCase(); var doublesText = ''; if (generation === 'xy' || generation === 'xy' || generation === '6' || generation === 'six') { generation = 'xy'; } else if (generation === 'bw' || generation === 'bw2' || generation === '5' || generation === 'five') { generation = 'bw'; genNumber = 5; } else if (generation === 'dp' || generation === 'dpp' || generation === '4' || generation === 'four') { generation = 'dp'; genNumber = 4; } else if (generation === 'adv' || generation === 'rse' || generation === 'rs' || generation === '3' || generation === 'three') { generation = 'rs'; genNumber = 3; } else if (generation === 'gsc' || generation === 'gs' || generation === '2' || generation === 'two') { generation = 'gs'; genNumber = 2; } else if (generation === 'rby' || generation === 'rb' || generation === '1' || generation === 'one') { generation = 'rb'; genNumber = 1; } else { generation = 'xy'; } if (doublesFormat !== '') { // Smogon only has doubles formats analysis from gen 5 onwards. if (!(generation in {'bw':1, 'xy':1}) || !(doublesFormat in doublesFormats)) { doublesFormat = ''; } else { doublesText = {'vgc2012':"VGC 2012", 'vgc2013':"VGC 2013", 'vgc2014':"VGC 2014", 'doubles':"Doubles"}[doublesFormat]; doublesFormat = '/' + doublesFormat; } } // Pokemon if (pokemon.exists) { atLeastOne = true; if (genNumber < pokemon.gen) { return this.sendReplyBox("" + pokemon.name + " did not exist in " + generation.toUpperCase() + "!"); } // if (pokemon.tier === 'CAP') generation = 'cap'; if (pokemon.tier === 'CAP') return this.sendReply("CAP is not currently supported by Smogon Strategic Pokedex."); var illegalStartNums = {'351':1, '421':1, '487':1, '493':1, '555':1, '647':1, '648':1, '649':1, '681':1}; if (pokemon.isMega || pokemon.num in illegalStartNums) pokemon = Tools.getTemplate(pokemon.baseSpecies); var poke = pokemon.name.toLowerCase().replace(/\ /g, '_').replace(/[^a-z0-9\-\_]+/g, ''); this.sendReplyBox("<a href=\"https://www.smogon.com/dex/" + generation + "/pokemon/" + poke + doublesFormat + "\">" + generation.toUpperCase() + " " + doublesText + " " + pokemon.name + " analysis</a>, brought to you by <a href=\"https://www.smogon.com\">Smogon University</a>"); } // Item if (item.exists && genNumber > 1 && item.gen <= genNumber) { atLeastOne = true; var itemName = item.name.toLowerCase().replace(' ', '_'); this.sendReplyBox("<a href=\"https://www.smogon.com/dex/" + generation + "/items/" + itemName + "\">" + generation.toUpperCase() + " " + item.name + " item analysis</a>, brought to you by <a href=\"https://www.smogon.com\">Smogon University</a>"); } // Ability if (ability.exists && genNumber > 2 && ability.gen <= genNumber) { atLeastOne = true; var abilityName = ability.name.toLowerCase().replace(' ', '_'); this.sendReplyBox("<a href=\"https://www.smogon.com/dex/" + generation + "/abilities/" + abilityName + "\">" + generation.toUpperCase() + " " + ability.name + " ability analysis</a>, brought to you by <a href=\"https://www.smogon.com\">Smogon University</a>"); } // Move if (move.exists && move.gen <= genNumber) { atLeastOne = true; var moveName = move.name.toLowerCase().replace(' ', '_'); this.sendReplyBox("<a href=\"https://www.smogon.com/dex/" + generation + "/moves/" + moveName + "\">" + generation.toUpperCase() + " " + move.name + " move analysis</a>, brought to you by <a href=\"https://www.smogon.com\">Smogon University</a>"); } if (!atLeastOne) { return this.sendReplyBox("Pokemon, item, move, or ability not found for generation " + generation.toUpperCase() + "."); } }, forums: function(target, room, user) { if (!this.canBroadcast()) return; return this.sendReplyBox('Gold Forums can be found <a href="http://w11.zetaboards.com/Goldserverps/index/">here</a>.'); }, regdate: function(target, room, user, connection) { if (!this.canBroadcast()) return; if (!target || target =="0") return this.sendReply('Lol, you can\'t do that, you nub.'); if (!target || target == "." || target == "," || target == "'") return this.sendReply('/regdate - Please specify a valid username.'); //temp fix for symbols that break the command var username = target; target = target.replace(/\s+/g, ''); var util = require("util"), http = require("http"); var options = { host: "www.pokemonshowdown.com", port: 80, path: "/forum/~"+target }; var content = ""; var self = this; var req = http.request(options, function(res) { res.setEncoding("utf8"); res.on("data", function (chunk) { content += chunk; }); res.on("end", function () { content = content.split("<em"); if (content[1]) { content = content[1].split("</p>"); if (content[0]) { content = content[0].split("</em>"); if (content[1]) { regdate = content[1]; data = Tools.escapeHTML(username)+' was registered on'+regdate+'.'; } } } else { data = Tools.escapeHTML(username)+' is not registered.'; } self.sendReplyBox(Tools.escapeHTML(data)); }); }); req.end(); }, league: function(target, room, user) { if (!this.canBroadcast()) return; return this.sendReplyBox('<font size="2"><b><center>Goodra League</font></b></center>' + '★The league consists of 3 Gym Leaders<br /> ' + '★Currently the Champion position is empty.<br/>' + '★Be the first to complete the league, and the spot is yours!<br />' + '★The champion gets a FREE trainer card, custom avatar and global voice!<br />' + '★The Goodra League information can be found <a href="http://goldserver.weebly.com/league.html" >here</a>.<br />' + '★Click <button name=\"joinRoom\" value=\"goodraleague\">here</button> to enter our League\'s room!'); }, stafffaq: function (target, room, user) { if (!this.canBroadcast()) return; return this.sendReplyBox('Click <a href="http://goldserver.weebly.com/how-do-i-get-a-rank-on-gold.html">here</a> to find out about Gold\'s ranks and promotion system.'); }, //Should solve the problem of users not being able to talk in chat unstick: function(target, room, user) { if (!this.can('hotpatch')) return; for (var uid in Users.users) { Users.users[uid].chatQueue = null; Users.users[uid].chatQueueTimeout = null; } }, /********************************************************* * Miscellaneous commands *********************************************************/ //kupo: function(target, room, user){ //if(!this.canBroadcast()|| !user.can('broadcast')) return this.sendReply('/kupo - Access Denied.'); //if(!target) return this.sendReply('Insufficent Parameters.'); //room.add('|c|~kupo|/me '+ target); //this.logModCommand(user.name + ' used /kupo to say ' + target); //}, birkal: function(target, room, user) { this.sendReply("It's not funny anymore."); }, potd: function(target, room, user) { if (!this.can('potd')) return false; Config.potd = target; Simulator.SimulatorProcess.eval('Config.potd = \'' + toId(target) + '\''); if (target) { if (Rooms.lobby) Rooms.lobby.addRaw("<div class=\"broadcast-blue\"><b>The Pokemon of the Day is now " + target + "!</b><br />This Pokemon will be guaranteed to show up in random battles.</div>"); this.logModCommand("The Pokemon of the Day was changed to " + target + " by " + user.name + "."); } else { if (Rooms.lobby) Rooms.lobby.addRaw("<div class=\"broadcast-blue\"><b>The Pokemon of the Day was removed!</b><br />No pokemon will be guaranteed in random battles.</div>"); this.logModCommand("The Pokemon of the Day was removed by " + user.name + "."); } }, nstaffmemberoftheday: 'smotd', nsmotd: function(target, room, user){ if (room.id !== 'lobby') return this.sendReply("This command can only be used in Lobby."); //Users cannot do HTML tags with this command. if (target.indexOf('<img ') > -1) { return this.sendReply('HTML is not supported in this command.') } if (target.indexOf('<a href') > -1) { return this.sendReply('HTML is not supported in this command.') } if (target.indexOf('<font ') > -1) { return this.sendReply('HTML is not supported in this command.') } if (target.indexOf('<marquee') > -1) { return this.sendReply('HTML is not supported in this command.') } if (target.indexOf('<blink') > -1) { return this.sendReply('HTML is not supported in this command.') } if (target.indexOf('<center') > -1) { return this.sendReply('HTML is not supported in this command.') } if(!target) return this.sendReply('/nsmotd needs an Staff Member.'); //Users who are muted cannot use this command. if (target.length > 25) { return this.sendReply('This Staff Member\'s name is too long; it cannot exceed 25 characters.'); } if (!this.canTalk()) return; room.addRaw(''+user.name+'\'s nomination for Staff Member of the Day is: <b><i>' + target +'</i></b>'); }, staffmemberoftheday: 'smotd', smotd: function(target, room, user) { if (room.id !== 'lobby') return this.sendReply("This command can only be used in Lobby."); //User use HTML with this command. if (target.indexOf('<img ') > -1) { return this.sendReply('HTML is not supported in this command.') } if (target.indexOf('<a href') > -1) { return this.sendReply('HTML is not supported in this command.') } if (target.indexOf('<font ') > -1) { return this.sendReply('HTML is not supported in this command.') } if (target.indexOf('<marquee') > -1) { return this.sendReply('HTML is not supported in this command.') } if (target.indexOf('<blink') > -1) { return this.sendReply('HTML is not supported in this command.') } if (target.indexOf('<center') > -1) { return this.sendReply('HTML is not supported in this command.') } if (!target) { //allows user to do /smotd to view who is the Staff Member of the day if people forget. return this.sendReply('The current Staff Member of the Day is: '+room.smotd); } //Users who are muted cannot use this command. if (!this.canTalk()) return; //Only room drivers and up may use this command. if (target.length > 25) { return this.sendReply('This Staff Member\'s name is too long; it cannot exceed 25 characters.'); } if (!this.can('mute', null, room)) return; room.smotd = target; if (target) { //if a user does /smotd (Staff Member name here), then we will display the Staff Member of the Day. room.addRaw('<div class="broadcast-red"><font size="2"><b>The Staff Member of the Day is now <font color="black">'+target+'!</font color></font size></b> <font size="1">(Set by '+user.name+'.)<br />This Staff Member is now the honorary Staff Member of the Day!</div>'); this.logModCommand('The Staff Member of the Day was changed to '+target+' by '+user.name+'.'); } else { //If there is no target, then it will remove the Staff Member of the Day. room.addRaw('<div class="broadcast-green"><b>The Staff Member of the Day was removed!</b><br />There is no longer an Staff Member of the day today!</div>'); this.logModCommand('The Staff Member of the Day was removed by '+user.name+'.'); } }, roll: 'dice', dice: function (target, room, user) { if (!target) return this.parse('/help dice'); if (!this.canBroadcast()) return; var d = target.indexOf("d"); if (d >= 0) { var num = parseInt(target.substring(0, d)); var faces; if (target.length > d) faces = parseInt(target.substring(d + 1)); if (isNaN(num)) num = 1; if (isNaN(faces)) return this.sendReply("The number of faces must be a valid integer."); if (faces < 1 || faces > 1000) return this.sendReply("The number of faces must be between 1 and 1000"); if (num < 1 || num > 20) return this.sendReply("The number of dice must be between 1 and 20"); var rolls = []; var total = 0; for (var i = 0; i < num; ++i) { rolls[i] = (Math.floor(faces * Math.random()) + 1); total += rolls[i]; } return this.sendReplyBox("Random number " + num + "x(1 - " + faces + "): " + rolls.join(", ") + "<br />Total: " + total); } if (target && isNaN(target) || target.length > 21) return this.sendReply("The max roll must be a number under 21 digits."); var maxRoll = (target)? target : 6; var rand = Math.floor(maxRoll * Math.random()) + 1; return this.sendReplyBox("Random number (1 - " + maxRoll + "): " + rand); }, /*/ rollgame: 'dicegame', dicegame: function(target, room, user) { if (!this.canBroadcast()) return; if (Users.get(''+user.name+'').money < target) { return this.sendReply('You cannot wager more than you have, nub.'); } if(!target) return this.sendReply('/dicegame [amount of bucks agreed to wager].'); if (isNaN(target)) { return this.sendReply('Very funny, now use a real number.'); } if (String(target).indexOf('.') >= 0) { return this.sendReply('You cannot wager numbers with decimals.'); } if (target < 0) { return this.sendReply('Number cannot be negative.'); } if (target > 100) { return this.sendReply('Error: You cannot wager over 100 bucks.'); } if (target == 0) { return this.sendReply('Number cannot be 0.'); } var player1 = Math.floor(6 * Math.random()) + 1; var player2 = Math.floor(6 * Math.random()) + 1; var winner = ''; var loser= ''; if (player1 > player2) { winner = 'The <b>winner</b> is <font color="green">'+user.name+'</font>!'; loser = 'Better luck next time, computer!'; return this.add('|c|~crowt|.custom /tb '+user.name+','+target+''); } if (player1 < player2) { winner = 'The <b>winner</b> is <font color="green">Opponent</font>!'; loser = 'Better luck next time, '+user.name+'!'; return this.add('|c|~crowt|.custom /removebucks '+user.name+','+target+''); } if (player1 === player2) { winner = 'It\'s a <b>tie</b>!'; loser = 'Try again!'; } return this.sendReplyBox('<center><font size="4"><b><img border="5" title="Dice Game!"></b></font></center><br />' + '<font color="red">This game is worth '+target+' buck(s).</font><br />' + 'Loser: Tranfer bucks to the winner using /tb [winner], '+target+' <br />' + '<hr>' + ''+user.name+' roll (1-6): '+player1+'<br />' + 'Opponent roll (1-6): '+player2+'<br />' + '<hr>' + 'Winner: '+winner+'<br />' + ''+loser+''); }, */ removebadge: function(target, room, user) { if (!this.can('hotpatch')) return false; target = this.splitTarget(target); var targetUser = this.targetUser; if (!target) return this.sendReply('/removebadge [user], [badge] - Removes a badge from a user.'); if (!targetUser) return this.sendReply('There is no user named '+this.targetUsername+'.'); var self = this; var type_of_badges = ['admin','bot','dev','vip','artist','mod','leader','champ','creator','concun','twinner','goodra','league']; if (type_of_badges.indexOf(target) > -1 == false) return this.sendReply('The badge '+target+' is not a valid badge.'); fs.readFile('badges.txt','utf8', function(err, data) { if (err) console.log(err); var match = false; var currentbadges = ''; var row = (''+data).split('\n'); var line = ''; for (var i = row.length; i > -1; i--) { if (!row[i]) continue; var split = row[i].split(':'); if (split[0] == targetUser.userid) { match = true; currentbadges = split[1]; line = row[i]; } } if (match == true) { if (currentbadges.indexOf(target) > -1 == false) return self.sendReply(currentbadges);//'The user '+targetUser+' does not have the badge.'); var re = new RegExp(line, 'g'); currentbadges = currentbadges.replace(target,''); var newdata = data.replace(re, targetUser.userid+':'+currentbadges); fs.writeFile('badges.txt',newdata, 'utf8', function(err, data) { if (err) console.log(err); return self.sendReply('You have removed the badge '+target+' from the user '+targetUser+'.'); }); } else { return self.sendReply('There is no match for the user '+targetUser+'.'); } }); }, givebadge: function(target, room, user) { if (!this.can('hotpatch')) return false; target = this.splitTarget(target); var targetUser = this.targetUser; if (!targetUser) return this.sendReply('There is no user named '+this.targetUsername+'.'); if (!target) return this.sendReply('/givebadge [user], [badge] - Gives a badge to a user. Requires: &~'); var self = this; var type_of_badges = ['admin','bot','dev','vip','mod','artist','leader','champ','creator','comcun','twinner','league']; if (type_of_badges.indexOf(target) > -1 == false) return this.sendReply('Ther is no badge named '+target+'.'); fs.readFile('badges.txt', 'utf8', function(err, data) { if (err) console.log(err); var currentbadges = ''; var line = ''; var row = (''+data).split('\n'); var match = false; for (var i = row.length; i > -1; i--) { if (!row[i]) continue; var split = row[i].split(':'); if (split[0] == targetUser.userid) { match = true; currentbadges = split[1]; line = row[i]; } } if (match == true) { if (currentbadges.indexOf(target) > -1) return self.sendReply('The user '+targerUser+' already has the badge '+target+'.'); var re = new RegExp(line, 'g'); var newdata = data.replace(re, targetUser.userid+':'+currentbadges+target); fs.writeFile('badges.txt', newdata, function(err, data) { if (err) console.log(err); self.sendReply('You have given the badge '+target+' to the user '+targetUser+'.'); targetUser.send('You have recieved the badge '+target+' from the user '+user.userid+'.'); room.addRaw(targetUser+' has recieved the '+target+' badge from '+user.name); }); } else { fs.appendFile('badges.txt','\n'+targetUser.userid+':'+target, function(err) { if (err) console.log(err); self.sendReply('You have given the badge '+target+' to the user '+targetUser+'.'); targetUser.send('You have recieved the badge '+target+' from the user '+user.userid+'.'); }); } }) }, badgelist: function(target, room, user) { if (!this.canBroadcast()) return; var admin = '<img src="http://www.smogon.com/media/forums/images/badges/sop.png" title="Server Administrator">'; var dev = '<img src="http://www.smogon.com/media/forums/images/badges/factory_foreman.png" title="Gold Developer">'; var creator = '<img src="http://www.smogon.com/media/forums/images/badges/dragon.png" title="Server Creator">'; var comcun = '<img src="http://www.smogon.com/media/forums/images/badges/cc.png" title="Community Contributor">'; var leader = '<img src="http://www.smogon.com/media/forums/images/badges/aop.png" title="Server Leader">'; var mod = '<img src="http://www.smogon.com/media/forums/images/badges/pyramid_king.png" title="Exceptional Staff Member">'; var league ='<img src="http://www.smogon.com/media/forums/images/badges/forumsmod.png" title="Successful League Owner">'; var champ ='<img src="http://www.smogon.com/media/forums/images/badges/forumadmin_alum.png" title="Goodra League Champion">'; var artist ='<img src="http://www.smogon.com/media/forums/images/badges/ladybug.png" title="Artist">'; var twinner='<img src="http://www.smogon.com/media/forums/images/badges/spl.png" title="Badge Tournament Winner">'; var vip ='<img src="http://www.smogon.com/media/forums/images/badges/zeph.png" title="VIP">'; var bot ='<img src="http://www.smogon.com/media/forums/images/badges/mind.png" title="Gold Bot Hoster">'; return this.sendReplyBox('<b>List of Gold Badges</b>:<br> '+admin+' '+dev+' '+creator+' '+comcun+' '+mod+' '+leader+' '+league+' '+champ+' '+artist+' '+twinner+' '+vip+' '+bot+' <br>--Hover over them to see the meaning of each.<br>--Get a badge and get a FREE custom avatar!<br>--Click <a href="http://goldserver.weebly.com/badges.html">here</a> to find out more about how to get a badge.'); }, badges: 'badge', badge: function(target, room, user) { if (!this.canBroadcast()) return; if (target == '') target = user.userid; target = this.splitTarget(target); var targetUser = this.targetUser; var matched = false; if (!targetUser) return false; var admin = '<img src="http://www.smogon.com/media/forums/images/badges/sop.png" title="Server Administrator">'; var dev = '<img src="http://www.smogon.com/media/forums/images/badges/factory_foreman.png" title="Gold Developer">'; var creator = '<img src="http://www.smogon.com/media/forums/images/badges/dragon.png" title="Server Creator">'; var comcun = '<img src="http://www.smogon.com/media/forums/images/badges/cc.png" title="Community Contributor">'; var leader = '<img src="http://www.smogon.com/media/forums/images/badges/aop.png" title="Server Leader">'; var mod = '<img src="http://www.smogon.com/media/forums/images/badges/pyramid_king.png" title="Exceptional Staff Member">'; var league ='<img src="http://www.smogon.com/media/forums/images/badges/forumsmod.png" title="Successful League Owner">'; var champ ='<img src="http://www.smogon.com/media/forums/images/badges/forumadmin_alum.png" title="Goodra League Champion">'; var artist ='<img src="http://www.smogon.com/media/forums/images/badges/ladybug.png" title="Artist">'; var twinner='<img src="http://www.smogon.com/media/forums/images/badges/spl.png" title="Badge Tournament Winner">'; var vip ='<img src="http://www.smogon.com/media/forums/images/badges/zeph.png" title="VIP">'; var bot ='<img src="http://www.smogon.com/media/forums/images/badges/mind.png" title="Gold Bot Hoster">'; var self = this; fs.readFile('badges.txt', 'utf8', function(err, data) { if (err) console.log(err); var row = (''+data).split('\n'); var match = false; var badges; for (var i = row.length; i > -1; i--) { if (!row[i]) continue; var split = row[i].split(':'); if (split[0] == targetUser.userid) { match = true; currentbadges = split[1]; } } if (match == true) { var badgelist = ''; if (currentbadges.indexOf('admin') > -1) badgelist+=' '+admin; if (currentbadges.indexOf('dev') > -1) badgelist+=' '+dev; if (currentbadges.indexOf('creator') > -1) badgelist+=' '+creator; if (currentbadges.indexOf('comcun') > -1) badgelist+=' '+comcun; if (currentbadges.indexOf('leader') > -1) badgelist+=' '+leader; if (currentbadges.indexOf('mod') > -1) badgelist+=' '+mod; if (currentbadges.indexOf('league') > -1) badgelist+=' '+league; if (currentbadges.indexOf('champ') > -1) badgelist+=' '+champ; if (currentbadges.indexOf('artist') > -1) badgelist+=' '+artist; if (currentbadges.indexOf('twinner') > -1) badgelist+=' '+twinner; if (currentbadges.indexOf('vip') > -1) badgelist+=' '+vip; if (currentbadges.indexOf('bot') > -1) badgelist+=' '+bot; self.sendReplyBox(targetUser.userid+"'s badges: "+badgelist); room.update(); } else { self.sendReplyBox('User '+targetUser.userid+' has no badges.'); room.update(); } }); }, helixfossil: 'm8b', helix: 'm8b', magic8ball: 'm8b', m8b: function(target, room, user) { if (!this.canBroadcast()) return; var random = Math.floor(20 * Math.random()) + 1; var results = ''; if (random == 1) { results = 'Signs point to yes.'; } if (random == 2) { results = 'Yes.'; } if (random == 3) { results = 'Reply hazy, try again.'; } if (random == 4) { results = 'Without a doubt.'; } if (random == 5) { results = 'My sources say no.'; } if (random == 6) { results = 'As I see it, yes.'; } if (random == 7) { results = 'You may rely on it.'; } if (random == 8) { results = 'Concentrate and ask again.'; } if (random == 9) { results = 'Outlook not so good.'; } if (random == 10) { results = 'It is decidedly so.'; } if (random == 11) { results = 'Better not tell you now.'; } if (random == 12) { results = 'Very doubtful.'; } if (random == 13) { results = 'Yes - definitely.'; } if (random == 14) { results = 'It is certain.'; } if (random == 15) { results = 'Cannot predict now.'; } if (random == 16) { results = 'Most likely.'; } if (random == 17) { results = 'Ask again later.'; } if (random == 18) { results = 'My reply is no.'; } if (random == 19) { results = 'Outlook good.'; } if (random == 20) { results = 'Don\'t count on it.'; } return this.sendReplyBox(''+results+''); }, hue: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://reactiongifs.me/wp-content/uploads/2013/08/ducks-laughing.gif">'); }, coins: 'coingame', coin: 'coingame', coingame: function(target, room, user) { if (!this.canBroadcast()) return; var random = Math.floor(2 * Math.random()) + 1; var results = ''; if (random == 1) { results = '<img src="http://surviveourcollapse.com/wp-content/uploads/2013/01/zinc.png" width="15%" title="Heads!"><br>It\'s heads!'; } if (random == 2) { results = '<img src="http://upload.wikimedia.org/wikipedia/commons/e/e5/2005_Penny_Rev_Unc_D.png" width="15%" title="Tails!"><br>It\'s tails!'; } return this.sendReplyBox('<center><font size="3"><b>Coin Game!</b></font><br>'+results+''); }, p: 'panagrams', panagrams: function(target, room, user) { if(!user.can('ban')) return; if (room.id == 'lobby') { room.addRaw( '<div class="broadcast-black"><b><center><font size="3">Panagrams has started!</font></b>' + '<center>This is Gold\'s version of anagrams, but with buck prizes! We currently have a random category and a Pokemon category!<br />' + '<button name="joinRoom" value="panagrams" target="_blank">Play now!</button></center></div>' ); } else { room.addRaw( '<div class="broadcast-black"><center><font size="3">A panagrams session is about to begin!</font></center></div>' ); } }, one: function(target, room, user) { if (room.id !== '1v1') return this.sendReply("This command can only be used in 1v1."); if (!this.canBroadcast()) return; var messages = { onevone: 'Global 1v1 bans are: Focus Sash, Sturdy (if doesnt naturally learn it), Sleep, Imposter/imprison, Parental Bond, and level 100 Pokemon only. You are only allowed to use "3 team preview" in all tiers falling under the "1v1 Elimination" tier. All other tiers must be 1 Pokemon only. No switching', reg: 'This is regular 1v1, only bans are Sleep, Ubers (except mega gengar), and ditto (imposter/imprison)', monogen: 'You may only use pokemon, from the gen decided by the !roll command. No ubers, and no sleep', monotype: 'You may only use Pokemon from the type dictated by the !roll command. Here are the list of types. http://bulbapedia.bulbagarden.net/wiki/Type_chart No ubers, and no sleep', monopoke: 'You may only use the Pokemon decided by the !roll command. No ubers, and no sleep', monoletter: 'You may only use Pokemon starting with the same letter dictated by the !roll command. No ubers, and no sleep.', monocolor: 'You may only use Pokemon sharing the same color dictated by the !pickrandom command.', cap: '1v1 using Create-A-Pokemon! No sleep, no focus sash.', megaevo: 'Only bring one Pokemon. http://pastebin.com/d9pJWpya ', bstbased: 'You may only use Pokemon based off or lower than the BST decided by !roll command. ', metronome: 'Only bring one Pokemon. http://pastebin.com/diff.php?i=QPZBDzKb ', twovtwo: 'You may only use 2 pokemon, banlist include: no sleep, no ubers (mega gengar allowed), only one focus sash, no parental bond. ', ouonevone: 'OU choice- The OU version of CC1v1. You use an OU team, and choose one Pokemon in battle. Once that Pokemon faints, you forfeit. You must use the same OU team throughout the tour, but you can change which Pokemon you select to choose. No ubers, no focus sash, no sleep. ', aaa: 'http://www.smogon.com/forums/threads/almost-any-ability-xy-aaa-xy-other-metagame-of-the-month-may.3495737/ You may only use a team of ONE pokemon, banlist in this room for this tier are: Sleep, focus sash, Sturdy, Parental Bond, Huge Power, Pure Power, Imprison, Normalize (on ghosts). ', stabmons: 'http://www.smogon.com/forums/threads/3484106/ You may only use a team of ONE Pokemon. Banlist = Sleep, Focus sash, Huge Power, Pure power, Sturdy, Parental Bond, Ubers. ', abccup: 'http://www.smogon.com/forums/threads/alphabet-cup-other-metagame-of-the-month-march.3498167/ You may only use a team of ONE Pokemon. Banlist = Sleep, Focus sash, Huge Power, Pure power, Sturdy, Parental Bond, Ubers. ', averagemons: 'http://www.smogon.com/forums/threads/averagemons.3495527/ You may only use a team of ONE Pokemon. Banlist = Sleep, Focus sash, Huge Power, Pure power, Sturdy, Parental Bond, Sableye. ', balancedhackmons: 'http://www.smogon.com/forums/threads/3463764/ You may only use a team of ONE Pokemon. Banlist = Sleep, Focus sash, Huge Power, Pure power, Sturdy, Parental Bond, Normalize Ghosts.', retro: 'This is how 1v1 used to be played before 3 team preview. Only bring ONE Pokemon, No sleep, no ubers (except mega gengar), no ditto. ', mediocremons: 'https://www.smogon.com/forums/threads/mediocre-mons-venomoth-banned.3507608/ You many only use a team of ONE Pokemon Banlist = Sleep, Focus sash, Huge Power, Pure power, Sturdy. ', eeveeonly: 'You may bring up to 3 mons that are eeveelutions. No sleep inducing moves. ', tiershift: 'http://www.smogon.com/forums/threads/tier-shift-xy.3508369/ Tiershift 1v1, you may only bring ONE Pokemon. roombans are slaking, sleep, sash, sturdy, ditto ', lc: 'Only use a team of ONE LC Pokemon. No sleep, no sash. ', lcstarters: 'Only use a team of ONE starter Pokemon in LC form. No sleep, no sash, no pikachu, no eevee. ', ubers: 'Only use a team of ONE uber pokemon. No sleep, no sash ', inverse: 'https://www.smogon.com/forums/threads/the-inverse-battle-ǝɯɐƃɐʇǝɯ.3492433/ You may use ONE pokemon. No sleep, no sash, no ubers (except mega gengar). ', }; try { return this.sendReplyBox(messages[target]); } catch (e) { this.sendReply('There is no target named /one '+target); } if (!target) { this.sendReplyBox('Available commands for /one: ' + Object.keys(messages).join(', ')); } }, color: function(target, room, user) { if (!this.canBroadcast()) return; if (target === 'list' || target === 'help' || target === 'options') { return this.sendReplyBox('The random colors are: <b><font color="red">Red</font>, <font color="blue">Blue</font>, <font color="orange">Orange</font>, <font color="green">Green</font>, <font color="teal">Teal</font>, <font color="brown">Brown</font>, <font color="black">Black</font>, <font color="purple">Purple</font>, <font color="pink">Pink</font>, <font color="gray">Gray</font>, <font color="tan">Tan</font>, <font color="gold">Gold</font>, <font color=#CC0000>R</font><font color=#AE1D00>a</font><font color=#913A00>i</font><font color=#745700>n</font><font color=#577400>b</font><font color=#3A9100>o</font><font color=#1DAE00>w</font>.'); } var colors = ['Red','Blue','Orange','Green','Teal','Brown','Black','Purple','Pink','Grey','Tan','Gold']; var results = colors[Math.floor(Math.random()*colors.length)]; if (results == 'Rainbow') { return this.sendReply('The random color is :<b><font color=#CC0000>R</font><font color=#AE1D00>a</font><font color=#913A00>i</font><font color=#745700>n</font><font color=#577400>b</font><font color=#3A9100>o</font><font color=#1DAE00>w</font></b>'); } else { return this.sendReplyBox('The random color is:<b><font color='+results+'>'+results+'</font></b>'); } }, guesscolor: function(target, room, user){ if (!target) return this.sendReply('/guesscolor [color] - Guesses a random color.'); var html = ['<img ','<a href','<font ','<marquee','<blink','<center']; for (var x in html) { if (target.indexOf(html[x]) > -1) return this.sendReply('HTML is not supported in this command.'); } if (target.length > 15) return this.sendReply('This new room suggestion is too long; it cannot exceed 15 characters.'); if (!this.canTalk()) return; Rooms.rooms.room.add('|html|<font size="4"><b>New color guessed!</b></font><br><b>Guessed by:</b> '+user.userid+'<br><b>Color:</b> '+target+''); this.sendReply('Thanks, your new color guess has been sent. We\'ll review your color soon and get back to you. ("'+target+'")'); }, pick: 'pickrandom', pickrandom: function (target, room, user) { var options = target.split(','); if (options.length < 2) return this.parse('/help pick'); if (!this.canBroadcast()) return false; return this.sendReplyBox('<em>We randomly picked:</em> ' + Tools.escapeHTML(options.sample().trim())); }, register: function () { if (!this.canBroadcast()) return; this.sendReplyBox('You will be prompted to register upon winning a rated battle. Alternatively, there is a register button in the <button name="openOptions"><i class="icon-cog"></i> Options</button> menu in the upper right.'); }, lobbychat: function (target, room, user, connection) { if (!Rooms.lobby) return this.popupReply("This server doesn't have a lobby."); target = toId(target); if (target === 'off') { user.leaveRoom(Rooms.lobby, connection.socket); connection.send('|users|'); this.sendReply("You are now blocking lobby chat."); } else { user.joinRoom(Rooms.lobby, connection); this.sendReply("You are now receiving lobby chat."); } }, showimage: function (target, room, user) { if (!target) return this.parse('/help showimage'); if (!this.can('declare', null, room)) return false; if (!this.canBroadcast()) return; var targets = target.split(','); if (targets.length !== 3) { return this.parse('/help showimage'); } this.sendReply('|raw|<img src="' + Tools.escapeHTML(targets[0]) + '" alt="" width="' + toId(targets[1]) + '" height="' + toId(targets[2]) + '" />'); }, htmlbox: function (target, room, user) { if (!target) return this.parse('/help htmlbox'); if (!this.can('declare', null, room)) return; if (!this.canHTML(target)) return; if (!this.canBroadcast('!htmlbox')) return; this.sendReplyBox(target); }, a: function (target, room, user) { if (!this.canTalk()) return; if (!this.can('rawpacket')) return false; // secret sysop command room.add(target); }, /* emotes: 'emoticon', emoticons: 'emoticon', emoticon: function (target, room, user) { if (!this.canBroadcast()) return; var name = Object.keys(Core.emoticons), emoticons = []; var len = name.length; while (len--) { emoticons.push((Core.processEmoticons(name[(name.length-1)-len]) + '&nbsp;' + name[(name.length-1)-len])); } this.sendReplyBox('<b><u>List of emoticons:</b></u> <br/><br/>' + emoticons.join(' ').toString()); }, */ sca: 'customavatar', setcustomavatar: 'customavatar', setcustomavi: 'customavatar', giveavatar: 'customavatar', customavatars: 'customavatar', customavatar: (function () { const script = (function () {/* FILENAME=`mktemp` function cleanup { rm -f $FILENAME } trap cleanup EXIT set -xe timeout 10 wget "$1" -nv -O $FILENAME FRAMES=`identify $FILENAME | wc -l` if [ $FRAMES -gt 1 ]; then EXT=".gif" else EXT=".png" fi timeout 10 convert $FILENAME -layers TrimBounds -coalesce -adaptive-resize 80x80\> -background transparent -gravity center -extent 80x80 "$2$EXT" */}).toString().match(/[^]*\/\*([^]*)\*\/\}$/)[1]; var pendingAdds = {}; return function (target, room, user) { var parts = target.split(','); var cmd = parts[0].trim().toLowerCase(); if (cmd in {'':1, show:1, view:1, display:1}) { var message = ""; for (var a in Config.customavatars) message += "<strong>" + Tools.escapeHTML(a) + ":</strong> " + Tools.escapeHTML(Config.customavatars[a]) + "<br />"; return this.sendReplyBox(message); } if (!this.can('giveavatar') && !user.vip) return false; switch (cmd) { case 'add': case 'set': var userid = toId(parts[1]); if (!this.can('giveavatar') && user.vip && userid !== user.userid) return false; var user = Users.getExact(userid); var avatar = parts.slice(2).join(',').trim(); if (!userid) return this.sendReply("You didn't specify a user."); if (Config.customavatars[userid]) return this.sendReply(userid + " already has a custom avatar."); var hash = require('crypto').createHash('sha512').update(userid + '\u0000' + avatar).digest('hex').slice(0, 8); pendingAdds[hash] = {userid: userid, avatar: avatar}; parts[1] = hash; if (!user) { this.sendReply("Warning: " + userid + " is not online."); this.sendReply("If you want to continue, use: /customavatar forceset, " + hash); return; } // Fallthrough case 'forceset': var hash = parts[1].trim(); if (!pendingAdds[hash]) return this.sendReply("Invalid hash."); var userid = pendingAdds[hash].userid; var avatar = pendingAdds[hash].avatar; delete pendingAdds[hash]; require('child_process').execFile('bash', ['-c', script, '-', avatar, './config/avatars/' + userid], (function (e, out, err) { if (e) { this.sendReply(userid + "'s custom avatar failed to be set. Script output:"); (out + err).split('\n').forEach(this.sendReply.bind(this)); return; } reloadCustomAvatars(); this.sendReply(userid + "'s custom avatar has been set."); Rooms.rooms.staff.add(parts[1]+' has received a custom avatar from '+user.name+'.'); }).bind(this)); break; case 'rem': case 'remove': case 'del': case 'delete': var userid = toId(parts[1]); if (!this.can('giveavatar') && user.vip && userid !== user.userid) return false; if (!Config.customavatars[userid]) return this.sendReply(userid + " does not have a custom avatar."); if (Config.customavatars[userid].toString().split('.').slice(0, -1).join('.') !== userid) return this.sendReply(userid + "'s custom avatar (" + Config.customavatars[userid] + ") cannot be removed with this script."); require('fs').unlink('./config/avatars/' + Config.customavatars[userid], (function (e) { if (e) return this.sendReply(userid + "'s custom avatar (" + Config.customavatars[userid] + ") could not be removed: " + e.toString()); delete Config.customavatars[userid]; this.sendReply(userid + "'s custom avatar removed successfully"); }).bind(this)); break; default: return this.sendReply("Invalid command. Valid commands are `/customavatar set, user, avatar` and `/customavatar delete, user`."); } }; })(), /********************************************************* * Help commands *********************************************************/ commands: 'help', h: 'help', '?': 'help', help: function (target, room, user) { target = target.toLowerCase(); var matched = false; if (target === 'msg' || target === 'pm' || target === 'whisper' || target === 'w') { matched = true; this.sendReply("/msg OR /whisper OR /w [username], [message] - Send a private message."); } if (target === 'r' || target === 'reply') { matched = true; this.sendReply("/reply OR /r [message] - Send a private message to the last person you received a message from, or sent a message to."); } if (target === 'rating' || target === 'ranking' || target === 'rank' || target === 'ladder') { matched = true; this.sendReply("/rating - Get your own rating."); this.sendReply("/rating [username] - Get user's rating."); } if (target === 'nick') { matched = true; this.sendReply("/nick [new username] - Change your username."); } if (target === 'avatar') { matched = true; this.sendReply("/avatar [new avatar number] - Change your trainer sprite."); } if (target === 'whois' || target === 'alts' || target === 'ip' || target === 'rooms') { matched = true; this.sendReply("/whois - Get details on yourself: alts, group, IP address, and rooms."); this.sendReply("/whois [username] - Get details on a username: alts (Requires: % @ & ~), group, IP address (Requires: @ & ~), and rooms."); } if (target === 'data') { matched = true; this.sendReply("/data [pokemon/item/move/ability] - Get details on this pokemon/item/move/ability/nature."); this.sendReply("!data [pokemon/item/move/ability] - Show everyone these details. Requires: + % @ & ~"); } if (target === 'details' || target === 'dt') { matched = true; this.sendReply("/details [pokemon] - Get additional details on this pokemon/item/move/ability/nature."); this.sendReply("!details [pokemon] - Show everyone these details. Requires: + % @ & ~"); } if (target === 'analysis') { matched = true; this.sendReply("/analysis [pokemon], [generation] - Links to the Smogon University analysis for this Pokemon in the given generation."); this.sendReply("!analysis [pokemon], [generation] - Shows everyone this link. Requires: + % @ & ~"); } if (target === 'groups') { matched = true; this.sendReply("/groups - Explains what the + % @ & next to people's names mean."); this.sendReply("!groups - Show everyone that information. Requires: + % @ & ~"); } if (target === 'opensource') { matched = true; this.sendReply("/opensource - Links to PS's source code repository."); this.sendReply("!opensource - Show everyone that information. Requires: + % @ & ~"); } if (target === 'avatars') { matched = true; this.sendReply("/avatars - Explains how to change avatars."); this.sendReply("!avatars - Show everyone that information. Requires: + % @ & ~"); } if (target === 'intro') { matched = true; this.sendReply("/intro - Provides an introduction to competitive pokemon."); this.sendReply("!intro - Show everyone that information. Requires: + % @ & ~"); } if (target === 'cap') { matched = true; this.sendReply("/cap - Provides an introduction to the Create-A-Pokemon project."); this.sendReply("!cap - Show everyone that information. Requires: + % @ & ~"); } if (target === 'om') { matched = true; this.sendReply("/om - Provides links to information on the Other Metagames."); this.sendReply("!om - Show everyone that information. Requires: + % @ & ~"); } if (target === 'learn' || target === 'learnset' || target === 'learnall') { matched = true; this.sendReply("/learn [pokemon], [move, move, ...] - Displays how a Pokemon can learn the given moves, if it can at all."); this.sendReply("!learn [pokemon], [move, move, ...] - Show everyone that information. Requires: + % @ & ~"); } if (target === 'calc' || target === 'calculator') { matched = true; this.sendReply("/calc - Provides a link to a damage calculator"); this.sendReply("!calc - Shows everyone a link to a damage calculator. Requires: + % @ & ~"); } if (target === 'blockchallenges' || target === 'away' || target === 'idle') { matched = true; this.sendReply("/away - Blocks challenges so no one can challenge you. Deactivate it with /back."); } if (target === 'allowchallenges' || target === 'back') { matched = true; this.sendReply("/back - Unlocks challenges so you can be challenged again. Deactivate it with /away."); } if (target === 'faq') { matched = true; this.sendReply("/faq [theme] - Provides a link to the FAQ. Add deviation, doubles, randomcap, restart, or staff for a link to these questions. Add all for all of them."); this.sendReply("!faq [theme] - Shows everyone a link to the FAQ. Add deviation, doubles, randomcap, restart, or staff for a link to these questions. Add all for all of them. Requires: + % @ & ~"); } if (target === 'highlight') { matched = true; this.sendReply("Set up highlights:"); this.sendReply("/highlight add, word - add a new word to the highlight list."); this.sendReply("/highlight list - list all words that currently highlight you."); this.sendReply("/highlight delete, word - delete a word from the highlight list."); this.sendReply("/highlight delete - clear the highlight list"); } if (target === 'timestamps') { matched = true; this.sendReply("Set your timestamps preference:"); this.sendReply("/timestamps [all|lobby|pms], [minutes|seconds|off]"); this.sendReply("all - change all timestamps preferences, lobby - change only lobby chat preferences, pms - change only PM preferences"); this.sendReply("off - set timestamps off, minutes - show timestamps of the form [hh:mm], seconds - show timestamps of the form [hh:mm:ss]"); } if (target === 'effectiveness' || target === 'matchup' || target === 'eff' || target === 'type') { matched = true; this.sendReply("/effectiveness OR /matchup OR /eff OR /type [attack], [defender] - Provides the effectiveness of a move or type on another type or a Pokémon."); this.sendReply("!effectiveness OR !matchup OR !eff OR !type [attack], [defender] - Shows everyone the effectiveness of a move or type on another type or a Pokémon."); } if (target === 'dexsearch' || target === 'dsearch' || target === 'ds') { matched = true; this.sendReply("/dexsearch [type], [move], [move], ... - Searches for Pokemon that fulfill the selected criteria."); this.sendReply("Search categories are: type, tier, color, moves, ability, gen."); this.sendReply("Valid colors are: green, red, blue, white, brown, yellow, purple, pink, gray and black."); this.sendReply("Valid tiers are: Uber/OU/BL/UU/BL2/RU/BL3/NU/PU/LC/CAP."); this.sendReply("Types must be followed by ' type', e.g., 'dragon type'."); this.sendReply("Parameters can be excluded through the use of '!', e.g., '!water type' excludes all water types."); this.sendReply("The parameter 'mega' can be added to search for Mega Evolutions only, and the parameters 'FE' or 'NFE' can be added to search fully or not-fully evolved Pokemon only."); this.sendReply("The order of the parameters does not matter."); } if (target === 'dice' || target === 'roll') { matched = true; this.sendReply("/dice [optional max number] - Randomly picks a number between 1 and 6, or between 1 and the number you choose."); this.sendReply("/dice [number of dice]d[number of sides] - Simulates rolling a number of dice, e.g., /dice 2d4 simulates rolling two 4-sided dice."); } if (target === 'pick' || target === 'pickrandom') { matched = true; this.sendReply("/pick [option], [option], ... - Randomly selects an item from a list containing 2 or more elements."); } if (target === 'join') { matched = true; this.sendReply("/join [roomname] - Attempts to join the room [roomname]."); } if (target === 'ignore') { matched = true; this.sendReply("/ignore [user] - Ignores all messages from the user [user]."); this.sendReply("Note that staff messages cannot be ignored."); } if (target === 'invite') { matched = true; this.sendReply("/invite [username], [roomname] - Invites the player [username] to join the room [roomname]."); } // driver commands if (target === 'lock' || target === 'l') { matched = true; this.sendReply("/lock OR /l [username], [reason] - Locks the user from talking in all chats. Requires: % @ & ~"); } if (target === 'unlock') { matched = true; this.sendReply("/unlock [username] - Unlocks the user. Requires: % @ & ~"); } if (target === 'redirect' || target === 'redir') { matched = true; this.sendReply("/redirect OR /redir [username], [roomname] - Attempts to redirect the user [username] to the room [roomname]. Requires: % @ & ~"); } if (target === 'modnote') { matched = true; this.sendReply("/modnote [note] - Adds a moderator note that can be read through modlog. Requires: % @ & ~"); } if (target === 'forcerename' || target === 'fr') { matched = true; this.sendReply("/forcerename OR /fr [username], [reason] - Forcibly change a user's name and shows them the [reason]. Requires: % @ & ~"); } if (target === 'kickbattle ') { matched = true; this.sendReply("/kickbattle [username], [reason] - Kicks a user from a battle with reason. Requires: % @ & ~"); } if (target === 'warn' || target === 'k') { matched = true; this.sendReply("/warn OR /k [username], [reason] - Warns a user showing them the Pokemon Showdown Rules and [reason] in an overlay. Requires: % @ & ~"); } if (target === 'modlog') { matched = true; this.sendReply("/modlog [roomid|all], [n] - Roomid defaults to current room. If n is a number or omitted, display the last n lines of the moderator log. Defaults to 15. If n is not a number, search the moderator log for 'n' on room's log [roomid]. If you set [all] as [roomid], searches for 'n' on all rooms's logs. Requires: % @ & ~"); } if (target === 'mute' || target === 'm') { matched = true; this.sendReply("/mute OR /m [username], [reason] - Mutes a user with reason for 7 minutes. Requires: % @ & ~"); } if (target === 'hourmute' || target === 'hm') { matched = true; this.sendReply("/hourmute OR /hm [username], [reason] - Mutes a user with reason for an hour. Requires: % @ & ~"); } if (target === 'unmute' || target === 'um') { matched = true; this.sendReply("/unmute [username] - Removes mute from user. Requires: % @ & ~"); } // mod commands if (target === 'roomban' || target === 'rb') { matched = true; this.sendReply("/roomban [username] - Bans the user from the room you are in. Requires: @ & ~"); } if (target === 'roomunban') { matched = true; this.sendReply("/roomunban [username] - Unbans the user from the room you are in. Requires: @ & ~"); } if (target === 'ban' || target === 'b') { matched = true; this.sendReply("/ban OR /b [username], [reason] - Kick user from all rooms and ban user's IP address with reason. Requires: @ & ~"); } if (target === 'unban') { matched = true; this.sendReply("/unban [username] - Unban a user. Requires: @ & ~"); } // RO commands if (target === 'showimage') { matched = true; this.sendReply("/showimage [url], [width], [height] - Show an image. Requires: # & ~"); } if (target === 'roompromote') { matched = true; this.sendReply("/roompromote [username], [group] - Promotes the user to the specified group or next ranked group. Requires: @ # & ~"); } if (target === 'roomdemote') { matched = true; this.sendReply("/roomdemote [username], [group] - Demotes the user to the specified group or previous ranked group. Requires: @ # & ~"); } // leader commands if (target === 'banip') { matched = true; this.sendReply("/banip [ip] - Kick users on this IP or IP range from all rooms and bans it. Accepts wildcards to ban ranges. Requires: & ~"); } if (target === 'unbanip') { matched = true; this.sendReply("/unbanip [ip] - Kick users on this IP or IP range from all rooms and bans it. Accepts wildcards to ban ranges. Requires: & ~"); } if (target === 'unbanall') { matched = true; this.sendReply("/unbanall - Unban all IP addresses. Requires: & ~"); } if (target === 'promote') { matched = true; this.sendReply("/promote [username], [group] - Promotes the user to the specified group or next ranked group. Requires: & ~"); } if (target === 'demote') { matched = true; this.sendReply("/demote [username], [group] - Demotes the user to the specified group or previous ranked group. Requires: & ~"); } if (target === 'forcetie') { matched = true; this.sendReply("/forcetie - Forces the current match to tie. Requires: & ~"); } if (target === 'declare') { matched = true; this.sendReply("/declare [message] - Anonymously announces a message. Requires: & ~"); } // admin commands if (target === 'chatdeclare' || target === 'cdeclare') { matched = true; this.sendReply("/cdeclare [message] - Anonymously announces a message to all chatrooms on the server. Requires: ~"); } if (target === 'globaldeclare' || target === 'gdeclare') { matched = true; this.sendReply("/globaldeclare [message] - Anonymously announces a message to every room on the server. Requires: ~"); } if (target === 'htmlbox') { matched = true; this.sendReply("/htmlbox [message] - Displays a message, parsing HTML code contained. Requires: ~ # with global authority"); } if (target === 'announce' || target === 'wall') { matched = true; this.sendReply("/announce OR /wall [message] - Makes an announcement. Requires: % @ & ~"); } if (target === 'modchat') { matched = true; this.sendReply("/modchat [off/autoconfirmed/+/%/@/&/~] - Set the level of moderated chat. Requires: @ for off/autoconfirmed/+ options, & ~ for all the options"); } if (target === 'hotpatch') { matched = true; this.sendReply("Hot-patching the game engine allows you to update parts of Showdown without interrupting currently-running battles. Requires: ~"); this.sendReply("Hot-patching has greater memory requirements than restarting."); this.sendReply("/hotpatch chat - reload chat-commands.js"); this.sendReply("/hotpatch battles - spawn new simulator processes"); this.sendReply("/hotpatch formats - reload the tools.js tree, rebuild and rebroad the formats list, and also spawn new simulator processes"); } if (target === 'lockdown') { matched = true; this.sendReply("/lockdown - locks down the server, which prevents new battles from starting so that the server can eventually be restarted. Requires: ~"); } if (target === 'kill') { matched = true; this.sendReply("/kill - kills the server. Can't be done unless the server is in lockdown state. Requires: ~"); } if (target === 'loadbanlist') { matched = true; this.sendReply("/loadbanlist - Loads the bans located at ipbans.txt. The command is executed automatically at startup. Requires: ~"); } if (target === 'makechatroom') { matched = true; this.sendReply("/makechatroom [roomname] - Creates a new room named [roomname]. Requires: ~"); } if (target === 'deregisterchatroom') { matched = true; this.sendReply("/deregisterchatroom [roomname] - Deletes room [roomname] after the next server restart. Requires: ~"); } if (target === 'roomowner') { matched = true; this.sendReply("/roomowner [username] - Appoints [username] as a room owner. Removes official status. Requires: ~"); } if (target === 'roomdeowner') { matched = true; this.sendReply("/roomdeowner [username] - Removes [username]'s status as a room owner. Requires: ~"); } if (target === 'privateroom') { matched = true; this.sendReply("/privateroom [on/off] - Makes or unmakes a room private. Requires: ~"); } // overall if (target === 'help' || target === 'h' || target === '?' || target === 'commands') { matched = true; this.sendReply("/help OR /h OR /? - Gives you help."); } if (!target) { this.sendReply("COMMANDS: /nick, /avatar, /rating, /whois, /msg, /reply, /ignore, /away, /back, /timestamps, /highlight"); this.sendReply("INFORMATIONAL COMMANDS: /data, /dexsearch, /groups, /opensource, /avatars, /faq, /rules, /intro, /tiers, /othermetas, /learn, /analysis, /calc (replace / with ! to broadcast. Broadcasting requires: + % @ & ~)"); if (user.group !== Config.groupsranking[0]) { this.sendReply("DRIVER COMMANDS: /warn, /mute, /unmute, /alts, /forcerename, /modlog, /lock, /unlock, /announce, /redirect"); this.sendReply("MODERATOR COMMANDS: /ban, /unban, /ip"); this.sendReply("LEADER COMMANDS: /declare, /forcetie, /forcewin, /promote, /demote, /banip, /unbanall"); } this.sendReply("For an overview of room commands, use /roomhelp"); this.sendReply("For details of a specific command, use something like: /help data"); } else if (!matched) { this.sendReply("Help for the command '" + target + "' was not found. Try /help for general help"); } } };
config/commands.js
/** * Commands * Pokemon Showdown - https://pokemonshowdown.com/ * * These are commands. For instance, you can define the command 'whois' * here, then use it by typing /whois into Pokemon Showdown. * * A command can be in the form: * ip: 'whois', * This is called an alias: it makes it so /ip does the same thing as * /whois. * * But to actually define a command, it's a function: * * allowchallenges: function (target, room, user) { * user.blockChallenges = false; * this.sendReply("You are available for challenges from now on."); * } * * Commands are actually passed five parameters: * function (target, room, user, connection, cmd, message) * Most of the time, you only need the first three, though. * * target = the part of the message after the command * room = the room object the message was sent to * The room name is room.id * user = the user object that sent the message * The user's name is user.name * connection = the connection that the message was sent from * cmd = the name of the command * message = the entire message sent by the user * * If a user types in "/msg zarel, hello" * target = "zarel, hello" * cmd = "msg" * message = "/msg zarel, hello" * * Commands return the message the user should say. If they don't * return anything or return something falsy, the user won't say * anything. * * Commands have access to the following functions: * * this.sendReply(message) * Sends a message back to the room the user typed the command into. * * this.sendReplyBox(html) * Same as sendReply, but shows it in a box, and you can put HTML in * it. * * this.popupReply(message) * Shows a popup in the window the user typed the command into. * * this.add(message) * Adds a message to the room so that everyone can see it. * This is like this.sendReply, except everyone in the room gets it, * instead of just the user that typed the command. * * this.send(message) * Sends a message to the room so that everyone can see it. * This is like this.add, except it's not logged, and users who join * the room later won't see it in the log, and if it's a battle, it * won't show up in saved replays. * You USUALLY want to use this.add instead. * * this.logEntry(message) * Log a message to the room's log without sending it to anyone. This * is like this.add, except no one will see it. * * this.addModCommand(message) * Like this.add, but also logs the message to the moderator log * which can be seen with /modlog. * * this.logModCommand(message) * Like this.addModCommand, except users in the room won't see it. * * this.can(permission) * this.can(permission, targetUser) * Checks if the user has the permission to do something, or if a * targetUser is passed, check if the user has permission to do * it to that user. Will automatically give the user an "Access * denied" message if the user doesn't have permission: use * user.can() if you don't want that message. * * Should usually be near the top of the command, like: * if (!this.can('potd')) return false; * * this.canBroadcast() * Signifies that a message can be broadcast, as long as the user * has permission to. This will check to see if the user used * "!command" instead of "/command". If so, it will check to see * if the user has permission to broadcast (by default, voice+ can), * and return false if not. Otherwise, it will add the message to * the room, and turn on the flag this.broadcasting, so that * this.sendReply and this.sendReplyBox will broadcast to the room * instead of just the user that used the command. * * Should usually be near the top of the command, like: * if (!this.canBroadcast()) return false; * * this.canBroadcast(suppressMessage) * Functionally the same as this.canBroadcast(). However, it * will look as if the user had written the text suppressMessage. * * this.canTalk() * Checks to see if the user can speak in the room. Returns false * if the user can't speak (is muted, the room has modchat on, etc), * or true otherwise. * * Should usually be near the top of the command, like: * if (!this.canTalk()) return false; * * this.canTalk(message, room) * Checks to see if the user can say the message in the room. * If a room is not specified, it will default to the current one. * If it has a falsy value, the check won't be attached to any room. * In addition to running the checks from this.canTalk(), it also * checks to see if the message has any banned words, is too long, * or was just sent by the user. Returns the filtered message, or a * falsy value if the user can't speak. * * Should usually be near the top of the command, like: * target = this.canTalk(target); * if (!target) return false; * * this.parse(message) * Runs the message as if the user had typed it in. * * Mostly useful for giving help messages, like for commands that * require a target: * if (!target) return this.parse('/help msg'); * * After 10 levels of recursion (calling this.parse from a command * called by this.parse from a command called by this.parse etc) * we will assume it's a bug in your command and error out. * * this.targetUserOrSelf(target, exactName) * If target is blank, returns the user that sent the message. * Otherwise, returns the user with the username in target, or * a falsy value if no user with that username exists. * By default, this will track users across name changes. However, * if exactName is true, it will enforce exact matches. * * this.getLastIdOf(user) * Returns the last userid of an specified user. * * this.splitTarget(target, exactName) * Splits a target in the form "user, message" into its * constituent parts. Returns message, and sets this.targetUser to * the user, and this.targetUsername to the username. * By default, this will track users across name changes. However, * if exactName is true, it will enforce exact matches. * * Remember to check if this.targetUser exists before going further. * * Unless otherwise specified, these functions will return undefined, * so you can return this.sendReply or something to send a reply and * stop the command there. * * @license MIT license */ var fs = require('fs'); var badges = fs.createWriteStream('badges.txt',{'flags':'a'}); var commands = exports.commands = { ip: 'whois', rooms: 'whois', alt: 'whois', alts: 'whois', whois: function (target, room, user) { var targetUser = this.targetUserOrSelf(target, user.group === ' '); if (!targetUser) { return this.sendReply("User " + this.targetUsername + " not found."); } this.sendReply("User: " + targetUser.name); if (user.can('alts', targetUser)) { var alts = targetUser.getAlts(true); var output = Object.keys(targetUser.prevNames).join(", "); if (output) this.sendReply("Previous names: " + output); for (var j = 0; j < alts.length; ++j) { var targetAlt = Users.get(alts[j]); if (!targetAlt.named && !targetAlt.connected) continue; if (targetAlt.group === '~' && user.group !== '~') continue; this.sendReply("Alt: " + targetAlt.name); output = Object.keys(targetAlt.prevNames).join(", "); if (output) this.sendReply("Previous names: " + output); } if (targetUser.locked) { this.sendReply("Locked under the username: " + targetUser.locked); } } if (Config.groups[targetUser.group] && Config.groups[targetUser.group].name) { this.sendReply("Group: " + Config.groups[targetUser.group].name + " (" + targetUser.group + ")"); } if (targetUser.goldDev) { this.sendReply('(Gold Development Staff)'); } if (targetUser.goldVip) { this.sendReply('|html|(<font color="gold">VIP</font> User)'); } if (targetUser.isSysop) { this.sendReply("(Pok\xE9mon Showdown System Operator)"); } if (!targetUser.authenticated) { this.sendReply("(Unregistered)"); } if (!this.broadcasting && (user.can('ip', targetUser) || user === targetUser)) { var ips = Object.keys(targetUser.ips); this.sendReply("IP" + ((ips.length > 1) ? "s" : "") + ": " + ips.join(", ") + (user.group !== ' ' && targetUser.latestHost ? "\nHost: " + targetUser.latestHost : "")); } if (targetUser.canCustomSymbol || targetUser.canCustomAvatar || targetUser.canAnimatedAvatar || targetUser.canChatRoom || targetUser.canTrainerCard || targetUser.canFixItem || targetUser.canDecAdvertise || targetUser.canBadge || targetUser.canPOTD || targetUser.canForcerename || targetUser.canMusicBox || targetUser.canCustomEmote) { var i = ''; if (targetUser.canCustomSymbol) i += ' Custom Symbol'; if (targetUser.canCustomAvatar) i += ' Custom Avatar'; if (targetUser.canCustomEmote) i += ' Custom Emote' if (targetUser.canAnimatedAvatar) i += ' Animated Avatar'; if (targetUser.canChatRoom) i += ' Chat Room'; if (targetUser.canTrainerCard) i += ' Trainer Card'; if (targetUser.canFixItem) i += ' Alter card/avatar/music box'; if (targetUser.canDecAdvertise) i += ' Declare Advertise'; if (targetUser.canBadge) i += ' VIP Badge / Global Voice'; if (targetUser.canMusicBox) i += ' Music Box'; if (targetUser.canPOTD) i += ' POTD'; if (targetUser.canForcerename) i += ' Forcerename' this.sendReply('Eligible for: ' + i); } var output = "In rooms: "; var first = true; for (var i in targetUser.roomCount) { if (i === 'global' || Rooms.get(i).isPrivate) continue; if (!first) output += " | "; first = false; output += '<a href="/' + i + '" room="' + i + '">' + i + '</a>'; } if (!targetUser.connected || targetUser.isAway) { this.sendReply('|raw|This user is ' + ((!targetUser.connected) ? '<font color = "red">offline</font>.' : '<font color = "orange">away</font>.')); } this.sendReply('|raw|' + output); }, aip: 'inprivaterooms', awhois: 'inprivaterooms', allrooms: 'inprivaterooms', prooms: 'inprivaterooms', adminwhois: 'inprivaterooms', inprivaterooms: function(target, room, user) { if (!this.can('seeprivaterooms')) return false; var targetUser = this.targetUserOrSelf(target); if (!targetUser) { return this.sendReply('User '+this.targetUsername+' not found.'); } this.sendReply('User: '+targetUser.name); if (user.can('seeprivaterooms',targetUser)) { var alts = targetUser.getAlts(); var output = ''; for (var i in targetUser.prevNames) { if (output) output += ", "; output += targetUser.prevNames[i]; } if (output) this.sendReply('Previous names: '+output); for (var j=0; j<alts.length; j++) { var targetAlt = Users.get(alts[j]); if (!targetAlt.named && !targetAlt.connected) continue; this.sendReply('Alt: '+targetAlt.name); output = ''; for (var i in targetAlt.prevNames) { if (output) output += ", "; output += targetAlt.prevNames[i]; } if (output) this.sendReply('Previous names: '+output); } } if (config.groups[targetUser.group] && config.groups[targetUser.group].name) { this.sendReply('Group: ' + config.groups[targetUser.group].name + ' (' + targetUser.group + ')'); } if (targetUser.isSysop) { this.sendReply('(Pok\xE9mon Showdown System Operator)'); } if (targetUser.goldDev) { this.sendReply('(Gold Development Staff)'); } if (!targetUser.authenticated) { this.sendReply('(Unregistered)'); } if (!this.broadcasting && (user.can('ip', targetUser) || user === targetUser)) { var ips = Object.keys(targetUser.ips); this.sendReply('IP' + ((ips.length > 1) ? 's' : '') + ': ' + ips.join(', ')); } var output = 'In all rooms: '; var first = false; for (var i in targetUser.roomCount) { if (i === 'global' || Rooms.get(i).isPublic) continue; if (!first) output += ' | '; first = false; output += '<a href="/'+i+'" room="'+i+'">'+i+'</a>'; } this.sendReply('|raw|'+output); }, tiertest: function(target, room, user) { if (!this.canBroadcast()) return; var targetId = toId(target); var newTargets = Tools.dataSearch(target); if (newTargets && newTargets.length) { for (var i = 0; i < newTargets.length; i++) { var template = Tools.getTemplate(newTargets[i].species); return this.sendReplyBox("" + template.name + " is in the " + template.tier + " tier."); } } else { return this.sendReplyBox("No Pokemon named '" + target + "' was found."); } }, aotdtest: function (target, room, user) { if (room.id !== 'thestudio') return this.sendReply("This command can only be used in The Studio."); if (!target) { if (!this.canBroadcast()) return; this.sendReplyBox("The current Artist of the Day is: <b>" + Tools.escapeHTML(room.aotd) + "</b>"); return; } if (!this.canTalk()) return; if (target.length > 25) { return this.sendReply("This Artist\'s name is too long; it cannot exceed 25 characters."); } if (!this.can('ban', null, room)) return; room.aotd = target; Rooms.rooms.thestudio.addRaw( '<div class=\"broadcast-green\"><font size="2"><b>The Artist of the Day is now </font><b><font color="black" size="2">' + Tools.escapeHTML(target) + '</font></b><br />' + '(Set by ' + Tools.escapeHTML(user.name) + '.)<br />' + 'This Artist will be posted on our <a href="http://thepsstudioroom.weebly.com/artist-of-the-day.html">Artist of the Day page</a>.</div>' ); room.aotdOn = false; this.logModCommand("The Artist of the Day was changed to " + Tools.escapeHTML(target) + " by " + Tools.escapeHTML(user.name) + "."); }, ipsearch: function (target, room, user) { if (!this.can('rangeban')) return; var atLeastOne = false; this.sendReply("Users with IP " + target + ":"); for (var userid in Users.users) { var curUser = Users.users[userid]; if (curUser.latestIp === target) { this.sendReply((curUser.connected ? " + " : "-") + " " + curUser.name); atLeastOne = true; } } if (!atLeastOne) this.sendReply("No results found."); }, gdeclarered: 'gdeclare', gdeclaregreen: 'gdeclare', gdeclare: function(target, room, user, connection, cmd) { if (!target) return this.parse('/help gdeclare'); if (!this.can('lockdown')) return false; var roomName = (room.isPrivate)? 'a private room' : room.id; if (cmd === 'gdeclare'){ for (var id in Rooms.rooms) { if (id !== 'global') Rooms.rooms[id].addRaw('<div class="broadcast-blue"><b><font size=1><i>Global declare from '+roomName+'<br /></i></font size>'+target+'</b></div>'); } } if (cmd === 'gdeclarered'){ for (var id in Rooms.rooms) { if (id !== 'global') Rooms.rooms[id].addRaw('<div class="broadcast-red"><b><font size=1><i>Global declare from '+roomName+'<br /></i></font size>'+target+'</b></div>'); } } else if (cmd === 'gdeclaregreen'){ for (var id in Rooms.rooms) { if (id !== 'global') Rooms.rooms[id].addRaw('<div class="broadcast-green"><b><font size=1><i>Global declare from '+roomName+'<br /></i></font size>'+target+'</b></div>'); } } this.logEntry(user.name + ' used /gdeclare'); }, declaregreen: 'declarered', declarered: function(target, room, user, connection, cmd) { if (!target) return this.parse('/help declare'); if (!this.can('declare', null, room)) return false; if (!this.canTalk()) return; if (cmd === 'declarered'){ this.add('|raw|<div class="broadcast-red"><b>'+target+'</b></div>'); } else if (cmd === 'declaregreen'){ this.add('|raw|<div class="broadcast-green"><b>'+target+'</b></div>'); } this.logModCommand(user.name+' declared '+target); }, declaregreen: 'declarered', declarered: function(target, room, user, connection, cmd) { if (!target) return this.parse('/help declare'); if (!this.can('declare', null, room)) return false; if (!this.canTalk()) return; if (cmd === 'declarered'){ this.add('|raw|<div class="broadcast-red"><b>'+target+'</b></div>'); } else if (cmd === 'declaregreen'){ this.add('|raw|<div class="broadcast-green"><b>'+target+'</b></div>'); } this.logModCommand(user.name+' declared '+target); }, pdeclare: function(target, room, user, connection, cmd) { if (!target) return this.parse('/help declare'); if (!this.can('declare', null, room)) return false; if (!this.canTalk()) return; if (cmd === 'pdeclare'){ this.add('|raw|<div class="broadcast-purple"><b>'+target+'</b></div>'); } else if (cmd === 'pdeclare'){ this.add('|raw|<div class="broadcast-purple"><b>'+target+'</b></div>'); } this.logModCommand(user.name+' declared '+target); }, k: 'kick', aura: 'kick', kick: function(target, room, user){ if (!this.can('lock')) return false; if (!target) return this.sendReply('/help kick'); if (!this.canTalk()) return false; target = this.splitTarget(target); var targetUser = this.targetUser; if (!targetUser || !targetUser.connected) { return this.sendReply('User '+this.targetUsername+' not found.'); } if (!this.can('lock', targetUser, room)) return false; this.addModCommand(targetUser.name+' was kicked from the room by '+user.name+'.'); targetUser.popup('You were kicked from '+room.id+' by '+user.name+'.'); targetUser.leaveRoom(room.id); }, dm: 'daymute', daymute: function(target, room, user) { if (!target) return this.parse('/help daymute'); if (!this.canTalk()) return false; target = this.splitTarget(target); var targetUser = this.targetUser; if (!targetUser) { return this.sendReply('User '+this.targetUsername+' not found.'); } if (!this.can('mute', targetUser, room)) return false; if (((targetUser.mutedRooms[room.id] && (targetUser.muteDuration[room.id]||0) >= 50*60*1000) || targetUser.locked) && !target) { var problem = ' but was already '+(!targetUser.connected ? 'offline' : targetUser.locked ? 'locked' : 'muted'); return this.privateModCommand('('+targetUser.name+' would be muted by '+user.name+problem+'.)'); } targetUser.popup(user.name+' has muted you for 24 hours. '+target); this.addModCommand(''+targetUser.name+' was muted by '+user.name+' for 24 hours.' + (target ? " (" + target + ")" : "")); var alts = targetUser.getAlts(); if (alts.length) this.addModCommand(""+targetUser.name+"'s alts were also muted: "+alts.join(", ")); targetUser.mute(room.id, 24*60*60*1000, true); }, flogout: 'forcelogout', forcelogout: function(target, room, user) { if(!user.can('hotpatch')) return; if (!this.canTalk()) return false; if (!target) return this.sendReply('/forcelogout [username], [reason] OR /flogout [username], [reason] - You do not have to add a reason'); target = this.splitTarget(target); var targetUser = this.targetUser; if (!targetUser) { return this.sendReply('User '+this.targetUsername+' not found.'); } if (targetUser.can('hotpatch')) return this.sendReply('You cannot force logout another Admin - nice try. Chump.'); this.addModCommand(''+targetUser.name+' was forcibly logged out by '+user.name+'.' + (target ? " (" + target + ")" : "")); targetUser.resetName(); }, declaregreen: 'declarered', declarered: function(target, room, user, connection, cmd) { if (!target) return this.parse('/help declare'); if (!this.can('declare', null, room)) return false; if (!this.canTalk()) return; if (cmd === 'declarered'){ this.add('|raw|<div class="broadcast-red"><b>'+target+'</b></div>'); } else if (cmd === 'declaregreen'){ this.add('|raw|<div class="broadcast-green"><b>'+target+'</b></div>'); } this.logModCommand(user.name+' declared '+target); }, gdeclarered: 'gdeclare', gdeclaregreen: 'gdeclare', gdeclare: function(target, room, user, connection, cmd) { if (!target) return this.parse('/help gdeclare'); if (!this.can('lockdown')) return false; var roomName = (room.isPrivate)? 'a private room' : room.id; if (cmd === 'gdeclare'){ for (var id in Rooms.rooms) { if (id !== 'global') Rooms.rooms[id].addRaw('<div class="broadcast-blue"><b><font size=1><i>Global declare from '+roomName+'<br /></i></font size>'+target+'</b></div>'); } } if (cmd === 'gdeclarered'){ for (var id in Rooms.rooms) { if (id !== 'global') Rooms.rooms[id].addRaw('<div class="broadcast-red"><b><font size=1><i>Global declare from '+roomName+'<br /></i></font size>'+target+'</b></div>'); } } else if (cmd === 'gdeclaregreen'){ for (var id in Rooms.rooms) { if (id !== 'global') Rooms.rooms[id].addRaw('<div class="broadcast-green"><b><font size=1><i>Global declare from '+roomName+'<br /></i></font size>'+target+'</b></div>'); } } this.logModCommand(user.name+' globally declared '+target); }, sd: 'declaremod', staffdeclare: 'declaremod', modmsg: 'declaremod', moddeclare: 'declaremod', declaremod: function(target, room, user) { if (!target) return this.sendReply('/declaremod [message] - Also /moddeclare and /modmsg'); if (!this.can('declare', null, room)) return false; if (!this.canTalk()) return; this.privateModCommand('|raw|<div class="broadcast-red"><b><font size=1><i>Private Auth (Driver +) declare from '+user.name+'<br /></i></font size>'+target+'</b></div>'); this.logModCommand(user.name+' mod declared '+target); }, /********************************************************* * Shortcuts *********************************************************/ invite: function (target, room, user) { target = this.splitTarget(target); if (!this.targetUser) { return this.sendReply("User " + this.targetUsername + " not found."); } var targetRoom = (target ? Rooms.search(target) : room); if (!targetRoom) { return this.sendReply("Room " + target + " not found."); } return this.parse('/msg ' + this.targetUsername + ', /invite ' + targetRoom.id); }, /********************************************************* * Informational commands *********************************************************/ pstats: 'data', stats: 'data', dex: 'data', pokedex: 'data', details: 'data', dt: 'data', data: function (target, room, user, connection, cmd) { if (!this.canBroadcast()) return; var buffer = ''; var targetId = toId(target); if (targetId === '' + parseInt(targetId)) { for (var p in Tools.data.Pokedex) { var pokemon = Tools.getTemplate(p); if (pokemon.num === parseInt(target)) { target = pokemon.species; targetId = pokemon.id; break; } } } var newTargets = Tools.dataSearch(target); var showDetails = (cmd === 'dt' || cmd === 'details'); if (newTargets && newTargets.length) { for (var i = 0; i < newTargets.length; ++i) { if (newTargets[i].id !== targetId && !Tools.data.Aliases[targetId] && !i) { buffer = "No Pokemon, item, move, ability or nature named '" + target + "' was found. Showing the data of '" + newTargets[0].name + "' instead.\n"; } if (newTargets[i].searchType === 'nature') { buffer += "" + newTargets[i].name + " nature: "; if (newTargets[i].plus) { var statNames = {'atk': "Attack", 'def': "Defense", 'spa': "Special Attack", 'spd': "Special Defense", 'spe': "Speed"}; buffer += "+10% " + statNames[newTargets[i].plus] + ", -10% " + statNames[newTargets[i].minus] + "."; } else { buffer += "No effect."; } return this.sendReply(buffer); } else { buffer += '|c|~|/data-' + newTargets[i].searchType + ' ' + newTargets[i].name + '\n'; } } } else { return this.sendReply("No Pokemon, item, move, ability or nature named '" + target + "' was found. (Check your spelling?)"); } if (showDetails) { var details; if (newTargets[0].searchType === 'pokemon') { var pokemon = Tools.getTemplate(newTargets[0].name); var weighthit = 20; if (pokemon.weightkg >= 200) { weighthit = 120; } else if (pokemon.weightkg >= 100) { weighthit = 100; } else if (pokemon.weightkg >= 50) { weighthit = 80; } else if (pokemon.weightkg >= 25) { weighthit = 60; } else if (pokemon.weightkg >= 10) { weighthit = 40; } details = { "Dex#": pokemon.num, "Height": pokemon.heightm + " m", "Weight": pokemon.weightkg + " kg <em>(" + weighthit + " BP)</em>", "Dex Colour": pokemon.color, "Egg Group(s)": pokemon.eggGroups.join(", ") }; if (!pokemon.evos.length) { details["<font color=#585858>Does Not Evolve</font>"] = ""; // this line exists on main } else { details["Evolution"] = pokemon.evos.map(function (evo) { evo = Tools.getTemplate(evo); return evo.name + " (" + evo.evoLevel + ")"; }).join(", "); } } else if (newTargets[0].searchType === 'move') { var move = Tools.getMove(newTargets[0].name); details = { "Priority": move.priority }; if (move.secondary || move.secondaries) details["<font color=black>&#10003; Secondary Effect</font>"] = ""; if (move.isContact) details["<font color=black>&#10003; Contact</font>"] = ""; if (move.isSoundBased) details["<font color=black>&#10003; Sound</font>"] = ""; if (move.isBullet) details["<font color=black>&#10003; Bullet</font>"] = ""; if (move.isPulseMove) details["<font color=black>&#10003; Pulse</font>"] = ""; details["Target"] = { 'normal': "Adjacent Pokemon", 'self': "Self", 'adjacentAlly': "Single Ally", 'allAdjacentFoes': "Adjacent Foes", 'foeSide': "All Foes", 'allySide': "All Allies", 'allAdjacent': "All Adjacent Pokemon", 'any': "Any Pokemon", 'all': "All Pokemon" }[move.target] || "Unknown"; } else if (newTargets[0].searchType === 'item') { var item = Tools.getItem(newTargets[0].name); details = {}; if (item.fling) { details["Fling Base Power"] = item.fling.basePower; if (item.fling.status) details["Fling Effect"] = item.fling.status; if (item.fling.volatileStatus) details["Fling Effect"] = item.fling.volatileStatus; if (item.isBerry) details["Fling Effect"] = "Activates effect of berry on target."; if (item.id === 'whiteherb') details["Fling Effect"] = "Removes all negative stat levels on the target."; if (item.id === 'mentalherb') details["Fling Effect"] = "Removes the effects of infatuation, Taunt, Encore, Torment, Disable, and Cursed Body on the target."; } if (!item.fling) details["Fling"] = "This item cannot be used with Fling"; if (item.naturalGift) { details["Natural Gift Type"] = item.naturalGift.type; details["Natural Gift BP"] = item.naturalGift.basePower; } } else { details = {}; } buffer += '|raw|<font size="1">' + Object.keys(details).map(function (detail) { return '<font color=#585858>' + detail + (details[detail] !== '' ? ':</font> ' + details[detail] : '</font>'); }).join("&nbsp;|&ThickSpace;") + '</font>'; } this.sendReply(buffer); }, ds: 'dexsearch', dsearch: 'dexsearch', dexsearch: function (target, room, user) { if (!this.canBroadcast()) return; if (!target) return this.parse('/help dexsearch'); var targets = target.split(','); var searches = {}; var allTiers = {'uber':1, 'ou':1, 'uu':1, 'lc':1, 'cap':1, 'bl':1, 'bl2':1, 'ru':1, 'bl3':1, 'nu':1, 'pu':1}; var allColours = {'green':1, 'red':1, 'blue':1, 'white':1, 'brown':1, 'yellow':1, 'purple':1, 'pink':1, 'gray':1, 'black':1}; var showAll = false; var megaSearch = null; var feSearch = null; // search for fully evolved pokemon only var recoverySearch = null; var output = 10; for (var i in targets) { var isNotSearch = false; target = targets[i].trim().toLowerCase(); if (target.slice(0, 1) === '!') { isNotSearch = true; target = target.slice(1); } var targetAbility = Tools.getAbility(targets[i]); if (targetAbility.exists) { if (!searches['ability']) searches['ability'] = {}; if (Object.count(searches['ability'], true) === 1 && !isNotSearch) return this.sendReplyBox("Specify only one ability."); if ((searches['ability'][targetAbility.name] && isNotSearch) || (searches['ability'][targetAbility.name] === false && !isNotSearch)) return this.sendReplyBox("A search cannot both exclude and include an ability."); searches['ability'][targetAbility.name] = !isNotSearch; continue; } if (target in allTiers) { if (!searches['tier']) searches['tier'] = {}; if ((searches['tier'][target] && isNotSearch) || (searches['tier'][target] === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include a tier.'); searches['tier'][target] = !isNotSearch; continue; } if (target in allColours) { if (!searches['color']) searches['color'] = {}; if ((searches['color'][target] && isNotSearch) || (searches['color'][target] === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include a color.'); searches['color'][target] = !isNotSearch; continue; } var targetInt = parseInt(target); if (0 < targetInt && targetInt < 7) { if (!searches['gen']) searches['gen'] = {}; if ((searches['gen'][target] && isNotSearch) || (searches['gen'][target] === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include a generation.'); searches['gen'][target] = !isNotSearch; continue; } if (target === 'all') { if (this.broadcasting) { return this.sendReplyBox("A search with the parameter 'all' cannot be broadcast."); } showAll = true; continue; } if (target === 'megas' || target === 'mega') { if ((megaSearch && isNotSearch) || (megaSearch === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include Mega Evolutions.'); megaSearch = !isNotSearch; continue; } if (target === 'fe' || target === 'fullyevolved' || target === 'nfe' || target === 'notfullyevolved') { if (target === 'nfe' || target === 'notfullyevolved') isNotSearch = !isNotSearch; if ((feSearch && isNotSearch) || (feSearch === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include fully evolved Pokémon.'); feSearch = !isNotSearch; continue; } if (target === 'recovery') { if ((recoverySearch && isNotSearch) || (recoverySearch === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and recovery moves.'); if (!searches['recovery']) searches['recovery'] = {}; recoverySearch = !isNotSearch; continue; } var targetMove = Tools.getMove(target); if (targetMove.exists) { if (!searches['moves']) searches['moves'] = {}; if (Object.count(searches['moves'], true) === 4 && !isNotSearch) return this.sendReplyBox("Specify a maximum of 4 moves."); if ((searches['moves'][targetMove.name] && isNotSearch) || (searches['moves'][targetMove.name] === false && !isNotSearch)) return this.sendReplyBox("A search cannot both exclude and include a move."); searches['moves'][targetMove.name] = !isNotSearch; continue; } if (target.indexOf(' type') > -1) { target = target.charAt(0).toUpperCase() + target.slice(1, target.indexOf(' type')); if (target in Tools.data.TypeChart) { if (!searches['types']) searches['types'] = {}; if (Object.count(searches['types'], true) === 2 && !isNotSearch) return this.sendReplyBox("Specify a maximum of two types."); if ((searches['types'][target] && isNotSearch) || (searches['types'][target] === false && !isNotSearch)) return this.sendReplyBox("A search cannot both exclude and include a type."); searches['types'][target] = !isNotSearch; continue; } } return this.sendReplyBox("'" + Tools.escapeHTML(target) + "' could not be found in any of the search categories."); } if (showAll && Object.size(searches) === 0 && megaSearch === null && feSearch === null) return this.sendReplyBox("No search parameters other than 'all' were found. Try '/help dexsearch' for more information on this command."); var dex = {}; for (var pokemon in Tools.data.Pokedex) { var template = Tools.getTemplate(pokemon); var megaSearchResult = (megaSearch === null || (megaSearch === true && template.isMega) || (megaSearch === false && !template.isMega)); var feSearchResult = (feSearch === null || (feSearch === true && !template.evos.length) || (feSearch === false && template.evos.length)); if (template.tier !== 'Unreleased' && template.tier !== 'Illegal' && (template.tier !== 'CAP' || (searches['tier'] && searches['tier']['cap'])) && megaSearchResult && feSearchResult) { dex[pokemon] = template; } } for (var search in {'moves':1, 'recovery':1, 'types':1, 'ability':1, 'tier':1, 'gen':1, 'color':1}) { if (!searches[search]) continue; switch (search) { case 'types': for (var mon in dex) { if (Object.count(searches[search], true) === 2) { if (!(searches[search][dex[mon].types[0]]) || !(searches[search][dex[mon].types[1]])) delete dex[mon]; } else { if (searches[search][dex[mon].types[0]] === false || searches[search][dex[mon].types[1]] === false || (Object.count(searches[search], true) > 0 && (!(searches[search][dex[mon].types[0]]) && !(searches[search][dex[mon].types[1]])))) delete dex[mon]; } } break; case 'tier': for (var mon in dex) { if ('lc' in searches[search]) { // some LC legal Pokemon are stored in other tiers (Ferroseed/Murkrow etc) // this checks for LC legality using the going criteria, instead of dex[mon].tier var isLC = (dex[mon].evos && dex[mon].evos.length > 0) && !dex[mon].prevo && Tools.data.Formats['lc'].banlist.indexOf(dex[mon].species) === -1; if ((searches[search]['lc'] && !isLC) || (!searches[search]['lc'] && isLC)) { delete dex[mon]; continue; } } if (searches[search][String(dex[mon][search]).toLowerCase()] === false) { delete dex[mon]; } else if (Object.count(searches[search], true) > 0 && !searches[search][String(dex[mon][search]).toLowerCase()]) delete dex[mon]; } break; case 'gen': case 'color': for (var mon in dex) { if (searches[search][String(dex[mon][search]).toLowerCase()] === false) { delete dex[mon]; } else if (Object.count(searches[search], true) > 0 && !searches[search][String(dex[mon][search]).toLowerCase()]) delete dex[mon]; } break; case 'ability': for (var mon in dex) { for (var ability in searches[search]) { var needsAbility = searches[search][ability]; var hasAbility = Object.count(dex[mon].abilities, ability) > 0; if (hasAbility !== needsAbility) { delete dex[mon]; break; } } } break; case 'moves': for (var mon in dex) { var template = Tools.getTemplate(dex[mon].id); if (!template.learnset) template = Tools.getTemplate(template.baseSpecies); if (!template.learnset) continue; for (var i in searches[search]) { var move = Tools.getMove(i); if (!move.exists) return this.sendReplyBox("'" + move + "' is not a known move."); var prevoTemp = Tools.getTemplate(template.id); while (prevoTemp.prevo && prevoTemp.learnset && !(prevoTemp.learnset[move.id])) { prevoTemp = Tools.getTemplate(prevoTemp.prevo); } var canLearn = (prevoTemp.learnset.sketch && !(move.id in {'chatter':1, 'struggle':1, 'magikarpsrevenge':1})) || prevoTemp.learnset[move.id]; if ((!canLearn && searches[search][i]) || (searches[search][i] === false && canLearn)) delete dex[mon]; } } break; case 'recovery': for (var mon in dex) { var template = Tools.getTemplate(dex[mon].id); if (!template.learnset) template = Tools.getTemplate(template.baseSpecies); if (!template.learnset) continue; var recoveryMoves = ["recover", "roost", "moonlight", "morningsun", "synthesis", "milkdrink", "slackoff", "softboiled", "wish", "healorder"]; var canLearn = false; for (var i = 0; i < recoveryMoves.length; i++) { var prevoTemp = Tools.getTemplate(template.id); while (prevoTemp.prevo && prevoTemp.learnset && !(prevoTemp.learnset[recoveryMoves[i]])) { prevoTemp = Tools.getTemplate(prevoTemp.prevo); } canLearn = (prevoTemp.learnset.sketch) || prevoTemp.learnset[recoveryMoves[i]]; if (canLearn) break; } if ((!canLearn && searches[search]) || (searches[search] === false && canLearn)) delete dex[mon]; } break; default: return this.sendReplyBox("Something broke! PM TalkTakesTime here or on the Smogon forums with the command you tried."); } } var results = Object.keys(dex).map(function (speciesid) {return dex[speciesid].species;}); results = results.filter(function (species) { var template = Tools.getTemplate(species); return !(species !== template.baseSpecies && results.indexOf(template.baseSpecies) > -1); }); var resultsStr = ""; if (results.length > 0) { if (showAll || results.length <= output) { results.sort(); resultsStr = results.join(", "); } else { results.randomize(); resultsStr = results.slice(0, 10).join(", ") + ", and " + string(results.length - output) + " more. Redo the search with 'all' as a search parameter to show all results."; } } else { resultsStr = "No Pokémon found."; } return this.sendReplyBox(resultsStr); }, learnset: 'learn', learnall: 'learn', learn5: 'learn', g6learn: 'learn', learn: function (target, room, user, connection, cmd) { if (!target) return this.parse('/help learn'); if (!this.canBroadcast()) return; var lsetData = {set:{}}; var targets = target.split(','); var template = Tools.getTemplate(targets[0]); var move = {}; var problem; var all = (cmd === 'learnall'); if (cmd === 'learn5') lsetData.set.level = 5; if (cmd === 'g6learn') lsetData.format = {noPokebank: true}; if (!template.exists) { return this.sendReply("Pokemon '" + template.id + "' not found."); } if (targets.length < 2) { return this.sendReply("You must specify at least one move."); } for (var i = 1, len = targets.length; i < len; ++i) { move = Tools.getMove(targets[i]); if (!move.exists) { return this.sendReply("Move '" + move.id + "' not found."); } problem = TeamValidator.checkLearnsetSync(null, move, template, lsetData); if (problem) break; } var buffer = template.name + (problem ? " <span class=\"message-learn-cannotlearn\">can't</span> learn " : " <span class=\"message-learn-canlearn\">can</span> learn ") + (targets.length > 2 ? "these moves" : move.name); if (!problem) { var sourceNames = {E:"egg", S:"event", D:"dream world"}; if (lsetData.sources || lsetData.sourcesBefore) buffer += " only when obtained from:<ul class=\"message-learn-list\">"; if (lsetData.sources) { var sources = lsetData.sources.sort(); var prevSource; var prevSourceType; var prevSourceCount = 0; for (var i = 0, len = sources.length; i < len; ++i) { var source = sources[i]; if (source.substr(0, 2) === prevSourceType) { if (prevSourceCount < 0) { buffer += ": " + source.substr(2); } else if (all || prevSourceCount < 3) { buffer += ", " + source.substr(2); } else if (prevSourceCount === 3) { buffer += ", ..."; } ++prevSourceCount; continue; } prevSourceType = source.substr(0, 2); prevSourceCount = source.substr(2) ? 0 : -1; buffer += "<li>gen " + source.substr(0, 1) + " " + sourceNames[source.substr(1, 1)]; if (prevSourceType === '5E' && template.maleOnlyHidden) buffer += " (cannot have hidden ability)"; if (source.substr(2)) buffer += ": " + source.substr(2); } } if (lsetData.sourcesBefore) buffer += "<li>any generation before " + (lsetData.sourcesBefore + 1); buffer += "</ul>"; } this.sendReplyBox(buffer); }, weak: 'weakness', resist: 'weakness', weakness: function (target, room, user) { if (!this.canBroadcast()) return; var targets = target.split(/[ ,\/]/); var pokemon = Tools.getTemplate(target); var type1 = Tools.getType(targets[0]); var type2 = Tools.getType(targets[1]); if (pokemon.exists) { target = pokemon.species; } else if (type1.exists && type2.exists) { pokemon = {types: [type1.id, type2.id]}; target = type1.id + "/" + type2.id; } else if (type1.exists) { pokemon = {types: [type1.id]}; target = type1.id; } else { return this.sendReplyBox("" + Tools.escapeHTML(target) + " isn't a recognized type or pokemon."); } var weaknesses = []; var resistances = []; var immunities = []; Object.keys(Tools.data.TypeChart).forEach(function (type) { var notImmune = Tools.getImmunity(type, pokemon); if (notImmune) { var typeMod = Tools.getEffectiveness(type, pokemon); switch (typeMod) { case 1: weaknesses.push(type); break; case 2: weaknesses.push("<b>" + type + "</b>"); break; case -1: resistances.push(type); break; case -2: resistances.push("<b>" + type + "</b>"); break; } } else { immunities.push(type); } }); var buffer = []; buffer.push(pokemon.exists ? "" + target + ' (ignoring abilities):' : '' + target + ':'); buffer.push('<span class=\"message-effect-weak\">Weaknesses</span>: ' + (weaknesses.join(', ') || 'None')); buffer.push('<span class=\"message-effect-resist\">Resistances</span>: ' + (resistances.join(', ') || 'None')); buffer.push('<span class=\"message-effect-immune\">Immunities</span>: ' + (immunities.join(', ') || 'None')); this.sendReplyBox(buffer.join('<br>')); }, eff: 'effectiveness', type: 'effectiveness', matchup: 'effectiveness', effectiveness: function (target, room, user) { var targets = target.split(/[,/]/).slice(0, 2); if (targets.length !== 2) return this.sendReply("Attacker and defender must be separated with a comma."); var searchMethods = {'getType':1, 'getMove':1, 'getTemplate':1}; var sourceMethods = {'getType':1, 'getMove':1}; var targetMethods = {'getType':1, 'getTemplate':1}; var source; var defender; var foundData; var atkName; var defName; for (var i = 0; i < 2; ++i) { var method; for (method in searchMethods) { foundData = Tools[method](targets[i]); if (foundData.exists) break; } if (!foundData.exists) return this.parse('/help effectiveness'); if (!source && method in sourceMethods) { if (foundData.type) { source = foundData; atkName = foundData.name; } else { source = foundData.id; atkName = foundData.id; } searchMethods = targetMethods; } else if (!defender && method in targetMethods) { if (foundData.types) { defender = foundData; defName = foundData.species + " (not counting abilities)"; } else { defender = {types: [foundData.id]}; defName = foundData.id; } searchMethods = sourceMethods; } } if (!this.canBroadcast()) return; var factor = 0; if (Tools.getImmunity(source.type || source, defender)) { if (source.effectType !== 'Move' || source.basePower || source.basePowerCallback) { factor = Math.pow(2, Tools.getEffectiveness(source, defender)); } else { factor = 1; } } this.sendReplyBox("" + atkName + " is " + factor + "x effective against " + defName + "."); }, uptime: (function(){ function formatUptime(uptime) { if (uptime > 24*60*60) { var uptimeText = ""; var uptimeDays = Math.floor(uptime/(24*60*60)); uptimeText = uptimeDays + " " + (uptimeDays == 1 ? "day" : "days"); var uptimeHours = Math.floor(uptime/(60*60)) - uptimeDays*24; if (uptimeHours) uptimeText += ", " + uptimeHours + " " + (uptimeHours == 1 ? "hour" : "hours"); return uptimeText; } else { return uptime.seconds().duration(); } } return function(target, room, user) { if (!this.canBroadcast()) return; var uptime = process.uptime(); this.sendReplyBox("Uptime: <b>" + formatUptime(uptime) + "</b>" + (global.uptimeRecord ? "<br /><font color=\"green\">Record: <b>" + formatUptime(global.uptimeRecord) + "</b></font>" : "")); }; })(), groups: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox( "+ <b>Voice</b> - They can use ! commands like !groups, and talk during moderated chat<br />" + "% <b>Driver</b> - The above, and they can mute. Global % can also lock users and check for alts<br />" + "@ <b>Moderator</b> - The above, and they can ban users<br />" + "&amp; <b>Leader</b> - The above, and they can promote to moderator and force ties<br />" + "# <b>Room Owner</b> - They are leaders of the room and can almost totally control it<br />" + "~ <b>Administrator</b> - They can do anything, like change what this message says" ); }, staff: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('The staff forums can be found <a href="https://groups.google.com/forum/#!forum/gold-staff">here</a>.'); }, whosgotthemoneyz: 'richestuser', richestuser: function(target, room, user) { if (!this.canBroadcast()) return; var data = fs.readFileSync('config/money.csv','utf8'); var row = (''+data).split("\n"); var userids = {id:[],money:[]}; var highest = {id:[],money:[]}; var size = 0; var amounts = []; for (var i = row.length; i > -1; i--) { if (!row[i]) continue; var parts = row[i].split(","); userids.id[i] = parts[0]; userids.money[i] = Number(parts[1]); size++; if (isNaN(parts[1]) || parts[1] === 'Infinity') userids.money[i] = 0; } for (var i=0; i<10;i++) { var tempHighest = 0; for (var x=0;x<size;x++) { if (userids.money[x] > tempHighest) tempHighest = userids.money[x]; } for (var x=0;x<size;x++) { var found = false; if (userids.money[x] === tempHighest && !found) { highest.id[i] = userids.id[x]; highest.money[i] = userids.money[x]; userids.id[x]; userids.money[x] = 0; found = true; } } } return this.sendReplyBox('<b>The richest users are:</b>' + '<br>1. ' + highest.id[0] + ': ' + highest.money[0] + '<br>2. ' + highest.id[1] + ': ' + highest.money[1] + '<br>3. ' + highest.id[2] + ': ' + highest.money[2] + '<br>4. ' + highest.id[3] + ': ' + highest.money[3] + '<br>5. ' + highest.id[4] + ': ' + highest.money[4] + '<br>6. ' + highest.id[5] + ': ' + highest.money[5] + '<br>7. ' + highest.id[6] + ': ' + highest.money[6] + '<br>8. ' + highest.id[7] + ': ' + highest.money[7] + '<br>9. ' + highest.id[8] + ': ' + highest.money[8] + '<br>10. ' + highest.id[9] + ': ' + highest.money[9]); }, pus: 'pmupperstaff', pmupperstaff: function (target, room, user) { if (!target) return this.sendReply('/pmupperstaff [message] - Sends a PM to every upper staff'); if (!this.can('pban')) return false; for (var u in Users.users) { if (Users.users[u].group == '~' || Users.users[u].group == '&') { Users.users[u].send('|pm|~Upper Staff PM|'+Users.users[u].group+Users.users[u].name+'| '+target+' (PM from '+user.name+')'); } } }, staff: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox("<a href=\"https://www.smogon.com/sim/staff_list\">Pokemon Showdown Staff List</a>"); }, beno: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://fc06.deviantart.net/fs29/f/2008/092/4/c/NOT_MY_MUDKIP_by_joeywaii.jpg" width="250">' + '<img src="http://images.fanpop.com/images/image_uploads/Mudkip-mudkip-marshtomp-and-swampert-432906_461_421.jpg" width="250" height="240""><br />' + '<b>Ace: </b>That sad moment when life gave you lemons but you\'re to lazy to make the lemonade.<br />' + '<button name="send" value="/transferbucks elitefourbeno, 5">Donate 5 bucks for a cookie</button></center>'); }, sand2: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/0dwzNX7.gif"><br />' + '<img src="http://media.giphy.com/media/FvtOorPNV09Og/giphy.gif" width="270" height="200">' + '<img src="http://media.giphy.com/media/O7UKZP7lMuZm8/giphy.gif" width="270" height="200"><br />' + 'I don\'t like it, the dark circles under my eyes will come back and I don\'t know how to deal with the dark circles</center>'); }, showtan: function (target, room, user) { if (room.id !== 'showderp') return this.sendReply("The command '/showtan' was unrecognized. To send a message starting with '/showtan', type '//showtan'."); if (!this.can('modchat', null, room)) return; target = this.splitTarget(target); if (!this.targetUser) return this.sendReply("User not found"); if (!room.users[this.targetUser.userid]) return this.sendReply("Not a showderper"); this.targetUser.avatar = '#showtan'; room.add("" + user.name + " applied showtan to affected area of " + this.targetUser.name); }, showtan: function (target, room, user) { if (room.id !== 'showderp') return this.sendReply("The command '/showtan' was unrecognized. To send a message starting with '/showtan', type '//showtan'."); if (!this.can('modchat', null, room)) return; target = this.splitTarget(target); if (!this.targetUser) return this.sendReply("User not found"); if (!room.users[this.targetUser.userid]) return this.sendReply("Not a showderper"); this.targetUser.avatar = '#showtan'; room.add("" + user.name + " applied showtan to affected area of " + this.targetUser.name); }, jlp: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/cmacyYX.gif" width="300">' + '<img src="http://i.imgur.com/J0B59PM.gif" height="200"><br />' + '<img src="http://i.imgur.com/u5Wd4Uf.gif"></center>'); }, nollid: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/0dwzNX7.gif"><br />' + '<img src="http://25.media.tumblr.com/f58fe4414fc7e71aa3e97b1da0d06c9b/tumblr_mf3kcgAp2k1r3ifxzo1_500.gif" width="260" height="200">' + '<img src="http://media.tumblr.com/50996a160cc5d34905ff35da5821d323/tumblr_inline_n5jcpzJd4p1suiunx.gif" width="260" height="200"><br />' + 'Thumbtacks in my shoes would stick into my feet whenever I tried to walk. It would hurt. I don\'t think I could deal with that really.</center>'); }, tesarand: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><b><font size="6" color="purple">Tesarand</b></font><br />' + '<img src="http://www.bonappetit.com/wp-content/uploads/2013/03/james-deen-646.jpg" height="200" width="300"><br />' + '<b>Ace: Dragonite<br />' + '"It tastes like glitter.... Rad.”</b><br></center>'); }, shrew: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/0dwzNX7.gif"><br />' + '<img src="http://i.imgur.com/tMGx5fT.gif" width="280" height="200"><br />' + '<img src="http://media.giphy.com/media/BPmdagBjYS6sM/giphy.gif" width="280" height="200"><br />' + 'I bet dead people are easier to get along with.</center>'); }, dildo: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/KpRmFDT.gif"><br />' + '<img src="http://i.imgur.com/4FwBKa4.gif" width="270">' + '<img src="http://i.imgur.com/JG2UXZd.gif" width="270"><br />' + 'The doors only open one way. They open inward.</center>'); }, cap: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox( "An introduction to the Create-A-Pokemon project:<br />" + "- <a href=\"https://www.smogon.com/cap/\">CAP project website and description</a><br />" + "- <a href=\"https://www.smogon.com/forums/showthread.php?t=48782\">What Pokemon have been made?</a><br />" + "- <a href=\"https://www.smogon.com/forums/forums/311\">Talk about the metagame here</a><br />" + "- <a href=\"https://www.smogon.com/forums/threads/3512318/#post-5594694\">Sample XY CAP teams</a>" ); }, hrey: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/RSOIh2j.gif"><br />' + '<img src="http://i.imgur.com/EsfjH9A.gif"><br />' + 'if we legalize pot, METH and THE MOLLYS will be legalized shortly after #420NO</center>'); }, shrewed: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/3scS0w5.gif"><br />' + '<img src="http://i.imgur.com/TS5dYjU.gif" width="270" height="160">' + '<img src="http://i.imgur.com/Dp5P3Bu.gif" width="270" height="160"><br />' + 'There are stars and planets floating around me. I don\'t think I can handle astronomy right now.</center>'); }, fork: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/HrDUGmr.png" width="75" height="100">'); }, dillon: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/PNy1HEf.gif"><br />' + '<img src="http://media.tumblr.com/tumblr_lz1xhpgIcY1qbnaro.gif" width="270">' + '<img src="http://img4.wikia.nocookie.net/__cb20130826213452/powerlisting/images/3/3a/Shadow_Dragon%27s_Roar.gif" width="270"><br />' + 'The loneliest people are the kindest. The saddest people smile the brightest. The most damaged people are the wisest. All because they don\'t wish to see anyone else suffer the way they did.</center>'); }, supersonic: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://img3.wikia.nocookie.net/__cb20120528125001/sonic/images/f/fc/Hyper_sonic.gif"><br />' + 'Gotta go fast much?</center>'); }, terlor: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/EEcZ4J2.png" width="350"><br />' + '<img src="http://i.imgur.com/bjVsAsj.png"><br />' + '"Why problem make when you no problem have you dont want to make."</center>'); }, saago: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/v3wWa5Z.jpg"><br />' + 'Everything you\'ve ever wanted is on the other side of fear.</center>'); }, sexykricketune: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/VPcZ1rC.png"><br />' + '<img src="https://fbcdn-sphotos-h-a.akamaihd.net/hphotos-ak-xpa1/v/t34.0-12/10537833_1479515712290994_1126670309_n.jpg?oh=52eb7d293765697c3c9e0a6ee235dd7d&oe=53BD3B02&__gda__=1404931411_57a9e1bbf14ec5949be27acfae62bf5f" width="500"><br />' + 'What, were you expecting something?</center>'); }, shikuthezorua: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://th01.deviantart.net/fs70/150/i/2013/147/5/1/zorua_by_andreehxd-d66umkw.png"><br />' + 'I may be cute, but I could make you fall off a cliff without anyone seeing it.</center>'); }, stone: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="https://i.imgur.com/DPy0OdR.gif" width="500"><br />' + '<img src="http://pldh.net/media/pokemon/gen6/xy-animated-shiny/376.gif"><br />' + '<b><font color="gold">Ace: Metagross</b></font><br />' + '<font color="gold">The secret to winning is to open your heart to pokemon and connect them to show how much you love your pokemon. Forcing them to attack every single time makes them lose energy & lose trust in you. So loving your pokemon and treating it well</font></center>'); }, dsuc: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><b><Font color="#FF0000">D</Font><Font color="#FF6000">e</Font><Font color="#FFC000">m</Font><Font color="#FFff00">o</Font><Font color="#9Fff00">n</Font><Font color="#3Fff00">i</Font><Font color="#00ff00">c</Font> ' + '<Font color="#00ffC0">S</Font><Font color="#00ffff">u</Font><Font color="#00C0ff">c</Font><Font color="#0060ff">c</Font><Font color="#0000ff">u</Font><Font color="#3F00ff">b</Font><Font color="#9F00ff">u</Font><Font color="#FF00ff">s</Font></b><br />' + '<img src="http://fc06.deviantart.net/fs70/i/2011/139/d/1/dcp_succubus_class_by_black_cat_mew-d3gqhbi.png" width="150"><br />' + 'Won\'t you be my pet?'); }, jacktr: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/X8Qshnz.gif"><br />' + 'With my bare hands I took back my life, now I\'ll take yours'); }, goal: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://cdn.bulbagarden.net/upload/thumb/4/47/181Ampharos.png/250px-181Ampharos.png">' + '<img src="http://lucien0maverick.files.wordpress.com/2014/05/tails-prower.png" width="200"><br />' + 'The Ultimate Team Combo</center>'); }, tailz: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/qO72kmo.png"><br />' + '<img src="http://37.media.tumblr.com/cc5c32483f12ae8866fda48d084f3861/tumblr_mww5peDTd71qkwzzdo1_400.gif"><br />' + '<i>Play Time Is Ogre</i>'); }, silver: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://img3.wikia.nocookie.net/__cb20091211143347/sonic/images/thumb/5/5d/Super_silver_final.png/150px-Super_silver_final.png"><br />' + '<img src="http://img1.wikia.nocookie.net/__cb20111024112339/sonic/images/thumb/3/34/Sonic_Channel_-_Silver_The_Hedgehog_2011.png/120px-Sonic_Channel_-_Silver_The_Hedgehog_2011.png"><br />' + 'Ace: Its no use!<br />'); }, gene: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/NO1PFB2.png"><br />' + '<img src="http://static2.wikia.nocookie.net/__cb20131130005232/bleedmancomics/images/6/66/Klefki_XY.gif"><br />' + '<b><font color="red">Ace:</b> Monopoly</font><br />' + '<font color="purple"> Romanticism is the expression of man\'s urge to rise above reason and common sense, just as rationalism is the expression of his urge to rise above theology and ion. Riot\'s suck, I love noodles.</font></center>'); }, hag: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://fc06.deviantart.net/fs70/f/2014/243/b/f/godzilla_vs_smaug_by_rumper1-d7xeyzt.png" width=500 height=500><br />' + 'What my battles are like</center>'); }, wrath: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/csloC44.gif"><br />' + '<img src="http://i.imgur.com/GS0kfMW.png"><br />' + 'No being an asshat. Asshats will face the Wrath of Espurr.</center>'); }, windy: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/CwmuZVJ.png"><br />' + '<img src="http://i.imgur.com/qOMMI3O.gif"><br />' + 'Show Your Victory!</center>'); }, coolasian: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/HbZN3Jm.png"><br />' + '<img src="http://i.imgur.com/PxPKnUs.jpg"><br />' + 'Scavenge. Slay. Survive.</center>'); }, aphrodisia: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/7SAR6FI.png"><br />' + '<img src="http://img2.wikia.nocookie.net/__cb20140319085812/pokemon/images/7/72/Pikachu_XY.gif"><br />' + 'Ace: Crumbster<br />' + '<font color=yellow> <b>If you want to find the secrets of the universe, think in terms of energy, frequency and vibration.</b></font></center>'); }, solox: 'solstice', equinox: 'solstice', solstice: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/6WcNxO9.gif">' + '<img src="http://i.imgur.com/vAsLJda.png"><br />' + '<img src="http://i.imgur.com/FnAsxKa.png"><br />' + 'Is what I\'ve done too much to take,<br />' + 'Or are you scared of being nothing?</center>'); }, typhozzz: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://th08.deviantart.net/fs70/PRE/i/2011/111/e/5/typhlosion_by_sharkjaw-d3ehtqh.jpg" height="100" width="100">' + '<img src="http://i.imgur.com/eDS32pU.gif">' + '<img src="http://i.imgur.com/UTfUkBW.png"><br />' + '<b>Ace: <font color="red"> Typhlosion</font></b><br />' + 'There ain\'t a soul or a person or thing that can stop me :]</center>'); }, cyllage: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/AUTOlch.png"><br />' + '<img src="http://i.imgur.com/Pyev2QI.jpg"><br />' + '<img src="http://i.imgur.com/02Y8dAA.png"><br />' + 'Ace: Volcarona<br />' + 'Catch phrase: Kindness is a virtue that should be expressed by everyone.</center>'); }, pan: 'panpawn', panpawn: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/BYTR6Fj.gif width="80" height="80">' + '<img src="http://i.imgur.com/xzfPeaL.gif">' + '<img src="http://107.161.19.43:8000/avatars/panpawn.gif"><br />' + '<b><font color="#4F86F7">Ace:</font></b> <font color="red">C<font color="orange">y<font color="red">n<font color="orange">d<font color="red">a<font color="orange">q<font color="red">u<font color="orange">i<font color="red">l</font><br />' + '<font color="black">"Don\'t touch me when I\'m sleeping."</font></center>'); }, mrbug: 'bug', bug: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><font size="5" color="darkgreen">Mr. Bug</font><br />' + '<img src="http://media.pocketmonsters.net/characters/2127.png" width="40%" align="left">'+ '<img src="https://1-media-cdn.foolz.us/ffuuka/board/vp/thumb/1379/30/1379304844529s.jpg" width="40%" align="right"><br />' + '<img src="http://fc01.deviantart.net/fs70/i/2011/341/9/8/kricketot_by_nami_tsuki-d4if7lr.png" width="35%"><br />' + '"delelele woooooop"<br />' + 'Ace: kriketot</center>'); }, comet: 'sunako', cometstorm: 'sunako', sunako: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/3uyLxHC.png"><br />' + '<font color="0F055C"><b><i>I came from the storm.</center>'); }, popcorn: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/jQwJOwk.gif"></center>'); }, sand: 'sandshrewed', sandshrewed: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/4kyR3d1.jpg" width="100%"><br />' + '<img src="http://i.imgur.com/lgNPrpK.png"><br />' + 'Ace: Gengar<br />' + '<font color=66CCFF>Don\'t need luck, got skill</font></center>'); }, destiny: 'itsdestiny', itsdestiny: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><font size="4" color="green"><b>It$de$tiny</b></font><br />' + '<img src="http://www.icleiusa.org/blog/library/images-phase1-051308/landscape/blog-images-90.jpg" width="55%"><img src="http://mindmillion.com/images/money/money-background-seamless-fill-bluesky.jpg" width="35%"><br />' + 'It ain\'t luck, it\'s destiny.</center>'); }, miah: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><font size="3" color="orange"><b>Miah</font></b><br />' + '<img src="https://i.imgur.com/2RHOuPi.gif" width="50%"><img src="https://fbcdn-sphotos-c-a.akamaihd.net/hphotos-ak-frc1/t1.0-9/1511712_629640560439158_8415184400256062344_n.jpg" width="50%"><br />' + 'Ace: Gliscor<br>Catch phrase: Adding Euphemisms to Pokemon</center>'); }, drag: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><font size="5" color="red">Akely</font><br />' + '<img src="http://gamesloveres.com/wp-content/uploads/2014/03/cute-pokemon-charmandercharmander-by-inversidom-riot-on-deviantart-llfutuct.png" width="25%"><br />' + 'Ace: Charizard<br />' + '"Real mens can cry but real mens doesn\'t give up."</center>'); }, kricketune: 'kriсketunе', kriсketunе: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/VPcZ1rC.png"><br />' + '<img src="http://i.imgur.com/NKGYqpn.png" width="50%"><br />' + 'Ace: Donnatello<br />' + '"At day I own the streets, but at night I own the closet..."</center>'); }, crowt: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><div class="infobox"><img src="http://i.imgur.com/BYTR6Fj.gif width="80" height="80" align="left">' + '<img src="http://i.imgur.com/czMd1X5.gif" border="6" align="center">' + '<img src="http://50.62.73.114:8000/avatars/crowt.png" align="right"><br clear="all" /></div>' + '<blink><font color="red">~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~</font></blink><br />' + '<div class="infobox"><b><font color="#4F86F7" size="3">Ace:</font></b> <font color="blue" size="3">G</font><font color="black" size="3">r</font><font color="blue" size="3">e</font><font color="black" size="3">n</font><font color="blue" size="3">i</font><font color="black" size="3">n</font><font color="blue" size="3">j</font><font color="black" size="3">a</font></font><br />' + '<font color="black">"It takes a great deal of <b>bravery</b> to <b>stand up to</b> our <b>enemies</b>, but just as much to stand up to our <b>friends</b>." - Dumbledore</font></center></div>'); }, ransu: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/kWaZd66.jpg" width="40%"><br />' + 'Develop a passion for learning. If you do, you will never cease to grow.</center>'); }, jessie: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/420CAz0.png"><br />' + '<img src="http://i.imgur.com/9ERgTNi.png"><br />' + 'Catch phrase: I\'m from Jakarta ah ah</center>'); }, berry: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://blog.flamingtext.com/blog/2014/04/02/flamingtext_com_1396402375_186122138.png" width="50%"><br />' + '<img src="http://50.62.73.114:8000/avatars/theberrymaster.gif"><br />' + 'Cherrim-Sunshine<br />' + 'I don\'t care what I end up being as long as I\'m a legend.</center>'); }, moist: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://fc04.deviantart.net/fs70/i/2010/338/6/3/moister_by_arvalis-d347xgw.jpg" width="50%"></center>'); }, spydreigon: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/57drGn3.jpg" width="75%"><br />' + '<img src="http://fc00.deviantart.net/fs70/f/2013/102/8/3/hydreigon___draco_meteor_by_ishmam-d61irtz.png" width="75%"><br />' + 'You wish you were as badass as me</center>'); }, mushy: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><font size="3" color=#8E019D>Mushy</font><br />' + '<img src="http://www.wall321.com/thumbnails/detail/20120504/angels%20army%20diablo%20armor%20tyrael%20swords%201920x1080%20wallpaper_www.wall321.com_75.jpg" width=400 height=225><br />' + '"Why do people hope for things that they know are near impossible?" "Because sometimes, hope is all you have."</center>'); }, panic: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/sGq1qy9.gif"></center>'); }, furgo: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/0qJzTgP.gif" width="25%"><br />' + '<font color="red">Ace:</font><br />' + '<img src="http://amethyst.xiaotai.org:2000/avatars/furgo.gif"><br />' + 'When I\'m sleeping, do not poke me. :I</center>'); }, blazingflareon: 'bf', bf: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/h3ZTk9u.gif"><br />' + '<img src="http://fc08.deviantart.net/fs71/i/2012/251/3/f/flareon_coloured_lineart_by_noel_tf-d5e166e.jpg" width="25%"><br />' + '<font size="3" color="red"><u><b><i>DARE TO DREAM</font></u></i></b></center>'); }, mikado: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/oS2jnht.gif"><br />' + '<img src="http://i.imgur.com/oKEA0Om.png"></center>'); }, dsg:'darkshinygiratina', darkshinygiratina: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><font size="4" color="blue" face="arial">DarkShinyGiratina</font><br />' + '<img src="http://i.imgur.com/sBIqMv8.gif"><br />' + 'I\'m gonna use Shadow Force on you!</center>'); }, archbisharp: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/ibC46tQ.png"><br />' + '<img src="http://fc07.deviantart.net/fs70/f/2012/294/f/c/bisharp_by_xdarkblaze-d5ijnsf.gif" width="350" hieght="350"><br />' + '<b>Ruling you with an Iron Head.</b></center>'); }, chimplup: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><b>Chimplup</b> - The almighty ruler of chimchars and piplups alike, also likes pie.</center>'); }, shephard: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><b>Shephard</b> - King Of Water and Ground types.</center>'); }, logic: 'psychological', psychological: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/c4j9EdJ.png?1">' + '<img src="http://i.imgur.com/tRRas7O.gif" width="200">' + '<img src="http://i.imgur.com/TwpGsh3.png?1"><br />' + '<img src="http://i.imgur.com/1MH0mJM.png" height="90">' + '<img src="http://i.imgur.com/TSEXdOm.gif" width="300">' + '<img src="http://i.imgur.com/4XlnMPZ.png" height="90"><br />' + 'If it isn\'t logical, it\'s probably Psychological.</center>'); }, seed: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><b>Seed</b> - /me plant and water</center>'); }, auraburst: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/9guvnD7.jpg">' + '<font color="orange"><font size="2"><b>Aura Butt</b> - Nick Cage.</font>' + '<img src="http://i.imgur.com/9guvnD7.jpg"></center>'); }, leo: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><b>Leonardo DiCaprio</b> - Mirror mirror on the wall, who is the chillest of them all?</center>'); }, kupo: 'moogle', moogle: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><font size="7" color="#AE8119"><b>kupo</font</b><br />' + '<img src="http://107.191.104.240:8000/avatars/kupo.png"><br />' + '<img src="http://th03.deviantart.net/fs70/PRE/i/2013/193/f/1/chocobo_and_moogle_by_judeydey-d6d629x.png" width="25%"><br />' + 'abc! O3O!</center>'); }, starmaster: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><b>Starmaster</b> - Well what were you expecting. Master of stars. Duh</center>'); }, ryun: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><b>Ryun</b> - Will fuck your shit up with his army of Gloom, Chimecho, Duosion, Dunsparce, Plusle and Mr. Mime</center>'); }, miikasa: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://fc06.deviantart.net/fs70/f/2010/330/2/0/cirno_neutral_special_by_generalcirno-d33ndj0.gif"><br />' + '<font color="purple"><font size="2"><b>Miikasa</b></font>' + '<font color="purple"><font size="2"> - There are no buses in Gensokyo.</center></font>'); }, poliii: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/GsI3Y75.jpg"><br />' + '<font color="blue"><font size="2"><b>Poliii</b></font>' + '<font color="blue"><font size="2"> - Greninja is behind you.</font></center>'); }, frozengrace: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><b>FrozenGrace</b> - The gentle wind blows as the song birds sing of her vibrant radiance. The vibrant flowers and luscious petals dance in the serenading wind, welcoming her arrival for the epitome of all things beautiful. Bow down to her majesty for she is the Queen. Let her bestow upon you as she graces you with her elegance. FrozenGrace, eternal serenity.</center>'); }, awk: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><b>Awk</b> - I have nothing to say to that!</center>'); }, screamingmilotic: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><b>ScreamingMilotic</b> - The shiny Milotic that wants to take over the world.</center>'); }, aikenka: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://fc05.deviantart.net/fs70/f/2010/004/3/4/Go_MAGIKARP_use_your_Splash_by_JoshR691.gif">' + '<b><font size="2"><font color="blue">Aikenká</b><font size="2"></font>' + '<font color="blue"> - The Master of the imp.</font>' + '<img src="http://fc05.deviantart.net/fs70/f/2010/004/3/4/Go_MAGIKARP_use_your_Splash_by_JoshR691.gif"></center>'); }, ipad: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/miLUHTz.png"><br><b>iPood</b><br />' + 'A total <font color="brown">pos</font> that panpawn will ban.<br />' + '<img src="http://i.imgur.com/miLUHTz.png"></center>'); }, rhan: 'rohansound', rohansound: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><font color="orange"><font size="2"><b>Rohansound</b>' + '<font size="orange"><font size="2"> - The master of the Snivy!</center>'); }, alittlepaw: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://fc00.deviantart.net/fs71/f/2013/025/5/d/wolf_dance_by_windwolf13-d5sq93d.gif"><br />' + '<font color="green"><font size="3"><b>ALittlePaw</b> - Fenrir would be proud.</center>'); }, smashbrosbrawl: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><b>SmashBrosBrawl</b> - Christian Bale</center>'); }, w00per: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/i3FYyoG.gif"><br />' + '<font size="2"><font color="brown"><b>W00per</b>' + '<font size="2"><font color="brown"> - "I CAME IN LIKE `EM WRECKIN` BALLZ!</center>'); }, empoleonxv: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/IHd5yRT.gif"><br />' + '<img src="http://i.imgur.com/sfQsRlH.gif"><br />' + '<b><font color="33FFFF"><big>Smiling and Waving can\'t make you more cute than me!</b></center>'); }, foe: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://s21.postimg.org/durjqji4z/aaaaa.gif"><br />' + '<font size="2"><b>Foe</b><font size="2"> - Not a friend.</center>'); }, op: 'orangepoptarts', orangepoptarts: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://www.jeboavatars.com/images/avatars/192809169066sunsetbeach.jpg"><br />' + '<b><font size="2">Orange Poptarts</b><font size="2"> - "Pop, who so you" ~ ALittlePaw</center>'); }, darkhanekawa: 'jackzero', v: 'jackzero', jack: 'jackzero', jackzero: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><font size="4" color="#1AACBC"><b>JackZero</b><br/></font>' + '<img src="http://i.imgur.com/wUqmPZz.gif" height="250"><br/>' + '<font size="2"><i>I stopped fighting my inner demons. We are on the same side now.</i></font></center>'); }, wd: 'windoge', windoge: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://i.imgur.com/qYTABJC.jpg" width="400"></center>'); }, party: 'dance', dance: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://collegecandy.files.wordpress.com/2013/05/tumblr_inline_mhv5qyiqvk1qz4rgp1.gif" width="400"></center>'); }, kayo: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><font size="2"><b>Kayo</b><br />' + 'By the Beard of Zeus that Ghost was Fat<br />' + '<img src="http://i.imgur.com/rPe9hBa.png"></center>'); }, saburo: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><font color="red" size="5"><b>Saburo</font></b><br />' + '<img src="http://i.imgur.com/pYUt8Hf.gif"><br>The god of dance.</center>'); }, gara: 'garazan', nub: 'garazan', garazan: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><font size="6" face="comic sans ms"><font color="red">G<font color="orange">a<font color="yellow">r<font color="tan">a<font color="violet">z<font color="purple">a<font color="blue">n</font><br />' + '<img src="http://www.quickmeme.com/img/3b/3b2ef0437a963f22d89b81bf7a8ef9d46f8770414ec98f3d25db4badbbe5f19c.jpg" width="150" height="150"></center>'); }, scizornician: 'sciz', sciz: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<div class="broadcast-blue"><center><font color="#A80000" size ="3"><b>Scizornician</b></font><br />' + '<b>Quote:</b> "It\'s all shits and giggles until someone giggles and shits."</font><br />' + '<b>Quote:</b> "Light travels faster than sound, that\'s why some people appear bright before they speak."</font><br />' + '<img src="http://107.191.104.240:8000/avatars/sciz.gif"></center></div>'); }, d3adm3owth: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><font color=#0E30AA size=3>d3adm3owth</font><br />' + '<img src="http://img2.wikia.nocookie.net/__cb20140120230002/pokemon/images/1/1b/OI015.jpg" width=320 height 240><br />' + 'Ace: Meowth<br />' + '...in accordance with the dictates of reason.</center>'); }, ashbloodthief: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><font size="5"><font color="#140391">ashbloodthief</font></font></center> <center><img src="http://107.191.104.240:8000/avatars/ashbloodthief.gif" width=100 height=100></center> <center><img src="http://fc04.deviantart.net/fs71/f/2013/259/f/f/mega_lucario_by_henshingeneration-d6mihft.jpg" width=270 height=200></center><br /> <center><font size="3"> Ace: Mega Lucario</font></center> <center><font size="3"> I\'m a being pure as energy! You can\'t stop me!</font></center>'); }, //***********************Music Boxes*************************** //View Music box command to reduce lobby spam vmb: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center>Click <button name="send" value="/'+ target + '" class="blackbutton" title="View musicbox!"><font color="white"><b>here</button></b></font> to view <b>' + target + '!</b></center>'); }, tailzbox: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<b>Tailz\'s Music Box!</b><br />' + '1. <a href="https://www.youtube.com/watch?v=zxof7Lh1u3c"><button>Nano - Savior Of Song</a></button><br />' + '2. <a href="https://www.youtube.com/watch?v=3ZckiELrRLU"><button>Nano - Black Board</a></button><br />' + '3. <a href="https://www.youtube.com/watch?v=P829PgxKxuM"><button>A Day To Remember - If It Means A Lot To You</a></button><br />' + '4. <a href="https://www.youtube.com/watch?v=QgFHL2R8m6s"><button>HollyWood Undead - Lion</a></button><br />' + '5. <a href="https://www.youtube.com/watch?v=fBocMs7EyOg"><button>Nano - Just Be Friends</a></button><br />' + '6. <a href="https://www.youtube.com/watch?v=Om5uXsD-aVo"><button>Rise Against - Satellite</a></button><br />' + '7. <a href="https://www.youtube.com/watch?v=YDJXr-Tzbqw"><button>Sora Amamiya - Skyreach</a></button><br />' + '8. <a href="https://www.youtube.com/watch?v=Ypl0gPtk0tA"><button>Three Days Grace - The High Road</a></button><br />' + '9. <a href="https://www.youtube.com/watch?v=xZ2yP7iUDeg"><button>Crown The Empire - Millenia</a></button><br /></center>' ); }, terbox: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<b>Sir Terlor\'s Music Box!</b><br />' + '1. <a href="https://www.youtube.com/watch?v=lL2ZwXj1tXM"><button>Three Days Grace - Never Too Late</a></button><br />' + '2. <a href="https://www.youtube.com/watch?v=JpDPOs-rddM"><button>Sonata Arctica - Mary Lou</a></button><br />' + '3. <a href="https://www.youtube.com/watch?v=IbOd8yf1ElI"><button>Hollywood Undead - The Diary</a></button><br />' + '4. <a href="https://www.youtube.com/watch?v=JCT5uTdPRgs"><button>Black Sabbath - N.I.B</a></button><br />' + '5. <a href="https://www.youtube.com/watch?v=as7p6VwnR5s"><button>Vexento - Praeclara</a></button><br />' + '6. <a href="https://www.youtube.com/watch?v=G5zdal1MKf0"><button>Volbeat - Doc Holiday</a></button><br />' + '7. <a href="https://www.youtube.com/watch?v=VRFCMM3bra8"><button>Billy Talent - Viking Death March</a></button></center>' ); }, silrbox: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<b>Silver\'s Music Box!</b><br />' + '1. <a href="https://www.youtube.com/watch?v=GEEYhzaeNus"><button>Union J - Carry You</a></button><br />' + '2. <a href="https://www.youtube.com/watch?v=cmSbXsFE3l8"><button>Anna Kendrick - Cups</a></button><br />' + '3. <a href="https://www.youtube.com/watch?v=iKaSbac2roQ"><button>Vacation - Vitamin C</a></button><br />' + '4. <a href="https://www.youtube.com/watch?v=LiaYDPRedWQ"><button>Avril Lavigne - Hello Kitty</a></button><br />'); }, sandbox: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<b>Sandshrewed\'s Music Box!</b><br />' + '1. <a href="https://www.youtube.com/watch?v=vN0I4b5YdOc"><button title="RAP Done It All - Iniquity Rhymes">RAP Done It All - Iniquity Rhymes</a></button><br />' + '2. <a href="https://www.youtube.com/watch?v=n3QmHNd0HWo"><button title="Metal Gear Rising: Revengeance ~ The Only Thing I Know For Real">Metal Gear Rising: Revengeance ~ The Only Thing I Know For Real</a></button><br />' + '3. <a href="https://www.youtube.com/watch?v=hV5sB5rRsGI"><button title="New Boyz - Colors">New Boyz - Colors</a></button><br />' + '4. <a href="https://www.youtube.com/watch?v=A1A0mIqlPiI"><button title="Young Cash feat. Shawn Jay (Field Mob) - Stress Free">Young Cash feat. Shawn Jay (Field Mob) - Stress Free</a></button><br />' + '5. <a href="https://www.youtube.com/watch?v=ULQgMntenO8"><button title="Metal Gear Rising, Monsoon\'s theme- Stains of Time">Metal Gear Rising, Monsoon\'s theme- Stains of Time</a></button><br />' + '6. <a href="https://www.youtube.com/watch?v=P4PgrY33-UA"><button title="Drop That NaeNae">Drop That NaeNae</a></button><br />' ); }, ampharosbox: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<b>AmpharosTheBeast\'s Music Box!</b><br />' + '1. <a href="https://www.youtube.com/watch?v=RRGSHvlu9Ss"><button title="Linkin Park - Castle of Glass">Linkin Park - Castle of Glass</a></button><br />' + '2. <a href="https://www.youtube.com/watch?v=ie1wU9BLGn8"><button title="Rixton - Me and My Broken Heart">Rixton - Me and My Broken Heart</a></button><br />' + '3. <a href="https://www.youtube.com/watch?v=psuRGfAaju4"><button title="Owl City - Fireflies">Owl City - Fireflies</a></button><br />' + '4. <a href="https://www.youtube.com/watch?v=hT_nvWreIhg"><button title="OneRepublic - Counting Stars">OneRepublic - Counting Stars</a></button><br />' + '5. <a href="https://www.youtube.com/watch?v=VDvr08sCPOc"><button title="Fort Minor - Remember The Name">Fort Minor - Remember The Name</a></button><br />' + '6. <a href="https://www.youtube.com/watch?v=JPCv5rubXhU"><button title="Pokemon Bank A Parody of Bad Day">Pokemon Bank A Parody of Bad Day</a></button>'); }, legitbox: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<b>Legit Buttons\'s Music Box!</b><br />' + '1. <a href="https://www.youtube.com/watch?v=y6Sxv-sUYtM"><button title="Pharrell Williams - Happy">Pharrell Williams - Happy</a></button><br />' + '2. <a href="https://www.youtube.com/watch?v=hT_nvWreIhg"><button title="OneRepublic - Counting Stars">OneRepublic - Counting Stars</a></button><br />' + '3. <a href="https://www.youtube.com/watch?v=6Cp6mKbRTQY"><button title="Avicii - Hey Brother">Avicii - Hey Brother</a></button><br />' + '4. <a href="https://www.youtube.com/watch?v=hHUbLv4ThOo"><button title="Pitbull - Timber ft. Ke$ha">Pitbull - Timber ft. Ke$ha</a></button><br />' ); }, riotbox: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<b>Jack Skellington\'s Music Box!</b><br />' + '1. <a href="https://www.youtube.com/watch?v=ubiZDYU7mv0"><button title="Metal Gear Rising: Revengeance - The Only Thing I Know for Real ">Metal Gear Rising: Revengeance - The Only Thing I Know for Real </a></button><br />' + '2. <a href="https://www.youtube.com/watch?v=ye0XhDdbFs4"><button title="A Day to Remember - You Had Me at Hello">A Day to Remember - You Had Me at Hello</a></button><br />' + '3. <a href="https://www.youtube.com/watch?v=vc6vs-l5dkc"><button title="Panic! At The Disco - I Write Sins Not Tragedies">Panic! At The Disco: I Write Sins Not Tragedies</a></button><br />' + '4. <a href="https://www.youtube.com/watch?v=FukeNR1ydOA"><button title="Suicide Silence - Disengage">Suicide Silence - Disengage</a></button><br />' + '5. <a href="https://www.youtube.com/watch?v=xyW9KknfwLU"><button title="A Day to Remember - Sometimes You\'re The Hammer, Sometimes You\'re The Nail">A Day to Remember - Sometimes You\'re The Hammer, Sometimes You\'re The Nail</a></button><br />' + '6. <a href="https://www.youtube.com/watch?v=sA5hj7wuJLQ"><button title="Bring Me The Horizon - Empire (Let Them Sing)">Bring Me The Horizon - Empire (Let Them Sing)</a></button><br />' ); }, berrybox: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<b>The Berry Master\'s Music Box!</b><br />' + '1. <a href="https://www.youtube.com/watch?v=fJ9rUzIMcZQ"><button title="Queen - Bohemian Rhapsody">Queen - Bohemian Rhapsody</a></button><br />' + '2. <a href="https://www.youtube.com/watch?v=xDMNHvnIxic"><button title="Hamster on a Piano">Hamster on a Piano</a></button><br />' + '3. <a href="https://www.youtube.com/watch?v=BuO5Jiqn9q4"><button title="The Ink Spots - Making Believe">The Ink Spots - Making Believe</a></button><br />' + '4. <a href="https://www.youtube.com/watch?v=ws8X31TTB5E"><button title="Cowboy Bebop OST 3 Blue - Adieu">Cowboy Bebop OST 3 Blue - Adieu</a></button><br />' + '5. <a href="https://www.youtube.com/watch?v=CnDJizJsMJg"><button title="ENTER SHIKARI - MOTHERSTEP/MOTHERSHIP">ENTER SHIKARI - MOTHERSTEP/MOTHERSHIP</a></button><br />' + '6. <a href="https://www.youtube.com/watch?v=-osNFEyI3vw"><button title="Gungor - Crags And Clay">Gungor - Crags And Clay</a></button><br />' ); }, sphealbox: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<b>Super Spheal Bros\'s Music Box!</b><br />' + '1. <a href="https://www.youtube.com/watch?v=85XM_Nl7_oo"><button title="Mother 1 (EarthBound Zero) Music - Eight Melodies">Mother 1 (EarthBound Zero) Music - Eight Melodies</a></button><br />' + '2. <a href="https://www.youtube.com/watch?v=oOy7cJowbQs"><button title="Pokemon Black & White 2 OST Kanto Gym Leader Battle Music">Pokemon Black & White 2 OST Kanto Gym Leader Battle Music</a></button><br />' + '3. <a href="https://www.youtube.com/watch?v=XEEceynk-mg"><button title="Sonic the Hedgehog Starlight Zone Music">Sonic the Hedgehog Starlight Zone Music</a></button><br />' + '4. <a href="https://www.youtube.com/watch?v=jofNR_WkoCE"><button title="Ylvis - The Fox (What Does The Fox Say?)">Ylvis - The Fox (What Does The Fox Say?)</a></button><br />' + '5. <a href="https://www.youtube.com/watch?v=EAwWPadFsOA"><button title="Mortal Kombat Theme Song">Mortal Kombat Theme Song</a></button><br />' + '6. <a href="https://www.youtube.com/watch?v=QH2-TGUlwu4"><button title="Nyan Cat">Nyan Cat</a></button><br />'); }, boxofdestiny: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<b>itsdestny\'s Music Box!</b><br />' + '1. <a href="https://www.youtube.com/watch?v=pucnAvLsgyI"><button title="Megaman Battle Network 5 Hero Theme">Megaman Battle Network 5 Hero Theme</a></button><br />' + '2. <a href="https://www.youtube.com/watch?v=ckNRHPlLBcU"><button title="Gospel - Monsters University">Gospel - Monsters University</a></button><br />' + '3. <a href="https://www.youtube.com/watch?v=sLgyd2HHvMc"><button title="Princess Kenny Theme Song">Princess Kenny Theme Song</a></button><br />' + '4. <a href="https://www.youtube.com/watch?v=9bZkp7q19f0"><button title="Psy - Gangnam Style">Psy - Gangnam Style</a></button><br />' + '5. <a href="https://www.youtube.com/watch?v=x4JdySEXrg8"><button title="Frozen - Let It Go">Frozen - Let It Go</a></button><br />'); }, cbox: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<b>Cyllage\'s Music Box!</b><br />' + '1. <a href="https://www.youtube.com/watch?v=SRvCvsRp5ho"><button title="Bon Jovi - Wanted Dead Or Alive">Bon Jovi - Wanted Dead Or Alive</a></button><br />' + '2. <a href="https://www.youtube.com/watch?v=c901NUazf3g"><button title="Muse - Exogenesis Symphony">Muse - Exogenesis Symphony</a></button><br />' + '3. <a href="https://www.youtube.com/watch?v=4MjLKjPc7q8"><button title="Rise Against - Audience Of One">Rise Against - Audience Of One</a></button><br />' + '4. <a href="https://www.youtube.com/watch?v=gxEPV4kolz0"><button title="Billy Joel - Piano Man">Billy Joel - Piano Man</a></button><br />' + '5. <a href="https://www.youtube.com/watch?v=IwdJYdDyKUw"><button title="Griffin Village - Spring">Griffin Village - Spring</a></button><br />'); }, spybox: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<b>Spydreigon\'s Music Box!</b><br />' + '1. <a href="https://www.youtube.com/watch?v=gL-ZIbF6J6s"><button title="Pursuit - Cornered">Pursuit - Cornered</a></button><br />' + '2. <a href="https://www.youtube.com/watch?v=qgP1yc1PpoU"><button title="Mega Man 10 - Abandoned Memory">Mega Man 10 - Abandoned Memory</a></button><br />' + '3. <a href="https://www.youtube.com/watch?v=yW6ECMHrGcI"><button title="Super Training! 8 Bit - Pokemon X/Y">Super Training! 8 Bit - Pokemon X/Y</a></button><br />' + '4. <a href="https://www.youtube.com/watch?v=NWYJYcpSpCs"><button title="Mighty No. 9 Theme 8 Bit">Mighty No. 9 Theme 8 Bit</a></button><br />' + '5. <a href="https://www.youtube.com/watch?v=NwaCMbfHwmQ"><button title="Mega Man X5 - X vs Zero">Mega Man X5 - X vs Zero</a></button><br />'); }, solstereo: 'solbox', solbox: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<b>The Sol Box</b><br />' + '1. <a href="https://www.youtube.com/watch?v=VIop055eJhU"><button title="Touhou 6 - EoSD - U.N. Owen was her?"> Touhou 6 - EoSD - U.N. Owen was her?</a></button><br />' + '2. <a href="https://www.youtube.com/watch?v=BwpLSiplyYc"><button title="Kirby 64: The Crystal Shards - Zero Two">Kirby 64: The Crystal Shards - Zero Two</a></button><br />' + '3. <a href="https://www.youtube.com/watch?v=EzCKrwOme2U"><button title="Muse - Butterflies and Hurricanes">Muse - Butterflies and Hurricanes</a></button><br />' + '4. <a href="https://www.youtube.com/watch?v=EqGs36oPpLQ"><button title="Last Dinosaurs - Zoom">Last Dinosaurs - Zoom</a></button><br />' + '5. <a href="https://www.youtube.com/watch?v=p9Y-r-rs9W8"><button title="Green Day - Welcome to Paradise">Green Day - Welcome to Paradise</a></button><br />' + '6. <a href="https://www.youtube.com/watch?v=aWxBrI0g1kE"><button title="Disturbed - Indestructible">Disturbed - Indestructible</a></button><br />' + '7. <a href="https://www.youtube.com/watch?v=Fi_GN1pHCVc"><button title="Avenged Sevenfold - Almost Easy">Avenged Sevenfold - Almost Easy</a></button><br />' + '8. <a href="https://www.youtube.com/watch?v=71CvlYX1Bqc"><button title="Linkin Park - Across The Line">Linkin Park - Across The Line</a></button><br />' + '9. <a href="https://www.youtube.com/watch?v=gMzSpvibN7A"><button title="30 Seconds To Mars - Hurricane (Nightcore)">30 Seconds To Mars - Hurricane (Nightcore)</a></button>'); }, vbox: 'jackbox', jackbox: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<b>Jacks\'s Music Box!</b><br />' + '1. <a href="https://www.youtube.com/watch?v=m0DMfaCh4aA"><button title="Attack on Titan - DOA">Attack on Titan - DOA</a></button><br />' + '2. <a href="https://www.youtube.com/watch?v=c-M34ZRM120"><button title=" ADTR - You be Tails, I\'ll be Sonic"> ADTR - You be Tails, I\'ll be Sonic</a></button><br />' + '3. <a href="https://www.youtube.com/watch?v=0B-xRO-vPPo"><button title="Papercut massacre - Lose my life">Papercut massacre - Lose my life</a></button><br />' + '4. <a href="https://www.youtube.com/watch?v=Qg_TRaiWj4o"><button title="The Who - Behind blue eyes">The Who - Behind blue eyes</a></button><br />' + '5. <a href="https://www.youtube.com/watch?v=0m9QUoW5KnY"><button title="Starbomb - It\'s dangerous to go alone">Starbomb - It\'s dangerous to go alone</a></button><br />' + '6. <a href="https://www.youtube.com/watch?v=Tt10gb8yf88"><button title="12 Stones - Psycho">12 Stones - Psycho</a></button><br />'); }, panbox: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<b>Panpawn\'s Music Box!</b><br />' + '1. <a href="https://www.youtube.com/watch?v=EJR5A2dttp8"><button title="Let It Go - Connie Talbot cover">Let It Go - Connie Talbot cover</a></button><br />' + '2. <a href="https://www.youtube.com/watch?v=Y2Ta0qCG8No"><button title="Crocodile Rock - Elton John">Crocodile Rock - Elton John</a></button><br />' + '3. <a href="https://www.youtube.com/watch?v=ZA3vZwxnKnE"><button title="My Angel Gabriel - Lamb">My Angel Gabriel - Lamb</a></button><br />' + '4. <a href="https://www.youtube.com/watch?v=y8AWFf7EAc4"><button title="Hallelujah - Jeff Buckley">Hallelujah - Jeff Buckley</a></button><br />' + '5. <a href="https://www.youtube.com/watch?v=aFIApXs0_Nw"><button title="Better Off Dead - Elton John">Better Off Dead - Elton John</a></button><br />' + '6. <a href="https://www.youtube.com/watch?v=eJLTGHEwaR8"><button title="Your Song - Carly Rose Sonenclar cover">Your Song - Carly Rose Sonenclar cover</a></button><br />' + '7. <a href="https://www.youtube.com/watch?v=DAJYk1jOhzk"><button title="Let It Go - Frozen - Alex Boyé">Let It Go - Frozen - Alex Boyé</a></button><br />' + '8. <a href="https://www.youtube.com/watch?v=8S-jdXJ0H4w"><button title="Elton John - Indian Sunset">Elton John-Indian Sunset</a></button><br />' + '9. <a href="https://www.youtube.com/watch?v=cnK_tfqHQnU"><button title="New York State Of Mind - Billy Joel">New York State Of Mind - Billy Joel</a></button><br />' + '10. <a href="https://www.youtube.com/watch?v=0KDjzP84sVA"><button title="Counting Stars - Cimorelli">Counting Stars - Cimorelli</a></button><br />' + '11. <a href="https://www.youtube.com/watch?v=PpntEOQLpzI"><button title="Stay - Christina Grimmie">Stay - Christina Grimmie</a></button><br />' + '12. <a href="https://www.youtube.com/watch?v=JiBKfl-xhI0"><button title="Carly Rose Sonenclar - Feeling Good">Carly Rose Sonenclar - Feeling Good</a></button><br />' + '13. <a href="https://www.youtube.com/watch?v=Gj-ntawOBw4"><button title="Shake It Out - Choral">Shake It Out - Choral</a></button><br />' + '14. <a href="https://www.youtube.com/watch?v=n7wQQGtM-Hc"><button title="Elton John Sixty Years On Royal Opera House">Elton John Sixty Years On Royal Opera House</a></button><br />' + '15. <a href="https://www.youtube.com/watch?v=Izma0gpiLBQ"><button title="Elton John - Oceans Away">Elton John - Oceans Away</a></button><br />' + '16. <a href="https://www.youtube.com/watch?v=hOpK1Euwu5U"><button title="JennaAnne: I\'m Coming Home">JennaAnne: I\'m Coming Home</a></button>'); }, cabox: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<b>CoolAsian\'s Music Box!</b><br />' + '1. <a href="http://youtu.be/UU8xKUoH_lU"><button title="Parkway Drive - Wild Eyes [Lyrics] [HD]">Parkway Drive - Wild Eyes [Lyrics] [HD]</a></button><br />' + '2. <a href="http://youtu.be/fOLqEOK_wLc"><button title="System Of A Down - B.Y.O.B.">System Of A Down - B.Y.O.B.</a></button><br />' + '3. <a href="http://youtu.be/312Sb-2PovA"><button title="SUICIDE SILENCE - You Only Live Once">SUICIDE SILENCE - You Only Live Once</a></button><br />' + '4. <a href="http://youtu.be/pUA-4WCXn5o"><button title="Atreyu - Demonology and Heartache">Atreyu - Demonology and Heartache</a></button><br />' + '5. <a href="http://youtu.be/zUq8I4JTOZU"><button title="Muse - Assassin (Grand Omega Bosses Edit)">Muse - Assassin (Grand Omega Bosses Edit)</a></button><br />' + '6. <a href="http://youtu.be/a89Shp0YhR8"><button title="A Day to Remember - I\'m Made of Wax, Larry, What Are You Made Of?">A Day to Remember - I\'m Made of Wax, Larry, What Are You Made Of?</a></button>'); }, lazerbox: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<b>lazerbeam\'s Music Box!</b><br />' + '1. <a href="https://www.youtube.com/watch?v=fJ9rUzIMcZQ"><button title="Bohemian Rhapsody - Queen">Bohemian Rhapsody - Queen</a></button><br />' + '2. <a href="https://www.youtube.com/watch?v=ZNaA7fVXB28"><button title="Against the Wind - Bob Seger">Against the Wind - Bob Seger</a></button><br />' + '3. <a href="https://www.youtube.com/watch?v=TuCGiV-EVjA"><button title="Livin\' on the Edge - Aerosmith">Livin\' on the Edge - Aerosmith</a></button><br />' + '4. <a href="https://www.youtube.com/watch?v=QZ_kYEDZVno"><button title="Rock and Roll Never Forgets - Bob Seger">Rock and Roll Never Forgets - Bob Seger</a></button><br />' + '5. <a href="https://www.youtube.com/watch?v=GHjKEwV2-ZM"><button title="Jaded - Aerosmith">Jaded - Aerosmith</a></button>'); }, //End Music Boxes. avatars: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox("Your avatar can be changed using the Options menu (it looks like a gear) in the upper right of Pokemon Showdown. Custom avatars are only obtainable by staff."); }, git: 'opensource', opensource: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('Pokemon Showdown is open source:<br />- Language: JavaScript (Node.js)<br />'+ '- <a href="https://github.com/Zarel/Pokemon-Showdown" target="_blank">Pokemon Showdown Source Code / How to create a PS server</a><br />'+ '- <a href="https://github.com/Zarel/Pokemon-Showdown-Client" target="_blank">Client Source Code</a><br />'+ '- <a href="https://github.com/panpawn/Pokemon-Showdown">Gold Source Code</a>'); }, events: 'activities', activities: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><font size="3" face="comic sans ms">Gold Activities:</font></center></br>' + '★ <b>Tournaments</b> - Here on Gold, we have a tournaments script that allows users to partake in several different tiers. For a list of tour commands do /th. Ask in the lobby for a voice (+) or up to start one of these if you\'re interesrted!<br>' + '★ <b>Hangmans</b> - We have a hangans script that allows users to partake in a "hangmans" sort of a game. For a list of hangmans commands, do /hh. As a voice (+) or up in the lobby to start one of these if interested.<br>' + '★ <b>Leagues</b> - If you click the "join room page" to the upper right (+), it will display a list of rooms we have. Several of these rooms are 3rd party leagues of Gold; join them to learn more about each one!<br>' + '★ <b>Battle</b> - By all means, invite your friends on here so that you can battle with each other! Here on Gold, we are always up to date on our formats, so we\'re a great place to battle on!<br>' + '★ <b>Chat</b> - Gold is full of great people in it\'s community and we\'d love to have you be apart of it!<br>' + '★ <b>Learn</b> - Are you new to Pokemon? If so, then feel FREE to ask the lobby any questions you might have!<br>' + '★ <b>Shop</b> - Do /shop to learn about where your Gold Bucks can go! <br>' + '★ <b>Plug.dj</b> - Come listen to music with us! Click <a href="http://plug.dj/gold-server/">here</a> to start!<br>' + '<i>--PM staff (%, @, &, ~) any questions you might have!</i>'); }, showtan: function (target, room, user) { if (room.id !== 'showderp') return this.sendReply("The command '/showtan' was unrecognized. To send a message starting with '/showtan', type '//showtan'."); if (!this.can('modchat', null, room)) return; target = this.splitTarget(target); if (!this.targetUser) return this.sendReply('user not found'); if (!room.users[this.targetUser.userid]) return this.sendReply('not a showderper'); this.targetUser.avatar = '#showtan'; room.add(user.name+' applied showtan to affected area of '+this.targetUser.name); }, introduction: 'intro', intro: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox( "New to competitive pokemon?<br />" + "- <a href=\"https://www.smogon.com/sim/ps_guide\">Beginner's Guide to Pokémon Showdown</a><br />" + "- <a href=\"https://www.smogon.com/dp/articles/intro_comp_pokemon\">An introduction to competitive Pokémon</a><br />" + "- <a href=\"https://www.smogon.com/bw/articles/bw_tiers\">What do 'OU', 'UU', etc mean?</a><br />" + "- <a href=\"https://www.smogon.com/xyhub/tiers\">What are the rules for each format? What is 'Sleep Clause'?</a>" ); }, support: 'donate', donate: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox( "<center>Like this server and want to keep it going? If so, you can make a paypal donation to Gold! You can choose the amount.<br />" + '<hr width="85%">' + "- Donations will help Gold to upgrade the VPS so we can do more and hold more users!<br />" + "- For donations <b>$5 or over</b>, you can get: 200 bucks, a custom avatar, a custom trainer card, a custom symbol, and a custom music box!<br />" + "- For donations <b>$10 and over</b>, it will get you: (the above), 600 bucks (in addition to the above 200, making 800 total) and VIP status along with a VIP badge!<br />" + "- Refer to the /shop command for a more detailed description of these prizes. After donating, PM panpawn.<br />" + '<hr width="85%">' + "Click the button below to donate!<br />" + '<a href="https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=FBZBA7MJNMG7J&lc=US&item_name=Gold%20Server&currency_code=USD&bn=PP%2dDonationsBF%3abtn_donate_LG%2egif%3aNonHosted"><img src="https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif" title=Donate now!">' ); }, links: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox( "<div class=\"broadcast-black\">Here are some helpful server related links:<b><br />" + "- <a href=\"http://goldserver.weebly.com/rules.html\"><font color=\"#FF0066\">Rules</a></font><br />" + "- <a href=\"http://w11.zetaboards.com/Goldserverps/index/\"><font color=\"#FF00\">Forums</a></font><br />" + "- <a href=\"http://goldserver.weebly.com\"><font color=\"#56600FF\">Website</a></font><br />" + "- <a href=\"http://plug.dj/gold-server/\"><font color=\"#FFFF\">Plug.dj</a></font><br />" + "- <a href=\"https://github.com/panpawn/Pokemon-Showdown\"><font color=\"#39FF14\">GitHub</a></font><br />" + "- <a href=\"http://goldserver.weebly.com/news.html\"><font color=\"#BFFF00\">News</a></font><br />" + "- <a href=\"http://goldserver.weebly.com/faqs.html\"><font color=\"#DA9D01\">FAQs</a></font><br />" + "- <a href=\"http://goldserver.weebly.com/discipline-appeals.html\"><font color=\"#12C418\">Discipline Appeals</a></font>" + "</b></div>" ); }, mentoring: 'smogintro', smogonintro: 'smogintro', smogintro: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox( "Welcome to Smogon's official simulator! Here are some useful links to <a href=\"https://www.smogon.com/mentorship/\">Smogon\'s Mentorship Program</a> to help you get integrated into the community:<br />" + "- <a href=\"https://www.smogon.com/mentorship/primer\">Smogon Primer: A brief introduction to Smogon's subcommunities</a><br />" + "- <a href=\"https://www.smogon.com/mentorship/introductions\">Introduce yourself to Smogon!</a><br />" + "- <a href=\"https://www.smogon.com/mentorship/profiles\">Profiles of current Smogon Mentors</a><br />" + "- <a href=\"http://mibbit.com/#[email protected]\">#mentor: the Smogon Mentorship IRC channel</a>" ); }, calculator: 'calc', calc: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox( "Pokemon Showdown! damage calculator. (Courtesy of Honko)<br />" + "- <a href=\"https://pokemonshowdown.com/damagecalc/\">Damage Calculator</a>" ); }, cap: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox( "An introduction to the Create-A-Pokemon project:<br />" + "- <a href=\"https://www.smogon.com/cap/\">CAP project website and description</a><br />" + "- <a href=\"https://www.smogon.com/forums/showthread.php?t=48782\">What Pokemon have been made?</a><br />" + "- <a href=\"https://www.smogon.com/forums/showthread.php?t=3464513\">Talk about the metagame here</a><br />" + "- <a href=\"https://www.smogon.com/forums/showthread.php?t=3466826\">Practice BW CAP teams</a>" ); }, gennext: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox( "NEXT (also called Gen-NEXT) is a mod that makes changes to the game:<br />" + "- <a href=\"https://github.com/Zarel/Pokemon-Showdown/blob/master/mods/gennext/README.md\">README: overview of NEXT</a><br />" + "Example replays:<br />" + "- <a href=\"https://replay.pokemonshowdown.com/gennextou-120689854\">Zergo vs Mr Weegle Snarf</a><br />" + "- <a href=\"https://replay.pokemonshowdown.com/gennextou-130756055\">NickMP vs Khalogie</a>" ); }, om: 'othermetas', othermetas: function (target, room, user) { if (!this.canBroadcast()) return; target = toId(target); var buffer = ""; var matched = false; if (!target) { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/forums/206/\">Other Metagames Forum</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3505031/\">Other Metagames Index</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3507466/\">Sample teams for entering Other Metagames</a><br />"; } if (target === 'smogondoublesuu' || target === 'doublesuu') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3516968/\">Doubles UU</a><br />"; } if (target === 'smogontriples' || target === 'triples') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3511522/\">Smogon Triples</a><br />"; } if (target === 'omofthemonth' || target === 'omotm' || target === 'month') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3481155/\">OM of the Month</a><br />"; } if (target === 'pokemonthrowback' || target === 'throwback') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3510401/\">Pokémon Throwback</a><br />"; } if (target === 'balancedhackmons' || target === 'bh') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3489849/\">Balanced Hackmons</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3499973/\">Balanced Hackmons Mentoring Program</a><br />"; } if (target === '1v1') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3496773/\">1v1</a><br />"; } if (target === 'monotype') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3493087/\">Monotype</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3517737/\">Monotype Viability Rankings</a><br />"; } if (target === 'tiershift' || target === 'ts') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3508369/\">Tier Shift</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3514386/\">Tier Shift Viability Rankings</a><br />"; } if (target === 'pu') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3513882/\">PU</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3517353/\">PU Viability Rankings</a><br />"; } if (target === 'lcuu') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3516967/\">LC UU</a><br />"; } if (target === 'almostanyability' || target === 'aaa') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3517022/\">Almost Any Ability</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3508794/\">Almost Any Ability Viability Rankings</a><br />"; } if (target === 'stabmons') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3493081/\">STABmons</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3512215/\">STABmons Viability Rankings</a><br />"; } if (target === 'hiddentype') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3516349/\">Hidden Type</a><br />"; } if (target === 'skybattles' || target === 'skybattle') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3493601/\">Sky Battles</a><br />"; } if (target === 'inversebattle' || target === 'inverse') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3518146/\">Inverse Battle</a><br />"; } if (target === '350cup') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3512945/\">350 Cup</a><br />"; } if (target === 'averagemons') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3495527/\">Averagemons</a><br />"; } if (target === 'hackmons' || target === 'purehackmons' || target === 'classichackmons') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3500418/\">Hackmons</a><br />"; } if (target === 'middlecup' || target === 'mc') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3494887/\">Middle Cup</a><br />"; } if (target === 'mashup') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3518763/\">OM Mashup</a><br />"; } if (target === 'glitchmons') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3467120/\">Glitchmons</a><br />"; } if (!matched) { return this.sendReply("The Other Metas entry '" + target + "' was not found. Try /othermetas or /om for general help."); } this.sendReplyBox(buffer); }, /*formats: 'formathelp', formatshelp: 'formathelp', formathelp: function (target, room, user) { if (!this.canBroadcast()) return; if (this.broadcasting && (room.id === 'lobby' || room.battle)) return this.sendReply("This command is too spammy to broadcast in lobby/battles"); var buf = []; var showAll = (target === 'all'); for (var id in Tools.data.Formats) { var format = Tools.data.Formats[id]; if (!format) continue; if (format.effectType !== 'Format') continue; if (!format.challengeShow) continue; if (!showAll && !format.searchShow) continue; buf.push({ name: format.name, gameType: format.gameType || 'singles', mod: format.mod, searchShow: format.searchShow, desc: format.desc || 'No description.' }); } this.sendReplyBox( "Available Formats: (<strong>Bold</strong> formats are on ladder.)<br />" + buf.map(function (data) { var str = ""; // Bold = Ladderable. str += (data.searchShow ? "<strong>" + data.name + "</strong>" : data.name) + ": "; str += "(" + (!data.mod || data.mod === 'base' ? "" : data.mod + " ") + data.gameType + " format) "; str += data.desc; return str; }).join("<br />") ); },*/ roomhelp: function (target, room, user) { if (room.id === 'lobby' || room.battle) return this.sendReply("This command is too spammy for lobby/battles."); if (!this.canBroadcast()) return; this.sendReplyBox('Room drivers (%) can use:<br />' + '- /warn OR /k <em>username</em>: warn a user and show the Pokemon Showdown rules<br />' + '- /mute OR /m <em>username</em>: 7 minute mute<br />' + '- /hourmute OR /hm <em>username</em>: 60 minute mute<br />' + '- /unmute <em>username</em>: unmute<br />' + '- /announce OR /wall <em>message</em>: make an announcement<br />' + '- /modlog <em>username</em>: search the moderator log of the room<br />' + '<br />' + 'Room moderators (@) can also use:<br />' + '- /roomban OR /rb <em>username</em>: bans user from the room<br />' + '- /roomunban <em>username</em>: unbans user from the room<br />' + '- /roomvoice <em>username</em>: appoint a room voice<br />' + '- /roomdevoice <em>username</em>: remove a room voice<br />' + '- /modchat <em>[off/autoconfirmed/+]</em>: set modchat level<br />' + '<br />' + 'Room owners (#) can also use:<br />' + '- /roomdesc <em>description</em>: set the room description on the room join page<br />' + '- /rules <em>rules link</em>: set the room rules link seen when using /rules<br />' + '- /roommod, /roomdriver <em>username</em>: appoint a room moderator/driver<br />' + '- /roomdemod, /roomdedriver <em>username</em>: remove a room moderator/driver<br />' + '- /modchat <em>[%/@/#]</em>: set modchat level<br />' + '- /declare <em>message</em>: make a room declaration<br /><br>' + 'The room founder can also use:<br />' + '- /roomowner <em>username</em><br />' + '- /roomdeowner <em>username</em><br />' + '</div>'); }, restarthelp: function (target, room, user) { if (room.id === 'lobby' && !this.can('lockdown')) return false; if (!this.canBroadcast()) return; this.sendReplyBox('The server is restarting. Things to know:<br />' + '- We wait a few minutes before restarting so people can finish up their battles<br />' + '- The restart itself will take a few seconds<br />' + '- Your ladder ranking and teams will not change<br />' + '- We are restarting to update Gold to a newer version' + '</div>'); }, tc: 'tourhelp', th: 'tourhelp', tourhelp: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<b><font size="4"><font color="green">Tournament Commands List:</font></b><br>' + '<b>/tpoll</b> - Starts a poll asking what tier users want. Requires: +, %, @, &, ~. <br>' + '<b>/tour [tier], [number of people or xminutes]</b> Requires: +, %, @, &, ~.<br>' + '<b>/endtour</b> - Ends the current tournement. Requires: +, %, @, &, ~.<br>' + '<b>/replace [replacee], [replacement]</b> Requires: +, %, @, &, ~.<br>' + '<b>/dq [username]</b> - Disqualifies a user from the tournement. Requires: +, %, @, &, ~.<br>' + '<b>/fj [user]</b> - Forcibily joins a user into the tournement in the sign up phase. Requires: +, %, @, &, ~.<br>' + '<b>/fl [username]</b> - Forcibily makes a user leave the tournement in the sign up phase. Requires: +, %, @, &, ~.<br>' + '<b>/vr</b> - Views the current round in the tournement of whose won and whose lost and who hasn\'t started yet.<br>' + '<b>/toursize [number]</b> - Changes the tour size if you started it with a number instead of a time limit during the sign up phase.<br>' + '<b>/tourtime [xminutes]</b> - Changes the tour time if you started it with a time limit instead of a number during the sign up phase.<br>' + '<b><font size="2"><font color="green">Polls Commands List:</b></font><br>' + '<b>/poll [title], [option],[option], exc...</b> - Starts a poll. Requires: +, %, @, &, ~.<br>' + '<b>/pr</b> - Reminds you of what the current poll is.<br>' + '<b>/endpoll</b> - Ends the current poll. Requires: +, %, @, &, ~.<br>' + '<b>/vote [opinion]</b> - votes for an option of the current poll.<br><br>' + '<i>--Just ask in the lobby if you\'d like a voice or up to start a tourney!</i>'); }, rule: 'rules', rules: function (target, room, user) { if (!target) { if (!this.canBroadcast()) return; this.sendReplyBox("Please follow the rules:<br />" + (room.rulesLink ? "- <a href=\"" + Tools.escapeHTML(room.rulesLink) + "\">" + Tools.escapeHTML(room.title) + " room rules</a><br />" : "") + "- <a href=\"http://goldserver.weebly.com/rules.html\">" + (room.rulesLink ? "Global rules" : "Rules") + "</a>"); return; } if (!this.can('roommod', null, room)) return; if (target.length > 80) { return this.sendReply("Error: Room rules link is too long (must be under 80 characters). You can use a URL shortener to shorten the link."); } room.rulesLink = target.trim(); this.sendReply("(The room rules link is now: " + target + ")"); if (room.chatRoomData) { room.chatRoomData.rulesLink = room.rulesLink; Rooms.global.writeChatRoomData(); } }, faq: function (target, room, user) { if (!this.canBroadcast()) return; target = target.toLowerCase(); var buffer = ""; var matched = false; if (!target || target === 'all') { matched = true; buffer += "<a href=\"https://www.smogon.com/sim/faq\">Frequently Asked Questions</a><br />"; } if (target === 'deviation') { matched = true; buffer += "<a href=\"https://www.smogon.com/sim/faq#deviation\">Why did this user gain or lose so many points?</a><br />"; } if (target === 'doubles' || target === 'triples' || target === 'rotation') { matched = true; buffer += "<a href=\"https://www.smogon.com/sim/faq#doubles\">Can I play doubles/triples/rotation battles here?</a><br />"; } if (target === 'randomcap') { matched = true; buffer += "<a href=\"https://www.smogon.com/sim/faq#randomcap\">What is this fakemon and what is it doing in my random battle?</a><br />"; } if (target === 'restarts') { matched = true; buffer += "<a href=\"https://www.smogon.com/sim/faq#restarts\">Why is the server restarting?</a><br />"; } if (target === 'all' || target === 'star' || target === 'player') { matched = true; buffer += '<a href="http://www.smogon.com/sim/faq#star">Why is there this star (&starf;) in front of my username?</a><br />'; } if (target === 'staff') { matched = true; buffer += '<a href="http://goldserver.weebly.com/how-do-i-get-a-rank.html">Staff FAQ</a><br />'; } if (target === 'autoconfirmed' || target === 'ac') { matched = true; buffer += "A user is autoconfirmed when they have won at least one rated battle and have been registered for a week or longer.<br />"; } if (target === 'all' || target === 'customsymbol' || target === 'cs') { matched = true; buffer += 'A custom symbol will bring your name up to the top of the userlist with a custom symbol next to it. These reset after the server restarts.<br />'; } if (target === 'all' || target === 'league') { matched = true; buffer += 'Welcome to Gold! So, you\'re interested in making or moving a league here? If so, read <a href="http://goldserver.weebly.com/making-a-league.html">this</a> and write down your answers on a <a href="http://pastebin.com">Pastebin</a> and PM it to an admin. Good luck!<br />'; } if (!matched) { return this.sendReply("The FAQ entry '" + target + "' was not found. Try /faq for general help."); } this.sendReplyBox(buffer); }, banlists: 'tiers', tier: 'tiers', tiers: function (target, room, user) { if (!this.canBroadcast()) return; target = toId(target); var buffer = ""; var matched = false; if (!target || target === 'all') { matched = true; buffer += "- <a href=\"https://www.smogon.com/tiers/\">Smogon Tiers</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/tiering-faq.3498332/\">Tiering FAQ</a><br />"; buffer += "- <a href=\"https://www.smogon.com/xyhub/tiers\">The banlists for each tier</a><br />"; } if (target === 'overused' || target === 'ou') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3514144/\">np: OU Stage 6</a><br />"; buffer += "- <a href=\"https://www.smogon.com/dex/xy/tags/ou/\">OU Banlist</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3515714/\">OU Viability Rankings</a><br />"; } if (target === 'ubers' || target === 'uber') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3513127/\">np: XY Ubers Gengarite Suspect Test</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3496305/\">Ubers Viability Rankings</a><br />"; } if (target === 'underused' || target === 'uu') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3516640/\">np: UU Stage 3</a><br />"; buffer += "- <a href=\"https://www.smogon.com/dex/xy/tags/uu/\">UU Banlist</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3516418/\">UU Viability Rankings</a><br />"; } if (target === 'rarelyused' || target === 'ru') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3515615/\">np: RU Stage 4</a><br />"; buffer += "- <a href=\"https://www.smogon.com/dex/xy/tags/ru/\">RU Banlist</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3516783/\">RU Viability Rankings</a><br />"; } if (target === 'neverused' || target === 'nu') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3516675/\">np: NU Stage 2</a><br />"; buffer += "- <a href=\"https://www.smogon.com/dex/xy/tags/nu/\">NU Banlist</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3509494/\">NU Viability Rankings</a><br />"; } if (target === 'littlecup' || target === 'lc') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3496013/\">LC Viability Rankings</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3490462/\">Official LC Banlist</a><br />"; } if (target === 'smogondoubles' || target === 'doubles') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3509279/\">np: Doubles Stage 3.5</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3498688/\">Doubles Banlist</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3496306/\">Doubles Viability Rankings</a><br />"; } if (!matched) { return this.sendReply("The Tiers entry '" + target + "' was not found. Try /tiers for general help."); } this.sendReplyBox(buffer); }, analysis: 'smogdex', strategy: 'smogdex', smogdex: function (target, room, user) { if (!this.canBroadcast()) return; var targets = target.split(','); if (toId(targets[0]) === 'previews') return this.sendReplyBox("<a href=\"https://www.smogon.com/forums/threads/sixth-generation-pokemon-analyses-index.3494918/\">Generation 6 Analyses Index</a>, brought to you by <a href=\"https://www.smogon.com\">Smogon University</a>"); var pokemon = Tools.getTemplate(targets[0]); var item = Tools.getItem(targets[0]); var move = Tools.getMove(targets[0]); var ability = Tools.getAbility(targets[0]); var atLeastOne = false; var generation = (targets[1] || 'xy').trim().toLowerCase(); var genNumber = 6; // var doublesFormats = {'vgc2012':1, 'vgc2013':1, 'vgc2014':1, 'doubles':1}; var doublesFormats = {}; var doublesFormat = (!targets[2] && generation in doublesFormats)? generation : (targets[2] || '').trim().toLowerCase(); var doublesText = ''; if (generation === 'xy' || generation === 'xy' || generation === '6' || generation === 'six') { generation = 'xy'; } else if (generation === 'bw' || generation === 'bw2' || generation === '5' || generation === 'five') { generation = 'bw'; genNumber = 5; } else if (generation === 'dp' || generation === 'dpp' || generation === '4' || generation === 'four') { generation = 'dp'; genNumber = 4; } else if (generation === 'adv' || generation === 'rse' || generation === 'rs' || generation === '3' || generation === 'three') { generation = 'rs'; genNumber = 3; } else if (generation === 'gsc' || generation === 'gs' || generation === '2' || generation === 'two') { generation = 'gs'; genNumber = 2; } else if (generation === 'rby' || generation === 'rb' || generation === '1' || generation === 'one') { generation = 'rb'; genNumber = 1; } else { generation = 'xy'; } if (doublesFormat !== '') { // Smogon only has doubles formats analysis from gen 5 onwards. if (!(generation in {'bw':1, 'xy':1}) || !(doublesFormat in doublesFormats)) { doublesFormat = ''; } else { doublesText = {'vgc2012':"VGC 2012", 'vgc2013':"VGC 2013", 'vgc2014':"VGC 2014", 'doubles':"Doubles"}[doublesFormat]; doublesFormat = '/' + doublesFormat; } } // Pokemon if (pokemon.exists) { atLeastOne = true; if (genNumber < pokemon.gen) { return this.sendReplyBox("" + pokemon.name + " did not exist in " + generation.toUpperCase() + "!"); } // if (pokemon.tier === 'CAP') generation = 'cap'; if (pokemon.tier === 'CAP') return this.sendReply("CAP is not currently supported by Smogon Strategic Pokedex."); var illegalStartNums = {'351':1, '421':1, '487':1, '493':1, '555':1, '647':1, '648':1, '649':1, '681':1}; if (pokemon.isMega || pokemon.num in illegalStartNums) pokemon = Tools.getTemplate(pokemon.baseSpecies); var poke = pokemon.name.toLowerCase().replace(/\ /g, '_').replace(/[^a-z0-9\-\_]+/g, ''); this.sendReplyBox("<a href=\"https://www.smogon.com/dex/" + generation + "/pokemon/" + poke + doublesFormat + "\">" + generation.toUpperCase() + " " + doublesText + " " + pokemon.name + " analysis</a>, brought to you by <a href=\"https://www.smogon.com\">Smogon University</a>"); } // Item if (item.exists && genNumber > 1 && item.gen <= genNumber) { atLeastOne = true; var itemName = item.name.toLowerCase().replace(' ', '_'); this.sendReplyBox("<a href=\"https://www.smogon.com/dex/" + generation + "/items/" + itemName + "\">" + generation.toUpperCase() + " " + item.name + " item analysis</a>, brought to you by <a href=\"https://www.smogon.com\">Smogon University</a>"); } // Ability if (ability.exists && genNumber > 2 && ability.gen <= genNumber) { atLeastOne = true; var abilityName = ability.name.toLowerCase().replace(' ', '_'); this.sendReplyBox("<a href=\"https://www.smogon.com/dex/" + generation + "/abilities/" + abilityName + "\">" + generation.toUpperCase() + " " + ability.name + " ability analysis</a>, brought to you by <a href=\"https://www.smogon.com\">Smogon University</a>"); } // Move if (move.exists && move.gen <= genNumber) { atLeastOne = true; var moveName = move.name.toLowerCase().replace(' ', '_'); this.sendReplyBox("<a href=\"https://www.smogon.com/dex/" + generation + "/moves/" + moveName + "\">" + generation.toUpperCase() + " " + move.name + " move analysis</a>, brought to you by <a href=\"https://www.smogon.com\">Smogon University</a>"); } if (!atLeastOne) { return this.sendReplyBox("Pokemon, item, move, or ability not found for generation " + generation.toUpperCase() + "."); } }, forums: function(target, room, user) { if (!this.canBroadcast()) return; return this.sendReplyBox('Gold Forums can be found <a href="http://w11.zetaboards.com/Goldserverps/index/">here</a>.'); }, regdate: function(target, room, user, connection) { if (!this.canBroadcast()) return; if (!target || target =="0") return this.sendReply('Lol, you can\'t do that, you nub.'); if (!target || target == "." || target == "," || target == "'") return this.sendReply('/regdate - Please specify a valid username.'); //temp fix for symbols that break the command var username = target; target = target.replace(/\s+/g, ''); var util = require("util"), http = require("http"); var options = { host: "www.pokemonshowdown.com", port: 80, path: "/forum/~"+target }; var content = ""; var self = this; var req = http.request(options, function(res) { res.setEncoding("utf8"); res.on("data", function (chunk) { content += chunk; }); res.on("end", function () { content = content.split("<em"); if (content[1]) { content = content[1].split("</p>"); if (content[0]) { content = content[0].split("</em>"); if (content[1]) { regdate = content[1]; data = Tools.escapeHTML(username)+' was registered on'+regdate+'.'; } } } else { data = Tools.escapeHTML(username)+' is not registered.'; } self.sendReplyBox(Tools.escapeHTML(data)); }); }); req.end(); }, league: function(target, room, user) { if (!this.canBroadcast()) return; return this.sendReplyBox('<font size="2"><b><center>Goodra League</font></b></center>' + '★The league consists of 3 Gym Leaders<br /> ' + '★Currently the Champion position is empty.<br/>' + '★Be the first to complete the league, and the spot is yours!<br />' + '★The champion gets a FREE trainer card, custom avatar and global voice!<br />' + '★The Goodra League information can be found <a href="http://goldserver.weebly.com/league.html" >here</a>.<br />' + '★Click <button name=\"joinRoom\" value=\"goodraleague\">here</button> to enter our League\'s room!'); }, stafffaq: function (target, room, user) { if (!this.canBroadcast()) return; return this.sendReplyBox('Click <a href="http://goldserver.weebly.com/how-do-i-get-a-rank-on-gold.html">here</a> to find out about Gold\'s ranks and promotion system.'); }, //Should solve the problem of users not being able to talk in chat unstick: function(target, room, user) { if (!this.can('hotpatch')) return; for (var uid in Users.users) { Users.users[uid].chatQueue = null; Users.users[uid].chatQueueTimeout = null; } }, /********************************************************* * Miscellaneous commands *********************************************************/ //kupo: function(target, room, user){ //if(!this.canBroadcast()|| !user.can('broadcast')) return this.sendReply('/kupo - Access Denied.'); //if(!target) return this.sendReply('Insufficent Parameters.'); //room.add('|c|~kupo|/me '+ target); //this.logModCommand(user.name + ' used /kupo to say ' + target); //}, birkal: function(target, room, user) { this.sendReply("It's not funny anymore."); }, potd: function(target, room, user) { if (!this.can('potd')) return false; Config.potd = target; Simulator.SimulatorProcess.eval('Config.potd = \'' + toId(target) + '\''); if (target) { if (Rooms.lobby) Rooms.lobby.addRaw("<div class=\"broadcast-blue\"><b>The Pokemon of the Day is now " + target + "!</b><br />This Pokemon will be guaranteed to show up in random battles.</div>"); this.logModCommand("The Pokemon of the Day was changed to " + target + " by " + user.name + "."); } else { if (Rooms.lobby) Rooms.lobby.addRaw("<div class=\"broadcast-blue\"><b>The Pokemon of the Day was removed!</b><br />No pokemon will be guaranteed in random battles.</div>"); this.logModCommand("The Pokemon of the Day was removed by " + user.name + "."); } }, nstaffmemberoftheday: 'smotd', nsmotd: function(target, room, user){ if (room.id !== 'lobby') return this.sendReply("This command can only be used in Lobby."); //Users cannot do HTML tags with this command. if (target.indexOf('<img ') > -1) { return this.sendReply('HTML is not supported in this command.') } if (target.indexOf('<a href') > -1) { return this.sendReply('HTML is not supported in this command.') } if (target.indexOf('<font ') > -1) { return this.sendReply('HTML is not supported in this command.') } if (target.indexOf('<marquee') > -1) { return this.sendReply('HTML is not supported in this command.') } if (target.indexOf('<blink') > -1) { return this.sendReply('HTML is not supported in this command.') } if (target.indexOf('<center') > -1) { return this.sendReply('HTML is not supported in this command.') } if(!target) return this.sendReply('/nsmotd needs an Staff Member.'); //Users who are muted cannot use this command. if (target.length > 25) { return this.sendReply('This Staff Member\'s name is too long; it cannot exceed 25 characters.'); } if (!this.canTalk()) return; room.addRaw(''+user.name+'\'s nomination for Staff Member of the Day is: <b><i>' + target +'</i></b>'); }, staffmemberoftheday: 'smotd', smotd: function(target, room, user) { if (room.id !== 'lobby') return this.sendReply("This command can only be used in Lobby."); //User use HTML with this command. if (target.indexOf('<img ') > -1) { return this.sendReply('HTML is not supported in this command.') } if (target.indexOf('<a href') > -1) { return this.sendReply('HTML is not supported in this command.') } if (target.indexOf('<font ') > -1) { return this.sendReply('HTML is not supported in this command.') } if (target.indexOf('<marquee') > -1) { return this.sendReply('HTML is not supported in this command.') } if (target.indexOf('<blink') > -1) { return this.sendReply('HTML is not supported in this command.') } if (target.indexOf('<center') > -1) { return this.sendReply('HTML is not supported in this command.') } if (!target) { //allows user to do /smotd to view who is the Staff Member of the day if people forget. return this.sendReply('The current Staff Member of the Day is: '+room.smotd); } //Users who are muted cannot use this command. if (!this.canTalk()) return; //Only room drivers and up may use this command. if (target.length > 25) { return this.sendReply('This Staff Member\'s name is too long; it cannot exceed 25 characters.'); } if (!this.can('mute', null, room)) return; room.smotd = target; if (target) { //if a user does /smotd (Staff Member name here), then we will display the Staff Member of the Day. room.addRaw('<div class="broadcast-red"><font size="2"><b>The Staff Member of the Day is now <font color="black">'+target+'!</font color></font size></b> <font size="1">(Set by '+user.name+'.)<br />This Staff Member is now the honorary Staff Member of the Day!</div>'); this.logModCommand('The Staff Member of the Day was changed to '+target+' by '+user.name+'.'); } else { //If there is no target, then it will remove the Staff Member of the Day. room.addRaw('<div class="broadcast-green"><b>The Staff Member of the Day was removed!</b><br />There is no longer an Staff Member of the day today!</div>'); this.logModCommand('The Staff Member of the Day was removed by '+user.name+'.'); } }, roll: 'dice', dice: function (target, room, user) { if (!target) return this.parse('/help dice'); if (!this.canBroadcast()) return; var d = target.indexOf("d"); if (d >= 0) { var num = parseInt(target.substring(0, d)); var faces; if (target.length > d) faces = parseInt(target.substring(d + 1)); if (isNaN(num)) num = 1; if (isNaN(faces)) return this.sendReply("The number of faces must be a valid integer."); if (faces < 1 || faces > 1000) return this.sendReply("The number of faces must be between 1 and 1000"); if (num < 1 || num > 20) return this.sendReply("The number of dice must be between 1 and 20"); var rolls = []; var total = 0; for (var i = 0; i < num; ++i) { rolls[i] = (Math.floor(faces * Math.random()) + 1); total += rolls[i]; } return this.sendReplyBox("Random number " + num + "x(1 - " + faces + "): " + rolls.join(", ") + "<br />Total: " + total); } if (target && isNaN(target) || target.length > 21) return this.sendReply("The max roll must be a number under 21 digits."); var maxRoll = (target)? target : 6; var rand = Math.floor(maxRoll * Math.random()) + 1; return this.sendReplyBox("Random number (1 - " + maxRoll + "): " + rand); }, /*/ rollgame: 'dicegame', dicegame: function(target, room, user) { if (!this.canBroadcast()) return; if (Users.get(''+user.name+'').money < target) { return this.sendReply('You cannot wager more than you have, nub.'); } if(!target) return this.sendReply('/dicegame [amount of bucks agreed to wager].'); if (isNaN(target)) { return this.sendReply('Very funny, now use a real number.'); } if (String(target).indexOf('.') >= 0) { return this.sendReply('You cannot wager numbers with decimals.'); } if (target < 0) { return this.sendReply('Number cannot be negative.'); } if (target > 100) { return this.sendReply('Error: You cannot wager over 100 bucks.'); } if (target == 0) { return this.sendReply('Number cannot be 0.'); } var player1 = Math.floor(6 * Math.random()) + 1; var player2 = Math.floor(6 * Math.random()) + 1; var winner = ''; var loser= ''; if (player1 > player2) { winner = 'The <b>winner</b> is <font color="green">'+user.name+'</font>!'; loser = 'Better luck next time, computer!'; return this.add('|c|~crowt|.custom /tb '+user.name+','+target+''); } if (player1 < player2) { winner = 'The <b>winner</b> is <font color="green">Opponent</font>!'; loser = 'Better luck next time, '+user.name+'!'; return this.add('|c|~crowt|.custom /removebucks '+user.name+','+target+''); } if (player1 === player2) { winner = 'It\'s a <b>tie</b>!'; loser = 'Try again!'; } return this.sendReplyBox('<center><font size="4"><b><img border="5" title="Dice Game!"></b></font></center><br />' + '<font color="red">This game is worth '+target+' buck(s).</font><br />' + 'Loser: Tranfer bucks to the winner using /tb [winner], '+target+' <br />' + '<hr>' + ''+user.name+' roll (1-6): '+player1+'<br />' + 'Opponent roll (1-6): '+player2+'<br />' + '<hr>' + 'Winner: '+winner+'<br />' + ''+loser+''); }, */ removebadge: function(target, room, user) { if (!this.can('hotpatch')) return false; target = this.splitTarget(target); var targetUser = this.targetUser; if (!target) return this.sendReply('/removebadge [user], [badge] - Removes a badge from a user.'); if (!targetUser) return this.sendReply('There is no user named '+this.targetUsername+'.'); var self = this; var type_of_badges = ['admin','bot','dev','vip','artist','mod','leader','champ','creator','concun','twinner','goodra','league']; if (type_of_badges.indexOf(target) > -1 == false) return this.sendReply('The badge '+target+' is not a valid badge.'); fs.readFile('badges.txt','utf8', function(err, data) { if (err) console.log(err); var match = false; var currentbadges = ''; var row = (''+data).split('\n'); var line = ''; for (var i = row.length; i > -1; i--) { if (!row[i]) continue; var split = row[i].split(':'); if (split[0] == targetUser.userid) { match = true; currentbadges = split[1]; line = row[i]; } } if (match == true) { if (currentbadges.indexOf(target) > -1 == false) return self.sendReply(currentbadges);//'The user '+targetUser+' does not have the badge.'); var re = new RegExp(line, 'g'); currentbadges = currentbadges.replace(target,''); var newdata = data.replace(re, targetUser.userid+':'+currentbadges); fs.writeFile('badges.txt',newdata, 'utf8', function(err, data) { if (err) console.log(err); return self.sendReply('You have removed the badge '+target+' from the user '+targetUser+'.'); }); } else { return self.sendReply('There is no match for the user '+targetUser+'.'); } }); }, givebadge: function(target, room, user) { if (!this.can('hotpatch')) return false; target = this.splitTarget(target); var targetUser = this.targetUser; if (!targetUser) return this.sendReply('There is no user named '+this.targetUsername+'.'); if (!target) return this.sendReply('/givebadge [user], [badge] - Gives a badge to a user. Requires: &~'); var self = this; var type_of_badges = ['admin','bot','dev','vip','mod','artist','leader','champ','creator','comcun','twinner','league']; if (type_of_badges.indexOf(target) > -1 == false) return this.sendReply('Ther is no badge named '+target+'.'); fs.readFile('badges.txt', 'utf8', function(err, data) { if (err) console.log(err); var currentbadges = ''; var line = ''; var row = (''+data).split('\n'); var match = false; for (var i = row.length; i > -1; i--) { if (!row[i]) continue; var split = row[i].split(':'); if (split[0] == targetUser.userid) { match = true; currentbadges = split[1]; line = row[i]; } } if (match == true) { if (currentbadges.indexOf(target) > -1) return self.sendReply('The user '+targerUser+' already has the badge '+target+'.'); var re = new RegExp(line, 'g'); var newdata = data.replace(re, targetUser.userid+':'+currentbadges+target); fs.writeFile('badges.txt', newdata, function(err, data) { if (err) console.log(err); self.sendReply('You have given the badge '+target+' to the user '+targetUser+'.'); targetUser.send('You have recieved the badge '+target+' from the user '+user.userid+'.'); room.addRaw(targetUser+' has recieved the '+target+' badge from '+user.name); }); } else { fs.appendFile('badges.txt','\n'+targetUser.userid+':'+target, function(err) { if (err) console.log(err); self.sendReply('You have given the badge '+target+' to the user '+targetUser+'.'); targetUser.send('You have recieved the badge '+target+' from the user '+user.userid+'.'); }); } }) }, badgelist: function(target, room, user) { if (!this.canBroadcast()) return; var admin = '<img src="http://www.smogon.com/media/forums/images/badges/sop.png" title="Server Administrator">'; var dev = '<img src="http://www.smogon.com/media/forums/images/badges/factory_foreman.png" title="Gold Developer">'; var creator = '<img src="http://www.smogon.com/media/forums/images/badges/dragon.png" title="Server Creator">'; var comcun = '<img src="http://www.smogon.com/media/forums/images/badges/cc.png" title="Community Contributor">'; var leader = '<img src="http://www.smogon.com/media/forums/images/badges/aop.png" title="Server Leader">'; var mod = '<img src="http://www.smogon.com/media/forums/images/badges/pyramid_king.png" title="Exceptional Staff Member">'; var league ='<img src="http://www.smogon.com/media/forums/images/badges/forumsmod.png" title="Successful League Owner">'; var champ ='<img src="http://www.smogon.com/media/forums/images/badges/forumadmin_alum.png" title="Goodra League Champion">'; var artist ='<img src="http://www.smogon.com/media/forums/images/badges/ladybug.png" title="Artist">'; var twinner='<img src="http://www.smogon.com/media/forums/images/badges/spl.png" title="Badge Tournament Winner">'; var vip ='<img src="http://www.smogon.com/media/forums/images/badges/zeph.png" title="VIP">'; var bot ='<img src="http://www.smogon.com/media/forums/images/badges/mind.png" title="Gold Bot Hoster">'; return this.sendReplyBox('<b>List of Gold Badges</b>:<br> '+admin+' '+dev+' '+creator+' '+comcun+' '+mod+' '+leader+' '+league+' '+champ+' '+artist+' '+twinner+' '+vip+' '+bot+' <br>--Hover over them to see the meaning of each.<br>--Get a badge and get a FREE custom avatar!<br>--Click <a href="http://goldserver.weebly.com/badges.html">here</a> to find out more about how to get a badge.'); }, badges: 'badge', badge: function(target, room, user) { if (!this.canBroadcast()) return; if (target == '') target = user.userid; target = this.splitTarget(target); var targetUser = this.targetUser; var matched = false; if (!targetUser) return false; var admin = '<img src="http://www.smogon.com/media/forums/images/badges/sop.png" title="Server Administrator">'; var dev = '<img src="http://www.smogon.com/media/forums/images/badges/factory_foreman.png" title="Gold Developer">'; var creator = '<img src="http://www.smogon.com/media/forums/images/badges/dragon.png" title="Server Creator">'; var comcun = '<img src="http://www.smogon.com/media/forums/images/badges/cc.png" title="Community Contributor">'; var leader = '<img src="http://www.smogon.com/media/forums/images/badges/aop.png" title="Server Leader">'; var mod = '<img src="http://www.smogon.com/media/forums/images/badges/pyramid_king.png" title="Exceptional Staff Member">'; var league ='<img src="http://www.smogon.com/media/forums/images/badges/forumsmod.png" title="Successful League Owner">'; var champ ='<img src="http://www.smogon.com/media/forums/images/badges/forumadmin_alum.png" title="Goodra League Champion">'; var artist ='<img src="http://www.smogon.com/media/forums/images/badges/ladybug.png" title="Artist">'; var twinner='<img src="http://www.smogon.com/media/forums/images/badges/spl.png" title="Badge Tournament Winner">'; var vip ='<img src="http://www.smogon.com/media/forums/images/badges/zeph.png" title="VIP">'; var bot ='<img src="http://www.smogon.com/media/forums/images/badges/mind.png" title="Gold Bot Hoster">'; var self = this; fs.readFile('badges.txt', 'utf8', function(err, data) { if (err) console.log(err); var row = (''+data).split('\n'); var match = false; var badges; for (var i = row.length; i > -1; i--) { if (!row[i]) continue; var split = row[i].split(':'); if (split[0] == targetUser.userid) { match = true; currentbadges = split[1]; } } if (match == true) { var badgelist = ''; if (currentbadges.indexOf('admin') > -1) badgelist+=' '+admin; if (currentbadges.indexOf('dev') > -1) badgelist+=' '+dev; if (currentbadges.indexOf('creator') > -1) badgelist+=' '+creator; if (currentbadges.indexOf('comcun') > -1) badgelist+=' '+comcun; if (currentbadges.indexOf('leader') > -1) badgelist+=' '+leader; if (currentbadges.indexOf('mod') > -1) badgelist+=' '+mod; if (currentbadges.indexOf('league') > -1) badgelist+=' '+league; if (currentbadges.indexOf('champ') > -1) badgelist+=' '+champ; if (currentbadges.indexOf('artist') > -1) badgelist+=' '+artist; if (currentbadges.indexOf('twinner') > -1) badgelist+=' '+twinner; if (currentbadges.indexOf('vip') > -1) badgelist+=' '+vip; if (currentbadges.indexOf('bot') > -1) badgelist+=' '+bot; self.sendReplyBox(targetUser.userid+"'s badges: "+badgelist); room.update(); } else { self.sendReplyBox('User '+targetUser.userid+' has no badges.'); room.update(); } }); }, helixfossil: 'm8b', helix: 'm8b', magic8ball: 'm8b', m8b: function(target, room, user) { if (!this.canBroadcast()) return; var random = Math.floor(20 * Math.random()) + 1; var results = ''; if (random == 1) { results = 'Signs point to yes.'; } if (random == 2) { results = 'Yes.'; } if (random == 3) { results = 'Reply hazy, try again.'; } if (random == 4) { results = 'Without a doubt.'; } if (random == 5) { results = 'My sources say no.'; } if (random == 6) { results = 'As I see it, yes.'; } if (random == 7) { results = 'You may rely on it.'; } if (random == 8) { results = 'Concentrate and ask again.'; } if (random == 9) { results = 'Outlook not so good.'; } if (random == 10) { results = 'It is decidedly so.'; } if (random == 11) { results = 'Better not tell you now.'; } if (random == 12) { results = 'Very doubtful.'; } if (random == 13) { results = 'Yes - definitely.'; } if (random == 14) { results = 'It is certain.'; } if (random == 15) { results = 'Cannot predict now.'; } if (random == 16) { results = 'Most likely.'; } if (random == 17) { results = 'Ask again later.'; } if (random == 18) { results = 'My reply is no.'; } if (random == 19) { results = 'Outlook good.'; } if (random == 20) { results = 'Don\'t count on it.'; } return this.sendReplyBox(''+results+''); }, hue: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><img src="http://reactiongifs.me/wp-content/uploads/2013/08/ducks-laughing.gif">'); }, coins: 'coingame', coin: 'coingame', coingame: function(target, room, user) { if (!this.canBroadcast()) return; var random = Math.floor(2 * Math.random()) + 1; var results = ''; if (random == 1) { results = '<img src="http://surviveourcollapse.com/wp-content/uploads/2013/01/zinc.png" width="15%" title="Heads!"><br>It\'s heads!'; } if (random == 2) { results = '<img src="http://upload.wikimedia.org/wikipedia/commons/e/e5/2005_Penny_Rev_Unc_D.png" width="15%" title="Tails!"><br>It\'s tails!'; } return this.sendReplyBox('<center><font size="3"><b>Coin Game!</b></font><br>'+results+''); }, p: 'panagrams', panagrams: function(target, room, user) { if(!user.can('ban')) return; if (room.id == 'lobby') { room.addRaw( '<div class="broadcast-black"><b><center><font size="3">Panagrams has started!</font></b>' + '<center>This is Gold\'s version of anagrams, but with buck prizes! We currently have a random category and a Pokemon category!<br />' + '<button name="joinRoom" value="panagrams" target="_blank">Play now!</button></center></div>' ); } else { room.addRaw( '<div class="broadcast-black"><center><font size="3">A panagrams session is about to begin!</font></center></div>' ); } }, one: function(target, room, user) { if (room.id !== '1v1') return this.sendReply("This command can only be used in 1v1."); if (!this.canBroadcast()) return; var messages = { onevone: 'Global 1v1 bans are: Focus Sash, Sturdy (if doesnt naturally learn it), Sleep, Imposter/imprison, Parental Bond, and level 100 Pokemon only. You are only allowed to use "3 team preview" in all tiers falling under the "1v1 Elimination" tier. All other tiers must be 1 Pokemon only. No switching', reg: 'This is regular 1v1, only bans are Sleep, Ubers (except mega gengar), and ditto (imposter/imprison)', monogen: 'You may only use pokemon, from the gen decided by the !roll command. No ubers, and no sleep', monotype: 'You may only use Pokemon from the type dictated by the !roll command. Here are the list of types. http://bulbapedia.bulbagarden.net/wiki/Type_chart No ubers, and no sleep', monopoke: 'You may only use the Pokemon decided by the !roll command. No ubers, and no sleep', monoletter: 'You may only use Pokemon starting with the same letter dictated by the !roll command. No ubers, and no sleep.', monocolor: 'You may only use Pokemon sharing the same color dictated by the !pickrandom command.', cap: '1v1 using Create-A-Pokemon! No sleep, no focus sash.', megaevo: 'Only bring one Pokemon. http://pastebin.com/d9pJWpya ', bstbased: 'You may only use Pokemon based off or lower than the BST decided by !roll command. ', metronome: 'Only bring one Pokemon. http://pastebin.com/diff.php?i=QPZBDzKb ', twovtwo: 'You may only use 2 pokemon, banlist include: no sleep, no ubers (mega gengar allowed), only one focus sash, no parental bond. ', ouonevone: 'OU choice- The OU version of CC1v1. You use an OU team, and choose one Pokemon in battle. Once that Pokemon faints, you forfeit. You must use the same OU team throughout the tour, but you can change which Pokemon you select to choose. No ubers, no focus sash, no sleep. ', aaa: 'http://www.smogon.com/forums/threads/almost-any-ability-xy-aaa-xy-other-metagame-of-the-month-may.3495737/ You may only use a team of ONE pokemon, banlist in this room for this tier are: Sleep, focus sash, Sturdy, Parental Bond, Huge Power, Pure Power, Imprison, Normalize (on ghosts). ', stabmons: 'http://www.smogon.com/forums/threads/3484106/ You may only use a team of ONE Pokemon. Banlist = Sleep, Focus sash, Huge Power, Pure power, Sturdy, Parental Bond, Ubers. ', abccup: 'http://www.smogon.com/forums/threads/alphabet-cup-other-metagame-of-the-month-march.3498167/ You may only use a team of ONE Pokemon. Banlist = Sleep, Focus sash, Huge Power, Pure power, Sturdy, Parental Bond, Ubers. ', averagemons: 'http://www.smogon.com/forums/threads/averagemons.3495527/ You may only use a team of ONE Pokemon. Banlist = Sleep, Focus sash, Huge Power, Pure power, Sturdy, Parental Bond, Sableye. ', balancedhackmons: 'http://www.smogon.com/forums/threads/3463764/ You may only use a team of ONE Pokemon. Banlist = Sleep, Focus sash, Huge Power, Pure power, Sturdy, Parental Bond, Normalize Ghosts.', retro: 'This is how 1v1 used to be played before 3 team preview. Only bring ONE Pokemon, No sleep, no ubers (except mega gengar), no ditto. ', mediocremons: 'https://www.smogon.com/forums/threads/mediocre-mons-venomoth-banned.3507608/ You many only use a team of ONE Pokemon Banlist = Sleep, Focus sash, Huge Power, Pure power, Sturdy. ', eeveeonly: 'You may bring up to 3 mons that are eeveelutions. No sleep inducing moves. ', tiershift: 'http://www.smogon.com/forums/threads/tier-shift-xy.3508369/ Tiershift 1v1, you may only bring ONE Pokemon. roombans are slaking, sleep, sash, sturdy, ditto ', lc: 'Only use a team of ONE LC Pokemon. No sleep, no sash. ', lcstarters: 'Only use a team of ONE starter Pokemon in LC form. No sleep, no sash, no pikachu, no eevee. ', ubers: 'Only use a team of ONE uber pokemon. No sleep, no sash ', inverse: 'https://www.smogon.com/forums/threads/the-inverse-battle-ǝɯɐƃɐʇǝɯ.3492433/ You may use ONE pokemon. No sleep, no sash, no ubers (except mega gengar). ', }; try { return this.sendReplyBox(messages[target]); } catch (e) { this.sendReply('There is no target named /one '+target); } if (!target) { this.sendReplyBox('Available commands for /one: ' + Object.keys(messages).join(', ')); } }, color: function(target, room, user) { if (!this.canBroadcast()) return; if (target === 'list' || target === 'help' || target === 'options') { return this.sendReplyBox('The random colors are: <b><font color="red">Red</font>, <font color="blue">Blue</font>, <font color="orange">Orange</font>, <font color="green">Green</font>, <font color="teal">Teal</font>, <font color="brown">Brown</font>, <font color="black">Black</font>, <font color="purple">Purple</font>, <font color="pink">Pink</font>, <font color="gray">Gray</font>, <font color="tan">Tan</font>, <font color="gold">Gold</font>, <font color=#CC0000>R</font><font color=#AE1D00>a</font><font color=#913A00>i</font><font color=#745700>n</font><font color=#577400>b</font><font color=#3A9100>o</font><font color=#1DAE00>w</font>.'); } var colors = ['Red','Blue','Orange','Green','Teal','Brown','Black','Purple','Pink','Grey','Tan','Gold']; var results = colors[Math.floor(Math.random()*colors.length)]; if (results == 'Rainbow') { return this.sendReply('The random color is :<b><font color=#CC0000>R</font><font color=#AE1D00>a</font><font color=#913A00>i</font><font color=#745700>n</font><font color=#577400>b</font><font color=#3A9100>o</font><font color=#1DAE00>w</font></b>'); } else { return this.sendReplyBox('The random color is:<b><font color='+results+'>'+results+'</font></b>'); } }, guesscolor: function(target, room, user){ if (!target) return this.sendReply('/guesscolor [color] - Guesses a random color.'); var html = ['<img ','<a href','<font ','<marquee','<blink','<center']; for (var x in html) { if (target.indexOf(html[x]) > -1) return this.sendReply('HTML is not supported in this command.'); } if (target.length > 15) return this.sendReply('This new room suggestion is too long; it cannot exceed 15 characters.'); if (!this.canTalk()) return; Rooms.rooms.room.add('|html|<font size="4"><b>New color guessed!</b></font><br><b>Guessed by:</b> '+user.userid+'<br><b>Color:</b> '+target+''); this.sendReply('Thanks, your new color guess has been sent. We\'ll review your color soon and get back to you. ("'+target+'")'); }, pick: 'pickrandom', pickrandom: function (target, room, user) { var options = target.split(','); if (options.length < 2) return this.parse('/help pick'); if (!this.canBroadcast()) return false; return this.sendReplyBox('<em>We randomly picked:</em> ' + Tools.escapeHTML(options.sample().trim())); }, register: function () { if (!this.canBroadcast()) return; this.sendReplyBox('You will be prompted to register upon winning a rated battle. Alternatively, there is a register button in the <button name="openOptions"><i class="icon-cog"></i> Options</button> menu in the upper right.'); }, lobbychat: function (target, room, user, connection) { if (!Rooms.lobby) return this.popupReply("This server doesn't have a lobby."); target = toId(target); if (target === 'off') { user.leaveRoom(Rooms.lobby, connection.socket); connection.send('|users|'); this.sendReply("You are now blocking lobby chat."); } else { user.joinRoom(Rooms.lobby, connection); this.sendReply("You are now receiving lobby chat."); } }, showimage: function (target, room, user) { if (!target) return this.parse('/help showimage'); if (!this.can('declare', null, room)) return false; if (!this.canBroadcast()) return; var targets = target.split(','); if (targets.length !== 3) { return this.parse('/help showimage'); } this.sendReply('|raw|<img src="' + Tools.escapeHTML(targets[0]) + '" alt="" width="' + toId(targets[1]) + '" height="' + toId(targets[2]) + '" />'); }, htmlbox: function (target, room, user) { if (!target) return this.parse('/help htmlbox'); if (!this.can('declare', null, room)) return; if (!this.canHTML(target)) return; if (!this.canBroadcast('!htmlbox')) return; this.sendReplyBox(target); }, a: function (target, room, user) { if (!this.canTalk()) return; if (!this.can('rawpacket')) return false; // secret sysop command room.add(target); }, /* emotes: 'emoticon', emoticons: 'emoticon', emoticon: function (target, room, user) { if (!this.canBroadcast()) return; var name = Object.keys(Core.emoticons), emoticons = []; var len = name.length; while (len--) { emoticons.push((Core.processEmoticons(name[(name.length-1)-len]) + '&nbsp;' + name[(name.length-1)-len])); } this.sendReplyBox('<b><u>List of emoticons:</b></u> <br/><br/>' + emoticons.join(' ').toString()); }, */ sca: 'customavatar', setcustomavatar: 'customavatar', setcustomavi: 'customavatar', giveavatar: 'customavatar', customavatars: 'customavatar', customavatar: (function () { const script = (function () {/* FILENAME=`mktemp` function cleanup { rm -f $FILENAME } trap cleanup EXIT set -xe timeout 10 wget "$1" -nv -O $FILENAME FRAMES=`identify $FILENAME | wc -l` if [ $FRAMES -gt 1 ]; then EXT=".gif" else EXT=".png" fi timeout 10 convert $FILENAME -layers TrimBounds -coalesce -adaptive-resize 80x80\> -background transparent -gravity center -extent 80x80 "$2$EXT" */}).toString().match(/[^]*\/\*([^]*)\*\/\}$/)[1]; var pendingAdds = {}; return function (target, room, user) { var parts = target.split(','); var cmd = parts[0].trim().toLowerCase(); if (cmd in {'':1, show:1, view:1, display:1}) { var message = ""; for (var a in Config.customavatars) message += "<strong>" + Tools.escapeHTML(a) + ":</strong> " + Tools.escapeHTML(Config.customavatars[a]) + "<br />"; return this.sendReplyBox(message); } if (!this.can('giveavatar') && !user.vip) return false; switch (cmd) { case 'add': case 'set': var userid = toId(parts[1]); if (!this.can('giveavatar') && user.vip && userid !== user.userid) return false; var user = Users.getExact(userid); var avatar = parts.slice(2).join(',').trim(); if (!userid) return this.sendReply("You didn't specify a user."); if (Config.customavatars[userid]) return this.sendReply(userid + " already has a custom avatar."); var hash = require('crypto').createHash('sha512').update(userid + '\u0000' + avatar).digest('hex').slice(0, 8); pendingAdds[hash] = {userid: userid, avatar: avatar}; parts[1] = hash; if (!user) { this.sendReply("Warning: " + userid + " is not online."); this.sendReply("If you want to continue, use: /customavatar forceset, " + hash); return; } // Fallthrough case 'forceset': var hash = parts[1].trim(); if (!pendingAdds[hash]) return this.sendReply("Invalid hash."); var userid = pendingAdds[hash].userid; var avatar = pendingAdds[hash].avatar; delete pendingAdds[hash]; require('child_process').execFile('bash', ['-c', script, '-', avatar, './config/avatars/' + userid], (function (e, out, err) { if (e) { this.sendReply(userid + "'s custom avatar failed to be set. Script output:"); (out + err).split('\n').forEach(this.sendReply.bind(this)); return; } reloadCustomAvatars(); this.sendReply(userid + "'s custom avatar has been set."); Rooms.rooms.staff.add(parts[1]+' has received a custom avatar from '+user.name+'.'); }).bind(this)); break; case 'rem': case 'remove': case 'del': case 'delete': var userid = toId(parts[1]); if (!this.can('giveavatar') && user.vip && userid !== user.userid) return false; if (!Config.customavatars[userid]) return this.sendReply(userid + " does not have a custom avatar."); if (Config.customavatars[userid].toString().split('.').slice(0, -1).join('.') !== userid) return this.sendReply(userid + "'s custom avatar (" + Config.customavatars[userid] + ") cannot be removed with this script."); require('fs').unlink('./config/avatars/' + Config.customavatars[userid], (function (e) { if (e) return this.sendReply(userid + "'s custom avatar (" + Config.customavatars[userid] + ") could not be removed: " + e.toString()); delete Config.customavatars[userid]; this.sendReply(userid + "'s custom avatar removed successfully"); }).bind(this)); break; default: return this.sendReply("Invalid command. Valid commands are `/customavatar set, user, avatar` and `/customavatar delete, user`."); } }; })(), /********************************************************* * Help commands *********************************************************/ commands: 'help', h: 'help', '?': 'help', help: function (target, room, user) { target = target.toLowerCase(); var matched = false; if (target === 'msg' || target === 'pm' || target === 'whisper' || target === 'w') { matched = true; this.sendReply("/msg OR /whisper OR /w [username], [message] - Send a private message."); } if (target === 'r' || target === 'reply') { matched = true; this.sendReply("/reply OR /r [message] - Send a private message to the last person you received a message from, or sent a message to."); } if (target === 'rating' || target === 'ranking' || target === 'rank' || target === 'ladder') { matched = true; this.sendReply("/rating - Get your own rating."); this.sendReply("/rating [username] - Get user's rating."); } if (target === 'nick') { matched = true; this.sendReply("/nick [new username] - Change your username."); } if (target === 'avatar') { matched = true; this.sendReply("/avatar [new avatar number] - Change your trainer sprite."); } if (target === 'whois' || target === 'alts' || target === 'ip' || target === 'rooms') { matched = true; this.sendReply("/whois - Get details on yourself: alts, group, IP address, and rooms."); this.sendReply("/whois [username] - Get details on a username: alts (Requires: % @ & ~), group, IP address (Requires: @ & ~), and rooms."); } if (target === 'data') { matched = true; this.sendReply("/data [pokemon/item/move/ability] - Get details on this pokemon/item/move/ability/nature."); this.sendReply("!data [pokemon/item/move/ability] - Show everyone these details. Requires: + % @ & ~"); } if (target === 'details' || target === 'dt') { matched = true; this.sendReply("/details [pokemon] - Get additional details on this pokemon/item/move/ability/nature."); this.sendReply("!details [pokemon] - Show everyone these details. Requires: + % @ & ~"); } if (target === 'analysis') { matched = true; this.sendReply("/analysis [pokemon], [generation] - Links to the Smogon University analysis for this Pokemon in the given generation."); this.sendReply("!analysis [pokemon], [generation] - Shows everyone this link. Requires: + % @ & ~"); } if (target === 'groups') { matched = true; this.sendReply("/groups - Explains what the + % @ & next to people's names mean."); this.sendReply("!groups - Show everyone that information. Requires: + % @ & ~"); } if (target === 'opensource') { matched = true; this.sendReply("/opensource - Links to PS's source code repository."); this.sendReply("!opensource - Show everyone that information. Requires: + % @ & ~"); } if (target === 'avatars') { matched = true; this.sendReply("/avatars - Explains how to change avatars."); this.sendReply("!avatars - Show everyone that information. Requires: + % @ & ~"); } if (target === 'intro') { matched = true; this.sendReply("/intro - Provides an introduction to competitive pokemon."); this.sendReply("!intro - Show everyone that information. Requires: + % @ & ~"); } if (target === 'cap') { matched = true; this.sendReply("/cap - Provides an introduction to the Create-A-Pokemon project."); this.sendReply("!cap - Show everyone that information. Requires: + % @ & ~"); } if (target === 'om') { matched = true; this.sendReply("/om - Provides links to information on the Other Metagames."); this.sendReply("!om - Show everyone that information. Requires: + % @ & ~"); } if (target === 'learn' || target === 'learnset' || target === 'learnall') { matched = true; this.sendReply("/learn [pokemon], [move, move, ...] - Displays how a Pokemon can learn the given moves, if it can at all."); this.sendReply("!learn [pokemon], [move, move, ...] - Show everyone that information. Requires: + % @ & ~"); } if (target === 'calc' || target === 'calculator') { matched = true; this.sendReply("/calc - Provides a link to a damage calculator"); this.sendReply("!calc - Shows everyone a link to a damage calculator. Requires: + % @ & ~"); } if (target === 'blockchallenges' || target === 'away' || target === 'idle') { matched = true; this.sendReply("/away - Blocks challenges so no one can challenge you. Deactivate it with /back."); } if (target === 'allowchallenges' || target === 'back') { matched = true; this.sendReply("/back - Unlocks challenges so you can be challenged again. Deactivate it with /away."); } if (target === 'faq') { matched = true; this.sendReply("/faq [theme] - Provides a link to the FAQ. Add deviation, doubles, randomcap, restart, or staff for a link to these questions. Add all for all of them."); this.sendReply("!faq [theme] - Shows everyone a link to the FAQ. Add deviation, doubles, randomcap, restart, or staff for a link to these questions. Add all for all of them. Requires: + % @ & ~"); } if (target === 'highlight') { matched = true; this.sendReply("Set up highlights:"); this.sendReply("/highlight add, word - add a new word to the highlight list."); this.sendReply("/highlight list - list all words that currently highlight you."); this.sendReply("/highlight delete, word - delete a word from the highlight list."); this.sendReply("/highlight delete - clear the highlight list"); } if (target === 'timestamps') { matched = true; this.sendReply("Set your timestamps preference:"); this.sendReply("/timestamps [all|lobby|pms], [minutes|seconds|off]"); this.sendReply("all - change all timestamps preferences, lobby - change only lobby chat preferences, pms - change only PM preferences"); this.sendReply("off - set timestamps off, minutes - show timestamps of the form [hh:mm], seconds - show timestamps of the form [hh:mm:ss]"); } if (target === 'effectiveness' || target === 'matchup' || target === 'eff' || target === 'type') { matched = true; this.sendReply("/effectiveness OR /matchup OR /eff OR /type [attack], [defender] - Provides the effectiveness of a move or type on another type or a Pokémon."); this.sendReply("!effectiveness OR !matchup OR !eff OR !type [attack], [defender] - Shows everyone the effectiveness of a move or type on another type or a Pokémon."); } if (target === 'dexsearch' || target === 'dsearch' || target === 'ds') { matched = true; this.sendReply("/dexsearch [type], [move], [move], ... - Searches for Pokemon that fulfill the selected criteria."); this.sendReply("Search categories are: type, tier, color, moves, ability, gen."); this.sendReply("Valid colors are: green, red, blue, white, brown, yellow, purple, pink, gray and black."); this.sendReply("Valid tiers are: Uber/OU/BL/UU/BL2/RU/BL3/NU/PU/LC/CAP."); this.sendReply("Types must be followed by ' type', e.g., 'dragon type'."); this.sendReply("Parameters can be excluded through the use of '!', e.g., '!water type' excludes all water types."); this.sendReply("The parameter 'mega' can be added to search for Mega Evolutions only, and the parameters 'FE' or 'NFE' can be added to search fully or not-fully evolved Pokemon only."); this.sendReply("The order of the parameters does not matter."); } if (target === 'dice' || target === 'roll') { matched = true; this.sendReply("/dice [optional max number] - Randomly picks a number between 1 and 6, or between 1 and the number you choose."); this.sendReply("/dice [number of dice]d[number of sides] - Simulates rolling a number of dice, e.g., /dice 2d4 simulates rolling two 4-sided dice."); } if (target === 'pick' || target === 'pickrandom') { matched = true; this.sendReply("/pick [option], [option], ... - Randomly selects an item from a list containing 2 or more elements."); } if (target === 'join') { matched = true; this.sendReply("/join [roomname] - Attempts to join the room [roomname]."); } if (target === 'ignore') { matched = true; this.sendReply("/ignore [user] - Ignores all messages from the user [user]."); this.sendReply("Note that staff messages cannot be ignored."); } if (target === 'invite') { matched = true; this.sendReply("/invite [username], [roomname] - Invites the player [username] to join the room [roomname]."); } // driver commands if (target === 'lock' || target === 'l') { matched = true; this.sendReply("/lock OR /l [username], [reason] - Locks the user from talking in all chats. Requires: % @ & ~"); } if (target === 'unlock') { matched = true; this.sendReply("/unlock [username] - Unlocks the user. Requires: % @ & ~"); } if (target === 'redirect' || target === 'redir') { matched = true; this.sendReply("/redirect OR /redir [username], [roomname] - Attempts to redirect the user [username] to the room [roomname]. Requires: % @ & ~"); } if (target === 'modnote') { matched = true; this.sendReply("/modnote [note] - Adds a moderator note that can be read through modlog. Requires: % @ & ~"); } if (target === 'forcerename' || target === 'fr') { matched = true; this.sendReply("/forcerename OR /fr [username], [reason] - Forcibly change a user's name and shows them the [reason]. Requires: % @ & ~"); } if (target === 'kickbattle ') { matched = true; this.sendReply("/kickbattle [username], [reason] - Kicks a user from a battle with reason. Requires: % @ & ~"); } if (target === 'warn' || target === 'k') { matched = true; this.sendReply("/warn OR /k [username], [reason] - Warns a user showing them the Pokemon Showdown Rules and [reason] in an overlay. Requires: % @ & ~"); } if (target === 'modlog') { matched = true; this.sendReply("/modlog [roomid|all], [n] - Roomid defaults to current room. If n is a number or omitted, display the last n lines of the moderator log. Defaults to 15. If n is not a number, search the moderator log for 'n' on room's log [roomid]. If you set [all] as [roomid], searches for 'n' on all rooms's logs. Requires: % @ & ~"); } if (target === 'mute' || target === 'm') { matched = true; this.sendReply("/mute OR /m [username], [reason] - Mutes a user with reason for 7 minutes. Requires: % @ & ~"); } if (target === 'hourmute' || target === 'hm') { matched = true; this.sendReply("/hourmute OR /hm [username], [reason] - Mutes a user with reason for an hour. Requires: % @ & ~"); } if (target === 'unmute' || target === 'um') { matched = true; this.sendReply("/unmute [username] - Removes mute from user. Requires: % @ & ~"); } // mod commands if (target === 'roomban' || target === 'rb') { matched = true; this.sendReply("/roomban [username] - Bans the user from the room you are in. Requires: @ & ~"); } if (target === 'roomunban') { matched = true; this.sendReply("/roomunban [username] - Unbans the user from the room you are in. Requires: @ & ~"); } if (target === 'ban' || target === 'b') { matched = true; this.sendReply("/ban OR /b [username], [reason] - Kick user from all rooms and ban user's IP address with reason. Requires: @ & ~"); } if (target === 'unban') { matched = true; this.sendReply("/unban [username] - Unban a user. Requires: @ & ~"); } // RO commands if (target === 'showimage') { matched = true; this.sendReply("/showimage [url], [width], [height] - Show an image. Requires: # & ~"); } if (target === 'roompromote') { matched = true; this.sendReply("/roompromote [username], [group] - Promotes the user to the specified group or next ranked group. Requires: @ # & ~"); } if (target === 'roomdemote') { matched = true; this.sendReply("/roomdemote [username], [group] - Demotes the user to the specified group or previous ranked group. Requires: @ # & ~"); } // leader commands if (target === 'banip') { matched = true; this.sendReply("/banip [ip] - Kick users on this IP or IP range from all rooms and bans it. Accepts wildcards to ban ranges. Requires: & ~"); } if (target === 'unbanip') { matched = true; this.sendReply("/unbanip [ip] - Kick users on this IP or IP range from all rooms and bans it. Accepts wildcards to ban ranges. Requires: & ~"); } if (target === 'unbanall') { matched = true; this.sendReply("/unbanall - Unban all IP addresses. Requires: & ~"); } if (target === 'promote') { matched = true; this.sendReply("/promote [username], [group] - Promotes the user to the specified group or next ranked group. Requires: & ~"); } if (target === 'demote') { matched = true; this.sendReply("/demote [username], [group] - Demotes the user to the specified group or previous ranked group. Requires: & ~"); } if (target === 'forcetie') { matched = true; this.sendReply("/forcetie - Forces the current match to tie. Requires: & ~"); } if (target === 'declare') { matched = true; this.sendReply("/declare [message] - Anonymously announces a message. Requires: & ~"); } // admin commands if (target === 'chatdeclare' || target === 'cdeclare') { matched = true; this.sendReply("/cdeclare [message] - Anonymously announces a message to all chatrooms on the server. Requires: ~"); } if (target === 'globaldeclare' || target === 'gdeclare') { matched = true; this.sendReply("/globaldeclare [message] - Anonymously announces a message to every room on the server. Requires: ~"); } if (target === 'htmlbox') { matched = true; this.sendReply("/htmlbox [message] - Displays a message, parsing HTML code contained. Requires: ~ # with global authority"); } if (target === 'announce' || target === 'wall') { matched = true; this.sendReply("/announce OR /wall [message] - Makes an announcement. Requires: % @ & ~"); } if (target === 'modchat') { matched = true; this.sendReply("/modchat [off/autoconfirmed/+/%/@/&/~] - Set the level of moderated chat. Requires: @ for off/autoconfirmed/+ options, & ~ for all the options"); } if (target === 'hotpatch') { matched = true; this.sendReply("Hot-patching the game engine allows you to update parts of Showdown without interrupting currently-running battles. Requires: ~"); this.sendReply("Hot-patching has greater memory requirements than restarting."); this.sendReply("/hotpatch chat - reload chat-commands.js"); this.sendReply("/hotpatch battles - spawn new simulator processes"); this.sendReply("/hotpatch formats - reload the tools.js tree, rebuild and rebroad the formats list, and also spawn new simulator processes"); } if (target === 'lockdown') { matched = true; this.sendReply("/lockdown - locks down the server, which prevents new battles from starting so that the server can eventually be restarted. Requires: ~"); } if (target === 'kill') { matched = true; this.sendReply("/kill - kills the server. Can't be done unless the server is in lockdown state. Requires: ~"); } if (target === 'loadbanlist') { matched = true; this.sendReply("/loadbanlist - Loads the bans located at ipbans.txt. The command is executed automatically at startup. Requires: ~"); } if (target === 'makechatroom') { matched = true; this.sendReply("/makechatroom [roomname] - Creates a new room named [roomname]. Requires: ~"); } if (target === 'deregisterchatroom') { matched = true; this.sendReply("/deregisterchatroom [roomname] - Deletes room [roomname] after the next server restart. Requires: ~"); } if (target === 'roomowner') { matched = true; this.sendReply("/roomowner [username] - Appoints [username] as a room owner. Removes official status. Requires: ~"); } if (target === 'roomdeowner') { matched = true; this.sendReply("/roomdeowner [username] - Removes [username]'s status as a room owner. Requires: ~"); } if (target === 'privateroom') { matched = true; this.sendReply("/privateroom [on/off] - Makes or unmakes a room private. Requires: ~"); } // overall if (target === 'help' || target === 'h' || target === '?' || target === 'commands') { matched = true; this.sendReply("/help OR /h OR /? - Gives you help."); } if (!target) { this.sendReply("COMMANDS: /nick, /avatar, /rating, /whois, /msg, /reply, /ignore, /away, /back, /timestamps, /highlight"); this.sendReply("INFORMATIONAL COMMANDS: /data, /dexsearch, /groups, /opensource, /avatars, /faq, /rules, /intro, /tiers, /othermetas, /learn, /analysis, /calc (replace / with ! to broadcast. Broadcasting requires: + % @ & ~)"); if (user.group !== Config.groupsranking[0]) { this.sendReply("DRIVER COMMANDS: /warn, /mute, /unmute, /alts, /forcerename, /modlog, /lock, /unlock, /announce, /redirect"); this.sendReply("MODERATOR COMMANDS: /ban, /unban, /ip"); this.sendReply("LEADER COMMANDS: /declare, /forcetie, /forcewin, /promote, /demote, /banip, /unbanall"); } this.sendReply("For an overview of room commands, use /roomhelp"); this.sendReply("For details of a specific command, use something like: /help data"); } else if (!matched) { this.sendReply("Help for the command '" + target + "' was not found. Try /help for general help"); } } };
chaotic tc
config/commands.js
chaotic tc
<ide><path>onfig/commands.js <ide> if (!this.canBroadcast()) return; <ide> this.sendReplyBox('<center><font size="5"><font color="#140391">ashbloodthief</font></font></center> <center><img src="http://107.191.104.240:8000/avatars/ashbloodthief.gif" width=100 height=100></center> <center><img src="http://fc04.deviantart.net/fs71/f/2013/259/f/f/mega_lucario_by_henshingeneration-d6mihft.jpg" width=270 height=200></center><br /> <center><font size="3"> Ace: Mega Lucario</font></center> <center><font size="3"> I\'m a being pure as energy! You can\'t stop me!</font></center>'); <ide> }, <add> <add> chaotic: function(target, room, user) { <add> if (!this.canBroadCast()) return; <add> this.sendReplayBox("<center><img src=\"http://i.imgur.com/NVEZJG1.png\" title=\"Hosted by imgur.com\" width=\"400\" height=\"100\"> </a><br><img src=\"http://media0.giphy.com/media/DCp4s7Z1FizZe/giphy.gif\" width=\"250\" height=\"250\"><img src=\"http://i269.photobucket.com/albums/jj77/YandereGIFs/Durarara%20GIFs/IzayaScared.gif\" width=\"250\" height=\"250\"> <br><center><b>\"A Caterpie may change into a Butterfree, but the heart that beats inside remains the same.\"</b>"); <add> }, <ide> <ide> //***********************Music Boxes*************************** <ide>
Java
apache-2.0
a0e2d3ea30c6debb8423f7b6ac80a37d6de8f5b9
0
ywjno/nutz,nutzam/nutz,elkan1788/nutz,nutzam/nutz,ywjno/nutz,ywjno/nutz,elkan1788/nutz,nutzam/nutz,elkan1788/nutz,nutzam/nutz,ywjno/nutz,elkan1788/nutz,ywjno/nutz,nutzam/nutz
package org.nutz.ioc.loader.annotation; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import org.nutz.ioc.IocException; import org.nutz.ioc.IocLoader; import org.nutz.ioc.IocLoading; import org.nutz.ioc.Iocs; import org.nutz.ioc.ObjectLoadException; import org.nutz.ioc.annotation.InjectName; import org.nutz.ioc.meta.IocEventSet; import org.nutz.ioc.meta.IocField; import org.nutz.ioc.meta.IocObject; import org.nutz.ioc.meta.IocValue; import org.nutz.json.Json; import org.nutz.lang.Lang; import org.nutz.lang.Mirror; import org.nutz.lang.Strings; import org.nutz.lang.util.MethodParamNamesScaner; import org.nutz.log.Log; import org.nutz.log.Logs; import org.nutz.resource.Scans; /** * 基于注解的Ioc配置 * * @author wendal([email protected]) * */ public class AnnotationIocLoader implements IocLoader { private static final Log log = Logs.get(); private HashMap<String, IocObject> map = new HashMap<String, IocObject>(); protected String[] packages; public AnnotationIocLoader() { packages = new String[0]; } public AnnotationIocLoader(String... packages) { for (String pkg : packages) { log.infof(" > scan '%s'", pkg); for (Class<?> classZ : Scans.me().scanPackage(pkg)) addClass(classZ); } if (map.isEmpty()) { log.warnf("NONE @IocBean found!! Check your ioc configure!! packages=%s", Arrays.toString(packages)); } this.packages = packages; } public void addClass(Class<?> classZ) { if (classZ.isInterface() || classZ.isMemberClass() || classZ.isEnum() || classZ.isAnnotation() || classZ.isAnonymousClass()) return; int modify = classZ.getModifiers(); if (Modifier.isAbstract(modify) || (!Modifier.isPublic(modify))) return; IocBean iocBean = classZ.getAnnotation(IocBean.class); if (iocBean != null) { // 采用 @IocBean->name String beanName = iocBean.name(); if (Strings.isBlank(beanName)) { // 否则采用 @InjectName InjectName innm = classZ.getAnnotation(InjectName.class); if (null != innm && !Strings.isBlank(innm.value())) { beanName = innm.value(); } // 大哥(姐),您都不设啊!? 那就用 simpleName 吧 else { beanName = Strings.lowerFirst(classZ.getSimpleName()); } } // 重名了, 需要用户用@IocBean(name="xxxx") 区分一下 if (map.containsKey(beanName)) throw new IocException(beanName, "Duplicate beanName=%s, by %s !! Have been define by %s !!", beanName, classZ.getName(), map.get(beanName).getType().getName()); IocObject iocObject = new IocObject(); iocObject.setType(classZ); map.put(beanName, iocObject); log.infof(" > add '%-40s' - %s", beanName, classZ.getName()); iocObject.setSingleton(iocBean.singleton()); if (!Strings.isBlank(iocBean.scope())) iocObject.setScope(iocBean.scope()); // 看看构造函数都需要什么函数 String[] args = iocBean.args(); // if (null == args || args.length == 0) // args = iocBean.param(); if (null != args && args.length > 0) for (String value : args) iocObject.addArg(Iocs.convert(value, true)); // 设置Events IocEventSet eventSet = new IocEventSet(); iocObject.setEvents(eventSet); if (!Strings.isBlank(iocBean.create())) eventSet.setCreate(iocBean.create().trim().intern()); if (!Strings.isBlank(iocBean.depose())) eventSet.setDepose(iocBean.depose().trim().intern()); if (!Strings.isBlank(iocBean.fetch())) eventSet.setFetch(iocBean.fetch().trim().intern()); // 处理字段(以@Inject方式,位于字段) List<String> fieldList = new ArrayList<String>(); Mirror<?> mirror = Mirror.me(classZ); Field[] fields = mirror.getFields(Inject.class); for (Field field : fields) { Inject inject = field.getAnnotation(Inject.class); // 无需检查,因为字段名是唯一的 // if(fieldList.contains(field.getName())) // throw duplicateField(classZ,field.getName()); IocField iocField = new IocField(); iocField.setName(field.getName()); IocValue iocValue; if (Strings.isBlank(inject.value())) { if (field.getName().equals("ioc")) { iocValue = new IocValue(); iocValue.setType(IocValue.TYPE_REFER); iocValue.setValue("$ioc"); } else { iocValue = new IocValue(); iocValue.setType(IocValue.TYPE_REFER_TYPE); iocValue.setValue(field); } } else iocValue = Iocs.convert(inject.value(), true); iocField.setValue(iocValue); iocField.setOptional(inject.optional()); iocObject.addField(iocField); fieldList.add(iocField.getName()); } // 处理字段(以@Inject方式,位于set方法) Method[] methods; try { methods = classZ.getMethods(); } catch (Exception e) { // 如果获取失败,就忽略之 log.infof("Fail to call getMethods() in Class=%s, miss class or Security Limit, ignore it", classZ, e); methods = new Method[0]; } catch (NoClassDefFoundError e) { log.infof("Fail to call getMethods() in Class=%s, miss class or Security Limit, ignore it", classZ, e); methods = new Method[0]; } for (Method method : methods) { Inject inject = method.getAnnotation(Inject.class); if (inject == null) continue; // 过滤特殊方法 int m = method.getModifiers(); if (Modifier.isAbstract(m) || (!Modifier.isPublic(m)) || Modifier.isStatic(m)) continue; String methodName = method.getName(); if (methodName.startsWith("set") && methodName.length() > 3 && method.getParameterTypes().length == 1) { IocField iocField = new IocField(); iocField.setName(Strings.lowerFirst(methodName.substring(3))); if (fieldList.contains(iocField.getName())) throw duplicateField(beanName, classZ, iocField.getName()); IocValue iocValue; if (Strings.isBlank(inject.value())) { iocValue = new IocValue(); iocValue.setType(IocValue.TYPE_REFER_TYPE); iocValue.setValue(Strings.lowerFirst(methodName.substring(3)) + "#" + method.getParameterTypes()[0].getName()); } else iocValue = Iocs.convert(inject.value(), true); iocField.setValue(iocValue); iocObject.addField(iocField); fieldList.add(iocField.getName()); } } // 处理字段(以@IocBean.field方式) String[] flds = iocBean.fields(); if (flds != null && flds.length > 0) { for (String fieldInfo : flds) { if (fieldList.contains(fieldInfo)) throw duplicateField(beanName, classZ, fieldInfo); IocField iocField = new IocField(); if (fieldInfo.contains(":")) { // dao:jndi:dataSource/jdbc形式 String[] datas = fieldInfo.split(":", 2); // 完整形式, 与@Inject完全一致了 iocField.setName(datas[0]); iocField.setValue(Iocs.convert(datas[1], true)); iocObject.addField(iocField); } else { // 基本形式, 引用与自身同名的bean iocField.setName(fieldInfo); IocValue iocValue = new IocValue(); iocValue.setType(IocValue.TYPE_REFER); iocValue.setValue(fieldInfo); iocField.setValue(iocValue); iocObject.addField(iocField); } fieldList.add(iocField.getName()); } } // 处理工厂方法 if (!Strings.isBlank(iocBean.factory())) { iocObject.setFactory(iocBean.factory()); } // 看看有没有方法标注了@IocBean for (Method method : methods) { IocBean ib = method.getAnnotation(IocBean.class); if (ib == null) continue; handleIocBeanMethod(method, ib, beanName); } } else { // 不再检查其他类. } } protected void handleIocBeanMethod(Method method, IocBean ib, String facotryBeanName) { String beanName = ib.name(); if (Strings.isBlank(beanName)) { String methodName = method.getName(); if (methodName.startsWith("get")) { methodName = methodName.substring(3); } else if (methodName.startsWith("build")) { methodName = methodName.substring(5); } beanName = Strings.lowerFirst(methodName); } if (log.isDebugEnabled()) log.debugf("Found @IocBean method : %s define as name=%s", Lang.simpleMethodDesc(method), beanName); IocObject iobj = new IocObject(); iobj.setType(method.getReturnType()); iobj.setFactory("$"+facotryBeanName+"#"+method.getName()); List<String> paramNames = MethodParamNamesScaner.getParamNames(method); Class<?>[] paramTypes = method.getParameterTypes(); Annotation[][] anns = method.getParameterAnnotations(); for (int i = 0; i < paramTypes.length; i++) { Class<?> paramType = paramTypes[i]; String paramName = (paramNames != null && (paramNames.size() >= (i - 1))) ? paramNames.get(i) : "arg" + i; IocValue ival = new IocValue(); Inject inject = null; if (anns[i] != null && anns[i].length > 0) { for (Annotation anno : anns[i]) { if (anno instanceof Inject) { inject = (Inject)anno; break; } } } if (inject == null || Strings.isBlank(inject.value())) { ival.setType(IocValue.TYPE_REFER_TYPE); ival.setValue(paramName + "#" + paramType.getName()); } else { ival = Iocs.convert(inject.value(), true); } iobj.addArg(ival); } // 设置Events IocEventSet eventSet = new IocEventSet(); iobj.setEvents(eventSet); if (!Strings.isBlank(ib.create())) eventSet.setCreate(ib.create().trim().intern()); if (!Strings.isBlank(ib.depose())) eventSet.setDepose(ib.depose().trim().intern()); if (!Strings.isBlank(ib.fetch())) eventSet.setFetch(ib.fetch().trim().intern()); iobj.setSingleton(ib.singleton()); map.put(beanName, iobj); } public String[] getName() { return map.keySet().toArray(new String[map.size()]); } public boolean has(String name) { return map.containsKey(name); } public IocObject load(IocLoading loading, String name) throws ObjectLoadException { if (has(name)) return map.get(name); throw new ObjectLoadException("Object '" + name + "' without define! Pls check your ioc configure"); } private static final IocException duplicateField(String beanName, Class<?> classZ, String name) { return new IocException(beanName, "Duplicate filed defined! Class=%s,FileName=%s", classZ, name); } public String toString() { return "/*AnnotationIocLoader*/\n" + Json.toJson(map); } public String[] getPackages() { return packages; } }
src/org/nutz/ioc/loader/annotation/AnnotationIocLoader.java
package org.nutz.ioc.loader.annotation; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import org.nutz.ioc.IocException; import org.nutz.ioc.IocLoader; import org.nutz.ioc.IocLoading; import org.nutz.ioc.Iocs; import org.nutz.ioc.ObjectLoadException; import org.nutz.ioc.annotation.InjectName; import org.nutz.ioc.meta.IocEventSet; import org.nutz.ioc.meta.IocField; import org.nutz.ioc.meta.IocObject; import org.nutz.ioc.meta.IocValue; import org.nutz.json.Json; import org.nutz.lang.Lang; import org.nutz.lang.Mirror; import org.nutz.lang.Strings; import org.nutz.lang.util.MethodParamNamesScaner; import org.nutz.log.Log; import org.nutz.log.Logs; import org.nutz.resource.Scans; /** * 基于注解的Ioc配置 * * @author wendal([email protected]) * */ public class AnnotationIocLoader implements IocLoader { private static final Log log = Logs.get(); private HashMap<String, IocObject> map = new HashMap<String, IocObject>(); protected String[] packages; public AnnotationIocLoader() { packages = new String[0]; } public AnnotationIocLoader(String... packages) { for (String pkg : packages) { log.infof(" > scan '%s'", pkg); for (Class<?> classZ : Scans.me().scanPackage(pkg)) addClass(classZ); } if (map.isEmpty()) { log.warnf("NONE @IocBean found!! Check your ioc configure!! packages=%s", Arrays.toString(packages)); } this.packages = packages; } public void addClass(Class<?> classZ) { if (classZ.isInterface() || classZ.isMemberClass() || classZ.isEnum() || classZ.isAnnotation() || classZ.isAnonymousClass()) return; int modify = classZ.getModifiers(); if (Modifier.isAbstract(modify) || (!Modifier.isPublic(modify))) return; IocBean iocBean = classZ.getAnnotation(IocBean.class); if (iocBean != null) { // 采用 @IocBean->name String beanName = iocBean.name(); if (Strings.isBlank(beanName)) { // 否则采用 @InjectName InjectName innm = classZ.getAnnotation(InjectName.class); if (null != innm && !Strings.isBlank(innm.value())) { beanName = innm.value(); } // 大哥(姐),您都不设啊!? 那就用 simpleName 吧 else { beanName = Strings.lowerFirst(classZ.getSimpleName()); } } // 重名了, 需要用户用@IocBean(name="xxxx") 区分一下 if (map.containsKey(beanName)) throw new IocException(beanName, "Duplicate beanName=%s, by %s !! Have been define by %s !!", beanName, classZ.getName(), map.get(beanName).getType().getName()); IocObject iocObject = new IocObject(); iocObject.setType(classZ); map.put(beanName, iocObject); log.infof(" > add '%-40s' - %s", beanName, classZ.getName()); iocObject.setSingleton(iocBean.singleton()); if (!Strings.isBlank(iocBean.scope())) iocObject.setScope(iocBean.scope()); // 看看构造函数都需要什么函数 String[] args = iocBean.args(); // if (null == args || args.length == 0) // args = iocBean.param(); if (null != args && args.length > 0) for (String value : args) iocObject.addArg(Iocs.convert(value, true)); // 设置Events IocEventSet eventSet = new IocEventSet(); iocObject.setEvents(eventSet); if (!Strings.isBlank(iocBean.create())) eventSet.setCreate(iocBean.create().trim().intern()); if (!Strings.isBlank(iocBean.depose())) eventSet.setDepose(iocBean.depose().trim().intern()); if (!Strings.isBlank(iocBean.fetch())) eventSet.setFetch(iocBean.fetch().trim().intern()); // 处理字段(以@Inject方式,位于字段) List<String> fieldList = new ArrayList<String>(); Mirror<?> mirror = Mirror.me(classZ); Field[] fields = mirror.getFields(Inject.class); for (Field field : fields) { Inject inject = field.getAnnotation(Inject.class); // 无需检查,因为字段名是唯一的 // if(fieldList.contains(field.getName())) // throw duplicateField(classZ,field.getName()); IocField iocField = new IocField(); iocField.setName(field.getName()); IocValue iocValue; if (Strings.isBlank(inject.value())) { if (field.getName().equals("ioc")) { iocValue = new IocValue(); iocValue.setType(IocValue.TYPE_REFER); iocValue.setValue("$ioc"); } else { iocValue = new IocValue(); iocValue.setType(IocValue.TYPE_REFER_TYPE); iocValue.setValue(field); } } else iocValue = Iocs.convert(inject.value(), true); iocField.setValue(iocValue); iocField.setOptional(inject.optional()); iocObject.addField(iocField); fieldList.add(iocField.getName()); } // 处理字段(以@Inject方式,位于set方法) Method[] methods; try { methods = classZ.getMethods(); } catch (Exception e) { // 如果获取失败,就忽略之 log.infof("Fail to call getMethods() in Class=%s, miss class or Security Limit, ignore it", classZ, e); methods = new Method[0]; } catch (NoClassDefFoundError e) { log.infof("Fail to call getMethods() in Class=%s, miss class or Security Limit, ignore it", classZ, e); methods = new Method[0]; } for (Method method : methods) { Inject inject = method.getAnnotation(Inject.class); if (inject == null) continue; // 过滤特殊方法 int m = method.getModifiers(); if (Modifier.isAbstract(m) || (!Modifier.isPublic(m)) || Modifier.isStatic(m)) continue; String methodName = method.getName(); if (methodName.startsWith("set") && methodName.length() > 3 && method.getParameterTypes().length == 1) { IocField iocField = new IocField(); iocField.setName(Strings.lowerFirst(methodName.substring(3))); if (fieldList.contains(iocField.getName())) throw duplicateField(beanName, classZ, iocField.getName()); IocValue iocValue; if (Strings.isBlank(inject.value())) { iocValue = new IocValue(); iocValue.setType(IocValue.TYPE_REFER_TYPE); iocValue.setValue(Strings.lowerFirst(methodName.substring(3)) + "#" + method.getParameterTypes()[0].getName()); } else iocValue = Iocs.convert(inject.value(), true); iocField.setValue(iocValue); iocObject.addField(iocField); fieldList.add(iocField.getName()); } } // 处理字段(以@IocBean.field方式) String[] flds = iocBean.fields(); if (flds != null && flds.length > 0) { for (String fieldInfo : flds) { if (fieldList.contains(fieldInfo)) throw duplicateField(beanName, classZ, fieldInfo); IocField iocField = new IocField(); if (fieldInfo.contains(":")) { // dao:jndi:dataSource/jdbc形式 String[] datas = fieldInfo.split(":", 2); // 完整形式, 与@Inject完全一致了 iocField.setName(datas[0]); iocField.setValue(Iocs.convert(datas[1], true)); iocObject.addField(iocField); } else { // 基本形式, 引用与自身同名的bean iocField.setName(fieldInfo); IocValue iocValue = new IocValue(); iocValue.setType(IocValue.TYPE_REFER); iocValue.setValue(fieldInfo); iocField.setValue(iocValue); iocObject.addField(iocField); } fieldList.add(iocField.getName()); } } // 处理工厂方法 if (!Strings.isBlank(iocBean.factory())) { iocObject.setFactory(iocBean.factory()); } // 看看有没有方法标注了@IocBean for (Method method : methods) { IocBean ib = method.getAnnotation(IocBean.class); if (ib == null) continue; handleIocBeanMethod(method, ib, beanName); } } else { // 不再检查其他类. } } protected void handleIocBeanMethod(Method method, IocBean ib, String facotryBeanName) { String beanName = ib.name(); if (Strings.isBlank(beanName)) { String methodName = method.getName(); if (methodName.startsWith("get")) { methodName = methodName.substring(3); } else if (methodName.startsWith("build")) { methodName = methodName.substring(5); } beanName = Strings.lowerFirst(methodName); } if (log.isDebugEnabled()) log.debugf("Found @IocBean method : %s define as name=%s", Lang.simpleMethodDesc(method), beanName); IocObject iobj = new IocObject(); iobj.setType(method.getReturnType()); iobj.setFactory("$"+facotryBeanName+"#"+method.getName()); List<String> paramNames = MethodParamNamesScaner.getParamNames(method); Class<?>[] paramTypes = method.getParameterTypes(); Annotation[][] anns = method.getParameterAnnotations(); for (int i = 0; i < paramTypes.length; i++) { Class<?> paramType = paramTypes[i]; String paramName = (paramNames != null && (paramNames.size() >= (i - 1))) ? paramNames.get(i) : "arg" + i; IocValue ival = new IocValue(); Inject inject = null; if (anns[i] != null && anns[i].length > 0) { for (Annotation anno : anns[i]) { if (anno instanceof Inject) { inject = (Inject)anno; break; } } } if (inject == null || Strings.isBlank(inject.value())) { ival.setType(IocValue.TYPE_REFER_TYPE); ival.setValue(paramName + "#" + paramType.getName()); } else { ival = Iocs.convert(inject.value(), true); } iobj.addArg(ival); } // 设置Events IocEventSet eventSet = new IocEventSet(); iobj.setEvents(eventSet); if (!Strings.isBlank(ib.create())) eventSet.setCreate(ib.create().trim().intern()); if (!Strings.isBlank(ib.depose())) eventSet.setDepose(ib.depose().trim().intern()); if (!Strings.isBlank(ib.fetch())) eventSet.setFetch(ib.fetch().trim().intern()); map.put(beanName, iobj); } public String[] getName() { return map.keySet().toArray(new String[map.size()]); } public boolean has(String name) { return map.containsKey(name); } public IocObject load(IocLoading loading, String name) throws ObjectLoadException { if (has(name)) return map.get(name); throw new ObjectLoadException("Object '" + name + "' without define! Pls check your ioc configure"); } private static final IocException duplicateField(String beanName, Class<?> classZ, String name) { return new IocException(beanName, "Duplicate filed defined! Class=%s,FileName=%s", classZ, name); } public String toString() { return "/*AnnotationIocLoader*/\n" + Json.toJson(map); } public String[] getPackages() { return packages; } }
fix: https://github.com/nutzam/nutz/issues/1490
src/org/nutz/ioc/loader/annotation/AnnotationIocLoader.java
fix: https://github.com/nutzam/nutz/issues/1490
<ide><path>rc/org/nutz/ioc/loader/annotation/AnnotationIocLoader.java <ide> eventSet.setDepose(ib.depose().trim().intern()); <ide> if (!Strings.isBlank(ib.fetch())) <ide> eventSet.setFetch(ib.fetch().trim().intern()); <add> iobj.setSingleton(ib.singleton()); <ide> map.put(beanName, iobj); <ide> } <ide>
Java
mit
576c9d30bbfd7bcd9cf51e34df69752976a0cf15
0
alvarolobato/pipeline-maven-plugin,alvarolobato/pipeline-maven-plugin,jenkinsci/pipeline-maven-plugin,netceler/pipeline-maven-plugin,jenkinsci/pipeline-maven-plugin,alvarolobato/pipeline-maven-plugin,netceler/pipeline-maven-plugin
package org.jenkinsci.plugins.pipeline.maven.publishers; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.model.FingerprintMap; import hudson.model.Run; import hudson.model.StreamBuildListener; import hudson.model.TaskListener; import hudson.tasks.Fingerprinter; import jenkins.model.ArtifactManager; import jenkins.model.Jenkins; import jenkins.util.BuildListenerAdapter; import org.apache.commons.lang.StringUtils; import org.jenkinsci.Symbol; import org.jenkinsci.plugins.pipeline.maven.MavenPublisher; import org.jenkinsci.plugins.pipeline.maven.MavenSpyLogProcessor; import org.jenkinsci.plugins.pipeline.maven.util.XmlUtils; import org.jenkinsci.plugins.workflow.steps.StepContext; import org.kohsuke.stapler.DataBoundConstructor; import org.w3c.dom.Element; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nonnull; /** * @author <a href="mailto:[email protected]">Cyrille Le Clerc</a> */ public class GeneratedArtifactsPublisher extends MavenPublisher { private static final Logger LOGGER = Logger.getLogger(MavenSpyLogProcessor.class.getName()); private static final long serialVersionUID = 1L; @DataBoundConstructor public GeneratedArtifactsPublisher() { } @Override public void process(@Nonnull StepContext context, @Nonnull Element mavenSpyLogsElt) throws IOException, InterruptedException { Run run = context.get(Run.class); ArtifactManager artifactManager = run.pickArtifactManager(); Launcher launcher = context.get(Launcher.class); TaskListener listener = context.get(TaskListener.class); if (listener == null) { LOGGER.warning("TaskListener is NULL, default to stderr"); listener = new StreamBuildListener((OutputStream) System.err); } FilePath workspace = context.get(FilePath.class); final String fileSeparatorOnAgent = XmlUtils.getFileSeparatorOnRemote(workspace); List<MavenSpyLogProcessor.MavenArtifact> mavenArtifacts = listArtifacts(mavenSpyLogsElt); List<MavenSpyLogProcessor.MavenArtifact> attachedMavenArtifacts = listAttachedArtifacts(mavenSpyLogsElt); List<MavenSpyLogProcessor.MavenArtifact> join = new ArrayList<>(); join.addAll(mavenArtifacts); join.addAll(attachedMavenArtifacts); Map<String, String> artifactsToArchive = new HashMap<>(); // artifactPathInArchiveZone -> artifactPathInWorkspace Map<String, String> artifactsToFingerPrint = new HashMap<>(); // artifactPathInArchiveZone -> artifactMd5 for (MavenSpyLogProcessor.MavenArtifact mavenArtifact : join) { try { if (StringUtils.isEmpty(mavenArtifact.file)) { if (LOGGER.isLoggable(Level.FINER)) { listener.getLogger().println("[withMaven] Can't archive maven artifact with no file attached: " + mavenArtifact); } continue; } else if (!(mavenArtifact.file.endsWith("." + mavenArtifact.extension))) { FilePath mavenGeneratedArtifact = workspace.child(XmlUtils.getPathInWorkspace(mavenArtifact.file, workspace)); if (mavenGeneratedArtifact.isDirectory()) { if (LOGGER.isLoggable(Level.FINE)) { listener.getLogger().println("[withMaven] Skip archiving for generated maven artifact of type directory (it's likely to be target/classes, see JENKINS-43714) " + mavenArtifact); } continue; } } String artifactPathInArchiveZone = mavenArtifact.groupId.replace(".", fileSeparatorOnAgent) + fileSeparatorOnAgent + mavenArtifact.artifactId + fileSeparatorOnAgent + mavenArtifact.version + fileSeparatorOnAgent + mavenArtifact.getFileName(); String artifactPathInWorkspace = XmlUtils.getPathInWorkspace(mavenArtifact.file, workspace); if (StringUtils.isEmpty(artifactPathInWorkspace)) { listener.error("[withMaven] Invalid path in the workspace (" + workspace.getRemote() + ") for artifact " + mavenArtifact); } else if (Objects.equals(artifactPathInArchiveZone, mavenArtifact.file)) { // troubleshoot JENKINS-44088 listener.error("[withMaven] Failed to relativize '" + mavenArtifact.file + "' in workspace '" + workspace.getRemote() + "' with file separator '" + fileSeparatorOnAgent + "'"); } else { FilePath artifactFilePath = new FilePath(workspace, artifactPathInWorkspace); if (artifactFilePath.exists()) { // the subsequent call to digest could test the existence but we don't want to prematurely optimize performances listener.getLogger().println("[withMaven] Archive artifact " + artifactPathInWorkspace + " under " + artifactPathInArchiveZone); artifactsToArchive.put(artifactPathInArchiveZone, artifactPathInWorkspace); String artifactDigest = artifactFilePath.digest(); artifactsToFingerPrint.put(artifactPathInArchiveZone, artifactDigest); } else { listener.getLogger().println("[withMaven] FAILURE to archive " + artifactPathInWorkspace + " under " + artifactPathInArchiveZone + ", file not found in workspace " + workspace); } } } catch (IOException | RuntimeException e) { listener.error("[withMaven] WARNING: Exception archiving and fingerprinting " + mavenArtifact + ", skip archiving of the artifacts"); e.printStackTrace(listener.getLogger()); listener.getLogger().flush(); } } if (LOGGER.isLoggable(Level.FINE)) { listener.getLogger().println("[withMaven] Archive and fingerprint artifacts " + artifactsToArchive + " located in workspace " + workspace.getRemote()); } // ARCHIVE GENERATED MAVEN ARTIFACT // see org.jenkinsci.plugins.workflow.steps.ArtifactArchiverStepExecution#run try { artifactManager.archive(workspace, launcher, new BuildListenerAdapter(listener), artifactsToArchive); } catch (IOException e) { throw new IOException("Exception archiving " + artifactsToArchive, e); } catch (RuntimeException e) { throw new RuntimeException("Exception archiving " + artifactsToArchive, e); } // FINGERPRINT GENERATED MAVEN ARTIFACT FingerprintMap fingerprintMap = Jenkins.getInstance().getFingerprintMap(); for (Map.Entry<String, String> artifactToFingerprint : artifactsToFingerPrint.entrySet()) { String artifactPathInArchiveZone = artifactToFingerprint.getKey(); String artifactMd5 = artifactToFingerprint.getValue(); fingerprintMap.getOrCreate(run, artifactPathInArchiveZone, artifactMd5).addFor(run); } // add action Fingerprinter.FingerprintAction fingerprintAction = run.getAction(Fingerprinter.FingerprintAction.class); if (fingerprintAction == null) { run.addAction(new Fingerprinter.FingerprintAction(run, artifactsToFingerPrint)); } else { fingerprintAction.add(artifactsToFingerPrint); } } /* <ExecutionEvent type="ProjectSucceeded" class="org.apache.maven.lifecycle.internal.DefaultExecutionEvent" _time="2017-01-31 00:15:42.255"> <project artifactId="pipeline-maven" groupId="org.jenkins-ci.plugins" name="Pipeline Maven Integration Plugin" version="0.6-SNAPSHOT"/> <no-execution-found/> <artifact groupId="org.jenkins-ci.plugins" artifactId="pipeline-maven" id="org.jenkins-ci.plugins:pipeline-maven:hpi:0.6-SNAPSHOT" type="hpi" version="0.6-SNAPSHOT"> <file>/Users/cleclerc/git/jenkins/pipeline-maven-plugin/target/pipeline-maven.hpi</file> </artifact> <attachedArtifacts> <artifact groupId="org.jenkins-ci.plugins" artifactId="pipeline-maven" id="org.jenkins-ci.plugins:pipeline-maven:jar:0.6-SNAPSHOT" type="jar" version="0.6-SNAPSHOT"> <file>/Users/cleclerc/git/jenkins/pipeline-maven-plugin/target/pipeline-maven.jar</file> </artifact> </attachedArtifacts> </ExecutionEvent> */ /** * @param mavenSpyLogs Root XML element * @return list of {@link MavenSpyLogProcessor.MavenArtifact} */ /* <artifact artifactId="demo-pom" groupId="com.example" id="com.example:demo-pom:pom:0.0.1-SNAPSHOT" type="pom" version="0.0.1-SNAPSHOT"> <file/> </artifact> */ @Nonnull public List<MavenSpyLogProcessor.MavenArtifact> listArtifacts(Element mavenSpyLogs) { List<MavenSpyLogProcessor.MavenArtifact> result = new ArrayList<>(); for (Element projectSucceededElt : XmlUtils.getExecutionEvents(mavenSpyLogs, "ProjectSucceeded")) { Element projectElt = XmlUtils.getUniqueChildElement(projectSucceededElt, "project"); MavenSpyLogProcessor.MavenArtifact projectArtifact = XmlUtils.newMavenArtifact(projectElt); MavenSpyLogProcessor.MavenArtifact pomArtifact = new MavenSpyLogProcessor.MavenArtifact(); pomArtifact.groupId = projectArtifact.groupId; pomArtifact.artifactId = projectArtifact.artifactId; pomArtifact.version = projectArtifact.version; pomArtifact.type = "pom"; pomArtifact.extension = "pom"; pomArtifact.file = projectElt.getAttribute("file"); result.add(pomArtifact); Element artifactElt = XmlUtils.getUniqueChildElement(projectSucceededElt, "artifact"); MavenSpyLogProcessor.MavenArtifact mavenArtifact = XmlUtils.newMavenArtifact(artifactElt); if ("pom".equals(mavenArtifact.type)) { // NO file is generated by Maven for pom projects, skip continue; } Element fileElt = XmlUtils.getUniqueChildElementOrNull(artifactElt, "file"); if (fileElt == null || fileElt.getTextContent() == null || fileElt.getTextContent().isEmpty()) { if (LOGGER.isLoggable(Level.FINER)) { LOGGER.log(Level.FINE, "listArtifacts: Project " + projectArtifact + ": no associated file found for " + mavenArtifact + " in " + XmlUtils.toString(artifactElt)); } } else { mavenArtifact.file = StringUtils.trim(fileElt.getTextContent()); } result.add(mavenArtifact); } return result; } /** * @param mavenSpyLogs Root XML element * @return list of {@link FilePath#getRemote()} */ /* <ExecutionEvent type="ProjectSucceeded" class="org.apache.maven.lifecycle.internal.DefaultExecutionEvent" _time="2017-01-31 00:15:42.255"> <project artifactId="pipeline-maven" groupId="org.jenkins-ci.plugins" name="Pipeline Maven Integration Plugin" version="0.6-SNAPSHOT"/> <no-execution-found/> <artifact groupId="org.jenkins-ci.plugins" artifactId="pipeline-maven" id="org.jenkins-ci.plugins:pipeline-maven:hpi:0.6-SNAPSHOT" type="hpi" version="0.6-SNAPSHOT"> <file>/Users/cleclerc/git/jenkins/pipeline-maven-plugin/target/pipeline-maven.hpi</file> </artifact> <attachedArtifacts> <artifact groupId="org.jenkins-ci.plugins" artifactId="pipeline-maven" id="org.jenkins-ci.plugins:pipeline-maven:jar:0.6-SNAPSHOT" type="jar" version="0.6-SNAPSHOT"> <file>/Users/cleclerc/git/jenkins/pipeline-maven-plugin/target/pipeline-maven.jar</file> </artifact> </attachedArtifacts> </ExecutionEvent> */ @Nonnull public List<MavenSpyLogProcessor.MavenArtifact> listAttachedArtifacts(Element mavenSpyLogs) { List<MavenSpyLogProcessor.MavenArtifact> result = new ArrayList<>(); for (Element projectSucceededElt : XmlUtils.getExecutionEvents(mavenSpyLogs, "ProjectSucceeded")) { Element projectElt = XmlUtils.getUniqueChildElement(projectSucceededElt, "project"); MavenSpyLogProcessor.MavenArtifact projectArtifact = XmlUtils.newMavenArtifact(projectElt); Element attachedArtifactsParentElt = XmlUtils.getUniqueChildElement(projectSucceededElt, "attachedArtifacts"); List<Element> attachedArtifactsElts = XmlUtils.getChildrenElements(attachedArtifactsParentElt, "artifact"); for (Element attachedArtifactElt : attachedArtifactsElts) { MavenSpyLogProcessor.MavenArtifact attachedMavenArtifact = XmlUtils.newMavenArtifact(attachedArtifactElt); Element fileElt = XmlUtils.getUniqueChildElementOrNull(attachedArtifactElt, "file"); if (fileElt == null || fileElt.getTextContent() == null || fileElt.getTextContent().isEmpty()) { if (LOGGER.isLoggable(Level.FINER)) { LOGGER.log(Level.FINER, "Project " + projectArtifact + ", no associated file found for attached artifact " + attachedMavenArtifact + " in " + XmlUtils.toString(attachedArtifactElt)); } } else { attachedMavenArtifact.file = StringUtils.trim(fileElt.getTextContent()); } result.add(attachedMavenArtifact); } } return result; } @Symbol("artifactsPublisher") @Extension public static class DescriptorImpl extends MavenPublisher.DescriptorImpl { @Nonnull @Override public String getDisplayName() { return "Generated Artifacts Publisher"; } @Override public int ordinal() { return 1; } @Nonnull @Override public String getSkipFileName() { return ".skip-archive-generated-artifacts"; } } }
jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/publishers/GeneratedArtifactsPublisher.java
package org.jenkinsci.plugins.pipeline.maven.publishers; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.model.FingerprintMap; import hudson.model.Run; import hudson.model.StreamBuildListener; import hudson.model.TaskListener; import hudson.tasks.Fingerprinter; import jenkins.model.ArtifactManager; import jenkins.model.Jenkins; import jenkins.util.BuildListenerAdapter; import org.apache.commons.lang.StringUtils; import org.jenkinsci.Symbol; import org.jenkinsci.plugins.pipeline.maven.MavenPublisher; import org.jenkinsci.plugins.pipeline.maven.MavenSpyLogProcessor; import org.jenkinsci.plugins.pipeline.maven.util.XmlUtils; import org.jenkinsci.plugins.workflow.steps.StepContext; import org.kohsuke.stapler.DataBoundConstructor; import org.w3c.dom.Element; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nonnull; /** * @author <a href="mailto:[email protected]">Cyrille Le Clerc</a> */ public class GeneratedArtifactsPublisher extends MavenPublisher { private static final Logger LOGGER = Logger.getLogger(MavenSpyLogProcessor.class.getName()); private static final long serialVersionUID = 1L; @DataBoundConstructor public GeneratedArtifactsPublisher() { } @Override public void process(@Nonnull StepContext context, @Nonnull Element mavenSpyLogsElt) throws IOException, InterruptedException { Run run = context.get(Run.class); ArtifactManager artifactManager = run.pickArtifactManager(); Launcher launcher = context.get(Launcher.class); TaskListener listener = context.get(TaskListener.class); if (listener == null) { LOGGER.warning("TaskListener is NULL, default to stderr"); listener = new StreamBuildListener((OutputStream) System.err); } FilePath workspace = context.get(FilePath.class); final String fileSeparatorOnAgent = XmlUtils.getFileSeparatorOnRemote(workspace); List<MavenSpyLogProcessor.MavenArtifact> mavenArtifacts = listArtifacts(mavenSpyLogsElt); List<MavenSpyLogProcessor.MavenArtifact> attachedMavenArtifacts = listAttachedArtifacts(mavenSpyLogsElt); List<MavenSpyLogProcessor.MavenArtifact> join = new ArrayList<>(); join.addAll(mavenArtifacts); join.addAll(attachedMavenArtifacts); Map<String, String> artifactsToArchive = new HashMap<>(); // artifactPathInArchiveZone -> artifactPathInWorkspace Map<String, String> artifactsToFingerPrint = new HashMap<>(); // artifactPathInArchiveZone -> artifactMd5 for (MavenSpyLogProcessor.MavenArtifact mavenArtifact : join) { try { if (StringUtils.isEmpty(mavenArtifact.file)) { if (LOGGER.isLoggable(Level.FINER)) { listener.getLogger().println("[withMaven] Can't archive maven artifact with no file attached: " + mavenArtifact); } continue; } else if (!(mavenArtifact.file.endsWith("." + mavenArtifact.extension))) { FilePath mavenGeneratedArtifact = workspace.child(XmlUtils.getPathInWorkspace(mavenArtifact.file, workspace)); if (mavenGeneratedArtifact.isDirectory()) { if (LOGGER.isLoggable(Level.FINE)) { listener.getLogger().println("[withMaven] Skip archiving for generated maven artifact of type directory (it's likely to be target/classes, see JENKINS-43714) " + mavenArtifact); } continue; } } String artifactPathInArchiveZone = mavenArtifact.groupId.replace(".", fileSeparatorOnAgent) + fileSeparatorOnAgent + mavenArtifact.artifactId + fileSeparatorOnAgent + mavenArtifact.version + fileSeparatorOnAgent + mavenArtifact.getFileName(); String artifactPathInWorkspace = XmlUtils.getPathInWorkspace(mavenArtifact.file, workspace); if (StringUtils.isEmpty(artifactPathInWorkspace)) { listener.error("[withMaven] Invalid path in the workspace (" + workspace.getRemote() + ") for artifact " + mavenArtifact); } else if (Objects.equals(artifactPathInArchiveZone, mavenArtifact.file)) { // troubleshoot JENKINS-44088 listener.error("[withMaven] Failed to relativize '" + mavenArtifact.file + "' in workspace '" + workspace.getRemote() + "' with file separator '" + fileSeparatorOnAgent + "'"); } else { FilePath artifactFilePath = new FilePath(workspace, artifactPathInWorkspace); if (artifactFilePath.exists()) { // the subsequent call to digest could test the existence but we don't want to prematurely optimize performances listener.getLogger().println("[withMaven] Archive artifact " + artifactPathInWorkspace + " under " + artifactPathInArchiveZone); artifactsToArchive.put(artifactPathInArchiveZone, artifactPathInWorkspace); String artifactDigest = artifactFilePath.digest(); artifactsToFingerPrint.put(artifactPathInArchiveZone, artifactDigest); } else { listener.getLogger().println("[withMaven] FAILURE to archive " + artifactPathInWorkspace + " under " + artifactPathInArchiveZone + ", file not found in workspace " + workspace); } } } catch (IOException | RuntimeException e) { listener.error("[withMaven] WARNING: Exception archiving and fingerprinting " + mavenArtifact + ", skip archiving of the artifacts"); e.printStackTrace(listener.getLogger()); listener.getLogger().flush(); } } if (LOGGER.isLoggable(Level.FINE)) { listener.getLogger().println("[withMaven] Archive and fingerprint artifacts " + artifactsToArchive + " located in workspace " + workspace.getRemote()); } // ARCHIVE GENERATED MAVEN ARTIFACT // see org.jenkinsci.plugins.workflow.steps.ArtifactArchiverStepExecution#run try { artifactManager.archive(workspace, launcher, new BuildListenerAdapter(listener), artifactsToArchive); } catch (IOException e) { throw new IOException("Exception archiving " + artifactsToArchive, e); } catch (RuntimeException e) { throw new RuntimeException("Exception archiving " + artifactsToArchive, e); } // FINGERPRINT GENERATED MAVEN ARTIFACT FingerprintMap fingerprintMap = Jenkins.getInstance().getFingerprintMap(); for (Map.Entry<String, String> artifactToFingerprint : artifactsToFingerPrint.entrySet()) { String artifactPathInArchiveZone = artifactToFingerprint.getKey(); String artifactMd5 = artifactToFingerprint.getValue(); fingerprintMap.getOrCreate(run, artifactPathInArchiveZone, artifactMd5); } // add action Fingerprinter.FingerprintAction fingerprintAction = run.getAction(Fingerprinter.FingerprintAction.class); if (fingerprintAction == null) { run.addAction(new Fingerprinter.FingerprintAction(run, artifactsToFingerPrint)); } else { fingerprintAction.add(artifactsToFingerPrint); } } /* <ExecutionEvent type="ProjectSucceeded" class="org.apache.maven.lifecycle.internal.DefaultExecutionEvent" _time="2017-01-31 00:15:42.255"> <project artifactId="pipeline-maven" groupId="org.jenkins-ci.plugins" name="Pipeline Maven Integration Plugin" version="0.6-SNAPSHOT"/> <no-execution-found/> <artifact groupId="org.jenkins-ci.plugins" artifactId="pipeline-maven" id="org.jenkins-ci.plugins:pipeline-maven:hpi:0.6-SNAPSHOT" type="hpi" version="0.6-SNAPSHOT"> <file>/Users/cleclerc/git/jenkins/pipeline-maven-plugin/target/pipeline-maven.hpi</file> </artifact> <attachedArtifacts> <artifact groupId="org.jenkins-ci.plugins" artifactId="pipeline-maven" id="org.jenkins-ci.plugins:pipeline-maven:jar:0.6-SNAPSHOT" type="jar" version="0.6-SNAPSHOT"> <file>/Users/cleclerc/git/jenkins/pipeline-maven-plugin/target/pipeline-maven.jar</file> </artifact> </attachedArtifacts> </ExecutionEvent> */ /** * @param mavenSpyLogs Root XML element * @return list of {@link MavenSpyLogProcessor.MavenArtifact} */ /* <artifact artifactId="demo-pom" groupId="com.example" id="com.example:demo-pom:pom:0.0.1-SNAPSHOT" type="pom" version="0.0.1-SNAPSHOT"> <file/> </artifact> */ @Nonnull public List<MavenSpyLogProcessor.MavenArtifact> listArtifacts(Element mavenSpyLogs) { List<MavenSpyLogProcessor.MavenArtifact> result = new ArrayList<>(); for (Element projectSucceededElt : XmlUtils.getExecutionEvents(mavenSpyLogs, "ProjectSucceeded")) { Element projectElt = XmlUtils.getUniqueChildElement(projectSucceededElt, "project"); MavenSpyLogProcessor.MavenArtifact projectArtifact = XmlUtils.newMavenArtifact(projectElt); MavenSpyLogProcessor.MavenArtifact pomArtifact = new MavenSpyLogProcessor.MavenArtifact(); pomArtifact.groupId = projectArtifact.groupId; pomArtifact.artifactId = projectArtifact.artifactId; pomArtifact.version = projectArtifact.version; pomArtifact.type = "pom"; pomArtifact.extension = "pom"; pomArtifact.file = projectElt.getAttribute("file"); result.add(pomArtifact); Element artifactElt = XmlUtils.getUniqueChildElement(projectSucceededElt, "artifact"); MavenSpyLogProcessor.MavenArtifact mavenArtifact = XmlUtils.newMavenArtifact(artifactElt); if ("pom".equals(mavenArtifact.type)) { // NO file is generated by Maven for pom projects, skip continue; } Element fileElt = XmlUtils.getUniqueChildElementOrNull(artifactElt, "file"); if (fileElt == null || fileElt.getTextContent() == null || fileElt.getTextContent().isEmpty()) { if (LOGGER.isLoggable(Level.FINER)) { LOGGER.log(Level.FINE, "listArtifacts: Project " + projectArtifact + ": no associated file found for " + mavenArtifact + " in " + XmlUtils.toString(artifactElt)); } } else { mavenArtifact.file = StringUtils.trim(fileElt.getTextContent()); } result.add(mavenArtifact); } return result; } /** * @param mavenSpyLogs Root XML element * @return list of {@link FilePath#getRemote()} */ /* <ExecutionEvent type="ProjectSucceeded" class="org.apache.maven.lifecycle.internal.DefaultExecutionEvent" _time="2017-01-31 00:15:42.255"> <project artifactId="pipeline-maven" groupId="org.jenkins-ci.plugins" name="Pipeline Maven Integration Plugin" version="0.6-SNAPSHOT"/> <no-execution-found/> <artifact groupId="org.jenkins-ci.plugins" artifactId="pipeline-maven" id="org.jenkins-ci.plugins:pipeline-maven:hpi:0.6-SNAPSHOT" type="hpi" version="0.6-SNAPSHOT"> <file>/Users/cleclerc/git/jenkins/pipeline-maven-plugin/target/pipeline-maven.hpi</file> </artifact> <attachedArtifacts> <artifact groupId="org.jenkins-ci.plugins" artifactId="pipeline-maven" id="org.jenkins-ci.plugins:pipeline-maven:jar:0.6-SNAPSHOT" type="jar" version="0.6-SNAPSHOT"> <file>/Users/cleclerc/git/jenkins/pipeline-maven-plugin/target/pipeline-maven.jar</file> </artifact> </attachedArtifacts> </ExecutionEvent> */ @Nonnull public List<MavenSpyLogProcessor.MavenArtifact> listAttachedArtifacts(Element mavenSpyLogs) { List<MavenSpyLogProcessor.MavenArtifact> result = new ArrayList<>(); for (Element projectSucceededElt : XmlUtils.getExecutionEvents(mavenSpyLogs, "ProjectSucceeded")) { Element projectElt = XmlUtils.getUniqueChildElement(projectSucceededElt, "project"); MavenSpyLogProcessor.MavenArtifact projectArtifact = XmlUtils.newMavenArtifact(projectElt); Element attachedArtifactsParentElt = XmlUtils.getUniqueChildElement(projectSucceededElt, "attachedArtifacts"); List<Element> attachedArtifactsElts = XmlUtils.getChildrenElements(attachedArtifactsParentElt, "artifact"); for (Element attachedArtifactElt : attachedArtifactsElts) { MavenSpyLogProcessor.MavenArtifact attachedMavenArtifact = XmlUtils.newMavenArtifact(attachedArtifactElt); Element fileElt = XmlUtils.getUniqueChildElementOrNull(attachedArtifactElt, "file"); if (fileElt == null || fileElt.getTextContent() == null || fileElt.getTextContent().isEmpty()) { if (LOGGER.isLoggable(Level.FINER)) { LOGGER.log(Level.FINER, "Project " + projectArtifact + ", no associated file found for attached artifact " + attachedMavenArtifact + " in " + XmlUtils.toString(attachedArtifactElt)); } } else { attachedMavenArtifact.file = StringUtils.trim(fileElt.getTextContent()); } result.add(attachedMavenArtifact); } } return result; } @Symbol("artifactsPublisher") @Extension public static class DescriptorImpl extends MavenPublisher.DescriptorImpl { @Nonnull @Override public String getDisplayName() { return "Generated Artifacts Publisher"; } @Override public int ordinal() { return 1; } @Nonnull @Override public String getSkipFileName() { return ".skip-archive-generated-artifacts"; } } }
[JENKINS-44807] Don't forget to track the usage of the fingerprinted artifact.
jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/publishers/GeneratedArtifactsPublisher.java
[JENKINS-44807] Don't forget to track the usage of the fingerprinted artifact.
<ide><path>enkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/publishers/GeneratedArtifactsPublisher.java <ide> for (Map.Entry<String, String> artifactToFingerprint : artifactsToFingerPrint.entrySet()) { <ide> String artifactPathInArchiveZone = artifactToFingerprint.getKey(); <ide> String artifactMd5 = artifactToFingerprint.getValue(); <del> fingerprintMap.getOrCreate(run, artifactPathInArchiveZone, artifactMd5); <add> fingerprintMap.getOrCreate(run, artifactPathInArchiveZone, artifactMd5).addFor(run); <ide> } <ide> <ide> // add action
Java
apache-2.0
error: pathspec 'fabric/fabric-itests/fabric-pax-exam/src/test/java/org/fusesource/fabric/itests/paxexam/SelfUpdateTest.java' did not match any file(s) known to git
f6856ec4a39d81798a0d2aa6fe249e0c01c184b0
1
ffang/fuse-1,hekonsek/fabric8,chirino/fuse,PhilHardwick/fabric8,sobkowiak/fuse,dhirajsb/fuse,aslakknutsen/fabric8,janstey/fabric8,janstey/fabric8,punkhorn/fuse,KurtStam/fabric8,christian-posta/fabric8,gnodet/fuse,gashcrumb/fabric8,joelschuster/fuse,chirino/fabric8v2,rnc/fabric8,christian-posta/fabric8,mwringe/fabric8,christian-posta/fabric8,cunningt/fuse,tadayosi/fuse,PhilHardwick/fabric8,dhirajsb/fabric8,zmhassan/fabric8,janstey/fuse,gashcrumb/fabric8,rmarting/fuse,jimmidyson/fabric8,gashcrumb/fabric8,jboss-fuse/fuse,rajdavies/fabric8,chirino/fabric8,zmhassan/fabric8,jimmidyson/fabric8,avano/fabric8,PhilHardwick/fabric8,PhilHardwick/fabric8,avano/fabric8,chirino/fabric8v2,rhuss/fabric8,janstey/fabric8,jimmidyson/fabric8,hekonsek/fabric8,rnc/fabric8,sobkowiak/fabric8,ffang/fuse-1,aslakknutsen/fabric8,jludvice/fabric8,sobkowiak/fabric8,punkhorn/fabric8,hekonsek/fabric8,EricWittmann/fabric8,gashcrumb/fabric8,janstey/fuse,janstey/fuse-1,gnodet/fuse,KurtStam/fabric8,rajdavies/fabric8,chirino/fabric8v2,rnc/fabric8,rmarting/fuse,punkhorn/fabric8,jonathanchristison/fabric8,rhuss/fabric8,dhirajsb/fabric8,gnodet/fuse,rhuss/fabric8,punkhorn/fabric8,mwringe/fabric8,KurtStam/fabric8,jonathanchristison/fabric8,jboss-fuse/fuse,jimmidyson/fabric8,hekonsek/fabric8,chirino/fabric8,janstey/fuse,avano/fabric8,rnc/fabric8,dhirajsb/fuse,dhirajsb/fabric8,rajdavies/fabric8,EricWittmann/fabric8,EricWittmann/fabric8,mwringe/fabric8,opensourceconsultant/fuse,zmhassan/fabric8,joelschuster/fuse,migue/fabric8,jboss-fuse/fuse,jonathanchristison/fabric8,chirino/fuse,dejanb/fuse,opensourceconsultant/fuse,sobkowiak/fabric8,rhuss/fabric8,dejanb/fuse,chirino/fabric8,dejanb/fuse,jludvice/fabric8,sobkowiak/fabric8,janstey/fuse,jonathanchristison/fabric8,sobkowiak/fuse,jludvice/fabric8,avano/fabric8,rmarting/fuse,rajdavies/fabric8,migue/fabric8,chirino/fabric8,janstey/fuse-1,joelschuster/fuse,aslakknutsen/fabric8,migue/fabric8,dhirajsb/fabric8,janstey/fuse-1,rnc/fabric8,chirino/fabric8v2,EricWittmann/fabric8,gnodet/fuse,punkhorn/fuse,zmhassan/fabric8,migue/fabric8,tadayosi/fuse,cunningt/fuse,jludvice/fabric8,KurtStam/fabric8,hekonsek/fabric8,opensourceconsultant/fuse,punkhorn/fabric8,ffang/fuse-1,mwringe/fabric8,jimmidyson/fabric8,christian-posta/fabric8
/* * Copyright (C) FuseSource, Inc. * http://fusesource.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.fusesource.fabric.itests.paxexam; import org.fusesource.fabric.api.FabricService; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.MavenUtils; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.Configuration; import org.ops4j.pax.exam.junit.ExamReactorStrategy; import org.ops4j.pax.exam.junit.JUnit4TestRunner; import org.ops4j.pax.exam.options.DefaultCompositeOption; import org.ops4j.pax.exam.spi.reactors.AllConfinedStagedReactorFactory; import static org.openengsb.labs.paxexam.karaf.options.KarafDistributionOption.editConfigurationFileExtend; import static org.openengsb.labs.paxexam.karaf.options.KarafDistributionOption.editConfigurationFilePut; import static org.ops4j.pax.exam.CoreOptions.scanFeatures; @RunWith(JUnit4TestRunner.class) @ExamReactorStrategy(AllConfinedStagedReactorFactory.class) public class SelfUpdateTest extends FabricTestSupport { private static final String FABRIC_FEATURE_REPO_URL = "mvn:org.fusesource.fabric/fuse-fabric/%s/xml/features"; private static final String TARGET_VERSION = "7.0.0.fuse-beta-040"; @After public void tearDown() throws InterruptedException { destroyChildContainer("child1"); } @Test public void testLocalChildCreation() throws Exception { FabricService fabricService = getOsgiService(FabricService.class); System.err.println(executeCommand("fabric:create")); addStagingRepoToDefaultProfile(); createAndAssertChildContainer("child1", "root", "default"); String curretRepoURL = String.format(FABRIC_FEATURE_REPO_URL,System.getProperty("fabric.version")); String targetRepoURL = String.format(FABRIC_FEATURE_REPO_URL,TARGET_VERSION); System.out.println(executeCommand("fabric:version-create --parent 1.0 1.1")); System.out.println(executeCommand("fabric:profile-edit --delete --repositories "+curretRepoURL+" default 1.1")); System.out.println(executeCommand("fabric:profile-edit --repositories "+targetRepoURL+" default 1.1")); System.out.println(executeCommand("fabric:profile-display --version 1.1 default")); System.out.println(executeCommand("fabric:container-upgrade --all 1.1")); Thread.sleep(5000); waitForProvisionSuccess(fabricService.getContainer("child1"), PROVISION_TIMEOUT); System.out.println(executeCommand("fabric:container-list")); } @Configuration public Option[] config() { return new Option[]{ new DefaultCompositeOption(fabricDistributionConfiguration()), editConfigurationFilePut("etc/system.properties", "fabric.version", MavenUtils.getArtifactVersion("org.fusesource.fabric", "fuse-fabric")) }; } }
fabric/fabric-itests/fabric-pax-exam/src/test/java/org/fusesource/fabric/itests/paxexam/SelfUpdateTest.java
[FABRICPRV-232] Created a selfupdate test.
fabric/fabric-itests/fabric-pax-exam/src/test/java/org/fusesource/fabric/itests/paxexam/SelfUpdateTest.java
[FABRICPRV-232] Created a selfupdate test.
<ide><path>abric/fabric-itests/fabric-pax-exam/src/test/java/org/fusesource/fabric/itests/paxexam/SelfUpdateTest.java <add>/* <add> * Copyright (C) FuseSource, Inc. <add> * http://fusesource.com <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.fusesource.fabric.itests.paxexam; <add> <add>import org.fusesource.fabric.api.FabricService; <add>import org.junit.After; <add>import org.junit.Test; <add>import org.junit.runner.RunWith; <add>import org.ops4j.pax.exam.MavenUtils; <add>import org.ops4j.pax.exam.Option; <add>import org.ops4j.pax.exam.junit.Configuration; <add>import org.ops4j.pax.exam.junit.ExamReactorStrategy; <add>import org.ops4j.pax.exam.junit.JUnit4TestRunner; <add>import org.ops4j.pax.exam.options.DefaultCompositeOption; <add>import org.ops4j.pax.exam.spi.reactors.AllConfinedStagedReactorFactory; <add> <add> <add>import static org.openengsb.labs.paxexam.karaf.options.KarafDistributionOption.editConfigurationFileExtend; <add>import static org.openengsb.labs.paxexam.karaf.options.KarafDistributionOption.editConfigurationFilePut; <add>import static org.ops4j.pax.exam.CoreOptions.scanFeatures; <add> <add>@RunWith(JUnit4TestRunner.class) <add>@ExamReactorStrategy(AllConfinedStagedReactorFactory.class) <add>public class SelfUpdateTest extends FabricTestSupport { <add> <add> private static final String FABRIC_FEATURE_REPO_URL = "mvn:org.fusesource.fabric/fuse-fabric/%s/xml/features"; <add> private static final String TARGET_VERSION = "7.0.0.fuse-beta-040"; <add> <add> @After <add> public void tearDown() throws InterruptedException { <add> destroyChildContainer("child1"); <add> } <add> <add> @Test <add> public void testLocalChildCreation() throws Exception { <add> FabricService fabricService = getOsgiService(FabricService.class); <add> <add> System.err.println(executeCommand("fabric:create")); <add> addStagingRepoToDefaultProfile(); <add> createAndAssertChildContainer("child1", "root", "default"); <add> String curretRepoURL = String.format(FABRIC_FEATURE_REPO_URL,System.getProperty("fabric.version")); <add> String targetRepoURL = String.format(FABRIC_FEATURE_REPO_URL,TARGET_VERSION); <add> System.out.println(executeCommand("fabric:version-create --parent 1.0 1.1")); <add> System.out.println(executeCommand("fabric:profile-edit --delete --repositories "+curretRepoURL+" default 1.1")); <add> System.out.println(executeCommand("fabric:profile-edit --repositories "+targetRepoURL+" default 1.1")); <add> System.out.println(executeCommand("fabric:profile-display --version 1.1 default")); <add> System.out.println(executeCommand("fabric:container-upgrade --all 1.1")); <add> Thread.sleep(5000); <add> waitForProvisionSuccess(fabricService.getContainer("child1"), PROVISION_TIMEOUT); <add> System.out.println(executeCommand("fabric:container-list")); <add> } <add> <add> @Configuration <add> public Option[] config() { <add> return new Option[]{ <add> new DefaultCompositeOption(fabricDistributionConfiguration()), <add> editConfigurationFilePut("etc/system.properties", "fabric.version", MavenUtils.getArtifactVersion("org.fusesource.fabric", "fuse-fabric")) <add> }; <add> } <add>}
Java
apache-2.0
error: pathspec 'src/main/java/org/pilgrim/base/LFUCache3.java' did not match any file(s) known to git
12a3c6e19ebcc56de78e4a2ba56f210893d6c6ed
1
sergeyltd/pilgrim-base,sergeyltd/pilgrim-base
package org.pilgrim.base; import java.util.HashMap; import java.util.Map; public class LFUCache3 { public static void main(String[] args) { // TODO Auto-generated method stub LFUCache3 lfu = new LFUCache3(2); lfu.put(1, 10); lfu.put(2, 20); lfu.get(1); lfu.put(3, 30); lfu.get(2); lfu.get(3); } class Node{ Node prev; Node next; int key; int val; public String toString(){ return "[" + key + ":" + val + "]"; } } class NodeList{ Node head; Node tail; public NodeList(){ head = new Node(); tail = new Node(); head.next = tail; tail.prev = head; } public String toString(){ return "head: " + head + " tail:" + tail; } public void delete(Node item){ item.next.prev = item.prev; item.prev.next = item.next; } public void append(Node item){ item.next = head.next; item.prev = head; head.next = item; item.next.prev = item; } } class Item{ Node node; int freq; // NodeList list; public String toString(){ return "node: " + node + " freq: " + freq; } } int minFreq = 0; int capacity; Map<Integer, Item> mapNode = new HashMap<>(); Map<Integer, NodeList> mapFreq = new HashMap<>(); public LFUCache3(int capacity) { this.capacity = capacity; } public int get(int key) { Map<Integer, Item> mapNode1 = this.mapNode; Map<Integer, NodeList> mapFreq1 = this.mapFreq; Item item = mapNode.get(key); if(item == null){ return -1; } NodeList list = mapFreq.get(item.freq); list.delete(item.node); if(list.head.next == list.tail && list.head == list.tail.prev){ mapFreq.remove(item.freq); if(item.freq == this.minFreq){ this.minFreq++; } } list = mapFreq.get(++item.freq); if(list == null){ list = new NodeList(); mapFreq.put(item.freq, list); } list.append(item.node); return item.node.val; } public void put(int key, int value) { if(capacity <= 0){ return; } Map<Integer, Item> mapNode1 = this.mapNode; Map<Integer, NodeList> mapFreq1 = this.mapFreq; int minF = this.minFreq; Item item = mapNode.get(key); if(item != null){ item.node.val = value; NodeList list = mapFreq.get(item.freq); Node node = item.node; list.delete(node); list.append(node); return; } if(mapNode.size() == this.capacity){ NodeList list = mapFreq.get(this.minFreq); Node node = list.tail.prev; mapNode.remove(node.key); list.delete(node); if(list.head.next == list.tail && list.head == list.tail.prev){ mapFreq.remove(this.minFreq); } } this.minFreq = 0; Node node = new Node(); node.val = value; node.key = key; item = new Item(); item.freq = 0; item.node = node; mapNode.put(key, item); NodeList list = mapFreq.get(this.minFreq); if(list == null) { list = new NodeList(); mapFreq.put(this.minFreq, list); } list.append(node); } } /** * Your LFUCache object will be instantiated and called as such: * LFUCache obj = new LFUCache(capacity); * int param_1 = obj.get(key); * obj.put(key,value); */
src/main/java/org/pilgrim/base/LFUCache3.java
add new implementation of LFU
src/main/java/org/pilgrim/base/LFUCache3.java
add new implementation of LFU
<ide><path>rc/main/java/org/pilgrim/base/LFUCache3.java <add>package org.pilgrim.base; <add> <add>import java.util.HashMap; <add>import java.util.Map; <add> <add>public class LFUCache3 { <add> <add> public static void main(String[] args) { <add> // TODO Auto-generated method stub <add> <add> LFUCache3 lfu = new LFUCache3(2); <add> lfu.put(1, 10); <add> lfu.put(2, 20); <add> lfu.get(1); <add> lfu.put(3, 30); <add> lfu.get(2); <add> lfu.get(3); <add> } <add> <add> class Node{ <add> Node prev; <add> Node next; <add> int key; <add> int val; <add> <add> public String toString(){ <add> return "[" + key + ":" + val + "]"; <add> } <add> } <add> <add> class NodeList{ <add> Node head; <add> Node tail; <add> <add> public NodeList(){ <add> head = new Node(); <add> tail = new Node(); <add> head.next = tail; <add> tail.prev = head; <add> } <add> <add> public String toString(){ <add> return "head: " + head + " tail:" + tail; <add> } <add> <add> public void delete(Node item){ <add> item.next.prev = item.prev; <add> item.prev.next = item.next; <add> } <add> <add> public void append(Node item){ <add> item.next = head.next; <add> item.prev = head; <add> head.next = item; <add> item.next.prev = item; <add> } <add> } <add> <add> class Item{ <add> Node node; <add> int freq; <add> // NodeList list; <add> <add> public String toString(){ <add> return "node: " + node + " freq: " + freq; <add> } <add> } <add> <add> int minFreq = 0; <add> int capacity; <add> Map<Integer, Item> mapNode = new HashMap<>(); <add> Map<Integer, NodeList> mapFreq = new HashMap<>(); <add> <add> public LFUCache3(int capacity) { <add> this.capacity = capacity; <add> } <add> <add> public int get(int key) { <add> Map<Integer, Item> mapNode1 = this.mapNode; <add> Map<Integer, NodeList> mapFreq1 = this.mapFreq; <add> <add> Item item = mapNode.get(key); <add> if(item == null){ <add> return -1; <add> } <add> <add> NodeList list = mapFreq.get(item.freq); <add> list.delete(item.node); <add> <add> if(list.head.next == list.tail && list.head == list.tail.prev){ <add> mapFreq.remove(item.freq); <add> <add> if(item.freq == this.minFreq){ <add> this.minFreq++; <add> } <add> } <add> <add> list = mapFreq.get(++item.freq); <add> if(list == null){ <add> list = new NodeList(); <add> mapFreq.put(item.freq, list); <add> } <add> list.append(item.node); <add> <add> return item.node.val; <add> } <add> <add> public void put(int key, int value) { <add> <add> if(capacity <= 0){ <add> return; <add> } <add> <add> Map<Integer, Item> mapNode1 = this.mapNode; <add> Map<Integer, NodeList> mapFreq1 = this.mapFreq; <add> int minF = this.minFreq; <add> <add> Item item = mapNode.get(key); <add> if(item != null){ <add> item.node.val = value; <add> NodeList list = mapFreq.get(item.freq); <add> Node node = item.node; <add> list.delete(node); <add> list.append(node); <add> return; <add> } <add> <add> if(mapNode.size() == this.capacity){ <add> NodeList list = mapFreq.get(this.minFreq); <add> Node node = list.tail.prev; <add> mapNode.remove(node.key); <add> list.delete(node); <add> <add> if(list.head.next == list.tail && list.head == list.tail.prev){ <add> mapFreq.remove(this.minFreq); <add> } <add> } <add> <add> this.minFreq = 0; <add> Node node = new Node(); <add> node.val = value; <add> node.key = key; <add> <add> item = new Item(); <add> item.freq = 0; <add> item.node = node; <add> <add> mapNode.put(key, item); <add> <add> NodeList list = mapFreq.get(this.minFreq); <add> if(list == null) { <add> list = new NodeList(); <add> mapFreq.put(this.minFreq, list); <add> } <add> <add> list.append(node); <add> } <add>} <add> <add> <add>/** <add> * Your LFUCache object will be instantiated and called as such: <add> * LFUCache obj = new LFUCache(capacity); <add> * int param_1 = obj.get(key); <add> * obj.put(key,value); <add> */
Java
apache-2.0
4f6d30e663614d07f5f57983a1a5cc7ad812826a
0
sangramjadhav/testrs
2154f844-2ece-11e5-905b-74de2bd44bed
hello.java
21546596-2ece-11e5-905b-74de2bd44bed
2154f844-2ece-11e5-905b-74de2bd44bed
hello.java
2154f844-2ece-11e5-905b-74de2bd44bed
<ide><path>ello.java <del>21546596-2ece-11e5-905b-74de2bd44bed <add>2154f844-2ece-11e5-905b-74de2bd44bed
Java
lgpl-2.1
fd7270458fb5b78c4c1f45492e57087329e7e38b
0
xwiki/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.extension.xar.internal.handler.packager; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Provider; import javax.inject.Singleton; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream; import org.apache.commons.io.input.CloseShieldInputStream; import org.slf4j.Logger; import org.xml.sax.ContentHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xwiki.component.annotation.Component; import org.xwiki.component.manager.ComponentLookupException; import org.xwiki.component.manager.ComponentManager; import org.xwiki.component.phase.Initializable; import org.xwiki.component.phase.InitializationException; import org.xwiki.extension.xar.internal.handler.packager.xml.DocumentImporterHandler; import org.xwiki.extension.xar.internal.handler.packager.xml.RootHandler; import org.xwiki.extension.xar.internal.handler.packager.xml.UnknownRootElement; import org.xwiki.extension.xar.internal.handler.packager.xml.XarPageLimitedHandler; import org.xwiki.model.reference.DocumentReference; import org.xwiki.model.reference.DocumentReferenceResolver; import org.xwiki.model.reference.EntityReference; import org.xwiki.model.reference.WikiReference; import org.xwiki.observation.ObservationManager; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.doc.XWikiDocument; import com.xpn.xwiki.internal.event.XARImportedEvent; import com.xpn.xwiki.internal.event.XARImportingEvent; /** * Default implementation of {@link Packager}. * * @version $Id$ * @since 4.0M1 */ @Component @Singleton public class DefaultPackager implements Packager, Initializable { @Inject private ComponentManager componentManager; @Inject @Named("explicit") private DocumentReferenceResolver<EntityReference> resolver; /** * The logger to log. */ @Inject private Logger logger; @Inject private ObservationManager observation; @Inject private Provider<XWikiContext> xcontextProvider; private SAXParserFactory parserFactory; @Override public void initialize() throws InitializationException { this.parserFactory = SAXParserFactory.newInstance(); } @Override public void importXAR(XarFile previousXarFile, File xarFile, PackageConfiguration configuration) throws IOException, XWikiException, ComponentLookupException { if (configuration.getWiki() == null) { XWikiContext xcontext = this.xcontextProvider.get(); if (xcontext.getWiki().isVirtualMode()) { List<String> wikis = xcontext.getWiki().getVirtualWikisDatabaseNames(xcontext); if (!wikis.contains(xcontext.getMainXWiki())) { importXARToWiki(previousXarFile, xarFile, xcontext.getMainXWiki(), configuration); } for (String subwiki : wikis) { importXARToWiki(previousXarFile, xarFile, subwiki, configuration); } } else { importXARToWiki(previousXarFile, xarFile, xcontext.getMainXWiki(), configuration); } } else { importXARToWiki(previousXarFile, xarFile, configuration.getWiki(), configuration); } } private XarMergeResult importXARToWiki(XarFile previousXarFile, File xarFile, String wiki, PackageConfiguration configuration) throws IOException, ComponentLookupException { FileInputStream fis = new FileInputStream(xarFile); try { return importXARToWiki(previousXarFile, fis, wiki, configuration); } finally { fis.close(); } } private XarMergeResult importXARToWiki(XarFile previousXarFile, InputStream xarInputStream, String wiki, PackageConfiguration configuration) throws IOException, ComponentLookupException { XarMergeResult mergeResult = new XarMergeResult(); ZipArchiveInputStream zis = new ZipArchiveInputStream(xarInputStream); XWikiContext xcontext = this.xcontextProvider.get(); String currentWiki = xcontext.getDatabase(); try { xcontext.setDatabase(wiki); this.observation.notify(new XARImportingEvent(), null, xcontext); for (ArchiveEntry entry = zis.getNextEntry(); entry != null; entry = zis.getNextEntry()) { if (!entry.isDirectory()) { DocumentImporterHandler documentHandler = new DocumentImporterHandler(this, this.componentManager, wiki); try { documentHandler.setPreviousXarFile(previousXarFile); documentHandler.setConfiguration(configuration); parseDocument(zis, documentHandler); if (documentHandler.getMergeResult() != null) { mergeResult.addMergeResult(documentHandler.getMergeResult()); } if (configuration.isLogEnabled()) { this.logger.info("Successfully imported document [{}] in language [{}]", documentHandler .getDocument().getDocumentReference(), documentHandler.getDocument().getRealLanguage()); } } catch (NotADocumentException e) { // Impossible to know that before parsing this.logger.debug("Entry [" + entry + "] is not a document", e); } catch (Exception e) { this.logger.error("Failed to parse document [" + entry.getName() + "]", e); if (configuration.isLogEnabled()) { this.logger.info("Failed to import document [{}] in language [{}]", documentHandler .getDocument().getDocumentReference(), documentHandler.getDocument().getRealLanguage()); } } } } } finally { this.observation.notify(new XARImportedEvent(), null, xcontext); xcontext.setDatabase(currentWiki); } return mergeResult; } @Override public void unimportXAR(File xarFile, PackageConfiguration configuration) throws IOException, XWikiException { if (configuration.getWiki() == null) { XWikiContext xcontext = this.xcontextProvider.get(); if (xcontext.getWiki().isVirtualMode()) { List<String> wikis = xcontext.getWiki().getVirtualWikisDatabaseNames(xcontext); if (!wikis.contains(xcontext.getMainXWiki())) { unimportXARFromWiki(xarFile, xcontext.getMainXWiki(), configuration); } for (String subwiki : wikis) { unimportXARFromWiki(xarFile, subwiki, configuration); } } else { unimportXARFromWiki(xarFile, xcontext.getMainXWiki(), configuration); } } else { unimportXARFromWiki(xarFile, configuration.getWiki(), configuration); } } private void unimportXARFromWiki(File xarFile, String wiki, PackageConfiguration configuration) throws IOException { unimportPagesFromWiki(getEntries(xarFile), wiki, configuration); } @Override public void unimportPages(Collection<XarEntry> pages, PackageConfiguration configuration) throws XWikiException { if (configuration.getWiki() == null) { XWikiContext xcontext = this.xcontextProvider.get(); if (xcontext.getWiki().isVirtualMode()) { List<String> wikis = xcontext.getWiki().getVirtualWikisDatabaseNames(xcontext); if (!wikis.contains(xcontext.getMainXWiki())) { unimportPagesFromWiki(pages, xcontext.getMainXWiki(), configuration); } for (String subwiki : wikis) { unimportPagesFromWiki(pages, subwiki, configuration); } } else { unimportPagesFromWiki(pages, xcontext.getMainXWiki(), configuration); } } else { unimportPagesFromWiki(pages, configuration.getWiki(), configuration); } } private void unimportPagesFromWiki(Collection<XarEntry> pages, String wiki, PackageConfiguration configuration) { WikiReference wikiReference = new WikiReference(wiki); XWikiContext xcontext = this.xcontextProvider.get(); for (XarEntry xarEntry : pages) { DocumentReference documentReference = this.resolver.resolve(xarEntry.getDocumentReference(), wikiReference); try { XWikiDocument document = xcontext.getWiki().getDocument(documentReference, xcontext); if (!document.isNew()) { String language = xarEntry.getLanguage(); if (language != null) { document = document.getTranslatedDocument(language, xcontext); xcontext.getWiki().deleteDocument(document, xcontext); this.logger.info("Successfully deleted document [{}] in language [{}]", document.getDocumentReference(), document.getRealLanguage()); } else { xcontext.getWiki().deleteAllDocuments(document, xcontext); this.logger.info("Successfully deleted document [{}]", document.getDocumentReference()); } } } catch (XWikiException e) { this.logger.error("Failed to delete document [{}]", documentReference, e); } } } @Override public List<XarEntry> getEntries(File xarFile) throws IOException { List<XarEntry> documents = null; FileInputStream fis = new FileInputStream(xarFile); ZipArchiveInputStream zis = new ZipArchiveInputStream(fis); try { for (ZipArchiveEntry zipEntry = zis.getNextZipEntry(); zipEntry != null; zipEntry = zis.getNextZipEntry()) { if (!zipEntry.isDirectory()) { try { XarPageLimitedHandler documentHandler = new XarPageLimitedHandler(this.componentManager); parseDocument(zis, documentHandler); if (documents == null) { documents = new ArrayList<XarEntry>(); } XarEntry xarEntry = documentHandler.getXarEntry(); xarEntry.setEntryName(zipEntry.getName()); documents.add(xarEntry); } catch (NotADocumentException e) { // Impossible to know that before parsing } catch (Exception e) { this.logger.error("Failed to parse document [" + zipEntry.getName() + "]", e); } } } } finally { zis.close(); } return documents != null ? documents : Collections.<XarEntry> emptyList(); } public void parseDocument(InputStream in, ContentHandler documentHandler) throws ParserConfigurationException, SAXException, IOException, NotADocumentException { SAXParser saxParser = this.parserFactory.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); RootHandler handler = new RootHandler(this.componentManager); handler.setHandler("xwikidoc", documentHandler); xmlReader.setContentHandler(handler); try { xmlReader.parse(new InputSource(new CloseShieldInputStream(in))); } catch (UnknownRootElement e) { throw new NotADocumentException("Failed to parse stream", e); } } }
xwiki-platform-core/xwiki-platform-extension/xwiki-platform-extension-handlers/xwiki-platform-extension-handler-xar/src/main/java/org/xwiki/extension/xar/internal/handler/packager/DefaultPackager.java
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.extension.xar.internal.handler.packager; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Provider; import javax.inject.Singleton; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream; import org.apache.commons.io.input.CloseShieldInputStream; import org.slf4j.Logger; import org.xml.sax.ContentHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xwiki.component.annotation.Component; import org.xwiki.component.manager.ComponentLookupException; import org.xwiki.component.manager.ComponentManager; import org.xwiki.component.phase.Initializable; import org.xwiki.component.phase.InitializationException; import org.xwiki.extension.xar.internal.handler.packager.xml.DocumentImporterHandler; import org.xwiki.extension.xar.internal.handler.packager.xml.RootHandler; import org.xwiki.extension.xar.internal.handler.packager.xml.UnknownRootElement; import org.xwiki.extension.xar.internal.handler.packager.xml.XarPageLimitedHandler; import org.xwiki.model.reference.DocumentReference; import org.xwiki.model.reference.DocumentReferenceResolver; import org.xwiki.model.reference.EntityReference; import org.xwiki.model.reference.WikiReference; import org.xwiki.observation.ObservationManager; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.doc.XWikiDocument; import com.xpn.xwiki.internal.event.XARImportedEvent; import com.xpn.xwiki.internal.event.XARImportingEvent; /** * Default implementation of {@link Packager}. * * @version $Id$ * @since 4.0M1 */ @Component @Singleton public class DefaultPackager implements Packager, Initializable { @Inject private ComponentManager componentManager; @Inject @Named("explicit") private DocumentReferenceResolver<EntityReference> resolver; /** * The logger to log. */ @Inject private Logger logger; @Inject private ObservationManager observation; @Inject private Provider<XWikiContext> xcontextProvider; private SAXParserFactory parserFactory; @Override public void initialize() throws InitializationException { this.parserFactory = SAXParserFactory.newInstance(); } @Override public void importXAR(XarFile previousXarFile, File xarFile, PackageConfiguration configuration) throws IOException, XWikiException, ComponentLookupException { if (configuration.getWiki() == null) { XWikiContext xcontext = this.xcontextProvider.get(); if (xcontext.getWiki().isVirtualMode()) { List<String> wikis = xcontext.getWiki().getVirtualWikisDatabaseNames(xcontext); if (!wikis.contains(xcontext.getMainXWiki())) { importXARToWiki(previousXarFile, xarFile, xcontext.getMainXWiki(), configuration); } for (String subwiki : wikis) { importXARToWiki(previousXarFile, xarFile, subwiki, configuration); } } else { importXARToWiki(previousXarFile, xarFile, xcontext.getMainXWiki(), configuration); } } else { importXARToWiki(previousXarFile, xarFile, configuration.getWiki(), configuration); } } private XarMergeResult importXARToWiki(XarFile previousXarFile, File xarFile, String wiki, PackageConfiguration configuration) throws IOException, ComponentLookupException { FileInputStream fis = new FileInputStream(xarFile); try { return importXARToWiki(previousXarFile, fis, wiki, configuration); } finally { fis.close(); } } private XarMergeResult importXARToWiki(XarFile previousXarFile, InputStream xarInputStream, String wiki, PackageConfiguration configuration) throws IOException, ComponentLookupException { XarMergeResult mergeResult = new XarMergeResult(); ZipArchiveInputStream zis = new ZipArchiveInputStream(xarInputStream); XWikiContext xcontext = this.xcontextProvider.get(); String currentWiki = xcontext.getDatabase(); try { xcontext.setDatabase(wiki); this.observation.notify(new XARImportingEvent(), null, xcontext); for (ArchiveEntry entry = zis.getNextEntry(); entry != null; entry = zis.getNextEntry()) { if (!entry.isDirectory()) { DocumentImporterHandler documentHandler = new DocumentImporterHandler(this, this.componentManager, wiki); try { documentHandler.setPreviousXarFile(previousXarFile); documentHandler.setConfiguration(configuration); parseDocument(zis, documentHandler); if (documentHandler.getMergeResult() != null) { mergeResult.addMergeResult(documentHandler.getMergeResult()); } if (configuration.isLogEnabled()) { this.logger.info("Successfully imported document [{}] in language [{}]", documentHandler .getDocument().getDocumentReference(), documentHandler.getDocument().getRealLanguage()); } } catch (NotADocumentException e) { // Impossible to know that before parsing this.logger.debug("Entry [" + entry + "] is not a document", e); } catch (Exception e) { this.logger.error("Failed to parse document [" + entry.getName() + "]", e); if (configuration.isLogEnabled()) { this.logger.info("Failed to import document [{}] in language [{}]", documentHandler .getDocument().getDocumentReference(), documentHandler.getDocument().getRealLanguage()); } } } } } finally { this.observation.notify(new XARImportedEvent(), null, xcontext); xcontext.setDatabase(currentWiki); } return mergeResult; } @Override public void unimportXAR(File xarFile, PackageConfiguration configuration) throws IOException, XWikiException { if (configuration.getWiki() == null) { XWikiContext xcontext = this.xcontextProvider.get(); if (xcontext.getWiki().isVirtualMode()) { List<String> wikis = xcontext.getWiki().getVirtualWikisDatabaseNames(xcontext); if (!wikis.contains(xcontext.getMainXWiki())) { unimportXARFromWiki(xarFile, xcontext.getMainXWiki(), configuration); } for (String subwiki : wikis) { unimportXARFromWiki(xarFile, subwiki, configuration); } } else { unimportXARFromWiki(xarFile, xcontext.getMainXWiki(), configuration); } } else { unimportXARFromWiki(xarFile, configuration.getWiki(), configuration); } } private void unimportXARFromWiki(File xarFile, String wiki, PackageConfiguration configuration) throws IOException { unimportPagesFromWiki(getEntries(xarFile), wiki, configuration); } @Override public void unimportPages(Collection<XarEntry> pages, PackageConfiguration configuration) throws XWikiException { if (configuration.getWiki() == null) { XWikiContext xcontext = this.xcontextProvider.get(); if (xcontext.getWiki().isVirtualMode()) { List<String> wikis = xcontext.getWiki().getVirtualWikisDatabaseNames(xcontext); if (!wikis.contains(xcontext.getMainXWiki())) { unimportPagesFromWiki(pages, xcontext.getMainXWiki(), configuration); } for (String subwiki : wikis) { unimportPagesFromWiki(pages, subwiki, configuration); } } else { unimportPagesFromWiki(pages, xcontext.getMainXWiki(), configuration); } } else { unimportPagesFromWiki(pages, configuration.getWiki(), configuration); } } private void unimportPagesFromWiki(Collection<XarEntry> pages, String wiki, PackageConfiguration configuration) { WikiReference wikiReference = new WikiReference(wiki); XWikiContext xcontext = this.xcontextProvider.get(); for (XarEntry xarEntry : pages) { DocumentReference documentReference = this.resolver.resolve(xarEntry.getDocumentReference(), wikiReference); try { XWikiDocument document = xcontext.getWiki().getDocument(documentReference, xcontext); if (!document.isNew()) { String language = xarEntry.getLanguage(); if (language != null) { document = document.getTranslatedDocument(language, xcontext); xcontext.getWiki().deleteDocument(document, xcontext); } else { xcontext.getWiki().deleteAllDocuments(document, xcontext); } } } catch (XWikiException e) { this.logger.error("Failed to delete document [" + documentReference + "]", e); } } } @Override public List<XarEntry> getEntries(File xarFile) throws IOException { List<XarEntry> documents = null; FileInputStream fis = new FileInputStream(xarFile); ZipArchiveInputStream zis = new ZipArchiveInputStream(fis); try { for (ZipArchiveEntry zipEntry = zis.getNextZipEntry(); zipEntry != null; zipEntry = zis.getNextZipEntry()) { if (!zipEntry.isDirectory()) { try { XarPageLimitedHandler documentHandler = new XarPageLimitedHandler(this.componentManager); parseDocument(zis, documentHandler); if (documents == null) { documents = new ArrayList<XarEntry>(); } XarEntry xarEntry = documentHandler.getXarEntry(); xarEntry.setEntryName(zipEntry.getName()); documents.add(xarEntry); } catch (NotADocumentException e) { // Impossible to know that before parsing } catch (Exception e) { this.logger.error("Failed to parse document [" + zipEntry.getName() + "]", e); } } } } finally { zis.close(); } return documents != null ? documents : Collections.<XarEntry> emptyList(); } public void parseDocument(InputStream in, ContentHandler documentHandler) throws ParserConfigurationException, SAXException, IOException, NotADocumentException { SAXParser saxParser = this.parserFactory.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); RootHandler handler = new RootHandler(this.componentManager); handler.setHandler("xwikidoc", documentHandler); xmlReader.setContentHandler(handler); try { xmlReader.parse(new InputSource(new CloseShieldInputStream(in))); } catch (UnknownRootElement e) { throw new NotADocumentException("Failed to parse stream", e); } } }
Add log
xwiki-platform-core/xwiki-platform-extension/xwiki-platform-extension-handlers/xwiki-platform-extension-handler-xar/src/main/java/org/xwiki/extension/xar/internal/handler/packager/DefaultPackager.java
Add log
<ide><path>wiki-platform-core/xwiki-platform-extension/xwiki-platform-extension-handlers/xwiki-platform-extension-handler-xar/src/main/java/org/xwiki/extension/xar/internal/handler/packager/DefaultPackager.java <ide> if (language != null) { <ide> document = document.getTranslatedDocument(language, xcontext); <ide> xcontext.getWiki().deleteDocument(document, xcontext); <add> <add> this.logger.info("Successfully deleted document [{}] in language [{}]", <add> document.getDocumentReference(), document.getRealLanguage()); <ide> } else { <ide> xcontext.getWiki().deleteAllDocuments(document, xcontext); <add> <add> this.logger.info("Successfully deleted document [{}]", document.getDocumentReference()); <ide> } <ide> } <ide> } catch (XWikiException e) { <del> this.logger.error("Failed to delete document [" + documentReference + "]", e); <add> this.logger.error("Failed to delete document [{}]", documentReference, e); <ide> } <ide> } <ide> }
Java
apache-2.0
f009a8b714ab10640cf42ef9908882be7e148230
0
kantenkugel/KanzeBot
/* * Copyright 2016 Michael Ritter (Kantenkugel) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.kantenkugel.discordbot.moduleutils; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.http.exceptions.UnirestException; import net.dv8tion.jda.utils.SimpleLog; import org.apache.commons.lang3.StringUtils; import org.json.JSONArray; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.*; import java.util.jar.JarFile; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; public class DocParser { private static final SimpleLog LOG = SimpleLog.getLog("DocParser"); private static final String JENKINS_PREFIX = "http://ci.dv8tion.net/job/JDA/lastSuccessfulBuild/"; private static final String ARTIFACT_SUFFIX = "api/json?tree=artifacts[*]"; private static final Path LOCAL_SRC_PATH = Paths.get("src.jar"); private static final String JDA_CODE_BASE = "net/dv8tion/jda"; private static final Pattern DOCS_PATTERN = Pattern.compile("/\\*{2}\\s*\n(.*?)\n\\s*\\*/\\s*\n\\s*(?:@[^\n]+\n\\s*)*(.*?)\n", Pattern.DOTALL); private static final Pattern METHOD_PATTERN = Pattern.compile(".*?\\s([a-zA-Z][a-zA-Z0-9]*)\\(([a-zA-Z0-9\\s,]*)\\)"); private static final Pattern METHOD_ARG_PATTERN = Pattern.compile("([a-zA-Z][a-zA-Z0-9]*)\\s+[a-zA-Z][a-zA-Z0-9]"); private static final Map<String, List<Documentation>> docs = new HashMap<>(); public static void init() { if(!docs.isEmpty()) return; LOG.info("Initializing JDA-Docs"); download(); parse(); LOG.info("JDA-Docs initialized"); } public static String get(String name) { String[] split = name.toLowerCase().split("[#\\.]", 2); if(split.length != 2) return "Incorrect Method declaration"; if(!docs.containsKey(split[0])) return "Class not Found!"; List<Documentation> methods = docs.get(split[0]); methods = methods.parallelStream().filter(doc -> doc.matches(split[1])).sorted(Comparator.comparingInt(doc -> doc.argTypes.size())).collect(Collectors.toList()); if(methods.size() == 0) return "Method not found/documented in Class!"; if(methods.size() > 1 && methods.get(0).argTypes.size() != 0) return "Multiple methods found: " + methods.parallelStream().map(m -> '(' + StringUtils.join(m.argTypes, ", ") + ')').collect(Collectors.joining(", ")); Documentation doc = methods.get(0); StringBuilder b = new StringBuilder(); b.append("```\n").append(doc.functionHead).append("\n```\n").append(doc.desc); if(doc.args.size() > 0) { b.append('\n').append('\n').append("**Arguments:**"); doc.args.entrySet().stream().map(e -> "**" + e.getKey() + "** - " + e.getValue()).forEach(a -> b.append('\n').append(a)); } if(doc.returns != null) b.append('\n').append('\n').append("**Returns:**\n").append(doc.returns); if(doc.throwing.size() > 0) { b.append('\n').append('\n').append("**Throws:**"); doc.throwing.entrySet().stream().map(e -> "**" + e.getKey() + "** - " + e.getValue()).forEach(a -> b.append('\n').append(a)); } return b.toString(); } private static void download() { LOG.info("Downloading source-file"); try { HttpResponse<String> response = Unirest.get(JENKINS_PREFIX + ARTIFACT_SUFFIX).asString(); if(response.getStatus() < 300 && response.getStatus() > 199) { JSONArray artifacts = new JSONObject(response.getBody()).getJSONArray("artifacts"); for(int i = 0; i < artifacts.length(); i++) { JSONObject artifact = artifacts.getJSONObject(i); if(artifact.getString("fileName").endsWith("sources.jar")) { URL artifactUrl = new URL(JENKINS_PREFIX + "artifact/" + artifact.getString("relativePath")); InputStream is = artifactUrl.openStream(); Files.copy(is, LOCAL_SRC_PATH, StandardCopyOption.REPLACE_EXISTING); is.close(); LOG.info("Done downloading source-file"); } } } } catch(UnirestException | IOException e) { LOG.log(e); } } private static void parse() { LOG.info("Parsing source-file"); try { JarFile file = new JarFile(LOCAL_SRC_PATH.toFile()); file.stream() .filter(entry -> !entry.isDirectory() && entry.getName().startsWith(JDA_CODE_BASE) && entry.getName().endsWith(".java")) .forEach(entry -> { try { parse(entry.getName(), file.getInputStream(entry)); } catch(IOException e) { e.printStackTrace(); } }); LOG.info("Done parsing source-file"); } catch(IOException e) { LOG.log(e); } } private static void parse(String name, InputStream inputStream) { String[] nameSplits = name.split("[/\\.]"); String className = nameSplits[nameSplits.length - 2]; docs.putIfAbsent(className.toLowerCase(), new ArrayList<>()); List<Documentation> docs = DocParser.docs.get(className.toLowerCase()); try (BufferedReader buffer = new BufferedReader(new InputStreamReader(inputStream))) { String content = buffer.lines().collect(Collectors.joining("\n")); Matcher matcher = DOCS_PATTERN.matcher(content); while(matcher.find()) { String method = matcher.group(2).trim(); if(method.contains("class ") || method.contains("interface ")) { continue; } if(method.endsWith("{")) method = method.substring(0, method.length() - 1).trim(); Matcher m2 = METHOD_PATTERN.matcher(method); if(!m2.find()) continue; String methodName = m2.group(1); List<String> argTypes = new ArrayList<>(); m2 = METHOD_ARG_PATTERN.matcher(m2.group(2)); while(m2.find()) argTypes.add(m2.group(1)); List<String> docText = cleanupDocs(matcher.group(1)); String returns = null; Map<String, String> args = new HashMap<>(); Map<String, String> throwing = new HashMap<>(); String desc = null; for(String line : docText) { if(!line.isEmpty() && line.charAt(0) == '@') { if(line.startsWith("@return ")) returns = line.substring(8); else if(line.startsWith("@param ")) { String[] split = line.split("\\s+", 3); args.put(split[1], split.length == 3 ? split[2] : "*No Description*"); } else if(line.startsWith("@throws ")) { String[] split = line.split("\\s+", 3); throwing.put(split[1], split.length == 3 ? split[2] : "*No Description*"); } } else { desc = desc == null ? line : desc + '\n' + line; } } docs.add(new Documentation(methodName, argTypes, method, desc, returns, args, throwing)); } } catch(IOException ignored) {} try { inputStream.close(); } catch(IOException e) { LOG.log(e); } } private static List<String> cleanupDocs(String docs) { docs = docs.replace("\n", " "); docs = docs.replaceAll("(?:\\s+\\*)+\\s+", " ").replaceAll("\\s{2,}", " "); docs = docs.replaceAll("</?b>", "**").replaceAll("</?i>", "*").replaceAll("<br/?>", "\n").replaceAll("<[^>]+>", ""); docs = docs.replaceAll("[^{]@", "\n@"); docs = docs.replaceAll("\\{@link[^}]*[ \\.](.*?)\\}", "***$1***"); return Arrays.stream(docs.split("\n")).map(String::trim).collect(Collectors.toList()); } private static class Documentation { private final String functionName; private final List<String> argTypes; private final String functionHead; private final String desc; private final String returns; private final Map<String, String> args; private final Map<String, String> throwing; private Documentation(String functionName, List<String> argTypes, String functionHead, String desc, String returns, Map<String, String> args, Map<String, String> throwing) { this.functionName = functionName; this.argTypes = argTypes; this.functionHead = functionHead; this.desc = desc; this.returns = returns; this.args = args; this.throwing = throwing; } private boolean matches(String input) { if(input.charAt(input.length()-1) != ')') input += "()"; Matcher matcher = METHOD_PATTERN.matcher(' ' + input); if(!matcher.find()) return false; if(!matcher.group(1).equalsIgnoreCase(functionName)) return false; String args = matcher.group(2); if(args.isEmpty()) return true; String[] split = args.split(","); if(split.length != argTypes.size()) return true; for(int i = 0; i < split.length; i++) { if(!split[i].trim().equalsIgnoreCase(argTypes.get(i))) return false; } return true; } } }
src/com/kantenkugel/discordbot/moduleutils/DocParser.java
/* * Copyright 2016 Michael Ritter (Kantenkugel) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.kantenkugel.discordbot.moduleutils; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.http.exceptions.UnirestException; import net.dv8tion.jda.utils.SimpleLog; import org.json.JSONArray; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.jar.JarFile; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; public class DocParser { private static final SimpleLog LOG = SimpleLog.getLog("DocParser"); private static final String JENKINS_PREFIX = "http://ci.dv8tion.net/job/JDA/lastSuccessfulBuild/"; private static final String ARTIFACT_SUFFIX = "api/json?tree=artifacts[*]"; private static final Path LOCAL_SRC_PATH = Paths.get("src.jar"); private static final String JDA_CODE_BASE = "net/dv8tion/jda"; private static final Pattern DOCS_PATTERN = Pattern.compile("/\\*{2}\\s*\n(.*?)\n\\s*\\*/\\s*\n\\s*(?:@[^\n]+\n\\s*)*(.*?)\n", Pattern.DOTALL); private static final Pattern METHOD_NAME_PATTERN = Pattern.compile(".*?\\s(\\S+)\\("); private static final Map<String, Map<String, Documentation>> docs = new HashMap<>(); public static void init() { LOG.info("Initializing JDA-Docs"); if(!docs.isEmpty()) return; download(); parse(); } public static String get(String name) { String[] split = name.toLowerCase().split("[#\\.]", 2); if(split.length != 2) return "Incorrect Method declaration"; if(!docs.containsKey(split[0])) return "Class not Found!"; Map<String, Documentation> methods = docs.get(split[0]); if(!methods.containsKey(split[1])) return "Method not found/documented in Class!"; Documentation doc = methods.get(split[1]); StringBuilder b = new StringBuilder(); b.append("```\n").append(doc.functionHead).append("\n```\n").append(doc.desc); if(doc.args.size() > 0) { b.append('\n').append('\n').append("**Arguments:**"); doc.args.entrySet().stream().map(e -> "**" + e.getKey() + "** - " + e.getValue()).forEach(a -> b.append('\n').append(a)); } if(doc.returns != null) b.append('\n').append('\n').append("**Returns:**\n").append(doc.returns); if(doc.throwing.size() > 0) { b.append('\n').append('\n').append("**Throws:**"); doc.throwing.entrySet().stream().map(e -> "**" + e.getKey() + "** - " + e.getValue()).forEach(a -> b.append('\n').append(a)); } return b.toString(); } private static void download() { LOG.info("Downloading source-file"); try { HttpResponse<String> response = Unirest.get(JENKINS_PREFIX + ARTIFACT_SUFFIX).asString(); if(response.getStatus() < 300 && response.getStatus() > 199) { JSONArray artifacts = new JSONObject(response.getBody()).getJSONArray("artifacts"); for(int i = 0; i < artifacts.length(); i++) { JSONObject artifact = artifacts.getJSONObject(i); if(artifact.getString("fileName").endsWith("sources.jar")) { URL artifactUrl = new URL(JENKINS_PREFIX + "artifact/" + artifact.getString("relativePath")); InputStream is = artifactUrl.openStream(); Files.copy(is, LOCAL_SRC_PATH, StandardCopyOption.REPLACE_EXISTING); is.close(); LOG.info("Done downloading source-file"); } } } } catch(UnirestException | IOException e) { LOG.log(e); } } private static void parse() { LOG.info("Parsing source-file"); try { JarFile file = new JarFile(LOCAL_SRC_PATH.toFile()); file.stream() .filter(entry -> !entry.isDirectory() && entry.getName().startsWith(JDA_CODE_BASE) && entry.getName().endsWith(".java")) .forEach(entry -> { try { parse(entry.getName(), file.getInputStream(entry)); } catch(IOException e) { e.printStackTrace(); } }); LOG.info("Done parsing source-file"); } catch(IOException e) { LOG.log(e); } } private static void parse(String name, InputStream inputStream) { String[] nameSplits = name.split("[/\\.]"); String className = nameSplits[nameSplits.length - 2]; docs.putIfAbsent(className.toLowerCase(), new HashMap<>()); Map<String, Documentation> docs = DocParser.docs.get(className.toLowerCase()); try (BufferedReader buffer = new BufferedReader(new InputStreamReader(inputStream))) { String content = buffer.lines().collect(Collectors.joining("\n")); Matcher matcher = DOCS_PATTERN.matcher(content); while(matcher.find()) { String method = matcher.group(2).trim(); if(method.contains("class ") || method.contains("interface ")) { continue; } if(method.endsWith("{")) method = method.substring(0, method.length() - 1).trim(); Matcher m2 = METHOD_NAME_PATTERN.matcher(method); if(!m2.find()) continue; String methodName = m2.group(1); List<String> docText = cleanupDocs(matcher.group(1)); String returns = null; Map<String, String> args = new HashMap<>(); Map<String, String> throwing = new HashMap<>(); String desc = null; for(String line : docText) { if(!line.isEmpty() && line.charAt(0) == '@') { if(line.startsWith("@return ")) returns = line.substring(8); else if(line.startsWith("@param ")) { String[] split = line.split("\\s+", 3); args.put(split[1], split.length == 3 ? split[2] : "*No Description*"); } else if(line.startsWith("@throws ")) { String[] split = line.split("\\s+", 3); throwing.put(split[1], split.length == 3 ? split[2] : "*No Description*"); } } else { desc = desc == null ? line : desc + '\n' + line; } } docs.put(methodName.toLowerCase(), new Documentation(method, desc, returns, args, throwing)); } } catch(IOException ignored) {} try { inputStream.close(); } catch(IOException e) { LOG.log(e); } } private static List<String> cleanupDocs(String docs) { docs = docs.replace("\n", " "); docs = docs.replaceAll("(?:\\s+\\*)+\\s+", " ").replaceAll("\\s{2,}", " "); docs = docs.replaceAll("</?b>", "**").replaceAll("</?i>", "*").replaceAll("<br/?>", "\n").replaceAll("<[^>]+>", ""); docs = docs.replaceAll("[^{]@", "\n@"); docs = docs.replaceAll("\\{@link [^}]*[ \\.](.*?)\\}", "***$1***"); return Arrays.stream(docs.split("\n")).map(String::trim).collect(Collectors.toList()); } private static class Documentation { private final String functionHead; private final String desc; private final String returns; private final Map<String, String> args; private final Map<String, String> throwing; public Documentation(String functionHead, String desc, String returns, Map<String, String> args, Map<String, String> throwing) { this.functionHead = functionHead; this.desc = desc; this.returns = returns; this.args = args; this.throwing = throwing; } } }
Allowed the jda-doc command to be able to differentiate between multiple methods with same name (just accept the ultra ugly code)
src/com/kantenkugel/discordbot/moduleutils/DocParser.java
Allowed the jda-doc command to be able to differentiate between multiple methods with same name (just accept the ultra ugly code)
<ide><path>rc/com/kantenkugel/discordbot/moduleutils/DocParser.java <ide> import com.mashape.unirest.http.Unirest; <ide> import com.mashape.unirest.http.exceptions.UnirestException; <ide> import net.dv8tion.jda.utils.SimpleLog; <add>import org.apache.commons.lang3.StringUtils; <ide> import org.json.JSONArray; <ide> import org.json.JSONObject; <ide> <ide> import java.nio.file.Path; <ide> import java.nio.file.Paths; <ide> import java.nio.file.StandardCopyOption; <del>import java.util.Arrays; <del>import java.util.HashMap; <del>import java.util.List; <del>import java.util.Map; <add>import java.util.*; <ide> import java.util.jar.JarFile; <ide> import java.util.regex.Matcher; <ide> import java.util.regex.Pattern; <ide> private static final String JDA_CODE_BASE = "net/dv8tion/jda"; <ide> <ide> private static final Pattern DOCS_PATTERN = Pattern.compile("/\\*{2}\\s*\n(.*?)\n\\s*\\*/\\s*\n\\s*(?:@[^\n]+\n\\s*)*(.*?)\n", Pattern.DOTALL); <del> private static final Pattern METHOD_NAME_PATTERN = Pattern.compile(".*?\\s(\\S+)\\("); <del> <del> private static final Map<String, Map<String, Documentation>> docs = new HashMap<>(); <add> private static final Pattern METHOD_PATTERN = Pattern.compile(".*?\\s([a-zA-Z][a-zA-Z0-9]*)\\(([a-zA-Z0-9\\s,]*)\\)"); <add> private static final Pattern METHOD_ARG_PATTERN = Pattern.compile("([a-zA-Z][a-zA-Z0-9]*)\\s+[a-zA-Z][a-zA-Z0-9]"); <add> <add> private static final Map<String, List<Documentation>> docs = new HashMap<>(); <ide> <ide> <ide> public static void init() { <del> LOG.info("Initializing JDA-Docs"); <ide> if(!docs.isEmpty()) <ide> return; <add> LOG.info("Initializing JDA-Docs"); <ide> download(); <ide> parse(); <add> LOG.info("JDA-Docs initialized"); <ide> } <ide> <ide> public static String get(String name) { <ide> return "Incorrect Method declaration"; <ide> if(!docs.containsKey(split[0])) <ide> return "Class not Found!"; <del> Map<String, Documentation> methods = docs.get(split[0]); <del> if(!methods.containsKey(split[1])) <add> List<Documentation> methods = docs.get(split[0]); <add> methods = methods.parallelStream().filter(doc -> doc.matches(split[1])).sorted(Comparator.comparingInt(doc -> doc.argTypes.size())).collect(Collectors.toList()); <add> if(methods.size() == 0) <ide> return "Method not found/documented in Class!"; <del> Documentation doc = methods.get(split[1]); <add> if(methods.size() > 1 && methods.get(0).argTypes.size() != 0) <add> return "Multiple methods found: " + methods.parallelStream().map(m -> '(' + StringUtils.join(m.argTypes, ", ") + ')').collect(Collectors.joining(", ")); <add> Documentation doc = methods.get(0); <ide> StringBuilder b = new StringBuilder(); <ide> b.append("```\n").append(doc.functionHead).append("\n```\n").append(doc.desc); <ide> if(doc.args.size() > 0) { <ide> private static void parse(String name, InputStream inputStream) { <ide> String[] nameSplits = name.split("[/\\.]"); <ide> String className = nameSplits[nameSplits.length - 2]; <del> docs.putIfAbsent(className.toLowerCase(), new HashMap<>()); <del> Map<String, Documentation> docs = DocParser.docs.get(className.toLowerCase()); <add> docs.putIfAbsent(className.toLowerCase(), new ArrayList<>()); <add> List<Documentation> docs = DocParser.docs.get(className.toLowerCase()); <ide> try (BufferedReader buffer = new BufferedReader(new InputStreamReader(inputStream))) { <ide> String content = buffer.lines().collect(Collectors.joining("\n")); <ide> Matcher matcher = DOCS_PATTERN.matcher(content); <ide> } <ide> if(method.endsWith("{")) <ide> method = method.substring(0, method.length() - 1).trim(); <del> Matcher m2 = METHOD_NAME_PATTERN.matcher(method); <add> Matcher m2 = METHOD_PATTERN.matcher(method); <ide> if(!m2.find()) <ide> continue; <ide> String methodName = m2.group(1); <add> List<String> argTypes = new ArrayList<>(); <add> m2 = METHOD_ARG_PATTERN.matcher(m2.group(2)); <add> while(m2.find()) <add> argTypes.add(m2.group(1)); <ide> List<String> docText = cleanupDocs(matcher.group(1)); <ide> String returns = null; <ide> <ide> desc = desc == null ? line : desc + '\n' + line; <ide> } <ide> } <del> docs.put(methodName.toLowerCase(), new Documentation(method, desc, returns, args, throwing)); <add> docs.add(new Documentation(methodName, argTypes, method, desc, returns, args, throwing)); <ide> } <ide> } catch(IOException ignored) {} <ide> try { <ide> docs = docs.replaceAll("(?:\\s+\\*)+\\s+", " ").replaceAll("\\s{2,}", " "); <ide> docs = docs.replaceAll("</?b>", "**").replaceAll("</?i>", "*").replaceAll("<br/?>", "\n").replaceAll("<[^>]+>", ""); <ide> docs = docs.replaceAll("[^{]@", "\n@"); <del> docs = docs.replaceAll("\\{@link [^}]*[ \\.](.*?)\\}", "***$1***"); <add> docs = docs.replaceAll("\\{@link[^}]*[ \\.](.*?)\\}", "***$1***"); <ide> return Arrays.stream(docs.split("\n")).map(String::trim).collect(Collectors.toList()); <ide> } <ide> <ide> private static class Documentation { <add> private final String functionName; <add> private final List<String> argTypes; <ide> private final String functionHead; <ide> private final String desc; <ide> private final String returns; <ide> private final Map<String, String> args; <ide> private final Map<String, String> throwing; <ide> <del> public Documentation(String functionHead, String desc, String returns, Map<String, String> args, Map<String, String> throwing) { <add> private Documentation(String functionName, List<String> argTypes, String functionHead, String desc, String returns, Map<String, String> args, Map<String, String> throwing) { <add> this.functionName = functionName; <add> this.argTypes = argTypes; <ide> this.functionHead = functionHead; <ide> this.desc = desc; <ide> this.returns = returns; <ide> this.args = args; <ide> this.throwing = throwing; <ide> } <add> <add> private boolean matches(String input) { <add> if(input.charAt(input.length()-1) != ')') <add> input += "()"; <add> Matcher matcher = METHOD_PATTERN.matcher(' ' + input); <add> if(!matcher.find()) <add> return false; <add> if(!matcher.group(1).equalsIgnoreCase(functionName)) <add> return false; <add> String args = matcher.group(2); <add> if(args.isEmpty()) <add> return true; <add> String[] split = args.split(","); <add> if(split.length != argTypes.size()) <add> return true; <add> for(int i = 0; i < split.length; i++) { <add> if(!split[i].trim().equalsIgnoreCase(argTypes.get(i))) <add> return false; <add> } <add> return true; <add> } <ide> } <ide> }
Java
apache-2.0
17c7ec6515b84c48341c45c146c55f1beed524e9
0
arijitt/incubator-ignite,avinogradovgg/ignite,ashutakGG/incubator-ignite,endian675/ignite,murador/ignite,sk0x50/ignite,ascherbakoff/ignite,ryanzz/ignite,dlnufox/ignite,tkpanther/ignite,nizhikov/ignite,andrey-kuznetsov/ignite,pperalta/ignite,vadopolski/ignite,thuTom/ignite,NSAmelchev/ignite,pperalta/ignite,xtern/ignite,mcherkasov/ignite,agura/incubator-ignite,apache/ignite,rfqu/ignite,WilliamDo/ignite,vladisav/ignite,ilantukh/ignite,tkpanther/ignite,murador/ignite,nivanov/ignite,amirakhmedov/ignite,leveyj/ignite,dream-x/ignite,agoncharuk/ignite,SharplEr/ignite,pperalta/ignite,alexzaitzev/ignite,ptupitsyn/ignite,SomeFire/ignite,chandresh-pancholi/ignite,avinogradovgg/ignite,nizhikov/ignite,apacheignite/ignite,akuznetsov-gridgain/ignite,kromulan/ignite,svladykin/ignite,ilantukh/ignite,vsisko/incubator-ignite,thuTom/ignite,NSAmelchev/ignite,psadusumilli/ignite,samaitra/ignite,NSAmelchev/ignite,thuTom/ignite,vldpyatkov/ignite,ntikhonov/ignite,ascherbakoff/ignite,a1vanov/ignite,vsisko/incubator-ignite,avinogradovgg/ignite,nizhikov/ignite,voipp/ignite,chandresh-pancholi/ignite,alexzaitzev/ignite,vsuslov/incubator-ignite,tkpanther/ignite,vsuslov/incubator-ignite,ilantukh/ignite,pperalta/ignite,nizhikov/ignite,shurun19851206/ignite,nizhikov/ignite,thuTom/ignite,VladimirErshov/ignite,endian675/ignite,apache/ignite,zzcclp/ignite,psadusumilli/ignite,daradurvs/ignite,ilantukh/ignite,chandresh-pancholi/ignite,sk0x50/ignite,avinogradovgg/ignite,andrey-kuznetsov/ignite,SomeFire/ignite,SharplEr/ignite,vldpyatkov/ignite,arijitt/incubator-ignite,NSAmelchev/ignite,vldpyatkov/ignite,vsisko/incubator-ignite,apache/ignite,apacheignite/ignite,kromulan/ignite,WilliamDo/ignite,amirakhmedov/ignite,shurun19851206/ignite,wmz7year/ignite,dmagda/incubator-ignite,ptupitsyn/ignite,rfqu/ignite,samaitra/ignite,pperalta/ignite,nivanov/ignite,DoudTechData/ignite,dlnufox/ignite,tkpanther/ignite,gridgain/apache-ignite,daradurvs/ignite,amirakhmedov/ignite,dream-x/ignite,vsisko/incubator-ignite,ashutakGG/incubator-ignite,gargvish/ignite,ryanzz/ignite,adeelmahmood/ignite,SomeFire/ignite,ptupitsyn/ignite,kidaa/incubator-ignite,amirakhmedov/ignite,xtern/ignite,endian675/ignite,ryanzz/ignite,shroman/ignite,BiryukovVA/ignite,irudyak/ignite,sylentprayer/ignite,ilantukh/ignite,apacheignite/ignite,kromulan/ignite,apache/ignite,vadopolski/ignite,iveselovskiy/ignite,BiryukovVA/ignite,louishust/incubator-ignite,andrey-kuznetsov/ignite,rfqu/ignite,dream-x/ignite,sk0x50/ignite,f7753/ignite,kromulan/ignite,tkpanther/ignite,f7753/ignite,StalkXT/ignite,adeelmahmood/ignite,svladykin/ignite,wmz7year/ignite,f7753/ignite,dlnufox/ignite,ntikhonov/ignite,ryanzz/ignite,StalkXT/ignite,dmagda/incubator-ignite,nivanov/ignite,vldpyatkov/ignite,kromulan/ignite,abhishek-ch/incubator-ignite,shurun19851206/ignite,mcherkasov/ignite,endian675/ignite,WilliamDo/ignite,thuTom/ignite,afinka77/ignite,leveyj/ignite,irudyak/ignite,amirakhmedov/ignite,ascherbakoff/ignite,agoncharuk/ignite,agoncharuk/ignite,VladimirErshov/ignite,gargvish/ignite,apache/ignite,SomeFire/ignite,tkpanther/ignite,gridgain/apache-ignite,vsuslov/incubator-ignite,vsuslov/incubator-ignite,gridgain/apache-ignite,DoudTechData/ignite,shurun19851206/ignite,BiryukovVA/ignite,sk0x50/ignite,abhishek-ch/incubator-ignite,BiryukovVA/ignite,shurun19851206/ignite,sk0x50/ignite,shroman/ignite,vadopolski/ignite,sylentprayer/ignite,thuTom/ignite,pperalta/ignite,psadusumilli/ignite,dream-x/ignite,daradurvs/ignite,BiryukovVA/ignite,f7753/ignite,wmz7year/ignite,ashutakGG/incubator-ignite,vsuslov/incubator-ignite,WilliamDo/ignite,voipp/ignite,kromulan/ignite,VladimirErshov/ignite,gridgain/apache-ignite,murador/ignite,pperalta/ignite,dmagda/incubator-ignite,xtern/ignite,svladykin/ignite,xtern/ignite,agoncharuk/ignite,chandresh-pancholi/ignite,apacheignite/ignite,rfqu/ignite,StalkXT/ignite,ashutakGG/incubator-ignite,irudyak/ignite,SharplEr/ignite,apache/ignite,VladimirErshov/ignite,mcherkasov/ignite,irudyak/ignite,alexzaitzev/ignite,leveyj/ignite,samaitra/ignite,WilliamDo/ignite,andrey-kuznetsov/ignite,daradurvs/ignite,afinka77/ignite,f7753/ignite,alexzaitzev/ignite,WilliamDo/ignite,adeelmahmood/ignite,StalkXT/ignite,zzcclp/ignite,daradurvs/ignite,ilantukh/ignite,ryanzz/ignite,dream-x/ignite,DoudTechData/ignite,ascherbakoff/ignite,BiryukovVA/ignite,dream-x/ignite,ascherbakoff/ignite,chandresh-pancholi/ignite,psadusumilli/ignite,shroman/ignite,BiryukovVA/ignite,sk0x50/ignite,VladimirErshov/ignite,BiryukovVA/ignite,vsisko/incubator-ignite,adeelmahmood/ignite,SomeFire/ignite,shroman/ignite,dmagda/incubator-ignite,xtern/ignite,SharplEr/ignite,alexzaitzev/ignite,ptupitsyn/ignite,agura/incubator-ignite,dream-x/ignite,a1vanov/ignite,adeelmahmood/ignite,louishust/incubator-ignite,xtern/ignite,apache/ignite,a1vanov/ignite,ptupitsyn/ignite,dlnufox/ignite,alexzaitzev/ignite,shroman/ignite,apacheignite/ignite,wmz7year/ignite,kidaa/incubator-ignite,ntikhonov/ignite,louishust/incubator-ignite,rfqu/ignite,gargvish/ignite,nizhikov/ignite,leveyj/ignite,irudyak/ignite,voipp/ignite,daradurvs/ignite,samaitra/ignite,vsisko/incubator-ignite,tkpanther/ignite,adeelmahmood/ignite,sk0x50/ignite,andrey-kuznetsov/ignite,apacheignite/ignite,vladisav/ignite,iveselovskiy/ignite,zzcclp/ignite,nivanov/ignite,andrey-kuznetsov/ignite,NSAmelchev/ignite,ascherbakoff/ignite,zzcclp/ignite,apache/ignite,afinka77/ignite,andrey-kuznetsov/ignite,xtern/ignite,andrey-kuznetsov/ignite,ascherbakoff/ignite,arijitt/incubator-ignite,irudyak/ignite,nivanov/ignite,andrey-kuznetsov/ignite,amirakhmedov/ignite,ilantukh/ignite,vladisav/ignite,irudyak/ignite,agoncharuk/ignite,rfqu/ignite,nizhikov/ignite,ntikhonov/ignite,kromulan/ignite,chandresh-pancholi/ignite,nivanov/ignite,ntikhonov/ignite,kidaa/incubator-ignite,amirakhmedov/ignite,apacheignite/ignite,vadopolski/ignite,NSAmelchev/ignite,sylentprayer/ignite,daradurvs/ignite,psadusumilli/ignite,WilliamDo/ignite,ntikhonov/ignite,shurun19851206/ignite,SomeFire/ignite,vladisav/ignite,ashutakGG/incubator-ignite,afinka77/ignite,samaitra/ignite,daradurvs/ignite,SomeFire/ignite,agura/incubator-ignite,xtern/ignite,daradurvs/ignite,iveselovskiy/ignite,zzcclp/ignite,DoudTechData/ignite,apacheignite/ignite,vadopolski/ignite,sk0x50/ignite,wmz7year/ignite,iveselovskiy/ignite,gridgain/apache-ignite,gargvish/ignite,DoudTechData/ignite,zzcclp/ignite,nizhikov/ignite,SharplEr/ignite,mcherkasov/ignite,SomeFire/ignite,VladimirErshov/ignite,afinka77/ignite,samaitra/ignite,NSAmelchev/ignite,alexzaitzev/ignite,SharplEr/ignite,abhishek-ch/incubator-ignite,a1vanov/ignite,agura/incubator-ignite,shroman/ignite,dmagda/incubator-ignite,voipp/ignite,endian675/ignite,daradurvs/ignite,louishust/incubator-ignite,vadopolski/ignite,ntikhonov/ignite,agoncharuk/ignite,endian675/ignite,gargvish/ignite,voipp/ignite,adeelmahmood/ignite,chandresh-pancholi/ignite,SharplEr/ignite,vadopolski/ignite,vladisav/ignite,NSAmelchev/ignite,wmz7year/ignite,vladisav/ignite,BiryukovVA/ignite,xtern/ignite,akuznetsov-gridgain/ignite,tkpanther/ignite,a1vanov/ignite,sk0x50/ignite,thuTom/ignite,ryanzz/ignite,vldpyatkov/ignite,zzcclp/ignite,shroman/ignite,abhishek-ch/incubator-ignite,voipp/ignite,murador/ignite,avinogradovgg/ignite,a1vanov/ignite,vldpyatkov/ignite,dream-x/ignite,ilantukh/ignite,voipp/ignite,chandresh-pancholi/ignite,endian675/ignite,ptupitsyn/ignite,VladimirErshov/ignite,agoncharuk/ignite,psadusumilli/ignite,pperalta/ignite,StalkXT/ignite,dlnufox/ignite,StalkXT/ignite,leveyj/ignite,agura/incubator-ignite,dmagda/incubator-ignite,dmagda/incubator-ignite,vsisko/incubator-ignite,afinka77/ignite,leveyj/ignite,sylentprayer/ignite,endian675/ignite,chandresh-pancholi/ignite,gargvish/ignite,DoudTechData/ignite,SharplEr/ignite,afinka77/ignite,a1vanov/ignite,vadopolski/ignite,gargvish/ignite,vsuslov/incubator-ignite,kidaa/incubator-ignite,ilantukh/ignite,arijitt/incubator-ignite,ashutakGG/incubator-ignite,irudyak/ignite,ptupitsyn/ignite,vldpyatkov/ignite,zzcclp/ignite,sylentprayer/ignite,andrey-kuznetsov/ignite,dlnufox/ignite,vsisko/incubator-ignite,amirakhmedov/ignite,ascherbakoff/ignite,arijitt/incubator-ignite,ascherbakoff/ignite,agoncharuk/ignite,arijitt/incubator-ignite,gridgain/apache-ignite,StalkXT/ignite,akuznetsov-gridgain/ignite,shurun19851206/ignite,wmz7year/ignite,psadusumilli/ignite,f7753/ignite,vldpyatkov/ignite,mcherkasov/ignite,kidaa/incubator-ignite,shroman/ignite,afinka77/ignite,kromulan/ignite,svladykin/ignite,leveyj/ignite,dlnufox/ignite,gargvish/ignite,alexzaitzev/ignite,shurun19851206/ignite,dlnufox/ignite,ptupitsyn/ignite,akuznetsov-gridgain/ignite,rfqu/ignite,avinogradovgg/ignite,psadusumilli/ignite,ptupitsyn/ignite,sylentprayer/ignite,sylentprayer/ignite,SomeFire/ignite,DoudTechData/ignite,svladykin/ignite,SharplEr/ignite,ilantukh/ignite,f7753/ignite,WilliamDo/ignite,vladisav/ignite,sylentprayer/ignite,murador/ignite,avinogradovgg/ignite,samaitra/ignite,agura/incubator-ignite,gridgain/apache-ignite,ryanzz/ignite,thuTom/ignite,samaitra/ignite,kidaa/incubator-ignite,dmagda/incubator-ignite,SomeFire/ignite,svladykin/ignite,wmz7year/ignite,a1vanov/ignite,voipp/ignite,louishust/incubator-ignite,samaitra/ignite,agura/incubator-ignite,abhishek-ch/incubator-ignite,akuznetsov-gridgain/ignite,svladykin/ignite,adeelmahmood/ignite,alexzaitzev/ignite,mcherkasov/ignite,nivanov/ignite,voipp/ignite,mcherkasov/ignite,StalkXT/ignite,f7753/ignite,shroman/ignite,ntikhonov/ignite,rfqu/ignite,nivanov/ignite,shroman/ignite,leveyj/ignite,ptupitsyn/ignite,abhishek-ch/incubator-ignite,amirakhmedov/ignite,iveselovskiy/ignite,StalkXT/ignite,irudyak/ignite,murador/ignite,NSAmelchev/ignite,ryanzz/ignite,apache/ignite,vladisav/ignite,VladimirErshov/ignite,iveselovskiy/ignite,murador/ignite,murador/ignite,DoudTechData/ignite,akuznetsov-gridgain/ignite,nizhikov/ignite,BiryukovVA/ignite,louishust/incubator-ignite,agura/incubator-ignite,samaitra/ignite,mcherkasov/ignite
/* @java.file.header */ /* _________ _____ __________________ _____ * __ ____/___________(_)______ /__ ____/______ ____(_)_______ * _ / __ __ ___/__ / _ __ / _ / __ _ __ `/__ / __ __ \ * / /_/ / _ / _ / / /_/ / / /_/ / / /_/ / _ / _ / / / * \____/ /_/ /_/ \_,__/ \____/ \__,_/ /_/ /_/ /_/ */ package org.gridgain.examples; /** * GridRouterExample multi-node self test. */ public class GridRouterExamplesMultiNodeSelfTest extends GridRouterExamplesSelfTest { /** {@inheritDoc} */ @Override protected void beforeTest() throws Exception { startRemoteNodes(); // Start up a router. startRouter("modules/clients/src/main/java/config/router/default-router.xml"); } }
examples/src/test/java/org/gridgain/examples/GridRouterExamplesMultiNodeSelfTest.java
/* @java.file.header */ /* _________ _____ __________________ _____ * __ ____/___________(_)______ /__ ____/______ ____(_)_______ * _ / __ __ ___/__ / _ __ / _ / __ _ __ `/__ / __ __ \ * / /_/ / _ / _ / / /_/ / / /_/ / / /_/ / _ / _ / / / * \____/ /_/ /_/ \_,__/ \____/ \__,_/ /_/ /_/ /_/ */ package org.gridgain.examples; /** * GridRouterExample multi-node self test. */ public class GridRouterExamplesMultiNodeSelfTest extends GridRouterExamplesSelfTest { /** {@inheritDoc} */ @Override protected void beforeTest() throws Exception { startRemoteNodes(); // Start up a router. startRouter("modules/clients/java/config/router/default-router.xml"); } }
# GG-7725 - Fixing tests
examples/src/test/java/org/gridgain/examples/GridRouterExamplesMultiNodeSelfTest.java
# GG-7725 - Fixing tests
<ide><path>xamples/src/test/java/org/gridgain/examples/GridRouterExamplesMultiNodeSelfTest.java <ide> @Override protected void beforeTest() throws Exception { <ide> startRemoteNodes(); <ide> // Start up a router. <del> startRouter("modules/clients/java/config/router/default-router.xml"); <add> startRouter("modules/clients/src/main/java/config/router/default-router.xml"); <ide> } <ide> }
JavaScript
mit
20c9ebcf9b7445f7c3cd178bef598a82eeeb1901
0
cguard90/phase-0,cguard90/phase-0,cguard90/phase-0
// Design Basic Game Solo Challenge // This is a solo challenge // Your mission description: choice game, follow guide, choose which treasure // Overall mission: player makes choice on guide, guide leads to different treasures, treasure leads to different outcome // Goals: guide gives you an item to help (you choose the item), item will be effective / ineffective against the 'boss'. // Characters: Player, guide, 'boss' // Objects: Player, Boss (guide is a thing for reference only, will actually be doing very little actively. ) // Functions: function... make choice on item, will update character property 'item'. use item on 'boss', which will either work / fail to incapacitate the boss. // Pseudocode // start by having a conversation with a dialogue, because who doesn't love dialogue. The guide mentions a treasure, tells you that he found it but it was guarded and he was unable to complete the quest. intrigued, you ask him to show you. He says you'll need an item to help you. choose 1 of 3 items... let's do gun, net, pixie dust (and update the character object accordingly). // next he successfully guides you to the room outside of the treasure, and says that this was as far as he made it. he offers a word of warning that he doesn't know what will await you inside. You can either choose to go in or not (if not, maybe you fight the guide). // if fight, go in room and use item on boss, item will update 'boss' status depending on item. // once 'boss' is defeated, move on to treasure choice // have treasure choice update boss status as well (depending on status) // Initial Code var player = { name: "", item: "", hp: 2, } var boss = { name: "Murphy", status: "asleep", hp: 4, } var intro = function() { console.log("I used to be an adventurer like you... until I took an arrow to the knee.") console.log("You look to your right and see a weatherworn old fellow, who certainly looks like he could be telling the truth.") console.log("'Where did your adventures take you?' you ask, out of curiousity.") console.log("'To a place lost in the jungle with a magical treasure, I could show you where it is, but I can't help you retrieve it.'") console.log("'sure' you reply. What else are you going to do on your Tuesday morning?") var name = prompt("'What is your name?' the old man asks.") player.name = name var item = prompt("'Nice to meet you' they say. 'Before we go, you will need an item to help you on this quest. I have 3, any of which can help you secure the treasure. You can choose between a net, a gun, and pixie dust.'") player.item = item if (player.item == 'gun') { console.log("'Let's be on our way then' he says.") middle() } else if (player.item == 'net') { middle() } else if (player.item == 'pixie dust') { console.log(player.item) } else { console.log("You are too drunk to adventure") } } var middle = function() { console.log("'This is where I must stop' the guide says, outside of an unremarkable hut made of stone in the woods.") console.log("'It may not look like much, but there is a terrible monster inside. If you succeed in getting past it you'll find an irreplaceable treasure.'") var choice = prompt("Are you ready to go in?") if (choice = 'yes') { console.log("good luck!"); conflict(player.item) } else { console.log("The guide knocks you out and throws you inside, secretly hoping you'll succeed. So much for choice, right?"); player.hp -= 1 conflict(player.item) } } var conflict = function(player_item) { if (player_item == 'gun') { } else { console.log("You wonder how you made it this far, as you are itemless facing a monster. An Arrow hits you in the knee, and you flee in terror. 60 years later, you find yourself in a Tuesday next to a stranger compelled to tell them your story.") } } intro() // Refactored Code // Reflection // // // // // // // //
week-7/game.js
// Design Basic Game Solo Challenge // This is a solo challenge // Your mission description: choice game, follow guide, choose which treasure // Overall mission: player makes choice on guide, guide leads to different treasures, treasure leads to different outcome // Goals: guide gives you an item to help (you choose the item), item will be effective / ineffective against the 'boss'. // Characters: Player, guide, 'boss' // Objects: Player, Boss (guide is a thing for reference only, will actually be doing very little actively. ) // Functions: function... make choice on item, will update character property 'item'. use item on 'boss', which will either work / fail to incapacitate the boss. // Pseudocode // start by having a conversation with a dialogue, because who doesn't love dialogue. The guide mentions a treasure, tells you that he found it but it was guarded and he was unable to complete the quest. intrigued, you ask him to show you. He says you'll need an item to help you. choose 1 of 3 items... let's do gun, net, pixie dust (and update the character object accordingly). // next he successfully guides you to the room outside of the treasure, and says that this was as far as he made it. he offers a word of warning that he doesn't know what will await you inside. You can either choose to go in or not (if not, maybe you fight the guide). // if fight, go in room and use item on boss, item will update 'boss' status depending on item. // once 'boss' is defeated, move on to treasure choice // have treasure choice update boss status as well (depending on status) // Initial Code var player = { name: "", item: "", hp: 2, } var boss = { name: "Murphy", status: "asleep", hp: 4, } var intro = function() { console.log("I used to be an adventurer like you... until I took an arrow to the knee.") console.log("You look to your right and see a weatherworn old fellow, who certainly looks like he could be telling the truth.") console.log("'Where did your adventures take you?' you ask, out of curiousity.") console.log("'To a place lost in the jungle with a magical treasure, I could show you where it is, but I can't help you retrieve it.'") console.log("'sure' you reply. What else are you going to do on your Tuesday morning?") var name = prompt("'What is your name?' the old man asks.") player.name = name var item = prompt("'Nice to meet you' they say. 'Before we go, you will need an item to help you on this quest. I have 3, any of which can help you secure the treasure. You can choose between a net, a gun, and pixie dust.'") player.item = item if (player.item == 'gun') { console.log("'Let's be on our way then' he says.") middle() } else if (player.item == 'net') { middle() } else if (player.item == 'pixie dust') { console.log(player.item) } else { console.log("You are too drunk to adventure") } } var middle = function() { console.log("'This is where I must stop' the guide says, outside of an unremarkable hut made of stone in the woods.") console.log("'It may not look like much, but there is a terrible monster inside. If you succeed in getting past it you'll find an irreplaceable treasure.'") var choice = prompt("Are you ready to go in?") if (choice = 'yes') { console.log("good luck!"); conclusion(player.item) } else { console.log("The guide knocks you out and throws you inside, secretly hoping you'll succeed. So much for choice, right?"); player.hp -= 1 conclusion(player.item) } } var conclusion = function(player_item) { if (player_item == 'gun') { var shoot = prompt("You are in the room with the treasure, and you see the monster. It's current status is" + boss.status + ". Do you shoot? (yes or no)") if (shoot = 'yes') { boss.hp -= 2 boss.status == "enraged" var shoot2 = prompt("The monster is wounded, but wakes up enraged. It charges at you, do you shoot again?") if (shoot2 == 'yes') { boss.hp -= 2 boss.status == "defeated" console.log("You have defeated the monster, you now get to claim your treasure") } else { console.log("The monster attacks you to defend itself. You suffer many injuries and escape, just to have the guide shoot you in the knee with an arrow. You live the rest of your life wondering what treasure was there.") } } else { console.log("You wonder how you made it this far, as you are itemless facing a monster. An Arrow hits you in the knee, and you flee in terror. 60 years later, you find yourself in a Tuesday next to a stranger compelled to tell them your story.") } } intro() // Refactored Code // Reflection // // // // // // // //
Update method function name
week-7/game.js
Update method function name
<ide><path>eek-7/game.js <ide> var choice = prompt("Are you ready to go in?") <ide> if (choice = 'yes') { <ide> console.log("good luck!"); <del> conclusion(player.item) <add> conflict(player.item) <ide> } <ide> else { <ide> console.log("The guide knocks you out and throws you inside, secretly hoping you'll succeed. So much for choice, right?"); <ide> player.hp -= 1 <del> conclusion(player.item) <add> conflict(player.item) <ide> } <ide> } <ide> <del>var conclusion = function(player_item) { <add>var conflict = function(player_item) { <ide> if (player_item == 'gun') { <del> var shoot = prompt("You are in the room with the treasure, and you see the monster. It's current status is" + boss.status + ". Do you shoot? (yes or no)") <del> if (shoot = 'yes') { <del> boss.hp -= 2 <del> boss.status == "enraged" <del> var shoot2 = prompt("The monster is wounded, but wakes up enraged. It charges at you, do you shoot again?") <del> if (shoot2 == 'yes') { <del> boss.hp -= 2 <del> boss.status == "defeated" <del> console.log("You have defeated the monster, you now get to claim your treasure") <del> } <del> else { <del> console.log("The monster attacks you to defend itself. You suffer many injuries and escape, just to have the guide shoot you in the knee with an arrow. You live the rest of your life wondering what treasure was there.") <del> } <add> <ide> } <del> <ide> else { <ide> console.log("You wonder how you made it this far, as you are itemless facing a monster. An Arrow hits you in the knee, and you flee in terror. 60 years later, you find yourself in a Tuesday next to a stranger compelled to tell them your story.") <ide> }
Java
mit
ac1eab0ab87774f379d4290b7c805fd60e1d1efa
0
the-blue-alliance/the-blue-alliance-android,the-blue-alliance/the-blue-alliance-android,the-blue-alliance/the-blue-alliance-android,nwalters512/the-blue-alliance-android,phil-lopreiato/the-blue-alliance-android,1fish2/the-blue-alliance-android,phil-lopreiato/the-blue-alliance-android,1fish2/the-blue-alliance-android,nwalters512/the-blue-alliance-android,phil-lopreiato/the-blue-alliance-android,nwalters512/the-blue-alliance-android,1fish2/the-blue-alliance-android
package com.thebluealliance.androidclient.subscribers; import android.util.Log; import com.thebluealliance.androidclient.Constants; import com.thebluealliance.androidclient.database.DatabaseWriter; import com.thebluealliance.androidclient.eventbus.NotificationsUpdatedEvent; import com.thebluealliance.androidclient.gcm.notifications.BaseNotification; import com.thebluealliance.androidclient.listitems.ListItem; import com.thebluealliance.androidclient.models.BasicModel; import com.thebluealliance.androidclient.models.StoredNotification; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; public class RecentNotificationsSubscriber extends BaseAPISubscriber<List<StoredNotification>, List<ListItem>> { private final DatabaseWriter mWriter; @Inject public RecentNotificationsSubscriber(DatabaseWriter writer) { super(); mWriter = writer; mDataToBind = new ArrayList<>(); } @Override public void parseData() throws BasicModel.FieldNotDefinedException { mDataToBind.clear(); for (int i = 0; i < mAPIData.size(); i++) { StoredNotification notification = mAPIData.get(i); BaseNotification renderable = notification.getNotification(mWriter); if (renderable != null) { renderable.parseMessageData(); if (renderable.shouldShowInRecentNotificationsList()) { mDataToBind.add(renderable); } } } } @Override public boolean isDataValid() { return super.isDataValid() && !mAPIData.isEmpty(); } /** * A new notification was received, refresh this view */ @SuppressWarnings("unused") public void onEvent(NotificationsUpdatedEvent event) { Log.d(Constants.LOG_TAG, "Updating notification list"); BaseNotification notification = event.getNotification(); notification.parseMessageData(); if (notification.shouldShowInRecentNotificationsList()) { mDataToBind.add(0, notification); } bindData(); } }
android/src/main/java/com/thebluealliance/androidclient/subscribers/RecentNotificationsSubscriber.java
package com.thebluealliance.androidclient.subscribers; import com.thebluealliance.androidclient.Constants; import com.thebluealliance.androidclient.database.DatabaseWriter; import com.thebluealliance.androidclient.eventbus.NotificationsUpdatedEvent; import com.thebluealliance.androidclient.gcm.notifications.BaseNotification; import com.thebluealliance.androidclient.listitems.ListItem; import com.thebluealliance.androidclient.models.BasicModel; import com.thebluealliance.androidclient.models.StoredNotification; import android.util.Log; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; public class RecentNotificationsSubscriber extends BaseAPISubscriber<List<StoredNotification>, List<ListItem>> { private final DatabaseWriter mWriter; @Inject public RecentNotificationsSubscriber(DatabaseWriter writer) { super(); mWriter = writer; mDataToBind = new ArrayList<>(); } @Override public void parseData() throws BasicModel.FieldNotDefinedException { mDataToBind.clear(); for (int i = 0; i < mAPIData.size(); i++) { StoredNotification notification = mAPIData.get(i); BaseNotification renderable = notification.getNotification(mWriter); if (renderable != null) { renderable.parseMessageData(); mDataToBind.add(renderable); } } } @Override public boolean isDataValid() { return super.isDataValid() && !mAPIData.isEmpty(); } /** * A new notification was received, refresh this view */ @SuppressWarnings("unused") public void onEvent(NotificationsUpdatedEvent event) { Log.d(Constants.LOG_TAG, "Updating notification list"); BaseNotification notification = event.getNotification(); notification.parseMessageData(); mDataToBind.add(0, notification); bindData(); } }
Recent Notifications now only shows notifications that are flagged as "display in recents"
android/src/main/java/com/thebluealliance/androidclient/subscribers/RecentNotificationsSubscriber.java
Recent Notifications now only shows notifications that are flagged as "display in recents"
<ide><path>ndroid/src/main/java/com/thebluealliance/androidclient/subscribers/RecentNotificationsSubscriber.java <ide> package com.thebluealliance.androidclient.subscribers; <add> <add>import android.util.Log; <ide> <ide> import com.thebluealliance.androidclient.Constants; <ide> import com.thebluealliance.androidclient.database.DatabaseWriter; <ide> import com.thebluealliance.androidclient.listitems.ListItem; <ide> import com.thebluealliance.androidclient.models.BasicModel; <ide> import com.thebluealliance.androidclient.models.StoredNotification; <del> <del>import android.util.Log; <ide> <ide> import java.util.ArrayList; <ide> import java.util.List; <ide> BaseNotification renderable = notification.getNotification(mWriter); <ide> if (renderable != null) { <ide> renderable.parseMessageData(); <del> mDataToBind.add(renderable); <add> if (renderable.shouldShowInRecentNotificationsList()) { <add> mDataToBind.add(renderable); <add> } <ide> } <ide> } <ide> } <ide> <del> @Override public boolean isDataValid() { <add> @Override <add> public boolean isDataValid() { <ide> return super.isDataValid() && !mAPIData.isEmpty(); <ide> } <ide> <ide> Log.d(Constants.LOG_TAG, "Updating notification list"); <ide> BaseNotification notification = event.getNotification(); <ide> notification.parseMessageData(); <del> mDataToBind.add(0, notification); <add> if (notification.shouldShowInRecentNotificationsList()) { <add> mDataToBind.add(0, notification); <add> } <ide> bindData(); <ide> } <ide> }
Java
agpl-3.0
45198b49474cfaaa9f92506096f0ea20a02b1748
0
sourcebits-praveenkh/Tagase,amikey/tigase-server,pivotal-nathan-sentjens/tigase-xmpp-java,caiyingyuan/tigase71,caiyingyuan/tigase71,cgvarela/tigase-server,amikey/tigase-server,f24-ag/tigase,pivotal-nathan-sentjens/tigase-xmpp-java,nate-sentjens/tigase-xmpp-java,pivotal-nathan-sentjens/tigase-xmpp-java,fanout/tigase-server,f24-ag/tigase,fanout/tigase-server,nate-sentjens/tigase-xmpp-java,pivotal-nathan-sentjens/tigase-xmpp-java,caiyingyuan/tigase71,cgvarela/tigase-server,cgvarela/tigase-server,caiyingyuan/tigase71,wangningbo/tigase-server,pivotal-nathan-sentjens/tigase-xmpp-java,wangningbo/tigase-server,fanout/tigase-server,cgvarela/tigase-server,sourcebits-praveenkh/Tagase,fanout/tigase-server,nate-sentjens/tigase-xmpp-java,sourcebits-praveenkh/Tagase,sourcebits-praveenkh/Tagase,fanout/tigase-server,fanout/tigase-server,wangningbo/tigase-server,amikey/tigase-server,nate-sentjens/tigase-xmpp-java,amikey/tigase-server,f24-ag/tigase,cgvarela/tigase-server,cgvarela/tigase-server,wangningbo/tigase-server,f24-ag/tigase,amikey/tigase-server,pivotal-nathan-sentjens/tigase-xmpp-java,amikey/tigase-server,wangningbo/tigase-server,caiyingyuan/tigase71,f24-ag/tigase,wangningbo/tigase-server,sourcebits-praveenkh/Tagase,caiyingyuan/tigase71,f24-ag/tigase,sourcebits-praveenkh/Tagase,nate-sentjens/tigase-xmpp-java,wangningbo/tigase-server,nate-sentjens/tigase-xmpp-java
/* * MessageRouter.java * * Tigase Jabber/XMPP Server * Copyright (C) 2004-2013 "Tigase, Inc." <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. Look for COPYING file in the top folder. * If not, see http://www.gnu.org/licenses/. * */ package tigase.server; //~--- non-JDK imports -------------------------------------------------------- import tigase.conf.ConfiguratorAbstract; import tigase.disco.XMPPService; import tigase.stats.StatisticsList; import tigase.sys.TigaseRuntime; import tigase.util.TigaseStringprepException; import tigase.util.UpdatesChecker; import tigase.xml.Element; import tigase.xmpp.Authorization; import tigase.xmpp.JID; import tigase.xmpp.PacketErrorTypeException; import tigase.xmpp.StanzaType; import static tigase.server.MessageRouterConfig.*; //~--- JDK imports ------------------------------------------------------------ import java.lang.management.ManagementFactory; import java.lang.management.MemoryUsage; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentSkipListSet; import java.util.logging.Level; import java.util.logging.Logger; /** * Class MessageRouter * * * Created: Tue Nov 22 07:07:11 2005 * * @author <a href="mailto:[email protected]">Artur Hefczyc</a> * @version $Rev$ */ public class MessageRouter extends AbstractMessageReceiver implements MessageRouterIfc { // implements XMPPService { // public static final String INFO_XMLNS = // "http://jabber.org/protocol/disco#info"; // public static final String ITEMS_XMLNS = // "http://jabber.org/protocol/disco#items"; private static final Logger log = Logger.getLogger(MessageRouter.class.getName()); //~--- fields --------------------------------------------------------------- private ConfiguratorAbstract config = null; // private static final long startupTime = System.currentTimeMillis(); // private Set<String> localAddresses = new CopyOnWriteArraySet<String>(); private String disco_name = DISCO_NAME_PROP_VAL; private boolean disco_show_version = DISCO_SHOW_VERSION_PROP_VAL; private UpdatesChecker updates_checker = null; private Map<String, XMPPService> xmppServices = new ConcurrentHashMap<String, XMPPService>(); private Map<String, ComponentRegistrator> registrators = new ConcurrentHashMap<String, ComponentRegistrator>(); private Map<String, MessageReceiver> receivers = new ConcurrentHashMap<String, MessageReceiver>(); private boolean inProperties = false; private Set<String> connectionManagerNames = new ConcurrentSkipListSet<String>(); private Map<JID, ServerComponent> components_byId = new ConcurrentHashMap<JID, ServerComponent>(); private Map<String, ServerComponent> components = new ConcurrentHashMap<String, ServerComponent>(); //~--- methods -------------------------------------------------------------- /** * Method description * * * @param component */ public void addComponent(ServerComponent component) { log.log(Level.INFO, "Adding component: ", component.getClass().getSimpleName()); for (ComponentRegistrator registr : registrators.values()) { if (registr != component) { if (log.isLoggable(Level.FINER)) { log.log(Level.FINER, "Adding: {0} component to {1} registrator.", new Object[] { component.getName(), registr.getName() }); } registr.addComponent(component); } // end of if (reg != component) } // end of for () components.put(component.getName(), component); components_byId.put(component.getComponentId(), component); if (component instanceof XMPPService) { xmppServices.put(component.getName(), (XMPPService) component); } } /** * Method description * * * @param registr */ public void addRegistrator(ComponentRegistrator registr) { log.log(Level.INFO, "Adding registrator: {0}", registr.getClass().getSimpleName()); registrators.put(registr.getName(), registr); addComponent(registr); for (ServerComponent comp : components.values()) { // if (comp != registr) { registr.addComponent(comp); // } // end of if (comp != registr) } // end of for (ServerComponent comp : components) } /** * Method description * * * @param receiver */ public void addRouter(MessageReceiver receiver) { log.info("Adding receiver: " + receiver.getClass().getSimpleName()); addComponent(receiver); receivers.put(receiver.getName(), receiver); } /** * Method description * * * @param packet * * @return */ @Override public int hashCodeForPacket(Packet packet) { // This is actually quite tricky part. We want to both avoid // packet reordering and also even packets distribution among // different threads. // If packet comes from a connection manager we must use packetFrom // address. However if the packet comes from SM, PubSub or other similar // component all packets would end-up in the same queue. // So, kind of a workaround here.... // TODO: develop a proper solution discovering which components are // connection managers and use their names here instead of static names. if ((packet.getPacketFrom() != null) && (packet.getPacketFrom().getLocalpart() != null)) { if (connectionManagerNames.contains(packet.getPacketFrom().getLocalpart())) { return packet.getPacketFrom().hashCode(); } } if ((packet.getPacketTo() != null) && (packet.getPacketTo().getLocalpart() != null)) { if (connectionManagerNames.contains(packet.getPacketTo().getLocalpart())) { return packet.getPacketTo().hashCode(); } } if (packet.getStanzaTo() != null) { return packet.getStanzaTo().getBareJID().hashCode(); } if ((packet.getPacketFrom() != null) &&!getComponentId().equals(packet .getPacketFrom())) { // This comes from connection manager so the best way is to get hashcode // by the connectionId, which is in the getFrom() return packet.getPacketFrom().hashCode(); } if ((packet.getPacketTo() != null) &&!getComponentId().equals(packet.getPacketTo())) { return packet.getPacketTo().hashCode(); } // If not, then a better way is to get hashCode from the elemTo address // as this would be by the destination address user name: return 1; } /** * Method description * * * @return */ @Override public int processingInThreads() { return Runtime.getRuntime().availableProcessors() * 4; } /** * Method description * * * @return */ @Override public int processingOutThreads() { return 1; } // ~--- methods -------------------------------------------------------------- // private String isToLocalComponent(String jid) { // String nick = JIDUtils.getNodeNick(jid); // if (nick == null) { // return null; // } // String host = JIDUtils.getNodeHost(jid); // if (isLocalDomain(host) && components.get(nick) != null) { // return nick; // } // return null; // } // private boolean isLocalDomain(String domain) { // return localAddresses.contains(domain); // } /** * Method description * * * @param packet */ @Override public void processPacket(Packet packet) { // We do not process packets with not destination address // Just dropping them and writing a log message if (packet.getTo() == null) { log.log(Level.WARNING, "Packet with TO attribute set to NULL: {0}", packet); return; } // end of if (packet.getTo() == null) // Intentionally comparing to static, final String // This is kind of a hack to handle packets addressed specifically for the // SessionManager // TODO: Replace the hack with a proper solution // if (packet.getTo() == NULL_ROUTING) { // log.info("NULL routing, it is normal if server doesn't know how to" // + " process packet: " + packet.toStringSecure()); // // try { // Packet error = // Authorization.FEATURE_NOT_IMPLEMENTED.getResponseMessage(packet, // "Feature not supported yet.", true); // // addOutPacketNB(error); // } catch (PacketErrorTypeException e) { // log.warning("Packet processing exception: " + e); // } // // return; // } // if (log.isLoggable(Level.FINER)) { // log.finer("Processing packet: " + packet.getElemName() // + ", type: " + packet.getType()); // } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Processing packet: {0}", packet); } // Detect inifinite loop if from == to // Maybe it is not needed anymore... // There is a need to process packets with the same from and to address // let't try to relax restriction and block all packets with error type // 2008-06-16 if (((packet.getType() == StanzaType.error) && (packet.getFrom() != null) && packet .getFrom().equals(packet.getTo()))) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Possible infinite loop, dropping packet: {0}", packet); } return; } // Catch and process all service discovery packets here.... ServerComponent comp = (packet.getStanzaTo() == null) ? null : getLocalComponent(packet.getStanzaTo()); if (packet.isServiceDisco() && (packet.getType() == StanzaType.get) && (packet .getStanzaFrom() != null) && ((packet.getStanzaTo() == null) || ((comp != null) && !(comp instanceof DisableDisco)) || isLocalDomain(packet.getStanzaTo() .toString()))) { Queue<Packet> results = new ArrayDeque<Packet>(); processDiscoQuery(packet, results); if (results.size() > 0) { for (Packet res : results) { // No more recurrential calls!! addOutPacketNB(res); } // end of for () } return; } // It is not a service discovery packet, we have to find a component to // process // the packet. The below block of code is to "quickly" find a component if // the // the packet is addressed to the component ID where the component ID is // either // of one below: // 1. component name + "@" + default domain name // 2. component name + "@" + any virtual host name // 3. component name + "." + default domain name // 4. component name + "." + any virtual host name // TODO: check the efficiency for packets addressed to c2s component comp = getLocalComponent(packet.getTo()); if (comp != null) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "1. Packet will be processed by: {0}, {1}", new Object[] { comp.getComponentId(), packet }); } Queue<Packet> results = new ArrayDeque<Packet>(); if (comp == this) { // This is addressed to the MessageRouter itself. Has to be processed // separately to avoid recurential calls by the packet processing // method. processPacketMR(packet, results); } else { // All other components process the packet the same way. comp.processPacket(packet, results); } if (results.size() > 0) { for (Packet res : results) { // No more recurrential calls!! addOutPacketNB(res); // processPacket(res); } // end of for () } // If the component is found the processing ends here as there can be // only one component with specific ID. return; } // This packet is not processed yet // The packet can be addressed to just a domain, one of the virtual hosts // The code below finds all components which handle packets addressed // to a virtual domains (implement VHostListener and return 'true' from // handlesLocalDomains() method call) String host = packet.getTo().getDomain(); ServerComponent[] comps = getComponentsForLocalDomain(host); if (comps == null) { // Still no component found, now the most expensive lookup. // Checking regex routings provided by the component. comps = getServerComponentsForRegex(packet.getTo().getBareJID().toString()); } if ((comps == null) &&!isLocalDomain(host)) { // None of the component want to process the packet. // If the packet is addressed to non-local domain then it is processed by // all components dealing with external world, like s2s comps = getComponentsForNonLocalDomain(host); } // Ok, if any component has been found then process the packet in a standard // way if (comps != null) { // Processing packet and handling results out Queue<Packet> results = new ArrayDeque<Packet>(); for (ServerComponent serverComponent : comps) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "2. Packet will be processed by: {0}, {1}", new Object[] { serverComponent.getComponentId(), packet }); } serverComponent.processPacket(packet, results); if (results.size() > 0) { for (Packet res : results) { // No more recurrential calls!! addOutPacketNB(res); // processPacket(res); } // end of for () } } } else { // No components for the packet, sending an error back if (log.isLoggable(Level.FINEST)) { log.finest("There is no component for the packet, sending it back"); } try { addOutPacketNB(Authorization.SERVICE_UNAVAILABLE.getResponseMessage(packet, "There is no service found to process your request.", true)); } catch (PacketErrorTypeException e) { // This packet is to local domain, we don't want to send it out // drop packet :-( log.warning("Can't process packet to local domain, dropping..." + packet .toStringSecure()); } } } /** * Method description * * * @param packet * @param results */ public void processPacketMR(Packet packet, Queue<Packet> results) { Iq iq = null; if (packet instanceof Iq) { iq = (Iq) packet; } else { // Not a command for sure... log.warning("I expect command (Iq) packet here, instead I got: " + packet .toString()); return; } if (packet.getPermissions() != Permissions.ADMIN) { try { Packet res = Authorization.NOT_AUTHORIZED.getResponseMessage(packet, "You are not authorized for this action.", true); results.offer(res); // processPacket(res); } catch (PacketErrorTypeException e) { log.warning("Packet processing exception: " + e); } return; } if (log.isLoggable(Level.FINEST)) { log.finest("Command received: " + iq.toString()); } switch (iq.getCommand()) { case OTHER : if (iq.getStrCommand() != null) { if (iq.getStrCommand().startsWith("controll/")) { String[] spl = iq.getStrCommand().split("/"); String cmd = spl[1]; if (cmd.equals("stop")) { Packet result = iq.commandResult(Command.DataType.result); results.offer(result); // processPacket(result); new Timer("Stopping...", true).schedule(new TimerTask() { @Override public void run() { System.exit(0); } }, 2000); } } } break; default : break; } } /** * Method description * * * @param component */ public void removeComponent(ServerComponent component) { for (ComponentRegistrator registr : registrators.values()) { if (registr != component) { if (log.isLoggable(Level.FINER)) { log.log(Level.FINER, "Adding: {0} component to {1} registrator.", new Object[] { component.getName(), registr.getName() }); } registr.deleteComponent(component); } // end of if (reg != component) } // end of for () components.remove(component.getName()); components_byId.remove(component.getComponentId()); if (component instanceof XMPPService) { xmppServices.remove(component.getName()); } } /** * Method description * * * @param receiver */ public void removeRouter(MessageReceiver receiver) { log.info("Removing receiver: " + receiver.getClass().getSimpleName()); receivers.remove(receiver.getName()); removeComponent(receiver); } /** * Method description * */ @Override public void start() { super.start(); } /** * Method description * */ @Override public void stop() { Set<String> comp_names = new TreeSet<String>(); comp_names.addAll(components.keySet()); for (String name : comp_names) { ServerComponent comp = components.remove(name); if ((comp != this) && (comp != null)) { comp.release(); } } super.stop(); } //~--- get methods ---------------------------------------------------------- // ~--- get methods ---------------------------------------------------------- /** * Method description * * * @param params * * @return */ @Override public Map<String, Object> getDefaults(Map<String, Object> params) { Map<String, Object> defs = super.getDefaults(params); MessageRouterConfig.getDefaults(defs, params, getName()); return defs; } /** * Method description * * * @return */ @Override public String getDiscoCategoryType() { return "im"; } /** * Method description * * * @return */ @Override public String getDiscoDescription() { return disco_name + (disco_show_version ? (" ver. " + XMPPServer.getImplementationVersion()) : ""); } // public List<Element> getDiscoItems(String node, String jid) { // return null; // } /** * Method description * * * @param list */ @Override public void getStatistics(StatisticsList list) { super.getStatistics(list); list.add(getName(), "Local hostname", getDefHostName().getDomain(), Level.INFO); TigaseRuntime runtime = TigaseRuntime.getTigaseRuntime(); list.add(getName(), "Uptime", runtime.getUptimeString(), Level.INFO); NumberFormat format = NumberFormat.getNumberInstance(); format.setMaximumFractionDigits(4); list.add(getName(), "Load average", format.format(runtime.getLoadAverage()), Level .FINE); list.add(getName(), "CPUs no", runtime.getCPUsNumber(), Level.FINEST); list.add(getName(), "Threads count", runtime.getThreadsNumber(), Level.FINEST); float cpuUsage = runtime.getCPUUsage(); float heapUsage = runtime.getHeapMemUsage(); float nonHeapUsage = runtime.getNonHeapMemUsage(); list.add(getName(), "CPU usage [%]", cpuUsage, Level.FINE); list.add(getName(), "HEAP usage [%]", heapUsage, Level.FINE); list.add(getName(), "NONHEAP usage [%]", nonHeapUsage, Level.FINE); format = NumberFormat.getNumberInstance(); format.setMaximumFractionDigits(1); // if (format instanceof DecimalFormat) { // DecimalFormat decf = (DecimalFormat)format; // decf.applyPattern(decf.toPattern()+"%"); // } list.add(getName(), "CPU usage", format.format(cpuUsage) + "%", Level.INFO); MemoryUsage heap = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage(); MemoryUsage nonHeap = ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage(); format = NumberFormat.getIntegerInstance(); if (format instanceof DecimalFormat) { DecimalFormat decf = (DecimalFormat) format; decf.applyPattern(decf.toPattern() + " KB"); } list.add(getName(), "Max Heap mem", format.format(heap.getMax() / 1024), Level.INFO); list.add(getName(), "Used Heap", format.format(heap.getUsed() / 1024), Level.INFO); list.add(getName(), "Free Heap", format.format((heap.getMax() - heap.getUsed()) / 1024), Level.FINE); list.add(getName(), "Max NonHeap mem", format.format(nonHeap.getMax() / 1024), Level .FINE); list.add(getName(), "Used NonHeap", format.format(nonHeap.getUsed() / 1024), Level .FINE); list.add(getName(), "Free NonHeap", format.format((nonHeap.getMax() - nonHeap .getUsed()) / 1024), Level.FINE); } //~--- set methods ---------------------------------------------------------- // ~--- set methods ---------------------------------------------------------- /** * Method description * * * @param config */ @Override public void setConfig(ConfiguratorAbstract config) { components.put(getName(), this); this.config = config; addRegistrator(config); } /** * Method description * * * @param props */ @Override public void setProperties(Map<String, Object> props) { if (inProperties) { return; } else { inProperties = true; } // end of if (inProperties) else connectionManagerNames.add("c2s"); connectionManagerNames.add("bosh"); connectionManagerNames.add("s2s"); if (props.get(DISCO_SHOW_VERSION_PROP_KEY) != null) { disco_show_version = (Boolean) props.get(DISCO_SHOW_VERSION_PROP_KEY); } if (props.get(DISCO_NAME_PROP_KEY) != null) { disco_name = (String) props.get(DISCO_NAME_PROP_KEY); } try { super.setProperties(props); updateServiceDiscoveryItem(getName(), null, getDiscoDescription(), "server", "im", false); if (props.size() == 1) { // If props.size() == 1, it means this is a single property update and // MR does // not support it yet. return; } HashSet<String> inactive_msgrec = new HashSet<String>(receivers.keySet()); MessageRouterConfig conf = new MessageRouterConfig(props); String[] reg_names = conf.getRegistrNames(); for (String name : reg_names) { inactive_msgrec.remove(name); // First remove it and later, add it again if still active ComponentRegistrator cr = registrators.remove(name); String cls_name = (String) props.get(REGISTRATOR_PROP_KEY + name + ".class"); try { if ((cr == null) ||!cr.getClass().getName().equals(cls_name)) { if (cr != null) { cr.release(); } cr = conf.getRegistrInstance(name); cr.setName(name); } // end of if (cr == null) addRegistrator(cr); } catch (Exception e) { e.printStackTrace(); } // end of try-catch } // end of for (String name: reg_names) String[] msgrcv_names = conf.getMsgRcvActiveNames(); for (String name : msgrcv_names) { if (log.isLoggable(Level.FINER)) { log.log(Level.FINER, "Loading and registering message receiver: {0}", name); } inactive_msgrec.remove(name); // First remove it and later, add it again if still active ServerComponent mr = receivers.remove(name); xmppServices.remove(name); String cls_name = (String) props.get(MSG_RECEIVERS_PROP_KEY + name + ".class"); try { // boolean start = false; if ((mr == null) || ((mr != null) &&!conf.componentClassEquals(cls_name, mr .getClass()))) { if (mr != null) { if (mr instanceof MessageReceiver) { removeRouter((MessageReceiver) mr); } else { removeComponent(mr); } mr.release(); } mr = conf.getMsgRcvInstance(name); mr.setName(name); if (mr instanceof MessageReceiver) { ((MessageReceiver) mr).setParent(this); ((MessageReceiver) mr).start(); // start = true; } } // end of if (cr == null) if (mr instanceof MessageReceiver) { addRouter((MessageReceiver) mr); } else { addComponent(mr); } // if (start) { // ((MessageReceiver) mr).start(); // } } // end of try catch (ClassNotFoundException e) { log.log(Level.WARNING, "class for component = {0} could not be found " + "- disabling component", name); // conf.setComponentActive(name, false); } // end of try catch (Exception e) { e.printStackTrace(); } // end of try-catch } // end of for (String name: reg_names) // String[] inactive_msgrec = conf.getMsgRcvInactiveNames(); for (String name : inactive_msgrec) { ServerComponent mr = receivers.remove(name); xmppServices.remove(name); if (mr != null) { try { if (mr instanceof MessageReceiver) { removeRouter((MessageReceiver) mr); } else { removeComponent(mr); } mr.release(); } catch (Exception ex) { log.log(Level.WARNING, "exception releasing component:", ex); } } } // for (MessageReceiver mr : tmp_rec.values()) { // mr.release(); // } // end of for () // // tmp_rec.clear(); if ((Boolean) props.get(UPDATES_CHECKING_PROP_KEY)) { installUpdatesChecker((Long) props.get(UPDATES_CHECKING_INTERVAL_PROP_KEY)); } else { log.log(Level.INFO, "Disabling updates checker."); stopUpdatesChecker(); } } finally { inProperties = false; } // end of try-finally for (ServerComponent comp : components.values()) { log.log(Level.INFO, "Initialization completed notification to: {0}", comp .getName()); comp.initializationCompleted(); } // log.info("Initialization completed notification to: " + // config.getName()); // config.initializationCompleted(); } //~--- get methods ---------------------------------------------------------- // ~--- get methods ---------------------------------------------------------- /** * Method description * * * @param def * * @return */ @Override protected Integer getMaxQueueSize(int def) { return def * 10; } //~--- methods -------------------------------------------------------------- // ~--- methods -------------------------------------------------------------- private void installUpdatesChecker(long interval) { stopUpdatesChecker(); updates_checker = new UpdatesChecker(interval, this, "This is automated message generated by updates checking module.\n" + " You can disable this function changing configuration option: " + "'/" + getName() + "/" + UPDATES_CHECKING_PROP_KEY + "' or adjust" + " updates checking interval time changing option: " + "'/" + getName() + "/" + UPDATES_CHECKING_INTERVAL_PROP_KEY + "' which" + " now set to " + interval + " days."); updates_checker.start(); } private void processDiscoQuery(final Packet packet, final Queue<Packet> results) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Processing disco query by: {0}", packet.toStringSecure()); } JID toJid = packet.getStanzaTo(); JID fromJid = packet.getStanzaFrom(); String node = packet.getAttributeStaticStr(Iq.IQ_QUERY_PATH, "node"); Element query = packet.getElement().getChild("query").clone(); if (packet.isXMLNSStaticStr(Iq.IQ_QUERY_PATH, INFO_XMLNS)) { if (isLocalDomain(toJid.toString()) && (node == null)) { try { query = getDiscoInfo(node, (toJid.getLocalpart() == null) ? JID.jidInstance(getName(), toJid.toString(), null) : toJid, fromJid); } catch (TigaseStringprepException e) { log.log(Level.WARNING, "processing by stringprep throw exception for = {0}@{1}", new Object[] { getName(), toJid.toString() }); } for (XMPPService comp : xmppServices.values()) { // Buggy custom component may throw exceptions here (NPE most likely) // which may cause service disco problems for well-behaving components // too // So this is kind of a protection try { List<Element> features = comp.getDiscoFeatures(fromJid); if (features != null) { query.addChildren(features); } } catch (Exception e) { log.log(Level.WARNING, "Component service disco problem: " + comp.getName(), e); } } } else { for (XMPPService comp : xmppServices.values()) { // Buggy custom component may throw exceptions here (NPE most likely) // which may cause service disco problems for well-behaving components // too // So this is kind of a protection try { // if (jid.startsWith(comp.getName() + ".")) { Element resp = comp.getDiscoInfo(node, toJid, fromJid); if (resp != null) { query.addChildren(resp.getChildren()); } } catch (Exception e) { log.log(Level.WARNING, "Component service disco problem: " + comp.getName(), e); } // } } } } if (packet.isXMLNSStaticStr(Iq.IQ_QUERY_PATH, ITEMS_XMLNS)) { boolean localDomain = isLocalDomain(toJid.toString()); if (localDomain) { for (XMPPService comp : xmppServices.values()) { // Buggy custom component may throw exceptions here (NPE most likely) // which may cause service disco problems for well-behaving components // too // So this is kind of a protection try { // if (localDomain || (nick != null && comp.getName().equals(nick))) // { List<Element> items = comp.getDiscoItems(node, toJid, fromJid); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Localdomain: {0}, DiscoItems processed by: {1}, items: {2}", new Object[] { toJid, comp.getComponentId(), (items == null) ? null : items.toString() }); } if ((items != null) && (items.size() > 0)) { query.addChildren(items); } } catch (Exception e) { log.log(Level.WARNING, "Component service disco problem: " + comp.getName(), e); } } // end of for () } else { ServerComponent comp = getLocalComponent(toJid); if ((comp != null) && (comp instanceof XMPPService)) { List<Element> items = ((XMPPService) comp).getDiscoItems(node, toJid, fromJid); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "DiscoItems processed by: {0}, items: {1}", new Object[] { comp.getComponentId(), (items == null) ? null : items.toString() }); } if ((items != null) && (items.size() > 0)) { query.addChildren(items); } } } } results.offer(packet.okResult(query, 0)); } private void stopUpdatesChecker() { if (updates_checker != null) { updates_checker.interrupt(); updates_checker = null; } } //~--- get methods ---------------------------------------------------------- private ServerComponent[] getComponentsForLocalDomain(String domain) { return vHostManager.getComponentsForLocalDomain(domain); } private ServerComponent[] getComponentsForNonLocalDomain(String domain) { return vHostManager.getComponentsForNonLocalDomain(domain); } private ServerComponent getLocalComponent(JID jid) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Called for : {0}", jid); } // Fast lookup in the server components to find a candidate // by the component ID (JID). If the packet is addressed directly // to the component ID then this is where the processing must happen. // Normally the component id is: component name + "@" + default hostname // However the component may "choose" to have any ID. ServerComponent comp = components_byId.get(jid); if (comp != null) { return comp; } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "None compId matches: {0}, for map: {1}", new Object[] { jid, components_byId }); } // Note, component ID consists of the component name + default hostname // which can be different from a virtual host. There might be many // virtual hosts and the packet can be addressed to the component by // the component name + virtual host name // Code below, tries to find a destination by the component name + any // active virtual hostname. if (jid.getLocalpart() != null) { comp = components.get(jid.getLocalpart()); if ((comp != null) && (isLocalDomain(jid.getDomain()) || jid.getDomain().equals( getDefHostName().getDomain()))) { return comp; } } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Still no comp name matches: {0}, for map: {1}, for all VHosts: {3}", new Object[] { jid, components, vHostManager.getAllVHosts() }); } // Instead of a component ID built of: component name + "@" domain name // Some components have an ID of: component name + "." domain name // Code below tries to find a packet receiver if the address have the other // type of form. int idx = jid.getDomain().indexOf('.'); if (idx > 0) { String cmpName = jid.getDomain().substring(0, idx); String basename = jid.getDomain().substring(idx + 1); comp = components.get(cmpName); if ((comp != null) && (isLocalDomain(basename) || basename.equals(getDefHostName() .getDomain()))) { return comp; } } return null; } private ServerComponent[] getServerComponentsForRegex(String id) { LinkedHashSet<ServerComponent> comps = new LinkedHashSet<ServerComponent>(); for (MessageReceiver mr : receivers.values()) { if (log.isLoggable(Level.FINEST)) { log.finest("Checking routings for: " + mr.getName()); } if (mr.isInRegexRoutings(id)) { comps.add(mr); } } if (comps.size() > 0) { return comps.toArray(new ServerComponent[comps.size()]); } else { return null; } } } // ~ Formatted in Sun Code Convention // ~ Formatted by Jindent --- http://www.jindent.com //~ Formatted in Tigase Code Convention on 13/04/11
src/main/java/tigase/server/MessageRouter.java
/* * MessageRouter.java * * Tigase Jabber/XMPP Server * Copyright (C) 2004-2013 "Tigase, Inc." <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. Look for COPYING file in the top folder. * If not, see http://www.gnu.org/licenses/. * */ package tigase.server; //~--- non-JDK imports -------------------------------------------------------- import tigase.conf.ConfiguratorAbstract; import tigase.disco.XMPPService; import tigase.stats.StatisticsList; import tigase.sys.TigaseRuntime; import tigase.util.TigaseStringprepException; import tigase.util.UpdatesChecker; import tigase.xml.Element; import tigase.xmpp.Authorization; import tigase.xmpp.JID; import tigase.xmpp.PacketErrorTypeException; import tigase.xmpp.StanzaType; import static tigase.server.MessageRouterConfig.*; //~--- JDK imports ------------------------------------------------------------ import java.lang.management.ManagementFactory; import java.lang.management.MemoryUsage; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentSkipListSet; import java.util.logging.Level; import java.util.logging.Logger; /** * Class MessageRouter * * * Created: Tue Nov 22 07:07:11 2005 * * @author <a href="mailto:[email protected]">Artur Hefczyc</a> * @version $Rev$ */ public class MessageRouter extends AbstractMessageReceiver implements MessageRouterIfc { // implements XMPPService { // public static final String INFO_XMLNS = // "http://jabber.org/protocol/disco#info"; // public static final String ITEMS_XMLNS = // "http://jabber.org/protocol/disco#items"; private static final Logger log = Logger.getLogger(MessageRouter.class.getName()); //~--- fields --------------------------------------------------------------- private ConfiguratorAbstract config = null; // private static final long startupTime = System.currentTimeMillis(); // private Set<String> localAddresses = new CopyOnWriteArraySet<String>(); private String disco_name = DISCO_NAME_PROP_VAL; private boolean disco_show_version = DISCO_SHOW_VERSION_PROP_VAL; private UpdatesChecker updates_checker = null; private Map<String, XMPPService> xmppServices = new ConcurrentHashMap<String, XMPPService>(); private Map<String, ComponentRegistrator> registrators = new ConcurrentHashMap<String, ComponentRegistrator>(); private Map<String, MessageReceiver> receivers = new ConcurrentHashMap<String, MessageReceiver>(); private boolean inProperties = false; private Set<String> connectionManagerNames = new ConcurrentSkipListSet<String>(); private Map<JID, ServerComponent> components_byId = new ConcurrentHashMap<JID, ServerComponent>(); private Map<String, ServerComponent> components = new ConcurrentHashMap<String, ServerComponent>(); //~--- methods -------------------------------------------------------------- /** * Method description * * * @param component */ public void addComponent(ServerComponent component) { log.log(Level.INFO, "Adding component: ", component.getClass().getSimpleName()); for (ComponentRegistrator registr : registrators.values()) { if (registr != component) { if (log.isLoggable(Level.FINER)) { log.log(Level.FINER, "Adding: {0} component to {1} registrator.", new Object[] { component.getName(), registr.getName() }); } registr.addComponent(component); } // end of if (reg != component) } // end of for () components.put(component.getName(), component); components_byId.put(component.getComponentId(), component); if (component instanceof XMPPService) { xmppServices.put(component.getName(), (XMPPService) component); } } /** * Method description * * * @param component */ public void removeComponent(ServerComponent component) { for (ComponentRegistrator registr : registrators.values()) { if (registr != component) { if (log.isLoggable(Level.FINER)) { log.log(Level.FINER, "Adding: {0} component to {1} registrator.", new Object[] { component.getName(), registr.getName() }); } registr.deleteComponent(component); } // end of if (reg != component) } // end of for () components.remove(component.getName()); components_byId.remove(component.getComponentId()); if (component instanceof XMPPService) { xmppServices.remove(component.getName()); } } /** * Method description * * * @param registr */ public void addRegistrator(ComponentRegistrator registr) { log.log(Level.INFO, "Adding registrator: {0}", registr.getClass().getSimpleName()); registrators.put(registr.getName(), registr); addComponent(registr); for (ServerComponent comp : components.values()) { // if (comp != registr) { registr.addComponent(comp); // } // end of if (comp != registr) } // end of for (ServerComponent comp : components) } /** * Method description * * * @param receiver */ public void addRouter(MessageReceiver receiver) { log.info("Adding receiver: " + receiver.getClass().getSimpleName()); addComponent(receiver); receivers.put(receiver.getName(), receiver); } /** * Method description * * * @param receiver */ public void removeRouter(MessageReceiver receiver) { log.info("Removing receiver: " + receiver.getClass().getSimpleName()); receivers.remove(receiver.getName()); removeComponent(receiver); } //~--- get methods ---------------------------------------------------------- // ~--- get methods ---------------------------------------------------------- /** * Method description * * * @param params * * @return */ @Override public Map<String, Object> getDefaults(Map<String, Object> params) { Map<String, Object> defs = super.getDefaults(params); MessageRouterConfig.getDefaults(defs, params, getName()); return defs; } /** * Method description * * * @return */ @Override public String getDiscoCategoryType() { return "im"; } /** * Method description * * * @return */ @Override public String getDiscoDescription() { return disco_name + (disco_show_version ? (" ver. " + XMPPServer.getImplementationVersion()) : ""); } // public List<Element> getDiscoItems(String node, String jid) { // return null; // } /** * Method description * * * @param list */ @Override public void getStatistics(StatisticsList list) { super.getStatistics(list); list.add(getName(), "Local hostname", getDefHostName().getDomain(), Level.INFO); TigaseRuntime runtime = TigaseRuntime.getTigaseRuntime(); list.add(getName(), "Uptime", runtime.getUptimeString(), Level.INFO); NumberFormat format = NumberFormat.getNumberInstance(); format.setMaximumFractionDigits(4); list.add(getName(), "Load average", format.format(runtime.getLoadAverage()), Level.FINE); list.add(getName(), "CPUs no", runtime.getCPUsNumber(), Level.FINEST); list.add(getName(), "Threads count", runtime.getThreadsNumber(), Level.FINEST); float cpuUsage = runtime.getCPUUsage(); float heapUsage = runtime.getHeapMemUsage(); float nonHeapUsage = runtime.getNonHeapMemUsage(); list.add(getName(), "CPU usage [%]", cpuUsage, Level.FINE); list.add(getName(), "HEAP usage [%]", heapUsage, Level.FINE); list.add(getName(), "NONHEAP usage [%]", nonHeapUsage, Level.FINE); format = NumberFormat.getNumberInstance(); format.setMaximumFractionDigits(1); // if (format instanceof DecimalFormat) { // DecimalFormat decf = (DecimalFormat)format; // decf.applyPattern(decf.toPattern()+"%"); // } list.add(getName(), "CPU usage", format.format(cpuUsage) + "%", Level.INFO); MemoryUsage heap = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage(); MemoryUsage nonHeap = ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage(); format = NumberFormat.getIntegerInstance(); if (format instanceof DecimalFormat) { DecimalFormat decf = (DecimalFormat) format; decf.applyPattern(decf.toPattern() + " KB"); } list.add(getName(), "Max Heap mem", format.format(heap.getMax() / 1024), Level.INFO); list.add(getName(), "Used Heap", format.format(heap.getUsed() / 1024), Level.INFO); list.add(getName(), "Free Heap", format.format((heap.getMax() - heap.getUsed()) / 1024), Level.FINE); list.add(getName(), "Max NonHeap mem", format.format(nonHeap.getMax() / 1024), Level.FINE); list.add(getName(), "Used NonHeap", format.format(nonHeap.getUsed() / 1024), Level.FINE); list.add(getName(), "Free NonHeap", format.format((nonHeap.getMax() - nonHeap.getUsed()) / 1024), Level.FINE); } //~--- methods -------------------------------------------------------------- // ~--- methods -------------------------------------------------------------- // private String isToLocalComponent(String jid) { // String nick = JIDUtils.getNodeNick(jid); // if (nick == null) { // return null; // } // String host = JIDUtils.getNodeHost(jid); // if (isLocalDomain(host) && components.get(nick) != null) { // return nick; // } // return null; // } // private boolean isLocalDomain(String domain) { // return localAddresses.contains(domain); // } /** * Method description * * * @param packet */ @Override public void processPacket(Packet packet) { // We do not process packets with not destination address // Just dropping them and writing a log message if (packet.getTo() == null) { log.log(Level.WARNING, "Packet with TO attribute set to NULL: {0}", packet); return; } // end of if (packet.getTo() == null) // Intentionally comparing to static, final String // This is kind of a hack to handle packets addressed specifically for the // SessionManager // TODO: Replace the hack with a proper solution // if (packet.getTo() == NULL_ROUTING) { // log.info("NULL routing, it is normal if server doesn't know how to" // + " process packet: " + packet.toStringSecure()); // // try { // Packet error = // Authorization.FEATURE_NOT_IMPLEMENTED.getResponseMessage(packet, // "Feature not supported yet.", true); // // addOutPacketNB(error); // } catch (PacketErrorTypeException e) { // log.warning("Packet processing exception: " + e); // } // // return; // } // if (log.isLoggable(Level.FINER)) { // log.finer("Processing packet: " + packet.getElemName() // + ", type: " + packet.getType()); // } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Processing packet: {0}", packet); } // Detect inifinite loop if from == to // Maybe it is not needed anymore... // There is a need to process packets with the same from and to address // let't try to relax restriction and block all packets with error type // 2008-06-16 if (((packet.getType() == StanzaType.error) && (packet.getFrom() != null) && packet.getFrom().equals(packet.getTo()))) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Possible infinite loop, dropping packet: {0}", packet); } return; } // Catch and process all service discovery packets here.... ServerComponent comp = (packet.getStanzaTo() == null) ? null : getLocalComponent(packet.getStanzaTo()); if (packet.isServiceDisco() && (packet.getType() == StanzaType.get) && (packet.getStanzaFrom() != null) && (((comp != null) &&!(comp instanceof DisableDisco)) || isLocalDomain(packet.getStanzaTo().toString()))) { Queue<Packet> results = new ArrayDeque<Packet>(); processDiscoQuery(packet, results); if (results.size() > 0) { for (Packet res : results) { // No more recurrential calls!! addOutPacketNB(res); } // end of for () } return; } // It is not a service discovery packet, we have to find a component to // process // the packet. The below block of code is to "quickly" find a component if // the // the packet is addressed to the component ID where the component ID is // either // of one below: // 1. component name + "@" + default domain name // 2. component name + "@" + any virtual host name // 3. component name + "." + default domain name // 4. component name + "." + any virtual host name // TODO: check the efficiency for packets addressed to c2s component comp = getLocalComponent(packet.getTo()); if (comp != null) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "1. Packet will be processed by: {0}, {1}", new Object[] { comp.getComponentId(), packet }); } Queue<Packet> results = new ArrayDeque<Packet>(); if (comp == this) { // This is addressed to the MessageRouter itself. Has to be processed // separately to avoid recurential calls by the packet processing // method. processPacketMR(packet, results); } else { // All other components process the packet the same way. comp.processPacket(packet, results); } if (results.size() > 0) { for (Packet res : results) { // No more recurrential calls!! addOutPacketNB(res); // processPacket(res); } // end of for () } // If the component is found the processing ends here as there can be // only one component with specific ID. return; } // This packet is not processed yet // The packet can be addressed to just a domain, one of the virtual hosts // The code below finds all components which handle packets addressed // to a virtual domains (implement VHostListener and return 'true' from // handlesLocalDomains() method call) String host = packet.getTo().getDomain(); ServerComponent[] comps = getComponentsForLocalDomain(host); if (comps == null) { // Still no component found, now the most expensive lookup. // Checking regex routings provided by the component. comps = getServerComponentsForRegex(packet.getTo().getBareJID().toString()); } if ((comps == null) &&!isLocalDomain(host)) { // None of the component want to process the packet. // If the packet is addressed to non-local domain then it is processed by // all components dealing with external world, like s2s comps = getComponentsForNonLocalDomain(host); } // Ok, if any component has been found then process the packet in a standard // way if (comps != null) { // Processing packet and handling results out Queue<Packet> results = new ArrayDeque<Packet>(); for (ServerComponent serverComponent : comps) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "2. Packet will be processed by: {0}, {1}", new Object[] { serverComponent.getComponentId(), packet }); } serverComponent.processPacket(packet, results); if (results.size() > 0) { for (Packet res : results) { // No more recurrential calls!! addOutPacketNB(res); // processPacket(res); } // end of for () } } } else { // No components for the packet, sending an error back if (log.isLoggable(Level.FINEST)) { log.finest("There is no component for the packet, sending it back"); } try { addOutPacketNB(Authorization.SERVICE_UNAVAILABLE.getResponseMessage(packet, "There is no service found to process your request.", true)); } catch (PacketErrorTypeException e) { // This packet is to local domain, we don't want to send it out // drop packet :-( log.warning("Can't process packet to local domain, dropping..." + packet.toStringSecure()); } } } /** * Method description * * * @param packet * @param results */ public void processPacketMR(Packet packet, Queue<Packet> results) { Iq iq = null; if (packet instanceof Iq) { iq = (Iq) packet; } else { // Not a command for sure... log.warning("I expect command (Iq) packet here, instead I got: " + packet.toString()); return; } if (packet.getPermissions() != Permissions.ADMIN) { try { Packet res = Authorization.NOT_AUTHORIZED.getResponseMessage(packet, "You are not authorized for this action.", true); results.offer(res); // processPacket(res); } catch (PacketErrorTypeException e) { log.warning("Packet processing exception: " + e); } return; } if (log.isLoggable(Level.FINEST)) { log.finest("Command received: " + iq.toString()); } switch (iq.getCommand()) { case OTHER : if (iq.getStrCommand() != null) { if (iq.getStrCommand().startsWith("controll/")) { String[] spl = iq.getStrCommand().split("/"); String cmd = spl[1]; if (cmd.equals("stop")) { Packet result = iq.commandResult(Command.DataType.result); results.offer(result); // processPacket(result); new Timer("Stopping...", true).schedule(new TimerTask() { @Override public void run() { System.exit(0); } }, 2000); } } } break; default : break; } } /** * Method description * * * @return */ @Override public int processingInThreads() { return Runtime.getRuntime().availableProcessors() * 4; } /** * Method description * * * @return */ @Override public int processingOutThreads() { return 1; } //~--- set methods ---------------------------------------------------------- // ~--- set methods ---------------------------------------------------------- /** * Method description * * * @param config */ @Override public void setConfig(ConfiguratorAbstract config) { components.put(getName(), this); this.config = config; addRegistrator(config); } /** * Method description * * * @param props */ @Override public void setProperties(Map<String, Object> props) { if (inProperties) { return; } else { inProperties = true; } // end of if (inProperties) else connectionManagerNames.add("c2s"); connectionManagerNames.add("bosh"); connectionManagerNames.add("s2s"); if (props.get(DISCO_SHOW_VERSION_PROP_KEY) != null) { disco_show_version = (Boolean) props.get(DISCO_SHOW_VERSION_PROP_KEY); } if (props.get(DISCO_NAME_PROP_KEY) != null) { disco_name = (String) props.get(DISCO_NAME_PROP_KEY); } try { super.setProperties(props); updateServiceDiscoveryItem(getName(), null, getDiscoDescription(), "server", "im", false); if (props.size() == 1) { // If props.size() == 1, it means this is a single property update and // MR does // not support it yet. return; } HashSet<String> inactive_msgrec = new HashSet<String>(receivers.keySet()); MessageRouterConfig conf = new MessageRouterConfig(props); String[] reg_names = conf.getRegistrNames(); for (String name : reg_names) { inactive_msgrec.remove(name); // First remove it and later, add it again if still active ComponentRegistrator cr = registrators.remove(name); String cls_name = (String) props.get(REGISTRATOR_PROP_KEY + name + ".class"); try { if ((cr == null) ||!cr.getClass().getName().equals(cls_name)) { if (cr != null) { cr.release(); } cr = conf.getRegistrInstance(name); cr.setName(name); } // end of if (cr == null) addRegistrator(cr); } catch (Exception e) { e.printStackTrace(); } // end of try-catch } // end of for (String name: reg_names) String[] msgrcv_names = conf.getMsgRcvActiveNames(); for (String name : msgrcv_names) { if (log.isLoggable(Level.FINER)) { log.log(Level.FINER, "Loading and registering message receiver: {0}", name); } inactive_msgrec.remove(name); // First remove it and later, add it again if still active ServerComponent mr = receivers.remove(name); xmppServices.remove(name); String cls_name = (String) props.get(MSG_RECEIVERS_PROP_KEY + name + ".class"); try { // boolean start = false; if ((mr == null) || ((mr != null) &&!conf.componentClassEquals(cls_name, mr.getClass()))) { if (mr != null) { if (mr instanceof MessageReceiver) { removeRouter((MessageReceiver) mr); } else { removeComponent(mr); } mr.release(); } mr = conf.getMsgRcvInstance(name); mr.setName(name); if (mr instanceof MessageReceiver) { ((MessageReceiver) mr).setParent(this); ((MessageReceiver) mr).start(); // start = true; } } // end of if (cr == null) if (mr instanceof MessageReceiver) { addRouter((MessageReceiver) mr); } else { addComponent(mr); } // if (start) { // ((MessageReceiver) mr).start(); // } } // end of try catch (ClassNotFoundException e) { log.log(Level.WARNING, "class for component = {0} could not be found " + "- disabling component", name); // conf.setComponentActive(name, false); } // end of try catch (Exception e) { e.printStackTrace(); } // end of try-catch } // end of for (String name: reg_names) // String[] inactive_msgrec = conf.getMsgRcvInactiveNames(); for (String name : inactive_msgrec) { ServerComponent mr = receivers.remove(name); xmppServices.remove(name); if (mr != null) { try { if (mr instanceof MessageReceiver) { removeRouter((MessageReceiver) mr); } else { removeComponent(mr); } mr.release(); } catch (Exception ex) { log.log(Level.WARNING, "exception releasing component:", ex); } } } // for (MessageReceiver mr : tmp_rec.values()) { // mr.release(); // } // end of for () // // tmp_rec.clear(); if ((Boolean) props.get(UPDATES_CHECKING_PROP_KEY)) { installUpdatesChecker((Long) props.get(UPDATES_CHECKING_INTERVAL_PROP_KEY)); } else { log.log(Level.INFO, "Disabling updates checker."); stopUpdatesChecker(); } } finally { inProperties = false; } // end of try-finally for (ServerComponent comp : components.values()) { log.log(Level.INFO, "Initialization completed notification to: {0}", comp.getName()); comp.initializationCompleted(); } // log.info("Initialization completed notification to: " + // config.getName()); // config.initializationCompleted(); } //~--- methods -------------------------------------------------------------- /** * Method description * */ @Override public void start() { super.start(); } /** * Method description * */ @Override public void stop() { Set<String> comp_names = new TreeSet<String>(); comp_names.addAll(components.keySet()); for (String name : comp_names) { ServerComponent comp = components.remove(name); if ((comp != this) && (comp != null)) { comp.release(); } } super.stop(); } //~--- get methods ---------------------------------------------------------- // ~--- get methods ---------------------------------------------------------- /** * Method description * * * @param def * * @return */ @Override protected Integer getMaxQueueSize(int def) { return def * 10; } private ServerComponent[] getComponentsForLocalDomain(String domain) { return vHostManager.getComponentsForLocalDomain(domain); } private ServerComponent[] getComponentsForNonLocalDomain(String domain) { return vHostManager.getComponentsForNonLocalDomain(domain); } private ServerComponent getLocalComponent(JID jid) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Called for : {0}", jid); } // Fast lookup in the server components to find a candidate // by the component ID (JID). If the packet is addressed directly // to the component ID then this is where the processing must happen. // Normally the component id is: component name + "@" + default hostname // However the component may "choose" to have any ID. ServerComponent comp = components_byId.get(jid); if (comp != null) { return comp; } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "None compId matches: {0}, for map: {1}", new Object[] { jid, components_byId }); } // Note, component ID consists of the component name + default hostname // which can be different from a virtual host. There might be many // virtual hosts and the packet can be addressed to the component by // the component name + virtual host name // Code below, tries to find a destination by the component name + any // active virtual hostname. if (jid.getLocalpart() != null) { comp = components.get(jid.getLocalpart()); if ((comp != null) && (isLocalDomain(jid.getDomain()) || jid.getDomain().equals(getDefHostName().getDomain()))) { return comp; } } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Still no comp name matches: {0}, for map: {1}, for all VHosts: {3}", new Object[] { jid, components, vHostManager.getAllVHosts() }); } // Instead of a component ID built of: component name + "@" domain name // Some components have an ID of: component name + "." domain name // Code below tries to find a packet receiver if the address have the other // type of form. int idx = jid.getDomain().indexOf('.'); if (idx > 0) { String cmpName = jid.getDomain().substring(0, idx); String basename = jid.getDomain().substring(idx + 1); comp = components.get(cmpName); if ((comp != null) && (isLocalDomain(basename) || basename.equals(getDefHostName().getDomain()))) { return comp; } } return null; } //~--- methods -------------------------------------------------------------- /** * Method description * * * @param packet * * @return */ @Override public int hashCodeForPacket(Packet packet) { // This is actually quite tricky part. We want to both avoid // packet reordering and also even packets distribution among // different threads. // If packet comes from a connection manager we must use packetFrom // address. However if the packet comes from SM, PubSub or other similar // component all packets would end-up in the same queue. // So, kind of a workaround here.... // TODO: develop a proper solution discovering which components are // connection managers and use their names here instead of static names. if ((packet.getPacketFrom() != null) && (packet.getPacketFrom().getLocalpart() != null)) { if (connectionManagerNames.contains(packet.getPacketFrom().getLocalpart())) { return packet.getPacketFrom().hashCode(); } } if ((packet.getPacketTo() != null) && (packet.getPacketTo().getLocalpart() != null)) { if (connectionManagerNames.contains(packet.getPacketTo().getLocalpart())) { return packet.getPacketTo().hashCode(); } } if (packet.getStanzaTo() != null) { return packet.getStanzaTo().getBareJID().hashCode(); } if ((packet.getPacketFrom() != null) && !getComponentId().equals(packet.getPacketFrom())) { // This comes from connection manager so the best way is to get hashcode // by the connectionId, which is in the getFrom() return packet.getPacketFrom().hashCode(); } if ((packet.getPacketTo() != null) &&!getComponentId().equals(packet.getPacketTo())) { return packet.getPacketTo().hashCode(); } // If not, then a better way is to get hashCode from the elemTo address // as this would be by the destination address user name: return 1; } //~--- get methods ---------------------------------------------------------- private ServerComponent[] getServerComponentsForRegex(String id) { LinkedHashSet<ServerComponent> comps = new LinkedHashSet<ServerComponent>(); for (MessageReceiver mr : receivers.values()) { if (log.isLoggable(Level.FINEST)) { log.finest("Checking routings for: " + mr.getName()); } if (mr.isInRegexRoutings(id)) { comps.add(mr); } } if (comps.size() > 0) { return comps.toArray(new ServerComponent[comps.size()]); } else { return null; } } //~--- methods -------------------------------------------------------------- // ~--- methods -------------------------------------------------------------- private void installUpdatesChecker(long interval) { stopUpdatesChecker(); updates_checker = new UpdatesChecker(interval, this, "This is automated message generated by updates checking module.\n" + " You can disable this function changing configuration option: " + "'/" + getName() + "/" + UPDATES_CHECKING_PROP_KEY + "' or adjust" + " updates checking interval time changing option: " + "'/" + getName() + "/" + UPDATES_CHECKING_INTERVAL_PROP_KEY + "' which" + " now set to " + interval + " days."); updates_checker.start(); } private void processDiscoQuery(final Packet packet, final Queue<Packet> results) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Processing disco query by: {0}", packet.toStringSecure()); } JID toJid = packet.getStanzaTo(); JID fromJid = packet.getStanzaFrom(); String node = packet.getAttributeStaticStr(Iq.IQ_QUERY_PATH, "node"); Element query = packet.getElement().getChild("query").clone(); if (packet.isXMLNSStaticStr(Iq.IQ_QUERY_PATH, INFO_XMLNS)) { if (isLocalDomain(toJid.toString()) && (node == null)) { try { query = getDiscoInfo(node, (toJid.getLocalpart() == null) ? JID.jidInstance(getName(), toJid.toString(), null) : toJid, fromJid); } catch (TigaseStringprepException e) { log.log(Level.WARNING, "processing by stringprep throw exception for = {0}@{1}", new Object[] { getName(), toJid.toString() }); } for (XMPPService comp : xmppServices.values()) { // Buggy custom component may throw exceptions here (NPE most likely) // which may cause service disco problems for well-behaving components // too // So this is kind of a protection try { List<Element> features = comp.getDiscoFeatures(fromJid); if (features != null) { query.addChildren(features); } } catch (Exception e) { log.log(Level.WARNING, "Component service disco problem: " + comp.getName(), e); } } } else { for (XMPPService comp : xmppServices.values()) { // Buggy custom component may throw exceptions here (NPE most likely) // which may cause service disco problems for well-behaving components // too // So this is kind of a protection try { // if (jid.startsWith(comp.getName() + ".")) { Element resp = comp.getDiscoInfo(node, toJid, fromJid); if (resp != null) { query.addChildren(resp.getChildren()); } } catch (Exception e) { log.log(Level.WARNING, "Component service disco problem: " + comp.getName(), e); } // } } } } if (packet.isXMLNSStaticStr(Iq.IQ_QUERY_PATH, ITEMS_XMLNS)) { boolean localDomain = isLocalDomain(toJid.toString()); if (localDomain) { for (XMPPService comp : xmppServices.values()) { // Buggy custom component may throw exceptions here (NPE most likely) // which may cause service disco problems for well-behaving components // too // So this is kind of a protection try { // if (localDomain || (nick != null && comp.getName().equals(nick))) // { List<Element> items = comp.getDiscoItems(node, toJid, fromJid); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Localdomain: {0}, DiscoItems processed by: {1}, items: {2}", new Object[] { toJid, comp.getComponentId(), (items == null) ? null : items.toString() }); } if ((items != null) && (items.size() > 0)) { query.addChildren(items); } } catch (Exception e) { log.log(Level.WARNING, "Component service disco problem: " + comp.getName(), e); } } // end of for () } else { ServerComponent comp = getLocalComponent(toJid); if ((comp != null) && (comp instanceof XMPPService)) { List<Element> items = ((XMPPService) comp).getDiscoItems(node, toJid, fromJid); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "DiscoItems processed by: {0}, items: {1}", new Object[] { comp.getComponentId(), (items == null) ? null : items.toString() }); } if ((items != null) && (items.size() > 0)) { query.addChildren(items); } } } } results.offer(packet.okResult(query, 0)); } private void stopUpdatesChecker() { if (updates_checker != null) { updates_checker.interrupt(); updates_checker = null; } } } // ~ Formatted in Sun Code Convention // ~ Formatted by Jindent --- http://www.jindent.com //~ Formatted in Tigase Code Convention on 13/03/05
Code formatting changes only.
src/main/java/tigase/server/MessageRouter.java
Code formatting changes only.
<ide><path>rc/main/java/tigase/server/MessageRouter.java <ide> <ide> // private static final long startupTime = System.currentTimeMillis(); <ide> // private Set<String> localAddresses = new CopyOnWriteArraySet<String>(); <del> private String disco_name = DISCO_NAME_PROP_VAL; <del> private boolean disco_show_version = DISCO_SHOW_VERSION_PROP_VAL; <del> private UpdatesChecker updates_checker = null; <add> private String disco_name = DISCO_NAME_PROP_VAL; <add> private boolean disco_show_version = DISCO_SHOW_VERSION_PROP_VAL; <add> private UpdatesChecker updates_checker = null; <ide> private Map<String, XMPPService> xmppServices = new ConcurrentHashMap<String, <del> XMPPService>(); <add> XMPPService>(); <ide> private Map<String, ComponentRegistrator> registrators = new ConcurrentHashMap<String, <del> ComponentRegistrator>(); <add> ComponentRegistrator>(); <ide> private Map<String, MessageReceiver> receivers = new ConcurrentHashMap<String, <del> MessageReceiver>(); <del> private boolean inProperties = false; <del> private Set<String> connectionManagerNames = new ConcurrentSkipListSet<String>(); <add> MessageReceiver>(); <add> private boolean inProperties = false; <add> private Set<String> connectionManagerNames = <add> new ConcurrentSkipListSet<String>(); <ide> private Map<JID, ServerComponent> components_byId = new ConcurrentHashMap<JID, <del> ServerComponent>(); <add> ServerComponent>(); <ide> private Map<String, ServerComponent> components = new ConcurrentHashMap<String, <del> ServerComponent>(); <add> ServerComponent>(); <ide> <ide> //~--- methods -------------------------------------------------------------- <ide> <ide> if (registr != component) { <ide> if (log.isLoggable(Level.FINER)) { <ide> log.log(Level.FINER, "Adding: {0} component to {1} registrator.", <del> new Object[] { component.getName(), <del> registr.getName() }); <add> new Object[] { component.getName(), <add> registr.getName() }); <ide> } <ide> registr.addComponent(component); <ide> } // end of if (reg != component) <ide> * Method description <ide> * <ide> * <del> * @param component <del> */ <del> public void removeComponent(ServerComponent component) { <del> for (ComponentRegistrator registr : registrators.values()) { <del> if (registr != component) { <del> if (log.isLoggable(Level.FINER)) { <del> log.log(Level.FINER, "Adding: {0} component to {1} registrator.", <del> new Object[] { component.getName(), <del> registr.getName() }); <del> } <del> registr.deleteComponent(component); <del> } // end of if (reg != component) <del> } // end of for () <del> components.remove(component.getName()); <del> components_byId.remove(component.getComponentId()); <del> if (component instanceof XMPPService) { <del> xmppServices.remove(component.getName()); <del> } <del> } <del> <del> /** <del> * Method description <del> * <del> * <ide> * @param registr <ide> */ <ide> public void addRegistrator(ComponentRegistrator registr) { <ide> * Method description <ide> * <ide> * <del> * @param receiver <del> */ <del> public void removeRouter(MessageReceiver receiver) { <del> log.info("Removing receiver: " + receiver.getClass().getSimpleName()); <del> receivers.remove(receiver.getName()); <del> removeComponent(receiver); <del> } <del> <del> //~--- get methods ---------------------------------------------------------- <del> <del> // ~--- get methods ---------------------------------------------------------- <del> <del> /** <del> * Method description <del> * <del> * <del> * @param params <add> * @param packet <ide> * <ide> * @return <ide> */ <ide> @Override <del> public Map<String, Object> getDefaults(Map<String, Object> params) { <del> Map<String, Object> defs = super.getDefaults(params); <del> <del> MessageRouterConfig.getDefaults(defs, params, getName()); <del> <del> return defs; <add> public int hashCodeForPacket(Packet packet) { <add> <add> // This is actually quite tricky part. We want to both avoid <add> // packet reordering and also even packets distribution among <add> // different threads. <add> // If packet comes from a connection manager we must use packetFrom <add> // address. However if the packet comes from SM, PubSub or other similar <add> // component all packets would end-up in the same queue. <add> // So, kind of a workaround here.... <add> // TODO: develop a proper solution discovering which components are <add> // connection managers and use their names here instead of static names. <add> if ((packet.getPacketFrom() != null) && (packet.getPacketFrom().getLocalpart() != <add> null)) { <add> if (connectionManagerNames.contains(packet.getPacketFrom().getLocalpart())) { <add> return packet.getPacketFrom().hashCode(); <add> } <add> } <add> if ((packet.getPacketTo() != null) && (packet.getPacketTo().getLocalpart() != null)) { <add> if (connectionManagerNames.contains(packet.getPacketTo().getLocalpart())) { <add> return packet.getPacketTo().hashCode(); <add> } <add> } <add> if (packet.getStanzaTo() != null) { <add> return packet.getStanzaTo().getBareJID().hashCode(); <add> } <add> if ((packet.getPacketFrom() != null) &&!getComponentId().equals(packet <add> .getPacketFrom())) { <add> <add> // This comes from connection manager so the best way is to get hashcode <add> // by the connectionId, which is in the getFrom() <add> return packet.getPacketFrom().hashCode(); <add> } <add> if ((packet.getPacketTo() != null) &&!getComponentId().equals(packet.getPacketTo())) { <add> return packet.getPacketTo().hashCode(); <add> } <add> <add> // If not, then a better way is to get hashCode from the elemTo address <add> // as this would be by the destination address user name: <add> return 1; <ide> } <ide> <ide> /** <ide> * @return <ide> */ <ide> @Override <del> public String getDiscoCategoryType() { <del> return "im"; <add> public int processingInThreads() { <add> return Runtime.getRuntime().availableProcessors() * 4; <ide> } <ide> <ide> /** <ide> * @return <ide> */ <ide> @Override <del> public String getDiscoDescription() { <del> return disco_name + (disco_show_version <del> ? (" ver. " + XMPPServer.getImplementationVersion()) <del> : ""); <del> } <del> <del> // public List<Element> getDiscoItems(String node, String jid) { <del> // return null; <del> // } <del> <del> /** <del> * Method description <del> * <del> * <del> * @param list <del> */ <del> @Override <del> public void getStatistics(StatisticsList list) { <del> super.getStatistics(list); <del> list.add(getName(), "Local hostname", getDefHostName().getDomain(), Level.INFO); <del> <del> TigaseRuntime runtime = TigaseRuntime.getTigaseRuntime(); <del> <del> list.add(getName(), "Uptime", runtime.getUptimeString(), Level.INFO); <del> <del> NumberFormat format = NumberFormat.getNumberInstance(); <del> <del> format.setMaximumFractionDigits(4); <del> list.add(getName(), "Load average", format.format(runtime.getLoadAverage()), <del> Level.FINE); <del> list.add(getName(), "CPUs no", runtime.getCPUsNumber(), Level.FINEST); <del> list.add(getName(), "Threads count", runtime.getThreadsNumber(), Level.FINEST); <del> <del> float cpuUsage = runtime.getCPUUsage(); <del> float heapUsage = runtime.getHeapMemUsage(); <del> float nonHeapUsage = runtime.getNonHeapMemUsage(); <del> <del> list.add(getName(), "CPU usage [%]", cpuUsage, Level.FINE); <del> list.add(getName(), "HEAP usage [%]", heapUsage, Level.FINE); <del> list.add(getName(), "NONHEAP usage [%]", nonHeapUsage, Level.FINE); <del> format = NumberFormat.getNumberInstance(); <del> format.setMaximumFractionDigits(1); <del> <del> // if (format instanceof DecimalFormat) { <del> // DecimalFormat decf = (DecimalFormat)format; <del> // decf.applyPattern(decf.toPattern()+"%"); <del> // } <del> list.add(getName(), "CPU usage", format.format(cpuUsage) + "%", Level.INFO); <del> <del> MemoryUsage heap = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage(); <del> MemoryUsage nonHeap = ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage(); <del> <del> format = NumberFormat.getIntegerInstance(); <del> if (format instanceof DecimalFormat) { <del> DecimalFormat decf = (DecimalFormat) format; <del> <del> decf.applyPattern(decf.toPattern() + " KB"); <del> } <del> list.add(getName(), "Max Heap mem", format.format(heap.getMax() / 1024), Level.INFO); <del> list.add(getName(), "Used Heap", format.format(heap.getUsed() / 1024), Level.INFO); <del> list.add(getName(), "Free Heap", <del> format.format((heap.getMax() - heap.getUsed()) / 1024), Level.FINE); <del> list.add(getName(), "Max NonHeap mem", format.format(nonHeap.getMax() / 1024), <del> Level.FINE); <del> list.add(getName(), "Used NonHeap", format.format(nonHeap.getUsed() / 1024), <del> Level.FINE); <del> list.add(getName(), "Free NonHeap", <del> format.format((nonHeap.getMax() - nonHeap.getUsed()) / 1024), Level.FINE); <del> } <del> <del> //~--- methods -------------------------------------------------------------- <add> public int processingOutThreads() { <add> return 1; <add> } <ide> <ide> // ~--- methods -------------------------------------------------------------- <ide> // private String isToLocalComponent(String jid) { <ide> // There is a need to process packets with the same from and to address <ide> // let't try to relax restriction and block all packets with error type <ide> // 2008-06-16 <del> if (((packet.getType() == StanzaType.error) && (packet.getFrom() != null) && <del> packet.getFrom().equals(packet.getTo()))) { <add> if (((packet.getType() == StanzaType.error) && (packet.getFrom() != null) && packet <add> .getFrom().equals(packet.getTo()))) { <ide> if (log.isLoggable(Level.FINEST)) { <ide> log.log(Level.FINEST, "Possible infinite loop, dropping packet: {0}", packet); <ide> } <ide> <ide> // Catch and process all service discovery packets here.... <ide> ServerComponent comp = (packet.getStanzaTo() == null) <del> ? null <del> : getLocalComponent(packet.getStanzaTo()); <del> <del> if (packet.isServiceDisco() && (packet.getType() == StanzaType.get) && <del> (packet.getStanzaFrom() != null) && <del> (((comp != null) &&!(comp instanceof DisableDisco)) || <del> isLocalDomain(packet.getStanzaTo().toString()))) { <add> ? null <add> : getLocalComponent(packet.getStanzaTo()); <add> <add> if (packet.isServiceDisco() && (packet.getType() == StanzaType.get) && (packet <add> .getStanzaFrom() != null) && ((packet.getStanzaTo() == null) || ((comp != null) && <add> !(comp instanceof DisableDisco)) || isLocalDomain(packet.getStanzaTo() <add> .toString()))) { <ide> Queue<Packet> results = new ArrayDeque<Packet>(); <ide> <ide> processDiscoQuery(packet, results); <ide> comp = getLocalComponent(packet.getTo()); <ide> if (comp != null) { <ide> if (log.isLoggable(Level.FINEST)) { <del> log.log(Level.FINEST, "1. Packet will be processed by: {0}, {1}", <del> new Object[] { comp.getComponentId(), <del> packet }); <add> log.log(Level.FINEST, "1. Packet will be processed by: {0}, {1}", new Object[] { <add> comp.getComponentId(), <add> packet }); <ide> } <ide> <ide> Queue<Packet> results = new ArrayDeque<Packet>(); <ide> // The code below finds all components which handle packets addressed <ide> // to a virtual domains (implement VHostListener and return 'true' from <ide> // handlesLocalDomains() method call) <del> String host = packet.getTo().getDomain(); <add> String host = packet.getTo().getDomain(); <ide> ServerComponent[] comps = getComponentsForLocalDomain(host); <ide> <ide> if (comps == null) { <ide> for (ServerComponent serverComponent : comps) { <ide> if (log.isLoggable(Level.FINEST)) { <ide> log.log(Level.FINEST, "2. Packet will be processed by: {0}, {1}", <del> new Object[] { serverComponent.getComponentId(), <del> packet }); <add> new Object[] { serverComponent.getComponentId(), <add> packet }); <ide> } <ide> serverComponent.processPacket(packet, results); <ide> if (results.size() > 0) { <ide> } <ide> try { <ide> addOutPacketNB(Authorization.SERVICE_UNAVAILABLE.getResponseMessage(packet, <del> "There is no service found to process your request.", true)); <add> "There is no service found to process your request.", true)); <ide> } catch (PacketErrorTypeException e) { <ide> <ide> // This packet is to local domain, we don't want to send it out <ide> // drop packet :-( <del> log.warning("Can't process packet to local domain, dropping..." + <del> packet.toStringSecure()); <add> log.warning("Can't process packet to local domain, dropping..." + packet <add> .toStringSecure()); <ide> } <ide> } <ide> } <ide> } else { <ide> <ide> // Not a command for sure... <del> log.warning("I expect command (Iq) packet here, instead I got: " + <del> packet.toString()); <add> log.warning("I expect command (Iq) packet here, instead I got: " + packet <add> .toString()); <ide> <ide> return; <ide> } <ide> if (packet.getPermissions() != Permissions.ADMIN) { <ide> try { <ide> Packet res = Authorization.NOT_AUTHORIZED.getResponseMessage(packet, <del> "You are not authorized for this action.", true); <add> "You are not authorized for this action.", true); <ide> <ide> results.offer(res); <ide> <ide> if (iq.getStrCommand() != null) { <ide> if (iq.getStrCommand().startsWith("controll/")) { <ide> String[] spl = iq.getStrCommand().split("/"); <del> String cmd = spl[1]; <add> String cmd = spl[1]; <ide> <ide> if (cmd.equals("stop")) { <ide> Packet result = iq.commandResult(Command.DataType.result); <ide> * Method description <ide> * <ide> * <add> * @param component <add> */ <add> public void removeComponent(ServerComponent component) { <add> for (ComponentRegistrator registr : registrators.values()) { <add> if (registr != component) { <add> if (log.isLoggable(Level.FINER)) { <add> log.log(Level.FINER, "Adding: {0} component to {1} registrator.", <add> new Object[] { component.getName(), <add> registr.getName() }); <add> } <add> registr.deleteComponent(component); <add> } // end of if (reg != component) <add> } // end of for () <add> components.remove(component.getName()); <add> components_byId.remove(component.getComponentId()); <add> if (component instanceof XMPPService) { <add> xmppServices.remove(component.getName()); <add> } <add> } <add> <add> /** <add> * Method description <add> * <add> * <add> * @param receiver <add> */ <add> public void removeRouter(MessageReceiver receiver) { <add> log.info("Removing receiver: " + receiver.getClass().getSimpleName()); <add> receivers.remove(receiver.getName()); <add> removeComponent(receiver); <add> } <add> <add> /** <add> * Method description <add> * <add> */ <add> @Override <add> public void start() { <add> super.start(); <add> } <add> <add> /** <add> * Method description <add> * <add> */ <add> @Override <add> public void stop() { <add> Set<String> comp_names = new TreeSet<String>(); <add> <add> comp_names.addAll(components.keySet()); <add> for (String name : comp_names) { <add> ServerComponent comp = components.remove(name); <add> <add> if ((comp != this) && (comp != null)) { <add> comp.release(); <add> } <add> } <add> super.stop(); <add> } <add> <add> //~--- get methods ---------------------------------------------------------- <add> <add> // ~--- get methods ---------------------------------------------------------- <add> <add> /** <add> * Method description <add> * <add> * <add> * @param params <add> * <ide> * @return <ide> */ <ide> @Override <del> public int processingInThreads() { <del> return Runtime.getRuntime().availableProcessors() * 4; <add> public Map<String, Object> getDefaults(Map<String, Object> params) { <add> Map<String, Object> defs = super.getDefaults(params); <add> <add> MessageRouterConfig.getDefaults(defs, params, getName()); <add> <add> return defs; <ide> } <ide> <ide> /** <ide> * @return <ide> */ <ide> @Override <del> public int processingOutThreads() { <del> return 1; <add> public String getDiscoCategoryType() { <add> return "im"; <add> } <add> <add> /** <add> * Method description <add> * <add> * <add> * @return <add> */ <add> @Override <add> public String getDiscoDescription() { <add> return disco_name + (disco_show_version <add> ? (" ver. " + XMPPServer.getImplementationVersion()) <add> : ""); <add> } <add> <add> // public List<Element> getDiscoItems(String node, String jid) { <add> // return null; <add> // } <add> <add> /** <add> * Method description <add> * <add> * <add> * @param list <add> */ <add> @Override <add> public void getStatistics(StatisticsList list) { <add> super.getStatistics(list); <add> list.add(getName(), "Local hostname", getDefHostName().getDomain(), Level.INFO); <add> <add> TigaseRuntime runtime = TigaseRuntime.getTigaseRuntime(); <add> <add> list.add(getName(), "Uptime", runtime.getUptimeString(), Level.INFO); <add> <add> NumberFormat format = NumberFormat.getNumberInstance(); <add> <add> format.setMaximumFractionDigits(4); <add> list.add(getName(), "Load average", format.format(runtime.getLoadAverage()), Level <add> .FINE); <add> list.add(getName(), "CPUs no", runtime.getCPUsNumber(), Level.FINEST); <add> list.add(getName(), "Threads count", runtime.getThreadsNumber(), Level.FINEST); <add> <add> float cpuUsage = runtime.getCPUUsage(); <add> float heapUsage = runtime.getHeapMemUsage(); <add> float nonHeapUsage = runtime.getNonHeapMemUsage(); <add> <add> list.add(getName(), "CPU usage [%]", cpuUsage, Level.FINE); <add> list.add(getName(), "HEAP usage [%]", heapUsage, Level.FINE); <add> list.add(getName(), "NONHEAP usage [%]", nonHeapUsage, Level.FINE); <add> format = NumberFormat.getNumberInstance(); <add> format.setMaximumFractionDigits(1); <add> <add> // if (format instanceof DecimalFormat) { <add> // DecimalFormat decf = (DecimalFormat)format; <add> // decf.applyPattern(decf.toPattern()+"%"); <add> // } <add> list.add(getName(), "CPU usage", format.format(cpuUsage) + "%", Level.INFO); <add> <add> MemoryUsage heap = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage(); <add> MemoryUsage nonHeap = ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage(); <add> <add> format = NumberFormat.getIntegerInstance(); <add> if (format instanceof DecimalFormat) { <add> DecimalFormat decf = (DecimalFormat) format; <add> <add> decf.applyPattern(decf.toPattern() + " KB"); <add> } <add> list.add(getName(), "Max Heap mem", format.format(heap.getMax() / 1024), Level.INFO); <add> list.add(getName(), "Used Heap", format.format(heap.getUsed() / 1024), Level.INFO); <add> list.add(getName(), "Free Heap", format.format((heap.getMax() - heap.getUsed()) / <add> 1024), Level.FINE); <add> list.add(getName(), "Max NonHeap mem", format.format(nonHeap.getMax() / 1024), Level <add> .FINE); <add> list.add(getName(), "Used NonHeap", format.format(nonHeap.getUsed() / 1024), Level <add> .FINE); <add> list.add(getName(), "Free NonHeap", format.format((nonHeap.getMax() - nonHeap <add> .getUsed()) / 1024), Level.FINE); <ide> } <ide> <ide> //~--- set methods ---------------------------------------------------------- <ide> try { <ide> super.setProperties(props); <ide> updateServiceDiscoveryItem(getName(), null, getDiscoDescription(), "server", "im", <del> false); <add> false); <ide> if (props.size() == 1) { <ide> <ide> // If props.size() == 1, it means this is a single property update and <ide> return; <ide> } <ide> <del> HashSet<String> inactive_msgrec = new HashSet<String>(receivers.keySet()); <del> MessageRouterConfig conf = new MessageRouterConfig(props); <del> String[] reg_names = conf.getRegistrNames(); <add> HashSet<String> inactive_msgrec = new HashSet<String>(receivers.keySet()); <add> MessageRouterConfig conf = new MessageRouterConfig(props); <add> String[] reg_names = conf.getRegistrNames(); <ide> <ide> for (String name : reg_names) { <ide> inactive_msgrec.remove(name); <ide> <ide> // First remove it and later, add it again if still active <ide> ComponentRegistrator cr = registrators.remove(name); <del> String cls_name = (String) props.get(REGISTRATOR_PROP_KEY + name + <del> ".class"); <add> String cls_name = (String) props.get(REGISTRATOR_PROP_KEY + name + <add> ".class"); <ide> <ide> try { <ide> if ((cr == null) ||!cr.getClass().getName().equals(cls_name)) { <ide> try { <ide> <ide> // boolean start = false; <del> if ((mr == null) || <del> ((mr != null) &&!conf.componentClassEquals(cls_name, mr.getClass()))) { <add> if ((mr == null) || ((mr != null) &&!conf.componentClassEquals(cls_name, mr <add> .getClass()))) { <ide> if (mr != null) { <ide> if (mr instanceof MessageReceiver) { <ide> removeRouter((MessageReceiver) mr); <ide> // ((MessageReceiver) mr).start(); <ide> // } <ide> } // end of try <del> catch (ClassNotFoundException e) { <del> log.log(Level.WARNING, <del> "class for component = {0} could not be found " + <del> "- disabling component", name); <add> catch (ClassNotFoundException e) { <add> log.log(Level.WARNING, "class for component = {0} could not be found " + <add> "- disabling component", name); <ide> <ide> // conf.setComponentActive(name, false); <ide> } // end of try <del> catch (Exception e) { <add> catch (Exception e) { <ide> e.printStackTrace(); <ide> } // end of try-catch <ide> } // end of for (String name: reg_names) <ide> inProperties = false; <ide> } // end of try-finally <ide> for (ServerComponent comp : components.values()) { <del> log.log(Level.INFO, "Initialization completed notification to: {0}", <del> comp.getName()); <add> log.log(Level.INFO, "Initialization completed notification to: {0}", comp <add> .getName()); <ide> comp.initializationCompleted(); <ide> } <ide> <ide> // config.initializationCompleted(); <ide> } <ide> <del> //~--- methods -------------------------------------------------------------- <del> <del> /** <del> * Method description <del> * <del> */ <del> @Override <del> public void start() { <del> super.start(); <del> } <del> <del> /** <del> * Method description <del> * <del> */ <del> @Override <del> public void stop() { <del> Set<String> comp_names = new TreeSet<String>(); <del> <del> comp_names.addAll(components.keySet()); <del> for (String name : comp_names) { <del> ServerComponent comp = components.remove(name); <del> <del> if ((comp != this) && (comp != null)) { <del> comp.release(); <del> } <del> } <del> super.stop(); <del> } <del> <ide> //~--- get methods ---------------------------------------------------------- <ide> <ide> // ~--- get methods ---------------------------------------------------------- <ide> protected Integer getMaxQueueSize(int def) { <ide> return def * 10; <ide> } <add> <add> //~--- methods -------------------------------------------------------------- <add> <add> // ~--- methods -------------------------------------------------------------- <add> private void installUpdatesChecker(long interval) { <add> stopUpdatesChecker(); <add> updates_checker = new UpdatesChecker(interval, this, <add> "This is automated message generated by updates checking module.\n" + <add> " You can disable this function changing configuration option: " + "'/" + <add> getName() + "/" + UPDATES_CHECKING_PROP_KEY + "' or adjust" + <add> " updates checking interval time changing option: " + "'/" + getName() + "/" + <add> UPDATES_CHECKING_INTERVAL_PROP_KEY + "' which" + " now set to " + interval + <add> " days."); <add> updates_checker.start(); <add> } <add> <add> private void processDiscoQuery(final Packet packet, final Queue<Packet> results) { <add> if (log.isLoggable(Level.FINEST)) { <add> log.log(Level.FINEST, "Processing disco query by: {0}", packet.toStringSecure()); <add> } <add> <add> JID toJid = packet.getStanzaTo(); <add> JID fromJid = packet.getStanzaFrom(); <add> String node = packet.getAttributeStaticStr(Iq.IQ_QUERY_PATH, "node"); <add> Element query = packet.getElement().getChild("query").clone(); <add> <add> if (packet.isXMLNSStaticStr(Iq.IQ_QUERY_PATH, INFO_XMLNS)) { <add> if (isLocalDomain(toJid.toString()) && (node == null)) { <add> try { <add> query = getDiscoInfo(node, (toJid.getLocalpart() == null) <add> ? JID.jidInstance(getName(), toJid.toString(), null) <add> : toJid, fromJid); <add> } catch (TigaseStringprepException e) { <add> log.log(Level.WARNING, <add> "processing by stringprep throw exception for = {0}@{1}", new Object[] { <add> getName(), <add> toJid.toString() }); <add> } <add> for (XMPPService comp : xmppServices.values()) { <add> <add> // Buggy custom component may throw exceptions here (NPE most likely) <add> // which may cause service disco problems for well-behaving components <add> // too <add> // So this is kind of a protection <add> try { <add> List<Element> features = comp.getDiscoFeatures(fromJid); <add> <add> if (features != null) { <add> query.addChildren(features); <add> } <add> } catch (Exception e) { <add> log.log(Level.WARNING, "Component service disco problem: " + comp.getName(), <add> e); <add> } <add> } <add> } else { <add> for (XMPPService comp : xmppServices.values()) { <add> <add> // Buggy custom component may throw exceptions here (NPE most likely) <add> // which may cause service disco problems for well-behaving components <add> // too <add> // So this is kind of a protection <add> try { <add> <add> // if (jid.startsWith(comp.getName() + ".")) { <add> Element resp = comp.getDiscoInfo(node, toJid, fromJid); <add> <add> if (resp != null) { <add> query.addChildren(resp.getChildren()); <add> } <add> } catch (Exception e) { <add> log.log(Level.WARNING, "Component service disco problem: " + comp.getName(), <add> e); <add> } <add> <add> // } <add> } <add> } <add> } <add> if (packet.isXMLNSStaticStr(Iq.IQ_QUERY_PATH, ITEMS_XMLNS)) { <add> boolean localDomain = isLocalDomain(toJid.toString()); <add> <add> if (localDomain) { <add> for (XMPPService comp : xmppServices.values()) { <add> <add> // Buggy custom component may throw exceptions here (NPE most likely) <add> // which may cause service disco problems for well-behaving components <add> // too <add> // So this is kind of a protection <add> try { <add> <add> // if (localDomain || (nick != null && comp.getName().equals(nick))) <add> // { <add> List<Element> items = comp.getDiscoItems(node, toJid, fromJid); <add> <add> if (log.isLoggable(Level.FINEST)) { <add> log.log(Level.FINEST, <add> "Localdomain: {0}, DiscoItems processed by: {1}, items: {2}", <add> new Object[] { toJid, <add> comp.getComponentId(), <add> (items == null) <add> ? null <add> : items.toString() }); <add> } <add> if ((items != null) && (items.size() > 0)) { <add> query.addChildren(items); <add> } <add> } catch (Exception e) { <add> log.log(Level.WARNING, "Component service disco problem: " + comp.getName(), <add> e); <add> } <add> } // end of for () <add> } else { <add> ServerComponent comp = getLocalComponent(toJid); <add> <add> if ((comp != null) && (comp instanceof XMPPService)) { <add> List<Element> items = ((XMPPService) comp).getDiscoItems(node, toJid, fromJid); <add> <add> if (log.isLoggable(Level.FINEST)) { <add> log.log(Level.FINEST, "DiscoItems processed by: {0}, items: {1}", <add> new Object[] { comp.getComponentId(), (items == null) <add> ? null <add> : items.toString() }); <add> } <add> if ((items != null) && (items.size() > 0)) { <add> query.addChildren(items); <add> } <add> } <add> } <add> } <add> results.offer(packet.okResult(query, 0)); <add> } <add> <add> private void stopUpdatesChecker() { <add> if (updates_checker != null) { <add> updates_checker.interrupt(); <add> updates_checker = null; <add> } <add> } <add> <add> //~--- get methods ---------------------------------------------------------- <ide> <ide> private ServerComponent[] getComponentsForLocalDomain(String domain) { <ide> return vHostManager.getComponentsForLocalDomain(domain); <ide> } <ide> if (log.isLoggable(Level.FINEST)) { <ide> log.log(Level.FINEST, "None compId matches: {0}, for map: {1}", new Object[] { jid, <del> components_byId }); <add> components_byId }); <ide> } <ide> <ide> // Note, component ID consists of the component name + default hostname <ide> // active virtual hostname. <ide> if (jid.getLocalpart() != null) { <ide> comp = components.get(jid.getLocalpart()); <del> if ((comp != null) && <del> (isLocalDomain(jid.getDomain()) || <del> jid.getDomain().equals(getDefHostName().getDomain()))) { <add> if ((comp != null) && (isLocalDomain(jid.getDomain()) || jid.getDomain().equals( <add> getDefHostName().getDomain()))) { <ide> return comp; <ide> } <ide> } <ide> if (log.isLoggable(Level.FINEST)) { <ide> log.log(Level.FINEST, <del> "Still no comp name matches: {0}, for map: {1}, for all VHosts: {3}", <del> new Object[] { jid, <del> components, vHostManager.getAllVHosts() }); <add> "Still no comp name matches: {0}, for map: {1}, for all VHosts: {3}", <add> new Object[] { jid, <add> components, vHostManager.getAllVHosts() }); <ide> } <ide> <ide> // Instead of a component ID built of: component name + "@" domain name <ide> String basename = jid.getDomain().substring(idx + 1); <ide> <ide> comp = components.get(cmpName); <del> if ((comp != null) && <del> (isLocalDomain(basename) || basename.equals(getDefHostName().getDomain()))) { <add> if ((comp != null) && (isLocalDomain(basename) || basename.equals(getDefHostName() <add> .getDomain()))) { <ide> return comp; <ide> } <ide> } <ide> <ide> return null; <ide> } <del> <del> //~--- methods -------------------------------------------------------------- <del> <del> /** <del> * Method description <del> * <del> * <del> * @param packet <del> * <del> * @return <del> */ <del> @Override <del> public int hashCodeForPacket(Packet packet) { <del> <del> // This is actually quite tricky part. We want to both avoid <del> // packet reordering and also even packets distribution among <del> // different threads. <del> // If packet comes from a connection manager we must use packetFrom <del> // address. However if the packet comes from SM, PubSub or other similar <del> // component all packets would end-up in the same queue. <del> // So, kind of a workaround here.... <del> // TODO: develop a proper solution discovering which components are <del> // connection managers and use their names here instead of static names. <del> if ((packet.getPacketFrom() != null) && <del> (packet.getPacketFrom().getLocalpart() != null)) { <del> if (connectionManagerNames.contains(packet.getPacketFrom().getLocalpart())) { <del> return packet.getPacketFrom().hashCode(); <del> } <del> } <del> if ((packet.getPacketTo() != null) && (packet.getPacketTo().getLocalpart() != null)) { <del> if (connectionManagerNames.contains(packet.getPacketTo().getLocalpart())) { <del> return packet.getPacketTo().hashCode(); <del> } <del> } <del> if (packet.getStanzaTo() != null) { <del> return packet.getStanzaTo().getBareJID().hashCode(); <del> } <del> if ((packet.getPacketFrom() != null) && <del> !getComponentId().equals(packet.getPacketFrom())) { <del> <del> // This comes from connection manager so the best way is to get hashcode <del> // by the connectionId, which is in the getFrom() <del> return packet.getPacketFrom().hashCode(); <del> } <del> if ((packet.getPacketTo() != null) &&!getComponentId().equals(packet.getPacketTo())) { <del> return packet.getPacketTo().hashCode(); <del> } <del> <del> // If not, then a better way is to get hashCode from the elemTo address <del> // as this would be by the destination address user name: <del> return 1; <del> } <del> <del> //~--- get methods ---------------------------------------------------------- <ide> <ide> private ServerComponent[] getServerComponentsForRegex(String id) { <ide> LinkedHashSet<ServerComponent> comps = new LinkedHashSet<ServerComponent>(); <ide> return null; <ide> } <ide> } <del> <del> //~--- methods -------------------------------------------------------------- <del> <del> // ~--- methods -------------------------------------------------------------- <del> private void installUpdatesChecker(long interval) { <del> stopUpdatesChecker(); <del> updates_checker = new UpdatesChecker(interval, this, <del> "This is automated message generated by updates checking module.\n" + <del> " You can disable this function changing configuration option: " + "'/" + <del> getName() + "/" + UPDATES_CHECKING_PROP_KEY + "' or adjust" + <del> " updates checking interval time changing option: " + "'/" + getName() + <del> "/" + UPDATES_CHECKING_INTERVAL_PROP_KEY + "' which" + " now set to " + <del> interval + " days."); <del> updates_checker.start(); <del> } <del> <del> private void processDiscoQuery(final Packet packet, final Queue<Packet> results) { <del> if (log.isLoggable(Level.FINEST)) { <del> log.log(Level.FINEST, "Processing disco query by: {0}", packet.toStringSecure()); <del> } <del> <del> JID toJid = packet.getStanzaTo(); <del> JID fromJid = packet.getStanzaFrom(); <del> String node = packet.getAttributeStaticStr(Iq.IQ_QUERY_PATH, "node"); <del> Element query = packet.getElement().getChild("query").clone(); <del> <del> if (packet.isXMLNSStaticStr(Iq.IQ_QUERY_PATH, INFO_XMLNS)) { <del> if (isLocalDomain(toJid.toString()) && (node == null)) { <del> try { <del> query = getDiscoInfo(node, (toJid.getLocalpart() == null) <del> ? JID.jidInstance(getName(), toJid.toString(), null) <del> : toJid, fromJid); <del> } catch (TigaseStringprepException e) { <del> log.log(Level.WARNING, <del> "processing by stringprep throw exception for = {0}@{1}", <del> new Object[] { getName(), <del> toJid.toString() }); <del> } <del> for (XMPPService comp : xmppServices.values()) { <del> <del> // Buggy custom component may throw exceptions here (NPE most likely) <del> // which may cause service disco problems for well-behaving components <del> // too <del> // So this is kind of a protection <del> try { <del> List<Element> features = comp.getDiscoFeatures(fromJid); <del> <del> if (features != null) { <del> query.addChildren(features); <del> } <del> } catch (Exception e) { <del> log.log(Level.WARNING, "Component service disco problem: " + comp.getName(), <del> e); <del> } <del> } <del> } else { <del> for (XMPPService comp : xmppServices.values()) { <del> <del> // Buggy custom component may throw exceptions here (NPE most likely) <del> // which may cause service disco problems for well-behaving components <del> // too <del> // So this is kind of a protection <del> try { <del> <del> // if (jid.startsWith(comp.getName() + ".")) { <del> Element resp = comp.getDiscoInfo(node, toJid, fromJid); <del> <del> if (resp != null) { <del> query.addChildren(resp.getChildren()); <del> } <del> } catch (Exception e) { <del> log.log(Level.WARNING, "Component service disco problem: " + comp.getName(), <del> e); <del> } <del> <del> // } <del> } <del> } <del> } <del> if (packet.isXMLNSStaticStr(Iq.IQ_QUERY_PATH, ITEMS_XMLNS)) { <del> boolean localDomain = isLocalDomain(toJid.toString()); <del> <del> if (localDomain) { <del> for (XMPPService comp : xmppServices.values()) { <del> <del> // Buggy custom component may throw exceptions here (NPE most likely) <del> // which may cause service disco problems for well-behaving components <del> // too <del> // So this is kind of a protection <del> try { <del> <del> // if (localDomain || (nick != null && comp.getName().equals(nick))) <del> // { <del> List<Element> items = comp.getDiscoItems(node, toJid, fromJid); <del> <del> if (log.isLoggable(Level.FINEST)) { <del> log.log(Level.FINEST, <del> "Localdomain: {0}, DiscoItems processed by: {1}, items: {2}", <del> new Object[] { toJid, <del> comp.getComponentId(), <del> (items == null) <del> ? null <del> : items.toString() }); <del> } <del> if ((items != null) && (items.size() > 0)) { <del> query.addChildren(items); <del> } <del> } catch (Exception e) { <del> log.log(Level.WARNING, "Component service disco problem: " + comp.getName(), <del> e); <del> } <del> } // end of for () <del> } else { <del> ServerComponent comp = getLocalComponent(toJid); <del> <del> if ((comp != null) && (comp instanceof XMPPService)) { <del> List<Element> items = ((XMPPService) comp).getDiscoItems(node, toJid, fromJid); <del> <del> if (log.isLoggable(Level.FINEST)) { <del> log.log(Level.FINEST, "DiscoItems processed by: {0}, items: {1}", <del> new Object[] { comp.getComponentId(), (items == null) <del> ? null <del> : items.toString() }); <del> } <del> if ((items != null) && (items.size() > 0)) { <del> query.addChildren(items); <del> } <del> } <del> } <del> } <del> results.offer(packet.okResult(query, 0)); <del> } <del> <del> private void stopUpdatesChecker() { <del> if (updates_checker != null) { <del> updates_checker.interrupt(); <del> updates_checker = null; <del> } <del> } <ide> } <ide> <ide> <ide> // ~ Formatted by Jindent --- http://www.jindent.com <ide> <ide> <del>//~ Formatted in Tigase Code Convention on 13/03/05 <add>//~ Formatted in Tigase Code Convention on 13/04/11
Java
mpl-2.0
ec955ba6ed8fe66ee8aa394e00363bfb19c575f4
0
qhanam/rhino,qhanam/rhino,qhanam/rhino,qhanam/rhino
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.javascript.ast; import javax.json.Json; import javax.json.JsonBuilderFactory; import javax.json.JsonObject; import org.mozilla.javascript.Token; /** * AST node representing an infix (binary operator) expression. * The operator is the node's {@link Token} type. */ public class InfixExpression extends AstNode { protected AstNode left; protected AstNode right; protected int operatorPosition = -1; public InfixExpression() { } public InfixExpression(int pos) { super(pos); } public InfixExpression(int pos, int len) { super(pos, len); } public InfixExpression(int pos, int len, AstNode left, AstNode right) { super(pos, len); setLeft(left); setRight(right); } /** * Constructs a new {@code InfixExpression}. Updates bounds to include * left and right nodes. */ public InfixExpression(AstNode left, AstNode right) { setLeftAndRight(left, right); } /** * Constructs a new {@code InfixExpression}. * @param operatorPos the <em>absolute</em> position of the operator */ public InfixExpression(int operator, AstNode left, AstNode right, int operatorPos) { setType(operator); setOperatorPosition(operatorPos - left.getPosition()); setLeftAndRight(left, right); } /** * @return This node as a JSON object in Esprima format. * @author qhanam */ @Override public JsonObject getJsonObject() { JsonBuilderFactory factory = Json.createBuilderFactory(null); String type = null; String operator = null; switch(this.getOperator()) { case Token.ASSIGN: // Assignment Operators case Token.ASSIGN_ADD: case Token.ASSIGN_SUB: case Token.ASSIGN_MUL: case Token.ASSIGN_DIV: case Token.ASSIGN_MOD: case Token.ASSIGN_LSH: case Token.ASSIGN_RSH: case Token.URSH: case Token.ASSIGN_BITAND: case Token.ASSIGN_BITXOR: case Token.ASSIGN_BITOR: type = "AssignmentExpression"; break; case Token.EQ: // Comparison Operators case Token.NE: case Token.SHEQ: case Token.SHNE: case Token.GT: case Token.GE: case Token.LT: case Token.LE: type = "BinaryExpression"; break; case Token.ADD: // Arithmetic Operators case Token.SUB: case Token.MUL: case Token.DIV: case Token.MOD: type = "BinaryExpression"; break; case Token.BITAND: // Bitwise Operators case Token.BITOR: case Token.BITXOR: case Token.LSH: case Token.RSH: type = "BinaryExpression"; break; case Token.AND: // Logical Operators case Token.OR: type = "Logical Expression"; break; default: type= "BinaryExpression"; break; } switch(this.getOperator()) { case Token.ASSIGN: // Assignment Operators operator = "="; break; case Token.ASSIGN_ADD: operator = "+="; break; case Token.ASSIGN_SUB: operator = "-="; break; case Token.ASSIGN_MUL: operator = "*="; break; case Token.ASSIGN_DIV: operator = "/="; break; case Token.ASSIGN_MOD: operator = "%="; break; case Token.ASSIGN_LSH: operator = "<<="; break; case Token.ASSIGN_RSH: operator = ">>="; break; case Token.URSH: operator = ">>>="; break; case Token.ASSIGN_BITAND: operator = "&="; break; case Token.ASSIGN_BITXOR: operator = "^="; break; case Token.ASSIGN_BITOR: operator = "|="; break; case Token.EQ: // Comparison Operators operator = "=="; break; case Token.NE: operator = "!="; break; case Token.SHEQ: operator = "==="; break; case Token.SHNE: operator = "!=="; break; case Token.GT: operator = ">"; break; case Token.GE: operator = ">="; break; case Token.LT: operator = "<"; break; case Token.LE: operator = "<="; break; case Token.MOD: // Arithmetic Operators operator = "%"; break; case Token.BITAND: // Bitwise Operators operator = "&"; break; case Token.BITOR: operator = "|"; break; case Token.BITXOR: operator = "^"; break; case Token.LSH: operator = "<<"; break; case Token.RSH: operator = ">>"; break; case Token.AND: // Logical Operators operator = "&&"; break; case Token.OR: type = "Logical Expression"; operator = "||"; break; default: operator = null; break; } return factory.createObjectBuilder() .add("type", type) .add("operator", operator) .add("change", changeType.toString()) .add("moved", String.valueOf(isMoved())).build(); } /** * Clones the AstNode. * @return The clone of the AstNode. * @throws CloneNotSupportedException */ @Override public AstNode clone(AstNode parent) { /* Get the shallow clone. */ InfixExpression clone = (InfixExpression)super.clone(); clone.setParent(parent); clone.changeType = this.changeType; clone.fixedPosition = this.fixedPosition; clone.ID = this.ID; /* Clone the children. */ AstNode left = this.getLeft().clone(clone); AstNode right = this.getRight().clone(clone); clone.setLeft(left); clone.setRight(right); return clone; } public void setLeftAndRight(AstNode left, AstNode right) { assertNotNull(left); assertNotNull(right); // compute our bounds while children have absolute positions int beg = left.getPosition(); int end = right.getPosition() + right.getLength(); setBounds(beg, end); // this updates their positions to be parent-relative setLeft(left); setRight(right); } /** * Returns operator token &ndash; alias for {@link #getType} */ public int getOperator() { return getType(); } /** * Sets operator token &ndash; like {@link #setType}, but throws * an exception if the operator is invalid. * @throws IllegalArgumentException if operator is not a valid token * code */ public void setOperator(int operator) { if (!Token.isValidToken(operator)) throw new IllegalArgumentException("Invalid token: " + operator); setType(operator); } /** * Returns the left-hand side of the expression */ public AstNode getLeft() { return left; } /** * Sets the left-hand side of the expression, and sets its * parent to this node. * @param left the left-hand side of the expression * @throws IllegalArgumentException} if left is {@code null} */ public void setLeft(AstNode left) { assertNotNull(left); this.left = left; // line number should agree with source position setLineno(left.getLineno()); left.setParent(this); } /** * Returns the right-hand side of the expression * @return the right-hand side. It's usually an * {@link AstNode} node, but can also be a {@link FunctionNode} * representing Function expressions. */ public AstNode getRight() { return right; } /** * Sets the right-hand side of the expression, and sets its parent to this * node. * @throws IllegalArgumentException} if right is {@code null} */ public void setRight(AstNode right) { assertNotNull(right); this.right = right; right.setParent(this); } /** * Returns relative offset of operator token */ public int getOperatorPosition() { return operatorPosition; } /** * Sets operator token's relative offset * @param operatorPosition offset in parent of operator token */ public void setOperatorPosition(int operatorPosition) { this.operatorPosition = operatorPosition; } @Override public boolean hasSideEffects() { // the null-checks are for malformed expressions in IDE-mode switch (getType()) { case Token.COMMA: return right != null && right.hasSideEffects(); case Token.AND: case Token.OR: return left != null && left.hasSideEffects() || (right != null && right.hasSideEffects()); default: return super.hasSideEffects(); } } @Override public String toSource(int depth) { StringBuilder sb = new StringBuilder(); sb.append(makeIndent(depth)); sb.append(left.toSource()); sb.append(" "); sb.append(operatorToString(getType())); sb.append(" "); sb.append(right.toSource()); return sb.toString(); } /** * Visits this node, the left operand, and the right operand. */ @Override public void visit(NodeVisitor v) { if (v.visit(this)) { left.visit(v); right.visit(v); } } @Override public boolean isStatement() { return false; } }
src/org/mozilla/javascript/ast/InfixExpression.java
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.javascript.ast; import javax.json.Json; import javax.json.JsonBuilderFactory; import javax.json.JsonObject; import org.mozilla.javascript.Token; /** * AST node representing an infix (binary operator) expression. * The operator is the node's {@link Token} type. */ public class InfixExpression extends AstNode { protected AstNode left; protected AstNode right; protected int operatorPosition = -1; public InfixExpression() { } public InfixExpression(int pos) { super(pos); } public InfixExpression(int pos, int len) { super(pos, len); } public InfixExpression(int pos, int len, AstNode left, AstNode right) { super(pos, len); setLeft(left); setRight(right); } /** * Constructs a new {@code InfixExpression}. Updates bounds to include * left and right nodes. */ public InfixExpression(AstNode left, AstNode right) { setLeftAndRight(left, right); } /** * Constructs a new {@code InfixExpression}. * @param operatorPos the <em>absolute</em> position of the operator */ public InfixExpression(int operator, AstNode left, AstNode right, int operatorPos) { setType(operator); setOperatorPosition(operatorPos - left.getPosition()); setLeftAndRight(left, right); } /** * @return This node as a JSON object in Esprima format. * @author qhanam */ @Override public JsonObject getJsonObject() { JsonBuilderFactory factory = Json.createBuilderFactory(null); String type = null; String operator = null; switch(this.getOperator()) { case Token.ASSIGN: // Assignment Operators case Token.ASSIGN_ADD: case Token.ASSIGN_SUB: case Token.ASSIGN_MUL: case Token.ASSIGN_DIV: case Token.ASSIGN_MOD: case Token.ASSIGN_LSH: case Token.ASSIGN_RSH: case Token.URSH: case Token.ASSIGN_BITAND: case Token.ASSIGN_BITXOR: case Token.ASSIGN_BITOR: type = "AssignmentExpression"; break; case Token.EQ: // Comparison Operators case Token.NE: case Token.SHEQ: case Token.SHNE: case Token.GT: case Token.GE: case Token.LT: case Token.LE: type = "BinaryExpression"; break; case Token.MOD: // Arithmetic Operators type = "BinaryExpression"; break; case Token.BITAND: // Bitwise Operators case Token.BITOR: case Token.BITXOR: case Token.LSH: case Token.RSH: type = "BinaryExpression"; break; case Token.AND: // Logical Operators case Token.OR: type = "Logical Expression"; break; default: type= "BinaryExpression"; break; } switch(this.getOperator()) { case Token.ASSIGN: // Assignment Operators operator = "="; break; case Token.ASSIGN_ADD: operator = "+="; break; case Token.ASSIGN_SUB: operator = "-="; break; case Token.ASSIGN_MUL: operator = "*="; break; case Token.ASSIGN_DIV: operator = "/="; break; case Token.ASSIGN_MOD: operator = "%="; break; case Token.ASSIGN_LSH: operator = "<<="; break; case Token.ASSIGN_RSH: operator = ">>="; break; case Token.URSH: operator = ">>>="; break; case Token.ASSIGN_BITAND: operator = "&="; break; case Token.ASSIGN_BITXOR: operator = "^="; break; case Token.ASSIGN_BITOR: operator = "|="; break; case Token.EQ: // Comparison Operators operator = "=="; break; case Token.NE: operator = "!="; break; case Token.SHEQ: operator = "==="; break; case Token.SHNE: operator = "!=="; break; case Token.GT: operator = ">"; break; case Token.GE: operator = ">="; break; case Token.LT: operator = "<"; break; case Token.LE: operator = "<="; break; case Token.MOD: // Arithmetic Operators operator = "%"; break; case Token.BITAND: // Bitwise Operators operator = "&"; break; case Token.BITOR: operator = "|"; break; case Token.BITXOR: operator = "^"; break; case Token.LSH: operator = "<<"; break; case Token.RSH: operator = ">>"; break; case Token.AND: // Logical Operators operator = "&&"; break; case Token.OR: type = "Logical Expression"; operator = "||"; break; default: operator = null; break; } return factory.createObjectBuilder() .add("type", type) .add("operator", operator) .add("change", changeType.toString()) .add("moved", String.valueOf(isMoved())).build(); } /** * Clones the AstNode. * @return The clone of the AstNode. * @throws CloneNotSupportedException */ @Override public AstNode clone(AstNode parent) { /* Get the shallow clone. */ InfixExpression clone = (InfixExpression)super.clone(); clone.setParent(parent); clone.changeType = this.changeType; clone.fixedPosition = this.fixedPosition; clone.ID = this.ID; /* Clone the children. */ AstNode left = this.getLeft().clone(clone); AstNode right = this.getRight().clone(clone); clone.setLeft(left); clone.setRight(right); return clone; } public void setLeftAndRight(AstNode left, AstNode right) { assertNotNull(left); assertNotNull(right); // compute our bounds while children have absolute positions int beg = left.getPosition(); int end = right.getPosition() + right.getLength(); setBounds(beg, end); // this updates their positions to be parent-relative setLeft(left); setRight(right); } /** * Returns operator token &ndash; alias for {@link #getType} */ public int getOperator() { return getType(); } /** * Sets operator token &ndash; like {@link #setType}, but throws * an exception if the operator is invalid. * @throws IllegalArgumentException if operator is not a valid token * code */ public void setOperator(int operator) { if (!Token.isValidToken(operator)) throw new IllegalArgumentException("Invalid token: " + operator); setType(operator); } /** * Returns the left-hand side of the expression */ public AstNode getLeft() { return left; } /** * Sets the left-hand side of the expression, and sets its * parent to this node. * @param left the left-hand side of the expression * @throws IllegalArgumentException} if left is {@code null} */ public void setLeft(AstNode left) { assertNotNull(left); this.left = left; // line number should agree with source position setLineno(left.getLineno()); left.setParent(this); } /** * Returns the right-hand side of the expression * @return the right-hand side. It's usually an * {@link AstNode} node, but can also be a {@link FunctionNode} * representing Function expressions. */ public AstNode getRight() { return right; } /** * Sets the right-hand side of the expression, and sets its parent to this * node. * @throws IllegalArgumentException} if right is {@code null} */ public void setRight(AstNode right) { assertNotNull(right); this.right = right; right.setParent(this); } /** * Returns relative offset of operator token */ public int getOperatorPosition() { return operatorPosition; } /** * Sets operator token's relative offset * @param operatorPosition offset in parent of operator token */ public void setOperatorPosition(int operatorPosition) { this.operatorPosition = operatorPosition; } @Override public boolean hasSideEffects() { // the null-checks are for malformed expressions in IDE-mode switch (getType()) { case Token.COMMA: return right != null && right.hasSideEffects(); case Token.AND: case Token.OR: return left != null && left.hasSideEffects() || (right != null && right.hasSideEffects()); default: return super.hasSideEffects(); } } @Override public String toSource(int depth) { StringBuilder sb = new StringBuilder(); sb.append(makeIndent(depth)); sb.append(left.toSource()); sb.append(" "); sb.append(operatorToString(getType())); sb.append(" "); sb.append(right.toSource()); return sb.toString(); } /** * Visits this node, the left operand, and the right operand. */ @Override public void visit(NodeVisitor v) { if (v.visit(this)) { left.visit(v); right.visit(v); } } @Override public boolean isStatement() { return false; } }
add missing operators to exprima json builder
src/org/mozilla/javascript/ast/InfixExpression.java
add missing operators to exprima json builder
<ide><path>rc/org/mozilla/javascript/ast/InfixExpression.java <ide> case Token.LE: <ide> type = "BinaryExpression"; <ide> break; <del> case Token.MOD: // Arithmetic Operators <add> case Token.ADD: // Arithmetic Operators <add> case Token.SUB: <add> case Token.MUL: <add> case Token.DIV: <add> case Token.MOD: <ide> type = "BinaryExpression"; <ide> break; <ide> case Token.BITAND: // Bitwise Operators
Java
mit
006a1d3fb32e36e3fad43765b8d5a0a657a3f66e
0
DoctorQ/jenkins,amruthsoft9/Jenkis,kohsuke/hudson,christ66/jenkins,ns163/jenkins,goldchang/jenkins,aduprat/jenkins,akshayabd/jenkins,protazy/jenkins,6WIND/jenkins,olivergondza/jenkins,ajshastri/jenkins,daniel-beck/jenkins,guoxu0514/jenkins,amuniz/jenkins,deadmoose/jenkins,paulmillar/jenkins,everyonce/jenkins,bpzhang/jenkins,huybrechts/hudson,yonglehou/jenkins,gorcz/jenkins,MadsNielsen/jtemp,escoem/jenkins,hashar/jenkins,jk47/jenkins,jcsirot/jenkins,rashmikanta-1984/jenkins,jpederzolli/jenkins-1,AustinKwang/jenkins,yonglehou/jenkins,noikiy/jenkins,evernat/jenkins,chbiel/jenkins,recena/jenkins,iqstack/jenkins,lvotypko/jenkins,mrobinet/jenkins,jtnord/jenkins,AustinKwang/jenkins,verbitan/jenkins,hashar/jenkins,verbitan/jenkins,ikedam/jenkins,Ykus/jenkins,1and1/jenkins,AustinKwang/jenkins,wuwen5/jenkins,vjuranek/jenkins,liorhson/jenkins,lindzh/jenkins,h4ck3rm1k3/jenkins,svanoort/jenkins,SebastienGllmt/jenkins,tfennelly/jenkins,azweb76/jenkins,aheritier/jenkins,jpbriend/jenkins,thomassuckow/jenkins,luoqii/jenkins,ydubreuil/jenkins,albers/jenkins,andresrc/jenkins,luoqii/jenkins,DanielWeber/jenkins,arcivanov/jenkins,guoxu0514/jenkins,1and1/jenkins,CodeShane/jenkins,csimons/jenkins,patbos/jenkins,hashar/jenkins,dariver/jenkins,shahharsh/jenkins,lilyJi/jenkins,oleg-nenashev/jenkins,wuwen5/jenkins,chbiel/jenkins,evernat/jenkins,lvotypko/jenkins,elkingtonmcb/jenkins,thomassuckow/jenkins,guoxu0514/jenkins,github-api-test-org/jenkins,luoqii/jenkins,rlugojr/jenkins,seanlin816/jenkins,arcivanov/jenkins,fbelzunc/jenkins,kohsuke/hudson,csimons/jenkins,SenolOzer/jenkins,SebastienGllmt/jenkins,dariver/jenkins,ikedam/jenkins,hashar/jenkins,Ykus/jenkins,keyurpatankar/hudson,jpbriend/jenkins,goldchang/jenkins,damianszczepanik/jenkins,viqueen/jenkins,aheritier/jenkins,gusreiber/jenkins,SenolOzer/jenkins,Ykus/jenkins,noikiy/jenkins,albers/jenkins,svanoort/jenkins,akshayabd/jenkins,rsandell/jenkins,mrooney/jenkins,msrb/jenkins,MichaelPranovich/jenkins_sc,lvotypko/jenkins,andresrc/jenkins,paulwellnerbou/jenkins,AustinKwang/jenkins,viqueen/jenkins,daspilker/jenkins,albers/jenkins,jtnord/jenkins,stephenc/jenkins,maikeffi/hudson,Jimilian/jenkins,gitaccountforprashant/gittest,jhoblitt/jenkins,hplatou/jenkins,patbos/jenkins,jpederzolli/jenkins-1,daspilker/jenkins,singh88/jenkins,oleg-nenashev/jenkins,patbos/jenkins,jglick/jenkins,shahharsh/jenkins,SebastienGllmt/jenkins,Jochen-A-Fuerbacher/jenkins,jpederzolli/jenkins-1,verbitan/jenkins,keyurpatankar/hudson,paulwellnerbou/jenkins,MadsNielsen/jtemp,FarmGeek4Life/jenkins,dbroady1/jenkins,mcanthony/jenkins,dariver/jenkins,bpzhang/jenkins,ajshastri/jenkins,tastatur/jenkins,Jimilian/jenkins,rsandell/jenkins,jpederzolli/jenkins-1,DanielWeber/jenkins,Krasnyanskiy/jenkins,vjuranek/jenkins,liupugong/jenkins,Ykus/jenkins,lindzh/jenkins,KostyaSha/jenkins,lilyJi/jenkins,kohsuke/hudson,elkingtonmcb/jenkins,viqueen/jenkins,MichaelPranovich/jenkins_sc,lvotypko/jenkins2,intelchen/jenkins,jzjzjzj/jenkins,samatdav/jenkins,vvv444/jenkins,liupugong/jenkins,goldchang/jenkins,h4ck3rm1k3/jenkins,christ66/jenkins,viqueen/jenkins,gitaccountforprashant/gittest,FarmGeek4Life/jenkins,mrooney/jenkins,aquarellian/jenkins,daniel-beck/jenkins,arcivanov/jenkins,petermarcoen/jenkins,evernat/jenkins,tangkun75/jenkins,batmat/jenkins,wuwen5/jenkins,lindzh/jenkins,hplatou/jenkins,liupugong/jenkins,liorhson/jenkins,1and1/jenkins,arcivanov/jenkins,Jimilian/jenkins,aduprat/jenkins,bpzhang/jenkins,scoheb/jenkins,DoctorQ/jenkins,vijayto/jenkins,jpbriend/jenkins,godfath3r/jenkins,hemantojhaa/jenkins,jcarrothers-sap/jenkins,sathiya-mit/jenkins,rashmikanta-1984/jenkins,luoqii/jenkins,goldchang/jenkins,gorcz/jenkins,vijayto/jenkins,seanlin816/jenkins,hplatou/jenkins,vlajos/jenkins,6WIND/jenkins,goldchang/jenkins,amuniz/jenkins,olivergondza/jenkins,akshayabd/jenkins,jenkinsci/jenkins,KostyaSha/jenkins,gorcz/jenkins,singh88/jenkins,292388900/jenkins,amuniz/jenkins,maikeffi/hudson,hplatou/jenkins,rlugojr/jenkins,jtnord/jenkins,kzantow/jenkins,synopsys-arc-oss/jenkins,olivergondza/jenkins,github-api-test-org/jenkins,lvotypko/jenkins3,lvotypko/jenkins2,6WIND/jenkins,mpeltonen/jenkins,thomassuckow/jenkins,jcsirot/jenkins,iqstack/jenkins,olivergondza/jenkins,FTG-003/jenkins,wangyikai/jenkins,v1v/jenkins,KostyaSha/jenkins,noikiy/jenkins,intelchen/jenkins,bkmeneguello/jenkins,fbelzunc/jenkins,AustinKwang/jenkins,protazy/jenkins,h4ck3rm1k3/jenkins,pselle/jenkins,msrb/jenkins,pjanouse/jenkins,MarkEWaite/jenkins,stephenc/jenkins,azweb76/jenkins,khmarbaise/jenkins,rashmikanta-1984/jenkins,tastatur/jenkins,FTG-003/jenkins,wangyikai/jenkins,maikeffi/hudson,noikiy/jenkins,jglick/jenkins,kohsuke/hudson,sathiya-mit/jenkins,nandan4/Jenkins,kohsuke/hudson,csimons/jenkins,bkmeneguello/jenkins,abayer/jenkins,keyurpatankar/hudson,liorhson/jenkins,jcsirot/jenkins,luoqii/jenkins,h4ck3rm1k3/jenkins,alvarolobato/jenkins,kzantow/jenkins,ns163/jenkins,ydubreuil/jenkins,godfath3r/jenkins,brunocvcunha/jenkins,paulmillar/jenkins,ndeloof/jenkins,Ykus/jenkins,vlajos/jenkins,Krasnyanskiy/jenkins,ErikVerheul/jenkins,escoem/jenkins,my7seven/jenkins,escoem/jenkins,patbos/jenkins,Wilfred/jenkins,kohsuke/hudson,hashar/jenkins,ErikVerheul/jenkins,maikeffi/hudson,thomassuckow/jenkins,Wilfred/jenkins,scoheb/jenkins,everyonce/jenkins,jpbriend/jenkins,gorcz/jenkins,varmenise/jenkins,protazy/jenkins,jk47/jenkins,vlajos/jenkins,aduprat/jenkins,escoem/jenkins,lvotypko/jenkins2,andresrc/jenkins,damianszczepanik/jenkins,Ykus/jenkins,tfennelly/jenkins,tangkun75/jenkins,mdonohue/jenkins,singh88/jenkins,recena/jenkins,verbitan/jenkins,amruthsoft9/Jenkis,aduprat/jenkins,everyonce/jenkins,pselle/jenkins,shahharsh/jenkins,1and1/jenkins,maikeffi/hudson,jk47/jenkins,jpbriend/jenkins,tastatur/jenkins,damianszczepanik/jenkins,jglick/jenkins,gusreiber/jenkins,batmat/jenkins,pjanouse/jenkins,deadmoose/jenkins,CodeShane/jenkins,ndeloof/jenkins,intelchen/jenkins,chbiel/jenkins,NehemiahMi/jenkins,jglick/jenkins,nandan4/Jenkins,SenolOzer/jenkins,soenter/jenkins,deadmoose/jenkins,jcarrothers-sap/jenkins,pselle/jenkins,paulmillar/jenkins,dennisjlee/jenkins,Jochen-A-Fuerbacher/jenkins,Vlatombe/jenkins,lvotypko/jenkins2,petermarcoen/jenkins,nandan4/Jenkins,lvotypko/jenkins3,rashmikanta-1984/jenkins,liorhson/jenkins,MarkEWaite/jenkins,github-api-test-org/jenkins,maikeffi/hudson,evernat/jenkins,duzifang/my-jenkins,tastatur/jenkins,MichaelPranovich/jenkins_sc,daniel-beck/jenkins,ns163/jenkins,dbroady1/jenkins,msrb/jenkins,pjanouse/jenkins,kzantow/jenkins,vjuranek/jenkins,intelchen/jenkins,jcarrothers-sap/jenkins,rsandell/jenkins,csimons/jenkins,keyurpatankar/hudson,DoctorQ/jenkins,intelchen/jenkins,soenter/jenkins,jzjzjzj/jenkins,tastatur/jenkins,jenkinsci/jenkins,daniel-beck/jenkins,aldaris/jenkins,NehemiahMi/jenkins,guoxu0514/jenkins,MarkEWaite/jenkins,ErikVerheul/jenkins,huybrechts/hudson,NehemiahMi/jenkins,v1v/jenkins,jhoblitt/jenkins,andresrc/jenkins,kohsuke/hudson,vvv444/jenkins,luoqii/jenkins,lvotypko/jenkins,vlajos/jenkins,lindzh/jenkins,aldaris/jenkins,CodeShane/jenkins,NehemiahMi/jenkins,varmenise/jenkins,aquarellian/jenkins,Jochen-A-Fuerbacher/jenkins,Jimilian/jenkins,soenter/jenkins,gorcz/jenkins,csimons/jenkins,lvotypko/jenkins3,vvv444/jenkins,lvotypko/jenkins3,batmat/jenkins,tangkun75/jenkins,akshayabd/jenkins,evernat/jenkins,jpbriend/jenkins,v1v/jenkins,MichaelPranovich/jenkins_sc,vijayto/jenkins,arunsingh/jenkins,aheritier/jenkins,noikiy/jenkins,oleg-nenashev/jenkins,MadsNielsen/jtemp,jpederzolli/jenkins-1,bkmeneguello/jenkins,synopsys-arc-oss/jenkins,duzifang/my-jenkins,jzjzjzj/jenkins,jcarrothers-sap/jenkins,petermarcoen/jenkins,recena/jenkins,ChrisA89/jenkins,jk47/jenkins,abayer/jenkins,huybrechts/hudson,v1v/jenkins,ns163/jenkins,samatdav/jenkins,kzantow/jenkins,wangyikai/jenkins,aheritier/jenkins,mattclark/jenkins,mdonohue/jenkins,mpeltonen/jenkins,khmarbaise/jenkins,lindzh/jenkins,DoctorQ/jenkins,synopsys-arc-oss/jenkins,MichaelPranovich/jenkins_sc,christ66/jenkins,bkmeneguello/jenkins,1and1/jenkins,my7seven/jenkins,yonglehou/jenkins,gusreiber/jenkins,tastatur/jenkins,kzantow/jenkins,nandan4/Jenkins,alvarolobato/jenkins,huybrechts/hudson,DoctorQ/jenkins,DanielWeber/jenkins,Wilfred/jenkins,verbitan/jenkins,brunocvcunha/jenkins,hplatou/jenkins,6WIND/jenkins,lordofthejars/jenkins,DanielWeber/jenkins,brunocvcunha/jenkins,vvv444/jenkins,singh88/jenkins,daniel-beck/jenkins,duzifang/my-jenkins,albers/jenkins,daspilker/jenkins,jpederzolli/jenkins-1,everyonce/jenkins,ErikVerheul/jenkins,amruthsoft9/Jenkis,dbroady1/jenkins,github-api-test-org/jenkins,morficus/jenkins,SebastienGllmt/jenkins,SebastienGllmt/jenkins,my7seven/jenkins,Vlatombe/jenkins,lvotypko/jenkins2,tangkun75/jenkins,shahharsh/jenkins,mcanthony/jenkins,thomassuckow/jenkins,paulwellnerbou/jenkins,kzantow/jenkins,jzjzjzj/jenkins,sathiya-mit/jenkins,goldchang/jenkins,mdonohue/jenkins,escoem/jenkins,my7seven/jenkins,stephenc/jenkins,elkingtonmcb/jenkins,lordofthejars/jenkins,ikedam/jenkins,lordofthejars/jenkins,tfennelly/jenkins,vijayto/jenkins,gusreiber/jenkins,liorhson/jenkins,jcsirot/jenkins,hemantojhaa/jenkins,mdonohue/jenkins,rsandell/jenkins,jcarrothers-sap/jenkins,azweb76/jenkins,synopsys-arc-oss/jenkins,CodeShane/jenkins,Wilfred/jenkins,tfennelly/jenkins,arunsingh/jenkins,bpzhang/jenkins,aduprat/jenkins,jenkinsci/jenkins,amuniz/jenkins,brunocvcunha/jenkins,lvotypko/jenkins3,mrooney/jenkins,jpbriend/jenkins,iqstack/jenkins,kohsuke/hudson,hashar/jenkins,mpeltonen/jenkins,svanoort/jenkins,mrobinet/jenkins,NehemiahMi/jenkins,scoheb/jenkins,FarmGeek4Life/jenkins,morficus/jenkins,daniel-beck/jenkins,Vlatombe/jenkins,sathiya-mit/jenkins,elkingtonmcb/jenkins,ErikVerheul/jenkins,mpeltonen/jenkins,maikeffi/hudson,vjuranek/jenkins,morficus/jenkins,amuniz/jenkins,damianszczepanik/jenkins,KostyaSha/jenkins,mattclark/jenkins,jenkinsci/jenkins,bpzhang/jenkins,lordofthejars/jenkins,gusreiber/jenkins,iqstack/jenkins,292388900/jenkins,iqstack/jenkins,pselle/jenkins,ydubreuil/jenkins,rlugojr/jenkins,ydubreuil/jenkins,wuwen5/jenkins,dariver/jenkins,jpederzolli/jenkins-1,brunocvcunha/jenkins,KostyaSha/jenkins,huybrechts/hudson,kzantow/jenkins,Vlatombe/jenkins,Jochen-A-Fuerbacher/jenkins,msrb/jenkins,ChrisA89/jenkins,daspilker/jenkins,oleg-nenashev/jenkins,khmarbaise/jenkins,ChrisA89/jenkins,jglick/jenkins,my7seven/jenkins,tastatur/jenkins,arcivanov/jenkins,jenkinsci/jenkins,lilyJi/jenkins,mrobinet/jenkins,MarkEWaite/jenkins,singh88/jenkins,samatdav/jenkins,mcanthony/jenkins,MarkEWaite/jenkins,NehemiahMi/jenkins,lvotypko/jenkins3,Krasnyanskiy/jenkins,rashmikanta-1984/jenkins,arunsingh/jenkins,jglick/jenkins,intelchen/jenkins,tfennelly/jenkins,FarmGeek4Life/jenkins,jk47/jenkins,arunsingh/jenkins,aquarellian/jenkins,olivergondza/jenkins,ndeloof/jenkins,my7seven/jenkins,ns163/jenkins,paulwellnerbou/jenkins,morficus/jenkins,ikedam/jenkins,seanlin816/jenkins,my7seven/jenkins,292388900/jenkins,albers/jenkins,luoqii/jenkins,aheritier/jenkins,Jochen-A-Fuerbacher/jenkins,pjanouse/jenkins,lilyJi/jenkins,batmat/jenkins,292388900/jenkins,chbiel/jenkins,sathiya-mit/jenkins,jtnord/jenkins,FTG-003/jenkins,protazy/jenkins,azweb76/jenkins,bpzhang/jenkins,aldaris/jenkins,mcanthony/jenkins,azweb76/jenkins,vvv444/jenkins,patbos/jenkins,DanielWeber/jenkins,aheritier/jenkins,sathiya-mit/jenkins,amruthsoft9/Jenkis,aldaris/jenkins,brunocvcunha/jenkins,varmenise/jenkins,khmarbaise/jenkins,MarkEWaite/jenkins,ydubreuil/jenkins,damianszczepanik/jenkins,stephenc/jenkins,yonglehou/jenkins,MadsNielsen/jtemp,jenkinsci/jenkins,deadmoose/jenkins,lvotypko/jenkins3,dennisjlee/jenkins,ChrisA89/jenkins,KostyaSha/jenkins,daniel-beck/jenkins,KostyaSha/jenkins,FTG-003/jenkins,stephenc/jenkins,maikeffi/hudson,jzjzjzj/jenkins,aldaris/jenkins,dbroady1/jenkins,amuniz/jenkins,noikiy/jenkins,Vlatombe/jenkins,huybrechts/hudson,mattclark/jenkins,Jimilian/jenkins,mdonohue/jenkins,paulmillar/jenkins,damianszczepanik/jenkins,pselle/jenkins,ErikVerheul/jenkins,tangkun75/jenkins,gitaccountforprashant/gittest,msrb/jenkins,lindzh/jenkins,gorcz/jenkins,sathiya-mit/jenkins,gusreiber/jenkins,amruthsoft9/Jenkis,github-api-test-org/jenkins,jenkinsci/jenkins,lvotypko/jenkins,Jimilian/jenkins,mrobinet/jenkins,jtnord/jenkins,albers/jenkins,andresrc/jenkins,elkingtonmcb/jenkins,DanielWeber/jenkins,Jochen-A-Fuerbacher/jenkins,gitaccountforprashant/gittest,andresrc/jenkins,evernat/jenkins,Krasnyanskiy/jenkins,scoheb/jenkins,elkingtonmcb/jenkins,nandan4/Jenkins,mpeltonen/jenkins,SebastienGllmt/jenkins,mrobinet/jenkins,gorcz/jenkins,everyonce/jenkins,FarmGeek4Life/jenkins,rsandell/jenkins,Wilfred/jenkins,wuwen5/jenkins,MadsNielsen/jtemp,csimons/jenkins,Wilfred/jenkins,wuwen5/jenkins,jhoblitt/jenkins,gitaccountforprashant/gittest,shahharsh/jenkins,recena/jenkins,paulwellnerbou/jenkins,Ykus/jenkins,samatdav/jenkins,lilyJi/jenkins,seanlin816/jenkins,lvotypko/jenkins2,soenter/jenkins,paulmillar/jenkins,keyurpatankar/hudson,amruthsoft9/Jenkis,ikedam/jenkins,292388900/jenkins,andresrc/jenkins,aheritier/jenkins,nandan4/Jenkins,ajshastri/jenkins,mrobinet/jenkins,viqueen/jenkins,thomassuckow/jenkins,rlugojr/jenkins,KostyaSha/jenkins,csimons/jenkins,jcsirot/jenkins,AustinKwang/jenkins,Krasnyanskiy/jenkins,petermarcoen/jenkins,aquarellian/jenkins,batmat/jenkins,aquarellian/jenkins,jenkinsci/jenkins,varmenise/jenkins,DoctorQ/jenkins,duzifang/my-jenkins,tfennelly/jenkins,wangyikai/jenkins,soenter/jenkins,SenolOzer/jenkins,duzifang/my-jenkins,gorcz/jenkins,msrb/jenkins,synopsys-arc-oss/jenkins,rlugojr/jenkins,akshayabd/jenkins,scoheb/jenkins,ns163/jenkins,tfennelly/jenkins,petermarcoen/jenkins,bkmeneguello/jenkins,abayer/jenkins,mattclark/jenkins,protazy/jenkins,azweb76/jenkins,liupugong/jenkins,christ66/jenkins,wangyikai/jenkins,dariver/jenkins,mattclark/jenkins,iqstack/jenkins,akshayabd/jenkins,v1v/jenkins,albers/jenkins,pjanouse/jenkins,liupugong/jenkins,hemantojhaa/jenkins,stephenc/jenkins,verbitan/jenkins,SenolOzer/jenkins,mdonohue/jenkins,keyurpatankar/hudson,pselle/jenkins,amruthsoft9/Jenkis,jhoblitt/jenkins,petermarcoen/jenkins,dbroady1/jenkins,damianszczepanik/jenkins,msrb/jenkins,alvarolobato/jenkins,keyurpatankar/hudson,guoxu0514/jenkins,Vlatombe/jenkins,ndeloof/jenkins,fbelzunc/jenkins,MadsNielsen/jtemp,scoheb/jenkins,azweb76/jenkins,yonglehou/jenkins,nandan4/Jenkins,stephenc/jenkins,aquarellian/jenkins,lindzh/jenkins,arunsingh/jenkins,dbroady1/jenkins,olivergondza/jenkins,liupugong/jenkins,NehemiahMi/jenkins,samatdav/jenkins,jcsirot/jenkins,mrooney/jenkins,hemantojhaa/jenkins,6WIND/jenkins,MarkEWaite/jenkins,christ66/jenkins,samatdav/jenkins,yonglehou/jenkins,MichaelPranovich/jenkins_sc,everyonce/jenkins,ErikVerheul/jenkins,shahharsh/jenkins,rsandell/jenkins,Krasnyanskiy/jenkins,christ66/jenkins,varmenise/jenkins,fbelzunc/jenkins,verbitan/jenkins,ajshastri/jenkins,christ66/jenkins,elkingtonmcb/jenkins,mdonohue/jenkins,morficus/jenkins,jhoblitt/jenkins,ydubreuil/jenkins,jcarrothers-sap/jenkins,yonglehou/jenkins,soenter/jenkins,MarkEWaite/jenkins,mrooney/jenkins,recena/jenkins,amuniz/jenkins,godfath3r/jenkins,oleg-nenashev/jenkins,vjuranek/jenkins,paulwellnerbou/jenkins,hplatou/jenkins,h4ck3rm1k3/jenkins,huybrechts/hudson,viqueen/jenkins,dariver/jenkins,mpeltonen/jenkins,ydubreuil/jenkins,chbiel/jenkins,Jimilian/jenkins,dennisjlee/jenkins,dariver/jenkins,alvarolobato/jenkins,escoem/jenkins,alvarolobato/jenkins,everyonce/jenkins,FTG-003/jenkins,lordofthejars/jenkins,recena/jenkins,batmat/jenkins,rsandell/jenkins,khmarbaise/jenkins,oleg-nenashev/jenkins,liorhson/jenkins,jcarrothers-sap/jenkins,abayer/jenkins,SebastienGllmt/jenkins,oleg-nenashev/jenkins,lvotypko/jenkins,goldchang/jenkins,intelchen/jenkins,MadsNielsen/jtemp,fbelzunc/jenkins,olivergondza/jenkins,bpzhang/jenkins,iqstack/jenkins,khmarbaise/jenkins,jcsirot/jenkins,protazy/jenkins,synopsys-arc-oss/jenkins,daniel-beck/jenkins,patbos/jenkins,ikedam/jenkins,rlugojr/jenkins,pjanouse/jenkins,292388900/jenkins,bkmeneguello/jenkins,abayer/jenkins,svanoort/jenkins,292388900/jenkins,mpeltonen/jenkins,chbiel/jenkins,jglick/jenkins,arunsingh/jenkins,aldaris/jenkins,gitaccountforprashant/gittest,soenter/jenkins,scoheb/jenkins,ndeloof/jenkins,bkmeneguello/jenkins,dbroady1/jenkins,Krasnyanskiy/jenkins,jzjzjzj/jenkins,SenolOzer/jenkins,ikedam/jenkins,guoxu0514/jenkins,deadmoose/jenkins,wangyikai/jenkins,arcivanov/jenkins,vijayto/jenkins,mattclark/jenkins,ikedam/jenkins,wangyikai/jenkins,tangkun75/jenkins,vijayto/jenkins,seanlin816/jenkins,akshayabd/jenkins,hemantojhaa/jenkins,arunsingh/jenkins,thomassuckow/jenkins,godfath3r/jenkins,abayer/jenkins,chbiel/jenkins,lvotypko/jenkins2,h4ck3rm1k3/jenkins,Jochen-A-Fuerbacher/jenkins,daspilker/jenkins,jcarrothers-sap/jenkins,6WIND/jenkins,1and1/jenkins,AustinKwang/jenkins,Vlatombe/jenkins,viqueen/jenkins,CodeShane/jenkins,godfath3r/jenkins,hemantojhaa/jenkins,goldchang/jenkins,vlajos/jenkins,duzifang/my-jenkins,rsandell/jenkins,dennisjlee/jenkins,ns163/jenkins,godfath3r/jenkins,jzjzjzj/jenkins,v1v/jenkins,svanoort/jenkins,lordofthejars/jenkins,svanoort/jenkins,daspilker/jenkins,rashmikanta-1984/jenkins,vlajos/jenkins,mrobinet/jenkins,vvv444/jenkins,jtnord/jenkins,vjuranek/jenkins,alvarolobato/jenkins,batmat/jenkins,FarmGeek4Life/jenkins,recena/jenkins,escoem/jenkins,ChrisA89/jenkins,FTG-003/jenkins,dennisjlee/jenkins,vjuranek/jenkins,khmarbaise/jenkins,guoxu0514/jenkins,DanielWeber/jenkins,godfath3r/jenkins,jhoblitt/jenkins,duzifang/my-jenkins,github-api-test-org/jenkins,jk47/jenkins,lvotypko/jenkins,tangkun75/jenkins,mcanthony/jenkins,varmenise/jenkins,mrooney/jenkins,mattclark/jenkins,jtnord/jenkins,deadmoose/jenkins,seanlin816/jenkins,mcanthony/jenkins,petermarcoen/jenkins,DoctorQ/jenkins,aduprat/jenkins,DoctorQ/jenkins,ajshastri/jenkins,noikiy/jenkins,daspilker/jenkins,aldaris/jenkins,singh88/jenkins,dennisjlee/jenkins,hplatou/jenkins,hashar/jenkins,FarmGeek4Life/jenkins,h4ck3rm1k3/jenkins,evernat/jenkins,rashmikanta-1984/jenkins,jzjzjzj/jenkins,arcivanov/jenkins,aquarellian/jenkins,varmenise/jenkins,samatdav/jenkins,6WIND/jenkins,shahharsh/jenkins,lordofthejars/jenkins,SenolOzer/jenkins,svanoort/jenkins,mrooney/jenkins,ajshastri/jenkins,paulmillar/jenkins,FTG-003/jenkins,abayer/jenkins,mcanthony/jenkins,deadmoose/jenkins,hemantojhaa/jenkins,protazy/jenkins,brunocvcunha/jenkins,v1v/jenkins,damianszczepanik/jenkins,github-api-test-org/jenkins,jhoblitt/jenkins,lilyJi/jenkins,morficus/jenkins,synopsys-arc-oss/jenkins,vvv444/jenkins,fbelzunc/jenkins,wuwen5/jenkins,alvarolobato/jenkins,pjanouse/jenkins,vlajos/jenkins,keyurpatankar/hudson,aduprat/jenkins,paulwellnerbou/jenkins,gusreiber/jenkins,rlugojr/jenkins,paulmillar/jenkins,1and1/jenkins,singh88/jenkins,vijayto/jenkins,ndeloof/jenkins,ChrisA89/jenkins,github-api-test-org/jenkins,liupugong/jenkins,lilyJi/jenkins,ChrisA89/jenkins,CodeShane/jenkins,morficus/jenkins,liorhson/jenkins,jk47/jenkins,CodeShane/jenkins,dennisjlee/jenkins,pselle/jenkins,ndeloof/jenkins,MichaelPranovich/jenkins_sc,shahharsh/jenkins,fbelzunc/jenkins,Wilfred/jenkins,ajshastri/jenkins,patbos/jenkins,gitaccountforprashant/gittest,seanlin816/jenkins
package hudson.tools; import com.gargoylesoftware.htmlunit.html.HtmlForm; import com.gargoylesoftware.htmlunit.html.HtmlPage; import hudson.model.Descriptor; import hudson.model.DownloadService; import hudson.tools.JDKInstaller.DescriptorImpl; import org.jvnet.hudson.test.HudsonTestCase; import hudson.model.JDK; import hudson.model.FreeStyleProject; import hudson.model.FreeStyleBuild; import hudson.model.TaskListener; import hudson.tasks.Shell; import hudson.util.StreamTaskListener; import hudson.tools.JDKInstaller.Platform; import hudson.tools.JDKInstaller.CPU; import hudson.FilePath; import hudson.Functions; import hudson.Launcher.LocalLauncher; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays; import java.util.Properties; import java.util.logging.Logger; import org.jvnet.hudson.test.Bug; import org.xml.sax.SAXException; /** * @author Kohsuke Kawaguchi */ public class JDKInstallerTest extends HudsonTestCase { boolean old; @Override protected void setUp() throws Exception { super.setUp(); old = DownloadService.neverUpdate; DownloadService.neverUpdate = false; File f = new File(new File(System.getProperty("user.home")),".jenkins-ci.org"); if (!f.exists()) { LOGGER.warning(f+" doesn't exist. Skipping JDK installation tests"); } else { Properties prop = new Properties(); FileInputStream in = new FileInputStream(f); try { prop.load(in); String u = prop.getProperty("oracle.userName"); String p = prop.getProperty("oracle.password"); if (u==null || p==null) { LOGGER.warning(f+" doesn't contain oracle.userName and oracle.password. Skipping JDK installation tests."); } else { DescriptorImpl d = jenkins.getDescriptorByType(DescriptorImpl.class); d.doPostCredential(u,p); } } finally { in.close(); } } } @Override protected void tearDown() throws Exception { DownloadService.neverUpdate = old; super.tearDown(); } public void testEnterCredential() throws Exception { HtmlPage p = createWebClient().goTo("/descriptorByName/hudson.tools.JDKInstaller/enterCredential"); HtmlForm form = p.getFormByName("postCredential"); form.getInputByName("username").setValueAttribute("foo"); form.getInputByName("password").setValueAttribute("bar"); form.submit(null); DescriptorImpl d = jenkins.getDescriptorByType(DescriptorImpl.class); assertEquals("foo",d.getUsername()); assertEquals("bar",d.getPassword().getPlainText()); } /** * Tests the configuration round trip. */ public void testConfigRoundtrip() throws Exception { File tmp = env.temporaryDirectoryAllocator.allocate(); JDKInstaller installer = new JDKInstaller("jdk-6u13-oth-JPR@CDS-CDS_Developer", true); hudson.getJDKs().add(new JDK("test",tmp.getAbsolutePath(), Arrays.asList( new InstallSourceProperty(Arrays.<ToolInstaller>asList(installer))))); submit(new WebClient().goTo("configure").getFormByName("config")); JDK jdk = hudson.getJDK("test"); InstallSourceProperty isp = jdk.getProperties().get(InstallSourceProperty.class); assertEquals(1,isp.installers.size()); assertEqualBeans(installer,isp.installers.get(JDKInstaller.class),"id,acceptLicense"); } /** * Can we locate the bundles? */ public void testLocate() throws Exception { retrieveUpdateCenterData(); JDKInstaller i = new JDKInstaller("jdk-6u13-oth-JPR@CDS-CDS_Developer", true); StreamTaskListener listener = StreamTaskListener.fromStdout(); i.locate(listener, Platform.LINUX, CPU.i386); i.locate(listener, Platform.WINDOWS, CPU.amd64); i.locate(listener, Platform.SOLARIS, CPU.Sparc); } private void retrieveUpdateCenterData() throws IOException, SAXException { new WebClient().goTo("/"); // make sure data is loaded } /** * Tests the auto installation. */ public void testAutoInstallation6u13() throws Exception { doTestAutoInstallation("jdk-6u13-oth-JPR@CDS-CDS_Developer", "1.6.0_13-b03"); } @Bug(3989) public void testAutoInstallation142_17() throws Exception { doTestAutoInstallation("j2sdk-1.4.2_17-oth-JPR@CDS-CDS_Developer", "1.4.2_17-b06"); } /** * End-to-end installation test. */ private void doTestAutoInstallation(String id, String fullversion) throws Exception { // this is a really time consuming test, so only run it when we really want // if(!Boolean.getBoolean("hudson.sunTests")) // return; retrieveUpdateCenterData(); File tmp = env.temporaryDirectoryAllocator.allocate(); JDKInstaller installer = new JDKInstaller(id, true); JDK jdk = new JDK("test", tmp.getAbsolutePath(), Arrays.asList( new InstallSourceProperty(Arrays.<ToolInstaller>asList(installer)))); hudson.getJDKs().add(jdk); FreeStyleProject p = createFreeStyleProject(); p.setJDK(jdk); p.getBuildersList().add(new Shell("java -fullversion\necho $JAVA_HOME")); FreeStyleBuild b = buildAndAssertSuccess(p); @SuppressWarnings("deprecation") String log = b.getLog(); System.out.println(log); // make sure it runs with the JDK that just got installed assertTrue(log.contains(fullversion)); assertTrue(log.contains(tmp.getAbsolutePath())); } /** * Fake installation on Unix. */ public void testFakeUnixInstall() throws Exception { // If we're on Windows, don't bother doing this. if (Functions.isWindows()) return; File bundle = File.createTempFile("fake-jdk-by-hudson","sh"); try { new FilePath(bundle).write( "#!/bin/bash -ex\n" + "mkdir -p jdk1.6.0_dummy/bin\n" + "touch jdk1.6.0_dummy/bin/java","ASCII"); TaskListener l = StreamTaskListener.fromStdout(); File d = env.temporaryDirectoryAllocator.allocate(); new JDKInstaller("",true).install(new LocalLauncher(l),Platform.LINUX, new JDKInstaller.FilePathFileSystem(hudson),l,d.getPath(),bundle.getPath()); assertTrue(new File(d,"bin/java").exists()); } finally { bundle.delete(); } } private static final Logger LOGGER = Logger.getLogger(JDKInstallerTest.class.getName()); }
test/src/test/java/hudson/tools/JDKInstallerTest.java
package hudson.tools; import hudson.model.Descriptor; import hudson.model.DownloadService; import hudson.tools.JDKInstaller.DescriptorImpl; import org.jvnet.hudson.test.HudsonTestCase; import hudson.model.JDK; import hudson.model.FreeStyleProject; import hudson.model.FreeStyleBuild; import hudson.model.TaskListener; import hudson.tasks.Shell; import hudson.util.StreamTaskListener; import hudson.tools.JDKInstaller.Platform; import hudson.tools.JDKInstaller.CPU; import hudson.FilePath; import hudson.Functions; import hudson.Launcher.LocalLauncher; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays; import java.util.Properties; import java.util.logging.Logger; import org.jvnet.hudson.test.Bug; import org.xml.sax.SAXException; /** * @author Kohsuke Kawaguchi */ public class JDKInstallerTest extends HudsonTestCase { boolean old; @Override protected void setUp() throws Exception { super.setUp(); old = DownloadService.neverUpdate; DownloadService.neverUpdate = false; File f = new File(new File(System.getProperty("user.home")),".jenkins-ci.org"); if (!f.exists()) { LOGGER.warning(f+" doesn't exist. Skipping JDK installation tests"); } else { Properties prop = new Properties(); FileInputStream in = new FileInputStream(f); try { prop.load(in); String u = prop.getProperty("oracle.userName"); String p = prop.getProperty("oracle.password"); if (u==null || p==null) { LOGGER.warning(f+" doesn't contain oracle.userName and oracle.password. Skipping JDK installation tests."); } else { DescriptorImpl d = jenkins.getDescriptorByType(DescriptorImpl.class); d.doPostCredential(u,p); } } finally { in.close(); } } } @Override protected void tearDown() throws Exception { DownloadService.neverUpdate = old; super.tearDown(); } /** * Tests the configuration round trip. */ public void testConfigRoundtrip() throws Exception { File tmp = env.temporaryDirectoryAllocator.allocate(); JDKInstaller installer = new JDKInstaller("jdk-6u13-oth-JPR@CDS-CDS_Developer", true); hudson.getJDKs().add(new JDK("test",tmp.getAbsolutePath(), Arrays.asList( new InstallSourceProperty(Arrays.<ToolInstaller>asList(installer))))); submit(new WebClient().goTo("configure").getFormByName("config")); JDK jdk = hudson.getJDK("test"); InstallSourceProperty isp = jdk.getProperties().get(InstallSourceProperty.class); assertEquals(1,isp.installers.size()); assertEqualBeans(installer,isp.installers.get(JDKInstaller.class),"id,acceptLicense"); } /** * Can we locate the bundles? */ public void testLocate() throws Exception { retrieveUpdateCenterData(); JDKInstaller i = new JDKInstaller("jdk-6u13-oth-JPR@CDS-CDS_Developer", true); StreamTaskListener listener = StreamTaskListener.fromStdout(); i.locate(listener, Platform.LINUX, CPU.i386); i.locate(listener, Platform.WINDOWS, CPU.amd64); i.locate(listener, Platform.SOLARIS, CPU.Sparc); } private void retrieveUpdateCenterData() throws IOException, SAXException { new WebClient().goTo("/"); // make sure data is loaded } /** * Tests the auto installation. */ public void testAutoInstallation6u13() throws Exception { doTestAutoInstallation("jdk-6u13-oth-JPR@CDS-CDS_Developer", "1.6.0_13-b03"); } @Bug(3989) public void testAutoInstallation142_17() throws Exception { doTestAutoInstallation("j2sdk-1.4.2_17-oth-JPR@CDS-CDS_Developer", "1.4.2_17-b06"); } /** * End-to-end installation test. */ private void doTestAutoInstallation(String id, String fullversion) throws Exception { // this is a really time consuming test, so only run it when we really want // if(!Boolean.getBoolean("hudson.sunTests")) // return; retrieveUpdateCenterData(); File tmp = env.temporaryDirectoryAllocator.allocate(); JDKInstaller installer = new JDKInstaller(id, true); JDK jdk = new JDK("test", tmp.getAbsolutePath(), Arrays.asList( new InstallSourceProperty(Arrays.<ToolInstaller>asList(installer)))); hudson.getJDKs().add(jdk); FreeStyleProject p = createFreeStyleProject(); p.setJDK(jdk); p.getBuildersList().add(new Shell("java -fullversion\necho $JAVA_HOME")); FreeStyleBuild b = buildAndAssertSuccess(p); @SuppressWarnings("deprecation") String log = b.getLog(); System.out.println(log); // make sure it runs with the JDK that just got installed assertTrue(log.contains(fullversion)); assertTrue(log.contains(tmp.getAbsolutePath())); } /** * Fake installation on Unix. */ public void testFakeUnixInstall() throws Exception { // If we're on Windows, don't bother doing this. if (Functions.isWindows()) return; File bundle = File.createTempFile("fake-jdk-by-hudson","sh"); try { new FilePath(bundle).write( "#!/bin/bash -ex\n" + "mkdir -p jdk1.6.0_dummy/bin\n" + "touch jdk1.6.0_dummy/bin/java","ASCII"); TaskListener l = StreamTaskListener.fromStdout(); File d = env.temporaryDirectoryAllocator.allocate(); new JDKInstaller("",true).install(new LocalLauncher(l),Platform.LINUX, new JDKInstaller.FilePathFileSystem(hudson),l,d.getPath(),bundle.getPath()); assertTrue(new File(d,"bin/java").exists()); } finally { bundle.delete(); } } private static final Logger LOGGER = Logger.getLogger(JDKInstallerTest.class.getName()); }
test the page that enters credential
test/src/test/java/hudson/tools/JDKInstallerTest.java
test the page that enters credential
<ide><path>est/src/test/java/hudson/tools/JDKInstallerTest.java <ide> package hudson.tools; <ide> <add>import com.gargoylesoftware.htmlunit.html.HtmlForm; <add>import com.gargoylesoftware.htmlunit.html.HtmlPage; <ide> import hudson.model.Descriptor; <ide> import hudson.model.DownloadService; <ide> import hudson.tools.JDKInstaller.DescriptorImpl; <ide> protected void tearDown() throws Exception { <ide> DownloadService.neverUpdate = old; <ide> super.tearDown(); <add> } <add> <add> public void testEnterCredential() throws Exception { <add> HtmlPage p = createWebClient().goTo("/descriptorByName/hudson.tools.JDKInstaller/enterCredential"); <add> HtmlForm form = p.getFormByName("postCredential"); <add> form.getInputByName("username").setValueAttribute("foo"); <add> form.getInputByName("password").setValueAttribute("bar"); <add> form.submit(null); <add> <add> DescriptorImpl d = jenkins.getDescriptorByType(DescriptorImpl.class); <add> assertEquals("foo",d.getUsername()); <add> assertEquals("bar",d.getPassword().getPlainText()); <ide> } <ide> <ide> /**
Java
apache-2.0
ac74a5c1e067a6c5596906cde96082eb801e0c5a
0
estatio/estatio,estatio/estatio,estatio/estatio,estatio/estatio
package org.estatio.capex.dom.invoice; import java.math.BigDecimal; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.function.Function; import java.util.stream.Collectors; import javax.annotation.Nullable; import javax.inject.Inject; import javax.jdo.annotations.Column; import javax.jdo.annotations.FetchGroup; import javax.jdo.annotations.IdentityType; import javax.jdo.annotations.Index; import javax.jdo.annotations.Indices; import javax.jdo.annotations.InheritanceStrategy; import javax.jdo.annotations.NotPersistent; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.Queries; import javax.jdo.annotations.Query; import javax.validation.constraints.Digits; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import com.google.common.collect.ComparisonChain; import com.google.common.collect.Lists; import org.joda.time.LocalDate; import org.apache.isis.applib.annotation.Action; import org.apache.isis.applib.annotation.ActionLayout; import org.apache.isis.applib.annotation.BookmarkPolicy; import org.apache.isis.applib.annotation.Contributed; import org.apache.isis.applib.annotation.DomainObject; import org.apache.isis.applib.annotation.DomainObjectLayout; import org.apache.isis.applib.annotation.Editing; import org.apache.isis.applib.annotation.MemberOrder; import org.apache.isis.applib.annotation.MinLength; import org.apache.isis.applib.annotation.Mixin; import org.apache.isis.applib.annotation.Programmatic; import org.apache.isis.applib.annotation.SemanticsOf; import org.apache.isis.applib.annotation.Where; import org.apache.isis.applib.services.metamodel.MetaModelService2; import org.apache.isis.applib.services.metamodel.MetaModelService3; import org.apache.isis.applib.util.TitleBuffer; import org.apache.isis.schema.utils.jaxbadapters.PersistentEntityAdapter; import org.incode.module.base.dom.valuetypes.LocalDateInterval; import org.incode.module.document.dom.impl.docs.Document; import org.estatio.capex.dom.bankaccount.verification.BankAccountVerificationState; import org.estatio.capex.dom.bankaccount.verification.BankAccountVerificationStateTransition; import org.estatio.capex.dom.documents.BudgetItemChooser; import org.estatio.capex.dom.documents.LookupAttachedPdfService; import org.estatio.capex.dom.invoice.approval.IncomingInvoiceApprovalState; import org.estatio.capex.dom.invoice.approval.IncomingInvoiceApprovalStateTransition; import org.estatio.capex.dom.orderinvoice.OrderItemInvoiceItemLink; import org.estatio.capex.dom.orderinvoice.OrderItemInvoiceItemLinkRepository; import org.estatio.capex.dom.payment.PaymentLine; import org.estatio.capex.dom.payment.PaymentLineRepository; import org.estatio.capex.dom.project.Project; import org.estatio.capex.dom.state.State; import org.estatio.capex.dom.state.StateTransition; import org.estatio.capex.dom.state.StateTransitionService; import org.estatio.capex.dom.state.StateTransitionType; import org.estatio.capex.dom.state.Stateful; import org.estatio.capex.dom.util.PeriodUtil; import org.estatio.dom.asset.FixedAsset; import org.estatio.dom.asset.Property; import org.estatio.dom.budgeting.budgetitem.BudgetItem; import org.estatio.dom.charge.Charge; import org.estatio.dom.charge.ChargeRepository; import org.estatio.dom.currency.Currency; import org.estatio.dom.financial.bankaccount.BankAccount; import org.estatio.dom.financial.bankaccount.BankAccountRepository; import org.estatio.dom.invoice.Invoice; import org.estatio.dom.invoice.InvoiceItem; import org.estatio.dom.invoice.InvoiceStatus; import org.estatio.dom.invoice.PaymentMethod; import org.estatio.dom.party.Party; import org.estatio.dom.party.PartyRepository; import org.estatio.dom.party.role.PartyRoleRepository; import org.estatio.dom.utils.ReasonBuffer2; import org.estatio.tax.dom.Tax; import lombok.Getter; import lombok.Setter; @PersistenceCapable( identityType = IdentityType.DATASTORE // unused since rolled-up to superclass: //,schema = "dbo" //,table = "IncomingInvoice" ) @javax.jdo.annotations.Inheritance( strategy = InheritanceStrategy.SUPERCLASS_TABLE) @javax.jdo.annotations.Discriminator( "incomingInvoice.IncomingInvoice" ) @Queries({ @Query( name = "findByApprovalState", language = "JDOQL", value = "SELECT " + "FROM org.estatio.capex.dom.invoice.IncomingInvoice " + "WHERE approvalState == :approvalState "), @Query( name = "findByApprovalStateAndPaymentMethod", language = "JDOQL", value = "SELECT " + "FROM org.estatio.capex.dom.invoice.IncomingInvoice " + "WHERE approvalState == :approvalState " + " && paymentMethod == :paymentMethod "), @Query( name = "findByInvoiceNumber", language = "JDOQL", value = "SELECT " + "FROM org.estatio.capex.dom.invoice.IncomingInvoice " + "WHERE invoiceNumber == :invoiceNumber "), @Query( name = "findByInvoiceNumberAndSeller", language = "JDOQL", value = "SELECT " + "FROM org.estatio.capex.dom.invoice.IncomingInvoice " + "WHERE invoiceNumber == :invoiceNumber " + " && seller == :seller "), @Query( name = "findByInvoiceNumberAndSellerAndInvoiceDate", language = "JDOQL", value = "SELECT " + "FROM org.estatio.capex.dom.invoice.IncomingInvoice " + "WHERE invoiceNumber == :invoiceNumber " + " && seller == :seller " + " && invoiceDate == :invoiceDate "), @Query( name = "findByInvoiceDateBetween", language = "JDOQL", value = "SELECT " + "FROM org.estatio.capex.dom.invoice.IncomingInvoice " + "WHERE invoiceDate >= :fromDate " + " && invoiceDate <= :toDate "), @Query( name = "findCompletedOrLaterWithItemsByReportedDate", language = "JDOQL", value = "SELECT " + "FROM org.estatio.capex.dom.invoice.IncomingInvoice " + "WHERE items.contains(ii) " + " && (ii.reportedDate == :reportedDate) " + " && (approvalState != 'NEW' && approvalState != 'DISCARDED') " + "VARIABLES org.estatio.capex.dom.invoice.IncomingInvoiceItem ii " ), @Query( name = "findByDueDateBetween", language = "JDOQL", value = "SELECT " + "FROM org.estatio.capex.dom.invoice.IncomingInvoice " + "WHERE dueDate >= :fromDate " + " && dueDate <= :toDate "), @Query( name = "findByPropertyAndDateReceivedBetween", language = "JDOQL", value = "SELECT " + "FROM org.estatio.capex.dom.invoice.IncomingInvoice " + "WHERE property == :property " + " && dateReceived >= :fromDate " + " && dateReceived <= :toDate "), @Query( name = "findNotInAnyPaymentBatchByApprovalStateAndPaymentMethod", language = "JDOQL", value = "SELECT " + "FROM org.estatio.capex.dom.invoice.IncomingInvoice " + "WHERE !(SELECT invoice " + " FROM org.estatio.capex.dom.payment.PaymentLine).contains(this) " + " && approvalState == :approvalState " + " && paymentMethod == :paymentMethod " + "ORDER BY invoiceDate ASC " // oldest first ), @Query( name = "findByBankAccount", language = "JDOQL", value = "SELECT " + "FROM org.estatio.capex.dom.invoice.IncomingInvoice " + "WHERE bankAccount == :bankAccount " + "ORDER BY invoiceDate DESC " // newest first ) }) @FetchGroup( name="seller_buyer_property_bankAccount", members={ @Persistent(name="seller"), @Persistent(name="buyer"), @Persistent(name="property"), @Persistent(name="bankAccount") }) @Indices({ @Index(name = "IncomingInvoice_approvalState_IDX", members = { "approvalState" }) }) // unused, since rolled-up //@Unique(name = "IncomingInvoice_invoiceNumber_UNQ", members = { "invoiceNumber" }) @DomainObject( editing = Editing.DISABLED, objectType = "incomingInvoice.IncomingInvoice", persistingLifecycleEvent = IncomingInvoice.ObjectPersistingEvent.class, persistedLifecycleEvent = IncomingInvoice.ObjectPersistedEvent.class, removingLifecycleEvent = IncomingInvoice.ObjectRemovingEvent.class ) @DomainObjectLayout( bookmarking = BookmarkPolicy.AS_ROOT ) @XmlJavaTypeAdapter(PersistentEntityAdapter.class) public class IncomingInvoice extends Invoice<IncomingInvoice> implements SellerBankAccountCreator, Stateful { public static class ApprovalInvalidatedEvent extends java.util.EventObject { public ApprovalInvalidatedEvent(final Object source) { super(source); } public IncomingInvoice getIncomingInvoice(){ return (IncomingInvoice) getSource(); } } public static class ObjectPersistingEvent extends org.apache.isis.applib.services.eventbus.ObjectPersistingEvent <IncomingInvoice> { } public static class ObjectPersistedEvent extends org.apache.isis.applib.services.eventbus.ObjectPersistedEvent <IncomingInvoice> { } public static class ObjectRemovingEvent extends org.apache.isis.applib.services.eventbus.ObjectRemovingEvent <IncomingInvoice> { } public IncomingInvoice() { super("seller,invoiceNumber"); } public IncomingInvoice( final IncomingInvoiceType typeIfAny, final String invoiceNumber, final Property property, final String atPath, final Party buyer, final Party seller, final LocalDate invoiceDate, final LocalDate dueDate, final PaymentMethod paymentMethod, final InvoiceStatus invoiceStatus, final LocalDate dateReceived, final BankAccount bankAccount, final IncomingInvoiceApprovalState approvalStateIfAny){ super("invoiceNumber"); setType(typeIfAny); setInvoiceNumber(invoiceNumber); setProperty(property); setApplicationTenancyPath(atPath); setBuyer(buyer); setSeller(seller); setInvoiceDate(invoiceDate); setDueDate(dueDate); setPaymentMethod(paymentMethod); setStatus(invoiceStatus); setDateReceived(dateReceived); setBankAccount(bankAccount); setApprovalState(approvalStateIfAny); } public String title() { final TitleBuffer buf = new TitleBuffer(); final Optional<Document> document = lookupAttachedPdfService.lookupIncomingInvoicePdfFrom(this); document.ifPresent(d -> buf.append(d.getName())); final Party seller = getSeller(); if(seller != null) { buf.append(": ", seller); } final String invoiceNumber = getInvoiceNumber(); if(invoiceNumber != null) { buf.append(", ", invoiceNumber); } return buf.toString(); } @MemberOrder(name="items", sequence = "1") public IncomingInvoice addItem( final IncomingInvoiceType type, final Charge charge, final String description, @Digits(integer=13, fraction = 2) final BigDecimal netAmount, @Nullable @Digits(integer=13, fraction = 2) final BigDecimal vatAmount, @Digits(integer=13, fraction = 2) final BigDecimal grossAmount, @Nullable final Tax tax, @Nullable final LocalDate dueDate, @Nullable final String period, @Nullable final Property property, @Nullable final Project project, @Nullable final BudgetItem budgetItem) { addItemToThis( type, charge, description, netAmount, vatAmount, grossAmount, tax, dueDate, period, property, project, budgetItem); return this; } public String disableAddItem() { final ReasonBuffer2 buf = ReasonBuffer2.forSingle("Cannot add item because"); buf.append(amountsCoveredByAmountsItems(), "invoice amounts are covered"); final Object viewContext = this; reasonDisabledDueToApprovalStateIfAny(viewContext, buf); return buf.getReason(); } public IncomingInvoiceType default0AddItem() { return getType(); } public LocalDate default7AddItem() { return ofFirstItem(IncomingInvoiceItem::getDueDate); } public String default8AddItem() { return ofFirstItem(IncomingInvoiceItem::getStartDate)!=null ? PeriodUtil.periodFromInterval(new LocalDateInterval(ofFirstItem(IncomingInvoiceItem::getStartDate), ofFirstItem(IncomingInvoiceItem::getEndDate))) : null; } public Property default9AddItem() { return getProperty(); } public Project default10AddItem() { return ofFirstItem(IncomingInvoiceItem::getProject); } public List<Charge> choices1AddItem(){ return chargeRepository.allIncoming(); } public List<BudgetItem> choices11AddItem( final IncomingInvoiceType type, final Charge charge, final String description, final BigDecimal netAmount, final BigDecimal vatAmount, final BigDecimal grossAmount, final Tax tax, final LocalDate dueDate, final String period, final Property property, final Project project, final BudgetItem budgetItem) { return budgetItemChooser.choicesBudgetItemFor(property, charge); } public String validateAddItem( final IncomingInvoiceType type, final Charge charge, final String description, final BigDecimal netAmount, final BigDecimal vatAmount, final BigDecimal grossAmount, final Tax tax, final LocalDate dueDate, final String period, final Property property, final Project project, final BudgetItem budgetItem){ if (period==null) return null; // period is optional return PeriodUtil.reasonInvalidPeriod(period); } boolean amountsCoveredByAmountsItems(){ if ((getNetAmount()!=null && getTotalNetAmount().compareTo(getNetAmount()) >= 0) || (getGrossAmount() !=null && getTotalGrossAmount().compareTo(getGrossAmount()) >= 0) ){ return true; } return false; } @Action @MemberOrder(name="items", sequence = "4") public IncomingInvoice reverseItem(final IncomingInvoiceItem itemToReverse) { final IncomingInvoiceItem reversal = copyWithLinks(itemToReverse, Sort.REVERSAL); final IncomingInvoiceItem correction = copyWithLinks(itemToReverse, Sort.CORRECTION); return this; } enum Sort { REVERSAL { @Override BigDecimal adjust(final BigDecimal amount) { return Sort.negate(amount); } }, CORRECTION { @Override BigDecimal adjust(final BigDecimal amount) { return amount; } }; String prefixTo(String description) { return name() + " of " + description; }; abstract BigDecimal adjust(BigDecimal amount); private static BigDecimal negate(@Nullable final BigDecimal amount) { return amount == null ? amount : BigDecimal.ZERO.subtract(amount); } } private IncomingInvoiceItem copyWithLinks( final IncomingInvoiceItem itemToReverse, final Sort sort) { final IncomingInvoiceType type = itemToReverse.getIncomingInvoiceType(); final String description = itemToReverse.getDescription(); final Charge charge = itemToReverse.getCharge(); final BigDecimal netAmount = itemToReverse.getNetAmount(); final BigDecimal vatAmount = itemToReverse.getVatAmount(); final BigDecimal grossAmount = itemToReverse.getGrossAmount(); final Tax tax = itemToReverse.getTax(); final LocalDate dueDate = itemToReverse.getDueDate(); final String period = itemToReverse.getPeriod(); final FixedAsset fixedAsset = itemToReverse.getFixedAsset(); final Project project = itemToReverse.getProject(); final BudgetItem budgetItem = itemToReverse.getBudgetItem(); final IncomingInvoiceItem copyItem = addItemToThis( type, charge, sort.prefixTo(description), sort.adjust(netAmount), sort.adjust(vatAmount), sort.adjust(grossAmount), tax, dueDate, period, fixedAsset, project, budgetItem); if(sort == Sort.REVERSAL) { copyItem.setReversalOf(itemToReverse); } final List<OrderItemInvoiceItemLink> links = orderItemInvoiceItemLinkRepository.findByInvoiceItem(itemToReverse); for (OrderItemInvoiceItemLink link : links) { orderItemInvoiceItemLinkRepository.createLink( link.getOrderItem(), copyItem, sort.adjust(link.getNetAmount())); } return copyItem; } public String disableReverseItem() { return choices0ReverseItem().isEmpty() ? "No items to reverse" : null; } public IncomingInvoiceItem default0ReverseItem() { final List<IncomingInvoiceItem> choices = choices0ReverseItem(); return choices.size() == 1 ? choices.get(0) : null; } public List<IncomingInvoiceItem> choices0ReverseItem() { return Lists.newArrayList(getItems()).stream(). filter(IncomingInvoiceItem.class::isInstance) .map(IncomingInvoiceItem.class::cast) .filter(x -> x.getReportedDate() != null) .filter(x -> x.getReversalOf() == null) .collect(Collectors.toList()); } @MemberOrder(name = "items", sequence = "2") public IncomingInvoice splitItem( final IncomingInvoiceItem itemToSplit, final String newItemDescription, @Digits(integer = 13, fraction = 2) final BigDecimal newItemNetAmount, @Nullable @Digits(integer = 13, fraction = 2) final BigDecimal newItemVatAmount, @Nullable final Tax newItemtax, @Digits(integer = 13, fraction = 2) final BigDecimal newItemGrossAmount, final Charge newItemCharge, @Nullable final Property newItemProperty, @Nullable final Project newItemProject, @Nullable final BudgetItem newItemBudgetItem, final String newItemPeriod ) { itemToSplit.subtractAmounts(newItemNetAmount, newItemVatAmount, newItemGrossAmount); addItemToThis(getType(), newItemCharge, newItemDescription, newItemNetAmount, newItemVatAmount, newItemGrossAmount, newItemtax, getDueDate(), newItemPeriod, newItemProperty, newItemProject, newItemBudgetItem); return this; } public String disableSplitItem() { ReasonBuffer2 buf = ReasonBuffer2.forSingle("Cannot spli items because"); reasonDisabledDueToApprovalStateIfAny(this, buf); buf.append(() -> choices0SplitItem().isEmpty(), "there are no items"); return buf.getReason(); } public IncomingInvoiceItem default0SplitItem() { final List<IncomingInvoiceItem> items = choices0SplitItem(); return items.isEmpty() ? null : items.get(0); } private Optional<IncomingInvoiceItem> optional0SplitItem() { return Optional.ofNullable(default0SplitItem()); } public Tax default4SplitItem() { return optional0SplitItem().map(IncomingInvoiceItem::getTax).orElse(null); } public Charge default6SplitItem() { return optional0SplitItem().map(IncomingInvoiceItem::getCharge).orElse(null); } public Property default7SplitItem() { return getProperty(); } public Project default8SplitItem() { return optional0SplitItem().map(IncomingInvoiceItem::getProject).orElse(null); } public BudgetItem default9SplitItem() { return optional0SplitItem().map(IncomingInvoiceItem::getBudgetItem).orElse(null); } public String default10SplitItem() { return optional0SplitItem().map(IncomingInvoiceItem::getPeriod).orElse(null); } public List<IncomingInvoiceItem> choices0SplitItem() { return Lists.newArrayList(getItems()).stream() .map(IncomingInvoiceItem.class::cast) .filter(IncomingInvoiceItem::neitherReversalNorReported) .collect(Collectors.toList()); } public List<Charge> choices6SplitItem(){ return chargeRepository.allIncoming(); } public List<BudgetItem> choices9SplitItem( final IncomingInvoiceItem item, final String newItemDescription, final BigDecimal newItemNetAmount, final BigDecimal newItemVatAmount, final Tax newItemtax, final BigDecimal newItemGrossAmount, final Charge newItemCharge, final Property newItemProperty, final Project newItemProject, final BudgetItem newItemBudgetItem, final String newItemPeriod) { return budgetItemChooser.choicesBudgetItemFor(newItemProperty, newItemCharge); } public String validateSplitItem( final IncomingInvoiceItem item, final String newItemDescription, final BigDecimal newItemNetAmount, final BigDecimal newItemVatAmount, final Tax newItemtax, final BigDecimal newItemGrossAmount, final Charge newItemCharge, final Property newItemProperty, final Project newItemProject, final BudgetItem newItemBudgetItem, final String newItemPeriod){ return PeriodUtil.reasonInvalidPeriod(newItemPeriod); } @Programmatic public <T> T ofFirstItem(final Function<IncomingInvoiceItem, T> f) { final Optional<IncomingInvoiceItem> firstItemIfAny = firstItemIfAny(); return firstItemIfAny.map(f).orElse(null); } @Programmatic public Optional<IncomingInvoiceItem> firstItemIfAny() { return Lists.newArrayList(getItems()).stream() .filter(IncomingInvoiceItem.class::isInstance) .map(IncomingInvoiceItem.class::cast) .findFirst(); } @MemberOrder(name = "items", sequence = "3") public IncomingInvoice mergeItems( final IncomingInvoiceItem item, final IncomingInvoiceItem mergeInto){ incomingInvoiceItemRepository.mergeItems(item, mergeInto); return this; } public String disableMergeItems() { final ReasonBuffer2 buf = ReasonBuffer2.forSingle("Cannot merge items because"); final Object viewContext = this; reasonDisabledDueToApprovalStateIfAny(viewContext, buf); buf.append(() -> getItems().size() < 2, "merging needs 2 or more items"); return buf.getReason(); } public IncomingInvoiceItem default0MergeItems() { return firstItemIfAny()!=null ? (IncomingInvoiceItem) getItems().last() : null; } public IncomingInvoiceItem default1MergeItems() { return firstItemIfAny()!=null ? (IncomingInvoiceItem) getItems().first() : null; } public List<IncomingInvoiceItem> choices0MergeItems() { return Lists.newArrayList(getItems()).stream() .map(IncomingInvoiceItem.class::cast) .filter(IncomingInvoiceItem::neitherReversalNorReported) .collect(Collectors.toList()); } public List<IncomingInvoiceItem> choices1MergeItems(final IncomingInvoiceItem item) { return Lists.newArrayList(getItems()).stream() .map(IncomingInvoiceItem.class::cast) .filter(IncomingInvoiceItem::neitherReversalNorReported) .filter(x->!x.equals(item)) .collect(Collectors.toList()); } private IncomingInvoiceItem addItemToThis( final IncomingInvoiceType type, final Charge charge, final String description, final BigDecimal netAmount, final BigDecimal vatAmount, final BigDecimal grossAmount, final Tax tax, final LocalDate dueDate, final String period, final FixedAsset<?> fixedAsset, final Project project, final BudgetItem budgetItem) { return incomingInvoiceItemRepository.addItem( this, type, charge, description, netAmount, vatAmount, grossAmount, tax, dueDate, period, fixedAsset, project, budgetItem); } /** * TODO: inline this mixin. */ @Mixin(method="act") public static class changeBankAccount { private final IncomingInvoice incomingInvoice; public changeBankAccount(final IncomingInvoice incomingInvoice) { this.incomingInvoice = incomingInvoice; } @Action(semantics = SemanticsOf.IDEMPOTENT) @ActionLayout(contributed= Contributed.AS_ACTION) public IncomingInvoice act(final BankAccount bankAccount){ incomingInvoice.setBankAccount(bankAccount); return incomingInvoice; } public String disableAct(){ final Object viewContext = incomingInvoice; final String reasonIfAny = incomingInvoice.reasonDisabledFinanceDetailsDueToState(viewContext); if(reasonIfAny != null) { return reasonIfAny; } if (incomingInvoice.getSeller() == null) { return "Require seller in order to list available bank accounts"; } final List<BankAccount> bankAccountsForSeller = choices0Act(); switch(bankAccountsForSeller.size()) { case 0: return "No bank accounts available for seller"; case 1: return "No other bank accounts for seller"; default: // continue } // if here then enabled return null; } public List<BankAccount> choices0Act(){ return bankAccountRepository.findBankAccountsByOwner(incomingInvoice.getSeller()); } public BankAccount default0Act(){ return incomingInvoice.getBankAccount(); } /** * An alternative design would be to filter out all non-verified bank accounts in the choicesXxx, but that * could be confusing to the end-user (wondering why some bank accounts of the seller aren't listed). */ public String validate0Act(final BankAccount bankAccount){ // a mutable invoice does not need a verified bankaccount if (!incomingInvoice.isImmutableDueToState()) return null; final BankAccountVerificationState state = stateTransitionService .currentStateOf(bankAccount, BankAccountVerificationStateTransition.class); return state != BankAccountVerificationState.VERIFIED ? "Bank account must be verified" : null; } @Inject BankAccountRepository bankAccountRepository; @Inject StateTransitionService stateTransitionService; } /** * Default type, used for routing. * * <p> * This can be overridden for each invoice item. * </p> */ @Getter @Setter @Column(allowsNull = "true") private IncomingInvoiceType type; public void setType(final IncomingInvoiceType type) { this.type = invalidateApprovalIfDiffer(this.type, type); } @Action(semantics = SemanticsOf.IDEMPOTENT) public IncomingInvoice editType( final IncomingInvoiceType type, final boolean changeOnItemsAsWell){ if (changeOnItemsAsWell){ Lists.newArrayList(getItems()) // eagerly load (DN 4.x collections do not support streaming) .stream() .map(IncomingInvoiceItem.class::cast) .forEach(x->x.setIncomingInvoiceType(type)); } setType(type); return this; } public IncomingInvoiceType default0EditType(){ return getType(); } public boolean default1EditType(){ return true; } public String disableEditType(){ return reasonDisabledDueToStateStrict(); } /** * This relates to the owning property, while the child items may either also relate to the property, * or could potentially relate to individual units within the property. * * <p> * Note that InvoiceForLease also has a reference to FixedAsset. It's not possible to move this * up to the Invoice superclass because invoicing module does not "know" about fixed assets. * </p> */ @javax.jdo.annotations.Column(name = "propertyId", allowsNull = "true") @org.apache.isis.applib.annotation.Property(hidden = Where.REFERENCES_PARENT) @Getter @Setter private Property property; public void setProperty(final Property property) { this.property = invalidateApprovalIfDiffer(this.property, property); } @Action(semantics = SemanticsOf.IDEMPOTENT) public IncomingInvoice editProperty( @Nullable final Property property, final boolean changeOnItemsAsWell){ setProperty(property); if (changeOnItemsAsWell){ Lists.newArrayList(getItems()) // eagerly load (DN 4.x collections do not support streaming) .stream() .map(IncomingInvoiceItem.class::cast) .forEach(x->x.setFixedAsset(property)); } return this; } public Property default0EditProperty(){ return getProperty(); } public boolean default1EditProperty(){ return true; } /** * Unlike pretty much every other property, changing the {@link #setBankAccount(BankAccount)} does _not_ cause the * {@link #isApprovedFully() approvedFully} flag to be reset. * Thus, if no other changes are made, then completing the invoice will send it straight through without requiring re-approval. */ @Getter @Setter @Column(allowsNull = "true", name = "bankAccountId") private BankAccount bankAccount; @Getter @Setter @Column(allowsNull = "true") private LocalDate dateReceived; public void setDateReceived(final LocalDate dateReceived) { this.dateReceived = invalidateApprovalIfDiffer(this.dateReceived, dateReceived); } // TODO: does not seem to be used, raised EST-1599 to look into removing it. @Getter @Setter @Column(allowsNull = "true", name="invoiceId") private IncomingInvoice relatesTo; // TODO: need to remove this from superclass, ie push down to InvoiceForLease subclass so not in this subtype @org.apache.isis.applib.annotation.Property(hidden = Where.EVERYWHERE) @Override public InvoiceStatus getStatus() { return super.getStatus(); } @Override public void setCurrency(final Currency currency) { super.setCurrency(invalidateApprovalIfDiffer(getCurrency(), currency)); } @org.apache.isis.applib.annotation.PropertyLayout(named = "ECP (as buyer)") @Override public Party getBuyer() { return super.getBuyer(); } @Override public void setBuyer(final Party buyer) { super.setBuyer(invalidateApprovalIfDiffer(super.getBuyer(), buyer)); } @org.apache.isis.applib.annotation.PropertyLayout(named = "Supplier") @Override public Party getSeller() { return super.getSeller(); } @Override public void setSeller(final Party seller) { super.setSeller(invalidateApprovalIfDiffer(getSeller(), seller)); } @Override public void setDueDate(final LocalDate dueDate) { super.setDueDate(invalidateApprovalIfDiffer(getDueDate(), dueDate)); } @Override public void setInvoiceNumber(final String invoiceNumber) { super.setInvoiceNumber(invalidateApprovalIfDiffer(getInvoiceNumber(), invoiceNumber)); } @Override public void setPaymentMethod(final PaymentMethod paymentMethod) { super.setPaymentMethod(invalidateApprovalIfDiffer(getPaymentMethod(), paymentMethod)); } @org.apache.isis.applib.annotation.Property(hidden = Where.ALL_TABLES) @javax.jdo.annotations.Column(scale = 2, allowsNull = "true") @Getter @Setter private BigDecimal netAmount; public void setNetAmount(final BigDecimal netAmount) { this.netAmount = invalidateApprovalIfDiffer(this.netAmount, netAmount); } @org.apache.isis.applib.annotation.Property(hidden = Where.ALL_TABLES) @Digits(integer = 9, fraction = 2) public BigDecimal getVatAmount() { return getGrossAmount() != null && getNetAmount() != null ? getGrossAmount().subtract(getNetAmount()) : null; } @javax.jdo.annotations.Column(scale = 2, allowsNull = "true") @Getter @Setter private BigDecimal grossAmount; public void setGrossAmount(final BigDecimal grossAmount) { this.grossAmount = invalidateApprovalIfDiffer(this.grossAmount, grossAmount); } @org.apache.isis.applib.annotation.Property(notPersisted = true, hidden = Where.ALL_TABLES) public BigDecimal getNetAmountLinked() { return orderItemInvoiceItemLinkRepository.calculateNetAmountLinkedToInvoice(this); } @Action(semantics = SemanticsOf.IDEMPOTENT) public IncomingInvoice changeAmounts(final BigDecimal netAmount, final BigDecimal grossAmount){ setNetAmount(netAmount); setGrossAmount(grossAmount); return this; } public BigDecimal default0ChangeAmounts(){ return getNetAmount(); } public BigDecimal default1ChangeAmounts(){ return getGrossAmount(); } public String validateChangeAmounts(final BigDecimal netAmount, final BigDecimal grossAmount){ if (grossAmount.compareTo(netAmount) < 0){ return "Gross amount cannot be lower than net amount"; } return null; } @Programmatic @Override public boolean isImmutableDueToState() { final Object viewContext = this; return reasonDisabledDueToState(viewContext)!=null; } @Action(semantics = SemanticsOf.IDEMPOTENT) public IncomingInvoice editInvoiceNumber( @Nullable final String invoiceNumber){ setInvoiceNumber(invoiceNumber); return this; } public String default0EditInvoiceNumber(){ return getInvoiceNumber(); } public String disableEditInvoiceNumber(){ final ReasonBuffer2 buf = ReasonBuffer2.forSingle("Cannot edit invoice number because"); final Object viewContext = this; reasonDisabledDueToApprovalStateIfAny(viewContext, buf); return buf.getReason(); } @Action(semantics = SemanticsOf.IDEMPOTENT) @ActionLayout(named = "Edit ECP (as buyer)") public IncomingInvoice editBuyer( @Nullable final Party buyer){ setBuyer(buyer); return this; } public List<Party> autoComplete0EditBuyer(@MinLength(3) final String searchPhrase){ return partyRepository.autoCompleteWithRole(searchPhrase, IncomingInvoiceRoleTypeEnum.ECP); } public String validate0EditBuyer(final Party party){ return partyRoleRepository.validateThat(party, IncomingInvoiceRoleTypeEnum.ECP); } public Party default0EditBuyer(){ return getBuyer(); } public String disableEditBuyer(){ final ReasonBuffer2 buf = ReasonBuffer2.forSingle("Cannot edit buyer because"); final Object viewContext = this; reasonDisabledDueToApprovalStateIfAny(viewContext, buf); return buf.getReason(); } @Action(semantics = SemanticsOf.IDEMPOTENT) @ActionLayout(named = "Edit Supplier") public IncomingInvoice editSeller( @Nullable final Party supplier, final boolean createRoleIfRequired){ setSeller(supplier); setBankAccount(bankAccountRepository.getFirstBankAccountOfPartyOrNull(supplier)); if(supplier != null && createRoleIfRequired) { partyRoleRepository.findOrCreate(supplier, IncomingInvoiceRoleTypeEnum.SUPPLIER); } return this; } public String validateEditSeller(final Party party, final boolean createRoleIfRequired){ if(party != null && !createRoleIfRequired) { // requires that the supplier already has this role return partyRoleRepository.validateThat(party, IncomingInvoiceRoleTypeEnum.SUPPLIER); } return null; } public Party default0EditSeller(){ return getSeller(); } public String disableEditSeller(){ final ReasonBuffer2 buf = ReasonBuffer2.forSingle("Cannot edit seller because"); final Object viewContext = this; reasonDisabledDueToApprovalStateIfAny(viewContext, buf); buf.append(this::sellerIsImmutableReason); return buf.getReason(); } private String sellerIsImmutableReason(){ for (InvoiceItem item : getItems()){ IncomingInvoiceItem ii = (IncomingInvoiceItem) item; if (ii.isLinkedToOrderItem()){ return "an item is linked to an order"; } } return null; } public IncomingInvoice changeDates( @Nullable final LocalDate dateReceived, @Nullable final LocalDate invoiceDate, @Nullable final LocalDate dueDate ){ setDateReceived(dateReceived); setInvoiceDate(invoiceDate); setDueDate(dueDate); return this; } public LocalDate default0ChangeDates(){ return getDateReceived(); } public LocalDate default1ChangeDates(){ return getInvoiceDate(); } public LocalDate default2ChangeDates(){ return getDueDate(); } public String disableChangeDates(){ final ReasonBuffer2 buf = ReasonBuffer2.forSingle("Cannot change dates because"); final Object viewContext = this; reasonDisabledDueToApprovalStateIfAny(viewContext, buf); return buf.getReason(); } @Getter @Setter @javax.jdo.annotations.Column(allowsNull = "false") private IncomingInvoiceApprovalState approvalState; /** * that is, has passed final approval step. * * Like {@link #getApprovalState()}, this field is populated as the result of transitioning. * It can be reset back if any property changes such as to invalidate the approval, as per {@link #invalidateApprovalIfDiffer(Object, Object)}. */ @Getter @Setter @Column(allowsNull = "false") private boolean approvedFully; @Override public < DO, ST extends StateTransition<DO, ST, STT, S>, STT extends StateTransitionType<DO, ST, STT, S>, S extends State<S> > S getStateOf( final Class<ST> stateTransitionClass) { if(stateTransitionClass == IncomingInvoiceApprovalStateTransition.class) { return (S) approvalState; } return null; } @Override public < DO, ST extends StateTransition<DO, ST, STT, S>, STT extends StateTransitionType<DO, ST, STT, S>, S extends State<S> > void setStateOf( final Class<ST> stateTransitionClass, final S newState) { if(stateTransitionClass == IncomingInvoiceApprovalStateTransition.class) { setApprovalState( (IncomingInvoiceApprovalState) newState ); } } // TODO: added this method for the moment until EST-1508 is picked up - then to be reviewed @Programmatic public String reasonDisabledDueToStateStrict() { final IncomingInvoiceApprovalState approvalState = getApprovalState(); // guard for historic invoices (and invoice items) if (approvalState==null){ return "Cannot modify (invoice was migrated from spreadsheets)"; } switch (approvalState) { case NEW: return null; default: return "Cannot modify because invoice is in state of " + getApprovalState(); } } @Override @Programmatic public String reasonDisabledFinanceDetailsDueToState(final Object viewContext) { final IncomingInvoiceApprovalState approvalState = getApprovalState(); if (approvalState==null){ return "Cannot modify (invoice was migrated from spreadsheets)"; } switch (approvalState) { case DISCARDED: return "Invoice has been DISCARDED"; case PAYABLE: final List<PaymentLine> paymentLines = paymentLineRepository.findByInvoice(this); if(!paymentLines.isEmpty()) { return "Invoice already in a payment batch"; } break; case PAID: return "Invoice has been PAID"; } return null; } @Override @Programmatic public String reasonDisabledDueToState(final Object viewContext) { final String reasonDisabledDueToApprovalStateIfAny = reasonDisabledDueToApprovalStateIfAny(viewContext); if(reasonDisabledDueToApprovalStateIfAny != null) { return reasonDisabledDueToApprovalStateIfAny; } return null; } String reasonDisabledDueToApprovalStateIfAny(final Object viewContext) { final ReasonBuffer2 buf = ReasonBuffer2.forSingle("Cannot modify invoice because"); reasonDisabledDueToApprovalStateIfAny(viewContext, buf); return buf.getReason(); } void reasonDisabledDueToApprovalStateIfAny(final Object viewContext, final ReasonBuffer2 buf) { final IncomingInvoiceApprovalState approvalState = getApprovalState(); buf.append( approvalState==null, "invoice state is unknown (was migrated so assumed to be approved)"); buf.append( approvalState == IncomingInvoiceApprovalState.COMPLETED && metaModelService3.sortOf(viewContext.getClass()) == MetaModelService2.Sort.VIEW_MODEL, "modification through view not allowed once invoice is " + approvalState); buf.append( approvalState != IncomingInvoiceApprovalState.NEW && approvalState != IncomingInvoiceApprovalState.COMPLETED, "invoice is in state of " + getApprovalState()); } @Programmatic public String reasonIncomplete(){ String invoiceValidatorResult = new Validator() .checkNotNull(getType(),"incoming invoice type") .checkNotNull(getInvoiceNumber(), "invoice number") .checkNotNull(getBuyer(), "buyer") .checkNotNull(getSeller(), "seller") .checkNotNull(getDateReceived(), "date received") .checkNotNull(getDueDate(), "due date") .checkNotNull(getPaymentMethod(), "payment method") .checkNotNull(getNetAmount(), "net amount") .checkNotNull(getGrossAmount(), "gross amount") .validateForPaymentMethod(this) .validateForIncomingInvoiceType(this) .validateForAmounts(this) .getResult(); return mergeReasonItemsIncomplete(invoiceValidatorResult); } private String mergeReasonItemsIncomplete(final String validatorResult){ if (reasonItemsIncomplete()!=null) { return validatorResult!=null ? validatorResult.replace(" required", ", ").concat(reasonItemsIncomplete()) : reasonItemsIncomplete(); } else { return validatorResult; } } static class Validator { public Validator() { this.result = null; } @Setter String result; String getResult() { return result != null ? result.concat(" required") : null; } IncomingInvoice.Validator checkNotNull(Object mandatoryProperty, String propertyName) { if (mandatoryProperty == null) { setResult(result == null ? propertyName : result.concat(", ").concat(propertyName)); } return this; } IncomingInvoice.Validator validateForIncomingInvoiceType(IncomingInvoice incomingInvoice){ if (incomingInvoice == null) return this; if (incomingInvoice.getType() == null) return this; String message; switch (incomingInvoice.getType()){ case CAPEX: case SERVICE_CHARGES: case PROPERTY_EXPENSES: message = "property"; if (incomingInvoice.getProperty()==null){ setResult(result==null ? message : result.concat(", ").concat(message)); } break; default: } return this; } IncomingInvoice.Validator validateForPaymentMethod(IncomingInvoice incomingInvoice){ if (incomingInvoice == null) return this; if (incomingInvoice.getPaymentMethod() == null) return this; String message; switch (incomingInvoice.getPaymentMethod()){ case BILLING_ACCOUNT: case BANK_TRANSFER: case CASH: case CHEQUE: message = "bank account"; if (incomingInvoice.getBankAccount()==null){ setResult(result==null ? message : result.concat(", ").concat(message)); } break; default: } return this; } IncomingInvoice.Validator validateForAmounts(IncomingInvoice incomingInvoice){ if (incomingInvoice.getNetAmount()==null || incomingInvoice.getGrossAmount()==null){ // only validate when amounts are set on the invoice return this; } String message; if (!incomingInvoice.getTotalNetAmount().setScale(2).equals(incomingInvoice.getNetAmount().setScale(2)) || !incomingInvoice.getTotalGrossAmount().setScale(2).equals(incomingInvoice.getGrossAmount().setScale(2)) || !incomingInvoice.getTotalVatAmount().setScale(2).equals(incomingInvoice.getVatAmount().setScale(2))){ message = "total amount on items equal to amount on the invoice"; setResult(result==null ? message : result.concat(", ").concat(message)); } return this; } } @Programmatic public String reasonItemsIncomplete(){ StringBuffer buffer = new StringBuffer(); for (InvoiceItem item : getItems()){ IncomingInvoiceItem incomingInvoiceItem = (IncomingInvoiceItem) item; if (incomingInvoiceItem.reasonIncomplete()!=null) { buffer.append("(on item "); buffer.append(incomingInvoiceItem.getSequence().toString()); buffer.append(") "); buffer.append(incomingInvoiceItem.reasonIncomplete()); } } return buffer.length() == 0 ? null : buffer.toString(); } /** * has final modifier so cannot be mocked out. */ final <T> T invalidateApprovalIfDiffer(T previousValue, T newValue) { if (!Objects.equals(previousValue, newValue)) { invalidateApproval(); } return newValue; } protected void invalidateApproval() { getEventBusService().post(new ApprovalInvalidatedEvent(this)); } @Override public int compareTo(final IncomingInvoice other) { return ComparisonChain.start() .compare(getSeller(), other.getSeller()) .compare(getInvoiceNumber(), other.getInvoiceNumber()) .result(); } @Inject @NotPersistent PaymentLineRepository paymentLineRepository; @Inject @NotPersistent LookupAttachedPdfService lookupAttachedPdfService; @Inject @NotPersistent MetaModelService3 metaModelService3; @Inject @NotPersistent BankAccountRepository bankAccountRepository; @Inject @NotPersistent OrderItemInvoiceItemLinkRepository orderItemInvoiceItemLinkRepository; @Inject @NotPersistent PartyRoleRepository partyRoleRepository; @Inject @NotPersistent PartyRepository partyRepository; @Inject @NotPersistent BudgetItemChooser budgetItemChooser; @Inject @NotPersistent IncomingInvoiceItemRepository incomingInvoiceItemRepository; @Inject @NotPersistent ChargeRepository chargeRepository; }
estatioapp/module/capex/dom/src/main/java/org/estatio/capex/dom/invoice/IncomingInvoice.java
package org.estatio.capex.dom.invoice; import java.math.BigDecimal; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.function.Function; import java.util.stream.Collectors; import javax.annotation.Nullable; import javax.inject.Inject; import javax.jdo.annotations.Column; import javax.jdo.annotations.FetchGroup; import javax.jdo.annotations.IdentityType; import javax.jdo.annotations.Index; import javax.jdo.annotations.Indices; import javax.jdo.annotations.InheritanceStrategy; import javax.jdo.annotations.NotPersistent; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.Queries; import javax.jdo.annotations.Query; import javax.validation.constraints.Digits; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import com.google.common.collect.ComparisonChain; import com.google.common.collect.Lists; import org.joda.time.LocalDate; import org.apache.isis.applib.annotation.Action; import org.apache.isis.applib.annotation.ActionLayout; import org.apache.isis.applib.annotation.BookmarkPolicy; import org.apache.isis.applib.annotation.Contributed; import org.apache.isis.applib.annotation.DomainObject; import org.apache.isis.applib.annotation.DomainObjectLayout; import org.apache.isis.applib.annotation.Editing; import org.apache.isis.applib.annotation.MemberOrder; import org.apache.isis.applib.annotation.MinLength; import org.apache.isis.applib.annotation.Mixin; import org.apache.isis.applib.annotation.Programmatic; import org.apache.isis.applib.annotation.SemanticsOf; import org.apache.isis.applib.annotation.Where; import org.apache.isis.applib.services.metamodel.MetaModelService2; import org.apache.isis.applib.services.metamodel.MetaModelService3; import org.apache.isis.applib.util.TitleBuffer; import org.apache.isis.schema.utils.jaxbadapters.PersistentEntityAdapter; import org.incode.module.base.dom.valuetypes.LocalDateInterval; import org.incode.module.document.dom.impl.docs.Document; import org.estatio.capex.dom.bankaccount.verification.BankAccountVerificationState; import org.estatio.capex.dom.bankaccount.verification.BankAccountVerificationStateTransition; import org.estatio.capex.dom.documents.BudgetItemChooser; import org.estatio.capex.dom.documents.LookupAttachedPdfService; import org.estatio.capex.dom.invoice.approval.IncomingInvoiceApprovalState; import org.estatio.capex.dom.invoice.approval.IncomingInvoiceApprovalStateTransition; import org.estatio.capex.dom.orderinvoice.OrderItemInvoiceItemLink; import org.estatio.capex.dom.orderinvoice.OrderItemInvoiceItemLinkRepository; import org.estatio.capex.dom.payment.PaymentLine; import org.estatio.capex.dom.payment.PaymentLineRepository; import org.estatio.capex.dom.project.Project; import org.estatio.capex.dom.state.State; import org.estatio.capex.dom.state.StateTransition; import org.estatio.capex.dom.state.StateTransitionService; import org.estatio.capex.dom.state.StateTransitionType; import org.estatio.capex.dom.state.Stateful; import org.estatio.capex.dom.util.PeriodUtil; import org.estatio.dom.asset.FixedAsset; import org.estatio.dom.asset.Property; import org.estatio.dom.budgeting.budgetitem.BudgetItem; import org.estatio.dom.charge.Charge; import org.estatio.dom.charge.ChargeRepository; import org.estatio.dom.currency.Currency; import org.estatio.dom.financial.bankaccount.BankAccount; import org.estatio.dom.financial.bankaccount.BankAccountRepository; import org.estatio.dom.invoice.Invoice; import org.estatio.dom.invoice.InvoiceItem; import org.estatio.dom.invoice.InvoiceStatus; import org.estatio.dom.invoice.PaymentMethod; import org.estatio.dom.party.Party; import org.estatio.dom.party.PartyRepository; import org.estatio.dom.party.role.PartyRoleRepository; import org.estatio.dom.utils.ReasonBuffer2; import org.estatio.tax.dom.Tax; import lombok.Getter; import lombok.Setter; @PersistenceCapable( identityType = IdentityType.DATASTORE // unused since rolled-up to superclass: //,schema = "dbo" //,table = "IncomingInvoice" ) @javax.jdo.annotations.Inheritance( strategy = InheritanceStrategy.SUPERCLASS_TABLE) @javax.jdo.annotations.Discriminator( "incomingInvoice.IncomingInvoice" ) @Queries({ @Query( name = "findByApprovalState", language = "JDOQL", value = "SELECT " + "FROM org.estatio.capex.dom.invoice.IncomingInvoice " + "WHERE approvalState == :approvalState "), @Query( name = "findByApprovalStateAndPaymentMethod", language = "JDOQL", value = "SELECT " + "FROM org.estatio.capex.dom.invoice.IncomingInvoice " + "WHERE approvalState == :approvalState " + " && paymentMethod == :paymentMethod "), @Query( name = "findByInvoiceNumber", language = "JDOQL", value = "SELECT " + "FROM org.estatio.capex.dom.invoice.IncomingInvoice " + "WHERE invoiceNumber == :invoiceNumber "), @Query( name = "findByInvoiceNumberAndSeller", language = "JDOQL", value = "SELECT " + "FROM org.estatio.capex.dom.invoice.IncomingInvoice " + "WHERE invoiceNumber == :invoiceNumber " + " && seller == :seller "), @Query( name = "findByInvoiceNumberAndSellerAndInvoiceDate", language = "JDOQL", value = "SELECT " + "FROM org.estatio.capex.dom.invoice.IncomingInvoice " + "WHERE invoiceNumber == :invoiceNumber " + " && seller == :seller " + " && invoiceDate == :invoiceDate "), @Query( name = "findByInvoiceDateBetween", language = "JDOQL", value = "SELECT " + "FROM org.estatio.capex.dom.invoice.IncomingInvoice " + "WHERE invoiceDate >= :fromDate " + " && invoiceDate <= :toDate "), @Query( name = "findCompletedOrLaterWithItemsByReportedDate", language = "JDOQL", value = "SELECT " + "FROM org.estatio.capex.dom.invoice.IncomingInvoice " + "WHERE items.contains(ii) " + " && (ii.reportedDate == :reportedDate) " + " && (approvalState != 'NEW' && approvalState != 'DISCARDED') " + "VARIABLES org.estatio.capex.dom.invoice.IncomingInvoiceItem ii " ), @Query( name = "findByDueDateBetween", language = "JDOQL", value = "SELECT " + "FROM org.estatio.capex.dom.invoice.IncomingInvoice " + "WHERE dueDate >= :fromDate " + " && dueDate <= :toDate "), @Query( name = "findByPropertyAndDateReceivedBetween", language = "JDOQL", value = "SELECT " + "FROM org.estatio.capex.dom.invoice.IncomingInvoice " + "WHERE property == :property " + " && dateReceived >= :fromDate " + " && dateReceived <= :toDate "), @Query( name = "findNotInAnyPaymentBatchByApprovalStateAndPaymentMethod", language = "JDOQL", value = "SELECT " + "FROM org.estatio.capex.dom.invoice.IncomingInvoice " + "WHERE !(SELECT invoice " + " FROM org.estatio.capex.dom.payment.PaymentLine).contains(this) " + " && approvalState == :approvalState " + " && paymentMethod == :paymentMethod " + "ORDER BY invoiceDate ASC " // oldest first ), @Query( name = "findByBankAccount", language = "JDOQL", value = "SELECT " + "FROM org.estatio.capex.dom.invoice.IncomingInvoice " + "WHERE bankAccount == :bankAccount " + "ORDER BY invoiceDate DESC " // newest first ) }) @FetchGroup( name="seller_buyer_property_bankAccount", members={ @Persistent(name="seller"), @Persistent(name="buyer"), @Persistent(name="property"), @Persistent(name="bankAccount") }) @Indices({ @Index(name = "IncomingInvoice_approvalState_IDX", members = { "approvalState" }) }) // unused, since rolled-up //@Unique(name = "IncomingInvoice_invoiceNumber_UNQ", members = { "invoiceNumber" }) @DomainObject( editing = Editing.DISABLED, objectType = "incomingInvoice.IncomingInvoice", persistingLifecycleEvent = IncomingInvoice.ObjectPersistingEvent.class, persistedLifecycleEvent = IncomingInvoice.ObjectPersistedEvent.class, removingLifecycleEvent = IncomingInvoice.ObjectRemovingEvent.class ) @DomainObjectLayout( bookmarking = BookmarkPolicy.AS_ROOT ) @XmlJavaTypeAdapter(PersistentEntityAdapter.class) public class IncomingInvoice extends Invoice<IncomingInvoice> implements SellerBankAccountCreator, Stateful { public static class ApprovalInvalidatedEvent extends java.util.EventObject { public ApprovalInvalidatedEvent(final Object source) { super(source); } public IncomingInvoice getIncomingInvoice(){ return (IncomingInvoice) getSource(); } } public static class ObjectPersistingEvent extends org.apache.isis.applib.services.eventbus.ObjectPersistingEvent <IncomingInvoice> { } public static class ObjectPersistedEvent extends org.apache.isis.applib.services.eventbus.ObjectPersistedEvent <IncomingInvoice> { } public static class ObjectRemovingEvent extends org.apache.isis.applib.services.eventbus.ObjectRemovingEvent <IncomingInvoice> { } public IncomingInvoice() { super("seller,invoiceNumber"); } public IncomingInvoice( final IncomingInvoiceType typeIfAny, final String invoiceNumber, final Property property, final String atPath, final Party buyer, final Party seller, final LocalDate invoiceDate, final LocalDate dueDate, final PaymentMethod paymentMethod, final InvoiceStatus invoiceStatus, final LocalDate dateReceived, final BankAccount bankAccount, final IncomingInvoiceApprovalState approvalStateIfAny){ super("invoiceNumber"); setType(typeIfAny); setInvoiceNumber(invoiceNumber); setProperty(property); setApplicationTenancyPath(atPath); setBuyer(buyer); setSeller(seller); setInvoiceDate(invoiceDate); setDueDate(dueDate); setPaymentMethod(paymentMethod); setStatus(invoiceStatus); setDateReceived(dateReceived); setBankAccount(bankAccount); setApprovalState(approvalStateIfAny); } public String title() { final TitleBuffer buf = new TitleBuffer(); final Optional<Document> document = lookupAttachedPdfService.lookupIncomingInvoicePdfFrom(this); document.ifPresent(d -> buf.append(d.getName())); final Party seller = getSeller(); if(seller != null) { buf.append(": ", seller); } final String invoiceNumber = getInvoiceNumber(); if(invoiceNumber != null) { buf.append(", ", invoiceNumber); } return buf.toString(); } @MemberOrder(name="items", sequence = "1") public IncomingInvoice addItem( final IncomingInvoiceType type, final Charge charge, final String description, @Digits(integer=13, fraction = 2) final BigDecimal netAmount, @Nullable @Digits(integer=13, fraction = 2) final BigDecimal vatAmount, @Digits(integer=13, fraction = 2) final BigDecimal grossAmount, @Nullable final Tax tax, @Nullable final LocalDate dueDate, @Nullable final String period, @Nullable final Property property, @Nullable final Project project, @Nullable final BudgetItem budgetItem) { addItemToThis( type, charge, description, netAmount, vatAmount, grossAmount, tax, dueDate, period, property, project, budgetItem); return this; } public String disableAddItem() { final ReasonBuffer2 buf = ReasonBuffer2.forSingle("Cannot add item because"); buf.append(amountsCoveredByAmountsItems(), "invoice amounts are covered"); final Object viewContext = this; reasonDisabledDueToApprovalStateIfAny(viewContext, buf); return buf.getReason(); } public IncomingInvoiceType default0AddItem() { return getType(); } public LocalDate default7AddItem() { return ofFirstItem(IncomingInvoiceItem::getDueDate); } public String default8AddItem() { return ofFirstItem(IncomingInvoiceItem::getStartDate)!=null ? PeriodUtil.periodFromInterval(new LocalDateInterval(ofFirstItem(IncomingInvoiceItem::getStartDate), ofFirstItem(IncomingInvoiceItem::getEndDate))) : null; } public Property default9AddItem() { return getProperty(); } public Project default10AddItem() { return ofFirstItem(IncomingInvoiceItem::getProject); } public List<Charge> choices1AddItem(){ return chargeRepository.allIncoming(); } public List<BudgetItem> choices11AddItem( final IncomingInvoiceType type, final Charge charge, final String description, final BigDecimal netAmount, final BigDecimal vatAmount, final BigDecimal grossAmount, final Tax tax, final LocalDate dueDate, final String period, final Property property, final Project project, final BudgetItem budgetItem) { return budgetItemChooser.choicesBudgetItemFor(property, charge); } public String validateAddItem( final IncomingInvoiceType type, final Charge charge, final String description, final BigDecimal netAmount, final BigDecimal vatAmount, final BigDecimal grossAmount, final Tax tax, final LocalDate dueDate, final String period, final Property property, final Project project, final BudgetItem budgetItem){ if (period==null) return null; // period is optional return PeriodUtil.reasonInvalidPeriod(period); } boolean amountsCoveredByAmountsItems(){ if ((getNetAmount()!=null && getTotalNetAmount().compareTo(getNetAmount()) >= 0) || (getGrossAmount() !=null && getTotalGrossAmount().compareTo(getGrossAmount()) >= 0) ){ return true; } return false; } @Action @MemberOrder(name="items", sequence = "4") public IncomingInvoiceItem reverseItem(final IncomingInvoiceItem itemToReverse) { final IncomingInvoiceItem reversal = copyWithLinks(itemToReverse, Sort.REVERSAL); final IncomingInvoiceItem correction = copyWithLinks(itemToReverse, Sort.CORRECTION); return reversal; } enum Sort { REVERSAL { @Override BigDecimal adjust(final BigDecimal amount) { return Sort.negate(amount); } }, CORRECTION { @Override BigDecimal adjust(final BigDecimal amount) { return amount; } }; String prefixTo(String description) { return name() + " of " + description; }; abstract BigDecimal adjust(BigDecimal amount); private static BigDecimal negate(@Nullable final BigDecimal amount) { return amount == null ? amount : BigDecimal.ZERO.subtract(amount); } } private IncomingInvoiceItem copyWithLinks( final IncomingInvoiceItem itemToReverse, final Sort sort) { final IncomingInvoiceType type = itemToReverse.getIncomingInvoiceType(); final String description = itemToReverse.getDescription(); final Charge charge = itemToReverse.getCharge(); final BigDecimal netAmount = itemToReverse.getNetAmount(); final BigDecimal vatAmount = itemToReverse.getVatAmount(); final BigDecimal grossAmount = itemToReverse.getGrossAmount(); final Tax tax = itemToReverse.getTax(); final LocalDate dueDate = itemToReverse.getDueDate(); final String period = itemToReverse.getPeriod(); final FixedAsset fixedAsset = itemToReverse.getFixedAsset(); final Project project = itemToReverse.getProject(); final BudgetItem budgetItem = itemToReverse.getBudgetItem(); final IncomingInvoiceItem copyItem = addItemToThis( type, charge, sort.prefixTo(description), sort.adjust(netAmount), sort.adjust(vatAmount), sort.adjust(grossAmount), tax, dueDate, period, fixedAsset, project, budgetItem); if(sort == Sort.REVERSAL) { copyItem.setReversalOf(itemToReverse); } final List<OrderItemInvoiceItemLink> links = orderItemInvoiceItemLinkRepository.findByInvoiceItem(itemToReverse); for (OrderItemInvoiceItemLink link : links) { orderItemInvoiceItemLinkRepository.createLink( link.getOrderItem(), copyItem, sort.adjust(link.getNetAmount())); } return copyItem; } public String disableReverseItem() { return choices0ReverseItem().isEmpty() ? "No items to reverse" : null; } public IncomingInvoiceItem default0ReverseItem() { final List<IncomingInvoiceItem> choices = choices0ReverseItem(); return choices.size() == 1 ? choices.get(0) : null; } public List<IncomingInvoiceItem> choices0ReverseItem() { return Lists.newArrayList(getItems()).stream(). filter(IncomingInvoiceItem.class::isInstance) .map(IncomingInvoiceItem.class::cast) .filter(x -> x.getReportedDate() != null) .filter(x -> x.getReversalOf() == null) .collect(Collectors.toList()); } @MemberOrder(name = "items", sequence = "2") public IncomingInvoice splitItem( final IncomingInvoiceItem itemToSplit, final String newItemDescription, @Digits(integer = 13, fraction = 2) final BigDecimal newItemNetAmount, @Nullable @Digits(integer = 13, fraction = 2) final BigDecimal newItemVatAmount, @Nullable final Tax newItemtax, @Digits(integer = 13, fraction = 2) final BigDecimal newItemGrossAmount, final Charge newItemCharge, @Nullable final Property newItemProperty, @Nullable final Project newItemProject, @Nullable final BudgetItem newItemBudgetItem, final String newItemPeriod ) { itemToSplit.subtractAmounts(newItemNetAmount, newItemVatAmount, newItemGrossAmount); addItemToThis(getType(), newItemCharge, newItemDescription, newItemNetAmount, newItemVatAmount, newItemGrossAmount, newItemtax, getDueDate(), newItemPeriod, newItemProperty, newItemProject, newItemBudgetItem); return this; } public String disableSplitItem() { ReasonBuffer2 buf = ReasonBuffer2.forSingle("Cannot spli items because"); reasonDisabledDueToApprovalStateIfAny(this, buf); buf.append(() -> choices0SplitItem().isEmpty(), "there are no items"); return buf.getReason(); } public IncomingInvoiceItem default0SplitItem() { final List<IncomingInvoiceItem> items = choices0SplitItem(); return items.isEmpty() ? null : items.get(0); } private Optional<IncomingInvoiceItem> optional0SplitItem() { return Optional.ofNullable(default0SplitItem()); } public Tax default4SplitItem() { return optional0SplitItem().map(IncomingInvoiceItem::getTax).orElse(null); } public Charge default6SplitItem() { return optional0SplitItem().map(IncomingInvoiceItem::getCharge).orElse(null); } public Property default7SplitItem() { return getProperty(); } public Project default8SplitItem() { return optional0SplitItem().map(IncomingInvoiceItem::getProject).orElse(null); } public BudgetItem default9SplitItem() { return optional0SplitItem().map(IncomingInvoiceItem::getBudgetItem).orElse(null); } public String default10SplitItem() { return optional0SplitItem().map(IncomingInvoiceItem::getPeriod).orElse(null); } public List<IncomingInvoiceItem> choices0SplitItem() { return Lists.newArrayList(getItems()).stream() .map(IncomingInvoiceItem.class::cast) .filter(IncomingInvoiceItem::neitherReversalNorReported) .collect(Collectors.toList()); } public List<Charge> choices6SplitItem(){ return chargeRepository.allIncoming(); } public List<BudgetItem> choices9SplitItem( final IncomingInvoiceItem item, final String newItemDescription, final BigDecimal newItemNetAmount, final BigDecimal newItemVatAmount, final Tax newItemtax, final BigDecimal newItemGrossAmount, final Charge newItemCharge, final Property newItemProperty, final Project newItemProject, final BudgetItem newItemBudgetItem, final String newItemPeriod) { return budgetItemChooser.choicesBudgetItemFor(newItemProperty, newItemCharge); } public String validateSplitItem( final IncomingInvoiceItem item, final String newItemDescription, final BigDecimal newItemNetAmount, final BigDecimal newItemVatAmount, final Tax newItemtax, final BigDecimal newItemGrossAmount, final Charge newItemCharge, final Property newItemProperty, final Project newItemProject, final BudgetItem newItemBudgetItem, final String newItemPeriod){ return PeriodUtil.reasonInvalidPeriod(newItemPeriod); } @Programmatic public <T> T ofFirstItem(final Function<IncomingInvoiceItem, T> f) { final Optional<IncomingInvoiceItem> firstItemIfAny = firstItemIfAny(); return firstItemIfAny.map(f).orElse(null); } @Programmatic public Optional<IncomingInvoiceItem> firstItemIfAny() { return Lists.newArrayList(getItems()).stream() .filter(IncomingInvoiceItem.class::isInstance) .map(IncomingInvoiceItem.class::cast) .findFirst(); } @MemberOrder(name = "items", sequence = "3") public IncomingInvoice mergeItems( final IncomingInvoiceItem item, final IncomingInvoiceItem mergeInto){ incomingInvoiceItemRepository.mergeItems(item, mergeInto); return this; } public String disableMergeItems() { final ReasonBuffer2 buf = ReasonBuffer2.forSingle("Cannot merge items because"); final Object viewContext = this; reasonDisabledDueToApprovalStateIfAny(viewContext, buf); buf.append(() -> getItems().size() < 2, "merging needs 2 or more items"); return buf.getReason(); } public IncomingInvoiceItem default0MergeItems() { return firstItemIfAny()!=null ? (IncomingInvoiceItem) getItems().last() : null; } public IncomingInvoiceItem default1MergeItems() { return firstItemIfAny()!=null ? (IncomingInvoiceItem) getItems().first() : null; } public List<IncomingInvoiceItem> choices0MergeItems() { return Lists.newArrayList(getItems()).stream() .map(IncomingInvoiceItem.class::cast) .filter(IncomingInvoiceItem::neitherReversalNorReported) .collect(Collectors.toList()); } public List<IncomingInvoiceItem> choices1MergeItems(final IncomingInvoiceItem item) { return Lists.newArrayList(getItems()).stream() .map(IncomingInvoiceItem.class::cast) .filter(IncomingInvoiceItem::neitherReversalNorReported) .filter(x->!x.equals(item)) .collect(Collectors.toList()); } private IncomingInvoiceItem addItemToThis( final IncomingInvoiceType type, final Charge charge, final String description, final BigDecimal netAmount, final BigDecimal vatAmount, final BigDecimal grossAmount, final Tax tax, final LocalDate dueDate, final String period, final FixedAsset<?> fixedAsset, final Project project, final BudgetItem budgetItem) { return incomingInvoiceItemRepository.addItem( this, type, charge, description, netAmount, vatAmount, grossAmount, tax, dueDate, period, fixedAsset, project, budgetItem); } /** * TODO: inline this mixin. */ @Mixin(method="act") public static class changeBankAccount { private final IncomingInvoice incomingInvoice; public changeBankAccount(final IncomingInvoice incomingInvoice) { this.incomingInvoice = incomingInvoice; } @Action(semantics = SemanticsOf.IDEMPOTENT) @ActionLayout(contributed= Contributed.AS_ACTION) public IncomingInvoice act(final BankAccount bankAccount){ incomingInvoice.setBankAccount(bankAccount); return incomingInvoice; } public String disableAct(){ final Object viewContext = incomingInvoice; final String reasonIfAny = incomingInvoice.reasonDisabledFinanceDetailsDueToState(viewContext); if(reasonIfAny != null) { return reasonIfAny; } if (incomingInvoice.getSeller() == null) { return "Require seller in order to list available bank accounts"; } final List<BankAccount> bankAccountsForSeller = choices0Act(); switch(bankAccountsForSeller.size()) { case 0: return "No bank accounts available for seller"; case 1: return "No other bank accounts for seller"; default: // continue } // if here then enabled return null; } public List<BankAccount> choices0Act(){ return bankAccountRepository.findBankAccountsByOwner(incomingInvoice.getSeller()); } public BankAccount default0Act(){ return incomingInvoice.getBankAccount(); } /** * An alternative design would be to filter out all non-verified bank accounts in the choicesXxx, but that * could be confusing to the end-user (wondering why some bank accounts of the seller aren't listed). */ public String validate0Act(final BankAccount bankAccount){ // a mutable invoice does not need a verified bankaccount if (!incomingInvoice.isImmutableDueToState()) return null; final BankAccountVerificationState state = stateTransitionService .currentStateOf(bankAccount, BankAccountVerificationStateTransition.class); return state != BankAccountVerificationState.VERIFIED ? "Bank account must be verified" : null; } @Inject BankAccountRepository bankAccountRepository; @Inject StateTransitionService stateTransitionService; } /** * Default type, used for routing. * * <p> * This can be overridden for each invoice item. * </p> */ @Getter @Setter @Column(allowsNull = "true") private IncomingInvoiceType type; public void setType(final IncomingInvoiceType type) { this.type = invalidateApprovalIfDiffer(this.type, type); } @Action(semantics = SemanticsOf.IDEMPOTENT) public IncomingInvoice editType( final IncomingInvoiceType type, final boolean changeOnItemsAsWell){ if (changeOnItemsAsWell){ Lists.newArrayList(getItems()) // eagerly load (DN 4.x collections do not support streaming) .stream() .map(IncomingInvoiceItem.class::cast) .forEach(x->x.setIncomingInvoiceType(type)); } setType(type); return this; } public IncomingInvoiceType default0EditType(){ return getType(); } public boolean default1EditType(){ return true; } public String disableEditType(){ return reasonDisabledDueToStateStrict(); } /** * This relates to the owning property, while the child items may either also relate to the property, * or could potentially relate to individual units within the property. * * <p> * Note that InvoiceForLease also has a reference to FixedAsset. It's not possible to move this * up to the Invoice superclass because invoicing module does not "know" about fixed assets. * </p> */ @javax.jdo.annotations.Column(name = "propertyId", allowsNull = "true") @org.apache.isis.applib.annotation.Property(hidden = Where.REFERENCES_PARENT) @Getter @Setter private Property property; public void setProperty(final Property property) { this.property = invalidateApprovalIfDiffer(this.property, property); } @Action(semantics = SemanticsOf.IDEMPOTENT) public IncomingInvoice editProperty( @Nullable final Property property, final boolean changeOnItemsAsWell){ setProperty(property); if (changeOnItemsAsWell){ Lists.newArrayList(getItems()) // eagerly load (DN 4.x collections do not support streaming) .stream() .map(IncomingInvoiceItem.class::cast) .forEach(x->x.setFixedAsset(property)); } return this; } public Property default0EditProperty(){ return getProperty(); } public boolean default1EditProperty(){ return true; } /** * Unlike pretty much every other property, changing the {@link #setBankAccount(BankAccount)} does _not_ cause the * {@link #isApprovedFully() approvedFully} flag to be reset. * Thus, if no other changes are made, then completing the invoice will send it straight through without requiring re-approval. */ @Getter @Setter @Column(allowsNull = "true", name = "bankAccountId") private BankAccount bankAccount; @Getter @Setter @Column(allowsNull = "true") private LocalDate dateReceived; public void setDateReceived(final LocalDate dateReceived) { this.dateReceived = invalidateApprovalIfDiffer(this.dateReceived, dateReceived); } // TODO: does not seem to be used, raised EST-1599 to look into removing it. @Getter @Setter @Column(allowsNull = "true", name="invoiceId") private IncomingInvoice relatesTo; // TODO: need to remove this from superclass, ie push down to InvoiceForLease subclass so not in this subtype @org.apache.isis.applib.annotation.Property(hidden = Where.EVERYWHERE) @Override public InvoiceStatus getStatus() { return super.getStatus(); } @Override public void setCurrency(final Currency currency) { super.setCurrency(invalidateApprovalIfDiffer(getCurrency(), currency)); } @org.apache.isis.applib.annotation.PropertyLayout(named = "ECP (as buyer)") @Override public Party getBuyer() { return super.getBuyer(); } @Override public void setBuyer(final Party buyer) { super.setBuyer(invalidateApprovalIfDiffer(super.getBuyer(), buyer)); } @org.apache.isis.applib.annotation.PropertyLayout(named = "Supplier") @Override public Party getSeller() { return super.getSeller(); } @Override public void setSeller(final Party seller) { super.setSeller(invalidateApprovalIfDiffer(getSeller(), seller)); } @Override public void setDueDate(final LocalDate dueDate) { super.setDueDate(invalidateApprovalIfDiffer(getDueDate(), dueDate)); } @Override public void setInvoiceNumber(final String invoiceNumber) { super.setInvoiceNumber(invalidateApprovalIfDiffer(getInvoiceNumber(), invoiceNumber)); } @Override public void setPaymentMethod(final PaymentMethod paymentMethod) { super.setPaymentMethod(invalidateApprovalIfDiffer(getPaymentMethod(), paymentMethod)); } @org.apache.isis.applib.annotation.Property(hidden = Where.ALL_TABLES) @javax.jdo.annotations.Column(scale = 2, allowsNull = "true") @Getter @Setter private BigDecimal netAmount; public void setNetAmount(final BigDecimal netAmount) { this.netAmount = invalidateApprovalIfDiffer(this.netAmount, netAmount); } @org.apache.isis.applib.annotation.Property(hidden = Where.ALL_TABLES) @Digits(integer = 9, fraction = 2) public BigDecimal getVatAmount() { return getGrossAmount() != null && getNetAmount() != null ? getGrossAmount().subtract(getNetAmount()) : null; } @javax.jdo.annotations.Column(scale = 2, allowsNull = "true") @Getter @Setter private BigDecimal grossAmount; public void setGrossAmount(final BigDecimal grossAmount) { this.grossAmount = invalidateApprovalIfDiffer(this.grossAmount, grossAmount); } @org.apache.isis.applib.annotation.Property(notPersisted = true, hidden = Where.ALL_TABLES) public BigDecimal getNetAmountLinked() { return orderItemInvoiceItemLinkRepository.calculateNetAmountLinkedToInvoice(this); } @Action(semantics = SemanticsOf.IDEMPOTENT) public IncomingInvoice changeAmounts(final BigDecimal netAmount, final BigDecimal grossAmount){ setNetAmount(netAmount); setGrossAmount(grossAmount); return this; } public BigDecimal default0ChangeAmounts(){ return getNetAmount(); } public BigDecimal default1ChangeAmounts(){ return getGrossAmount(); } public String validateChangeAmounts(final BigDecimal netAmount, final BigDecimal grossAmount){ if (grossAmount.compareTo(netAmount) < 0){ return "Gross amount cannot be lower than net amount"; } return null; } @Programmatic @Override public boolean isImmutableDueToState() { final Object viewContext = this; return reasonDisabledDueToState(viewContext)!=null; } @Action(semantics = SemanticsOf.IDEMPOTENT) public IncomingInvoice editInvoiceNumber( @Nullable final String invoiceNumber){ setInvoiceNumber(invoiceNumber); return this; } public String default0EditInvoiceNumber(){ return getInvoiceNumber(); } public String disableEditInvoiceNumber(){ final ReasonBuffer2 buf = ReasonBuffer2.forSingle("Cannot edit invoice number because"); final Object viewContext = this; reasonDisabledDueToApprovalStateIfAny(viewContext, buf); return buf.getReason(); } @Action(semantics = SemanticsOf.IDEMPOTENT) @ActionLayout(named = "Edit ECP (as buyer)") public IncomingInvoice editBuyer( @Nullable final Party buyer){ setBuyer(buyer); return this; } public List<Party> autoComplete0EditBuyer(@MinLength(3) final String searchPhrase){ return partyRepository.autoCompleteWithRole(searchPhrase, IncomingInvoiceRoleTypeEnum.ECP); } public String validate0EditBuyer(final Party party){ return partyRoleRepository.validateThat(party, IncomingInvoiceRoleTypeEnum.ECP); } public Party default0EditBuyer(){ return getBuyer(); } public String disableEditBuyer(){ final ReasonBuffer2 buf = ReasonBuffer2.forSingle("Cannot edit buyer because"); final Object viewContext = this; reasonDisabledDueToApprovalStateIfAny(viewContext, buf); return buf.getReason(); } @Action(semantics = SemanticsOf.IDEMPOTENT) @ActionLayout(named = "Edit Supplier") public IncomingInvoice editSeller( @Nullable final Party supplier, final boolean createRoleIfRequired){ setSeller(supplier); setBankAccount(bankAccountRepository.getFirstBankAccountOfPartyOrNull(supplier)); if(supplier != null && createRoleIfRequired) { partyRoleRepository.findOrCreate(supplier, IncomingInvoiceRoleTypeEnum.SUPPLIER); } return this; } public String validateEditSeller(final Party party, final boolean createRoleIfRequired){ if(party != null && !createRoleIfRequired) { // requires that the supplier already has this role return partyRoleRepository.validateThat(party, IncomingInvoiceRoleTypeEnum.SUPPLIER); } return null; } public Party default0EditSeller(){ return getSeller(); } public String disableEditSeller(){ final ReasonBuffer2 buf = ReasonBuffer2.forSingle("Cannot edit seller because"); final Object viewContext = this; reasonDisabledDueToApprovalStateIfAny(viewContext, buf); buf.append(this::sellerIsImmutableReason); return buf.getReason(); } private String sellerIsImmutableReason(){ for (InvoiceItem item : getItems()){ IncomingInvoiceItem ii = (IncomingInvoiceItem) item; if (ii.isLinkedToOrderItem()){ return "an item is linked to an order"; } } return null; } public IncomingInvoice changeDates( @Nullable final LocalDate dateReceived, @Nullable final LocalDate invoiceDate, @Nullable final LocalDate dueDate ){ setDateReceived(dateReceived); setInvoiceDate(invoiceDate); setDueDate(dueDate); return this; } public LocalDate default0ChangeDates(){ return getDateReceived(); } public LocalDate default1ChangeDates(){ return getInvoiceDate(); } public LocalDate default2ChangeDates(){ return getDueDate(); } public String disableChangeDates(){ final ReasonBuffer2 buf = ReasonBuffer2.forSingle("Cannot change dates because"); final Object viewContext = this; reasonDisabledDueToApprovalStateIfAny(viewContext, buf); return buf.getReason(); } @Getter @Setter @javax.jdo.annotations.Column(allowsNull = "false") private IncomingInvoiceApprovalState approvalState; /** * that is, has passed final approval step. * * Like {@link #getApprovalState()}, this field is populated as the result of transitioning. * It can be reset back if any property changes such as to invalidate the approval, as per {@link #invalidateApprovalIfDiffer(Object, Object)}. */ @Getter @Setter @Column(allowsNull = "false") private boolean approvedFully; @Override public < DO, ST extends StateTransition<DO, ST, STT, S>, STT extends StateTransitionType<DO, ST, STT, S>, S extends State<S> > S getStateOf( final Class<ST> stateTransitionClass) { if(stateTransitionClass == IncomingInvoiceApprovalStateTransition.class) { return (S) approvalState; } return null; } @Override public < DO, ST extends StateTransition<DO, ST, STT, S>, STT extends StateTransitionType<DO, ST, STT, S>, S extends State<S> > void setStateOf( final Class<ST> stateTransitionClass, final S newState) { if(stateTransitionClass == IncomingInvoiceApprovalStateTransition.class) { setApprovalState( (IncomingInvoiceApprovalState) newState ); } } // TODO: added this method for the moment until EST-1508 is picked up - then to be reviewed @Programmatic public String reasonDisabledDueToStateStrict() { final IncomingInvoiceApprovalState approvalState = getApprovalState(); // guard for historic invoices (and invoice items) if (approvalState==null){ return "Cannot modify (invoice was migrated from spreadsheets)"; } switch (approvalState) { case NEW: return null; default: return "Cannot modify because invoice is in state of " + getApprovalState(); } } @Override @Programmatic public String reasonDisabledFinanceDetailsDueToState(final Object viewContext) { final IncomingInvoiceApprovalState approvalState = getApprovalState(); if (approvalState==null){ return "Cannot modify (invoice was migrated from spreadsheets)"; } switch (approvalState) { case DISCARDED: return "Invoice has been DISCARDED"; case PAYABLE: final List<PaymentLine> paymentLines = paymentLineRepository.findByInvoice(this); if(!paymentLines.isEmpty()) { return "Invoice already in a payment batch"; } break; case PAID: return "Invoice has been PAID"; } return null; } @Override @Programmatic public String reasonDisabledDueToState(final Object viewContext) { final String reasonDisabledDueToApprovalStateIfAny = reasonDisabledDueToApprovalStateIfAny(viewContext); if(reasonDisabledDueToApprovalStateIfAny != null) { return reasonDisabledDueToApprovalStateIfAny; } return null; } String reasonDisabledDueToApprovalStateIfAny(final Object viewContext) { final ReasonBuffer2 buf = ReasonBuffer2.forSingle("Cannot modify invoice because"); reasonDisabledDueToApprovalStateIfAny(viewContext, buf); return buf.getReason(); } void reasonDisabledDueToApprovalStateIfAny(final Object viewContext, final ReasonBuffer2 buf) { final IncomingInvoiceApprovalState approvalState = getApprovalState(); buf.append( approvalState==null, "invoice state is unknown (was migrated so assumed to be approved)"); buf.append( approvalState == IncomingInvoiceApprovalState.COMPLETED && metaModelService3.sortOf(viewContext.getClass()) == MetaModelService2.Sort.VIEW_MODEL, "modification through view not allowed once invoice is " + approvalState); buf.append( approvalState != IncomingInvoiceApprovalState.NEW && approvalState != IncomingInvoiceApprovalState.COMPLETED, "invoice is in state of " + getApprovalState()); } @Programmatic public String reasonIncomplete(){ String invoiceValidatorResult = new Validator() .checkNotNull(getType(),"incoming invoice type") .checkNotNull(getInvoiceNumber(), "invoice number") .checkNotNull(getBuyer(), "buyer") .checkNotNull(getSeller(), "seller") .checkNotNull(getDateReceived(), "date received") .checkNotNull(getDueDate(), "due date") .checkNotNull(getPaymentMethod(), "payment method") .checkNotNull(getNetAmount(), "net amount") .checkNotNull(getGrossAmount(), "gross amount") .validateForPaymentMethod(this) .validateForIncomingInvoiceType(this) .validateForAmounts(this) .getResult(); return mergeReasonItemsIncomplete(invoiceValidatorResult); } private String mergeReasonItemsIncomplete(final String validatorResult){ if (reasonItemsIncomplete()!=null) { return validatorResult!=null ? validatorResult.replace(" required", ", ").concat(reasonItemsIncomplete()) : reasonItemsIncomplete(); } else { return validatorResult; } } static class Validator { public Validator() { this.result = null; } @Setter String result; String getResult() { return result != null ? result.concat(" required") : null; } IncomingInvoice.Validator checkNotNull(Object mandatoryProperty, String propertyName) { if (mandatoryProperty == null) { setResult(result == null ? propertyName : result.concat(", ").concat(propertyName)); } return this; } IncomingInvoice.Validator validateForIncomingInvoiceType(IncomingInvoice incomingInvoice){ if (incomingInvoice == null) return this; if (incomingInvoice.getType() == null) return this; String message; switch (incomingInvoice.getType()){ case CAPEX: case SERVICE_CHARGES: case PROPERTY_EXPENSES: message = "property"; if (incomingInvoice.getProperty()==null){ setResult(result==null ? message : result.concat(", ").concat(message)); } break; default: } return this; } IncomingInvoice.Validator validateForPaymentMethod(IncomingInvoice incomingInvoice){ if (incomingInvoice == null) return this; if (incomingInvoice.getPaymentMethod() == null) return this; String message; switch (incomingInvoice.getPaymentMethod()){ case BILLING_ACCOUNT: case BANK_TRANSFER: case CASH: case CHEQUE: message = "bank account"; if (incomingInvoice.getBankAccount()==null){ setResult(result==null ? message : result.concat(", ").concat(message)); } break; default: } return this; } IncomingInvoice.Validator validateForAmounts(IncomingInvoice incomingInvoice){ if (incomingInvoice.getNetAmount()==null || incomingInvoice.getGrossAmount()==null){ // only validate when amounts are set on the invoice return this; } String message; if (!incomingInvoice.getTotalNetAmount().setScale(2).equals(incomingInvoice.getNetAmount().setScale(2)) || !incomingInvoice.getTotalGrossAmount().setScale(2).equals(incomingInvoice.getGrossAmount().setScale(2)) || !incomingInvoice.getTotalVatAmount().setScale(2).equals(incomingInvoice.getVatAmount().setScale(2))){ message = "total amount on items equal to amount on the invoice"; setResult(result==null ? message : result.concat(", ").concat(message)); } return this; } } @Programmatic public String reasonItemsIncomplete(){ StringBuffer buffer = new StringBuffer(); for (InvoiceItem item : getItems()){ IncomingInvoiceItem incomingInvoiceItem = (IncomingInvoiceItem) item; if (incomingInvoiceItem.reasonIncomplete()!=null) { buffer.append("(on item "); buffer.append(incomingInvoiceItem.getSequence().toString()); buffer.append(") "); buffer.append(incomingInvoiceItem.reasonIncomplete()); } } return buffer.length() == 0 ? null : buffer.toString(); } /** * has final modifier so cannot be mocked out. */ final <T> T invalidateApprovalIfDiffer(T previousValue, T newValue) { if (!Objects.equals(previousValue, newValue)) { invalidateApproval(); } return newValue; } protected void invalidateApproval() { getEventBusService().post(new ApprovalInvalidatedEvent(this)); } @Override public int compareTo(final IncomingInvoice other) { return ComparisonChain.start() .compare(getSeller(), other.getSeller()) .compare(getInvoiceNumber(), other.getInvoiceNumber()) .result(); } @Inject @NotPersistent PaymentLineRepository paymentLineRepository; @Inject @NotPersistent LookupAttachedPdfService lookupAttachedPdfService; @Inject @NotPersistent MetaModelService3 metaModelService3; @Inject @NotPersistent BankAccountRepository bankAccountRepository; @Inject @NotPersistent OrderItemInvoiceItemLinkRepository orderItemInvoiceItemLinkRepository; @Inject @NotPersistent PartyRoleRepository partyRoleRepository; @Inject @NotPersistent PartyRepository partyRepository; @Inject @NotPersistent BudgetItemChooser budgetItemChooser; @Inject @NotPersistent IncomingInvoiceItemRepository incomingInvoiceItemRepository; @Inject @NotPersistent ChargeRepository chargeRepository; }
EST-1576: tiny update, when reverse invoice, return the invoice itself rather than the reversed item
estatioapp/module/capex/dom/src/main/java/org/estatio/capex/dom/invoice/IncomingInvoice.java
EST-1576: tiny update, when reverse invoice, return the invoice itself rather than the reversed item
<ide><path>statioapp/module/capex/dom/src/main/java/org/estatio/capex/dom/invoice/IncomingInvoice.java <ide> <ide> @Action <ide> @MemberOrder(name="items", sequence = "4") <del> public IncomingInvoiceItem reverseItem(final IncomingInvoiceItem itemToReverse) { <add> public IncomingInvoice reverseItem(final IncomingInvoiceItem itemToReverse) { <ide> <ide> final IncomingInvoiceItem reversal = copyWithLinks(itemToReverse, Sort.REVERSAL); <ide> final IncomingInvoiceItem correction = copyWithLinks(itemToReverse, Sort.CORRECTION); <ide> <del> return reversal; <add> return this; <ide> } <ide> <ide> enum Sort {
JavaScript
mit
470d8bfc6a2928fbb39e8ee36c3115411b3386c1
0
diasdavid/node-libp2p-tcp,diasdavid/js-libp2p-tcp
var tcp = require('net') exports = module.exports exports.dial = function (multiaddr, options) { options.ready = options.ready || function noop () {} return tcp.connect(multiaddr.toOptions(), options.ready) } exports.createListener = tcp.createServer
src/index.js
var tcp = require('net') var async = require('async') exports = module.exports exports.dial = function (peerInfo, callback) { var socket async.eachSeries(peerInfo.multiaddrs, function (multiaddr, next) { if (!multiaddr.protoNames().indexOf('tcp')) { return next() } if (socket) { return next() } var tmp = tcp.connect(multiaddr.toOptions(), function connected () { socket = tmp next() }) tmp.once('error', function (err) { console.log(multiaddr.toString(), 'on', peerInfo.id.toB58String(), 'not available', err) next() }) }, function done () { if (!socket) { return callback(new Error('Not able to open a scoket with peer - ', peerInfo.id.toB58String())) } callback(null, socket) }) } exports.listen = function (options, callback, readyCallback) { options.port = options.port || 4001 var listener = tcp.createServer(function (socket) { callback(null, socket) }) listener.listen(options.port, readyCallback) return listener }
after many solo-bikeshedding, figured out that I could make it way simpler
src/index.js
after many solo-bikeshedding, figured out that I could make it way simpler
<ide><path>rc/index.js <ide> var tcp = require('net') <del>var async = require('async') <ide> <ide> exports = module.exports <ide> <del>exports.dial = function (peerInfo, callback) { <del> var socket <del> async.eachSeries(peerInfo.multiaddrs, function (multiaddr, next) { <del> if (!multiaddr.protoNames().indexOf('tcp')) { <del> return next() <del> } <del> <del> if (socket) { <del> return next() <del> } <del> <del> var tmp = tcp.connect(multiaddr.toOptions(), function connected () { <del> socket = tmp <del> next() <del> }) <del> <del> tmp.once('error', function (err) { <del> console.log(multiaddr.toString(), 'on', <del> peerInfo.id.toB58String(), 'not available', err) <del> next() <del> }) <del> }, function done () { <del> if (!socket) { <del> return callback(new Error('Not able to open a scoket with peer - ', <del> peerInfo.id.toB58String())) <del> } <del> callback(null, socket) <del> }) <add>exports.dial = function (multiaddr, options) { <add> options.ready = options.ready || function noop () {} <add> return tcp.connect(multiaddr.toOptions(), options.ready) <ide> } <ide> <del>exports.listen = function (options, callback, readyCallback) { <del> options.port = options.port || 4001 <del> <del> var listener = tcp.createServer(function (socket) { <del> callback(null, socket) <del> }) <del> <del> listener.listen(options.port, readyCallback) <del> <del> return listener <del>} <add>exports.createListener = tcp.createServer
Java
mit
9a210a370aeb4cb56215e402b95f378f022071eb
0
ulriknyman/H-Uppaal
package dk.cs.aau.huppaal.abstractions; import dk.cs.aau.huppaal.HUPPAAL; import dk.cs.aau.huppaal.backend.QueryListener; import dk.cs.aau.huppaal.backend.UPPAALDriver; import dk.cs.aau.huppaal.controllers.HUPPAALController; import dk.cs.aau.huppaal.utility.serialize.Serializable; import com.google.gson.JsonObject; import com.uppaal.engine.Engine; import javafx.application.Platform; import javafx.beans.property.*; import java.util.function.Consumer; import static dk.cs.aau.huppaal.HUPPAAL.showToast; public class Query implements Serializable { private static final String QUERY = "query"; private static final String COMMENT = "comment"; private static final String IS_PERIODIC = "is_periodic"; private final ObjectProperty<QueryState> queryState = new SimpleObjectProperty<>(QueryState.UNKNOWN); private final StringProperty query = new SimpleStringProperty(""); private final StringProperty comment = new SimpleStringProperty(""); private final SimpleBooleanProperty isPeriodic = new SimpleBooleanProperty(false); private Consumer<Boolean> runQuery; public Query(final String query, final String comment, final QueryState queryState) { this.query.set(query); this.comment.set(comment); this.queryState.set(queryState); initializeRunQuery(); } public Query(final JsonObject jsonElement) { deserialize(jsonElement); initializeRunQuery(); } public QueryState getQueryState() { return queryState.get(); } public void setQueryState(final QueryState queryState) { this.queryState.set(queryState); } public ObjectProperty<QueryState> queryStateProperty() { return queryState; } public String getQuery() { return query.get(); } public void setQuery(final String query) { this.query.set(query); } public StringProperty queryProperty() { return query; } public String getComment() { return comment.get(); } public void setComment(final String comment) { this.comment.set(comment); } public StringProperty commentProperty() { return comment; } public boolean isPeriodic() { return isPeriodic.get(); } public SimpleBooleanProperty isPeriodicProperty() { return isPeriodic; } public void setIsPeriodic(final boolean isPeriodic) { this.isPeriodic.set(isPeriodic); } private Engine engine = null; private Boolean forcedCancel = false; private void initializeRunQuery() { runQuery = (buildHUPPAALDocument) -> { setQueryState(QueryState.RUNNING); final Component mainComponent = HUPPAAL.getProject().getMainComponent(); if (mainComponent == null) { return; // We cannot generate a UPPAAL file without a main component } try { if (buildHUPPAALDocument) { UPPAALDriver.buildHUPPAALDocument(); } UPPAALDriver.runQuery(getQuery(), aBoolean -> { if (aBoolean) { setQueryState(QueryState.SUCCESSFUL); } else { setQueryState(QueryState.ERROR); } }, e -> { if (forcedCancel) { setQueryState(QueryState.UNKNOWN); } else { setQueryState(QueryState.SYNTAX_ERROR); final Throwable cause = e.getCause(); if (cause != null) { // We had trouble generating the model if we get a NullPointerException if(cause instanceof NullPointerException) { setQueryState(QueryState.UNKNOWN); } else { Platform.runLater(() -> HUPPAALController.openQueryDialog(this, cause.toString())); } } } }, eng -> { engine = eng; }, new QueryListener(this) ).start(); } catch (final Exception e) { e.printStackTrace(); setQueryState(QueryState.ERROR); showToast("Query failed: " + e.getMessage()); } }; } @Override public JsonObject serialize() { final JsonObject result = new JsonObject(); result.addProperty(QUERY, getQuery()); result.addProperty(COMMENT, getComment()); result.addProperty(IS_PERIODIC, isPeriodic()); return result; } @Override public void deserialize(final JsonObject json) { setQuery(json.getAsJsonPrimitive(QUERY).getAsString()); setComment(json.getAsJsonPrimitive(COMMENT).getAsString()); if (json.has(IS_PERIODIC)) { setIsPeriodic(json.getAsJsonPrimitive(IS_PERIODIC).getAsBoolean()); } } public void run() { run(true); } public void run(final boolean buildHUPPAALDocument) { runQuery.accept(buildHUPPAALDocument); } public void cancel() { if (getQueryState().equals(QueryState.RUNNING)) { synchronized (UPPAALDriver.engineLock) { if (engine != null) { forcedCancel = true; engine.cancel(); } } setQueryState(QueryState.UNKNOWN); } } }
src/main/java/dk/cs/aau/huppaal/abstractions/Query.java
package dk.cs.aau.huppaal.abstractions; import dk.cs.aau.huppaal.HUPPAAL; import dk.cs.aau.huppaal.backend.QueryListener; import dk.cs.aau.huppaal.backend.UPPAALDriver; import dk.cs.aau.huppaal.controllers.HUPPAALController; import dk.cs.aau.huppaal.utility.serialize.Serializable; import com.google.gson.JsonObject; import com.uppaal.engine.Engine; import javafx.application.Platform; import javafx.beans.property.*; import java.util.function.Consumer; public class Query implements Serializable { private static final String QUERY = "query"; private static final String COMMENT = "comment"; private static final String IS_PERIODIC = "is_periodic"; private final ObjectProperty<QueryState> queryState = new SimpleObjectProperty<>(QueryState.UNKNOWN); private final StringProperty query = new SimpleStringProperty(""); private final StringProperty comment = new SimpleStringProperty(""); private final SimpleBooleanProperty isPeriodic = new SimpleBooleanProperty(false); private Consumer<Boolean> runQuery; public Query(final String query, final String comment, final QueryState queryState) { this.query.set(query); this.comment.set(comment); this.queryState.set(queryState); initializeRunQuery(); } public Query(final JsonObject jsonElement) { deserialize(jsonElement); initializeRunQuery(); } public QueryState getQueryState() { return queryState.get(); } public void setQueryState(final QueryState queryState) { this.queryState.set(queryState); } public ObjectProperty<QueryState> queryStateProperty() { return queryState; } public String getQuery() { return query.get(); } public void setQuery(final String query) { this.query.set(query); } public StringProperty queryProperty() { return query; } public String getComment() { return comment.get(); } public void setComment(final String comment) { this.comment.set(comment); } public StringProperty commentProperty() { return comment; } public boolean isPeriodic() { return isPeriodic.get(); } public SimpleBooleanProperty isPeriodicProperty() { return isPeriodic; } public void setIsPeriodic(final boolean isPeriodic) { this.isPeriodic.set(isPeriodic); } private Engine engine = null; private Boolean forcedCancel = false; private void initializeRunQuery() { runQuery = (buildHUPPAALDocument) -> { setQueryState(QueryState.RUNNING); final Component mainComponent = HUPPAAL.getProject().getMainComponent(); if (mainComponent == null) { return; // We cannot generate a UPPAAL file without a main component } try { if (buildHUPPAALDocument) { UPPAALDriver.buildHUPPAALDocument(); } UPPAALDriver.runQuery(getQuery(), aBoolean -> { if (aBoolean) { setQueryState(QueryState.SUCCESSFUL); } else { setQueryState(QueryState.ERROR); } }, e -> { if (forcedCancel) { setQueryState(QueryState.UNKNOWN); } else { setQueryState(QueryState.SYNTAX_ERROR); final Throwable cause = e.getCause(); if (cause != null) { // We had trouble generating the model if we get a NullPointerException if(cause instanceof NullPointerException) { setQueryState(QueryState.UNKNOWN); } else { Platform.runLater(() -> HUPPAALController.openQueryDialog(this, cause.toString())); } } } }, eng -> { engine = eng; }, new QueryListener(this) ).start(); } catch (final Exception e) { e.printStackTrace(); setQueryState(QueryState.ERROR); //Todo: handle Fork has an edge to something that s not a subcomponent } }; } @Override public JsonObject serialize() { final JsonObject result = new JsonObject(); result.addProperty(QUERY, getQuery()); result.addProperty(COMMENT, getComment()); result.addProperty(IS_PERIODIC, isPeriodic()); return result; } @Override public void deserialize(final JsonObject json) { setQuery(json.getAsJsonPrimitive(QUERY).getAsString()); setComment(json.getAsJsonPrimitive(COMMENT).getAsString()); if (json.has(IS_PERIODIC)) { setIsPeriodic(json.getAsJsonPrimitive(IS_PERIODIC).getAsBoolean()); } } public void run() { run(true); } public void run(final boolean buildHUPPAALDocument) { runQuery.accept(buildHUPPAALDocument); } public void cancel() { if (getQueryState().equals(QueryState.RUNNING)) { synchronized (UPPAALDriver.engineLock) { if (engine != null) { forcedCancel = true; engine.cancel(); } } setQueryState(QueryState.UNKNOWN); } } }
Run query error handling
src/main/java/dk/cs/aau/huppaal/abstractions/Query.java
Run query error handling
<ide><path>rc/main/java/dk/cs/aau/huppaal/abstractions/Query.java <ide> import javafx.beans.property.*; <ide> <ide> import java.util.function.Consumer; <add> <add>import static dk.cs.aau.huppaal.HUPPAAL.showToast; <ide> <ide> public class Query implements Serializable { <ide> private static final String QUERY = "query"; <ide> } catch (final Exception e) { <ide> e.printStackTrace(); <ide> setQueryState(QueryState.ERROR); <del> //Todo: handle Fork has an edge to something that s not a subcomponent <add> showToast("Query failed: " + e.getMessage()); <ide> } <ide> }; <ide> }
Java
apache-2.0
dfc0b7144bd3ec26d6f3a6c73a9a4b1d362a99e5
0
pax95/camel,cunningt/camel,gnodet/camel,tadayosi/camel,apache/camel,pax95/camel,pmoerenhout/camel,nicolaferraro/camel,tdiesler/camel,DariusX/camel,pax95/camel,gnodet/camel,nikhilvibhav/camel,apache/camel,pmoerenhout/camel,tdiesler/camel,gnodet/camel,christophd/camel,DariusX/camel,pmoerenhout/camel,adessaigne/camel,alvinkwekel/camel,mcollovati/camel,christophd/camel,ullgren/camel,DariusX/camel,tdiesler/camel,zregvart/camel,cunningt/camel,nicolaferraro/camel,christophd/camel,cunningt/camel,alvinkwekel/camel,pax95/camel,christophd/camel,pax95/camel,cunningt/camel,nikhilvibhav/camel,tadayosi/camel,adessaigne/camel,cunningt/camel,nikhilvibhav/camel,tadayosi/camel,mcollovati/camel,adessaigne/camel,alvinkwekel/camel,adessaigne/camel,nikhilvibhav/camel,cunningt/camel,apache/camel,apache/camel,christophd/camel,nicolaferraro/camel,ullgren/camel,mcollovati/camel,alvinkwekel/camel,pmoerenhout/camel,zregvart/camel,tdiesler/camel,pmoerenhout/camel,tdiesler/camel,mcollovati/camel,ullgren/camel,zregvart/camel,tdiesler/camel,nicolaferraro/camel,christophd/camel,gnodet/camel,apache/camel,tadayosi/camel,ullgren/camel,DariusX/camel,pmoerenhout/camel,zregvart/camel,tadayosi/camel,pax95/camel,tadayosi/camel,gnodet/camel,adessaigne/camel,apache/camel,adessaigne/camel
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.builder; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.camel.Endpoint; import org.apache.camel.model.AdviceWithDefinition; import org.apache.camel.model.ChoiceDefinition; import org.apache.camel.model.EndpointRequiredDefinition; import org.apache.camel.model.FromDefinition; import org.apache.camel.model.InterceptDefinition; import org.apache.camel.model.InterceptSendToEndpointDefinition; import org.apache.camel.model.OnCompletionDefinition; import org.apache.camel.model.OnExceptionDefinition; import org.apache.camel.model.PipelineDefinition; import org.apache.camel.model.ProcessorDefinition; import org.apache.camel.model.ProcessorDefinitionHelper; import org.apache.camel.model.RouteDefinition; import org.apache.camel.model.TransactedDefinition; import org.apache.camel.support.PatternHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * {@link AdviceWithTask} tasks which are used by the * {@link AdviceWithRouteBuilder}. */ public final class AdviceWithTasks { private static final Logger LOG = LoggerFactory.getLogger(AdviceWithTasks.class); private AdviceWithTasks() { // utility class } /** * Match by is used for pluggable match by logic. */ private interface MatchBy { String getId(); boolean match(ProcessorDefinition<?> processor); } /** * Will match by id of the processor. */ private static final class MatchById implements MatchBy { private final String id; private MatchById(String id) { this.id = id; } @Override public String getId() { return id; } @Override public boolean match(ProcessorDefinition<?> processor) { if (id.equals("*")) { // make sure the processor which id isn't be set is matched. return true; } return PatternHelper.matchPattern(processor.getId(), id); } } /** * Will match by the to string representation of the processor. */ private static final class MatchByToString implements MatchBy { private final String toString; private MatchByToString(String toString) { this.toString = toString; } @Override public String getId() { return toString; } @Override public boolean match(ProcessorDefinition<?> processor) { return PatternHelper.matchPattern(processor.toString(), toString); } } /** * Will match by the sending to endpoint uri representation of the * processor. */ private static final class MatchByToUri implements MatchBy { private final String toUri; private MatchByToUri(String toUri) { this.toUri = toUri; } @Override public String getId() { return toUri; } @Override public boolean match(ProcessorDefinition<?> processor) { if (processor instanceof EndpointRequiredDefinition) { String uri = ((EndpointRequiredDefinition)processor).getEndpointUri(); return PatternHelper.matchPattern(uri, toUri); } return false; } } /** * Will match by the type of the processor. */ private static final class MatchByType implements MatchBy { private final Class<?> type; private MatchByType(Class<?> type) { this.type = type; } @Override public String getId() { return type.getSimpleName(); } @Override public boolean match(ProcessorDefinition<?> processor) { return type.isAssignableFrom(processor.getClass()); } } public static AdviceWithTask replaceByToString(final RouteDefinition route, final String toString, final ProcessorDefinition<?> replace, boolean selectFirst, boolean selectLast, int selectFrom, int selectTo, int maxDeep) { MatchBy matchBy = new MatchByToString(toString); return doReplace(route, matchBy, replace, selectFirst, selectLast, selectFrom, selectTo, maxDeep); } public static AdviceWithTask replaceByToUri(final RouteDefinition route, final String toUri, final ProcessorDefinition<?> replace, boolean selectFirst, boolean selectLast, int selectFrom, int selectTo, int maxDeep) { MatchBy matchBy = new MatchByToUri(toUri); return doReplace(route, matchBy, replace, selectFirst, selectLast, selectFrom, selectTo, maxDeep); } public static AdviceWithTask replaceById(final RouteDefinition route, final String id, final ProcessorDefinition<?> replace, boolean selectFirst, boolean selectLast, int selectFrom, int selectTo, int maxDeep) { MatchBy matchBy = new MatchById(id); return doReplace(route, matchBy, replace, selectFirst, selectLast, selectFrom, selectTo, maxDeep); } public static AdviceWithTask replaceByType(final RouteDefinition route, final Class<?> type, final ProcessorDefinition<?> replace, boolean selectFirst, boolean selectLast, int selectFrom, int selectTo, int maxDeep) { MatchBy matchBy = new MatchByType(type); return doReplace(route, matchBy, replace, selectFirst, selectLast, selectFrom, selectTo, maxDeep); } private static AdviceWithTask doReplace(final RouteDefinition route, final MatchBy matchBy, final ProcessorDefinition<?> replace, boolean selectFirst, boolean selectLast, int selectFrom, int selectTo, int maxDeep) { return new AdviceWithTask() { public void task() throws Exception { Iterator<ProcessorDefinition<?>> it = AdviceWithTasks.createMatchByIterator(route, matchBy, selectFirst, selectLast, selectFrom, selectTo, maxDeep); boolean match = false; while (it.hasNext()) { ProcessorDefinition<?> output = it.next(); if (matchBy.match(output)) { List<ProcessorDefinition<?>> outputs = getOutputs(output, route); if (outputs != null) { int index = outputs.indexOf(output); if (index != -1) { match = true; // flattern as replace uses a pipeline as // temporary holder ProcessorDefinition<?> flattern = flatternOutput(replace); outputs.add(index + 1, flattern); Object old = outputs.remove(index); // must set parent on the node we added in the // route ProcessorDefinition parent = output.getParent() != null ? output.getParent() : route; flattern.setParent(parent); LOG.info("AdviceWith ({}) : [{}] --> replace [{}]", matchBy.getId(), old, flattern); } } } } if (!match) { throw new IllegalArgumentException("There are no outputs which matches: " + matchBy.getId() + " in the route: " + route); } } }; } public static AdviceWithTask removeByToString(final RouteDefinition route, final String toString, boolean selectFirst, boolean selectLast, int selectFrom, int selectTo, int maxDeep) { MatchBy matchBy = new MatchByToString(toString); return doRemove(route, matchBy, selectFirst, selectLast, selectFrom, selectTo, maxDeep); } public static AdviceWithTask removeByToUri(final RouteDefinition route, final String toUri, boolean selectFirst, boolean selectLast, int selectFrom, int selectTo, int maxDeep) { MatchBy matchBy = new MatchByToUri(toUri); return doRemove(route, matchBy, selectFirst, selectLast, selectFrom, selectTo, maxDeep); } public static AdviceWithTask removeById(final RouteDefinition route, final String id, boolean selectFirst, boolean selectLast, int selectFrom, int selectTo, int maxDeep) { MatchBy matchBy = new MatchById(id); return doRemove(route, matchBy, selectFirst, selectLast, selectFrom, selectTo, maxDeep); } public static AdviceWithTask removeByType(final RouteDefinition route, final Class<?> type, boolean selectFirst, boolean selectLast, int selectFrom, int selectTo, int maxDeep) { MatchBy matchBy = new MatchByType(type); return doRemove(route, matchBy, selectFirst, selectLast, selectFrom, selectTo, maxDeep); } private static AdviceWithTask doRemove(final RouteDefinition route, final MatchBy matchBy, boolean selectFirst, boolean selectLast, int selectFrom, int selectTo, int maxDeep) { return new AdviceWithTask() { public void task() throws Exception { boolean match = false; Iterator<ProcessorDefinition<?>> it = AdviceWithTasks.createMatchByIterator(route, matchBy, selectFirst, selectLast, selectFrom, selectTo, maxDeep); while (it.hasNext()) { ProcessorDefinition<?> output = it.next(); if (matchBy.match(output)) { List<ProcessorDefinition<?>> outputs = getOutputs(output, route); if (outputs != null) { int index = outputs.indexOf(output); if (index != -1) { match = true; Object old = outputs.remove(index); LOG.info("AdviceWith ({}) : [{}] --> remove", matchBy.getId(), old); } } } } if (!match) { throw new IllegalArgumentException("There are no outputs which matches: " + matchBy.getId() + " in the route: " + route); } } }; } public static AdviceWithTask beforeByToString(final RouteDefinition route, final String toString, final ProcessorDefinition<?> before, boolean selectFirst, boolean selectLast, int selectFrom, int selectTo, int maxDeep) { MatchBy matchBy = new MatchByToString(toString); return doBefore(route, matchBy, before, selectFirst, selectLast, selectFrom, selectTo, maxDeep); } public static AdviceWithTask beforeByToUri(final RouteDefinition route, final String toUri, final ProcessorDefinition<?> before, boolean selectFirst, boolean selectLast, int selectFrom, int selectTo, int maxDeep) { MatchBy matchBy = new MatchByToUri(toUri); return doBefore(route, matchBy, before, selectFirst, selectLast, selectFrom, selectTo, maxDeep); } public static AdviceWithTask beforeById(final RouteDefinition route, final String id, final ProcessorDefinition<?> before, boolean selectFirst, boolean selectLast, int selectFrom, int selectTo, int maxDeep) { MatchBy matchBy = new MatchById(id); return doBefore(route, matchBy, before, selectFirst, selectLast, selectFrom, selectTo, maxDeep); } public static AdviceWithTask beforeByType(final RouteDefinition route, final Class<?> type, final ProcessorDefinition<?> before, boolean selectFirst, boolean selectLast, int selectFrom, int selectTo, int maxDeep) { MatchBy matchBy = new MatchByType(type); return doBefore(route, matchBy, before, selectFirst, selectLast, selectFrom, selectTo, maxDeep); } private static AdviceWithTask doBefore(final RouteDefinition route, final MatchBy matchBy, final ProcessorDefinition<?> before, boolean selectFirst, boolean selectLast, int selectFrom, int selectTo, int maxDeep) { return new AdviceWithTask() { public void task() throws Exception { boolean match = false; Iterator<ProcessorDefinition<?>> it = AdviceWithTasks.createMatchByIterator(route, matchBy, selectFirst, selectLast, selectFrom, selectTo, maxDeep); while (it.hasNext()) { ProcessorDefinition<?> output = it.next(); if (matchBy.match(output)) { List<ProcessorDefinition<?>> outputs = getOutputs(output, route); if (outputs != null) { int index = outputs.indexOf(output); if (index != -1) { match = true; // flattern as before uses a pipeline as // temporary holder ProcessorDefinition<?> flattern = flatternOutput(before); Object existing = outputs.get(index); outputs.add(index, flattern); // must set parent on the node we added in the // route ProcessorDefinition parent = output.getParent() != null ? output.getParent() : route; flattern.setParent(parent); LOG.info("AdviceWith ({}) : [{}] --> before [{}]", matchBy.getId(), existing, flattern); } } } } if (!match) { throw new IllegalArgumentException("There are no outputs which matches: " + matchBy.getId() + " in the route: " + route); } } }; } public static AdviceWithTask afterByToString(final RouteDefinition route, final String toString, final ProcessorDefinition<?> after, boolean selectFirst, boolean selectLast, int selectFrom, int selectTo, int maxDeep) { MatchBy matchBy = new MatchByToString(toString); return doAfter(route, matchBy, after, selectFirst, selectLast, selectFrom, selectTo, maxDeep); } public static AdviceWithTask afterByToUri(final RouteDefinition route, final String toUri, final ProcessorDefinition<?> after, boolean selectFirst, boolean selectLast, int selectFrom, int selectTo, int maxDeep) { MatchBy matchBy = new MatchByToUri(toUri); return doAfter(route, matchBy, after, selectFirst, selectLast, selectFrom, selectTo, maxDeep); } public static AdviceWithTask afterById(final RouteDefinition route, final String id, final ProcessorDefinition<?> after, boolean selectFirst, boolean selectLast, int selectFrom, int selectTo, int maxDeep) { MatchBy matchBy = new MatchById(id); return doAfter(route, matchBy, after, selectFirst, selectLast, selectFrom, selectTo, maxDeep); } public static AdviceWithTask afterByType(final RouteDefinition route, final Class<?> type, final ProcessorDefinition<?> after, boolean selectFirst, boolean selectLast, int selectFrom, int selectTo, int maxDeep) { MatchBy matchBy = new MatchByType(type); return doAfter(route, matchBy, after, selectFirst, selectLast, selectFrom, selectTo, maxDeep); } private static AdviceWithTask doAfter(final RouteDefinition route, final MatchBy matchBy, final ProcessorDefinition<?> after, boolean selectFirst, boolean selectLast, int selectFrom, int selectTo, int maxDeep) { return new AdviceWithTask() { public void task() throws Exception { boolean match = false; Iterator<ProcessorDefinition<?>> it = AdviceWithTasks.createMatchByIterator(route, matchBy, selectFirst, selectLast, selectFrom, selectTo, maxDeep); while (it.hasNext()) { ProcessorDefinition<?> output = it.next(); if (matchBy.match(output)) { List<ProcessorDefinition<?>> outputs = getOutputs(output, route); if (outputs != null) { int index = outputs.indexOf(output); if (index != -1) { match = true; // flattern as after uses a pipeline as // temporary holder ProcessorDefinition<?> flattern = flatternOutput(after); Object existing = outputs.get(index); outputs.add(index + 1, flattern); // must set parent on the node we added in the // route ProcessorDefinition parent = output.getParent() != null ? output.getParent() : route; flattern.setParent(parent); LOG.info("AdviceWith ({}) : [{}] --> after [{}]", matchBy.getId(), existing, flattern); } } } } if (!match) { throw new IllegalArgumentException("There are no outputs which matches: " + matchBy.getId() + " in the route: " + route); } } }; } /** * Gets the outputs to use with advice with from the given child/parent * <p/> * This implementation deals with that outputs can be abstract and retrieves * the <i>correct</i> parent output. * * @param node the node * @return <tt>null</tt> if not outputs to be used */ private static List<ProcessorDefinition<?>> getOutputs(ProcessorDefinition<?> node, RouteDefinition route) { if (node == null) { return null; } // for intercept/onException/onCompletion then we want to work on the // route outputs as they are top-level if (node instanceof InterceptDefinition) { return route.getOutputs(); } else if (node instanceof InterceptSendToEndpointDefinition) { return route.getOutputs(); } else if (node instanceof OnExceptionDefinition) { return route.getOutputs(); } else if (node instanceof OnCompletionDefinition) { return route.getOutputs(); } ProcessorDefinition<?> parent = node.getParent(); if (parent == null) { return null; } // for CBR then use the outputs from the node itself // so we work on the right branch in the CBR (when/otherwise) if (parent instanceof ChoiceDefinition) { return node.getOutputs(); } List<ProcessorDefinition<?>> outputs = parent.getOutputs(); if (outputs.size() == 1 && outputs.get(0).isAbstract()) { // if the output is abstract then get its output, as outputs = outputs.get(0).getOutputs(); } return outputs; } public static AdviceWithTask replaceFromWith(final RouteDefinition route, final String uri) { return new AdviceWithTask() { public void task() throws Exception { FromDefinition from = route.getInput(); LOG.info("AdviceWith replace input from [{}] --> [{}]", from.getEndpointUri(), uri); from.setEndpoint(null); from.setUri(uri); } }; } public static AdviceWithTask replaceFrom(final RouteDefinition route, final Endpoint endpoint) { return new AdviceWithTask() { public void task() throws Exception { FromDefinition from = route.getInput(); LOG.info("AdviceWith replace input from [{}] --> [{}]", from.getEndpointUri(), endpoint.getEndpointUri()); from.setUri(null); from.setEndpoint(endpoint); } }; } /** * Create iterator which walks the route, and only returns nodes which * matches the given set of criteria. * * @param route the route * @param matchBy match by which must match * @param selectFirst optional to select only the first * @param selectLast optional to select only the last * @param selectFrom optional to select index/range * @param selectTo optional to select index/range * @param maxDeep maximum levels deep (is unbounded by default) * @return the iterator */ private static Iterator<ProcessorDefinition<?>> createMatchByIterator(final RouteDefinition route, final MatchBy matchBy, final boolean selectFirst, final boolean selectLast, final int selectFrom, final int selectTo, int maxDeep) { // first iterator and apply match by List<ProcessorDefinition<?>> matched = new ArrayList<>(); List<ProcessorDefinition<?>> outputs = new ArrayList<>(); // if we are in first|last mode then we should // skip abstract nodes in the beginning as they are cross cutting // functionality such as onException, onCompletion etc // and the user want to select first or last outputs in the route (not // cross cutting functionality) boolean skip = selectFirst || selectLast; for (ProcessorDefinition output : route.getOutputs()) { // special for transacted, which we need to unwrap if (output instanceof TransactedDefinition) { outputs.addAll(output.getOutputs()); } else if (skip) { boolean invalid = outputs.isEmpty() && output.isAbstract(); if (!invalid) { outputs.add(output); } } else { outputs.add(output); } } @SuppressWarnings("rawtypes") Iterator<ProcessorDefinition> itAll = ProcessorDefinitionHelper.filterTypeInOutputs(outputs, ProcessorDefinition.class, maxDeep); while (itAll.hasNext()) { ProcessorDefinition<?> next = itAll.next(); if (matchBy.match(next)) { matched.add(next); } } // and then apply the selector iterator return createSelectorIterator(matched, selectFirst, selectLast, selectFrom, selectTo); } private static Iterator<ProcessorDefinition<?>> createSelectorIterator(final List<ProcessorDefinition<?>> list, final boolean selectFirst, final boolean selectLast, final int selectFrom, final int selectTo) { return new Iterator<ProcessorDefinition<?>>() { private int current; private boolean done; @Override public boolean hasNext() { if (list.isEmpty() || done) { return false; } if (selectFirst) { done = true; // spool to first current = 0; return true; } if (selectLast) { done = true; // spool to last current = list.size() - 1; return true; } if (selectFrom >= 0 && selectTo >= 0) { // check for out of bounds if (selectFrom >= list.size() || selectTo >= list.size()) { return false; } if (current < selectFrom) { // spool to beginning of range current = selectFrom; } return current <= selectTo; } return current < list.size(); } @Override public ProcessorDefinition<?> next() { ProcessorDefinition<?> answer = list.get(current); current++; return answer; } @Override public void remove() { // noop } }; } private static ProcessorDefinition<?> flatternOutput(ProcessorDefinition<?> output) { if (output instanceof AdviceWithDefinition) { AdviceWithDefinition advice = (AdviceWithDefinition)output; if (advice.getOutputs().size() == 1) { return advice.getOutputs().get(0); } else { // it should be a pipeline PipelineDefinition pipe = new PipelineDefinition(); pipe.setOutputs(advice.getOutputs()); return pipe; } } return output; } }
core/camel-core-engine/src/main/java/org/apache/camel/builder/AdviceWithTasks.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.builder; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.camel.Endpoint; import org.apache.camel.model.AdviceWithDefinition; import org.apache.camel.model.ChoiceDefinition; import org.apache.camel.model.EndpointRequiredDefinition; import org.apache.camel.model.FromDefinition; import org.apache.camel.model.InterceptDefinition; import org.apache.camel.model.InterceptSendToEndpointDefinition; import org.apache.camel.model.OnCompletionDefinition; import org.apache.camel.model.OnExceptionDefinition; import org.apache.camel.model.PipelineDefinition; import org.apache.camel.model.ProcessorDefinition; import org.apache.camel.model.ProcessorDefinitionHelper; import org.apache.camel.model.RouteDefinition; import org.apache.camel.model.TransactedDefinition; import org.apache.camel.support.PatternHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * {@link AdviceWithTask} tasks which are used by the * {@link AdviceWithRouteBuilder}. */ public final class AdviceWithTasks { private static final Logger LOG = LoggerFactory.getLogger(AdviceWithTasks.class); private AdviceWithTasks() { // utility class } /** * Match by is used for pluggable match by logic. */ private interface MatchBy { String getId(); boolean match(ProcessorDefinition<?> processor); } /** * Will match by id of the processor. */ private static final class MatchById implements MatchBy { private final String id; private MatchById(String id) { this.id = id; } @Override public String getId() { return id; } @Override public boolean match(ProcessorDefinition<?> processor) { if (id.equals("*")) { // make sure the processor which id isn't be set is matched. return true; } return PatternHelper.matchPattern(processor.getId(), id); } } /** * Will match by the to string representation of the processor. */ private static final class MatchByToString implements MatchBy { private final String toString; private MatchByToString(String toString) { this.toString = toString; } @Override public String getId() { return toString; } @Override public boolean match(ProcessorDefinition<?> processor) { return PatternHelper.matchPattern(processor.toString(), toString); } } /** * Will match by the sending to endpoint uri representation of the * processor. */ private static final class MatchByToUri implements MatchBy { private final String toUri; private MatchByToUri(String toUri) { this.toUri = toUri; } @Override public String getId() { return toUri; } @Override public boolean match(ProcessorDefinition<?> processor) { if (processor instanceof EndpointRequiredDefinition) { String uri = ((EndpointRequiredDefinition)processor).getEndpointUri(); return PatternHelper.matchPattern(uri, toUri); } return false; } } /** * Will match by the type of the processor. */ private static final class MatchByType implements MatchBy { private final Class<?> type; private MatchByType(Class<?> type) { this.type = type; } @Override public String getId() { return type.getSimpleName(); } @Override public boolean match(ProcessorDefinition<?> processor) { return type.isAssignableFrom(processor.getClass()); } } public static AdviceWithTask replaceByToString(final RouteDefinition route, final String toString, final ProcessorDefinition<?> replace, boolean selectFirst, boolean selectLast, int selectFrom, int selectTo, int maxDeep) { MatchBy matchBy = new MatchByToString(toString); return doReplace(route, matchBy, replace, selectFirst, selectLast, selectFrom, selectTo, maxDeep); } public static AdviceWithTask replaceByToUri(final RouteDefinition route, final String toUri, final ProcessorDefinition<?> replace, boolean selectFirst, boolean selectLast, int selectFrom, int selectTo, int maxDeep) { MatchBy matchBy = new MatchByToUri(toUri); return doReplace(route, matchBy, replace, selectFirst, selectLast, selectFrom, selectTo, maxDeep); } public static AdviceWithTask replaceById(final RouteDefinition route, final String id, final ProcessorDefinition<?> replace, boolean selectFirst, boolean selectLast, int selectFrom, int selectTo, int maxDeep) { MatchBy matchBy = new MatchById(id); return doReplace(route, matchBy, replace, selectFirst, selectLast, selectFrom, selectTo, maxDeep); } public static AdviceWithTask replaceByType(final RouteDefinition route, final Class<?> type, final ProcessorDefinition<?> replace, boolean selectFirst, boolean selectLast, int selectFrom, int selectTo, int maxDeep) { MatchBy matchBy = new MatchByType(type); return doReplace(route, matchBy, replace, selectFirst, selectLast, selectFrom, selectTo, maxDeep); } private static AdviceWithTask doReplace(final RouteDefinition route, final MatchBy matchBy, final ProcessorDefinition<?> replace, boolean selectFirst, boolean selectLast, int selectFrom, int selectTo, int maxDeep) { return new AdviceWithTask() { public void task() throws Exception { Iterator<ProcessorDefinition<?>> it = AdviceWithTasks.createMatchByIterator(route, matchBy, selectFirst, selectLast, selectFrom, selectTo, maxDeep); boolean match = false; while (it.hasNext()) { ProcessorDefinition<?> output = it.next(); if (matchBy.match(output)) { List<ProcessorDefinition<?>> outputs = getOutputs(output, route); if (outputs != null) { int index = outputs.indexOf(output); if (index != -1) { match = true; // flattern as replace uses a pipeline as // temporary holder ProcessorDefinition<?> flattern = flatternOutput(replace); outputs.add(index + 1, flattern); Object old = outputs.remove(index); // must set parent on the node we added in the // route ProcessorDefinition parent = output.getParent() != null ? output.getParent() : route; flattern.setParent(parent); LOG.info("AdviceWith ({}) : [{}] --> replace [{}]", matchBy.getId(), old, flattern); } } } } if (!match) { throw new IllegalArgumentException("There are no outputs which matches: " + matchBy.getId() + " in the route: " + route); } } }; } public static AdviceWithTask removeByToString(final RouteDefinition route, final String toString, boolean selectFirst, boolean selectLast, int selectFrom, int selectTo, int maxDeep) { MatchBy matchBy = new MatchByToString(toString); return doRemove(route, matchBy, selectFirst, selectLast, selectFrom, selectTo, maxDeep); } public static AdviceWithTask removeByToUri(final RouteDefinition route, final String toUri, boolean selectFirst, boolean selectLast, int selectFrom, int selectTo, int maxDeep) { MatchBy matchBy = new MatchByToUri(toUri); return doRemove(route, matchBy, selectFirst, selectLast, selectFrom, selectTo, maxDeep); } public static AdviceWithTask removeById(final RouteDefinition route, final String id, boolean selectFirst, boolean selectLast, int selectFrom, int selectTo, int maxDeep) { MatchBy matchBy = new MatchById(id); return doRemove(route, matchBy, selectFirst, selectLast, selectFrom, selectTo, maxDeep); } public static AdviceWithTask removeByType(final RouteDefinition route, final Class<?> type, boolean selectFirst, boolean selectLast, int selectFrom, int selectTo, int maxDeep) { MatchBy matchBy = new MatchByType(type); return doRemove(route, matchBy, selectFirst, selectLast, selectFrom, selectTo, maxDeep); } private static AdviceWithTask doRemove(final RouteDefinition route, final MatchBy matchBy, boolean selectFirst, boolean selectLast, int selectFrom, int selectTo, int maxDeep) { return new AdviceWithTask() { public void task() throws Exception { boolean match = false; Iterator<ProcessorDefinition<?>> it = AdviceWithTasks.createMatchByIterator(route, matchBy, selectFirst, selectLast, selectFrom, selectTo, maxDeep); while (it.hasNext()) { ProcessorDefinition<?> output = it.next(); if (matchBy.match(output)) { List<ProcessorDefinition<?>> outputs = getOutputs(output, route); if (outputs != null) { int index = outputs.indexOf(output); if (index != -1) { match = true; Object old = outputs.remove(index); LOG.info("AdviceWith ({}) : [{}] --> remove", matchBy.getId(), old); } } } } if (!match) { throw new IllegalArgumentException("There are no outputs which matches: " + matchBy.getId() + " in the route: " + route); } } }; } public static AdviceWithTask beforeByToString(final RouteDefinition route, final String toString, final ProcessorDefinition<?> before, boolean selectFirst, boolean selectLast, int selectFrom, int selectTo, int maxDeep) { MatchBy matchBy = new MatchByToString(toString); return doBefore(route, matchBy, before, selectFirst, selectLast, selectFrom, selectTo, maxDeep); } public static AdviceWithTask beforeByToUri(final RouteDefinition route, final String toUri, final ProcessorDefinition<?> before, boolean selectFirst, boolean selectLast, int selectFrom, int selectTo, int maxDeep) { MatchBy matchBy = new MatchByToUri(toUri); return doBefore(route, matchBy, before, selectFirst, selectLast, selectFrom, selectTo, maxDeep); } public static AdviceWithTask beforeById(final RouteDefinition route, final String id, final ProcessorDefinition<?> before, boolean selectFirst, boolean selectLast, int selectFrom, int selectTo, int maxDeep) { MatchBy matchBy = new MatchById(id); return doBefore(route, matchBy, before, selectFirst, selectLast, selectFrom, selectTo, maxDeep); } public static AdviceWithTask beforeByType(final RouteDefinition route, final Class<?> type, final ProcessorDefinition<?> before, boolean selectFirst, boolean selectLast, int selectFrom, int selectTo, int maxDeep) { MatchBy matchBy = new MatchByType(type); return doBefore(route, matchBy, before, selectFirst, selectLast, selectFrom, selectTo, maxDeep); } private static AdviceWithTask doBefore(final RouteDefinition route, final MatchBy matchBy, final ProcessorDefinition<?> before, boolean selectFirst, boolean selectLast, int selectFrom, int selectTo, int maxDeep) { return new AdviceWithTask() { public void task() throws Exception { boolean match = false; Iterator<ProcessorDefinition<?>> it = AdviceWithTasks.createMatchByIterator(route, matchBy, selectFirst, selectLast, selectFrom, selectTo, maxDeep); while (it.hasNext()) { ProcessorDefinition<?> output = it.next(); if (matchBy.match(output)) { List<ProcessorDefinition<?>> outputs = getOutputs(output, route); if (outputs != null) { int index = outputs.indexOf(output); if (index != -1) { match = true; // flattern as before uses a pipeline as // temporary holder ProcessorDefinition<?> flattern = flatternOutput(before); Object existing = outputs.get(index); outputs.add(index, flattern); // must set parent on the node we added in the // route ProcessorDefinition parent = output.getParent() != null ? output.getParent() : route; flattern.setParent(parent); LOG.info("AdviceWith ({}) : [{}] --> before [{}]", matchBy.getId(), existing, flattern); } } } } if (!match) { throw new IllegalArgumentException("There are no outputs which matches: " + matchBy.getId() + " in the route: " + route); } } }; } public static AdviceWithTask afterByToString(final RouteDefinition route, final String toString, final ProcessorDefinition<?> after, boolean selectFirst, boolean selectLast, int selectFrom, int selectTo, int maxDeep) { MatchBy matchBy = new MatchByToString(toString); return doAfter(route, matchBy, after, selectFirst, selectLast, selectFrom, selectTo, maxDeep); } public static AdviceWithTask afterByToUri(final RouteDefinition route, final String toUri, final ProcessorDefinition<?> after, boolean selectFirst, boolean selectLast, int selectFrom, int selectTo, int maxDeep) { MatchBy matchBy = new MatchByToUri(toUri); return doAfter(route, matchBy, after, selectFirst, selectLast, selectFrom, selectTo, maxDeep); } public static AdviceWithTask afterById(final RouteDefinition route, final String id, final ProcessorDefinition<?> after, boolean selectFirst, boolean selectLast, int selectFrom, int selectTo, int maxDeep) { MatchBy matchBy = new MatchById(id); return doAfter(route, matchBy, after, selectFirst, selectLast, selectFrom, selectTo, maxDeep); } public static AdviceWithTask afterByType(final RouteDefinition route, final Class<?> type, final ProcessorDefinition<?> after, boolean selectFirst, boolean selectLast, int selectFrom, int selectTo, int maxDeep) { MatchBy matchBy = new MatchByType(type); return doAfter(route, matchBy, after, selectFirst, selectLast, selectFrom, selectTo, maxDeep); } private static AdviceWithTask doAfter(final RouteDefinition route, final MatchBy matchBy, final ProcessorDefinition<?> after, boolean selectFirst, boolean selectLast, int selectFrom, int selectTo, int maxDeep) { return new AdviceWithTask() { public void task() throws Exception { boolean match = false; Iterator<ProcessorDefinition<?>> it = AdviceWithTasks.createMatchByIterator(route, matchBy, selectFirst, selectLast, selectFrom, selectTo, maxDeep); while (it.hasNext()) { ProcessorDefinition<?> output = it.next(); if (matchBy.match(output)) { List<ProcessorDefinition<?>> outputs = getOutputs(output, route); if (outputs != null) { int index = outputs.indexOf(output); if (index != -1) { match = true; // flattern as after uses a pipeline as // temporary holder ProcessorDefinition<?> flattern = flatternOutput(after); Object existing = outputs.get(index); outputs.add(index + 1, flattern); // must set parent on the node we added in the // route ProcessorDefinition parent = output.getParent() != null ? output.getParent() : route; flattern.setParent(parent); LOG.info("AdviceWith ({}) : [{}] --> after [{}]", matchBy.getId(), existing, flattern); } } } } if (!match) { throw new IllegalArgumentException("There are no outputs which matches: " + matchBy.getId() + " in the route: " + route); } } }; } /** * Gets the outputs to use with advice with from the given child/parent * <p/> * This implementation deals with that outputs can be abstract and retrieves * the <i>correct</i> parent output. * * @param node the node * @return <tt>null</tt> if not outputs to be used */ private static List<ProcessorDefinition<?>> getOutputs(ProcessorDefinition<?> node, RouteDefinition route) { if (node == null) { return null; } // for intercept/onException/onCompletion then we want to work on the // route outputs as they are top-level if (node instanceof InterceptDefinition) { return route.getOutputs(); } else if (node instanceof InterceptSendToEndpointDefinition) { return route.getOutputs(); } else if (node instanceof OnExceptionDefinition) { return route.getOutputs(); } else if (node instanceof OnCompletionDefinition) { return route.getOutputs(); } ProcessorDefinition<?> parent = node.getParent(); if (parent == null) { return null; } // for CBR then use the outputs from the node itself // so we work on the right branch in the CBR (when/otherwise) if (parent instanceof ChoiceDefinition) { return node.getOutputs(); } List<ProcessorDefinition<?>> outputs = parent.getOutputs(); if (outputs.size() == 1 && outputs.get(0).isAbstract()) { // if the output is abstract then get its output, as outputs = outputs.get(0).getOutputs(); } return outputs; } public static AdviceWithTask replaceFromWith(final RouteDefinition route, final String uri) { return new AdviceWithTask() { public void task() throws Exception { FromDefinition from = route.getInput(); LOG.info("AdviceWith replace input from [{}] --> [{}]", from.getEndpointUri(), uri); from.setEndpoint(null); from.setUri(uri); } }; } public static AdviceWithTask replaceFrom(final RouteDefinition route, final Endpoint endpoint) { return new AdviceWithTask() { public void task() throws Exception { FromDefinition from = route.getInput(); LOG.info("AdviceWith replace input from [{}] --> [{}]", from.getEndpointUri(), endpoint.getEndpointUri()); from.setUri(null); from.setEndpoint(endpoint); } }; } /** * Create iterator which walks the route, and only returns nodes which * matches the given set of criteria. * * @param route the route * @param matchBy match by which must match * @param selectFirst optional to select only the first * @param selectLast optional to select only the last * @param selectFrom optional to select index/range * @param selectTo optional to select index/range * @param maxDeep maximum levels deep (is unbounded by default) * @return the iterator */ private static Iterator<ProcessorDefinition<?>> createMatchByIterator(final RouteDefinition route, final MatchBy matchBy, final boolean selectFirst, final boolean selectLast, final int selectFrom, final int selectTo, int maxDeep) { // first iterator and apply match by List<ProcessorDefinition<?>> matched = new ArrayList<>(); List<ProcessorDefinition<?>> outputs = new ArrayList<>(); // if we are in first|last mode then we should // skip abstract nodes in the beginning as they are cross cutting // functionality such as onException, onCompletion etc // and the user want to select first or last outputs in the route (not // cross cutting functionality) boolean skip = selectFirst || selectLast; for (ProcessorDefinition output : route.getOutputs()) { // special for transacted, which we need to unwrap if (output instanceof TransactedDefinition) { outputs.addAll(output.getOutputs()); } else if (skip) { boolean invalid = outputs.isEmpty() && output.isAbstract(); if (!invalid) { outputs.add(output); } } else { outputs.add(output); } } @SuppressWarnings("rawtypes") Iterator<ProcessorDefinition> itAll = ProcessorDefinitionHelper.filterTypeInOutputs(outputs, ProcessorDefinition.class, maxDeep); while (itAll.hasNext()) { ProcessorDefinition<?> next = itAll.next(); if (matchBy.match(next)) { matched.add(next); } } // and then apply the selector iterator return createSelectorIterator(matched, selectFirst, selectLast, selectFrom, selectTo); } private static Iterator<ProcessorDefinition<?>> createSelectorIterator(final List<ProcessorDefinition<?>> list, final boolean selectFirst, final boolean selectLast, final int selectFrom, final int selectTo) { return new Iterator<ProcessorDefinition<?>>() { private int current; private boolean done; @Override public boolean hasNext() { if (list.isEmpty() || done) { return false; } if (selectFirst) { done = true; // spool to first current = 0; return true; } if (selectLast) { done = true; // spool to last current = list.size() - 1; return true; } if (selectFrom >= 0 && selectTo >= 0) { // check for out of bounds if (selectFrom >= list.size() || selectTo >= list.size()) { return false; } if (current < selectFrom) { // spool to beginning of range current = selectFrom; } return current >= selectFrom && current <= selectTo; } return current < list.size(); } @Override public ProcessorDefinition<?> next() { ProcessorDefinition<?> answer = list.get(current); current++; return answer; } @Override public void remove() { // noop } }; } private static ProcessorDefinition<?> flatternOutput(ProcessorDefinition<?> output) { if (output instanceof AdviceWithDefinition) { AdviceWithDefinition advice = (AdviceWithDefinition)output; if (advice.getOutputs().size() == 1) { return advice.getOutputs().get(0); } else { // it should be a pipeline PipelineDefinition pipe = new PipelineDefinition(); pipe.setOutputs(advice.getOutputs()); return pipe; } } return output; } }
AdviceWithTasks#createSelectorIterator: Remove comparison test which is always true (as reported by lgtm.com).
core/camel-core-engine/src/main/java/org/apache/camel/builder/AdviceWithTasks.java
AdviceWithTasks#createSelectorIterator: Remove comparison test which is always true (as reported by lgtm.com).
<ide><path>ore/camel-core-engine/src/main/java/org/apache/camel/builder/AdviceWithTasks.java <ide> // spool to beginning of range <ide> current = selectFrom; <ide> } <del> return current >= selectFrom && current <= selectTo; <add> return current <= selectTo; <ide> } <ide> <ide> return current < list.size();
Java
apache-2.0
fe01730524602df80311c9a2fe0ee2e11752287e
0
qmx/jitescript
/** * Copyright 2011 Douglas Campos <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.qmx.jitescript; import org.objectweb.asm.Handle; import org.objectweb.asm.Label; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.FieldInsnNode; import org.objectweb.asm.tree.FrameNode; import org.objectweb.asm.tree.IincInsnNode; import org.objectweb.asm.tree.InsnList; import org.objectweb.asm.tree.InsnNode; import org.objectweb.asm.tree.IntInsnNode; import org.objectweb.asm.tree.InvokeDynamicInsnNode; import org.objectweb.asm.tree.JumpInsnNode; import org.objectweb.asm.tree.LabelNode; import org.objectweb.asm.tree.LdcInsnNode; import org.objectweb.asm.tree.LineNumberNode; import org.objectweb.asm.tree.LocalVariableNode; import org.objectweb.asm.tree.LookupSwitchInsnNode; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MultiANewArrayInsnNode; import org.objectweb.asm.tree.TableSwitchInsnNode; import org.objectweb.asm.tree.TryCatchBlockNode; import org.objectweb.asm.tree.TypeInsnNode; import org.objectweb.asm.tree.VarInsnNode; import java.io.PrintStream; import java.util.ArrayList; import java.util.List; import static me.qmx.jitescript.util.CodegenUtils.ci; import static me.qmx.jitescript.util.CodegenUtils.p; import static me.qmx.jitescript.util.CodegenUtils.params; import static me.qmx.jitescript.util.CodegenUtils.sig; /** * @author qmx */ public class CodeBlock implements Opcodes { private boolean DEBUG = false; private InsnList instructionList = new InsnList(); private List<TryCatchBlockNode> tryCatchBlockList = new ArrayList<TryCatchBlockNode>(); private List<LocalVariableNode> localVariableList = new ArrayList<LocalVariableNode>(); private List<String> localVariables = new ArrayList<String>(); private int arity = 0; private boolean returns = false; public CodeBlock() { } public CodeBlock(CodeBlock block) { this.arity = block.arity(); this.localVariables.addAll(block.localVariables); prepend(block); } public CodeBlock(int arity) { this.arity = arity; } public static CodeBlock newCodeBlock() { return new CodeBlock(); } public static CodeBlock newCodeBlock(int arity) { return new CodeBlock(arity); } public static CodeBlock newCodeBlock(CodeBlock block) { return new CodeBlock(block); } /** * Short-hand for specifying a set of aloads * * @param args list of aloads you want */ public CodeBlock aloadMany(int... args) { for (int arg : args) { aload(arg); } return this; } public CodeBlock aload(int arg0) { this.instructionList.add(new VarInsnNode(ALOAD, arg0)); return this; } public CodeBlock iload(int arg0) { this.instructionList.add(new VarInsnNode(ILOAD, arg0)); return this; } public CodeBlock lload(int arg0) { this.instructionList.add(new VarInsnNode(LLOAD, arg0)); return this; } public CodeBlock fload(int arg0) { this.instructionList.add(new VarInsnNode(FLOAD, arg0)); return this; } public CodeBlock dload(int arg0) { this.instructionList.add(new VarInsnNode(DLOAD, arg0)); return this; } public CodeBlock astore(int arg0) { this.instructionList.add(new VarInsnNode(ASTORE, arg0)); return this; } public CodeBlock istore(int arg0) { this.instructionList.add(new VarInsnNode(ISTORE, arg0)); return this; } public CodeBlock lstore(int arg0) { this.instructionList.add(new VarInsnNode(LSTORE, arg0)); return this; } public CodeBlock fstore(int arg0) { this.instructionList.add(new VarInsnNode(FSTORE, arg0)); return this; } public CodeBlock dstore(int arg0) { this.instructionList.add(new VarInsnNode(DSTORE, arg0)); return this; } public CodeBlock ldc(Object arg0) { this.instructionList.add(new LdcInsnNode(arg0)); return this; } public CodeBlock bipush(int arg) { this.instructionList.add(new IntInsnNode(BIPUSH, arg)); return this; } public CodeBlock sipush(int arg) { this.instructionList.add(new IntInsnNode(SIPUSH, arg)); return this; } public CodeBlock pushInt(int value) { if (value <= Byte.MAX_VALUE && value >= Byte.MIN_VALUE) { switch (value) { case -1: iconst_m1(); break; case 0: iconst_0(); break; case 1: iconst_1(); break; case 2: iconst_2(); break; case 3: iconst_3(); break; case 4: iconst_4(); break; case 5: iconst_5(); break; default: bipush(value); break; } } else if (value <= Short.MAX_VALUE && value >= Short.MIN_VALUE) { sipush(value); } else { ldc(value); } return this; } public CodeBlock pushBoolean(boolean bool) { if (bool) { iconst_1(); } else { iconst_0(); } return this; } public CodeBlock invokestatic(String arg1, String arg2, String arg3) { this.instructionList.add(new MethodInsnNode(INVOKESTATIC, arg1, arg2, arg3)); return this; } public CodeBlock invokespecial(String arg1, String arg2, String arg3) { this.instructionList.add(new MethodInsnNode(INVOKESPECIAL, arg1, arg2, arg3)); return this; } public CodeBlock invokevirtual(String arg1, String arg2, String arg3) { this.instructionList.add(new MethodInsnNode(INVOKEVIRTUAL, arg1, arg2, arg3)); return this; } public CodeBlock invokeinterface(String arg1, String arg2, String arg3) { this.instructionList.add(new MethodInsnNode(INVOKEINTERFACE, arg1, arg2, arg3)); return this; } public CodeBlock invokedynamic(String arg0, String arg1, Handle arg2, Object... arg3) { this.instructionList.add(new InvokeDynamicInsnNode(arg0, arg1, arg2, arg3)); return this; } public CodeBlock aprintln() { dup(); getstatic(p(System.class), "out", ci(PrintStream.class)); swap(); invokevirtual(p(PrintStream.class), "println", sig(void.class, params(Object.class))); return this; } public CodeBlock iprintln() { dup(); getstatic(p(System.class), "out", ci(PrintStream.class)); swap(); invokevirtual(p(PrintStream.class), "println", sig(void.class, params(int.class))); return this; } public CodeBlock areturn() { this.returns = true; this.instructionList.add(new InsnNode(ARETURN)); return this; } public CodeBlock ireturn() { this.instructionList.add(new InsnNode(IRETURN)); return this; } public CodeBlock freturn() { this.instructionList.add(new InsnNode(FRETURN)); return this; } public CodeBlock lreturn() { this.instructionList.add(new InsnNode(LRETURN)); return this; } public CodeBlock dreturn() { this.instructionList.add(new InsnNode(DRETURN)); return this; } public CodeBlock newobj(String arg0) { this.instructionList.add(new TypeInsnNode(NEW, arg0)); return this; } public CodeBlock dup() { this.instructionList.add(new InsnNode(DUP)); return this; } public CodeBlock swap() { this.instructionList.add(new InsnNode(SWAP)); return this; } public CodeBlock swap2() { dup2_x2(); pop2(); return this; } public CodeBlock getstatic(String arg1, String arg2, String arg3) { this.instructionList.add(new FieldInsnNode(GETSTATIC, arg1, arg2, arg3)); return this; } public CodeBlock putstatic(String arg1, String arg2, String arg3) { this.instructionList.add(new FieldInsnNode(PUTSTATIC, arg1, arg2, arg3)); return this; } public CodeBlock getfield(String arg1, String arg2, String arg3) { this.instructionList.add(new FieldInsnNode(GETFIELD, arg1, arg2, arg3)); return this; } public CodeBlock putfield(String arg1, String arg2, String arg3) { this.instructionList.add(new FieldInsnNode(PUTFIELD, arg1, arg2, arg3)); return this; } public CodeBlock voidreturn() { this.instructionList.add(new InsnNode(RETURN)); return this; } public CodeBlock anewarray(String arg0) { this.instructionList.add(new TypeInsnNode(ANEWARRAY, arg0)); return this; } public CodeBlock multianewarray(String arg0, int dims) { this.instructionList.add(new MultiANewArrayInsnNode(arg0, dims)); return this; } public CodeBlock newarray(int arg0) { this.instructionList.add(new IntInsnNode(NEWARRAY, arg0)); return this; } public CodeBlock iconst_m1() { this.instructionList.add(new InsnNode(ICONST_M1)); return this; } public CodeBlock iconst_0() { this.instructionList.add(new InsnNode(ICONST_0)); return this; } public CodeBlock iconst_1() { this.instructionList.add(new InsnNode(ICONST_1)); return this; } public CodeBlock iconst_2() { this.instructionList.add(new InsnNode(ICONST_2)); return this; } public CodeBlock iconst_3() { this.instructionList.add(new InsnNode(ICONST_3)); return this; } public CodeBlock iconst_4() { this.instructionList.add(new InsnNode(ICONST_4)); return this; } public CodeBlock iconst_5() { this.instructionList.add(new InsnNode(ICONST_5)); return this; } public CodeBlock lconst_0() { this.instructionList.add(new InsnNode(LCONST_0)); return this; } public CodeBlock aconst_null() { this.instructionList.add(new InsnNode(ACONST_NULL)); return this; } public CodeBlock label(LabelNode labelNode) { this.instructionList.add(labelNode); return this; } public CodeBlock nop() { this.instructionList.add(new InsnNode(NOP)); return this; } public CodeBlock pop() { this.instructionList.add(new InsnNode(POP)); return this; } public CodeBlock pop2() { this.instructionList.add(new InsnNode(POP2)); return this; } public CodeBlock arrayload() { this.instructionList.add(new InsnNode(AALOAD)); return this; } public CodeBlock arraystore() { this.instructionList.add(new InsnNode(AASTORE)); return this; } public CodeBlock iarrayload() { this.instructionList.add(new InsnNode(IALOAD)); return this; } public CodeBlock barrayload() { this.instructionList.add(new InsnNode(BALOAD)); return this; } public CodeBlock barraystore() { this.instructionList.add(new InsnNode(BASTORE)); return this; } public CodeBlock aaload() { this.instructionList.add(new InsnNode(AALOAD)); return this; } public CodeBlock aastore() { this.instructionList.add(new InsnNode(AASTORE)); return this; } public CodeBlock iaload() { this.instructionList.add(new InsnNode(IALOAD)); return this; } public CodeBlock iastore() { this.instructionList.add(new InsnNode(IASTORE)); return this; } public CodeBlock laload() { this.instructionList.add(new InsnNode(LALOAD)); return this; } public CodeBlock lastore() { this.instructionList.add(new InsnNode(LASTORE)); return this; } public CodeBlock baload() { this.instructionList.add(new InsnNode(BALOAD)); return this; } public CodeBlock bastore() { this.instructionList.add(new InsnNode(BASTORE)); return this; } public CodeBlock saload() { this.instructionList.add(new InsnNode(SALOAD)); return this; } public CodeBlock sastore() { this.instructionList.add(new InsnNode(SASTORE)); return this; } public CodeBlock caload() { this.instructionList.add(new InsnNode(CALOAD)); return this; } public CodeBlock castore() { this.instructionList.add(new InsnNode(CASTORE)); return this; } public CodeBlock faload() { this.instructionList.add(new InsnNode(FALOAD)); return this; } public CodeBlock fastore() { this.instructionList.add(new InsnNode(FASTORE)); return this; } public CodeBlock daload() { this.instructionList.add(new InsnNode(DALOAD)); return this; } public CodeBlock dastore() { this.instructionList.add(new InsnNode(DASTORE)); return this; } public CodeBlock fcmpl() { this.instructionList.add(new InsnNode(FCMPL)); return this; } public CodeBlock fcmpg() { this.instructionList.add(new InsnNode(FCMPG)); return this; } public CodeBlock dcmpl() { this.instructionList.add(new InsnNode(DCMPL)); return this; } public CodeBlock dcmpg() { this.instructionList.add(new InsnNode(DCMPG)); return this; } public CodeBlock dup_x2() { this.instructionList.add(new InsnNode(DUP_X2)); return this; } public CodeBlock dup_x1() { this.instructionList.add(new InsnNode(DUP_X1)); return this; } public CodeBlock dup2_x2() { this.instructionList.add(new InsnNode(DUP2_X2)); return this; } public CodeBlock dup2_x1() { this.instructionList.add(new InsnNode(DUP2_X1)); return this; } public CodeBlock dup2() { this.instructionList.add(new InsnNode(DUP2)); return this; } public CodeBlock trycatch(LabelNode arg0, LabelNode arg1, LabelNode arg2, String arg3) { this.tryCatchBlockList.add(new TryCatchBlockNode(arg0, arg1, arg2, arg3)); return this; } public CodeBlock trycatch(String type, Runnable body, Runnable catchBody) { LabelNode before = new LabelNode(); LabelNode after = new LabelNode(); LabelNode catchStart = new LabelNode(); LabelNode done = new LabelNode(); trycatch(before, after, catchStart, type); label(before); body.run(); label(after); go_to(done); if (catchBody != null) { label(catchStart); catchBody.run(); } label(done); return this; } public CodeBlock go_to(LabelNode arg0) { this.instructionList.add(new JumpInsnNode(GOTO, arg0)); return this; } public CodeBlock lookupswitch(LabelNode arg0, int[] arg1, LabelNode[] arg2) { this.instructionList.add(new LookupSwitchInsnNode(arg0, arg1, arg2)); return this; } public CodeBlock athrow() { this.instructionList.add(new InsnNode(ATHROW)); return this; } public CodeBlock instance_of(String arg0) { this.instructionList.add(new TypeInsnNode(INSTANCEOF, arg0)); return this; } public CodeBlock ifeq(LabelNode arg0) { this.instructionList.add(new JumpInsnNode(IFEQ, arg0)); return this; } public CodeBlock iffalse(LabelNode arg0) { ifeq(arg0); return this; } public CodeBlock ifne(LabelNode arg0) { this.instructionList.add(new JumpInsnNode(IFNE, arg0)); return this; } public CodeBlock iftrue(LabelNode arg0) { ifne(arg0); return this; } public CodeBlock if_acmpne(LabelNode arg0) { this.instructionList.add(new JumpInsnNode(IF_ACMPNE, arg0)); return this; } public CodeBlock if_acmpeq(LabelNode arg0) { this.instructionList.add(new JumpInsnNode(IF_ACMPEQ, arg0)); return this; } public CodeBlock if_icmple(LabelNode arg0) { this.instructionList.add(new JumpInsnNode(IF_ICMPLE, arg0)); return this; } public CodeBlock if_icmpgt(LabelNode arg0) { this.instructionList.add(new JumpInsnNode(IF_ICMPGT, arg0)); return this; } public CodeBlock if_icmplt(LabelNode arg0) { this.instructionList.add(new JumpInsnNode(IF_ICMPLT, arg0)); return this; } public CodeBlock if_icmpne(LabelNode arg0) { this.instructionList.add(new JumpInsnNode(IF_ICMPNE, arg0)); return this; } public CodeBlock if_icmpeq(LabelNode arg0) { this.instructionList.add(new JumpInsnNode(IF_ICMPEQ, arg0)); return this; } public CodeBlock checkcast(String arg0) { this.instructionList.add(new TypeInsnNode(CHECKCAST, arg0)); return this; } public CodeBlock line(int line) { visitLineNumber(line, new LabelNode()); return this; } public CodeBlock line(int line, LabelNode label) { visitLineNumber(line, label); return this; } public CodeBlock ifnonnull(LabelNode arg0) { this.instructionList.add(new JumpInsnNode(IFNONNULL, arg0)); return this; } public CodeBlock ifnull(LabelNode arg0) { this.instructionList.add(new JumpInsnNode(IFNULL, arg0)); return this; } public CodeBlock iflt(LabelNode arg0) { this.instructionList.add(new JumpInsnNode(IFLT, arg0)); return this; } public CodeBlock ifle(LabelNode arg0) { this.instructionList.add(new JumpInsnNode(IFLE, arg0)); return this; } public CodeBlock ifgt(LabelNode arg0) { this.instructionList.add(new JumpInsnNode(IFGT, arg0)); return this; } public CodeBlock ifge(LabelNode arg0) { this.instructionList.add(new JumpInsnNode(IFGE, arg0)); return this; } public CodeBlock arraylength() { this.instructionList.add(new InsnNode(ARRAYLENGTH)); return this; } public CodeBlock ishr() { this.instructionList.add(new InsnNode(ISHR)); return this; } public CodeBlock ishl() { this.instructionList.add(new InsnNode(ISHL)); return this; } public CodeBlock iushr() { this.instructionList.add(new InsnNode(IUSHR)); return this; } public CodeBlock lshr() { this.instructionList.add(new InsnNode(LSHR)); return this; } public CodeBlock lshl() { this.instructionList.add(new InsnNode(LSHL)); return this; } public CodeBlock lushr() { this.instructionList.add(new InsnNode(LUSHR)); return this; } public CodeBlock lcmp() { this.instructionList.add(new InsnNode(LCMP)); return this; } public CodeBlock iand() { this.instructionList.add(new InsnNode(IAND)); return this; } public CodeBlock ior() { this.instructionList.add(new InsnNode(IOR)); return this; } public CodeBlock ixor() { this.instructionList.add(new InsnNode(IXOR)); return this; } public CodeBlock land() { this.instructionList.add(new InsnNode(LAND)); return this; } public CodeBlock lor() { this.instructionList.add(new InsnNode(LOR)); return this; } public CodeBlock lxor() { this.instructionList.add(new InsnNode(LXOR)); return this; } public CodeBlock iadd() { this.instructionList.add(new InsnNode(IADD)); return this; } public CodeBlock ladd() { this.instructionList.add(new InsnNode(LADD)); return this; } public CodeBlock fadd() { this.instructionList.add(new InsnNode(FADD)); return this; } public CodeBlock dadd() { this.instructionList.add(new InsnNode(DADD)); return this; } public CodeBlock isub() { this.instructionList.add(new InsnNode(ISUB)); return this; } public CodeBlock lsub() { this.instructionList.add(new InsnNode(LSUB)); return this; } public CodeBlock fsub() { this.instructionList.add(new InsnNode(FSUB)); return this; } public CodeBlock dsub() { this.instructionList.add(new InsnNode(DSUB)); return this; } public CodeBlock idiv() { this.instructionList.add(new InsnNode(IDIV)); return this; } public CodeBlock irem() { this.instructionList.add(new InsnNode(IREM)); return this; } public CodeBlock ineg() { this.instructionList.add(new InsnNode(INEG)); return this; } public CodeBlock i2d() { this.instructionList.add(new InsnNode(I2D)); return this; } public CodeBlock i2l() { this.instructionList.add(new InsnNode(I2L)); return this; } public CodeBlock i2f() { this.instructionList.add(new InsnNode(I2F)); return this; } public CodeBlock i2s() { this.instructionList.add(new InsnNode(I2S)); return this; } public CodeBlock i2c() { this.instructionList.add(new InsnNode(I2C)); return this; } public CodeBlock i2b() { this.instructionList.add(new InsnNode(I2B)); return this; } public CodeBlock ldiv() { this.instructionList.add(new InsnNode(LDIV)); return this; } public CodeBlock lrem() { this.instructionList.add(new InsnNode(LREM)); return this; } public CodeBlock lneg() { this.instructionList.add(new InsnNode(LNEG)); return this; } public CodeBlock l2d() { this.instructionList.add(new InsnNode(L2D)); return this; } public CodeBlock l2i() { this.instructionList.add(new InsnNode(L2I)); return this; } public CodeBlock l2f() { this.instructionList.add(new InsnNode(L2F)); return this; } public CodeBlock fdiv() { this.instructionList.add(new InsnNode(FDIV)); return this; } public CodeBlock frem() { this.instructionList.add(new InsnNode(FREM)); return this; } public CodeBlock fneg() { this.instructionList.add(new InsnNode(FNEG)); return this; } public CodeBlock f2d() { this.instructionList.add(new InsnNode(F2D)); return this; } public CodeBlock f2i() { this.instructionList.add(new InsnNode(F2D)); return this; } public CodeBlock f2l() { this.instructionList.add(new InsnNode(F2L)); return this; } public CodeBlock ddiv() { this.instructionList.add(new InsnNode(DDIV)); return this; } public CodeBlock drem() { this.instructionList.add(new InsnNode(DREM)); return this; } public CodeBlock dneg() { this.instructionList.add(new InsnNode(DNEG)); return this; } public CodeBlock d2f() { this.instructionList.add(new InsnNode(D2F)); return this; } public CodeBlock d2i() { this.instructionList.add(new InsnNode(D2I)); return this; } public CodeBlock d2l() { this.instructionList.add(new InsnNode(D2L)); return this; } public CodeBlock imul() { this.instructionList.add(new InsnNode(IMUL)); return this; } public CodeBlock lmul() { this.instructionList.add(new InsnNode(LMUL)); return this; } public CodeBlock fmul() { this.instructionList.add(new InsnNode(FMUL)); return this; } public CodeBlock dmul() { this.instructionList.add(new InsnNode(DMUL)); return this; } public CodeBlock iinc(int arg0, int arg1) { this.instructionList.add(new IincInsnNode(arg0, arg1)); return this; } public CodeBlock monitorenter() { this.instructionList.add(new InsnNode(MONITORENTER)); return this; } public CodeBlock monitorexit() { this.instructionList.add(new InsnNode(MONITOREXIT)); return this; } public CodeBlock jsr(LabelNode branch) { this.instructionList.add(new JumpInsnNode(JSR, branch)); return this; } public CodeBlock ret(int arg0) { this.instructionList.add(new IntInsnNode(RET, arg0)); return this; } public CodeBlock visitInsn(int arg0) { this.instructionList.add(new InsnNode(arg0)); return this; } public CodeBlock visitIntInsn(int arg0, int arg1) { this.instructionList.add(new IntInsnNode(arg0, arg1)); return this; } public CodeBlock visitInsnNode(int arg0, int arg1) { this.instructionList.add(new IntInsnNode(arg0, arg1)); return this; } public CodeBlock visitTypeInsn(int arg0, String arg1) { this.instructionList.add(new TypeInsnNode(arg0, arg1)); return this; } public CodeBlock visitFieldInsn(int arg0, String arg1, String arg2, String arg3) { this.instructionList.add(new FieldInsnNode(arg0, arg1, arg2, arg3)); return this; } public CodeBlock visitMethodInsn(int arg0, String arg1, String arg2, String arg3) { this.instructionList.add(new MethodInsnNode(arg0, arg1, arg2, arg3)); return this; } public CodeBlock visitInvokeDynamicInsn(String arg0, String arg1, Handle arg2, Object... arg3) { this.instructionList.add(new InvokeDynamicInsnNode(arg0, arg1, arg2, arg3)); return this; } public CodeBlock visitJumpInsn(int arg0, LabelNode arg1) { this.instructionList.add(new JumpInsnNode(arg0, arg1)); return this; } public CodeBlock visitLabel(Label arg0) { this.instructionList.add(new LabelNode(arg0)); return this; } public CodeBlock visitLdcInsn(Object arg0) { this.instructionList.add(new LdcInsnNode(arg0)); return this; } public CodeBlock visitIincInsn(int arg0, int arg1) { this.instructionList.add(new IincInsnNode(arg0, arg1)); return this; } public CodeBlock visitTableSwitchInsn(int arg0, int arg1, LabelNode arg2, LabelNode[] arg3) { this.instructionList.add(new TableSwitchInsnNode(arg0, arg1, arg2, arg3)); return this; } public CodeBlock visitLookupSwitchInsn(LabelNode arg0, int[] arg1, LabelNode[] arg2) { this.instructionList.add(new LookupSwitchInsnNode(arg0, arg1, arg2)); return this; } public CodeBlock visitMultiANewArrayInsn(String arg0, int arg1) { this.instructionList.add(new MultiANewArrayInsnNode(arg0, arg1)); return this; } public CodeBlock visitTryCatchBlock(LabelNode arg0, LabelNode arg1, LabelNode arg2, String arg3) { this.tryCatchBlockList.add(new TryCatchBlockNode(arg0, arg1, arg2, arg3)); return this; } public CodeBlock visitLocalVariable(String arg0, String arg1, String arg2, LabelNode arg3, LabelNode arg4, int arg5) { this.localVariableList.add(new LocalVariableNode(arg0, arg1, arg2, arg3, arg4, arg5)); return this; } public CodeBlock visitLineNumber(int arg0, LabelNode arg1) { this.instructionList.add(new LineNumberNode(arg0, arg1)); return this; } public CodeBlock tableswitch(int min, int max, LabelNode defaultLabel, LabelNode[] cases) { this.instructionList.add(new TableSwitchInsnNode(min, max, defaultLabel, cases)); return this; } public CodeBlock visitFrame(int arg0, int arg1, Object[] arg2, int arg3, Object[] arg4) { this.instructionList.add(new FrameNode(arg0, arg1, arg2, arg3, arg4)); return this; } public InsnList getInstructionList() { return instructionList; } public List<TryCatchBlockNode> getTryCatchBlockList() { return tryCatchBlockList; } public List<LocalVariableNode> getLocalVariableList() { return localVariableList; } public CodeBlock prepend(CodeBlock codeBlock) { this.getInstructionList().insert(codeBlock.getInstructionList()); return this; } public CodeBlock append(CodeBlock codeBlock) { this.getInstructionList().add(codeBlock.getInstructionList()); return this; } public CodeBlock pushLocalVar(String arg) { this.localVariables.add(arg); int slot = localVariables.indexOf(arg); astore(arity() + slot); return this; } public CodeBlock popLocalVar(String arg) { int slot = localVariables.indexOf(arg); aload(arity() + slot); return this; } public int arity() { return this.arity; } public List<String> getLocalVariables() { return localVariables; } public boolean itReturns() { return returns; } }
src/main/java/me/qmx/jitescript/CodeBlock.java
/** * Copyright 2011 Douglas Campos <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.qmx.jitescript; import org.objectweb.asm.Handle; import org.objectweb.asm.Label; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.FieldInsnNode; import org.objectweb.asm.tree.FrameNode; import org.objectweb.asm.tree.IincInsnNode; import org.objectweb.asm.tree.InsnList; import org.objectweb.asm.tree.InsnNode; import org.objectweb.asm.tree.IntInsnNode; import org.objectweb.asm.tree.InvokeDynamicInsnNode; import org.objectweb.asm.tree.JumpInsnNode; import org.objectweb.asm.tree.LabelNode; import org.objectweb.asm.tree.LdcInsnNode; import org.objectweb.asm.tree.LineNumberNode; import org.objectweb.asm.tree.LocalVariableNode; import org.objectweb.asm.tree.LookupSwitchInsnNode; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MultiANewArrayInsnNode; import org.objectweb.asm.tree.TableSwitchInsnNode; import org.objectweb.asm.tree.TryCatchBlockNode; import org.objectweb.asm.tree.TypeInsnNode; import org.objectweb.asm.tree.VarInsnNode; import java.io.PrintStream; import java.util.ArrayList; import java.util.List; import static me.qmx.jitescript.util.CodegenUtils.ci; import static me.qmx.jitescript.util.CodegenUtils.p; import static me.qmx.jitescript.util.CodegenUtils.params; import static me.qmx.jitescript.util.CodegenUtils.sig; /** * @author qmx */ public class CodeBlock implements Opcodes { private boolean DEBUG = false; private InsnList instructionList = new InsnList(); private List<TryCatchBlockNode> tryCatchBlockList = new ArrayList<TryCatchBlockNode>(); private List<LocalVariableNode> localVariableList = new ArrayList<LocalVariableNode>(); private List<String> localVariables = new ArrayList<String>(); private int arity = 0; public CodeBlock() { } public CodeBlock(CodeBlock block) { this.arity = block.arity(); this.localVariables.addAll(block.localVariables); prepend(block); } public CodeBlock(int arity) { this.arity = arity; } public static CodeBlock newCodeBlock() { return new CodeBlock(); } public static CodeBlock newCodeBlock(int arity) { return new CodeBlock(arity); } public static CodeBlock newCodeBlock(CodeBlock block) { return new CodeBlock(block); } /** * Short-hand for specifying a set of aloads * * @param args list of aloads you want */ public CodeBlock aloadMany(int... args) { for (int arg : args) { aload(arg); } return this; } public CodeBlock aload(int arg0) { this.instructionList.add(new VarInsnNode(ALOAD, arg0)); return this; } public CodeBlock iload(int arg0) { this.instructionList.add(new VarInsnNode(ILOAD, arg0)); return this; } public CodeBlock lload(int arg0) { this.instructionList.add(new VarInsnNode(LLOAD, arg0)); return this; } public CodeBlock fload(int arg0) { this.instructionList.add(new VarInsnNode(FLOAD, arg0)); return this; } public CodeBlock dload(int arg0) { this.instructionList.add(new VarInsnNode(DLOAD, arg0)); return this; } public CodeBlock astore(int arg0) { this.instructionList.add(new VarInsnNode(ASTORE, arg0)); return this; } public CodeBlock istore(int arg0) { this.instructionList.add(new VarInsnNode(ISTORE, arg0)); return this; } public CodeBlock lstore(int arg0) { this.instructionList.add(new VarInsnNode(LSTORE, arg0)); return this; } public CodeBlock fstore(int arg0) { this.instructionList.add(new VarInsnNode(FSTORE, arg0)); return this; } public CodeBlock dstore(int arg0) { this.instructionList.add(new VarInsnNode(DSTORE, arg0)); return this; } public CodeBlock ldc(Object arg0) { this.instructionList.add(new LdcInsnNode(arg0)); return this; } public CodeBlock bipush(int arg) { this.instructionList.add(new IntInsnNode(BIPUSH, arg)); return this; } public CodeBlock sipush(int arg) { this.instructionList.add(new IntInsnNode(SIPUSH, arg)); return this; } public CodeBlock pushInt(int value) { if (value <= Byte.MAX_VALUE && value >= Byte.MIN_VALUE) { switch (value) { case -1: iconst_m1(); break; case 0: iconst_0(); break; case 1: iconst_1(); break; case 2: iconst_2(); break; case 3: iconst_3(); break; case 4: iconst_4(); break; case 5: iconst_5(); break; default: bipush(value); break; } } else if (value <= Short.MAX_VALUE && value >= Short.MIN_VALUE) { sipush(value); } else { ldc(value); } return this; } public CodeBlock pushBoolean(boolean bool) { if (bool) { iconst_1(); } else { iconst_0(); } return this; } public CodeBlock invokestatic(String arg1, String arg2, String arg3) { this.instructionList.add(new MethodInsnNode(INVOKESTATIC, arg1, arg2, arg3)); return this; } public CodeBlock invokespecial(String arg1, String arg2, String arg3) { this.instructionList.add(new MethodInsnNode(INVOKESPECIAL, arg1, arg2, arg3)); return this; } public CodeBlock invokevirtual(String arg1, String arg2, String arg3) { this.instructionList.add(new MethodInsnNode(INVOKEVIRTUAL, arg1, arg2, arg3)); return this; } public CodeBlock invokeinterface(String arg1, String arg2, String arg3) { this.instructionList.add(new MethodInsnNode(INVOKEINTERFACE, arg1, arg2, arg3)); return this; } public CodeBlock invokedynamic(String arg0, String arg1, Handle arg2, Object... arg3) { this.instructionList.add(new InvokeDynamicInsnNode(arg0, arg1, arg2, arg3)); return this; } public CodeBlock aprintln() { dup(); getstatic(p(System.class), "out", ci(PrintStream.class)); swap(); invokevirtual(p(PrintStream.class), "println", sig(void.class, params(Object.class))); return this; } public CodeBlock iprintln() { dup(); getstatic(p(System.class), "out", ci(PrintStream.class)); swap(); invokevirtual(p(PrintStream.class), "println", sig(void.class, params(int.class))); return this; } public CodeBlock areturn() { this.instructionList.add(new InsnNode(ARETURN)); return this; } public CodeBlock ireturn() { this.instructionList.add(new InsnNode(IRETURN)); return this; } public CodeBlock freturn() { this.instructionList.add(new InsnNode(FRETURN)); return this; } public CodeBlock lreturn() { this.instructionList.add(new InsnNode(LRETURN)); return this; } public CodeBlock dreturn() { this.instructionList.add(new InsnNode(DRETURN)); return this; } public CodeBlock newobj(String arg0) { this.instructionList.add(new TypeInsnNode(NEW, arg0)); return this; } public CodeBlock dup() { this.instructionList.add(new InsnNode(DUP)); return this; } public CodeBlock swap() { this.instructionList.add(new InsnNode(SWAP)); return this; } public CodeBlock swap2() { dup2_x2(); pop2(); return this; } public CodeBlock getstatic(String arg1, String arg2, String arg3) { this.instructionList.add(new FieldInsnNode(GETSTATIC, arg1, arg2, arg3)); return this; } public CodeBlock putstatic(String arg1, String arg2, String arg3) { this.instructionList.add(new FieldInsnNode(PUTSTATIC, arg1, arg2, arg3)); return this; } public CodeBlock getfield(String arg1, String arg2, String arg3) { this.instructionList.add(new FieldInsnNode(GETFIELD, arg1, arg2, arg3)); return this; } public CodeBlock putfield(String arg1, String arg2, String arg3) { this.instructionList.add(new FieldInsnNode(PUTFIELD, arg1, arg2, arg3)); return this; } public CodeBlock voidreturn() { this.instructionList.add(new InsnNode(RETURN)); return this; } public CodeBlock anewarray(String arg0) { this.instructionList.add(new TypeInsnNode(ANEWARRAY, arg0)); return this; } public CodeBlock multianewarray(String arg0, int dims) { this.instructionList.add(new MultiANewArrayInsnNode(arg0, dims)); return this; } public CodeBlock newarray(int arg0) { this.instructionList.add(new IntInsnNode(NEWARRAY, arg0)); return this; } public CodeBlock iconst_m1() { this.instructionList.add(new InsnNode(ICONST_M1)); return this; } public CodeBlock iconst_0() { this.instructionList.add(new InsnNode(ICONST_0)); return this; } public CodeBlock iconst_1() { this.instructionList.add(new InsnNode(ICONST_1)); return this; } public CodeBlock iconst_2() { this.instructionList.add(new InsnNode(ICONST_2)); return this; } public CodeBlock iconst_3() { this.instructionList.add(new InsnNode(ICONST_3)); return this; } public CodeBlock iconst_4() { this.instructionList.add(new InsnNode(ICONST_4)); return this; } public CodeBlock iconst_5() { this.instructionList.add(new InsnNode(ICONST_5)); return this; } public CodeBlock lconst_0() { this.instructionList.add(new InsnNode(LCONST_0)); return this; } public CodeBlock aconst_null() { this.instructionList.add(new InsnNode(ACONST_NULL)); return this; } public CodeBlock label(LabelNode labelNode) { this.instructionList.add(labelNode); return this; } public CodeBlock nop() { this.instructionList.add(new InsnNode(NOP)); return this; } public CodeBlock pop() { this.instructionList.add(new InsnNode(POP)); return this; } public CodeBlock pop2() { this.instructionList.add(new InsnNode(POP2)); return this; } public CodeBlock arrayload() { this.instructionList.add(new InsnNode(AALOAD)); return this; } public CodeBlock arraystore() { this.instructionList.add(new InsnNode(AASTORE)); return this; } public CodeBlock iarrayload() { this.instructionList.add(new InsnNode(IALOAD)); return this; } public CodeBlock barrayload() { this.instructionList.add(new InsnNode(BALOAD)); return this; } public CodeBlock barraystore() { this.instructionList.add(new InsnNode(BASTORE)); return this; } public CodeBlock aaload() { this.instructionList.add(new InsnNode(AALOAD)); return this; } public CodeBlock aastore() { this.instructionList.add(new InsnNode(AASTORE)); return this; } public CodeBlock iaload() { this.instructionList.add(new InsnNode(IALOAD)); return this; } public CodeBlock iastore() { this.instructionList.add(new InsnNode(IASTORE)); return this; } public CodeBlock laload() { this.instructionList.add(new InsnNode(LALOAD)); return this; } public CodeBlock lastore() { this.instructionList.add(new InsnNode(LASTORE)); return this; } public CodeBlock baload() { this.instructionList.add(new InsnNode(BALOAD)); return this; } public CodeBlock bastore() { this.instructionList.add(new InsnNode(BASTORE)); return this; } public CodeBlock saload() { this.instructionList.add(new InsnNode(SALOAD)); return this; } public CodeBlock sastore() { this.instructionList.add(new InsnNode(SASTORE)); return this; } public CodeBlock caload() { this.instructionList.add(new InsnNode(CALOAD)); return this; } public CodeBlock castore() { this.instructionList.add(new InsnNode(CASTORE)); return this; } public CodeBlock faload() { this.instructionList.add(new InsnNode(FALOAD)); return this; } public CodeBlock fastore() { this.instructionList.add(new InsnNode(FASTORE)); return this; } public CodeBlock daload() { this.instructionList.add(new InsnNode(DALOAD)); return this; } public CodeBlock dastore() { this.instructionList.add(new InsnNode(DASTORE)); return this; } public CodeBlock fcmpl() { this.instructionList.add(new InsnNode(FCMPL)); return this; } public CodeBlock fcmpg() { this.instructionList.add(new InsnNode(FCMPG)); return this; } public CodeBlock dcmpl() { this.instructionList.add(new InsnNode(DCMPL)); return this; } public CodeBlock dcmpg() { this.instructionList.add(new InsnNode(DCMPG)); return this; } public CodeBlock dup_x2() { this.instructionList.add(new InsnNode(DUP_X2)); return this; } public CodeBlock dup_x1() { this.instructionList.add(new InsnNode(DUP_X1)); return this; } public CodeBlock dup2_x2() { this.instructionList.add(new InsnNode(DUP2_X2)); return this; } public CodeBlock dup2_x1() { this.instructionList.add(new InsnNode(DUP2_X1)); return this; } public CodeBlock dup2() { this.instructionList.add(new InsnNode(DUP2)); return this; } public CodeBlock trycatch(LabelNode arg0, LabelNode arg1, LabelNode arg2, String arg3) { this.tryCatchBlockList.add(new TryCatchBlockNode(arg0, arg1, arg2, arg3)); return this; } public CodeBlock trycatch(String type, Runnable body, Runnable catchBody) { LabelNode before = new LabelNode(); LabelNode after = new LabelNode(); LabelNode catchStart = new LabelNode(); LabelNode done = new LabelNode(); trycatch(before, after, catchStart, type); label(before); body.run(); label(after); go_to(done); if (catchBody != null) { label(catchStart); catchBody.run(); } label(done); return this; } public CodeBlock go_to(LabelNode arg0) { this.instructionList.add(new JumpInsnNode(GOTO, arg0)); return this; } public CodeBlock lookupswitch(LabelNode arg0, int[] arg1, LabelNode[] arg2) { this.instructionList.add(new LookupSwitchInsnNode(arg0, arg1, arg2)); return this; } public CodeBlock athrow() { this.instructionList.add(new InsnNode(ATHROW)); return this; } public CodeBlock instance_of(String arg0) { this.instructionList.add(new TypeInsnNode(INSTANCEOF, arg0)); return this; } public CodeBlock ifeq(LabelNode arg0) { this.instructionList.add(new JumpInsnNode(IFEQ, arg0)); return this; } public CodeBlock iffalse(LabelNode arg0) { ifeq(arg0); return this; } public CodeBlock ifne(LabelNode arg0) { this.instructionList.add(new JumpInsnNode(IFNE, arg0)); return this; } public CodeBlock iftrue(LabelNode arg0) { ifne(arg0); return this; } public CodeBlock if_acmpne(LabelNode arg0) { this.instructionList.add(new JumpInsnNode(IF_ACMPNE, arg0)); return this; } public CodeBlock if_acmpeq(LabelNode arg0) { this.instructionList.add(new JumpInsnNode(IF_ACMPEQ, arg0)); return this; } public CodeBlock if_icmple(LabelNode arg0) { this.instructionList.add(new JumpInsnNode(IF_ICMPLE, arg0)); return this; } public CodeBlock if_icmpgt(LabelNode arg0) { this.instructionList.add(new JumpInsnNode(IF_ICMPGT, arg0)); return this; } public CodeBlock if_icmplt(LabelNode arg0) { this.instructionList.add(new JumpInsnNode(IF_ICMPLT, arg0)); return this; } public CodeBlock if_icmpne(LabelNode arg0) { this.instructionList.add(new JumpInsnNode(IF_ICMPNE, arg0)); return this; } public CodeBlock if_icmpeq(LabelNode arg0) { this.instructionList.add(new JumpInsnNode(IF_ICMPEQ, arg0)); return this; } public CodeBlock checkcast(String arg0) { this.instructionList.add(new TypeInsnNode(CHECKCAST, arg0)); return this; } public CodeBlock line(int line) { visitLineNumber(line, new LabelNode()); return this; } public CodeBlock line(int line, LabelNode label) { visitLineNumber(line, label); return this; } public CodeBlock ifnonnull(LabelNode arg0) { this.instructionList.add(new JumpInsnNode(IFNONNULL, arg0)); return this; } public CodeBlock ifnull(LabelNode arg0) { this.instructionList.add(new JumpInsnNode(IFNULL, arg0)); return this; } public CodeBlock iflt(LabelNode arg0) { this.instructionList.add(new JumpInsnNode(IFLT, arg0)); return this; } public CodeBlock ifle(LabelNode arg0) { this.instructionList.add(new JumpInsnNode(IFLE, arg0)); return this; } public CodeBlock ifgt(LabelNode arg0) { this.instructionList.add(new JumpInsnNode(IFGT, arg0)); return this; } public CodeBlock ifge(LabelNode arg0) { this.instructionList.add(new JumpInsnNode(IFGE, arg0)); return this; } public CodeBlock arraylength() { this.instructionList.add(new InsnNode(ARRAYLENGTH)); return this; } public CodeBlock ishr() { this.instructionList.add(new InsnNode(ISHR)); return this; } public CodeBlock ishl() { this.instructionList.add(new InsnNode(ISHL)); return this; } public CodeBlock iushr() { this.instructionList.add(new InsnNode(IUSHR)); return this; } public CodeBlock lshr() { this.instructionList.add(new InsnNode(LSHR)); return this; } public CodeBlock lshl() { this.instructionList.add(new InsnNode(LSHL)); return this; } public CodeBlock lushr() { this.instructionList.add(new InsnNode(LUSHR)); return this; } public CodeBlock lcmp() { this.instructionList.add(new InsnNode(LCMP)); return this; } public CodeBlock iand() { this.instructionList.add(new InsnNode(IAND)); return this; } public CodeBlock ior() { this.instructionList.add(new InsnNode(IOR)); return this; } public CodeBlock ixor() { this.instructionList.add(new InsnNode(IXOR)); return this; } public CodeBlock land() { this.instructionList.add(new InsnNode(LAND)); return this; } public CodeBlock lor() { this.instructionList.add(new InsnNode(LOR)); return this; } public CodeBlock lxor() { this.instructionList.add(new InsnNode(LXOR)); return this; } public CodeBlock iadd() { this.instructionList.add(new InsnNode(IADD)); return this; } public CodeBlock ladd() { this.instructionList.add(new InsnNode(LADD)); return this; } public CodeBlock fadd() { this.instructionList.add(new InsnNode(FADD)); return this; } public CodeBlock dadd() { this.instructionList.add(new InsnNode(DADD)); return this; } public CodeBlock isub() { this.instructionList.add(new InsnNode(ISUB)); return this; } public CodeBlock lsub() { this.instructionList.add(new InsnNode(LSUB)); return this; } public CodeBlock fsub() { this.instructionList.add(new InsnNode(FSUB)); return this; } public CodeBlock dsub() { this.instructionList.add(new InsnNode(DSUB)); return this; } public CodeBlock idiv() { this.instructionList.add(new InsnNode(IDIV)); return this; } public CodeBlock irem() { this.instructionList.add(new InsnNode(IREM)); return this; } public CodeBlock ineg() { this.instructionList.add(new InsnNode(INEG)); return this; } public CodeBlock i2d() { this.instructionList.add(new InsnNode(I2D)); return this; } public CodeBlock i2l() { this.instructionList.add(new InsnNode(I2L)); return this; } public CodeBlock i2f() { this.instructionList.add(new InsnNode(I2F)); return this; } public CodeBlock i2s() { this.instructionList.add(new InsnNode(I2S)); return this; } public CodeBlock i2c() { this.instructionList.add(new InsnNode(I2C)); return this; } public CodeBlock i2b() { this.instructionList.add(new InsnNode(I2B)); return this; } public CodeBlock ldiv() { this.instructionList.add(new InsnNode(LDIV)); return this; } public CodeBlock lrem() { this.instructionList.add(new InsnNode(LREM)); return this; } public CodeBlock lneg() { this.instructionList.add(new InsnNode(LNEG)); return this; } public CodeBlock l2d() { this.instructionList.add(new InsnNode(L2D)); return this; } public CodeBlock l2i() { this.instructionList.add(new InsnNode(L2I)); return this; } public CodeBlock l2f() { this.instructionList.add(new InsnNode(L2F)); return this; } public CodeBlock fdiv() { this.instructionList.add(new InsnNode(FDIV)); return this; } public CodeBlock frem() { this.instructionList.add(new InsnNode(FREM)); return this; } public CodeBlock fneg() { this.instructionList.add(new InsnNode(FNEG)); return this; } public CodeBlock f2d() { this.instructionList.add(new InsnNode(F2D)); return this; } public CodeBlock f2i() { this.instructionList.add(new InsnNode(F2D)); return this; } public CodeBlock f2l() { this.instructionList.add(new InsnNode(F2L)); return this; } public CodeBlock ddiv() { this.instructionList.add(new InsnNode(DDIV)); return this; } public CodeBlock drem() { this.instructionList.add(new InsnNode(DREM)); return this; } public CodeBlock dneg() { this.instructionList.add(new InsnNode(DNEG)); return this; } public CodeBlock d2f() { this.instructionList.add(new InsnNode(D2F)); return this; } public CodeBlock d2i() { this.instructionList.add(new InsnNode(D2I)); return this; } public CodeBlock d2l() { this.instructionList.add(new InsnNode(D2L)); return this; } public CodeBlock imul() { this.instructionList.add(new InsnNode(IMUL)); return this; } public CodeBlock lmul() { this.instructionList.add(new InsnNode(LMUL)); return this; } public CodeBlock fmul() { this.instructionList.add(new InsnNode(FMUL)); return this; } public CodeBlock dmul() { this.instructionList.add(new InsnNode(DMUL)); return this; } public CodeBlock iinc(int arg0, int arg1) { this.instructionList.add(new IincInsnNode(arg0, arg1)); return this; } public CodeBlock monitorenter() { this.instructionList.add(new InsnNode(MONITORENTER)); return this; } public CodeBlock monitorexit() { this.instructionList.add(new InsnNode(MONITOREXIT)); return this; } public CodeBlock jsr(LabelNode branch) { this.instructionList.add(new JumpInsnNode(JSR, branch)); return this; } public CodeBlock ret(int arg0) { this.instructionList.add(new IntInsnNode(RET, arg0)); return this; } public CodeBlock visitInsn(int arg0) { this.instructionList.add(new InsnNode(arg0)); return this; } public CodeBlock visitIntInsn(int arg0, int arg1) { this.instructionList.add(new IntInsnNode(arg0, arg1)); return this; } public CodeBlock visitInsnNode(int arg0, int arg1) { this.instructionList.add(new IntInsnNode(arg0, arg1)); return this; } public CodeBlock visitTypeInsn(int arg0, String arg1) { this.instructionList.add(new TypeInsnNode(arg0, arg1)); return this; } public CodeBlock visitFieldInsn(int arg0, String arg1, String arg2, String arg3) { this.instructionList.add(new FieldInsnNode(arg0, arg1, arg2, arg3)); return this; } public CodeBlock visitMethodInsn(int arg0, String arg1, String arg2, String arg3) { this.instructionList.add(new MethodInsnNode(arg0, arg1, arg2, arg3)); return this; } public CodeBlock visitInvokeDynamicInsn(String arg0, String arg1, Handle arg2, Object... arg3) { this.instructionList.add(new InvokeDynamicInsnNode(arg0, arg1, arg2, arg3)); return this; } public CodeBlock visitJumpInsn(int arg0, LabelNode arg1) { this.instructionList.add(new JumpInsnNode(arg0, arg1)); return this; } public CodeBlock visitLabel(Label arg0) { this.instructionList.add(new LabelNode(arg0)); return this; } public CodeBlock visitLdcInsn(Object arg0) { this.instructionList.add(new LdcInsnNode(arg0)); return this; } public CodeBlock visitIincInsn(int arg0, int arg1) { this.instructionList.add(new IincInsnNode(arg0, arg1)); return this; } public CodeBlock visitTableSwitchInsn(int arg0, int arg1, LabelNode arg2, LabelNode[] arg3) { this.instructionList.add(new TableSwitchInsnNode(arg0, arg1, arg2, arg3)); return this; } public CodeBlock visitLookupSwitchInsn(LabelNode arg0, int[] arg1, LabelNode[] arg2) { this.instructionList.add(new LookupSwitchInsnNode(arg0, arg1, arg2)); return this; } public CodeBlock visitMultiANewArrayInsn(String arg0, int arg1) { this.instructionList.add(new MultiANewArrayInsnNode(arg0, arg1)); return this; } public CodeBlock visitTryCatchBlock(LabelNode arg0, LabelNode arg1, LabelNode arg2, String arg3) { this.tryCatchBlockList.add(new TryCatchBlockNode(arg0, arg1, arg2, arg3)); return this; } public CodeBlock visitLocalVariable(String arg0, String arg1, String arg2, LabelNode arg3, LabelNode arg4, int arg5) { this.localVariableList.add(new LocalVariableNode(arg0, arg1, arg2, arg3, arg4, arg5)); return this; } public CodeBlock visitLineNumber(int arg0, LabelNode arg1) { this.instructionList.add(new LineNumberNode(arg0, arg1)); return this; } public CodeBlock tableswitch(int min, int max, LabelNode defaultLabel, LabelNode[] cases) { this.instructionList.add(new TableSwitchInsnNode(min, max, defaultLabel, cases)); return this; } public CodeBlock visitFrame(int arg0, int arg1, Object[] arg2, int arg3, Object[] arg4) { this.instructionList.add(new FrameNode(arg0, arg1, arg2, arg3, arg4)); return this; } public InsnList getInstructionList() { return instructionList; } public List<TryCatchBlockNode> getTryCatchBlockList() { return tryCatchBlockList; } public List<LocalVariableNode> getLocalVariableList() { return localVariableList; } public CodeBlock prepend(CodeBlock codeBlock) { this.getInstructionList().insert(codeBlock.getInstructionList()); return this; } public CodeBlock append(CodeBlock codeBlock) { this.getInstructionList().add(codeBlock.getInstructionList()); return this; } public CodeBlock pushLocalVar(String arg) { this.localVariables.add(arg); int slot = localVariables.indexOf(arg); astore(arity() + slot); return this; } public CodeBlock popLocalVar(String arg) { int slot = localVariables.indexOf(arg); aload(arity() + slot); return this; } public int arity() { return this.arity; } public List<String> getLocalVariables() { return localVariables; } }
adding returns control
src/main/java/me/qmx/jitescript/CodeBlock.java
adding returns control
<ide><path>rc/main/java/me/qmx/jitescript/CodeBlock.java <ide> private List<LocalVariableNode> localVariableList = new ArrayList<LocalVariableNode>(); <ide> private List<String> localVariables = new ArrayList<String>(); <ide> private int arity = 0; <add> private boolean returns = false; <ide> <ide> public CodeBlock() { <ide> } <ide> } <ide> <ide> public CodeBlock areturn() { <add> this.returns = true; <ide> this.instructionList.add(new InsnNode(ARETURN)); <ide> return this; <ide> } <ide> public List<String> getLocalVariables() { <ide> return localVariables; <ide> } <add> <add> public boolean itReturns() { <add> return returns; <add> } <ide> }
JavaScript
bsd-3-clause
7f6d6c1c79387099dd700d2b6584af066e2b67a7
0
CESNET/etlog,CESNET/etlog,CESNET/etlog,CESNET/etlog
module.exports = function(app, database) { // ----------------------------------------------------------- // TODO // prepend authentication to all routes // TODO // use permissions - [ user, administrator ] // // all routes may be used by administrator // // only specific routes may be used by user // set up routes // ----------------------------------------------------------- app.use('/', require('./routes/index')); // title page app.use('/api/search', require('./routes/search')); // generic search api app.use('/api/mac_count', require('./routes/mac_count')); // generic api for mac address count app.use('/api/roaming/most_provided', require('./routes/roaming_most_provided')); // generic api for institutions most providing roaming app.use('/api/roaming/most_used', require('./routes/roaming_most_used')); // generic api for institutions most using roaming app.use('/api/failed_logins', require('./routes/failed_logins')); // generic api for failed logins app.use('/api/shared_mac', require('./routes/shared_mac')); // generic api for shared mac app.use('/api/heat_map', require('./routes/heat_map')); // generic api for heat map app.use('/api/db_data', require('./routes/db_data')); // api for db data app.use('/api/realms', require('./routes/realms')); // api for realms app.use('/api/count', require('./routes/count')); // api to count records for pagination purposes app.use('/api/succ_logins', require('./routes/succ_logins')); // generic api for successful logins // ----------------------------------------------------------- // login routing is defined separately // see auth.js // saml test app.use('/auth_fail', require('./routes/auth_fail')); //app.use('/login/callback', require('./routes/callback')); }
routes.js
module.exports = function(app, database) { // ----------------------------------------------------------- // TODO // prepend authentication to all routes // TODO // use permissions - [ user, administrator ] // // all routes may be used by administrator // // only specific routes may be used by user // set up routes // ----------------------------------------------------------- app.use('/', require('./routes/index')); // title page app.use('/api/search', require('./routes/search')); // generic search api app.use('/api/mac_count', require('./routes/mac_count')); // generic api for mac address count app.use('/api/roaming/most_provided', require('./routes/roaming_most_provided')); // generic api for institutions most providing roaming app.use('/api/roaming/most_used', require('./routes/roaming_most_used')); // generic api for institutions most using roaming app.use('/api/failed_logins', require('./routes/failed_logins')); // generic api for failed logins app.use('/api/shared_mac', require('./routes/shared_mac')); // generic api for shared mac app.use('/api/heat_map', require('./routes/heat_map')); // generic api for heat map app.use('/api/db_data', require('./routes/db_data')); // api for db data app.use('/api/realms', require('./routes/realms')); // api for realms app.use('/api/count', require('./routes/count')); // api to count records for pagination purposes // TODO // app.use('/api/stats', require('./routes/stats')); // TODO // ----------------------------------------------------------- // login routing is defined separately // see auth.js // TODO // metadata url // saml test app.use('/auth_fail', require('./routes/auth_fail')); //app.use('/login/callback', require('./routes/callback')); }
use new route
routes.js
use new route
<ide><path>outes.js <ide> app.use('/api/db_data', require('./routes/db_data')); // api for db data <ide> app.use('/api/realms', require('./routes/realms')); // api for realms <ide> app.use('/api/count', require('./routes/count')); // api to count records for pagination purposes <del> // TODO <del> // app.use('/api/stats', require('./routes/stats')); // TODO <del> <add> app.use('/api/succ_logins', require('./routes/succ_logins')); // generic api for successful logins <ide> <ide> // ----------------------------------------------------------- <ide> // login routing is defined separately <ide> // see auth.js <del> // TODO <del> // metadata url <ide> <ide> // saml test <ide> app.use('/auth_fail', require('./routes/auth_fail'));
Java
apache-2.0
92fc0451e6ccffbbecaf08ada8e8685592364eb6
0
robovm/robovm-studio,fnouama/intellij-community,asedunov/intellij-community,signed/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,supersven/intellij-community,da1z/intellij-community,asedunov/intellij-community,ibinti/intellij-community,ernestp/consulo,wreckJ/intellij-community,ryano144/intellij-community,petteyg/intellij-community,jexp/idea2,FHannes/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,amith01994/intellij-community,retomerz/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,jexp/idea2,idea4bsd/idea4bsd,supersven/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,jexp/idea2,FHannes/intellij-community,signed/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,joewalnes/idea-community,gnuhub/intellij-community,semonte/intellij-community,ibinti/intellij-community,semonte/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,izonder/intellij-community,gnuhub/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,izonder/intellij-community,retomerz/intellij-community,hurricup/intellij-community,caot/intellij-community,xfournet/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,da1z/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,vladmm/intellij-community,vvv1559/intellij-community,semonte/intellij-community,clumsy/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,supersven/intellij-community,signed/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,ibinti/intellij-community,fnouama/intellij-community,kool79/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,kool79/intellij-community,supersven/intellij-community,fnouama/intellij-community,ibinti/intellij-community,semonte/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,robovm/robovm-studio,diorcety/intellij-community,blademainer/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,caot/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,ibinti/intellij-community,kool79/intellij-community,samthor/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,consulo/consulo,allotria/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,slisson/intellij-community,ryano144/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,kool79/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,fitermay/intellij-community,samthor/intellij-community,dslomov/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,samthor/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,slisson/intellij-community,supersven/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,ernestp/consulo,vvv1559/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,da1z/intellij-community,izonder/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,da1z/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,caot/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,jagguli/intellij-community,allotria/intellij-community,petteyg/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,joewalnes/idea-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,diorcety/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,amith01994/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,caot/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,samthor/intellij-community,jexp/idea2,mglukhikh/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,FHannes/intellij-community,signed/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,allotria/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,kool79/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,diorcety/intellij-community,orekyuu/intellij-community,holmes/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,amith01994/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,izonder/intellij-community,caot/intellij-community,ernestp/consulo,michaelgallacher/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,diorcety/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,fnouama/intellij-community,signed/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,fitermay/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,allotria/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,caot/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,fitermay/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,kool79/intellij-community,hurricup/intellij-community,samthor/intellij-community,FHannes/intellij-community,fnouama/intellij-community,ibinti/intellij-community,clumsy/intellij-community,fnouama/intellij-community,ernestp/consulo,gnuhub/intellij-community,joewalnes/idea-community,petteyg/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,fnouama/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,ibinti/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,consulo/consulo,consulo/consulo,fengbaicanhe/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,joewalnes/idea-community,mglukhikh/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,xfournet/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,consulo/consulo,TangHao1987/intellij-community,consulo/consulo,retomerz/intellij-community,orekyuu/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,dslomov/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,kool79/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,ernestp/consulo,dslomov/intellij-community,semonte/intellij-community,izonder/intellij-community,retomerz/intellij-community,robovm/robovm-studio,holmes/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,joewalnes/idea-community,youdonghai/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,vladmm/intellij-community,xfournet/intellij-community,joewalnes/idea-community,joewalnes/idea-community,SerCeMan/intellij-community,signed/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,ryano144/intellij-community,kool79/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,petteyg/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,supersven/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,jexp/idea2,adedayo/intellij-community,robovm/robovm-studio,ryano144/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,caot/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,hurricup/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,fitermay/intellij-community,ryano144/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,dslomov/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,caot/intellij-community,adedayo/intellij-community,amith01994/intellij-community,ryano144/intellij-community,signed/intellij-community,amith01994/intellij-community,izonder/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,ernestp/consulo,orekyuu/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,kdwink/intellij-community,amith01994/intellij-community,jagguli/intellij-community,holmes/intellij-community,vvv1559/intellij-community,signed/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,consulo/consulo,pwoodworth/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,signed/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,jagguli/intellij-community,adedayo/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,amith01994/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,holmes/intellij-community,clumsy/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,kool79/intellij-community,ryano144/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,vladmm/intellij-community,joewalnes/idea-community,kdwink/intellij-community,allotria/intellij-community,slisson/intellij-community,samthor/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,amith01994/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,semonte/intellij-community,jexp/idea2,salguarnieri/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,semonte/intellij-community,retomerz/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,allotria/intellij-community,signed/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,kool79/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,blademainer/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,signed/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,vladmm/intellij-community,kdwink/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,signed/intellij-community,ryano144/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,signed/intellij-community,dslomov/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,slisson/intellij-community,xfournet/intellij-community,FHannes/intellij-community,robovm/robovm-studio,slisson/intellij-community,clumsy/intellij-community,asedunov/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,joewalnes/idea-community,fnouama/intellij-community,vladmm/intellij-community,izonder/intellij-community,caot/intellij-community,Lekanich/intellij-community,kool79/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,jexp/idea2,TangHao1987/intellij-community,jexp/idea2,ivan-fedorov/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,kdwink/intellij-community,akosyakov/intellij-community,semonte/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,hurricup/intellij-community,apixandru/intellij-community,FHannes/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,samthor/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd
/* * Copyright (c) 2000-2007 JetBrains s.r.o. All Rights Reserved. */ /* * User: anna * Date: 09-Jan-2007 */ package com.intellij.codeInspection.actions; import com.intellij.analysis.AnalysisScope; import com.intellij.analysis.PerformAnalysisInBackgroundOption; import com.intellij.codeHighlighting.HighlightDisplayLevel; import com.intellij.codeInsight.daemon.HighlightDisplayKey; import com.intellij.codeInspection.InspectionProfile; import com.intellij.codeInspection.InspectionsBundle; import com.intellij.codeInspection.ex.*; import com.intellij.codeInspection.offlineViewer.OfflineInspectionRVContentProvider; import com.intellij.codeInspection.offlineViewer.OfflineProblemDescriptor; import com.intellij.codeInspection.offlineViewer.OfflineViewParseUtil; import com.intellij.codeInspection.reference.RefManagerImpl; import com.intellij.codeInspection.ui.InspectionResultsView; import com.intellij.ide.highlighter.XmlFileType; import com.intellij.ide.util.BrowseFilesListener; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileChooser.FileChooser; import com.intellij.openapi.fileEditor.impl.LoadTextUtil; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.Computable; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.profile.Profile; import com.intellij.profile.codeInspection.InspectionProfileManager; import com.intellij.profile.codeInspection.InspectionProjectProfileManager; import com.intellij.util.ui.tree.TreeUtil; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.HashMap; import java.util.Map; import java.util.Set; public class ViewOfflineResultsAction extends AnAction { private static final Logger LOG = Logger.getInstance("#com.intellij.codeInspection.actions.ViewOfflineResultsAction"); public void update(AnActionEvent event) { final Presentation presentation = event.getPresentation(); final Project project = event.getData(DataKeys.PROJECT); presentation.setEnabled(project != null); presentation.setVisible(ActionPlaces.MAIN_MENU.equals(event.getPlace())); } public void actionPerformed(AnActionEvent event) { final Project project = event.getData(DataKeys.PROJECT); LOG.assertTrue(project != null); final VirtualFile[] virtualFiles = FileChooser.chooseFiles(project, BrowseFilesListener.SINGLE_DIRECTORY_DESCRIPTOR); if (virtualFiles == null || virtualFiles.length == 0) return; if (!virtualFiles[0].isDirectory()) return; final Map<String, Map<String, Set<OfflineProblemDescriptor>>> resMap = new HashMap<String, Map<String, Set<OfflineProblemDescriptor>>>(); final String [] profileName = new String[1]; final Runnable process = new Runnable() { public void run() { final VirtualFile[] files = virtualFiles[0].getChildren(); try { for (final VirtualFile inspectionFile : files) { if (inspectionFile.isDirectory()) continue; final String shortName = inspectionFile.getNameWithoutExtension(); if (shortName.equals(InspectionApplication.DESCRIPTIONS)) { profileName[0] = ApplicationManager.getApplication().runReadAction( new Computable<String>() { @Nullable public String compute() { return OfflineViewParseUtil.parseProfileName(LoadTextUtil.loadText(inspectionFile).toString()); } } ); } else if (inspectionFile.getFileType() instanceof XmlFileType) { resMap.put(shortName, ApplicationManager.getApplication().runReadAction( new Computable<Map<String, Set<OfflineProblemDescriptor>>>() { public Map<String, Set<OfflineProblemDescriptor>> compute() { return OfflineViewParseUtil.parse(LoadTextUtil.loadText(inspectionFile).toString()); } } )); } } } catch (final Exception e) { //all parse exceptions SwingUtilities.invokeLater(new Runnable() { public void run() { Messages.showInfoMessage(e.getMessage(), InspectionsBundle.message("offline.view.parse.exception.title")); } }); throw new ProcessCanceledException(); //cancel process } } }; ProgressManager.getInstance().runProcessWithProgressAsynchronously(project, InspectionsBundle.message("parsing.inspections.dump.progress.title"), process, new Runnable() { public void run() { SwingUtilities.invokeLater(new Runnable(){ public void run() { final String name = profileName[0]; showOfflineView(project, name, resMap, InspectionsBundle.message("offline.view.title") + " (" + (name != null ? name : InspectionsBundle.message("offline.view.editor.settings.title")) +")"); } }); } }, null, new PerformAnalysisInBackgroundOption(project)); } @SuppressWarnings({"UnusedDeclaration", "WeakerAccess", "UnusedReturnValue"}) //used in TeamCity public static InspectionResultsView showOfflineView(final Project project, @Nullable final String profileName, final Map<String, Map<String, Set<OfflineProblemDescriptor>>> resMap, final String title) { final InspectionProfile inspectionProfile; Profile profile; if (profileName != null) { profile = InspectionProjectProfileManager.getInstance(project).getProfile(profileName); if (profile == null) { profile = InspectionProfileManager.getInstance().getProfiles().get(profileName); } } else { profile = null; } if (profile != null) { inspectionProfile = (InspectionProfile)profile; } else { inspectionProfile = new InspectionProfileImpl("Server Side") { public boolean isToolEnabled(final HighlightDisplayKey key) { return resMap.containsKey(key.toString()); } public HighlightDisplayLevel getErrorLevel(final HighlightDisplayKey key) { return ((InspectionProfile)InspectionProfileManager.getInstance().getRootProfile()).getErrorLevel(key); } public boolean isEditable() { return false; } }; } return showOfflineView(project, resMap, inspectionProfile, title); } public static InspectionResultsView showOfflineView(final Project project, final Map<String, Map<String, Set<OfflineProblemDescriptor>>> resMap, final InspectionProfile inspectionProfile, final String title) { final AnalysisScope scope = new AnalysisScope(project); final InspectionManagerEx managerEx = ((InspectionManagerEx)InspectionManagerEx.getInstance(project)); final GlobalInspectionContextImpl inspectionContext = managerEx.createNewGlobalContext(false); inspectionContext.setExternalProfile(inspectionProfile); inspectionContext.setCurrentScope(scope); inspectionContext.initializeTools(scope, new HashMap<String, Set<InspectionTool>>(), new HashMap<String, Set<InspectionTool>>()); final InspectionResultsView view = new InspectionResultsView(project, inspectionProfile, scope, inspectionContext, new OfflineInspectionRVContentProvider(resMap, project)); ((RefManagerImpl)inspectionContext.getRefManager()).inspectionReadActionStarted(); view.update(); TreeUtil.selectFirstNode(view.getTree()); if (inspectionContext.getContentManager() != null) { //test inspectionContext.addView(view, title); } return view; } }
inspections/impl/com/intellij/codeInspection/actions/ViewOfflineResultsAction.java
/* * Copyright (c) 2000-2007 JetBrains s.r.o. All Rights Reserved. */ /* * User: anna * Date: 09-Jan-2007 */ package com.intellij.codeInspection.actions; import com.intellij.analysis.AnalysisScope; import com.intellij.analysis.PerformAnalysisInBackgroundOption; import com.intellij.codeHighlighting.HighlightDisplayLevel; import com.intellij.codeInsight.daemon.HighlightDisplayKey; import com.intellij.codeInspection.InspectionProfile; import com.intellij.codeInspection.InspectionsBundle; import com.intellij.codeInspection.ex.*; import com.intellij.codeInspection.offlineViewer.OfflineInspectionRVContentProvider; import com.intellij.codeInspection.offlineViewer.OfflineProblemDescriptor; import com.intellij.codeInspection.offlineViewer.OfflineViewParseUtil; import com.intellij.codeInspection.reference.RefManagerImpl; import com.intellij.codeInspection.ui.InspectionResultsView; import com.intellij.ide.highlighter.XmlFileType; import com.intellij.ide.util.BrowseFilesListener; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileChooser.FileChooser; import com.intellij.openapi.fileEditor.impl.LoadTextUtil; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.Computable; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.profile.Profile; import com.intellij.profile.codeInspection.InspectionProfileManager; import com.intellij.profile.codeInspection.InspectionProjectProfileManager; import com.intellij.util.ui.tree.TreeUtil; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.HashMap; import java.util.Map; import java.util.Set; public class ViewOfflineResultsAction extends AnAction { private static final Logger LOG = Logger.getInstance("#com.intellij.codeInspection.actions.ViewOfflineResultsAction"); public void update(AnActionEvent event) { final Presentation presentation = event.getPresentation(); final Project project = event.getData(DataKeys.PROJECT); presentation.setEnabled(project != null); presentation.setVisible(ActionPlaces.MAIN_MENU.equals(event.getPlace())); } public void actionPerformed(AnActionEvent event) { final Project project = event.getData(DataKeys.PROJECT); LOG.assertTrue(project != null); final VirtualFile[] virtualFiles = FileChooser.chooseFiles(project, BrowseFilesListener.SINGLE_DIRECTORY_DESCRIPTOR); if (virtualFiles == null || virtualFiles.length == 0) return; if (!virtualFiles[0].isDirectory()) return; final Map<String, Map<String, Set<OfflineProblemDescriptor>>> resMap = new HashMap<String, Map<String, Set<OfflineProblemDescriptor>>>(); final String [] profileName = new String[1]; final Runnable process = new Runnable() { public void run() { final VirtualFile[] files = virtualFiles[0].getChildren(); try { for (final VirtualFile inspectionFile : files) { if (inspectionFile.isDirectory()) continue; final String shortName = inspectionFile.getNameWithoutExtension(); if (shortName.equals(InspectionApplication.DESCRIPTIONS)) { profileName[0] = ApplicationManager.getApplication().runReadAction( new Computable<String>() { @Nullable public String compute() { return OfflineViewParseUtil.parseProfileName(LoadTextUtil.loadText(inspectionFile).toString()); } } ); } else if (inspectionFile.getFileType() instanceof XmlFileType) { resMap.put(shortName, ApplicationManager.getApplication().runReadAction( new Computable<Map<String, Set<OfflineProblemDescriptor>>>() { public Map<String, Set<OfflineProblemDescriptor>> compute() { return OfflineViewParseUtil.parse(LoadTextUtil.loadText(inspectionFile).toString()); } } )); } } } catch (final Exception e) { //all parse exceptions SwingUtilities.invokeLater(new Runnable() { public void run() { Messages.showInfoMessage(e.getMessage(), InspectionsBundle.message("offline.view.parse.exception.title")); } }); throw new ProcessCanceledException(); //cancel process } } }; ProgressManager.getInstance().runProcessWithProgressAsynchronously(project, InspectionsBundle.message("parsing.inspections.dump.progress.title"), process, new Runnable() { public void run() { SwingUtilities.invokeLater(new Runnable(){ public void run() { final String name = profileName[0]; showOfflineView(project, name, resMap, InspectionsBundle.message("offline.view.title") + " (" + (name != null ? name : InspectionsBundle.message("offline.view.editor.settings.title")) +")"); } }); } }, null, new PerformAnalysisInBackgroundOption(project)); } @SuppressWarnings({"UnusedDeclaration"}) public static InspectionResultsView showOfflineView(final Project project, @Nullable final String profileName, final Map<String, Map<String, Set<OfflineProblemDescriptor>>> resMap, final String title) { final InspectionProfile inspectionProfile; Profile profile; if (profileName != null) { profile = InspectionProjectProfileManager.getInstance(project).getProfile(profileName); if (profile == null) { profile = InspectionProfileManager.getInstance().getProfile(profileName); } } else { profile = null; } if (profile != null) { inspectionProfile = (InspectionProfile)profile; } else { inspectionProfile = new InspectionProfileImpl("Server Side") { public boolean isToolEnabled(final HighlightDisplayKey key) { return resMap.containsKey(key.toString()); } public HighlightDisplayLevel getErrorLevel(final HighlightDisplayKey key) { return ((InspectionProfile)InspectionProfileManager.getInstance().getRootProfile()).getErrorLevel(key); } public boolean isEditable() { return false; } }; } return showOfflineView(project, resMap, inspectionProfile, title); } public static InspectionResultsView showOfflineView(final Project project, final Map<String, Map<String, Set<OfflineProblemDescriptor>>> resMap, final InspectionProfile inspectionProfile, final String title) { final AnalysisScope scope = new AnalysisScope(project); final InspectionManagerEx managerEx = ((InspectionManagerEx)InspectionManagerEx.getInstance(project)); final GlobalInspectionContextImpl inspectionContext = managerEx.createNewGlobalContext(false); inspectionContext.setExternalProfile(inspectionProfile); inspectionContext.setCurrentScope(scope); inspectionContext.initializeTools(scope, new HashMap<String, Set<InspectionTool>>(), new HashMap<String, Set<InspectionTool>>()); final InspectionResultsView view = new InspectionResultsView(project, inspectionProfile, scope, inspectionContext, new OfflineInspectionRVContentProvider(resMap, project)); ((RefManagerImpl)inspectionContext.getRefManager()).inspectionReadActionStarted(); view.update(); TreeUtil.selectFirstNode(view.getTree()); if (inspectionContext.getContentManager() != null) { //test inspectionContext.addView(view, title); } return view; } }
do not use default profile when load results from server
inspections/impl/com/intellij/codeInspection/actions/ViewOfflineResultsAction.java
do not use default profile when load results from server
<ide><path>nspections/impl/com/intellij/codeInspection/actions/ViewOfflineResultsAction.java <ide> }, null, new PerformAnalysisInBackgroundOption(project)); <ide> } <ide> <del> @SuppressWarnings({"UnusedDeclaration"}) <add> @SuppressWarnings({"UnusedDeclaration", "WeakerAccess", "UnusedReturnValue"}) //used in TeamCity <ide> public static InspectionResultsView showOfflineView(final Project project, <ide> @Nullable <ide> final String profileName, <ide> if (profileName != null) { <ide> profile = InspectionProjectProfileManager.getInstance(project).getProfile(profileName); <ide> if (profile == null) { <del> profile = InspectionProfileManager.getInstance().getProfile(profileName); <add> profile = InspectionProfileManager.getInstance().getProfiles().get(profileName); <ide> } <ide> } <ide> else {
Java
apache-2.0
cc17135ac684896538e14633b262639667caa463
0
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.hosted.provision.maintenance; import com.yahoo.component.Version; import com.yahoo.config.provision.ApplicationId; import com.yahoo.config.provision.Flavor; import com.yahoo.config.provision.NodeType; import com.yahoo.jdisc.Metric; import com.yahoo.vespa.applicationmodel.HostName; import com.yahoo.vespa.hosted.provision.Node; import com.yahoo.vespa.hosted.provision.NodeRepository; import com.yahoo.vespa.hosted.provision.node.Allocation; import com.yahoo.vespa.hosted.provision.provisioning.DockerHostCapacity; import com.yahoo.vespa.orchestrator.HostNameNotFoundException; import com.yahoo.vespa.orchestrator.Orchestrator; import com.yahoo.vespa.orchestrator.status.HostStatus; import java.time.Duration; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; /** * @author oyving */ public class MetricsReporter extends Maintainer { private final Metric metric; private final Orchestrator orchestrator; private final Map<Map<String, String>, Metric.Context> contextMap = new HashMap<>(); public MetricsReporter(NodeRepository nodeRepository, Metric metric, Orchestrator orchestrator, Duration interval, JobControl jobControl) { super(nodeRepository, interval, jobControl); this.metric = metric; this.orchestrator = orchestrator; } @Override public void maintain() { List<Node> nodes = nodeRepository().getNodes(); nodes.forEach(this::updateNodeMetrics); updateStateMetrics(nodes); updateDockerMetrics(nodes); } private void updateNodeMetrics(Node node) { // Dimensions automatically added: host, vespaVersion, zone, role, and colo. // 'vespaVersion' is the vespaVersion for the config server and not related // to the node we're making metric for now. Metric.Context context; Optional<Allocation> allocation = node.allocation(); if (allocation.isPresent()) { ApplicationId applicationId = allocation.get().owner(); context = getContextAt( "state", node.state().name(), "hostname", node.hostname(), "tenantName", applicationId.tenant().value(), "applicationId", applicationId.serializedForm().replace(':', '.'), "clustertype", allocation.get().membership().cluster().type().name(), "clusterid", allocation.get().membership().cluster().id().value()); long wantedRestartGeneration = allocation.get().restartGeneration().wanted(); metric.set("wantedRestartGeneration", wantedRestartGeneration, context); long currentRestartGeneration = allocation.get().restartGeneration().wanted(); metric.set("currentRestartGeneration", currentRestartGeneration, context); boolean wantToRestart = currentRestartGeneration < wantedRestartGeneration; metric.set("wantToRestart", wantToRestart ? 1 : 0, context); Version wantedVersion = allocation.get().membership().cluster().vespaVersion(); double wantedVersionNumber = getVersionAsNumber(wantedVersion); metric.set("wantedVespaVersion", wantedVersionNumber, context); Optional<Version> currentVersion = node.status().vespaVersion(); boolean converged = currentVersion.isPresent() && currentVersion.get().equals(wantedVersion); metric.set("wantToChangeVespaVersion", converged ? 0 : 1, context); } else { context = getContextAt( "state", node.state().name(), "hostname", node.hostname()); } Optional<Version> currentVersion = node.status().vespaVersion(); // Node repo checks for !isEmpty(), so let's do that here too. if (currentVersion.isPresent() && !currentVersion.get().isEmpty()) { double currentVersionNumber = getVersionAsNumber(currentVersion.get()); metric.set("currentVespaVersion", currentVersionNumber, context); } long wantedRebootGeneration = node.status().reboot().wanted(); metric.set("wantedRebootGeneration", wantedRebootGeneration, context); long currentRebootGeneration = node.status().reboot().current(); metric.set("currentRebootGeneration", currentRebootGeneration, context); boolean wantToReboot = currentRebootGeneration < wantedRebootGeneration; metric.set("wantToReboot", wantToReboot ? 1 : 0, context); metric.set("wantToRetire", node.status().wantToRetire() ? 1 : 0, context); metric.set("wantToDeprovision", node.status().wantToDeprovision() ? 1 : 0, context); try { HostStatus status = orchestrator.getNodeStatus(new HostName(node.hostname())); boolean allowedToBeDown = status == HostStatus.ALLOWED_TO_BE_DOWN; metric.set("allowedToBeDown", allowedToBeDown ? 1 : 0, context); } catch (HostNameNotFoundException e) { // Ignore } // TODO: Also add metric on whether some services are down on node? } /** * A version 6.163.20 will be returned as a number 163.020. The major * version can normally be inferred. As long as the micro version stays * below 1000 these numbers sort like Version. */ private static double getVersionAsNumber(Version version) { return version.getMinor() + version.getMicro() / 1000.0; } private Metric.Context getContextAt(String... point) { if (point.length % 2 != 0) { throw new IllegalArgumentException("Dimension specification comes in pairs"); } Map<String, String> dimensions = new HashMap<>(); for (int i = 0; i < point.length; i += 2) { dimensions.put(point[i], point[i + 1]); } Metric.Context context = contextMap.get(dimensions); if (context != null) { return context; } context = metric.createContext(dimensions); contextMap.put(dimensions, context); return context; } private void updateStateMetrics(List<Node> nodes) { Map<Node.State, List<Node>> nodesByState = nodes.stream() .collect(Collectors.groupingBy(Node::state)); // Metrics pr state for (Node.State state : Node.State.values()) { List<Node> nodesInState = nodesByState.getOrDefault(state, new ArrayList<>()); long size = nodesInState.stream().filter(node -> node.type() == NodeType.tenant).count(); metric.set("hostedVespa." + state.name() + "Hosts", size, null); } } private void updateDockerMetrics(List<Node> nodes) { // Capacity flavors for docker DockerHostCapacity capacity = new DockerHostCapacity(nodes); metric.set("hostedVespa.docker.totalCapacityCpu", capacity.getCapacityTotal().getCpu(), null); metric.set("hostedVespa.docker.totalCapacityMem", capacity.getCapacityTotal().getMemory(), null); metric.set("hostedVespa.docker.totalCapacityDisk", capacity.getCapacityTotal().getDisk(), null); metric.set("hostedVespa.docker.freeCapacityCpu", capacity.getFreeCapacityTotal().getCpu(), null); metric.set("hostedVespa.docker.freeCapacityMem", capacity.getFreeCapacityTotal().getMemory(), null); metric.set("hostedVespa.docker.freeCapacityDisk", capacity.getFreeCapacityTotal().getDisk(), null); List<Flavor> dockerFlavors = nodeRepository().getAvailableFlavors().getFlavors().stream() .filter(f -> f.getType().equals(Flavor.Type.DOCKER_CONTAINER)) .collect(Collectors.toList()); for (Flavor flavor : dockerFlavors) { Metric.Context context = getContextAt("flavor", flavor.name()); metric.set("hostedVespa.docker.freeCapacityFlavor", capacity.freeCapacityInFlavorEquivalence(flavor), context); metric.set("hostedVespa.docker.idealHeadroomFlavor", flavor.getIdealHeadroom(), context); metric.set("hostedVespa.docker.hostsAvailableFlavor", capacity.getNofHostsAvailableFor(flavor), context); } } }
node-repository/src/main/java/com/yahoo/vespa/hosted/provision/maintenance/MetricsReporter.java
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.hosted.provision.maintenance; import com.yahoo.component.Version; import com.yahoo.config.provision.ApplicationId; import com.yahoo.config.provision.Flavor; import com.yahoo.config.provision.NodeType; import com.yahoo.jdisc.Metric; import com.yahoo.vespa.applicationmodel.HostName; import com.yahoo.vespa.hosted.provision.Node; import com.yahoo.vespa.hosted.provision.NodeRepository; import com.yahoo.vespa.hosted.provision.node.Allocation; import com.yahoo.vespa.hosted.provision.provisioning.DockerHostCapacity; import com.yahoo.vespa.orchestrator.HostNameNotFoundException; import com.yahoo.vespa.orchestrator.Orchestrator; import com.yahoo.vespa.orchestrator.status.HostStatus; import java.time.Duration; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; /** * @author oyving */ public class MetricsReporter extends Maintainer { private final Metric metric; private final Orchestrator orchestrator; private final Map<Map<String, String>, Metric.Context> contextMap = new HashMap<>(); public MetricsReporter(NodeRepository nodeRepository, Metric metric, Orchestrator orchestrator, Duration interval, JobControl jobControl) { super(nodeRepository, interval, jobControl); this.metric = metric; this.orchestrator = orchestrator; } @Override public void maintain() { List<Node> nodes = nodeRepository().getNodes(); nodes.forEach(this::updateNodeMetrics); updateStateMetrics(nodes); updateDockerMetrics(nodes); } private void updateNodeMetrics(Node node) { // Dimensions automatically added: host, vespaVersion, zone, role, and colo. // 'vespaVersion' is the vespaVersion for the config server and not related // to the node we're making metric for now. Metric.Context context; Optional<Allocation> allocation = node.allocation(); if (allocation.isPresent()) { ApplicationId applicationId = allocation.get().owner(); context = getContextAt( "state", node.state().name(), "hostname", node.hostname(), "tenantName", applicationId.tenant().value(), "applicationId", applicationId.serializedForm().replace(':', '.'), "clustertype", allocation.get().membership().cluster().type().name(), "clusterid", allocation.get().membership().cluster().id().value()); long wantedRestartGeneration = allocation.get().restartGeneration().wanted(); metric.set("wantedRestartGeneration", wantedRestartGeneration, context); long currentRestartGeneration = allocation.get().restartGeneration().wanted(); metric.set("currentRestartGeneration", currentRestartGeneration, context); boolean wantToRestart = currentRestartGeneration < wantedRestartGeneration; metric.set("wantToRestart", wantToRestart ? 1 : 0, context); Version wantedVersion = allocation.get().membership().cluster().vespaVersion(); double wantedVersionNumber = getVersionAsNumber(wantedVersion); metric.set("wantedVersion", wantedVersionNumber, context); Optional<Version> currentVersion = node.status().vespaVersion(); boolean converged = currentVersion.isPresent() && currentVersion.get().equals(wantedVersion); metric.set("wantToChangeVersion", converged ? 0 : 1, context); } else { context = getContextAt( "state", node.state().name(), "hostname", node.hostname()); } Optional<Version> currentVersion = node.status().vespaVersion(); // Node repo checks for !isEmpty(), so let's do that here too. if (currentVersion.isPresent() && !currentVersion.get().isEmpty()) { double currentVersionNumber = getVersionAsNumber(currentVersion.get()); metric.set("currentVersion", currentVersionNumber, context); } long wantedRebootGeneration = node.status().reboot().wanted(); metric.set("wantedRebootGeneration", wantedRebootGeneration, context); long currentRebootGeneration = node.status().reboot().current(); metric.set("currentRebootGeneration", currentRebootGeneration, context); boolean wantToReboot = currentRebootGeneration < wantedRebootGeneration; metric.set("wantToReboot", wantToReboot ? 1 : 0, context); metric.set("wantToRetire", node.status().wantToRetire() ? 1 : 0, context); metric.set("wantToDeprovision", node.status().wantToDeprovision() ? 1 : 0, context); try { HostStatus status = orchestrator.getNodeStatus(new HostName(node.hostname())); boolean allowedToBeDown = status == HostStatus.ALLOWED_TO_BE_DOWN; metric.set("allowedToBeDown", allowedToBeDown ? 1 : 0, context); } catch (HostNameNotFoundException e) { // Ignore } // TODO: Also add metric on whether some services are down on node? } /** * A version 6.163.20 will be returned as a number 163.020. The major * version can normally be inferred. As long as the micro version stays * below 1000 these numbers sort like Version. */ private static double getVersionAsNumber(Version version) { return version.getMinor() + version.getMicro() / 1000.0; } private Metric.Context getContextAt(String... point) { if (point.length % 2 != 0) { throw new IllegalArgumentException("Dimension specification comes in pairs"); } Map<String, String> dimensions = new HashMap<>(); for (int i = 0; i < point.length; i += 2) { dimensions.put(point[i], point[i + 1]); } Metric.Context context = contextMap.get(dimensions); if (context != null) { return context; } context = metric.createContext(dimensions); contextMap.put(dimensions, context); return context; } private void updateStateMetrics(List<Node> nodes) { Map<Node.State, List<Node>> nodesByState = nodes.stream() .collect(Collectors.groupingBy(Node::state)); // Metrics pr state for (Node.State state : Node.State.values()) { List<Node> nodesInState = nodesByState.getOrDefault(state, new ArrayList<>()); long size = nodesInState.stream().filter(node -> node.type() == NodeType.tenant).count(); metric.set("hostedVespa." + state.name() + "Hosts", size, null); } } private void updateDockerMetrics(List<Node> nodes) { // Capacity flavors for docker DockerHostCapacity capacity = new DockerHostCapacity(nodes); metric.set("hostedVespa.docker.totalCapacityCpu", capacity.getCapacityTotal().getCpu(), null); metric.set("hostedVespa.docker.totalCapacityMem", capacity.getCapacityTotal().getMemory(), null); metric.set("hostedVespa.docker.totalCapacityDisk", capacity.getCapacityTotal().getDisk(), null); metric.set("hostedVespa.docker.freeCapacityCpu", capacity.getFreeCapacityTotal().getCpu(), null); metric.set("hostedVespa.docker.freeCapacityMem", capacity.getFreeCapacityTotal().getMemory(), null); metric.set("hostedVespa.docker.freeCapacityDisk", capacity.getFreeCapacityTotal().getDisk(), null); List<Flavor> dockerFlavors = nodeRepository().getAvailableFlavors().getFlavors().stream() .filter(f -> f.getType().equals(Flavor.Type.DOCKER_CONTAINER)) .collect(Collectors.toList()); for (Flavor flavor : dockerFlavors) { Metric.Context context = getContextAt("flavor", flavor.name()); metric.set("hostedVespa.docker.freeCapacityFlavor", capacity.freeCapacityInFlavorEquivalence(flavor), context); metric.set("hostedVespa.docker.idealHeadroomFlavor", flavor.getIdealHeadroom(), context); metric.set("hostedVespa.docker.hostsAvailableFlavor", capacity.getNofHostsAvailableFor(flavor), context); } } }
Use VespaVersion instead of Version
node-repository/src/main/java/com/yahoo/vespa/hosted/provision/maintenance/MetricsReporter.java
Use VespaVersion instead of Version
<ide><path>ode-repository/src/main/java/com/yahoo/vespa/hosted/provision/maintenance/MetricsReporter.java <ide> <ide> Version wantedVersion = allocation.get().membership().cluster().vespaVersion(); <ide> double wantedVersionNumber = getVersionAsNumber(wantedVersion); <del> metric.set("wantedVersion", wantedVersionNumber, context); <add> metric.set("wantedVespaVersion", wantedVersionNumber, context); <ide> <ide> Optional<Version> currentVersion = node.status().vespaVersion(); <ide> boolean converged = currentVersion.isPresent() && <ide> currentVersion.get().equals(wantedVersion); <del> metric.set("wantToChangeVersion", converged ? 0 : 1, context); <add> metric.set("wantToChangeVespaVersion", converged ? 0 : 1, context); <ide> } else { <ide> context = getContextAt( <ide> "state", node.state().name(), <ide> // Node repo checks for !isEmpty(), so let's do that here too. <ide> if (currentVersion.isPresent() && !currentVersion.get().isEmpty()) { <ide> double currentVersionNumber = getVersionAsNumber(currentVersion.get()); <del> metric.set("currentVersion", currentVersionNumber, context); <add> metric.set("currentVespaVersion", currentVersionNumber, context); <ide> } <ide> <ide> long wantedRebootGeneration = node.status().reboot().wanted();
JavaScript
apache-2.0
646ba2ff547087ddce2d551266f750b9871afe8c
0
Sage/carbon,Sage/carbon,Sage/carbon
import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react/lib/ReactTestUtils'; import Form from './index'; import Textbox from './../textbox'; import Validation from './../../utils/validations/presence'; import InputGrid from './../input-grid'; import TableRow from './../table-row'; import ImmutableHelper from './../../utils/helpers/immutable'; describe('Form', () => { let instance; beforeEach(() => { instance = TestUtils.renderIntoDocument( <Form model='test' /> ); }); describe('initialize', () => { it('sets the errorCount to 0', () => { expect(instance.state.errorCount).toEqual(0); }); }); describe('incrementErrorCount', () => { it('increments the state error count', () => { instance.setState({ errorCount: 2 }); instance.incrementErrorCount(); expect(instance.state.errorCount).toEqual(3); }); }); describe('decrementErrorCount', () => { it('increments the state error count', () => { instance.setState({ errorCount: 2 }); instance.decrementErrorCount(); expect(instance.state.errorCount).toEqual(1); }); }); describe('attachToForm', () => { beforeEach(() => { instance = TestUtils.renderIntoDocument( <Form model='test'> <Textbox validations={ [Validation] } name='excludedBox' value='' /> <InputGrid name='grid' data={ ImmutableHelper.parseJSON([ { foo: 'bar' } ]) } updateRowHandler={ function(){} } deleteRowHandler={ function(){} } fields={ [ <Textbox validations={ [Validation] } name='box1' value='foo' />, <Textbox validations={ [Validation] } name='box2' value='foo' /> ] } /> </Form> ); }); describe('when the component is a grid', () => { it('adds a key value pair to tables', () => { expect(instance.tables.grid).toBeTruthy(); }); }); describe('when the component is an element in a grid', () => { it('adds a input nested by namespace and row_id', () => { let keys = Object.keys(instance.inputs.grid); expect(Object.keys(instance.inputs.grid[keys[0]]).length).toEqual(2); }); }); describe('when the component is self contained', () => { it('adds a input by its name', () => { expect(instance.inputs.excludedBox).toBeTruthy(); }); }); }); describe('detachFromForm', () => { let textbox1; let textbox2; let grid; let excludedTextbox; beforeEach(() => { textbox1 = <Textbox validations={ [Validation] } name='box1' value='' />; textbox2 = <Textbox validations={ [Validation] } name='box2' value='' />; excludedTextbox = <Textbox validations={ [Validation] } name='excludedBox' value='' />; grid = <InputGrid name='grid' data={ ImmutableHelper.parseJSON([ { box1: 'bar' } ]) } updateRowHandler={ function(){} } deleteRowHandler={ function(){} } fields={ [ textbox1, textbox2 ] } /> instance = TestUtils.renderIntoDocument( <Form model='test'> { excludedTextbox } { grid } </Form> ); }); describe('when the component is a grid', () => { it('removes a key value pair from tables', () => { expect(instance.tables.grid).toBeTruthy(); instance.detachFromForm(instance.tables.grid); expect(instance.tables.grid).toBeFalsy(); }); }); describe('when the component is a row in a grid', () => { let regular; beforeEach(() => { let regularTable = document.createElement('table'); regularTable.innerHTML = '<tbody></tbody>'; regular = ReactDOM.render((<TableRow name='regular' key='regular_1' namespace='namespace' row_id='row_id' data={ ImmutableHelper.parseJSON({ foo: 'text', bar: '1.00' }) } fields={ [ textbox1, textbox2 ] } />), regularTable.children[0]); instance.attachToForm(regular); }); it('removes a input nested by namespace and row_id', () => { expect(instance.inputs.namespace.row_id.regular).toBeTruthy(); instance.detachFromForm(regular); expect(instance.inputs.namespace.row_id.regular).toBeFalsy(); }); }); describe('when the component is self contained', () => { it('removes a input by its name', () => { expect(instance.inputs.excludedBox).toBeTruthy(); instance.detachFromForm(instance.inputs.excludedBox); expect(instance.inputs.excludedBox).toBeFalsy(); }); }); }); describe('handleOnSubmit', () => { describe('valid input', () => { it('submits the form', () => { spyOn(instance, 'setState'); let form = TestUtils.findRenderedDOMComponentWithTag(instance, 'form'); TestUtils.Simulate.submit(form); expect(instance.setState).toHaveBeenCalledWith({ errorCount: 0 }); }); }); describe('invalid input', () => { it('does not not submit the form', () => { instance = TestUtils.renderIntoDocument( <Form model='test'> <Textbox validations={ [Validation] } name='test' value='' /> </Form> ); spyOn(instance, 'setState'); let form = TestUtils.findRenderedDOMComponentWithTag(instance, 'form'); TestUtils.Simulate.submit(form); expect(instance.setState).toHaveBeenCalledWith({ errorCount :1 }); }); }); describe('submitting a input grid', () => { it('removes placeholder when the form is valid', () => { instance = TestUtils.renderIntoDocument( <Form model='test'> <InputGrid name='test' data={ ImmutableHelper.parseJSON([ { box: 'bar' } ]) } updateRowHandler={ function(){} } deleteRowHandler={ function(){} } fields={ [<Textbox validation={ [Validation] } name='box' />] } /> </Form> ); spyOn(instance, 'setState'); let form = TestUtils.findRenderedDOMComponentWithTag(instance, 'form'); spyOn(instance.tables.test, 'setState'); TestUtils.Simulate.submit(form); expect(instance.setState).toHaveBeenCalledWith({ errorCount : 0 }); expect(instance.tables.test.setState).toHaveBeenCalledWith({ placeholder: false }); }); it('checks the validation of each field', () => { let baseData = ImmutableHelper.parseJSON( [ { box1: 'bar', box2: '' } ] ); let textbox1 = <Textbox validations={ [Validation] } name='box1' />; let textbox2 = <Textbox validations={ [Validation] } name='box2' />; let grid = <InputGrid name='grid' data={ baseData } updateRowHandler={ function(){} } deleteRowHandler={ function(){} } fields={ [ textbox1, textbox2 ] } /> instance = TestUtils.renderIntoDocument( <Form model='test'> { grid } </Form> ); let form = TestUtils.findRenderedDOMComponentWithTag(instance, 'form'); TestUtils.Simulate.submit(form); expect(instance.state.errorCount).toEqual(1); }); }); }); describe('htmlProps', () => { it('pulls out the model from props', () => { expect(instance.htmlProps().model).toBeFalsy(); }); it('sets the className', () => { expect(instance.htmlProps().className).toEqual('ui-form'); }); }); describe('cancelForm', () => { describe('when window history is availiable', () => { it('redirects to the previous page', () => { spyOn(window.history, 'back') let cancel = TestUtils.scryRenderedDOMComponentsWithTag(instance, 'button')[0]; TestUtils.Simulate.click(cancel); expect(window.history.back).toHaveBeenCalled(); }); }); }); describe('mainClasses', () => { it('returns the ui-form class', () => { expect(instance.mainClasses).toEqual('ui-form'); }); }); describe('render', () => { it('renders a parent form', () => { let form = TestUtils.findRenderedDOMComponentWithTag(instance, 'form') expect(form.className).toEqual('ui-form'); }); it('renders a hidden CSRFToken field', () => { let csrf = TestUtils.findRenderedDOMComponentWithTag(instance, 'input') expect(csrf.type).toEqual('hidden'); expect(csrf.readOnly).toBeTruthy(); }); describe('buttons', () => { let buttons; let buttonContainers; beforeEach(() => { buttons = TestUtils.scryRenderedDOMComponentsWithTag(instance, 'button') buttonContainers = TestUtils.scryRenderedDOMComponentsWithTag(instance, 'div'); }); it('renders two buttons', () => { expect(buttons.length).toEqual(2); }); it('renders a secondary cancel button with cancelClasses', () => { expect(buttons[0].className).toEqual('ui-button ui-button--secondary'); expect(buttonContainers[0].className).toEqual('ui-form__cancel'); }); it('renders a primary save button with saveClasses', () => { expect(buttons[1].className).toEqual('ui-button ui-button--primary'); expect(buttonContainers[1].className).toEqual('ui-form__save'); }); }); describe('errorMessage', () => { beforeEach(() => { instance.setState({ errorCount: 2}); }); it('displays an error message', () => { let summary = TestUtils.findRenderedDOMComponentWithClass(instance, 'ui-form__summary') expect(summary.textContent).toEqual('There are 2 errors'); }); it('adds a invalid CSS class on the Save button div', () => { let saveContainer = TestUtils.scryRenderedDOMComponentsWithTag(instance, 'div')[1]; expect(saveContainer.className).toEqual('ui-form__save ui-form__save--invalid'); }); }); }); });
src/components/form/__spec__.js
import React from 'react'; import TestUtils from 'react/lib/ReactTestUtils'; import Form from './index'; import Textbox from './../textbox'; import Validation from './../../utils/validations/presence'; import InputGrid from './../input-grid'; import ImmutableHelper from './../../utils/helpers/immutable'; describe('Form', () => { let instance; beforeEach(() => { instance = TestUtils.renderIntoDocument( <Form model='test' /> ); }); describe('initialize', () => { it('sets the errorCount to 0', () => { expect(instance.state.errorCount).toEqual(0); }); }); describe('incrementErrorCount', () => { it('increments the state error count', () => { instance.setState({ errorCount: 2 }); instance.incrementErrorCount(); expect(instance.state.errorCount).toEqual(3); }); }); describe('decrementErrorCount', () => { it('increments the state error count', () => { instance.setState({ errorCount: 2 }); instance.decrementErrorCount(); expect(instance.state.errorCount).toEqual(1); }); }); describe('attachToForm', () => { beforeEach(() => { instance = TestUtils.renderIntoDocument( <Form model='test'> <Textbox validations={ [Validation] } name='excludedBox' /> <InputGrid name='grid' data={ ImmutableHelper.parseJSON([ { foo: 'bar' } ]) } updateRowHandler={ function(){} } deleteRowHandler={ function(){} } fields={ [ <Textbox validations={ [Validation] } name='box1' />, <Textbox validations={ [Validation] } name='box2' /> ] } /> </Form> ); }); describe('when the component is a grid', () => { it('adds a key value pair to tables', () => { expect(instance.tables.grid).toBeTruthy(); }); }); describe('when the component is an element in a grid', () => { it('adds a input nested by namespace and row_id', () => { let keys = Object.keys(instance.inputs.grid); expect(Object.keys(instance.inputs.grid[keys[0]]).length).toEqual(2); }); }); describe('when the component is self contained', () => { it('adds a input by its name', () => { expect(instance.inputs.excludedBox).toBeTruthy(); }); }); }); describe('detachFromForm', () => { let textbox1; let textbox2; let grid; let excludedTextbox; beforeEach(() => { textbox1 = <Textbox validations={ [Validation] } name='box1' />; textbox2 = <Textbox validations={ [Validation] } name='box2' />; excludedTextbox = <Textbox validations={ [Validation] } name='excludedBox' />; grid = <InputGrid name='grid' data={ ImmutableHelper.parseJSON([ { foo: 'bar' } ]) } updateRowHandler={ function(){} } deleteRowHandler={ function(){} } fields={ [ textbox1, textbox2 ] } /> instance = TestUtils.renderIntoDocument( <Form model='test'> { excludedTextbox } { grid } </Form> ); }); describe('when the component is a grid', () => { it('removes a key value pair from tables', () => { expect(instance.tables.grid).toBeTruthy(); instance.detachFromForm(instance.tables.grid); expect(instance.tables.grid).toBeFalsy(); }); }); describe('when the component is a a element in a grid', () => { it('removes a input nested by namespace and row_id', () => { let keys = Object.keys(instance.inputs.grid); instance.detachFromForm(instance.tables.grid); expect(Object.keys(instance.inputs.grid[keys[0]]).length).toEqual(2); }); }); describe('when the component is self contained', () => { it('removes a input by its name', () => { expect(instance.inputs.excludedBox).toBeTruthy(); instance.detachFromForm(instance.inputs.excludedBox); expect(instance.inputs.excludedBox).toBeFalsy(); }); }); }); describe('handleOnSubmit', () => { describe('valid input', () => { it('submits the form', () => { spyOn(instance, 'setState'); let form = TestUtils.findRenderedDOMComponentWithTag(instance, 'form'); TestUtils.Simulate.submit(form); expect(instance.setState).toHaveBeenCalledWith({ errorCount: 0 }); }); }); describe('invalid input', () => { it('does not not submit the form', () => { instance = TestUtils.renderIntoDocument( <Form model='test'> <Textbox validations={ [Validation] } name='test'/> </Form> ); spyOn(instance, 'setState'); let form = TestUtils.findRenderedDOMComponentWithTag(instance, 'form'); TestUtils.Simulate.submit(form); expect(instance.setState).toHaveBeenCalledWith({ errorCount :1 }); }); }); describe('submitting a input grid', () => { it('removes placeholders when the form is valid', () => { instance = TestUtils.renderIntoDocument( <Form model='test'> <InputGrid name='test' data={ ImmutableHelper.parseJSON([ { foo: 'bar' } ]) } updateRowHandler={ function(){} } deleteRowHandler={ function(){} } fields={ [<Textbox name='box' />] } /> </Form> ); spyOn(instance, 'setState'); let form = TestUtils.findRenderedDOMComponentWithTag(instance, 'form'); spyOn(instance.tables.test, 'setState'); TestUtils.Simulate.submit(form); expect(instance.setState).toHaveBeenCalledWith({ errorCount : 0 }); expect(instance.tables.test.setState).toHaveBeenCalledWith({ placeholder: false }); }); }); }); describe('htmlProps', () => { it('pulls out the model from props', () => { expect(instance.htmlProps().model).toBeFalsy(); }); it('sets the className', () => { expect(instance.htmlProps().className).toEqual('ui-form'); }); }); describe('cancelForm', () => { describe('when window history is availiable', () => { it('redirects to the previous page', () => { spyOn(window.history, 'back') let cancel = TestUtils.scryRenderedDOMComponentsWithTag(instance, 'button')[0]; TestUtils.Simulate.click(cancel); expect(window.history.back).toHaveBeenCalled(); }); }); }); describe('mainClasses', () => { it('returns the ui-form class', () => { expect(instance.mainClasses).toEqual('ui-form'); }); }); describe('render', () => { it('renders a parent form', () => { let form = TestUtils.findRenderedDOMComponentWithTag(instance, 'form') expect(form.className).toEqual('ui-form'); }); it('renders a hidden CSRFToken field', () => { let csrf = TestUtils.findRenderedDOMComponentWithTag(instance, 'input') expect(csrf.type).toEqual('hidden'); expect(csrf.readOnly).toBeTruthy(); }); describe('buttons', () => { let buttons; let buttonContainers; beforeEach(() => { buttons = TestUtils.scryRenderedDOMComponentsWithTag(instance, 'button') buttonContainers = TestUtils.scryRenderedDOMComponentsWithTag(instance, 'div'); }); it('renders two buttons', () => { expect(buttons.length).toEqual(2); }); it('renders a secondary cancel button with cancelClasses', () => { expect(buttons[0].className).toEqual('ui-button ui-button--secondary'); expect(buttonContainers[0].className).toEqual('ui-form__cancel'); }); it('renders a primary save button with saveClasses', () => { expect(buttons[1].className).toEqual('ui-button ui-button--primary'); expect(buttonContainers[1].className).toEqual('ui-form__save'); }); }); describe('errorMessage', () => { beforeEach(() => { instance.setState({ errorCount: 2}); }); it('displays an error message', () => { let summary = TestUtils.findRenderedDOMComponentWithClass(instance, 'ui-form__summary') expect(summary.textContent).toEqual('There are 2 errors'); }); it('adds a invalid CSS class on the Save button div', () => { let saveContainer = TestUtils.scryRenderedDOMComponentsWithTag(instance, 'div')[1]; expect(saveContainer.className).toEqual('ui-form__save ui-form__save--invalid'); }); }); }); });
9.8.8% coverage for form
src/components/form/__spec__.js
9.8.8% coverage for form
<ide><path>rc/components/form/__spec__.js <ide> import React from 'react'; <add>import ReactDOM from 'react-dom'; <ide> import TestUtils from 'react/lib/ReactTestUtils'; <ide> import Form from './index'; <ide> import Textbox from './../textbox'; <ide> import Validation from './../../utils/validations/presence'; <ide> import InputGrid from './../input-grid'; <add>import TableRow from './../table-row'; <ide> import ImmutableHelper from './../../utils/helpers/immutable'; <ide> <ide> describe('Form', () => { <ide> beforeEach(() => { <ide> instance = TestUtils.renderIntoDocument( <ide> <Form model='test'> <del> <Textbox validations={ [Validation] } name='excludedBox' /> <add> <Textbox validations={ [Validation] } name='excludedBox' value='' /> <ide> <InputGrid <ide> name='grid' <ide> data={ ImmutableHelper.parseJSON([ { foo: 'bar' } ]) } <ide> updateRowHandler={ function(){} } <ide> deleteRowHandler={ function(){} } <ide> fields={ [ <del> <Textbox validations={ [Validation] } name='box1' />, <del> <Textbox validations={ [Validation] } name='box2' /> <add> <Textbox validations={ [Validation] } name='box1' value='foo' />, <add> <Textbox validations={ [Validation] } name='box2' value='foo' /> <ide> ] } <ide> /> <ide> </Form> <ide> let excludedTextbox; <ide> <ide> beforeEach(() => { <del> <del> textbox1 = <Textbox validations={ [Validation] } name='box1' />; <del> textbox2 = <Textbox validations={ [Validation] } name='box2' />; <del> excludedTextbox = <Textbox validations={ [Validation] } name='excludedBox' />; <add> textbox1 = <Textbox validations={ [Validation] } name='box1' value='' />; <add> textbox2 = <Textbox validations={ [Validation] } name='box2' value='' />; <add> excludedTextbox = <Textbox validations={ [Validation] } name='excludedBox' value='' />; <ide> grid = <InputGrid <ide> name='grid' <del> data={ ImmutableHelper.parseJSON([ { foo: 'bar' } ]) } <add> data={ ImmutableHelper.parseJSON([ { box1: 'bar' } ]) } <ide> updateRowHandler={ function(){} } <ide> deleteRowHandler={ function(){} } <ide> fields={ [ textbox1, textbox2 ] } <ide> }); <ide> }); <ide> <del> describe('when the component is a a element in a grid', () => { <add> describe('when the component is a row in a grid', () => { <add> let regular; <add> <add> beforeEach(() => { <add> let regularTable = document.createElement('table'); <add> regularTable.innerHTML = '<tbody></tbody>'; <add> <add> regular = ReactDOM.render((<TableRow <add> name='regular' <add> key='regular_1' <add> namespace='namespace' <add> row_id='row_id' <add> data={ ImmutableHelper.parseJSON({ foo: 'text', bar: '1.00' }) } <add> fields={ [ textbox1, textbox2 ] } <add> />), regularTable.children[0]); <add> <add> instance.attachToForm(regular); <add> }); <add> <ide> it('removes a input nested by namespace and row_id', () => { <del> let keys = Object.keys(instance.inputs.grid); <del> instance.detachFromForm(instance.tables.grid); <del> expect(Object.keys(instance.inputs.grid[keys[0]]).length).toEqual(2); <add> expect(instance.inputs.namespace.row_id.regular).toBeTruthy(); <add> instance.detachFromForm(regular); <add> expect(instance.inputs.namespace.row_id.regular).toBeFalsy(); <ide> }); <ide> }); <ide> <ide> it('does not not submit the form', () => { <ide> instance = TestUtils.renderIntoDocument( <ide> <Form model='test'> <del> <Textbox validations={ [Validation] } name='test'/> <add> <Textbox validations={ [Validation] } name='test' value='' /> <ide> </Form> <ide> ); <ide> <ide> }); <ide> <ide> describe('submitting a input grid', () => { <del> it('removes placeholders when the form is valid', () => { <add> it('removes placeholder when the form is valid', () => { <ide> instance = TestUtils.renderIntoDocument( <ide> <Form model='test'> <ide> <InputGrid <ide> name='test' <del> data={ ImmutableHelper.parseJSON([ { foo: 'bar' } ]) } <add> data={ ImmutableHelper.parseJSON([ { box: 'bar' } ]) } <ide> updateRowHandler={ function(){} } <ide> deleteRowHandler={ function(){} } <del> fields={ [<Textbox name='box' />] } <add> fields={ [<Textbox validation={ [Validation] } name='box' />] } <ide> /> <ide> </Form> <ide> ); <ide> TestUtils.Simulate.submit(form); <ide> expect(instance.setState).toHaveBeenCalledWith({ errorCount : 0 }); <ide> expect(instance.tables.test.setState).toHaveBeenCalledWith({ placeholder: false }); <add> }); <add> <add> it('checks the validation of each field', () => { <add> let baseData = ImmutableHelper.parseJSON( <add> [ { box1: 'bar', box2: '' } ] <add> ); <add> <add> let textbox1 = <Textbox validations={ [Validation] } name='box1' />; <add> let textbox2 = <Textbox validations={ [Validation] } name='box2' />; <add> <add> let grid = <InputGrid <add> name='grid' <add> data={ baseData } <add> updateRowHandler={ function(){} } <add> deleteRowHandler={ function(){} } <add> fields={ [ textbox1, textbox2 ] } /> <add> <add> instance = TestUtils.renderIntoDocument( <add> <Form model='test'> <add> { grid } <add> </Form> <add> ); <add> <add> let form = TestUtils.findRenderedDOMComponentWithTag(instance, 'form'); <add> TestUtils.Simulate.submit(form); <add> expect(instance.state.errorCount).toEqual(1); <ide> }); <ide> }); <ide> });
Java
agpl-3.0
12f0e300e26daf3375ab7c2d946410cafe81a888
0
KinshipSoftware/KinOathKinshipArchiver,PeterWithers/temp-to-delete1,KinshipSoftware/KinOathKinshipArchiver,PeterWithers/temp-to-delete1
package nl.mpi.kinnate.ui; import java.awt.BorderLayout; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.HashSet; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.tree.DefaultTreeCellRenderer; import nl.mpi.arbil.data.ArbilDataNode; import nl.mpi.arbil.data.ArbilDataNodeLoader; import nl.mpi.arbil.ui.ArbilTree; import nl.mpi.arbil.ui.ArbilTreeRenderer; import nl.mpi.kinnate.kindata.EntityData; /** * Document : EgoSelectionPanel * Created on : Sep 29, 2010, 13:12:01 PM * Author : Peter Withers */ public class EgoSelectionPanel extends JPanel { private ArbilTree egoTree; // DefaultTreeModel egoModel; // DefaultMutableTreeNode egoRootNode; private ArbilTree requiredTree; // DefaultTreeModel requiredModel; // DefaultMutableTreeNode requiredRootNode; private ArbilTree impliedTree; // DefaultTreeModel impliedModel; // DefaultMutableTreeNode impliedRootNode; public EgoSelectionPanel() { DefaultTreeCellRenderer cellRenderer = new DefaultTreeCellRenderer(); // egoRootNode = new DefaultMutableTreeNode(new JLabel("Ego", cellRenderer.getDefaultOpenIcon(), JLabel.LEFT)); // egoModel = new DefaultTreeModel(egoRootNode); // egoTree = new JTree(egoModel); egoTree = new ArbilTree(); // egoTree.setRootVisible(false); egoTree.setCellRenderer(new ArbilTreeRenderer()); // requiredRootNode = new DefaultMutableTreeNode(new JLabel("Required", cellRenderer.getDefaultOpenIcon(), JLabel.LEFT)); // requiredModel = new DefaultTreeModel(requiredRootNode); // requiredTree = new JTree(requiredModel); requiredTree = new ArbilTree(); // requiredTree.setRootVisible(false); requiredTree.setCellRenderer(new ArbilTreeRenderer()); // impliedRootNode = new DefaultMutableTreeNode(new JLabel("Implied", cellRenderer.getDefaultOpenIcon(), JLabel.LEFT)); // impliedModel = new DefaultTreeModel(impliedRootNode); // impliedTree = new JTree(impliedModel); impliedTree = new ArbilTree(); // impliedTree.setRootVisible(false); impliedTree.setCellRenderer(new ArbilTreeRenderer()); // egoTree.setRootVisible(false); this.setLayout(new BorderLayout()); JPanel treePanel1 = new JPanel(new BorderLayout()); JPanel treePanel2 = new JPanel(new BorderLayout()); // treePanel.setLayout(new BoxLayout(treePanel, BoxLayout.PAGE_AXIS)); JScrollPane outerScrolPane = new JScrollPane(treePanel1); // this.setBorder(javax.swing.BorderFactory.createTitledBorder("Selected Ego")); JPanel labelPanel1 = new JPanel(new BorderLayout()); JPanel labelPanel2 = new JPanel(new BorderLayout()); JPanel labelPanel3 = new JPanel(new BorderLayout()); labelPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Ego")); labelPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Required")); labelPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Implied")); labelPanel1.add(egoTree); labelPanel2.add(requiredTree); labelPanel3.add(impliedTree); egoTree.setBackground(labelPanel1.getBackground()); requiredTree.setBackground(labelPanel1.getBackground()); impliedTree.setBackground(labelPanel1.getBackground()); treePanel1.add(labelPanel1, BorderLayout.PAGE_START); treePanel1.add(treePanel2, BorderLayout.CENTER); treePanel2.add(labelPanel2, BorderLayout.PAGE_START); treePanel2.add(labelPanel3, BorderLayout.CENTER); this.add(outerScrolPane, BorderLayout.CENTER); } public void setTreeNodes(HashSet<String> egoIdentifiers, HashSet<String> requiredEntityIdentifiers, EntityData[] allEntities) { ArrayList<ArbilDataNode> egoNodeArray = new ArrayList<ArbilDataNode>(); ArrayList<ArbilDataNode> requiredNodeArray = new ArrayList<ArbilDataNode>(); ArrayList<ArbilDataNode> remainingNodeArray = new ArrayList<ArbilDataNode>(); for (EntityData entityData : allEntities) { try { ArbilDataNode arbilDataNode = ArbilDataNodeLoader.getSingleInstance().getArbilDataNode(null, new URI(entityData.getEntityPath())); if (entityData.isEgo || egoIdentifiers.contains(entityData.getUniqueIdentifier())) { egoNodeArray.add(arbilDataNode); } else if (requiredEntityIdentifiers.contains(entityData.getUniqueIdentifier())) { requiredNodeArray.add(arbilDataNode); } else { remainingNodeArray.add(arbilDataNode); } } catch (URISyntaxException exception) { System.err.println(exception.getMessage()); } // setEgoNodes(egoNodeArray, egoTree, egoModel, egoRootNode); egoTree.rootNodeChildren = egoNodeArray.toArray(new ArbilDataNode[]{}); egoTree.requestResort(); // setEgoNodes(requiredNodeArray, requiredTree, requiredModel, requiredRootNode); requiredTree.rootNodeChildren = requiredNodeArray.toArray(new ArbilDataNode[]{}); requiredTree.requestResort(); // setEgoNodes(remainingNodeArray, impliedTree, impliedModel, impliedRootNode); impliedTree.rootNodeChildren = remainingNodeArray.toArray(new ArbilDataNode[]{}); impliedTree.requestResort(); } } // private void setEgoNodes(ArrayList<ArbilDataNode> selectedNodes, JTree currentTree, DefaultTreeModel currentModel, DefaultMutableTreeNode currentRootNode) { // currentRootNode.removeAllChildren(); // currentModel.nodeStructureChanged(currentRootNode); // if (selectedNodes != null) { // for (ArbilDataNode imdiTreeObject : selectedNodes) { //// System.out.println("adding node: " + imdiTreeObject.toString()); // currentModel.insertNodeInto(new DefaultMutableTreeNode(imdiTreeObject), currentRootNode, 0); // } // currentTree.expandPath(new TreePath(currentRootNode.getPath())); // } // } }
src/main/java/nl/mpi/kinnate/ui/EgoSelectionPanel.java
package nl.mpi.kinnate.ui; import java.awt.BorderLayout; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.HashSet; import javax.swing.BoxLayout; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; import nl.mpi.arbil.data.ArbilDataNode; import nl.mpi.arbil.data.ArbilDataNodeLoader; import nl.mpi.arbil.ui.ArbilTreeRenderer; import nl.mpi.kinnate.kindata.EntityData; /** * Document : EgoSelectionPanel * Created on : Sep 29, 2010, 13:12:01 PM * Author : Peter Withers */ public class EgoSelectionPanel extends JPanel { private JTree egoTree; DefaultTreeModel egoModel; DefaultMutableTreeNode egoRootNode; private JTree requiredTree; DefaultTreeModel requiredModel; DefaultMutableTreeNode requiredRootNode; private JTree impliedTree; DefaultTreeModel impliedModel; DefaultMutableTreeNode impliedRootNode; public EgoSelectionPanel() { DefaultTreeCellRenderer cellRenderer = new DefaultTreeCellRenderer(); egoRootNode = new DefaultMutableTreeNode(new JLabel("Ego", cellRenderer.getDefaultOpenIcon(), JLabel.LEFT)); egoModel = new DefaultTreeModel(egoRootNode); egoTree = new JTree(egoModel); egoTree.setCellRenderer(new ArbilTreeRenderer()); requiredRootNode = new DefaultMutableTreeNode(new JLabel("Required", cellRenderer.getDefaultOpenIcon(), JLabel.LEFT)); requiredModel = new DefaultTreeModel(requiredRootNode); requiredTree = new JTree(requiredModel); requiredTree.setCellRenderer(new ArbilTreeRenderer()); impliedRootNode = new DefaultMutableTreeNode(new JLabel("Implied", cellRenderer.getDefaultOpenIcon(), JLabel.LEFT)); impliedModel = new DefaultTreeModel(impliedRootNode); impliedTree = new JTree(impliedModel); impliedTree.setCellRenderer(new ArbilTreeRenderer()); // egoTree.setRootVisible(false); this.setLayout(new BorderLayout()); JPanel treePanel = new JPanel(); treePanel.setLayout(new BoxLayout(treePanel, BoxLayout.PAGE_AXIS)); JScrollPane outerScrolPane = new JScrollPane(treePanel); // this.setBorder(javax.swing.BorderFactory.createTitledBorder("Selected Ego")); treePanel.add(egoTree, BorderLayout.PAGE_START); treePanel.add(requiredTree, BorderLayout.CENTER); treePanel.add(impliedTree, BorderLayout.PAGE_END); this.add(outerScrolPane, BorderLayout.CENTER); } public void setTreeNodes(HashSet<String> egoIdentifiers, HashSet<String> requiredEntityIdentifiers, EntityData[] allEntities) { ArrayList<ArbilDataNode> egoNodeArray = new ArrayList<ArbilDataNode>(); ArrayList<ArbilDataNode> requiredNodeArray = new ArrayList<ArbilDataNode>(); ArrayList<ArbilDataNode> remainingNodeArray = new ArrayList<ArbilDataNode>(); for (EntityData entityData : allEntities) { try { ArbilDataNode arbilDataNode = ArbilDataNodeLoader.getSingleInstance().getArbilDataNode(null, new URI(entityData.getEntityPath())); if (entityData.isEgo || egoIdentifiers.contains(entityData.getUniqueIdentifier())) { egoNodeArray.add(arbilDataNode); } else if (requiredEntityIdentifiers.contains(entityData.getUniqueIdentifier())) { requiredNodeArray.add(arbilDataNode); } else { remainingNodeArray.add(arbilDataNode); } } catch (URISyntaxException exception) { System.err.println(exception.getMessage()); } setEgoNodes(egoNodeArray, egoTree, egoModel, egoRootNode); setEgoNodes(requiredNodeArray, requiredTree, requiredModel, requiredRootNode); setEgoNodes(remainingNodeArray, impliedTree, impliedModel, impliedRootNode); } } private void setEgoNodes(ArrayList<ArbilDataNode> selectedNodes, JTree currentTree, DefaultTreeModel currentModel, DefaultMutableTreeNode currentRootNode) { currentRootNode.removeAllChildren(); currentModel.nodeStructureChanged(currentRootNode); if (selectedNodes != null) { for (ArbilDataNode imdiTreeObject : selectedNodes) { // System.out.println("adding node: " + imdiTreeObject.toString()); currentModel.insertNodeInto(new DefaultMutableTreeNode(imdiTreeObject), currentRootNode, 0); } currentTree.expandPath(new TreePath(currentRootNode.getPath())); } } }
Added the use of Arbil trees so that archive data can be accessed from the diagram window. Added separate trees to show the various entities: ego, required (selected as required for the diagram) and implied (selected via kintype strings).
src/main/java/nl/mpi/kinnate/ui/EgoSelectionPanel.java
Added the use of Arbil trees so that archive data can be accessed from the diagram window. Added separate trees to show the various entities: ego, required (selected as required for the diagram) and implied (selected via kintype strings).
<ide><path>rc/main/java/nl/mpi/kinnate/ui/EgoSelectionPanel.java <ide> import java.net.URISyntaxException; <ide> import java.util.ArrayList; <ide> import java.util.HashSet; <del>import javax.swing.BoxLayout; <del>import javax.swing.JLabel; <ide> import javax.swing.JPanel; <ide> import javax.swing.JScrollPane; <del>import javax.swing.JTree; <del>import javax.swing.tree.DefaultMutableTreeNode; <ide> import javax.swing.tree.DefaultTreeCellRenderer; <del>import javax.swing.tree.DefaultTreeModel; <del>import javax.swing.tree.TreePath; <ide> import nl.mpi.arbil.data.ArbilDataNode; <ide> import nl.mpi.arbil.data.ArbilDataNodeLoader; <add>import nl.mpi.arbil.ui.ArbilTree; <ide> import nl.mpi.arbil.ui.ArbilTreeRenderer; <ide> import nl.mpi.kinnate.kindata.EntityData; <ide> <ide> */ <ide> public class EgoSelectionPanel extends JPanel { <ide> <del> private JTree egoTree; <del> DefaultTreeModel egoModel; <del> DefaultMutableTreeNode egoRootNode; <del> private JTree requiredTree; <del> DefaultTreeModel requiredModel; <del> DefaultMutableTreeNode requiredRootNode; <del> private JTree impliedTree; <del> DefaultTreeModel impliedModel; <del> DefaultMutableTreeNode impliedRootNode; <add> private ArbilTree egoTree; <add>// DefaultTreeModel egoModel; <add>// DefaultMutableTreeNode egoRootNode; <add> private ArbilTree requiredTree; <add>// DefaultTreeModel requiredModel; <add>// DefaultMutableTreeNode requiredRootNode; <add> private ArbilTree impliedTree; <add>// DefaultTreeModel impliedModel; <add>// DefaultMutableTreeNode impliedRootNode; <ide> <ide> public EgoSelectionPanel() { <ide> DefaultTreeCellRenderer cellRenderer = new DefaultTreeCellRenderer(); <ide> <del> egoRootNode = new DefaultMutableTreeNode(new JLabel("Ego", cellRenderer.getDefaultOpenIcon(), JLabel.LEFT)); <del> egoModel = new DefaultTreeModel(egoRootNode); <del> egoTree = new JTree(egoModel); <add>// egoRootNode = new DefaultMutableTreeNode(new JLabel("Ego", cellRenderer.getDefaultOpenIcon(), JLabel.LEFT)); <add>// egoModel = new DefaultTreeModel(egoRootNode); <add>// egoTree = new JTree(egoModel); <add> egoTree = new ArbilTree(); <add>// egoTree.setRootVisible(false); <ide> egoTree.setCellRenderer(new ArbilTreeRenderer()); <ide> <del> requiredRootNode = new DefaultMutableTreeNode(new JLabel("Required", cellRenderer.getDefaultOpenIcon(), JLabel.LEFT)); <del> requiredModel = new DefaultTreeModel(requiredRootNode); <del> requiredTree = new JTree(requiredModel); <add>// requiredRootNode = new DefaultMutableTreeNode(new JLabel("Required", cellRenderer.getDefaultOpenIcon(), JLabel.LEFT)); <add>// requiredModel = new DefaultTreeModel(requiredRootNode); <add>// requiredTree = new JTree(requiredModel); <add> requiredTree = new ArbilTree(); <add>// requiredTree.setRootVisible(false); <ide> requiredTree.setCellRenderer(new ArbilTreeRenderer()); <ide> <del> impliedRootNode = new DefaultMutableTreeNode(new JLabel("Implied", cellRenderer.getDefaultOpenIcon(), JLabel.LEFT)); <del> impliedModel = new DefaultTreeModel(impliedRootNode); <del> impliedTree = new JTree(impliedModel); <add>// impliedRootNode = new DefaultMutableTreeNode(new JLabel("Implied", cellRenderer.getDefaultOpenIcon(), JLabel.LEFT)); <add>// impliedModel = new DefaultTreeModel(impliedRootNode); <add>// impliedTree = new JTree(impliedModel); <add> impliedTree = new ArbilTree(); <add>// impliedTree.setRootVisible(false); <ide> impliedTree.setCellRenderer(new ArbilTreeRenderer()); <ide> <ide> // egoTree.setRootVisible(false); <ide> this.setLayout(new BorderLayout()); <del> JPanel treePanel = new JPanel(); <del> treePanel.setLayout(new BoxLayout(treePanel, BoxLayout.PAGE_AXIS)); <del> JScrollPane outerScrolPane = new JScrollPane(treePanel); <add> JPanel treePanel1 = new JPanel(new BorderLayout()); <add> JPanel treePanel2 = new JPanel(new BorderLayout()); <add>// treePanel.setLayout(new BoxLayout(treePanel, BoxLayout.PAGE_AXIS)); <add> JScrollPane outerScrolPane = new JScrollPane(treePanel1); <ide> // this.setBorder(javax.swing.BorderFactory.createTitledBorder("Selected Ego")); <del> treePanel.add(egoTree, BorderLayout.PAGE_START); <del> treePanel.add(requiredTree, BorderLayout.CENTER); <del> treePanel.add(impliedTree, BorderLayout.PAGE_END); <add> JPanel labelPanel1 = new JPanel(new BorderLayout()); <add> JPanel labelPanel2 = new JPanel(new BorderLayout()); <add> JPanel labelPanel3 = new JPanel(new BorderLayout()); <add> labelPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Ego")); <add> labelPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Required")); <add> labelPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Implied")); <add> labelPanel1.add(egoTree); <add> labelPanel2.add(requiredTree); <add> labelPanel3.add(impliedTree); <add> egoTree.setBackground(labelPanel1.getBackground()); <add> requiredTree.setBackground(labelPanel1.getBackground()); <add> impliedTree.setBackground(labelPanel1.getBackground()); <add> treePanel1.add(labelPanel1, BorderLayout.PAGE_START); <add> treePanel1.add(treePanel2, BorderLayout.CENTER); <add> treePanel2.add(labelPanel2, BorderLayout.PAGE_START); <add> treePanel2.add(labelPanel3, BorderLayout.CENTER); <ide> this.add(outerScrolPane, BorderLayout.CENTER); <ide> } <ide> <ide> } catch (URISyntaxException exception) { <ide> System.err.println(exception.getMessage()); <ide> } <del> setEgoNodes(egoNodeArray, egoTree, egoModel, egoRootNode); <del> setEgoNodes(requiredNodeArray, requiredTree, requiredModel, requiredRootNode); <del> setEgoNodes(remainingNodeArray, impliedTree, impliedModel, impliedRootNode); <add>// setEgoNodes(egoNodeArray, egoTree, egoModel, egoRootNode); <add> egoTree.rootNodeChildren = egoNodeArray.toArray(new ArbilDataNode[]{}); <add> egoTree.requestResort(); <add>// setEgoNodes(requiredNodeArray, requiredTree, requiredModel, requiredRootNode); <add> requiredTree.rootNodeChildren = requiredNodeArray.toArray(new ArbilDataNode[]{}); <add> requiredTree.requestResort(); <add>// setEgoNodes(remainingNodeArray, impliedTree, impliedModel, impliedRootNode); <add> impliedTree.rootNodeChildren = remainingNodeArray.toArray(new ArbilDataNode[]{}); <add> impliedTree.requestResort(); <ide> } <ide> } <ide> <del> private void setEgoNodes(ArrayList<ArbilDataNode> selectedNodes, JTree currentTree, DefaultTreeModel currentModel, DefaultMutableTreeNode currentRootNode) { <del> currentRootNode.removeAllChildren(); <del> currentModel.nodeStructureChanged(currentRootNode); <del> if (selectedNodes != null) { <del> for (ArbilDataNode imdiTreeObject : selectedNodes) { <del>// System.out.println("adding node: " + imdiTreeObject.toString()); <del> currentModel.insertNodeInto(new DefaultMutableTreeNode(imdiTreeObject), currentRootNode, 0); <del> } <del> currentTree.expandPath(new TreePath(currentRootNode.getPath())); <del> } <del> } <add>// private void setEgoNodes(ArrayList<ArbilDataNode> selectedNodes, JTree currentTree, DefaultTreeModel currentModel, DefaultMutableTreeNode currentRootNode) { <add>// currentRootNode.removeAllChildren(); <add>// currentModel.nodeStructureChanged(currentRootNode); <add>// if (selectedNodes != null) { <add>// for (ArbilDataNode imdiTreeObject : selectedNodes) { <add>//// System.out.println("adding node: " + imdiTreeObject.toString()); <add>// currentModel.insertNodeInto(new DefaultMutableTreeNode(imdiTreeObject), currentRootNode, 0); <add>// } <add>// currentTree.expandPath(new TreePath(currentRootNode.getPath())); <add>// } <add>// } <ide> }
Java
apache-2.0
4a9baec60f0c58e935b4baddba66acbf2eff0ae4
0
hank/feathercoinj
/** * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.feathercoin.core; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import java.math.BigInteger; import java.util.Arrays; /** * Parses and generates private keys in the form used by the Feathercoin "dumpprivkey" command. This is the private key * bytes with a header byte and 4 checksum bytes at the end. If there are 33 private key bytes instead of 32, then * the last byte is a discriminator value for the compressed pubkey. */ public class DumpedPrivateKey extends VersionedChecksummedBytes { private boolean compressed; // Used by ECKey.getPrivateKeyEncoded() DumpedPrivateKey(NetworkParameters params, byte[] keyBytes, boolean compressed) { //super(params.dumpedPrivateKeyHeader, encode(keyBytes, compressed)); // feathercoin-wallet Issue 3 // Fix courtesy of d4n13 super(params.dumpedPrivateKeyHeader + params.addressHeader, encode(keyBytes, compressed)); this.compressed = compressed; } private static byte[] encode(byte[] keyBytes, boolean compressed) { Preconditions.checkArgument(keyBytes.length == 32, "Private keys must be 32 bytes"); if (!compressed) { return keyBytes; } else { // Keys that have compressed public components have an extra 1 byte on the end in dumped form. byte[] bytes = new byte[33]; System.arraycopy(keyBytes, 0, bytes, 0, 32); bytes[32] = 1; return bytes; } } /** * Parses the given private key as created by the "dumpprivkey" Feathercoin C++ RPC. * * @param params The expected network parameters of the key. If you don't care, provide null. * @param encoded The base58 encoded string. * @throws AddressFormatException If the string is invalid or the header byte doesn't match the network params. */ public DumpedPrivateKey(NetworkParameters params, String encoded) throws AddressFormatException { super(encoded); if (params != null && version != (params.dumpedPrivateKeyHeader + params.addressHeader)) throw new AddressFormatException("Mismatched version number, trying to cross networks? " + version + " vs " + (params.dumpedPrivateKeyHeader + params.addressHeader)); if (bytes.length == 33) { compressed = true; bytes = Arrays.copyOf(bytes, 32); // Chop off the additional marker byte. } else if (bytes.length == 32) { compressed = false; } else { throw new AddressFormatException("Wrong number of bytes for a private key, not 32 or 33"); } } /** * Returns an ECKey created from this encoded private key. */ public ECKey getKey() { return new ECKey(new BigInteger(1, bytes), null, compressed); } @Override public boolean equals(Object other) { // This odd construction is to avoid anti-symmetry of equality: where a.equals(b) != b.equals(a). boolean result = false; if (other instanceof VersionedChecksummedBytes) { result = Arrays.equals(bytes, ((VersionedChecksummedBytes)other).bytes); } if (other instanceof DumpedPrivateKey) { DumpedPrivateKey o = (DumpedPrivateKey) other; result = Arrays.equals(bytes, o.bytes) && version == o.version && compressed == o.compressed; } return result; } @Override public int hashCode() { return Objects.hashCode(bytes, version, compressed); } }
core/src/main/java/com/google/feathercoin/core/DumpedPrivateKey.java
/** * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.feathercoin.core; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import java.math.BigInteger; import java.util.Arrays; /** * Parses and generates private keys in the form used by the Feathercoin "dumpprivkey" command. This is the private key * bytes with a header byte and 4 checksum bytes at the end. If there are 33 private key bytes instead of 32, then * the last byte is a discriminator value for the compressed pubkey. */ public class DumpedPrivateKey extends VersionedChecksummedBytes { private boolean compressed; // Used by ECKey.getPrivateKeyEncoded() DumpedPrivateKey(NetworkParameters params, byte[] keyBytes, boolean compressed) { //super(params.dumpedPrivateKeyHeader, encode(keyBytes, compressed)); // feathercoin-wallet Issue 3 // Fix courtesy of d4n13 super(params.dumpedPrivateKeyHeader + params.addressHeader, encode(keyBytes, compressed)); this.compressed = compressed; } private static byte[] encode(byte[] keyBytes, boolean compressed) { Preconditions.checkArgument(keyBytes.length == 32, "Private keys must be 32 bytes"); if (!compressed) { return keyBytes; } else { // Keys that have compressed public components have an extra 1 byte on the end in dumped form. byte[] bytes = new byte[33]; System.arraycopy(keyBytes, 0, bytes, 0, 32); bytes[32] = 1; return bytes; } } /** * Parses the given private key as created by the "dumpprivkey" Feathercoin C++ RPC. * * @param params The expected network parameters of the key. If you don't care, provide null. * @param encoded The base58 encoded string. * @throws AddressFormatException If the string is invalid or the header byte doesn't match the network params. */ public DumpedPrivateKey(NetworkParameters params, String encoded) throws AddressFormatException { super(encoded); if (params != null && version != params.dumpedPrivateKeyHeader + params.addressHeader) throw new AddressFormatException("Mismatched version number, trying to cross networks? " + version + " vs " + params.dumpedPrivateKeyHeader + params.addressHeader); if (bytes.length == 33) { compressed = true; bytes = Arrays.copyOf(bytes, 32); // Chop off the additional marker byte. } else if (bytes.length == 32) { compressed = false; } else { throw new AddressFormatException("Wrong number of bytes for a private key, not 32 or 33"); } } /** * Returns an ECKey created from this encoded private key. */ public ECKey getKey() { return new ECKey(new BigInteger(1, bytes), null, compressed); } @Override public boolean equals(Object other) { // This odd construction is to avoid anti-symmetry of equality: where a.equals(b) != b.equals(a). boolean result = false; if (other instanceof VersionedChecksummedBytes) { result = Arrays.equals(bytes, ((VersionedChecksummedBytes)other).bytes); } if (other instanceof DumpedPrivateKey) { DumpedPrivateKey o = (DumpedPrivateKey) other; result = Arrays.equals(bytes, o.bytes) && version == o.version && compressed == o.compressed; } return result; } @Override public int hashCode() { return Objects.hashCode(bytes, version, compressed); } }
Quick string concat fix
core/src/main/java/com/google/feathercoin/core/DumpedPrivateKey.java
Quick string concat fix
<ide><path>ore/src/main/java/com/google/feathercoin/core/DumpedPrivateKey.java <ide> */ <ide> public DumpedPrivateKey(NetworkParameters params, String encoded) throws AddressFormatException { <ide> super(encoded); <del> if (params != null && version != params.dumpedPrivateKeyHeader + params.addressHeader) <add> if (params != null && version != (params.dumpedPrivateKeyHeader + params.addressHeader)) <ide> throw new AddressFormatException("Mismatched version number, trying to cross networks? " + version + <del> " vs " + params.dumpedPrivateKeyHeader + params.addressHeader); <add> " vs " + (params.dumpedPrivateKeyHeader + params.addressHeader)); <ide> if (bytes.length == 33) { <ide> compressed = true; <ide> bytes = Arrays.copyOf(bytes, 32); // Chop off the additional marker byte.
JavaScript
mit
dc14e43f51bc52493c63390cebd6f333b23bd098
0
ArnaudBuchholz/gpf-js,ArnaudBuchholz/gpf-js
/** * @file Encoding helpers */ /*#ifndef(UMD)*/ "use strict"; /*global _gpfDefine*/ // Shortcut for gpf.define /*global _gpfErrorDeclare*/ // Declare new gpf.Error names /*exported _gpfEncodings*/ /*#endif*/ _gpfErrorDeclare("encoding", { "encodingNotSupported": "Encoding not supported", "encodingEOFWithUnprocessedBytes": "Unexpected end of stream: unprocessed bytes" }); var /** * Map that relates encoding to the appropriate encoder/decoder * * encode (string input) : byte[] * decode (byte[] input, byte[] unprocessed) : string * * @type {Object} */ _gpfEncodings = {}, //region Encoder / Decoder stream implementation /** * Encoder stream * * @class gpf.encoding.EncoderStream * @extends gpf.stream.BufferedOnRead * @implements gpf.interfaces.IReadableStream */ EncoderStream = _gpfDefine("EncoderStream", gpf.stream.BufferedOnRead, { "+": { /** * @param {Function} encoder * @param {gpf.interfaces.IReadableStream} input */ constructor: function (encoder, input) { this._super(input); this._encoder = encoder; } }, "#": { // @inheritdoc gpf.stream.BufferedOnRead#_addToBuffer _addToBuffer: function (buffer) { this._buffer = this._buffer.concat(this._encoder(buffer)); this._bufferLength = this._buffer.length; }, // @inheritdoc gpf.stream.BufferedOnRead#_readFromBuffer _readFromBuffer: gpf.stream.BufferedOnRead.prototype._readFromByteBuffer }, "-": { // @property {Function} _encoder: null } }), /** * Decoder stream * * @class gpf.encoding.DecoderStream * @extends gpf.stream.BufferedOnRead * @implements gpf.interfaces.IReadableStream */ DecoderStream = _gpfDefine("DecoderStream", gpf.stream.BufferedOnRead, { "+": { /** * @param {Function} decoder * @param {gpf.interfaces.IReadableStream} input */ constructor: function (decoder, input) { this._super(input); this._decoder = decoder; } }, "#": { // @inheritdoc gpf.stream.BufferedOnRead#_addToBuffer _addToBuffer: function (buffer) { var string; if (this._unprocessed.length) { buffer = this._unprocessed.concat(buffer); } this._unprocessed = []; string = this._decoder(buffer, this._unprocessed); this._buffer.push(string); this._bufferLength += string.length; }, // @inheritdoc gpf.stream.BufferedOnRead#_endOfInputStream _endOfInputStream: function () { if (this._unprocessed.length) { gpf.Error.encodingEOFWithUnprocessedBytes(); } }, // @inheritdoc gpf.stream.BufferedOnRead#_readFromBuffer _readFromBuffer: gpf.stream.BufferedOnRead.prototype._readFromStringBuffer }, "-": { /** * @type {Function} * @private */ _decoder: null, /** * @type {Number[]} * @private */ _unprocessed: [] } }); //endregion gpf.encoding = { /** * Create a encoder to convert an input text stream into an output * binary buffer. * * @param {gpf.interfaces.IReadableStream} input * @param {String} encoding * @return {gpf.interfaces.IReadableStream} */ createEncoder: function (input, encoding) { var module = _gpfEncodings[encoding]; if (undefined === module) { gpf.Error.encodingNotSupported(); } return new EncoderStream(module[0], input); }, /** * Create a decoder to convert an input binary stream into an output * string. * * @param {gpf.interfaces.IReadableStream} input * @param {String} encoding * @return {gpf.interfaces.IReadableStream} */ createDecoder: function (input, encoding) { var module = _gpfEncodings[encoding]; if (undefined === module) { gpf.Error.encodingNotSupported(); } return new DecoderStream(module[1], input); } };
src/encoding.js
/** * @file Encoding helpers */ /*#ifndef(UMD)*/ "use strict"; /*global _gpfDefine*/ // Shortcut for gpf.define /*global _gpfErrorDeclare*/ // Declare new gpf.Error names /*exported _gpfEncodings*/ /*#endif*/ _gpfErrorDeclare("encoding", { "encodingNotSupported": "Encoding not supported", "encodingEOFWithUnprocessedBytes": "Unexpected end of stream: unprocessed bytes" }); var /** * Map that relates encoding to the appropriate encoder/decoder * * encode (string input) : byte[] * decode (byte[] input, byte[] unprocessed) : string * * @type {Object} */ _gpfEncodings = {}, //region Encoder / Decoder stream implementation /** * Encoder stream * * @class gpf.encoding.EncoderStream * @extends gpf.stream.BufferedOnRead * @implements gpf.interfaces.IReadableStream */ EncoderStream = _gpfDefine("EncoderStream", gpf.stream.BufferedOnRead, { "+": { /** * @param {Function} encoder * @param {gpf.interfaces.IReadableStream} input */ constructor: function (encoder, input) { this._super(input); this._encoder = encoder; } }, "#": { // @inheritdoc gpf.stream.BufferedOnRead#_addToBuffer _addToBuffer: function (buffer) { this._buffer = this._buffer.concat(this._encoder(buffer)); this._bufferLength = this._buffer.length; }, // @inheritdoc gpf.stream.BufferedOnRead#_readFromBuffer _readFromBuffer: gpf.stream.BufferedOnRead.prototype._readFromByteBuffer }, "-": { // @property {Function} _encoder: null } }), /** * Decoder stream * * @class gpf.encoding.DecoderStream * @extends gpf.stream.BufferedOnRead * @implements gpf.interfaces.IReadableStream */ DecoderStream = _gpfDefine("DecoderStream", gpf.stream.BufferedOnRead, { "+": { /** * @param {Function} decoder * @param {gpf.interfaces.IReadableStream} input */ constructor: function (decoder, input) { this._super(input); this._decoder = decoder; } }, "#": { // @inheritdoc gpf.stream.BufferedOnRead#_addToBuffer _addToBuffer: function (buffer) { var string; if (this._unprocessed.length) { buffer = this._unprocessed.concat(buffer); } this._unprocessed = []; string = this._decoder(buffer, this._unprocessed); this._buffer.push(string); this._bufferLength += string.length; }, // @inheritdoc gpf.stream.BufferedOnRead#_endOfInputStream _endOfInputStream: function () { if (this._unprocessed.length) { throw gpf.Error.encodingEOFWithUnprocessedBytes(); } }, // @inheritdoc gpf.stream.BufferedOnRead#_readFromBuffer _readFromBuffer: gpf.stream.BufferedOnRead.prototype._readFromStringBuffer }, "-": { /** * @type {Function} * @private */ _decoder: null, /** * @type {Number[]} * @private */ _unprocessed: [] } }); //endregion gpf.encoding = { /** * Create a encoder to convert an input text stream into an output * binary buffer. * * @param {gpf.interfaces.IReadableStream} input * @param {String} encoding * @return {gpf.interfaces.IReadableStream} */ createEncoder: function (input, encoding) { var module = _gpfEncodings[encoding]; if (undefined === module) { throw gpf.Error.encodingNotSupported(); } return new EncoderStream(module[0], input); }, /** * Create a decoder to convert an input binary stream into an output * string. * * @param {gpf.interfaces.IReadableStream} input * @param {String} encoding * @return {gpf.interfaces.IReadableStream} */ createDecoder: function (input, encoding) { var module = _gpfEncodings[encoding]; if (undefined === module) { throw gpf.Error.encodingNotSupported(); } return new DecoderStream(module[1], input); } };
Removes throw
src/encoding.js
Removes throw
<ide><path>rc/encoding.js <ide> // @inheritdoc gpf.stream.BufferedOnRead#_endOfInputStream <ide> _endOfInputStream: function () { <ide> if (this._unprocessed.length) { <del> throw gpf.Error.encodingEOFWithUnprocessedBytes(); <add> gpf.Error.encodingEOFWithUnprocessedBytes(); <ide> } <ide> }, <ide> <ide> createEncoder: function (input, encoding) { <ide> var module = _gpfEncodings[encoding]; <ide> if (undefined === module) { <del> throw gpf.Error.encodingNotSupported(); <add> gpf.Error.encodingNotSupported(); <ide> } <ide> return new EncoderStream(module[0], input); <ide> }, <ide> createDecoder: function (input, encoding) { <ide> var module = _gpfEncodings[encoding]; <ide> if (undefined === module) { <del> throw gpf.Error.encodingNotSupported(); <add> gpf.Error.encodingNotSupported(); <ide> } <ide> return new DecoderStream(module[1], input); <ide> }
Java
apache-2.0
21e804f13ac6b81ee127f4e52f7af4fe45bb4c6e
0
fazlan-nazeem/carbon-apimgt,ruks/carbon-apimgt,ruks/carbon-apimgt,praminda/carbon-apimgt,prasa7/carbon-apimgt,tharindu1st/carbon-apimgt,uvindra/carbon-apimgt,malinthaprasan/carbon-apimgt,malinthaprasan/carbon-apimgt,fazlan-nazeem/carbon-apimgt,wso2/carbon-apimgt,fazlan-nazeem/carbon-apimgt,isharac/carbon-apimgt,praminda/carbon-apimgt,tharikaGitHub/carbon-apimgt,wso2/carbon-apimgt,chamilaadhi/carbon-apimgt,prasa7/carbon-apimgt,isharac/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,chamilaadhi/carbon-apimgt,malinthaprasan/carbon-apimgt,uvindra/carbon-apimgt,ruks/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,chamilaadhi/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,praminda/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,tharikaGitHub/carbon-apimgt,wso2/carbon-apimgt,malinthaprasan/carbon-apimgt,prasa7/carbon-apimgt,prasa7/carbon-apimgt,tharindu1st/carbon-apimgt,isharac/carbon-apimgt,tharikaGitHub/carbon-apimgt,tharindu1st/carbon-apimgt,wso2/carbon-apimgt,tharikaGitHub/carbon-apimgt,ruks/carbon-apimgt,tharindu1st/carbon-apimgt,uvindra/carbon-apimgt,chamilaadhi/carbon-apimgt,fazlan-nazeem/carbon-apimgt,isharac/carbon-apimgt,uvindra/carbon-apimgt
package org.wso2.carbon.apimgt.gateway.throttling.publisher; import org.apache.axiom.soap.SOAPBody; import org.apache.axiom.soap.SOAPEnvelope; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.synapse.MessageContext; import org.apache.synapse.core.axis2.Axis2MessageContext; import org.apache.synapse.rest.RESTConstants; import org.apache.synapse.transport.passthru.util.RelayUtils; import org.json.simple.JSONObject; import org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext; import org.wso2.carbon.apimgt.gateway.handlers.throttling.APIThrottleConstants; import org.wso2.carbon.apimgt.gateway.internal.ServiceReferenceHolder; import org.wso2.carbon.apimgt.gateway.utils.GatewayUtils; import org.wso2.carbon.apimgt.impl.APIConstants; import org.wso2.carbon.apimgt.impl.dto.ThrottleProperties; import org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO; import org.wso2.carbon.apimgt.impl.utils.APIUtil; import org.wso2.carbon.databridge.agent.DataPublisher; import java.io.IOException; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Map; import java.util.TreeMap; import javax.xml.stream.XMLStreamException; /** * This class is responsible for executing data publishing logic. This class implements runnable interface and * need to execute using thread pool executor. Primary task of this class it is accept message context as parameter * and perform time consuming data extraction and publish event to data publisher. Having data extraction and * transformation logic in this class will help to reduce overhead added to main message flow. */ public class DataProcessAndPublishingAgent implements Runnable { private static final Log log = LogFactory.getLog(DataProcessAndPublishingAgent.class); private static String streamID = "org.wso2.throttle.request.stream:1.0.0"; private MessageContext messageContext; private DataPublisher dataPublisher; String applicationLevelThrottleKey; String applicationLevelTier; String apiLevelThrottleKey; String apiLevelTier; String subscriptionLevelThrottleKey; String subscriptionLevelTier; String resourceLevelThrottleKey; String authorizedUser; String resourceLevelTier; String apiContext; String apiVersion; String appTenant; String apiTenant; String apiName; String appId; Map<String, String> headersMap; private AuthenticationContext authenticationContext; private long messageSizeInBytes; public DataProcessAndPublishingAgent() { dataPublisher = getDataPublisher(); } /** * This method will clean data references. This method should call whenever we return data process and publish * agent back to pool. Every time when we add new property we need to implement cleaning logic as well. */ public void clearDataReference() { this.authenticationContext = null; this.messageContext = null; this.applicationLevelThrottleKey = null; this.applicationLevelTier = null; this.apiLevelThrottleKey = null; this.applicationLevelTier = null; this.subscriptionLevelThrottleKey = null; this.subscriptionLevelTier = null; this.resourceLevelThrottleKey = null; this.resourceLevelTier = null; this.authorizedUser = null; this.apiContext = null; this.apiVersion = null; this.appTenant = null; this.apiTenant = null; this.appId = null; this.apiName = null; this.messageSizeInBytes = 0; } /** * This method will use to set message context. */ public void setDataReference(String applicationLevelThrottleKey, String applicationLevelTier, String apiLevelThrottleKey, String apiLevelTier, String subscriptionLevelThrottleKey, String subscriptionLevelTier, String resourceLevelThrottleKey, String resourceLevelTier, String authorizedUser, String apiContext, String apiVersion, String appTenant, String apiTenant, String appId, MessageContext messageContext, AuthenticationContext authenticationContext) { if (!StringUtils.isEmpty(apiLevelTier)) { resourceLevelTier = apiLevelTier; resourceLevelThrottleKey = apiLevelThrottleKey; } this.authenticationContext = authenticationContext; this.messageContext = messageContext; this.applicationLevelThrottleKey = applicationLevelThrottleKey; this.applicationLevelTier = applicationLevelTier; this.apiLevelThrottleKey = apiLevelThrottleKey; this.subscriptionLevelThrottleKey = subscriptionLevelThrottleKey; this.subscriptionLevelTier = subscriptionLevelTier; this.resourceLevelThrottleKey = resourceLevelThrottleKey; this.resourceLevelTier = resourceLevelTier; this.authorizedUser = authorizedUser; this.apiContext = apiContext; this.apiVersion = apiVersion; this.appTenant = appTenant; this.apiTenant = apiTenant; this.appId = appId; this.apiName = GatewayUtils.getAPINameFromContextAndVersion(messageContext); this.messageSizeInBytes = 0; ArrayList<VerbInfoDTO> list = (ArrayList<VerbInfoDTO>) messageContext.getProperty(APIConstants.VERB_INFO_DTO); boolean isVerbInfoContentAware = false; if (list != null && !list.isEmpty()) { VerbInfoDTO verbInfoDTO = list.get(0); isVerbInfoContentAware = verbInfoDTO.isContentAware(); } //Build the message if needed from here since it cannot be done from the run() method because content //in axis2MessageContext is modified. if (authenticationContext.isContentAwareTierPresent() || isVerbInfoContentAware) { org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext) .getAxis2MessageContext(); TreeMap<String, String> transportHeaderMap = (TreeMap<String, String>) axis2MessageContext .getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); Object contentLength = transportHeaderMap.get(APIThrottleConstants.CONTENT_LENGTH); if (contentLength != null) { log.debug("Content lenght found in the request. Using it as the message size.."); messageSizeInBytes = Long.parseLong(contentLength.toString()); } else { log.debug("Building the message to get the message size.."); try { buildMessage(axis2MessageContext); } catch (Exception ex) { //In case of any exception, it won't be propagated up,and set response size to 0 log.error("Error occurred while building the message to" + " calculate the response body size", ex); } SOAPEnvelope env = messageContext.getEnvelope(); if (env != null) { SOAPBody soapbody = env.getBody(); if (soapbody != null) { byte[] size = soapbody.toString().getBytes(Charset.defaultCharset()); messageSizeInBytes = size.length; } } } } if (getThrottleProperties().isEnableHeaderConditions()) { org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext) .getAxis2MessageContext(); TreeMap<String, String> transportHeaderMap = (TreeMap<String, String>) axis2MessageContext .getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); //Set transport headers of the message. Header Map will be put to the JSON Map which gets transferred // to CEP. Since this operation runs asynchronously if we are to get the header Map present in the // messageContext a ConcurrentModificationException will be thrown. Reason is at the time of sending the // request out, header map is modified by the Synapse layer. It's to avoid this problem a clone of the // map is used. if (transportHeaderMap != null) { this.headersMap = (Map<String, String>) transportHeaderMap.clone(); } } } public void run() { JSONObject jsonObMap = new JSONObject(); org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext) .getAxis2MessageContext(); String remoteIP = GatewayUtils.getIp(axis2MessageContext); if (log.isDebugEnabled()) { log.debug("Remote IP address : " + remoteIP); } if (remoteIP != null && remoteIP.length() > 0) { if (remoteIP.contains(":") && remoteIP.split(":").length == 2) { log.warn("Client port will be ignored and only the IP address (IPV4) will concern from " + remoteIP); remoteIP = remoteIP.split(":")[0]; } try { InetAddress address = APIUtil.getAddress(remoteIP); if (address instanceof Inet4Address) { jsonObMap.put(APIThrottleConstants.IP, APIUtil.ipToLong(remoteIP)); jsonObMap.put(APIThrottleConstants.IPv6, 0); } else if (address instanceof Inet6Address) { jsonObMap.put(APIThrottleConstants.IPv6, APIUtil.ipToBigInteger(remoteIP)); jsonObMap.put(APIThrottleConstants.IP, 0); } } catch (UnknownHostException e) { //send empty value as ip log.error("Error while parsing host IP " + remoteIP, e); jsonObMap.put(APIThrottleConstants.IPv6, 0); jsonObMap.put(APIThrottleConstants.IP, 0); } } //HeaderMap will only be set if the Header Publishing has been enabled. if (this.headersMap != null) { jsonObMap.putAll(this.headersMap); } //Setting query parameters if (getThrottleProperties().isEnableQueryParamConditions()) { Map<String, String> queryParams = GatewayUtils.getQueryParams(axis2MessageContext); if (queryParams != null) { jsonObMap.putAll(queryParams); } } //Publish jwt claims if (getThrottleProperties().isEnableJwtConditions()) { if (authenticationContext.getCallerToken() != null) { Map assertions = GatewayUtils.getJWTClaims(authenticationContext); if (assertions != null) { jsonObMap.putAll(assertions); } } } //this parameter will be used to capture message size and pass it to calculation logic ArrayList<VerbInfoDTO> list = (ArrayList<VerbInfoDTO>) messageContext.getProperty(APIConstants.VERB_INFO_DTO); boolean isVerbInfoContentAware = false; if (list != null && !list.isEmpty()) { VerbInfoDTO verbInfoDTO = list.get(0); isVerbInfoContentAware = verbInfoDTO.isContentAware(); } if (authenticationContext.isContentAwareTierPresent() || isVerbInfoContentAware) { if (log.isDebugEnabled()) { log.debug("Message size: " + messageSizeInBytes + "B"); } jsonObMap.put(APIThrottleConstants.MESSAGE_SIZE, messageSizeInBytes); if (!StringUtils.isEmpty(authenticationContext.getApplicationName())) { jsonObMap.put(APIThrottleConstants.APPLICATION_NAME, authenticationContext.getApplicationName()); } if (!StringUtils.isEmpty(authenticationContext.getProductName()) && !StringUtils .isEmpty(authenticationContext.getProductProvider())) { jsonObMap.put(APIThrottleConstants.SUBSCRIPTION_TYPE, APIConstants.API_PRODUCT_SUBSCRIPTION_TYPE); } else { jsonObMap.put(APIThrottleConstants.SUBSCRIPTION_TYPE, APIConstants.API_SUBSCRIPTION_TYPE); } } Object[] objects = new Object[]{messageContext.getMessageID(), this.applicationLevelThrottleKey, this.applicationLevelTier, this.apiLevelThrottleKey, this.apiLevelTier, this.subscriptionLevelThrottleKey, this.subscriptionLevelTier, this.resourceLevelThrottleKey, this.resourceLevelTier, this.authorizedUser, this.apiContext, this.apiVersion, this.appTenant, this.apiTenant, this.appId, this.apiName, jsonObMap.toString()}; org.wso2.carbon.databridge.commons.Event event = new org.wso2.carbon.databridge.commons.Event(streamID, System.currentTimeMillis(), null, null, objects); dataPublisher.tryPublish(event); } protected void buildMessage(org.apache.axis2.context.MessageContext axis2MessageContext) throws IOException, XMLStreamException { RelayUtils.buildMessage(axis2MessageContext); } protected ThrottleProperties getThrottleProperties() { return ServiceReferenceHolder.getInstance().getThrottleProperties(); } protected DataPublisher getDataPublisher() { return ThrottleDataPublisher.getDataPublisher(); } }
components/apimgt/org.wso2.carbon.apimgt.gateway/src/main/java/org/wso2/carbon/apimgt/gateway/throttling/publisher/DataProcessAndPublishingAgent.java
package org.wso2.carbon.apimgt.gateway.throttling.publisher; import org.apache.axiom.soap.SOAPBody; import org.apache.axiom.soap.SOAPEnvelope; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.synapse.MessageContext; import org.apache.synapse.core.axis2.Axis2MessageContext; import org.apache.synapse.rest.RESTConstants; import org.apache.synapse.transport.passthru.util.RelayUtils; import org.json.simple.JSONObject; import org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext; import org.wso2.carbon.apimgt.gateway.handlers.throttling.APIThrottleConstants; import org.wso2.carbon.apimgt.gateway.internal.ServiceReferenceHolder; import org.wso2.carbon.apimgt.gateway.utils.GatewayUtils; import org.wso2.carbon.apimgt.impl.APIConstants; import org.wso2.carbon.apimgt.impl.dto.ThrottleProperties; import org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO; import org.wso2.carbon.apimgt.impl.utils.APIUtil; import org.wso2.carbon.databridge.agent.DataPublisher; import java.io.IOException; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Map; import java.util.TreeMap; import javax.xml.stream.XMLStreamException; /** * This class is responsible for executing data publishing logic. This class implements runnable interface and * need to execute using thread pool executor. Primary task of this class it is accept message context as parameter * and perform time consuming data extraction and publish event to data publisher. Having data extraction and * transformation logic in this class will help to reduce overhead added to main message flow. */ public class DataProcessAndPublishingAgent implements Runnable { private static final Log log = LogFactory.getLog(DataProcessAndPublishingAgent.class); private static String streamID = "org.wso2.throttle.request.stream:1.0.0"; private MessageContext messageContext; private DataPublisher dataPublisher; String applicationLevelThrottleKey; String applicationLevelTier; String apiLevelThrottleKey; String apiLevelTier; String subscriptionLevelThrottleKey; String subscriptionLevelTier; String resourceLevelThrottleKey; String authorizedUser; String resourceLevelTier; String apiContext; String apiVersion; String appTenant; String apiTenant; String apiName; String appId; Map<String, String> headersMap; private AuthenticationContext authenticationContext; private long messageSizeInBytes; public DataProcessAndPublishingAgent() { dataPublisher = getDataPublisher(); } /** * This method will clean data references. This method should call whenever we return data process and publish * agent back to pool. Every time when we add new property we need to implement cleaning logic as well. */ public void clearDataReference() { this.authenticationContext = null; this.messageContext = null; this.applicationLevelThrottleKey = null; this.applicationLevelTier = null; this.apiLevelThrottleKey = null; this.applicationLevelTier = null; this.subscriptionLevelThrottleKey = null; this.subscriptionLevelTier = null; this.resourceLevelThrottleKey = null; this.resourceLevelTier = null; this.authorizedUser = null; this.apiContext = null; this.apiVersion = null; this.appTenant = null; this.apiTenant = null; this.appId = null; this.apiName = null; this.messageSizeInBytes = 0; } /** * This method will use to set message context. */ public void setDataReference(String applicationLevelThrottleKey, String applicationLevelTier, String apiLevelThrottleKey, String apiLevelTier, String subscriptionLevelThrottleKey, String subscriptionLevelTier, String resourceLevelThrottleKey, String resourceLevelTier, String authorizedUser, String apiContext, String apiVersion, String appTenant, String apiTenant, String appId, MessageContext messageContext, AuthenticationContext authenticationContext) { if (!StringUtils.isEmpty(apiLevelTier)) { resourceLevelTier = apiLevelTier; resourceLevelThrottleKey = apiLevelThrottleKey; } this.authenticationContext = authenticationContext; this.messageContext = messageContext; this.applicationLevelThrottleKey = applicationLevelThrottleKey; this.applicationLevelTier = applicationLevelTier; this.apiLevelThrottleKey = apiLevelThrottleKey; this.subscriptionLevelThrottleKey = subscriptionLevelThrottleKey; this.subscriptionLevelTier = subscriptionLevelTier; this.resourceLevelThrottleKey = resourceLevelThrottleKey; this.resourceLevelTier = resourceLevelTier; this.authorizedUser = authorizedUser; this.apiContext = apiContext; this.apiVersion = apiVersion; this.appTenant = appTenant; this.apiTenant = apiTenant; this.appId = appId; this.apiName = GatewayUtils.getAPINameFromContextAndVersion(messageContext); this.messageSizeInBytes = 0; ArrayList<VerbInfoDTO> list = (ArrayList<VerbInfoDTO>) messageContext.getProperty(APIConstants.VERB_INFO_DTO); boolean isVerbInfoContentAware = false; if (list != null && !list.isEmpty()) { VerbInfoDTO verbInfoDTO = list.get(0); isVerbInfoContentAware = verbInfoDTO.isContentAware(); } //Build the message if needed from here since it cannot be done from the run() method because content //in axis2MessageContext is modified. if (authenticationContext.isContentAwareTierPresent() || isVerbInfoContentAware) { org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext) .getAxis2MessageContext(); TreeMap<String, String> transportHeaderMap = (TreeMap<String, String>) axis2MessageContext .getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); Object contentLength = transportHeaderMap.get(APIThrottleConstants.CONTENT_LENGTH); if (contentLength != null) { log.debug("Content lenght found in the request. Using it as the message size.."); messageSizeInBytes = Long.parseLong(contentLength.toString()); } else { log.debug("Building the message to get the message size.."); try { buildMessage(axis2MessageContext); } catch (Exception ex) { //In case of any exception, it won't be propagated up,and set response size to 0 log.error("Error occurred while building the message to" + " calculate the response body size", ex); } SOAPEnvelope env = messageContext.getEnvelope(); if (env != null) { SOAPBody soapbody = env.getBody(); if (soapbody != null) { byte[] size = soapbody.toString().getBytes(Charset.defaultCharset()); messageSizeInBytes = size.length; } } } } if (getThrottleProperties().isEnableHeaderConditions()) { org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext) .getAxis2MessageContext(); TreeMap<String, String> transportHeaderMap = (TreeMap<String, String>) axis2MessageContext .getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); //Set transport headers of the message. Header Map will be put to the JSON Map which gets transferred // to CEP. Since this operation runs asynchronously if we are to get the header Map present in the // messageContext a ConcurrentModificationException will be thrown. Reason is at the time of sending the // request out, header map is modified by the Synapse layer. It's to avoid this problem a clone of the // map is used. if (transportHeaderMap != null) { this.headersMap = (Map<String, String>) transportHeaderMap.clone(); } } } public void run() { JSONObject jsonObMap = new JSONObject(); org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext) .getAxis2MessageContext(); //Set transport headers of the message TreeMap<String, String> transportHeaderMap = (TreeMap<String, String>) axis2MessageContext .getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); String remoteIP = GatewayUtils.getIp(axis2MessageContext); if (log.isDebugEnabled()) { log.debug("Remote IP address : " + remoteIP); } if (remoteIP != null && remoteIP.length() > 0) { if (remoteIP.contains(":") && remoteIP.split(":").length == 2) { log.warn("Client port will be ignored and only the IP address (IPV4) will concern from " + remoteIP); remoteIP = remoteIP.split(":")[0]; } try { InetAddress address = APIUtil.getAddress(remoteIP); if (address instanceof Inet4Address) { jsonObMap.put(APIThrottleConstants.IP, APIUtil.ipToLong(remoteIP)); jsonObMap.put(APIThrottleConstants.IPv6, 0); } else if (address instanceof Inet6Address) { jsonObMap.put(APIThrottleConstants.IPv6, APIUtil.ipToBigInteger(remoteIP)); jsonObMap.put(APIThrottleConstants.IP, 0); } } catch (UnknownHostException e) { //send empty value as ip log.error("Error while parsing host IP " + remoteIP, e); jsonObMap.put(APIThrottleConstants.IPv6, 0); jsonObMap.put(APIThrottleConstants.IP, 0); } } //HeaderMap will only be set if the Header Publishing has been enabled. if (this.headersMap != null) { jsonObMap.putAll(this.headersMap); } //Setting query parameters if (getThrottleProperties().isEnableQueryParamConditions()) { Map<String, String> queryParams = GatewayUtils.getQueryParams(axis2MessageContext); if (queryParams != null) { jsonObMap.putAll(queryParams); } } //Publish jwt claims if (getThrottleProperties().isEnableJwtConditions()) { if (authenticationContext.getCallerToken() != null) { Map assertions = GatewayUtils.getJWTClaims(authenticationContext); if (assertions != null) { jsonObMap.putAll(assertions); } } } //this parameter will be used to capture message size and pass it to calculation logic ArrayList<VerbInfoDTO> list = (ArrayList<VerbInfoDTO>) messageContext.getProperty(APIConstants.VERB_INFO_DTO); boolean isVerbInfoContentAware = false; if (list != null && !list.isEmpty()) { VerbInfoDTO verbInfoDTO = list.get(0); isVerbInfoContentAware = verbInfoDTO.isContentAware(); } if (authenticationContext.isContentAwareTierPresent() || isVerbInfoContentAware) { if (log.isDebugEnabled()) { log.debug("Message size: " + messageSizeInBytes + "B"); } jsonObMap.put(APIThrottleConstants.MESSAGE_SIZE, messageSizeInBytes); if (!StringUtils.isEmpty(authenticationContext.getApplicationName())) { jsonObMap.put(APIThrottleConstants.APPLICATION_NAME, authenticationContext.getApplicationName()); } if (!StringUtils.isEmpty(authenticationContext.getProductName()) && !StringUtils .isEmpty(authenticationContext.getProductProvider())) { jsonObMap.put(APIThrottleConstants.SUBSCRIPTION_TYPE, APIConstants.API_PRODUCT_SUBSCRIPTION_TYPE); } else { jsonObMap.put(APIThrottleConstants.SUBSCRIPTION_TYPE, APIConstants.API_SUBSCRIPTION_TYPE); } } Object[] objects = new Object[]{messageContext.getMessageID(), this.applicationLevelThrottleKey, this.applicationLevelTier, this.apiLevelThrottleKey, this.apiLevelTier, this.subscriptionLevelThrottleKey, this.subscriptionLevelTier, this.resourceLevelThrottleKey, this.resourceLevelTier, this.authorizedUser, this.apiContext, this.apiVersion, this.appTenant, this.apiTenant, this.appId, this.apiName, jsonObMap.toString()}; org.wso2.carbon.databridge.commons.Event event = new org.wso2.carbon.databridge.commons.Event(streamID, System.currentTimeMillis(), null, null, objects); dataPublisher.tryPublish(event); } protected void buildMessage(org.apache.axis2.context.MessageContext axis2MessageContext) throws IOException, XMLStreamException { RelayUtils.buildMessage(axis2MessageContext); } protected ThrottleProperties getThrottleProperties() { return ServiceReferenceHolder.getInstance().getThrottleProperties(); } protected DataPublisher getDataPublisher() { return ThrottleDataPublisher.getDataPublisher(); } }
Remove unused line which cause class cast exception
components/apimgt/org.wso2.carbon.apimgt.gateway/src/main/java/org/wso2/carbon/apimgt/gateway/throttling/publisher/DataProcessAndPublishingAgent.java
Remove unused line which cause class cast exception
<ide><path>omponents/apimgt/org.wso2.carbon.apimgt.gateway/src/main/java/org/wso2/carbon/apimgt/gateway/throttling/publisher/DataProcessAndPublishingAgent.java <ide> } <ide> <ide> public void run() { <del> <ide> JSONObject jsonObMap = new JSONObject(); <del> <ide> org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext) <ide> .getAxis2MessageContext(); <del> //Set transport headers of the message <del> TreeMap<String, String> transportHeaderMap = (TreeMap<String, String>) axis2MessageContext <del> .getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); <del> <del> <ide> String remoteIP = GatewayUtils.getIp(axis2MessageContext); <ide> if (log.isDebugEnabled()) { <ide> log.debug("Remote IP address : " + remoteIP);
Java
mit
f9757e2ec547c3fafe2054f3b7cb98722867e91b
0
TPCISIIE/FindYourWay,TPCISIIE/FindYourWay,TPCISIIE/FindYourWay
package boundary.Score; import boundary.Question.QuestionResource; import boundary.Representation; import boundary.User.UserResource; import com.wordnik.swagger.annotations.Api; import com.wordnik.swagger.annotations.ApiOperation; import com.wordnik.swagger.annotations.ApiResponse; import com.wordnik.swagger.annotations.ApiResponses; import entity.Score; import entity.User; import entity.UserRole; import provider.Secured; import java.util.List; import javax.ejb.EJB; import javax.ejb.Stateless; import javax.ws.rs.*; import javax.ws.rs.core.*; @Path("/scores") @Stateless @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Api(value = "/scores", description = "Scores management") public class ScoreRepresentation extends Representation { @EJB private ScoreResource scoreResource; @EJB private UserResource userResource; @EJB private QuestionResource questionResource; @GET @ApiOperation(value = "Get all the scores", notes = "Access : Everyone") @ApiResponses(value = { @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 500, message = "Internal server error") }) public Response getAll() { GenericEntity<List<Score>> list = new GenericEntity<List<Score>>(scoreResource.findAll()){}; return Response.ok(list, MediaType.APPLICATION_JSON).build(); } @GET @Path("/{id}") @ApiOperation(value = "Get a score by its id", notes = "Access : Everyone") @ApiResponses(value = { @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 404, message = "Not found"), @ApiResponse(code = 500, message = "Internal server error") }) public Response get(@PathParam("id") String id) { Score score = scoreResource.findById(id); if (score == null) flash(404, "Error : Score does not exist"); return Response.ok(score, MediaType.APPLICATION_JSON).build(); } @POST @Secured({UserRole.CUSTOMER}) @ApiOperation(value = "Add a new score", notes = "Access : Customer only") @ApiResponses(value = { @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 400, message = "Bad Request"), @ApiResponse(code = 404, message = "Question not found"), @ApiResponse(code = 500, message = "Internal server error") }) public Response add(@Context SecurityContext securityContext, Score score) { if(score == null) flash(400, EMPTY_JSON); User user = userResource.findByEmail(securityContext.getUserPrincipal().getName()); score.setUser(user); if (!score.isValid()) flash(400, MISSING_FIELDS + ", also be sure the score is greater than 0"); if (questionResource.findById(score.getQuestion().getId()) == null) flash(404, "Error : Question does not exist"); score = scoreResource.insert(score); return Response.ok(score, MediaType.APPLICATION_JSON).build(); } @DELETE @Path("/{id}") @ApiOperation(value = "Delete a score by its id", notes = "Access : Owner only") @ApiResponses(value = { @ApiResponse(code = 204, message = "No content"), @ApiResponse(code = 400, message = "Bad Request"), @ApiResponse(code = 401, message = "Unauthorized"), @ApiResponse(code = 404, message = "Question not found"), @ApiResponse(code = 500, message = "Internal server error") }) public Response delete(@PathParam("id") String id, @Context SecurityContext securityContext) { Score score = scoreResource.findById(id); if(score == null) return Response.status(Response.Status.NOT_FOUND).build(); User user = userResource.findByEmail(securityContext.getUserPrincipal().getName()); if (!score.getUser().equals(user)) return Response.status(Response.Status.UNAUTHORIZED).build(); scoreResource.delete(score); return Response.noContent().build(); } @PUT @Path("/{id}") //@Secured({UserRole.ADMIN}) @ApiOperation(value = "Update a score by its id", notes = "Access : Admin only") @ApiResponses(value = { @ApiResponse(code = 204, message = "No content"), @ApiResponse(code = 400, message = "Bad Request"), @ApiResponse(code = 401, message = "Unauthorized"), @ApiResponse(code = 404, message = "Question not found"), @ApiResponse(code = 500, message = "Internal server error") }) public Response update(@PathParam("id") String id, Score score) { if (score == null) flash(400, EMPTY_JSON); score = scoreResource.findById(score.getId()); if(score == null) return Response.noContent().build(); if (!score.isValid()) flash(400, INVALID_JSON); Score originalScore = scoreResource.findById(id); if (originalScore == null) return Response.status(Response.Status.NOT_FOUND).build(); if (questionResource.findById(score.getQuestion().getId()) == null) flash(404, "Error : Question does not exist"); return Response.status(Response.Status.NO_CONTENT).build(); } }
Server/src/main/java/boundary/Score/ScoreRepresentation.java
package boundary.Score; import boundary.Question.QuestionResource; import boundary.Representation; import boundary.User.UserResource; import com.wordnik.swagger.annotations.Api; import com.wordnik.swagger.annotations.ApiOperation; import com.wordnik.swagger.annotations.ApiResponse; import com.wordnik.swagger.annotations.ApiResponses; import entity.Score; import entity.User; import entity.UserRole; import provider.Secured; import java.util.List; import javax.ejb.EJB; import javax.ejb.Stateless; import javax.ws.rs.*; import javax.ws.rs.core.*; @Path("/scores") @Stateless @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Api(value = "/scores", description = "Scores management") public class ScoreRepresentation extends Representation { @EJB private ScoreResource scoreResource; @EJB private UserResource userResource; @EJB private QuestionResource questionResource; @GET @ApiOperation(value = "Get all the scores", notes = "Access : Everyone") @ApiResponses(value = { @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 500, message = "Internal server error") }) public Response getAll() { GenericEntity<List<Score>> list = new GenericEntity<List<Score>>(scoreResource.findAll()){}; return Response.ok(list, MediaType.APPLICATION_JSON).build(); } @GET @Path("/{id}") @ApiOperation(value = "Get a score by its id", notes = "Access : Everyone") @ApiResponses(value = { @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 404, message = "Not found"), @ApiResponse(code = 500, message = "Internal server error") }) public Response get(@PathParam("id") String id) { Score score = scoreResource.findById(id); if (score == null) flash(404, "Error : Score does not exist"); return Response.ok(score, MediaType.APPLICATION_JSON).build(); } @POST @Secured({UserRole.CUSTOMER}) @ApiOperation(value = "Add a new score", notes = "Access : Customer only") @ApiResponses(value = { @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 400, message = "Bad Request"), @ApiResponse(code = 404, message = "Question not found"), @ApiResponse(code = 500, message = "Internal server error") }) public Response add(@Context SecurityContext securityContext, Score score) { if(score == null) flash(400, EMPTY_JSON); User user = userResource.findByEmail(securityContext.getUserPrincipal().getName()); score.setUser(user); if (!score.isValid()) flash(400, MISSING_FIELDS + ", also be sure the score is greater than 0"); if (questionResource.findById(score.getQuestion().getId()) == null) flash(404, "Error : Question does not exist"); score = scoreResource.insert(score); return Response.ok(score, MediaType.APPLICATION_JSON).build(); } @DELETE @Path("/{id}") @ApiOperation(value = "Delete a score by its id", notes = "Access : Customer only") @ApiResponses(value = { @ApiResponse(code = 204, message = "No content"), @ApiResponse(code = 400, message = "Bad Request"), @ApiResponse(code = 401, message = "Unauthorized"), @ApiResponse(code = 404, message = "Question not found"), @ApiResponse(code = 500, message = "Internal server error") }) public Response delete(@PathParam("id") String id, @Context SecurityContext securityContext) { Score score = scoreResource.findById(id); if(score == null) return Response.status(Response.Status.NOT_FOUND).build(); User user = userResource.findByEmail(securityContext.getUserPrincipal().getName()); if (!score.getUser().equals(user)) return Response.status(Response.Status.UNAUTHORIZED).build(); scoreResource.delete(score); return Response.noContent().build(); } @PUT @Path("/{id}") //@Secured({UserRole.ADMIN}) @ApiOperation(value = "Update a score by its id", notes = "Access : Admin only") @ApiResponses(value = { @ApiResponse(code = 204, message = "No content"), @ApiResponse(code = 400, message = "Bad Request"), @ApiResponse(code = 401, message = "Unauthorized"), @ApiResponse(code = 404, message = "Question not found"), @ApiResponse(code = 500, message = "Internal server error") }) public Response update(@PathParam("id") String id, Score score) { if (score == null) flash(400, EMPTY_JSON); score = scoreResource.findById(score.getId()); if(score == null) return Response.noContent().build(); if (!score.isValid()) flash(400, INVALID_JSON); Score originalScore = scoreResource.findById(id); if (originalScore == null) return Response.status(Response.Status.NOT_FOUND).build(); if (questionResource.findById(score.getQuestion().getId()) == null) flash(404, "Error : Question does not exist"); return Response.status(Response.Status.NO_CONTENT).build(); } }
Fixed access
Server/src/main/java/boundary/Score/ScoreRepresentation.java
Fixed access
<ide><path>erver/src/main/java/boundary/Score/ScoreRepresentation.java <ide> <ide> @DELETE <ide> @Path("/{id}") <del> @ApiOperation(value = "Delete a score by its id", notes = "Access : Customer only") <add> @ApiOperation(value = "Delete a score by its id", notes = "Access : Owner only") <ide> @ApiResponses(value = { <ide> @ApiResponse(code = 204, message = "No content"), <ide> @ApiResponse(code = 400, message = "Bad Request"),
JavaScript
mit
bd8d556400ef9c4b5f2a68e6b19d09891c77dc40
0
esviji/esviji,nhoizey/esviji,nhoizey/esviji,esviji/esviji,nhoizey/esviji
window.onload = function(){ esviji.run(); } var esviji = { VIEWPORT_WIDTH: 320, VIEWPORT_HEIGHT: 480, EMPTY: 0, ROCK: -1, board: null, theme: 'metro', themes: { 'metro': { 'rock': 'metro', 'regularPieces': ['m1', 'm2', 'm3', 'm4', 'm5', 'm6', 'm7', 'm8', 'm9', 'm10', 'm11', 'm12', 'm13', 'm14'] } }, currentPieces: [], drawnCurrentPieces: [], validPieces: [], currentPiece: 0, currentPosX: 9, currentPosY: 7, maxAvailablePieces: 0, nbPieces: 0, level: 0, score: 0, scoreThisTurn: 0, drawnScore: null, lives: 10, drawnLevelAndLives: null, viewportWidth: 0, viewportHeight: 0, init: function init() { esviji.board = new ScaleRaphael('board', esviji.VIEWPORT_WIDTH, esviji.VIEWPORT_HEIGHT); esviji.updateViewportSize(); var windowAddEvent = window.attachEvent || window.addEventListener; windowAddEvent('onresize', esviji.updateViewportSize, false); var background = esviji.board.rect(1, 1, esviji.VIEWPORT_WIDTH, esviji.VIEWPORT_HEIGHT), header = esviji.board.path('M 1 21 l 0 205 l 35 0 l 0 -35 l 35 0 l 0 -35 l 35 0 l 0 -35 l 35 0 l 0 -35 l 35 0 l 0 -35 l 35 0 l 108 0 l 0 -30 z'), title = esviji.board.print(0, 60, "esviji", esviji.board.getFont('ChewyRegular'), 60); esviji.drawScore(); esviji.drawLevel(); esviji.drawLives(); background.attr({ 'fill': '#ffffff'}); header.attr({ 'fill': '#9999cc', 'stroke': '#666699', 'stroke-width': 2 }); title.attr({ 'fill': '#666699', 'stroke': '#333366', 'stroke-width': 2 }); esviji.maxAvailablePieces = esviji.themes[esviji.theme].regularPieces.length; }, updateViewportSize: function updateViewportSize() { // http://andylangton.co.uk/articles/javascript/get-viewport-size-javascript/ var w = window, d = document, e = d.documentElement, b = d.getElementsByTagName('body')[0]; esviji.viewportWidth = w.innerWidth || e.clientWidth || b.clientWidth; esviji.viewportHeight = w.innerHeight || e.clientHeight || b.clientHeight; esviji.board.changeSize(esviji.viewportWidth, esviji.viewportHeight, true, false); }, scaledX: function scaledX(x) { return x * esviji.VIEWPORT_WIDTH / esviji.board.width; }, scaledY: function scaledY(y) { return y * esviji.VIEWPORT_HEIGHT / esviji.board.height; }, nextLevel: function nextLevel() { esviji.level++; esviji.drawLevel(); esviji.lives++; esviji.drawLives(); esviji.nbPieces = Math.min(esviji.maxAvailablePieces, Math.floor(5 + (esviji.level / 5))); esviji.initPieces(); esviji.erasePieces(); esviji.drawPieces(); esviji.startNewTurn(); }, xToCoord: function xToCoord(x) { return x * 35 - 30; }, yToCoord: function yToCoord(y) { return esviji.VIEWPORT_HEIGHT - 35 * y; }, startNewTurn: function startNewTurn() { esviji.currentPosX = 9; esviji.currentPosY = 8; esviji.scoreThisTurn = 0; esviji.currentDirX = -1; esviji.currentDirY = 0; esviji.getValidPieces(); if (esviji.validPieces.length == 0) { // no more valid piece, end of the turn esviji.nextLevel(); } else { if (esviji.validPieces.indexOf(esviji.currentPiece) == -1) { esviji.lives--; esviji.drawLives(); if (esviji.lives == 0) { gameOver = esviji.board.print(5, 200, "Game Over", esviji.board.getFont('ChewyRegular'), 64).attr({'fill': 'red', 'stroke': 'black', 'stroke-width': 2}); //TODO: really stop the game } esviji.currentPiece = esviji.validPieces[Math.floor(Math.random() * esviji.validPieces.length)]; } pieceFile = 'themes/' + esviji.theme + '/' + esviji.themes[esviji.theme].regularPieces[esviji.currentPiece - 1] + '.svg'; esviji.drawnCurrentPiece = esviji.board.image(pieceFile, esviji.xToCoord(esviji.currentPosX), esviji.yToCoord(esviji.currentPosY), 30, 30); esviji.drawnCurrentPiece.drag(function(dx, dy) { this.attr({ x: esviji.xToCoord(9), y: Math.min(Math.max(yBeforeDrag + esviji.scaledY(dy), esviji.yToCoord(12)), esviji.yToCoord(1)) }); }, function () { xBeforeDrag = this.attr('x'); yBeforeDrag = this.attr('y'); }, function () { yAfterDrag = this.attr('y'); diff = 1000; for (i = 1; i <= 12; i++) { thisDiff = Math.abs(yAfterDrag - esviji.yToCoord(i)); if (thisDiff < diff) { diff = thisDiff; esviji.currentPosY = i; } } esviji.drawnCurrentPiece.animate({'y': esviji.yToCoord(esviji.currentPosY)}, 500, 'elastic', esviji.playUserChoice); }); } }, playUserChoice: function playUserChoice () { var stopped = false; if (esviji.currentPosY == 1 && esviji.currentDirY == -1) { stopped = true; } else { if (esviji.currentPosX == 1 && esviji.currentDirX == -1) { esviji.currentDirX = 0; esviji.currentDirY = -1; } else { nextPiece = esviji.currentPieces[esviji.currentPosX + esviji.currentDirX][esviji.currentPosY + esviji.currentDirY]; if (nextPiece == esviji.ROCK) { if (esviji.currentDirX == -1) { esviji.currentDirX = 0; esviji.currentDirY = -1; } else { stopped = true; } } else { if (nextPiece == esviji.EMPTY) { esviji.currentPosX += esviji.currentDirX; esviji.currentPosY += esviji.currentDirY; } else { if (nextPiece == esviji.currentPiece) { esviji.currentPosX += esviji.currentDirX; esviji.currentPosY += esviji.currentDirY; esviji.currentPieces[esviji.currentPosX][esviji.currentPosY] = esviji.EMPTY; esviji.drawnCurrentPieces[esviji.currentPosX][esviji.currentPosY].remove(); esviji.scoreThisTurn++; } else { if (esviji.scoreThisTurn > 0) { esviji.currentPiece = nextPiece; } stopped = true; } } } } } if (!stopped) { esviji.drawnCurrentPiece.animate({'x': esviji.xToCoord(esviji.currentPosX), 'y': esviji.yToCoord(esviji.currentPosY), 'rotate': 360}, 200, 'linear', esviji.playUserChoice); } else { esviji.score += Math.pow(esviji.scoreThisTurn, 2); esviji.drawScore(); esviji.drawnCurrentPiece.remove(); esviji.makePiecesFall(); esviji.startNewTurn(); } }, makePiecesFall: function makePiecesFall() { var abovePieces; for(x = 1; x <= 6; x++) { for (y = 1; y <= 5; y++) { if (esviji.currentPieces[x][y] == esviji.EMPTY) { abovePieces = 0; for (z = y; z <= 5; z++) { if (esviji.currentPieces[x][z + 1] != esviji.EMPTY && esviji.currentPieces[x][z + 1] != esviji.ROCK) { abovePieces++; } if (esviji.currentPieces[x][z + 1] == esviji.ROCK) { z = 5; } else { esviji.currentPieces[x][z] = esviji.currentPieces[x][z + 1]; esviji.currentPieces[x][z + 1] = esviji.EMPTY; if (esviji.drawnCurrentPieces[x][z + 1] != null) { esviji.drawnCurrentPieces[x][z] = esviji.drawnCurrentPieces[x][z + 1]; esviji.drawnCurrentPieces[x][z].animate({'y': esviji.yToCoord(z)}, 500, 'bounce'); esviji.drawnCurrentPieces[x][z + 1] = null; } } } if (abovePieces > 0) { y--; } } } } }, initPieces: function initPieces() { esviji.currentPieces = []; for(x = 1; x <= 8; x++) { esviji.currentPieces[x] = []; for (y = 1; y <= 12; y++) { if (x > 6) { esviji.currentPieces[x][y] = esviji.EMPTY; } else { if (y > 6) { if (y - 6 > x) { esviji.currentPieces[x][y] = esviji.ROCK; } else { esviji.currentPieces[x][y] = esviji.EMPTY; } } else { esviji.currentPieces[x][y] = 1 + Math.floor(Math.random() * esviji.nbPieces); } } } } // add rocks in the middle after level 10 if (esviji.level > 10) { nbRocks = Math.floor((esviji.level - 5) / 5); positionedRocks = 0; while (positionedRocks < nbRocks) { rock_x = 1 + Math.floor(Math.random() * 6); rock_y = 1 + Math.floor(Math.random() * 6); if (esviji.currentPieces[rock_x][rock_y] != esviji.ROCK) { esviji.currentPieces[rock_x][rock_y] = esviji.ROCK; positionedRocks++; } } } }, drawPieces: function drawPieces() { esviji.drawnCurrentPieces = []; for(x = 1; x <= 6; x++) { esviji.drawnCurrentPieces[x] = []; for (y = 1; y <= 6; y++) { if (esviji.currentPieces[x][y] != esviji.EMPTY) { if (esviji.currentPieces[x][y] == esviji.ROCK) { pieceFile = 'themes/' + esviji.theme + '/' + esviji.themes[esviji.theme].rock + '.svg'; } else { pieceFile = 'themes/' + esviji.theme + '/' + esviji.themes[esviji.theme].regularPieces[esviji.currentPieces[x][y] - 1] + '.svg'; } piece_x = esviji.xToCoord(x); piece_y = esviji.yToCoord(y); esviji.drawnCurrentPieces[x][y] = esviji.board.image(pieceFile, piece_x, -30, 30, 30); esviji.drawnCurrentPieces[x][y].animate({'y': piece_y}, 2000, 'bounce'); } } } }, erasePieces: function erasePieces() { for(x = 1; x <= 6; x++) { if (esviji.drawnCurrentPieces[x] != undefined) { for (y = 1; y <= 6; y++) { if (esviji.drawnCurrentPieces[x][y] != null) { esviji.drawnCurrentPieces[x][y].remove(); } } } } }, getValidPieces: function getValidPieces() { var x, y, dir_x, dir_y, found; esviji.validPieces = []; for (y_start = 1; y_start <= 12; y_start++) { x = 9; y = y_start; dir_x = -1; dir_y = 0; found = false; while (!found) { if (y == 1 && dir_y == -1) { found = true; } else { if (x == 1 && dir_x == -1) { dir_x = 0; dir_y = -1; } else { nextPiece = esviji.currentPieces[x + dir_x][y + dir_y]; if (nextPiece == esviji.ROCK) { if (dir_x == -1) { dir_x = 0; dir_y = -1; } else { found = true; } } else { if (nextPiece == esviji.EMPTY) { x += dir_x; y += dir_y; } else { if (esviji.validPieces.indexOf(nextPiece) == -1) { esviji.validPieces.push(nextPiece); } found = true; } } } } } } }, drawScore: function drawScore() { if (esviji.drawnScore != null) { esviji.drawnScore.remove(); } esviji.drawnScore = esviji.board.print(170, 38, "score: " + esviji.score, esviji.board.getFont('ChewyRegular'), 24); esviji.drawnScore.attr({'fill': '#333366'}); }, drawLevel: function drawLevel() { if (esviji.drawnLevel != null) { esviji.drawnLevel.remove(); } esviji.drawnLevel = esviji.board.print(10, 110, 'level ' + esviji.level, esviji.board.getFont('ChewyRegular'), 20); esviji.drawnLevel.attr({'fill': '#333366'}); }, drawLives: function drawLives() { if (esviji.drawnLives != null) { esviji.drawnLives.remove(); } esviji.drawnLives = esviji.board.print(10, 140, esviji.lives + ' lives', esviji.board.getFont('ChewyRegular'), 20); esviji.drawnLives.attr({'fill': '#333366'}); }, run: function run() { esviji.init(); esviji.nextLevel(); } }
esviji.js
window.onload = function(){ esviji.run(); } var esviji = { VIEWPORT_WIDTH: 320, VIEWPORT_HEIGHT: 480, EMPTY: 0, ROCK: -1, board: null, theme: 'metro', themes: { 'metro': { 'rock': 'metro', 'regularPieces': ['m1', 'm2', 'm3', 'm4', 'm5', 'm6', 'm7', 'm8', 'm9', 'm10', 'm11', 'm12', 'm13', 'm14'] } }, currentPieces: [], drawnCurrentPieces: [], validPieces: [], currentPiece: 0, currentPosX: 9, currentPosY: 7, maxAvailablePieces: 0, nbPieces: 0, level: 0, score: 0, scoreThisTurn: 0, drawnScore: null, lives: 10, drawnLevelAndLives: null, viewportWidth: 0, viewportHeight: 0, init: function init() { esviji.board = new ScaleRaphael('board', esviji.VIEWPORT_WIDTH, esviji.VIEWPORT_HEIGHT); esviji.updateViewportSize(); var windowAddEvent = window.attachEvent || window.addEventListener; windowAddEvent('onresize', esviji.updateViewportSize, false); var header = esviji.board.path('M 1 21 l 0 205 l 35 0 l 0 -35 l 35 0 l 0 -35 l 35 0 l 0 -35 l 35 0 l 0 -35 l 35 0 l 0 -35 l 35 0 l 108 0 l 0 -30 z'), title = esviji.board.print(0, 60, "esviji", esviji.board.getFont('ChewyRegular'), 60); esviji.drawScore(); esviji.drawLevel(); esviji.drawLives(); header.attr({ 'fill': '#9999cc', 'stroke': '#666699', 'stroke-width': 2 }); title.attr({ 'fill': '#666699', 'stroke': '#333366', 'stroke-width': 2 }); esviji.maxAvailablePieces = esviji.themes[esviji.theme].regularPieces.length; }, updateViewportSize: function updateViewportSize() { // http://andylangton.co.uk/articles/javascript/get-viewport-size-javascript/ var w = window, d = document, e = d.documentElement, b = d.getElementsByTagName('body')[0]; esviji.viewportWidth = w.innerWidth || e.clientWidth || b.clientWidth; esviji.viewportHeight = w.innerHeight || e.clientHeight || b.clientHeight; esviji.board.changeSize(esviji.viewportWidth, esviji.viewportHeight, true, false); }, scaledX: function scaledX(x) { return x * esviji.VIEWPORT_WIDTH / esviji.board.width; }, scaledY: function scaledY(y) { return y * esviji.VIEWPORT_HEIGHT / esviji.board.height; }, nextLevel: function nextLevel() { esviji.level++; esviji.drawLevel(); esviji.lives++; esviji.drawLives(); esviji.nbPieces = Math.min(esviji.maxAvailablePieces, Math.floor(5 + (esviji.level / 5))); esviji.initPieces(); esviji.erasePieces(); esviji.drawPieces(); esviji.startNewTurn(); }, xToCoord: function xToCoord(x) { return x * 35 - 30; }, yToCoord: function yToCoord(y) { return esviji.VIEWPORT_HEIGHT - 35 * y; }, startNewTurn: function startNewTurn() { esviji.currentPosX = 9; esviji.currentPosY = 8; esviji.scoreThisTurn = 0; esviji.currentDirX = -1; esviji.currentDirY = 0; esviji.getValidPieces(); if (esviji.validPieces.length == 0) { // no more valid piece, end of the turn esviji.nextLevel(); } else { if (esviji.validPieces.indexOf(esviji.currentPiece) == -1) { esviji.lives--; esviji.drawLives(); if (esviji.lives == 0) { gameOver = esviji.board.print(5, 200, "Game Over", esviji.board.getFont('ChewyRegular'), 64).attr({'fill': 'red', 'stroke': 'black', 'stroke-width': 2}); //TODO: really stop the game } esviji.currentPiece = esviji.validPieces[Math.floor(Math.random() * esviji.validPieces.length)]; } pieceFile = 'themes/' + esviji.theme + '/' + esviji.themes[esviji.theme].regularPieces[esviji.currentPiece - 1] + '.svg'; esviji.drawnCurrentPiece = esviji.board.image(pieceFile, esviji.xToCoord(esviji.currentPosX), esviji.yToCoord(esviji.currentPosY), 30, 30); esviji.drawnCurrentPiece.drag(function(dx, dy) { this.attr({ x: esviji.xToCoord(9), y: Math.min(Math.max(yBeforeDrag + esviji.scaledY(dy), esviji.yToCoord(12)), esviji.yToCoord(1)) }); }, function () { xBeforeDrag = this.attr('x'); yBeforeDrag = this.attr('y'); }, function () { yAfterDrag = this.attr('y'); diff = 1000; for (i = 1; i <= 12; i++) { thisDiff = Math.abs(yAfterDrag - esviji.yToCoord(i)); if (thisDiff < diff) { diff = thisDiff; esviji.currentPosY = i; } } esviji.drawnCurrentPiece.animate({'y': esviji.yToCoord(esviji.currentPosY)}, 500, 'elastic', esviji.playUserChoice); }); } }, playUserChoice: function playUserChoice () { var stopped = false; if (esviji.currentPosY == 1 && esviji.currentDirY == -1) { stopped = true; } else { if (esviji.currentPosX == 1 && esviji.currentDirX == -1) { esviji.currentDirX = 0; esviji.currentDirY = -1; } else { nextPiece = esviji.currentPieces[esviji.currentPosX + esviji.currentDirX][esviji.currentPosY + esviji.currentDirY]; if (nextPiece == esviji.ROCK) { if (esviji.currentDirX == -1) { esviji.currentDirX = 0; esviji.currentDirY = -1; } else { stopped = true; } } else { if (nextPiece == esviji.EMPTY) { esviji.currentPosX += esviji.currentDirX; esviji.currentPosY += esviji.currentDirY; } else { if (nextPiece == esviji.currentPiece) { esviji.currentPosX += esviji.currentDirX; esviji.currentPosY += esviji.currentDirY; esviji.currentPieces[esviji.currentPosX][esviji.currentPosY] = esviji.EMPTY; esviji.drawnCurrentPieces[esviji.currentPosX][esviji.currentPosY].remove(); esviji.scoreThisTurn++; } else { if (esviji.scoreThisTurn > 0) { esviji.currentPiece = nextPiece; } stopped = true; } } } } } if (!stopped) { esviji.drawnCurrentPiece.animate({'x': esviji.xToCoord(esviji.currentPosX), 'y': esviji.yToCoord(esviji.currentPosY), 'rotate': 360}, 200, 'linear', esviji.playUserChoice); } else { esviji.score += Math.pow(esviji.scoreThisTurn, 2); esviji.drawScore(); esviji.drawnCurrentPiece.remove(); esviji.makePiecesFall(); esviji.startNewTurn(); } }, makePiecesFall: function makePiecesFall() { var abovePieces; for(x = 1; x <= 6; x++) { for (y = 1; y <= 5; y++) { if (esviji.currentPieces[x][y] == esviji.EMPTY) { abovePieces = 0; for (z = y; z <= 5; z++) { if (esviji.currentPieces[x][z + 1] != esviji.EMPTY && esviji.currentPieces[x][z + 1] != esviji.ROCK) { abovePieces++; } if (esviji.currentPieces[x][z + 1] == esviji.ROCK) { z = 5; } else { esviji.currentPieces[x][z] = esviji.currentPieces[x][z + 1]; esviji.currentPieces[x][z + 1] = esviji.EMPTY; if (esviji.drawnCurrentPieces[x][z + 1] != null) { esviji.drawnCurrentPieces[x][z] = esviji.drawnCurrentPieces[x][z + 1]; esviji.drawnCurrentPieces[x][z].animate({'y': esviji.yToCoord(z)}, 500, 'bounce'); esviji.drawnCurrentPieces[x][z + 1] = null; } } } if (abovePieces > 0) { y--; } } } } }, initPieces: function initPieces() { esviji.currentPieces = []; for(x = 1; x <= 8; x++) { esviji.currentPieces[x] = []; for (y = 1; y <= 12; y++) { if (x > 6) { esviji.currentPieces[x][y] = esviji.EMPTY; } else { if (y > 6) { if (y - 6 > x) { esviji.currentPieces[x][y] = esviji.ROCK; } else { esviji.currentPieces[x][y] = esviji.EMPTY; } } else { esviji.currentPieces[x][y] = 1 + Math.floor(Math.random() * esviji.nbPieces); } } } } // add rocks in the middle after level 10 if (esviji.level > 10) { nbRocks = Math.floor((esviji.level - 5) / 5); positionedRocks = 0; while (positionedRocks < nbRocks) { rock_x = 1 + Math.floor(Math.random() * 6); rock_y = 1 + Math.floor(Math.random() * 6); if (esviji.currentPieces[rock_x][rock_y] != esviji.ROCK) { esviji.currentPieces[rock_x][rock_y] = esviji.ROCK; positionedRocks++; } } } }, drawPieces: function drawPieces() { esviji.drawnCurrentPieces = []; for(x = 1; x <= 6; x++) { esviji.drawnCurrentPieces[x] = []; for (y = 1; y <= 6; y++) { if (esviji.currentPieces[x][y] != esviji.EMPTY) { if (esviji.currentPieces[x][y] == esviji.ROCK) { pieceFile = 'themes/' + esviji.theme + '/' + esviji.themes[esviji.theme].rock + '.svg'; } else { pieceFile = 'themes/' + esviji.theme + '/' + esviji.themes[esviji.theme].regularPieces[esviji.currentPieces[x][y] - 1] + '.svg'; } piece_x = esviji.xToCoord(x); piece_y = esviji.yToCoord(y); esviji.drawnCurrentPieces[x][y] = esviji.board.image(pieceFile, piece_x, -30, 30, 30); esviji.drawnCurrentPieces[x][y].animate({'y': piece_y}, 2000, 'bounce'); } } } }, erasePieces: function erasePieces() { for(x = 1; x <= 6; x++) { if (esviji.drawnCurrentPieces[x] != undefined) { for (y = 1; y <= 6; y++) { if (esviji.drawnCurrentPieces[x][y] != null) { esviji.drawnCurrentPieces[x][y].remove(); } } } } }, getValidPieces: function getValidPieces() { var x, y, dir_x, dir_y, found; esviji.validPieces = []; for (y_start = 1; y_start <= 12; y_start++) { x = 9; y = y_start; dir_x = -1; dir_y = 0; found = false; while (!found) { if (y == 1 && dir_y == -1) { found = true; } else { if (x == 1 && dir_x == -1) { dir_x = 0; dir_y = -1; } else { nextPiece = esviji.currentPieces[x + dir_x][y + dir_y]; if (nextPiece == esviji.ROCK) { if (dir_x == -1) { dir_x = 0; dir_y = -1; } else { found = true; } } else { if (nextPiece == esviji.EMPTY) { x += dir_x; y += dir_y; } else { if (esviji.validPieces.indexOf(nextPiece) == -1) { esviji.validPieces.push(nextPiece); } found = true; } } } } } } }, drawScore: function drawScore() { if (esviji.drawnScore != null) { esviji.drawnScore.remove(); } esviji.drawnScore = esviji.board.print(170, 38, "score: " + esviji.score, esviji.board.getFont('ChewyRegular'), 24); esviji.drawnScore.attr({'fill': '#333366'}); }, drawLevel: function drawLevel() { if (esviji.drawnLevel != null) { esviji.drawnLevel.remove(); } esviji.drawnLevel = esviji.board.print(10, 110, 'level ' + esviji.level, esviji.board.getFont('ChewyRegular'), 20); esviji.drawnLevel.attr({'fill': '#333366'}); }, drawLives: function drawLives() { if (esviji.drawnLives != null) { esviji.drawnLives.remove(); } esviji.drawnLives = esviji.board.print(10, 140, esviji.lives + ' lives', esviji.board.getFont('ChewyRegular'), 20); esviji.drawnLives.attr({'fill': '#333366'}); }, run: function run() { esviji.init(); esviji.nextLevel(); } }
white background
esviji.js
white background
<ide><path>sviji.js <ide> var windowAddEvent = window.attachEvent || window.addEventListener; <ide> windowAddEvent('onresize', esviji.updateViewportSize, false); <ide> <del> var header = esviji.board.path('M 1 21 l 0 205 l 35 0 l 0 -35 l 35 0 l 0 -35 l 35 0 l 0 -35 l 35 0 l 0 -35 l 35 0 l 0 -35 l 35 0 l 108 0 l 0 -30 z'), <add> var background = esviji.board.rect(1, 1, esviji.VIEWPORT_WIDTH, esviji.VIEWPORT_HEIGHT), <add> header = esviji.board.path('M 1 21 l 0 205 l 35 0 l 0 -35 l 35 0 l 0 -35 l 35 0 l 0 -35 l 35 0 l 0 -35 l 35 0 l 0 -35 l 35 0 l 108 0 l 0 -30 z'), <ide> title = esviji.board.print(0, 60, "esviji", esviji.board.getFont('ChewyRegular'), 60); <ide> <ide> esviji.drawScore(); <ide> esviji.drawLevel(); <ide> esviji.drawLives(); <ide> <add> background.attr({ 'fill': '#ffffff'}); <add> <ide> header.attr({ <ide> 'fill': '#9999cc', <ide> 'stroke': '#666699',
Java
apache-2.0
4a347e1add766bb82853036198e0e6ca396073a9
0
charlesccychen/beam,apache/beam,chamikaramj/beam,charlesccychen/beam,RyanSkraba/beam,apache/beam,apache/beam,lukecwik/incubator-beam,charlesccychen/beam,mxm/incubator-beam,charlesccychen/beam,chamikaramj/beam,robertwb/incubator-beam,charlesccychen/incubator-beam,lukecwik/incubator-beam,RyanSkraba/beam,rangadi/incubator-beam,rangadi/beam,rangadi/beam,RyanSkraba/beam,iemejia/incubator-beam,charlesccychen/beam,apache/beam,robertwb/incubator-beam,lukecwik/incubator-beam,rangadi/beam,robertwb/incubator-beam,mxm/incubator-beam,rangadi/incubator-beam,apache/beam,markflyhigh/incubator-beam,markflyhigh/incubator-beam,apache/beam,markflyhigh/incubator-beam,lukecwik/incubator-beam,lukecwik/incubator-beam,robertwb/incubator-beam,apache/beam,charlesccychen/beam,robertwb/incubator-beam,apache/beam,charlesccychen/incubator-beam,chamikaramj/beam,chamikaramj/beam,robertwb/incubator-beam,rangadi/incubator-beam,RyanSkraba/beam,markflyhigh/incubator-beam,lukecwik/incubator-beam,markflyhigh/incubator-beam,chamikaramj/beam,apache/beam,markflyhigh/incubator-beam,chamikaramj/beam,apache/beam,rangadi/beam,charlesccychen/incubator-beam,chamikaramj/beam,RyanSkraba/beam,rangadi/beam,markflyhigh/incubator-beam,apache/beam,lukecwik/incubator-beam,lukecwik/incubator-beam,robertwb/incubator-beam,chamikaramj/beam,robertwb/incubator-beam,robertwb/incubator-beam,chamikaramj/beam,robertwb/incubator-beam,chamikaramj/beam,iemejia/incubator-beam,rangadi/beam,rangadi/beam,RyanSkraba/beam,charlesccychen/beam,RyanSkraba/beam,lukecwik/incubator-beam,lukecwik/incubator-beam
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.beam.runners.direct.portable; import static com.google.common.base.Preconditions.checkState; import static com.google.common.collect.Iterables.getOnlyElement; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; import com.google.common.collect.Iterables; import java.io.Serializable; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import org.apache.beam.model.pipeline.v1.RunnerApi; import org.apache.beam.runners.core.construction.PipelineTranslation; import org.apache.beam.runners.core.construction.graph.ExecutableStage; import org.apache.beam.runners.core.construction.graph.GreedyPipelineFuser; import org.apache.beam.runners.core.construction.graph.PipelineNode; import org.apache.beam.runners.core.construction.graph.PipelineNode.PCollectionNode; import org.apache.beam.runners.core.construction.graph.PipelineNode.PTransformNode; import org.apache.beam.runners.core.construction.graph.QueryablePipeline; import org.apache.beam.runners.fnexecution.GrpcContextHeaderAccessorProvider; import org.apache.beam.runners.fnexecution.GrpcFnServer; import org.apache.beam.runners.fnexecution.InProcessServerFactory; import org.apache.beam.runners.fnexecution.control.FnApiControlClientPoolService; import org.apache.beam.runners.fnexecution.control.InstructionRequestHandler; import org.apache.beam.runners.fnexecution.control.JobBundleFactory; import org.apache.beam.runners.fnexecution.data.GrpcDataService; import org.apache.beam.runners.fnexecution.environment.EnvironmentFactory; import org.apache.beam.runners.fnexecution.environment.InProcessEnvironmentFactory; import org.apache.beam.runners.fnexecution.logging.GrpcLoggingService; import org.apache.beam.runners.fnexecution.logging.Slf4jLogWriter; import org.apache.beam.runners.fnexecution.state.GrpcStateService; import org.apache.beam.sdk.Pipeline; import org.apache.beam.sdk.options.PipelineOptionsFactory; import org.apache.beam.sdk.transforms.DoFn; import org.apache.beam.sdk.transforms.Flatten; import org.apache.beam.sdk.transforms.GroupByKey; import org.apache.beam.sdk.transforms.Impulse; import org.apache.beam.sdk.transforms.ParDo; import org.apache.beam.sdk.util.WindowedValue; import org.apache.beam.sdk.values.KV; import org.apache.beam.sdk.values.PCollection; import org.apache.beam.sdk.values.PCollectionList; import org.joda.time.Instant; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link RemoteStageEvaluatorFactory}. */ @RunWith(JUnit4.class) public class RemoteStageEvaluatorFactoryTest implements Serializable { private transient RemoteStageEvaluatorFactory factory; private transient ExecutorService executor; private transient GrpcFnServer<GrpcDataService> dataServer; private transient GrpcFnServer<GrpcStateService> stateServer; private transient GrpcFnServer<FnApiControlClientPoolService> controlServer; private transient GrpcFnServer<GrpcLoggingService> loggingServer; private transient BundleFactory bundleFactory; @Before public void setup() throws Exception { InProcessServerFactory serverFactory = InProcessServerFactory.create(); BlockingQueue<InstructionRequestHandler> clientPool = new LinkedBlockingQueue<>(); controlServer = GrpcFnServer.allocatePortAndCreateFor( FnApiControlClientPoolService.offeringClientsToPool( (workerId, instructionHandler) -> clientPool.put(instructionHandler), GrpcContextHeaderAccessorProvider.getHeaderAccessor()), serverFactory); loggingServer = GrpcFnServer.allocatePortAndCreateFor( GrpcLoggingService.forWriter(Slf4jLogWriter.getDefault()), serverFactory); EnvironmentFactory environmentFactory = InProcessEnvironmentFactory.create( PipelineOptionsFactory.create(), loggingServer, controlServer, (workerId, timeout) -> clientPool.take()); executor = Executors.newCachedThreadPool(); dataServer = GrpcFnServer.allocatePortAndCreateFor(GrpcDataService.create(executor), serverFactory); stateServer = GrpcFnServer.allocatePortAndCreateFor(GrpcStateService.create(), serverFactory); bundleFactory = ImmutableListBundleFactory.create(); JobBundleFactory jobBundleFactory = DirectJobBundleFactory.create(environmentFactory, dataServer, stateServer); factory = new RemoteStageEvaluatorFactory(bundleFactory, jobBundleFactory); } @After public void teardown() throws Exception { try (AutoCloseable logging = loggingServer; AutoCloseable exec = executor::shutdownNow; AutoCloseable data = dataServer; AutoCloseable state = stateServer; AutoCloseable control = controlServer) {} } @Test public void executesRemoteStage() throws Exception { Pipeline p = Pipeline.create(); p.apply("impulse", Impulse.create()) .apply( "CreateInputs", ParDo.of( new DoFn<byte[], Integer>() { @ProcessElement public void create(ProcessContext ctxt) { ctxt.output(1); ctxt.output(2); ctxt.output(3); } })) .apply( "ParDo", ParDo.of( new DoFn<Integer, KV<String, Long>>() { @ProcessElement public void proc(ProcessContext ctxt) { ctxt.output(KV.of("foo", ctxt.element().longValue())); } })) .apply(GroupByKey.create()); RunnerApi.Pipeline fusedPipeline = GreedyPipelineFuser.fuse(PipelineTranslation.toProto(p)).toPipeline(); QueryablePipeline fusedQP = QueryablePipeline.forPipeline(fusedPipeline); PTransformNode impulseTransform = getOnlyElement(fusedQP.getRootTransforms()); PCollectionNode impulseOutput = getOnlyElement(fusedQP.getOutputPCollections(impulseTransform)); PTransformNode stage = fusedPipeline .getRootTransformIdsList() .stream() .map( id -> PipelineNode.pTransform( id, fusedPipeline.getComponents().getTransformsOrThrow(id))) .filter(node -> node.getTransform().getSpec().getUrn().equals(ExecutableStage.URN)) .findFirst() .orElseThrow(IllegalArgumentException::new); WindowedValue<byte[]> impulse = WindowedValue.valueInGlobalWindow(new byte[0]); CommittedBundle<byte[]> inputBundle = bundleFactory.<byte[]>createBundle(impulseOutput).add(impulse).commit(Instant.now()); TransformEvaluator<byte[]> evaluator = factory.forApplication(stage, inputBundle); evaluator.processElement(impulse); TransformResult<byte[]> result = evaluator.finishBundle(); assertThat(Iterables.size(result.getOutputBundles()), equalTo(1)); CommittedBundle<?> outputs = getOnlyElement(result.getOutputBundles()).commit(Instant.now()); assertThat(Iterables.size(outputs), equalTo(3)); } @Test public void executesStageWithFlatten() throws Exception { ParDo.SingleOutput<byte[], KV<Integer, String>> parDo = ParDo.of( new DoFn<byte[], KV<Integer, String>>() { @ProcessElement public void process(ProcessContext ctxt) { ctxt.output(KV.of(1, "foo")); ctxt.output(KV.of(1, "bar")); ctxt.output(KV.of(2, "foo")); } }); Pipeline p = Pipeline.create(); PCollection<KV<Integer, String>> left = p.apply("left", Impulse.create()).apply(parDo); PCollection<KV<Integer, String>> right = p.apply("right", Impulse.create()).apply(parDo); PCollectionList.of(left).and(right).apply(Flatten.pCollections()).apply(GroupByKey.create()); RunnerApi.Pipeline fusedPipeline = GreedyPipelineFuser.fuse(PipelineTranslation.toProto(p)).toPipeline(); QueryablePipeline fusedQP = QueryablePipeline.forPipeline(fusedPipeline); PTransformNode leftRoot = null; PTransformNode rightRoot = null; for (PTransformNode root : fusedQP.getRootTransforms()) { if (root.getId().equals("left")) { leftRoot = root; } else { rightRoot = root; } } checkState(leftRoot != null); checkState(rightRoot != null); PTransformNode stage = fusedPipeline .getRootTransformIdsList() .stream() .map( id -> PipelineNode.pTransform( id, fusedPipeline.getComponents().getTransformsOrThrow(id))) .filter(node -> node.getTransform().getSpec().getUrn().equals(ExecutableStage.URN)) .findFirst() .orElseThrow(IllegalArgumentException::new); WindowedValue<byte[]> impulse = WindowedValue.valueInGlobalWindow(new byte[0]); String inputId = getOnlyElement(stage.getTransform().getInputsMap().values()); CommittedBundle<byte[]> inputBundle = bundleFactory .<byte[]>createBundle( PipelineNode.pCollection( inputId, fusedPipeline.getComponents().getPcollectionsOrThrow(inputId))) .add(impulse) .commit(Instant.now()); TransformEvaluator<byte[]> evaluator = factory.forApplication(stage, inputBundle); evaluator.processElement(impulse); TransformResult<byte[]> result = evaluator.finishBundle(); assertThat(Iterables.size(result.getOutputBundles()), equalTo(1)); CommittedBundle<?> outputs = getOnlyElement(result.getOutputBundles()).commit(Instant.now()); assertThat(Iterables.size(outputs), equalTo(3)); } }
runners/direct-java/src/test/java/org/apache/beam/runners/direct/portable/RemoteStageEvaluatorFactoryTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.beam.runners.direct.portable; import static com.google.common.collect.Iterables.getOnlyElement; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; import com.google.common.collect.Iterables; import java.io.Serializable; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import org.apache.beam.model.pipeline.v1.RunnerApi; import org.apache.beam.runners.core.construction.PipelineTranslation; import org.apache.beam.runners.core.construction.graph.ExecutableStage; import org.apache.beam.runners.core.construction.graph.GreedyPipelineFuser; import org.apache.beam.runners.core.construction.graph.PipelineNode; import org.apache.beam.runners.core.construction.graph.PipelineNode.PCollectionNode; import org.apache.beam.runners.core.construction.graph.PipelineNode.PTransformNode; import org.apache.beam.runners.core.construction.graph.QueryablePipeline; import org.apache.beam.runners.fnexecution.GrpcContextHeaderAccessorProvider; import org.apache.beam.runners.fnexecution.GrpcFnServer; import org.apache.beam.runners.fnexecution.InProcessServerFactory; import org.apache.beam.runners.fnexecution.control.FnApiControlClientPoolService; import org.apache.beam.runners.fnexecution.control.InstructionRequestHandler; import org.apache.beam.runners.fnexecution.control.JobBundleFactory; import org.apache.beam.runners.fnexecution.data.GrpcDataService; import org.apache.beam.runners.fnexecution.environment.EnvironmentFactory; import org.apache.beam.runners.fnexecution.environment.InProcessEnvironmentFactory; import org.apache.beam.runners.fnexecution.logging.GrpcLoggingService; import org.apache.beam.runners.fnexecution.logging.Slf4jLogWriter; import org.apache.beam.runners.fnexecution.state.GrpcStateService; import org.apache.beam.sdk.Pipeline; import org.apache.beam.sdk.options.PipelineOptionsFactory; import org.apache.beam.sdk.transforms.DoFn; import org.apache.beam.sdk.transforms.GroupByKey; import org.apache.beam.sdk.transforms.Impulse; import org.apache.beam.sdk.transforms.ParDo; import org.apache.beam.sdk.util.WindowedValue; import org.apache.beam.sdk.values.KV; import org.joda.time.Instant; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link RemoteStageEvaluatorFactory}. */ @RunWith(JUnit4.class) public class RemoteStageEvaluatorFactoryTest implements Serializable { private transient RemoteStageEvaluatorFactory factory; private transient ExecutorService executor; private transient GrpcFnServer<GrpcDataService> dataServer; private transient GrpcFnServer<GrpcStateService> stateServer; private transient GrpcFnServer<FnApiControlClientPoolService> controlServer; private transient GrpcFnServer<GrpcLoggingService> loggingServer; private transient BundleFactory bundleFactory; @Before public void setup() throws Exception { InProcessServerFactory serverFactory = InProcessServerFactory.create(); BlockingQueue<InstructionRequestHandler> clientPool = new LinkedBlockingQueue<>(); controlServer = GrpcFnServer.allocatePortAndCreateFor( FnApiControlClientPoolService.offeringClientsToPool( (workerId, instructionHandler) -> clientPool.put(instructionHandler), GrpcContextHeaderAccessorProvider.getHeaderAccessor()), serverFactory); loggingServer = GrpcFnServer.allocatePortAndCreateFor( GrpcLoggingService.forWriter(Slf4jLogWriter.getDefault()), serverFactory); EnvironmentFactory environmentFactory = InProcessEnvironmentFactory.create( PipelineOptionsFactory.create(), loggingServer, controlServer, (workerId, timeout) -> clientPool.take()); executor = Executors.newCachedThreadPool(); dataServer = GrpcFnServer.allocatePortAndCreateFor(GrpcDataService.create(executor), serverFactory); stateServer = GrpcFnServer.allocatePortAndCreateFor(GrpcStateService.create(), serverFactory); bundleFactory = ImmutableListBundleFactory.create(); JobBundleFactory jobBundleFactory = DirectJobBundleFactory.create(environmentFactory, dataServer, stateServer); factory = new RemoteStageEvaluatorFactory(bundleFactory, jobBundleFactory); } @After public void teardown() throws Exception { try (AutoCloseable logging = loggingServer; AutoCloseable exec = executor::shutdownNow; AutoCloseable data = dataServer; AutoCloseable state = stateServer; AutoCloseable control = controlServer) {} } @Test public void executesRemoteStage() throws Exception { Pipeline p = Pipeline.create(); p.apply("impulse", Impulse.create()) .apply( "CreateInputs", ParDo.of( new DoFn<byte[], Integer>() { @ProcessElement public void create(ProcessContext ctxt) { ctxt.output(1); ctxt.output(2); ctxt.output(3); } })) .apply( "ParDo", ParDo.of( new DoFn<Integer, KV<String, Long>>() { @ProcessElement public void proc(ProcessContext ctxt) { ctxt.output(KV.of("foo", ctxt.element().longValue())); } })) .apply(GroupByKey.create()); RunnerApi.Pipeline fusedPipeline = GreedyPipelineFuser.fuse(PipelineTranslation.toProto(p)).toPipeline(); QueryablePipeline fusedQP = QueryablePipeline.forPipeline(fusedPipeline); PTransformNode impulseTransform = getOnlyElement(fusedQP.getRootTransforms()); PCollectionNode impulseOutput = getOnlyElement(fusedQP.getOutputPCollections(impulseTransform)); PTransformNode stage = fusedPipeline .getRootTransformIdsList() .stream() .map( id -> PipelineNode.pTransform( id, fusedPipeline.getComponents().getTransformsOrThrow(id))) .filter(node -> node.getTransform().getSpec().getUrn().equals(ExecutableStage.URN)) .findFirst() .orElseThrow(IllegalArgumentException::new); WindowedValue<byte[]> impulse = WindowedValue.valueInGlobalWindow(new byte[0]); CommittedBundle<byte[]> inputBundle = bundleFactory.<byte[]>createBundle(impulseOutput).add(impulse).commit(Instant.now()); TransformEvaluator<byte[]> evaluator = factory.forApplication(stage, inputBundle); evaluator.processElement(impulse); TransformResult<byte[]> result = evaluator.finishBundle(); assertThat(Iterables.size(result.getOutputBundles()), equalTo(1)); CommittedBundle<?> outputs = getOnlyElement(result.getOutputBundles()).commit(Instant.now()); assertThat(Iterables.size(outputs), equalTo(3)); } }
Add a test to show Flatten Execution A broader test had broken in the PortableDirectRunner, so add a focused test to rule out the Flatten being the cause of the break.
runners/direct-java/src/test/java/org/apache/beam/runners/direct/portable/RemoteStageEvaluatorFactoryTest.java
Add a test to show Flatten Execution
<ide><path>unners/direct-java/src/test/java/org/apache/beam/runners/direct/portable/RemoteStageEvaluatorFactoryTest.java <ide> <ide> package org.apache.beam.runners.direct.portable; <ide> <add>import static com.google.common.base.Preconditions.checkState; <ide> import static com.google.common.collect.Iterables.getOnlyElement; <ide> import static org.hamcrest.Matchers.equalTo; <ide> import static org.junit.Assert.assertThat; <ide> import org.apache.beam.sdk.Pipeline; <ide> import org.apache.beam.sdk.options.PipelineOptionsFactory; <ide> import org.apache.beam.sdk.transforms.DoFn; <add>import org.apache.beam.sdk.transforms.Flatten; <ide> import org.apache.beam.sdk.transforms.GroupByKey; <ide> import org.apache.beam.sdk.transforms.Impulse; <ide> import org.apache.beam.sdk.transforms.ParDo; <ide> import org.apache.beam.sdk.util.WindowedValue; <ide> import org.apache.beam.sdk.values.KV; <add>import org.apache.beam.sdk.values.PCollection; <add>import org.apache.beam.sdk.values.PCollectionList; <ide> import org.joda.time.Instant; <ide> import org.junit.After; <ide> import org.junit.Before; <ide> CommittedBundle<?> outputs = getOnlyElement(result.getOutputBundles()).commit(Instant.now()); <ide> assertThat(Iterables.size(outputs), equalTo(3)); <ide> } <add> <add> @Test <add> public void executesStageWithFlatten() throws Exception { <add> ParDo.SingleOutput<byte[], KV<Integer, String>> parDo = <add> ParDo.of( <add> new DoFn<byte[], KV<Integer, String>>() { <add> @ProcessElement <add> public void process(ProcessContext ctxt) { <add> ctxt.output(KV.of(1, "foo")); <add> ctxt.output(KV.of(1, "bar")); <add> ctxt.output(KV.of(2, "foo")); <add> } <add> }); <add> Pipeline p = Pipeline.create(); <add> <add> PCollection<KV<Integer, String>> left = p.apply("left", Impulse.create()).apply(parDo); <add> PCollection<KV<Integer, String>> right = p.apply("right", Impulse.create()).apply(parDo); <add> PCollectionList.of(left).and(right).apply(Flatten.pCollections()).apply(GroupByKey.create()); <add> <add> RunnerApi.Pipeline fusedPipeline = <add> GreedyPipelineFuser.fuse(PipelineTranslation.toProto(p)).toPipeline(); <add> QueryablePipeline fusedQP = QueryablePipeline.forPipeline(fusedPipeline); <add> PTransformNode leftRoot = null; <add> PTransformNode rightRoot = null; <add> for (PTransformNode root : fusedQP.getRootTransforms()) { <add> if (root.getId().equals("left")) { <add> leftRoot = root; <add> } else { <add> rightRoot = root; <add> } <add> } <add> checkState(leftRoot != null); <add> checkState(rightRoot != null); <add> PTransformNode stage = <add> fusedPipeline <add> .getRootTransformIdsList() <add> .stream() <add> .map( <add> id -> <add> PipelineNode.pTransform( <add> id, fusedPipeline.getComponents().getTransformsOrThrow(id))) <add> .filter(node -> node.getTransform().getSpec().getUrn().equals(ExecutableStage.URN)) <add> .findFirst() <add> .orElseThrow(IllegalArgumentException::new); <add> <add> WindowedValue<byte[]> impulse = WindowedValue.valueInGlobalWindow(new byte[0]); <add> String inputId = getOnlyElement(stage.getTransform().getInputsMap().values()); <add> CommittedBundle<byte[]> inputBundle = <add> bundleFactory <add> .<byte[]>createBundle( <add> PipelineNode.pCollection( <add> inputId, fusedPipeline.getComponents().getPcollectionsOrThrow(inputId))) <add> .add(impulse) <add> .commit(Instant.now()); <add> TransformEvaluator<byte[]> evaluator = factory.forApplication(stage, inputBundle); <add> evaluator.processElement(impulse); <add> TransformResult<byte[]> result = evaluator.finishBundle(); <add> assertThat(Iterables.size(result.getOutputBundles()), equalTo(1)); <add> CommittedBundle<?> outputs = getOnlyElement(result.getOutputBundles()).commit(Instant.now()); <add> assertThat(Iterables.size(outputs), equalTo(3)); <add> } <ide> }
Java
apache-2.0
2303cdda5cf69eaccabc5eca79be12a3f3cc9d0d
0
SpineEventEngine/base,SpineEventEngine/base,SpineEventEngine/base
/* * Copyright 2021, TeamDev. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.tools.javadoc.style; import com.google.common.base.Splitter; import static java.lang.System.lineSeparator; import static java.util.stream.Collectors.joining; /** * A {@link FormattingAction}, that formats lines independently of each other. */ abstract class LineFormatting implements FormattingAction { private static final Splitter splitter = Splitter.on(lineSeparator()); /** * Obtains the formatted representation of the specified text. * * <p>The text will be split and lines will be formatted independently from each other. * * @param text the text to format * @return the formatted text */ @Override public String execute(String text) { String result = splitter.splitToStream(text) .map(this::formatLine) .collect(joining(lineSeparator())); return result; } /** * Obtains the formatted representation of the specified line. * * @param line the single line without line separators * @return the formatted representation */ abstract String formatLine(String line); }
tools/javadoc-style/src/main/java/io/spine/tools/javadoc/style/LineFormatting.java
/* * Copyright 2021, TeamDev. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.tools.javadoc.style; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import java.util.List; import static java.lang.System.lineSeparator; import static java.util.stream.Collectors.toList; /** * A {@link FormattingAction}, that formats lines independently of each other. */ abstract class LineFormatting implements FormattingAction { private static final Splitter splitter = Splitter.on(lineSeparator()); private static final Joiner joiner = Joiner.on(lineSeparator()); /** * Obtains the formatted representation of the specified text. * * <p>The text will be split and lines will be formatted independently from each other. * * @param text the text to format * @return the formatted text */ @Override public String execute(String text) { List<String> formattedLines = splitter.splitToStream(text) .map(this::formatLine) .collect(toList()); String result = joiner.join(formattedLines); return result; } /** * Obtains the formatted representation of the specified line. * * @param line the single line without line separators * @return the formatted representation */ abstract String formatLine(String line); }
Improve splitting and joining
tools/javadoc-style/src/main/java/io/spine/tools/javadoc/style/LineFormatting.java
Improve splitting and joining
<ide><path>ools/javadoc-style/src/main/java/io/spine/tools/javadoc/style/LineFormatting.java <ide> <ide> package io.spine.tools.javadoc.style; <ide> <del>import com.google.common.base.Joiner; <ide> import com.google.common.base.Splitter; <ide> <del>import java.util.List; <del> <ide> import static java.lang.System.lineSeparator; <del>import static java.util.stream.Collectors.toList; <add>import static java.util.stream.Collectors.joining; <ide> <ide> /** <ide> * A {@link FormattingAction}, that formats lines independently of each other. <ide> abstract class LineFormatting implements FormattingAction { <ide> <ide> private static final Splitter splitter = Splitter.on(lineSeparator()); <del> private static final Joiner joiner = Joiner.on(lineSeparator()); <ide> <ide> /** <ide> * Obtains the formatted representation of the specified text. <ide> */ <ide> @Override <ide> public String execute(String text) { <del> List<String> formattedLines = <add> String result = <ide> splitter.splitToStream(text) <ide> .map(this::formatLine) <del> .collect(toList()); <del> String result = joiner.join(formattedLines); <add> .collect(joining(lineSeparator())); <ide> return result; <ide> } <ide>
Java
bsd-3-clause
edb4f598c0f64c4a7c15bc15f84c648f68a36041
0
lviggiano/owner,FrimaStudio/owner,gintau/owner,kevin-canadian/owner,gintau/owner,lightglitch/owner,FrimaStudio/owner,gintau/owner,rrialq/owner,lightglitch/owner,kevin-canadian/owner,lviggiano/owner,rrialq/owner,StFS/owner,jghoman/owner,FrimaStudio/owner,lightglitch/owner,lviggiano/owner,jghoman/owner,StFS/owner,kevin-canadian/owner,jghoman/owner,StFS/owner,rrialq/owner
/* * Copyright (c) 2012, Luigi R. Viggiano * All rights reserved. * * This software is distributable under the BSD license. * See the terms of the BSD license in the documentation provided with this software. */ package org.aeonbits.owner; import org.junit.Test; import java.util.Properties; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; /** * @author Luigi R. Viggiano */ public class StrSubstitutorTest { @Test public void shouldReturnNullWhenNullIsProvided() { Properties props = new Properties(); StrSubstitutor substitutor = new StrSubstitutor(props); assertNull(substitutor.replace(null)); } @Test public void shouldReplaceVariables() { Properties values = new Properties(); values.setProperty("animal", "quick brown fox"); values.setProperty("target", "lazy dog"); String templateString = "The ${animal} jumped over the ${target}."; StrSubstitutor sub = new StrSubstitutor(values); String resolvedString = sub.replace(templateString); assertEquals("The quick brown fox jumped over the lazy dog.", resolvedString); } @Test public void testRecoursiveResolution() { Properties values = new Properties(); values.setProperty("color", "brown"); values.setProperty("animal", "quick ${color} fox"); values.setProperty("target.attribute", "lazy"); values.setProperty("target.animal", "dog"); values.setProperty("target", "${target.attribute} ${target.animal}"); values.setProperty("template", "The ${animal} jumped over the ${target}."); String templateString = "${template}"; StrSubstitutor sub = new StrSubstitutor(values); String resolvedString = sub.replace(templateString); assertEquals("The quick brown fox jumped over the lazy dog.", resolvedString); } @Test public void testMissingPropertyIsReplacedWithEmptyString() { Properties values = new Properties() {{ setProperty("foo", "fooValue"); setProperty("baz", "bazValue"); }}; String template = "Test: ${foo} ${bar} ${baz} :Test"; String expected = "Test: fooValue bazValue :Test"; String result = new StrSubstitutor(values).replace(template); assertEquals(expected, result); } }
src/test/java/org/aeonbits/owner/StrSubstitutorTest.java
/* * Copyright (c) 2012, Luigi R. Viggiano * All rights reserved. * * This software is distributable under the BSD license. * See the terms of the BSD license in the documentation provided with this software. */ package org.aeonbits.owner; import org.junit.Test; import java.util.Properties; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; /** * @author Luigi R. Viggiano */ public class StrSubstitutorTest { @Test public void shouldReturnNullWhenNullIsProvided() { Properties props = new Properties(); StrSubstitutor substitutor = new StrSubstitutor(props); assertNull(substitutor.replace(null)); } @Test public void shouldReplaceVariables() { Properties values = new Properties(); values.setProperty("animal", "quick brown fox"); values.setProperty("target", "lazy dog"); String templateString = "The ${animal} jumped over the ${target}."; StrSubstitutor sub = new StrSubstitutor(values); String resolvedString = sub.replace(templateString); assertEquals("The quick brown fox jumped over the lazy dog.", resolvedString); } @Test public void testRecoursiveResolution() { Properties values = new Properties(); values.setProperty("color", "brown"); values.setProperty("animal", "quick ${color} fox"); values.setProperty("target.attribute", "lazy"); values.setProperty("target.animal", "dog"); values.setProperty("target", "${target.attribute} ${target.animal}"); values.setProperty("template", "The ${animal} jumped over the ${target}."); String templateString = "${template}"; StrSubstitutor sub = new StrSubstitutor(values); String resolvedString = sub.replace(templateString); assertEquals("The quick brown fox jumped over the lazy dog.", resolvedString); } }
added test for a corner case
src/test/java/org/aeonbits/owner/StrSubstitutorTest.java
added test for a corner case
<ide><path>rc/test/java/org/aeonbits/owner/StrSubstitutorTest.java <ide> assertEquals("The quick brown fox jumped over the lazy dog.", resolvedString); <ide> } <ide> <add> @Test <add> public void testMissingPropertyIsReplacedWithEmptyString() { <add> Properties values = new Properties() {{ <add> setProperty("foo", "fooValue"); <add> setProperty("baz", "bazValue"); <add> }}; <add> String template = "Test: ${foo} ${bar} ${baz} :Test"; <add> String expected = "Test: fooValue bazValue :Test"; <add> String result = new StrSubstitutor(values).replace(template); <add> assertEquals(expected, result); <add> } <add> <ide> }
Java
bsd-2-clause
5bbd790a2fd56dd7c4a9f1da07c7448d4fa72eb7
0
bartbes/OpenBlocks-Elevator-Indicator
package com.bartbes.openblocksElevatorIndicator; import org.lwjgl.opengl.GL11; import net.minecraft.block.Block; import net.minecraft.world.World; import net.minecraft.client.gui.Gui; import net.minecraft.client.Minecraft; import net.minecraft.util.ResourceLocation; import net.minecraft.client.entity.EntityClientPlayerMP; import cpw.mods.fml.common.gameevent.TickEvent; import cpw.mods.fml.common.gameevent.TickEvent.Phase; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.client.event.RenderGameOverlayEvent; public class IndicatorOverlay extends Gui { private static final int ICON_SIZE = 32; private static final int HALF_ICON_SIZE = ICON_SIZE/2; private static final ResourceLocation ICON_RES = new ResourceLocation("openblockselevatorindicator:gui/obelevindicator.png"); private Minecraft minecraft; private boolean onElevator = false; private int xPos = 0; private int yPos = 0; private int zPos = 0; private boolean moved = true; IndicatorOverlay() { super(); minecraft = Minecraft.getMinecraft(); } // Updating stuff private int round(double x) { // Round away from 0 int y = (int) x; if (y < 0) return y-1; return y; } private void updatePosition() { EntityClientPlayerMP player = minecraft.thePlayer; int x = round(player.posX); int y = round(player.posY-player.height); int z = round(player.posZ); moved = (x != xPos || y != yPos || z != zPos); xPos = x; yPos = y; zPos = z; } private Block getBlockUnderPlayer() { World world = minecraft.thePlayer.worldObj; return world.getBlock(xPos, yPos, zPos); } @SubscribeEvent public void onPlayerTick(TickEvent.PlayerTickEvent event) { if (event.phase != Phase.START) return; updatePosition(); if (!moved) return; Block b = getBlockUnderPlayer(); onElevator = (b == IndicatorMod.instance.elevatorBlock); } // Drawing stuff @SubscribeEvent public void onRenderIndicator(RenderGameOverlayEvent.Post event) { if (event.type != RenderGameOverlayEvent.ElementType.EXPERIENCE) return; if (!onElevator) return; GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); GL11.glDisable(GL11.GL_LIGHTING); minecraft.renderEngine.bindTexture(ICON_RES); // Represents center x int xpos = event.resolution.getScaledWidth()/2; // Represents bottom y int ypos = event.resolution.getScaledHeight() - 31; // Our image is a bit large, so we'll scale it down GL11.glPushMatrix(); GL11.glTranslatef(xpos, ypos, 0.0f); GL11.glScalef(0.25f, 0.25f, 1.0f); drawTexturedModalRect(-HALF_ICON_SIZE, -ICON_SIZE, 0, 0, ICON_SIZE, ICON_SIZE); // Now undo our transformation GL11.glPopMatrix(); } }
src/main/java/com/bartbes/openblocksElevatorIndicator/IndicatorOverlay.java
package com.bartbes.openblocksElevatorIndicator; import org.lwjgl.opengl.GL11; import net.minecraft.block.Block; import net.minecraft.world.World; import net.minecraft.client.gui.Gui; import net.minecraft.client.Minecraft; import net.minecraft.util.ResourceLocation; import net.minecraft.client.entity.EntityClientPlayerMP; import cpw.mods.fml.common.gameevent.TickEvent; import cpw.mods.fml.common.gameevent.TickEvent.Phase; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.client.event.RenderGameOverlayEvent; public class IndicatorOverlay extends Gui { private static final int ICON_SIZE = 32; private static final int HALF_ICON_SIZE = ICON_SIZE/2; private static final ResourceLocation ICON_RES = new ResourceLocation("openblockselevatorindicator:gui/obelevindicator.png"); private Minecraft minecraft; private boolean onElevator = false; private int xPos = 0; private int yPos = 0; private int zPos = 0; private boolean moved = true; IndicatorOverlay() { super(); minecraft = Minecraft.getMinecraft(); } @SubscribeEvent public void onPlayerTick(TickEvent.PlayerTickEvent event) { if (event.phase != Phase.START) return; updatePosition(); if (!moved) return; Block b = getBlockUnderPlayer(); onElevator = (b == IndicatorMod.instance.elevatorBlock); } @SubscribeEvent public void onRenderIndicator(RenderGameOverlayEvent.Post event) { if (event.type != RenderGameOverlayEvent.ElementType.EXPERIENCE) return; if (!onElevator) return; GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); GL11.glDisable(GL11.GL_LIGHTING); minecraft.renderEngine.bindTexture(ICON_RES); // Represents center x int xpos = event.resolution.getScaledWidth()/2; // Represents bottom y int ypos = event.resolution.getScaledHeight() - 31; // Our image is a bit large, so we'll scale it down GL11.glPushMatrix(); GL11.glTranslatef(xpos, ypos, 0.0f); GL11.glScalef(0.25f, 0.25f, 1.0f); drawTexturedModalRect(-HALF_ICON_SIZE, -ICON_SIZE, 0, 0, ICON_SIZE, ICON_SIZE); // Now undo our transformation GL11.glPopMatrix(); } private int round(double x) { // Round away from 0 int y = (int) x; if (y < 0) return y-1; return y; } private void updatePosition() { EntityClientPlayerMP player = minecraft.thePlayer; int x = round(player.posX); int y = round(player.posY-player.height); int z = round(player.posZ); moved = (x != xPos || y != yPos || z != zPos); xPos = x; yPos = y; zPos = z; } private Block getBlockUnderPlayer() { World world = minecraft.thePlayer.worldObj; return world.getBlock(xPos, yPos, zPos); } }
Reorganize functions
src/main/java/com/bartbes/openblocksElevatorIndicator/IndicatorOverlay.java
Reorganize functions
<ide><path>rc/main/java/com/bartbes/openblocksElevatorIndicator/IndicatorOverlay.java <ide> minecraft = Minecraft.getMinecraft(); <ide> } <ide> <add> // Updating stuff <add> private int round(double x) <add> { <add> // Round away from 0 <add> int y = (int) x; <add> if (y < 0) <add> return y-1; <add> return y; <add> } <add> <add> private void updatePosition() <add> { <add> EntityClientPlayerMP player = minecraft.thePlayer; <add> <add> int x = round(player.posX); <add> int y = round(player.posY-player.height); <add> int z = round(player.posZ); <add> <add> moved = (x != xPos || y != yPos || z != zPos); <add> <add> xPos = x; <add> yPos = y; <add> zPos = z; <add> } <add> <add> private Block getBlockUnderPlayer() <add> { <add> World world = minecraft.thePlayer.worldObj; <add> return world.getBlock(xPos, yPos, zPos); <add> } <add> <ide> @SubscribeEvent <ide> public void onPlayerTick(TickEvent.PlayerTickEvent event) <ide> { <ide> onElevator = (b == IndicatorMod.instance.elevatorBlock); <ide> } <ide> <add> // Drawing stuff <ide> @SubscribeEvent <ide> public void onRenderIndicator(RenderGameOverlayEvent.Post event) <ide> { <ide> // Now undo our transformation <ide> GL11.glPopMatrix(); <ide> } <del> <del> private int round(double x) <del> { <del> // Round away from 0 <del> int y = (int) x; <del> if (y < 0) <del> return y-1; <del> return y; <del> } <del> <del> private void updatePosition() <del> { <del> EntityClientPlayerMP player = minecraft.thePlayer; <del> <del> int x = round(player.posX); <del> int y = round(player.posY-player.height); <del> int z = round(player.posZ); <del> <del> moved = (x != xPos || y != yPos || z != zPos); <del> <del> xPos = x; <del> yPos = y; <del> zPos = z; <del> } <del> <del> private Block getBlockUnderPlayer() <del> { <del> World world = minecraft.thePlayer.worldObj; <del> return world.getBlock(xPos, yPos, zPos); <del> } <ide> }
Java
apache-2.0
89d5e8cf0f8e179cab9c0d3dd29a2cd66a339979
0
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.config.model.api; import com.yahoo.config.provision.ApplicationId; import com.yahoo.config.provision.ClusterSpec; import com.yahoo.config.provision.SystemName; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; /** * Represents one endpoint for an application cluster * * @author mortent */ public class ApplicationClusterEndpoint { @Override public String toString() { return "ApplicationClusterEndpoint{" + "dnsName=" + dnsName + ", scope=" + scope + ", routingMethod=" + routingMethod + ", weight=" + weight + ", hostNames=" + hostNames + ", clusterId='" + clusterId + '\'' + '}'; } public enum Scope {application, global, zone} public enum RoutingMethod {shared, sharedLayer4} private final DnsName dnsName; private final Scope scope; private final RoutingMethod routingMethod; private final int weight; private final List<String> hostNames; private final String clusterId; private ApplicationClusterEndpoint(DnsName dnsName, Scope scope, RoutingMethod routingMethod, int weight, List<String> hostNames, String clusterId) { this.dnsName = dnsName; this.scope = scope; this.routingMethod = routingMethod; this.weight = weight; this.hostNames = List.copyOf(hostNames); this.clusterId = clusterId; } public DnsName dnsName() { return dnsName; } public Scope scope() { return scope; } public RoutingMethod routingMethod() { return routingMethod; } public int weight() { return weight; } public List<String> hostNames() { return hostNames; } public String clusterId() { return clusterId; } public static Builder builder() { return new Builder(); } public static class Builder { private DnsName dnsName; private Scope scope; private RoutingMethod routingMethod; private int weigth = 1; private List<String> hosts; private String clusterId; public Builder dnsName(DnsName name) { this.dnsName = name; return this; } public Builder zoneScope() { this.scope = Scope.zone; return this; } public Builder scope(Scope scope) { this.scope = scope; return this; } public Builder sharedRouting() { this.routingMethod = RoutingMethod.shared; return this; } public Builder sharedL4Routing() { this.routingMethod = RoutingMethod.sharedLayer4; return this; } public Builder weight(int weigth) { this.weigth = weigth; return this; } public Builder hosts(List<String> hosts) { this.hosts = List.copyOf(hosts); return this; } public Builder clusterId(String clusterId) { this.clusterId = clusterId; return this; } public ApplicationClusterEndpoint build() { return new ApplicationClusterEndpoint(dnsName, scope, routingMethod, weigth, hosts, clusterId); } } public static class DnsName { private static final int MAX_LABEL_LENGTH = 63; private final String name; private DnsName(String name) { this.name = name; } public String value() { return name; } // TODO: remove when public static DnsName sharedNameFrom(ClusterSpec.Id cluster, ApplicationId applicationId, String suffix) { return sharedNameFrom(SystemName.main, cluster, applicationId, suffix); } public static DnsName sharedNameFrom(SystemName systemName, ClusterSpec.Id cluster, ApplicationId applicationId, String suffix) { String name = dnsParts(systemName, cluster, applicationId) .filter(Objects::nonNull) // remove null values that were "default" .collect(Collectors.joining("--")); return new DnsName(sanitize(name) + suffix); // Need to sanitize name since it is considered one label } // TODO remove this method when 7.508 is latest version public static DnsName sharedL4NameFrom(ClusterSpec.Id cluster, ApplicationId applicationId, String suffix) { return sharedL4NameFrom(SystemName.main, cluster, applicationId, suffix); } public static DnsName sharedL4NameFrom(SystemName systemName, ClusterSpec.Id cluster, ApplicationId applicationId, String suffix) { String name = dnsParts(systemName, cluster, applicationId) .filter(Objects::nonNull) // remove null values that were "default" .map(DnsName::sanitize) .collect(Collectors.joining(".")); return new DnsName(name + suffix); } public static DnsName from(String name) { return new DnsName(name); } private static Stream<String> dnsParts(SystemName systemName, ClusterSpec.Id cluster, ApplicationId applicationId) { return Stream.of( nullIfDefault(cluster.value()), systemPart(systemName), nullIfDefault(applicationId.instance().value()), applicationId.application().value(), applicationId.tenant().value() ); } /** * Remove any invalid characters from the hostnames */ private static String sanitize(String id) { return shortenIfNeeded(id.toLowerCase() .replace('_', '-') .replaceAll("[^a-z0-9-]*", "")); } /** * Truncate the given string at the front so its length does not exceed 63 characters. */ private static String shortenIfNeeded(String id) { return id.substring(Math.max(0, id.length() - MAX_LABEL_LENGTH)); } private static String nullIfDefault(String string) { return Optional.of(string).filter(s -> !s.equals("default")).orElse(null); } private static String systemPart(SystemName systemName) { return "cd".equals(systemName.value()) ? systemName.value() : null; } @Override public String toString() { return "DnsName{" + "name='" + name + '\'' + '}'; } } }
config-model-api/src/main/java/com/yahoo/config/model/api/ApplicationClusterEndpoint.java
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.config.model.api; import com.yahoo.config.provision.ApplicationId; import com.yahoo.config.provision.ClusterSpec; import com.yahoo.config.provision.SystemName; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; /** * Represents one endpoint for an application cluster * * @author mortent */ public class ApplicationClusterEndpoint { @Override public String toString() { return "ApplicationClusterEndpoint{" + "dnsName=" + dnsName + ", scope=" + scope + ", routingMethod=" + routingMethod + ", weight=" + weight + ", hostNames=" + hostNames + ", clusterId='" + clusterId + '\'' + '}'; } public enum Scope {application, global, zone} public enum RoutingMethod {shared, sharedLayer4} private final DnsName dnsName; private final Scope scope; private final RoutingMethod routingMethod; private final int weight; private final List<String> hostNames; private final String clusterId; private ApplicationClusterEndpoint(DnsName dnsName, Scope scope, RoutingMethod routingMethod, int weight, List<String> hostNames, String clusterId) { this.dnsName = dnsName; this.scope = scope; this.routingMethod = routingMethod; this.weight = weight; this.hostNames = List.copyOf(hostNames); this.clusterId = clusterId; } public DnsName dnsName() { return dnsName; } public Scope scope() { return scope; } public RoutingMethod routingMethod() { return routingMethod; } public int weight() { return weight; } public List<String> hostNames() { return hostNames; } public String clusterId() { return clusterId; } public static Builder builder() { return new Builder(); } public static class Builder { private DnsName dnsName; private Scope scope; private RoutingMethod routingMethod; private int weigth = 1; private List<String> hosts; private String clusterId; public Builder dnsName(DnsName name) { this.dnsName = name; return this; } public Builder zoneScope() { this.scope = Scope.zone; return this; } public Builder scope(Scope scope) { this.scope = scope; return this; } public Builder sharedRouting() { this.routingMethod = RoutingMethod.shared; return this; } public Builder sharedL4Routing() { this.routingMethod = RoutingMethod.sharedLayer4; return this; } public Builder weight(int weigth) { this.weigth = weigth; return this; } public Builder hosts(List<String> hosts) { this.hosts = List.copyOf(hosts); return this; } public Builder clusterId(String clusterId) { this.clusterId = clusterId; return this; } public ApplicationClusterEndpoint build() { return new ApplicationClusterEndpoint(dnsName, scope, routingMethod, weigth, hosts, clusterId); } } public static class DnsName { private static final int MAX_LABEL_LENGTH = 63; private final String name; private DnsName(String name) { this.name = name; } public String value() { return name; } // TODO: remove public static DnsName sharedNameFrom(SystemName systemName, ClusterSpec.Id cluster, ApplicationId applicationId, String suffix) { String name = dnsParts(systemName, cluster, applicationId) .filter(Objects::nonNull) // remove null values that were "default" .collect(Collectors.joining("--")); return new DnsName(sanitize(name) + suffix); // Need to sanitize name since it is considered one label } public static DnsName sharedL4NameFrom(SystemName systemName, ClusterSpec.Id cluster, ApplicationId applicationId, String suffix) { String name = dnsParts(systemName, cluster, applicationId) .filter(Objects::nonNull) // remove null values that were "default" .map(DnsName::sanitize) .collect(Collectors.joining(".")); return new DnsName(name + suffix); } public static DnsName from(String name) { return new DnsName(name); } private static Stream<String> dnsParts(SystemName systemName, ClusterSpec.Id cluster, ApplicationId applicationId) { return Stream.of( nullIfDefault(cluster.value()), systemPart(systemName), nullIfDefault(applicationId.instance().value()), applicationId.application().value(), applicationId.tenant().value() ); } /** * Remove any invalid characters from the hostnames */ private static String sanitize(String id) { return shortenIfNeeded(id.toLowerCase() .replace('_', '-') .replaceAll("[^a-z0-9-]*", "")); } /** * Truncate the given string at the front so its length does not exceed 63 characters. */ private static String shortenIfNeeded(String id) { return id.substring(Math.max(0, id.length() - MAX_LABEL_LENGTH)); } private static String nullIfDefault(String string) { return Optional.of(string).filter(s -> !s.equals("default")).orElse(null); } private static String systemPart(SystemName systemName) { return "cd".equals(systemName.value()) ? systemName.value() : null; } @Override public String toString() { return "DnsName{" + "name='" + name + '\'' + '}'; } } }
Reintroduce old methods
config-model-api/src/main/java/com/yahoo/config/model/api/ApplicationClusterEndpoint.java
Reintroduce old methods
<ide><path>onfig-model-api/src/main/java/com/yahoo/config/model/api/ApplicationClusterEndpoint.java <ide> return name; <ide> } <ide> <del> // TODO: remove <add> // TODO: remove when <add> public static DnsName sharedNameFrom(ClusterSpec.Id cluster, ApplicationId applicationId, String suffix) { <add> return sharedNameFrom(SystemName.main, cluster, applicationId, suffix); <add> } <add> <ide> public static DnsName sharedNameFrom(SystemName systemName, ClusterSpec.Id cluster, ApplicationId applicationId, String suffix) { <ide> String name = dnsParts(systemName, cluster, applicationId) <ide> .filter(Objects::nonNull) // remove null values that were "default" <ide> .collect(Collectors.joining("--")); <ide> return new DnsName(sanitize(name) + suffix); // Need to sanitize name since it is considered one label <add> } <add> <add> // TODO remove this method when 7.508 is latest version <add> public static DnsName sharedL4NameFrom(ClusterSpec.Id cluster, ApplicationId applicationId, String suffix) { <add> return sharedL4NameFrom(SystemName.main, cluster, applicationId, suffix); <ide> } <ide> <ide> public static DnsName sharedL4NameFrom(SystemName systemName, ClusterSpec.Id cluster, ApplicationId applicationId, String suffix) {
JavaScript
mit
96700950c776a5bc4075c36d43c1f8dd514f78f8
0
pluggemi/roon-web-controller,pluggemi/roon-web-controller
"use strict"; // Setup general variables var defaultListenPort = 8080; var core, transport; var pairStatus = 0; var zoneStatus = []; var zoneList = []; // Change to working directory try { process.chdir(__dirname); console.log(`Working directory: ${process.cwd()}`); } catch (err) { console.error(`chdir: ${err}`); } // Read command line options var commandLineArgs = require('command-line-args'); var getUsage = require('command-line-usage'); var optionDefinitions = [ { name: 'help', alias: 'h', description: 'Display this usage guide.', type: Boolean }, { name: 'port', alias: 'p', description: 'Specify the port the server listens on.', type: Number } ]; var options = commandLineArgs(optionDefinitions, { partial: true }); var usage = getUsage([ { header: 'Roon Web Controller', content: 'A web based controller for the Roon Music Player.\n\nUsage: [bold]{node app.js <options>}' }, { header: 'Options', optionList: optionDefinitions }, { content: 'Project home: [underline]{https://github.com/pluggemi/roon-web-controller}' } ]); if (options.help) { console.log(usage); process.exit(); } // Read config file var config = require('config'); var configPort = config.get('server.port'); // Determine listen port if (options.port) { var listenPort = options.port; } else if (configPort){ var listenPort = configPort; } else { var listenPort = defaultListenPort; } // Setup Express var express = require('express'); var http = require('http'); var bodyParser = require('body-parser'); var app = express(); app.use(express.static('public')); app.use(bodyParser.json()); app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }); // Setup Socket IO var server = http.createServer(app); var io = require('socket.io').listen(server); server.listen(listenPort, function() { console.log('Listening on port ' + listenPort); }); // Setup Roon var RoonApi = require("node-roon-api"); var RoonApiImage = require("node-roon-api-image"); var RoonApiStatus = require("node-roon-api-status"); var RoonApiTransport = require("node-roon-api-transport"); var RoonApiBrowse = require("node-roon-api-browse"); var roon = new RoonApi({ extension_id: 'com.pluggemi.web.controller', display_name: "Web Controller", display_version: "1.2.1", publisher: 'Mike Plugge', log_level: 'none', email: 'masked', website: 'https://github.com/pluggemi/roon-web-controller', core_paired: function(core_) { core = core_; pairStatus = true; io.emit("pairStatus", JSON.parse('{"pairEnabled": ' + pairStatus + '}')); transport = core_.services.RoonApiTransport; transport.subscribe_zones(function(response, data){ var i, x, y, zone_id, display_name; if (response == "Subscribed") { for ( x in data.zones ) { zone_id = data.zones[x].zone_id; display_name = data.zones[x].display_name; var item = {}; item.zone_id = zone_id; item.display_name = display_name; zoneList.push(item); zoneStatus.push(data.zones[x]); } removeDuplicateList(zoneList, 'zone_id'); removeDuplicateStatus(zoneStatus, 'zone_id'); } else if (response == "Changed") { for ( i in data ){ if (i == "zones_changed") { for (x in data.zones_changed){ for ( y in zoneStatus){ if (zoneStatus[y].zone_id == data.zones_changed[x].zone_id){ zoneStatus[y] = data.zones_changed[x]; } } } io.emit("zoneStatus", zoneStatus); } else if (i == "zones_added") { for ( x in data.zones_added ) { zone_id = data.zones_added[x].zone_id; display_name = data.zones_added[x].display_name; item = {}; item.zone_id = zone_id; item.display_name = display_name; zoneList.push(item); zoneStatus.push(data.zones_added[x]); } removeDuplicateList(zoneList, 'zone_id'); removeDuplicateStatus(zoneStatus, 'zone_id'); } else if (i == "zones_removed") { for (x in data.zones_removed) { zoneList = zoneList.filter(function(zone){ return zone.zone_id != data.zones_removed[x]; }); zoneStatus = zoneStatus.filter(function(zone){ return zone.zone_id != data.zones_removed[x]; }); } removeDuplicateList(zoneList, 'zone_id'); removeDuplicateStatus(zoneStatus, 'zone_id'); } } } }); }, core_unpaired: function(core_) { pairStatus = false; io.emit("pairStatus", JSON.parse('{"pairEnabled": ' + pairStatus + '}')); } }); var svc_status = new RoonApiStatus(roon); roon.init_services({ required_services: [ RoonApiTransport, RoonApiImage, RoonApiBrowse ], provided_services: [ svc_status ] }); svc_status.set_status("Extenstion enabled", false); roon.start_discovery(); // Remove duplicates from zoneList array function removeDuplicateList(array, property) { var x; var new_array = []; var lookup = {}; for (x in array) { lookup[array[x][property]] = array[x]; } for (x in lookup) { new_array.push(lookup[x]); } zoneList = new_array; io.emit("zoneList", zoneList); } // Remove duplicates from zoneStatus array function removeDuplicateStatus(array, property) { var x; var new_array = []; var lookup = {}; for (x in array) { lookup[array[x][property]] = array[x]; } for (x in lookup) { new_array.push(lookup[x]); } zoneStatus = new_array; io.emit("zoneStatus", zoneStatus); } function refresh_browse(zone_id, options, callback) { options = Object.assign({ hierarchy: "browse", zone_or_output_id: zone_id, }, options); core.services.RoonApiBrowse.browse(options, function(error, payload) { if (error) { console.log(error, payload); return;} if (payload.action == "list") { var items = []; if (payload.list.display_offset > 0) { var listoffset = payload.list.display_offset; } else { var listoffset = 0; } core.services.RoonApiBrowse.load({ hierarchy: "browse", offset: listoffset, set_display_offset: listoffset, }, function(error, payload) { callback(payload); }); } }); } function load_browse(listoffset, callback) { core.services.RoonApiBrowse.load({ hierarchy: "browse", offset: listoffset, set_display_offset: listoffset, }, function(error, payload) { callback(payload); }); } // ---------------------------- WEB SOCKET -------------- io.on('connection', function(socket){ io.emit("pairStatus", JSON.parse('{"pairEnabled": ' + pairStatus + '}')); io.emit("zoneList", zoneList); io.emit("zoneStatus", zoneStatus); socket.on('getZone', function(){ io.emit("zoneStatus", zoneStatus); }); socket.on('changeVolume', function(msg) { transport.change_volume(msg.output_id, "absolute", msg.volume); }); socket.on('changeSetting', function(msg) { var settings = []; if (msg.setting == "shuffle") { settings.shuffle = msg.value; } else if (msg.setting == "auto_radio") { settings.auto_radio = msg.value; } else if (msg.setting == "loop") { settings.loop = msg.value; } transport.change_settings(msg.zone_id, settings, function(error){ }); }); socket.on('goPrev', function(msg) { transport.control(msg, 'previous'); }); socket.on('goNext', function(msg) { transport.control(msg, 'next'); }); socket.on('goPlayPause', function(msg) { transport.control(msg, 'playpause'); }); socket.on('goPlay', function(msg) { transport.control(msg, 'play'); }); socket.on('goPause', function(msg) { transport.control(msg, 'pause'); }); socket.on('goStop', function(msg) { transport.control(msg, 'stop'); }); }); // Web Routes app.get('/', function(req, res){ res.sendFile(__dirname + '/public/fullscreen.html'); }); app.get('/roonapi/getImage', function(req, res){ core.services.RoonApiImage.get_image(req.query.image_key, {"scale": "fit", "width": 1000, "height": 1000, "format": "image/jpeg"}, function(cb, contentType, body) { res.contentType = contentType; res.writeHead(200, {'Content-Type': 'image/jpeg' }); res.end(body, 'binary'); }); }); app.post('/roonapi/goRefreshBrowse', function(req, res){ refresh_browse(req.body.zone_id, req.body.options, function(payload){ res.send({"data": payload}); }); }); app.post('/roonapi/goLoadBrowse', function(req, res){ load_browse(req.body.listoffset, function(payload){ res.send({"data": payload}); }); }); app.use('/jquery/jquery.min.js', express.static(__dirname + '/node_modules/jquery/dist/jquery.min.js')); app.use('/js-cookie/js.cookie.js', express.static(__dirname + '/node_modules/js-cookie/src/js.cookie.js'));
app.js
"use strict"; // Setup general variables var defaultListenPort = 8080; var core, transport; var pairStatus = 0; var zoneStatus = []; var zoneList = []; // Read command line options var commandLineArgs = require('command-line-args'); var getUsage = require('command-line-usage'); var optionDefinitions = [ { name: 'help', alias: 'h', description: 'Display this usage guide.', type: Boolean }, { name: 'port', alias: 'p', description: 'Specify the port the server listens on.', type: Number } ]; var options = commandLineArgs(optionDefinitions, { partial: true }); var usage = getUsage([ { header: 'Roon Web Controller', content: 'A web based controller for the Roon Music Player.\n\nUsage: [bold]{node app.js <options>}' }, { header: 'Options', optionList: optionDefinitions }, { content: 'Project home: [underline]{https://github.com/pluggemi/roon-web-controller}' } ]); if (options.help) { console.log(usage); process.exit(); } // Read config file var config = require('config'); var configPort = config.get('server.port'); // Determine listen port if (options.port) { var listenPort = options.port; } else if (configPort){ var listenPort = configPort; } else { var listenPort = defaultListenPort; } // Setup Express var express = require('express'); var http = require('http'); var bodyParser = require('body-parser'); var app = express(); app.use(express.static('public')); app.use(bodyParser.json()); app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }); // Setup Socket IO var server = http.createServer(app); var io = require('socket.io').listen(server); server.listen(listenPort, function() { console.log('Listening on port ' + listenPort); }); // Setup Roon var RoonApi = require("node-roon-api"); var RoonApiImage = require("node-roon-api-image"); var RoonApiStatus = require("node-roon-api-status"); var RoonApiTransport = require("node-roon-api-transport"); var RoonApiBrowse = require("node-roon-api-browse"); var roon = new RoonApi({ extension_id: 'com.pluggemi.web.controller', display_name: "Web Controller", display_version: "1.2.1", publisher: 'Mike Plugge', email: 'masked', website: 'https://github.com/pluggemi/roon-web-controller', core_paired: function(core_) { core = core_; pairStatus = true; io.emit("pairStatus", JSON.parse('{"pairEnabled": ' + pairStatus + '}')); transport = core_.services.RoonApiTransport; transport.subscribe_zones(function(response, data){ var i, x, y, zone_id, display_name; if (response == "Subscribed") { for ( x in data.zones ) { zone_id = data.zones[x].zone_id; display_name = data.zones[x].display_name; var item = {}; item.zone_id = zone_id; item.display_name = display_name; zoneList.push(item); zoneStatus.push(data.zones[x]); } removeDuplicateList(zoneList, 'zone_id'); removeDuplicateStatus(zoneStatus, 'zone_id'); } else if (response == "Changed") { for ( i in data ){ if (i == "zones_changed") { for (x in data.zones_changed){ for ( y in zoneStatus){ if (zoneStatus[y].zone_id == data.zones_changed[x].zone_id){ zoneStatus[y] = data.zones_changed[x]; } } } io.emit("zoneStatus", zoneStatus); } else if (i == "zones_added") { for ( x in data.zones_added ) { zone_id = data.zones_added[x].zone_id; display_name = data.zones_added[x].display_name; item = {}; item.zone_id = zone_id; item.display_name = display_name; zoneList.push(item); zoneStatus.push(data.zones_added[x]); } removeDuplicateList(zoneList, 'zone_id'); removeDuplicateStatus(zoneStatus, 'zone_id'); } else if (i == "zones_removed") { for (x in data.zones_removed) { zoneList = zoneList.filter(function(zone){ return zone.zone_id != data.zones_removed[x]; }); zoneStatus = zoneStatus.filter(function(zone){ return zone.zone_id != data.zones_removed[x]; }); } removeDuplicateList(zoneList, 'zone_id'); removeDuplicateStatus(zoneStatus, 'zone_id'); } } } }); }, core_unpaired: function(core_) { pairStatus = false; io.emit("pairStatus", JSON.parse('{"pairEnabled": ' + pairStatus + '}')); } }); var svc_status = new RoonApiStatus(roon); roon.init_services({ required_services: [ RoonApiTransport, RoonApiImage, RoonApiBrowse ], provided_services: [ svc_status ] }); svc_status.set_status("Extenstion enabled", false); roon.start_discovery(); // Remove duplicates from zoneList array function removeDuplicateList(array, property) { var x; var new_array = []; var lookup = {}; for (x in array) { lookup[array[x][property]] = array[x]; } for (x in lookup) { new_array.push(lookup[x]); } zoneList = new_array; io.emit("zoneList", zoneList); } // Remove duplicates from zoneStatus array function removeDuplicateStatus(array, property) { var x; var new_array = []; var lookup = {}; for (x in array) { lookup[array[x][property]] = array[x]; } for (x in lookup) { new_array.push(lookup[x]); } zoneStatus = new_array; io.emit("zoneStatus", zoneStatus); } function refresh_browse(zone_id, options, callback) { options = Object.assign({ hierarchy: "browse", zone_or_output_id: zone_id, }, options); core.services.RoonApiBrowse.browse(options, function(error, payload) { if (error) { console.log(error, payload); return;} if (payload.action == "list") { var items = []; if (payload.list.display_offset > 0) { var listoffset = payload.list.display_offset; } else { var listoffset = 0; } core.services.RoonApiBrowse.load({ hierarchy: "browse", offset: listoffset, set_display_offset: listoffset, }, function(error, payload) { callback(payload); }); } }); } function load_browse(listoffset, callback) { core.services.RoonApiBrowse.load({ hierarchy: "browse", offset: listoffset, set_display_offset: listoffset, }, function(error, payload) { callback(payload); }); } // ---------------------------- WEB SOCKET -------------- io.on('connection', function(socket){ io.emit("pairStatus", JSON.parse('{"pairEnabled": ' + pairStatus + '}')); io.emit("zoneList", zoneList); io.emit("zoneStatus", zoneStatus); socket.on('getZone', function(){ io.emit("zoneStatus", zoneStatus); }); socket.on('changeVolume', function(msg) { transport.change_volume(msg.output_id, "absolute", msg.volume); }); socket.on('changeSetting', function(msg) { var settings = []; if (msg.setting == "shuffle") { settings.shuffle = msg.value; } else if (msg.setting == "auto_radio") { settings.auto_radio = msg.value; } else if (msg.setting == "loop") { settings.loop = msg.value; } transport.change_settings(msg.zone_id, settings, function(error){ }); }); socket.on('goPrev', function(msg) { transport.control(msg, 'previous'); }); socket.on('goNext', function(msg) { transport.control(msg, 'next'); }); socket.on('goPlayPause', function(msg) { transport.control(msg, 'playpause'); }); socket.on('goPlay', function(msg) { transport.control(msg, 'play'); }); socket.on('goPause', function(msg) { transport.control(msg, 'pause'); }); socket.on('goStop', function(msg) { transport.control(msg, 'stop'); }); }); // Web Routes app.get('/', function(req, res){ res.sendFile(__dirname + '/public/fullscreen.html'); }); app.get('/roonapi/getImage', function(req, res){ core.services.RoonApiImage.get_image(req.query.image_key, {"scale": "fit", "width": 1000, "height": 1000, "format": "image/jpeg"}, function(cb, contentType, body) { res.contentType = contentType; res.writeHead(200, {'Content-Type': 'image/jpeg' }); res.end(body, 'binary'); }); }); app.post('/roonapi/goRefreshBrowse', function(req, res){ refresh_browse(req.body.zone_id, req.body.options, function(payload){ res.send({"data": payload}); }); }); app.post('/roonapi/goLoadBrowse', function(req, res){ load_browse(req.body.listoffset, function(payload){ res.send({"data": payload}); }); }); app.use('/jquery/jquery.min.js', express.static(__dirname + '/node_modules/jquery/dist/jquery.min.js')); app.use('/js-cookie/js.cookie.js', express.static(__dirname + '/node_modules/js-cookie/src/js.cookie.js'));
added support for changing to the working directory - allows the script to be started from any location
app.js
added support for changing to the working directory - allows the script to be started from any location
<ide><path>pp.js <ide> var pairStatus = 0; <ide> var zoneStatus = []; <ide> var zoneList = []; <add> <add>// Change to working directory <add>try { <add> process.chdir(__dirname); <add> console.log(`Working directory: ${process.cwd()}`); <add>} catch (err) { <add> console.error(`chdir: ${err}`); <add>} <ide> <ide> // Read command line options <ide> var commandLineArgs = require('command-line-args'); <ide> } else { <ide> var listenPort = defaultListenPort; <ide> } <del> <ide> // Setup Express <ide> var express = require('express'); <ide> var http = require('http'); <ide> display_name: "Web Controller", <ide> display_version: "1.2.1", <ide> publisher: 'Mike Plugge', <add> log_level: 'none', <ide> email: 'masked', <ide> website: 'https://github.com/pluggemi/roon-web-controller', <ide>
Java
bsd-3-clause
28fffbede56cef049e82068ad8eda0abd78c9ed6
0
NightSwimming/Raptor-Chess,raptor-chess-interface/raptor-chess-interface,raptor-chess/raptor-chess-interface,NightSwimming/Raptor-Chess,NightSwimming/Raptor-Chess,evilwan/raptor-chess-interface,NightSwimming/Raptor-Chess,raptor-chess-interface/raptor-chess-interface,raptor-chess/raptor-chess-interface,raptor-chess/raptor-chess-interface,raptor-chess-interface/raptor-chess-interface,evilwan/raptor-chess-interface,raptor-chess-interface/raptor-chess-interface,raptor-chess/raptor-chess-interface,evilwan/raptor-chess-interface,evilwan/raptor-chess-interface
/** * New BSD License * http://www.opensource.org/licenses/bsd-license.php * Copyright (c) 2009, RaptorProject (http://code.google.com/p/raptor-chess-interface/) * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the RaptorProject nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package raptor.connector.bics; import org.apache.commons.lang.StringUtils; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.preference.PreferenceNode; import org.eclipse.jface.preference.PreferencePage; import raptor.Raptor; import raptor.connector.bics.pref.BicsPage; import raptor.connector.fics.FicsParser; import raptor.connector.ics.IcsConnector; import raptor.connector.ics.IcsConnectorContext; import raptor.connector.ics.dialog.IcsLoginDialog; import raptor.pref.PreferenceKeys; import raptor.service.ThreadService; import raptor.swt.BugButtonsWindowItem; import raptor.util.RaptorStringTokenizer; /** * The connector used to connect to www.freechess.org. */ public class BicsConnector extends IcsConnector implements PreferenceKeys { public static class BicsConnectorContext extends IcsConnectorContext { public BicsConnectorContext() { super(new FicsParser()); } @Override public String getDescription() { return "Bughouse Internet Chess Server"; } @Override public String getEnterPrompt() { return "\":"; } @Override public String getLoggedInMessage() { return "**** Starting BICS session as "; } @Override public String getLoginErrorMessage() { return "\n*** "; } @Override public String getLoginPrompt() { return "login: "; } @Override public String getPasswordPrompt() { return "password:"; } @Override public String getPreferencePrefix() { return "bics-"; } @Override public String getPrompt() { return "fics%"; } @Override public String getRawPrompt() { return "\n" + getPrompt() + " "; } @Override public int getRawPromptLength() { return getRawPrompt().length(); } @Override public String getShortName() { return "bics"; } } /** * Raptor allows connecting to fics twice with different profiles. Override * short name and change it to fics2 so users can distinguish the two. */ protected BicsConnector bics2 = null; protected MenuManager connectionsMenu; protected Action autoConnectAction; protected Action bughouseArenaAction; protected Action connectAction; protected Action disconnectAction; protected Action reconnectAction; protected Action bugbuttonsAction; protected Action isShowingBugButtonsOnConnectAction; public BicsConnector() { this(new BicsConnectorContext()); } public BicsConnector(BicsConnectorContext context) { super(context); ((FicsParser) context.getParser()).setConnector(this); initBics2(); createMenuActions(); } @Override protected void connect(final String profileName) { super.connect(profileName); if (isConnecting) { connectAction.setEnabled(false); autoConnectAction.setChecked(getPreferences().getBoolean( context.getPreferencePrefix() + "auto-connect")); disconnectAction.setEnabled(true); reconnectAction.setEnabled(true); bughouseArenaAction.setEnabled(true); bugbuttonsAction.setEnabled(true); isShowingBugButtonsOnConnectAction.setChecked(getPreferences() .getBoolean( context.getPreferencePrefix() + "show-bugbuttons-on-connect")); if (getPreferences().getBoolean( context.getPreferencePrefix() + "show-bugbuttons-on-connect")) { Raptor.getInstance().getWindow().addRaptorWindowItem( new BugButtonsWindowItem(this)); } } } /** * Creates the connectionsMenu and all of the actions associated with it. */ protected void createMenuActions() { connectionsMenu = new MenuManager("&Bics"); connectAction = new Action("&Connect") { @Override public void run() { IcsLoginDialog dialog = new IcsLoginDialog(context .getPreferencePrefix(), "Bics Login"); dialog.open(); getPreferences().setValue( context.getPreferencePrefix() + "profile", dialog.getSelectedProfile()); autoConnectAction.setChecked(getPreferences().getBoolean( context.getPreferencePrefix() + "auto-connect")); getPreferences().save(); if (dialog.wasLoginPressed()) { connect(); } } }; disconnectAction = new Action("&Disconnect") { @Override public void run() { disconnect(); } }; reconnectAction = new Action("&Reconnect") { @Override public void run() { disconnect(); // Sleep half a second for everything to adjust. try { Thread.sleep(500); } catch (InterruptedException ie) { } connect(currentProfileName); } }; bughouseArenaAction = new Action("Show &Bughouse Arena") { @Override public void run() { Raptor.getInstance().alert("Bughouse Areana Comming soon"); } }; bugbuttonsAction = new Action("Show Bughouse &Buttons") { @Override public void run() { if (!Raptor.getInstance().getWindow().containsBugButtonsItem( BicsConnector.this)) { Raptor.getInstance().getWindow().addRaptorWindowItem( new BugButtonsWindowItem(BicsConnector.this)); } } }; isShowingBugButtonsOnConnectAction = new Action( "Show Bug Buttons On Connect", IAction.AS_CHECK_BOX) { @Override public void run() { getPreferences().setValue( context.getPreferencePrefix() + "show-bugbuttons-on-connect", isChecked()); getPreferences().save(); } }; autoConnectAction = new Action("Auto &Login", IAction.AS_CHECK_BOX) { @Override public void run() { getPreferences().setValue( context.getPreferencePrefix() + "auto-connect", isChecked()); getPreferences().save(); } }; connectAction.setEnabled(true); disconnectAction.setEnabled(false); reconnectAction.setEnabled(false); bughouseArenaAction.setEnabled(false); autoConnectAction.setEnabled(true); bugbuttonsAction.setEnabled(false); isShowingBugButtonsOnConnectAction.setEnabled(true); isShowingBugButtonsOnConnectAction.setChecked(getPreferences() .getBoolean( context.getPreferencePrefix() + "show-bugbuttons-on-connect")); connectionsMenu.add(connectAction); connectionsMenu.add(disconnectAction); connectionsMenu.add(reconnectAction); connectionsMenu.add(autoConnectAction); connectionsMenu.add(isShowingBugButtonsOnConnectAction); connectionsMenu.add(new Separator()); connectionsMenu.add(bugbuttonsAction); connectionsMenu.add(bughouseArenaAction); connectionsMenu.add(new Separator()); MenuManager bics2Menu = new MenuManager( "&Another Simultaneous Connection"); bics2.connectAction = new Action("&Connect") { @Override public void run() { IcsLoginDialog dialog = new IcsLoginDialog(context .getPreferencePrefix(), "Bics Simultaneous Login"); dialog.open(); if (dialog.wasLoginPressed()) { bics2.connect(dialog.getSelectedProfile()); } } }; bics2.disconnectAction = new Action("&Disconnect") { @Override public void run() { bics2.disconnect(); } }; bics2.reconnectAction = new Action("&Reconnect") { @Override public void run() { bics2.disconnect(); // Sleep half a second for everything to adjust. try { Thread.sleep(500); } catch (InterruptedException ie) { } bics2.connect(bics2.currentProfileName); } }; bics2.bughouseArenaAction = new Action("Show &Bughouse Arena") { @Override public void run() { Raptor.getInstance().alert("Bughouse Areana Comming soon"); } }; bics2.autoConnectAction = new Action("Auto &Login", IAction.AS_CHECK_BOX) { @Override public void run() { } }; bics2.bugbuttonsAction = new Action("Show Bughouse &Buttons") { @Override public void run() { if (!Raptor.getInstance().getWindow().containsBugButtonsItem( BicsConnector.this)) { Raptor.getInstance().getWindow().addRaptorWindowItem( new BugButtonsWindowItem(BicsConnector.this)); } } }; bics2.isShowingBugButtonsOnConnectAction = new Action( "Show Bug Buttons On Connect") { @Override public void run() { } }; bics2.connectAction.setEnabled(true); bics2.disconnectAction.setEnabled(false); bics2.reconnectAction.setEnabled(false); bics2.bughouseArenaAction.setEnabled(false); bics2.bugbuttonsAction.setEnabled(false); bics2.isShowingBugButtonsOnConnectAction.setEnabled(true); bics2Menu.add(bics2.connectAction); bics2Menu.add(bics2.disconnectAction); bics2Menu.add(bics2.reconnectAction); bics2Menu.add(new Separator()); bics2Menu.add(bics2.bugbuttonsAction); bics2Menu.add(bics2.bughouseArenaAction); bics2Menu.add(new Separator()); connectionsMenu.add(bics2Menu); } @Override public void disconnect() { super.disconnect(); connectAction.setEnabled(true); disconnectAction.setEnabled(false); reconnectAction.setEnabled(false); bughouseArenaAction.setEnabled(false); autoConnectAction.setEnabled(true); isShowingBugButtonsOnConnectAction.setEnabled(true); bugbuttonsAction.setEnabled(false); } @Override public void dispose() { super.dispose(); if (bics2 != null) { bics2.dispose(); bics2 = null; } } /** * Returns the menu manager for this connector. */ public MenuManager getMenuManager() { return connectionsMenu; } /** * Return the preference node to add to the root preference dialog. This * preference node will show up with the connectors first name. You can add * secondary nodes by implementing getSecondaryPreferenceNodes. These nodes * will show up below the root node. */ public PreferencePage getRootPreferencePage() { return new BicsPage(); } /** * Returns an array of the secondary preference nodes. */ public PreferenceNode[] getSecondaryPreferenceNodes() { return null; } protected void initBics2() { bics2 = new BicsConnector(new BicsConnectorContext() { @Override public String getDescription() { return "Bughouse Internet Chess Server Another Simultaneous Connection"; } @Override public String getShortName() { return "bics2"; } }) { /** * Override not needed. */ @Override protected void createMenuActions() { } /** * Override not needed. */ @Override public PreferencePage getRootPreferencePage() { return null; } /** * Override not needed. */ @Override public PreferenceNode[] getSecondaryPreferenceNodes() { return null; } /** * Override the initFics2 method to do nothing to avoid the * recursion. */ @Override protected void initBics2() { } }; } @Override protected void onSuccessfulLogin() { ThreadService.getInstance().run(new Runnable() { public void run() { isConnecting = false; fireConnected(); sendMessage("iset defprompt 1", true); sendMessage("iset gameinfo 1", true); sendMessage("iset ms 1", true); sendMessage("iset allresults 1", true); sendMessage( "iset premove " + (getPreferences().getBoolean( BOARD_PREMOVE_ENABLED) ? "1" : "0"), true); sendMessage( "iset smartmove " + (getPreferences().getBoolean( BOARD_SMARTMOVE_ENABLED) ? "1" : "0"), true); sendMessage("set interface " + getPreferences().getString(APP_NAME)); sendMessage("set style 12", true); sendMessage("set bell 0", true); String loginScript = getPreferences().getString( BICS_LOGIN_SCRIPT); if (StringUtils.isNotBlank(loginScript)) { RaptorStringTokenizer tok = new RaptorStringTokenizer( loginScript, "\n\r", true); while (tok.hasMoreTokens()) { try { Thread.sleep(50L); } catch (InterruptedException ie) { } sendMessage(tok.nextToken().trim()); } } } }); } }
raptor/src/raptor/connector/bics/BicsConnector.java
/** * New BSD License * http://www.opensource.org/licenses/bsd-license.php * Copyright (c) 2009, RaptorProject (http://code.google.com/p/raptor-chess-interface/) * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the RaptorProject nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package raptor.connector.bics; import org.apache.commons.lang.StringUtils; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.preference.PreferenceNode; import org.eclipse.jface.preference.PreferencePage; import raptor.Raptor; import raptor.connector.bics.pref.BicsPage; import raptor.connector.fics.FicsParser; import raptor.connector.ics.IcsConnector; import raptor.connector.ics.IcsConnectorContext; import raptor.connector.ics.dialog.IcsLoginDialog; import raptor.pref.PreferenceKeys; import raptor.service.ThreadService; import raptor.util.RaptorStringTokenizer; /** * The connector used to connect to www.freechess.org. */ public class BicsConnector extends IcsConnector implements PreferenceKeys { public static class BicsConnectorContext extends IcsConnectorContext { public BicsConnectorContext() { super(new FicsParser()); } @Override public String getDescription() { return "Bughouse Internet Chess Server"; } @Override public String getEnterPrompt() { return "\":"; } @Override public String getLoggedInMessage() { return "**** Starting BICS session as "; } @Override public String getLoginErrorMessage() { return "\n*** "; } @Override public String getLoginPrompt() { return "login: "; } @Override public String getPasswordPrompt() { return "password:"; } @Override public String getPreferencePrefix() { return "bics-"; } @Override public String getPrompt() { return "fics%"; } @Override public String getRawPrompt() { return "\n" + getPrompt() + " "; } @Override public int getRawPromptLength() { return getRawPrompt().length(); } @Override public String getShortName() { return "bics"; } } protected Action autoConnectAction; /** * Raptor allows connecting to fics twice with different profiles. Override * short name and change it to fics2 so users can distinguish the two. */ protected BicsConnector bics2 = null; protected Action bughouseArenaAction; protected Action connectAction; protected MenuManager connectionsMenu; protected Action disconnectAction; protected Action reconnectAction; public BicsConnector() { this(new BicsConnectorContext()); } public BicsConnector(BicsConnectorContext context) { super(context); ((FicsParser) context.getParser()).setConnector(this); initBics2(); createMenuActions(); } @Override protected void connect(final String profileName) { super.connect(profileName); if (isConnecting) { connectAction.setEnabled(false); autoConnectAction.setChecked(getPreferences().getBoolean( context.getPreferencePrefix() + "auto-connect")); disconnectAction.setEnabled(true); reconnectAction.setEnabled(true); bughouseArenaAction.setEnabled(true); } } /** * Creates the connectionsMenu and all of the actions associated with it. */ protected void createMenuActions() { connectionsMenu = new MenuManager("&Bics"); connectAction = new Action("&Connect") { @Override public void run() { IcsLoginDialog dialog = new IcsLoginDialog(context .getPreferencePrefix(), "Bics Login"); dialog.open(); getPreferences().setValue( context.getPreferencePrefix() + "profile", dialog.getSelectedProfile()); autoConnectAction.setChecked(getPreferences().getBoolean( context.getPreferencePrefix() + "auto-connect")); getPreferences().save(); if (dialog.wasLoginPressed()) { connect(); } } }; disconnectAction = new Action("&Disconnect") { @Override public void run() { disconnect(); } }; reconnectAction = new Action("&Reconnect") { @Override public void run() { disconnect(); // Sleep half a second for everything to adjust. try { Thread.sleep(500); } catch (InterruptedException ie) { } connect(currentProfileName); } }; bughouseArenaAction = new Action("Show &Bughouse Arena") { @Override public void run() { Raptor.getInstance().alert("Bughouse Areana Comming soon"); } }; autoConnectAction = new Action("Auto &Login", IAction.AS_CHECK_BOX) { @Override public void run() { getPreferences().setValue( context.getPreferencePrefix() + "auto-connect", isChecked()); getPreferences().save(); } }; connectAction.setEnabled(true); disconnectAction.setEnabled(false); reconnectAction.setEnabled(false); bughouseArenaAction.setEnabled(false); autoConnectAction.setEnabled(true); connectionsMenu.add(connectAction); connectionsMenu.add(disconnectAction); connectionsMenu.add(reconnectAction); connectionsMenu.add(autoConnectAction); connectionsMenu.add(new Separator()); connectionsMenu.add(bughouseArenaAction); connectionsMenu.add(new Separator()); MenuManager bics2Menu = new MenuManager( "&Another Simultaneous Connection"); bics2.connectAction = new Action("&Connect") { @Override public void run() { IcsLoginDialog dialog = new IcsLoginDialog(context .getPreferencePrefix(), "Bics Simultaneous Login"); dialog.open(); if (dialog.wasLoginPressed()) { bics2.connect(dialog.getSelectedProfile()); } } }; bics2.disconnectAction = new Action("&Disconnect") { @Override public void run() { bics2.disconnect(); } }; bics2.reconnectAction = new Action("&Reconnect") { @Override public void run() { bics2.disconnect(); // Sleep half a second for everything to adjust. try { Thread.sleep(500); } catch (InterruptedException ie) { } bics2.connect(bics2.currentProfileName); } }; bics2.bughouseArenaAction = new Action("Show &Bughouse Arena") { @Override public void run() { Raptor.getInstance().alert("Bughouse Areana Comming soon"); } }; bics2.autoConnectAction = new Action("Auto &Login", IAction.AS_CHECK_BOX) { @Override public void run() { } }; bics2.connectAction.setEnabled(true); bics2.disconnectAction.setEnabled(false); bics2.reconnectAction.setEnabled(false); bics2.bughouseArenaAction.setEnabled(false); bics2Menu.add(bics2.connectAction); bics2Menu.add(bics2.disconnectAction); bics2Menu.add(bics2.reconnectAction); bics2Menu.add(new Separator()); bics2Menu.add(bics2.bughouseArenaAction); bics2Menu.add(new Separator()); connectionsMenu.add(bics2Menu); } @Override public void disconnect() { super.disconnect(); connectAction.setEnabled(true); disconnectAction.setEnabled(false); reconnectAction.setEnabled(false); bughouseArenaAction.setEnabled(false); autoConnectAction.setEnabled(true); } @Override public void dispose() { super.dispose(); if (bics2 != null) { bics2.dispose(); bics2 = null; } } /** * Returns the menu manager for this connector. */ public MenuManager getMenuManager() { return connectionsMenu; } /** * Return the preference node to add to the root preference dialog. This * preference node will show up with the connectors first name. You can add * secondary nodes by implementing getSecondaryPreferenceNodes. These nodes * will show up below the root node. */ public PreferencePage getRootPreferencePage() { return new BicsPage(); } /** * Returns an array of the secondary preference nodes. */ public PreferenceNode[] getSecondaryPreferenceNodes() { return null; } protected void initBics2() { bics2 = new BicsConnector(new BicsConnectorContext() { @Override public String getDescription() { return "Bughouse Internet Chess Server Another Simultaneous Connection"; } @Override public String getShortName() { return "bics2"; } }) { /** * Override not needed. */ @Override protected void createMenuActions() { } /** * Override not needed. */ @Override public PreferencePage getRootPreferencePage() { return null; } /** * Override not needed. */ @Override public PreferenceNode[] getSecondaryPreferenceNodes() { return null; } /** * Override the initFics2 method to do nothing to avoid the * recursion. */ @Override protected void initBics2() { } }; } @Override protected void onSuccessfulLogin() { ThreadService.getInstance().run(new Runnable() { public void run() { isConnecting = false; fireConnected(); sendMessage("iset defprompt 1", true); sendMessage("iset gameinfo 1", true); sendMessage("iset ms 1", true); sendMessage("iset allresults 1", true); sendMessage( "iset premove " + (getPreferences().getBoolean( BOARD_PREMOVE_ENABLED) ? "1" : "0"), true); sendMessage( "iset smartmove " + (getPreferences().getBoolean( BOARD_SMARTMOVE_ENABLED) ? "1" : "0"), true); sendMessage("set interface " + getPreferences().getString(APP_NAME)); sendMessage("set style 12", true); sendMessage("set bell 0", true); String loginScript = getPreferences().getString( BICS_LOGIN_SCRIPT); if (StringUtils.isNotBlank(loginScript)) { RaptorStringTokenizer tok = new RaptorStringTokenizer( loginScript, "\n\r", true); while (tok.hasMoreTokens()) { try { Thread.sleep(50L); } catch (InterruptedException ie) { } sendMessage(tok.nextToken().trim()); } } } }); } }
Added bics menu items for bug buttons.
raptor/src/raptor/connector/bics/BicsConnector.java
Added bics menu items for bug buttons.
<ide><path>aptor/src/raptor/connector/bics/BicsConnector.java <ide> import raptor.connector.ics.dialog.IcsLoginDialog; <ide> import raptor.pref.PreferenceKeys; <ide> import raptor.service.ThreadService; <add>import raptor.swt.BugButtonsWindowItem; <ide> import raptor.util.RaptorStringTokenizer; <ide> <ide> /** <ide> } <ide> } <ide> <del> protected Action autoConnectAction; <add> <ide> <ide> /** <ide> * Raptor allows connecting to fics twice with different profiles. Override <ide> * short name and change it to fics2 so users can distinguish the two. <ide> */ <ide> protected BicsConnector bics2 = null; <add> protected MenuManager connectionsMenu; <add> <add> protected Action autoConnectAction; <ide> protected Action bughouseArenaAction; <ide> protected Action connectAction; <del> protected MenuManager connectionsMenu; <ide> protected Action disconnectAction; <del> <ide> protected Action reconnectAction; <add> protected Action bugbuttonsAction; <add> protected Action isShowingBugButtonsOnConnectAction; <ide> <ide> public BicsConnector() { <ide> this(new BicsConnectorContext()); <ide> disconnectAction.setEnabled(true); <ide> reconnectAction.setEnabled(true); <ide> bughouseArenaAction.setEnabled(true); <add> bugbuttonsAction.setEnabled(true); <add> isShowingBugButtonsOnConnectAction.setChecked(getPreferences() <add> .getBoolean( <add> context.getPreferencePrefix() <add> + "show-bugbuttons-on-connect")); <add> <add> if (getPreferences().getBoolean( <add> context.getPreferencePrefix() <add> + "show-bugbuttons-on-connect")) { <add> Raptor.getInstance().getWindow().addRaptorWindowItem( <add> new BugButtonsWindowItem(this)); <add> } <ide> } <ide> } <ide> <ide> Raptor.getInstance().alert("Bughouse Areana Comming soon"); <ide> } <ide> }; <add> <add> bugbuttonsAction = new Action("Show Bughouse &Buttons") { <add> @Override <add> public void run() { <add> if (!Raptor.getInstance().getWindow().containsBugButtonsItem( <add> BicsConnector.this)) { <add> Raptor.getInstance().getWindow().addRaptorWindowItem( <add> new BugButtonsWindowItem(BicsConnector.this)); <add> } <add> } <add> }; <add> <add> isShowingBugButtonsOnConnectAction = new Action( <add> "Show Bug Buttons On Connect", IAction.AS_CHECK_BOX) { <add> @Override <add> public void run() { <add> getPreferences().setValue( <add> context.getPreferencePrefix() <add> + "show-bugbuttons-on-connect", isChecked()); <add> getPreferences().save(); <add> } <add> }; <ide> <ide> autoConnectAction = new Action("Auto &Login", IAction.AS_CHECK_BOX) { <ide> @Override <ide> reconnectAction.setEnabled(false); <ide> bughouseArenaAction.setEnabled(false); <ide> autoConnectAction.setEnabled(true); <del> <add> bugbuttonsAction.setEnabled(false); <add> isShowingBugButtonsOnConnectAction.setEnabled(true); <add> isShowingBugButtonsOnConnectAction.setChecked(getPreferences() <add> .getBoolean( <add> context.getPreferencePrefix() <add> + "show-bugbuttons-on-connect")); <ide> connectionsMenu.add(connectAction); <ide> connectionsMenu.add(disconnectAction); <ide> connectionsMenu.add(reconnectAction); <ide> connectionsMenu.add(autoConnectAction); <add> connectionsMenu.add(isShowingBugButtonsOnConnectAction); <ide> connectionsMenu.add(new Separator()); <add> connectionsMenu.add(bugbuttonsAction); <ide> connectionsMenu.add(bughouseArenaAction); <ide> connectionsMenu.add(new Separator()); <ide> <ide> public void run() { <ide> } <ide> }; <add> <add> bics2.bugbuttonsAction = new Action("Show Bughouse &Buttons") { <add> @Override <add> public void run() { <add> if (!Raptor.getInstance().getWindow().containsBugButtonsItem( <add> BicsConnector.this)) { <add> Raptor.getInstance().getWindow().addRaptorWindowItem( <add> new BugButtonsWindowItem(BicsConnector.this)); <add> } <add> } <add> }; <add> <add> bics2.isShowingBugButtonsOnConnectAction = new Action( <add> "Show Bug Buttons On Connect") { <add> @Override <add> public void run() { <add> } <add> }; <ide> <ide> bics2.connectAction.setEnabled(true); <ide> bics2.disconnectAction.setEnabled(false); <ide> bics2.reconnectAction.setEnabled(false); <ide> bics2.bughouseArenaAction.setEnabled(false); <add> bics2.bugbuttonsAction.setEnabled(false); <add> bics2.isShowingBugButtonsOnConnectAction.setEnabled(true); <ide> <ide> bics2Menu.add(bics2.connectAction); <ide> bics2Menu.add(bics2.disconnectAction); <ide> bics2Menu.add(bics2.reconnectAction); <ide> bics2Menu.add(new Separator()); <add> bics2Menu.add(bics2.bugbuttonsAction); <ide> bics2Menu.add(bics2.bughouseArenaAction); <ide> bics2Menu.add(new Separator()); <ide> <ide> reconnectAction.setEnabled(false); <ide> bughouseArenaAction.setEnabled(false); <ide> autoConnectAction.setEnabled(true); <add> isShowingBugButtonsOnConnectAction.setEnabled(true); <add> bugbuttonsAction.setEnabled(false); <ide> } <ide> <ide> @Override
Java
mit
d0c6151c09b0a54693fbdd466065023d66085623
0
DaFlight/DaFlightCommon,killjoy1221/DaFlightCommon
package me.dags.daflight.utils; import java.lang.reflect.Field; /** * @author dags_ <[email protected]> */ public class FieldAccess<T> { private Field field; private String[] fieldNames; private int attempt = 0; public FieldAccess(Class owner, String[] obfNames) { this.fieldNames = obfNames; this.field = getField(owner); } private Field getField(Class owner) { if (this.attempt >= this.fieldNames.length) return null; Field f; try { f = owner.getDeclaredField(this.fieldNames[this.attempt]); f.setAccessible(true); } catch (NoSuchFieldException e) { this.attempt++; f = getField(owner); } return f; } @SuppressWarnings("unchecked") public T get(Object owner) { try { return (T) field.get(owner); } catch (IllegalAccessException e) { return null; } } public void set(Object owner, T t) { try { field.set(owner, t); } catch (IllegalAccessException e) { e.printStackTrace(); } } }
java/me/dags/daflight/utils/FieldAccess.java
package me.dags.daflight.utils; import java.lang.reflect.Field; /** * @author dags_ <[email protected]> */ public class FieldAccess<T> { private Field field; private String[] fieldNames; private int attempt = 0; public FieldAccess(Object owner, String[] obfNames) { this.fieldNames = obfNames; this.field = getField(owner); } private Field getField(Object owner) { if (this.attempt >= this.fieldNames.length) return null; Field f; try { f = owner.getClass().getDeclaredField(this.fieldNames[this.attempt]); f.setAccessible(true); } catch (NoSuchFieldException e) { this.attempt++; f = getField(owner); } return f; } @SuppressWarnings("unchecked") public T get(Object owner) { try { return (T) field.get(owner); } catch (IllegalAccessException e) { return null; } } public void set(Object owner, T t) { try { field.set(owner, t); } catch (IllegalAccessException e) { e.printStackTrace(); } } }
Accept class instead of object
java/me/dags/daflight/utils/FieldAccess.java
Accept class instead of object
<ide><path>ava/me/dags/daflight/utils/FieldAccess.java <ide> private String[] fieldNames; <ide> private int attempt = 0; <ide> <del> public FieldAccess(Object owner, String[] obfNames) <add> public FieldAccess(Class owner, String[] obfNames) <ide> { <ide> this.fieldNames = obfNames; <ide> this.field = getField(owner); <ide> } <ide> <del> private Field getField(Object owner) <add> private Field getField(Class owner) <ide> { <ide> if (this.attempt >= this.fieldNames.length) <ide> return null; <ide> Field f; <ide> try <ide> { <del> f = owner.getClass().getDeclaredField(this.fieldNames[this.attempt]); <add> f = owner.getDeclaredField(this.fieldNames[this.attempt]); <ide> f.setAccessible(true); <ide> } <ide> catch (NoSuchFieldException e)
Java
apache-2.0
3bdb4996b0391f6e13128bf7f5b4fa9c1ea1ead4
0
real-logic/Agrona,tbrooks8/Agrona
/* * Copyright 2014-2018 Real Logic Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.agrona.collections; import org.agrona.generation.DoNotSub; import java.io.Serializable; import java.util.*; import java.util.function.BiConsumer; import java.util.function.Function; import java.util.function.IntUnaryOperator; import static org.agrona.BitUtil.findNextPositivePowerOfTwo; import static org.agrona.collections.CollectionUtil.validateLoadFactor; /** * A open addressing with linear probing hash map specialised for primitive key and value pairs. */ public class Int2IntHashMap implements Map<Integer, Integer>, Serializable { @DoNotSub static final int MIN_CAPACITY = 8; @DoNotSub private final float loadFactor; private final int missingValue; @DoNotSub private int resizeThreshold; @DoNotSub private int size = 0; @DoNotSub private final boolean shouldCacheIterator; private int[] entries; private KeySet keySet; private Values values; private EntrySet entrySet; public Int2IntHashMap(final int missingValue) { this(MIN_CAPACITY, Hashing.DEFAULT_LOAD_FACTOR, missingValue); } @SuppressWarnings("unchecked") public Int2IntHashMap( @DoNotSub final int initialCapacity, @DoNotSub final float loadFactor, final int missingValue) { this(initialCapacity, loadFactor, missingValue, true); } public Int2IntHashMap( @DoNotSub final int initialCapacity, @DoNotSub final float loadFactor, final int missingValue, final boolean shouldCacheIterator) { validateLoadFactor(loadFactor); this.loadFactor = loadFactor; this.missingValue = missingValue; this.shouldCacheIterator = shouldCacheIterator; capacity(findNextPositivePowerOfTwo(Math.max(MIN_CAPACITY, initialCapacity))); } /** * The value to be used as a null marker in the map. * * @return value to be used as a null marker in the map. */ public int missingValue() { return missingValue; } /** * Get the load factor applied for resize operations. * * @return the load factor applied for resize operations. */ public float loadFactor() { return loadFactor; } /** * Get the actual threshold which when reached the map will resize. * This is a function of the current capacity and load factor. * * @return the threshold when the map will resize. */ @DoNotSub public int resizeThreshold() { return resizeThreshold; } /** * {@inheritDoc} */ @DoNotSub public int size() { return size; } /** * {@inheritDoc} */ public boolean isEmpty() { return size == 0; } public int get(final int key) { final int[] entries = this.entries; final int missingValue = this.missingValue; @DoNotSub final int mask = entries.length - 1; @DoNotSub int index = Hashing.evenHash(key, mask); int value = missingValue; while (entries[index + 1] != missingValue) { if (entries[index] == key) { value = entries[index + 1]; break; } index = next(index, mask); } return value; } /** * Put a key value pair into the map. * * @param key lookup key * @param value new value, must not be initialValue * @return current counter value associated with key, or initialValue if none found * @throws IllegalArgumentException if value is missingValue */ public int put(final int key, final int value) { if (value == missingValue) { throw new IllegalArgumentException("Cannot accept missingValue"); } final int[] entries = this.entries; final int missingValue = this.missingValue; @DoNotSub final int mask = entries.length - 1; @DoNotSub int index = Hashing.evenHash(key, mask); int oldValue = missingValue; while (entries[index + 1] != missingValue) { if (entries[index] == key) { oldValue = entries[index + 1]; break; } index = next(index, mask); } if (oldValue == missingValue) { ++size; entries[index] = key; } entries[index + 1] = value; increaseCapacity(); return oldValue; } private void increaseCapacity() { if (size > resizeThreshold) { // entries.length = 2 * capacity @DoNotSub final int newCapacity = entries.length; rehash(newCapacity); } } private void rehash(@DoNotSub final int newCapacity) { final int[] oldEntries = entries; final int missingValue = this.missingValue; @DoNotSub final int length = entries.length; capacity(newCapacity); for (@DoNotSub int keyIndex = 0; keyIndex < length; keyIndex += 2) { if (oldEntries[keyIndex + 1] != missingValue) { put(oldEntries[keyIndex], oldEntries[keyIndex + 1]); } } } /** * Primitive specialised forEach implementation. * <p> * NB: Renamed from forEach to avoid overloading on parameter types of lambda * expression, which doesn't interplay well with type inference in lambda expressions. * * @param consumer a callback called for each key/value pair in the map. */ public void intForEach(final IntIntConsumer consumer) { final int[] entries = this.entries; final int missingValue = this.missingValue; @DoNotSub final int length = entries.length; for (@DoNotSub int keyIndex = 0; keyIndex < length; keyIndex += 2) { if (entries[keyIndex + 1] != missingValue) { consumer.accept(entries[keyIndex], entries[keyIndex + 1]); } } } /** * Int primitive specialised containsKey. * * @param key the key to check. * @return true if the map contains key as a key, false otherwise. */ public boolean containsKey(final int key) { return get(key) != missingValue; } /** * Does the map contain the value. * * @param value to be tested against contained values. * @return true if contained otherwise value. */ public boolean containsValue(final int value) { boolean found = false; if (value != missingValue) { final int[] entries = this.entries; @DoNotSub final int length = entries.length; for (@DoNotSub int valueIndex = 1; valueIndex < length; valueIndex += 2) { if (value == entries[valueIndex]) { found = true; break; } } } return found; } /** * {@inheritDoc} */ public void clear() { Arrays.fill(entries, missingValue); size = 0; } /** * Compact the backing arrays by rehashing with a capacity just larger than current size * and giving consideration to the load factor. */ public void compact() { @DoNotSub final int idealCapacity = (int)Math.round(size() * (1.0d / loadFactor)); rehash(findNextPositivePowerOfTwo(Math.max(MIN_CAPACITY, idealCapacity))); } /** * Primitive specialised version of {@link #computeIfAbsent(Object, Function)} * * @param key to search on. * @param mappingFunction to provide a value if the get returns null. * @return the value if found otherwise the missing value. */ public int computeIfAbsent(final int key, final IntUnaryOperator mappingFunction) { int value = get(key); if (value == missingValue) { value = mappingFunction.applyAsInt(key); if (value != missingValue) { put(key, value); } } return value; } // ---------------- Boxed Versions Below ---------------- /** * {@inheritDoc} */ public Integer get(final Object key) { final int value = get((int)key); return value == missingValue ? null : value; } /** * {@inheritDoc} */ public Integer put(final Integer key, final Integer value) { final int existingValue = put((int)key, (int)value); return existingValue == missingValue ? null : existingValue; } /** * {@inheritDoc} */ public void forEach(final BiConsumer<? super Integer, ? super Integer> action) { intForEach(action::accept); } /** * {@inheritDoc} */ public boolean containsKey(final Object key) { return containsKey((int)key); } /** * {@inheritDoc} */ public boolean containsValue(final Object value) { return containsValue((int)value); } /** * {@inheritDoc} */ public void putAll(final Map<? extends Integer, ? extends Integer> map) { for (final Map.Entry<? extends Integer, ? extends Integer> entry : map.entrySet()) { put(entry.getKey(), entry.getValue()); } } /** * {@inheritDoc} */ public KeySet keySet() { if (null == keySet) { keySet = new KeySet(); } return keySet; } /** * {@inheritDoc} */ public Values values() { if (null == values) { values = new Values(); } return values; } /** * {@inheritDoc} */ public Set<Entry<Integer, Integer>> entrySet() { if (null == entrySet) { entrySet = new EntrySet(); } return entrySet; } /** * {@inheritDoc} */ public Integer remove(final Object key) { final int value = remove((int)key); return value == missingValue ? null : value; } public int remove(final int key) { final int[] entries = this.entries; final int missingValue = this.missingValue; @DoNotSub final int mask = entries.length - 1; @DoNotSub int keyIndex = Hashing.evenHash(key, mask); int oldValue = missingValue; while (entries[keyIndex + 1] != missingValue) { if (entries[keyIndex] == key) { oldValue = entries[keyIndex + 1]; entries[keyIndex + 1] = missingValue; size--; compactChain(keyIndex); break; } keyIndex = next(keyIndex, mask); } return oldValue; } @SuppressWarnings("FinalParameters") private void compactChain(@DoNotSub int deleteKeyIndex) { final int[] entries = this.entries; final int missingValue = this.missingValue; @DoNotSub final int mask = entries.length - 1; @DoNotSub int keyIndex = deleteKeyIndex; while (true) { keyIndex = next(keyIndex, mask); if (entries[keyIndex + 1] == missingValue) { break; } @DoNotSub final int hash = Hashing.evenHash(entries[keyIndex], mask); if ((keyIndex < hash && (hash <= deleteKeyIndex || deleteKeyIndex <= keyIndex)) || (hash <= deleteKeyIndex && deleteKeyIndex <= keyIndex)) { entries[deleteKeyIndex] = entries[keyIndex]; entries[deleteKeyIndex + 1] = entries[keyIndex + 1]; entries[keyIndex + 1] = missingValue; deleteKeyIndex = keyIndex; } } } /** * Get the minimum value stored in the map. If the map is empty then it will return {@link #missingValue()} * * @return the minimum value stored in the map. */ public int minValue() { final int missingValue = this.missingValue; int min = size == 0 ? missingValue : Integer.MAX_VALUE; final int[] entries = this.entries; @DoNotSub final int length = entries.length; for (@DoNotSub int valueIndex = 1; valueIndex < length; valueIndex += 2) { final int value = entries[valueIndex]; if (value != missingValue) { min = Math.min(min, value); } } return min; } /** * Get the maximum value stored in the map. If the map is empty then it will return {@link #missingValue()} * * @return the maximum value stored in the map. */ public int maxValue() { final int missingValue = this.missingValue; int max = size == 0 ? missingValue : Integer.MIN_VALUE; final int[] entries = this.entries; @DoNotSub final int length = entries.length; for (@DoNotSub int valueIndex = 1; valueIndex < length; valueIndex += 2) { final int value = entries[valueIndex]; if (value != missingValue) { max = Math.max(max, value); } } return max; } /** * {@inheritDoc} */ public String toString() { final StringBuilder sb = new StringBuilder(); sb.append('{'); for (@DoNotSub int i = 1, length = entries.length; i < length; i += 2) { final int value = entries[i]; if (value != missingValue) { sb.append(entries[i - 1]); sb.append('='); sb.append(value); sb.append(", "); } } if (sb.length() > 1) { sb.setLength(sb.length() - 2); } sb.append('}'); return sb.toString(); } /** * Primitive specialised version of {@link #replace(Object, Object)} * * @param key key with which the specified value is associated * @param value value to be associated with the specified key * @return the previous value associated with the specified key, or * {@link #missingValue()} if there was no mapping for the key. */ public int replace(final int key, final int value) { int curValue = get(key); if (curValue != missingValue) { curValue = put(key, value); } return curValue; } /** * Primitive specialised version of {@link #replace(Object, Object, Object)} * * @param key key with which the specified value is associated * @param oldValue value expected to be associated with the specified key * @param newValue value to be associated with the specified key * @return {@code true} if the value was replaced */ public boolean replace(final int key, final int oldValue, final int newValue) { final int curValue = get(key); if (curValue != oldValue || curValue == missingValue) { return false; } put(key, newValue); return true; } /** * {@inheritDoc} */ @SuppressWarnings("unchecked") public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof Map)) { return false; } final Map<Integer, Integer> that = (Map<Integer, Integer>)o; return size == that.size() && entrySet().equals(that.entrySet()); } @DoNotSub public int hashCode() { return entrySet().hashCode(); } @DoNotSub private static int next(final int index, final int mask) { return (index + 2) & mask; } private void capacity(@DoNotSub final int newCapacity) { @DoNotSub final int entriesLength = newCapacity * 2; if (entriesLength < 0) { throw new IllegalStateException("Max capacity reached at size=" + size); } /*@DoNotSub*/ resizeThreshold = (int)(newCapacity * loadFactor); entries = new int[entriesLength]; size = 0; Arrays.fill(entries, missingValue); } // ---------------- Utility Classes ---------------- abstract class AbstractIterator implements Serializable { protected boolean isPositionValid = false; @DoNotSub private int remaining; @DoNotSub private int positionCounter; @DoNotSub private int stopCounter; final void reset() { isPositionValid = false; remaining = Int2IntHashMap.this.size; final int missingValue = Int2IntHashMap.this.missingValue; final int[] entries = Int2IntHashMap.this.entries; @DoNotSub final int capacity = entries.length; @DoNotSub int keyIndex = capacity; if (entries[capacity - 1] != missingValue) { keyIndex = 0; for (@DoNotSub int size = capacity; keyIndex < size; keyIndex += 2) { if (entries[keyIndex + 1] == missingValue) { break; } } } stopCounter = keyIndex; positionCounter = keyIndex + capacity; } @DoNotSub protected final int keyPosition() { return positionCounter & entries.length - 1; } @DoNotSub public int remaining() { return remaining; } public boolean hasNext() { return remaining > 0; } protected final void findNext() { if (!hasNext()) { throw new NoSuchElementException(); } final int[] entries = Int2IntHashMap.this.entries; final int missingValue = Int2IntHashMap.this.missingValue; @DoNotSub final int mask = entries.length - 1; for (@DoNotSub int keyIndex = positionCounter - 2; keyIndex >= stopCounter; keyIndex -= 2) { @DoNotSub final int index = keyIndex & mask; if (entries[index + 1] != missingValue) { isPositionValid = true; positionCounter = keyIndex; --remaining; return; } } isPositionValid = false; throw new IllegalStateException(); } public void remove() { if (isPositionValid) { @DoNotSub final int position = keyPosition(); entries[position + 1] = missingValue; --size; compactChain(position); isPositionValid = false; } else { throw new IllegalStateException(); } } } public final class KeyIterator extends AbstractIterator implements Iterator<Integer> { public Integer next() { return nextValue(); } public int nextValue() { findNext(); return entries[keyPosition()]; } } public final class ValueIterator extends AbstractIterator implements Iterator<Integer> { public Integer next() { return nextValue(); } public int nextValue() { findNext(); return entries[keyPosition() + 1]; } } public final class EntryIterator extends AbstractIterator implements Iterator<Entry<Integer, Integer>>, Entry<Integer, Integer> { public Integer getKey() { return getIntKey(); } public int getIntKey() { return entries[keyPosition()]; } public Integer getValue() { return getIntValue(); } public int getIntValue() { return entries[keyPosition() + 1]; } public Integer setValue(final Integer value) { if (!isPositionValid) { throw new IllegalStateException(); } if (missingValue == value) { throw new IllegalArgumentException(); } @DoNotSub final int keyPosition = keyPosition(); final int prevValue = entries[keyPosition + 1]; entries[keyPosition + 1] = value; return prevValue == missingValue ? null : prevValue; } public Entry<Integer, Integer> next() { findNext(); if (shouldCacheIterator) { return this; } return allocateDuplicateEntry(); } private Entry<Integer, Integer> allocateDuplicateEntry() { final int k = getIntKey(); final int v = getIntValue(); return new Entry<Integer, Integer>() { public Integer getKey() { return k; } public Integer getValue() { return v; } public Integer setValue(final Integer value) { return Int2IntHashMap.this.put(k, value.intValue()); } @DoNotSub public int hashCode() { return Integer.hashCode(getIntKey()) ^ Integer.hashCode(getIntValue()); } @DoNotSub public boolean equals(final Object o) { if (!(o instanceof Entry)) { return false; } final Map.Entry e = (Entry)o; return (e.getKey() != null && e.getValue() != null) && (e.getKey().equals(k) && e.getValue().equals(v)); } public String toString() { return k + "=" + v; } }; } /** * {@inheritDoc} */ @DoNotSub public int hashCode() { return Integer.hashCode(getIntKey()) ^ Integer.hashCode(getIntValue()); } /** * {@inheritDoc} */ public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof Entry)) { return false; } final Entry that = (Entry)o; return Objects.equals(getKey(), that.getKey()) && Objects.equals(getValue(), that.getValue()); } } public final class KeySet extends AbstractSet<Integer> implements Serializable { private final KeyIterator keyIterator = shouldCacheIterator ? new KeyIterator() : null; /** * {@inheritDoc} */ public KeyIterator iterator() { KeyIterator keyIterator = this.keyIterator; if (null == keyIterator) { keyIterator = new KeyIterator(); } keyIterator.reset(); return keyIterator; } /** * {@inheritDoc} */ @DoNotSub public int size() { return Int2IntHashMap.this.size(); } /** * {@inheritDoc} */ public boolean isEmpty() { return Int2IntHashMap.this.isEmpty(); } /** * {@inheritDoc} */ public void clear() { Int2IntHashMap.this.clear(); } /** * {@inheritDoc} */ public boolean contains(final Object o) { return contains((int)o); } public boolean contains(final int key) { return containsKey(key); } } public final class Values extends AbstractCollection<Integer> { private final ValueIterator valueIterator = shouldCacheIterator ? new ValueIterator() : null; /** * {@inheritDoc} */ public ValueIterator iterator() { ValueIterator valueIterator = this.valueIterator; if (null == valueIterator) { valueIterator = new ValueIterator(); } valueIterator.reset(); return valueIterator; } /** * {@inheritDoc} */ @DoNotSub public int size() { return Int2IntHashMap.this.size(); } /** * {@inheritDoc} */ public boolean contains(final Object o) { return contains((int)o); } public boolean contains(final int key) { return containsValue(key); } } private final class EntrySet extends AbstractSet<Entry<Integer, Integer>> implements Serializable { private final EntryIterator entryIterator = shouldCacheIterator ? new EntryIterator() : null; /** * {@inheritDoc} */ public EntryIterator iterator() { EntryIterator entryIterator = this.entryIterator; if (null == entryIterator) { entryIterator = new EntryIterator(); } entryIterator.reset(); return entryIterator; } /** * {@inheritDoc} */ @DoNotSub public int size() { return Int2IntHashMap.this.size(); } /** * {@inheritDoc} */ public boolean isEmpty() { return Int2IntHashMap.this.isEmpty(); } /** * {@inheritDoc} */ public void clear() { Int2IntHashMap.this.clear(); } /** * {@inheritDoc} */ public boolean contains(final Object o) { final Entry entry = (Entry)o; final Integer val = get(entry.getKey()); return val != null && val.equals(entry.getValue()); } } }
agrona/src/main/java/org/agrona/collections/Int2IntHashMap.java
/* * Copyright 2014-2018 Real Logic Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.agrona.collections; import org.agrona.generation.DoNotSub; import java.io.Serializable; import java.util.*; import java.util.function.BiConsumer; import java.util.function.Function; import java.util.function.IntUnaryOperator; import static org.agrona.BitUtil.findNextPositivePowerOfTwo; import static org.agrona.collections.CollectionUtil.validateLoadFactor; /** * A open addressing with linear probing hash map specialised for primitive key and value pairs. */ public class Int2IntHashMap implements Map<Integer, Integer>, Serializable { @DoNotSub static final int MIN_CAPACITY = 8; @DoNotSub private final float loadFactor; private final int missingValue; @DoNotSub private int resizeThreshold; @DoNotSub private int size = 0; @DoNotSub private final boolean shouldCacheIterator; private int[] entries; private KeySet keySet; private Values values; private EntrySet entrySet; public Int2IntHashMap(final int missingValue) { this(MIN_CAPACITY, Hashing.DEFAULT_LOAD_FACTOR, missingValue); } @SuppressWarnings("unchecked") public Int2IntHashMap( @DoNotSub final int initialCapacity, @DoNotSub final float loadFactor, final int missingValue) { this(initialCapacity, loadFactor, missingValue, true); } public Int2IntHashMap( @DoNotSub final int initialCapacity, @DoNotSub final float loadFactor, final int missingValue, final boolean shouldCacheIterator) { validateLoadFactor(loadFactor); this.loadFactor = loadFactor; this.missingValue = missingValue; this.shouldCacheIterator = shouldCacheIterator; capacity(findNextPositivePowerOfTwo(Math.max(MIN_CAPACITY, initialCapacity))); } /** * The value to be used as a null marker in the map. * * @return value to be used as a null marker in the map. */ public int missingValue() { return missingValue; } /** * Get the load factor applied for resize operations. * * @return the load factor applied for resize operations. */ public float loadFactor() { return loadFactor; } /** * Get the actual threshold which when reached the map will resize. * This is a function of the current capacity and load factor. * * @return the threshold when the map will resize. */ @DoNotSub public int resizeThreshold() { return resizeThreshold; } /** * {@inheritDoc} */ @DoNotSub public int size() { return size; } /** * {@inheritDoc} */ public boolean isEmpty() { return size == 0; } public int get(final int key) { final int[] entries = this.entries; final int missingValue = this.missingValue; @DoNotSub final int mask = entries.length - 1; @DoNotSub int index = Hashing.evenHash(key, mask); int value = missingValue; while (entries[index + 1] != missingValue) { if (entries[index] == key) { value = entries[index + 1]; break; } index = next(index, mask); } return value; } /** * Put a key value pair into the map. * * @param key lookup key * @param value new value, must not be initialValue * @return current counter value associated with key, or initialValue if none found * @throws IllegalArgumentException if value is missingValue */ public int put(final int key, final int value) { if (value == missingValue) { throw new IllegalArgumentException("Cannot accept missingValue"); } final int[] entries = this.entries; final int missingValue = this.missingValue; @DoNotSub final int mask = entries.length - 1; @DoNotSub int index = Hashing.evenHash(key, mask); int oldValue = missingValue; while (entries[index + 1] != missingValue) { if (entries[index] == key) { oldValue = entries[index + 1]; break; } index = next(index, mask); } if (oldValue == missingValue) { ++size; entries[index] = key; } entries[index + 1] = value; increaseCapacity(); return oldValue; } private void increaseCapacity() { if (size > resizeThreshold) { // entries.length = 2 * capacity @DoNotSub final int newCapacity = entries.length; rehash(newCapacity); } } private void rehash(@DoNotSub final int newCapacity) { final int[] oldEntries = entries; final int missingValue = this.missingValue; @DoNotSub final int length = entries.length; capacity(newCapacity); for (@DoNotSub int keyIndex = 0; keyIndex < length; keyIndex += 2) { if (oldEntries[keyIndex + 1] != missingValue) { put(oldEntries[keyIndex], oldEntries[keyIndex + 1]); } } } /** * Primitive specialised forEach implementation. * <p> * NB: Renamed from forEach to avoid overloading on parameter types of lambda * expression, which doesn't interplay well with type inference in lambda expressions. * * @param consumer a callback called for each key/value pair in the map. */ public void intForEach(final IntIntConsumer consumer) { final int[] entries = this.entries; final int missingValue = this.missingValue; @DoNotSub final int length = entries.length; for (@DoNotSub int keyIndex = 0; keyIndex < length; keyIndex += 2) { if (entries[keyIndex + 1] != missingValue) { consumer.accept(entries[keyIndex], entries[keyIndex + 1]); } } } /** * Int primitive specialised containsKey. * * @param key the key to check. * @return true if the map contains key as a key, false otherwise. */ public boolean containsKey(final int key) { return get(key) != missingValue; } /** * Does the map contain the value. * * @param value to be tested against contained values. * @return true if contained otherwise value. */ public boolean containsValue(final int value) { boolean found = false; if (value != missingValue) { final int[] entries = this.entries; @DoNotSub final int length = entries.length; for (@DoNotSub int valueIndex = 1; valueIndex < length; valueIndex += 2) { if (value == entries[valueIndex]) { found = true; break; } } } return found; } /** * {@inheritDoc} */ public void clear() { Arrays.fill(entries, missingValue); size = 0; } /** * Compact the backing arrays by rehashing with a capacity just larger than current size * and giving consideration to the load factor. */ public void compact() { @DoNotSub final int idealCapacity = (int)Math.round(size() * (1.0d / loadFactor)); rehash(findNextPositivePowerOfTwo(Math.max(MIN_CAPACITY, idealCapacity))); } /** * Primitive specialised version of {@link #computeIfAbsent(Object, Function)} * * @param key to search on. * @param mappingFunction to provide a value if the get returns null. * @return the value if found otherwise the missing value. */ public int computeIfAbsent(final int key, final IntUnaryOperator mappingFunction) { int value = get(key); if (value == missingValue) { value = mappingFunction.applyAsInt(key); if (value != missingValue) { put(key, value); } } return value; } // ---------------- Boxed Versions Below ---------------- /** * {@inheritDoc} */ public Integer get(final Object key) { final int value = get((int)key); return value == missingValue ? null : value; } /** * {@inheritDoc} */ public Integer put(final Integer key, final Integer value) { final int existingValue = put((int)key, (int)value); return existingValue == missingValue ? null : existingValue; } /** * {@inheritDoc} */ public void forEach(final BiConsumer<? super Integer, ? super Integer> action) { intForEach(action::accept); } /** * {@inheritDoc} */ public boolean containsKey(final Object key) { return containsKey((int)key); } /** * {@inheritDoc} */ public boolean containsValue(final Object value) { return containsValue((int)value); } /** * {@inheritDoc} */ public void putAll(final Map<? extends Integer, ? extends Integer> map) { for (final Map.Entry<? extends Integer, ? extends Integer> entry : map.entrySet()) { put(entry.getKey(), entry.getValue()); } } /** * {@inheritDoc} */ public KeySet keySet() { if (null == keySet) { keySet = new KeySet(); } return keySet; } /** * {@inheritDoc} */ public Values values() { if (null == values) { values = new Values(); } return values; } /** * {@inheritDoc} */ public Set<Entry<Integer, Integer>> entrySet() { if (null == entrySet) { entrySet = new EntrySet(); } return entrySet; } /** * {@inheritDoc} */ public Integer remove(final Object key) { final int value = remove((int)key); return value == missingValue ? null : value; } public int remove(final int key) { final int[] entries = this.entries; final int missingValue = this.missingValue; @DoNotSub final int mask = entries.length - 1; @DoNotSub int keyIndex = Hashing.evenHash(key, mask); int oldValue = missingValue; while (entries[keyIndex + 1] != missingValue) { if (entries[keyIndex] == key) { oldValue = entries[keyIndex + 1]; entries[keyIndex + 1] = missingValue; size--; compactChain(keyIndex); break; } keyIndex = next(keyIndex, mask); } return oldValue; } @SuppressWarnings("FinalParameters") private void compactChain(@DoNotSub int deleteKeyIndex) { final int[] entries = this.entries; final int missingValue = this.missingValue; @DoNotSub final int mask = entries.length - 1; @DoNotSub int keyIndex = deleteKeyIndex; while (true) { keyIndex = next(keyIndex, mask); if (entries[keyIndex + 1] == missingValue) { break; } @DoNotSub final int hash = Hashing.evenHash(entries[keyIndex], mask); if ((keyIndex < hash && (hash <= deleteKeyIndex || deleteKeyIndex <= keyIndex)) || (hash <= deleteKeyIndex && deleteKeyIndex <= keyIndex)) { entries[deleteKeyIndex] = entries[keyIndex]; entries[deleteKeyIndex + 1] = entries[keyIndex + 1]; entries[keyIndex + 1] = missingValue; deleteKeyIndex = keyIndex; } } } /** * Get the minimum value stored in the map. If the map is empty then it will return {@link #missingValue()} * * @return the minimum value stored in the map. */ public int minValue() { final int missingValue = this.missingValue; int min = size == 0 ? missingValue : Integer.MAX_VALUE; final int[] entries = this.entries; @DoNotSub final int length = entries.length; for (@DoNotSub int valueIndex = 1; valueIndex < length; valueIndex += 2) { final int value = entries[valueIndex]; if (value != missingValue) { min = Math.min(min, value); } } return min; } /** * Get the maximum value stored in the map. If the map is empty then it will return {@link #missingValue()} * * @return the maximum value stored in the map. */ public int maxValue() { final int missingValue = this.missingValue; int max = size == 0 ? missingValue : Integer.MIN_VALUE; final int[] entries = this.entries; @DoNotSub final int length = entries.length; for (@DoNotSub int valueIndex = 1; valueIndex < length; valueIndex += 2) { final int value = entries[valueIndex]; if (value != missingValue) { max = Math.max(max, value); } } return max; } /** * {@inheritDoc} */ public String toString() { if (isEmpty()) { return "{}"; } final EntryIterator entryIterator = (EntryIterator)entrySet().iterator(); final StringBuilder sb = new StringBuilder().append('{'); while (true) { entryIterator.next(); sb.append(entryIterator.getIntKey()).append('=').append(entryIterator.getIntValue()); if (!entryIterator.hasNext()) { return sb.append('}').toString(); } sb.append(',').append(' '); } } /** * Primitive specialised version of {@link #replace(Object, Object)} * * @param key key with which the specified value is associated * @param value value to be associated with the specified key * @return the previous value associated with the specified key, or * {@link #missingValue()} if there was no mapping for the key. */ public int replace(final int key, final int value) { int curValue = get(key); if (curValue != missingValue) { curValue = put(key, value); } return curValue; } /** * Primitive specialised version of {@link #replace(Object, Object, Object)} * * @param key key with which the specified value is associated * @param oldValue value expected to be associated with the specified key * @param newValue value to be associated with the specified key * @return {@code true} if the value was replaced */ public boolean replace(final int key, final int oldValue, final int newValue) { final int curValue = get(key); if (curValue != oldValue || curValue == missingValue) { return false; } put(key, newValue); return true; } /** * {@inheritDoc} */ @SuppressWarnings("unchecked") public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof Map)) { return false; } final Map<Integer, Integer> that = (Map<Integer, Integer>)o; return size == that.size() && entrySet().equals(that.entrySet()); } @DoNotSub public int hashCode() { return entrySet().hashCode(); } @DoNotSub private static int next(final int index, final int mask) { return (index + 2) & mask; } private void capacity(@DoNotSub final int newCapacity) { @DoNotSub final int entriesLength = newCapacity * 2; if (entriesLength < 0) { throw new IllegalStateException("Max capacity reached at size=" + size); } /*@DoNotSub*/ resizeThreshold = (int)(newCapacity * loadFactor); entries = new int[entriesLength]; size = 0; Arrays.fill(entries, missingValue); } // ---------------- Utility Classes ---------------- abstract class AbstractIterator implements Serializable { protected boolean isPositionValid = false; @DoNotSub private int remaining; @DoNotSub private int positionCounter; @DoNotSub private int stopCounter; final void reset() { isPositionValid = false; remaining = Int2IntHashMap.this.size; final int missingValue = Int2IntHashMap.this.missingValue; final int[] entries = Int2IntHashMap.this.entries; @DoNotSub final int capacity = entries.length; @DoNotSub int keyIndex = capacity; if (entries[capacity - 1] != missingValue) { keyIndex = 0; for (@DoNotSub int size = capacity; keyIndex < size; keyIndex += 2) { if (entries[keyIndex + 1] == missingValue) { break; } } } stopCounter = keyIndex; positionCounter = keyIndex + capacity; } @DoNotSub protected final int keyPosition() { return positionCounter & entries.length - 1; } @DoNotSub public int remaining() { return remaining; } public boolean hasNext() { return remaining > 0; } protected final void findNext() { if (!hasNext()) { throw new NoSuchElementException(); } final int[] entries = Int2IntHashMap.this.entries; final int missingValue = Int2IntHashMap.this.missingValue; @DoNotSub final int mask = entries.length - 1; for (@DoNotSub int keyIndex = positionCounter - 2; keyIndex >= stopCounter; keyIndex -= 2) { @DoNotSub final int index = keyIndex & mask; if (entries[index + 1] != missingValue) { isPositionValid = true; positionCounter = keyIndex; --remaining; return; } } isPositionValid = false; throw new IllegalStateException(); } public void remove() { if (isPositionValid) { @DoNotSub final int position = keyPosition(); entries[position + 1] = missingValue; --size; compactChain(position); isPositionValid = false; } else { throw new IllegalStateException(); } } } public final class KeyIterator extends AbstractIterator implements Iterator<Integer> { public Integer next() { return nextValue(); } public int nextValue() { findNext(); return entries[keyPosition()]; } } public final class ValueIterator extends AbstractIterator implements Iterator<Integer> { public Integer next() { return nextValue(); } public int nextValue() { findNext(); return entries[keyPosition() + 1]; } } public final class EntryIterator extends AbstractIterator implements Iterator<Entry<Integer, Integer>>, Entry<Integer, Integer> { public Integer getKey() { return getIntKey(); } public int getIntKey() { return entries[keyPosition()]; } public Integer getValue() { return getIntValue(); } public int getIntValue() { return entries[keyPosition() + 1]; } public Integer setValue(final Integer value) { if (!isPositionValid) { throw new IllegalStateException(); } if (missingValue == value) { throw new IllegalArgumentException(); } @DoNotSub final int keyPosition = keyPosition(); final int prevValue = entries[keyPosition + 1]; entries[keyPosition + 1] = value; return prevValue == missingValue ? null : prevValue; } public Entry<Integer, Integer> next() { findNext(); if (shouldCacheIterator) { return this; } return allocateDuplicateEntry(); } private Entry<Integer, Integer> allocateDuplicateEntry() { final int k = getIntKey(); final int v = getIntValue(); return new Entry<Integer, Integer>() { public Integer getKey() { return k; } public Integer getValue() { return v; } public Integer setValue(final Integer value) { return Int2IntHashMap.this.put(k, value.intValue()); } @DoNotSub public int hashCode() { return Integer.hashCode(getIntKey()) ^ Integer.hashCode(getIntValue()); } @DoNotSub public boolean equals(final Object o) { if (!(o instanceof Entry)) { return false; } final Map.Entry e = (Entry)o; return (e.getKey() != null && e.getValue() != null) && (e.getKey().equals(k) && e.getValue().equals(v)); } public String toString() { return k + "=" + v; } }; } /** * {@inheritDoc} */ @DoNotSub public int hashCode() { return Integer.hashCode(getIntKey()) ^ Integer.hashCode(getIntValue()); } /** * {@inheritDoc} */ public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof Entry)) { return false; } final Entry that = (Entry)o; return Objects.equals(getKey(), that.getKey()) && Objects.equals(getValue(), that.getValue()); } } public final class KeySet extends AbstractSet<Integer> implements Serializable { private final KeyIterator keyIterator = shouldCacheIterator ? new KeyIterator() : null; /** * {@inheritDoc} */ public KeyIterator iterator() { KeyIterator keyIterator = this.keyIterator; if (null == keyIterator) { keyIterator = new KeyIterator(); } keyIterator.reset(); return keyIterator; } /** * {@inheritDoc} */ @DoNotSub public int size() { return Int2IntHashMap.this.size(); } /** * {@inheritDoc} */ public boolean isEmpty() { return Int2IntHashMap.this.isEmpty(); } /** * {@inheritDoc} */ public void clear() { Int2IntHashMap.this.clear(); } /** * {@inheritDoc} */ public boolean contains(final Object o) { return contains((int)o); } public boolean contains(final int key) { return containsKey(key); } } public final class Values extends AbstractCollection<Integer> { private final ValueIterator valueIterator = shouldCacheIterator ? new ValueIterator() : null; /** * {@inheritDoc} */ public ValueIterator iterator() { ValueIterator valueIterator = this.valueIterator; if (null == valueIterator) { valueIterator = new ValueIterator(); } valueIterator.reset(); return valueIterator; } /** * {@inheritDoc} */ @DoNotSub public int size() { return Int2IntHashMap.this.size(); } /** * {@inheritDoc} */ public boolean contains(final Object o) { return contains((int)o); } public boolean contains(final int key) { return containsValue(key); } } private final class EntrySet extends AbstractSet<Entry<Integer, Integer>> implements Serializable { private final EntryIterator entryIterator = shouldCacheIterator ? new EntryIterator() : null; /** * {@inheritDoc} */ public EntryIterator iterator() { EntryIterator entryIterator = this.entryIterator; if (null == entryIterator) { entryIterator = new EntryIterator(); } entryIterator.reset(); return entryIterator; } /** * {@inheritDoc} */ @DoNotSub public int size() { return Int2IntHashMap.this.size(); } /** * {@inheritDoc} */ public boolean isEmpty() { return Int2IntHashMap.this.isEmpty(); } /** * {@inheritDoc} */ public void clear() { Int2IntHashMap.this.clear(); } /** * {@inheritDoc} */ public boolean contains(final Object o) { final Entry entry = (Entry)o; final Integer val = get(entry.getKey()); return val != null && val.equals(entry.getValue()); } } }
[Java] Don't use iterator in toString() as it maybe cached and in use.
agrona/src/main/java/org/agrona/collections/Int2IntHashMap.java
[Java] Don't use iterator in toString() as it maybe cached and in use.
<ide><path>grona/src/main/java/org/agrona/collections/Int2IntHashMap.java <ide> */ <ide> public String toString() <ide> { <del> if (isEmpty()) <del> { <del> return "{}"; <del> } <del> <del> final EntryIterator entryIterator = (EntryIterator)entrySet().iterator(); <del> <del> final StringBuilder sb = new StringBuilder().append('{'); <del> while (true) <del> { <del> entryIterator.next(); <del> sb.append(entryIterator.getIntKey()).append('=').append(entryIterator.getIntValue()); <del> if (!entryIterator.hasNext()) <del> { <del> return sb.append('}').toString(); <del> } <del> sb.append(',').append(' '); <del> } <add> final StringBuilder sb = new StringBuilder(); <add> sb.append('{'); <add> <add> for (@DoNotSub int i = 1, length = entries.length; i < length; i += 2) <add> { <add> final int value = entries[i]; <add> if (value != missingValue) <add> { <add> sb.append(entries[i - 1]); <add> sb.append('='); <add> sb.append(value); <add> sb.append(", "); <add> } <add> } <add> <add> if (sb.length() > 1) <add> { <add> sb.setLength(sb.length() - 2); <add> } <add> <add> sb.append('}'); <add> <add> return sb.toString(); <ide> } <ide> <ide> /**
Java
mit
4da74fd5d5e07b5acce10665717edd5416ac3ea7
0
JamesDeCarlo/Chat-Client-Server
package com.cst242.finalproject.server.model; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; /** * This class implements the {@code FileIOInterface} refer to that for * documentation. * * @author James DeCarlo */ public class FileIO implements FileIOInterface { BufferedReader reader; PrintWriter writer; int accountNumber; @Override public boolean register(String loginId, int hashedPassword, String firstName, String lastName, String screenName) { File file = new File("userlist.dat"); if (!file.exists()) { try { file.createNewFile(); } catch (IOException ex) { return false; } } if (file.length() == 0) { try { writer = new PrintWriter(file); accountNumber = 1001; User user = new User(accountNumber, loginId, hashedPassword, firstName, lastName, screenName); //Writing the User object to the file. writer.println(user.toString()); writer.close(); } catch (IOException e) { return false; } } else { try { reader = new BufferedReader(new FileReader(file)); } catch (IOException e) { return false; } List<User> users = new ArrayList<>(); String line = ""; try { while ((line = reader.readLine()) != null) { if (!line.equals("")) { User u = new User(line.trim()); users.add(u); } } reader.close(); } catch (IOException ex) { return false; } // check if login id is unique and find max account number index accountNumber = 1000; for (User u : users) { if (u.getAccountNumber() > accountNumber) { accountNumber = u.getAccountNumber(); } if (u.getLoginId().toLowerCase().equals(loginId.toLowerCase())) { return false; } } // all went well create user and add to list array accountNumber++; User user = new User(accountNumber, loginId, hashedPassword, firstName, lastName, screenName); users.add(user); try { writer = new PrintWriter(file); } catch (FileNotFoundException ex) { return false; } for (User u : users) { writer.append(u.toString()); writer.flush(); } writer.close(); } return true; } @Override public User loginUser(String loginId, int hashedPassword ) { User user = new User(1001, "JohnDoe", 6969, "John", "Doe", "SomeGuy"); return user; } @Override public boolean updateUser(int accountNumber, int hashedPassword, String firstName, String lastName, String screenName ) { return false; } }
Chat-Client-Server/src/com/cst242/finalproject/server/model/FileIO.java
package com.cst242.finalproject.server.model; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * This class implements the {@code FileIOInterface} refer to that for * documentation. * * @author James DeCarlo */ public class FileIO implements FileIOInterface { BufferedReader reader; PrintWriter writer; int accountNumber; @Override public boolean register(String loginId, int hashedPassword, String firstName, String lastName, String screenName) { File file = new File("userlist.dat"); if (!file.exists()) { try { file.createNewFile(); } catch (IOException ex) { return false; } } if (file.length() == 0) { try { writer = new PrintWriter(file); accountNumber = 1001; User user = new User(accountNumber, loginId, hashedPassword, firstName, lastName, screenName); //Writing the User object to the file. writer.println(user.toString()); writer.close(); } catch (IOException e) { return false; } } else { try { reader = new BufferedReader(new FileReader(file)); } catch (IOException e) { return false; } List<User> users = new ArrayList<>(); String line = ""; try { while ((line = reader.readLine()) != null) { if (!line.equals("")) { User u = new User(line.trim()); users.add(u); } } reader.close(); } catch (IOException ex) { return false; } // check if login id is unique and find max account number index accountNumber = 1000; for (User u : users) { if (u.getAccountNumber() > accountNumber) { accountNumber = u.getAccountNumber(); } if (u.getLoginId().toLowerCase().equals(loginId.toLowerCase())) { return false; } } // all went well create user and add to list array accountNumber++; User user = new User(accountNumber, loginId, hashedPassword, firstName, lastName, screenName); users.add(user); try { writer = new PrintWriter(file); } catch (FileNotFoundException ex) { return false; } for (User u : users) { writer.append(u.toString()); writer.flush(); } writer.close(); } return true; } @Override public User loginUser(String loginId, int hashedPassword ) { User user = new User(1001, "JohnDoe", 6969, "John", "Doe", "SomeGuy"); return user; } @Override public boolean updateUser(int accountNumber, int hashedPassword, String firstName, String lastName, String screenName ) { return false; } }
unused imports cleaned up
Chat-Client-Server/src/com/cst242/finalproject/server/model/FileIO.java
unused imports cleaned up
<ide><path>hat-Client-Server/src/com/cst242/finalproject/server/model/FileIO.java <ide> package com.cst242.finalproject.server.model; <ide> <ide> import java.io.BufferedReader; <del>import java.io.BufferedWriter; <ide> import java.io.File; <del>import java.io.FileInputStream; <ide> import java.io.FileNotFoundException; <del>import java.io.FileOutputStream; <ide> import java.io.FileReader; <del>import java.io.FileWriter; <ide> import java.io.IOException; <del>import java.io.InputStreamReader; <ide> import java.io.PrintWriter; <ide> import java.util.ArrayList; <ide> import java.util.List; <del>import java.util.logging.Level; <del>import java.util.logging.Logger; <ide> <ide> /** <ide> * This class implements the {@code FileIOInterface} refer to that for
JavaScript
mit
dba93ca3b6f590d4b97457cd9b9e4b18eea4c12b
0
nugget/sync,aykl/sync,jasonbio/tubesynch,Poniverse/Equestria.tv,gv1222/sync,bush6/sync,6IRCNet/sync,bush6/sync,jasonbio/tubesynch,pajlada/sync,pajlada/sync,pajlada/sync,gv1222/sync,6IRCNet/sync,aykl/sync,6IRCNet/sync,Poniverse/Equestria.tv,jasonbio/tubesynch,nugget/sync,pajlada/sync,bush6/sync,jasonbio/tubesynch,gv1222/sync,gv1222/sync,nugget/sync,Poniverse/Equestria.tv
/* The MIT License (MIT) Copyright (c) 2013 Calvin Montgomery Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ var CL_VERSION = "2.0.0"; var CLIENT = { rank: -1, leader: false, name: "", logged_in: false, profile: { image: "", text: "" } }; var SUPERADMIN = false; var CHANNEL = { opts: {}, openqueue: false, perms: {}, css: "", js: "", motd: "", motd_text: "", name: false }; var PLAYER = false; var VIDEOQUALITY = false; var FLUIDLAYOUT = false; var VWIDTH; var VHEIGHT; if($("#videowidth").length > 0) { VWIDTH = $("#videowidth").css("width").replace("px", ""); VHEIGHT = ""+parseInt(parseInt(VWIDTH) * 9 / 16); } var MEDIA = { hash: "" }; var PL_MOVING = false; var PL_ADDING = false; var PL_DELETING = false; var REBUILDING = false; var socket = { emit: function() { console.log("socket not initialized"); console.log(arguments); } }; var IGNORED = []; var CHATHIST = []; var CHATHISTIDX = 0; var SCROLLCHAT = true; var LASTCHATNAME = ""; var LASTCHATTIME = 0; var FOCUSED = true; var PAGETITLE = "CyTube"; var TITLE_BLINK; var KICKED = false; var NAME = readCookie("cytube_uname"); var SESSION = readCookie("cytube_session"); var LEADTMR = false; var PL_FROM = ""; var PL_AFTER = ""; var PL_WAIT_SCROLL = false; var FILTER_FROM = 0; var FILTER_TO = 0; var NO_STORAGE = typeof localStorage == "undefined" || localStorage === null; function getOpt(k) { return NO_STORAGE ? readCookie(k) : localStorage.getItem(k); } function setOpt(k, v) { NO_STORAGE ? createCookie(k, v, 1000) : localStorage.setItem(k, v); } function getOrDefault(k, def) { var v = getOpt(k); if(v === null) return def; if(v === "true") return true; if(v === "false") return false; if(v.match(/^[0-9]+$/)) return parseInt(v); if(v.match(/^[0-9\.]+$/)) return parseFloat(v); return v; } var USEROPTS = { theme : getOrDefault("theme", "default"), css : getOrDefault("css", ""), layout : getOrDefault("layout", "default"), synch : getOrDefault("synch", true), hidevid : getOrDefault("hidevid", false), show_timestamps : getOrDefault("show_timestamps", true), modhat : getOrDefault("modhat", false), blink_title : getOrDefault("blink_title", false), sync_accuracy : getOrDefault("sync_accuracy", 2), wmode_transparent : getOrDefault("wmode_transparent", true), chatbtn : getOrDefault("chatbtn", false), altsocket : getOrDefault("altsocket", false), joinmessage : getOrDefault("joinmessage", true), qbtn_hide : getOrDefault("qbtn_hide", false), qbtn_idontlikechange : getOrDefault("qbtn_idontlikechange", false), first_visit : getOrDefault("first_visit", true), ignore_channelcss : getOrDefault("ignore_channelcss", false), ignore_channeljs : getOrDefault("ignore_channeljs", false), sort_rank : getOrDefault("sort_rank", false), sort_afk : getOrDefault("sort_afk", false) }; var NO_WEBSOCKETS = USEROPTS.altsocket; var Rank = { Guest: 0, Member: 1, Leader: 1.5, Moderator: 2, Admin: 3, Owner: 10, Siteadmin: 255 }; function createCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; document.cookie = name+"="+value+expires+"; path=/"; } function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(";"); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==" ") c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } function eraseCookie(name) { createCookie(name,"",-1); } /* to be implemented in callbacks.js */ function setupCallbacks() { }
www/assets/js/data.js
/* The MIT License (MIT) Copyright (c) 2013 Calvin Montgomery Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ var CL_VERSION = "2.0.0"; var CLIENT = { rank: -1, leader: false, name: "", logged_in: false, profile: { image: "", text: "" } }; var SUPERADMIN = false; var CHANNEL = { opts: {}, openqueue: false, perms: {}, css: "", js: "", motd: "", motd_text: "", name: false }; var PLAYER = false; var VIDEOQUALITY = false; var FLUIDLAYOUT = false; var VWIDTH; var VHEIGHT; if($("#videowidth").length > 0) { VWIDTH = $("#videowidth").css("width").replace("px", ""); VHEIGHT = ""+parseInt(parseInt(VWIDTH) * 9 / 16); } var MEDIA = { hash: "" }; var PL_MOVING = false; var PL_ADDING = false; var PL_DELETING = false; var REBUILDING = false; var socket = { emit: function() { console.log("socket not initialized"); console.log(arguments); } }; var IGNORED = []; var CHATHIST = []; var CHATHISTIDX = 0; var SCROLLCHAT = true; var LASTCHATNAME = ""; var LASTCHATTIME = 0; var FOCUSED = true; var PAGETITLE = "CyTube"; var TITLE_BLINK; var KICKED = false; var NAME = readCookie("cytube_uname"); var SESSION = readCookie("cytube_session"); var LEADTMR = false; var PL_FROM = ""; var PL_AFTER = ""; var PL_WAIT_SCROLL = false; var FILTER_FROM = 0; var FILTER_TO = 0; var NO_STORAGE = typeof localStorage == "undefined" || localStorage === null; function getOpt(k) { return NO_STORAGE ? readCookie(k) : localStorage.getItem(k); } function setOpt(k, v) { NO_STORAGE ? createCookie(k, v, 1000) : localStorage.setItem(k, v); } function getOrDefault(k, def) { var v = getOpt(k); if(v === null) return def; if(v === "true") return true; if(v === "false") return false; if(v.match(/^[0-9]+$/)) return parseInt(v); if(v.match(/^[0-9\.]+$/)) return parseFloat(v); return v; } var USEROPTS = { theme : getOrDefault("theme", "default"), css : getOrDefault("css", ""), layout : getOrDefault("layout", "default"), synch : getOrDefault("synch", true), hidevid : getOrDefault("hidevid", false), show_timestamps : getOrDefault("show_timestamps", true), modhat : getOrDefault("modhat", false), blink_title : getOrDefault("blink_title", false), sync_accuracy : getOrDefault("sync_accuracy", 2), wmode_transparent : getOrDefault("wmode_transparent", true), chatbtn : getOrDefault("chatbtn", false), altsocket : getOrDefault("altsocket", false), joinmessage : getOrDefault("joinmessage", true), qbtn_hide : getOrDefault("qbtn_hide", false), qbtn_idontlikechange : getOrDefault("qbtn_idontlikechange", false), first_visit : getOrDefault("first_visit", true), ignore_channelcss : getOrDefault("ignore_channelcss", false), ignore_channeljs : getOrDefault("ignore_channeljs", false) }; var NO_WEBSOCKETS = USEROPTS.altsocket; var Rank = { Guest: 0, Member: 1, Leader: 1.5, Moderator: 2, Admin: 3, Owner: 10, Siteadmin: 255 }; function createCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; document.cookie = name+"="+value+expires+"; path=/"; } function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(";"); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==" ") c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } function eraseCookie(name) { createCookie(name,"",-1); } /* to be implemented in callbacks.js */ function setupCallbacks() { }
Fix #254
www/assets/js/data.js
Fix #254
<ide><path>ww/assets/js/data.js <ide> qbtn_idontlikechange : getOrDefault("qbtn_idontlikechange", false), <ide> first_visit : getOrDefault("first_visit", true), <ide> ignore_channelcss : getOrDefault("ignore_channelcss", false), <del> ignore_channeljs : getOrDefault("ignore_channeljs", false) <add> ignore_channeljs : getOrDefault("ignore_channeljs", false), <add> sort_rank : getOrDefault("sort_rank", false), <add> sort_afk : getOrDefault("sort_afk", false) <ide> }; <ide> <ide> var NO_WEBSOCKETS = USEROPTS.altsocket;
Java
apache-2.0
4b9ca7636e15c368067a8af42652a180292500e6
0
jaamsim/jaamsim,jaamsim/jaamsim,jaamsim/jaamsim,jaamsim/jaamsim
/* * JaamSim Discrete Event Simulation * Copyright (C) 2014 Ausenco Engineering Canada Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jaamsim.ProcessFlow; import com.jaamsim.Graphics.DisplayEntity; import com.jaamsim.Samples.SampleInput; import com.jaamsim.input.Input; import com.jaamsim.input.Keyword; import com.jaamsim.input.Output; import com.jaamsim.input.UnitTypeInput; import com.jaamsim.units.Unit; import com.jaamsim.units.UserSpecifiedUnit; /** * Collects basic statistical information on the entities that are received. * @author Harry King * */ public class Statistics extends LinkedComponent { @Keyword(description = "The unit type for the variable whose statistics will be collected.", exampleList = {"DistanceUnit"}) private final UnitTypeInput unitType; @Keyword(description = "The variable for which statistics will be collected.", exampleList = {"'this.obj.attrib1'"}) private final SampleInput sampleValue; private double minValue; private double maxValue; private double totalValue; private double totalSquaredValue; private double lastValue; private double lastUpdateTime; private double totalTimeValue; private double totalSquaredTimeValue; private double firstSampleTime; { stateAssignment.setHidden(true); unitType = new UnitTypeInput("UnitType", "Key Inputs", UserSpecifiedUnit.class); unitType.setRequired(true); this.addInput(unitType); sampleValue = new SampleInput("SampleValue", "Key Inputs", null); sampleValue.setUnitType(UserSpecifiedUnit.class); sampleValue.setEntity(this); sampleValue.setRequired(true); this.addInput(sampleValue); } public Statistics() {} @Override public void updateForInput(Input<?> in) { super.updateForInput(in); if (in == unitType) { Class<? extends Unit> ut = unitType.getUnitType(); sampleValue.setUnitType(ut); return; } } @Override public void earlyInit() { super.earlyInit(); minValue = Double.POSITIVE_INFINITY; maxValue = Double.NEGATIVE_INFINITY; totalValue = 0.0; totalSquaredValue = 0.0; lastValue = 0.0; lastUpdateTime = 0.0; totalTimeValue = 0.0; totalSquaredTimeValue = 0.0; firstSampleTime = 0.0; } @Override public void addEntity(DisplayEntity ent) { super.addEntity(ent); double simTime = this.getSimTime(); // Update the statistics double val = sampleValue.getValue().getNextSample(simTime); minValue = Math.min(minValue, val); maxValue = Math.max(maxValue, val); totalValue += val; totalSquaredValue += val*val; // Calculate the time average if (this.getNumberAdded(simTime) == 1L) { firstSampleTime = simTime; } else { double weightedVal = lastValue * (simTime - lastUpdateTime); totalTimeValue += weightedVal; totalSquaredTimeValue += lastValue*weightedVal; } lastValue = val; lastUpdateTime = simTime; // Pass the entity to the next component this.sendToNextComponent(ent); } @Override public void clearStatistics() { super.clearStatistics(); minValue = Double.POSITIVE_INFINITY; maxValue = Double.NEGATIVE_INFINITY; totalValue = 0.0; totalSquaredValue = 0.0; totalTimeValue = 0.0; lastValue = 0.0; lastUpdateTime = 0.0; totalSquaredTimeValue = 0.0; firstSampleTime = 0.0; } @Override public Class<? extends Unit> getUserUnitType() { return unitType.getUnitType(); } // ****************************************************************************************************** // OUTPUT METHODS // ****************************************************************************************************** @Output(name = "SampleMinimum", description = "The smallest value that was recorded.", unitType = UserSpecifiedUnit.class, reportable = true, sequence = 0) public double getSampleMinimum(double simTime) { return minValue; } @Output(name = "SampleMaximum", description = "The largest value that was recorded.", unitType = UserSpecifiedUnit.class, reportable = true, sequence = 1) public double getSampleMaximum(double simTime) { return maxValue; } @Output(name = "SampleAverage", description = "The average of the values that were recorded.", unitType = UserSpecifiedUnit.class, reportable = true, sequence = 2) public double getSampleAverage(double simTime) { long num = this.getNumberAdded(simTime); if (num == 0L) return 0.0d; return totalValue/num; } @Output(name = "SampleStandardDeviation", description = "The standard deviation of the values that were recorded.", unitType = UserSpecifiedUnit.class, reportable = true, sequence = 3) public double getSampleStandardDeviation(double simTime) { long num = this.getNumberAdded(simTime); if (num == 0L) return 0.0d; double mean = totalValue/num; return Math.sqrt(totalSquaredValue/num - mean*mean); } @Output(name = "StandardDeviationOfTheMean", description = "The estimated standard deviation of the sample mean.", unitType = UserSpecifiedUnit.class, reportable = true, sequence = 4) public double getStandardDeviationOfTheMean(double simTime) { long num = this.getNumberAdded(simTime); if (num <= 1L) return 0.0d; return this.getSampleStandardDeviation(simTime)/Math.sqrt(num-1L); } @Output(name = "TimeAverage", description = "The average of the values recorded, weighted by the duration of each value.", unitType = UserSpecifiedUnit.class, reportable = true, sequence = 5) public double getTimeAverage(double simTime) { long num = this.getNumberAdded(simTime); if (num == 0L) return 0.0d; if (num == 1L) return lastValue; double dt = simTime - lastUpdateTime; return (totalTimeValue + lastValue*dt)/(simTime - firstSampleTime); } @Output(name = "TimeStandardDeviation", description = "The standard deviation of the values recorded, weighted by the duration of each value.", unitType = UserSpecifiedUnit.class, reportable = true, sequence = 6) public double getTimeStandardDeviation(double simTime) { long num = this.getNumberAdded(simTime); if (num <= 1L) return 0.0d; double mean = this.getTimeAverage(simTime); double dt = simTime - lastUpdateTime; double meanOfSquare = (totalSquaredTimeValue + lastValue*lastValue*dt)/(simTime - firstSampleTime); return Math.sqrt(meanOfSquare - mean*mean); } }
src/main/java/com/jaamsim/ProcessFlow/Statistics.java
/* * JaamSim Discrete Event Simulation * Copyright (C) 2014 Ausenco Engineering Canada Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jaamsim.ProcessFlow; import com.jaamsim.Graphics.DisplayEntity; import com.jaamsim.Samples.SampleInput; import com.jaamsim.input.Input; import com.jaamsim.input.Keyword; import com.jaamsim.input.Output; import com.jaamsim.input.UnitTypeInput; import com.jaamsim.units.Unit; import com.jaamsim.units.UserSpecifiedUnit; /** * Collects basic statistical information on the entities that are received. * @author Harry King * */ public class Statistics extends LinkedComponent { @Keyword(description = "The unit type for the variable whose statistic will be collected.", exampleList = {"DistanceUnit"}) private final UnitTypeInput unitType; @Keyword(description = "The variable for which statistics will be collected.", exampleList = {"'this.obj.attrib1'"}) private final SampleInput sampleValue; private double minValue; private double maxValue; private double totalValue; private double totalSquaredValue; private double lastValue; private double lastUpdateTime; private double totalTimeValue; private double totalSquaredTimeValue; private double firstSampleTime; { stateAssignment.setHidden(true); unitType = new UnitTypeInput("UnitType", "Key Inputs", UserSpecifiedUnit.class); unitType.setRequired(true); this.addInput(unitType); sampleValue = new SampleInput("SampleValue", "Key Inputs", null); sampleValue.setUnitType(UserSpecifiedUnit.class); sampleValue.setEntity(this); sampleValue.setRequired(true); this.addInput(sampleValue); } public Statistics() {} @Override public void updateForInput(Input<?> in) { super.updateForInput(in); if (in == unitType) { Class<? extends Unit> ut = unitType.getUnitType(); sampleValue.setUnitType(ut); return; } } @Override public void earlyInit() { super.earlyInit(); minValue = Double.POSITIVE_INFINITY; maxValue = Double.NEGATIVE_INFINITY; totalValue = 0.0; totalSquaredValue = 0.0; lastValue = 0.0; lastUpdateTime = 0.0; totalTimeValue = 0.0; totalSquaredTimeValue = 0.0; firstSampleTime = 0.0; } @Override public void addEntity(DisplayEntity ent) { super.addEntity(ent); double simTime = this.getSimTime(); // Update the statistics double val = sampleValue.getValue().getNextSample(simTime); minValue = Math.min(minValue, val); maxValue = Math.max(maxValue, val); totalValue += val; totalSquaredValue += val*val; // Calculate the time average if (this.getNumberAdded(simTime) == 1L) { firstSampleTime = simTime; } else { double weightedVal = lastValue * (simTime - lastUpdateTime); totalTimeValue += weightedVal; totalSquaredTimeValue += lastValue*weightedVal; } lastValue = val; lastUpdateTime = simTime; // Pass the entity to the next component this.sendToNextComponent(ent); } @Override public void clearStatistics() { super.clearStatistics(); minValue = Double.POSITIVE_INFINITY; maxValue = Double.NEGATIVE_INFINITY; totalValue = 0.0; totalSquaredValue = 0.0; totalTimeValue = 0.0; lastValue = 0.0; lastUpdateTime = 0.0; totalSquaredTimeValue = 0.0; firstSampleTime = 0.0; } @Override public Class<? extends Unit> getUserUnitType() { return unitType.getUnitType(); } // ****************************************************************************************************** // OUTPUT METHODS // ****************************************************************************************************** @Output(name = "SampleMinimum", description = "The smallest value that was recorded.", unitType = UserSpecifiedUnit.class, reportable = true, sequence = 0) public double getSampleMinimum(double simTime) { return minValue; } @Output(name = "SampleMaximum", description = "The largest value that was recorded.", unitType = UserSpecifiedUnit.class, reportable = true, sequence = 1) public double getSampleMaximum(double simTime) { return maxValue; } @Output(name = "SampleAverage", description = "The average of the values that were recorded.", unitType = UserSpecifiedUnit.class, reportable = true, sequence = 2) public double getSampleAverage(double simTime) { long num = this.getNumberAdded(simTime); if (num == 0L) return 0.0d; return totalValue/num; } @Output(name = "SampleStandardDeviation", description = "The standard deviation of the values that were recorded.", unitType = UserSpecifiedUnit.class, reportable = true, sequence = 3) public double getSampleStandardDeviation(double simTime) { long num = this.getNumberAdded(simTime); if (num == 0L) return 0.0d; double mean = totalValue/num; return Math.sqrt(totalSquaredValue/num - mean*mean); } @Output(name = "StandardDeviationOfTheMean", description = "The estimated standard deviation of the sample mean.", unitType = UserSpecifiedUnit.class, reportable = true, sequence = 4) public double getStandardDeviationOfTheMean(double simTime) { long num = this.getNumberAdded(simTime); if (num <= 1L) return 0.0d; return this.getSampleStandardDeviation(simTime)/Math.sqrt(num-1L); } @Output(name = "TimeAverage", description = "The average of the values recorded, weighted by the duration of each value.", unitType = UserSpecifiedUnit.class, reportable = true, sequence = 5) public double getTimeAverage(double simTime) { long num = this.getNumberAdded(simTime); if (num == 0L) return 0.0d; if (num == 1L) return lastValue; double dt = simTime - lastUpdateTime; return (totalTimeValue + lastValue*dt)/(simTime - firstSampleTime); } @Output(name = "TimeStandardDeviation", description = "The standard deviation of the values recorded, weighted by the duration of each value.", unitType = UserSpecifiedUnit.class, reportable = true, sequence = 6) public double getTimeStandardDeviation(double simTime) { long num = this.getNumberAdded(simTime); if (num <= 1L) return 0.0d; double mean = this.getTimeAverage(simTime); double dt = simTime - lastUpdateTime; double meanOfSquare = (totalSquaredTimeValue + lastValue*lastValue*dt)/(simTime - firstSampleTime); return Math.sqrt(meanOfSquare - mean*mean); } }
JS: improved keyword description for Statistics Signed-off-by: Harry King <[email protected]>
src/main/java/com/jaamsim/ProcessFlow/Statistics.java
JS: improved keyword description for Statistics
<ide><path>rc/main/java/com/jaamsim/ProcessFlow/Statistics.java <ide> */ <ide> public class Statistics extends LinkedComponent { <ide> <del> @Keyword(description = "The unit type for the variable whose statistic will be collected.", <add> @Keyword(description = "The unit type for the variable whose statistics will be collected.", <ide> exampleList = {"DistanceUnit"}) <ide> private final UnitTypeInput unitType; <ide>
Java
apache-2.0
fe6b1c3945bf68030c1ad9fa0a544727a0196b19
0
zzuhtzy/okio-source-read,zzuhtzy/okio-source-read
/* * Copyright (C) 2014 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okio; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InterruptedIOException; import java.io.OutputStream; import java.net.Socket; import java.net.SocketTimeoutException; import java.nio.file.Files; import java.nio.file.OpenOption; import java.nio.file.Path; import java.util.logging.Level; import java.util.logging.Logger; import org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement; import static okio.Util.checkOffsetAndCount; /** Essential APIs for working with Okio. */ public final class Okio { static final Logger logger = Logger.getLogger(Okio.class.getName()); private Okio() { } /** * Returns a new source that buffers reads from {@code source}. The returned * source will perform bulk reads into its in-memory buffer. Use this wherever * you read a source to get an ergonomic and efficient access to data. * 任何地方都可以使用,返回Source */ public static BufferedSource buffer(Source source) { return new RealBufferedSource(source); } /** * Returns a new sink that buffers writes to {@code sink}. The returned sink * will batch writes to {@code sink}. Use this wherever you write to a sink to * get an ergonomic and efficient access to data. * 任何地方都可以使用,返回Sink */ public static BufferedSink buffer(Sink sink) { return new RealBufferedSink(sink); } /** Returns a sink that writes to {@code out}. */ // 返回写到out的sink public static Sink sink(OutputStream out) { return sink(out, new Timeout()); } // 非对外接口 private static Sink sink(final OutputStream out, final Timeout timeout) { if (out == null) throw new IllegalArgumentException("out == null"); if (timeout == null) throw new IllegalArgumentException("timeout == null"); return new Sink() { @Override public void write(Buffer source, long byteCount) throws IOException { checkOffsetAndCount(source.size, 0, byteCount); while (byteCount > 0) { timeout.throwIfReached(); Segment head = source.head; int toCopy = (int) Math.min(byteCount, head.limit - head.pos); out.write(head.data, head.pos, toCopy); head.pos += toCopy; byteCount -= toCopy; source.size -= toCopy; if (head.pos == head.limit) { source.head = head.pop(); SegmentPool.recycle(head); } } } @Override public void flush() throws IOException { out.flush(); } @Override public void close() throws IOException { out.close(); } @Override public Timeout timeout() { return timeout; } @Override public String toString() { return "sink(" + out + ")"; } }; } /** * Returns a sink that writes to {@code socket}. Prefer this over {@link * #sink(OutputStream)} because this method honors timeouts. When the socket * write times out, the socket is asynchronously closed by a watchdog thread. * 返回一个写到socket的sink,如果超时,socket被看门狗进程关闭 */ public static Sink sink(Socket socket) throws IOException { if (socket == null) throw new IllegalArgumentException("socket == null"); AsyncTimeout timeout = timeout(socket); Sink sink = sink(socket.getOutputStream(), timeout); return timeout.sink(sink); } /** Returns a source that reads from {@code in}. */ // 返回从从in读数据的source public static Source source(InputStream in) { return source(in, new Timeout()); } // 非对外接口 private static Source source(final InputStream in, final Timeout timeout) { if (in == null) throw new IllegalArgumentException("in == null"); if (timeout == null) throw new IllegalArgumentException("timeout == null"); return new Source() { @Override public long read(Buffer sink, long byteCount) throws IOException { if (byteCount < 0) throw new IllegalArgumentException("byteCount < 0: " + byteCount); if (byteCount == 0) return 0; try { timeout.throwIfReached(); Segment tail = sink.writableSegment(1); int maxToCopy = (int) Math.min(byteCount, Segment.SIZE - tail.limit); int bytesRead = in.read(tail.data, tail.limit, maxToCopy); if (bytesRead == -1) return -1; tail.limit += bytesRead; sink.size += bytesRead; return bytesRead; } catch (AssertionError e) { if (isAndroidGetsocknameError(e)) throw new IOException(e); throw e; } } @Override public void close() throws IOException { in.close(); } @Override public Timeout timeout() { return timeout; } @Override public String toString() { return "source(" + in + ")"; } }; } /** Returns a source that reads from {@code file}. */ // 从文件中读 public static Source source(File file) throws FileNotFoundException { if (file == null) throw new IllegalArgumentException("file == null"); return source(new FileInputStream(file)); } /** Returns a source that reads from {@code path}. */ // 从路径读 @IgnoreJRERequirement // Should only be invoked on Java 7+. public static Source source(Path path, OpenOption... options) throws IOException { if (path == null) throw new IllegalArgumentException("path == null"); return source(Files.newInputStream(path, options)); } /** Returns a sink that writes to {@code file}. */ // 写到文件 public static Sink sink(File file) throws FileNotFoundException { if (file == null) throw new IllegalArgumentException("file == null"); return sink(new FileOutputStream(file)); } /** Returns a sink that appends to {@code file}. */ // 追加写到文件 public static Sink appendingSink(File file) throws FileNotFoundException { if (file == null) throw new IllegalArgumentException("file == null"); return sink(new FileOutputStream(file, true)); } /** Returns a sink that writes to {@code path}. */ // 写到path @IgnoreJRERequirement // Should only be invoked on Java 7+. public static Sink sink(Path path, OpenOption... options) throws IOException { if (path == null) throw new IllegalArgumentException("path == null"); return sink(Files.newOutputStream(path, options)); } /** Returns a sink that writes nowhere. */ // 没地方写的sink public static Sink blackhole() { return new Sink() { @Override public void write(Buffer source, long byteCount) throws IOException { source.skip(byteCount); } @Override public void flush() throws IOException {} @Override public Timeout timeout() { return Timeout.NONE; } @Override public void close() throws IOException {} }; } /** * Returns a source that reads from {@code socket}. Prefer this over {@link * #source(InputStream)} because this method honors timeouts. When the socket * read times out, the socket is asynchronously closed by a watchdog thread. * 从socket读,超时时socket自动关闭 */ public static Source source(Socket socket) throws IOException { if (socket == null) throw new IllegalArgumentException("socket == null"); AsyncTimeout timeout = timeout(socket); Source source = source(socket.getInputStream(), timeout); return timeout.source(source); } // 超时 private static AsyncTimeout timeout(final Socket socket) { return new AsyncTimeout() { @Override protected IOException newTimeoutException(IOException cause) { InterruptedIOException ioe = new SocketTimeoutException("timeout"); if (cause != null) { ioe.initCause(cause); } return ioe; } @Override protected void timedOut() { try { socket.close(); } catch (Exception e) { logger.log(Level.WARNING, "Failed to close timed out socket " + socket, e); } catch (AssertionError e) { if (isAndroidGetsocknameError(e)) { // Catch this exception due to a Firmware issue up to android 4.2.2 // https://code.google.com/p/android/issues/detail?id=54072 logger.log(Level.WARNING, "Failed to close timed out socket " + socket, e); } else { throw e; } } } }; } /** * Returns true if {@code e} is due to a firmware bug fixed after Android 4.2.2. * https://code.google.com/p/android/issues/detail?id=54072 */ static boolean isAndroidGetsocknameError(AssertionError e) { return e.getCause() != null && e.getMessage() != null && e.getMessage().contains("getsockname failed"); } }
okio/src/main/java/okio/Okio.java
/* * Copyright (C) 2014 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okio; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InterruptedIOException; import java.io.OutputStream; import java.net.Socket; import java.net.SocketTimeoutException; import java.nio.file.Files; import java.nio.file.OpenOption; import java.nio.file.Path; import java.util.logging.Level; import java.util.logging.Logger; import org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement; import static okio.Util.checkOffsetAndCount; /** Essential APIs for working with Okio. */ public final class Okio { static final Logger logger = Logger.getLogger(Okio.class.getName()); private Okio() { } /** * Returns a new source that buffers reads from {@code source}. The returned * source will perform bulk reads into its in-memory buffer. Use this wherever * you read a source to get an ergonomic and efficient access to data. */ public static BufferedSource buffer(Source source) { return new RealBufferedSource(source); } /** * Returns a new sink that buffers writes to {@code sink}. The returned sink * will batch writes to {@code sink}. Use this wherever you write to a sink to * get an ergonomic and efficient access to data. */ public static BufferedSink buffer(Sink sink) { return new RealBufferedSink(sink); } /** Returns a sink that writes to {@code out}. */ public static Sink sink(OutputStream out) { return sink(out, new Timeout()); } private static Sink sink(final OutputStream out, final Timeout timeout) { if (out == null) throw new IllegalArgumentException("out == null"); if (timeout == null) throw new IllegalArgumentException("timeout == null"); return new Sink() { @Override public void write(Buffer source, long byteCount) throws IOException { checkOffsetAndCount(source.size, 0, byteCount); while (byteCount > 0) { timeout.throwIfReached(); Segment head = source.head; int toCopy = (int) Math.min(byteCount, head.limit - head.pos); out.write(head.data, head.pos, toCopy); head.pos += toCopy; byteCount -= toCopy; source.size -= toCopy; if (head.pos == head.limit) { source.head = head.pop(); SegmentPool.recycle(head); } } } @Override public void flush() throws IOException { out.flush(); } @Override public void close() throws IOException { out.close(); } @Override public Timeout timeout() { return timeout; } @Override public String toString() { return "sink(" + out + ")"; } }; } /** * Returns a sink that writes to {@code socket}. Prefer this over {@link * #sink(OutputStream)} because this method honors timeouts. When the socket * write times out, the socket is asynchronously closed by a watchdog thread. */ public static Sink sink(Socket socket) throws IOException { if (socket == null) throw new IllegalArgumentException("socket == null"); AsyncTimeout timeout = timeout(socket); Sink sink = sink(socket.getOutputStream(), timeout); return timeout.sink(sink); } /** Returns a source that reads from {@code in}. */ public static Source source(InputStream in) { return source(in, new Timeout()); } private static Source source(final InputStream in, final Timeout timeout) { if (in == null) throw new IllegalArgumentException("in == null"); if (timeout == null) throw new IllegalArgumentException("timeout == null"); return new Source() { @Override public long read(Buffer sink, long byteCount) throws IOException { if (byteCount < 0) throw new IllegalArgumentException("byteCount < 0: " + byteCount); if (byteCount == 0) return 0; try { timeout.throwIfReached(); Segment tail = sink.writableSegment(1); int maxToCopy = (int) Math.min(byteCount, Segment.SIZE - tail.limit); int bytesRead = in.read(tail.data, tail.limit, maxToCopy); if (bytesRead == -1) return -1; tail.limit += bytesRead; sink.size += bytesRead; return bytesRead; } catch (AssertionError e) { if (isAndroidGetsocknameError(e)) throw new IOException(e); throw e; } } @Override public void close() throws IOException { in.close(); } @Override public Timeout timeout() { return timeout; } @Override public String toString() { return "source(" + in + ")"; } }; } /** Returns a source that reads from {@code file}. */ public static Source source(File file) throws FileNotFoundException { if (file == null) throw new IllegalArgumentException("file == null"); return source(new FileInputStream(file)); } /** Returns a source that reads from {@code path}. */ @IgnoreJRERequirement // Should only be invoked on Java 7+. public static Source source(Path path, OpenOption... options) throws IOException { if (path == null) throw new IllegalArgumentException("path == null"); return source(Files.newInputStream(path, options)); } /** Returns a sink that writes to {@code file}. */ public static Sink sink(File file) throws FileNotFoundException { if (file == null) throw new IllegalArgumentException("file == null"); return sink(new FileOutputStream(file)); } /** Returns a sink that appends to {@code file}. */ public static Sink appendingSink(File file) throws FileNotFoundException { if (file == null) throw new IllegalArgumentException("file == null"); return sink(new FileOutputStream(file, true)); } /** Returns a sink that writes to {@code path}. */ @IgnoreJRERequirement // Should only be invoked on Java 7+. public static Sink sink(Path path, OpenOption... options) throws IOException { if (path == null) throw new IllegalArgumentException("path == null"); return sink(Files.newOutputStream(path, options)); } /** Returns a sink that writes nowhere. */ public static Sink blackhole() { return new Sink() { @Override public void write(Buffer source, long byteCount) throws IOException { source.skip(byteCount); } @Override public void flush() throws IOException {} @Override public Timeout timeout() { return Timeout.NONE; } @Override public void close() throws IOException {} }; } /** * Returns a source that reads from {@code socket}. Prefer this over {@link * #source(InputStream)} because this method honors timeouts. When the socket * read times out, the socket is asynchronously closed by a watchdog thread. */ public static Source source(Socket socket) throws IOException { if (socket == null) throw new IllegalArgumentException("socket == null"); AsyncTimeout timeout = timeout(socket); Source source = source(socket.getInputStream(), timeout); return timeout.source(source); } private static AsyncTimeout timeout(final Socket socket) { return new AsyncTimeout() { @Override protected IOException newTimeoutException(IOException cause) { InterruptedIOException ioe = new SocketTimeoutException("timeout"); if (cause != null) { ioe.initCause(cause); } return ioe; } @Override protected void timedOut() { try { socket.close(); } catch (Exception e) { logger.log(Level.WARNING, "Failed to close timed out socket " + socket, e); } catch (AssertionError e) { if (isAndroidGetsocknameError(e)) { // Catch this exception due to a Firmware issue up to android 4.2.2 // https://code.google.com/p/android/issues/detail?id=54072 logger.log(Level.WARNING, "Failed to close timed out socket " + socket, e); } else { throw e; } } } }; } /** * Returns true if {@code e} is due to a firmware bug fixed after Android 4.2.2. * https://code.google.com/p/android/issues/detail?id=54072 */ static boolean isAndroidGetsocknameError(AssertionError e) { return e.getCause() != null && e.getMessage() != null && e.getMessage().contains("getsockname failed"); } }
KO Okio.java
okio/src/main/java/okio/Okio.java
KO Okio.java
<ide><path>kio/src/main/java/okio/Okio.java <ide> * Returns a new source that buffers reads from {@code source}. The returned <ide> * source will perform bulk reads into its in-memory buffer. Use this wherever <ide> * you read a source to get an ergonomic and efficient access to data. <add> * 任何地方都可以使用,返回Source <ide> */ <ide> public static BufferedSource buffer(Source source) { <ide> return new RealBufferedSource(source); <ide> * Returns a new sink that buffers writes to {@code sink}. The returned sink <ide> * will batch writes to {@code sink}. Use this wherever you write to a sink to <ide> * get an ergonomic and efficient access to data. <add> * 任何地方都可以使用,返回Sink <ide> */ <ide> public static BufferedSink buffer(Sink sink) { <ide> return new RealBufferedSink(sink); <ide> } <ide> <ide> /** Returns a sink that writes to {@code out}. */ <add> // 返回写到out的sink <ide> public static Sink sink(OutputStream out) { <ide> return sink(out, new Timeout()); <ide> } <ide> <add> // 非对外接口 <ide> private static Sink sink(final OutputStream out, final Timeout timeout) { <ide> if (out == null) throw new IllegalArgumentException("out == null"); <ide> if (timeout == null) throw new IllegalArgumentException("timeout == null"); <ide> * Returns a sink that writes to {@code socket}. Prefer this over {@link <ide> * #sink(OutputStream)} because this method honors timeouts. When the socket <ide> * write times out, the socket is asynchronously closed by a watchdog thread. <add> * 返回一个写到socket的sink,如果超时,socket被看门狗进程关闭 <ide> */ <ide> public static Sink sink(Socket socket) throws IOException { <ide> if (socket == null) throw new IllegalArgumentException("socket == null"); <ide> } <ide> <ide> /** Returns a source that reads from {@code in}. */ <add> // 返回从从in读数据的source <ide> public static Source source(InputStream in) { <ide> return source(in, new Timeout()); <ide> } <ide> <add> // 非对外接口 <ide> private static Source source(final InputStream in, final Timeout timeout) { <ide> if (in == null) throw new IllegalArgumentException("in == null"); <ide> if (timeout == null) throw new IllegalArgumentException("timeout == null"); <ide> } <ide> <ide> /** Returns a source that reads from {@code file}. */ <add> // 从文件中读 <ide> public static Source source(File file) throws FileNotFoundException { <ide> if (file == null) throw new IllegalArgumentException("file == null"); <ide> return source(new FileInputStream(file)); <ide> } <ide> <ide> /** Returns a source that reads from {@code path}. */ <add> // 从路径读 <ide> @IgnoreJRERequirement // Should only be invoked on Java 7+. <ide> public static Source source(Path path, OpenOption... options) throws IOException { <ide> if (path == null) throw new IllegalArgumentException("path == null"); <ide> } <ide> <ide> /** Returns a sink that writes to {@code file}. */ <add> // 写到文件 <ide> public static Sink sink(File file) throws FileNotFoundException { <ide> if (file == null) throw new IllegalArgumentException("file == null"); <ide> return sink(new FileOutputStream(file)); <ide> } <ide> <ide> /** Returns a sink that appends to {@code file}. */ <add> // 追加写到文件 <ide> public static Sink appendingSink(File file) throws FileNotFoundException { <ide> if (file == null) throw new IllegalArgumentException("file == null"); <ide> return sink(new FileOutputStream(file, true)); <ide> } <ide> <ide> /** Returns a sink that writes to {@code path}. */ <add> // 写到path <ide> @IgnoreJRERequirement // Should only be invoked on Java 7+. <ide> public static Sink sink(Path path, OpenOption... options) throws IOException { <ide> if (path == null) throw new IllegalArgumentException("path == null"); <ide> } <ide> <ide> /** Returns a sink that writes nowhere. */ <add> // 没地方写的sink <ide> public static Sink blackhole() { <ide> return new Sink() { <ide> @Override public void write(Buffer source, long byteCount) throws IOException { <ide> * Returns a source that reads from {@code socket}. Prefer this over {@link <ide> * #source(InputStream)} because this method honors timeouts. When the socket <ide> * read times out, the socket is asynchronously closed by a watchdog thread. <add> * 从socket读,超时时socket自动关闭 <ide> */ <ide> public static Source source(Socket socket) throws IOException { <ide> if (socket == null) throw new IllegalArgumentException("socket == null"); <ide> return timeout.source(source); <ide> } <ide> <add> // 超时 <ide> private static AsyncTimeout timeout(final Socket socket) { <ide> return new AsyncTimeout() { <ide> @Override protected IOException newTimeoutException(IOException cause) {
Java
apache-2.0
c9d5d0deac6ce587761f3359cdcfe161cb991ec5
0
apache/incubator-kylin,apache/incubator-kylin,apache/kylin,apache/incubator-kylin,apache/incubator-kylin,apache/kylin,apache/kylin,apache/incubator-kylin,apache/kylin,apache/incubator-kylin,apache/kylin,apache/kylin,apache/kylin
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kylin.metadata.model; import org.apache.kylin.common.util.DateFormat; import org.apache.kylin.common.util.LocalFileMetadataTestCase; import org.apache.kylin.metadata.model.SegmentRange.TSRange; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class DefaultPartitionConditionBuilderTest extends LocalFileMetadataTestCase { @Before public void setup() throws Exception { this.createTestMetadata(); } @After public void after() throws Exception { this.cleanupTestMetadata(); } private PartitionDesc.DefaultPartitionConditionBuilder partitionConditionBuilder; @Before public void setUp() { partitionConditionBuilder = new PartitionDesc.DefaultPartitionConditionBuilder(); } @Test public void testDatePartition() { PartitionDesc partitionDesc = new PartitionDesc(); TblColRef col = TblColRef.mockup(TableDesc.mockup("DEFAULT.TABLE_NAME"), 1, "DATE_COLUMN", "string"); partitionDesc.setPartitionDateColumnRef(col); partitionDesc.setPartitionDateColumn(col.getCanonicalName()); partitionDesc.setPartitionDateFormat("yyyy-MM-dd"); TSRange range = new TSRange(DateFormat.stringToMillis("2016-02-22"), DateFormat.stringToMillis("2016-02-23")); String condition = partitionConditionBuilder.buildDateRangeCondition(partitionDesc, null, range); Assert.assertEquals("UNKNOWN_ALIAS.DATE_COLUMN >= '2016-02-22' AND UNKNOWN_ALIAS.DATE_COLUMN < '2016-02-23'", condition); range = new TSRange(0L, 0L); condition = partitionConditionBuilder.buildDateRangeCondition(partitionDesc, null, range); Assert.assertEquals("1=0", condition); } @Test public void testTimePartition() { PartitionDesc partitionDesc = new PartitionDesc(); TblColRef col = TblColRef.mockup(TableDesc.mockup("DEFAULT.TABLE_NAME"), 2, "HOUR_COLUMN", "string"); partitionDesc.setPartitionTimeColumnRef(col); partitionDesc.setPartitionTimeColumn(col.getCanonicalName()); partitionDesc.setPartitionTimeFormat("HH"); TSRange range = new TSRange(DateFormat.stringToMillis("2016-02-22 00:00:00"), DateFormat.stringToMillis("2016-02-23 01:00:00")); String condition = partitionConditionBuilder.buildDateRangeCondition(partitionDesc, null, range); Assert.assertEquals("UNKNOWN_ALIAS.HOUR_COLUMN >= '00' AND UNKNOWN_ALIAS.HOUR_COLUMN < '01'", condition); } @Test public void testDateAndTimePartition() { PartitionDesc partitionDesc = new PartitionDesc(); TblColRef col1 = TblColRef.mockup(TableDesc.mockup("DEFAULT.TABLE_NAME"), 1, "DATE_COLUMN", "string"); partitionDesc.setPartitionDateColumnRef(col1); partitionDesc.setPartitionDateColumn(col1.getCanonicalName()); partitionDesc.setPartitionDateFormat("yyyy-MM-dd"); TblColRef col2 = TblColRef.mockup(TableDesc.mockup("DEFAULT.TABLE_NAME"), 2, "HOUR_COLUMN", "string"); partitionDesc.setPartitionTimeColumnRef(col2); partitionDesc.setPartitionTimeColumn(col2.getCanonicalName()); partitionDesc.setPartitionTimeFormat("H"); TSRange range = new TSRange(DateFormat.stringToMillis("2016-02-22 00:00:00"), DateFormat.stringToMillis("2016-02-23 01:00:00")); String condition = partitionConditionBuilder.buildDateRangeCondition(partitionDesc, null, range); Assert.assertEquals( "((UNKNOWN_ALIAS.DATE_COLUMN = '2016-02-22' AND UNKNOWN_ALIAS.HOUR_COLUMN >= '0') OR (UNKNOWN_ALIAS.DATE_COLUMN > '2016-02-22')) AND ((UNKNOWN_ALIAS.DATE_COLUMN = '2016-02-23' AND UNKNOWN_ALIAS.HOUR_COLUMN < '1') OR (UNKNOWN_ALIAS.DATE_COLUMN < '2016-02-23'))", condition); } }
core-metadata/src/test/java/org/apache/kylin/metadata/model/DefaultPartitionConditionBuilderTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kylin.metadata.model; import org.apache.kylin.common.util.DateFormat; import org.apache.kylin.common.util.LocalFileMetadataTestCase; import org.apache.kylin.metadata.model.SegmentRange.TSRange; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class DefaultPartitionConditionBuilderTest extends LocalFileMetadataTestCase { @Before public void setup() throws Exception { this.createTestMetadata(); } @After public void after() throws Exception { this.cleanupTestMetadata(); } private PartitionDesc.DefaultPartitionConditionBuilder partitionConditionBuilder; @Before public void setUp() { partitionConditionBuilder = new PartitionDesc.DefaultPartitionConditionBuilder(); } @Test public void testDatePartition() { PartitionDesc partitionDesc = new PartitionDesc(); TblColRef col = TblColRef.mockup(TableDesc.mockup("DEFAULT.TABLE_NAME"), 1, "DATE_COLUMN", "string"); partitionDesc.setPartitionDateColumnRef(col); partitionDesc.setPartitionDateColumn(col.getCanonicalName()); partitionDesc.setPartitionDateFormat("yyyy-MM-dd"); TSRange range = new TSRange(DateFormat.stringToMillis("2016-02-22"), DateFormat.stringToMillis("2016-02-23")); String condition = partitionConditionBuilder.buildDateRangeCondition(partitionDesc, null, range); Assert.assertEquals("UNKNOWN_ALIAS.DATE_COLUMN >= '2016-02-22' AND UNKNOWN_ALIAS.DATE_COLUMN < '2016-02-23'", condition); range = new TSRange(0L, 0L); condition = partitionConditionBuilder.buildDateRangeCondition(partitionDesc, null, range); Assert.assertEquals("1=1", condition); } @Test public void testTimePartition() { PartitionDesc partitionDesc = new PartitionDesc(); TblColRef col = TblColRef.mockup(TableDesc.mockup("DEFAULT.TABLE_NAME"), 2, "HOUR_COLUMN", "string"); partitionDesc.setPartitionTimeColumnRef(col); partitionDesc.setPartitionTimeColumn(col.getCanonicalName()); partitionDesc.setPartitionTimeFormat("HH"); TSRange range = new TSRange(DateFormat.stringToMillis("2016-02-22 00:00:00"), DateFormat.stringToMillis("2016-02-23 01:00:00")); String condition = partitionConditionBuilder.buildDateRangeCondition(partitionDesc, null, range); Assert.assertEquals("UNKNOWN_ALIAS.HOUR_COLUMN >= '00' AND UNKNOWN_ALIAS.HOUR_COLUMN < '01'", condition); } @Test public void testDateAndTimePartition() { PartitionDesc partitionDesc = new PartitionDesc(); TblColRef col1 = TblColRef.mockup(TableDesc.mockup("DEFAULT.TABLE_NAME"), 1, "DATE_COLUMN", "string"); partitionDesc.setPartitionDateColumnRef(col1); partitionDesc.setPartitionDateColumn(col1.getCanonicalName()); partitionDesc.setPartitionDateFormat("yyyy-MM-dd"); TblColRef col2 = TblColRef.mockup(TableDesc.mockup("DEFAULT.TABLE_NAME"), 2, "HOUR_COLUMN", "string"); partitionDesc.setPartitionTimeColumnRef(col2); partitionDesc.setPartitionTimeColumn(col2.getCanonicalName()); partitionDesc.setPartitionTimeFormat("H"); TSRange range = new TSRange(DateFormat.stringToMillis("2016-02-22 00:00:00"), DateFormat.stringToMillis("2016-02-23 01:00:00")); String condition = partitionConditionBuilder.buildDateRangeCondition(partitionDesc, null, range); Assert.assertEquals( "((UNKNOWN_ALIAS.DATE_COLUMN = '2016-02-22' AND UNKNOWN_ALIAS.HOUR_COLUMN >= '0') OR (UNKNOWN_ALIAS.DATE_COLUMN > '2016-02-22')) AND ((UNKNOWN_ALIAS.DATE_COLUMN = '2016-02-23' AND UNKNOWN_ALIAS.HOUR_COLUMN < '1') OR (UNKNOWN_ALIAS.DATE_COLUMN < '2016-02-23'))", condition); } }
KYLIN-3689 fix UT
core-metadata/src/test/java/org/apache/kylin/metadata/model/DefaultPartitionConditionBuilderTest.java
KYLIN-3689 fix UT
<ide><path>ore-metadata/src/test/java/org/apache/kylin/metadata/model/DefaultPartitionConditionBuilderTest.java <ide> <ide> range = new TSRange(0L, 0L); <ide> condition = partitionConditionBuilder.buildDateRangeCondition(partitionDesc, null, range); <del> Assert.assertEquals("1=1", condition); <add> Assert.assertEquals("1=0", condition); <ide> } <ide> <ide> @Test
Java
mit
error: pathspec 'src/org/lff/plugin/dupfinder/utility/FilenameUtility.java' did not match any file(s) known to git
12cc4b69371621ac57ff7462705bbfb7149129ad
1
lff0305/duplicateClassFinder
package org.lff.plugin.dupfinder.utility; import java.net.MalformedURLException; import java.net.URL; /** * @author Feifei Liu * @datetime Jul 10 2017 10:35 */ public class FilenameUtility { public static void main(String[] argu) { String t = "jar://C:/dev/apache-tomcat-8.5.15/lib/annotations-api.jar!/"; System.out.println(getFileName(t)); } public static String getFileName(String urlName) { int index = urlName.indexOf("://"); int last = urlName.indexOf("!/"); if (index != -1 && last == -1) { return urlName.substring(index + 3); } if (index != -1 && last != -1) { return urlName.substring(index + 3, last); } return null; } }
src/org/lff/plugin/dupfinder/utility/FilenameUtility.java
No issue. Add filename utility.
src/org/lff/plugin/dupfinder/utility/FilenameUtility.java
No issue. Add filename utility.
<ide><path>rc/org/lff/plugin/dupfinder/utility/FilenameUtility.java <add>package org.lff.plugin.dupfinder.utility; <add> <add>import java.net.MalformedURLException; <add>import java.net.URL; <add> <add>/** <add> * @author Feifei Liu <add> * @datetime Jul 10 2017 10:35 <add> */ <add>public class FilenameUtility { <add> <add> public static void main(String[] argu) { <add> String t = "jar://C:/dev/apache-tomcat-8.5.15/lib/annotations-api.jar!/"; <add> System.out.println(getFileName(t)); <add> } <add> <add> public static String getFileName(String urlName) { <add> int index = urlName.indexOf("://"); <add> int last = urlName.indexOf("!/"); <add> if (index != -1 && last == -1) { <add> return urlName.substring(index + 3); <add> } <add> if (index != -1 && last != -1) { <add> return urlName.substring(index + 3, last); <add> } <add> return null; <add> } <add>}
Java
apache-2.0
020e28f88e5ab6f4bde8cdf96e1003bdeb45dd8c
0
nickbutcher/plaid,nickbutcher/plaid,nickbutcher/plaid,nickbutcher/plaid
/* * Copyright 2015 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.plaidapp.ui.recyclerview; import android.support.annotation.NonNull; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import io.plaidapp.data.DataLoadingSubject; /** * A scroll listener for RecyclerView to load more items as you approach the end. * * Adapted from https://gist.github.com/ssinss/e06f12ef66c51252563e */ public abstract class InfiniteScrollListener extends RecyclerView.OnScrollListener { // The minimum number of items remaining before we should loading more. private static final int VISIBLE_THRESHOLD = 5; private final LinearLayoutManager layoutManager; private final DataLoadingSubject dataLoading; private final Runnable loadMoreRunnable = new Runnable() { @Override public void run() { onLoadMore(); } }; public InfiniteScrollListener(@NonNull LinearLayoutManager layoutManager, @NonNull DataLoadingSubject dataLoading) { this.layoutManager = layoutManager; this.dataLoading = dataLoading; } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { // bail out if scrolling upward or already loading data if (dy < 0 || dataLoading.isDataLoading()) return; final int visibleItemCount = recyclerView.getChildCount(); final int totalItemCount = layoutManager.getItemCount(); final int firstVisibleItem = layoutManager.findFirstVisibleItemPosition(); if ((totalItemCount - visibleItemCount) <= (firstVisibleItem + VISIBLE_THRESHOLD)) { recyclerView.post(loadMoreRunnable); } } public abstract void onLoadMore(); }
app/src/main/java/io/plaidapp/ui/recyclerview/InfiniteScrollListener.java
/* * Copyright 2015 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.plaidapp.ui.recyclerview; import android.support.annotation.NonNull; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import io.plaidapp.data.DataLoadingSubject; /** * A scroll listener for RecyclerView to load more items as you approach the end. * * Adapted from https://gist.github.com/ssinss/e06f12ef66c51252563e */ public abstract class InfiniteScrollListener extends RecyclerView.OnScrollListener { // The minimum number of items remaining before we should loading more. private static final int VISIBLE_THRESHOLD = 5; private final LinearLayoutManager layoutManager; private final DataLoadingSubject dataLoading; public InfiniteScrollListener(@NonNull LinearLayoutManager layoutManager, @NonNull DataLoadingSubject dataLoading) { this.layoutManager = layoutManager; this.dataLoading = dataLoading; } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { // bail out if scrolling upward or already loading data if (dy < 0 || dataLoading.isDataLoading()) return; final int visibleItemCount = recyclerView.getChildCount(); final int totalItemCount = layoutManager.getItemCount(); final int firstVisibleItem = layoutManager.findFirstVisibleItemPosition(); if ((totalItemCount - visibleItemCount) <= (firstVisibleItem + VISIBLE_THRESHOLD)) { recyclerView.post(new Runnable() { @Override public void run() { onLoadMore(); } }); } } public abstract void onLoadMore(); }
move runnable to field
app/src/main/java/io/plaidapp/ui/recyclerview/InfiniteScrollListener.java
move runnable to field
<ide><path>pp/src/main/java/io/plaidapp/ui/recyclerview/InfiniteScrollListener.java <ide> <ide> private final LinearLayoutManager layoutManager; <ide> private final DataLoadingSubject dataLoading; <add> private final Runnable loadMoreRunnable = new Runnable() { <add> @Override <add> public void run() { <add> onLoadMore(); <add> } <add> }; <ide> <ide> public InfiniteScrollListener(@NonNull LinearLayoutManager layoutManager, <ide> @NonNull DataLoadingSubject dataLoading) { <ide> final int firstVisibleItem = layoutManager.findFirstVisibleItemPosition(); <ide> <ide> if ((totalItemCount - visibleItemCount) <= (firstVisibleItem + VISIBLE_THRESHOLD)) { <del> recyclerView.post(new Runnable() { <del> @Override public void run() { <del> onLoadMore(); <del> } <del> }); <add> recyclerView.post(loadMoreRunnable); <ide> } <ide> } <ide>
Java
apache-2.0
f3ea6d2d077b51a311685c7fb4bc987fb4cb4139
0
bf8086/alluxio,carsonwang/tachyon,bf8086/alluxio,maobaolong/alluxio,wwjiang007/alluxio,calvinjia/tachyon,wwjiang007/alluxio,madanadit/alluxio,maboelhassan/alluxio,apc999/alluxio,riversand963/alluxio,wwjiang007/alluxio,ShailShah/alluxio,bf8086/alluxio,maobaolong/alluxio,apc999/alluxio,aaudiber/alluxio,EvilMcJerkface/alluxio,ChangerYoung/alluxio,uronce-cc/alluxio,jswudi/alluxio,Alluxio/alluxio,bf8086/alluxio,ChangerYoung/alluxio,ooq/memory,Alluxio/alluxio,WilliamZapata/alluxio,maobaolong/alluxio,madanadit/alluxio,Alluxio/alluxio,mesosphere/tachyon,solzy/tachyon,yuluo-ding/alluxio,Reidddddd/alluxio,calvinjia/tachyon,ChangerYoung/alluxio,PasaLab/tachyon,ShailShah/alluxio,PasaLab/tachyon,EvilMcJerkface/alluxio,maboelhassan/alluxio,madanadit/alluxio,madanadit/alluxio,uronce-cc/alluxio,ShailShah/alluxio,Reidddddd/mo-alluxio,riversand963/alluxio,Reidddddd/alluxio,apc999/alluxio,WilliamZapata/alluxio,wwjiang007/alluxio,wwjiang007/alluxio,jswudi/alluxio,yuluo-ding/alluxio,ChangerYoung/alluxio,WilliamZapata/alluxio,riversand963/alluxio,jswudi/alluxio,wwjiang007/alluxio,jswudi/alluxio,bf8086/alluxio,mesosphere/tachyon,apc999/alluxio,EvilMcJerkface/alluxio,mesosphere/tachyon,aaudiber/alluxio,uronce-cc/alluxio,maobaolong/alluxio,Alluxio/alluxio,yuluo-ding/alluxio,Reidddddd/alluxio,PasaLab/tachyon,madanadit/alluxio,Reidddddd/alluxio,riversand963/alluxio,wwjiang007/alluxio,jsimsa/alluxio,Reidddddd/mo-alluxio,ooq/memory,maboelhassan/alluxio,calvinjia/tachyon,calvinjia/tachyon,PasaLab/tachyon,Reidddddd/mo-alluxio,WilliamZapata/alluxio,uronce-cc/alluxio,jswudi/alluxio,jsimsa/alluxio,madanadit/alluxio,calvinjia/tachyon,jsimsa/alluxio,Reidddddd/mo-alluxio,ChangerYoung/alluxio,uronce-cc/alluxio,yuluo-ding/alluxio,Alluxio/alluxio,wwjiang007/alluxio,Alluxio/alluxio,carsonwang/tachyon,uronce-cc/alluxio,aaudiber/alluxio,apc999/alluxio,ShailShah/alluxio,bf8086/alluxio,maobaolong/alluxio,Alluxio/alluxio,bf8086/alluxio,ShailShah/alluxio,WilliamZapata/alluxio,Alluxio/alluxio,madanadit/alluxio,maboelhassan/alluxio,maobaolong/alluxio,maobaolong/alluxio,jswudi/alluxio,PasaLab/tachyon,Reidddddd/mo-alluxio,jsimsa/alluxio,Alluxio/alluxio,carsonwang/tachyon,maboelhassan/alluxio,EvilMcJerkface/alluxio,solzy/tachyon,Reidddddd/alluxio,aaudiber/alluxio,apc999/alluxio,apc999/alluxio,ooq/memory,bf8086/alluxio,EvilMcJerkface/alluxio,maboelhassan/alluxio,ShailShah/alluxio,EvilMcJerkface/alluxio,wwjiang007/alluxio,Reidddddd/alluxio,aaudiber/alluxio,EvilMcJerkface/alluxio,madanadit/alluxio,riversand963/alluxio,wwjiang007/alluxio,ooq/memory,riversand963/alluxio,ChangerYoung/alluxio,maboelhassan/alluxio,calvinjia/tachyon,aaudiber/alluxio,Reidddddd/mo-alluxio,EvilMcJerkface/alluxio,maobaolong/alluxio,yuluo-ding/alluxio,jsimsa/alluxio,maobaolong/alluxio,Reidddddd/alluxio,PasaLab/tachyon,solzy/tachyon,PasaLab/tachyon,maobaolong/alluxio,WilliamZapata/alluxio,aaudiber/alluxio,jsimsa/alluxio,calvinjia/tachyon,carsonwang/tachyon,mesosphere/tachyon,yuluo-ding/alluxio,Alluxio/alluxio,calvinjia/tachyon,solzy/tachyon
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tachyon.web; import java.io.IOException; import java.util.List; import java.util.Set; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import tachyon.Constants; import tachyon.Version; import tachyon.master.DependencyVariables; import tachyon.master.MasterInfo; import tachyon.thrift.ClientWorkerInfo; import tachyon.util.CommonUtils; /** * Servlet that provides data for viewing the general status of the filesystem. */ public class WebInterfaceGeneralServlet extends HttpServlet { /** * Class to make referencing worker nodes more intuitive. Mainly to avoid implicit association * by array indexes. */ public class NodeInfo { private final String NAME; private final String LAST_CONTACT_SEC; private final String STATE; private final int FREE_SPACE_PERCENT; private final int USED_SPACE_PERCENT; private final String UPTIME_CLOCK_TIME; private NodeInfo(ClientWorkerInfo workerInfo) { NAME = workerInfo.getAddress().getMHost(); LAST_CONTACT_SEC = Integer.toString(workerInfo.getLastContactSec()); STATE = workerInfo.getState(); USED_SPACE_PERCENT = (int) (100L * workerInfo.getUsedBytes() / workerInfo.getCapacityBytes()); FREE_SPACE_PERCENT = 100 - USED_SPACE_PERCENT; UPTIME_CLOCK_TIME = CommonUtils.convertMsToShortClockTime(System.currentTimeMillis() - workerInfo.getStarttimeMs()); } public int getFreeSpacePercent() { return FREE_SPACE_PERCENT; } public String getLastHeartbeat() { return LAST_CONTACT_SEC; } public String getName() { return NAME; } public String getState() { return STATE; } public String getUptimeClockTime() { return UPTIME_CLOCK_TIME; } public int getUsedSpacePercent() { return USED_SPACE_PERCENT; } } private static final long serialVersionUID = 2335205655766736309L; private MasterInfo mMasterInfo; public WebInterfaceGeneralServlet(MasterInfo masterInfo) { mMasterInfo = masterInfo; } /** * Redirects the request to a JSP after populating attributes via populateValues. * * @param request * The HttpServletRequest object * @param response * The HttpServletResponse object */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { populateValues(request); getServletContext().getRequestDispatcher("/general.jsp").forward(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { DependencyVariables.sVariables.clear(); for (String key : (Set<String>) request.getParameterMap().keySet()) { if (key.startsWith("varName")) { String value = request.getParameter("varVal" + key.substring(7)); if (value != null) { DependencyVariables.sVariables.put(request.getParameter(key), value); } } } populateValues(request); getServletContext().getRequestDispatcher("/general.jsp").forward(request, response); } /** * Populates key, value pairs for UI display * * @param request * The HttpServletRequest object * @throws IOException */ private void populateValues(HttpServletRequest request) throws IOException { request.setAttribute("debug", Constants.DEBUG); request.setAttribute("masterNodeAddress", mMasterInfo.getMasterAddress().toString()); request.setAttribute("uptime", CommonUtils.convertMsToClockTime(System.currentTimeMillis() - mMasterInfo.getStarttimeMs())); request.setAttribute("startTime", CommonUtils.convertMsToDate(mMasterInfo.getStarttimeMs())); request.setAttribute("version", Version.VERSION); request.setAttribute("liveWorkerNodes", Integer.toString(mMasterInfo.getWorkerCount())); request.setAttribute("capacity", CommonUtils.getSizeFromBytes(mMasterInfo.getCapacityBytes())); request.setAttribute("usedCapacity", CommonUtils.getSizeFromBytes(mMasterInfo.getUsedBytes())); request.setAttribute("freeCapacity", CommonUtils.getSizeFromBytes((mMasterInfo .getCapacityBytes() - mMasterInfo.getUsedBytes()))); long sizeBytes = mMasterInfo.getUnderFsCapacityBytes(); if (sizeBytes >= 0) { request.setAttribute("diskCapacity", CommonUtils.getSizeFromBytes(sizeBytes)); } else { request.setAttribute("diskCapacity", "UNKNOWN"); } sizeBytes = mMasterInfo.getUnderFsUsedBytes(); if (sizeBytes >= 0) { request.setAttribute("diskUsedCapacity", CommonUtils.getSizeFromBytes(sizeBytes)); } else { request.setAttribute("diskUsedCapacity", "UNKNOWN"); } sizeBytes = mMasterInfo.getUnderFsFreeBytes(); if (sizeBytes >= 0) { request.setAttribute("diskFreeCapacity", CommonUtils.getSizeFromBytes(sizeBytes)); } else { request.setAttribute("diskFreeCapacity", "UNKNOWN"); } request.setAttribute("recomputeVariables", DependencyVariables.sVariables); List<ClientWorkerInfo> workerInfos = mMasterInfo.getWorkersInfo(); for (int i = 0; i < workerInfos.size(); i ++) { for (int j = i + 1; j < workerInfos.size(); j ++) { if (workerInfos.get(i).getAddress().getMHost() .compareTo(workerInfos.get(j).getAddress().getMHost()) > 0) { ClientWorkerInfo temp = workerInfos.get(i); workerInfos.set(i, workerInfos.get(j)); workerInfos.set(j, temp); } } } int index = 0; NodeInfo[] nodeInfos = new NodeInfo[workerInfos.size()]; for (ClientWorkerInfo workerInfo : workerInfos) { nodeInfos[index ++] = new NodeInfo(workerInfo); } request.setAttribute("nodeInfos", nodeInfos); //request.setAttribute("pinlist", mMasterInfo.getPinList()); //request.setAttribute("whitelist", mMasterInfo.getWhiteList()); } }
main/src/main/java/tachyon/web/WebInterfaceGeneralServlet.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tachyon.web; import java.io.IOException; import java.util.List; import java.util.Set; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import tachyon.Constants; import tachyon.Version; import tachyon.master.DependencyVariables; import tachyon.master.MasterInfo; import tachyon.thrift.ClientWorkerInfo; import tachyon.util.CommonUtils; /** * Servlet that provides data for viewing the general status of the filesystem. */ public class WebInterfaceGeneralServlet extends HttpServlet { /** * Class to make referencing worker nodes more intuitive. Mainly to avoid implicit association * by array indexes. */ public class NodeInfo { private final String NAME; private final String LAST_CONTACT_SEC; private final String STATE; private final int FREE_SPACE_PERCENT; private final int USED_SPACE_PERCENT; private final String UPTIME_CLOCK_TIME; private NodeInfo(ClientWorkerInfo workerInfo) { NAME = workerInfo.getAddress().getMHost(); LAST_CONTACT_SEC = Integer.toString(workerInfo.getLastContactSec()); STATE = workerInfo.getState(); USED_SPACE_PERCENT = (int) (100L * workerInfo.getUsedBytes() / workerInfo.getCapacityBytes()); FREE_SPACE_PERCENT = 100 - USED_SPACE_PERCENT; UPTIME_CLOCK_TIME = CommonUtils.convertMsToShortClockTime(System.currentTimeMillis() - workerInfo.getStarttimeMs()); } public int getFreeSpacePercent() { return FREE_SPACE_PERCENT; } public String getLastHeartbeat() { return LAST_CONTACT_SEC; } public String getName() { return NAME; } public String getState() { return STATE; } public String getUptimeClockTime() { return UPTIME_CLOCK_TIME; } public int getUsedSpacePercent() { return USED_SPACE_PERCENT; } } private static final long serialVersionUID = 2335205655766736309L; private MasterInfo mMasterInfo; public WebInterfaceGeneralServlet(MasterInfo masterInfo) { mMasterInfo = masterInfo; } /** * Redirects the request to a JSP after populating attributes via populateValues. * * @param request * The HttpServletRequest object * @param response * The HttpServletResponse object */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { populateValues(request); getServletContext().getRequestDispatcher("/general.jsp").forward(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { DependencyVariables.sVariables.clear(); for (String key : (Set<String>) request.getParameterMap().keySet()) { if (key.startsWith("varName")) { String value = request.getParameter("varVal" + key.substring(7)); if (value != null) { DependencyVariables.sVariables.put(request.getParameter(key), value); } } } populateValues(request); getServletContext().getRequestDispatcher("/general.jsp").forward(request, response); } /** * Populates key, value pairs for UI display * * @param request * The HttpServletRequest object * @throws IOException */ private void populateValues(HttpServletRequest request) throws IOException { request.setAttribute("debug", Constants.DEBUG); request.setAttribute("masterNodeAddress", mMasterInfo.getMasterAddress().toString()); request.setAttribute("uptime", CommonUtils.convertMsToClockTime(System.currentTimeMillis() - mMasterInfo.getStarttimeMs())); request.setAttribute("startTime", CommonUtils.convertMsToDate(mMasterInfo.getStarttimeMs())); request.setAttribute("version", Version.VERSION); request.setAttribute("liveWorkerNodes", Integer.toString(mMasterInfo.getWorkerCount())); request.setAttribute("capacity", CommonUtils.getSizeFromBytes(mMasterInfo.getCapacityBytes())); request.setAttribute("usedCapacity", CommonUtils.getSizeFromBytes(mMasterInfo.getUsedBytes())); request.setAttribute("freeCapacity", CommonUtils.getSizeFromBytes((mMasterInfo .getCapacityBytes() - mMasterInfo.getUsedBytes()))); long sizeBytes = mMasterInfo.getUnderFsCapacityBytes(); if (sizeBytes >= 0) { request.setAttribute("diskCapacity", CommonUtils.getSizeFromBytes(sizeBytes)); } else { request.setAttribute("diskCapacity", "UNKNOWN"); } sizeBytes = mMasterInfo.getUnderFsUsedBytes(); if (sizeBytes >= 0) { request.setAttribute("diskUsedCapacity", CommonUtils.getSizeFromBytes(sizeBytes)); } else { request.setAttribute("diskUsedCapacity", "UNKNOWN"); } sizeBytes = mMasterInfo.getUnderFsFreeBytes(); if (sizeBytes >= 0) { request.setAttribute("diskFreeCapacity", CommonUtils.getSizeFromBytes(sizeBytes)); } else { request.setAttribute("diskFreeCapacity", "UNKNOWN"); } request.setAttribute("recomputeVariables", DependencyVariables.sVariables); List<ClientWorkerInfo> workerInfos = mMasterInfo.getWorkersInfo(); for (int i = 0; i < workerInfos.size(); i ++) { for (int j = i + 1; j < workerInfos.size(); j ++) { if (workerInfos.get(i).getAddress().getMHost() .compareTo(workerInfos.get(j).getAddress().getMHost()) > 0) { ClientWorkerInfo temp = workerInfos.get(i); workerInfos.set(i, workerInfos.get(j)); workerInfos.set(j, temp); } } } int index = 0; NodeInfo[] nodeInfos = new NodeInfo[workerInfos.size()]; for (ClientWorkerInfo workerInfo : workerInfos) { nodeInfos[index ++] = new NodeInfo(workerInfo); } request.setAttribute("nodeInfos", nodeInfos); request.setAttribute("pinlist", mMasterInfo.getPinList()); request.setAttribute("whitelist", mMasterInfo.getWhiteList()); } }
Update WebInterfaceGeneralServlet.java Remove "pinlist" and "whitelist", which have been moved to WebInterfaceConfigurationServlet.java .
main/src/main/java/tachyon/web/WebInterfaceGeneralServlet.java
Update WebInterfaceGeneralServlet.java
<ide><path>ain/src/main/java/tachyon/web/WebInterfaceGeneralServlet.java <ide> } <ide> request.setAttribute("nodeInfos", nodeInfos); <ide> <del> request.setAttribute("pinlist", mMasterInfo.getPinList()); <add> //request.setAttribute("pinlist", mMasterInfo.getPinList()); <ide> <del> request.setAttribute("whitelist", mMasterInfo.getWhiteList()); <add> //request.setAttribute("whitelist", mMasterInfo.getWhiteList()); <ide> } <ide> }
Java
apache-2.0
594c82f666c504731d6d8bdd6ee85873ead30be7
0
MatthewTamlin/Mixtape
/* * Copyright 2017 Matthew Tamlin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.matthewtamlin.mixtape.library.databinders; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ValueAnimator; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.util.LruCache; import android.widget.ImageView; import com.matthewtamlin.java_utilities.testing.Tested; import com.matthewtamlin.mixtape.library.data.DisplayableDefaults; import com.matthewtamlin.mixtape.library.data.LibraryItem; import com.matthewtamlin.mixtape.library.data.LibraryReadException; import java.util.HashMap; import java.util.Iterator; import static com.matthewtamlin.java_utilities.checkers.NullChecker.checkNotNull; /** * Binds artwork data from LibraryItems to ImageViews. Data is cached as it is loaded to improve * future performance, and asynchronous processing is only used if data is not already cached. By * default a fade-in effect is used when artwork is bound, but this can be disabled if desired. */ @Tested(testMethod = "automated") public class ArtworkBinder implements DataBinder<LibraryItem, ImageView> { /** * A record of all bind tasks currently in progress. Each task is mapped to the target * ImageView. */ private final HashMap<ImageView, BinderTask> tasks = new HashMap<>(); /** * Stores artwork to increase performance and efficiency. */ private final LruCache<LibraryItem, Drawable> cache; /** * Supplies the default artwork. */ private final DisplayableDefaults defaults; /** * The duration to use when transitioning artwork, measured in milliseconds. */ private int fadeInDurationMs = 300; /** * The width to use when decoding artwork if the optimal dimension cannot be inferred from the * target ImageView. */ private int fallbackDecodingWidth = 300; /** * The height to use when decoding artwork if the optimal dimension cannot be inferred from the * target ImageView. */ private int fallbackDecodingHeight = 300; /** * Constructs a new ArtworkBinder. * * @param cache * stores subtitles to increase performance and efficiency, not null * @param defaults * supplies the default subtitle, not null * @throws IllegalArgumentException * if {@code cache} is null * @throws IllegalArgumentException * if {@code defaults} is null */ public ArtworkBinder(final LruCache<LibraryItem, Drawable> cache, final DisplayableDefaults defaults) { this.cache = checkNotNull(cache, "cache cannot be null."); this.defaults = checkNotNull(defaults, "defaults cannot be null."); } @Override public void bind(final ImageView imageView, final LibraryItem data) { checkNotNull(imageView, "imageView cannot be null"); // There should never be more than one task operating on the same ImageView concurrently cancel(imageView); // Create, register and start task final BinderTask task = new BinderTask(imageView, data); tasks.put(imageView, task); task.execute(); } @Override public void cancel(final ImageView imageView) { final AsyncTask existingTask = tasks.get(imageView); if (existingTask != null) { existingTask.cancel(false); tasks.remove(imageView); } } @Override public void cancelAll() { final Iterator<ImageView> imageViewIterator = tasks.keySet().iterator(); while (imageViewIterator.hasNext()) { final AsyncTask existingTask = tasks.get(imageViewIterator.next()); if (existingTask != null) { existingTask.cancel(false); imageViewIterator.remove(); } } } /** * @return the cache used to store artwork, not null */ public LruCache<LibraryItem, Drawable> getCache() { return cache; } /** * @return the default artwork supplier, not null */ public DisplayableDefaults getDefaults() { return defaults; } /** * @return the duration used when fading in artwork */ public int getFadeInDurationMs() { return fadeInDurationMs; } /** * Sets the duration to use when fading in artwork. * * @param durationMs * the duration to use, measured in milliseconds, not less than zero */ public void setFadeInDurationMs(final int durationMs) { fadeInDurationMs = durationMs; } /** * @return the width dimension to use when decoding artwork if the optimal dimension cannot be * inferred from the target ImageView */ public int getFallbackDecodingWidth() { return fallbackDecodingWidth; } /** * Sets the width to use when decoding artwork if the target ImageView cannot return its * dimensions. */ public void setFallbackDecodingWidth(final int width) { this.fallbackDecodingWidth = width; } /** * @return the height dimension to use when decoding artwork if the optimal dimension cannot be * inferred from the target ImageView */ public int getFallbackDecodingHeight() { return fallbackDecodingHeight; } /** * Sets the height to use when decoding artwork if the target ImageView cannot return its * dimensions. */ public void setFallbackDecodingHeight(final int height) { this.fallbackDecodingHeight = height; } /** * Task for asynchronously loading data and binding it to the UI when available. */ private class BinderTask extends AsyncTask<Void, Void, Drawable> { /** * The ImageView to bind data to. */ private final ImageView imageView; /** * The LibraryItem to source the artwork from. */ private final LibraryItem data; /** * The width to use when decoding the artwork, measured in pixels. */ private int imageWidth; /** * The height to use when decoding the artwork, measured in pixels. */ private int imageHeight; /** * Constructs a new BinderTask. * * @param imageView * the ImageView to bind data to, not null * @param data * the LibraryItem to source the artwork from * @throws IllegalArgumentException * if {@code imageView} is null */ public BinderTask(final ImageView imageView, final LibraryItem data) { this.imageView = checkNotNull(imageView, "imageView cannot be null"); this.data = data; } @Override public void onPreExecute() { if (!isCancelled()) { imageView.setImageDrawable(null); // Read the dimensions from the image view and select decoding values final int viewWidth = imageView.getWidth(); final int viewHeight = imageView.getHeight(); imageWidth = viewWidth == 0 ? fallbackDecodingWidth : viewWidth; imageHeight = viewHeight == 0 ? fallbackDecodingHeight : viewHeight; } } @Override public Drawable doInBackground(final Void... params) { if (isCancelled() || data == null) { return null; } final Drawable cachedArtwork = cache.get(data); if (cachedArtwork == null) { try { final Drawable loadedArtwork = data.getArtwork(imageWidth, imageHeight); if (loadedArtwork != null) { cache.put(data, loadedArtwork); } return loadedArtwork; } catch (final LibraryReadException e) { return defaults.getArtwork(); } } else { return cachedArtwork; } } @Override public void onPostExecute(final Drawable artwork) { // Skip the animation if it isn't necessary if (fadeInDurationMs <= 0 || artwork == null) { if (!isCancelled()) { imageView.setImageDrawable(null); // Resets view imageView.setImageDrawable(artwork); } } else { // Animation to fade in from fully invisible to fully visible final ValueAnimator fadeInAnimation = ValueAnimator.ofFloat(0, 1); // When the animations starts, bind the artwork but make it invisible fadeInAnimation.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(final Animator animation) { // If the task has been cancelled, it must not modify the UI if (!isCancelled()) { imageView.setAlpha(0f); //imageView.setImageDrawable(null); // Resets ensures image changes imageView.setImageDrawable(artwork); } } @Override public void onAnimationCancel(final Animator animation) { imageView.setAlpha(1f); imageView.setImageDrawable(null); } }); // As the animation progresses, fade-in the artwork by changing the transparency fadeInAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(final ValueAnimator animation) { // If the task has been cancelled, the animation must also be cancelled if (isCancelled()) { fadeInAnimation.cancel(); } else { final Float value = (Float) animation.getAnimatedValue(); imageView.setAlpha(value); } } }); fadeInAnimation.setDuration(fadeInDurationMs); fadeInAnimation.start(); } } } }
library/src/main/java/com/matthewtamlin/mixtape/library/databinders/ArtworkBinder.java
/* * Copyright 2017 Matthew Tamlin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.matthewtamlin.mixtape.library.databinders; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ValueAnimator; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.util.LruCache; import android.widget.ImageView; import com.matthewtamlin.java_utilities.testing.Tested; import com.matthewtamlin.mixtape.library.data.DisplayableDefaults; import com.matthewtamlin.mixtape.library.data.LibraryItem; import com.matthewtamlin.mixtape.library.data.LibraryReadException; import java.util.HashMap; import java.util.Iterator; import static com.matthewtamlin.java_utilities.checkers.NullChecker.checkNotNull; /** * Binds artwork data from LibraryItems to ImageViews. Data is cached as it is loaded to improve * future performance, and asynchronous processing is only used if data is not already cached. By * default a fade-in effect is used when artwork is bound, but this can be disabled if desired. */ @Tested(testMethod = "automated") public class ArtworkBinder implements DataBinder<LibraryItem, ImageView> { /** * A record of all bind tasks currently in progress. Each task is mapped to the target * ImageView. */ private final HashMap<ImageView, BinderTask> tasks = new HashMap<>(); /** * Stores artwork to increase performance and efficiency. */ private final LruCache<LibraryItem, Drawable> cache; /** * Supplies the default artwork. */ private final DisplayableDefaults defaults; /** * The duration to use when transitioning artwork, measured in milliseconds. */ private int fadeInDurationMs = 300; /** * The width to use when decoding artwork if the optimal dimension cannot be inferred from the * target ImageView. */ private int fallbackDecodingWidth = 300; /** * The height to use when decoding artwork if the optimal dimension cannot be inferred from the * target ImageView. */ private int fallbackDecodingHeight = 300; /** * Constructs a new ArtworkBinder. * * @param cache * stores subtitles to increase performance and efficiency, not null * @param defaults * supplies the default subtitle, not null * @throws IllegalArgumentException * if {@code cache} is null * @throws IllegalArgumentException * if {@code defaults} is null */ public ArtworkBinder(final LruCache<LibraryItem, Drawable> cache, final DisplayableDefaults defaults) { this.cache = checkNotNull(cache, "cache cannot be null."); this.defaults = checkNotNull(defaults, "defaults cannot be null."); } @Override public void bind(final ImageView imageView, final LibraryItem data) { checkNotNull(imageView, "imageView cannot be null"); // There should never be more than one task operating on the same ImageView concurrently cancel(imageView); // Create, register and start task final BinderTask task = new BinderTask(imageView, data); tasks.put(imageView, task); task.execute(); } @Override public void cancel(final ImageView imageView) { final AsyncTask existingTask = tasks.get(imageView); if (existingTask != null) { existingTask.cancel(false); tasks.remove(imageView); } } @Override public void cancelAll() { final Iterator<ImageView> imageViewIterator = tasks.keySet().iterator(); while (imageViewIterator.hasNext()) { final AsyncTask existingTask = tasks.get(imageViewIterator.next()); if (existingTask != null) { existingTask.cancel(false); imageViewIterator.remove(); } } } /** * @return the cache used to store artwork, not null */ public LruCache<LibraryItem, Drawable> getCache() { return cache; } /** * @return the default artwork supplier, not null */ public DisplayableDefaults getDefaults() { return defaults; } /** * @return the duration used when fading in artwork */ public int getFadeInDurationMs() { return fadeInDurationMs; } /** * Sets the duration to use when fading in artwork. * * @param durationMs * the duration to use, measured in milliseconds, not less than zero */ public void setFadeInDurationMs(final int durationMs) { fadeInDurationMs = durationMs; } /** * @return the width dimension to use when decoding artwork if the optimal dimension cannot be * inferred from the target ImageView */ public int getFallbackDecodingWidth() { return fallbackDecodingWidth; } /** * Sets the width to use when decoding artwork if the target ImageView cannot return its * dimensions. */ public void setFallbackDecodingWidth(final int width) { this.fallbackDecodingWidth = width; } /** * @return the height dimension to use when decoding artwork if the optimal dimension cannot be * inferred from the target ImageView */ public int getFallbackDecodingHeight() { return fallbackDecodingHeight; } /** * Sets the height to use when decoding artwork if the target ImageView cannot return its * dimensions. */ public void setFallbackDecodingHeight(final int height) { this.fallbackDecodingHeight = height; } /** * Task for asynchronously loading data and binding it to the UI when available. */ private class BinderTask extends AsyncTask<Void, Void, Drawable> { /** * The ImageView to bind data to. */ private final ImageView imageView; /** * The LibraryItem to source the artwork from. */ private final LibraryItem data; /** * The width to use when decoding the artwork, measured in pixels. */ private int imageWidth; /** * The height to use when decoding the artwork, measured in pixels. */ private int imageHeight; /** * Constructs a new BinderTask. * * @param imageView * the ImageView to bind data to, not null * @param data * the LibraryItem to source the artwork from * @throws IllegalArgumentException * if {@code imageView} is null */ public BinderTask(final ImageView imageView, final LibraryItem data) { this.imageView = checkNotNull(imageView, "imageView cannot be null"); this.data = data; } @Override public void onPreExecute() { if (!isCancelled()) { imageView.setImageDrawable(null); // Read the dimensions from the image view and select decoding values final int viewWidth = imageView.getWidth(); final int viewHeight = imageView.getHeight(); imageWidth = viewWidth == 0 ? fallbackDecodingWidth : viewWidth; imageHeight = viewHeight == 0 ? fallbackDecodingHeight : viewHeight; } } @Override public Drawable doInBackground(final Void... params) { if (isCancelled() || data == null) { return null; } final Drawable cachedArtwork = cache.get(data); if (cachedArtwork == null) { try { final Drawable loadedArtwork = data.getArtwork(imageWidth, imageHeight); cache.put(data, loadedArtwork); return loadedArtwork; } catch (final LibraryReadException e) { return defaults.getArtwork(); } } else { return cachedArtwork; } } @Override public void onPostExecute(final Drawable artwork) { // Skip the animation if it isn't necessary if (fadeInDurationMs <= 0 || artwork == null) { if (!isCancelled()) { imageView.setImageDrawable(null); // Resets view imageView.setImageDrawable(artwork); } } else { // Animation to fade in from fully invisible to fully visible final ValueAnimator fadeInAnimation = ValueAnimator.ofFloat(0, 1); // When the animations starts, bind the artwork but make it invisible fadeInAnimation.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(final Animator animation) { // If the task has been cancelled, it must not modify the UI if (!isCancelled()) { imageView.setAlpha(0f); //imageView.setImageDrawable(null); // Resets ensures image changes imageView.setImageDrawable(artwork); } } @Override public void onAnimationCancel(final Animator animation) { imageView.setAlpha(1f); imageView.setImageDrawable(null); } }); // As the animation progresses, fade-in the artwork by changing the transparency fadeInAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(final ValueAnimator animation) { // If the task has been cancelled, the animation must also be cancelled if (isCancelled()) { fadeInAnimation.cancel(); } else { final Float value = (Float) animation.getAnimatedValue(); imageView.setAlpha(value); } } }); fadeInAnimation.setDuration(fadeInDurationMs); fadeInAnimation.start(); } } } }
Added null check on loaded artwork
library/src/main/java/com/matthewtamlin/mixtape/library/databinders/ArtworkBinder.java
Added null check on loaded artwork
<ide><path>ibrary/src/main/java/com/matthewtamlin/mixtape/library/databinders/ArtworkBinder.java <ide> if (cachedArtwork == null) { <ide> try { <ide> final Drawable loadedArtwork = data.getArtwork(imageWidth, imageHeight); <del> cache.put(data, loadedArtwork); <add> <add> if (loadedArtwork != null) { <add> cache.put(data, loadedArtwork); <add> } <add> <ide> return loadedArtwork; <ide> } catch (final LibraryReadException e) { <ide> return defaults.getArtwork();
JavaScript
mit
36402f2331770ea903a378e09248b3fa99d4e645
0
ccxt/ccxt,ccxt/ccxt,ccxt/ccxt,ccxt/ccxt,ccxt/ccxt
'use strict'; // --------------------------------------------------------------------------- const Exchange = require ('./base/Exchange'); const { ExchangeError, ArgumentsRequired, InsufficientFunds, OrderNotFound, InvalidOrder, AuthenticationError, PermissionDenied, BadRequest } = require ('./base/errors'); // --------------------------------------------------------------------------- module.exports = class bitrue extends Exchange { describe () { return this.deepExtend (super.describe (), { 'id': 'bitrue', 'name': 'Bitrue', 'countries': ['US'], 'version': 'v1', 'rateLimit': 3000, 'urls': { 'logo': 'https://www.bitrue.com/includes/assets/346c710f38975f71fa8ea90f9f7457a3.svg', 'api': 'https://www.bitrue.com/api', 'www': 'https://bitrue.com', 'doc': 'https://github.com/Bitrue/bitrue-official-api-docs', 'referral': 'https://www.bitrue.com/activity/task/task-landing?inviteCode=TAEZWW&cn=900000', }, 'has': { 'fetchMarkets': true, 'fetchCurrencies': false, 'fetchTicker': true, 'fetchTickers': true, 'fetchOrderBook': true, 'fetchOrderBooks': false, 'fetchTrades': true, 'fetchTradingLimits': false, 'fetchTradingFees': false, 'fetchAllTradingFees': false, 'fetchFundingFees': false, 'fetchTime': true, 'fetchOrder': true, 'fetchOrders': true, 'fetchOpenOrders': true, 'fetchClosedOrders': true, 'fetchBalance': true, 'createMarketOrder': true, 'createOrder': true, 'cancelOrder': true, 'cancelOrders': false, 'cancelAllOrders': false, }, 'timeframes': { '1m': '1m', '5m': '5m', '15m': '15m', '30m': '30m', '1h': '1h', '4h': '4h', '12h': '12h', '1d': '1d', '1w': '1w', }, 'api': { 'public': { 'get': [ 'exchangeInfo', 'ticker/24hr', 'ticker/24hr', 'depth', 'trades', 'time', ], }, 'private': { 'get': [ 'account', 'order', 'openOrders', 'myTrades', 'allOrders', ], 'post': [ 'order', ], 'delete': [ 'order', ], }, }, 'fees': { 'trading': { 'tierBased': false, 'percentage': true, 'maker': 0.1 / 100, 'taker': 0.1 / 100, }, }, 'commonCurrencies': { 'PLA': 'Plair', }, 'options': { 'timeDifference': undefined, // the difference between system clock and Bitrue clock, normally about 57 seconds 'adjustForTimeDifference': true, }, 'exceptions': { 'codes': { '-1': BadRequest, '-2': BadRequest, '1001': BadRequest, '1004': ArgumentsRequired, '1006': AuthenticationError, '1008': AuthenticationError, '1010': AuthenticationError, '1011': PermissionDenied, '2001': AuthenticationError, '2002': InvalidOrder, '2004': OrderNotFound, '9003': PermissionDenied, }, 'exact': { 'market does not have a valid value': BadRequest, 'side does not have a valid value': BadRequest, 'Account::AccountError: Cannot lock funds': InsufficientFunds, 'The account does not exist': AuthenticationError, }, }, }); } async fetchMarkets (params = {}) { if (this.options['adjustForTimeDifference']) { await this.loadTimeDifference (); } const request = { 'show_details': true }; const response = await this.publicGetExchangeInfo (this.extend (request, params)); const result = []; // const symbols = this.safeValue (response, 'symbols'); const markets = this.safeValue (response, 'symbols'); for (let i = 0; i < markets.length; i++) { const market = markets[i]; const id = this.safeStringLower (market, 'symbol'); const base = this.safeStringUpper (market, 'baseAsset'); const quote = this.safeStringUpper (market, 'quoteAsset'); const baseId = base.toLowerCase (); const quoteId = quote.toLowerCase (); const symbol = base + '/' + quote; const filters = this.safeValue (market, 'filters'); const price_filter = this.safeValue (filters, 0); const volume_filter = this.safeValue (filters, 1); result.push ({ 'id': id, 'symbol': symbol, 'base': base, 'quote': quote, 'baseId': baseId, 'quoteId': quoteId, 'active': true, 'info': market, 'precision': { 'amount': this.safeValue (volume_filter, 'volumeScale'), 'price': this.safeValue (price_filter, 'priceScale'), 'base': this.safeValue (volume_filter, 'volumeScale'), 'quote': this.safeValue (price_filter, 'priceScale'), }, 'limits': { 'amount': { 'min': this.safeValue (volume_filter, 'minQty'), 'max': this.safeValue (volume_filter, 'maxQty'), }, 'price': { 'min': this.safeValue (price_filter, 'minPrice'), 'max': this.safeValue (price_filter, 'maxPrice'), }, 'cost': { 'min': this.safeValue (volume_filter, 'minQty'), 'max': this.safeValue (volume_filter, 'maxQty'), }, }, }); } return result; } async fetchTicker (symbol, params = {}) { await this.loadMarkets (); const market = this.market (symbol); const request = { 'symbol': market['id'], }; const response = await this.publicGetTicker24hr (this.extend (request, params)); const data = this.safeValue (response, 0); return this.parseTicker (data, market); } async fetchTickers (symbols = undefined, params = {}) { await this.loadMarkets (); const response = await this.publicGetTicker24hr (params); // const data = this.safeValue (response, 0, []); return this.parseTickers (response, symbols); } parseTickers (rawTickers, symbols = undefined) { const tickers = []; for (let i = 0; i < rawTickers.length; i++) { tickers.push (this.parseTicker (rawTickers[i])); } return this.filterByArray (tickers, 'symbol', symbols); } parseTicker (ticker, market = undefined) { let symbol = undefined; const marketId = this.safeStringLower (ticker, 'symbol'); if (marketId in this.markets_by_id) { market = this.markets_by_id[marketId]; } if (market !== undefined) { symbol = market['symbol']; } let timestamp = this.safeTimestamp (ticker, 'closeTime'); if (timestamp === undefined || timestamp === 0) { timestamp = this.milliseconds (); } const vwap = this.safeFloat (ticker, 'weightedAvgPrice'); // response includes `volume`, but it is equal to `quoteVolume` // since e.g. BTC/USDT volume = quoteVolume ~ 30000000, we can assume it is quoteVolume let baseVolume = undefined; const quoteVolume = this.safeFloat (ticker, 'quoteVolume'); if ((quoteVolume !== undefined) && (vwap !== undefined) && (vwap > 0)) { baseVolume = quoteVolume / vwap; } return { 'symbol': symbol, 'timestamp': timestamp, 'datetime': this.iso8601 (timestamp), 'high': this.safeFloat (ticker, 'highPrice'), 'low': this.safeFloat (ticker, 'lowPrice'), 'bid': this.safeFloat (ticker, 'bidPrice'), 'bidVolume': undefined, 'ask': this.safeFloat (ticker, 'askPrice'), 'askVolume': undefined, 'vwap': vwap, 'open': this.safeFloat (ticker, 'openPrice'), 'close': this.safeFloat (ticker, 'lastPrice'), 'last': this.safeFloat (ticker, 'lastPrice'), 'previousClose': this.safeFloat (ticker, 'prevClosePrice'), 'change': this.safeFloat (ticker, 'priceChange'), 'percentage': undefined, 'average': undefined, 'baseVolume': baseVolume, 'quoteVolume': quoteVolume, 'info': ticker, }; } async fetchOrderBook (symbol, limit = undefined, params = {}) { await this.loadMarkets (); const market = this.market (symbol); const request = { 'symbol': market['id'], }; if (limit !== undefined) { request['limit'] = limit; } const response = await this.publicGetDepth (this.extend (request, params)); const orderbook = response ? response : {}; const timestamp = this.safeInteger (orderbook, 'lastUpdateId'); return this.parseOrderBook (orderbook, timestamp); } async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) { await this.loadMarkets (); const market = this.market (symbol); const request = { 'symbol': market['id'], }; if (limit !== undefined) { request['limit'] = limit; } const response = await this.publicGetTrades (this.extend (request, params)); const data = Array.isArray (response) ? response : []; return this.parseTrades (data, market, since, limit); } parseTrade (trade, market = undefined) { const side = this.safeValue (trade, 'isBuyer') ? 'buy' : 'sell'; const takerOrMaker = this.safeValue (trade, 'isMaker') ? 'maker' : 'taker'; let symbol = undefined; if (market !== undefined) { symbol = market['symbol']; } if (symbol === undefined) { if (market === undefined) { market = this.markets_by_id[this.safeStringLower (trade, 'symbol')]; } symbol = market['symbol']; } let timestamp = this.safeInteger (trade, 'time'); if (timestamp === undefined) { timestamp = this.parse8601 (this.safeString (trade, 'time')); } const price = this.safeFloat (trade, 'price'); const amount = this.safeFloat (trade, 'qty'); const cost = price * amount; return { 'info': trade, 'timestamp': timestamp, 'datetime': this.iso8601 (timestamp), 'symbol': symbol, 'id': this.safeString (trade, 'id'), 'order': undefined, 'type': 'limit', 'takerOrMaker': takerOrMaker, 'side': side, 'price': price, 'amount': amount, 'cost': cost, 'fee': undefined, }; } async loadTimeDiff () { if (this.defMillis === undefined) { await this.fetchTime (); } } async fetchTime (params = {}) { const response = await this.publicGetTime (params); const serverMillis = this.safeInteger (response, 'serverTime'); const localMillis = this.milliseconds (); this.diffMillis = serverMillis - localMillis; return serverMillis; } async fetchBalance (params = {}) { await this.loadMarkets (); const response = await this.privateGetAccount (params); const balances = this.safeValue (response, 'balances'); const result = { 'info': response, }; for (let i = 0; i < balances.length; i++) { const balance = balances[i]; const currencyId = this.safeValue (balance, 'asset'); const code = this.safeCurrencyCode (currencyId); const account = this.account (); account['free'] = this.safeFloat (balance, 'free'); account['used'] = this.safeFloat (balance, 'locked'); result[code] = account; } return this.parseBalance (result); } async createOrder (symbol, type, side, amount, price = undefined, params = {}) { await this.loadMarkets (); const market = this.market (symbol); const request = { 'symbol': market['id'], 'side': side.toUpperCase (), 'type': type.toUpperCase (), 'quantity': this.amountToPrecision (symbol, amount), }; if (type.toUpperCase () === 'LIMIT') { request['price'] = this.priceToPrecision (symbol, price); } const response = this.privatePostOrder (this.extend (request, params)); return this.parseOrder (response, market); } async fetchOrder (id, symbol = undefined, params = {}) { await this.loadMarkets (); let market = undefined; if (symbol !== undefined) { market = this.market (symbol); } const request = { 'orderId': id, 'symbol': market['id'], }; const response = this.privateGetOrder (this.extend (request, params)); const orderId = this.safeString (response, 'orderId'); if (orderId === undefined) { throw new OrderNotFound (this.id + ' could not find matching order'); } return this.parseOrder (response, market); } async fetchOpenOrders (symbol, params = {}) { await this.loadMarkets (); const market = this.market (symbol); const request = { 'symbol': market['id'], }; const response = this.privateGetOpenOrders (this.extend (request, params)); const orders = Array.isArray (response) ? response : []; const result = this.parseOrders (orders, market, undefined, undefined, params = {}); return result; } async fetchClosedOrders (symbol = undefined, start_id = undefined, limit = undefined, params = {}) { await this.loadMarkets (); const request = {}; if (symbol !== undefined) { const market = this.market (symbol); request['symbol'] = market['id']; } if (start_id !== undefined) { request['fromId'] = start_id; } if (limit !== undefined) { request['limit'] = limit; } const response = this.privateGetMyTrades (this.extend (request, params)); const trades = Array.isArray (response) ? response : []; const result = []; for (let i = 0; i < trades.length; i++) { const trade = this.parseTrade (trades[i], undefined); result.push (trade); } return result; } async fetchOrders (symbol = undefined, orderId = undefined, limit = undefined, params = {}) { if (symbol === undefined) { throw new ArgumentsRequired (this.id + ' fetchOrders() requires a symbol argument'); } await this.loadMarkets (); const market = this.market (symbol); const query = this.omit (params, 'states'); const request = { 'symbol': market['id'], }; if (orderId !== undefined) { request['orderId'] = orderId; } if (limit !== undefined) { request['limit'] = limit; } const response = this.privateGetAllOrders (this.extend (request, query)); const orders = Array.isArray (response) ? response : []; return this.parseOrders (orders, market, orderId, limit, {}); } async parseOrder (order, market = undefined) { // { // "symbol": "BATBTC", // "orderId": "194601105", // "clientOrderId": "", // "price": "0.0000216600000000", // "origQty": "155.0000000000000000", // "executedQty": "0.0000000000000000", // "cummulativeQuoteQty": "0.0000000000000000", // "status": "NEW", // "timeInForce": "", // "type": "LIMIT", // "side": "BUY", // "stopPrice": "", // "icebergQty": "", // "time": 1590637046000, // "updateTime": 1590637046000, // "isWorking": "False" // } const status = this.parseOrderStatus (this.safeValue (order, 'status')); let symbol = undefined; if (market !== undefined) { symbol = market['symbol']; } else { market = this.marketsById[this.safeString (order, 'symbol').lower ()]; } let timestamp = undefined; if ('time' in order) { timestamp = this.safeInteger (order, 'time'); } else if ('updateTime' in order) { timestamp = this.safeInteger (order, 'updateTime'); } else if ('transactTime' in order) { timestamp = this.safeInteger (order, 'transactTime'); } const executeQty = this.safeFloat (order, 'executedQty'); const cummulativeQuoteQty = this.safeFloat (order, 'cummulativeQuoteQty'); let average = undefined; if (executeQty !== undefined && cummulativeQuoteQty !== undefined) { average = (executeQty > 0) ? cummulativeQuoteQty / executeQty : 0.0; } const amount = this.safeFloat (order, 'origQty'); const remaining = (amount !== undefined && executeQty !== undefined) ? amount - executeQty : undefined; return { 'info': order, 'id': this.safeString (order, 'orderId'), 'clientOrderId': undefined, 'timestamp': timestamp, 'datetime': this.iso8601 (timestamp), 'lastTradeTimestamp': undefined, 'symbol': symbol, 'type': this.safeValue (order, 'type'), 'side': this.safeValue (order, 'side'), 'price': this.safeFloat (order, 'price'), 'average': average, 'amount': amount, 'remaining': remaining, 'filled': executeQty, 'status': status, 'cost': undefined, 'trades': undefined, 'fee': undefined, }; } async parseOrderStatus (status) { const statuses = { 'NEW': 'open', 'PARTIALLY_FILLED': 'open', 'FILLED': 'closed', 'CANCELED': 'canceled', 'PENDING_CANCEL': 'canceled', 'REJECTED': 'failed', 'EXPIRED': 'canceled', }; return this.safeString (statuses, status, status); } async cancelOrder (id, symbol = undefined, params = {}) { await this.loadMarkets (); const market = this.market (symbol); const request = { 'symbol': market['id'], 'orderId': id, }; return this.privateDeleteOrder (this.extend (request, params)); } async loadTimeDifference (params = {}) { const serverTime = await this.fetchTime (params); const after = this.milliseconds (); this.options['timeDifference'] = after - serverTime; return this.options['timeDifference']; } sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) { let url = this.urls['api'] + '/' + this.version + '/' + this.implodeParams (path, params); let query = this.omit (params, this.extractParams (path)); if (api === 'public') { if (query) { url += '?' + this.urlencode (query); } } else if (api === 'private') { this.checkRequiredCredentials (); const timestamp = (this.options['timeDifference'] !== undefined) ? (this.milliseconds () - this.options['timeDifference']) : 0; query = this.extend ({ 'timestamp': timestamp }, query); const signStr = this.urlencode (query); const signature = this.hmac (this.encode (signStr), this.encode (this.secret)); query = this.extend ({ 'signature': signature }, query); if (method === 'GET') { url += '?' + signStr + '&signature=' + signature; } else { body = signStr + '&signature=' + signature; } } headers = { 'Content-Type': 'application/json', 'X-MBX-APIKEY': this.apiKey }; return { 'url': url, 'method': method, 'body': body, 'headers': headers }; } handleErrors (code, reason, url, method, headers, body, response, requestHeaders, requestBody) { // // {"code":1011,"message":"This IP '5.228.233.138' is not allowed","data":{}} // if (response === undefined) { return; } const errorCode = this.safeString (response, 'code'); const message = this.safeString (response, 'message'); if ((errorCode !== undefined) && (errorCode !== '0')) { const feedback = this.id + ' ' + body; this.throw_exactly_matched_exception (this.exceptions['codes'], errorCode, feedback); this.throw_exactly_matched_exception (this.exceptions['exact'], message, feedback); throw new ExchangeError (response); } } };
js/bitrue.js
'use strict'; // --------------------------------------------------------------------------- const Exchange = require ('./base/Exchange'); const { ExchangeError, ArgumentsRequired, InsufficientFunds, OrderNotFound, InvalidOrder, AuthenticationError, PermissionDenied, BadRequest } = require ('./base/errors'); // --------------------------------------------------------------------------- module.exports = class bitrue extends Exchange { describe () { return this.deepExtend (super.describe (), { 'id': 'bitrue', 'name': 'Bitrue', 'countries': ['US'], 'version': 'v1', 'rateLimit': 3000, 'urls': { 'logo': 'https://www.bitrue.com/includes/assets/346c710f38975f71fa8ea90f9f7457a3.svg', 'api': 'https://www.bitrue.com/api', 'www': 'https://bitrue.com', 'doc': 'https://github.com/Bitrue/bitrue-official-api-docs', 'referral': 'https://www.bitrue.com/activity/task/task-landing?inviteCode=TAEZWW&cn=900000', }, 'has': { 'fetchMarkets': true, 'fetchCurrencies': false, 'fetchTicker': true, 'fetchTickers': true, 'fetchOrderBook': true, 'fetchOrderBooks': false, 'fetchTrades': true, 'fetchTradingLimits': false, 'fetchTradingFees': false, 'fetchAllTradingFees': false, 'fetchFundingFees': false, 'fetchTime': true, 'fetchOrder': true, 'fetchOrders': true, 'fetchOpenOrders': true, 'fetchClosedOrders': true, 'fetchBalance': true, 'createMarketOrder': true, 'createOrder': true, 'cancelOrder': true, 'cancelOrders': false, 'cancelAllOrders': false, }, 'timeframes': { '1m': '1m', '5m': '5m', '15m': '15m', '30m': '30m', '1h': '1h', '4h': '4h', '12h': '12h', '1d': '1d', '1w': '1w', }, 'api': { 'public': { 'get': [ 'exchangeInfo', 'ticker/24hr', 'ticker/24hr', 'depth', 'trades', 'time', ], }, 'private': { 'get': [ 'account', 'order', 'openOrders', 'myTrades', 'allOrders', ], 'post': [ 'order', ], 'delete': [ 'order', ], }, }, 'fees': { 'trading': { 'tierBased': false, 'percentage': true, 'maker': 0.1 / 100, 'taker': 0.1 / 100, }, }, 'commonCurrencies': { 'PLA': 'Plair', }, 'options': { 'timeDifference': undefined, // the difference between system clock and Bitrue clock, normally about 57 seconds 'adjustForTimeDifference': true, }, 'exceptions': { 'codes': { '-1': BadRequest, '-2': BadRequest, '1001': BadRequest, '1004': ArgumentsRequired, '1006': AuthenticationError, '1008': AuthenticationError, '1010': AuthenticationError, '1011': PermissionDenied, '2001': AuthenticationError, '2002': InvalidOrder, '2004': OrderNotFound, '9003': PermissionDenied, }, 'exact': { 'market does not have a valid value': BadRequest, 'side does not have a valid value': BadRequest, 'Account::AccountError: Cannot lock funds': InsufficientFunds, 'The account does not exist': AuthenticationError, }, }, }); } async fetchMarkets (params = {}) { if (this.options['adjustForTimeDifference']) { await this.loadTimeDifference (); } const request = { 'show_details': true }; const response = await this.publicGetExchangeInfo (this.extend (request, params)); const result = []; // const symbols = this.safeValue (response, 'symbols'); const markets = this.safeValue (response, 'symbols'); for (let i = 0; i < markets.length; i++) { const market = markets[i]; const id = this.safeStringLower (market, 'symbol'); const base = this.safeStringUpper (market, 'baseAsset'); const quote = this.safeStringUpper (market, 'quoteAsset'); const baseId = base.toLowerCase (); const quoteId = quote.toLowerCase (); const symbol = base + '/' + quote; const filters = this.safeValue (market, 'filters'); const price_filter = this.safeValue (filters, 0); const volume_filter = this.safeValue (filters, 1); result.push ({ 'id': id, 'symbol': symbol, 'base': base, 'quote': quote, 'baseId': baseId, 'quoteId': quoteId, 'active': true, 'info': market, 'precision': { 'amount': this.safeValue (volume_filter, 'volumeScale'), 'price': this.safeValue (price_filter, 'priceScale'), 'base': this.safeValue (volume_filter, 'volumeScale'), 'quote': this.safeValue (price_filter, 'priceScale'), }, 'limits': { 'amount': { 'min': this.safeValue (volume_filter, 'minQty'), 'max': this.safeValue (volume_filter, 'maxQty'), }, 'price': { 'min': this.safeValue (price_filter, 'minPrice'), 'max': this.safeValue (price_filter, 'maxPrice'), }, 'cost': { 'min': this.safeValue (volume_filter, 'minQty'), 'max': this.safeValue (volume_filter, 'maxQty'), }, }, }); } return result; } async fetchTicker (symbol, params = {}) { await this.loadMarkets (); const market = this.market (symbol); const request = { 'symbol': market['id'], }; const response = await this.publicGetTicker24hr (this.extend (request, params)); const data = this.safeValue (response, 0); return this.parseTicker (data, market); } async fetchTickers (symbols = undefined, params = {}) { await this.loadMarkets (); const response = await this.publicGetTicker24hr (params); // const data = this.safeValue (response, 0, []); return this.parseTickers (response, symbols); } parseTickers (rawTickers, symbols = undefined) { const tickers = []; for (let i = 0; i < rawTickers.length; i++) { tickers.push (this.parseTicker (rawTickers[i])); } return this.filterByArray (tickers, 'symbol', symbols); } parseTicker (ticker, market = undefined) { let symbol = undefined; const marketId = this.safeStringLower (ticker, 'symbol'); if (marketId in this.markets_by_id) { market = this.markets_by_id[marketId]; } if (market !== undefined) { symbol = market['symbol']; } let timestamp = this.safeTimestamp (ticker, 'closeTime'); if (timestamp === undefined || timestamp === 0) { timestamp = this.milliseconds (); } const vwap = this.safeFloat (ticker, 'weightedAvgPrice'); // response includes `volume`, but it is equal to `quoteVolume` // since e.g. BTC/USDT volume = quoteVolume ~ 30000000, we can assume it is quoteVolume let baseVolume = undefined; const quoteVolume = this.safeFloat (ticker, 'quoteVolume'); if ((quoteVolume !== undefined) && (vwap !== undefined) && (vwap > 0)) { baseVolume = quoteVolume / vwap; } return { 'symbol': symbol, 'timestamp': timestamp, 'datetime': this.iso8601 (timestamp), 'high': this.safeFloat (ticker, 'highPrice'), 'low': this.safeFloat (ticker, 'lowPrice'), 'bid': this.safeFloat (ticker, 'bidPrice'), 'bidVolume': undefined, 'ask': this.safeFloat (ticker, 'askPrice'), 'askVolume': undefined, 'vwap': vwap, 'open': this.safeFloat (ticker, 'openPrice'), 'close': this.safeFloat (ticker, 'lastPrice'), 'last': this.safeFloat (ticker, 'lastPrice'), 'previousClose': this.safeFloat (ticker, 'prevClosePrice'), 'change': this.safeFloat (ticker, 'priceChange'), 'percentage': undefined, 'average': undefined, 'baseVolume': baseVolume, 'quoteVolume': quoteVolume, 'info': ticker, }; } async fetchOrderBook (symbol, limit = undefined, params = {}) { await this.loadMarkets (); const market = this.market (symbol); const request = { 'symbol': market['id'], }; if (limit !== undefined) { request['limit'] = limit; } const response = await this.publicGetDepth (this.extend (request, params)); const orderbook = response ? response : {}; const timestamp = this.safeInteger (orderbook, 'lastUpdateId'); return this.parseOrderBook (orderbook, timestamp); } async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) { await this.loadMarkets (); const market = this.market (symbol); const request = { 'symbol': market['id'], }; if (limit !== undefined) { request['limit'] = limit; } const response = await this.publicGetTrades (this.extend (request, params)); const data = Array.isArray (response) ? response : []; return this.parseTrades (data, market, since, limit); } parseTrade (trade, market = undefined) { const side = this.safeValue (trade, 'isBuyer') ? 'buy' : 'sell'; const takerOrMaker = this.safeValue (trade, 'isMaker') ? 'maker' : 'taker'; let symbol = undefined; if (market !== undefined) { symbol = market['symbol']; } if (symbol === undefined) { if (market === undefined) { market = this.markets_by_id[this.safeStringLower (trade, 'symbol')]; } symbol = market['symbol']; } let timestamp = this.safeInteger (trade, 'time'); if (timestamp === undefined) { timestamp = this.parse8601 (this.safeString (trade, 'time')); } const price = this.safeFloat (trade, 'price'); const amount = this.safeFloat (trade, 'qty'); const cost = price * amount; return { 'info': trade, 'timestamp': timestamp, 'datetime': this.iso8601 (timestamp), 'symbol': symbol, 'id': this.safeString (trade, 'id'), 'order': undefined, 'type': 'limit', 'takerOrMaker': takerOrMaker, 'side': side, 'price': price, 'amount': amount, 'cost': cost, 'fee': undefined, }; } async loadTimeDiff () { if (this.defMillis === undefined) { await this.fetchTime (); } } async fetchTime (params = {}) { const response = await this.publicGetTime (params); const serverMillis = this.safeInteger (response, 'serverTime'); const localMillis = this.milliseconds (); this.diffMillis = serverMillis - localMillis; return serverMillis; } async fetchBalance (params = {}) { await this.loadMarkets (); const response = await this.privateGetAccount (params); const balances = this.safeValue (response, 'balances'); const result = { 'info': response, }; for (let i = 0; i < balances.length; i++) { const balance = balances[i]; const currencyId = this.safeValue (balance, 'asset'); const code = this.safeCurrencyCode (currencyId); const account = this.account (); account['free'] = this.safeFloat (balance, 'free'); account['used'] = this.safeFloat (balance, 'locked'); result[code] = account; } return this.parseBalance (result); } async createOrder (symbol, type, side, amount, price = undefined, params = {}) { await this.loadMarkets (); const market = this.market (symbol); const request = { 'symbol': market['id'], 'side': side.toUpperCase (), 'type': type.toUpperCase (), 'quantity': this.amountToPrecision (symbol, amount), }; if (type.toUpperCase () === 'LIMIT') { request['price'] = this.priceToPrecision (symbol, price); } const response = this.privatePostOrder (this.extend (request, params)); return this.parseOrder (response, market); } async fetchOrder (id, symbol = undefined, params = {}) { await this.loadMarkets (); let market = undefined; if (symbol !== undefined) { market = this.market (symbol); } const request = { 'orderId': id, 'symbol': market['id'], }; const response = this.privateGetOrder (this.extend (request, params)); const orderId = this.safeString (response, 'orderId'); if (orderId === undefined) { throw new OrderNotFound (this.id + ' could not find matching order'); } return this.parseOrder (response, market); } async fetchOpenOrders (symbol, params = {}) { await this.loadMarkets (); const market = this.market (symbol); const request = { 'symbol': market['id'], }; const response = this.privateGetOpenOrders (this.extend (request, params)); const orders = Array.isArray (response) ? response : []; const result = this.parseOrders (orders, market, undefined, undefined, params = {}); return result; } async fetchClosedOrders (symbol = undefined, start_id = undefined, limit = undefined, params = {}) { await this.loadMarkets (); const request = {}; if (symbol !== undefined) { const market = this.market (symbol); request['symbol'] = market['id']; } if (start_id !== undefined) { request['fromId'] = start_id; } if (limit !== undefined) { request['limit'] = limit; } const response = this.privateGetMyTrades (this.extend (request, params)); const trades = Array.isArray (response) ? response : []; const result = []; for (let i = 0; i < trades.length; i++) { const trade = this.parseTrade (trades[i], undefined); result.push (trade); } return result; } async fetchOrders (symbol = undefined, orderId = undefined, limit = undefined, params = {}) { if (symbol === undefined) { throw new ArgumentsRequired (this.id + ' fetchOrders() requires a symbol argument'); } await this.loadMarkets (); const market = this.market (symbol); const states = this.safeValue (params, 'states', []); // 'NEW', 'PARTIALLY_FILLED', 'CANCELED', 'FILLED' const query = this.omit (params, 'states'); let request = { 'symbol': market['id'], }; if (orderId !== undefined) { request['orderId'] = orderId; } if (limit !== undefined) { request['limit'] = limit; } const response = this.privateGetAllOrders (this.extend (request, query)); const orders = Array.isArray (response) ? response : []; return this.parseOrders (orders, market, orderId, limit, {}); } async parseOrder (order, market = undefined) { // { // "symbol": "BATBTC", // "orderId": "194601105", // "clientOrderId": "", // "price": "0.0000216600000000", // "origQty": "155.0000000000000000", // "executedQty": "0.0000000000000000", // "cummulativeQuoteQty": "0.0000000000000000", // "status": "NEW", // "timeInForce": "", // "type": "LIMIT", // "side": "BUY", // "stopPrice": "", // "icebergQty": "", // "time": 1590637046000, // "updateTime": 1590637046000, // "isWorking": "False" // } const status = this.parseOrderStatus (this.safeValue (order, 'status')); let symbol = undefined; if (market !== undefined) { symbol = market['symbol']; } else { market = this.marketsById[this.safeString (order, 'symbol').lower ()]; } let timestamp = undefined; if ('time' in order) { timestamp = this.safeInteger (order, 'time'); } else if ('updateTime' in order) { timestamp = this.safeInteger (order, 'updateTime'); } else if ('transactTime' in order) { timestamp = this.safeInteger (order, 'transactTime'); } const executeQty = this.safeFloat (order, 'executedQty'); const cummulativeQuoteQty = this.safeFloat (order, 'cummulativeQuoteQty'); let average = undefined; if (executeQty !== undefined && cummulativeQuoteQty !== undefined) { average = (executeQty > 0) ? cummulativeQuoteQty / executeQty : 0.0; } const amount = this.safeFloat (order, 'origQty'); const remaining = (amount !== undefined && executeQty !== undefined) ? amount - executeQty : undefined; return { 'info': order, 'id': this.safeString (order, 'orderId'), 'clientOrderId': undefined, 'timestamp': timestamp, 'datetime': this.iso8601 (timestamp), 'lastTradeTimestamp': undefined, 'symbol': symbol, 'type': this.safeValue (order, 'type'), 'side': this.safeValue (order, 'side'), 'price': this.safeFloat (order, 'price'), 'average': average, 'amount': amount, 'remaining': remaining, 'filled': executeQty, 'status': status, 'cost': undefined, 'trades': undefined, 'fee': undefined, }; } async parseOrderStatus (status) { const statuses = { 'NEW': 'open', 'PARTIALLY_FILLED': 'open', 'FILLED': 'closed', 'CANCELED': 'canceled', 'PENDING_CANCEL': 'canceled', 'REJECTED': 'failed', 'EXPIRED': 'canceled', }; return this.safeString (statuses, status, status); } async cancelOrder (id, symbol = undefined, params = {}) { await this.loadMarkets (); const market = this.market (symbol); const request = { 'symbol': market['id'], 'orderId': id, }; return this.privateDeleteOrder (this.extend (request, params)); } async loadTimeDifference (params = {}) { const serverTime = await this.fetchTime (params); const after = this.milliseconds (); this.options['timeDifference'] = after - serverTime; return this.options['timeDifference']; } sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) { let url = this.urls['api'] + '/' + this.version + '/' + this.implodeParams (path, params); let query = this.omit (params, this.extractParams (path)); if (api === 'public') { if (query) { url += '?' + this.urlencode (query); } } else if (api === 'private') { this.checkRequiredCredentials (); const timestamp = (this.options['timeDifference'] !== undefined) ? (this.milliseconds () - this.options['timeDifference']) : 0; query = this.extend ({ 'timestamp': timestamp }, query); const signStr = this.urlencode (query); const signature = this.hmac (this.encode (signStr), this.encode (this.secret)); query = this.extend ({ 'signature': signature }, query); if (method === 'GET') { url += '?' + signStr + '&signature=' + signature; } else { body = signStr + '&signature=' + signature; } } headers = { 'Content-Type': 'application/json', 'X-MBX-APIKEY': this.apiKey }; return { 'url': url, 'method': method, 'body': body, 'headers': headers }; } handleErrors (code, reason, url, method, headers, body, response, requestHeaders, requestBody) { // // {"code":1011,"message":"This IP '5.228.233.138' is not allowed","data":{}} // if (response === undefined) { return; } const errorCode = this.safeString (response, 'code'); const message = this.safeString (response, 'message'); if ((errorCode !== undefined) && (errorCode !== '0')) { const feedback = this.id + ' ' + body; this.throw_exactly_matched_exception (this.exceptions['codes'], errorCode, feedback); this.throw_exactly_matched_exception (this.exceptions['exact'], message, feedback); throw new ExchangeError (response); } } };
Fix lint errors
js/bitrue.js
Fix lint errors
<ide><path>s/bitrue.js <ide> } <ide> await this.loadMarkets (); <ide> const market = this.market (symbol); <del> const states = this.safeValue (params, 'states', []); // 'NEW', 'PARTIALLY_FILLED', 'CANCELED', 'FILLED' <ide> const query = this.omit (params, 'states'); <del> let request = { <add> const request = { <ide> 'symbol': market['id'], <ide> }; <ide> if (orderId !== undefined) {
Java
unlicense
b22cd1df4cc9c45180c42f17e0f010766a06f53e
0
PankaJJakhar/Algorithms
import java.math.BigInteger; import java.util.HashMap; import java.util.Scanner; /** * Created by pankajjakhar on 23/12/17. * */ public class ExtraLongFactorials { private static Scanner scanner; private static int N; private static HashMap<Integer, BigInteger> numberToFactorialValueMap; private static int iterationsCount; public static void main(String[] args) { process(); } private static void process() { iterationsCount = 0; scanner = new Scanner(System.in); numberToFactorialValueMap = new HashMap<Integer, BigInteger>(); System.out.print("Enter the number: "); N = scanner.nextInt(); BigInteger result = calculateFactorial(N); //System.out.println(result.toString()); System.out.printf("\nFactorial of %d: " + result.toString(), N); //System.out.printf("\nIterations Count: %d", iterationsCount); } private static BigInteger calculateFactorial(int number) { if(number == 0 || number == 1) return BigInteger.valueOf(number); if(numberToFactorialValueMap.containsKey(number)) return numberToFactorialValueMap.get(number); iterationsCount++; BigInteger result = (BigInteger.valueOf(number)).multiply(calculateFactorial(number - 1)); numberToFactorialValueMap.put(number, result); return result; } }
src/com/master/jakhar/general/ExtraLongFactorials.java
import java.math.BigInteger; import java.util.HashMap; import java.util.Scanner; /** * Created by pankajjakhar on 23/12/17. * */ public class ExtraLongFactorials { private static Scanner mScanner; private static int N; private static HashMap<Integer, BigInteger> numberToFactorialValueMap; private static int iterationsCount; public static void main(String[] args) { process(); } private static void process() { iterationsCount = 0; mScanner = new Scanner(System.in); numberToFactorialValueMap = new HashMap<Integer, BigInteger>(); System.out.print("Enter the number: "); N = mScanner.nextInt(); BigInteger result = calculateFactorial(N); //System.out.println(result.toString()); System.out.printf("\nFactorial of %d: " + result.toString(), N); //System.out.printf("\nIterations Count: %d", iterationsCount); } private static BigInteger calculateFactorial(int number) { if(number == 0 || number == 1) return BigInteger.valueOf(number); if(numberToFactorialValueMap.containsKey(number)) return numberToFactorialValueMap.get(number); iterationsCount++; BigInteger result = (BigInteger.valueOf(number)).multiply(calculateFactorial(number - 1)); numberToFactorialValueMap.put(number, result); return result; } }
Changes in ExtraLongFactorials
src/com/master/jakhar/general/ExtraLongFactorials.java
Changes in ExtraLongFactorials
<ide><path>rc/com/master/jakhar/general/ExtraLongFactorials.java <ide> * <ide> */ <ide> public class ExtraLongFactorials { <del> private static Scanner mScanner; <add> private static Scanner scanner; <ide> private static int N; <ide> private static HashMap<Integer, BigInteger> numberToFactorialValueMap; <ide> private static int iterationsCount; <ide> <ide> private static void process() { <ide> iterationsCount = 0; <del> mScanner = new Scanner(System.in); <add> scanner = new Scanner(System.in); <ide> numberToFactorialValueMap = new HashMap<Integer, BigInteger>(); <ide> System.out.print("Enter the number: "); <del> N = mScanner.nextInt(); <add> N = scanner.nextInt(); <ide> BigInteger result = calculateFactorial(N); <ide> //System.out.println(result.toString()); <ide> System.out.printf("\nFactorial of %d: " + result.toString(), N);
Java
apache-2.0
2d5752990e6824d6b03797d5f264e86ed126ea08
0
tingletech/jena-joseki,tingletech/jena-joseki,tingletech/jena-joseki
/* * (c) Copyright 2005, 2006, 2007 Hewlett-Packard Development Company, LP * All rights reserved. * [See end of file] */ package org.joseki; import com.hp.hpl.jena.shared.JenaException; import com.hp.hpl.jena.shared.NotFoundException; import com.hp.hpl.jena.util.FileManager; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class Dispatcher { private static Log log = LogFactory.getLog(Dispatcher.class) ; static Configuration configuration = null ; static ServiceRegistry serviceRegistry = null ; //Dispatcher dispatcher = new Dispatcher() ; public static void dispatch(String serviceURI, Request request, Response response) throws ExecutionException { if ( serviceRegistry == null ) { log.fatal("Service registry not initialized") ; throw new ExecutionException(ReturnCodes.rcInternalError, "Service registry not initialized") ; } try { Service service = serviceRegistry.find(serviceURI) ; if ( service == null ) { log.info("404 - Service <"+serviceURI+"> not found") ; throw new ExecutionException(ReturnCodes.rcNoSuchURI, "Service <"+serviceURI+"> not found") ; } if ( !service.isAvailable() ) { log.info("Service is not available") ; throw new ExecutionException(ReturnCodes.rcServiceUnavailable, "Service <"+serviceURI+"> unavailable") ; } service.exec(request, response) ; response.sendResponse() ; } catch (ExecutionException ex) { response.sendException(ex) ; return ; } } // This method contains the pragmatic algorithm to determine the configuration URI. // // In this order (i.e. specific to general) to find the filename: // System property org.joseki.rdfserver.config => a URI. // Resource: // System property: jena.rdfserver.modelmap => file name // Webapp init parameter: jena.rdfserver.modelmap // Servlet init parameter: jena.rdfserver.modelmap // and then the file is loaded. public static void initServiceRegistry() { initServiceRegistry(FileManager.get()) ; } public static void initServiceRegistry(FileManager fileManager) { initServiceRegistry(fileManager, null) ; } public static void initServiceRegistry(String configURI) { initServiceRegistry(FileManager.get(), configURI) ; } public static void initServiceRegistry(FileManager fileManager, String configURI) { if ( configURI == null ) configURI = System.getProperty(Joseki.configurationFileProperty, RDFServer.defaultConfigFile) ; setConfiguration(fileManager, configURI) ; } public static synchronized void setConfiguration(FileManager fileManager, String configURI) { if ( serviceRegistry != null ) { log.debug("Service registry already initialized") ; return ; } if ( configURI == null ) { log.fatal("Null for configuration URI") ; return ; } // Already squirreled away somewhere? serviceRegistry = (ServiceRegistry)Registry.find(RDFServer.ServiceRegistryName) ; if ( serviceRegistry != null ) { log.debug("Using globally registered service registry") ; return ; } // Better find one. ServiceRegistry tmp = new ServiceRegistry() ; try { configuration = new Configuration(fileManager, configURI, tmp) ; log.info("Loaded data source configuration: " + configURI); } catch (NotFoundException ex) { throw new ConfigurationErrorException("Not found: "+ex.getMessage(), ex) ; //return false; } catch (JenaException rdfEx) { // Trouble processing a configuration throw new ConfigurationErrorException("RDF Exception: "+rdfEx.getMessage(), rdfEx) ; //return false ; } Registry.add(RDFServer.ServiceRegistryName, tmp) ; serviceRegistry = (ServiceRegistry)Registry.find(RDFServer.ServiceRegistryName) ; } } /* * (c) Copyright 2005, 2006, 2007 Hewlett-Packard Development Company, LP * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
src/org/joseki/Dispatcher.java
/* * (c) Copyright 2005, 2006, 2007 Hewlett-Packard Development Company, LP * All rights reserved. * [See end of file] */ package org.joseki; import com.hp.hpl.jena.rdf.model.RDFException; import com.hp.hpl.jena.shared.NotFoundException; import com.hp.hpl.jena.util.FileManager; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class Dispatcher { private static Log log = LogFactory.getLog(Dispatcher.class) ; static Configuration configuration = null ; static ServiceRegistry serviceRegistry = null ; //Dispatcher dispatcher = new Dispatcher() ; public static void dispatch(String serviceURI, Request request, Response response) throws ExecutionException { if ( serviceRegistry == null ) { log.fatal("Service registry not initialized") ; throw new ExecutionException(ReturnCodes.rcInternalError, "Service registry not initialized") ; } try { Service service = serviceRegistry.find(serviceURI) ; if ( service == null ) { log.info("404 - Service <"+serviceURI+"> not found") ; throw new ExecutionException(ReturnCodes.rcNoSuchURI, "Service <"+serviceURI+"> not found") ; } if ( !service.isAvailable() ) { log.info("Service is not available") ; throw new ExecutionException(ReturnCodes.rcServiceUnavailable, "Service <"+serviceURI+"> unavailable") ; } service.exec(request, response) ; response.sendResponse() ; } catch (ExecutionException ex) { response.sendException(ex) ; return ; } } // This method contains the pragmatic algorithm to determine the configuration URI. // // In this order (i.e. specific to general) to find the filename: // System property org.joseki.rdfserver.config => a URI. // Resource: // System property: jena.rdfserver.modelmap => file name // Webapp init parameter: jena.rdfserver.modelmap // Servlet init parameter: jena.rdfserver.modelmap // and then the file is loaded. public static void initServiceRegistry() { initServiceRegistry(FileManager.get()) ; } public static void initServiceRegistry(FileManager fileManager) { initServiceRegistry(fileManager, null) ; } public static void initServiceRegistry(String configURI) { initServiceRegistry(FileManager.get(), configURI) ; } public static void initServiceRegistry(FileManager fileManager, String configURI) { if ( configURI == null ) configURI = System.getProperty(Joseki.configurationFileProperty, RDFServer.defaultConfigFile) ; setConfiguration(fileManager, configURI) ; } public static synchronized void setConfiguration(FileManager fileManager, String configURI) { if ( serviceRegistry != null ) { log.debug("Service registry already initialized") ; return ; } if ( configURI == null ) { log.fatal("Null for configuration URI") ; return ; } // Already squirreled away somewhere? serviceRegistry = (ServiceRegistry)Registry.find(RDFServer.ServiceRegistryName) ; if ( serviceRegistry != null ) { log.debug("Using globally registered service registry") ; return ; } // Better find one. ServiceRegistry tmp = new ServiceRegistry() ; try { configuration = new Configuration(fileManager, configURI, tmp) ; log.info("Loaded data source configuration: " + configURI); } catch (RDFException rdfEx) { // Trouble processing a configuration throw new ConfigurationErrorException("RDF Exception: "+rdfEx.getMessage(), rdfEx) ; //return false ; } catch (NotFoundException ex) { throw new ConfigurationErrorException("Not found: "+ex.getMessage(), ex) ; //return false; } Registry.add(RDFServer.ServiceRegistryName, tmp) ; serviceRegistry = (ServiceRegistry)Registry.find(RDFServer.ServiceRegistryName) ; } } /* * (c) Copyright 2005, 2006, 2007 Hewlett-Packard Development Company, LP * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
*** empty log message *** git-svn-id: 1a37ca0372d1852423f8ef75091f1e501b9acb0e@1114969 13f79535-47bb-0310-9956-ffa450edef68
src/org/joseki/Dispatcher.java
*** empty log message ***
<ide><path>rc/org/joseki/Dispatcher.java <ide> <ide> package org.joseki; <ide> <del>import com.hp.hpl.jena.rdf.model.RDFException; <add>import com.hp.hpl.jena.shared.JenaException; <ide> import com.hp.hpl.jena.shared.NotFoundException; <ide> import com.hp.hpl.jena.util.FileManager; <ide> <ide> try { <ide> configuration = new Configuration(fileManager, configURI, tmp) ; <ide> log.info("Loaded data source configuration: " + configURI); <del> } catch (RDFException rdfEx) <add> } catch (NotFoundException ex) <add> { <add> throw new ConfigurationErrorException("Not found: "+ex.getMessage(), ex) ; <add> //return false; <add> } catch (JenaException rdfEx) <ide> { <ide> // Trouble processing a configuration <ide> throw new ConfigurationErrorException("RDF Exception: "+rdfEx.getMessage(), rdfEx) ; <ide> //return false ; <del> } catch (NotFoundException ex) <del> { <del> throw new ConfigurationErrorException("Not found: "+ex.getMessage(), ex) ; <del> //return false; <ide> } <ide> <ide> Registry.add(RDFServer.ServiceRegistryName, tmp) ;
JavaScript
mit
c85056407bf1161609fe27ac5d43314bc540eee9
0
dj31416/JSX,dj31416/JSX,jsx/JSX,dj31416/JSX,jsx/JSX,jsx/JSX,jsx/JSX,jsx/JSX,dj31416/JSX,dj31416/JSX
/* * Copyright (c) 2012 DeNA Co., Ltd. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ var Class = require("./Class"); eval(Class.$import("./classdef")); eval(Class.$import("./type")); eval(Class.$import("./expression")); eval(Class.$import("./statement")); eval(Class.$import("./emitter")); eval(Class.$import("./jssourcemap")); eval(Class.$import("./util")); "use strict"; var _Util = exports._Util = Class.extend({ $toClosureType: function (type) { if (type.equals(Type.booleanType)) { return "!boolean"; } else if (type.equals(Type.integerType) || type.equals(Type.numberType)) { return "!number"; } else if (type.equals(Type.stringType)) { return "!string"; } else if (type instanceof NullableType) { return "undefined|" + this.toClosureType(type.getBaseType()); } else if (type instanceof ObjectType) { var classDef = type.getClassDef(); if (classDef instanceof InstantiatedClassDefinition && classDef.getTemplateClassName() == "Array") { return "Array.<undefined|" + this.toClosureType(classDef.getTypeArguments()[0]) + ">"; } else if (classDef instanceof InstantiatedClassDefinition && classDef.getTemplateClassName() == "Map") { return "Object.<string, undefined|" + this.toClosureType(classDef.getTypeArguments()[0]) + ">"; } else { return classDef.getOutputClassName(); } } else if (type instanceof VariantType) { return "*"; } return null; }, $getInstanceofNameFromClassDef: function (classDef) { if (classDef instanceof InstantiatedClassDefinition) { var name = classDef.getTemplateClassName(); if (name == "Map") name = "Object"; } else { name = classDef.getOutputClassName(); } return name; }, $buildAnnotation: function (template, type) { var closureType = this.toClosureType(type); if (closureType == null) return ""; return Util.format(template, [closureType]); }, $emitLabelOfStatement: function (emitter, statement) { var label = statement.getLabel(); if (label != null) { emitter._reduceIndent(); emitter._emit(label.getValue() + ":\n", label); emitter._advanceIndent(); } }, $getStash: function (stashable) { var stashHash = stashable.getOptimizerStash(); var stash; if ((stash = stashHash["jsemitter"]) == null) { stash = stashHash["jsemitter"] = {}; } return stashHash; }, $setupBooleanizeFlags: function (funcDef) { var exprReturnsBoolean = function (expr) { if (expr instanceof LogicalExpression) { return _Util.getStash(expr).returnsBoolean; } else { return expr.getType().equals(Type.booleanType); } }; funcDef.forEachStatement(function onStatement(statement) { var parentExpr = []; // [0] is stack top statement.forEachExpression(function onExpr(expr) { // handle children parentExpr.unshift(expr); expr.forEachExpression(onExpr.bind(this)); parentExpr.shift(); // check if (expr instanceof LogicalExpression) { var shouldBooleanize = true; var returnsBoolean = false; if (exprReturnsBoolean(expr.getFirstExpr()) && exprReturnsBoolean(expr.getSecondExpr())) { returnsBoolean = true; shouldBooleanize = false; } else if (parentExpr.length == 0) { if (statement instanceof ExpressionStatement || statement instanceof IfStatement || statement instanceof DoWhileStatement || statement instanceof WhileStatement || statement instanceof ForStatement) { shouldBooleanize = false; } } else if (parentExpr[0] instanceof LogicalExpression || parentExpr[0] instanceof LogicalNotExpression) { shouldBooleanize = false; } else if (parentExpr[0] instanceof ConditionalExpression && parentExpr[0].getCondExpr() == expr) { shouldBooleanize = false; } _Util.getStash(expr).shouldBooleanize = shouldBooleanize; _Util.getStash(expr).returnsBoolean = returnsBoolean; } return true; }); return statement.forEachStatement(onStatement.bind(this)); }); }, $shouldBooleanize: function (logicalExpr) { return _Util.getStash(logicalExpr).shouldBooleanize; } }); // statement emitter var _StatementEmitter = exports._StatementEmitter = Class.extend({ constructor: function (emitter) { this._emitter = emitter; } }); var _ConstructorInvocationStatementEmitter = exports._ConstructorInvocationStatementEmitter = _StatementEmitter.extend({ constructor: function (emitter, statement) { _StatementEmitter.prototype.constructor.call(this, emitter); this._statement = statement; }, emit: function () { var ctorType = this._statement.getConstructorType(); var argTypes = ctorType != null ? ctorType.getArgumentTypes() : []; var ctorName = this._emitter._mangleConstructorName(this._statement.getConstructingClassDef(), argTypes); var token = this._statement.getToken(); if (ctorName == "Error" && this._statement.getArguments().length == 1) { /* At least v8 does not support "Error.call(this, message)"; it not only does not setup the stacktrace but also does not set the message property. So we set the message property. We continue to call "Error" hoping that it would have some positive effect on other platforms (like setting the stacktrace, etc.). FIXME check that doing "Error.call(this);" does not have any negative effect on other platforms */ this._emitter._emit("Error.call(this);\n", token); this._emitter._emit("this.message = ", token); this._emitter._getExpressionEmitterFor(this._statement.getArguments()[0]).emit(_BinaryExpressionEmitter._operatorPrecedence["="]); this._emitter._emit(";\n", token); } else { this._emitter._emitCallArguments(token, ctorName + ".call(this", this._statement.getArguments(), argTypes); this._emitter._emit(";\n", token); } } }); var _ExpressionStatementEmitter = exports._ExpressionStatementEmitter = _StatementEmitter.extend({ constructor: function (emitter, statement) { _StatementEmitter.prototype.constructor.call(this, emitter); this._statement = statement; }, emit: function () { this._emitter._getExpressionEmitterFor(this._statement.getExpr()).emit(0); this._emitter._emit(";\n", null); } }); var _ReturnStatementEmitter = exports._ReturnStatementEmitter = _StatementEmitter.extend({ constructor: function (emitter, statement) { _StatementEmitter.prototype.constructor.call(this, emitter); this._statement = statement; }, emit: function () { var expr = this._statement.getExpr(); if (expr != null) { this._emitter._emit("return ", null); if (this._emitter._enableProfiler) { this._emitter._emit("$__jsx_profiler.exit(", null); } this._emitter._emitRHSOfAssignment(this._statement.getExpr(), this._emitter._emittingFunction.getReturnType()); if (this._emitter._enableProfiler) { this._emitter._emit(")", null); } this._emitter._emit(";\n", null); } else { if (this._emitter._enableProfiler) { this._emitter._emit("return $__jsx_profiler.exit();\n", this._statement.getToken()); } else { this._emitter._emit("return;\n", this._statement.getToken()); } } } }); var _DeleteStatementEmitter = exports._DeleteStatementEmitter = _StatementEmitter.extend({ constructor: function (emitter, statement) { _StatementEmitter.prototype.constructor.call(this, emitter); this._statement = statement; }, emit: function () { this._emitter._emit("delete ", this._statement.getToken()); this._emitter._getExpressionEmitterFor(this._statement.getExpr()).emit(0); this._emitter._emit(";\n", null); } }); var _BreakStatementEmitter = exports._BreakStatementEmitter = _StatementEmitter.extend({ constructor: function (emitter, statement) { _StatementEmitter.prototype.constructor.call(this, emitter); this._statement = statement; }, emit: function () { if (this._statement.getLabel() != null) this._emitter._emit("break " + this._statement.getLabel().getValue() + ";\n", this._statement.getToken()); else this._emitter._emit("break;\n", this._statement.getToken()); } }); var _ContinueStatementEmitter = exports._ContinueStatementEmitter = _StatementEmitter.extend({ constructor: function (emitter, statement) { _StatementEmitter.prototype.constructor.call(this, emitter); this._statement = statement; }, emit: function () { if (this._statement.getLabel() != null) this._emitter._emit("continue " + this._statement.getLabel().getValue() + ";\n", this._statement.getToken()); else this._emitter._emit("continue;\n", this._statement.getToken()); } }); var _DoWhileStatementEmitter = exports._DoWhileStatementEmitter = _StatementEmitter.extend({ constructor: function (emitter, statement) { _StatementEmitter.prototype.constructor.call(this, emitter); this._statement = statement; }, emit: function () { _Util.emitLabelOfStatement(this._emitter, this._statement); this._emitter._emit("do {\n", null); this._emitter._emitStatements(this._statement.getStatements()); this._emitter._emit("} while (", null); this._emitter._getExpressionEmitterFor(this._statement.getExpr()).emit(0); this._emitter._emit(");\n", null); } }); var _ForInStatementEmitter = exports._ForInStatementEmitter = _StatementEmitter.extend({ constructor: function (emitter, statement) { _StatementEmitter.prototype.constructor.call(this, emitter); this._statement = statement; }, emit: function () { _Util.emitLabelOfStatement(this._emitter, this._statement); this._emitter._emit("for (", null); this._emitter._getExpressionEmitterFor(this._statement.getLHSExpr()).emit(0); this._emitter._emit(" in ", null); this._emitter._getExpressionEmitterFor(this._statement.getListExpr()).emit(0); this._emitter._emit(") {\n", null); this._emitter._emitStatements(this._statement.getStatements()); this._emitter._emit("}\n", null); } }); var _ForStatementEmitter = exports._ForStatementEmitter = _StatementEmitter.extend({ constructor: function (emitter, statement) { _StatementEmitter.prototype.constructor.call(this, emitter); this._statement = statement; }, emit: function () { _Util.emitLabelOfStatement(this._emitter, this._statement); this._emitter._emit("for (", this._statement.getToken()); var initExpr = this._statement.getInitExpr(); if (initExpr != null) this._emitter._getExpressionEmitterFor(initExpr).emit(0); this._emitter._emit("; ", null); var condExpr = this._statement.getCondExpr(); if (condExpr != null) this._emitter._getExpressionEmitterFor(condExpr).emit(0); this._emitter._emit("; ", null); var postExpr = this._statement.getPostExpr(); if (postExpr != null) this._emitter._getExpressionEmitterFor(postExpr).emit(0); this._emitter._emit(") {\n", null); this._emitter._emitStatements(this._statement.getStatements()); this._emitter._emit("}\n", null); } }); var _IfStatementEmitter = exports._IfStatementEmitter = _StatementEmitter.extend({ constructor: function (emitter, statement) { _StatementEmitter.prototype.constructor.call(this, emitter); this._statement = statement; }, emit: function () { this._emitter._emit("if (", this._statement.getToken()); this._emitter._getExpressionEmitterFor(this._statement.getExpr()).emit(0); this._emitter._emit(") {\n", null); this._emitter._emitStatements(this._statement.getOnTrueStatements()); var ifFalseStatements = this._statement.getOnFalseStatements(); if (ifFalseStatements.length != 0) { this._emitter._emit("} else {\n", null); this._emitter._emitStatements(ifFalseStatements); } this._emitter._emit("}\n", null); } }); var _SwitchStatementEmitter = exports._SwitchStatementEmitter = _StatementEmitter.extend({ constructor: function (emitter, statement) { _StatementEmitter.prototype.constructor.call(this, emitter); this._statement = statement; }, emit: function () { _Util.emitLabelOfStatement(this._emitter, this._statement); this._emitter._emit("switch (", this._statement.getToken()); var expr = this._statement.getExpr(); if (this._emitter._enableRunTimeTypeCheck && expr.getType() instanceof NullableType) { this._emitter._emitExpressionWithUndefinedAssertion(expr); } else { this._emitter._getExpressionEmitterFor(expr).emit(0); } this._emitter._emit(") {\n", null); this._emitter._emitStatements(this._statement.getStatements()); this._emitter._emit("}\n", null); } }); var _CaseStatementEmitter = exports._CaseStatementEmitter = _StatementEmitter.extend({ constructor: function (emitter, statement) { _StatementEmitter.prototype.constructor.call(this, emitter); this._statement = statement; }, emit: function () { this._emitter._reduceIndent(); this._emitter._emit("case ", null); var expr = this._statement.getExpr(); if (this._emitter._enableRunTimeTypeCheck && expr.getType() instanceof NullableType) { this._emitter._emitExpressionWithUndefinedAssertion(expr); } else { this._emitter._getExpressionEmitterFor(expr).emit(0); } this._emitter._emit(":\n", null); this._emitter._advanceIndent(); } }); var _DefaultStatementEmitter = exports._DefaultStatementEmitter = _StatementEmitter.extend({ constructor: function (emitter, statement) { _StatementEmitter.prototype.constructor.call(this, emitter); this._statement = statement; }, emit: function () { this._emitter._reduceIndent(); this._emitter._emit("default:\n", null); this._emitter._advanceIndent(); } }); var _WhileStatementEmitter = exports._WhileStatementEmitter = _StatementEmitter.extend({ constructor: function (emitter, statement) { _StatementEmitter.prototype.constructor.call(this, emitter); this._statement = statement; }, emit: function () { _Util.emitLabelOfStatement(this._emitter, this._statement); this._emitter._emit("while (", this._statement.getToken()); this._emitter._getExpressionEmitterFor(this._statement.getExpr()).emit(0); this._emitter._emit(") {\n", null); this._emitter._emitStatements(this._statement.getStatements()); this._emitter._emit("}\n", null); } }); var _TryStatementEmitter = exports._TryStatementEmitter = _StatementEmitter.extend({ constructor: function (emitter, statement) { _StatementEmitter.prototype.constructor.call(this, emitter); this._statement = statement; var outerCatchStatements = 0; for (var i = 0; i < this._emitter._emittingStatementStack.length; ++i) { if (this._emitter._emittingStatementStack[i] instanceof _TryStatementEmitter) ++outerCatchStatements; } this._emittingLocalName = "$__jsx_catch_" + outerCatchStatements; }, emit: function () { this._emitter._emit("try {\n", this._statement.getToken()); this._emitter._emitStatements(this._statement.getTryStatements()); this._emitter._emit("}", null); var catchStatements = this._statement.getCatchStatements(); if (catchStatements.length != 0) { this._emitter._emit(" catch (" + this._emittingLocalName + ") {\n", null); if (this._emitter._enableProfiler) { this._emitter._advanceIndent(); this._emitter._emit("$__jsx_profiler.resume($__jsx_profiler_ctx);\n", null); this._emitter._reduceIndent(); } this._emitter._emitStatements(catchStatements); if (! catchStatements[catchStatements.length - 1].getLocal().getType().equals(Type.variantType)) { this._emitter._advanceIndent(); this._emitter._emit("{\n", null); this._emitter._advanceIndent(); this._emitter._emit("throw " + this._emittingLocalName + ";\n", null); this._emitter._reduceIndent(); this._emitter._emit("}\n", null); this._emitter._reduceIndent(); } this._emitter._emit("}", null); } var finallyStatements = this._statement.getFinallyStatements(); if (finallyStatements.length != 0) { this._emitter._emit(" finally {\n", null); this._emitter._emitStatements(finallyStatements); this._emitter._emit("}", null); } this._emitter._emit("\n", null); }, getEmittingLocalName: function () { return this._emittingLocalName; } }); var _CatchStatementEmitter = exports._CatchStatementEmitter = _StatementEmitter.extend({ constructor: function (emitter, statement) { _StatementEmitter.prototype.constructor.call(this, emitter); this._statement = statement; }, emit: function () { var localType = this._statement.getLocal().getType(); if (localType instanceof ObjectType) { var tryStatement = this._emitter._emittingStatementStack[this._emitter._emittingStatementStack.length - 2]; var localName = tryStatement.getEmittingLocalName(); this._emitter._emit("if (" + localName + " instanceof " + localType.getClassDef().getOutputClassName() + ") {\n", this._statement.getToken()); this._emitter._emitStatements(this._statement.getStatements()); this._emitter._emit("} else ", null); } else { this._emitter._emit("{\n", null); this._emitter._emitStatements(this._statement.getStatements()); this._emitter._emit("}\n", null); } }, $getLocalNameFor: function (emitter, name) { for (var i = emitter._emittingStatementStack.length - 1; i >= 0; --i) { if (! (emitter._emittingStatementStack[i] instanceof _CatchStatementEmitter)) continue; var catchStatement = emitter._emittingStatementStack[i]; if (catchStatement._statement.getLocal().getName().getValue() == name) { var tryEmitter = emitter._emittingStatementStack[i - 1]; if (! (tryEmitter instanceof _TryStatementEmitter)) throw new Error("logic flaw"); return tryEmitter.getEmittingLocalName(); } } throw new Error("logic flaw"); } }); var _ThrowStatementEmitter = exports._ThrowStatementEmitter = _StatementEmitter.extend({ constructor: function (emitter, statement) { _StatementEmitter.prototype.constructor.call(this, emitter); this._statement = statement; }, emit: function () { this._emitter._emit("throw ", this._statement.getToken()); this._emitter._getExpressionEmitterFor(this._statement.getExpr()).emit(0); this._emitter._emit(";\n", null); } }); var _AssertStatementEmitter = exports._AssertStatementEmitter = _StatementEmitter.extend({ constructor: function (emitter, statement) { _StatementEmitter.prototype.constructor.call(this, emitter); this._statement = statement; }, emit: function () { var condExpr = this._statement._expr; this._emitter._emitAssertion(function () { this._emitter._getExpressionEmitterFor(condExpr).emit(0); }.bind(this), this._statement.getToken(), "assertion failure"); } }); var _LogStatementEmitter = exports._LogStatementEmitter = _StatementEmitter.extend({ constructor: function (emitter, statement) { _StatementEmitter.prototype.constructor.call(this, emitter); this._statement = statement; }, emit: function () { this._emitter._emit("console.log(", this._statement.getToken()); var exprs = this._statement.getExprs(); for (var i = 0; i < exprs.length; ++i) { if (i != 0) this._emitter._emit(", ", null); this._emitter._getExpressionEmitterFor(exprs[i]).emit(0); } this._emitter._emit(");\n", null); } }); var _DebuggerStatementEmitter = exports._DebuggerStatementEmitter = _StatementEmitter.extend({ constructor: function (emitter, statement) { _StatementEmitter.prototype.constructor.call(this, emitter); this._statement = statement; }, emit: function () { this._emitter._emit("debugger;\n", this._statement.getToken()); } }); // expression emitter var _ExpressionEmitter = exports._ExpressionEmitter = Class.extend({ constructor: function (emitter) { this._emitter = emitter; }, emitWithPrecedence: function (outerOpPrecedence, precedence, callback) { if (precedence > outerOpPrecedence) { this._emitter._emit("(", null); callback(); this._emitter._emit(")", null); } else { callback(); } } }); var _LocalExpressionEmitter = exports._LocalExpressionEmitter = _ExpressionEmitter.extend({ constructor: function (emitter, expr) { _ExpressionEmitter.prototype.constructor.call(this, emitter); this._expr = expr; }, emit: function (outerOpPrecedence) { var local = this._expr.getLocal(); var localName = local.getName().getValue(); if (local instanceof CaughtVariable) { localName = _CatchStatementEmitter.getLocalNameFor(this._emitter, localName); } this._emitter._emit(localName, this._expr.getToken()); } }); var _ClassExpressionEmitter = exports._ClassExpressionEmitter = _ExpressionEmitter.extend({ constructor: function (emitter, expr) { _ExpressionEmitter.prototype.constructor.call(this, emitter); this._expr = expr; }, emit: function (outerOpPrecedence) { var type = this._expr.getType(); this._emitter._emit(type.getClassDef().getOutputClassName(), null); } }); var _NullExpressionEmitter = exports._NullExpressionEmitter = _ExpressionEmitter.extend({ constructor: function (emitter, expr) { _ExpressionEmitter.prototype.constructor.call(this, emitter); this._expr = expr; }, emit: function (outerOpPrecedence) { var token = this._expr.getToken(); this._emitter._emit("undefined", token); } }); var _BooleanLiteralExpressionEmitter = exports._BooleanLiteralExpressionEmitter = _ExpressionEmitter.extend({ constructor: function (emitter, expr) { _ExpressionEmitter.prototype.constructor.call(this, emitter); this._expr = expr; }, emit: function (outerOpPrecedence) { var token = this._expr.getToken(); this._emitter._emit(token.getValue(), token); } }); var _IntegerLiteralExpressionEmitter = exports._IntegerLiteralExpressionEmitter = _ExpressionEmitter.extend({ constructor: function (emitter, expr) { _ExpressionEmitter.prototype.constructor.call(this, emitter); this._expr = expr; }, emit: function (outerOpPrecedence) { var token = this._expr.getToken(); this._emitter._emit("" + token.getValue(), token); } }); var _NumberLiteralExpressionEmitter = exports._NumberLiteralExpressionEmitter = _ExpressionEmitter.extend({ constructor: function (emitter, expr) { _ExpressionEmitter.prototype.constructor.call(this, emitter); this._expr = expr; }, emit: function (outerOpPrecedence) { var token = this._expr.getToken(); var str = token.getValue(); if (outerOpPrecedence == _PropertyExpressionEmitter._operatorPrecedence && str.indexOf(".") == -1) { this._emitter._emit("(" + str + ")", token); } else { this._emitter._emit("" + str, token); } } }); var _StringLiteralExpressionEmitter = exports._StringLiteralExpressionEmitter = _ExpressionEmitter.extend({ constructor: function (emitter, expr) { _ExpressionEmitter.prototype.constructor.call(this, emitter); this._expr = expr; }, emit: function (outerOpPrecedence) { var token = this._expr.getToken(); // FIXME escape this._emitter._emit(token.getValue(), token); } }); var _RegExpLiteralExpressionEmitter = exports._RegExpLiteralExpressionEmitter = _ExpressionEmitter.extend({ constructor: function (emitter, expr) { _ExpressionEmitter.prototype.constructor.call(this, emitter); this._expr = expr; }, emit: function (outerOpPrecedence) { var token = this._expr.getToken(); this._emitter._emit(token.getValue(), token); } }); var _ArrayLiteralExpressionEmitter = exports._ArrayLiteralExpressionEmitter = _ExpressionEmitter.extend({ constructor: function (emitter, expr) { _ExpressionEmitter.prototype.constructor.call(this, emitter); this._expr = expr; }, emit: function (outerOpPrecedence) { this._emitter._emit("[ ", null); var exprs = this._expr.getExprs(); for (var i = 0; i < exprs.length; ++i) { if (i != 0) this._emitter._emit(", ", null); this._emitter._getExpressionEmitterFor(exprs[i]).emit(0); } this._emitter._emit(" ]", null); } }); var _MapLiteralExpressionEmitter = exports._MapLiteralExpressionEmitter = _ExpressionEmitter.extend({ constructor: function (emitter, expr) { _ExpressionEmitter.prototype.constructor.call(this, emitter); this._expr = expr; }, emit: function (outerOpPrecedence) { this._emitter._emit("{ ", null); var elements = this._expr.getElements(); for (var i = 0; i < elements.length; ++i) { var element = elements[i]; if (i != 0) this._emitter._emit(", ", null); this._emitter._emit(element.getKey().getValue(), element.getKey()); this._emitter._emit(": ", null); this._emitter._getExpressionEmitterFor(element.getExpr()).emit(0); } this._emitter._emit(" }", null); } }); var _ThisExpressionEmitter = exports._ThisExpressionEmitter = _ExpressionEmitter.extend({ constructor: function (emitter, expr) { _ExpressionEmitter.prototype.constructor.call(this, emitter); this._expr = expr; }, emit: function (outerOpPrecedence) { var emittingFunction = this._emitter._emittingFunction; if ((emittingFunction.flags() & ClassDefinition.IS_STATIC) != 0) this._emitter._emit("$this", this._expr.getToken()); else this._emitter._emit("this", this._expr.getToken()); } }); var _AsExpressionEmitter = exports._AsExpressionEmitter = _ExpressionEmitter.extend({ constructor: function (emitter, expr) { _ExpressionEmitter.prototype.constructor.call(this, emitter); this._expr = expr; }, emit: function (outerOpPrecedence) { var srcType = this._expr.getExpr().getType(); var destType = this._expr.getType(); if (srcType.resolveIfNullable() instanceof ObjectType || srcType.equals(Type.variantType)) { if (srcType.resolveIfNullable().isConvertibleTo(destType)) { if (srcType instanceof NullableType) { var prec = _BinaryExpressionEmitter._operatorPrecedence["||"]; this._emitWithParens(outerOpPrecedence, prec, prec, null, "|| null"); } else { this._emitter._getExpressionEmitterFor(this._expr.getExpr()).emit(outerOpPrecedence); } return true; } if (destType instanceof ObjectType) { // unsafe cast if ((destType.getClassDef().flags() & (ClassDefinition.IS_INTERFACE | ClassDefinition.IS_MIXIN)) == 0) { this.emitWithPrecedence(outerOpPrecedence, _CallExpressionEmitter._operatorPrecedence, (function () { this._emitter._emit("(function (o) { return o instanceof " + _Util.getInstanceofNameFromClassDef(destType.getClassDef()) + " ? o : null; })(", this._expr.getToken()); this._emitter._getExpressionEmitterFor(this._expr.getExpr()).emit(0); this._emitter._emit(")", this._expr.getToken()); }).bind(this)); } else { this.emitWithPrecedence(outerOpPrecedence, _CallExpressionEmitter._operatorPrecedence, (function () { this._emitter._emit("(function (o) { return o && o.$__jsx_implements_" + destType.getClassDef().getOutputClassName() + " ? o : null; })(", this._expr.getToken()); this._emitter._getExpressionEmitterFor(this._expr.getExpr()).emit(0); this._emitter._emit(")", this._expr.getToken()); }).bind(this)); } return true; } if (destType instanceof FunctionType) { // cast to function this._emitter._emit("(function (o) { return typeof(o) === \"function\" ? o : null; })(", this._expr.getToken()); this._emitter._getExpressionEmitterFor(this._expr.getExpr()).emit(0); this._emitter._emit(")", this._expr.getToken()); return true; } } if (srcType.equals(Type.nullType)) { // from null if (destType.equals(Type.booleanType)) { this._emitter._emit("false", this._expr.getToken()); return true; } if (destType.equals(Type.integerType) || destType.equals(Type.numberType)) { this._emitter._emit("0", this._expr.getToken()); return true; } if (destType.equals(Type.stringType)) { this._emitter._emit("\"null\"", this._expr.getToken()); return true; } if (destType instanceof ObjectType || destType instanceof FunctionType) { this._emitter._emit("null", this._expr.getToken()); return true; } } if (srcType.equals(Type.booleanType)) { // from boolean if (destType.equals(Type.integerType) || destType.equals(Type.numberType)) { var prec = _UnaryExpressionEmitter._operatorPrecedence["+"]; this._emitWithParens(outerOpPrecedence, prec, prec, "+", null); return true; } if (destType.equals(Type.stringType)) { var prec = _BinaryExpressionEmitter._operatorPrecedence["+"]; this._emitWithParens(outerOpPrecedence, prec, prec, null, " + \"\""); return true; } } if (srcType instanceof NullableType && srcType.getBaseType().equals(Type.booleanType)) { // from Nullable.<boolean> if (destType.equals(Type.booleanType)) { var prec = _BinaryExpressionEmitter._operatorPrecedence["||"]; this._emitWithParens(outerOpPrecedence, prec, prec, null, " || false"); return true; } if (destType.equals(Type.integerType) || destType.equals(Type.numberType)) { this._emitWithParens( outerOpPrecedence, _BinaryExpressionEmitter._operatorPrecedence["-"], _UnaryExpressionEmitter._operatorPrecedence["!"], "1 - ! ", null); return true; } if (destType.equals(Type.stringType)) { var prec = _BinaryExpressionEmitter._operatorPrecedence["+"]; this._emitWithParens(outerOpPrecedence, prec, prec, null, " + \"\""); return true; } } if (srcType.equals(Type.integerType)) { // from integer if (destType.equals(Type.booleanType)) { var prec = _UnaryExpressionEmitter._operatorPrecedence["!"]; this._emitWithParens(outerOpPrecedence, prec, prec, "!! ", null); return true; } if (destType.equals(Type.numberType)) { this._emitter._getExpressionEmitterFor(this._expr.getExpr()).emit(outerOpPrecedence); return true; } if (destType.equals(Type.stringType)) { var prec = _BinaryExpressionEmitter._operatorPrecedence["+"]; this._emitWithParens(outerOpPrecedence, prec, prec, null, " + \"\""); return true; } } if (srcType instanceof NullableType && srcType.getBaseType().equals(Type.integerType)) { // from Nullable.<int> if (destType.equals(Type.booleanType)) { var prec = _UnaryExpressionEmitter._operatorPrecedence["!"]; this._emitWithParens(outerOpPrecedence, prec, prec, "!! ", null); return true; } if (destType.equals(Type.integerType) || destType.equals(Type.numberType)) { var prec = _BinaryExpressionEmitter._operatorPrecedence["|"]; this._emitWithParens(outerOpPrecedence, prec, prec, null, " | 0"); return true; } if (destType.equals(Type.stringType)) { var prec = _BinaryExpressionEmitter._operatorPrecedence["+"]; this._emitWithParens(outerOpPrecedence, prec, prec, null, " + \"\""); return true; } } if (srcType.equals(Type.numberType)) { // from number if (destType.equals(Type.booleanType)) { var prec = _UnaryExpressionEmitter._operatorPrecedence["!"]; this._emitWithParens(outerOpPrecedence, prec, prec, "!! ", null); return true; } if (destType.equals(Type.integerType)) { var prec = _BinaryExpressionEmitter._operatorPrecedence["|"]; this._emitWithParens(outerOpPrecedence, prec, prec, null, " | 0"); return true; } if (destType.equals(Type.stringType)) { var prec = _BinaryExpressionEmitter._operatorPrecedence["+"]; this._emitWithParens(outerOpPrecedence, prec, prec, null, " + \"\""); return true; } } if (srcType instanceof NullableType && srcType.getBaseType().equals(Type.numberType)) { // from Nullable.<number> if (destType.equals(Type.booleanType)) { var prec = _UnaryExpressionEmitter._operatorPrecedence["!"]; this._emitWithParens(outerOpPrecedence, prec, prec, "!! ", null); return true; } if (destType.equals(Type.integerType)) { var prec = _BinaryExpressionEmitter._operatorPrecedence["|"]; this._emitWithParens(outerOpPrecedence, prec, prec, null, " | 0"); return true; } if (destType.equals(Type.numberType)) { var prec = _UnaryExpressionEmitter._operatorPrecedence["+"]; this._emitWithParens(outerOpPrecedence, prec, prec, "+", null); return true; } if (destType.equals(Type.stringType)) { var prec = _BinaryExpressionEmitter._operatorPrecedence["+"]; this._emitWithParens(outerOpPrecedence, prec, prec, null, " + \"\""); return true; } } if (srcType.equals(Type.stringType)) { // from String if (destType.equals(Type.booleanType)) { var prec = _UnaryExpressionEmitter._operatorPrecedence["!"]; this._emitWithParens(outerOpPrecedence, prec, prec, "!! ", null); return true; } if (destType.equals(Type.integerType)) { var prec = _BinaryExpressionEmitter._operatorPrecedence["|"]; this._emitWithParens(outerOpPrecedence, prec, prec, null, " | 0"); return true; } if (destType.equals(Type.numberType)) { var prec = _UnaryExpressionEmitter._operatorPrecedence["+"]; this._emitWithParens(outerOpPrecedence, prec, prec, "+", null); return true; } } if (srcType instanceof NullableType && srcType.getBaseType().equals(Type.stringType)) { // from Nullable.<String> if (destType.equals(Type.booleanType)) { var prec = _UnaryExpressionEmitter._operatorPrecedence["!"]; this._emitWithParens(outerOpPrecedence, prec, prec, "!! ", null); return true; } if (destType.equals(Type.integerType)) { var prec = _BinaryExpressionEmitter._operatorPrecedence["|"]; this._emitWithParens(outerOpPrecedence, prec, prec, null, " | 0"); return true; } if (destType.equals(Type.numberType)) { var prec = _UnaryExpressionEmitter._operatorPrecedence["+"]; this._emitWithParens(outerOpPrecedence, prec, prec, "+", null); return true; } if (destType.equals(Type.stringType)) { var prec = _BinaryExpressionEmitter._operatorPrecedence["+"]; this._emitWithParens(outerOpPrecedence, prec, prec, null, " + \"\""); return true; } } if (srcType.equals(Type.variantType)) { // from variant if (destType.equals(Type.booleanType)) { var prec = _UnaryExpressionEmitter._operatorPrecedence["!"]; this._emitWithParens(outerOpPrecedence, prec, prec, "!! ", null); return true; } if (destType.equals(Type.integerType)) { var prec = _BinaryExpressionEmitter._operatorPrecedence["|"]; this._emitWithParens(outerOpPrecedence, prec, prec, null, " | 0"); return true; } if (destType.equals(Type.numberType)) { var prec = _UnaryExpressionEmitter._operatorPrecedence["+"]; this._emitWithParens(outerOpPrecedence, prec, prec, "+", null); return true; } if (destType.equals(Type.stringType)) { var prec = _BinaryExpressionEmitter._operatorPrecedence["+"]; this._emitWithParens(outerOpPrecedence, prec, prec, null, " + \"\""); return true; } } if (srcType.isConvertibleTo(destType)) { // can perform implicit conversion this._emitter._getExpressionEmitterFor(this._expr.getExpr()).emit(outerOpPrecedence); return true; } throw new Error("explicit conversion logic unknown from " + srcType.toString() + " to " + destType.toString()); }, _emitWithParens: function (outerOpPrecedence, opPrecedence, innerOpPrecedence, prefix, postfix) { // in contrast to _ExpressionEmitter#emitWithPrecedence the comparison op. is >=, since the conversion should have higher precedence than the outer op. (see t/run/110) if (opPrecedence >= outerOpPrecedence) this._emitter._emit("(", null); if (prefix != null) this._emitter._emit(prefix, this._expr.getToken()); this._emitter._getExpressionEmitterFor(this._expr.getExpr()).emit(innerOpPrecedence); if (postfix != null) this._emitter._emit(postfix, this._expr.getToken()); if (opPrecedence >= outerOpPrecedence) this._emitter._emit(")", null); } }); var _AsNoConvertExpressionEmitter = exports._AsNoConvertExpressionEmitter = _ExpressionEmitter.extend({ constructor: function (emitter, expr) { _ExpressionEmitter.prototype.constructor.call(this, emitter); this._expr = expr; }, emit: function (outerOpPrecedence) { if (this._emitter._enableRunTimeTypeCheck) { var emitWithAssertion = function (emitCheckExpr, message) { var token = this._expr.getToken(); this._emitter._emit("(function (v) {\n", token); this._emitter._advanceIndent(); this._emitter._emitAssertion(emitCheckExpr, token, message); this._emitter._emit("return v;\n", token); this._emitter._reduceIndent(); this._emitter._emit("}(", token); this._emitter._getExpressionEmitterFor(this._expr.getExpr()).emit(0); this._emitter._emit("))", token); }.bind(this); var srcType = this._expr.getExpr().getType(); var destType = this._expr.getType(); if (srcType.equals(destType) || srcType.equals(destType.resolveIfNullable)) { // skip } else if (destType instanceof VariantType) { // skip } else if (srcType instanceof ObjectType && srcType.isConvertibleTo(destType)) { // skip } else if (destType.equals(Type.booleanType)) { emitWithAssertion(function () { this._emitter._emit("typeof v === \"boolean\"", this._expr.getToken()); }.bind(this), "detected invalid cast, value is not a boolean"); return; } else if (destType.equals(Type.integerType) || destType.equals(Type.numberType)) { emitWithAssertion(function () { this._emitter._emit("typeof v === \"number\"", this._expr.getToken()); }.bind(this), "detected invalid cast, value is not a number"); return; } else if (destType.equals(Type.stringType)) { emitWithAssertion(function () { this._emitter._emit("typeof v === \"string\"", this._expr.getToken()); }.bind(this), "detected invalid cast, value is not a string"); return; } else if (destType instanceof FunctionType) { emitWithAssertion(function () { this._emitter._emit("v == null || typeof v === \"function\"", this._expr.getToken()); }.bind(this), "detected invalid cast, value is not a function or null"); return; } else if (destType instanceof ObjectType) { var destClassDef = destType.getClassDef(); if ((destClassDef.flags() & ClassDefinition.IS_FAKE) != 0) { // skip } else if (destClassDef instanceof InstantiatedClassDefinition && destClassDef.getTemplateClassName() == "Array") { emitWithAssertion(function () { this._emitter._emit("v == null || v instanceof Array", this._expr.getToken()); }.bind(this), "detected invalid cast, value is not an Array or null"); return; } else if (destClassDef instanceof InstantiatedClassDefinition && destClassDef.getTemplateClassName() == "Map") { emitWithAssertion(function () { this._emitter._emit("v == null || typeof v === \"object\"", this._expr.getToken()); }.bind(this), "detected invalid cast, value is not a Map or null"); return; } else { emitWithAssertion(function () { this._emitter._emit("v == null || v instanceof " + destClassDef.getOutputClassName(), this._expr.getToken()); }.bind(this), "detected invalid cast, value is not an instance of the designated type or null"); return; } } } this._emitter._getExpressionEmitterFor(this._expr.getExpr()).emit(outerOpPrecedence); return; } }); var _OperatorExpressionEmitter = exports._OperatorExpressionEmitter = _ExpressionEmitter.extend({ constructor: function (emitter) { _ExpressionEmitter.prototype.constructor.call(this, emitter); }, emit: function (outerOpPrecedence) { this.emitWithPrecedence(outerOpPrecedence, this._getPrecedence(), this._emit.bind(this)); }, _emit: null, // void emit() _getPrecedence: null // int _getPrecedence() }); var _UnaryExpressionEmitter = exports._UnaryExpressionEmitter = _OperatorExpressionEmitter.extend({ constructor: function (emitter, expr) { _OperatorExpressionEmitter.prototype.constructor.call(this, emitter); this._expr = expr; }, _emit: function () { var opToken = this._expr.getToken(); this._emitter._emit(opToken.getValue() + " ", opToken); this._emitter._getExpressionEmitterFor(this._expr.getExpr()).emit(this._getPrecedence()); }, _getPrecedence: function () { return _UnaryExpressionEmitter._operatorPrecedence[this._expr.getToken().getValue()]; }, $_operatorPrecedence: {}, $_setOperatorPrecedence: function (op, precedence) { _UnaryExpressionEmitter._operatorPrecedence[op] = precedence; } }); var _PostfixExpressionEmitter = exports._PostfixExpressionEmitter = _UnaryExpressionEmitter.extend({ constructor: function (emitter, expr) { _UnaryExpressionEmitter.prototype.constructor.call(this, emitter, expr); }, _emit: function () { var opToken = this._expr.getToken(); this._emitter._getExpressionEmitterFor(this._expr.getExpr()).emit(this._getPrecedence()); this._emitter._emit(opToken.getValue(), opToken); }, _getPrecedence: function () { return _PostfixExpressionEmitter._operatorPrecedence[this._expr.getToken().getValue()]; }, $_operatorPrecedence: {}, $_setOperatorPrecedence: function (op, precedence) { _PostfixExpressionEmitter._operatorPrecedence[op] = precedence; } }); var _InstanceofExpressionEmitter = exports._InstanceofExpressionEmitter = _ExpressionEmitter.extend({ constructor: function (emitter, expr) { _ExpressionEmitter.prototype.constructor.call(this, emitter); this._expr = expr; }, emit: function (outerOpPrecedence) { var expectedType = this._expr.getExpectedType(); if ((expectedType.getClassDef().flags() & (ClassDefinition.IS_INTERFACE | ClassDefinition.IS_MIXIN)) == 0) { this.emitWithPrecedence(outerOpPrecedence, _InstanceofExpressionEmitter._operatorPrecedence, (function () { this._emitter._getExpressionEmitterFor(this._expr.getExpr()).emit(_InstanceofExpressionEmitter._operatorPrecedence); this._emitter._emit(" instanceof " + _Util.getInstanceofNameFromClassDef(expectedType.getClassDef()), null); }).bind(this)); } else { this.emitWithPrecedence(outerOpPrecedence, _CallExpressionEmitter._operatorPrecedence, (function () { this._emitter._emit("(function (o) { return !! (o && o.$__jsx_implements_" + expectedType.getClassDef().getOutputClassName() + "); })(", this._expr.getToken()); this._emitter._getExpressionEmitterFor(this._expr.getExpr()).emit(0); this._emitter._emit(")", this._expr.getToken()); }).bind(this)); } }, $_operatorPrecedence: 0, $_setOperatorPrecedence: function (op, precedence) { _InstanceofExpressionEmitter._operatorPrecedence = precedence; } }); var _PropertyExpressionEmitter = exports._PropertyExpressionEmitter = _UnaryExpressionEmitter.extend({ constructor: function (emitter, expr) { _UnaryExpressionEmitter.prototype.constructor.call(this, emitter, expr); }, _emit: function () { var expr = this._expr; var exprType = expr.getType(); var identifierToken = this._expr.getIdentifierToken(); // replace methods to global function (e.g. Number.isNaN to isNaN) if (expr.getExpr() instanceof ClassExpression && expr.getExpr().getType().getClassDef() === Type.numberType.getClassDef()) { switch (identifierToken.getValue()) { case "parseInt": case "parseFloat": case "isNaN": case "isFinite": this._emitter._emit('$__jsx_' + identifierToken.getValue(), identifierToken); return; } } else if (expr.getExpr() instanceof ClassExpression && expr.getExpr().getType().getClassDef() === Type.stringType.getClassDef()) { switch (identifierToken.getValue()) { case "encodeURIComponent": case "decodeURIComponent": case "encodeURI": case "decodeURI": this._emitter._emit('$__jsx_' + identifierToken.getValue(), identifierToken); return; } } this._emitter._getExpressionEmitterFor(expr.getExpr()).emit(this._getPrecedence()); // mangle the name if necessary if (exprType instanceof FunctionType && ! exprType.isAssignable() && (expr.getHolderType().getClassDef().flags() & ClassDefinition.IS_NATIVE) == 0) { if (expr.getExpr() instanceof ClassExpression) { // do not use "." notation for static functions, but use class$name this._emitter._emit("$", identifierToken); } else { this._emitter._emit(".", identifierToken); } this._emitter._emit(this._emitter._mangleFunctionName(identifierToken.getValue(), exprType.getArgumentTypes()), identifierToken); } else { this._emitter._emit(".", identifierToken); this._emitter._emit(identifierToken.getValue(), identifierToken); } }, _getPrecedence: function () { return _PropertyExpressionEmitter._operatorPrecedence; }, $_operatorPrecedence: 0, $_setOperatorPrecedence: function (op, precedence) { _PropertyExpressionEmitter._operatorPrecedence = precedence; } }); var _FunctionExpressionEmitter = exports._FunctionExpressionEmitter = _UnaryExpressionEmitter.extend({ constructor: function (emitter, expr) { _UnaryExpressionEmitter.prototype.constructor.call(this, emitter, expr); }, _emit: function () { var funcDef = this._expr.getFuncDef(); this._emitter._emit("(function (", funcDef.getToken()); var args = funcDef.getArguments(); for (var i = 0; i < args.length; ++i) { if (i != 0) this._emitter._emit(", ", funcDef.getToken()); this._emitter._emit(args[i].getName().getValue(), funcDef.getToken()); } this._emitter._emit(") {\n", funcDef.getToken()); this._emitter._advanceIndent(); this._emitter._emitFunctionBody(funcDef); this._emitter._reduceIndent(); this._emitter._emit("})", funcDef.getToken()) }, _getPrecedence: function () { return _FunctionExpressionEmitter._operatorPrecedence; }, $_operatorPrecedence: 0, $_setOperatorPrecedence: function (op, precedence) { _FunctionExpressionEmitter._operatorPrecedence = precedence; } }); var _BinaryExpressionEmitter = exports._BinaryExpressionEmitter = _OperatorExpressionEmitter.extend({ constructor: function (emitter, expr) { _OperatorExpressionEmitter.prototype.constructor.call(this, emitter); this._expr = expr; this._precedence = _BinaryExpressionEmitter._operatorPrecedence[this._expr.getToken().getValue()]; }, emit: function (outerOpPrecedence) { // handle the lazy conversion to boolean if (this._expr instanceof LogicalExpression && _Util.shouldBooleanize(this._expr)) { // !! is faster than Boolean, see http://jsperf.com/boolean-vs-notnot this._emitter._emit("!! (", this._expr.getToken()); _OperatorExpressionEmitter.prototype.emit.call(this, 0); this._emitter._emit(")", this._expr.getToken()); return; } // optimization of "1 * x" => x if (this._expr.getToken().getValue() === "*") { // optimize "1 * x" => x if (this._emitIfEitherIs(outerOpPrecedence, function (expr1, expr2) { return ((expr1 instanceof IntegerLiteralExpression || expr1 instanceof NumberLiteralExpression) && +expr1.getToken().getValue() === 1) ? expr2 : null; })) { return; } } else if (this._expr.getToken().getValue() === "/=" && this._expr.getFirstExpr().getType().resolveIfNullable().equals(Type.integerType)) { this._emitDivAssignToInt(outerOpPrecedence); return; } // normal _OperatorExpressionEmitter.prototype.emit.call(this, outerOpPrecedence); }, _emit: function () { var opToken = this._expr.getToken(); var firstExpr = this._expr.getFirstExpr(); var firstExprType = firstExpr.getType(); var secondExpr = this._expr.getSecondExpr(); var secondExprType = secondExpr.getType(); var op = opToken.getValue(); switch (op) { case "+": // special handling: (undefined as Nullable<String>) + (undefined as Nullable<String>) should produce "undefinedundefined", not NaN if (firstExprType.equals(secondExprType) && firstExprType.equals(Type.stringType.toNullableType())) this._emitter._emit("\"\" + ", null); break; case "==": case "!=": // NOTE: works for cases where one side is an object and the other is the primitive counterpart if (firstExprType instanceof PrimitiveType && secondExprType instanceof PrimitiveType) { op += "="; } break; } // emit left-hand if (this._emitter._enableRunTimeTypeCheck && firstExpr instanceof NullableType && ! (this._expr instanceof AssignmentExpression)) { this._emitExpressionWithUndefinedAssertion(firstExpr); } else { this._emitter._getExpressionEmitterFor(firstExpr).emit(this._precedence); } // emit operator this._emitter._emit(" " + op + " ", opToken); // emit right-hand if (this._expr instanceof AssignmentExpression && op != "/=") { this._emitter._emitRHSOfAssignment(secondExpr, firstExprType); } else if (this._emitter._enableRunTimeTypeCheck && secondExpr instanceof NullableType) { this._emitExpressionWithUndefinedAssertion(secondExpr); } else { // RHS should have higher precedence (consider: 1 - (1 + 1)) this._emitter._getExpressionEmitterFor(secondExpr).emit(this._precedence - 1); } }, _emitIfEitherIs: function (outerOpPrecedence, cb) { var outcomeExpr; if ((outcomeExpr = cb(this._expr.getFirstExpr(), this._expr.getSecondExpr())) != null || (outcomeExpr = cb(this._expr.getSecondExpr(), this._expr.getFirstExpr())) != null) { this._emitter._getExpressionEmitterFor(outcomeExpr).emit(outerOpPrecedence); return true; } else { return false; } }, _emitDivAssignToInt: function (outerOpPrecedence) { var firstExpr = this._expr.getFirstExpr(); var secondExpr = this._expr.getSecondExpr(); if (firstExpr instanceof PropertyExpression || firstExpr instanceof ArrayExpression) { this._emitter._emit("$__jsx_div_assign(", this._expr.getToken()); if (firstExpr instanceof PropertyExpression) { this._emitter._getExpressionEmitterFor(firstExpr.getExpr()).emit(0); this._emitter._emit(", ", this._expr.getToken()); this._emitter._emit(Util.encodeStringLiteral(firstExpr.getIdentifierToken().getValue()), firstExpr.getIdentifierToken()); } else { this._emitter._getExpressionEmitterFor(firstExpr.getFirstExpr()).emit(0); this._emitter._emit(", ", this._expr.getToken()); this._emitter._getExpressionEmitterFor(firstExpr.getSecondExpr()).emit(0); } this._emitter._emit(", ", this._expr.getToken()); if (this._emitter._enableRunTimeTypeCheck && secondExpr instanceof NullableType) { this._emitExpressionWithUndefinedAssertion(secondExpr); } else { this._emitter._getExpressionEmitterFor(secondExpr).emit(0); } this._emitter._emit(")", this._expr.getToken()); } else { this.emitWithPrecedence(outerOpPrecedence, _BinaryExpressionEmitter._operatorPrecedence["="], function () { this._emitter._getExpressionEmitterFor(firstExpr).emit(_BinaryExpressionEmitter._operatorPrecedence["="]); this._emitter._emit(" = (", this._expr.getToken()); if (this._emitter._enableRunTimeTypeCheck && firstExpr instanceof NullableType) { this._emitExpressionWithUndefinedAssertion(firstExpr); } else { this._emitter._getExpressionEmitterFor(firstExpr).emit(_BinaryExpressionEmitter._operatorPrecedence["/"]); } this._emitter._emit(" / ", this._expr.getToken()); if (this._emitter._enableRunTimeTypeCheck && secondExpr instanceof NullableType) { this._emitExpressionWithUndefinedAssertion(secondExpr); } else { this._emitter._getExpressionEmitterFor(secondExpr).emit(_BinaryExpressionEmitter._operatorPrecedence["/"] - 1); } this._emitter._emit(") | 0", this._expr.getToken()); }.bind(this)); } }, _getPrecedence: function () { return this._precedence; }, $_operatorPrecedence: {}, $_setOperatorPrecedence: function (op, precedence) { _BinaryExpressionEmitter._operatorPrecedence[op] = precedence; } }); var _ArrayExpressionEmitter = exports._ArrayExpressionEmitter = _OperatorExpressionEmitter.extend({ constructor: function (emitter, expr) { _OperatorExpressionEmitter.prototype.constructor.call(this, emitter); this._expr = expr; }, _emit: function () { this._emitter._getExpressionEmitterFor(this._expr.getFirstExpr()).emit(_ArrayExpressionEmitter._operatorPrecedence); var secondExpr = this._expr.getSecondExpr(); // property access using . is 4x faster on safari than using [], see http://jsperf.com/access-using-dot-vs-array var emitted = false; if (secondExpr instanceof StringLiteralExpression) { var propertyName = Util.decodeStringLiteral(secondExpr.getToken().getValue()); if (propertyName.match(/^[\$_A-Za-z][\$_0-9A-Za-z]*$/) != null) { this._emitter._emit(".", this._expr.getToken()); this._emitter._emit(propertyName, secondExpr.getToken()); emitted = true; } } if (! emitted) { this._emitter._emit("[", this._expr.getToken()); this._emitter._getExpressionEmitterFor(secondExpr).emit(0); this._emitter._emit("]", null); } }, _getPrecedence: function () { return _ArrayExpressionEmitter._operatorPrecedence; }, $_operatorPrecedence: 0, $_setOperatorPrecedence: function (op, precedence) { _ArrayExpressionEmitter._operatorPrecedence = precedence; } }); var _ConditionalExpressionEmitter = exports._ConditionalExpressionEmitter = _OperatorExpressionEmitter.extend({ constructor: function (emitter, expr) { _OperatorExpressionEmitter.prototype.constructor.call(this, emitter); this._expr = expr; }, _emit: function () { var precedence = this._getPrecedence(); var ifTrueExpr = this._expr.getIfTrueExpr(); if (ifTrueExpr != null) { this._emitter._getExpressionEmitterFor(this._expr.getCondExpr()).emit(precedence); this._emitter._emit(" ? ", null); this._emitter._getExpressionEmitterFor(ifTrueExpr).emit(precedence); this._emitter._emit(" : ", null); this._emitter._getExpressionEmitterFor(this._expr.getIfFalseExpr()).emit(precedence); } else { this._emitter._getExpressionEmitterFor(this._expr.getCondExpr()).emit(precedence); this._emitter._emit(" || ", null); this._emitter._getExpressionEmitterFor(this._expr.getIfFalseExpr()).emit(precedence); } }, _getPrecedence: function () { return this._expr.getIfTrueExpr() != null ? _ConditionalExpressionEmitter._operatorPrecedence : _BinaryExpressionEmitter._operatorPrecedence["||"]; }, $_operatorPrecedence: 0, $_setOperatorPrecedence: function (op, precedence) { _ConditionalExpressionEmitter._operatorPrecedence = precedence; } }); var _CallExpressionEmitter = exports._CallExpressionEmitter = _OperatorExpressionEmitter.extend({ constructor: function (emitter, expr) { _OperatorExpressionEmitter.prototype.constructor.call(this, emitter); this._expr = expr; }, _emit: function () { if (this._emitSpecial()) return; // normal case var calleeExpr = this._expr.getExpr(); if (this._emitter._enableRunTimeTypeCheck && calleeExpr.getType() instanceof NullableType) this._emitter._emitExpressionWithUndefinedAssertion(calleeExpr); else this._emitter._getExpressionEmitterFor(calleeExpr).emit(_CallExpressionEmitter._operatorPrecedence); this._emitter._emitCallArguments(this._expr.getToken(), "(", this._expr.getArguments(), this._expr.getExpr().getType().resolveIfNullable().getArgumentTypes()); }, _getPrecedence: function () { return _CallExpressionEmitter._operatorPrecedence; }, $_operatorPrecedence: 0, $_setOperatorPrecedence: function (op, precedence) { _CallExpressionEmitter._operatorPrecedence = precedence; }, _emitSpecial: function () { // return false if is not js.apply var calleeExpr = this._expr.getExpr(); if (! (calleeExpr instanceof PropertyExpression)) return false; if (this._emitIfJsInvoke(calleeExpr)) return true; else if (this._emitCallsToMap(calleeExpr)) return true; else if (this._emitIfMathAbs(calleeExpr)) return true; return false; }, _emitIfJsInvoke: function (calleeExpr) { if (! (calleeExpr.getType() instanceof StaticFunctionType)) return false; if (calleeExpr.getIdentifierToken().getValue() != "invoke") return false; var classDef = calleeExpr.getExpr().getType().getClassDef(); if (! (classDef.className() == "js" && classDef.getToken().getFilename() == Util.resolvePath(this._emitter._platform.getRoot() + "/lib/js/js.jsx"))) return false; // emit var args = this._expr.getArguments(); if (args[2] instanceof ArrayLiteralExpression) { this._emitter._getExpressionEmitterFor(args[0]).emit(_PropertyExpressionEmitter._operatorPrecedence); // FIXME emit as property expression if possible this._emitter._emit("[", calleeExpr.getToken()); this._emitter._getExpressionEmitterFor(args[1]).emit(0); this._emitter._emit("]", calleeExpr.getToken()); this._emitter._emitCallArguments(this._expr.getToken(), "(", args[2].getExprs(), null); } else { this._emitter._emit("(function (o, p, a) { return o[p].apply(o, a); }(", calleeExpr.getToken()); this._emitter._getExpressionEmitterFor(args[0]).emit(0); this._emitter._emit(", ", this._expr.getToken()); this._emitter._getExpressionEmitterFor(args[1]).emit(0); this._emitter._emit(", ", this._expr.getToken()); this._emitter._getExpressionEmitterFor(args[2]).emit(0); this._emitter._emit("))", this._expr.getToken()); } return true; }, _emitCallsToMap: function (calleeExpr) { // NOTE once we support member function references, we need to add special handling in _PropertyExpressionEmitter as well if (calleeExpr.getType() instanceof StaticFunctionType) return false; var classDef = calleeExpr.getExpr().getType().getClassDef(); if (! (classDef instanceof InstantiatedClassDefinition)) return false; if (classDef.getTemplateClassName() != "Map") return false; switch (calleeExpr.getIdentifierToken().getValue()) { case "toString": this._emitter._emitCallArguments( calleeExpr.getToken(), "$__jsx_ObjectToString.call(", [ calleeExpr.getExpr() ], [ new ObjectType(classDef) ]); return true; case "hasOwnProperty": this._emitter._emitCallArguments( calleeExpr.getToken(), "$__jsx_ObjectHasOwnProperty.call(", [ calleeExpr.getExpr(), this._expr.getArguments()[0] ], [ new ObjectType(classDef), Type.stringType ]); return true; default: return false; } }, _emitIfMathAbs: function (calleeExpr) { if (! _CallExpressionEmitter._calleeIsMathAbs(calleeExpr)) return false; var argExpr = this._expr.getArguments()[0]; if (argExpr instanceof LeafExpression) { this._emitter._emit("(", this._expr.getToken()); this._emitter._getExpressionEmitterFor(argExpr).emit(0); this._emitter._emit(" >= 0 ? ", this._expr.getToken()); this._emitter._getExpressionEmitterFor(argExpr).emit(0); this._emitter._emit(" : - ", this._expr.getToken()); this._emitter._getExpressionEmitterFor(argExpr).emit(0); this._emitter._emit(")", this._expr.getToken()); } else { this._emitter._emit("(($math_abs_t = ", this._expr.getToken()); this._emitter._getExpressionEmitterFor(argExpr).emit(_BinaryExpressionEmitter._operatorPrecedence["="]); this._emitter._emit(") >= 0 ? $math_abs_t : -$math_abs_t)", this._expr.getToken()); } return true; }, $_calleeIsMathAbs: function (calleeExpr) { if (! (calleeExpr.getType() instanceof StaticFunctionType)) return false; if (calleeExpr.getIdentifierToken().getValue() != "abs") return false; if (calleeExpr.getExpr().getType().getClassDef().className() != "Math") return false; return true; }, $mathAbsUsesTemporary: function (funcDef) { return ! funcDef.forEachStatement(function onStatement(statement) { if (! statement.forEachExpression(function onExpr(expr) { var calleeExpr; if (expr instanceof CallExpression && (calleeExpr = expr.getExpr()) instanceof PropertyExpression && _CallExpressionEmitter._calleeIsMathAbs(calleeExpr) && ! (expr.getArguments()[0] instanceof LeafExpression)) return false; return expr.forEachExpression(onExpr); })) { return false; } return statement.forEachStatement(onStatement); }); } }); var _SuperExpressionEmitter = exports._SuperExpressionEmitter = _OperatorExpressionEmitter.extend({ constructor: function (emitter, expr) { _OperatorExpressionEmitter.prototype.constructor.call(this, emitter); this._expr = expr; }, _emit: function () { var funcType = this._expr.getFunctionType(); var className = funcType.getObjectType().getClassDef().getOutputClassName(); var argTypes = funcType.getArgumentTypes(); var mangledFuncName = this._emitter._mangleFunctionName(this._expr.getName().getValue(), argTypes); this._emitter._emitCallArguments(this._expr.getToken(), className + ".prototype." + mangledFuncName + ".call(this", this._expr.getArguments(), argTypes); }, _getPrecedence: function () { return _CallExpressionEmitter._operatorPrecedence; }, $_operatorPrecedence: 0, $_setOperatorPrecedence: function (op, precedence) { _SuperExpressionEmitter._operatorPrecedence = precedence; } }); var _NewExpressionEmitter = exports._NewExpressionEmitter = _OperatorExpressionEmitter.extend({ constructor: function (emitter, expr) { _OperatorExpressionEmitter.prototype.constructor.call(this, emitter); this._expr = expr; }, emit: function (outerOpPrecedence) { var classDef = this._expr.getType().getClassDef(); var ctor = this._expr.getConstructor(); var argTypes = ctor.getArgumentTypes(); this._emitter._emitCallArguments( this._expr.getToken(), "new " + this._emitter._mangleConstructorName(classDef, argTypes) + "(", this._expr.getArguments(), argTypes); }, _getPrecedence: function () { return _NewExpressionEmitter._operatorPrecedence; }, $_operatorPrecedence: 0, $_setOperatorPrecedence: function (op, precedence) { _NewExpressionEmitter._operatorPrecedence = precedence; } }); var _CommaExpressionEmitter = exports._CommaExpressionEmitter = _ExpressionEmitter.extend({ constructor: function (emitter, expr) { _ExpressionEmitter.prototype.constructor.call(this, emitter); this._expr = expr; }, emit: function (outerOpPrecedence) { // comma operations should be surrounded by brackets unless within a comma expression, since "," might get considered as an argument separator (of function calls, etc.) var useBrackets = outerOpPrecedence != _CommaExpressionEmitter._operatorPrecedence; if (useBrackets) this._emitter._emit("(", null); this._emitter._getExpressionEmitterFor(this._expr.getFirstExpr()).emit(_CommaExpressionEmitter._operatorPrecedence); this._emitter._emit(", ", null); this._emitter._getExpressionEmitterFor(this._expr.getSecondExpr()).emit(_CommaExpressionEmitter._operatorPrecedence); if (useBrackets) this._emitter._emit(")", null); }, $_operatorPrecedence: 0, $_setOperatorPrecedence: function (op, precedence) { _CommaExpressionEmitter._operatorPrecedence = precedence; } }); // the global emitter var JavaScriptEmitter = exports.JavaScriptEmitter = Class.extend({ constructor: function (platform) { this._platform = platform; this._output = ""; this._outputEndsWithReturn = this._output.match(/\n$/) != null; this._outputFile = null; this._indent = 0; this._emittingClass = null; this._emittingFunction = null; this._emittingStatementStack = []; this._enableRunTimeTypeCheck = true; }, getSearchPaths: function () { return [ this._platform.getRoot() + "/lib/js" ]; }, setOutputFile: function (name) { this._outputFile = name; if(this._enableSourceMap) { // FIXME: set correct sourceRoot var sourceRoot = null; this._sourceMapGen = new SourceMapGenerator(name, sourceRoot); } }, saveSourceMappingFile: function (platform) { var gen = this._sourceMapGen; if(gen != null) { platform.save(gen.getSourceMappingFile(), gen.generate()); } }, setSourceMapGenerator: function (gen) { this._sourceMapGen = gen; }, setEnableRunTimeTypeCheck: function (enable) { this._enableRunTimeTypeCheck = enable; }, setEnableSourceMap : function (enable) { this._enableSourceMap = enable; }, setEnableProfiler: function (enable) { this._enableProfiler = enable; }, addHeader: function (header) { this._output += header; }, emit: function (classDefs) { var bootstrap = this._platform.load(this._platform.getRoot() + "/src/js/bootstrap.js"); this._output += bootstrap; for (var i = 0; i < classDefs.length; ++i) { classDefs[i].forEachMemberFunction(function onFuncDef(funcDef) { funcDef.forEachClosure(onFuncDef); _Util.setupBooleanizeFlags(funcDef); return true; }); } for (var i = 0; i < classDefs.length; ++i) { if ((classDefs[i].flags() & ClassDefinition.IS_NATIVE) == 0) this._emitClassDefinition(classDefs[i]); } for (var i = 0; i < classDefs.length; ++i) this._emitStaticInitializationCode(classDefs[i]); this._emitClassMap(classDefs); }, _emitClassDefinition: function (classDef) { this._emittingClass = classDef; try { // emit class object this._emitClassObject(classDef); // emit constructors var ctors = this._findFunctions(classDef, "constructor", false); for (var i = 0; i < ctors.length; ++i) this._emitConstructor(ctors[i]); // emit functions var members = classDef.members(); for (var i = 0; i < members.length; ++i) { var member = members[i]; if (member instanceof MemberFunctionDefinition) { if (! (member.name() == "constructor" && (member.flags() & ClassDefinition.IS_STATIC) == 0) && member.getStatements() != null) { this._emitFunction(member); } } } } finally { this._emittingClass = null; } }, _emitStaticInitializationCode: function (classDef) { if ((classDef.flags() & ClassDefinition.IS_NATIVE) != 0) return; // special handling for js.jsx if (classDef.getToken() != null && classDef.getToken().getFilename() == Util.resolvePath(this._platform.getRoot() + "/lib/js/js.jsx")) { this._emit("js.global = (function () { return this; })();\n\n", null); return; } // normal handling var members = classDef.members(); // FIXME can we (should we?) automatically resolve dependencies? isn't it impossible? for (var i = 0; i < members.length; ++i) { var member = members[i]; if ((member instanceof MemberVariableDefinition) && (member.flags() & (ClassDefinition.IS_STATIC | ClassDefinition.IS_NATIVE)) == ClassDefinition.IS_STATIC) this._emitStaticMemberVariable(classDef.getOutputClassName(), member); } }, _emitClassMap: function (classDefs) { classDefs = classDefs.concat([]); // shallow clone // remove the classDefs wo. source token or native for (var i = 0; i < classDefs.length;) { if (classDefs[i].getToken() == null || (classDefs[i].flags() & ClassDefinition.IS_NATIVE) != 0) classDefs.splice(i, 1); else ++i; } // start emitting this._emit("var $__jsx_classMap = {\n", null); this._advanceIndent(); while (classDefs.length != 0) { // fetch the first classDef, and others that came from the same file var list = []; var pushClass = (function (classDef) { var push = function (suffix) { list.push([ classDef.className() + suffix, classDef.getOutputClassName() + suffix ]); }; var ctors = this._findFunctions(classDef, "constructor", false); push(""); if (ctors.length == 0) { push(this._mangleFunctionArguments([])); } else { for (var i = 0; i < ctors.length; ++i) push(this._mangleFunctionArguments(ctors[i].getArgumentTypes())); } }).bind(this); var filename = classDefs[0].getToken().getFilename(); pushClass(classDefs.shift()); for (var i = 0; i < classDefs.length;) { if (classDefs[i].getToken().getFilename() == filename) { pushClass(classDefs[i]); classDefs.splice(i, 1); } else { ++i; } } // emit the map var escapedFilename = JSON.stringify(this._encodeFilename(filename, "system:")); this._emit(escapedFilename + ": ", null); this._emit("{\n", null); this._advanceIndent(); for (var i = 0; i < list.length; ++i) { this._emit(list[i][0] + ": " + list[i][1], null); if (i != list.length - 1) this._emit(",", null); this._emit("\n", null); } this._reduceIndent(); this._emit("}", null); if (classDefs.length != 0) this._emit(",", null); this._emit("\n", null); } this._reduceIndent(); this._emit("};\n\n", null); }, _encodeFilename: function (filename, prefix) { var rootDir = this._platform.getRoot() + "/"; if (filename.indexOf(rootDir) == 0) filename = prefix + filename.substring(rootDir.length); return filename; }, getOutput: function (sourceFile, entryPoint, executableFor) { var output = this._output + "\n"; if (this._enableProfiler) { output += this._platform.load(this._platform.getRoot() + "/src/js/profiler.js"); } if (entryPoint != null) { output = this._platform.addLauncher(this, this._encodeFilename(sourceFile, "system:"), output, entryPoint, executableFor); } output += "})();\n"; if (this._sourceMapGen) { output += this._sourceMapGen.magicToken(); } return output; }, _emitClassObject: function (classDef) { this._emit( "/**\n" + " * class " + classDef.getOutputClassName() + (classDef.extendType() != null ? " extends " + classDef.extendType().getClassDef().getOutputClassName() : "") + "\n" + " * @constructor\n" + " */\n" + "function ", null); this._emit(classDef.getOutputClassName() + "() {\n" + "}\n" + "\n", classDef.getToken()); if (classDef.extendType() != null) this._emit(classDef.getOutputClassName() + ".prototype = new " + classDef.extendType().getClassDef().getOutputClassName() + ";\n", null); var implementTypes = classDef.implementTypes(); if (implementTypes.length != 0) { for (var i = 0; i < implementTypes.length; ++i) this._emit("$__jsx_merge_interface(" + classDef.getOutputClassName() + ", " + implementTypes[i].getClassDef().getOutputClassName() + ");\n", null); this._emit("\n", null); } if ((classDef.flags() & (ClassDefinition.IS_INTERFACE | ClassDefinition.IS_MIXIN)) != 0) this._emit(classDef.getOutputClassName() + ".prototype.$__jsx_implements_" + classDef.getOutputClassName() + " = true;\n\n", null); }, _emitConstructor: function (funcDef) { var funcName = this._mangleConstructorName(funcDef.getClassDef(), funcDef.getArgumentTypes()); // emit prologue this._emit("/**\n", null); this._emit(" * @constructor\n", null); this._emitFunctionArgumentAnnotations(funcDef); this._emit(" */\n", null); this._emit("function ", null); this._emit(funcName + "(", funcDef.getClassDef().getToken()); this._emitFunctionArguments(funcDef); this._emit(") {\n", null); this._advanceIndent(); // emit body this._emitFunctionBody(funcDef); // emit epilogue this._reduceIndent(); this._emit("};\n\n", null); this._emit(funcName + ".prototype = new " + funcDef.getClassDef().getOutputClassName() + ";\n\n", null); }, _emitFunction: function (funcDef) { var className = funcDef.getClassDef().getOutputClassName(); var funcName = this._mangleFunctionName(funcDef.name(), funcDef.getArgumentTypes()); // emit this._emit("/**\n", null); this._emitFunctionArgumentAnnotations(funcDef); this._emit(_Util.buildAnnotation(" * @return {%1}\n", funcDef.getReturnType()), null); this._emit(" */\n", null); this._emit(className + ".", null); if ((funcDef.flags() & ClassDefinition.IS_STATIC) == 0) this._emit("prototype.", null); this._emit(funcName + " = ", funcDef.getNameToken()); this._emit("function (", funcDef.getToken()); this._emitFunctionArguments(funcDef); this._emit(") {\n", null); this._advanceIndent(); this._emitFunctionBody(funcDef); this._reduceIndent(); this._emit("};\n\n", null); if ((funcDef.flags() & ClassDefinition.IS_STATIC) != 0) this._emit("var " + className + "$" + funcName + " = " + className + "." + funcName + ";\n\n", null); }, _emitFunctionArgumentAnnotations: function (funcDef) { var args = funcDef.getArguments(); for (var i = 0; i < args.length; ++i) this._emit(_Util.buildAnnotation(" * @param {%1} " + args[i].getName().getValue() + "\n", args[i].getType()), null); }, _emitFunctionArguments: function (funcDef) { var args = funcDef.getArguments(); for (var i = 0; i < args.length; ++i) { if (i != 0) this._emit(", "); var name = args[i].getName(); this._emit(name.getValue(), name); } }, _emitFunctionBody: function (funcDef) { var prevEmittingFunction = this._emittingFunction; try { this._emittingFunction = funcDef; if (this._enableProfiler) { this._emit( "var $__jsx_profiler_ctx = $__jsx_profiler.enter(" + Util.encodeStringLiteral( (funcDef.getClassDef() != null ? funcDef.getClassDef().className() : "<<unnamed>>") + ((funcDef.flags() & ClassDefinition.IS_STATIC) != 0 ? "." : "#") + (funcDef.getNameToken() != null ? funcDef.name() : "line_" + funcDef.getToken().getLineNumber()) + "(" + function () { var r = []; funcDef.getArgumentTypes().forEach(function (argType) { r.push(":" + argType.toString()); }); return r.join(", "); }() + ")") + ");\n", null); } // emit reference to this for closures // if funDef is NOT in another closure if (funcDef.getClosures().length != 0 && (funcDef.flags() & ClassDefinition.IS_STATIC) == 0) this._emit("var $this = this;\n", null); // emit helper variable for Math.abs if (_CallExpressionEmitter.mathAbsUsesTemporary(funcDef)) { this._emit("var $math_abs_t;\n", null); } // emit local variable declarations var locals = funcDef.getLocals(); for (var i = 0; i < locals.length; ++i) { // FIXME unused variables should never be emitted by the compiler var type = locals[i].getType(); if (type == null) continue; this._emit(_Util.buildAnnotation("/** @type {%1} */\n", type), null); var name = locals[i].getName(); // do not pass the token for declaration this._emit("var " + name.getValue() + ";\n", null); } // emit code var statements = funcDef.getStatements(); for (var i = 0; i < statements.length; ++i) this._emitStatement(statements[i]); if (this._enableProfiler) { if (statements.length == 0 || ! (statements[statements.length - 1] instanceof ReturnStatement)) { this._emit("$__jsx_profiler.exit();\n", null); } } } finally { this._emittingFunction = prevEmittingFunction; } }, _emitStaticMemberVariable: function (holder, variable) { var initialValue = variable.getInitialValue(); if (initialValue != null && ! (initialValue instanceof NullExpression || initialValue instanceof BooleanLiteralExpression || initialValue instanceof IntegerLiteralExpression || initialValue instanceof NumberLiteralExpression || initialValue instanceof StringLiteralExpression || initialValue instanceof RegExpLiteralExpression)) { // use deferred initialization this._emit("$__jsx_lazy_init(" + holder + ", \"" + variable.name() + "\", function () {\n", variable.getNameToken()); this._advanceIndent(); this._emit("return ", variable.getNameToken()); this._emitRHSOfAssignment(initialValue, variable.getType()); this._emit(";\n", variable.getNameToken()); this._reduceIndent(); this._emit("});\n", variable.getNameToken()); } else { this._emit(holder + "." + variable.name() + " = ", variable.getNameToken()); this._emitRHSOfAssignment(initialValue, variable.getType()); this._emit(";\n", initialValue.getToken()); } }, _emitDefaultValueOf: function (type) { if (type.equals(Type.booleanType)) this._emit("false", null); else if (type.equals(Type.integerType) || type.equals(Type.numberType)) this._emit("0", null); else if (type.equals(Type.stringType)) this._emit("\"\"", null); else if (type instanceof NullableType) this._emit("undefined", null); else this._emit("null", null); }, _emitStatements: function (statements) { this._advanceIndent(); for (var i = 0; i < statements.length; ++i) this._emitStatement(statements[i]); this._reduceIndent(); }, _emitStatement: function (statement) { var emitter = this._getStatementEmitterFor(statement); this._emittingStatementStack.push(emitter); try { emitter.emit(); } finally { this._emittingStatementStack.pop(); } }, _emit: function (str, token) { if (str == "") return; if (this._outputEndsWithReturn && this._indent != 0) { this._output += this._getIndent(); this._outputEndsWithReturn = false; } // optional source map if(this._sourceMapGen != null && token != null) { var lastNewLinePos = this._output.lastIndexOf("\n") + 1; var genColumn = (this._output.length - lastNewLinePos) - 1; var genPos = { line: this._output.match(/^/mg).length, column: genColumn, }; var origPos = { line: token.getLineNumber(), column: token.getColumnNumber() }; var tokenValue = token.isIdentifier() ? token.getValue() : null; var filename = token.getFilename(); if (filename != null) { filename = this._encodeFilename(filename, ""); } this._sourceMapGen.add(genPos, origPos, filename, tokenValue); } str = str.replace(/\n(.)/g, (function (a, m) { return "\n" + this._getIndent() + m; }).bind(this)); this._output += str; this._outputEndsWithReturn = str.charAt(str.length - 1) == "\n"; }, _advanceIndent: function () { ++this._indent; }, _reduceIndent: function () { if (--this._indent < 0) throw new Error("indent mistach"); }, _getIndent: function () { var s = ""; for (var i = 0; i < this._indent; ++i) s += "\t"; return s; }, _getStatementEmitterFor: function (statement) { if (statement instanceof ConstructorInvocationStatement) return new _ConstructorInvocationStatementEmitter(this, statement); else if (statement instanceof ExpressionStatement) return new _ExpressionStatementEmitter(this, statement); else if (statement instanceof ReturnStatement) return new _ReturnStatementEmitter(this, statement); else if (statement instanceof DeleteStatement) return new _DeleteStatementEmitter(this, statement); else if (statement instanceof BreakStatement) return new _BreakStatementEmitter(this, statement); else if (statement instanceof ContinueStatement) return new _ContinueStatementEmitter(this, statement); else if (statement instanceof DoWhileStatement) return new _DoWhileStatementEmitter(this, statement); else if (statement instanceof ForInStatement) return new _ForInStatementEmitter(this, statement); else if (statement instanceof ForStatement) return new _ForStatementEmitter(this, statement); else if (statement instanceof IfStatement) return new _IfStatementEmitter(this, statement); else if (statement instanceof SwitchStatement) return new _SwitchStatementEmitter(this, statement); else if (statement instanceof CaseStatement) return new _CaseStatementEmitter(this, statement); else if (statement instanceof DefaultStatement) return new _DefaultStatementEmitter(this, statement); else if (statement instanceof WhileStatement) return new _WhileStatementEmitter(this, statement); else if (statement instanceof TryStatement) return new _TryStatementEmitter(this, statement); else if (statement instanceof CatchStatement) return new _CatchStatementEmitter(this, statement); else if (statement instanceof ThrowStatement) return new _ThrowStatementEmitter(this, statement); else if (statement instanceof AssertStatement) return new _AssertStatementEmitter(this, statement); else if (statement instanceof LogStatement) return new _LogStatementEmitter(this, statement); else if (statement instanceof DebuggerStatement) return new _DebuggerStatementEmitter(this, statement); throw new Error("got unexpected type of statement: " + JSON.stringify(statement.serialize())); }, _getExpressionEmitterFor: function (expr) { if (expr instanceof LocalExpression) return new _LocalExpressionEmitter(this, expr); else if (expr instanceof ClassExpression) return new _ClassExpressionEmitter(this, expr); else if (expr instanceof NullExpression) return new _NullExpressionEmitter(this, expr); else if (expr instanceof BooleanLiteralExpression) return new _BooleanLiteralExpressionEmitter(this, expr); else if (expr instanceof IntegerLiteralExpression) return new _IntegerLiteralExpressionEmitter(this, expr); else if (expr instanceof NumberLiteralExpression) return new _NumberLiteralExpressionEmitter(this, expr); else if (expr instanceof StringLiteralExpression) return new _StringLiteralExpressionEmitter(this, expr); else if (expr instanceof RegExpLiteralExpression) return new _RegExpLiteralExpressionEmitter(this, expr); else if (expr instanceof ArrayLiteralExpression) return new _ArrayLiteralExpressionEmitter(this, expr); else if (expr instanceof MapLiteralExpression) return new _MapLiteralExpressionEmitter(this, expr); else if (expr instanceof ThisExpression) return new _ThisExpressionEmitter(this, expr); else if (expr instanceof BitwiseNotExpression) return new _UnaryExpressionEmitter(this, expr); else if (expr instanceof InstanceofExpression) return new _InstanceofExpressionEmitter(this, expr); else if (expr instanceof AsExpression) return new _AsExpressionEmitter(this, expr); else if (expr instanceof AsNoConvertExpression) return new _AsNoConvertExpressionEmitter(this, expr); else if (expr instanceof LogicalNotExpression) return new _UnaryExpressionEmitter(this, expr); else if (expr instanceof TypeofExpression) return new _UnaryExpressionEmitter(this, expr); else if (expr instanceof PostIncrementExpression) return new _PostfixExpressionEmitter(this, expr); else if (expr instanceof PreIncrementExpression) return new _UnaryExpressionEmitter(this, expr); else if (expr instanceof PropertyExpression) return new _PropertyExpressionEmitter(this, expr); else if (expr instanceof SignExpression) return new _UnaryExpressionEmitter(this, expr); else if (expr instanceof AdditiveExpression) return new _BinaryExpressionEmitter(this, expr); else if (expr instanceof ArrayExpression) return new _ArrayExpressionEmitter(this, expr); else if (expr instanceof AssignmentExpression) return new _BinaryExpressionEmitter(this, expr); else if (expr instanceof BinaryNumberExpression) return new _BinaryExpressionEmitter(this, expr); else if (expr instanceof EqualityExpression) return new _BinaryExpressionEmitter(this, expr); else if (expr instanceof InExpression) return new _BinaryExpressionEmitter(this, expr); else if (expr instanceof LogicalExpression) return new _BinaryExpressionEmitter(this, expr); else if (expr instanceof ShiftExpression) return new _BinaryExpressionEmitter(this, expr); else if (expr instanceof ConditionalExpression) return new _ConditionalExpressionEmitter(this, expr); else if (expr instanceof CallExpression) return new _CallExpressionEmitter(this, expr); else if (expr instanceof SuperExpression) return new _SuperExpressionEmitter(this, expr); else if (expr instanceof NewExpression) return new _NewExpressionEmitter(this, expr); else if (expr instanceof FunctionExpression) return new _FunctionExpressionEmitter(this, expr); else if (expr instanceof CommaExpression) return new _CommaExpressionEmitter(this, expr); throw new Error("got unexpected type of expression: " + (expr != null ? JSON.stringify(expr.serialize()) : expr)); }, _mangleConstructorName: function (classDef, argTypes) { if ((classDef.flags() & ClassDefinition.IS_NATIVE) != 0) { if (classDef instanceof InstantiatedClassDefinition) { if (classDef.getTemplateClassName() == "Map") { return "Object"; } else { return classDef.getTemplateClassName(); } } else { return classDef.className(); } } return classDef.getOutputClassName() + this._mangleFunctionArguments(argTypes); }, _mangleFunctionName: function (name, argTypes) { // NOTE: how mangling of "toString" is omitted is very hacky, but it seems like the easiest way, taking the fact into consideration that it is the only function in Object if (name != "toString") name += this._mangleFunctionArguments(argTypes); return name; }, _mangleTypeName: function (type) { if (type.equals(Type.voidType)) return "V"; else if (type.equals(Type.booleanType)) return "B"; else if (type.equals(Type.integerType)) return "I"; else if (type.equals(Type.numberType)) return "N"; else if (type.equals(Type.stringType)) return "S"; else if (type instanceof ObjectType) { var classDef = type.getClassDef(); if (classDef instanceof InstantiatedClassDefinition) { var typeArgs = classDef.getTypeArguments(); switch (classDef.getTemplateClassName()) { case "Array": return "A" + this._mangleTypeName(typeArgs[0]); case "Map": return "H" + this._mangleTypeName(typeArgs[0]); default: throw new Error("unexpected template type: " + classDef.getTemplateClassName()); } } return "L" + type.getClassDef().getOutputClassName() + "$"; } else if (type instanceof StaticFunctionType) return "F" + this._mangleFunctionArguments(type.getArgumentTypes()) + this._mangleTypeName(type.getReturnType()) + "$"; else if (type instanceof MemberFunctionType) return "M" + this._mangleTypeName(type.getObjectType()) + this._mangleFunctionArguments(type.getArgumentTypes()) + this._mangleTypeName(type.getReturnType()) + "$"; else if (type instanceof NullableType) return "U" + this._mangleTypeName(type.getBaseType()); else if (type.equals(Type.variantType)) return "X"; else throw new Error("FIXME " + type.toString()); }, _mangleFunctionArguments: function (argTypes) { var s = "$"; for (var i = 0; i < argTypes.length; ++i) s += this._mangleTypeName(argTypes[i]); return s; }, _mangleTypeString: function (s) { return s.length + s; }, _findFunctions: function (classDef, name, isStatic) { var functions = []; var members = classDef.members(); for (var i = 0; i < members.length; ++i) { var member = members[i]; if ((member instanceof MemberFunctionDefinition) && member.name() == name && (member.flags() & ClassDefinition.IS_STATIC) == (isStatic ? ClassDefinition.IS_STATIC : 0)) functions.push(member); } return functions; }, _emitCallArguments: function (token, prefix, args, argTypes) { this._emit(prefix, token); for (var i = 0; i < args.length; ++i) { if (i != 0 || prefix[prefix.length - 1] != '(') this._emit(", ", null); if (argTypes != null && this._enableRunTimeTypeCheck && args[i].getType() instanceof NullableType && ! (argTypes[i] instanceof NullableType || argTypes[i] instanceof VariantType)) { this._emitExpressionWithUndefinedAssertion(args[i]); } else { this._getExpressionEmitterFor(args[i]).emit(0); } } this._emit(")", token); }, _emitAssertion: function (emitTestExpr, token, message) { this._emit("if (! (", token); emitTestExpr(); this._emit(")) {\n", null); this._advanceIndent(); this._emit("debugger;\n", null); // FIXME make the expression source and throw a fit exception class var err = Util.format('throw new Error("[%1:%2] %3");\n', [token.getFilename(), token.getLineNumber(), message]); this._emit(err, null); this._reduceIndent(); this._emit("}\n", null); }, _emitExpressionWithUndefinedAssertion: function (expr) { var token = expr.getToken(); this._emit("(function (v) {\n", token); this._advanceIndent(); this._emitAssertion(function () { this._emit("typeof v !== \"undefined\"", token); }.bind(this), token, "detected misuse of 'undefined' as type '" + expr.getType().resolveIfNullable().toString() + "'"); this._emit("return v;\n", token); this._reduceIndent(); this._emit("}(", token); this._getExpressionEmitterFor(expr).emit(0); this._emit("))", token); }, _emitRHSOfAssignment: function (expr, lhsType) { var exprType = expr.getType(); // FIXME what happens if the op is /= or %= ? if (lhsType.resolveIfNullable().equals(Type.integerType) && exprType.equals(Type.numberType)) { if (expr instanceof NumberLiteralExpression || expr instanceof IntegerLiteralExpression) { this._emit((expr.getToken().getValue() | 0).toString(), expr.getToken()); } else { this._emit("(", expr.getToken()); this._getExpressionEmitterFor(expr).emit(_BinaryExpressionEmitter._operatorPrecedence["|"]); this._emit(" | 0)", expr.getToken()); } return; } if (lhsType.equals(Type.integerType) && (exprType instanceof NullableType && exprType.getBaseType().equals(Type.numberType))) { this._emit("(", expr.getToken()); if (this._enableRunTimeTypeCheck) { this._emitExpressionWithUndefinedAssertion(expr); } else { this._getExpressionEmitterFor(expr).emit(_BinaryExpressionEmitter._operatorPrecedence["|"]); } this._emit(" | 0)", expr.getToken()); return; } if ((lhsType instanceof NullableType && lhsType.getBaseType().equals(Type.integerType)) && (exprType instanceof NullableType && exprType.getBaseType().equals(Type.numberType))) { // NOTE this is very slow, but such an operation would practically not be found this._emit("(function (v) { return v !== undefined ? v | 0 : v; })(", expr.getToken()); this._getExpressionEmitterFor(expr).emit(0); this._emit(")", expr.getToken()); return; } // normal mode if (this._enableRunTimeTypeCheck && ! (lhsType instanceof NullableType || lhsType.equals(Type.variantType)) && exprType instanceof NullableType) { this._emitExpressionWithUndefinedAssertion(expr); } else { this._getExpressionEmitterFor(expr).emit(_BinaryExpressionEmitter._operatorPrecedence["="]); } }, $constructor: function () { var precedence = [ [ [ "new", _NewExpressionEmitter._setOperatorPrecedence ], [ "[", _ArrayExpressionEmitter._setOperatorPrecedence ], [ ".", _PropertyExpressionEmitter._setOperatorPrecedence ], [ "(", _CallExpressionEmitter._setOperatorPrecedence ], [ "super", _SuperExpressionEmitter._setOperatorPrecedence ], [ "function", _FunctionExpressionEmitter._setOperatorPrecedence ], ], [ [ "++", _PostfixExpressionEmitter._setOperatorPrecedence ], [ "--", _PostfixExpressionEmitter._setOperatorPrecedence ] ], [ // delete is not used by JSX [ "void", _UnaryExpressionEmitter._setOperatorPrecedence ], [ "typeof", _UnaryExpressionEmitter._setOperatorPrecedence ], [ "++", _UnaryExpressionEmitter._setOperatorPrecedence ], [ "--", _UnaryExpressionEmitter._setOperatorPrecedence ], [ "+", _UnaryExpressionEmitter._setOperatorPrecedence ], [ "-", _UnaryExpressionEmitter._setOperatorPrecedence ], [ "~", _UnaryExpressionEmitter._setOperatorPrecedence ], [ "!", _UnaryExpressionEmitter._setOperatorPrecedence ] ], [ [ "*", _BinaryExpressionEmitter._setOperatorPrecedence ], [ "/", _BinaryExpressionEmitter._setOperatorPrecedence ], [ "%", _BinaryExpressionEmitter._setOperatorPrecedence ] ], [ [ "+", _BinaryExpressionEmitter._setOperatorPrecedence ], [ "-", _BinaryExpressionEmitter._setOperatorPrecedence ] ], [ [ "<<", _BinaryExpressionEmitter._setOperatorPrecedence ], [ ">>", _BinaryExpressionEmitter._setOperatorPrecedence ], [ ">>>", _BinaryExpressionEmitter._setOperatorPrecedence ], ], [ [ "<", _BinaryExpressionEmitter._setOperatorPrecedence ], [ ">", _BinaryExpressionEmitter._setOperatorPrecedence ], [ "<=", _BinaryExpressionEmitter._setOperatorPrecedence ], [ ">=", _BinaryExpressionEmitter._setOperatorPrecedence ], [ "instanceof", _InstanceofExpressionEmitter._setOperatorPrecedence ], [ "in", _BinaryExpressionEmitter._setOperatorPrecedence ] ], [ [ "==", _BinaryExpressionEmitter._setOperatorPrecedence ], [ "!=", _BinaryExpressionEmitter._setOperatorPrecedence ] ], [ [ "&", _BinaryExpressionEmitter._setOperatorPrecedence ] ], [ [ "^", _BinaryExpressionEmitter._setOperatorPrecedence ] ], [ [ "|", _BinaryExpressionEmitter._setOperatorPrecedence ] ], [ [ "&&", _BinaryExpressionEmitter._setOperatorPrecedence ] ], [ [ "||", _BinaryExpressionEmitter._setOperatorPrecedence ] ], [ [ "=", _BinaryExpressionEmitter._setOperatorPrecedence ], [ "*=", _BinaryExpressionEmitter._setOperatorPrecedence ], [ "/=", _BinaryExpressionEmitter._setOperatorPrecedence ], [ "%=", _BinaryExpressionEmitter._setOperatorPrecedence ], [ "+=", _BinaryExpressionEmitter._setOperatorPrecedence ], [ "-=", _BinaryExpressionEmitter._setOperatorPrecedence ], [ "<<=", _BinaryExpressionEmitter._setOperatorPrecedence ], [ ">>=", _BinaryExpressionEmitter._setOperatorPrecedence ], [ ">>>=", _BinaryExpressionEmitter._setOperatorPrecedence ], [ "&=", _BinaryExpressionEmitter._setOperatorPrecedence ], [ "^=", _BinaryExpressionEmitter._setOperatorPrecedence ], [ "|=", _BinaryExpressionEmitter._setOperatorPrecedence ] ], [ [ "?", _ConditionalExpressionEmitter._setOperatorPrecedence ] ], [ [ ",", _CommaExpressionEmitter._setOperatorPrecedence ] ] ]; for (var i = 0; i < precedence.length; ++i) { var opTypeList = precedence[i]; for (var j = 0; j < opTypeList.length; ++j) opTypeList[j][1](opTypeList[j][0], -(precedence.length - i)); } } }); // vim: set noexpandtab:
src/jsemitter.js
/* * Copyright (c) 2012 DeNA Co., Ltd. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ var Class = require("./Class"); eval(Class.$import("./classdef")); eval(Class.$import("./type")); eval(Class.$import("./expression")); eval(Class.$import("./statement")); eval(Class.$import("./emitter")); eval(Class.$import("./jssourcemap")); eval(Class.$import("./util")); "use strict"; var _Util = exports._Util = Class.extend({ $toClosureType: function (type) { if (type.equals(Type.booleanType)) { return "!boolean"; } else if (type.equals(Type.integerType) || type.equals(Type.numberType)) { return "!number"; } else if (type.equals(Type.stringType)) { return "!string"; } else if (type instanceof NullableType) { return "undefined|" + this.toClosureType(type.getBaseType()); } else if (type instanceof ObjectType) { var classDef = type.getClassDef(); if (classDef instanceof InstantiatedClassDefinition && classDef.getTemplateClassName() == "Array") { return "Array.<undefined|" + this.toClosureType(classDef.getTypeArguments()[0]) + ">"; } else if (classDef instanceof InstantiatedClassDefinition && classDef.getTemplateClassName() == "Map") { return "Object.<string, undefined|" + this.toClosureType(classDef.getTypeArguments()[0]) + ">"; } else { return classDef.getOutputClassName(); } } else if (type instanceof VariantType) { return "*"; } return null; }, $getInstanceofNameFromClassDef: function (classDef) { if (classDef instanceof InstantiatedClassDefinition) { var name = classDef.getTemplateClassName(); if (name == "Map") name = "Object"; } else { name = classDef.getOutputClassName(); } return name; }, $buildAnnotation: function (template, type) { var closureType = this.toClosureType(type); if (closureType == null) return ""; return Util.format(template, [closureType]); }, $emitLabelOfStatement: function (emitter, statement) { var label = statement.getLabel(); if (label != null) { emitter._reduceIndent(); emitter._emit(label.getValue() + ":\n", label); emitter._advanceIndent(); } }, $getStash: function (stashable) { var stashHash = stashable.getOptimizerStash(); var stash; if ((stash = stashHash["jsemitter"]) == null) { stash = stashHash["jsemitter"] = {}; } return stashHash; }, $setupBooleanizeFlags: function (funcDef) { var exprReturnsBoolean = function (expr) { if (expr instanceof LogicalExpression) { return _Util.getStash(expr).returnsBoolean; } else { return expr.getType().equals(Type.booleanType); } }; funcDef.forEachStatement(function onStatement(statement) { var parentExpr = []; // [0] is stack top statement.forEachExpression(function onExpr(expr) { // handle children parentExpr.unshift(expr); expr.forEachExpression(onExpr.bind(this)); parentExpr.shift(); // check if (expr instanceof LogicalExpression) { var shouldBooleanize = true; var returnsBoolean = false; if (exprReturnsBoolean(expr.getFirstExpr()) && exprReturnsBoolean(expr.getSecondExpr())) { returnsBoolean = true; shouldBooleanize = false; } else if (parentExpr.length == 0) { if (statement instanceof ExpressionStatement || statement instanceof IfStatement || statement instanceof DoWhileStatement || statement instanceof WhileStatement || statement instanceof ForStatement) { shouldBooleanize = false; } } else if (parentExpr[0] instanceof LogicalExpression || parentExpr[0] instanceof LogicalNotExpression) { shouldBooleanize = false; } else if (parentExpr[0] instanceof ConditionalExpression && parentExpr[0].getCondExpr() == expr) { shouldBooleanize = false; } _Util.getStash(expr).shouldBooleanize = shouldBooleanize; _Util.getStash(expr).returnsBoolean = returnsBoolean; } return true; }); return statement.forEachStatement(onStatement.bind(this)); }); }, $shouldBooleanize: function (logicalExpr) { return _Util.getStash(logicalExpr).shouldBooleanize; } }); // statement emitter var _StatementEmitter = exports._StatementEmitter = Class.extend({ constructor: function (emitter) { this._emitter = emitter; } }); var _ConstructorInvocationStatementEmitter = exports._ConstructorInvocationStatementEmitter = _StatementEmitter.extend({ constructor: function (emitter, statement) { _StatementEmitter.prototype.constructor.call(this, emitter); this._statement = statement; }, emit: function () { var ctorType = this._statement.getConstructorType(); var argTypes = ctorType != null ? ctorType.getArgumentTypes() : []; var ctorName = this._emitter._mangleConstructorName(this._statement.getConstructingClassDef(), argTypes); var token = this._statement.getToken(); if (ctorName == "Error" && this._statement.getArguments().length == 1) { /* At least v8 does not support "Error.call(this, message)"; it not only does not setup the stacktrace but also does not set the message property. So we set the message property. We continue to call "Error" hoping that it would have some positive effect on other platforms (like setting the stacktrace, etc.). FIXME check that doing "Error.call(this);" does not have any negative effect on other platforms */ this._emitter._emit("Error.call(this);\n", token); this._emitter._emit("this.message = ", token); this._emitter._getExpressionEmitterFor(this._statement.getArguments()[0]).emit(_BinaryExpressionEmitter._operatorPrecedence["="]); this._emitter._emit(";\n", token); } else { this._emitter._emitCallArguments(token, ctorName + ".call(this", this._statement.getArguments(), argTypes); this._emitter._emit(";\n", token); } } }); var _ExpressionStatementEmitter = exports._ExpressionStatementEmitter = _StatementEmitter.extend({ constructor: function (emitter, statement) { _StatementEmitter.prototype.constructor.call(this, emitter); this._statement = statement; }, emit: function () { this._emitter._getExpressionEmitterFor(this._statement.getExpr()).emit(0); this._emitter._emit(";\n", null); } }); var _ReturnStatementEmitter = exports._ReturnStatementEmitter = _StatementEmitter.extend({ constructor: function (emitter, statement) { _StatementEmitter.prototype.constructor.call(this, emitter); this._statement = statement; }, emit: function () { var expr = this._statement.getExpr(); if (expr != null) { this._emitter._emit("return ", null); if (this._emitter._enableProfiler) { this._emitter._emit("$__jsx_profiler.exit(", null); } this._emitter._emitRHSOfAssignment(this._statement.getExpr(), this._emitter._emittingFunction.getReturnType()); if (this._emitter._enableProfiler) { this._emitter._emit(")", null); } this._emitter._emit(";\n", null); } else { if (this._emitter._enableProfiler) { this._emitter._emit("return $__jsx_profiler.exit();\n", this._statement.getToken()); } else { this._emitter._emit("return;\n", this._statement.getToken()); } } } }); var _DeleteStatementEmitter = exports._DeleteStatementEmitter = _StatementEmitter.extend({ constructor: function (emitter, statement) { _StatementEmitter.prototype.constructor.call(this, emitter); this._statement = statement; }, emit: function () { this._emitter._emit("delete ", this._statement.getToken()); this._emitter._getExpressionEmitterFor(this._statement.getExpr()).emit(0); this._emitter._emit(";\n", null); } }); var _BreakStatementEmitter = exports._BreakStatementEmitter = _StatementEmitter.extend({ constructor: function (emitter, statement) { _StatementEmitter.prototype.constructor.call(this, emitter); this._statement = statement; }, emit: function () { if (this._statement.getLabel() != null) this._emitter._emit("break " + this._statement.getLabel().getValue() + ";\n", this._statement.getToken()); else this._emitter._emit("break;\n", this._statement.getToken()); } }); var _ContinueStatementEmitter = exports._ContinueStatementEmitter = _StatementEmitter.extend({ constructor: function (emitter, statement) { _StatementEmitter.prototype.constructor.call(this, emitter); this._statement = statement; }, emit: function () { if (this._statement.getLabel() != null) this._emitter._emit("continue " + this._statement.getLabel().getValue() + ";\n", this._statement.getToken()); else this._emitter._emit("continue;\n", this._statement.getToken()); } }); var _DoWhileStatementEmitter = exports._DoWhileStatementEmitter = _StatementEmitter.extend({ constructor: function (emitter, statement) { _StatementEmitter.prototype.constructor.call(this, emitter); this._statement = statement; }, emit: function () { _Util.emitLabelOfStatement(this._emitter, this._statement); this._emitter._emit("do {\n", null); this._emitter._emitStatements(this._statement.getStatements()); this._emitter._emit("} while (", null); this._emitter._getExpressionEmitterFor(this._statement.getExpr()).emit(0); this._emitter._emit(");\n", null); } }); var _ForInStatementEmitter = exports._ForInStatementEmitter = _StatementEmitter.extend({ constructor: function (emitter, statement) { _StatementEmitter.prototype.constructor.call(this, emitter); this._statement = statement; }, emit: function () { _Util.emitLabelOfStatement(this._emitter, this._statement); this._emitter._emit("for (", null); this._emitter._getExpressionEmitterFor(this._statement.getLHSExpr()).emit(0); this._emitter._emit(" in ", null); this._emitter._getExpressionEmitterFor(this._statement.getListExpr()).emit(0); this._emitter._emit(") {\n", null); this._emitter._emitStatements(this._statement.getStatements()); this._emitter._emit("}\n", null); } }); var _ForStatementEmitter = exports._ForStatementEmitter = _StatementEmitter.extend({ constructor: function (emitter, statement) { _StatementEmitter.prototype.constructor.call(this, emitter); this._statement = statement; }, emit: function () { _Util.emitLabelOfStatement(this._emitter, this._statement); this._emitter._emit("for (", this._statement.getToken()); var initExpr = this._statement.getInitExpr(); if (initExpr != null) this._emitter._getExpressionEmitterFor(initExpr).emit(0); this._emitter._emit("; ", null); var condExpr = this._statement.getCondExpr(); if (condExpr != null) this._emitter._getExpressionEmitterFor(condExpr).emit(0); this._emitter._emit("; ", null); var postExpr = this._statement.getPostExpr(); if (postExpr != null) this._emitter._getExpressionEmitterFor(postExpr).emit(0); this._emitter._emit(") {\n", null); this._emitter._emitStatements(this._statement.getStatements()); this._emitter._emit("}\n", null); } }); var _IfStatementEmitter = exports._IfStatementEmitter = _StatementEmitter.extend({ constructor: function (emitter, statement) { _StatementEmitter.prototype.constructor.call(this, emitter); this._statement = statement; }, emit: function () { this._emitter._emit("if (", this._statement.getToken()); this._emitter._getExpressionEmitterFor(this._statement.getExpr()).emit(0); this._emitter._emit(") {\n", null); this._emitter._emitStatements(this._statement.getOnTrueStatements()); var ifFalseStatements = this._statement.getOnFalseStatements(); if (ifFalseStatements.length != 0) { this._emitter._emit("} else {\n", null); this._emitter._emitStatements(ifFalseStatements); } this._emitter._emit("}\n", null); } }); var _SwitchStatementEmitter = exports._SwitchStatementEmitter = _StatementEmitter.extend({ constructor: function (emitter, statement) { _StatementEmitter.prototype.constructor.call(this, emitter); this._statement = statement; }, emit: function () { _Util.emitLabelOfStatement(this._emitter, this._statement); this._emitter._emit("switch (", this._statement.getToken()); var expr = this._statement.getExpr(); if (this._emitter._enableRunTimeTypeCheck && expr.getType() instanceof NullableType) { this._emitter._emitExpressionWithUndefinedAssertion(expr); } else { this._emitter._getExpressionEmitterFor(expr).emit(0); } this._emitter._emit(") {\n", null); this._emitter._emitStatements(this._statement.getStatements()); this._emitter._emit("}\n", null); } }); var _CaseStatementEmitter = exports._CaseStatementEmitter = _StatementEmitter.extend({ constructor: function (emitter, statement) { _StatementEmitter.prototype.constructor.call(this, emitter); this._statement = statement; }, emit: function () { this._emitter._reduceIndent(); this._emitter._emit("case ", null); var expr = this._statement.getExpr(); if (this._emitter._enableRunTimeTypeCheck && expr.getType() instanceof NullableType) { this._emitter._emitExpressionWithUndefinedAssertion(expr); } else { this._emitter._getExpressionEmitterFor(expr).emit(0); } this._emitter._emit(":\n", null); this._emitter._advanceIndent(); } }); var _DefaultStatementEmitter = exports._DefaultStatementEmitter = _StatementEmitter.extend({ constructor: function (emitter, statement) { _StatementEmitter.prototype.constructor.call(this, emitter); this._statement = statement; }, emit: function () { this._emitter._reduceIndent(); this._emitter._emit("default:\n", null); this._emitter._advanceIndent(); } }); var _WhileStatementEmitter = exports._WhileStatementEmitter = _StatementEmitter.extend({ constructor: function (emitter, statement) { _StatementEmitter.prototype.constructor.call(this, emitter); this._statement = statement; }, emit: function () { _Util.emitLabelOfStatement(this._emitter, this._statement); this._emitter._emit("while (", this._statement.getToken()); this._emitter._getExpressionEmitterFor(this._statement.getExpr()).emit(0); this._emitter._emit(") {\n", null); this._emitter._emitStatements(this._statement.getStatements()); this._emitter._emit("}\n", null); } }); var _TryStatementEmitter = exports._TryStatementEmitter = _StatementEmitter.extend({ constructor: function (emitter, statement) { _StatementEmitter.prototype.constructor.call(this, emitter); this._statement = statement; var outerCatchStatements = 0; for (var i = 0; i < this._emitter._emittingStatementStack.length; ++i) { if (this._emitter._emittingStatementStack[i] instanceof _TryStatementEmitter) ++outerCatchStatements; } this._emittingLocalName = "$__jsx_catch_" + outerCatchStatements; }, emit: function () { this._emitter._emit("try {\n", this._statement.getToken()); this._emitter._emitStatements(this._statement.getTryStatements()); this._emitter._emit("}", null); var catchStatements = this._statement.getCatchStatements(); if (catchStatements.length != 0) { this._emitter._emit(" catch (" + this._emittingLocalName + ") {\n", null); if (this._emitter._enableProfiler) { this._emitter._advanceIndent(); this._emitter._emit("$__jsx_profiler.resume($__jsx_profiler_ctx);\n", null); this._emitter._reduceIndent(); } this._emitter._emitStatements(catchStatements); if (! catchStatements[catchStatements.length - 1].getLocal().getType().equals(Type.variantType)) { this._emitter._advanceIndent(); this._emitter._emit("{\n", null); this._emitter._advanceIndent(); this._emitter._emit("throw " + this._emittingLocalName + ";\n", null); this._emitter._reduceIndent(); this._emitter._emit("}\n", null); this._emitter._reduceIndent(); } this._emitter._emit("}", null); } var finallyStatements = this._statement.getFinallyStatements(); if (finallyStatements.length != 0) { this._emitter._emit(" finally {\n", null); this._emitter._emitStatements(finallyStatements); this._emitter._emit("}", null); } this._emitter._emit("\n", null); }, getEmittingLocalName: function () { return this._emittingLocalName; } }); var _CatchStatementEmitter = exports._CatchStatementEmitter = _StatementEmitter.extend({ constructor: function (emitter, statement) { _StatementEmitter.prototype.constructor.call(this, emitter); this._statement = statement; }, emit: function () { var localType = this._statement.getLocal().getType(); if (localType instanceof ObjectType) { var tryStatement = this._emitter._emittingStatementStack[this._emitter._emittingStatementStack.length - 2]; var localName = tryStatement.getEmittingLocalName(); this._emitter._emit("if (" + localName + " instanceof " + localType.getClassDef().getOutputClassName() + ") {\n", this._statement.getToken()); this._emitter._emitStatements(this._statement.getStatements()); this._emitter._emit("} else ", null); } else { this._emitter._emit("{\n", null); this._emitter._emitStatements(this._statement.getStatements()); this._emitter._emit("}\n", null); } }, $getLocalNameFor: function (emitter, name) { for (var i = emitter._emittingStatementStack.length - 1; i >= 0; --i) { if (! (emitter._emittingStatementStack[i] instanceof _CatchStatementEmitter)) continue; var catchStatement = emitter._emittingStatementStack[i]; if (catchStatement._statement.getLocal().getName().getValue() == name) { var tryEmitter = emitter._emittingStatementStack[i - 1]; if (! (tryEmitter instanceof _TryStatementEmitter)) throw new Error("logic flaw"); return tryEmitter.getEmittingLocalName(); } } throw new Error("logic flaw"); } }); var _ThrowStatementEmitter = exports._ThrowStatementEmitter = _StatementEmitter.extend({ constructor: function (emitter, statement) { _StatementEmitter.prototype.constructor.call(this, emitter); this._statement = statement; }, emit: function () { this._emitter._emit("throw ", this._statement.getToken()); this._emitter._getExpressionEmitterFor(this._statement.getExpr()).emit(0); this._emitter._emit(";\n", null); } }); var _AssertStatementEmitter = exports._AssertStatementEmitter = _StatementEmitter.extend({ constructor: function (emitter, statement) { _StatementEmitter.prototype.constructor.call(this, emitter); this._statement = statement; }, emit: function () { var condExpr = this._statement._expr; this._emitter._emitAssertion(function () { this._emitter._getExpressionEmitterFor(condExpr).emit(0); }.bind(this), this._statement.getToken(), "assertion failure"); } }); var _LogStatementEmitter = exports._LogStatementEmitter = _StatementEmitter.extend({ constructor: function (emitter, statement) { _StatementEmitter.prototype.constructor.call(this, emitter); this._statement = statement; }, emit: function () { this._emitter._emit("console.log(", this._statement.getToken()); var exprs = this._statement.getExprs(); for (var i = 0; i < exprs.length; ++i) { if (i != 0) this._emitter._emit(", ", null); this._emitter._getExpressionEmitterFor(exprs[i]).emit(0); } this._emitter._emit(");\n", null); } }); var _DebuggerStatementEmitter = exports._DebuggerStatementEmitter = _StatementEmitter.extend({ constructor: function (emitter, statement) { _StatementEmitter.prototype.constructor.call(this, emitter); this._statement = statement; }, emit: function () { this._emitter._emit("debugger;\n", this._statement.getToken()); } }); // expression emitter var _ExpressionEmitter = exports._ExpressionEmitter = Class.extend({ constructor: function (emitter) { this._emitter = emitter; }, emitWithPrecedence: function (outerOpPrecedence, precedence, callback) { if (precedence > outerOpPrecedence) { this._emitter._emit("(", null); callback(); this._emitter._emit(")", null); } else { callback(); } } }); var _LocalExpressionEmitter = exports._LocalExpressionEmitter = _ExpressionEmitter.extend({ constructor: function (emitter, expr) { _ExpressionEmitter.prototype.constructor.call(this, emitter); this._expr = expr; }, emit: function (outerOpPrecedence) { var local = this._expr.getLocal(); var localName = local.getName().getValue(); if (local instanceof CaughtVariable) { localName = _CatchStatementEmitter.getLocalNameFor(this._emitter, localName); } this._emitter._emit(localName, this._expr.getToken()); } }); var _ClassExpressionEmitter = exports._ClassExpressionEmitter = _ExpressionEmitter.extend({ constructor: function (emitter, expr) { _ExpressionEmitter.prototype.constructor.call(this, emitter); this._expr = expr; }, emit: function (outerOpPrecedence) { var type = this._expr.getType(); this._emitter._emit(type.getClassDef().getOutputClassName(), null); } }); var _NullExpressionEmitter = exports._NullExpressionEmitter = _ExpressionEmitter.extend({ constructor: function (emitter, expr) { _ExpressionEmitter.prototype.constructor.call(this, emitter); this._expr = expr; }, emit: function (outerOpPrecedence) { var token = this._expr.getToken(); this._emitter._emit("undefined", token); } }); var _BooleanLiteralExpressionEmitter = exports._BooleanLiteralExpressionEmitter = _ExpressionEmitter.extend({ constructor: function (emitter, expr) { _ExpressionEmitter.prototype.constructor.call(this, emitter); this._expr = expr; }, emit: function (outerOpPrecedence) { var token = this._expr.getToken(); this._emitter._emit(token.getValue(), token); } }); var _IntegerLiteralExpressionEmitter = exports._IntegerLiteralExpressionEmitter = _ExpressionEmitter.extend({ constructor: function (emitter, expr) { _ExpressionEmitter.prototype.constructor.call(this, emitter); this._expr = expr; }, emit: function (outerOpPrecedence) { var token = this._expr.getToken(); this._emitter._emit("" + token.getValue(), token); } }); var _NumberLiteralExpressionEmitter = exports._NumberLiteralExpressionEmitter = _ExpressionEmitter.extend({ constructor: function (emitter, expr) { _ExpressionEmitter.prototype.constructor.call(this, emitter); this._expr = expr; }, emit: function (outerOpPrecedence) { var token = this._expr.getToken(); var str = token.getValue(); if (outerOpPrecedence == _PropertyExpressionEmitter._operatorPrecedence && str.indexOf(".") == -1) { this._emitter._emit("(" + str + ")", token); } else { this._emitter._emit("" + str, token); } } }); var _StringLiteralExpressionEmitter = exports._StringLiteralExpressionEmitter = _ExpressionEmitter.extend({ constructor: function (emitter, expr) { _ExpressionEmitter.prototype.constructor.call(this, emitter); this._expr = expr; }, emit: function (outerOpPrecedence) { var token = this._expr.getToken(); // FIXME escape this._emitter._emit(token.getValue(), token); } }); var _RegExpLiteralExpressionEmitter = exports._RegExpLiteralExpressionEmitter = _ExpressionEmitter.extend({ constructor: function (emitter, expr) { _ExpressionEmitter.prototype.constructor.call(this, emitter); this._expr = expr; }, emit: function (outerOpPrecedence) { var token = this._expr.getToken(); this._emitter._emit(token.getValue(), token); } }); var _ArrayLiteralExpressionEmitter = exports._ArrayLiteralExpressionEmitter = _ExpressionEmitter.extend({ constructor: function (emitter, expr) { _ExpressionEmitter.prototype.constructor.call(this, emitter); this._expr = expr; }, emit: function (outerOpPrecedence) { this._emitter._emit("[ ", null); var exprs = this._expr.getExprs(); for (var i = 0; i < exprs.length; ++i) { if (i != 0) this._emitter._emit(", ", null); this._emitter._getExpressionEmitterFor(exprs[i]).emit(0); } this._emitter._emit(" ]", null); } }); var _MapLiteralExpressionEmitter = exports._MapLiteralExpressionEmitter = _ExpressionEmitter.extend({ constructor: function (emitter, expr) { _ExpressionEmitter.prototype.constructor.call(this, emitter); this._expr = expr; }, emit: function (outerOpPrecedence) { this._emitter._emit("{ ", null); var elements = this._expr.getElements(); for (var i = 0; i < elements.length; ++i) { var element = elements[i]; if (i != 0) this._emitter._emit(", ", null); this._emitter._emit(element.getKey().getValue(), element.getKey()); this._emitter._emit(": ", null); this._emitter._getExpressionEmitterFor(element.getExpr()).emit(0); } this._emitter._emit(" }", null); } }); var _ThisExpressionEmitter = exports._ThisExpressionEmitter = _ExpressionEmitter.extend({ constructor: function (emitter, expr) { _ExpressionEmitter.prototype.constructor.call(this, emitter); this._expr = expr; }, emit: function (outerOpPrecedence) { var emittingFunction = this._emitter._emittingFunction; if ((emittingFunction.flags() & ClassDefinition.IS_STATIC) != 0) this._emitter._emit("$this", this._expr.getToken()); else this._emitter._emit("this", this._expr.getToken()); } }); var _AsExpressionEmitter = exports._AsExpressionEmitter = _ExpressionEmitter.extend({ constructor: function (emitter, expr) { _ExpressionEmitter.prototype.constructor.call(this, emitter); this._expr = expr; }, emit: function (outerOpPrecedence) { var srcType = this._expr.getExpr().getType(); var destType = this._expr.getType(); if (srcType.resolveIfNullable() instanceof ObjectType || srcType.equals(Type.variantType)) { if (srcType.resolveIfNullable().isConvertibleTo(destType)) { if (srcType instanceof NullableType) { var prec = _BinaryExpressionEmitter._operatorPrecedence["||"]; this._emitWithParens(outerOpPrecedence, prec, prec, null, "|| null"); } else { this._emitter._getExpressionEmitterFor(this._expr.getExpr()).emit(outerOpPrecedence); } return true; } if (destType instanceof ObjectType) { // unsafe cast if ((destType.getClassDef().flags() & (ClassDefinition.IS_INTERFACE | ClassDefinition.IS_MIXIN)) == 0) { this.emitWithPrecedence(outerOpPrecedence, _CallExpressionEmitter._operatorPrecedence, (function () { this._emitter._emit("(function (o) { return o instanceof " + _Util.getInstanceofNameFromClassDef(destType.getClassDef()) + " ? o : null; })(", this._expr.getToken()); this._emitter._getExpressionEmitterFor(this._expr.getExpr()).emit(0); this._emitter._emit(")", this._expr.getToken()); }).bind(this)); } else { this.emitWithPrecedence(outerOpPrecedence, _CallExpressionEmitter._operatorPrecedence, (function () { this._emitter._emit("(function (o) { return o && o.$__jsx_implements_" + destType.getClassDef().getOutputClassName() + " ? o : null; })(", this._expr.getToken()); this._emitter._getExpressionEmitterFor(this._expr.getExpr()).emit(0); this._emitter._emit(")", this._expr.getToken()); }).bind(this)); } return true; } if (destType instanceof FunctionType) { // cast to function this._emitter._emit("(function (o) { return typeof(o) === \"function\" ? o : null; })(", this._expr.getToken()); this._emitter._getExpressionEmitterFor(this._expr.getExpr()).emit(0); this._emitter._emit(")", this._expr.getToken()); return true; } } if (srcType.equals(Type.nullType)) { // from null if (destType.equals(Type.booleanType)) { this._emitter._emit("false", this._expr.getToken()); return true; } if (destType.equals(Type.integerType) || destType.equals(Type.numberType)) { this._emitter._emit("0", this._expr.getToken()); return true; } if (destType.equals(Type.stringType)) { this._emitter._emit("\"null\"", this._expr.getToken()); return true; } if (destType instanceof ObjectType || destType instanceof FunctionType) { this._emitter._emit("null", this._expr.getToken()); return true; } } if (srcType.equals(Type.booleanType)) { // from boolean if (destType.equals(Type.integerType) || destType.equals(Type.numberType)) { var prec = _UnaryExpressionEmitter._operatorPrecedence["+"]; this._emitWithParens(outerOpPrecedence, prec, prec, "+", null); return true; } if (destType.equals(Type.stringType)) { var prec = _BinaryExpressionEmitter._operatorPrecedence["+"]; this._emitWithParens(outerOpPrecedence, prec, prec, null, " + \"\""); return true; } } if (srcType instanceof NullableType && srcType.getBaseType().equals(Type.booleanType)) { // from Nullable.<boolean> if (destType.equals(Type.booleanType)) { var prec = _BinaryExpressionEmitter._operatorPrecedence["||"]; this._emitWithParens(outerOpPrecedence, prec, prec, null, " || false"); return true; } if (destType.equals(Type.integerType) || destType.equals(Type.numberType)) { this._emitWithParens( outerOpPrecedence, _BinaryExpressionEmitter._operatorPrecedence["-"], _UnaryExpressionEmitter._operatorPrecedence["!"], "1 - ! ", null); return true; } if (destType.equals(Type.stringType)) { var prec = _BinaryExpressionEmitter._operatorPrecedence["+"]; this._emitWithParens(outerOpPrecedence, prec, prec, null, " + \"\""); return true; } } if (srcType.equals(Type.integerType)) { // from integer if (destType.equals(Type.booleanType)) { var prec = _UnaryExpressionEmitter._operatorPrecedence["!"]; this._emitWithParens(outerOpPrecedence, prec, prec, "!! ", null); return true; } if (destType.equals(Type.numberType)) { this._emitter._getExpressionEmitterFor(this._expr.getExpr()).emit(outerOpPrecedence); return true; } if (destType.equals(Type.stringType)) { var prec = _BinaryExpressionEmitter._operatorPrecedence["+"]; this._emitWithParens(outerOpPrecedence, prec, prec, null, " + \"\""); return true; } } if (srcType instanceof NullableType && srcType.getBaseType().equals(Type.integerType)) { // from Nullable.<int> if (destType.equals(Type.booleanType)) { var prec = _UnaryExpressionEmitter._operatorPrecedence["!"]; this._emitWithParens(outerOpPrecedence, prec, prec, "!! ", null); return true; } if (destType.equals(Type.integerType) || destType.equals(Type.numberType)) { var prec = _BinaryExpressionEmitter._operatorPrecedence["|"]; this._emitWithParens(outerOpPrecedence, prec, prec, null, " | 0"); return true; } if (destType.equals(Type.stringType)) { var prec = _BinaryExpressionEmitter._operatorPrecedence["+"]; this._emitWithParens(outerOpPrecedence, prec, prec, null, " + \"\""); return true; } } if (srcType.equals(Type.numberType)) { // from number if (destType.equals(Type.booleanType)) { var prec = _UnaryExpressionEmitter._operatorPrecedence["!"]; this._emitWithParens(outerOpPrecedence, prec, prec, "!! ", null); return true; } if (destType.equals(Type.integerType)) { var prec = _BinaryExpressionEmitter._operatorPrecedence["|"]; this._emitWithParens(outerOpPrecedence, prec, prec, null, " | 0"); return true; } if (destType.equals(Type.stringType)) { var prec = _BinaryExpressionEmitter._operatorPrecedence["+"]; this._emitWithParens(outerOpPrecedence, prec, prec, null, " + \"\""); return true; } } if (srcType instanceof NullableType && srcType.getBaseType().equals(Type.numberType)) { // from Nullable.<number> if (destType.equals(Type.booleanType)) { var prec = _UnaryExpressionEmitter._operatorPrecedence["!"]; this._emitWithParens(outerOpPrecedence, prec, prec, "!! ", null); return true; } if (destType.equals(Type.integerType)) { var prec = _BinaryExpressionEmitter._operatorPrecedence["|"]; this._emitWithParens(outerOpPrecedence, prec, prec, null, " | 0"); return true; } if (destType.equals(Type.numberType)) { var prec = _UnaryExpressionEmitter._operatorPrecedence["+"]; this._emitWithParens(outerOpPrecedence, prec, prec, "+", null); return true; } if (destType.equals(Type.stringType)) { var prec = _BinaryExpressionEmitter._operatorPrecedence["+"]; this._emitWithParens(outerOpPrecedence, prec, prec, null, " + \"\""); return true; } } if (srcType.equals(Type.stringType)) { // from String if (destType.equals(Type.booleanType)) { var prec = _UnaryExpressionEmitter._operatorPrecedence["!"]; this._emitWithParens(outerOpPrecedence, prec, prec, "!! ", null); return true; } if (destType.equals(Type.integerType)) { var prec = _BinaryExpressionEmitter._operatorPrecedence["|"]; this._emitWithParens(outerOpPrecedence, prec, prec, null, " | 0"); return true; } if (destType.equals(Type.numberType)) { var prec = _UnaryExpressionEmitter._operatorPrecedence["+"]; this._emitWithParens(outerOpPrecedence, prec, prec, "+", null); return true; } } if (srcType instanceof NullableType && srcType.getBaseType().equals(Type.stringType)) { // from Nullable.<String> if (destType.equals(Type.booleanType)) { var prec = _UnaryExpressionEmitter._operatorPrecedence["!"]; this._emitWithParens(outerOpPrecedence, prec, prec, "!! ", null); return true; } if (destType.equals(Type.integerType)) { var prec = _BinaryExpressionEmitter._operatorPrecedence["|"]; this._emitWithParens(outerOpPrecedence, prec, prec, null, " | 0"); return true; } if (destType.equals(Type.numberType)) { var prec = _UnaryExpressionEmitter._operatorPrecedence["+"]; this._emitWithParens(outerOpPrecedence, prec, prec, "+", null); return true; } if (destType.equals(Type.stringType)) { var prec = _BinaryExpressionEmitter._operatorPrecedence["+"]; this._emitWithParens(outerOpPrecedence, prec, prec, null, " + \"\""); return true; } } if (srcType.equals(Type.variantType)) { // from variant if (destType.equals(Type.booleanType)) { var prec = _UnaryExpressionEmitter._operatorPrecedence["!"]; this._emitWithParens(outerOpPrecedence, prec, prec, "!! ", null); return true; } if (destType.equals(Type.integerType)) { var prec = _BinaryExpressionEmitter._operatorPrecedence["|"]; this._emitWithParens(outerOpPrecedence, prec, prec, null, " | 0"); return true; } if (destType.equals(Type.numberType)) { var prec = _UnaryExpressionEmitter._operatorPrecedence["+"]; this._emitWithParens(outerOpPrecedence, prec, prec, "+", null); return true; } if (destType.equals(Type.stringType)) { var prec = _BinaryExpressionEmitter._operatorPrecedence["+"]; this._emitWithParens(outerOpPrecedence, prec, prec, null, " + \"\""); return true; } } if (srcType.isConvertibleTo(destType)) { // can perform implicit conversion this._emitter._getExpressionEmitterFor(this._expr.getExpr()).emit(outerOpPrecedence); return true; } throw new Error("explicit conversion logic unknown from " + srcType.toString() + " to " + destType.toString()); }, _emitWithParens: function (outerOpPrecedence, opPrecedence, innerOpPrecedence, prefix, postfix) { // in contrast to _ExpressionEmitter#emitWithPrecedence the comparison op. is >=, since the conversion should have higher precedence than the outer op. (see t/run/110) if (opPrecedence >= outerOpPrecedence) this._emitter._emit("(", null); if (prefix != null) this._emitter._emit(prefix, this._expr.getToken()); this._emitter._getExpressionEmitterFor(this._expr.getExpr()).emit(innerOpPrecedence); if (postfix != null) this._emitter._emit(postfix, this._expr.getToken()); if (opPrecedence >= outerOpPrecedence) this._emitter._emit(")", null); } }); var _AsNoConvertExpressionEmitter = exports._AsNoConvertExpressionEmitter = _ExpressionEmitter.extend({ constructor: function (emitter, expr) { _ExpressionEmitter.prototype.constructor.call(this, emitter); this._expr = expr; }, emit: function (outerOpPrecedence) { if (this._emitter._enableRunTimeTypeCheck) { var emitWithAssertion = function (emitCheckExpr, message) { var token = this._expr.getToken(); this._emitter._emit("(function (v) {\n", token); this._emitter._advanceIndent(); this._emitter._emitAssertion(emitCheckExpr, token, message); this._emitter._emit("return v;\n", token); this._emitter._reduceIndent(); this._emitter._emit("}(", token); this._emitter._getExpressionEmitterFor(this._expr.getExpr()).emit(0); this._emitter._emit("))", token); }.bind(this); var srcType = this._expr.getExpr().getType(); var destType = this._expr.getType(); if (srcType.equals(destType) || srcType.equals(destType.resolveIfNullable)) { // skip } else if (destType instanceof VariantType) { // skip } else if (srcType instanceof ObjectType && srcType.isConvertibleTo(destType)) { // skip } else if (destType.equals(Type.booleanType)) { emitWithAssertion(function () { this._emitter._emit("typeof v === \"boolean\"", this._expr.getToken()); }.bind(this), "detected invalid cast, value is not a boolean"); return; } else if (destType.equals(Type.integerType) || destType.equals(Type.numberType)) { emitWithAssertion(function () { this._emitter._emit("typeof v === \"number\"", this._expr.getToken()); }.bind(this), "detected invalid cast, value is not a number"); return; } else if (destType.equals(Type.stringType)) { emitWithAssertion(function () { this._emitter._emit("typeof v === \"string\"", this._expr.getToken()); }.bind(this), "detected invalid cast, value is not a string"); return; } else if (destType instanceof FunctionType) { emitWithAssertion(function () { this._emitter._emit("v == null || typeof v === \"function\"", this._expr.getToken()); }.bind(this), "detected invalid cast, value is not a function or null"); return; } else if (destType instanceof ObjectType) { var destClassDef = destType.getClassDef(); if ((destClassDef.flags() & ClassDefinition.IS_FAKE) != 0) { // skip } else if (destClassDef instanceof InstantiatedClassDefinition && destClassDef.getTemplateClassName() == "Array") { emitWithAssertion(function () { this._emitter._emit("v == null || v instanceof Array", this._expr.getToken()); }.bind(this), "detected invalid cast, value is not an Array or null"); return; } else if (destClassDef instanceof InstantiatedClassDefinition && destClassDef.getTemplateClassName() == "Map") { emitWithAssertion(function () { this._emitter._emit("v == null || typeof v === \"object\"", this._expr.getToken()); }.bind(this), "detected invalid cast, value is not a Map or null"); return; } else { emitWithAssertion(function () { this._emitter._emit("v == null || v instanceof " + destClassDef.getOutputClassName(), this._expr.getToken()); }.bind(this), "detected invalid cast, value is not an instance of the designated type or null"); return; } } } this._emitter._getExpressionEmitterFor(this._expr.getExpr()).emit(outerOpPrecedence); return; } }); var _OperatorExpressionEmitter = exports._OperatorExpressionEmitter = _ExpressionEmitter.extend({ constructor: function (emitter) { _ExpressionEmitter.prototype.constructor.call(this, emitter); }, emit: function (outerOpPrecedence) { this.emitWithPrecedence(outerOpPrecedence, this._getPrecedence(), this._emit.bind(this)); }, _emit: null, // void emit() _getPrecedence: null // int _getPrecedence() }); var _UnaryExpressionEmitter = exports._UnaryExpressionEmitter = _OperatorExpressionEmitter.extend({ constructor: function (emitter, expr) { _OperatorExpressionEmitter.prototype.constructor.call(this, emitter); this._expr = expr; }, _emit: function () { var opToken = this._expr.getToken(); this._emitter._emit(opToken.getValue() + " ", opToken); this._emitter._getExpressionEmitterFor(this._expr.getExpr()).emit(this._getPrecedence()); }, _getPrecedence: function () { return _UnaryExpressionEmitter._operatorPrecedence[this._expr.getToken().getValue()]; }, $_operatorPrecedence: {}, $_setOperatorPrecedence: function (op, precedence) { _UnaryExpressionEmitter._operatorPrecedence[op] = precedence; } }); var _PostfixExpressionEmitter = exports._PostfixExpressionEmitter = _UnaryExpressionEmitter.extend({ constructor: function (emitter, expr) { _UnaryExpressionEmitter.prototype.constructor.call(this, emitter, expr); }, _emit: function () { var opToken = this._expr.getToken(); this._emitter._getExpressionEmitterFor(this._expr.getExpr()).emit(this._getPrecedence()); this._emitter._emit(opToken.getValue(), opToken); }, _getPrecedence: function () { return _PostfixExpressionEmitter._operatorPrecedence[this._expr.getToken().getValue()]; }, $_operatorPrecedence: {}, $_setOperatorPrecedence: function (op, precedence) { _PostfixExpressionEmitter._operatorPrecedence[op] = precedence; } }); var _InstanceofExpressionEmitter = exports._InstanceofExpressionEmitter = _ExpressionEmitter.extend({ constructor: function (emitter, expr) { _ExpressionEmitter.prototype.constructor.call(this, emitter); this._expr = expr; }, emit: function (outerOpPrecedence) { var expectedType = this._expr.getExpectedType(); if ((expectedType.getClassDef().flags() & (ClassDefinition.IS_INTERFACE | ClassDefinition.IS_MIXIN)) == 0) { this.emitWithPrecedence(outerOpPrecedence, _InstanceofExpressionEmitter._operatorPrecedence, (function () { this._emitter._getExpressionEmitterFor(this._expr.getExpr()).emit(_InstanceofExpressionEmitter._operatorPrecedence); this._emitter._emit(" instanceof " + _Util.getInstanceofNameFromClassDef(expectedType.getClassDef()), null); }).bind(this)); } else { this.emitWithPrecedence(outerOpPrecedence, _CallExpressionEmitter._operatorPrecedence, (function () { this._emitter._emit("(function (o) { return !! (o && o.$__jsx_implements_" + expectedType.getClassDef().getOutputClassName() + "); })(", this._expr.getToken()); this._emitter._getExpressionEmitterFor(this._expr.getExpr()).emit(0); this._emitter._emit(")", this._expr.getToken()); }).bind(this)); } }, $_operatorPrecedence: 0, $_setOperatorPrecedence: function (op, precedence) { _InstanceofExpressionEmitter._operatorPrecedence = precedence; } }); var _PropertyExpressionEmitter = exports._PropertyExpressionEmitter = _UnaryExpressionEmitter.extend({ constructor: function (emitter, expr) { _UnaryExpressionEmitter.prototype.constructor.call(this, emitter, expr); }, _emit: function () { var expr = this._expr; var exprType = expr.getType(); var identifierToken = this._expr.getIdentifierToken(); // replace methods to global function (e.g. Number.isNaN to isNaN) if (expr.getExpr() instanceof ClassExpression && expr.getExpr().getType().getClassDef() === Type.numberType.getClassDef()) { switch (identifierToken.getValue()) { case "parseInt": case "parseFloat": case "isNaN": case "isFinite": this._emitter._emit('$__jsx_' + identifierToken.getValue(), identifierToken); return; } } else if (expr.getExpr() instanceof ClassExpression && expr.getExpr().getType().getClassDef() === Type.stringType.getClassDef()) { switch (identifierToken.getValue()) { case "encodeURIComponent": case "decodeURIComponent": case "encodeURI": case "decodeURI": this._emitter._emit('$__jsx_' + identifierToken.getValue(), identifierToken); return; } } this._emitter._getExpressionEmitterFor(expr.getExpr()).emit(this._getPrecedence()); // mangle the name if necessary if (exprType instanceof FunctionType && ! exprType.isAssignable() && (expr.getHolderType().getClassDef().flags() & ClassDefinition.IS_NATIVE) == 0) { if (expr.getExpr() instanceof ClassExpression) { // do not use "." notation for static functions, but use class$name this._emitter._emit("$", identifierToken); } else { this._emitter._emit(".", identifierToken); } this._emitter._emit(this._emitter._mangleFunctionName(identifierToken.getValue(), exprType.getArgumentTypes()), identifierToken); } else { this._emitter._emit(".", identifierToken); this._emitter._emit(identifierToken.getValue(), identifierToken); } }, _getPrecedence: function () { return _PropertyExpressionEmitter._operatorPrecedence; }, $_operatorPrecedence: 0, $_setOperatorPrecedence: function (op, precedence) { _PropertyExpressionEmitter._operatorPrecedence = precedence; } }); var _FunctionExpressionEmitter = exports._FunctionExpressionEmitter = _UnaryExpressionEmitter.extend({ constructor: function (emitter, expr) { _UnaryExpressionEmitter.prototype.constructor.call(this, emitter, expr); }, _emit: function () { var funcDef = this._expr.getFuncDef(); this._emitter._emit("(function (", funcDef.getToken()); var args = funcDef.getArguments(); for (var i = 0; i < args.length; ++i) { if (i != 0) this._emitter._emit(", ", funcDef.getToken()); this._emitter._emit(args[i].getName().getValue(), funcDef.getToken()); } this._emitter._emit(") {\n", funcDef.getToken()); this._emitter._advanceIndent(); this._emitter._emitFunctionBody(funcDef); this._emitter._reduceIndent(); this._emitter._emit("})", funcDef.getToken()) }, _getPrecedence: function () { return _FunctionExpressionEmitter._operatorPrecedence; }, $_operatorPrecedence: 0, $_setOperatorPrecedence: function (op, precedence) { _FunctionExpressionEmitter._operatorPrecedence = precedence; } }); var _BinaryExpressionEmitter = exports._BinaryExpressionEmitter = _OperatorExpressionEmitter.extend({ constructor: function (emitter, expr) { _OperatorExpressionEmitter.prototype.constructor.call(this, emitter); this._expr = expr; this._precedence = _BinaryExpressionEmitter._operatorPrecedence[this._expr.getToken().getValue()]; }, emit: function (outerOpPrecedence) { // handle the lazy conversion to boolean if (this._expr instanceof LogicalExpression && _Util.shouldBooleanize(this._expr)) { // !! is faster than Boolean, see http://jsperf.com/boolean-vs-notnot this._emitter._emit("!! (", this._expr.getToken()); _OperatorExpressionEmitter.prototype.emit.call(this, 0); this._emitter._emit(")", this._expr.getToken()); return; } // optimization of "1 * x" => x if (this._expr.getToken().getValue() === "*") { // optimize "1 * x" => x if (this._emitIfEitherIs(outerOpPrecedence, function (expr1, expr2) { return ((expr1 instanceof IntegerLiteralExpression || expr1 instanceof NumberLiteralExpression) && +expr1.getToken().getValue() === 1) ? expr2 : null; })) { return; } } else if (this._expr.getToken().getValue() === "/=" && this._expr.getFirstExpr().getType().resolveIfNullable().equals(Type.integerType)) { this._emitDivAssignToInt(outerOpPrecedence); return; } // normal _OperatorExpressionEmitter.prototype.emit.call(this, outerOpPrecedence); }, _emit: function () { var opToken = this._expr.getToken(); var firstExpr = this._expr.getFirstExpr(); var firstExprType = firstExpr.getType(); var secondExpr = this._expr.getSecondExpr(); var secondExprType = secondExpr.getType(); var op = opToken.getValue(); switch (op) { case "+": // special handling: (undefined as Nullable<String>) + (undefined as Nullable<String>) should produce "undefinedundefined", not NaN if (firstExprType.equals(secondExprType) && firstExprType.equals(Type.stringType.toNullableType())) this._emitter._emit("\"\" + ", null); break; case "==": case "!=": // NOTE: works for cases where one side is an object and the other is the primitive counterpart if (firstExprType instanceof PrimitiveType && secondExprType instanceof PrimitiveType) { op += "="; } break; } // emit left-hand if (this._emitter._enableRunTimeTypeCheck && firstExpr instanceof NullableType && ! (this._expr instanceof AssignmentExpression)) { this._emitExpressionWithUndefinedAssertion(firstExpr); } else { this._emitter._getExpressionEmitterFor(firstExpr).emit(this._precedence); } // emit operator this._emitter._emit(" " + op + " ", opToken); // emit right-hand if (this._expr instanceof AssignmentExpression && op != "/=") { this._emitter._emitRHSOfAssignment(secondExpr, firstExprType); } else if (this._emitter._enableRunTimeTypeCheck && secondExpr instanceof NullableType) { this._emitExpressionWithUndefinedAssertion(secondExpr); } else { // RHS should have higher precedence (consider: 1 - (1 + 1)) this._emitter._getExpressionEmitterFor(secondExpr).emit(this._precedence - 1); } }, _emitIfEitherIs: function (outerOpPrecedence, cb) { var outcomeExpr; if ((outcomeExpr = cb(this._expr.getFirstExpr(), this._expr.getSecondExpr())) != null || (outcomeExpr = cb(this._expr.getSecondExpr(), this._expr.getFirstExpr())) != null) { this._emitter._getExpressionEmitterFor(outcomeExpr).emit(outerOpPrecedence); return true; } else { return false; } }, _emitDivAssignToInt: function (outerOpPrecedence) { var firstExpr = this._expr.getFirstExpr(); var secondExpr = this._expr.getSecondExpr(); if (firstExpr instanceof PropertyExpression || firstExpr instanceof ArrayExpression) { this._emitter._emit("$__jsx_div_assign(", this._expr.getToken()); if (firstExpr instanceof PropertyExpression) { this._emitter._getExpressionEmitterFor(firstExpr.getExpr()).emit(0); this._emitter._emit(", ", this._expr.getToken()); this._emitter._emit(Util.encodeStringLiteral(firstExpr.getIdentifierToken().getValue()), firstExpr.getIdentifierToken()); } else { this._emitter._getExpressionEmitterFor(firstExpr.getFirstExpr()).emit(0); this._emitter._emit(", ", this._expr.getToken()); this._emitter._getExpressionEmitterFor(firstExpr.getSecondExpr()).emit(0); } this._emitter._emit(", ", this._expr.getToken()); if (this._emitter._enableRunTimeTypeCheck && secondExpr instanceof NullableType) { this._emitExpressionWithUndefinedAssertion(secondExpr); } else { this._emitter._getExpressionEmitterFor(secondExpr).emit(0); } this._emitter._emit(")", this._expr.getToken()); } else { this.emitWithPrecedence(outerOpPrecedence, _BinaryExpressionEmitter._operatorPrecedence["="], function () { this._emitter._getExpressionEmitterFor(firstExpr).emit(_BinaryExpressionEmitter._operatorPrecedence["="]); this._emitter._emit(" = (", this._expr.getToken()); if (this._emitter._enableRunTimeTypeCheck && firstExpr instanceof NullableType) { this._emitExpressionWithUndefinedAssertion(firstExpr); } else { this._emitter._getExpressionEmitterFor(firstExpr).emit(_BinaryExpressionEmitter._operatorPrecedence["/"]); } this._emitter._emit(" / ", this._expr.getToken()); if (this._emitter._enableRunTimeTypeCheck && secondExpr instanceof NullableType) { this._emitExpressionWithUndefinedAssertion(secondExpr); } else { this._emitter._getExpressionEmitterFor(secondExpr).emit(_BinaryExpressionEmitter._operatorPrecedence["/"] - 1); } this._emitter._emit(") | 0", this._expr.getToken()); }.bind(this)); } }, _getPrecedence: function () { return this._precedence; }, $_operatorPrecedence: {}, $_setOperatorPrecedence: function (op, precedence) { _BinaryExpressionEmitter._operatorPrecedence[op] = precedence; } }); var _ArrayExpressionEmitter = exports._ArrayExpressionEmitter = _OperatorExpressionEmitter.extend({ constructor: function (emitter, expr) { _OperatorExpressionEmitter.prototype.constructor.call(this, emitter); this._expr = expr; }, _emit: function () { this._emitter._getExpressionEmitterFor(this._expr.getFirstExpr()).emit(_ArrayExpressionEmitter._operatorPrecedence); var secondExpr = this._expr.getSecondExpr(); // property access using . is 4x faster on safari than using [], see http://jsperf.com/access-using-dot-vs-array var emitted = false; if (secondExpr instanceof StringLiteralExpression) { var propertyName = Util.decodeStringLiteral(secondExpr.getToken().getValue()); if (propertyName.match(/^[\$_A-Za-z][\$_0-9A-Za-z]*$/) != null) { this._emitter._emit(".", this._expr.getToken()); this._emitter._emit(propertyName, secondExpr.getToken()); emitted = true; } } if (! emitted) { this._emitter._emit("[", this._expr.getToken()); this._emitter._getExpressionEmitterFor(secondExpr).emit(0); this._emitter._emit("]", null); } }, _getPrecedence: function () { return _ArrayExpressionEmitter._operatorPrecedence; }, $_operatorPrecedence: 0, $_setOperatorPrecedence: function (op, precedence) { _ArrayExpressionEmitter._operatorPrecedence = precedence; } }); var _ConditionalExpressionEmitter = exports._ConditionalExpressionEmitter = _OperatorExpressionEmitter.extend({ constructor: function (emitter, expr) { _OperatorExpressionEmitter.prototype.constructor.call(this, emitter); this._expr = expr; }, _emit: function () { var precedence = this._getPrecedence(); var ifTrueExpr = this._expr.getIfTrueExpr(); if (ifTrueExpr != null) { this._emitter._getExpressionEmitterFor(this._expr.getCondExpr()).emit(precedence); this._emitter._emit(" ? ", null); this._emitter._getExpressionEmitterFor(ifTrueExpr).emit(precedence); this._emitter._emit(" : ", null); this._emitter._getExpressionEmitterFor(this._expr.getIfFalseExpr()).emit(precedence); } else { this._emitter._getExpressionEmitterFor(this._expr.getCondExpr()).emit(precedence); this._emitter._emit(" || ", null); this._emitter._getExpressionEmitterFor(this._expr.getIfFalseExpr()).emit(precedence); } }, _getPrecedence: function () { return this._expr.getIfTrueExpr() != null ? _ConditionalExpressionEmitter._operatorPrecedence : _BinaryExpressionEmitter._operatorPrecedence["||"]; }, $_operatorPrecedence: 0, $_setOperatorPrecedence: function (op, precedence) { _ConditionalExpressionEmitter._operatorPrecedence = precedence; } }); var _CallExpressionEmitter = exports._CallExpressionEmitter = _OperatorExpressionEmitter.extend({ constructor: function (emitter, expr) { _OperatorExpressionEmitter.prototype.constructor.call(this, emitter); this._expr = expr; }, _emit: function () { if (this._emitSpecial()) return; // normal case var calleeExpr = this._expr.getExpr(); if (this._emitter._enableRunTimeTypeCheck && calleeExpr.getType() instanceof NullableType) this._emitter._emitExpressionWithUndefinedAssertion(calleeExpr); else this._emitter._getExpressionEmitterFor(calleeExpr).emit(_CallExpressionEmitter._operatorPrecedence); this._emitter._emitCallArguments(this._expr.getToken(), "(", this._expr.getArguments(), this._expr.getExpr().getType().resolveIfNullable().getArgumentTypes()); }, _getPrecedence: function () { return _CallExpressionEmitter._operatorPrecedence; }, $_operatorPrecedence: 0, $_setOperatorPrecedence: function (op, precedence) { _CallExpressionEmitter._operatorPrecedence = precedence; }, _emitSpecial: function () { // return false if is not js.apply var calleeExpr = this._expr.getExpr(); if (! (calleeExpr instanceof PropertyExpression)) return false; if (this._emitIfJsInvoke(calleeExpr)) return true; else if (this._emitCallsToMap(calleeExpr)) return true; else if (this._emitIfMathAbs(calleeExpr)) return true; return false; }, _emitIfJsInvoke: function (calleeExpr) { if (! (calleeExpr.getType() instanceof StaticFunctionType)) return false; if (calleeExpr.getIdentifierToken().getValue() != "invoke") return false; var classDef = calleeExpr.getExpr().getType().getClassDef(); if (! (classDef.className() == "js" && classDef.getToken().getFilename() == Util.resolvePath(this._emitter._platform.getRoot() + "/lib/js/js.jsx"))) return false; // emit var args = this._expr.getArguments(); if (args[2] instanceof ArrayLiteralExpression) { this._emitter._getExpressionEmitterFor(args[0]).emit(_PropertyExpressionEmitter._operatorPrecedence); // FIXME emit as property expression if possible this._emitter._emit("[", calleeExpr.getToken()); this._emitter._getExpressionEmitterFor(args[1]).emit(0); this._emitter._emit("]", calleeExpr.getToken()); this._emitter._emitCallArguments(this._expr.getToken(), "(", args[2].getExprs(), null); } else { this._emitter._emit("(function (o, p, a) { return o[p].apply(o, a); }(", calleeExpr.getToken()); this._emitter._getExpressionEmitterFor(args[0]).emit(0); this._emitter._emit(", ", this._expr.getToken()); this._emitter._getExpressionEmitterFor(args[1]).emit(0); this._emitter._emit(", ", this._expr.getToken()); this._emitter._getExpressionEmitterFor(args[2]).emit(0); this._emitter._emit("))", this._expr.getToken()); } return true; }, _emitCallsToMap: function (calleeExpr) { // NOTE once we support member function references, we need to add special handling in _PropertyExpressionEmitter as well if (calleeExpr.getType() instanceof StaticFunctionType) return false; var classDef = calleeExpr.getExpr().getType().getClassDef(); if (! (classDef instanceof InstantiatedClassDefinition)) return false; if (classDef.getTemplateClassName() != "Map") return false; switch (calleeExpr.getIdentifierToken().getValue()) { case "toString": this._emitter._emitCallArguments( calleeExpr.getToken(), "$__jsx_ObjectToString.call(", [ calleeExpr.getExpr() ], [ new ObjectType(classDef) ]); return true; case "hasOwnProperty": this._emitter._emitCallArguments( calleeExpr.getToken(), "$__jsx_ObjectHasOwnProperty.call(", [ calleeExpr.getExpr(), this._expr.getArguments()[0] ], [ new ObjectType(classDef), Type.stringType ]); return true; default: return false; } }, _emitIfMathAbs: function (calleeExpr) { if (! _CallExpressionEmitter._calleeIsMathAbs(calleeExpr)) return false; var argExpr = this._expr.getArguments()[0]; if (argExpr instanceof LeafExpression) { this._emitter._emit("(", this._expr.getToken()); this._emitter._getExpressionEmitterFor(argExpr).emit(0); this._emitter._emit(" >= 0 ? ", this._expr.getToken()); this._emitter._getExpressionEmitterFor(argExpr).emit(0); this._emitter._emit(" : - ", this._expr.getToken()); this._emitter._getExpressionEmitterFor(argExpr).emit(0); this._emitter._emit(")", this._expr.getToken()); } else { this._emitter._emit("(($math_abs_t = ", this._expr.getToken()); this._emitter._getExpressionEmitterFor(argExpr).emit(_BinaryExpressionEmitter._operatorPrecedence["="]); this._emitter._emit(") >= 0 ? $math_abs_t : -$math_abs_t)", this._expr.getToken()); } return true; }, $_calleeIsMathAbs: function (calleeExpr) { if (! (calleeExpr.getType() instanceof StaticFunctionType)) return false; if (calleeExpr.getIdentifierToken().getValue() != "abs") return false; if (calleeExpr.getExpr().getType().getClassDef().className() != "Math") return false; return true; }, $mathAbsUsesTemporary: function (funcDef) { return ! funcDef.forEachStatement(function onStatement(statement) { if (! statement.forEachExpression(function onExpr(expr) { var calleeExpr; if (expr instanceof CallExpression && (calleeExpr = expr.getExpr()) instanceof PropertyExpression && _CallExpressionEmitter._calleeIsMathAbs(calleeExpr) && ! (expr.getArguments()[0] instanceof LeafExpression)) return false; return expr.forEachExpression(onExpr); })) { return false; } return statement.forEachStatement(onStatement); }); } }); var _SuperExpressionEmitter = exports._SuperExpressionEmitter = _OperatorExpressionEmitter.extend({ constructor: function (emitter, expr) { _OperatorExpressionEmitter.prototype.constructor.call(this, emitter); this._expr = expr; }, _emit: function () { var funcType = this._expr.getFunctionType(); var className = funcType.getObjectType().getClassDef().getOutputClassName(); var argTypes = funcType.getArgumentTypes(); var mangledFuncName = this._emitter._mangleFunctionName(this._expr.getName().getValue(), argTypes); this._emitter._emitCallArguments(this._expr.getToken(), className + ".prototype." + mangledFuncName + ".call(this", this._expr.getArguments(), argTypes); }, _getPrecedence: function () { return _CallExpressionEmitter._operatorPrecedence; }, $_operatorPrecedence: 0, $_setOperatorPrecedence: function (op, precedence) { _SuperExpressionEmitter._operatorPrecedence = precedence; } }); var _NewExpressionEmitter = exports._NewExpressionEmitter = _OperatorExpressionEmitter.extend({ constructor: function (emitter, expr) { _OperatorExpressionEmitter.prototype.constructor.call(this, emitter); this._expr = expr; }, emit: function (outerOpPrecedence) { var classDef = this._expr.getType().getClassDef(); var ctor = this._expr.getConstructor(); var argTypes = ctor.getArgumentTypes(); this._emitter._emitCallArguments( this._expr.getToken(), "new " + this._emitter._mangleConstructorName(classDef, argTypes) + "(", this._expr.getArguments(), argTypes); }, _getPrecedence: function () { return _NewExpressionEmitter._operatorPrecedence; }, $_operatorPrecedence: 0, $_setOperatorPrecedence: function (op, precedence) { _NewExpressionEmitter._operatorPrecedence = precedence; } }); var _CommaExpressionEmitter = exports._CommaExpressionEmitter = _ExpressionEmitter.extend({ constructor: function (emitter, expr) { _ExpressionEmitter.prototype.constructor.call(this, emitter); this._expr = expr; }, emit: function (outerOpPrecedence) { // comma operations should be surrounded by brackets unless within a comma expression, since "," might get considered as an argument separator (of function calls, etc.) var useBrackets = outerOpPrecedence != _CommaExpressionEmitter._operatorPrecedence; if (useBrackets) this._emitter._emit("(", null); this._emitter._getExpressionEmitterFor(this._expr.getFirstExpr()).emit(_CommaExpressionEmitter._operatorPrecedence); this._emitter._emit(", ", null); this._emitter._getExpressionEmitterFor(this._expr.getSecondExpr()).emit(_CommaExpressionEmitter._operatorPrecedence); if (useBrackets) this._emitter._emit(")", null); }, $_operatorPrecedence: 0, $_setOperatorPrecedence: function (op, precedence) { _CommaExpressionEmitter._operatorPrecedence = precedence; } }); // the global emitter var JavaScriptEmitter = exports.JavaScriptEmitter = Class.extend({ constructor: function (platform) { this._platform = platform; this._output = ""; this._outputEndsWithReturn = this._output.match(/\n$/) != null; this._outputFile = null; this._indent = 0; this._emittingClass = null; this._emittingFunction = null; this._emittingStatementStack = []; this._enableRunTimeTypeCheck = true; }, getSearchPaths: function () { return [ this._platform.getRoot() + "/lib/js" ]; }, setOutputFile: function (name) { this._outputFile = name; if(this._enableSourceMap) { // FIXME: set correct sourceRoot var sourceRoot = null; this._sourceMapGen = new SourceMapGenerator(name, sourceRoot); } }, saveSourceMappingFile: function (platform) { var gen = this._sourceMapGen; if(gen != null) { platform.save(gen.getSourceMappingFile(), gen.generate()); } }, setSourceMapGenerator: function (gen) { this._sourceMapGen = gen; }, setEnableRunTimeTypeCheck: function (enable) { this._enableRunTimeTypeCheck = enable; }, setEnableSourceMap : function (enable) { this._enableSourceMap = enable; }, setEnableProfiler: function (enable) { this._enableProfiler = enable; }, addHeader: function (header) { this._output += header; }, emit: function (classDefs) { var bootstrap = this._platform.load(this._platform.getRoot() + "/src/js/bootstrap.js"); this._output += bootstrap; for (var i = 0; i < classDefs.length; ++i) { classDefs[i].forEachMemberFunction(function onFuncDef(funcDef) { funcDef.forEachClosure(onFuncDef); _Util.setupBooleanizeFlags(funcDef); return true; }); } for (var i = 0; i < classDefs.length; ++i) { if ((classDefs[i].flags() & ClassDefinition.IS_NATIVE) == 0) this._emitClassDefinition(classDefs[i]); } for (var i = 0; i < classDefs.length; ++i) this._emitStaticInitializationCode(classDefs[i]); this._emitClassMap(classDefs); }, _emitClassDefinition: function (classDef) { this._emittingClass = classDef; try { // emit class object this._emitClassObject(classDef); // emit constructors var ctors = this._findFunctions(classDef, "constructor", false); for (var i = 0; i < ctors.length; ++i) this._emitConstructor(ctors[i]); // emit functions var members = classDef.members(); for (var i = 0; i < members.length; ++i) { var member = members[i]; if (member instanceof MemberFunctionDefinition) { if (! (member.name() == "constructor" && (member.flags() & ClassDefinition.IS_STATIC) == 0) && member.getStatements() != null) { this._emitFunction(member); } } } } finally { this._emittingClass = null; } }, _emitStaticInitializationCode: function (classDef) { if ((classDef.flags() & ClassDefinition.IS_NATIVE) != 0) return; // special handling for js.jsx if (classDef.getToken() != null && classDef.getToken().getFilename() == Util.resolvePath(this._platform.getRoot() + "/lib/js/js.jsx")) { this._emit("js.global = (function () { return this; })();\n\n", null); return; } // normal handling var members = classDef.members(); // FIXME can we (should we?) automatically resolve dependencies? isn't it impossible? for (var i = 0; i < members.length; ++i) { var member = members[i]; if ((member instanceof MemberVariableDefinition) && (member.flags() & (ClassDefinition.IS_STATIC | ClassDefinition.IS_NATIVE)) == ClassDefinition.IS_STATIC) this._emitStaticMemberVariable(classDef.getOutputClassName(), member); } }, _emitClassMap: function (classDefs) { classDefs = classDefs.concat([]); // shallow clone // remove the classDefs wo. source token or native for (var i = 0; i < classDefs.length;) { if (classDefs[i].getToken() == null || (classDefs[i].flags() & ClassDefinition.IS_NATIVE) != 0) classDefs.splice(i, 1); else ++i; } // start emitting this._emit("var $__jsx_classMap = {\n", null); this._advanceIndent(); while (classDefs.length != 0) { // fetch the first classDef, and others that came from the same file var list = []; var pushClass = (function (classDef) { var push = function (suffix) { list.push([ classDef.className() + suffix, classDef.getOutputClassName() + suffix ]); }; var ctors = this._findFunctions(classDef, "constructor", false); push(""); if (ctors.length == 0) { push(this._mangleFunctionArguments([])); } else { for (var i = 0; i < ctors.length; ++i) push(this._mangleFunctionArguments(ctors[i].getArgumentTypes())); } }).bind(this); var filename = classDefs[0].getToken().getFilename(); pushClass(classDefs.shift()); for (var i = 0; i < classDefs.length;) { if (classDefs[i].getToken().getFilename() == filename) { pushClass(classDefs[i]); classDefs.splice(i, 1); } else { ++i; } } // emit the map var escapedFilename = JSON.stringify(this._encodeFilename(filename, "system:")); this._emit(escapedFilename + ": ", null); this._emit("{\n", null); this._advanceIndent(); for (var i = 0; i < list.length; ++i) { this._emit(list[i][0] + ": " + list[i][1], null); if (i != list.length - 1) this._emit(",", null); this._emit("\n", null); } this._reduceIndent(); this._emit("}", null); if (classDefs.length != 0) this._emit(",", null); this._emit("\n", null); } this._reduceIndent(); this._emit("};\n\n", null); }, _encodeFilename: function (filename, prefix) { var rootDir = this._platform.getRoot() + "/"; if (filename.indexOf(rootDir) == 0) filename = prefix + filename.substring(rootDir.length); return filename; }, getOutput: function (sourceFile, entryPoint, executableFor) { var output = this._output + "\n"; if (this._enableProfiler) { output += this._platform.load(this._platform.getRoot() + "/src/js/profiler.js"); } if (entryPoint != null) { output = this._platform.addLauncher(this, this._encodeFilename(sourceFile, "system:"), output, entryPoint, executableFor); } output += "})();\n"; if (this._sourceMapGen) { output += this._sourceMapGen.magicToken(); } return output; }, _emitClassObject: function (classDef) { this._emit( "/**\n" + " * class " + classDef.getOutputClassName() + (classDef.extendType() != null ? " extends " + classDef.extendType().getClassDef().getOutputClassName() + "\n" : "") + " * @constructor\n" + " */\n" + "function ", null); this._emit(classDef.getOutputClassName() + "() {\n" + "}\n" + "\n", classDef.getToken()); if (classDef.extendType() != null) this._emit(classDef.getOutputClassName() + ".prototype = new " + classDef.extendType().getClassDef().getOutputClassName() + ";\n", null); var implementTypes = classDef.implementTypes(); if (implementTypes.length != 0) { for (var i = 0; i < implementTypes.length; ++i) this._emit("$__jsx_merge_interface(" + classDef.getOutputClassName() + ", " + implementTypes[i].getClassDef().getOutputClassName() + ");\n", null); this._emit("\n", null); } if ((classDef.flags() & (ClassDefinition.IS_INTERFACE | ClassDefinition.IS_MIXIN)) != 0) this._emit(classDef.getOutputClassName() + ".prototype.$__jsx_implements_" + classDef.getOutputClassName() + " = true;\n\n", null); }, _emitConstructor: function (funcDef) { var funcName = this._mangleConstructorName(funcDef.getClassDef(), funcDef.getArgumentTypes()); // emit prologue this._emit("/**\n", null); this._emit(" * @constructor\n", null); this._emitFunctionArgumentAnnotations(funcDef); this._emit(" */\n", null); this._emit("function ", null); this._emit(funcName + "(", funcDef.getClassDef().getToken()); this._emitFunctionArguments(funcDef); this._emit(") {\n", null); this._advanceIndent(); // emit body this._emitFunctionBody(funcDef); // emit epilogue this._reduceIndent(); this._emit("};\n\n", null); this._emit(funcName + ".prototype = new " + funcDef.getClassDef().getOutputClassName() + ";\n\n", null); }, _emitFunction: function (funcDef) { var className = funcDef.getClassDef().getOutputClassName(); var funcName = this._mangleFunctionName(funcDef.name(), funcDef.getArgumentTypes()); // emit this._emit("/**\n", null); this._emitFunctionArgumentAnnotations(funcDef); this._emit(_Util.buildAnnotation(" * @return {%1}\n", funcDef.getReturnType()), null); this._emit(" */\n", null); this._emit(className + ".", null); if ((funcDef.flags() & ClassDefinition.IS_STATIC) == 0) this._emit("prototype.", null); this._emit(funcName + " = ", funcDef.getNameToken()); this._emit("function (", funcDef.getToken()); this._emitFunctionArguments(funcDef); this._emit(") {\n", null); this._advanceIndent(); this._emitFunctionBody(funcDef); this._reduceIndent(); this._emit("};\n\n", null); if ((funcDef.flags() & ClassDefinition.IS_STATIC) != 0) this._emit("var " + className + "$" + funcName + " = " + className + "." + funcName + ";\n\n", null); }, _emitFunctionArgumentAnnotations: function (funcDef) { var args = funcDef.getArguments(); for (var i = 0; i < args.length; ++i) this._emit(_Util.buildAnnotation(" * @param {%1} " + args[i].getName().getValue() + "\n", args[i].getType()), null); }, _emitFunctionArguments: function (funcDef) { var args = funcDef.getArguments(); for (var i = 0; i < args.length; ++i) { if (i != 0) this._emit(", "); var name = args[i].getName(); this._emit(name.getValue(), name); } }, _emitFunctionBody: function (funcDef) { var prevEmittingFunction = this._emittingFunction; try { this._emittingFunction = funcDef; if (this._enableProfiler) { this._emit( "var $__jsx_profiler_ctx = $__jsx_profiler.enter(" + Util.encodeStringLiteral( (funcDef.getClassDef() != null ? funcDef.getClassDef().className() : "<<unnamed>>") + ((funcDef.flags() & ClassDefinition.IS_STATIC) != 0 ? "." : "#") + (funcDef.getNameToken() != null ? funcDef.name() : "line_" + funcDef.getToken().getLineNumber()) + "(" + function () { var r = []; funcDef.getArgumentTypes().forEach(function (argType) { r.push(":" + argType.toString()); }); return r.join(", "); }() + ")") + ");\n", null); } // emit reference to this for closures // if funDef is NOT in another closure if (funcDef.getClosures().length != 0 && (funcDef.flags() & ClassDefinition.IS_STATIC) == 0) this._emit("var $this = this;\n", null); // emit helper variable for Math.abs if (_CallExpressionEmitter.mathAbsUsesTemporary(funcDef)) { this._emit("var $math_abs_t;\n", null); } // emit local variable declarations var locals = funcDef.getLocals(); for (var i = 0; i < locals.length; ++i) { // FIXME unused variables should never be emitted by the compiler var type = locals[i].getType(); if (type == null) continue; this._emit(_Util.buildAnnotation("/** @type {%1} */\n", type), null); var name = locals[i].getName(); // do not pass the token for declaration this._emit("var " + name.getValue() + ";\n", null); } // emit code var statements = funcDef.getStatements(); for (var i = 0; i < statements.length; ++i) this._emitStatement(statements[i]); if (this._enableProfiler) { if (statements.length == 0 || ! (statements[statements.length - 1] instanceof ReturnStatement)) { this._emit("$__jsx_profiler.exit();\n", null); } } } finally { this._emittingFunction = prevEmittingFunction; } }, _emitStaticMemberVariable: function (holder, variable) { var initialValue = variable.getInitialValue(); if (initialValue != null && ! (initialValue instanceof NullExpression || initialValue instanceof BooleanLiteralExpression || initialValue instanceof IntegerLiteralExpression || initialValue instanceof NumberLiteralExpression || initialValue instanceof StringLiteralExpression || initialValue instanceof RegExpLiteralExpression)) { // use deferred initialization this._emit("$__jsx_lazy_init(" + holder + ", \"" + variable.name() + "\", function () {\n", variable.getNameToken()); this._advanceIndent(); this._emit("return ", variable.getNameToken()); this._emitRHSOfAssignment(initialValue, variable.getType()); this._emit(";\n", variable.getNameToken()); this._reduceIndent(); this._emit("});\n", variable.getNameToken()); } else { this._emit(holder + "." + variable.name() + " = ", variable.getNameToken()); this._emitRHSOfAssignment(initialValue, variable.getType()); this._emit(";\n", initialValue.getToken()); } }, _emitDefaultValueOf: function (type) { if (type.equals(Type.booleanType)) this._emit("false", null); else if (type.equals(Type.integerType) || type.equals(Type.numberType)) this._emit("0", null); else if (type.equals(Type.stringType)) this._emit("\"\"", null); else if (type instanceof NullableType) this._emit("undefined", null); else this._emit("null", null); }, _emitStatements: function (statements) { this._advanceIndent(); for (var i = 0; i < statements.length; ++i) this._emitStatement(statements[i]); this._reduceIndent(); }, _emitStatement: function (statement) { var emitter = this._getStatementEmitterFor(statement); this._emittingStatementStack.push(emitter); try { emitter.emit(); } finally { this._emittingStatementStack.pop(); } }, _emit: function (str, token) { if (str == "") return; if (this._outputEndsWithReturn && this._indent != 0) { this._output += this._getIndent(); this._outputEndsWithReturn = false; } // optional source map if(this._sourceMapGen != null && token != null) { var lastNewLinePos = this._output.lastIndexOf("\n") + 1; var genColumn = (this._output.length - lastNewLinePos) - 1; var genPos = { line: this._output.match(/^/mg).length, column: genColumn, }; var origPos = { line: token.getLineNumber(), column: token.getColumnNumber() }; var tokenValue = token.isIdentifier() ? token.getValue() : null; var filename = token.getFilename(); if (filename != null) { filename = this._encodeFilename(filename, ""); } this._sourceMapGen.add(genPos, origPos, filename, tokenValue); } str = str.replace(/\n(.)/g, (function (a, m) { return "\n" + this._getIndent() + m; }).bind(this)); this._output += str; this._outputEndsWithReturn = str.charAt(str.length - 1) == "\n"; }, _advanceIndent: function () { ++this._indent; }, _reduceIndent: function () { if (--this._indent < 0) throw new Error("indent mistach"); }, _getIndent: function () { var s = ""; for (var i = 0; i < this._indent; ++i) s += "\t"; return s; }, _getStatementEmitterFor: function (statement) { if (statement instanceof ConstructorInvocationStatement) return new _ConstructorInvocationStatementEmitter(this, statement); else if (statement instanceof ExpressionStatement) return new _ExpressionStatementEmitter(this, statement); else if (statement instanceof ReturnStatement) return new _ReturnStatementEmitter(this, statement); else if (statement instanceof DeleteStatement) return new _DeleteStatementEmitter(this, statement); else if (statement instanceof BreakStatement) return new _BreakStatementEmitter(this, statement); else if (statement instanceof ContinueStatement) return new _ContinueStatementEmitter(this, statement); else if (statement instanceof DoWhileStatement) return new _DoWhileStatementEmitter(this, statement); else if (statement instanceof ForInStatement) return new _ForInStatementEmitter(this, statement); else if (statement instanceof ForStatement) return new _ForStatementEmitter(this, statement); else if (statement instanceof IfStatement) return new _IfStatementEmitter(this, statement); else if (statement instanceof SwitchStatement) return new _SwitchStatementEmitter(this, statement); else if (statement instanceof CaseStatement) return new _CaseStatementEmitter(this, statement); else if (statement instanceof DefaultStatement) return new _DefaultStatementEmitter(this, statement); else if (statement instanceof WhileStatement) return new _WhileStatementEmitter(this, statement); else if (statement instanceof TryStatement) return new _TryStatementEmitter(this, statement); else if (statement instanceof CatchStatement) return new _CatchStatementEmitter(this, statement); else if (statement instanceof ThrowStatement) return new _ThrowStatementEmitter(this, statement); else if (statement instanceof AssertStatement) return new _AssertStatementEmitter(this, statement); else if (statement instanceof LogStatement) return new _LogStatementEmitter(this, statement); else if (statement instanceof DebuggerStatement) return new _DebuggerStatementEmitter(this, statement); throw new Error("got unexpected type of statement: " + JSON.stringify(statement.serialize())); }, _getExpressionEmitterFor: function (expr) { if (expr instanceof LocalExpression) return new _LocalExpressionEmitter(this, expr); else if (expr instanceof ClassExpression) return new _ClassExpressionEmitter(this, expr); else if (expr instanceof NullExpression) return new _NullExpressionEmitter(this, expr); else if (expr instanceof BooleanLiteralExpression) return new _BooleanLiteralExpressionEmitter(this, expr); else if (expr instanceof IntegerLiteralExpression) return new _IntegerLiteralExpressionEmitter(this, expr); else if (expr instanceof NumberLiteralExpression) return new _NumberLiteralExpressionEmitter(this, expr); else if (expr instanceof StringLiteralExpression) return new _StringLiteralExpressionEmitter(this, expr); else if (expr instanceof RegExpLiteralExpression) return new _RegExpLiteralExpressionEmitter(this, expr); else if (expr instanceof ArrayLiteralExpression) return new _ArrayLiteralExpressionEmitter(this, expr); else if (expr instanceof MapLiteralExpression) return new _MapLiteralExpressionEmitter(this, expr); else if (expr instanceof ThisExpression) return new _ThisExpressionEmitter(this, expr); else if (expr instanceof BitwiseNotExpression) return new _UnaryExpressionEmitter(this, expr); else if (expr instanceof InstanceofExpression) return new _InstanceofExpressionEmitter(this, expr); else if (expr instanceof AsExpression) return new _AsExpressionEmitter(this, expr); else if (expr instanceof AsNoConvertExpression) return new _AsNoConvertExpressionEmitter(this, expr); else if (expr instanceof LogicalNotExpression) return new _UnaryExpressionEmitter(this, expr); else if (expr instanceof TypeofExpression) return new _UnaryExpressionEmitter(this, expr); else if (expr instanceof PostIncrementExpression) return new _PostfixExpressionEmitter(this, expr); else if (expr instanceof PreIncrementExpression) return new _UnaryExpressionEmitter(this, expr); else if (expr instanceof PropertyExpression) return new _PropertyExpressionEmitter(this, expr); else if (expr instanceof SignExpression) return new _UnaryExpressionEmitter(this, expr); else if (expr instanceof AdditiveExpression) return new _BinaryExpressionEmitter(this, expr); else if (expr instanceof ArrayExpression) return new _ArrayExpressionEmitter(this, expr); else if (expr instanceof AssignmentExpression) return new _BinaryExpressionEmitter(this, expr); else if (expr instanceof BinaryNumberExpression) return new _BinaryExpressionEmitter(this, expr); else if (expr instanceof EqualityExpression) return new _BinaryExpressionEmitter(this, expr); else if (expr instanceof InExpression) return new _BinaryExpressionEmitter(this, expr); else if (expr instanceof LogicalExpression) return new _BinaryExpressionEmitter(this, expr); else if (expr instanceof ShiftExpression) return new _BinaryExpressionEmitter(this, expr); else if (expr instanceof ConditionalExpression) return new _ConditionalExpressionEmitter(this, expr); else if (expr instanceof CallExpression) return new _CallExpressionEmitter(this, expr); else if (expr instanceof SuperExpression) return new _SuperExpressionEmitter(this, expr); else if (expr instanceof NewExpression) return new _NewExpressionEmitter(this, expr); else if (expr instanceof FunctionExpression) return new _FunctionExpressionEmitter(this, expr); else if (expr instanceof CommaExpression) return new _CommaExpressionEmitter(this, expr); throw new Error("got unexpected type of expression: " + (expr != null ? JSON.stringify(expr.serialize()) : expr)); }, _mangleConstructorName: function (classDef, argTypes) { if ((classDef.flags() & ClassDefinition.IS_NATIVE) != 0) { if (classDef instanceof InstantiatedClassDefinition) { if (classDef.getTemplateClassName() == "Map") { return "Object"; } else { return classDef.getTemplateClassName(); } } else { return classDef.className(); } } return classDef.getOutputClassName() + this._mangleFunctionArguments(argTypes); }, _mangleFunctionName: function (name, argTypes) { // NOTE: how mangling of "toString" is omitted is very hacky, but it seems like the easiest way, taking the fact into consideration that it is the only function in Object if (name != "toString") name += this._mangleFunctionArguments(argTypes); return name; }, _mangleTypeName: function (type) { if (type.equals(Type.voidType)) return "V"; else if (type.equals(Type.booleanType)) return "B"; else if (type.equals(Type.integerType)) return "I"; else if (type.equals(Type.numberType)) return "N"; else if (type.equals(Type.stringType)) return "S"; else if (type instanceof ObjectType) { var classDef = type.getClassDef(); if (classDef instanceof InstantiatedClassDefinition) { var typeArgs = classDef.getTypeArguments(); switch (classDef.getTemplateClassName()) { case "Array": return "A" + this._mangleTypeName(typeArgs[0]); case "Map": return "H" + this._mangleTypeName(typeArgs[0]); default: throw new Error("unexpected template type: " + classDef.getTemplateClassName()); } } return "L" + type.getClassDef().getOutputClassName() + "$"; } else if (type instanceof StaticFunctionType) return "F" + this._mangleFunctionArguments(type.getArgumentTypes()) + this._mangleTypeName(type.getReturnType()) + "$"; else if (type instanceof MemberFunctionType) return "M" + this._mangleTypeName(type.getObjectType()) + this._mangleFunctionArguments(type.getArgumentTypes()) + this._mangleTypeName(type.getReturnType()) + "$"; else if (type instanceof NullableType) return "U" + this._mangleTypeName(type.getBaseType()); else if (type.equals(Type.variantType)) return "X"; else throw new Error("FIXME " + type.toString()); }, _mangleFunctionArguments: function (argTypes) { var s = "$"; for (var i = 0; i < argTypes.length; ++i) s += this._mangleTypeName(argTypes[i]); return s; }, _mangleTypeString: function (s) { return s.length + s; }, _findFunctions: function (classDef, name, isStatic) { var functions = []; var members = classDef.members(); for (var i = 0; i < members.length; ++i) { var member = members[i]; if ((member instanceof MemberFunctionDefinition) && member.name() == name && (member.flags() & ClassDefinition.IS_STATIC) == (isStatic ? ClassDefinition.IS_STATIC : 0)) functions.push(member); } return functions; }, _emitCallArguments: function (token, prefix, args, argTypes) { this._emit(prefix, token); for (var i = 0; i < args.length; ++i) { if (i != 0 || prefix[prefix.length - 1] != '(') this._emit(", ", null); if (argTypes != null && this._enableRunTimeTypeCheck && args[i].getType() instanceof NullableType && ! (argTypes[i] instanceof NullableType || argTypes[i] instanceof VariantType)) { this._emitExpressionWithUndefinedAssertion(args[i]); } else { this._getExpressionEmitterFor(args[i]).emit(0); } } this._emit(")", token); }, _emitAssertion: function (emitTestExpr, token, message) { this._emit("if (! (", token); emitTestExpr(); this._emit(")) {\n", null); this._advanceIndent(); this._emit("debugger;\n", null); // FIXME make the expression source and throw a fit exception class var err = Util.format('throw new Error("[%1:%2] %3");\n', [token.getFilename(), token.getLineNumber(), message]); this._emit(err, null); this._reduceIndent(); this._emit("}\n", null); }, _emitExpressionWithUndefinedAssertion: function (expr) { var token = expr.getToken(); this._emit("(function (v) {\n", token); this._advanceIndent(); this._emitAssertion(function () { this._emit("typeof v !== \"undefined\"", token); }.bind(this), token, "detected misuse of 'undefined' as type '" + expr.getType().resolveIfNullable().toString() + "'"); this._emit("return v;\n", token); this._reduceIndent(); this._emit("}(", token); this._getExpressionEmitterFor(expr).emit(0); this._emit("))", token); }, _emitRHSOfAssignment: function (expr, lhsType) { var exprType = expr.getType(); // FIXME what happens if the op is /= or %= ? if (lhsType.resolveIfNullable().equals(Type.integerType) && exprType.equals(Type.numberType)) { if (expr instanceof NumberLiteralExpression || expr instanceof IntegerLiteralExpression) { this._emit((expr.getToken().getValue() | 0).toString(), expr.getToken()); } else { this._emit("(", expr.getToken()); this._getExpressionEmitterFor(expr).emit(_BinaryExpressionEmitter._operatorPrecedence["|"]); this._emit(" | 0)", expr.getToken()); } return; } if (lhsType.equals(Type.integerType) && (exprType instanceof NullableType && exprType.getBaseType().equals(Type.numberType))) { this._emit("(", expr.getToken()); if (this._enableRunTimeTypeCheck) { this._emitExpressionWithUndefinedAssertion(expr); } else { this._getExpressionEmitterFor(expr).emit(_BinaryExpressionEmitter._operatorPrecedence["|"]); } this._emit(" | 0)", expr.getToken()); return; } if ((lhsType instanceof NullableType && lhsType.getBaseType().equals(Type.integerType)) && (exprType instanceof NullableType && exprType.getBaseType().equals(Type.numberType))) { // NOTE this is very slow, but such an operation would practically not be found this._emit("(function (v) { return v !== undefined ? v | 0 : v; })(", expr.getToken()); this._getExpressionEmitterFor(expr).emit(0); this._emit(")", expr.getToken()); return; } // normal mode if (this._enableRunTimeTypeCheck && ! (lhsType instanceof NullableType || lhsType.equals(Type.variantType)) && exprType instanceof NullableType) { this._emitExpressionWithUndefinedAssertion(expr); } else { this._getExpressionEmitterFor(expr).emit(_BinaryExpressionEmitter._operatorPrecedence["="]); } }, $constructor: function () { var precedence = [ [ [ "new", _NewExpressionEmitter._setOperatorPrecedence ], [ "[", _ArrayExpressionEmitter._setOperatorPrecedence ], [ ".", _PropertyExpressionEmitter._setOperatorPrecedence ], [ "(", _CallExpressionEmitter._setOperatorPrecedence ], [ "super", _SuperExpressionEmitter._setOperatorPrecedence ], [ "function", _FunctionExpressionEmitter._setOperatorPrecedence ], ], [ [ "++", _PostfixExpressionEmitter._setOperatorPrecedence ], [ "--", _PostfixExpressionEmitter._setOperatorPrecedence ] ], [ // delete is not used by JSX [ "void", _UnaryExpressionEmitter._setOperatorPrecedence ], [ "typeof", _UnaryExpressionEmitter._setOperatorPrecedence ], [ "++", _UnaryExpressionEmitter._setOperatorPrecedence ], [ "--", _UnaryExpressionEmitter._setOperatorPrecedence ], [ "+", _UnaryExpressionEmitter._setOperatorPrecedence ], [ "-", _UnaryExpressionEmitter._setOperatorPrecedence ], [ "~", _UnaryExpressionEmitter._setOperatorPrecedence ], [ "!", _UnaryExpressionEmitter._setOperatorPrecedence ] ], [ [ "*", _BinaryExpressionEmitter._setOperatorPrecedence ], [ "/", _BinaryExpressionEmitter._setOperatorPrecedence ], [ "%", _BinaryExpressionEmitter._setOperatorPrecedence ] ], [ [ "+", _BinaryExpressionEmitter._setOperatorPrecedence ], [ "-", _BinaryExpressionEmitter._setOperatorPrecedence ] ], [ [ "<<", _BinaryExpressionEmitter._setOperatorPrecedence ], [ ">>", _BinaryExpressionEmitter._setOperatorPrecedence ], [ ">>>", _BinaryExpressionEmitter._setOperatorPrecedence ], ], [ [ "<", _BinaryExpressionEmitter._setOperatorPrecedence ], [ ">", _BinaryExpressionEmitter._setOperatorPrecedence ], [ "<=", _BinaryExpressionEmitter._setOperatorPrecedence ], [ ">=", _BinaryExpressionEmitter._setOperatorPrecedence ], [ "instanceof", _InstanceofExpressionEmitter._setOperatorPrecedence ], [ "in", _BinaryExpressionEmitter._setOperatorPrecedence ] ], [ [ "==", _BinaryExpressionEmitter._setOperatorPrecedence ], [ "!=", _BinaryExpressionEmitter._setOperatorPrecedence ] ], [ [ "&", _BinaryExpressionEmitter._setOperatorPrecedence ] ], [ [ "^", _BinaryExpressionEmitter._setOperatorPrecedence ] ], [ [ "|", _BinaryExpressionEmitter._setOperatorPrecedence ] ], [ [ "&&", _BinaryExpressionEmitter._setOperatorPrecedence ] ], [ [ "||", _BinaryExpressionEmitter._setOperatorPrecedence ] ], [ [ "=", _BinaryExpressionEmitter._setOperatorPrecedence ], [ "*=", _BinaryExpressionEmitter._setOperatorPrecedence ], [ "/=", _BinaryExpressionEmitter._setOperatorPrecedence ], [ "%=", _BinaryExpressionEmitter._setOperatorPrecedence ], [ "+=", _BinaryExpressionEmitter._setOperatorPrecedence ], [ "-=", _BinaryExpressionEmitter._setOperatorPrecedence ], [ "<<=", _BinaryExpressionEmitter._setOperatorPrecedence ], [ ">>=", _BinaryExpressionEmitter._setOperatorPrecedence ], [ ">>>=", _BinaryExpressionEmitter._setOperatorPrecedence ], [ "&=", _BinaryExpressionEmitter._setOperatorPrecedence ], [ "^=", _BinaryExpressionEmitter._setOperatorPrecedence ], [ "|=", _BinaryExpressionEmitter._setOperatorPrecedence ] ], [ [ "?", _ConditionalExpressionEmitter._setOperatorPrecedence ] ], [ [ ",", _CommaExpressionEmitter._setOperatorPrecedence ] ] ]; for (var i = 0; i < precedence.length; ++i) { var opTypeList = precedence[i]; for (var j = 0; j < opTypeList.length; ++j) opTypeList[j][1](opTypeList[j][0], -(precedence.length - i)); } } }); // vim: set noexpandtab:
fix annotations about class
src/jsemitter.js
fix annotations about class
<ide><path>rc/jsemitter.js <ide> this._emit( <ide> "/**\n" + <ide> " * class " + classDef.getOutputClassName() + <del> (classDef.extendType() != null ? " extends " + classDef.extendType().getClassDef().getOutputClassName() + "\n" : "") + <add> (classDef.extendType() != null ? " extends " + classDef.extendType().getClassDef().getOutputClassName() : "") + "\n" + <ide> " * @constructor\n" + <ide> " */\n" + <ide> "function ", null);
Java
apache-2.0
cfeaa46bd9a6311ebeddfa190897cc90755149bb
0
cisco-system-traffic-generator/trex-java-sdk,cisco-system-traffic-generator/trex-java-sdk
package com.cisco.trex.stateful.api.lowlevel; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import java.util.ArrayList; import java.util.List; import java.util.Objects; /** * Java implementation for TRex python sdk ASTFIpGenDist class */ public class ASTFIpGenDist { private static List<Inner> inList = new ArrayList(); private String ipStart; private String ipEnd; private Distribution distribution; private PerCoreDistributionVals perCoreDistributionVals; private Inner newInner; private int index; /** * construct * * @param ipStart * @param ipEnd */ public ASTFIpGenDist(String ipStart, String ipEnd) { this(ipStart, ipEnd, Distribution.SEQ, null); } /** * construct * * @param ipStart * @param ipEnd * @param distribution * @param perCoreDistributionVals */ public ASTFIpGenDist(String ipStart, String ipEnd, Distribution distribution, PerCoreDistributionVals perCoreDistributionVals) { this.ipStart = ipStart; this.ipEnd = ipEnd; this.distribution = distribution; this.perCoreDistributionVals = perCoreDistributionVals; this.newInner = new Inner(ipStart, ipEnd, distribution, perCoreDistributionVals); for (int i = 0; i < inList.size(); i++) { if (newInner.equals(inList.get(i))) { this.index = i; return; } } this.inList.add(newInner); this.index = inList.size() - 1; } /** * getIpStart * * @return ip start */ public String getIpStart() { return this.inList.get(this.index).getIpStart(); } /** * getIpEnd * * @return ip end */ public String getIpEnd() { return this.inList.get(this.index).getIpEnd(); } /** * getDistribution * * @return distribution */ public Distribution getDistribution() { return this.inList.get(this.index).getDistribution(); } /** * getPerCoreDistributionVals * * @return perCoreDistributionVals */ public PerCoreDistributionVals getPerCoreDistributionVals() { return this.inList.get(this.index).getPerCoreDistributionVals(); } /** * setDirection * * @param direction direction */ public void setDirection(String direction) { this.inList.get(this.index).setDirection(direction); } /** * setIpOffset * * @param ipOffset ipOffset */ public void setIpOffset(String ipOffset) { this.inList.get(this.index).setIpOffset(ipOffset); } /** * to json format * * @return JsonObject */ public JsonObject toJson() { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("index", this.index); return jsonObject; } /** * including all cached gen dist json string * * @return JsonArray */ public static JsonArray clssToJson() { JsonArray jsonArray = new JsonArray(); for (Inner inner : inList) { jsonArray.add(inner.toJson()); } return jsonArray; } /** * class reset, clear all cached data */ public static void classReset() { inList.clear(); } /** * Inner class */ class Inner { private String ipStart; private String ipEnd; private Distribution distribution; private PerCoreDistributionVals perCoreDistributionVals; private String direction; private String ipOffset; private JsonObject fields = new JsonObject(); /** * Inner Construct * * @param ipStart * @param ipEnd * @param distribution * @param perCoreDistributionVals */ Inner(String ipStart, String ipEnd, Distribution distribution, PerCoreDistributionVals perCoreDistributionVals) { fields.addProperty("ip_start", ipStart); fields.addProperty("ip_end", ipEnd); fields.addProperty("distribution", distribution.getType()); if (perCoreDistributionVals != null) { fields.addProperty("per_core_distribution", perCoreDistributionVals.getType()); } } String getIpStart() { return ipStart; } String getIpEnd() { return ipEnd; } Distribution getDistribution() { return distribution; } PerCoreDistributionVals getPerCoreDistributionVals() { return perCoreDistributionVals; } void setDirection(String direction) { fields.addProperty("dir", direction); this.direction = direction; } void setIpOffset(String ipOffset) { fields.addProperty("ip_offset", ipOffset); this.ipOffset = ipOffset; } JsonObject toJson() { return fields; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Inner inner = (Inner) o; return fields.equals(inner.fields); } @Override public int hashCode() { return Objects.hash(fields); } } /** * Distribution enum */ public enum Distribution { SEQ("seq"), RAND("rand"); private String type; Distribution(String type) { this.type = type; } /** * get type * * @return type */ public String getType() { return type; } } /** * PerCoreDistributionVals enum */ public enum PerCoreDistributionVals { DEFAULT("default"), SEQ("seq"); String type; PerCoreDistributionVals(String type) { this.type = type; } /** * get type * * @return type */ public String getType() { return type; } } }
src/main/java/com/cisco/trex/stateful/api/lowlevel/ASTFIpGenDist.java
package com.cisco.trex.stateful.api.lowlevel; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import java.util.ArrayList; import java.util.List; import java.util.Objects; /** * Java implementation for TRex python sdk ASTFIpGenDist class */ public class ASTFIpGenDist { private static List<Inner> inList = new ArrayList(); private String ipStart; private String ipEnd; private Distribution distribution; private PerCoreDistributionVals perCoreDistributionVals; private Inner newInner; private int index; /** * construct * * @param ipStart * @param ipEnd */ public ASTFIpGenDist(String ipStart, String ipEnd) { this(ipStart, ipEnd, Distribution.SEQ, null); } /** * construct * * @param ipStart * @param ipEnd * @param distribution * @param perCoreDistributionVals */ public ASTFIpGenDist(String ipStart, String ipEnd, Distribution distribution, PerCoreDistributionVals perCoreDistributionVals) { this.ipStart = ipStart; this.ipEnd = ipEnd; this.distribution = distribution; this.perCoreDistributionVals = perCoreDistributionVals; this.newInner = new Inner(ipStart, ipEnd, distribution, perCoreDistributionVals); for (int i = 0; i < inList.size(); i++) { if (newInner.equals(inList.get(i))) { this.index = i; return; } } this.inList.add(newInner); this.index = inList.size() - 1; } /** * getIpStart * * @return ip start */ public String getIpStart() { return this.inList.get(this.index).getIpStart(); } /** * getIpEnd * * @return ip end */ public String getIpEnd() { return this.inList.get(this.index).getIpEnd(); } /** * getDistribution * * @return distribution */ public Distribution getDistribution() { return this.inList.get(this.index).getDistribution(); } /** * getPerCoreDistributionVals * * @return perCoreDistributionVals */ public PerCoreDistributionVals getPerCoreDistributionVals() { return this.inList.get(this.index).getPerCoreDistributionVals(); } /** * setDirection * * @param direction direction */ public void setDirection(String direction) { this.inList.get(this.index).setDirection(direction); } /** * setIpOffset * * @param ipOffset ipOffset */ public void setIpOffset(String ipOffset) { this.inList.get(this.index).setIpOffset(ipOffset); } /** * to json format * * @return JsonObject */ public JsonObject toJson() { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("index", this.index); return jsonObject; } /** * including all cached gen dist json string * * @return JsonArray */ public static JsonArray clssToJson() { JsonArray jsonArray = new JsonArray(); for (Inner inner : inList) { jsonArray.add(inner.toJson()); } return jsonArray; } /** * class reset, clear all cached data */ public static void classReset() { inList.clear(); } /** * Inner class */ class Inner { private String ipStart; private String ipEnd; private Distribution distribution; private PerCoreDistributionVals perCoreDistributionVals; private String direction; private String ipOffset; private JsonObject fields = new JsonObject(); /** * Inner Construct * * @param ipStart * @param ipEnd * @param distribution * @param perCoreDistributionVals */ Inner(String ipStart, String ipEnd, Distribution distribution, PerCoreDistributionVals perCoreDistributionVals) { fields.addProperty("ip_start", ipStart); fields.addProperty("ip_end", ipEnd); fields.addProperty("distribution", distribution.getType()); if (perCoreDistributionVals != null) { fields.addProperty("per_core_distribution", perCoreDistributionVals.getType()); } } String getIpStart() { return ipStart; } String getIpEnd() { return ipEnd; } Distribution getDistribution() { return distribution; } PerCoreDistributionVals getPerCoreDistributionVals() { return perCoreDistributionVals; } void setDirection(String direction) { fields.addProperty("dir", direction); this.direction = direction; } void setIpOffset(String ipOffset) { fields.addProperty("ip_offset", ipOffset); this.ipOffset = ipOffset; } JsonObject toJson() { return fields; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Inner inner = (Inner) o; return fields.equals(inner.fields); } @Override public int hashCode() { return Objects.hash(fields); } } /** * Distribution enum */ public enum Distribution { SEQ("seq"), RAND("rand"); private String type; Distribution(String type) { this.type = type; } /** * get type * * @return */ public String getType() { return type; } } /** * PerCoreDistributionVals enum */ public enum PerCoreDistributionVals { DEFAULT("default"), SEQ("seq"); String type; PerCoreDistributionVals(String type) { this.type = type; } /** * get type * * @return */ public String getType() { return type; } } }
fix javadoc warnings
src/main/java/com/cisco/trex/stateful/api/lowlevel/ASTFIpGenDist.java
fix javadoc warnings
<ide><path>rc/main/java/com/cisco/trex/stateful/api/lowlevel/ASTFIpGenDist.java <ide> /** <ide> * get type <ide> * <del> * @return <add> * @return type <ide> */ <ide> public String getType() { <ide> return type; <ide> /** <ide> * get type <ide> * <del> * @return <add> * @return type <ide> */ <ide> public String getType() { <ide> return type;
JavaScript
mit
7cf3f10afb3c1e4b2e5242c91d333cb7dad4a7ab
0
dawoe/Umbraco-CMS,WebCentrum/Umbraco-CMS,bjarnef/Umbraco-CMS,bjarnef/Umbraco-CMS,marcemarc/Umbraco-CMS,hfloyd/Umbraco-CMS,dawoe/Umbraco-CMS,NikRimington/Umbraco-CMS,KevinJump/Umbraco-CMS,mattbrailsford/Umbraco-CMS,kgiszewski/Umbraco-CMS,leekelleher/Umbraco-CMS,dawoe/Umbraco-CMS,PeteDuncanson/Umbraco-CMS,arknu/Umbraco-CMS,mattbrailsford/Umbraco-CMS,hfloyd/Umbraco-CMS,umbraco/Umbraco-CMS,tcmorris/Umbraco-CMS,mattbrailsford/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,base33/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,lars-erik/Umbraco-CMS,kgiszewski/Umbraco-CMS,leekelleher/Umbraco-CMS,base33/Umbraco-CMS,leekelleher/Umbraco-CMS,lars-erik/Umbraco-CMS,aaronpowell/Umbraco-CMS,KevinJump/Umbraco-CMS,hfloyd/Umbraco-CMS,dawoe/Umbraco-CMS,arknu/Umbraco-CMS,marcemarc/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,kgiszewski/Umbraco-CMS,tompipe/Umbraco-CMS,hfloyd/Umbraco-CMS,abryukhov/Umbraco-CMS,leekelleher/Umbraco-CMS,madsoulswe/Umbraco-CMS,tcmorris/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,aadfPT/Umbraco-CMS,abjerner/Umbraco-CMS,tcmorris/Umbraco-CMS,arknu/Umbraco-CMS,umbraco/Umbraco-CMS,umbraco/Umbraco-CMS,aaronpowell/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,bjarnef/Umbraco-CMS,KevinJump/Umbraco-CMS,jchurchley/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abryukhov/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,PeteDuncanson/Umbraco-CMS,PeteDuncanson/Umbraco-CMS,robertjf/Umbraco-CMS,abryukhov/Umbraco-CMS,base33/Umbraco-CMS,rasmuseeg/Umbraco-CMS,leekelleher/Umbraco-CMS,robertjf/Umbraco-CMS,marcemarc/Umbraco-CMS,WebCentrum/Umbraco-CMS,robertjf/Umbraco-CMS,madsoulswe/Umbraco-CMS,tompipe/Umbraco-CMS,bjarnef/Umbraco-CMS,nul800sebastiaan/Umbraco-CMS,abryukhov/Umbraco-CMS,dawoe/Umbraco-CMS,mattbrailsford/Umbraco-CMS,abjerner/Umbraco-CMS,jchurchley/Umbraco-CMS,KevinJump/Umbraco-CMS,tompipe/Umbraco-CMS,aadfPT/Umbraco-CMS,jchurchley/Umbraco-CMS,tcmorris/Umbraco-CMS,madsoulswe/Umbraco-CMS,abjerner/Umbraco-CMS,aadfPT/Umbraco-CMS,tcmorris/Umbraco-CMS,nul800sebastiaan/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,robertjf/Umbraco-CMS,arknu/Umbraco-CMS,rasmuseeg/Umbraco-CMS,NikRimington/Umbraco-CMS,tcmorris/Umbraco-CMS,WebCentrum/Umbraco-CMS,abjerner/Umbraco-CMS,NikRimington/Umbraco-CMS,nul800sebastiaan/Umbraco-CMS,aaronpowell/Umbraco-CMS,hfloyd/Umbraco-CMS,lars-erik/Umbraco-CMS,KevinJump/Umbraco-CMS,rasmuseeg/Umbraco-CMS,lars-erik/Umbraco-CMS,lars-erik/Umbraco-CMS,umbraco/Umbraco-CMS,marcemarc/Umbraco-CMS
(function () { "use strict"; function UsersOverviewController($scope) { var vm = this; vm.page = {}; vm.page.name = "User Management"; vm.page.navigation = [ { "name": "Users", "icon": "icon-user", "view": "views/users/views/users/users.html", "active": true }, { "name": "Roles", "icon": "icon-users", "view": "views/users/views/roles/roles.html" } ]; function init() { } init(); } angular.module("umbraco").controller("Umbraco.Editors.Users.OverviewController", UsersOverviewController); })();
src/Umbraco.Web.UI.Client/src/views/users/overview.controller.js
(function () { "use strict"; function UsersOverviewController($scope) { var vm = this; vm.page = {}; vm.page.name = "User Management"; vm.page.navigation = [ { "name": "Users", "icon": "icon-user", "view": "views/usersV2/views/users/users.html", "active": true }, { "name": "Roles", "icon": "icon-users", "view": "views/usersV2/views/roles/roles.html" } ]; function init() { } init(); } angular.module("umbraco").controller("Umbraco.Editors.Users.OverviewController", UsersOverviewController); })();
missed two paths
src/Umbraco.Web.UI.Client/src/views/users/overview.controller.js
missed two paths
<ide><path>rc/Umbraco.Web.UI.Client/src/views/users/overview.controller.js <ide> { <ide> "name": "Users", <ide> "icon": "icon-user", <del> "view": "views/usersV2/views/users/users.html", <add> "view": "views/users/views/users/users.html", <ide> "active": true <ide> }, <ide> { <ide> "name": "Roles", <ide> "icon": "icon-users", <del> "view": "views/usersV2/views/roles/roles.html" <add> "view": "views/users/views/roles/roles.html" <ide> } <ide> ]; <ide>
Java
mit
c2dc3afb6dac7e44737f8187591349cd3e44db0c
0
NutriCampus/NutriCampus,NutriCampus/NutriCampus
package com.nutricampus.app.model; /** * Created by Felipe on 23/06/2017. * For project NutriCampus. * Contact: <[email protected]> */ import android.text.Editable; import android.text.TextWatcher; import android.widget.EditText; public abstract class Mask { public static String CPF_MASK = "###.###.###-##"; public static String CELULAR_MASK = "(##) ##### ####"; public static String CEP_MASK = "#####-###"; public static String unmask(String s) { return s.replaceAll("[.]", "").replaceAll("[-]", "") .replaceAll("[/]", "").replaceAll("[(]", "") .replaceAll("[)]", "").replaceAll(" ", "") .replaceAll(",", ""); } public static boolean isASign(char c) { if (c == '.' || c == '-' || c == '/' || c == '(' || c == ')' || c == ',' || c == ' ') { return true; } else { return false; } } public static String mask(String mask, String text) { int i = 0; String mascara = ""; for (char m : mask.toCharArray()) { if (m != '#') { mascara += m; continue; } try { mascara += text.charAt(i); } catch (Exception e) { break; } i++; } return mascara; } public static TextWatcher insert(final String mask, final EditText ediTxt) { return new TextWatcher() { boolean isUpdating; String old = ""; public void onTextChanged(CharSequence s, int start, int before, int count) { String str = Mask.unmask(s.toString()); String mascara = ""; if (isUpdating) { old = str; isUpdating = false; return; } int index = 0; for (int i = 0; i < mask.length(); i++) { char m = mask.charAt(i); if (m != '#') { if (index == str.length() && str.length() < old.length()) { continue; } mascara += m; continue; } try { mascara += str.charAt(index); } catch (Exception e) { break; } index++; } if (mascara.length() > 0) { char last_char = mascara.charAt(mascara.length() - 1); boolean hadSign = false; while (isASign(last_char) && str.length() == old.length()) { mascara = mascara.substring(0, mascara.length() - 1); last_char = mascara.charAt(mascara.length() - 1); hadSign = true; } if (mascara.length() > 0 && hadSign) { mascara = mascara.substring(0, mascara.length() - 1); } } isUpdating = true; ediTxt.setText(mascara); ediTxt.setSelection(mascara.length()); } public void beforeTextChanged(CharSequence s, int start, int count, int after) {} public void afterTextChanged(Editable s) {} }; } public static boolean validateCpf(String cpfComplete) { String cpf = ""; for (char c : cpfComplete.toCharArray()) { if (Character.isDigit(c)) { cpf += c; } } int digitoCpf; int somaD1 = 0; int somaD2 = 0; int peso = 12; int digito1 = 0; int digito2 = 0; int resto = 0; String digVerificar = ""; String digResultado = ""; for (int i = 0; i < cpf.length() - 2; i++) { digitoCpf = Integer.parseInt(cpf.substring(i, i + 1)); somaD1 += (digitoCpf * (peso - 2)); somaD2 += (digitoCpf * (peso - 1)); peso--; } resto = somaD1 % 11; if (resto < 2) { digito1 = 0; } else { digito1 = 11 - resto; } somaD2 += (2 * digito1); resto = somaD2 % 11; if (resto < 2) { digito2 = 0; } else { digito2 = 11 - resto; } digResultado = String.valueOf(digito1); digResultado += String.valueOf(digito2); digVerificar = cpf.substring(cpf.length() - 2, cpf.length()); return digResultado.equals(digVerificar); } }
app/src/main/java/com/nutricampus/app/model/Mask.java
package com.nutricampus.app.model; /** * Created by Felipe on 23/06/2017. */ public class Mask { }
Classe para mudar a máscara de um atributo
app/src/main/java/com/nutricampus/app/model/Mask.java
Classe para mudar a máscara de um atributo
<ide><path>pp/src/main/java/com/nutricampus/app/model/Mask.java <ide> <ide> /** <ide> * Created by Felipe on 23/06/2017. <add> * For project NutriCampus. <add> * Contact: <[email protected]> <ide> */ <ide> <del>public class Mask { <add>import android.text.Editable; <add>import android.text.TextWatcher; <add>import android.widget.EditText; <add> <add>public abstract class Mask { <add> public static String CPF_MASK = "###.###.###-##"; <add> public static String CELULAR_MASK = "(##) ##### ####"; <add> public static String CEP_MASK = "#####-###"; <add> <add> public static String unmask(String s) { <add> return s.replaceAll("[.]", "").replaceAll("[-]", "") <add> .replaceAll("[/]", "").replaceAll("[(]", "") <add> .replaceAll("[)]", "").replaceAll(" ", "") <add> .replaceAll(",", ""); <add> } <add> <add> public static boolean isASign(char c) { <add> if (c == '.' || c == '-' || c == '/' || c == '(' || c == ')' || c == ',' || c == ' ') { <add> return true; <add> } else { <add> return false; <add> } <add> } <add> <add> public static String mask(String mask, String text) { <add> int i = 0; <add> String mascara = ""; <add> for (char m : mask.toCharArray()) { <add> if (m != '#') { <add> mascara += m; <add> continue; <add> } <add> try { <add> mascara += text.charAt(i); <add> } catch (Exception e) { <add> break; <add> } <add> i++; <add> } <add> <add> return mascara; <add> } <add> <add> public static TextWatcher insert(final String mask, final EditText ediTxt) { <add> return new TextWatcher() { <add> boolean isUpdating; <add> String old = ""; <add> <add> public void onTextChanged(CharSequence s, int start, int before, int count) { <add> String str = Mask.unmask(s.toString()); <add> String mascara = ""; <add> if (isUpdating) { <add> old = str; <add> isUpdating = false; <add> return; <add> } <add> <add> int index = 0; <add> for (int i = 0; i < mask.length(); i++) { <add> char m = mask.charAt(i); <add> if (m != '#') { <add> if (index == str.length() && str.length() < old.length()) { <add> continue; <add> } <add> mascara += m; <add> continue; <add> } <add> <add> try { <add> mascara += str.charAt(index); <add> } catch (Exception e) { <add> break; <add> } <add> <add> index++; <add> } <add> <add> if (mascara.length() > 0) { <add> char last_char = mascara.charAt(mascara.length() - 1); <add> boolean hadSign = false; <add> while (isASign(last_char) && str.length() == old.length()) { <add> mascara = mascara.substring(0, mascara.length() - 1); <add> last_char = mascara.charAt(mascara.length() - 1); <add> hadSign = true; <add> } <add> <add> if (mascara.length() > 0 && hadSign) { <add> mascara = mascara.substring(0, mascara.length() - 1); <add> } <add> } <add> <add> isUpdating = true; <add> ediTxt.setText(mascara); <add> ediTxt.setSelection(mascara.length()); <add> } <add> <add> public void beforeTextChanged(CharSequence s, int start, int count, int after) {} <add> <add> public void afterTextChanged(Editable s) {} <add> }; <add> } <add> <add> public static boolean validateCpf(String cpfComplete) { <add> String cpf = ""; <add> <add> for (char c : cpfComplete.toCharArray()) { <add> if (Character.isDigit(c)) { <add> cpf += c; <add> } <add> } <add> <add> int digitoCpf; <add> int somaD1 = 0; <add> int somaD2 = 0; <add> int peso = 12; <add> int digito1 = 0; <add> int digito2 = 0; <add> int resto = 0; <add> String digVerificar = ""; <add> String digResultado = ""; <add> <add> for (int i = 0; i < cpf.length() - 2; i++) { <add> digitoCpf = Integer.parseInt(cpf.substring(i, i + 1)); <add> somaD1 += (digitoCpf * (peso - 2)); <add> somaD2 += (digitoCpf * (peso - 1)); <add> peso--; <add> } <add> <add> resto = somaD1 % 11; <add> <add> if (resto < 2) { <add> digito1 = 0; <add> } else { <add> digito1 = 11 - resto; <add> } <add> <add> somaD2 += (2 * digito1); <add> <add> resto = somaD2 % 11; <add> <add> if (resto < 2) { <add> digito2 = 0; <add> } else { <add> digito2 = 11 - resto; <add> } <add> <add> digResultado = String.valueOf(digito1); <add> digResultado += String.valueOf(digito2); <add> <add> digVerificar = cpf.substring(cpf.length() - 2, cpf.length()); <add> <add> return digResultado.equals(digVerificar); <add> <add> } <ide> }
Java
lgpl-2.1
7932dbde0e2cfbf7f60ce106055839e7ca7cf274
0
samskivert/samskivert,samskivert/samskivert
// // $Id$ // // samskivert library - useful routines for java programs // Copyright (C) 2006 Michael Bayne, Pär Winzell // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.samskivert.jdbc.depot; import java.lang.reflect.Field; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.logging.Level; import com.samskivert.io.PersistenceException; import com.samskivert.jdbc.depot.annotation.Computed; import com.samskivert.jdbc.depot.annotation.Entity; import com.samskivert.jdbc.depot.annotation.GeneratedValue; import com.samskivert.jdbc.depot.annotation.Id; import com.samskivert.jdbc.depot.annotation.Index; import com.samskivert.jdbc.depot.annotation.Table; import com.samskivert.jdbc.depot.annotation.TableGenerator; import com.samskivert.jdbc.depot.annotation.Transient; import com.samskivert.jdbc.depot.annotation.UniqueConstraint; import com.samskivert.jdbc.JDBCUtil; import com.samskivert.jdbc.depot.clause.Where; import com.samskivert.util.ArrayUtil; import com.samskivert.util.ListUtil; import com.samskivert.util.StringUtil; import static com.samskivert.jdbc.depot.Log.log; /** * Handles the marshalling and unmarshalling of persistent instances to JDBC primitives ({@link * PreparedStatement} and {@link ResultSet}). */ public class DepotMarshaller<T extends PersistentRecord> { /** The name of a private static field that must be defined for all persistent object classes. * It is used to handle schema migration. If automatic schema migration is not desired, define * this field and set its value to -1. */ public static final String SCHEMA_VERSION_FIELD = "SCHEMA_VERSION"; /** * Creates a marshaller for the specified persistent object class. */ public DepotMarshaller (Class<T> pclass, PersistenceContext context) { _pclass = pclass; Entity entity = pclass.getAnnotation(Entity.class); Table table = null; // see if this is a computed entity Computed computed = pclass.getAnnotation(Computed.class); if (computed == null) { // if not, this class has a corresponding SQL table _tableName = _pclass.getName(); _tableName = _tableName.substring(_tableName.lastIndexOf(".")+1); // see if there are Entity values specified if (entity != null) { if (entity.name().length() > 0) { _tableName = entity.name(); } _postamble = entity.postamble(); } // check for a Table annotation, for unique constraints table = pclass.getAnnotation(Table.class); } // if the entity defines a new TableGenerator, map that in our static table as those are // shared across all entities TableGenerator generator = pclass.getAnnotation(TableGenerator.class); if (generator != null) { context.tableGenerators.put(generator.name(), generator); } // introspect on the class and create marshallers for persistent fields ArrayList<String> fields = new ArrayList<String>(); for (Field field : _pclass.getFields()) { int mods = field.getModifiers(); // check for a static constant schema version if (java.lang.reflect.Modifier.isStatic(mods) && field.getName().equals(SCHEMA_VERSION_FIELD)) { try { _schemaVersion = (Integer)field.get(null); } catch (Exception e) { log.log(Level.WARNING, "Failed to read schema version " + "[class=" + _pclass + "].", e); } } // the field must be public, non-static and non-transient if (!java.lang.reflect.Modifier.isPublic(mods) || java.lang.reflect.Modifier.isStatic(mods) || field.getAnnotation(Transient.class) != null) { continue; } FieldMarshaller fm = FieldMarshaller.createMarshaller(field); _fields.put(fm.getColumnName(), fm); fields.add(fm.getColumnName()); // check to see if this is our primary key if (field.getAnnotation(Id.class) != null) { if (_pkColumns == null) { _pkColumns = new ArrayList<FieldMarshaller>(); } _pkColumns.add(fm); // check if this field defines a new TableGenerator generator = field.getAnnotation(TableGenerator.class); if (generator != null) { context.tableGenerators.put(generator.name(), generator); } } } // if the entity defines a single-columnar primary key, figure out if we will be generating // values for it if (_pkColumns != null) { GeneratedValue gv = null; FieldMarshaller keyField = null; // loop over fields to see if there's a @GeneratedValue at all for (FieldMarshaller field : _pkColumns) { gv = field.getGeneratedValue(); if (gv != null) { keyField = field; break; } } if (keyField != null) { // and if there is, make sure we've a single-column id if (_pkColumns.size() > 1) { throw new IllegalArgumentException( "Cannot use @GeneratedValue on multiple-column @Id's"); } // the primary key must be numeric if we are to auto-assign it Class<?> ftype = keyField.getField().getType(); boolean isNumeric = ( ftype.equals(Byte.TYPE) || ftype.equals(Byte.class) || ftype.equals(Short.TYPE) || ftype.equals(Short.class) || ftype.equals(Integer.TYPE) || ftype.equals(Integer.class) || ftype.equals(Long.TYPE) || ftype.equals(Long.class)); if (!isNumeric) { throw new IllegalArgumentException( "Cannot use @GeneratedValue on non-numeric column"); } switch(gv.strategy()) { case AUTO: case IDENTITY: _keyGenerator = new IdentityKeyGenerator(); break; case TABLE: String name = gv.generator(); generator = context.tableGenerators.get(name); if (generator == null) { throw new IllegalArgumentException( "Unknown generator [generator=" + name + "]"); } _keyGenerator = new TableKeyGenerator(generator); break; } } } // generate our full list of fields/columns for use in queries _allFields = fields.toArray(new String[fields.size()]); // if we're a computed entity, stop here if (_tableName == null) { return; } // figure out the list of fields that correspond to actual table columns and generate the // SQL used to create and migrate our table (unless we're a computed entity) _columnFields = new String[_allFields.length]; int jj = 0; for (int ii = 0; ii < _allFields.length; ii++) { // include all persistent non-computed fields String colDef = _fields.get(_allFields[ii]).getColumnDefinition(); if (colDef != null) { _columnFields[jj] = _allFields[ii]; _declarations.add(colDef); jj ++; } } _columnFields = ArrayUtil.splice(_columnFields, jj); // determine whether we have any index definitions if (entity != null) { for (Index index : entity.indices()) { // TODO: delegate this to a database specific SQL generator _declarations.add(index.type() + " index " + index.name() + " (" + StringUtil.join(index.columns(), ", ") + ")"); } } // add any unique constraints given if (table != null) { for (UniqueConstraint constraint : table.uniqueConstraints()) { _declarations.add( "UNIQUE (" + StringUtil.join(constraint.columnNames(), ", ") + ")"); } } // add the primary key, if we have one if (hasPrimaryKey()) { _declarations.add("PRIMARY KEY (" + getPrimaryKeyColumns() + ")"); } // if we did not find a schema version field, complain if (_schemaVersion < 0) { log.warning("Unable to read " + _pclass.getName() + "." + SCHEMA_VERSION_FIELD + ". Schema migration disabled."); } } /** * Returns the name of the table in which persistent instances of our class are stored. By * default this is the classname of the persistent object without the package. */ public String getTableName () { return _tableName; } /** * Returns all the persistent fields of our class, in definition order. */ public String[] getFieldNames () { return _allFields; } /** * Returns the {@link FieldMarshaller} for a named field on our persistent class. */ public FieldMarshaller getFieldMarshaller (String fieldName) { return _fields.get(fieldName); } /** * Returns true if our persistent object defines a primary key. */ public boolean hasPrimaryKey () { return (_pkColumns != null); } /** * Returns a key configured with the primary key of the supplied object. If all the fields are * null, this method returns null. An exception is thrown if some of the fields are null and * some are not, or if the object does not declare a primary key. */ public Key<T> getPrimaryKey (Object object) { return getPrimaryKey(object, true); } /** * Returns a key configured with the primary key of the supplied object. If all the fields are * null, this method returns null. If some of the fields are null and some are not, an * exception is thrown. If the object does not declare a primary key and the second argument is * true, this method throws an exception; if it's false, the method returns null. */ public Key<T> getPrimaryKey (Object object, boolean requireKey) { if (!hasPrimaryKey()) { if (requireKey) { throw new UnsupportedOperationException( _pclass.getName() + " does not define a primary key"); } return null; } try { Comparable[] values = new Comparable[_pkColumns.size()]; boolean hasNulls = false; for (int ii = 0; ii < _pkColumns.size(); ii++) { FieldMarshaller field = _pkColumns.get(ii); values[ii] = (Comparable) field.getField().get(object); if (values[ii] == null || Integer.valueOf(0).equals(values[ii])) { // if this is the first null we see but not the first field, freak out if (!hasNulls && ii > 0) { throw new IllegalArgumentException( "Persistent object's primary key fields are mixed null and non-null."); } hasNulls = true; } else if (hasNulls) { // if this is a non-null field and we've previously seen nulls, also freak throw new IllegalArgumentException( "Persistent object's primary key fields are mixed null and non-null."); } } // if all the fields were null, return null, else build a key return hasNulls ? null : makePrimaryKey(values); } catch (IllegalAccessException iae) { throw new RuntimeException(iae); } } /** * Creates a primary key record for the type of object handled by this marshaller, using the * supplied primary key value. */ public Key<T> makePrimaryKey (Comparable... values) { if (!hasPrimaryKey()) { throw new UnsupportedOperationException( getClass().getName() + " does not define a primary key"); } String[] columns = new String[_pkColumns.size()]; for (int ii = 0; ii < _pkColumns.size(); ii++) { columns[ii] = _pkColumns.get(ii).getColumnName(); } return new Key<T>(_pclass, columns, values); } /** * Returns true if this marshaller has been initialized ({@link #init} has been called), its * migrations run and it is ready for operation. False otherwise. */ public boolean isInitialized () { return _initialized; } /** * Creates a persistent object from the supplied result set. The result set must have come from * a query provided by {@link #createQuery}. */ public T createObject (ResultSet rs) throws SQLException { try { // first, build a set of the fields that we actually received Set<String> fields = new HashSet<String>(); ResultSetMetaData metadata = rs.getMetaData(); for (int ii = 1; ii <= metadata.getColumnCount(); ii ++) { fields.add(metadata.getColumnName(ii)); } // then create and populate the persistent object T po = _pclass.newInstance(); for (FieldMarshaller fm : _fields.values()) { if (!fields.contains(fm.getField().getName())) { // this field was not in the result set, make sure that's OK if (fm.getComputed() != null && !fm.getComputed().required()) { continue; } throw new SQLException("ResultSet missing field: " + fm.getField().getName()); } fm.getValue(rs, po); } return po; } catch (SQLException sqe) { // pass this on through throw sqe; } catch (Exception e) { String errmsg = "Failed to unmarshall persistent object [pclass=" + _pclass.getName() + "]"; throw (SQLException)new SQLException(errmsg).initCause(e); } } /** * Creates a statement that will insert the supplied persistent object into the database. */ public PreparedStatement createInsert (Connection conn, Object po) throws SQLException { requireNotComputed("insert rows into"); try { StringBuilder insert = new StringBuilder(); insert.append("insert into ").append(getTableName()); insert.append(" (").append(StringUtil.join(_columnFields, ",")); insert.append(")").append(" values("); for (int ii = 0; ii < _columnFields.length; ii++) { if (ii > 0) { insert.append(", "); } insert.append("?"); } insert.append(")"); // TODO: handle primary key, nullable fields specially? PreparedStatement pstmt = conn.prepareStatement(insert.toString()); int idx = 0; for (String field : _columnFields) { _fields.get(field).setValue(po, pstmt, ++idx); } return pstmt; } catch (SQLException sqe) { // pass this on through throw sqe; } catch (Exception e) { String errmsg = "Failed to marshall persistent object [pclass=" + _pclass.getName() + "]"; throw (SQLException)new SQLException(errmsg).initCause(e); } } /** * Fills in the primary key just assigned to the supplied persistence object by the execution * of the results of {@link #createInsert}. * * @return the newly assigned primary key or null if the object does not use primary keys or * this is not the right time to assign the key. */ public Key assignPrimaryKey (Connection conn, Object po, boolean postFactum) throws SQLException { // if we have no primary key or no generator, then we're done if (!hasPrimaryKey() || _keyGenerator == null) { return null; } // run this generator either before or after the actual insertion if (_keyGenerator.isPostFactum() != postFactum) { return null; } try { int nextValue = _keyGenerator.nextGeneratedValue(conn); _pkColumns.get(0).getField().set(po, nextValue); return makePrimaryKey(nextValue); } catch (Exception e) { String errmsg = "Failed to assign primary key [type=" + _pclass + "]"; throw (SQLException) new SQLException(errmsg).initCause(e); } } /** * Creates a statement that will update the supplied persistent object using the supplied key. */ public PreparedStatement createUpdate (Connection conn, Object po, Where key) throws SQLException { return createUpdate(conn, po, key, _columnFields); } /** * Creates a statement that will update the supplied persistent object * using the supplied key. */ public PreparedStatement createUpdate ( Connection conn, Object po, Where key, String[] modifiedFields) throws SQLException { requireNotComputed("update rows in"); StringBuilder update = new StringBuilder(); update.append("update ").append(getTableName()).append(" set "); int idx = 0; for (String field : modifiedFields) { if (idx++ > 0) { update.append(", "); } update.append(field).append(" = ?"); } key.appendClause(null, update); try { PreparedStatement pstmt = conn.prepareStatement(update.toString()); idx = 0; // bind the update arguments for (String field : modifiedFields) { _fields.get(field).setValue(po, pstmt, ++idx); } // now bind the key arguments key.bindArguments(pstmt, ++idx); return pstmt; } catch (SQLException sqe) { // pass this on through throw sqe; } catch (Exception e) { String errmsg = "Failed to marshall persistent object " + "[pclass=" + _pclass.getName() + "]"; throw (SQLException)new SQLException(errmsg).initCause(e); } } /** * Creates a statement that will update the specified set of fields for all persistent objects * that match the supplied key. */ public PreparedStatement createPartialUpdate ( Connection conn, Where key, String[] modifiedFields, Object[] modifiedValues) throws SQLException { requireNotComputed("update rows in"); StringBuilder update = new StringBuilder(); update.append("update ").append(getTableName()).append(" set "); int idx = 0; for (String field : modifiedFields) { if (idx++ > 0) { update.append(", "); } update.append(field).append(" = ?"); } key.appendClause(null, update); PreparedStatement pstmt = conn.prepareStatement(update.toString()); idx = 0; // bind the update arguments for (Object value : modifiedValues) { // TODO: use the field marshaller? pstmt.setObject(++idx, value); } // now bind the key arguments key.bindArguments(pstmt, ++idx); return pstmt; } /** * Creates a statement that will delete all rows matching the supplied key. */ public PreparedStatement createDelete (Connection conn, Where key) throws SQLException { requireNotComputed("delete rows from"); StringBuilder query = new StringBuilder("delete from " + getTableName()); key.appendClause(null, query); PreparedStatement pstmt = conn.prepareStatement(query.toString()); key.bindArguments(pstmt, 1); return pstmt; } /** * Creates a statement that will update the specified set of fields, using the supplied literal * SQL values, for all persistent objects that match the supplied key. */ public PreparedStatement createLiteralUpdate ( Connection conn, Where key, String[] modifiedFields, Object[] modifiedValues) throws SQLException { requireNotComputed("update rows in"); StringBuilder update = new StringBuilder(); update.append("update ").append(getTableName()).append(" set "); for (int ii = 0; ii < modifiedFields.length; ii++) { if (ii > 0) { update.append(", "); } update.append(modifiedFields[ii]).append(" = "); update.append(modifiedValues[ii]); } key.appendClause(null, update); PreparedStatement pstmt = conn.prepareStatement(update.toString()); key.bindArguments(pstmt, 1); return pstmt; } /** * This is called by the persistence context to register a migration for the entity managed by * this marshaller. */ protected void registerMigration (EntityMigration migration) { _migrations.add(migration); } /** * Initializes the table used by this marshaller. This is called automatically by the {@link * PersistenceContext} the first time an entity is used. If the table does not exist, it will * be created. If the schema version specified by the persistent object is newer than the * database schema, it will be migrated. */ protected void init (PersistenceContext ctx) throws PersistenceException { if (_initialized) { // sanity check throw new IllegalStateException( "Cannot re-initialize marshaller [type=" + _pclass + "]."); } _initialized = true; // if we have no table (i.e. we're a computed entity), we have nothing to create if (getTableName() == null) { return; } // check to see if our schema version table exists, create it if not ctx.invoke(new Modifier() { public int invoke (Connection conn) throws SQLException { JDBCUtil.createTableIfMissing( conn, SCHEMA_VERSION_TABLE, new String[] { "persistentClass VARCHAR(255) NOT NULL", "version INTEGER NOT NULL" }, ""); return 0; } }); // now create the table for our persistent class if it does not exist ctx.invoke(new Modifier() { public int invoke (Connection conn) throws SQLException { if (!JDBCUtil.tableExists(conn, getTableName())) { log.info("Creating table " + getTableName() + " (" + _declarations + ") " + _postamble); String[] definition = _declarations.toArray(new String[_declarations.size()]); JDBCUtil.createTableIfMissing(conn, getTableName(), definition, _postamble); updateVersion(conn, _schemaVersion); } return 0; } }); // if we have a key generator, initialize that too if (_keyGenerator != null) { ctx.invoke(new Modifier() { public int invoke (Connection conn) throws SQLException { _keyGenerator.init(conn); return 0; } }); } // if schema versioning is disabled, stop now if (_schemaVersion < 0) { return; } // make sure the versions match int currentVersion = ctx.invoke(new Modifier() { public int invoke (Connection conn) throws SQLException { String query = "select version from " + SCHEMA_VERSION_TABLE + " where persistentClass = '" + getTableName() + "'"; Statement stmt = conn.createStatement(); try { ResultSet rs = stmt.executeQuery(query); return (rs.next()) ? rs.getInt(1) : 1; } finally { stmt.close(); } } }); if (currentVersion == _schemaVersion) { return; } // otherwise try to migrate the schema log.info("Migrating " + getTableName() + " from " + currentVersion + " to " + _schemaVersion + "..."); // run our pre-default-migrations for (EntityMigration migration : _migrations) { if (migration.runBeforeDefault() && migration.shouldRunMigration(currentVersion, _schemaVersion)) { migration.init(getTableName(), _fields); ctx.invoke(migration); } } // enumerate all of the columns now that we've run our pre-migrations final Set<String> columns = new HashSet<String>(); final Map<String, Set<String>> indexColumns = new HashMap<String, Set<String>>(); ctx.invoke(new Modifier() { public int invoke (Connection conn) throws SQLException { DatabaseMetaData meta = conn.getMetaData(); ResultSet rs = meta.getColumns(null, null, getTableName(), "%"); while (rs.next()) { columns.add(rs.getString("COLUMN_NAME")); } rs = meta.getIndexInfo(null, null, getTableName(), false, false); while (rs.next()) { String indexName = rs.getString("INDEX_NAME"); Set<String> set = indexColumns.get(indexName); if (rs.getBoolean("NON_UNIQUE")) { // not a unique index: just make sure there's an entry in the keyset if (set == null) { indexColumns.put(indexName, null); } } else { // for unique indices we collect the column names if (set == null) { set = new HashSet<String>(); indexColumns.put(indexName, set); } set.add(rs.getString("COLUMN_NAME")); } } return 0; } }); // this is a little silly, but we need a copy for name disambiguation later Set<String> indicesCopy = new HashSet<String>(indexColumns.keySet()); // add any missing columns for (String fname : _columnFields) { FieldMarshaller fmarsh = _fields.get(fname); if (columns.remove(fmarsh.getColumnName())) { continue; } // otherwise add the column String coldef = fmarsh.getColumnDefinition(); String query = "alter table " + getTableName() + " add column " + coldef; // try to add it to the appropriate spot int fidx = ListUtil.indexOf(_allFields, fmarsh.getColumnName()); if (fidx == 0) { query += " first"; } else { query += " after " + _allFields[fidx-1]; } log.info("Adding column to " + getTableName() + ": " + coldef); ctx.invoke(new Modifier.Simple(query)); // if the column is a TIMESTAMP or DATETIME column, we need to run a special query to // update all existing rows to the current time because MySQL annoyingly assigns // TIMESTAMP columns a value of "0000-00-00 00:00:00" regardless of whether we // explicitly provide a "DEFAULT" value for the column or not, and DATETIME columns // cannot accept CURRENT_TIME or NOW() defaults at all. if (coldef.toLowerCase().indexOf(" timestamp") != -1 || coldef.toLowerCase().indexOf(" datetime") != -1) { query = "update " + getTableName() + " set " + fmarsh.getColumnName() + " = NOW()"; log.info("Assigning current time to column: " + query); ctx.invoke(new Modifier.Simple(query)); } } // add or remove the primary key as needed if (hasPrimaryKey() && !indexColumns.containsKey("PRIMARY")) { String pkdef = "primary key (" + getPrimaryKeyColumns() + ")"; log.info("Adding primary key to " + getTableName() + ": " + pkdef); ctx.invoke(new Modifier.Simple("alter table " + getTableName() + " add " + pkdef)); } else if (!hasPrimaryKey() && indexColumns.containsKey("PRIMARY")) { indexColumns.remove("PRIMARY"); log.info("Dropping primary from " + getTableName()); ctx.invoke(new Modifier.Simple("alter table " + getTableName() + " drop primary key")); } // add any missing indices Entity entity = _pclass.getAnnotation(Entity.class); for (Index index : (entity == null ? new Index[0] : entity.indices())) { if (indexColumns.containsKey(index.name())) { indexColumns.remove(index.name()); continue; } String indexdef = "create " + index.type() + " index " + index.name() + " on " + getTableName() + " (" + StringUtil.join(index.columns(), ", ") + ")"; log.info("Adding index: " + indexdef); ctx.invoke(new Modifier.Simple(indexdef)); } // to get the @Table(uniqueIndices...) indices, we use our clever set of column name sets Set<Set<String>> uniqueIndices = new HashSet<Set<String>>(indexColumns.values()); Table table; if (getTableName() != null && (table = _pclass.getAnnotation(Table.class)) != null) { Set<String> colSet = new HashSet<String>(); for (UniqueConstraint constraint : table.uniqueConstraints()) { // for each given UniqueConstraint, build a new column set colSet.clear(); for (String column : constraint.columnNames()) { colSet.add(column); } // and check if the table contained this set if (uniqueIndices.contains(colSet)) { continue; // good, carry on } // else build the index; we'll use mysql's convention of naming it after a column, // with possible _N disambiguation; luckily we made a copy of the index names! String indexName = colSet.iterator().next(); if (indicesCopy.contains(indexName)) { int num = 1; indexName += "_"; while (indicesCopy.contains(indexName + num)) { num ++; } indexName += num; } String[] columnArr = colSet.toArray(new String[colSet.size()]); String indexdef = "create unique index " + indexName + " on " + getTableName() + " (" + StringUtil.join(columnArr, ", ") + ")"; log.info("Adding unique index: " + indexdef); ctx.invoke(new Modifier.Simple(indexdef)); } } // we do not auto-remove columns but rather require that EntityMigration.Drop records be // registered by hand to avoid accidentally causin the loss of data // we don't auto-remove indices either because we'd have to sort out the potentially // complex origins of an index (which might be because of a @Unique column or maybe the // index was hand defined in a @Column clause) // run our post-default-migrations for (EntityMigration migration : _migrations) { if (!migration.runBeforeDefault() && migration.shouldRunMigration(currentVersion, _schemaVersion)) { migration.init(getTableName(), _fields); ctx.invoke(migration); } } // record our new version in the database ctx.invoke(new Modifier() { public int invoke (Connection conn) throws SQLException { updateVersion(conn, _schemaVersion); return 0; } }); } protected String getPrimaryKeyColumns () { String[] pkcols = new String[_pkColumns.size()]; for (int ii = 0; ii < pkcols.length; ii ++) { pkcols[ii] = _pkColumns.get(ii).getColumnName(); } return StringUtil.join(pkcols, ", "); } protected void updateVersion (Connection conn, int version) throws SQLException { String update = "update " + SCHEMA_VERSION_TABLE + " set version = " + version + " where persistentClass = '" + getTableName() + "'"; String insert = "insert into " + SCHEMA_VERSION_TABLE + " values('" + getTableName() + "', " + version + ")"; Statement stmt = conn.createStatement(); try { if (stmt.executeUpdate(update) == 0) { stmt.executeUpdate(insert); } } finally { stmt.close(); } } protected void requireNotComputed (String action) throws SQLException { if (getTableName() == null) { throw new IllegalArgumentException( "Can't " + action + " computed entities [class=" + _pclass + "]"); } } /** The persistent object class that we manage. */ protected Class<T> _pclass; /** The name of our persistent object table. */ protected String _tableName; /** A field marshaller for each persistent field in our object. */ protected HashMap<String, FieldMarshaller> _fields = new HashMap<String, FieldMarshaller>(); /** The field marshallers for our persistent object's primary key columns * or null if it did not define a primary key. */ protected ArrayList<FieldMarshaller> _pkColumns; /** The generator to use for auto-generating primary key values, or null. */ protected KeyGenerator _keyGenerator; /** The persisent fields of our object, in definition order. */ protected String[] _allFields; /** The fields of our object with directly corresponding table columns. */ protected String[] _columnFields; /** The version of our persistent object schema as specified in the class * definition. */ protected int _schemaVersion = -1; /** Used when creating and migrating our table schema. */ protected ArrayList<String> _declarations = new ArrayList<String>(); /** Used when creating and migrating our table schema. */ protected String _postamble = ""; /** Indicates that we have been initialized (created or migrated our tables). */ protected boolean _initialized; /** A list of hand registered entity migrations to run prior to doing the default migration. */ protected ArrayList<EntityMigration> _migrations = new ArrayList<EntityMigration>(); /** The name of the table we use to track schema versions. */ protected static final String SCHEMA_VERSION_TABLE = "DepotSchemaVersion"; }
src/java/com/samskivert/jdbc/depot/DepotMarshaller.java
// // $Id$ // // samskivert library - useful routines for java programs // Copyright (C) 2006 Michael Bayne, Pär Winzell // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.samskivert.jdbc.depot; import java.lang.reflect.Field; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.logging.Level; import com.samskivert.io.PersistenceException; import com.samskivert.jdbc.depot.annotation.Computed; import com.samskivert.jdbc.depot.annotation.Entity; import com.samskivert.jdbc.depot.annotation.GeneratedValue; import com.samskivert.jdbc.depot.annotation.Id; import com.samskivert.jdbc.depot.annotation.Index; import com.samskivert.jdbc.depot.annotation.Table; import com.samskivert.jdbc.depot.annotation.TableGenerator; import com.samskivert.jdbc.depot.annotation.Transient; import com.samskivert.jdbc.depot.annotation.UniqueConstraint; import com.samskivert.jdbc.JDBCUtil; import com.samskivert.jdbc.depot.clause.Where; import com.samskivert.util.ArrayUtil; import com.samskivert.util.ListUtil; import com.samskivert.util.StringUtil; import static com.samskivert.jdbc.depot.Log.log; /** * Handles the marshalling and unmarshalling of persistent instances to JDBC primitives ({@link * PreparedStatement} and {@link ResultSet}). */ public class DepotMarshaller<T extends PersistentRecord> { /** The name of a private static field that must be defined for all persistent object classes. * It is used to handle schema migration. If automatic schema migration is not desired, define * this field and set its value to -1. */ public static final String SCHEMA_VERSION_FIELD = "SCHEMA_VERSION"; /** * Creates a marshaller for the specified persistent object class. */ public DepotMarshaller (Class<T> pclass, PersistenceContext context) { _pclass = pclass; Entity entity = pclass.getAnnotation(Entity.class); Table table = null; // see if this is a computed entity Computed computed = pclass.getAnnotation(Computed.class); if (computed == null) { // if not, this class has a corresponding SQL table _tableName = _pclass.getName(); _tableName = _tableName.substring(_tableName.lastIndexOf(".")+1); // see if there are Entity values specified if (entity != null) { if (entity.name().length() > 0) { _tableName = entity.name(); } _postamble = entity.postamble(); } // check for a Table annotation, for unique constraints table = pclass.getAnnotation(Table.class); } // if the entity defines a new TableGenerator, map that in our static table as those are // shared across all entities TableGenerator generator = pclass.getAnnotation(TableGenerator.class); if (generator != null) { context.tableGenerators.put(generator.name(), generator); } // introspect on the class and create marshallers for persistent fields ArrayList<String> fields = new ArrayList<String>(); for (Field field : _pclass.getFields()) { int mods = field.getModifiers(); // check for a static constant schema version if (java.lang.reflect.Modifier.isStatic(mods) && field.getName().equals(SCHEMA_VERSION_FIELD)) { try { _schemaVersion = (Integer)field.get(null); } catch (Exception e) { log.log(Level.WARNING, "Failed to read schema version " + "[class=" + _pclass + "].", e); } } // the field must be public, non-static and non-transient if (!java.lang.reflect.Modifier.isPublic(mods) || java.lang.reflect.Modifier.isStatic(mods) || field.getAnnotation(Transient.class) != null) { continue; } FieldMarshaller fm = FieldMarshaller.createMarshaller(field); _fields.put(fm.getColumnName(), fm); fields.add(fm.getColumnName()); // check to see if this is our primary key if (field.getAnnotation(Id.class) != null) { if (_pkColumns == null) { _pkColumns = new ArrayList<FieldMarshaller>(); } _pkColumns.add(fm); // check if this field defines a new TableGenerator generator = field.getAnnotation(TableGenerator.class); if (generator != null) { context.tableGenerators.put(generator.name(), generator); } } } // if the entity defines a single-columnar primary key, figure out if we will be generating // values for it if (_pkColumns != null) { GeneratedValue gv = null; FieldMarshaller keyField = null; // loop over fields to see if there's a @GeneratedValue at all for (FieldMarshaller field : _pkColumns) { gv = field.getGeneratedValue(); if (gv != null) { keyField = field; break; } } if (keyField != null) { // and if there is, make sure we've a single-column id if (_pkColumns.size() > 1) { throw new IllegalArgumentException( "Cannot use @GeneratedValue on multiple-column @Id's"); } // the primary key must be numeric if we are to auto-assign it Class<?> ftype = keyField.getField().getType(); boolean isNumeric = ( ftype.equals(Byte.TYPE) || ftype.equals(Byte.class) || ftype.equals(Short.TYPE) || ftype.equals(Short.class) || ftype.equals(Integer.TYPE) || ftype.equals(Integer.class) || ftype.equals(Long.TYPE) || ftype.equals(Long.class)); if (!isNumeric) { throw new IllegalArgumentException( "Cannot use @GeneratedValue on non-numeric column"); } switch(gv.strategy()) { case AUTO: case IDENTITY: _keyGenerator = new IdentityKeyGenerator(); break; case TABLE: String name = gv.generator(); generator = context.tableGenerators.get(name); if (generator == null) { throw new IllegalArgumentException( "Unknown generator [generator=" + name + "]"); } _keyGenerator = new TableKeyGenerator(generator); break; } } } // generate our full list of fields/columns for use in queries _allFields = fields.toArray(new String[fields.size()]); // if we're a computed entity, stop here if (_tableName == null) { return; } // figure out the list of fields that correspond to actual table columns and generate the // SQL used to create and migrate our table (unless we're a computed entity) _columnFields = new String[_allFields.length]; int jj = 0; for (int ii = 0; ii < _allFields.length; ii++) { // include all persistent non-computed fields String colDef = _fields.get(_allFields[ii]).getColumnDefinition(); if (colDef != null) { _columnFields[jj] = _allFields[ii]; _declarations.add(colDef); jj ++; } } _columnFields = ArrayUtil.splice(_columnFields, jj); // determine whether we have any index definitions if (entity != null) { for (Index index : entity.indices()) { // TODO: delegate this to a database specific SQL generator _declarations.add(index.type() + " index " + index.name() + " (" + StringUtil.join(index.columns(), ", ") + ")"); } } // add any unique constraints given if (table != null) { for (UniqueConstraint constraint : table.uniqueConstraints()) { _declarations.add( "UNIQUE (" + StringUtil.join(constraint.columnNames(), ", ") + ")"); } } // add the primary key, if we have one if (hasPrimaryKey()) { _declarations.add("PRIMARY KEY (" + getPrimaryKeyColumns() + ")"); } // if we did not find a schema version field, complain if (_schemaVersion < 0) { log.warning("Unable to read " + _pclass.getName() + "." + SCHEMA_VERSION_FIELD + ". Schema migration disabled."); } } /** * Returns the name of the table in which persistent instances of our class are stored. By * default this is the classname of the persistent object without the package. */ public String getTableName () { return _tableName; } /** * Returns all the persistent fields of our class, in definition order. */ public String[] getFieldNames () { return _allFields; } /** * Returns the {@link FieldMarshaller} for a named field on our persistent class. */ public FieldMarshaller getFieldMarshaller (String fieldName) { return _fields.get(fieldName); } /** * Returns true if our persistent object defines a primary key. */ public boolean hasPrimaryKey () { return (_pkColumns != null); } /** * Returns a key configured with the primary key of the supplied object. If all the fields are * null, this method returns null. An exception is thrown if some of the fields are null and * some are not, or if the object does not declare a primary key. */ public Key<T> getPrimaryKey (Object object) { return getPrimaryKey(object, true); } /** * Returns a key configured with the primary key of the supplied object. If all the fields are * null, this method returns null. If some of the fields are null and some are not, an * exception is thrown. If the object does not declare a primary key and the second argument is * true, this method throws an exception; if it's false, the method returns null. */ public Key<T> getPrimaryKey (Object object, boolean requireKey) { if (!hasPrimaryKey()) { if (requireKey) { throw new UnsupportedOperationException( _pclass.getName() + " does not define a primary key"); } return null; } try { Comparable[] values = new Comparable[_pkColumns.size()]; boolean hasNulls = false; for (int ii = 0; ii < _pkColumns.size(); ii++) { FieldMarshaller field = _pkColumns.get(ii); values[ii] = (Comparable) field.getField().get(object); if (values[ii] == null || Integer.valueOf(0).equals(values[ii])) { // if this is the first null we see but not the first field, freak out if (!hasNulls && ii > 0) { throw new IllegalArgumentException( "Persistent object's primary key fields are mixed null and non-null."); } hasNulls = true; } else if (hasNulls) { // if this is a non-null field and we've previously seen nulls, also freak throw new IllegalArgumentException( "Persistent object's primary key fields are mixed null and non-null."); } } // if all the fields were null, return null, else build a key return hasNulls ? null : makePrimaryKey(values); } catch (IllegalAccessException iae) { throw new RuntimeException(iae); } } /** * Creates a primary key record for the type of object handled by this marshaller, using the * supplied primary key value. */ public Key<T> makePrimaryKey (Comparable... values) { if (!hasPrimaryKey()) { throw new UnsupportedOperationException( getClass().getName() + " does not define a primary key"); } String[] columns = new String[_pkColumns.size()]; for (int ii = 0; ii < _pkColumns.size(); ii++) { columns[ii] = _pkColumns.get(ii).getColumnName(); } return new Key<T>(_pclass, columns, values); } /** * Returns true if this marshaller has been initialized ({@link #init} has been called), its * migrations run and it is ready for operation. False otherwise. */ public boolean isInitialized () { return _initialized; } /** * Creates a persistent object from the supplied result set. The result set must have come from * a query provided by {@link #createQuery}. */ public T createObject (ResultSet rs) throws SQLException { try { // first, build a set of the fields that we actually received Set<String> fields = new HashSet<String>(); ResultSetMetaData metadata = rs.getMetaData(); for (int ii = 1; ii <= metadata.getColumnCount(); ii ++) { fields.add(metadata.getColumnName(ii)); } // then create and populate the persistent object T po = _pclass.newInstance(); for (FieldMarshaller fm : _fields.values()) { if (!fields.contains(fm.getField().getName())) { // this field was not in the result set, make sure that's OK if (fm.getComputed() != null && !fm.getComputed().required()) { continue; } throw new SQLException("ResultSet missing field: " + fm.getField().getName()); } fm.getValue(rs, po); } return po; } catch (SQLException sqe) { // pass this on through throw sqe; } catch (Exception e) { String errmsg = "Failed to unmarshall persistent object [pclass=" + _pclass.getName() + "]"; throw (SQLException)new SQLException(errmsg).initCause(e); } } /** * Creates a statement that will insert the supplied persistent object into the database. */ public PreparedStatement createInsert (Connection conn, Object po) throws SQLException { requireNotComputed("insert rows into"); try { StringBuilder insert = new StringBuilder(); insert.append("insert into ").append(getTableName()); insert.append(" (").append(StringUtil.join(_columnFields, ",")); insert.append(")").append(" values("); for (int ii = 0; ii < _columnFields.length; ii++) { if (ii > 0) { insert.append(", "); } insert.append("?"); } insert.append(")"); // TODO: handle primary key, nullable fields specially? PreparedStatement pstmt = conn.prepareStatement(insert.toString()); int idx = 0; for (String field : _columnFields) { _fields.get(field).setValue(po, pstmt, ++idx); } return pstmt; } catch (SQLException sqe) { // pass this on through throw sqe; } catch (Exception e) { String errmsg = "Failed to marshall persistent object [pclass=" + _pclass.getName() + "]"; throw (SQLException)new SQLException(errmsg).initCause(e); } } /** * Fills in the primary key just assigned to the supplied persistence object by the execution * of the results of {@link #createInsert}. * * @return the newly assigned primary key or null if the object does not use primary keys or * this is not the right time to assign the key. */ public Key assignPrimaryKey (Connection conn, Object po, boolean postFactum) throws SQLException { // if we have no primary key or no generator, then we're done if (!hasPrimaryKey() || _keyGenerator == null) { return null; } // run this generator either before or after the actual insertion if (_keyGenerator.isPostFactum() != postFactum) { return null; } try { int nextValue = _keyGenerator.nextGeneratedValue(conn); _pkColumns.get(0).getField().set(po, nextValue); return makePrimaryKey(nextValue); } catch (Exception e) { String errmsg = "Failed to assign primary key [type=" + _pclass + "]"; throw (SQLException) new SQLException(errmsg).initCause(e); } } /** * Creates a statement that will update the supplied persistent object using the supplied key. */ public PreparedStatement createUpdate (Connection conn, Object po, Where key) throws SQLException { return createUpdate(conn, po, key, _columnFields); } /** * Creates a statement that will update the supplied persistent object * using the supplied key. */ public PreparedStatement createUpdate ( Connection conn, Object po, Where key, String[] modifiedFields) throws SQLException { requireNotComputed("update rows in"); StringBuilder update = new StringBuilder(); update.append("update ").append(getTableName()).append(" set "); int idx = 0; for (String field : modifiedFields) { if (idx++ > 0) { update.append(", "); } update.append(field).append(" = ?"); } key.appendClause(null, update); try { PreparedStatement pstmt = conn.prepareStatement(update.toString()); idx = 0; // bind the update arguments for (String field : modifiedFields) { _fields.get(field).setValue(po, pstmt, ++idx); } // now bind the key arguments key.bindArguments(pstmt, ++idx); return pstmt; } catch (SQLException sqe) { // pass this on through throw sqe; } catch (Exception e) { String errmsg = "Failed to marshall persistent object " + "[pclass=" + _pclass.getName() + "]"; throw (SQLException)new SQLException(errmsg).initCause(e); } } /** * Creates a statement that will update the specified set of fields for all persistent objects * that match the supplied key. */ public PreparedStatement createPartialUpdate ( Connection conn, Where key, String[] modifiedFields, Object[] modifiedValues) throws SQLException { requireNotComputed("update rows in"); StringBuilder update = new StringBuilder(); update.append("update ").append(getTableName()).append(" set "); int idx = 0; for (String field : modifiedFields) { if (idx++ > 0) { update.append(", "); } update.append(field).append(" = ?"); } key.appendClause(null, update); PreparedStatement pstmt = conn.prepareStatement(update.toString()); idx = 0; // bind the update arguments for (Object value : modifiedValues) { // TODO: use the field marshaller? pstmt.setObject(++idx, value); } // now bind the key arguments key.bindArguments(pstmt, ++idx); return pstmt; } /** * Creates a statement that will delete all rows matching the supplied key. */ public PreparedStatement createDelete (Connection conn, Where key) throws SQLException { requireNotComputed("delete rows from"); StringBuilder query = new StringBuilder("delete from " + getTableName()); key.appendClause(null, query); PreparedStatement pstmt = conn.prepareStatement(query.toString()); key.bindArguments(pstmt, 1); return pstmt; } /** * Creates a statement that will update the specified set of fields, using the supplied literal * SQL values, for all persistent objects that match the supplied key. */ public PreparedStatement createLiteralUpdate ( Connection conn, Where key, String[] modifiedFields, Object[] modifiedValues) throws SQLException { requireNotComputed("update rows in"); StringBuilder update = new StringBuilder(); update.append("update ").append(getTableName()).append(" set "); for (int ii = 0; ii < modifiedFields.length; ii++) { if (ii > 0) { update.append(", "); } update.append(modifiedFields[ii]).append(" = "); update.append(modifiedValues[ii]); } key.appendClause(null, update); PreparedStatement pstmt = conn.prepareStatement(update.toString()); key.bindArguments(pstmt, 1); return pstmt; } /** * This is called by the persistence context to register a migration for the entity managed by * this marshaller. */ protected void registerMigration (EntityMigration migration) { _migrations.add(migration); } /** * Initializes the table used by this marshaller. This is called automatically by the {@link * PersistenceContext} the first time an entity is used. If the table does not exist, it will * be created. If the schema version specified by the persistent object is newer than the * database schema, it will be migrated. */ protected void init (PersistenceContext ctx) throws PersistenceException { if (_initialized) { // sanity check throw new IllegalStateException( "Cannot re-initialize marshaller [type=" + _pclass + "]."); } _initialized = true; // if we have no table (i.e. we're a computed entity), we have nothing to create if (getTableName() == null) { return; } // check to see if our schema version table exists, create it if not ctx.invoke(new Modifier() { public int invoke (Connection conn) throws SQLException { JDBCUtil.createTableIfMissing( conn, SCHEMA_VERSION_TABLE, new String[] { "persistentClass VARCHAR(255) NOT NULL", "version INTEGER NOT NULL" }, ""); return 0; } }); // now create the table for our persistent class if it does not exist ctx.invoke(new Modifier() { public int invoke (Connection conn) throws SQLException { if (!JDBCUtil.tableExists(conn, getTableName())) { log.info("Creating table " + getTableName() + " (" + _declarations + ") " + _postamble); String[] definition = _declarations.toArray(new String[_declarations.size()]); JDBCUtil.createTableIfMissing(conn, getTableName(), definition, _postamble); updateVersion(conn, _schemaVersion); } return 0; } }); // if we have a key generator, initialize that too if (_keyGenerator != null) { ctx.invoke(new Modifier() { public int invoke (Connection conn) throws SQLException { _keyGenerator.init(conn); return 0; } }); } // if schema versioning is disabled, stop now if (_schemaVersion < 0) { return; } // make sure the versions match int currentVersion = ctx.invoke(new Modifier() { public int invoke (Connection conn) throws SQLException { String query = "select version from " + SCHEMA_VERSION_TABLE + " where persistentClass = '" + getTableName() + "'"; Statement stmt = conn.createStatement(); try { ResultSet rs = stmt.executeQuery(query); return (rs.next()) ? rs.getInt(1) : 1; } finally { stmt.close(); } } }); if (currentVersion == _schemaVersion) { return; } // otherwise try to migrate the schema log.info("Migrating " + getTableName() + " from " + currentVersion + " to " + _schemaVersion + "..."); // run our pre-default-migrations for (EntityMigration migration : _migrations) { if (migration.runBeforeDefault() && migration.shouldRunMigration(currentVersion, _schemaVersion)) { migration.init(getTableName(), _fields); ctx.invoke(migration); } } // enumerate all of the columns now that we've run our pre-migrations final Set<String> columns = new HashSet<String>(); final Map<String, Set<String>> indexColumns = new HashMap<String, Set<String>>(); ctx.invoke(new Modifier() { public int invoke (Connection conn) throws SQLException { DatabaseMetaData meta = conn.getMetaData(); ResultSet rs = meta.getColumns(null, null, getTableName(), "%"); while (rs.next()) { columns.add(rs.getString("COLUMN_NAME")); } rs = meta.getIndexInfo(null, null, getTableName(), false, false); while (rs.next()) { String indexName = rs.getString("INDEX_NAME"); Set<String> set = indexColumns.get(indexName); if (rs.getBoolean("NON_UNIQUE")) { // not a unique index: just make sure there's an entry in the keyset if (set == null) { indexColumns.put(indexName, null); } } else { // for unique indices we collect the column names if (set == null) { set = new HashSet<String>(); indexColumns.put(indexName, set); } set.add(rs.getString("COLUMN_NAME")); } } return 0; } }); // this is a little silly, but we need a copy for name disambiguation later Set<String> indicesCopy = new HashSet<String>(indexColumns.keySet()); // add any missing columns for (String fname : _columnFields) { FieldMarshaller fmarsh = _fields.get(fname); if (columns.remove(fmarsh.getColumnName())) { continue; } // otherwise add the column String coldef = fmarsh.getColumnDefinition(); String query = "alter table " + getTableName() + " add column " + coldef; // try to add it to the appropriate spot int fidx = ListUtil.indexOf(_allFields, fmarsh.getColumnName()); if (fidx == 0) { query += " first"; } else { query += " after " + _allFields[fidx-1]; } log.info("Adding column to " + getTableName() + ": " + coldef); ctx.invoke(new Modifier.Simple(query)); // if the column is a TIMESTAMP or DATETIME column, we need to run a special query to // update all existing rows to the current time because MySQL annoyingly assigns // TIMESTAMP columns a value of "0000-00-00 00:00:00" regardless of whether we // explicitly provide a "DEFAULT" value for the column or not, and DATETIME columns // cannot accept CURRENT_TIME or NOW() defaults at all. if (coldef.toLowerCase().indexOf(" timestamp") != -1 || coldef.toLowerCase().indexOf(" datetime") != -1) { query = "update " + getTableName() + " set " + fmarsh.getColumnName() + " = NOW()"; log.info("Assigning current time to column: " + query); ctx.invoke(new Modifier.Simple(query)); } } // add or remove the primary key as needed if (hasPrimaryKey() && !indexColumns.containsKey("PRIMARY")) { String pkdef = "primary key (" + getPrimaryKeyColumns() + ")"; log.info("Adding primary key to " + getTableName() + ": " + pkdef); ctx.invoke(new Modifier.Simple("alter table " + getTableName() + " add " + pkdef)); } else if (!hasPrimaryKey() && indexColumns.containsKey("PRIMARY")) { indexColumns.remove("PRIMARY"); log.info("Dropping primary from " + getTableName()); ctx.invoke(new Modifier.Simple("alter table " + getTableName() + " drop primary key")); } // add any missing indices Entity entity = _pclass.getAnnotation(Entity.class); for (Index index : (entity == null ? new Index[0] : entity.indices())) { if (indexColumns.containsKey(index.name())) { indexColumns.remove(index.name()); continue; } String indexdef = "create " + index.type() + " index " + index.name() + " on " + getTableName() + " (" + StringUtil.join(index.columns(), ", ") + ")"; log.info("Adding index: " + indexdef); ctx.invoke(new Modifier.Simple(indexdef)); } // to get the @Table(uniqueIndices...) indices, we use our clever set of column name sets Set<Set<String>> uniqueIndices = new HashSet<Set<String>>(indexColumns.values()); Table table; if (getTableName() != null && (table = _pclass.getAnnotation(Table.class)) != null) { Set<String> colSet = new HashSet<String>(); for (UniqueConstraint constraint : table.uniqueConstraints()) { // for each given UniqueConstraint, build a new column set colSet.clear(); for (String column : constraint.columnNames()) { colSet.add(column); } // and check if the table contained this set if (uniqueIndices.contains(colSet)) { continue; // good, carry on } // else build the index; we'll use mysql's convention of naming it after a column, // with possible _N disambiguation; luckily we made a copy of the index names! String indexName = colSet.iterator().next(); if (indicesCopy.contains(indexName)) { int num = 1; indexName += "_"; while (indicesCopy.contains(indexName + num)) { num ++; } indexName += num; } String[] columnArr = colSet.toArray(new String[colSet.size()]); String indexdef = "create unique index " + indexName + " on " + getTableName() + " (" + StringUtil.join(columnArr, ", ") + ")"; log.info("Adding unique index: " + indexdef); ctx.invoke(new Modifier.Simple(indexdef)); } } // we do not auto-remove columns but rather require that EntityMigration.Drop records be // registered by hand to avoid accidentally causin the loss of data // we don't auto-remove indices either because we'd have to sort out the potentially // complex origins of an index (which might be because of a @Unique column or maybe the // index was hand defined in a @Column clause) // run our post-default-migrations for (EntityMigration migration : _migrations) { if (!migration.runBeforeDefault() && migration.shouldRunMigration(currentVersion, _schemaVersion)) { ctx.invoke(migration); } } // record our new version in the database ctx.invoke(new Modifier() { public int invoke (Connection conn) throws SQLException { updateVersion(conn, _schemaVersion); return 0; } }); } protected String getPrimaryKeyColumns () { String[] pkcols = new String[_pkColumns.size()]; for (int ii = 0; ii < pkcols.length; ii ++) { pkcols[ii] = _pkColumns.get(ii).getColumnName(); } return StringUtil.join(pkcols, ", "); } protected void updateVersion (Connection conn, int version) throws SQLException { String update = "update " + SCHEMA_VERSION_TABLE + " set version = " + version + " where persistentClass = '" + getTableName() + "'"; String insert = "insert into " + SCHEMA_VERSION_TABLE + " values('" + getTableName() + "', " + version + ")"; Statement stmt = conn.createStatement(); try { if (stmt.executeUpdate(update) == 0) { stmt.executeUpdate(insert); } } finally { stmt.close(); } } protected void requireNotComputed (String action) throws SQLException { if (getTableName() == null) { throw new IllegalArgumentException( "Can't " + action + " computed entities [class=" + _pclass + "]"); } } /** The persistent object class that we manage. */ protected Class<T> _pclass; /** The name of our persistent object table. */ protected String _tableName; /** A field marshaller for each persistent field in our object. */ protected HashMap<String, FieldMarshaller> _fields = new HashMap<String, FieldMarshaller>(); /** The field marshallers for our persistent object's primary key columns * or null if it did not define a primary key. */ protected ArrayList<FieldMarshaller> _pkColumns; /** The generator to use for auto-generating primary key values, or null. */ protected KeyGenerator _keyGenerator; /** The persisent fields of our object, in definition order. */ protected String[] _allFields; /** The fields of our object with directly corresponding table columns. */ protected String[] _columnFields; /** The version of our persistent object schema as specified in the class * definition. */ protected int _schemaVersion = -1; /** Used when creating and migrating our table schema. */ protected ArrayList<String> _declarations = new ArrayList<String>(); /** Used when creating and migrating our table schema. */ protected String _postamble = ""; /** Indicates that we have been initialized (created or migrated our tables). */ protected boolean _initialized; /** A list of hand registered entity migrations to run prior to doing the default migration. */ protected ArrayList<EntityMigration> _migrations = new ArrayList<EntityMigration>(); /** The name of the table we use to track schema versions. */ protected static final String SCHEMA_VERSION_TABLE = "DepotSchemaVersion"; }
We need to initialize migrations here as well. git-svn-id: 64ebf368729f38804935acb7146e017e0f909c6b@2109 6335cc39-0255-0410-8fd6-9bcaacd3b74c
src/java/com/samskivert/jdbc/depot/DepotMarshaller.java
We need to initialize migrations here as well.
<ide><path>rc/java/com/samskivert/jdbc/depot/DepotMarshaller.java <ide> for (EntityMigration migration : _migrations) { <ide> if (!migration.runBeforeDefault() && <ide> migration.shouldRunMigration(currentVersion, _schemaVersion)) { <add> migration.init(getTableName(), _fields); <ide> ctx.invoke(migration); <ide> } <ide> }
Java
mit
5f4a853779fbfc41e2a2d33ddbd5f440619f4c34
0
nrg12/VOOGASalad,ankitkayastha/VOOGASalad
/** * */ package engine.front_end; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import engine.events.EventManager; import engine.events.IGameUpdatedHandler; import engine.events.IRoomUpdatedHandler; import exceptions.ResourceFailedException; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.geometry.Pos; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.canvas.Canvas; import javafx.scene.control.Button; import javafx.scene.control.ChoiceBox; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem; import javafx.scene.control.RadioMenuItem; import javafx.scene.control.ToggleGroup; import javafx.scene.control.ToolBar; import javafx.scene.image.ImageView; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseEvent; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.StackPane; import javafx.scene.layout.VBox; import javafx.scene.text.Text; import javafx.stage.FileChooser; import javafx.stage.Stage; import structures.run.IParameters; import structures.run.RunRoom; //uncomment for controller functionality //import voogasalad.util.externalcontroller.ControllerListener; /** * @author loganrooper */ public class FrontEnd implements IGameUpdatedHandler, IRoomUpdatedHandler { public static final String DEFAULT_RESOURCE_PACKAGE = "css/"; public static final String STYLESHEET = ".css"; public static final String DEFAULT_IMAGE_PACKAGE = "resources/"; public static final String[] COLORS = {"Blue", "Green", "Grey", "Pink", "Purple", "Red", "Yellow"}; private String styleSheetColor = "blue"; private Canvas myCanvas; private IDraw myCanvasDrawer; private Group myRoot; private Stage stage; private Scene playScene; private EventManager myEventManager; private String myCurrentGame; private VBox topContainer; private BorderPane borderPane; private HighScoreView myHighScoreView; private ObjectInformationView myObjectInformationView; private int gameHeight, gameWidth; public FrontEnd(int width, int height, EventManager eventManager, Stage stage, String game) throws IOException, ResourceFailedException { gameHeight = height; gameWidth = width; myCurrentGame = game; borderPane = new BorderPane(); topContainer = new VBox(); myEventManager = eventManager; this.stage = stage; stage.setHeight(height + 100); stage.setWidth(500 + width); stage.centerOnScreen(); stage.setY(stage.getY()-100); setupFramework(gameWidth, gameHeight); setupCanvas(width, height); } private void setupFramework(int gameWidth, int gameHeight) throws IOException, ResourceFailedException{ myRoot = new Group(); playScene = new Scene(borderPane, 200 + gameWidth, 100 + gameHeight); playScene.getStylesheets().add(DEFAULT_RESOURCE_PACKAGE + styleSheetColor + STYLESHEET); stage.setScene(playScene); borderPane.setCenter(myRoot); makeMenu(); makeToolBar(); makeHighScoreBar(); } private void makeMenu() { MenuBar myMenus = new MenuBar(); myMenus.useSystemMenuBarProperty().set(true); Menu fileMenu = new Menu("File"); MenuItem open = new MenuItem("Open"); open.setOnAction(e -> { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Choose a Game"); fileChooser.showOpenDialog(stage); }); MenuItem reset = new MenuItem("Reset"); reset.setOnAction(e -> { try { myEventManager.onReset(); } catch (Exception e1) { e1.printStackTrace(); } }); MenuItem save = new MenuItem("Save"); save.setOnAction(e -> { myEventManager.onSave(); }); MenuItem close = new MenuItem("Close"); close.setOnAction(e -> { myEventManager.onSave(); stage.close(); }); MenuItem pause = new MenuItem("Pause"); pause.setOnAction(e -> { myEventManager.onPause(); }); Menu savedGames = new Menu("Saved Games"); Menu view = new Menu("View"); MenuItem highScore = new MenuItem("Show High Scores"); MenuItem showHelp = new MenuItem("Show Help"); Menu option = new Menu("Options"); Menu debugOption = new Menu("Debug Option"); RadioMenuItem yes = new RadioMenuItem("Yes"); ToggleGroup debugToggle = new ToggleGroup(); yes.setOnAction(e -> myEventManager.setDebug(true)); yes.setToggleGroup(debugToggle); RadioMenuItem no = new RadioMenuItem("No"); no.setOnAction(e -> myEventManager.setDebug(false)); no.setToggleGroup(debugToggle); no.setSelected(true); Menu colorOption = new Menu("Theme"); ToggleGroup colorToggle = new ToggleGroup(); for (String color : COLORS) { RadioMenuItem radioItem = new RadioMenuItem(color); radioItem.setOnAction(e -> {styleSheetColor = radioItem.getText().toLowerCase(); playScene.getStylesheets().clear(); playScene.getStylesheets().add(DEFAULT_RESOURCE_PACKAGE + styleSheetColor + STYLESHEET);}); radioItem.setToggleGroup(colorToggle); if (color.toLowerCase().equals(styleSheetColor)) radioItem.setSelected(true); colorOption.getItems().add(radioItem); } myMenus.getMenus().addAll(fileMenu, savedGames, view, option); fileMenu.getItems().addAll(open, reset, save, close, pause); view.getItems().addAll(highScore, showHelp); option.getItems().addAll(debugOption, colorOption); debugOption.getItems().addAll(yes, no); topContainer.getChildren().add(myMenus); } public Menu makeColorOptionMenu(ToggleGroup colorToggle) { Menu colorOption = new Menu("Theme"); for (String color : COLORS) { RadioMenuItem radioItem = new RadioMenuItem(color); radioItem.setOnAction(e -> {styleSheetColor = radioItem.getText().toLowerCase(); playScene.getStylesheets().clear(); playScene.getStylesheets().add(DEFAULT_RESOURCE_PACKAGE + styleSheetColor + STYLESHEET);}); radioItem.setToggleGroup(colorToggle); if (color.equals(styleSheetColor)) radioItem.setSelected(true); } return colorOption; } public void makeToolBar() throws ResourceFailedException { HBox hbox = new HBox(8); hbox.setAlignment(Pos.CENTER); Button playButton = new Button(); playButton.setGraphic(new ImageView(DEFAULT_IMAGE_PACKAGE + "play.png")); playButton.setOnMouseClicked(e -> { myEventManager.onResume(); }); Button pauseButton = new Button(); pauseButton.setGraphic(new ImageView(DEFAULT_IMAGE_PACKAGE + "pause.png")); pauseButton.setOnMouseClicked(e -> { myEventManager.onPause(); }); Button resetButton = new Button(); resetButton.setGraphic(new ImageView(DEFAULT_IMAGE_PACKAGE + "reset.png")); resetButton.setOnMouseClicked(e -> { try { myEventManager.onReset(); } catch (Exception e1) { e1.printStackTrace(); } }); Button saveButton = new Button(); saveButton.setGraphic(new ImageView(DEFAULT_IMAGE_PACKAGE + "save.png")); saveButton.setOnMouseClicked(e -> { myEventManager.onSave(); }); Button openButton = new Button(); openButton.setGraphic(new ImageView(DEFAULT_IMAGE_PACKAGE + "open.png")); openButton.setOnMouseClicked(e -> { myEventManager.onLoadSave("10"); }); ToolBar tBar = new ToolBar(playButton, pauseButton, resetButton, saveButton, openButton); VBox change = new VBox(2); Text changeTitle = new Text("Change game"); ChoiceBox<String> cb = new ChoiceBox<String>(); cb.setFocusTraversable(false); cb.getItems().addAll(addGamesFromDirectory()); //cb.setOnAction(e -> onGameChange(cb.getValue())); //cb.addEventHandler(ChoiceBox, e -> onGameChange(cb.getValue())); cb.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { public void changed(ObservableValue<? extends String> source, String oldValue, String newValue) { onGameChange(cb.getValue()); }}); change.getChildren().addAll(changeTitle, cb); hbox.getChildren().add(tBar); hbox.getChildren().add(change); topContainer.getChildren().add(hbox); borderPane.setTop(topContainer); } private List<String> addGamesFromDirectory() { List<String> choices = new ArrayList<String>(); for (final File fileEntry : new File("Games/").listFiles()) { choices.add(fileEntry.getName()); } return choices; } private void makeHighScoreBar() throws IOException{ myHighScoreView = new HighScoreView(myCurrentGame); myHighScoreView.setPrefWidth(150); myHighScoreView.setFocusTraversable(false); borderPane.setRight(myHighScoreView); } public void makeObjectInformationBar(IParameters parameterObject) { myObjectInformationView = new ObjectInformationView(parameterObject); myObjectInformationView.setPrefWidth(275); myObjectInformationView.setFocusTraversable(false); borderPane.setLeft(myObjectInformationView); stage.setWidth(1100); } private void setupCanvas(int width, int height) throws IOException{ myCanvas = new Canvas(width, height); myCanvasDrawer = new Draw(myCanvas); StackPane pane = (StackPane) myCanvasDrawer; myRoot.getChildren().add(pane); setupUserInteraction(pane); } private void setupUserInteraction(StackPane pane) throws IOException{ pane.addEventFilter(MouseEvent.MOUSE_PRESSED, myEventManager::onMouseEvent); stage.getScene().setOnMouseMoved(myEventManager::onMouseEvent); stage.getScene().addEventFilter(KeyEvent.KEY_PRESSED, myEventManager::onKeyEvent); stage.getScene().addEventFilter(KeyEvent.KEY_RELEASED, myEventManager::onKeyEvent); //uncomment for controller functionality // ControllerListener controllerTest = new ControllerListener(); // if(controllerTest.getControllerConnected()){ // controllerTest.initialize(stage); // } } public IDraw getDrawListener(){ return myCanvasDrawer; } public IGameUpdatedHandler getFrontEndUpdateHandler(){ return this; } public IRoomUpdatedHandler getRoomUpdateHandler(){ return this; } public void onGameChange(String name) { try { myHighScoreView.setGame(name); myEventManager.onChangeGame(name); } catch (ResourceFailedException e) { e.printStackTrace(); } } @Override public void onRoomChanged(RunRoom runRoom) { // stage.setWidth(runRoom.getView().getView().width()); // stage.setHeight(runRoom.getView().getView().height()); } @Override public void setHighScore(double highScore) { myHighScoreView.updateScore(highScore); } @Override public double getHighScore() { return myHighScoreView.getHighScore(); } }
src/engine/front_end/FrontEnd.java
/** * */ package engine.front_end; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import engine.events.EventManager; import engine.events.IGameUpdatedHandler; import engine.events.IRoomUpdatedHandler; import exceptions.ResourceFailedException; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.geometry.Pos; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.canvas.Canvas; import javafx.scene.control.Button; import javafx.scene.control.ChoiceBox; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem; import javafx.scene.control.RadioMenuItem; import javafx.scene.control.ToggleGroup; import javafx.scene.control.ToolBar; import javafx.scene.image.ImageView; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseEvent; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.StackPane; import javafx.scene.layout.VBox; import javafx.scene.text.Text; import javafx.stage.FileChooser; import javafx.stage.Stage; import structures.run.IParameters; import structures.run.RunRoom; //uncomment for controller functionality //import voogasalad.util.externalcontroller.ControllerListener; /** * @author loganrooper */ public class FrontEnd implements IGameUpdatedHandler, IRoomUpdatedHandler { public static final String DEFAULT_RESOURCE_PACKAGE = "css/"; public static final String STYLESHEET = ".css"; public static final String DEFAULT_IMAGE_PACKAGE = "resources/"; private String styleSheetColor = "blue"; private Canvas myCanvas; private IDraw myCanvasDrawer; private Group myRoot; private Stage stage; private Scene playScene; private EventManager myEventManager; private String myCurrentGame; private VBox topContainer; private BorderPane borderPane; private HighScoreView myHighScoreView; private ObjectInformationView myObjectInformationView; private int gameHeight, gameWidth; public FrontEnd(int width, int height, EventManager eventManager, Stage stage, String game) throws IOException, ResourceFailedException { gameHeight = height; gameWidth = width; myCurrentGame = game; borderPane = new BorderPane(); topContainer = new VBox(); myEventManager = eventManager; this.stage = stage; stage.setHeight(height + 100); stage.setWidth(500 + width); stage.centerOnScreen(); stage.setY(stage.getY()-100); setupFramework(gameWidth, gameHeight); setupCanvas(width, height); } private void setupFramework(int gameWidth, int gameHeight) throws IOException, ResourceFailedException{ myRoot = new Group(); playScene = new Scene(borderPane, 200 + gameWidth, 100 + gameHeight); playScene.getStylesheets().add(DEFAULT_RESOURCE_PACKAGE + styleSheetColor + STYLESHEET); stage.setScene(playScene); borderPane.setCenter(myRoot); makeMenu(); makeToolBar(); makeHighScoreBar(); } private void makeMenu() { MenuBar myMenus = new MenuBar(); myMenus.useSystemMenuBarProperty().set(true); Menu fileMenu = new Menu("File"); MenuItem open = new MenuItem("Open"); open.setOnAction(e -> { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Choose a Game"); fileChooser.showOpenDialog(stage); }); MenuItem reset = new MenuItem("Reset"); reset.setOnAction(e -> { try { myEventManager.onReset(); } catch (Exception e1) { e1.printStackTrace(); } }); MenuItem save = new MenuItem("Save"); save.setOnAction(e -> { myEventManager.onSave(); }); MenuItem close = new MenuItem("Close"); close.setOnAction(e -> { myEventManager.onSave(); stage.close(); }); MenuItem pause = new MenuItem("Pause"); pause.setOnAction(e -> { myEventManager.onPause(); }); Menu savedGames = new Menu("Saved Games"); Menu view = new Menu("View"); MenuItem highScore = new MenuItem("Show High Scores"); MenuItem showHelp = new MenuItem("Show Help"); Menu option = new Menu("Options"); Menu debugOption = new Menu("Debug Option"); RadioMenuItem yes = new RadioMenuItem("Yes"); ToggleGroup debugToggle = new ToggleGroup(); yes.setOnAction(e -> myEventManager.setDebug(true)); yes.setToggleGroup(debugToggle); RadioMenuItem no = new RadioMenuItem("No"); no.setOnAction(e -> myEventManager.setDebug(false)); no.setToggleGroup(debugToggle); no.setSelected(true); myMenus.getMenus().addAll(fileMenu, savedGames, view, option); fileMenu.getItems().addAll(open, reset, save, close, pause); view.getItems().addAll(highScore, showHelp); option.getItems().add(debugOption); debugOption.getItems().addAll(yes, no); topContainer.getChildren().add(myMenus); } public void makeToolBar() throws ResourceFailedException { HBox hbox = new HBox(8); hbox.setAlignment(Pos.CENTER); Button playButton = new Button(); playButton.setGraphic(new ImageView(DEFAULT_IMAGE_PACKAGE + "play.png")); playButton.setOnMouseClicked(e -> { myEventManager.onResume(); }); Button pauseButton = new Button(); pauseButton.setGraphic(new ImageView(DEFAULT_IMAGE_PACKAGE + "pause.png")); pauseButton.setOnMouseClicked(e -> { myEventManager.onPause(); }); Button resetButton = new Button(); resetButton.setGraphic(new ImageView(DEFAULT_IMAGE_PACKAGE + "reset.png")); resetButton.setOnMouseClicked(e -> { try { myEventManager.onReset(); } catch (Exception e1) { e1.printStackTrace(); } }); Button saveButton = new Button(); saveButton.setGraphic(new ImageView(DEFAULT_IMAGE_PACKAGE + "save.png")); saveButton.setOnMouseClicked(e -> { myEventManager.onSave(); }); Button openButton = new Button(); openButton.setGraphic(new ImageView(DEFAULT_IMAGE_PACKAGE + "open.png")); openButton.setOnMouseClicked(e -> { myEventManager.onLoadSave("10"); }); ToolBar tBar = new ToolBar(playButton, pauseButton, resetButton, saveButton, openButton); VBox change = new VBox(2); Text changeTitle = new Text("Change game"); ChoiceBox<String> cb = new ChoiceBox<String>(); cb.setFocusTraversable(false); cb.getItems().addAll(addGamesFromDirectory()); //cb.setOnAction(e -> onGameChange(cb.getValue())); //cb.addEventHandler(ChoiceBox, e -> onGameChange(cb.getValue())); cb.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { public void changed(ObservableValue<? extends String> source, String oldValue, String newValue) { onGameChange(cb.getValue()); }}); change.getChildren().addAll(changeTitle, cb); hbox.getChildren().add(tBar); hbox.getChildren().add(change); topContainer.getChildren().add(hbox); borderPane.setTop(topContainer); } private List<String> addGamesFromDirectory() { List<String> choices = new ArrayList<String>(); for (final File fileEntry : new File("Games/").listFiles()) { choices.add(fileEntry.getName()); } return choices; } private void makeHighScoreBar() throws IOException{ myHighScoreView = new HighScoreView(myCurrentGame); myHighScoreView.setPrefWidth(150); myHighScoreView.setFocusTraversable(false); borderPane.setRight(myHighScoreView); } public void makeObjectInformationBar(IParameters parameterObject) { myObjectInformationView = new ObjectInformationView(parameterObject); myObjectInformationView.setPrefWidth(275); myObjectInformationView.setFocusTraversable(false); borderPane.setLeft(myObjectInformationView); stage.setWidth(1100); } private void setupCanvas(int width, int height) throws IOException{ myCanvas = new Canvas(width, height); myCanvasDrawer = new Draw(myCanvas); StackPane pane = (StackPane) myCanvasDrawer; myRoot.getChildren().add(pane); setupUserInteraction(pane); } private void setupUserInteraction(StackPane pane) throws IOException{ pane.addEventFilter(MouseEvent.MOUSE_PRESSED, myEventManager::onMouseEvent); stage.getScene().setOnMouseMoved(myEventManager::onMouseEvent); stage.getScene().addEventFilter(KeyEvent.KEY_PRESSED, myEventManager::onKeyEvent); stage.getScene().addEventFilter(KeyEvent.KEY_RELEASED, myEventManager::onKeyEvent); //uncomment for controller functionality // ControllerListener controllerTest = new ControllerListener(); // if(controllerTest.getControllerConnected()){ // controllerTest.initialize(stage); // } } public IDraw getDrawListener(){ return myCanvasDrawer; } public IGameUpdatedHandler getFrontEndUpdateHandler(){ return this; } public IRoomUpdatedHandler getRoomUpdateHandler(){ return this; } public void onGameChange(String name) { try { myHighScoreView.setGame(name); myEventManager.onChangeGame(name); } catch (ResourceFailedException e) { e.printStackTrace(); } } @Override public void onRoomChanged(RunRoom runRoom) { // stage.setWidth(runRoom.getView().getView().width()); // stage.setHeight(runRoom.getView().getView().height()); } @Override public void setHighScore(double highScore) { myHighScoreView.updateScore(highScore); } @Override public double getHighScore() { return myHighScoreView.getHighScore(); } }
theme options on engine
src/engine/front_end/FrontEnd.java
theme options on engine
<ide><path>rc/engine/front_end/FrontEnd.java <ide> public static final String DEFAULT_RESOURCE_PACKAGE = "css/"; <ide> public static final String STYLESHEET = ".css"; <ide> public static final String DEFAULT_IMAGE_PACKAGE = "resources/"; <add> public static final String[] COLORS = {"Blue", "Green", "Grey", "Pink", "Purple", "Red", "Yellow"}; <ide> <ide> private String styleSheetColor = "blue"; <ide> private Canvas myCanvas; <ide> no.setOnAction(e -> myEventManager.setDebug(false)); <ide> no.setToggleGroup(debugToggle); <ide> no.setSelected(true); <add> <add> Menu colorOption = new Menu("Theme"); <add> <add> ToggleGroup colorToggle = new ToggleGroup(); <add> for (String color : COLORS) { <add> RadioMenuItem radioItem = new RadioMenuItem(color); <add> radioItem.setOnAction(e -> {styleSheetColor = radioItem.getText().toLowerCase(); <add> playScene.getStylesheets().clear(); <add> playScene.getStylesheets().add(DEFAULT_RESOURCE_PACKAGE + styleSheetColor + STYLESHEET);}); <add> radioItem.setToggleGroup(colorToggle); <add> if (color.toLowerCase().equals(styleSheetColor)) radioItem.setSelected(true); <add> colorOption.getItems().add(radioItem); <add> } <ide> myMenus.getMenus().addAll(fileMenu, savedGames, view, option); <ide> fileMenu.getItems().addAll(open, reset, save, close, pause); <ide> view.getItems().addAll(highScore, showHelp); <del> option.getItems().add(debugOption); <add> option.getItems().addAll(debugOption, colorOption); <ide> debugOption.getItems().addAll(yes, no); <ide> topContainer.getChildren().add(myMenus); <add> } <add> <add> public Menu makeColorOptionMenu(ToggleGroup colorToggle) { <add> Menu colorOption = new Menu("Theme"); <add> for (String color : COLORS) { <add> RadioMenuItem radioItem = new RadioMenuItem(color); <add> radioItem.setOnAction(e -> {styleSheetColor = radioItem.getText().toLowerCase(); <add> playScene.getStylesheets().clear(); <add> playScene.getStylesheets().add(DEFAULT_RESOURCE_PACKAGE + styleSheetColor + STYLESHEET);}); <add> radioItem.setToggleGroup(colorToggle); <add> if (color.equals(styleSheetColor)) radioItem.setSelected(true); <add> } <add> return colorOption; <ide> } <ide> <ide> public void makeToolBar() throws ResourceFailedException {
Java
apache-2.0
776aab0bacaa1b0ab5a33c2436ee4e62747253f2
0
boyan-velinov/cf-mta-deploy-service,boyan-velinov/cf-mta-deploy-service,boyan-velinov/cf-mta-deploy-service
package com.sap.cloud.lm.sl.cf.core.helpers; import static java.text.MessageFormat.format; import java.util.Arrays; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.sap.cloud.lm.sl.cf.core.cf.HandlerFactory; import com.sap.cloud.lm.sl.cf.core.dao.ConfigurationEntryDao; import com.sap.cloud.lm.sl.cf.core.helpers.v2.ConfigurationReferencesResolver; import com.sap.cloud.lm.sl.cf.core.message.Messages; import com.sap.cloud.lm.sl.cf.core.model.CloudTarget; import com.sap.cloud.lm.sl.cf.core.model.ConfigurationSubscription; import com.sap.cloud.lm.sl.cf.core.model.ResolvedConfigurationReference; import com.sap.cloud.lm.sl.cf.core.model.SupportedParameters; import com.sap.cloud.lm.sl.cf.core.security.serialization.SecureSerializationFacade; import com.sap.cloud.lm.sl.cf.core.util.ApplicationConfiguration; import com.sap.cloud.lm.sl.cf.core.util.ApplicationURI; import com.sap.cloud.lm.sl.cf.core.validators.parameters.ApplicationNameValidator; import com.sap.cloud.lm.sl.cf.core.validators.parameters.DomainValidator; import com.sap.cloud.lm.sl.cf.core.validators.parameters.HostValidator; import com.sap.cloud.lm.sl.cf.core.validators.parameters.ParameterValidator; import com.sap.cloud.lm.sl.cf.core.validators.parameters.PortValidator; import com.sap.cloud.lm.sl.cf.core.validators.parameters.RestartOnEnvChangeValidator; import com.sap.cloud.lm.sl.cf.core.validators.parameters.RoutesValidator; import com.sap.cloud.lm.sl.cf.core.validators.parameters.ServiceNameValidator; import com.sap.cloud.lm.sl.cf.core.validators.parameters.TasksValidator; import com.sap.cloud.lm.sl.cf.core.validators.parameters.v3.VisibilityValidator; import com.sap.cloud.lm.sl.mta.model.DeploymentDescriptor; import com.sap.cloud.lm.sl.mta.model.Module; import com.sap.cloud.lm.sl.mta.resolvers.NullPropertiesResolverBuilder; import com.sap.cloud.lm.sl.mta.resolvers.ResolverBuilder; public class MtaDescriptorPropertiesResolver { private static final Logger LOGGER = LoggerFactory.getLogger(MtaDescriptorPropertiesResolver.class); public static final String IDLE_DOMAIN_PLACEHOLDER = "${" + SupportedParameters.IDLE_DOMAIN + "}"; public static final String IDLE_HOST_PLACEHOLDER = "${" + SupportedParameters.IDLE_HOST + "}"; public static final String IDLE_PORT_PLACEHOLDER = "${" + SupportedParameters.IDLE_PORT + "}"; private final SecureSerializationFacade secureSerializer = new SecureSerializationFacade().setFormattedOutput(true); private final HandlerFactory handlerFactory; private final ConfigurationEntryDao dao; private final CloudTarget cloudTarget; private final String currentSpaceId; private List<ConfigurationSubscription> subscriptions; private final ApplicationConfiguration configuration; private final boolean useNamespaces; private final boolean useNamespacesForServices; private final boolean reserveTemporaryRoute; public MtaDescriptorPropertiesResolver(HandlerFactory handlerFactory, ConfigurationEntryDao dao, CloudTarget cloudTarget, String currentSpaceId, ApplicationConfiguration configuration, boolean useNamespaces, boolean useNamespacesForServices, boolean reserveTemporaryRoute) { this.handlerFactory = handlerFactory; this.dao = dao; this.cloudTarget = cloudTarget; this.currentSpaceId = currentSpaceId; this.configuration = configuration; this.useNamespaces = useNamespaces; this.useNamespacesForServices = useNamespacesForServices; this.reserveTemporaryRoute = reserveTemporaryRoute; } public List<ParameterValidator> getValidatorsList() { return Arrays.asList(new PortValidator(), new HostValidator(), new DomainValidator(), new RoutesValidator(), new TasksValidator(), new VisibilityValidator(), new RestartOnEnvChangeValidator()); } public DeploymentDescriptor resolve(DeploymentDescriptor descriptor) { descriptor = correctEntityNames(descriptor); // Resolve placeholders in parameters: descriptor = handlerFactory .getDescriptorPlaceholderResolver(descriptor, new NullPropertiesResolverBuilder(), new ResolverBuilder(), SupportedParameters.SINGULAR_PLURAL_MAPPING) .resolve(); if (reserveTemporaryRoute) { // temporary placeholders should be set at this point, since they are need for provides/requires placeholder resolution editRoutesSetTemporaryPlaceholders(descriptor); LOGGER.debug(format(Messages.DEPLOYMENT_DESCRIPTOR_IDLE_ROUTES, secureSerializer.toJson(descriptor))); // Resolve again due to new temporary routes descriptor = handlerFactory .getDescriptorPlaceholderResolver(descriptor, new NullPropertiesResolverBuilder(), new ResolverBuilder(), SupportedParameters.SINGULAR_PLURAL_MAPPING) .resolve(); } List<ParameterValidator> validatorsList = getValidatorsList(); descriptor = handlerFactory.getDescriptorParametersValidator(descriptor, validatorsList) .validate(); LOGGER.debug(format(Messages.DEPLOYMENT_DESCRIPTOR_AFTER_PARAMETER_CORRECTION, secureSerializer.toJson(descriptor))); // Resolve placeholders in properties: descriptor = handlerFactory .getDescriptorPlaceholderResolver(descriptor, new ResolverBuilder(), new NullPropertiesResolverBuilder(), SupportedParameters.SINGULAR_PLURAL_MAPPING) .resolve(); DeploymentDescriptor descriptorWithUnresolvedReferences = DeploymentDescriptor.copyOf(descriptor); ConfigurationReferencesResolver resolver = handlerFactory.getConfigurationReferencesResolver(descriptor, dao, cloudTarget, configuration); resolver.resolve(descriptor); LOGGER.debug(format(Messages.DEPLOYMENT_DESCRIPTOR_AFTER_CROSS_MTA_DEPENDENCY_RESOLUTION, secureSerializer.toJson(descriptor))); subscriptions = createSubscriptions(descriptorWithUnresolvedReferences, resolver.getResolvedReferences()); LOGGER.debug(format(Messages.SUBSCRIPTIONS, secureSerializer.toJson(subscriptions))); descriptor = handlerFactory .getDescriptorReferenceResolver(descriptor, new ResolverBuilder(), new ResolverBuilder(), new ResolverBuilder()) .resolve(); LOGGER.debug(format(Messages.RESOLVED_DEPLOYMENT_DESCRIPTOR, secureSerializer.toJson(descriptor))); descriptor = handlerFactory.getDescriptorParametersValidator(descriptor, validatorsList, true) .validate(); return descriptor; } private DeploymentDescriptor correctEntityNames(DeploymentDescriptor descriptor) { List<ParameterValidator> correctors = Arrays.asList(new ApplicationNameValidator(descriptor.getId(), useNamespaces), new ServiceNameValidator(descriptor.getId(), useNamespaces, useNamespacesForServices)); return handlerFactory.getDescriptorParametersValidator(descriptor, correctors) .validate(); } private void editRoutesSetTemporaryPlaceholders(DeploymentDescriptor descriptor) { for (Module module : descriptor.getModules()) { Map<String, Object> moduleParameters = module.getParameters(); if (moduleParameters.get(SupportedParameters.ROUTES) == null) { continue; } List<Map<String, Object>> routes = RoutesValidator.applyRoutesType(moduleParameters.get(SupportedParameters.ROUTES)); for (Map<String, Object> route : routes) { Object routeValue = route.get(SupportedParameters.ROUTE); if (routeValue != null && routeValue instanceof String) { route.put(SupportedParameters.ROUTE, replacePartsWithIdlePlaceholders((String) routeValue)); } } } } private String replacePartsWithIdlePlaceholders(String uriString) { ApplicationURI uri = new ApplicationURI(uriString); uri.setDomain(IDLE_DOMAIN_PLACEHOLDER); if (uri.isHostBased()) { uri.setHost(IDLE_HOST_PLACEHOLDER); } else { uri.setUnparsablePort(IDLE_PORT_PLACEHOLDER); } return uri.toString(); } private List<ConfigurationSubscription> createSubscriptions(DeploymentDescriptor descriptorWithUnresolvedReferences, Map<String, ResolvedConfigurationReference> resolvedResources) { return handlerFactory.getConfigurationSubscriptionFactory() .create(descriptorWithUnresolvedReferences, resolvedResources, currentSpaceId); } public List<ConfigurationSubscription> getSubscriptions() { return subscriptions; } }
com.sap.cloud.lm.sl.cf.core/src/main/java/com/sap/cloud/lm/sl/cf/core/helpers/MtaDescriptorPropertiesResolver.java
package com.sap.cloud.lm.sl.cf.core.helpers; import static java.text.MessageFormat.format; import java.util.Arrays; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.sap.cloud.lm.sl.cf.core.cf.HandlerFactory; import com.sap.cloud.lm.sl.cf.core.dao.ConfigurationEntryDao; import com.sap.cloud.lm.sl.cf.core.helpers.v2.ConfigurationReferencesResolver; import com.sap.cloud.lm.sl.cf.core.message.Messages; import com.sap.cloud.lm.sl.cf.core.model.CloudTarget; import com.sap.cloud.lm.sl.cf.core.model.ConfigurationSubscription; import com.sap.cloud.lm.sl.cf.core.model.ResolvedConfigurationReference; import com.sap.cloud.lm.sl.cf.core.model.SupportedParameters; import com.sap.cloud.lm.sl.cf.core.security.serialization.SecureSerializationFacade; import com.sap.cloud.lm.sl.cf.core.util.ApplicationConfiguration; import com.sap.cloud.lm.sl.cf.core.util.ApplicationURI; import com.sap.cloud.lm.sl.cf.core.validators.parameters.ApplicationNameValidator; import com.sap.cloud.lm.sl.cf.core.validators.parameters.DomainValidator; import com.sap.cloud.lm.sl.cf.core.validators.parameters.HostValidator; import com.sap.cloud.lm.sl.cf.core.validators.parameters.ParameterValidator; import com.sap.cloud.lm.sl.cf.core.validators.parameters.PortValidator; import com.sap.cloud.lm.sl.cf.core.validators.parameters.RestartOnEnvChangeValidator; import com.sap.cloud.lm.sl.cf.core.validators.parameters.RoutesValidator; import com.sap.cloud.lm.sl.cf.core.validators.parameters.ServiceNameValidator; import com.sap.cloud.lm.sl.cf.core.validators.parameters.TasksValidator; import com.sap.cloud.lm.sl.cf.core.validators.parameters.v3.VisibilityValidator; import com.sap.cloud.lm.sl.mta.model.DeploymentDescriptor; import com.sap.cloud.lm.sl.mta.model.Module; import com.sap.cloud.lm.sl.mta.resolvers.NullPropertiesResolverBuilder; import com.sap.cloud.lm.sl.mta.resolvers.ResolverBuilder; public class MtaDescriptorPropertiesResolver { private static final Logger LOGGER = LoggerFactory.getLogger(MtaDescriptorPropertiesResolver.class); public static String IDLE_DOMAIN_PLACEHOLDER = "${" + SupportedParameters.IDLE_DOMAIN + "}"; public static String IDLE_HOST_PLACEHOLDER = "${" + SupportedParameters.IDLE_HOST + "}"; public static String IDLE_PORT_PLACEHOLDER = "${" + SupportedParameters.IDLE_PORT + "}"; private final SecureSerializationFacade secureSerializer = new SecureSerializationFacade().setFormattedOutput(true); private final HandlerFactory handlerFactory; private final ConfigurationEntryDao dao; private final CloudTarget cloudTarget; private final String currentSpaceId; private List<ConfigurationSubscription> subscriptions; private final ApplicationConfiguration configuration; private final boolean useNamespaces; private final boolean useNamespacesForServices; private final boolean reserveTemporaryRoute; public MtaDescriptorPropertiesResolver(HandlerFactory handlerFactory, ConfigurationEntryDao dao, CloudTarget cloudTarget, String currentSpaceId, ApplicationConfiguration configuration, boolean useNamespaces, boolean useNamespacesForServices, boolean reserveTemporaryRoute) { this.handlerFactory = handlerFactory; this.dao = dao; this.cloudTarget = cloudTarget; this.currentSpaceId = currentSpaceId; this.configuration = configuration; this.useNamespaces = useNamespaces; this.useNamespacesForServices = useNamespacesForServices; this.reserveTemporaryRoute = reserveTemporaryRoute; } public List<ParameterValidator> getValidatorsList() { return Arrays.asList(new PortValidator(), new HostValidator(), new DomainValidator(), new RoutesValidator(), new TasksValidator(), new VisibilityValidator(), new RestartOnEnvChangeValidator()); } public DeploymentDescriptor resolve(DeploymentDescriptor descriptor) { descriptor = correctEntityNames(descriptor); // Resolve placeholders in parameters: descriptor = handlerFactory .getDescriptorPlaceholderResolver(descriptor, new NullPropertiesResolverBuilder(), new ResolverBuilder(), SupportedParameters.SINGULAR_PLURAL_MAPPING) .resolve(); if (reserveTemporaryRoute) { // temporary placeholders should be set at this point, since they are need for provides/requires placeholder resolution editRoutesSetTemporaryPlaceholders(descriptor); LOGGER.debug(format(Messages.DEPLOYMENT_DESCRIPTOR_IDLE_ROUTES, secureSerializer.toJson(descriptor))); // Resolve again due to new temporary routes descriptor = handlerFactory .getDescriptorPlaceholderResolver(descriptor, new NullPropertiesResolverBuilder(), new ResolverBuilder(), SupportedParameters.SINGULAR_PLURAL_MAPPING) .resolve(); } List<ParameterValidator> validatorsList = getValidatorsList(); descriptor = handlerFactory.getDescriptorParametersValidator(descriptor, validatorsList) .validate(); LOGGER.debug(format(Messages.DEPLOYMENT_DESCRIPTOR_AFTER_PARAMETER_CORRECTION, secureSerializer.toJson(descriptor))); // Resolve placeholders in properties: descriptor = handlerFactory .getDescriptorPlaceholderResolver(descriptor, new ResolverBuilder(), new NullPropertiesResolverBuilder(), SupportedParameters.SINGULAR_PLURAL_MAPPING) .resolve(); DeploymentDescriptor descriptorWithUnresolvedReferences = DeploymentDescriptor.copyOf(descriptor); ConfigurationReferencesResolver resolver = handlerFactory.getConfigurationReferencesResolver(descriptor, dao, cloudTarget, configuration); resolver.resolve(descriptor); LOGGER.debug(format(Messages.DEPLOYMENT_DESCRIPTOR_AFTER_CROSS_MTA_DEPENDENCY_RESOLUTION, secureSerializer.toJson(descriptor))); subscriptions = createSubscriptions(descriptorWithUnresolvedReferences, resolver.getResolvedReferences()); LOGGER.debug(format(Messages.SUBSCRIPTIONS, secureSerializer.toJson(subscriptions))); descriptor = handlerFactory .getDescriptorReferenceResolver(descriptor, new ResolverBuilder(), new ResolverBuilder(), new ResolverBuilder()) .resolve(); LOGGER.debug(format(Messages.RESOLVED_DEPLOYMENT_DESCRIPTOR, secureSerializer.toJson(descriptor))); descriptor = handlerFactory.getDescriptorParametersValidator(descriptor, validatorsList, true) .validate(); return descriptor; } private DeploymentDescriptor correctEntityNames(DeploymentDescriptor descriptor) { List<ParameterValidator> correctors = Arrays.asList(new ApplicationNameValidator(descriptor.getId(), useNamespaces), new ServiceNameValidator(descriptor.getId(), useNamespaces, useNamespacesForServices)); return handlerFactory.getDescriptorParametersValidator(descriptor, correctors) .validate(); } private void editRoutesSetTemporaryPlaceholders(DeploymentDescriptor descriptor) { for (Module module : descriptor.getModules()) { Map<String, Object> moduleParameters = module.getParameters(); if (moduleParameters.get(SupportedParameters.ROUTES) == null) { continue; } List<Map<String, Object>> routes = RoutesValidator.applyRoutesType(moduleParameters.get(SupportedParameters.ROUTES)); for (Map<String, Object> route : routes) { Object routeValue = route.get(SupportedParameters.ROUTE); if (routeValue != null && routeValue instanceof String) { route.put(SupportedParameters.ROUTE, replacePartsWithIdlePlaceholders((String) routeValue)); } } } } private String replacePartsWithIdlePlaceholders(String uriString) { ApplicationURI uri = new ApplicationURI(uriString); uri.setDomain(IDLE_DOMAIN_PLACEHOLDER); if (uri.isHostBased()) { uri.setHost(IDLE_HOST_PLACEHOLDER); } else { uri.setUnparsablePort(IDLE_PORT_PLACEHOLDER); } return uri.toString(); } private List<ConfigurationSubscription> createSubscriptions(DeploymentDescriptor descriptorWithUnresolvedReferences, Map<String, ResolvedConfigurationReference> resolvedResources) { return handlerFactory.getConfigurationSubscriptionFactory() .create(descriptorWithUnresolvedReferences, resolvedResources, currentSpaceId); } public List<ConfigurationSubscription> getSubscriptions() { return subscriptions; } }
Fix some sonar issues
com.sap.cloud.lm.sl.cf.core/src/main/java/com/sap/cloud/lm/sl/cf/core/helpers/MtaDescriptorPropertiesResolver.java
Fix some sonar issues
<ide><path>om.sap.cloud.lm.sl.cf.core/src/main/java/com/sap/cloud/lm/sl/cf/core/helpers/MtaDescriptorPropertiesResolver.java <ide> <ide> private static final Logger LOGGER = LoggerFactory.getLogger(MtaDescriptorPropertiesResolver.class); <ide> <del> public static String IDLE_DOMAIN_PLACEHOLDER = "${" + SupportedParameters.IDLE_DOMAIN + "}"; <del> public static String IDLE_HOST_PLACEHOLDER = "${" + SupportedParameters.IDLE_HOST + "}"; <del> public static String IDLE_PORT_PLACEHOLDER = "${" + SupportedParameters.IDLE_PORT + "}"; <add> public static final String IDLE_DOMAIN_PLACEHOLDER = "${" + SupportedParameters.IDLE_DOMAIN + "}"; <add> public static final String IDLE_HOST_PLACEHOLDER = "${" + SupportedParameters.IDLE_HOST + "}"; <add> public static final String IDLE_PORT_PLACEHOLDER = "${" + SupportedParameters.IDLE_PORT + "}"; <ide> <ide> private final SecureSerializationFacade secureSerializer = new SecureSerializationFacade().setFormattedOutput(true); <ide>
Java
apache-2.0
error: pathspec 'src/db/ExerciseFetch.java' did not match any file(s) known to git
49dbd75ec08236259246d615f97a474ef93f42ea
1
mariusmoe/datamod
package db; import gui.Exercise; import java.sql.*; import java.util.ArrayList; import java.util.Collection; /** * Created by Hallgeir on 14.03.2016. */ public class ExerciseFetch { public ExerciseFetch(){ } private Collection<Exercise> exercises = new ArrayList<Exercise>(); private static Connection connect = null; private static Statement statement = null; static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost:3306/dag"; static final String USER = "root"; static final String PASS = null; public Collection<Exercise> getExercises() { return exercises; } private void addExercise(Exercise ex){ exercises.add(ex); } public void readExercises(String name){ try { Class.forName(JDBC_DRIVER); System.out.println("Connecting to a selected database..."); connect = DriverManager.getConnection(DB_URL, USER, PASS); System.out.println("Connected database successfully..."); PreparedStatement prstmnt = null; String get = "SELECT * from dag.ovelse"; prstmnt = connect.prepareStatement(get); ResultSet set = prstmnt.executeQuery(); while (set.next()){ String exerciseName = set.getString("navn"); String description = set.getString("beskrivelse"); String alternative = set.getString("ovelse_navn"); String category = set.getString("kategori_knavn"); addExercise(new Exercise(exerciseName, description, alternative, category)); } set.close(); } catch (SQLException se) { se.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (statement != null) connect.close(); } catch (SQLException se) { se.printStackTrace(); } } } }
src/db/ExerciseFetch.java
Lagde klassen ExerciseFetch, som kan instansieres for å hente øvelser fra databasen og lagre de i en Collection med Exercise-objekter
src/db/ExerciseFetch.java
Lagde klassen ExerciseFetch, som kan instansieres for å hente øvelser fra databasen og lagre de i en Collection med Exercise-objekter
<ide><path>rc/db/ExerciseFetch.java <add>package db; <add> <add>import gui.Exercise; <add> <add>import java.sql.*; <add>import java.util.ArrayList; <add>import java.util.Collection; <add> <add>/** <add> * Created by Hallgeir on 14.03.2016. <add> */ <add>public class ExerciseFetch { <add> <add> public ExerciseFetch(){ <add> <add> } <add> <add> private Collection<Exercise> exercises = new ArrayList<Exercise>(); <add> <add> private static Connection connect = null; <add> private static Statement statement = null; <add> <add> static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; <add> static final String DB_URL = "jdbc:mysql://localhost:3306/dag"; <add> static final String USER = "root"; <add> static final String PASS = null; <add> <add> <add> public Collection<Exercise> getExercises() { <add> return exercises; <add> } <add> <add> private void addExercise(Exercise ex){ <add> exercises.add(ex); <add> } <add> <add> <add> public void readExercises(String name){ <add> <add> <add> try { <add> Class.forName(JDBC_DRIVER); <add> System.out.println("Connecting to a selected database..."); <add> connect = DriverManager.getConnection(DB_URL, USER, PASS); <add> System.out.println("Connected database successfully..."); <add> PreparedStatement prstmnt = null; <add> String get = "SELECT * from dag.ovelse"; <add> prstmnt = connect.prepareStatement(get); <add> ResultSet set = prstmnt.executeQuery(); <add> while (set.next()){ <add> String exerciseName = set.getString("navn"); <add> String description = set.getString("beskrivelse"); <add> String alternative = set.getString("ovelse_navn"); <add> String category = set.getString("kategori_knavn"); <add> addExercise(new Exercise(exerciseName, description, alternative, category)); <add> <add> <add> } <add> set.close(); <add> <add> <add> <add> <add> <add> <add> } catch (SQLException se) { <add> se.printStackTrace(); <add> } catch (Exception e) { <add> e.printStackTrace(); <add> } finally { <add> try { <add> if (statement != null) <add> connect.close(); <add> } catch (SQLException se) { <add> se.printStackTrace(); <add> } <add> } <add> <add> <add> } <add>}
Java
epl-1.0
b1f7bb533e0dc655ada6745db5e704b054596ef5
0
ESSICS/cs-studio,ESSICS/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,css-iter/cs-studio,css-iter/cs-studio,css-iter/cs-studio,css-iter/cs-studio,ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio,ESSICS/cs-studio,ControlSystemStudio/cs-studio,ESSICS/cs-studio,ControlSystemStudio/cs-studio,css-iter/cs-studio,css-iter/cs-studio,ControlSystemStudio/cs-studio,ESSICS/cs-studio,ControlSystemStudio/cs-studio,ESSICS/cs-studio
package org.csstudio.opibuilder.widgets.model; import org.csstudio.opibuilder.model.AbstractPVWidgetModel; import org.csstudio.opibuilder.properties.BooleanProperty; import org.csstudio.opibuilder.properties.ColorProperty; import org.csstudio.opibuilder.properties.ComboProperty; import org.csstudio.opibuilder.properties.DoubleProperty; import org.csstudio.opibuilder.properties.FontProperty; import org.csstudio.opibuilder.properties.IntegerProperty; import org.csstudio.opibuilder.properties.NameDefinedCategory; import org.csstudio.opibuilder.properties.PVValueProperty; import org.csstudio.opibuilder.properties.StringProperty; import org.csstudio.opibuilder.properties.WidgetPropertyCategory; import org.csstudio.opibuilder.util.OPIFont; import org.csstudio.platform.ui.util.CustomMediaFactory; import org.csstudio.swt.xygraph.dataprovider.CircularBufferDataProvider.PlotMode; import org.csstudio.swt.xygraph.dataprovider.CircularBufferDataProvider.UpdateMode; import org.csstudio.swt.xygraph.figures.XYGraph; import org.csstudio.swt.xygraph.figures.Trace.PointStyle; import org.csstudio.swt.xygraph.figures.Trace.TraceType; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.RGB; /** * The model for XYGraph * @author Xihui Chen */ public class XYGraphModel extends AbstractPVWidgetModel { public enum AxisProperty{ Y_AXIS("y_axis", "Y Axis"), VISIBLE("visible", "Visible"), PRIMARY("left_bottom_side", "Left/Bottom Side"), TITLE("axis_title", "Axis Title"), TITLE_FONT("title_font", "Title Font"), AXIS_COLOR("axis_color", "Axis Color"), AUTO_SCALE("auto_scale", "Auto Scale"), AUTO_SCALE_THRESHOLD("auto_scale_threshold", "Auto Scale Threshold"), LOG("log_scale", "Log Scale"), MAX("maximum", "Maximum"), MIN("minimum", "Minimum"), TIME_FORMAT("time_format", "Time Format"), SHOW_GRID("show_grid", "Show Grid"), GRID_COLOR("grid_color", "Grid Color"), DASH_GRID("dash_grid_line", "Dash Grid Line"); public String propIDPre; public String description; private AxisProperty(String propertyIDPrefix, String description) { this.propIDPre = propertyIDPrefix; this.description = description; } @Override public String toString() { return description; } } public enum TraceProperty{ NAME("name", "Name"), PLOTMODE("plot_mode", "Plot Mode"), BUFFER_SIZE("buffer_size", "Buffer Size"), UPDATE_DELAY("update_delay", "Update Delay"), //TRIGGER_VALUE("trigger_value", "Trigger Value"), //CLEAR_TRACE("clear_trace", "Clear Plot History"), XPV("x_pv", "X PV"), YPV("y_pv", "Y PV"), XPV_VALUE("x_pv_value", "X PV Value"), YPV_VALUE("y_pv_value", "Y PV Value"), CHRONOLOGICAL("chronological", "Chronological"), TRACE_COLOR("trace_color","Trace Color"), XAXIS_INDEX("x_axis_index", "X Axis Index"), YAXIS_INDEX("y_axis_index", "Y Axis Index"), TRACE_TYPE("trace_type", "Trace Type"), LINE_WIDTH("line_width", "Line Width"), POINT_STYLE("point_style", "Point Style"), POINT_SIZE("point_size", "Point Size"), ANTI_ALIAS("anti_alias", "Anti Alias"), UPDATE_MODE("update_mode", "Update Mode"), CONCATENATE_DATA("concatenate_data", "Concatenate Data"); public String propIDPre; public String description; private TraceProperty(String propertyIDPrefix, String description) { this.propIDPre = propertyIDPrefix; this.description = description; } @Override public String toString() { return description; } } public final static String[] TIME_FORMAT_ARRAY = new String[]{ "None", "yyyy-MM-dd\nHH:mm:ss", "yyyy-MM-dd\nHH:mm:ss.SSS", "HH:mm:ss", "HH:mm:ss.SSS", "HH:mm", "yyyy-MM-dd", "MMMMM d"}; /** The ID of the title property. */ public static final String PROP_TITLE = "title"; //$NON-NLS-1$ /** The ID of the title font property. */ public static final String PROP_TITLE_FONT = "title_font"; //$NON-NLS-1$ /** The ID of the show legend property. */ public static final String PROP_SHOW_LEGEND = "show_legend"; //$NON-NLS-1$ /** The ID of the show plot area border property. */ public static final String PROP_SHOW_PLOTAREA_BORDER = "show_plot_area_border"; //$NON-NLS-1$ /** The ID of the plot area background color property.*/ public static final String PROP_PLOTAREA_BACKCOLOR = "plot_area_background_color"; //$NON-NLS-1$ /** The ID of the transparent property. */ public static final String PROP_TRANSPARENT = "transparent"; //$NON-NLS-1$ /** The ID of the number of axes property. */ public static final String PROP_AXIS_COUNT = "axis_count"; //$NON-NLS-1$ /** The ID of the number of axes property. */ public static final String PROP_TRACE_COUNT = "trace_count"; //$NON-NLS-1$ /** The ID of the show toolbar property. */ public static final String PROP_SHOW_TOOLBAR = "show_toolbar"; //$NON-NLS-1$ public static final String PROP_TRIGGER_PV = "trigger_pv"; //$NON-NLS-1$ public static final String PROP_TRIGGER_PV_VALUE = "trigger_pv_value"; //$NON-NLS-1$ /** The default color of the plot area background color property. */ private static final RGB DEFAULT_PLOTAREA_BACKCOLOR = new RGB(255,255,255); /** The default color of the axis color property. */ private static final RGB DEFAULT_AXIS_COLOR = new RGB(0,0,0); /** The default color of the grid color property. */ private static final RGB DEFAULT_GRID_COLOR = new RGB(200,200,200); /** The default color of the trace color property. */ private static final RGB DEFAULT_TRACE_COLOR = new RGB(255,0,0); /** The default value of the minimum property. */ private static final double DEFAULT_MIN = 0; /** The default value of the maximum property. */ private static final double DEFAULT_MAX = 100; /** The default value of the buffer size property. */ private static final int DEFAULT_BUFFER_SIZE = 100; /** The maximum allowed buffer size. */ private static final int MAX_BUFFER_SIZE = 10000000; public static final int MAX_AXES_AMOUNT = 4; public static final int MAX_TRACES_AMOUNT = 20; public final static String[] AXES_ARRAY = new String[MAX_AXES_AMOUNT]; { AXES_ARRAY[0] = "Primary X Axis (0)"; AXES_ARRAY[1] = "Primary Y Axis (1)"; for(int i=2; i<MAX_AXES_AMOUNT; i++) AXES_ARRAY[i] = "Secondary Axis (" + i + ")"; } /** * The ID of this widget model. */ public static final String ID = "org.csstudio.opibuilder.widgets.xyGraph"; //$NON-NLS-1$ /** The default value of the height property. */ private static final int DEFAULT_HEIGHT = 250; /** The default value of the width property. */ private static final int DEFAULT_WIDTH = 400; public XYGraphModel() { setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); setForegroundColor(CustomMediaFactory.COLOR_BLUE); setPropertyValue(PROP_PVNAME, "$(trace_0_y_pv)"); //$NON-NLS-1$ setTooltip("$(trace_0_y_pv)\n$(trace_0_y_pv_value)"); } @Override protected void configureProperties() { addPVProperty(new StringProperty(PROP_TRIGGER_PV, "Trigger PV", WidgetPropertyCategory.Behavior, ""), new PVValueProperty(PROP_TRIGGER_PV_VALUE, null)); addProperty(new StringProperty(PROP_TITLE, "Title", WidgetPropertyCategory.Display, "")); addProperty(new FontProperty(PROP_TITLE_FONT, "Title Font", WidgetPropertyCategory.Display,new FontData("Arial", 12, SWT.BOLD))); //$NON-NLS-1$ addProperty(new BooleanProperty(PROP_SHOW_LEGEND, "Show Legend", WidgetPropertyCategory.Display,true)); addProperty(new BooleanProperty(PROP_SHOW_PLOTAREA_BORDER, "Show Plot Area Border", WidgetPropertyCategory.Display,false)); addProperty(new BooleanProperty(PROP_SHOW_TOOLBAR, "Show Toolbar", WidgetPropertyCategory.Display,true)); addProperty(new ColorProperty(PROP_PLOTAREA_BACKCOLOR, "Plot Area Background Color", WidgetPropertyCategory.Display,DEFAULT_PLOTAREA_BACKCOLOR)); addProperty(new BooleanProperty(PROP_TRANSPARENT, "Transparent", WidgetPropertyCategory.Display,false)); addProperty(new IntegerProperty(PROP_AXIS_COUNT, "Axis Count", WidgetPropertyCategory.Behavior,2, 2, MAX_AXES_AMOUNT)); addProperty(new IntegerProperty(PROP_TRACE_COUNT, "Trace Count", WidgetPropertyCategory.Behavior, 1, 0, MAX_TRACES_AMOUNT)); addAxisProperties(); addTraceProperties(); setPropertyVisible(PROP_PVNAME, false); } private void addAxisProperties(){ for(int i=0; i < MAX_AXES_AMOUNT; i++){ WidgetPropertyCategory category; if(i ==0) category = new NameDefinedCategory("Primary X Axis (0)"); else if(i == 1) category = new NameDefinedCategory("Primary Y Axis (1)"); else category = new NameDefinedCategory("Secondary Axis (" + i + ")"); for(AxisProperty axisProperty : AxisProperty.values()) addAxisProperty(axisProperty, i, category); } } private void addAxisProperty(AxisProperty axisProperty, int axisIndex, WidgetPropertyCategory category){ String propID = makeAxisPropID(axisProperty.propIDPre, axisIndex); switch (axisProperty) { case Y_AXIS: if(axisIndex < 2) break; addProperty(new BooleanProperty(propID, axisProperty.toString(), category, true)); break; case PRIMARY: if(axisIndex < 2) break; addProperty(new BooleanProperty(propID, axisProperty.toString(), category, true)); break; case TITLE: addProperty(new StringProperty(propID, axisProperty.toString(), category, category.toString())); break; case TITLE_FONT: addProperty(new FontProperty(propID, axisProperty.toString(), category, new FontData("Arial", 9, SWT.BOLD))); break; case AXIS_COLOR: addProperty(new ColorProperty(propID, axisProperty.toString(), category, DEFAULT_AXIS_COLOR)); break; case AUTO_SCALE_THRESHOLD: addProperty(new DoubleProperty(propID, axisProperty.toString(), category,0, 0, 1)); break; case LOG: addProperty(new BooleanProperty(propID, axisProperty.toString(), category,false)); break; case AUTO_SCALE: case SHOW_GRID: case DASH_GRID: addProperty(new BooleanProperty(propID, axisProperty.toString(), category, true)); break; case MAX: addProperty(new DoubleProperty(propID, axisProperty.toString(), category, DEFAULT_MAX)); break; case MIN: addProperty(new DoubleProperty(propID, axisProperty.toString(), category,DEFAULT_MIN)); break; case TIME_FORMAT: addProperty(new ComboProperty(propID, axisProperty.toString(), category, TIME_FORMAT_ARRAY, 0)); break; case GRID_COLOR: addProperty(new ColorProperty(propID, axisProperty.toString(), category,DEFAULT_GRID_COLOR)); break; case VISIBLE: addProperty(new BooleanProperty(propID, axisProperty.toString(), category, true)); break; default: break; } } public static String makeAxisPropID(String propIDPre, int index){ return "axis_" + index + "_" + propIDPre; //$NON-NLS-1$ //$NON-NLS-2$ } private void addTraceProperties(){ for(int i=0; i < MAX_TRACES_AMOUNT; i++){ for(TraceProperty traceProperty : TraceProperty.values()) addTraceProperty(traceProperty, i); } } private void addTraceProperty(TraceProperty traceProperty, int traceIndex){ String propID = makeTracePropID(traceProperty.propIDPre, traceIndex); WidgetPropertyCategory category = new NameDefinedCategory("Trace " + traceIndex); switch (traceProperty) { case NAME: addProperty(new StringProperty(propID, traceProperty.toString(), category, category.toString())); break; case ANTI_ALIAS: case CHRONOLOGICAL: addProperty(new BooleanProperty(propID, traceProperty.toString(), category, true)); break; case BUFFER_SIZE: addProperty(new IntegerProperty(propID, traceProperty.toString(), category, DEFAULT_BUFFER_SIZE, 1, MAX_BUFFER_SIZE)); break; case CONCATENATE_DATA: addProperty(new BooleanProperty(propID, traceProperty.toString(), category, true)); break; //case CLEAR_TRACE: // addProperty(new BooleanProperty(propID, traceProperty.toString(), category, false)); // break; case LINE_WIDTH: addProperty(new IntegerProperty(propID, traceProperty.toString(), category, 1, 1, 100)); break; case PLOTMODE: addProperty(new ComboProperty(propID, traceProperty.toString(), category, PlotMode.stringValues(), 0)); break; case POINT_SIZE: addProperty(new IntegerProperty(propID, traceProperty.toString(), category, 4, 1, 200)); break; case POINT_STYLE: addProperty(new ComboProperty(propID, traceProperty.toString(), category, PointStyle.stringValues(), 0)); break; case TRACE_COLOR: addProperty(new ColorProperty(propID, traceProperty.toString(), category, traceIndex < XYGraph.DEFAULT_TRACES_COLOR.length? XYGraph.DEFAULT_TRACES_COLOR[traceIndex].getRGB() : DEFAULT_TRACE_COLOR)); break; case TRACE_TYPE: addProperty(new ComboProperty(propID, traceProperty.toString(), category, TraceType.stringValues(), 0)); break; // case TRIGGER_VALUE: // addProperty(new DoubleProperty(propID, traceProperty.toString(), category, 0)); // break; case UPDATE_DELAY: addProperty(new IntegerProperty(propID, traceProperty.toString(), category, 100, 0, 655350)); break; case UPDATE_MODE: addProperty(new ComboProperty(propID, traceProperty.toString(), category, UpdateMode.stringValues(), 0)); break; case XAXIS_INDEX: addProperty(new ComboProperty(propID, traceProperty.toString(), category, AXES_ARRAY, 0)); break; case XPV: addPVProperty(new StringProperty(propID, traceProperty.toString(), category, ""), new PVValueProperty(makeTracePropID(TraceProperty.XPV_VALUE.propIDPre, traceIndex), null)); break; case YPV: addPVProperty(new StringProperty(propID, traceProperty.toString(), category, ""), new PVValueProperty(makeTracePropID(TraceProperty.YPV_VALUE.propIDPre, traceIndex), null)); break; case YAXIS_INDEX: addProperty(new ComboProperty(propID, traceProperty.toString(), category, AXES_ARRAY, 1)); break; default: break; } } public static String makeTracePropID(String propIDPre, int index){ return "trace_" +index + "_" + propIDPre; //$NON-NLS-1$ //$NON-NLS-2$ } /** * @return the title */ public String getTitle() { return (String) getProperty(PROP_TITLE).getPropertyValue(); } /** * Return the title font. * * @return The title font. */ public OPIFont getTitleFont() { return (OPIFont) getProperty(PROP_TITLE_FONT).getPropertyValue(); } /** * @return true if the plot area border should be shown, false otherwise */ public boolean isShowPlotAreaBorder() { return (Boolean) getProperty(PROP_SHOW_PLOTAREA_BORDER).getPropertyValue(); } /** * @return the plot area background color */ public RGB getPlotAreaBackColor() { return getRGBFromColorProperty(PROP_PLOTAREA_BACKCOLOR); } /** * @return true if the XY Graph is transparent, false otherwise */ public boolean isTransprent() { return (Boolean) getProperty(PROP_TRANSPARENT).getPropertyValue(); } /** * @return true if the legend should be shown, false otherwise */ public boolean isShowLegend() { return (Boolean) getProperty(PROP_SHOW_LEGEND).getPropertyValue(); } /** * @return true if the legend should be shown, false otherwise */ public boolean isShowToolbar() { return (Boolean) getProperty(PROP_SHOW_TOOLBAR).getPropertyValue(); } /** * @return The number of axes. */ public int getAxesAmount() { return (Integer) getProperty(PROP_AXIS_COUNT).getPropertyValue(); } /** * @return The number of traces. */ public int getTracesAmount() { return (Integer) getProperty(PROP_TRACE_COUNT).getPropertyValue(); } @Override public String getTypeID() { return ID; } }
applications/plugins/org.csstudio.opibuilder.widgets/src/org/csstudio/opibuilder/widgets/model/XYGraphModel.java
package org.csstudio.opibuilder.widgets.model; import org.csstudio.opibuilder.model.AbstractPVWidgetModel; import org.csstudio.opibuilder.properties.BooleanProperty; import org.csstudio.opibuilder.properties.ColorProperty; import org.csstudio.opibuilder.properties.ComboProperty; import org.csstudio.opibuilder.properties.DoubleProperty; import org.csstudio.opibuilder.properties.FontProperty; import org.csstudio.opibuilder.properties.IntegerProperty; import org.csstudio.opibuilder.properties.NameDefinedCategory; import org.csstudio.opibuilder.properties.PVValueProperty; import org.csstudio.opibuilder.properties.StringProperty; import org.csstudio.opibuilder.properties.WidgetPropertyCategory; import org.csstudio.opibuilder.util.OPIFont; import org.csstudio.platform.ui.util.CustomMediaFactory; import org.csstudio.swt.xygraph.dataprovider.CircularBufferDataProvider.PlotMode; import org.csstudio.swt.xygraph.dataprovider.CircularBufferDataProvider.UpdateMode; import org.csstudio.swt.xygraph.figures.XYGraph; import org.csstudio.swt.xygraph.figures.Trace.PointStyle; import org.csstudio.swt.xygraph.figures.Trace.TraceType; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.RGB; /** * The model for XYGraph * @author Xihui Chen */ public class XYGraphModel extends AbstractPVWidgetModel { public enum AxisProperty{ Y_AXIS("y_axis", "Y Axis"), VISIBLE("visible", "Visible"), PRIMARY("left_bottom_side", "Left/Bottom Side"), TITLE("axis_title", "Axis Title"), TITLE_FONT("title_font", "Title Font"), AXIS_COLOR("axis_color", "Axis Color"), AUTO_SCALE("auto_scale", "Auto Scale"), AUTO_SCALE_THRESHOLD("auto_scale_threshold", "Auto Scale Threshold"), LOG("log_scale", "Log Scale"), MAX("maximum", "Maximum"), MIN("minimum", "Minimum"), TIME_FORMAT("time_format", "Time Format"), SHOW_GRID("show_grid", "Show Grid"), GRID_COLOR("grid_color", "Grid Color"), DASH_GRID("dash_grid_line", "Dash Grid Line"); public String propIDPre; public String description; private AxisProperty(String propertyIDPrefix, String description) { this.propIDPre = propertyIDPrefix; this.description = description; } @Override public String toString() { return description; } } public enum TraceProperty{ NAME("name", "Name"), PLOTMODE("plot_mode", "Plot Mode"), BUFFER_SIZE("buffer_size", "Buffer Size"), UPDATE_DELAY("update_delay", "Update Delay"), //TRIGGER_VALUE("trigger_value", "Trigger Value"), //CLEAR_TRACE("clear_trace", "Clear Plot History"), XPV("x_pv", "X PV"), YPV("y_pv", "Y PV"), XPV_VALUE("x_pv_value", "X PV Value"), YPV_VALUE("y_pv_value", "Y PV Value"), CHRONOLOGICAL("chronological", "Chronological"), TRACE_COLOR("trace_color","Trace Color"), XAXIS_INDEX("x_axis_index", "X Axis Index"), YAXIS_INDEX("y_axis_index", "Y Axis Index"), TRACE_TYPE("trace_type", "Trace Type"), LINE_WIDTH("line_width", "Line Width"), POINT_STYLE("point_style", "Point Style"), POINT_SIZE("point_size", "Point Size"), ANTI_ALIAS("anti_alias", "Anti Alias"), UPDATE_MODE("update_mode", "Update Mode"), CONCATENATE_DATA("concatenate_data", "Concatenate Data"); public String propIDPre; public String description; private TraceProperty(String propertyIDPrefix, String description) { this.propIDPre = propertyIDPrefix; this.description = description; } @Override public String toString() { return description; } } public final static String[] TIME_FORMAT_ARRAY = new String[]{ "None", "yyyy-MM-dd\nHH:mm:ss", "yyyy-MM-dd\nHH:mm:ss.SSS", "HH:mm:ss", "HH:mm:ss.SSS", "HH:mm", "yyyy-MM-dd", "MMMMM d"}; /** The ID of the title property. */ public static final String PROP_TITLE = "title"; //$NON-NLS-1$ /** The ID of the title font property. */ public static final String PROP_TITLE_FONT = "title_font"; //$NON-NLS-1$ /** The ID of the show legend property. */ public static final String PROP_SHOW_LEGEND = "show_legend"; //$NON-NLS-1$ /** The ID of the show plot area border property. */ public static final String PROP_SHOW_PLOTAREA_BORDER = "show_plot_area_border"; //$NON-NLS-1$ /** The ID of the plot area background color property.*/ public static final String PROP_PLOTAREA_BACKCOLOR = "plot_area_background_color"; //$NON-NLS-1$ /** The ID of the transparent property. */ public static final String PROP_TRANSPARENT = "transparent"; //$NON-NLS-1$ /** The ID of the number of axes property. */ public static final String PROP_AXIS_COUNT = "axis_count"; //$NON-NLS-1$ /** The ID of the number of axes property. */ public static final String PROP_TRACE_COUNT = "trace_count"; //$NON-NLS-1$ /** The ID of the show toolbar property. */ public static final String PROP_SHOW_TOOLBAR = "show_toolbar"; //$NON-NLS-1$ public static final String PROP_TRIGGER_PV = "trigger_pv"; //$NON-NLS-1$ public static final String PROP_TRIGGER_PV_VALUE = "trigger_pv_value"; //$NON-NLS-1$ /** The default color of the plot area background color property. */ private static final RGB DEFAULT_PLOTAREA_BACKCOLOR = new RGB(255,255,255); /** The default color of the axis color property. */ private static final RGB DEFAULT_AXIS_COLOR = new RGB(0,0,0); /** The default color of the grid color property. */ private static final RGB DEFAULT_GRID_COLOR = new RGB(200,200,200); /** The default color of the trace color property. */ private static final RGB DEFAULT_TRACE_COLOR = new RGB(255,0,0); /** The default value of the minimum property. */ private static final double DEFAULT_MIN = 0; /** The default value of the maximum property. */ private static final double DEFAULT_MAX = 100; /** The default value of the buffer size property. */ private static final int DEFAULT_BUFFER_SIZE = 100; /** The maximum allowed buffer size. */ private static final int MAX_BUFFER_SIZE = 10000000; public static final int MAX_AXES_AMOUNT = 4; public static final int MAX_TRACES_AMOUNT = 20; public final static String[] AXES_ARRAY = new String[MAX_AXES_AMOUNT]; { AXES_ARRAY[0] = "Primary X Axis (0)"; AXES_ARRAY[1] = "Primary Y Axis (1)"; for(int i=2; i<MAX_AXES_AMOUNT; i++) AXES_ARRAY[i] = "Secondary Axis (" + i + ")"; } /** * The ID of this widget model. */ public static final String ID = "org.csstudio.opibuilder.widgets.xyGraph"; //$NON-NLS-1$ /** The default value of the height property. */ private static final int DEFAULT_HEIGHT = 250; /** The default value of the width property. */ private static final int DEFAULT_WIDTH = 400; public XYGraphModel() { setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); setForegroundColor(CustomMediaFactory.COLOR_BLUE); setPropertyValue(PROP_PVNAME, "$(trace_0_y_pv)"); //$NON-NLS-1$ } @Override protected void configureProperties() { addPVProperty(new StringProperty(PROP_TRIGGER_PV, "Trigger PV", WidgetPropertyCategory.Behavior, ""), new PVValueProperty(PROP_TRIGGER_PV_VALUE, null)); addProperty(new StringProperty(PROP_TITLE, "Title", WidgetPropertyCategory.Display, "")); addProperty(new FontProperty(PROP_TITLE_FONT, "Title Font", WidgetPropertyCategory.Display,new FontData("Arial", 12, SWT.BOLD))); //$NON-NLS-1$ addProperty(new BooleanProperty(PROP_SHOW_LEGEND, "Show Legend", WidgetPropertyCategory.Display,true)); addProperty(new BooleanProperty(PROP_SHOW_PLOTAREA_BORDER, "Show Plot Area Border", WidgetPropertyCategory.Display,false)); addProperty(new BooleanProperty(PROP_SHOW_TOOLBAR, "Show Toolbar", WidgetPropertyCategory.Display,true)); addProperty(new ColorProperty(PROP_PLOTAREA_BACKCOLOR, "Plot Area Background Color", WidgetPropertyCategory.Display,DEFAULT_PLOTAREA_BACKCOLOR)); addProperty(new BooleanProperty(PROP_TRANSPARENT, "Transparent", WidgetPropertyCategory.Display,false)); addProperty(new IntegerProperty(PROP_AXIS_COUNT, "Axis Count", WidgetPropertyCategory.Behavior,2, 2, MAX_AXES_AMOUNT)); addProperty(new IntegerProperty(PROP_TRACE_COUNT, "Trace Count", WidgetPropertyCategory.Behavior, 1, 0, MAX_TRACES_AMOUNT)); addAxisProperties(); addTraceProperties(); setPropertyVisible(PROP_PVNAME, false); } private void addAxisProperties(){ for(int i=0; i < MAX_AXES_AMOUNT; i++){ WidgetPropertyCategory category; if(i ==0) category = new NameDefinedCategory("Primary X Axis (0)"); else if(i == 1) category = new NameDefinedCategory("Primary Y Axis (1)"); else category = new NameDefinedCategory("Secondary Axis (" + i + ")"); for(AxisProperty axisProperty : AxisProperty.values()) addAxisProperty(axisProperty, i, category); } } private void addAxisProperty(AxisProperty axisProperty, int axisIndex, WidgetPropertyCategory category){ String propID = makeAxisPropID(axisProperty.propIDPre, axisIndex); switch (axisProperty) { case Y_AXIS: if(axisIndex < 2) break; addProperty(new BooleanProperty(propID, axisProperty.toString(), category, true)); break; case PRIMARY: if(axisIndex < 2) break; addProperty(new BooleanProperty(propID, axisProperty.toString(), category, true)); break; case TITLE: addProperty(new StringProperty(propID, axisProperty.toString(), category, category.toString())); break; case TITLE_FONT: addProperty(new FontProperty(propID, axisProperty.toString(), category, new FontData("Arial", 9, SWT.BOLD))); break; case AXIS_COLOR: addProperty(new ColorProperty(propID, axisProperty.toString(), category, DEFAULT_AXIS_COLOR)); break; case AUTO_SCALE_THRESHOLD: addProperty(new DoubleProperty(propID, axisProperty.toString(), category,0, 0, 1)); break; case LOG: addProperty(new BooleanProperty(propID, axisProperty.toString(), category,false)); break; case AUTO_SCALE: case SHOW_GRID: case DASH_GRID: addProperty(new BooleanProperty(propID, axisProperty.toString(), category, true)); break; case MAX: addProperty(new DoubleProperty(propID, axisProperty.toString(), category, DEFAULT_MAX)); break; case MIN: addProperty(new DoubleProperty(propID, axisProperty.toString(), category,DEFAULT_MIN)); break; case TIME_FORMAT: addProperty(new ComboProperty(propID, axisProperty.toString(), category, TIME_FORMAT_ARRAY, 0)); break; case GRID_COLOR: addProperty(new ColorProperty(propID, axisProperty.toString(), category,DEFAULT_GRID_COLOR)); break; case VISIBLE: addProperty(new BooleanProperty(propID, axisProperty.toString(), category, true)); break; default: break; } } public static String makeAxisPropID(String propIDPre, int index){ return "axis_" + index + "_" + propIDPre; //$NON-NLS-1$ //$NON-NLS-2$ } private void addTraceProperties(){ for(int i=0; i < MAX_TRACES_AMOUNT; i++){ for(TraceProperty traceProperty : TraceProperty.values()) addTraceProperty(traceProperty, i); } } private void addTraceProperty(TraceProperty traceProperty, int traceIndex){ String propID = makeTracePropID(traceProperty.propIDPre, traceIndex); WidgetPropertyCategory category = new NameDefinedCategory("Trace " + traceIndex); switch (traceProperty) { case NAME: addProperty(new StringProperty(propID, traceProperty.toString(), category, category.toString())); break; case ANTI_ALIAS: case CHRONOLOGICAL: addProperty(new BooleanProperty(propID, traceProperty.toString(), category, true)); break; case BUFFER_SIZE: addProperty(new IntegerProperty(propID, traceProperty.toString(), category, DEFAULT_BUFFER_SIZE, 1, MAX_BUFFER_SIZE)); break; case CONCATENATE_DATA: addProperty(new BooleanProperty(propID, traceProperty.toString(), category, true)); break; //case CLEAR_TRACE: // addProperty(new BooleanProperty(propID, traceProperty.toString(), category, false)); // break; case LINE_WIDTH: addProperty(new IntegerProperty(propID, traceProperty.toString(), category, 1, 1, 100)); break; case PLOTMODE: addProperty(new ComboProperty(propID, traceProperty.toString(), category, PlotMode.stringValues(), 0)); break; case POINT_SIZE: addProperty(new IntegerProperty(propID, traceProperty.toString(), category, 4, 1, 200)); break; case POINT_STYLE: addProperty(new ComboProperty(propID, traceProperty.toString(), category, PointStyle.stringValues(), 0)); break; case TRACE_COLOR: addProperty(new ColorProperty(propID, traceProperty.toString(), category, traceIndex < XYGraph.DEFAULT_TRACES_COLOR.length? XYGraph.DEFAULT_TRACES_COLOR[traceIndex].getRGB() : DEFAULT_TRACE_COLOR)); break; case TRACE_TYPE: addProperty(new ComboProperty(propID, traceProperty.toString(), category, TraceType.stringValues(), 0)); break; // case TRIGGER_VALUE: // addProperty(new DoubleProperty(propID, traceProperty.toString(), category, 0)); // break; case UPDATE_DELAY: addProperty(new IntegerProperty(propID, traceProperty.toString(), category, 100, 0, 655350)); break; case UPDATE_MODE: addProperty(new ComboProperty(propID, traceProperty.toString(), category, UpdateMode.stringValues(), 0)); break; case XAXIS_INDEX: addProperty(new ComboProperty(propID, traceProperty.toString(), category, AXES_ARRAY, 0)); break; case XPV: addPVProperty(new StringProperty(propID, traceProperty.toString(), category, ""), new PVValueProperty(makeTracePropID(TraceProperty.XPV_VALUE.propIDPre, traceIndex), null)); break; case YPV: addPVProperty(new StringProperty(propID, traceProperty.toString(), category, ""), new PVValueProperty(makeTracePropID(TraceProperty.YPV_VALUE.propIDPre, traceIndex), null)); break; case YAXIS_INDEX: addProperty(new ComboProperty(propID, traceProperty.toString(), category, AXES_ARRAY, 1)); break; default: break; } } public static String makeTracePropID(String propIDPre, int index){ return "trace_" +index + "_" + propIDPre; //$NON-NLS-1$ //$NON-NLS-2$ } /** * @return the title */ public String getTitle() { return (String) getProperty(PROP_TITLE).getPropertyValue(); } /** * Return the title font. * * @return The title font. */ public OPIFont getTitleFont() { return (OPIFont) getProperty(PROP_TITLE_FONT).getPropertyValue(); } /** * @return true if the plot area border should be shown, false otherwise */ public boolean isShowPlotAreaBorder() { return (Boolean) getProperty(PROP_SHOW_PLOTAREA_BORDER).getPropertyValue(); } /** * @return the plot area background color */ public RGB getPlotAreaBackColor() { return getRGBFromColorProperty(PROP_PLOTAREA_BACKCOLOR); } /** * @return true if the XY Graph is transparent, false otherwise */ public boolean isTransprent() { return (Boolean) getProperty(PROP_TRANSPARENT).getPropertyValue(); } /** * @return true if the legend should be shown, false otherwise */ public boolean isShowLegend() { return (Boolean) getProperty(PROP_SHOW_LEGEND).getPropertyValue(); } /** * @return true if the legend should be shown, false otherwise */ public boolean isShowToolbar() { return (Boolean) getProperty(PROP_SHOW_TOOLBAR).getPropertyValue(); } /** * @return The number of axes. */ public int getAxesAmount() { return (Integer) getProperty(PROP_AXIS_COUNT).getPropertyValue(); } /** * @return The number of traces. */ public int getTracesAmount() { return (Integer) getProperty(PROP_TRACE_COUNT).getPropertyValue(); } @Override public String getTypeID() { return ID; } }
change tooltip to the first trace pv
applications/plugins/org.csstudio.opibuilder.widgets/src/org/csstudio/opibuilder/widgets/model/XYGraphModel.java
change tooltip to the first trace pv
<ide><path>pplications/plugins/org.csstudio.opibuilder.widgets/src/org/csstudio/opibuilder/widgets/model/XYGraphModel.java <ide> setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); <ide> setForegroundColor(CustomMediaFactory.COLOR_BLUE); <ide> setPropertyValue(PROP_PVNAME, "$(trace_0_y_pv)"); //$NON-NLS-1$ <add> setTooltip("$(trace_0_y_pv)\n$(trace_0_y_pv_value)"); <ide> <ide> } <ide>
JavaScript
mit
81981138da1fcc70c0d3e69565420e57d9e580f2
0
collinsnji/Furler
'use strict'; /** * Furler v0.0.1 * * @author Collin Grimm <[email protected]> * @copyright (c) 2017 Collin Grimm * @license MIT License https://collingrimm.me/LICENSE.txt */ const fs = require('fs'); const request = require('request'); const cheerio = require('cheerio'); const path = require('path'); const { exec } = require('child_process'); var Spacer = function (str) { return str.toLowerCase().match(/[^_\s\W]+/g).join(''); } var lyricsDir = path.join(path.resolve('.'), 'lyrics'); /** * * @param {String} song Name of song. Default => 'Elastic Heart' * @param {String} artist Name of artist. Default => 'Sia' */ var Furler = function (song, artist) { this.artist = artist || 'Sia'; this.song = song || 'Elastic Heart'; return this; } Furler.prototype.Lyrics = function () { var Sia = this; var LyricURL = `https://www.azlyrics.com/lyrics/${Spacer(Sia.artist)}/${Spacer(Sia.song)}.html`; return request(LyricURL, function (error, response, songData) { var $ = cheerio.load(songData); if ($('html').children('body').toString().includes('Welcome to AZLyrics!')) { throw new Error('Song not found'); } var lyrics = $('.text-center').children('div').text().toString().replace(/^(\n){2,}/gm, "\r\n"); fs.writeFileSync(`${lyricsDir}/${Spacer(Sia.song)}.txt`, lyrics); exec(`./siafy ${lyricsDir}/${Spacer(Sia.song)}.txt`); }); } module.exports = Furler; //var Sia = new Furler('Big Girls cry').Lyrics();
src/Furler.js
'use strict'; /** * Versionizr v0.0.1 * * @author Collin Grimm <[email protected]> * @copyright (c) 2017 Collin Grimm * @license MIT License https://collingrimm.me/LICENSE.txt */ const fs = require('fs'); const request = require('request'); const cheerio = require('cheerio'); const { exec } = require('child_process'); var Spacer = function (str) { return str.toLowerCase().match(/[^_\s\W]+/g).join(''); } var Furler = function (song, artist) { this.artist = artist || 'Sia'; this.song = song || 'Elastic Heart'; return this; } Furler.prototype.Lyrics = function () { var sia = this; var LyricURL = `https://www.azlyrics.com/lyrics/${Spacer(sia.artist)}/${Spacer(sia.song)}.html`; request(LyricURL, function (error, response, songData) { var $ = cheerio.load(songData); var lyrics = $('.text-center').children('div').text().toString().replace(/^(\n){2,}/gm, "\r\n"); fs.writeFileSync(`${Spacer(sia.song)}.txt`, lyrics); const child = exec(`./siafy ${Spacer(sia.song)}.txt`); }); } module.exports = Furler; //var Sia = new Furler('Big Girls cry').Lyrics();
Throw an exception if lyrics was not found added jsdocs as well. I <3 documentation
src/Furler.js
Throw an exception if lyrics was not found added jsdocs as well. I <3 documentation
<ide><path>rc/Furler.js <ide> 'use strict'; <ide> <ide> /** <del> * Versionizr v0.0.1 <add> * Furler v0.0.1 <ide> * <ide> * @author Collin Grimm <[email protected]> <ide> * @copyright (c) 2017 Collin Grimm <ide> const fs = require('fs'); <ide> const request = require('request'); <ide> const cheerio = require('cheerio'); <add>const path = require('path'); <ide> const { exec } = require('child_process'); <ide> <ide> var Spacer = function (str) { return str.toLowerCase().match(/[^_\s\W]+/g).join(''); } <add>var lyricsDir = path.join(path.resolve('.'), 'lyrics'); <ide> <add>/** <add> * <add> * @param {String} song Name of song. Default => 'Elastic Heart' <add> * @param {String} artist Name of artist. Default => 'Sia' <add> */ <ide> var Furler = function (song, artist) { <ide> this.artist = artist || 'Sia'; <ide> this.song = song || 'Elastic Heart'; <ide> return this; <ide> } <ide> Furler.prototype.Lyrics = function () { <del> var sia = this; <del> var LyricURL = `https://www.azlyrics.com/lyrics/${Spacer(sia.artist)}/${Spacer(sia.song)}.html`; <del> request(LyricURL, function (error, response, songData) { <add> var Sia = this; <add> var LyricURL = `https://www.azlyrics.com/lyrics/${Spacer(Sia.artist)}/${Spacer(Sia.song)}.html`; <add> return request(LyricURL, function (error, response, songData) { <ide> var $ = cheerio.load(songData); <add> if ($('html').children('body').toString().includes('Welcome to AZLyrics!')) { throw new Error('Song not found'); } <add> <ide> var lyrics = $('.text-center').children('div').text().toString().replace(/^(\n){2,}/gm, "\r\n"); <del> <del> fs.writeFileSync(`${Spacer(sia.song)}.txt`, lyrics); <del> const child = exec(`./siafy ${Spacer(sia.song)}.txt`); <add> fs.writeFileSync(`${lyricsDir}/${Spacer(Sia.song)}.txt`, lyrics); <add> exec(`./siafy ${lyricsDir}/${Spacer(Sia.song)}.txt`); <ide> }); <ide> } <ide>
Java
epl-1.0
dc1125c95c19510a418dcd49620ef9f139d4357c
0
floralvikings/jenjin
package com.jenjinstudios.world; import com.jenjinstudios.world.collections.LocationArrayList; import com.jenjinstudios.world.math.Dimension2D; import javax.xml.bind.annotation.*; import java.util.Collections; /** * The {@code Zone} class represents a grid of {@code Location} objects within the {@code World}. Zones cannot be * accessed from other Zones. Support for this feature is planned in a future release. * @author Caleb Brinkman */ @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name = "zone", namespace = "https://www.jenjinstudios.com") public class Zone { @XmlAttribute(name = "id", namespace = "https://www.jenjinstudios.com") private int id; @XmlAttribute(name = "xSize", namespace = "https://www.jenjinstudios.com") private int xSize; @XmlAttribute(name = "ySize", namespace = "https://www.jenjinstudios.com") private int ySize; @XmlElement(name = "location", namespace = "https://www.jenjinstudios.com") private LocationArrayList locationGrid; /** * Construct a new zone with the given ID and size. * @param id The id number of the zone. * @param specialLocations Any special locations that should be set on zone creation. */ public Zone(int id, Dimension2D size, Location... specialLocations) { this.id = id; this.xSize = size.getXSize(); this.ySize = size.getYSize(); locationGrid = new LocationArrayList(); populateLocations(); Collections.addAll(locationGrid, specialLocations); } public LocationArrayList getLocationGrid() { if (locationGrid == null) { locationGrid = new LocationArrayList(); populateLocations(); } return locationGrid; } public int getId() { return id; } public int getXSize() { return xSize; } public int getYSize() { return ySize; } private void populateLocations() { for (int x = 0; x < xSize; x++) { populateColumn(x); } } private void populateColumn(int x) { for (int y = 0; y < ySize; y++) { locationGrid.add(new Location(x, y)); } } }
jenjin-world-core/src/main/java/com/jenjinstudios/world/Zone.java
package com.jenjinstudios.world; import com.jenjinstudios.world.collections.LocationArrayList; import com.jenjinstudios.world.math.Dimension2D; import java.util.Collections; /** * The {@code Zone} class represents a grid of {@code Location} objects within the {@code World}. Zones cannot be * accessed from other Zones. Support for this feature is planned in a future release. * @author Caleb Brinkman */ public class Zone { private int id; private int xSize; private int ySize; private LocationArrayList locationGrid; /** * Construct a new zone with the given ID and size. * @param id The id number of the zone. * @param specialLocations Any special locations that should be set on zone creation. */ public Zone(int id, Dimension2D size, Location... specialLocations) { this.id = id; this.xSize = size.getXSize(); this.ySize = size.getYSize(); locationGrid = new LocationArrayList(); populateLocations(); Collections.addAll(locationGrid, specialLocations); } public LocationArrayList getLocationGrid() { if (locationGrid == null) { locationGrid = new LocationArrayList(); populateLocations(); } return locationGrid; } public int getId() { return id; } public int getXSize() { return xSize; } public int getYSize() { return ySize; } private void populateLocations() { for (int x = 0; x < xSize; x++) { populateColumn(x); } } private void populateColumn(int x) { for (int y = 0; y < ySize; y++) { locationGrid.add(new Location(x, y)); } } }
Added JAXB annotations
jenjin-world-core/src/main/java/com/jenjinstudios/world/Zone.java
Added JAXB annotations
<ide><path>enjin-world-core/src/main/java/com/jenjinstudios/world/Zone.java <ide> import com.jenjinstudios.world.collections.LocationArrayList; <ide> import com.jenjinstudios.world.math.Dimension2D; <ide> <add>import javax.xml.bind.annotation.*; <ide> import java.util.Collections; <ide> <ide> /** <ide> * accessed from other Zones. Support for this feature is planned in a future release. <ide> * @author Caleb Brinkman <ide> */ <add>@XmlAccessorType(XmlAccessType.FIELD) <add>@XmlRootElement(name = "zone", namespace = "https://www.jenjinstudios.com") <ide> public class Zone <ide> { <add> @XmlAttribute(name = "id", namespace = "https://www.jenjinstudios.com") <ide> private int id; <add> @XmlAttribute(name = "xSize", namespace = "https://www.jenjinstudios.com") <ide> private int xSize; <add> @XmlAttribute(name = "ySize", namespace = "https://www.jenjinstudios.com") <ide> private int ySize; <add> @XmlElement(name = "location", namespace = "https://www.jenjinstudios.com") <ide> private LocationArrayList locationGrid; <ide> <ide> /**
JavaScript
mit
82cd20faea3ec39788c1ed331296a82acc81db23
0
wenzhixin/multiple-select,wenzhixin/multiple-select,wenzhixin/multiple-select
/* eslint-disable unicorn/no-fn-reference-in-iterator */ import cssEscape from 'css.escape' import removeDiacritics from './utils/removeDiacritics.js' import {s, sprintf} from './utils/sprintf.js' class MultipleSelect { constructor ($el, options) { const el = $el[0] const name = el.getAttribute('name') || options.name || '' this.options = $.extend({}, defaults, options) // hide select element this.$el = $el.hide() // label element this.$label = this.$el.closest('label') if (this.$label.length === 0 && el.getAttribute('id')) { this.$label = $(sprintf`label[for="${s}"]`(cssEscape(el.getAttribute('id')))) } // restore class and title from select element this.$parent = $(sprintf`<div class="ms-parent ${s}" ${s}/>`( el.getAttribute('class') || '', sprintf`title="${s}"`(el.getAttribute('title')) )) // add placeholder to choice button this.options.placeholder = this.options.placeholder || el.getAttribute('placeholder') || '' this.$choice = $(sprintf` <button type="button" class="ms-choice"> <span class="placeholder">${s}</span> <div></div> </button> `(this.options.placeholder)) // default position is bottom this.$drop = $(sprintf`<div class="ms-drop ${s}"></div>`(this.options.position)) if (this.options.dropWidth) { this.$drop.css('width', this.options.dropWidth) } this.$el.after(this.$parent) this.$parent.append(this.$choice) this.$parent.append(this.$drop) if (el.disabled) { this.$choice.addClass('disabled') } this.$parent.css('width', this.options.width || this.$el.css('width') || this.$el.outerWidth() + 20) this.selectAllName = `data-name="selectAll${name}"` this.selectGroupName = `data-name="selectGroup${name}"` this.selectItemName = `data-name="selectItem${name}"` if (!this.options.keepOpen) { $(document).click(e => { if ( $(e.target)[0] === this.$choice[0] || $(e.target).parents('.ms-choice')[0] === this.$choice[0] ) { return } if ( ($(e.target)[0] === this.$drop[0] || ($(e.target).parents('.ms-drop')[0] !== this.$drop[0] && e.target !== el)) && this.options.isOpen ) { this.close() } }) } this.options.onAfterCreate() } init () { const $ul = $('<ul></ul>') this.$drop.html('') if (this.options.filter) { this.$drop.append(` <div class="ms-search"> <input type="text" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" ${sprintf`placeholder="${s}"`(this.options.filterPlaceholder)}> </div> `) } if (this.options.selectAll && !this.options.single) { $ul.append([ '<li class="ms-select-all">', '<label>', sprintf`<input type="checkbox" ${s} />`(this.selectAllName), `<span>${this.options.formatSelectAll()}</span>`, '</label>', '</li>' ].join('')) } $.each(this.$el.children(), (i, elm) => { $ul.append(this.optionToHtml(i, elm)) }) $ul.append(sprintf`<li class="ms-no-results">${s}</li>`( this.options.formatNoMatchesFound() )) this.$drop.append($ul) this.$drop.find('ul').css('max-height', `${this.options.maxHeight}px`) this.$drop.find('.multiple').css('width', `${this.options.multipleWidth}px`) this.$searchInput = this.$drop.find('.ms-search input') this.$selectAll = this.$drop.find(`input[${this.selectAllName}]`) this.$selectGroups = this.$drop.find(`input[${this.selectGroupName}]`) this.$selectItems = this.$drop.find(`input[${this.selectItemName}]:enabled`) this.$disableItems = this.$drop.find(`input[${this.selectItemName}]:disabled`) this.$noResults = this.$drop.find('.ms-no-results') this.events() this.updateSelectAll(true) this.update(true) this.updateOptGroupSelect(true) if (this.options.isOpen) { this.open() } if (this.options.openOnHover) { this.$parent.hover(() => { this.open() }, () => { this.close() }) } } optionToHtml (i, elm, group, groupDisabled) { const $elm = $(elm) const el = $elm[0] const classes = el.getAttribute('class') || '' const title = sprintf`title="${s}"`(el.getAttribute('title')) const multiple = this.options.multiple ? 'multiple' : '' let disabled const type = this.options.single ? 'radio' : 'checkbox' if ($elm.is('option')) { const text = this.options.textTemplate($elm) const {value, selected} = el const customStyle = this.options.styler(value) const style = customStyle ? sprintf`style="${s}"`(customStyle) : '' disabled = groupDisabled || el.disabled const $el = $([ sprintf`<li class="${s} ${s}" ${s} ${s}>`(multiple, classes, title, style), sprintf`<label class="${s}">`(disabled ? 'disabled' : ''), sprintf`<input type="${s}" ${s}${s}${s}${s}>`( type, this.selectItemName, selected ? ' checked="checked"' : '', disabled ? ' disabled="disabled"' : '', sprintf` data-group="${s}"`(group) ), sprintf`<span>${s}</span>`(text), '</label>', '</li>' ].join('')) $el.find('input').val(value) return $el } if ($elm.is('optgroup')) { const label = this.options.labelTemplate($elm) const $group = $('<div/>') group = `group_${i}`; ({disabled} = el) $group.append([ '<li class="group">', sprintf`<label class="optgroup ${s}" data-group="${s}">`( disabled ? 'disabled' : '', group ), this.options.hideOptgroupCheckboxes || this.options.single ? '' : sprintf`<input type="checkbox" ${s} ${s}>`( this.selectGroupName, disabled ? 'disabled="disabled"' : '' ), label, '</label>', '</li>' ].join('')) $.each($elm.children(), (j, elem) => { $group.append(this.optionToHtml(j, elem, group, disabled)) }) return $group.html() } // Append nothing return undefined } events () { const toggleOpen = e => { e.preventDefault() this[this.options.isOpen ? 'close' : 'open']() } if (this.$label) { this.$label.off('click').on('click', e => { if (e.target.nodeName.toLowerCase() !== 'label' || e.target !== this) { return } toggleOpen(e) if (!this.options.filter || !this.options.isOpen) { this.focus() } e.stopPropagation() // Causes lost focus otherwise }) } this.$choice.off('click').on('click', toggleOpen) .off('focus').on('focus', this.options.onFocus) .off('blur').on('blur', this.options.onBlur) this.$parent.off('keydown').on('keydown', e => { // esc key if (e.which === 27) { this.close() this.$choice.focus() } }) this.$searchInput.off('keydown').on('keydown', e => { // Ensure shift-tab causes lost focus from filter as with clicking away if (e.keyCode === 9 && e.shiftKey) { this.close() } }).off('keyup').on('keyup', e => { // enter or space // Avoid selecting/deselecting if no choices made if ( this.options.filterAcceptOnEnter && [13, 32].includes(e.which) && this.$searchInput.val() ) { this.$selectAll.click() this.close() this.focus() return } this.filter() }) this.$selectAll.off('click').on('click', e => { const checked = $(e.currentTarget).prop('checked') const $items = this.$selectItems.filter(':visible') if ($items.length === this.$selectItems.length) { this[checked ? 'checkAll' : 'uncheckAll']() } else { // when the filter option is true this.$selectGroups.prop('checked', checked) $items.prop('checked', checked) this.options[checked ? 'onCheckAll' : 'onUncheckAll']() this.update() } }) this.$selectGroups.off('click').on('click', e => { const $this = $(e.currentTarget) const group = $this.parent()[0].getAttribute('data-group') const $items = this.$selectItems.filter(':visible') const $children = $items.filter(sprintf`[data-group="${s}"]`(group)) const checked = $children.length !== $children.filter(':checked').length $children.prop('checked', checked) this.updateSelectAll() this.update() this.options.onOptgroupClick({ label: $this.parent().text(), checked, children: $children.get().map(el => { return { label: $(el).parent().text(), value: $(el).val(), check: $(el).prop('checked') } }) }) }) this.$selectItems.off('click').on('click', e => { const $this = $(e.currentTarget) if (this.options.single) { const clickedVal = $(e.currentTarget).val() this.$selectItems.filter((i, el) => { return $(el).val() !== clickedVal }).each((i, el) => { $(el).prop('checked', false) }) } this.updateSelectAll() this.update() this.updateOptGroupSelect() this.options.onClick({ label: $this.parent().text(), value: $this.val(), checked: $this.prop('checked') }) if (this.options.single && this.options.isOpen && !this.options.keepOpen) { this.close() } }) } open () { if (this.$choice.hasClass('disabled')) { return } this.options.isOpen = true this.$choice.find('>div').addClass('open') this.$drop[this.animateMethod('show')]() // fix filter bug: no results show this.$selectAll.parent().show() this.$noResults.hide() // Fix #77: 'All selected' when no options if (!this.$el.children().length) { this.$selectAll.parent().hide() this.$noResults.show() } if (this.options.container) { const offset = this.$drop.offset() this.$drop.appendTo($(this.options.container)) this.$drop.offset({ top: offset.top, left: offset.left }) this.$drop.outerWidth(this.$parent.outerWidth()) } if (this.$el.children().length && this.options.filter) { this.$searchInput.val('') this.$searchInput.focus() this.filter() } this.options.onOpen() } close () { this.options.isOpen = false this.$choice.find('>div').removeClass('open') this.$drop[this.animateMethod('hide')]() if (this.options.container) { this.$parent.append(this.$drop) this.$drop.css({ 'top': 'auto', 'left': 'auto' }) } this.options.onClose() } animateMethod (method) { const methods = { show: { fade: 'fadeIn', slide: 'slideDown' }, hide: { fade: 'fadeOut', slide: 'slideUp' } } return methods[method][this.options.animate] || method } update (ignoreTrigger) { const valueSelects = this.getSelects() const textSelects = this.options.displayValues ? valueSelects : this.getSelects('text') const $span = this.$choice.find('>span') const sl = valueSelects.length if (sl === 0) { $span.addClass('placeholder').html(this.options.placeholder) } else if (this.options.formatAllSelected() && sl === this.$selectItems.length + this.$disableItems.length) { $span.removeClass('placeholder').html(this.options.formatAllSelected()) } else if (this.options.ellipsis && sl > this.options.minimumCountSelected) { $span.removeClass('placeholder').text(`${textSelects.slice(0, this.options.minimumCountSelected) .join(this.options.displayDelimiter)}...`) } else if (this.options.formatCountSelected() && sl > this.options.minimumCountSelected) { $span.removeClass('placeholder').html(this.options.formatCountSelected( sl, this.$selectItems.length + this.$disableItems.length )) } else { $span.removeClass('placeholder').text(textSelects.join(this.options.displayDelimiter)) } if (this.options.displayTitle) { $span.prop('title', this.getSelects('text')) } // set selects to select this.$el.val(this.getSelects()) // add selected class to selected li this.$drop.find('li').removeClass('selected') this.$drop.find('input:checked').each((i, el) => { $(el).parents('li').first().addClass('selected') }) // trigger <select> change event if (!ignoreTrigger) { this.$el.trigger('change') } } updateSelectAll (isInit) { let $items = this.$selectItems if (!isInit) { $items = $items.filter(':visible') } this.$selectAll.prop('checked', $items.length && $items.length === $items.filter(':checked').length) if (!isInit && this.$selectAll.prop('checked')) { this.options.onCheckAll() } } updateOptGroupSelect (isInit) { let $items = this.$selectItems if (!isInit) { $items = $items.filter(':visible') } $.each(this.$selectGroups, (i, val) => { const group = $(val).parent()[0].getAttribute('data-group') const $children = $items.filter(sprintf`[data-group="${s}"]`(group)) $(val).prop('checked', $children.length && $children.length === $children.filter(':checked').length) }) } // value or text, default: 'value' getSelects (type) { let texts = [] const values = [] this.$drop.find(sprintf`input[${s}]:checked`(this.selectItemName)).each((i, el) => { texts.push($(el).parents('li').first().text()) values.push($(el).val()) }) if (type === 'text' && this.$selectGroups.length) { texts = [] this.$selectGroups.each((i, el) => { const html = [] const text = $.trim($(el).parent().text()) const group = $(el).parent().data('group') const $children = this.$drop.find(sprintf`[${s}][data-group="${s}"]`( this.selectItemName, group )) const $selected = $children.filter(':checked') if (!$selected.length) { return } html.push('[') html.push(text) if ($children.length > $selected.length) { const list = [] $selected.each((j, elem) => { list.push($(elem).parent().text()) }) html.push(`: ${list.join(', ')}`) } html.push(']') texts.push(html.join('')) }) } return type === 'text' ? texts : values } setSelects (values) { this.$selectItems.prop('checked', false) this.$disableItems.prop('checked', false) $.each(values, (i, value) => { this.$selectItems.filter(sprintf`[value="${s}"]`(value)).prop('checked', true) this.$disableItems.filter(sprintf`[value="${s}"]`(value)).prop('checked', true) }) this.$selectAll.prop('checked', this.$selectItems.length === this.$selectItems.filter(':checked').length + this.$disableItems.filter(':checked').length) $.each(this.$selectGroups, (i, val) => { const group = $(val).parent()[0].getAttribute('data-group') const $children = this.$selectItems.filter(`[data-group="${group}"]`) $(val).prop('checked', $children.length && $children.length === $children.filter(':checked').length) }) this.update(false) } enable () { this.$choice.removeClass('disabled') } disable () { this.$choice.addClass('disabled') } checkAll () { this.$selectItems.prop('checked', true) this.$selectGroups.prop('checked', true) this.$selectAll.prop('checked', true) this.update() this.options.onCheckAll() } uncheckAll () { this.$selectItems.prop('checked', false) this.$selectGroups.prop('checked', false) this.$selectAll.prop('checked', false) this.update() this.options.onUncheckAll() } focus () { this.$choice.focus() this.options.onFocus() } blur () { this.$choice.blur() this.options.onBlur() } refresh () { this.init() } filter () { const text = $.trim(this.$searchInput.val()).toLowerCase() if (text.length === 0) { this.$selectAll.closest('li').show() this.$selectItems.closest('li').show() this.$disableItems.closest('li').show() this.$selectGroups.closest('li').show() this.$noResults.hide() } else { if (!this.options.filterGroup) { this.$selectItems.each((i, el) => { const $parent = $(el).parent() const hasText = removeDiacritics($parent.text().toLowerCase()) .includes(removeDiacritics(text)) $parent.closest('li')[hasText ? 'show' : 'hide']() }) } this.$disableItems.parent().hide() this.$selectGroups.each((i, el) => { const $parent = $(el).parent() const group = $parent[0].getAttribute('data-group') if (this.options.filterGroup) { const hasText = removeDiacritics($parent.text().toLowerCase()) .includes(removeDiacritics(text)) const func = hasText ? 'show' : 'hide' $parent.closest('li')[func]() this.$selectItems.filter(`[data-group="${group}"]`).closest('li')[func]() } else { const $items = this.$selectItems.filter(':visible') const hasText = $items.filter(sprintf`[data-group="${s}"]`(group)).length $parent.closest('li')[hasText ? 'show' : 'hide']() } }) // Check if no matches found if (this.$selectItems.parent().filter(':visible').length) { this.$selectAll.closest('li').show() this.$noResults.hide() } else { this.$selectAll.closest('li').hide() this.$noResults.show() } } this.updateOptGroupSelect() this.updateSelectAll() this.options.onFilter(text) } destroy () { this.$el.before(this.$parent).show() this.$parent.remove() } } const defaults = { name: '', placeholder: '', selectAll: true, single: false, multiple: false, hideOptgroupCheckboxes: false, multipleWidth: 80, width: undefined, dropWidth: undefined, maxHeight: 250, position: 'bottom', displayValues: false, displayTitle: false, displayDelimiter: ', ', minimumCountSelected: 3, ellipsis: false, isOpen: false, keepOpen: false, openOnHover: false, container: null, filter: false, filterGroup: false, filterPlaceholder: '', filterAcceptOnEnter: false, animate: undefined, styler () { return false }, textTemplate ($elm) { return $elm[0].innerHTML }, labelTemplate ($elm) { return $elm[0].getAttribute('label') }, formatSelectAll () { return '[Select all]' }, formatAllSelected () { return 'All selected' }, formatCountSelected (count, total) { return count + ' of ' + total + ' selected' }, formatNoMatchesFound () { return 'No matches found' }, onOpen () { return false }, onClose () { return false }, onCheckAll () { return false }, onUncheckAll () { return false }, onFocus () { return false }, onBlur () { return false }, onOptgroupClick () { return false }, onClick () { return false }, onFilter () { return false }, onAfterCreate () { return false } } export default MultipleSelect
src/MultipleSelect.js
/* eslint-disable unicorn/no-fn-reference-in-iterator */ import cssEscape from 'css.escape' import removeDiacritics from './utils/removeDiacritics.js' import {s, sprintf} from './utils/sprintf.js' class MultipleSelect { constructor ($el, options) { const el = $el[0] const name = el.getAttribute('name') || options.name || '' this.options = $.extend({}, defaults, options) // hide select element this.$el = $el.hide() // label element this.$label = this.$el.closest('label') if (this.$label.length === 0 && el.getAttribute('id')) { this.$label = $(sprintf`label[for="${s}"]`(cssEscape(el.getAttribute('id')))) } // restore class and title from select element this.$parent = $(sprintf`<div class="ms-parent ${s}" ${s}/>`( el.getAttribute('class') || '', sprintf`title="${s}"`(el.getAttribute('title')) )) // add placeholder to choice button this.options.placeholder = this.options.placeholder || el.getAttribute('placeholder') || '' this.$choice = $(sprintf` <button type="button" class="ms-choice"> <span class="placeholder">${s}</span> <div></div> </button> `(this.options.placeholder)) // default position is bottom this.$drop = $(sprintf`<div class="ms-drop ${s}"></div>`(this.options.position)) if (this.options.dropWidth) { this.$drop.css('width', this.options.dropWidth) } this.$el.after(this.$parent) this.$parent.append(this.$choice) this.$parent.append(this.$drop) if (el.disabled) { this.$choice.addClass('disabled') } this.$parent.css('width', this.options.width || this.$el.css('width') || this.$el.outerWidth() + 20) this.selectAllName = `data-name="selectAll${name}"` this.selectGroupName = `data-name="selectGroup${name}"` this.selectItemName = `data-name="selectItem${name}"` if (!this.options.keepOpen) { $(document).click(e => { if ( $(e.target)[0] === this.$choice[0] || $(e.target).parents('.ms-choice')[0] === this.$choice[0] ) { return } if ( ($(e.target)[0] === this.$drop[0] || ($(e.target).parents('.ms-drop')[0] !== this.$drop[0] && e.target !== el)) && this.options.isOpen ) { this.close() } }) } this.options.onAfterCreate() } initDrop () { const $ul = $('<ul></ul>') this.$drop.html('') if (this.options.filter) { this.$drop.append(` <div class="ms-search"> <input type="text" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" ${sprintf`placeholder="${s}"`(this.options.filterPlaceholder)}> </div> `) } if (this.options.selectAll && !this.options.single) { $ul.append([ '<li class="ms-select-all">', '<label>', sprintf`<input type="checkbox" ${s} />`(this.selectAllName), `<span>${this.options.formatSelectAll()}</span>`, '</label>', '</li>' ].join('')) } $.each(this.$el.children(), (i, elm) => { $ul.append(this.optionToHtml(i, elm)) }) $ul.append(sprintf`<li class="ms-no-results">${s}</li>`( this.options.formatNoMatchesFound() )) this.$drop.append($ul) this.$drop.find('ul').css('max-height', `${this.options.maxHeight}px`) this.$drop.find('.multiple').css('width', `${this.options.multipleWidth}px`) } init () { this.initDrop() this.$searchInput = this.$drop.find('.ms-search input') this.$selectAll = this.$drop.find(`input[${this.selectAllName}]`) this.$selectGroups = this.$drop.find(`input[${this.selectGroupName}]`) this.$selectItems = this.$drop.find(`input[${this.selectItemName}]:enabled`) this.$disableItems = this.$drop.find(`input[${this.selectItemName}]:disabled`) this.$noResults = this.$drop.find('.ms-no-results') this.events() this.updateSelectAll(true) this.update(true) this.updateOptGroupSelect(true) if (this.options.isOpen) { this.open() } if (this.options.openOnHover) { this.$parent.hover(() => { this.open() }, () => { this.close() }) } } optionToHtml (i, elm, group, groupDisabled) { const $elm = $(elm) const el = $elm[0] const classes = el.getAttribute('class') || '' const title = sprintf`title="${s}"`(el.getAttribute('title')) const multiple = this.options.multiple ? 'multiple' : '' let disabled const type = this.options.single ? 'radio' : 'checkbox' if ($elm.is('option')) { const text = this.options.textTemplate($elm) const {value, selected} = el const customStyle = this.options.styler(value) const style = customStyle ? sprintf`style="${s}"`(customStyle) : '' disabled = groupDisabled || el.disabled const $el = $([ sprintf`<li class="${s} ${s}" ${s} ${s}>`(multiple, classes, title, style), sprintf`<label class="${s}">`(disabled ? 'disabled' : ''), sprintf`<input type="${s}" ${s}${s}${s}${s}>`( type, this.selectItemName, selected ? ' checked="checked"' : '', disabled ? ' disabled="disabled"' : '', sprintf` data-group="${s}"`(group) ), sprintf`<span>${s}</span>`(text), '</label>', '</li>' ].join('')) $el.find('input').val(value) return $el } if ($elm.is('optgroup')) { const label = this.options.labelTemplate($elm) const $group = $('<div/>') group = `group_${i}`; ({disabled} = el) $group.append([ '<li class="group">', sprintf`<label class="optgroup ${s}" data-group="${s}">`( disabled ? 'disabled' : '', group ), this.options.hideOptgroupCheckboxes || this.options.single ? '' : sprintf`<input type="checkbox" ${s} ${s}>`( this.selectGroupName, disabled ? 'disabled="disabled"' : '' ), label, '</label>', '</li>' ].join('')) $.each($elm.children(), (j, elem) => { $group.append(this.optionToHtml(j, elem, group, disabled)) }) return $group.html() } // Append nothing return undefined } events () { const toggleOpen = e => { e.preventDefault() this[this.options.isOpen ? 'close' : 'open']() } if (this.$label) { this.$label.off('click').on('click', e => { if (e.target.nodeName.toLowerCase() !== 'label' || e.target !== this) { return } toggleOpen(e) if (!this.options.filter || !this.options.isOpen) { this.focus() } e.stopPropagation() // Causes lost focus otherwise }) } this.$choice.off('click').on('click', toggleOpen) .off('focus').on('focus', this.options.onFocus) .off('blur').on('blur', this.options.onBlur) this.$parent.off('keydown').on('keydown', e => { // esc key if (e.which === 27) { this.close() this.$choice.focus() } }) this.$searchInput.off('keydown').on('keydown', e => { // Ensure shift-tab causes lost focus from filter as with clicking away if (e.keyCode === 9 && e.shiftKey) { this.close() } }).off('keyup').on('keyup', e => { // enter or space // Avoid selecting/deselecting if no choices made if ( this.options.filterAcceptOnEnter && [13, 32].includes(e.which) && this.$searchInput.val() ) { this.$selectAll.click() this.close() this.focus() return } this.filter() }) this.$selectAll.off('click').on('click', e => { const checked = $(e.currentTarget).prop('checked') const $items = this.$selectItems.filter(':visible') if ($items.length === this.$selectItems.length) { this[checked ? 'checkAll' : 'uncheckAll']() } else { // when the filter option is true this.$selectGroups.prop('checked', checked) $items.prop('checked', checked) this.options[checked ? 'onCheckAll' : 'onUncheckAll']() this.update() } }) this.$selectGroups.off('click').on('click', e => { const $this = $(e.currentTarget) const group = $this.parent()[0].getAttribute('data-group') const $items = this.$selectItems.filter(':visible') const $children = $items.filter(sprintf`[data-group="${s}"]`(group)) const checked = $children.length !== $children.filter(':checked').length $children.prop('checked', checked) this.updateSelectAll() this.update() this.options.onOptgroupClick({ label: $this.parent().text(), checked, children: $children.get().map(el => { return { label: $(el).parent().text(), value: $(el).val(), check: $(el).prop('checked') } }) }) }) this.$selectItems.off('click').on('click', e => { const $this = $(e.currentTarget) if (this.options.single) { const clickedVal = $(e.currentTarget).val() this.$selectItems.filter((i, el) => { return $(el).val() !== clickedVal }).each((i, el) => { $(el).prop('checked', false) }) } this.updateSelectAll() this.update() this.updateOptGroupSelect() this.options.onClick({ label: $this.parent().text(), value: $this.val(), checked: $this.prop('checked') }) if (this.options.single && this.options.isOpen && !this.options.keepOpen) { this.close() } }) } open () { if (this.$choice.hasClass('disabled')) { return } this.options.isOpen = true this.$choice.find('>div').addClass('open') this.$drop[this.animateMethod('show')]() // fix filter bug: no results show this.$selectAll.parent().show() this.$noResults.hide() // Fix #77: 'All selected' when no options if (!this.$el.children().length) { this.$selectAll.parent().hide() this.$noResults.show() } if (this.options.container) { const offset = this.$drop.offset() this.$drop.appendTo($(this.options.container)) this.$drop.offset({ top: offset.top, left: offset.left }) this.$drop.outerWidth(this.$parent.outerWidth()) } if (this.$el.children().length && this.options.filter) { this.$searchInput.val('') this.$searchInput.focus() this.filter() } this.options.onOpen() } close () { this.options.isOpen = false this.$choice.find('>div').removeClass('open') this.$drop[this.animateMethod('hide')]() if (this.options.container) { this.$parent.append(this.$drop) this.$drop.css({ 'top': 'auto', 'left': 'auto' }) } this.options.onClose() } animateMethod (method) { const methods = { show: { fade: 'fadeIn', slide: 'slideDown' }, hide: { fade: 'fadeOut', slide: 'slideUp' } } return methods[method][this.options.animate] || method } update (ignoreTrigger) { const valueSelects = this.getSelects() const textSelects = this.options.displayValues ? valueSelects : this.getSelects('text') const $span = this.$choice.find('>span') const sl = valueSelects.length if (sl === 0) { $span.addClass('placeholder').html(this.options.placeholder) } else if (this.options.formatAllSelected() && sl === this.$selectItems.length + this.$disableItems.length) { $span.removeClass('placeholder').html(this.options.formatAllSelected()) } else if (this.options.ellipsis && sl > this.options.minimumCountSelected) { $span.removeClass('placeholder').text(`${textSelects.slice(0, this.options.minimumCountSelected) .join(this.options.displayDelimiter)}...`) } else if (this.options.formatCountSelected() && sl > this.options.minimumCountSelected) { $span.removeClass('placeholder').html(this.options.formatCountSelected( sl, this.$selectItems.length + this.$disableItems.length )) } else { $span.removeClass('placeholder').text(textSelects.join(this.options.displayDelimiter)) } if (this.options.displayTitle) { $span.prop('title', this.getSelects('text')) } // set selects to select this.$el.val(this.getSelects()) // add selected class to selected li this.$drop.find('li').removeClass('selected') this.$drop.find('input:checked').each((i, el) => { $(el).parents('li').first().addClass('selected') }) // trigger <select> change event if (!ignoreTrigger) { this.$el.trigger('change') } } updateSelectAll (isInit) { let $items = this.$selectItems if (!isInit) { $items = $items.filter(':visible') } this.$selectAll.prop('checked', $items.length && $items.length === $items.filter(':checked').length) if (!isInit && this.$selectAll.prop('checked')) { this.options.onCheckAll() } } updateOptGroupSelect (isInit) { let $items = this.$selectItems if (!isInit) { $items = $items.filter(':visible') } $.each(this.$selectGroups, (i, val) => { const group = $(val).parent()[0].getAttribute('data-group') const $children = $items.filter(sprintf`[data-group="${s}"]`(group)) $(val).prop('checked', $children.length && $children.length === $children.filter(':checked').length) }) } // value or text, default: 'value' getSelects (type) { let texts = [] const values = [] this.$drop.find(sprintf`input[${s}]:checked`(this.selectItemName)).each((i, el) => { texts.push($(el).parents('li').first().text()) values.push($(el).val()) }) if (type === 'text' && this.$selectGroups.length) { texts = [] this.$selectGroups.each((i, el) => { const html = [] const text = $.trim($(el).parent().text()) const group = $(el).parent().data('group') const $children = this.$drop.find(sprintf`[${s}][data-group="${s}"]`( this.selectItemName, group )) const $selected = $children.filter(':checked') if (!$selected.length) { return } html.push('[') html.push(text) if ($children.length > $selected.length) { const list = [] $selected.each((j, elem) => { list.push($(elem).parent().text()) }) html.push(`: ${list.join(', ')}`) } html.push(']') texts.push(html.join('')) }) } return type === 'text' ? texts : values } setSelects (values) { this.$selectItems.prop('checked', false) this.$disableItems.prop('checked', false) $.each(values, (i, value) => { this.$selectItems.filter(sprintf`[value="${s}"]`(value)).prop('checked', true) this.$disableItems.filter(sprintf`[value="${s}"]`(value)).prop('checked', true) }) this.$selectAll.prop('checked', this.$selectItems.length === this.$selectItems.filter(':checked').length + this.$disableItems.filter(':checked').length) $.each(this.$selectGroups, (i, val) => { const group = $(val).parent()[0].getAttribute('data-group') const $children = this.$selectItems.filter(`[data-group="${group}"]`) $(val).prop('checked', $children.length && $children.length === $children.filter(':checked').length) }) this.update(false) } enable () { this.$choice.removeClass('disabled') } disable () { this.$choice.addClass('disabled') } checkAll () { this.$selectItems.prop('checked', true) this.$selectGroups.prop('checked', true) this.$selectAll.prop('checked', true) this.update() this.options.onCheckAll() } uncheckAll () { this.$selectItems.prop('checked', false) this.$selectGroups.prop('checked', false) this.$selectAll.prop('checked', false) this.update() this.options.onUncheckAll() } focus () { this.$choice.focus() this.options.onFocus() } blur () { this.$choice.blur() this.options.onBlur() } refresh () { this.initDrop() } filter () { const text = $.trim(this.$searchInput.val()).toLowerCase() if (text.length === 0) { this.$selectAll.closest('li').show() this.$selectItems.closest('li').show() this.$disableItems.closest('li').show() this.$selectGroups.closest('li').show() this.$noResults.hide() } else { if (!this.options.filterGroup) { this.$selectItems.each((i, el) => { const $parent = $(el).parent() const hasText = removeDiacritics($parent.text().toLowerCase()) .includes(removeDiacritics(text)) $parent.closest('li')[hasText ? 'show' : 'hide']() }) } this.$disableItems.parent().hide() this.$selectGroups.each((i, el) => { const $parent = $(el).parent() const group = $parent[0].getAttribute('data-group') if (this.options.filterGroup) { const hasText = removeDiacritics($parent.text().toLowerCase()) .includes(removeDiacritics(text)) const func = hasText ? 'show' : 'hide' $parent.closest('li')[func]() this.$selectItems.filter(`[data-group="${group}"]`).closest('li')[func]() } else { const $items = this.$selectItems.filter(':visible') const hasText = $items.filter(sprintf`[data-group="${s}"]`(group)).length $parent.closest('li')[hasText ? 'show' : 'hide']() } }) // Check if no matches found if (this.$selectItems.parent().filter(':visible').length) { this.$selectAll.closest('li').show() this.$noResults.hide() } else { this.$selectAll.closest('li').hide() this.$noResults.show() } } this.updateOptGroupSelect() this.updateSelectAll() this.options.onFilter(text) } destroy () { this.$el.before(this.$parent).show() this.$parent.remove() } } const defaults = { name: '', placeholder: '', selectAll: true, single: false, multiple: false, hideOptgroupCheckboxes: false, multipleWidth: 80, width: undefined, dropWidth: undefined, maxHeight: 250, position: 'bottom', displayValues: false, displayTitle: false, displayDelimiter: ', ', minimumCountSelected: 3, ellipsis: false, isOpen: false, keepOpen: false, openOnHover: false, container: null, filter: false, filterGroup: false, filterPlaceholder: '', filterAcceptOnEnter: false, animate: undefined, styler () { return false }, textTemplate ($elm) { return $elm[0].innerHTML }, labelTemplate ($elm) { return $elm[0].getAttribute('label') }, formatSelectAll () { return '[Select all]' }, formatAllSelected () { return 'All selected' }, formatCountSelected (count, total) { return count + ' of ' + total + ' selected' }, formatNoMatchesFound () { return 'No matches found' }, onOpen () { return false }, onClose () { return false }, onCheckAll () { return false }, onUncheckAll () { return false }, onFocus () { return false }, onBlur () { return false }, onOptgroupClick () { return false }, onClick () { return false }, onFilter () { return false }, onAfterCreate () { return false } } export default MultipleSelect
Revert refresh method updated
src/MultipleSelect.js
Revert refresh method updated
<ide><path>rc/MultipleSelect.js <ide> this.options.onAfterCreate() <ide> } <ide> <del> initDrop () { <add> init () { <ide> const $ul = $('<ul></ul>') <ide> <ide> this.$drop.html('') <ide> <ide> this.$drop.find('ul').css('max-height', `${this.options.maxHeight}px`) <ide> this.$drop.find('.multiple').css('width', `${this.options.multipleWidth}px`) <del> } <del> <del> init () { <del> this.initDrop() <ide> <ide> this.$searchInput = this.$drop.find('.ms-search input') <ide> this.$selectAll = this.$drop.find(`input[${this.selectAllName}]`) <ide> } <ide> <ide> refresh () { <del> this.initDrop() <add> this.init() <ide> } <ide> <ide> filter () {
Java
mit
error: pathspec 'SplitArrayLargestSum.java' did not match any file(s) known to git
62a0f61a9c92b66e3e14bef140839c26a400f37e
1
fang19911030/Leetcode,fang19911030/Leetcode
public class Solution{ Map<String, Integer> map; int[][] sumMap; public int splitArray(int[]nums, int m){ map = new HashMap<>(); sumMap = new int[nums.length][nums.length]; for(int i=0;i<nums.length;i++){ int sum = 0; for(int j=i;j<nums.length;j++){ sum+=nums[j]; dp[i][j] = sum; } } return helper(nums,m,0,nums.length-1); } private int helper(int[] nums,int m, int low, int high){ String key = String.format("%d#%d#%d",low, high,m); if(m == 1){ int sum = sumMap[low][high]; map.put(key,sum); return sum; } if(map.containsKey(key)){ return map.get(key); } int max = Integer.MAX_VALUE; for(int i=low;i<=hight-m+1;i++){ int tmp = Math.max(sumMap[low][i],helper(nums,m-1,i+1,high)); max = Math.min(tmp, max); } map.put(key, max); return max; } public int splitArray2(int[] nums, int m) { int max = 0; long sum = 0; for(int num:nums){ sum+=num; max = Math.max(num,max); } if(m == 1) return (int)sum; long l = max; long r = sum; while(l<=r){ long mid = (l+r)/2; if(valid(mid,nums,m)){ r = mid-1; }else{ l = mid+1; } } return (int)l; } private boolean valid(long mid, int[] nums, int m){ int count=1; long total=0; for(int num:nums){ total+= num; if(total >mid){ total = num; count++; if(count>m){ return false; } } } return true; } }
SplitArrayLargestSum.java
An interesting question
SplitArrayLargestSum.java
An interesting question
<ide><path>plitArrayLargestSum.java <add>public class Solution{ <add> Map<String, Integer> map; <add> int[][] sumMap; <add> public int splitArray(int[]nums, int m){ <add> map = new HashMap<>(); <add> sumMap = new int[nums.length][nums.length]; <add> for(int i=0;i<nums.length;i++){ <add> int sum = 0; <add> for(int j=i;j<nums.length;j++){ <add> sum+=nums[j]; <add> dp[i][j] = sum; <add> } <add> } <add> return helper(nums,m,0,nums.length-1); <add> } <add> <add> private int helper(int[] nums,int m, int low, int high){ <add> String key = String.format("%d#%d#%d",low, high,m); <add> if(m == 1){ <add> int sum = sumMap[low][high]; <add> map.put(key,sum); <add> return sum; <add> } <add> <add> if(map.containsKey(key)){ <add> return map.get(key); <add> } <add> int max = Integer.MAX_VALUE; <add> <add> for(int i=low;i<=hight-m+1;i++){ <add> int tmp = Math.max(sumMap[low][i],helper(nums,m-1,i+1,high)); <add> max = Math.min(tmp, max); <add> } <add> map.put(key, max); <add> return max; <add> } <add> <add> public int splitArray2(int[] nums, int m) { <add> int max = 0; <add> long sum = 0; <add> for(int num:nums){ <add> sum+=num; <add> max = Math.max(num,max); <add> } <add> if(m == 1) return (int)sum; <add> <add> long l = max; <add> long r = sum; <add> while(l<=r){ <add> long mid = (l+r)/2; <add> if(valid(mid,nums,m)){ <add> r = mid-1; <add> }else{ <add> l = mid+1; <add> } <add> } <add> return (int)l; <add> } <add> <add> private boolean valid(long mid, int[] nums, int m){ <add> int count=1; <add> long total=0; <add> for(int num:nums){ <add> total+= num; <add> if(total >mid){ <add> total = num; <add> count++; <add> if(count>m){ <add> return false; <add> } <add> } <add> } <add> return true; <add> } <add> <add> <add>}
Java
apache-2.0
87912811adbe37649eca2c4e362497e65d66dc94
0
SpineEventEngine/core-java,SpineEventEngine/core-java,SpineEventEngine/core-java
/* * Copyright 2017, TeamDev Ltd. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.spine3.server.projection; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import com.google.protobuf.Duration; import com.google.protobuf.Message; import com.google.protobuf.Timestamp; import io.grpc.stub.StreamObserver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spine3.annotation.Internal; import org.spine3.base.Event; import org.spine3.base.EventContext; import org.spine3.envelope.EventEnvelope; import org.spine3.server.BoundedContext; import org.spine3.server.entity.EntityStorageConverter; import org.spine3.server.entity.EventDispatchingRepository; import org.spine3.server.entity.idfunc.EventTargetsFunction; import org.spine3.server.entity.storage.EntityRecordWithColumns; import org.spine3.server.event.EventFilter; import org.spine3.server.event.EventStore; import org.spine3.server.event.EventStreamQuery; import org.spine3.server.stand.Stand; import org.spine3.server.storage.RecordStorage; import org.spine3.server.storage.StorageFactory; import org.spine3.server.tenant.AllTenantOperation; import org.spine3.type.EventClass; import org.spine3.type.TypeName; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Collection; import java.util.Map; import java.util.Set; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; /** * Abstract base for repositories managing {@link Projection}s. * * @param <I> the type of IDs of projections * @param <P> the type of projections * @param <S> the type of projection state messages * @author Alexander Yevsyukov */ public abstract class ProjectionRepository<I, P extends Projection<I, S, ?>, S extends Message> extends EventDispatchingRepository<I, P, S> { /** The {@code BoundedContext} in which this repository works. */ private final BoundedContext boundedContext; /** An instance of {@link Stand} to be informed about state updates */ private final Stand stand; /** * If {@code true} the projection repository will start the {@linkplain #catchUp() catch up} * process after {@linkplain #initStorage(StorageFactory) initialization}. */ private final boolean catchUpAfterStorageInit; private final Duration catchUpMaxDuration; /** The current status of the repository. */ private Status status = Status.CREATED; /** An underlying entity storage used to store projections. */ private RecordStorage<I> recordStorage; @Nullable private BulkWriteOperation<I, P> ongoingOperation; /** * Creates a {@code ProjectionRepository} for the given {@link BoundedContext} instance and * enables catching up after the storage initialization. * * <p>NOTE: The {@link #catchUp()} will be called automatically after * the storage is {@linkplain #initStorage(StorageFactory) initialized}. * To override this behavior, please use * {@link #ProjectionRepository(BoundedContext, boolean, Duration)} constructor. * * @param boundedContext the target {@code BoundedContext} */ protected ProjectionRepository(BoundedContext boundedContext) { this(boundedContext, true); } /** * Creates a {@code ProjectionRepository} for the given {@link BoundedContext} instance. * * <p>If {@code catchUpAfterStorageInit} is set to {@code true}, * the {@link #catchUp()} will be called automatically after the * {@link #initStorage(StorageFactory)} call is performed. * * @param boundedContext the target {@code BoundedContext} * @param catchUpAfterStorageInit whether the automatic catch-up should be performed after * storage initialization */ @SuppressWarnings("MethodParameterNamingConvention") protected ProjectionRepository(BoundedContext boundedContext, boolean catchUpAfterStorageInit) { this(boundedContext, catchUpAfterStorageInit, Duration.getDefaultInstance()); } /** * Creates a {@code ProjectionRepository} for the given {@link BoundedContext} instance. * * <p>If {@code catchUpAfterStorageInit} is set to {@code true}, the {@link #catchUp()} * will be called automatically after the storage is {@linkplain #initStorage(StorageFactory) * initialized}. * * <p>If the passed {@code catchUpMaxDuration} is not default, the repository uses a * {@link BulkWriteOperation} to accumulate the read projections and then save them as * a single bulk of records. * * <p>The {@code catchUpMaxDuration} represents the maximum time span for the catch-up to read * the events and apply them to corresponding projections. If the reading process takes longer * then this time, the the read will be automatically finished and all the result projections * will be flushed to the storage as a bulk. * * @param boundedContext the target {@code BoundedContext} * @param catchUpAfterStorageInit whether the automatic catch-up should be performed after * storage initialization * @param catchUpMaxDuration the maximum duration of the catch-up */ @SuppressWarnings("MethodParameterNamingConvention") protected ProjectionRepository(BoundedContext boundedContext, boolean catchUpAfterStorageInit, Duration catchUpMaxDuration) { super(EventDispatchingRepository.<I>producerFromContext()); this.boundedContext = boundedContext; this.stand = boundedContext.getStand(); this.catchUpAfterStorageInit = catchUpAfterStorageInit; this.catchUpMaxDuration = checkNotNull(catchUpMaxDuration); } /** Returns the {@link BoundedContext} in which this repository works. */ BoundedContext getBoundedContext() { return boundedContext; } /** Obtains {@link EventStore} from which to get events during catch-up. */ EventStore getEventStore() { return boundedContext.getEventBus() .getEventStore(); } /** * {@inheritDoc} * * <p>Overrides to open the method to the {@code beam} package. */ @Override protected EventTargetsFunction<I, Message> getIdSetFunction() { return super.getIdSetFunction(); } /** * {@inheritDoc} * * <p>Overrides to open the method to the package. */ @Override protected Class<I> getIdClass() { return super.getIdClass(); } /** * Obtains event filters for event classes handled by projections of this repository. */ Set<EventFilter> createEventFilters() { final ImmutableSet.Builder<EventFilter> builder = ImmutableSet.builder(); final Set<EventClass> eventClasses = getMessageClasses(); for (EventClass eventClass : eventClasses) { final String typeName = TypeName.of(eventClass.value()) .value(); builder.add(EventFilter.newBuilder() .setEventType(typeName) .build()); } return builder.build(); } @VisibleForTesting static Timestamp nullToDefault(@Nullable Timestamp timestamp) { return timestamp == null ? Timestamp.getDefaultInstance() : timestamp; } private static Logger log() { return LogSingleton.INSTANCE.value; } protected Status getStatus() { return status; } protected void setStatus(Status status) { this.status = status; } protected boolean isOnline() { return this.status == Status.ONLINE; } /** * {@inheritDoc} * <p>Overrides to open the method to the package. */ @Override protected EntityStorageConverter<I, P, S> entityConverter() { return super.entityConverter(); } @Override @SuppressWarnings("MethodDoesntCallSuperMethod" /* We do not call super.createStorage() because we create a specific type of a storage, not a regular entity storage created in the parent. */) protected RecordStorage<I> createStorage(StorageFactory factory) { final Class<P> projectionClass = getEntityClass(); final ProjectionStorage<I> projectionStorage = factory.createProjectionStorage(projectionClass); this.recordStorage = projectionStorage.recordStorage(); return projectionStorage; } /** * Ensures that the repository has the storage. * * @return storage instance * @throws IllegalStateException if the storage is null */ @Override @Nonnull @SuppressWarnings("MethodDoesntCallSuperMethod") protected RecordStorage<I> recordStorage() { return checkStorage(recordStorage); } /** {@inheritDoc} */ @Override public void initStorage(StorageFactory factory) { super.initStorage(factory); setStatus(Status.STORAGE_ASSIGNED); if (catchUpAfterStorageInit) { log().debug("Storage assigned. {} is starting to catch-up", getClass()); catchUp(); } } /** {@inheritDoc} */ @Override public void close() { super.close(); setStatus(Status.CLOSED); } /** * Ensures that the repository has the storage. * * @return storage instance * @throws IllegalStateException if the storage is null */ @Nonnull protected ProjectionStorage<I> projectionStorage() { @SuppressWarnings("unchecked") // It is safe to cast as we control the creation in createStorage(). final ProjectionStorage<I> storage = (ProjectionStorage<I>) getStorage(); return checkStorage(storage); } /** {@inheritDoc} */ @Override public Set<EventClass> getMessageClasses() { final Class<? extends Projection> projectionClass = getEntityClass(); final Set<EventClass> result = Projection.TypeInfo.getEventClasses(projectionClass); return result; } /** * Dispatches the passed event to corresponding {@link Projection}s if the repository is * in {@link Status#ONLINE}. * * <p>If the repository in another status the event is not dispatched. This is needed to * preserve the chronological sequence of events delivered to the repository, while it's * updating projections using the {@link #catchUp()} call. * * <p>The ID of the projection must be specified as the first property of the passed event. * * <p>If there is no stored projection with the ID from the event, a new projection is created * and stored after it handles the passed event. * * @param eventEnvelope the event to dispatch packed into an envelope * @see #catchUp() * @see Projection#handle(Message, EventContext) */ @SuppressWarnings("MethodDoesntCallSuperMethod") // We call indirectly via `internalDispatch()`. @Override public void dispatch(EventEnvelope eventEnvelope) { if (!isOnline()) { log().trace("Ignoring event {} while repository is not in {} status", eventEnvelope.getOuterObject(), Status.ONLINE); return; } internalDispatch(eventEnvelope); } @VisibleForTesting void dispatch(Event event) { dispatch(EventEnvelope.of(event)); } @Override protected void dispatchToEntity(I id, Message eventMessage, EventContext context) { final P projection = findOrCreate(id); final ProjectionTransaction<I, ?, ?> tx = ProjectionTransaction.start((Projection<I, ?, ?>) projection); projection.handle(eventMessage, context); tx.commit(); if (projection.isChanged()) { final Timestamp eventTime = context.getTimestamp(); if (isBulkWriteInProgress()) { storePostponed(projection, eventTime); } else { storeNow(projection, eventTime); } // Do not post to stand during CatchUp. if (getStatus() != Status.CATCHING_UP) { stand.post(projection, context.getCommandContext()); } } } /** * Dispatches the passed event to projections without checking the status. */ private void internalDispatch(EventEnvelope envelope) { super.dispatch(envelope); } private void storeNow(P projection, Timestamp eventTime) { store(projection); projectionStorage().writeLastHandledEventTime(eventTime); } private void storePostponed(P projection, Timestamp eventTime) { checkState(ongoingOperation != null, "Unable to store postponed projection: ongoingOperation is null."); ongoingOperation.storeProjection(projection); ongoingOperation.storeLastHandledEventTime(eventTime); } /** * Store a number of projections at a time. * * @param projections {@link Projection} bulk to store */ @VisibleForTesting void store(Collection<P> projections) { final RecordStorage<I> storage = recordStorage(); final Map<I, EntityRecordWithColumns> records = Maps.newHashMapWithExpectedSize(projections.size()); for (P projection : projections) { final I id = projection.getId(); final EntityRecordWithColumns record = toRecord(projection); records.put(id, record); } storage.write(records); } /** * Updates projections from the event stream obtained from {@code EventStore}. */ public void catchUp() { setStatus(Status.CATCHING_UP); allTenantOpCatchup(); // BeamCatchUp.catchUp(this); completeCatchUp(); logCatchUpComplete(); } @Internal public void writeLastHandledEventTime(Timestamp timestamp) { projectionStorage().writeLastHandledEventTime(timestamp); } @Internal public Timestamp readLastHandledEventTime() { return projectionStorage().readLastHandledEventTime(); } @SuppressWarnings("unused") // A direct catch-up impl. Do not delete until Beam-based catch-up is finished. private void allTenantOpCatchup() { final AllTenantOperation op = new AllTenantOperation(boundedContext.getTenantIndex()) { @Override public void run() { final EventStreamQuery query = createStreamQuery(); getEventStore().read(query, new EventStreamObserver(ProjectionRepository.this)); } }; op.execute(); } EventStreamQuery createStreamQuery() { final Set<EventFilter> eventFilters = createEventFilters(); // Get the timestamp of the last event. This also ensures we have the storage. final Timestamp timestamp = nullToDefault( projectionStorage().readLastHandledEventTime()); return EventStreamQuery.newBuilder() .setAfter(timestamp) .addAllFilter(eventFilters) .build(); } private void completeCatchUp() { setOnline(); } private void logCatchUpComplete() { if (log().isInfoEnabled()) { final Class<? extends ProjectionRepository> repositoryClass = getClass(); log().info("{} catch-up complete", repositoryClass.getName()); } } /** * Sets the repository online bypassing the catch-up from the {@code EventStore}. */ public void setOnline() { setStatus(Status.ONLINE); } private boolean isBulkWriteInProgress() { return ongoingOperation != null && ongoingOperation.isInProgress(); } private boolean isBulkWriteRequired() { return !catchUpMaxDuration.equals( catchUpMaxDuration.getDefaultInstanceForType()); } private BulkWriteOperation startBulkWrite(Duration expirationTime) { final BulkWriteOperation<I, P> bulkWriteOperation = new BulkWriteOperation<>( expirationTime, new PendingDataFlushTask<>(this)); this.ongoingOperation = bulkWriteOperation; return bulkWriteOperation; } /** * The enumeration of statuses in which a Projection Repository can be during its lifecycle. */ protected enum Status { /** * The repository instance has been created. * * <p>In this status the storage is not yet assigned. */ CREATED, /** * A storage has been assigned to the repository. */ STORAGE_ASSIGNED, /** * The repository is getting events from EventStore and builds projections. */ CATCHING_UP, /** * The repository completed the catch-up process. */ ONLINE, /** * The repository is closed and no longer accept events. */ CLOSED } private enum LogSingleton { INSTANCE; @SuppressWarnings("NonSerializableFieldInSerializableClass") private final Logger value = LoggerFactory.getLogger(ProjectionRepository.class); } /** * The stream observer which redirects events from {@code EventStore} to * the associated {@code ProjectionRepository}. */ private static class EventStreamObserver implements StreamObserver<Event> { private final ProjectionRepository repository; private BulkWriteOperation operation; private EventStreamObserver(ProjectionRepository repository) { this.repository = repository; } @Override public void onNext(Event event) { if (repository.status != Status.CATCHING_UP) { // The repository is catching up. // Skip all the events and perform {@code #onCompleted}. log().info("The catch-up is completing due to an overtime. Skipping event {}.", event); return; } if (repository.isBulkWriteRequired()) { if (!repository.isBulkWriteInProgress()) { operation = repository.startBulkWrite(repository.catchUpMaxDuration); } // `flush` the data if the operation expires. operation.checkExpiration(); if (!operation.isInProgress()) { // Expired. End now return; } } repository.internalDispatch(EventEnvelope.of(event)); } @Override public void onError(Throwable throwable) { log().error("Error obtaining events from EventStore.", throwable); } @Override public void onCompleted() { if (repository.isBulkWriteInProgress()) { operation.complete(); } } } /** * Implementation of the {@link BulkWriteOperation.FlushCallback} for storing * the projections and the last handled event time into the {@link ProjectionRepository}. */ private static class PendingDataFlushTask<I, P extends Projection<I, S, ?>, S extends Message> implements BulkWriteOperation.FlushCallback<P> { private final ProjectionRepository<I, P, S> repository; private PendingDataFlushTask(ProjectionRepository<I, P, S> repository) { this.repository = repository; } @Override public void onFlushResults(Set<P> projections, Timestamp lastHandledEventTime) { repository.store(projections); repository.projectionStorage() .writeLastHandledEventTime(lastHandledEventTime); repository.completeCatchUp(); } } /* * Beam support *************************/ @Override public ProjectionRepositoryIO<I, P, S> getIO() { return new ProjectionRepositoryIO<>(projectionStorage().getIO(getIdClass()), entityConverter()); } }
server/src/main/java/org/spine3/server/projection/ProjectionRepository.java
/* * Copyright 2017, TeamDev Ltd. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.spine3.server.projection; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import com.google.protobuf.Duration; import com.google.protobuf.Message; import com.google.protobuf.Timestamp; import io.grpc.stub.StreamObserver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spine3.annotation.Internal; import org.spine3.base.Event; import org.spine3.base.EventContext; import org.spine3.envelope.EventEnvelope; import org.spine3.server.BoundedContext; import org.spine3.server.entity.EntityStorageConverter; import org.spine3.server.entity.EventDispatchingRepository; import org.spine3.server.entity.idfunc.EventTargetsFunction; import org.spine3.server.entity.storage.EntityRecordWithColumns; import org.spine3.server.event.EventFilter; import org.spine3.server.event.EventStore; import org.spine3.server.event.EventStreamQuery; import org.spine3.server.stand.Stand; import org.spine3.server.storage.RecordStorage; import org.spine3.server.storage.StorageFactory; import org.spine3.server.tenant.AllTenantOperation; import org.spine3.type.EventClass; import org.spine3.type.TypeName; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Collection; import java.util.Map; import java.util.Set; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; /** * Abstract base for repositories managing {@link Projection}s. * * @param <I> the type of IDs of projections * @param <P> the type of projections * @param <S> the type of projection state messages * @author Alexander Yevsyukov */ public abstract class ProjectionRepository<I, P extends Projection<I, S, ?>, S extends Message> extends EventDispatchingRepository<I, P, S> { /** The {@code BoundedContext} in which this repository works. */ private final BoundedContext boundedContext; /** An instance of {@link Stand} to be informed about state updates */ private final Stand stand; /** * If {@code true} the projection repository will start the {@linkplain #catchUp() catch up} * process after {@linkplain #initStorage(StorageFactory) initialization}. */ private final boolean catchUpAfterStorageInit; private final Duration catchUpMaxDuration; /** The current status of the repository. */ private Status status = Status.CREATED; /** An underlying entity storage used to store projections. */ private RecordStorage<I> recordStorage; @Nullable private BulkWriteOperation<I, P> ongoingOperation; /** * Creates a {@code ProjectionRepository} for the given {@link BoundedContext} instance and * enables catching up after the storage initialization. * * <p>NOTE: The {@link #catchUp()} will be called automatically after * the storage is {@linkplain #initStorage(StorageFactory) initialized}. * To override this behavior, please use * {@link #ProjectionRepository(BoundedContext, boolean, Duration)} constructor. * * @param boundedContext the target {@code BoundedContext} */ protected ProjectionRepository(BoundedContext boundedContext) { this(boundedContext, true); } /** * Creates a {@code ProjectionRepository} for the given {@link BoundedContext} instance. * * <p>If {@code catchUpAfterStorageInit} is set to {@code true}, * the {@link #catchUp()} will be called automatically after the * {@link #initStorage(StorageFactory)} call is performed. * * @param boundedContext the target {@code BoundedContext} * @param catchUpAfterStorageInit whether the automatic catch-up should be performed after * storage initialization */ @SuppressWarnings("MethodParameterNamingConvention") protected ProjectionRepository(BoundedContext boundedContext, boolean catchUpAfterStorageInit) { this(boundedContext, catchUpAfterStorageInit, Duration.getDefaultInstance()); } /** * Creates a {@code ProjectionRepository} for the given {@link BoundedContext} instance. * * <p>If {@code catchUpAfterStorageInit} is set to {@code true}, the {@link #catchUp()} * will be called automatically after the storage is {@linkplain #initStorage(StorageFactory) * initialized}. * * <p>If the passed {@code catchUpMaxDuration} is not default, the repository uses a * {@link BulkWriteOperation} to accumulate the read projections and then save them as * a single bulk of records. * * <p>The {@code catchUpMaxDuration} represents the maximum time span for the catch-up to read * the events and apply them to corresponding projections. If the reading process takes longer * then this time, the the read will be automatically finished and all the result projections * will be flushed to the storage as a bulk. * * @param boundedContext the target {@code BoundedContext} * @param catchUpAfterStorageInit whether the automatic catch-up should be performed after * storage initialization * @param catchUpMaxDuration the maximum duration of the catch-up */ @SuppressWarnings("MethodParameterNamingConvention") protected ProjectionRepository(BoundedContext boundedContext, boolean catchUpAfterStorageInit, Duration catchUpMaxDuration) { super(EventDispatchingRepository.<I>producerFromContext()); this.boundedContext = boundedContext; this.stand = boundedContext.getStand(); this.catchUpAfterStorageInit = catchUpAfterStorageInit; this.catchUpMaxDuration = checkNotNull(catchUpMaxDuration); } /** Returns the {@link BoundedContext} in which this repository works. */ BoundedContext getBoundedContext() { return boundedContext; } /** Obtains {@link EventStore} from which to get events during catch-up. */ EventStore getEventStore() { return boundedContext.getEventBus() .getEventStore(); } /** * {@inheritDoc} * * <p>Overrides to open the method to the {@code beam} package. */ @Override protected EventTargetsFunction<I, Message> getIdSetFunction() { return super.getIdSetFunction(); } /** * {@inheritDoc} * * <p>Overrides to open the method to the package. */ @Override protected Class<I> getIdClass() { return super.getIdClass(); } /** * Obtains event filters for event classes handled by projections of this repository. */ Set<EventFilter> createEventFilters() { final ImmutableSet.Builder<EventFilter> builder = ImmutableSet.builder(); final Set<EventClass> eventClasses = getMessageClasses(); for (EventClass eventClass : eventClasses) { final String typeName = TypeName.of(eventClass.value()) .value(); builder.add(EventFilter.newBuilder() .setEventType(typeName) .build()); } return builder.build(); } @VisibleForTesting static Timestamp nullToDefault(@Nullable Timestamp timestamp) { return timestamp == null ? Timestamp.getDefaultInstance() : timestamp; } private static Logger log() { return LogSingleton.INSTANCE.value; } protected Status getStatus() { return status; } protected void setStatus(Status status) { this.status = status; } protected boolean isOnline() { return this.status == Status.ONLINE; } /** * {@inheritDoc} * <p>Overrides to open the method to the package. */ @Override protected EntityStorageConverter<I, P, S> entityConverter() { return super.entityConverter(); } @Override @SuppressWarnings("MethodDoesntCallSuperMethod" /* We do not call super.createStorage() because we create a specific type of a storage, not a regular entity storage created in the parent. */) protected RecordStorage<I> createStorage(StorageFactory factory) { final Class<P> projectionClass = getEntityClass(); final ProjectionStorage<I> projectionStorage = factory.createProjectionStorage(projectionClass); this.recordStorage = projectionStorage.recordStorage(); return projectionStorage; } /** * Ensures that the repository has the storage. * * @return storage instance * @throws IllegalStateException if the storage is null */ @Override @Nonnull @SuppressWarnings("MethodDoesntCallSuperMethod") protected RecordStorage<I> recordStorage() { return checkStorage(recordStorage); } /** {@inheritDoc} */ @Override public void initStorage(StorageFactory factory) { super.initStorage(factory); setStatus(Status.STORAGE_ASSIGNED); if (catchUpAfterStorageInit) { log().debug("Storage assigned. {} is starting to catch-up", getClass()); catchUp(); } } /** {@inheritDoc} */ @Override public void close() { super.close(); setStatus(Status.CLOSED); } /** * Ensures that the repository has the storage. * * @return storage instance * @throws IllegalStateException if the storage is null */ @Nonnull protected ProjectionStorage<I> projectionStorage() { @SuppressWarnings("unchecked") // It is safe to cast as we control the creation in createStorage(). final ProjectionStorage<I> storage = (ProjectionStorage<I>) getStorage(); return checkStorage(storage); } /** {@inheritDoc} */ @Override public Set<EventClass> getMessageClasses() { final Class<? extends Projection> projectionClass = getEntityClass(); final Set<EventClass> result = Projection.TypeInfo.getEventClasses(projectionClass); return result; } /** * Dispatches the passed event to corresponding {@link Projection}s if the repository is * in {@link Status#ONLINE}. * * <p>If the repository in another status the event is not dispatched. This is needed to * preserve the chronological sequence of events delivered to the repository, while it's * updating projections using the {@link #catchUp()} call. * * <p>The ID of the projection must be specified as the first property of the passed event. * * <p>If there is no stored projection with the ID from the event, a new projection is created * and stored after it handles the passed event. * * @param eventEnvelope the event to dispatch packed into an envelope * @see #catchUp() * @see Projection#handle(Message, EventContext) */ @SuppressWarnings("MethodDoesntCallSuperMethod") // We call indirectly via `internalDispatch()`. @Override public void dispatch(EventEnvelope eventEnvelope) { if (!isOnline()) { log().trace("Ignoring event {} while repository is not in {} status", eventEnvelope.getOuterObject(), Status.ONLINE); return; } internalDispatch(eventEnvelope); } @VisibleForTesting void dispatch(Event event) { dispatch(EventEnvelope.of(event)); } @Override protected void dispatchToEntity(I id, Message eventMessage, EventContext context) { final P projection = findOrCreate(id); final ProjectionTransaction<I, ?, ?> tx = ProjectionTransaction.start((Projection<I, ?, ?>) projection); projection.handle(eventMessage, context); tx.commit(); if (projection.isChanged()) { final Timestamp eventTime = context.getTimestamp(); if (isBulkWriteInProgress()) { storePostponed(projection, eventTime); } else { storeNow(projection, eventTime); } // Do not post to stand during CatchUp. if (getStatus() != Status.CATCHING_UP) { stand.post(projection, context.getCommandContext()); } } } /** * Dispatches the passed event to projections without checking the status. */ private void internalDispatch(EventEnvelope envelope) { super.dispatch(envelope); } private void storeNow(P projection, Timestamp eventTime) { store(projection); projectionStorage().writeLastHandledEventTime(eventTime); } private void storePostponed(P projection, Timestamp eventTime) { checkState(ongoingOperation != null, "Unable to store postponed projection: ongoingOperation is null."); ongoingOperation.storeProjection(projection); ongoingOperation.storeLastHandledEventTime(eventTime); } /** * Store a number of projections at a time. * * @param projections {@link Projection} bulk to store */ @VisibleForTesting void store(Collection<P> projections) { final RecordStorage<I> storage = recordStorage(); final Map<I, EntityRecordWithColumns> records = Maps.newHashMapWithExpectedSize(projections.size()); for (P projection : projections) { final I id = projection.getId(); final EntityRecordWithColumns record = toRecord(projection); records.put(id, record); } storage.write(records); } /** * Updates projections from the event stream obtained from {@code EventStore}. */ public void catchUp() { setStatus(Status.CATCHING_UP); // allTenantOpCatchup(); BeamCatchUp.catchUp(this); completeCatchUp(); logCatchUpComplete(); } @Internal public void writeLastHandledEventTime(Timestamp timestamp) { projectionStorage().writeLastHandledEventTime(timestamp); } @Internal public Timestamp readLastHandledEventTime() { return projectionStorage().readLastHandledEventTime(); } @SuppressWarnings("unused") // A direct catch-up impl. Do not delete until Beam-based catch-up is finished. private void allTenantOpCatchup() { final AllTenantOperation op = new AllTenantOperation(boundedContext.getTenantIndex()) { @Override public void run() { final EventStreamQuery query = createStreamQuery(); getEventStore().read(query, new EventStreamObserver(ProjectionRepository.this)); } }; op.execute(); } EventStreamQuery createStreamQuery() { final Set<EventFilter> eventFilters = createEventFilters(); // Get the timestamp of the last event. This also ensures we have the storage. final Timestamp timestamp = nullToDefault( projectionStorage().readLastHandledEventTime()); return EventStreamQuery.newBuilder() .setAfter(timestamp) .addAllFilter(eventFilters) .build(); } private void completeCatchUp() { setOnline(); } private void logCatchUpComplete() { if (log().isInfoEnabled()) { final Class<? extends ProjectionRepository> repositoryClass = getClass(); log().info("{} catch-up complete", repositoryClass.getName()); } } /** * Sets the repository online bypassing the catch-up from the {@code EventStore}. */ public void setOnline() { setStatus(Status.ONLINE); } private boolean isBulkWriteInProgress() { return ongoingOperation != null && ongoingOperation.isInProgress(); } private boolean isBulkWriteRequired() { return !catchUpMaxDuration.equals( catchUpMaxDuration.getDefaultInstanceForType()); } private BulkWriteOperation startBulkWrite(Duration expirationTime) { final BulkWriteOperation<I, P> bulkWriteOperation = new BulkWriteOperation<>( expirationTime, new PendingDataFlushTask<>(this)); this.ongoingOperation = bulkWriteOperation; return bulkWriteOperation; } /** * The enumeration of statuses in which a Projection Repository can be during its lifecycle. */ protected enum Status { /** * The repository instance has been created. * * <p>In this status the storage is not yet assigned. */ CREATED, /** * A storage has been assigned to the repository. */ STORAGE_ASSIGNED, /** * The repository is getting events from EventStore and builds projections. */ CATCHING_UP, /** * The repository completed the catch-up process. */ ONLINE, /** * The repository is closed and no longer accept events. */ CLOSED } private enum LogSingleton { INSTANCE; @SuppressWarnings("NonSerializableFieldInSerializableClass") private final Logger value = LoggerFactory.getLogger(ProjectionRepository.class); } /** * The stream observer which redirects events from {@code EventStore} to * the associated {@code ProjectionRepository}. */ private static class EventStreamObserver implements StreamObserver<Event> { private final ProjectionRepository repository; private BulkWriteOperation operation; private EventStreamObserver(ProjectionRepository repository) { this.repository = repository; } @Override public void onNext(Event event) { if (repository.status != Status.CATCHING_UP) { // The repository is catching up. // Skip all the events and perform {@code #onCompleted}. log().info("The catch-up is completing due to an overtime. Skipping event {}.", event); return; } if (repository.isBulkWriteRequired()) { if (!repository.isBulkWriteInProgress()) { operation = repository.startBulkWrite(repository.catchUpMaxDuration); } // `flush` the data if the operation expires. operation.checkExpiration(); if (!operation.isInProgress()) { // Expired. End now return; } } repository.internalDispatch(EventEnvelope.of(event)); } @Override public void onError(Throwable throwable) { log().error("Error obtaining events from EventStore.", throwable); } @Override public void onCompleted() { if (repository.isBulkWriteInProgress()) { operation.complete(); } } } /** * Implementation of the {@link BulkWriteOperation.FlushCallback} for storing * the projections and the last handled event time into the {@link ProjectionRepository}. */ private static class PendingDataFlushTask<I, P extends Projection<I, S, ?>, S extends Message> implements BulkWriteOperation.FlushCallback<P> { private final ProjectionRepository<I, P, S> repository; private PendingDataFlushTask(ProjectionRepository<I, P, S> repository) { this.repository = repository; } @Override public void onFlushResults(Set<P> projections, Timestamp lastHandledEventTime) { repository.store(projections); repository.projectionStorage() .writeLastHandledEventTime(lastHandledEventTime); repository.completeCatchUp(); } } /* * Beam support *************************/ @Override public ProjectionRepositoryIO<I, P, S> getIO() { return new ProjectionRepositoryIO<>(projectionStorage().getIO(getIdClass()), entityConverter()); } }
Temporarily switch to old catch-up
server/src/main/java/org/spine3/server/projection/ProjectionRepository.java
Temporarily switch to old catch-up
<ide><path>erver/src/main/java/org/spine3/server/projection/ProjectionRepository.java <ide> public void catchUp() { <ide> setStatus(Status.CATCHING_UP); <ide> <del>// allTenantOpCatchup(); <del> BeamCatchUp.catchUp(this); <add> allTenantOpCatchup(); <add>// BeamCatchUp.catchUp(this); <ide> <ide> completeCatchUp(); <ide> logCatchUpComplete();
Java
apache-2.0
5efcca57e031e954fe9a9b9c8610b0f27f4d1900
0
apache/shiro,feige712/shiro,feige712/shiro,apache/shiro
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.shiro.config.ogdl; import java.beans.PropertyDescriptor; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.beanutils.BeanUtilsBean; import org.apache.commons.beanutils.ConvertUtilsBean; import org.apache.commons.beanutils.SuppressPropertiesBeanIntrospector; import org.apache.shiro.lang.codec.Base64; import org.apache.shiro.lang.codec.Hex; import org.apache.shiro.config.ConfigurationException; import org.apache.shiro.config.ogdl.event.BeanEvent; import org.apache.shiro.config.ogdl.event.ConfiguredBeanEvent; import org.apache.shiro.config.ogdl.event.DestroyedBeanEvent; import org.apache.shiro.config.ogdl.event.InitializedBeanEvent; import org.apache.shiro.config.ogdl.event.InstantiatedBeanEvent; import org.apache.shiro.event.EventBus; import org.apache.shiro.event.EventBusAware; import org.apache.shiro.event.Subscribe; import org.apache.shiro.event.support.DefaultEventBus; import org.apache.shiro.lang.util.Assert; import org.apache.shiro.lang.util.ByteSource; import org.apache.shiro.lang.util.ClassUtils; import org.apache.shiro.lang.util.Factory; import org.apache.shiro.lang.util.LifecycleUtils; import org.apache.shiro.lang.util.Nameable; import org.apache.shiro.lang.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Object builder that uses reflection and Apache Commons BeanUtils to build objects given a * map of "property values". Typically these come from the Shiro INI configuration and are used * to construct or modify the SecurityManager, its dependencies, and web-based security filters. * <p/> * Recognizes {@link Factory} implementations and will call * {@link org.apache.shiro.lang.util.Factory#getInstance() getInstance} to satisfy any reference to this bean. * * @since 0.9 */ public class ReflectionBuilder { //TODO - complete JavaDoc private static final Logger log = LoggerFactory.getLogger(ReflectionBuilder.class); private static final String OBJECT_REFERENCE_BEGIN_TOKEN = "$"; private static final String ESCAPED_OBJECT_REFERENCE_BEGIN_TOKEN = "\\$"; private static final String GLOBAL_PROPERTY_PREFIX = "shiro"; private static final char MAP_KEY_VALUE_DELIMITER = ':'; private static final String HEX_BEGIN_TOKEN = "0x"; private static final String NULL_VALUE_TOKEN = "null"; private static final String EMPTY_STRING_VALUE_TOKEN = "\"\""; private static final char STRING_VALUE_DELIMETER = '"'; private static final char MAP_PROPERTY_BEGIN_TOKEN = '['; private static final char MAP_PROPERTY_END_TOKEN = ']'; private static final String EVENT_BUS_NAME = "eventBus"; private final Map<String, Object> objects; /** * Interpolation allows for ${key} substitution of values. * @since 1.4 */ private Interpolator interpolator; /** * @since 1.3 */ private EventBus eventBus; /** * Keeps track of event subscribers that were automatically registered by this ReflectionBuilder during * object construction. This is used in case a new EventBus is discovered during object graph * construction: upon discovery of the new EventBus, the existing subscribers will be unregistered from the * old EventBus and then re-registered with the new EventBus. * * @since 1.3 */ private final Map<String,Object> registeredEventSubscribers; /** * @since 1.4 */ private final BeanUtilsBean beanUtilsBean; //@since 1.3 private Map<String,Object> createDefaultObjectMap() { Map<String,Object> map = new LinkedHashMap<String, Object>(); map.put(EVENT_BUS_NAME, new DefaultEventBus()); return map; } public ReflectionBuilder() { this(null); } public ReflectionBuilder(Map<String, ?> defaults) { // SHIRO-619 // SHIRO-739 beanUtilsBean = new BeanUtilsBean(new ConvertUtilsBean() { @Override public Object convert(String value, Class clazz) { if (clazz.isEnum()){ return Enum.valueOf(clazz, value); }else{ return super.convert(value, clazz); } } }); beanUtilsBean.getPropertyUtils().addBeanIntrospector(SuppressPropertiesBeanIntrospector.SUPPRESS_CLASS); this.interpolator = createInterpolator(); this.objects = createDefaultObjectMap(); this.registeredEventSubscribers = new LinkedHashMap<String,Object>(); apply(defaults); } private void apply(Map<String, ?> objects) { if(!isEmpty(objects)) { this.objects.putAll(objects); } EventBus found = findEventBus(this.objects); Assert.notNull(found, "An " + EventBus.class.getName() + " instance must be present in the object defaults"); enableEvents(found); } public Map<String, ?> getObjects() { return objects; } /** * @param objects */ public void setObjects(Map<String, ?> objects) { this.objects.clear(); this.objects.putAll(createDefaultObjectMap()); apply(objects); } //@since 1.3 private void enableEvents(EventBus eventBus) { Assert.notNull(eventBus, "EventBus argument cannot be null."); //clean up old auto-registered subscribers: for (Object subscriber : this.registeredEventSubscribers.values()) { this.eventBus.unregister(subscriber); } this.registeredEventSubscribers.clear(); this.eventBus = eventBus; for(Map.Entry<String,Object> entry : this.objects.entrySet()) { enableEventsIfNecessary(entry.getValue(), entry.getKey()); } } //@since 1.3 private void enableEventsIfNecessary(Object bean, String name) { boolean applied = applyEventBusIfNecessary(bean); if (!applied) { //if the event bus is applied, and the bean wishes to be a subscriber as well (not just a publisher), // we assume that the implementation registers itself with the event bus, i.e. eventBus.register(this); //if the event bus isn't applied, only then do we need to check to see if the bean is an event subscriber, // and if so, register it on the event bus automatically since it has no ability to do so itself: if (isEventSubscriber(bean, name)) { //found an event subscriber, so register them with the EventBus: this.eventBus.register(bean); this.registeredEventSubscribers.put(name, bean); } } } //@since 1.3 private boolean isEventSubscriber(Object bean, String name) { List annotatedMethods = ClassUtils.getAnnotatedMethods(bean.getClass(), Subscribe.class); return !isEmpty(annotatedMethods); } //@since 1.3 protected EventBus findEventBus(Map<String,?> objects) { if (isEmpty(objects)) { return null; } //prefer a named object first: Object value = objects.get(EVENT_BUS_NAME); if (value != null && value instanceof EventBus) { return (EventBus)value; } //couldn't find a named 'eventBus' EventBus object. Try to find the first typed value we can: for( Object v : objects.values()) { if (v instanceof EventBus) { return (EventBus)v; } } return null; } private boolean applyEventBusIfNecessary(Object value) { if (value instanceof EventBusAware) { ((EventBusAware)value).setEventBus(this.eventBus); return true; } return false; } public Object getBean(String id) { return objects.get(id); } @SuppressWarnings({"unchecked"}) public <T> T getBean(String id, Class<T> requiredType) { if (requiredType == null) { throw new NullPointerException("requiredType argument cannot be null."); } Object bean = getBean(id); if (bean == null) { return null; } Assert.state(requiredType.isAssignableFrom(bean.getClass()), "Bean with id [" + id + "] is not of the required type [" + requiredType.getName() + "]."); return (T) bean; } private String parseBeanId(String lhs) { Assert.notNull(lhs); if (lhs.indexOf('.') < 0) { return lhs; } String classSuffix = ".class"; int index = lhs.indexOf(classSuffix); if (index >= 0) { return lhs.substring(0, index); } return null; } @SuppressWarnings({"unchecked"}) public Map<String, ?> buildObjects(Map<String, String> kvPairs) { if (kvPairs != null && !kvPairs.isEmpty()) { BeanConfigurationProcessor processor = new BeanConfigurationProcessor(); for (Map.Entry<String, String> entry : kvPairs.entrySet()) { String lhs = entry.getKey(); String rhs = interpolator.interpolate(entry.getValue()); String beanId = parseBeanId(lhs); if (beanId != null) { //a beanId could be parsed, so the line is a bean instance definition processor.add(new InstantiationStatement(beanId, rhs)); } else { //the line must be a property configuration processor.add(new AssignmentStatement(lhs, rhs)); } } processor.execute(); //SHIRO-778: onInit method on AuthenticatingRealm is called twice objects.keySet().stream() .filter(key -> !kvPairs.containsKey(key)) .forEach(key -> LifecycleUtils.init(objects.get(key))); } else { //SHIRO-413: init method must be called for constructed objects that are Initializable LifecycleUtils.init(objects.values()); } return objects; } public void destroy() { final Map<String, Object> immutableObjects = Collections.unmodifiableMap(objects); //destroy objects in the opposite order they were initialized: List<Map.Entry<String,?>> entries = new ArrayList<Map.Entry<String,?>>(objects.entrySet()); Collections.reverse(entries); for(Map.Entry<String, ?> entry: entries) { String id = entry.getKey(); Object bean = entry.getValue(); //don't destroy the eventbus until the end - we need it to still be 'alive' while publishing destroy events: if (bean != this.eventBus) { //memory equality check (not .equals) on purpose LifecycleUtils.destroy(bean); BeanEvent event = new DestroyedBeanEvent(id, bean, immutableObjects); eventBus.publish(event); this.eventBus.unregister(bean); //bean is now destroyed - it should not receive any other events } } //only now destroy the event bus: LifecycleUtils.destroy(this.eventBus); } protected void createNewInstance(Map<String, Object> objects, String name, String value) { Object currentInstance = objects.get(name); if (currentInstance != null) { log.info("An instance with name '{}' already exists. " + "Redefining this object as a new instance of type {}", name, value); } Object instance;//name with no property, assume right hand side of equals sign is the class name: try { instance = ClassUtils.newInstance(value); if (instance instanceof Nameable) { ((Nameable) instance).setName(name); } } catch (Exception e) { String msg = "Unable to instantiate class [" + value + "] for object named '" + name + "'. " + "Please ensure you've specified the fully qualified class name correctly."; throw new ConfigurationException(msg, e); } objects.put(name, instance); } protected void applyProperty(String key, String value, Map objects) { int index = key.indexOf('.'); if (index >= 0) { String name = key.substring(0, index); String property = key.substring(index + 1, key.length()); if (GLOBAL_PROPERTY_PREFIX.equalsIgnoreCase(name)) { applyGlobalProperty(objects, property, value); } else { applySingleProperty(objects, name, property, value); } } else { throw new IllegalArgumentException("All property keys must contain a '.' character. " + "(e.g. myBean.property = value) These should already be separated out by buildObjects()."); } } protected void applyGlobalProperty(Map objects, String property, String value) { for (Object instance : objects.values()) { try { PropertyDescriptor pd = beanUtilsBean.getPropertyUtils().getPropertyDescriptor(instance, property); if (pd != null) { applyProperty(instance, property, value); } } catch (Exception e) { String msg = "Error retrieving property descriptor for instance " + "of type [" + instance.getClass().getName() + "] " + "while setting property [" + property + "]"; throw new ConfigurationException(msg, e); } } } protected void applySingleProperty(Map objects, String name, String property, String value) { Object instance = objects.get(name); if (property.equals("class")) { throw new IllegalArgumentException("Property keys should not contain 'class' properties since these " + "should already be separated out by buildObjects()."); } else if (instance == null) { String msg = "Configuration error. Specified object [" + name + "] with property [" + property + "] without first defining that object's class. Please first " + "specify the class property first, e.g. myObject = fully_qualified_class_name " + "and then define additional properties."; throw new IllegalArgumentException(msg); } else { applyProperty(instance, property, value); } } protected boolean isReference(String value) { return value != null && value.startsWith(OBJECT_REFERENCE_BEGIN_TOKEN); } protected String getId(String referenceToken) { return referenceToken.substring(OBJECT_REFERENCE_BEGIN_TOKEN.length()); } protected Object getReferencedObject(String id) { Object o = objects != null && !objects.isEmpty() ? objects.get(id) : null; if (o == null) { String msg = "The object with id [" + id + "] has not yet been defined and therefore cannot be " + "referenced. Please ensure objects are defined in the order in which they should be " + "created and made available for future reference."; throw new UnresolveableReferenceException(msg); } return o; } protected String unescapeIfNecessary(String value) { if (value != null && value.startsWith(ESCAPED_OBJECT_REFERENCE_BEGIN_TOKEN)) { return value.substring(ESCAPED_OBJECT_REFERENCE_BEGIN_TOKEN.length() - 1); } return value; } protected Object resolveReference(String reference) { String id = getId(reference); log.debug("Encountered object reference '{}'. Looking up object with id '{}'", reference, id); final Object referencedObject = getReferencedObject(id); if (referencedObject instanceof Factory) { return ((Factory) referencedObject).getInstance(); } return referencedObject; } protected boolean isTypedProperty(Object object, String propertyName, Class clazz) { if (clazz == null) { throw new NullPointerException("type (class) argument cannot be null."); } try { PropertyDescriptor descriptor = beanUtilsBean.getPropertyUtils().getPropertyDescriptor(object, propertyName); if (descriptor == null) { String msg = "Property '" + propertyName + "' does not exist for object of " + "type " + object.getClass().getName() + "."; throw new ConfigurationException(msg); } Class propertyClazz = descriptor.getPropertyType(); return clazz.isAssignableFrom(propertyClazz); } catch (ConfigurationException ce) { //let it propagate: throw ce; } catch (Exception e) { String msg = "Unable to determine if property [" + propertyName + "] represents a " + clazz.getName(); throw new ConfigurationException(msg, e); } } protected Set<?> toSet(String sValue) { String[] tokens = StringUtils.split(sValue); if (tokens == null || tokens.length <= 0) { return null; } //SHIRO-423: check to see if the value is a referenced Set already, and if so, return it immediately: if (tokens.length == 1 && isReference(tokens[0])) { Object reference = resolveReference(tokens[0]); if (reference instanceof Set) { return (Set)reference; } } Set<String> setTokens = new LinkedHashSet<String>(Arrays.asList(tokens)); //now convert into correct values and/or references: Set<Object> values = new LinkedHashSet<Object>(setTokens.size()); for (String token : setTokens) { Object value = resolveValue(token); values.add(value); } return values; } protected Map<?, ?> toMap(String sValue) { String[] tokens = StringUtils.split(sValue, StringUtils.DEFAULT_DELIMITER_CHAR, StringUtils.DEFAULT_QUOTE_CHAR, StringUtils.DEFAULT_QUOTE_CHAR, true, true); if (tokens == null || tokens.length <= 0) { return null; } //SHIRO-423: check to see if the value is a referenced Map already, and if so, return it immediately: if (tokens.length == 1 && isReference(tokens[0])) { Object reference = resolveReference(tokens[0]); if (reference instanceof Map) { return (Map)reference; } } Map<String, String> mapTokens = new LinkedHashMap<String, String>(tokens.length); for (String token : tokens) { String[] kvPair = StringUtils.split(token, MAP_KEY_VALUE_DELIMITER); if (kvPair == null || kvPair.length != 2) { String msg = "Map property value [" + sValue + "] contained key-value pair token [" + token + "] that does not properly split to a single key and pair. This must be the " + "case for all map entries."; throw new ConfigurationException(msg); } mapTokens.put(kvPair[0], kvPair[1]); } //now convert into correct values and/or references: Map<Object, Object> map = new LinkedHashMap<Object, Object>(mapTokens.size()); for (Map.Entry<String, String> entry : mapTokens.entrySet()) { Object key = resolveValue(entry.getKey()); Object value = resolveValue(entry.getValue()); map.put(key, value); } return map; } // @since 1.2.2 protected Collection<?> toCollection(String sValue) { String[] tokens = StringUtils.split(sValue); if (tokens == null || tokens.length <= 0) { return null; } //SHIRO-423: check to see if the value is a referenced Collection already, and if so, return it immediately: if (tokens.length == 1 && isReference(tokens[0])) { Object reference = resolveReference(tokens[0]); if (reference instanceof Collection) { return (Collection)reference; } } //now convert into correct values and/or references: List<Object> values = new ArrayList<Object>(tokens.length); for (String token : tokens) { Object value = resolveValue(token); values.add(value); } return values; } protected List<?> toList(String sValue) { String[] tokens = StringUtils.split(sValue); if (tokens == null || tokens.length <= 0) { return null; } //SHIRO-423: check to see if the value is a referenced List already, and if so, return it immediately: if (tokens.length == 1 && isReference(tokens[0])) { Object reference = resolveReference(tokens[0]); if (reference instanceof List) { return (List)reference; } } //now convert into correct values and/or references: List<Object> values = new ArrayList<Object>(tokens.length); for (String token : tokens) { Object value = resolveValue(token); values.add(value); } return values; } protected byte[] toBytes(String sValue) { if (sValue == null) { return null; } byte[] bytes; if (sValue.startsWith(HEX_BEGIN_TOKEN)) { String hex = sValue.substring(HEX_BEGIN_TOKEN.length()); bytes = Hex.decode(hex); } else { //assume base64 encoded: bytes = Base64.decode(sValue); } return bytes; } protected Object resolveValue(String stringValue) { Object value; if (isReference(stringValue)) { value = resolveReference(stringValue); } else { value = unescapeIfNecessary(stringValue); } return value; } protected String checkForNullOrEmptyLiteral(String stringValue) { if (stringValue == null) { return null; } //check if the value is the actual literal string 'null' (expected to be wrapped in quotes): if (stringValue.equals("\"null\"")) { return NULL_VALUE_TOKEN; } //or the actual literal string of two quotes '""' (expected to be wrapped in quotes): else if (stringValue.equals("\"\"\"\"")) { return EMPTY_STRING_VALUE_TOKEN; } else { return stringValue; } } protected void applyProperty(Object object, String propertyPath, Object value) { int mapBegin = propertyPath.indexOf(MAP_PROPERTY_BEGIN_TOKEN); int mapEnd = -1; String mapPropertyPath = null; String keyString = null; String remaining = null; if (mapBegin >= 0) { //a map is being referenced in the overall property path. Find just the map's path: mapPropertyPath = propertyPath.substring(0, mapBegin); //find the end of the map reference: mapEnd = propertyPath.indexOf(MAP_PROPERTY_END_TOKEN, mapBegin); //find the token in between the [ and the ] (the map/array key or index): keyString = propertyPath.substring(mapBegin+1, mapEnd); //find out if there is more path reference to follow. If not, we're at a terminal of the OGNL expression if (propertyPath.length() > (mapEnd+1)) { remaining = propertyPath.substring(mapEnd+1); if (remaining.startsWith(".")) { remaining = StringUtils.clean(remaining.substring(1)); } } } if (remaining == null) { //we've terminated the OGNL expression. Check to see if we're assigning a property or a map entry: if (keyString == null) { //not a map or array value assignment - assign the property directly: setProperty(object, propertyPath, value); } else { //we're assigning a map or array entry. Check to see which we should call: if (isTypedProperty(object, mapPropertyPath, Map.class)) { Map map = (Map)getProperty(object, mapPropertyPath); Object mapKey = resolveValue(keyString); //noinspection unchecked map.put(mapKey, value); } else { //must be an array property. Convert the key string to an index: int index = Integer.valueOf(keyString); setIndexedProperty(object, mapPropertyPath, index, value); } } } else { //property is being referenced as part of a nested path. Find the referenced map/array entry and //recursively call this method with the remaining property path Object referencedValue = null; if (isTypedProperty(object, mapPropertyPath, Map.class)) { Map map = (Map)getProperty(object, mapPropertyPath); Object mapKey = resolveValue(keyString); referencedValue = map.get(mapKey); } else { //must be an array property: int index = Integer.valueOf(keyString); referencedValue = getIndexedProperty(object, mapPropertyPath, index); } if (referencedValue == null) { throw new ConfigurationException("Referenced map/array value '" + mapPropertyPath + "[" + keyString + "]' does not exist."); } applyProperty(referencedValue, remaining, value); } } private void setProperty(Object object, String propertyPath, Object value) { try { if (log.isTraceEnabled()) { log.trace("Applying property [{}] value [{}] on object of type [{}]", new Object[]{propertyPath, value, object.getClass().getName()}); } beanUtilsBean.setProperty(object, propertyPath, value); } catch (Exception e) { String msg = "Unable to set property '" + propertyPath + "' with value [" + value + "] on object " + "of type " + (object != null ? object.getClass().getName() : null) + ". If " + "'" + value + "' is a reference to another (previously defined) object, prefix it with " + "'" + OBJECT_REFERENCE_BEGIN_TOKEN + "' to indicate that the referenced " + "object should be used as the actual value. " + "For example, " + OBJECT_REFERENCE_BEGIN_TOKEN + value; throw new ConfigurationException(msg, e); } } private Object getProperty(Object object, String propertyPath) { try { return beanUtilsBean.getPropertyUtils().getProperty(object, propertyPath); } catch (Exception e) { throw new ConfigurationException("Unable to access property '" + propertyPath + "'", e); } } private void setIndexedProperty(Object object, String propertyPath, int index, Object value) { try { beanUtilsBean.getPropertyUtils().setIndexedProperty(object, propertyPath, index, value); } catch (Exception e) { throw new ConfigurationException("Unable to set array property '" + propertyPath + "'", e); } } private Object getIndexedProperty(Object object, String propertyPath, int index) { try { return beanUtilsBean.getPropertyUtils().getIndexedProperty(object, propertyPath, index); } catch (Exception e) { throw new ConfigurationException("Unable to acquire array property '" + propertyPath + "'", e); } } protected boolean isIndexedPropertyAssignment(String propertyPath) { return propertyPath.endsWith("" + MAP_PROPERTY_END_TOKEN); } protected void applyProperty(Object object, String propertyName, String stringValue) { Object value; if (NULL_VALUE_TOKEN.equals(stringValue)) { value = null; } else if (EMPTY_STRING_VALUE_TOKEN.equals(stringValue)) { value = StringUtils.EMPTY_STRING; } else if (isIndexedPropertyAssignment(propertyName)) { String checked = checkForNullOrEmptyLiteral(stringValue); value = resolveValue(checked); } else if (isTypedProperty(object, propertyName, Set.class)) { value = toSet(stringValue); } else if (isTypedProperty(object, propertyName, Map.class)) { value = toMap(stringValue); } else if (isTypedProperty(object, propertyName, List.class)) { value = toList(stringValue); } else if (isTypedProperty(object, propertyName, Collection.class)) { value = toCollection(stringValue); } else if (isTypedProperty(object, propertyName, byte[].class)) { value = toBytes(stringValue); } else if (isTypedProperty(object, propertyName, ByteSource.class)) { byte[] bytes = toBytes(stringValue); value = ByteSource.Util.bytes(bytes); } else { String checked = checkForNullOrEmptyLiteral(stringValue); value = resolveValue(checked); } applyProperty(object, propertyName, value); } private Interpolator createInterpolator() { if (ClassUtils.isAvailable("org.apache.commons.configuration2.interpol.ConfigurationInterpolator")) { return new CommonsInterpolator(); } return new DefaultInterpolator(); } /** * Sets the {@link Interpolator} used when evaluating the right side of the expressions. * @since 1.4 */ public void setInterpolator(Interpolator interpolator) { this.interpolator = interpolator; } private class BeanConfigurationProcessor { private final List<Statement> statements = new ArrayList<Statement>(); private final List<BeanConfiguration> beanConfigurations = new ArrayList<BeanConfiguration>(); public void add(Statement statement) { statements.add(statement); //we execute bean configuration statements in the order they are declared. if (statement instanceof InstantiationStatement) { InstantiationStatement is = (InstantiationStatement)statement; beanConfigurations.add(new BeanConfiguration(is)); } else { AssignmentStatement as = (AssignmentStatement)statement; //statements always apply to the most recently defined bean configuration with the same name, so we //have to traverse the configuration list starting at the end (most recent elements are appended): boolean addedToConfig = false; String beanName = as.getRootBeanName(); for( int i = beanConfigurations.size()-1; i >= 0; i--) { BeanConfiguration mostRecent = beanConfigurations.get(i); String mostRecentBeanName = mostRecent.getBeanName(); if (beanName.equals(mostRecentBeanName)) { mostRecent.add(as); addedToConfig = true; break; } } if (!addedToConfig) { // the AssignmentStatement must be for an existing bean that does not yet have a corresponding // configuration object (this would happen if the bean is in the default objects map). Because // BeanConfiguration instances don't exist for default (already instantiated) beans, // we simulate a creation of one to satisfy this processors implementation: beanConfigurations.add(new BeanConfiguration(as)); } } } public void execute() { for( Statement statement : statements) { statement.execute(); BeanConfiguration bd = statement.getBeanConfiguration(); if (bd.isExecuted()) { //bean is fully configured, no more statements to execute for it: //bean configured overrides the 'eventBus' bean - replace the existing eventBus with the one configured: if (bd.getBeanName().equals(EVENT_BUS_NAME)) { EventBus eventBus = (EventBus)bd.getBean(); enableEvents(eventBus); } //ignore global 'shiro.' shortcut mechanism: if (!bd.isGlobalConfig()) { BeanEvent event = new ConfiguredBeanEvent(bd.getBeanName(), bd.getBean(), Collections.unmodifiableMap(objects)); eventBus.publish(event); } //initialize the bean if necessary: LifecycleUtils.init(bd.getBean()); //ignore global 'shiro.' shortcut mechanism: if (!bd.isGlobalConfig()) { BeanEvent event = new InitializedBeanEvent(bd.getBeanName(), bd.getBean(), Collections.unmodifiableMap(objects)); eventBus.publish(event); } } } } } private class BeanConfiguration { private final InstantiationStatement instantiationStatement; private final List<AssignmentStatement> assignments = new ArrayList<AssignmentStatement>(); private final String beanName; private Object bean; private BeanConfiguration(InstantiationStatement statement) { statement.setBeanConfiguration(this); this.instantiationStatement = statement; this.beanName = statement.lhs; } private BeanConfiguration(AssignmentStatement as) { this.instantiationStatement = null; this.beanName = as.getRootBeanName(); add(as); } public String getBeanName() { return this.beanName; } public boolean isGlobalConfig() { //BeanConfiguration instance representing the global 'shiro.' properties // (we should remove this concept). return GLOBAL_PROPERTY_PREFIX.equals(getBeanName()); } public void add(AssignmentStatement as) { as.setBeanConfiguration(this); assignments.add(as); } /** * When this configuration is parsed sufficiently to create (or find) an actual bean instance, that instance * will be associated with its configuration by setting it via this method. * * @param bean the bean instantiated (or found) that corresponds to this BeanConfiguration instance. */ public void setBean(Object bean) { this.bean = bean; } public Object getBean() { return this.bean; } /** * Returns true if all configuration statements have been executed. * @return true if all configuration statements have been executed. */ public boolean isExecuted() { if (instantiationStatement != null && !instantiationStatement.isExecuted()) { return false; } for (AssignmentStatement as : assignments) { if (!as.isExecuted()) { return false; } } return true; } } private abstract class Statement { protected final String lhs; protected final String rhs; protected Object bean; private Object result; private boolean executed; private BeanConfiguration beanConfiguration; private Statement(String lhs, String rhs) { this.lhs = lhs; this.rhs = rhs; this.executed = false; } public void setBeanConfiguration(BeanConfiguration bd) { this.beanConfiguration = bd; } public BeanConfiguration getBeanConfiguration() { return this.beanConfiguration; } public Object execute() { if (!isExecuted()) { this.result = doExecute(); this.executed = true; } if (!getBeanConfiguration().isGlobalConfig()) { Assert.notNull(this.bean, "Implementation must set the root bean for which it executed."); } return this.result; } public Object getBean() { return this.bean; } protected void setBean(Object bean) { this.bean = bean; if (this.beanConfiguration.getBean() == null) { this.beanConfiguration.setBean(bean); } } public Object getResult() { return result; } protected abstract Object doExecute(); public boolean isExecuted() { return executed; } } private class InstantiationStatement extends Statement { private InstantiationStatement(String lhs, String rhs) { super(lhs, rhs); } @Override protected Object doExecute() { String beanName = this.lhs; createNewInstance(objects, beanName, this.rhs); Object instantiated = objects.get(beanName); setBean(instantiated); //also ensure the instantiated bean has access to the event bus or is subscribed to events if necessary: //Note: because events are being enabled on this bean here (before the instantiated event below is //triggered), beans can react to their own instantiation events. enableEventsIfNecessary(instantiated, beanName); BeanEvent event = new InstantiatedBeanEvent(beanName, instantiated, Collections.unmodifiableMap(objects)); eventBus.publish(event); return instantiated; } } private class AssignmentStatement extends Statement { private final String rootBeanName; private AssignmentStatement(String lhs, String rhs) { super(lhs, rhs); int index = lhs.indexOf('.'); this.rootBeanName = lhs.substring(0, index); } @Override protected Object doExecute() { applyProperty(lhs, rhs, objects); Object bean = objects.get(this.rootBeanName); setBean(bean); return null; } public String getRootBeanName() { return this.rootBeanName; } } ////////////////////////// // From CollectionUtils // ////////////////////////// // CollectionUtils cannot be removed from shiro-core until 2.0 as it has a dependency on PrincipalCollection private static boolean isEmpty(Map m) { return m == null || m.isEmpty(); } private static boolean isEmpty(Collection c) { return c == null || c.isEmpty(); } }
config/ogdl/src/main/java/org/apache/shiro/config/ogdl/ReflectionBuilder.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.shiro.config.ogdl; import java.beans.PropertyDescriptor; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.beanutils.BeanUtilsBean; import org.apache.commons.beanutils.ConvertUtilsBean; import org.apache.commons.beanutils.SuppressPropertiesBeanIntrospector; import org.apache.shiro.lang.codec.Base64; import org.apache.shiro.lang.codec.Hex; import org.apache.shiro.config.ConfigurationException; import org.apache.shiro.config.ogdl.event.BeanEvent; import org.apache.shiro.config.ogdl.event.ConfiguredBeanEvent; import org.apache.shiro.config.ogdl.event.DestroyedBeanEvent; import org.apache.shiro.config.ogdl.event.InitializedBeanEvent; import org.apache.shiro.config.ogdl.event.InstantiatedBeanEvent; import org.apache.shiro.event.EventBus; import org.apache.shiro.event.EventBusAware; import org.apache.shiro.event.Subscribe; import org.apache.shiro.event.support.DefaultEventBus; import org.apache.shiro.lang.util.Assert; import org.apache.shiro.lang.util.ByteSource; import org.apache.shiro.lang.util.ClassUtils; import org.apache.shiro.lang.util.Factory; import org.apache.shiro.lang.util.LifecycleUtils; import org.apache.shiro.lang.util.Nameable; import org.apache.shiro.lang.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Object builder that uses reflection and Apache Commons BeanUtils to build objects given a * map of "property values". Typically these come from the Shiro INI configuration and are used * to construct or modify the SecurityManager, its dependencies, and web-based security filters. * <p/> * Recognizes {@link Factory} implementations and will call * {@link org.apache.shiro.lang.util.Factory#getInstance() getInstance} to satisfy any reference to this bean. * * @since 0.9 */ public class ReflectionBuilder { //TODO - complete JavaDoc private static final Logger log = LoggerFactory.getLogger(ReflectionBuilder.class); private static final String OBJECT_REFERENCE_BEGIN_TOKEN = "$"; private static final String ESCAPED_OBJECT_REFERENCE_BEGIN_TOKEN = "\\$"; private static final String GLOBAL_PROPERTY_PREFIX = "shiro"; private static final char MAP_KEY_VALUE_DELIMITER = ':'; private static final String HEX_BEGIN_TOKEN = "0x"; private static final String NULL_VALUE_TOKEN = "null"; private static final String EMPTY_STRING_VALUE_TOKEN = "\"\""; private static final char STRING_VALUE_DELIMETER = '"'; private static final char MAP_PROPERTY_BEGIN_TOKEN = '['; private static final char MAP_PROPERTY_END_TOKEN = ']'; private static final String EVENT_BUS_NAME = "eventBus"; private final Map<String, Object> objects; /** * Interpolation allows for ${key} substitution of values. * @since 1.4 */ private Interpolator interpolator; /** * @since 1.3 */ private EventBus eventBus; /** * Keeps track of event subscribers that were automatically registered by this ReflectionBuilder during * object construction. This is used in case a new EventBus is discovered during object graph * construction: upon discovery of the new EventBus, the existing subscribers will be unregistered from the * old EventBus and then re-registered with the new EventBus. * * @since 1.3 */ private final Map<String,Object> registeredEventSubscribers; /** * @since 1.4 */ private final BeanUtilsBean beanUtilsBean; //@since 1.3 private Map<String,Object> createDefaultObjectMap() { Map<String,Object> map = new LinkedHashMap<String, Object>(); map.put(EVENT_BUS_NAME, new DefaultEventBus()); return map; } public ReflectionBuilder() { this(null); } public ReflectionBuilder(Map<String, ?> defaults) { // SHIRO-619 // SHIRO-739 beanUtilsBean = new BeanUtilsBean(new ConvertUtilsBean() { @Override public Object convert(String value, Class clazz) { if (clazz.isEnum()){ return Enum.valueOf(clazz, value); }else{ return super.convert(value, clazz); } } }); beanUtilsBean.getPropertyUtils().addBeanIntrospector(SuppressPropertiesBeanIntrospector.SUPPRESS_CLASS); this.interpolator = createInterpolator(); this.objects = createDefaultObjectMap(); this.registeredEventSubscribers = new LinkedHashMap<String,Object>(); apply(defaults); } private void apply(Map<String, ?> objects) { if(!isEmpty(objects)) { this.objects.putAll(objects); } EventBus found = findEventBus(this.objects); Assert.notNull(found, "An " + EventBus.class.getName() + " instance must be present in the object defaults"); enableEvents(found); } public Map<String, ?> getObjects() { return objects; } /** * @param objects */ public void setObjects(Map<String, ?> objects) { this.objects.clear(); this.objects.putAll(createDefaultObjectMap()); apply(objects); } //@since 1.3 private void enableEvents(EventBus eventBus) { Assert.notNull(eventBus, "EventBus argument cannot be null."); //clean up old auto-registered subscribers: for (Object subscriber : this.registeredEventSubscribers.values()) { this.eventBus.unregister(subscriber); } this.registeredEventSubscribers.clear(); this.eventBus = eventBus; for(Map.Entry<String,Object> entry : this.objects.entrySet()) { enableEventsIfNecessary(entry.getValue(), entry.getKey()); } } //@since 1.3 private void enableEventsIfNecessary(Object bean, String name) { boolean applied = applyEventBusIfNecessary(bean); if (!applied) { //if the event bus is applied, and the bean wishes to be a subscriber as well (not just a publisher), // we assume that the implementation registers itself with the event bus, i.e. eventBus.register(this); //if the event bus isn't applied, only then do we need to check to see if the bean is an event subscriber, // and if so, register it on the event bus automatically since it has no ability to do so itself: if (isEventSubscriber(bean, name)) { //found an event subscriber, so register them with the EventBus: this.eventBus.register(bean); this.registeredEventSubscribers.put(name, bean); } } } //@since 1.3 private boolean isEventSubscriber(Object bean, String name) { List annotatedMethods = ClassUtils.getAnnotatedMethods(bean.getClass(), Subscribe.class); return !isEmpty(annotatedMethods); } //@since 1.3 protected EventBus findEventBus(Map<String,?> objects) { if (isEmpty(objects)) { return null; } //prefer a named object first: Object value = objects.get(EVENT_BUS_NAME); if (value != null && value instanceof EventBus) { return (EventBus)value; } //couldn't find a named 'eventBus' EventBus object. Try to find the first typed value we can: for( Object v : objects.values()) { if (v instanceof EventBus) { return (EventBus)v; } } return null; } private boolean applyEventBusIfNecessary(Object value) { if (value instanceof EventBusAware) { ((EventBusAware)value).setEventBus(this.eventBus); return true; } return false; } public Object getBean(String id) { return objects.get(id); } @SuppressWarnings({"unchecked"}) public <T> T getBean(String id, Class<T> requiredType) { if (requiredType == null) { throw new NullPointerException("requiredType argument cannot be null."); } Object bean = getBean(id); if (bean == null) { return null; } Assert.state(requiredType.isAssignableFrom(bean.getClass()), "Bean with id [" + id + "] is not of the required type [" + requiredType.getName() + "]."); return (T) bean; } private String parseBeanId(String lhs) { Assert.notNull(lhs); if (lhs.indexOf('.') < 0) { return lhs; } String classSuffix = ".class"; int index = lhs.indexOf(classSuffix); if (index >= 0) { return lhs.substring(0, index); } return null; } @SuppressWarnings({"unchecked"}) public Map<String, ?> buildObjects(Map<String, String> kvPairs) { if (kvPairs != null && !kvPairs.isEmpty()) { BeanConfigurationProcessor processor = new BeanConfigurationProcessor(); for (Map.Entry<String, String> entry : kvPairs.entrySet()) { String lhs = entry.getKey(); String rhs = interpolator.interpolate(entry.getValue()); String beanId = parseBeanId(lhs); if (beanId != null) { //a beanId could be parsed, so the line is a bean instance definition processor.add(new InstantiationStatement(beanId, rhs)); } else { //the line must be a property configuration processor.add(new AssignmentStatement(lhs, rhs)); } } processor.execute(); } //SHIRO-413: init method must be called for constructed objects that are Initializable LifecycleUtils.init(objects.values()); return objects; } public void destroy() { final Map<String, Object> immutableObjects = Collections.unmodifiableMap(objects); //destroy objects in the opposite order they were initialized: List<Map.Entry<String,?>> entries = new ArrayList<Map.Entry<String,?>>(objects.entrySet()); Collections.reverse(entries); for(Map.Entry<String, ?> entry: entries) { String id = entry.getKey(); Object bean = entry.getValue(); //don't destroy the eventbus until the end - we need it to still be 'alive' while publishing destroy events: if (bean != this.eventBus) { //memory equality check (not .equals) on purpose LifecycleUtils.destroy(bean); BeanEvent event = new DestroyedBeanEvent(id, bean, immutableObjects); eventBus.publish(event); this.eventBus.unregister(bean); //bean is now destroyed - it should not receive any other events } } //only now destroy the event bus: LifecycleUtils.destroy(this.eventBus); } protected void createNewInstance(Map<String, Object> objects, String name, String value) { Object currentInstance = objects.get(name); if (currentInstance != null) { log.info("An instance with name '{}' already exists. " + "Redefining this object as a new instance of type {}", name, value); } Object instance;//name with no property, assume right hand side of equals sign is the class name: try { instance = ClassUtils.newInstance(value); if (instance instanceof Nameable) { ((Nameable) instance).setName(name); } } catch (Exception e) { String msg = "Unable to instantiate class [" + value + "] for object named '" + name + "'. " + "Please ensure you've specified the fully qualified class name correctly."; throw new ConfigurationException(msg, e); } objects.put(name, instance); } protected void applyProperty(String key, String value, Map objects) { int index = key.indexOf('.'); if (index >= 0) { String name = key.substring(0, index); String property = key.substring(index + 1, key.length()); if (GLOBAL_PROPERTY_PREFIX.equalsIgnoreCase(name)) { applyGlobalProperty(objects, property, value); } else { applySingleProperty(objects, name, property, value); } } else { throw new IllegalArgumentException("All property keys must contain a '.' character. " + "(e.g. myBean.property = value) These should already be separated out by buildObjects()."); } } protected void applyGlobalProperty(Map objects, String property, String value) { for (Object instance : objects.values()) { try { PropertyDescriptor pd = beanUtilsBean.getPropertyUtils().getPropertyDescriptor(instance, property); if (pd != null) { applyProperty(instance, property, value); } } catch (Exception e) { String msg = "Error retrieving property descriptor for instance " + "of type [" + instance.getClass().getName() + "] " + "while setting property [" + property + "]"; throw new ConfigurationException(msg, e); } } } protected void applySingleProperty(Map objects, String name, String property, String value) { Object instance = objects.get(name); if (property.equals("class")) { throw new IllegalArgumentException("Property keys should not contain 'class' properties since these " + "should already be separated out by buildObjects()."); } else if (instance == null) { String msg = "Configuration error. Specified object [" + name + "] with property [" + property + "] without first defining that object's class. Please first " + "specify the class property first, e.g. myObject = fully_qualified_class_name " + "and then define additional properties."; throw new IllegalArgumentException(msg); } else { applyProperty(instance, property, value); } } protected boolean isReference(String value) { return value != null && value.startsWith(OBJECT_REFERENCE_BEGIN_TOKEN); } protected String getId(String referenceToken) { return referenceToken.substring(OBJECT_REFERENCE_BEGIN_TOKEN.length()); } protected Object getReferencedObject(String id) { Object o = objects != null && !objects.isEmpty() ? objects.get(id) : null; if (o == null) { String msg = "The object with id [" + id + "] has not yet been defined and therefore cannot be " + "referenced. Please ensure objects are defined in the order in which they should be " + "created and made available for future reference."; throw new UnresolveableReferenceException(msg); } return o; } protected String unescapeIfNecessary(String value) { if (value != null && value.startsWith(ESCAPED_OBJECT_REFERENCE_BEGIN_TOKEN)) { return value.substring(ESCAPED_OBJECT_REFERENCE_BEGIN_TOKEN.length() - 1); } return value; } protected Object resolveReference(String reference) { String id = getId(reference); log.debug("Encountered object reference '{}'. Looking up object with id '{}'", reference, id); final Object referencedObject = getReferencedObject(id); if (referencedObject instanceof Factory) { return ((Factory) referencedObject).getInstance(); } return referencedObject; } protected boolean isTypedProperty(Object object, String propertyName, Class clazz) { if (clazz == null) { throw new NullPointerException("type (class) argument cannot be null."); } try { PropertyDescriptor descriptor = beanUtilsBean.getPropertyUtils().getPropertyDescriptor(object, propertyName); if (descriptor == null) { String msg = "Property '" + propertyName + "' does not exist for object of " + "type " + object.getClass().getName() + "."; throw new ConfigurationException(msg); } Class propertyClazz = descriptor.getPropertyType(); return clazz.isAssignableFrom(propertyClazz); } catch (ConfigurationException ce) { //let it propagate: throw ce; } catch (Exception e) { String msg = "Unable to determine if property [" + propertyName + "] represents a " + clazz.getName(); throw new ConfigurationException(msg, e); } } protected Set<?> toSet(String sValue) { String[] tokens = StringUtils.split(sValue); if (tokens == null || tokens.length <= 0) { return null; } //SHIRO-423: check to see if the value is a referenced Set already, and if so, return it immediately: if (tokens.length == 1 && isReference(tokens[0])) { Object reference = resolveReference(tokens[0]); if (reference instanceof Set) { return (Set)reference; } } Set<String> setTokens = new LinkedHashSet<String>(Arrays.asList(tokens)); //now convert into correct values and/or references: Set<Object> values = new LinkedHashSet<Object>(setTokens.size()); for (String token : setTokens) { Object value = resolveValue(token); values.add(value); } return values; } protected Map<?, ?> toMap(String sValue) { String[] tokens = StringUtils.split(sValue, StringUtils.DEFAULT_DELIMITER_CHAR, StringUtils.DEFAULT_QUOTE_CHAR, StringUtils.DEFAULT_QUOTE_CHAR, true, true); if (tokens == null || tokens.length <= 0) { return null; } //SHIRO-423: check to see if the value is a referenced Map already, and if so, return it immediately: if (tokens.length == 1 && isReference(tokens[0])) { Object reference = resolveReference(tokens[0]); if (reference instanceof Map) { return (Map)reference; } } Map<String, String> mapTokens = new LinkedHashMap<String, String>(tokens.length); for (String token : tokens) { String[] kvPair = StringUtils.split(token, MAP_KEY_VALUE_DELIMITER); if (kvPair == null || kvPair.length != 2) { String msg = "Map property value [" + sValue + "] contained key-value pair token [" + token + "] that does not properly split to a single key and pair. This must be the " + "case for all map entries."; throw new ConfigurationException(msg); } mapTokens.put(kvPair[0], kvPair[1]); } //now convert into correct values and/or references: Map<Object, Object> map = new LinkedHashMap<Object, Object>(mapTokens.size()); for (Map.Entry<String, String> entry : mapTokens.entrySet()) { Object key = resolveValue(entry.getKey()); Object value = resolveValue(entry.getValue()); map.put(key, value); } return map; } // @since 1.2.2 protected Collection<?> toCollection(String sValue) { String[] tokens = StringUtils.split(sValue); if (tokens == null || tokens.length <= 0) { return null; } //SHIRO-423: check to see if the value is a referenced Collection already, and if so, return it immediately: if (tokens.length == 1 && isReference(tokens[0])) { Object reference = resolveReference(tokens[0]); if (reference instanceof Collection) { return (Collection)reference; } } //now convert into correct values and/or references: List<Object> values = new ArrayList<Object>(tokens.length); for (String token : tokens) { Object value = resolveValue(token); values.add(value); } return values; } protected List<?> toList(String sValue) { String[] tokens = StringUtils.split(sValue); if (tokens == null || tokens.length <= 0) { return null; } //SHIRO-423: check to see if the value is a referenced List already, and if so, return it immediately: if (tokens.length == 1 && isReference(tokens[0])) { Object reference = resolveReference(tokens[0]); if (reference instanceof List) { return (List)reference; } } //now convert into correct values and/or references: List<Object> values = new ArrayList<Object>(tokens.length); for (String token : tokens) { Object value = resolveValue(token); values.add(value); } return values; } protected byte[] toBytes(String sValue) { if (sValue == null) { return null; } byte[] bytes; if (sValue.startsWith(HEX_BEGIN_TOKEN)) { String hex = sValue.substring(HEX_BEGIN_TOKEN.length()); bytes = Hex.decode(hex); } else { //assume base64 encoded: bytes = Base64.decode(sValue); } return bytes; } protected Object resolveValue(String stringValue) { Object value; if (isReference(stringValue)) { value = resolveReference(stringValue); } else { value = unescapeIfNecessary(stringValue); } return value; } protected String checkForNullOrEmptyLiteral(String stringValue) { if (stringValue == null) { return null; } //check if the value is the actual literal string 'null' (expected to be wrapped in quotes): if (stringValue.equals("\"null\"")) { return NULL_VALUE_TOKEN; } //or the actual literal string of two quotes '""' (expected to be wrapped in quotes): else if (stringValue.equals("\"\"\"\"")) { return EMPTY_STRING_VALUE_TOKEN; } else { return stringValue; } } protected void applyProperty(Object object, String propertyPath, Object value) { int mapBegin = propertyPath.indexOf(MAP_PROPERTY_BEGIN_TOKEN); int mapEnd = -1; String mapPropertyPath = null; String keyString = null; String remaining = null; if (mapBegin >= 0) { //a map is being referenced in the overall property path. Find just the map's path: mapPropertyPath = propertyPath.substring(0, mapBegin); //find the end of the map reference: mapEnd = propertyPath.indexOf(MAP_PROPERTY_END_TOKEN, mapBegin); //find the token in between the [ and the ] (the map/array key or index): keyString = propertyPath.substring(mapBegin+1, mapEnd); //find out if there is more path reference to follow. If not, we're at a terminal of the OGNL expression if (propertyPath.length() > (mapEnd+1)) { remaining = propertyPath.substring(mapEnd+1); if (remaining.startsWith(".")) { remaining = StringUtils.clean(remaining.substring(1)); } } } if (remaining == null) { //we've terminated the OGNL expression. Check to see if we're assigning a property or a map entry: if (keyString == null) { //not a map or array value assignment - assign the property directly: setProperty(object, propertyPath, value); } else { //we're assigning a map or array entry. Check to see which we should call: if (isTypedProperty(object, mapPropertyPath, Map.class)) { Map map = (Map)getProperty(object, mapPropertyPath); Object mapKey = resolveValue(keyString); //noinspection unchecked map.put(mapKey, value); } else { //must be an array property. Convert the key string to an index: int index = Integer.valueOf(keyString); setIndexedProperty(object, mapPropertyPath, index, value); } } } else { //property is being referenced as part of a nested path. Find the referenced map/array entry and //recursively call this method with the remaining property path Object referencedValue = null; if (isTypedProperty(object, mapPropertyPath, Map.class)) { Map map = (Map)getProperty(object, mapPropertyPath); Object mapKey = resolveValue(keyString); referencedValue = map.get(mapKey); } else { //must be an array property: int index = Integer.valueOf(keyString); referencedValue = getIndexedProperty(object, mapPropertyPath, index); } if (referencedValue == null) { throw new ConfigurationException("Referenced map/array value '" + mapPropertyPath + "[" + keyString + "]' does not exist."); } applyProperty(referencedValue, remaining, value); } } private void setProperty(Object object, String propertyPath, Object value) { try { if (log.isTraceEnabled()) { log.trace("Applying property [{}] value [{}] on object of type [{}]", new Object[]{propertyPath, value, object.getClass().getName()}); } beanUtilsBean.setProperty(object, propertyPath, value); } catch (Exception e) { String msg = "Unable to set property '" + propertyPath + "' with value [" + value + "] on object " + "of type " + (object != null ? object.getClass().getName() : null) + ". If " + "'" + value + "' is a reference to another (previously defined) object, prefix it with " + "'" + OBJECT_REFERENCE_BEGIN_TOKEN + "' to indicate that the referenced " + "object should be used as the actual value. " + "For example, " + OBJECT_REFERENCE_BEGIN_TOKEN + value; throw new ConfigurationException(msg, e); } } private Object getProperty(Object object, String propertyPath) { try { return beanUtilsBean.getPropertyUtils().getProperty(object, propertyPath); } catch (Exception e) { throw new ConfigurationException("Unable to access property '" + propertyPath + "'", e); } } private void setIndexedProperty(Object object, String propertyPath, int index, Object value) { try { beanUtilsBean.getPropertyUtils().setIndexedProperty(object, propertyPath, index, value); } catch (Exception e) { throw new ConfigurationException("Unable to set array property '" + propertyPath + "'", e); } } private Object getIndexedProperty(Object object, String propertyPath, int index) { try { return beanUtilsBean.getPropertyUtils().getIndexedProperty(object, propertyPath, index); } catch (Exception e) { throw new ConfigurationException("Unable to acquire array property '" + propertyPath + "'", e); } } protected boolean isIndexedPropertyAssignment(String propertyPath) { return propertyPath.endsWith("" + MAP_PROPERTY_END_TOKEN); } protected void applyProperty(Object object, String propertyName, String stringValue) { Object value; if (NULL_VALUE_TOKEN.equals(stringValue)) { value = null; } else if (EMPTY_STRING_VALUE_TOKEN.equals(stringValue)) { value = StringUtils.EMPTY_STRING; } else if (isIndexedPropertyAssignment(propertyName)) { String checked = checkForNullOrEmptyLiteral(stringValue); value = resolveValue(checked); } else if (isTypedProperty(object, propertyName, Set.class)) { value = toSet(stringValue); } else if (isTypedProperty(object, propertyName, Map.class)) { value = toMap(stringValue); } else if (isTypedProperty(object, propertyName, List.class)) { value = toList(stringValue); } else if (isTypedProperty(object, propertyName, Collection.class)) { value = toCollection(stringValue); } else if (isTypedProperty(object, propertyName, byte[].class)) { value = toBytes(stringValue); } else if (isTypedProperty(object, propertyName, ByteSource.class)) { byte[] bytes = toBytes(stringValue); value = ByteSource.Util.bytes(bytes); } else { String checked = checkForNullOrEmptyLiteral(stringValue); value = resolveValue(checked); } applyProperty(object, propertyName, value); } private Interpolator createInterpolator() { if (ClassUtils.isAvailable("org.apache.commons.configuration2.interpol.ConfigurationInterpolator")) { return new CommonsInterpolator(); } return new DefaultInterpolator(); } /** * Sets the {@link Interpolator} used when evaluating the right side of the expressions. * @since 1.4 */ public void setInterpolator(Interpolator interpolator) { this.interpolator = interpolator; } private class BeanConfigurationProcessor { private final List<Statement> statements = new ArrayList<Statement>(); private final List<BeanConfiguration> beanConfigurations = new ArrayList<BeanConfiguration>(); public void add(Statement statement) { statements.add(statement); //we execute bean configuration statements in the order they are declared. if (statement instanceof InstantiationStatement) { InstantiationStatement is = (InstantiationStatement)statement; beanConfigurations.add(new BeanConfiguration(is)); } else { AssignmentStatement as = (AssignmentStatement)statement; //statements always apply to the most recently defined bean configuration with the same name, so we //have to traverse the configuration list starting at the end (most recent elements are appended): boolean addedToConfig = false; String beanName = as.getRootBeanName(); for( int i = beanConfigurations.size()-1; i >= 0; i--) { BeanConfiguration mostRecent = beanConfigurations.get(i); String mostRecentBeanName = mostRecent.getBeanName(); if (beanName.equals(mostRecentBeanName)) { mostRecent.add(as); addedToConfig = true; break; } } if (!addedToConfig) { // the AssignmentStatement must be for an existing bean that does not yet have a corresponding // configuration object (this would happen if the bean is in the default objects map). Because // BeanConfiguration instances don't exist for default (already instantiated) beans, // we simulate a creation of one to satisfy this processors implementation: beanConfigurations.add(new BeanConfiguration(as)); } } } public void execute() { for( Statement statement : statements) { statement.execute(); BeanConfiguration bd = statement.getBeanConfiguration(); if (bd.isExecuted()) { //bean is fully configured, no more statements to execute for it: //bean configured overrides the 'eventBus' bean - replace the existing eventBus with the one configured: if (bd.getBeanName().equals(EVENT_BUS_NAME)) { EventBus eventBus = (EventBus)bd.getBean(); enableEvents(eventBus); } //ignore global 'shiro.' shortcut mechanism: if (!bd.isGlobalConfig()) { BeanEvent event = new ConfiguredBeanEvent(bd.getBeanName(), bd.getBean(), Collections.unmodifiableMap(objects)); eventBus.publish(event); } //initialize the bean if necessary: LifecycleUtils.init(bd.getBean()); //ignore global 'shiro.' shortcut mechanism: if (!bd.isGlobalConfig()) { BeanEvent event = new InitializedBeanEvent(bd.getBeanName(), bd.getBean(), Collections.unmodifiableMap(objects)); eventBus.publish(event); } } } } } private class BeanConfiguration { private final InstantiationStatement instantiationStatement; private final List<AssignmentStatement> assignments = new ArrayList<AssignmentStatement>(); private final String beanName; private Object bean; private BeanConfiguration(InstantiationStatement statement) { statement.setBeanConfiguration(this); this.instantiationStatement = statement; this.beanName = statement.lhs; } private BeanConfiguration(AssignmentStatement as) { this.instantiationStatement = null; this.beanName = as.getRootBeanName(); add(as); } public String getBeanName() { return this.beanName; } public boolean isGlobalConfig() { //BeanConfiguration instance representing the global 'shiro.' properties // (we should remove this concept). return GLOBAL_PROPERTY_PREFIX.equals(getBeanName()); } public void add(AssignmentStatement as) { as.setBeanConfiguration(this); assignments.add(as); } /** * When this configuration is parsed sufficiently to create (or find) an actual bean instance, that instance * will be associated with its configuration by setting it via this method. * * @param bean the bean instantiated (or found) that corresponds to this BeanConfiguration instance. */ public void setBean(Object bean) { this.bean = bean; } public Object getBean() { return this.bean; } /** * Returns true if all configuration statements have been executed. * @return true if all configuration statements have been executed. */ public boolean isExecuted() { if (instantiationStatement != null && !instantiationStatement.isExecuted()) { return false; } for (AssignmentStatement as : assignments) { if (!as.isExecuted()) { return false; } } return true; } } private abstract class Statement { protected final String lhs; protected final String rhs; protected Object bean; private Object result; private boolean executed; private BeanConfiguration beanConfiguration; private Statement(String lhs, String rhs) { this.lhs = lhs; this.rhs = rhs; this.executed = false; } public void setBeanConfiguration(BeanConfiguration bd) { this.beanConfiguration = bd; } public BeanConfiguration getBeanConfiguration() { return this.beanConfiguration; } public Object execute() { if (!isExecuted()) { this.result = doExecute(); this.executed = true; } if (!getBeanConfiguration().isGlobalConfig()) { Assert.notNull(this.bean, "Implementation must set the root bean for which it executed."); } return this.result; } public Object getBean() { return this.bean; } protected void setBean(Object bean) { this.bean = bean; if (this.beanConfiguration.getBean() == null) { this.beanConfiguration.setBean(bean); } } public Object getResult() { return result; } protected abstract Object doExecute(); public boolean isExecuted() { return executed; } } private class InstantiationStatement extends Statement { private InstantiationStatement(String lhs, String rhs) { super(lhs, rhs); } @Override protected Object doExecute() { String beanName = this.lhs; createNewInstance(objects, beanName, this.rhs); Object instantiated = objects.get(beanName); setBean(instantiated); //also ensure the instantiated bean has access to the event bus or is subscribed to events if necessary: //Note: because events are being enabled on this bean here (before the instantiated event below is //triggered), beans can react to their own instantiation events. enableEventsIfNecessary(instantiated, beanName); BeanEvent event = new InstantiatedBeanEvent(beanName, instantiated, Collections.unmodifiableMap(objects)); eventBus.publish(event); return instantiated; } } private class AssignmentStatement extends Statement { private final String rootBeanName; private AssignmentStatement(String lhs, String rhs) { super(lhs, rhs); int index = lhs.indexOf('.'); this.rootBeanName = lhs.substring(0, index); } @Override protected Object doExecute() { applyProperty(lhs, rhs, objects); Object bean = objects.get(this.rootBeanName); setBean(bean); return null; } public String getRootBeanName() { return this.rootBeanName; } } ////////////////////////// // From CollectionUtils // ////////////////////////// // CollectionUtils cannot be removed from shiro-core until 2.0 as it has a dependency on PrincipalCollection private static boolean isEmpty(Map m) { return m == null || m.isEmpty(); } private static boolean isEmpty(Collection c) { return c == null || c.isEmpty(); } }
[SHIRO-778] onInit method on AuthenticatingRealm is called twice
config/ogdl/src/main/java/org/apache/shiro/config/ogdl/ReflectionBuilder.java
[SHIRO-778] onInit method on AuthenticatingRealm is called twice
<ide><path>onfig/ogdl/src/main/java/org/apache/shiro/config/ogdl/ReflectionBuilder.java <ide> } <ide> <ide> processor.execute(); <del> } <del> <del> //SHIRO-413: init method must be called for constructed objects that are Initializable <del> LifecycleUtils.init(objects.values()); <add> <add> //SHIRO-778: onInit method on AuthenticatingRealm is called twice <add> objects.keySet().stream() <add> .filter(key -> !kvPairs.containsKey(key)) <add> .forEach(key -> LifecycleUtils.init(objects.get(key))); <add> } else { <add> //SHIRO-413: init method must be called for constructed objects that are Initializable <add> LifecycleUtils.init(objects.values()); <add> } <ide> <ide> return objects; <ide> }
JavaScript
apache-2.0
06c44988d860fff63951577d3690e58925b93707
0
ftgoncalves/jmodal
/* Copyright 2014 Felipe Theodoro Goncalves Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function($) { $.fn.jmodal = function(opt) { var settings = $.extend({ 'background-color' : '#000', 'class' : 'modal', 'outsideClickable' : true, 'closeButton' : '' }, opt); $(this).click(function(e) { e.preventDefault(); var maskHeight = $(document).height(); var maskWidth = $(window).width(); div = $("<div>").css({ 'width': maskWidth, 'height': maskHeight, 'position': 'absolute', 'left': 0, 'top': 0, 'z-index': 9000, 'background-color': settings['background-color'] }); $("body").append(div); $(div).addClass(settings['class']).fadeIn(1000).fadeTo("slow", 0.8); var win = $(window); var id = $(this).attr('href'); $(id).css({ 'top': win.height() / 2 - $(id).height() / 2, 'left': win.width() / 2 - $(id).width() / 2, 'position': 'fixed', 'z-index': 9999 }).fadeIn(200); if (settings['outsideClickable']) { $(div).click(function() { $(this).hide(); $(id).hide(); }); } $(settings['closeButton']).click(function() { $(div).hide(); $(id).hide(); }); }); }; }(jQuery));
jmodal.js
/* Copyright 2014 Felipe Theodoro Goncalves Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function($) { $.fn.jmodal = function(opt) { var settings = $.extend({ 'background-color' : '#000', 'class' : 'modal', 'outsideClickable' : true }, opt); $(this).click(function(e) { e.preventDefault(); var maskHeight = $(document).height(); var maskWidth = $(window).width(); div = $("<div>").css({ 'width': maskWidth, 'height': maskHeight, 'position': 'absolute', 'left': 0, 'top': 0, 'z-index': 9000, 'background-color': settings['background-color'] }); $("body").append(div); $(div).addClass(settings['class']).fadeIn(1000).fadeTo("slow", 0.8); var win = $(window); var id = $(this).attr('href'); $(id).css({ 'top': win.height() / 2 - $(id).height() / 2, 'left': win.width() / 2 - $(id).width() / 2, 'position': 'absolute', 'z-index': 9999 }).fadeIn(200); if (settings['outsideClickable']) { $(div).click(function() { $(this).hide(); $(id).hide(); }); } }); }; }(jQuery));
settings to close button
jmodal.js
settings to close button
<ide><path>modal.js <ide> var settings = $.extend({ <ide> 'background-color' : '#000', <ide> 'class' : 'modal', <del> 'outsideClickable' : true <add> 'outsideClickable' : true, <add> 'closeButton' : '' <ide> }, opt); <ide> <ide> $(this).click(function(e) { <ide> $(id).css({ <ide> 'top': win.height() / 2 - $(id).height() / 2, <ide> 'left': win.width() / 2 - $(id).width() / 2, <del> 'position': 'absolute', <add> 'position': 'fixed', <ide> 'z-index': 9999 <ide> }).fadeIn(200); <ide> <ide> $(id).hide(); <ide> }); <ide> } <add> <add> $(settings['closeButton']).click(function() { <add> $(div).hide(); <add> $(id).hide(); <add> }); <ide> }); <ide> }; <ide>
Java
bsd-3-clause
b405f0f8db7231532410e222599254a8fd037b57
0
stoewer/nix-java
package org.gnode.nix; import org.bytedeco.javacpp.Loader; import org.bytedeco.javacpp.annotation.*; import org.gnode.nix.base.NamedEntity; import org.gnode.nix.internal.None; import org.gnode.nix.internal.OptionalString; import org.gnode.nix.internal.Utils; import java.util.Date; import java.util.List; @Platform(value = "linux", include = {"<nix/Block.hpp>"}, link = {"nix"}) @Namespace("nix") public class Block extends NamedEntity { static { Loader.load(); } /** * Constructor that creates an uninitialized Block. * <p/> * Calling any method on an uninitialized block will throw a {@link java.lang.RuntimeException}. */ public Block() { allocate(); } private native void allocate(); //-------------------------------------------------- // Base class methods //-------------------------------------------------- public native @Cast("bool") boolean isNone(); /** * Get id of the block * * @return id string */ public native @Name("id") @StdString String getId(); private native @Cast("time_t") long createdAt(); /** * Get the creation date of the block. * * @return The creation date of the block. */ public Date getCreatedAt() { return Utils.convertSecondsToDate(createdAt()); } private native @Cast("time_t") long updatedAt(); /** * Get the date of the last update. * * @return The date of the last update. */ public Date getUpdatedAt() { return Utils.convertSecondsToDate(updatedAt()); } /** * Sets the time of the last update to the current time if the field is not set. */ public native void setUpdatedAt(); /** * Sets the time of the last update to the current time. */ public native void forceUpdatedAt(); /** * Sets the creation time to the current time if the field is not set. */ public native void setCreatedAt(); private native void forceCreatedAt(@Cast("time_t") long time); /** * Sets the creation date to the provided value even if the attribute is set. * * @param date The creation date to set. */ public void forceCreatedAt(Date date) { forceCreatedAt(Utils.convertDateToSeconds(date)); } /** * Setter for the type of the block * * @param type The type of the block */ public native @Name("type") void setType(@StdString String type); /** * Getter for the type of the block * * @return The type of the block */ public native @Name("type") @StdString String getType(); /** * Getter for the name of the block. * * @return The name of the block. */ public native @Name("name") @StdString String getName(); private native void definition(@Const @ByVal None t); private native void definition(@StdString String definition); /** * Setter for the definition of the block. If null is passed definition is removed. * * @param definition definition of block */ public void setDefinition(String definition) { if (definition != null) { definition(definition); } else { definition(new None()); } } private native @ByVal OptionalString definition(); /** * Getter for the definition of the block. * * @return The definition of the block. */ public String getDefinition() { OptionalString defintion = definition(); if (defintion.isPresent()) { return defintion.getString(); } return null; } //-------------------------------------------------- // Methods concerning data arrays //-------------------------------------------------- /** * Checks if a specific data array exists in this block. * * @param nameOrId Name or id of a data array. * @return True if the data array exists, false otherwise. */ public native @Cast("bool") boolean hasDataArray(@StdString String nameOrId); /** * Checks if a specific data array exists in this block. * * @param dataArray The data array to check. * @return True if the data array exists, false otherwise. */ public native @Cast("bool") boolean hasDataArray(@Const @ByRef DataArray dataArray); private native @Name("getDataArray") @ByVal DataArray fetchDataArray(@StdString String nameOrId); /** * Retrieves a specific data array from the block by name or id. * * @param nameOrId Name or id of an existing data array. * @return The data array with the specified id. If this * doesn't exist, an exception will be thrown. */ public DataArray getDataArray(String nameOrId) { DataArray da = fetchDataArray(nameOrId); if (da.isInitialized()) { return da; } return null; } private native @Name("getDataArray") @ByVal DataArray fetchDataArray(@Cast("size_t") long index); /** * Retrieves a data array by index. * * @param index The index of the data array. * @return The data array at the specified index. */ public DataArray getDataArray(long index) { DataArray da = fetchDataArray(index); if (da.isInitialized()) { return da; } return null; } private native @Name("dataArrays") @StdVector DataArray getDataArrays(); /** * Get data arrays within this block. * * @return list of data arrays */ public List<DataArray> dataArrays() { return Utils.convertPointerToList(getDataArrays(), DataArray.class); } /** * Returns the number of all data arrays of the block. * * @return The number of data arrays of the block. */ public native @Name("dataArrayCount") long getDataArrayCount(); private native @Name("createDataArray") @ByVal DataArray makeDataArray(@StdString String name, @StdString String type, @Cast("nix::DataType") int dataType, @Const @ByRef NDSize shape); /** * Create a new data array associated with this block. * * @param name The name of the data array to create. * @param type The type of the data array. * @param dataType A {@link DataType} indicating the format to store values. * @param shape A NDSize holding the extent of the array to create. * @return The newly created data array. */ public DataArray createDataArray(String name, String type, int dataType, NDSize shape) { DataArray da = makeDataArray(name, type, dataType, shape); if (da.isInitialized()) { return da; } return null; } /** * Deletes a data array from this block. * <p/> * This deletes a data array and all its dimensions from the block and the file. * The deletion can't be undone. * * @param nameOrId Name or id of the data array to delete. * @return True if the data array was deleted, false otherwise. */ public native @Cast("bool") boolean deleteDataArray(@StdString String nameOrId); /** * Deletes a data array from this block. * <p/> * This deletes a data array and all its dimensions from the block and the file. * The deletion can't be undone. * * @param dataArray The data array to delete. * @return True if the data array was deleted, false otherwise. */ public native @Cast("bool") boolean deleteDataArray(@Const @ByRef DataArray dataArray); //-------------------------------------------------- // Overrides //-------------------------------------------------- @Override public String toString() { return "Block: {name = " + this.getName() + ", type = " + this.getType() + ", id = " + this.getId() + "}"; } }
src/main/java/org/gnode/nix/Block.java
package org.gnode.nix; import org.bytedeco.javacpp.Loader; import org.bytedeco.javacpp.annotation.*; import org.gnode.nix.base.NamedEntity; import org.gnode.nix.internal.None; import org.gnode.nix.internal.OptionalString; import org.gnode.nix.internal.Utils; import java.util.Date; @Platform(value = "linux", include = {"<nix/Block.hpp>"}, link = {"nix"}) @Namespace("nix") public class Block extends NamedEntity { static { Loader.load(); } /** * Constructor that creates an uninitialized Block. * <p/> * Calling any method on an uninitialized block will throw a {@link java.lang.RuntimeException}. */ public Block() { allocate(); } private native void allocate(); //-------------------------------------------------- // Base class methods //-------------------------------------------------- public native @Cast("bool") boolean isNone(); /** * Get id of the block * * @return id string */ public native @Name("id") @StdString String getId(); private native @Cast("time_t") long createdAt(); /** * Get the creation date of the block. * * @return The creation date of the block. */ public Date getCreatedAt() { return Utils.convertSecondsToDate(createdAt()); } private native @Cast("time_t") long updatedAt(); /** * Get the date of the last update. * * @return The date of the last update. */ public Date getUpdatedAt() { return Utils.convertSecondsToDate(updatedAt()); } /** * Sets the time of the last update to the current time if the field is not set. */ public native void setUpdatedAt(); /** * Sets the time of the last update to the current time. */ public native void forceUpdatedAt(); /** * Sets the creation time to the current time if the field is not set. */ public native void setCreatedAt(); private native void forceCreatedAt(@Cast("time_t") long time); /** * Sets the creation date to the provided value even if the attribute is set. * * @param date The creation date to set. */ public void forceCreatedAt(Date date) { forceCreatedAt(Utils.convertDateToSeconds(date)); } /** * Setter for the type of the block * * @param type The type of the block */ public native @Name("type") void setType(@StdString String type); /** * Getter for the type of the block * * @return The type of the block */ public native @Name("type") @StdString String getType(); /** * Getter for the name of the block. * * @return The name of the block. */ public native @Name("name") @StdString String getName(); private native void definition(@Const @ByVal None t); private native void definition(@StdString String definition); /** * Setter for the definition of the block. If null is passed definition is removed. * * @param definition definition of block */ public void setDefinition(String definition) { if (definition != null) { definition(definition); } else { definition(new None()); } } private native @ByVal OptionalString definition(); /** * Getter for the definition of the block. * * @return The definition of the block. */ public String getDefinition() { OptionalString defintion = definition(); if (defintion.isPresent()) { return defintion.getString(); } return null; } @Override public String toString() { return "Block: {name = " + this.getName() + ", type = " + this.getType() + ", id = " + this.getId() + "}"; } }
add data array related methods to Block
src/main/java/org/gnode/nix/Block.java
add data array related methods to Block
<ide><path>rc/main/java/org/gnode/nix/Block.java <ide> import org.gnode.nix.internal.Utils; <ide> <ide> import java.util.Date; <add>import java.util.List; <ide> <ide> @Platform(value = "linux", <ide> include = {"<nix/Block.hpp>"}, <ide> return null; <ide> } <ide> <add> //-------------------------------------------------- <add> // Methods concerning data arrays <add> //-------------------------------------------------- <add> <add> /** <add> * Checks if a specific data array exists in this block. <add> * <add> * @param nameOrId Name or id of a data array. <add> * @return True if the data array exists, false otherwise. <add> */ <add> public native <add> @Cast("bool") <add> boolean hasDataArray(@StdString String nameOrId); <add> <add> /** <add> * Checks if a specific data array exists in this block. <add> * <add> * @param dataArray The data array to check. <add> * @return True if the data array exists, false otherwise. <add> */ <add> public native <add> @Cast("bool") <add> boolean hasDataArray(@Const @ByRef DataArray dataArray); <add> <add> private native <add> @Name("getDataArray") <add> @ByVal <add> DataArray fetchDataArray(@StdString String nameOrId); <add> <add> /** <add> * Retrieves a specific data array from the block by name or id. <add> * <add> * @param nameOrId Name or id of an existing data array. <add> * @return The data array with the specified id. If this <add> * doesn't exist, an exception will be thrown. <add> */ <add> public DataArray getDataArray(String nameOrId) { <add> DataArray da = fetchDataArray(nameOrId); <add> if (da.isInitialized()) { <add> return da; <add> } <add> return null; <add> } <add> <add> private native <add> @Name("getDataArray") <add> @ByVal <add> DataArray fetchDataArray(@Cast("size_t") long index); <add> <add> /** <add> * Retrieves a data array by index. <add> * <add> * @param index The index of the data array. <add> * @return The data array at the specified index. <add> */ <add> public DataArray getDataArray(long index) { <add> DataArray da = fetchDataArray(index); <add> if (da.isInitialized()) { <add> return da; <add> } <add> return null; <add> } <add> <add> private native <add> @Name("dataArrays") <add> @StdVector <add> DataArray getDataArrays(); <add> <add> /** <add> * Get data arrays within this block. <add> * <add> * @return list of data arrays <add> */ <add> public List<DataArray> dataArrays() { <add> return Utils.convertPointerToList(getDataArrays(), DataArray.class); <add> } <add> <add> /** <add> * Returns the number of all data arrays of the block. <add> * <add> * @return The number of data arrays of the block. <add> */ <add> public native <add> @Name("dataArrayCount") <add> long getDataArrayCount(); <add> <add> <add> private native <add> @Name("createDataArray") <add> @ByVal <add> DataArray makeDataArray(@StdString String name, <add> @StdString String type, @Cast("nix::DataType") <add> int dataType, <add> @Const @ByRef NDSize shape); <add> <add> /** <add> * Create a new data array associated with this block. <add> * <add> * @param name The name of the data array to create. <add> * @param type The type of the data array. <add> * @param dataType A {@link DataType} indicating the format to store values. <add> * @param shape A NDSize holding the extent of the array to create. <add> * @return The newly created data array. <add> */ <add> public DataArray createDataArray(String name, String type, int dataType, NDSize shape) { <add> DataArray da = makeDataArray(name, type, dataType, shape); <add> if (da.isInitialized()) { <add> return da; <add> } <add> return null; <add> } <add> <add> /** <add> * Deletes a data array from this block. <add> * <p/> <add> * This deletes a data array and all its dimensions from the block and the file. <add> * The deletion can't be undone. <add> * <add> * @param nameOrId Name or id of the data array to delete. <add> * @return True if the data array was deleted, false otherwise. <add> */ <add> public native <add> @Cast("bool") <add> boolean deleteDataArray(@StdString String nameOrId); <add> <add> /** <add> * Deletes a data array from this block. <add> * <p/> <add> * This deletes a data array and all its dimensions from the block and the file. <add> * The deletion can't be undone. <add> * <add> * @param dataArray The data array to delete. <add> * @return True if the data array was deleted, false otherwise. <add> */ <add> public native <add> @Cast("bool") <add> boolean deleteDataArray(@Const @ByRef DataArray dataArray); <add> <add> //-------------------------------------------------- <add> // Overrides <add> //-------------------------------------------------- <add> <ide> @Override <ide> public String toString() { <ide> return "Block: {name = " + this.getName()
Java
apache-2.0
98cc5ffb22f7d82157b2dcda8f6252e27b741edf
0
tailanx/test,tailanx/test
package com.yidejia.app.mall.util; public class Consts { public static final String UPDATE_CHANGE = "com.yidejia.UPDATE"; public static final int GENERAL = 126; public static final int EMS = 127; }
src/com/yidejia/app/mall/util/Consts.java
package com.yidejia.app.mall.util; public class Consts { public static final String UPDATE_CHANGE = "com.yidejia.UPDATE"; }
定义常量,用来发送通知,修改界面的购物车里面商品的数目
src/com/yidejia/app/mall/util/Consts.java
定义常量,用来发送通知,修改界面的购物车里面商品的数目
<ide><path>rc/com/yidejia/app/mall/util/Consts.java <ide> <ide> public class Consts { <ide> public static final String UPDATE_CHANGE = "com.yidejia.UPDATE"; <add> public static final int GENERAL = 126; <add> public static final int EMS = 127; <ide> }
Java
apache-2.0
85b20aa08afe2394cfc4028fc301326a1521c530
0
spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework
/* * Copyright 2002-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cache.jcache.interceptor; import java.util.Arrays; import java.util.concurrent.atomic.AtomicLong; import javax.cache.annotation.CacheDefaults; import javax.cache.annotation.CachePut; import javax.cache.annotation.CacheRemove; import javax.cache.annotation.CacheRemoveAll; import javax.cache.annotation.CacheResult; import javax.cache.annotation.CacheValue; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.interceptor.CacheErrorHandler; import org.springframework.cache.interceptor.SimpleKeyGenerator; import org.springframework.cache.jcache.config.JCacheConfigurerSupport; import org.springframework.cache.support.SimpleCacheManager; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import static org.junit.Assert.*; import static org.mockito.BDDMockito.*; /** * @author Stephane Nicoll */ public class JCacheErrorHandlerTests { @Rule public final ExpectedException thrown = ExpectedException.none(); private Cache cache; private Cache errorCache; private CacheErrorHandler errorHandler; private SimpleService simpleService; @Before public void setup() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class); this.cache = context.getBean("mockCache", Cache.class); this.errorCache = context.getBean("mockErrorCache", Cache.class); this.errorHandler = context.getBean(CacheErrorHandler.class); this.simpleService = context.getBean(SimpleService.class); } @Test public void getFail() { UnsupportedOperationException exception = new UnsupportedOperationException("Test exception on get"); Object key = SimpleKeyGenerator.generateKey(0L); willThrow(exception).given(this.cache).get(key); this.simpleService.get(0L); verify(this.errorHandler).handleCacheGetError(exception, this.cache, key); } @Test public void getPutNewElementFail() { UnsupportedOperationException exception = new UnsupportedOperationException("Test exception on put"); Object key = SimpleKeyGenerator.generateKey(0L); given(this.cache.get(key)).willReturn(null); willThrow(exception).given(this.cache).put(key, 0L); this.simpleService.get(0L); verify(this.errorHandler).handleCachePutError(exception, this.cache, key, 0L); } @Test public void getFailPutExceptionFail() { UnsupportedOperationException exceptionOnPut = new UnsupportedOperationException("Test exception on put"); Object key = SimpleKeyGenerator.generateKey(0L); given(this.cache.get(key)).willReturn(null); willThrow(exceptionOnPut).given(this.errorCache).put(key, SimpleService.TEST_EXCEPTION); try { this.simpleService.getFail(0L); } catch (IllegalStateException ex) { assertEquals("Test exception", ex.getMessage()); } verify(this.errorHandler).handleCachePutError(exceptionOnPut, this.errorCache, key, SimpleService.TEST_EXCEPTION); } @Test public void putFail() { UnsupportedOperationException exception = new UnsupportedOperationException("Test exception on put"); Object key = SimpleKeyGenerator.generateKey(0L); willThrow(exception).given(this.cache).put(key, 234L); this.simpleService.put(0L, 234L); verify(this.errorHandler).handleCachePutError(exception, this.cache, key, 234L); } @Test public void evictFail() { UnsupportedOperationException exception = new UnsupportedOperationException("Test exception on evict"); Object key = SimpleKeyGenerator.generateKey(0L); willThrow(exception).given(this.cache).evict(key); this.simpleService.evict(0L); verify(this.errorHandler).handleCacheEvictError(exception, this.cache, key); } @Test public void clearFail() { UnsupportedOperationException exception = new UnsupportedOperationException("Test exception on evict"); willThrow(exception).given(this.cache).clear(); this.simpleService.clear(); verify(this.errorHandler).handleCacheClearError(exception, this.cache); } @Configuration @EnableCaching static class Config extends JCacheConfigurerSupport { @Bean @Override public CacheManager cacheManager() { SimpleCacheManager cacheManager = new SimpleCacheManager(); cacheManager.setCaches(Arrays.asList(mockCache(), mockErrorCache())); return cacheManager; } @Bean @Override public CacheErrorHandler errorHandler() { return mock(CacheErrorHandler.class); } @Bean public SimpleService simpleService() { return new SimpleService(); } @Bean public Cache mockCache() { Cache cache = mock(Cache.class); given(cache.getName()).willReturn("test"); return cache; } @Bean public Cache mockErrorCache() { Cache cache = mock(Cache.class); given(cache.getName()).willReturn("error"); return cache; } } @CacheDefaults(cacheName = "test") public static class SimpleService { private static final IllegalStateException TEST_EXCEPTION = new IllegalStateException("Test exception"); private AtomicLong counter = new AtomicLong(); @CacheResult public Object get(long id) { return this.counter.getAndIncrement(); } @CacheResult(exceptionCacheName = "error") public Object getFail(long id) { throw TEST_EXCEPTION; } @CachePut public void put(long id, @CacheValue Object object) { } @CacheRemove public void evict(long id) { } @CacheRemoveAll public void clear() { } } }
spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/JCacheErrorHandlerTests.java
/* * Copyright 2002-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cache.jcache.interceptor; import java.util.Arrays; import java.util.concurrent.atomic.AtomicLong; import javax.cache.annotation.CacheDefaults; import javax.cache.annotation.CachePut; import javax.cache.annotation.CacheRemove; import javax.cache.annotation.CacheRemoveAll; import javax.cache.annotation.CacheResult; import javax.cache.annotation.CacheValue; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.interceptor.CacheErrorHandler; import org.springframework.cache.interceptor.SimpleKeyGenerator; import org.springframework.cache.jcache.config.JCacheConfigurerSupport; import org.springframework.cache.support.SimpleCacheManager; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import static org.junit.Assert.*; import static org.mockito.BDDMockito.*; /** * @author Stephane Nicoll */ public class JCacheErrorHandlerTests { @Rule public final ExpectedException thrown = ExpectedException.none(); private Cache cache; private Cache errorCache; private CacheErrorHandler errorHandler; private SimpleService simpleService; @Before public void setup() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class); this.cache = context.getBean("mockCache", Cache.class); this.errorCache = context.getBean("mockErrorCache", Cache.class); this.errorHandler = context.getBean(CacheErrorHandler.class); this.simpleService = context.getBean(SimpleService.class); } @Test public void getFail() { UnsupportedOperationException exception = new UnsupportedOperationException("Test exception on get"); Object key = SimpleKeyGenerator.generateKey(0L); willThrow(exception).given(cache).get(key); this.simpleService.get(0L); verify(errorHandler).handleCacheGetError(exception, cache, key); } @Test public void getPutNewElementFail() { UnsupportedOperationException exception = new UnsupportedOperationException("Test exception on put"); Object key = SimpleKeyGenerator.generateKey(0L); given(this.cache.get(key)).willReturn(null); willThrow(exception).given(this.cache).put(key, 0L); this.simpleService.get(0L); verify(this.errorHandler).handleCachePutError(exception, this.cache, key, 0L); } @Test public void getFailPutExceptionFail() { UnsupportedOperationException exceptionOnPut = new UnsupportedOperationException("Test exception on put"); Object key = SimpleKeyGenerator.generateKey(0L); given(this.cache.get(key)).willReturn(null); willThrow(exceptionOnPut).given(this.errorCache).put(key, SimpleService.TEST_EXCEPTION); try { this.simpleService.getFail(0L); } catch (IllegalStateException ex) { assertEquals("Test exception", ex.getMessage()); } verify(this.errorHandler).handleCachePutError(exceptionOnPut, this.errorCache, key, SimpleService.TEST_EXCEPTION); } @Test public void putFail() { UnsupportedOperationException exception = new UnsupportedOperationException("Test exception on put"); Object key = SimpleKeyGenerator.generateKey(0L); willThrow(exception).given(cache).put(key, 234L); this.simpleService.put(0L, 234L); verify(errorHandler).handleCachePutError(exception, cache, key, 234L); } @Test public void evictFail() { UnsupportedOperationException exception = new UnsupportedOperationException("Test exception on evict"); Object key = SimpleKeyGenerator.generateKey(0L); willThrow(exception).given(cache).evict(key); this.simpleService.evict(0L); verify(errorHandler).handleCacheEvictError(exception, cache, key); } @Test public void clearFail() { UnsupportedOperationException exception = new UnsupportedOperationException("Test exception on evict"); willThrow(exception).given(cache).clear(); this.simpleService.clear(); verify(errorHandler).handleCacheClearError(exception, cache); } @Configuration @EnableCaching static class Config extends JCacheConfigurerSupport { @Bean @Override public CacheManager cacheManager() { SimpleCacheManager cacheManager = new SimpleCacheManager(); cacheManager.setCaches(Arrays.asList(mockCache(), mockErrorCache())); return cacheManager; } @Bean @Override public CacheErrorHandler errorHandler() { return mock(CacheErrorHandler.class); } @Bean public SimpleService simpleService() { return new SimpleService(); } @Bean public Cache mockCache() { Cache cache = mock(Cache.class); given(cache.getName()).willReturn("test"); return cache; } @Bean public Cache mockErrorCache() { Cache cache = mock(Cache.class); given(cache.getName()).willReturn("error"); return cache; } } @CacheDefaults(cacheName = "test") public static class SimpleService { private static final IllegalStateException TEST_EXCEPTION = new IllegalStateException("Test exception"); private AtomicLong counter = new AtomicLong(); @CacheResult public Object get(long id) { return counter.getAndIncrement(); } @CacheResult(exceptionCacheName = "error") public Object getFail(long id) { throw TEST_EXCEPTION; } @CachePut public void put(long id, @CacheValue Object object) { } @CacheRemove public void evict(long id) { } @CacheRemoveAll public void clear() { } } }
Polish
spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/JCacheErrorHandlerTests.java
Polish
<ide><path>pring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/JCacheErrorHandlerTests.java <ide> <ide> @Before <ide> public void setup() { <del> AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class); <add> AnnotationConfigApplicationContext context = <add> new AnnotationConfigApplicationContext(Config.class); <ide> this.cache = context.getBean("mockCache", Cache.class); <ide> this.errorCache = context.getBean("mockErrorCache", Cache.class); <ide> this.errorHandler = context.getBean(CacheErrorHandler.class); <ide> <ide> @Test <ide> public void getFail() { <del> UnsupportedOperationException exception = new UnsupportedOperationException("Test exception on get"); <del> Object key = SimpleKeyGenerator.generateKey(0L); <del> willThrow(exception).given(cache).get(key); <add> UnsupportedOperationException exception = <add> new UnsupportedOperationException("Test exception on get"); <add> Object key = SimpleKeyGenerator.generateKey(0L); <add> willThrow(exception).given(this.cache).get(key); <ide> <ide> this.simpleService.get(0L); <del> verify(errorHandler).handleCacheGetError(exception, cache, key); <add> verify(this.errorHandler).handleCacheGetError(exception, this.cache, key); <ide> } <ide> <ide> @Test <ide> public void getPutNewElementFail() { <del> UnsupportedOperationException exception = new UnsupportedOperationException("Test exception on put"); <add> UnsupportedOperationException exception = <add> new UnsupportedOperationException("Test exception on put"); <ide> Object key = SimpleKeyGenerator.generateKey(0L); <ide> given(this.cache.get(key)).willReturn(null); <ide> willThrow(exception).given(this.cache).put(key, 0L); <ide> <ide> @Test <ide> public void getFailPutExceptionFail() { <del> UnsupportedOperationException exceptionOnPut = new UnsupportedOperationException("Test exception on put"); <add> UnsupportedOperationException exceptionOnPut = <add> new UnsupportedOperationException("Test exception on put"); <ide> Object key = SimpleKeyGenerator.generateKey(0L); <ide> given(this.cache.get(key)).willReturn(null); <ide> willThrow(exceptionOnPut).given(this.errorCache).put(key, <ide> <ide> @Test <ide> public void putFail() { <del> UnsupportedOperationException exception = new UnsupportedOperationException("Test exception on put"); <del> Object key = SimpleKeyGenerator.generateKey(0L); <del> willThrow(exception).given(cache).put(key, 234L); <add> UnsupportedOperationException exception = <add> new UnsupportedOperationException("Test exception on put"); <add> Object key = SimpleKeyGenerator.generateKey(0L); <add> willThrow(exception).given(this.cache).put(key, 234L); <ide> <ide> this.simpleService.put(0L, 234L); <del> verify(errorHandler).handleCachePutError(exception, cache, key, 234L); <add> verify(this.errorHandler).handleCachePutError(exception, this.cache, key, 234L); <ide> } <ide> <ide> @Test <ide> public void evictFail() { <del> UnsupportedOperationException exception = new UnsupportedOperationException("Test exception on evict"); <del> Object key = SimpleKeyGenerator.generateKey(0L); <del> willThrow(exception).given(cache).evict(key); <add> UnsupportedOperationException exception = <add> new UnsupportedOperationException("Test exception on evict"); <add> Object key = SimpleKeyGenerator.generateKey(0L); <add> willThrow(exception).given(this.cache).evict(key); <ide> <ide> this.simpleService.evict(0L); <del> verify(errorHandler).handleCacheEvictError(exception, cache, key); <add> verify(this.errorHandler).handleCacheEvictError(exception, this.cache, key); <ide> } <ide> <ide> @Test <ide> public void clearFail() { <del> UnsupportedOperationException exception = new UnsupportedOperationException("Test exception on evict"); <del> willThrow(exception).given(cache).clear(); <add> UnsupportedOperationException exception = <add> new UnsupportedOperationException("Test exception on evict"); <add> willThrow(exception).given(this.cache).clear(); <ide> <ide> this.simpleService.clear(); <del> verify(errorHandler).handleCacheClearError(exception, cache); <add> verify(this.errorHandler).handleCacheClearError(exception, this.cache); <ide> } <ide> <ide> <ide> <ide> @CacheResult <ide> public Object get(long id) { <del> return counter.getAndIncrement(); <add> return this.counter.getAndIncrement(); <ide> } <ide> <ide> @CacheResult(exceptionCacheName = "error")