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
|
fa40bd83ddb6ce332506a535061b4193cf4438d7
| 0 |
spring-cloud/spring-cloud-sleuth,spring-cloud/spring-cloud-sleuth,spring-cloud/spring-cloud-sleuth,spring-cloud/spring-cloud-sleuth,spring-cloud/spring-cloud-sleuth
|
/*
* Copyright 2013-2018 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.cloud.sleuth.annotation;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import brave.Tracer;
import brave.sampler.Sampler;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.awaitility.Awaitility;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Mono;
import zipkin2.Span;
import zipkin2.reporter.Reporter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.trace.http.HttpTrace;
import org.springframework.boot.actuate.trace.http.HttpTraceRepository;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.cloud.sleuth.DisableWebFluxSecurity;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;
import static org.assertj.core.api.BDDAssertions.then;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(properties = { "spring.main.web-application-type=reactive" }, classes = {
SleuthSpanCreatorAspectWebFluxTests.TestEndpoint.class,
SleuthSpanCreatorAspectWebFluxTests.TestConfiguration.class }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class SleuthSpanCreatorAspectWebFluxTests {
private static final Log log = LogFactory
.getLog(SleuthSpanCreatorAspectWebFluxTests.class);
private static final ConcurrentLinkedQueue<Long> spanIdsInHttpTrace = new ConcurrentLinkedQueue<>();
private final WebClient webClient = WebClient.create();
@Autowired
Tracer tracer;
@Autowired
ArrayListSpanReporter reporter;
@LocalServerPort
private int port;
private static String toHexString(long value) {
return StringUtils.leftPad(Long.toHexString(value), 16, '0');
}
@Before
public void setup() {
this.reporter.clear();
spanIdsInHttpTrace.clear();
}
@Test
public void shouldReturnSpanFromWebFluxTraceContext() {
Mono<Long> mono = webClient.get().uri("http://localhost:" + port + "/test/ping")
.retrieve().bodyToMono(Long.class);
then(this.reporter.getSpans()).isEmpty();
Long newSpanId = mono.block();
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = getSpans();
then(spans).hasSize(1);
then(spans.get(0).kind()).isEqualTo(Span.Kind.SERVER);
then(spans.get(0).name()).isEqualTo("get /test/ping");
then(spans.get(0).id()).isEqualTo(toHexString(newSpanId));
then(this.tracer.currentSpan()).isNull();
});
}
private List<zipkin2.Span> getSpans() {
List<zipkin2.Span> spans = this.reporter.getSpans();
log.info("Reported the following spans: \n\n" + spans);
return spans;
}
@Test
public void shouldReturnSpanFromWebFluxSubscriptionContext() {
Mono<Long> mono = webClient.get()
.uri("http://localhost:" + port + "/test/pingFromContext").retrieve()
.bodyToMono(Long.class);
then(this.reporter.getSpans()).isEmpty();
Long newSpanId = mono.block();
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = getSpans();
then(spans).hasSize(1);
then(spans.get(0).kind()).isEqualTo(Span.Kind.SERVER);
then(spans.get(0).name()).isEqualTo("get /test/pingfromcontext");
then(spans.get(0).id()).isEqualTo(toHexString(newSpanId));
then(this.tracer.currentSpan()).isNull();
});
}
@Test
public void shouldContinueSpanInWebFlux() {
Mono<Long> mono = webClient.get()
.uri("http://localhost:" + port + "/test/continueSpan").retrieve()
.bodyToMono(Long.class);
then(this.reporter.getSpans()).isEmpty();
Long newSpanId = mono.block();
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = getSpans();
then(spans).hasSize(1);
then(spans.get(0).kind()).isEqualTo(Span.Kind.SERVER);
then(spans.get(0).name()).isEqualTo("get /test/continuespan");
then(spans.get(0).id()).isEqualTo(toHexString(newSpanId));
then(this.tracer.currentSpan()).isNull();
});
}
@Test
public void shouldCreateNewSpanInWebFlux() {
Mono<Long> mono = webClient.get()
.uri("http://localhost:" + port + "/test/newSpan1").retrieve()
.bodyToMono(Long.class);
then(this.reporter.getSpans()).isEmpty();
Long newSpanId = mono.block();
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = getSpans();
then(spans).hasSize(2);
then(spans.get(0).name()).isEqualTo("new-span-in-trace-context");
then(spans.get(0).id()).isEqualTo(toHexString(newSpanId));
then(spans.get(1).kind()).isEqualTo(Span.Kind.SERVER);
then(spans.get(1).name()).isEqualTo("get /test/newspan1");
then(this.tracer.currentSpan()).isNull();
});
}
@Test
public void shouldCreateNewSpanInWebFluxInSubscriberContext() {
Mono<Long> mono = webClient.get()
.uri("http://localhost:" + port + "/test/newSpan2").retrieve()
.bodyToMono(Long.class);
then(this.reporter.getSpans()).isEmpty();
Long newSpanId = mono.block();
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = getSpans();
then(spans).hasSize(2);
then(spans.get(0).name()).isEqualTo("new-span-in-subscriber-context");
then(spans.get(0).id()).isEqualTo(toHexString(newSpanId));
then(spans.get(1).kind()).isEqualTo(Span.Kind.SERVER);
then(spans.get(1).name()).isEqualTo("get /test/newspan2");
then(this.tracer.currentSpan()).isNull();
});
}
// TODO: Fix me
@Test
@Ignore("The order with HttpTraceWebFilter has changed in Boot")
public void shouldSetupCorrectSpanInHttpTrace() {
spanIdsInHttpTrace.clear();
Mono<Long> mono = webClient.get().uri("http://localhost:" + port + "/test/ping")
.retrieve().bodyToMono(Long.class);
then(this.reporter.getSpans()).isEmpty();
Long newSpanId = mono.block();
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = getSpans();
then(spans).hasSize(1);
then(spans.get(0).kind()).isEqualTo(Span.Kind.SERVER);
then(spans.get(0).name()).isEqualTo("get /test/ping");
then(spans.get(0).id()).isEqualTo(toHexString(newSpanId))
.isEqualTo(toHexString(spanIdsInHttpTrace.poll()));
then(this.tracer.currentSpan()).isNull();
});
}
@Configuration
@EnableAutoConfiguration
@DisableWebFluxSecurity
protected static class TestConfiguration {
@Bean
TestBean testBean(Tracer tracer) {
return new TestBean(tracer);
}
@Bean
Reporter<zipkin2.Span> spanReporter() {
return new ArrayListSpanReporter();
}
@Bean
Sampler alwaysSampler() {
return Sampler.ALWAYS_SAMPLE;
}
@Bean
AccessLoggingHttpTraceRepository accessLoggingHttpTraceRepository() {
return new AccessLoggingHttpTraceRepository();
}
}
static class AccessLoggingHttpTraceRepository implements HttpTraceRepository {
@Autowired
Tracer tracer;
@Override
public List<HttpTrace> findAll() {
return null;
}
@Override
public void add(HttpTrace trace) {
if (tracer.currentSpan() != null) {
spanIdsInHttpTrace.add(tracer.currentSpan().context().spanId());
}
}
}
@RestController
@RequestMapping("/test")
static class TestEndpoint {
private static final Logger log = LoggerFactory.getLogger(TestEndpoint.class);
@Autowired
Tracer tracer;
@Autowired
TestBean testBean;
@GetMapping("/ping")
Mono<Long> ping() {
return Mono.just(tracer.currentSpan().context().spanId());
}
@GetMapping("/pingFromContext")
Mono<Long> pingFromContext() {
return Mono.subscriberContext()
.doOnSuccess(context -> log.info("Ping from context"))
.flatMap(context -> Mono
.just(tracer.currentSpan().context().spanId()));
}
@GetMapping("/continueSpan")
Mono<Long> continueSpan() {
log.info("continueSpan");
return testBean.continueSpanInTraceContext();
}
@GetMapping("/newSpan1")
Mono<Long> newSpan1() {
log.info("newSpan1");
return testBean.newSpanInTraceContext();
}
@GetMapping("/newSpan2")
Mono<Long> newSpan2() {
log.info("newSpan2");
return testBean.newSpanInSubscriberContext();
}
}
static class TestBean {
private static final Logger log = LoggerFactory.getLogger(TestBean.class);
private final Tracer tracer;
TestBean(Tracer tracer) {
this.tracer = tracer;
}
@ContinueSpan
public Mono<Long> continueSpanInTraceContext() {
log.info("Continue");
Long span = tracer.currentSpan().context().spanId();
return Mono.defer(() -> Mono.just(span));
}
@NewSpan(name = "newSpanInTraceContext")
public Mono<Long> newSpanInTraceContext() {
log.info("New Span in Trace Context");
Long span = tracer.currentSpan().context().spanId();
return Mono.defer(() -> Mono.just(span));
}
@NewSpan(name = "newSpanInSubscriberContext")
public Mono<Long> newSpanInSubscriberContext() {
log.info("New Span in Subscriber Context");
Long span = tracer.currentSpan().context().spanId();
return Mono.subscriberContext()
.doOnSuccess(
context -> log.info("New Span in deferred Trace Context"))
.flatMap(context -> Mono.defer(() -> Mono.just(span)));
}
}
}
|
spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/annotation/SleuthSpanCreatorAspectWebFluxTests.java
|
/*
* Copyright 2013-2018 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.cloud.sleuth.annotation;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import brave.Tracer;
import brave.sampler.Sampler;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.awaitility.Awaitility;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Mono;
import zipkin2.Span;
import zipkin2.reporter.Reporter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.trace.http.HttpTrace;
import org.springframework.boot.actuate.trace.http.HttpTraceRepository;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.cloud.sleuth.DisableWebFluxSecurity;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;
import static org.assertj.core.api.BDDAssertions.then;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(properties = { "spring.main.web-application-type=reactive" }, classes = {
SleuthSpanCreatorAspectWebFluxTests.TestEndpoint.class,
SleuthSpanCreatorAspectWebFluxTests.TestConfiguration.class }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class SleuthSpanCreatorAspectWebFluxTests {
private static final Log log = LogFactory
.getLog(SleuthSpanCreatorAspectWebFluxTests.class);
private static final ConcurrentLinkedQueue<Long> spanIdsInHttpTrace = new ConcurrentLinkedQueue<>();
private final WebClient webClient = WebClient.create();
@Autowired
Tracer tracer;
@Autowired
ArrayListSpanReporter reporter;
@LocalServerPort
private int port;
private static String toHexString(long value) {
return StringUtils.leftPad(Long.toHexString(value), 16, '0');
}
@Before
public void setup() {
this.reporter.clear();
spanIdsInHttpTrace.clear();
}
@Test
public void shouldReturnSpanFromWebFluxTraceContext() {
Mono<Long> mono = webClient.get().uri("http://localhost:" + port + "/test/ping")
.retrieve().bodyToMono(Long.class);
then(this.reporter.getSpans()).isEmpty();
Long newSpanId = mono.block();
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = getSpans();
then(spans).hasSize(1);
then(spans.get(0).kind()).isEqualTo(Span.Kind.SERVER);
then(spans.get(0).name()).isEqualTo("get /test/ping");
then(spans.get(0).id()).isEqualTo(toHexString(newSpanId));
then(this.tracer.currentSpan()).isNull();
});
}
private List<zipkin2.Span> getSpans() {
List<zipkin2.Span> spans = this.reporter.getSpans();
log.info("Reported the following spans: \n\n" + spans);
return spans;
}
@Test
public void shouldReturnSpanFromWebFluxSubscriptionContext() {
Mono<Long> mono = webClient.get()
.uri("http://localhost:" + port + "/test/pingFromContext").retrieve()
.bodyToMono(Long.class);
then(this.reporter.getSpans()).isEmpty();
Long newSpanId = mono.block();
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = getSpans();
then(spans).hasSize(1);
then(spans.get(0).kind()).isEqualTo(Span.Kind.SERVER);
then(spans.get(0).name()).isEqualTo("get /test/pingfromcontext");
then(spans.get(0).id()).isEqualTo(toHexString(newSpanId));
then(this.tracer.currentSpan()).isNull();
});
}
@Test
public void shouldContinueSpanInWebFlux() {
Mono<Long> mono = webClient.get()
.uri("http://localhost:" + port + "/test/continueSpan").retrieve()
.bodyToMono(Long.class);
then(this.reporter.getSpans()).isEmpty();
Long newSpanId = mono.block();
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = getSpans();
then(spans).hasSize(1);
then(spans.get(0).kind()).isEqualTo(Span.Kind.SERVER);
then(spans.get(0).name()).isEqualTo("get /test/continuespan");
then(spans.get(0).id()).isEqualTo(toHexString(newSpanId));
then(this.tracer.currentSpan()).isNull();
});
}
@Test
public void shouldCreateNewSpanInWebFlux() {
Mono<Long> mono = webClient.get()
.uri("http://localhost:" + port + "/test/newSpan1").retrieve()
.bodyToMono(Long.class);
then(this.reporter.getSpans()).isEmpty();
Long newSpanId = mono.block();
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = getSpans();
then(spans).hasSize(2);
then(spans.get(0).name()).isEqualTo("new-span-in-trace-context");
then(spans.get(0).id()).isEqualTo(toHexString(newSpanId));
then(spans.get(1).kind()).isEqualTo(Span.Kind.SERVER);
then(spans.get(1).name()).isEqualTo("get /test/newspan1");
then(this.tracer.currentSpan()).isNull();
});
}
@Test
public void shouldCreateNewSpanInWebFluxInSubscriberContext() {
Mono<Long> mono = webClient.get()
.uri("http://localhost:" + port + "/test/newSpan2").retrieve()
.bodyToMono(Long.class);
then(this.reporter.getSpans()).isEmpty();
Long newSpanId = mono.block();
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = getSpans();
then(spans).hasSize(2);
then(spans.get(0).name()).isEqualTo("new-span-in-subscriber-context");
then(spans.get(0).id()).isEqualTo(toHexString(newSpanId));
then(spans.get(1).kind()).isEqualTo(Span.Kind.SERVER);
then(spans.get(1).name()).isEqualTo("get /test/newspan2");
then(this.tracer.currentSpan()).isNull();
});
}
// TODO: Fix me
@Test
@Ignore("The order with HttpTraceWebFilter has changed in Boot")
public void shouldSetupCorrectSpanInHttpTrace() {
spanIdsInHttpTrace.clear();
Mono<Long> mono = webClient.get().uri("http://localhost:" + port + "/test/ping")
.retrieve().bodyToMono(Long.class);
then(this.reporter.getSpans()).isEmpty();
Long newSpanId = mono.block();
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = getSpans();
then(spans).hasSize(1);
then(spans.get(0).kind()).isEqualTo(Span.Kind.SERVER);
then(spans.get(0).name()).isEqualTo("get /test/ping");
then(spans.get(0).id()).isEqualTo(toHexString(newSpanId))
.isEqualTo(toHexString(spanIdsInHttpTrace.poll()));
then(this.tracer.currentSpan()).isNull();
});
}
@Configuration
@EnableAutoConfiguration
@DisableWebFluxSecurity
protected static class TestConfiguration {
@Bean
TestBean testBean(Tracer tracer) {
return new TestBean(tracer);
}
@Bean
Reporter<zipkin2.Span> spanReporter() {
return new ArrayListSpanReporter();
}
@Bean
Sampler alwaysSampler() {
return Sampler.ALWAYS_SAMPLE;
}
@Bean
AccessLoggingHttpTraceRepository accessLoggingHttpTraceRepository() {
return new AccessLoggingHttpTraceRepository();
}
}
static class AccessLoggingHttpTraceRepository implements HttpTraceRepository {
@Autowired
Tracer tracer;
@Override
public List<HttpTrace> findAll() {
return null;
}
@Override
public void add(HttpTrace trace) {
if (tracer.currentSpan() != null) {
spanIdsInHttpTrace.add(tracer.currentSpan().context().spanId());
}
}
}
@RestController
@RequestMapping("/test")
static class TestEndpoint {
private static final Logger log = LoggerFactory.getLogger(TestEndpoint.class);
@Autowired
Tracer tracer;
@Autowired
TestBean testBean;
@GetMapping("/ping")
Mono<Long> ping() {
return Mono.just(tracer.currentSpan().context().spanId());
}
@GetMapping("/pingFromContext")
Mono<Long> pingFromContext() {
return Mono.subscriberContext()
.doOnSuccess(context -> log.info("Ping from context"))
.flatMap(context -> Mono
.just(tracer.currentSpan().context().spanId()));
}
@GetMapping("/continueSpan")
Mono<Long> continueSpan() {
log.info("continueSpan");
return testBean.continueSpanInTraceContext();
}
@GetMapping("/newSpan1")
Mono<Long> newSpan1() {
log.info("newSpan1");
return testBean.newSpanInTraceContext();
}
@GetMapping("/newSpan2")
Mono<Long> newSpan2() {
log.info("newSpan2");
return testBean.newSpanInSubscriberContext();
}
}
static class TestBean {
private static final Logger log = LoggerFactory.getLogger(TestBean.class);
private final Tracer tracer;
TestBean(Tracer tracer) {
this.tracer = tracer;
}
@ContinueSpan
public Mono<Long> continueSpanInTraceContext() {
log.info("Continue");
Long span = tracer.currentSpan().context().spanId();
return Mono.defer(() -> Mono.just(span));
}
@NewSpan(name = "newSpanInTraceContext")
public Mono<Long> newSpanInTraceContext() {
log.info("New Span in Trace Context");
Long span = tracer.currentSpan().context().spanId();
return Mono.defer(() -> Mono.just(span));
}
@NewSpan(name = "newSpanInSubscriberContext")
public Mono<Long> newSpanInSubscriberContext() {
log.info("New Span in Subscriber Context");
Long span = tracer.currentSpan().context().spanId();
return Mono.subscriberContext()
.doOnSuccess(
context -> log.info("New Span in deferred Trace Context"))
.flatMap(context -> Mono.defer(
() -> Mono.just(span)));
}
}
}
|
Fixed the formatting
|
spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/annotation/SleuthSpanCreatorAspectWebFluxTests.java
|
Fixed the formatting
|
<ide><path>pring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/annotation/SleuthSpanCreatorAspectWebFluxTests.java
<ide> return Mono.subscriberContext()
<ide> .doOnSuccess(
<ide> context -> log.info("New Span in deferred Trace Context"))
<del> .flatMap(context -> Mono.defer(
<del> () -> Mono.just(span)));
<add> .flatMap(context -> Mono.defer(() -> Mono.just(span)));
<ide> }
<ide>
<ide> }
|
|
Java
|
apache-2.0
|
6c284579ab01bb3e15e73e8b106b5f8cf8b39a6b
| 0 |
ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma
|
/*
* The Gemma project
*
* Copyright (c) 2006 University of British Columbia
*
* 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 ubic.gemma.apps;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.lang3.time.StopWatch;
import ubic.basecode.dataStructure.matrix.DoubleMatrix;
import ubic.basecode.io.ByteArrayConverter;
import ubic.basecode.util.FileTools;
import ubic.gemma.analysis.expression.coexpression.links.LinkAnalysisConfig;
import ubic.gemma.analysis.expression.coexpression.links.LinkAnalysisConfig.NormalizationMethod;
import ubic.gemma.analysis.expression.coexpression.links.LinkAnalysisConfig.SingularThreshold;
import ubic.gemma.analysis.expression.coexpression.links.LinkAnalysisPersister;
import ubic.gemma.analysis.expression.coexpression.links.LinkAnalysisService;
import ubic.gemma.analysis.preprocess.filter.FilterConfig;
import ubic.gemma.loader.expression.simple.SimpleExpressionDataLoaderService;
import ubic.gemma.model.association.coexpression.CoexpressionService;
import ubic.gemma.model.common.auditAndSecurity.eventType.LinkAnalysisEvent;
import ubic.gemma.model.common.quantitationtype.GeneralType;
import ubic.gemma.model.common.quantitationtype.PrimitiveType;
import ubic.gemma.model.common.quantitationtype.QuantitationType;
import ubic.gemma.model.common.quantitationtype.ScaleType;
import ubic.gemma.model.common.quantitationtype.StandardQuantitationType;
import ubic.gemma.model.expression.arrayDesign.ArrayDesign;
import ubic.gemma.model.expression.arrayDesign.ArrayDesignService;
import ubic.gemma.model.expression.bioAssay.BioAssay;
import ubic.gemma.model.expression.bioAssayData.BioAssayDimension;
import ubic.gemma.model.expression.bioAssayData.ProcessedExpressionDataVector;
import ubic.gemma.model.expression.biomaterial.BioMaterial;
import ubic.gemma.model.expression.designElement.CompositeSequence;
import ubic.gemma.model.expression.experiment.BioAssaySet;
import ubic.gemma.model.expression.experiment.ExpressionExperiment;
import ubic.gemma.model.expression.experiment.ExpressionExperimentValueObject;
import ubic.gemma.util.EntityUtils;
/**
* Commandline tool to conduct link analysis.
*
* @author xiangwan
* @author paul (refactoring)
* @author vaneet
* @version $Id$
*/
public class LinkAnalysisCli extends ExpressionExperimentManipulatingCLI {
/**
* @param args
*/
public static void main( String[] args ) {
LinkAnalysisCli analysis = new LinkAnalysisCli();
StopWatch watch = new StopWatch();
watch.start();
try {
Exception ex = analysis.doWork( args );
if ( ex != null ) {
ex.printStackTrace();
}
watch.stop();
log.info( "Elapsed time: " + watch.getTime() / 1000 + " seconds" );
} catch ( Exception e ) {
throw new RuntimeException( e );
}
}
private LinkAnalysisService linkAnalysisService;
private FilterConfig filterConfig = new FilterConfig();
private LinkAnalysisConfig linkAnalysisConfig = new LinkAnalysisConfig();
private String dataFileName = null;
private String analysisTaxon = null;
private boolean updateNodeDegree = false;
@Override
public String getShortDesc() {
return "Analyze expression data sets for coexpressed genes";
}
/*
* (non-Javadoc)
*
* @see ubic.gemma.apps.ExpressionExperimentManipulatingCLI#buildOptions()
*/
@SuppressWarnings("static-access")
@Override
protected void buildOptions() {
super.buildOptions();
super.addDateOption();
Option nodeDegreeUpdate = OptionBuilder.withDescription(
"Update the node degree for taxon given by -t option. All other options ignored." ).create( 'n' );
addOption( nodeDegreeUpdate );
addOption( OptionBuilder.withDescription(
"Initialize links for taxon given by -t option, based on old data. All other options ignored." )
.create( "init" ) );
Option cdfCut = OptionBuilder.hasArg().withArgName( "Tolerance Thresold" )
.withDescription( "The tolerance threshold for coefficient value" ).withLongOpt( "cdfcut" )
.create( 'c' );
addOption( cdfCut );
Option tooSmallToKeep = OptionBuilder.hasArg().withArgName( "Cache Threshold" )
.withDescription( "The threshold for coefficient cache" ).withLongOpt( "cachecut" ).create( 'k' );
addOption( tooSmallToKeep );
Option fwe = OptionBuilder.hasArg().withArgName( "Family Wise Error Rate" )
.withDescription( "The setting for family wise error control" ).withLongOpt( "fwe" ).create( 'w' );
addOption( fwe );
buildFilterConfigOptions();
Option absoluteValue = OptionBuilder
.withDescription( "Use the absolute value of the correlation (rarely used)" ).withLongOpt( "abs" )
.create( 'a' );
addOption( absoluteValue );
Option noNegCorr = OptionBuilder.withDescription( "Omit negative correlated probes in link selection" ).create(
"nonegcorr" );
addOption( noNegCorr );
Option useDB = OptionBuilder.withDescription( "Don't save the results in the database (i.e., testing)" )
.withLongOpt( "nodb" ).create( 'd' );
addOption( useDB );
Option fileOpt = OptionBuilder
.hasArg()
.withArgName( "Expression data file" )
.withDescription(
"Provide expression data from a tab-delimited text file, rather than from the database. Implies 'nodb' and must also provide 'array' and 't' option" )
.create( "dataFile" );
addOption( fileOpt );
// supply taxon on command line
Option taxonNameOption = OptionBuilder.hasArg().withDescription( "Taxon species name e.g. 'mouse'" )
.create( "t" );
addOption( taxonNameOption );
Option arrayOpt = OptionBuilder
.hasArg()
.withArgName( "Array Design" )
.withDescription(
"Provide the short name of the array design used. Only needed if you are using the 'dataFile' option" )
.create( "array" );
addOption( arrayOpt );
Option textOutOpt = OptionBuilder
.withDescription(
"Output links as text. If multiple experiments are analyzed (e.g. using -f option) "
+ "results for each are put in a separate file in the current directory with the format {shortname}-links.txt. Otherwise output is to STDOUT" )
.create( "text" );
addOption( textOutOpt );
Option metricOption = OptionBuilder.hasArg().withArgName( "metric" )
.withDescription( "Similarity metric {pearson|spearman}, default is pearson" ).create( "metric" );
addOption( metricOption );
Option imagesOption = OptionBuilder.withDescription( "Suppress the generation of correlation matrix images" )
.create( "noimages" );
addOption( imagesOption );
Option normalizationOption = OptionBuilder
.hasArg()
.withArgName( "method" )
.withDescription(
"Normalization method to apply to the data matrix first: SVD, BALANCE, SPELL or omit this option for none (default=none)" )
.create( "normalizemethod" );
addOption( normalizationOption );
Option logTransformOption = OptionBuilder.withDescription(
"Log-transform the data prior to analysis, if it is not already transformed." ).create( "logtransform" );
addOption( logTransformOption );
Option subsetOption = OptionBuilder
.hasArg()
.withArgName( "Number of coexpression links to print out" )
.withDescription(
"Only a random subset of total coexpression links will be written to output with approximate "
+ "size given as the argument; recommended if thresholds are loose to avoid memory problems or gigantic files." )
.create( "subset" );
addOption( subsetOption );
Option chooseCutOption = OptionBuilder
.hasArg()
.withArgName( "Singular correlation threshold" )
.withDescription(
"Choose correlation threshold {fwe|cdfCut} to be used independently to select best links, default is none" )
.create( "choosecut" );
addOption( chooseCutOption );
// Option probeDegreeThresholdOption = OptionBuilder
// .hasArg()
// .withArgName( "threshold" )
// .withDescription(
// "Probes with greater than this number of links will be ignored; default is "
// + LinkAnalysisConfig.DEFAULT_PROBE_DEGREE_THRESHOLD ).create( "probeDegreeLim" );
// addOption( probeDegreeThresholdOption );
addForceOption();
addAutoOption();
}
private boolean initalizeFromOldData = false;
@Override
protected Exception doWork( String[] args ) {
Exception err = processCommandLine( "Link Analysis Data Loader", args );
if ( err != null ) {
return err;
}
if ( initalizeFromOldData ) {
log.info( "Initializing links from old data for " + this.taxon );
LinkAnalysisPersister s = this.getBean( LinkAnalysisPersister.class );
s.initializeLinksFromOldData( this.taxon );
return null;
} else if ( updateNodeDegree ) {
// we waste some time here getting the experiments.
loadTaxon();
this.getBean( CoexpressionService.class ).updateNodeDegrees( this.taxon );
return null;
}
this.linkAnalysisService = this.getBean( LinkAnalysisService.class );
if ( this.dataFileName != null ) {
/*
* Read vectors from file. Could provide as a matrix, but it's easier to provide vectors (less mess in later
* code)
*/
ArrayDesignService arrayDesignService = this.getBean( ArrayDesignService.class );
ArrayDesign arrayDesign = arrayDesignService.findByShortName( this.linkAnalysisConfig.getArrayName() );
if ( arrayDesign == null ) {
return new IllegalArgumentException( "No such array design " + this.linkAnalysisConfig.getArrayName() );
}
loadTaxon();
arrayDesign = arrayDesignService.thawLite( arrayDesign );
Collection<ProcessedExpressionDataVector> dataVectors = new HashSet<ProcessedExpressionDataVector>();
Map<String, CompositeSequence> csMap = new HashMap<String, CompositeSequence>();
for ( CompositeSequence cs : arrayDesign.getCompositeSequences() ) {
csMap.put( cs.getName(), cs );
}
QuantitationType qtype = makeQuantitationType();
SimpleExpressionDataLoaderService simpleExpressionDataLoaderService = this
.getBean( SimpleExpressionDataLoaderService.class );
ByteArrayConverter bArrayConverter = new ByteArrayConverter();
try (InputStream data = new FileInputStream( new File( this.dataFileName ) );) {
DoubleMatrix<String, String> matrix = simpleExpressionDataLoaderService.parse( data );
BioAssayDimension bad = makeBioAssayDimension( arrayDesign, matrix );
for ( int i = 0; i < matrix.rows(); i++ ) {
byte[] bdata = bArrayConverter.doubleArrayToBytes( matrix.getRow( i ) );
ProcessedExpressionDataVector vector = ProcessedExpressionDataVector.Factory.newInstance();
vector.setData( bdata );
CompositeSequence cs = csMap.get( matrix.getRowName( i ) );
if ( cs == null ) {
continue;
}
vector.setDesignElement( cs );
vector.setBioAssayDimension( bad );
vector.setQuantitationType( qtype );
dataVectors.add( vector );
}
log.info( "Read " + dataVectors.size() + " data vectors" );
} catch ( Exception e ) {
return e;
}
this.linkAnalysisService.processVectors( this.taxon, dataVectors, filterConfig, linkAnalysisConfig );
} else {
/*
* Do in decreasing order of size, to help capture more links earlier - reduces fragmentation.
*/
List<BioAssaySet> sees = new ArrayList<>( expressionExperiments );
if ( expressionExperiments.size() > 1 ) {
log.info( "Sorting data sets by number of samples, doing large data sets first." );
Collection<ExpressionExperimentValueObject> vos = eeService.loadValueObjects(
EntityUtils.getIds( expressionExperiments ), true );
final Map<Long, ExpressionExperimentValueObject> idMap = EntityUtils.getIdMap( vos );
// FIXME this doesn't know how to deal with BioAssaySets yet.
Collections.sort( sees, new Comparator<BioAssaySet>() {
@Override
public int compare( BioAssaySet o1, BioAssaySet o2 ) {
ExpressionExperimentValueObject e1 = idMap.get( o1.getId() );
ExpressionExperimentValueObject e2 = idMap.get( o2.getId() );
assert e1 != null : "No valueobject: " + e2;
assert e2 != null : "No valueobject: " + e1;
return -e1.getBioMaterialCount().compareTo( e2.getBioMaterialCount() );
}
} );
}
for ( BioAssaySet ee : sees ) {
if ( ee instanceof ExpressionExperiment ) {
processExperiment( ( ExpressionExperiment ) ee );
} else {
throw new UnsupportedOperationException( "Can't handle non-EE BioAssaySets yet" );
}
}
summarizeProcessing();
}
return null;
}
/**
*
*/
private void loadTaxon() {
this.taxon = taxonService.findByCommonName( analysisTaxon );
if ( this.taxon == null || !this.taxon.getIsGenesUsable() ) {
throw new IllegalArgumentException( "No such taxon or, does not have usable gene information: " + taxon );
}
log.debug( taxon + "is used" );
}
@Override
protected void processOptions() {
this.autoSeekEventType = LinkAnalysisEvent.class;
super.processOptions();
if ( hasOption( "init" ) ) {
initalizeFromOldData = true;
if ( hasOption( 't' ) ) {
this.analysisTaxon = this.getOptionValue( 't' );
} else {
log.error( "Must provide 'taxon' option when initializing from old data" );
this.bail( ErrorCode.INVALID_OPTION );
}
// all other options ignored.
return;
} else if ( hasOption( 'n' ) ) {
this.updateNodeDegree = true;
if ( hasOption( 't' ) ) {
this.analysisTaxon = this.getOptionValue( 't' );
} else {
log.error( "Must provide 'taxon' option when updating node degree" );
this.bail( ErrorCode.INVALID_OPTION );
}
// all other options ignored.
return;
}
if ( hasOption( "dataFile" ) ) {
if ( this.expressionExperiments.size() > 0 ) {
log.error( "The 'dataFile' option is incompatible with other data set selection options" );
this.bail( ErrorCode.INVALID_OPTION );
}
if ( hasOption( "array" ) ) {
this.linkAnalysisConfig.setArrayName( getOptionValue( "array" ) );
} else {
log.error( "Must provide 'array' option if you use 'dataFile" );
this.bail( ErrorCode.INVALID_OPTION );
}
if ( hasOption( 't' ) ) {
this.analysisTaxon = this.getOptionValue( 't' );
} else {
log.error( "Must provide 'taxon' option if you use 'dataFile' as RNA taxon may be different to array taxon" );
this.bail( ErrorCode.INVALID_OPTION );
}
this.dataFileName = getOptionValue( "dataFile" );
this.linkAnalysisConfig.setUseDb( false );
}
if ( hasOption( "logTransform" ) ) {
this.filterConfig.setLogTransform( true );
}
if ( hasOption( 'c' ) ) {
this.linkAnalysisConfig.setCdfCut( Double.parseDouble( getOptionValue( 'c' ) ) );
}
if ( hasOption( 'k' ) ) {
this.linkAnalysisConfig.setCorrelationCacheThreshold( Double.parseDouble( getOptionValue( 'k' ) ) );
}
if ( hasOption( 'w' ) ) {
this.linkAnalysisConfig.setFwe( Double.parseDouble( getOptionValue( 'w' ) ) );
}
getFilterConfigOptions();
if ( hasOption( 'a' ) ) {
this.linkAnalysisConfig.setAbsoluteValue( true );
}
if ( hasOption( 'd' ) ) {
this.linkAnalysisConfig.setUseDb( false );
}
if ( hasOption( "metric" ) ) {
this.linkAnalysisConfig.setMetric( getOptionValue( "metric" ) );
}
if ( hasOption( "text" ) ) {
this.linkAnalysisConfig.setTextOut( true );
}
if ( hasOption( "noimages" ) ) {
linkAnalysisConfig.setMakeSampleCorrMatImages( false );
}
if ( hasOption( "nonegcorr" ) ) {
this.linkAnalysisConfig.setOmitNegLinks( true );
}
if ( hasOption( "normalizemethod" ) ) {
String optionValue = getOptionValue( "normalizemethod" );
NormalizationMethod value = NormalizationMethod.valueOf( optionValue );
if ( value == null ) {
log.error( "No such normalization method: " + value );
this.bail( ErrorCode.INVALID_OPTION );
}
this.linkAnalysisConfig.setNormalizationMethod( value );
}
if ( hasOption( "subset" ) ) {
String subsetSize = getOptionValue( "subset" );
log.info( "Representative subset of links requested for output" );
this.linkAnalysisConfig.setSubsetSize( Double.parseDouble( subsetSize ) );
this.linkAnalysisConfig.setSubset( true );
}
if ( hasOption( "choosecut" ) ) {
String singularThreshold = getOptionValue( "choosecut" );
if ( singularThreshold.equals( "fwe" ) || singularThreshold.equals( "cdfCut" )
|| singularThreshold.equals( "none" ) ) {
log.info( "Singular correlation threshold chosen" );
this.linkAnalysisConfig.setSingularThreshold( SingularThreshold.valueOf( singularThreshold ) );
} else {
log.error( "Must choose 'fwe', 'cdfCut', or 'none' as the singular correlation threshold, defaulting to 'none'" );
}
}
if ( hasOption( "probeDegreeLim" ) ) {
this.linkAnalysisConfig.setProbeDegreeThreshold( getIntegerOptionValue( "probeDegreeLim" ) );
}
}
@SuppressWarnings("static-access")
private void buildFilterConfigOptions() {
Option minPresentFraction = OptionBuilder
.hasArg()
.withArgName( "Missing Value Threshold" )
.withDescription(
"Fraction of data points that must be present in a profile to be retained , default="
+ FilterConfig.DEFAULT_MINPRESENT_FRACTION ).withLongOpt( "missingcut" ).create( 'm' );
addOption( minPresentFraction );
Option lowExpressionCut = OptionBuilder
.hasArg()
.withArgName( "Expression Threshold" )
.withDescription(
"Fraction of expression vectors to reject based on low values, default="
+ FilterConfig.DEFAULT_LOWEXPRESSIONCUT ).withLongOpt( "lowcut" ).create( 'l' );
addOption( lowExpressionCut );
Option lowVarianceCut = OptionBuilder
.hasArg()
.withArgName( "Variance Threshold" )
.withDescription(
"Fraction of expression vectors to reject based on low variance (or coefficient of variation), default="
+ FilterConfig.DEFAULT_LOWVARIANCECUT ).withLongOpt( "lowvarcut" ).create( "lv" );
addOption( lowVarianceCut );
Option distinctValueCut = OptionBuilder
.hasArg()
.withArgName( "Fraction distinct values threshold" )
.withDescription(
"Fraction of values which must be distinct (NaN counts as one value), default="
+ FilterConfig.DEFAULT_DISTINCTVALUE_FRACTION ).withLongOpt( "distinctValCut" )
.create( "dv" );
addOption( distinctValueCut );
}
private void getFilterConfigOptions() {
if ( hasOption( 'm' ) ) {
filterConfig.setMinPresentFraction( Double.parseDouble( getOptionValue( 'm' ) ) );
}
if ( hasOption( 'l' ) ) {
filterConfig.setLowExpressionCut( Double.parseDouble( getOptionValue( 'l' ) ) );
}
if ( hasOption( "lv" ) ) {
filterConfig.setLowVarianceCut( Double.parseDouble( getOptionValue( "lv" ) ) );
}
if ( hasOption( "dv" ) ) {
filterConfig.setLowDistinctValueCut( Double.parseDouble( getOptionValue( "dv" ) ) );
}
}
/**
* @param arrayDesign
* @param matrix
* @return
*/
private BioAssayDimension makeBioAssayDimension( ArrayDesign arrayDesign, DoubleMatrix<String, String> matrix ) {
BioAssayDimension bad = BioAssayDimension.Factory.newInstance();
bad.setName( "For " + this.dataFileName );
bad.setDescription( "Generated from flat file" );
for ( int i = 0; i < matrix.columns(); i++ ) {
Object columnName = matrix.getColName( i );
BioMaterial bioMaterial = BioMaterial.Factory.newInstance();
bioMaterial.setName( columnName.toString() );
bioMaterial.setSourceTaxon( taxon );
BioAssay assay = BioAssay.Factory.newInstance();
assay.setName( columnName.toString() );
assay.setArrayDesignUsed( arrayDesign );
assay.setSampleUsed( bioMaterial );
assay.setIsOutlier( false );
assay.setSequencePairedReads( false );
bad.getBioAssays().add( assay );
}
return bad;
}
/**
* @return
*/
private QuantitationType makeQuantitationType() {
QuantitationType qtype = QuantitationType.Factory.newInstance();
qtype.setName( "Dummy" );
qtype.setGeneralType( GeneralType.QUANTITATIVE );
qtype.setRepresentation( PrimitiveType.DOUBLE ); // no choice here
qtype.setIsPreferred( Boolean.TRUE );
qtype.setIsNormalized( Boolean.TRUE );
qtype.setIsBackgroundSubtracted( Boolean.TRUE );
qtype.setIsBackground( false );
qtype.setType( StandardQuantitationType.AMOUNT );// this shouldn't get used, just filled in to keep everybody
// happy.
qtype.setIsMaskedPreferred( true );
qtype.setScale( ScaleType.OTHER );// this shouldn't get used, just filled in to keep everybody happy.
qtype.setIsRatio( false ); // this shouldn't get used, just filled in to keep everybody happy.
return qtype;
}
/**
* @param ee
*/
private void processExperiment( ExpressionExperiment ee ) {
ee = eeService.thaw( ee );
/*
* If we're not using the database, always run it.
*/
if ( linkAnalysisConfig.isUseDb() && !force && !needToRun( ee, LinkAnalysisEvent.class ) ) {
log.info( "Can't or Don't need to run " + ee );
return;
}
/*
* Note that auditing is handled by the service.
*/
StopWatch sw = new StopWatch();
sw.start();
try {
if ( this.expressionExperiments.size() > 1 && linkAnalysisConfig.isTextOut() ) {
linkAnalysisConfig.setOutputFile( new File( FileTools.cleanForFileName( ee.getShortName() )
+ "-links.txt" ) );
}
log.info( "==== Starting: [" + ee.getShortName() + "] ======" );
linkAnalysisService.process( ee, filterConfig, linkAnalysisConfig );
successObjects.add( ee.toString() );
} catch ( Exception e ) {
errorObjects.add( ee + ": " + e.getMessage() );
log.error( "**** Exception while processing " + ee + ": " + e.getMessage() + " ********" );
log.error( e, e );
}
log.info( "==== Done: [" + ee.getShortName() + "] ======" );
log.info( "Time elapsed: " + String.format( "%.2f", sw.getTime() / 1000.0 / 60.0 ) + " minutes" );
}
}
|
gemma-core/src/main/java/ubic/gemma/apps/LinkAnalysisCli.java
|
/*
* The Gemma project
*
* Copyright (c) 2006 University of British Columbia
*
* 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 ubic.gemma.apps;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.lang3.time.StopWatch;
import ubic.basecode.dataStructure.matrix.DoubleMatrix;
import ubic.basecode.io.ByteArrayConverter;
import ubic.basecode.util.FileTools;
import ubic.gemma.analysis.expression.coexpression.links.LinkAnalysisConfig;
import ubic.gemma.analysis.expression.coexpression.links.LinkAnalysisConfig.NormalizationMethod;
import ubic.gemma.analysis.expression.coexpression.links.LinkAnalysisConfig.SingularThreshold;
import ubic.gemma.analysis.expression.coexpression.links.LinkAnalysisPersister;
import ubic.gemma.analysis.expression.coexpression.links.LinkAnalysisService;
import ubic.gemma.analysis.preprocess.filter.FilterConfig;
import ubic.gemma.loader.expression.simple.SimpleExpressionDataLoaderService;
import ubic.gemma.model.association.coexpression.CoexpressionService;
import ubic.gemma.model.common.auditAndSecurity.eventType.LinkAnalysisEvent;
import ubic.gemma.model.common.quantitationtype.GeneralType;
import ubic.gemma.model.common.quantitationtype.PrimitiveType;
import ubic.gemma.model.common.quantitationtype.QuantitationType;
import ubic.gemma.model.common.quantitationtype.ScaleType;
import ubic.gemma.model.common.quantitationtype.StandardQuantitationType;
import ubic.gemma.model.expression.arrayDesign.ArrayDesign;
import ubic.gemma.model.expression.arrayDesign.ArrayDesignService;
import ubic.gemma.model.expression.bioAssay.BioAssay;
import ubic.gemma.model.expression.bioAssayData.BioAssayDimension;
import ubic.gemma.model.expression.bioAssayData.ProcessedExpressionDataVector;
import ubic.gemma.model.expression.biomaterial.BioMaterial;
import ubic.gemma.model.expression.designElement.CompositeSequence;
import ubic.gemma.model.expression.experiment.BioAssaySet;
import ubic.gemma.model.expression.experiment.ExpressionExperiment;
import ubic.gemma.model.expression.experiment.ExpressionExperimentValueObject;
import ubic.gemma.util.EntityUtils;
/**
* Commandline tool to conduct link analysis.
*
* @author xiangwan
* @author paul (refactoring)
* @author vaneet
* @version $Id$
*/
public class LinkAnalysisCli extends ExpressionExperimentManipulatingCLI {
/**
* @param args
*/
public static void main( String[] args ) {
LinkAnalysisCli analysis = new LinkAnalysisCli();
StopWatch watch = new StopWatch();
watch.start();
try {
Exception ex = analysis.doWork( args );
if ( ex != null ) {
ex.printStackTrace();
}
watch.stop();
log.info( "Elapsed time: " + watch.getTime() / 1000 + " seconds" );
} catch ( Exception e ) {
throw new RuntimeException( e );
}
}
private LinkAnalysisService linkAnalysisService;
private FilterConfig filterConfig = new FilterConfig();
private LinkAnalysisConfig linkAnalysisConfig = new LinkAnalysisConfig();
private String dataFileName = null;
private String analysisTaxon = null;
private boolean updateNodeDegree = false;
@Override
public String getShortDesc() {
return "Analyze expression data sets for coexpressed genes";
}
/*
* (non-Javadoc)
*
* @see ubic.gemma.apps.ExpressionExperimentManipulatingCLI#buildOptions()
*/
@SuppressWarnings("static-access")
@Override
protected void buildOptions() {
super.buildOptions();
super.addDateOption();
Option nodeDegreeUpdate = OptionBuilder.withDescription(
"Update the node degree for taxon given by -t option. All other options ignored." ).create( 'n' );
addOption( nodeDegreeUpdate );
addOption( OptionBuilder.withDescription(
"Initialize links for taxon given by -t option, based on old data. All other options ignored." )
.create( "init" ) );
Option cdfCut = OptionBuilder.hasArg().withArgName( "Tolerance Thresold" )
.withDescription( "The tolerance threshold for coefficient value" ).withLongOpt( "cdfcut" )
.create( 'c' );
addOption( cdfCut );
Option tooSmallToKeep = OptionBuilder.hasArg().withArgName( "Cache Threshold" )
.withDescription( "The threshold for coefficient cache" ).withLongOpt( "cachecut" ).create( 'k' );
addOption( tooSmallToKeep );
Option fwe = OptionBuilder.hasArg().withArgName( "Family Wise Error Rate" )
.withDescription( "The setting for family wise error control" ).withLongOpt( "fwe" ).create( 'w' );
addOption( fwe );
buildFilterConfigOptions();
Option absoluteValue = OptionBuilder
.withDescription( "Use the absolute value of the correlation (rarely used)" ).withLongOpt( "abs" )
.create( 'a' );
addOption( absoluteValue );
Option noNegCorr = OptionBuilder.withDescription( "Omit negative correlated probes in link selection" ).create(
"nonegcorr" );
addOption( noNegCorr );
Option useDB = OptionBuilder.withDescription( "Don't save the results in the database (i.e., testing)" )
.withLongOpt( "nodb" ).create( 'd' );
addOption( useDB );
Option fileOpt = OptionBuilder
.hasArg()
.withArgName( "Expression data file" )
.withDescription(
"Provide expression data from a tab-delimited text file, rather than from the database. Implies 'nodb' and must also provide 'array' and 't' option" )
.create( "dataFile" );
addOption( fileOpt );
// supply taxon on command line
Option taxonNameOption = OptionBuilder.hasArg().withDescription( "Taxon species name e.g. 'mouse'" )
.create( "t" );
addOption( taxonNameOption );
Option arrayOpt = OptionBuilder
.hasArg()
.withArgName( "Array Design" )
.withDescription(
"Provide the short name of the array design used. Only needed if you are using the 'dataFile' option" )
.create( "array" );
addOption( arrayOpt );
Option textOutOpt = OptionBuilder
.withDescription(
"Output links as text. If multiple experiments are analyzed (e.g. using -f option) "
+ "results for each are put in a separate file in the current directory with the format {shortname}-links.txt. Otherwise output is to STDOUT" )
.create( "text" );
addOption( textOutOpt );
Option metricOption = OptionBuilder.hasArg().withArgName( "metric" )
.withDescription( "Similarity metric {pearson|spearman}, default is pearson" ).create( "metric" );
addOption( metricOption );
Option imagesOption = OptionBuilder.withDescription( "Suppress the generation of correlation matrix images" )
.create( "noimages" );
addOption( imagesOption );
Option normalizationOption = OptionBuilder
.hasArg()
.withArgName( "method" )
.withDescription(
"Normalization method to apply to the data matrix first: SVD, BALANCE, SPELL or omit this option for none (default=none)" )
.create( "normalizemethod" );
addOption( normalizationOption );
Option logTransformOption = OptionBuilder.withDescription(
"Log-transform the data prior to analysis, if it is not already transformed." ).create( "logtransform" );
addOption( logTransformOption );
Option subsetOption = OptionBuilder
.hasArg()
.withArgName( "Number of coexpression links to print out" )
.withDescription(
"Only a random subset of total coexpression links will be written to output with approximate "
+ "size given as the argument; recommended if thresholds are loose to avoid memory problems or gigantic files." )
.create( "subset" );
addOption( subsetOption );
Option chooseCutOption = OptionBuilder
.hasArg()
.withArgName( "Singular correlation threshold" )
.withDescription(
"Choose correlation threshold {fwe|cdfCut} to be used independently to select best links, default is none" )
.create( "choosecut" );
addOption( chooseCutOption );
// Option probeDegreeThresholdOption = OptionBuilder
// .hasArg()
// .withArgName( "threshold" )
// .withDescription(
// "Probes with greater than this number of links will be ignored; default is "
// + LinkAnalysisConfig.DEFAULT_PROBE_DEGREE_THRESHOLD ).create( "probeDegreeLim" );
// addOption( probeDegreeThresholdOption );
addForceOption();
addAutoOption();
}
private boolean initalizeFromOldData = false;
@Override
protected Exception doWork( String[] args ) {
Exception err = processCommandLine( "Link Analysis Data Loader", args );
if ( err != null ) {
return err;
}
if ( initalizeFromOldData ) {
log.info( "Initializing links from old data for " + this.taxon );
LinkAnalysisPersister s = this.getBean( LinkAnalysisPersister.class );
s.initializeLinksFromOldData( this.taxon );
return null;
} else if ( updateNodeDegree ) {
// we waste some time here getting the experiments.
loadTaxon();
this.getBean( CoexpressionService.class ).updateNodeDegrees( this.taxon );
return null;
}
this.linkAnalysisService = this.getBean( LinkAnalysisService.class );
if ( this.dataFileName != null ) {
/*
* Read vectors from file. Could provide as a matrix, but it's easier to provide vectors (less mess in later
* code)
*/
ArrayDesignService arrayDesignService = this.getBean( ArrayDesignService.class );
ArrayDesign arrayDesign = arrayDesignService.findByShortName( this.linkAnalysisConfig.getArrayName() );
if ( arrayDesign == null ) {
return new IllegalArgumentException( "No such array design " + this.linkAnalysisConfig.getArrayName() );
}
loadTaxon();
arrayDesign = arrayDesignService.thawLite( arrayDesign );
Collection<ProcessedExpressionDataVector> dataVectors = new HashSet<ProcessedExpressionDataVector>();
Map<String, CompositeSequence> csMap = new HashMap<String, CompositeSequence>();
for ( CompositeSequence cs : arrayDesign.getCompositeSequences() ) {
csMap.put( cs.getName(), cs );
}
QuantitationType qtype = makeQuantitationType();
SimpleExpressionDataLoaderService simpleExpressionDataLoaderService = this
.getBean( SimpleExpressionDataLoaderService.class );
ByteArrayConverter bArrayConverter = new ByteArrayConverter();
try (InputStream data = new FileInputStream( new File( this.dataFileName ) );) {
DoubleMatrix<String, String> matrix = simpleExpressionDataLoaderService.parse( data );
BioAssayDimension bad = makeBioAssayDimension( arrayDesign, matrix );
for ( int i = 0; i < matrix.rows(); i++ ) {
byte[] bdata = bArrayConverter.doubleArrayToBytes( matrix.getRow( i ) );
ProcessedExpressionDataVector vector = ProcessedExpressionDataVector.Factory.newInstance();
vector.setData( bdata );
CompositeSequence cs = csMap.get( matrix.getRowName( i ) );
if ( cs == null ) {
continue;
}
vector.setDesignElement( cs );
vector.setBioAssayDimension( bad );
vector.setQuantitationType( qtype );
dataVectors.add( vector );
}
log.info( "Read " + dataVectors.size() + " data vectors" );
} catch ( Exception e ) {
return e;
}
this.linkAnalysisService.processVectors( this.taxon, dataVectors, filterConfig, linkAnalysisConfig );
} else {
/*
* Do in decreasing order of size, to help capture more links earlier - reduces fragmentation.
*/
List<BioAssaySet> sees = new ArrayList<>( expressionExperiments );
if ( expressionExperiments.size() > 1 ) {
log.info( "Sorting data sets by number of samples, doing large data sets first." );
Collection<ExpressionExperimentValueObject> vos = eeService.loadValueObjects(
EntityUtils.getIds( expressionExperiments ), true );
final Map<Long, ExpressionExperimentValueObject> idMap = EntityUtils.getIdMap( vos );
// FIXME this doesn't know how to deal with BioAssaySets yet.
Collections.sort( sees, new Comparator<BioAssaySet>() {
@Override
public int compare( BioAssaySet o1, BioAssaySet o2 ) {
ExpressionExperimentValueObject e1 = idMap.get( o1.getId() );
ExpressionExperimentValueObject e2 = idMap.get( o2.getId() );
assert e1 != null : "No valueobject: " + e2;
assert e2 != null : "No valueobject: " + e1;
return -e1.getBioMaterialCount().compareTo( e2.getBioMaterialCount() );
}
} );
}
for ( BioAssaySet ee : sees ) {
if ( ee instanceof ExpressionExperiment ) {
processExperiment( ( ExpressionExperiment ) ee );
} else {
throw new UnsupportedOperationException( "Can't handle non-EE BioAssaySets yet" );
}
}
summarizeProcessing();
}
return null;
}
/**
*
*/
private void loadTaxon() {
this.taxon = taxonService.findByCommonName( analysisTaxon );
if ( this.taxon == null || !this.taxon.getIsSpecies() ) {
throw new IllegalArgumentException( "No such taxon held in system please check that it is a species: "
+ taxon );
}
log.debug( taxon + "is used" );
}
@Override
protected void processOptions() {
this.autoSeekEventType = LinkAnalysisEvent.class;
super.processOptions();
if ( hasOption( "init" ) ) {
initalizeFromOldData = true;
if ( hasOption( 't' ) ) {
this.analysisTaxon = this.getOptionValue( 't' );
} else {
log.error( "Must provide 'taxon' option when initializing from old data" );
this.bail( ErrorCode.INVALID_OPTION );
}
// all other options ignored.
return;
} else if ( hasOption( 'n' ) ) {
this.updateNodeDegree = true;
if ( hasOption( 't' ) ) {
this.analysisTaxon = this.getOptionValue( 't' );
} else {
log.error( "Must provide 'taxon' option when updating node degree" );
this.bail( ErrorCode.INVALID_OPTION );
}
// all other options ignored.
return;
}
if ( hasOption( "dataFile" ) ) {
if ( this.expressionExperiments.size() > 0 ) {
log.error( "The 'dataFile' option is incompatible with other data set selection options" );
this.bail( ErrorCode.INVALID_OPTION );
}
if ( hasOption( "array" ) ) {
this.linkAnalysisConfig.setArrayName( getOptionValue( "array" ) );
} else {
log.error( "Must provide 'array' option if you use 'dataFile" );
this.bail( ErrorCode.INVALID_OPTION );
}
if ( hasOption( 't' ) ) {
this.analysisTaxon = this.getOptionValue( 't' );
} else {
log.error( "Must provide 'taxon' option if you use 'dataFile' as RNA taxon may be different to array taxon" );
this.bail( ErrorCode.INVALID_OPTION );
}
this.dataFileName = getOptionValue( "dataFile" );
this.linkAnalysisConfig.setUseDb( false );
}
if ( hasOption( "logTransform" ) ) {
this.filterConfig.setLogTransform( true );
}
if ( hasOption( 'c' ) ) {
this.linkAnalysisConfig.setCdfCut( Double.parseDouble( getOptionValue( 'c' ) ) );
}
if ( hasOption( 'k' ) ) {
this.linkAnalysisConfig.setCorrelationCacheThreshold( Double.parseDouble( getOptionValue( 'k' ) ) );
}
if ( hasOption( 'w' ) ) {
this.linkAnalysisConfig.setFwe( Double.parseDouble( getOptionValue( 'w' ) ) );
}
getFilterConfigOptions();
if ( hasOption( 'a' ) ) {
this.linkAnalysisConfig.setAbsoluteValue( true );
}
if ( hasOption( 'd' ) ) {
this.linkAnalysisConfig.setUseDb( false );
}
if ( hasOption( "metric" ) ) {
this.linkAnalysisConfig.setMetric( getOptionValue( "metric" ) );
}
if ( hasOption( "text" ) ) {
this.linkAnalysisConfig.setTextOut( true );
}
if ( hasOption( "noimages" ) ) {
linkAnalysisConfig.setMakeSampleCorrMatImages( false );
}
if ( hasOption( "nonegcorr" ) ) {
this.linkAnalysisConfig.setOmitNegLinks( true );
}
if ( hasOption( "normalizemethod" ) ) {
String optionValue = getOptionValue( "normalizemethod" );
NormalizationMethod value = NormalizationMethod.valueOf( optionValue );
if ( value == null ) {
log.error( "No such normalization method: " + value );
this.bail( ErrorCode.INVALID_OPTION );
}
this.linkAnalysisConfig.setNormalizationMethod( value );
}
if ( hasOption( "subset" ) ) {
String subsetSize = getOptionValue( "subset" );
log.info( "Representative subset of links requested for output" );
this.linkAnalysisConfig.setSubsetSize( Double.parseDouble( subsetSize ) );
this.linkAnalysisConfig.setSubset( true );
}
if ( hasOption( "choosecut" ) ) {
String singularThreshold = getOptionValue( "choosecut" );
if ( singularThreshold.equals( "fwe" ) || singularThreshold.equals( "cdfCut" )
|| singularThreshold.equals( "none" ) ) {
log.info( "Singular correlation threshold chosen" );
this.linkAnalysisConfig.setSingularThreshold( SingularThreshold.valueOf( singularThreshold ) );
} else {
log.error( "Must choose 'fwe', 'cdfCut', or 'none' as the singular correlation threshold, defaulting to 'none'" );
}
}
if ( hasOption( "probeDegreeLim" ) ) {
this.linkAnalysisConfig.setProbeDegreeThreshold( getIntegerOptionValue( "probeDegreeLim" ) );
}
}
@SuppressWarnings("static-access")
private void buildFilterConfigOptions() {
Option minPresentFraction = OptionBuilder
.hasArg()
.withArgName( "Missing Value Threshold" )
.withDescription(
"Fraction of data points that must be present in a profile to be retained , default="
+ FilterConfig.DEFAULT_MINPRESENT_FRACTION ).withLongOpt( "missingcut" ).create( 'm' );
addOption( minPresentFraction );
Option lowExpressionCut = OptionBuilder
.hasArg()
.withArgName( "Expression Threshold" )
.withDescription(
"Fraction of expression vectors to reject based on low values, default="
+ FilterConfig.DEFAULT_LOWEXPRESSIONCUT ).withLongOpt( "lowcut" ).create( 'l' );
addOption( lowExpressionCut );
Option lowVarianceCut = OptionBuilder
.hasArg()
.withArgName( "Variance Threshold" )
.withDescription(
"Fraction of expression vectors to reject based on low variance (or coefficient of variation), default="
+ FilterConfig.DEFAULT_LOWVARIANCECUT ).withLongOpt( "lowvarcut" ).create( "lv" );
addOption( lowVarianceCut );
Option distinctValueCut = OptionBuilder
.hasArg()
.withArgName( "Fraction distinct values threshold" )
.withDescription(
"Fraction of values which must be distinct (NaN counts as one value), default="
+ FilterConfig.DEFAULT_DISTINCTVALUE_FRACTION ).withLongOpt( "distinctValCut" )
.create( "dv" );
addOption( distinctValueCut );
}
private void getFilterConfigOptions() {
if ( hasOption( 'm' ) ) {
filterConfig.setMinPresentFraction( Double.parseDouble( getOptionValue( 'm' ) ) );
}
if ( hasOption( 'l' ) ) {
filterConfig.setLowExpressionCut( Double.parseDouble( getOptionValue( 'l' ) ) );
}
if ( hasOption( "lv" ) ) {
filterConfig.setLowVarianceCut( Double.parseDouble( getOptionValue( "lv" ) ) );
}
if ( hasOption( "dv" ) ) {
filterConfig.setLowDistinctValueCut( Double.parseDouble( getOptionValue( "dv" ) ) );
}
}
/**
* @param arrayDesign
* @param matrix
* @return
*/
private BioAssayDimension makeBioAssayDimension( ArrayDesign arrayDesign, DoubleMatrix<String, String> matrix ) {
BioAssayDimension bad = BioAssayDimension.Factory.newInstance();
bad.setName( "For " + this.dataFileName );
bad.setDescription( "Generated from flat file" );
for ( int i = 0; i < matrix.columns(); i++ ) {
Object columnName = matrix.getColName( i );
BioMaterial bioMaterial = BioMaterial.Factory.newInstance();
bioMaterial.setName( columnName.toString() );
bioMaterial.setSourceTaxon( taxon );
BioAssay assay = BioAssay.Factory.newInstance();
assay.setName( columnName.toString() );
assay.setArrayDesignUsed( arrayDesign );
assay.setSampleUsed( bioMaterial );
assay.setIsOutlier( false );
assay.setSequencePairedReads( false );
bad.getBioAssays().add( assay );
}
return bad;
}
/**
* @return
*/
private QuantitationType makeQuantitationType() {
QuantitationType qtype = QuantitationType.Factory.newInstance();
qtype.setName( "Dummy" );
qtype.setGeneralType( GeneralType.QUANTITATIVE );
qtype.setRepresentation( PrimitiveType.DOUBLE ); // no choice here
qtype.setIsPreferred( Boolean.TRUE );
qtype.setIsNormalized( Boolean.TRUE );
qtype.setIsBackgroundSubtracted( Boolean.TRUE );
qtype.setIsBackground( false );
qtype.setType( StandardQuantitationType.AMOUNT );// this shouldn't get used, just filled in to keep everybody
// happy.
qtype.setIsMaskedPreferred( true );
qtype.setScale( ScaleType.OTHER );// this shouldn't get used, just filled in to keep everybody happy.
qtype.setIsRatio( false ); // this shouldn't get used, just filled in to keep everybody happy.
return qtype;
}
/**
* @param ee
*/
private void processExperiment( ExpressionExperiment ee ) {
ee = eeService.thaw( ee );
/*
* If we're not using the database, always run it.
*/
if ( linkAnalysisConfig.isUseDb() && !force && !needToRun( ee, LinkAnalysisEvent.class ) ) {
log.info( "Can't or Don't need to run " + ee );
return;
}
/*
* Note that auditing is handled by the service.
*/
StopWatch sw = new StopWatch();
sw.start();
try {
if ( this.expressionExperiments.size() > 1 && linkAnalysisConfig.isTextOut() ) {
linkAnalysisConfig.setOutputFile( new File( FileTools.cleanForFileName( ee.getShortName() )
+ "-links.txt" ) );
}
log.info( "==== Starting: [" + ee.getShortName() + "] ======" );
linkAnalysisService.process( ee, filterConfig, linkAnalysisConfig );
successObjects.add( ee.toString() );
} catch ( Exception e ) {
errorObjects.add( ee + ": " + e.getMessage() );
log.error( "**** Exception while processing " + ee + ": " + e.getMessage() + " ********" );
log.error( e, e );
}
log.info( "==== Done: [" + ee.getShortName() + "] ======" );
log.info( "Time elapsed: " + String.format( "%.2f", sw.getTime() / 1000.0 / 60.0 ) + " minutes" );
}
}
|
okay to run on orgs that have genes, does not have to be a species
|
gemma-core/src/main/java/ubic/gemma/apps/LinkAnalysisCli.java
|
okay to run on orgs that have genes, does not have to be a species
|
<ide><path>emma-core/src/main/java/ubic/gemma/apps/LinkAnalysisCli.java
<ide> */
<ide> private void loadTaxon() {
<ide> this.taxon = taxonService.findByCommonName( analysisTaxon );
<del> if ( this.taxon == null || !this.taxon.getIsSpecies() ) {
<del> throw new IllegalArgumentException( "No such taxon held in system please check that it is a species: "
<del> + taxon );
<add> if ( this.taxon == null || !this.taxon.getIsGenesUsable() ) {
<add> throw new IllegalArgumentException( "No such taxon or, does not have usable gene information: " + taxon );
<ide> }
<ide> log.debug( taxon + "is used" );
<ide> }
|
|
Java
|
apache-2.0
|
d305db7f2b8425d7fa25d5c53994673ffdfd4405
| 0 |
alphazero/jredis,gshlsh17/jredis
|
/*
* Copyright 2009 Joubin Houshyar
*
* 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.jredis;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
/**
* <p>This is effectively a one to one mapping to Redis commands. And that
* is basically it.
* <p>Beyond that , just be aware that an implementation may throw {@link ClientRuntimeException}
* or an extension to report problems (typically connectivity) or features {@link NotSupportedException}
* or bugs. These are {@link RuntimeException}.
*
* @author joubin ([email protected])
* @version alpha.0, 04/02/09
* @since alpha.0
*
*/
public interface JRedis {
// ------------------------------------------------------------------------
// Semantic context methods
// ------------------------------------------------------------------------
// TODO: reach a decision on whether to include this or not.
// /**
// * Provides for access to an interface providing standard Java collections
// * semantics on the specified parametric type.
// * <p>
// * The type <code>T</code> can be of 3 categories:
// * <ol>
// * <li>It is
// * </ol>
// * @param <T> a Java class type that you wish to perform {@link Set},
// * {@link List}, or {@link Map}, operations.
// * @return the {@link JavaSemantics} for type <code>T</code>, if the type specified meets
// * the required initialization characteristics.
// */
// public <T> JavaSemantics<T> semantic (Class<T> type) throws ClientRuntimeException;
// ------------------------------------------------------------------------
// Security and User Management
// NOTE: Moved to ConnectionSpec
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// "Connection Handling"
// ------------------------------------------------------------------------
/**
* Ping redis
* @return true (unless not authorized)
* @throws RedisException (as of ver. 0.09) in case of unauthorized access
*/
public JRedis ping () throws RedisException;
/**
* Disconnects the client.
* @Redis QUIT
*/
public void quit ();
// ------------------------------------------------------------------------
// "Commands operating on string values"
// ------------------------------------------------------------------------
/**
* Bind the value to key.
* @Redis SET
* @param key any UTF-8 {@link String}
* @param value any bytes. For current data size limitations, refer to
* Redis documentation.
* @throws RedisException on user error.
* @throws ProviderException on un-documented features/bug
* @throws ClientRuntimeException on errors due to operating environment (Redis or network)
*/
public void set (String key, byte[] value) throws RedisException;
/**
* Convenient method for {@link String} data binding
* @Redis SET
* @param key
* @param stringValue
* @throws RedisException
* @see {@link JRedis#set(String, byte[])}
*/
public void set (String key, String stringValue) throws RedisException;
/**
* Convenient method for {@link String} numeric values binding
* @Redis SET
* @param key
* @param numberValue
* @throws RedisException
* @see {@link JRedis#set(String, byte[])}
*/
public void set (String key, Number numberValue) throws RedisException;
/**
* Binds the given java {@link Object} to the key. Serialization format is
* implementation specific. Simple implementations may apply the basic {@link Serializable}
* protocol.
* @Redis SET
* @param <T>
* @param key
* @param object
* @throws RedisException
* @see {@link JRedis#set(String, byte[])}
*/
public <T extends Serializable>
void set (String key, T object) throws RedisException;
/**
* @Redis SETNX
* @param key
* @param value
* @return
* @throws RedisException
*/
public boolean setnx (String key, byte[] value) throws RedisException;
public boolean setnx (String key, String stringValue) throws RedisException;
public boolean setnx (String key, Number numberValue) throws RedisException;
public <T extends Serializable>
boolean setnx (String key, T object) throws RedisException;
/**
* @Redis GET
* @param key
* @return
* @throws RedisException
*/
public byte[] get (String key) throws RedisException;
public byte[] getset (String key, byte[] value) throws RedisException;
public byte[] getset (String key, String stringValue) throws RedisException;
public byte[] getset (String key, Number numberValue) throws RedisException;
public <T extends Serializable>
byte[] getset (String key, T object) throws RedisException;
/**
* @Redis MGET
* @param key
* @param moreKeys
* @return
* @throws RedisException
*/
public List<byte[]> mget(String key, String...moreKeys) throws RedisException;
/**
* @Redis INCR
* @param key
* @return
* @throws RedisException
*/
public long incr (String key) throws RedisException;
/**
* @Redis INCRBY
* @param key
* @param delta
* @return
* @throws RedisException
*/
public long incrby (String key, int delta) throws RedisException;
/**
* @Redis DECR
* @param key
* @return
* @throws RedisException
*/
public long decr (String key) throws RedisException;
/**
* @Redis DECRBY
* @param key
* @param delta
* @return
* @throws RedisException
*/
public long decrby (String key, int delta) throws RedisException;
/**
* @Redis EXISTS
* @param key
* @return
* @throws RedisException
*/
public boolean exists(String key) throws RedisException;
/**
* @Redis DEL
* @param key
* @return
* @throws RedisException
*/
public boolean del (String key) throws RedisException;
/**
* @Redis TYPE
* @param key
* @return
* @throws RedisException
*/
public RedisType type (String key) throws RedisException;
// ------------------------------------------------------------------------
// "Commands operating on the key space"
// ------------------------------------------------------------------------
/**
* @Redis KEYS
* @param pattern
* @return
* @throws RedisException
*/
public List<String> keys (String pattern) throws RedisException;
/**
* Convenience method. Equivalent to calling <code>jredis.keys("*");</code>
* @Redis KEYS
* @return
* @throws RedisException
* @see {@link JRedis#keys(String)}
*/
public List<String> keys () throws RedisException;
/**
* @Redis RANDOMKEY
* @return
* @throws RedisException
*/
public String randomkey() throws RedisException;
/**
* @Redis RENAME
* @param oldkey
* @param newkey
* @throws RedisException
*/
public void rename (String oldkey, String newkey) throws RedisException;
/**
* @Redis RENAMENX
* @param oldkey
* @param brandnewkey
* @return
* @throws RedisException
*/
public boolean renamenx (String oldkey, String brandnewkey) throws RedisException;
/**
* @Redis DBSIZE
* @return
* @throws RedisException
*/
public long dbsize () throws RedisException;
/**
* @Redis EXPIRE
* @param key
* @param ttlseconds
* @return
* @throws RedisException
*/
public boolean expire (String key, int ttlseconds) throws RedisException;
/**
* @Redis TTL
* @param key
* @return
* @throws RedisException
*/
public long ttl (String key) throws RedisException;
// ------------------------------------------------------------------------
// Commands operating on lists
// ------------------------------------------------------------------------
/**
* @Redis RPUSH
* @param listkey
* @param value
* @throws RedisException
*/
public void rpush (String listkey, byte[] value) throws RedisException;
public void rpush (String listkey, String stringValue) throws RedisException;
public void rpush (String listkey, Number numberValue) throws RedisException;
public <T extends Serializable>
void rpush (String listkey, T object) throws RedisException;
/**
* @Redis LPUSH
* @param listkey
* @param value
* @throws RedisException
*/
public void lpush (String listkey, byte[] value) throws RedisException;
public void lpush (String listkey, String stringValue) throws RedisException;
public void lpush (String listkey, Number numberValue) throws RedisException;
public <T extends Serializable>
void lpush (String listkey, T object) throws RedisException;
/**
* @Redis LSET
* @param key
* @param index
* @param value
* @throws RedisException
*/
public void lset (String key, long index, byte[] value) throws RedisException;
public void lset (String key, long index, String stringValue) throws RedisException;
public void lset (String key, long index, Number numberValue) throws RedisException;
public <T extends Serializable>
void lset (String key, long index, T object) throws RedisException;
/**
* @Redis LREM
* @param listKey
* @param value
* @param count
* @return
* @throws RedisException
*/
public long lrem (String listKey, byte[] value, int count) throws RedisException;
public long lrem (String listKey, String stringValue, int count) throws RedisException;
public long lrem (String listKey, Number numberValue, int count) throws RedisException;
public <T extends Serializable>
long lrem (String listKey, T object, int count) throws RedisException;
/**
* Given a 'list' key, returns the number of items in the list.
* @Redis LLEN
* @param listkey
* @return
* @throws RedisException
*/
public long llen (String listkey) throws RedisException;
/**
* @Redis LRANGE
* @param listkey
* @param from
* @param to
* @return
* @throws RedisException
*/
public List<byte[]> lrange (String listkey, long from, long to) throws RedisException;
/**
* @Redis LTRIM
* @param listkey
* @param keepFrom
* @param keepTo
* @throws RedisException
*/
public void ltrim (String listkey, long keepFrom, long keepTo) throws RedisException;
/**
* @Redis LINDEX
* @param listkey
* @param index
* @return
* @throws RedisException
*/
public byte[] lindex (String listkey, long index) throws RedisException;
/**
* @Redis LPOP
* @param listKey
* @return
* @throws RedisException
*/
public byte[] lpop (String listKey) throws RedisException;
/**
* @Redis RPOP
* @param listKey
* @return
* @throws RedisException
*/
public byte[] rpop (String listKey) throws RedisException;
// ------------------------------------------------------------------------
// Commands operating on sets
// ------------------------------------------------------------------------
/**
* @Redis SADD
* @param setkey
* @param member
* @return
* @throws RedisException
*/
public boolean sadd (String setkey, byte[] member) throws RedisException;
public boolean sadd (String setkey, String stringValue) throws RedisException;
public boolean sadd (String setkey, Number numberValue) throws RedisException;
public <T extends Serializable>
boolean sadd (String setkey, T object) throws RedisException;
/**
* @Redis SREM
* @param setKey
* @param member
* @return
* @throws RedisException
*/
public boolean srem (String setKey, byte[] member) throws RedisException;
public boolean srem (String setKey, String stringValue) throws RedisException;
public boolean srem (String setKey, Number numberValue) throws RedisException;
public <T extends Serializable>
boolean srem (String setKey, T object) throws RedisException;
/**
* @Redis SISMEMBER
* @param setKey
* @param member
* @return
* @throws RedisException
*/
public boolean sismember (String setKey, byte[] member) throws RedisException;
public boolean sismember (String setKey, String stringValue) throws RedisException;
public boolean sismember (String setKey, Number numberValue) throws RedisException;
public <T extends Serializable>
boolean sismember (String setKey, T object) throws RedisException;
/**
* @Redis SMOVE
* @param srcKey
* @param destKey
* @param member
* @return
* @throws RedisException
*/
public boolean smove (String srcKey, String destKey, byte[] member) throws RedisException;
public boolean smove (String srcKey, String destKey, String stringValue) throws RedisException;
public boolean smove (String srcKey, String destKey, Number numberValue) throws RedisException;
public <T extends Serializable>
boolean smove (String srcKey, String destKey, T object) throws RedisException;
/**
* @Redis SCARD
* @param setKey
* @return
* @throws RedisException
*/
public long scard (String setKey) throws RedisException;
/**
* @Redis SINTER
* @param set1
* @param sets
* @return
* @throws RedisException
*/
public List<byte[]> sinter (String set1, String...sets) throws RedisException;
/**
* @Redis SINTERSTORE
* @param destSetKey
* @param sets
* @throws RedisException
*/
public void sinterstore (String destSetKey, String...sets) throws RedisException;
/**
* @Redis SUNION
* @param set1
* @param sets
* @return
* @throws RedisException
*/
public List<byte[]> sunion (String set1, String...sets) throws RedisException;
/**
* @Redis SUNIONSTORE
* @param destSetKey
* @param sets
* @throws RedisException
*/
public void sunionstore (String destSetKey, String...sets) throws RedisException;
/**
* @Redis SDIFF
* @param set1
* @param sets
* @return
* @throws RedisException
*/
public List<byte[]> sdiff (String set1, String...sets) throws RedisException;
/**
* @Redis SDIFFSTORE
* @param destSetKey
* @param sets
* @throws RedisException
*/
public void sdiffstore (String destSetKey, String...sets) throws RedisException;
/**
* @Redis SMEMBERS
* @param setkey
* @return
* @throws RedisException
*/
public List<byte[]> smembers (String setkey) throws RedisException;
// ------------------------------------------------------------------------
// Multiple databases handling commands
// ------------------------------------------------------------------------
// @Deprecated
// public JRedis select (int index) throws RedisException;
/**
* Flushes the db you selected when connecting to Redis server. Typically,
* implementations will select db 0 on connecting if non was specified. Remember
* that there is no roll-back.
* @Redis FLUSHDB
* @return
* @throws RedisException
*/
public JRedis flushdb () throws RedisException;
/**
* Flushes all dbs in the connect Redis server, regardless of which db was selected
* on connect time. Remember that there is no rollback.
* @Redis FLUSHALL
* @return
* @throws RedisException
*/
public JRedis flushall () throws RedisException;
/**
* Moves the given key from the currently selected db to the one indicated
* by <code>dbIndex</code>.
* @Redis MOVE
* @param key
* @param dbIndex
* @return
* @throws RedisException
*/
public boolean move (String key, int dbIndex) throws RedisException;
// ------------------------------------------------------------------------
// Sorting
// ------------------------------------------------------------------------
/**
* Usage:
* <p>Usage:
* <p><code><pre>
* List<byte[]> results = redis.sort("my-list-or-set-key").BY("weight*").LIMIT(1, 11).GET("object*").DESC().ALPHA().exec();
* for(byte[] item : results) {
* // do something with item ..
* }
* </pre></code>
* <p>Sort specification elements are all options. You could simply say:
* <p><code><pre>
* List<byte[]> results = redis.sort("my-list-or-set-key").exec();
* for(byte[] item : results) {
* // do something with item ..
* }
* </pre></code>
* <p>Sort specification elements are also can appear in any order -- the client implementation will send them to the server
* in the order expected by the protocol, although it is good form to specify the predicates in natural order:
* <p><code><pre>
* List<byte[]> results = redis.sort("my-list-or-set-key").GET("object*").DESC().ALPHA().BY("weight*").LIMIT(1, 11).exec();
* for(byte[] item : results) {
* // do something with item ..
* }
* </pre></code>
*
* @Redis SORT
*/
public Sort sort(String key);
// ------------------------------------------------------------------------
// Persistence control commands
// ------------------------------------------------------------------------
/**
* @Redis SAVE
* @throws RedisException
*/
public void save() throws RedisException;
/**
* @Redis BGSAVE
* @throws RedisException
*/
public void bgsave () throws RedisException;
/**
* @Redis LASTSAVE
* @return
* @throws RedisException
*/
public long lastsave () throws RedisException;
// @Deprecated
// public void shutdown () throws RedisException;
// ------------------------------------------------------------------------
// Remote server control commands
// ------------------------------------------------------------------------
/**
* @Redis INFO
* @return
* @throws RedisException
*/
public Map<String, String> info () throws RedisException;
}
|
core/api/src/main/java/org/jredis/JRedis.java
|
/*
* Copyright 2009 Joubin Houshyar
*
* 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.jredis;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
/**
* Temp doc:
* <p>This is effectively a one to one mapping to Redis commands. And that
* is basically it.
* <p>Beyond that , just be aware that an implementation may throw {@link ClientRuntimeException}
* or an extension to report problems (typically connectivity) or features {@link NotSupportedException}
* or bugs. These are {@link RuntimeException}.
*
* [TODO: document me!]
*
* @author Joubin Houshyar ([email protected])
* @version alpha.0, 04/02/09
* @since alpha.0
*
*/
public interface JRedis {
// ------------------------------------------------------------------------
// Semantic context methods
// ------------------------------------------------------------------------
// TODO: reach a decision on whether to include this or not.
// /**
// * Provides for access to an interface providing standard Java collections
// * semantics on the specified parametric type.
// * <p>
// * The type <code>T</code> can be of 3 categories:
// * <ol>
// * <li>It is
// * </ol>
// * @param <T> a Java class type that you wish to perform {@link Set},
// * {@link List}, or {@link Map}, operations.
// * @return the {@link JavaSemantics} for type <code>T</code>, if the type specified meets
// * the required initialization characteristics.
// */
// public <T> JavaSemantics<T> semantic (Class<T> type) throws ClientRuntimeException;
// ------------------------------------------------------------------------
// Security and User Management
// ------------------------------------------------------------------------
// /**
// * Required for authorizing access to the server. This method implements
// * the AUTH command. It may be used with a non-secured server without
// * any side effect.
// *
// * @param authorization key as defined in the server.
// * @throws RedisException if the server is in secure more and the
// * authorization provided
// */
// @Deprecated
// public JRedis auth (String authorization) throws RedisException;
// ------------------------------------------------------------------------
// "Connection Handling"
// ------------------------------------------------------------------------
/**
* Ping redis
* @return true (unless not authorized)
* @throws RedisException (as of ver. 0.09) in case of unauthorized access
*/
public JRedis ping () throws RedisException;
public void quit ();
// ------------------------------------------------------------------------
// "Commands operating on string values"
// ------------------------------------------------------------------------
public void set (String key, byte[] value) throws RedisException;
public void set (String key, String stringValue) throws RedisException;
public void set (String key, Number numberValue) throws RedisException;
public <T extends Serializable>
void set (String key, T object) throws RedisException;
public boolean setnx (String key, byte[] value) throws RedisException;
public boolean setnx (String key, String stringValue) throws RedisException;
public boolean setnx (String key, Number numberValue) throws RedisException;
public <T extends Serializable>
boolean setnx (String key, T object) throws RedisException;
public byte[] get (String key) throws RedisException;
public byte[] getset (String key, byte[] value) throws RedisException;
public byte[] getset (String key, String stringValue) throws RedisException;
public byte[] getset (String key, Number numberValue) throws RedisException;
public <T extends Serializable>
byte[] getset (String key, T object) throws RedisException;
public List<byte[]> mget(String key, String...moreKeys) throws RedisException;
public long incr (String key) throws RedisException;
public long incrby (String key, int delta) throws RedisException;
public long decr (String key) throws RedisException;
public long decrby (String key, int delta) throws RedisException;
public boolean exists(String key) throws RedisException;
public boolean del (String key) throws RedisException;
public RedisType type (String key) throws RedisException;
// ------------------------------------------------------------------------
// "Commands operating on the key space"
// ------------------------------------------------------------------------
public List<String> keys () throws RedisException;
public List<String> keys (String pattern) throws RedisException;
public String randomkey() throws RedisException;
public void rename (String oldkey, String newkey) throws RedisException;
public boolean renamenx (String oldkey, String brandnewkey) throws RedisException;
public long dbsize () throws RedisException;
public boolean expire (String key, int ttlseconds) throws RedisException;
public long ttl (String key) throws RedisException;
// ------------------------------------------------------------------------
// Commands operating on lists
// ------------------------------------------------------------------------
public void rpush (String listkey, byte[] value) throws RedisException;
public void rpush (String listkey, String stringValue) throws RedisException;
public void rpush (String listkey, Number numberValue) throws RedisException;
public <T extends Serializable>
void rpush (String listkey, T object) throws RedisException;
public void lpush (String listkey, byte[] value) throws RedisException;
public void lpush (String listkey, String stringValue) throws RedisException;
public void lpush (String listkey, Number numberValue) throws RedisException;
public <T extends Serializable>
void lpush (String listkey, T object) throws RedisException;
public void lset (String key, long index, byte[] value) throws RedisException;
public void lset (String key, long index, String stringValue) throws RedisException;
public void lset (String key, long index, Number numberValue) throws RedisException;
public <T extends Serializable>
void lset (String key, long index, T object) throws RedisException;
public long lrem (String listKey, byte[] value, int count) throws RedisException;
public long lrem (String listKey, String stringValue, int count) throws RedisException;
public long lrem (String listKey, Number numberValue, int count) throws RedisException;
public <T extends Serializable>
long lrem (String listKey, T object, int count) throws RedisException;
public long llen (String listkey) throws RedisException;
public List<byte[]> lrange (String listkey, long from, long to) throws RedisException;
public void ltrim (String listkey, long keepFrom, long keepTo) throws RedisException;
public byte[] lindex (String listkey, long index) throws RedisException;
public byte[] lpop (String listKey) throws RedisException;
public byte[] rpop (String listKey) throws RedisException;
// ------------------------------------------------------------------------
// Commands operating on sets
// ------------------------------------------------------------------------
public boolean sadd (String setkey, byte[] member) throws RedisException;
public boolean sadd (String setkey, String stringValue) throws RedisException;
public boolean sadd (String setkey, Number numberValue) throws RedisException;
public <T extends Serializable>
boolean sadd (String setkey, T object) throws RedisException;
public boolean srem (String setKey, byte[] member) throws RedisException;
public boolean srem (String setKey, String stringValue) throws RedisException;
public boolean srem (String setKey, Number numberValue) throws RedisException;
public <T extends Serializable>
boolean srem (String setKey, T object) throws RedisException;
public boolean sismember (String setKey, byte[] member) throws RedisException;
public boolean sismember (String setKey, String stringValue) throws RedisException;
public boolean sismember (String setKey, Number numberValue) throws RedisException;
public <T extends Serializable>
boolean sismember (String setKey, T object) throws RedisException;
public boolean smove (String srcKey, String destKey, byte[] member) throws RedisException;
public boolean smove (String srcKey, String destKey, String stringValue) throws RedisException;
public boolean smove (String srcKey, String destKey, Number numberValue) throws RedisException;
public <T extends Serializable>
boolean smove (String srcKey, String destKey, T object) throws RedisException;
public long scard (String setKey) throws RedisException;
public List<byte[]> sinter (String set1, String...sets) throws RedisException;
public void sinterstore (String destSetKey, String...sets) throws RedisException;
public List<byte[]> sunion (String set1, String...sets) throws RedisException;
public void sunionstore (String destSetKey, String...sets) throws RedisException;
public List<byte[]> sdiff (String set1, String...sets) throws RedisException;
public void sdiffstore (String destSetKey, String...sets) throws RedisException;
public List<byte[]> smembers (String setkey) throws RedisException;
// ------------------------------------------------------------------------
// Multiple databases handling commands
// ------------------------------------------------------------------------
// @Deprecated
// public JRedis select (int index) throws RedisException;
public JRedis flushdb () throws RedisException;
public JRedis flushall () throws RedisException;
public boolean move (String key, int dbIndex) throws RedisException;
// ------------------------------------------------------------------------
// Sorting
// ------------------------------------------------------------------------
/**
* Usage:
* <p>Usage:
* <p><code><pre>
* List<byte[]> results = redis.sort("my-list-or-set-key").BY("weight*").LIMIT(1, 11).GET("object*").DESC().ALPHA().exec();
* for(byte[] item : results) {
* // do something with item ..
* }
* </pre></code>
* <p>Sort specification elements are all options. You could simply say:
* <p><code><pre>
* List<byte[]> results = redis.sort("my-list-or-set-key").exec();
* for(byte[] item : results) {
* // do something with item ..
* }
* </pre></code>
* <p>Sort specification elements are also can appear in any order -- the client implementation will send them to the server
* in the order expected by the protocol, although it is good form to specify the predicates in natural order:
* <p><code><pre>
* List<byte[]> results = redis.sort("my-list-or-set-key").GET("object*").DESC().ALPHA().BY("weight*").LIMIT(1, 11).exec();
* for(byte[] item : results) {
* // do something with item ..
* }
* </pre></code>
*/
public Sort sort(String key);
// ------------------------------------------------------------------------
// Persistence control commands
// ------------------------------------------------------------------------
public void save() throws RedisException;
public void bgsave () throws RedisException;
public long lastsave () throws RedisException;
// @Deprecated
// public void shutdown () throws RedisException;
// ------------------------------------------------------------------------
// Remote server control commands
// ------------------------------------------------------------------------
public Map<String, String> info () throws RedisException;
}
|
Updated the javadoc comments for JRedis interface methods.
|
core/api/src/main/java/org/jredis/JRedis.java
|
Updated the javadoc comments for JRedis interface methods.
|
<ide><path>ore/api/src/main/java/org/jredis/JRedis.java
<ide>
<ide>
<ide> /**
<del> * Temp doc:
<ide> * <p>This is effectively a one to one mapping to Redis commands. And that
<ide> * is basically it.
<ide> * <p>Beyond that , just be aware that an implementation may throw {@link ClientRuntimeException}
<ide> * or an extension to report problems (typically connectivity) or features {@link NotSupportedException}
<ide> * or bugs. These are {@link RuntimeException}.
<ide> *
<del> * [TODO: document me!]
<del> *
<del> * @author Joubin Houshyar ([email protected])
<add> * @author joubin ([email protected])
<ide> * @version alpha.0, 04/02/09
<ide> * @since alpha.0
<ide> *
<ide>
<ide> // ------------------------------------------------------------------------
<ide> // Security and User Management
<del> // ------------------------------------------------------------------------
<del>
<del>// /**
<del>// * Required for authorizing access to the server. This method implements
<del>// * the AUTH command. It may be used with a non-secured server without
<del>// * any side effect.
<del>// *
<del>// * @param authorization key as defined in the server.
<del>// * @throws RedisException if the server is in secure more and the
<del>// * authorization provided
<del>// */
<del>// @Deprecated
<del>// public JRedis auth (String authorization) throws RedisException;
<add> // NOTE: Moved to ConnectionSpec
<add> // ------------------------------------------------------------------------
<add>
<ide>
<ide> // ------------------------------------------------------------------------
<ide> // "Connection Handling"
<ide> */
<ide> public JRedis ping () throws RedisException;
<ide>
<add> /**
<add> * Disconnects the client.
<add> * @Redis QUIT
<add> */
<ide> public void quit ();
<ide>
<ide> // ------------------------------------------------------------------------
<ide> // "Commands operating on string values"
<ide> // ------------------------------------------------------------------------
<ide>
<add> /**
<add> * Bind the value to key.
<add> * @Redis SET
<add> * @param key any UTF-8 {@link String}
<add> * @param value any bytes. For current data size limitations, refer to
<add> * Redis documentation.
<add> * @throws RedisException on user error.
<add> * @throws ProviderException on un-documented features/bug
<add> * @throws ClientRuntimeException on errors due to operating environment (Redis or network)
<add> */
<ide> public void set (String key, byte[] value) throws RedisException;
<add> /**
<add> * Convenient method for {@link String} data binding
<add> * @Redis SET
<add> * @param key
<add> * @param stringValue
<add> * @throws RedisException
<add> * @see {@link JRedis#set(String, byte[])}
<add> */
<ide> public void set (String key, String stringValue) throws RedisException;
<add> /**
<add> * Convenient method for {@link String} numeric values binding
<add> * @Redis SET
<add> * @param key
<add> * @param numberValue
<add> * @throws RedisException
<add> * @see {@link JRedis#set(String, byte[])}
<add> */
<ide> public void set (String key, Number numberValue) throws RedisException;
<add> /**
<add> * Binds the given java {@link Object} to the key. Serialization format is
<add> * implementation specific. Simple implementations may apply the basic {@link Serializable}
<add> * protocol.
<add> * @Redis SET
<add> * @param <T>
<add> * @param key
<add> * @param object
<add> * @throws RedisException
<add> * @see {@link JRedis#set(String, byte[])}
<add> */
<ide> public <T extends Serializable>
<ide> void set (String key, T object) throws RedisException;
<ide>
<add> /**
<add> * @Redis SETNX
<add> * @param key
<add> * @param value
<add> * @return
<add> * @throws RedisException
<add> */
<ide> public boolean setnx (String key, byte[] value) throws RedisException;
<ide> public boolean setnx (String key, String stringValue) throws RedisException;
<ide> public boolean setnx (String key, Number numberValue) throws RedisException;
<ide> public <T extends Serializable>
<ide> boolean setnx (String key, T object) throws RedisException;
<ide>
<add> /**
<add> * @Redis GET
<add> * @param key
<add> * @return
<add> * @throws RedisException
<add> */
<ide> public byte[] get (String key) throws RedisException;
<ide>
<ide> public byte[] getset (String key, byte[] value) throws RedisException;
<ide> byte[] getset (String key, T object) throws RedisException;
<ide>
<ide>
<add> /**
<add> * @Redis MGET
<add> * @param key
<add> * @param moreKeys
<add> * @return
<add> * @throws RedisException
<add> */
<ide> public List<byte[]> mget(String key, String...moreKeys) throws RedisException;
<ide>
<add> /**
<add> * @Redis INCR
<add> * @param key
<add> * @return
<add> * @throws RedisException
<add> */
<ide> public long incr (String key) throws RedisException;
<ide>
<add> /**
<add> * @Redis INCRBY
<add> * @param key
<add> * @param delta
<add> * @return
<add> * @throws RedisException
<add> */
<ide> public long incrby (String key, int delta) throws RedisException;
<ide>
<add> /**
<add> * @Redis DECR
<add> * @param key
<add> * @return
<add> * @throws RedisException
<add> */
<ide> public long decr (String key) throws RedisException;
<ide>
<add> /**
<add> * @Redis DECRBY
<add> * @param key
<add> * @param delta
<add> * @return
<add> * @throws RedisException
<add> */
<ide> public long decrby (String key, int delta) throws RedisException;
<ide>
<add> /**
<add> * @Redis EXISTS
<add> * @param key
<add> * @return
<add> * @throws RedisException
<add> */
<ide> public boolean exists(String key) throws RedisException;
<ide>
<add> /**
<add> * @Redis DEL
<add> * @param key
<add> * @return
<add> * @throws RedisException
<add> */
<ide> public boolean del (String key) throws RedisException;
<ide>
<add> /**
<add> * @Redis TYPE
<add> * @param key
<add> * @return
<add> * @throws RedisException
<add> */
<ide> public RedisType type (String key) throws RedisException;
<ide>
<ide>
<ide> // "Commands operating on the key space"
<ide> // ------------------------------------------------------------------------
<ide>
<add> /**
<add> * @Redis KEYS
<add> * @param pattern
<add> * @return
<add> * @throws RedisException
<add> */
<add> public List<String> keys (String pattern) throws RedisException;
<add>
<add> /**
<add> * Convenience method. Equivalent to calling <code>jredis.keys("*");</code>
<add> * @Redis KEYS
<add> * @return
<add> * @throws RedisException
<add> * @see {@link JRedis#keys(String)}
<add> */
<ide> public List<String> keys () throws RedisException;
<ide>
<del> public List<String> keys (String pattern) throws RedisException;
<del>
<add> /**
<add> * @Redis RANDOMKEY
<add> * @return
<add> * @throws RedisException
<add> */
<ide> public String randomkey() throws RedisException;
<ide>
<add> /**
<add> * @Redis RENAME
<add> * @param oldkey
<add> * @param newkey
<add> * @throws RedisException
<add> */
<ide> public void rename (String oldkey, String newkey) throws RedisException;
<ide>
<add> /**
<add> * @Redis RENAMENX
<add> * @param oldkey
<add> * @param brandnewkey
<add> * @return
<add> * @throws RedisException
<add> */
<ide> public boolean renamenx (String oldkey, String brandnewkey) throws RedisException;
<ide>
<add> /**
<add> * @Redis DBSIZE
<add> * @return
<add> * @throws RedisException
<add> */
<ide> public long dbsize () throws RedisException;
<ide>
<add> /**
<add> * @Redis EXPIRE
<add> * @param key
<add> * @param ttlseconds
<add> * @return
<add> * @throws RedisException
<add> */
<ide> public boolean expire (String key, int ttlseconds) throws RedisException;
<ide>
<add> /**
<add> * @Redis TTL
<add> * @param key
<add> * @return
<add> * @throws RedisException
<add> */
<ide> public long ttl (String key) throws RedisException;
<ide>
<ide> // ------------------------------------------------------------------------
<ide> // Commands operating on lists
<ide> // ------------------------------------------------------------------------
<ide>
<add> /**
<add> * @Redis RPUSH
<add> * @param listkey
<add> * @param value
<add> * @throws RedisException
<add> */
<ide> public void rpush (String listkey, byte[] value) throws RedisException;
<ide> public void rpush (String listkey, String stringValue) throws RedisException;
<ide> public void rpush (String listkey, Number numberValue) throws RedisException;
<ide> public <T extends Serializable>
<ide> void rpush (String listkey, T object) throws RedisException;
<ide>
<add> /**
<add> * @Redis LPUSH
<add> * @param listkey
<add> * @param value
<add> * @throws RedisException
<add> */
<ide> public void lpush (String listkey, byte[] value) throws RedisException;
<ide> public void lpush (String listkey, String stringValue) throws RedisException;
<ide> public void lpush (String listkey, Number numberValue) throws RedisException;
<ide> public <T extends Serializable>
<ide> void lpush (String listkey, T object) throws RedisException;
<ide>
<add> /**
<add> * @Redis LSET
<add> * @param key
<add> * @param index
<add> * @param value
<add> * @throws RedisException
<add> */
<ide> public void lset (String key, long index, byte[] value) throws RedisException;
<ide> public void lset (String key, long index, String stringValue) throws RedisException;
<ide> public void lset (String key, long index, Number numberValue) throws RedisException;
<ide> void lset (String key, long index, T object) throws RedisException;
<ide>
<ide>
<add> /**
<add> * @Redis LREM
<add> * @param listKey
<add> * @param value
<add> * @param count
<add> * @return
<add> * @throws RedisException
<add> */
<ide> public long lrem (String listKey, byte[] value, int count) throws RedisException;
<ide> public long lrem (String listKey, String stringValue, int count) throws RedisException;
<ide> public long lrem (String listKey, Number numberValue, int count) throws RedisException;
<ide> public <T extends Serializable>
<ide> long lrem (String listKey, T object, int count) throws RedisException;
<ide>
<add> /**
<add> * Given a 'list' key, returns the number of items in the list.
<add> * @Redis LLEN
<add> * @param listkey
<add> * @return
<add> * @throws RedisException
<add> */
<ide> public long llen (String listkey) throws RedisException;
<ide>
<add> /**
<add> * @Redis LRANGE
<add> * @param listkey
<add> * @param from
<add> * @param to
<add> * @return
<add> * @throws RedisException
<add> */
<ide> public List<byte[]> lrange (String listkey, long from, long to) throws RedisException;
<ide>
<add> /**
<add> * @Redis LTRIM
<add> * @param listkey
<add> * @param keepFrom
<add> * @param keepTo
<add> * @throws RedisException
<add> */
<ide> public void ltrim (String listkey, long keepFrom, long keepTo) throws RedisException;
<ide>
<add> /**
<add> * @Redis LINDEX
<add> * @param listkey
<add> * @param index
<add> * @return
<add> * @throws RedisException
<add> */
<ide> public byte[] lindex (String listkey, long index) throws RedisException;
<ide>
<add> /**
<add> * @Redis LPOP
<add> * @param listKey
<add> * @return
<add> * @throws RedisException
<add> */
<ide> public byte[] lpop (String listKey) throws RedisException;
<ide>
<add> /**
<add> * @Redis RPOP
<add> * @param listKey
<add> * @return
<add> * @throws RedisException
<add> */
<ide> public byte[] rpop (String listKey) throws RedisException;
<ide>
<ide> // ------------------------------------------------------------------------
<ide> // Commands operating on sets
<ide> // ------------------------------------------------------------------------
<ide>
<add> /**
<add> * @Redis SADD
<add> * @param setkey
<add> * @param member
<add> * @return
<add> * @throws RedisException
<add> */
<ide> public boolean sadd (String setkey, byte[] member) throws RedisException;
<ide> public boolean sadd (String setkey, String stringValue) throws RedisException;
<ide> public boolean sadd (String setkey, Number numberValue) throws RedisException;
<ide> public <T extends Serializable>
<ide> boolean sadd (String setkey, T object) throws RedisException;
<ide>
<add> /**
<add> * @Redis SREM
<add> * @param setKey
<add> * @param member
<add> * @return
<add> * @throws RedisException
<add> */
<ide> public boolean srem (String setKey, byte[] member) throws RedisException;
<ide> public boolean srem (String setKey, String stringValue) throws RedisException;
<ide> public boolean srem (String setKey, Number numberValue) throws RedisException;
<ide> public <T extends Serializable>
<ide> boolean srem (String setKey, T object) throws RedisException;
<ide>
<add> /**
<add> * @Redis SISMEMBER
<add> * @param setKey
<add> * @param member
<add> * @return
<add> * @throws RedisException
<add> */
<ide> public boolean sismember (String setKey, byte[] member) throws RedisException;
<ide> public boolean sismember (String setKey, String stringValue) throws RedisException;
<ide> public boolean sismember (String setKey, Number numberValue) throws RedisException;
<ide> public <T extends Serializable>
<ide> boolean sismember (String setKey, T object) throws RedisException;
<ide>
<add> /**
<add> * @Redis SMOVE
<add> * @param srcKey
<add> * @param destKey
<add> * @param member
<add> * @return
<add> * @throws RedisException
<add> */
<ide> public boolean smove (String srcKey, String destKey, byte[] member) throws RedisException;
<ide> public boolean smove (String srcKey, String destKey, String stringValue) throws RedisException;
<ide> public boolean smove (String srcKey, String destKey, Number numberValue) throws RedisException;
<ide> public <T extends Serializable>
<ide> boolean smove (String srcKey, String destKey, T object) throws RedisException;
<ide>
<add> /**
<add> * @Redis SCARD
<add> * @param setKey
<add> * @return
<add> * @throws RedisException
<add> */
<ide> public long scard (String setKey) throws RedisException;
<ide>
<add> /**
<add> * @Redis SINTER
<add> * @param set1
<add> * @param sets
<add> * @return
<add> * @throws RedisException
<add> */
<ide> public List<byte[]> sinter (String set1, String...sets) throws RedisException;
<add> /**
<add> * @Redis SINTERSTORE
<add> * @param destSetKey
<add> * @param sets
<add> * @throws RedisException
<add> */
<ide> public void sinterstore (String destSetKey, String...sets) throws RedisException;
<ide>
<add> /**
<add> * @Redis SUNION
<add> * @param set1
<add> * @param sets
<add> * @return
<add> * @throws RedisException
<add> */
<ide> public List<byte[]> sunion (String set1, String...sets) throws RedisException;
<add>
<add> /**
<add> * @Redis SUNIONSTORE
<add> * @param destSetKey
<add> * @param sets
<add> * @throws RedisException
<add> */
<ide> public void sunionstore (String destSetKey, String...sets) throws RedisException;
<ide>
<add> /**
<add> * @Redis SDIFF
<add> * @param set1
<add> * @param sets
<add> * @return
<add> * @throws RedisException
<add> */
<ide> public List<byte[]> sdiff (String set1, String...sets) throws RedisException;
<add>
<add> /**
<add> * @Redis SDIFFSTORE
<add> * @param destSetKey
<add> * @param sets
<add> * @throws RedisException
<add> */
<ide> public void sdiffstore (String destSetKey, String...sets) throws RedisException;
<ide>
<add> /**
<add> * @Redis SMEMBERS
<add> * @param setkey
<add> * @return
<add> * @throws RedisException
<add> */
<ide> public List<byte[]> smembers (String setkey) throws RedisException;
<ide>
<ide> // ------------------------------------------------------------------------
<ide> // @Deprecated
<ide> // public JRedis select (int index) throws RedisException;
<ide>
<add> /**
<add> * Flushes the db you selected when connecting to Redis server. Typically,
<add> * implementations will select db 0 on connecting if non was specified. Remember
<add> * that there is no roll-back.
<add> * @Redis FLUSHDB
<add> * @return
<add> * @throws RedisException
<add> */
<ide> public JRedis flushdb () throws RedisException;
<ide>
<add> /**
<add> * Flushes all dbs in the connect Redis server, regardless of which db was selected
<add> * on connect time. Remember that there is no rollback.
<add> * @Redis FLUSHALL
<add> * @return
<add> * @throws RedisException
<add> */
<ide> public JRedis flushall () throws RedisException;
<ide>
<add> /**
<add> * Moves the given key from the currently selected db to the one indicated
<add> * by <code>dbIndex</code>.
<add> * @Redis MOVE
<add> * @param key
<add> * @param dbIndex
<add> * @return
<add> * @throws RedisException
<add> */
<ide> public boolean move (String key, int dbIndex) throws RedisException;
<ide>
<ide> // ------------------------------------------------------------------------
<ide> * // do something with item ..
<ide> * }
<ide> * </pre></code>
<add> *
<add> * @Redis SORT
<ide> */
<ide> public Sort sort(String key);
<ide>
<ide> // Persistence control commands
<ide> // ------------------------------------------------------------------------
<ide>
<add> /**
<add> * @Redis SAVE
<add> * @throws RedisException
<add> */
<ide> public void save() throws RedisException;
<ide>
<add> /**
<add> * @Redis BGSAVE
<add> * @throws RedisException
<add> */
<ide> public void bgsave () throws RedisException;
<ide>
<add> /**
<add> * @Redis LASTSAVE
<add> * @return
<add> * @throws RedisException
<add> */
<ide> public long lastsave () throws RedisException;
<ide>
<ide> // @Deprecated
<ide> // Remote server control commands
<ide> // ------------------------------------------------------------------------
<ide>
<add> /**
<add> * @Redis INFO
<add> * @return
<add> * @throws RedisException
<add> */
<ide> public Map<String, String> info () throws RedisException;
<ide> }
|
|
Java
|
apache-2.0
|
7523f62165528859df9ff12e7c8c04f5437edf11
| 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 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.container.xml;
import com.google.common.collect.ImmutableSet;
import com.yahoo.collections.CollectionUtil;
import com.yahoo.config.model.builder.xml.test.DomBuilderTest;
import com.yahoo.container.jdisc.state.StateHandler;
import com.yahoo.vespa.model.container.ContainerCluster;
import com.yahoo.vespa.model.container.http.AccessControl;
import com.yahoo.vespa.model.container.http.Http;
import com.yahoo.vespa.model.container.http.Http.Binding;
import com.yahoo.vespa.model.container.http.xml.HttpBuilder;
import org.junit.Test;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* @author gjoranv
*/
public class AccessControlTest extends ContainerModelBuilderTestBase {
private static final Set<String> REQUIRED_BINDINGS = ImmutableSet.of(
"/custom-handler/",
"/search/",
"/feed/",
"/remove/",
"/removelocation/",
"/get/",
"/visit/",
"/document/",
"/feedstatus/",
ContainerCluster.RESERVED_URI_PREFIX);
private static final Set<String> FORBIDDEN_BINDINGS = ImmutableSet.of(
"/ApplicationStatus",
"/status.html",
"/statistics/",
StateHandler.STATE_API_ROOT,
ContainerCluster.ROOT_HANDLER_BINDING);
@Test
public void access_control_filter_chain_is_set_up() throws Exception {
Element clusterElem = DomBuilderTest.parse(
" <http>",
" <filtering>",
" <access-control domain='foo' />",
" </filtering>",
" </http>");
Http http = new HttpBuilder().build(root, clusterElem);
root.freezeModelTopology();
assertTrue(http.getFilterChains().hasChain(AccessControl.ACCESS_CONTROL_CHAIN_ID));
}
@Test
public void access_control_filter_chain_has_correct_handler_bindings() throws Exception {
Element clusterElem = DomBuilderTest.parse(
"<jdisc version='1.0'>",
" <search/>",
" <document-api/>",
" <handler id='custom.Handler'>",
" <binding>http://*/custom-handler/*</binding>",
" </handler>",
" <http>",
" <filtering>",
" <access-control domain='foo' />",
" </filtering>",
" </http>",
"</jdisc>");
Http http = getHttp(clusterElem);
Set<String> foundRequiredBindings = REQUIRED_BINDINGS.stream()
.filter(requiredBinding -> containsBinding(http.getBindings(), requiredBinding))
.collect(Collectors.toSet());
Set<String> missingRequiredBindings = new HashSet<>(REQUIRED_BINDINGS);
missingRequiredBindings.removeAll(foundRequiredBindings);
assertTrue("Access control chain was not bound to: " + CollectionUtil.mkString(missingRequiredBindings, ", "),
missingRequiredBindings.isEmpty());
FORBIDDEN_BINDINGS.forEach(forbiddenBinding -> http.getBindings().forEach(
binding -> assertFalse("Access control chain was bound to: " + binding.binding,
binding.binding.contains(forbiddenBinding))));
}
@Test
public void handler_can_be_excluded_by_excluding_one_of_its_bindings() throws Exception {
final String notExcludedBinding = "http://*/custom-handler/*";
final String excludedBinding = "http://*/excluded/*";
Element clusterElem = DomBuilderTest.parse(
"<jdisc version='1.0'>",
" <handler id='custom.Handler'>",
" <binding>" + notExcludedBinding + "</binding>",
" <binding>" + excludedBinding + "</binding>",
" </handler>",
" <http>",
" <filtering>",
" <access-control domain='foo'>",
" <exclude>",
" <binding>" + excludedBinding + "</binding>",
" </exclude>",
" </access-control>",
" </filtering>",
" </http>",
"</jdisc>");
Http http = getHttp(clusterElem);
assertFalse("Excluded binding was not removed.",
containsBinding(http.getBindings(), excludedBinding));
assertFalse("Not all bindings of an excluded handler was removed.",
containsBinding(http.getBindings(), notExcludedBinding));
}
private Http getHttp(Element clusterElem) throws SAXException, IOException {
createModel(root, clusterElem);
ContainerCluster cluster = (ContainerCluster) root.getChildren().get("jdisc");
Http http = cluster.getHttp();
assertNotNull(http);
return http;
}
private boolean containsBinding(Collection<Binding> bindings, String binding) {
for (Binding b : bindings) {
if (b.binding.contains(binding))
return true;
}
return false;
}
}
|
config-model/src/test/java/com/yahoo/vespa/model/container/xml/AccessControlTest.java
|
// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.container.xml;
import com.google.common.collect.ImmutableSet;
import com.yahoo.collections.CollectionUtil;
import com.yahoo.config.model.builder.xml.test.DomBuilderTest;
import com.yahoo.container.jdisc.state.StateHandler;
import com.yahoo.vespa.model.container.ContainerCluster;
import com.yahoo.vespa.model.container.http.AccessControl;
import com.yahoo.vespa.model.container.http.Http;
import com.yahoo.vespa.model.container.http.Http.Binding;
import org.junit.Test;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* @author gjoranv
*/
public class AccessControlTest extends ContainerModelBuilderTestBase {
private static final Set<String> REQUIRED_BINDINGS = ImmutableSet.of(
"/custom-handler/",
"/search/",
"/feed/",
"/remove/",
"/removelocation/",
"/get/",
"/visit/",
"/document/",
"/feedstatus/",
ContainerCluster.RESERVED_URI_PREFIX);
private static final Set<String> FORBIDDEN_BINDINGS = ImmutableSet.of(
"/ApplicationStatus",
"/status.html",
"/statistics/",
StateHandler.STATE_API_ROOT,
ContainerCluster.ROOT_HANDLER_BINDING);
@Test
public void access_control_filter_chain_is_set_up() throws Exception {
Element clusterElem = DomBuilderTest.parse(
"<jdisc version='1.0'>",
" <http>",
" <filtering>",
" <access-control domain='foo' />",
" </filtering>",
" </http>",
"</jdisc>");
Http http = getHttp(clusterElem);
assertTrue(http.getFilterChains().hasChain(AccessControl.ACCESS_CONTROL_CHAIN_ID));
}
@Test
public void access_control_filter_chain_has_correct_handler_bindings() throws Exception {
Element clusterElem = DomBuilderTest.parse(
"<jdisc version='1.0'>",
" <search/>",
" <document-api/>",
" <handler id='custom.Handler'>",
" <binding>http://*/custom-handler/*</binding>",
" </handler>",
" <http>",
" <filtering>",
" <access-control domain='foo' />",
" </filtering>",
" </http>",
"</jdisc>");
Http http = getHttp(clusterElem);
Set<String> foundRequiredBindings = REQUIRED_BINDINGS.stream()
.filter(requiredBinding -> containsBinding(http.getBindings(), requiredBinding))
.collect(Collectors.toSet());
Set<String> missingRequiredBindings = new HashSet<>(REQUIRED_BINDINGS);
missingRequiredBindings.removeAll(foundRequiredBindings);
assertTrue("Access control chain was not bound to: " + CollectionUtil.mkString(missingRequiredBindings, ", "),
missingRequiredBindings.isEmpty());
FORBIDDEN_BINDINGS.forEach(forbiddenBinding -> http.getBindings().forEach(
binding -> assertFalse("Access control chain was bound to: " + binding.binding,
binding.binding.contains(forbiddenBinding))));
}
@Test
public void handler_can_be_excluded_by_excluding_one_of_its_bindings() throws Exception {
final String notExcludedBinding = "http://*/custom-handler/*";
final String excludedBinding = "http://*/excluded/*";
Element clusterElem = DomBuilderTest.parse(
"<jdisc version='1.0'>",
" <handler id='custom.Handler'>",
" <binding>" + notExcludedBinding + "</binding>",
" <binding>" + excludedBinding + "</binding>",
" </handler>",
" <http>",
" <filtering>",
" <access-control domain='foo'>",
" <exclude>",
" <binding>" + excludedBinding + "</binding>",
" </exclude>",
" </access-control>",
" </filtering>",
" </http>",
"</jdisc>");
Http http = getHttp(clusterElem);
assertFalse("Excluded binding was not removed.",
containsBinding(http.getBindings(), excludedBinding));
assertFalse("Not all bindings of an excluded handler was removed.",
containsBinding(http.getBindings(), notExcludedBinding));
}
private Http getHttp(Element clusterElem) throws SAXException, IOException {
createModel(root, clusterElem);
ContainerCluster cluster = (ContainerCluster) root.getChildren().get("jdisc");
Http http = cluster.getHttp();
assertNotNull(http);
return http;
}
private boolean containsBinding(Collection<Binding> bindings, String binding) {
for (Binding b : bindings) {
if (b.binding.contains(binding))
return true;
}
return false;
}
}
|
Skip 'jdisc' element where unnecessary.
|
config-model/src/test/java/com/yahoo/vespa/model/container/xml/AccessControlTest.java
|
Skip 'jdisc' element where unnecessary.
|
<ide><path>onfig-model/src/test/java/com/yahoo/vespa/model/container/xml/AccessControlTest.java
<ide> import com.yahoo.vespa.model.container.http.AccessControl;
<ide> import com.yahoo.vespa.model.container.http.Http;
<ide> import com.yahoo.vespa.model.container.http.Http.Binding;
<add>import com.yahoo.vespa.model.container.http.xml.HttpBuilder;
<ide> import org.junit.Test;
<ide> import org.w3c.dom.Element;
<ide> import org.xml.sax.SAXException;
<ide> @Test
<ide> public void access_control_filter_chain_is_set_up() throws Exception {
<ide> Element clusterElem = DomBuilderTest.parse(
<del> "<jdisc version='1.0'>",
<ide> " <http>",
<ide> " <filtering>",
<ide> " <access-control domain='foo' />",
<ide> " </filtering>",
<del> " </http>",
<del> "</jdisc>");
<add> " </http>");
<ide>
<del> Http http = getHttp(clusterElem);
<add> Http http = new HttpBuilder().build(root, clusterElem);
<add> root.freezeModelTopology();
<add>
<ide> assertTrue(http.getFilterChains().hasChain(AccessControl.ACCESS_CONTROL_CHAIN_ID));
<ide> }
<ide>
|
|
Java
|
mit
|
325bb46aece2f1fa8f109a0f7bfd8a58c0e2058d
| 0 |
Hana-Lee/pc-bang
|
package kr.co.leehana.view;
import javax.swing.*;
import java.awt.*;
/**
* @author Hana Lee
* @since 2015-11-13 20-06
*/
public class ManageView extends JFrame {
private static final long serialVersionUID = -7777187062556506831L;
private static final int width = 1600;
private static final int height = 900;
public ManageView() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(width, height);
setTitle("관리 화면");
setLayout(null);
setCenterLocation();
JLayeredPane layeredPane = new JLayeredPane();
layeredPane.setBounds(0, 0, width, height);
layeredPane.setLayout(null);
JPanel mainPanel = new MainPanel();
mainPanel.setLayout(null);
mainPanel.setBounds(0, -30, width, height);
ClockPanel clockPanel = new ClockPanel();
clockPanel.setLayout(null);
clockPanel.setBounds(15, 20, 179, 149);
clockPanel.setOpaque(false);
new Thread(clockPanel).start();
layeredPane.add(mainPanel, new Integer(0));
layeredPane.add(clockPanel, new Integer(1));
add(layeredPane);
setVisible(true);
}
private void setCenterLocation() {
Dimension frameSize = this.getSize();
Dimension windowSize = Toolkit.getDefaultToolkit().getScreenSize();
setLocation((windowSize.width - frameSize.width) / 2, (windowSize.height - frameSize.height) / 2);
}
class MainPanel extends JPanel {
private Image image;
public MainPanel() {
image = Toolkit.getDefaultToolkit().createImage(ManageView.class.getResource("/img/mainHud_back.png"));
}
@Override
public void paint(Graphics g) {
g.drawImage(image, 0, 0, this);
}
@Override
public void update(Graphics g) {
super.update(g);
}
}
class ClockPanel extends JPanel implements Runnable {
private Image[] images = new Image[4];
private int i = 1;
public ClockPanel() {
images[1] = Toolkit.getDefaultToolkit().createImage(ManageView.class.getResource("/img/cl1.png"));
images[2] = Toolkit.getDefaultToolkit().createImage(ManageView.class.getResource("/img/cl2.png"));
images[3] = Toolkit.getDefaultToolkit().createImage(ManageView.class.getResource("/img/cl3.png"));
images[0] = images[1];
}
@Override
public void paint(Graphics g) {
g.drawImage(images[0], 0, 0, this);
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(10000);
switch (i) {
case 1:
images[0] = images[i];
i++;
repaint();
break;
case 2:
images[0] = images[i];
i++;
repaint();
break;
case 3:
images[0] = images[i];
i = 1;
repaint();
break;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
new ManageView();
}
}
|
src/main/java/kr/co/leehana/view/ManageView.java
|
package kr.co.leehana.view;
import javax.swing.*;
import java.awt.*;
/**
* @author Hana Lee
* @since 2015-11-13 20-06
*/
public class ManageView extends JFrame {
private static final long serialVersionUID = -7777187062556506831L;
private static final int width = 1600;
private static final int height = 900;
public ManageView() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(width, height);
setTitle("관리 화면");
setCenterLocation();
JPanel mainPanel = new MainPanel();
add(mainPanel, BorderLayout.CENTER);
setVisible(true);
}
private void setCenterLocation() {
Dimension frameSize = this.getSize();
Dimension windowSize = Toolkit.getDefaultToolkit().getScreenSize();
setLocation((windowSize.width - frameSize.width) / 2, (windowSize.height - frameSize.height) / 2);
}
class MainPanel extends JPanel {
private Image image;
public MainPanel() {
image = Toolkit.getDefaultToolkit().createImage(ManageView.class.getResource("/img/mainHud_back.png"));
}
@Override
public void paint(Graphics g) {
g.drawImage(image, 0, 0, this);
}
@Override
public void update(Graphics g) {
super.update(g);
}
}
public static void main(String[] args) {
new ManageView();
}
}
|
관리 화면의 좌측 상단에 시계를 보여주기 위한 패널 추가.
|
src/main/java/kr/co/leehana/view/ManageView.java
|
관리 화면의 좌측 상단에 시계를 보여주기 위한 패널 추가.
|
<ide><path>rc/main/java/kr/co/leehana/view/ManageView.java
<ide> setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
<ide> setSize(width, height);
<ide> setTitle("관리 화면");
<add> setLayout(null);
<ide>
<ide> setCenterLocation();
<ide>
<add> JLayeredPane layeredPane = new JLayeredPane();
<add> layeredPane.setBounds(0, 0, width, height);
<add> layeredPane.setLayout(null);
<add>
<ide> JPanel mainPanel = new MainPanel();
<del> add(mainPanel, BorderLayout.CENTER);
<add> mainPanel.setLayout(null);
<add> mainPanel.setBounds(0, -30, width, height);
<add>
<add> ClockPanel clockPanel = new ClockPanel();
<add> clockPanel.setLayout(null);
<add> clockPanel.setBounds(15, 20, 179, 149);
<add> clockPanel.setOpaque(false);
<add> new Thread(clockPanel).start();
<add>
<add> layeredPane.add(mainPanel, new Integer(0));
<add> layeredPane.add(clockPanel, new Integer(1));
<add>
<add> add(layeredPane);
<ide>
<ide> setVisible(true);
<ide> }
<ide> }
<ide> }
<ide>
<add> class ClockPanel extends JPanel implements Runnable {
<add>
<add> private Image[] images = new Image[4];
<add> private int i = 1;
<add>
<add> public ClockPanel() {
<add> images[1] = Toolkit.getDefaultToolkit().createImage(ManageView.class.getResource("/img/cl1.png"));
<add> images[2] = Toolkit.getDefaultToolkit().createImage(ManageView.class.getResource("/img/cl2.png"));
<add> images[3] = Toolkit.getDefaultToolkit().createImage(ManageView.class.getResource("/img/cl3.png"));
<add>
<add> images[0] = images[1];
<add> }
<add>
<add> @Override
<add> public void paint(Graphics g) {
<add> g.drawImage(images[0], 0, 0, this);
<add> }
<add>
<add> @Override
<add> public void run() {
<add> while (true) {
<add> try {
<add> Thread.sleep(10000);
<add>
<add> switch (i) {
<add> case 1:
<add> images[0] = images[i];
<add> i++;
<add> repaint();
<add> break;
<add> case 2:
<add> images[0] = images[i];
<add> i++;
<add> repaint();
<add> break;
<add> case 3:
<add> images[0] = images[i];
<add> i = 1;
<add> repaint();
<add> break;
<add> }
<add> } catch (InterruptedException e) {
<add> e.printStackTrace();
<add> }
<add> }
<add> }
<add> }
<add>
<ide> public static void main(String[] args) {
<ide> new ManageView();
<ide> }
|
|
JavaScript
|
mit
|
5dc9b5f256ce155c55b937c8e9c94564dfcd79ca
| 0 |
StreetSupport/streetsupport-web,StreetSupport/streetsupport-web,StreetSupport/streetsupport-web
|
/*
global google
*/
// Common modules
import './common'
let sortBy = require('lodash/collection/sortBy')
let htmlEncode = require('htmlencode')
let apiRoutes = require('./api')
let getApiData = require('./get-api-data')
let templating = require('./template-render')
let browser = require('./browser')
let querystring = require('./get-url-parameter')
let locationSelector = require('./location/locationSelector')
let onChangeLocation = (newLocation) => {
window.location.href = '/find-help/all-service-providers/?location=' + newLocation
}
const buildInfoWindowMarkup = (p) => {
return `<div class="map-info-window">
<h1 class="h2"><a href="/find-help/organisation/?organisation=${p.key}">${htmlEncode.htmlDecode(p.name)}</a></h1>
<p>${htmlEncode.htmlDecode(p.shortDescription)}</p>
<a href="/find-help/organisation/?organisation=${p.key}" class="btn btn--brand-e">
<span class="btn__text">More about ${htmlEncode.htmlDecode(p.name)}</span>
</a>
</div>`
}
const buildMap = (userLocation) => {
const centre = {lat: userLocation.latitude, lng: userLocation.longitude}
return new google.maps.Map(document.querySelector('.js-map'), {
zoom: 11,
center: centre
})
}
window.initMap = () => {}
const displayMap = function (providers, userLocation) {
const map = buildMap(userLocation)
const infoWindows = []
providers
.forEach((p) => {
if (p.addresses.length === 0) return
const infoWindow = new google.maps.InfoWindow({
content: buildInfoWindowMarkup(p)
})
infoWindows.push(infoWindow)
const marker = new google.maps.Marker({
position: { lat: p.addresses[0].latitude, lng: p.addresses[0].longitude },
map: map,
title: `${htmlEncode.htmlDecode(p.name)}`
})
marker.addListener('click', () => {
infoWindows
.forEach((w) => w.close())
infoWindow.open(map, marker)
})
})
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
}
new google.maps.Marker({ // eslint-disable-line
position: pos,
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 3,
fillColor: 'blue',
strokeColor: 'blue'
},
map: map
})
}, function () {
})
} else {
// Browser doesn't support Geolocation
}
}
let getData = (currentLocation) => {
if (window.location.search.length === 0) {
var saved = document.cookie.replace(/(?:(?:^|.*;\s*)desired-location\s*=\s*([^;]*).*$)|^.*$/, '$1')
if (saved !== undefined && saved.length > 0 && saved !== 'my-location') {
onChangeLocation(saved)
}
}
getApiData.data(apiRoutes.serviceProviders + querystring.parameter('location'))
.then((result) => {
const callback = () => {
locationSelector.handler(onChangeLocation)
browser.loaded()
displayMap(result.data, currentLocation)
}
if (result.data.length === 0) {
let theData = {
location: currentLocation.name
}
templating.renderTemplate('js-category-no-result-tpl', theData, 'js-category-result-output', callback)
} else {
let sorted = sortBy(result.data, function (provider) {
return provider.name.toLowerCase()
})
let theData = {
organisations: sorted,
location: currentLocation.name
}
templating.renderTemplate('js-category-result-tpl', theData, 'js-category-result-output', callback)
}
})
}
let init = () => {
browser.loading()
locationSelector
.getCurrent()
.then((result) => {
getData(result)
})
}
init()
|
src/js/page-all-service-providers.js
|
/*
global google
*/
// Common modules
import './common'
let sortBy = require('lodash/collection/sortBy')
let htmlEncode = require('htmlencode')
let apiRoutes = require('./api')
let getApiData = require('./get-api-data')
let templating = require('./template-render')
let browser = require('./browser')
let querystring = require('./get-url-parameter')
let locationSelector = require('./location/locationSelector')
let onChangeLocation = (newLocation) => {
window.location.href = '/find-help/all-service-providers/?location=' + newLocation
}
const buildInfoWindowMarkup = (p) => {
return `<div class="map-info-window">
<h1 class="h2"><a href="/find-help/organisation/?organisation=${p.key}">${htmlEncode.htmlDecode(p.name)}</a></h1>
<p>${htmlEncode.htmlDecode(p.shortDescription)}</p>
<a href="/find-help/organisation/?organisation=${p.key}" class="btn btn--brand-e">
<span class="btn__text">More about ${htmlEncode.htmlDecode(p.name)}</span>
</a>
</div>`
}
const buildMap = (userLocation) => {
const centre = {lat: userLocation.latitude, lng: userLocation.longitude}
return new google.maps.Map(document.querySelector('.js-map'), {
zoom: 11,
center: centre
})
}
window.initMap = () => {}
const displayMap = function (providers, userLocation) {
const map = buildMap(userLocation)
const infoWindows = []
providers
.forEach((p) => {
console.log(p)
if (p.addresses.length === 0) return
const infoWindow = new google.maps.InfoWindow({
content: buildInfoWindowMarkup(p)
})
infoWindows.push(infoWindow)
console.log(infoWindow)
const marker = new google.maps.Marker({
position: { lat: p.addresses[0].latitude, lng: p.addresses[0].longitude },
map: map,
title: `${htmlEncode.htmlDecode(p.name)}`
})
marker.addListener('click', () => {
infoWindows
.forEach((w) => w.close())
infoWindow.open(map, marker)
})
})
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
}
new google.maps.Marker({ // eslint-disable-line
position: pos,
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 3,
fillColor: 'blue',
strokeColor: 'blue'
},
map: map
})
}, function () {
})
} else {
// Browser doesn't support Geolocation
}
}
let getData = (currentLocation) => {
if (window.location.search.length === 0) {
var saved = document.cookie.replace(/(?:(?:^|.*;\s*)desired-location\s*=\s*([^;]*).*$)|^.*$/, '$1')
if (saved !== undefined && saved.length > 0 && saved !== 'my-location') {
onChangeLocation(saved)
}
}
getApiData.data(apiRoutes.serviceProviders + querystring.parameter('location'))
.then((result) => {
const callback = () => {
locationSelector.handler(onChangeLocation)
browser.loaded()
displayMap(result.data, currentLocation)
}
if (result.data.length === 0) {
let theData = {
location: currentLocation.name
}
templating.renderTemplate('js-category-no-result-tpl', theData, 'js-category-result-output', callback)
} else {
let sorted = sortBy(result.data, function (provider) {
return provider.name.toLowerCase()
})
let theData = {
organisations: sorted,
location: currentLocation.name
}
templating.renderTemplate('js-category-result-tpl', theData, 'js-category-result-output', callback)
}
})
}
let init = () => {
browser.loading()
locationSelector
.getCurrent()
.then((result) => {
getData(result)
})
}
init()
|
remove console.log
|
src/js/page-all-service-providers.js
|
remove console.log
|
<ide><path>rc/js/page-all-service-providers.js
<ide>
<ide> providers
<ide> .forEach((p) => {
<del> console.log(p)
<del>
<ide> if (p.addresses.length === 0) return
<ide>
<ide> const infoWindow = new google.maps.InfoWindow({
<ide> })
<ide>
<ide> infoWindows.push(infoWindow)
<del>
<del> console.log(infoWindow)
<ide>
<ide> const marker = new google.maps.Marker({
<ide> position: { lat: p.addresses[0].latitude, lng: p.addresses[0].longitude },
|
|
Java
|
apache-2.0
|
87acc27eff54653169a4d520d6bced7c5718b7af
| 0 |
szugyi/Android-CircleMenu,szugyi/Android-CircleMenu
|
package com.szugyi.circlemenu.view;
/*
* Copyright 2015 Csaba Szugyiczki
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import com.szugyi.circlemenu.R;
/**
* @author Szugyi Creates a rotatable circle menu which can be parameterized by
* custom attributes. Handles touches and gestures to make the menu
* rotatable, and to make the menu items selectable and clickable.
*/
public class CircleLayout extends ViewGroup {
// Event listeners
private OnItemClickListener onItemClickListener = null;
private OnItemSelectedListener onItemSelectedListener = null;
private OnCenterClickListener onCenterClickListener = null;
private OnRotationFinishedListener onRotationFinishedListener = null;
// Background image
private Bitmap imageOriginal, imageScaled;
// Sizes of the ViewGroup
private int circleWidth, circleHeight;
private float radius = 0;
// Child sizes
private int maxChildWidth = 0;
private int maxChildHeight = 0;
// Touch detection
private GestureDetector gestureDetector;
// Detecting inverse rotations
private boolean[] quadrantTouched;
// Settings of the ViewGroup
private int speed = 25;
private float angle = 90;
private float firstChildPos = 90;
private boolean isRotating = true;
// Tapped and selected child
private View selectedView = null;
// Rotation animator
private ObjectAnimator animator;
public CircleLayout(Context context) {
this(context, null);
}
public CircleLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CircleLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(attrs);
}
/**
* Initializes the ViewGroup and modifies it's default behavior by the
* passed attributes
*
* @param attrs the attributes used to modify default settings
*/
protected void init(AttributeSet attrs) {
gestureDetector = new GestureDetector(getContext(),
new MyGestureListener());
quadrantTouched = new boolean[]{false, false, false, false, false};
if (attrs != null) {
TypedArray a = getContext().obtainStyledAttributes(attrs,
R.styleable.CircleLayout);
// The angle where the first menu item will be drawn
angle = a.getInt(R.styleable.CircleLayout_firstChildPosition,
(int) angle);
firstChildPos = angle;
speed = a.getInt(R.styleable.CircleLayout_speed, speed);
isRotating = a.getBoolean(R.styleable.CircleLayout_isRotating,
isRotating);
if (imageOriginal == null) {
int picId = a.getResourceId(
R.styleable.CircleLayout_circleBackground, -1);
// If a background image was set as an attribute,
// retrieve the image
if (picId != -1) {
imageOriginal = BitmapFactory.decodeResource(
getResources(), picId);
}
}
a.recycle();
// Needed for the ViewGroup to be drawn
setWillNotDraw(false);
}
}
public float getAngle() {
return angle;
}
public void setAngle(float angle) {
this.angle = angle % 360;
setChildAngles();
}
/**
* Returns the currently selected menu
*
* @return the view which is currently the closest to the first item
* position
*/
public View getSelectedItem() {
if (selectedView == null) {
selectedView = getChildAt(0);
}
return selectedView;
}
@Override
protected void onDraw(Canvas canvas) {
// The sizes of the ViewGroup
circleHeight = getHeight();
circleWidth = getWidth();
if (imageOriginal != null) {
// Scaling the size of the background image
if (imageScaled == null) {
float diameter = radius * 2;
float sx = diameter / imageOriginal
.getWidth();
float sy = diameter / imageOriginal
.getHeight();
Matrix matrix = new Matrix();
matrix.postScale(sx, sy);
imageScaled = Bitmap.createBitmap(imageOriginal, 0, 0,
imageOriginal.getWidth(), imageOriginal.getHeight(),
matrix, false);
}
if (imageScaled != null) {
// Move the background to the center
int cx = (circleWidth - imageScaled.getWidth()) / 2;
int cy = (circleHeight - imageScaled.getHeight()) / 2;
canvas.drawBitmap(imageScaled, cx, cy, null);
}
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Log.v(VIEW_LOG_TAG, "onMeasure");
// Measure child views first
maxChildWidth = 0;
maxChildHeight = 0;
int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.AT_MOST);
int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.AT_MOST);
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == GONE) {
continue;
}
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
maxChildWidth = Math.max(maxChildWidth, child.getMeasuredWidth());
maxChildHeight = Math.max(maxChildHeight, child.getMeasuredHeight());
}
// Then decide what size we want to be
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int width;
int height;
//Measure Width
if (widthMode == MeasureSpec.EXACTLY) {
//Must be this size
width = widthSize;
} else if (widthMode == MeasureSpec.AT_MOST) {
//Can't be bigger than...
width = Math.min(widthSize, heightSize);
} else {
//Be whatever you want
width = maxChildWidth * 3;
}
//Measure Height
if (heightMode == MeasureSpec.EXACTLY) {
//Must be this size
height = heightSize;
} else if (heightMode == MeasureSpec.AT_MOST) {
//Can't be bigger than...
height = Math.min(heightSize, widthSize);
} else {
//Be whatever you want
height = maxChildHeight * 3;
}
setMeasuredDimension(resolveSize(width, widthMeasureSpec),
resolveSize(height, heightMeasureSpec));
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
Log.v(VIEW_LOG_TAG, "onLayout");
int layoutWidth = r - l;
int layoutHeight = b - t;
radius = (layoutWidth <= layoutHeight) ? layoutWidth / 3
: layoutHeight / 3;
circleHeight = getHeight();
circleWidth = getWidth();
setChildAngles();
}
/**
* Rotates the given view to the firstChildPosition
*
* @param view the view to be rotated
*/
private void rotateViewToCenter(View view) {
Log.v(VIEW_LOG_TAG, "rotateViewToCenter");
if (isRotating) {
float viewAngle = view.getTag() != null ? (Float) view.getTag() : 0;
float destAngle = (firstChildPos - viewAngle);
if (destAngle < 0) {
destAngle += 360;
}
if (destAngle > 180) {
destAngle = -1 * (360 - destAngle);
}
animateTo(angle + destAngle, 7500 / speed);
}
}
private void rotateButtons(float degrees) {
angle += degrees;
setChildAngles();
}
private void setChildAngles() {
int left, top, childWidth, childHeight, childCount = getChildCount();
float angleDelay = 360.0f / childCount;
float halfAngle = angleDelay / 2;
float localAngle = angle;
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == GONE) {
continue;
}
if (localAngle > 360) {
localAngle -= 360;
} else if (localAngle < 0) {
localAngle += 360;
}
childWidth = child.getMeasuredWidth();
childHeight = child.getMeasuredHeight();
left = Math
.round((float) (((circleWidth / 2.0) - childWidth / 2.0) + radius
* Math.cos(Math.toRadians(localAngle))));
top = Math
.round((float) (((circleHeight / 2.0) - childHeight / 2.0) + radius
* Math.sin(Math.toRadians(localAngle))));
child.setTag(localAngle);
float distance = Math.abs(localAngle - firstChildPos);
boolean isFirstItem = distance < halfAngle
|| distance > (360 - halfAngle);
if (isFirstItem && selectedView != child) {
selectedView = child;
if (onItemSelectedListener != null && isRotating) {
onItemSelectedListener.onItemSelected(child);
}
}
child.layout(left, top, left + childWidth, top + childHeight);
localAngle += angleDelay;
}
}
private void animateTo(float endDegree, long duration) {
if (animator != null && animator.isRunning()
|| Math.abs(angle - endDegree) < 1) {
return;
}
animator = ObjectAnimator.ofFloat(CircleLayout.this, "angle", angle,
endDegree);
animator.setDuration(duration);
animator.setInterpolator(new DecelerateInterpolator());
animator.addListener(new Animator.AnimatorListener() {
private boolean wasCanceled = false;
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
if (wasCanceled) {
return;
}
if (onRotationFinishedListener != null) {
View view = getSelectedItem();
onRotationFinishedListener.onRotationFinished(view);
}
}
@Override
public void onAnimationCancel(Animator animation) {
wasCanceled = true;
}
});
animator.start();
}
private void stopAnimation() {
if (animator != null && animator.isRunning()) {
animator.cancel();
animator = null;
}
}
/**
* @return The angle of the unit circle with the image views center
*/
private double getPositionAngle(double xTouch, double yTouch) {
double x = xTouch - (circleWidth / 2d);
double y = circleHeight - yTouch - (circleHeight / 2d);
switch (getPositionQuadrant(x, y)) {
case 1:
return Math.asin(y / Math.hypot(x, y)) * 180 / Math.PI;
case 2:
case 3:
return 180 - (Math.asin(y / Math.hypot(x, y)) * 180 / Math.PI);
case 4:
return 360 + Math.asin(y / Math.hypot(x, y)) * 180 / Math.PI;
default:
// ignore, does not happen
return 0;
}
}
/**
* @return The quadrant of the position
*/
private static int getPositionQuadrant(double x, double y) {
if (x >= 0) {
return y >= 0 ? 1 : 4;
} else {
return y >= 0 ? 2 : 3;
}
}
// Touch helpers
private double touchStartAngle;
private boolean didMove = false;
@Override
public boolean onTouchEvent(MotionEvent event) {
if (isEnabled()) {
gestureDetector.onTouchEvent(event);
if (isRotating) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// reset the touched quadrants
for (int i = 0; i < quadrantTouched.length; i++) {
quadrantTouched[i] = false;
}
stopAnimation();
touchStartAngle = getPositionAngle(event.getX(),
event.getY());
didMove = false;
break;
case MotionEvent.ACTION_MOVE:
double currentAngle = getPositionAngle(event.getX(),
event.getY());
rotateButtons((float) (touchStartAngle - currentAngle));
touchStartAngle = currentAngle;
didMove = true;
break;
case MotionEvent.ACTION_UP:
if (didMove) {
rotateViewToCenter(selectedView);
}
break;
}
}
// set the touched quadrant to true
quadrantTouched[getPositionQuadrant(event.getX()
- (circleWidth / 2), circleHeight - event.getY()
- (circleHeight / 2))] = true;
return true;
}
return false;
}
private class MyGestureListener extends SimpleOnGestureListener {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
if (!isRotating) {
return false;
}
// get the quadrant of the start and the end of the fling
int q1 = getPositionQuadrant(e1.getX() - (circleWidth / 2),
circleHeight - e1.getY() - (circleHeight / 2));
int q2 = getPositionQuadrant(e2.getX() - (circleWidth / 2),
circleHeight - e2.getY() - (circleHeight / 2));
if ((q1 == 2 && q2 == 2 && Math.abs(velocityX) < Math
.abs(velocityY))
|| (q1 == 3 && q2 == 3)
|| (q1 == 1 && q2 == 3)
|| (q1 == 4 && q2 == 4 && Math.abs(velocityX) > Math
.abs(velocityY))
|| ((q1 == 2 && q2 == 3) || (q1 == 3 && q2 == 2))
|| ((q1 == 3 && q2 == 4) || (q1 == 4 && q2 == 3))
|| (q1 == 2 && q2 == 4 && quadrantTouched[3])
|| (q1 == 4 && q2 == 2 && quadrantTouched[3])) {
// the inverted rotations
animateTo(
getCenteredAngle(angle - (velocityX + velocityY) / 25),
25000 / speed);
} else {
// the normal rotation
animateTo(
getCenteredAngle(angle + (velocityX + velocityY) / 25),
25000 / speed);
}
return true;
}
private float getCenteredAngle(float angle) {
float angleDelay = 360 / getChildCount();
float localAngle = angle % 360;
if (localAngle < 0) {
localAngle = 360 + localAngle;
}
for (float i = firstChildPos; i < firstChildPos + 360; i += angleDelay) {
float locI = i % 360;
float diff = localAngle - locI;
if (Math.abs(diff) < angleDelay / 2) {
angle -= diff;
break;
}
}
return angle;
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
View tappedView = null;
int tappedViewsPosition = pointToChildPosition(e.getX(), e.getY());
if (tappedViewsPosition >= 0) {
tappedView = getChildAt(tappedViewsPosition);
tappedView.setPressed(true);
} else {
// Determine if it was a center click
float centerX = circleWidth / 2;
float centerY = circleHeight / 2;
if (onCenterClickListener != null
&& e.getX() < centerX + radius - (maxChildWidth / 2)
&& e.getX() > centerX - radius + (maxChildWidth / 2)
&& e.getY() < centerY + radius - (maxChildHeight / 2)
&& e.getY() > centerY - radius + (maxChildHeight / 2)) {
onCenterClickListener.onCenterClick();
return true;
}
}
if (tappedView != null) {
if (selectedView == tappedView) {
if (onItemClickListener != null) {
onItemClickListener.onItemClick(tappedView);
}
} else {
rotateViewToCenter(tappedView);
if (!isRotating) {
if (onItemSelectedListener != null) {
onItemSelectedListener.onItemSelected(tappedView);
}
if (onItemClickListener != null) {
onItemClickListener.onItemClick(tappedView);
}
}
}
return true;
}
return super.onSingleTapUp(e);
}
private int pointToChildPosition(float x, float y) {
for (int i = 0; i < getChildCount(); i++) {
View view = getChildAt(i);
if (view.getLeft() < x && view.getRight() > x
& view.getTop() < y && view.getBottom() > y) {
return i;
}
}
return -1;
}
}
public interface OnItemClickListener {
void onItemClick(View view);
}
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
public interface OnItemSelectedListener {
void onItemSelected(View view);
}
public void setOnItemSelectedListener(
OnItemSelectedListener onItemSelectedListener) {
this.onItemSelectedListener = onItemSelectedListener;
}
public interface OnCenterClickListener {
void onCenterClick();
}
public void setOnCenterClickListener(
OnCenterClickListener onCenterClickListener) {
this.onCenterClickListener = onCenterClickListener;
}
public interface OnRotationFinishedListener {
void onRotationFinished(View view);
}
public void setOnRotationFinishedListener(
OnRotationFinishedListener onRotationFinishedListener) {
this.onRotationFinishedListener = onRotationFinishedListener;
}
}
|
circlemenu/src/main/java/com/szugyi/circlemenu/view/CircleLayout.java
|
package com.szugyi.circlemenu.view;
/*
* Copyright 2015 Csaba Szugyiczki
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import com.szugyi.circlemenu.R;
/**
* @author Szugyi Creates a rotatable circle menu which can be parameterized by
* custom attributes. Handles touches and gestures to make the menu
* rotatable, and to make the menu items selectable and clickable.
*/
public class CircleLayout extends ViewGroup {
// Event listeners
private OnItemClickListener onItemClickListener = null;
private OnItemSelectedListener onItemSelectedListener = null;
private OnCenterClickListener onCenterClickListener = null;
private OnRotationFinishedListener onRotationFinishedListener = null;
// Background image
private Bitmap imageOriginal, imageScaled;
// Sizes of the ViewGroup
private int circleWidth, circleHeight;
private float radius = 0;
// Child sizes
private int maxChildWidth = 0;
private int maxChildHeight = 0;
// Touch detection
private GestureDetector gestureDetector;
// Detecting inverse rotations
private boolean[] quadrantTouched;
// Settings of the ViewGroup
private int speed = 25;
private float angle = 90;
private float firstChildPos = 90;
private boolean isRotating = true;
// Tapped and selected child
private View selectedView = null;
// Rotation animator
private ObjectAnimator animator;
public CircleLayout(Context context) {
this(context, null);
}
public CircleLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CircleLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(attrs);
}
/**
* Initializes the ViewGroup and modifies it's default behavior by the
* passed attributes
*
* @param attrs the attributes used to modify default settings
*/
protected void init(AttributeSet attrs) {
gestureDetector = new GestureDetector(getContext(),
new MyGestureListener());
quadrantTouched = new boolean[]{false, false, false, false, false};
if (attrs != null) {
TypedArray a = getContext().obtainStyledAttributes(attrs,
R.styleable.CircleLayout);
// The angle where the first menu item will be drawn
angle = a.getInt(R.styleable.CircleLayout_firstChildPosition,
(int) angle);
firstChildPos = angle;
speed = a.getInt(R.styleable.CircleLayout_speed, speed);
isRotating = a.getBoolean(R.styleable.CircleLayout_isRotating,
isRotating);
if (imageOriginal == null) {
int picId = a.getResourceId(
R.styleable.CircleLayout_circleBackground, -1);
// If a background image was set as an attribute,
// retrieve the image
if (picId != -1) {
imageOriginal = BitmapFactory.decodeResource(
getResources(), picId);
}
}
a.recycle();
// Needed for the ViewGroup to be drawn
setWillNotDraw(false);
}
}
public float getAngle() {
return angle;
}
public void setAngle(float angle) {
this.angle = angle % 360;
setChildAngles();
}
/**
* Returns the currently selected menu
*
* @return the view which is currently the closest to the first item
* position
*/
public View getSelectedItem() {
if (selectedView == null) {
selectedView = getChildAt(0);
}
return selectedView;
}
@Override
protected void onDraw(Canvas canvas) {
// The sizes of the ViewGroup
circleHeight = getHeight();
circleWidth = getWidth();
if (imageOriginal != null) {
// Scaling the size of the background image
if (imageScaled == null) {
float diameter = radius * 2;
float sx = diameter / imageOriginal
.getWidth();
float sy = diameter / imageOriginal
.getHeight();
Matrix matrix = new Matrix();
matrix.postScale(sx, sy);
imageScaled = Bitmap.createBitmap(imageOriginal, 0, 0,
imageOriginal.getWidth(), imageOriginal.getHeight(),
matrix, false);
}
if (imageScaled != null) {
// Move the background to the center
int cx = (circleWidth - imageScaled.getWidth()) / 2;
int cy = (circleHeight - imageScaled.getHeight()) / 2;
canvas.drawBitmap(imageScaled, cx, cy, null);
}
}
}
// TODO Modify onMeasure to be able to handle Wrap_Content appropriately
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Log.v(VIEW_LOG_TAG, "onMeasure");
// Measure child views first
maxChildWidth = 0;
maxChildHeight = 0;
int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.AT_MOST);
int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.AT_MOST);
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == GONE) {
continue;
}
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
maxChildWidth = Math.max(maxChildWidth, child.getMeasuredWidth());
maxChildHeight = Math.max(maxChildHeight, child.getMeasuredHeight());
}
// Then decide what size we want to be
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int width;
int height;
//Measure Width
if (widthMode == MeasureSpec.EXACTLY) {
//Must be this size
width = widthSize;
} else if (widthMode == MeasureSpec.AT_MOST) {
//Can't be bigger than...
width = Math.min(widthSize, heightSize);
} else {
//Be whatever you want
width = maxChildWidth * 3;
}
//Measure Height
if (heightMode == MeasureSpec.EXACTLY) {
//Must be this size
height = heightSize;
} else if (heightMode == MeasureSpec.AT_MOST) {
//Can't be bigger than...
height = Math.min(heightSize, widthSize);
} else {
//Be whatever you want
height = maxChildHeight * 3;
}
setMeasuredDimension(resolveSize(width, widthMeasureSpec),
resolveSize(height, heightMeasureSpec));
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
Log.v(VIEW_LOG_TAG, "onLayout");
int layoutWidth = r - l;
int layoutHeight = b - t;
radius = (layoutWidth <= layoutHeight) ? layoutWidth / 3
: layoutHeight / 3;
circleHeight = getHeight();
circleWidth = getWidth();
setChildAngles();
}
/**
* Rotates the given view to the firstChildPosition
*
* @param view the view to be rotated
*/
private void rotateViewToCenter(View view) {
Log.v(VIEW_LOG_TAG, "rotateViewToCenter");
if (isRotating) {
float viewAngle = view.getTag() != null ? (Float) view.getTag() : 0;
float destAngle = (firstChildPos - viewAngle);
if (destAngle < 0) {
destAngle += 360;
}
if (destAngle > 180) {
destAngle = -1 * (360 - destAngle);
}
animateTo(angle + destAngle, 7500 / speed);
}
}
private void rotateButtons(float degrees) {
angle += degrees;
setChildAngles();
}
private void setChildAngles() {
int left, top, childWidth, childHeight, childCount = getChildCount();
float angleDelay = 360.0f / childCount;
float halfAngle = angleDelay / 2;
float localAngle = angle;
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == GONE) {
continue;
}
if (localAngle > 360) {
localAngle -= 360;
} else if (localAngle < 0) {
localAngle += 360;
}
childWidth = child.getMeasuredWidth();
childHeight = child.getMeasuredHeight();
left = Math
.round((float) (((circleWidth / 2.0) - childWidth / 2.0) + radius
* Math.cos(Math.toRadians(localAngle))));
top = Math
.round((float) (((circleHeight / 2.0) - childHeight / 2.0) + radius
* Math.sin(Math.toRadians(localAngle))));
child.setTag(localAngle);
float distance = Math.abs(localAngle - firstChildPos);
boolean isFirstItem = distance < halfAngle
|| distance > (360 - halfAngle);
if (isFirstItem && selectedView != child) {
selectedView = child;
if (onItemSelectedListener != null && isRotating) {
onItemSelectedListener.onItemSelected(child);
}
}
child.layout(left, top, left + childWidth, top + childHeight);
localAngle += angleDelay;
}
}
private void animateTo(float endDegree, long duration) {
if (animator != null && animator.isRunning()
|| Math.abs(angle - endDegree) < 1) {
return;
}
animator = ObjectAnimator.ofFloat(CircleLayout.this, "angle", angle,
endDegree);
animator.setDuration(duration);
animator.setInterpolator(new DecelerateInterpolator());
animator.addListener(new Animator.AnimatorListener() {
private boolean wasCanceled = false;
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
if (wasCanceled) {
return;
}
if (onRotationFinishedListener != null) {
View view = getSelectedItem();
onRotationFinishedListener.onRotationFinished(view);
}
}
@Override
public void onAnimationCancel(Animator animation) {
wasCanceled = true;
}
});
animator.start();
}
private void stopAnimation() {
if (animator != null && animator.isRunning()) {
animator.cancel();
animator = null;
}
}
/**
* @return The angle of the unit circle with the image views center
*/
private double getPositionAngle(double xTouch, double yTouch) {
double x = xTouch - (circleWidth / 2d);
double y = circleHeight - yTouch - (circleHeight / 2d);
switch (getPositionQuadrant(x, y)) {
case 1:
return Math.asin(y / Math.hypot(x, y)) * 180 / Math.PI;
case 2:
case 3:
return 180 - (Math.asin(y / Math.hypot(x, y)) * 180 / Math.PI);
case 4:
return 360 + Math.asin(y / Math.hypot(x, y)) * 180 / Math.PI;
default:
// ignore, does not happen
return 0;
}
}
/**
* @return The quadrant of the position
*/
private static int getPositionQuadrant(double x, double y) {
if (x >= 0) {
return y >= 0 ? 1 : 4;
} else {
return y >= 0 ? 2 : 3;
}
}
// Touch helpers
private double touchStartAngle;
private boolean didMove = false;
@Override
public boolean onTouchEvent(MotionEvent event) {
if (isEnabled()) {
gestureDetector.onTouchEvent(event);
if (isRotating) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// reset the touched quadrants
for (int i = 0; i < quadrantTouched.length; i++) {
quadrantTouched[i] = false;
}
stopAnimation();
touchStartAngle = getPositionAngle(event.getX(),
event.getY());
didMove = false;
break;
case MotionEvent.ACTION_MOVE:
double currentAngle = getPositionAngle(event.getX(),
event.getY());
rotateButtons((float) (touchStartAngle - currentAngle));
touchStartAngle = currentAngle;
didMove = true;
break;
case MotionEvent.ACTION_UP:
if (didMove) {
rotateViewToCenter(selectedView);
}
break;
}
}
// set the touched quadrant to true
quadrantTouched[getPositionQuadrant(event.getX()
- (circleWidth / 2), circleHeight - event.getY()
- (circleHeight / 2))] = true;
return true;
}
return false;
}
private class MyGestureListener extends SimpleOnGestureListener {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
if (!isRotating) {
return false;
}
// get the quadrant of the start and the end of the fling
int q1 = getPositionQuadrant(e1.getX() - (circleWidth / 2),
circleHeight - e1.getY() - (circleHeight / 2));
int q2 = getPositionQuadrant(e2.getX() - (circleWidth / 2),
circleHeight - e2.getY() - (circleHeight / 2));
if ((q1 == 2 && q2 == 2 && Math.abs(velocityX) < Math
.abs(velocityY))
|| (q1 == 3 && q2 == 3)
|| (q1 == 1 && q2 == 3)
|| (q1 == 4 && q2 == 4 && Math.abs(velocityX) > Math
.abs(velocityY))
|| ((q1 == 2 && q2 == 3) || (q1 == 3 && q2 == 2))
|| ((q1 == 3 && q2 == 4) || (q1 == 4 && q2 == 3))
|| (q1 == 2 && q2 == 4 && quadrantTouched[3])
|| (q1 == 4 && q2 == 2 && quadrantTouched[3])) {
// the inverted rotations
animateTo(
getCenteredAngle(angle - (velocityX + velocityY) / 25),
25000 / speed);
} else {
// the normal rotation
animateTo(
getCenteredAngle(angle + (velocityX + velocityY) / 25),
25000 / speed);
}
return true;
}
private float getCenteredAngle(float angle) {
float angleDelay = 360 / getChildCount();
float localAngle = angle % 360;
if (localAngle < 0) {
localAngle = 360 + localAngle;
}
for (float i = firstChildPos; i < firstChildPos + 360; i += angleDelay) {
float locI = i % 360;
float diff = localAngle - locI;
if (Math.abs(diff) < angleDelay / 2) {
angle -= diff;
break;
}
}
return angle;
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
View tappedView = null;
int tappedViewsPosition = pointToChildPosition(e.getX(), e.getY());
if (tappedViewsPosition >= 0) {
tappedView = getChildAt(tappedViewsPosition);
tappedView.setPressed(true);
} else {
// Determine if it was a center click
float centerX = circleWidth / 2;
float centerY = circleHeight / 2;
if (onCenterClickListener != null
&& e.getX() < centerX + radius - (maxChildWidth / 2)
&& e.getX() > centerX - radius + (maxChildWidth / 2)
&& e.getY() < centerY + radius - (maxChildHeight / 2)
&& e.getY() > centerY - radius + (maxChildHeight / 2)) {
onCenterClickListener.onCenterClick();
return true;
}
}
if (tappedView != null) {
if (selectedView == tappedView) {
if (onItemClickListener != null) {
onItemClickListener.onItemClick(tappedView);
}
} else {
rotateViewToCenter(tappedView);
if (!isRotating) {
if (onItemSelectedListener != null) {
onItemSelectedListener.onItemSelected(tappedView);
}
if (onItemClickListener != null) {
onItemClickListener.onItemClick(tappedView);
}
}
}
return true;
}
return super.onSingleTapUp(e);
}
private int pointToChildPosition(float x, float y) {
for (int i = 0; i < getChildCount(); i++) {
View view = getChildAt(i);
if (view.getLeft() < x && view.getRight() > x
& view.getTop() < y && view.getBottom() > y) {
return i;
}
}
return -1;
}
}
public interface OnItemClickListener {
void onItemClick(View view);
}
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
public interface OnItemSelectedListener {
void onItemSelected(View view);
}
public void setOnItemSelectedListener(
OnItemSelectedListener onItemSelectedListener) {
this.onItemSelectedListener = onItemSelectedListener;
}
public interface OnCenterClickListener {
void onCenterClick();
}
public void setOnCenterClickListener(
OnCenterClickListener onCenterClickListener) {
this.onCenterClickListener = onCenterClickListener;
}
public interface OnRotationFinishedListener {
void onRotationFinished(View view);
}
public void setOnRotationFinishedListener(
OnRotationFinishedListener onRotationFinishedListener) {
this.onRotationFinishedListener = onRotationFinishedListener;
}
}
|
fixed TODO deleted
|
circlemenu/src/main/java/com/szugyi/circlemenu/view/CircleLayout.java
|
fixed TODO deleted
|
<ide><path>irclemenu/src/main/java/com/szugyi/circlemenu/view/CircleLayout.java
<ide> }
<ide> }
<ide>
<del> // TODO Modify onMeasure to be able to handle Wrap_Content appropriately
<ide> @Override
<ide> protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
<ide> Log.v(VIEW_LOG_TAG, "onMeasure");
|
|
Java
|
bsd-3-clause
|
6e611a7022bc402208258d0136e700bbe9de206c
| 0 |
antlr/antlr4,parrt/antlr4,ericvergnaud/antlr4,antlr/antlr4,parrt/antlr4,ericvergnaud/antlr4,ericvergnaud/antlr4,ericvergnaud/antlr4,antlr/antlr4,ericvergnaud/antlr4,parrt/antlr4,antlr/antlr4,parrt/antlr4,parrt/antlr4,antlr/antlr4,antlr/antlr4,ericvergnaud/antlr4,parrt/antlr4,antlr/antlr4,ericvergnaud/antlr4,parrt/antlr4,parrt/antlr4,antlr/antlr4,ericvergnaud/antlr4,ericvergnaud/antlr4,parrt/antlr4,antlr/antlr4,ericvergnaud/antlr4,parrt/antlr4,antlr/antlr4
|
/*
* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
package org.antlr.v4.runtime.atn;
import org.antlr.v4.runtime.misc.AbstractEqualityComparator;
import org.antlr.v4.runtime.misc.Array2DHashSet;
import org.antlr.v4.runtime.misc.DoubleKeyMap;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
/**
* Specialized {@link Set}{@code <}{@link ATNConfig}{@code >} that can track
* info about the set, with support for combining similar configurations using a
* graph-structured stack.
*/
public class ATNConfigSet implements Set<ATNConfig> {
/**
* The reason that we need this is because we don't want the hash map to use
* the standard hash code and equals. We need all configurations with the same
* {@code (s,i,_,semctx)} to be equal. Unfortunately, this key effectively doubles
* the number of objects associated with ATNConfigs. The other solution is to
* use a hash table that lets us specify the equals/hashcode operation.
*/
public static class ConfigHashSet extends AbstractConfigHashSet {
public ConfigHashSet() {
super(ConfigEqualityComparator.INSTANCE);
}
}
public static final class ConfigEqualityComparator extends AbstractEqualityComparator<ATNConfig> {
public static final ConfigEqualityComparator INSTANCE = new ConfigEqualityComparator();
private ConfigEqualityComparator() {
}
@Override
public int hashCode(ATNConfig o) {
int hashCode = 7;
hashCode = 31 * hashCode + o.state.stateNumber;
hashCode = 31 * hashCode + o.alt;
hashCode = 31 * hashCode + o.semanticContext.hashCode();
return hashCode;
}
@Override
public boolean equals(ATNConfig a, ATNConfig b) {
if ( a==b ) return true;
if ( a==null || b==null ) return false;
return a.state.stateNumber==b.state.stateNumber
&& a.alt==b.alt
&& a.semanticContext.equals(b.semanticContext);
}
}
/** Indicates that the set of configurations is read-only. Do not
* allow any code to manipulate the set; DFA states will point at
* the sets and they must not change. This does not protect the other
* fields; in particular, conflictingAlts is set after
* we've made this readonly.
*/
protected boolean readonly = false;
/**
* All configs but hashed by (s, i, _, pi) not including context. Wiped out
* when we go readonly as this set becomes a DFA state.
*/
public AbstractConfigHashSet configLookup;
/** Track the elements as they are added to the set; supports get(i) */
public final ArrayList<ATNConfig> configs = new ArrayList<ATNConfig>(7);
// TODO: these fields make me pretty uncomfortable but nice to pack up info together, saves recomputation
// TODO: can we track conflicts as they are added to save scanning configs later?
public int uniqueAlt;
/** Currently this is only used when we detect SLL conflict; this does
* not necessarily represent the ambiguous alternatives. In fact,
* I should also point out that this seems to include predicated alternatives
* that have predicates that evaluate to false. Computed in computeTargetState().
*/
protected BitSet conflictingAlts;
// Used in parser and lexer. In lexer, it indicates we hit a pred
// while computing a closure operation. Don't make a DFA state from this.
public boolean hasSemanticContext;
public boolean dipsIntoOuterContext;
/** Indicates that this configuration set is part of a full context
* LL prediction. It will be used to determine how to merge $. With SLL
* it's a wildcard whereas it is not for LL context merge.
*/
public final boolean fullCtx;
private int cachedHashCode = -1;
public ATNConfigSet(boolean fullCtx) {
configLookup = new ConfigHashSet();
this.fullCtx = fullCtx;
}
public ATNConfigSet() { this(true); }
public ATNConfigSet(ATNConfigSet old) {
this(old.fullCtx);
addAll(old);
this.uniqueAlt = old.uniqueAlt;
this.conflictingAlts = old.conflictingAlts;
this.hasSemanticContext = old.hasSemanticContext;
this.dipsIntoOuterContext = old.dipsIntoOuterContext;
}
@Override
public boolean add(ATNConfig config) {
return add(config, null);
}
/**
* Adding a new config means merging contexts with existing configs for
* {@code (s, i, pi, _)}, where {@code s} is the
* {@link ATNConfig#state}, {@code i} is the {@link ATNConfig#alt}, and
* {@code pi} is the {@link ATNConfig#semanticContext}. We use
* {@code (s,i,pi)} as key.
*
* <p>This method updates {@link #dipsIntoOuterContext} and
* {@link #hasSemanticContext} when necessary.</p>
*/
public boolean add(
ATNConfig config,
DoubleKeyMap<PredictionContext,PredictionContext,PredictionContext> mergeCache)
{
if ( readonly ) throw new IllegalStateException("This set is readonly");
if ( config.semanticContext != SemanticContext.Empty.Instance ) {
hasSemanticContext = true;
}
if (config.getOuterContextDepth() > 0) {
dipsIntoOuterContext = true;
}
ATNConfig existing = configLookup.getOrAdd(config);
if ( existing==config ) { // we added this new one
cachedHashCode = -1;
configs.add(config); // track order here
return true;
}
// a previous (s,i,pi,_), merge with it and save result
boolean rootIsWildcard = !fullCtx;
PredictionContext merged =
PredictionContext.merge(existing.context, config.context, rootIsWildcard, mergeCache);
// no need to check for existing.context, config.context in cache
// since only way to create new graphs is "call rule" and here. We
// cache at both places.
existing.reachesIntoOuterContext =
Math.max(existing.reachesIntoOuterContext, config.reachesIntoOuterContext);
// make sure to preserve the precedence filter suppression during the merge
if (config.isPrecedenceFilterSuppressed()) {
existing.setPrecedenceFilterSuppressed(true);
}
existing.context = merged; // replace context; no need to alt mapping
return true;
}
/** Return a List holding list of configs */
public List<ATNConfig> elements() { return configs; }
public Set<ATNState> getStates() {
Set<ATNState> states = new HashSet<ATNState>();
for (ATNConfig c : configs) {
states.add(c.state);
}
return states;
}
/**
* Gets the complete set of represented alternatives for the configuration
* set.
*
* @return the set of represented alternatives in this configuration set
*
* @since 4.3
*/
public BitSet getAlts() {
BitSet alts = new BitSet();
for (ATNConfig config : configs) {
alts.set(config.alt);
}
return alts;
}
public List<SemanticContext> getPredicates() {
List<SemanticContext> preds = new ArrayList<SemanticContext>();
for (ATNConfig c : configs) {
if ( c.semanticContext!=SemanticContext.Empty.Instance ) {
preds.add(c.semanticContext);
}
}
return preds;
}
public ATNConfig get(int i) { return configs.get(i); }
public void optimizeConfigs(ATNSimulator interpreter) {
if ( readonly ) throw new IllegalStateException("This set is readonly");
if ( configLookup.isEmpty() ) return;
for (ATNConfig config : configs) {
// int before = PredictionContext.getAllContextNodes(config.context).size();
config.context = interpreter.getCachedContext(config.context);
// int after = PredictionContext.getAllContextNodes(config.context).size();
// System.out.println("configs "+before+"->"+after);
}
}
@Override
public boolean addAll(Collection<? extends ATNConfig> coll) {
for (ATNConfig c : coll) add(c);
return false;
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
else if (!(o instanceof ATNConfigSet)) {
return false;
}
// System.out.print("equals " + this + ", " + o+" = ");
ATNConfigSet other = (ATNConfigSet)o;
boolean same = configs!=null &&
configs.equals(other.configs) && // includes stack context
this.fullCtx == other.fullCtx &&
this.uniqueAlt == other.uniqueAlt &&
this.conflictingAlts == other.conflictingAlts &&
this.hasSemanticContext == other.hasSemanticContext &&
this.dipsIntoOuterContext == other.dipsIntoOuterContext;
// System.out.println(same);
return same;
}
@Override
public int hashCode() {
if (isReadonly()) {
if (cachedHashCode == -1) {
cachedHashCode = configs.hashCode();
}
return cachedHashCode;
}
return configs.hashCode();
}
@Override
public int size() {
return configs.size();
}
@Override
public boolean isEmpty() {
return configs.isEmpty();
}
@Override
public boolean contains(Object o) {
if (configLookup == null) {
throw new UnsupportedOperationException("This method is not implemented for readonly sets.");
}
return configLookup.contains(o);
}
public boolean containsFast(ATNConfig obj) {
if (configLookup == null) {
throw new UnsupportedOperationException("This method is not implemented for readonly sets.");
}
return configLookup.containsFast(obj);
}
@Override
public Iterator<ATNConfig> iterator() {
return configs.iterator();
}
@Override
public void clear() {
if ( readonly ) throw new IllegalStateException("This set is readonly");
configs.clear();
cachedHashCode = -1;
configLookup.clear();
}
public boolean isReadonly() {
return readonly;
}
public void setReadonly(boolean readonly) {
this.readonly = readonly;
configLookup = null; // can't mod, no need for lookup cache
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder();
buf.append(elements().toString());
if ( hasSemanticContext ) buf.append(",hasSemanticContext=").append(hasSemanticContext);
if ( uniqueAlt!=ATN.INVALID_ALT_NUMBER ) buf.append(",uniqueAlt=").append(uniqueAlt);
if ( conflictingAlts!=null ) buf.append(",conflictingAlts=").append(conflictingAlts);
if ( dipsIntoOuterContext ) buf.append(",dipsIntoOuterContext");
return buf.toString();
}
// satisfy interface
@Override
public ATNConfig[] toArray() {
return configLookup.toArray();
}
@Override
public <T> T[] toArray(T[] a) {
return configLookup.toArray(a);
}
@Override
public boolean remove(Object o) {
throw new UnsupportedOperationException();
}
@Override
public boolean containsAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean retainAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean removeAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
public static abstract class AbstractConfigHashSet extends Array2DHashSet<ATNConfig> {
public AbstractConfigHashSet(AbstractEqualityComparator<? super ATNConfig> comparator) {
this(comparator, 16, 2);
}
public AbstractConfigHashSet(AbstractEqualityComparator<? super ATNConfig> comparator, int initialCapacity, int initialBucketCapacity) {
super(comparator, initialCapacity, initialBucketCapacity);
}
@Override
protected final ATNConfig asElementType(Object o) {
if (!(o instanceof ATNConfig)) {
return null;
}
return (ATNConfig)o;
}
@Override
protected final ATNConfig[][] createBuckets(int capacity) {
return new ATNConfig[capacity][];
}
@Override
protected final ATNConfig[] createBucket(int capacity) {
return new ATNConfig[capacity];
}
}
}
|
runtime/Java/src/org/antlr/v4/runtime/atn/ATNConfigSet.java
|
/*
* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
package org.antlr.v4.runtime.atn;
import org.antlr.v4.runtime.misc.AbstractEqualityComparator;
import org.antlr.v4.runtime.misc.Array2DHashSet;
import org.antlr.v4.runtime.misc.DoubleKeyMap;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
/**
* Specialized {@link Set}{@code <}{@link ATNConfig}{@code >} that can track
* info about the set, with support for combining similar configurations using a
* graph-structured stack.
*/
public class ATNConfigSet implements Set<ATNConfig> {
/**
* The reason that we need this is because we don't want the hash map to use
* the standard hash code and equals. We need all configurations with the same
* {@code (s,i,_,semctx)} to be equal. Unfortunately, this key effectively doubles
* the number of objects associated with ATNConfigs. The other solution is to
* use a hash table that lets us specify the equals/hashcode operation.
*/
public static class ConfigHashSet extends AbstractConfigHashSet {
public ConfigHashSet() {
super(ConfigEqualityComparator.INSTANCE);
}
}
public static final class ConfigEqualityComparator extends AbstractEqualityComparator<ATNConfig> {
public static final ConfigEqualityComparator INSTANCE = new ConfigEqualityComparator();
private ConfigEqualityComparator() {
}
@Override
public int hashCode(ATNConfig o) {
int hashCode = 7;
hashCode = 31 * hashCode + o.state.stateNumber;
hashCode = 31 * hashCode + o.alt;
hashCode = 31 * hashCode + o.semanticContext.hashCode();
return hashCode;
}
@Override
public boolean equals(ATNConfig a, ATNConfig b) {
if ( a==b ) return true;
if ( a==null || b==null ) return false;
return a.state.stateNumber==b.state.stateNumber
&& a.alt==b.alt
&& a.semanticContext.equals(b.semanticContext);
}
}
/** Indicates that the set of configurations is read-only. Do not
* allow any code to manipulate the set; DFA states will point at
* the sets and they must not change. This does not protect the other
* fields; in particular, conflictingAlts is set after
* we've made this readonly.
*/
protected boolean readonly = false;
/**
* All configs but hashed by (s, i, _, pi) not including context. Wiped out
* when we go readonly as this set becomes a DFA state.
*/
public AbstractConfigHashSet configLo
// TODO: these fields make me pretty uncomfortable but nice to pack up info together, saves recomputation
// TODO: can we track conflicts as they are added to save scanning configs later?
public int uniqueAlt;
/** Currently this is only used when we detect SLL conflict; this does
* not necessarily represent the ambiguous alternatives. In fact,
* I should also point out that this seems to include predicated alternatives
* that have predicates that evaluate to false. Computed in computeTargetState().
*/
protected BitSet conflictingAlts;
// Used in parser and lexer. In lexer, it indicates we hit a pred
// while computing a closure operation. Don't make a DFA state from this.
public boolean hasSemanticContext;
public boolean dipsIntoOuterContext;
/** Indicates that this configuration set is part of a full context
* LL prediction. It will be used to determine how to merge $. With SLL
* it's a wildcard whereas it is not for LL context merge.
*/
public final boolean fullCtx;
private int cachedHashCode = -1;
public ATNConfigSet(boolean fullCtx) {
configLookup = new ConfigHashSet();
this.fullCtx = fullCtx;
}
public ATNConfigSet() { this(true); }
public ATNConfigSet(ATNConfigSet old) {
this(old.fullCtx);
addAll(old);
this.uniqueAlt = old.uniqueAlt;
this.conflictingAlts = old.conflictingAlts;
this.hasSemanticContext = old.hasSemanticContext;
this.dipsIntoOuterContext = old.dipsIntoOuterContext;
}
@Override
public boolean add(ATNConfig config) {
return add(config, null);
}
/**
* Adding a new config means merging contexts with existing configs for
* {@code (s, i, pi, _)}, where {@code s} is the
* {@link ATNConfig#state}, {@code i} is the {@link ATNConfig#alt}, and
* {@code pi} is the {@link ATNConfig#semanticContext}. We use
* {@code (s,i,pi)} as key.
*
* <p>This method updates {@link #dipsIntoOuterContext} and
* {@link #hasSemanticContext} when necessary.</p>
*/
public boolean add(
ATNConfig config,
DoubleKeyMap<PredictionContext,PredictionContext,PredictionContext> mergeCache)
{
if ( readonly ) throw new IllegalStateException("This set is readonly");
if ( config.semanticContext != SemanticContext.Empty.Instance ) {
hasSemanticContext = true;
}
if (config.getOuterContextDepth() > 0) {
dipsIntoOuterContext = true;
}
ATNConfig existing = configLookup.getOrAdd(config);
if ( existing==config ) { // we added this new one
cachedHashCode = -1;
configs.add(config); // track order here
return true;
}
// a previous (s,i,pi,_), merge with it and save result
boolean rootIsWildcard = !fullCtx;
PredictionContext merged =
PredictionContext.merge(existing.context, config.context, rootIsWildcard, mergeCache);
// no need to check for existing.context, config.context in cache
// since only way to create new graphs is "call rule" and here. We
// cache at both places.
existing.reachesIntoOuterContext =
Math.max(existing.reachesIntoOuterContext, config.reachesIntoOuterContext);
// make sure to preserve the precedence filter suppression during the merge
if (config.isPrecedenceFilterSuppressed()) {
existing.setPrecedenceFilterSuppressed(true);
}
existing.context = merged; // replace context; no need to alt mapping
return true;
}
/** Return a List holding list of configs */
public List<ATNConfig> elements() { return configs; }
public Set<ATNState> getStates() {
Set<ATNState> states = new HashSet<ATNState>();
for (ATNConfig c : configs) {
states.add(c.state);
}
return states;
}
/**
* Gets the complete set of represented alternatives for the configuration
* set.
*
* @return the set of represented alternatives in this configuration set
*
* @since 4.3
*/
public BitSet getAlts() {
BitSet alts = new BitSet();
for (ATNConfig config : configs) {
alts.set(config.alt);
}
return alts;
}
public List<SemanticContext> getPredicates() {
List<SemanticContext> preds = new ArrayList<SemanticContext>();
for (ATNConfig c : configs) {
if ( c.semanticContext!=SemanticContext.Empty.Instance ) {
preds.add(c.semanticContext);
}
}
return preds;
}
public ATNConfig get(int i) { return configs.get(i); }
public void optimizeConfigs(ATNSimulator interpreter) {
if ( readonly ) throw new IllegalStateException("This set is readonly");
if ( configLookup.isEmpty() ) return;
for (ATNConfig config : configs) {
// int before = PredictionContext.getAllContextNodes(config.context).size();
config.context = interpreter.getCachedContext(config.context);
// int after = PredictionContext.getAllContextNodes(config.context).size();
// System.out.println("configs "+before+"->"+after);
}
}
@Override
public boolean addAll(Collection<? extends ATNConfig> coll) {
for (ATNConfig c : coll) add(c);
return false;
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
else if (!(o instanceof ATNConfigSet)) {
return false;
}
// System.out.print("equals " + this + ", " + o+" = ");
ATNConfigSet other = (ATNConfigSet)o;
boolean same = configs!=null &&
configs.equals(other.configs) && // includes stack context
this.fullCtx == other.fullCtx &&
this.uniqueAlt == other.uniqueAlt &&
this.conflictingAlts == other.conflictingAlts &&
this.hasSemanticContext == other.hasSemanticContext &&
this.dipsIntoOuterContext == other.dipsIntoOuterContext;
// System.out.println(same);
return same;
}
@Override
public int hashCode() {
if (isReadonly()) {
if (cachedHashCode == -1) {
cachedHashCode = configs.hashCode();
}
return cachedHashCode;
}
return configs.hashCode();
}
@Override
public int size() {
return configs.size();
}
@Override
public boolean isEmpty() {
return configs.isEmpty();
}
@Override
public boolean contains(Object o) {
if (configLookup == null) {
throw new UnsupportedOperationException("This method is not implemented for readonly sets.");
}
return configLookup.contains(o);
}
public boolean containsFast(ATNConfig obj) {
if (configLookup == null) {
throw new UnsupportedOperationException("This method is not implemented for readonly sets.");
}
return configLookup.containsFast(obj);
}
@Override
public Iterator<ATNConfig> iterator() {
return configs.iterator();
}
@Override
public void clear() {
if ( readonly ) throw new IllegalStateException("This set is readonly");
configs.clear();
cachedHashCode = -1;
configLookup.clear();
}
public boolean isReadonly() {
return readonly;
}
public void setReadonly(boolean readonly) {
this.readonly = readonly;
configLookup = null; // can't mod, no need for lookup cache
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder();
buf.append(elements().toString());
if ( hasSemanticContext ) buf.append(",hasSemanticContext=").append(hasSemanticContext);
if ( uniqueAlt!=ATN.INVALID_ALT_NUMBER ) buf.append(",uniqueAlt=").append(uniqueAlt);
if ( conflictingAlts!=null ) buf.append(",conflictingAlts=").append(conflictingAlts);
if ( dipsIntoOuterContext ) buf.append(",dipsIntoOuterContext");
return buf.toString();
}
// satisfy interface
@Override
public ATNConfig[] toArray() {
return configLookup.toArray();
}
@Override
public <T> T[] toArray(T[] a) {
return configLookup.toArray(a);
}
@Override
public boolean remove(Object o) {
throw new UnsupportedOperationException();
}
@Override
public boolean containsAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean retainAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean removeAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
public static abstract class AbstractConfigHashSet extends Array2DHashSet<ATNConfig> {
public AbstractConfigHashSet(AbstractEqualityComparator<? super ATNConfig> comparator) {
this(comparator, 16, 2);
}
public AbstractConfigHashSet(AbstractEqualityComparator<? super ATNConfig> comparator, int initialCapacity, int initialBucketCapacity) {
super(comparator, initialCapacity, initialBucketCapacity);
}
@Override
protected final ATNConfig asElementType(Object o) {
if (!(o instanceof ATNConfig)) {
return null;
}
return (ATNConfig)o;
}
@Override
protected final ATNConfig[][] createBuckets(int capacity) {
return new ATNConfig[capacity][];
}
@Override
protected final ATNConfig[] createBucket(int capacity) {
return new ATNConfig[capacity];
}
}
}
|
fix: #3718 Revert accidental keyboard error in Java target
Signed-off-by: Jim.Idle <[email protected]>
|
runtime/Java/src/org/antlr/v4/runtime/atn/ATNConfigSet.java
|
fix: #3718 Revert accidental keyboard error in Java target
|
<ide><path>untime/Java/src/org/antlr/v4/runtime/atn/ATNConfigSet.java
<ide> * All configs but hashed by (s, i, _, pi) not including context. Wiped out
<ide> * when we go readonly as this set becomes a DFA state.
<ide> */
<del> public AbstractConfigHashSet configLo
<add> public AbstractConfigHashSet configLookup;
<add>
<add> /** Track the elements as they are added to the set; supports get(i) */
<add> public final ArrayList<ATNConfig> configs = new ArrayList<ATNConfig>(7);
<ide>
<ide> // TODO: these fields make me pretty uncomfortable but nice to pack up info together, saves recomputation
<ide> // TODO: can we track conflicts as they are added to save scanning configs later?
|
|
JavaScript
|
mit
|
eeded9783d4c2228f653b34b2a9a5c9cd9cb151b
| 0 |
ruffrey/jsdoxy,ruffrey/jsdoxy
|
/*
* # grunt-jsdoxy
*
* forked from Matt McManus grunt-dox https://github.com/punkave/grunt-dox
*
* Licensed under the MIT license.
*/
var exec = require('child_process').exec;
var fs = require('fs');
var path = require('path');
var rimraf = require('rimraf');
var jade = require('jade');
var async = require('async');
var markdown = require('../lib/markdown');
module.exports = function(grunt) {
grunt.registerMultiTask('jsdoxy', 'Generate jsdoxy output ', function jsdoxyTask() {
var dir = this.filesSrc;
var dest = this.data.dest;
var done = this.async();
var doxPath = path.resolve(__dirname, '../');
var _opts = this.options();
_opts.template = _opts.template || path.normalize(__dirname + "/../default-template.jade");
var _args = [];
var outputFile = _opts.jsonOutput || "jsdoxy-output.json";
// Absolute path to jsdoxy
var jsdoxy = [doxPath, 'bin', 'jsdoxy'].join(path.sep);
// Cleanup any existing docs
rimraf.sync(dest);
var executeFiles = [];
var output = [];
var allFileLinks = [];
var markdownFiles = [];
dir.forEach(forEachFile);
function forEachFile(file) {
executeFiles.push(execFile);
function execFile(cb) {
// Markdown files.
// these are treated differently.
var isMarkdown = path.extname(file) === '.md';
if (isMarkdown) {
markdownFiles.push(file);
var filenameOut = _opts.flatten
? path.basename(file, '.md') + '.html'
: file.replace('.md', '.html');
allFileLinks.push(filenameOut);
cb();
return;
}
// Code files.
// Probably with .js extension.
var outputFilepath = path.join(dest, file + ".json");
// the exec'd process seems to not have proper permissions to write,
// unless the file exists already
grunt.file.write(outputFilepath, " ");
// capture the outputted file
var jsdoxyCommand = jsdoxy + ' < ' + file + " > " + outputFilepath;
var soMuch = 5000 * 1024;
var execOptions = { maxBuffer: soMuch };
exec(jsdoxyCommand, execOptions, onFileDoxxed);
function onFileDoxxed(error, stout, sterr) {
if (error) {
grunt.log.error("jsdoxy ERROR: " + error + "\n" + error.stack);
grunt.log.error(sterr);
return cb(err);
}
grunt.log.ok(file + '" got doxxed, yo!');
var fileJson = grunt.file.readJSON(outputFilepath);
fileJson.forEach(function(comment) {
if (!comment.ctx) comment.ctx = {};
comment.ctx.file = {
input: file,
output: outputFilepath
};
});
// then rewrite it with the most recent details
grunt.file.write(outputFilepath, JSON.stringify(fileJson, null, 4));
output = output.concat(fileJson);
cb();
}
}
}
async.series(executeFiles, function afterExec(err) {
if (err) throw err;
var organizedByClass = {};
var lastClassnameWas = "";
// comments.forEach, really
output.forEach(function (comment) {
var thisCommentGoesSomewhereElse = null;
function moveComment() {
grunt.log.ok(
'Moving "event" comment from',
lastClassnameWas, 'to',
comment.ctx.name
);
if (!organizedByClass[thisCommentGoesSomewhereElse]) {
organizedByClass[thisCommentGoesSomewhereElse] = [];
}
organizedByClass[thisCommentGoesSomewhereElse].push(comment);
return;
}
//
// Important:
// the `@class SomeClass` comment should always be in the first comment.
//
//
// Organize the comments by @class.
//
// Unless it's an event that is documented on a different class.
// Then move it to the right class.
if (comment.ctx.type && comment.ctx.name) {
if (comment.ctx.type === 'event' && !~comment.ctx.name.indexOf(lastClassnameWas) ) {
thisCommentGoesSomewhereElse = comment.ctx.name.split('#')[0];
moveComment();
}
}
comment.tags.forEach(function (tag) {
// Start a new class here
if (tag.type === 'class') {
if (comment.isPrivate && !_opts.outputPrivate) {
// do not include the private comments unless specified
} else {
lastClassnameWas = tag.string;
organizedByClass[lastClassnameWas] = [];
comment.ctx.name = lastClassnameWas;
}
}
if (tag.type === 'event' && tag.string && !~tag.string.indexOf(lastClassnameWas) ) {
thisCommentGoesSomewhereElse = tag.string.split('#')[0];
}
});
if (thisCommentGoesSomewhereElse) return moveComment();
if (!lastClassnameWas) return;
organizedByClass[lastClassnameWas].push(comment);
});
// writing out a giant JSON blob of everything, into one file
grunt.file.write(outputFile, JSON.stringify(organizedByClass, null, 4));
grunt.log.ok(
"Organized docs into " + Object.keys(organizedByClass).length + " classes and wrote to " + outputFile
);
if (_opts.template === false) return done();
if (!fs.existsSync(_opts.template)) return done(new Error(_opts.template + " does not exist!"));
grunt.log.ok('Jadifying the output using template ' + _opts.template);
// first get the file list for code comments
Object.keys(organizedByClass).forEach(function(classKey) {
var filenameOut = _opts.flatten
? classKey + ".html"
: organizedByClass[classKey][0].ctx.file.input.replace('.js', '.html');
allFileLinks.push(filenameOut);
});
// render the code comments, by class, into the jade template
Object.keys(organizedByClass).forEach(function(classKey) {
var thisClassDocs = organizedByClass[classKey];
var classCommentLink;
thisClassDocs.forEach(function(comment) {
comment.tags.forEach(function(tag) {
if (tag.type === "link") classCommentLink = tag.string;
if (classCommentLink) return false;
});
if (classCommentLink) return false;
});
var filenameOut = _opts.flatten
? classKey + ".html"
: organizedByClass[classKey][0].ctx.file.input.replace('.js', '.html');
var jadeLocals = {
structure: organizedByClass,
comments: thisClassDocs,
className: classKey,
link: classCommentLink,
files: allFileLinks,
basePath: _opts.basePath,
filenameOut: filenameOut
};
grunt.log.ok('Rendering docs page', filenameOut, 'with template', _opts.template, thisClassDocs.length, 'comments');
var html;
try {
html = jade.renderFile(_opts.template, jadeLocals);
} catch (ex) {
grunt.log.error('!! Failed rendering', filenameOut, ex);
return;
}
grunt.file.write(path.join(dest, filenameOut), html);
grunt.log.ok('Successfully rendered docs page', filenameOut);
});
// render the markdown pages
markdownFiles.forEach(function(file) {
var filenameOut = file.replace('.md', '.html');
var outpath = path.join(dest, filenameOut);
grunt.log.ok('Outputting markdown file ' + outpath);
var mdContents = markdown(fs.readFileSync(file, {
encoding: 'utf8'
}));
grunt.log.ok('Rendering markdown page ' + filenameOut, 'with template', _opts.template);
var html = jade.renderFile(_opts.template, {
structure: organizedByClass,
mdContents: mdContents,
comments: [],
className: file,
files: allFileLinks,
basePath: _opts.basePath,
filenameOut: filenameOut
});
grunt.file.write(outpath, html);
});
// write a little contents page if there is not one yet
if (_opts.generateIndex && allFileLinks.indexOf('index.html') === -1) {
grunt.log.ok('Generating index page.');
var html = jade.renderFile(_opts.template, {
mdContents: '<h1>Documentation</h1>',
comments: [],
structure: organizedByClass,
className: 'Index',
files: allFileLinks,
basePath: _opts.basePath,
filenameOut: 'index.html'
});
grunt.file.write(path.join(dest, 'index.html'), html);
}
done();
});
});
};
|
tasks/jsdoxy.js
|
/*
* # grunt-jsdoxy
*
* forked from Matt McManus grunt-dox https://github.com/punkave/grunt-dox
*
* Licensed under the MIT license.
*/
var exec = require('child_process').exec;
var fs = require('fs');
var path = require('path');
var rimraf = require('rimraf');
var jade = require('jade');
var async = require('async');
var markdown = require('../lib/markdown');
module.exports = function(grunt) {
grunt.registerMultiTask('jsdoxy', 'Generate jsdoxy output ', function jsdoxyTask() {
var dir = this.filesSrc;
var dest = this.data.dest;
var done = this.async();
var doxPath = path.resolve(__dirname, '../');
var _opts = this.options();
_opts.template = _opts.template || path.normalize(__dirname + "/../default-template.jade");
var _args = [];
var outputFile = _opts.jsonOutput || "jsdoxy-output.json";
// Absolute path to jsdoxy
var jsdoxy = [doxPath, 'bin', 'jsdoxy'].join(path.sep);
// Cleanup any existing docs
rimraf.sync(dest);
var executeFiles = [];
var output = [];
var allFileLinks = [];
var markdownFiles = [];
dir.forEach(forEachFile);
function forEachFile(file) {
executeFiles.push(execFile);
function execFile(cb) {
// Markdown files.
// these are treated differently.
var isMarkdown = path.extname(file) === '.md';
if (isMarkdown) {
markdownFiles.push(file);
var filenameOut = _opts.flatten
? path.basename(file, '.md') + '.html'
: file.replace('.md', '.html');
allFileLinks.push(filenameOut);
cb();
return;
}
// Code files.
// Probably with .js extension.
var outputFilepath = path.join(dest, file + ".json");
// the exec'd process seems to not have proper permissions to write,
// unless the file exists already
grunt.file.write(outputFilepath, " ");
// capture the outputted file
var jsdoxyCommand = jsdoxy + ' < ' + file + " > " + outputFilepath;
var soMuch = 5000 * 1024;
var execOptions = { maxBuffer: soMuch };
exec(jsdoxyCommand, execOptions, onFileDoxxed);
function onFileDoxxed(error, stout, sterr) {
if (error) {
grunt.log.error("jsdoxy ERROR: " + error + "\n" + error.stack);
grunt.log.error(sterr);
return cb(err);
}
grunt.log.ok(file + '" got doxxed, yo!');
var fileJson = grunt.file.readJSON(outputFilepath);
fileJson.forEach(function(comment) {
if (!comment.ctx) comment.ctx = {};
comment.ctx.file = {
input: file,
output: outputFilepath
};
});
// then rewrite it with the most recent details
grunt.file.write(outputFilepath, JSON.stringify(fileJson, null, 4));
output = output.concat(fileJson);
cb();
}
}
}
async.series(executeFiles, function afterExec(err) {
if (err) throw err;
var organizedByClass = {};
var lastClassnameWas = "";
// comments.forEach, really
output.forEach(function(comment) {
//
// Important:
// the `@class SomeClass` comment should always be in the first comment.
//
// organize the comments by @class
comment.tags.forEach(function(tag) {
if (tag.type == "class") {
if (comment.isPrivate && !_opts.outputPrivate) {
// do not include the private comments unless specified
} else {
lastClassnameWas = tag.string;
organizedByClass[lastClassnameWas] = [];
comment.ctx.name = lastClassnameWas;
}
}
});
if (!lastClassnameWas) return;
organizedByClass[lastClassnameWas].push(comment);
});
// writing out a giant JSON blob of everything, into one file
grunt.file.write(outputFile, JSON.stringify(organizedByClass, null, 4));
grunt.log.ok(
"Organized docs into " + Object.keys(organizedByClass).length + " classes and wrote to " + outputFile
);
if (_opts.template === false) return done();
if (!fs.existsSync(_opts.template)) return done(new Error(_opts.template + " does not exist!"));
grunt.log.ok('Jadifying the output using template ' + _opts.template);
// first get the file list for code comments
Object.keys(organizedByClass).forEach(function(classKey) {
var filenameOut = _opts.flatten
? classKey + ".html"
: organizedByClass[classKey][0].ctx.file.input.replace('.js', '.html');
allFileLinks.push(filenameOut);
});
// render the code comments, by class, into the jade template
Object.keys(organizedByClass).forEach(function(classKey) {
var thisClassDocs = organizedByClass[classKey];
var classCommentLink;
thisClassDocs.forEach(function(comment) {
comment.tags.forEach(function(tag) {
if (tag.type === "link") classCommentLink = tag.string;
if (classCommentLink) return false;
});
if (classCommentLink) return false;
});
var filenameOut = _opts.flatten
? classKey + ".html"
: organizedByClass[classKey][0].ctx.file.input.replace('.js', '.html');
var jadeLocals = {
structure: organizedByClass,
comments: thisClassDocs,
className: classKey,
link: classCommentLink,
files: allFileLinks,
basePath: _opts.basePath,
filenameOut: filenameOut
};
grunt.log.ok('Rendering docs page', filenameOut, 'with template', _opts.template, thisClassDocs.length, 'comments');
var html;
try {
html = jade.renderFile(_opts.template, jadeLocals);
} catch (ex) {
grunt.log.error('!! Failed rendering', filenameOut, ex);
return;
}
grunt.file.write(path.join(dest, filenameOut), html);
grunt.log.ok('Successfully rendered docs page', filenameOut);
});
// render the markdown pages
markdownFiles.forEach(function(file) {
var filenameOut = file.replace('.md', '.html');
var outpath = path.join(dest, filenameOut);
grunt.log.ok('Outputting markdown file ' + outpath);
var mdContents = markdown(fs.readFileSync(file, {
encoding: 'utf8'
}));
grunt.log.ok('Rendering markdown page ' + filenameOut, 'with template', _opts.template);
var html = jade.renderFile(_opts.template, {
structure: organizedByClass,
mdContents: mdContents,
comments: [],
className: file,
files: allFileLinks,
basePath: _opts.basePath,
filenameOut: filenameOut
});
grunt.file.write(outpath, html);
});
// write a little contents page if there is not one yet
if (_opts.generateIndex && allFileLinks.indexOf('index.html') === -1) {
grunt.log.ok('Generating index page.');
var html = jade.renderFile(_opts.template, {
mdContents: '<h1>Documentation</h1>',
comments: [],
structure: organizedByClass,
className: 'Index',
files: allFileLinks,
basePath: _opts.basePath,
filenameOut: 'index.html'
});
grunt.file.write(path.join(dest, 'index.html'), html);
}
done();
});
});
};
|
Move comments that refer to other classes of type event onto that other class.
|
tasks/jsdoxy.js
|
Move comments that refer to other classes of type event onto that other class.
|
<ide><path>asks/jsdoxy.js
<ide>
<ide>
<ide> // comments.forEach, really
<del> output.forEach(function(comment) {
<del>
<add> output.forEach(function (comment) {
<add> var thisCommentGoesSomewhereElse = null;
<add>
<add> function moveComment() {
<add> grunt.log.ok(
<add> 'Moving "event" comment from',
<add> lastClassnameWas, 'to',
<add> comment.ctx.name
<add> );
<add> if (!organizedByClass[thisCommentGoesSomewhereElse]) {
<add> organizedByClass[thisCommentGoesSomewhereElse] = [];
<add> }
<add> organizedByClass[thisCommentGoesSomewhereElse].push(comment);
<add> return;
<add> }
<add>
<ide> //
<ide> // Important:
<ide> // the `@class SomeClass` comment should always be in the first comment.
<ide> //
<ide>
<del>
<del> // organize the comments by @class
<del>
<del> comment.tags.forEach(function(tag) {
<del>
<del> if (tag.type == "class") {
<add> //
<add> // Organize the comments by @class.
<add> //
<add> // Unless it's an event that is documented on a different class.
<add> // Then move it to the right class.
<add>
<add> if (comment.ctx.type && comment.ctx.name) {
<add> if (comment.ctx.type === 'event' && !~comment.ctx.name.indexOf(lastClassnameWas) ) {
<add> thisCommentGoesSomewhereElse = comment.ctx.name.split('#')[0];
<add> moveComment();
<add> }
<add> }
<add> comment.tags.forEach(function (tag) {
<add>
<add> // Start a new class here
<add> if (tag.type === 'class') {
<ide> if (comment.isPrivate && !_opts.outputPrivate) {
<ide> // do not include the private comments unless specified
<ide> } else {
<ide> comment.ctx.name = lastClassnameWas;
<ide> }
<ide> }
<del>
<del> });
<del>
<add> if (tag.type === 'event' && tag.string && !~tag.string.indexOf(lastClassnameWas) ) {
<add> thisCommentGoesSomewhereElse = tag.string.split('#')[0];
<add> }
<add> });
<add> if (thisCommentGoesSomewhereElse) return moveComment();
<ide> if (!lastClassnameWas) return;
<ide>
<ide> organizedByClass[lastClassnameWas].push(comment);
|
|
Java
|
artistic-2.0
|
223ad99eeb28806d51f7bb9daf8d56b106090f3d
| 0 |
friedlwo/AppWoksUtils,friedlwo/AppWoksUtils
|
/**
* Copyright (c) 2009 - 2010 AppWork UG(haftungsbeschränkt) <[email protected]>
*
* This file is part of org.appwork.utils.singleapp
*
* This software is licensed under the Artistic License 2.0,
* see the LICENSE file or http://www.opensource.org/licenses/artistic-license-2.0.php
* for details
*/
package org.appwork.utils.singleapp;
/**
* @author daniel
*
*/
public interface InstanceMessageListener {
public void parseMessage(String[] message);
/**
* @param args
*/
}
|
src/org/appwork/utils/singleapp/InstanceMessageListener.java
|
/**
* Copyright (c) 2009 - 2010 AppWork UG(haftungsbeschränkt) <[email protected]>
*
* This file is part of org.appwork.utils.singleapp
*
* This software is licensed under the Artistic License 2.0,
* see the LICENSE file or http://www.opensource.org/licenses/artistic-license-2.0.php
* for details
*/
package org.appwork.utils.singleapp;
/**
* @author daniel
*
*/
public interface InstanceMessageListener {
public void parseMessage(String[] message);
}
|
Added new startup parameter Handling
|
src/org/appwork/utils/singleapp/InstanceMessageListener.java
|
Added new startup parameter Handling
|
<ide><path>rc/org/appwork/utils/singleapp/InstanceMessageListener.java
<ide> public interface InstanceMessageListener {
<ide>
<ide> public void parseMessage(String[] message);
<add>
<add> /**
<add> * @param args
<add> */
<add>
<ide> }
|
|
Java
|
bsd-3-clause
|
87ae73eb3d1e594bb81f9d4739a2b68415bb775c
| 0 |
ojacobson/dryad-repo,ojacobson/dryad-repo,rnathanday/dryad-repo,rnathanday/dryad-repo,rnathanday/dryad-repo,rnathanday/dryad-repo,rnathanday/dryad-repo,mdiggory/dryad-repo,ojacobson/dryad-repo,jimallman/dryad-repo,rnathanday/dryad-repo,jimallman/dryad-repo,mdiggory/dryad-repo,jimallman/dryad-repo,jimallman/dryad-repo,ojacobson/dryad-repo,mdiggory/dryad-repo,jamie-dryad/dryad-repo,jamie-dryad/dryad-repo,jamie-dryad/dryad-repo,jamie-dryad/dryad-repo,jamie-dryad/dryad-repo,mdiggory/dryad-repo,ojacobson/dryad-repo,jimallman/dryad-repo,mdiggory/dryad-repo,jimallman/dryad-repo,ojacobson/dryad-repo
|
package org.dspace.app.mediafilter;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Map;
import java.util.HashMap;
import java.util.StringTokenizer;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.PosixParser;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context;
import org.dspace.content.Bitstream;
import org.dspace.content.BitstreamFormat;
import org.dspace.content.Bundle;
import org.dspace.content.Item;
import org.dspace.content.ItemIterator;
import org.dspace.search.DSIndexer;
/**
* MediaFilterManager is the class that invokes the media filters over the
* repository's content. a few command line flags affect the operation of the
* MFM: -v verbose outputs all extracted text to SDTDOUT -f force forces all
* bitstreams to be processed, even if they have been before -n noindex does not
* recreate index after processing bitstreams
*
*/
public class MediaFilterManager
{
private static Map filterNames = new HashMap();
private static Map filterCache = new HashMap();
public static boolean createIndex = true; // default to creating index
public static boolean isVerbose = false; // default to not verbose
public static boolean isForce = false; // default to not forced
public static void main(String[] argv) throws Exception
{
// set headless for non-gui workstations
System.setProperty("java.awt.headless", "true");
// create an options object and populate it
CommandLineParser parser = new PosixParser();
Options options = new Options();
options.addOption("v", "verbose", false,
"print all extracted text and other details to STDOUT");
options.addOption("f", "force", false,
"force all bitstreams to be processed");
options.addOption("n", "noindex", false,
"do NOT re-create search index after filtering bitstreams");
options.addOption("h", "help", false, "help");
CommandLine line = parser.parse(options, argv);
if (line.hasOption('h'))
{
HelpFormatter myhelp = new HelpFormatter();
myhelp.printHelp("MediaFilter\n", options);
System.exit(0);
}
if (line.hasOption('v'))
{
isVerbose = true;
}
if (line.hasOption('n'))
{
createIndex = false;
}
if (line.hasOption('f'))
{
isForce = true;
}
// get path to config file
String myPath = ConfigurationManager.getProperty("dspace.dir")
+ File.separator + "config" + File.separator + "mediafilter.cfg";
// format name, classname
System.out.println("Using configuration in " + myPath);
Context c = null;
try
{
c = new Context();
// have to be super-user to do the filtering
c.setIgnoreAuthorization(true);
// read in the mediafilter.cfg file, store in HashMap
BufferedReader is = new BufferedReader(new FileReader(myPath));
String myLine = null;
while ((myLine = is.readLine()) != null)
{
// skip any lines beginning with #
if (myLine.indexOf("#") == 0) continue;
// no comment, so try and parse line
StringTokenizer st = new StringTokenizer(myLine);
// has to have at least 2 tokens
if (st.countTokens() >= 2)
{
String[] tokens = new String[st.countTokens()];
// grab all tokens and stuff in array
for (int i = 0; i < tokens.length; i++)
{
tokens[i] = st.nextToken();
}
// class is the last token
String myClass = tokens[tokens.length - 1];
String myFormat = tokens[0];
// everything else is the format
for (int i = 1; i < (tokens.length - 1); i++)
{
myFormat = myFormat + " " + tokens[i];
}
System.out.println("Format: '" + myFormat
+ "' Filtering Class: '" + myClass + "'");
// now convert format name to a format ID (int) for the hash key
int formatID = BitstreamFormat.findByShortDescription(c,
myFormat).getID();
filterNames.put(new Integer(formatID), myClass);
}
}
is.close();
// now apply the filters
applyFiltersAllItems(c);
// create search index?
if (createIndex)
{
System.out.println("Creating search index:");
DSIndexer.createIndex(c);
}
c.complete();
c = null;
}
finally
{
if (c != null) c.abort();
}
}
public static void applyFiltersAllItems(Context c) throws Exception
{
ItemIterator i = Item.findAll(c);
while (i.hasNext())
{
Item myItem = i.next();
filterItem(c, myItem);
}
}
/**
* iterate through the item's bitstreams in the ORIGINAL bundle, applying
* filters if possible
*/
public static void filterItem(Context c, Item myItem) throws Exception
{
// get 'original' bundles
Bundle[] myBundles = myItem.getBundles();
for (int i = 0; i < myBundles.length; i++)
{
// could have multiple 'ORIGINAL' bundles (hmm, probably not)
if (myBundles[i].getName().equals("ORIGINAL"))
{
// now look at all of the bitstreams
Bitstream[] myBitstreams = myBundles[i].getBitstreams();
for (int k = 0; k < myBitstreams.length; k++)
{
filterBitstream(c, myItem, myBitstreams[k]);
}
}
}
}
/**
* Attempt to filter a bitstream
*
* An exception will be thrown if the media filter class cannot be
* instantiated, exceptions from filtering will be logged to STDOUT and
* swallowed.
*/
public static void filterBitstream(Context c, Item myItem,
Bitstream myBitstream) throws Exception
{
// do we have a filter for that format?
Integer formatID = new Integer(myBitstream.getFormat().getID());
if (filterNames.containsKey(formatID))
{
// now, have we instantiated the class already?
if (!filterCache.containsKey(formatID))
{
// given a class name, load the class
Class f = Class.forName((String) filterNames.get(formatID));
MediaFilter myFilter = (MediaFilter) f.newInstance();
filterCache.put(formatID, myFilter);
}
// now get the filter and use it
MediaFilter myFilter = (MediaFilter) filterCache.get(formatID);
try
{
// only update item if bitstream not skipped
if (myFilter.processBitstream(c, myItem, myBitstream))
{
myItem.update(); // Make sure new bitstream has a sequence number
}
}
catch (Exception e)
{
System.out.println("ERROR filtering, skipping bitstream #"
+ myBitstream.getID() + " " + e);
e.printStackTrace();
}
}
}
}
|
dspace/src/org/dspace/app/mediafilter/MediaFilterManager.java
|
package org.dspace.app.mediafilter;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Map;
import java.util.HashMap;
import java.util.StringTokenizer;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.PosixParser;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context;
import org.dspace.content.Bitstream;
import org.dspace.content.BitstreamFormat;
import org.dspace.content.Bundle;
import org.dspace.content.Item;
import org.dspace.content.ItemIterator;
import org.dspace.search.DSIndexer;
/**
* MediaFilterManager is the class that invokes the media filters over the
* repository's content. a few command line flags affect the operation of the
* MFM: -v verbose outputs all extracted text to SDTDOUT -f force forces all
* bitstreams to be processed, even if they have been before -n noindex does not
* recreate index after processing bitstreams
*
*/
public class MediaFilterManager
{
private static Map filterNames = new HashMap();
private static Map filterCache = new HashMap();
public static boolean createIndex = true; // default to creating index
public static boolean isVerbose = false; // default to not verbose
public static boolean isForce = false; // default to not forced
public static void main(String[] argv) throws Exception
{
// set headless for non-gui workstations
System.setProperty("java.awt.headless", "true");
// create an options object and populate it
CommandLineParser parser = new PosixParser();
Options options = new Options();
options.addOption("v", "verbose", false,
"print all extracted text and other details to STDOUT");
options.addOption("f", "force", false,
"force all bitstreams to be processed");
options.addOption("n", "noindex", false,
"do NOT re-create search index after filtering bitstreams");
options.addOption("h", "help", false, "help");
CommandLine line = parser.parse(options, argv);
if (line.hasOption('h'))
{
HelpFormatter myhelp = new HelpFormatter();
myhelp.printHelp("MediaFilter\n", options);
System.exit(0);
}
if (line.hasOption('v'))
{
isVerbose = true;
}
if (line.hasOption('n'))
{
createIndex = false;
}
if (line.hasOption('f'))
{
isForce = true;
}
// get path to config file
String myPath = ConfigurationManager.getProperty("dspace.dir")
+ File.separator + "config" + File.separator + "mediafilter.cfg";
// format name, classname
System.out.println("Using configuration in " + myPath);
Context c = null;
try
{
c = new Context();
// have to be super-user to do the filtering
c.setIgnoreAuthorization(true);
// read in the mediafilter.cfg file, store in HashMap
BufferedReader is = new BufferedReader(new FileReader(myPath));
String myLine = null;
while ((myLine = is.readLine()) != null)
{
// skip any lines beginning with #
if (myLine.indexOf("#") == 0) continue;
// no comment, so try and parse line
StringTokenizer st = new StringTokenizer(myLine);
// has to have at least 2 tokens
if (st.countTokens() >= 2)
{
String[] tokens = new String[st.countTokens()];
// grab all tokens and stuff in array
for (int i = 0; i < tokens.length; i++)
{
tokens[i] = st.nextToken();
}
// class is the last token
String myClass = tokens[tokens.length - 1];
String myFormat = tokens[0];
// everything else is the format
for (int i = 1; i < (tokens.length - 1); i++)
{
myFormat = myFormat + " " + tokens[i];
}
System.out.println("Format: '" + myFormat
+ "' Filtering Class: '" + myClass + "'");
// now convert format name to a format ID (int) for the hash key
int formatID = BitstreamFormat.findByShortDescription(c,
myFormat).getID();
filterNames.put(new Integer(formatID), myClass);
}
}
is.close();
// now apply the filters
applyFiltersAllItems(c);
// create search index?
if (createIndex)
{
System.out.println("Creating search index:");
DSIndexer.createIndex(c);
}
c.complete();
c = null;
}
finally
{
if (c != null) c.abort();
}
}
public static void applyFiltersAllItems(Context c) throws Exception
{
ItemIterator i = Item.findAll(c);
while (i.hasNext())
{
Item myItem = i.next();
filterItem(c, myItem);
}
}
/**
* iterate through the item's bitstreams in the ORIGINAL bundle, applying
* filters if possible
*/
public static void filterItem(Context c, Item myItem) throws Exception
{
// get 'original' bundles
Bundle[] myBundles = myItem.getBundles();
for (int i = 0; i < myBundles.length; i++)
{
// could have multiple 'ORIGINAL' bundles (hmm, probably not)
if (myBundles[i].getName().equals("ORIGINAL"))
{
// now look at all of the bitstreams
Bitstream[] myBitstreams = myBundles[i].getBitstreams();
for (int k = 0; k < myBitstreams.length; k++)
{
filterBitstream(c, myItem, myBitstreams[k]);
}
}
}
}
/**
* Attempt to filter a bitstream
*
* An exception will be thrown if the media filter class cannot be
* instantiated, exceptions from filtering will be logged to STDOUT and
* swallowed.
*/
public static void filterBitstream(Context c, Item myItem,
Bitstream myBitstream) throws Exception
{
// do we have a filter for that format?
Integer formatID = new Integer(myBitstream.getFormat().getID());
if (filterNames.containsKey(formatID))
{
// now, have we instantiated the class already?
if (!filterCache.containsKey(formatID))
{
// given a class name, load the class
Class f = Class.forName((String) filterNames.get(formatID));
MediaFilter myFilter = (MediaFilter) f.newInstance();
filterCache.put(formatID, myFilter);
}
// now get the filter and use it
MediaFilter myFilter = (MediaFilter) filterCache.get(formatID);
try
{
myFilter.processBitstream(c, myItem, myBitstream);
myItem.update(); // Make sure new bitstream has a sequence number
}
catch (Exception e)
{
System.out.println("ERROR filtering, skipping bitstream #"
+ myBitstream.getID() + " " + e);
e.printStackTrace();
}
}
}
}
|
Fix for SF bug ID# 1015296
Only invokes item.update() if item has not been skipped - i.e.
if the MediaFilter has run against it to create new bitstream.
git-svn-id: 39c64a9546defcc59b5f71fe8fe20b2d01c24c1f@1037 9c30dcfa-912a-0410-8fc2-9e0234be79fd
|
dspace/src/org/dspace/app/mediafilter/MediaFilterManager.java
|
Fix for SF bug ID# 1015296 Only invokes item.update() if item has not been skipped - i.e. if the MediaFilter has run against it to create new bitstream.
|
<ide><path>space/src/org/dspace/app/mediafilter/MediaFilterManager.java
<ide>
<ide> try
<ide> {
<del> myFilter.processBitstream(c, myItem, myBitstream);
<del> myItem.update(); // Make sure new bitstream has a sequence number
<add> // only update item if bitstream not skipped
<add> if (myFilter.processBitstream(c, myItem, myBitstream))
<add> {
<add> myItem.update(); // Make sure new bitstream has a sequence number
<add> }
<ide> }
<ide> catch (Exception e)
<ide> {
|
|
JavaScript
|
mit
|
cd1d02d443c24eda9336625107ac6fc6c854824f
| 0 |
wadecon/wadecon,wadecon/wadecon
|
/// <reference path="typings/node/node.d.ts"/>
var express = require("express");
var app = express();
// fucking dependencies
var server = require('http').Server(app);
var io = require('socket.io')(server);
var bodyParser = require("body-parser");
var cookieParser = require("cookie-parser");
var session = require('express-session');
var path = require('path');
var async = require('async');
var md = require("node-markdown").Markdown;
var fs = require("fs");
var request = require("request");
require('colors'); // for fantastic debug
// setting app -> too dizzy to fuck with
app.use(cookieParser());
app.use(session({ secret: "secret", resave: false, saveUninitialized: false}));
var set = require('./setting.json');
var options = process.argv;
for( var num in options){
if(options[num] == "--port" || options[num] == "-p"){
set.port = options[Number(num)+1];
}
if(options[num] == "--quiet" || options[num] == "-q"){
console.log = function(){};
}
}
app.set("view engine", "ejs");
app.set("views", __dirname+"/app/views");
app.use( express.static( __dirname + "/public" ));
app.use(bodyParser.urlencoded({ extended: false }));
// homemade modules
var dbnotices = require("./dbmodules/dbnotices.js");
var dbusers = require("./dbmodules/dbusers.js");
var dbdislikes = require("./dbmodules/dbdislikes.js");
var dbjoins = require("./dbmodules/dbjoins.js");
var dbworks = require("./dbmodules/dbworks.js");
var dbbadges = require("./dbmodules/dbbadges.js");
var dbbadgemaps = require("./dbmodules/dbbadgemaps.js");
var dblogs = require("./dbmodules/dblogs.js");
var systemMod = require("./systemMod.js");
var redisMod = require("./redisMod.js");
var socketMod = require("./socketMod.js");
socketMod.setIoAsyncRedis(io, async, redisMod);
socketMod.setDBs(dbnotices, dbusers, dbdislikes, dbjoins, dbworks, dbbadgemaps, dbbadgemaps, dblogs);
var auth = require("./auth.js");
auth.init(app);
var passport = auth.getPassport();
require('./database.js')();
// fucking routing
app.get('/auth/fb', passport.authenticate('facebook'));
app.get('/auth/fb/callback',
passport.authenticate('facebook', {
successRedirect: '/join',
failureRedirect: '/loginFail'
})
);
app.get('/login', function(req, res) {
res.render("login.ejs", {
isIntro: true, //메인페이지에서 헤더에 로그인버튼을 보여주지 않는데 사용
host: set.host,
user: req.user,
port: ((set.main)?'':':'+set.port),
isMember: false
});
});
app.get('/logout', function(req, res){
req.logout();
res.redirect('/');
});
app.route("/")
.get(auth.checkAuthRegi, function(req, res) {
systemMod.checkBrowser(req.headers['user-agent'],function(browserName){
// && browserVersion <= 9
if (browserName == 'IE') {
res.write("<script>window.open('http://www.opera.com/ko/computer');</script>");
res.write("<script>window.open('https://www.mozilla.org/ko/firefox/new/');</script>");
res.end("<script>location.href='https://www.google.com/chrome/browser/desktop/index.html';</script>");
}
});
async.parallel([
function(callback) {
Works.findAll({
order: ['dislikes', 'DESC']
}).then(function(works, err) {
if(err) callback(err, null);
else {
callback(null, works);
}
});
},
function(callback) {
Dislikes.findAll().then(function(dislikes, err){
if(err) callback(err, null);
else{
callback(null, dislikes);
}
});
},
function(callback) {
Joins.findAll().then(function(joins, err){
if(err) callback(err, null);
else{
callback(null, joins);
}
});
}
], function(err, results) {
if(err) console.error(err);
else{
if(req.user != null) {
redisMod.setSession(req.user.id, set.expire, req.user, function() { // 널을 반환하므로 받을 필요가 없다
console.log("세션 설정!!".cyan);
});
}
var works = results[0];
var dislikes = results[1];
var joins = results[2];
dbdislikes.getWorksDislikesNum(works, function(arrWorksDislikesNum) {
res.render("frontpage.ejs", {
works: works,
isMember: true,
user: req.user,
dislikes: dislikes,
numDislikes: arrWorksDislikesNum,
joins: joins,
host: set.host,
port: ((set.main)?'':':'+set.port)
});
});
}
});
});
app.route("/makework")
.get(auth.checkAuthRegi, function(req, res){
res.render('makework.ejs', {
host: set.host,
isMember: true,
port: ((set.main)?'':':'+set.port),
userId: req.user.id,
user: req.user,
pageTitle: '공작 모의'
});
})
.post(auth.checkAuthRegi, function(req, res){
try {
async.waterfall([
function(callback) {
dbworks.createWork( req.body.name, req.body.desc, function(work, err) {
if(err) throw err;
else callback(null, work);
});
},
function(work, callback) {
var data = {
workId: work.id,
userId: req.user.id
};
dbjoins.joinOwner(null, data, function(join, err) {
if(err) throw err;
else callback(null, work);
})
},
function(work, callback) {
fs.mkdir("./public/workpage/" + work.id, function(err) {
if(err) callback(err);
else {
async.parallel([
function(cb) {
fs.writeFileSync("./public/workpage/" + work.id + "/front.html", md(req.body.readme));
cb(null);
},
function(cb) {
fs.writeFileSync("./public/workpage/" + work.id + "/needs.html", md(req.body.needs));
cb(null);
},
function(cb) {
fs.writeFileSync("./public/workpage/" + work.id + "/front.md", req.body.readme);
cb(null);
},
function(cb) {
fs.writeFileSync("./public/workpage/" + work.id + "/needs.md", req.body.needs);
cb(null);
},
], function(err, results) {
//여긴 에러를 받을 일이 없다. fs에서 오류나면 그냥 catch됨.
callback(null, results, work);
});
}
})
}
], function(err, result, work){
if(err) throw err;
else res.send({code: 201, url: '/work/'+encodeURIComponent(work.name)});
});
} catch(err) {
console.error(err);
res.status(500).end();
}
});
app.route("/join")
.get(auth.checkAuth, function(req, res) {
dbusers.searchByFbid(req.user.fbId, function(user, err) {
if(err) console.error(err);
else if(user) {
if(user.nickname == null)
res.render('join.ejs', {
pageTitle: '가입',
user: req.user,
isMember: false, //예외사항: 항시 거짓
host: set.host,
port: ((set.main)?'':':'+set.port),
isIntro: true
});
else res.redirect('/'); //닉네임 이미 등록됨.
} else {
res.redirect('/'); //잘못된 접근: 세션은 인증되어 있는데 해당하는 정보가 DB에 없음
}
})
})
.post(auth.checkAuth, function(req, res) {
if(req.body.nickname) {
dbusers.searchByNickname(req.body.nickname, function(user, err) {
if(err) console.error(err);
else if(!user) { // 가능한 닉네임
dbusers.searchByFbid(req.user.fbId, function(user, err) {
if(err) console.error(err);
else if(!user){ // 그 세션의 uid에 해당하는 게 등록 안되어있음 (이상한 케이스)
res.redirect('/login');
} else {
// 여기서 검사는 다 끝남
console.log("유저 생성 :".cyan, user.name);
res.send("201").end();
dbusers.changeNickname(user, req.body.nickname, function(user, err) {
if(err) {
console.error(err);
res.send("500").end();
}
else {
dbusers.cacheUserImage(user.picture, user.id, request, fs, function() {
fs.mkdir('./public/userbios/' + user.id, function(err) {
if(err) console.error(err);
else console.log('이미지 저장')
});
});
}
});
}
});
} else {
// 이미 존재하는 닉네임
res.send("409").end();
}
})
} else res.send("400").end();
});
app.route("/work/:workName")
.get(auth.inspectRegi, function(req, res) {
try {
async.parallel([
function(callback) {
if(req.regiState) {
dbworks.searchByName(req.params.workName, function(work, err) {
if(err) callback(err);
else {
dbjoins.searchById(req.user.id, work.id, function(join, err) {
if(err) throw callback(err);
else if(join && join.userId === req.user.id) callback(null, true);
else callback(null, false);
});
}
});
} else callback(null, false);
},
function(callback) {
dbworks.getDislikeJoinedUserByName(req.params.workName, dbjoins, dbdislikes, function(err, results) {
if(err) callback(err);
else callback(err, results);
});
}
], function(err, results) {
if(err) throw err;
else {
res.render("workpage.ejs", {
work: results[1][2],
numDislikes: results[1][1].length,
members: results[1][0],
isMember: req.regiState, // 조합원
isJoined: results[0], // 공작 참여
host: set.host,
port: ((set.main)?'':':'+set.port),
user: (req.regiState)?req.user:null
});
}
});
} catch(err) {
console.error(err);
res.send(500).end();
}
})
.post(auth.checkAuthRegi, function(req, res){
try {
var inputData = {};
async.waterfall([
function(callback) {
dbworks.searchByName(req.params.workName, function(work, err) {
if(err) throw err;
else if(work) callback(null, work);
else throw 'No work';
});
},
function(work, callback) {
async.parallel([
function(cb) {
if(req.body.readme) {
fs.writeFileSync("./public/workpage/" + work.id + "/front.html", md(req.body.readme));
inputData.frontboard = "./public/workpage/" + work.id + "/front.html";
}
cb(null);
},
function(cb) {
if(req.body.needs) {
fs.writeFileSync("./public/workpage/" + work.id + "/needs.html", md(req.body.needs));
inputData.needs = "./public/workpage/" + work.id + "/needs.html";
}
cb(null);
},
function(cb) {
if(req.body.readme)
fs.writeFileSync("./public/workpage/" + work.id + "/front.md", req.body.readme);
cb(null);
},
function(cb) {
if(req.body.needs)
fs.writeFileSync("./public/workpage/" + work.id + "/needs.md", req.body.needs);
cb(null);
},
], function(err, results) {
//여긴 에러를 받을 일이 없다. fs에서 오류나면 그냥 catch됨.
callback(null, work);
});
},
function(work, callback) {
dbworks.editWorkInfo(work.id, inputData, function(work, err) {
if(err) throw err;
else callback(null, work);
});
}
], function(err, work){
if(err) throw err;
else {
console.log(work.name + " 수정 성공".green);
res.send('200');
}
});
} catch(err) {
console.error(err);
res.status(500).end();
}
});
app.route("/user/:userNick")
.get(auth.inspectRegi, function(req, res){
dbusers.searchByNickname(req.params.userNick, function(user, err){
if(err) console.error(err);
else if(!user) {
res.status(404).end();
}
else{
res.render('userpage.ejs', {
host: set.host,
port: ((set.main)?'':':'+set.port),
pageTitle: '얘의 정보',
isMember: req.regiState,
user: req.user,
object: user
});
}
});
})
.post(auth.checkAuthRegi, function(req, res){
try {
async.parallel([
function(callback) {
fs.writeFileSync('./public/userbios/' + req.user.id + '/bio.html', md(req.body.bio));
callback(null);
},
function(callback) {
fs.writeFileSync('./public/userbios/' + req.user.id + '/bio.md', req.body.bio);
callback(null);
}
], function(err, results) {
if(err) throw err;
else {
dbusers.editInfoByNickname(req.user.nickname, {
bio: '.public/userbios/' + req.user.nickname + '/bio.html'
}, function(user, err) {
if(err) throw err;
else res.send("200");
});
}
});
} catch(err) {
console.error(err);
res.send("500");
}
});
// handle 404
app.use(function(req, res) {
res.status(404).sendFile( __dirname+"/public/status/404NF.html");
});
// handle 500
// app.use(function(error, req, res, next) {
// res.status(500).send('500: Internal Server Error\n'+error);
// });
server.listen(set.port || 8080);
console.log((set.host+":"+(set.port || 8080)).cyan+"에서 서버 시작".green);
dbbadges.createBadge("반동놈의자식", "이놈은빨갱입니다", 10, function(a, err) {
});
|
server.js
|
/// <reference path="typings/node/node.d.ts"/>
var express = require("express");
var app = express();
// fucking dependencies
var server = require('http').Server(app);
var io = require('socket.io')(server);
var bodyParser = require("body-parser");
var cookieParser = require("cookie-parser");
var session = require('express-session');
var path = require('path');
var async = require('async');
var md = require("node-markdown").Markdown;
var fs = require("fs");
var request = require("request");
require('colors'); // for fantastic debug
// setting app -> too dizzy to fuck with
app.use(cookieParser());
app.use(session({ secret: "secret", resave: false, saveUninitialized: false}));
var set = require('./setting.json');
var options = process.argv;
for( var num in options){
if(options[num] == "--port" || options[num] == "-p"){
set.port = options[Number(num)+1];
}
if(options[num] == "--quiet" || options[num] == "-q"){
console.log = function(){};
}
}
app.set("view engine", "ejs");
app.set("views", __dirname+"/app/views");
app.use( express.static( __dirname + "/public" ));
app.use(bodyParser.urlencoded({ extended: false }));
// homemade modules
var dbnotices = require("./dbmodules/dbnotices.js");
var dbusers = require("./dbmodules/dbusers.js");
var dbdislikes = require("./dbmodules/dbdislikes.js");
var dbjoins = require("./dbmodules/dbjoins.js");
var dbworks = require("./dbmodules/dbworks.js");
var dbbadges = require("./dbmodules/dbbadges.js");
var dbbadgemaps = require("./dbmodules/dbbadgemaps.js");
var dblogs = require("./dbmodules/dblogs.js");
var systemMod = require("./systemMod.js");
var redisMod = require("./redisMod.js");
var socketMod = require("./socketMod.js");
socketMod.setIoAsyncRedis(io, async, redisMod);
socketMod.setDBs(dbnotices, dbusers, dbdislikes, dbjoins, dbworks, dbbadgemaps, dbbadgemaps, dblogs);
var auth = require("./auth.js");
auth.init(app);
var passport = auth.getPassport();
require('./database.js')();
// fucking routing
app.get('/auth/fb', passport.authenticate('facebook'));
app.get('/auth/fb/callback',
passport.authenticate('facebook', {
successRedirect: '/join',
failureRedirect: '/loginFail'
})
);
app.get('/login', function(req, res) {
res.render("login.ejs", {
isIntro: true, //메인페이지에서 헤더에 로그인버튼을 보여주지 않는데 사용
host: set.host,
user: req.user,
port: ((set.main)?'':':'+set.port),
isMember: false
});
});
app.get('/logout', function(req, res){
req.logout();
res.redirect('/');
});
app.route("/")
.get(auth.checkAuthRegi, function(req, res) {
systemMod.checkBrowser(req.headers['user-agent'],function(browserName){
// && browserVersion <= 9
if (browserName == 'IE') {
res.write("<script>window.open('http://www.opera.com/ko/computer');</script>");
res.write("<script>window.open('https://www.mozilla.org/ko/firefox/new/');</script>");
res.end("<script>location.href='https://www.google.com/chrome/browser/desktop/index.html';</script>");
}
});
async.parallel([
function(callback) {
Works.findAll({
order: ['dislikes', 'DESC']
}).then(function(works, err) {
if(err) callback(err, null);
else {
callback(null, works);
}
});
},
function(callback) {
Dislikes.findAll().then(function(dislikes, err){
if(err) callback(err, null);
else{
callback(null, dislikes);
}
});
},
function(callback) {
Joins.findAll().then(function(joins, err){
if(err) callback(err, null);
else{
callback(null, joins);
}
});
}
], function(err, results) {
if(err) console.error(err);
else{
if(req.user != null) {
redisMod.setSession(req.user.id, set.expire, req.user, function() { // 널을 반환하므로 받을 필요가 없다
console.log("세션 설정!!".cyan);
});
}
var works = results[0];
var dislikes = results[1];
var joins = results[2];
dbdislikes.getWorksDislikesNum(works, function(arrWorksDislikesNum) {
res.render("frontpage.ejs", {
works: works,
isMember: true,
user: req.user,
dislikes: dislikes,
numDislikes: arrWorksDislikesNum,
joins: joins,
host: set.host,
port: ((set.main)?'':':'+set.port)
});
});
}
});
});
app.route("/makework")
.get(auth.checkAuthRegi, function(req, res){
res.render('makework.ejs', {
host: set.host,
isMember: true,
port: ((set.main)?'':':'+set.port),
userId: req.user.id,
user: req.user,
pageTitle: '공작 모의'
});
})
.post(auth.checkAuthRegi, function(req, res){
try {
async.waterfall([
function(callback) {
dbworks.createWork( req.body.name, req.body.desc, function(work, err) {
if(err) throw err;
else callback(null, work);
});
},
function(work, callback) {
var data = {
workId: work.id,
userId: req.user.id
};
dbjoins.joinOwner(null, data, function(join, err) {
if(err) throw err;
else callback(null, work);
})
},
function(work, callback) {
fs.mkdir("./public/workpage/" + work.id, function(err) {
if(err) callback(err);
else {
async.parallel([
function(cb) {
fs.writeFileSync("./public/workpage/" + work.id + "/front.html", md(req.body.readme));
cb(null);
},
function(cb) {
fs.writeFileSync("./public/workpage/" + work.id + "/needs.html", md(req.body.needs));
cb(null);
},
function(cb) {
fs.writeFileSync("./public/workpage/" + work.id + "/front.md", req.body.readme);
cb(null);
},
function(cb) {
fs.writeFileSync("./public/workpage/" + work.id + "/needs.md", req.body.needs);
cb(null);
},
], function(err, results) {
//여긴 에러를 받을 일이 없다. fs에서 오류나면 그냥 catch됨.
callback(null, results, work);
});
}
})
}
], function(err, result, work){
if(err) throw err;
else res.send({code: 201, url: '/work/'+encodeURIComponent(work.name)});
});
} catch(err) {
console.error(err);
res.status(500).end();
}
});
app.route("/join")
.get(auth.checkAuth, function(req, res) {
dbusers.searchByFbid(req.user.fbId, function(user, err) {
if(err) console.error(err);
else if(user) {
if(user.nickname == null)
res.render('join.ejs', {
pageTitle: '가입',
user: req.user,
isMember: false, //예외사항: 항시 거짓
host: set.host,
port: ((set.main)?'':':'+set.port),
isIntro: true
});
else res.redirect('/'); //닉네임 이미 등록됨.
} else {
res.redirect('/'); //잘못된 접근: 세션은 인증되어 있는데 해당하는 정보가 DB에 없음
}
})
})
.post(auth.checkAuth, function(req, res) {
if(req.body.nickname) {
dbusers.searchByNickname(req.body.nickname, function(user, err) {
if(err) console.error(err);
else if(!user) { // 가능한 닉네임
dbusers.searchByFbid(req.user.fbId, function(user, err) {
if(err) console.error(err);
else if(!user){ // 그 세션의 uid에 해당하는 게 등록 안되어있음 (이상한 케이스)
res.redirect('/');
} else {
dbusers.changeNickname(user, req.body.nickname, function(user, err) {
if(err) {
console.error(err);
res.send("500").end();
}
else {
dbusers.cacheUserImage(user.picture, user.id, request, fs, function() {
fs.mkdir('./public/userbios/' + user.id, function(err) {
if(err) console.error(err);
else {
/* 이미지저장한걸로업데이트 */
console.log("유저 생성 :".cyan, user.name);
res.send("201").end();
}
});
});
}
});
}
});
} else {
// 이미 존재하는 닉네임
res.send("409").end();
}
})
} else res.send("400").end();
});
app.route("/work/:workName")
.get(auth.inspectRegi, function(req, res) {
try {
async.parallel([
function(callback) {
if(req.regiState) {
dbworks.searchByName(req.params.workName, function(work, err) {
if(err) callback(err);
else {
dbjoins.searchById(req.user.id, work.id, function(join, err) {
if(err) throw callback(err);
else if(join && join.userId === req.user.id) callback(null, true);
else callback(null, false);
});
}
});
} else callback(null, false);
},
function(callback) {
dbworks.getDislikeJoinedUserByName(req.params.workName, dbjoins, dbdislikes, function(err, results) {
if(err) callback(err);
else callback(err, results);
});
}
], function(err, results) {
if(err) throw err;
else {
res.render("workpage.ejs", {
work: results[1][2],
numDislikes: results[1][1].length,
members: results[1][0],
isMember: req.regiState, // 조합원
isJoined: results[0], // 공작 참여
host: set.host,
port: ((set.main)?'':':'+set.port),
user: (req.regiState)?req.user:null
});
}
});
} catch(err) {
console.error(err);
res.send(500).end();
}
})
.post(auth.checkAuthRegi, function(req, res){
try {
var inputData = {};
async.waterfall([
function(callback) {
dbworks.searchByName(req.params.workName, function(work, err) {
if(err) throw err;
else if(work) callback(null, work);
else throw 'No work';
});
},
function(work, callback) {
async.parallel([
function(cb) {
if(req.body.readme) {
fs.writeFileSync("./public/workpage/" + work.id + "/front.html", md(req.body.readme));
inputData.frontboard = "./public/workpage/" + work.id + "/front.html";
}
cb(null);
},
function(cb) {
if(req.body.needs) {
fs.writeFileSync("./public/workpage/" + work.id + "/needs.html", md(req.body.needs));
inputData.needs = "./public/workpage/" + work.id + "/needs.html";
}
cb(null);
},
function(cb) {
if(req.body.readme)
fs.writeFileSync("./public/workpage/" + work.id + "/front.md", req.body.readme);
cb(null);
},
function(cb) {
if(req.body.needs)
fs.writeFileSync("./public/workpage/" + work.id + "/needs.md", req.body.needs);
cb(null);
},
], function(err, results) {
//여긴 에러를 받을 일이 없다. fs에서 오류나면 그냥 catch됨.
callback(null, work);
});
},
function(work, callback) {
dbworks.editWorkInfo(work.id, inputData, function(work, err) {
if(err) throw err;
else callback(null, work);
});
}
], function(err, work){
if(err) throw err;
else {
console.log(work.name + " 수정 성공".green);
res.send('200');
}
});
} catch(err) {
console.error(err);
res.status(500).end();
}
});
app.route("/user/:userNick")
.get(auth.inspectRegi, function(req, res){
dbusers.searchByNickname(req.params.userNick, function(user, err){
if(err) console.error(err);
else if(!user) {
res.status(404).end();
}
else{
res.render('userpage.ejs', {
host: set.host,
port: ((set.main)?'':':'+set.port),
pageTitle: '얘의 정보',
isMember: req.regiState,
user: req.user,
object: user
});
}
});
})
.post(auth.checkAuthRegi, function(req, res){
try {
async.parallel([
function(callback) {
fs.writeFileSync('./public/userbios/' + req.user.id + '/bio.html', md(req.body.bio));
callback(null);
},
function(callback) {
fs.writeFileSync('./public/userbios/' + req.user.id + '/bio.md', req.body.bio);
callback(null);
}
], function(err, results) {
if(err) throw err;
else {
dbusers.editInfoByNickname(req.user.nickname, {
bio: '.public/userbios/' + req.user.nickname + '/bio.html'
}, function(user, err) {
if(err) throw err;
else res.send("200");
});
}
});
} catch(err) {
console.error(err);
res.send("500");
}
});
// handle 404
app.use(function(req, res) {
res.status(404).sendFile( __dirname+"/public/status/404NF.html");
});
// handle 500
// app.use(function(error, req, res, next) {
// res.status(500).send('500: Internal Server Error\n'+error);
// });
server.listen(set.port || 8080);
console.log((set.host+":"+(set.port || 8080)).cyan+"에서 서버 시작".green);
dbbadges.createBadge("반동놈의자식", "이놈은빨갱입니다", 10, function(a, err) {
});
|
빠른 가입 응답
|
server.js
|
빠른 가입 응답
|
<ide><path>erver.js
<ide> dbusers.searchByFbid(req.user.fbId, function(user, err) {
<ide> if(err) console.error(err);
<ide> else if(!user){ // 그 세션의 uid에 해당하는 게 등록 안되어있음 (이상한 케이스)
<del> res.redirect('/');
<add> res.redirect('/login');
<ide> } else {
<add> // 여기서 검사는 다 끝남
<add> console.log("유저 생성 :".cyan, user.name);
<add> res.send("201").end();
<ide> dbusers.changeNickname(user, req.body.nickname, function(user, err) {
<ide> if(err) {
<ide> console.error(err);
<ide> dbusers.cacheUserImage(user.picture, user.id, request, fs, function() {
<ide> fs.mkdir('./public/userbios/' + user.id, function(err) {
<ide> if(err) console.error(err);
<del> else {
<del> /* 이미지저장한걸로업데이트 */
<del> console.log("유저 생성 :".cyan, user.name);
<del> res.send("201").end();
<del> }
<add> else console.log('이미지 저장')
<ide> });
<ide> });
<ide> }
|
|
Java
|
apache-2.0
|
5692a05c8930489bca8f685adaca50756c377d32
| 0 |
alipay/SoloPi,alipay/SoloPi,alipay/SoloPi
|
/*
* Copyright (C) 2015-present, Ant Financial Services Group
*
* 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.alipay.hulu.common.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
* Created by qiaoruikai on 2018/12/18 8:16 PM.
*/
public class DecompressUtil {
private static final String TAG = "DecompressUtil";
/**
* 解压到目标文件
* @param originFile 原始文件
* @param targetFolder 解压到的文件夹
* @return
*/
public static File decompressZip(File originFile, File targetFolder) {
if (!originFile.exists() || !originFile.canRead()) {
LogUtil.e(TAG, "压缩文件【%s】无法解析,不存在或者无法读取", originFile);
return null;
}
FileInputStream inputStream;
try {
inputStream = new FileInputStream(originFile);
} catch (FileNotFoundException e) {
LogUtil.e(TAG, "Catch java.io.FileNotFoundException: " + e.getMessage(), e);
return null;
}
String folderName = originFile.getName();
int pointPos;
if ((pointPos = folderName.indexOf('.')) > -1) {
folderName = folderName.substring(0, pointPos);
}
// 设置为子文件夹
targetFolder = new File(targetFolder, folderName);
if (!targetFolder.exists()) {
targetFolder.mkdirs();
}
String originCanonicalPath;
try {
originCanonicalPath = originFile.getCanonicalPath();
} catch (IOException e) {
LogUtil.e(TAG, "Get Canonical Path Failed, throw exception", e);
originCanonicalPath = originFile.getPath();
}
ZipInputStream zip = new ZipInputStream(inputStream);
ZipEntry zipEntry;
String szName;
try {
while ((zipEntry = zip.getNextEntry()) != null) {
szName = zipEntry.getName();
File f = new File(originFile, zipEntry.getName());
String canonicalPath = f.getCanonicalPath();
if (!canonicalPath.startsWith(originCanonicalPath)) {
LogUtil.e(TAG, "Zip Entry: " + szName + ", not belong to zip file " + canonicalPath);
// 忽略该zip压缩包
continue;
}
if (zipEntry.isDirectory()) {
//获取部件的文件夹名
szName = szName.substring(0, szName.length() - 1);
File folder = new File(targetFolder, szName);
if (!folder.exists()) {
folder.mkdirs();
}
} else {
File file = new File(targetFolder, szName);
if (!file.exists()){
LogUtil.d(TAG, "Create the file: %s", szName);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
file.createNewFile();
}
// 获取文件的输出流
FileOutputStream out = new FileOutputStream(file);
int len;
byte[] buffer = new byte[4096];
// 读取(字节)字节到缓冲区
while ((len = zip.read(buffer)) != -1) {
// 从缓冲区(0)位置写入(字节)字节
out.write(buffer, 0, len);
out.flush();
}
out.close();
}
LogUtil.d(TAG, "处理Entry=%s完毕", szName);
}
} catch (IOException e) {
LogUtil.e(TAG, "Catch java.io.IOException: " + e.getMessage(), e);
}
return targetFolder;
}
}
|
src/common/src/main/java/com/alipay/hulu/common/utils/DecompressUtil.java
|
/*
* Copyright (C) 2015-present, Ant Financial Services Group
*
* 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.alipay.hulu.common.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
* Created by qiaoruikai on 2018/12/18 8:16 PM.
*/
public class DecompressUtil {
private static final String TAG = "DecompressUtil";
/**
* 解压到目标文件
* @param originFile 原始文件
* @param targetFolder 解压到的文件夹
* @return
*/
public static File decompressZip(File originFile, File targetFolder) {
if (!originFile.exists() || !originFile.canRead()) {
LogUtil.e(TAG, "压缩文件【%s】无法解析,不存在或者无法读取", originFile);
return null;
}
FileInputStream inputStream;
try {
inputStream = new FileInputStream(originFile);
} catch (FileNotFoundException e) {
LogUtil.e(TAG, "Catch java.io.FileNotFoundException: " + e.getMessage(), e);
return null;
}
String folderName = originFile.getName();
int pointPos;
if ((pointPos = folderName.indexOf('.')) > -1) {
folderName = folderName.substring(0, pointPos);
}
// 设置为子文件夹
targetFolder = new File(targetFolder, folderName);
if (!targetFolder.exists()) {
targetFolder.mkdirs();
}
ZipInputStream zip = new ZipInputStream(inputStream);
ZipEntry zipEntry;
String szName;
try {
while ((zipEntry = zip.getNextEntry()) != null) {
szName = zipEntry.getName();
if (zipEntry.isDirectory()) {
//获取部件的文件夹名
szName = szName.substring(0, szName.length() - 1);
File folder = new File(targetFolder, szName);
if (!folder.exists()) {
folder.mkdirs();
}
} else {
File file = new File(targetFolder, szName);
if (!file.exists()){
LogUtil.d(TAG, "Create the file: %s", szName);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
file.createNewFile();
}
// 获取文件的输出流
FileOutputStream out = new FileOutputStream(file);
int len;
byte[] buffer = new byte[4096];
// 读取(字节)字节到缓冲区
while ((len = zip.read(buffer)) != -1) {
// 从缓冲区(0)位置写入(字节)字节
out.write(buffer, 0, len);
out.flush();
}
out.close();
}
LogUtil.d(TAG, "处理Entry=%s完毕", szName);
}
} catch (IOException e) {
LogUtil.e(TAG, "Catch java.io.IOException: " + e.getMessage(), e);
}
return targetFolder;
}
}
|
fix safety issue
|
src/common/src/main/java/com/alipay/hulu/common/utils/DecompressUtil.java
|
fix safety issue
|
<ide><path>rc/common/src/main/java/com/alipay/hulu/common/utils/DecompressUtil.java
<ide> targetFolder.mkdirs();
<ide> }
<ide>
<add> String originCanonicalPath;
<add> try {
<add> originCanonicalPath = originFile.getCanonicalPath();
<add> } catch (IOException e) {
<add> LogUtil.e(TAG, "Get Canonical Path Failed, throw exception", e);
<add> originCanonicalPath = originFile.getPath();
<add> }
<add>
<ide> ZipInputStream zip = new ZipInputStream(inputStream);
<ide> ZipEntry zipEntry;
<ide> String szName;
<ide> try {
<ide> while ((zipEntry = zip.getNextEntry()) != null) {
<ide> szName = zipEntry.getName();
<add>
<add>
<add> File f = new File(originFile, zipEntry.getName());
<add> String canonicalPath = f.getCanonicalPath();
<add> if (!canonicalPath.startsWith(originCanonicalPath)) {
<add> LogUtil.e(TAG, "Zip Entry: " + szName + ", not belong to zip file " + canonicalPath);
<add> // 忽略该zip压缩包
<add> continue;
<add> }
<add>
<ide> if (zipEntry.isDirectory()) {
<ide> //获取部件的文件夹名
<ide> szName = szName.substring(0, szName.length() - 1);
|
|
Java
|
apache-2.0
|
2c27fc0a9e12a786d216777df3e0353c29901fad
| 0 |
PerfCake/pc4idea
|
package org.perfcake.pc4idea.editor.gui;
import org.perfcake.model.Property;
import org.perfcake.model.Scenario;
import org.perfcake.pc4idea.editor.PerfCakeEditorGUI;
import org.perfcake.pc4idea.editor.components.ComponentEditor;
import org.perfcake.pc4idea.editor.components.PropertyComponent;
import org.perfcake.pc4idea.editor.wizard.PropertyEditor;
import org.perfcake.pc4idea.editor.wizard.SenderEditor;
import javax.swing.*;
import javax.swing.event.MouseInputAdapter;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: Stanislav Kaleta
* Date: 28.9.2014
*/
public class SenderPanel extends AbstractPanel {
private final String TITLE ="Sender Editor";
private Color senderColor = Color.getHSBColor(220/360f,0.5f,0.75f);
private SenderEditor senderEditor;
private Scenario.Sender sender;
private PerfCakeEditorGUI.ScenarioEvent scenarioEvent;
private JLabel labelSenderClass;
private PanelProperties panelProperties;
private int labelSenderClassWidth;
public SenderPanel(PerfCakeEditorGUI.ScenarioEvent scenarioEvent){
this.scenarioEvent = scenarioEvent;
labelSenderClassWidth = 0;
initComponents();
}
private void initComponents() {
labelSenderClass = new JLabel("---");
labelSenderClass.setFont(new Font(labelSenderClass.getFont().getName(), 0, 15));
labelSenderClass.setForeground(senderColor);
panelProperties = new PanelProperties();
SpringLayout layout = new SpringLayout();
this.setLayout(layout);
this.add(labelSenderClass);
this.add(panelProperties);
layout.putConstraint(SpringLayout.HORIZONTAL_CENTER, labelSenderClass,
0,
SpringLayout.HORIZONTAL_CENTER, this);
layout.putConstraint(SpringLayout.NORTH, labelSenderClass,
10,
SpringLayout.NORTH, this);
layout.putConstraint(SpringLayout.WEST, panelProperties,
10,
SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, panelProperties,8,SpringLayout.SOUTH, labelSenderClass);
this.addComponentListener( new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
e.getComponent().revalidate();
e.getComponent().repaint();
}
});
this.setTransferHandler(new TransferHandler(){
@Override
public boolean canImport(TransferHandler.TransferSupport support){
support.setDropAction(COPY);
return support.isDataFlavorSupported(DataFlavor.stringFlavor);
}
@Override
public boolean importData(TransferHandler.TransferSupport support){
if (!canImport(support)) {
return false;
}
Transferable t = support.getTransferable();
String transferredData = "";
try {
transferredData = (String)t.getTransferData(DataFlavor.stringFlavor);
} catch (UnsupportedFlavorException e) {
e.printStackTrace(); /*TODO log*/
} catch (IOException e) {
e.printStackTrace(); /*TODO log*/
}
if (transferredData.equals("Property")) {
PropertyEditor propertyEditor = new PropertyEditor();
ComponentEditor editor = new ComponentEditor("Property Editor", propertyEditor);
editor.show();
if (editor.getExitCode() == 0) {
sender.getProperty().add(propertyEditor.getProperty());
setComponent(sender);
scenarioEvent.saveSender();
}
}
return true;
}
});
}
@Override
protected Color getColor() {
return senderColor;
}
@Override
protected String getEditorTitle() {
return TITLE;
}
@Override
protected JPanel getEditorPanel() {
senderEditor = new SenderEditor();
senderEditor.setSender(sender);
return senderEditor;
}
@Override
protected void applyChanges() {
setComponent(senderEditor.getSender());
scenarioEvent.saveSender();
}
@Override
public void setComponent(Object component) {
sender = (Scenario.Sender) component;
labelSenderClass.setText(sender.getClazz());
FontMetrics fontMetrics = labelSenderClass.getFontMetrics(labelSenderClass.getFont());
labelSenderClassWidth = fontMetrics.stringWidth(labelSenderClass.getText());
panelProperties.setProperties(sender.getProperty());
this.revalidate();
}
@Override
public Object getComponent() {
return sender;
}
@Override
public Dimension getMinimumSize(){
Dimension dimension = new Dimension();
int widestPropertyWidth = panelProperties.getWidestPropertyWidth();
dimension.width = (widestPropertyWidth+20 > labelSenderClassWidth+30) ? widestPropertyWidth+20 : labelSenderClassWidth+30;
dimension.height = panelProperties.getPropertiesRowCount()*40 + 50;
return dimension;
}
@Override
public Dimension getPreferredSize(){
Dimension dimension = new Dimension();
dimension.width = super.getPreferredSize().width;
dimension.height = panelProperties.getPropertiesRowCount()*40 + 50;
return dimension;
}
@Override
public Dimension getMaximumSize(){
Dimension dimension = new Dimension();
dimension.width = super.getMaximumSize().width;
dimension.height = panelProperties.getPropertiesRowCount()*40 + 50;
return dimension;
}
public class PanelProperties extends JPanel {
private List<PropertyComponent> propertyComponentList;
private List<Property> propertiesList;
private int widestPropertyWidth;
private int propertiesRowCount;
private PanelProperties(){
propertyComponentList = new ArrayList<>();
propertiesList = new ArrayList<>();
widestPropertyWidth = 0;
propertiesRowCount = 0;
this.setLayout(new FlowLayout(FlowLayout.LEFT,0,0));
this.addMouseListener(new DragListener());
this.setOpaque(false);
}
private void setProperties(List<Property> properties){
propertiesList.clear();
propertiesList.addAll(properties);
propertyComponentList.clear();
this.removeAll();
this.repaint();
widestPropertyWidth = 0;
int propertyId = 0;
for (Property property : propertiesList) {
PropertyComponent propertyComponent = new PropertyComponent(senderColor,propertyId,new SenderEvent());
propertyComponent.setProperty(property);
propertyComponentList.add(propertyComponent);
this.add(propertyComponent);
if (propertyComponent.getPreferredSize().width > widestPropertyWidth) {
widestPropertyWidth = propertyComponent.getPreferredSize().width;
}
propertyId++;
}
countPropertiesRowCount();
this.revalidate();
}
private int getWidestPropertyWidth(){
return widestPropertyWidth;
}
private int getPropertiesRowCount(){
return propertiesRowCount;
}
private void countPropertiesRowCount(){
int thisPanelWidth = SenderPanel.this.getSize().width-20;
thisPanelWidth = (thisPanelWidth < 0) ? Integer.MAX_VALUE : thisPanelWidth;
if (widestPropertyWidth <= thisPanelWidth) {
int controlSum = 0;
int expectedRows = 0;
for (int i = 0; i < propertyComponentList.size(); i++) {
if (i == 0) {
expectedRows = 1;
}
controlSum += propertyComponentList.get(i).getPreferredSize().width;
if (controlSum > thisPanelWidth) {
i--;
controlSum = 0;
expectedRows++;
}
}
propertiesRowCount = (expectedRows != propertiesRowCount) ? expectedRows : propertiesRowCount;
}
}
@Override
public Dimension getMinimumSize(){
Dimension dimension = new Dimension();
dimension.width = widestPropertyWidth;
dimension.height = propertiesRowCount*40;
return dimension;
}
@Override
public Dimension getPreferredSize(){
countPropertiesRowCount();
Dimension dimension = new Dimension();
dimension.width = SenderPanel.this.getSize().width-20;
dimension.height = propertiesRowCount*40;
return dimension;
}
@Override
public Dimension getMaximumSize(){
Dimension dimension = new Dimension();
dimension.width = SenderPanel.this.getSize().width-20;
dimension.height = propertiesRowCount*40;
return dimension;
}
public final class SenderEvent {
public void saveProperty(int propertyId){
for (int i = 0; i<propertyComponentList.size();i++){
if (propertyComponentList.get(i).getId() == propertyId){
propertiesList.set(i, propertyComponentList.get(i).getProperty());
sender.getProperty().clear();
sender.getProperty().addAll(propertiesList);
SenderPanel.this.setComponent(sender);
scenarioEvent.saveSender();
}
}
}
public void deleteProperty(int propertyId){
for (int i = 0; i<propertyComponentList.size();i++){
if (propertyComponentList.get(i).getId() == propertyId){
propertiesList.remove(i);
sender.getProperty().clear();
sender.getProperty().addAll(propertiesList);
SenderPanel.this.setComponent(sender);
scenarioEvent.saveSender();
}
}
}
}
private class DragListener extends MouseInputAdapter {
private boolean mousePressed;
private int selectedComponent;
private int expectedReleaseComponent;
private DragListener(){
mousePressed = false;
}
@Override
public void mousePressed(MouseEvent e){
if (e.getComponent() instanceof PropertyComponent){
for (int i = 0;i< propertyComponentList.size();i++){
if (e.getComponent().equals(propertyComponentList.get(i))){
selectedComponent = i;
expectedReleaseComponent = i;
mousePressed = true;
}
}
}
}
@Override
public void mouseEntered(MouseEvent e) {
if (e.getComponent() instanceof PropertyComponent){
for (int i = 0;i< propertyComponentList.size();i++){
if (e.getComponent().equals(propertyComponentList.get(i))){
expectedReleaseComponent = i;
}
}
}
}
@Override
public void mouseReleased(MouseEvent e){
if(mousePressed) {
if (selectedComponent == expectedReleaseComponent) {
// do nothing
} else {
if (selectedComponent < expectedReleaseComponent) {
for (int i = 0; i < propertiesList.size(); i++) {
if (i < selectedComponent) {
// do nothing
} else {
if (i < expectedReleaseComponent) {
Collections.swap(propertiesList, i, i + 1);
}
}
}
}
if (selectedComponent > expectedReleaseComponent) {
for (int i = propertiesList.size() - 1; 0 <= i; i--) {
if (i < selectedComponent) {
if (i >= expectedReleaseComponent) {
Collections.swap(propertiesList, i, i + 1);
}
}
}
}
sender.getProperty().clear();
sender.getProperty().addAll(propertiesList);
SenderPanel.this.setComponent(sender);
scenarioEvent.saveSender();
}
mousePressed = false;
}
}
@Override
public void mouseClicked(MouseEvent e){
MouseEvent wrappedEvent = new MouseEvent((Component)e.getSource(),e.getID(),e.getWhen(),e.getModifiers(),e.getX()+10,e.getY()+40,e.getClickCount(),e.isPopupTrigger(),e.getButton());
((JPanel)e.getComponent().getAccessibleContext().getAccessibleParent()).dispatchEvent(wrappedEvent);
}
}
}
}
|
src/main/java/org/perfcake/pc4idea/editor/gui/SenderPanel.java
|
package org.perfcake.pc4idea.editor.gui;
import com.intellij.openapi.project.Project;
import org.perfcake.model.Property;
import org.perfcake.model.Scenario;
import org.perfcake.pc4idea.editor.PerfCakeEditorGUI;
import org.perfcake.pc4idea.editor.components.ComponentEditor;
import org.perfcake.pc4idea.editor.components.PropertyComponent;
import org.perfcake.pc4idea.editor.wizard.PropertyEditor;
import org.perfcake.pc4idea.editor.wizard.SenderEditor;
import javax.swing.*;
import javax.swing.event.MouseInputAdapter;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: Stanislav Kaleta
* Date: 28.9.2014
*/
public class SenderPanel extends AbstractPanel {
private final String TITLE ="Sender Editor";
private Color senderColor = Color.getHSBColor(220/360f,0.5f,0.75f);
private final Project project;
private SenderEditor senderEditor;
private Scenario.Sender sender;
PerfCakeEditorGUI.ScenarioEvent scenarioEvent;
private JLabel labelSenderClass;
private PanelProperties panelProperties;
private int labelSenderClassWidth;
public SenderPanel(Project project, PerfCakeEditorGUI.ScenarioEvent scenarioEvent){
super(project);
this.project = project;
this.scenarioEvent = scenarioEvent;
labelSenderClassWidth = 0;
initComponents();
}
private void initComponents() {
labelSenderClass = new JLabel("---");
labelSenderClass.setFont(new Font(labelSenderClass.getFont().getName(), 0, 15));
labelSenderClass.setForeground(senderColor);
panelProperties = new PanelProperties();
SpringLayout layout = new SpringLayout();
this.setLayout(layout);
this.add(labelSenderClass);
this.add(panelProperties);
layout.putConstraint(SpringLayout.HORIZONTAL_CENTER, labelSenderClass,
0,
SpringLayout.HORIZONTAL_CENTER, this);
layout.putConstraint(SpringLayout.NORTH, labelSenderClass,
10,
SpringLayout.NORTH, this);
layout.putConstraint(SpringLayout.WEST, panelProperties,
10,
SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, panelProperties,8,SpringLayout.SOUTH, labelSenderClass);
this.addComponentListener( new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
e.getComponent().revalidate();
e.getComponent().repaint();
}
});
this.setTransferHandler(new TransferHandler(){
@Override
public boolean canImport(TransferHandler.TransferSupport support){
support.setDropAction(COPY);
return support.isDataFlavorSupported(DataFlavor.stringFlavor);
}
@Override
public boolean importData(TransferHandler.TransferSupport support){
if (!canImport(support)) {
return false;
}
Transferable t = support.getTransferable();
String transferredData = "";
try {
transferredData = (String)t.getTransferData(DataFlavor.stringFlavor);
} catch (UnsupportedFlavorException e) {
e.printStackTrace(); /*TODO log*/
} catch (IOException e) {
e.printStackTrace(); /*TODO log*/
}
switch (transferredData){
case "Property": {
PropertyEditor propertyEditor = new PropertyEditor();
ComponentEditor editor = new ComponentEditor("Property Editor",propertyEditor);
editor.show();
if (editor.getExitCode() == 0) {
sender.getProperty().add(propertyEditor.getProperty());
setComponent(sender);
scenarioEvent.saveSender();
}
break;
}
default: break;
}
return true;
}
});
}
@Override
protected Color getColor() {
return senderColor;
}
@Override
protected String getEditorTitle() {
return TITLE;
}
@Override
protected JPanel getEditorPanel() {
senderEditor = new SenderEditor();
senderEditor.setSender(sender);
return senderEditor;
}
@Override
protected void applyChanges() {
setComponent(senderEditor.getSender());
scenarioEvent.saveSender();
}
@Override
public void setComponent(Object component) {
sender = (Scenario.Sender) component;
labelSenderClass.setText(sender.getClazz());
FontMetrics fontMetrics = labelSenderClass.getFontMetrics(labelSenderClass.getFont());
labelSenderClassWidth = fontMetrics.stringWidth(labelSenderClass.getText());
panelProperties.setProperties(sender.getProperty());
this.revalidate();
}
@Override
public Object getComponent() {
return sender;
}
@Override
public Dimension getMinimumSize(){
Dimension dimension = new Dimension();
int widestPropertyWidth = panelProperties.getWidestPropertyWidth();
dimension.width = (widestPropertyWidth+20 > labelSenderClassWidth+30) ? widestPropertyWidth+20 : labelSenderClassWidth+30;
dimension.height = 50;
return dimension;
}
@Override
public Dimension getPreferredSize(){
Dimension dimension = new Dimension();
dimension.width = super.getPreferredSize().width;
dimension.height = panelProperties.getPropertiesRowCount()*40 + 50;
return dimension;
}
@Override
public Dimension getMaximumSize(){
Dimension dimension = new Dimension();
dimension.width = super.getMaximumSize().width;
dimension.height = panelProperties.getPropertiesRowCount()*40 + 50;
return dimension;
}
public class PanelProperties extends JPanel {
private List<PropertyComponent> propertyComponentList;
private List<Property> propertiesList;
private int widestPropertyWidth;
private int propertiesRowCount;
private PanelProperties(){
propertyComponentList = new ArrayList<>();
propertiesList = new ArrayList<>();
widestPropertyWidth = 0;
propertiesRowCount = 0;
this.setLayout(new FlowLayout(FlowLayout.LEFT,0,0));
this.addMouseListener(new DragListener());
this.setOpaque(false);
}
private void setProperties(List<Property> properties){
propertiesList.clear();
propertiesList.addAll(properties);
propertyComponentList.clear();
this.removeAll();
this.repaint();
widestPropertyWidth = 0;
int propertyId = 0;
for (Property property : propertiesList) {
PropertyComponent propertyComponent = new PropertyComponent(senderColor,propertyId,new SenderEvent());
propertyComponent.setProperty(property);
propertyComponentList.add(propertyComponent);
this.add(propertyComponent);
if (propertyComponent.getPreferredSize().width > widestPropertyWidth) {
widestPropertyWidth = propertyComponent.getPreferredSize().width;
}
propertyId++;
}
countPropertiesRowCount();
this.revalidate();
}
private int getWidestPropertyWidth(){
return widestPropertyWidth;
}
private int getPropertiesRowCount(){
return propertiesRowCount;
}
private void countPropertiesRowCount(){
int thisPanelWidth = SenderPanel.this.getSize().width-20;
thisPanelWidth = (thisPanelWidth < 0) ? Integer.MAX_VALUE : thisPanelWidth;
if (widestPropertyWidth <= thisPanelWidth) {
int controlSum = 0;
int expectedRows = 0;
for (int i = 0; i < propertyComponentList.size(); i++) {
if (i == 0) {
expectedRows = 1;
}
controlSum += propertyComponentList.get(i).getPreferredSize().width;
if (controlSum > thisPanelWidth) {
i--;
controlSum = 0;
expectedRows++;
}
}
propertiesRowCount = (expectedRows != propertiesRowCount) ? expectedRows : propertiesRowCount;
}
}
@Override
public Dimension getMinimumSize(){
Dimension dimension = new Dimension();
dimension.width = widestPropertyWidth;
dimension.height = 20;
return dimension;
}
@Override
public Dimension getPreferredSize(){
countPropertiesRowCount();
Dimension dimension = new Dimension();
dimension.width = SenderPanel.this.getSize().width-20;
dimension.height = propertiesRowCount*40;
return dimension;
}
@Override
public Dimension getMaximumSize(){
Dimension dimension = new Dimension();
dimension.width = SenderPanel.this.getSize().width-20;
dimension.height = Integer.MAX_VALUE;
return dimension;
}
public final class SenderEvent {
public void saveProperty(int propertyId){
for (int i = 0; i<propertyComponentList.size();i++){
if (propertyComponentList.get(i).getId() == propertyId){
propertiesList.set(i, propertyComponentList.get(i).getProperty());
sender.getProperty().clear();
sender.getProperty().addAll(propertiesList);
SenderPanel.this.setComponent(sender);
scenarioEvent.saveSender();
}
}
}
public void deleteProperty(int propertyId){
for (int i = 0; i<propertyComponentList.size();i++){
if (propertyComponentList.get(i).getId() == propertyId){
propertiesList.remove(i);
sender.getProperty().clear();
sender.getProperty().addAll(propertiesList);
SenderPanel.this.setComponent(sender);
scenarioEvent.saveSender();
}
}
}
}
private class DragListener extends MouseInputAdapter {
private boolean mousePressed;
private int selectedComponent;
private int expectedReleaseComponent;
private DragListener(){
mousePressed = false;
}
@Override
public void mousePressed(MouseEvent e){
if (e.getComponent() instanceof PropertyComponent){
for (int i = 0;i< propertyComponentList.size();i++){
if (e.getComponent().equals(propertyComponentList.get(i))){
selectedComponent = i;
expectedReleaseComponent = i;
mousePressed = true;
}
}
}
}
@Override
public void mouseEntered(MouseEvent e) {
if (e.getComponent() instanceof PropertyComponent){
for (int i = 0;i< propertyComponentList.size();i++){
if (e.getComponent().equals(propertyComponentList.get(i))){
expectedReleaseComponent = i;
}
}
} else {
expectedReleaseComponent = -1;
}
}
@Override
public void mouseReleased(MouseEvent e){
if(mousePressed){
if (expectedReleaseComponent >= 0) {
if (selectedComponent == expectedReleaseComponent) {
// do nothing
} else {
if (selectedComponent < expectedReleaseComponent) {
for (int i = 0; i < propertiesList.size(); i++) {
if (i < selectedComponent) {
// do nothing
} else {
if (i < expectedReleaseComponent) {
Collections.swap(propertiesList, i, i + 1);
}
}
}
}
if (selectedComponent > expectedReleaseComponent) {
for (int i = propertiesList.size() - 1; 0 <= i; i--) {
if (i < selectedComponent) {
if (i >= expectedReleaseComponent) {
Collections.swap(propertiesList, i, i + 1);
}
}
}
}
sender.getProperty().clear();
sender.getProperty().addAll(propertiesList);
SenderPanel.this.setComponent(sender);
scenarioEvent.saveSender();
}
mousePressed = false;
}
}
}
@Override
public void mouseClicked(MouseEvent e){
MouseEvent wrappedEvent = new MouseEvent((Component)e.getSource(),e.getID(),e.getWhen(),e.getModifiers(),e.getX()+10,e.getY()+40,e.getClickCount(),e.isPopupTrigger(),e.getButton());
((JPanel)e.getComponent().getAccessibleContext().getAccessibleParent()).dispatchEvent(wrappedEvent);
}
}
}
}
|
minor changes
|
src/main/java/org/perfcake/pc4idea/editor/gui/SenderPanel.java
|
minor changes
|
<ide><path>rc/main/java/org/perfcake/pc4idea/editor/gui/SenderPanel.java
<ide> package org.perfcake.pc4idea.editor.gui;
<ide>
<del>import com.intellij.openapi.project.Project;
<ide> import org.perfcake.model.Property;
<ide> import org.perfcake.model.Scenario;
<ide> import org.perfcake.pc4idea.editor.PerfCakeEditorGUI;
<ide> public class SenderPanel extends AbstractPanel {
<ide> private final String TITLE ="Sender Editor";
<ide> private Color senderColor = Color.getHSBColor(220/360f,0.5f,0.75f);
<del> private final Project project;
<ide>
<ide> private SenderEditor senderEditor;
<ide> private Scenario.Sender sender;
<del> PerfCakeEditorGUI.ScenarioEvent scenarioEvent;
<add> private PerfCakeEditorGUI.ScenarioEvent scenarioEvent;
<ide>
<ide> private JLabel labelSenderClass;
<ide> private PanelProperties panelProperties;
<ide>
<ide> private int labelSenderClassWidth;
<ide>
<del> public SenderPanel(Project project, PerfCakeEditorGUI.ScenarioEvent scenarioEvent){
<del> super(project);
<del> this.project = project;
<add> public SenderPanel(PerfCakeEditorGUI.ScenarioEvent scenarioEvent){
<ide> this.scenarioEvent = scenarioEvent;
<ide> labelSenderClassWidth = 0;
<ide>
<ide> } catch (IOException e) {
<ide> e.printStackTrace(); /*TODO log*/
<ide> }
<del> switch (transferredData){
<del> case "Property": {
<del> PropertyEditor propertyEditor = new PropertyEditor();
<del> ComponentEditor editor = new ComponentEditor("Property Editor",propertyEditor);
<del> editor.show();
<del> if (editor.getExitCode() == 0) {
<del> sender.getProperty().add(propertyEditor.getProperty());
<del> setComponent(sender);
<del> scenarioEvent.saveSender();
<del> }
<del> break;
<del> }
<del> default: break;
<add> if (transferredData.equals("Property")) {
<add> PropertyEditor propertyEditor = new PropertyEditor();
<add> ComponentEditor editor = new ComponentEditor("Property Editor", propertyEditor);
<add> editor.show();
<add> if (editor.getExitCode() == 0) {
<add> sender.getProperty().add(propertyEditor.getProperty());
<add> setComponent(sender);
<add> scenarioEvent.saveSender();
<add> }
<ide> }
<ide> return true;
<ide> }
<ide> Dimension dimension = new Dimension();
<ide> int widestPropertyWidth = panelProperties.getWidestPropertyWidth();
<ide> dimension.width = (widestPropertyWidth+20 > labelSenderClassWidth+30) ? widestPropertyWidth+20 : labelSenderClassWidth+30;
<del> dimension.height = 50;
<add> dimension.height = panelProperties.getPropertiesRowCount()*40 + 50;
<ide> return dimension;
<ide> }
<ide>
<ide> public Dimension getMinimumSize(){
<ide> Dimension dimension = new Dimension();
<ide> dimension.width = widestPropertyWidth;
<del> dimension.height = 20;
<add> dimension.height = propertiesRowCount*40;
<ide> return dimension;
<ide> }
<ide>
<ide> public Dimension getMaximumSize(){
<ide> Dimension dimension = new Dimension();
<ide> dimension.width = SenderPanel.this.getSize().width-20;
<del> dimension.height = Integer.MAX_VALUE;
<add> dimension.height = propertiesRowCount*40;
<ide> return dimension;
<ide> }
<ide>
<ide> expectedReleaseComponent = i;
<ide> }
<ide> }
<del> } else {
<del> expectedReleaseComponent = -1;
<ide> }
<ide> }
<ide>
<ide> @Override
<ide> public void mouseReleased(MouseEvent e){
<del> if(mousePressed){
<del> if (expectedReleaseComponent >= 0) {
<del> if (selectedComponent == expectedReleaseComponent) {
<del> // do nothing
<del> } else {
<del> if (selectedComponent < expectedReleaseComponent) {
<del> for (int i = 0; i < propertiesList.size(); i++) {
<del> if (i < selectedComponent) {
<del> // do nothing
<del> } else {
<del> if (i < expectedReleaseComponent) {
<del> Collections.swap(propertiesList, i, i + 1);
<del> }
<add> if(mousePressed) {
<add> if (selectedComponent == expectedReleaseComponent) {
<add> // do nothing
<add> } else {
<add> if (selectedComponent < expectedReleaseComponent) {
<add> for (int i = 0; i < propertiesList.size(); i++) {
<add> if (i < selectedComponent) {
<add> // do nothing
<add> } else {
<add> if (i < expectedReleaseComponent) {
<add> Collections.swap(propertiesList, i, i + 1);
<ide> }
<ide> }
<ide> }
<del> if (selectedComponent > expectedReleaseComponent) {
<del> for (int i = propertiesList.size() - 1; 0 <= i; i--) {
<del> if (i < selectedComponent) {
<del> if (i >= expectedReleaseComponent) {
<del> Collections.swap(propertiesList, i, i + 1);
<del> }
<add> }
<add> if (selectedComponent > expectedReleaseComponent) {
<add> for (int i = propertiesList.size() - 1; 0 <= i; i--) {
<add> if (i < selectedComponent) {
<add> if (i >= expectedReleaseComponent) {
<add> Collections.swap(propertiesList, i, i + 1);
<ide> }
<ide> }
<ide> }
<del> sender.getProperty().clear();
<del> sender.getProperty().addAll(propertiesList);
<del> SenderPanel.this.setComponent(sender);
<del> scenarioEvent.saveSender();
<ide> }
<del> mousePressed = false;
<del> }
<add> sender.getProperty().clear();
<add> sender.getProperty().addAll(propertiesList);
<add> SenderPanel.this.setComponent(sender);
<add> scenarioEvent.saveSender();
<add> }
<add> mousePressed = false;
<ide> }
<ide> }
<ide>
|
|
Java
|
apache-2.0
|
8c4951c2200599aa77d458d436fc19fd836977f0
| 0 |
duke-compsci290-spring2016/sakai,hackbuteer59/sakai,colczr/sakai,ktakacs/sakai,bzhouduke123/sakai,OpenCollabZA/sakai,whumph/sakai,frasese/sakai,colczr/sakai,bkirschn/sakai,zqian/sakai,colczr/sakai,udayg/sakai,kwedoff1/sakai,conder/sakai,hackbuteer59/sakai,tl-its-umich-edu/sakai,bzhouduke123/sakai,bkirschn/sakai,conder/sakai,OpenCollabZA/sakai,puramshetty/sakai,introp-software/sakai,zqian/sakai,kwedoff1/sakai,frasese/sakai,lorenamgUMU/sakai,bkirschn/sakai,conder/sakai,Fudan-University/sakai,puramshetty/sakai,rodriguezdevera/sakai,introp-software/sakai,willkara/sakai,noondaysun/sakai,OpenCollabZA/sakai,pushyamig/sakai,clhedrick/sakai,introp-software/sakai,frasese/sakai,ouit0408/sakai,puramshetty/sakai,puramshetty/sakai,conder/sakai,whumph/sakai,wfuedu/sakai,bkirschn/sakai,rodriguezdevera/sakai,wfuedu/sakai,puramshetty/sakai,clhedrick/sakai,kwedoff1/sakai,noondaysun/sakai,joserabal/sakai,pushyamig/sakai,liubo404/sakai,bkirschn/sakai,Fudan-University/sakai,conder/sakai,Fudan-University/sakai,pushyamig/sakai,ktakacs/sakai,lorenamgUMU/sakai,rodriguezdevera/sakai,ktakacs/sakai,whumph/sakai,clhedrick/sakai,tl-its-umich-edu/sakai,lorenamgUMU/sakai,liubo404/sakai,noondaysun/sakai,Fudan-University/sakai,Fudan-University/sakai,tl-its-umich-edu/sakai,ouit0408/sakai,lorenamgUMU/sakai,tl-its-umich-edu/sakai,udayg/sakai,clhedrick/sakai,udayg/sakai,pushyamig/sakai,Fudan-University/sakai,wfuedu/sakai,clhedrick/sakai,hackbuteer59/sakai,udayg/sakai,pushyamig/sakai,noondaysun/sakai,wfuedu/sakai,liubo404/sakai,introp-software/sakai,frasese/sakai,duke-compsci290-spring2016/sakai,bzhouduke123/sakai,bkirschn/sakai,hackbuteer59/sakai,noondaysun/sakai,joserabal/sakai,kingmook/sakai,tl-its-umich-edu/sakai,colczr/sakai,surya-janani/sakai,surya-janani/sakai,rodriguezdevera/sakai,buckett/sakai-gitflow,kingmook/sakai,liubo404/sakai,joserabal/sakai,kingmook/sakai,surya-janani/sakai,wfuedu/sakai,rodriguezdevera/sakai,ktakacs/sakai,tl-its-umich-edu/sakai,bkirschn/sakai,lorenamgUMU/sakai,buckett/sakai-gitflow,whumph/sakai,willkara/sakai,clhedrick/sakai,buckett/sakai-gitflow,Fudan-University/sakai,pushyamig/sakai,Fudan-University/sakai,clhedrick/sakai,duke-compsci290-spring2016/sakai,colczr/sakai,duke-compsci290-spring2016/sakai,udayg/sakai,kingmook/sakai,bkirschn/sakai,rodriguezdevera/sakai,colczr/sakai,willkara/sakai,willkara/sakai,willkara/sakai,whumph/sakai,lorenamgUMU/sakai,ouit0408/sakai,duke-compsci290-spring2016/sakai,kwedoff1/sakai,udayg/sakai,clhedrick/sakai,udayg/sakai,OpenCollabZA/sakai,zqian/sakai,willkara/sakai,ktakacs/sakai,hackbuteer59/sakai,liubo404/sakai,buckett/sakai-gitflow,joserabal/sakai,liubo404/sakai,introp-software/sakai,hackbuteer59/sakai,bzhouduke123/sakai,ouit0408/sakai,duke-compsci290-spring2016/sakai,introp-software/sakai,noondaysun/sakai,puramshetty/sakai,noondaysun/sakai,zqian/sakai,ouit0408/sakai,ouit0408/sakai,kingmook/sakai,zqian/sakai,OpenCollabZA/sakai,lorenamgUMU/sakai,tl-its-umich-edu/sakai,ouit0408/sakai,buckett/sakai-gitflow,conder/sakai,joserabal/sakai,zqian/sakai,surya-janani/sakai,lorenamgUMU/sakai,duke-compsci290-spring2016/sakai,joserabal/sakai,kingmook/sakai,surya-janani/sakai,pushyamig/sakai,zqian/sakai,willkara/sakai,ktakacs/sakai,hackbuteer59/sakai,introp-software/sakai,kingmook/sakai,ouit0408/sakai,tl-its-umich-edu/sakai,liubo404/sakai,colczr/sakai,ktakacs/sakai,buckett/sakai-gitflow,OpenCollabZA/sakai,noondaysun/sakai,conder/sakai,OpenCollabZA/sakai,hackbuteer59/sakai,willkara/sakai,bzhouduke123/sakai,wfuedu/sakai,ktakacs/sakai,kwedoff1/sakai,whumph/sakai,surya-janani/sakai,kingmook/sakai,wfuedu/sakai,surya-janani/sakai,kwedoff1/sakai,colczr/sakai,duke-compsci290-spring2016/sakai,rodriguezdevera/sakai,rodriguezdevera/sakai,wfuedu/sakai,frasese/sakai,surya-janani/sakai,bzhouduke123/sakai,udayg/sakai,kwedoff1/sakai,whumph/sakai,bzhouduke123/sakai,zqian/sakai,introp-software/sakai,kwedoff1/sakai,liubo404/sakai,frasese/sakai,conder/sakai,buckett/sakai-gitflow,buckett/sakai-gitflow,frasese/sakai,puramshetty/sakai,joserabal/sakai,whumph/sakai,OpenCollabZA/sakai,joserabal/sakai,bzhouduke123/sakai,puramshetty/sakai,frasese/sakai,pushyamig/sakai
|
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009 The Sakai Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ECL-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.sakaiproject.calendar.impl;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Enumeration;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Properties;
import java.util.Set;
import java.util.Stack;
import java.util.TimeZone;
import java.util.Vector;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.URIResolver;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.stream.StreamSource;
import net.fortuna.ical4j.data.CalendarOutputter;
import net.fortuna.ical4j.model.DateTime;
import net.fortuna.ical4j.model.Property;
import net.fortuna.ical4j.model.TimeZoneRegistry;
import net.fortuna.ical4j.model.TimeZoneRegistryFactory;
import net.fortuna.ical4j.model.component.VEvent;
import net.fortuna.ical4j.model.parameter.Value;
import net.fortuna.ical4j.model.property.CalScale;
import net.fortuna.ical4j.model.property.Comment;
import net.fortuna.ical4j.model.property.Description;
import net.fortuna.ical4j.model.property.Location;
import net.fortuna.ical4j.model.property.Organizer;
import net.fortuna.ical4j.model.property.ProdId;
import net.fortuna.ical4j.model.property.TzId;
import net.fortuna.ical4j.model.property.Uid;
import net.fortuna.ical4j.model.property.Version;
import org.apache.avalon.framework.logger.ConsoleLogger;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.fop.apps.Driver;
import org.apache.fop.apps.FOPException;
import org.apache.fop.apps.Options;
import org.apache.fop.configuration.Configuration;
import org.apache.fop.messaging.MessageHandler;
import org.sakaiproject.alias.api.Alias;
import org.sakaiproject.alias.api.AliasService;
import org.sakaiproject.authz.api.AuthzGroupService;
import org.sakaiproject.authz.api.AuthzPermissionException;
import org.sakaiproject.authz.api.FunctionManager;
import org.sakaiproject.authz.api.GroupNotDefinedException;
import org.sakaiproject.authz.api.SecurityService;
import org.sakaiproject.calendar.api.Calendar;
import org.sakaiproject.calendar.api.CalendarEdit;
import org.sakaiproject.calendar.api.CalendarEvent;
import org.sakaiproject.calendar.api.CalendarEventEdit;
import org.sakaiproject.calendar.api.CalendarEventVector;
import org.sakaiproject.calendar.api.CalendarService;
import org.sakaiproject.calendar.api.RecurrenceRule;
import org.sakaiproject.calendar.api.CalendarEvent.EventAccess;
import org.sakaiproject.calendar.cover.ExternalCalendarSubscriptionService;
import org.sakaiproject.util.CalendarUtil;
import org.sakaiproject.component.api.ServerConfigurationService;
import org.sakaiproject.component.cover.ComponentManager;
import org.sakaiproject.content.api.ContentHostingService;
import org.sakaiproject.content.api.ContentResource;
import org.sakaiproject.entity.api.ContextObserver;
import org.sakaiproject.entity.api.Edit;
import org.sakaiproject.entity.api.Entity;
import org.sakaiproject.entity.api.EntityAccessOverloadException;
import org.sakaiproject.entity.api.EntityCopyrightException;
import org.sakaiproject.entity.api.EntityManager;
import org.sakaiproject.entity.api.EntityNotDefinedException;
import org.sakaiproject.entity.api.EntityPermissionException;
import org.sakaiproject.entity.api.EntityTransferrer;
import org.sakaiproject.entity.api.EntityTransferrerRefMigrator;
import org.sakaiproject.entity.api.HttpAccess;
import org.sakaiproject.entity.api.Reference;
import org.sakaiproject.entity.api.ResourceProperties;
import org.sakaiproject.entity.api.ResourcePropertiesEdit;
import org.sakaiproject.event.api.Event;
import org.sakaiproject.event.api.EventTrackingService;
import org.sakaiproject.event.api.NotificationService;
import org.sakaiproject.exception.IdInvalidException;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.exception.IdUsedException;
import org.sakaiproject.exception.InUseException;
import org.sakaiproject.exception.PermissionException;
import org.sakaiproject.id.api.IdManager;
import org.sakaiproject.javax.Filter;
import org.sakaiproject.memory.api.Cache;
import org.sakaiproject.memory.api.CacheRefresher;
import org.sakaiproject.memory.api.MemoryService;
import org.sakaiproject.site.api.Group;
import org.sakaiproject.site.api.Site;
import org.sakaiproject.site.api.SiteService;
import org.sakaiproject.thread_local.api.ThreadLocalManager;
import org.sakaiproject.time.api.Time;
import org.sakaiproject.time.api.TimeBreakdown;
import org.sakaiproject.time.api.TimeRange;
import org.sakaiproject.time.api.TimeService;
import org.sakaiproject.tool.api.SessionBindingEvent;
import org.sakaiproject.tool.api.SessionBindingListener;
import org.sakaiproject.tool.api.SessionManager;
import org.sakaiproject.tool.api.ToolManager;
import org.sakaiproject.user.api.UserDirectoryService;
import org.sakaiproject.user.api.UserNotDefinedException;
import org.sakaiproject.util.BaseResourcePropertiesEdit;
import org.sakaiproject.util.CalendarUtil;
import org.sakaiproject.util.DefaultEntityHandler;
import org.sakaiproject.util.DoubleStorageUser;
import org.sakaiproject.util.EntityCollections;
import org.sakaiproject.util.FormattedText;
import org.sakaiproject.util.ResourceLoader;
import org.sakaiproject.util.SAXEntityReader;
import org.sakaiproject.util.Validator;
import org.sakaiproject.util.Web;
import org.sakaiproject.util.Xml;
import org.sakaiproject.util.LinkMigrationHelper;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import java.util.Map.Entry;
/**
* <p>
* BaseCalendarService is an base implementation of the CalendarService. Extension classes implement object creation, access and storage.
* </p>
*/
public abstract class BaseCalendarService implements CalendarService, DoubleStorageUser, CacheRefresher, ContextObserver, EntityTransferrer, SAXEntityReader, EntityTransferrerRefMigrator
{
/** Our logger. */
private static Log M_log = LogFactory.getLog(BaseCalendarService.class);
/** The initial portion of a relative access point URL. */
protected String m_relativeAccessPoint = null;
/** A Cache object for caching: calendars keyed by reference. */
protected Cache m_calendarCache = null;
/** A bunch of caches for events: keyed by calendar id, the cache is keyed by event reference. */
protected Hashtable m_eventCaches = null;
/** A Storage object for access to calendars and events. */
protected Storage m_storage = null;
/** DELIMETER used to separate the list of custom fields for this calendar. */
private final static String ADDFIELDS_DELIMITER = "_,_";
/** Security lock / event root for generic message events to make it a mail event. */
public static final String SECURE_SCHEDULE_ROOT = "calendar.";
private TransformerFactory transformerFactory = null;
private DocumentBuilder docBuilder = null;
private ResourceLoader rb = new ResourceLoader("calendar");
private ContentHostingService contentHostingService;
private GroupComparator groupComparator = new GroupComparator();
/**
* Access this service from the inner classes.
*/
protected BaseCalendarService service()
{
return this;
}
/**
* Construct a Storage object.
*
* @return The new storage object.
*/
protected abstract Storage newStorage();
/**
* Access the partial URL that forms the root of calendar URLs.
*
* @param relative
* if true, form within the access path only (i.e. starting with /content)
* @return the partial URL that forms the root of calendar URLs.
*/
protected String getAccessPoint(boolean relative)
{
return (relative ? "" : m_serverConfigurationService.getAccessUrl()) + m_relativeAccessPoint;
} // getAccessPoint
/**
* Check security permission.
*
* @param lock
* The lock id string.
* @param reference
* The resource's reference string, or null if no resource is involved.
* @return true if permitted, false if not.
*/
protected boolean unlockCheck(String lock, String reference)
{
return m_securityService.unlock(lock, reference);
} // unlockCheck
/**
* Check security permission.
*
* @param lock
* The lock id string.
* @param reference
* The resource's reference string, or null if no resource is involved.
* @exception PermissionException
* thrown if the user does not have access
*/
protected void unlock(String lock, String reference) throws PermissionException
{
// check if publicly accessible via export
if ( getExportEnabled(reference) && lock.equals(AUTH_READ_CALENDAR) )
return;
// otherwise check permissions
else if (!m_securityService.unlock(lock, reference))
throw new PermissionException(m_sessionManager.getCurrentSessionUserId(), lock, reference);
} // unlock
/**
* Access the internal reference which can be used to access the calendar from within the system.
*
* @param context
* The context.
* @param id
* The calendar id.
* @return The the internal reference which can be used to access the calendar from within the system.
*/
public String calendarReference(String context, String id)
{
return getAccessPoint(true) + Entity.SEPARATOR + REF_TYPE_CALENDAR + Entity.SEPARATOR + context + Entity.SEPARATOR + id;
} // calendarReference
/**
* @inheritDoc
*/
public String calendarPdfReference(String context, String id, int scheduleType, String timeRangeString,
String userName, TimeRange dailyTimeRange)
{
return getAccessPoint(true) + Entity.SEPARATOR + REF_TYPE_CALENDAR_PDF + Entity.SEPARATOR + context + Entity.SEPARATOR + id
+ "?" + SCHEDULE_TYPE_PARAMETER_NAME + "=" + Validator.escapeHtml(Integer.valueOf(scheduleType).toString()) + "&"
+ TIME_RANGE_PARAMETER_NAME + "=" + timeRangeString + "&"
+ Validator.escapeHtml(USER_NAME_PARAMETER_NAME) + "=" + Validator.escapeHtml(userName) + "&"
+ DAILY_START_TIME_PARAMETER_NAME + "=" + Validator.escapeHtml(dailyTimeRange.toString());
}
/**
* @inheritDoc
*/
public String calendarICalReference(Reference ref)
{
String context = ref.getContext();
String id = ref.getId();
String alias = null;
List aliasList = m_aliasService.getAliases( ref.getReference() );
if ( ! aliasList.isEmpty() )
alias = ((Alias)aliasList.get(0)).getId();
if ( alias != null)
return getAccessPoint(true) + Entity.SEPARATOR + REF_TYPE_CALENDAR_ICAL + Entity.SEPARATOR + alias;
else
return getAccessPoint(true) + Entity.SEPARATOR + REF_TYPE_CALENDAR_ICAL + Entity.SEPARATOR + context + Entity.SEPARATOR + id;
}
/**
* @inheritDoc
*/
public String calendarSubscriptionReference(String context, String id)
{
return getAccessPoint(true) + Entity.SEPARATOR + REF_TYPE_CALENDAR_SUBSCRIPTION + Entity.SEPARATOR + context + Entity.SEPARATOR + id;
}
/**
* @inheritDoc
*/
public boolean getExportEnabled(String ref)
{
Calendar cal = findCalendar(ref);
if ( cal == null )
return false;
else
return cal.getExportEnabled();
}
/**
* @inheritDoc
*/
public void setExportEnabled(String ref, boolean enable)
{
try
{
CalendarEdit cal = editCalendar(ref);
cal.setExportEnabled(enable);
commitCalendar(cal);
}
catch ( Exception e)
{
M_log.warn("setExportEnabled(): ", e);
}
}
/**
* Access the internal reference which can be used to access the event from within the system.
*
* @param context
* The context.
* @param calendarId
* The calendar id.
* @param id
* The event id.
* @return The the internal reference which can be used to access the event from within the system.
*/
public String eventReference(String context, String calendarId, String id)
{
return getAccessPoint(true) + Entity.SEPARATOR + REF_TYPE_EVENT + Entity.SEPARATOR + context + Entity.SEPARATOR
+ calendarId + Entity.SEPARATOR + id;
} // eventReference
/**
* Access the internal reference which can be used to access the subscripted event from within the system.
*
* @param context
* The context.
* @param calendarId
* The calendar id.
* @param id
* The event id.
* @return The the internal reference which can be used to access the subscripted event from within the system.
*/
public String eventSubscriptionReference(String context, String calendarId, String id)
{
return getAccessPoint(true) + Entity.SEPARATOR + REF_TYPE_EVENT_SUBSCRIPTION + Entity.SEPARATOR + context + Entity.SEPARATOR
+ calendarId + Entity.SEPARATOR + id;
} // eventSubscriptionReference
/**
* Takes several calendar References and merges their events from within a given time range.
*
* @param references
* The List of calendar References.
* @param range
* The time period to use to select events.
* @return CalendarEventVector object with the union of all events from the list of calendars in the given time range.
*/
public CalendarEventVector getEvents(List references, TimeRange range)
{
CalendarEventVector calendarEventVector = null;
if (references != null && range != null)
{
List allEvents = new ArrayList();
Iterator it = references.iterator();
// Add the events for each calendar in our list.
while (it.hasNext())
{
String calendarReference = (String) it.next();
Calendar calendarObj = null;
try
{
calendarObj = getCalendar(calendarReference);
}
catch (IdUnusedException e)
{
continue;
}
catch (PermissionException e)
{
continue;
}
if (calendarObj != null)
{
Iterator calEvent = null;
try
{
calEvent = calendarObj.getEvents(range, null).iterator();
}
catch (PermissionException e1)
{
continue;
}
allEvents.addAll(new CalendarEventVector(calEvent));
}
}
// Do a sort since each of the events implements the Comparable interface.
Collections.sort(allEvents);
// Build up a CalendarEventVector and return it.
calendarEventVector = new CalendarEventVector(allEvents.iterator());
}
return calendarEventVector;
}
/**
* Form a tracking event string based on a security function string.
* @param secure The security function string.
* @return The event tracking string.
*/
protected String eventId(String secure)
{
return SECURE_SCHEDULE_ROOT + secure;
} // eventId
/**
* Access the id generating service and return a unique id.
*
* @return a unique id.
*/
protected String getUniqueId()
{
return m_idManager.createUuid();
}
/**********************************************************************************************************************************************************************************************************************************************************
* Constructors, Dependencies and their setter methods
*********************************************************************************************************************************************************************************************************************************************************/
/** Dependency: MemoryService. */
protected MemoryService m_memoryService = null;
/**
* Dependency: MemoryService.
*
* @param service
* The MemoryService.
*/
public void setMemoryService(MemoryService service)
{
m_memoryService = service;
}
/** Dependency: IdManager. */
protected IdManager m_idManager = null;
/**
* Dependency: IdManager.
*
* @param manager
* The IdManager.
*/
public void setIdManager(IdManager manager)
{
m_idManager = manager;
}
/** Configuration: cache, or not. */
protected boolean m_caching = false;
/**
* Configuration: set the caching
*
* @param path
* The storage path.
*/
public void setCaching(String value)
{
m_caching = Boolean.valueOf(value).booleanValue();
}
/** Dependency: EntityManager. */
protected EntityManager m_entityManager = null;
/**
* Dependency: EntityManager.
*
* @param service
* The EntityManager.
*/
public void setEntityManager(EntityManager service)
{
m_entityManager = service;
}
/** Dependency: ServerConfigurationService. */
protected ServerConfigurationService m_serverConfigurationService = null;
/**
* Dependency: ServerConfigurationService.
*
* @param service
* The ServerConfigurationService.
*/
public void setServerConfigurationService(ServerConfigurationService service)
{
m_serverConfigurationService = service;
}
/** Dependency: AliasService. */
protected AliasService m_aliasService = null;
/** Dependency: SiteService. */
protected SiteService m_siteService = null;
/** Dependency: AuthzGroupService */
protected AuthzGroupService m_authzGroupService = null;
/** Dependency: FunctionManager */
protected FunctionManager m_functionManager = null;
/** Dependency: SecurityService */
protected SecurityService m_securityService = null;
/** Dependency: EventTrackingService */
protected EventTrackingService m_eventTrackingService = null;
/** Depedency: SessionManager */
protected SessionManager m_sessionManager = null;
/** Dependency: ThreadLocalManager */
protected ThreadLocalManager m_threadLocalManager = null;
/** Dependency: TimeService */
protected TimeService m_timeService = null;
/** Dependency: ToolManager */
protected ToolManager m_toolManager = null;
/** Dependency: UserDirectoryService */
protected UserDirectoryService m_userDirectoryService = null;
/** A map of services used in SAX serialization */
private Map<String, Object> m_services;
/**
* Dependency: AliasService.
*
* @param service
* The AliasService.
*/
public void setAliasService(AliasService service)
{
m_aliasService = service;
}
/**
* Dependency: SiteService.
*
* @param service
* The SiteService.
*/
public void setSiteService(SiteService service)
{
m_siteService = service;
}
/**
* Dependency: AuthzGroupService.
*
* @param authzGroupService
* The AuthzGroupService.
*/
public void setAuthzGroupService(AuthzGroupService authzGroupService)
{
m_authzGroupService = authzGroupService;
}
/**
* Dependency: FunctionManager.
*
* @param functionManager
* The FunctionManager.
*/
public void setFunctionManager(FunctionManager functionManager)
{
m_functionManager = functionManager;
}
/**
* Dependency: SecurityService.
*
* @param securityService
* The SecurityService.
*/
public void setSecurityService(SecurityService securityService)
{
m_securityService = securityService;
}
/**
* Dependency: EventTrackingService.
* @param eventTrackingService
* The EventTrackingService.
*/
public void setEventTrackingService(EventTrackingService eventTrackingService)
{
this.m_eventTrackingService = eventTrackingService;
}
/**
* Dependency: SessionManager.
* @param sessionManager
* The SessionManager.
*/
public void setSessionManager(SessionManager sessionManager)
{
this.m_sessionManager = sessionManager;
}
/**
* Dependency: ThreadLocalManager.
* @param threadLocalManager
* The ThreadLocalManager.
*/
public void setThreadLocalManager(ThreadLocalManager threadLocalManager)
{
this.m_threadLocalManager = threadLocalManager;
}
/**
* Dependency: TimeService.
* @param timeService
* The TimeService.
*/
public void setTimeService(TimeService timeService)
{
this.m_timeService = timeService;
}
/**
* Dependency: ToolManager.
* @param toolManager
* The ToolManager.
*/
public void setToolManager(ToolManager toolManager)
{
this.m_toolManager = toolManager;
}
/**
* Dependency: UserDirectoryService.
* @param userDirectoryService
* The UserDirectoryService.
*/
public void setUserDirectoryService(UserDirectoryService userDirectoryService)
{
this.m_userDirectoryService = userDirectoryService;
}
/**********************************************************************************************************************************************************************************************************************************************************
* Init and Destroy
*********************************************************************************************************************************************************************************************************************************************************/
/**
* Final initialization, once all dependencies are set.
*/
public void init()
{
contentHostingService = (ContentHostingService) ComponentManager.get("org.sakaiproject.content.api.ContentHostingService");
try
{
m_relativeAccessPoint = REFERENCE_ROOT;
// construct a storage helper and read
m_storage = newStorage();
m_storage.open();
// make the calendar cache
if (m_caching)
{
m_calendarCache = m_memoryService
.newCache(
"org.sakaiproject.calendar.api.CalendarService.calendarCache",
this, getAccessPoint(true) + Entity.SEPARATOR
+ REF_TYPE_CALENDAR + Entity.SEPARATOR);
// make the table to hold the event caches
m_eventCaches = new Hashtable();
}
// create transformerFactory object needed by generatePDF
transformerFactory = TransformerFactory.newInstance();
transformerFactory.setURIResolver( new MyURIResolver(getClass().getClassLoader()) );
// create DocumentBuilder object needed by printSchedule
docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
M_log.info("init(): caching: " + m_caching);
}
catch (Throwable t)
{
M_log.warn("init(): ", t);
}
// register as an entity producer
m_entityManager.registerEntityProducer(this, REFERENCE_ROOT);
// register functions
m_functionManager.registerFunction(AUTH_ADD_CALENDAR);
m_functionManager.registerFunction(AUTH_REMOVE_CALENDAR_OWN);
m_functionManager.registerFunction(AUTH_REMOVE_CALENDAR_ANY);
m_functionManager.registerFunction(AUTH_MODIFY_CALENDAR_OWN);
m_functionManager.registerFunction(AUTH_MODIFY_CALENDAR_ANY);
m_functionManager.registerFunction(AUTH_IMPORT_CALENDAR);
m_functionManager.registerFunction(AUTH_SUBSCRIBE_CALENDAR);
m_functionManager.registerFunction(AUTH_READ_CALENDAR);
m_functionManager.registerFunction(AUTH_ALL_GROUPS_CALENDAR);
m_functionManager.registerFunction(AUTH_OPTIONS_CALENDAR);
}
/**
* Returns to uninitialized state.
*/
public void destroy()
{
if (m_caching)
{
m_calendarCache.destroy();
m_calendarCache = null;
// TODO: destroy each cache
m_eventCaches.clear();
m_eventCaches = null;
}
m_storage.close();
m_storage = null;
M_log.info("destroy()");
}
/**********************************************************************************************************************************************************************************************************************************************************
* CalendarService implementation
*********************************************************************************************************************************************************************************************************************************************************/
/**
* Add a new calendar. Must commitCalendar() to make official, or cancelCalendar() when done!
*
* @param ref
* A reference for the calendar.
* @return The newly created calendar.
* @exception IdUsedException
* if the id is not unique.
* @exception IdInvalidException
* if the id is not made up of valid characters.
*/
public CalendarEdit addCalendar(String ref) throws IdUsedException, IdInvalidException
{
// check the name's validity
if (!m_entityManager.checkReference(ref)) throw new IdInvalidException(ref);
// check for existance
if (m_storage.checkCalendar(ref))
{
throw new IdUsedException(ref);
}
// keep it
CalendarEdit calendar = m_storage.putCalendar(ref);
((BaseCalendarEdit) calendar).setEvent(EVENT_CREATE_CALENDAR);
return calendar;
} // addCalendar
/**
* check permissions for getCalendar().
*
* @param ref
* The calendar reference.
* @return true if the user is allowed to getCalendar(calendarId), false if not.
*/
public boolean allowGetCalendar(String ref)
{
if(REF_TYPE_CALENDAR_SUBSCRIPTION.equals(m_entityManager.newReference(ref).getSubType()))
return true;
return unlockCheck(AUTH_READ_CALENDAR, ref);
} // allowGetCalendar
/**
* Find the calendar, in cache or info store - cache it if newly found.
*
* @param ref
* The calendar reference.
* @return The calendar, if found.
*/
protected Calendar findCalendar(String ref)
{
Calendar calendar = null;
if ((!m_caching) || (m_calendarCache == null) || (m_calendarCache.disabled()))
{
// TODO: do we really want to do this? -ggolden
// if we have done this already in this thread, use that
calendar = (Calendar) m_threadLocalManager.get(ref);
if (calendar == null)
{
calendar = m_storage.getCalendar(ref);
// "cache" the calendar in the current service in case they are needed again in this thread...
if (calendar != null)
{
m_threadLocalManager.set(ref, calendar);
}
}
return calendar;
}
// if we have it cached, use it (even if it's cached as a null, a miss)
if (m_calendarCache.containsKey(ref))
{
calendar = (Calendar) m_calendarCache.get(ref);
}
// if not in the cache, see if we have it in our info store
if ( calendar == null ) //SAK-12447 cache.get can return null on expired
{
calendar = m_storage.getCalendar(ref);
// if so, cache it, even misses
m_calendarCache.put(ref, calendar);
}
return calendar;
} // findCalendar
/**
* Return a specific calendar.
*
* @param ref
* The calendar reference.
* @return the Calendar that has the specified name.
* @exception IdUnusedException
* If this name is not defined for any calendar.
* @exception PermissionException
* If the user does not have any permissions to the calendar.
*/
public Calendar getCalendar(String ref) throws IdUnusedException, PermissionException
{
Reference _ref = m_entityManager.newReference(ref);
if(REF_TYPE_CALENDAR_SUBSCRIPTION.equals(_ref.getSubType())) {
Calendar c = ExternalCalendarSubscriptionService.getCalendarSubscription(ref);
if (c == null) throw new IdUnusedException(ref);
return c;
}
Calendar c = findCalendar(ref);
if (c == null) throw new IdUnusedException(ref);
// check security (throws if not permitted)
unlock(AUTH_READ_CALENDAR, ref);
return c;
} // getCalendar
/**
* Remove a calendar that is locked for edit.
*
* @param calendar
* The calendar to remove.
* @exception PermissionException
* if the user does not have permission to remove a calendar.
*/
public void removeCalendar(CalendarEdit calendar) throws PermissionException
{
// check for closed edit
if (!calendar.isActiveEdit())
{
try
{
throw new Exception();
}
catch (Exception e)
{
M_log.warn("removeCalendar(): closed CalendarEdit", e);
}
return;
}
// check security
unlock(AUTH_REMOVE_CALENDAR_ANY, calendar.getReference());
m_storage.removeCalendar(calendar);
// track event
Event event = m_eventTrackingService.newEvent(EVENT_REMOVE_CALENDAR, calendar.getReference(), true);
m_eventTrackingService.post(event);
// mark the calendar as removed
((BaseCalendarEdit) calendar).setRemoved(event);
// close the edit object
((BaseCalendarEdit) calendar).closeEdit();
// remove any realm defined for this resource
try
{
m_authzGroupService.removeAuthzGroup(m_authzGroupService.getAuthzGroup(calendar.getReference()));
}
catch (AuthzPermissionException e)
{
M_log.warn("removeCalendar: removing realm for : " + calendar.getReference() + " : " + e);
}
catch (GroupNotDefinedException ignore)
{
}
} // removeCalendar
/**
* Return a List of all the defined calendars.
*
* @return a List of Calendar objects (may be empty)
*/
public List getCalendars()
{
List calendars = new Vector();
if ((!m_caching) || (m_calendarCache == null) || (m_calendarCache.disabled()))
{
calendars = m_storage.getCalendars();
return calendars;
}
// if the cache is complete, use it
if (m_calendarCache.isComplete())
{
// get just the calendars in the cache
calendars = m_calendarCache.getAll();
}
// otherwise get all the calendars from storage
else
{
// Note: while we are getting from storage, storage might change. These can be processed
// after we get the storage entries, and put them in the cache, and mark the cache complete.
// -ggolden
synchronized (m_calendarCache)
{
// if we were waiting and it's now complete...
if (m_calendarCache.isComplete())
{
// get just the calendars in the cache
calendars = m_calendarCache.getAll();
return calendars;
}
// save up any events to the cache until we get past this load
m_calendarCache.holdEvents();
calendars = m_storage.getCalendars();
// update the cache, and mark it complete
for (int i = 0; i < calendars.size(); i++)
{
Calendar calendar = (Calendar) calendars.get(i);
m_calendarCache.put(calendar.getReference(), calendar);
}
m_calendarCache.setComplete();
// now we are complete, process any cached events
m_calendarCache.processEvents();
}
}
return calendars;
} // getCalendars
/**
* check permissions for importing calendar events
*
* @param ref
* The calendar reference.
* @return true if the user is allowed to import events, false if not.
*/
public boolean allowImportCalendar(String ref)
{
return unlockCheck(AUTH_IMPORT_CALENDAR, ref);
} // allowImportCalendar
/**
* check permissions for subscribing external calendars
*
* @param ref
* The calendar reference.
* @return true if the user is allowed to subscribe external calendars, false if not.
*/
public boolean allowSubscribeCalendar(String ref)
{
return unlockCheck(AUTH_SUBSCRIBE_CALENDAR, ref);
} // allowSubscribeCalendar
/**
* check permissions for editCalendar()
*
* @param ref
* The calendar reference.
* @return true if the user is allowed to update the calendar, false if not.
*/
public boolean allowEditCalendar(String ref)
{
return unlockCheck(AUTH_MODIFY_CALENDAR_ANY, ref);
} // allowEditCalendar
/**
* check permissions for merge()
* @param ref The calendar reference.
* @return true if the user is allowed to update the calendar, false if not.
*/
public boolean allowMergeCalendar(String ref)
{
String displayMerge = getString("calendar.merge.display", "1");
if(displayMerge != null && !displayMerge.equals("1"))
return false;
return unlockCheck(AUTH_MODIFY_CALENDAR_ANY, ref);
} // allowMergeCalendar
/**
* Get a locked calendar object for editing. Must commitCalendar() to make official, or cancelCalendar() or removeCalendar() when done!
*
* @param ref
* The calendar reference.
* @return A CalendarEdit object for editing.
* @exception IdUnusedException
* if not found, or if not an CalendarEdit object
* @exception PermissionException
* if the current user does not have permission to mess with this user.
* @exception InUseException
* if the Calendar object is locked by someone else.
*/
public CalendarEdit editCalendar(String ref) throws IdUnusedException, PermissionException, InUseException
{
// check for existance
if (!m_storage.checkCalendar(ref))
{
throw new IdUnusedException(ref);
}
// check security (throws if not permitted)
unlock(AUTH_MODIFY_CALENDAR_ANY, ref);
// ignore the cache - get the calendar with a lock from the info store
CalendarEdit edit = m_storage.editCalendar(ref);
if (edit == null) throw new InUseException(ref);
((BaseCalendarEdit) edit).setEvent(EVENT_MODIFY_CALENDAR);
return edit;
} // editCalendar
/**
* Commit the changes made to a CalendarEdit object, and release the lock. The CalendarEdit is disabled, and not to be used after this call.
*
* @param edit
* The CalendarEdit object to commit.
*/
public void commitCalendar(CalendarEdit edit)
{
// check for closed edit
if (!edit.isActiveEdit())
{
M_log.warn("commitCalendar(): closed CalendarEdit " + edit.getContext());
return;
}
m_storage.commitCalendar(edit);
// track event
Event event = m_eventTrackingService.newEvent(((BaseCalendarEdit) edit).getEvent(), edit.getReference(), true);
m_eventTrackingService.post(event);
// close the edit object
((BaseCalendarEdit) edit).closeEdit();
} // commitCalendar
/**
* Cancel the changes made to a CalendarEdit object, and release the lock. The CalendarEdit is disabled, and not to be used after this call.
*
* @param edit
* The CalendarEdit object to commit.
*/
public void cancelCalendar(CalendarEdit edit)
{
// check for closed edit
if (!edit.isActiveEdit())
{
M_log.warn("cancelCalendar(): closed CalendarEventEdit " + edit.getContext());
return;
}
// release the edit lock
m_storage.cancelCalendar(edit);
// close the edit object
((BaseCalendarEdit) edit).closeEdit();
} // cancelCalendar
/**
* {@inheritDoc}
*/
public RecurrenceRule newRecurrence(String frequency)
{
if (frequency.equals(DailyRecurrenceRule.FREQ))
{
return new DailyRecurrenceRule();
}
else if (frequency.equals(WeeklyRecurrenceRule.FREQ))
{
return new WeeklyRecurrenceRule();
}
else if (frequency.equals(TThRecurrenceRule.FREQ))
{
return new TThRecurrenceRule();
}
else if (frequency.equals(MWFRecurrenceRule.FREQ))
{
return new MWFRecurrenceRule();
}
else if (frequency.equals(MonthlyRecurrenceRule.FREQ))
{
return new MonthlyRecurrenceRule();
}
else if (frequency.equals(YearlyRecurrenceRule.FREQ))
{
return new YearlyRecurrenceRule();
}
else if (frequency.equals(MWRecurrenceRule.FREQ))
{
return new MWRecurrenceRule();
}
else if (frequency.equals(SMWRecurrenceRule.FREQ))
{
return new SMWRecurrenceRule();
}
else if (frequency.equals(SMTWRecurrenceRule.FREQ))
{
return new SMTWRecurrenceRule();
}
else if (frequency.equals(STTRecurrenceRule.FREQ))
{
return new STTRecurrenceRule();
}
//add more here
return null;
}
/**
* {@inheritDoc}
*/
public RecurrenceRule newRecurrence(String frequency, int interval)
{
if (frequency.equals(DailyRecurrenceRule.FREQ))
{
return new DailyRecurrenceRule(interval);
}
else if (frequency.equals(WeeklyRecurrenceRule.FREQ))
{
return new WeeklyRecurrenceRule(interval);
}
else if (frequency.equals(TThRecurrenceRule.FREQ))
{
return new TThRecurrenceRule(interval);
}
else if (frequency.equals(MWFRecurrenceRule.FREQ))
{
return new MWFRecurrenceRule(interval);
}
else if (frequency.equals(MonthlyRecurrenceRule.FREQ))
{
return new MonthlyRecurrenceRule(interval);
}
else if (frequency.equals(YearlyRecurrenceRule.FREQ))
{
return new YearlyRecurrenceRule(interval);
}
else if (frequency.equals(MWRecurrenceRule.FREQ))
{
return new MWRecurrenceRule(interval);
}
else if (frequency.equals(SMWRecurrenceRule.FREQ))
{
return new SMWRecurrenceRule(interval);
}
else if (frequency.equals(SMTWRecurrenceRule.FREQ))
{
return new SMTWRecurrenceRule(interval);
}
else if (frequency.equals(STTRecurrenceRule.FREQ))
{
return new STTRecurrenceRule(interval);
}
//add more here
return null;
}
/**
* {@inheritDoc}
*/
public RecurrenceRule newRecurrence(String frequency, int interval, int count)
{
M_log.debug("\n"+ frequency +"\nand Internval is \n "+ interval +"count is\n " + count);
if (frequency.equals(DailyRecurrenceRule.FREQ))
{
return new DailyRecurrenceRule(interval, count);
}
else if (frequency.equals(WeeklyRecurrenceRule.FREQ))
{
return new WeeklyRecurrenceRule(interval, count);
}
else if (frequency.equals(TThRecurrenceRule.FREQ))
{
return new TThRecurrenceRule(interval,count);
}
else if (frequency.equals(MWFRecurrenceRule.FREQ))
{
return new MWFRecurrenceRule(interval,count);
}
else if (frequency.equals(MonthlyRecurrenceRule.FREQ))
{
return new MonthlyRecurrenceRule(interval, count);
}
else if (frequency.equals(YearlyRecurrenceRule.FREQ))
{
return new YearlyRecurrenceRule(interval, count);
}
else if (frequency.equals(MWRecurrenceRule.FREQ))
{
return new MWRecurrenceRule(interval, count);
}
else if (frequency.equals(SMWRecurrenceRule.FREQ))
{
return new SMWRecurrenceRule(interval, count);
}
else if (frequency.equals(SMTWRecurrenceRule.FREQ))
{
return new SMTWRecurrenceRule(interval, count);
}
else if (frequency.equals(STTRecurrenceRule.FREQ))
{
return new STTRecurrenceRule(interval, count);
}
//add more here
return null;
}
/**
* {@inheritDoc}
*/
public RecurrenceRule newRecurrence(String frequency, int interval, Time until)
{
if (frequency.equals(DailyRecurrenceRule.FREQ))
{
return new DailyRecurrenceRule(interval, until);
}
else if (frequency.equals(WeeklyRecurrenceRule.FREQ))
{
return new WeeklyRecurrenceRule(interval, until);
}
else if (frequency.equals(TThRecurrenceRule.FREQ))
{
return new TThRecurrenceRule(interval,until);
}
else if (frequency.equals(MWFRecurrenceRule.FREQ))
{
return new MWFRecurrenceRule(interval,until);
}
else if (frequency.equals(MonthlyRecurrenceRule.FREQ))
{
return new MonthlyRecurrenceRule(interval, until);
}
else if (frequency.equals(YearlyRecurrenceRule.FREQ))
{
return new YearlyRecurrenceRule(interval, until);
}
else if (frequency.equals(MWRecurrenceRule.FREQ))
{
return new MWRecurrenceRule(interval, until);
}
else if (frequency.equals(SMWRecurrenceRule.FREQ))
{
return new SMWRecurrenceRule(interval, until);
}
else if (frequency.equals(SMTWRecurrenceRule.FREQ))
{
return new SMTWRecurrenceRule(interval, until);
}
else if (frequency.equals(STTRecurrenceRule.FREQ))
{
return new STTRecurrenceRule(interval, until);
}
//add more here
return null;
}
/**********************************************************************************************************************************************************************************************************************************************************
* ResourceService implementation
*********************************************************************************************************************************************************************************************************************************************************/
/**
* {@inheritDoc}
*/
public String getLabel()
{
return "calendar";
}
/**
* {@inheritDoc}
*/
public boolean willArchiveMerge()
{
return true;
}
/**
* {@inheritDoc}
*/
public HttpAccess getHttpAccess()
{
return new HttpAccess()
{
public void handleAccess(HttpServletRequest req, HttpServletResponse res, Reference ref,
Collection copyrightAcceptedRefs) throws EntityPermissionException, EntityNotDefinedException,
EntityAccessOverloadException, EntityCopyrightException
{
String calRef = calendarReference(ref.getContext(), SiteService.MAIN_CONTAINER);
// we only access the pdf & ical reference
if ( !REF_TYPE_CALENDAR_PDF.equals(ref.getSubType()) &&
!REF_TYPE_CALENDAR_ICAL.equals(ref.getSubType()) )
throw new EntityNotDefinedException(ref.getReference());
// check if ical export is enabled
if ( REF_TYPE_CALENDAR_ICAL.equals(ref.getSubType()) &&
!getExportEnabled(calRef) )
throw new EntityNotDefinedException(ref.getReference());
try
{
Properties options = new Properties();
Enumeration e = req.getParameterNames();
while (e.hasMoreElements())
{
String key = (String) e.nextElement();
String[] values = req.getParameterValues(key);
if (values.length == 1)
{
options.put(key, values[0]);
}
else
{
StringBuilder buf = new StringBuilder();
for (int i = 0; i < values.length; i++)
{
buf.append(values[i] + "^");
}
options.put(key, buf.toString());
}
}
// We need to write to a temporary stream for better speed, plus
// so we can get a byte count. Internet Explorer has problems
// if we don't make the setContentLength() call.
ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
// Check if PDF document requested
if ( REF_TYPE_CALENDAR_PDF.equals(ref.getSubType()) )
{
res.addHeader("Content-Disposition", "inline; filename=\"schedule.pdf\"");
res.setContentType(PDF_MIME_TYPE);
printSchedule(options, outByteStream);
}
else
{
List alias = m_aliasService.getAliases(calRef);
String aliasName = "schedule.ics";
if ( ! alias.isEmpty() )
aliasName = ((Alias)alias.get(0)).getId();
// update date/time reference
Time modDate = findCalendar(calRef).getModified();
if ( modDate == null )
modDate = m_timeService.newTime(0);
res.addHeader("Content-Disposition", "inline; filename=\"" + Web.encodeFileName(req, aliasName) + "\"");
res.setContentType(ICAL_MIME_TYPE);
res.setDateHeader("Last-Modified", modDate.getTime() );
printICalSchedule(calRef, res.getOutputStream());
}
res.setContentLength(outByteStream.size());
if (outByteStream.size() > 0)
{
// Increase the buffer size for more speed.
res.setBufferSize(outByteStream.size());
}
OutputStream out = null;
try
{
out = res.getOutputStream();
if (outByteStream.size() > 0)
{
outByteStream.writeTo(out);
}
out.flush();
out.close();
}
catch (Throwable ignore)
{
}
finally
{
if (out != null)
{
try
{
out.close();
}
catch (Throwable ignore)
{
}
}
}
}
catch (Throwable t)
{
throw new EntityNotDefinedException(ref.getReference());
}
}
};
}
/**
* {@inheritDoc}
*/
public boolean parseEntityReference(String reference, Reference ref)
{
if (reference.startsWith(CalendarService.REFERENCE_ROOT))
{
String[] parts = reference.split(Entity.SEPARATOR);
String subType = null;
String context = null;
String id = null;
String container = null;
// the first part will be null, then next the service, the third will be "calendar" or "event"
if (parts.length > 2)
{
subType = parts[2];
if (REF_TYPE_CALENDAR.equals(subType) ||
REF_TYPE_CALENDAR_PDF.equals(subType) ||
REF_TYPE_CALENDAR_ICAL.equals(subType) ||
REF_TYPE_CALENDAR_SUBSCRIPTION.equals(subType))
{
// next is the context id
if (parts.length > 3)
{
context = parts[3];
// next is the optional calendar id
if (parts.length > 4)
{
id = parts[4];
}
}
}
else if (REF_TYPE_EVENT.equals(subType) || REF_TYPE_EVENT_SUBSCRIPTION.equals(subType))
{
// next three parts are context, channel (container) and event id
if (parts.length > 5)
{
context = parts[3];
container = parts[4];
id = parts[5];
}
}
else
M_log.warn(".parseEntityReference(): unknown calendar subtype: " + subType + " in ref: " + reference);
}
// Translate context alias into site id if necessary
if ((context != null) && (context.length() > 0))
{
if (!m_siteService.siteExists(context))
{
try
{
Calendar calendarObj = getCalendar(m_aliasService.getTarget(context));
context = calendarObj.getContext();
}
catch (IdUnusedException ide) {
M_log.info(".parseEntityReference():"+ide.toString());
return false;
}
catch (PermissionException pe) {
M_log.info(".parseEntityReference():"+pe.toString());
return false;
}
catch (Exception e)
{
M_log.warn(".parseEntityReference(): ", e);
return false;
}
}
}
// if context still isn't valid, then no valid alias or site was specified
if (!m_siteService.siteExists(context))
{
M_log.warn(".parseEntityReference() no valid site or alias: " + context);
return false;
}
// build updated reference
ref.set(APPLICATION_ID, subType, id, container, context);
return true;
}
return false;
}
/**
* {@inheritDoc}
*/
public String getEntityDescription(Reference ref)
{
// double check that it's mine
if (!APPLICATION_ID.equals(ref.getType())) return null;
String rv = "Calendar: " + ref.getReference();
try
{
// if this is a calendar
if (REF_TYPE_CALENDAR.equals(ref.getSubType()) || REF_TYPE_CALENDAR_PDF.equals(ref.getSubType()))
{
Calendar cal = getCalendar(ref.getReference());
rv = "Calendar: " + cal.getId() + " (" + cal.getContext() + ")";
}
// otherwise an event
else if (REF_TYPE_EVENT.equals(ref.getSubType()))
{
rv = "Event: " + ref.getReference();
}
}
catch (PermissionException ignore) {}
catch (IdUnusedException ignore) {}
catch (NullPointerException ignore) {}
return rv;
}
/**
* {@inheritDoc}
*/
public ResourceProperties getEntityResourceProperties(Reference ref)
{
// double check that it's mine
if (!APPLICATION_ID.equals(ref.getType())) return null;
ResourceProperties props = null;
try
{
// if this is a calendar
if (REF_TYPE_CALENDAR.equals(ref.getSubType()) || REF_TYPE_CALENDAR_PDF.equals(ref.getSubType()) || REF_TYPE_CALENDAR_SUBSCRIPTION.equals(ref.getSubType()))
{
Calendar cal = getCalendar(ref.getReference());
props = cal.getProperties();
}
// otherwise an event
else if (REF_TYPE_EVENT.equals(ref.getSubType()))
{
Calendar cal = getCalendar(calendarReference(ref.getContext(), ref.getContainer()));
CalendarEvent event = cal.getEvent(ref.getId());
props = event.getProperties();
}
else if (REF_TYPE_EVENT_SUBSCRIPTION.equals(ref.getSubType()))
{
Calendar cal = getCalendar(calendarSubscriptionReference(ref.getContext(), ref.getContainer()));
CalendarEvent event = cal.getEvent(ref.getId());
props = event.getProperties();
}
else
M_log.warn(".getEntityResourceProperties(): unknown calendar ref subtype: " + ref.getSubType() + " in ref: "
+ ref.getReference());
}
catch (PermissionException e)
{
M_log.warn(".getEntityResourceProperties(): " + e);
}
catch (IdUnusedException ignore)
{
// This just means that the resource once pointed to as an attachment or something has been deleted.
// m_logger(this + ".getProperties(): " + e);
}
catch (NullPointerException e)
{
M_log.warn(".getEntityResourceProperties(): " + e);
}
return props;
}
/**
* {@inheritDoc}
*/
public Entity getEntity(Reference ref)
{
// double check that it's mine
if (!APPLICATION_ID.equals(ref.getType())) return null;
Entity rv = null;
try
{
// if this is a calendar
if (REF_TYPE_CALENDAR.equals(ref.getSubType()) || REF_TYPE_CALENDAR_PDF.equals(ref.getSubType()) || REF_TYPE_CALENDAR_SUBSCRIPTION.equals(ref.getSubType()))
{
rv = getCalendar(ref.getReference());
}
// otherwise a event
else if (REF_TYPE_EVENT.equals(ref.getSubType()))
{
Calendar cal = getCalendar(calendarReference(ref.getContext(), ref.getContainer()));
rv = cal.getEvent(ref.getId());
}
else if (REF_TYPE_EVENT_SUBSCRIPTION.equals(ref.getSubType()))
{
Calendar cal = getCalendar(calendarSubscriptionReference(ref.getContext(), ref.getContainer()));
rv = cal.getEvent(ref.getId());
}
else
M_log.warn("getEntity(): unknown calendar ref subtype: " + ref.getSubType() + " in ref: " + ref.getReference());
}
catch (PermissionException e)
{
M_log.warn("getEntity(): " + e);
}
catch (IdUnusedException e)
{
M_log.warn("getEntity(): " + e);
}
catch (NullPointerException e)
{
M_log.warn(".getEntity(): " + e);
}
return rv;
}
/**
* {@inheritDoc}
*/
public Collection getEntityAuthzGroups(Reference ref, String userId)
{
// double check that it's mine
if (!APPLICATION_ID.equals(ref.getType())) return null;
Collection rv = new Vector();
// for events:
// if access set to SITE (or PUBLIC), use the event, calendar and site authzGroups.
// if access set to GROUPED, use the event, and the groups, but not the calendar or site authzGroups.
// if the user has SECURE_ALL_GROUPS in the context, ignore GROUPED access and treat as if SITE
// for Calendars: use the calendar and site authzGroups.
try
{
// for event
if (REF_TYPE_EVENT.equals(ref.getSubType()))
{
// event
rv.add(ref.getReference());
boolean grouped = false;
Collection groups = null;
// check SECURE_ALL_GROUPS - if not, check if the event has groups or not
// TODO: the last param needs to be a ContextService.getRef(ref.getContext())... or a ref.getContextAuthzGroup() -ggolden
if ((userId == null) || ((!m_securityService.isSuperUser(userId)) && (!m_authzGroupService.isAllowed(userId, SECURE_ALL_GROUPS, m_siteService.siteReference(ref.getContext())))))
{
// get the calendar to get the message to get group information
String calendarRef = calendarReference(ref.getContext(), ref.getContainer());
Calendar c = findCalendar(calendarRef);
if (c != null)
{
CalendarEvent e = ((BaseCalendarEdit) c).findEvent(ref.getId());
if (e != null)
{
grouped = EventAccess.GROUPED == e.getAccess();
groups = e.getGroups();
}
}
}
if (grouped)
{
// groups
rv.addAll(groups);
}
// not grouped
else
{
// calendar
rv.add(calendarReference(ref.getContext(), ref.getContainer()));
// site
ref.addSiteContextAuthzGroup(rv);
}
}
// for calendar
else
{
// calendar
rv.add(calendarReference(ref.getContext(), ref.getId()));
// site
ref.addSiteContextAuthzGroup(rv);
}
}
catch (Throwable e)
{
M_log.warn("getEntityAuthzGroups(): " + e);
}
return rv;
}
/**
* {@inheritDoc}
*/
public String getEntityUrl(Reference ref)
{
// double check that it's mine
if (!APPLICATION_ID.equals(ref.getType())) return null;
String rv = null;
try
{
// if this is a calendar
if (REF_TYPE_CALENDAR.equals(ref.getSubType()) || REF_TYPE_CALENDAR_PDF.equals(ref.getSubType()))
{
Calendar cal = getCalendar(ref.getReference());
rv = cal.getUrl();
}
// otherwise a event
else if (REF_TYPE_EVENT.equals(ref.getSubType()))
{
Calendar cal = getCalendar(calendarReference(ref.getContext(), ref.getContainer()));
CalendarEvent event = cal.getEvent(ref.getId());
rv = event.getUrl();
}
else
M_log.warn("getEntityUrl(): unknown calendar ref subtype: " + ref.getSubType() + " in ref: " + ref.getReference());
}
catch (PermissionException e)
{
M_log.warn(".getEntityUrl(): " + e);
}
catch (IdUnusedException e)
{
M_log.warn(".getEntityUrl(): " + e);
}
catch (NullPointerException e)
{
M_log.warn(".getEntityUrl(): " + e);
}
return rv;
}
/**
* {@inheritDoc}
*/
public String archive(String siteId, Document doc, Stack stack, String archivePath, List attachments)
{
// prepare the buffer for the results log
StringBuilder results = new StringBuilder();
// start with an element with our very own (service) name
Element element = doc.createElement(CalendarService.class.getName());
((Element) stack.peek()).appendChild(element);
stack.push(element);
// get the channel associated with this site
String calRef = calendarReference(siteId, SiteService.MAIN_CONTAINER);
results.append("archiving calendar " + calRef + ".\n");
try
{
// do the channel
Calendar cal = getCalendar(calRef);
Element containerElement = cal.toXml(doc, stack);
stack.push(containerElement);
// do the messages in the channel
Iterator events = cal.getEvents(null, null).iterator();
while (events.hasNext())
{
CalendarEvent event = (CalendarEvent) events.next();
event.toXml(doc, stack);
// collect message attachments
List atts = event.getAttachments();
for (int i = 0; i < atts.size(); i++)
{
Reference ref = (Reference) atts.get(i);
// if it's in the attachment area, and not already in the list
if ((ref.getReference().startsWith("/content/attachment/")) && (!attachments.contains(ref)))
{
attachments.add(ref);
}
}
}
stack.pop();
}
catch (Exception any)
{
M_log.warn(".archve: exception archiving messages for service: " + CalendarService.class.getName() + " channel: "
+ calRef);
}
stack.pop();
return results.toString();
}
/**
* {@inheritDoc}
*/
public String merge(String siteId, Element root, String archivePath, String fromSiteId, Map attachmentNames, Map userIdTrans,
Set userListAllowImport)
{
// prepare the buffer for the results log
StringBuilder results = new StringBuilder();
// get the channel associated with this site
String calendarRef = calendarReference(siteId, SiteService.MAIN_CONTAINER);
int count = 0;
try
{
Calendar calendar = null;
try
{
calendar = getCalendar(calendarRef);
}
catch (IdUnusedException e)
{
CalendarEdit edit = addCalendar(calendarRef);
commitCalendar(edit);
calendar = edit;
}
// pass the DOM to get new event ids, and adjust attachments
NodeList children2 = root.getChildNodes();
int length2 = children2.getLength();
for (int i2 = 0; i2 < length2; i2++)
{
Node child2 = children2.item(i2);
if (child2.getNodeType() == Node.ELEMENT_NODE)
{
Element element2 = (Element) child2;
// get the "calendar" child
if (element2.getTagName().equals("calendar"))
{
NodeList children3 = element2.getChildNodes();
final int length3 = children3.getLength();
for (int i3 = 0; i3 < length3; i3++)
{
Node child3 = children3.item(i3);
if (child3.getNodeType() == Node.ELEMENT_NODE)
{
Element element3 = (Element) child3;
if (element3.getTagName().equals("properties"))
{
NodeList children8 = element3.getChildNodes();
final int length8 = children8.getLength();
for (int i8 = 0; i8 < length8; i8++)
{
Node child8 = children8.item(i8);
if (child8.getNodeType() == Node.ELEMENT_NODE)
{
Element element8 = (Element) child8;
// for "event" children
if (element8.getTagName().equals("property"))
{
String pName = element8.getAttribute("name");
if ((pName != null) && (pName.equalsIgnoreCase("CHEF:calendar-fields")))
{
String pValue = element8.getAttribute("value");
if ("BASE64".equalsIgnoreCase(element8.getAttribute("enc")))
{
pValue = Xml.decodeAttribute(element8, "value");
}
if (pValue != null)
{
try
{
CalendarEdit calEdit = editCalendar(calendarRef);
String calFields = StringUtils.trimToEmpty(calEdit.getEventFields());
if (calFields != null)
pValue = calFields + ADDFIELDS_DELIMITER + pValue;
calEdit.setEventFields(pValue);
commitCalendar(calEdit);
}
catch (Exception e)
{
M_log.warn(".merge() when editing calendar: exception: ", e);
}
}
}
}
}
}
}
// for "event" children
if (element3.getTagName().equals("event"))
{
// adjust the id
String oldId = element3.getAttribute("id");
String newId = getUniqueId();
element3.setAttribute("id", newId);
// get the attachment kids
NodeList children5 = element3.getChildNodes();
final int length5 = children5.getLength();
for (int i5 = 0; i5 < length5; i5++)
{
Node child5 = children5.item(i5);
if (child5.getNodeType() == Node.ELEMENT_NODE)
{
Element element5 = (Element) child5;
// for "attachment" children
if (element5.getTagName().equals("attachment"))
{
// map the attachment area folder name
String oldUrl = element5.getAttribute("relative-url");
if (oldUrl.startsWith("/content/attachment/"))
{
String newUrl = (String) attachmentNames.get(oldUrl);
if (newUrl != null)
{
if (newUrl.startsWith("/attachment/")) newUrl = "/content".concat(newUrl);
element5.setAttribute("relative-url", Validator.escapeQuestionMark(newUrl));
}
}
// map any references to this site to the new site id
else if (oldUrl.startsWith("/content/group/" + fromSiteId + "/"))
{
String newUrl = "/content/group/" + siteId
+ oldUrl.substring(15 + fromSiteId.length());
element5.setAttribute("relative-url", Validator.escapeQuestionMark(newUrl));
}
}
}
}
// create a new message in the calendar
CalendarEventEdit edit = calendar.mergeEvent(element3);
calendar.commitEvent(edit);
count++;
}
}
}
}
}
}
}
catch (Exception any)
{
M_log.warn(".merge(): exception: ", any);
}
results.append("merging calendar " + calendarRef + " (" + count + ") messages.\n");
return results.toString();
}
/**
* {@inheritDoc}
*/
public void transferCopyEntities(String fromContext, String toContext, List resourceIds)
{
transferCopyEntitiesRefMigrator(fromContext, toContext, resourceIds);
}
public Map<String, String> transferCopyEntitiesRefMigrator(String fromContext, String toContext, List resourceIds)
{
Map<String, String> transversalMap = new HashMap<String, String>();
// get the channel associated with this site
String oCalendarRef = calendarReference(fromContext, SiteService.MAIN_CONTAINER);
Calendar oCalendar = null;
try
{
oCalendar = getCalendar(oCalendarRef);
// new calendar
CalendarEdit nCalendar = null;
String nCalendarRef = calendarReference(toContext, SiteService.MAIN_CONTAINER);
try
{
nCalendar = editCalendar(nCalendarRef);
}
catch (IdUnusedException e)
{
try
{
nCalendar = addCalendar(nCalendarRef);
}
catch (IdUsedException ignore) {}
catch (IdInvalidException ignore) {}
}
catch (PermissionException ignore) {}
catch (InUseException ignore) {}
if (nCalendar != null)
{
List oEvents = oCalendar.getEvents(null, null);
String oFields = StringUtils.trimToNull(oCalendar.getEventFields());
String nFields = StringUtils.trimToNull(nCalendar.getEventFields());
String allFields = "";
if (oFields != null)
{
if (nFields != null)
{
allFields = nFields + ADDFIELDS_DELIMITER + oFields;
}
else
{
allFields = oFields;
}
nCalendar.setEventFields(allFields);
}
for (int i = 0; i < oEvents.size(); i++)
{
CalendarEvent oEvent = (CalendarEvent) oEvents.get(i);
try
{
// Skip calendar events based on assignment due dates
String assignmentId = oEvent.getField(CalendarUtil.NEW_ASSIGNMENT_DUEDATE_CALENDAR_ASSIGNMENT_ID);
if (assignmentId != null && assignmentId.length() > 0)
continue;
CalendarEvent e = nCalendar.addEvent(oEvent.getRange(), oEvent.getDisplayName(), oEvent.getDescription(),
oEvent.getType(), oEvent.getLocation(), oEvent.getAttachments());
try
{
BaseCalendarEventEdit eEdit = (BaseCalendarEventEdit) nCalendar.getEditEvent(e.getId(),EVENT_ADD_CALENDAR );
// properties
ResourcePropertiesEdit p = eEdit.getPropertiesEdit();
p.clear();
p.addAll(oEvent.getProperties());
// attachment
List oAttachments = eEdit.getAttachments();
List nAttachments = m_entityManager.newReferenceList();
for (int n = 0; n < oAttachments.size(); n++)
{
Reference oAttachmentRef = (Reference) oAttachments.get(n);
String oAttachmentId = ((Reference) oAttachments.get(n)).getId();
if (oAttachmentId.indexOf(fromContext) != -1)
{
// replace old site id with new site id in attachments
String nAttachmentId = oAttachmentId.replaceAll(fromContext, toContext);
try
{
ContentResource attachment = contentHostingService.getResource(nAttachmentId);
nAttachments.add(m_entityManager.newReference(attachment.getReference()));
}
catch (IdUnusedException ee)
{
try
{
ContentResource oAttachment = contentHostingService.getResource(oAttachmentId);
try
{
if (contentHostingService.isAttachmentResource(nAttachmentId))
{
// add the new resource into attachment collection area
ContentResource attachment = contentHostingService.addAttachmentResource(
Validator.escapeResourceName(oAttachment.getProperties().getProperty(ResourceProperties.PROP_DISPLAY_NAME)),
toContext,
m_toolManager.getTool("sakai.schedule").getTitle(),
oAttachment.getContentType(),
oAttachment.getContent(),
oAttachment.getProperties());
// add to attachment list
nAttachments.add(m_entityManager.newReference(attachment.getReference()));
}
else
{
// add the new resource into resource area
ContentResource attachment = contentHostingService.addResource(
Validator.escapeResourceName(oAttachment.getProperties().getProperty(ResourceProperties.PROP_DISPLAY_NAME)),
toContext,
1,
oAttachment.getContentType(),
oAttachment.getContent(),
oAttachment.getProperties(),
NotificationService.NOTI_NONE);
// add to attachment list
nAttachments.add(m_entityManager.newReference(attachment.getReference()));
}
}
catch (Exception eeAny)
{
// if the new resource cannot be added
M_log.warn(" cannot add new attachment with id=" + nAttachmentId);
}
}
catch (Exception eAny)
{
// if cannot find the original attachment, do nothing.
M_log.warn(" cannot find the original attachment with id=" + oAttachmentId);
}
}
catch (Exception any)
{
M_log.warn(this + any.getMessage());
}
}
else
{
nAttachments.add(oAttachmentRef);
}
}
eEdit.replaceAttachments(nAttachments);
// recurrence rules
RecurrenceRule rule = oEvent.getRecurrenceRule();
eEdit.setRecurrenceRule(rule);
RecurrenceRule exRule = oEvent.getExclusionRule();
eEdit.setExclusionRule(exRule);
// commit new event
m_storage.commitEvent(nCalendar, eEdit);
}
catch (InUseException ignore) {}
}
catch (PermissionException ignore) {}
}
// commit new calendar
m_storage.commitCalendar(nCalendar);
((BaseCalendarEdit) nCalendar).closeEdit();
} // if
}
catch (IdUnusedException ignore) {}
catch (PermissionException ignore) {}
return transversalMap;
} // importResources
/**
* {@inheritDoc}
*/
public void updateEntityReferences(String toContext, Map<String, String> transversalMap){
if(transversalMap != null && transversalMap.size() > 0){
Set<Entry<String, String>> entrySet = (Set<Entry<String, String>>) transversalMap.entrySet();
try
{
String toSiteId = toContext;
String calendarId = calendarReference(toSiteId, SiteService.MAIN_CONTAINER);
Calendar calendarObj = getCalendar(calendarId);
List calEvents = calendarObj.getEvents(null,null);
for (int i = 0; i < calEvents.size(); i++)
{
try
{
CalendarEvent ce = (CalendarEvent) calEvents.get(i);
String msgBodyFormatted = ce.getDescriptionFormatted();
boolean updated = false;
/*
Iterator<Entry<String, String>> entryItr = entrySet.iterator();
while(entryItr.hasNext()) {
Entry<String, String> entry = (Entry<String, String>) entryItr.next();
String fromContextRef = entry.getKey();
if(msgBodyFormatted.contains(fromContextRef)){
msgBodyFormatted = msgBodyFormatted.replace(fromContextRef, entry.getValue());
updated = true;
}
}
*/
StringBuffer msgBodyPreMigrate = new StringBuffer(msgBodyFormatted);
msgBodyFormatted = LinkMigrationHelper.editLinks(msgBodyFormatted, "sam_pub");
msgBodyFormatted = LinkMigrationHelper.editLinks(msgBodyFormatted, "/posts/");
msgBodyFormatted = LinkMigrationHelper.miagrateAllLinks(entrySet, msgBodyFormatted);
if(!msgBodyFormatted.equals(msgBodyPreMigrate.toString())){
// if(updated){
CalendarEventEdit edit = calendarObj.getEditEvent(ce.getId(), org.sakaiproject.calendar.api.CalendarService.EVENT_MODIFY_CALENDAR);
edit.setDescriptionFormatted(msgBodyFormatted);
calendarObj.commitEvent(edit);
}
}
catch (IdUnusedException e)
{
M_log.debug(".IdUnusedException " + e);
}
catch (PermissionException e)
{
M_log.debug(".PermissionException " + e);
}
catch (InUseException e)
{
M_log.debug(".InUseException delete" + e);
}
}
}
catch (Exception e)
{
M_log.info("importSiteClean: End removing Calendar data" + e);
}
}
}
/**
* @inheritDoc
*/
public String[] myToolIds()
{
String[] toolIds = { "sakai.schedule" };
return toolIds;
}
/**
* {@inheritDoc}
*/
public void contextCreated(String context, boolean toolPlacement)
{
if (toolPlacement) enableSchedule(context);
}
/**
* {@inheritDoc}
*/
public void contextUpdated(String context, boolean toolPlacement)
{
if (toolPlacement) enableSchedule(context);
}
/**
* {@inheritDoc}
*/
public void contextDeleted(String context, boolean toolPlacement)
{
disableSchedule(context);
}
/**
* Setup a calendar for the site.
*
* @param site
* The site.
*/
protected void enableSchedule(String context)
{
// form the calendar name
String calRef = calendarReference(context, SiteService.MAIN_CONTAINER);
// see if there's a calendar
try
{
getCalendar(calRef);
}
catch (IdUnusedException un)
{
try
{
// create a calendar
CalendarEdit edit = addCalendar(calRef);
commitCalendar(edit);
}
catch (IdUsedException ignore) {}
catch (IdInvalidException ignore) {}
}
catch (PermissionException ignore) {}
}
/**
* Remove a calendar for the site.
*
* @param site
* The site.
*/
protected void disableSchedule(String context)
{
// TODO: currently we do not remove a calendar when the tool is removed from the site or the site is deleted -ggolden
}
/**********************************************************************************************************************************************************************************************************************************************************
* Calendar implementation
*********************************************************************************************************************************************************************************************************************************************************/
public class BaseCalendarEdit extends Observable implements CalendarEdit, SessionBindingListener
{
/** The context in which this calendar exists. */
protected String m_context = null;
/** Store the unique-in-context calendar id. */
protected String m_id = null;
/** The properties. */
protected ResourcePropertiesEdit m_properties = null;
/** When true, the calendar has been removed. */
protected boolean m_isRemoved = false;
/** The event code for this edit. */
protected String m_event = null;
/** Active flag. */
protected boolean m_active = false;
/**
* Construct with an id.
*
* @param ref
* The calendar reference.
*/
public BaseCalendarEdit(String ref)
{
// set the ids
Reference r = m_entityManager.newReference(ref);
m_context = r.getContext();
m_id = r.getId();
// setup for properties
m_properties = new BaseResourcePropertiesEdit();
} // BaseCalendarEdit
/**
* Construct as a copy of another.
*
* @param id
* The other to copy.
*/
public BaseCalendarEdit(Calendar other)
{
// set the ids
m_context = other.getContext();
m_id = other.getId();
// setup for properties
m_properties = new BaseResourcePropertiesEdit();
m_properties.addAll(other.getProperties());
} // BaseCalendarEdit
protected BaseCalendarEdit() {
m_properties = new BaseResourcePropertiesEdit();
}
/**
* Construct from a calendar (and possibly events) already defined in XML in a DOM tree. The Calendar is added to storage.
*
* @param el
* The XML DOM element defining the calendar.
*/
public BaseCalendarEdit(Element el)
{
// setup for properties
m_properties = new BaseResourcePropertiesEdit();
m_id = el.getAttribute("id");
m_context = el.getAttribute("context");
// the children (properties, ignore events)
NodeList children = el.getChildNodes();
final int length = children.getLength();
for (int i = 0; i < length; i++)
{
Node child = children.item(i);
if (child.getNodeType() != Node.ELEMENT_NODE) continue;
Element element = (Element) child;
// look for properties (ignore possible "event" entries)
if (element.getTagName().equals("properties"))
{
// re-create properties
m_properties = new BaseResourcePropertiesEdit(element);
}
}
} // BaseCalendarEdit
/**
* Set the calendar as removed.
*
* @param event
* The tracking event associated with this action.
*/
public void setRemoved(Event event)
{
m_isRemoved = true;
// notify observers
notify(event);
// now clear observers
deleteObservers();
} // setRemoved
/**
* Access the context of the resource.
*
* @return The context.
*/
public String getContext()
{
return m_context;
} // getContext
/**
* Access the id of the resource.
*
* @return The id.
*/
public String getId()
{
return m_id;
} // getId
/**
* Access the URL which can be used to access the resource.
*
* @return The URL which can be used to access the resource.
*/
public String getUrl()
{
return getAccessPoint(false) + SEPARATOR + getId() + SEPARATOR; // %%% needs fixing re: context
} // getUrl
/**
* Access the internal reference which can be used to access the resource from within the system.
*
* @return The the internal reference which can be used to access the resource from within the system.
*/
public String getReference()
{
return calendarReference(m_context, m_id);
} // getReference
/**
* @inheritDoc
*/
public String getReference(String rootProperty)
{
return getReference();
}
/**
* @inheritDoc
*/
public String getUrl(String rootProperty)
{
return getUrl();
}
/**
* Access the collection's properties.
*
* @return The collection's properties.
*/
public ResourceProperties getProperties()
{
return m_properties;
} // getProperties
/**
** check if this calendar allows ical exports
** @return true if the calender allows exports; false if not
**/
public boolean getExportEnabled()
{
String enable = m_properties.getProperty(CalendarService.PROP_ICAL_ENABLE);
return Boolean.valueOf(enable);
}
/**
** set if this calendar allows ical exports
** @return true if the calender allows exports; false if not
**/
public void setExportEnabled( boolean enable )
{
m_properties.addProperty(CalendarService.PROP_ICAL_ENABLE, String.valueOf(enable));
}
/**
** Get the time of the last modify to this calendar
** @return String representation of current time (may be null if not initialized)
**/
public Time getModified()
{
String timeStr = m_properties.getProperty(ResourceProperties.PROP_MODIFIED_DATE);
if ( timeStr == null )
return null;
else
return m_timeService.newTimeGmt(timeStr);
}
/**
** Set the time of the last modify for this calendar to now
** @return true if successful; false if not
**/
public void setModified()
{
String currentUser = m_sessionManager.getCurrentSessionUserId();
String now = m_timeService.newTime().toString();
m_properties.addProperty(ResourceProperties.PROP_MODIFIED_BY, currentUser);
m_properties.addProperty(ResourceProperties.PROP_MODIFIED_DATE, now);
}
/**
* check permissions for getEvents() and getEvent().
*
* @return true if the user is allowed to get events from the calendar, false if not.
*/
public boolean allowGetEvents()
{
return unlockCheck(AUTH_READ_CALENDAR, getReference());
} // allowGetEvents
/**
* {@inheritDoc}
*/
public boolean allowGetEvent(String eventId)
{
return unlockCheck(AUTH_READ_CALENDAR, eventReference(m_context, m_id, eventId));
}
/**
* Return a List of all or filtered events in the calendar. The order in which the events will be found in the iteration is by event start date.
*
* @param range
* A time range to limit the iterated events. May be null; all events will be returned.
* @param filter
* A filtering object to accept events into the iterator, or null if no filtering is desired.
* @return a List of all or filtered CalendarEvents in the calendar (may be empty).
* @exception PermissionException
* if the user does not have read permission to the calendar.
*/
public List getEvents(TimeRange range, Filter filter) throws PermissionException
{
// check security (throws if not permitted)
unlock(AUTH_READ_CALENDAR, getReference());
List events = new Vector();
if ((!m_caching) || (m_calendarCache == null) || (m_calendarCache.disabled()))
{
if ( range != null )
events = m_storage.getEvents(this, range.firstTime().getTime(), range.lastTime().getTime() );
else
events = m_storage.getEvents(this);
}
else
{
// find the event cache
Cache eventCache = (Cache) m_eventCaches.get(getReference());
if (eventCache == null)
{
synchronized (m_eventCaches)
{
// check again
eventCache = (Cache) m_eventCaches.get(getReference());
// if still not there, make one
if (eventCache == null)
{
eventCache = m_memoryService
.newCache(
"org.sakaiproject.calendar.api.CalendarService.eventCache",
service(), eventReference(
m_context, m_id, ""));
m_eventCaches.put(getReference(), eventCache);
}
}
}
// if the cache is complete, use it
if (eventCache.isComplete())
{
// get just this calendar's events
events = eventCache.getAll();
}
// otherwise get all the events from storage
else
{
// Note: while we are getting from storage, storage might change. These can be processed
// after we get the storage entries, and put them in the cache, and mark the cache complete.
// -ggolden
synchronized (eventCache)
{
// if we were waiting and it's now complete...
if (eventCache.isComplete())
{
// get just this calendar's events
events = eventCache.getAll();
}
else
{
// save up any events to the cache until we get past this load
eventCache.holdEvents();
// get all the events for the calendar
events = m_storage.getEvents(this);
// update the cache, and mark it complete
for (int i = 0; i < events.size(); i++)
{
CalendarEvent event = (CalendarEvent) events.get(i);
eventCache.put(event.getReference(), event);
}
eventCache.setComplete();
// now we are complete, process any cached events
eventCache.processEvents();
}
}
}
}
// now filter out the events to just those in the range
// Note: if no range, we won't filter, which means we don't expand recurring events, but just
// return it as a single event. This is very good for an archive... -ggolden
if (range != null)
{
events = filterEvents(events, range);
}
if (events.size() == 0) return events;
// filter out based on the filter
if (filter != null)
{
List filtered = new Vector();
for (int i = 0; i < events.size(); i++)
{
Event event = (Event) events.get(i);
if (filter.accept(event)) filtered.add(event);
}
if (filtered.size() == 0) return filtered;
events = filtered;
}
// remove any events that are grouped, and that the current user does not have permission to see
Collection groupsAllowed = getGroupsAllowGetEvent();
List allowedEvents = new Vector();
for (Iterator i = events.iterator(); i.hasNext();)
{
CalendarEvent event = (CalendarEvent) i.next();
if (event.getAccess() == EventAccess.SITE)
{
allowedEvents.add(event);
}
else
{
// if the user's Groups overlap the event's group refs it's grouped to, keep it
if (EntityCollections.isIntersectionEntityRefsToEntities(event.getGroups(), groupsAllowed))
{
allowedEvents.add(event);
}
}
}
// sort - natural order is date ascending
Collections.sort(allowedEvents);
return allowedEvents;
} // getEvents
/**
* Filter the events to only those in the time range.
*
* @param events
* The full list of events.
* @param range
* The time range.
* @return A list of events from the incoming list that overlap the given time range.
*/
protected List filterEvents(List events, TimeRange range)
{
List filtered = new Vector();
for (int i = 0; i < events.size(); i++)
{
CalendarEvent event = (CalendarEvent) events.get(i);
// resolve the event to the list of events in this range
List resolved = ((BaseCalendarEventEdit) event).resolve(range);
filtered.addAll(resolved);
}
return filtered;
} // filterEvents
/**
* Return a specific calendar event, as specified by event id.
*
* @param eventId
* The id of the event to get.
* @return the CalendarEvent that has the specified id.
* @exception IdUnusedException
* If this id is not a defined event in this calendar.
* @exception PermissionException
* If the user does not have any permissions to read the calendar.
*/
public CalendarEvent getEvent(String eventId) throws IdUnusedException, PermissionException
{
// check security on the event (throws if not permitted)
unlock(AUTH_READ_CALENDAR, eventReference(m_context, m_id, eventId));
CalendarEvent e = findEvent(eventId);
if (e == null) throw new IdUnusedException(eventId);
return e;
} // getEvent
/**
* check permissions for addEvent().
*
* @return true if the user is allowed to addEvent(...), false if not.
*/
public boolean allowAddEvent()
{
// checking allow at the channel (site) level
if (allowAddCalendarEvent()) return true;
// if not, see if the user has any groups to which adds are allowed
return (!getGroupsAllowAddEvent().isEmpty());
} // allowAddEvent
/**
* @inheritDoc
*/
public boolean allowAddCalendarEvent()
{
// check for events that will be calendar (site) -wide:
// base the check for SECURE_ADD on the site and the calendar only (not the groups).
// check security on the calendar (throws if not permitted)
return unlockCheck(AUTH_ADD_CALENDAR, getReference());
}
/**
* Add a new event to this calendar.
*
* @param range
* The event's time range.
* @param displayName
* The event's display name (PROP_DISPLAY_NAME) property value.
* @param description
* The event's description as plain text (PROP_DESCRIPTION) property value.
* @param type
* The event's calendar event type (PROP_CALENDAR_TYPE) property value.
* @param location
* The event's calendar event location (PROP_CALENDAR_LOCATION) property value.
* @param attachments
* The event attachments, a vector of Reference objects.
* @return The newly added event.
* @exception PermissionException
* If the user does not have permission to modify the calendar.
*/
public CalendarEvent addEvent(TimeRange range, String displayName, String description, String type, String location, EventAccess access, Collection groups,
List attachments) throws PermissionException
{
// securtiy check (any sort (group, site) of add)
if (!allowAddEvent())
{
throw new PermissionException(m_sessionManager.getCurrentSessionUserId(), eventId(SECURE_ADD), getReference());
}
// make one
// allocate a new unique event id
String id = getUniqueId();
// get a new event in the info store
CalendarEventEdit edit = m_storage.putEvent(this, id);
((BaseCalendarEventEdit) edit).setEvent(EVENT_ADD_CALENDAR);
// set it up
edit.setRange(range);
edit.setDisplayName(displayName);
edit.setDescription(description);
edit.setType(type);
edit.setLocation(location);
edit.setCreator();
// for site...
if (access == EventAccess.SITE)
{
// if not allowd to SITE, will throw permission exception
try
{
edit.clearGroupAccess();
}
catch (PermissionException e)
{
cancelEvent(edit);
throw new PermissionException(m_sessionManager.getCurrentSessionUserId(), eventId(SECURE_ADD), getReference());
}
}
// for grouped...
else
{
// if not allowed to GROUP, will throw permission exception
try
{
edit.setGroupAccess(groups,true);
}
catch (PermissionException e)
{
cancelEvent(edit);
throw new PermissionException(m_sessionManager.getCurrentSessionUserId(), eventId(SECURE_ADD), getReference());
}
}
edit.replaceAttachments(attachments);
// commit it
commitEvent(edit);
return edit;
} // addEvent
/**
* Add a new event to this calendar.
*
* @param range
* The event's time range.
* @param displayName
* The event's display name (PROP_DISPLAY_NAME) property value.
* @param description
* The event's description as plain text (PROP_DESCRIPTION) property value.
* @param type
* The event's calendar event type (PROP_CALENDAR_TYPE) property value.
* @param location
* The event's calendar event location (PROP_CALENDAR_LOCATION) property value.
* @param attachments
* The event attachments, a vector of Reference objects.
* @return The newly added event.
* @exception PermissionException
* If the user does not have permission to modify the calendar.
*/
public CalendarEvent addEvent(TimeRange range, String displayName, String description, String type, String location,
List attachments) throws PermissionException
{
// make one
CalendarEventEdit edit = addEvent();
// set it up
edit.setRange(range);
edit.setDisplayName(displayName);
edit.setDescription(description);
edit.setType(type);
edit.setLocation(location);
edit.replaceAttachments(attachments);
// commit it
commitEvent(edit);
return edit;
} // addEvent
/**
* Add a new event to this calendar. Must commitEvent() to make official, or cancelEvent() when done!
*
* @return The newly added event, locked for update.
* @exception PermissionException
* If the user does not have write permission to the calendar.
*/
public CalendarEventEdit addEvent() throws PermissionException
{
// check security (throws if not permitted)
unlock(AUTH_ADD_CALENDAR, getReference());
// allocate a new unique event id
String id = getUniqueId();
// get a new event in the info store
CalendarEventEdit event = m_storage.putEvent(this, id);
((BaseCalendarEventEdit) event).setEvent(EVENT_ADD_CALENDAR);
return event;
} // addEvent
/**
* Merge in a new event as defined in the xml.
*
* @param el
* The event information in XML in a DOM element.
* @exception PermissionException
* If the user does not have write permission to the calendar.
* @exception IdUsedException
* if the user id is already used.
*/
public CalendarEventEdit mergeEvent(Element el) throws PermissionException, IdUsedException
{
CalendarEvent eventFromXml = (CalendarEvent) newResource(this, el);
// check security
if ( ! allowAddEvent() )
throw new PermissionException(m_sessionManager.getCurrentSessionUserId(),
AUTH_ADD_CALENDAR, getReference());
// reserve a calendar event with this id from the info store - if it's in use, this will return null
CalendarEventEdit event = m_storage.putEvent(this, eventFromXml.getId());
if (event == null)
{
throw new IdUsedException(eventFromXml.getId());
}
// transfer from the XML read object to the Edit
((BaseCalendarEventEdit) event).set(eventFromXml);
((BaseCalendarEventEdit) event).setEvent(EVENT_MODIFY_CALENDAR);
return event;
} // mergeEvent
/**
* check permissions for removeEvent().
*
* @param event
* The event from this calendar to remove.
* @return true if the user is allowed to removeEvent(event), false if not.
*/
public boolean allowRemoveEvent(CalendarEvent event)
{
boolean allowed = false;
boolean ownEvent = event.isUserOwner();
// check security to delete any event
if ( unlockCheck(AUTH_REMOVE_CALENDAR_ANY, getReference()) )
allowed = true;
// check security to delete own event
else if ( unlockCheck(AUTH_REMOVE_CALENDAR_OWN, getReference()) && ownEvent )
allowed = true;
// but we must also assure, that for grouped events, we can remove it from ALL of the groups
if (allowed && (event.getAccess() == EventAccess.GROUPED))
{
allowed = EntityCollections.isContainedEntityRefsToEntities(event.getGroups(), getGroupsAllowRemoveEvent(ownEvent));
}
return allowed;
} // allowRemoveEvent
/**
* Remove an event from the calendar, one locked for edit. Note: if the event is a recurring event, the entire sequence is modified by this commit (MOD_ALL).
*
* @param event
* The event from this calendar to remove.
*/
public void removeEvent(CalendarEventEdit edit) throws PermissionException
{
removeEvent(edit, MOD_ALL);
} // removeEvent
/**
* Remove an event from the calendar, one locked for edit.
*
* @param event
* The event from this calendar to remove.
* @param intention
* The recurring event modification intention, based on values in the CalendarService "MOD_*", used if the event is part of a recurring event sequence to determine how much of the sequence is removed.
*/
public void removeEvent(CalendarEventEdit edit, int intention) throws PermissionException
{
// check for closed edit
if (!edit.isActiveEdit())
{
try
{
throw new Exception();
}
catch (Exception e)
{
M_log.warn("removeEvent(): closed EventEdit", e);
}
return;
}
// securityCheck
if (!allowRemoveEvent(edit))
{
cancelEvent(edit);
throw new PermissionException(m_sessionManager.getCurrentSessionUserId(), AUTH_REMOVE_CALENDAR_ANY, edit.getReference());
}
BaseCalendarEventEdit bedit = (BaseCalendarEventEdit) edit;
// if the id has a time range encoded, as for one of a sequence of recurring events, separate that out
String indivEventEntityRef = null;
TimeRange timeRange = null;
int sequence = 0;
if (bedit.m_id.startsWith("!"))
{
indivEventEntityRef = bedit.getReference();
String[] parts = bedit.m_id.substring(1).split("!");
try
{
timeRange = m_timeService.newTimeRange(parts[0]);
sequence = Integer.parseInt(parts[1]);
bedit.m_id = parts[2];
}
catch (Exception ex)
{
M_log.warn("removeEvent: exception parsing eventId: " + bedit.m_id + " : " + ex);
}
}
// deal with recurring event sequence modification
if (timeRange != null)
{
// delete only this - add it as an exclusion in the edit
if (intention == MOD_THIS)
{
// get the edit back to initial values... so only the exclusion is changed
edit = (CalendarEventEdit) m_storage.getEvent(this, bedit.m_id);
bedit = (BaseCalendarEventEdit) edit;
// add an exclusion for where this one would have been %%% we are changing it, should it be immutable? -ggolden
List exclusions = ((ExclusionSeqRecurrenceRule) bedit.getExclusionRule()).getExclusions();
exclusions.add(Integer.valueOf(sequence));
// complete the edit
m_storage.commitEvent(this, edit);
// post event for excluding the instance
m_eventTrackingService.post(m_eventTrackingService.newEvent(EVENT_MODIFY_CALENDAR_EVENT_EXCLUSIONS, indivEventEntityRef, true));
}
// delete them all, i.e. the one initial event
else
{
m_storage.removeEvent(this, edit);
m_eventTrackingService.post(m_eventTrackingService.newEvent(EVENT_REMOVE_CALENDAR_EVENT, edit.getReference(), true));
}
}
// else a single event to delete
else
{
m_storage.removeEvent(this, edit);
m_eventTrackingService.post(m_eventTrackingService.newEvent(EVENT_REMOVE_CALENDAR_EVENT, edit.getReference(), true));
}
// track event
Event event = m_eventTrackingService.newEvent(EVENT_MODIFY_CALENDAR, edit.getReference(), true);
m_eventTrackingService.post(event);
// calendar notification
notify(event);
// close the edit object
((BaseCalendarEventEdit) edit).closeEdit();
// remove any realm defined for this resource
try
{
m_authzGroupService.removeAuthzGroup(m_authzGroupService.getAuthzGroup(edit.getReference()));
}
catch (AuthzPermissionException e)
{
M_log.warn("removeEvent: removing realm for : " + edit.getReference() + " : " + e);
}
catch (GroupNotDefinedException ignore)
{
}
} // removeEvent
/**
* check permissions for editEvent()
*
* @param id
* The event id.
* @return true if the user is allowed to update the event, false if not.
*/
public boolean allowEditEvent(String eventId)
{
CalendarEvent e = findEvent(eventId);
if (e == null) return false;
boolean ownEvent = e.isUserOwner();
// check security to revise any event
if ( unlockCheck(AUTH_MODIFY_CALENDAR_ANY, getReference()) )
return true;
// check security to revise own event
else if ( unlockCheck(AUTH_MODIFY_CALENDAR_OWN, getReference()) && ownEvent )
return true;
// otherwise not authorized
else
return false;
} // allowEditEvent
/**
* Return a specific calendar event, as specified by event name, locked for update.
* Must commitEvent() to make official, or cancelEvent(), or removeEvent() when done!
*
* @param eventId The id of the event to get.
* @param editType add, remove or modifying calendar?
* @return the Event that has the specified id.
* @exception IdUnusedException
* If this name is not a defined event in this calendar.
* @exception PermissionException
* If the user does not have any permissions to edit the event.
* @exception InUseException
* if the event is locked for edit by someone else.
*/
public CalendarEventEdit getEditEvent(String eventId, String editType)
throws IdUnusedException, PermissionException, InUseException
{
// if the id has a time range encoded, as for one of a sequence of recurring events, separate that out
TimeRange timeRange = null;
int sequence = 0;
if (eventId.startsWith("!"))
{
String[] parts = eventId.substring(1).split("!");
try
{
timeRange = m_timeService.newTimeRange(parts[0]);
sequence = Integer.parseInt(parts[1]);
eventId = parts[2];
}
catch (Exception ex)
{
M_log.warn("getEditEvent: exception parsing eventId: " + eventId + " : " + ex);
}
}
CalendarEvent e = findEvent(eventId);
if (e == null) throw new IdUnusedException(eventId);
// check security
if ( editType.equals(EVENT_ADD_CALENDAR) && ! allowAddEvent() )
throw new PermissionException(m_sessionManager.getCurrentSessionUserId(),
AUTH_ADD_CALENDAR, getReference());
else if ( editType.equals(EVENT_REMOVE_CALENDAR) && ! allowRemoveEvent(e) )
throw new PermissionException(m_sessionManager.getCurrentSessionUserId(),
AUTH_REMOVE_CALENDAR_ANY, getReference());
else if ( editType.equals(EVENT_MODIFY_CALENDAR) && ! allowEditEvent(eventId) )
throw new PermissionException(m_sessionManager.getCurrentSessionUserId(),
AUTH_MODIFY_CALENDAR_ANY, getReference());
// ignore the cache - get the CalendarEvent with a lock from the info store
CalendarEventEdit edit = m_storage.editEvent(this, eventId);
if (edit == null) throw new InUseException(eventId);
BaseCalendarEventEdit bedit = (BaseCalendarEventEdit) edit;
// if this is one in a sequence, adjust it
if (timeRange != null)
{
// move the specified range into the event's range, storing the base range
bedit.m_baseRange = bedit.m_range;
bedit.m_range = timeRange;
bedit.m_id = '!' + bedit.m_range.toString() + '!' + sequence + '!' + bedit.m_id;
}
bedit.setEvent(EVENT_MODIFY_CALENDAR);
return edit;
} // getEditEvent
/**
* Commit the changes made to a CalendarEventEdit object, and release the lock. The CalendarEventEdit is disabled, and not to be used after this call. Note: if the event is a recurring event, the entire sequence is modified by this commit
* (MOD_ALL).
*
* @param edit
* The CalendarEventEdit object to commit.
*/
public void commitEvent(CalendarEventEdit edit)
{
commitEvent(edit, MOD_ALL);
} // commitEvent
/**
* Commit the changes made to a CalendarEventEdit object, and release the lock. The CalendarEventEdit is disabled, and not to be used after this call.
*
* @param edit
* The CalendarEventEdit object to commit.
* @param intention
* The recurring event modification intention, based on values in the CalendarService "MOD_*", used if the event is part of a recurring event sequence to determine how much of the sequence is changed by this commmit.
*/
public void commitEvent(CalendarEventEdit edit, int intention)
{
// check for closed edit
if (!edit.isActiveEdit())
{
M_log.warn("commitEvent(): closed CalendarEventEdit " + edit.getId());
return;
}
BaseCalendarEventEdit bedit = (BaseCalendarEventEdit) edit;
// If creator doesn't exist, set it now (backward compatibility)
if ( edit.getCreator() == null || edit.getCreator().equals("") )
edit.setCreator();
// update modified-by properties for event
edit.setModifiedBy();
// if the id has a time range encoded, as for one of a sequence of recurring events, separate that out
String indivEventEntityRef = null;
TimeRange timeRange = null;
int sequence = 0;
if (bedit.m_id.startsWith("!"))
{
indivEventEntityRef = bedit.getReference();
String[] parts = bedit.m_id.substring(1).split("!");
try
{
timeRange = m_timeService.newTimeRange(parts[0]);
sequence = Integer.parseInt(parts[1]);
bedit.m_id = parts[2];
}
catch (Exception ex)
{
M_log.warn("commitEvent: exception parsing eventId: " + bedit.m_id + " : " + ex);
}
}
// for recurring event sequence
TimeRange newTimeRange = null;
BaseCalendarEventEdit newEvent = null;
if (timeRange != null)
{
// if changing this event only
if (intention == MOD_THIS)
{
// make a new event for this one
String id = getUniqueId();
newEvent = (BaseCalendarEventEdit) m_storage.putEvent(this, id);
newEvent.setPartial(edit);
m_storage.commitEvent(this, newEvent);
m_eventTrackingService.post(m_eventTrackingService.newEvent(EVENT_MODIFY_CALENDAR, newEvent.getReference(), true));
m_eventTrackingService.post(m_eventTrackingService.newEvent(EVENT_MODIFY_CALENDAR_EVENT_EXCLUDED, newEvent.getReference(), true));
m_eventTrackingService.post(m_eventTrackingService.newEvent(EVENT_MODIFY_CALENDAR_EVENT_EXCLUSIONS, indivEventEntityRef, true));
// get the edit back to initial values... so only the exclusion is changed
edit = (CalendarEventEdit) m_storage.getEvent(this, bedit.m_id);
bedit = (BaseCalendarEventEdit) edit;
// add an exclusion for where this one would have been %%% we are changing it, should it be immutable? -ggolden
List exclusions = ((ExclusionSeqRecurrenceRule) bedit.getExclusionRule()).getExclusions();
exclusions.add(Integer.valueOf(sequence));
}
// else change the entire sequence (i.e. the one initial event)
else
{
// the time range may have been modified in the edit
newTimeRange = bedit.m_range;
// restore the real range, that of the base event of a sequence, if this is one of the other events in the sequence.
bedit.m_range = bedit.m_baseRange;
// adjust the base range if there was an edit to range
bedit.m_range.adjust(timeRange, newTimeRange);
}
}
// update the properties
// addLiveUpdateProperties(edit.getPropertiesEdit());//%%%
postEventsForChanges(bedit);
// complete the edit
m_storage.commitEvent(this, edit);
// track event
Event event = m_eventTrackingService.newEvent(bedit.getEvent(), edit.getReference(), true);
m_eventTrackingService.post(event);
// calendar notification
notify(event);
// close the edit object
bedit.closeEdit();
// Update modify time on calendar
this.setModified();
m_storage.commitCalendar(this);
// restore this one's range etc so it can be further referenced
if (timeRange != null)
{
// if changing this event only
if (intention == MOD_THIS)
{
// set the edit to the values of the new event
bedit.set(newEvent);
}
// else we changed the sequence
else
{
// move the specified range into the event's range, storing the base range
bedit.m_baseRange = bedit.m_range;
bedit.m_range = newTimeRange;
bedit.m_id = '!' + bedit.m_range.toString() + '!' + sequence + '!' + bedit.m_id;
}
}
} // commitEvent
/**
* @param newEvent
*/
public void postEventsForChanges(BaseCalendarEventEdit newEvent) {
// determine which events should be posted by comparing with saved properties
BaseCalendarEventEdit savedEvent = (BaseCalendarEventEdit) this.findEvent(newEvent.m_id);
if(savedEvent == null) {
} else {
// has type changed?
String savedType = savedEvent.getType();
String newType = newEvent.getType();
if(savedType == null || newType == null) {
// TODO: is this an error?
} else {
if (!newType.equals(savedType))
{
// post type-change event
m_eventTrackingService.post(m_eventTrackingService.newEvent(EVENT_MODIFY_CALENDAR_EVENT_TYPE, newEvent.getReference() + "::" + savedType + "::" + newType, true));
}
}
// has title changed?
if(savedEvent.getDisplayName() != null && ! savedEvent.getDisplayName().equals(newEvent.getDisplayName())) {
// post title-change event
m_eventTrackingService.post(m_eventTrackingService.newEvent(EVENT_MODIFY_CALENDAR_EVENT_TITLE, newEvent.getReference(), true));
}
// has start-time changed?
TimeRange savedRange = savedEvent.getRange();
TimeRange newRange = newEvent.getRange();
if(savedRange == null || newRange == null) {
// TODO: Is this an error?
} else if(savedRange.firstTime() != null && savedRange.firstTime().compareTo(newRange.firstTime()) != 0) {
// post time-change event
m_eventTrackingService.post(m_eventTrackingService.newEvent(EVENT_MODIFY_CALENDAR_EVENT_TIME, newEvent.getReference(), true));
}
// has access changed?
if(savedEvent.getAccess() != newEvent.getAccess()) {
// post access-change event
m_eventTrackingService.post(m_eventTrackingService.newEvent(EVENT_MODIFY_CALENDAR_EVENT_ACCESS, newEvent.getReference(), true));
} else {
Collection savedGroups = savedEvent.getGroups();
Collection newGroups = newEvent.getGroups();
if(! (savedGroups.containsAll(newGroups) && newGroups.containsAll(savedGroups))) {
// post access-change event
m_eventTrackingService.post(m_eventTrackingService.newEvent(EVENT_MODIFY_CALENDAR_EVENT_ACCESS, newEvent.getReference(), true));
}
}
// has frequency changed (other than exclusions)?
RecurrenceRule savedRule = savedEvent.getRecurrenceRule();
RecurrenceRule newRule = newEvent.getRecurrenceRule();
if(savedRule == null && newRule == null) {
// do nothing -- no change
} else if(savedRule == null || newRule == null) {
// post frequency-change event
m_eventTrackingService.post(m_eventTrackingService.newEvent(EVENT_MODIFY_CALENDAR_EVENT_FREQUENCY, newEvent.getReference(), true));
} else {
// check for changes in properties of the rules
// (rule.getCount() rule.getFrequency() rule.getInterval() rule.getUntil()
if(savedRule.getCount() != newRule.getCount() || savedRule.getInterval() != newRule.getInterval()) {
// post frequency-change event
m_eventTrackingService.post(m_eventTrackingService.newEvent(EVENT_MODIFY_CALENDAR_EVENT_FREQUENCY, newEvent.getReference(), true));
} else if((savedRule.getFrequency() != null && ! savedRule.getFrequency().equals(newRule.getFrequency())) || (savedRule.getFrequency() == null && newRule.getFrequency() != null)) {
// post frequency-change event
m_eventTrackingService.post(m_eventTrackingService.newEvent(EVENT_MODIFY_CALENDAR_EVENT_FREQUENCY, newEvent.getReference(), true));
} else if((savedRule.getUntil() == null && newRule.getUntil() != null)
|| (savedRule.getUntil() != null && newRule.getUntil() == null)
|| (savedRule.getUntil() != null && savedRule.getUntil().getTime() != newRule.getUntil().getTime())) {
// post frequency-change event
m_eventTrackingService.post(m_eventTrackingService.newEvent(EVENT_MODIFY_CALENDAR_EVENT_FREQUENCY, newEvent.getReference(), true));
}
}
}
}
/**
* Cancel the changes made to a CalendarEventEdit object, and release the lock. The CalendarEventEdit is disabled, and not to be used after this call.
*
* @param edit
* The CalendarEventEdit object to commit.
*/
public void cancelEvent(CalendarEventEdit edit)
{
// check for closed edit
if (!edit.isActiveEdit())
{
Throwable e = new Throwable();
M_log.warn("cancelEvent(): closed CalendarEventEdit", e);
return;
}
BaseCalendarEventEdit bedit = (BaseCalendarEventEdit) edit;
// if the id has a time range encoded, as for one of a sequence of recurring events, separate that out
TimeRange timeRange = null;
int sequence = 0;
if (bedit.m_id.startsWith("!"))
{
String[] parts = bedit.m_id.substring(1).split( "!");
try
{
timeRange = m_timeService.newTimeRange(parts[0]);
sequence = Integer.parseInt(parts[1]);
bedit.m_id = parts[2];
}
catch (Exception ex)
{
M_log.warn("commitEvent: exception parsing eventId: " + bedit.m_id + " : " + ex);
}
}
// release the edit lock
m_storage.cancelEvent(this, edit);
// close the edit object
((BaseCalendarEventEdit) edit).closeEdit();
} // cancelCalendarEvent
/**
* Return the extra fields kept for each event in this calendar.
*
* @return the extra fields kept for each event in this calendar, formatted into a single string. %%%
*/
public String getEventFields()
{
return m_properties.getPropertyFormatted(ResourceProperties.PROP_CALENDAR_EVENT_FIELDS);
} // getEventFields
/**
* Set the extra fields kept for each event in this calendar.
*
* @param meta
* The extra fields kept for each event in this calendar, formatted into a single string. %%%
*/
public void setEventFields(String fields)
{
m_properties.addProperty(ResourceProperties.PROP_CALENDAR_EVENT_FIELDS, fields);
} // setEventFields
/**
* Notify the calendar that it has changed
*
* @param event
* The event that caused the update.
*/
public void notify(Event event)
{
// notify observers, sending the tracking event to identify the change
setChanged();
notifyObservers(event);
} // notify
/**
* Serialize the resource into XML, adding an element to the doc under the top of the stack element.
*
* @param doc
* The DOM doc to contain the XML (or null for a string return).
* @param stack
* The DOM elements, the top of which is the containing element of the new "resource" element.
* @return The newly added element.
*/
public Element toXml(Document doc, Stack stack)
{
Element calendar = doc.createElement("calendar");
if (stack.isEmpty())
{
doc.appendChild(calendar);
}
else
{
((Element) stack.peek()).appendChild(calendar);
}
stack.push(calendar);
calendar.setAttribute("context", m_context);
calendar.setAttribute("id", m_id);
// properties
m_properties.toXml(doc, stack);
stack.pop();
return calendar;
} // toXml
/**
* Find the event, in cache or info store - cache it if newly found.
*
* @param eventId
* The id of the event.
* @return The event, if found.
*/
protected CalendarEvent findEvent(String eventId)
{
CalendarEvent e = null;
// if the id has a time range encoded, as for one of a sequence of recurring events, separate that out
TimeRange timeRange = null;
int sequence = 0;
if (eventId.startsWith("!"))
{
String[] parts = eventId.substring(1).split("!");
try
{
timeRange = m_timeService.newTimeRange(parts[0]);
sequence = Integer.parseInt(parts[1]);
eventId = parts[2];
}
catch (Exception ex)
{
M_log.warn("findEvent: exception parsing eventId: " + eventId + " : " + ex);
}
}
// events are cached with the full reference as key
String key = eventReference(m_context, m_id, eventId);
// if cache is disabled, don't use it
if ((!m_caching) || (m_calendarCache == null) || (m_calendarCache.disabled()))
{
// if we have "cached" the entire set of events in the thread, get that and find our message there
List events = (List) m_threadLocalManager.get(getReference() + ".events");
if (events != null)
{
for (Iterator i = events.iterator(); i.hasNext();)
{
CalendarEvent event = (CalendarEvent) i.next();
if (event.getId().equals(eventId))
{
e = event;
break;
}
}
}
if (e == null)
{
e = m_storage.getEvent(this, eventId);
}
}
else
{
// find the event cache
Cache eventCache = (Cache) m_eventCaches.get(getReference());
if (eventCache == null)
{
synchronized (m_eventCaches)
{
// check again
eventCache = (Cache) m_eventCaches.get(getReference());
// if still not there, make one
if (eventCache == null)
{
eventCache = m_memoryService
.newCache(
"org.sakaiproject.calendar.api.CalendarService.eventCache",
service(), eventReference(
m_context, m_id, ""));
m_eventCaches.put(getReference(), eventCache);
}
}
}
// if we have it cached, use it (even if it's cached as a null, a miss)
if (eventCache.containsKey(key))
{
e = (CalendarEvent) eventCache.get(key);
}
// if not in the cache, see if we have it in our info store
if ( e == null ) //SAK-12447 cache.get can return null on expired
{
e = m_storage.getEvent(this, eventId);
// if so, cache it, even misses
eventCache.put(key, e);
}
}
// now we have the primary event, if we have a recurring event sequence time range selector, use it
if ((e != null) && (timeRange != null))
{
e = new BaseCalendarEventEdit(e, new RecurrenceInstance(timeRange, sequence));
}
return e;
} // findEvent
/**
* Access the event code for this edit.
*
* @return The event code for this edit.
*/
protected String getEvent()
{
return m_event;
}
/**
* Set the event code for this edit.
*
* @param event
* The event code for this edit.
*/
protected void setEvent(String event)
{
m_event = event;
}
/**
* Access the resource's properties for modification
*
* @return The resource's properties.
*/
public ResourcePropertiesEdit getPropertiesEdit()
{
return m_properties;
} // getPropertiesEdit
/**
* Enable editing.
*/
protected void activate()
{
m_active = true;
} // activate
/**
* Check to see if the edit is still active, or has already been closed.
*
* @return true if the edit is active, false if it's been closed.
*/
public boolean isActiveEdit()
{
return m_active;
} // isActiveEdit
/**
* Close the edit object - it cannot be used after this.
*/
protected void closeEdit()
{
m_active = false;
} // closeEdit
/**
* {@inheritDoc}
*/
public Collection getGroupsAllowAddEvent()
{
return getGroupsAllowFunction(AUTH_ADD_CALENDAR);
}
/**
* {@inheritDoc}
*/
public Collection getGroupsAllowGetEvent()
{
return getGroupsAllowFunction(AUTH_READ_CALENDAR);
}
/**
* {@inheritDoc}
*/
public Collection getGroupsAllowRemoveEvent( boolean own )
{
return getGroupsAllowFunction(own ? AUTH_REMOVE_CALENDAR_OWN : AUTH_REMOVE_CALENDAR_ANY );
}
/**
* Get the groups of this channel's contex-site that the end user has permission to "function" in.
* @param function The function to check
*/
protected Collection getGroupsAllowFunction(String function)
{
Vector rv = new Vector();
try
{
// get the channel's site's groups
Site site = m_siteService.getSite(m_context);
Collection groups = site.getGroups();
// if the user has SECURE_ALL_GROUPS in the context (site), and the function for the calendar (calendar,site), select all site groups
if ((m_securityService.isSuperUser()) || (m_authzGroupService.isAllowed(m_sessionManager.getCurrentSessionUserId(), SECURE_ALL_GROUPS, m_siteService.siteReference(m_context))
&& unlockCheck(function, getReference())))
{
rv.addAll( groups );
Collections.sort( rv, groupComparator );
return (Collection)rv;
}
// otherwise, check the groups for function
// get a list of the group refs, which are authzGroup ids
Collection groupRefs = new Vector();
for (Iterator i = groups.iterator(); i.hasNext();)
{
Group group = (Group) i.next();
groupRefs.add(group.getReference());
}
// ask the authzGroup service to filter them down based on function
groupRefs = m_authzGroupService.getAuthzGroupsIsAllowed(m_sessionManager.getCurrentSessionUserId(), function, groupRefs);
// pick the Group objects from the site's groups to return, those that are in the groupRefs list
for (Iterator i = groups.iterator(); i.hasNext();)
{
Group group = (Group) i.next();
if (groupRefs.contains(group.getReference()))
{
rv.add(group);
}
}
}
catch (IdUnusedException ignore) {}
Collections.sort( rv, groupComparator );
return (Collection)rv;
} // getGroupsAllowFunction
/******************************************************************************************************************************************************************************************************************************************************
* SessionBindingListener implementation
*****************************************************************************************************************************************************************************************************************************************************/
public void valueBound(SessionBindingEvent event)
{
}
public void valueUnbound(SessionBindingEvent event)
{
if (M_log.isDebugEnabled()) M_log.debug("valueUnbound()");
// catch the case where an edit was made but never resolved
if (m_active)
{
cancelCalendar(this);
}
} // valueUnbound
/**
* Get a ContentHandler suitable for populating this object from SAX Events
* @return
*/
public ContentHandler getContentHandler(Map<String,Object> services)
{
final Entity thisEntity = this;
return new DefaultEntityHandler() {
/* (non-Javadoc)
* @see org.sakaiproject.util.DefaultEntityHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)
*/
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException
{
if ( doStartElement(uri, localName, qName, attributes) ) {
if ( "calendar".equals(qName) && entity == null ) {
m_id = attributes.getValue("id");
m_context = attributes.getValue("context");
entity = thisEntity;
} else {
M_log.warn("Unexpected element "+qName);
}
}
}
};
}
} // class BaseCalendar
/**********************************************************************************************************************************************************************************************************************************************************
* CalendarEvent implementation
*********************************************************************************************************************************************************************************************************************************************************/
public class BaseCalendarEventEdit implements CalendarEventEdit, SessionBindingListener
{
/** The calendar in which this event lives. */
protected BaseCalendarEdit m_calendar = null;
/** The effective time range. */
protected TimeRange m_range = null;
/**
* The base time range: for non-recurring events, this matches m_range, but for recurring events, it is always the range of the initial event in the sequence (transient).
*/
protected TimeRange m_baseRange = null;
/** The recurrence rule (single rule). */
protected RecurrenceRule m_singleRule = null;
/** The exclusion recurrence rule. */
protected RecurrenceRule m_exclusionRule = null;
/** The properties. */
protected ResourcePropertiesEdit m_properties = null;
/** The event id. */
protected String m_id = null;
/** The attachments - dereferencer objects. */
protected List m_attachments = null;
/** The event code for this edit. */
protected String m_event = null;
/** Active flag. */
protected boolean m_active = false;
/** The Collection of groups (authorization group id strings). */
protected Collection m_groups = new Vector();
/** The message access. */
protected EventAccess m_access = EventAccess.SITE;
/**
* Construct.
*
* @param calendar
* The calendar in which this event lives.
* @param id
* The event id, unique within the calendar.
*/
public BaseCalendarEventEdit(Calendar calendar, String id)
{
m_calendar = (BaseCalendarEdit) calendar;
m_id = id;
// setup for properties
m_properties = new BaseResourcePropertiesEdit();
// init the AttachmentContainer
m_attachments = m_entityManager.newReferenceList();
} // BaseCalendarEventEdit
/**
* Construct as a copy of another event.
*
* @param other
* The other event to copy.
*/
public BaseCalendarEventEdit(Calendar calendar, CalendarEvent other)
{
// store the calendar
m_calendar = (BaseCalendarEdit) calendar;
set(other);
} // BaseCalendarEventEdit
/**
* Construct as a thin copy of another event, with this new time range, and no rules, as part of a recurring event sequence.
*
* @param other
* The other event to copy.
* @param ri
* The RecurrenceInstance with the time range (and sequence number) to use.
*/
public BaseCalendarEventEdit(CalendarEvent other, RecurrenceInstance ri)
{
// store the calendar
m_calendar = ((BaseCalendarEventEdit) other).m_calendar;
// encode the instance and the other's id into my id
m_id = '!' + ri.getRange().toString() + '!' + ri.getSequence() + '!' + ((BaseCalendarEventEdit) other).m_id;
// use the new range
m_range = (TimeRange) ri.getRange().clone();
m_baseRange = ((BaseCalendarEventEdit) other).m_range;
// point at the properties
m_properties = ((BaseCalendarEventEdit) other).m_properties;
m_access = ((BaseCalendarEventEdit) other).m_access;
// point at the groups
m_groups = ((BaseCalendarEventEdit) other).m_groups;
// point at the attachments
m_attachments = ((BaseCalendarEventEdit) other).m_attachments;
// point at the rules
m_singleRule = ((BaseCalendarEventEdit) other).m_singleRule;
m_exclusionRule = ((BaseCalendarEventEdit) other).m_exclusionRule;
} // BaseCalendarEventEdit
/**
* Construct from an existing definition, in xml.
*
* @param calendar
* The calendar in which this event lives.
* @param el
* The event in XML in a DOM element.
*/
public BaseCalendarEventEdit(Calendar calendar, Element el)
{
m_calendar = (BaseCalendarEdit) calendar;
m_properties = new BaseResourcePropertiesEdit();
m_attachments = m_entityManager.newReferenceList();
m_id = el.getAttribute("id");
m_range = m_timeService.newTimeRange(el.getAttribute("range"));
m_access = CalendarEvent.EventAccess.SITE;
String access_str = el.getAttribute("access").toString();
if (access_str.equals(CalendarEvent.EventAccess.GROUPED.toString()))
m_access = CalendarEvent.EventAccess.GROUPED;
// the children (props / attachments / rules)
NodeList children = el.getChildNodes();
final int length = children.getLength();
for (int i = 0; i < length; i++)
{
Node child = children.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE)
{
Element element = (Element) child;
// look for an attachment
if (element.getTagName().equals("attachment"))
{
m_attachments.add(m_entityManager.newReference(element.getAttribute("relative-url")));
}
// look for properties
else if (element.getTagName().equals("properties"))
{
// re-create properties
m_properties = new BaseResourcePropertiesEdit(element);
}
else if (element.getTagName().equals("group"))
{
m_groups.add(element.getAttribute("authzGroup"));
}
// else look for rules
else if (element.getTagName().equals("rules"))
{
// children are "rule" elements
NodeList ruleChildren = element.getChildNodes();
final int ruleChildrenLength = ruleChildren.getLength();
for (int iRuleChildren = 0; iRuleChildren < ruleChildrenLength; iRuleChildren++)
{
Node ruleChildNode = ruleChildren.item(iRuleChildren);
if (ruleChildNode.getNodeType() == Node.ELEMENT_NODE)
{
Element ruleChildElement = (Element) ruleChildNode;
// look for a rule or exclusion rule
if (ruleChildElement.getTagName().equals("rule") || ruleChildElement.getTagName().equals("ex-rule"))
{
// get the rule name - modern style encoding
String ruleName = StringUtils.trimToNull(ruleChildElement.getAttribute("name"));
// deal with old data
if (ruleName == null)
{
// get the class - this is old CHEF 1.2.10 style encoding
String ruleClassOld = ruleChildElement.getAttribute("class");
// use the last class name minus the package
if ( ruleClassOld != null )
ruleName = ruleClassOld.substring(ruleClassOld.lastIndexOf('.') + 1);
if ( ruleName == null )
M_log.warn("trouble loading rule");
}
if (ruleName != null)
{
// put my package on the class name
String ruleClass = this.getClass().getPackage().getName() + "." + ruleName;
// construct
try
{
if (ruleChildElement.getTagName().equals("rule"))
{
m_singleRule = (RecurrenceRule) Class.forName(ruleClass).newInstance();
m_singleRule.set(ruleChildElement);
}
else // ruleChildElement.getTagName().equals("ex-rule"))
{
m_exclusionRule = (RecurrenceRule) Class.forName(ruleClass).newInstance();
m_exclusionRule.set(ruleChildElement);
}
}
catch (Exception e)
{
M_log.warn("trouble loading rule: " + ruleClass + " : " + e);
}
}
}
}
}
}
}
}
} // BaseCalendarEventEdit
/**
*
*/
public BaseCalendarEventEdit(Entity container)
{
m_calendar = (BaseCalendarEdit) container;
m_properties = new BaseResourcePropertiesEdit();
m_attachments = m_entityManager.newReferenceList();
}
/**
* Take all values from this object.
*
* @param other
* The other object to take values from.
*/
protected void set(CalendarEvent other)
{
// copy the id
m_id = other.getId();
// copy the range
m_range = (TimeRange) other.getRange().clone();
// copy the properties
m_properties = new BaseResourcePropertiesEdit();
m_properties.addAll(other.getProperties());
m_access = other.getAccess();
m_groups = new Vector();
m_groups.addAll(other.getGroups());
// copy the attachments
m_attachments = m_entityManager.newReferenceList();
replaceAttachments(other.getAttachments());
// copy the rules
// %%% deep enough? -ggolden
m_singleRule = ((BaseCalendarEventEdit) other).m_singleRule;
m_exclusionRule = ((BaseCalendarEventEdit) other).m_exclusionRule;
} // set
/**
* Take some values from this object (not id, not rules).
*
* @param other
* The other object to take values from.
*/
protected void setPartial(CalendarEvent other)
{
// copy the range
m_range = (TimeRange) other.getRange().clone();
// copy the properties
m_properties = new BaseResourcePropertiesEdit();
m_properties.addAll(other.getProperties());
m_access = other.getAccess();
m_groups = new Vector();
m_groups.addAll(other.getGroups());
// copy the attachments
m_attachments = m_entityManager.newReferenceList();
replaceAttachments(other.getAttachments());
} // setPartial
/**
* Access the time range
*
* @return The event time range
*/
public TimeRange getRange()
{
// range might be null in the creation process, before the fields are set in an edit, but
// after the storage has registered the event and it's id.
if (m_range == null)
{
return m_timeService.newTimeRange(m_timeService.newTime(0));
}
// return (TimeRange) m_range.clone();
return m_range;
} // getRange
/**
* Replace the time range
*
* @param The
* new event time range
*/
public void setRange(TimeRange range)
{
m_range = (TimeRange) range.clone();
} // setRange
/**
* Access the display name property (cover for PROP_DISPLAY_NAME).
*
* @return The event's display name property.
*/
public String getDisplayName()
{
return m_properties.getPropertyFormatted(ResourceProperties.PROP_DISPLAY_NAME);
} // getDisplayName
/**
* Set the display name property (cover for PROP_DISPLAY_NAME).
*
* @param name
* The event's display name property.
*/
public void setDisplayName(String name)
{
m_properties.addProperty(ResourceProperties.PROP_DISPLAY_NAME, name);
} // setDisplayName
/**
* Access the description property as plain text.
*
* @return The event's description property.
*/
public String getDescription()
{
return FormattedText.convertFormattedTextToPlaintext(getDescriptionFormatted());
}
/**
* Access the description property as formatted text.
*
* @return The event's description property.
*/
public String getDescriptionFormatted()
{
// %%% JANDERSE the calendar event description can now be formatted text
// first try to use the formatted text description; if that isn't found, use the plaintext description
String desc = m_properties.getPropertyFormatted(ResourceProperties.PROP_DESCRIPTION + "-html");
if (desc != null && desc.length() > 0) return desc;
desc = m_properties.getPropertyFormatted(ResourceProperties.PROP_DESCRIPTION + "-formatted");
desc = FormattedText.convertOldFormattedText(desc);
if (desc != null && desc.length() > 0) return desc;
desc = FormattedText.convertPlaintextToFormattedText(m_properties
.getPropertyFormatted(ResourceProperties.PROP_DESCRIPTION));
return desc;
} // getDescriptionFormatted()
/**
* Set the description property as plain text.
*
* @param description
* The event's description property.
*/
public void setDescription(String description)
{
setDescriptionFormatted(FormattedText.convertPlaintextToFormattedText(description));
}
/**
* Set the description property as formatted text.
*
* @param description
* The event's description property.
*/
public void setDescriptionFormatted(String description)
{
// %%% JANDERSE the calendar event description can now be formatted text
// save both a formatted and a plaintext version of the description
m_properties.addProperty(ResourceProperties.PROP_DESCRIPTION + "-html", description);
m_properties.addProperty(ResourceProperties.PROP_DESCRIPTION, FormattedText
.convertFormattedTextToPlaintext(description));
} // setDescriptionFormatted()
/**
* Access the type (cover for PROP_CALENDAR_TYPE).
*
* @return The event's type property.
*/
public String getType()
{
return m_properties.getPropertyFormatted(ResourceProperties.PROP_CALENDAR_TYPE);
} // getType
/**
* Set the type (cover for PROP_CALENDAR_TYPE).
*
* @param type
* The event's type property.
*/
public void setType(String type)
{
m_properties.addProperty(ResourceProperties.PROP_CALENDAR_TYPE, type);
} // setType
/**
* Access the location (cover for PROP_CALENDAR_LOCATION).
*
* @return The event's location property.
*/
public String getLocation()
{
return m_properties.getPropertyFormatted(ResourceProperties.PROP_CALENDAR_LOCATION);
} // getLocation
/**
* Gets the recurrence rule, if any.
*
* @return The recurrence rule, or null if none.
*/
public RecurrenceRule getRecurrenceRule()
{
return m_singleRule;
} // getRecurrenceRule
/**
* Gets the exclusion recurrence rule, if any.
*
* @return The exclusionrecurrence rule, or null if none.
*/
public RecurrenceRule getExclusionRule()
{
if (m_exclusionRule == null) m_exclusionRule = new ExclusionSeqRecurrenceRule();
return m_exclusionRule;
} // getExclusionRule
/*
* Return a list of all resolved events generated from this event plus it's recurrence rules that fall within the time range, including this event, possibly empty.
*
* @param range
* The time range bounds for the events returned.
* @return a List (CalendarEvent) of all events and recurrences within the time range, including this, possibly empty.
*/
protected List resolve(TimeRange range)
{
List rv = new Vector();
// for no rules, use the event if it's in range
if (m_singleRule == null)
{
// the actual event
if (range.overlaps(getRange()))
{
rv.add(this);
}
}
// for rules...
else
{
// for a re-occurring event, the time zone where the first event is created
// is passed as a parameter (timezone) to correctly generate the instances
String timeZoneID = this.getField("createdInTimeZone");
TimeZone timezone = null;
if (timeZoneID.equals(""))
{
timezone = m_timeService.getLocalTimeZone();
}
else
{
timezone = TimeZone.getTimeZone(timeZoneID);
}
List instances = m_singleRule.generateInstances(this.getRange(), range, timezone);
// remove any excluded
getExclusionRule().excludeInstances(instances);
for (Iterator iRanges = instances.iterator(); iRanges.hasNext();)
{
RecurrenceInstance ri = (RecurrenceInstance) iRanges.next();
// generate an event object that is exactly like me but with this range and no rules
CalendarEvent clone = new BaseCalendarEventEdit(this, ri);
rv.add(clone);
}
}
return rv;
} // resolve
/**
* Get the value of an "extra" event field.
*
* @param name
* The name of the field.
* @return the value of the "extra" event field.
*/
public String getField(String name)
{
// names are prefixed to form a namespace
name = ResourceProperties.PROP_CALENDAR_EVENT_FIELDS + "." + name;
return m_properties.getPropertyFormatted(name);
} // getField
/**
* Set the value of an "extra" event field.
*
* @param name
* The "extra" field name
* @param value
* The value to set, or null to remove the field.
*/
public void setField(String name, String value)
{
// names are prefixed to form a namespace
name = ResourceProperties.PROP_CALENDAR_EVENT_FIELDS + "." + name;
if (value == null)
{
m_properties.removeProperty(name);
}
else
{
m_properties.addProperty(name, value);
}
} // setField
/**
* Set the location (cover for PROP_CALENDAR_LOCATION).
*
* @param location
* The event's location property.
*/
public void setLocation(String location)
{
m_properties.addProperty(ResourceProperties.PROP_CALENDAR_LOCATION, location);
} // setLocation
/**
* Gets the event creator (userid), if any (cover for PROP_CREATOR).
* @return The event's creator property.
*/
public String getCreator()
{
return m_properties.getProperty(ResourceProperties.PROP_CREATOR);
} // getCreator
/**
* Returns true if current user is thhe event's owner/creator
* @return boolean true or false
*/
public boolean isUserOwner()
{
String currentUser = m_sessionManager.getCurrentSessionUserId();
String eventOwner = this.getCreator();
// for backward compatibility, treat unowned event as if it owned by this user
return (eventOwner == null || eventOwner.equals("") || (currentUser != null && currentUser.equals(eventOwner)) );
}
/**
* Set the event creator (cover for PROP_CREATOR) to current user
*/
public void setCreator()
{
String currentUser = m_sessionManager.getCurrentSessionUserId();
String now = m_timeService.newTime().toString();
m_properties.addProperty(ResourceProperties.PROP_CREATOR, currentUser);
m_properties.addProperty(ResourceProperties.PROP_CREATION_DATE, now);
} // setCreator
/**
* Gets the event modifier (userid), if any (cover for PROP_MODIFIED_BY).
* @return The event's modified-by property.
*/
public String getModifiedBy()
{
return m_properties.getPropertyFormatted(ResourceProperties.PROP_MODIFIED_BY);
} // getModifiedBy
/**
* Set the event modifier (cover for PROP_MODIFIED_BY) to current user
*/
public void setModifiedBy()
{
String currentUser = m_sessionManager.getCurrentSessionUserId();
String now = m_timeService.newTime().toString();
m_properties.addProperty(ResourceProperties.PROP_MODIFIED_BY, currentUser);
m_properties.addProperty(ResourceProperties.PROP_MODIFIED_DATE, now);
} // setModifiedBy
/**
* Sets the recurrence rule.
*
* @param rule
* The recurrence rule, or null to clear out the rule.
*/
public void setRecurrenceRule(RecurrenceRule rule)
{
m_singleRule = rule;
} // setRecurrenceRule
/**
* Sets the exclusion recurrence rule.
*
* @param rule
* The recurrence rule, or null to clear out the rule.
*/
public void setExclusionRule(RecurrenceRule rule)
{
m_exclusionRule = rule;
} // setExclusionRule
/**
* Access the id of the resource.
*
* @return The id.
*/
public String getId()
{
return m_id;
} // getId
/**
* Access the URL which can be used to access the resource.
*
* @return The URL which can be used to access the resource.
*/
public String getUrl()
{
return m_calendar.getUrl() + getId();
} // getUrl
/**
* Access the internal reference which can be used to access the resource from within the system.
*
* @return The the internal reference which can be used to access the resource from within the system.
*/
public String getReference()
{
return eventReference(m_calendar.getContext(), m_calendar.getId(), getId());
} // getReference
/**
* @inheritDoc
*/
public String getReference(String rootProperty)
{
return getReference();
}
/**
* @inheritDoc
*/
public String getUrl(String rootProperty)
{
return getUrl();
}
/**
* Access the event's properties.
*
* @return The event's properties.
*/
public ResourceProperties getProperties()
{
return m_properties;
} // getProperties
/**
* Gets a site name for this calendar event
*/
public String getSiteName()
{
String calendarName = "";
if (m_calendar != null)
{
try
{
Site site = m_siteService.getSite(m_calendar.getContext());
if (site != null)
calendarName = site.getTitle();
}
catch (IdUnusedException e)
{
M_log.warn(".getSiteName(): " + e);
}
}
return calendarName;
}
/**
* Notify the event that it has changed.
*
* @param event
* The event that caused the update.
*/
public void notify(Event event)
{
m_calendar.notify(event);
} // notify
/**
* Compare one event to another, based on range.
*
* @param o
* The object to be compared.
* @return A negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
*/
public int compareTo(Object o)
{
if (!(o instanceof CalendarEvent)) throw new ClassCastException();
Time mine = getRange().firstTime();
Time other = ((CalendarEvent) o).getRange().firstTime();
if (mine.before(other)) return -1;
if (mine.after(other)) return +1;
return 0; // %%% perhaps check the rest of the range if the starts are the same?
}
/**
* Serialize the resource into XML, adding an element to the doc under the top of the stack element.
*
* @param doc
* The DOM doc to contain the XML (or null for a string return).
* @param stack
* The DOM elements, the top of which is the containing element of the new "resource" element.
* @return The newly added element.
*/
public Element toXml(Document doc, Stack stack)
{
Element event = doc.createElement("event");
if (stack.isEmpty())
{
doc.appendChild(event);
}
else
{
((Element) stack.peek()).appendChild(event);
}
stack.push(event);
event.setAttribute("id", getId());
event.setAttribute("range", getRange().toString());
// add access
event.setAttribute("access", m_access.toString());
// add groups
if ((m_groups != null) && (m_groups.size() > 0))
{
for (Iterator i = m_groups.iterator(); i.hasNext();)
{
String group = (String) i.next();
Element sect = doc.createElement("group");
event.appendChild(sect);
sect.setAttribute("authzGroup", group);
}
}
// properties
m_properties.toXml(doc, stack);
if ((m_attachments != null) && (m_attachments.size() > 0))
{
for (int i = 0; i < m_attachments.size(); i++)
{
Reference attch = (Reference) m_attachments.get(i);
Element attachment = doc.createElement("attachment");
event.appendChild(attachment);
attachment.setAttribute("relative-url", attch.getReference());
}
}
// rules
if (m_singleRule != null)
{
Element rules = doc.createElement("rules");
event.appendChild(rules);
stack.push(rules);
// the rule
m_singleRule.toXml(doc, stack);
// the exculsions
if (m_exclusionRule != null)
{
m_exclusionRule.toXml(doc, stack);
}
stack.pop();
}
stack.pop();
return event;
} // toXml
/**
* Access the event code for this edit.
*
* @return The event code for this edit.
*/
protected String getEvent()
{
return m_event;
}
/**
* Set the event code for this edit.
*
* @param event
* The event code for this edit.
*/
protected void setEvent(String event)
{
m_event = event;
}
/**
* Access the resource's properties for modification
*
* @return The resource's properties.
*/
public ResourcePropertiesEdit getPropertiesEdit()
{
return m_properties;
} // getPropertiesEdit
/**
* Enable editing.
*/
protected void activate()
{
m_active = true;
} // activate
/**
* Check to see if the edit is still active, or has already been closed.
*
* @return true if the edit is active, false if it's been closed.
*/
public boolean isActiveEdit()
{
return m_active;
} // isActiveEdit
/**
* Close the edit object - it cannot be used after this.
*/
protected void closeEdit()
{
m_active = false;
} // closeEdit
/******************************************************************************************************************************************************************************************************************************************************
* AttachmentContainer implementation
*****************************************************************************************************************************************************************************************************************************************************/
/**
* Access the attachments of the event.
*
* @return An copy of the set of attachments (a ReferenceVector containing Reference objects) (may be empty).
*/
public List getAttachments()
{
return m_entityManager.newReferenceList(m_attachments);
} // getAttachments
/**
* Add an attachment.
*
* @param ref
* The attachment Reference.
*/
public void addAttachment(Reference ref)
{
m_attachments.add(ref);
} // addAttachment
/**
* Remove an attachment.
*
* @param ref
* The attachment Reference to remove (the one removed will equal this, they need not be ==).
*/
public void removeAttachment(Reference ref)
{
m_attachments.remove(ref);
} // removeAttachment
/**
* Replace the attachment set.
*
* @param attachments
* A vector of Reference objects that will become the new set of attachments.
*/
public void replaceAttachments(List attachments)
{
m_attachments.clear();
if (attachments != null)
{
Iterator it = attachments.iterator();
while (it.hasNext())
{
m_attachments.add(it.next());
}
}
} // replaceAttachments
/**
* Clear all attachments.
*/
public void clearAttachments()
{
m_attachments.clear();
} // clearAttachments
/**
* {@inheritDoc}
*/
public EventAccess getAccess()
{
return m_access;
}
/**
* {@inheritDoc}
*/
public Collection getGroups()
{
return new Vector(m_groups);
}
/**
* {@inheritDoc}
*/
public Collection getGroupObjects()
{
Vector rv = new Vector();
if (m_groups != null)
{
for (Iterator i = m_groups.iterator(); i.hasNext();)
{
String groupId = (String) i.next();
Group group = m_siteService.findGroup(groupId);
if (group != null)
{
rv.add(group);
}
}
}
return rv;
}
/**
* @inheritDoc
*/
public void setGroupAccess(Collection groups, boolean own) throws PermissionException
{
// convenience (and what else are we going to do?)
if ((groups == null) || (groups.size() == 0))
{
clearGroupAccess();
return;
}
// is there any change? If we are already grouped, and the group list is the same, ignore the call
if ((m_access == EventAccess.GROUPED) && (EntityCollections.isEqualEntityRefsToEntities(m_groups, groups))) return;
// isolate any groups that would be removed or added
Collection addedGroups = new Vector();
Collection removedGroups = new Vector();
EntityCollections.computeAddedRemovedEntityRefsFromNewEntitiesOldRefs(addedGroups, removedGroups, groups, m_groups);
// verify that the user has permission to remove
if (removedGroups.size() > 0)
{
// the Group objects the user has remove permission
Collection allowedGroups = m_calendar.getGroupsAllowRemoveEvent(own);
for (Iterator i = removedGroups.iterator(); i.hasNext();)
{
String ref = (String) i.next();
// is ref a group the user can remove from?
if ( !EntityCollections.entityCollectionContainsRefString(allowedGroups, ref) )
{
throw new PermissionException(m_sessionManager.getCurrentSessionUserId(), "access:group:remove", ref);
}
}
}
// verify that the user has permission to add in those contexts
if (addedGroups.size() > 0)
{
// the Group objects the user has add permission
Collection allowedGroups = m_calendar.getGroupsAllowAddEvent();
for (Iterator i = addedGroups.iterator(); i.hasNext();)
{
String ref = (String) i.next();
// is ref a group the user can remove from?
if (!EntityCollections.entityCollectionContainsRefString(allowedGroups, ref))
{
throw new PermissionException(m_sessionManager.getCurrentSessionUserId(), "access:group:add", ref);
}
}
}
// we are clear to perform this
m_access = EventAccess.GROUPED;
EntityCollections.setEntityRefsFromEntities(m_groups, groups);
}
/**
* @inheritDoc
*/
public void clearGroupAccess() throws PermissionException
{
// is there any change? If we are already channel, ignore the call
if (m_access == EventAccess.SITE) return;
// verify that the user has permission to add in the calendar context
boolean allowed = m_calendar.allowAddCalendarEvent();
if (!allowed)
{
throw new PermissionException(m_sessionManager.getCurrentSessionUserId(), "access:channel", getReference());
}
// we are clear to perform this
m_access = EventAccess.SITE;
m_groups.clear();
}
/******************************************************************************************************************************************************************************************************************************************************
* SessionBindingListener implementation
*****************************************************************************************************************************************************************************************************************************************************/
public void valueBound(SessionBindingEvent event)
{
}
public void valueUnbound(SessionBindingEvent event)
{
if (M_log.isDebugEnabled()) M_log.debug("valueUnbound()");
// catch the case where an edit was made but never resolved
if (m_active)
{
m_calendar.cancelEvent(this);
}
} // valueUnbound
/**
* Gets the containing calendar's reference.
*
* @return The containing calendar reference.
*/
public String getCalendarReference()
{
return m_calendar.getReference();
} // getCalendarReference
public String getGroupRangeForDisplay(Calendar cal)
{
// TODO: check this - if used for the UI list, it needs the user's groups and the event's groups... -ggolden
if (m_access.equals(CalendarEvent.EventAccess.SITE))
{
return "";
}
else
{
int count = 0;
String allGroupString="";
try
{
Site site = m_siteService.getSite(cal.getContext());
for (Iterator i= m_groups.iterator(); i.hasNext();)
{
Group aGroup = site.getGroup((String) i.next());
if (aGroup != null)
{
count++;
if (count > 1)
{
allGroupString = allGroupString.concat(", ").concat(aGroup.getTitle());
}
else
{
allGroupString = aGroup.getTitle();
}
}
}
}
catch (IdUnusedException e)
{
// No site available.
}
return allGroupString;
}
}
/**
* Get a content handler suitable for populating this object from SAX events
* @return
*/
public ContentHandler getContentHandler(final Map<String,Object> services)
{
final Entity thisEntity = this;
return new DefaultEntityHandler() {
/* (non-Javadoc)
* @see org.sakaiproject.util.DefaultEntityHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)
*/
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException
{
if ( doStartElement(uri, localName, qName, attributes) ) {
if ( "event".equals(qName) && entity == null ) {
m_id = attributes.getValue("id");
m_range = m_timeService.newTimeRange(attributes
.getValue("range"));
m_access = CalendarEvent.EventAccess.SITE;
String access_str = String.valueOf(attributes
.getValue("access"));
if (access_str.equals(CalendarEvent.EventAccess.GROUPED
.toString()))
m_access = CalendarEvent.EventAccess.GROUPED;
entity = thisEntity;
}
else if ("attachment".equals(qName))
{
m_attachments.add(m_entityManager.newReference(attributes
.getValue("relative-url")));
}
else if ("group".equals(qName))
{
m_groups.add(attributes.getValue("authzGroup"));
}
else if ("rules".equals(qName))
{
// we can ignore this as its a contianer
}
else if ("rule".equals(qName) || "ex-rule".equals(qName))
{
// get the rule name - modern style encoding
String ruleName = StringUtils.trimToNull(attributes.getValue("name"));
// deal with old data
if (ruleName == null)
{
// get the class - this is old CHEF 1.2.10 style encoding
String ruleClassOld = attributes.getValue("class");
// use the last class name minus the package
if ( ruleClassOld != null )
ruleName = ruleClassOld.substring(ruleClassOld.lastIndexOf('.') + 1);
if ( ruleName == null )
M_log.warn("trouble loading rule");
}
if (ruleName != null)
{
// put my package on the class name
String ruleClass = this.getClass().getPackage().getName() + "." + ruleName;
// construct
try
{
if ("rule".equals(qName))
{
m_singleRule = (RecurrenceRule) Class.forName(ruleClass).newInstance();
setContentHandler(m_singleRule.getContentHandler(services), uri, localName, qName, attributes);
}
else // ("ex-rule".equals(qName))
{
m_exclusionRule = (RecurrenceRule) Class.forName(ruleClass).newInstance();
setContentHandler(m_exclusionRule.getContentHandler(services), uri, localName, qName, attributes);
}
}
catch (Exception e)
{
M_log.warn("trouble loading rule: " + ruleClass + " : " + e);
}
}
}
else
{
M_log.warn("Unexpected Element "+qName);
}
}
}
};
}
} // BaseCalendarEvent
/**********************************************************************************************************************************************************************************************************************************************************
* Storage implementation
*********************************************************************************************************************************************************************************************************************************************************/
protected interface Storage
{
/**
* Open and read.
*/
public void open();
/**
* Write and Close.
*/
public void close();
/**
* Return the identified calendar, or null if not found.
*/
public Calendar getCalendar(String ref);
/**
* Return true if the identified calendar exists.
*/
public boolean checkCalendar(String ref);
/**
* Get a list of all calendars
*/
public List getCalendars();
/**
* Keep a new calendar.
*/
public CalendarEdit putCalendar(String ref);
/**
* Get a calendar locked for update
*/
public CalendarEdit editCalendar(String ref);
/**
* Commit a calendar edit.
*/
public void commitCalendar(CalendarEdit edit);
/**
* Cancel a calendar edit.
*/
public void cancelCalendar(CalendarEdit edit);
/**
* Forget about a calendar.
*/
public void removeCalendar(CalendarEdit calendar);
/**
* Get a event from a calendar.
*/
public CalendarEvent getEvent(Calendar calendar, String eventId);
/**
* Get a event from a calendar locked for update
*/
public CalendarEventEdit editEvent(Calendar calendar, String eventId);
/**
* Commit an edit.
*/
public void commitEvent(Calendar calendar, CalendarEventEdit edit);
/**
* Cancel an edit.
*/
public void cancelEvent(Calendar calendar, CalendarEventEdit edit);
/**
* Does this events exist in a calendar?
*/
public boolean checkEvent(Calendar calendar, String eventId);
/**
* Get all events from a calendar
*/
public List getEvents(Calendar calendar);
/**
* Get the events from a calendar, within this time range
*/
public List getEvents(Calendar calendar, long l, long m);
/**
* Make and lock a new event.
*/
public CalendarEventEdit putEvent(Calendar calendar, String id);
/**
* Forget about a event.
*/
public void removeEvent(Calendar calendar, CalendarEventEdit edit);
} // Storage
/**********************************************************************************************************************************************************************************************************************************************************
* CacheRefresher implementation (no container)
*********************************************************************************************************************************************************************************************************************************************************/
/**
* Get a new value for this key whose value has already expired in the cache.
*
* @param key
* The key whose value has expired and needs to be refreshed.
* @param oldValue
* The old exipred value of the key.
* @param event
* The event which triggered this refresh.
* @return a new value for use in the cache for this key; if null, the entry will be removed.
*/
public Object refresh(Object key, Object oldValue, Event event)
{
Object rv = null;
// key is a reference
Reference ref = m_entityManager.newReference((String) key);
// get from storage only (not cache!)
// for events
if (REF_TYPE_EVENT.equals(ref.getSubType()))
{
if (M_log.isDebugEnabled())
M_log.debug("refresh(): key " + key + " calendar id : " + ref.getContext() + "/" + ref.getContainer()
+ " event id : " + ref.getId());
// get calendar (Note: from the cache is ok)
Calendar calendar = findCalendar(calendarReference(ref.getContext(), ref.getContainer()));
// get the CalendarEvent (Note: not from cache! but only from storage)
if (calendar != null)
{
rv = m_storage.getEvent(calendar, ref.getId());
}
}
// for calendar
else
{
if (M_log.isDebugEnabled()) M_log.debug("refresh(): key " + key + " calendar id : " + ref.getReference());
// return the calendar (Note: not from cache! but only from storage)
rv = m_storage.getCalendar(ref.getReference());
}
return rv;
} // refresh
/**********************************************************************************************************************************************************************************************************************************************************
* StorageUser implementation
*********************************************************************************************************************************************************************************************************************************************************/
/**
* Construct a new continer given just an id.
*
* @param ref
* The reference for the new object.
* @return The new containe Resource.
*/
public Entity newContainer(String ref)
{
return new BaseCalendarEdit(ref);
}
/**
* Construct a new container resource, from an XML element.
*
* @param element
* The XML.
* @return The new container resource.
*/
public Entity newContainer(Element element)
{
return new BaseCalendarEdit(element);
}
/**
* Construct a new container resource, as a copy of another
*
* @param other
* The other contianer to copy.
* @return The new container resource.
*/
public Entity newContainer(Entity other)
{
return new BaseCalendarEdit((Calendar) other);
}
/**
* Construct a new rsource given just an id.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param id
* The id for the new object.
* @param others
* (options) array of objects to load into the Resource's fields.
* @return The new resource.
*/
public Entity newResource(Entity container, String id, Object[] others)
{
return new BaseCalendarEventEdit((Calendar) container, id);
}
/**
* Construct a new resource, from an XML element.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param element
* The XML.
* @return The new resource from the XML.
*/
public Entity newResource(Entity container, Element element)
{
return new BaseCalendarEventEdit((Calendar) container, element);
}
/**
* Construct a new resource from another resource of the same type.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param other
* The other resource.
* @return The new resource as a copy of the other.
*/
public Entity newResource(Entity container, Entity other)
{
return new BaseCalendarEventEdit((Calendar) container, (CalendarEvent) other);
}
/**
* Construct a new continer given just an id.
*
* @param ref
* The reference for the new object.
* @return The new containe Resource.
*/
public Edit newContainerEdit(String ref)
{
BaseCalendarEdit rv = new BaseCalendarEdit(ref);
rv.activate();
return rv;
}
/**
* Construct a new container resource, from an XML element.
*
* @param element
* The XML.
* @return The new container resource.
*/
public Edit newContainerEdit(Element element)
{
BaseCalendarEdit rv = new BaseCalendarEdit(element);
rv.activate();
return rv;
}
/**
* Construct a new container resource, as a copy of another
*
* @param other
* The other contianer to copy.
* @return The new container resource.
*/
public Edit newContainerEdit(Entity other)
{
BaseCalendarEdit rv = new BaseCalendarEdit((Calendar) other);
rv.activate();
return rv;
}
/**
* Construct a new rsource given just an id.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param id
* The id for the new object.
* @param others
* (options) array of objects to load into the Resource's fields.
* @return The new resource.
*/
public Edit newResourceEdit(Entity container, String id, Object[] others)
{
BaseCalendarEventEdit rv = new BaseCalendarEventEdit((Calendar) container, id);
rv.activate();
return rv;
}
/**
* Construct a new resource, from an XML element.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param element
* The XML.
* @return The new resource from the XML.
*/
public Edit newResourceEdit(Entity container, Element element)
{
BaseCalendarEventEdit rv = new BaseCalendarEventEdit((Calendar) container, element);
rv.activate();
return rv;
}
/**
* Construct a new resource from another resource of the same type.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param other
* The other resource.
* @return The new resource as a copy of the other.
*/
public Edit newResourceEdit(Entity container, Entity other)
{
BaseCalendarEventEdit rv = new BaseCalendarEventEdit((Calendar) container, (CalendarEvent) other);
rv.activate();
return rv;
}
/**
* Collect the fields that need to be stored outside the XML (for the resource).
*
* @return An array of field values to store in the record outside the XML (for the resource).
*/
public Object[] storageFields(Entity r)
{
Object[] rv = new Object[4];
TimeRange range = ((CalendarEvent) r).getRange();
rv[0] = range.firstTime(); // %%% fudge?
rv[1] = range.lastTime(); // %%% fudge?
// we use hours rather than ms for the range to reduce the index size in the database
// I dont what to use days just incase we want sub day range finds
long oneHour = 60L*60L*1000L;
rv[2] = (int)(range.firstTime().getTime()/oneHour);
rv[3] = (int)(range.lastTime().getTime()/oneHour);
// find the end of the sequence
RecurrenceRuleBase rr = (RecurrenceRuleBase)((CalendarEvent) r).getRecurrenceRule();
if ( rr != null ) {
Time until = rr.getUntil();
if ( until != null ) {
rv[3] = (int)(until.getTime()/oneHour);
} else {
int count = rr.getCount();
int interval = rr.getInterval();
long endevent = range.lastTime().getTime();
if ( count == 0 ) {
rv[3] = Integer.MAX_VALUE-1; // hours since epoch, this represnts 9 Oct 246953 07:00:00
} else {
String frequency = rr.getFrequency();
GregorianCalendar c = new GregorianCalendar();
c.setTimeInMillis(endevent);
c.add(rr.getRecurrenceType(), count*interval);
rv[3] = (int)(c.getTimeInMillis()/oneHour);
}
}
}
return rv;
}
/**
* Check if this resource is in draft mode.
*
* @param r
* The resource.
* @return true if the resource is in draft mode, false if not.
*/
public boolean isDraft(Entity r)
{
return false;
}
/**
* Access the resource owner user id.
*
* @param r
* The resource.
* @return The resource owner user id.
*/
public String getOwnerId(Entity r)
{
return null;
}
/**
* Access the resource date.
*
* @param r
* The resource.
* @return The resource date.
*/
public Time getDate(Entity r)
{
return null;
}
/**********************************************************************************************************************************************************************************************************************************************************
* PDF file generation
*********************************************************************************************************************************************************************************************************************************************************/
// XSL File Names
protected final static String DAY_VIEW_XSLT_FILENAME = "schedule.xsl";
protected final static String LIST_VIEW_XSLT_FILENAME = "schlist.xsl";
protected final static String MONTH_VIEW_XSLT_FILENAME = "schedulemm.xsl";
protected final static String WEEK_VIEW_XSLT_FILENAME = "schedule.xsl";
// FOP Configuration
protected final static String FOP_USERCONFIG = "fonts/userconfig.xml";
protected final static String FOP_FONTBASEDIR = "fonts";
// Mime Types
protected final static String PDF_MIME_TYPE = "application/pdf";
protected final static String ICAL_MIME_TYPE = "text/calendar";
// Constants for time calculations
protected static long MILLISECONDS_IN_DAY = (60 * 60 * 24 * 1000);
protected final static long MILLISECONDS_IN_HOUR = (60 * 60 * 1000);
protected final static long MILLISECONDS_IN_MINUTE = (1000 * 60);
protected static final long MINIMUM_EVENT_LENGTH_IN_MSECONDS = (29 * MILLISECONDS_IN_MINUTE);
protected static final int SCHEDULE_INTERVAL_IN_MINUTES = 15;
protected static final int MAX_OVERLAPPING_COLUMNS = 7;
protected static final int TIMESLOT_FOR_OVERLAP_DETECTION_IN_MINUTES = 10;
// URL Parameter Constants
protected static final String TIME_RANGE_PARAMETER_NAME = "timeRange";
protected static final String DAILY_START_TIME_PARAMETER_NAME = "dailyStartTime";
protected final static String USER_NAME_PARAMETER_NAME = "user";
protected final static String CALENDAR_PARAMETER_BASE_NAME = "calendar";
protected final static String SCHEDULE_TYPE_PARAMETER_NAME = "scheduleType";
// XML Node/Attribute Names
protected static final String COLUMN_NODE_NAME = "col";
protected static final String EVENT_NODE_NAME = "event";
protected static final String FACULTY_EVENT_ATTRIBUTE_NAME = "Faculty";
protected static final String FACULTY_NODE = "faculty";
protected static final String DESCRIPTION_NODE = "description";
protected static final String FROM_ATTRIBUTE_STRING = "from";
protected static final String GROUP_NODE = "grp";
protected static final String LIST_DATE_ATTRIBUTE_NAME = "dt";
protected static final String LIST_DAY_OF_MONTH_ATTRIBUTE_NAME = "dayofmonth";
protected static final String LIST_DAY_OF_WEEK_ATTRIBUTE_NAME = "dayofweek";
protected static final String LIST_NODE_NAME = "list";
protected static final String MONTH_NODE_NAME = "month";
protected static final String MAX_CONCURRENT_EVENTS_NAME = "maxConcurrentEvents";
protected static final String PLACE_NODE = "place";
protected static final String ROW_NODE_NAME = "row";
protected static final String SCHEDULE_NODE = "schedule";
protected static final String START_DAY_WEEK_ATTRIBUTE_NAME = "startdayweek";
protected static final String MONTH_ATTRIBUTE_NAME = "month";
protected static final String YEAR_ATTRIBUTE_NAME = "yyyy";
protected static final String START_TIME_ATTRIBUTE_NAME = "start-time";
protected static final String SUB_EVENT_NODE_NAME = "subEvent";
protected static final String TITLE_NODE = "title";
protected static final String TO_ATTRIBUTE_STRING = "to";
protected static final String TYPE_NODE = "type";
protected static final String UID_NODE = "uid";
// Misc.
protected static final String HOUR_MINUTE_SEPARATOR = ":";
/**
* This is a container for a list of columns, plus the timerange for all the events contained in the row. This time range is a union of all the separate time ranges.
*/
protected class LayoutRow extends ArrayList
{
// Union of all event time ranges in this row.
private TimeRange rowTimeRange;
/**
* Gets the union of all event time ranges in this row.
*/
public TimeRange getRowTimeRange()
{
return rowTimeRange;
}
/**
* Sets the union of all event time ranges in this row.
*/
public void setRowTimeRange(TimeRange range)
{
rowTimeRange = range;
}
}
/**
* Table used to layout a single day, with potentially overlapping events.
*/
protected class SingleDayLayoutTable
{
protected long millisecondsPerTimeslot;
protected int numCols;
protected int numRows;
protected ArrayList rows;
// Overall time range for this table.
protected TimeRange timeRange;
/**
* Constructor for SingleDayLayoutTable
*/
public SingleDayLayoutTable(TimeRange timeRange, int maxNumberOverlappingEvents, int timeslotInMinutes)
{
this.timeRange = timeRange;
numCols = maxNumberOverlappingEvents;
millisecondsPerTimeslot = timeslotInMinutes * MILLISECONDS_IN_MINUTE;
numRows = getNumberOfRowsNeeded(timeRange);
rows = new ArrayList(numRows);
for (int i = 0; i < numRows; i++)
{
ArrayList newRow = new ArrayList(numCols);
rows.add(i, newRow);
for (int j = 0; j < numCols; j++)
{
newRow.add(j, new LayoutTableCell());
}
}
}
/**
* Adds an event to the SingleDayLayoutTable
*/
public void addEvent(CalendarEvent calendarEvent)
{
if (calendarEvent == null)
{
return;
}
int startingRow = getStartingRow(roundRangeToMinimumTimeInterval(calendarEvent.getRange()));
int numRowsNeeded = getNumberOfRowsNeeded(roundRangeToMinimumTimeInterval(calendarEvent.getRange()));
// Trim to the end of the table.
if (startingRow + numRowsNeeded >= getNumRows())
{
numRowsNeeded = getNumRows() - startingRow;
}
// Get the first column that has enough sequential free intervals to
// contain this event.
int columnNumber = getFreeColumn(startingRow, numRowsNeeded);
if (columnNumber != -1)
{
for (int i = startingRow; i < startingRow + numRowsNeeded; i++)
{
LayoutTableCell cell = getCell(i, columnNumber);
// All cells have the calendar event information.
cell.setCalendarEvent(calendarEvent);
// Only the first cell is marked as such.
if (i == startingRow)
{
cell.setFirstCell(true);
}
cell.setFirstCellRow(startingRow);
cell.setFirstCellColumn(columnNumber);
cell.setThisCellRow(i);
cell.setThisCellColumn(columnNumber);
cell.setNumCellsInEvent(numRowsNeeded);
}
}
}
/**
* Convert the time range to fall entirely within the time range of the layout table.
*/
protected TimeRange adjustTimeRangeToLayoutTable(TimeRange eventTimeRange)
{
Time lowerBound = null, upperBound = null;
//
// Make sure that the upper/lower bounds fall within the layout table.
//
if (this.timeRange.firstTime().compareTo(eventTimeRange.firstTime()) > 0)
{
lowerBound = this.timeRange.firstTime();
}
else
{
lowerBound = eventTimeRange.firstTime();
}
if (this.timeRange.lastTime().compareTo(eventTimeRange.lastTime()) < 0)
{
upperBound = this.timeRange.lastTime();
}
else
{
upperBound = eventTimeRange.lastTime();
}
return m_timeService.newTimeRange(lowerBound, upperBound, true, false);
}
/**
* Returns true if there are any events in this or other rows that overlap the event associated with this cell.
*/
protected boolean cellHasOverlappingEvents(int rowNum, int colNum)
{
LayoutTableCell cell = this.getFirstCell(rowNum, colNum);
// Start at the first cell of this event and check every row
// to see if we find any cells in that row that are not empty
// and are not one of ours.
if (cell != null && !cell.isEmptyCell())
{
for (int i = cell.getFirstCellRow(); i < (cell.getFirstCellRow() + cell.getNumCellsInEvent()); i++)
{
for (int j = 0; j < this.numCols; j++)
{
LayoutTableCell curCell = this.getCell(i, j);
if (curCell != null && !curCell.isEmptyCell() && curCell.getCalendarEvent() != cell.getCalendarEvent())
{
return true;
}
}
}
}
return false;
}
/**
* Get a particular cell. Returns a reference to the actual cell and not a copy.
*/
protected LayoutTableCell getCell(int rowNum, int colNum)
{
if (rowNum < 0 || rowNum >= this.numRows || colNum < 0 || colNum >= this.numCols)
{
// Illegal cell indices
return null;
}
else
{
ArrayList row = (ArrayList) rows.get(rowNum);
return (LayoutTableCell) row.get(colNum);
}
}
/**
* Gets the first cell associated with the event that's stored at this row/column
*/
protected LayoutTableCell getFirstCell(int rowNum, int colNum)
{
LayoutTableCell cell = this.getCell(rowNum, colNum);
if (cell == null || cell.isEmptyCell())
{
return null;
}
else
{
return getCell(cell.getFirstCellRow(), cell.getFirstCellColumn());
}
}
/**
* Looks for a column where the whole event can be placed.
*/
protected int getFreeColumn(int rowNum, int numberColumnsNeeded)
{
// Keep going through the columns until we hit one that has
// enough empty cells to accomodate our event.
for (int i = 0; i < this.numCols; i++)
{
boolean foundOccupiedCell = false;
for (int j = rowNum; j < rowNum + numberColumnsNeeded; j++)
{
LayoutTableCell cell = getCell(j, i);
if (cell == null)
{
// Out of range.
return -1;
}
if (!cell.isEmptyCell())
{
foundOccupiedCell = true;
break;
}
}
if (!foundOccupiedCell)
{
return i;
}
}
return -1;
}
/**
* Creates a list of lists of lists. The outer list is a list of rows. Each row is a list of columns. Each column is a list of column values.
*/
public List getLayoutRows()
{
List allRows = new ArrayList();
// Scan all rows in the table.
for (int mainRowIndex = 0; mainRowIndex < this.getNumRows(); mainRowIndex++)
{
// If we hit a starting row, then iterate through all rows of the
// event group.
if (isStartingRowOfGroup(mainRowIndex))
{
LayoutRow newRow = new LayoutRow();
allRows.add(newRow);
int numRowsInGroup = getNumberRowsInEventGroup(mainRowIndex);
newRow.setRowTimeRange(getTimeRangeForEventGroup(mainRowIndex, numRowsInGroup));
for (int columnIndex = 0; columnIndex < this.getNumCols(); columnIndex++)
{
List columnList = new ArrayList();
boolean addedCell = false;
for (int eventGroupRowIndex = mainRowIndex; eventGroupRowIndex < mainRowIndex + numRowsInGroup; eventGroupRowIndex++)
{
LayoutTableCell cell = getCell(eventGroupRowIndex, columnIndex);
if (cell.isFirstCell())
{
columnList.add(cell.getCalendarEvent());
addedCell = true;
}
}
// Don't add to our list unless we actually added a cell.
if (addedCell)
{
newRow.add(columnList);
}
}
// Get ready for the next iteration. Skip those
// rows that we have already processed.
mainRowIndex += (numRowsInGroup - 1);
}
}
return allRows;
}
protected int getNumberOfRowsNeeded(TimeRange eventTimeRange)
{
TimeRange adjustedTimeRange = adjustTimeRangeToLayoutTable(eventTimeRange);
// Use the ceiling function to obtain the next highest integral number of time slots.
return (int) (Math.ceil((double) (adjustedTimeRange.duration()) / (double) millisecondsPerTimeslot));
}
/**
* Gets the number of rows in an event group. This function assumes that the row that it starts on is the starting row of the group.
*/
protected int getNumberRowsInEventGroup(int rowNum)
{
int numEventRows = 0;
if (isStartingRowOfGroup(rowNum))
{
numEventRows++;
// Keep going unless we see an all empty row
// or another starting row.
for (int i = rowNum + 1; i < this.getNumRows() && !isEmptyRow(i) && !isStartingRowOfGroup(i); i++)
{
numEventRows++;
}
}
return numEventRows;
}
/**
* Gets the total number of columns in the layout table.
*/
public int getNumCols()
{
return this.numCols;
}
/**
* Gets the total number of rows in the layout table.
*/
public int getNumRows()
{
return rows.size();
}
/**
* Given a time range, returns the starting row number in the layout table.
*/
protected int getStartingRow(TimeRange eventTimeRange)
{
TimeRange adjustedTimeRange = adjustTimeRangeToLayoutTable(eventTimeRange);
TimeRange timeRangeToStart = m_timeService.newTimeRange(this.timeRange.firstTime(), adjustedTimeRange.firstTime(), true,
true);
//
// We form a new time range where the ending time is the (adjusted) event
// time range and the starting time is the starting time of the layout table.
// The number of rows required for this range will be the starting row of the table.
//
return getNumberOfRowsNeeded(timeRangeToStart);
}
/**
* Returns the earliest/latest times for events in this group. This function assumes that the row that it starts on is the starting row of the group.
*/
public TimeRange getTimeRangeForEventGroup(int rowNum, int numRowsInThisEventGroup)
{
Time firstTime = null;
Time lastTime = null;
for (int i = rowNum; i < rowNum + numRowsInThisEventGroup; i++)
{
for (int j = 0; j < this.getNumCols(); j++)
{
LayoutTableCell cell = getCell(i, j);
CalendarEvent event = cell.getCalendarEvent();
if (event != null)
{
TimeRange adjustedTimeRange = adjustTimeRangeToLayoutTable(roundRangeToMinimumTimeInterval(cell
.getCalendarEvent().getRange()));
//
// Replace our earliest time to date with the
// time from the event, if the time from the
// event is earlier.
//
if (firstTime == null)
{
firstTime = adjustedTimeRange.firstTime();
}
else
{
Time eventFirstTime = adjustedTimeRange.firstTime();
if (eventFirstTime.compareTo(firstTime) < 0)
{
firstTime = eventFirstTime;
}
}
//
// Replace our latest time to date with the
// time from the event, if the time from the
// event is later.
//
if (lastTime == null)
{
lastTime = adjustedTimeRange.lastTime();
}
else
{
Time eventLastTime = adjustedTimeRange.lastTime();
if (eventLastTime.compareTo(lastTime) > 0)
{
lastTime = eventLastTime;
}
}
}
}
}
return m_timeService.newTimeRange(firstTime, lastTime, true, false);
}
/**
* Returns true if this row has only empty cells.
*/
protected boolean isEmptyRow(int rowNum)
{
boolean sawNonEmptyCell = false;
for (int i = 0; i < this.getNumCols(); i++)
{
LayoutTableCell cell = getCell(rowNum, i);
if (!cell.isEmptyCell())
{
sawNonEmptyCell = true;
break;
}
}
return !sawNonEmptyCell;
}
/**
* Returns true if this row has only starting cells and no continuation cells.
*/
protected boolean isStartingRowOfGroup(int rowNum)
{
boolean sawContinuationCells = false;
boolean sawFirstCell = false;
for (int i = 0; i < this.getNumCols(); i++)
{
LayoutTableCell cell = getCell(rowNum, i);
if (cell.isContinuationCell())
{
sawContinuationCells = true;
}
if (cell.isFirstCell)
{
sawFirstCell = true;
}
}
//
// In order to be a starting row must have a "first"
// cell no continuation cells.
//
return (!sawContinuationCells && sawFirstCell);
}
/**
* Returns true if there are any cells in this row associated with events which overlap each other in this row or any other row.
*/
public boolean rowHasOverlappingEvents(int rowNum)
{
for (int i = 0; i < this.getNumCols(); i++)
{
if (cellHasOverlappingEvents(rowNum, i))
{
return true;
}
}
return false;
}
}
/**
* This is a single cell in a layout table (an instance of SingleDayLayoutTable).
*/
protected class LayoutTableCell
{
protected CalendarEvent calendarEvent = null;
protected int firstCellColumn = -1;
protected int firstCellRow = -1;
protected boolean isFirstCell = false;
protected int numCellsInEvent = 0;
protected int thisCellColumn = -1;
protected int thisCellRow = -1;
/**
* Gets the calendar event associated with this cell.
*/
public CalendarEvent getCalendarEvent()
{
return calendarEvent;
}
/**
* Gets the first column associated with this cell.
*/
public int getFirstCellColumn()
{
return firstCellColumn;
}
/**
* Gets the first row associated with this cell.
*/
public int getFirstCellRow()
{
return firstCellRow;
}
/**
* Get the number of cells in this event.
*/
public int getNumCellsInEvent()
{
return numCellsInEvent;
}
/**
* Gets the column associated with this particular cell.
*/
public int getThisCellColumn()
{
return thisCellColumn;
}
/**
* Gets the row associated with this cell.
*/
public int getThisCellRow()
{
return thisCellRow;
}
/**
* Returns true if this cell is a continuation of an event and not the first cell in the event.
*/
public boolean isContinuationCell()
{
return !isFirstCell() && !isEmptyCell();
}
/**
* Returns true if this cell is not associated with any events.
*/
public boolean isEmptyCell()
{
return calendarEvent == null;
}
/**
* Returns true if this is the first cell in a column of cells associated with an event.
*/
public boolean isFirstCell()
{
return isFirstCell;
}
/**
* Set the calendar event associated with this cell.
*/
public void setCalendarEvent(CalendarEvent event)
{
calendarEvent = event;
}
/**
* Set flag indicating that this is the first cell in column of cells associated with an event.
*/
public void setFirstCell(boolean b)
{
isFirstCell = b;
}
/**
* Sets a value in this cell to point to the very first cell in the column of cells associated with this event.
*/
public void setFirstCellColumn(int i)
{
firstCellColumn = i;
}
/**
* Sets a value in this cell to point to the very first cell in the column of cells associated with this event.
*/
public void setFirstCellRow(int i)
{
firstCellRow = i;
}
/**
* Gets the number of cells (if any) in the group of cells associated with this cell by event.
*/
public void setNumCellsInEvent(int i)
{
numCellsInEvent = i;
}
/**
* Sets the actual column index for this cell.
*/
public void setThisCellColumn(int i)
{
thisCellColumn = i;
}
/**
* Sets the actual row index for this cell.
*/
public void setThisCellRow(int i)
{
thisCellRow = i;
}
}
/**
* Debugging routine to get a string for a TimeRange. This should probably be in the TimeRange class.
*/
protected String dumpTimeRange(TimeRange timeRange)
{
String returnString = "";
if (timeRange != null)
{
returnString = timeRange.firstTime().toStringLocalFull() + " - " + timeRange.lastTime().toStringLocalFull();
}
return returnString;
}
/**
* Takes a DOM structure and renders a PDF
*
* @param doc
* DOM structure
* @param xslFileName
* XSL file to use to translate the DOM document to FOP
*/
protected void generatePDF(Document doc, String xslFileName, OutputStream streamOut)
{
Driver driver = new Driver();
org.apache.avalon.framework.logger.Logger logger = new ConsoleLogger(ConsoleLogger.LEVEL_ERROR);
MessageHandler.setScreenLogger(logger);
driver.setLogger(logger);
try {
String baseDir = getClass().getClassLoader().getResource(FOP_FONTBASEDIR).toString();
Configuration.put("fontBaseDir", baseDir);
InputStream userConfig = getClass().getClassLoader().getResourceAsStream(FOP_USERCONFIG);
new Options(userConfig);
}
catch (FOPException fe){
M_log.warn(this+".generatePDF: ", fe);
}
catch(Exception e){
M_log.warn(this+".generatePDF: ", e);
}
driver.setOutputStream(streamOut);
driver.setRenderer(Driver.RENDER_PDF);
try
{
InputStream in = getClass().getClassLoader().getResourceAsStream(xslFileName);
Transformer transformer = transformerFactory.newTransformer(new StreamSource(in));
Source src = new DOMSource(doc);
java.util.Calendar c = java.util.Calendar.getInstance(m_timeService.getLocalTimeZone(),new ResourceLoader().getLocale());
CalendarUtil calUtil = new CalendarUtil(c);
String[] dayNames = calUtil.getCalendarDaysOfWeekNames(true);
// Kludge: Xalan in JDK 1.4/1.5 does not properly resolve java classes
// (http://xml.apache.org/xalan-j/faq.html#jdk14)
// Clean this up in JDK 1.6 and pass ResourceBundle/ArrayList parms
transformer.setParameter("dayNames0", dayNames[0]);
transformer.setParameter("dayNames1", dayNames[1]);
transformer.setParameter("dayNames2", dayNames[2]);
transformer.setParameter("dayNames3", dayNames[3]);
transformer.setParameter("dayNames4", dayNames[4]);
transformer.setParameter("dayNames5", dayNames[5]);
transformer.setParameter("dayNames6", dayNames[6]);
transformer.setParameter("jan", rb.getString("month.jan"));
transformer.setParameter("feb", rb.getString("month.feb"));
transformer.setParameter("mar", rb.getString("month.mar"));
transformer.setParameter("apr", rb.getString("month.apr"));
transformer.setParameter("may", rb.getString("month.may"));
transformer.setParameter("jun", rb.getString("month.jun"));
transformer.setParameter("jul", rb.getString("month.jul"));
transformer.setParameter("aug", rb.getString("month.aug"));
transformer.setParameter("sep", rb.getString("month.sep"));
transformer.setParameter("oct", rb.getString("month.oct"));
transformer.setParameter("nov", rb.getString("month.nov"));
transformer.setParameter("dec", rb.getString("month.dec"));
transformer.setParameter("site", rb.getString("event.site"));
transformer.setParameter("event", rb.getString("event.event"));
transformer.setParameter("location", rb.getString("event.location"));
transformer.setParameter("type", rb.getString("event.type"));
transformer.setParameter("from", rb.getString("event.from"));
transformer.setParameter("sched", rb.getString("sched.for"));
transformer.transform(src, new SAXResult(driver.getContentHandler()));
}
catch (TransformerException e)
{
e.printStackTrace();
M_log.warn(this+".generatePDF(): " + e);
return;
}
}
/**
* Make a full-day time range given a year, month, and day
*/
protected TimeRange getFullDayTimeRangeFromYMD(int year, int month, int day)
{
return m_timeService.newTimeRange(m_timeService.newTimeLocal(year, month, day, 0, 0, 0, 0), m_timeService.newTimeLocal(year,
month, day, 23, 59, 59, 999));
}
/**
* Make a list of days for use in generating an XML document for the list view.
*/
protected List makeListViewTimeRangeList(TimeRange timeRange, List calendarReferenceList)
{
// This is used to dimension a hash table. The default load factor is .75.
// A rehash isn't done until the number of items in the table is .75 * the number
// of items in the capacity.
final int DEFAULT_INITIAL_HASH_CAPACITY = 150;
List listOfDays = new ArrayList();
// Get a list of merged events.
CalendarEventVector calendarEventVector = getEvents(calendarReferenceList, timeRange);
Iterator itEvents = calendarEventVector.iterator();
HashMap datesSeenSoFar = new HashMap(DEFAULT_INITIAL_HASH_CAPACITY);
while (itEvents.hasNext())
{
CalendarEvent event = (CalendarEvent) itEvents.next();
//
// Each event may span multiple days, so we need to split each
// events's time range into single day slots.
//
List timeRangeList = splitTimeRangeIntoListOfSingleDayTimeRanges(event.getRange(), null);
Iterator itDatesInRange = timeRangeList.iterator();
while (itDatesInRange.hasNext())
{
TimeRange curDay = (TimeRange) itDatesInRange.next();
String curDate = curDay.firstTime().toStringLocalDate();
if (!datesSeenSoFar.containsKey(curDate))
{
// Add this day to list
TimeBreakdown startBreakDown = curDay.firstTime().breakdownLocal();
listOfDays.add(getFullDayTimeRangeFromYMD(startBreakDown.getYear(), startBreakDown.getMonth(), startBreakDown
.getDay()));
datesSeenSoFar.put(curDate, "");
}
}
}
return listOfDays;
}
/**
* @param scheduleType
* daily, weekly, monthly, or list (no yearly).
* @param doc
* XML output document
* @param timeRange
* this is the overall time range. For example, for a weekly schedule, it would be the start/end times for the currently selected week period.
* @param dailyTimeRange
* On a weekly time schedule, even if the overall time range is for a week, you're only looking at a portion of the day (e.g., 8 AM to 6 PM, etc.)
* @param userID
* This is the name of the user whose schedule is being printed.
*/
protected void generateXMLDocument(int scheduleType, Document doc, TimeRange timeRange, TimeRange dailyTimeRange,
List calendarReferenceList, String userID)
{
// This list will have an entry for every week day that we care about.
List timeRangeList = null;
TimeRange actualTimeRange = null;
Element topLevelMaxConcurrentEvents = null;
switch (scheduleType)
{
case WEEK_VIEW:
actualTimeRange = timeRange;
timeRangeList = getTimeRangeListForWeek(actualTimeRange, calendarReferenceList, dailyTimeRange);
break;
case MONTH_VIEW:
// Make sure that we trim off the days of the previous and next
// month. The time range that we're being passed is "padded"
// with extra days to make up a full block of an integral number
// of seven day weeks.
actualTimeRange = shrinkTimeRangeToCurrentMonth(timeRange);
timeRangeList = splitTimeRangeIntoListOfSingleDayTimeRanges(actualTimeRange, null);
break;
case LIST_VIEW:
//
// With the list view, we want to come up with a list of days
// that have events, not every day in the range.
//
actualTimeRange = timeRange;
timeRangeList = makeListViewTimeRangeList(actualTimeRange, calendarReferenceList);
break;
case DAY_VIEW:
//
// We have a single entry in the list for a day. Having a singleton
// list may seem wasteful, but it allows us to use one loop below
// for all processing.
//
actualTimeRange = timeRange;
timeRangeList = splitTimeRangeIntoListOfSingleDayTimeRanges(actualTimeRange, dailyTimeRange);
break;
default:
M_log.warn(".generateXMLDocument(): bad scheduleType parameter = " + scheduleType);
break;
}
if (timeRangeList != null)
{
// Create Root Element
Element root = doc.createElement(SCHEDULE_NODE);
if (userID != null)
{
writeStringNodeToDom(doc, root, UID_NODE, userID);
}
// Write out the number of events that we have per timeslot.
// This is used to figure out how to display overlapping events.
// At this level, assume that we start with 1 event.
topLevelMaxConcurrentEvents = writeStringNodeToDom(doc, root, MAX_CONCURRENT_EVENTS_NAME, "1");
// Add a start time node.
writeStringNodeToDom(doc, root, START_TIME_ATTRIBUTE_NAME, getTimeString(dailyTimeRange.firstTime()));
// Add the Root Element to Document
doc.appendChild(root);
//
// Only add a "month" node with the first numeric day
// of the month if we're in the month view.
//
if (scheduleType == MONTH_VIEW)
{
CalendarUtil monthCalendar = new CalendarUtil();
// Use the middle of the month since the start/end ranges
// may be in an adjacent month.
TimeBreakdown breakDown = actualTimeRange.firstTime().breakdownLocal();
monthCalendar.setDay(breakDown.getYear(), breakDown.getMonth(), breakDown.getDay());
int firstDayOfMonth = monthCalendar.getFirstDayOfMonth(breakDown.getMonth() - 1);
// Create a list of events for the given day.
Element monthElement = doc.createElement(MONTH_NODE_NAME);
monthElement.setAttribute(START_DAY_WEEK_ATTRIBUTE_NAME, Integer.toString(firstDayOfMonth));
monthElement.setAttribute(MONTH_ATTRIBUTE_NAME, Integer.toString(breakDown.getMonth()));
monthElement.setAttribute(YEAR_ATTRIBUTE_NAME, Integer.toString(breakDown.getYear()));
root.appendChild(monthElement);
}
Iterator itList = timeRangeList.iterator();
int maxNumberOfColumnsPerRow = 1;
// Go through all the time ranges (days)
while (itList.hasNext())
{
TimeRange currentTimeRange = (TimeRange) itList.next();
int maxConcurrentEventsOverListNode = 1;
// Get a list of merged events.
CalendarEventVector calendarEventVector = getEvents(calendarReferenceList, currentTimeRange);
//
// We don't need to generate "empty" event lists for the list view.
//
if (scheduleType == LIST_VIEW && calendarEventVector.size() == 0)
{
continue;
}
// Create a list of events for the given day.
Element eventList = doc.createElement(LIST_NODE_NAME);
// Set the current date
eventList.setAttribute(LIST_DATE_ATTRIBUTE_NAME, getDateFromTime(currentTimeRange.firstTime()));
eventList.setAttribute(LIST_DAY_OF_MONTH_ATTRIBUTE_NAME, getDayOfMonthFromTime(currentTimeRange.firstTime()));
// Set the maximum number of events per timeslot
// Assume 1 as a starting point. This may be changed
// later on.
eventList.setAttribute(MAX_CONCURRENT_EVENTS_NAME, Integer.toString(maxConcurrentEventsOverListNode));
// Calculate the day of the week.
java.util.Calendar c = java.util.Calendar.getInstance(m_timeService.getLocalTimeZone(),new ResourceLoader().getLocale());
CalendarUtil cal = new CalendarUtil(c);
Time date = currentTimeRange.firstTime();
TimeBreakdown breakdown = date.breakdownLocal();
cal.setDay(breakdown.getYear(), breakdown.getMonth(), breakdown.getDay());
// Set the day of the week as a node attribute.
eventList.setAttribute(LIST_DAY_OF_WEEK_ATTRIBUTE_NAME, Integer.toString(cal.getDay_Of_Week(true) - 1));
// Attach this list to the top-level node
root.appendChild(eventList);
Iterator itEvent = calendarEventVector.iterator();
//
// Day and week views use a layout table to assist in constructing the
// rowspan information for layout.
//
if (scheduleType == DAY_VIEW || scheduleType == WEEK_VIEW)
{
SingleDayLayoutTable layoutTable = new SingleDayLayoutTable(currentTimeRange, MAX_OVERLAPPING_COLUMNS,
SCHEDULE_INTERVAL_IN_MINUTES);
// Load all the events into our layout table.
while (itEvent.hasNext())
{
CalendarEvent event = (CalendarEvent) itEvent.next();
layoutTable.addEvent(event);
}
List layoutRows = layoutTable.getLayoutRows();
Iterator rowIterator = layoutRows.iterator();
// Iterate through the list of rows.
while (rowIterator.hasNext())
{
LayoutRow layoutRow = (LayoutRow) rowIterator.next();
TimeRange rowTimeRange = layoutRow.getRowTimeRange();
if (maxNumberOfColumnsPerRow < layoutRow.size())
{
maxNumberOfColumnsPerRow = layoutRow.size();
}
if (maxConcurrentEventsOverListNode < layoutRow.size())
{
maxConcurrentEventsOverListNode = layoutRow.size();
}
Element eventNode = doc.createElement(EVENT_NODE_NAME);
eventList.appendChild(eventNode);
// Add the "from" time as an attribute.
eventNode.setAttribute(FROM_ATTRIBUTE_STRING, getTimeString(rowTimeRange.firstTime()));
// Add the "to" time as an attribute.
eventNode.setAttribute(TO_ATTRIBUTE_STRING, getTimeString(performEndMinuteKludge(rowTimeRange.lastTime()
.breakdownLocal())));
Element rowNode = doc.createElement(ROW_NODE_NAME);
// Set an attribute indicating the number of columns in this row.
rowNode.setAttribute(MAX_CONCURRENT_EVENTS_NAME, Integer.toString(layoutRow.size()));
eventNode.appendChild(rowNode);
Iterator layoutRowIterator = layoutRow.iterator();
// Iterate through our list of column lists.
while (layoutRowIterator.hasNext())
{
Element columnNode = doc.createElement(COLUMN_NODE_NAME);
rowNode.appendChild(columnNode);
List columnList = (List) layoutRowIterator.next();
Iterator columnListIterator = columnList.iterator();
// Iterate through the list of columns.
while (columnListIterator.hasNext())
{
CalendarEvent event = (CalendarEvent) columnListIterator.next();
generateXMLEvent(doc, columnNode, event, SUB_EVENT_NODE_NAME, rowTimeRange, true, false, false);
}
}
}
}
else
{
// Generate XML for all the events.
while (itEvent.hasNext())
{
CalendarEvent event = (CalendarEvent) itEvent.next();
generateXMLEvent(doc, eventList, event, EVENT_NODE_NAME, currentTimeRange, false, false,
(scheduleType == LIST_VIEW ? true : false));
}
}
// Update this event after having gone through all the rows.
eventList.setAttribute(MAX_CONCURRENT_EVENTS_NAME, Integer.toString(maxConcurrentEventsOverListNode));
}
// Set the node value way up at the head of the document to indicate
// what the maximum number of columns was for the entire document.
topLevelMaxConcurrentEvents.getFirstChild().setNodeValue(Integer.toString(maxNumberOfColumnsPerRow));
}
}
/**
* @param ical
* iCal object
* @param calendarReferenceList
* This is the name of the user whose schedule is being printed.
* @return Number of events generated in ical object
*/
protected int generateICal(net.fortuna.ical4j.model.Calendar ical,
String calendarReference)
{
int numEvents = 0;
// This list will have an entry for every week day that we care about.
TimeRange currentTimeRange = getICalTimeRange();
// Get a list of events.
List calList = new ArrayList();
calList.add(calendarReference);
CalendarEventVector calendarEventVector = getEvents(calList, currentTimeRange);
Iterator itEvent = calendarEventVector.iterator();
// Generate XML for all the events.
while (itEvent.hasNext())
{
CalendarEvent event = (CalendarEvent) itEvent.next();
DateTime icalStartDate = new DateTime(event.getRange().firstTime().getTime());
long seconds = event.getRange().duration() / 1000;
String timeString = "PT" + String.valueOf(seconds) + "S";
net.fortuna.ical4j.model.Dur duration = new net.fortuna.ical4j.model.Dur( timeString );
VEvent icalEvent = new VEvent(icalStartDate, duration, event.getDisplayName() );
net.fortuna.ical4j.model.parameter.TzId tzId = new net.fortuna.ical4j.model.parameter.TzId( m_timeService.getLocalTimeZone().getID() );
icalEvent.getProperty(Property.DTSTART).getParameters().add(tzId);
icalEvent.getProperty(Property.DTSTART).getParameters().add(Value.DATE_TIME);
icalEvent.getProperties().add(new Uid(event.getId()));
// build the description, adding links to attachments if necessary
StringBuffer description = new StringBuffer("");
if ( event.getDescription() != null && !event.getDescription().equals("") )
description.append(event.getDescription());
List attachments = event.getAttachments();
if(attachments != null){
for (Iterator iter = attachments.iterator(); iter.hasNext();) {
Reference attachment = (Reference) iter.next();
description.append("\n");
description.append(attachment.getUrl());
description.append("\n");
}
}
if(description.length() > 0) {
//Replace \r with \n
icalEvent.getProperties().add(new Description(description.toString().replace('\r', '\n')));
}
if ( event.getLocation() != null && !event.getLocation().equals("") )
icalEvent.getProperties().add(new Location(event.getLocation()));
try
{
String organizer = m_userDirectoryService.getUser( event.getCreator() ).getDisplayName();
organizer = organizer.replaceAll(" ","%20"); // get rid of illegal URI characters
icalEvent.getProperties().add(new Organizer(new URI("CN="+organizer)));
}
catch (UserNotDefinedException e) {} // ignore
catch (URISyntaxException e) {} // ignore
StringBuffer comment = new StringBuffer(event.getType());
comment.append(" (");
comment.append(event.getSiteName());
comment.append(")");
icalEvent.getProperties().add(new Comment(comment.toString()));
ical.getComponents().add( icalEvent );
numEvents++;
/* TBD: add to VEvent: recurring schedule, ...
RecurenceRUle x = event.getRecurrenceRule();
*/
}
return numEvents;
}
/* Given a current date via the calendarUtil paramter, returns a TimeRange for the year,
* 6 months either side of the current date. (calculate milleseconds in 6 months)
*/
private static long SIX_MONTHS = (long)1000 * (long)60 * (long)60 * (long)24 * (long)183;
public TimeRange getICalTimeRange()
{
Time now = m_timeService.newTime();
Time startTime = m_timeService.newTime( now.getTime() - SIX_MONTHS );
Time endTime = m_timeService.newTime( now.getTime() + SIX_MONTHS );
return m_timeService.newTimeRange(startTime,endTime,true,true);
}
/**
* Trim the range that is passed in to the containing time range.
*/
protected TimeRange trimTimeRange(TimeRange containingRange, TimeRange rangeToTrim)
{
long containingRangeStartTime = containingRange.firstTime().getTime();
long containingRangeEndTime = containingRange.lastTime().getTime();
long rangeToTrimStartTime = rangeToTrim.firstTime().getTime();
long rangeToTrimEndTime = rangeToTrim.lastTime().getTime();
long trimmedStartTime = 0, trimmedEndTime = 0;
trimmedStartTime = Math.min(Math.max(containingRangeStartTime, rangeToTrimStartTime), containingRangeEndTime);
trimmedEndTime = Math.max(Math.min(containingRangeEndTime, rangeToTrimEndTime), rangeToTrimStartTime);
return m_timeService.newTimeRange(m_timeService.newTime(trimmedStartTime), m_timeService.newTime(trimmedEndTime), true, false);
}
/**
* Rounds a time range up to a minimum interval.
*/
protected TimeRange roundRangeToMinimumTimeInterval(TimeRange timeRange)
{
TimeRange roundedTimeRange = timeRange;
if (timeRange.duration() < MINIMUM_EVENT_LENGTH_IN_MSECONDS)
{
roundedTimeRange = m_timeService.newTimeRange(timeRange.firstTime().getTime(), MINIMUM_EVENT_LENGTH_IN_MSECONDS);
}
return roundedTimeRange;
}
/**
* Generates the XML for an event.
*/
protected void generateXMLEvent(Document doc, Element parent, CalendarEvent event, String eventNodeName,
TimeRange containingTimeRange, boolean forceMinimumTime, boolean hideGroupIfNoSpace, boolean performEndTimeKludge)
{
Element eventElement = doc.createElement(eventNodeName);
TimeRange trimmedTimeRange = trimTimeRange(containingTimeRange, event.getRange());
// Optionally force the event to have a minimum time slot.
if (forceMinimumTime)
{
trimmedTimeRange = roundRangeToMinimumTimeInterval(trimmedTimeRange);
}
// Add the "from" time as an attribute.
eventElement.setAttribute(FROM_ATTRIBUTE_STRING, getTimeString(trimmedTimeRange.firstTime()));
// Add the "to" time as an attribute.
Time endTime = null;
// Optionally adjust the end time
if (performEndTimeKludge)
{
endTime = performEndMinuteKludge(trimmedTimeRange.lastTime().breakdownLocal());
}
else
{
endTime = trimmedTimeRange.lastTime();
}
eventElement.setAttribute(TO_ATTRIBUTE_STRING, getTimeString(endTime));
//
// Add the group (really "site") node
// Provide that we have space or if we've been told we need to display it.
//
if (!hideGroupIfNoSpace || trimmedTimeRange.duration() > MINIMUM_EVENT_LENGTH_IN_MSECONDS)
{
writeStringNodeToDom(doc, eventElement, GROUP_NODE, event.getSiteName());
}
// Add the display name node.
writeStringNodeToDom(doc, eventElement, TITLE_NODE, event.getDisplayName());
// Add the event type node.
writeStringNodeToDom(doc, eventElement, TYPE_NODE, getEventDescription(event.getType()));
// Add the place/location node.
writeStringNodeToDom(doc, eventElement, PLACE_NODE, event.getLocation());
// If a "Faculty" extra field is present, then add the node.
writeStringNodeToDom(doc, eventElement, FACULTY_NODE, event.getField(FACULTY_EVENT_ATTRIBUTE_NAME));
// If a "Description" field is present, then add the node.
writeStringNodeToDom(doc, eventElement, DESCRIPTION_NODE, event.getDescription());
parent.appendChild(eventElement);
}
protected String getEventDescription(String type){
ResourceLoader rl = new ResourceLoader("calendar");
if ((type!=null) && (type.trim()!="")){
if (type.equals("Academic Calendar"))
return rl.getString("legend.key1");
else if (type.equals("Activity"))
return rl.getString("legend.key2");
else if (type.equals("Cancellation"))
return rl.getString("legend.key3");
else if (type.equals("Class section - Discussion"))
return rl.getString("legend.key4");
else if (type.equals("Class section - Lab"))
return rl.getString("legend.key5");
else if (type.equals("Class section - Lecture"))
return rl.getString("legend.key6");
else if (type.equals("Class section - Small Group"))
return rl.getString("legend.key7");
else if (type.equals("Class session"))
return rl.getString("legend.key8");
else if (type.equals("Computer Session"))
return rl.getString("legend.key9");
else if (type.equals("Deadline"))
return rl.getString("legend.key10");
else if (type.equals("Exam"))
return rl.getString("legend.key11");
else if (type.equals("Meeting"))
return rl.getString("legend.key12");
else if (type.equals("Multidisciplinary Conference"))
return rl.getString("legend.key13");
else if (type.equals("Quiz"))
return rl.getString("legend.key14");
else if (type.equals("Special event"))
return rl.getString("legend.key15");
else if (type.equals("Web Assignment"))
return rl.getString("legend.key16");
else if (type.equals("Teletutoria"))
return rl.getString("legend.key17");
else
return rl.getString("legend.key2");
}else{
return rl.getString("legend.key2");
}
}
/*
* Gets the daily start time parameter from a Properties object filled from URL parameters.
*/
protected TimeRange getDailyStartTimeFromParameters(Properties parameters)
{
return getTimeRangeParameterByName(parameters, DAILY_START_TIME_PARAMETER_NAME);
}
/**
* Gets the standard date string from the time parameter
*/
protected String getDateFromTime(Time time)
{
TimeBreakdown timeBreakdown = time.breakdownLocal();
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT,rb.getLocale());
return dateFormat.format(new Date(time.getTime()));
}
protected String getDayOfMonthFromTime(Time time)
{
TimeBreakdown timeBreakdown = time.breakdownLocal();
return Integer.toString(timeBreakdown.getDay());
}
/**
* Gets the schedule type from a Properties object (filled from a URL parameter list).
*/
protected int getScheduleTypeFromParameterList(Properties parameters)
{
int scheduleType = UNKNOWN_VIEW;
// Get the type of schedule (daily, weekly, etc.)
String scheduleTypeString = (String) parameters.get(SCHEDULE_TYPE_PARAMETER_NAME);
scheduleType = Integer.parseInt(scheduleTypeString);
return scheduleType;
}
/**
* Access some named configuration value as a string.
*
* @param name
* The configuration value name.
* @param dflt
* The value to return if not found.
* @return The configuration value with this name, or the default value if not found.
*/
protected String getString(String name, String dflt)
{
return m_serverConfigurationService.getString(name, dflt);
}
/*
* Gets the time range parameter from a Properties object filled from URL parameters.
*/
protected TimeRange getTimeRangeFromParameters(Properties parameters)
{
return getTimeRangeParameterByName(parameters, TIME_RANGE_PARAMETER_NAME);
}
/**
* Generates a list of time ranges for a week. Each range in the list is a day.
*
* @param timeRange start & end date range
* @param calendarReferenceList list of calendar(s)
* @param dailyTimeRange start and end hour/minute time range
*/
protected ArrayList getTimeRangeListForWeek(TimeRange timeRange, List calendarReferenceList, TimeRange dailyTimeRange)
{
TimeBreakdown startBreakdown = timeRange.firstTime().breakdownLocal();
GregorianCalendar startCalendarDate = (GregorianCalendar)GregorianCalendar.getInstance(m_timeService.getLocalTimeZone(), rb.getLocale());
startCalendarDate.set(startBreakdown.getYear(), startBreakdown.getMonth() - 1, startBreakdown.getDay(), 0, 0, 0);
ArrayList weekDayTimeRanges = new ArrayList();
TimeBreakdown startBreakDown = dailyTimeRange.firstTime().breakdownLocal();
TimeBreakdown endBreakDown = dailyTimeRange.lastTime().breakdownLocal();
// Search all seven weekdays
// Note: no assumption can be made regarding the first day being Sunday,
// since in some locales, the first weekday is Monday.
for (int i = 0; i <= 6; i++)
{
//
// Use the same start/end times for all days.
//
Time curStartTime = m_timeService.newTimeLocal(startCalendarDate.get(GregorianCalendar.YEAR), startCalendarDate
.get(GregorianCalendar.MONTH) + 1, startCalendarDate.get(GregorianCalendar.DAY_OF_MONTH), startBreakDown
.getHour(), startBreakDown.getMin(), startBreakDown.getSec(), startBreakDown.getMs());
Time curEndTime = m_timeService.newTimeLocal(startCalendarDate.get(GregorianCalendar.YEAR), startCalendarDate
.get(GregorianCalendar.MONTH) + 1, startCalendarDate.get(GregorianCalendar.DAY_OF_MONTH), endBreakDown
.getHour(), endBreakDown.getMin(), endBreakDown.getSec(), endBreakDown.getMs());
TimeRange newTimeRange = m_timeService.newTimeRange(curStartTime, curEndTime, true, false);
weekDayTimeRanges.add(newTimeRange);
// Move to the next day.
startCalendarDate.add(GregorianCalendar.DATE, 1);
}
return weekDayTimeRanges;
}
/**
* Utility routine to get a time range parameter from the URL parameters store in a Properties object.
*/
protected TimeRange getTimeRangeParameterByName(Properties parameters, String name)
{
// Now get the time range.
String timeRangeString = (String) parameters.get(name);
TimeRange timeRange = null;
timeRange = m_timeService.newTimeRange(timeRangeString);
return timeRange;
}
/**
* Gets a standard time string give the time parameter.
*/
protected String getTimeString(Time time)
{
TimeBreakdown timeBreakdown = time.breakdownLocal();
DecimalFormat twoDecimalDigits = new DecimalFormat("00");
return timeBreakdown.getHour() + HOUR_MINUTE_SEPARATOR + twoDecimalDigits.format(timeBreakdown.getMin());
}
/**
* Given a schedule type, the appropriate XSLT file is returned
*/
protected String getXSLFileNameForScheduleType(int scheduleType)
{
// get a relative path to the file
String baseFileName = "";
switch (scheduleType)
{
case WEEK_VIEW:
baseFileName = WEEK_VIEW_XSLT_FILENAME;
break;
case DAY_VIEW:
baseFileName = DAY_VIEW_XSLT_FILENAME;
break;
case MONTH_VIEW:
baseFileName = MONTH_VIEW_XSLT_FILENAME;
break;
case LIST_VIEW:
baseFileName = LIST_VIEW_XSLT_FILENAME;
break;
default:
M_log.debug("PrintFileGeneration.getXSLFileNameForScheduleType(): unexpected scehdule type = " + scheduleType);
break;
}
return baseFileName;
}
/**
* This routine is used to round the end time. The time is stored at one minute less than the actual end time,
* but the user will expect to see the end time on the hour. For example, an event that ends at 10:00 is
* actually stored at 9:59. This code should really be in a central place so that the velocity template can see it as well.
*/
protected Time performEndMinuteKludge(TimeBreakdown breakDown)
{
int endMin = breakDown.getMin();
int endHour = breakDown.getHour();
int tmpMinVal = endMin % TIMESLOT_FOR_OVERLAP_DETECTION_IN_MINUTES;
if (tmpMinVal == 4 || tmpMinVal == 9)
{
endMin = endMin + 1;
if (endMin == 60)
{
endMin = 00;
endHour = endHour + 1;
}
}
return m_timeService.newTimeLocal(breakDown.getYear(), breakDown.getMonth(), breakDown.getDay(), endHour, endMin, breakDown
.getSec(), breakDown.getMs());
}
protected List getCalendarReferenceList()
throws PermissionException
{
// Get the list of calendars.from user session
List calendarReferenceList = (List)m_sessionManager.getCurrentSession().getAttribute(SESSION_CALENDAR_LIST);
// check if there is any calendar to which the user has acces
Iterator it = calendarReferenceList.iterator();
int permissionCount = calendarReferenceList.size();
while (it.hasNext())
{
String calendarReference = (String) it.next();
try
{
getCalendar(calendarReference);
}
catch (IdUnusedException e)
{
continue;
}
catch (PermissionException e)
{
permissionCount--;
continue;
}
}
// if no permission to any of the calendars, throw exception and do nothing
// the expection will be caught by AccessServlet.doPrintingRequest()
if (permissionCount == 0)
{
throw new PermissionException("", "", "");
}
return calendarReferenceList;
}
protected void printICalSchedule(String calRef, OutputStream os)
throws PermissionException
{
// generate iCal text file
net.fortuna.ical4j.model.Calendar ical = new net.fortuna.ical4j.model.Calendar();
ical.getProperties().add(new ProdId("-//SakaiProject//iCal4j 1.0//EN"));
ical.getProperties().add(Version.VERSION_2_0);
ical.getProperties().add(CalScale.GREGORIAN);
TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry();
TzId tzId = new TzId( m_timeService.getLocalTimeZone().getID() );
ical.getComponents().add(registry.getTimeZone(tzId.getValue()).getVTimeZone());
CalendarOutputter icalOut = new CalendarOutputter();
int numEvents = generateICal(ical, calRef);
try
{
if ( numEvents > 0 )
icalOut.output( ical, os );
}
catch (Exception e)
{
M_log.warn(".printICalSchedule(): ", e);
}
}
/**
* Called by the servlet to service a get/post requesting a calendar in PDF format.
*/
protected void printSchedule(Properties parameters, OutputStream os) throws PermissionException
{
// Get the user name.
String userName = (String) parameters.get(USER_NAME_PARAMETER_NAME);
// Get the list of calendars.from user session
List calendarReferenceList = getCalendarReferenceList();
// Get the type of schedule (daily, weekly, etc.)
int scheduleType = getScheduleTypeFromParameterList(parameters);
// Now get the time range.
TimeRange timeRange = getTimeRangeFromParameters(parameters);
Document document = docBuilder.newDocument();
generateXMLDocument(scheduleType, document, timeRange, getDailyStartTimeFromParameters(parameters),
calendarReferenceList, userName);
generatePDF(document, getXSLFileNameForScheduleType(scheduleType), os);
}
/**
* The time ranges that we get from the CalendarAction class have days in the week of the first and last weeks padded out to make a full week. This function will shrink this range to only one month.
*/
protected TimeRange shrinkTimeRangeToCurrentMonth(TimeRange expandedTimeRange)
{
long millisecondsInWeek = (7 * MILLISECONDS_IN_DAY);
Time startTime = expandedTimeRange.firstTime();
// Grab something in the middle of the time range so that we know that we're
// in the right month.
Time somewhereInTheMonthTime = m_timeService.newTime(startTime.getTime() + 2 * millisecondsInWeek);
TimeBreakdown somewhereInTheMonthBreakdown = somewhereInTheMonthTime.breakdownLocal();
CalendarUtil calendar = new CalendarUtil();
calendar.setDay(somewhereInTheMonthBreakdown.getYear(), somewhereInTheMonthBreakdown.getMonth(),
somewhereInTheMonthBreakdown.getDay());
int numDaysInMonth = calendar.getNumberOfDays();
//
// Construct a new time range starting on the first day of the month and ending on
// the last day at one millisecond before midnight.
//
return m_timeService.newTimeRange(m_timeService.newTimeLocal(somewhereInTheMonthBreakdown.getYear(),
somewhereInTheMonthBreakdown.getMonth(), 1, 0, 0, 0, 0), m_timeService.newTimeLocal(somewhereInTheMonthBreakdown
.getYear(), somewhereInTheMonthBreakdown.getMonth(), numDaysInMonth, 23, 59, 59, 999));
}
/**
* Calculate the number of days in a range of time given two dates.
*
* @param startMonth
* (zero based, 0-11)
* @param startDay
* (one based, 1-31)
* @param endYear
* (one based, 1-31)
* @param endMonth
* (zero based, 0-11
*/
protected long getNumberDaysGivenTwoDates(int startYear, int startMonth, int startDay, int endYear, int endMonth, int endDay)
{
GregorianCalendar startDate = new GregorianCalendar();
GregorianCalendar endDate = new GregorianCalendar();
startDate.set(startYear, startMonth, startDay, 0, 0, 0);
endDate.set(endYear, endMonth, endDay, 0, 0, 0);
long duration = endDate.getTime().getTime() - startDate.getTime().getTime();
// Allow for daylight savings time.
return ((duration + MILLISECONDS_IN_HOUR) / (24 * MILLISECONDS_IN_HOUR)) + 1;
}
/**
* Returns a list of daily time ranges for every day in a range.
*
* @param timeRange
* overall time range
* @param dailyTimeRange
* representative daily time range (start hour/minute, end hour/minute). If null, this parameter is ignored.
*/
protected ArrayList splitTimeRangeIntoListOfSingleDayTimeRanges(TimeRange timeRange, TimeRange dailyTimeRange)
{
TimeBreakdown startBreakdown = timeRange.firstTime().breakdownLocal();
TimeBreakdown endBreakdown = timeRange.lastTime().breakdownLocal();
GregorianCalendar startCalendarDate = new GregorianCalendar();
startCalendarDate.set(startBreakdown.getYear(), startBreakdown.getMonth() - 1, startBreakdown.getDay(), 0, 0, 0);
long numDaysInTimeRange = getNumberDaysGivenTwoDates(startBreakdown.getYear(), startBreakdown.getMonth() - 1,
startBreakdown.getDay(), endBreakdown.getYear(), endBreakdown.getMonth() - 1, endBreakdown.getDay());
ArrayList splitTimeRanges = new ArrayList();
TimeBreakdown dailyStartBreakDown = null;
TimeBreakdown dailyEndBreakDown = null;
if (dailyTimeRange != null)
{
dailyStartBreakDown = dailyTimeRange.firstTime().breakdownLocal();
dailyEndBreakDown = dailyTimeRange.lastTime().breakdownLocal();
}
for (long i = 0; i < numDaysInTimeRange; i++)
{
Time curStartTime = null;
Time curEndTime = null;
if (dailyTimeRange != null)
{
//
// Use the same start/end times for all days.
//
curStartTime = m_timeService.newTimeLocal(startCalendarDate.get(GregorianCalendar.YEAR), startCalendarDate
.get(GregorianCalendar.MONTH) + 1, startCalendarDate.get(GregorianCalendar.DAY_OF_MONTH),
dailyStartBreakDown.getHour(), dailyStartBreakDown.getMin(), dailyStartBreakDown.getSec(),
dailyStartBreakDown.getMs());
curEndTime = m_timeService.newTimeLocal(startCalendarDate.get(GregorianCalendar.YEAR), startCalendarDate
.get(GregorianCalendar.MONTH) + 1, startCalendarDate.get(GregorianCalendar.DAY_OF_MONTH), dailyEndBreakDown
.getHour(), dailyEndBreakDown.getMin(), dailyEndBreakDown.getSec(), dailyEndBreakDown.getMs());
splitTimeRanges.add(m_timeService.newTimeRange(curStartTime, curEndTime, true, false));
}
else
{
//
// Add a full day range since no start/stop time was specified.
//
splitTimeRanges.add(getFullDayTimeRangeFromYMD(startCalendarDate.get(GregorianCalendar.YEAR), startCalendarDate
.get(GregorianCalendar.MONTH) + 1, startCalendarDate.get(GregorianCalendar.DAY_OF_MONTH)));
}
// Move to the next day.
startCalendarDate.add(GregorianCalendar.DATE, 1);
}
return splitTimeRanges;
}
/**
* Utility routine to write a string node to the DOM.
*/
protected Element writeStringNodeToDom(Document doc, Element parent, String nodeName, String nodeValue)
{
if (nodeValue != null && nodeValue.length() != 0)
{
Element name = doc.createElement(nodeName);
name.appendChild(doc.createTextNode(nodeValue));
parent.appendChild(name);
return name;
}
return null;
}
/**
** Internal class for resolving stylesheet URIs
**/
protected class MyURIResolver implements URIResolver
{
ClassLoader classLoader = null;
/**
** Constructor: use BaseCalendarService ClassLoader
**/
public MyURIResolver( ClassLoader classLoader )
{
this.classLoader = classLoader;
}
/**
** Resolve XSLT pathnames invoked within stylesheet (e.g. xsl:import)
** using ClassLoader.
**
** @param href href attribute of XSLT file
** @param base base URI in affect when href attribute encountered
** @return Source object for requested XSLT file
**/
public Source resolve( String href, String base )
throws TransformerException
{
InputStream in = classLoader.getResourceAsStream(href);
return (Source)(new StreamSource(in));
}
}
/**
* Get a DefaultHandler so that the StorageUser here can parse using SAX events.
*
* @see org.sakaiproject.util.SAXEntityReader#getDefaultHandler()
*/
public DefaultEntityHandler getDefaultHandler(final Map<String,Object> services)
{
return new DefaultEntityHandler()
{
/*
* (non-Javadoc)
*
* @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String,
* java.lang.String, java.lang.String, org.xml.sax.Attributes)
*/
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException
{
if (doStartElement(uri, localName, qName, attributes))
{
if (entity == null)
{
if ("calendar".equals(qName))
{
BaseCalendarEdit bce = new BaseCalendarEdit();
entity = bce;
setContentHandler(bce.getContentHandler(services), uri, localName,
qName, attributes);
}
else if ("event".equals(qName))
{
BaseCalendarEventEdit bcee = new BaseCalendarEventEdit(
container);
entity = bcee;
setContentHandler(bcee.getContentHandler(services), uri, localName,
qName, attributes);
} else {
M_log.warn("Unexpected Element in XML ["+qName+"]");
}
}
}
}
};
}
/* (non-Javadoc)
* @see org.sakaiproject.util.SAXEntityReader#getServices()
*/
public Map<String, Object> getServices()
{
if ( m_services == null ) {
m_services = new HashMap<String, Object>();
m_services.put("timeservice", m_timeService);
}
return m_services;
}
public void setServices(Map<String,Object> services) {
m_services = services;
}
public void transferCopyEntities(String fromContext, String toContext, List ids, boolean cleanup)
{
transferCopyEntitiesRefMigrator(fromContext, toContext, ids, cleanup);
}
public Map<String, String> transferCopyEntitiesRefMigrator(String fromContext, String toContext, List ids, boolean cleanup)
{
Map<String, String> transversalMap = new HashMap<String, String>();
try
{
if(cleanup == true)
{
String toSiteId = toContext;
String calendarId = calendarReference(toSiteId, SiteService.MAIN_CONTAINER);
Calendar calendarObj = getCalendar(calendarId);
List calEvents = calendarObj.getEvents(null,null);
for (int i = 0; i < calEvents.size(); i++)
{
try
{
CalendarEvent ce = (CalendarEvent) calEvents.get(i);
calendarObj.removeEvent(calendarObj.getEditEvent(ce.getId(), CalendarService.EVENT_REMOVE_CALENDAR));
CalendarEventEdit edit = calendarObj.getEditEvent(ce.getId(), org.sakaiproject.calendar.api.CalendarService.EVENT_REMOVE_CALENDAR);
calendarObj.removeEvent(edit);
calendarObj.commitEvent(edit);
}
catch (IdUnusedException e)
{
M_log.debug(".IdUnusedException " + e);
}
catch (PermissionException e)
{
M_log.debug(".PermissionException " + e);
}
catch (InUseException e)
{
M_log.debug(".InUseException delete" + e);
}
}
}
transversalMap.putAll(transferCopyEntitiesRefMigrator(fromContext, toContext, ids));
}
catch (Exception e)
{
M_log.info("importSiteClean: End removing Calendar data" + e);
}
return transversalMap;
}
/**
** Comparator for sorting Group objects
**/
private class GroupComparator implements Comparator {
public int compare(Object o1, Object o2) {
return ((Group)o1).getTitle().compareToIgnoreCase( ((Group)o2).getTitle() );
}
}
} // BaseCalendarService
|
calendar/calendar-impl/impl/src/java/org/sakaiproject/calendar/impl/BaseCalendarService.java
|
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009 The Sakai Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ECL-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.sakaiproject.calendar.impl;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Enumeration;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Properties;
import java.util.Set;
import java.util.Stack;
import java.util.TimeZone;
import java.util.Vector;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.URIResolver;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.stream.StreamSource;
import net.fortuna.ical4j.data.CalendarOutputter;
import net.fortuna.ical4j.model.DateTime;
import net.fortuna.ical4j.model.Property;
import net.fortuna.ical4j.model.TimeZoneRegistry;
import net.fortuna.ical4j.model.TimeZoneRegistryFactory;
import net.fortuna.ical4j.model.component.VEvent;
import net.fortuna.ical4j.model.parameter.Value;
import net.fortuna.ical4j.model.property.CalScale;
import net.fortuna.ical4j.model.property.Comment;
import net.fortuna.ical4j.model.property.Description;
import net.fortuna.ical4j.model.property.Location;
import net.fortuna.ical4j.model.property.Organizer;
import net.fortuna.ical4j.model.property.ProdId;
import net.fortuna.ical4j.model.property.TzId;
import net.fortuna.ical4j.model.property.Uid;
import net.fortuna.ical4j.model.property.Version;
import org.apache.avalon.framework.logger.ConsoleLogger;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.fop.apps.Driver;
import org.apache.fop.apps.FOPException;
import org.apache.fop.apps.Options;
import org.apache.fop.configuration.Configuration;
import org.apache.fop.messaging.MessageHandler;
import org.sakaiproject.alias.api.Alias;
import org.sakaiproject.alias.api.AliasService;
import org.sakaiproject.authz.api.AuthzGroupService;
import org.sakaiproject.authz.api.AuthzPermissionException;
import org.sakaiproject.authz.api.FunctionManager;
import org.sakaiproject.authz.api.GroupNotDefinedException;
import org.sakaiproject.authz.api.SecurityService;
import org.sakaiproject.calendar.api.Calendar;
import org.sakaiproject.calendar.api.CalendarEdit;
import org.sakaiproject.calendar.api.CalendarEvent;
import org.sakaiproject.calendar.api.CalendarEventEdit;
import org.sakaiproject.calendar.api.CalendarEventVector;
import org.sakaiproject.calendar.api.CalendarService;
import org.sakaiproject.calendar.api.RecurrenceRule;
import org.sakaiproject.calendar.api.CalendarEvent.EventAccess;
import org.sakaiproject.calendar.cover.ExternalCalendarSubscriptionService;
import org.sakaiproject.util.CalendarUtil;
import org.sakaiproject.component.api.ServerConfigurationService;
import org.sakaiproject.component.cover.ComponentManager;
import org.sakaiproject.content.api.ContentHostingService;
import org.sakaiproject.content.api.ContentResource;
import org.sakaiproject.entity.api.ContextObserver;
import org.sakaiproject.entity.api.Edit;
import org.sakaiproject.entity.api.Entity;
import org.sakaiproject.entity.api.EntityAccessOverloadException;
import org.sakaiproject.entity.api.EntityCopyrightException;
import org.sakaiproject.entity.api.EntityManager;
import org.sakaiproject.entity.api.EntityNotDefinedException;
import org.sakaiproject.entity.api.EntityPermissionException;
import org.sakaiproject.entity.api.EntityTransferrer;
import org.sakaiproject.entity.api.EntityTransferrerRefMigrator;
import org.sakaiproject.entity.api.HttpAccess;
import org.sakaiproject.entity.api.Reference;
import org.sakaiproject.entity.api.ResourceProperties;
import org.sakaiproject.entity.api.ResourcePropertiesEdit;
import org.sakaiproject.event.api.Event;
import org.sakaiproject.event.api.EventTrackingService;
import org.sakaiproject.event.api.NotificationService;
import org.sakaiproject.exception.IdInvalidException;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.exception.IdUsedException;
import org.sakaiproject.exception.InUseException;
import org.sakaiproject.exception.PermissionException;
import org.sakaiproject.id.api.IdManager;
import org.sakaiproject.javax.Filter;
import org.sakaiproject.memory.api.Cache;
import org.sakaiproject.memory.api.CacheRefresher;
import org.sakaiproject.memory.api.MemoryService;
import org.sakaiproject.site.api.Group;
import org.sakaiproject.site.api.Site;
import org.sakaiproject.site.api.SiteService;
import org.sakaiproject.thread_local.api.ThreadLocalManager;
import org.sakaiproject.time.api.Time;
import org.sakaiproject.time.api.TimeBreakdown;
import org.sakaiproject.time.api.TimeRange;
import org.sakaiproject.time.api.TimeService;
import org.sakaiproject.tool.api.SessionBindingEvent;
import org.sakaiproject.tool.api.SessionBindingListener;
import org.sakaiproject.tool.api.SessionManager;
import org.sakaiproject.tool.api.ToolManager;
import org.sakaiproject.user.api.UserDirectoryService;
import org.sakaiproject.user.api.UserNotDefinedException;
import org.sakaiproject.util.BaseResourcePropertiesEdit;
import org.sakaiproject.util.CalendarUtil;
import org.sakaiproject.util.DefaultEntityHandler;
import org.sakaiproject.util.DoubleStorageUser;
import org.sakaiproject.util.EntityCollections;
import org.sakaiproject.util.FormattedText;
import org.sakaiproject.util.ResourceLoader;
import org.sakaiproject.util.SAXEntityReader;
import org.sakaiproject.util.Validator;
import org.sakaiproject.util.Web;
import org.sakaiproject.util.Xml;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import java.util.Map.Entry;
/**
* <p>
* BaseCalendarService is an base implementation of the CalendarService. Extension classes implement object creation, access and storage.
* </p>
*/
public abstract class BaseCalendarService implements CalendarService, DoubleStorageUser, CacheRefresher, ContextObserver, EntityTransferrer, SAXEntityReader, EntityTransferrerRefMigrator
{
/** Our logger. */
private static Log M_log = LogFactory.getLog(BaseCalendarService.class);
/** The initial portion of a relative access point URL. */
protected String m_relativeAccessPoint = null;
/** A Cache object for caching: calendars keyed by reference. */
protected Cache m_calendarCache = null;
/** A bunch of caches for events: keyed by calendar id, the cache is keyed by event reference. */
protected Hashtable m_eventCaches = null;
/** A Storage object for access to calendars and events. */
protected Storage m_storage = null;
/** DELIMETER used to separate the list of custom fields for this calendar. */
private final static String ADDFIELDS_DELIMITER = "_,_";
/** Security lock / event root for generic message events to make it a mail event. */
public static final String SECURE_SCHEDULE_ROOT = "calendar.";
private TransformerFactory transformerFactory = null;
private DocumentBuilder docBuilder = null;
private ResourceLoader rb = new ResourceLoader("calendar");
private ContentHostingService contentHostingService;
private GroupComparator groupComparator = new GroupComparator();
/**
* Access this service from the inner classes.
*/
protected BaseCalendarService service()
{
return this;
}
/**
* Construct a Storage object.
*
* @return The new storage object.
*/
protected abstract Storage newStorage();
/**
* Access the partial URL that forms the root of calendar URLs.
*
* @param relative
* if true, form within the access path only (i.e. starting with /content)
* @return the partial URL that forms the root of calendar URLs.
*/
protected String getAccessPoint(boolean relative)
{
return (relative ? "" : m_serverConfigurationService.getAccessUrl()) + m_relativeAccessPoint;
} // getAccessPoint
/**
* Check security permission.
*
* @param lock
* The lock id string.
* @param reference
* The resource's reference string, or null if no resource is involved.
* @return true if permitted, false if not.
*/
protected boolean unlockCheck(String lock, String reference)
{
return m_securityService.unlock(lock, reference);
} // unlockCheck
/**
* Check security permission.
*
* @param lock
* The lock id string.
* @param reference
* The resource's reference string, or null if no resource is involved.
* @exception PermissionException
* thrown if the user does not have access
*/
protected void unlock(String lock, String reference) throws PermissionException
{
// check if publicly accessible via export
if ( getExportEnabled(reference) && lock.equals(AUTH_READ_CALENDAR) )
return;
// otherwise check permissions
else if (!m_securityService.unlock(lock, reference))
throw new PermissionException(m_sessionManager.getCurrentSessionUserId(), lock, reference);
} // unlock
/**
* Access the internal reference which can be used to access the calendar from within the system.
*
* @param context
* The context.
* @param id
* The calendar id.
* @return The the internal reference which can be used to access the calendar from within the system.
*/
public String calendarReference(String context, String id)
{
return getAccessPoint(true) + Entity.SEPARATOR + REF_TYPE_CALENDAR + Entity.SEPARATOR + context + Entity.SEPARATOR + id;
} // calendarReference
/**
* @inheritDoc
*/
public String calendarPdfReference(String context, String id, int scheduleType, String timeRangeString,
String userName, TimeRange dailyTimeRange)
{
return getAccessPoint(true) + Entity.SEPARATOR + REF_TYPE_CALENDAR_PDF + Entity.SEPARATOR + context + Entity.SEPARATOR + id
+ "?" + SCHEDULE_TYPE_PARAMETER_NAME + "=" + Validator.escapeHtml(Integer.valueOf(scheduleType).toString()) + "&"
+ TIME_RANGE_PARAMETER_NAME + "=" + timeRangeString + "&"
+ Validator.escapeHtml(USER_NAME_PARAMETER_NAME) + "=" + Validator.escapeHtml(userName) + "&"
+ DAILY_START_TIME_PARAMETER_NAME + "=" + Validator.escapeHtml(dailyTimeRange.toString());
}
/**
* @inheritDoc
*/
public String calendarICalReference(Reference ref)
{
String context = ref.getContext();
String id = ref.getId();
String alias = null;
List aliasList = m_aliasService.getAliases( ref.getReference() );
if ( ! aliasList.isEmpty() )
alias = ((Alias)aliasList.get(0)).getId();
if ( alias != null)
return getAccessPoint(true) + Entity.SEPARATOR + REF_TYPE_CALENDAR_ICAL + Entity.SEPARATOR + alias;
else
return getAccessPoint(true) + Entity.SEPARATOR + REF_TYPE_CALENDAR_ICAL + Entity.SEPARATOR + context + Entity.SEPARATOR + id;
}
/**
* @inheritDoc
*/
public String calendarSubscriptionReference(String context, String id)
{
return getAccessPoint(true) + Entity.SEPARATOR + REF_TYPE_CALENDAR_SUBSCRIPTION + Entity.SEPARATOR + context + Entity.SEPARATOR + id;
}
/**
* @inheritDoc
*/
public boolean getExportEnabled(String ref)
{
Calendar cal = findCalendar(ref);
if ( cal == null )
return false;
else
return cal.getExportEnabled();
}
/**
* @inheritDoc
*/
public void setExportEnabled(String ref, boolean enable)
{
try
{
CalendarEdit cal = editCalendar(ref);
cal.setExportEnabled(enable);
commitCalendar(cal);
}
catch ( Exception e)
{
M_log.warn("setExportEnabled(): ", e);
}
}
/**
* Access the internal reference which can be used to access the event from within the system.
*
* @param context
* The context.
* @param calendarId
* The calendar id.
* @param id
* The event id.
* @return The the internal reference which can be used to access the event from within the system.
*/
public String eventReference(String context, String calendarId, String id)
{
return getAccessPoint(true) + Entity.SEPARATOR + REF_TYPE_EVENT + Entity.SEPARATOR + context + Entity.SEPARATOR
+ calendarId + Entity.SEPARATOR + id;
} // eventReference
/**
* Access the internal reference which can be used to access the subscripted event from within the system.
*
* @param context
* The context.
* @param calendarId
* The calendar id.
* @param id
* The event id.
* @return The the internal reference which can be used to access the subscripted event from within the system.
*/
public String eventSubscriptionReference(String context, String calendarId, String id)
{
return getAccessPoint(true) + Entity.SEPARATOR + REF_TYPE_EVENT_SUBSCRIPTION + Entity.SEPARATOR + context + Entity.SEPARATOR
+ calendarId + Entity.SEPARATOR + id;
} // eventSubscriptionReference
/**
* Takes several calendar References and merges their events from within a given time range.
*
* @param references
* The List of calendar References.
* @param range
* The time period to use to select events.
* @return CalendarEventVector object with the union of all events from the list of calendars in the given time range.
*/
public CalendarEventVector getEvents(List references, TimeRange range)
{
CalendarEventVector calendarEventVector = null;
if (references != null && range != null)
{
List allEvents = new ArrayList();
Iterator it = references.iterator();
// Add the events for each calendar in our list.
while (it.hasNext())
{
String calendarReference = (String) it.next();
Calendar calendarObj = null;
try
{
calendarObj = getCalendar(calendarReference);
}
catch (IdUnusedException e)
{
continue;
}
catch (PermissionException e)
{
continue;
}
if (calendarObj != null)
{
Iterator calEvent = null;
try
{
calEvent = calendarObj.getEvents(range, null).iterator();
}
catch (PermissionException e1)
{
continue;
}
allEvents.addAll(new CalendarEventVector(calEvent));
}
}
// Do a sort since each of the events implements the Comparable interface.
Collections.sort(allEvents);
// Build up a CalendarEventVector and return it.
calendarEventVector = new CalendarEventVector(allEvents.iterator());
}
return calendarEventVector;
}
/**
* Form a tracking event string based on a security function string.
* @param secure The security function string.
* @return The event tracking string.
*/
protected String eventId(String secure)
{
return SECURE_SCHEDULE_ROOT + secure;
} // eventId
/**
* Access the id generating service and return a unique id.
*
* @return a unique id.
*/
protected String getUniqueId()
{
return m_idManager.createUuid();
}
/**********************************************************************************************************************************************************************************************************************************************************
* Constructors, Dependencies and their setter methods
*********************************************************************************************************************************************************************************************************************************************************/
/** Dependency: MemoryService. */
protected MemoryService m_memoryService = null;
/**
* Dependency: MemoryService.
*
* @param service
* The MemoryService.
*/
public void setMemoryService(MemoryService service)
{
m_memoryService = service;
}
/** Dependency: IdManager. */
protected IdManager m_idManager = null;
/**
* Dependency: IdManager.
*
* @param manager
* The IdManager.
*/
public void setIdManager(IdManager manager)
{
m_idManager = manager;
}
/** Configuration: cache, or not. */
protected boolean m_caching = false;
/**
* Configuration: set the caching
*
* @param path
* The storage path.
*/
public void setCaching(String value)
{
m_caching = Boolean.valueOf(value).booleanValue();
}
/** Dependency: EntityManager. */
protected EntityManager m_entityManager = null;
/**
* Dependency: EntityManager.
*
* @param service
* The EntityManager.
*/
public void setEntityManager(EntityManager service)
{
m_entityManager = service;
}
/** Dependency: ServerConfigurationService. */
protected ServerConfigurationService m_serverConfigurationService = null;
/**
* Dependency: ServerConfigurationService.
*
* @param service
* The ServerConfigurationService.
*/
public void setServerConfigurationService(ServerConfigurationService service)
{
m_serverConfigurationService = service;
}
/** Dependency: AliasService. */
protected AliasService m_aliasService = null;
/** Dependency: SiteService. */
protected SiteService m_siteService = null;
/** Dependency: AuthzGroupService */
protected AuthzGroupService m_authzGroupService = null;
/** Dependency: FunctionManager */
protected FunctionManager m_functionManager = null;
/** Dependency: SecurityService */
protected SecurityService m_securityService = null;
/** Dependency: EventTrackingService */
protected EventTrackingService m_eventTrackingService = null;
/** Depedency: SessionManager */
protected SessionManager m_sessionManager = null;
/** Dependency: ThreadLocalManager */
protected ThreadLocalManager m_threadLocalManager = null;
/** Dependency: TimeService */
protected TimeService m_timeService = null;
/** Dependency: ToolManager */
protected ToolManager m_toolManager = null;
/** Dependency: UserDirectoryService */
protected UserDirectoryService m_userDirectoryService = null;
/** A map of services used in SAX serialization */
private Map<String, Object> m_services;
/**
* Dependency: AliasService.
*
* @param service
* The AliasService.
*/
public void setAliasService(AliasService service)
{
m_aliasService = service;
}
/**
* Dependency: SiteService.
*
* @param service
* The SiteService.
*/
public void setSiteService(SiteService service)
{
m_siteService = service;
}
/**
* Dependency: AuthzGroupService.
*
* @param authzGroupService
* The AuthzGroupService.
*/
public void setAuthzGroupService(AuthzGroupService authzGroupService)
{
m_authzGroupService = authzGroupService;
}
/**
* Dependency: FunctionManager.
*
* @param functionManager
* The FunctionManager.
*/
public void setFunctionManager(FunctionManager functionManager)
{
m_functionManager = functionManager;
}
/**
* Dependency: SecurityService.
*
* @param securityService
* The SecurityService.
*/
public void setSecurityService(SecurityService securityService)
{
m_securityService = securityService;
}
/**
* Dependency: EventTrackingService.
* @param eventTrackingService
* The EventTrackingService.
*/
public void setEventTrackingService(EventTrackingService eventTrackingService)
{
this.m_eventTrackingService = eventTrackingService;
}
/**
* Dependency: SessionManager.
* @param sessionManager
* The SessionManager.
*/
public void setSessionManager(SessionManager sessionManager)
{
this.m_sessionManager = sessionManager;
}
/**
* Dependency: ThreadLocalManager.
* @param threadLocalManager
* The ThreadLocalManager.
*/
public void setThreadLocalManager(ThreadLocalManager threadLocalManager)
{
this.m_threadLocalManager = threadLocalManager;
}
/**
* Dependency: TimeService.
* @param timeService
* The TimeService.
*/
public void setTimeService(TimeService timeService)
{
this.m_timeService = timeService;
}
/**
* Dependency: ToolManager.
* @param toolManager
* The ToolManager.
*/
public void setToolManager(ToolManager toolManager)
{
this.m_toolManager = toolManager;
}
/**
* Dependency: UserDirectoryService.
* @param userDirectoryService
* The UserDirectoryService.
*/
public void setUserDirectoryService(UserDirectoryService userDirectoryService)
{
this.m_userDirectoryService = userDirectoryService;
}
/**********************************************************************************************************************************************************************************************************************************************************
* Init and Destroy
*********************************************************************************************************************************************************************************************************************************************************/
/**
* Final initialization, once all dependencies are set.
*/
public void init()
{
contentHostingService = (ContentHostingService) ComponentManager.get("org.sakaiproject.content.api.ContentHostingService");
try
{
m_relativeAccessPoint = REFERENCE_ROOT;
// construct a storage helper and read
m_storage = newStorage();
m_storage.open();
// make the calendar cache
if (m_caching)
{
m_calendarCache = m_memoryService
.newCache(
"org.sakaiproject.calendar.api.CalendarService.calendarCache",
this, getAccessPoint(true) + Entity.SEPARATOR
+ REF_TYPE_CALENDAR + Entity.SEPARATOR);
// make the table to hold the event caches
m_eventCaches = new Hashtable();
}
// create transformerFactory object needed by generatePDF
transformerFactory = TransformerFactory.newInstance();
transformerFactory.setURIResolver( new MyURIResolver(getClass().getClassLoader()) );
// create DocumentBuilder object needed by printSchedule
docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
M_log.info("init(): caching: " + m_caching);
}
catch (Throwable t)
{
M_log.warn("init(): ", t);
}
// register as an entity producer
m_entityManager.registerEntityProducer(this, REFERENCE_ROOT);
// register functions
m_functionManager.registerFunction(AUTH_ADD_CALENDAR);
m_functionManager.registerFunction(AUTH_REMOVE_CALENDAR_OWN);
m_functionManager.registerFunction(AUTH_REMOVE_CALENDAR_ANY);
m_functionManager.registerFunction(AUTH_MODIFY_CALENDAR_OWN);
m_functionManager.registerFunction(AUTH_MODIFY_CALENDAR_ANY);
m_functionManager.registerFunction(AUTH_IMPORT_CALENDAR);
m_functionManager.registerFunction(AUTH_SUBSCRIBE_CALENDAR);
m_functionManager.registerFunction(AUTH_READ_CALENDAR);
m_functionManager.registerFunction(AUTH_ALL_GROUPS_CALENDAR);
m_functionManager.registerFunction(AUTH_OPTIONS_CALENDAR);
}
/**
* Returns to uninitialized state.
*/
public void destroy()
{
if (m_caching)
{
m_calendarCache.destroy();
m_calendarCache = null;
// TODO: destroy each cache
m_eventCaches.clear();
m_eventCaches = null;
}
m_storage.close();
m_storage = null;
M_log.info("destroy()");
}
/**********************************************************************************************************************************************************************************************************************************************************
* CalendarService implementation
*********************************************************************************************************************************************************************************************************************************************************/
/**
* Add a new calendar. Must commitCalendar() to make official, or cancelCalendar() when done!
*
* @param ref
* A reference for the calendar.
* @return The newly created calendar.
* @exception IdUsedException
* if the id is not unique.
* @exception IdInvalidException
* if the id is not made up of valid characters.
*/
public CalendarEdit addCalendar(String ref) throws IdUsedException, IdInvalidException
{
// check the name's validity
if (!m_entityManager.checkReference(ref)) throw new IdInvalidException(ref);
// check for existance
if (m_storage.checkCalendar(ref))
{
throw new IdUsedException(ref);
}
// keep it
CalendarEdit calendar = m_storage.putCalendar(ref);
((BaseCalendarEdit) calendar).setEvent(EVENT_CREATE_CALENDAR);
return calendar;
} // addCalendar
/**
* check permissions for getCalendar().
*
* @param ref
* The calendar reference.
* @return true if the user is allowed to getCalendar(calendarId), false if not.
*/
public boolean allowGetCalendar(String ref)
{
if(REF_TYPE_CALENDAR_SUBSCRIPTION.equals(m_entityManager.newReference(ref).getSubType()))
return true;
return unlockCheck(AUTH_READ_CALENDAR, ref);
} // allowGetCalendar
/**
* Find the calendar, in cache or info store - cache it if newly found.
*
* @param ref
* The calendar reference.
* @return The calendar, if found.
*/
protected Calendar findCalendar(String ref)
{
Calendar calendar = null;
if ((!m_caching) || (m_calendarCache == null) || (m_calendarCache.disabled()))
{
// TODO: do we really want to do this? -ggolden
// if we have done this already in this thread, use that
calendar = (Calendar) m_threadLocalManager.get(ref);
if (calendar == null)
{
calendar = m_storage.getCalendar(ref);
// "cache" the calendar in the current service in case they are needed again in this thread...
if (calendar != null)
{
m_threadLocalManager.set(ref, calendar);
}
}
return calendar;
}
// if we have it cached, use it (even if it's cached as a null, a miss)
if (m_calendarCache.containsKey(ref))
{
calendar = (Calendar) m_calendarCache.get(ref);
}
// if not in the cache, see if we have it in our info store
if ( calendar == null ) //SAK-12447 cache.get can return null on expired
{
calendar = m_storage.getCalendar(ref);
// if so, cache it, even misses
m_calendarCache.put(ref, calendar);
}
return calendar;
} // findCalendar
/**
* Return a specific calendar.
*
* @param ref
* The calendar reference.
* @return the Calendar that has the specified name.
* @exception IdUnusedException
* If this name is not defined for any calendar.
* @exception PermissionException
* If the user does not have any permissions to the calendar.
*/
public Calendar getCalendar(String ref) throws IdUnusedException, PermissionException
{
Reference _ref = m_entityManager.newReference(ref);
if(REF_TYPE_CALENDAR_SUBSCRIPTION.equals(_ref.getSubType())) {
Calendar c = ExternalCalendarSubscriptionService.getCalendarSubscription(ref);
if (c == null) throw new IdUnusedException(ref);
return c;
}
Calendar c = findCalendar(ref);
if (c == null) throw new IdUnusedException(ref);
// check security (throws if not permitted)
unlock(AUTH_READ_CALENDAR, ref);
return c;
} // getCalendar
/**
* Remove a calendar that is locked for edit.
*
* @param calendar
* The calendar to remove.
* @exception PermissionException
* if the user does not have permission to remove a calendar.
*/
public void removeCalendar(CalendarEdit calendar) throws PermissionException
{
// check for closed edit
if (!calendar.isActiveEdit())
{
try
{
throw new Exception();
}
catch (Exception e)
{
M_log.warn("removeCalendar(): closed CalendarEdit", e);
}
return;
}
// check security
unlock(AUTH_REMOVE_CALENDAR_ANY, calendar.getReference());
m_storage.removeCalendar(calendar);
// track event
Event event = m_eventTrackingService.newEvent(EVENT_REMOVE_CALENDAR, calendar.getReference(), true);
m_eventTrackingService.post(event);
// mark the calendar as removed
((BaseCalendarEdit) calendar).setRemoved(event);
// close the edit object
((BaseCalendarEdit) calendar).closeEdit();
// remove any realm defined for this resource
try
{
m_authzGroupService.removeAuthzGroup(m_authzGroupService.getAuthzGroup(calendar.getReference()));
}
catch (AuthzPermissionException e)
{
M_log.warn("removeCalendar: removing realm for : " + calendar.getReference() + " : " + e);
}
catch (GroupNotDefinedException ignore)
{
}
} // removeCalendar
/**
* Return a List of all the defined calendars.
*
* @return a List of Calendar objects (may be empty)
*/
public List getCalendars()
{
List calendars = new Vector();
if ((!m_caching) || (m_calendarCache == null) || (m_calendarCache.disabled()))
{
calendars = m_storage.getCalendars();
return calendars;
}
// if the cache is complete, use it
if (m_calendarCache.isComplete())
{
// get just the calendars in the cache
calendars = m_calendarCache.getAll();
}
// otherwise get all the calendars from storage
else
{
// Note: while we are getting from storage, storage might change. These can be processed
// after we get the storage entries, and put them in the cache, and mark the cache complete.
// -ggolden
synchronized (m_calendarCache)
{
// if we were waiting and it's now complete...
if (m_calendarCache.isComplete())
{
// get just the calendars in the cache
calendars = m_calendarCache.getAll();
return calendars;
}
// save up any events to the cache until we get past this load
m_calendarCache.holdEvents();
calendars = m_storage.getCalendars();
// update the cache, and mark it complete
for (int i = 0; i < calendars.size(); i++)
{
Calendar calendar = (Calendar) calendars.get(i);
m_calendarCache.put(calendar.getReference(), calendar);
}
m_calendarCache.setComplete();
// now we are complete, process any cached events
m_calendarCache.processEvents();
}
}
return calendars;
} // getCalendars
/**
* check permissions for importing calendar events
*
* @param ref
* The calendar reference.
* @return true if the user is allowed to import events, false if not.
*/
public boolean allowImportCalendar(String ref)
{
return unlockCheck(AUTH_IMPORT_CALENDAR, ref);
} // allowImportCalendar
/**
* check permissions for subscribing external calendars
*
* @param ref
* The calendar reference.
* @return true if the user is allowed to subscribe external calendars, false if not.
*/
public boolean allowSubscribeCalendar(String ref)
{
return unlockCheck(AUTH_SUBSCRIBE_CALENDAR, ref);
} // allowSubscribeCalendar
/**
* check permissions for editCalendar()
*
* @param ref
* The calendar reference.
* @return true if the user is allowed to update the calendar, false if not.
*/
public boolean allowEditCalendar(String ref)
{
return unlockCheck(AUTH_MODIFY_CALENDAR_ANY, ref);
} // allowEditCalendar
/**
* check permissions for merge()
* @param ref The calendar reference.
* @return true if the user is allowed to update the calendar, false if not.
*/
public boolean allowMergeCalendar(String ref)
{
String displayMerge = getString("calendar.merge.display", "1");
if(displayMerge != null && !displayMerge.equals("1"))
return false;
return unlockCheck(AUTH_MODIFY_CALENDAR_ANY, ref);
} // allowMergeCalendar
/**
* Get a locked calendar object for editing. Must commitCalendar() to make official, or cancelCalendar() or removeCalendar() when done!
*
* @param ref
* The calendar reference.
* @return A CalendarEdit object for editing.
* @exception IdUnusedException
* if not found, or if not an CalendarEdit object
* @exception PermissionException
* if the current user does not have permission to mess with this user.
* @exception InUseException
* if the Calendar object is locked by someone else.
*/
public CalendarEdit editCalendar(String ref) throws IdUnusedException, PermissionException, InUseException
{
// check for existance
if (!m_storage.checkCalendar(ref))
{
throw new IdUnusedException(ref);
}
// check security (throws if not permitted)
unlock(AUTH_MODIFY_CALENDAR_ANY, ref);
// ignore the cache - get the calendar with a lock from the info store
CalendarEdit edit = m_storage.editCalendar(ref);
if (edit == null) throw new InUseException(ref);
((BaseCalendarEdit) edit).setEvent(EVENT_MODIFY_CALENDAR);
return edit;
} // editCalendar
/**
* Commit the changes made to a CalendarEdit object, and release the lock. The CalendarEdit is disabled, and not to be used after this call.
*
* @param edit
* The CalendarEdit object to commit.
*/
public void commitCalendar(CalendarEdit edit)
{
// check for closed edit
if (!edit.isActiveEdit())
{
M_log.warn("commitCalendar(): closed CalendarEdit " + edit.getContext());
return;
}
m_storage.commitCalendar(edit);
// track event
Event event = m_eventTrackingService.newEvent(((BaseCalendarEdit) edit).getEvent(), edit.getReference(), true);
m_eventTrackingService.post(event);
// close the edit object
((BaseCalendarEdit) edit).closeEdit();
} // commitCalendar
/**
* Cancel the changes made to a CalendarEdit object, and release the lock. The CalendarEdit is disabled, and not to be used after this call.
*
* @param edit
* The CalendarEdit object to commit.
*/
public void cancelCalendar(CalendarEdit edit)
{
// check for closed edit
if (!edit.isActiveEdit())
{
M_log.warn("cancelCalendar(): closed CalendarEventEdit " + edit.getContext());
return;
}
// release the edit lock
m_storage.cancelCalendar(edit);
// close the edit object
((BaseCalendarEdit) edit).closeEdit();
} // cancelCalendar
/**
* {@inheritDoc}
*/
public RecurrenceRule newRecurrence(String frequency)
{
if (frequency.equals(DailyRecurrenceRule.FREQ))
{
return new DailyRecurrenceRule();
}
else if (frequency.equals(WeeklyRecurrenceRule.FREQ))
{
return new WeeklyRecurrenceRule();
}
else if (frequency.equals(TThRecurrenceRule.FREQ))
{
return new TThRecurrenceRule();
}
else if (frequency.equals(MWFRecurrenceRule.FREQ))
{
return new MWFRecurrenceRule();
}
else if (frequency.equals(MonthlyRecurrenceRule.FREQ))
{
return new MonthlyRecurrenceRule();
}
else if (frequency.equals(YearlyRecurrenceRule.FREQ))
{
return new YearlyRecurrenceRule();
}
else if (frequency.equals(MWRecurrenceRule.FREQ))
{
return new MWRecurrenceRule();
}
else if (frequency.equals(SMWRecurrenceRule.FREQ))
{
return new SMWRecurrenceRule();
}
else if (frequency.equals(SMTWRecurrenceRule.FREQ))
{
return new SMTWRecurrenceRule();
}
else if (frequency.equals(STTRecurrenceRule.FREQ))
{
return new STTRecurrenceRule();
}
//add more here
return null;
}
/**
* {@inheritDoc}
*/
public RecurrenceRule newRecurrence(String frequency, int interval)
{
if (frequency.equals(DailyRecurrenceRule.FREQ))
{
return new DailyRecurrenceRule(interval);
}
else if (frequency.equals(WeeklyRecurrenceRule.FREQ))
{
return new WeeklyRecurrenceRule(interval);
}
else if (frequency.equals(TThRecurrenceRule.FREQ))
{
return new TThRecurrenceRule(interval);
}
else if (frequency.equals(MWFRecurrenceRule.FREQ))
{
return new MWFRecurrenceRule(interval);
}
else if (frequency.equals(MonthlyRecurrenceRule.FREQ))
{
return new MonthlyRecurrenceRule(interval);
}
else if (frequency.equals(YearlyRecurrenceRule.FREQ))
{
return new YearlyRecurrenceRule(interval);
}
else if (frequency.equals(MWRecurrenceRule.FREQ))
{
return new MWRecurrenceRule(interval);
}
else if (frequency.equals(SMWRecurrenceRule.FREQ))
{
return new SMWRecurrenceRule(interval);
}
else if (frequency.equals(SMTWRecurrenceRule.FREQ))
{
return new SMTWRecurrenceRule(interval);
}
else if (frequency.equals(STTRecurrenceRule.FREQ))
{
return new STTRecurrenceRule(interval);
}
//add more here
return null;
}
/**
* {@inheritDoc}
*/
public RecurrenceRule newRecurrence(String frequency, int interval, int count)
{
M_log.debug("\n"+ frequency +"\nand Internval is \n "+ interval +"count is\n " + count);
if (frequency.equals(DailyRecurrenceRule.FREQ))
{
return new DailyRecurrenceRule(interval, count);
}
else if (frequency.equals(WeeklyRecurrenceRule.FREQ))
{
return new WeeklyRecurrenceRule(interval, count);
}
else if (frequency.equals(TThRecurrenceRule.FREQ))
{
return new TThRecurrenceRule(interval,count);
}
else if (frequency.equals(MWFRecurrenceRule.FREQ))
{
return new MWFRecurrenceRule(interval,count);
}
else if (frequency.equals(MonthlyRecurrenceRule.FREQ))
{
return new MonthlyRecurrenceRule(interval, count);
}
else if (frequency.equals(YearlyRecurrenceRule.FREQ))
{
return new YearlyRecurrenceRule(interval, count);
}
else if (frequency.equals(MWRecurrenceRule.FREQ))
{
return new MWRecurrenceRule(interval, count);
}
else if (frequency.equals(SMWRecurrenceRule.FREQ))
{
return new SMWRecurrenceRule(interval, count);
}
else if (frequency.equals(SMTWRecurrenceRule.FREQ))
{
return new SMTWRecurrenceRule(interval, count);
}
else if (frequency.equals(STTRecurrenceRule.FREQ))
{
return new STTRecurrenceRule(interval, count);
}
//add more here
return null;
}
/**
* {@inheritDoc}
*/
public RecurrenceRule newRecurrence(String frequency, int interval, Time until)
{
if (frequency.equals(DailyRecurrenceRule.FREQ))
{
return new DailyRecurrenceRule(interval, until);
}
else if (frequency.equals(WeeklyRecurrenceRule.FREQ))
{
return new WeeklyRecurrenceRule(interval, until);
}
else if (frequency.equals(TThRecurrenceRule.FREQ))
{
return new TThRecurrenceRule(interval,until);
}
else if (frequency.equals(MWFRecurrenceRule.FREQ))
{
return new MWFRecurrenceRule(interval,until);
}
else if (frequency.equals(MonthlyRecurrenceRule.FREQ))
{
return new MonthlyRecurrenceRule(interval, until);
}
else if (frequency.equals(YearlyRecurrenceRule.FREQ))
{
return new YearlyRecurrenceRule(interval, until);
}
else if (frequency.equals(MWRecurrenceRule.FREQ))
{
return new MWRecurrenceRule(interval, until);
}
else if (frequency.equals(SMWRecurrenceRule.FREQ))
{
return new SMWRecurrenceRule(interval, until);
}
else if (frequency.equals(SMTWRecurrenceRule.FREQ))
{
return new SMTWRecurrenceRule(interval, until);
}
else if (frequency.equals(STTRecurrenceRule.FREQ))
{
return new STTRecurrenceRule(interval, until);
}
//add more here
return null;
}
/**********************************************************************************************************************************************************************************************************************************************************
* ResourceService implementation
*********************************************************************************************************************************************************************************************************************************************************/
/**
* {@inheritDoc}
*/
public String getLabel()
{
return "calendar";
}
/**
* {@inheritDoc}
*/
public boolean willArchiveMerge()
{
return true;
}
/**
* {@inheritDoc}
*/
public HttpAccess getHttpAccess()
{
return new HttpAccess()
{
public void handleAccess(HttpServletRequest req, HttpServletResponse res, Reference ref,
Collection copyrightAcceptedRefs) throws EntityPermissionException, EntityNotDefinedException,
EntityAccessOverloadException, EntityCopyrightException
{
String calRef = calendarReference(ref.getContext(), SiteService.MAIN_CONTAINER);
// we only access the pdf & ical reference
if ( !REF_TYPE_CALENDAR_PDF.equals(ref.getSubType()) &&
!REF_TYPE_CALENDAR_ICAL.equals(ref.getSubType()) )
throw new EntityNotDefinedException(ref.getReference());
// check if ical export is enabled
if ( REF_TYPE_CALENDAR_ICAL.equals(ref.getSubType()) &&
!getExportEnabled(calRef) )
throw new EntityNotDefinedException(ref.getReference());
try
{
Properties options = new Properties();
Enumeration e = req.getParameterNames();
while (e.hasMoreElements())
{
String key = (String) e.nextElement();
String[] values = req.getParameterValues(key);
if (values.length == 1)
{
options.put(key, values[0]);
}
else
{
StringBuilder buf = new StringBuilder();
for (int i = 0; i < values.length; i++)
{
buf.append(values[i] + "^");
}
options.put(key, buf.toString());
}
}
// We need to write to a temporary stream for better speed, plus
// so we can get a byte count. Internet Explorer has problems
// if we don't make the setContentLength() call.
ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
// Check if PDF document requested
if ( REF_TYPE_CALENDAR_PDF.equals(ref.getSubType()) )
{
res.addHeader("Content-Disposition", "inline; filename=\"schedule.pdf\"");
res.setContentType(PDF_MIME_TYPE);
printSchedule(options, outByteStream);
}
else
{
List alias = m_aliasService.getAliases(calRef);
String aliasName = "schedule.ics";
if ( ! alias.isEmpty() )
aliasName = ((Alias)alias.get(0)).getId();
// update date/time reference
Time modDate = findCalendar(calRef).getModified();
if ( modDate == null )
modDate = m_timeService.newTime(0);
res.addHeader("Content-Disposition", "inline; filename=\"" + Web.encodeFileName(req, aliasName) + "\"");
res.setContentType(ICAL_MIME_TYPE);
res.setDateHeader("Last-Modified", modDate.getTime() );
printICalSchedule(calRef, res.getOutputStream());
}
res.setContentLength(outByteStream.size());
if (outByteStream.size() > 0)
{
// Increase the buffer size for more speed.
res.setBufferSize(outByteStream.size());
}
OutputStream out = null;
try
{
out = res.getOutputStream();
if (outByteStream.size() > 0)
{
outByteStream.writeTo(out);
}
out.flush();
out.close();
}
catch (Throwable ignore)
{
}
finally
{
if (out != null)
{
try
{
out.close();
}
catch (Throwable ignore)
{
}
}
}
}
catch (Throwable t)
{
throw new EntityNotDefinedException(ref.getReference());
}
}
};
}
/**
* {@inheritDoc}
*/
public boolean parseEntityReference(String reference, Reference ref)
{
if (reference.startsWith(CalendarService.REFERENCE_ROOT))
{
String[] parts = reference.split(Entity.SEPARATOR);
String subType = null;
String context = null;
String id = null;
String container = null;
// the first part will be null, then next the service, the third will be "calendar" or "event"
if (parts.length > 2)
{
subType = parts[2];
if (REF_TYPE_CALENDAR.equals(subType) ||
REF_TYPE_CALENDAR_PDF.equals(subType) ||
REF_TYPE_CALENDAR_ICAL.equals(subType) ||
REF_TYPE_CALENDAR_SUBSCRIPTION.equals(subType))
{
// next is the context id
if (parts.length > 3)
{
context = parts[3];
// next is the optional calendar id
if (parts.length > 4)
{
id = parts[4];
}
}
}
else if (REF_TYPE_EVENT.equals(subType) || REF_TYPE_EVENT_SUBSCRIPTION.equals(subType))
{
// next three parts are context, channel (container) and event id
if (parts.length > 5)
{
context = parts[3];
container = parts[4];
id = parts[5];
}
}
else
M_log.warn(".parseEntityReference(): unknown calendar subtype: " + subType + " in ref: " + reference);
}
// Translate context alias into site id if necessary
if ((context != null) && (context.length() > 0))
{
if (!m_siteService.siteExists(context))
{
try
{
Calendar calendarObj = getCalendar(m_aliasService.getTarget(context));
context = calendarObj.getContext();
}
catch (IdUnusedException ide) {
M_log.info(".parseEntityReference():"+ide.toString());
return false;
}
catch (PermissionException pe) {
M_log.info(".parseEntityReference():"+pe.toString());
return false;
}
catch (Exception e)
{
M_log.warn(".parseEntityReference(): ", e);
return false;
}
}
}
// if context still isn't valid, then no valid alias or site was specified
if (!m_siteService.siteExists(context))
{
M_log.warn(".parseEntityReference() no valid site or alias: " + context);
return false;
}
// build updated reference
ref.set(APPLICATION_ID, subType, id, container, context);
return true;
}
return false;
}
/**
* {@inheritDoc}
*/
public String getEntityDescription(Reference ref)
{
// double check that it's mine
if (!APPLICATION_ID.equals(ref.getType())) return null;
String rv = "Calendar: " + ref.getReference();
try
{
// if this is a calendar
if (REF_TYPE_CALENDAR.equals(ref.getSubType()) || REF_TYPE_CALENDAR_PDF.equals(ref.getSubType()))
{
Calendar cal = getCalendar(ref.getReference());
rv = "Calendar: " + cal.getId() + " (" + cal.getContext() + ")";
}
// otherwise an event
else if (REF_TYPE_EVENT.equals(ref.getSubType()))
{
rv = "Event: " + ref.getReference();
}
}
catch (PermissionException ignore) {}
catch (IdUnusedException ignore) {}
catch (NullPointerException ignore) {}
return rv;
}
/**
* {@inheritDoc}
*/
public ResourceProperties getEntityResourceProperties(Reference ref)
{
// double check that it's mine
if (!APPLICATION_ID.equals(ref.getType())) return null;
ResourceProperties props = null;
try
{
// if this is a calendar
if (REF_TYPE_CALENDAR.equals(ref.getSubType()) || REF_TYPE_CALENDAR_PDF.equals(ref.getSubType()) || REF_TYPE_CALENDAR_SUBSCRIPTION.equals(ref.getSubType()))
{
Calendar cal = getCalendar(ref.getReference());
props = cal.getProperties();
}
// otherwise an event
else if (REF_TYPE_EVENT.equals(ref.getSubType()))
{
Calendar cal = getCalendar(calendarReference(ref.getContext(), ref.getContainer()));
CalendarEvent event = cal.getEvent(ref.getId());
props = event.getProperties();
}
else if (REF_TYPE_EVENT_SUBSCRIPTION.equals(ref.getSubType()))
{
Calendar cal = getCalendar(calendarSubscriptionReference(ref.getContext(), ref.getContainer()));
CalendarEvent event = cal.getEvent(ref.getId());
props = event.getProperties();
}
else
M_log.warn(".getEntityResourceProperties(): unknown calendar ref subtype: " + ref.getSubType() + " in ref: "
+ ref.getReference());
}
catch (PermissionException e)
{
M_log.warn(".getEntityResourceProperties(): " + e);
}
catch (IdUnusedException ignore)
{
// This just means that the resource once pointed to as an attachment or something has been deleted.
// m_logger(this + ".getProperties(): " + e);
}
catch (NullPointerException e)
{
M_log.warn(".getEntityResourceProperties(): " + e);
}
return props;
}
/**
* {@inheritDoc}
*/
public Entity getEntity(Reference ref)
{
// double check that it's mine
if (!APPLICATION_ID.equals(ref.getType())) return null;
Entity rv = null;
try
{
// if this is a calendar
if (REF_TYPE_CALENDAR.equals(ref.getSubType()) || REF_TYPE_CALENDAR_PDF.equals(ref.getSubType()) || REF_TYPE_CALENDAR_SUBSCRIPTION.equals(ref.getSubType()))
{
rv = getCalendar(ref.getReference());
}
// otherwise a event
else if (REF_TYPE_EVENT.equals(ref.getSubType()))
{
Calendar cal = getCalendar(calendarReference(ref.getContext(), ref.getContainer()));
rv = cal.getEvent(ref.getId());
}
else if (REF_TYPE_EVENT_SUBSCRIPTION.equals(ref.getSubType()))
{
Calendar cal = getCalendar(calendarSubscriptionReference(ref.getContext(), ref.getContainer()));
rv = cal.getEvent(ref.getId());
}
else
M_log.warn("getEntity(): unknown calendar ref subtype: " + ref.getSubType() + " in ref: " + ref.getReference());
}
catch (PermissionException e)
{
M_log.warn("getEntity(): " + e);
}
catch (IdUnusedException e)
{
M_log.warn("getEntity(): " + e);
}
catch (NullPointerException e)
{
M_log.warn(".getEntity(): " + e);
}
return rv;
}
/**
* {@inheritDoc}
*/
public Collection getEntityAuthzGroups(Reference ref, String userId)
{
// double check that it's mine
if (!APPLICATION_ID.equals(ref.getType())) return null;
Collection rv = new Vector();
// for events:
// if access set to SITE (or PUBLIC), use the event, calendar and site authzGroups.
// if access set to GROUPED, use the event, and the groups, but not the calendar or site authzGroups.
// if the user has SECURE_ALL_GROUPS in the context, ignore GROUPED access and treat as if SITE
// for Calendars: use the calendar and site authzGroups.
try
{
// for event
if (REF_TYPE_EVENT.equals(ref.getSubType()))
{
// event
rv.add(ref.getReference());
boolean grouped = false;
Collection groups = null;
// check SECURE_ALL_GROUPS - if not, check if the event has groups or not
// TODO: the last param needs to be a ContextService.getRef(ref.getContext())... or a ref.getContextAuthzGroup() -ggolden
if ((userId == null) || ((!m_securityService.isSuperUser(userId)) && (!m_authzGroupService.isAllowed(userId, SECURE_ALL_GROUPS, m_siteService.siteReference(ref.getContext())))))
{
// get the calendar to get the message to get group information
String calendarRef = calendarReference(ref.getContext(), ref.getContainer());
Calendar c = findCalendar(calendarRef);
if (c != null)
{
CalendarEvent e = ((BaseCalendarEdit) c).findEvent(ref.getId());
if (e != null)
{
grouped = EventAccess.GROUPED == e.getAccess();
groups = e.getGroups();
}
}
}
if (grouped)
{
// groups
rv.addAll(groups);
}
// not grouped
else
{
// calendar
rv.add(calendarReference(ref.getContext(), ref.getContainer()));
// site
ref.addSiteContextAuthzGroup(rv);
}
}
// for calendar
else
{
// calendar
rv.add(calendarReference(ref.getContext(), ref.getId()));
// site
ref.addSiteContextAuthzGroup(rv);
}
}
catch (Throwable e)
{
M_log.warn("getEntityAuthzGroups(): " + e);
}
return rv;
}
/**
* {@inheritDoc}
*/
public String getEntityUrl(Reference ref)
{
// double check that it's mine
if (!APPLICATION_ID.equals(ref.getType())) return null;
String rv = null;
try
{
// if this is a calendar
if (REF_TYPE_CALENDAR.equals(ref.getSubType()) || REF_TYPE_CALENDAR_PDF.equals(ref.getSubType()))
{
Calendar cal = getCalendar(ref.getReference());
rv = cal.getUrl();
}
// otherwise a event
else if (REF_TYPE_EVENT.equals(ref.getSubType()))
{
Calendar cal = getCalendar(calendarReference(ref.getContext(), ref.getContainer()));
CalendarEvent event = cal.getEvent(ref.getId());
rv = event.getUrl();
}
else
M_log.warn("getEntityUrl(): unknown calendar ref subtype: " + ref.getSubType() + " in ref: " + ref.getReference());
}
catch (PermissionException e)
{
M_log.warn(".getEntityUrl(): " + e);
}
catch (IdUnusedException e)
{
M_log.warn(".getEntityUrl(): " + e);
}
catch (NullPointerException e)
{
M_log.warn(".getEntityUrl(): " + e);
}
return rv;
}
/**
* {@inheritDoc}
*/
public String archive(String siteId, Document doc, Stack stack, String archivePath, List attachments)
{
// prepare the buffer for the results log
StringBuilder results = new StringBuilder();
// start with an element with our very own (service) name
Element element = doc.createElement(CalendarService.class.getName());
((Element) stack.peek()).appendChild(element);
stack.push(element);
// get the channel associated with this site
String calRef = calendarReference(siteId, SiteService.MAIN_CONTAINER);
results.append("archiving calendar " + calRef + ".\n");
try
{
// do the channel
Calendar cal = getCalendar(calRef);
Element containerElement = cal.toXml(doc, stack);
stack.push(containerElement);
// do the messages in the channel
Iterator events = cal.getEvents(null, null).iterator();
while (events.hasNext())
{
CalendarEvent event = (CalendarEvent) events.next();
event.toXml(doc, stack);
// collect message attachments
List atts = event.getAttachments();
for (int i = 0; i < atts.size(); i++)
{
Reference ref = (Reference) atts.get(i);
// if it's in the attachment area, and not already in the list
if ((ref.getReference().startsWith("/content/attachment/")) && (!attachments.contains(ref)))
{
attachments.add(ref);
}
}
}
stack.pop();
}
catch (Exception any)
{
M_log.warn(".archve: exception archiving messages for service: " + CalendarService.class.getName() + " channel: "
+ calRef);
}
stack.pop();
return results.toString();
}
/**
* {@inheritDoc}
*/
public String merge(String siteId, Element root, String archivePath, String fromSiteId, Map attachmentNames, Map userIdTrans,
Set userListAllowImport)
{
// prepare the buffer for the results log
StringBuilder results = new StringBuilder();
// get the channel associated with this site
String calendarRef = calendarReference(siteId, SiteService.MAIN_CONTAINER);
int count = 0;
try
{
Calendar calendar = null;
try
{
calendar = getCalendar(calendarRef);
}
catch (IdUnusedException e)
{
CalendarEdit edit = addCalendar(calendarRef);
commitCalendar(edit);
calendar = edit;
}
// pass the DOM to get new event ids, and adjust attachments
NodeList children2 = root.getChildNodes();
int length2 = children2.getLength();
for (int i2 = 0; i2 < length2; i2++)
{
Node child2 = children2.item(i2);
if (child2.getNodeType() == Node.ELEMENT_NODE)
{
Element element2 = (Element) child2;
// get the "calendar" child
if (element2.getTagName().equals("calendar"))
{
NodeList children3 = element2.getChildNodes();
final int length3 = children3.getLength();
for (int i3 = 0; i3 < length3; i3++)
{
Node child3 = children3.item(i3);
if (child3.getNodeType() == Node.ELEMENT_NODE)
{
Element element3 = (Element) child3;
if (element3.getTagName().equals("properties"))
{
NodeList children8 = element3.getChildNodes();
final int length8 = children8.getLength();
for (int i8 = 0; i8 < length8; i8++)
{
Node child8 = children8.item(i8);
if (child8.getNodeType() == Node.ELEMENT_NODE)
{
Element element8 = (Element) child8;
// for "event" children
if (element8.getTagName().equals("property"))
{
String pName = element8.getAttribute("name");
if ((pName != null) && (pName.equalsIgnoreCase("CHEF:calendar-fields")))
{
String pValue = element8.getAttribute("value");
if ("BASE64".equalsIgnoreCase(element8.getAttribute("enc")))
{
pValue = Xml.decodeAttribute(element8, "value");
}
if (pValue != null)
{
try
{
CalendarEdit calEdit = editCalendar(calendarRef);
String calFields = StringUtils.trimToEmpty(calEdit.getEventFields());
if (calFields != null)
pValue = calFields + ADDFIELDS_DELIMITER + pValue;
calEdit.setEventFields(pValue);
commitCalendar(calEdit);
}
catch (Exception e)
{
M_log.warn(".merge() when editing calendar: exception: ", e);
}
}
}
}
}
}
}
// for "event" children
if (element3.getTagName().equals("event"))
{
// adjust the id
String oldId = element3.getAttribute("id");
String newId = getUniqueId();
element3.setAttribute("id", newId);
// get the attachment kids
NodeList children5 = element3.getChildNodes();
final int length5 = children5.getLength();
for (int i5 = 0; i5 < length5; i5++)
{
Node child5 = children5.item(i5);
if (child5.getNodeType() == Node.ELEMENT_NODE)
{
Element element5 = (Element) child5;
// for "attachment" children
if (element5.getTagName().equals("attachment"))
{
// map the attachment area folder name
String oldUrl = element5.getAttribute("relative-url");
if (oldUrl.startsWith("/content/attachment/"))
{
String newUrl = (String) attachmentNames.get(oldUrl);
if (newUrl != null)
{
if (newUrl.startsWith("/attachment/")) newUrl = "/content".concat(newUrl);
element5.setAttribute("relative-url", Validator.escapeQuestionMark(newUrl));
}
}
// map any references to this site to the new site id
else if (oldUrl.startsWith("/content/group/" + fromSiteId + "/"))
{
String newUrl = "/content/group/" + siteId
+ oldUrl.substring(15 + fromSiteId.length());
element5.setAttribute("relative-url", Validator.escapeQuestionMark(newUrl));
}
}
}
}
// create a new message in the calendar
CalendarEventEdit edit = calendar.mergeEvent(element3);
calendar.commitEvent(edit);
count++;
}
}
}
}
}
}
}
catch (Exception any)
{
M_log.warn(".merge(): exception: ", any);
}
results.append("merging calendar " + calendarRef + " (" + count + ") messages.\n");
return results.toString();
}
/**
* {@inheritDoc}
*/
public void transferCopyEntities(String fromContext, String toContext, List resourceIds)
{
transferCopyEntitiesRefMigrator(fromContext, toContext, resourceIds);
}
public Map<String, String> transferCopyEntitiesRefMigrator(String fromContext, String toContext, List resourceIds)
{
Map<String, String> transversalMap = new HashMap<String, String>();
// get the channel associated with this site
String oCalendarRef = calendarReference(fromContext, SiteService.MAIN_CONTAINER);
Calendar oCalendar = null;
try
{
oCalendar = getCalendar(oCalendarRef);
// new calendar
CalendarEdit nCalendar = null;
String nCalendarRef = calendarReference(toContext, SiteService.MAIN_CONTAINER);
try
{
nCalendar = editCalendar(nCalendarRef);
}
catch (IdUnusedException e)
{
try
{
nCalendar = addCalendar(nCalendarRef);
}
catch (IdUsedException ignore) {}
catch (IdInvalidException ignore) {}
}
catch (PermissionException ignore) {}
catch (InUseException ignore) {}
if (nCalendar != null)
{
List oEvents = oCalendar.getEvents(null, null);
String oFields = StringUtils.trimToNull(oCalendar.getEventFields());
String nFields = StringUtils.trimToNull(nCalendar.getEventFields());
String allFields = "";
if (oFields != null)
{
if (nFields != null)
{
allFields = nFields + ADDFIELDS_DELIMITER + oFields;
}
else
{
allFields = oFields;
}
nCalendar.setEventFields(allFields);
}
for (int i = 0; i < oEvents.size(); i++)
{
CalendarEvent oEvent = (CalendarEvent) oEvents.get(i);
try
{
// Skip calendar events based on assignment due dates
String assignmentId = oEvent.getField(CalendarUtil.NEW_ASSIGNMENT_DUEDATE_CALENDAR_ASSIGNMENT_ID);
if (assignmentId != null && assignmentId.length() > 0)
continue;
CalendarEvent e = nCalendar.addEvent(oEvent.getRange(), oEvent.getDisplayName(), oEvent.getDescription(),
oEvent.getType(), oEvent.getLocation(), oEvent.getAttachments());
try
{
BaseCalendarEventEdit eEdit = (BaseCalendarEventEdit) nCalendar.getEditEvent(e.getId(),EVENT_ADD_CALENDAR );
// properties
ResourcePropertiesEdit p = eEdit.getPropertiesEdit();
p.clear();
p.addAll(oEvent.getProperties());
// attachment
List oAttachments = eEdit.getAttachments();
List nAttachments = m_entityManager.newReferenceList();
for (int n = 0; n < oAttachments.size(); n++)
{
Reference oAttachmentRef = (Reference) oAttachments.get(n);
String oAttachmentId = ((Reference) oAttachments.get(n)).getId();
if (oAttachmentId.indexOf(fromContext) != -1)
{
// replace old site id with new site id in attachments
String nAttachmentId = oAttachmentId.replaceAll(fromContext, toContext);
try
{
ContentResource attachment = contentHostingService.getResource(nAttachmentId);
nAttachments.add(m_entityManager.newReference(attachment.getReference()));
}
catch (IdUnusedException ee)
{
try
{
ContentResource oAttachment = contentHostingService.getResource(oAttachmentId);
try
{
if (contentHostingService.isAttachmentResource(nAttachmentId))
{
// add the new resource into attachment collection area
ContentResource attachment = contentHostingService.addAttachmentResource(
Validator.escapeResourceName(oAttachment.getProperties().getProperty(ResourceProperties.PROP_DISPLAY_NAME)),
toContext,
m_toolManager.getTool("sakai.schedule").getTitle(),
oAttachment.getContentType(),
oAttachment.getContent(),
oAttachment.getProperties());
// add to attachment list
nAttachments.add(m_entityManager.newReference(attachment.getReference()));
}
else
{
// add the new resource into resource area
ContentResource attachment = contentHostingService.addResource(
Validator.escapeResourceName(oAttachment.getProperties().getProperty(ResourceProperties.PROP_DISPLAY_NAME)),
toContext,
1,
oAttachment.getContentType(),
oAttachment.getContent(),
oAttachment.getProperties(),
NotificationService.NOTI_NONE);
// add to attachment list
nAttachments.add(m_entityManager.newReference(attachment.getReference()));
}
}
catch (Exception eeAny)
{
// if the new resource cannot be added
M_log.warn(" cannot add new attachment with id=" + nAttachmentId);
}
}
catch (Exception eAny)
{
// if cannot find the original attachment, do nothing.
M_log.warn(" cannot find the original attachment with id=" + oAttachmentId);
}
}
catch (Exception any)
{
M_log.warn(this + any.getMessage());
}
}
else
{
nAttachments.add(oAttachmentRef);
}
}
eEdit.replaceAttachments(nAttachments);
// recurrence rules
RecurrenceRule rule = oEvent.getRecurrenceRule();
eEdit.setRecurrenceRule(rule);
RecurrenceRule exRule = oEvent.getExclusionRule();
eEdit.setExclusionRule(exRule);
// commit new event
m_storage.commitEvent(nCalendar, eEdit);
}
catch (InUseException ignore) {}
}
catch (PermissionException ignore) {}
}
// commit new calendar
m_storage.commitCalendar(nCalendar);
((BaseCalendarEdit) nCalendar).closeEdit();
} // if
}
catch (IdUnusedException ignore) {}
catch (PermissionException ignore) {}
return transversalMap;
} // importResources
/**
* {@inheritDoc}
*/
public void updateEntityReferences(String toContext, Map<String, String> transversalMap){
if(transversalMap != null && transversalMap.size() > 0){
Set<Entry<String, String>> entrySet = (Set<Entry<String, String>>) transversalMap.entrySet();
try
{
String toSiteId = toContext;
String calendarId = calendarReference(toSiteId, SiteService.MAIN_CONTAINER);
Calendar calendarObj = getCalendar(calendarId);
List calEvents = calendarObj.getEvents(null,null);
for (int i = 0; i < calEvents.size(); i++)
{
try
{
CalendarEvent ce = (CalendarEvent) calEvents.get(i);
String msgBodyFormatted = ce.getDescriptionFormatted();
boolean updated = false;
Iterator<Entry<String, String>> entryItr = entrySet.iterator();
while(entryItr.hasNext()) {
Entry<String, String> entry = (Entry<String, String>) entryItr.next();
String fromContextRef = entry.getKey();
if(msgBodyFormatted.contains(fromContextRef)){
msgBodyFormatted = msgBodyFormatted.replace(fromContextRef, entry.getValue());
updated = true;
}
}
if(updated){
CalendarEventEdit edit = calendarObj.getEditEvent(ce.getId(), org.sakaiproject.calendar.api.CalendarService.EVENT_MODIFY_CALENDAR);
edit.setDescriptionFormatted(msgBodyFormatted);
calendarObj.commitEvent(edit);
}
}
catch (IdUnusedException e)
{
M_log.debug(".IdUnusedException " + e);
}
catch (PermissionException e)
{
M_log.debug(".PermissionException " + e);
}
catch (InUseException e)
{
M_log.debug(".InUseException delete" + e);
}
}
}
catch (Exception e)
{
M_log.info("importSiteClean: End removing Calendar data" + e);
}
}
}
/**
* @inheritDoc
*/
public String[] myToolIds()
{
String[] toolIds = { "sakai.schedule" };
return toolIds;
}
/**
* {@inheritDoc}
*/
public void contextCreated(String context, boolean toolPlacement)
{
if (toolPlacement) enableSchedule(context);
}
/**
* {@inheritDoc}
*/
public void contextUpdated(String context, boolean toolPlacement)
{
if (toolPlacement) enableSchedule(context);
}
/**
* {@inheritDoc}
*/
public void contextDeleted(String context, boolean toolPlacement)
{
disableSchedule(context);
}
/**
* Setup a calendar for the site.
*
* @param site
* The site.
*/
protected void enableSchedule(String context)
{
// form the calendar name
String calRef = calendarReference(context, SiteService.MAIN_CONTAINER);
// see if there's a calendar
try
{
getCalendar(calRef);
}
catch (IdUnusedException un)
{
try
{
// create a calendar
CalendarEdit edit = addCalendar(calRef);
commitCalendar(edit);
}
catch (IdUsedException ignore) {}
catch (IdInvalidException ignore) {}
}
catch (PermissionException ignore) {}
}
/**
* Remove a calendar for the site.
*
* @param site
* The site.
*/
protected void disableSchedule(String context)
{
// TODO: currently we do not remove a calendar when the tool is removed from the site or the site is deleted -ggolden
}
/**********************************************************************************************************************************************************************************************************************************************************
* Calendar implementation
*********************************************************************************************************************************************************************************************************************************************************/
public class BaseCalendarEdit extends Observable implements CalendarEdit, SessionBindingListener
{
/** The context in which this calendar exists. */
protected String m_context = null;
/** Store the unique-in-context calendar id. */
protected String m_id = null;
/** The properties. */
protected ResourcePropertiesEdit m_properties = null;
/** When true, the calendar has been removed. */
protected boolean m_isRemoved = false;
/** The event code for this edit. */
protected String m_event = null;
/** Active flag. */
protected boolean m_active = false;
/**
* Construct with an id.
*
* @param ref
* The calendar reference.
*/
public BaseCalendarEdit(String ref)
{
// set the ids
Reference r = m_entityManager.newReference(ref);
m_context = r.getContext();
m_id = r.getId();
// setup for properties
m_properties = new BaseResourcePropertiesEdit();
} // BaseCalendarEdit
/**
* Construct as a copy of another.
*
* @param id
* The other to copy.
*/
public BaseCalendarEdit(Calendar other)
{
// set the ids
m_context = other.getContext();
m_id = other.getId();
// setup for properties
m_properties = new BaseResourcePropertiesEdit();
m_properties.addAll(other.getProperties());
} // BaseCalendarEdit
protected BaseCalendarEdit() {
m_properties = new BaseResourcePropertiesEdit();
}
/**
* Construct from a calendar (and possibly events) already defined in XML in a DOM tree. The Calendar is added to storage.
*
* @param el
* The XML DOM element defining the calendar.
*/
public BaseCalendarEdit(Element el)
{
// setup for properties
m_properties = new BaseResourcePropertiesEdit();
m_id = el.getAttribute("id");
m_context = el.getAttribute("context");
// the children (properties, ignore events)
NodeList children = el.getChildNodes();
final int length = children.getLength();
for (int i = 0; i < length; i++)
{
Node child = children.item(i);
if (child.getNodeType() != Node.ELEMENT_NODE) continue;
Element element = (Element) child;
// look for properties (ignore possible "event" entries)
if (element.getTagName().equals("properties"))
{
// re-create properties
m_properties = new BaseResourcePropertiesEdit(element);
}
}
} // BaseCalendarEdit
/**
* Set the calendar as removed.
*
* @param event
* The tracking event associated with this action.
*/
public void setRemoved(Event event)
{
m_isRemoved = true;
// notify observers
notify(event);
// now clear observers
deleteObservers();
} // setRemoved
/**
* Access the context of the resource.
*
* @return The context.
*/
public String getContext()
{
return m_context;
} // getContext
/**
* Access the id of the resource.
*
* @return The id.
*/
public String getId()
{
return m_id;
} // getId
/**
* Access the URL which can be used to access the resource.
*
* @return The URL which can be used to access the resource.
*/
public String getUrl()
{
return getAccessPoint(false) + SEPARATOR + getId() + SEPARATOR; // %%% needs fixing re: context
} // getUrl
/**
* Access the internal reference which can be used to access the resource from within the system.
*
* @return The the internal reference which can be used to access the resource from within the system.
*/
public String getReference()
{
return calendarReference(m_context, m_id);
} // getReference
/**
* @inheritDoc
*/
public String getReference(String rootProperty)
{
return getReference();
}
/**
* @inheritDoc
*/
public String getUrl(String rootProperty)
{
return getUrl();
}
/**
* Access the collection's properties.
*
* @return The collection's properties.
*/
public ResourceProperties getProperties()
{
return m_properties;
} // getProperties
/**
** check if this calendar allows ical exports
** @return true if the calender allows exports; false if not
**/
public boolean getExportEnabled()
{
String enable = m_properties.getProperty(CalendarService.PROP_ICAL_ENABLE);
return Boolean.valueOf(enable);
}
/**
** set if this calendar allows ical exports
** @return true if the calender allows exports; false if not
**/
public void setExportEnabled( boolean enable )
{
m_properties.addProperty(CalendarService.PROP_ICAL_ENABLE, String.valueOf(enable));
}
/**
** Get the time of the last modify to this calendar
** @return String representation of current time (may be null if not initialized)
**/
public Time getModified()
{
String timeStr = m_properties.getProperty(ResourceProperties.PROP_MODIFIED_DATE);
if ( timeStr == null )
return null;
else
return m_timeService.newTimeGmt(timeStr);
}
/**
** Set the time of the last modify for this calendar to now
** @return true if successful; false if not
**/
public void setModified()
{
String currentUser = m_sessionManager.getCurrentSessionUserId();
String now = m_timeService.newTime().toString();
m_properties.addProperty(ResourceProperties.PROP_MODIFIED_BY, currentUser);
m_properties.addProperty(ResourceProperties.PROP_MODIFIED_DATE, now);
}
/**
* check permissions for getEvents() and getEvent().
*
* @return true if the user is allowed to get events from the calendar, false if not.
*/
public boolean allowGetEvents()
{
return unlockCheck(AUTH_READ_CALENDAR, getReference());
} // allowGetEvents
/**
* {@inheritDoc}
*/
public boolean allowGetEvent(String eventId)
{
return unlockCheck(AUTH_READ_CALENDAR, eventReference(m_context, m_id, eventId));
}
/**
* Return a List of all or filtered events in the calendar. The order in which the events will be found in the iteration is by event start date.
*
* @param range
* A time range to limit the iterated events. May be null; all events will be returned.
* @param filter
* A filtering object to accept events into the iterator, or null if no filtering is desired.
* @return a List of all or filtered CalendarEvents in the calendar (may be empty).
* @exception PermissionException
* if the user does not have read permission to the calendar.
*/
public List getEvents(TimeRange range, Filter filter) throws PermissionException
{
// check security (throws if not permitted)
unlock(AUTH_READ_CALENDAR, getReference());
List events = new Vector();
if ((!m_caching) || (m_calendarCache == null) || (m_calendarCache.disabled()))
{
if ( range != null )
events = m_storage.getEvents(this, range.firstTime().getTime(), range.lastTime().getTime() );
else
events = m_storage.getEvents(this);
}
else
{
// find the event cache
Cache eventCache = (Cache) m_eventCaches.get(getReference());
if (eventCache == null)
{
synchronized (m_eventCaches)
{
// check again
eventCache = (Cache) m_eventCaches.get(getReference());
// if still not there, make one
if (eventCache == null)
{
eventCache = m_memoryService
.newCache(
"org.sakaiproject.calendar.api.CalendarService.eventCache",
service(), eventReference(
m_context, m_id, ""));
m_eventCaches.put(getReference(), eventCache);
}
}
}
// if the cache is complete, use it
if (eventCache.isComplete())
{
// get just this calendar's events
events = eventCache.getAll();
}
// otherwise get all the events from storage
else
{
// Note: while we are getting from storage, storage might change. These can be processed
// after we get the storage entries, and put them in the cache, and mark the cache complete.
// -ggolden
synchronized (eventCache)
{
// if we were waiting and it's now complete...
if (eventCache.isComplete())
{
// get just this calendar's events
events = eventCache.getAll();
}
else
{
// save up any events to the cache until we get past this load
eventCache.holdEvents();
// get all the events for the calendar
events = m_storage.getEvents(this);
// update the cache, and mark it complete
for (int i = 0; i < events.size(); i++)
{
CalendarEvent event = (CalendarEvent) events.get(i);
eventCache.put(event.getReference(), event);
}
eventCache.setComplete();
// now we are complete, process any cached events
eventCache.processEvents();
}
}
}
}
// now filter out the events to just those in the range
// Note: if no range, we won't filter, which means we don't expand recurring events, but just
// return it as a single event. This is very good for an archive... -ggolden
if (range != null)
{
events = filterEvents(events, range);
}
if (events.size() == 0) return events;
// filter out based on the filter
if (filter != null)
{
List filtered = new Vector();
for (int i = 0; i < events.size(); i++)
{
Event event = (Event) events.get(i);
if (filter.accept(event)) filtered.add(event);
}
if (filtered.size() == 0) return filtered;
events = filtered;
}
// remove any events that are grouped, and that the current user does not have permission to see
Collection groupsAllowed = getGroupsAllowGetEvent();
List allowedEvents = new Vector();
for (Iterator i = events.iterator(); i.hasNext();)
{
CalendarEvent event = (CalendarEvent) i.next();
if (event.getAccess() == EventAccess.SITE)
{
allowedEvents.add(event);
}
else
{
// if the user's Groups overlap the event's group refs it's grouped to, keep it
if (EntityCollections.isIntersectionEntityRefsToEntities(event.getGroups(), groupsAllowed))
{
allowedEvents.add(event);
}
}
}
// sort - natural order is date ascending
Collections.sort(allowedEvents);
return allowedEvents;
} // getEvents
/**
* Filter the events to only those in the time range.
*
* @param events
* The full list of events.
* @param range
* The time range.
* @return A list of events from the incoming list that overlap the given time range.
*/
protected List filterEvents(List events, TimeRange range)
{
List filtered = new Vector();
for (int i = 0; i < events.size(); i++)
{
CalendarEvent event = (CalendarEvent) events.get(i);
// resolve the event to the list of events in this range
List resolved = ((BaseCalendarEventEdit) event).resolve(range);
filtered.addAll(resolved);
}
return filtered;
} // filterEvents
/**
* Return a specific calendar event, as specified by event id.
*
* @param eventId
* The id of the event to get.
* @return the CalendarEvent that has the specified id.
* @exception IdUnusedException
* If this id is not a defined event in this calendar.
* @exception PermissionException
* If the user does not have any permissions to read the calendar.
*/
public CalendarEvent getEvent(String eventId) throws IdUnusedException, PermissionException
{
// check security on the event (throws if not permitted)
unlock(AUTH_READ_CALENDAR, eventReference(m_context, m_id, eventId));
CalendarEvent e = findEvent(eventId);
if (e == null) throw new IdUnusedException(eventId);
return e;
} // getEvent
/**
* check permissions for addEvent().
*
* @return true if the user is allowed to addEvent(...), false if not.
*/
public boolean allowAddEvent()
{
// checking allow at the channel (site) level
if (allowAddCalendarEvent()) return true;
// if not, see if the user has any groups to which adds are allowed
return (!getGroupsAllowAddEvent().isEmpty());
} // allowAddEvent
/**
* @inheritDoc
*/
public boolean allowAddCalendarEvent()
{
// check for events that will be calendar (site) -wide:
// base the check for SECURE_ADD on the site and the calendar only (not the groups).
// check security on the calendar (throws if not permitted)
return unlockCheck(AUTH_ADD_CALENDAR, getReference());
}
/**
* Add a new event to this calendar.
*
* @param range
* The event's time range.
* @param displayName
* The event's display name (PROP_DISPLAY_NAME) property value.
* @param description
* The event's description as plain text (PROP_DESCRIPTION) property value.
* @param type
* The event's calendar event type (PROP_CALENDAR_TYPE) property value.
* @param location
* The event's calendar event location (PROP_CALENDAR_LOCATION) property value.
* @param attachments
* The event attachments, a vector of Reference objects.
* @return The newly added event.
* @exception PermissionException
* If the user does not have permission to modify the calendar.
*/
public CalendarEvent addEvent(TimeRange range, String displayName, String description, String type, String location, EventAccess access, Collection groups,
List attachments) throws PermissionException
{
// securtiy check (any sort (group, site) of add)
if (!allowAddEvent())
{
throw new PermissionException(m_sessionManager.getCurrentSessionUserId(), eventId(SECURE_ADD), getReference());
}
// make one
// allocate a new unique event id
String id = getUniqueId();
// get a new event in the info store
CalendarEventEdit edit = m_storage.putEvent(this, id);
((BaseCalendarEventEdit) edit).setEvent(EVENT_ADD_CALENDAR);
// set it up
edit.setRange(range);
edit.setDisplayName(displayName);
edit.setDescription(description);
edit.setType(type);
edit.setLocation(location);
edit.setCreator();
// for site...
if (access == EventAccess.SITE)
{
// if not allowd to SITE, will throw permission exception
try
{
edit.clearGroupAccess();
}
catch (PermissionException e)
{
cancelEvent(edit);
throw new PermissionException(m_sessionManager.getCurrentSessionUserId(), eventId(SECURE_ADD), getReference());
}
}
// for grouped...
else
{
// if not allowed to GROUP, will throw permission exception
try
{
edit.setGroupAccess(groups,true);
}
catch (PermissionException e)
{
cancelEvent(edit);
throw new PermissionException(m_sessionManager.getCurrentSessionUserId(), eventId(SECURE_ADD), getReference());
}
}
edit.replaceAttachments(attachments);
// commit it
commitEvent(edit);
return edit;
} // addEvent
/**
* Add a new event to this calendar.
*
* @param range
* The event's time range.
* @param displayName
* The event's display name (PROP_DISPLAY_NAME) property value.
* @param description
* The event's description as plain text (PROP_DESCRIPTION) property value.
* @param type
* The event's calendar event type (PROP_CALENDAR_TYPE) property value.
* @param location
* The event's calendar event location (PROP_CALENDAR_LOCATION) property value.
* @param attachments
* The event attachments, a vector of Reference objects.
* @return The newly added event.
* @exception PermissionException
* If the user does not have permission to modify the calendar.
*/
public CalendarEvent addEvent(TimeRange range, String displayName, String description, String type, String location,
List attachments) throws PermissionException
{
// make one
CalendarEventEdit edit = addEvent();
// set it up
edit.setRange(range);
edit.setDisplayName(displayName);
edit.setDescription(description);
edit.setType(type);
edit.setLocation(location);
edit.replaceAttachments(attachments);
// commit it
commitEvent(edit);
return edit;
} // addEvent
/**
* Add a new event to this calendar. Must commitEvent() to make official, or cancelEvent() when done!
*
* @return The newly added event, locked for update.
* @exception PermissionException
* If the user does not have write permission to the calendar.
*/
public CalendarEventEdit addEvent() throws PermissionException
{
// check security (throws if not permitted)
unlock(AUTH_ADD_CALENDAR, getReference());
// allocate a new unique event id
String id = getUniqueId();
// get a new event in the info store
CalendarEventEdit event = m_storage.putEvent(this, id);
((BaseCalendarEventEdit) event).setEvent(EVENT_ADD_CALENDAR);
return event;
} // addEvent
/**
* Merge in a new event as defined in the xml.
*
* @param el
* The event information in XML in a DOM element.
* @exception PermissionException
* If the user does not have write permission to the calendar.
* @exception IdUsedException
* if the user id is already used.
*/
public CalendarEventEdit mergeEvent(Element el) throws PermissionException, IdUsedException
{
CalendarEvent eventFromXml = (CalendarEvent) newResource(this, el);
// check security
if ( ! allowAddEvent() )
throw new PermissionException(m_sessionManager.getCurrentSessionUserId(),
AUTH_ADD_CALENDAR, getReference());
// reserve a calendar event with this id from the info store - if it's in use, this will return null
CalendarEventEdit event = m_storage.putEvent(this, eventFromXml.getId());
if (event == null)
{
throw new IdUsedException(eventFromXml.getId());
}
// transfer from the XML read object to the Edit
((BaseCalendarEventEdit) event).set(eventFromXml);
((BaseCalendarEventEdit) event).setEvent(EVENT_MODIFY_CALENDAR);
return event;
} // mergeEvent
/**
* check permissions for removeEvent().
*
* @param event
* The event from this calendar to remove.
* @return true if the user is allowed to removeEvent(event), false if not.
*/
public boolean allowRemoveEvent(CalendarEvent event)
{
boolean allowed = false;
boolean ownEvent = event.isUserOwner();
// check security to delete any event
if ( unlockCheck(AUTH_REMOVE_CALENDAR_ANY, getReference()) )
allowed = true;
// check security to delete own event
else if ( unlockCheck(AUTH_REMOVE_CALENDAR_OWN, getReference()) && ownEvent )
allowed = true;
// but we must also assure, that for grouped events, we can remove it from ALL of the groups
if (allowed && (event.getAccess() == EventAccess.GROUPED))
{
allowed = EntityCollections.isContainedEntityRefsToEntities(event.getGroups(), getGroupsAllowRemoveEvent(ownEvent));
}
return allowed;
} // allowRemoveEvent
/**
* Remove an event from the calendar, one locked for edit. Note: if the event is a recurring event, the entire sequence is modified by this commit (MOD_ALL).
*
* @param event
* The event from this calendar to remove.
*/
public void removeEvent(CalendarEventEdit edit) throws PermissionException
{
removeEvent(edit, MOD_ALL);
} // removeEvent
/**
* Remove an event from the calendar, one locked for edit.
*
* @param event
* The event from this calendar to remove.
* @param intention
* The recurring event modification intention, based on values in the CalendarService "MOD_*", used if the event is part of a recurring event sequence to determine how much of the sequence is removed.
*/
public void removeEvent(CalendarEventEdit edit, int intention) throws PermissionException
{
// check for closed edit
if (!edit.isActiveEdit())
{
try
{
throw new Exception();
}
catch (Exception e)
{
M_log.warn("removeEvent(): closed EventEdit", e);
}
return;
}
// securityCheck
if (!allowRemoveEvent(edit))
{
cancelEvent(edit);
throw new PermissionException(m_sessionManager.getCurrentSessionUserId(), AUTH_REMOVE_CALENDAR_ANY, edit.getReference());
}
BaseCalendarEventEdit bedit = (BaseCalendarEventEdit) edit;
// if the id has a time range encoded, as for one of a sequence of recurring events, separate that out
String indivEventEntityRef = null;
TimeRange timeRange = null;
int sequence = 0;
if (bedit.m_id.startsWith("!"))
{
indivEventEntityRef = bedit.getReference();
String[] parts = bedit.m_id.substring(1).split("!");
try
{
timeRange = m_timeService.newTimeRange(parts[0]);
sequence = Integer.parseInt(parts[1]);
bedit.m_id = parts[2];
}
catch (Exception ex)
{
M_log.warn("removeEvent: exception parsing eventId: " + bedit.m_id + " : " + ex);
}
}
// deal with recurring event sequence modification
if (timeRange != null)
{
// delete only this - add it as an exclusion in the edit
if (intention == MOD_THIS)
{
// get the edit back to initial values... so only the exclusion is changed
edit = (CalendarEventEdit) m_storage.getEvent(this, bedit.m_id);
bedit = (BaseCalendarEventEdit) edit;
// add an exclusion for where this one would have been %%% we are changing it, should it be immutable? -ggolden
List exclusions = ((ExclusionSeqRecurrenceRule) bedit.getExclusionRule()).getExclusions();
exclusions.add(Integer.valueOf(sequence));
// complete the edit
m_storage.commitEvent(this, edit);
// post event for excluding the instance
m_eventTrackingService.post(m_eventTrackingService.newEvent(EVENT_MODIFY_CALENDAR_EVENT_EXCLUSIONS, indivEventEntityRef, true));
}
// delete them all, i.e. the one initial event
else
{
m_storage.removeEvent(this, edit);
m_eventTrackingService.post(m_eventTrackingService.newEvent(EVENT_REMOVE_CALENDAR_EVENT, edit.getReference(), true));
}
}
// else a single event to delete
else
{
m_storage.removeEvent(this, edit);
m_eventTrackingService.post(m_eventTrackingService.newEvent(EVENT_REMOVE_CALENDAR_EVENT, edit.getReference(), true));
}
// track event
Event event = m_eventTrackingService.newEvent(EVENT_MODIFY_CALENDAR, edit.getReference(), true);
m_eventTrackingService.post(event);
// calendar notification
notify(event);
// close the edit object
((BaseCalendarEventEdit) edit).closeEdit();
// remove any realm defined for this resource
try
{
m_authzGroupService.removeAuthzGroup(m_authzGroupService.getAuthzGroup(edit.getReference()));
}
catch (AuthzPermissionException e)
{
M_log.warn("removeEvent: removing realm for : " + edit.getReference() + " : " + e);
}
catch (GroupNotDefinedException ignore)
{
}
} // removeEvent
/**
* check permissions for editEvent()
*
* @param id
* The event id.
* @return true if the user is allowed to update the event, false if not.
*/
public boolean allowEditEvent(String eventId)
{
CalendarEvent e = findEvent(eventId);
if (e == null) return false;
boolean ownEvent = e.isUserOwner();
// check security to revise any event
if ( unlockCheck(AUTH_MODIFY_CALENDAR_ANY, getReference()) )
return true;
// check security to revise own event
else if ( unlockCheck(AUTH_MODIFY_CALENDAR_OWN, getReference()) && ownEvent )
return true;
// otherwise not authorized
else
return false;
} // allowEditEvent
/**
* Return a specific calendar event, as specified by event name, locked for update.
* Must commitEvent() to make official, or cancelEvent(), or removeEvent() when done!
*
* @param eventId The id of the event to get.
* @param editType add, remove or modifying calendar?
* @return the Event that has the specified id.
* @exception IdUnusedException
* If this name is not a defined event in this calendar.
* @exception PermissionException
* If the user does not have any permissions to edit the event.
* @exception InUseException
* if the event is locked for edit by someone else.
*/
public CalendarEventEdit getEditEvent(String eventId, String editType)
throws IdUnusedException, PermissionException, InUseException
{
// if the id has a time range encoded, as for one of a sequence of recurring events, separate that out
TimeRange timeRange = null;
int sequence = 0;
if (eventId.startsWith("!"))
{
String[] parts = eventId.substring(1).split("!");
try
{
timeRange = m_timeService.newTimeRange(parts[0]);
sequence = Integer.parseInt(parts[1]);
eventId = parts[2];
}
catch (Exception ex)
{
M_log.warn("getEditEvent: exception parsing eventId: " + eventId + " : " + ex);
}
}
CalendarEvent e = findEvent(eventId);
if (e == null) throw new IdUnusedException(eventId);
// check security
if ( editType.equals(EVENT_ADD_CALENDAR) && ! allowAddEvent() )
throw new PermissionException(m_sessionManager.getCurrentSessionUserId(),
AUTH_ADD_CALENDAR, getReference());
else if ( editType.equals(EVENT_REMOVE_CALENDAR) && ! allowRemoveEvent(e) )
throw new PermissionException(m_sessionManager.getCurrentSessionUserId(),
AUTH_REMOVE_CALENDAR_ANY, getReference());
else if ( editType.equals(EVENT_MODIFY_CALENDAR) && ! allowEditEvent(eventId) )
throw new PermissionException(m_sessionManager.getCurrentSessionUserId(),
AUTH_MODIFY_CALENDAR_ANY, getReference());
// ignore the cache - get the CalendarEvent with a lock from the info store
CalendarEventEdit edit = m_storage.editEvent(this, eventId);
if (edit == null) throw new InUseException(eventId);
BaseCalendarEventEdit bedit = (BaseCalendarEventEdit) edit;
// if this is one in a sequence, adjust it
if (timeRange != null)
{
// move the specified range into the event's range, storing the base range
bedit.m_baseRange = bedit.m_range;
bedit.m_range = timeRange;
bedit.m_id = '!' + bedit.m_range.toString() + '!' + sequence + '!' + bedit.m_id;
}
bedit.setEvent(EVENT_MODIFY_CALENDAR);
return edit;
} // getEditEvent
/**
* Commit the changes made to a CalendarEventEdit object, and release the lock. The CalendarEventEdit is disabled, and not to be used after this call. Note: if the event is a recurring event, the entire sequence is modified by this commit
* (MOD_ALL).
*
* @param edit
* The CalendarEventEdit object to commit.
*/
public void commitEvent(CalendarEventEdit edit)
{
commitEvent(edit, MOD_ALL);
} // commitEvent
/**
* Commit the changes made to a CalendarEventEdit object, and release the lock. The CalendarEventEdit is disabled, and not to be used after this call.
*
* @param edit
* The CalendarEventEdit object to commit.
* @param intention
* The recurring event modification intention, based on values in the CalendarService "MOD_*", used if the event is part of a recurring event sequence to determine how much of the sequence is changed by this commmit.
*/
public void commitEvent(CalendarEventEdit edit, int intention)
{
// check for closed edit
if (!edit.isActiveEdit())
{
M_log.warn("commitEvent(): closed CalendarEventEdit " + edit.getId());
return;
}
BaseCalendarEventEdit bedit = (BaseCalendarEventEdit) edit;
// If creator doesn't exist, set it now (backward compatibility)
if ( edit.getCreator() == null || edit.getCreator().equals("") )
edit.setCreator();
// update modified-by properties for event
edit.setModifiedBy();
// if the id has a time range encoded, as for one of a sequence of recurring events, separate that out
String indivEventEntityRef = null;
TimeRange timeRange = null;
int sequence = 0;
if (bedit.m_id.startsWith("!"))
{
indivEventEntityRef = bedit.getReference();
String[] parts = bedit.m_id.substring(1).split("!");
try
{
timeRange = m_timeService.newTimeRange(parts[0]);
sequence = Integer.parseInt(parts[1]);
bedit.m_id = parts[2];
}
catch (Exception ex)
{
M_log.warn("commitEvent: exception parsing eventId: " + bedit.m_id + " : " + ex);
}
}
// for recurring event sequence
TimeRange newTimeRange = null;
BaseCalendarEventEdit newEvent = null;
if (timeRange != null)
{
// if changing this event only
if (intention == MOD_THIS)
{
// make a new event for this one
String id = getUniqueId();
newEvent = (BaseCalendarEventEdit) m_storage.putEvent(this, id);
newEvent.setPartial(edit);
m_storage.commitEvent(this, newEvent);
m_eventTrackingService.post(m_eventTrackingService.newEvent(EVENT_MODIFY_CALENDAR, newEvent.getReference(), true));
m_eventTrackingService.post(m_eventTrackingService.newEvent(EVENT_MODIFY_CALENDAR_EVENT_EXCLUDED, newEvent.getReference(), true));
m_eventTrackingService.post(m_eventTrackingService.newEvent(EVENT_MODIFY_CALENDAR_EVENT_EXCLUSIONS, indivEventEntityRef, true));
// get the edit back to initial values... so only the exclusion is changed
edit = (CalendarEventEdit) m_storage.getEvent(this, bedit.m_id);
bedit = (BaseCalendarEventEdit) edit;
// add an exclusion for where this one would have been %%% we are changing it, should it be immutable? -ggolden
List exclusions = ((ExclusionSeqRecurrenceRule) bedit.getExclusionRule()).getExclusions();
exclusions.add(Integer.valueOf(sequence));
}
// else change the entire sequence (i.e. the one initial event)
else
{
// the time range may have been modified in the edit
newTimeRange = bedit.m_range;
// restore the real range, that of the base event of a sequence, if this is one of the other events in the sequence.
bedit.m_range = bedit.m_baseRange;
// adjust the base range if there was an edit to range
bedit.m_range.adjust(timeRange, newTimeRange);
}
}
// update the properties
// addLiveUpdateProperties(edit.getPropertiesEdit());//%%%
postEventsForChanges(bedit);
// complete the edit
m_storage.commitEvent(this, edit);
// track event
Event event = m_eventTrackingService.newEvent(bedit.getEvent(), edit.getReference(), true);
m_eventTrackingService.post(event);
// calendar notification
notify(event);
// close the edit object
bedit.closeEdit();
// Update modify time on calendar
this.setModified();
m_storage.commitCalendar(this);
// restore this one's range etc so it can be further referenced
if (timeRange != null)
{
// if changing this event only
if (intention == MOD_THIS)
{
// set the edit to the values of the new event
bedit.set(newEvent);
}
// else we changed the sequence
else
{
// move the specified range into the event's range, storing the base range
bedit.m_baseRange = bedit.m_range;
bedit.m_range = newTimeRange;
bedit.m_id = '!' + bedit.m_range.toString() + '!' + sequence + '!' + bedit.m_id;
}
}
} // commitEvent
/**
* @param newEvent
*/
public void postEventsForChanges(BaseCalendarEventEdit newEvent) {
// determine which events should be posted by comparing with saved properties
BaseCalendarEventEdit savedEvent = (BaseCalendarEventEdit) this.findEvent(newEvent.m_id);
if(savedEvent == null) {
} else {
// has type changed?
String savedType = savedEvent.getType();
String newType = newEvent.getType();
if(savedType == null || newType == null) {
// TODO: is this an error?
} else {
if (!newType.equals(savedType))
{
// post type-change event
m_eventTrackingService.post(m_eventTrackingService.newEvent(EVENT_MODIFY_CALENDAR_EVENT_TYPE, newEvent.getReference() + "::" + savedType + "::" + newType, true));
}
}
// has title changed?
if(savedEvent.getDisplayName() != null && ! savedEvent.getDisplayName().equals(newEvent.getDisplayName())) {
// post title-change event
m_eventTrackingService.post(m_eventTrackingService.newEvent(EVENT_MODIFY_CALENDAR_EVENT_TITLE, newEvent.getReference(), true));
}
// has start-time changed?
TimeRange savedRange = savedEvent.getRange();
TimeRange newRange = newEvent.getRange();
if(savedRange == null || newRange == null) {
// TODO: Is this an error?
} else if(savedRange.firstTime() != null && savedRange.firstTime().compareTo(newRange.firstTime()) != 0) {
// post time-change event
m_eventTrackingService.post(m_eventTrackingService.newEvent(EVENT_MODIFY_CALENDAR_EVENT_TIME, newEvent.getReference(), true));
}
// has access changed?
if(savedEvent.getAccess() != newEvent.getAccess()) {
// post access-change event
m_eventTrackingService.post(m_eventTrackingService.newEvent(EVENT_MODIFY_CALENDAR_EVENT_ACCESS, newEvent.getReference(), true));
} else {
Collection savedGroups = savedEvent.getGroups();
Collection newGroups = newEvent.getGroups();
if(! (savedGroups.containsAll(newGroups) && newGroups.containsAll(savedGroups))) {
// post access-change event
m_eventTrackingService.post(m_eventTrackingService.newEvent(EVENT_MODIFY_CALENDAR_EVENT_ACCESS, newEvent.getReference(), true));
}
}
// has frequency changed (other than exclusions)?
RecurrenceRule savedRule = savedEvent.getRecurrenceRule();
RecurrenceRule newRule = newEvent.getRecurrenceRule();
if(savedRule == null && newRule == null) {
// do nothing -- no change
} else if(savedRule == null || newRule == null) {
// post frequency-change event
m_eventTrackingService.post(m_eventTrackingService.newEvent(EVENT_MODIFY_CALENDAR_EVENT_FREQUENCY, newEvent.getReference(), true));
} else {
// check for changes in properties of the rules
// (rule.getCount() rule.getFrequency() rule.getInterval() rule.getUntil()
if(savedRule.getCount() != newRule.getCount() || savedRule.getInterval() != newRule.getInterval()) {
// post frequency-change event
m_eventTrackingService.post(m_eventTrackingService.newEvent(EVENT_MODIFY_CALENDAR_EVENT_FREQUENCY, newEvent.getReference(), true));
} else if((savedRule.getFrequency() != null && ! savedRule.getFrequency().equals(newRule.getFrequency())) || (savedRule.getFrequency() == null && newRule.getFrequency() != null)) {
// post frequency-change event
m_eventTrackingService.post(m_eventTrackingService.newEvent(EVENT_MODIFY_CALENDAR_EVENT_FREQUENCY, newEvent.getReference(), true));
} else if((savedRule.getUntil() == null && newRule.getUntil() != null)
|| (savedRule.getUntil() != null && newRule.getUntil() == null)
|| (savedRule.getUntil() != null && savedRule.getUntil().getTime() != newRule.getUntil().getTime())) {
// post frequency-change event
m_eventTrackingService.post(m_eventTrackingService.newEvent(EVENT_MODIFY_CALENDAR_EVENT_FREQUENCY, newEvent.getReference(), true));
}
}
}
}
/**
* Cancel the changes made to a CalendarEventEdit object, and release the lock. The CalendarEventEdit is disabled, and not to be used after this call.
*
* @param edit
* The CalendarEventEdit object to commit.
*/
public void cancelEvent(CalendarEventEdit edit)
{
// check for closed edit
if (!edit.isActiveEdit())
{
Throwable e = new Throwable();
M_log.warn("cancelEvent(): closed CalendarEventEdit", e);
return;
}
BaseCalendarEventEdit bedit = (BaseCalendarEventEdit) edit;
// if the id has a time range encoded, as for one of a sequence of recurring events, separate that out
TimeRange timeRange = null;
int sequence = 0;
if (bedit.m_id.startsWith("!"))
{
String[] parts = bedit.m_id.substring(1).split( "!");
try
{
timeRange = m_timeService.newTimeRange(parts[0]);
sequence = Integer.parseInt(parts[1]);
bedit.m_id = parts[2];
}
catch (Exception ex)
{
M_log.warn("commitEvent: exception parsing eventId: " + bedit.m_id + " : " + ex);
}
}
// release the edit lock
m_storage.cancelEvent(this, edit);
// close the edit object
((BaseCalendarEventEdit) edit).closeEdit();
} // cancelCalendarEvent
/**
* Return the extra fields kept for each event in this calendar.
*
* @return the extra fields kept for each event in this calendar, formatted into a single string. %%%
*/
public String getEventFields()
{
return m_properties.getPropertyFormatted(ResourceProperties.PROP_CALENDAR_EVENT_FIELDS);
} // getEventFields
/**
* Set the extra fields kept for each event in this calendar.
*
* @param meta
* The extra fields kept for each event in this calendar, formatted into a single string. %%%
*/
public void setEventFields(String fields)
{
m_properties.addProperty(ResourceProperties.PROP_CALENDAR_EVENT_FIELDS, fields);
} // setEventFields
/**
* Notify the calendar that it has changed
*
* @param event
* The event that caused the update.
*/
public void notify(Event event)
{
// notify observers, sending the tracking event to identify the change
setChanged();
notifyObservers(event);
} // notify
/**
* Serialize the resource into XML, adding an element to the doc under the top of the stack element.
*
* @param doc
* The DOM doc to contain the XML (or null for a string return).
* @param stack
* The DOM elements, the top of which is the containing element of the new "resource" element.
* @return The newly added element.
*/
public Element toXml(Document doc, Stack stack)
{
Element calendar = doc.createElement("calendar");
if (stack.isEmpty())
{
doc.appendChild(calendar);
}
else
{
((Element) stack.peek()).appendChild(calendar);
}
stack.push(calendar);
calendar.setAttribute("context", m_context);
calendar.setAttribute("id", m_id);
// properties
m_properties.toXml(doc, stack);
stack.pop();
return calendar;
} // toXml
/**
* Find the event, in cache or info store - cache it if newly found.
*
* @param eventId
* The id of the event.
* @return The event, if found.
*/
protected CalendarEvent findEvent(String eventId)
{
CalendarEvent e = null;
// if the id has a time range encoded, as for one of a sequence of recurring events, separate that out
TimeRange timeRange = null;
int sequence = 0;
if (eventId.startsWith("!"))
{
String[] parts = eventId.substring(1).split("!");
try
{
timeRange = m_timeService.newTimeRange(parts[0]);
sequence = Integer.parseInt(parts[1]);
eventId = parts[2];
}
catch (Exception ex)
{
M_log.warn("findEvent: exception parsing eventId: " + eventId + " : " + ex);
}
}
// events are cached with the full reference as key
String key = eventReference(m_context, m_id, eventId);
// if cache is disabled, don't use it
if ((!m_caching) || (m_calendarCache == null) || (m_calendarCache.disabled()))
{
// if we have "cached" the entire set of events in the thread, get that and find our message there
List events = (List) m_threadLocalManager.get(getReference() + ".events");
if (events != null)
{
for (Iterator i = events.iterator(); i.hasNext();)
{
CalendarEvent event = (CalendarEvent) i.next();
if (event.getId().equals(eventId))
{
e = event;
break;
}
}
}
if (e == null)
{
e = m_storage.getEvent(this, eventId);
}
}
else
{
// find the event cache
Cache eventCache = (Cache) m_eventCaches.get(getReference());
if (eventCache == null)
{
synchronized (m_eventCaches)
{
// check again
eventCache = (Cache) m_eventCaches.get(getReference());
// if still not there, make one
if (eventCache == null)
{
eventCache = m_memoryService
.newCache(
"org.sakaiproject.calendar.api.CalendarService.eventCache",
service(), eventReference(
m_context, m_id, ""));
m_eventCaches.put(getReference(), eventCache);
}
}
}
// if we have it cached, use it (even if it's cached as a null, a miss)
if (eventCache.containsKey(key))
{
e = (CalendarEvent) eventCache.get(key);
}
// if not in the cache, see if we have it in our info store
if ( e == null ) //SAK-12447 cache.get can return null on expired
{
e = m_storage.getEvent(this, eventId);
// if so, cache it, even misses
eventCache.put(key, e);
}
}
// now we have the primary event, if we have a recurring event sequence time range selector, use it
if ((e != null) && (timeRange != null))
{
e = new BaseCalendarEventEdit(e, new RecurrenceInstance(timeRange, sequence));
}
return e;
} // findEvent
/**
* Access the event code for this edit.
*
* @return The event code for this edit.
*/
protected String getEvent()
{
return m_event;
}
/**
* Set the event code for this edit.
*
* @param event
* The event code for this edit.
*/
protected void setEvent(String event)
{
m_event = event;
}
/**
* Access the resource's properties for modification
*
* @return The resource's properties.
*/
public ResourcePropertiesEdit getPropertiesEdit()
{
return m_properties;
} // getPropertiesEdit
/**
* Enable editing.
*/
protected void activate()
{
m_active = true;
} // activate
/**
* Check to see if the edit is still active, or has already been closed.
*
* @return true if the edit is active, false if it's been closed.
*/
public boolean isActiveEdit()
{
return m_active;
} // isActiveEdit
/**
* Close the edit object - it cannot be used after this.
*/
protected void closeEdit()
{
m_active = false;
} // closeEdit
/**
* {@inheritDoc}
*/
public Collection getGroupsAllowAddEvent()
{
return getGroupsAllowFunction(AUTH_ADD_CALENDAR);
}
/**
* {@inheritDoc}
*/
public Collection getGroupsAllowGetEvent()
{
return getGroupsAllowFunction(AUTH_READ_CALENDAR);
}
/**
* {@inheritDoc}
*/
public Collection getGroupsAllowRemoveEvent( boolean own )
{
return getGroupsAllowFunction(own ? AUTH_REMOVE_CALENDAR_OWN : AUTH_REMOVE_CALENDAR_ANY );
}
/**
* Get the groups of this channel's contex-site that the end user has permission to "function" in.
* @param function The function to check
*/
protected Collection getGroupsAllowFunction(String function)
{
Vector rv = new Vector();
try
{
// get the channel's site's groups
Site site = m_siteService.getSite(m_context);
Collection groups = site.getGroups();
// if the user has SECURE_ALL_GROUPS in the context (site), and the function for the calendar (calendar,site), select all site groups
if ((m_securityService.isSuperUser()) || (m_authzGroupService.isAllowed(m_sessionManager.getCurrentSessionUserId(), SECURE_ALL_GROUPS, m_siteService.siteReference(m_context))
&& unlockCheck(function, getReference())))
{
rv.addAll( groups );
Collections.sort( rv, groupComparator );
return (Collection)rv;
}
// otherwise, check the groups for function
// get a list of the group refs, which are authzGroup ids
Collection groupRefs = new Vector();
for (Iterator i = groups.iterator(); i.hasNext();)
{
Group group = (Group) i.next();
groupRefs.add(group.getReference());
}
// ask the authzGroup service to filter them down based on function
groupRefs = m_authzGroupService.getAuthzGroupsIsAllowed(m_sessionManager.getCurrentSessionUserId(), function, groupRefs);
// pick the Group objects from the site's groups to return, those that are in the groupRefs list
for (Iterator i = groups.iterator(); i.hasNext();)
{
Group group = (Group) i.next();
if (groupRefs.contains(group.getReference()))
{
rv.add(group);
}
}
}
catch (IdUnusedException ignore) {}
Collections.sort( rv, groupComparator );
return (Collection)rv;
} // getGroupsAllowFunction
/******************************************************************************************************************************************************************************************************************************************************
* SessionBindingListener implementation
*****************************************************************************************************************************************************************************************************************************************************/
public void valueBound(SessionBindingEvent event)
{
}
public void valueUnbound(SessionBindingEvent event)
{
if (M_log.isDebugEnabled()) M_log.debug("valueUnbound()");
// catch the case where an edit was made but never resolved
if (m_active)
{
cancelCalendar(this);
}
} // valueUnbound
/**
* Get a ContentHandler suitable for populating this object from SAX Events
* @return
*/
public ContentHandler getContentHandler(Map<String,Object> services)
{
final Entity thisEntity = this;
return new DefaultEntityHandler() {
/* (non-Javadoc)
* @see org.sakaiproject.util.DefaultEntityHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)
*/
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException
{
if ( doStartElement(uri, localName, qName, attributes) ) {
if ( "calendar".equals(qName) && entity == null ) {
m_id = attributes.getValue("id");
m_context = attributes.getValue("context");
entity = thisEntity;
} else {
M_log.warn("Unexpected element "+qName);
}
}
}
};
}
} // class BaseCalendar
/**********************************************************************************************************************************************************************************************************************************************************
* CalendarEvent implementation
*********************************************************************************************************************************************************************************************************************************************************/
public class BaseCalendarEventEdit implements CalendarEventEdit, SessionBindingListener
{
/** The calendar in which this event lives. */
protected BaseCalendarEdit m_calendar = null;
/** The effective time range. */
protected TimeRange m_range = null;
/**
* The base time range: for non-recurring events, this matches m_range, but for recurring events, it is always the range of the initial event in the sequence (transient).
*/
protected TimeRange m_baseRange = null;
/** The recurrence rule (single rule). */
protected RecurrenceRule m_singleRule = null;
/** The exclusion recurrence rule. */
protected RecurrenceRule m_exclusionRule = null;
/** The properties. */
protected ResourcePropertiesEdit m_properties = null;
/** The event id. */
protected String m_id = null;
/** The attachments - dereferencer objects. */
protected List m_attachments = null;
/** The event code for this edit. */
protected String m_event = null;
/** Active flag. */
protected boolean m_active = false;
/** The Collection of groups (authorization group id strings). */
protected Collection m_groups = new Vector();
/** The message access. */
protected EventAccess m_access = EventAccess.SITE;
/**
* Construct.
*
* @param calendar
* The calendar in which this event lives.
* @param id
* The event id, unique within the calendar.
*/
public BaseCalendarEventEdit(Calendar calendar, String id)
{
m_calendar = (BaseCalendarEdit) calendar;
m_id = id;
// setup for properties
m_properties = new BaseResourcePropertiesEdit();
// init the AttachmentContainer
m_attachments = m_entityManager.newReferenceList();
} // BaseCalendarEventEdit
/**
* Construct as a copy of another event.
*
* @param other
* The other event to copy.
*/
public BaseCalendarEventEdit(Calendar calendar, CalendarEvent other)
{
// store the calendar
m_calendar = (BaseCalendarEdit) calendar;
set(other);
} // BaseCalendarEventEdit
/**
* Construct as a thin copy of another event, with this new time range, and no rules, as part of a recurring event sequence.
*
* @param other
* The other event to copy.
* @param ri
* The RecurrenceInstance with the time range (and sequence number) to use.
*/
public BaseCalendarEventEdit(CalendarEvent other, RecurrenceInstance ri)
{
// store the calendar
m_calendar = ((BaseCalendarEventEdit) other).m_calendar;
// encode the instance and the other's id into my id
m_id = '!' + ri.getRange().toString() + '!' + ri.getSequence() + '!' + ((BaseCalendarEventEdit) other).m_id;
// use the new range
m_range = (TimeRange) ri.getRange().clone();
m_baseRange = ((BaseCalendarEventEdit) other).m_range;
// point at the properties
m_properties = ((BaseCalendarEventEdit) other).m_properties;
m_access = ((BaseCalendarEventEdit) other).m_access;
// point at the groups
m_groups = ((BaseCalendarEventEdit) other).m_groups;
// point at the attachments
m_attachments = ((BaseCalendarEventEdit) other).m_attachments;
// point at the rules
m_singleRule = ((BaseCalendarEventEdit) other).m_singleRule;
m_exclusionRule = ((BaseCalendarEventEdit) other).m_exclusionRule;
} // BaseCalendarEventEdit
/**
* Construct from an existing definition, in xml.
*
* @param calendar
* The calendar in which this event lives.
* @param el
* The event in XML in a DOM element.
*/
public BaseCalendarEventEdit(Calendar calendar, Element el)
{
m_calendar = (BaseCalendarEdit) calendar;
m_properties = new BaseResourcePropertiesEdit();
m_attachments = m_entityManager.newReferenceList();
m_id = el.getAttribute("id");
m_range = m_timeService.newTimeRange(el.getAttribute("range"));
m_access = CalendarEvent.EventAccess.SITE;
String access_str = el.getAttribute("access").toString();
if (access_str.equals(CalendarEvent.EventAccess.GROUPED.toString()))
m_access = CalendarEvent.EventAccess.GROUPED;
// the children (props / attachments / rules)
NodeList children = el.getChildNodes();
final int length = children.getLength();
for (int i = 0; i < length; i++)
{
Node child = children.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE)
{
Element element = (Element) child;
// look for an attachment
if (element.getTagName().equals("attachment"))
{
m_attachments.add(m_entityManager.newReference(element.getAttribute("relative-url")));
}
// look for properties
else if (element.getTagName().equals("properties"))
{
// re-create properties
m_properties = new BaseResourcePropertiesEdit(element);
}
else if (element.getTagName().equals("group"))
{
m_groups.add(element.getAttribute("authzGroup"));
}
// else look for rules
else if (element.getTagName().equals("rules"))
{
// children are "rule" elements
NodeList ruleChildren = element.getChildNodes();
final int ruleChildrenLength = ruleChildren.getLength();
for (int iRuleChildren = 0; iRuleChildren < ruleChildrenLength; iRuleChildren++)
{
Node ruleChildNode = ruleChildren.item(iRuleChildren);
if (ruleChildNode.getNodeType() == Node.ELEMENT_NODE)
{
Element ruleChildElement = (Element) ruleChildNode;
// look for a rule or exclusion rule
if (ruleChildElement.getTagName().equals("rule") || ruleChildElement.getTagName().equals("ex-rule"))
{
// get the rule name - modern style encoding
String ruleName = StringUtils.trimToNull(ruleChildElement.getAttribute("name"));
// deal with old data
if (ruleName == null)
{
// get the class - this is old CHEF 1.2.10 style encoding
String ruleClassOld = ruleChildElement.getAttribute("class");
// use the last class name minus the package
if ( ruleClassOld != null )
ruleName = ruleClassOld.substring(ruleClassOld.lastIndexOf('.') + 1);
if ( ruleName == null )
M_log.warn("trouble loading rule");
}
if (ruleName != null)
{
// put my package on the class name
String ruleClass = this.getClass().getPackage().getName() + "." + ruleName;
// construct
try
{
if (ruleChildElement.getTagName().equals("rule"))
{
m_singleRule = (RecurrenceRule) Class.forName(ruleClass).newInstance();
m_singleRule.set(ruleChildElement);
}
else // ruleChildElement.getTagName().equals("ex-rule"))
{
m_exclusionRule = (RecurrenceRule) Class.forName(ruleClass).newInstance();
m_exclusionRule.set(ruleChildElement);
}
}
catch (Exception e)
{
M_log.warn("trouble loading rule: " + ruleClass + " : " + e);
}
}
}
}
}
}
}
}
} // BaseCalendarEventEdit
/**
*
*/
public BaseCalendarEventEdit(Entity container)
{
m_calendar = (BaseCalendarEdit) container;
m_properties = new BaseResourcePropertiesEdit();
m_attachments = m_entityManager.newReferenceList();
}
/**
* Take all values from this object.
*
* @param other
* The other object to take values from.
*/
protected void set(CalendarEvent other)
{
// copy the id
m_id = other.getId();
// copy the range
m_range = (TimeRange) other.getRange().clone();
// copy the properties
m_properties = new BaseResourcePropertiesEdit();
m_properties.addAll(other.getProperties());
m_access = other.getAccess();
m_groups = new Vector();
m_groups.addAll(other.getGroups());
// copy the attachments
m_attachments = m_entityManager.newReferenceList();
replaceAttachments(other.getAttachments());
// copy the rules
// %%% deep enough? -ggolden
m_singleRule = ((BaseCalendarEventEdit) other).m_singleRule;
m_exclusionRule = ((BaseCalendarEventEdit) other).m_exclusionRule;
} // set
/**
* Take some values from this object (not id, not rules).
*
* @param other
* The other object to take values from.
*/
protected void setPartial(CalendarEvent other)
{
// copy the range
m_range = (TimeRange) other.getRange().clone();
// copy the properties
m_properties = new BaseResourcePropertiesEdit();
m_properties.addAll(other.getProperties());
m_access = other.getAccess();
m_groups = new Vector();
m_groups.addAll(other.getGroups());
// copy the attachments
m_attachments = m_entityManager.newReferenceList();
replaceAttachments(other.getAttachments());
} // setPartial
/**
* Access the time range
*
* @return The event time range
*/
public TimeRange getRange()
{
// range might be null in the creation process, before the fields are set in an edit, but
// after the storage has registered the event and it's id.
if (m_range == null)
{
return m_timeService.newTimeRange(m_timeService.newTime(0));
}
// return (TimeRange) m_range.clone();
return m_range;
} // getRange
/**
* Replace the time range
*
* @param The
* new event time range
*/
public void setRange(TimeRange range)
{
m_range = (TimeRange) range.clone();
} // setRange
/**
* Access the display name property (cover for PROP_DISPLAY_NAME).
*
* @return The event's display name property.
*/
public String getDisplayName()
{
return m_properties.getPropertyFormatted(ResourceProperties.PROP_DISPLAY_NAME);
} // getDisplayName
/**
* Set the display name property (cover for PROP_DISPLAY_NAME).
*
* @param name
* The event's display name property.
*/
public void setDisplayName(String name)
{
m_properties.addProperty(ResourceProperties.PROP_DISPLAY_NAME, name);
} // setDisplayName
/**
* Access the description property as plain text.
*
* @return The event's description property.
*/
public String getDescription()
{
return FormattedText.convertFormattedTextToPlaintext(getDescriptionFormatted());
}
/**
* Access the description property as formatted text.
*
* @return The event's description property.
*/
public String getDescriptionFormatted()
{
// %%% JANDERSE the calendar event description can now be formatted text
// first try to use the formatted text description; if that isn't found, use the plaintext description
String desc = m_properties.getPropertyFormatted(ResourceProperties.PROP_DESCRIPTION + "-html");
if (desc != null && desc.length() > 0) return desc;
desc = m_properties.getPropertyFormatted(ResourceProperties.PROP_DESCRIPTION + "-formatted");
desc = FormattedText.convertOldFormattedText(desc);
if (desc != null && desc.length() > 0) return desc;
desc = FormattedText.convertPlaintextToFormattedText(m_properties
.getPropertyFormatted(ResourceProperties.PROP_DESCRIPTION));
return desc;
} // getDescriptionFormatted()
/**
* Set the description property as plain text.
*
* @param description
* The event's description property.
*/
public void setDescription(String description)
{
setDescriptionFormatted(FormattedText.convertPlaintextToFormattedText(description));
}
/**
* Set the description property as formatted text.
*
* @param description
* The event's description property.
*/
public void setDescriptionFormatted(String description)
{
// %%% JANDERSE the calendar event description can now be formatted text
// save both a formatted and a plaintext version of the description
m_properties.addProperty(ResourceProperties.PROP_DESCRIPTION + "-html", description);
m_properties.addProperty(ResourceProperties.PROP_DESCRIPTION, FormattedText
.convertFormattedTextToPlaintext(description));
} // setDescriptionFormatted()
/**
* Access the type (cover for PROP_CALENDAR_TYPE).
*
* @return The event's type property.
*/
public String getType()
{
return m_properties.getPropertyFormatted(ResourceProperties.PROP_CALENDAR_TYPE);
} // getType
/**
* Set the type (cover for PROP_CALENDAR_TYPE).
*
* @param type
* The event's type property.
*/
public void setType(String type)
{
m_properties.addProperty(ResourceProperties.PROP_CALENDAR_TYPE, type);
} // setType
/**
* Access the location (cover for PROP_CALENDAR_LOCATION).
*
* @return The event's location property.
*/
public String getLocation()
{
return m_properties.getPropertyFormatted(ResourceProperties.PROP_CALENDAR_LOCATION);
} // getLocation
/**
* Gets the recurrence rule, if any.
*
* @return The recurrence rule, or null if none.
*/
public RecurrenceRule getRecurrenceRule()
{
return m_singleRule;
} // getRecurrenceRule
/**
* Gets the exclusion recurrence rule, if any.
*
* @return The exclusionrecurrence rule, or null if none.
*/
public RecurrenceRule getExclusionRule()
{
if (m_exclusionRule == null) m_exclusionRule = new ExclusionSeqRecurrenceRule();
return m_exclusionRule;
} // getExclusionRule
/*
* Return a list of all resolved events generated from this event plus it's recurrence rules that fall within the time range, including this event, possibly empty.
*
* @param range
* The time range bounds for the events returned.
* @return a List (CalendarEvent) of all events and recurrences within the time range, including this, possibly empty.
*/
protected List resolve(TimeRange range)
{
List rv = new Vector();
// for no rules, use the event if it's in range
if (m_singleRule == null)
{
// the actual event
if (range.overlaps(getRange()))
{
rv.add(this);
}
}
// for rules...
else
{
// for a re-occurring event, the time zone where the first event is created
// is passed as a parameter (timezone) to correctly generate the instances
String timeZoneID = this.getField("createdInTimeZone");
TimeZone timezone = null;
if (timeZoneID.equals(""))
{
timezone = m_timeService.getLocalTimeZone();
}
else
{
timezone = TimeZone.getTimeZone(timeZoneID);
}
List instances = m_singleRule.generateInstances(this.getRange(), range, timezone);
// remove any excluded
getExclusionRule().excludeInstances(instances);
for (Iterator iRanges = instances.iterator(); iRanges.hasNext();)
{
RecurrenceInstance ri = (RecurrenceInstance) iRanges.next();
// generate an event object that is exactly like me but with this range and no rules
CalendarEvent clone = new BaseCalendarEventEdit(this, ri);
rv.add(clone);
}
}
return rv;
} // resolve
/**
* Get the value of an "extra" event field.
*
* @param name
* The name of the field.
* @return the value of the "extra" event field.
*/
public String getField(String name)
{
// names are prefixed to form a namespace
name = ResourceProperties.PROP_CALENDAR_EVENT_FIELDS + "." + name;
return m_properties.getPropertyFormatted(name);
} // getField
/**
* Set the value of an "extra" event field.
*
* @param name
* The "extra" field name
* @param value
* The value to set, or null to remove the field.
*/
public void setField(String name, String value)
{
// names are prefixed to form a namespace
name = ResourceProperties.PROP_CALENDAR_EVENT_FIELDS + "." + name;
if (value == null)
{
m_properties.removeProperty(name);
}
else
{
m_properties.addProperty(name, value);
}
} // setField
/**
* Set the location (cover for PROP_CALENDAR_LOCATION).
*
* @param location
* The event's location property.
*/
public void setLocation(String location)
{
m_properties.addProperty(ResourceProperties.PROP_CALENDAR_LOCATION, location);
} // setLocation
/**
* Gets the event creator (userid), if any (cover for PROP_CREATOR).
* @return The event's creator property.
*/
public String getCreator()
{
return m_properties.getProperty(ResourceProperties.PROP_CREATOR);
} // getCreator
/**
* Returns true if current user is thhe event's owner/creator
* @return boolean true or false
*/
public boolean isUserOwner()
{
String currentUser = m_sessionManager.getCurrentSessionUserId();
String eventOwner = this.getCreator();
// for backward compatibility, treat unowned event as if it owned by this user
return (eventOwner == null || eventOwner.equals("") || (currentUser != null && currentUser.equals(eventOwner)) );
}
/**
* Set the event creator (cover for PROP_CREATOR) to current user
*/
public void setCreator()
{
String currentUser = m_sessionManager.getCurrentSessionUserId();
String now = m_timeService.newTime().toString();
m_properties.addProperty(ResourceProperties.PROP_CREATOR, currentUser);
m_properties.addProperty(ResourceProperties.PROP_CREATION_DATE, now);
} // setCreator
/**
* Gets the event modifier (userid), if any (cover for PROP_MODIFIED_BY).
* @return The event's modified-by property.
*/
public String getModifiedBy()
{
return m_properties.getPropertyFormatted(ResourceProperties.PROP_MODIFIED_BY);
} // getModifiedBy
/**
* Set the event modifier (cover for PROP_MODIFIED_BY) to current user
*/
public void setModifiedBy()
{
String currentUser = m_sessionManager.getCurrentSessionUserId();
String now = m_timeService.newTime().toString();
m_properties.addProperty(ResourceProperties.PROP_MODIFIED_BY, currentUser);
m_properties.addProperty(ResourceProperties.PROP_MODIFIED_DATE, now);
} // setModifiedBy
/**
* Sets the recurrence rule.
*
* @param rule
* The recurrence rule, or null to clear out the rule.
*/
public void setRecurrenceRule(RecurrenceRule rule)
{
m_singleRule = rule;
} // setRecurrenceRule
/**
* Sets the exclusion recurrence rule.
*
* @param rule
* The recurrence rule, or null to clear out the rule.
*/
public void setExclusionRule(RecurrenceRule rule)
{
m_exclusionRule = rule;
} // setExclusionRule
/**
* Access the id of the resource.
*
* @return The id.
*/
public String getId()
{
return m_id;
} // getId
/**
* Access the URL which can be used to access the resource.
*
* @return The URL which can be used to access the resource.
*/
public String getUrl()
{
return m_calendar.getUrl() + getId();
} // getUrl
/**
* Access the internal reference which can be used to access the resource from within the system.
*
* @return The the internal reference which can be used to access the resource from within the system.
*/
public String getReference()
{
return eventReference(m_calendar.getContext(), m_calendar.getId(), getId());
} // getReference
/**
* @inheritDoc
*/
public String getReference(String rootProperty)
{
return getReference();
}
/**
* @inheritDoc
*/
public String getUrl(String rootProperty)
{
return getUrl();
}
/**
* Access the event's properties.
*
* @return The event's properties.
*/
public ResourceProperties getProperties()
{
return m_properties;
} // getProperties
/**
* Gets a site name for this calendar event
*/
public String getSiteName()
{
String calendarName = "";
if (m_calendar != null)
{
try
{
Site site = m_siteService.getSite(m_calendar.getContext());
if (site != null)
calendarName = site.getTitle();
}
catch (IdUnusedException e)
{
M_log.warn(".getSiteName(): " + e);
}
}
return calendarName;
}
/**
* Notify the event that it has changed.
*
* @param event
* The event that caused the update.
*/
public void notify(Event event)
{
m_calendar.notify(event);
} // notify
/**
* Compare one event to another, based on range.
*
* @param o
* The object to be compared.
* @return A negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
*/
public int compareTo(Object o)
{
if (!(o instanceof CalendarEvent)) throw new ClassCastException();
Time mine = getRange().firstTime();
Time other = ((CalendarEvent) o).getRange().firstTime();
if (mine.before(other)) return -1;
if (mine.after(other)) return +1;
return 0; // %%% perhaps check the rest of the range if the starts are the same?
}
/**
* Serialize the resource into XML, adding an element to the doc under the top of the stack element.
*
* @param doc
* The DOM doc to contain the XML (or null for a string return).
* @param stack
* The DOM elements, the top of which is the containing element of the new "resource" element.
* @return The newly added element.
*/
public Element toXml(Document doc, Stack stack)
{
Element event = doc.createElement("event");
if (stack.isEmpty())
{
doc.appendChild(event);
}
else
{
((Element) stack.peek()).appendChild(event);
}
stack.push(event);
event.setAttribute("id", getId());
event.setAttribute("range", getRange().toString());
// add access
event.setAttribute("access", m_access.toString());
// add groups
if ((m_groups != null) && (m_groups.size() > 0))
{
for (Iterator i = m_groups.iterator(); i.hasNext();)
{
String group = (String) i.next();
Element sect = doc.createElement("group");
event.appendChild(sect);
sect.setAttribute("authzGroup", group);
}
}
// properties
m_properties.toXml(doc, stack);
if ((m_attachments != null) && (m_attachments.size() > 0))
{
for (int i = 0; i < m_attachments.size(); i++)
{
Reference attch = (Reference) m_attachments.get(i);
Element attachment = doc.createElement("attachment");
event.appendChild(attachment);
attachment.setAttribute("relative-url", attch.getReference());
}
}
// rules
if (m_singleRule != null)
{
Element rules = doc.createElement("rules");
event.appendChild(rules);
stack.push(rules);
// the rule
m_singleRule.toXml(doc, stack);
// the exculsions
if (m_exclusionRule != null)
{
m_exclusionRule.toXml(doc, stack);
}
stack.pop();
}
stack.pop();
return event;
} // toXml
/**
* Access the event code for this edit.
*
* @return The event code for this edit.
*/
protected String getEvent()
{
return m_event;
}
/**
* Set the event code for this edit.
*
* @param event
* The event code for this edit.
*/
protected void setEvent(String event)
{
m_event = event;
}
/**
* Access the resource's properties for modification
*
* @return The resource's properties.
*/
public ResourcePropertiesEdit getPropertiesEdit()
{
return m_properties;
} // getPropertiesEdit
/**
* Enable editing.
*/
protected void activate()
{
m_active = true;
} // activate
/**
* Check to see if the edit is still active, or has already been closed.
*
* @return true if the edit is active, false if it's been closed.
*/
public boolean isActiveEdit()
{
return m_active;
} // isActiveEdit
/**
* Close the edit object - it cannot be used after this.
*/
protected void closeEdit()
{
m_active = false;
} // closeEdit
/******************************************************************************************************************************************************************************************************************************************************
* AttachmentContainer implementation
*****************************************************************************************************************************************************************************************************************************************************/
/**
* Access the attachments of the event.
*
* @return An copy of the set of attachments (a ReferenceVector containing Reference objects) (may be empty).
*/
public List getAttachments()
{
return m_entityManager.newReferenceList(m_attachments);
} // getAttachments
/**
* Add an attachment.
*
* @param ref
* The attachment Reference.
*/
public void addAttachment(Reference ref)
{
m_attachments.add(ref);
} // addAttachment
/**
* Remove an attachment.
*
* @param ref
* The attachment Reference to remove (the one removed will equal this, they need not be ==).
*/
public void removeAttachment(Reference ref)
{
m_attachments.remove(ref);
} // removeAttachment
/**
* Replace the attachment set.
*
* @param attachments
* A vector of Reference objects that will become the new set of attachments.
*/
public void replaceAttachments(List attachments)
{
m_attachments.clear();
if (attachments != null)
{
Iterator it = attachments.iterator();
while (it.hasNext())
{
m_attachments.add(it.next());
}
}
} // replaceAttachments
/**
* Clear all attachments.
*/
public void clearAttachments()
{
m_attachments.clear();
} // clearAttachments
/**
* {@inheritDoc}
*/
public EventAccess getAccess()
{
return m_access;
}
/**
* {@inheritDoc}
*/
public Collection getGroups()
{
return new Vector(m_groups);
}
/**
* {@inheritDoc}
*/
public Collection getGroupObjects()
{
Vector rv = new Vector();
if (m_groups != null)
{
for (Iterator i = m_groups.iterator(); i.hasNext();)
{
String groupId = (String) i.next();
Group group = m_siteService.findGroup(groupId);
if (group != null)
{
rv.add(group);
}
}
}
return rv;
}
/**
* @inheritDoc
*/
public void setGroupAccess(Collection groups, boolean own) throws PermissionException
{
// convenience (and what else are we going to do?)
if ((groups == null) || (groups.size() == 0))
{
clearGroupAccess();
return;
}
// is there any change? If we are already grouped, and the group list is the same, ignore the call
if ((m_access == EventAccess.GROUPED) && (EntityCollections.isEqualEntityRefsToEntities(m_groups, groups))) return;
// isolate any groups that would be removed or added
Collection addedGroups = new Vector();
Collection removedGroups = new Vector();
EntityCollections.computeAddedRemovedEntityRefsFromNewEntitiesOldRefs(addedGroups, removedGroups, groups, m_groups);
// verify that the user has permission to remove
if (removedGroups.size() > 0)
{
// the Group objects the user has remove permission
Collection allowedGroups = m_calendar.getGroupsAllowRemoveEvent(own);
for (Iterator i = removedGroups.iterator(); i.hasNext();)
{
String ref = (String) i.next();
// is ref a group the user can remove from?
if ( !EntityCollections.entityCollectionContainsRefString(allowedGroups, ref) )
{
throw new PermissionException(m_sessionManager.getCurrentSessionUserId(), "access:group:remove", ref);
}
}
}
// verify that the user has permission to add in those contexts
if (addedGroups.size() > 0)
{
// the Group objects the user has add permission
Collection allowedGroups = m_calendar.getGroupsAllowAddEvent();
for (Iterator i = addedGroups.iterator(); i.hasNext();)
{
String ref = (String) i.next();
// is ref a group the user can remove from?
if (!EntityCollections.entityCollectionContainsRefString(allowedGroups, ref))
{
throw new PermissionException(m_sessionManager.getCurrentSessionUserId(), "access:group:add", ref);
}
}
}
// we are clear to perform this
m_access = EventAccess.GROUPED;
EntityCollections.setEntityRefsFromEntities(m_groups, groups);
}
/**
* @inheritDoc
*/
public void clearGroupAccess() throws PermissionException
{
// is there any change? If we are already channel, ignore the call
if (m_access == EventAccess.SITE) return;
// verify that the user has permission to add in the calendar context
boolean allowed = m_calendar.allowAddCalendarEvent();
if (!allowed)
{
throw new PermissionException(m_sessionManager.getCurrentSessionUserId(), "access:channel", getReference());
}
// we are clear to perform this
m_access = EventAccess.SITE;
m_groups.clear();
}
/******************************************************************************************************************************************************************************************************************************************************
* SessionBindingListener implementation
*****************************************************************************************************************************************************************************************************************************************************/
public void valueBound(SessionBindingEvent event)
{
}
public void valueUnbound(SessionBindingEvent event)
{
if (M_log.isDebugEnabled()) M_log.debug("valueUnbound()");
// catch the case where an edit was made but never resolved
if (m_active)
{
m_calendar.cancelEvent(this);
}
} // valueUnbound
/**
* Gets the containing calendar's reference.
*
* @return The containing calendar reference.
*/
public String getCalendarReference()
{
return m_calendar.getReference();
} // getCalendarReference
public String getGroupRangeForDisplay(Calendar cal)
{
// TODO: check this - if used for the UI list, it needs the user's groups and the event's groups... -ggolden
if (m_access.equals(CalendarEvent.EventAccess.SITE))
{
return "";
}
else
{
int count = 0;
String allGroupString="";
try
{
Site site = m_siteService.getSite(cal.getContext());
for (Iterator i= m_groups.iterator(); i.hasNext();)
{
Group aGroup = site.getGroup((String) i.next());
if (aGroup != null)
{
count++;
if (count > 1)
{
allGroupString = allGroupString.concat(", ").concat(aGroup.getTitle());
}
else
{
allGroupString = aGroup.getTitle();
}
}
}
}
catch (IdUnusedException e)
{
// No site available.
}
return allGroupString;
}
}
/**
* Get a content handler suitable for populating this object from SAX events
* @return
*/
public ContentHandler getContentHandler(final Map<String,Object> services)
{
final Entity thisEntity = this;
return new DefaultEntityHandler() {
/* (non-Javadoc)
* @see org.sakaiproject.util.DefaultEntityHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)
*/
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException
{
if ( doStartElement(uri, localName, qName, attributes) ) {
if ( "event".equals(qName) && entity == null ) {
m_id = attributes.getValue("id");
m_range = m_timeService.newTimeRange(attributes
.getValue("range"));
m_access = CalendarEvent.EventAccess.SITE;
String access_str = String.valueOf(attributes
.getValue("access"));
if (access_str.equals(CalendarEvent.EventAccess.GROUPED
.toString()))
m_access = CalendarEvent.EventAccess.GROUPED;
entity = thisEntity;
}
else if ("attachment".equals(qName))
{
m_attachments.add(m_entityManager.newReference(attributes
.getValue("relative-url")));
}
else if ("group".equals(qName))
{
m_groups.add(attributes.getValue("authzGroup"));
}
else if ("rules".equals(qName))
{
// we can ignore this as its a contianer
}
else if ("rule".equals(qName) || "ex-rule".equals(qName))
{
// get the rule name - modern style encoding
String ruleName = StringUtils.trimToNull(attributes.getValue("name"));
// deal with old data
if (ruleName == null)
{
// get the class - this is old CHEF 1.2.10 style encoding
String ruleClassOld = attributes.getValue("class");
// use the last class name minus the package
if ( ruleClassOld != null )
ruleName = ruleClassOld.substring(ruleClassOld.lastIndexOf('.') + 1);
if ( ruleName == null )
M_log.warn("trouble loading rule");
}
if (ruleName != null)
{
// put my package on the class name
String ruleClass = this.getClass().getPackage().getName() + "." + ruleName;
// construct
try
{
if ("rule".equals(qName))
{
m_singleRule = (RecurrenceRule) Class.forName(ruleClass).newInstance();
setContentHandler(m_singleRule.getContentHandler(services), uri, localName, qName, attributes);
}
else // ("ex-rule".equals(qName))
{
m_exclusionRule = (RecurrenceRule) Class.forName(ruleClass).newInstance();
setContentHandler(m_exclusionRule.getContentHandler(services), uri, localName, qName, attributes);
}
}
catch (Exception e)
{
M_log.warn("trouble loading rule: " + ruleClass + " : " + e);
}
}
}
else
{
M_log.warn("Unexpected Element "+qName);
}
}
}
};
}
} // BaseCalendarEvent
/**********************************************************************************************************************************************************************************************************************************************************
* Storage implementation
*********************************************************************************************************************************************************************************************************************************************************/
protected interface Storage
{
/**
* Open and read.
*/
public void open();
/**
* Write and Close.
*/
public void close();
/**
* Return the identified calendar, or null if not found.
*/
public Calendar getCalendar(String ref);
/**
* Return true if the identified calendar exists.
*/
public boolean checkCalendar(String ref);
/**
* Get a list of all calendars
*/
public List getCalendars();
/**
* Keep a new calendar.
*/
public CalendarEdit putCalendar(String ref);
/**
* Get a calendar locked for update
*/
public CalendarEdit editCalendar(String ref);
/**
* Commit a calendar edit.
*/
public void commitCalendar(CalendarEdit edit);
/**
* Cancel a calendar edit.
*/
public void cancelCalendar(CalendarEdit edit);
/**
* Forget about a calendar.
*/
public void removeCalendar(CalendarEdit calendar);
/**
* Get a event from a calendar.
*/
public CalendarEvent getEvent(Calendar calendar, String eventId);
/**
* Get a event from a calendar locked for update
*/
public CalendarEventEdit editEvent(Calendar calendar, String eventId);
/**
* Commit an edit.
*/
public void commitEvent(Calendar calendar, CalendarEventEdit edit);
/**
* Cancel an edit.
*/
public void cancelEvent(Calendar calendar, CalendarEventEdit edit);
/**
* Does this events exist in a calendar?
*/
public boolean checkEvent(Calendar calendar, String eventId);
/**
* Get all events from a calendar
*/
public List getEvents(Calendar calendar);
/**
* Get the events from a calendar, within this time range
*/
public List getEvents(Calendar calendar, long l, long m);
/**
* Make and lock a new event.
*/
public CalendarEventEdit putEvent(Calendar calendar, String id);
/**
* Forget about a event.
*/
public void removeEvent(Calendar calendar, CalendarEventEdit edit);
} // Storage
/**********************************************************************************************************************************************************************************************************************************************************
* CacheRefresher implementation (no container)
*********************************************************************************************************************************************************************************************************************************************************/
/**
* Get a new value for this key whose value has already expired in the cache.
*
* @param key
* The key whose value has expired and needs to be refreshed.
* @param oldValue
* The old exipred value of the key.
* @param event
* The event which triggered this refresh.
* @return a new value for use in the cache for this key; if null, the entry will be removed.
*/
public Object refresh(Object key, Object oldValue, Event event)
{
Object rv = null;
// key is a reference
Reference ref = m_entityManager.newReference((String) key);
// get from storage only (not cache!)
// for events
if (REF_TYPE_EVENT.equals(ref.getSubType()))
{
if (M_log.isDebugEnabled())
M_log.debug("refresh(): key " + key + " calendar id : " + ref.getContext() + "/" + ref.getContainer()
+ " event id : " + ref.getId());
// get calendar (Note: from the cache is ok)
Calendar calendar = findCalendar(calendarReference(ref.getContext(), ref.getContainer()));
// get the CalendarEvent (Note: not from cache! but only from storage)
if (calendar != null)
{
rv = m_storage.getEvent(calendar, ref.getId());
}
}
// for calendar
else
{
if (M_log.isDebugEnabled()) M_log.debug("refresh(): key " + key + " calendar id : " + ref.getReference());
// return the calendar (Note: not from cache! but only from storage)
rv = m_storage.getCalendar(ref.getReference());
}
return rv;
} // refresh
/**********************************************************************************************************************************************************************************************************************************************************
* StorageUser implementation
*********************************************************************************************************************************************************************************************************************************************************/
/**
* Construct a new continer given just an id.
*
* @param ref
* The reference for the new object.
* @return The new containe Resource.
*/
public Entity newContainer(String ref)
{
return new BaseCalendarEdit(ref);
}
/**
* Construct a new container resource, from an XML element.
*
* @param element
* The XML.
* @return The new container resource.
*/
public Entity newContainer(Element element)
{
return new BaseCalendarEdit(element);
}
/**
* Construct a new container resource, as a copy of another
*
* @param other
* The other contianer to copy.
* @return The new container resource.
*/
public Entity newContainer(Entity other)
{
return new BaseCalendarEdit((Calendar) other);
}
/**
* Construct a new rsource given just an id.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param id
* The id for the new object.
* @param others
* (options) array of objects to load into the Resource's fields.
* @return The new resource.
*/
public Entity newResource(Entity container, String id, Object[] others)
{
return new BaseCalendarEventEdit((Calendar) container, id);
}
/**
* Construct a new resource, from an XML element.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param element
* The XML.
* @return The new resource from the XML.
*/
public Entity newResource(Entity container, Element element)
{
return new BaseCalendarEventEdit((Calendar) container, element);
}
/**
* Construct a new resource from another resource of the same type.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param other
* The other resource.
* @return The new resource as a copy of the other.
*/
public Entity newResource(Entity container, Entity other)
{
return new BaseCalendarEventEdit((Calendar) container, (CalendarEvent) other);
}
/**
* Construct a new continer given just an id.
*
* @param ref
* The reference for the new object.
* @return The new containe Resource.
*/
public Edit newContainerEdit(String ref)
{
BaseCalendarEdit rv = new BaseCalendarEdit(ref);
rv.activate();
return rv;
}
/**
* Construct a new container resource, from an XML element.
*
* @param element
* The XML.
* @return The new container resource.
*/
public Edit newContainerEdit(Element element)
{
BaseCalendarEdit rv = new BaseCalendarEdit(element);
rv.activate();
return rv;
}
/**
* Construct a new container resource, as a copy of another
*
* @param other
* The other contianer to copy.
* @return The new container resource.
*/
public Edit newContainerEdit(Entity other)
{
BaseCalendarEdit rv = new BaseCalendarEdit((Calendar) other);
rv.activate();
return rv;
}
/**
* Construct a new rsource given just an id.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param id
* The id for the new object.
* @param others
* (options) array of objects to load into the Resource's fields.
* @return The new resource.
*/
public Edit newResourceEdit(Entity container, String id, Object[] others)
{
BaseCalendarEventEdit rv = new BaseCalendarEventEdit((Calendar) container, id);
rv.activate();
return rv;
}
/**
* Construct a new resource, from an XML element.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param element
* The XML.
* @return The new resource from the XML.
*/
public Edit newResourceEdit(Entity container, Element element)
{
BaseCalendarEventEdit rv = new BaseCalendarEventEdit((Calendar) container, element);
rv.activate();
return rv;
}
/**
* Construct a new resource from another resource of the same type.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param other
* The other resource.
* @return The new resource as a copy of the other.
*/
public Edit newResourceEdit(Entity container, Entity other)
{
BaseCalendarEventEdit rv = new BaseCalendarEventEdit((Calendar) container, (CalendarEvent) other);
rv.activate();
return rv;
}
/**
* Collect the fields that need to be stored outside the XML (for the resource).
*
* @return An array of field values to store in the record outside the XML (for the resource).
*/
public Object[] storageFields(Entity r)
{
Object[] rv = new Object[4];
TimeRange range = ((CalendarEvent) r).getRange();
rv[0] = range.firstTime(); // %%% fudge?
rv[1] = range.lastTime(); // %%% fudge?
// we use hours rather than ms for the range to reduce the index size in the database
// I dont what to use days just incase we want sub day range finds
long oneHour = 60L*60L*1000L;
rv[2] = (int)(range.firstTime().getTime()/oneHour);
rv[3] = (int)(range.lastTime().getTime()/oneHour);
// find the end of the sequence
RecurrenceRuleBase rr = (RecurrenceRuleBase)((CalendarEvent) r).getRecurrenceRule();
if ( rr != null ) {
Time until = rr.getUntil();
if ( until != null ) {
rv[3] = (int)(until.getTime()/oneHour);
} else {
int count = rr.getCount();
int interval = rr.getInterval();
long endevent = range.lastTime().getTime();
if ( count == 0 ) {
rv[3] = Integer.MAX_VALUE-1; // hours since epoch, this represnts 9 Oct 246953 07:00:00
} else {
String frequency = rr.getFrequency();
GregorianCalendar c = new GregorianCalendar();
c.setTimeInMillis(endevent);
c.add(rr.getRecurrenceType(), count*interval);
rv[3] = (int)(c.getTimeInMillis()/oneHour);
}
}
}
return rv;
}
/**
* Check if this resource is in draft mode.
*
* @param r
* The resource.
* @return true if the resource is in draft mode, false if not.
*/
public boolean isDraft(Entity r)
{
return false;
}
/**
* Access the resource owner user id.
*
* @param r
* The resource.
* @return The resource owner user id.
*/
public String getOwnerId(Entity r)
{
return null;
}
/**
* Access the resource date.
*
* @param r
* The resource.
* @return The resource date.
*/
public Time getDate(Entity r)
{
return null;
}
/**********************************************************************************************************************************************************************************************************************************************************
* PDF file generation
*********************************************************************************************************************************************************************************************************************************************************/
// XSL File Names
protected final static String DAY_VIEW_XSLT_FILENAME = "schedule.xsl";
protected final static String LIST_VIEW_XSLT_FILENAME = "schlist.xsl";
protected final static String MONTH_VIEW_XSLT_FILENAME = "schedulemm.xsl";
protected final static String WEEK_VIEW_XSLT_FILENAME = "schedule.xsl";
// FOP Configuration
protected final static String FOP_USERCONFIG = "fonts/userconfig.xml";
protected final static String FOP_FONTBASEDIR = "fonts";
// Mime Types
protected final static String PDF_MIME_TYPE = "application/pdf";
protected final static String ICAL_MIME_TYPE = "text/calendar";
// Constants for time calculations
protected static long MILLISECONDS_IN_DAY = (60 * 60 * 24 * 1000);
protected final static long MILLISECONDS_IN_HOUR = (60 * 60 * 1000);
protected final static long MILLISECONDS_IN_MINUTE = (1000 * 60);
protected static final long MINIMUM_EVENT_LENGTH_IN_MSECONDS = (29 * MILLISECONDS_IN_MINUTE);
protected static final int SCHEDULE_INTERVAL_IN_MINUTES = 15;
protected static final int MAX_OVERLAPPING_COLUMNS = 7;
protected static final int TIMESLOT_FOR_OVERLAP_DETECTION_IN_MINUTES = 10;
// URL Parameter Constants
protected static final String TIME_RANGE_PARAMETER_NAME = "timeRange";
protected static final String DAILY_START_TIME_PARAMETER_NAME = "dailyStartTime";
protected final static String USER_NAME_PARAMETER_NAME = "user";
protected final static String CALENDAR_PARAMETER_BASE_NAME = "calendar";
protected final static String SCHEDULE_TYPE_PARAMETER_NAME = "scheduleType";
// XML Node/Attribute Names
protected static final String COLUMN_NODE_NAME = "col";
protected static final String EVENT_NODE_NAME = "event";
protected static final String FACULTY_EVENT_ATTRIBUTE_NAME = "Faculty";
protected static final String FACULTY_NODE = "faculty";
protected static final String DESCRIPTION_NODE = "description";
protected static final String FROM_ATTRIBUTE_STRING = "from";
protected static final String GROUP_NODE = "grp";
protected static final String LIST_DATE_ATTRIBUTE_NAME = "dt";
protected static final String LIST_DAY_OF_MONTH_ATTRIBUTE_NAME = "dayofmonth";
protected static final String LIST_DAY_OF_WEEK_ATTRIBUTE_NAME = "dayofweek";
protected static final String LIST_NODE_NAME = "list";
protected static final String MONTH_NODE_NAME = "month";
protected static final String MAX_CONCURRENT_EVENTS_NAME = "maxConcurrentEvents";
protected static final String PLACE_NODE = "place";
protected static final String ROW_NODE_NAME = "row";
protected static final String SCHEDULE_NODE = "schedule";
protected static final String START_DAY_WEEK_ATTRIBUTE_NAME = "startdayweek";
protected static final String MONTH_ATTRIBUTE_NAME = "month";
protected static final String YEAR_ATTRIBUTE_NAME = "yyyy";
protected static final String START_TIME_ATTRIBUTE_NAME = "start-time";
protected static final String SUB_EVENT_NODE_NAME = "subEvent";
protected static final String TITLE_NODE = "title";
protected static final String TO_ATTRIBUTE_STRING = "to";
protected static final String TYPE_NODE = "type";
protected static final String UID_NODE = "uid";
// Misc.
protected static final String HOUR_MINUTE_SEPARATOR = ":";
/**
* This is a container for a list of columns, plus the timerange for all the events contained in the row. This time range is a union of all the separate time ranges.
*/
protected class LayoutRow extends ArrayList
{
// Union of all event time ranges in this row.
private TimeRange rowTimeRange;
/**
* Gets the union of all event time ranges in this row.
*/
public TimeRange getRowTimeRange()
{
return rowTimeRange;
}
/**
* Sets the union of all event time ranges in this row.
*/
public void setRowTimeRange(TimeRange range)
{
rowTimeRange = range;
}
}
/**
* Table used to layout a single day, with potentially overlapping events.
*/
protected class SingleDayLayoutTable
{
protected long millisecondsPerTimeslot;
protected int numCols;
protected int numRows;
protected ArrayList rows;
// Overall time range for this table.
protected TimeRange timeRange;
/**
* Constructor for SingleDayLayoutTable
*/
public SingleDayLayoutTable(TimeRange timeRange, int maxNumberOverlappingEvents, int timeslotInMinutes)
{
this.timeRange = timeRange;
numCols = maxNumberOverlappingEvents;
millisecondsPerTimeslot = timeslotInMinutes * MILLISECONDS_IN_MINUTE;
numRows = getNumberOfRowsNeeded(timeRange);
rows = new ArrayList(numRows);
for (int i = 0; i < numRows; i++)
{
ArrayList newRow = new ArrayList(numCols);
rows.add(i, newRow);
for (int j = 0; j < numCols; j++)
{
newRow.add(j, new LayoutTableCell());
}
}
}
/**
* Adds an event to the SingleDayLayoutTable
*/
public void addEvent(CalendarEvent calendarEvent)
{
if (calendarEvent == null)
{
return;
}
int startingRow = getStartingRow(roundRangeToMinimumTimeInterval(calendarEvent.getRange()));
int numRowsNeeded = getNumberOfRowsNeeded(roundRangeToMinimumTimeInterval(calendarEvent.getRange()));
// Trim to the end of the table.
if (startingRow + numRowsNeeded >= getNumRows())
{
numRowsNeeded = getNumRows() - startingRow;
}
// Get the first column that has enough sequential free intervals to
// contain this event.
int columnNumber = getFreeColumn(startingRow, numRowsNeeded);
if (columnNumber != -1)
{
for (int i = startingRow; i < startingRow + numRowsNeeded; i++)
{
LayoutTableCell cell = getCell(i, columnNumber);
// All cells have the calendar event information.
cell.setCalendarEvent(calendarEvent);
// Only the first cell is marked as such.
if (i == startingRow)
{
cell.setFirstCell(true);
}
cell.setFirstCellRow(startingRow);
cell.setFirstCellColumn(columnNumber);
cell.setThisCellRow(i);
cell.setThisCellColumn(columnNumber);
cell.setNumCellsInEvent(numRowsNeeded);
}
}
}
/**
* Convert the time range to fall entirely within the time range of the layout table.
*/
protected TimeRange adjustTimeRangeToLayoutTable(TimeRange eventTimeRange)
{
Time lowerBound = null, upperBound = null;
//
// Make sure that the upper/lower bounds fall within the layout table.
//
if (this.timeRange.firstTime().compareTo(eventTimeRange.firstTime()) > 0)
{
lowerBound = this.timeRange.firstTime();
}
else
{
lowerBound = eventTimeRange.firstTime();
}
if (this.timeRange.lastTime().compareTo(eventTimeRange.lastTime()) < 0)
{
upperBound = this.timeRange.lastTime();
}
else
{
upperBound = eventTimeRange.lastTime();
}
return m_timeService.newTimeRange(lowerBound, upperBound, true, false);
}
/**
* Returns true if there are any events in this or other rows that overlap the event associated with this cell.
*/
protected boolean cellHasOverlappingEvents(int rowNum, int colNum)
{
LayoutTableCell cell = this.getFirstCell(rowNum, colNum);
// Start at the first cell of this event and check every row
// to see if we find any cells in that row that are not empty
// and are not one of ours.
if (cell != null && !cell.isEmptyCell())
{
for (int i = cell.getFirstCellRow(); i < (cell.getFirstCellRow() + cell.getNumCellsInEvent()); i++)
{
for (int j = 0; j < this.numCols; j++)
{
LayoutTableCell curCell = this.getCell(i, j);
if (curCell != null && !curCell.isEmptyCell() && curCell.getCalendarEvent() != cell.getCalendarEvent())
{
return true;
}
}
}
}
return false;
}
/**
* Get a particular cell. Returns a reference to the actual cell and not a copy.
*/
protected LayoutTableCell getCell(int rowNum, int colNum)
{
if (rowNum < 0 || rowNum >= this.numRows || colNum < 0 || colNum >= this.numCols)
{
// Illegal cell indices
return null;
}
else
{
ArrayList row = (ArrayList) rows.get(rowNum);
return (LayoutTableCell) row.get(colNum);
}
}
/**
* Gets the first cell associated with the event that's stored at this row/column
*/
protected LayoutTableCell getFirstCell(int rowNum, int colNum)
{
LayoutTableCell cell = this.getCell(rowNum, colNum);
if (cell == null || cell.isEmptyCell())
{
return null;
}
else
{
return getCell(cell.getFirstCellRow(), cell.getFirstCellColumn());
}
}
/**
* Looks for a column where the whole event can be placed.
*/
protected int getFreeColumn(int rowNum, int numberColumnsNeeded)
{
// Keep going through the columns until we hit one that has
// enough empty cells to accomodate our event.
for (int i = 0; i < this.numCols; i++)
{
boolean foundOccupiedCell = false;
for (int j = rowNum; j < rowNum + numberColumnsNeeded; j++)
{
LayoutTableCell cell = getCell(j, i);
if (cell == null)
{
// Out of range.
return -1;
}
if (!cell.isEmptyCell())
{
foundOccupiedCell = true;
break;
}
}
if (!foundOccupiedCell)
{
return i;
}
}
return -1;
}
/**
* Creates a list of lists of lists. The outer list is a list of rows. Each row is a list of columns. Each column is a list of column values.
*/
public List getLayoutRows()
{
List allRows = new ArrayList();
// Scan all rows in the table.
for (int mainRowIndex = 0; mainRowIndex < this.getNumRows(); mainRowIndex++)
{
// If we hit a starting row, then iterate through all rows of the
// event group.
if (isStartingRowOfGroup(mainRowIndex))
{
LayoutRow newRow = new LayoutRow();
allRows.add(newRow);
int numRowsInGroup = getNumberRowsInEventGroup(mainRowIndex);
newRow.setRowTimeRange(getTimeRangeForEventGroup(mainRowIndex, numRowsInGroup));
for (int columnIndex = 0; columnIndex < this.getNumCols(); columnIndex++)
{
List columnList = new ArrayList();
boolean addedCell = false;
for (int eventGroupRowIndex = mainRowIndex; eventGroupRowIndex < mainRowIndex + numRowsInGroup; eventGroupRowIndex++)
{
LayoutTableCell cell = getCell(eventGroupRowIndex, columnIndex);
if (cell.isFirstCell())
{
columnList.add(cell.getCalendarEvent());
addedCell = true;
}
}
// Don't add to our list unless we actually added a cell.
if (addedCell)
{
newRow.add(columnList);
}
}
// Get ready for the next iteration. Skip those
// rows that we have already processed.
mainRowIndex += (numRowsInGroup - 1);
}
}
return allRows;
}
protected int getNumberOfRowsNeeded(TimeRange eventTimeRange)
{
TimeRange adjustedTimeRange = adjustTimeRangeToLayoutTable(eventTimeRange);
// Use the ceiling function to obtain the next highest integral number of time slots.
return (int) (Math.ceil((double) (adjustedTimeRange.duration()) / (double) millisecondsPerTimeslot));
}
/**
* Gets the number of rows in an event group. This function assumes that the row that it starts on is the starting row of the group.
*/
protected int getNumberRowsInEventGroup(int rowNum)
{
int numEventRows = 0;
if (isStartingRowOfGroup(rowNum))
{
numEventRows++;
// Keep going unless we see an all empty row
// or another starting row.
for (int i = rowNum + 1; i < this.getNumRows() && !isEmptyRow(i) && !isStartingRowOfGroup(i); i++)
{
numEventRows++;
}
}
return numEventRows;
}
/**
* Gets the total number of columns in the layout table.
*/
public int getNumCols()
{
return this.numCols;
}
/**
* Gets the total number of rows in the layout table.
*/
public int getNumRows()
{
return rows.size();
}
/**
* Given a time range, returns the starting row number in the layout table.
*/
protected int getStartingRow(TimeRange eventTimeRange)
{
TimeRange adjustedTimeRange = adjustTimeRangeToLayoutTable(eventTimeRange);
TimeRange timeRangeToStart = m_timeService.newTimeRange(this.timeRange.firstTime(), adjustedTimeRange.firstTime(), true,
true);
//
// We form a new time range where the ending time is the (adjusted) event
// time range and the starting time is the starting time of the layout table.
// The number of rows required for this range will be the starting row of the table.
//
return getNumberOfRowsNeeded(timeRangeToStart);
}
/**
* Returns the earliest/latest times for events in this group. This function assumes that the row that it starts on is the starting row of the group.
*/
public TimeRange getTimeRangeForEventGroup(int rowNum, int numRowsInThisEventGroup)
{
Time firstTime = null;
Time lastTime = null;
for (int i = rowNum; i < rowNum + numRowsInThisEventGroup; i++)
{
for (int j = 0; j < this.getNumCols(); j++)
{
LayoutTableCell cell = getCell(i, j);
CalendarEvent event = cell.getCalendarEvent();
if (event != null)
{
TimeRange adjustedTimeRange = adjustTimeRangeToLayoutTable(roundRangeToMinimumTimeInterval(cell
.getCalendarEvent().getRange()));
//
// Replace our earliest time to date with the
// time from the event, if the time from the
// event is earlier.
//
if (firstTime == null)
{
firstTime = adjustedTimeRange.firstTime();
}
else
{
Time eventFirstTime = adjustedTimeRange.firstTime();
if (eventFirstTime.compareTo(firstTime) < 0)
{
firstTime = eventFirstTime;
}
}
//
// Replace our latest time to date with the
// time from the event, if the time from the
// event is later.
//
if (lastTime == null)
{
lastTime = adjustedTimeRange.lastTime();
}
else
{
Time eventLastTime = adjustedTimeRange.lastTime();
if (eventLastTime.compareTo(lastTime) > 0)
{
lastTime = eventLastTime;
}
}
}
}
}
return m_timeService.newTimeRange(firstTime, lastTime, true, false);
}
/**
* Returns true if this row has only empty cells.
*/
protected boolean isEmptyRow(int rowNum)
{
boolean sawNonEmptyCell = false;
for (int i = 0; i < this.getNumCols(); i++)
{
LayoutTableCell cell = getCell(rowNum, i);
if (!cell.isEmptyCell())
{
sawNonEmptyCell = true;
break;
}
}
return !sawNonEmptyCell;
}
/**
* Returns true if this row has only starting cells and no continuation cells.
*/
protected boolean isStartingRowOfGroup(int rowNum)
{
boolean sawContinuationCells = false;
boolean sawFirstCell = false;
for (int i = 0; i < this.getNumCols(); i++)
{
LayoutTableCell cell = getCell(rowNum, i);
if (cell.isContinuationCell())
{
sawContinuationCells = true;
}
if (cell.isFirstCell)
{
sawFirstCell = true;
}
}
//
// In order to be a starting row must have a "first"
// cell no continuation cells.
//
return (!sawContinuationCells && sawFirstCell);
}
/**
* Returns true if there are any cells in this row associated with events which overlap each other in this row or any other row.
*/
public boolean rowHasOverlappingEvents(int rowNum)
{
for (int i = 0; i < this.getNumCols(); i++)
{
if (cellHasOverlappingEvents(rowNum, i))
{
return true;
}
}
return false;
}
}
/**
* This is a single cell in a layout table (an instance of SingleDayLayoutTable).
*/
protected class LayoutTableCell
{
protected CalendarEvent calendarEvent = null;
protected int firstCellColumn = -1;
protected int firstCellRow = -1;
protected boolean isFirstCell = false;
protected int numCellsInEvent = 0;
protected int thisCellColumn = -1;
protected int thisCellRow = -1;
/**
* Gets the calendar event associated with this cell.
*/
public CalendarEvent getCalendarEvent()
{
return calendarEvent;
}
/**
* Gets the first column associated with this cell.
*/
public int getFirstCellColumn()
{
return firstCellColumn;
}
/**
* Gets the first row associated with this cell.
*/
public int getFirstCellRow()
{
return firstCellRow;
}
/**
* Get the number of cells in this event.
*/
public int getNumCellsInEvent()
{
return numCellsInEvent;
}
/**
* Gets the column associated with this particular cell.
*/
public int getThisCellColumn()
{
return thisCellColumn;
}
/**
* Gets the row associated with this cell.
*/
public int getThisCellRow()
{
return thisCellRow;
}
/**
* Returns true if this cell is a continuation of an event and not the first cell in the event.
*/
public boolean isContinuationCell()
{
return !isFirstCell() && !isEmptyCell();
}
/**
* Returns true if this cell is not associated with any events.
*/
public boolean isEmptyCell()
{
return calendarEvent == null;
}
/**
* Returns true if this is the first cell in a column of cells associated with an event.
*/
public boolean isFirstCell()
{
return isFirstCell;
}
/**
* Set the calendar event associated with this cell.
*/
public void setCalendarEvent(CalendarEvent event)
{
calendarEvent = event;
}
/**
* Set flag indicating that this is the first cell in column of cells associated with an event.
*/
public void setFirstCell(boolean b)
{
isFirstCell = b;
}
/**
* Sets a value in this cell to point to the very first cell in the column of cells associated with this event.
*/
public void setFirstCellColumn(int i)
{
firstCellColumn = i;
}
/**
* Sets a value in this cell to point to the very first cell in the column of cells associated with this event.
*/
public void setFirstCellRow(int i)
{
firstCellRow = i;
}
/**
* Gets the number of cells (if any) in the group of cells associated with this cell by event.
*/
public void setNumCellsInEvent(int i)
{
numCellsInEvent = i;
}
/**
* Sets the actual column index for this cell.
*/
public void setThisCellColumn(int i)
{
thisCellColumn = i;
}
/**
* Sets the actual row index for this cell.
*/
public void setThisCellRow(int i)
{
thisCellRow = i;
}
}
/**
* Debugging routine to get a string for a TimeRange. This should probably be in the TimeRange class.
*/
protected String dumpTimeRange(TimeRange timeRange)
{
String returnString = "";
if (timeRange != null)
{
returnString = timeRange.firstTime().toStringLocalFull() + " - " + timeRange.lastTime().toStringLocalFull();
}
return returnString;
}
/**
* Takes a DOM structure and renders a PDF
*
* @param doc
* DOM structure
* @param xslFileName
* XSL file to use to translate the DOM document to FOP
*/
protected void generatePDF(Document doc, String xslFileName, OutputStream streamOut)
{
Driver driver = new Driver();
org.apache.avalon.framework.logger.Logger logger = new ConsoleLogger(ConsoleLogger.LEVEL_ERROR);
MessageHandler.setScreenLogger(logger);
driver.setLogger(logger);
try {
String baseDir = getClass().getClassLoader().getResource(FOP_FONTBASEDIR).toString();
Configuration.put("fontBaseDir", baseDir);
InputStream userConfig = getClass().getClassLoader().getResourceAsStream(FOP_USERCONFIG);
new Options(userConfig);
}
catch (FOPException fe){
M_log.warn(this+".generatePDF: ", fe);
}
catch(Exception e){
M_log.warn(this+".generatePDF: ", e);
}
driver.setOutputStream(streamOut);
driver.setRenderer(Driver.RENDER_PDF);
try
{
InputStream in = getClass().getClassLoader().getResourceAsStream(xslFileName);
Transformer transformer = transformerFactory.newTransformer(new StreamSource(in));
Source src = new DOMSource(doc);
java.util.Calendar c = java.util.Calendar.getInstance(m_timeService.getLocalTimeZone(),new ResourceLoader().getLocale());
CalendarUtil calUtil = new CalendarUtil(c);
String[] dayNames = calUtil.getCalendarDaysOfWeekNames(true);
// Kludge: Xalan in JDK 1.4/1.5 does not properly resolve java classes
// (http://xml.apache.org/xalan-j/faq.html#jdk14)
// Clean this up in JDK 1.6 and pass ResourceBundle/ArrayList parms
transformer.setParameter("dayNames0", dayNames[0]);
transformer.setParameter("dayNames1", dayNames[1]);
transformer.setParameter("dayNames2", dayNames[2]);
transformer.setParameter("dayNames3", dayNames[3]);
transformer.setParameter("dayNames4", dayNames[4]);
transformer.setParameter("dayNames5", dayNames[5]);
transformer.setParameter("dayNames6", dayNames[6]);
transformer.setParameter("jan", rb.getString("month.jan"));
transformer.setParameter("feb", rb.getString("month.feb"));
transformer.setParameter("mar", rb.getString("month.mar"));
transformer.setParameter("apr", rb.getString("month.apr"));
transformer.setParameter("may", rb.getString("month.may"));
transformer.setParameter("jun", rb.getString("month.jun"));
transformer.setParameter("jul", rb.getString("month.jul"));
transformer.setParameter("aug", rb.getString("month.aug"));
transformer.setParameter("sep", rb.getString("month.sep"));
transformer.setParameter("oct", rb.getString("month.oct"));
transformer.setParameter("nov", rb.getString("month.nov"));
transformer.setParameter("dec", rb.getString("month.dec"));
transformer.setParameter("site", rb.getString("event.site"));
transformer.setParameter("event", rb.getString("event.event"));
transformer.setParameter("location", rb.getString("event.location"));
transformer.setParameter("type", rb.getString("event.type"));
transformer.setParameter("from", rb.getString("event.from"));
transformer.setParameter("sched", rb.getString("sched.for"));
transformer.transform(src, new SAXResult(driver.getContentHandler()));
}
catch (TransformerException e)
{
e.printStackTrace();
M_log.warn(this+".generatePDF(): " + e);
return;
}
}
/**
* Make a full-day time range given a year, month, and day
*/
protected TimeRange getFullDayTimeRangeFromYMD(int year, int month, int day)
{
return m_timeService.newTimeRange(m_timeService.newTimeLocal(year, month, day, 0, 0, 0, 0), m_timeService.newTimeLocal(year,
month, day, 23, 59, 59, 999));
}
/**
* Make a list of days for use in generating an XML document for the list view.
*/
protected List makeListViewTimeRangeList(TimeRange timeRange, List calendarReferenceList)
{
// This is used to dimension a hash table. The default load factor is .75.
// A rehash isn't done until the number of items in the table is .75 * the number
// of items in the capacity.
final int DEFAULT_INITIAL_HASH_CAPACITY = 150;
List listOfDays = new ArrayList();
// Get a list of merged events.
CalendarEventVector calendarEventVector = getEvents(calendarReferenceList, timeRange);
Iterator itEvents = calendarEventVector.iterator();
HashMap datesSeenSoFar = new HashMap(DEFAULT_INITIAL_HASH_CAPACITY);
while (itEvents.hasNext())
{
CalendarEvent event = (CalendarEvent) itEvents.next();
//
// Each event may span multiple days, so we need to split each
// events's time range into single day slots.
//
List timeRangeList = splitTimeRangeIntoListOfSingleDayTimeRanges(event.getRange(), null);
Iterator itDatesInRange = timeRangeList.iterator();
while (itDatesInRange.hasNext())
{
TimeRange curDay = (TimeRange) itDatesInRange.next();
String curDate = curDay.firstTime().toStringLocalDate();
if (!datesSeenSoFar.containsKey(curDate))
{
// Add this day to list
TimeBreakdown startBreakDown = curDay.firstTime().breakdownLocal();
listOfDays.add(getFullDayTimeRangeFromYMD(startBreakDown.getYear(), startBreakDown.getMonth(), startBreakDown
.getDay()));
datesSeenSoFar.put(curDate, "");
}
}
}
return listOfDays;
}
/**
* @param scheduleType
* daily, weekly, monthly, or list (no yearly).
* @param doc
* XML output document
* @param timeRange
* this is the overall time range. For example, for a weekly schedule, it would be the start/end times for the currently selected week period.
* @param dailyTimeRange
* On a weekly time schedule, even if the overall time range is for a week, you're only looking at a portion of the day (e.g., 8 AM to 6 PM, etc.)
* @param userID
* This is the name of the user whose schedule is being printed.
*/
protected void generateXMLDocument(int scheduleType, Document doc, TimeRange timeRange, TimeRange dailyTimeRange,
List calendarReferenceList, String userID)
{
// This list will have an entry for every week day that we care about.
List timeRangeList = null;
TimeRange actualTimeRange = null;
Element topLevelMaxConcurrentEvents = null;
switch (scheduleType)
{
case WEEK_VIEW:
actualTimeRange = timeRange;
timeRangeList = getTimeRangeListForWeek(actualTimeRange, calendarReferenceList, dailyTimeRange);
break;
case MONTH_VIEW:
// Make sure that we trim off the days of the previous and next
// month. The time range that we're being passed is "padded"
// with extra days to make up a full block of an integral number
// of seven day weeks.
actualTimeRange = shrinkTimeRangeToCurrentMonth(timeRange);
timeRangeList = splitTimeRangeIntoListOfSingleDayTimeRanges(actualTimeRange, null);
break;
case LIST_VIEW:
//
// With the list view, we want to come up with a list of days
// that have events, not every day in the range.
//
actualTimeRange = timeRange;
timeRangeList = makeListViewTimeRangeList(actualTimeRange, calendarReferenceList);
break;
case DAY_VIEW:
//
// We have a single entry in the list for a day. Having a singleton
// list may seem wasteful, but it allows us to use one loop below
// for all processing.
//
actualTimeRange = timeRange;
timeRangeList = splitTimeRangeIntoListOfSingleDayTimeRanges(actualTimeRange, dailyTimeRange);
break;
default:
M_log.warn(".generateXMLDocument(): bad scheduleType parameter = " + scheduleType);
break;
}
if (timeRangeList != null)
{
// Create Root Element
Element root = doc.createElement(SCHEDULE_NODE);
if (userID != null)
{
writeStringNodeToDom(doc, root, UID_NODE, userID);
}
// Write out the number of events that we have per timeslot.
// This is used to figure out how to display overlapping events.
// At this level, assume that we start with 1 event.
topLevelMaxConcurrentEvents = writeStringNodeToDom(doc, root, MAX_CONCURRENT_EVENTS_NAME, "1");
// Add a start time node.
writeStringNodeToDom(doc, root, START_TIME_ATTRIBUTE_NAME, getTimeString(dailyTimeRange.firstTime()));
// Add the Root Element to Document
doc.appendChild(root);
//
// Only add a "month" node with the first numeric day
// of the month if we're in the month view.
//
if (scheduleType == MONTH_VIEW)
{
CalendarUtil monthCalendar = new CalendarUtil();
// Use the middle of the month since the start/end ranges
// may be in an adjacent month.
TimeBreakdown breakDown = actualTimeRange.firstTime().breakdownLocal();
monthCalendar.setDay(breakDown.getYear(), breakDown.getMonth(), breakDown.getDay());
int firstDayOfMonth = monthCalendar.getFirstDayOfMonth(breakDown.getMonth() - 1);
// Create a list of events for the given day.
Element monthElement = doc.createElement(MONTH_NODE_NAME);
monthElement.setAttribute(START_DAY_WEEK_ATTRIBUTE_NAME, Integer.toString(firstDayOfMonth));
monthElement.setAttribute(MONTH_ATTRIBUTE_NAME, Integer.toString(breakDown.getMonth()));
monthElement.setAttribute(YEAR_ATTRIBUTE_NAME, Integer.toString(breakDown.getYear()));
root.appendChild(monthElement);
}
Iterator itList = timeRangeList.iterator();
int maxNumberOfColumnsPerRow = 1;
// Go through all the time ranges (days)
while (itList.hasNext())
{
TimeRange currentTimeRange = (TimeRange) itList.next();
int maxConcurrentEventsOverListNode = 1;
// Get a list of merged events.
CalendarEventVector calendarEventVector = getEvents(calendarReferenceList, currentTimeRange);
//
// We don't need to generate "empty" event lists for the list view.
//
if (scheduleType == LIST_VIEW && calendarEventVector.size() == 0)
{
continue;
}
// Create a list of events for the given day.
Element eventList = doc.createElement(LIST_NODE_NAME);
// Set the current date
eventList.setAttribute(LIST_DATE_ATTRIBUTE_NAME, getDateFromTime(currentTimeRange.firstTime()));
eventList.setAttribute(LIST_DAY_OF_MONTH_ATTRIBUTE_NAME, getDayOfMonthFromTime(currentTimeRange.firstTime()));
// Set the maximum number of events per timeslot
// Assume 1 as a starting point. This may be changed
// later on.
eventList.setAttribute(MAX_CONCURRENT_EVENTS_NAME, Integer.toString(maxConcurrentEventsOverListNode));
// Calculate the day of the week.
java.util.Calendar c = java.util.Calendar.getInstance(m_timeService.getLocalTimeZone(),new ResourceLoader().getLocale());
CalendarUtil cal = new CalendarUtil(c);
Time date = currentTimeRange.firstTime();
TimeBreakdown breakdown = date.breakdownLocal();
cal.setDay(breakdown.getYear(), breakdown.getMonth(), breakdown.getDay());
// Set the day of the week as a node attribute.
eventList.setAttribute(LIST_DAY_OF_WEEK_ATTRIBUTE_NAME, Integer.toString(cal.getDay_Of_Week(true) - 1));
// Attach this list to the top-level node
root.appendChild(eventList);
Iterator itEvent = calendarEventVector.iterator();
//
// Day and week views use a layout table to assist in constructing the
// rowspan information for layout.
//
if (scheduleType == DAY_VIEW || scheduleType == WEEK_VIEW)
{
SingleDayLayoutTable layoutTable = new SingleDayLayoutTable(currentTimeRange, MAX_OVERLAPPING_COLUMNS,
SCHEDULE_INTERVAL_IN_MINUTES);
// Load all the events into our layout table.
while (itEvent.hasNext())
{
CalendarEvent event = (CalendarEvent) itEvent.next();
layoutTable.addEvent(event);
}
List layoutRows = layoutTable.getLayoutRows();
Iterator rowIterator = layoutRows.iterator();
// Iterate through the list of rows.
while (rowIterator.hasNext())
{
LayoutRow layoutRow = (LayoutRow) rowIterator.next();
TimeRange rowTimeRange = layoutRow.getRowTimeRange();
if (maxNumberOfColumnsPerRow < layoutRow.size())
{
maxNumberOfColumnsPerRow = layoutRow.size();
}
if (maxConcurrentEventsOverListNode < layoutRow.size())
{
maxConcurrentEventsOverListNode = layoutRow.size();
}
Element eventNode = doc.createElement(EVENT_NODE_NAME);
eventList.appendChild(eventNode);
// Add the "from" time as an attribute.
eventNode.setAttribute(FROM_ATTRIBUTE_STRING, getTimeString(rowTimeRange.firstTime()));
// Add the "to" time as an attribute.
eventNode.setAttribute(TO_ATTRIBUTE_STRING, getTimeString(performEndMinuteKludge(rowTimeRange.lastTime()
.breakdownLocal())));
Element rowNode = doc.createElement(ROW_NODE_NAME);
// Set an attribute indicating the number of columns in this row.
rowNode.setAttribute(MAX_CONCURRENT_EVENTS_NAME, Integer.toString(layoutRow.size()));
eventNode.appendChild(rowNode);
Iterator layoutRowIterator = layoutRow.iterator();
// Iterate through our list of column lists.
while (layoutRowIterator.hasNext())
{
Element columnNode = doc.createElement(COLUMN_NODE_NAME);
rowNode.appendChild(columnNode);
List columnList = (List) layoutRowIterator.next();
Iterator columnListIterator = columnList.iterator();
// Iterate through the list of columns.
while (columnListIterator.hasNext())
{
CalendarEvent event = (CalendarEvent) columnListIterator.next();
generateXMLEvent(doc, columnNode, event, SUB_EVENT_NODE_NAME, rowTimeRange, true, false, false);
}
}
}
}
else
{
// Generate XML for all the events.
while (itEvent.hasNext())
{
CalendarEvent event = (CalendarEvent) itEvent.next();
generateXMLEvent(doc, eventList, event, EVENT_NODE_NAME, currentTimeRange, false, false,
(scheduleType == LIST_VIEW ? true : false));
}
}
// Update this event after having gone through all the rows.
eventList.setAttribute(MAX_CONCURRENT_EVENTS_NAME, Integer.toString(maxConcurrentEventsOverListNode));
}
// Set the node value way up at the head of the document to indicate
// what the maximum number of columns was for the entire document.
topLevelMaxConcurrentEvents.getFirstChild().setNodeValue(Integer.toString(maxNumberOfColumnsPerRow));
}
}
/**
* @param ical
* iCal object
* @param calendarReferenceList
* This is the name of the user whose schedule is being printed.
* @return Number of events generated in ical object
*/
protected int generateICal(net.fortuna.ical4j.model.Calendar ical,
String calendarReference)
{
int numEvents = 0;
// This list will have an entry for every week day that we care about.
TimeRange currentTimeRange = getICalTimeRange();
// Get a list of events.
List calList = new ArrayList();
calList.add(calendarReference);
CalendarEventVector calendarEventVector = getEvents(calList, currentTimeRange);
Iterator itEvent = calendarEventVector.iterator();
// Generate XML for all the events.
while (itEvent.hasNext())
{
CalendarEvent event = (CalendarEvent) itEvent.next();
DateTime icalStartDate = new DateTime(event.getRange().firstTime().getTime());
long seconds = event.getRange().duration() / 1000;
String timeString = "PT" + String.valueOf(seconds) + "S";
net.fortuna.ical4j.model.Dur duration = new net.fortuna.ical4j.model.Dur( timeString );
VEvent icalEvent = new VEvent(icalStartDate, duration, event.getDisplayName() );
net.fortuna.ical4j.model.parameter.TzId tzId = new net.fortuna.ical4j.model.parameter.TzId( m_timeService.getLocalTimeZone().getID() );
icalEvent.getProperty(Property.DTSTART).getParameters().add(tzId);
icalEvent.getProperty(Property.DTSTART).getParameters().add(Value.DATE_TIME);
icalEvent.getProperties().add(new Uid(event.getId()));
// build the description, adding links to attachments if necessary
StringBuffer description = new StringBuffer("");
if ( event.getDescription() != null && !event.getDescription().equals("") )
description.append(event.getDescription());
List attachments = event.getAttachments();
if(attachments != null){
for (Iterator iter = attachments.iterator(); iter.hasNext();) {
Reference attachment = (Reference) iter.next();
description.append("\n");
description.append(attachment.getUrl());
description.append("\n");
}
}
if(description.length() > 0) {
//Replace \r with \n
icalEvent.getProperties().add(new Description(description.toString().replace('\r', '\n')));
}
if ( event.getLocation() != null && !event.getLocation().equals("") )
icalEvent.getProperties().add(new Location(event.getLocation()));
try
{
String organizer = m_userDirectoryService.getUser( event.getCreator() ).getDisplayName();
organizer = organizer.replaceAll(" ","%20"); // get rid of illegal URI characters
icalEvent.getProperties().add(new Organizer(new URI("CN="+organizer)));
}
catch (UserNotDefinedException e) {} // ignore
catch (URISyntaxException e) {} // ignore
StringBuffer comment = new StringBuffer(event.getType());
comment.append(" (");
comment.append(event.getSiteName());
comment.append(")");
icalEvent.getProperties().add(new Comment(comment.toString()));
ical.getComponents().add( icalEvent );
numEvents++;
/* TBD: add to VEvent: recurring schedule, ...
RecurenceRUle x = event.getRecurrenceRule();
*/
}
return numEvents;
}
/* Given a current date via the calendarUtil paramter, returns a TimeRange for the year,
* 6 months either side of the current date. (calculate milleseconds in 6 months)
*/
private static long SIX_MONTHS = (long)1000 * (long)60 * (long)60 * (long)24 * (long)183;
public TimeRange getICalTimeRange()
{
Time now = m_timeService.newTime();
Time startTime = m_timeService.newTime( now.getTime() - SIX_MONTHS );
Time endTime = m_timeService.newTime( now.getTime() + SIX_MONTHS );
return m_timeService.newTimeRange(startTime,endTime,true,true);
}
/**
* Trim the range that is passed in to the containing time range.
*/
protected TimeRange trimTimeRange(TimeRange containingRange, TimeRange rangeToTrim)
{
long containingRangeStartTime = containingRange.firstTime().getTime();
long containingRangeEndTime = containingRange.lastTime().getTime();
long rangeToTrimStartTime = rangeToTrim.firstTime().getTime();
long rangeToTrimEndTime = rangeToTrim.lastTime().getTime();
long trimmedStartTime = 0, trimmedEndTime = 0;
trimmedStartTime = Math.min(Math.max(containingRangeStartTime, rangeToTrimStartTime), containingRangeEndTime);
trimmedEndTime = Math.max(Math.min(containingRangeEndTime, rangeToTrimEndTime), rangeToTrimStartTime);
return m_timeService.newTimeRange(m_timeService.newTime(trimmedStartTime), m_timeService.newTime(trimmedEndTime), true, false);
}
/**
* Rounds a time range up to a minimum interval.
*/
protected TimeRange roundRangeToMinimumTimeInterval(TimeRange timeRange)
{
TimeRange roundedTimeRange = timeRange;
if (timeRange.duration() < MINIMUM_EVENT_LENGTH_IN_MSECONDS)
{
roundedTimeRange = m_timeService.newTimeRange(timeRange.firstTime().getTime(), MINIMUM_EVENT_LENGTH_IN_MSECONDS);
}
return roundedTimeRange;
}
/**
* Generates the XML for an event.
*/
protected void generateXMLEvent(Document doc, Element parent, CalendarEvent event, String eventNodeName,
TimeRange containingTimeRange, boolean forceMinimumTime, boolean hideGroupIfNoSpace, boolean performEndTimeKludge)
{
Element eventElement = doc.createElement(eventNodeName);
TimeRange trimmedTimeRange = trimTimeRange(containingTimeRange, event.getRange());
// Optionally force the event to have a minimum time slot.
if (forceMinimumTime)
{
trimmedTimeRange = roundRangeToMinimumTimeInterval(trimmedTimeRange);
}
// Add the "from" time as an attribute.
eventElement.setAttribute(FROM_ATTRIBUTE_STRING, getTimeString(trimmedTimeRange.firstTime()));
// Add the "to" time as an attribute.
Time endTime = null;
// Optionally adjust the end time
if (performEndTimeKludge)
{
endTime = performEndMinuteKludge(trimmedTimeRange.lastTime().breakdownLocal());
}
else
{
endTime = trimmedTimeRange.lastTime();
}
eventElement.setAttribute(TO_ATTRIBUTE_STRING, getTimeString(endTime));
//
// Add the group (really "site") node
// Provide that we have space or if we've been told we need to display it.
//
if (!hideGroupIfNoSpace || trimmedTimeRange.duration() > MINIMUM_EVENT_LENGTH_IN_MSECONDS)
{
writeStringNodeToDom(doc, eventElement, GROUP_NODE, event.getSiteName());
}
// Add the display name node.
writeStringNodeToDom(doc, eventElement, TITLE_NODE, event.getDisplayName());
// Add the event type node.
writeStringNodeToDom(doc, eventElement, TYPE_NODE, getEventDescription(event.getType()));
// Add the place/location node.
writeStringNodeToDom(doc, eventElement, PLACE_NODE, event.getLocation());
// If a "Faculty" extra field is present, then add the node.
writeStringNodeToDom(doc, eventElement, FACULTY_NODE, event.getField(FACULTY_EVENT_ATTRIBUTE_NAME));
// If a "Description" field is present, then add the node.
writeStringNodeToDom(doc, eventElement, DESCRIPTION_NODE, event.getDescription());
parent.appendChild(eventElement);
}
protected String getEventDescription(String type){
ResourceLoader rl = new ResourceLoader("calendar");
if ((type!=null) && (type.trim()!="")){
if (type.equals("Academic Calendar"))
return rl.getString("legend.key1");
else if (type.equals("Activity"))
return rl.getString("legend.key2");
else if (type.equals("Cancellation"))
return rl.getString("legend.key3");
else if (type.equals("Class section - Discussion"))
return rl.getString("legend.key4");
else if (type.equals("Class section - Lab"))
return rl.getString("legend.key5");
else if (type.equals("Class section - Lecture"))
return rl.getString("legend.key6");
else if (type.equals("Class section - Small Group"))
return rl.getString("legend.key7");
else if (type.equals("Class session"))
return rl.getString("legend.key8");
else if (type.equals("Computer Session"))
return rl.getString("legend.key9");
else if (type.equals("Deadline"))
return rl.getString("legend.key10");
else if (type.equals("Exam"))
return rl.getString("legend.key11");
else if (type.equals("Meeting"))
return rl.getString("legend.key12");
else if (type.equals("Multidisciplinary Conference"))
return rl.getString("legend.key13");
else if (type.equals("Quiz"))
return rl.getString("legend.key14");
else if (type.equals("Special event"))
return rl.getString("legend.key15");
else if (type.equals("Web Assignment"))
return rl.getString("legend.key16");
else if (type.equals("Teletutoria"))
return rl.getString("legend.key17");
else
return rl.getString("legend.key2");
}else{
return rl.getString("legend.key2");
}
}
/*
* Gets the daily start time parameter from a Properties object filled from URL parameters.
*/
protected TimeRange getDailyStartTimeFromParameters(Properties parameters)
{
return getTimeRangeParameterByName(parameters, DAILY_START_TIME_PARAMETER_NAME);
}
/**
* Gets the standard date string from the time parameter
*/
protected String getDateFromTime(Time time)
{
TimeBreakdown timeBreakdown = time.breakdownLocal();
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT,rb.getLocale());
return dateFormat.format(new Date(time.getTime()));
}
protected String getDayOfMonthFromTime(Time time)
{
TimeBreakdown timeBreakdown = time.breakdownLocal();
return Integer.toString(timeBreakdown.getDay());
}
/**
* Gets the schedule type from a Properties object (filled from a URL parameter list).
*/
protected int getScheduleTypeFromParameterList(Properties parameters)
{
int scheduleType = UNKNOWN_VIEW;
// Get the type of schedule (daily, weekly, etc.)
String scheduleTypeString = (String) parameters.get(SCHEDULE_TYPE_PARAMETER_NAME);
scheduleType = Integer.parseInt(scheduleTypeString);
return scheduleType;
}
/**
* Access some named configuration value as a string.
*
* @param name
* The configuration value name.
* @param dflt
* The value to return if not found.
* @return The configuration value with this name, or the default value if not found.
*/
protected String getString(String name, String dflt)
{
return m_serverConfigurationService.getString(name, dflt);
}
/*
* Gets the time range parameter from a Properties object filled from URL parameters.
*/
protected TimeRange getTimeRangeFromParameters(Properties parameters)
{
return getTimeRangeParameterByName(parameters, TIME_RANGE_PARAMETER_NAME);
}
/**
* Generates a list of time ranges for a week. Each range in the list is a day.
*
* @param timeRange start & end date range
* @param calendarReferenceList list of calendar(s)
* @param dailyTimeRange start and end hour/minute time range
*/
protected ArrayList getTimeRangeListForWeek(TimeRange timeRange, List calendarReferenceList, TimeRange dailyTimeRange)
{
TimeBreakdown startBreakdown = timeRange.firstTime().breakdownLocal();
GregorianCalendar startCalendarDate = (GregorianCalendar)GregorianCalendar.getInstance(m_timeService.getLocalTimeZone(), rb.getLocale());
startCalendarDate.set(startBreakdown.getYear(), startBreakdown.getMonth() - 1, startBreakdown.getDay(), 0, 0, 0);
ArrayList weekDayTimeRanges = new ArrayList();
TimeBreakdown startBreakDown = dailyTimeRange.firstTime().breakdownLocal();
TimeBreakdown endBreakDown = dailyTimeRange.lastTime().breakdownLocal();
// Search all seven weekdays
// Note: no assumption can be made regarding the first day being Sunday,
// since in some locales, the first weekday is Monday.
for (int i = 0; i <= 6; i++)
{
//
// Use the same start/end times for all days.
//
Time curStartTime = m_timeService.newTimeLocal(startCalendarDate.get(GregorianCalendar.YEAR), startCalendarDate
.get(GregorianCalendar.MONTH) + 1, startCalendarDate.get(GregorianCalendar.DAY_OF_MONTH), startBreakDown
.getHour(), startBreakDown.getMin(), startBreakDown.getSec(), startBreakDown.getMs());
Time curEndTime = m_timeService.newTimeLocal(startCalendarDate.get(GregorianCalendar.YEAR), startCalendarDate
.get(GregorianCalendar.MONTH) + 1, startCalendarDate.get(GregorianCalendar.DAY_OF_MONTH), endBreakDown
.getHour(), endBreakDown.getMin(), endBreakDown.getSec(), endBreakDown.getMs());
TimeRange newTimeRange = m_timeService.newTimeRange(curStartTime, curEndTime, true, false);
weekDayTimeRanges.add(newTimeRange);
// Move to the next day.
startCalendarDate.add(GregorianCalendar.DATE, 1);
}
return weekDayTimeRanges;
}
/**
* Utility routine to get a time range parameter from the URL parameters store in a Properties object.
*/
protected TimeRange getTimeRangeParameterByName(Properties parameters, String name)
{
// Now get the time range.
String timeRangeString = (String) parameters.get(name);
TimeRange timeRange = null;
timeRange = m_timeService.newTimeRange(timeRangeString);
return timeRange;
}
/**
* Gets a standard time string give the time parameter.
*/
protected String getTimeString(Time time)
{
TimeBreakdown timeBreakdown = time.breakdownLocal();
DecimalFormat twoDecimalDigits = new DecimalFormat("00");
return timeBreakdown.getHour() + HOUR_MINUTE_SEPARATOR + twoDecimalDigits.format(timeBreakdown.getMin());
}
/**
* Given a schedule type, the appropriate XSLT file is returned
*/
protected String getXSLFileNameForScheduleType(int scheduleType)
{
// get a relative path to the file
String baseFileName = "";
switch (scheduleType)
{
case WEEK_VIEW:
baseFileName = WEEK_VIEW_XSLT_FILENAME;
break;
case DAY_VIEW:
baseFileName = DAY_VIEW_XSLT_FILENAME;
break;
case MONTH_VIEW:
baseFileName = MONTH_VIEW_XSLT_FILENAME;
break;
case LIST_VIEW:
baseFileName = LIST_VIEW_XSLT_FILENAME;
break;
default:
M_log.debug("PrintFileGeneration.getXSLFileNameForScheduleType(): unexpected scehdule type = " + scheduleType);
break;
}
return baseFileName;
}
/**
* This routine is used to round the end time. The time is stored at one minute less than the actual end time,
* but the user will expect to see the end time on the hour. For example, an event that ends at 10:00 is
* actually stored at 9:59. This code should really be in a central place so that the velocity template can see it as well.
*/
protected Time performEndMinuteKludge(TimeBreakdown breakDown)
{
int endMin = breakDown.getMin();
int endHour = breakDown.getHour();
int tmpMinVal = endMin % TIMESLOT_FOR_OVERLAP_DETECTION_IN_MINUTES;
if (tmpMinVal == 4 || tmpMinVal == 9)
{
endMin = endMin + 1;
if (endMin == 60)
{
endMin = 00;
endHour = endHour + 1;
}
}
return m_timeService.newTimeLocal(breakDown.getYear(), breakDown.getMonth(), breakDown.getDay(), endHour, endMin, breakDown
.getSec(), breakDown.getMs());
}
protected List getCalendarReferenceList()
throws PermissionException
{
// Get the list of calendars.from user session
List calendarReferenceList = (List)m_sessionManager.getCurrentSession().getAttribute(SESSION_CALENDAR_LIST);
// check if there is any calendar to which the user has acces
Iterator it = calendarReferenceList.iterator();
int permissionCount = calendarReferenceList.size();
while (it.hasNext())
{
String calendarReference = (String) it.next();
try
{
getCalendar(calendarReference);
}
catch (IdUnusedException e)
{
continue;
}
catch (PermissionException e)
{
permissionCount--;
continue;
}
}
// if no permission to any of the calendars, throw exception and do nothing
// the expection will be caught by AccessServlet.doPrintingRequest()
if (permissionCount == 0)
{
throw new PermissionException("", "", "");
}
return calendarReferenceList;
}
protected void printICalSchedule(String calRef, OutputStream os)
throws PermissionException
{
// generate iCal text file
net.fortuna.ical4j.model.Calendar ical = new net.fortuna.ical4j.model.Calendar();
ical.getProperties().add(new ProdId("-//SakaiProject//iCal4j 1.0//EN"));
ical.getProperties().add(Version.VERSION_2_0);
ical.getProperties().add(CalScale.GREGORIAN);
TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry();
TzId tzId = new TzId( m_timeService.getLocalTimeZone().getID() );
ical.getComponents().add(registry.getTimeZone(tzId.getValue()).getVTimeZone());
CalendarOutputter icalOut = new CalendarOutputter();
int numEvents = generateICal(ical, calRef);
try
{
if ( numEvents > 0 )
icalOut.output( ical, os );
}
catch (Exception e)
{
M_log.warn(".printICalSchedule(): ", e);
}
}
/**
* Called by the servlet to service a get/post requesting a calendar in PDF format.
*/
protected void printSchedule(Properties parameters, OutputStream os) throws PermissionException
{
// Get the user name.
String userName = (String) parameters.get(USER_NAME_PARAMETER_NAME);
// Get the list of calendars.from user session
List calendarReferenceList = getCalendarReferenceList();
// Get the type of schedule (daily, weekly, etc.)
int scheduleType = getScheduleTypeFromParameterList(parameters);
// Now get the time range.
TimeRange timeRange = getTimeRangeFromParameters(parameters);
Document document = docBuilder.newDocument();
generateXMLDocument(scheduleType, document, timeRange, getDailyStartTimeFromParameters(parameters),
calendarReferenceList, userName);
generatePDF(document, getXSLFileNameForScheduleType(scheduleType), os);
}
/**
* The time ranges that we get from the CalendarAction class have days in the week of the first and last weeks padded out to make a full week. This function will shrink this range to only one month.
*/
protected TimeRange shrinkTimeRangeToCurrentMonth(TimeRange expandedTimeRange)
{
long millisecondsInWeek = (7 * MILLISECONDS_IN_DAY);
Time startTime = expandedTimeRange.firstTime();
// Grab something in the middle of the time range so that we know that we're
// in the right month.
Time somewhereInTheMonthTime = m_timeService.newTime(startTime.getTime() + 2 * millisecondsInWeek);
TimeBreakdown somewhereInTheMonthBreakdown = somewhereInTheMonthTime.breakdownLocal();
CalendarUtil calendar = new CalendarUtil();
calendar.setDay(somewhereInTheMonthBreakdown.getYear(), somewhereInTheMonthBreakdown.getMonth(),
somewhereInTheMonthBreakdown.getDay());
int numDaysInMonth = calendar.getNumberOfDays();
//
// Construct a new time range starting on the first day of the month and ending on
// the last day at one millisecond before midnight.
//
return m_timeService.newTimeRange(m_timeService.newTimeLocal(somewhereInTheMonthBreakdown.getYear(),
somewhereInTheMonthBreakdown.getMonth(), 1, 0, 0, 0, 0), m_timeService.newTimeLocal(somewhereInTheMonthBreakdown
.getYear(), somewhereInTheMonthBreakdown.getMonth(), numDaysInMonth, 23, 59, 59, 999));
}
/**
* Calculate the number of days in a range of time given two dates.
*
* @param startMonth
* (zero based, 0-11)
* @param startDay
* (one based, 1-31)
* @param endYear
* (one based, 1-31)
* @param endMonth
* (zero based, 0-11
*/
protected long getNumberDaysGivenTwoDates(int startYear, int startMonth, int startDay, int endYear, int endMonth, int endDay)
{
GregorianCalendar startDate = new GregorianCalendar();
GregorianCalendar endDate = new GregorianCalendar();
startDate.set(startYear, startMonth, startDay, 0, 0, 0);
endDate.set(endYear, endMonth, endDay, 0, 0, 0);
long duration = endDate.getTime().getTime() - startDate.getTime().getTime();
// Allow for daylight savings time.
return ((duration + MILLISECONDS_IN_HOUR) / (24 * MILLISECONDS_IN_HOUR)) + 1;
}
/**
* Returns a list of daily time ranges for every day in a range.
*
* @param timeRange
* overall time range
* @param dailyTimeRange
* representative daily time range (start hour/minute, end hour/minute). If null, this parameter is ignored.
*/
protected ArrayList splitTimeRangeIntoListOfSingleDayTimeRanges(TimeRange timeRange, TimeRange dailyTimeRange)
{
TimeBreakdown startBreakdown = timeRange.firstTime().breakdownLocal();
TimeBreakdown endBreakdown = timeRange.lastTime().breakdownLocal();
GregorianCalendar startCalendarDate = new GregorianCalendar();
startCalendarDate.set(startBreakdown.getYear(), startBreakdown.getMonth() - 1, startBreakdown.getDay(), 0, 0, 0);
long numDaysInTimeRange = getNumberDaysGivenTwoDates(startBreakdown.getYear(), startBreakdown.getMonth() - 1,
startBreakdown.getDay(), endBreakdown.getYear(), endBreakdown.getMonth() - 1, endBreakdown.getDay());
ArrayList splitTimeRanges = new ArrayList();
TimeBreakdown dailyStartBreakDown = null;
TimeBreakdown dailyEndBreakDown = null;
if (dailyTimeRange != null)
{
dailyStartBreakDown = dailyTimeRange.firstTime().breakdownLocal();
dailyEndBreakDown = dailyTimeRange.lastTime().breakdownLocal();
}
for (long i = 0; i < numDaysInTimeRange; i++)
{
Time curStartTime = null;
Time curEndTime = null;
if (dailyTimeRange != null)
{
//
// Use the same start/end times for all days.
//
curStartTime = m_timeService.newTimeLocal(startCalendarDate.get(GregorianCalendar.YEAR), startCalendarDate
.get(GregorianCalendar.MONTH) + 1, startCalendarDate.get(GregorianCalendar.DAY_OF_MONTH),
dailyStartBreakDown.getHour(), dailyStartBreakDown.getMin(), dailyStartBreakDown.getSec(),
dailyStartBreakDown.getMs());
curEndTime = m_timeService.newTimeLocal(startCalendarDate.get(GregorianCalendar.YEAR), startCalendarDate
.get(GregorianCalendar.MONTH) + 1, startCalendarDate.get(GregorianCalendar.DAY_OF_MONTH), dailyEndBreakDown
.getHour(), dailyEndBreakDown.getMin(), dailyEndBreakDown.getSec(), dailyEndBreakDown.getMs());
splitTimeRanges.add(m_timeService.newTimeRange(curStartTime, curEndTime, true, false));
}
else
{
//
// Add a full day range since no start/stop time was specified.
//
splitTimeRanges.add(getFullDayTimeRangeFromYMD(startCalendarDate.get(GregorianCalendar.YEAR), startCalendarDate
.get(GregorianCalendar.MONTH) + 1, startCalendarDate.get(GregorianCalendar.DAY_OF_MONTH)));
}
// Move to the next day.
startCalendarDate.add(GregorianCalendar.DATE, 1);
}
return splitTimeRanges;
}
/**
* Utility routine to write a string node to the DOM.
*/
protected Element writeStringNodeToDom(Document doc, Element parent, String nodeName, String nodeValue)
{
if (nodeValue != null && nodeValue.length() != 0)
{
Element name = doc.createElement(nodeName);
name.appendChild(doc.createTextNode(nodeValue));
parent.appendChild(name);
return name;
}
return null;
}
/**
** Internal class for resolving stylesheet URIs
**/
protected class MyURIResolver implements URIResolver
{
ClassLoader classLoader = null;
/**
** Constructor: use BaseCalendarService ClassLoader
**/
public MyURIResolver( ClassLoader classLoader )
{
this.classLoader = classLoader;
}
/**
** Resolve XSLT pathnames invoked within stylesheet (e.g. xsl:import)
** using ClassLoader.
**
** @param href href attribute of XSLT file
** @param base base URI in affect when href attribute encountered
** @return Source object for requested XSLT file
**/
public Source resolve( String href, String base )
throws TransformerException
{
InputStream in = classLoader.getResourceAsStream(href);
return (Source)(new StreamSource(in));
}
}
/**
* Get a DefaultHandler so that the StorageUser here can parse using SAX events.
*
* @see org.sakaiproject.util.SAXEntityReader#getDefaultHandler()
*/
public DefaultEntityHandler getDefaultHandler(final Map<String,Object> services)
{
return new DefaultEntityHandler()
{
/*
* (non-Javadoc)
*
* @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String,
* java.lang.String, java.lang.String, org.xml.sax.Attributes)
*/
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException
{
if (doStartElement(uri, localName, qName, attributes))
{
if (entity == null)
{
if ("calendar".equals(qName))
{
BaseCalendarEdit bce = new BaseCalendarEdit();
entity = bce;
setContentHandler(bce.getContentHandler(services), uri, localName,
qName, attributes);
}
else if ("event".equals(qName))
{
BaseCalendarEventEdit bcee = new BaseCalendarEventEdit(
container);
entity = bcee;
setContentHandler(bcee.getContentHandler(services), uri, localName,
qName, attributes);
} else {
M_log.warn("Unexpected Element in XML ["+qName+"]");
}
}
}
}
};
}
/* (non-Javadoc)
* @see org.sakaiproject.util.SAXEntityReader#getServices()
*/
public Map<String, Object> getServices()
{
if ( m_services == null ) {
m_services = new HashMap<String, Object>();
m_services.put("timeservice", m_timeService);
}
return m_services;
}
public void setServices(Map<String,Object> services) {
m_services = services;
}
public void transferCopyEntities(String fromContext, String toContext, List ids, boolean cleanup)
{
transferCopyEntitiesRefMigrator(fromContext, toContext, ids, cleanup);
}
public Map<String, String> transferCopyEntitiesRefMigrator(String fromContext, String toContext, List ids, boolean cleanup)
{
Map<String, String> transversalMap = new HashMap<String, String>();
try
{
if(cleanup == true)
{
String toSiteId = toContext;
String calendarId = calendarReference(toSiteId, SiteService.MAIN_CONTAINER);
Calendar calendarObj = getCalendar(calendarId);
List calEvents = calendarObj.getEvents(null,null);
for (int i = 0; i < calEvents.size(); i++)
{
try
{
CalendarEvent ce = (CalendarEvent) calEvents.get(i);
calendarObj.removeEvent(calendarObj.getEditEvent(ce.getId(), CalendarService.EVENT_REMOVE_CALENDAR));
CalendarEventEdit edit = calendarObj.getEditEvent(ce.getId(), org.sakaiproject.calendar.api.CalendarService.EVENT_REMOVE_CALENDAR);
calendarObj.removeEvent(edit);
calendarObj.commitEvent(edit);
}
catch (IdUnusedException e)
{
M_log.debug(".IdUnusedException " + e);
}
catch (PermissionException e)
{
M_log.debug(".PermissionException " + e);
}
catch (InUseException e)
{
M_log.debug(".InUseException delete" + e);
}
}
}
transversalMap.putAll(transferCopyEntitiesRefMigrator(fromContext, toContext, ids));
}
catch (Exception e)
{
M_log.info("importSiteClean: End removing Calendar data" + e);
}
return transversalMap;
}
/**
** Comparator for sorting Group objects
**/
private class GroupComparator implements Comparator {
public int compare(Object o1, Object o2) {
return ((Group)o1).getTitle().compareToIgnoreCase( ((Group)o2).getTitle() );
}
}
} // BaseCalendarService
|
SAK-22283 iSyllabus linking and link migration
Subtask: SAK-23041 Link Migration Improvements
git-svn-id: 04d4787a8f5c2a5245f79294070475605a4425d0@118096 66ffb92e-73f9-0310-93c1-f5514f145a0a
|
calendar/calendar-impl/impl/src/java/org/sakaiproject/calendar/impl/BaseCalendarService.java
|
SAK-22283 iSyllabus linking and link migration Subtask: SAK-23041 Link Migration Improvements
|
<ide><path>alendar/calendar-impl/impl/src/java/org/sakaiproject/calendar/impl/BaseCalendarService.java
<ide> import org.sakaiproject.util.Validator;
<ide> import org.sakaiproject.util.Web;
<ide> import org.sakaiproject.util.Xml;
<add>import org.sakaiproject.util.LinkMigrationHelper;
<ide> import org.w3c.dom.Document;
<ide> import org.w3c.dom.Element;
<ide> import org.w3c.dom.Node;
<ide> CalendarEvent ce = (CalendarEvent) calEvents.get(i);
<ide> String msgBodyFormatted = ce.getDescriptionFormatted();
<ide> boolean updated = false;
<add>/*
<ide> Iterator<Entry<String, String>> entryItr = entrySet.iterator();
<ide> while(entryItr.hasNext()) {
<ide> Entry<String, String> entry = (Entry<String, String>) entryItr.next();
<ide> updated = true;
<ide> }
<ide> }
<del> if(updated){
<add>*/
<add> StringBuffer msgBodyPreMigrate = new StringBuffer(msgBodyFormatted);
<add> msgBodyFormatted = LinkMigrationHelper.editLinks(msgBodyFormatted, "sam_pub");
<add> msgBodyFormatted = LinkMigrationHelper.editLinks(msgBodyFormatted, "/posts/");
<add> msgBodyFormatted = LinkMigrationHelper.miagrateAllLinks(entrySet, msgBodyFormatted);
<add> if(!msgBodyFormatted.equals(msgBodyPreMigrate.toString())){
<add>
<add>// if(updated){
<ide> CalendarEventEdit edit = calendarObj.getEditEvent(ce.getId(), org.sakaiproject.calendar.api.CalendarService.EVENT_MODIFY_CALENDAR);
<ide> edit.setDescriptionFormatted(msgBodyFormatted);
<ide> calendarObj.commitEvent(edit);
|
|
Java
|
mit
|
ac999a8d5f4cbc5d0b8914676fa715e0eb3c5d49
| 0 |
rafalmag/EV3-projects
|
package lejos.hardware.ev3;
import java.util.ArrayList;
import lejos.hardware.Battery;
import lejos.hardware.lcd.Font;
import lejos.hardware.lcd.GraphicsLCD;
import lejos.hardware.lcd.TextLCD;
import lejos.hardware.port.Port;
import lejos.internal.ev3.EV3DeviceManager;
import lejos.internal.ev3.EV3GraphicsLCD;
import lejos.internal.ev3.EV3Port;
import lejos.internal.ev3.EV3Battery;
import lejos.internal.ev3.EV3TextLCD;
/**
* This class represents the local instance of an EV3 device. It can be used to
* obtain access to the various system resources (Sensors, Motors etc.).
* @author andy
*
*/
public class LocalEV3 implements EV3
{
static
{
// Check that we have EV3 hardware available
EV3DeviceManager.getLocalDeviceManager();
}
public static final LocalEV3 ev3 = new LocalEV3();
public final Battery battery = new EV3Battery();
protected ArrayList<EV3Port> ports = new ArrayList<EV3Port>();
protected TextLCD textLCD;
protected GraphicsLCD graphicsLCD;
private LocalEV3()
{
// Create the port objects
ports.add(new EV3Port("S1", EV3Port.SENSOR_PORT, 0));
ports.add(new EV3Port("S2", EV3Port.SENSOR_PORT, 1));
ports.add(new EV3Port("S3", EV3Port.SENSOR_PORT, 2));
ports.add(new EV3Port("S4", EV3Port.SENSOR_PORT, 3));
ports.add(new EV3Port("A", EV3Port.MOTOR_PORT, 0));
ports.add(new EV3Port("B", EV3Port.MOTOR_PORT, 1));
ports.add(new EV3Port("C", EV3Port.MOTOR_PORT, 2));
ports.add(new EV3Port("D", EV3Port.MOTOR_PORT, 3));
}
public static EV3 get()
{
return ev3;
}
/** {@inheritDoc}
*/
@Override
public Port getPort(String portName)
{
for(EV3Port p : ports)
if (p.getName().equals(portName))
return p;
throw new IllegalArgumentException("No such port " + portName);
}
/** {@inheritDoc}
*/
@Override
public Battery getBattery()
{
return battery;
}
@Override
public TextLCD getTextLCD() {
if (textLCD == null) textLCD = new EV3TextLCD();
return textLCD;
}
@Override
public GraphicsLCD getGraphicsLCD() {
if (graphicsLCD == null) graphicsLCD = new EV3GraphicsLCD();
return graphicsLCD;
}
@Override
public TextLCD getTextLCD(Font f) {
return new EV3TextLCD(f);
}
}
|
ev3classes/src/lejos/hardware/ev3/LocalEV3.java
|
package lejos.hardware.ev3;
import java.util.ArrayList;
import lejos.hardware.Battery;
import lejos.hardware.lcd.Font;
import lejos.hardware.lcd.GraphicsLCD;
import lejos.hardware.lcd.TextLCD;
import lejos.hardware.port.Port;
import lejos.internal.ev3.EV3DeviceManager;
import lejos.internal.ev3.EV3GraphicsLCD;
import lejos.internal.ev3.EV3Port;
import lejos.internal.ev3.EV3Battery;
import lejos.internal.ev3.EV3TextLCD;
/**
* This class represents the local instance of an EV3 device. It can be used to
* obtain access to the various system resources (Sensors, Motors etc.).
* @author andy
*
*/
public class LocalEV3 implements EV3
{
static
{
// Check that we have EV3 hardware available
EV3DeviceManager.getLocalDeviceManager();
}
public static final LocalEV3 ev3 = new LocalEV3();
public final Battery battery = new EV3Battery();
protected ArrayList<EV3Port> ports = new ArrayList<EV3Port>();
private LocalEV3()
{
// Create the port objects
ports.add(new EV3Port("S1", EV3Port.SENSOR_PORT, 0));
ports.add(new EV3Port("S2", EV3Port.SENSOR_PORT, 1));
ports.add(new EV3Port("S3", EV3Port.SENSOR_PORT, 2));
ports.add(new EV3Port("S4", EV3Port.SENSOR_PORT, 3));
ports.add(new EV3Port("A", EV3Port.MOTOR_PORT, 0));
ports.add(new EV3Port("B", EV3Port.MOTOR_PORT, 1));
ports.add(new EV3Port("C", EV3Port.MOTOR_PORT, 2));
ports.add(new EV3Port("D", EV3Port.MOTOR_PORT, 3));
}
public static EV3 get()
{
return ev3;
}
/** {@inheritDoc}
*/
@Override
public Port getPort(String portName)
{
for(EV3Port p : ports)
if (p.getName().equals(portName))
return p;
throw new IllegalArgumentException("No such port " + portName);
}
/** {@inheritDoc}
*/
@Override
public Battery getBattery()
{
return battery;
}
@Override
public TextLCD getTextLCD() {
return new EV3TextLCD();
}
@Override
public GraphicsLCD getGraphicsLCD() {
return new EV3GraphicsLCD();
}
@Override
public TextLCD getTextLCD(Font f) {
return new EV3TextLCD(f);
}
}
|
Avoid multiple instances of LCD classes
|
ev3classes/src/lejos/hardware/ev3/LocalEV3.java
|
Avoid multiple instances of LCD classes
|
<ide><path>v3classes/src/lejos/hardware/ev3/LocalEV3.java
<ide> // Check that we have EV3 hardware available
<ide> EV3DeviceManager.getLocalDeviceManager();
<ide> }
<add>
<ide> public static final LocalEV3 ev3 = new LocalEV3();
<ide> public final Battery battery = new EV3Battery();
<ide> protected ArrayList<EV3Port> ports = new ArrayList<EV3Port>();
<add> protected TextLCD textLCD;
<add> protected GraphicsLCD graphicsLCD;
<ide>
<ide> private LocalEV3()
<ide> {
<ide>
<ide> @Override
<ide> public TextLCD getTextLCD() {
<del> return new EV3TextLCD();
<add> if (textLCD == null) textLCD = new EV3TextLCD();
<add> return textLCD;
<ide> }
<ide>
<ide> @Override
<ide> public GraphicsLCD getGraphicsLCD() {
<del> return new EV3GraphicsLCD();
<add>
<add> if (graphicsLCD == null) graphicsLCD = new EV3GraphicsLCD();
<add> return graphicsLCD;
<ide> }
<ide>
<ide> @Override
|
|
Java
|
apache-2.0
|
35759fc79ef15042966696b1062d516001676147
| 0 |
apache/shiro,relateiq/shiro,apache/shiro,feige712/shiro,feige712/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.session.mgt;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* SessionValidationScheduler implementation that uses a
* {@link ScheduledExecutorService} to call {@link ValidatingSessionManager#validateSessions()} every
* <em>{@link #getInterval interval}</em> milliseconds.
*
* @author Les Hazlewood
* @since 0.9
*/
public class ExecutorServiceSessionValidationScheduler implements SessionValidationScheduler, Runnable {
//TODO - complete JavaDoc
/** Private internal log instance. */
private static final Logger log = LoggerFactory.getLogger(ExecutorServiceSessionValidationScheduler.class);
ValidatingSessionManager sessionManager;
private ScheduledExecutorService service;
private long interval = DefaultSessionManager.DEFAULT_SESSION_VALIDATION_INTERVAL;
private boolean enabled = false;
public ExecutorServiceSessionValidationScheduler() {
super();
}
public ExecutorServiceSessionValidationScheduler(ValidatingSessionManager sessionManager) {
this.sessionManager = sessionManager;
}
public ValidatingSessionManager getSessionManager() {
return sessionManager;
}
public void setSessionManager(ValidatingSessionManager sessionManager) {
this.sessionManager = sessionManager;
}
public long getInterval() {
return interval;
}
public void setInterval(long interval) {
this.interval = interval;
}
public boolean isEnabled() {
return this.enabled;
}
/**
* Creates a single thread {@link ScheduledExecutorService} to validate sessions at fixed intervals
* and enables this scheduler. The executor is created as a daemon thread to allow JVM to shut down
*/
//TODO Implement an integration test to test for jvm exit as part of the standalone example
// (so we don't have to change the unit test execution model for the core module)
public void enableSessionValidation() {
if (this.interval > 0l) {
this.service = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setDaemon(true);
return thread;
}
});
this.service.scheduleAtFixedRate(this, interval, interval, TimeUnit.MILLISECONDS);
this.enabled = true;
}
}
public void run() {
if (log.isDebugEnabled()) {
log.debug("Executing session validation...");
}
long startTime = System.currentTimeMillis();
this.sessionManager.validateSessions();
long stopTime = System.currentTimeMillis();
if (log.isDebugEnabled()) {
log.debug("Session validation completed successfully in " + (stopTime - startTime) + " milliseconds.");
}
}
public void disableSessionValidation() {
this.service.shutdownNow();
this.enabled = false;
}
}
|
core/src/main/java/org/apache/shiro/session/mgt/ExecutorServiceSessionValidationScheduler.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.session.mgt;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* SessionValidationScheduler implementation that uses a
* {@link ScheduledExecutorService} to call {@link ValidatingSessionManager#validateSessions()} every
* <em>{@link #getInterval interval}</em> milliseconds.
*
* @author Les Hazlewood
* @since 0.9
*/
public class ExecutorServiceSessionValidationScheduler implements SessionValidationScheduler, Runnable {
//TODO - complete JavaDoc
/** Private internal log instance. */
private static final Logger log = LoggerFactory.getLogger(ExecutorServiceSessionValidationScheduler.class);
ValidatingSessionManager sessionManager;
private ScheduledExecutorService service;
private long interval = DefaultSessionManager.DEFAULT_SESSION_VALIDATION_INTERVAL;
private boolean enabled = false;
public ExecutorServiceSessionValidationScheduler() {
super();
}
public ExecutorServiceSessionValidationScheduler(ValidatingSessionManager sessionManager) {
this.sessionManager = sessionManager;
}
public ValidatingSessionManager getSessionManager() {
return sessionManager;
}
public void setSessionManager(ValidatingSessionManager sessionManager) {
this.sessionManager = sessionManager;
}
public long getInterval() {
return interval;
}
public void setInterval(long interval) {
this.interval = interval;
}
public boolean isEnabled() {
return this.enabled;
}
/**
* Creates a single thread {@link ScheduledExecutorService} to validate sessions at fixed intervals
* and enables this scheduler. The executor is created as a daemon thread to allow JVM to shut down
*/
public void enableSessionValidation() {
if (this.interval > 0l) {
this.service = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setDaemon(true);
return thread;
}
});
this.service.scheduleAtFixedRate(this, interval, interval, TimeUnit.MILLISECONDS);
this.enabled = true;
}
}
public void run() {
if (log.isDebugEnabled()) {
log.debug("Executing session validation...");
}
long startTime = System.currentTimeMillis();
this.sessionManager.validateSessions();
long stopTime = System.currentTimeMillis();
if (log.isDebugEnabled()) {
log.debug("Session validation completed successfully in " + (stopTime - startTime) + " milliseconds.");
}
}
public void disableSessionValidation() {
this.service.shutdownNow();
this.enabled = false;
}
}
|
Complete - issue SHIRO-133: Automatically shut down the Session validation thread
http://issues.apache.org/jira/browse/SHIRO-133
- Added TODO as a reminder to implement an integration test for this
git-svn-id: b992ad72ce451249ae394650ed6fff1ebb4bf6b8@904640 13f79535-47bb-0310-9956-ffa450edef68
|
core/src/main/java/org/apache/shiro/session/mgt/ExecutorServiceSessionValidationScheduler.java
|
Complete - issue SHIRO-133: Automatically shut down the Session validation thread http://issues.apache.org/jira/browse/SHIRO-133 - Added TODO as a reminder to implement an integration test for this
|
<ide><path>ore/src/main/java/org/apache/shiro/session/mgt/ExecutorServiceSessionValidationScheduler.java
<ide> * Creates a single thread {@link ScheduledExecutorService} to validate sessions at fixed intervals
<ide> * and enables this scheduler. The executor is created as a daemon thread to allow JVM to shut down
<ide> */
<add> //TODO Implement an integration test to test for jvm exit as part of the standalone example
<add> // (so we don't have to change the unit test execution model for the core module)
<ide> public void enableSessionValidation() {
<ide> if (this.interval > 0l) {
<ide> this.service = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
|
|
Java
|
apache-2.0
|
09c3a51dbf6ee76d38ec43572a9e0abf1eef1178
| 0 |
signed/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,supersven/intellij-community,ernestp/consulo,MER-GROUP/intellij-community,petteyg/intellij-community,slisson/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,clumsy/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,fitermay/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,fitermay/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,da1z/intellij-community,dslomov/intellij-community,samthor/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,clumsy/intellij-community,ibinti/intellij-community,consulo/consulo,akosyakov/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,jexp/idea2,ibinti/intellij-community,retomerz/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,supersven/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,diorcety/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,slisson/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,asedunov/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,jexp/idea2,nicolargo/intellij-community,samthor/intellij-community,da1z/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,caot/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,petteyg/intellij-community,supersven/intellij-community,hurricup/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,allotria/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,supersven/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,slisson/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,izonder/intellij-community,izonder/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,adedayo/intellij-community,consulo/consulo,kdwink/intellij-community,joewalnes/idea-community,consulo/consulo,retomerz/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,signed/intellij-community,petteyg/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,caot/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,FHannes/intellij-community,caot/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,caot/intellij-community,fnouama/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,ernestp/consulo,da1z/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,joewalnes/idea-community,ivan-fedorov/intellij-community,FHannes/intellij-community,slisson/intellij-community,robovm/robovm-studio,amith01994/intellij-community,semonte/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,consulo/consulo,dslomov/intellij-community,ivan-fedorov/intellij-community,nicolargo/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,FHannes/intellij-community,kdwink/intellij-community,slisson/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,fitermay/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,samthor/intellij-community,joewalnes/idea-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,fitermay/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,caot/intellij-community,retomerz/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,wreckJ/intellij-community,slisson/intellij-community,adedayo/intellij-community,Distrotech/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,kdwink/intellij-community,semonte/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,apixandru/intellij-community,robovm/robovm-studio,vladmm/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,FHannes/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,izonder/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,signed/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,allotria/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,da1z/intellij-community,xfournet/intellij-community,apixandru/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,jexp/idea2,retomerz/intellij-community,allotria/intellij-community,ernestp/consulo,vladmm/intellij-community,da1z/intellij-community,semonte/intellij-community,gnuhub/intellij-community,signed/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,ernestp/consulo,jagguli/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,semonte/intellij-community,caot/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,jexp/idea2,mglukhikh/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,xfournet/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,xfournet/intellij-community,fitermay/intellij-community,robovm/robovm-studio,pwoodworth/intellij-community,semonte/intellij-community,jexp/idea2,idea4bsd/idea4bsd,Distrotech/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,dslomov/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,jagguli/intellij-community,izonder/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,dslomov/intellij-community,vladmm/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,signed/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,FHannes/intellij-community,robovm/robovm-studio,da1z/intellij-community,ryano144/intellij-community,slisson/intellij-community,hurricup/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,FHannes/intellij-community,jagguli/intellij-community,apixandru/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,holmes/intellij-community,ryano144/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,da1z/intellij-community,allotria/intellij-community,samthor/intellij-community,orekyuu/intellij-community,jagguli/intellij-community,signed/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,kdwink/intellij-community,slisson/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,slisson/intellij-community,amith01994/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,supersven/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,jexp/idea2,slisson/intellij-community,retomerz/intellij-community,fnouama/intellij-community,apixandru/intellij-community,petteyg/intellij-community,asedunov/intellij-community,robovm/robovm-studio,fitermay/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,allotria/intellij-community,signed/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,consulo/consulo,Lekanich/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,allotria/intellij-community,ernestp/consulo,diorcety/intellij-community,petteyg/intellij-community,joewalnes/idea-community,blademainer/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,signed/intellij-community,ibinti/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,holmes/intellij-community,caot/intellij-community,youdonghai/intellij-community,caot/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,joewalnes/idea-community,semonte/intellij-community,robovm/robovm-studio,wreckJ/intellij-community,suncycheng/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,joewalnes/idea-community,muntasirsyed/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,apixandru/intellij-community,caot/intellij-community,kdwink/intellij-community,da1z/intellij-community,diorcety/intellij-community,consulo/consulo,amith01994/intellij-community,kool79/intellij-community,adedayo/intellij-community,petteyg/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,izonder/intellij-community,vvv1559/intellij-community,samthor/intellij-community,adedayo/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,joewalnes/idea-community,mglukhikh/intellij-community,kool79/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,caot/intellij-community,apixandru/intellij-community,supersven/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,jexp/idea2,idea4bsd/idea4bsd,retomerz/intellij-community,FHannes/intellij-community,holmes/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,da1z/intellij-community,ernestp/consulo,asedunov/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,retomerz/intellij-community,retomerz/intellij-community,izonder/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,slisson/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,hurricup/intellij-community,signed/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,jexp/idea2,asedunov/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,clumsy/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,semonte/intellij-community,TangHao1987/intellij-community,robovm/robovm-studio,kool79/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,fitermay/intellij-community,samthor/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,ryano144/intellij-community,tmpgit/intellij-community,fnouama/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,muntasirsyed/intellij-community,akosyakov/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,caot/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,signed/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,kool79/intellij-community,ahb0327/intellij-community,semonte/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,holmes/intellij-community,petteyg/intellij-community,signed/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,blademainer/intellij-community,dslomov/intellij-community,jagguli/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,joewalnes/idea-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,joewalnes/idea-community,caot/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community
|
/*
* Copyright 2000-2007 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.openapi.util.text;
import com.intellij.CommonBundle;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.TextRange;
import com.intellij.util.Function;
import com.intellij.util.SmartList;
import com.intellij.util.text.CharArrayCharSequence;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.beans.Introspector;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.*;
public class StringUtil {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.util.text.StringUtil");
@NonNls private static final String VOWELS = "aeiouy";
public static String replace(@NonNls @NotNull String text, @NonNls @NotNull String oldS, @NonNls @Nullable String newS) {
return replace(text, oldS, newS, false);
}
public static String replaceIgnoreCase(@NotNull String text, @NotNull String oldS, @Nullable String newS) {
return replace(text, oldS, newS, true);
}
public static void replaceChar(@NotNull char[] buffer, char oldChar, char newChar, int start, int end) {
for (int i = start; i < end; i++) {
char c = buffer[i];
if (c == oldChar) {
buffer[i] = newChar;
}
}
}
public static String replace(@NotNull final String text, @NotNull final String oldS, @Nullable final String newS, boolean ignoreCase) {
if (text.length() < oldS.length()) return text;
final String text1 = ignoreCase ? text.toLowerCase() : text;
final String oldS1 = ignoreCase ? oldS.toLowerCase() : oldS;
final StringBuilder newText = new StringBuilder();
int i = 0;
while (i < text1.length()) {
int i1 = text1.indexOf(oldS1, i);
if (i1 < 0) {
if (i == 0) return text;
newText.append(text, i, text.length());
break;
}
else {
if (newS == null) return null;
newText.append(text, i, i1);
newText.append(newS);
i = i1 + oldS.length();
}
}
return newText.toString();
}
@NotNull public static String getShortName(@NotNull String fqName) {
return getShortName(fqName, '.');
}
@NotNull public static String getShortName(@NotNull Class aClass) {
return getShortName(aClass.getName());
}
/**
* Implementation copied from {@link String#indexOf(String, int)} except character comparisons made case insensitive
*
* @param where
* @param what
* @param fromIndex
* @return
*/
public static int indexOfIgnoreCase(@NotNull String where, @NotNull String what, int fromIndex) {
int targetCount = what.length();
int sourceCount = where.length();
if (fromIndex >= sourceCount) {
return targetCount == 0 ? sourceCount : -1;
}
if (fromIndex < 0) {
fromIndex = 0;
}
if (targetCount == 0) {
return fromIndex;
}
char first = what.charAt(0);
int max = sourceCount - targetCount;
for (int i = fromIndex; i <= max; i++) {
/* Look for first character. */
if (!charsEqualIgnoreCase(where.charAt(i), first)) {
while (++i <= max && !charsEqualIgnoreCase(where.charAt(i), first)) ;
}
/* Found first character, now look at the rest of v2 */
if (i <= max) {
int j = i + 1;
int end = j + targetCount - 1;
for (int k = 1; j < end && charsEqualIgnoreCase(where.charAt(j), what.charAt(k)); j++, k++) ;
if (j == end) {
/* Found whole string. */
return i;
}
}
}
return -1;
}
public static boolean containsIgnoreCase(String where, String what) {
return indexOfIgnoreCase(where, what, 0) >= 0;
}
public static boolean endsWithIgnoreCase(@NonNls String str, @NonNls String suffix) {
final int stringLength = str.length();
final int suffixLength = suffix.length();
return stringLength >= suffixLength && str.regionMatches(true, stringLength - suffixLength, suffix, 0, suffixLength);
}
public static boolean startsWithIgnoreCase(String str, String prefix) {
final int stringLength = str.length();
final int prefixLength = prefix.length();
return stringLength >= prefixLength && str.regionMatches(true, 0, prefix, 0, prefixLength);
}
public static boolean charsEqualIgnoreCase(char a, char b) {
return a == b || toUpperCase(a) == toUpperCase(b) || toLowerCase(a) == toLowerCase(b);
}
public static char toUpperCase(char a) {
if (a < 'a') {
return a;
}
if (a >= 'a' && a <= 'z') {
return (char)(a + ('A' - 'a'));
}
return Character.toUpperCase(a);
}
public static char toLowerCase(final char a) {
if (a < 'A' || a >= 'a' && a <= 'z') {
return a;
}
if (a >= 'A' && a <= 'Z') {
return (char)(a + ('a' - 'A'));
}
return Character.toLowerCase(a);
}
@NotNull public static String getShortName(@NotNull String fqName, char separator) {
int lastPointIdx = fqName.lastIndexOf(separator);
if (lastPointIdx >= 0) {
return fqName.substring(lastPointIdx + 1);
}
return fqName;
}
@NotNull public static String getPackageName(@NotNull String fqName) {
return getPackageName(fqName, '.');
}
@NotNull public static String getPackageName(@NotNull String fqName, char separator) {
int lastPointIdx = fqName.lastIndexOf(separator);
if (lastPointIdx >= 0) {
return fqName.substring(0, lastPointIdx);
}
return "";
}
/**
* Converts line separators to <code>"\n"</code>
*/
@NotNull public static String convertLineSeparators(@NotNull String text) {
return convertLineSeparators(text, "\n", null);
}
@NotNull public static String convertLineSeparators(@NotNull String text, @NotNull String newSeparator) {
return convertLineSeparators(text, newSeparator, null);
}
@NotNull public static String convertLineSeparators(@NotNull String text, @NotNull String newSeparator, @Nullable int[] offsetsToKeep) {
StringBuilder buffer = new StringBuilder(text.length());
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c == '\n') {
buffer.append(newSeparator);
shiftOffsets(offsetsToKeep, buffer.length(), 1, newSeparator.length());
}
else if (c == '\r') {
buffer.append(newSeparator);
if (i < text.length() - 1 && text.charAt(i + 1) == '\n') {
i++;
shiftOffsets(offsetsToKeep, buffer.length(), 2, newSeparator.length());
}
else {
shiftOffsets(offsetsToKeep, buffer.length(), 1, newSeparator.length());
}
}
else {
buffer.append(c);
}
}
return buffer.toString();
}
private static void shiftOffsets(int[] offsets, int changeOffset, int oldLength, int newLength) {
if (offsets == null) return;
int shift = newLength - oldLength;
if (shift == 0) return;
for (int i = 0; i < offsets.length; i++) {
int offset = offsets[i];
if (offset >= changeOffset + oldLength) {
offsets[i] += shift;
}
}
}
public static int getLineBreakCount(@NotNull CharSequence text) {
int count = 0;
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c == '\n') {
count++;
}
else if (c == '\r') {
if (i + 1 < text.length() && text.charAt(i + 1) == '\n') {
i++;
count++;
}
else {
count++;
}
}
}
return count;
}
public static int lineColToOffset(@NotNull CharSequence text, int line, int col) {
int curLine = 0;
int offset = 0;
while (true) {
if (line == curLine) {
return offset + col;
}
if (offset == text.length()) return -1;
char c = text.charAt(offset);
if (c == '\n') {
curLine++;
}
else if (c == '\r') {
curLine++;
if (offset < text.length() - 1 && text.charAt(offset + 1) == '\n') {
offset++;
}
}
offset++;
}
}
public static int offsetToLineNumber(@NotNull CharSequence text, int offset) {
int curLine = 0;
int curOffset = 0;
while (true) {
if (offset <= curOffset) {
return curLine;
}
if (curOffset == text.length()) return -1;
char c = text.charAt(curOffset);
if (c == '\n') {
curLine++;
}
else if (c == '\r') {
curLine++;
if (curOffset < text.length() - 1 && text.charAt(curOffset + 1) == '\n') {
curOffset++;
}
}
curOffset++;
}
}
/**
* Classic dynamic programming algorithm for string differences.
*/
public static int difference(@NotNull String s1, @NotNull String s2) {
int[][] a = new int[s1.length()][s2.length()];
for (int i = 0; i < s1.length(); i++) {
a[i][0] = i;
}
for (int j = 0; j < s2.length(); j++) {
a[0][j] = j;
}
for (int i = 1; i < s1.length(); i++) {
for (int j = 1; j < s2.length(); j++) {
a[i][j] = Math.min(Math.min(a[i - 1][j - 1] + (s1.charAt(i) == s2.charAt(j) ? 0 : 1), a[i - 1][j] + 1), a[i][j - 1] + 1);
}
}
return a[s1.length() - 1][s2.length() - 1];
}
@NotNull public static String wordsToBeginFromUpperCase(@NotNull String s) {
StringBuffer buffer = null;
for (int i = 0; i < s.length(); i++) {
char prevChar = i == 0 ? ' ' : s.charAt(i - 1);
char currChar = s.charAt(i);
if (!Character.isLetterOrDigit(prevChar)) {
if (Character.isLetterOrDigit(currChar)) {
if (!Character.isUpperCase(currChar)) {
int j = i;
for (; j < s.length(); j++) {
if (!Character.isLetterOrDigit(s.charAt(j))) {
break;
}
}
if (!isPreposition(s, i, j - 1)) {
if (buffer == null) {
buffer = new StringBuffer(s);
}
buffer.setCharAt(i, toUpperCase(currChar));
}
}
}
}
}
if (buffer == null) {
return s;
}
else {
return buffer.toString();
}
}
@NonNls private static final String[] ourPrepositions =
new String[]{"at", "the", "and", "not", "if", "a", "or", "to", "in", "on", "into"};
public static boolean isPreposition(@NotNull String s, int firstChar, int lastChar) {
for (String preposition : ourPrepositions) {
boolean found = false;
if (lastChar - firstChar + 1 == preposition.length()) {
found = true;
for (int j = 0; j < preposition.length(); j++) {
if (!(toLowerCase(s.charAt(firstChar + j)) == preposition.charAt(j))) {
found = false;
}
}
}
if (found) {
return true;
}
}
return false;
}
public static void escapeStringCharacters(int length, final String str, @NotNull @NonNls StringBuilder buffer) {
for (int idx = 0; idx < length; idx++) {
char ch = str.charAt(idx);
switch (ch) {
case'\b':
buffer.append("\\b");
break;
case'\t':
buffer.append("\\t");
break;
case'\n':
buffer.append("\\n");
break;
case'\f':
buffer.append("\\f");
break;
case'\r':
buffer.append("\\r");
break;
case'\"':
buffer.append("\\\"");
break;
case'\\':
buffer.append("\\\\");
break;
default:
if (Character.isISOControl(ch)) {
String hexCode = Integer.toHexString(ch).toUpperCase();
buffer.append("\\u");
int paddingCount = 4 - hexCode.length();
while (paddingCount-- > 0) {
buffer.append(0);
}
buffer.append(hexCode);
}
else {
buffer.append(ch);
}
}
}
}
@NotNull public static String escapeStringCharacters(@NotNull String s) {
StringBuilder buffer = new StringBuilder();
escapeStringCharacters(s.length(), s, buffer);
return buffer.toString();
}
@NotNull public static String unescapeStringCharacters(@NotNull String s) {
StringBuilder buffer = new StringBuilder();
unescapeStringCharacters(s.length(), s, buffer);
return buffer.toString();
}
@NotNull public static String unquoteString( @NotNull String s )
{
if( s.length() > 1 && s.charAt( 0 ) == '"' && s.charAt( s.length() - 1) == '"' )
return s.substring( 1, s.length() - 1 );
else
return s;
}
private static void unescapeStringCharacters(int length, String s, StringBuilder buffer) {
boolean escaped = false;
for (int idx = 0; idx < length; idx++) {
char ch = s.charAt(idx);
if (!escaped) {
if (ch == '\\') {
escaped = true;
}
else {
buffer.append(ch);
}
}
else {
switch (ch) {
case'n':
buffer.append('\n');
break;
case'r':
buffer.append('\r');
break;
case'b':
buffer.append('\b');
break;
case't':
buffer.append('\t');
break;
case'f':
buffer.append('\f');
break;
case'\'':
buffer.append('\'');
break;
case'\"':
buffer.append('\"');
break;
case'\\':
buffer.append('\\');
break;
case'u':
if (idx + 4 < length) {
try {
int code = Integer.valueOf(s.substring(idx + 1, idx + 5), 16).intValue();
idx += 4;
buffer.append((char)code);
}
catch (NumberFormatException e) {
buffer.append("\\u");
}
}
else {
buffer.append("\\u");
}
break;
default:
buffer.append(ch);
break;
}
escaped = false;
}
}
if (escaped) buffer.append('\\');
}
@SuppressWarnings({"HardCodedStringLiteral"})
@NotNull public static String pluralize(@NotNull String suggestion) {
if (suggestion.endsWith("Child") || suggestion.endsWith("child")) {
return suggestion + "ren";
}
if (endsWithChar(suggestion, 's') || endsWithChar(suggestion, 'x') || suggestion.endsWith("ch")) {
return suggestion + "es";
}
int len = suggestion.length();
if (endsWithChar(suggestion, 'y') && len > 1 && !isVowel(suggestion.charAt(len - 2))) {
return suggestion.substring(0, len - 1) + "ies";
}
return suggestion + "s";
}
@NotNull public static String capitalizeWords(@NotNull String text, boolean allWords) {
StringTokenizer tokenizer = new StringTokenizer(text);
String out = "";
String delim = "";
boolean toCapitalize = true;
while (tokenizer.hasMoreTokens()) {
String word = tokenizer.nextToken();
out += delim + (toCapitalize ? capitalize(word) : word);
delim = " ";
if (!allWords) {
toCapitalize = false;
}
}
return out;
}
public static String decapitalize(String s) {
return Introspector.decapitalize(s);
}
public static boolean isVowel(char c) {
return VOWELS.indexOf(c) >= 0;
}
@NotNull public static String capitalize(@NotNull String s) {
if (s.length() == 0) return s;
if (s.length() == 1) return s.toUpperCase();
// Optimization
if (Character.isUpperCase(s.charAt(0)) ) return s;
return toUpperCase(s.charAt(0)) + s.substring(1);
}
public static int stringHashCode(CharSequence chars) {
if (chars instanceof String) return chars.hashCode();
if (chars instanceof CharSequenceWithStringHash) return chars.hashCode();
if (chars instanceof CharArrayCharSequence) return chars.hashCode();
int h = 0;
int to = chars.length();
for (int off = 0; off < to; off++) {
h = 31 * h + chars.charAt(off);
}
return h;
}
public static int stringHashCode(CharSequence chars, int from, int to) {
int h = 0;
for (int off = from; off < to; off++) {
h = 31 * h + chars.charAt(off);
}
return h;
}
public static int stringHashCode(char[] chars, int from, int to) {
int h = 0;
for (int off = from; off < to; off++) {
h = 31 * h + chars[off];
}
return h;
}
public static int stringHashCodeInsensitive(char[] chars, int from, int to) {
int h = 0;
for (int off = from; off < to; off++) {
h = 31 * h + toLowerCase(chars[off]);
}
return h;
}
public static int stringHashCodeInsensitive(CharSequence chars, int from, int to) {
int h = 0;
for (int off = from; off < to; off++) {
h = 31 * h + toLowerCase(chars.charAt(off));
}
return h;
}
public static int stringHashCodeInsensitive(@NotNull CharSequence chars) {
int h = 0;
final int len = chars.length();
for (int i = 0; i < len; i++) {
h = 31 * h + toLowerCase(chars.charAt(i));
}
return h;
}
@NotNull public static String trimEnd(@NotNull String s, @NonNls @NotNull String suffix) {
if (s.endsWith(suffix)) {
return s.substring(0, s.lastIndexOf(suffix));
}
return s;
}
public static boolean startsWithChar(@Nullable CharSequence s, char prefix) {
return s != null && s.length() != 0 && s.charAt(0) == prefix;
}
public static boolean endsWithChar(@Nullable CharSequence s, char suffix) {
return s != null && s.length() != 0 && s.charAt(s.length() - 1) == suffix;
}
@NotNull public static String trimStart(@NotNull String s, @NonNls @NotNull String prefix) {
if (s.startsWith(prefix)) {
return s.substring(prefix.length());
}
return s;
}
@NotNull public static String pluralize(@NotNull String base, int n) {
if (n == 1) return base;
return pluralize(base);
}
public static void repeatSymbol(Appendable buffer, char symbol, int times) {
try {
for (int i = 0; i < times; i++) {
buffer.append(symbol);
}
}
catch (IOException e) {
LOG.error(e);
}
}
public static boolean isNotEmpty(final String s) {
return s != null && s.length() > 0;
}
public static boolean isEmpty(final String s) {
return s == null || s.length() == 0;
}
@NotNull
public static String notNullize(final String s) {
return s == null ? "" : s;
}
public static boolean isEmptyOrSpaces(final String s) {
return s == null || s.trim().length() == 0;
}
public static String getThrowableText(final Throwable aThrowable) {
StringWriter stringWriter = new StringWriter();
PrintWriter writer = new PrintWriter(stringWriter);
aThrowable.printStackTrace(writer);
return stringWriter.getBuffer().toString();
}
public static String getThrowableText(final Throwable aThrowable, @NonNls @NotNull final String stackFrameSkipPattern) {
@NonNls final String prefix = "\tat ";
final String skipPattern = prefix + stackFrameSkipPattern;
final StringWriter stringWriter = new StringWriter();
final PrintWriter writer = new PrintWriter(stringWriter) {
boolean skipping = false;
public void println(final String x) {
if (x != null) {
if (!skipping && x.startsWith(skipPattern)) skipping = true;
else if (skipping && !x.startsWith(prefix)) skipping = false;
}
if (skipping) return;
super.println(x);
}
};
aThrowable.printStackTrace(writer);
return stringWriter.getBuffer().toString();
}
public static String getMessage(Throwable e) {
String result = e.getMessage();
@NonNls final String exceptionPattern = "Exception: ";
@NonNls final String errorPattern = "Error: ";
while ((result == null || result.contains(exceptionPattern) || result.contains(errorPattern)) && e.getCause() != null) {
e = e.getCause();
result = e.getMessage();
}
if (result != null) {
result = extractMessage(result, exceptionPattern);
result = extractMessage(result, errorPattern);
}
return result;
}
@NotNull private static String extractMessage(@NotNull String result, @NotNull final String errorPattern) {
if (result.lastIndexOf(errorPattern) >= 0) {
result = result.substring(result.lastIndexOf(errorPattern) + errorPattern.length());
}
return result;
}
@NotNull public static String repeatSymbol(final char aChar, final int count) {
final StringBuilder buffer = new StringBuilder();
repeatSymbol(buffer, aChar, count);
return buffer.toString();
}
@NotNull
public static List<String> splitHonorQuotes(@NotNull String s, char separator) {
final ArrayList<String> result = new ArrayList<String>();
final StringBuilder builder = new StringBuilder();
boolean inQuotes = false;
for (int i = 0; i < s.length(); i++) {
final char c = s.charAt(i);
if (c == separator && !inQuotes) {
if (builder.length() > 0) {
result.add(builder.toString());
builder.setLength(0);
}
continue;
}
if ((c == '"' || c == '\'') && !(i > 0 && s.charAt(i - 1) == '\\')) {
inQuotes = !inQuotes;
}
builder.append(c);
}
if (builder.length() > 0) {
result.add(builder.toString());
}
return result;
}
@NotNull public static List<String> split(@NotNull String s, @NotNull String separator) {
if (separator.length() == 0) {
return Collections.singletonList(s);
}
ArrayList<String> result = new ArrayList<String>();
int pos = 0;
while (true) {
int index = s.indexOf(separator, pos);
if (index == -1) break;
String token = s.substring(pos, index);
if (token.length() != 0) {
result.add(token);
}
pos = index + separator.length();
}
if (pos < s.length()) {
result.add(s.substring(pos, s.length()));
}
return result;
}
@NotNull
public static Iterable<String> tokenize(@NotNull String s, @NotNull String separators) {
final com.intellij.util.text.StringTokenizer tokenizer = new com.intellij.util.text.StringTokenizer(s, separators);
return new Iterable<String>() {
public Iterator<String> iterator() {
return new Iterator<String>() {
public boolean hasNext() {
return tokenizer.hasMoreTokens();
}
public String next() {
return tokenizer.nextToken();
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
@NotNull
public static List<String> getWordsIn(@NotNull String text) {
List<String> result = new SmartList<String>();
int start = -1;
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
boolean isIdentifierPart = Character.isJavaIdentifierPart(c);
if (isIdentifierPart && start == -1) {
start = i;
}
if (isIdentifierPart && i == text.length() - 1 && start != -1) {
result.add(text.substring(start, i + 1));
}
else if (!isIdentifierPart && start != -1) {
result.add(text.substring(start, i));
start = -1;
}
}
return result;
}
@NotNull public static String join(@NotNull final String[] strings, @NotNull final String separator) {
return join(strings, 0, strings.length, separator);
}
@NotNull public static String join(@NotNull final String[] strings, int startIndex, int endIndex, @NotNull final String separator) {
final StringBuilder result = new StringBuilder();
for (int i = startIndex; i < endIndex; i++) {
if (i > startIndex) result.append(separator);
result.append(strings[i]);
}
return result.toString();
}
@NotNull public static String[] zip(@NotNull String[] strings1, @NotNull String[] strings2, String separator) {
if (strings1.length != strings2.length) throw new IllegalArgumentException();
String[] result = new String[strings1.length];
for (int i = 0; i < result.length; i++) {
result[i] = strings1[i] + separator + strings2[i];
}
return result;
}
public static String[] surround(String[] strings1, String prefix, String suffix) {
String[] result = new String[strings1.length];
for (int i = 0; i < result.length; i++) {
result[i] = prefix + strings1[i] + suffix;
}
return result;
}
@NotNull public static <T> String join(@NotNull T[] items, @NotNull Function<T, String> f, @NotNull @NonNls String separator) {
return join(Arrays.asList(items), f, separator);
}
@NotNull public static <T> String join(@NotNull Iterable<T> items, @NotNull Function<T, String> f, @NotNull @NonNls String separator) {
final StringBuilder result = new StringBuilder();
for (T item : items) {
String string = f.fun(item);
if (string != null && string.length() != 0) {
if (result.length() != 0) result.append(separator);
result.append(string);
}
}
return result.toString();
}
@NotNull public static String join(@NotNull Collection<String> strings, @NotNull final String separator) {
final StringBuilder result = new StringBuilder();
for (String string : strings) {
if (string != null && string.length() != 0) {
if (result.length() != 0) result.append(separator);
result.append(string);
}
}
return result.toString();
}
@NotNull public static String join(@NotNull final int[] strings, @NotNull final String separator) {
final StringBuilder result = new StringBuilder();
for (int i = 0; i < strings.length; i++) {
if (i > 0) result.append(separator);
result.append(strings[i]);
}
return result.toString();
}
@NotNull public static String stripQuotesAroundValue(@NotNull String text) {
if (startsWithChar(text, '\"') || startsWithChar(text, '\'')) text = text.substring(1);
if (endsWithChar(text, '\"') || endsWithChar(text, '\'')) text = text.substring(0, text.length() - 1);
return text;
}
public static boolean isQuotedString(@NotNull String text) {
return startsWithChar(text, '\"') && endsWithChar(text, '\"')
|| startsWithChar(text, '\'') && endsWithChar(text, '\'');
}
/**
* Formats the specified file size as a string.
*
* @param fileSize the size to format.
* @return the size formatted as a string.
* @since 5.0.1
*/
@NotNull public static String formatFileSize(final long fileSize) {
if (fileSize < 0x400) {
return CommonBundle.message("file.size.format.bytes", fileSize);
}
if (fileSize < 0x100000) {
long kbytes = fileSize * 100 / 1024;
final String kbs = kbytes / 100 + "." + kbytes % 100;
return CommonBundle.message("file.size.format.kbytes", kbs);
}
long mbytes = fileSize * 100 / 1024 / 1024;
final String size = mbytes / 100 + "." + mbytes % 100;
return CommonBundle.message("file.size.format.mbytes", size);
}
/**
* Returns unpluralized variant using English based heuristics like properties -> property, names -> name, children -> child.
* Returns <code>null</code> if failed to match appropriate heuristic.
*
* @param name english word in plural form
* @return name in singular form or <code>null</code> if failed to find one.
*/
@SuppressWarnings({"HardCodedStringLiteral"})
@Nullable
public static String unpluralize(@NotNull final String name) {
if (name.endsWith("sses") || name.endsWith("shes") || name.endsWith("ches") || name.endsWith("xes")) { //?
return name.substring(0, name.length() - 2);
}
if (name.endsWith("ses")) {
return name.substring(0, name.length() - 1);
}
if (name.endsWith("ies")) {
return name.substring(0, name.length() - 3) + "y";
}
String result = stripEnding(name, "s");
if (result != null) {
return result;
}
if (name.endsWith("children")) {
return name.substring(0, name.length() - "children".length()) + "child";
}
if (name.endsWith("Children") && name.length() > "Children".length()) {
return name.substring(0, name.length() - "Children".length()) + "Child";
}
return null;
}
private static String stripEnding(String name, String ending) {
if (name.endsWith(ending)) {
if (name.equals(ending)) return name; // do not return empty string
return name.substring(0, name.length() - 1);
}
return null;
}
public static boolean containsAlphaCharacters(@NotNull String value) {
for (int i = 0; i < value.length(); i++) {
if (Character.isLetter(value.charAt(i))) return true;
}
return false;
}
public static String firstLetterToUpperCase(final String displayString) {
if (displayString == null || displayString.length() == 0) return displayString;
char firstChar = displayString.charAt(0);
char uppedFirstChar = toUpperCase(firstChar);
if (uppedFirstChar == firstChar) return displayString;
StringBuilder builder = new StringBuilder(displayString);
builder.setCharAt(0, uppedFirstChar);
return builder.toString();
}
/**
* Strip out all characters not accepted by given filter
* @param s e.g. "/n my string "
* @param filter e.g. {@link CharFilter#NOT_WHITESPACE_FILTER}
* @return stripped string e.g. "mystring"
*/
@NotNull public static String strip(@NotNull final String s, @NotNull CharFilter filter) {
StringBuilder result = new StringBuilder(s.length());
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (filter.accept(ch)) {
result.append(ch);
}
}
return result.toString();
}
/**
* Find position of the first charachter accepted by given filter
* @param s the string to search
* @param filter
* @return position of the first charachter accepted or -1 if not found
*/
public static int findFirst(@NotNull final String s, @NotNull CharFilter filter) {
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (filter.accept(ch)) {
return i;
}
}
return -1;
}
@NotNull public static String replaceSubstring(@NotNull String string, @NotNull TextRange range, @NotNull String replacement) {
return string.substring(0, range.getStartOffset()) + replacement + string.substring(range.getEndOffset());
}
public static boolean startsWith(@NotNull CharSequence text, @NotNull CharSequence prefix) {
int l1 = text.length();
int l2 = prefix.length();
if (l1 < l2) return false;
for (int i = 0; i < l2; i++) {
if (text.charAt(i) != prefix.charAt(i)) return false;
}
return true;
}
public static boolean endsWith(@NotNull CharSequence text, @NotNull CharSequence suffix) {
int l1 = text.length();
int l2 = suffix.length();
if (l1 < l2) return false;
for (int i = l1-1; i >= l1-l2; i--) {
if (text.charAt(i) != suffix.charAt(i+l2-l1)) return false;
}
return true;
}
@NotNull
public static String commonPrefix(@NotNull String s1, @NotNull String s2) {
int i;
for (i = 0; i<s1.length() && i<s2.length(); i++) {
if (s1.charAt(i) != s2.charAt(i)) {
break;
}
}
return s1.substring(0, i);
}
@NotNull
public static String commonSuffix(@NotNull String s1, @NotNull String s2) {
if (s1.length() == 0 || s2.length() == 0) return "";
int i;
for (i = s1.length()-1; i>=0 && i>=s1.length() - s2.length(); i--) {
if (s1.charAt(i) != s2.charAt(i+s2.length()-s1.length())) {
break;
}
}
return s1.substring(i, s1.length());
}
public static int indexOf(CharSequence s, char c) {
int l = s.length();
for (int i = 0; i < l; i++) {
if (s.charAt(i) == c) return i;
}
return -1;
}
public static String first(final String text, final int length, final boolean appendEllipsis) {
return text.length() > length ? text.substring(0, length) + (appendEllipsis ? "..." : "") : text;
}
public static String escapeQuotes(@NotNull final String str) {
int idx = str.indexOf('"');
if (idx < 0) return str;
StringBuilder buf = new StringBuilder(str);
while (idx < buf.length()) {
if (buf.charAt(idx) == '"') {
buf.replace(idx, idx + 1, "\\\"");
idx += 2;
}
else {
idx += 1;
}
}
return buf.toString();
}
@NonNls private static final String[] REPLACES_REFS = new String[]{"<", " ", ">", "&", "'", """};
@NonNls private static final String[] REPLACES_DISP = new String[]{"<", "\u00a0", ">", "&", "'", "\""};
public static String unescapeXml(final String text) {
if (text == null) return null;
return replace(text, REPLACES_REFS, REPLACES_DISP);
}
public static String escapeXml(final String text) {
if (text == null) return null;
return replace(text, REPLACES_DISP, REPLACES_REFS);
}
public static String escapeToRegexp(String text) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < text.length(); i++) {
final char c = text.charAt(i);
if (c == ' ' || Character.isLetter(c) || Character.isDigit(c)) {
result.append(c);
}
else {
result.append('\\').append(c);
}
}
return result.toString();
}
private static String replace(final String text, final String[] from, final String[] to) {
final StringBuilder result = new StringBuilder(text.length());
replace:
for (int i = 0; i < text.length(); i++) {
for (int j = 0; j < from.length; j += 1) {
String toReplace = from[j];
String replaceWith = to[j];
final int len = toReplace.length();
if (text.regionMatches(i, toReplace, 0, len)) {
result.append(replaceWith);
i += len - 1;
continue replace;
}
}
result.append(text.charAt(i));
}
return result.toString();
}
public static String[] filterEmptyStrings(String[] strings) {
int emptyCount = 0;
for (String string : strings) {
if (string == null || string.length() == 0) emptyCount++;
}
if (emptyCount == 0) return strings;
String[] result = new String[strings.length - emptyCount];
int count = 0;
for (String string : strings) {
if (string == null || string.length() == 0) continue;
result[count++] = string;
}
return result;
}
public static int countNewLines(final CharSequence text) {
int lineShift = 0;
for(int i = 0; i < text.length(); ++i) {
final char ch = text.charAt(i);
if (ch == '\n') {
++lineShift;
}
}
return lineShift;
}
public static String capitalsOnly(String s) {
StringBuilder b = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
if (Character.isUpperCase(s.charAt(i))) {
b.append(s.charAt(i));
}
}
return b.toString();
}
// returns null if any of args is null
@Nullable
public static String joinOrNull(@NotNull String... args) {
StringBuilder r = new StringBuilder();
for (String arg : args) {
if (arg == null) return null;
r.append(arg);
}
return r.toString();
}
public static String getPropertyName(@NonNls final String methodName) {
if (methodName.startsWith("get")) {
return Introspector.decapitalize(methodName.substring(3));
}
else if (methodName.startsWith("is")) {
return Introspector.decapitalize(methodName.substring(2));
}
else if (methodName.startsWith("set")) {
return Introspector.decapitalize(methodName.substring(3));
}
else {
return null;
}
}
public static boolean isJavaIdentifierStart(char c) {
return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || Character.isJavaIdentifierStart(c);
}
public static boolean isJavaIdentifierPart(char c) {
return c >= '0' && c <= '9' || isJavaIdentifierStart(c);
}
public static boolean isJavaIdentifier(String text) {
int len = text.length();
if (len == 0) return false;
if (!isJavaIdentifierStart(text.charAt(0))) return false;
for (int i = 1; i < len; i++) {
if (!isJavaIdentifierPart(text.charAt(i))) return false;
}
return true;
}
}
|
util/src/com/intellij/openapi/util/text/StringUtil.java
|
/*
* Copyright 2000-2007 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.openapi.util.text;
import com.intellij.CommonBundle;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.TextRange;
import com.intellij.util.Function;
import com.intellij.util.SmartList;
import com.intellij.util.text.CharArrayCharSequence;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.beans.Introspector;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.*;
public class StringUtil {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.util.text.StringUtil");
@NonNls private static final String VOWELS = "aeiouy";
public static String replace(@NonNls @NotNull String text, @NonNls @NotNull String oldS, @NonNls @Nullable String newS) {
return replace(text, oldS, newS, false);
}
public static String replaceIgnoreCase(@NotNull String text, @NotNull String oldS, @Nullable String newS) {
return replace(text, oldS, newS, true);
}
public static void replaceChar(@NotNull char[] buffer, char oldChar, char newChar, int start, int end) {
for (int i = start; i < end; i++) {
char c = buffer[i];
if (c == oldChar) {
buffer[i] = newChar;
}
}
}
public static String replace(@NotNull final String text, @NotNull final String oldS, @Nullable final String newS, boolean ignoreCase) {
if (text.length() < oldS.length()) return text;
final String text1 = ignoreCase ? text.toLowerCase() : text;
final String oldS1 = ignoreCase ? oldS.toLowerCase() : oldS;
final StringBuilder newText = new StringBuilder();
int i = 0;
while (i < text1.length()) {
int i1 = text1.indexOf(oldS1, i);
if (i1 < 0) {
if (i == 0) return text;
newText.append(text, i, text.length());
break;
}
else {
if (newS == null) return null;
newText.append(text, i, i1);
newText.append(newS);
i = i1 + oldS.length();
}
}
return newText.toString();
}
@NotNull public static String getShortName(@NotNull String fqName) {
return getShortName(fqName, '.');
}
@NotNull public static String getShortName(@NotNull Class aClass) {
return getShortName(aClass.getName());
}
/**
* Implementation copied from {@link String#indexOf(String, int)} except character comparisons made case insensitive
*
* @param where
* @param what
* @param fromIndex
* @return
*/
public static int indexOfIgnoreCase(@NotNull String where, @NotNull String what, int fromIndex) {
int targetCount = what.length();
int sourceCount = where.length();
if (fromIndex >= sourceCount) {
return targetCount == 0 ? sourceCount : -1;
}
if (fromIndex < 0) {
fromIndex = 0;
}
if (targetCount == 0) {
return fromIndex;
}
char first = what.charAt(0);
int max = sourceCount - targetCount;
for (int i = fromIndex; i <= max; i++) {
/* Look for first character. */
if (!charsEqualIgnoreCase(where.charAt(i), first)) {
while (++i <= max && !charsEqualIgnoreCase(where.charAt(i), first)) ;
}
/* Found first character, now look at the rest of v2 */
if (i <= max) {
int j = i + 1;
int end = j + targetCount - 1;
for (int k = 1; j < end && charsEqualIgnoreCase(where.charAt(j), what.charAt(k)); j++, k++) ;
if (j == end) {
/* Found whole string. */
return i;
}
}
}
return -1;
}
public static boolean containsIgnoreCase(String where, String what) {
return indexOfIgnoreCase(where, what, 0) >= 0;
}
public static boolean endsWithIgnoreCase(@NonNls String str, @NonNls String suffix) {
final int stringLength = str.length();
final int suffixLength = suffix.length();
return stringLength >= suffixLength && str.regionMatches(true, stringLength - suffixLength, suffix, 0, suffixLength);
}
public static boolean startsWithIgnoreCase(String str, String prefix) {
final int stringLength = str.length();
final int prefixLength = prefix.length();
return stringLength >= prefixLength && str.regionMatches(true, 0, prefix, 0, prefixLength);
}
public static boolean charsEqualIgnoreCase(char a, char b) {
return a == b || toUpperCase(a) == toUpperCase(b) || toLowerCase(a) == toLowerCase(b);
}
public static char toUpperCase(char a) {
if (a < 'a') {
return a;
}
if (a >= 'a' && a <= 'z') {
return (char)(a + ('A' - 'a'));
}
return Character.toUpperCase(a);
}
public static char toLowerCase(final char a) {
if (a < 'A' || a >= 'a' && a <= 'z') {
return a;
}
if (a >= 'A' && a <= 'Z') {
return (char)(a + ('a' - 'A'));
}
return Character.toLowerCase(a);
}
@NotNull public static String getShortName(@NotNull String fqName, char separator) {
int lastPointIdx = fqName.lastIndexOf(separator);
if (lastPointIdx >= 0) {
return fqName.substring(lastPointIdx + 1);
}
return fqName;
}
@NotNull public static String getPackageName(@NotNull String fqName) {
return getPackageName(fqName, '.');
}
@NotNull public static String getPackageName(@NotNull String fqName, char separator) {
int lastPointIdx = fqName.lastIndexOf(separator);
if (lastPointIdx >= 0) {
return fqName.substring(0, lastPointIdx);
}
return "";
}
/**
* Converts line separators to <code>"\n"</code>
*/
@NotNull public static String convertLineSeparators(@NotNull String text) {
return convertLineSeparators(text, "\n", null);
}
@NotNull public static String convertLineSeparators(@NotNull String text, @NotNull String newSeparator) {
return convertLineSeparators(text, newSeparator, null);
}
@NotNull public static String convertLineSeparators(@NotNull String text, @NotNull String newSeparator, @Nullable int[] offsetsToKeep) {
StringBuilder buffer = new StringBuilder(text.length());
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c == '\n') {
buffer.append(newSeparator);
shiftOffsets(offsetsToKeep, buffer.length(), 1, newSeparator.length());
}
else if (c == '\r') {
buffer.append(newSeparator);
if (i < text.length() - 1 && text.charAt(i + 1) == '\n') {
i++;
shiftOffsets(offsetsToKeep, buffer.length(), 2, newSeparator.length());
}
else {
shiftOffsets(offsetsToKeep, buffer.length(), 1, newSeparator.length());
}
}
else {
buffer.append(c);
}
}
return buffer.toString();
}
private static void shiftOffsets(int[] offsets, int changeOffset, int oldLength, int newLength) {
if (offsets == null) return;
int shift = newLength - oldLength;
if (shift == 0) return;
for (int i = 0; i < offsets.length; i++) {
int offset = offsets[i];
if (offset >= changeOffset + oldLength) {
offsets[i] += shift;
}
}
}
public static int getLineBreakCount(@NotNull CharSequence text) {
int count = 0;
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c == '\n') {
count++;
}
else if (c == '\r') {
if (i + 1 < text.length() && text.charAt(i + 1) == '\n') {
i++;
count++;
}
else {
count++;
}
}
}
return count;
}
public static int lineColToOffset(@NotNull CharSequence text, int line, int col) {
int curLine = 0;
int offset = 0;
while (true) {
if (line == curLine) {
return offset + col;
}
if (offset == text.length()) return -1;
char c = text.charAt(offset);
if (c == '\n') {
curLine++;
}
else if (c == '\r') {
curLine++;
if (offset < text.length() - 1 && text.charAt(offset + 1) == '\n') {
offset++;
}
}
offset++;
}
}
public static int offsetToLineNumber(@NotNull CharSequence text, int offset) {
int curLine = 0;
int curOffset = 0;
while (true) {
if (offset <= curOffset) {
return curLine;
}
if (curOffset == text.length()) return -1;
char c = text.charAt(curOffset);
if (c == '\n') {
curLine++;
}
else if (c == '\r') {
curLine++;
if (curOffset < text.length() - 1 && text.charAt(curOffset + 1) == '\n') {
curOffset++;
}
}
curOffset++;
}
}
/**
* Classic dynamic programming algorithm for string differences.
*/
public static int difference(@NotNull String s1, @NotNull String s2) {
int[][] a = new int[s1.length()][s2.length()];
for (int i = 0; i < s1.length(); i++) {
a[i][0] = i;
}
for (int j = 0; j < s2.length(); j++) {
a[0][j] = j;
}
for (int i = 1; i < s1.length(); i++) {
for (int j = 1; j < s2.length(); j++) {
a[i][j] = Math.min(Math.min(a[i - 1][j - 1] + (s1.charAt(i) == s2.charAt(j) ? 0 : 1), a[i - 1][j] + 1), a[i][j - 1] + 1);
}
}
return a[s1.length() - 1][s2.length() - 1];
}
@NotNull public static String wordsToBeginFromUpperCase(@NotNull String s) {
StringBuffer buffer = null;
for (int i = 0; i < s.length(); i++) {
char prevChar = i == 0 ? ' ' : s.charAt(i - 1);
char currChar = s.charAt(i);
if (!Character.isLetterOrDigit(prevChar)) {
if (Character.isLetterOrDigit(currChar)) {
if (!Character.isUpperCase(currChar)) {
int j = i;
for (; j < s.length(); j++) {
if (!Character.isLetterOrDigit(s.charAt(j))) {
break;
}
}
if (!isPreposition(s, i, j - 1)) {
if (buffer == null) {
buffer = new StringBuffer(s);
}
buffer.setCharAt(i, toUpperCase(currChar));
}
}
}
}
}
if (buffer == null) {
return s;
}
else {
return buffer.toString();
}
}
@NonNls private static final String[] ourPrepositions =
new String[]{"at", "the", "and", "not", "if", "a", "or", "to", "in", "on", "into"};
public static boolean isPreposition(@NotNull String s, int firstChar, int lastChar) {
for (String preposition : ourPrepositions) {
boolean found = false;
if (lastChar - firstChar + 1 == preposition.length()) {
found = true;
for (int j = 0; j < preposition.length(); j++) {
if (!(toLowerCase(s.charAt(firstChar + j)) == preposition.charAt(j))) {
found = false;
}
}
}
if (found) {
return true;
}
}
return false;
}
public static void escapeStringCharacters(int length, final String str, @NotNull @NonNls StringBuilder buffer) {
for (int idx = 0; idx < length; idx++) {
char ch = str.charAt(idx);
switch (ch) {
case'\b':
buffer.append("\\b");
break;
case'\t':
buffer.append("\\t");
break;
case'\n':
buffer.append("\\n");
break;
case'\f':
buffer.append("\\f");
break;
case'\r':
buffer.append("\\r");
break;
case'\"':
buffer.append("\\\"");
break;
case'\\':
buffer.append("\\\\");
break;
default:
if (Character.isISOControl(ch)) {
String hexCode = Integer.toHexString(ch).toUpperCase();
buffer.append("\\u");
int paddingCount = 4 - hexCode.length();
while (paddingCount-- > 0) {
buffer.append(0);
}
buffer.append(hexCode);
}
else {
buffer.append(ch);
}
}
}
}
@NotNull public static String escapeStringCharacters(@NotNull String s) {
StringBuilder buffer = new StringBuilder();
escapeStringCharacters(s.length(), s, buffer);
return buffer.toString();
}
@NotNull public static String unescapeStringCharacters(@NotNull String s) {
StringBuilder buffer = new StringBuilder();
unescapeStringCharacters(s.length(), s, buffer);
return buffer.toString();
}
@NotNull public static String unquoteString( @NotNull String s )
{
if( s.length() > 1 && s.charAt( 0 ) == '"' && s.charAt( s.length() - 1) == '"' )
return s.substring( 1, s.length() - 1 );
else
return s;
}
private static void unescapeStringCharacters(int length, String s, StringBuilder buffer) {
boolean escaped = false;
for (int idx = 0; idx < length; idx++) {
char ch = s.charAt(idx);
if (!escaped) {
if (ch == '\\') {
escaped = true;
}
else {
buffer.append(ch);
}
}
else {
switch (ch) {
case'n':
buffer.append('\n');
break;
case'r':
buffer.append('\r');
break;
case'b':
buffer.append('\b');
break;
case't':
buffer.append('\t');
break;
case'f':
buffer.append('\f');
break;
case'\'':
buffer.append('\'');
break;
case'\"':
buffer.append('\"');
break;
case'\\':
buffer.append('\\');
break;
case'u':
if (idx + 4 < length) {
try {
int code = Integer.valueOf(s.substring(idx + 1, idx + 5), 16).intValue();
idx += 4;
buffer.append((char)code);
}
catch (NumberFormatException e) {
buffer.append("\\u");
}
}
else {
buffer.append("\\u");
}
break;
default:
buffer.append(ch);
break;
}
escaped = false;
}
}
if (escaped) buffer.append('\\');
}
@SuppressWarnings({"HardCodedStringLiteral"})
@NotNull public static String pluralize(@NotNull String suggestion) {
if (suggestion.endsWith("Child") || suggestion.endsWith("child")) {
return suggestion + "ren";
}
if (endsWithChar(suggestion, 's') || endsWithChar(suggestion, 'x') || suggestion.endsWith("ch")) {
return suggestion + "es";
}
int len = suggestion.length();
if (endsWithChar(suggestion, 'y') && len > 1 && !isVowel(suggestion.charAt(len - 2))) {
return suggestion.substring(0, len - 1) + "ies";
}
return suggestion + "s";
}
@NotNull public static String capitalizeWords(@NotNull String text, boolean allWords) {
StringTokenizer tokenizer = new StringTokenizer(text);
String out = "";
String delim = "";
boolean toCapitalize = true;
while (tokenizer.hasMoreTokens()) {
String word = tokenizer.nextToken();
out += delim + (toCapitalize ? capitalize(word) : word);
delim = " ";
if (!allWords) {
toCapitalize = false;
}
}
return out;
}
public static String decapitalize(String s) {
return Introspector.decapitalize(s);
}
public static boolean isVowel(char c) {
return VOWELS.indexOf(c) >= 0;
}
@NotNull public static String capitalize(@NotNull String s) {
if (s.length() == 0) return s;
if (s.length() == 1) return s.toUpperCase();
// Optimization
if (Character.isUpperCase(s.charAt(0)) ) return s;
return toUpperCase(s.charAt(0)) + s.substring(1);
}
public static int stringHashCode(CharSequence chars) {
if (chars instanceof String) return chars.hashCode();
if (chars instanceof CharSequenceWithStringHash) return chars.hashCode();
if (chars instanceof CharArrayCharSequence) return chars.hashCode();
int h = 0;
int to = chars.length();
for (int off = 0; off < to; off++) {
h = 31 * h + chars.charAt(off);
}
return h;
}
public static int stringHashCode(CharSequence chars, int from, int to) {
int h = 0;
for (int off = from; off < to; off++) {
h = 31 * h + chars.charAt(off);
}
return h;
}
public static int stringHashCode(char[] chars, int from, int to) {
int h = 0;
for (int off = from; off < to; off++) {
h = 31 * h + chars[off];
}
return h;
}
public static int stringHashCodeInsensitive(char[] chars, int from, int to) {
int h = 0;
for (int off = from; off < to; off++) {
h = 31 * h + toLowerCase(chars[off]);
}
return h;
}
public static int stringHashCodeInsensitive(CharSequence chars, int from, int to) {
int h = 0;
for (int off = from; off < to; off++) {
h = 31 * h + toLowerCase(chars.charAt(off));
}
return h;
}
public static int stringHashCodeInsensitive(@NotNull CharSequence chars) {
int h = 0;
final int len = chars.length();
for (int i = 0; i < len; i++) {
h = 31 * h + toLowerCase(chars.charAt(i));
}
return h;
}
@NotNull public static String trimEnd(@NotNull String s, @NonNls @NotNull String suffix) {
if (s.endsWith(suffix)) {
return s.substring(0, s.lastIndexOf(suffix));
}
return s;
}
public static boolean startsWithChar(@Nullable CharSequence s, char prefix) {
return s != null && s.length() != 0 && s.charAt(0) == prefix;
}
public static boolean endsWithChar(@Nullable CharSequence s, char suffix) {
return s != null && s.length() != 0 && s.charAt(s.length() - 1) == suffix;
}
@NotNull public static String trimStart(@NotNull String s, @NonNls @NotNull String prefix) {
if (s.startsWith(prefix)) {
return s.substring(prefix.length());
}
return s;
}
@NotNull public static String pluralize(@NotNull String base, int n) {
if (n == 1) return base;
return pluralize(base);
}
public static void repeatSymbol(Appendable buffer, char symbol, int times) {
try {
for (int i = 0; i < times; i++) {
buffer.append(symbol);
}
}
catch (IOException e) {
LOG.error(e);
}
}
public static boolean isNotEmpty(final String s) {
return s != null && s.length() > 0;
}
public static boolean isEmpty(final String s) {
return s == null || s.length() == 0;
}
@NotNull
public static String notNullize(final String s) {
return s == null ? "" : s;
}
public static boolean isEmptyOrSpaces(final String s) {
return s == null || s.trim().length() == 0;
}
public static String getThrowableText(final Throwable aThrowable) {
StringWriter stringWriter = new StringWriter();
PrintWriter writer = new PrintWriter(stringWriter);
aThrowable.printStackTrace(writer);
return stringWriter.getBuffer().toString();
}
public static String getThrowableText(final Throwable aThrowable, @NonNls @NotNull final String stackFrameSkipPattern) {
@NonNls final String prefix = "\tat ";
final String skipPattern = prefix + stackFrameSkipPattern;
final StringWriter stringWriter = new StringWriter();
final PrintWriter writer = new PrintWriter(stringWriter) {
boolean skipping = false;
public void println(final String x) {
if (x != null) {
if (!skipping && x.startsWith(skipPattern)) skipping = true;
else if (skipping && !x.startsWith(prefix)) skipping = false;
}
if (skipping) return;
super.println(x);
}
};
aThrowable.printStackTrace(writer);
return stringWriter.getBuffer().toString();
}
public static String getMessage(Throwable e) {
String result = e.getMessage();
@NonNls final String exceptionPattern = "Exception: ";
@NonNls final String errorPattern = "Error: ";
while ((result == null || result.contains(exceptionPattern) || result.contains(errorPattern)) && e.getCause() != null) {
e = e.getCause();
result = e.getMessage();
}
if (result != null) {
result = extractMessage(result, exceptionPattern);
result = extractMessage(result, errorPattern);
}
return result;
}
@NotNull private static String extractMessage(@NotNull String result, @NotNull final String errorPattern) {
if (result.lastIndexOf(errorPattern) >= 0) {
result = result.substring(result.lastIndexOf(errorPattern) + errorPattern.length());
}
return result;
}
@NotNull public static String repeatSymbol(final char aChar, final int count) {
final StringBuilder buffer = new StringBuilder();
repeatSymbol(buffer, aChar, count);
return buffer.toString();
}
@NotNull
public static List<String> splitHonorQuotes(@NotNull String s, char separator) {
final ArrayList<String> result = new ArrayList<String>();
final StringBuilder builder = new StringBuilder();
boolean inQuotes = false;
for (int i = 0; i < s.length(); i++) {
final char c = s.charAt(i);
if (c == separator && !inQuotes) {
if (builder.length() > 0) {
result.add(builder.toString());
builder.setLength(0);
}
continue;
}
if (c == '"' && !(i > 0 && s.charAt(i - 1) == '\\')) {
inQuotes = !inQuotes;
}
builder.append(c);
}
if (builder.length() > 0) {
result.add(builder.toString());
}
return result;
}
@NotNull public static List<String> split(@NotNull String s, @NotNull String separator) {
if (separator.length() == 0) {
return Collections.singletonList(s);
}
ArrayList<String> result = new ArrayList<String>();
int pos = 0;
while (true) {
int index = s.indexOf(separator, pos);
if (index == -1) break;
String token = s.substring(pos, index);
if (token.length() != 0) {
result.add(token);
}
pos = index + separator.length();
}
if (pos < s.length()) {
result.add(s.substring(pos, s.length()));
}
return result;
}
@NotNull
public static Iterable<String> tokenize(@NotNull String s, @NotNull String separators) {
final com.intellij.util.text.StringTokenizer tokenizer = new com.intellij.util.text.StringTokenizer(s, separators);
return new Iterable<String>() {
public Iterator<String> iterator() {
return new Iterator<String>() {
public boolean hasNext() {
return tokenizer.hasMoreTokens();
}
public String next() {
return tokenizer.nextToken();
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
@NotNull
public static List<String> getWordsIn(@NotNull String text) {
List<String> result = new SmartList<String>();
int start = -1;
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
boolean isIdentifierPart = Character.isJavaIdentifierPart(c);
if (isIdentifierPart && start == -1) {
start = i;
}
if (isIdentifierPart && i == text.length() - 1 && start != -1) {
result.add(text.substring(start, i + 1));
}
else if (!isIdentifierPart && start != -1) {
result.add(text.substring(start, i));
start = -1;
}
}
return result;
}
@NotNull public static String join(@NotNull final String[] strings, @NotNull final String separator) {
return join(strings, 0, strings.length, separator);
}
@NotNull public static String join(@NotNull final String[] strings, int startIndex, int endIndex, @NotNull final String separator) {
final StringBuilder result = new StringBuilder();
for (int i = startIndex; i < endIndex; i++) {
if (i > startIndex) result.append(separator);
result.append(strings[i]);
}
return result.toString();
}
@NotNull public static String[] zip(@NotNull String[] strings1, @NotNull String[] strings2, String separator) {
if (strings1.length != strings2.length) throw new IllegalArgumentException();
String[] result = new String[strings1.length];
for (int i = 0; i < result.length; i++) {
result[i] = strings1[i] + separator + strings2[i];
}
return result;
}
public static String[] surround(String[] strings1, String prefix, String suffix) {
String[] result = new String[strings1.length];
for (int i = 0; i < result.length; i++) {
result[i] = prefix + strings1[i] + suffix;
}
return result;
}
@NotNull public static <T> String join(@NotNull T[] items, @NotNull Function<T, String> f, @NotNull @NonNls String separator) {
return join(Arrays.asList(items), f, separator);
}
@NotNull public static <T> String join(@NotNull Iterable<T> items, @NotNull Function<T, String> f, @NotNull @NonNls String separator) {
final StringBuilder result = new StringBuilder();
for (T item : items) {
String string = f.fun(item);
if (string != null && string.length() != 0) {
if (result.length() != 0) result.append(separator);
result.append(string);
}
}
return result.toString();
}
@NotNull public static String join(@NotNull Collection<String> strings, @NotNull final String separator) {
final StringBuilder result = new StringBuilder();
for (String string : strings) {
if (string != null && string.length() != 0) {
if (result.length() != 0) result.append(separator);
result.append(string);
}
}
return result.toString();
}
@NotNull public static String join(@NotNull final int[] strings, @NotNull final String separator) {
final StringBuilder result = new StringBuilder();
for (int i = 0; i < strings.length; i++) {
if (i > 0) result.append(separator);
result.append(strings[i]);
}
return result.toString();
}
@NotNull public static String stripQuotesAroundValue(@NotNull String text) {
if (startsWithChar(text, '\"') || startsWithChar(text, '\'')) text = text.substring(1);
if (endsWithChar(text, '\"') || endsWithChar(text, '\'')) text = text.substring(0, text.length() - 1);
return text;
}
public static boolean isQuotedString(@NotNull String text) {
return startsWithChar(text, '\"') && endsWithChar(text, '\"')
|| startsWithChar(text, '\'') && endsWithChar(text, '\'');
}
/**
* Formats the specified file size as a string.
*
* @param fileSize the size to format.
* @return the size formatted as a string.
* @since 5.0.1
*/
@NotNull public static String formatFileSize(final long fileSize) {
if (fileSize < 0x400) {
return CommonBundle.message("file.size.format.bytes", fileSize);
}
if (fileSize < 0x100000) {
long kbytes = fileSize * 100 / 1024;
final String kbs = kbytes / 100 + "." + kbytes % 100;
return CommonBundle.message("file.size.format.kbytes", kbs);
}
long mbytes = fileSize * 100 / 1024 / 1024;
final String size = mbytes / 100 + "." + mbytes % 100;
return CommonBundle.message("file.size.format.mbytes", size);
}
/**
* Returns unpluralized variant using English based heuristics like properties -> property, names -> name, children -> child.
* Returns <code>null</code> if failed to match appropriate heuristic.
*
* @param name english word in plural form
* @return name in singular form or <code>null</code> if failed to find one.
*/
@SuppressWarnings({"HardCodedStringLiteral"})
@Nullable
public static String unpluralize(@NotNull final String name) {
if (name.endsWith("sses") || name.endsWith("shes") || name.endsWith("ches") || name.endsWith("xes")) { //?
return name.substring(0, name.length() - 2);
}
if (name.endsWith("ses")) {
return name.substring(0, name.length() - 1);
}
if (name.endsWith("ies")) {
return name.substring(0, name.length() - 3) + "y";
}
String result = stripEnding(name, "s");
if (result != null) {
return result;
}
if (name.endsWith("children")) {
return name.substring(0, name.length() - "children".length()) + "child";
}
if (name.endsWith("Children") && name.length() > "Children".length()) {
return name.substring(0, name.length() - "Children".length()) + "Child";
}
return null;
}
private static String stripEnding(String name, String ending) {
if (name.endsWith(ending)) {
if (name.equals(ending)) return name; // do not return empty string
return name.substring(0, name.length() - 1);
}
return null;
}
public static boolean containsAlphaCharacters(@NotNull String value) {
for (int i = 0; i < value.length(); i++) {
if (Character.isLetter(value.charAt(i))) return true;
}
return false;
}
public static String firstLetterToUpperCase(final String displayString) {
if (displayString == null || displayString.length() == 0) return displayString;
char firstChar = displayString.charAt(0);
char uppedFirstChar = toUpperCase(firstChar);
if (uppedFirstChar == firstChar) return displayString;
StringBuilder builder = new StringBuilder(displayString);
builder.setCharAt(0, uppedFirstChar);
return builder.toString();
}
/**
* Strip out all characters not accepted by given filter
* @param s e.g. "/n my string "
* @param filter e.g. {@link CharFilter#NOT_WHITESPACE_FILTER}
* @return stripped string e.g. "mystring"
*/
@NotNull public static String strip(@NotNull final String s, @NotNull CharFilter filter) {
StringBuilder result = new StringBuilder(s.length());
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (filter.accept(ch)) {
result.append(ch);
}
}
return result.toString();
}
/**
* Find position of the first charachter accepted by given filter
* @param s the string to search
* @param filter
* @return position of the first charachter accepted or -1 if not found
*/
public static int findFirst(@NotNull final String s, @NotNull CharFilter filter) {
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (filter.accept(ch)) {
return i;
}
}
return -1;
}
@NotNull public static String replaceSubstring(@NotNull String string, @NotNull TextRange range, @NotNull String replacement) {
return string.substring(0, range.getStartOffset()) + replacement + string.substring(range.getEndOffset());
}
public static boolean startsWith(@NotNull CharSequence text, @NotNull CharSequence prefix) {
int l1 = text.length();
int l2 = prefix.length();
if (l1 < l2) return false;
for (int i = 0; i < l2; i++) {
if (text.charAt(i) != prefix.charAt(i)) return false;
}
return true;
}
public static boolean endsWith(@NotNull CharSequence text, @NotNull CharSequence suffix) {
int l1 = text.length();
int l2 = suffix.length();
if (l1 < l2) return false;
for (int i = l1-1; i >= l1-l2; i--) {
if (text.charAt(i) != suffix.charAt(i+l2-l1)) return false;
}
return true;
}
@NotNull
public static String commonPrefix(@NotNull String s1, @NotNull String s2) {
int i;
for (i = 0; i<s1.length() && i<s2.length(); i++) {
if (s1.charAt(i) != s2.charAt(i)) {
break;
}
}
return s1.substring(0, i);
}
@NotNull
public static String commonSuffix(@NotNull String s1, @NotNull String s2) {
if (s1.length() == 0 || s2.length() == 0) return "";
int i;
for (i = s1.length()-1; i>=0 && i>=s1.length() - s2.length(); i--) {
if (s1.charAt(i) != s2.charAt(i+s2.length()-s1.length())) {
break;
}
}
return s1.substring(i, s1.length());
}
public static int indexOf(CharSequence s, char c) {
int l = s.length();
for (int i = 0; i < l; i++) {
if (s.charAt(i) == c) return i;
}
return -1;
}
public static String first(final String text, final int length, final boolean appendEllipsis) {
return text.length() > length ? text.substring(0, length) + (appendEllipsis ? "..." : "") : text;
}
public static String escapeQuotes(@NotNull final String str) {
int idx = str.indexOf('"');
if (idx < 0) return str;
StringBuilder buf = new StringBuilder(str);
while (idx < buf.length()) {
if (buf.charAt(idx) == '"') {
buf.replace(idx, idx + 1, "\\\"");
idx += 2;
}
else {
idx += 1;
}
}
return buf.toString();
}
@NonNls private static final String[] REPLACES_REFS = new String[]{"<", " ", ">", "&", "'", """};
@NonNls private static final String[] REPLACES_DISP = new String[]{"<", "\u00a0", ">", "&", "'", "\""};
public static String unescapeXml(final String text) {
if (text == null) return null;
return replace(text, REPLACES_REFS, REPLACES_DISP);
}
public static String escapeXml(final String text) {
if (text == null) return null;
return replace(text, REPLACES_DISP, REPLACES_REFS);
}
public static String escapeToRegexp(String text) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < text.length(); i++) {
final char c = text.charAt(i);
if (c == ' ' || Character.isLetter(c) || Character.isDigit(c)) {
result.append(c);
}
else {
result.append('\\').append(c);
}
}
return result.toString();
}
private static String replace(final String text, final String[] from, final String[] to) {
final StringBuilder result = new StringBuilder(text.length());
replace:
for (int i = 0; i < text.length(); i++) {
for (int j = 0; j < from.length; j += 1) {
String toReplace = from[j];
String replaceWith = to[j];
final int len = toReplace.length();
if (text.regionMatches(i, toReplace, 0, len)) {
result.append(replaceWith);
i += len - 1;
continue replace;
}
}
result.append(text.charAt(i));
}
return result.toString();
}
public static String[] filterEmptyStrings(String[] strings) {
int emptyCount = 0;
for (String string : strings) {
if (string == null || string.length() == 0) emptyCount++;
}
if (emptyCount == 0) return strings;
String[] result = new String[strings.length - emptyCount];
int count = 0;
for (String string : strings) {
if (string == null || string.length() == 0) continue;
result[count++] = string;
}
return result;
}
public static int countNewLines(final CharSequence text) {
int lineShift = 0;
for(int i = 0; i < text.length(); ++i) {
final char ch = text.charAt(i);
if (ch == '\n') {
++lineShift;
}
}
return lineShift;
}
public static String capitalsOnly(String s) {
StringBuilder b = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
if (Character.isUpperCase(s.charAt(i))) {
b.append(s.charAt(i));
}
}
return b.toString();
}
// returns null if any of args is null
@Nullable
public static String joinOrNull(@NotNull String... args) {
StringBuilder r = new StringBuilder();
for (String arg : args) {
if (arg == null) return null;
r.append(arg);
}
return r.toString();
}
public static String getPropertyName(@NonNls final String methodName) {
if (methodName.startsWith("get")) {
return Introspector.decapitalize(methodName.substring(3));
}
else if (methodName.startsWith("is")) {
return Introspector.decapitalize(methodName.substring(2));
}
else if (methodName.startsWith("set")) {
return Introspector.decapitalize(methodName.substring(3));
}
else {
return null;
}
}
public static boolean isJavaIdentifierStart(char c) {
return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || Character.isJavaIdentifierStart(c);
}
public static boolean isJavaIdentifierPart(char c) {
return c >= '0' && c <= '9' || isJavaIdentifierStart(c);
}
public static boolean isJavaIdentifier(String text) {
int len = text.length();
if (len == 0) return false;
if (!isJavaIdentifierStart(text.charAt(0))) return false;
for (int i = 1; i < len; i++) {
if (!isJavaIdentifierPart(text.charAt(i))) return false;
}
return true;
}
}
|
script support
execute current statement action
|
util/src/com/intellij/openapi/util/text/StringUtil.java
|
script support execute current statement action
|
<ide><path>til/src/com/intellij/openapi/util/text/StringUtil.java
<ide> continue;
<ide> }
<ide>
<del> if (c == '"' && !(i > 0 && s.charAt(i - 1) == '\\')) {
<add> if ((c == '"' || c == '\'') && !(i > 0 && s.charAt(i - 1) == '\\')) {
<ide> inQuotes = !inQuotes;
<ide> }
<ide> builder.append(c);
|
|
JavaScript
|
mit
|
d5ce9d635800fc8cc208ccdc5a871c5f2089be22
| 0 |
nodeGame/nodegame-client
|
/**
* # GamePlot
* Copyright(c) 2020 Stefano Balietti
* MIT Licensed
*
* Wraps a stager and exposes methods to navigate through the sequence
*
* TODO: previousStage
*/
(function(exports, parent) {
"use strict";
// ## Global scope
exports.GamePlot = GamePlot;
var GameStage = parent.GameStage;
var J = parent.JSUS;
// ## Constants
GamePlot.GAMEOVER = 'NODEGAME_GAMEOVER';
GamePlot.END_SEQ = 'NODEGAME_END_SEQ';
GamePlot.NO_SEQ = 'NODEGAME_NO_SEQ';
/**
* ## GamePlot constructor
*
* Creates a new instance of GamePlot
*
* Takes a sequence object created with Stager.
*
* If the Stager parameter has an empty sequence, flexible mode is assumed
* (used by e.g. GamePlot.next).
*
* @param {NodeGameClient} node Reference to current node object
* @param {Stager} stager Optional. The Stager object.
*
* @see Stager
*/
function GamePlot(node, stager) {
// ## GamePlot Properties
/**
* ### GamePlot.node
*
* Reference to the node object
*/
this.node = node;
/**
* ### GamePlot.stager
*
* The stager object used to perform stepping operations
*/
this.stager = null;
/**
* ### GamePlot.cache
*
* Caches the value of previously fetched properties per game stage
*/
this.cache = {};
/**
* ### GamePlot.tmpCache
*
* Handles a temporary cache for properties of current step
*
* If set, properties are served first by the `getProperty` method.
* This cache is deleted each time a step is done.
* Used, for example, to reset some properties upon reconnect.
*
* Defined two additional methods:
*
* - tmpCache.hasOwnProperty
* - tmpCache.clear
*
* @param {string} prop the name of the property to retrieve or set
* @param {mixed} value The value of property to set
*
* @return {mixed} The current value of the property
*/
this.tmpCache = (function() {
var tmpCache, handler;
tmpCache = {};
handler = function(prop, value) {
if ('undefined' === typeof prop) {
return tmpCache;
}
else if ('string' === typeof prop) {
if (arguments.length === 1) return tmpCache[prop];
tmpCache[prop] = value;
return value;
}
throw new TypeError('GamePlot.tmpCache: prop must be ' +
'string. Found: ' + prop);
};
handler.clear = function() {
var tmp;
tmp = tmpCache;
tmpCache = {};
return tmp;
};
handler.hasOwnProperty = function(prop) {
if ('string' !== typeof prop) {
throw new TypeError('GamePlot.tmpCache.hasProperty: ' +
'prop must be string. Found: ' +
prop);
}
return tmpCache.hasOwnProperty(prop);
};
return handler;
})();
/**
* ### GamePlot._normalizedCache
*
* Caches the value of previously normalized Game Stages objects.
*
* @api private
*/
this._normalizedCache = {};
this.init(stager);
}
// ## GamePlot methods
/**
* ### GamePlot.init
*
* Initializes the GamePlot with a stager
*
* Clears the cache also.
*
* @param {Stager} stager Optional. The Stager object.
*
* @see Stager
*/
GamePlot.prototype.init = function(stager) {
if (stager) {
if ('object' !== typeof stager) {
throw new Error('GamePlot.init: called with invalid stager.');
}
this.stager = stager;
}
else {
this.stager = null;
}
this.cache = {};
this.tmpCache.clear();
};
/**
* ### GamePlot.next
*
* Returns the next step in the sequence
*
* If the step in `curStage` is an integer and out of bounds,
* that bound is assumed.
*
* // TODO: previousStage
*
* @param {GameStage} curStage The GameStage of reference
* @param {bolean} execLoops Optional. If true, loop and doLoop
* conditional function will be executed to determine next stage.
* If false, null will be returned if the next stage depends
* on the execution of the loop/doLoop conditional function.
* Default: true.
*
* @return {GameStage|string} The GameStage after _curStage_
*
* @see GameStage
*/
GamePlot.prototype.nextStage = function(curStage, execLoops) {
var seqObj, stageObj;
var stageNo, stepNo, steps;
var normStage, nextStage;
var flexibleMode;
// GamePlot was not correctly initialized.
if (!this.stager) return GamePlot.NO_SEQ;
flexibleMode = this.isFlexibleMode();
if (flexibleMode) {
// TODO. What does next stage mean in flexible mode?
// Calling the next cb of the last step? A separate cb?
console.log('***GamePlot.nextStage: method not available in ' +
'flexible mode.***');
return null;
}
// Standard Mode.
else {
// Get normalized GameStage:
// makes sures stage is with numbers and not strings.
normStage = this.normalizeGameStage(curStage);
if (normStage === null) {
this.node.silly('GamePlot.nextStage: invalid stage: ' +
curStage);
return null;
}
stageNo = normStage.stage;
if (stageNo === 0) {
return new GameStage({
stage: 1,
step: 1,
round: 1
});
}
seqObj = this.stager.sequence[stageNo - 1];
if (seqObj.type === 'gameover') return GamePlot.GAMEOVER;
execLoops = 'undefined' === typeof execLoops ? true : execLoops;
// Get stage object.
stageObj = this.stager.stages[seqObj.id];
// Go to next stage.
if (stageNo < this.stager.sequence.length) {
seqObj = this.stager.sequence[stageNo];
// Return null if a loop is found and can't be executed.
if (!execLoops && seqObj.type === 'loop') return null;
// Skip over loops if their callbacks return false:
while (seqObj.type === 'loop' &&
!seqObj.cb.call(this.node.game)) {
stageNo++;
if (stageNo >= this.stager.sequence.length) {
return GamePlot.END_SEQ;
}
// Update seq object.
seqObj = this.stager.sequence[stageNo];
}
// Handle gameover:
if (this.stager.sequence[stageNo].type === 'gameover') {
return GamePlot.GAMEOVER;
}
return new GameStage({
stage: stageNo + 1,
step: 1,
round: 1
});
}
// No more stages remaining:
return GamePlot.END_SEQ;
}
};
/**
* ### GamePlot.next
*
* Returns the next step in the sequence
*
* If the step in `curStage` is an integer and out of bounds,
* that bound is assumed.
*
* @param {GameStage} curStage The GameStage of reference
* @param {bolean} execLoops Optional. If true, loop and doLoop
* conditional function will be executed to determine next stage.
* If false, null will be returned if the next stage depends
* on the execution of the loop/doLoop conditional function.
* Default: true.
*
* @return {GameStage|string} The GameStage after _curStage_
*
* @see GameStage
*/
GamePlot.prototype.next = function(curStage, execLoops) {
var seqObj, stageObj;
var stageNo, stepNo, steps;
var normStage, nextStage;
var flexibleMode;
// GamePlot was not correctly initialized.
if (!this.stager) return GamePlot.NO_SEQ;
// Init variables.
seqObj = null, stageObj = null, normStage = null, nextStage = null;
// Find out flexibility mode.
flexibleMode = this.isFlexibleMode();
if (flexibleMode) {
curStage = new GameStage(curStage);
if (curStage.stage === 0) {
// Get first stage:
if (this.stager.generalNextFunction) {
nextStage = this.stager.generalNextFunction();
}
if (nextStage) {
return new GameStage({
stage: nextStage,
step: 1,
round: 1
});
}
return GamePlot.END_SEQ;
}
// Get stage object:
stageObj = this.stager.stages[curStage.stage];
if ('undefined' === typeof stageObj) {
throw new Error('Gameplot.next: received non-existent stage: ' +
curStage.stage);
}
// Find step number:
if ('number' === typeof curStage.step) {
stepNo = curStage.step;
}
else {
stepNo = stageObj.steps.indexOf(curStage.step) + 1;
}
if (stepNo < 1) {
throw new Error('GamePlot.next: received non-existent step: ' +
stageObj.id + '.' + curStage.step);
}
// Handle stepping:
if (stepNo + 1 <= stageObj.steps.length) {
return new GameStage({
stage: stageObj.id,
step: stepNo + 1,
round: 1
});
}
// Get next stage:
if (this.stager.nextFunctions[stageObj.id]) {
nextStage = this.stager.nextFunctions[stageObj.id]();
}
else if (this.stager.generalNextFunction) {
nextStage = this.stager.generalNextFunction();
}
// If next-deciding function returns GamePlot.GAMEOVER,
// consider it game over.
if (nextStage === GamePlot.GAMEOVER) {
return GamePlot.GAMEOVER;
}
else if (nextStage) {
return new GameStage({
stage: nextStage,
step: 1,
round: 1
});
}
return GamePlot.END_SEQ;
}
// Standard Mode.
else {
// Get normalized GameStage:
// makes sures stage is with numbers and not strings.
normStage = this.normalizeGameStage(curStage);
if (normStage === null) {
this.node.silly('GamePlot.next: invalid stage: ' + curStage);
return null;
}
stageNo = normStage.stage;
if (stageNo === 0) {
return new GameStage({
stage: 1,
step: 1,
round: 1
});
}
stepNo = normStage.step;
seqObj = this.stager.sequence[stageNo - 1];
if (seqObj.type === 'gameover') return GamePlot.GAMEOVER;
execLoops = 'undefined' === typeof execLoops ? true : execLoops;
// Get stage object.
stageObj = this.stager.stages[seqObj.id];
steps = seqObj.steps;
// Handle stepping:
if (stepNo + 1 <= steps.length) {
return new GameStage({
stage: stageNo,
step: stepNo + 1,
round: normStage.round
});
}
// Handle repeat block:
if (seqObj.type === 'repeat' && normStage.round + 1 <= seqObj.num) {
return new GameStage({
stage: stageNo,
step: 1,
round: normStage.round + 1
});
}
// Handle looping blocks:
if (seqObj.type === 'doLoop' || seqObj.type === 'loop') {
// Return null if a loop is found and can't be executed.
if (!execLoops) return null;
// Call loop function. True means continue loop.
if (seqObj.cb.call(this.node.game)) {
return new GameStage({
stage: stageNo,
step: 1,
round: normStage.round + 1
});
}
}
// Go to next stage.
if (stageNo < this.stager.sequence.length) {
seqObj = this.stager.sequence[stageNo];
// Return null if a loop is found and can't be executed.
if (!execLoops && seqObj.type === 'loop') return null;
// Skip over loops if their callbacks return false:
while (seqObj.type === 'loop' &&
!seqObj.cb.call(this.node.game)) {
stageNo++;
if (stageNo >= this.stager.sequence.length) {
return GamePlot.END_SEQ;
}
// Update seq object.
seqObj = this.stager.sequence[stageNo];
}
// Handle gameover:
if (this.stager.sequence[stageNo].type === 'gameover') {
return GamePlot.GAMEOVER;
}
return new GameStage({
stage: stageNo + 1,
step: 1,
round: 1
});
}
// No more stages remaining:
return GamePlot.END_SEQ;
}
};
/**
* ### GamePlot.previous
*
* Returns the previous step in the sequence
*
* Works only in simple mode.
*
* Previous of 0.0.0 is 0.0.0.
*
* @param {GameStage} curStage The GameStage of reference
* @param {bolean} execLoops Optional. If true, loop and doLoop
* conditional function will be executed to determine previous stage.
* If false, null will be returned if the previous stage depends
* on the execution of the loop/doLoop conditional function.
* Default: true.
*
* @return {GameStage|null} The GameStage before _curStage_, or null
* if _curStage_ is invalid.
*
* @see GameStage
*/
GamePlot.prototype.previous = function(curStage, execLoops) {
var normStage;
var seqObj, stageObj;
var prevSeqObj;
var stageNo, stepNo, prevStepNo;
// GamePlot was not correctly initialized.
if (!this.stager) return GamePlot.NO_SEQ;
seqObj = null, stageObj = null;
// Get normalized GameStage (calls GameStage constructor).
normStage = this.normalizeGameStage(curStage);
if (normStage === null) {
this.node.warn('GamePlot.previous: invalid stage: ' + curStage);
return null;
}
stageNo = normStage.stage;
// Already 0.0.0, there is nothing before.
if (stageNo === 0) return new GameStage();
stepNo = normStage.step;
seqObj = this.stager.sequence[stageNo - 1];
execLoops = 'undefined' === typeof execLoops ? true : execLoops;
// Within same stage.
// Handle stepping.
if (stepNo > 1) {
return new GameStage({
stage: stageNo,
step: stepNo - 1,
round: normStage.round
});
}
// Handle rounds:
if (normStage.round > 1) {
return new GameStage({
stage: stageNo,
step: seqObj.steps.length,
round: normStage.round - 1
});
}
// Handle beginning (0.0.0).
if (stageNo === 1) return new GameStage();
// Go to previous stage.
// Get previous sequence object:
prevSeqObj = this.stager.sequence[stageNo - 2];
// Return null if a loop is found and can't be executed.
if (!execLoops && seqObj.type === 'loop') return null;
// Skip over loops if their callbacks return false:
while (prevSeqObj.type === 'loop' &&
!prevSeqObj.cb.call(this.node.game)) {
stageNo--;
// (0.0.0).
if (stageNo <= 1) return new GameStage();
// Update seq object.
prevSeqObj = this.stager.sequence[stageNo - 2];
}
// Get number of steps in previous stage:
prevStepNo = prevSeqObj.steps.length;
// Handle repeat block:
if (prevSeqObj.type === 'repeat') {
return new GameStage({
stage: stageNo - 1,
step: prevStepNo,
round: prevSeqObj.num
});
}
// Handle normal blocks:
return new GameStage({
stage: stageNo - 1,
step: prevStepNo,
round: 1
});
};
/**
* ### GamePlot.jump
*
* Returns a distant stage in the stager
*
* Works with negative delta only in simple mode.
*
* Uses `GamePlot.previous` and `GamePlot.next` for stepping.
*
* @param {GameStage} curStage The GameStage of reference
* @param {number} delta The offset. Negative number for backward stepping.
* @param {bolean} execLoops Optional. If true, loop and doLoop
* conditional function will be executed to determine next stage.
* If false, null will be returned when a loop or doLoop is found
* and more evaluations are still required. Default: true.
*
* @return {GameStage|string|null} The distant game stage
*
* @see GameStage
* @see GamePlot.previous
* @see GamePlot.next
*/
GamePlot.prototype.jump = function(curStage, delta, execLoops) {
var stageType;
execLoops = 'undefined' === typeof execLoops ? true : execLoops;
if (delta < 0) {
while (delta < 0) {
curStage = this.previous(curStage, execLoops);
if (!(curStage instanceof GameStage) || curStage.stage === 0) {
return curStage;
}
delta++;
if (!execLoops) {
// If there are more steps to jump, check if we have loops.
stageType = this.stager.sequence[curStage.stage -1].type;
if (stageType === 'loop') {
if (delta < 0) return null;
}
else if (stageType === 'doLoop') {
if (delta < -1) return null;
else return curStage;
}
}
}
}
else {
while (delta > 0) {
curStage = this.next(curStage, execLoops);
// If we find a loop return null.
if (!(curStage instanceof GameStage)) return curStage;
delta--;
if (!execLoops) {
// If there are more steps to jump, check if we have loops.
stageType = this.stager.sequence[curStage.stage -1].type;
if (stageType === 'loop' || stageType === 'doLoop') {
if (delta > 0) return null;
else return curStage;
}
}
}
}
return curStage;
};
/**
* ### GamePlot.stepsToNextStage
*
* Returns the number of steps to reach the next stage
*
* By default, each stage repetition is considered as a new stage.
*
* @param {GameStage|string} gameStage The reference step
* @param {boolean} countRepeat If TRUE stage repetitions are
* considered as current stage, and included in the count. Default: FALSE.
*
* @return {number|null} The number of steps including current one,
* or NULL on error.
*
* @see GamePlot.normalizeGameStage
*/
GamePlot.prototype.stepsToNextStage = function(gameStage, countRepeat) {
var seqObj, totSteps, stepNo;
if (!this.stager) return null;
// Checks stage and step ranges.
gameStage = this.normalizeGameStage(gameStage);
if (!gameStage) return null;
if (gameStage.stage === 0) return 1;
seqObj = this.getSequenceObject(gameStage);
if (!seqObj) return null;
stepNo = gameStage.step;
totSteps = seqObj.steps.length;
if (countRepeat) {
if (seqObj.type === 'repeat') {
if (gameStage.round > 1) {
stepNo = ((gameStage.round-1) * totSteps) + stepNo;
}
totSteps = totSteps * seqObj.num;
}
else if (seqObj.type === 'loop' || seqObj.type === 'doLoop') {
return null;
}
}
return 1 + totSteps - stepNo;
};
// TODO: remove in next version.
GamePlot.prototype.stepsToPreviousStage = function(gameStage) {
console.log('GamePlot.stepsToPreviousStage is **deprecated**. Use' +
'GamePlot.stepsFromPreviousStage instead.');
return this.stepsFromPreviousStage(gameStage);
};
/**
* ### GamePlot.stepsFromPreviousStage
*
* Returns the number of steps passed from the previous stage
*
* By default, each stage repetition is considered as a new stage.
*
* @param {GameStage|string} gameStage The reference step
* @param {boolean} countRepeat If TRUE stage repetitions are
* considered as current stage, and included in the count. Default: FALSE.
*
* @return {number|null} The number of steps including current one, or
* NULL on error.
*
* @see GamePlot.normalizeGameStage
*/
GamePlot.prototype.stepsFromPreviousStage = function(gameStage,
countRepeat) {
var seqObj, stepNo;
if (!this.stager) return null;
// Checks stage and step ranges.
gameStage = this.normalizeGameStage(gameStage);
if (!gameStage || gameStage.stage === 0) return null;
seqObj = this.getSequenceObject(gameStage);
if (!seqObj) return null;
stepNo = gameStage.step;
if (countRepeat) {
if (seqObj.type === 'repeat') {
if (gameStage.round > 1) {
stepNo = (seqObj.steps.length * (gameStage.round-1)) +
stepNo;
}
}
else if (seqObj.type === 'loop' || seqObj.type === 'doLoop') {
return null;
}
}
return stepNo;
};
/**
* ### GamePlot.getSequenceObject
*
* Returns the sequence object corresponding to a GameStage
*
* @param {GameStage|string} gameStage The GameStage object,
* or its string representation
*
* @return {object|null} The corresponding sequence object,
* or NULL if not found
*/
GamePlot.prototype.getSequenceObject = function(gameStage) {
if (!this.stager) return null;
gameStage = this.normalizeGameStage(gameStage);
return gameStage ? this.stager.sequence[gameStage.stage - 1] : null;
};
/**
* ### GamePlot.getStage
*
* Returns the stage object corresponding to a GameStage
*
* @param {GameStage|string} gameStage The GameStage object,
* or its string representation
*
* @return {object|null} The corresponding stage object, or NULL
* if the step was not found
*/
GamePlot.prototype.getStage = function(gameStage) {
var stageObj;
if (!this.stager) return null;
gameStage = this.normalizeGameStage(gameStage);
if (gameStage) {
stageObj = this.stager.sequence[gameStage.stage - 1];
stageObj = stageObj ? this.stager.stages[stageObj.id] : null;
}
return stageObj || null;
};
/**
* ### GamePlot.getStep
*
* Returns the step object corresponding to a GameStage
*
* @param {GameStage|string} gameStage The GameStage object,
* or its string representation
*
* @return {object|null} The corresponding step object, or NULL
* if the step was not found
*/
GamePlot.prototype.getStep = function(gameStage) {
var seqObj, stepObj;
if (!this.stager) return null;
// Game stage is normalized inside getSequenceObject.
seqObj = this.getSequenceObject(gameStage);
if (seqObj) {
stepObj = this.stager.steps[seqObj.steps[gameStage.step - 1]];
}
return stepObj || null;
};
/**
* ### GamePlot.getStepRule
*
* Returns the step-rule function for a given game-stage
*
* Otherwise, the order of lookup is:
*
* 1. step object
* 2. stage object
* 3. default property
* 4. default step-rule of the Stager object
*
* @param {GameStage|string} gameStage The GameStage object,
* or its string representation
*
* @return {function} The step-rule function or the default rule
*
* @see Stager.getDefaultStepRule
*/
GamePlot.prototype.getStepRule = function(gameStage) {
var rule;
rule = this.getProperty(gameStage, 'stepRule');
if ('string' === typeof rule) rule = parent.stepRules[rule];
return rule || this.stager.getDefaultStepRule();
};
/**
* ### GamePlot.getGlobal
*
* Looks up the value of a global variable
*
* Looks for definitions of a global variable in
*
* 1. the globals property of the step object of the given gameStage,
*
* 2. the globals property of the stage object of the given gameStage,
*
* 3. the defaults, defined in the Stager.
*
* @param {GameStage|string} gameStage The GameStage object,
* or its string representation
* @param {string} globalVar The name of the global variable
*
* @return {mixed|null} The value of the global variable if found,
* NULL otherwise.
*/
GamePlot.prototype.getGlobal = function(gameStage, globalVar) {
var stepObj, stageObj;
var stepGlobals, stageGlobals, defaultGlobals;
gameStage = new GameStage(gameStage);
// Look in current step:
stepObj = this.getStep(gameStage);
if (stepObj) {
stepGlobals = stepObj.globals;
if (stepGlobals && stepGlobals.hasOwnProperty(globalVar)) {
return stepGlobals[globalVar];
}
}
// Look in current stage:
stageObj = this.getStage(gameStage);
if (stageObj) {
stageGlobals = stageObj.globals;
if (stageGlobals && stageGlobals.hasOwnProperty(globalVar)) {
return stageGlobals[globalVar];
}
}
// Look in Stager's defaults:
if (this.stager) {
defaultGlobals = this.stager.getDefaultGlobals();
if (defaultGlobals && defaultGlobals.hasOwnProperty(globalVar)) {
return defaultGlobals[globalVar];
}
}
// Not found:
return null;
};
/**
* ### GamePlot.getGlobals
*
* Looks up and build the _globals_ object for the specified game stage
*
* Globals properties are mixed in at each level (defaults, stage, step)
* to form the complete set of globals available for the specified
* game stage.
*
* @param {GameStage|string} gameStage The GameStage object,
* or its string representation
*
* @return {object} The _globals_ object for the specified game stage
*/
GamePlot.prototype.getGlobals = function(gameStage) {
var stepstage, globals;
if ('string' !== typeof gameStage && 'object' !== typeof gameStage) {
throw new TypeError('GamePlot.getGlobals: gameStage must be ' +
'string or object.');
}
globals = {};
// No stager found, no globals!
if (!this.stager) return globals;
// Look in Stager's defaults:
J.mixin(globals, this.stager.getDefaultGlobals());
// Look in current stage:
stepstage = this.getStage(gameStage);
if (stepstage) J.mixin(globals, stepstage.globals);
// Look in current step:
stepstage = this.getStep(gameStage);
if (stepstage) J.mixin(globals, stepstage.globals);
return globals;
};
/**
* ### GamePlot.getProperty
*
* Looks up the value of a property in a hierarchy of lookup locations
*
* The hierarchy of lookup locations is:
*
* 1. the temporary cache, if game stage equals current game stage
* 2. the game plot cache
* 3. the step object of the given gameStage,
* 4. the stage object of the given gameStage,
* 5. the defaults, defined in the Stager.
*
* @param {GameStage|string} gameStage The GameStage object,
* or its string representation
* @param {string} prop The name of the property
* @param {mixed} notFound Optional. A value to return if
* property is not found. Default: NULL
* @param {object} mask Optional. An object disabling specific lookup
* locations. Default:
* ```
* { tmpCache: false, cache: false, step: false, stage: false, game: false }
* ```
*
* @return {mixed|null} The value of the property if found, NULL otherwise.
*
* @see GamePlot.cache
*/
GamePlot.prototype.getProperty = function(gameStage, prop, notFound, mask) {
var stepObj, stageObj, defaultProps, found, res;
if ('string' !== typeof prop) {
throw new TypeError('GamePlot.getProperty: property must be ' +
'string. Found: ' + prop);
}
gameStage = new GameStage(gameStage);
mask = mask || {};
if ('object' !== typeof mask) {
throw new TypeError('GamePlot.getProperty: mask must be ' +
'object or undefined. Found: ' + mask);
}
// Look in the tmpCache (cleared every step).
if (!mask.tmpCache && this.tmpCache.hasOwnProperty(prop) &&
GameStage.compare(gameStage,this.node.player.stage) === 0) {
return this.tmpCache(prop);
}
// Look in the main cache (this persists over steps).
if (!mask.tmpCache && this.cache[gameStage] &&
this.cache[gameStage].hasOwnProperty(prop)) {
return this.cache[gameStage][prop];
}
// Look in current step.
if (!mask.step) {
stepObj = this.getStep(gameStage);
if (stepObj && stepObj.hasOwnProperty(prop)) {
res = stepObj[prop];
found = true;
}
}
// Look in current stage.
if (!found && !mask.stage) {
stageObj = this.getStage(gameStage);
if (stageObj && stageObj.hasOwnProperty(prop)) {
res = stageObj[prop];
found = true;
}
}
// Look in Stager's defaults.
if (!found && !mask.game && this.stager) {
defaultProps = this.stager.getDefaultProperties();
if (defaultProps && defaultProps.hasOwnProperty(prop)) {
res = defaultProps[prop];
found = true;
}
}
// Cache it and return it.
if (found) {
cacheStepProperty(this, gameStage, prop, res);
return res;
}
// Return notFound.
return 'undefined' === typeof notFound ? null : notFound;
};
/**
* ### GamePlot.updateProperty
*
* Looks up a property and updates it to the new value
*
* Look up follows the steps described in _GamePlot.getProperty_,
* excluding step 1. If a property is found and updated, its value
* is stored in the cached.
*
* @param {GameStage|string} gameStage The GameStage object,
* or its string representation
* @param {string} property The name of the property
* @param {mixed} value The new value for the property.
*
* @return {bool} TRUE, if property is found and updated, FALSE otherwise.
*
* @see GamePlot.cache
*/
GamePlot.prototype.updateProperty = function(gameStage, property, value) {
var stepObj, stageObj, defaultProps, found;
gameStage = new GameStage(gameStage);
if ('string' !== typeof property) {
throw new TypeError('GamePlot.updateProperty: property must be ' +
'string. Found: ' + property);
}
// Look in current step.
stepObj = this.getStep(gameStage);
if (stepObj && stepObj.hasOwnProperty(property)) {
stepObj[property] = value;
found = true;
}
// Look in current stage.
if (!found) {
stageObj = this.getStage(gameStage);
if (stageObj && stageObj.hasOwnProperty(property)) {
stageObj[property] = value;
found = true;
}
}
// Look in Stager's defaults.
if (!found && this.stager) {
defaultProps = this.stager.getDefaultProperties();
if (defaultProps && defaultProps.hasOwnProperty(property)) {
defaultProps[property] = value;
found = true;
}
}
// Cache it and return it.
if (found) {
cacheStepProperty(this, gameStage, property, value);
return true;
}
// Not found.
return false;
};
/**
* ### GamePlot.setStepProperty
*
* Sets the value a property in a step object
*
* @param {GameStage|string} gameStage The GameStage object,
* or its string representation
* @param {string} property The name of the property
* @param {mixed} value The new value for the property.
*
* @return {bool} TRUE, if property is found and updated, FALSE otherwise.
*
* @see GamePlot.cache
*/
GamePlot.prototype.setStepProperty = function(gameStage, property, value) {
var stepObj;
gameStage = new GameStage(gameStage);
if ('string' !== typeof property) {
throw new TypeError('GamePlot.setStepProperty: property must be ' +
'string');
}
// Get step.
stepObj = this.getStep(gameStage);
if (stepObj) {
stepObj[property] = value;
// Cache it.
cacheStepProperty(this, gameStage, property, value);
return true;
}
return false;
};
/**
* ### GamePlot.setStageProperty
*
* Sets the value a property in a step object
*
* @param {GameStage|string} gameStage The GameStage object,
* or its string representation
* @param {string} property The name of the property
* @param {mixed} value The new value for the property.
*
* @return {bool} TRUE, if property is found and updated, FALSE otherwise.
*
* @see GamePlot.cache
*/
GamePlot.prototype.setStageProperty = function(gameStage, property, value) {
var stageObj;
gameStage = new GameStage(gameStage);
if ('string' !== typeof property) {
throw new TypeError('GamePlot.setStageProperty: property must be ' +
'string');
}
// Get stage.
stageObj = this.getStage(gameStage);
if (stageObj) {
stageObj[property] = value;
return true;
}
return false;
};
/**
* ### GamePlot.isReady
*
* Returns whether the stager has any content
*
* @return {boolean} FALSE if stager is empty, TRUE otherwise
*/
GamePlot.prototype.isReady = function() {
return this.stager &&
(this.stager.sequence.length > 0 ||
this.stager.generalNextFunction !== null ||
!J.isEmpty(this.stager.nextFunctions));
};
/**
* ### GamePlot.normalizeGameStage
*
* Converts the GameStage fields to numbers
*
* Checks if stage and step numbers are within the range
* of what found in the stager.
*
* Works only in simple mode.
*
* @param {GameStage|string} gameStage The GameStage object
*
* @return {GameStage|null} The normalized GameStage object; NULL on error
*/
GamePlot.prototype.normalizeGameStage = function(gameStage) {
var stageNo, stageObj, stepNo, seqIdx, seqObj;
var gs;
if (this.isFlexibleMode()) {
throw new Error('GamePlot.normalizeGameStage: invalid call in ' +
'flexible sequence.')
}
// If already normalized and in cache, return it.
if ('string' === typeof gameStage) {
if (this._normalizedCache[gameStage]) {
return this._normalizedCache[gameStage];
}
}
gs = new GameStage(gameStage);
// Find stage number.
if ('number' === typeof gs.stage) {
if (gs.stage === 0) return new GameStage();
stageNo = gs.stage;
}
else if ('string' === typeof gs.stage) {
if (gs.stage === GamePlot.GAMEOVER ||
gs.stage === GamePlot.END_SEQ ||
gs.stage === GamePlot.NO_SEQ) {
return null;
}
for (seqIdx = 0; seqIdx < this.stager.sequence.length; seqIdx++) {
if (this.stager.sequence[seqIdx].id === gs.stage) {
break;
}
}
stageNo = seqIdx + 1;
}
else {
throw new Error('GamePlot.normalizeGameStage: gameStage.stage ' +
'must be number or string: ' +
(typeof gs.stage));
}
if (stageNo < 1 || stageNo > this.stager.sequence.length) {
this.node.silly('GamePlot.normalizeGameStage: non-existent ' +
'stage: ' + gs.stage);
return null;
}
// Get sequence object.
seqObj = this.stager.sequence[stageNo - 1];
if (!seqObj) return null;
if (seqObj.type === 'gameover') {
return new GameStage({
stage: stageNo,
step: 1,
round: gs.round
});
}
// Get stage object.
stageObj = this.stager.stages[seqObj.id];
if (!stageObj) return null;
// Find step number.
if ('number' === typeof gs.step) {
stepNo = gs.step;
}
else if ('string' === typeof gs.step) {
stepNo = seqObj.steps.indexOf(gs.step) + 1;
}
else {
throw new Error('GamePlot.normalizeGameStage: gameStage.step ' +
'must be number or string: ' +
(typeof gs.step));
}
if (stepNo < 1 || stepNo > stageObj.steps.length) {
this.node.silly('normalizeGameStage non-existent step: ' +
stageObj.id + '.' + gs.step);
return null;
}
// Check round property.
if ('number' !== typeof gs.round) return null;
gs = new GameStage({
stage: stageNo,
step: stepNo,
round: gs.round
});
if ('string' === typeof gameStage) {
this._normalizedCache[gameStage] = gs;
}
return gs;
};
/**
* ### GamePlot.isFlexibleMode
*
* Returns TRUE if operating in _flexible_ mode
*
* In _flexible_ mode the next step to be executed is decided by a
* a callback function.
*
* In standard mode all steps are already inserted in a sequence.
*
* @return {boolean} TRUE if flexible mode is on
*/
GamePlot.prototype.isFlexibleMode = function() {
return this.stager.sequence.length === 0;
};
/**
* ### GamePlot.getRound
*
* Returns the current/remaining/past/total round number in a game stage
*
* @param {mixed} gs The game stage of reference
* @param {string} mod Optional. Modifies the return value.
*
* - 'current': current round number (default)
* - 'total': total number of rounds
* - 'remaining': number of rounds remaining (excluding current round)
* - 'past': number of rounds already past (excluding current round)
*
* @return {number|null} The requested information, or null if
* the number of rounds is not known (e.g. if the stage is a loop)
*
* @see GamePlot.getSequenceObject
*/
GamePlot.prototype.getRound = function(gs, mod) {
var seqObj;
gs = new GameStage(gs);
if (gs.stage === 0) return null;
seqObj = this.getSequenceObject(gs);
if (!seqObj) return null;
if (!mod || mod === 'current') return gs.round;
if (mod === 'past') return gs.round - 1;
if (mod === 'total') {
if (seqObj.type === 'repeat') return seqObj.num;
else if (seqObj.type === 'plain') return 1;
else return null;
}
if (mod === 'remaining') {
if (seqObj.type === 'repeat') return seqObj.num - gs.round;
else if (seqObj.type === 'plain') return 1;
else return null;
}
throw new TypeError('GamePlot.getRound: mod must be a known string ' +
'or undefined. Found: ' + mod);
};
// ## Helper Methods
/**
* ### cacheStepProperty
*
* Sets the value of a property in the cache
*
* Parameters are not checked
*
* @param {GamePlot} that The game plot instance
* @param {GameStage|string} gameStage The GameStage object,
* or its string representation
* @param {string} property The name of the property
* @param {mixed} value The value of the property
*
* @see GamePlot.cache
*
* @api private
*/
function cacheStepProperty(that, gameStage, property, value) {
if (!that.cache[gameStage]) that.cache[gameStage] = {};
that.cache[gameStage][property] = value;
}
// ## Closure
})(
'undefined' != typeof node ? node : module.exports,
'undefined' != typeof node ? node : module.parent.exports
);
|
lib/core/GamePlot.js
|
/**
* # GamePlot
* Copyright(c) 2020 Stefano Balietti
* MIT Licensed
*
* Wraps a stager and exposes methods to navigate through the sequence
*
* TODO: previousStage
*/
(function(exports, parent) {
"use strict";
// ## Global scope
exports.GamePlot = GamePlot;
var GameStage = parent.GameStage;
var J = parent.JSUS;
// ## Constants
GamePlot.GAMEOVER = 'NODEGAME_GAMEOVER';
GamePlot.END_SEQ = 'NODEGAME_END_SEQ';
GamePlot.NO_SEQ = 'NODEGAME_NO_SEQ';
/**
* ## GamePlot constructor
*
* Creates a new instance of GamePlot
*
* Takes a sequence object created with Stager.
*
* If the Stager parameter has an empty sequence, flexible mode is assumed
* (used by e.g. GamePlot.next).
*
* @param {NodeGameClient} node Reference to current node object
* @param {Stager} stager Optional. The Stager object.
*
* @see Stager
*/
function GamePlot(node, stager) {
// ## GamePlot Properties
/**
* ### GamePlot.node
*
* Reference to the node object
*/
this.node = node;
/**
* ### GamePlot.stager
*
* The stager object used to perform stepping operations
*/
this.stager = null;
/**
* ### GamePlot.cache
*
* Caches the value of previously fetched properties per game stage
*/
this.cache = {};
/**
* ### GamePlot.tmpCache
*
* Handles a temporary cache for properties of current step
*
* If set, properties are served first by the `getProperty` method.
* This cache is deleted each time a step is done.
* Used, for example, to reset some properties upon reconnect.
*
* Defined two additional methods:
*
* - tmpCache.hasOwnProperty
* - tmpCache.clear
*
* @param {string} prop the name of the property to retrieve or set
* @param {mixed} value The value of property to set
*
* @return {mixed} The current value of the property
*/
this.tmpCache = (function() {
var tmpCache, handler;
tmpCache = {};
handler = function(prop, value) {
if ('undefined' === typeof prop) {
return tmpCache;
}
else if ('string' === typeof prop) {
if (arguments.length === 1) return tmpCache[prop];
tmpCache[prop] = value;
return value;
}
throw new TypeError('GamePlot.tmpCache: prop must be ' +
'string. Found: ' + prop);
};
handler.clear = function() {
var tmp;
tmp = tmpCache;
tmpCache = {};
return tmp;
};
handler.hasOwnProperty = function(prop) {
if ('string' !== typeof prop) {
throw new TypeError('GamePlot.tmpCache.hasProperty: ' +
'prop must be string. Found: ' +
prop);
}
return tmpCache.hasOwnProperty(prop);
};
return handler;
})();
/**
* ### GamePlot._normalizedCache
*
* Caches the value of previously normalized Game Stages objects.
*
* @api private
*/
this._normalizedCache = {};
this.init(stager);
}
// ## GamePlot methods
/**
* ### GamePlot.init
*
* Initializes the GamePlot with a stager
*
* Clears the cache also.
*
* @param {Stager} stager Optional. The Stager object.
*
* @see Stager
*/
GamePlot.prototype.init = function(stager) {
if (stager) {
if ('object' !== typeof stager) {
throw new Error('GamePlot.init: called with invalid stager.');
}
this.stager = stager;
}
else {
this.stager = null;
}
this.cache = {};
this.tmpCache.clear();
};
/**
* ### GamePlot.next
*
* Returns the next step in the sequence
*
* If the step in `curStage` is an integer and out of bounds,
* that bound is assumed.
*
* // TODO: previousStage
*
* @param {GameStage} curStage The GameStage of reference
* @param {bolean} execLoops Optional. If true, loop and doLoop
* conditional function will be executed to determine next stage.
* If false, null will be returned if the next stage depends
* on the execution of the loop/doLoop conditional function.
* Default: true.
*
* @return {GameStage|string} The GameStage after _curStage_
*
* @see GameStage
*/
GamePlot.prototype.nextStage = function(curStage, execLoops) {
var seqObj, stageObj;
var stageNo, stepNo, steps;
var normStage, nextStage;
var flexibleMode;
// GamePlot was not correctly initialized.
if (!this.stager) return GamePlot.NO_SEQ;
flexibleMode = this.isFlexibleMode();
if (flexibleMode) {
// TODO. What does next stage mean in flexible mode?
// Calling the next cb of the last step? A separate cb?
console.log('***GamePlot.nextStage: method not available in ' +
'flexible mode.***');
return null;
}
// Standard Mode.
else {
// Get normalized GameStage:
// makes sures stage is with numbers and not strings.
normStage = this.normalizeGameStage(curStage);
if (normStage === null) {
this.node.warn('GamePlot.nextStage: invalid stage: ' +
curStage);
return null;
}
stageNo = normStage.stage;
if (stageNo === 0) {
return new GameStage({
stage: 1,
step: 1,
round: 1
});
}
seqObj = this.stager.sequence[stageNo - 1];
if (seqObj.type === 'gameover') return GamePlot.GAMEOVER;
execLoops = 'undefined' === typeof execLoops ? true : execLoops;
// Get stage object.
stageObj = this.stager.stages[seqObj.id];
// Go to next stage.
if (stageNo < this.stager.sequence.length) {
seqObj = this.stager.sequence[stageNo];
// Return null if a loop is found and can't be executed.
if (!execLoops && seqObj.type === 'loop') return null;
// Skip over loops if their callbacks return false:
while (seqObj.type === 'loop' &&
!seqObj.cb.call(this.node.game)) {
stageNo++;
if (stageNo >= this.stager.sequence.length) {
return GamePlot.END_SEQ;
}
// Update seq object.
seqObj = this.stager.sequence[stageNo];
}
// Handle gameover:
if (this.stager.sequence[stageNo].type === 'gameover') {
return GamePlot.GAMEOVER;
}
return new GameStage({
stage: stageNo + 1,
step: 1,
round: 1
});
}
// No more stages remaining:
return GamePlot.END_SEQ;
}
};
/**
* ### GamePlot.next
*
* Returns the next step in the sequence
*
* If the step in `curStage` is an integer and out of bounds,
* that bound is assumed.
*
* @param {GameStage} curStage The GameStage of reference
* @param {bolean} execLoops Optional. If true, loop and doLoop
* conditional function will be executed to determine next stage.
* If false, null will be returned if the next stage depends
* on the execution of the loop/doLoop conditional function.
* Default: true.
*
* @return {GameStage|string} The GameStage after _curStage_
*
* @see GameStage
*/
GamePlot.prototype.next = function(curStage, execLoops) {
var seqObj, stageObj;
var stageNo, stepNo, steps;
var normStage, nextStage;
var flexibleMode;
// GamePlot was not correctly initialized.
if (!this.stager) return GamePlot.NO_SEQ;
// Init variables.
seqObj = null, stageObj = null, normStage = null, nextStage = null;
// Find out flexibility mode.
flexibleMode = this.isFlexibleMode();
if (flexibleMode) {
curStage = new GameStage(curStage);
if (curStage.stage === 0) {
// Get first stage:
if (this.stager.generalNextFunction) {
nextStage = this.stager.generalNextFunction();
}
if (nextStage) {
return new GameStage({
stage: nextStage,
step: 1,
round: 1
});
}
return GamePlot.END_SEQ;
}
// Get stage object:
stageObj = this.stager.stages[curStage.stage];
if ('undefined' === typeof stageObj) {
throw new Error('Gameplot.next: received non-existent stage: ' +
curStage.stage);
}
// Find step number:
if ('number' === typeof curStage.step) {
stepNo = curStage.step;
}
else {
stepNo = stageObj.steps.indexOf(curStage.step) + 1;
}
if (stepNo < 1) {
throw new Error('GamePlot.next: received non-existent step: ' +
stageObj.id + '.' + curStage.step);
}
// Handle stepping:
if (stepNo + 1 <= stageObj.steps.length) {
return new GameStage({
stage: stageObj.id,
step: stepNo + 1,
round: 1
});
}
// Get next stage:
if (this.stager.nextFunctions[stageObj.id]) {
nextStage = this.stager.nextFunctions[stageObj.id]();
}
else if (this.stager.generalNextFunction) {
nextStage = this.stager.generalNextFunction();
}
// If next-deciding function returns GamePlot.GAMEOVER,
// consider it game over.
if (nextStage === GamePlot.GAMEOVER) {
return GamePlot.GAMEOVER;
}
else if (nextStage) {
return new GameStage({
stage: nextStage,
step: 1,
round: 1
});
}
return GamePlot.END_SEQ;
}
// Standard Mode.
else {
// Get normalized GameStage:
// makes sures stage is with numbers and not strings.
normStage = this.normalizeGameStage(curStage);
if (normStage === null) {
this.node.warn('GamePlot.next: invalid stage: ' + curStage);
return null;
}
stageNo = normStage.stage;
if (stageNo === 0) {
return new GameStage({
stage: 1,
step: 1,
round: 1
});
}
stepNo = normStage.step;
seqObj = this.stager.sequence[stageNo - 1];
if (seqObj.type === 'gameover') return GamePlot.GAMEOVER;
execLoops = 'undefined' === typeof execLoops ? true : execLoops;
// Get stage object.
stageObj = this.stager.stages[seqObj.id];
steps = seqObj.steps;
// Handle stepping:
if (stepNo + 1 <= steps.length) {
return new GameStage({
stage: stageNo,
step: stepNo + 1,
round: normStage.round
});
}
// Handle repeat block:
if (seqObj.type === 'repeat' && normStage.round + 1 <= seqObj.num) {
return new GameStage({
stage: stageNo,
step: 1,
round: normStage.round + 1
});
}
// Handle looping blocks:
if (seqObj.type === 'doLoop' || seqObj.type === 'loop') {
// Return null if a loop is found and can't be executed.
if (!execLoops) return null;
// Call loop function. True means continue loop.
if (seqObj.cb.call(this.node.game)) {
return new GameStage({
stage: stageNo,
step: 1,
round: normStage.round + 1
});
}
}
// Go to next stage.
if (stageNo < this.stager.sequence.length) {
seqObj = this.stager.sequence[stageNo];
// Return null if a loop is found and can't be executed.
if (!execLoops && seqObj.type === 'loop') return null;
// Skip over loops if their callbacks return false:
while (seqObj.type === 'loop' &&
!seqObj.cb.call(this.node.game)) {
stageNo++;
if (stageNo >= this.stager.sequence.length) {
return GamePlot.END_SEQ;
}
// Update seq object.
seqObj = this.stager.sequence[stageNo];
}
// Handle gameover:
if (this.stager.sequence[stageNo].type === 'gameover') {
return GamePlot.GAMEOVER;
}
return new GameStage({
stage: stageNo + 1,
step: 1,
round: 1
});
}
// No more stages remaining:
return GamePlot.END_SEQ;
}
};
/**
* ### GamePlot.previous
*
* Returns the previous step in the sequence
*
* Works only in simple mode.
*
* Previous of 0.0.0 is 0.0.0.
*
* @param {GameStage} curStage The GameStage of reference
* @param {bolean} execLoops Optional. If true, loop and doLoop
* conditional function will be executed to determine previous stage.
* If false, null will be returned if the previous stage depends
* on the execution of the loop/doLoop conditional function.
* Default: true.
*
* @return {GameStage|null} The GameStage before _curStage_, or null
* if _curStage_ is invalid.
*
* @see GameStage
*/
GamePlot.prototype.previous = function(curStage, execLoops) {
var normStage;
var seqObj, stageObj;
var prevSeqObj;
var stageNo, stepNo, prevStepNo;
// GamePlot was not correctly initialized.
if (!this.stager) return GamePlot.NO_SEQ;
seqObj = null, stageObj = null;
// Get normalized GameStage (calls GameStage constructor).
normStage = this.normalizeGameStage(curStage);
if (normStage === null) {
this.node.warn('GamePlot.previous: invalid stage: ' + curStage);
return null;
}
stageNo = normStage.stage;
// Already 0.0.0, there is nothing before.
if (stageNo === 0) return new GameStage();
stepNo = normStage.step;
seqObj = this.stager.sequence[stageNo - 1];
execLoops = 'undefined' === typeof execLoops ? true : execLoops;
// Within same stage.
// Handle stepping.
if (stepNo > 1) {
return new GameStage({
stage: stageNo,
step: stepNo - 1,
round: normStage.round
});
}
// Handle rounds:
if (normStage.round > 1) {
return new GameStage({
stage: stageNo,
step: seqObj.steps.length,
round: normStage.round - 1
});
}
// Handle beginning (0.0.0).
if (stageNo === 1) return new GameStage();
// Go to previous stage.
// Get previous sequence object:
prevSeqObj = this.stager.sequence[stageNo - 2];
// Return null if a loop is found and can't be executed.
if (!execLoops && seqObj.type === 'loop') return null;
// Skip over loops if their callbacks return false:
while (prevSeqObj.type === 'loop' &&
!prevSeqObj.cb.call(this.node.game)) {
stageNo--;
// (0.0.0).
if (stageNo <= 1) return new GameStage();
// Update seq object.
prevSeqObj = this.stager.sequence[stageNo - 2];
}
// Get number of steps in previous stage:
prevStepNo = prevSeqObj.steps.length;
// Handle repeat block:
if (prevSeqObj.type === 'repeat') {
return new GameStage({
stage: stageNo - 1,
step: prevStepNo,
round: prevSeqObj.num
});
}
// Handle normal blocks:
return new GameStage({
stage: stageNo - 1,
step: prevStepNo,
round: 1
});
};
/**
* ### GamePlot.jump
*
* Returns a distant stage in the stager
*
* Works with negative delta only in simple mode.
*
* Uses `GamePlot.previous` and `GamePlot.next` for stepping.
*
* @param {GameStage} curStage The GameStage of reference
* @param {number} delta The offset. Negative number for backward stepping.
* @param {bolean} execLoops Optional. If true, loop and doLoop
* conditional function will be executed to determine next stage.
* If false, null will be returned when a loop or doLoop is found
* and more evaluations are still required. Default: true.
*
* @return {GameStage|string|null} The distant game stage
*
* @see GameStage
* @see GamePlot.previous
* @see GamePlot.next
*/
GamePlot.prototype.jump = function(curStage, delta, execLoops) {
var stageType;
execLoops = 'undefined' === typeof execLoops ? true : execLoops;
if (delta < 0) {
while (delta < 0) {
curStage = this.previous(curStage, execLoops);
if (!(curStage instanceof GameStage) || curStage.stage === 0) {
return curStage;
}
delta++;
if (!execLoops) {
// If there are more steps to jump, check if we have loops.
stageType = this.stager.sequence[curStage.stage -1].type;
if (stageType === 'loop') {
if (delta < 0) return null;
}
else if (stageType === 'doLoop') {
if (delta < -1) return null;
else return curStage;
}
}
}
}
else {
while (delta > 0) {
curStage = this.next(curStage, execLoops);
// If we find a loop return null.
if (!(curStage instanceof GameStage)) return curStage;
delta--;
if (!execLoops) {
// If there are more steps to jump, check if we have loops.
stageType = this.stager.sequence[curStage.stage -1].type;
if (stageType === 'loop' || stageType === 'doLoop') {
if (delta > 0) return null;
else return curStage;
}
}
}
}
return curStage;
};
/**
* ### GamePlot.stepsToNextStage
*
* Returns the number of steps to reach the next stage
*
* By default, each stage repetition is considered as a new stage.
*
* @param {GameStage|string} gameStage The reference step
* @param {boolean} countRepeat If TRUE stage repetitions are
* considered as current stage, and included in the count. Default: FALSE.
*
* @return {number|null} The number of steps including current one,
* or NULL on error.
*
* @see GamePlot.normalizeGameStage
*/
GamePlot.prototype.stepsToNextStage = function(gameStage, countRepeat) {
var seqObj, totSteps, stepNo;
if (!this.stager) return null;
// Checks stage and step ranges.
gameStage = this.normalizeGameStage(gameStage);
if (!gameStage) return null;
if (gameStage.stage === 0) return 1;
seqObj = this.getSequenceObject(gameStage);
if (!seqObj) return null;
stepNo = gameStage.step;
totSteps = seqObj.steps.length;
if (countRepeat) {
if (seqObj.type === 'repeat') {
if (gameStage.round > 1) {
stepNo = ((gameStage.round-1) * totSteps) + stepNo;
}
totSteps = totSteps * seqObj.num;
}
else if (seqObj.type === 'loop' || seqObj.type === 'doLoop') {
return null;
}
}
return 1 + totSteps - stepNo;
};
// TODO: remove in next version.
GamePlot.prototype.stepsToPreviousStage = function(gameStage) {
console.log('GamePlot.stepsToPreviousStage is **deprecated**. Use' +
'GamePlot.stepsFromPreviousStage instead.');
return this.stepsFromPreviousStage(gameStage);
};
/**
* ### GamePlot.stepsFromPreviousStage
*
* Returns the number of steps passed from the previous stage
*
* By default, each stage repetition is considered as a new stage.
*
* @param {GameStage|string} gameStage The reference step
* @param {boolean} countRepeat If TRUE stage repetitions are
* considered as current stage, and included in the count. Default: FALSE.
*
* @return {number|null} The number of steps including current one, or
* NULL on error.
*
* @see GamePlot.normalizeGameStage
*/
GamePlot.prototype.stepsFromPreviousStage = function(gameStage,
countRepeat) {
var seqObj, stepNo;
if (!this.stager) return null;
// Checks stage and step ranges.
gameStage = this.normalizeGameStage(gameStage);
if (!gameStage || gameStage.stage === 0) return null;
seqObj = this.getSequenceObject(gameStage);
if (!seqObj) return null;
stepNo = gameStage.step;
if (countRepeat) {
if (seqObj.type === 'repeat') {
if (gameStage.round > 1) {
stepNo = (seqObj.steps.length * (gameStage.round-1)) +
stepNo;
}
}
else if (seqObj.type === 'loop' || seqObj.type === 'doLoop') {
return null;
}
}
return stepNo;
};
/**
* ### GamePlot.getSequenceObject
*
* Returns the sequence object corresponding to a GameStage
*
* @param {GameStage|string} gameStage The GameStage object,
* or its string representation
*
* @return {object|null} The corresponding sequence object,
* or NULL if not found
*/
GamePlot.prototype.getSequenceObject = function(gameStage) {
if (!this.stager) return null;
gameStage = this.normalizeGameStage(gameStage);
return gameStage ? this.stager.sequence[gameStage.stage - 1] : null;
};
/**
* ### GamePlot.getStage
*
* Returns the stage object corresponding to a GameStage
*
* @param {GameStage|string} gameStage The GameStage object,
* or its string representation
*
* @return {object|null} The corresponding stage object, or NULL
* if the step was not found
*/
GamePlot.prototype.getStage = function(gameStage) {
var stageObj;
if (!this.stager) return null;
gameStage = this.normalizeGameStage(gameStage);
if (gameStage) {
stageObj = this.stager.sequence[gameStage.stage - 1];
stageObj = stageObj ? this.stager.stages[stageObj.id] : null;
}
return stageObj || null;
};
/**
* ### GamePlot.getStep
*
* Returns the step object corresponding to a GameStage
*
* @param {GameStage|string} gameStage The GameStage object,
* or its string representation
*
* @return {object|null} The corresponding step object, or NULL
* if the step was not found
*/
GamePlot.prototype.getStep = function(gameStage) {
var seqObj, stepObj;
if (!this.stager) return null;
// Game stage is normalized inside getSequenceObject.
seqObj = this.getSequenceObject(gameStage);
if (seqObj) {
stepObj = this.stager.steps[seqObj.steps[gameStage.step - 1]];
}
return stepObj || null;
};
/**
* ### GamePlot.getStepRule
*
* Returns the step-rule function for a given game-stage
*
* Otherwise, the order of lookup is:
*
* 1. step object
* 2. stage object
* 3. default property
* 4. default step-rule of the Stager object
*
* @param {GameStage|string} gameStage The GameStage object,
* or its string representation
*
* @return {function} The step-rule function or the default rule
*
* @see Stager.getDefaultStepRule
*/
GamePlot.prototype.getStepRule = function(gameStage) {
var rule;
rule = this.getProperty(gameStage, 'stepRule');
if ('string' === typeof rule) rule = parent.stepRules[rule];
return rule || this.stager.getDefaultStepRule();
};
/**
* ### GamePlot.getGlobal
*
* Looks up the value of a global variable
*
* Looks for definitions of a global variable in
*
* 1. the globals property of the step object of the given gameStage,
*
* 2. the globals property of the stage object of the given gameStage,
*
* 3. the defaults, defined in the Stager.
*
* @param {GameStage|string} gameStage The GameStage object,
* or its string representation
* @param {string} globalVar The name of the global variable
*
* @return {mixed|null} The value of the global variable if found,
* NULL otherwise.
*/
GamePlot.prototype.getGlobal = function(gameStage, globalVar) {
var stepObj, stageObj;
var stepGlobals, stageGlobals, defaultGlobals;
gameStage = new GameStage(gameStage);
// Look in current step:
stepObj = this.getStep(gameStage);
if (stepObj) {
stepGlobals = stepObj.globals;
if (stepGlobals && stepGlobals.hasOwnProperty(globalVar)) {
return stepGlobals[globalVar];
}
}
// Look in current stage:
stageObj = this.getStage(gameStage);
if (stageObj) {
stageGlobals = stageObj.globals;
if (stageGlobals && stageGlobals.hasOwnProperty(globalVar)) {
return stageGlobals[globalVar];
}
}
// Look in Stager's defaults:
if (this.stager) {
defaultGlobals = this.stager.getDefaultGlobals();
if (defaultGlobals && defaultGlobals.hasOwnProperty(globalVar)) {
return defaultGlobals[globalVar];
}
}
// Not found:
return null;
};
/**
* ### GamePlot.getGlobals
*
* Looks up and build the _globals_ object for the specified game stage
*
* Globals properties are mixed in at each level (defaults, stage, step)
* to form the complete set of globals available for the specified
* game stage.
*
* @param {GameStage|string} gameStage The GameStage object,
* or its string representation
*
* @return {object} The _globals_ object for the specified game stage
*/
GamePlot.prototype.getGlobals = function(gameStage) {
var stepstage, globals;
if ('string' !== typeof gameStage && 'object' !== typeof gameStage) {
throw new TypeError('GamePlot.getGlobals: gameStage must be ' +
'string or object.');
}
globals = {};
// No stager found, no globals!
if (!this.stager) return globals;
// Look in Stager's defaults:
J.mixin(globals, this.stager.getDefaultGlobals());
// Look in current stage:
stepstage = this.getStage(gameStage);
if (stepstage) J.mixin(globals, stepstage.globals);
// Look in current step:
stepstage = this.getStep(gameStage);
if (stepstage) J.mixin(globals, stepstage.globals);
return globals;
};
/**
* ### GamePlot.getProperty
*
* Looks up the value of a property in a hierarchy of lookup locations
*
* The hierarchy of lookup locations is:
*
* 1. the temporary cache, if game stage equals current game stage
* 2. the game plot cache
* 3. the step object of the given gameStage,
* 4. the stage object of the given gameStage,
* 5. the defaults, defined in the Stager.
*
* @param {GameStage|string} gameStage The GameStage object,
* or its string representation
* @param {string} prop The name of the property
* @param {mixed} notFound Optional. A value to return if
* property is not found. Default: NULL
* @param {object} mask Optional. An object disabling specific lookup
* locations. Default:
* ```
* { tmpCache: false, cache: false, step: false, stage: false, game: false }
* ```
*
* @return {mixed|null} The value of the property if found, NULL otherwise.
*
* @see GamePlot.cache
*/
GamePlot.prototype.getProperty = function(gameStage, prop, notFound, mask) {
var stepObj, stageObj, defaultProps, found, res;
if ('string' !== typeof prop) {
throw new TypeError('GamePlot.getProperty: property must be ' +
'string. Found: ' + prop);
}
gameStage = new GameStage(gameStage);
mask = mask || {};
if ('object' !== typeof mask) {
throw new TypeError('GamePlot.getProperty: mask must be ' +
'object or undefined. Found: ' + mask);
}
// Look in the tmpCache (cleared every step).
if (!mask.tmpCache && this.tmpCache.hasOwnProperty(prop) &&
GameStage.compare(gameStage,this.node.player.stage) === 0) {
return this.tmpCache(prop);
}
// Look in the main cache (this persists over steps).
if (!mask.tmpCache && this.cache[gameStage] &&
this.cache[gameStage].hasOwnProperty(prop)) {
return this.cache[gameStage][prop];
}
// Look in current step.
if (!mask.step) {
stepObj = this.getStep(gameStage);
if (stepObj && stepObj.hasOwnProperty(prop)) {
res = stepObj[prop];
found = true;
}
}
// Look in current stage.
if (!found && !mask.stage) {
stageObj = this.getStage(gameStage);
if (stageObj && stageObj.hasOwnProperty(prop)) {
res = stageObj[prop];
found = true;
}
}
// Look in Stager's defaults.
if (!found && !mask.game && this.stager) {
defaultProps = this.stager.getDefaultProperties();
if (defaultProps && defaultProps.hasOwnProperty(prop)) {
res = defaultProps[prop];
found = true;
}
}
// Cache it and return it.
if (found) {
cacheStepProperty(this, gameStage, prop, res);
return res;
}
// Return notFound.
return 'undefined' === typeof notFound ? null : notFound;
};
/**
* ### GamePlot.updateProperty
*
* Looks up a property and updates it to the new value
*
* Look up follows the steps described in _GamePlot.getProperty_,
* excluding step 1. If a property is found and updated, its value
* is stored in the cached.
*
* @param {GameStage|string} gameStage The GameStage object,
* or its string representation
* @param {string} property The name of the property
* @param {mixed} value The new value for the property.
*
* @return {bool} TRUE, if property is found and updated, FALSE otherwise.
*
* @see GamePlot.cache
*/
GamePlot.prototype.updateProperty = function(gameStage, property, value) {
var stepObj, stageObj, defaultProps, found;
gameStage = new GameStage(gameStage);
if ('string' !== typeof property) {
throw new TypeError('GamePlot.updateProperty: property must be ' +
'string. Found: ' + property);
}
// Look in current step.
stepObj = this.getStep(gameStage);
if (stepObj && stepObj.hasOwnProperty(property)) {
stepObj[property] = value;
found = true;
}
// Look in current stage.
if (!found) {
stageObj = this.getStage(gameStage);
if (stageObj && stageObj.hasOwnProperty(property)) {
stageObj[property] = value;
found = true;
}
}
// Look in Stager's defaults.
if (!found && this.stager) {
defaultProps = this.stager.getDefaultProperties();
if (defaultProps && defaultProps.hasOwnProperty(property)) {
defaultProps[property] = value;
found = true;
}
}
// Cache it and return it.
if (found) {
cacheStepProperty(this, gameStage, property, value);
return true;
}
// Not found.
return false;
};
/**
* ### GamePlot.setStepProperty
*
* Sets the value a property in a step object
*
* @param {GameStage|string} gameStage The GameStage object,
* or its string representation
* @param {string} property The name of the property
* @param {mixed} value The new value for the property.
*
* @return {bool} TRUE, if property is found and updated, FALSE otherwise.
*
* @see GamePlot.cache
*/
GamePlot.prototype.setStepProperty = function(gameStage, property, value) {
var stepObj;
gameStage = new GameStage(gameStage);
if ('string' !== typeof property) {
throw new TypeError('GamePlot.setStepProperty: property must be ' +
'string');
}
// Get step.
stepObj = this.getStep(gameStage);
if (stepObj) {
stepObj[property] = value;
// Cache it.
cacheStepProperty(this, gameStage, property, value);
return true;
}
return false;
};
/**
* ### GamePlot.setStageProperty
*
* Sets the value a property in a step object
*
* @param {GameStage|string} gameStage The GameStage object,
* or its string representation
* @param {string} property The name of the property
* @param {mixed} value The new value for the property.
*
* @return {bool} TRUE, if property is found and updated, FALSE otherwise.
*
* @see GamePlot.cache
*/
GamePlot.prototype.setStageProperty = function(gameStage, property, value) {
var stageObj;
gameStage = new GameStage(gameStage);
if ('string' !== typeof property) {
throw new TypeError('GamePlot.setStageProperty: property must be ' +
'string');
}
// Get stage.
stageObj = this.getStage(gameStage);
if (stageObj) {
stageObj[property] = value;
return true;
}
return false;
};
/**
* ### GamePlot.isReady
*
* Returns whether the stager has any content
*
* @return {boolean} FALSE if stager is empty, TRUE otherwise
*/
GamePlot.prototype.isReady = function() {
return this.stager &&
(this.stager.sequence.length > 0 ||
this.stager.generalNextFunction !== null ||
!J.isEmpty(this.stager.nextFunctions));
};
/**
* ### GamePlot.normalizeGameStage
*
* Converts the GameStage fields to numbers
*
* Checks if stage and step numbers are within the range
* of what found in the stager.
*
* Works only in simple mode.
*
* @param {GameStage|string} gameStage The GameStage object
*
* @return {GameStage|null} The normalized GameStage object; NULL on error
*/
GamePlot.prototype.normalizeGameStage = function(gameStage) {
var stageNo, stageObj, stepNo, seqIdx, seqObj;
var gs;
if (this.isFlexibleMode()) {
throw new Error('GamePlot.normalizeGameStage: invalid call in ' +
'flexible sequence.')
}
// If already normalized and in cache, return it.
if ('string' === typeof gameStage) {
if (this._normalizedCache[gameStage]) {
return this._normalizedCache[gameStage];
}
}
gs = new GameStage(gameStage);
// Find stage number.
if ('number' === typeof gs.stage) {
if (gs.stage === 0) return new GameStage();
stageNo = gs.stage;
}
else if ('string' === typeof gs.stage) {
if (gs.stage === GamePlot.GAMEOVER ||
gs.stage === GamePlot.END_SEQ ||
gs.stage === GamePlot.NO_SEQ) {
return null;
}
for (seqIdx = 0; seqIdx < this.stager.sequence.length; seqIdx++) {
if (this.stager.sequence[seqIdx].id === gs.stage) {
break;
}
}
stageNo = seqIdx + 1;
}
else {
throw new Error('GamePlot.normalizeGameStage: gameStage.stage ' +
'must be number or string: ' +
(typeof gs.stage));
}
if (stageNo < 1 || stageNo > this.stager.sequence.length) {
this.node.silly('GamePlot.normalizeGameStage: non-existent ' +
'stage: ' + gs.stage);
return null;
}
// Get sequence object.
seqObj = this.stager.sequence[stageNo - 1];
if (!seqObj) return null;
if (seqObj.type === 'gameover') {
return new GameStage({
stage: stageNo,
step: 1,
round: gs.round
});
}
// Get stage object.
stageObj = this.stager.stages[seqObj.id];
if (!stageObj) return null;
// Find step number.
if ('number' === typeof gs.step) {
stepNo = gs.step;
}
else if ('string' === typeof gs.step) {
stepNo = seqObj.steps.indexOf(gs.step) + 1;
}
else {
throw new Error('GamePlot.normalizeGameStage: gameStage.step ' +
'must be number or string: ' +
(typeof gs.step));
}
if (stepNo < 1 || stepNo > stageObj.steps.length) {
this.node.warn('normalizeGameStage received non-existent step: ' +
stageObj.id + '.' + gs.step);
return null;
}
// Check round property.
if ('number' !== typeof gs.round) return null;
gs = new GameStage({
stage: stageNo,
step: stepNo,
round: gs.round
});
if ('string' === typeof gameStage) {
this._normalizedCache[gameStage] = gs;
}
return gs;
};
/**
* ### GamePlot.isFlexibleMode
*
* Returns TRUE if operating in _flexible_ mode
*
* In _flexible_ mode the next step to be executed is decided by a
* a callback function.
*
* In standard mode all steps are already inserted in a sequence.
*
* @return {boolean} TRUE if flexible mode is on
*/
GamePlot.prototype.isFlexibleMode = function() {
return this.stager.sequence.length === 0;
};
/**
* ### GamePlot.getRound
*
* Returns the current/remaining/past/total round number in a game stage
*
* @param {mixed} gs The game stage of reference
* @param {string} mod Optional. Modifies the return value.
*
* - 'current': current round number (default)
* - 'total': total number of rounds
* - 'remaining': number of rounds remaining (excluding current round)
* - 'past': number of rounds already past (excluding current round)
*
* @return {number|null} The requested information, or null if
* the number of rounds is not known (e.g. if the stage is a loop)
*
* @see GamePlot.getSequenceObject
*/
GamePlot.prototype.getRound = function(gs, mod) {
var seqObj;
gs = new GameStage(gs);
if (gs.stage === 0) return null;
seqObj = this.getSequenceObject(gs);
if (!seqObj) return null;
if (!mod || mod === 'current') return gs.round;
if (mod === 'past') return gs.round - 1;
if (mod === 'total') {
if (seqObj.type === 'repeat') return seqObj.num;
else if (seqObj.type === 'plain') return 1;
else return null;
}
if (mod === 'remaining') {
if (seqObj.type === 'repeat') return seqObj.num - gs.round;
else if (seqObj.type === 'plain') return 1;
else return null;
}
throw new TypeError('GamePlot.getRound: mod must be a known string ' +
'or undefined. Found: ' + mod);
};
// ## Helper Methods
/**
* ### cacheStepProperty
*
* Sets the value of a property in the cache
*
* Parameters are not checked
*
* @param {GamePlot} that The game plot instance
* @param {GameStage|string} gameStage The GameStage object,
* or its string representation
* @param {string} property The name of the property
* @param {mixed} value The value of the property
*
* @see GamePlot.cache
*
* @api private
*/
function cacheStepProperty(that, gameStage, property, value) {
if (!that.cache[gameStage]) that.cache[gameStage] = {};
that.cache[gameStage][property] = value;
}
// ## Closure
})(
'undefined' != typeof node ? node : module.exports,
'undefined' != typeof node ? node : module.parent.exports
);
|
warn -> silly
|
lib/core/GamePlot.js
|
warn -> silly
|
<ide><path>ib/core/GamePlot.js
<ide> // makes sures stage is with numbers and not strings.
<ide> normStage = this.normalizeGameStage(curStage);
<ide> if (normStage === null) {
<del> this.node.warn('GamePlot.nextStage: invalid stage: ' +
<add> this.node.silly('GamePlot.nextStage: invalid stage: ' +
<ide> curStage);
<ide> return null;
<ide> }
<ide> // makes sures stage is with numbers and not strings.
<ide> normStage = this.normalizeGameStage(curStage);
<ide> if (normStage === null) {
<del> this.node.warn('GamePlot.next: invalid stage: ' + curStage);
<add> this.node.silly('GamePlot.next: invalid stage: ' + curStage);
<ide> return null;
<ide> }
<ide>
<ide> }
<ide>
<ide> if (stepNo < 1 || stepNo > stageObj.steps.length) {
<del> this.node.warn('normalizeGameStage received non-existent step: ' +
<add> this.node.silly('normalizeGameStage non-existent step: ' +
<ide> stageObj.id + '.' + gs.step);
<ide> return null;
<ide> }
|
|
Java
|
isc
|
9077aa57ac191270a11d23dd95ecacdf7c9884e9
| 0 |
TealCube/strife
|
package info.faceland.strife.effects;
import info.faceland.strife.data.StrifeMob;
import org.bukkit.Location;
import org.bukkit.Particle;
import org.bukkit.entity.LivingEntity;
public class SpawnParticle extends Effect {
private Particle particle;
private int quantity;
private float spread;
private float speed;
private ParticleOriginLocation particleOriginLocation = ParticleOriginLocation.CENTER;
@Override
public void apply(StrifeMob caster, StrifeMob target) {
Location loc = getLoc(target.getEntity());
target.getEntity().getWorld()
.spawnParticle(particle, loc, quantity, spread, spread, spread, speed);
}
public void setParticle(Particle particle) {
this.particle = particle;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public void setSpeed(float speed) {
this.speed = speed;
}
public void setSpread(float spread) {
this.spread = spread;
}
public void setParticleOriginLocation(
ParticleOriginLocation particleOriginLocation) {
this.particleOriginLocation = particleOriginLocation;
}
private Location getLoc(LivingEntity le) {
switch (particleOriginLocation) {
case HEAD:
return le.getEyeLocation();
case CENTER:
return le.getEyeLocation().clone()
.subtract(le.getEyeLocation().clone().subtract(le.getLocation()).multiply(0.5));
case GROUND:
return le.getLocation();
}
return null;
}
public enum ParticleOriginLocation {
HEAD,
CENTER,
GROUND
}
}
|
src/main/java/info/faceland/strife/effects/SpawnParticle.java
|
package info.faceland.strife.effects;
import info.faceland.strife.data.StrifeMob;
import org.bukkit.Location;
import org.bukkit.Particle;
public class SpawnParticle extends Effect {
private Particle particle;
private int quantity;
private float spread;
private float speed;
@Override
public void apply(StrifeMob caster, StrifeMob target) {
Location loc = target.getEntity().getLocation().clone().add(target.getEntity().getEyeLocation());
target.getEntity().getWorld()
.spawnParticle(particle, loc, quantity, spread, spread, spread, speed);
}
public void setParticle(Particle particle) {
this.particle = particle;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public void setSpeed(float speed) {
this.speed = speed;
}
public void setSpread(float spread) {
this.spread = spread;
}
}
|
Fixing particles and adding option for particle origin
|
src/main/java/info/faceland/strife/effects/SpawnParticle.java
|
Fixing particles and adding option for particle origin
|
<ide><path>rc/main/java/info/faceland/strife/effects/SpawnParticle.java
<ide> import info.faceland.strife.data.StrifeMob;
<ide> import org.bukkit.Location;
<ide> import org.bukkit.Particle;
<add>import org.bukkit.entity.LivingEntity;
<ide>
<ide> public class SpawnParticle extends Effect {
<ide>
<ide> private int quantity;
<ide> private float spread;
<ide> private float speed;
<add> private ParticleOriginLocation particleOriginLocation = ParticleOriginLocation.CENTER;
<ide>
<ide> @Override
<ide> public void apply(StrifeMob caster, StrifeMob target) {
<del> Location loc = target.getEntity().getLocation().clone().add(target.getEntity().getEyeLocation());
<add> Location loc = getLoc(target.getEntity());
<ide> target.getEntity().getWorld()
<ide> .spawnParticle(particle, loc, quantity, spread, spread, spread, speed);
<ide> }
<ide> this.spread = spread;
<ide> }
<ide>
<add> public void setParticleOriginLocation(
<add> ParticleOriginLocation particleOriginLocation) {
<add> this.particleOriginLocation = particleOriginLocation;
<add> }
<add>
<add> private Location getLoc(LivingEntity le) {
<add> switch (particleOriginLocation) {
<add> case HEAD:
<add> return le.getEyeLocation();
<add> case CENTER:
<add> return le.getEyeLocation().clone()
<add> .subtract(le.getEyeLocation().clone().subtract(le.getLocation()).multiply(0.5));
<add> case GROUND:
<add> return le.getLocation();
<add> }
<add> return null;
<add> }
<add>
<add> public enum ParticleOriginLocation {
<add> HEAD,
<add> CENTER,
<add> GROUND
<add> }
<ide> }
|
|
Java
|
bsd-3-clause
|
536b17361b77b7617c1de4ed23b77ff0f3909e90
| 0 |
meg23/esapi-java,meg23/esapi-java,marylinh/esapi-java-legacy,marylinh/esapi-java-legacy,marylinh/esapi-java-legacy
|
/**
* OWASP Enterprise Security API (ESAPI)
*
* This file is part of the Open Web Application Security Project (OWASP)
* Enterprise Security API (ESAPI) project. For details, please see
* <a href="http://www.owasp.org/index.php/ESAPI">http://www.owasp.org/index.php/ESAPI</a>.
*
* Copyright (c) 2007 - The OWASP Foundation
*
* The ESAPI is published by OWASP under the BSD license. You should read and accept the
* LICENSE before you use, modify, and/or redistribute this software.
*
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
* @created 2009
*/
package org.owasp.esapi;
import java.util.ArrayList;
import org.owasp.esapi.codecs.Codec;
import org.owasp.esapi.codecs.HTMLEntityCodec;
/**
* A parameterized string that uses escaping to make untrusted data safe before combining it with
* a command or query intended for use in an interpreter.
* <pre>
* PreparedString div = new PreparedString( "<a href=\"http:\\\\example.com?id=?\" onmouseover=\"alert('?')\">test</a>", new HTMLEntityCodec() );
* div.setURL( 1, request.getParameter( "url" ), new PercentCodec() );
* div.set( 2, request.getParameter( "message" ), new JavaScriptCodec() );
* out.println( div.toString() );
*
* // escaping for SQL
* PreparedString query = new PreparedString( "SELECT * FROM users WHERE name='?' AND password='?'", new OracleCodec() );
* query.set( 1, request.getParameter( "name" ) );
* query.set( 2, request.getParameter( "pass" ) );
* stmt.execute( query.toString() );
* </pre>
*
* @author Jeff Williams (jeff.williams .at. aspectsecurity.com) <a href="http://www.aspectsecurity.com">Aspect Security</a>
* @since June 1, 2007
*/
public class PreparedString {
char parameterCharacter = '?';
Codec codec = null;
String[] parameters = null;
ArrayList parts = new ArrayList();
private final static char[] IMMUNE = {};
/**
* Create a PreparedString with the supplied template and Codec. The template should use the
* default parameter placeholder character (?) in the place where actual parameters are to be inserted.
* The supplied Codec will be used to escape characters in calls to set, unless a specific Codec is
* provided to override it.
* @param template
* @param codec
*/
public PreparedString( String template, Codec codec ) {
this.codec = codec;
split( template, parameterCharacter );
}
/**
* Create a PreparedString with the supplied template, parameter placeholder character, and Codec. The parameter character
* can be any character, but should not be one that will be used in the template. The parameter character can safely
* be used in a parameter passed into the set methods.
* @param template
* @param parameterCharacter
* @param codec
*/
public PreparedString( String template, char parameterCharacter, Codec codec ) {
this.codec = codec;
this.parameterCharacter = parameterCharacter;
split( template, parameterCharacter );
}
/**
* Split a string with a particular character.
* @param str
* @param c
*/
private void split( String str, char c ) {
int index = 0;
int pcount = 0;
for ( int i = 0; i < str.length(); i++ ) {
if ( str.charAt(i) == c ) {
pcount++;
parts.add( str.substring(index,i) );
index = i + 1;
}
}
parts.add( str.substring(index) );
parameters = new String[pcount];
}
/**
* Set the parameter at index with supplied value using the default Codec to escape.
* @param index
* @param value
*/
public void set( int index, String value ) {
if ( index < 1 || index > parameters.length ) {
throw new IllegalArgumentException( "Attempt to set parameter " + index + " on a PreparedString with only " + parameters.length + " placeholders" );
}
String encoded = codec.encode( IMMUNE, value );
parameters[index-1] = encoded;
}
/**
* Set the parameter at index with supplied value using the supplied Codec to escape.
* @param index
* @param value
* @param codec
*/
public void set( int index, String value, Codec codec ) {
if ( index < 1 || index > parameters.length ) {
throw new IllegalArgumentException( "Attempt to set parameter " + index + " on a PreparedString with only " + parameters.length + " placeholders" );
}
String encoded = codec.encode( IMMUNE, value );
parameters[index-1] = encoded;
}
/**
* Render the PreparedString by combining the template with properly escaped parameters.
*/
public String toString() {
for ( int ix = 0; ix < parameters.length; ix++ ) {
if ( parameters[ix] == null ) {
throw new RuntimeException( "Attempt to render PreparedString without setting parameter " + ( ix + 1 ));
}
}
StringBuilder sb = new StringBuilder();
int i = 0;
for ( int p=0; p < parts.size(); p++ ) {
sb.append( parts.get( p ) );
if ( i < parameters.length ) sb.append( parameters[i++] );
}
return sb.toString();
}
}
|
src/main/java/org/owasp/esapi/PreparedString.java
|
/**
* OWASP Enterprise Security API (ESAPI)
*
* This file is part of the Open Web Application Security Project (OWASP)
* Enterprise Security API (ESAPI) project. For details, please see
* <a href="http://www.owasp.org/index.php/ESAPI">http://www.owasp.org/index.php/ESAPI</a>.
*
* Copyright (c) 2007 - The OWASP Foundation
*
* The ESAPI is published by OWASP under the BSD license. You should read and accept the
* LICENSE before you use, modify, and/or redistribute this software.
*
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
* @created 2009
*/
package org.owasp.esapi;
import java.util.ArrayList;
import org.owasp.esapi.codecs.Codec;
import org.owasp.esapi.codecs.HTMLEntityCodec;
/**
* A parameterized string that uses escaping to make untrusted data safe before combining it with
* a command or query intended for use in an interpreter.
* <pre>
* PreparedString div = new PreparedString( "<a href=\"http:\\\\example.com?id=?\" onmouseover=\"alert('?')\">test</a>", new HTMLEntityCodec() );
* div.setURL( 1, request.getParameter( "url" ), new PercentCodec() );
* div.set( 2, request.getParameter( "message" ), new JavaScriptCodec() );
* out.println( div.toString() );
*
* // escaping for SQL
* PreparedString query = new PreparedString( "SELECT * FROM users WHERE name=? AND password=?", new OracleCodec() );
* query.set( 1, request.getParameter( "name" ) );
* query.set( 2, request.getParameter( "pass" ) );
* stmt.execute( query.toString() );
* </pre>
*
* @author Jeff Williams (jeff.williams .at. aspectsecurity.com) <a href="http://www.aspectsecurity.com">Aspect Security</a>
* @since June 1, 2007
*/
public class PreparedString {
char parameterCharacter = '?';
Codec codec = null;
String[] parameters = null;
ArrayList parts = new ArrayList();
private final static char[] IMMUNE = {};
/**
* Create a PreparedString with the supplied template and Codec. The template should use the
* default parameter placeholder character (?) in the place where actual parameters are to be inserted.
* The supplied Codec will be used to escape characters in calls to set, unless a specific Codec is
* provided to override it.
* @param template
* @param codec
*/
public PreparedString( String template, Codec codec ) {
this.codec = codec;
split( template, parameterCharacter );
}
/**
* Create a PreparedString with the supplied template, parameter placeholder character, and Codec. The parameter character
* can be any character, but should not be one that will be used in the template. The parameter character can safely
* be used in a parameter passed into the set methods.
* @param template
* @param parameterCharacter
* @param codec
*/
public PreparedString( String template, char parameterCharacter, Codec codec ) {
this.codec = codec;
this.parameterCharacter = parameterCharacter;
split( template, parameterCharacter );
}
/**
* Split a string with a particular character.
* @param str
* @param c
*/
private void split( String str, char c ) {
int index = 0;
int pcount = 0;
for ( int i = 0; i < str.length(); i++ ) {
if ( str.charAt(i) == c ) {
pcount++;
parts.add( str.substring(index,i) );
index = i + 1;
}
}
parts.add( str.substring(index) );
parameters = new String[pcount];
}
/**
* Set the parameter at index with supplied value using the default Codec to escape.
* @param index
* @param value
*/
public void set( int index, String value ) {
if ( index < 1 || index > parameters.length ) {
throw new IllegalArgumentException( "Attempt to set parameter " + index + " on a PreparedString with only " + parameters.length + " placeholders" );
}
String encoded = codec.encode( IMMUNE, value );
parameters[index-1] = encoded;
}
/**
* Set the parameter at index with supplied value using the supplied Codec to escape.
* @param index
* @param value
* @param codec
*/
public void set( int index, String value, Codec codec ) {
if ( index < 1 || index > parameters.length ) {
throw new IllegalArgumentException( "Attempt to set parameter " + index + " on a PreparedString with only " + parameters.length + " placeholders" );
}
String encoded = codec.encode( IMMUNE, value );
parameters[index-1] = encoded;
}
/**
* Render the PreparedString by combining the template with properly escaped parameters.
*/
public String toString() {
for ( int ix = 0; ix < parameters.length; ix++ ) {
if ( parameters[ix] == null ) {
throw new RuntimeException( "Attempt to render PreparedString without setting parameter " + ( ix + 1 ));
}
}
StringBuilder sb = new StringBuilder();
int i = 0;
for ( int p=0; p < parts.size(); p++ ) {
sb.append( parts.get( p ) );
if ( i < parameters.length ) sb.append( parameters[i++] );
}
return sb.toString();
}
}
|
Fixed the javadoc to apply single quotes per oracle example.
|
src/main/java/org/owasp/esapi/PreparedString.java
|
Fixed the javadoc to apply single quotes per oracle example.
|
<ide><path>rc/main/java/org/owasp/esapi/PreparedString.java
<ide> * out.println( div.toString() );
<ide> *
<ide> * // escaping for SQL
<del> * PreparedString query = new PreparedString( "SELECT * FROM users WHERE name=? AND password=?", new OracleCodec() );
<add> * PreparedString query = new PreparedString( "SELECT * FROM users WHERE name='?' AND password='?'", new OracleCodec() );
<ide> * query.set( 1, request.getParameter( "name" ) );
<ide> * query.set( 2, request.getParameter( "pass" ) );
<ide> * stmt.execute( query.toString() );
|
|
Java
|
mit
|
a8d78f34488d32797cd2d476651a600db97f779e
| 0 |
Innovimax-SARL/mix-them
|
package innovimax.mixthem.io;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.stream.IntStream;
public class MultiChannelLineReader implements IMultiChannelLineInput {
private final List<ILineInput> readers = new ArrayList<ILineInput>();
/**
* Constructor
* @param inputs The list of inputs as InputResource
* @param selection The input index selection (maybe empty)
* @see innovimax.mixthem.io.InputResource
*/
public MultiChannelLineReader(final List<InputResource> inputs, final Set<Integer> selection) {
IntStream.rangeClosed(1, inputs.size())
.filter(index -> selection.isEmpty() || selection.contains(Integer.valueOf(index)))
.mapToObj(index -> inputs.get(index-1))
.forEach(input -> {
try {
this.readers.add(new DefaultLineReader(input));
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
@Override
public boolean hasLine() throws IOException {
return this.readers.stream()
.anyMatch(reader -> {
try {
return reader.hasLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
@Override
public List<String> nextLineRange() throws IOException {
final List<String> lines = new ArrayList<String>();
final Iterator<ILineInput> iterator = this.readers.iterator();
while (iterator.hasNext()) {
final ILineInput reader = iterator.next();
final String line = reader.nextLine();
lines.add(line);
}
return lines;
}
@Override
public List<String> nextLineRange(List<Boolean> readingRange) throws IOException {
final List<String> lines = new ArrayList<String>();
int index = 0;
final Iterator<ILineInput> iterator = this.readers.iterator();
while (iterator.hasNext()) {
final ILineInput reader = iterator.next();
if (readingRange.get(index).booleanValue()) {
lines.add(reader.nextLine());
} else {
lines.add(null);
}
index++;
}
return lines;
}
@Override
public void close() throws IOException {
this.readers.forEach(reader -> {
try {
reader.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
}
|
src/main/java/innovimax/mixthem/io/MultiChannelLineReader.java
|
package innovimax.mixthem.io;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class MultiChannelLineReader implements IMultiChannelLineInput {
private final List<ILineInput> readers = new ArrayList<ILineInput>();
public MultiChannelLineReader(final List<InputResource> inputs) {
inputs.stream().forEach(input -> {
try {
this.readers.add(new DefaultLineReader(input));
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
@Override
public boolean hasLine() throws IOException {
final Iterator<ILineInput> iterator = this.readers.iterator();
while (iterator.hasNext()) {
final ILineInput reader = iterator.next();
if (reader.hasLine()) {
return true;
}
}
return false;
}
@Override
public List<String> nextLineRange() throws IOException {
final List<String> lines = new ArrayList<String>();
final Iterator<ILineInput> iterator = this.readers.iterator();
while (iterator.hasNext()) {
final ILineInput reader = iterator.next();
final String line = reader.nextLine();
lines.add(line);
}
return lines;
}
@Override
public List<String> nextLineRange(List<Boolean> readingRange) throws IOException {
final List<String> lines = new ArrayList<String>();
int index = 0;
final Iterator<ILineInput> iterator = this.readers.iterator();
while (iterator.hasNext()) {
final ILineInput reader = iterator.next();
if (readingRange.get(index).booleanValue()) {
lines.add(reader.nextLine());
} else {
lines.add(null);
}
index++;
}
return lines;
}
@Override
public void close() throws IOException {
final Iterator<ILineInput> iterator = this.readers.iterator();
while (iterator.hasNext()) {
final ILineInput reader = iterator.next();
reader.close();
}
}
}
|
Update MultiChannelLineReader.java
|
src/main/java/innovimax/mixthem/io/MultiChannelLineReader.java
|
Update MultiChannelLineReader.java
|
<ide><path>rc/main/java/innovimax/mixthem/io/MultiChannelLineReader.java
<ide> import java.util.ArrayList;
<ide> import java.util.Iterator;
<ide> import java.util.List;
<add>import java.util.Set;
<add>import java.util.stream.IntStream;
<ide>
<ide> public class MultiChannelLineReader implements IMultiChannelLineInput {
<ide>
<ide> private final List<ILineInput> readers = new ArrayList<ILineInput>();
<ide>
<del> public MultiChannelLineReader(final List<InputResource> inputs) {
<del> inputs.stream().forEach(input -> {
<del> try {
<del> this.readers.add(new DefaultLineReader(input));
<del> } catch (IOException e) {
<del> throw new RuntimeException(e);
<del> }
<del> });
<add> /**
<add> * Constructor
<add> * @param inputs The list of inputs as InputResource
<add> * @param selection The input index selection (maybe empty)
<add> * @see innovimax.mixthem.io.InputResource
<add> */
<add> public MultiChannelLineReader(final List<InputResource> inputs, final Set<Integer> selection) {
<add> IntStream.rangeClosed(1, inputs.size())
<add> .filter(index -> selection.isEmpty() || selection.contains(Integer.valueOf(index)))
<add> .mapToObj(index -> inputs.get(index-1))
<add> .forEach(input -> {
<add> try {
<add> this.readers.add(new DefaultLineReader(input));
<add> } catch (IOException e) {
<add> throw new RuntimeException(e);
<add> }
<add> });
<ide> }
<ide>
<ide> @Override
<ide> public boolean hasLine() throws IOException {
<del> final Iterator<ILineInput> iterator = this.readers.iterator();
<del> while (iterator.hasNext()) {
<del> final ILineInput reader = iterator.next();
<del> if (reader.hasLine()) {
<del> return true;
<del> }
<del> }
<del> return false;
<add> return this.readers.stream()
<add> .anyMatch(reader -> {
<add> try {
<add> return reader.hasLine();
<add> } catch (IOException e) {
<add> throw new RuntimeException(e);
<add> }
<add> });
<ide> }
<ide>
<ide> @Override
<ide>
<ide> @Override
<ide> public void close() throws IOException {
<del> final Iterator<ILineInput> iterator = this.readers.iterator();
<del> while (iterator.hasNext()) {
<del> final ILineInput reader = iterator.next();
<del> reader.close();
<del> }
<add> this.readers.forEach(reader -> {
<add> try {
<add> reader.close();
<add> } catch (IOException e) {
<add> throw new RuntimeException(e);
<add> }
<add> });
<ide> }
<ide>
<ide> }
|
|
JavaScript
|
mit
|
ebb233bfe229a66e3f0be160b7f20cf7972010e5
| 0 |
trotzig/import-js,trotzig/import-js,Galooshi/import-js,trotzig/import-js
|
import sqlite3 from 'sqlite3';
import lastUpdate from './lastUpdate';
const MAX_CHUNK_SIZE = 100;
function normalizedExportName(string) {
return string.toLowerCase().replace(/[-_.]/g, '');
}
function inParam(sql, values) {
// https://github.com/mapbox/node-sqlite3/issues/721
return sql.replace('?#', values.map(() => '?').join(','));
}
function arrayToChunks(array, chunkSize) {
const chunks = [];
for (let i = 0; i < array.length; i += chunkSize) {
chunks.push(array.slice(i, i + chunkSize));
}
return chunks;
}
export default class ExportsStorage {
init(dbFilename) {
return new Promise((resolve, reject) => {
this.db = new sqlite3.Database(dbFilename);
this.db.all('PRAGMA table_info(exports)', (pragmaErr, result) => {
if (pragmaErr) {
reject(pragmaErr);
return;
}
if (result.length) {
// DB has already been initialized
resolve({ isFreshInstall: false });
return;
}
this.db.run(`
CREATE TABLE exports (
name VARCHAR(100),
isDefault INTEGER,
path TEXT
)
`, (err) => {
if (err) {
reject(err);
return;
}
this.db.run(`
CREATE TABLE mtimes (
path TEXT,
mtime NUMERIC
)
`, (err) => {
if (err) {
reject(err);
return;
}
resolve({ isFreshInstall: true });
});
});
});
});
}
close() {
return new Promise((resolve, reject) => {
this.db.close((err) => {
if (err) {
reject(err);
return;
}
resolve();
});
});
}
needsUpdate(files) {
if (files.length > MAX_CHUNK_SIZE) {
// sqlite has a max number for arguments passed. We need to execute in
// chunks if we exceed the max.
const promises = arrayToChunks(files, MAX_CHUNK_SIZE).map((chunk) =>
this.needsUpdate(chunk));
return Promise.all(promises)
.then((chunks) => chunks.reduce((a, b) => a.concat(b))); // flatten
}
return new Promise((resolve, reject) => {
const filePaths = files.map(({ path: p }) => p);
this.db.all(inParam(`
SELECT path, mtime FROM mtimes
WHERE (path IN (?#))
`, filePaths), filePaths, (err, items) => {
if (err) {
reject(err);
return;
}
const mtimes = {};
items.forEach(({ path: pathToFile, mtime }) => {
mtimes[pathToFile] = mtime;
});
const filtered = files.filter(({ path: pathToFile, mtime }) =>
mtime !== mtimes[pathToFile]);
resolve(filtered);
});
});
}
allFiles() {
return new Promise((resolve, reject) => {
this.db.all('SELECT path FROM mtimes', (err, files) => {
if (err) {
reject(err);
return;
}
resolve(files.map(({ path }) => path));
});
});
}
updateMtime(pathToFile, mtime) {
return new Promise((resolve, reject) => {
this.db.get('SELECT mtime FROM mtimes WHERE (path = ?)',
pathToFile, (err, item) => {
if (err) {
reject(err);
return;
}
if (item) {
this.db.run('UPDATE mtimes SET mtime = ? WHERE (path = ?)',
mtime, pathToFile, (err) => {
if (err) {
reject(err);
return;
}
resolve();
});
} else {
this.db.run('INSERT INTO mtimes (mtime, path) VALUES (?, ?)',
mtime, pathToFile, (err) => {
if (err) {
reject(err);
return;
}
resolve();
});
}
});
});
}
_insert({ name, pathToFile, isDefault }) {
const exportName = isDefault ? normalizedExportName(name) : name;
return new Promise((resolve, reject) => {
this.db.run('INSERT INTO exports (name, path, isDefault) VALUES (?, ?, ?)',
exportName, pathToFile, isDefault, (err) => {
if (err) {
reject(err);
return;
}
resolve();
});
});
}
update({ names, defaultNames, pathToFile, mtime }) {
return this.remove(pathToFile).then(() =>
this.updateMtime(pathToFile, mtime).then(() => {
const promises = names.map((name) =>
this._insert({ name, pathToFile, isDefault: false }));
promises.push(...defaultNames.map((name) =>
this._insert({ name, pathToFile, isDefault: true })));
return Promise.all(promises);
}));
}
_remove(pattern, operator = '=') {
return new Promise((resolve, reject) => {
this.db.run(`DELETE FROM exports WHERE (path ${operator} ?)`,
pattern, (err) => {
if (err) {
reject(err);
return;
}
this.db.run(`DELETE FROM mtimes WHERE (path ${operator} ?)`,
pattern, (mErr) => {
if (mErr) {
reject(mErr);
return;
}
resolve();
});
});
});
}
remove(pathToFile) {
return this._remove(pathToFile);
}
removeAll(globPattern) {
return this._remove(globPattern, 'GLOB');
}
purgeDeadNodeModules(workingDirectory) {
return new Promise((resolve, reject) => {
this.db.all('SELECT path FROM mtimes WHERE (path LIKE "./node_modules/%")', (err, files) => {
if (err) {
reject(err);
return;
}
const promises = files.map(({ path: pathToFile }) =>
new Promise((removeResolve) => {
lastUpdate(pathToFile, workingDirectory)
.then(removeResolve)
.catch(() => this.remove(pathToFile).then(removeResolve));
}));
Promise.all(promises)
.then(resolve)
.catch(reject);
});
});
}
get(variableName) {
return new Promise((resolve, reject) => {
this.db.all(`
SELECT name, path, isDefault
FROM exports WHERE (
(name = ? AND isDefault = 0) OR
(name = ? AND isDefault = 1)
)
`,
variableName, normalizedExportName(variableName), (err, rows) => {
if (err) {
reject(err);
return;
}
resolve(rows.map(({ name, path, isDefault }) => ({
name,
path,
isDefault: !!isDefault,
})));
});
});
}
}
|
lib/ExportsStorage.js
|
import sqlite3 from 'sqlite3';
import lastUpdate from './lastUpdate';
const MAX_CHUNK_SIZE = 100;
function normalizedExportName(string) {
return string.toLowerCase().replace(/[-_.]/g, '');
}
function inParam(sql, values) {
// https://github.com/mapbox/node-sqlite3/issues/721
return sql.replace('?#', values.map(() => '?').join(','));
}
function arrayToChunks(array, chunkSize) {
const chunks = [];
for (let i = 0; i < array.length; i += chunkSize) {
chunks.push(array.slice(i, i + chunkSize));
}
return chunks;
}
export default class ExportsStorage {
init(dbFilename) {
return new Promise((resolve, reject) => {
this.db = new sqlite3.Database(dbFilename);
this.db.all('PRAGMA table_info(exports)', (pragmaErr, result) => {
if (pragmaErr) {
reject(pragmaErr);
return;
}
if (result.length) {
// DB has already been initialized
resolve({ isFreshInstall: false });
return;
}
this.db.run(`
CREATE TABLE exports (
name VARCHAR(100),
isDefault INTEGER,
path TEXT
)
`, (err) => {
if (err) {
reject(err);
return;
}
this.db.run(`
CREATE TABLE mtimes (
path TEXT,
mtime NUMERIC
)
`, (err) => {
if (err) {
reject(err);
return;
}
resolve({ isFreshInstall: true });
});
});
});
});
}
close() {
return new Promise((resolve, reject) => {
this.db.close((err) => {
if (err) {
reject(err);
return;
}
resolve();
});
});
}
needsUpdate(files) {
if (files.length > MAX_CHUNK_SIZE) {
// sqlite has a max number for arguments passed. We need to execute in
// chunks if we exceed the max.
const promises = arrayToChunks(files, MAX_CHUNK_SIZE).map((chunk) =>
this.needsUpdate(chunk));
return Promise.all(promises)
.then((chunks) => chunks.reduce((a, b) => a.concat(b))); // flatten
}
return new Promise((resolve, reject) => {
const filePaths = files.map(({ path: p }) => p);
this.db.all(inParam(`
SELECT path, mtime FROM mtimes
WHERE (path IN (?#))
`, filePaths), filePaths, (err, items) => {
if (err) {
reject(err);
return;
}
const mtimes = {};
items.forEach(({ path: pathToFile, mtime }) => {
mtimes[pathToFile] = mtime;
});
const filtered = files.filter(({ path: pathToFile, mtime }) =>
mtime !== mtimes[pathToFile]);
resolve(filtered);
});
});
}
allFiles() {
return new Promise((resolve, reject) => {
this.db.all('SELECT path FROM mtimes', (err, files) => {
if (err) {
reject(err);
return;
}
resolve(files.map(({ path }) => path));
});
});
}
updateMtime(pathToFile, mtime) {
return new Promise((resolve, reject) => {
this.db.get('SELECT mtime FROM mtimes WHERE (path = ?)',
pathToFile, (err, item) => {
if (err) {
reject(err);
return;
}
if (item) {
this.db.run('UPDATE mtimes SET mtime = ? WHERE (path = ?)',
mtime, pathToFile, (err) => {
if (err) {
reject(err);
return;
}
resolve();
});
} else {
this.db.run('INSERT INTO mtimes (mtime, path) VALUES (?, ?)',
mtime, pathToFile, (err) => {
if (err) {
reject(err);
return;
}
resolve();
});
}
});
});
}
_insert({ name, pathToFile, isDefault }) {
const exportName = isDefault ? normalizedExportName(name) : name;
return new Promise((resolve, reject) => {
this.db.run('INSERT INTO exports (name, path, isDefault) VALUES (?, ?, ?)',
exportName, pathToFile, isDefault, (err) => {
if (err) {
reject(err);
return;
}
resolve();
});
});
}
update({ names, defaultNames, pathToFile, mtime }) {
return this.remove(pathToFile).then(() =>
this.updateMtime(pathToFile, mtime).then(() => {
const promises = names.map((name) =>
this._insert({ name, pathToFile, isDefault: false }));
promises.push(...defaultNames.map((name) =>
this._insert({ name, pathToFile, isDefault: true })));
return Promise.all(promises);
}));
}
_remove(pattern, operator = '=') {
return new Promise((resolve, reject) => {
this.db.run(`DELETE FROM exports WHERE (path ${operator} ?)`,
pattern, (err) => {
if (err) {
reject(err);
return;
}
this.db.run(`DELETE FROM mtimes WHERE (path ${operator} ?)`,
pattern, (mErr) => {
if (mErr) {
reject(mErr);
return;
}
resolve();
});
});
});
}
remove(pathToFile) {
return this._remove(pathToFile);
}
removeAll(globPattern) {
return this._remove(globPattern, 'GLOB');
}
purgeDeadNodeModules(workingDirectory) {
return new Promise((resolve, reject) => {
this.db.all('SELECT path FROM mtimes WHERE (path LIKE "./node_modules/%")', (err, files) => {
if (err) {
reject(err);
return;
}
const promises = files.map(({ path: pathToFile }) =>
new Promise((resolve) => {
lastUpdate(pathToFile, workingDirectory)
.then(resolve)
.catch(() => this.remove(pathToFile).then(resolve));
}));
Promise.all(promises)
.then(resolve)
.catch(reject);
});
});
}
get(variableName) {
return new Promise((resolve, reject) => {
this.db.all(`
SELECT name, path, isDefault
FROM exports WHERE (
(name = ? AND isDefault = 0) OR
(name = ? AND isDefault = 1)
)
`,
variableName, normalizedExportName(variableName), (err, rows) => {
if (err) {
reject(err);
return;
}
resolve(rows.map(({ name, path, isDefault }) => ({
name,
path,
isDefault: !!isDefault,
})));
});
});
}
}
|
Avoid shadowing variable name
We were using `resolve` for both an inner promise and an outer one,
leading to a little bit of confusion.
|
lib/ExportsStorage.js
|
Avoid shadowing variable name
|
<ide><path>ib/ExportsStorage.js
<ide> return;
<ide> }
<ide> const promises = files.map(({ path: pathToFile }) =>
<del> new Promise((resolve) => {
<add> new Promise((removeResolve) => {
<ide> lastUpdate(pathToFile, workingDirectory)
<del> .then(resolve)
<del> .catch(() => this.remove(pathToFile).then(resolve));
<add> .then(removeResolve)
<add> .catch(() => this.remove(pathToFile).then(removeResolve));
<ide> }));
<ide> Promise.all(promises)
<ide> .then(resolve)
|
|
Java
|
epl-1.0
|
58085eed91ab9ee5ba6be39635b0b1c6c774b55b
| 0 |
sbrannen/junit-lambda,junit-team/junit-lambda
|
/*
* Copyright 2015-2016 the original author or authors.
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution and is available at
*
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.junit.gen5.launcher.main;
import static java.util.stream.Collectors.toList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.gen5.api.Assertions.assertEquals;
import static org.junit.gen5.api.Assertions.expectThrows;
import static org.junit.gen5.engine.FilterResult.excluded;
import static org.junit.gen5.engine.discovery.ClassSelector.forClass;
import static org.junit.gen5.engine.discovery.ClassSelector.forClassName;
import static org.junit.gen5.engine.discovery.MethodSelector.forMethod;
import static org.junit.gen5.engine.discovery.PackageSelector.forPackageName;
import static org.junit.gen5.engine.discovery.UniqueIdSelector.forUniqueId;
import static org.junit.gen5.launcher.main.DefaultLaunchParameter.keyValuePair;
import static org.junit.gen5.launcher.main.TestDiscoveryRequestBuilder.request;
import java.io.File;
import java.lang.reflect.Method;
import java.util.List;
import org.assertj.core.util.Files;
import org.junit.gen5.api.Nested;
import org.junit.gen5.api.Test;
import org.junit.gen5.commons.util.PreconditionViolationException;
import org.junit.gen5.engine.DiscoveryFilter;
import org.junit.gen5.engine.discovery.ClassSelector;
import org.junit.gen5.engine.discovery.ClasspathSelector;
import org.junit.gen5.engine.discovery.MethodSelector;
import org.junit.gen5.engine.discovery.PackageSelector;
import org.junit.gen5.engine.discovery.UniqueIdSelector;
import org.junit.gen5.launcher.DiscoveryFilterStub;
import org.junit.gen5.launcher.EngineIdFilter;
import org.junit.gen5.launcher.PostDiscoveryFilter;
import org.junit.gen5.launcher.PostDiscoveryFilterStub;
import org.junit.gen5.launcher.TestDiscoveryRequest;
/**
* @since 5.0
*/
public class TestDiscoveryRequestBuilderTests {
@Nested
class DiscoverySelectionTests {
@Test
public void packagesAreStoredInDiscoveryRequest() throws Exception {
// @formatter:off
TestDiscoveryRequest discoveryRequest = request()
.select(
forPackageName("org.junit.gen5.engine")
).build();
// @formatter:on
List<String> packageSelectors = discoveryRequest.getSelectorsByType(PackageSelector.class).stream().map(
PackageSelector::getPackageName).collect(toList());
assertThat(packageSelectors).contains("org.junit.gen5.engine");
}
@Test
public void classesAreStoredInDiscoveryRequest() throws Exception {
// @formatter:off
TestDiscoveryRequest discoveryRequest = request()
.select(
forClassName(TestDiscoveryRequestBuilderTests.class.getName()),
forClass(SampleTestClass.class)
)
.build();
// @formatter:on
List<Class<?>> classes = discoveryRequest.getSelectorsByType(ClassSelector.class).stream().map(
ClassSelector::getTestClass).collect(toList());
assertThat(classes).contains(SampleTestClass.class, TestDiscoveryRequestBuilderTests.class);
}
@Test
public void methodsByNameAreStoredInDiscoveryRequest() throws Exception {
Class<?> testClass = SampleTestClass.class;
Method testMethod = testClass.getMethod("test");
// @formatter:off
TestDiscoveryRequest discoveryRequest = request()
.select(forMethod(SampleTestClass.class.getName(), "test"))
.build();
// @formatter:on
List<MethodSelector> methodSelectors = discoveryRequest.getSelectorsByType(MethodSelector.class);
assertThat(methodSelectors).hasSize(1);
MethodSelector methodSelector = methodSelectors.get(0);
assertThat(methodSelector.getTestClass()).isEqualTo(testClass);
assertThat(methodSelector.getTestMethod()).isEqualTo(testMethod);
}
@Test
public void methodsByClassAreStoredInDiscoveryRequest() throws Exception {
Class<?> testClass = SampleTestClass.class;
Method testMethod = testClass.getMethod("test");
// @formatter:off
DiscoveryRequest discoveryRequest = (DiscoveryRequest) request()
.select(
MethodSelector.forMethod(SampleTestClass.class, "test")
).build();
// @formatter:on
List<MethodSelector> methodSelectors = discoveryRequest.getSelectorsByType(MethodSelector.class);
assertThat(methodSelectors).hasSize(1);
MethodSelector methodSelector = methodSelectors.get(0);
assertThat(methodSelector.getTestClass()).isEqualTo(testClass);
assertThat(methodSelector.getTestMethod()).isEqualTo(testMethod);
}
@Test
public void unavailableFoldersAreNotStoredInDiscoveryRequest() throws Exception {
// @formatter:off
TestDiscoveryRequest discoveryRequest = request()
.select(
ClasspathSelector.forPath("/some/local/path")
).build();
// @formatter:on
List<String> folders = discoveryRequest.getSelectorsByType(ClasspathSelector.class).stream().map(
ClasspathSelector::getClasspathRoot).map(File::getAbsolutePath).collect(toList());
assertThat(folders).isEmpty();
}
@Test
public void availableFoldersAreStoredInDiscoveryRequest() throws Exception {
File temporaryFolder = Files.newTemporaryFolder();
try {
// @formatter:off
TestDiscoveryRequest discoveryRequest = request()
.select(
ClasspathSelector.forPath(temporaryFolder.getAbsolutePath())
).build();
// @formatter:on
List<String> folders = discoveryRequest.getSelectorsByType(ClasspathSelector.class).stream().map(
ClasspathSelector::getClasspathRoot).map(File::getAbsolutePath).collect(toList());
assertThat(folders).contains(temporaryFolder.getAbsolutePath());
}
finally {
temporaryFolder.delete();
}
}
@Test
public void uniqueIdsAreStoredInDiscoveryRequest() throws Exception {
// @formatter:off
TestDiscoveryRequest discoveryRequest = request()
.select(
forUniqueId("engine:bla:foo:bar:id1"),
forUniqueId("engine:bla:foo:bar:id2")
).build();
// @formatter:on
List<String> uniqueIds = discoveryRequest.getSelectorsByType(UniqueIdSelector.class).stream().map(
UniqueIdSelector::getUniqueId).collect(toList());
assertThat(uniqueIds).contains("engine:bla:foo:bar:id1", "engine:bla:foo:bar:id2");
}
}
@Nested
class DiscoveryFilterTests {
@Test
public void engineFiltersAreStoredInDiscoveryRequest() throws Exception {
// @formatter:off
TestDiscoveryRequest discoveryRequest = request()
.filter(
EngineIdFilter.byEngineId("engine1"),
EngineIdFilter.byEngineId("engine2")
).build();
// @formatter:on
List<String> engineIds = discoveryRequest.getEngineIdFilters().stream().map(
EngineIdFilter::getEngineId).collect(toList());
assertThat(engineIds).hasSize(2);
assertThat(engineIds).contains("engine1", "engine2");
}
@Test
@SuppressWarnings("rawtypes")
public void discoveryFiltersAreStoredInDiscoveryRequest() throws Exception {
// @formatter:off
TestDiscoveryRequest discoveryRequest = request()
.filter(
new DiscoveryFilterStub("filter1"),
new DiscoveryFilterStub("filter2")
).build();
// @formatter:on
List<String> filterStrings = discoveryRequest.getDiscoveryFiltersByType(DiscoveryFilter.class).stream().map(
DiscoveryFilter::toString).collect(toList());
assertThat(filterStrings).hasSize(2);
assertThat(filterStrings).contains("filter1", "filter2");
}
@Test
public void postDiscoveryFiltersAreStoredInDiscoveryRequest() throws Exception {
// @formatter:off
TestDiscoveryRequest discoveryRequest = request()
.filter(
new PostDiscoveryFilterStub("postFilter1"),
new PostDiscoveryFilterStub("postFilter2")
).build();
// @formatter:on
List<String> filterStrings = discoveryRequest.getPostDiscoveryFilters().stream().map(
PostDiscoveryFilter::toString).collect(toList());
assertThat(filterStrings).hasSize(2);
assertThat(filterStrings).contains("postFilter1", "postFilter2");
}
@Test
public void exceptionForIllegalFilterClass() throws Exception {
PreconditionViolationException exception = expectThrows(PreconditionViolationException.class,
() -> request().filter(o -> excluded("reason")));
assertEquals("Filter must implement EngineIdFilter, PostDiscoveryFilter or DiscoveryFilter.",
exception.getMessage());
}
}
@Nested
class DiscoveryLaunchParameterTests {
@Test
void withoutLaunchParametersSet_NoLaunchParametersAreStoredInDiscoveryRequest() throws Exception {
TestDiscoveryRequest discoveryRequest = request().build();
assertThat(discoveryRequest.getLaunchParameter("key").isPresent()).isFalse();
assertThat(discoveryRequest.getLaunchParameters()).isEmpty();
}
@Test
void launchParameterAddedDirectly_isStoredInDiscoveryRequest() throws Exception {
// @formatter:off
TestDiscoveryRequest discoveryRequest = request()
.launchParameter("key", "value")
.build();
assertThat(discoveryRequest.getLaunchParameter("key").isPresent()).isTrue();
assertThat(discoveryRequest.getLaunchParameter("key").get()).isEqualTo("value");
assertThat(discoveryRequest.getLaunchParameters())
.hasSize(1)
.containsKey("key")
.containsValue("value");
// @formatter:on
}
@Test
void launchParameterAddedDirectlyTwice_overridesPreviousValueInDiscoveryRequest() throws Exception {
// @formatter:off
TestDiscoveryRequest discoveryRequest = request()
.launchParameter("key", "value")
.launchParameter("key", "value-new")
.build();
assertThat(discoveryRequest.getLaunchParameter("key").isPresent()).isTrue();
assertThat(discoveryRequest.getLaunchParameter("key").get()).isEqualTo("value-new");
assertThat(discoveryRequest.getLaunchParameters())
.hasSize(1)
.containsKey("key")
.containsValue("value-new");
// @formatter:on
}
@Test
void multipleLaunchParameterAddedDirectly_isStoredInDiscoveryRequest() throws Exception {
// @formatter:off
TestDiscoveryRequest discoveryRequest = request()
.launchParameter("key1", "value1")
.launchParameter("key2", "value2")
.build();
assertThat(discoveryRequest.getLaunchParameter("key1").isPresent()).isTrue();
assertThat(discoveryRequest.getLaunchParameter("key1").get()).isEqualTo("value1");
assertThat(discoveryRequest.getLaunchParameter("key2").isPresent()).isTrue();
assertThat(discoveryRequest.getLaunchParameter("key2").get()).isEqualTo("value2");
assertThat(discoveryRequest.getLaunchParameters())
.hasSize(2)
.containsKeys("key1", "key2")
.containsValues("value1", "value2");
// @formatter:on
}
@Test
void launchParameterAddedByList_isStoredInDiscoveryRequest() throws Exception {
// @formatter:off
TestDiscoveryRequest discoveryRequest = request()
.launchParameters(keyValuePair("key", "value"))
.build();
assertThat(discoveryRequest.getLaunchParameter("key").isPresent()).isTrue();
assertThat(discoveryRequest.getLaunchParameter("key").get()).isEqualTo("value");
assertThat(discoveryRequest.getLaunchParameters())
.hasSize(1)
.containsKey("key")
.containsValue("value");
// @formatter:on
}
@Test
void multipleLaunchParameterAddedByList_isStoredInDiscoveryRequest() throws Exception {
// @formatter:off
TestDiscoveryRequest discoveryRequest = request()
.launchParameters(keyValuePair("key1", "value1"))
.launchParameters(keyValuePair("key2", "value2"))
.build();
assertThat(discoveryRequest.getLaunchParameter("key1").isPresent()).isTrue();
assertThat(discoveryRequest.getLaunchParameter("key1").get()).isEqualTo("value1");
assertThat(discoveryRequest.getLaunchParameter("key2").isPresent()).isTrue();
assertThat(discoveryRequest.getLaunchParameter("key2").get()).isEqualTo("value2");
assertThat(discoveryRequest.getLaunchParameters())
.hasSize(2)
.containsKeys("key1", "key2")
.containsValues("value1", "value2");
// @formatter:on
}
@Test
void launchParameterAddedByListTwice_overridesPreviousValueInDiscoveryRequest() throws Exception {
// @formatter:off
TestDiscoveryRequest discoveryRequest = request()
.launchParameters(
keyValuePair("key", "value"),
keyValuePair("key", "value-new")
)
.build();
assertThat(discoveryRequest.getLaunchParameter("key").isPresent()).isTrue();
assertThat(discoveryRequest.getLaunchParameter("key").get()).isEqualTo("value-new");
assertThat(discoveryRequest.getLaunchParameters())
.hasSize(1)
.containsKey("key")
.containsValue("value-new");
// @formatter:on
}
}
private static class SampleTestClass {
@Test
public void test() {
}
}
}
|
junit-tests/src/test/java/org/junit/gen5/launcher/main/TestDiscoveryRequestBuilderTests.java
|
/*
* Copyright 2015-2016 the original author or authors.
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution and is available at
*
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.junit.gen5.launcher.main;
import static java.util.stream.Collectors.toList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.gen5.api.Assertions.assertEquals;
import static org.junit.gen5.api.Assertions.expectThrows;
import static org.junit.gen5.engine.FilterResult.excluded;
import static org.junit.gen5.engine.discovery.ClassSelector.forClass;
import static org.junit.gen5.engine.discovery.ClassSelector.forClassName;
import static org.junit.gen5.engine.discovery.MethodSelector.forMethod;
import static org.junit.gen5.engine.discovery.PackageSelector.forPackageName;
import static org.junit.gen5.engine.discovery.UniqueIdSelector.forUniqueId;
import static org.junit.gen5.launcher.main.DefaultLaunchParameter.keyValuePair;
import static org.junit.gen5.launcher.main.TestDiscoveryRequestBuilder.request;
import java.io.File;
import java.lang.reflect.Method;
import java.util.List;
import org.assertj.core.util.Files;
import org.junit.gen5.api.Nested;
import org.junit.gen5.api.Test;
import org.junit.gen5.commons.util.PreconditionViolationException;
import org.junit.gen5.engine.DiscoveryFilter;
import org.junit.gen5.engine.discovery.ClassSelector;
import org.junit.gen5.engine.discovery.ClasspathSelector;
import org.junit.gen5.engine.discovery.MethodSelector;
import org.junit.gen5.engine.discovery.PackageSelector;
import org.junit.gen5.engine.discovery.UniqueIdSelector;
import org.junit.gen5.launcher.DiscoveryFilterStub;
import org.junit.gen5.launcher.EngineIdFilter;
import org.junit.gen5.launcher.PostDiscoveryFilter;
import org.junit.gen5.launcher.PostDiscoveryFilterStub;
import org.junit.gen5.launcher.TestDiscoveryRequest;
/**
* @since 5.0
*/
public class TestDiscoveryRequestBuilderTests {
@Nested
class DiscoverySelectionTests {
@Test
public void packagesAreStoredInDiscoveryRequest() throws Exception {
// @formatter:off
TestDiscoveryRequest discoveryRequest = request()
.select(
forPackageName("org.junit.gen5.engine")
).build();
// @formatter:on
List<String> packageSelectors = discoveryRequest.getSelectorsByType(PackageSelector.class).stream().map(
PackageSelector::getPackageName).collect(toList());
assertThat(packageSelectors).contains("org.junit.gen5.engine");
}
@Test
public void classesAreStoredInDiscoveryRequest() throws Exception {
// @formatter:off
TestDiscoveryRequest discoveryRequest = request()
.select(
forClassName(TestDiscoveryRequestBuilderTests.class.getName()),
forClass(SampleTestClass.class)
)
.build();
// @formatter:on
List<Class<?>> classes = discoveryRequest.getSelectorsByType(ClassSelector.class).stream().map(
ClassSelector::getTestClass).collect(toList());
assertThat(classes).contains(SampleTestClass.class, TestDiscoveryRequestBuilderTests.class);
}
@Test
public void methodsByNameAreStoredInDiscoveryRequest() throws Exception {
Class<?> testClass = SampleTestClass.class;
Method testMethod = testClass.getMethod("test");
// @formatter:off
TestDiscoveryRequest discoveryRequest = request()
.select(forMethod(SampleTestClass.class.getName(), "test"))
.build();
// @formatter:on
List<MethodSelector> methodSelectors = discoveryRequest.getSelectorsByType(MethodSelector.class);
assertThat(methodSelectors).hasSize(1);
MethodSelector methodSelector = methodSelectors.get(0);
assertThat(methodSelector.getTestClass()).isEqualTo(testClass);
assertThat(methodSelector.getTestMethod()).isEqualTo(testMethod);
}
@Test
public void methodsByClassAreStoredInDiscoveryRequest() throws Exception {
Class<?> testClass = SampleTestClass.class;
Method testMethod = testClass.getMethod("test");
// @formatter:off
DiscoveryRequest discoveryRequest = (DiscoveryRequest) request()
.select(
MethodSelector.forMethod(SampleTestClass.class, "test")
).build();
// @formatter:on
List<MethodSelector> methodSelectors = discoveryRequest.getSelectorsByType(MethodSelector.class);
assertThat(methodSelectors).hasSize(1);
MethodSelector methodSelector = methodSelectors.get(0);
assertThat(methodSelector.getTestClass()).isEqualTo(testClass);
assertThat(methodSelector.getTestMethod()).isEqualTo(testMethod);
}
@Test
public void unavailableFoldersAreNotStoredInDiscoveryRequest() throws Exception {
// @formatter:off
TestDiscoveryRequest discoveryRequest = request()
.select(
ClasspathSelector.forPath("/some/local/path")
).build();
// @formatter:on
List<String> folders = discoveryRequest.getSelectorsByType(ClasspathSelector.class).stream().map(
ClasspathSelector::getClasspathRoot).map(File::getAbsolutePath).collect(toList());
assertThat(folders).isEmpty();
}
@Test
public void availableFoldersAreStoredInDiscoveryRequest() throws Exception {
File temporaryFolder = Files.newTemporaryFolder();
try {
// @formatter:off
TestDiscoveryRequest discoveryRequest = request()
.select(
ClasspathSelector.forPath(temporaryFolder.getAbsolutePath())
).build();
// @formatter:on
List<String> folders = discoveryRequest.getSelectorsByType(ClasspathSelector.class).stream().map(
ClasspathSelector::getClasspathRoot).map(File::getAbsolutePath).collect(toList());
assertThat(folders).contains(temporaryFolder.getAbsolutePath());
}
finally {
temporaryFolder.delete();
}
}
@Test
public void uniqueIdsAreStoredInDiscoveryRequest() throws Exception {
// @formatter:off
TestDiscoveryRequest discoveryRequest = request()
.select(
forUniqueId("engine:bla:foo:bar:id1"),
forUniqueId("engine:bla:foo:bar:id2")
).build();
// @formatter:on
List<String> uniqueIds = discoveryRequest.getSelectorsByType(UniqueIdSelector.class).stream().map(
UniqueIdSelector::getUniqueId).collect(toList());
assertThat(uniqueIds).contains("engine:bla:foo:bar:id1", "engine:bla:foo:bar:id2");
}
}
@Nested
class DiscoveryFilterTests {
@Test
public void engineFiltersAreStoredInDiscoveryRequest() throws Exception {
// @formatter:off
TestDiscoveryRequest discoveryRequest = request()
.filter(
EngineIdFilter.byEngineId("engine1"),
EngineIdFilter.byEngineId("engine2")
).build();
// @formatter:on
List<String> engineIds = discoveryRequest.getEngineIdFilters().stream().map(
EngineIdFilter::getEngineId).collect(toList());
assertThat(engineIds).hasSize(2);
assertThat(engineIds).contains("engine1", "engine2");
}
@Test
@SuppressWarnings("rawtypes")
public void discoveryFiltersAreStoredInDiscoveryRequest() throws Exception {
// @formatter:off
TestDiscoveryRequest discoveryRequest = request()
.filter(
new DiscoveryFilterStub("filter1"),
new DiscoveryFilterStub("filter2")
).build();
// @formatter:on
List<String> filterStrings = discoveryRequest.getDiscoveryFiltersByType(DiscoveryFilter.class).stream().map(
DiscoveryFilter::toString).collect(toList());
assertThat(filterStrings).hasSize(2);
assertThat(filterStrings).contains("filter1", "filter2");
}
@Test
public void postDiscoveryFiltersAreStoredInDiscoveryRequest() throws Exception {
// @formatter:off
TestDiscoveryRequest discoveryRequest = request()
.filter(
new PostDiscoveryFilterStub("postFilter1"),
new PostDiscoveryFilterStub("postFilter2")
).build();
// @formatter:on
List<String> filterStrings = discoveryRequest.getPostDiscoveryFilters().stream().map(
PostDiscoveryFilter::toString).collect(toList());
assertThat(filterStrings).hasSize(2);
assertThat(filterStrings).contains("postFilter1", "postFilter2");
}
@Test
public void exceptionForIllegalFilterClass() throws Exception {
PreconditionViolationException exception = expectThrows(PreconditionViolationException.class,
() -> request().filter(o -> excluded("reason")));
assertEquals("Filter must implement EngineIdFilter, PostDiscoveryFilter or DiscoveryFilter.",
exception.getMessage());
}
}
@Test
void withoutLaunchParametersSet_NoLaunchParametersAreStoredInDiscoveryRequest() throws Exception {
TestDiscoveryRequest discoveryRequest = request().build();
assertThat(discoveryRequest.getLaunchParameter("key").isPresent()).isFalse();
assertThat(discoveryRequest.getLaunchParameters()).isEmpty();
}
@Test
void launchParameterAddedDirectly_isStoredInDiscoveryRequest() throws Exception {
// @formatter:off
TestDiscoveryRequest discoveryRequest = request()
.launchParameter("key", "value")
.build();
assertThat(discoveryRequest.getLaunchParameter("key").isPresent()).isTrue();
assertThat(discoveryRequest.getLaunchParameter("key").get()).isEqualTo("value");
assertThat(discoveryRequest.getLaunchParameters())
.hasSize(1)
.containsKey("key")
.containsValue("value");
// @formatter:on
}
@Test
void launchParameterAddedDirectlyTwice_overridesPreviousValueInDiscoveryRequest() throws Exception {
// @formatter:off
TestDiscoveryRequest discoveryRequest = request()
.launchParameter("key", "value")
.launchParameter("key", "value-new")
.build();
assertThat(discoveryRequest.getLaunchParameter("key").isPresent()).isTrue();
assertThat(discoveryRequest.getLaunchParameter("key").get()).isEqualTo("value-new");
assertThat(discoveryRequest.getLaunchParameters())
.hasSize(1)
.containsKey("key")
.containsValue("value-new");
// @formatter:on
}
@Test
void multipleLaunchParameterAddedDirectly_isStoredInDiscoveryRequest() throws Exception {
// @formatter:off
TestDiscoveryRequest discoveryRequest = request()
.launchParameter("key1", "value1")
.launchParameter("key2", "value2")
.build();
assertThat(discoveryRequest.getLaunchParameter("key1").isPresent()).isTrue();
assertThat(discoveryRequest.getLaunchParameter("key1").get()).isEqualTo("value1");
assertThat(discoveryRequest.getLaunchParameter("key2").isPresent()).isTrue();
assertThat(discoveryRequest.getLaunchParameter("key2").get()).isEqualTo("value2");
assertThat(discoveryRequest.getLaunchParameters())
.hasSize(2)
.containsKeys("key1", "key2")
.containsValues("value1", "value2");
// @formatter:on
}
@Test
void launchParameterAddedByList_isStoredInDiscoveryRequest() throws Exception {
// @formatter:off
TestDiscoveryRequest discoveryRequest = request()
.launchParameters(keyValuePair("key", "value"))
.build();
assertThat(discoveryRequest.getLaunchParameter("key").isPresent()).isTrue();
assertThat(discoveryRequest.getLaunchParameter("key").get()).isEqualTo("value");
assertThat(discoveryRequest.getLaunchParameters())
.hasSize(1)
.containsKey("key")
.containsValue("value");
// @formatter:on
}
@Test
void multipleLaunchParameterAddedByList_isStoredInDiscoveryRequest() throws Exception {
// @formatter:off
TestDiscoveryRequest discoveryRequest = request()
.launchParameters(keyValuePair("key1", "value1"))
.launchParameters(keyValuePair("key2", "value2"))
.build();
assertThat(discoveryRequest.getLaunchParameter("key1").isPresent()).isTrue();
assertThat(discoveryRequest.getLaunchParameter("key1").get()).isEqualTo("value1");
assertThat(discoveryRequest.getLaunchParameter("key2").isPresent()).isTrue();
assertThat(discoveryRequest.getLaunchParameter("key2").get()).isEqualTo("value2");
assertThat(discoveryRequest.getLaunchParameters())
.hasSize(2)
.containsKeys("key1", "key2")
.containsValues("value1", "value2");
// @formatter:on
}
@Test
void launchParameterAddedByListTwice_overridesPreviousValueInDiscoveryRequest() throws Exception {
// @formatter:off
TestDiscoveryRequest discoveryRequest = request()
.launchParameters(
keyValuePair("key", "value"),
keyValuePair("key", "value-new")
)
.build();
assertThat(discoveryRequest.getLaunchParameter("key").isPresent()).isTrue();
assertThat(discoveryRequest.getLaunchParameter("key").get()).isEqualTo("value-new");
assertThat(discoveryRequest.getLaunchParameters())
.hasSize(1)
.containsKey("key")
.containsValue("value-new");
// @formatter:on
}
private static class SampleTestClass {
@Test
public void test() {
}
}
}
|
Polish: Moved tests into nested class #233
|
junit-tests/src/test/java/org/junit/gen5/launcher/main/TestDiscoveryRequestBuilderTests.java
|
Polish: Moved tests into nested class #233
|
<ide><path>unit-tests/src/test/java/org/junit/gen5/launcher/main/TestDiscoveryRequestBuilderTests.java
<ide> }
<ide> }
<ide>
<del> @Test
<del> void withoutLaunchParametersSet_NoLaunchParametersAreStoredInDiscoveryRequest() throws Exception {
<del> TestDiscoveryRequest discoveryRequest = request().build();
<del>
<del> assertThat(discoveryRequest.getLaunchParameter("key").isPresent()).isFalse();
<del> assertThat(discoveryRequest.getLaunchParameters()).isEmpty();
<add> @Nested
<add> class DiscoveryLaunchParameterTests {
<add> @Test
<add> void withoutLaunchParametersSet_NoLaunchParametersAreStoredInDiscoveryRequest() throws Exception {
<add> TestDiscoveryRequest discoveryRequest = request().build();
<add>
<add> assertThat(discoveryRequest.getLaunchParameter("key").isPresent()).isFalse();
<add> assertThat(discoveryRequest.getLaunchParameters()).isEmpty();
<add> }
<add>
<add> @Test
<add> void launchParameterAddedDirectly_isStoredInDiscoveryRequest() throws Exception {
<add> // @formatter:off
<add> TestDiscoveryRequest discoveryRequest = request()
<add> .launchParameter("key", "value")
<add> .build();
<add>
<add> assertThat(discoveryRequest.getLaunchParameter("key").isPresent()).isTrue();
<add> assertThat(discoveryRequest.getLaunchParameter("key").get()).isEqualTo("value");
<add> assertThat(discoveryRequest.getLaunchParameters())
<add> .hasSize(1)
<add> .containsKey("key")
<add> .containsValue("value");
<add> // @formatter:on
<add> }
<add>
<add> @Test
<add> void launchParameterAddedDirectlyTwice_overridesPreviousValueInDiscoveryRequest() throws Exception {
<add> // @formatter:off
<add> TestDiscoveryRequest discoveryRequest = request()
<add> .launchParameter("key", "value")
<add> .launchParameter("key", "value-new")
<add> .build();
<add>
<add> assertThat(discoveryRequest.getLaunchParameter("key").isPresent()).isTrue();
<add> assertThat(discoveryRequest.getLaunchParameter("key").get()).isEqualTo("value-new");
<add> assertThat(discoveryRequest.getLaunchParameters())
<add> .hasSize(1)
<add> .containsKey("key")
<add> .containsValue("value-new");
<add> // @formatter:on
<add> }
<add>
<add> @Test
<add> void multipleLaunchParameterAddedDirectly_isStoredInDiscoveryRequest() throws Exception {
<add> // @formatter:off
<add> TestDiscoveryRequest discoveryRequest = request()
<add> .launchParameter("key1", "value1")
<add> .launchParameter("key2", "value2")
<add> .build();
<add>
<add> assertThat(discoveryRequest.getLaunchParameter("key1").isPresent()).isTrue();
<add> assertThat(discoveryRequest.getLaunchParameter("key1").get()).isEqualTo("value1");
<add> assertThat(discoveryRequest.getLaunchParameter("key2").isPresent()).isTrue();
<add> assertThat(discoveryRequest.getLaunchParameter("key2").get()).isEqualTo("value2");
<add> assertThat(discoveryRequest.getLaunchParameters())
<add> .hasSize(2)
<add> .containsKeys("key1", "key2")
<add> .containsValues("value1", "value2");
<add> // @formatter:on
<add> }
<add>
<add> @Test
<add> void launchParameterAddedByList_isStoredInDiscoveryRequest() throws Exception {
<add> // @formatter:off
<add> TestDiscoveryRequest discoveryRequest = request()
<add> .launchParameters(keyValuePair("key", "value"))
<add> .build();
<add>
<add> assertThat(discoveryRequest.getLaunchParameter("key").isPresent()).isTrue();
<add> assertThat(discoveryRequest.getLaunchParameter("key").get()).isEqualTo("value");
<add> assertThat(discoveryRequest.getLaunchParameters())
<add> .hasSize(1)
<add> .containsKey("key")
<add> .containsValue("value");
<add> // @formatter:on
<add> }
<add>
<add> @Test
<add> void multipleLaunchParameterAddedByList_isStoredInDiscoveryRequest() throws Exception {
<add> // @formatter:off
<add> TestDiscoveryRequest discoveryRequest = request()
<add> .launchParameters(keyValuePair("key1", "value1"))
<add> .launchParameters(keyValuePair("key2", "value2"))
<add> .build();
<add>
<add> assertThat(discoveryRequest.getLaunchParameter("key1").isPresent()).isTrue();
<add> assertThat(discoveryRequest.getLaunchParameter("key1").get()).isEqualTo("value1");
<add> assertThat(discoveryRequest.getLaunchParameter("key2").isPresent()).isTrue();
<add> assertThat(discoveryRequest.getLaunchParameter("key2").get()).isEqualTo("value2");
<add> assertThat(discoveryRequest.getLaunchParameters())
<add> .hasSize(2)
<add> .containsKeys("key1", "key2")
<add> .containsValues("value1", "value2");
<add> // @formatter:on
<add> }
<add>
<add> @Test
<add> void launchParameterAddedByListTwice_overridesPreviousValueInDiscoveryRequest() throws Exception {
<add> // @formatter:off
<add> TestDiscoveryRequest discoveryRequest = request()
<add> .launchParameters(
<add> keyValuePair("key", "value"),
<add> keyValuePair("key", "value-new")
<add> )
<add> .build();
<add>
<add> assertThat(discoveryRequest.getLaunchParameter("key").isPresent()).isTrue();
<add> assertThat(discoveryRequest.getLaunchParameter("key").get()).isEqualTo("value-new");
<add> assertThat(discoveryRequest.getLaunchParameters())
<add> .hasSize(1)
<add> .containsKey("key")
<add> .containsValue("value-new");
<add> // @formatter:on
<add> }
<ide> }
<ide>
<del> @Test
<del> void launchParameterAddedDirectly_isStoredInDiscoveryRequest() throws Exception {
<del> // @formatter:off
<del> TestDiscoveryRequest discoveryRequest = request()
<del> .launchParameter("key", "value")
<del> .build();
<del>
<del> assertThat(discoveryRequest.getLaunchParameter("key").isPresent()).isTrue();
<del> assertThat(discoveryRequest.getLaunchParameter("key").get()).isEqualTo("value");
<del> assertThat(discoveryRequest.getLaunchParameters())
<del> .hasSize(1)
<del> .containsKey("key")
<del> .containsValue("value");
<del> // @formatter:on
<add> private static class SampleTestClass {
<add>
<add> @Test
<add> public void test() {
<add> }
<ide> }
<ide>
<del> @Test
<del> void launchParameterAddedDirectlyTwice_overridesPreviousValueInDiscoveryRequest() throws Exception {
<del> // @formatter:off
<del> TestDiscoveryRequest discoveryRequest = request()
<del> .launchParameter("key", "value")
<del> .launchParameter("key", "value-new")
<del> .build();
<del>
<del> assertThat(discoveryRequest.getLaunchParameter("key").isPresent()).isTrue();
<del> assertThat(discoveryRequest.getLaunchParameter("key").get()).isEqualTo("value-new");
<del> assertThat(discoveryRequest.getLaunchParameters())
<del> .hasSize(1)
<del> .containsKey("key")
<del> .containsValue("value-new");
<del> // @formatter:on
<del> }
<del>
<del> @Test
<del> void multipleLaunchParameterAddedDirectly_isStoredInDiscoveryRequest() throws Exception {
<del> // @formatter:off
<del> TestDiscoveryRequest discoveryRequest = request()
<del> .launchParameter("key1", "value1")
<del> .launchParameter("key2", "value2")
<del> .build();
<del>
<del> assertThat(discoveryRequest.getLaunchParameter("key1").isPresent()).isTrue();
<del> assertThat(discoveryRequest.getLaunchParameter("key1").get()).isEqualTo("value1");
<del> assertThat(discoveryRequest.getLaunchParameter("key2").isPresent()).isTrue();
<del> assertThat(discoveryRequest.getLaunchParameter("key2").get()).isEqualTo("value2");
<del> assertThat(discoveryRequest.getLaunchParameters())
<del> .hasSize(2)
<del> .containsKeys("key1", "key2")
<del> .containsValues("value1", "value2");
<del> // @formatter:on
<del> }
<del>
<del> @Test
<del> void launchParameterAddedByList_isStoredInDiscoveryRequest() throws Exception {
<del> // @formatter:off
<del> TestDiscoveryRequest discoveryRequest = request()
<del> .launchParameters(keyValuePair("key", "value"))
<del> .build();
<del>
<del> assertThat(discoveryRequest.getLaunchParameter("key").isPresent()).isTrue();
<del> assertThat(discoveryRequest.getLaunchParameter("key").get()).isEqualTo("value");
<del> assertThat(discoveryRequest.getLaunchParameters())
<del> .hasSize(1)
<del> .containsKey("key")
<del> .containsValue("value");
<del> // @formatter:on
<del> }
<del>
<del> @Test
<del> void multipleLaunchParameterAddedByList_isStoredInDiscoveryRequest() throws Exception {
<del> // @formatter:off
<del> TestDiscoveryRequest discoveryRequest = request()
<del> .launchParameters(keyValuePair("key1", "value1"))
<del> .launchParameters(keyValuePair("key2", "value2"))
<del> .build();
<del>
<del> assertThat(discoveryRequest.getLaunchParameter("key1").isPresent()).isTrue();
<del> assertThat(discoveryRequest.getLaunchParameter("key1").get()).isEqualTo("value1");
<del> assertThat(discoveryRequest.getLaunchParameter("key2").isPresent()).isTrue();
<del> assertThat(discoveryRequest.getLaunchParameter("key2").get()).isEqualTo("value2");
<del> assertThat(discoveryRequest.getLaunchParameters())
<del> .hasSize(2)
<del> .containsKeys("key1", "key2")
<del> .containsValues("value1", "value2");
<del> // @formatter:on
<del> }
<del>
<del> @Test
<del> void launchParameterAddedByListTwice_overridesPreviousValueInDiscoveryRequest() throws Exception {
<del> // @formatter:off
<del> TestDiscoveryRequest discoveryRequest = request()
<del> .launchParameters(
<del> keyValuePair("key", "value"),
<del> keyValuePair("key", "value-new")
<del> )
<del> .build();
<del>
<del> assertThat(discoveryRequest.getLaunchParameter("key").isPresent()).isTrue();
<del> assertThat(discoveryRequest.getLaunchParameter("key").get()).isEqualTo("value-new");
<del> assertThat(discoveryRequest.getLaunchParameters())
<del> .hasSize(1)
<del> .containsKey("key")
<del> .containsValue("value-new");
<del> // @formatter:on
<del> }
<del>
<del> private static class SampleTestClass {
<del>
<del> @Test
<del> public void test() {
<del> }
<del> }
<del>
<ide> }
|
|
Java
|
mit
|
error: pathspec 'src/main/java/com/suse/saltstack/netapi/calls/modules/Status.java' did not match any file(s) known to git
|
2108d9d8e9ea125414386a7e1295bea9a3b9a2d4
| 1 |
SUSE/salt-netapi-client,jkandasa/saltstack-netapi-client-java,mbologna/saltstack-netapi-client-java,SUSE/saltstack-netapi-client-java,mbologna/saltstack-netapi-client-java,lucidd/saltstack-netapi-client-java,mbologna/salt-netapi-client,mbologna/salt-netapi-client,jkandasa/saltstack-netapi-client-java,lucidd/saltstack-netapi-client-java,SUSE/saltstack-netapi-client-java
|
package com.suse.saltstack.netapi.calls.modules;
import com.suse.saltstack.netapi.calls.LocalCall;
import com.google.gson.reflect.TypeToken;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* salt.modules.status
*/
public class Status {
private Status() { }
public static LocalCall<Map<String, Object>> allstatus() {
return new LocalCall<>("status.all_status", Optional.empty(), Optional.empty(),
new TypeToken<Map<String, Object>>(){});
}
public static LocalCall<Map<String, Object>> cpuinfo() {
return new LocalCall<>("status.cpuinfo", Optional.empty(), Optional.empty(),
new TypeToken<Map<String, Object>>(){});
}
public static LocalCall<Map<String, Object>> cpustats() {
return new LocalCall<>("status.cpustats", Optional.empty(), Optional.empty(),
new TypeToken<Map<String, Object>>(){});
}
public static LocalCall<Map<String, Object>> custom() {
return new LocalCall<>("status.custom", Optional.empty(), Optional.empty(),
new TypeToken<Map<String, Object>>(){});
}
public static LocalCall<Map<String, Map<String, Object>>> diskstats() {
return new LocalCall<>("status.diskstats", Optional.empty(), Optional.empty(),
new TypeToken<Map<String, Map<String, Object>>>(){});
}
public static LocalCall<Map<String, Map<String, Long>>> diskusage(
String... pathsOrFSTypes) {
List<Object> args = Arrays.asList((Object[]) pathsOrFSTypes);
return new LocalCall<>("status.diskusage", Optional.of(args), Optional.empty(),
new TypeToken<Map<String, Map<String, Long>>>(){});
}
public static LocalCall<Map<String, Double>> loadavg() {
return new LocalCall<>("status.loadavg", Optional.empty(), Optional.empty(),
new TypeToken<Map<String, Double>>(){});
}
public static LocalCall<Map<String, Map<String, Object>>> meminfo() {
return new LocalCall<>("status.meminfo", Optional.empty(), Optional.empty(),
new TypeToken<Map<String, Map<String, Object>>>(){});
}
public static LocalCall<Map<String, Map<String, Object>>> netdev() {
return new LocalCall<>("status.netdev", Optional.empty(), Optional.empty(),
new TypeToken<Map<String, Map<String, Object>>>(){});
}
public static LocalCall<Map<String, Map<String, Long>>> netstats() {
return new LocalCall<>("status.netstats", Optional.empty(), Optional.empty(),
new TypeToken<Map<String, Map<String, Long>>>(){});
}
public static LocalCall<Integer> nproc() {
return new LocalCall<>("status.nproc", Optional.empty(), Optional.empty(),
new TypeToken<Integer>(){});
}
public static LocalCall<String> pid(String signature) {
List<Object> args = new ArrayList<>();
args.add(signature);
return new LocalCall<>("status.pid", Optional.of(args), Optional.empty(),
new TypeToken<String>(){});
}
public static LocalCall<Map<Integer, Map<String, String>>> procs() {
return new LocalCall<>("status.procs", Optional.empty(), Optional.empty(),
new TypeToken<Map<Integer, Map<String, String>>>(){});
}
public static LocalCall<String> uptime() {
return new LocalCall<>("status.uptime", Optional.empty(), Optional.empty(),
new TypeToken<String>(){});
}
public static LocalCall<String> version() {
return new LocalCall<>("status.version", Optional.empty(), Optional.empty(),
new TypeToken<String>(){});
}
public static LocalCall<Map<String, Long>> vmstats() {
return new LocalCall<>("status.vmstats", Optional.empty(), Optional.empty(),
new TypeToken<Map<String, Long>>(){});
}
public static LocalCall<List<Map<String, String>>> w() {
return new LocalCall<>("status.w", Optional.empty(), Optional.empty(),
new TypeToken<List<Map<String, String>>>(){});
}
}
|
src/main/java/com/suse/saltstack/netapi/calls/modules/Status.java
|
Add support for salt.modules.status
https://docs.saltstack.com/en/latest/ref/modules/all/salt.modules.status.html
|
src/main/java/com/suse/saltstack/netapi/calls/modules/Status.java
|
Add support for salt.modules.status
|
<ide><path>rc/main/java/com/suse/saltstack/netapi/calls/modules/Status.java
<add>package com.suse.saltstack.netapi.calls.modules;
<add>
<add>import com.suse.saltstack.netapi.calls.LocalCall;
<add>
<add>import com.google.gson.reflect.TypeToken;
<add>
<add>import java.util.ArrayList;
<add>import java.util.Arrays;
<add>import java.util.List;
<add>import java.util.Map;
<add>import java.util.Optional;
<add>
<add>/**
<add> * salt.modules.status
<add> */
<add>public class Status {
<add>
<add> private Status() { }
<add>
<add> public static LocalCall<Map<String, Object>> allstatus() {
<add> return new LocalCall<>("status.all_status", Optional.empty(), Optional.empty(),
<add> new TypeToken<Map<String, Object>>(){});
<add> }
<add>
<add> public static LocalCall<Map<String, Object>> cpuinfo() {
<add> return new LocalCall<>("status.cpuinfo", Optional.empty(), Optional.empty(),
<add> new TypeToken<Map<String, Object>>(){});
<add> }
<add>
<add> public static LocalCall<Map<String, Object>> cpustats() {
<add> return new LocalCall<>("status.cpustats", Optional.empty(), Optional.empty(),
<add> new TypeToken<Map<String, Object>>(){});
<add> }
<add>
<add> public static LocalCall<Map<String, Object>> custom() {
<add> return new LocalCall<>("status.custom", Optional.empty(), Optional.empty(),
<add> new TypeToken<Map<String, Object>>(){});
<add> }
<add>
<add> public static LocalCall<Map<String, Map<String, Object>>> diskstats() {
<add> return new LocalCall<>("status.diskstats", Optional.empty(), Optional.empty(),
<add> new TypeToken<Map<String, Map<String, Object>>>(){});
<add> }
<add>
<add> public static LocalCall<Map<String, Map<String, Long>>> diskusage(
<add> String... pathsOrFSTypes) {
<add> List<Object> args = Arrays.asList((Object[]) pathsOrFSTypes);
<add> return new LocalCall<>("status.diskusage", Optional.of(args), Optional.empty(),
<add> new TypeToken<Map<String, Map<String, Long>>>(){});
<add> }
<add>
<add> public static LocalCall<Map<String, Double>> loadavg() {
<add> return new LocalCall<>("status.loadavg", Optional.empty(), Optional.empty(),
<add> new TypeToken<Map<String, Double>>(){});
<add> }
<add>
<add> public static LocalCall<Map<String, Map<String, Object>>> meminfo() {
<add> return new LocalCall<>("status.meminfo", Optional.empty(), Optional.empty(),
<add> new TypeToken<Map<String, Map<String, Object>>>(){});
<add> }
<add>
<add> public static LocalCall<Map<String, Map<String, Object>>> netdev() {
<add> return new LocalCall<>("status.netdev", Optional.empty(), Optional.empty(),
<add> new TypeToken<Map<String, Map<String, Object>>>(){});
<add> }
<add>
<add> public static LocalCall<Map<String, Map<String, Long>>> netstats() {
<add> return new LocalCall<>("status.netstats", Optional.empty(), Optional.empty(),
<add> new TypeToken<Map<String, Map<String, Long>>>(){});
<add> }
<add>
<add> public static LocalCall<Integer> nproc() {
<add> return new LocalCall<>("status.nproc", Optional.empty(), Optional.empty(),
<add> new TypeToken<Integer>(){});
<add> }
<add>
<add> public static LocalCall<String> pid(String signature) {
<add> List<Object> args = new ArrayList<>();
<add> args.add(signature);
<add> return new LocalCall<>("status.pid", Optional.of(args), Optional.empty(),
<add> new TypeToken<String>(){});
<add> }
<add>
<add> public static LocalCall<Map<Integer, Map<String, String>>> procs() {
<add> return new LocalCall<>("status.procs", Optional.empty(), Optional.empty(),
<add> new TypeToken<Map<Integer, Map<String, String>>>(){});
<add> }
<add>
<add> public static LocalCall<String> uptime() {
<add> return new LocalCall<>("status.uptime", Optional.empty(), Optional.empty(),
<add> new TypeToken<String>(){});
<add> }
<add>
<add> public static LocalCall<String> version() {
<add> return new LocalCall<>("status.version", Optional.empty(), Optional.empty(),
<add> new TypeToken<String>(){});
<add> }
<add>
<add> public static LocalCall<Map<String, Long>> vmstats() {
<add> return new LocalCall<>("status.vmstats", Optional.empty(), Optional.empty(),
<add> new TypeToken<Map<String, Long>>(){});
<add> }
<add>
<add> public static LocalCall<List<Map<String, String>>> w() {
<add> return new LocalCall<>("status.w", Optional.empty(), Optional.empty(),
<add> new TypeToken<List<Map<String, String>>>(){});
<add> }
<add>}
|
|
Java
|
apache-2.0
|
10ecc19ee50330c4a49d04b6791d3b6d1b50ef60
| 0 |
MatthewTamlin/Spyglass
|
package com.matthewtamlin.spyglass.library.handler_adapters;
import android.content.res.TypedArray;
import com.matthewtamlin.spyglass.library.handler_annotations.FlagHandler;
import static com.matthewtamlin.java_utilities.checkers.NullChecker.checkNotNull;
public class FlagHandlerAdapter implements HandlerAdapter<Void, FlagHandler> {
@Override
public TypedArrayAccessor<Void> getAccessor(final FlagHandler annotation) {
checkNotNull(annotation, "Argument \'annotation\' cannot be null.");
return new TypedArrayAccessor<Void>() {
@Override
public boolean valueExistsInArray(final TypedArray array) {
checkNotNull(array, "Argument \'array\' cannot be null.");
// Compare two different results to see if the default is consistently returned
final int reading1 = array.getInt(annotation.attributeId(), 0);
final int reading2 = array.getInt(annotation.attributeId(), 1);
final boolean consistentlyDefault = (reading1 == 0) && (reading2 == 1);
if (!consistentlyDefault) {
final int handledFlags = annotation.handledFlags();
final int foundFlags = array.getInt(annotation.attributeId(), 0);
// Return true if at least one flag bit matches
return (foundFlags & handledFlags) > 0;
} else {
return false;
}
}
@Override
public Void getValueFromArray(final TypedArray array) {
checkNotNull(array, "Argument \'array\' cannot be null.");
if (valueExistsInArray(array)) {
return null;
} else {
throw new RuntimeException("No attribute found for attribute ID " +
annotation.attributeId());
}
}
};
}
@Override
public int getAttributeId(final FlagHandler annotation) {
checkNotNull(annotation, "Argument \'annotation\' cannot be null.");
return annotation.attributeId();
}
@Override
public boolean isMandatory(final FlagHandler annotation) {
checkNotNull(annotation, "Argument \'annotation\' cannot be null.");
return false;
}
}
|
library/src/main/java/com/matthewtamlin/spyglass/library/handler_adapters/FlagHandlerAdapter.java
|
package com.matthewtamlin.spyglass.library.handler_adapters;
import android.content.res.TypedArray;
import com.matthewtamlin.spyglass.library.handler_annotations.FlagHandler;
import static com.matthewtamlin.java_utilities.checkers.NullChecker.checkNotNull;
public class FlagHandlerAdapter implements HandlerAdapter<Void, FlagHandler> {
@Override
public TypedArrayAccessor<Void> getAccessor(final FlagHandler annotation) {
checkNotNull(annotation, "Argument \'annotation\' cannot be null.");
return new TypedArrayAccessor<Void>() {
@Override
public boolean valueExistsInArray(final TypedArray array) {
checkNotNull(array, "Argument \'array\' cannot be null.");
// Compare two different results to see if the default is consistently returned
final int reading1 = array.getInt(annotation.attributeId(), 0);
final int reading2 = array.getInt(annotation.attributeId(), 1);
final boolean consistentlyDefault = (reading1 == 0) && (reading2 == 1);
if (!consistentlyDefault) {
final int handledFlags = annotation.handledFlags();
final int foundFlags = array.getInt(annotation.attributeId(), 0);
// Return true if at least one flag bit matches
return (reading1 & handledFlags) > 0;
} else {
return false;
}
}
@Override
public Void getValueFromArray(final TypedArray array) {
checkNotNull(array, "Argument \'array\' cannot be null.");
if (valueExistsInArray(array)) {
return null;
} else {
throw new RuntimeException("No attribute found for attribute ID " +
annotation.attributeId());
}
}
};
}
@Override
public int getAttributeId(final FlagHandler annotation) {
checkNotNull(annotation, "Argument \'annotation\' cannot be null.");
return annotation.attributeId();
}
@Override
public boolean isMandatory(final FlagHandler annotation) {
checkNotNull(annotation, "Argument \'annotation\' cannot be null.");
return false;
}
}
|
Fixed incorrect variable reference
|
library/src/main/java/com/matthewtamlin/spyglass/library/handler_adapters/FlagHandlerAdapter.java
|
Fixed incorrect variable reference
|
<ide><path>ibrary/src/main/java/com/matthewtamlin/spyglass/library/handler_adapters/FlagHandlerAdapter.java
<ide> final int foundFlags = array.getInt(annotation.attributeId(), 0);
<ide>
<ide> // Return true if at least one flag bit matches
<del> return (reading1 & handledFlags) > 0;
<add> return (foundFlags & handledFlags) > 0;
<ide> } else {
<ide> return false;
<ide> }
|
|
JavaScript
|
mit
|
01da52ba47eb3c0f9162deb4e69b8803087a7bf2
| 0 |
hl198181/neptune,hl198181/neptune
|
/*!
* mars
* Copyright(c) 2015 huangbinglong
* MIT Licensed
*/
angular.module("ui.neptune.formly.ui-select")
.run(function (formlyConfig, $q, $filter) {
formlyConfig.setType({
name: 'ui-select',
extends: 'select',
templateUrl: "/template/formly/ui-select.html",
defaultOptions: {
wrapper: ["showErrorMessage"],
ngModelAttrs: {
multiple: {
attribute: 'multiple'
}
},
templateOptions: {
ngOptions: 'option[to.valueProp] as option in to.options | filterBy:[to.valueProp,to.labelProp]: $select.search',
refresh: function refresh(value, model, field, scope) {
var valueProp = field.templateOptions.valueProp;
var labelProp = field.templateOptions.labelProp;
//默认空内容
var promise = $q.when({
data: []
});
var searchFields = angular.copy(field.templateOptions.search || []);
var searchValue = value;
var keepModelValue = model[field.key];
field.templateOptions.placeholder = field.templateOptions.placeholder || "";
if (field.templateOptions.search && field.templateOptions.repository) {
//存在search以及repository,表示按输入条件检索
//model[field.key];
//此处会有一个暂时不好解决的问题.如果当前模型数据上有值,在首次刷新页面后,由于没有输入值,会导致此处不刷新后台数据,
//从而导致界面显示空,但是实际有模型数据
if (!value && !model[field.key]) { //viewValue跟modelValue都为空
// 监控model值的变化;
// 因为refresh仅在viewValue改变时触发
var theWatcher = scope.$watch("model." + field.key, function (nV, oV,$scope) {
if (nV && nV != oV) {
theWatcher();
field.templateOptions.refresh(undefined, $scope.$parent.model, field, $scope);
}
});
return;
}
var filterBy = $filter("filterBy");
var params = angular.copy(field.templateOptions.repositoryParams, {});
var oldOptions = field.templateOptions.options || [];
if (value) {
//检查到输入内容,检索数据
oldOptions = filterBy(field.templateOptions.options, [labelProp], value);
if (searchFields.length === 0) {
searchFields.push(labelProp);
}
searchValue = value;
} else if (model[field.key]) {
//使用模型值,检索数据
oldOptions = filterBy(field.templateOptions.options, [valueProp], model[field.key]);
if (searchFields.length === 0) {
searchFields.push(valueProp);
}
searchValue = model[field.key];
model[field.key] = undefined;
}
if (oldOptions.length > 0) { // 用户输入或者model里面的值在现有的options中存在,不检索
promise = $q.when({
data: oldOptions
});
} else {
field.templateOptions.placeholder = field.templateOptions.placeholder + " (正在查询...)";
if (angular.isArray(searchValue)) {
var promiseArr = [];
angular.forEach(searchValue, function (sv) {
promiseArr.push(function () {
var pParams = angular.copy(params);
searchFields.forEach(function (field) {
pParams[field] = sv;
});
return field.templateOptions.repository.post(pParams);
}());
});
promise = $q.all(promiseArr);
} else {
searchFields.forEach(function (field) {
params[field] = searchValue;
});
promise = field.templateOptions.repository.post(params);
}
}
} else if (field.templateOptions.options && field.templateOptions.options.length > 0) {
//存在options,使用静态选择
promise = $q.when({
data: field.templateOptions.options
});
} else if (field.templateOptions.repository) {
//存在repository表示,检索资源作为待选列表,只在首次检索
field.templateOptions.placeholder = field.templateOptions.placeholder + " (正在查询...)";
promise = field.templateOptions.repository.post(field.templateOptions.repositoryParams || {});
}
return promise.then(function (response) {
field.templateOptions.placeholder = field.templateOptions.placeholder.replace(" (正在查询...)", "");
model[field.key] = keepModelValue;
if (angular.isArray(response)) {
field.templateOptions.options = [];
angular.forEach(response, function (resp) {
var dd = angular.isArray(resp.data) ? resp.data : [resp.data];
dd.forEach(function (d) {
field.templateOptions.options.push(d);
});
});
} else {
field.templateOptions.options = angular.isArray(response.data) ? response.data : [response.data];
}
if (!model[field.key] && angular.isDefined(field.templateOptions.selectIndex) &&
field.templateOptions.options && field.templateOptions.options.length > 0 && !value) {
var indx = field.templateOptions.selectIndex;
if (field.templateOptions.multiple) {
model[field.key] = [];
model[field.key].push(field.templateOptions.options[indx][valueProp]);
} else {
model[field.key] = field.templateOptions.options[indx][valueProp];
}
}
// 更新后事件
if (field.templateOptions.afterRefresh) {
field.templateOptions.afterRefresh(value, model, field, scope);
}
});
},
refreshDelay: 0
}
}
});
});
|
src/npt/formly/ui-select.js
|
/*!
* mars
* Copyright(c) 2015 huangbinglong
* MIT Licensed
*/
angular.module("ui.neptune.formly.ui-select")
.run(function (formlyConfig, $q, $filter) {
formlyConfig.setType({
name: 'ui-select',
extends: 'select',
templateUrl: "/template/formly/ui-select.html",
defaultOptions: {
wrapper: ["showErrorMessage"],
ngModelAttrs: {
multiple: {
attribute: 'multiple'
}
},
templateOptions: {
ngOptions: 'option[to.valueProp] as option in to.options | filterBy:[to.valueProp,to.labelProp]: $select.search',
refresh: function refresh(value, model, field, scope) {
var valueProp = field.templateOptions.valueProp;
var labelProp = field.templateOptions.labelProp;
//默认空内容
var promise = $q.when({
data: []
});
var searchFields = angular.copy(field.templateOptions.search || []);
var searchValue = value;
var keepModelValue = model[field.key];
field.templateOptions.placeholder = field.templateOptions.placeholder || "";
if (field.templateOptions.search && field.templateOptions.repository) {
//存在search以及repository,表示按输入条件检索
//model[field.key];
//此处会有一个暂时不好解决的问题.如果当前模型数据上有值,在首次刷新页面后,由于没有输入值,会导致此处不刷新后台数据,
//从而导致界面显示空,但是实际有模型数据
if (!value && !model[field.key]) { //viewValue跟modelValue都为空
// 监控model值的变化;
// 因为refresh仅在viewValue改变时触发
var theWatcher = scope.$watch("model." + field.key, function (nV, oV,$scope) {
if (nV && nV != oV) {
theWatcher();
field.templateOptions.refresh(undefined, $scope.$parent.model, field, $scope);
}
});
return;
}
var filterBy = $filter("filterBy");
var params = angular.copy(field.templateOptions.repositoryParams, {});
var oldOptions = field.templateOptions.options || [];
if (value) {
//检查到输入内容,检索数据
oldOptions = filterBy(field.templateOptions.options, [labelProp], value);
if (searchFields.length === 0) {
searchFields.push(labelProp);
}
searchValue = value;
} else if (model[field.key]) {
//使用模型值,检索数据
oldOptions = filterBy(field.templateOptions.options, [valueProp], model[field.key]);
if (searchFields.length === 0) {
searchFields.push(valueProp);
}
searchValue = model[field.key];
model[field.key] = undefined;
}
if (oldOptions.length > 0) { // 用户输入或者model里面的值在现有的options中存在,不检索
promise = $q.when({
data: oldOptions
});
} else {
field.templateOptions.placeholder = field.templateOptions.placeholder + " (正在查询...)";
if (angular.isArray(searchValue)) {
var promiseArr = [];
angular.forEach(searchValue, function (sv) {
promiseArr.push(function () {
var pParams = angular.copy(params);
searchFields.forEach(function (field) {
pParams[field] = sv;
});
return field.templateOptions.repository.post(pParams);
}());
});
promise = $q.all(promiseArr);
} else {
searchFields.forEach(function (field) {
params[field] = searchValue;
});
promise = field.templateOptions.repository.post(params);
}
}
} else if (field.templateOptions.options && field.templateOptions.options.length > 0) {
//存在options,使用静态选择
promise = $q.when({
data: field.templateOptions.options
});
} else if (field.templateOptions.repository) {
//存在repository表示,检索资源作为待选列表,只在首次检索
field.templateOptions.placeholder = field.templateOptions.placeholder + " (正在查询...)";
promise = field.templateOptions.repository.post(field.templateOptions.repositoryParams || {});
}
return promise.then(function (response) {
field.templateOptions.placeholder = field.templateOptions.placeholder.replace(" (正在查询...)", "");
model[field.key] = keepModelValue;
if (angular.isArray(response)) {
field.templateOptions.options = [];
angular.forEach(response, function (resp) {
var dd = angular.isArray(resp.data) ? resp.data : [resp.data];
dd.forEach(function (d) {
field.templateOptions.options.push(d);
});
});
} else {
field.templateOptions.options = angular.isArray(response.data) ? response.data : [response.data];
}
if (!model[field.key] && angular.isDefined(field.templateOptions.selectIndex) &&
field.templateOptions.options && field.templateOptions.options.length > 0 && !value) {
var indx = field.templateOptions.selectIndex;
if (field.templateOptions.multiple) {
model[field.key] = [];
model[field.key].push(field.templateOptions.options[indx][valueProp]);
} else {
model[field.key] = field.templateOptions.options[indx][valueProp];
}
}
// 更新后事件
if (field.templateOptions.afterRrefresh) {
field.templateOptions.afterRrefresh(value, model, field, scope);
}
});
},
refreshDelay: 0
}
}
});
});
|
ui-select afterRefresh
|
src/npt/formly/ui-select.js
|
ui-select afterRefresh
|
<ide><path>rc/npt/formly/ui-select.js
<ide> }
<ide>
<ide> // 更新后事件
<del> if (field.templateOptions.afterRrefresh) {
<del> field.templateOptions.afterRrefresh(value, model, field, scope);
<add> if (field.templateOptions.afterRefresh) {
<add> field.templateOptions.afterRefresh(value, model, field, scope);
<ide> }
<ide>
<ide> });
|
|
Java
|
apache-2.0
|
01e784763c0ca4e284a0c98575fe19e8ab941d60
| 0 |
SLAsticSPE/slastic,SLAsticSPE/slastic,SLAsticSPE/slastic,SLAsticSPE/slastic,SLAsticSPE/slastic,SLAsticSPE/slastic
|
package org.trustsoft.slastic.tests.junit.model.manager.usage;
import java.io.File;
import java.io.IOException;
import java.util.Map.Entry;
import java.util.TreeMap;
import junit.framework.Assert;
import junit.framework.TestCase;
import kieker.common.record.OperationExecutionRecord;
import org.apache.commons.lang.StringUtils;
import org.trustsoft.slastic.plugins.slasticImpl.ModelManager;
import org.trustsoft.slastic.plugins.slasticImpl.model.NameUtils;
import org.trustsoft.slastic.plugins.slasticImpl.model.componentAssembly.ComponentAssemblyModelManager;
import org.trustsoft.slastic.plugins.slasticImpl.model.typeRepository.TypeRepositoryModelManager;
import org.trustsoft.slastic.plugins.slasticImpl.model.usage.UsageModelManager;
import org.trustsoft.slastic.plugins.slasticImpl.monitoring.kieker.reconstruction.ExecutionRecordTransformationFilter;
import org.trustsoft.slastic.tests.junit.model.ModelEntityCreationUtils;
import de.cau.se.slastic.metamodel.componentAssembly.AssemblyComponent;
import de.cau.se.slastic.metamodel.componentAssembly.AssemblyComponentConnector;
import de.cau.se.slastic.metamodel.componentAssembly.SystemProvidedInterfaceDelegationConnector;
import de.cau.se.slastic.metamodel.core.SystemModel;
import de.cau.se.slastic.metamodel.monitoring.DeploymentComponentOperationExecution;
import de.cau.se.slastic.metamodel.typeRepository.Interface;
import de.cau.se.slastic.metamodel.typeRepository.Operation;
import de.cau.se.slastic.metamodel.typeRepository.Signature;
import de.cau.se.slastic.metamodel.usage.AssemblyComponentConnectorCallFrequency;
import de.cau.se.slastic.metamodel.usage.CallingRelationship;
import de.cau.se.slastic.metamodel.usage.FrequencyDistribution;
import de.cau.se.slastic.metamodel.usage.OperationCallFrequency;
import de.cau.se.slastic.metamodel.usage.SystemProvidedInterfaceDelegationConnectorFrequency;
import de.cau.se.slastic.metamodel.usage.UsageFactory;
import de.cau.se.slastic.metamodel.usage.UsageModel;
/**
* In this test, we are manually filling a {@link UsageModel} without the use of
* the {@link UsageModelManager}.
*
* @author Andre van Hoorn
*
*/
public class TestUsageModelSimple extends TestCase {
/** Create {@link ModelManager} with empty {@link SystemModel} and {@link UsageModel} */
private final ModelManager systemModelManager = new ModelManager();
private final TypeRepositoryModelManager typeMgr = this.systemModelManager.getTypeRepositoryManager();
private final ComponentAssemblyModelManager assemblyMgr = this.systemModelManager
.getComponentAssemblyModelManager();
/** Since we are modifying the {@link UsageModel} directly, we need to retrieve it. */
private final UsageModel usageModel = this.systemModelManager.getUsageModelManager().getModel();
private final ExecutionRecordTransformationFilter execRecFilter =
new ExecutionRecordTransformationFilter(this.systemModelManager,
NameUtils.ABSTRACTION_MODE_CLASS);
private volatile AssemblyComponent requiringAsmCompA;
private volatile DeploymentComponentOperationExecution opExecAa;
private volatile Interface providedInterfaceA;
private volatile AssemblyComponent providingAsmCompB;
private volatile DeploymentComponentOperationExecution opExecBb;
private volatile Interface commonInterfaceB;
private volatile AssemblyComponentConnector asmConnector;
private volatile SystemProvidedInterfaceDelegationConnector sysProvDelegationConnector;
/**
* Intermediate data structure capturing the distribution of calls from
* operation A.a(..) to Signature b(..).
* */
private final TreeMap<Long, Long> frequencyMap = new TreeMap<Long, Long>();
{
this.frequencyMap.put(0l, 2l);
// implicitly included: frequencyMap.put(1, 0);
this.frequencyMap.put(2l, 1l);
this.frequencyMap.put(3l, 2l);
// implicitly included: frequencyMap.put(4, 0);
// implicitly included: frequencyMap.put(5, 0);
this.frequencyMap.put(6l, 1l);
}
/**
* Manually fills the {@link UsageModel} without using the
* {@link UsageModelManager}.
* @throws IOException
*/
public void testManuallyFillModel() throws IOException {
this.initModelAndVars();
this.addOperationCallFrequencies();
this.addCallingRelationship();
this.addAssemblyConnectorCallFrequencies();
this.saveModels();
}
/**
* Initializes a {@link SystemModel} by creating (among other entities) the
* {@link AssemblyComponent}s {@link #requiringAsmCompA} and
* {@link #providingAsmCompB} properly connected via the
* {@link AssemblyComponentConnector} {@link #asmConnector} with the common Interface
* {@link #commonInterfaceB}.
*/
private void initModelAndVars() {
// Create asmCompB providing the interface commonInterfaceB
this.opExecBb =
this.fillSystemModelByOperationExecution("package.ComponentB",
/* no required interface: */null,
"opB", "void", new String[] { String.class.getName() });
this.providingAsmCompB = this.opExecBb.getDeploymentComponent().getAssemblyComponent();
this.commonInterfaceB = this.providingAsmCompB.getComponentType().getProvidedInterfaces().get(0);
// Create asmCompA whose type requires asmCompB's type's providing
// interface
this.opExecAa =
this.fillSystemModelByOperationExecution("package.ComponentA", this.commonInterfaceB,
"opA", Long.class.getName(), new String[] { Boolean.class.getName() });
this.requiringAsmCompA = this.opExecAa.getDeploymentComponent().getAssemblyComponent();
this.providedInterfaceA = this.requiringAsmCompA.getComponentType().getProvidedInterfaces().get(0);
// Connect the two components
this.connect(this.requiringAsmCompA, this.providingAsmCompB, this.commonInterfaceB);
// Delegate system-provided interface
this.assemblyMgr.registerSystemProvidedInterface(this.providedInterfaceA);
this.delegate(this.requiringAsmCompA, this.providedInterfaceA);
}
/**
* Adds {@link OperationCallFrequency}s for the {@link Operation}s of the
* two components {@link #requiringAsmCompA} and {@link #providingAsmCompB}.
*/
private void addOperationCallFrequencies() {
int numCallsAa = 0;
int numCallsBb = 0;
for (final Entry<Long, Long> e : this.frequencyMap.entrySet()) {
numCallsAa += e.getValue();
numCallsBb += e.getValue() * e.getKey();
}
final OperationCallFrequency opCallFrequencyOpAa =
UsageFactory.eINSTANCE.createOperationCallFrequency();
opCallFrequencyOpAa.setOperation(this.opExecAa.getOperation());
opCallFrequencyOpAa.setFrequency(numCallsAa);
this.usageModel.getOperationCallFrequencies().add(opCallFrequencyOpAa);
final OperationCallFrequency opCallFrequencyOpBb =
UsageFactory.eINSTANCE.createOperationCallFrequency();
opCallFrequencyOpBb.setOperation(this.opExecBb.getOperation());
opCallFrequencyOpBb.setFrequency(numCallsBb);
this.usageModel.getOperationCallFrequencies().add(opCallFrequencyOpBb);
}
/**
* Adds the relationship A.a(..) calls interface signature b(..) (for
* example implemented by B.b(..)) with the frequency distribution
* {@link #frequencyMap} to the {@link #usageModel}.
*/
private void addCallingRelationship() {
final CallingRelationship cr =
this.createCallingRelationship(
/* calling operation: */this.opExecAa.getOperation(),
/* called interface: */this.commonInterfaceB,
/* called signature of interface: */this.opExecBb.getOperation().getSignature(),
/* frequency distribution (internal representation) */this.frequencyMap);
this.usageModel.getCallingRelationships().add(cr);
}
/**
* Adds frequencies for calls to the {@link Signature} b(..) of the
* {@link AssemblyComponentConnector} {@link #asmConnector}.
*/
private void addAssemblyConnectorCallFrequencies() {
int numCallsAa = 0;
int numCallsBb = 0;
for (final Entry<Long, Long> e : this.frequencyMap.entrySet()) {
numCallsAa += e.getValue();
numCallsBb += e.getValue() * e.getKey();
}
/*
* Frequency for assembly component connector
*/
final AssemblyComponentConnectorCallFrequency asmCallFreqAaToBb =
UsageFactory.eINSTANCE.createAssemblyComponentConnectorCallFrequency();
asmCallFreqAaToBb.setConnector(this.asmConnector);
asmCallFreqAaToBb.setSignature(this.commonInterfaceB.getSignatures().get(0));
asmCallFreqAaToBb.setFrequency(numCallsBb);
this.usageModel.getAssemblyComponentConnectorCallFrequencies().add(asmCallFreqAaToBb);
/*
* Frequency for system-provided interface delegation connector
*/
final SystemProvidedInterfaceDelegationConnectorFrequency sysProvDelegFreqAa =
UsageFactory.eINSTANCE.createSystemProvidedInterfaceDelegationConnectorFrequency();
sysProvDelegFreqAa.setConnector(this.sysProvDelegationConnector);
sysProvDelegFreqAa.setSignature(this.providedInterfaceA.getSignatures().get(0));
sysProvDelegFreqAa.setFrequency(numCallsAa);
this.usageModel.getSystemProvidedInterfaceDelegationConnectorFrequencies().add(sysProvDelegFreqAa);
}
private void saveModels() throws IOException {
/* Create a tmp files the models will be saved to
* and mark the files to be deleted on jvm termination */
final File tmpSystemModelFile =
File.createTempFile(this.getClass().getSimpleName() +"-systemModel-", "");
//tmpSystemModelFile.deleteOnExit();
final File tmpUsageModelFile =
File.createTempFile(this.getClass().getSimpleName() +"-usageModel-", "");
//tmpSystemModelFile.deleteOnExit();
this.systemModelManager.saveModels(tmpSystemModelFile.getAbsolutePath(), tmpUsageModelFile.getAbsolutePath());
}
private final CallingRelationship createCallingRelationship(final Operation op, final Interface iface,
final Signature signature,
final TreeMap<Long, Long> frequencyDistribution) {
final CallingRelationship cr = UsageFactory.eINSTANCE.createCallingRelationship();
cr.setCallingOperation(op);
cr.setCalledInterface(iface);
// TODO: make sure that signature and operation's signature contained in
// interface
cr.setCalledSignature(signature);
final FrequencyDistribution fd = UsageFactory.eINSTANCE.createFrequencyDistribution();
fd.getValues().addAll(frequencyDistribution.keySet());
Assert.assertEquals("Unexpected number of values in frequency distribution",
frequencyDistribution.keySet().size(), fd.getValues().size());
fd.getFrequencies().addAll(frequencyDistribution.values());
Assert.assertEquals("Unexpected number of frequencies in frequency distribution",
frequencyDistribution.values().size(), fd.getFrequencies().size());
cr.setFrequencyDistribution(fd);
return cr;
}
private DeploymentComponentOperationExecution fillSystemModelByOperationExecution(
final String fqAssemblyComponentName, final Interface requiredInterface,
final String opName, final String returnType, final String[] paramTypes) {
/**
* Record used to setup the following model entities (excerpt of the
* relevant ones):
* <ul>
* <li>Interface <i>package.IComponentA__T</i> with a signature
* <code>opA(java.lang.String)</code></li>
* <li>ComponentType <i>package.ComponentA__T</i> providing interface
* <i>package.TComponentAT</i></li>
* <li>AssemblyComponent <i>package.ComponentA</i></li>
* </ul>
*/
final OperationExecutionRecord kiekerRecord =
new OperationExecutionRecord();
{
kiekerRecord.className = fqAssemblyComponentName;
kiekerRecord.eoi = 77;
kiekerRecord.ess = 98;
kiekerRecord.hostName = "theHostname";
kiekerRecord.operationName =
new StringBuilder(opName).append("(").append(StringUtils.join(paramTypes, ',')).append(')')
.toString();
kiekerRecord.sessionId = "ZUKGHGF435JJ";
kiekerRecord.tin = 65656868l;
kiekerRecord.tout = 9878787887l;
kiekerRecord.traceId = 88878787877887l;
}
final DeploymentComponentOperationExecution slasticRecord =
(DeploymentComponentOperationExecution) this.execRecFilter
.transformExecutionRecord(kiekerRecord);
final AssemblyComponent asmComp = slasticRecord.getDeploymentComponent().getAssemblyComponent();
if (requiredInterface != null) {
this.typeMgr.registerRequiredInterface(asmComp.getComponentType(), requiredInterface);
}
return slasticRecord;
}
private void connect(final AssemblyComponent requiringComponent, final AssemblyComponent providingComponent,
final Interface iface) {
this.asmConnector =
ModelEntityCreationUtils.createAssemblyConnector(this.systemModelManager, "ConnectorT", iface);
Assert.assertTrue("Failed to connect", this.assemblyMgr.connect(this.asmConnector, requiringComponent, providingComponent));
}
private void delegate(final AssemblyComponent providingComponent, final Interface iface) {
this.sysProvDelegationConnector =
ModelEntityCreationUtils.createSystemProvidedDelegationConnector(this.systemModelManager, "SysProvConnectT", iface);
Assert.assertTrue("Failed to delegate", this.assemblyMgr.delegate(this.sysProvDelegationConnector, iface, providingComponent));
}
}
|
tests/org/trustsoft/slastic/tests/junit/model/manager/usage/TestUsageModelSimple.java
|
package org.trustsoft.slastic.tests.junit.model.manager.usage;
import java.io.File;
import java.io.IOException;
import java.util.Map.Entry;
import java.util.TreeMap;
import junit.framework.Assert;
import junit.framework.TestCase;
import kieker.common.record.OperationExecutionRecord;
import org.apache.commons.lang.StringUtils;
import org.trustsoft.slastic.plugins.slasticImpl.ModelManager;
import org.trustsoft.slastic.plugins.slasticImpl.model.NameUtils;
import org.trustsoft.slastic.plugins.slasticImpl.model.componentAssembly.ComponentAssemblyModelManager;
import org.trustsoft.slastic.plugins.slasticImpl.model.typeRepository.TypeRepositoryModelManager;
import org.trustsoft.slastic.plugins.slasticImpl.model.usage.UsageModelManager;
import org.trustsoft.slastic.plugins.slasticImpl.monitoring.kieker.reconstruction.ExecutionRecordTransformationFilter;
import org.trustsoft.slastic.tests.junit.model.ModelEntityCreationUtils;
import de.cau.se.slastic.metamodel.componentAssembly.AssemblyComponent;
import de.cau.se.slastic.metamodel.componentAssembly.AssemblyComponentConnector;
import de.cau.se.slastic.metamodel.componentAssembly.SystemProvidedInterfaceDelegationConnector;
import de.cau.se.slastic.metamodel.core.SystemModel;
import de.cau.se.slastic.metamodel.monitoring.DeploymentComponentOperationExecution;
import de.cau.se.slastic.metamodel.typeRepository.Interface;
import de.cau.se.slastic.metamodel.typeRepository.Operation;
import de.cau.se.slastic.metamodel.typeRepository.Signature;
import de.cau.se.slastic.metamodel.usage.AssemblyComponentConnectorCallFrequency;
import de.cau.se.slastic.metamodel.usage.CallingRelationship;
import de.cau.se.slastic.metamodel.usage.FrequencyDistribution;
import de.cau.se.slastic.metamodel.usage.OperationCallFrequency;
import de.cau.se.slastic.metamodel.usage.UsageFactory;
import de.cau.se.slastic.metamodel.usage.UsageModel;
/**
* In this test, we are manually filling a {@link UsageModel} without the use of
* the {@link UsageModelManager}.
*
* @author Andre van Hoorn
*
*/
public class TestUsageModelSimple extends TestCase {
/** Create {@link ModelManager} with empty {@link SystemModel} and {@link UsageModel} */
private final ModelManager systemModelManager = new ModelManager();
private final TypeRepositoryModelManager typeMgr = this.systemModelManager.getTypeRepositoryManager();
private final ComponentAssemblyModelManager assemblyMgr = this.systemModelManager
.getComponentAssemblyModelManager();
/** Since we are modifying the {@link UsageModel} directly, we need to retrieve it. */
private final UsageModel usageModel = this.systemModelManager.getUsageModelManager().getModel();
private final ExecutionRecordTransformationFilter execRecFilter =
new ExecutionRecordTransformationFilter(this.systemModelManager,
NameUtils.ABSTRACTION_MODE_CLASS);
private volatile AssemblyComponent requiringAsmCompA;
private volatile DeploymentComponentOperationExecution opExecAa;
private volatile Interface providedInterfaceA;
private volatile AssemblyComponent providingAsmCompB;
private volatile DeploymentComponentOperationExecution opExecBb;
private volatile Interface commonInterfaceB;
private volatile AssemblyComponentConnector asmConnector;
private volatile SystemProvidedInterfaceDelegationConnector sysProvDelegationConnector;
/**
* Intermediate data structure capturing the distribution of calls from
* operation A.a(..) to Signature b(..).
* */
private final TreeMap<Long, Long> frequencyMap = new TreeMap<Long, Long>();
{
this.frequencyMap.put(0l, 2l);
// implicitly included: frequencyMap.put(1, 0);
this.frequencyMap.put(2l, 1l);
this.frequencyMap.put(3l, 2l);
// implicitly included: frequencyMap.put(4, 0);
// implicitly included: frequencyMap.put(5, 0);
this.frequencyMap.put(6l, 1l);
}
/**
* Manually fills the {@link UsageModel} without using the
* {@link UsageModelManager}.
* @throws IOException
*/
public void testManuallyFillModel() throws IOException {
this.initModelAndVars();
this.addOperationCallFrequencies();
this.addCallingRelationship();
this.addAssemblyConnectorCallFrequencies();
this.saveModels();
}
/**
* Initializes a {@link SystemModel} by creating (among other entities) the
* {@link AssemblyComponent}s {@link #requiringAsmCompA} and
* {@link #providingAsmCompB} properly connected via the
* {@link AssemblyComponentConnector} {@link #asmConnector} with the common Interface
* {@link #commonInterfaceB}.
*/
private void initModelAndVars() {
// Create asmCompB providing the interface commonInterfaceB
this.opExecBb =
this.fillSystemModelByOperationExecution("package.ComponentB",
/* no required interface: */null,
"opB", "void", new String[] { String.class.getName() });
this.providingAsmCompB = this.opExecBb.getDeploymentComponent().getAssemblyComponent();
this.commonInterfaceB = this.providingAsmCompB.getComponentType().getProvidedInterfaces().get(0);
// Create asmCompA whose type requires asmCompB's type's providing
// interface
this.opExecAa =
this.fillSystemModelByOperationExecution("package.ComponentA", this.commonInterfaceB,
"opA", Long.class.getName(), new String[] { Boolean.class.getName() });
this.requiringAsmCompA = this.opExecAa.getDeploymentComponent().getAssemblyComponent();
this.providedInterfaceA = this.requiringAsmCompA.getComponentType().getProvidedInterfaces().get(0);
// Connect the two components
this.connect(this.requiringAsmCompA, this.providingAsmCompB, this.commonInterfaceB);
// Delegate system-provided interface
this.assemblyMgr.registerSystemProvidedInterface(this.providedInterfaceA);
this.delegate(this.requiringAsmCompA, this.providedInterfaceA);
}
/**
* Adds {@link OperationCallFrequency}s for the {@link Operation}s of the
* two components {@link #requiringAsmCompA} and {@link #providingAsmCompB}.
*/
private void addOperationCallFrequencies() {
int numCallsAa = 0;
int numCallsBb = 0;
for (final Entry<Long, Long> e : this.frequencyMap.entrySet()) {
numCallsAa += e.getValue();
numCallsBb += e.getValue() * e.getKey();
}
final OperationCallFrequency opCallFrequencyOpAa =
UsageFactory.eINSTANCE.createOperationCallFrequency();
opCallFrequencyOpAa.setOperation(this.opExecAa.getOperation());
opCallFrequencyOpAa.setFrequency(numCallsAa);
this.usageModel.getOperationCallFrequencies().add(opCallFrequencyOpAa);
final OperationCallFrequency opCallFrequencyOpBb =
UsageFactory.eINSTANCE.createOperationCallFrequency();
opCallFrequencyOpBb.setOperation(this.opExecBb.getOperation());
opCallFrequencyOpBb.setFrequency(numCallsBb);
this.usageModel.getOperationCallFrequencies().add(opCallFrequencyOpBb);
}
/**
* Adds the relationship A.a(..) calls interface signature b(..) (for
* example implemented by B.b(..)) with the frequency distribution
* {@link #frequencyMap} to the {@link #usageModel}.
*/
private void addCallingRelationship() {
final CallingRelationship cr =
this.createCallingRelationship(
/* calling operation: */this.opExecAa.getOperation(),
/* called interface: */this.commonInterfaceB,
/* called signature of interface: */this.opExecBb.getOperation().getSignature(),
/* frequency distribution (internal representation) */this.frequencyMap);
this.usageModel.getCallingRelationships().add(cr);
}
/**
* Adds frequencies for calls to the {@link Signature} b(..) of the
* {@link AssemblyComponentConnector} {@link #asmConnector}.
*/
private void addAssemblyConnectorCallFrequencies() {
int numCallsAa = 0;
int numCallsBb = 0;
for (final Entry<Long, Long> e : this.frequencyMap.entrySet()) {
numCallsAa += e.getValue();
numCallsBb += e.getValue() * e.getKey();
}
final AssemblyComponentConnectorCallFrequency asmCallFreqAaToBb =
UsageFactory.eINSTANCE.createAssemblyComponentConnectorCallFrequency();
asmCallFreqAaToBb.setConnector(this.asmConnector);
asmCallFreqAaToBb.setSignature(this.opExecBb.getOperation().getSignature());
asmCallFreqAaToBb.setFrequency(numCallsBb);
this.usageModel.getAssemblyComponentConnectorCallFrequencies().add(asmCallFreqAaToBb);
// TODO: Add frequency for system-provided connector
}
private void saveModels() throws IOException {
/* Create a tmp files the models will be saved to
* and mark the files to be deleted on jvm termination */
final File tmpSystemModelFile =
File.createTempFile("systemModel-", "");
//tmpSystemModelFile.deleteOnExit();
final File tmpUsageModelFile =
File.createTempFile("usageModel-", "");
//tmpSystemModelFile.deleteOnExit();
this.systemModelManager.saveModels(tmpSystemModelFile.getAbsolutePath(), tmpUsageModelFile.getAbsolutePath());
}
private final CallingRelationship createCallingRelationship(final Operation op, final Interface iface,
final Signature signature,
final TreeMap<Long, Long> frequencyDistribution) {
final CallingRelationship cr = UsageFactory.eINSTANCE.createCallingRelationship();
cr.setCallingOperation(op);
cr.setCalledInterface(iface);
// TODO: make sure that signature and operation's signature contained in
// interface
cr.setCalledSignature(signature);
final FrequencyDistribution fd = UsageFactory.eINSTANCE.createFrequencyDistribution();
fd.getValues().addAll(frequencyDistribution.keySet());
Assert.assertEquals("Unexpected number of values in frequency distribution",
frequencyDistribution.keySet().size(), fd.getValues().size());
fd.getFrequencies().addAll(frequencyDistribution.values());
Assert.assertEquals("Unexpected number of frequencies in frequency distribution",
frequencyDistribution.values().size(), fd.getFrequencies().size());
cr.setFrequencyDistribution(fd);
return cr;
}
private DeploymentComponentOperationExecution fillSystemModelByOperationExecution(
final String fqAssemblyComponentName, final Interface requiredInterface,
final String opName, final String returnType, final String[] paramTypes) {
/**
* Record used to setup the following model entities (excerpt of the
* relevant ones):
* <ul>
* <li>Interface <i>package.IComponentA__T</i> with a signature
* <code>opA(java.lang.String)</code></li>
* <li>ComponentType <i>package.ComponentA__T</i> providing interface
* <i>package.TComponentAT</i></li>
* <li>AssemblyComponent <i>package.ComponentA</i></li>
* </ul>
*/
final OperationExecutionRecord kiekerRecord =
new OperationExecutionRecord();
{
kiekerRecord.className = fqAssemblyComponentName;
kiekerRecord.eoi = 77;
kiekerRecord.ess = 98;
kiekerRecord.hostName = "theHostname";
kiekerRecord.operationName =
new StringBuilder(opName).append("(").append(StringUtils.join(paramTypes, ',')).append(')')
.toString();
kiekerRecord.sessionId = "ZUKGHGF435JJ";
kiekerRecord.tin = 65656868l;
kiekerRecord.tout = 9878787887l;
kiekerRecord.traceId = 88878787877887l;
}
final DeploymentComponentOperationExecution slasticRecord =
(DeploymentComponentOperationExecution) this.execRecFilter
.transformExecutionRecord(kiekerRecord);
final AssemblyComponent asmComp = slasticRecord.getDeploymentComponent().getAssemblyComponent();
if (requiredInterface != null) {
this.typeMgr.registerRequiredInterface(asmComp.getComponentType(), requiredInterface);
}
return slasticRecord;
}
private void connect(final AssemblyComponent requiringComponent, final AssemblyComponent providingComponent,
final Interface iface) {
this.asmConnector =
ModelEntityCreationUtils.createAssemblyConnector(this.systemModelManager, "ConnectorT", iface);
Assert.assertTrue("Failed to connect", this.assemblyMgr.connect(this.asmConnector, requiringComponent, providingComponent));
}
private void delegate(final AssemblyComponent providingComponent, final Interface iface) {
this.sysProvDelegationConnector =
ModelEntityCreationUtils.createSystemProvidedDelegationConnector(this.systemModelManager, "SysProvConnectT", iface);
Assert.assertTrue("Failed to delegate", this.assemblyMgr.delegate(this.sysProvDelegationConnector, iface, providingComponent));
}
}
|
completed test for system-provided delegation connector call frequency
|
tests/org/trustsoft/slastic/tests/junit/model/manager/usage/TestUsageModelSimple.java
|
completed test for system-provided delegation connector call frequency
|
<ide><path>ests/org/trustsoft/slastic/tests/junit/model/manager/usage/TestUsageModelSimple.java
<ide> import de.cau.se.slastic.metamodel.usage.CallingRelationship;
<ide> import de.cau.se.slastic.metamodel.usage.FrequencyDistribution;
<ide> import de.cau.se.slastic.metamodel.usage.OperationCallFrequency;
<add>import de.cau.se.slastic.metamodel.usage.SystemProvidedInterfaceDelegationConnectorFrequency;
<ide> import de.cau.se.slastic.metamodel.usage.UsageFactory;
<ide> import de.cau.se.slastic.metamodel.usage.UsageModel;
<ide>
<ide> numCallsBb += e.getValue() * e.getKey();
<ide> }
<ide>
<add> /*
<add> * Frequency for assembly component connector
<add> */
<ide> final AssemblyComponentConnectorCallFrequency asmCallFreqAaToBb =
<ide> UsageFactory.eINSTANCE.createAssemblyComponentConnectorCallFrequency();
<ide> asmCallFreqAaToBb.setConnector(this.asmConnector);
<del> asmCallFreqAaToBb.setSignature(this.opExecBb.getOperation().getSignature());
<add> asmCallFreqAaToBb.setSignature(this.commonInterfaceB.getSignatures().get(0));
<ide> asmCallFreqAaToBb.setFrequency(numCallsBb);
<ide> this.usageModel.getAssemblyComponentConnectorCallFrequencies().add(asmCallFreqAaToBb);
<del>
<del> // TODO: Add frequency for system-provided connector
<del> }
<del>
<add>
<add> /*
<add> * Frequency for system-provided interface delegation connector
<add> */
<add> final SystemProvidedInterfaceDelegationConnectorFrequency sysProvDelegFreqAa =
<add> UsageFactory.eINSTANCE.createSystemProvidedInterfaceDelegationConnectorFrequency();
<add> sysProvDelegFreqAa.setConnector(this.sysProvDelegationConnector);
<add> sysProvDelegFreqAa.setSignature(this.providedInterfaceA.getSignatures().get(0));
<add> sysProvDelegFreqAa.setFrequency(numCallsAa);
<add> this.usageModel.getSystemProvidedInterfaceDelegationConnectorFrequencies().add(sysProvDelegFreqAa);
<add> }
<add>
<ide> private void saveModels() throws IOException {
<ide> /* Create a tmp files the models will be saved to
<ide> * and mark the files to be deleted on jvm termination */
<ide> final File tmpSystemModelFile =
<del> File.createTempFile("systemModel-", "");
<add> File.createTempFile(this.getClass().getSimpleName() +"-systemModel-", "");
<ide> //tmpSystemModelFile.deleteOnExit();
<ide>
<ide> final File tmpUsageModelFile =
<del> File.createTempFile("usageModel-", "");
<add> File.createTempFile(this.getClass().getSimpleName() +"-usageModel-", "");
<ide> //tmpSystemModelFile.deleteOnExit();
<ide>
<ide> this.systemModelManager.saveModels(tmpSystemModelFile.getAbsolutePath(), tmpUsageModelFile.getAbsolutePath());
|
|
Java
|
mit
|
01f6052c8a5b1a5180c2db419bde221491101ee6
| 0 |
Belberus/UrlShortener,nebur395/UrlShortener,anicacortes/UrlShortener,Belberus/UrlShortener,anicacortes/UrlShortener,nebur395/UrlShortener,anicacortes/UrlShortener,nebur395/UrlShortener,Belberus/UrlShortener
|
package urlshortener.aeternum.web;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
@Component
public class SendMail {
private static final Logger logger = LoggerFactory.getLogger(SendMail.class);
private static String RECIPIENT = "[email protected]";
public void sendMail(String url) {
String from = "[email protected]";
String pass = "pruprupru99";
String[] to = { RECIPIENT }; // list of recipient email addresses
String subject = "Warning!";
String body = "The url " + url + " has become unsafe! To be able to visit the page go to http://localhost:8080/#/unsafePage";
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(from));
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for( int i = 0; i < to.length; i++ ) {
toAddress[i] = new InternetAddress(to[i]);
}
for( int i = 0; i < toAddress.length; i++) {
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
message.setSubject(subject);
message.setText(body);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch (AddressException ae) {
ae.printStackTrace();
}
catch (MessagingException me) {
me.printStackTrace();
}
logger.info("Correo enviado!");
}
}
|
team/src/main/java/urlshortener/aeternum/web/SendMail.java
|
package urlshortener.aeternum.web;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
@Component
public class SendMail {
private static final Logger logger = LoggerFactory.getLogger(SendMail.class);
private static String RECIPIENT = "[email protected]";
public void sendMail(String url) {
String from = "[email protected]";
String pass = "pruprupru99";
String[] to = { RECIPIENT }; // list of recipient email addresses
String subject = "Warning!";
String body = "The url " + url + " has become unsafe! To be able to visit the page go to http://localhost:8080/#/unsafePage";
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(from));
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for( int i = 0; i < to.length; i++ ) {
toAddress[i] = new InternetAddress(to[i]);
}
for( int i = 0; i < toAddress.length; i++) {
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
message.setSubject(subject);
message.setText(body);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch (AddressException ae) {
ae.printStackTrace();
}
catch (MessagingException me) {
me.printStackTrace();
}
logger.info("Correo enviado!")
}
}
|
Test not ignored
|
team/src/main/java/urlshortener/aeternum/web/SendMail.java
|
Test not ignored
|
<ide><path>eam/src/main/java/urlshortener/aeternum/web/SendMail.java
<ide> package urlshortener.aeternum.web;
<ide> import org.springframework.beans.factory.annotation.Value;
<ide> import org.springframework.stereotype.Component;
<add>import org.slf4j.Logger;
<add>import org.slf4j.LoggerFactory;
<add>import java.util.*;
<ide>
<del>import java.util.*;
<ide> import javax.mail.*;
<ide> import javax.mail.internet.*;
<ide>
<ide> catch (MessagingException me) {
<ide> me.printStackTrace();
<ide> }
<del> logger.info("Correo enviado!")
<add> logger.info("Correo enviado!");
<ide> }
<ide> }
|
|
Java
|
apache-2.0
|
e3ec8ebcf05cdad207715fd456e6fc8110b93e08
| 0 |
apache/commons-math,apache/commons-math,Hipparchus-Math/hipparchus,Hipparchus-Math/hipparchus,Hipparchus-Math/hipparchus,sdinot/hipparchus,sdinot/hipparchus,apache/commons-math,Hipparchus-Math/hipparchus,apache/commons-math,sdinot/hipparchus,sdinot/hipparchus
|
/*
* 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.commons.math3.special;
import org.apache.commons.math3.exception.MaxCountExceededException;
import org.apache.commons.math3.util.ContinuedFraction;
import org.apache.commons.math3.util.FastMath;
/**
* This is a utility class that provides computation methods related to the
* Gamma family of functions.
*
* @version $Id$
*/
public class Gamma {
/**
* <a href="http://en.wikipedia.org/wiki/Euler-Mascheroni_constant">Euler-Mascheroni constant</a>
* @since 2.0
*/
public static final double GAMMA = 0.577215664901532860606512090082;
/**
* The value of the {@code g} constant in the Lanczos approximation, see
* {@link #lanczos(double)}.
*/
public static final double LANCZOS_G = 607.0 / 128.0;
/** Maximum allowed numerical error. */
private static final double DEFAULT_EPSILON = 10e-15;
/** Lanczos coefficients */
private static final double[] LANCZOS = {
0.99999999999999709182,
57.156235665862923517,
-59.597960355475491248,
14.136097974741747174,
-0.49191381609762019978,
.33994649984811888699e-4,
.46523628927048575665e-4,
-.98374475304879564677e-4,
.15808870322491248884e-3,
-.21026444172410488319e-3,
.21743961811521264320e-3,
-.16431810653676389022e-3,
.84418223983852743293e-4,
-.26190838401581408670e-4,
.36899182659531622704e-5,
};
/** Avoid repeated computation of log of 2 PI in logGamma */
private static final double HALF_LOG_2_PI = 0.5 * FastMath.log(2.0 * FastMath.PI);
// limits for switching algorithm in digamma
/** C limit. */
private static final double C_LIMIT = 49;
/** S limit. */
private static final double S_LIMIT = 1e-5;
/**
* Default constructor. Prohibit instantiation.
*/
private Gamma() {}
/**
* Returns the natural logarithm of the gamma function Γ(x).
*
* The implementation of this method is based on:
* <ul>
* <li><a href="http://mathworld.wolfram.com/GammaFunction.html">
* Gamma Function</a>, equation (28).</li>
* <li><a href="http://mathworld.wolfram.com/LanczosApproximation.html">
* Lanczos Approximation</a>, equations (1) through (5).</li>
* <li><a href="http://my.fit.edu/~gabdo/gamma.txt">Paul Godfrey, A note on
* the computation of the convergent Lanczos complex Gamma approximation
* </a></li>
* </ul>
*
* @param x Value.
* @return log(Γ(x))
*/
public static double logGamma(double x) {
double ret;
if (Double.isNaN(x) || (x <= 0.0)) {
ret = Double.NaN;
} else {
double g = 607.0 / 128.0;
double sum = lanczos(x);
double tmp = x + g + .5;
ret = ((x + .5) * FastMath.log(tmp)) - tmp +
HALF_LOG_2_PI + FastMath.log(sum / x);
}
return ret;
}
/**
* Returns the regularized gamma function P(a, x).
*
* @param a Parameter.
* @param x Value.
* @return the regularized gamma function P(a, x).
* @throws MaxCountExceededException if the algorithm fails to converge.
*/
public static double regularizedGammaP(double a, double x) {
return regularizedGammaP(a, x, DEFAULT_EPSILON, Integer.MAX_VALUE);
}
/**
* Returns the regularized gamma function P(a, x).
*
* The implementation of this method is based on:
* <ul>
* <li>
* <a href="http://mathworld.wolfram.com/RegularizedGammaFunction.html">
* Regularized Gamma Function</a>, equation (1)
* </li>
* <li>
* <a href="http://mathworld.wolfram.com/IncompleteGammaFunction.html">
* Incomplete Gamma Function</a>, equation (4).
* </li>
* <li>
* <a href="http://mathworld.wolfram.com/ConfluentHypergeometricFunctionoftheFirstKind.html">
* Confluent Hypergeometric Function of the First Kind</a>, equation (1).
* </li>
* </ul>
*
* @param a the a parameter.
* @param x the value.
* @param epsilon When the absolute value of the nth item in the
* series is less than epsilon the approximation ceases to calculate
* further elements in the series.
* @param maxIterations Maximum number of "iterations" to complete.
* @return the regularized gamma function P(a, x)
* @throws MaxCountExceededException if the algorithm fails to converge.
*/
public static double regularizedGammaP(double a,
double x,
double epsilon,
int maxIterations) {
double ret;
if (Double.isNaN(a) || Double.isNaN(x) || (a <= 0.0) || (x < 0.0)) {
ret = Double.NaN;
} else if (x == 0.0) {
ret = 0.0;
} else if (x >= a + 1) {
// use regularizedGammaQ because it should converge faster in this
// case.
ret = 1.0 - regularizedGammaQ(a, x, epsilon, maxIterations);
} else {
// calculate series
double n = 0.0; // current element index
double an = 1.0 / a; // n-th element in the series
double sum = an; // partial sum
while (FastMath.abs(an/sum) > epsilon &&
n < maxIterations &&
sum < Double.POSITIVE_INFINITY) {
// compute next element in the series
n = n + 1.0;
an = an * (x / (a + n));
// update partial sum
sum = sum + an;
}
if (n >= maxIterations) {
throw new MaxCountExceededException(maxIterations);
} else if (Double.isInfinite(sum)) {
ret = 1.0;
} else {
ret = FastMath.exp(-x + (a * FastMath.log(x)) - logGamma(a)) * sum;
}
}
return ret;
}
/**
* Returns the regularized gamma function Q(a, x) = 1 - P(a, x).
*
* @param a the a parameter.
* @param x the value.
* @return the regularized gamma function Q(a, x)
* @throws MaxCountExceededException if the algorithm fails to converge.
*/
public static double regularizedGammaQ(double a, double x) {
return regularizedGammaQ(a, x, DEFAULT_EPSILON, Integer.MAX_VALUE);
}
/**
* Returns the regularized gamma function Q(a, x) = 1 - P(a, x).
*
* The implementation of this method is based on:
* <ul>
* <li>
* <a href="http://mathworld.wolfram.com/RegularizedGammaFunction.html">
* Regularized Gamma Function</a>, equation (1).
* </li>
* <li>
* <a href="http://functions.wolfram.com/GammaBetaErf/GammaRegularized/10/0003/">
* Regularized incomplete gamma function: Continued fraction representations
* (formula 06.08.10.0003)</a>
* </li>
* </ul>
*
* @param a the a parameter.
* @param x the value.
* @param epsilon When the absolute value of the nth item in the
* series is less than epsilon the approximation ceases to calculate
* further elements in the series.
* @param maxIterations Maximum number of "iterations" to complete.
* @return the regularized gamma function P(a, x)
* @throws MaxCountExceededException if the algorithm fails to converge.
*/
public static double regularizedGammaQ(final double a,
double x,
double epsilon,
int maxIterations) {
double ret;
if (Double.isNaN(a) || Double.isNaN(x) || (a <= 0.0) || (x < 0.0)) {
ret = Double.NaN;
} else if (x == 0.0) {
ret = 1.0;
} else if (x < a + 1.0) {
// use regularizedGammaP because it should converge faster in this
// case.
ret = 1.0 - regularizedGammaP(a, x, epsilon, maxIterations);
} else {
// create continued fraction
ContinuedFraction cf = new ContinuedFraction() {
@Override
protected double getA(int n, double x) {
return ((2.0 * n) + 1.0) - a + x;
}
@Override
protected double getB(int n, double x) {
return n * (a - n);
}
};
ret = 1.0 / cf.evaluate(x, epsilon, maxIterations);
ret = FastMath.exp(-x + (a * FastMath.log(x)) - logGamma(a)) * ret;
}
return ret;
}
/**
* <p>Computes the digamma function of x.</p>
*
* <p>This is an independently written implementation of the algorithm described in
* Jose Bernardo, Algorithm AS 103: Psi (Digamma) Function, Applied Statistics, 1976.</p>
*
* <p>Some of the constants have been changed to increase accuracy at the moderate expense
* of run-time. The result should be accurate to within 10^-8 absolute tolerance for
* x >= 10^-5 and within 10^-8 relative tolerance for x > 0.</p>
*
* <p>Performance for large negative values of x will be quite expensive (proportional to
* |x|). Accuracy for negative values of x should be about 10^-8 absolute for results
* less than 10^5 and 10^-8 relative for results larger than that.</p>
*
* @param x Argument.
* @return digamma(x) to within 10-8 relative or absolute error whichever is smaller.
* @see <a href="http://en.wikipedia.org/wiki/Digamma_function">Digamma</a>
* @see <a href="http://www.uv.es/~bernardo/1976AppStatist.pdf">Bernardo's original article </a>
* @since 2.0
*/
public static double digamma(double x) {
if (x > 0 && x <= S_LIMIT) {
// use method 5 from Bernardo AS103
// accurate to O(x)
return -GAMMA - 1 / x;
}
if (x >= C_LIMIT) {
// use method 4 (accurate to O(1/x^8)
double inv = 1 / (x * x);
// 1 1 1 1
// log(x) - --- - ------ + ------- - -------
// 2 x 12 x^2 120 x^4 252 x^6
return FastMath.log(x) - 0.5 / x - inv * ((1.0 / 12) + inv * (1.0 / 120 - inv / 252));
}
return digamma(x + 1) - 1 / x;
}
/**
* Computes the trigamma function of x.
* This function is derived by taking the derivative of the implementation
* of digamma.
*
* @param x Argument.
* @return trigamma(x) to within 10-8 relative or absolute error whichever is smaller
* @see <a href="http://en.wikipedia.org/wiki/Trigamma_function">Trigamma</a>
* @see Gamma#digamma(double)
* @since 2.0
*/
public static double trigamma(double x) {
if (x > 0 && x <= S_LIMIT) {
return 1 / (x * x);
}
if (x >= C_LIMIT) {
double inv = 1 / (x * x);
// 1 1 1 1 1
// - + ---- + ---- - ----- + -----
// x 2 3 5 7
// 2 x 6 x 30 x 42 x
return 1 / x + inv / 2 + inv / x * (1.0 / 6 - inv * (1.0 / 30 + inv / 42));
}
return trigamma(x + 1) + 1 / (x * x);
}
/**
* <p>
* Returns the Lanczos approximation used to compute the gamma function.
* The Lanczos approximation is related to the Gamma function by the
* following equation
* <center>
* {@code gamma(x) = sqrt(2 * pi) / x * (x + g + 0.5) ^ (x + 0.5)
* * exp(-x - g - 0.5) * lanczos(x)},
* </center>
* where {@code g} is a constant, returned by {@link #getLanczosG()}.
* </p>
*
* @param x the argument
* @return the Lanczos approximation
* @see <a href="http://mathworld.wolfram.com/LanczosApproximation.html">Lanczos Approximation</a>
* equations (1) through (5), and Paul Godfrey's
* <a href="http://my.fit.edu/~gabdo/gamma.txt">Note on the computation
* of the convergent Lanczos complex Gamma approximation</a>
*/
public static double lanczos(final double x) {
double sum = 0.0;
for (int i = LANCZOS.length - 1; i > 0; --i) {
sum = sum + (LANCZOS[i] / (x + i));
}
return sum + LANCZOS[0];
}
}
|
src/main/java/org/apache/commons/math3/special/Gamma.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.commons.math3.special;
import org.apache.commons.math3.exception.MaxCountExceededException;
import org.apache.commons.math3.util.ContinuedFraction;
import org.apache.commons.math3.util.FastMath;
/**
* This is a utility class that provides computation methods related to the
* Gamma family of functions.
*
* @version $Id$
*/
public class Gamma {
/**
* <a href="http://en.wikipedia.org/wiki/Euler-Mascheroni_constant">Euler-Mascheroni constant</a>
* @since 2.0
*/
public static final double GAMMA = 0.577215664901532860606512090082;
/**
* The value of the {@code g} constant in the Lanczos approximation, see
* {@link #lanczos(double)}.
*/
public static final double LANCZOS_G = 607.0 / 128.0;
/** Maximum allowed numerical error. */
private static final double DEFAULT_EPSILON = 10e-15;
/** Lanczos coefficients */
private static final double[] LANCZOS = {
0.99999999999999709182,
57.156235665862923517,
-59.597960355475491248,
14.136097974741747174,
-0.49191381609762019978,
.33994649984811888699e-4,
.46523628927048575665e-4,
-.98374475304879564677e-4,
.15808870322491248884e-3,
-.21026444172410488319e-3,
.21743961811521264320e-3,
-.16431810653676389022e-3,
.84418223983852743293e-4,
-.26190838401581408670e-4,
.36899182659531622704e-5,
};
/** Avoid repeated computation of log of 2 PI in logGamma */
private static final double HALF_LOG_2_PI = 0.5 * FastMath.log(2.0 * FastMath.PI);
// limits for switching algorithm in digamma
/** C limit. */
private static final double C_LIMIT = 49;
/** S limit. */
private static final double S_LIMIT = 1e-5;
/**
* Default constructor. Prohibit instantiation.
*/
private Gamma() {}
/**
* Returns the natural logarithm of the gamma function Γ(x).
*
* The implementation of this method is based on:
* <ul>
* <li><a href="http://mathworld.wolfram.com/GammaFunction.html">
* Gamma Function</a>, equation (28).</li>
* <li><a href="http://mathworld.wolfram.com/LanczosApproximation.html">
* Lanczos Approximation</a>, equations (1) through (5).</li>
* <li><a href="http://my.fit.edu/~gabdo/gamma.txt">Paul Godfrey, A note on
* the computation of the convergent Lanczos complex Gamma approximation
* </a></li>
* </ul>
*
* @param x Value.
* @return log(Γ(x))
*/
public static double logGamma(double x) {
double ret;
if (Double.isNaN(x) || (x <= 0.0)) {
ret = Double.NaN;
} else {
double g = 607.0 / 128.0;
double sum = lanczos(x);
double tmp = x + g + .5;
ret = ((x + .5) * FastMath.log(tmp)) - tmp +
HALF_LOG_2_PI + FastMath.log(sum / x);
}
return ret;
}
/**
* Returns the regularized gamma function P(a, x).
*
* @param a Parameter.
* @param x Value.
* @return the regularized gamma function P(a, x).
* @throws MaxCountExceededException if the algorithm fails to converge.
*/
public static double regularizedGammaP(double a, double x) {
return regularizedGammaP(a, x, DEFAULT_EPSILON, Integer.MAX_VALUE);
}
/**
* Returns the regularized gamma function P(a, x).
*
* The implementation of this method is based on:
* <ul>
* <li>
* <a href="http://mathworld.wolfram.com/RegularizedGammaFunction.html">
* Regularized Gamma Function</a>, equation (1)
* </li>
* <li>
* <a href="http://mathworld.wolfram.com/IncompleteGammaFunction.html">
* Incomplete Gamma Function</a>, equation (4).
* </li>
* <li>
* <a href="http://mathworld.wolfram.com/ConfluentHypergeometricFunctionoftheFirstKind.html">
* Confluent Hypergeometric Function of the First Kind</a>, equation (1).
* </li>
* </ul>
*
* @param a the a parameter.
* @param x the value.
* @param epsilon When the absolute value of the nth item in the
* series is less than epsilon the approximation ceases to calculate
* further elements in the series.
* @param maxIterations Maximum number of "iterations" to complete.
* @return the regularized gamma function P(a, x)
* @throws MaxCountExceededException if the algorithm fails to converge.
*/
public static double regularizedGammaP(double a,
double x,
double epsilon,
int maxIterations) {
double ret;
if (Double.isNaN(a) || Double.isNaN(x) || (a <= 0.0) || (x < 0.0)) {
ret = Double.NaN;
} else if (x == 0.0) {
ret = 0.0;
} else if (x >= a + 1) {
// use regularizedGammaQ because it should converge faster in this
// case.
ret = 1.0 - regularizedGammaQ(a, x, epsilon, maxIterations);
} else {
// calculate series
double n = 0.0; // current element index
double an = 1.0 / a; // n-th element in the series
double sum = an; // partial sum
while (FastMath.abs(an/sum) > epsilon &&
n < maxIterations &&
sum < Double.POSITIVE_INFINITY) {
// compute next element in the series
n = n + 1.0;
an = an * (x / (a + n));
// update partial sum
sum = sum + an;
}
if (n >= maxIterations) {
throw new MaxCountExceededException(maxIterations);
} else if (Double.isInfinite(sum)) {
ret = 1.0;
} else {
ret = FastMath.exp(-x + (a * FastMath.log(x)) - logGamma(a)) * sum;
}
}
return ret;
}
/**
* Returns the regularized gamma function Q(a, x) = 1 - P(a, x).
*
* @param a the a parameter.
* @param x the value.
* @return the regularized gamma function Q(a, x)
* @throws MaxCountExceededException if the algorithm fails to converge.
*/
public static double regularizedGammaQ(double a, double x) {
return regularizedGammaQ(a, x, DEFAULT_EPSILON, Integer.MAX_VALUE);
}
/**
* Returns the regularized gamma function Q(a, x) = 1 - P(a, x).
*
* The implementation of this method is based on:
* <ul>
* <li>
* <a href="http://mathworld.wolfram.com/RegularizedGammaFunction.html">
* Regularized Gamma Function</a>, equation (1).
* </li>
* <li>
* <a href="http://functions.wolfram.com/GammaBetaErf/GammaRegularized/10/0003/">
* Regularized incomplete gamma function: Continued fraction representations
* (formula 06.08.10.0003)</a>
* </li>
* </ul>
*
* @param a the a parameter.
* @param x the value.
* @param epsilon When the absolute value of the nth item in the
* series is less than epsilon the approximation ceases to calculate
* further elements in the series.
* @param maxIterations Maximum number of "iterations" to complete.
* @return the regularized gamma function P(a, x)
* @throws MaxCountExceededException if the algorithm fails to converge.
*/
public static double regularizedGammaQ(final double a,
double x,
double epsilon,
int maxIterations) {
double ret;
if (Double.isNaN(a) || Double.isNaN(x) || (a <= 0.0) || (x < 0.0)) {
ret = Double.NaN;
} else if (x == 0.0) {
ret = 1.0;
} else if (x < a + 1.0) {
// use regularizedGammaP because it should converge faster in this
// case.
ret = 1.0 - regularizedGammaP(a, x, epsilon, maxIterations);
} else {
// create continued fraction
ContinuedFraction cf = new ContinuedFraction() {
@Override
protected double getA(int n, double x) {
return ((2.0 * n) + 1.0) - a + x;
}
@Override
protected double getB(int n, double x) {
return n * (a - n);
}
};
ret = 1.0 / cf.evaluate(x, epsilon, maxIterations);
ret = FastMath.exp(-x + (a * FastMath.log(x)) - logGamma(a)) * ret;
}
return ret;
}
/**
* <p>Computes the digamma function of x.</p>
*
* <p>This is an independently written implementation of the algorithm described in
* Jose Bernardo, Algorithm AS 103: Psi (Digamma) Function, Applied Statistics, 1976.</p>
*
* <p>Some of the constants have been changed to increase accuracy at the moderate expense
* of run-time. The result should be accurate to within 10^-8 absolute tolerance for
* x >= 10^-5 and within 10^-8 relative tolerance for x > 0.</p>
*
* <p>Performance for large negative values of x will be quite expensive (proportional to
* |x|). Accuracy for negative values of x should be about 10^-8 absolute for results
* less than 10^5 and 10^-8 relative for results larger than that.</p>
*
* @param x Argument.
* @return digamma(x) to within 10-8 relative or absolute error whichever is smaller.
* @see <a href="http://en.wikipedia.org/wiki/Digamma_function">Digamma</a>
* @see <a href="http://www.uv.es/~bernardo/1976AppStatist.pdf">Bernardo's original article </a>
* @since 2.0
*/
public static double digamma(double x) {
if (x > 0 && x <= S_LIMIT) {
// use method 5 from Bernardo AS103
// accurate to O(x)
return -GAMMA - 1 / x;
}
if (x >= C_LIMIT) {
// use method 4 (accurate to O(1/x^8)
double inv = 1 / (x * x);
// 1 1 1 1
// log(x) - --- - ------ + ------- - -------
// 2 x 12 x^2 120 x^4 252 x^6
return FastMath.log(x) - 0.5 / x - inv * ((1.0 / 12) + inv * (1.0 / 120 - inv / 252));
}
return digamma(x + 1) - 1 / x;
}
/**
* Computes the trigamma function of x.
* This function is derived by taking the derivative of the implementation
* of digamma.
*
* @param x Argument.
* @return trigamma(x) to within 10-8 relative or absolute error whichever is smaller
* @see <a href="http://en.wikipedia.org/wiki/Trigamma_function">Trigamma</a>
* @see Gamma#digamma(double)
* @since 2.0
*/
public static double trigamma(double x) {
if (x > 0 && x <= S_LIMIT) {
return 1 / (x * x);
}
if (x >= C_LIMIT) {
double inv = 1 / (x * x);
// 1 1 1 1 1
// - + ---- + ---- - ----- + -----
// x 2 3 5 7
// 2 x 6 x 30 x 42 x
return 1 / x + inv / 2 + inv / x * (1.0 / 6 - inv * (1.0 / 30 + inv / 42));
}
return trigamma(x + 1) + 1 / (x * x);
}
/**
* <p>
* Returns the Lanczos approximation used to compute the gamma function.
* The Lanczos approximation is related to the Gamma function by the
* following equation
* <center>
* {@code gamma(x) = sqrt(2 * pi) / x * (x + g + 0.5) ^ (x + 0.5)
* * exp(-x - g - 0.5) * lanczos(x)},
* </center>
* where {@code g} is a constant, returned by {@link #getLanczosG()}.
* </p>
*
* @param x the argument
* @return the Lanczos approximation
* @see <a href="http://mathworld.wolfram.com/LanczosApproximation.html">Lanczos Approximation</a>,
* equations (1) through (5), and Paul Godfrey's
* <a href="http://my.fit.edu/~gabdo/gamma.txt">Note on the computation
* of the convergent Lanczos complex Gamma approximation</a>
*/
public static double lanczos(final double x) {
double sum = 0.0;
for (int i = LANCZOS.length - 1; i > 0; --i) {
sum = sum + (LANCZOS[i] / (x + i));
}
return sum + LANCZOS[0];
}
}
|
Javadoc syntax
git-svn-id: 80d496c472b8b763a5e941dba212da9bf48aeceb@1370214 13f79535-47bb-0310-9956-ffa450edef68
|
src/main/java/org/apache/commons/math3/special/Gamma.java
|
Javadoc syntax
|
<ide><path>rc/main/java/org/apache/commons/math3/special/Gamma.java
<ide> *
<ide> * @param x the argument
<ide> * @return the Lanczos approximation
<del> * @see <a href="http://mathworld.wolfram.com/LanczosApproximation.html">Lanczos Approximation</a>,
<add> * @see <a href="http://mathworld.wolfram.com/LanczosApproximation.html">Lanczos Approximation</a>
<ide> * equations (1) through (5), and Paul Godfrey's
<ide> * <a href="http://my.fit.edu/~gabdo/gamma.txt">Note on the computation
<ide> * of the convergent Lanczos complex Gamma approximation</a>
|
|
Java
|
mit
|
4c8ca2119acd3699c4e810b261e54f7506b1a665
| 0 |
mvit/sixes-wild
|
package controller;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import model.PlayerModel;
import boundary.PlayerApplication;
import boundary.PlayerEndLevelView;
/**
* PlayerEndLevelCtrl handles what occurs at the end of a level.
*
* @author Bailey Sheridan, and Eli Skeggs
*/
public class PlayerEndLevelCtrl implements Runnable {
PlayerApplication app;
PlayerModel model;
public static final File progressfile = PlayerLoadProgressCtrl.progressfile;
public static final File progressdir = PlayerLoadProgressCtrl.progressdir;
/**
* Creates a new PlayerEndLevelCtrl.
*
* @param app
* @param model
*/
public PlayerEndLevelCtrl(PlayerApplication app, PlayerModel model) {
this.app = app;
this.model = model;
}
/**
* Get the message associated with the threshold the user passed.
*
* @return The message for the corresponding score threshold.
*/
protected String getWonMessage() {
int[] thresholds = model.level.rules.scoreThresholds;
if (thresholds.length > 0) {
for (int i = thresholds.length - 1; i > 0; i++) {
if (model.score > thresholds[i]) {
return " You got " + (i + 1) + (i == 0 ? " star!" : " stars!");
}
}
return " You didn't pass.";
}
return "";
}
/**
* Ends the level via pop-up window.
*/
public void endLevel() {
// writes progress to file
if (progressdir.mkdirs() || progressdir.isDirectory()) {
try {
model.progress.write(new DataOutputStream(new FileOutputStream(
progressfile)));
} catch (IOException err) {
System.err.println("Unable to save progress");
}
} else {
System.err.println("Unable to create the appropriate directory structure,"
+ "your progress will not be saved");
}
PlayerEndLevelView endView = new PlayerEndLevelView(app, model);
String endMsg = "You won! Good job!" + getWonMessage();
// always set the achieved score, even if we haven't crossed a threshold
model.progress.setAchievedScore(model.levelnum, model.score);
endView.openDialog(endMsg);
}
/**
* Allow this to be deferred, calls endLevel.
*/
@Override
public void run() {
endLevel();
}
}
|
controller/PlayerEndLevelCtrl.java
|
package controller;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import model.PlayerModel;
import boundary.PlayerApplication;
import boundary.PlayerEndLevelView;
/**
* PlayerEndLevelCtrl handles what occurs at the end of a level.
*
* @author Bailey Sheridan, and Eli Skeggs
*/
public class PlayerEndLevelCtrl implements Runnable {
PlayerApplication app;
PlayerModel model;
public static final File progressfile = PlayerLoadProgressCtrl.progressfile;
public static final File progressdir = PlayerLoadProgressCtrl.progressdir;
/**
* Creates a new PlayerEndLevelCtrl.
*
* @param app
* @param model
*/
public PlayerEndLevelCtrl(PlayerApplication app, PlayerModel model) {
this.app = app;
this.model = model;
}
/**
* Get the message associated with the threshold the user passed.
*
* @return The message for the corresponding score threshold.
*/
protected String getWonMessage() {
int[] thresholds = model.level.rules.scoreThresholds;
if (thresholds.length > 0) {
for (int i = thresholds.length - 1; i > 0; i++) {
if (model.score > thresholds[i]) {
return " You got " + (i + 1) + (i == 0 ? "star!" : "stars!");
}
}
return " You didn't pass.";
}
return "";
}
/**
* Ends the level via pop-up window.
*/
public void endLevel() {
// writes progress to file
if (progressdir.mkdirs() || progressdir.isDirectory()) {
try {
model.progress.write(new DataOutputStream(new FileOutputStream(
progressfile)));
} catch (IOException err) {
System.err.println("Unable to save progress");
}
} else {
System.err.println("Unable to create the appropriate directory structure,"
+ "your progress will not be saved");
}
PlayerEndLevelView endView = new PlayerEndLevelView(app, model);
String endMsg = "You won! Good job!" + getWonMessage();
// always set the achieved score, even if we haven't crossed a threshold
model.progress.setAchievedScore(model.levelnum, model.score);
endView.openDialog(endMsg);
}
/**
* Allow this to be deferred, calls endLevel.
*/
@Override
public void run() {
endLevel();
}
}
|
Fix end level messaging
Signed-off-by: Eli Skeggs <[email protected]>
|
controller/PlayerEndLevelCtrl.java
|
Fix end level messaging
|
<ide><path>ontroller/PlayerEndLevelCtrl.java
<ide> if (thresholds.length > 0) {
<ide> for (int i = thresholds.length - 1; i > 0; i++) {
<ide> if (model.score > thresholds[i]) {
<del> return " You got " + (i + 1) + (i == 0 ? "star!" : "stars!");
<add> return " You got " + (i + 1) + (i == 0 ? " star!" : " stars!");
<ide> }
<ide> }
<ide>
|
|
Java
|
apache-2.0
|
81b6d5b94d4e99d68fd0fcc07433e25219cecd94
| 0 |
dhutchis/accumulo,ivakegg/accumulo,lstav/accumulo,dhutchis/accumulo,ctubbsii/accumulo,lstav/accumulo,dhutchis/accumulo,phrocker/accumulo-1,adamjshook/accumulo,mikewalch/accumulo,lstav/accumulo,keith-turner/accumulo,mjwall/accumulo,adamjshook/accumulo,mikewalch/accumulo,milleruntime/accumulo,mjwall/accumulo,phrocker/accumulo-1,milleruntime/accumulo,phrocker/accumulo-1,mjwall/accumulo,ivakegg/accumulo,adamjshook/accumulo,ivakegg/accumulo,milleruntime/accumulo,ctubbsii/accumulo,dhutchis/accumulo,mjwall/accumulo,dhutchis/accumulo,keith-turner/accumulo,phrocker/accumulo-1,milleruntime/accumulo,ctubbsii/accumulo,apache/accumulo,apache/accumulo,apache/accumulo,ivakegg/accumulo,ctubbsii/accumulo,mikewalch/accumulo,milleruntime/accumulo,adamjshook/accumulo,mikewalch/accumulo,ivakegg/accumulo,keith-turner/accumulo,milleruntime/accumulo,ctubbsii/accumulo,adamjshook/accumulo,mikewalch/accumulo,mikewalch/accumulo,ctubbsii/accumulo,adamjshook/accumulo,mjwall/accumulo,apache/accumulo,apache/accumulo,apache/accumulo,mikewalch/accumulo,lstav/accumulo,keith-turner/accumulo,phrocker/accumulo-1,lstav/accumulo,keith-turner/accumulo,mjwall/accumulo,keith-turner/accumulo,lstav/accumulo,phrocker/accumulo-1,dhutchis/accumulo,mikewalch/accumulo,ivakegg/accumulo,ivakegg/accumulo,adamjshook/accumulo,dhutchis/accumulo,phrocker/accumulo-1,dhutchis/accumulo,keith-turner/accumulo,lstav/accumulo,mjwall/accumulo,dhutchis/accumulo,apache/accumulo,ctubbsii/accumulo,milleruntime/accumulo,adamjshook/accumulo,adamjshook/accumulo
|
/*
* 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.accumulo.core.conf;
import java.io.File;
import java.lang.annotation.Annotation;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import org.apache.accumulo.core.Constants;
import org.apache.accumulo.core.client.security.tokens.PasswordToken;
import org.apache.accumulo.core.file.rfile.RFile;
import org.apache.accumulo.core.iterators.IteratorUtil.IteratorScope;
import org.apache.accumulo.core.util.format.DefaultFormatter;
import org.apache.accumulo.core.util.interpret.DefaultScanInterpreter;
import org.apache.accumulo.start.classloader.AccumuloClassLoader;
import org.apache.accumulo.start.classloader.vfs.AccumuloVFSClassLoader;
import org.apache.commons.configuration.MapConfiguration;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public enum Property {
// Crypto-related properties
@Experimental
CRYPTO_PREFIX("crypto.", null, PropertyType.PREFIX, "Properties in this category related to the configuration of both default and custom crypto modules."),
@Experimental
CRYPTO_MODULE_CLASS("crypto.module.class", "NullCryptoModule", PropertyType.STRING,
"Fully qualified class name of the class that implements the CryptoModule interface, to be used in setting up encryption at rest for the WAL and "
+ "(future) other parts of the code."),
@Experimental
CRYPTO_CIPHER_SUITE("crypto.cipher.suite", "NullCipher", PropertyType.STRING, "Describes the cipher suite to use for the write-ahead log"),
@Experimental
CRYPTO_CIPHER_ALGORITHM_NAME("crypto.cipher.algorithm.name", "NullCipher", PropertyType.STRING,
"States the name of the algorithm used in the corresponding cipher suite. Do not make these different, unless you enjoy mysterious exceptions and bugs."),
@Experimental
CRYPTO_BLOCK_STREAM_SIZE("crypto.block.stream.size", "1K", PropertyType.MEMORY,
"The size of the buffer above the cipher stream. Used for reading files and padding walog entries."),
@Experimental
CRYPTO_CIPHER_KEY_LENGTH("crypto.cipher.key.length", "128", PropertyType.STRING,
"Specifies the key length *in bits* to use for the symmetric key, should probably be 128 or 256 unless you really know what you're doing"),
@Experimental
CRYPTO_SECURE_RNG("crypto.secure.rng", "SHA1PRNG", PropertyType.STRING,
"States the secure random number generator to use, and defaults to the built-in Sun SHA1PRNG"),
@Experimental
CRYPTO_SECURE_RNG_PROVIDER("crypto.secure.rng.provider", "SUN", PropertyType.STRING,
"States the secure random number generator provider to use, and defaults to the built-in SUN provider"),
@Experimental
CRYPTO_SECRET_KEY_ENCRYPTION_STRATEGY_CLASS("crypto.secret.key.encryption.strategy.class", "NullSecretKeyEncryptionStrategy", PropertyType.STRING,
"The class Accumulo should use for its key encryption strategy."),
@Experimental
CRYPTO_DEFAULT_KEY_STRATEGY_HDFS_URI("crypto.default.key.strategy.hdfs.uri", "", PropertyType.STRING,
"The path relative to the top level instance directory (instance.dfs.dir) where to store the key encryption key within HDFS."),
@Experimental
CRYPTO_DEFAULT_KEY_STRATEGY_KEY_LOCATION("crypto.default.key.strategy.key.location", "/crypto/secret/keyEncryptionKey", PropertyType.ABSOLUTEPATH,
"The path relative to the top level instance directory (instance.dfs.dir) where to store the key encryption key within HDFS."),
@Experimental
CRYPTO_DEFAULT_KEY_STRATEGY_CIPHER_SUITE("crypto.default.key.strategy.cipher.suite", "NullCipher", PropertyType.STRING,
"The cipher suite to use when encrypting session keys with a key encryption keyThis should be set to match the overall encryption algorithm "
+ "but with ECB mode and no padding unless you really know what you're doing and are sure you won't break internal file formats"),
@Experimental
CRYPTO_OVERRIDE_KEY_STRATEGY_WITH_CONFIGURED_STRATEGY("crypto.override.key.strategy.with.configured.strategy", "false", PropertyType.BOOLEAN,
"The default behavior is to record the key encryption strategy with the encrypted file, and continue to use that strategy for the life "
+ "of that file. Sometimes, you change your strategy and want to use the new strategy, not the old one. (Most commonly, this will be "
+ "because you have moved key material from one spot to another.) If you want to override the recorded key strategy with the one in "
+ "the configuration file, set this property to true."),
// SSL properties local to each node (see also instance.ssl.enabled which must be consistent across all nodes in an instance)
RPC_PREFIX("rpc.", null, PropertyType.PREFIX, "Properties in this category related to the configuration of SSL keys for RPC. See also instance.ssl.enabled"),
RPC_SSL_KEYSTORE_PATH("rpc.javax.net.ssl.keyStore", "$ACCUMULO_CONF_DIR/ssl/keystore.jks", PropertyType.PATH,
"Path of the keystore file for the servers' private SSL key"),
@Sensitive
RPC_SSL_KEYSTORE_PASSWORD("rpc.javax.net.ssl.keyStorePassword", "", PropertyType.STRING,
"Password used to encrypt the SSL private keystore. Leave blank to use the Accumulo instance secret"),
RPC_SSL_KEYSTORE_TYPE("rpc.javax.net.ssl.keyStoreType", "jks", PropertyType.STRING, "Type of SSL keystore"),
RPC_SSL_TRUSTSTORE_PATH("rpc.javax.net.ssl.trustStore", "$ACCUMULO_CONF_DIR/ssl/truststore.jks", PropertyType.PATH,
"Path of the truststore file for the root cert"),
@Sensitive
RPC_SSL_TRUSTSTORE_PASSWORD("rpc.javax.net.ssl.trustStorePassword", "", PropertyType.STRING,
"Password used to encrypt the SSL truststore. Leave blank to use no password"),
RPC_SSL_TRUSTSTORE_TYPE("rpc.javax.net.ssl.trustStoreType", "jks", PropertyType.STRING, "Type of SSL truststore"),
RPC_USE_JSSE("rpc.useJsse", "false", PropertyType.BOOLEAN, "Use JSSE system properties to configure SSL rather than the " + RPC_PREFIX.getKey()
+ "javax.net.ssl.* Accumulo properties"),
RPC_SSL_CIPHER_SUITES("rpc.ssl.cipher.suites", "", PropertyType.STRING, "Comma separated list of cipher suites that can be used by accepted connections"),
RPC_SSL_ENABLED_PROTOCOLS("rpc.ssl.server.enabled.protocols", "TLSv1,TLSv1.1,TLSv1.2", PropertyType.STRING,
"Comma separated list of protocols that can be used to accept connections"),
// TLSv1.2 should be used as the default when JDK6 support is dropped
RPC_SSL_CLIENT_PROTOCOL("rpc.ssl.client.protocol", "TLSv1", PropertyType.STRING,
"The protocol used to connect to a secure server, must be in the list of enabled protocols on the server side (rpc.ssl.server.enabled.protocols)"),
/**
* @since 1.7.0
*/
RPC_SASL_QOP("rpc.sasl.qop", "auth", PropertyType.STRING,
"The quality of protection to be used with SASL. Valid values are 'auth', 'auth-int', and 'auth-conf'"),
// instance properties (must be the same for every node in an instance)
INSTANCE_PREFIX("instance.", null, PropertyType.PREFIX,
"Properties in this category must be consistent throughout a cloud. This is enforced and servers won't be able to communicate if these differ."),
INSTANCE_ZK_HOST("instance.zookeeper.host", "localhost:2181", PropertyType.HOSTLIST, "Comma separated list of zookeeper servers"),
INSTANCE_ZK_TIMEOUT("instance.zookeeper.timeout", "30s", PropertyType.TIMEDURATION,
"Zookeeper session timeout; max value when represented as milliseconds should be no larger than " + Integer.MAX_VALUE),
@Deprecated
INSTANCE_DFS_URI("instance.dfs.uri", "", PropertyType.URI,
"A url accumulo should use to connect to DFS. If this is empty, accumulo will obtain this information from the hadoop configuration. This property "
+ "will only be used when creating new files if instance.volumes is empty. After an upgrade to 1.6.0 Accumulo will start using absolute paths to "
+ "reference files. Files created before a 1.6.0 upgrade are referenced via relative paths. Relative paths will always be resolved using this "
+ "config (if empty using the hadoop config)."),
@Deprecated
INSTANCE_DFS_DIR("instance.dfs.dir", "/accumulo", PropertyType.ABSOLUTEPATH,
"HDFS directory in which accumulo instance will run. Do not change after accumulo is initialized."),
@Sensitive
INSTANCE_SECRET("instance.secret", "DEFAULT", PropertyType.STRING,
"A secret unique to a given instance that all servers must know in order to communicate with one another."
+ " Change it before initialization. To change it later use ./bin/accumulo accumulo.server.util.ChangeSecret [oldpasswd] [newpasswd], "
+ " and then update conf/accumulo-site.xml everywhere."),
INSTANCE_VOLUMES("instance.volumes", "", PropertyType.STRING,
"A comma seperated list of dfs uris to use. Files will be stored across these filesystems. If this is empty, then instance.dfs.uri will be used. "
+ "After adding uris to this list, run 'accumulo init --add-volume' and then restart tservers. If entries are removed from this list then tservers "
+ "will need to be restarted. After a uri is removed from the list Accumulo will not create new files in that location, however Accumulo can still "
+ "reference files created at that location before the config change. To use a comma or other reserved characters in a URI use standard URI hex "
+ "encoding. For example replace commas with %2C."),
INSTANCE_VOLUMES_REPLACEMENTS("instance.volumes.replacements", "", PropertyType.STRING,
"Since accumulo stores absolute URIs changing the location of a namenode could prevent Accumulo from starting. The property helps deal with that "
+ "situation. Provide a comma separated list of uri replacement pairs here if a namenode location changes. Each pair shold be separated with a "
+ "space. For example, if hdfs://nn1 was replaced with hdfs://nnA and hdfs://nn2 was replaced with hdfs://nnB, then set this property to "
+ "'hdfs://nn1 hdfs://nnA,hdfs://nn2 hdfs://nnB' Replacements must be configured for use. To see which volumes are currently in use, run "
+ "'accumulo admin volumes -l'. To use a comma or other reserved characters in a URI use standard URI hex encoding. For example replace commas with "
+ "%2C."),
INSTANCE_SECURITY_AUTHENTICATOR("instance.security.authenticator", "org.apache.accumulo.server.security.handler.ZKAuthenticator", PropertyType.CLASSNAME,
"The authenticator class that accumulo will use to determine if a user has privilege to perform an action"),
INSTANCE_SECURITY_AUTHORIZOR("instance.security.authorizor", "org.apache.accumulo.server.security.handler.ZKAuthorizor", PropertyType.CLASSNAME,
"The authorizor class that accumulo will use to determine what labels a user has privilege to see"),
INSTANCE_SECURITY_PERMISSION_HANDLER("instance.security.permissionHandler", "org.apache.accumulo.server.security.handler.ZKPermHandler",
PropertyType.CLASSNAME, "The permission handler class that accumulo will use to determine if a user has privilege to perform an action"),
INSTANCE_RPC_SSL_ENABLED("instance.rpc.ssl.enabled", "false", PropertyType.BOOLEAN,
"Use SSL for socket connections from clients and among accumulo services. Mutually exclusive with SASL RPC configuration."),
INSTANCE_RPC_SSL_CLIENT_AUTH("instance.rpc.ssl.clientAuth", "false", PropertyType.BOOLEAN, "Require clients to present certs signed by a trusted root"),
/**
* @since 1.7.0
*/
INSTANCE_RPC_SASL_ENABLED("instance.rpc.sasl.enabled", "false", PropertyType.BOOLEAN,
"Configures Thrift RPCs to require SASL with GSSAPI which supports Kerberos authentication. Mutually exclusive with SSL RPC configuration."),
INSTANCE_RPC_SASL_PROXYUSERS("instance.rpc.sasl.impersonation.", null, PropertyType.PREFIX,
"Prefix that allows configuration of users that are allowed to impersonate other users"),
// general properties
GENERAL_PREFIX("general.", null, PropertyType.PREFIX,
"Properties in this category affect the behavior of accumulo overall, but do not have to be consistent throughout a cloud."),
GENERAL_CLASSPATHS(AccumuloClassLoader.CLASSPATH_PROPERTY_NAME, AccumuloClassLoader.ACCUMULO_CLASSPATH_VALUE, PropertyType.STRING,
"A list of all of the places to look for a class. Order does matter, as it will look for the jar "
+ "starting in the first location to the last. Please note, hadoop conf and hadoop lib directories NEED to be here, "
+ "along with accumulo lib and zookeeper directory. Supports full regex on filename alone."), // needs special treatment in accumulo start jar
GENERAL_DYNAMIC_CLASSPATHS(AccumuloVFSClassLoader.DYNAMIC_CLASSPATH_PROPERTY_NAME, AccumuloVFSClassLoader.DEFAULT_DYNAMIC_CLASSPATH_VALUE,
PropertyType.STRING, "A list of all of the places where changes in jars or classes will force a reload of the classloader."),
GENERAL_RPC_TIMEOUT("general.rpc.timeout", "120s", PropertyType.TIMEDURATION, "Time to wait on I/O for simple, short RPC calls"),
@Experimental
GENERAL_RPC_SERVER_TYPE("general.rpc.server.type", "", PropertyType.STRING,
"Type of Thrift server to instantiate, see org.apache.accumulo.server.rpc.ThriftServerType for more information. Only useful for benchmarking thrift servers"),
GENERAL_KERBEROS_KEYTAB("general.kerberos.keytab", "", PropertyType.PATH, "Path to the kerberos keytab to use. Leave blank if not using kerberoized hdfs"),
GENERAL_KERBEROS_PRINCIPAL("general.kerberos.principal", "", PropertyType.STRING, "Name of the kerberos principal to use. _HOST will automatically be "
+ "replaced by the machines hostname in the hostname portion of the principal. Leave blank if not using kerberoized hdfs"),
GENERAL_MAX_MESSAGE_SIZE("general.server.message.size.max", "1G", PropertyType.MEMORY, "The maximum size of a message that can be sent to a server."),
GENERAL_SIMPLETIMER_THREADPOOL_SIZE("general.server.simpletimer.threadpool.size", "1", PropertyType.COUNT, "The number of threads to use for "
+ "server-internal scheduled tasks"),
// If you update the default type, be sure to update the default used for initialization failures in VolumeManagerImpl
@Experimental
GENERAL_VOLUME_CHOOSER("general.volume.chooser", "org.apache.accumulo.server.fs.PerTableVolumeChooser", PropertyType.CLASSNAME,
"The class that will be used to select which volume will be used to create new files."),
GENERAL_SECURITY_CREDENTIAL_PROVIDER_PATHS("general.security.credential.provider.paths", "", PropertyType.STRING,
"Comma-separated list of paths to CredentialProviders"),
GENERAL_LEGACY_METRICS("general.legacy.metrics", "false", PropertyType.BOOLEAN,
"Use the old metric infrastructure configured by accumulo-metrics.xml, instead of Hadoop Metrics2"),
GENERAL_DELEGATION_TOKEN_LIFETIME("general.delegation.token.lifetime", "7d", PropertyType.TIMEDURATION,
"The length of time that delegation tokens and secret keys are valid"),
GENERAL_DELEGATION_TOKEN_UPDATE_INTERVAL("general.delegation.token.update.interval", "1d", PropertyType.TIMEDURATION,
"The length of time between generation of new secret keys"),
// properties that are specific to master server behavior
MASTER_PREFIX("master.", null, PropertyType.PREFIX, "Properties in this category affect the behavior of the master server"),
MASTER_CLIENTPORT("master.port.client", "9999", PropertyType.PORT, "The port used for handling client connections on the master"),
MASTER_TABLET_BALANCER("master.tablet.balancer", "org.apache.accumulo.server.master.balancer.TableLoadBalancer", PropertyType.CLASSNAME,
"The balancer class that accumulo will use to make tablet assignment and migration decisions."),
MASTER_RECOVERY_MAXAGE("master.recovery.max.age", "60m", PropertyType.TIMEDURATION, "Recovery files older than this age will be removed."),
MASTER_RECOVERY_MAXTIME("master.recovery.time.max", "30m", PropertyType.TIMEDURATION, "The maximum time to attempt recovery before giving up"),
MASTER_BULK_RETRIES("master.bulk.retries", "3", PropertyType.COUNT, "The number of attempts to bulk-load a file before giving up."),
MASTER_BULK_THREADPOOL_SIZE("master.bulk.threadpool.size", "5", PropertyType.COUNT, "The number of threads to use when coordinating a bulk-import."),
MASTER_BULK_TIMEOUT("master.bulk.timeout", "5m", PropertyType.TIMEDURATION, "The time to wait for a tablet server to process a bulk import request"),
MASTER_BULK_RENAME_THREADS("master.bulk.rename.threadpool.size", "20", PropertyType.COUNT,
"The number of threads to use when moving user files to bulk ingest directories under accumulo control"),
MASTER_MINTHREADS("master.server.threads.minimum", "20", PropertyType.COUNT, "The minimum number of threads to use to handle incoming requests."),
MASTER_THREADCHECK("master.server.threadcheck.time", "1s", PropertyType.TIMEDURATION, "The time between adjustments of the server thread pool."),
MASTER_RECOVERY_DELAY("master.recovery.delay", "10s", PropertyType.TIMEDURATION,
"When a tablet server's lock is deleted, it takes time for it to completely quit. This delay gives it time before log recoveries begin."),
MASTER_LEASE_RECOVERY_WAITING_PERIOD("master.lease.recovery.interval", "5s", PropertyType.TIMEDURATION,
"The amount of time to wait after requesting a WAL file to be recovered"),
MASTER_WALOG_CLOSER_IMPLEMETATION("master.walog.closer.implementation", "org.apache.accumulo.server.master.recovery.HadoopLogCloser", PropertyType.CLASSNAME,
"A class that implements a mechansim to steal write access to a file"),
MASTER_FATE_THREADPOOL_SIZE("master.fate.threadpool.size", "4", PropertyType.COUNT,
"The number of threads used to run FAult-Tolerant Executions. These are primarily table operations like merge."),
MASTER_REPLICATION_SCAN_INTERVAL("master.replication.status.scan.interval", "30s", PropertyType.TIMEDURATION,
"Amount of time to sleep before scanning the status section of the replication table for new data"),
MASTER_REPLICATION_COORDINATOR_PORT("master.replication.coordinator.port", "10001", PropertyType.PORT, "Port for the replication coordinator service"),
MASTER_REPLICATION_COORDINATOR_MINTHREADS("master.replication.coordinator.minthreads", "4", PropertyType.COUNT,
"Minimum number of threads dedicated to answering coordinator requests"),
MASTER_REPLICATION_COORDINATOR_THREADCHECK("master.replication.coordinator.threadcheck.time", "5s", PropertyType.TIMEDURATION,
"The time between adjustments of the coordinator thread pool"),
// properties that are specific to tablet server behavior
TSERV_PREFIX("tserver.", null, PropertyType.PREFIX, "Properties in this category affect the behavior of the tablet servers"),
TSERV_CLIENT_TIMEOUT("tserver.client.timeout", "3s", PropertyType.TIMEDURATION, "Time to wait for clients to continue scans before closing a session."),
TSERV_DEFAULT_BLOCKSIZE("tserver.default.blocksize", "1M", PropertyType.MEMORY, "Specifies a default blocksize for the tserver caches"),
TSERV_DATACACHE_SIZE("tserver.cache.data.size", "128M", PropertyType.MEMORY, "Specifies the size of the cache for file data blocks."),
TSERV_INDEXCACHE_SIZE("tserver.cache.index.size", "512M", PropertyType.MEMORY, "Specifies the size of the cache for file indices."),
TSERV_PORTSEARCH("tserver.port.search", "false", PropertyType.BOOLEAN, "if the ports above are in use, search higher ports until one is available"),
TSERV_CLIENTPORT("tserver.port.client", "9997", PropertyType.PORT, "The port used for handling client connections on the tablet servers"),
@Deprecated
TSERV_MUTATION_QUEUE_MAX("tserver.mutation.queue.max", "1M", PropertyType.MEMORY, "This setting is deprecated. See tserver.total.mutation.queue.max. "
+ "The amount of memory to use to store write-ahead-log mutations-per-session before flushing them. Since the buffer is per write session, consider the"
+ " max number of concurrent writer when configuring. When using Hadoop 2, Accumulo will call hsync() on the WAL . For a small number of "
+ "concurrent writers, increasing this buffer size decreases the frequncy of hsync calls. For a large number of concurrent writers a small buffers "
+ "size is ok because of group commit."),
TSERV_TOTAL_MUTATION_QUEUE_MAX("tserver.total.mutation.queue.max", "50M", PropertyType.MEMORY,
"The amount of memory used to store write-ahead-log mutations before flushing them."),
TSERV_TABLET_SPLIT_FINDMIDPOINT_MAXOPEN("tserver.tablet.split.midpoint.files.max", "30", PropertyType.COUNT,
"To find a tablets split points, all index files are opened. This setting determines how many index "
+ "files can be opened at once. When there are more index files than this setting multiple passes "
+ "must be made, which is slower. However opening too many files at once can cause problems."),
TSERV_WALOG_MAX_SIZE("tserver.walog.max.size", "1G", PropertyType.MEMORY,
"The maximum size for each write-ahead log. See comment for property tserver.memory.maps.max"),
TSERV_WALOG_TOLERATED_CREATION_FAILURES("tserver.walog.tolerated.creation.failures", "50", PropertyType.COUNT,
"The maximum number of failures tolerated when creating a new WAL file within the period specified by tserver.walog.failures.period."
+ " Exceeding this number of failures in the period causes the TabletServer to exit."),
TSERV_WALOG_TOLERATED_WAIT_INCREMENT("tserver.walog.tolerated.wait.increment", "1000ms", PropertyType.TIMEDURATION,
"The amount of time to wait between failures to create a WALog."),
// Never wait longer than 5 mins for a retry
TSERV_WALOG_TOLERATED_MAXIMUM_WAIT_DURATION("tserver.walog.maximum.wait.duration", "5m", PropertyType.TIMEDURATION,
"The maximum amount of time to wait after a failure to create a WAL file."),
TSERV_MAJC_DELAY("tserver.compaction.major.delay", "30s", PropertyType.TIMEDURATION,
"Time a tablet server will sleep between checking which tablets need compaction."),
TSERV_MAJC_THREAD_MAXOPEN("tserver.compaction.major.thread.files.open.max", "10", PropertyType.COUNT,
"Max number of files a major compaction thread can open at once. "),
TSERV_SCAN_MAX_OPENFILES("tserver.scan.files.open.max", "100", PropertyType.COUNT,
"Maximum total files that all tablets in a tablet server can open for scans. "),
TSERV_MAX_IDLE("tserver.files.open.idle", "1m", PropertyType.TIMEDURATION, "Tablet servers leave previously used files open for future queries. "
+ "This setting determines how much time an unused file should be kept open until it is closed."),
TSERV_NATIVEMAP_ENABLED("tserver.memory.maps.native.enabled", "true", PropertyType.BOOLEAN,
"An in-memory data store for accumulo implemented in c++ that increases the amount of data accumulo can hold in memory and avoids Java GC pauses."),
TSERV_MAXMEM("tserver.memory.maps.max", "1G", PropertyType.MEMORY,
"Maximum amount of memory that can be used to buffer data written to a tablet server. There are two other properties that can effectively limit memory"
+ " usage table.compaction.minor.logs.threshold and tserver.walog.max.size. Ensure that table.compaction.minor.logs.threshold *"
+ " tserver.walog.max.size >= this property."),
TSERV_MEM_MGMT("tserver.memory.manager", "org.apache.accumulo.server.tabletserver.LargestFirstMemoryManager", PropertyType.CLASSNAME,
"An implementation of MemoryManger that accumulo will use."),
TSERV_SESSION_MAXIDLE("tserver.session.idle.max", "1m", PropertyType.TIMEDURATION, "maximum idle time for a session"),
TSERV_READ_AHEAD_MAXCONCURRENT("tserver.readahead.concurrent.max", "16", PropertyType.COUNT,
"The maximum number of concurrent read ahead that will execute. This effectively"
+ " limits the number of long running scans that can run concurrently per tserver."),
TSERV_METADATA_READ_AHEAD_MAXCONCURRENT("tserver.metadata.readahead.concurrent.max", "8", PropertyType.COUNT,
"The maximum number of concurrent metadata read ahead that will execute."),
TSERV_MIGRATE_MAXCONCURRENT("tserver.migrations.concurrent.max", "1", PropertyType.COUNT,
"The maximum number of concurrent tablet migrations for a tablet server"),
TSERV_MAJC_MAXCONCURRENT("tserver.compaction.major.concurrent.max", "3", PropertyType.COUNT,
"The maximum number of concurrent major compactions for a tablet server"),
TSERV_MINC_MAXCONCURRENT("tserver.compaction.minor.concurrent.max", "4", PropertyType.COUNT,
"The maximum number of concurrent minor compactions for a tablet server"),
TSERV_MAJC_TRACE_PERCENT("tserver.compaction.major.trace.percent", "0.1", PropertyType.FRACTION, "The percent of major compactions to trace"),
TSERV_MINC_TRACE_PERCENT("tserver.compaction.minor.trace.percent", "0.1", PropertyType.FRACTION, "The percent of minor compactions to trace"),
TSERV_COMPACTION_WARN_TIME("tserver.compaction.warn.time", "10m", PropertyType.TIMEDURATION,
"When a compaction has not made progress for this time period, a warning will be logged"),
TSERV_BLOOM_LOAD_MAXCONCURRENT("tserver.bloom.load.concurrent.max", "4", PropertyType.COUNT,
"The number of concurrent threads that will load bloom filters in the background. "
+ "Setting this to zero will make bloom filters load in the foreground."),
TSERV_MONITOR_FS("tserver.monitor.fs", "true", PropertyType.BOOLEAN,
"When enabled the tserver will monitor file systems and kill itself when one switches from rw to ro. This is usually and indication that Linux has"
+ " detected a bad disk."),
TSERV_MEMDUMP_DIR("tserver.dir.memdump", "/tmp", PropertyType.PATH,
"A long running scan could possibly hold memory that has been minor compacted. To prevent this, the in memory map is dumped to a local file and the "
+ "scan is switched to that local file. We can not switch to the minor compacted file because it may have been modified by iterators. The file "
+ "dumped to the local dir is an exact copy of what was in memory."),
TSERV_BULK_PROCESS_THREADS("tserver.bulk.process.threads", "1", PropertyType.COUNT,
"The master will task a tablet server with pre-processing a bulk file prior to assigning it to the appropriate tablet servers. This configuration"
+ " value controls the number of threads used to process the files."),
TSERV_BULK_ASSIGNMENT_THREADS("tserver.bulk.assign.threads", "1", PropertyType.COUNT,
"The master delegates bulk file processing and assignment to tablet servers. After the bulk file has been processed, the tablet server will assign"
+ " the file to the appropriate tablets on all servers. This property controls the number of threads used to communicate to the other servers."),
TSERV_BULK_RETRY("tserver.bulk.retry.max", "5", PropertyType.COUNT,
"The number of times the tablet server will attempt to assign a file to a tablet as it migrates and splits."),
TSERV_BULK_TIMEOUT("tserver.bulk.timeout", "5m", PropertyType.TIMEDURATION, "The time to wait for a tablet server to process a bulk import request."),
TSERV_MINTHREADS("tserver.server.threads.minimum", "20", PropertyType.COUNT, "The minimum number of threads to use to handle incoming requests."),
TSERV_THREADCHECK("tserver.server.threadcheck.time", "1s", PropertyType.TIMEDURATION, "The time between adjustments of the server thread pool."),
TSERV_MAX_MESSAGE_SIZE("tserver.server.message.size.max", "1G", PropertyType.MEMORY, "The maximum size of a message that can be sent to a tablet server."),
TSERV_HOLD_TIME_SUICIDE("tserver.hold.time.max", "5m", PropertyType.TIMEDURATION,
"The maximum time for a tablet server to be in the \"memory full\" state. If the tablet server cannot write out memory"
+ " in this much time, it will assume there is some failure local to its node, and quit. A value of zero is equivalent to forever."),
TSERV_WAL_BLOCKSIZE("tserver.wal.blocksize", "0", PropertyType.MEMORY,
"The size of the HDFS blocks used to write to the Write-Ahead log. If zero, it will be 110% of tserver.walog.max.size (that is, try to use just one"
+ " block)"),
TSERV_WAL_REPLICATION("tserver.wal.replication", "0", PropertyType.COUNT,
"The replication to use when writing the Write-Ahead log to HDFS. If zero, it will use the HDFS default replication setting."),
TSERV_RECOVERY_MAX_CONCURRENT("tserver.recovery.concurrent.max", "2", PropertyType.COUNT, "The maximum number of threads to use to sort logs during"
+ " recovery"),
TSERV_SORT_BUFFER_SIZE("tserver.sort.buffer.size", "200M", PropertyType.MEMORY, "The amount of memory to use when sorting logs during recovery."),
TSERV_ARCHIVE_WALOGS("tserver.archive.walogs", "false", PropertyType.BOOLEAN, "Keep copies of the WALOGs for debugging purposes"),
TSERV_WORKQ_THREADS("tserver.workq.threads", "2", PropertyType.COUNT,
"The number of threads for the distributed work queue. These threads are used for copying failed bulk files."),
TSERV_WAL_SYNC("tserver.wal.sync", "true", PropertyType.BOOLEAN,
"Use the SYNC_BLOCK create flag to sync WAL writes to disk. Prevents problems recovering from sudden system resets."),
@Deprecated
TSERV_WAL_SYNC_METHOD("tserver.wal.sync.method", "hsync", PropertyType.STRING, "This property is deprecated. Use table.durability instead."),
TSERV_ASSIGNMENT_DURATION_WARNING("tserver.assignment.duration.warning", "10m", PropertyType.TIMEDURATION, "The amount of time an assignment can run "
+ " before the server will print a warning along with the current stack trace. Meant to help debug stuck assignments"),
TSERV_REPLICATION_REPLAYERS("tserver.replication.replayer.", null, PropertyType.PREFIX,
"Allows configuration of implementation used to apply replicated data"),
TSERV_REPLICATION_DEFAULT_HANDLER("tserver.replication.default.replayer", "org.apache.accumulo.tserver.replication.BatchWriterReplicationReplayer",
PropertyType.CLASSNAME, "Default AccumuloReplicationReplayer implementation"),
TSERV_REPLICATION_BW_REPLAYER_MEMORY("tserver.replication.batchwriter.replayer.memory", "50M", PropertyType.MEMORY,
"Memory to provide to batchwriter to replay mutations for replication"),
TSERV_ASSIGNMENT_MAXCONCURRENT("tserver.assignment.concurrent.max", "2", PropertyType.COUNT,
"The number of threads available to load tablets. Recoveries are still performed serially."),
// properties that are specific to logger server behavior
LOGGER_PREFIX("logger.", null, PropertyType.PREFIX, "Properties in this category affect the behavior of the write-ahead logger servers"),
LOGGER_DIR("logger.dir.walog", "walogs", PropertyType.PATH, "This property is only needed if Accumulo was upgraded from a 1.4 or earlier version. "
+ "In the upgrade to 1.5 this property is used to copy any earlier write ahead logs into DFS. "
+ "In 1.6+, this property is used by the LocalWALRecovery utility in the event that something went wrong with that earlier upgrade. "
+ "It is possible to specify a comma-separated list of directories."),
// accumulo garbage collector properties
GC_PREFIX("gc.", null, PropertyType.PREFIX, "Properties in this category affect the behavior of the accumulo garbage collector."),
GC_CYCLE_START("gc.cycle.start", "30s", PropertyType.TIMEDURATION, "Time to wait before attempting to garbage collect any old files."),
GC_CYCLE_DELAY("gc.cycle.delay", "5m", PropertyType.TIMEDURATION, "Time between garbage collection cycles. In each cycle, old files "
+ "no longer in use are removed from the filesystem."),
GC_PORT("gc.port.client", "50091", PropertyType.PORT, "The listening port for the garbage collector's monitor service"),
GC_DELETE_THREADS("gc.threads.delete", "16", PropertyType.COUNT, "The number of threads used to delete files"),
GC_TRASH_IGNORE("gc.trash.ignore", "false", PropertyType.BOOLEAN, "Do not use the Trash, even if it is configured"),
GC_FILE_ARCHIVE("gc.file.archive", "false", PropertyType.BOOLEAN, "Archive any files/directories instead of moving to the HDFS trash or deleting"),
GC_TRACE_PERCENT("gc.trace.percent", "0.01", PropertyType.FRACTION, "Percent of gc cycles to trace"),
// properties that are specific to the monitor server behavior
MONITOR_PREFIX("monitor.", null, PropertyType.PREFIX, "Properties in this category affect the behavior of the monitor web server."),
MONITOR_PORT("monitor.port.client", "50095", PropertyType.PORT, "The listening port for the monitor's http service"),
MONITOR_LOG4J_PORT("monitor.port.log4j", "4560", PropertyType.PORT, "The listening port for the monitor's log4j logging collection."),
MONITOR_BANNER_TEXT("monitor.banner.text", "", PropertyType.STRING, "The banner text displayed on the monitor page."),
MONITOR_BANNER_COLOR("monitor.banner.color", "#c4c4c4", PropertyType.STRING, "The color of the banner text displayed on the monitor page."),
MONITOR_BANNER_BACKGROUND("monitor.banner.background", "#304065", PropertyType.STRING,
"The background color of the banner text displayed on the monitor page."),
MONITOR_SSL_KEYSTORE("monitor.ssl.keyStore", "", PropertyType.PATH, "The keystore for enabling monitor SSL."),
@Sensitive
MONITOR_SSL_KEYSTOREPASS("monitor.ssl.keyStorePassword", "", PropertyType.STRING, "The keystore password for enabling monitor SSL."),
MONITOR_SSL_KEYSTORETYPE("monitor.ssl.keyStoreType", "", PropertyType.STRING, "Type of SSL keystore"),
MONITOR_SSL_TRUSTSTORE("monitor.ssl.trustStore", "", PropertyType.PATH, "The truststore for enabling monitor SSL."),
@Sensitive
MONITOR_SSL_TRUSTSTOREPASS("monitor.ssl.trustStorePassword", "", PropertyType.STRING, "The truststore password for enabling monitor SSL."),
MONITOR_SSL_TRUSTSTORETYPE("monitor.ssl.trustStoreType", "", PropertyType.STRING, "Type of SSL truststore"),
MONITOR_SSL_INCLUDE_CIPHERS("monitor.ssl.include.ciphers", "", PropertyType.STRING,
"A comma-separated list of allows SSL Ciphers, see monitor.ssl.exclude.ciphers to disallow ciphers"),
MONITOR_SSL_EXCLUDE_CIPHERS("monitor.ssl.exclude.ciphers", "", PropertyType.STRING,
"A comma-separated list of disallowed SSL Ciphers, see mmonitor.ssl.include.ciphers to allow ciphers"),
MONITOR_SSL_INCLUDE_PROTOCOLS("monitor.ssl.include.protocols", "TLSv1,TLSv1.1,TLSv1.2", PropertyType.STRING, "A comma-separate list of allowed SSL protocols"),
MONITOR_LOCK_CHECK_INTERVAL("monitor.lock.check.interval", "5s", PropertyType.TIMEDURATION,
"The amount of time to sleep between checking for the Montior ZooKeeper lock"),
MONITOR_LOG_DATE_FORMAT("monitor.log.date.format", "yyyy/MM/dd HH:mm:ss,SSS", PropertyType.STRING, "The SimpleDateFormat string used to configure "
+ "the date shown on the 'Recent Logs' monitor page"),
TRACE_PREFIX("trace.", null, PropertyType.PREFIX, "Properties in this category affect the behavior of distributed tracing."),
TRACE_SPAN_RECEIVERS("trace.span.receivers", "org.apache.accumulo.tracer.ZooTraceClient", PropertyType.CLASSNAMELIST,
"A list of span receiver classes to send trace spans"),
TRACE_SPAN_RECEIVER_PREFIX("trace.span.receiver.", null, PropertyType.PREFIX, "Prefix for span receiver configuration properties"),
TRACE_ZK_PATH("trace.zookeeper.path", Constants.ZTRACERS, PropertyType.STRING, "The zookeeper node where tracers are registered"),
TRACE_PORT("trace.port.client", "12234", PropertyType.PORT, "The listening port for the trace server"),
TRACE_TABLE("trace.table", "trace", PropertyType.STRING, "The name of the table to store distributed traces"),
TRACE_USER("trace.user", "root", PropertyType.STRING, "The name of the user to store distributed traces"),
@Sensitive
TRACE_PASSWORD("trace.password", "secret", PropertyType.STRING, "The password for the user used to store distributed traces"),
@Sensitive
TRACE_TOKEN_PROPERTY_PREFIX("trace.token.property.", null, PropertyType.PREFIX,
"The prefix used to create a token for storing distributed traces. For each propetry required by trace.token.type, place this prefix in front of it."),
TRACE_TOKEN_TYPE("trace.token.type", PasswordToken.class.getName(), PropertyType.CLASSNAME, "An AuthenticationToken type supported by the authorizer"),
// per table properties
TABLE_PREFIX("table.", null, PropertyType.PREFIX, "Properties in this category affect tablet server treatment of tablets, but can be configured "
+ "on a per-table basis. Setting these properties in the site file will override the default globally "
+ "for all tables and not any specific table. However, both the default and the global setting can be "
+ "overridden per table using the table operations API or in the shell, which sets the overridden value "
+ "in zookeeper. Restarting accumulo tablet servers after setting these properties in the site file "
+ "will cause the global setting to take effect. However, you must use the API or the shell to change "
+ "properties in zookeeper that are set on a table."),
TABLE_ARBITRARY_PROP_PREFIX("table.custom.", null, PropertyType.PREFIX, "Prefix to be used for user defined arbitrary properties."),
TABLE_MAJC_RATIO("table.compaction.major.ratio", "3", PropertyType.FRACTION,
"minimum ratio of total input size to maximum input file size for running a major compactionWhen adjusting this property you may want to also "
+ "adjust table.file.max. Want to avoid the situation where only merging minor compactions occur."),
TABLE_MAJC_COMPACTALL_IDLETIME("table.compaction.major.everything.idle", "1h", PropertyType.TIMEDURATION,
"After a tablet has been idle (no mutations) for this time period it may have all "
+ "of its files compacted into one. There is no guarantee an idle tablet will be compacted. "
+ "Compactions of idle tablets are only started when regular compactions are not running. Idle "
+ "compactions only take place for tablets that have one or more files."),
TABLE_SPLIT_THRESHOLD("table.split.threshold", "1G", PropertyType.MEMORY, "When combined size of files exceeds this amount a tablet is split."),
TABLE_MAX_END_ROW_SIZE("table.split.endrow.size.max", "10K", PropertyType.MEMORY, "Maximum size of end row"),
TABLE_MINC_LOGS_MAX("table.compaction.minor.logs.threshold", "3", PropertyType.COUNT,
"When there are more than this many write-ahead logs against a tablet, it will be minor compacted. See comment for property tserver.memory.maps.max"),
TABLE_MINC_COMPACT_IDLETIME("table.compaction.minor.idle", "5m", PropertyType.TIMEDURATION,
"After a tablet has been idle (no mutations) for this time period it may have its "
+ "in-memory map flushed to disk in a minor compaction. There is no guarantee an idle " + "tablet will be compacted."),
TABLE_SCAN_MAXMEM("table.scan.max.memory", "512K", PropertyType.MEMORY,
"The maximum amount of memory that will be used to cache results of a client query/scan. "
+ "Once this limit is reached, the buffered data is sent to the client."),
TABLE_FILE_TYPE("table.file.type", RFile.EXTENSION, PropertyType.STRING, "Change the type of file a table writes"),
TABLE_LOAD_BALANCER("table.balancer", "org.apache.accumulo.server.master.balancer.DefaultLoadBalancer", PropertyType.STRING,
"This property can be set to allow the LoadBalanceByTable load balancer to change the called Load Balancer for this table"),
TABLE_FILE_COMPRESSION_TYPE("table.file.compress.type", "gz", PropertyType.STRING, "One of gz,lzo,none"),
TABLE_FILE_COMPRESSED_BLOCK_SIZE("table.file.compress.blocksize", "100K", PropertyType.MEMORY,
"Similar to the hadoop io.seqfile.compress.blocksize setting, so that files have better query performance. The maximum value for this is "
+ Integer.MAX_VALUE + ". (This setting is the size threshold prior to compression, and applies even compression is disabled.)"),
TABLE_FILE_COMPRESSED_BLOCK_SIZE_INDEX("table.file.compress.blocksize.index", "128K", PropertyType.MEMORY,
"Determines how large index blocks can be in files that support multilevel indexes. The maximum value for this is " + Integer.MAX_VALUE + "."
+ " (This setting is the size threshold prior to compression, and applies even compression is disabled.)"),
TABLE_FILE_BLOCK_SIZE("table.file.blocksize", "0B", PropertyType.MEMORY,
"Overrides the hadoop dfs.block.size setting so that files have better query performance. The maximum value for this is " + Integer.MAX_VALUE),
TABLE_FILE_REPLICATION("table.file.replication", "0", PropertyType.COUNT, "Determines how many replicas to keep of a tables' files in HDFS. "
+ "When this value is LTE 0, HDFS defaults are used."),
TABLE_FILE_MAX("table.file.max", "15", PropertyType.COUNT,
"Determines the max # of files each tablet in a table can have. When adjusting this property you may want to consider adjusting"
+ " table.compaction.major.ratio also. Setting this property to 0 will make it default to tserver.scan.files.open.max-1, this will prevent a"
+ " tablet from having more files than can be opened. Setting this property low may throttle ingest and increase query performance."),
@Deprecated
TABLE_WALOG_ENABLED("table.walog.enabled", "true", PropertyType.BOOLEAN, "This setting is deprecated. Use table.durability=none instead."),
TABLE_BLOOM_ENABLED("table.bloom.enabled", "false", PropertyType.BOOLEAN, "Use bloom filters on this table."),
TABLE_BLOOM_LOAD_THRESHOLD("table.bloom.load.threshold", "1", PropertyType.COUNT,
"This number of seeks that would actually use a bloom filter must occur before a file's bloom filter is loaded."
+ " Set this to zero to initiate loading of bloom filters when a file is opened."),
TABLE_BLOOM_SIZE("table.bloom.size", "1048576", PropertyType.COUNT, "Bloom filter size, as number of keys."),
TABLE_BLOOM_ERRORRATE("table.bloom.error.rate", "0.5%", PropertyType.FRACTION, "Bloom filter error rate."),
TABLE_BLOOM_KEY_FUNCTOR("table.bloom.key.functor", "org.apache.accumulo.core.file.keyfunctor.RowFunctor", PropertyType.CLASSNAME,
"A function that can transform the key prior to insertion and check of bloom filter. org.apache.accumulo.core.file.keyfunctor.RowFunctor,"
+ ",org.apache.accumulo.core.file.keyfunctor.ColumnFamilyFunctor, and org.apache.accumulo.core.file.keyfunctor.ColumnQualifierFunctor are"
+ " allowable values. One can extend any of the above mentioned classes to perform specialized parsing of the key. "),
TABLE_BLOOM_HASHTYPE("table.bloom.hash.type", "murmur", PropertyType.STRING, "The bloom filter hash type"),
TABLE_DURABILITY("table.durability", "sync", PropertyType.DURABILITY, "The durability used to write to the write-ahead log."
+ " Legal values are: none, which skips the write-ahead log; "
+ "log, which sends the data to the write-ahead log, but does nothing to make it durable; " + "flush, which pushes data to the file system; and "
+ "sync, which ensures the data is written to disk."),
TABLE_FAILURES_IGNORE("table.failures.ignore", "false", PropertyType.BOOLEAN,
"If you want queries for your table to hang or fail when data is missing from the system, "
+ "then set this to false. When this set to true missing data will be reported but queries "
+ "will still run possibly returning a subset of the data."),
TABLE_DEFAULT_SCANTIME_VISIBILITY("table.security.scan.visibility.default", "", PropertyType.STRING,
"The security label that will be assumed at scan time if an entry does not have a visibility set.\n"
+ "Note: An empty security label is displayed as []. The scan results will show an empty visibility even if "
+ "the visibility from this setting is applied to the entry.\n"
+ "CAUTION: If a particular key has an empty security label AND its table's default visibility is also empty, "
+ "access will ALWAYS be granted for users with permission to that table. Additionally, if this field is changed, "
+ "all existing data with an empty visibility label will be interpreted with the new label on the next scan."),
TABLE_LOCALITY_GROUPS("table.groups.enabled", "", PropertyType.STRING, "A comma separated list of locality group names to enable for this table."),
TABLE_CONSTRAINT_PREFIX("table.constraint.", null, PropertyType.PREFIX,
"Properties in this category are per-table properties that add constraints to a table. "
+ "These properties start with the category prefix, followed by a number, and their values "
+ "correspond to a fully qualified Java class that implements the Constraint interface.\n"
+ "For example:\ntable.constraint.1 = org.apache.accumulo.core.constraints.MyCustomConstraint\n"
+ "and:\ntable.constraint.2 = my.package.constraints.MySecondConstraint"),
TABLE_INDEXCACHE_ENABLED("table.cache.index.enable", "true", PropertyType.BOOLEAN, "Determines whether index cache is enabled."),
TABLE_BLOCKCACHE_ENABLED("table.cache.block.enable", "false", PropertyType.BOOLEAN, "Determines whether file block cache is enabled."),
TABLE_ITERATOR_PREFIX("table.iterator.", null, PropertyType.PREFIX,
"Properties in this category specify iterators that are applied at various stages (scopes) of interaction "
+ "with a table. These properties start with the category prefix, followed by a scope (minc, majc, scan, etc.), "
+ "followed by a period, followed by a name, as in table.iterator.scan.vers, or table.iterator.scan.custom. "
+ "The values for these properties are a number indicating the ordering in which it is applied, and a class name "
+ "such as:\n table.iterator.scan.vers = 10,org.apache.accumulo.core.iterators.VersioningIterator\n "
+ "These iterators can take options if additional properties are set that look like this property, "
+ "but are suffixed with a period, followed by 'opt' followed by another period, and a property name.\n"
+ "For example, table.iterator.minc.vers.opt.maxVersions = 3"),
TABLE_ITERATOR_SCAN_PREFIX(TABLE_ITERATOR_PREFIX.getKey() + IteratorScope.scan.name() + ".", null, PropertyType.PREFIX,
"Convenience prefix to find options for the scan iterator scope"),
TABLE_ITERATOR_MINC_PREFIX(TABLE_ITERATOR_PREFIX.getKey() + IteratorScope.minc.name() + ".", null, PropertyType.PREFIX,
"Convenience prefix to find options for the minc iterator scope"),
TABLE_ITERATOR_MAJC_PREFIX(TABLE_ITERATOR_PREFIX.getKey() + IteratorScope.majc.name() + ".", null, PropertyType.PREFIX,
"Convenience prefix to find options for the majc iterator scope"),
TABLE_LOCALITY_GROUP_PREFIX("table.group.", null, PropertyType.PREFIX,
"Properties in this category are per-table properties that define locality groups in a table. These properties start "
+ "with the category prefix, followed by a name, followed by a period, and followed by a property for that group.\n"
+ "For example table.group.group1=x,y,z sets the column families for a group called group1. Once configured, "
+ "group1 can be enabled by adding it to the list of groups in the " + TABLE_LOCALITY_GROUPS.getKey() + " property.\n"
+ "Additional group options may be specified for a named group by setting table.group.<name>.opt.<key>=<value>."),
TABLE_FORMATTER_CLASS("table.formatter", DefaultFormatter.class.getName(), PropertyType.STRING, "The Formatter class to apply on results in the shell"),
TABLE_INTERPRETER_CLASS("table.interepreter", DefaultScanInterpreter.class.getName(), PropertyType.STRING,
"The ScanInterpreter class to apply on scan arguments in the shell"),
TABLE_CLASSPATH("table.classpath.context", "", PropertyType.STRING, "Per table classpath context"),
TABLE_COMPACTION_STRATEGY("table.majc.compaction.strategy", "org.apache.accumulo.tserver.compaction.DefaultCompactionStrategy", PropertyType.CLASSNAME,
"A customizable major compaction strategy."),
TABLE_COMPACTION_STRATEGY_PREFIX("table.majc.compaction.strategy.opts.", null, PropertyType.PREFIX,
"Properties in this category are used to configure the compaction strategy."),
TABLE_REPLICATION("table.replication", "false", PropertyType.BOOLEAN, "Is replication enabled for the given table"),
TABLE_REPLICATION_TARGET("table.replication.target.", null, PropertyType.PREFIX, "Enumerate a mapping of other systems which this table should "
+ "replicate their data to. The key suffix is the identifying cluster name and the value is an identifier for a location on the target system, "
+ "e.g. the ID of the table on the target to replicate to"),
@Experimental
TABLE_VOLUME_CHOOSER("table.volume.chooser", "org.apache.accumulo.server.fs.RandomVolumeChooser", PropertyType.CLASSNAME,
"The class that will be used to select which volume will be used to create new files for this table."),
// VFS ClassLoader properties
VFS_CLASSLOADER_SYSTEM_CLASSPATH_PROPERTY(AccumuloVFSClassLoader.VFS_CLASSLOADER_SYSTEM_CLASSPATH_PROPERTY, "", PropertyType.STRING,
"Configuration for a system level vfs classloader. Accumulo jar can be configured here and loaded out of HDFS."),
VFS_CONTEXT_CLASSPATH_PROPERTY(AccumuloVFSClassLoader.VFS_CONTEXT_CLASSPATH_PROPERTY, null, PropertyType.PREFIX,
"Properties in this category are define a classpath. These properties start with the category prefix, followed by a context name. "
+ "The value is a comma seperated list of URIs. Supports full regex on filename alone. For example, "
+ "general.vfs.context.classpath.cx1=hdfs://nn1:9902/mylibdir/*.jar. "
+ "You can enable post delegation for a context, which will load classes from the context first instead of the parent first. "
+ "Do this by setting general.vfs.context.classpath.<name>.delegation=post, where <name> is your context name"
+ "If delegation is not specified, it defaults to loading from parent classloader first."),
@Interpolated
VFS_CLASSLOADER_CACHE_DIR(AccumuloVFSClassLoader.VFS_CACHE_DIR, "${java.io.tmpdir}" + File.separator + "accumulo-vfs-cache-${user.name}",
PropertyType.ABSOLUTEPATH, "Directory to use for the vfs cache. The cache will keep a soft reference to all of the classes loaded in the VM."
+ " This should be on local disk on each node with sufficient space. It defaults to ${java.io.tmpdir}/accumulo-vfs-cache-${user.name}"),
@Interpolated
@Experimental
GENERAL_MAVEN_PROJECT_BASEDIR(AccumuloClassLoader.MAVEN_PROJECT_BASEDIR_PROPERTY_NAME, AccumuloClassLoader.DEFAULT_MAVEN_PROJECT_BASEDIR_VALUE,
PropertyType.ABSOLUTEPATH, "Set this to automatically add maven target/classes directories to your dynamic classpath"),
// General properties for configuring replication
REPLICATION_PREFIX("replication.", null, PropertyType.PREFIX, "Properties in this category affect the replication of data to other Accumulo instances."),
REPLICATION_PEERS("replication.peer.", null, PropertyType.PREFIX, "Properties in this category control what systems data can be replicated to"),
REPLICATION_PEER_USER("replication.peer.user.", null, PropertyType.PREFIX, "The username to provide when authenticating with the given peer"),
@Sensitive
REPLICATION_PEER_PASSWORD("replication.peer.password.", null, PropertyType.PREFIX, "The password to provide when authenticating with the given peer"),
REPLICATION_PEER_KEYTAB("replication.peer.keytab.", null, PropertyType.PREFIX, "The keytab to use when authenticating with the given peer"),
REPLICATION_NAME("replication.name", "", PropertyType.STRING,
"Name of this cluster with respect to replication. Used to identify this instance from other peers"),
REPLICATION_MAX_WORK_QUEUE("replication.max.work.queue", "1000", PropertyType.COUNT, "Upper bound of the number of files queued for replication"),
REPLICATION_WORK_ASSIGNMENT_SLEEP("replication.work.assignment.sleep", "30s", PropertyType.TIMEDURATION,
"Amount of time to sleep between replication work assignment"),
REPLICATION_WORKER_THREADS("replication.worker.threads", "4", PropertyType.COUNT, "Size of the threadpool that each tabletserver devotes to replicating data"),
REPLICATION_RECEIPT_SERVICE_PORT("replication.receipt.service.port", "10002", PropertyType.PORT,
"Listen port used by thrift service in tserver listening for replication"),
REPLICATION_WORK_ATTEMPTS("replication.work.attempts", "10", PropertyType.COUNT,
"Number of attempts to try to replicate some data before giving up and letting it naturally be retried later"),
REPLICATION_MIN_THREADS("replication.receiver.min.threads", "1", PropertyType.COUNT, "Minimum number of threads for replication"),
REPLICATION_THREADCHECK("replication.receiver.threadcheck.time", "30s", PropertyType.TIMEDURATION,
"The time between adjustments of the replication thread pool."),
REPLICATION_MAX_UNIT_SIZE("replication.max.unit.size", "64M", PropertyType.MEMORY, "Maximum size of data to send in a replication message"),
REPLICATION_WORK_ASSIGNER("replication.work.assigner", "org.apache.accumulo.master.replication.UnorderedWorkAssigner", PropertyType.CLASSNAME,
"Replication WorkAssigner implementation to use"),
REPLICATION_DRIVER_DELAY("replication.driver.delay", "0s", PropertyType.TIMEDURATION,
"Amount of time to wait before the replication work loop begins in the master."),
REPLICATION_WORK_PROCESSOR_DELAY("replication.work.processor.delay", "0s", PropertyType.TIMEDURATION,
"Amount of time to wait before first checking for replication work, not useful outside of tests"),
REPLICATION_WORK_PROCESSOR_PERIOD("replication.work.processor.period", "0s", PropertyType.TIMEDURATION,
"Amount of time to wait before re-checking for replication work, not useful outside of tests"),
REPLICATION_TRACE_PERCENT("replication.trace.percent", "0.1", PropertyType.FRACTION, "The sampling percentage to use for replication traces"),
;
private String key, defaultValue, description;
private PropertyType type;
private static final Logger log = LoggerFactory.getLogger(Property.class);
private Property(String name, String defaultValue, PropertyType type, String description) {
this.key = name;
this.defaultValue = defaultValue;
this.description = description;
this.type = type;
}
@Override
public String toString() {
return this.key;
}
/**
* Gets the key (string) for this property.
*
* @return key
*/
public String getKey() {
return this.key;
}
/**
* Gets the default value for this property exactly as provided in its definition (i.e., without interpolation or conversion to absolute paths).
*
* @return raw default value
*/
public String getRawDefaultValue() {
return this.defaultValue;
}
/**
* Gets the default value for this property. System properties are interpolated into the value if necessary.
*
* @return default value
*/
public String getDefaultValue() {
String v;
if (isInterpolated()) {
PropertiesConfiguration pconf = new PropertiesConfiguration();
Properties systemProperties = System.getProperties();
synchronized (systemProperties) {
pconf.append(new MapConfiguration(systemProperties));
}
pconf.addProperty("hack_default_value", this.defaultValue);
v = pconf.getString("hack_default_value");
} else {
v = getRawDefaultValue();
}
if (this.type == PropertyType.ABSOLUTEPATH && !(v.trim().equals("")))
v = new File(v).getAbsolutePath();
return v;
}
/**
* Gets the type of this property.
*
* @return property type
*/
public PropertyType getType() {
return this.type;
}
/**
* Gets the description of this property.
*
* @return description
*/
public String getDescription() {
return this.description;
}
private boolean isInterpolated() {
return hasAnnotation(Interpolated.class) || hasPrefixWithAnnotation(getKey(), Interpolated.class);
}
/**
* Checks if this property is experimental.
*
* @return true if this property is experimental
*/
public boolean isExperimental() {
return hasAnnotation(Experimental.class) || hasPrefixWithAnnotation(getKey(), Experimental.class);
}
/**
* Checks if this property is deprecated.
*
* @return true if this property is deprecated
*/
public boolean isDeprecated() {
return hasAnnotation(Deprecated.class) || hasPrefixWithAnnotation(getKey(), Deprecated.class);
}
private volatile Boolean isSensitive = null;
/**
* Checks if this property is sensitive.
*
* @return true if this property is sensitive
*/
public boolean isSensitive() {
if (isSensitive == null) {
isSensitive = hasAnnotation(Sensitive.class) || hasPrefixWithAnnotation(getKey(), Sensitive.class);
}
return isSensitive.booleanValue();
}
/**
* Checks if a property with the given key is sensitive. The key must be for a valid property, and must either itself be annotated as sensitive or have a
* prefix annotated as sensitive.
*
* @param key
* property key
* @return true if property is sensitive
*/
public static boolean isSensitive(String key) {
return hasPrefixWithAnnotation(key, Sensitive.class);
}
private <T extends Annotation> boolean hasAnnotation(Class<T> annotationType) {
Logger log = LoggerFactory.getLogger(getClass());
try {
for (Annotation a : getClass().getField(name()).getAnnotations())
if (annotationType.isInstance(a))
return true;
} catch (SecurityException e) {
log.error("{}", e.getMessage(), e);
} catch (NoSuchFieldException e) {
log.error("{}", e.getMessage(), e);
}
return false;
}
private static <T extends Annotation> boolean hasPrefixWithAnnotation(String key, Class<T> annotationType) {
// relies on side-effects of isValidPropertyKey to populate validPrefixes
if (isValidPropertyKey(key)) {
// check if property exists on its own and has the annotation
if (Property.getPropertyByKey(key) != null)
return getPropertyByKey(key).hasAnnotation(annotationType);
// can't find the property, so check the prefixes
boolean prefixHasAnnotation = false;
for (String prefix : validPrefixes)
if (key.startsWith(prefix))
prefixHasAnnotation = prefixHasAnnotation || getPropertyByKey(prefix).hasAnnotation(annotationType);
return prefixHasAnnotation;
}
return false;
}
private static HashSet<String> validTableProperties = null;
private static HashSet<String> validProperties = null;
private static HashSet<String> validPrefixes = null;
private static boolean isKeyValidlyPrefixed(String key) {
for (String prefix : validPrefixes) {
if (key.startsWith(prefix))
return true;
}
return false;
}
/**
* Checks if the given property key is valid. A valid property key is either equal to the key of some defined property or has a prefix matching some prefix
* defined in this class.
*
* @param key
* property key
* @return true if key is valid (recognized, or has a recognized prefix)
*/
public synchronized static boolean isValidPropertyKey(String key) {
if (validProperties == null) {
validProperties = new HashSet<String>();
validPrefixes = new HashSet<String>();
for (Property p : Property.values()) {
if (p.getType().equals(PropertyType.PREFIX)) {
validPrefixes.add(p.getKey());
} else {
validProperties.add(p.getKey());
}
}
}
return validProperties.contains(key) || isKeyValidlyPrefixed(key);
}
/**
* Checks if the given property key is for a valid table property. A valid table property key is either equal to the key of some defined table property (which
* each start with {@link #TABLE_PREFIX}) or has a prefix matching {@link #TABLE_CONSTRAINT_PREFIX}, {@link #TABLE_ITERATOR_PREFIX}, or
* {@link #TABLE_LOCALITY_GROUP_PREFIX}.
*
* @param key
* property key
* @return true if key is valid for a table property (recognized, or has a recognized prefix)
*/
public synchronized static boolean isValidTablePropertyKey(String key) {
if (validTableProperties == null) {
validTableProperties = new HashSet<String>();
for (Property p : Property.values()) {
if (!p.getType().equals(PropertyType.PREFIX) && p.getKey().startsWith(Property.TABLE_PREFIX.getKey())) {
validTableProperties.add(p.getKey());
}
}
}
return validTableProperties.contains(key) || key.startsWith(Property.TABLE_CONSTRAINT_PREFIX.getKey())
|| key.startsWith(Property.TABLE_ITERATOR_PREFIX.getKey()) || key.startsWith(Property.TABLE_LOCALITY_GROUP_PREFIX.getKey())
|| key.startsWith(Property.TABLE_COMPACTION_STRATEGY_PREFIX.getKey()) || key.startsWith(Property.TABLE_REPLICATION_TARGET.getKey())
|| key.startsWith(Property.TABLE_ARBITRARY_PROP_PREFIX.getKey());
}
private static final EnumSet<Property> fixedProperties = EnumSet.of(Property.TSERV_CLIENTPORT, Property.TSERV_NATIVEMAP_ENABLED,
Property.TSERV_SCAN_MAX_OPENFILES, Property.MASTER_CLIENTPORT, Property.GC_PORT);
/**
* Checks if the given property may be changed via Zookeeper, but not recognized until the restart of some relevant daemon.
*
* @param key
* property key
* @return true if property may be changed via Zookeeper but only heeded upon some restart
*/
public static boolean isFixedZooPropertyKey(Property key) {
return fixedProperties.contains(key);
}
/**
* Checks if the given property key is valid for a property that may be changed via Zookeeper.
*
* @param key
* property key
* @return true if key's property may be changed via Zookeeper
*/
public static boolean isValidZooPropertyKey(String key) {
// white list prefixes
return key.startsWith(Property.TABLE_PREFIX.getKey()) || key.startsWith(Property.TSERV_PREFIX.getKey()) || key.startsWith(Property.LOGGER_PREFIX.getKey())
|| key.startsWith(Property.MASTER_PREFIX.getKey()) || key.startsWith(Property.GC_PREFIX.getKey())
|| key.startsWith(Property.MONITOR_PREFIX.getKey() + "banner.") || key.startsWith(VFS_CONTEXT_CLASSPATH_PROPERTY.getKey())
|| key.startsWith(Property.TABLE_COMPACTION_STRATEGY_PREFIX.getKey()) || key.startsWith(REPLICATION_PREFIX.getKey());
}
/**
* Gets a {@link Property} instance with the given key.
*
* @param key
* property key
* @return property, or null if not found
*/
public static Property getPropertyByKey(String key) {
for (Property prop : Property.values())
if (prop.getKey().equals(key))
return prop;
return null;
}
/**
* Checks if this property is expected to have a Java class as a value.
*
* @return true if this is property is a class property
*/
public static boolean isClassProperty(String key) {
return (key.startsWith(Property.TABLE_CONSTRAINT_PREFIX.getKey()) && key.substring(Property.TABLE_CONSTRAINT_PREFIX.getKey().length()).split("\\.").length == 1)
|| (key.startsWith(Property.TABLE_ITERATOR_PREFIX.getKey()) && key.substring(Property.TABLE_ITERATOR_PREFIX.getKey().length()).split("\\.").length == 2)
|| key.equals(Property.TABLE_LOAD_BALANCER.getKey());
}
// This is not a cache for loaded classes, just a way to avoid spamming the debug log
static Map<String,Class<?>> loaded = Collections.synchronizedMap(new HashMap<String,Class<?>>());
private static <T> T createInstance(String context, String clazzName, Class<T> base, T defaultInstance) {
T instance = null;
try {
Class<? extends T> clazz;
if (context != null && !context.equals("")) {
clazz = AccumuloVFSClassLoader.getContextManager().loadClass(context, clazzName, base);
} else {
clazz = AccumuloVFSClassLoader.loadClass(clazzName, base);
}
instance = clazz.newInstance();
if (loaded.put(clazzName, clazz) != clazz)
log.debug("Loaded class : " + clazzName);
} catch (Exception e) {
log.warn("Failed to load class ", e);
}
if (instance == null) {
log.info("Using default class " + defaultInstance.getClass().getName());
instance = defaultInstance;
}
return instance;
}
/**
* Creates a new instance of a class specified in a configuration property. The table classpath context is used if set.
*
* @param conf
* configuration containing property
* @param property
* property specifying class name
* @param base
* base class of type
* @param defaultInstance
* instance to use if creation fails
* @return new class instance, or default instance if creation failed
* @see AccumuloVFSClassLoader
*/
public static <T> T createTableInstanceFromPropertyName(AccumuloConfiguration conf, Property property, Class<T> base, T defaultInstance) {
String clazzName = conf.get(property);
String context = conf.get(TABLE_CLASSPATH);
return createInstance(context, clazzName, base, defaultInstance);
}
/**
* Creates a new instance of a class specified in a configuration property.
*
* @param conf
* configuration containing property
* @param property
* property specifying class name
* @param base
* base class of type
* @param defaultInstance
* instance to use if creation fails
* @return new class instance, or default instance if creation failed
* @see AccumuloVFSClassLoader
*/
public static <T> T createInstanceFromPropertyName(AccumuloConfiguration conf, Property property, Class<T> base, T defaultInstance) {
String clazzName = conf.get(property);
return createInstance(null, clazzName, base, defaultInstance);
}
/**
* Collects together properties from the given configuration pertaining to compaction strategies. The relevant properties all begin with the prefix in
* {@link #TABLE_COMPACTION_STRATEGY_PREFIX}. In the returned map, the prefix is removed from each property's key.
*
* @param tableConf
* configuration
* @return map of compaction strategy property keys and values, with the detection prefix removed from each key
*/
public static Map<String,String> getCompactionStrategyOptions(AccumuloConfiguration tableConf) {
Map<String,String> longNames = tableConf.getAllPropertiesWithPrefix(Property.TABLE_COMPACTION_STRATEGY_PREFIX);
Map<String,String> result = new HashMap<String,String>();
for (Entry<String,String> entry : longNames.entrySet()) {
result.put(entry.getKey().substring(Property.TABLE_COMPACTION_STRATEGY_PREFIX.getKey().length()), entry.getValue());
}
return result;
}
}
|
core/src/main/java/org/apache/accumulo/core/conf/Property.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.accumulo.core.conf;
import java.io.File;
import java.lang.annotation.Annotation;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import org.apache.accumulo.core.Constants;
import org.apache.accumulo.core.client.security.tokens.PasswordToken;
import org.apache.accumulo.core.file.rfile.RFile;
import org.apache.accumulo.core.iterators.IteratorUtil.IteratorScope;
import org.apache.accumulo.core.util.format.DefaultFormatter;
import org.apache.accumulo.core.util.interpret.DefaultScanInterpreter;
import org.apache.accumulo.start.classloader.AccumuloClassLoader;
import org.apache.accumulo.start.classloader.vfs.AccumuloVFSClassLoader;
import org.apache.commons.configuration.MapConfiguration;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public enum Property {
// Crypto-related properties
@Experimental
CRYPTO_PREFIX("crypto.", null, PropertyType.PREFIX, "Properties in this category related to the configuration of both default and custom crypto modules."),
@Experimental
CRYPTO_MODULE_CLASS("crypto.module.class", "NullCryptoModule", PropertyType.STRING,
"Fully qualified class name of the class that implements the CryptoModule interface, to be used in setting up encryption at rest for the WAL and "
+ "(future) other parts of the code."),
@Experimental
CRYPTO_CIPHER_SUITE("crypto.cipher.suite", "NullCipher", PropertyType.STRING, "Describes the cipher suite to use for the write-ahead log"),
@Experimental
CRYPTO_CIPHER_ALGORITHM_NAME("crypto.cipher.algorithm.name", "NullCipher", PropertyType.STRING,
"States the name of the algorithm used in the corresponding cipher suite. Do not make these different, unless you enjoy mysterious exceptions and bugs."),
@Experimental
CRYPTO_BLOCK_STREAM_SIZE("crypto.block.stream.size", "1K", PropertyType.MEMORY,
"The size of the buffer above the cipher stream. Used for reading files and padding walog entries."),
@Experimental
CRYPTO_CIPHER_KEY_LENGTH("crypto.cipher.key.length", "128", PropertyType.STRING,
"Specifies the key length *in bits* to use for the symmetric key, should probably be 128 or 256 unless you really know what you're doing"),
@Experimental
CRYPTO_SECURE_RNG("crypto.secure.rng", "SHA1PRNG", PropertyType.STRING,
"States the secure random number generator to use, and defaults to the built-in Sun SHA1PRNG"),
@Experimental
CRYPTO_SECURE_RNG_PROVIDER("crypto.secure.rng.provider", "SUN", PropertyType.STRING,
"States the secure random number generator provider to use, and defaults to the built-in SUN provider"),
@Experimental
CRYPTO_SECRET_KEY_ENCRYPTION_STRATEGY_CLASS("crypto.secret.key.encryption.strategy.class", "NullSecretKeyEncryptionStrategy", PropertyType.STRING,
"The class Accumulo should use for its key encryption strategy."),
@Experimental
CRYPTO_DEFAULT_KEY_STRATEGY_HDFS_URI("crypto.default.key.strategy.hdfs.uri", "", PropertyType.STRING,
"The path relative to the top level instance directory (instance.dfs.dir) where to store the key encryption key within HDFS."),
@Experimental
CRYPTO_DEFAULT_KEY_STRATEGY_KEY_LOCATION("crypto.default.key.strategy.key.location", "/crypto/secret/keyEncryptionKey", PropertyType.ABSOLUTEPATH,
"The path relative to the top level instance directory (instance.dfs.dir) where to store the key encryption key within HDFS."),
@Experimental
CRYPTO_DEFAULT_KEY_STRATEGY_CIPHER_SUITE("crypto.default.key.strategy.cipher.suite", "NullCipher", PropertyType.STRING,
"The cipher suite to use when encrypting session keys with a key encryption keyThis should be set to match the overall encryption algorithm "
+ "but with ECB mode and no padding unless you really know what you're doing and are sure you won't break internal file formats"),
@Experimental
CRYPTO_OVERRIDE_KEY_STRATEGY_WITH_CONFIGURED_STRATEGY("crypto.override.key.strategy.with.configured.strategy", "false", PropertyType.BOOLEAN,
"The default behavior is to record the key encryption strategy with the encrypted file, and continue to use that strategy for the life "
+ "of that file. Sometimes, you change your strategy and want to use the new strategy, not the old one. (Most commonly, this will be "
+ "because you have moved key material from one spot to another.) If you want to override the recorded key strategy with the one in "
+ "the configuration file, set this property to true."),
// SSL properties local to each node (see also instance.ssl.enabled which must be consistent across all nodes in an instance)
RPC_PREFIX("rpc.", null, PropertyType.PREFIX, "Properties in this category related to the configuration of SSL keys for RPC. See also instance.ssl.enabled"),
RPC_SSL_KEYSTORE_PATH("rpc.javax.net.ssl.keyStore", "$ACCUMULO_CONF_DIR/ssl/keystore.jks", PropertyType.PATH,
"Path of the keystore file for the servers' private SSL key"),
@Sensitive
RPC_SSL_KEYSTORE_PASSWORD("rpc.javax.net.ssl.keyStorePassword", "", PropertyType.STRING,
"Password used to encrypt the SSL private keystore. Leave blank to use the Accumulo instance secret"),
RPC_SSL_KEYSTORE_TYPE("rpc.javax.net.ssl.keyStoreType", "jks", PropertyType.STRING, "Type of SSL keystore"),
RPC_SSL_TRUSTSTORE_PATH("rpc.javax.net.ssl.trustStore", "$ACCUMULO_CONF_DIR/ssl/truststore.jks", PropertyType.PATH,
"Path of the truststore file for the root cert"),
@Sensitive
RPC_SSL_TRUSTSTORE_PASSWORD("rpc.javax.net.ssl.trustStorePassword", "", PropertyType.STRING,
"Password used to encrypt the SSL truststore. Leave blank to use no password"),
RPC_SSL_TRUSTSTORE_TYPE("rpc.javax.net.ssl.trustStoreType", "jks", PropertyType.STRING, "Type of SSL truststore"),
RPC_USE_JSSE("rpc.useJsse", "false", PropertyType.BOOLEAN, "Use JSSE system properties to configure SSL rather than the " + RPC_PREFIX.getKey()
+ "javax.net.ssl.* Accumulo properties"),
RPC_SSL_CIPHER_SUITES("rpc.ssl.cipher.suites", "", PropertyType.STRING, "Comma separated list of cipher suites that can be used by accepted connections"),
RPC_SSL_ENABLED_PROTOCOLS("rpc.ssl.server.enabled.protocols", "TLSv1,TLSv1.1,TLSv1.2", PropertyType.STRING,
"Comma separated list of protocols that can be used to accept connections"),
// TLSv1.2 should be used as the default when JDK6 support is dropped
RPC_SSL_CLIENT_PROTOCOL("rpc.ssl.client.protocol", "TLSv1", PropertyType.STRING,
"The protocol used to connect to a secure server, must be in the list of enabled protocols on the server side (rpc.ssl.server.enabled.protocols)"),
/**
* @since 1.7.0
*/
RPC_SASL_QOP("rpc.sasl.qop", "auth", PropertyType.STRING,
"The quality of protection to be used with SASL. Valid values are 'auth', 'auth-int', and 'auth-conf'"),
// instance properties (must be the same for every node in an instance)
INSTANCE_PREFIX("instance.", null, PropertyType.PREFIX,
"Properties in this category must be consistent throughout a cloud. This is enforced and servers won't be able to communicate if these differ."),
INSTANCE_ZK_HOST("instance.zookeeper.host", "localhost:2181", PropertyType.HOSTLIST, "Comma separated list of zookeeper servers"),
INSTANCE_ZK_TIMEOUT("instance.zookeeper.timeout", "30s", PropertyType.TIMEDURATION,
"Zookeeper session timeout; max value when represented as milliseconds should be no larger than " + Integer.MAX_VALUE),
@Deprecated
INSTANCE_DFS_URI("instance.dfs.uri", "", PropertyType.URI,
"A url accumulo should use to connect to DFS. If this is empty, accumulo will obtain this information from the hadoop configuration. This property "
+ "will only be used when creating new files if instance.volumes is empty. After an upgrade to 1.6.0 Accumulo will start using absolute paths to "
+ "reference files. Files created before a 1.6.0 upgrade are referenced via relative paths. Relative paths will always be resolved using this "
+ "config (if empty using the hadoop config)."),
@Deprecated
INSTANCE_DFS_DIR("instance.dfs.dir", "/accumulo", PropertyType.ABSOLUTEPATH,
"HDFS directory in which accumulo instance will run. Do not change after accumulo is initialized."),
@Sensitive
INSTANCE_SECRET("instance.secret", "DEFAULT", PropertyType.STRING,
"A secret unique to a given instance that all servers must know in order to communicate with one another."
+ " Change it before initialization. To change it later use ./bin/accumulo accumulo.server.util.ChangeSecret [oldpasswd] [newpasswd], "
+ " and then update conf/accumulo-site.xml everywhere."),
INSTANCE_VOLUMES("instance.volumes", "", PropertyType.STRING,
"A comma seperated list of dfs uris to use. Files will be stored across these filesystems. If this is empty, then instance.dfs.uri will be used. "
+ "After adding uris to this list, run 'accumulo init --add-volume' and then restart tservers. If entries are removed from this list then tservers "
+ "will need to be restarted. After a uri is removed from the list Accumulo will not create new files in that location, however Accumulo can still "
+ "reference files created at that location before the config change. To use a comma or other reserved characters in a URI use standard URI hex "
+ "encoding. For example replace commas with %2C."),
INSTANCE_VOLUMES_REPLACEMENTS("instance.volumes.replacements", "", PropertyType.STRING,
"Since accumulo stores absolute URIs changing the location of a namenode could prevent Accumulo from starting. The property helps deal with that "
+ "situation. Provide a comma separated list of uri replacement pairs here if a namenode location changes. Each pair shold be separated with a "
+ "space. For example, if hdfs://nn1 was replaced with hdfs://nnA and hdfs://nn2 was replaced with hdfs://nnB, then set this property to "
+ "'hdfs://nn1 hdfs://nnA,hdfs://nn2 hdfs://nnB' Replacements must be configured for use. To see which volumes are currently in use, run "
+ "'accumulo admin volumes -l'. To use a comma or other reserved characters in a URI use standard URI hex encoding. For example replace commas with "
+ "%2C."),
INSTANCE_SECURITY_AUTHENTICATOR("instance.security.authenticator", "org.apache.accumulo.server.security.handler.ZKAuthenticator", PropertyType.CLASSNAME,
"The authenticator class that accumulo will use to determine if a user has privilege to perform an action"),
INSTANCE_SECURITY_AUTHORIZOR("instance.security.authorizor", "org.apache.accumulo.server.security.handler.ZKAuthorizor", PropertyType.CLASSNAME,
"The authorizor class that accumulo will use to determine what labels a user has privilege to see"),
INSTANCE_SECURITY_PERMISSION_HANDLER("instance.security.permissionHandler", "org.apache.accumulo.server.security.handler.ZKPermHandler",
PropertyType.CLASSNAME, "The permission handler class that accumulo will use to determine if a user has privilege to perform an action"),
INSTANCE_RPC_SSL_ENABLED("instance.rpc.ssl.enabled", "false", PropertyType.BOOLEAN,
"Use SSL for socket connections from clients and among accumulo services. Mutually exclusive with SASL RPC configuration."),
INSTANCE_RPC_SSL_CLIENT_AUTH("instance.rpc.ssl.clientAuth", "false", PropertyType.BOOLEAN, "Require clients to present certs signed by a trusted root"),
/**
* @since 1.7.0
*/
INSTANCE_RPC_SASL_ENABLED("instance.rpc.sasl.enabled", "false", PropertyType.BOOLEAN,
"Configures Thrift RPCs to require SASL with GSSAPI which supports Kerberos authentication. Mutually exclusive with SSL RPC configuration."),
INSTANCE_RPC_SASL_PROXYUSERS("instance.rpc.sasl.impersonation.", null, PropertyType.PREFIX,
"Prefix that allows configuration of users that are allowed to impersonate other users"),
// general properties
GENERAL_PREFIX("general.", null, PropertyType.PREFIX,
"Properties in this category affect the behavior of accumulo overall, but do not have to be consistent throughout a cloud."),
GENERAL_CLASSPATHS(AccumuloClassLoader.CLASSPATH_PROPERTY_NAME, AccumuloClassLoader.ACCUMULO_CLASSPATH_VALUE, PropertyType.STRING,
"A list of all of the places to look for a class. Order does matter, as it will look for the jar "
+ "starting in the first location to the last. Please note, hadoop conf and hadoop lib directories NEED to be here, "
+ "along with accumulo lib and zookeeper directory. Supports full regex on filename alone."), // needs special treatment in accumulo start jar
GENERAL_DYNAMIC_CLASSPATHS(AccumuloVFSClassLoader.DYNAMIC_CLASSPATH_PROPERTY_NAME, AccumuloVFSClassLoader.DEFAULT_DYNAMIC_CLASSPATH_VALUE,
PropertyType.STRING, "A list of all of the places where changes in jars or classes will force a reload of the classloader."),
GENERAL_RPC_TIMEOUT("general.rpc.timeout", "120s", PropertyType.TIMEDURATION, "Time to wait on I/O for simple, short RPC calls"),
@Experimental
GENERAL_RPC_SERVER_TYPE("general.rpc.server.type", "", PropertyType.STRING,
"Type of Thrift server to instantiate, see org.apache.accumulo.server.rpc.ThriftServerType for more information. Only useful for benchmarking thrift servers"),
GENERAL_KERBEROS_KEYTAB("general.kerberos.keytab", "", PropertyType.PATH, "Path to the kerberos keytab to use. Leave blank if not using kerberoized hdfs"),
GENERAL_KERBEROS_PRINCIPAL("general.kerberos.principal", "", PropertyType.STRING, "Name of the kerberos principal to use. _HOST will automatically be "
+ "replaced by the machines hostname in the hostname portion of the principal. Leave blank if not using kerberoized hdfs"),
GENERAL_MAX_MESSAGE_SIZE("general.server.message.size.max", "1G", PropertyType.MEMORY, "The maximum size of a message that can be sent to a server."),
GENERAL_SIMPLETIMER_THREADPOOL_SIZE("general.server.simpletimer.threadpool.size", "1", PropertyType.COUNT, "The number of threads to use for "
+ "server-internal scheduled tasks"),
// If you update the default type, be sure to update the default used for initialization failures in VolumeManagerImpl
@Experimental
GENERAL_VOLUME_CHOOSER("general.volume.chooser", "org.apache.accumulo.server.fs.PerTableVolumeChooser", PropertyType.CLASSNAME,
"The class that will be used to select which volume will be used to create new files."),
GENERAL_SECURITY_CREDENTIAL_PROVIDER_PATHS("general.security.credential.provider.paths", "", PropertyType.STRING,
"Comma-separated list of paths to CredentialProviders"),
GENERAL_LEGACY_METRICS("general.legacy.metrics", "false", PropertyType.BOOLEAN,
"Use the old metric infrastructure configured by accumulo-metrics.xml, instead of Hadoop Metrics2"),
GENERAL_DELEGATION_TOKEN_LIFETIME("general.delegation.token.lifetime", "7d", PropertyType.TIMEDURATION,
"The length of time that delegation tokens and secret keys are valid"),
GENERAL_DELEGATION_TOKEN_UPDATE_INTERVAL("general.delegation.token.update.interval", "1d", PropertyType.TIMEDURATION,
"The length of time between generation of new secret keys"),
// properties that are specific to master server behavior
MASTER_PREFIX("master.", null, PropertyType.PREFIX, "Properties in this category affect the behavior of the master server"),
MASTER_CLIENTPORT("master.port.client", "9999", PropertyType.PORT, "The port used for handling client connections on the master"),
MASTER_TABLET_BALANCER("master.tablet.balancer", "org.apache.accumulo.server.master.balancer.TableLoadBalancer", PropertyType.CLASSNAME,
"The balancer class that accumulo will use to make tablet assignment and migration decisions."),
MASTER_RECOVERY_MAXAGE("master.recovery.max.age", "60m", PropertyType.TIMEDURATION, "Recovery files older than this age will be removed."),
MASTER_RECOVERY_MAXTIME("master.recovery.time.max", "30m", PropertyType.TIMEDURATION, "The maximum time to attempt recovery before giving up"),
MASTER_BULK_RETRIES("master.bulk.retries", "3", PropertyType.COUNT, "The number of attempts to bulk-load a file before giving up."),
MASTER_BULK_THREADPOOL_SIZE("master.bulk.threadpool.size", "5", PropertyType.COUNT, "The number of threads to use when coordinating a bulk-import."),
MASTER_BULK_TIMEOUT("master.bulk.timeout", "5m", PropertyType.TIMEDURATION, "The time to wait for a tablet server to process a bulk import request"),
MASTER_BULK_RENAME_THREADS("master.bulk.rename.threadpool.size", "20", PropertyType.COUNT,
"The number of threads to use when moving user files to bulk ingest directories under accumulo control"),
MASTER_MINTHREADS("master.server.threads.minimum", "20", PropertyType.COUNT, "The minimum number of threads to use to handle incoming requests."),
MASTER_THREADCHECK("master.server.threadcheck.time", "1s", PropertyType.TIMEDURATION, "The time between adjustments of the server thread pool."),
MASTER_RECOVERY_DELAY("master.recovery.delay", "10s", PropertyType.TIMEDURATION,
"When a tablet server's lock is deleted, it takes time for it to completely quit. This delay gives it time before log recoveries begin."),
MASTER_LEASE_RECOVERY_WAITING_PERIOD("master.lease.recovery.interval", "5s", PropertyType.TIMEDURATION,
"The amount of time to wait after requesting a WAL file to be recovered"),
MASTER_WALOG_CLOSER_IMPLEMETATION("master.walog.closer.implementation", "org.apache.accumulo.server.master.recovery.HadoopLogCloser", PropertyType.CLASSNAME,
"A class that implements a mechansim to steal write access to a file"),
MASTER_FATE_THREADPOOL_SIZE("master.fate.threadpool.size", "4", PropertyType.COUNT,
"The number of threads used to run FAult-Tolerant Executions. These are primarily table operations like merge."),
MASTER_REPLICATION_SCAN_INTERVAL("master.replication.status.scan.interval", "30s", PropertyType.TIMEDURATION,
"Amount of time to sleep before scanning the status section of the replication table for new data"),
MASTER_REPLICATION_COORDINATOR_PORT("master.replication.coordinator.port", "10001", PropertyType.PORT, "Port for the replication coordinator service"),
MASTER_REPLICATION_COORDINATOR_MINTHREADS("master.replication.coordinator.minthreads", "4", PropertyType.COUNT,
"Minimum number of threads dedicated to answering coordinator requests"),
MASTER_REPLICATION_COORDINATOR_THREADCHECK("master.replication.coordinator.threadcheck.time", "5s", PropertyType.TIMEDURATION,
"The time between adjustments of the coordinator thread pool"),
// properties that are specific to tablet server behavior
TSERV_PREFIX("tserver.", null, PropertyType.PREFIX, "Properties in this category affect the behavior of the tablet servers"),
TSERV_CLIENT_TIMEOUT("tserver.client.timeout", "3s", PropertyType.TIMEDURATION, "Time to wait for clients to continue scans before closing a session."),
TSERV_DEFAULT_BLOCKSIZE("tserver.default.blocksize", "1M", PropertyType.MEMORY, "Specifies a default blocksize for the tserver caches"),
TSERV_DATACACHE_SIZE("tserver.cache.data.size", "128M", PropertyType.MEMORY, "Specifies the size of the cache for file data blocks."),
TSERV_INDEXCACHE_SIZE("tserver.cache.index.size", "512M", PropertyType.MEMORY, "Specifies the size of the cache for file indices."),
TSERV_PORTSEARCH("tserver.port.search", "false", PropertyType.BOOLEAN, "if the ports above are in use, search higher ports until one is available"),
TSERV_CLIENTPORT("tserver.port.client", "9997", PropertyType.PORT, "The port used for handling client connections on the tablet servers"),
@Deprecated
TSERV_MUTATION_QUEUE_MAX("tserver.mutation.queue.max", "1M", PropertyType.MEMORY, "This setting is deprecated. See tserver.total.mutation.queue.max. "
+ "The amount of memory to use to store write-ahead-log mutations-per-session before flushing them. Since the buffer is per write session, consider the"
+ " max number of concurrent writer when configuring. When using Hadoop 2, Accumulo will call hsync() on the WAL . For a small number of "
+ "concurrent writers, increasing this buffer size decreases the frequncy of hsync calls. For a large number of concurrent writers a small buffers "
+ "size is ok because of group commit."),
TSERV_TOTAL_MUTATION_QUEUE_MAX("tserver.total.mutation.queue.max", "50M", PropertyType.MEMORY,
"The amount of memory used to store write-ahead-log mutations before flushing them."),
TSERV_TABLET_SPLIT_FINDMIDPOINT_MAXOPEN("tserver.tablet.split.midpoint.files.max", "30", PropertyType.COUNT,
"To find a tablets split points, all index files are opened. This setting determines how many index "
+ "files can be opened at once. When there are more index files than this setting multiple passes "
+ "must be made, which is slower. However opening too many files at once can cause problems."),
TSERV_WALOG_MAX_SIZE("tserver.walog.max.size", "1G", PropertyType.MEMORY,
"The maximum size for each write-ahead log. See comment for property tserver.memory.maps.max"),
TSERV_WALOG_TOLERATED_CREATION_FAILURES("tserver.walog.tolerated.creation.failures", "50", PropertyType.COUNT,
"The maximum number of failures tolerated when creating a new WAL file within the period specified by tserver.walog.failures.period."
+ " Exceeding this number of failures in the period causes the TabletServer to exit."),
TSERV_WALOG_TOLERATED_WAIT_INCREMENT("tserver.walog.tolerated.wait.increment", "1000ms", PropertyType.TIMEDURATION,
"The amount of time to wait between failures to create a WALog."),
// Never wait longer than 5 mins for a retry
TSERV_WALOG_TOLERATED_MAXIMUM_WAIT_DURATION("tserver.walog.maximum.wait.duration", "5m", PropertyType.TIMEDURATION,
"The maximum amount of time to wait after a failure to create a WAL file."),
TSERV_MAJC_DELAY("tserver.compaction.major.delay", "30s", PropertyType.TIMEDURATION,
"Time a tablet server will sleep between checking which tablets need compaction."),
TSERV_MAJC_THREAD_MAXOPEN("tserver.compaction.major.thread.files.open.max", "10", PropertyType.COUNT,
"Max number of files a major compaction thread can open at once. "),
TSERV_SCAN_MAX_OPENFILES("tserver.scan.files.open.max", "100", PropertyType.COUNT,
"Maximum total files that all tablets in a tablet server can open for scans. "),
TSERV_MAX_IDLE("tserver.files.open.idle", "1m", PropertyType.TIMEDURATION, "Tablet servers leave previously used files open for future queries. "
+ "This setting determines how much time an unused file should be kept open until it is closed."),
TSERV_NATIVEMAP_ENABLED("tserver.memory.maps.native.enabled", "true", PropertyType.BOOLEAN,
"An in-memory data store for accumulo implemented in c++ that increases the amount of data accumulo can hold in memory and avoids Java GC pauses."),
TSERV_MAXMEM("tserver.memory.maps.max", "1G", PropertyType.MEMORY,
"Maximum amount of memory that can be used to buffer data written to a tablet server. There are two other properties that can effectively limit memory"
+ " usage table.compaction.minor.logs.threshold and tserver.walog.max.size. Ensure that table.compaction.minor.logs.threshold *"
+ " tserver.walog.max.size >= this property."),
TSERV_MEM_MGMT("tserver.memory.manager", "org.apache.accumulo.server.tabletserver.LargestFirstMemoryManager", PropertyType.CLASSNAME,
"An implementation of MemoryManger that accumulo will use."),
TSERV_SESSION_MAXIDLE("tserver.session.idle.max", "1m", PropertyType.TIMEDURATION, "maximum idle time for a session"),
TSERV_READ_AHEAD_MAXCONCURRENT("tserver.readahead.concurrent.max", "16", PropertyType.COUNT,
"The maximum number of concurrent read ahead that will execute. This effectively"
+ " limits the number of long running scans that can run concurrently per tserver."),
TSERV_METADATA_READ_AHEAD_MAXCONCURRENT("tserver.metadata.readahead.concurrent.max", "8", PropertyType.COUNT,
"The maximum number of concurrent metadata read ahead that will execute."),
TSERV_MIGRATE_MAXCONCURRENT("tserver.migrations.concurrent.max", "1", PropertyType.COUNT,
"The maximum number of concurrent tablet migrations for a tablet server"),
TSERV_MAJC_MAXCONCURRENT("tserver.compaction.major.concurrent.max", "3", PropertyType.COUNT,
"The maximum number of concurrent major compactions for a tablet server"),
TSERV_MINC_MAXCONCURRENT("tserver.compaction.minor.concurrent.max", "4", PropertyType.COUNT,
"The maximum number of concurrent minor compactions for a tablet server"),
TSERV_MAJC_TRACE_PERCENT("tserver.compaction.major.trace.percent", "0.1", PropertyType.FRACTION, "The percent of major compactions to trace"),
TSERV_MINC_TRACE_PERCENT("tserver.compaction.minor.trace.percent", "0.1", PropertyType.FRACTION, "The percent of minor compactions to trace"),
TSERV_COMPACTION_WARN_TIME("tserver.compaction.warn.time", "10m", PropertyType.TIMEDURATION,
"When a compaction has not made progress for this time period, a warning will be logged"),
TSERV_BLOOM_LOAD_MAXCONCURRENT("tserver.bloom.load.concurrent.max", "4", PropertyType.COUNT,
"The number of concurrent threads that will load bloom filters in the background. "
+ "Setting this to zero will make bloom filters load in the foreground."),
TSERV_MONITOR_FS("tserver.monitor.fs", "true", PropertyType.BOOLEAN,
"When enabled the tserver will monitor file systems and kill itself when one switches from rw to ro. This is usually and indication that Linux has"
+ " detected a bad disk."),
TSERV_MEMDUMP_DIR("tserver.dir.memdump", "/tmp", PropertyType.PATH,
"A long running scan could possibly hold memory that has been minor compacted. To prevent this, the in memory map is dumped to a local file and the "
+ "scan is switched to that local file. We can not switch to the minor compacted file because it may have been modified by iterators. The file "
+ "dumped to the local dir is an exact copy of what was in memory."),
TSERV_BULK_PROCESS_THREADS("tserver.bulk.process.threads", "1", PropertyType.COUNT,
"The master will task a tablet server with pre-processing a bulk file prior to assigning it to the appropriate tablet servers. This configuration"
+ " value controls the number of threads used to process the files."),
TSERV_BULK_ASSIGNMENT_THREADS("tserver.bulk.assign.threads", "1", PropertyType.COUNT,
"The master delegates bulk file processing and assignment to tablet servers. After the bulk file has been processed, the tablet server will assign"
+ " the file to the appropriate tablets on all servers. This property controls the number of threads used to communicate to the other servers."),
TSERV_BULK_RETRY("tserver.bulk.retry.max", "5", PropertyType.COUNT,
"The number of times the tablet server will attempt to assign a file to a tablet as it migrates and splits."),
TSERV_BULK_TIMEOUT("tserver.bulk.timeout", "5m", PropertyType.TIMEDURATION, "The time to wait for a tablet server to process a bulk import request."),
TSERV_MINTHREADS("tserver.server.threads.minimum", "20", PropertyType.COUNT, "The minimum number of threads to use to handle incoming requests."),
TSERV_THREADCHECK("tserver.server.threadcheck.time", "1s", PropertyType.TIMEDURATION, "The time between adjustments of the server thread pool."),
TSERV_MAX_MESSAGE_SIZE("tserver.server.message.size.max", "1G", PropertyType.MEMORY, "The maximum size of a message that can be sent to a tablet server."),
TSERV_HOLD_TIME_SUICIDE("tserver.hold.time.max", "5m", PropertyType.TIMEDURATION,
"The maximum time for a tablet server to be in the \"memory full\" state. If the tablet server cannot write out memory"
+ " in this much time, it will assume there is some failure local to its node, and quit. A value of zero is equivalent to forever."),
TSERV_WAL_BLOCKSIZE("tserver.wal.blocksize", "0", PropertyType.MEMORY,
"The size of the HDFS blocks used to write to the Write-Ahead log. If zero, it will be 110% of tserver.walog.max.size (that is, try to use just one"
+ " block)"),
TSERV_WAL_REPLICATION("tserver.wal.replication", "0", PropertyType.COUNT,
"The replication to use when writing the Write-Ahead log to HDFS. If zero, it will use the HDFS default replication setting."),
TSERV_RECOVERY_MAX_CONCURRENT("tserver.recovery.concurrent.max", "2", PropertyType.COUNT, "The maximum number of threads to use to sort logs during"
+ " recovery"),
TSERV_SORT_BUFFER_SIZE("tserver.sort.buffer.size", "200M", PropertyType.MEMORY, "The amount of memory to use when sorting logs during recovery."),
TSERV_ARCHIVE_WALOGS("tserver.archive.walogs", "false", PropertyType.BOOLEAN, "Keep copies of the WALOGs for debugging purposes"),
TSERV_WORKQ_THREADS("tserver.workq.threads", "2", PropertyType.COUNT,
"The number of threads for the distributed work queue. These threads are used for copying failed bulk files."),
TSERV_WAL_SYNC("tserver.wal.sync", "true", PropertyType.BOOLEAN,
"Use the SYNC_BLOCK create flag to sync WAL writes to disk. Prevents problems recovering from sudden system resets."),
@Deprecated
TSERV_WAL_SYNC_METHOD("tserver.wal.sync.method", "hsync", PropertyType.STRING, "This property is deprecated. Use table.durability instead."),
TSERV_ASSIGNMENT_DURATION_WARNING("tserver.assignment.duration.warning", "10m", PropertyType.TIMEDURATION, "The amount of time an assignment can run "
+ " before the server will print a warning along with the current stack trace. Meant to help debug stuck assignments"),
TSERV_REPLICATION_REPLAYERS("tserver.replication.replayer.", null, PropertyType.PREFIX,
"Allows configuration of implementation used to apply replicated data"),
TSERV_REPLICATION_DEFAULT_HANDLER("tserver.replication.default.replayer", "org.apache.accumulo.tserver.replication.BatchWriterReplicationReplayer",
PropertyType.CLASSNAME, "Default AccumuloReplicationReplayer implementation"),
TSERV_REPLICATION_BW_REPLAYER_MEMORY("tserver.replication.batchwriter.replayer.memory", "50M", PropertyType.MEMORY,
"Memory to provide to batchwriter to replay mutations for replication"),
TSERV_ASSIGNMENT_MAXCONCURRENT("tserver.assignment.concurrent.max", "2", PropertyType.COUNT,
"The number of threads available to load tablets. Recoveries are still performed serially."),
// properties that are specific to logger server behavior
LOGGER_PREFIX("logger.", null, PropertyType.PREFIX, "Properties in this category affect the behavior of the write-ahead logger servers"),
LOGGER_DIR("logger.dir.walog", "walogs", PropertyType.PATH, "This property is only needed if Accumulo was upgraded from a 1.4 or earlier version. "
+ "In the upgrade to 1.5 this property is used to copy any earlier write ahead logs into DFS. "
+ "In 1.6+, this property is used by the LocalWALRecovery utility in the event that something went wrong with that earlier upgrade. "
+ "It is possible to specify a comma-separated list of directories."),
// accumulo garbage collector properties
GC_PREFIX("gc.", null, PropertyType.PREFIX, "Properties in this category affect the behavior of the accumulo garbage collector."),
GC_CYCLE_START("gc.cycle.start", "30s", PropertyType.TIMEDURATION, "Time to wait before attempting to garbage collect any old files."),
GC_CYCLE_DELAY("gc.cycle.delay", "5m", PropertyType.TIMEDURATION, "Time between garbage collection cycles. In each cycle, old files "
+ "no longer in use are removed from the filesystem."),
GC_PORT("gc.port.client", "50091", PropertyType.PORT, "The listening port for the garbage collector's monitor service"),
GC_DELETE_THREADS("gc.threads.delete", "16", PropertyType.COUNT, "The number of threads used to delete files"),
GC_TRASH_IGNORE("gc.trash.ignore", "false", PropertyType.BOOLEAN, "Do not use the Trash, even if it is configured"),
GC_FILE_ARCHIVE("gc.file.archive", "false", PropertyType.BOOLEAN, "Archive any files/directories instead of moving to the HDFS trash or deleting"),
GC_TRACE_PERCENT("gc.trace.percent", "0.01", PropertyType.FRACTION, "Percent of gc cycles to trace"),
// properties that are specific to the monitor server behavior
MONITOR_PREFIX("monitor.", null, PropertyType.PREFIX, "Properties in this category affect the behavior of the monitor web server."),
MONITOR_PORT("monitor.port.client", "50095", PropertyType.PORT, "The listening port for the monitor's http service"),
MONITOR_LOG4J_PORT("monitor.port.log4j", "4560", PropertyType.PORT, "The listening port for the monitor's log4j logging collection."),
MONITOR_BANNER_TEXT("monitor.banner.text", "", PropertyType.STRING, "The banner text displayed on the monitor page."),
MONITOR_BANNER_COLOR("monitor.banner.color", "#c4c4c4", PropertyType.STRING, "The color of the banner text displayed on the monitor page."),
MONITOR_BANNER_BACKGROUND("monitor.banner.background", "#304065", PropertyType.STRING,
"The background color of the banner text displayed on the monitor page."),
MONITOR_SSL_KEYSTORE("monitor.ssl.keyStore", "", PropertyType.PATH, "The keystore for enabling monitor SSL."),
@Sensitive
MONITOR_SSL_KEYSTOREPASS("monitor.ssl.keyStorePassword", "", PropertyType.STRING, "The keystore password for enabling monitor SSL."),
MONITOR_SSL_KEYSTORETYPE("monitor.ssl.keyStoreType", "", PropertyType.STRING, "Type of SSL keystore"),
MONITOR_SSL_TRUSTSTORE("monitor.ssl.trustStore", "", PropertyType.PATH, "The truststore for enabling monitor SSL."),
@Sensitive
MONITOR_SSL_TRUSTSTOREPASS("monitor.ssl.trustStorePassword", "", PropertyType.STRING, "The truststore password for enabling monitor SSL."),
MONITOR_SSL_TRUSTSTORETYPE("monitor.ssl.trustStoreType", "", PropertyType.STRING, "Type of SSL truststore"),
MONITOR_SSL_INCLUDE_CIPHERS("monitor.ssl.include.ciphers", "", PropertyType.STRING,
"A comma-separated list of allows SSL Ciphers, see monitor.ssl.exclude.ciphers to disallow ciphers"),
MONITOR_SSL_EXCLUDE_CIPHERS("monitor.ssl.exclude.ciphers", "", PropertyType.STRING,
"A comma-separated list of disallowed SSL Ciphers, see mmonitor.ssl.include.ciphers to allow ciphers"),
MONITOR_SSL_INCLUDE_PROTOCOLS("monitor.ssl.include.protocols", "TLSv1,TLSv1.1,TLSv1.2", PropertyType.STRING, "A comma-separate list of allowed SSL protocols"),
MONITOR_LOCK_CHECK_INTERVAL("monitor.lock.check.interval", "5s", PropertyType.TIMEDURATION,
"The amount of time to sleep between checking for the Montior ZooKeeper lock"),
MONITOR_LOG_DATE_FORMAT("monitor.log.date.format", "yyyy/MM/dd HH:mm:ss,SSS", PropertyType.STRING, "The SimpleDateFormat string used to configure "
+ "the date shown on the 'Recent Logs' monitor page"),
TRACE_PREFIX("trace.", null, PropertyType.PREFIX, "Properties in this category affect the behavior of distributed tracing."),
TRACE_SPAN_RECEIVERS("trace.span.receivers", "org.apache.accumulo.tracer.ZooTraceClient", PropertyType.CLASSNAMELIST,
"A list of span receiver classes to send trace spans"),
TRACE_SPAN_RECEIVER_PREFIX("trace.span.receiver.", null, PropertyType.PREFIX, "Prefix for span receiver configuration properties"),
TRACE_ZK_PATH("trace.zookeeper.path", Constants.ZTRACERS, PropertyType.STRING, "The zookeeper node where tracers are registered"),
TRACE_PORT("trace.port.client", "12234", PropertyType.PORT, "The listening port for the trace server"),
TRACE_TABLE("trace.table", "trace", PropertyType.STRING, "The name of the table to store distributed traces"),
TRACE_USER("trace.user", "root", PropertyType.STRING, "The name of the user to store distributed traces"),
@Sensitive
TRACE_PASSWORD("trace.password", "secret", PropertyType.STRING, "The password for the user used to store distributed traces"),
@Sensitive
TRACE_TOKEN_PROPERTY_PREFIX("trace.token.property.", null, PropertyType.PREFIX,
"The prefix used to create a token for storing distributed traces. For each propetry required by trace.token.type, place this prefix in front of it."),
TRACE_TOKEN_TYPE("trace.token.type", PasswordToken.class.getName(), PropertyType.CLASSNAME, "An AuthenticationToken type supported by the authorizer"),
// per table properties
TABLE_PREFIX("table.", null, PropertyType.PREFIX, "Properties in this category affect tablet server treatment of tablets, but can be configured "
+ "on a per-table basis. Setting these properties in the site file will override the default globally "
+ "for all tables and not any specific table. However, both the default and the global setting can be "
+ "overridden per table using the table operations API or in the shell, which sets the overridden value "
+ "in zookeeper. Restarting accumulo tablet servers after setting these properties in the site file "
+ "will cause the global setting to take effect. However, you must use the API or the shell to change "
+ "properties in zookeeper that are set on a table."),
TABLE_ARBITRARY_PROP_PREFIX("table.custom.", null, PropertyType.PREFIX, "Prefix to be used for user defined arbitrary properties."),
TABLE_MAJC_RATIO("table.compaction.major.ratio", "3", PropertyType.FRACTION,
"minimum ratio of total input size to maximum input file size for running a major compactionWhen adjusting this property you may want to also "
+ "adjust table.file.max. Want to avoid the situation where only merging minor compactions occur."),
TABLE_MAJC_COMPACTALL_IDLETIME("table.compaction.major.everything.idle", "1h", PropertyType.TIMEDURATION,
"After a tablet has been idle (no mutations) for this time period it may have all "
+ "of its files compacted into one. There is no guarantee an idle tablet will be compacted. "
+ "Compactions of idle tablets are only started when regular compactions are not running. Idle "
+ "compactions only take place for tablets that have one or more files."),
TABLE_SPLIT_THRESHOLD("table.split.threshold", "1G", PropertyType.MEMORY, "When combined size of files exceeds this amount a tablet is split."),
TABLE_MAX_END_ROW_SIZE("table.split.endrow.size.max", "10K", PropertyType.MEMORY, "Maximum size of end row"),
TABLE_MINC_LOGS_MAX("table.compaction.minor.logs.threshold", "3", PropertyType.COUNT,
"When there are more than this many write-ahead logs against a tablet, it will be minor compacted. See comment for property tserver.memory.maps.max"),
TABLE_MINC_COMPACT_IDLETIME("table.compaction.minor.idle", "5m", PropertyType.TIMEDURATION,
"After a tablet has been idle (no mutations) for this time period it may have its "
+ "in-memory map flushed to disk in a minor compaction. There is no guarantee an idle " + "tablet will be compacted."),
TABLE_SCAN_MAXMEM("table.scan.max.memory", "512K", PropertyType.MEMORY,
"The maximum amount of memory that will be used to cache results of a client query/scan. "
+ "Once this limit is reached, the buffered data is sent to the client."),
TABLE_FILE_TYPE("table.file.type", RFile.EXTENSION, PropertyType.STRING, "Change the type of file a table writes"),
TABLE_LOAD_BALANCER("table.balancer", "org.apache.accumulo.server.master.balancer.DefaultLoadBalancer", PropertyType.STRING,
"This property can be set to allow the LoadBalanceByTable load balancer to change the called Load Balancer for this table"),
TABLE_FILE_COMPRESSION_TYPE("table.file.compress.type", "gz", PropertyType.STRING, "One of gz,lzo,none"),
TABLE_FILE_COMPRESSED_BLOCK_SIZE("table.file.compress.blocksize", "100K", PropertyType.MEMORY,
"Similar to the hadoop io.seqfile.compress.blocksize setting, so that files have better query performance. The maximum value for this is "
+ Integer.MAX_VALUE + ". (This setting is the size threshold prior to compression, and applies even compression is disabled.)"),
TABLE_FILE_COMPRESSED_BLOCK_SIZE_INDEX("table.file.compress.blocksize.index", "128K", PropertyType.MEMORY,
"Determines how large index blocks can be in files that support multilevel indexes. The maximum value for this is " + Integer.MAX_VALUE + "."
+ " (This setting is the size threshold prior to compression, and applies even compression is disabled.)"),
TABLE_FILE_BLOCK_SIZE("table.file.blocksize", "0B", PropertyType.MEMORY,
"Overrides the hadoop dfs.block.size setting so that files have better query performance. The maximum value for this is " + Integer.MAX_VALUE),
TABLE_FILE_REPLICATION("table.file.replication", "0", PropertyType.COUNT, "Determines how many replicas to keep of a tables' files in HDFS. "
+ "When this value is LTE 0, HDFS defaults are used."),
TABLE_FILE_MAX("table.file.max", "15", PropertyType.COUNT,
"Determines the max # of files each tablet in a table can have. When adjusting this property you may want to consider adjusting"
+ " table.compaction.major.ratio also. Setting this property to 0 will make it default to tserver.scan.files.open.max-1, this will prevent a"
+ " tablet from having more files than can be opened. Setting this property low may throttle ingest and increase query performance."),
@Deprecated
TABLE_WALOG_ENABLED("table.walog.enabled", "true", PropertyType.BOOLEAN, "This setting is deprecated. Use table.durability=none instead."),
TABLE_BLOOM_ENABLED("table.bloom.enabled", "false", PropertyType.BOOLEAN, "Use bloom filters on this table."),
TABLE_BLOOM_LOAD_THRESHOLD("table.bloom.load.threshold", "1", PropertyType.COUNT,
"This number of seeks that would actually use a bloom filter must occur before a file's bloom filter is loaded."
+ " Set this to zero to initiate loading of bloom filters when a file is opened."),
TABLE_BLOOM_SIZE("table.bloom.size", "1048576", PropertyType.COUNT, "Bloom filter size, as number of keys."),
TABLE_BLOOM_ERRORRATE("table.bloom.error.rate", "0.5%", PropertyType.FRACTION, "Bloom filter error rate."),
TABLE_BLOOM_KEY_FUNCTOR("table.bloom.key.functor", "org.apache.accumulo.core.file.keyfunctor.RowFunctor", PropertyType.CLASSNAME,
"A function that can transform the key prior to insertion and check of bloom filter. org.apache.accumulo.core.file.keyfunctor.RowFunctor,"
+ ",org.apache.accumulo.core.file.keyfunctor.ColumnFamilyFunctor, and org.apache.accumulo.core.file.keyfunctor.ColumnQualifierFunctor are"
+ " allowable values. One can extend any of the above mentioned classes to perform specialized parsing of the key. "),
TABLE_BLOOM_HASHTYPE("table.bloom.hash.type", "murmur", PropertyType.STRING, "The bloom filter hash type"),
TABLE_DURABILITY("table.durability", "sync", PropertyType.DURABILITY, "The durability used to write to the write-ahead log."
+ " Legal values are: none, which skips the write-ahead log; "
+ "log, which sends the data to the write-ahead log, but does nothing to make it durable; " + "flush, which pushes data to the file system; and "
+ "sync, which ensures the data is written to disk."),
TABLE_FAILURES_IGNORE("table.failures.ignore", "false", PropertyType.BOOLEAN,
"If you want queries for your table to hang or fail when data is missing from the system, "
+ "then set this to false. When this set to true missing data will be reported but queries "
+ "will still run possibly returning a subset of the data."),
TABLE_DEFAULT_SCANTIME_VISIBILITY("table.security.scan.visibility.default", "", PropertyType.STRING,
"The security label that will be assumed at scan time if an entry does not have a visibility set.\n"
+ "Note: An empty security label is displayed as []. The scan results will show an empty visibility even if "
+ "the visibility from this setting is applied to the entry.\n"
+ "CAUTION: If a particular key has an empty security label AND its table's default visibility is also empty, "
+ "access will ALWAYS be granted for users with permission to that table. Additionally, if this field is changed, "
+ "all existing data with an empty visibility label will be interpreted with the new label on the next scan."),
TABLE_LOCALITY_GROUPS("table.groups.enabled", "", PropertyType.STRING, "A comma separated list of locality group names to enable for this table."),
TABLE_CONSTRAINT_PREFIX("table.constraint.", null, PropertyType.PREFIX,
"Properties in this category are per-table properties that add constraints to a table. "
+ "These properties start with the category prefix, followed by a number, and their values "
+ "correspond to a fully qualified Java class that implements the Constraint interface.\n"
+ "For example:\ntable.constraint.1 = org.apache.accumulo.core.constraints.MyCustomConstraint\n"
+ "and:\ntable.constraint.2 = my.package.constraints.MySecondConstraint"),
TABLE_INDEXCACHE_ENABLED("table.cache.index.enable", "true", PropertyType.BOOLEAN, "Determines whether index cache is enabled."),
TABLE_BLOCKCACHE_ENABLED("table.cache.block.enable", "false", PropertyType.BOOLEAN, "Determines whether file block cache is enabled."),
TABLE_ITERATOR_PREFIX("table.iterator.", null, PropertyType.PREFIX,
"Properties in this category specify iterators that are applied at various stages (scopes) of interaction "
+ "with a table. These properties start with the category prefix, followed by a scope (minc, majc, scan, etc.), "
+ "followed by a period, followed by a name, as in table.iterator.scan.vers, or table.iterator.scan.custom. "
+ "The values for these properties are a number indicating the ordering in which it is applied, and a class name "
+ "such as:\n table.iterator.scan.vers = 10,org.apache.accumulo.core.iterators.VersioningIterator\n "
+ "These iterators can take options if additional properties are set that look like this property, "
+ "but are suffixed with a period, followed by 'opt' followed by another period, and a property name.\n"
+ "For example, table.iterator.minc.vers.opt.maxVersions = 3"),
TABLE_ITERATOR_SCAN_PREFIX(TABLE_ITERATOR_PREFIX.getKey() + IteratorScope.scan.name() + ".", null, PropertyType.PREFIX,
"Convenience prefix to find options for the scan iterator scope"),
TABLE_ITERATOR_MINC_PREFIX(TABLE_ITERATOR_PREFIX.getKey() + IteratorScope.minc.name() + ".", null, PropertyType.PREFIX,
"Convenience prefix to find options for the minc iterator scope"),
TABLE_ITERATOR_MAJC_PREFIX(TABLE_ITERATOR_PREFIX.getKey() + IteratorScope.majc.name() + ".", null, PropertyType.PREFIX,
"Convenience prefix to find options for the majc iterator scope"),
TABLE_LOCALITY_GROUP_PREFIX("table.group.", null, PropertyType.PREFIX,
"Properties in this category are per-table properties that define locality groups in a table. These properties start "
+ "with the category prefix, followed by a name, followed by a period, and followed by a property for that group.\n"
+ "For example table.group.group1=x,y,z sets the column families for a group called group1. Once configured, "
+ "group1 can be enabled by adding it to the list of groups in the " + TABLE_LOCALITY_GROUPS.getKey() + " property.\n"
+ "Additional group options may be specified for a named group by setting table.group.<name>.opt.<key>=<value>."),
TABLE_FORMATTER_CLASS("table.formatter", DefaultFormatter.class.getName(), PropertyType.STRING, "The Formatter class to apply on results in the shell"),
TABLE_INTERPRETER_CLASS("table.interepreter", DefaultScanInterpreter.class.getName(), PropertyType.STRING,
"The ScanInterpreter class to apply on scan arguments in the shell"),
TABLE_CLASSPATH("table.classpath.context", "", PropertyType.STRING, "Per table classpath context"),
TABLE_COMPACTION_STRATEGY("table.majc.compaction.strategy", "org.apache.accumulo.tserver.compaction.DefaultCompactionStrategy", PropertyType.CLASSNAME,
"A customizable major compaction strategy."),
TABLE_COMPACTION_STRATEGY_PREFIX("table.majc.compaction.strategy.opts.", null, PropertyType.PREFIX,
"Properties in this category are used to configure the compaction strategy."),
TABLE_REPLICATION("table.replication", "false", PropertyType.BOOLEAN, "Is replication enabled for the given table"),
TABLE_REPLICATION_TARGET("table.replication.target.", null, PropertyType.PREFIX, "Enumerate a mapping of other systems which this table should "
+ "replicate their data to. The key suffix is the identifying cluster name and the value is an identifier for a location on the target system, "
+ "e.g. the ID of the table on the target to replicate to"),
@Experimental
TABLE_VOLUME_CHOOSER("table.volume.chooser", "org.apache.accumulo.server.fs.RandomVolumeChooser", PropertyType.CLASSNAME,
"The class that will be used to select which volume will be used to create new files for this table."),
// VFS ClassLoader properties
VFS_CLASSLOADER_SYSTEM_CLASSPATH_PROPERTY(AccumuloVFSClassLoader.VFS_CLASSLOADER_SYSTEM_CLASSPATH_PROPERTY, "", PropertyType.STRING,
"Configuration for a system level vfs classloader. Accumulo jar can be configured here and loaded out of HDFS."),
VFS_CONTEXT_CLASSPATH_PROPERTY(AccumuloVFSClassLoader.VFS_CONTEXT_CLASSPATH_PROPERTY, null, PropertyType.PREFIX,
"Properties in this category are define a classpath. These properties start with the category prefix, followed by a context name. "
+ "The value is a comma seperated list of URIs. Supports full regex on filename alone. For example, "
+ "general.vfs.context.classpath.cx1=hdfs://nn1:9902/mylibdir/*.jar. "
+ "You can enable post delegation for a context, which will load classes from the context first instead of the parent first. "
+ "Do this by setting general.vfs.context.classpath.<name>.delegation=post, where <name> is your context name"
+ "If delegation is not specified, it defaults to loading from parent classloader first."),
@Interpolated
VFS_CLASSLOADER_CACHE_DIR(AccumuloVFSClassLoader.VFS_CACHE_DIR, "${java.io.tmpdir}" + File.separator + "accumulo-vfs-cache-${user.name}",
PropertyType.ABSOLUTEPATH, "Directory to use for the vfs cache. The cache will keep a soft reference to all of the classes loaded in the VM."
+ " This should be on local disk on each node with sufficient space. It defaults to ${java.io.tmpdir}/accumulo-vfs-cache-${user.name}"),
@Interpolated
@Experimental
GENERAL_MAVEN_PROJECT_BASEDIR(AccumuloClassLoader.MAVEN_PROJECT_BASEDIR_PROPERTY_NAME, AccumuloClassLoader.DEFAULT_MAVEN_PROJECT_BASEDIR_VALUE,
PropertyType.ABSOLUTEPATH, "Set this to automatically add maven target/classes directories to your dynamic classpath"),
// General properties for configuring replication
REPLICATION_PREFIX("replication.", null, PropertyType.PREFIX, "Properties in this category affect the replication of data to other Accumulo instances."),
REPLICATION_PEERS("replication.peer.", null, PropertyType.PREFIX, "Properties in this category control what systems data can be replicated to"),
REPLICATION_PEER_USER("replication.peer.user.", null, PropertyType.PREFIX, "The username to provide when authenticating with the given peer"),
@Sensitive
REPLICATION_PEER_PASSWORD("replication.peer.password.", null, PropertyType.PREFIX, "The password to provide when authenticating with the given peer"),
REPLICATION_PEER_KEYTAB("replication.peer.keytab.", null, PropertyType.PREFIX, "The keytab to use when authenticating with the given peer"),
REPLICATION_NAME("replication.name", "", PropertyType.STRING,
"Name of this cluster with respect to replication. Used to identify this instance from other peers"),
REPLICATION_MAX_WORK_QUEUE("replication.max.work.queue", "1000", PropertyType.COUNT, "Upper bound of the number of files queued for replication"),
REPLICATION_WORK_ASSIGNMENT_SLEEP("replication.work.assignment.sleep", "30s", PropertyType.TIMEDURATION,
"Amount of time to sleep between replication work assignment"),
REPLICATION_WORKER_THREADS("replication.worker.threads", "4", PropertyType.COUNT, "Size of the threadpool that each tabletserver devotes to replicating data"),
REPLICATION_RECEIPT_SERVICE_PORT("replication.receipt.service.port", "10002", PropertyType.PORT,
"Listen port used by thrift service in tserver listening for replication"),
REPLICATION_WORK_ATTEMPTS("replication.work.attempts", "10", PropertyType.COUNT,
"Number of attempts to try to replicate some data before giving up and letting it naturally be retried later"),
REPLICATION_MIN_THREADS("replication.receiver.min.threads", "1", PropertyType.COUNT, "Minimum number of threads for replication"),
REPLICATION_THREADCHECK("replication.receiver.threadcheck.time", "30s", PropertyType.TIMEDURATION,
"The time between adjustments of the replication thread pool."),
REPLICATION_MAX_UNIT_SIZE("replication.max.unit.size", "64M", PropertyType.MEMORY, "Maximum size of data to send in a replication message"),
REPLICATION_WORK_ASSIGNER("replication.work.assigner", "org.apache.accumulo.master.replication.UnorderedWorkAssigner", PropertyType.CLASSNAME,
"Replication WorkAssigner implementation to use"),
REPLICATION_DRIVER_DELAY("replication.driver.delay", "0s", PropertyType.TIMEDURATION,
"Amount of time to wait before the replication work loop begins in the master."),
REPLICATION_WORK_PROCESSOR_DELAY("replication.work.processor.delay", "0s", PropertyType.TIMEDURATION,
"Amount of time to wait before first checking for replication work, not useful outside of tests"),
REPLICATION_WORK_PROCESSOR_PERIOD("replication.work.processor.period", "0s", PropertyType.TIMEDURATION,
"Amount of time to wait before re-checking for replication work, not useful outside of tests"),
REPLICATION_TRACE_PERCENT("replication.trace.percent", "0.1", PropertyType.FRACTION, "The sampling percentage to use for replication traces"),
;
private String key, defaultValue, description;
private PropertyType type;
private static final Logger log = LoggerFactory.getLogger(Property.class);
private Property(String name, String defaultValue, PropertyType type, String description) {
this.key = name;
this.defaultValue = defaultValue;
this.description = description;
this.type = type;
}
@Override
public String toString() {
return this.key;
}
/**
* Gets the key (string) for this property.
*
* @return key
*/
public String getKey() {
return this.key;
}
/**
* Gets the default value for this property exactly as provided in its definition (i.e., without interpolation or conversion to absolute paths).
*
* @return raw default value
*/
public String getRawDefaultValue() {
return this.defaultValue;
}
/**
* Gets the default value for this property. System properties are interpolated into the value if necessary.
*
* @return default value
*/
public String getDefaultValue() {
String v;
if (isInterpolated()) {
PropertiesConfiguration pconf = new PropertiesConfiguration();
Properties systemProperties = System.getProperties();
synchronized (systemProperties) {
pconf.append(new MapConfiguration(systemProperties));
}
pconf.addProperty("hack_default_value", this.defaultValue);
v = pconf.getString("hack_default_value");
} else {
v = getRawDefaultValue();
}
if (this.type == PropertyType.ABSOLUTEPATH && !(v.trim().equals("")))
v = new File(v).getAbsolutePath();
return v;
}
/**
* Gets the type of this property.
*
* @return property type
*/
public PropertyType getType() {
return this.type;
}
/**
* Gets the description of this property.
*
* @return description
*/
public String getDescription() {
return this.description;
}
private boolean isInterpolated() {
return hasAnnotation(Interpolated.class) || hasPrefixWithAnnotation(getKey(), Interpolated.class);
}
/**
* Checks if this property is experimental.
*
* @return true if this property is experimental
*/
public boolean isExperimental() {
return hasAnnotation(Experimental.class) || hasPrefixWithAnnotation(getKey(), Experimental.class);
}
/**
* Checks if this property is deprecated.
*
* @return true if this property is deprecated
*/
public boolean isDeprecated() {
return hasAnnotation(Deprecated.class) || hasPrefixWithAnnotation(getKey(), Deprecated.class);
}
/**
* Checks if this property is sensitive.
*
* @return true if this property is sensitive
*/
public boolean isSensitive() {
return hasAnnotation(Sensitive.class) || hasPrefixWithAnnotation(getKey(), Sensitive.class);
}
/**
* Checks if a property with the given key is sensitive. The key must be for a valid property, and must either itself be annotated as sensitive or have a
* prefix annotated as sensitive.
*
* @param key
* property key
* @return true if property is sensitive
*/
public static boolean isSensitive(String key) {
return hasPrefixWithAnnotation(key, Sensitive.class);
}
private <T extends Annotation> boolean hasAnnotation(Class<T> annotationType) {
Logger log = LoggerFactory.getLogger(getClass());
try {
for (Annotation a : getClass().getField(name()).getAnnotations())
if (annotationType.isInstance(a))
return true;
} catch (SecurityException e) {
log.error("{}", e.getMessage(), e);
} catch (NoSuchFieldException e) {
log.error("{}", e.getMessage(), e);
}
return false;
}
private static <T extends Annotation> boolean hasPrefixWithAnnotation(String key, Class<T> annotationType) {
// relies on side-effects of isValidPropertyKey to populate validPrefixes
if (isValidPropertyKey(key)) {
// check if property exists on its own and has the annotation
if (Property.getPropertyByKey(key) != null)
return getPropertyByKey(key).hasAnnotation(annotationType);
// can't find the property, so check the prefixes
boolean prefixHasAnnotation = false;
for (String prefix : validPrefixes)
if (key.startsWith(prefix))
prefixHasAnnotation = prefixHasAnnotation || getPropertyByKey(prefix).hasAnnotation(annotationType);
return prefixHasAnnotation;
}
return false;
}
private static HashSet<String> validTableProperties = null;
private static HashSet<String> validProperties = null;
private static HashSet<String> validPrefixes = null;
private static boolean isKeyValidlyPrefixed(String key) {
for (String prefix : validPrefixes) {
if (key.startsWith(prefix))
return true;
}
return false;
}
/**
* Checks if the given property key is valid. A valid property key is either equal to the key of some defined property or has a prefix matching some prefix
* defined in this class.
*
* @param key
* property key
* @return true if key is valid (recognized, or has a recognized prefix)
*/
public synchronized static boolean isValidPropertyKey(String key) {
if (validProperties == null) {
validProperties = new HashSet<String>();
validPrefixes = new HashSet<String>();
for (Property p : Property.values()) {
if (p.getType().equals(PropertyType.PREFIX)) {
validPrefixes.add(p.getKey());
} else {
validProperties.add(p.getKey());
}
}
}
return validProperties.contains(key) || isKeyValidlyPrefixed(key);
}
/**
* Checks if the given property key is for a valid table property. A valid table property key is either equal to the key of some defined table property (which
* each start with {@link #TABLE_PREFIX}) or has a prefix matching {@link #TABLE_CONSTRAINT_PREFIX}, {@link #TABLE_ITERATOR_PREFIX}, or
* {@link #TABLE_LOCALITY_GROUP_PREFIX}.
*
* @param key
* property key
* @return true if key is valid for a table property (recognized, or has a recognized prefix)
*/
public synchronized static boolean isValidTablePropertyKey(String key) {
if (validTableProperties == null) {
validTableProperties = new HashSet<String>();
for (Property p : Property.values()) {
if (!p.getType().equals(PropertyType.PREFIX) && p.getKey().startsWith(Property.TABLE_PREFIX.getKey())) {
validTableProperties.add(p.getKey());
}
}
}
return validTableProperties.contains(key) || key.startsWith(Property.TABLE_CONSTRAINT_PREFIX.getKey())
|| key.startsWith(Property.TABLE_ITERATOR_PREFIX.getKey()) || key.startsWith(Property.TABLE_LOCALITY_GROUP_PREFIX.getKey())
|| key.startsWith(Property.TABLE_COMPACTION_STRATEGY_PREFIX.getKey()) || key.startsWith(Property.TABLE_REPLICATION_TARGET.getKey())
|| key.startsWith(Property.TABLE_ARBITRARY_PROP_PREFIX.getKey());
}
private static final EnumSet<Property> fixedProperties = EnumSet.of(Property.TSERV_CLIENTPORT, Property.TSERV_NATIVEMAP_ENABLED,
Property.TSERV_SCAN_MAX_OPENFILES, Property.MASTER_CLIENTPORT, Property.GC_PORT);
/**
* Checks if the given property may be changed via Zookeeper, but not recognized until the restart of some relevant daemon.
*
* @param key
* property key
* @return true if property may be changed via Zookeeper but only heeded upon some restart
*/
public static boolean isFixedZooPropertyKey(Property key) {
return fixedProperties.contains(key);
}
/**
* Checks if the given property key is valid for a property that may be changed via Zookeeper.
*
* @param key
* property key
* @return true if key's property may be changed via Zookeeper
*/
public static boolean isValidZooPropertyKey(String key) {
// white list prefixes
return key.startsWith(Property.TABLE_PREFIX.getKey()) || key.startsWith(Property.TSERV_PREFIX.getKey()) || key.startsWith(Property.LOGGER_PREFIX.getKey())
|| key.startsWith(Property.MASTER_PREFIX.getKey()) || key.startsWith(Property.GC_PREFIX.getKey())
|| key.startsWith(Property.MONITOR_PREFIX.getKey() + "banner.") || key.startsWith(VFS_CONTEXT_CLASSPATH_PROPERTY.getKey())
|| key.startsWith(Property.TABLE_COMPACTION_STRATEGY_PREFIX.getKey()) || key.startsWith(REPLICATION_PREFIX.getKey());
}
/**
* Gets a {@link Property} instance with the given key.
*
* @param key
* property key
* @return property, or null if not found
*/
public static Property getPropertyByKey(String key) {
for (Property prop : Property.values())
if (prop.getKey().equals(key))
return prop;
return null;
}
/**
* Checks if this property is expected to have a Java class as a value.
*
* @return true if this is property is a class property
*/
public static boolean isClassProperty(String key) {
return (key.startsWith(Property.TABLE_CONSTRAINT_PREFIX.getKey()) && key.substring(Property.TABLE_CONSTRAINT_PREFIX.getKey().length()).split("\\.").length == 1)
|| (key.startsWith(Property.TABLE_ITERATOR_PREFIX.getKey()) && key.substring(Property.TABLE_ITERATOR_PREFIX.getKey().length()).split("\\.").length == 2)
|| key.equals(Property.TABLE_LOAD_BALANCER.getKey());
}
// This is not a cache for loaded classes, just a way to avoid spamming the debug log
static Map<String,Class<?>> loaded = Collections.synchronizedMap(new HashMap<String,Class<?>>());
private static <T> T createInstance(String context, String clazzName, Class<T> base, T defaultInstance) {
T instance = null;
try {
Class<? extends T> clazz;
if (context != null && !context.equals("")) {
clazz = AccumuloVFSClassLoader.getContextManager().loadClass(context, clazzName, base);
} else {
clazz = AccumuloVFSClassLoader.loadClass(clazzName, base);
}
instance = clazz.newInstance();
if (loaded.put(clazzName, clazz) != clazz)
log.debug("Loaded class : " + clazzName);
} catch (Exception e) {
log.warn("Failed to load class ", e);
}
if (instance == null) {
log.info("Using default class " + defaultInstance.getClass().getName());
instance = defaultInstance;
}
return instance;
}
/**
* Creates a new instance of a class specified in a configuration property. The table classpath context is used if set.
*
* @param conf
* configuration containing property
* @param property
* property specifying class name
* @param base
* base class of type
* @param defaultInstance
* instance to use if creation fails
* @return new class instance, or default instance if creation failed
* @see AccumuloVFSClassLoader
*/
public static <T> T createTableInstanceFromPropertyName(AccumuloConfiguration conf, Property property, Class<T> base, T defaultInstance) {
String clazzName = conf.get(property);
String context = conf.get(TABLE_CLASSPATH);
return createInstance(context, clazzName, base, defaultInstance);
}
/**
* Creates a new instance of a class specified in a configuration property.
*
* @param conf
* configuration containing property
* @param property
* property specifying class name
* @param base
* base class of type
* @param defaultInstance
* instance to use if creation fails
* @return new class instance, or default instance if creation failed
* @see AccumuloVFSClassLoader
*/
public static <T> T createInstanceFromPropertyName(AccumuloConfiguration conf, Property property, Class<T> base, T defaultInstance) {
String clazzName = conf.get(property);
return createInstance(null, clazzName, base, defaultInstance);
}
/**
* Collects together properties from the given configuration pertaining to compaction strategies. The relevant properties all begin with the prefix in
* {@link #TABLE_COMPACTION_STRATEGY_PREFIX}. In the returned map, the prefix is removed from each property's key.
*
* @param tableConf
* configuration
* @return map of compaction strategy property keys and values, with the detection prefix removed from each key
*/
public static Map<String,String> getCompactionStrategyOptions(AccumuloConfiguration tableConf) {
Map<String,String> longNames = tableConf.getAllPropertiesWithPrefix(Property.TABLE_COMPACTION_STRATEGY_PREFIX);
Map<String,String> result = new HashMap<String,String>();
for (Entry<String,String> entry : longNames.entrySet()) {
result.put(entry.getKey().substring(Property.TABLE_COMPACTION_STRATEGY_PREFIX.getKey().length()), entry.getValue());
}
return result;
}
}
|
ACCUMULO-4041 memoize isSensitive for faster lookups in getSiteConfiguration
|
core/src/main/java/org/apache/accumulo/core/conf/Property.java
|
ACCUMULO-4041 memoize isSensitive for faster lookups in getSiteConfiguration
|
<ide><path>ore/src/main/java/org/apache/accumulo/core/conf/Property.java
<ide> return hasAnnotation(Deprecated.class) || hasPrefixWithAnnotation(getKey(), Deprecated.class);
<ide> }
<ide>
<add> private volatile Boolean isSensitive = null;
<add>
<ide> /**
<ide> * Checks if this property is sensitive.
<ide> *
<ide> * @return true if this property is sensitive
<ide> */
<ide> public boolean isSensitive() {
<del> return hasAnnotation(Sensitive.class) || hasPrefixWithAnnotation(getKey(), Sensitive.class);
<add> if (isSensitive == null) {
<add> isSensitive = hasAnnotation(Sensitive.class) || hasPrefixWithAnnotation(getKey(), Sensitive.class);
<add> }
<add> return isSensitive.booleanValue();
<ide> }
<ide>
<ide> /**
|
|
JavaScript
|
mit
|
65f5d6d96b6c436d5c5226dc479a896453623c9e
| 0 |
DbauchdSloth/dbotchd
|
var loki = require('lokijs');
var jsgraph = require('jsgraph');
var irc = require('tmi.js');
var uuid = require('uuid');
var express = require('express');
//var util = require('../src/util');
//var digraph = require('../src/digraph');
//var entity = require('../src/entity');
//var extend = util.extend;
//var DirectedGraph = digraph.DirectedGraph;
//var Entity = entity.Entity;
//var Relationship = entity.Relationship;
/*
User = (function(superclass) {
extend(User, superClass);
function User(username) {
return User.__super__.constructor.apply(this, username, {username: username});
}
return User;
})(Entity);
Channel = (function(superclass) {
extend(Channel, superClass);
function Channel(username) {
return User.__super__.constructor.apply(this, username, {username: username});
}
return Channel;
})(Entity);
//var collections = require('./collections');
Event = (function(superClass) { //var e = new Event(type, args);
extend(Event, superClass);
function Event(opts) {
Event.__super__.constructor.apply(this, uuid.v4(), opts);
}
return Event;
})(Entity);
JoinEvent = (function(superClass) {
extend(JoinEvent, superClass);
function JoinEvent(channel, username) {
this.eventType = "irc-join";
return User.__super__.constructor.apply(this, {channel: channel, username: username});
}
return JoinEvent;
})(Event);
PartEvent = (function(superClass) {
extend(PartEvent, superClass);s
function PartEvent(channel, username) {
this.eventType = "irc-part";
return User.__super__.constructor.apply(this, {channel: channel, username: username});
}
return PartEvent;
})(Event);
*/
module.exports = function(emitter, username, secret, config) {
/*
this.started = new Date();
var lokiConfig = {
autosave: true,
autosaveInterval: 1000
};
var channeldb = new loki('twitch-channel.json', lokiConfig);
var channels = channeldb.addCollection('channels');
var socialdb = new loki('twitch-' + username + '-social-graph.json');
var entities = socialdb.addCollection('entities');
var relationships = socialdb.addCollection('relationships');
var socialGraph = new DirectedGraph("twitch-" + username + "-social");
var userdb = new loki('twitch-' + username + '.json', lokiConfig);
var users = userdb.addCollection('users');
var hosting = userdb.addCollection('hosting');
var follows = userdb.addCollection('follow');
var events = userdb.addCollection('event');
this.client = new irc.client(config);
this.cacheChannel= function(name) {
//var channel = channels.findObject({"name": {"$eq": name}});
if (!channel) { // always cache channels for now
client.api({
url: "https://api.twitch.tv/kraken/channels/" + name
}, function(err, res, body) {
if (err) return console.error(err);
vat tchannel = JSON.parse(body);
var channel new Channel(username);
channels.insert(channel.toJSON());
vres = socialGraph.addVertex(channel.toVertex());
if (vres.error) return console.error(vres.error);
entities.insert(vres.result);
});
cacheChannelHosting(name);
cacheChannelFollows(name);
}
}
this.cacheChannelHosting = function(name) {
}
this.cacheChannelFollows = function(name) {
}
this.cacheUser = function(name) {
var user = users.findObject({"username": {"$eq": name}});
if (!user) {
this.client.api({
url: "https://api.twitch.tv/kraken/users/" + name
}, function(err, res, body) {
if (err) return console.error(err);
var tuser = JSON.parse(body);
var user = new User(tuser.username);
users.insert(user.toJSON());
vres = socialGraph.addVertex(user.toVertex());
if (vres.error) return console.error(vres.error);
entities.insert(vres.result);
});
}
}
function onConnected(address, port) {
var event = new Event("irc-connected", {address: address, port: port});
console.dir(event);
}
function onJoin(channel, user) {
var event = new JoinEvent(channel, user);
events.insert(event);
var user = users.findObject({"username": {"$eq": username}});
if (!user) {
cacheUser(user);
}
}
function onPart(channel, username) {
var event = new PartEvent(channel, user);
events.insert(event);
};
function onHosted(channel, user, viewers) {
var ts = new Date();
console.log("%s [%s] <%s> host %s", ts.toUTCString(), channel, user, viewers);
var event = {
created: ts.toUTCString(),
type: "hosted",
channel: channel,
username: user,
viewers: viewers
};
events.insert(event);
if (!user) {
cacheUser(user);
}
}
function onChat(channel, user, message, self) {
var ts = new Date();
console.log("%s [%s] <%s> %s", ts.toUTCString(), channel, user.username, message);
events.insert({
created: ts.toUTCString(),
type: "chat",
channel: channel,
username: user.username,
message: message
});
cacheUser(user.username);
var commandPattern = new RegExp("^!\\w+");
if (commandPattern.test(message)) {
var command = commandPattern.exec(message);
emitter.emit("command-dispatch", command, user.username, message);
}
}
function onAction(channel, user, message, self) {
var ts = new Date();
console.log("%s [%s] <*%s> %s", ts.toUTCString(), channel, user.username, message);
events.insert({
created: ts.toUTCString(),
type: "action",
channel: channel,
user: user.username,
message: message
});
cacheUser(user.username);
};
this.say = function(channel, message) {
this.client.say(channel, message);
}
this.client.on("connected", onConnected);
this.client.on("join", onJoin);
this.client.on("part", onPart);
this.client.on("hosted", onHosted);
this.client.on("chat", onChat);
this.client.on("action", onAction);
emitter.on('cache-user', this.cacheUser);
emitter.on('cache-channel', this.cacheChannel);
emitter.on('cache-channel-hosting', this.cacheChannelHosting);
emitter.on('cache-channel-follows', this.cacheChannelFollows);
this.router = express.Router();
this.router.get('/channel/:name', function(req, res) {
cacheChannel(req.params.name);
return res.json(channels.find({"name": req.params.name}));
});
this.router.get('/channel/:name/hosting', function(req, res) {
cacheChannel(req.params.name);
return res.json(hosting.find());
});
this.router.get('/channel/:name/follows', function(req, res) {
cacheChannel(req.params.name);
return res.json(follows.find());
});
// register new router for every new user identified so they get their own base loki file registered once
*/
this.connect = function() {
this.client.connect();
};
this.disconnect = function() {
this.client.disconnect();
};
return this;
};
|
extension/twitch-api.js
|
var loki = require('lokijs');
var jsgraph = require('jsgraph');
var irc = require('tmi.js');
var uuid = require('uuid');
var express = require('express');
//var util = require('../src/util');
//var digraph = require('../src/digraph');
//var entity = require('../src/entity');
//var extend = util.extend;
//var DirectedGraph = digraph.DirectedGraph;
//var Entity = entity.Entity;
//var Relationship = entity.Relationship;
/*
User = (function(superclass) {
extend(User, superClass);
function User(username) {
return User.__super__.constructor.apply(this, username, {username: username});
}
return User;
})(Entity);
Channel = (function(superclass) {
extend(Channel, superClass);
function Channel(username) {
return User.__super__.constructor.apply(this, username, {username: username});
}
return Channel;
})(Entity);
//var collections = require('./collections');
Event = (function(superClass) { //var e = new Event(type, args);
extend(Event, superClass);
function Event(opts) {
Event.__super__.constructor.apply(this, uuid.v4(), opts);
}
return Event;
})(Entity);
JoinEvent = (function(superClass) {
extend(JoinEvent, superClass);
function JoinEvent(channel, username) {
this.eventType = "irc-join";
return User.__super__.constructor.apply(this, {channel: channel, username: username});
}
return JoinEvent;
})(Event);
PartEvent = (function(superClass) {
extend(PartEvent, superClass);s
function PartEvent(channel, username) {
this.eventType = "irc-part";
return User.__super__.constructor.apply(this, {channel: channel, username: username});
}
return PartEvent;
})(Event);
module.exports = function(emitter, username, secret, config) {
this.started = new Date();
var lokiConfig = {
autosave: true,
autosaveInterval: 1000
};
var channeldb = new loki('twitch-channel.json', lokiConfig);
var channels = channeldb.addCollection('channels');
var socialdb = new loki('twitch-' + username + '-social-graph.json');
var entities = socialdb.addCollection('entities');
var relationships = socialdb.addCollection('relationships');
var socialGraph = new DirectedGraph("twitch-" + username + "-social");
var userdb = new loki('twitch-' + username + '.json', lokiConfig);
var users = userdb.addCollection('users');
var hosting = userdb.addCollection('hosting');
var follows = userdb.addCollection('follow');
var events = userdb.addCollection('event');
this.client = new irc.client(config);
this.cacheChannel= function(name) {
//var channel = channels.findObject({"name": {"$eq": name}});
if (!channel) { // always cache channels for now
client.api({
url: "https://api.twitch.tv/kraken/channels/" + name
}, function(err, res, body) {
if (err) return console.error(err);
vat tchannel = JSON.parse(body);
var channel new Channel(username);
channels.insert(channel.toJSON());
vres = socialGraph.addVertex(channel.toVertex());
if (vres.error) return console.error(vres.error);
entities.insert(vres.result);
});
cacheChannelHosting(name);
cacheChannelFollows(name);
}
}
this.cacheChannelHosting = function(name) {
}
this.cacheChannelFollows = function(name) {
}
this.cacheUser = function(name) {
var user = users.findObject({"username": {"$eq": name}});
if (!user) {
this.client.api({
url: "https://api.twitch.tv/kraken/users/" + name
}, function(err, res, body) {
if (err) return console.error(err);
var tuser = JSON.parse(body);
var user = new User(tuser.username);
users.insert(user.toJSON());
vres = socialGraph.addVertex(user.toVertex());
if (vres.error) return console.error(vres.error);
entities.insert(vres.result);
});
}
}
function onConnected(address, port) {
var event = new Event("irc-connected", {address: address, port: port});
console.dir(event);
}
function onJoin(channel, user) {
var event = new JoinEvent(channel, user);
events.insert(event);
var user = users.findObject({"username": {"$eq": username}});
if (!user) {
cacheUser(user);
}
}
function onPart(channel, username) {
var event = new PartEvent(channel, user);
events.insert(event);
};
function onHosted(channel, user, viewers) {
var ts = new Date();
console.log("%s [%s] <%s> host %s", ts.toUTCString(), channel, user, viewers);
var event = {
created: ts.toUTCString(),
type: "hosted",
channel: channel,
username: user,
viewers: viewers
};
events.insert(event);
if (!user) {
cacheUser(user);
}
}
function onChat(channel, user, message, self) {
var ts = new Date();
console.log("%s [%s] <%s> %s", ts.toUTCString(), channel, user.username, message);
events.insert({
created: ts.toUTCString(),
type: "chat",
channel: channel,
username: user.username,
message: message
});
cacheUser(user.username);
var commandPattern = new RegExp("^!\\w+");
if (commandPattern.test(message)) {
var command = commandPattern.exec(message);
emitter.emit("command-dispatch", command, user.username, message);
}
}
function onAction(channel, user, message, self) {
var ts = new Date();
console.log("%s [%s] <*%s> %s", ts.toUTCString(), channel, user.username, message);
events.insert({
created: ts.toUTCString(),
type: "action",
channel: channel,
user: user.username,
message: message
});
cacheUser(user.username);
};
this.say = function(channel, message) {
this.client.say(channel, message);
}
this.client.on("connected", onConnected);
this.client.on("join", onJoin);
this.client.on("part", onPart);
this.client.on("hosted", onHosted);
this.client.on("chat", onChat);
this.client.on("action", onAction);
emitter.on('cache-user', this.cacheUser);
emitter.on('cache-channel', this.cacheChannel);
emitter.on('cache-channel-hosting', this.cacheChannelHosting);
emitter.on('cache-channel-follows', this.cacheChannelFollows);
this.router = express.Router();
this.router.get('/channel/:name', function(req, res) {
cacheChannel(req.params.name);
return res.json(channels.find({"name": req.params.name}));
});
this.router.get('/channel/:name/hosting', function(req, res) {
cacheChannel(req.params.name);
return res.json(hosting.find());
});
this.router.get('/channel/:name/follows', function(req, res) {
cacheChannel(req.params.name);
return res.json(follows.find());
});
// register new router for every new user identified so they get their own base loki file registered once
*/
this.connect = function() {
this.client.connect();
};
this.disconnect = function() {
this.client.disconnect();
};
return this;
};
|
debug
|
extension/twitch-api.js
|
debug
|
<ide><path>xtension/twitch-api.js
<ide> }
<ide> return PartEvent;
<ide> })(Event);
<del>
<add>*/
<ide> module.exports = function(emitter, username, secret, config) {
<del>
<add>/*
<ide> this.started = new Date();
<ide>
<ide> var lokiConfig = {
|
|
Java
|
apache-2.0
|
ca566907c679bd8e1ffddb2d3557bfaab0de7e49
| 0 |
actionml/harness,actionml/harness,actionml/harness
|
package com.actionml;
import akka.http.javadsl.model.*;
import akka.japi.Pair;
import com.actionml.entity.Event;
import com.actionml.entity.EventId;
import org.joda.time.DateTime;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletionStage;
import java.util.stream.Collectors;
/**
* @author The ActionML Team (<a href="http://actionml.com">http://actionml.com</a>)
* 04.02.17 17:50
*/
public class EventClient extends RestClient {
private Uri uri;
EventClient(String datasetId, String host, Integer port) {
super(host, port);
uri = Uri.create("/datasets/").addPathSegment(datasetId).addPathSegment("events");
}
CompletionStage<Event> getEvent(String eventId) {
return this.get(uri, eventId).thenApply(jsonElement -> toPojo(jsonElement, Event.class));
}
CompletionStage<List<Pair<Long, CompletionStage<Event>>>> getEvents(List<String> eventIds) {
return this.multiGet(uri, eventIds).thenApply(pairs ->
pairs.stream().map(pair ->
pair.copy(pair.first(), pair.second().thenApply(jsonElement -> toPojo(jsonElement, Event.class)))
).collect(Collectors.toList())
);
}
CompletionStage<EventId> createEvent(Event event) {
return this.post(uri, event.toJsonString()).thenApply(jsonElement -> toPojo(jsonElement, EventId.class));
}
CompletionStage<List<Pair<Long, CompletionStage<EventId>>>> createEvents(List<Event> events) {
List<String> jsonList = events.stream().map(Event::toJsonString).collect(Collectors.toList());
return this.multiPost(uri, jsonList).thenApply(pairs ->
pairs.stream().map(pair ->
pair.copy(pair.first(), pair.second().thenApply(jsonElement -> toPojo(jsonElement, EventId.class)))
).collect(Collectors.toList())
);
}
private Event buildEvent(String id, DateTime eventTime) {
return new Event().entityId(id).eventTime(eventTime);
}
/*******************************************************************************************************************
* User actions
******************************************************************************************************************/
private Event buildUserEvent(String uid, DateTime eventTime) {
return buildEvent(uid, eventTime).entityType("user");
}
private Event buildUserEvent(String uid, Map<String, Object> properties, DateTime eventTime) {
return buildUserEvent(uid, eventTime).properties(properties);
}
/**
* Sends a set user properties request. Implicitly creates the user if it's not already there.
* Properties could be empty.
* @param uid ID of the user
* @param properties a map of all the properties to be associated with the user, could be empty
* @param eventTime timestamp of the event
* @return ID of this event
*/
public CompletionStage<EventId> setUser(String uid, Map<String, Object> properties, DateTime eventTime) {
Event event = buildUserEvent(uid, properties, eventTime).event("$set");
return createEvent(event);
}
/**
* Sets properties of a user. Same as {@link #setUser(String, Map, DateTime)}
* except event time is not specified and recorded as the time when the function is called.
*/
public CompletionStage<EventId> setUser(String uid, Map<String, Object> properties) {
return setUser(uid, properties, new DateTime());
}
/**
* Unsets properties of a user. The list must not be empty.
*
* @param uid ID of the user
* @param properties a list of all the properties to unset
* @param eventTime timestamp of the event
* @return ID of this event
*/
public CompletionStage<EventId> unsetUser(String uid, List<String> properties, DateTime eventTime) throws IOException {
if (properties.isEmpty()) {
throw new IllegalStateException("property list cannot be empty");
}
// converts the list into a map (to empty string) before creating the event object
Map<String, Object> propertiesMap = properties.stream().collect(Collectors.toMap(o -> o, s -> ""));
Event event = buildUserEvent(uid, propertiesMap, eventTime).event("$unset");
return createEvent(event);
}
/**
* Unsets properties of a user. Same as {@link #unsetUser(String, List, DateTime)
* unsetUser(String, List<String>, DateTime)}
* except event time is not specified and recorded as the time when the function is called.
*/
public CompletionStage<EventId> unsetUser(String uid, List<String> properties) throws IOException {
return unsetUser(uid, properties, new DateTime());
}
/**
* Deletes a user.
*
* @param uid ID of the user
* @param eventTime timestamp of the event
* @return ID of this event
*/
public CompletionStage<EventId> deleteUser(String uid, DateTime eventTime) {
Event event = buildUserEvent(uid, eventTime).event("$delete");
return createEvent(event);
}
/**
* Deletes a user. Event time is recorded as the time when the function is called.
*
* @param uid ID of the user
* @return ID of this event
*/
public CompletionStage<EventId> deleteUser(String uid) {
return deleteUser(uid, new DateTime());
}
/*******************************************************************************************************************
* Item actions
******************************************************************************************************************/
private Event buildItemEvent(String iid, DateTime eventTime) {
return buildEvent(iid, eventTime).entityType("item");
}
private Event buildItemEvent(String iid, Map<String, Object> properties, DateTime eventTime) {
return buildItemEvent(iid, eventTime).properties(properties);
}
/**
* Sets properties of a item. Implicitly creates the item if it's not already there.
* Properties could be empty.
*
* @param iid ID of the item
* @param properties a map of all the properties to be associated with the item, could be empty
* @param eventTime timestamp of the event
* @return ID of this event
*/
public CompletionStage<EventId> setItem(String iid, Map<String, Object> properties, DateTime eventTime) {
Event event = buildItemEvent(iid, properties, eventTime).event("$set");
return createEvent(event);
}
/**
* Sets properties of a item. Same as {@link #setItem(String, Map, DateTime)
* setItem(String, Map<String, Object>, DateTime)}
* except event time is not specified and recorded as the time when the function is called.
*/
public CompletionStage<EventId> setItem(String iid, Map<String, Object> properties) {
return setItem(iid, properties, new DateTime());
}
/**
* Unsets properties of a item. The list must not be empty.
*
* @param iid ID of the item
* @param properties a list of all the properties to unset
* @param eventTime timestamp of the event
* @return ID of this event
*/
public CompletionStage<EventId> unsetItem(String iid, List<String> properties, DateTime eventTime) throws IOException {
if (properties.isEmpty()) {
throw new IllegalStateException("property list cannot be empty");
}
// converts the list into a map (to empty string) before creating the event object
Map<String, Object> propertiesMap = properties.stream().collect(Collectors.toMap(o -> o, s -> ""));
Event event = buildItemEvent(iid, propertiesMap, eventTime).event("$unset");
return createEvent(event);
}
/**
* Unsets properties of a item. Same as {@link #unsetItem(String, List, DateTime)
* unsetItem(String, List<String>, DateTime)}
* except event time is not specified and recorded as the time when the function is called.
*/
public CompletionStage<EventId> unsetItem(String iid, List<String> properties) throws IOException {
return unsetItem(iid, properties, new DateTime());
}
/**
* Deletes a item.
*
* @param iid ID of the item
* @param eventTime timestamp of the event
* @return ID of this event
*/
public CompletionStage<EventId> deleteItem(String iid, DateTime eventTime) {
Event event = buildItemEvent(iid, eventTime).event("$delete");
return createEvent(event);
}
/**
* Deletes a item. Event time is recorded as the time when the function is called.
*
* @param iid ID of the item
* @return ID of this event
*/
public CompletionStage<EventId> deleteItem(String iid) {
return deleteItem(iid, new DateTime());
}
/*******************************************************************************************************************
* User to Item actions
******************************************************************************************************************/
/**
* Records a user-action-on-item event.
*
* @param action name of the action performed
* @param uid ID of the user
* @param iid ID of the item
* @param properties a map of properties associated with this action
* @param eventTime timestamp of the event
* @return ID of this event
*/
public CompletionStage<EventId> userActionItem(String action, String uid, String iid, Map<String, Object> properties, DateTime eventTime) {
Event event = buildUserEvent(uid, properties, eventTime).event(action).targetEntityType("item").targetEntityId(iid);
return createEvent(event);
}
public CompletionStage<EventId> userActionItem(String action, String uid, String iid, Map<String, Object> properties) {
return userActionItem(action, uid, iid, properties, new DateTime());
}
}
|
java-sdk/src/main/java/com/actionml/EventClient.java
|
package com.actionml;
import akka.http.javadsl.model.*;
import akka.japi.Pair;
import com.actionml.entity.Event;
import com.actionml.entity.EventId;
import org.joda.time.DateTime;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletionStage;
import java.util.stream.Collectors;
/**
* @author The ActionML Team (<a href="http://actionml.com">http://actionml.com</a>)
* 04.02.17 17:50
*/
public class EventClient extends RestClient {
private Uri uri;
EventClient(String datasetId, String host, Integer port) {
super(host, port);
uri = Uri.create("/datasets/").addPathSegment(datasetId).addPathSegment("events");
}
CompletionStage<Event> getEvent(String eventId) {
return this.get(uri, eventId).thenApply(jsonElement -> toPojo(jsonElement, Event.class));
}
CompletionStage<List<Pair<Long, CompletionStage<Event>>>> getEvents(List<String> eventIds) {
return this.multiGet(uri, eventIds).thenApply(pairs ->
pairs.stream().map(pair ->
pair.copy(pair.first(), pair.second().thenApply(jsonElement -> toPojo(jsonElement, Event.class)))
).collect(Collectors.toList())
);
}
CompletionStage<EventId> createEvent(Event event) {
return this.post(uri, event.toJsonString()).thenApply(jsonElement -> toPojo(jsonElement, EventId.class));
}
CompletionStage<List<Pair<Long, CompletionStage<EventId>>>> createEvents(List<Event> events) {
List<String> jsonList = events.stream().map(event -> event.toJsonString()).collect(Collectors.toList());
return this.multiPost(uri, jsonList).thenApply(pairs ->
pairs.stream().map(pair ->
pair.copy(pair.first(), pair.second().thenApply(jsonElement -> toPojo(jsonElement, EventId.class)))
).collect(Collectors.toList())
);
}
private Event buildEvent(String id, DateTime eventTime) {
return new Event().entityId(id).eventTime(eventTime);
}
/*******************************************************************************************************************
* User actions
******************************************************************************************************************/
private Event buildUserEvent(String uid, DateTime eventTime) {
return buildEvent(uid, eventTime).entityType("user");
}
private Event buildUserEvent(String uid, Map<String, Object> properties, DateTime eventTime) {
return buildUserEvent(uid, eventTime).properties(properties);
}
/**
* Sends a set user properties request. Implicitly creates the user if it's not already there.
* Properties could be empty.
* @param uid ID of the user
* @param properties a map of all the properties to be associated with the user, could be empty
* @param eventTime timestamp of the event
* @return ID of this event
*/
public CompletionStage<EventId> setUser(String uid, Map<String, Object> properties, DateTime eventTime) {
Event event = buildUserEvent(uid, properties, eventTime).event("$set");
return createEvent(event);
}
/**
* Sets properties of a user. Same as {@link #setUser(String, Map, DateTime)}
* except event time is not specified and recorded as the time when the function is called.
*/
public CompletionStage<EventId> setUser(String uid, Map<String, Object> properties) {
return setUser(uid, properties, new DateTime());
}
/**
* Unsets properties of a user. The list must not be empty.
*
* @param uid ID of the user
* @param properties a list of all the properties to unset
* @param eventTime timestamp of the event
* @return ID of this event
*/
public CompletionStage<EventId> unsetUser(String uid, List<String> properties, DateTime eventTime) throws IOException {
if (properties.isEmpty()) {
throw new IllegalStateException("property list cannot be empty");
}
// converts the list into a map (to empty string) before creating the event object
Map<String, Object> propertiesMap = properties.stream().collect(Collectors.toMap(o -> o, s -> ""));
Event event = buildUserEvent(uid, propertiesMap, eventTime).event("$unset");
return createEvent(event);
}
/**
* Unsets properties of a user. Same as {@link #unsetUser(String, List, DateTime)
* unsetUser(String, List<String>, DateTime)}
* except event time is not specified and recorded as the time when the function is called.
*/
public CompletionStage<EventId> unsetUser(String uid, List<String> properties) throws IOException {
return unsetUser(uid, properties, new DateTime());
}
/**
* Deletes a user.
*
* @param uid ID of the user
* @param eventTime timestamp of the event
* @return ID of this event
*/
public CompletionStage<EventId> deleteUser(String uid, DateTime eventTime) {
Event event = buildUserEvent(uid, eventTime).event("$delete");
return createEvent(event);
}
/**
* Deletes a user. Event time is recorded as the time when the function is called.
*
* @param uid ID of the user
* @return ID of this event
*/
public CompletionStage<EventId> deleteUser(String uid) {
return deleteUser(uid, new DateTime());
}
/*******************************************************************************************************************
* Item actions
******************************************************************************************************************/
private Event buildItemEvent(String iid, DateTime eventTime) {
return buildEvent(iid, eventTime).entityType("item");
}
private Event buildItemEvent(String iid, Map<String, Object> properties, DateTime eventTime) {
return buildItemEvent(iid, eventTime).properties(properties);
}
/**
* Sets properties of a item. Implicitly creates the item if it's not already there.
* Properties could be empty.
*
* @param iid ID of the item
* @param properties a map of all the properties to be associated with the item, could be empty
* @param eventTime timestamp of the event
* @return ID of this event
*/
public CompletionStage<EventId> setItem(String iid, Map<String, Object> properties, DateTime eventTime) {
Event event = buildItemEvent(iid, properties, eventTime).event("$set");
return createEvent(event);
}
/**
* Sets properties of a item. Same as {@link #setItem(String, Map, DateTime)
* setItem(String, Map<String, Object>, DateTime)}
* except event time is not specified and recorded as the time when the function is called.
*/
public CompletionStage<EventId> setItem(String iid, Map<String, Object> properties) {
return setItem(iid, properties, new DateTime());
}
/**
* Unsets properties of a item. The list must not be empty.
*
* @param iid ID of the item
* @param properties a list of all the properties to unset
* @param eventTime timestamp of the event
* @return ID of this event
*/
public CompletionStage<EventId> unsetItem(String iid, List<String> properties, DateTime eventTime) throws IOException {
if (properties.isEmpty()) {
throw new IllegalStateException("property list cannot be empty");
}
// converts the list into a map (to empty string) before creating the event object
Map<String, Object> propertiesMap = properties.stream().collect(Collectors.toMap(o -> o, s -> ""));
Event event = buildItemEvent(iid, propertiesMap, eventTime).event("$unset");
return createEvent(event);
}
/**
* Unsets properties of a item. Same as {@link #unsetItem(String, List, DateTime)
* unsetItem(String, List<String>, DateTime)}
* except event time is not specified and recorded as the time when the function is called.
*/
public CompletionStage<EventId> unsetItem(String iid, List<String> properties) throws IOException {
return unsetItem(iid, properties, new DateTime());
}
/**
* Deletes a item.
*
* @param iid ID of the item
* @param eventTime timestamp of the event
* @return ID of this event
*/
public CompletionStage<EventId> deleteItem(String iid, DateTime eventTime) {
Event event = buildItemEvent(iid, eventTime).event("$delete");
return createEvent(event);
}
/**
* Deletes a item. Event time is recorded as the time when the function is called.
*
* @param iid ID of the item
* @return ID of this event
*/
public CompletionStage<EventId> deleteItem(String iid) {
return deleteItem(iid, new DateTime());
}
/*******************************************************************************************************************
* User to Item actions
******************************************************************************************************************/
/**
* Records a user-action-on-item event.
*
* @param action name of the action performed
* @param uid ID of the user
* @param iid ID of the item
* @param properties a map of properties associated with this action
* @param eventTime timestamp of the event
* @return ID of this event
*/
public CompletionStage<EventId> userActionItem(String action, String uid, String iid, Map<String, Object> properties, DateTime eventTime) {
Event event = buildUserEvent(uid, properties, eventTime).event(action).targetEntityType("item").targetEntityId(iid);
return createEvent(event);
}
public CompletionStage<EventId> userActionItem(String action, String uid, String iid, Map<String, Object> properties) {
return userActionItem(action, uid, iid, properties, new DateTime());
}
}
|
simplified
|
java-sdk/src/main/java/com/actionml/EventClient.java
|
simplified
|
<ide><path>ava-sdk/src/main/java/com/actionml/EventClient.java
<ide> }
<ide>
<ide> CompletionStage<List<Pair<Long, CompletionStage<EventId>>>> createEvents(List<Event> events) {
<del> List<String> jsonList = events.stream().map(event -> event.toJsonString()).collect(Collectors.toList());
<add> List<String> jsonList = events.stream().map(Event::toJsonString).collect(Collectors.toList());
<ide> return this.multiPost(uri, jsonList).thenApply(pairs ->
<ide> pairs.stream().map(pair ->
<ide> pair.copy(pair.first(), pair.second().thenApply(jsonElement -> toPojo(jsonElement, EventId.class)))
|
|
Java
|
lgpl-2.1
|
ebe12b0dfd3cad8505352f76805f649cde5f08ca
| 0 |
jfree/jfreechart,jfree/jfreechart,jfree/jfreechart,jfree/jfreechart
|
/* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2016, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.]
*
* -----------------------------
* KeyedValueComparatorType.java
* -----------------------------
* (C) Copyright 2003-2012, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes:
* --------
* 05-Mar-2003 : Version 1 (DG);
* 23-Sep-2012 : Make this class serializable (DG);
*
*/
package org.jfree.data;
/**
* Used to indicate the type of a {@link KeyedValueComparator} : 'by key' or
* 'by value'.
*/
public enum KeyedValueComparatorType {
/** An object representing 'by key' sorting. */
BY_KEY,
/** An object representing 'by value' sorting. */
BY_VALUE
}
|
src/main/java/org/jfree/data/KeyedValueComparatorType.java
|
/* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2016, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.]
*
* -----------------------------
* KeyedValueComparatorType.java
* -----------------------------
* (C) Copyright 2003-2012, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes:
* --------
* 05-Mar-2003 : Version 1 (DG);
* 23-Sep-2012 : Make this class serializable (DG);
*
*/
package org.jfree.data;
import java.io.Serializable;
/**
* Used to indicate the type of a {@link KeyedValueComparator} : 'by key' or
* 'by value'.
*/
public final class KeyedValueComparatorType implements Serializable {
/** An object representing 'by key' sorting. */
public static final KeyedValueComparatorType BY_KEY
= new KeyedValueComparatorType("KeyedValueComparatorType.BY_KEY");
/** An object representing 'by value' sorting. */
public static final KeyedValueComparatorType BY_VALUE
= new KeyedValueComparatorType("KeyedValueComparatorType.BY_VALUE");
/** The name. */
private String name;
/**
* Private constructor.
*
* @param name the name.
*/
private KeyedValueComparatorType(String name) {
this.name = name;
}
/**
* Returns a string representing the object.
*
* @return The string.
*/
@Override
public String toString() {
return this.name;
}
/**
* Returns {@code true} if this object is equal to the specified
* object, and {@code false} otherwise.
*
* @param o the other object.
*
* @return A boolean.
*/
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof KeyedValueComparatorType)) {
return false;
}
KeyedValueComparatorType type = (KeyedValueComparatorType) o;
if (!this.name.equals(type.name)) {
return false;
}
return true;
}
/**
* Returns a hash code.
*
* @return A hash code.
*/
@Override
public int hashCode() {
return this.name.hashCode();
}
}
|
KeyedValueComparatorType as enum
|
src/main/java/org/jfree/data/KeyedValueComparatorType.java
|
KeyedValueComparatorType as enum
|
<ide><path>rc/main/java/org/jfree/data/KeyedValueComparatorType.java
<ide>
<ide> package org.jfree.data;
<ide>
<del>import java.io.Serializable;
<del>
<ide> /**
<ide> * Used to indicate the type of a {@link KeyedValueComparator} : 'by key' or
<ide> * 'by value'.
<ide> */
<del>public final class KeyedValueComparatorType implements Serializable {
<add>public enum KeyedValueComparatorType {
<ide>
<ide> /** An object representing 'by key' sorting. */
<del> public static final KeyedValueComparatorType BY_KEY
<del> = new KeyedValueComparatorType("KeyedValueComparatorType.BY_KEY");
<add> BY_KEY,
<ide>
<ide> /** An object representing 'by value' sorting. */
<del> public static final KeyedValueComparatorType BY_VALUE
<del> = new KeyedValueComparatorType("KeyedValueComparatorType.BY_VALUE");
<add> BY_VALUE
<ide>
<del> /** The name. */
<del> private String name;
<del>
<del> /**
<del> * Private constructor.
<del> *
<del> * @param name the name.
<del> */
<del> private KeyedValueComparatorType(String name) {
<del> this.name = name;
<del> }
<del>
<del> /**
<del> * Returns a string representing the object.
<del> *
<del> * @return The string.
<del> */
<del> @Override
<del> public String toString() {
<del> return this.name;
<del> }
<del>
<del> /**
<del> * Returns {@code true} if this object is equal to the specified
<del> * object, and {@code false} otherwise.
<del> *
<del> * @param o the other object.
<del> *
<del> * @return A boolean.
<del> */
<del> @Override
<del> public boolean equals(Object o) {
<del> if (this == o) {
<del> return true;
<del> }
<del> if (!(o instanceof KeyedValueComparatorType)) {
<del> return false;
<del> }
<del>
<del> KeyedValueComparatorType type = (KeyedValueComparatorType) o;
<del> if (!this.name.equals(type.name)) {
<del> return false;
<del> }
<del>
<del> return true;
<del> }
<del>
<del> /**
<del> * Returns a hash code.
<del> *
<del> * @return A hash code.
<del> */
<del> @Override
<del> public int hashCode() {
<del> return this.name.hashCode();
<del> }
<ide> }
<del>
|
|
Java
|
mit
|
232b2ae0693b08337c05a73219eb9f622c1e95ca
| 0 |
sameer49/Appium-Grid-For-Android,sameer49/Appium-Grid-For-Android
|
package runTest;
import libs.BaseTest;
import org.openqa.selenium.By;
public class GmailExmaple extends BaseTest{
public GmailExmaple(){
}
public GmailExmaple(int deviceNum){
super(deviceNum);
}
public void login(){
try{
driver.get("http://gmail.com/");
Thread.sleep(2000);
driver.findElement(By.id("Email")).sendKeys("test");
Thread.sleep(2000);
driver.findElement(By.id("Passwd")).sendKeys("test");
Thread.sleep(2000);
driver.findElement(By.id("signIn")).click();
Thread.sleep(2000);
}
catch(Exception e){
e.printStackTrace();
}
finally{
driver.quit(); // close driver
}
}
public void run(){
login();
}
public static void main(String[] args) {
// Create object
GmailExmaple gmail = new GmailExmaple();
// Get connected device count
int totalDevices=gmail.deviceCount;
// Initialize threads for each connected devices
GmailExmaple[] threads = new GmailExmaple[totalDevices];
// Create threads for each connected devices
for(int i=0;i<totalDevices;i++)
threads[i] = new GmailExmaple(i);
// Start running execution on each device
for(int i=0;i<totalDevices;i++)
threads[i].start();
}
}
|
src/runTest/GmailExmaple.java
|
package runTest;
import io.appium.java_client.android.AndroidDriver;
import org.openqa.selenium.By;
public class GmailExmaple {
AndroidDriver driver;
public GmailExmaple(AndroidDriver driver) {
this.driver=driver;
}
public void login()
{
try
{
driver.get("http://gmail.com/");
Thread.sleep(2000);
driver.findElement(By.id("Email")).sendKeys("test");
Thread.sleep(2000);
driver.findElement(By.id("Passwd")).sendKeys("test");
Thread.sleep(2000);
driver.findElement(By.id("signIn")).click();
Thread.sleep(2000);
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
// close driver
driver.quit();
}
}
}
|
extended BaseTest and ran test from here
|
src/runTest/GmailExmaple.java
|
extended BaseTest and ran test from here
|
<ide><path>rc/runTest/GmailExmaple.java
<ide> package runTest;
<ide>
<del>import io.appium.java_client.android.AndroidDriver;
<del>
<add>import libs.BaseTest;
<ide> import org.openqa.selenium.By;
<ide>
<del>public class GmailExmaple {
<ide>
<del> AndroidDriver driver;
<add>public class GmailExmaple extends BaseTest{
<add>
<add> public GmailExmaple(){
<add> }
<ide>
<del> public GmailExmaple(AndroidDriver driver) {
<del> this.driver=driver;
<add> public GmailExmaple(int deviceNum){
<add> super(deviceNum);
<ide> }
<del>
<del> public void login()
<del> {
<del> try
<del> {
<add>
<add> public void login(){
<add> try{
<ide> driver.get("http://gmail.com/");
<ide> Thread.sleep(2000);
<ide> driver.findElement(By.id("Email")).sendKeys("test");
<ide> driver.findElement(By.id("signIn")).click();
<ide> Thread.sleep(2000);
<ide> }
<del> catch(Exception e)
<del> {
<add> catch(Exception e){
<ide> e.printStackTrace();
<ide> }
<del> finally
<del> {
<del> // close driver
<del> driver.quit();
<add> finally{
<add> driver.quit(); // close driver
<ide> }
<ide> }
<add>
<add> public void run(){
<add> login();
<add> }
<add>
<add> public static void main(String[] args) {
<add> // Create object
<add> GmailExmaple gmail = new GmailExmaple();
<add>
<add> // Get connected device count
<add> int totalDevices=gmail.deviceCount;
<add>
<add> // Initialize threads for each connected devices
<add> GmailExmaple[] threads = new GmailExmaple[totalDevices];
<add>
<add> // Create threads for each connected devices
<add> for(int i=0;i<totalDevices;i++)
<add> threads[i] = new GmailExmaple(i);
<add>
<add> // Start running execution on each device
<add> for(int i=0;i<totalDevices;i++)
<add> threads[i].start();
<add> }
<ide> }
|
|
Java
|
isc
|
a758613bc7daa8b7def4a992c4e49582802c10f7
| 0 |
butzist/ActivityLauncher,butzist/ActivityLauncher,butzist/ActivityLauncher
|
package de.szalkowski.activitylauncher;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.ExpandableListContextMenuInfo;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import org.thirdparty.LauncherIconCreator;
public class AllTasksListFragment extends Fragment implements AllTasksListAsyncProvider.Listener<AllTasksListAdapter>, Filterable {
private ExpandableListView list;
AllTasksListFragment() {
super();
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_all_list, container, false);
this.list = view.findViewById(R.id.expandableListView1);
this.list.setOnChildClickListener(
(parent, v, groupPosition, childPosition, id) -> {
ExpandableListAdapter adapter = parent.getExpandableListAdapter();
MyActivityInfo info = (MyActivityInfo) adapter.getChild(groupPosition, childPosition);
LauncherIconCreator.launchActivity(getActivity(), info.component_name, false);
return false;
}
);
this.list.setTextFilterEnabled(true);
registerForContextMenu(this.list);
AllTasksListAsyncProvider provider = new AllTasksListAsyncProvider(getActivity(), this);
provider.execute();
return view;
}
@Override
public void onCreateContextMenu(@NonNull ContextMenu menu, @NonNull View v,
ContextMenuInfo menuInfo) {
menu.add(Menu.NONE, 0, Menu.NONE, R.string.context_action_shortcut);
menu.add(Menu.NONE, 1, Menu.NONE, R.string.context_action_launch);
menu.add(Menu.NONE, 2, Menu.NONE, R.string.context_action_launch_as_root);
ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo) menuInfo;
ExpandableListView list = requireView().findViewById(R.id.expandableListView1);
switch (ExpandableListView.getPackedPositionType(info.packedPosition)) {
case ExpandableListView.PACKED_POSITION_TYPE_CHILD:
MyActivityInfo activity = (MyActivityInfo) list.getExpandableListAdapter().getChild(ExpandableListView.getPackedPositionGroup(info.packedPosition), ExpandableListView.getPackedPositionChild(info.packedPosition));
menu.setHeaderIcon(activity.icon);
menu.setHeaderTitle(activity.name);
menu.add(Menu.NONE, 3, Menu.NONE, R.string.context_action_edit);
break;
case ExpandableListView.PACKED_POSITION_TYPE_GROUP:
MyPackageInfo pack = (MyPackageInfo) list.getExpandableListAdapter().getGroup(ExpandableListView.getPackedPositionGroup(info.packedPosition));
menu.setHeaderIcon(pack.icon);
menu.setHeaderTitle(pack.name);
break;
}
super.onCreateContextMenu(menu, v, menuInfo);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo) item.getMenuInfo();
ExpandableListView list = requireView().findViewById(R.id.expandableListView1);
switch (ExpandableListView.getPackedPositionType(info.packedPosition)) {
case ExpandableListView.PACKED_POSITION_TYPE_CHILD:
MyActivityInfo activity = (MyActivityInfo) list.getExpandableListAdapter().getChild(ExpandableListView.getPackedPositionGroup(info.packedPosition), ExpandableListView.getPackedPositionChild(info.packedPosition));
switch (item.getItemId()) {
case 0:
LauncherIconCreator.createLauncherIcon(getActivity(), activity);
break;
case 1:
LauncherIconCreator.launchActivity(getActivity(), activity.component_name, false);
break;
case 2:
LauncherIconCreator.launchActivity(getActivity(), activity.component_name, true);
break;
case 3:
DialogFragment dialog = new ShortcutEditDialogFragment();
Bundle args = new Bundle();
args.putParcelable("activity", activity.component_name);
dialog.setArguments(args);
dialog.show(getChildFragmentManager(), "ShortcutEditor");
break;
}
break;
case ExpandableListView.PACKED_POSITION_TYPE_GROUP:
MyPackageInfo pack = (MyPackageInfo) list.getExpandableListAdapter().getGroup(ExpandableListView.getPackedPositionGroup(info.packedPosition));
switch (item.getItemId()) {
case 0:
LauncherIconCreator.createLauncherIcon(requireActivity(), pack);
Toast.makeText(getActivity(), getString(R.string.error_no_default_activity), Toast.LENGTH_LONG).show();
break;
case 1:
PackageManager pm = requireActivity().getPackageManager();
Intent intent = pm.getLaunchIntentForPackage(pack.package_name);
if (intent != null) {
Toast.makeText(getActivity(), String.format(getText(R.string.starting_application).toString(), pack.name), Toast.LENGTH_LONG).show();
requireActivity().startActivity(intent);
} else {
Toast.makeText(getActivity(), getString(R.string.error_no_default_activity), Toast.LENGTH_LONG).show();
}
break;
}
}
return super.onContextItemSelected(item);
}
@Override
public void onProviderFinished(AsyncProvider<AllTasksListAdapter> task, AllTasksListAdapter value) {
try {
this.list.setAdapter(value);
} catch (Exception e) {
Toast.makeText(getActivity(), R.string.error_tasks, Toast.LENGTH_SHORT).show();
}
}
@Override
public Filter getFilter() {
AllTasksListAdapter adapter = (AllTasksListAdapter) this.list.getExpandableListAdapter();
if (adapter != null) {
return adapter.getFilter();
} else {
return null;
}
}
}
|
ActivityLauncherApp/src/main/java/de/szalkowski/activitylauncher/AllTasksListFragment.java
|
package de.szalkowski.activitylauncher;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.ExpandableListContextMenuInfo;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import org.thirdparty.LauncherIconCreator;
public class AllTasksListFragment extends Fragment implements AllTasksListAsyncProvider.Listener<AllTasksListAdapter>, Filterable {
private ExpandableListView list;
AllTasksListFragment() {
super();
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_all_list, container, false);
this.list = view.findViewById(R.id.expandableListView1);
this.list.setOnChildClickListener(
(parent, v, groupPosition, childPosition, id) -> {
ExpandableListAdapter adapter = parent.getExpandableListAdapter();
MyActivityInfo info = (MyActivityInfo) adapter.getChild(groupPosition, childPosition);
LauncherIconCreator.launchActivity(getActivity(), info.component_name, false);
return false;
}
);
this.list.setTextFilterEnabled(true);
AllTasksListAsyncProvider provider = new AllTasksListAsyncProvider(getActivity(), this);
provider.execute();
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
registerForContextMenu(this.list);
}
@Override
public void onCreateContextMenu(@NonNull ContextMenu menu, @NonNull View v,
ContextMenuInfo menuInfo) {
menu.add(Menu.NONE, 0, Menu.NONE, R.string.context_action_shortcut);
menu.add(Menu.NONE, 1, Menu.NONE, R.string.context_action_launch);
menu.add(Menu.NONE, 2, Menu.NONE, R.string.context_action_launch_as_root);
ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo) menuInfo;
ExpandableListView list = requireView().findViewById(R.id.expandableListView1);
switch (ExpandableListView.getPackedPositionType(info.packedPosition)) {
case ExpandableListView.PACKED_POSITION_TYPE_CHILD:
MyActivityInfo activity = (MyActivityInfo) list.getExpandableListAdapter().getChild(ExpandableListView.getPackedPositionGroup(info.packedPosition), ExpandableListView.getPackedPositionChild(info.packedPosition));
menu.setHeaderIcon(activity.icon);
menu.setHeaderTitle(activity.name);
menu.add(Menu.NONE, 3, Menu.NONE, R.string.context_action_edit);
break;
case ExpandableListView.PACKED_POSITION_TYPE_GROUP:
MyPackageInfo pack = (MyPackageInfo) list.getExpandableListAdapter().getGroup(ExpandableListView.getPackedPositionGroup(info.packedPosition));
menu.setHeaderIcon(pack.icon);
menu.setHeaderTitle(pack.name);
break;
}
super.onCreateContextMenu(menu, v, menuInfo);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo) item.getMenuInfo();
ExpandableListView list = requireView().findViewById(R.id.expandableListView1);
switch (ExpandableListView.getPackedPositionType(info.packedPosition)) {
case ExpandableListView.PACKED_POSITION_TYPE_CHILD:
MyActivityInfo activity = (MyActivityInfo) list.getExpandableListAdapter().getChild(ExpandableListView.getPackedPositionGroup(info.packedPosition), ExpandableListView.getPackedPositionChild(info.packedPosition));
switch (item.getItemId()) {
case 0:
LauncherIconCreator.createLauncherIcon(getActivity(), activity);
break;
case 1:
LauncherIconCreator.launchActivity(getActivity(), activity.component_name, false);
break;
case 2:
LauncherIconCreator.launchActivity(getActivity(), activity.component_name, true);
break;
case 3:
DialogFragment dialog = new ShortcutEditDialogFragment();
Bundle args = new Bundle();
args.putParcelable("activity", activity.component_name);
dialog.setArguments(args);
dialog.show(getChildFragmentManager(), "ShortcutEditor");
break;
}
break;
case ExpandableListView.PACKED_POSITION_TYPE_GROUP:
MyPackageInfo pack = (MyPackageInfo) list.getExpandableListAdapter().getGroup(ExpandableListView.getPackedPositionGroup(info.packedPosition));
switch (item.getItemId()) {
case 0:
LauncherIconCreator.createLauncherIcon(requireActivity(), pack);
Toast.makeText(getActivity(), getString(R.string.error_no_default_activity), Toast.LENGTH_LONG).show();
break;
case 1:
PackageManager pm = requireActivity().getPackageManager();
Intent intent = pm.getLaunchIntentForPackage(pack.package_name);
if (intent != null) {
Toast.makeText(getActivity(), String.format(getText(R.string.starting_application).toString(), pack.name), Toast.LENGTH_LONG).show();
requireActivity().startActivity(intent);
} else {
Toast.makeText(getActivity(), getString(R.string.error_no_default_activity), Toast.LENGTH_LONG).show();
}
break;
}
}
return super.onContextItemSelected(item);
}
@Override
public void onProviderFinished(AsyncProvider<AllTasksListAdapter> task, AllTasksListAdapter value) {
try {
this.list.setAdapter(value);
} catch (Exception e) {
Toast.makeText(getActivity(), R.string.error_tasks, Toast.LENGTH_SHORT).show();
}
}
@Override
public Filter getFilter() {
AllTasksListAdapter adapter = (AllTasksListAdapter) this.list.getExpandableListAdapter();
if (adapter != null) {
return adapter.getFilter();
} else {
return null;
}
}
}
|
chore: eliminate deprecation warning
|
ActivityLauncherApp/src/main/java/de/szalkowski/activitylauncher/AllTasksListFragment.java
|
chore: eliminate deprecation warning
|
<ide><path>ctivityLauncherApp/src/main/java/de/szalkowski/activitylauncher/AllTasksListFragment.java
<ide> }
<ide> );
<ide> this.list.setTextFilterEnabled(true);
<add> registerForContextMenu(this.list);
<ide>
<ide> AllTasksListAsyncProvider provider = new AllTasksListAsyncProvider(getActivity(), this);
<ide> provider.execute();
<ide>
<ide> return view;
<del> }
<del>
<del> @Override
<del> public void onActivityCreated(Bundle savedInstanceState) {
<del> super.onActivityCreated(savedInstanceState);
<del>
<del> registerForContextMenu(this.list);
<ide> }
<ide>
<ide> @Override
|
|
JavaScript
|
apache-2.0
|
c18e1687741ef3fbee53dbc0ef0f08ec5b7011ae
| 0 |
OADA/oada-formats
|
var _ = require('lodash');
var config = require('../config');
require('extend-error');
// Errors:
var UnknownVocabularyTerm = Error.extend('UnknownVocabularyTerm');
var NoPropertySchemaDefined = Error.extend('NoPropertySchemaDefined');
var NoPropertySchemaDefaultDefined = Error.extend('NoPropertySchemaDefaultDefined');
var NoPropertiesFound = Error.extend('NoPropertiesFound');
var NoModuleSpecified = Error.extend('NoModuleSpecified');
var modules = {};
module.exports = function(modulename) {
if (!modulename) throw new NoModuleSpecified('No modulename was given to main vocab function.');
if (modules[modulename]) return modules[modulename];
var _M = { // short for _Module
_vocab: {},
_registrationOrder: 0, // increment on each registration, store with term.
// enumSchema checks the global config for strictness. If not strict,
// returns a schema that matches a string. If strict, returns a schema
// that matches a string which can only be the known set of values. Also
// includes a custom key called 'known' which records the original set of
// known values regardless of the config setting.
//
// The parameter to enumSchema can be either an array, or an object which
// at least contains a 'known' key.
enumSchema: function (values) {
// first assume ret is already object with 'known':
var ret = values;
// if it's an array, replace with object that has 'known':
if (_.isArray(values)) { ret = { known: values }; }
// Make sure it has a type:
if (!ret.type) { ret.type = 'string' };
// Add enum if running in strict mode:
if (config.get('strict')) {
ret.enum = ret.known;
}
return ret;
},
// propertySchemaToProperties creates properties and patternProperties on
// a schema according to rules defined in the propertySchema key. It's purely
// a convenience to avoid having to write things twice above.
//
// It uses two extensions to JSONSchema that I made up:
// propertySchema defining what properties should look like, and
// propertySchemaDefault defining what schema to put at each property if
// the property name isn't a vocab term. Supports oneOf[] arrays to recursively set
// properties from a combination of propertySchemas.
// Note this function DOES NOT mutate the schema passed, it returns a new schema.
//
// This function is simplified by realizing that properties can only be strings
// in our case (not objects or arrays), so any propertySchema used above must
// either be an enumSchema or a string with a pattern.
propertySchemaToProperties: function (main_schema, opts) {
opts = opts || {};
main_schema = _.cloneDeep(main_schema);
var prop_default = main_schema.propertySchemaDefault;
var prop_schema = main_schema.propertySchema;
// you can optionally pass a different property schema:
if (opts.overridePropertySchema) {
prop_schema = opts.overridePropertySchema;
}
if (!prop_schema) {
throw new NoPropertySchemaDefined('propertySchemaToProperties was called on term ' + term + ', but it has no propertySchema defined');
}
// If it's got a oneOf key or anyOf key or allOf key, loop through each and recurse
// Look at geohash-length-index for example: the properties are a combination of
// a pattern (geohash-X) and a known vocab term (datum). This takes each individually
// as if it were the only propertySchema on this term_schema and adds those properties.
var arr;
if (prop_schema.oneOf) arr = prop_schema.oneOf;
if (prop_schema.anyOf) arr = prop_schema.anyOf;
if (prop_schema.allOf) arr = prop_schema.allOf;
if (arr) {
// loop through each schema in the array and set any properties or patternProperties
// that it warrants:
_.each(arr, function(individual_propertySchema) {
_M.propertySchemaToProperties(main_schema, {
overridePropertySchema: individual_propertySchema
});
});
}
// Now check for pattern first. patternProperties can only be set by the
// schema_for_each function parameter since patterns aren't vocab words.
if (prop_schema.pattern) {
if (!main_schema.patternProperties) main_schema.patternProperties = {};
if (!prop_default) {
throw new NoPropertySchemaDefaultDefined('A pattern-based property schema was found for id ' + term_schema.id + ', but no default schema was defined to put there.');
}
main_schema.patternProperties[prop_schema.pattern] = prop_default;
}
// Now check if this is an enumSchema with a 'known' key that may have vocab
// terms in it:
if (prop_schema.known) {
if (!main_schema.properties) main_schema.properties = {};
// loop through each 'known' thing and make it a property:
_.each(prop_schema.known, function(key) {
// first set to default schema:
if (prop_default) {
main_schema.properties[key] = prop_default;
}
// vocab term replaced prop_default if it exists
if (_M.vocab(key, { exists: true })) {
main_schema.properties[key] = _M.vocab(key);
}
if (!main_schema.properties[key]) {
throw new NoPropertySchemaDefaultDefined('A string property was found in schema ' + main_schema.id + ' that is not a vocab term ('+key+'), and no default schema was defined to put there.');
}
});
}
return main_schema;
},
// propertiesToPropertySchema is a convenience function that fills in the
// propertySchema for you if you defined all the properties.
// Doesn't work if you have a complex schema that contains allOf, anyOf, oneOf.
// NOTE: this DOES NOT mutate the schema passed, it returns a new schema.
propertiesToPropertySchema: function(main_schema) {
main_schema = _.cloneDeep(main_schema);
if (!main_schema.properties) {
throw new NoPropertiesFound('propertiesToPropertySchema called for id ' + main_schema.id + ', but it has no properties');
}
// Not supporting patternProperties for now because I don't see where I would ever
// need that.
main_schema.propertySchema = _M.enumSchema(_.keys(main_schema.properties));
return main_schema;
},
//--------------------------------------------------------------------
//--------------------------------------------------------------------
// Main export of this module: function to access _vocab information:
//--------------------------------------------------------------------
// Use a function to access vocab terms and schemas so we can copy each one
// as needed to prevent accidentally changing them.
// If nothing is passed, it returns the list of all known terms.
// You can have opts of:
// opts:
// - exists: true => return true or false if term exists
// - merge: { object } => merge this object into the resulting schema to override it
// - also: { schema } => returns allOf: [ vocab(term), schema ]
vocab: function (term, opts) {
opts = opts || {};
if (!term) { // if no term, return all known terms as an array of strings
return _.keys(_M._vocab);
}
if (typeof _M._vocab[term] === 'undefined') {
if (opts.exists) return false; // they just wanted to test for existence
throw new UnknownVocabularyTerm('The term "'+term+'" is not a known vocabulary term.');
}
if (opts.exists) return true; // they just wanted to test for existence
var ret = _.cloneDeep(_M._vocab[term]);
if (opts.merge) {
_.merge(ret, opts.merge);
// If changing the propertySchema or it's default, update the properties
// from the new propertySchema:
if (opts.merge.propertySchema || opts.merge.propertySchemaDefault) {
ret = _M.propertySchemaToProperties(ret);
}
}
// If there's an also schema, add it with allOf. Useful when
// restricting a schema to a subset of the main vocab's properties.
if (opts.also) {
ret = {
allOf: [ ret, opts.also ]
};
}
return ret;
},
// sameAs is just a wrapper for vocab that keeps you from having to
// write "merge" all the time up in the term definitions.
sameAs: function(term, merge) {
return _M.vocab(term, { merge: merge });
},
// register adds a term to the known vocabulary. You can have opts of:
// opts:
// - skipCreatingProperties: skips step which creates properties from the
// propertySchema if there is a propertySchema on the object.
// - skipCreatingPropertySchema: skips step which creates a propertySchema from the
// list of properties if there is not a propertySchema on the object.
register: function(term, schema, opts) {
opts = opts || {};
// Add the id to the schema:
if (!schema.id) {
schema.id = 'oada-formats://vocab/' + modulename + '/' + term;
}
// If it has a propertySchema, create properties with it:
if (schema.propertySchema && !opts.skipCreatingProperties) {
schema = _M.propertySchemaToProperties(schema)
}
// If it has no propertySchema, make one if possible:
if (!schema.propertySchema
&& schema.properties
&& !opts.skipCreatingPropertySchema) {
schema = _M.propertiesToPropertySchema(schema);
}
// Store original vocab source definition in the schema itself for reference later
schema.vocab = {
module: modulename,
term,
registrationOrder: _M._registrationOrder++,
};
// Store term in global vocab object:
_M._vocab[term] = schema;
},
};
modules[modulename] = _M;
return _M;
};
|
lib/vocab.js
|
var _ = require('lodash');
var config = require('../config');
require('extend-error');
// Errors:
var UnknownVocabularyTerm = Error.extend('UnknownVocabularyTerm');
var NoPropertySchemaDefined = Error.extend('NoPropertySchemaDefined');
var NoPropertySchemaDefaultDefined = Error.extend('NoPropertySchemaDefaultDefined');
var NoPropertiesFound = Error.extend('NoPropertiesFound');
var NoModuleSpecified = Error.extend('NoModuleSpecified');
var modules = {};
module.exports = function(modulename) {
if (!modulename) throw new NoModuleSpecified('No modulename was given to main vocab function.');
if (modules[modulename]) return modules[modulename];
var _M = { // short for _Module
_vocab: {},
_registrationOrder: 0, // increment on each registration, store with term.
// enumSchema checks the global config for strictness. If not strict,
// returns a schema that matches a string. If strict, returns a schema
// that matches a string which can only be the known set of values. Also
// includes a custom key called 'known' which records the original set of
// known values regardless of the config setting.
//
// The parameter to enumSchema can be either an array, or an object which
// at least contains a 'known' key.
enumSchema: function (values) {
// first assume ret is already object with 'known':
var ret = values;
// if it's an array, replace with object that has 'known':
if (_.isArray(values)) { ret = { known: values }; }
// Make sure it has a type:
if (!ret.type) { ret.type = 'string' };
// Add enum if running in strict mode:
if (config.get('strict')) {
ret.enum = ret.known;
}
return ret;
},
// propertySchemaToProperties creates properties and patternProperties on
// a schema according to rules defined in the propertySchema key. It's purely
// a convenience to avoid having to write things twice above.
//
// It uses two extensions to JSONSchema that I made up:
// propertySchema defining what properties should look like, and
// propertySchemaDefault defining what schema to put at each property if
// the property name isn't a vocab term. Supports oneOf[] arrays to recursively set
// properties from a combination of propertySchemas.
// Note this function DOES NOT mutate the schema passed, it returns a new schema.
//
// This function is simplified by realizing that properties can only be strings
// in our case (not objects or arrays), so any propertySchema used above must
// either be an enumSchema or a string with a pattern.
propertySchemaToProperties: function (main_schema, opts) {
opts = opts || {};
main_schema = _.cloneDeep(main_schema);
var prop_default = main_schema.propertySchemaDefault;
var prop_schema = main_schema.propertySchema;
// you can optionally pass a different property schema:
if (opts.overridePropertySchema) {
prop_schema = opts.overridePropertySchema;
}
if (!prop_schema) {
throw new NoPropertySchemaDefined('propertySchemaToProperties was called on term ' + term + ', but it has no propertySchema defined');
}
// If it's got a oneOf key or anyOf key or allOf key, loop through each and recurse
// Look at geohash-length-index for example: the properties are a combination of
// a pattern (geohash-X) and a known vocab term (datum). This takes each individually
// as if it were the only propertySchema on this term_schema and adds those properties.
var arr;
if (prop_schema.oneOf) arr = prop_schema.oneOf;
if (prop_schema.anyOf) arr = prop_schema.anyOf;
if (prop_schema.allOf) arr = prop_schema.allOf;
if (arr) {
// loop through each schema in the array and set any properties or patternProperties
// that it warrants:
_.each(arr, function(individual_propertySchema) {
_M.propertySchemaToProperties(main_schema, {
overridePropertySchema: individual_propertySchema
});
});
}
// Now check for pattern first. patternProperties can only be set by the
// schema_for_each function parameter since patterns aren't vocab words.
if (prop_schema.pattern) {
if (!main_schema.patternProperties) main_schema.patternProperties = {};
if (!prop_default) {
throw new NoPropertySchemaDefaultDefined('A pattern-based property schema was found for id ' + term_schema.id + ', but no default schema was defined to put there.');
}
main_schema.patternProperties[prop_schema.pattern] = prop_default;
}
// Now check if this is an enumSchema with a 'known' key that may have vocab
// terms in it:
if (prop_schema.known) {
if (!main_schema.properties) main_schema.properties = {};
// loop through each 'known' thing and make it a property:
_.each(prop_schema.known, function(key) {
// first set to default schema:
if (prop_default) {
main_schema.properties[key] = prop_default;
}
// vocab term replaced prop_default if it exists
if (_M.vocab(key, { exists: true })) {
main_schema.properties[key] = _M.vocab(key);
}
if (!main_schema.properties[key]) {
throw new NoPropertySchemaDefaultDefined('A string property was found in schema ' + main_schema.id + ' that is not a vocab term ('+key+'), and no default schema was defined to put there.');
}
});
}
return main_schema;
},
// propertiesToPropertySchema is a convenience function that fills in the
// propertySchema for you if you defined all the properties.
// Doesn't work if you have a complex schema that contains allOf, anyOf, oneOf.
// NOTE: this DOES NOT mutate the schema passed, it returns a new schema.
propertiesToPropertySchema: function(main_schema) {
main_schema = _.cloneDeep(main_schema);
if (!main_schema.properties) {
throw new NoPropertiesFound('propertiesToPropertySchema called for id ' + main_schema.id + ', but it has no properties');
}
// Not supporting patternProperties for now because I don't see where I would ever
// need that.
main_schema.propertySchema = _M.enumSchema(_.keys(main_schema.properties));
return main_schema;
},
//--------------------------------------------------------------------
//--------------------------------------------------------------------
// Main export of this module: function to access _vocab information:
//--------------------------------------------------------------------
// Use a function to access vocab terms and schemas so we can copy each one
// as needed to prevent accidentally changing them.
// If nothing is passed, it returns the list of all known terms.
// You can have opts of:
// opts:
// - exists: true => return true or false if term exists
// - merge: { object } => merge this object into the resulting schema to override it
// - also: { schema } => returns allOf: [ vocab(term), schema ]
vocab: function (term, opts) {
opts = opts || {};
if (!term) { // if no term, return all known terms as an array of strings
return _.keys(_M._vocab);
}
if (typeof _M._vocab[term] === 'undefined') {
if (opts.exists) return false; // they just wanted to test for existence
throw new UnknownVocabularyTerm('The term "'+term+'" is not a known vocabulary term.');
}
if (opts.exists) return true; // they just wanted to test for existence
var ret = _.cloneDeep(_M._vocab[term]);
if (opts.merge) {
_.merge(ret, opts.merge);
// If changing the propertySchema or it's default, update the properties
// from the new propertySchema:
if (opts.merge.propertySchema || opts.merge.propertySchemaDefault) {
ret = _M.propertySchemaToProperties(ret);
}
}
// If there's an also schema, add it with allOf. Useful when
// restricting a schema to a subset of the main vocab's properties.
if (opts.also) {
ret = {
allOf: [ ret, opts.also ]
};
}
return ret;
},
// sameAs is just a wrapper for vocab that keeps you from having to
// write "merge" all the time up in the term definitions.
sameAs: function(term, merge) {
return _M.vocab(term, { merge: merge });
},
// register adds a term to the known vocabulary. You can have opts of:
// opts:
// - skipCreatingProperties: skips step which creates properties from the
// propertySchema if there is a propertySchema on the object.
// - skipCreatingPropertySchema: skips step which creates a propertySchema from the
// list of properties if there is not a propertySchema on the object.
register: function(term, schema, opts) {
opts = opts || {};
// Add the id to the schema:
if (!schema.id) {
schema.id = 'oada-formats://vocab/' + modulename + '/' + term;
}
// If it has a propertySchema, create properties with it:
if (schema.propertySchema && !opts.skipCreatingProperties) {
schema = _M.propertySchemaToProperties(schema)
}
// If it has no propertySchema, make one if possible:
if (!schema.propertySchema
&& schema.properties
&& !opts.skipCreatingPropertySchema) {
schema = _M.propertiesToPropertySchema(schema);
}
// Store original vocab source definition in the schema itself for reference later
schema.vocab = {
module: modulename,
term,
registrationOrder: _M.registrationOrder++,
};
// Store term in global vocab object:
_M._vocab[term] = schema;
},
};
modules[modulename] = _M;
return _M;
};
|
forgot an underscore on _registrationOrder
|
lib/vocab.js
|
forgot an underscore on _registrationOrder
|
<ide><path>ib/vocab.js
<ide> schema.vocab = {
<ide> module: modulename,
<ide> term,
<del> registrationOrder: _M.registrationOrder++,
<add> registrationOrder: _M._registrationOrder++,
<ide> };
<ide>
<ide> // Store term in global vocab object:
|
|
JavaScript
|
apache-2.0
|
a79ee01004c25d8d336e66223f8604bf4f1cd0b8
| 0 |
binary-com/binary-static,raunakkathuria/binary-static,ashkanx/binary-static,kellybinary/binary-static,binary-com/binary-static,4p00rv/binary-static,4p00rv/binary-static,binary-com/binary-static,kellybinary/binary-static,kellybinary/binary-static,ashkanx/binary-static,raunakkathuria/binary-static,raunakkathuria/binary-static,negar-binary/binary-static,binary-static-deployed/binary-static,negar-binary/binary-static,binary-static-deployed/binary-static,negar-binary/binary-static,4p00rv/binary-static,ashkanx/binary-static,binary-static-deployed/binary-static
|
const BinaryPjax = require('./binary_pjax');
const pages_config = require('./binary_pages');
const Client = require('./client');
const GTM = require('./gtm');
const localize = require('./localize').localize;
const Login = require('./login');
const Page = require('./page');
const defaultRedirectUrl = require('./url').defaultRedirectUrl;
const BinarySocket = require('../websocket_pages/socket');
const BinarySocketGeneral = require('../websocket_pages/socket_general');
const BinaryLoader = (() => {
'use strict';
let container,
active_script = null;
const init = () => {
if (!/\.html$/i.test(window.location.pathname)) {
window.location.pathname += '.html';
return;
}
Client.init();
BinarySocket.init(BinarySocketGeneral.initOptions());
container = $('#content-holder');
container.on('binarypjax:before', beforeContentChange);
container.on('binarypjax:after', afterContentChange);
BinaryPjax.init(container, '#content');
};
const beforeContentChange = () => {
if (active_script) {
Page.onUnload();
BinarySocket.removeOnDisconnect();
if (typeof active_script.onUnload === 'function') {
active_script.onUnload();
}
active_script = null;
}
};
const afterContentChange = (e, content) => {
Page.onLoad();
GTM.pushDataLayer();
const this_page = content.getAttribute('data-page');
if (this_page in pages_config) {
loadHandler(pages_config[this_page]);
} else if (/\/get-started\//i.test(window.location.pathname)) {
loadHandler(pages_config['get-started']);
}
};
const error_messages = {
login : () => localize('Please <a href="[_1]">log in</a> to view this page.', [`${'java'}${'script:;'}`]),
only_virtual: 'Sorry, this feature is available to virtual accounts only.',
only_real : 'This feature is not relevant to virtual-money accounts.',
};
const loadHandler = (config) => {
active_script = config.module;
if (config.is_authenticated) {
if (!Client.isLoggedIn()) {
displayMessage(error_messages.login());
} else {
BinarySocket.wait('authorize')
.then((response) => {
if (response.error) {
displayMessage(error_messages.login());
} else if (config.only_virtual && !Client.get('is_virtual')) {
displayMessage(error_messages.only_virtual);
} else if (config.only_real && Client.get('is_virtual')) {
displayMessage(error_messages.only_real);
} else {
loadActiveScript();
}
});
}
} else if (config.not_authenticated && Client.isLoggedIn()) {
BinaryPjax.load(defaultRedirectUrl(), true);
} else {
loadActiveScript();
}
BinarySocket.setOnDisconnect(active_script.onDisconnect);
};
const loadActiveScript = () => {
if (Login.isLoginPages()) {
active_script.onLoad();
} else {
BinarySocket.wait('website_status').then(() => {
if (active_script && typeof active_script.onLoad === 'function') {
active_script.onLoad();
}
});
}
};
const displayMessage = (message) => {
const $content = container.find('#content .container');
$content.html($('<div/>', { class: 'logged_out_title_container', html: $content.find('h1')[0] }))
.append($('<p/>', { class: 'center-text notice-msg', html: localize(message) }));
$content.find('a').on('click', () => { Login.redirectToLogin(); });
};
return {
init: init,
};
})();
module.exports = BinaryLoader;
|
src/javascript/binary/base/binary_loader.js
|
const BinaryPjax = require('./binary_pjax');
const pages_config = require('./binary_pages');
const Client = require('./client');
const GTM = require('./gtm');
const localize = require('./localize').localize;
const Login = require('./login');
const Page = require('./page');
const defaultRedirectUrl = require('./url').defaultRedirectUrl;
const BinarySocket = require('../websocket_pages/socket');
const BinarySocketGeneral = require('../websocket_pages/socket_general');
const BinaryLoader = (() => {
'use strict';
let container,
active_script = null;
const init = () => {
if (!/\.html$/i.test(window.location.pathname)) {
window.location.pathname += '.html';
return;
}
Client.init();
BinarySocket.init(BinarySocketGeneral.initOptions());
container = $('#content-holder');
container.on('binarypjax:before', beforeContentChange);
container.on('binarypjax:after', afterContentChange);
BinaryPjax.init(container, '#content');
};
const beforeContentChange = () => {
if (active_script) {
Page.onUnload();
BinarySocket.removeOnDisconnect();
if (typeof active_script.onUnload === 'function') {
active_script.onUnload();
}
active_script = null;
}
};
const afterContentChange = (e, content) => {
Page.onLoad();
GTM.pushDataLayer();
const this_page = content.getAttribute('data-page');
if (this_page in pages_config) {
loadHandler(pages_config[this_page]);
} else if (/\/get-started\//i.test(window.location.pathname)) {
loadHandler(pages_config['get-started']);
}
};
const error_messages = {
login : () => localize('Please <a href="[_1]">log in</a> to view this page.', [`${'java'}${'script:;'}`]),
only_virtual: 'Sorry, this feature is available to virtual accounts only.',
only_real : 'This feature is not relevant to virtual-money accounts.',
};
const loadHandler = (config) => {
active_script = config.module;
if (config.is_authenticated) {
if (!Client.isLoggedIn()) {
displayMessage(error_messages.login());
} else {
BinarySocket.wait('authorize')
.then((response) => {
if (response.error) {
displayMessage(error_messages.login());
} else if (config.only_virtual && !Client.get('is_virtual')) {
displayMessage(error_messages.only_virtual);
} else if (config.only_real && Client.get('is_virtual')) {
displayMessage(error_messages.only_real);
} else {
loadActiveScript();
}
});
}
} else if (config.not_authenticated && Client.isLoggedIn()) {
BinaryPjax.load(defaultRedirectUrl(), true);
} else {
loadActiveScript();
}
BinarySocket.setOnDisconnect(active_script.onDisconnect);
};
const loadActiveScript = () => {
if (Login.isLoginPages()) {
active_script.onLoad();
} else {
BinarySocket.wait('website_status').then(() => {
active_script.onLoad();
});
}
};
const displayMessage = (message) => {
const $content = container.find('#content .container');
$content.html($('<div/>', { class: 'logged_out_title_container', html: $content.find('h1')[0] }))
.append($('<p/>', { class: 'center-text notice-msg', html: localize(message) }));
$content.find('a').on('click', () => { Login.redirectToLogin(); });
};
return {
init: init,
};
})();
module.exports = BinaryLoader;
|
Fix the error with navigating to no-script page before response
|
src/javascript/binary/base/binary_loader.js
|
Fix the error with navigating to no-script page before response
|
<ide><path>rc/javascript/binary/base/binary_loader.js
<ide> active_script.onLoad();
<ide> } else {
<ide> BinarySocket.wait('website_status').then(() => {
<del> active_script.onLoad();
<add> if (active_script && typeof active_script.onLoad === 'function') {
<add> active_script.onLoad();
<add> }
<ide> });
<ide> }
<ide> };
|
|
Java
|
mpl-2.0
|
d634ba347b3f525860fb1107d40a5f317a67b629
| 0 |
Subterranean-Security/Sandpolis,Subterranean-Security/Sandpolis,Subterranean-Security/Sandpolis,Subterranean-Security/Sandpolis,Subterranean-Security/Sandpolis,Subterranean-Security/Sandpolis,Subterranean-Security/Sandpolis,Subterranean-Security/Sandpolis
|
/******************************************************************************
* *
* Copyright 2019 Subterranean Security *
* *
* 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.sandpolis.viewer.jfx.common.pane;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.testfx.assertions.api.Assertions.assertThat;
import java.util.function.Supplier;
import java.util.prefs.Preferences;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.testfx.api.FxRobot;
import org.testfx.framework.junit5.ApplicationExtension;
import org.testfx.framework.junit5.Start;
import com.sandpolis.core.instance.store.pref.PrefStore;
import com.sandpolis.viewer.jfx.PrefConstant.ui;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.stage.Stage;
@ExtendWith(ApplicationExtension.class)
class CarouselPaneTest {
private static void waitCondition(Supplier<Boolean> condition, int timeout) throws InterruptedException {
int waited = 0;
while(!condition.get()) {
if (waited >= timeout)
throw new RuntimeException();
Thread.sleep(100);
waited += 100;
}
}
@BeforeAll
private static void init() throws Exception {
PrefStore.init(Preferences.userNodeForPackage(CarouselPaneTest.class));
PrefStore.register(ui.animations, true);
System.setProperty("java.awt.headless", "true");
System.setProperty("testfx.headless", "true");
System.setProperty("testfx.robot", "glass");
System.setProperty("prism.order", "sw");
}
private Label view1;
private Label view2;
private Label view3;
private CarouselPane carousel;
@Start
private void start(Stage stage) {
view1 = new Label("1");
view1.setId("view1");
view2 = new Label("2");
view2.setId("view2");
view3 = new Label("3");
view3.setId("view3");
carousel = new CarouselPane("left", 100, view1, view2, view3);
stage.setScene(new Scene(carousel, 100, 100));
stage.show();
}
@Test
@DisplayName("Try to construct a CarouselPane with an invalid direction")
void carouselPane_1() {
assertThrows(IllegalArgumentException.class, () -> new CarouselPane("invalid", 100, new Label()));
}
@Test
@DisplayName("Try to construct a CarouselPane with an invalid duration")
void carouselPane_2() {
assertThrows(IllegalArgumentException.class, () -> new CarouselPane("invalid", -1, new Label()));
}
@Test
@DisplayName("Test a multi-view carousel")
void carouselPane_3(FxRobot robot) throws Exception {
assertFalse(carousel.isMoving());
assertThat(carousel).hasChild("#view1");
assertThat(carousel).doesNotHaveChild("#view2");
assertThat(carousel).doesNotHaveChild("#view3");
// Move view and check state
robot.interact(() -> carousel.moveForward());
waitCondition(() -> !carousel.isMoving(), 5000);
assertThat(carousel).doesNotHaveChild("#view1");
assertThat(carousel).hasChild("#view2");
assertThat(carousel).doesNotHaveChild("#view3");
// Move view and check state
robot.interact(() -> carousel.moveForward());
waitCondition(() -> !carousel.isMoving(), 5000);
assertThat(carousel).doesNotHaveChild("#view1");
assertThat(carousel).doesNotHaveChild("#view2");
assertThat(carousel).hasChild("#view3");
// Move view and check state
robot.interact(() -> carousel.moveBackward());
waitCondition(() -> !carousel.isMoving(), 5000);
assertThat(carousel).doesNotHaveChild("#view1");
assertThat(carousel).hasChild("#view2");
assertThat(carousel).doesNotHaveChild("#view3");
// Move view and check state
robot.interact(() -> carousel.moveBackward());
waitCondition(() -> !carousel.isMoving(), 5000);
assertThat(carousel).hasChild("#view1");
assertThat(carousel).doesNotHaveChild("#view2");
assertThat(carousel).doesNotHaveChild("#view3");
}
}
|
com.sandpolis.viewer.jfx/src/test/java/com/sandpolis/viewer/jfx/common/pane/CarouselPaneTest.java
|
/******************************************************************************
* *
* Copyright 2019 Subterranean Security *
* *
* 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.sandpolis.viewer.jfx.common.pane;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.testfx.assertions.api.Assertions.assertThat;
import java.util.prefs.Preferences;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.testfx.api.FxRobot;
import org.testfx.framework.junit5.ApplicationExtension;
import org.testfx.framework.junit5.Start;
import com.sandpolis.core.instance.store.pref.PrefStore;
import com.sandpolis.viewer.jfx.PrefConstant.ui;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.stage.Stage;
@ExtendWith(ApplicationExtension.class)
class CarouselPaneTest {
@BeforeAll
private static void init() throws Exception {
PrefStore.init(Preferences.userNodeForPackage(CarouselPaneTest.class));
PrefStore.register(ui.animations, true);
System.setProperty("java.awt.headless", "true");
System.setProperty("testfx.headless", "true");
System.setProperty("testfx.robot", "glass");
System.setProperty("prism.order", "sw");
}
private Label view1;
private Label view2;
private Label view3;
private CarouselPane carousel;
@Start
private void start(Stage stage) {
view1 = new Label("1");
view1.setId("view1");
view2 = new Label("2");
view2.setId("view2");
view3 = new Label("3");
view3.setId("view3");
carousel = new CarouselPane("left", 100, view1, view2, view3);
stage.setScene(new Scene(carousel, 100, 100));
stage.show();
}
@Test
@DisplayName("Try to construct a CarouselPane with an invalid direction")
void carouselPane_1() {
assertThrows(IllegalArgumentException.class, () -> new CarouselPane("invalid", 100, new Label()));
}
@Test
@DisplayName("Try to construct a CarouselPane with an invalid duration")
void carouselPane_2() {
assertThrows(IllegalArgumentException.class, () -> new CarouselPane("invalid", -1, new Label()));
}
@Test
@DisplayName("Test a multi-view carousel")
void carouselPane_3(FxRobot robot) throws Exception {
assertFalse(carousel.isMoving());
assertThat(carousel).hasChild("#view1");
assertThat(carousel).doesNotHaveChild("#view2");
assertThat(carousel).doesNotHaveChild("#view3");
// Move view and wait
Platform.runLater(() -> carousel.moveForward());
// TODO check state
}
}
|
Check carousel state in unit test
|
com.sandpolis.viewer.jfx/src/test/java/com/sandpolis/viewer/jfx/common/pane/CarouselPaneTest.java
|
Check carousel state in unit test
|
<ide><path>om.sandpolis.viewer.jfx/src/test/java/com/sandpolis/viewer/jfx/common/pane/CarouselPaneTest.java
<ide> import static org.junit.jupiter.api.Assertions.assertThrows;
<ide> import static org.testfx.assertions.api.Assertions.assertThat;
<ide>
<add>import java.util.function.Supplier;
<ide> import java.util.prefs.Preferences;
<ide>
<ide> import org.junit.jupiter.api.BeforeAll;
<ide>
<ide> @ExtendWith(ApplicationExtension.class)
<ide> class CarouselPaneTest {
<add>
<add> private static void waitCondition(Supplier<Boolean> condition, int timeout) throws InterruptedException {
<add> int waited = 0;
<add> while(!condition.get()) {
<add> if (waited >= timeout)
<add> throw new RuntimeException();
<add> Thread.sleep(100);
<add> waited += 100;
<add> }
<add> }
<ide>
<ide> @BeforeAll
<ide> private static void init() throws Exception {
<ide> assertThat(carousel).doesNotHaveChild("#view2");
<ide> assertThat(carousel).doesNotHaveChild("#view3");
<ide>
<del> // Move view and wait
<del> Platform.runLater(() -> carousel.moveForward());
<add> // Move view and check state
<add> robot.interact(() -> carousel.moveForward());
<add> waitCondition(() -> !carousel.isMoving(), 5000);
<add> assertThat(carousel).doesNotHaveChild("#view1");
<add> assertThat(carousel).hasChild("#view2");
<add> assertThat(carousel).doesNotHaveChild("#view3");
<ide>
<del> // TODO check state
<add> // Move view and check state
<add> robot.interact(() -> carousel.moveForward());
<add> waitCondition(() -> !carousel.isMoving(), 5000);
<add> assertThat(carousel).doesNotHaveChild("#view1");
<add> assertThat(carousel).doesNotHaveChild("#view2");
<add> assertThat(carousel).hasChild("#view3");
<add>
<add> // Move view and check state
<add> robot.interact(() -> carousel.moveBackward());
<add> waitCondition(() -> !carousel.isMoving(), 5000);
<add> assertThat(carousel).doesNotHaveChild("#view1");
<add> assertThat(carousel).hasChild("#view2");
<add> assertThat(carousel).doesNotHaveChild("#view3");
<add>
<add> // Move view and check state
<add> robot.interact(() -> carousel.moveBackward());
<add> waitCondition(() -> !carousel.isMoving(), 5000);
<add> assertThat(carousel).hasChild("#view1");
<add> assertThat(carousel).doesNotHaveChild("#view2");
<add> assertThat(carousel).doesNotHaveChild("#view3");
<ide> }
<ide>
<ide> }
|
|
Java
|
lgpl-2.1
|
288ed86b204274cf2a7508aaea96c74e4d1d7cf3
| 0 |
pbondoer/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,xwiki/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.webjars.internal;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.apache.tika.Tika;
import org.xwiki.component.annotation.Component;
import org.xwiki.container.Container;
import org.xwiki.container.Request;
import org.xwiki.container.Response;
import org.xwiki.container.servlet.ServletRequest;
import org.xwiki.container.servlet.ServletResponse;
import org.xwiki.resource.AbstractResourceReferenceHandler;
import org.xwiki.resource.ResourceReference;
import org.xwiki.resource.ResourceReferenceHandlerChain;
import org.xwiki.resource.ResourceReferenceHandlerException;
import org.xwiki.resource.entity.EntityResourceAction;
import org.xwiki.velocity.VelocityManager;
/**
* Handles {@code webjars} Resource References.
* <p>
* At the moment we're mapping calls to the "webjars" URL as an EntityResourceReference.
* In the future it would be cleaner to register some new URL factory instead of reusing the format for Entity
* Resources and have some URL of the type {@code http://server/context/webjars?resource=(resourceName)}.
* Since we don't have this now and we're using the Entity Resource Reference URL format we're using the following URL
* format:
* <code>
* http://server/context/bin/webjars/resource/path?value=(resource name)
* </code>
* (for example: http://localhost:8080/xwiki/bin/webjars/resource/path?value=angularjs/1.1.5/angular.js)
* So this means that the resource name will be parsed as a query string "value" parameter (with a fixed space of
* "resource" and a fixed page name of "path").
* </p>
*
* @version $Id$
* @since 6.1M2
*/
@Component
@Named("webjars")
@Singleton
public class WebJarsResourceReferenceHandler extends AbstractResourceReferenceHandler<EntityResourceAction>
{
/**
* The WebJars Action.
*/
public static final EntityResourceAction ACTION = new EntityResourceAction("webjars");
/**
* Prefix for locating resource files (JavaScript, CSS) in the classloader.
*/
private static final String WEBJARS_RESOURCE_PREFIX = "META-INF/resources/webjars/";
/**
* The encoding used when evaluating WebJar (text) resources.
*/
private static final String UTF8 = "UTF-8";
@Inject
private Container container;
/**
* Used to evaluate the Velocity code from the WebJar resources.
*/
@Inject
private VelocityManager velocityManager;
/**
* Used to determine the Content Type of the requested resource files.
*/
private Tika tika = new Tika();
@Override
public List<EntityResourceAction> getSupportedResourceReferences()
{
return Arrays.asList(ACTION);
}
@Override
public void handle(ResourceReference reference, ResourceReferenceHandlerChain chain)
throws ResourceReferenceHandlerException
{
if (!shouldBrowserUseCachedContent(reference)) {
String resourceName = reference.getParameterValue("value");
String resourcePath = String.format("%s%s", WEBJARS_RESOURCE_PREFIX, resourceName);
InputStream resourceStream = getClassLoader().getResourceAsStream(resourcePath);
if (resourceStream != null) {
if (shouldEvaluateResource(reference)) {
resourceStream = evaluate(resourceName, resourceStream);
}
// Make sure the resource stream supports mark & reset which is needed in order be able to detect the
// content type without affecting the stream (Tika may need to read a few bytes from the start of the
// stream, in which case it will mark & reset the stream).
if (!resourceStream.markSupported()) {
resourceStream = new BufferedInputStream(resourceStream);
}
try {
Response response = this.container.getResponse();
setResponseHeaders(response, reference);
response.setContentType(tika.detect(resourceStream, resourceName));
IOUtils.copy(resourceStream, this.container.getResponse().getOutputStream());
} catch (Exception e) {
throw new ResourceReferenceHandlerException(
String.format("Failed to read resource [%s]", resourceName), e);
} finally {
IOUtils.closeQuietly(resourceStream);
}
}
}
// Be a good citizen, continue the chain, in case some lower-priority Handler has something to do for this
// Resource Reference.
chain.handleNext(reference);
}
private void setResponseHeaders(Response response, ResourceReference reference)
{
// If the resource contains Velocity code then this code must be evaluated on each request and so the resource
// must not be cached. Otherwise, if the resource is static we need to send back the "Last-Modified" header in
// the response so that the browser will send us an "If-Modified-Since" request for any subsequent call for this
// static resource. When this happens we return a 304 to tell the browser to use its cached version.
if (response instanceof ServletResponse && !shouldEvaluateResource(reference)) {
HttpServletResponse httpResponse = ((ServletResponse) response).getHttpServletResponse();
httpResponse.setDateHeader("Last-Modified", new Date().getTime() / 1000 * 1000);
}
}
private boolean shouldBrowserUseCachedContent(ResourceReference reference)
{
// If the request contains a "If-Modified-Since" and the referenced resource is not supposed to be evaluated
// (i.e. no Velocity code) then return a 304 so to tell the browser to use its cached version.
Request request = this.container.getRequest();
if (request instanceof ServletRequest && !shouldEvaluateResource(reference)) {
HttpServletRequest httpRequest = ((ServletRequest) request).getHttpServletRequest();
if (httpRequest.getHeader("If-Modified-Since") != null) {
// Return the 304
Response response = this.container.getResponse();
if (response instanceof ServletResponse) {
HttpServletResponse httpResponse = ((ServletResponse) response).getHttpServletResponse();
httpResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
return true;
}
}
}
return false;
}
/**
* @param reference a resource reference
* @return {@code true} if the resource should be evaluated (e.g. if the resource has Velocity code), {@code false}
* otherwise
*/
private boolean shouldEvaluateResource(ResourceReference reference)
{
return Boolean.valueOf(reference.getParameterValue("evaluate"));
}
private InputStream evaluate(String resourceName, InputStream resourceStream)
throws ResourceReferenceHandlerException
{
try {
StringWriter writer = new StringWriter();
this.velocityManager.getVelocityEngine().evaluate(this.velocityManager.getVelocityContext(), writer,
resourceName, new InputStreamReader(resourceStream, UTF8));
return new ByteArrayInputStream(writer.toString().getBytes(UTF8));
} catch (Exception e) {
throw new ResourceReferenceHandlerException("Faild to evaluate the Velocity code from WebJar resource ["
+ resourceName + "]", e);
}
}
/**
* @return the Class Loader from which to look for WebJars resources
*/
protected ClassLoader getClassLoader()
{
// Load the resource from the context class loader in order to support webjars located in XWiki Extensions
// loaded by the Extension Manager.
return Thread.currentThread().getContextClassLoader();
}
}
|
xwiki-platform-core/xwiki-platform-webjars/src/main/java/org/xwiki/webjars/internal/WebJarsResourceReferenceHandler.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.webjars.internal;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.apache.tika.Tika;
import org.xwiki.component.annotation.Component;
import org.xwiki.container.Container;
import org.xwiki.container.Request;
import org.xwiki.container.Response;
import org.xwiki.container.servlet.ServletRequest;
import org.xwiki.container.servlet.ServletResponse;
import org.xwiki.resource.AbstractResourceReferenceHandler;
import org.xwiki.resource.ResourceReference;
import org.xwiki.resource.ResourceReferenceHandlerChain;
import org.xwiki.resource.ResourceReferenceHandlerException;
import org.xwiki.resource.entity.EntityResourceAction;
import org.xwiki.velocity.VelocityManager;
/**
* Handles {@code webjars} Resource References.
* <p>
* At the moment we're mapping calls to the "webjars" URL as an EntityResourceReference.
* In the future it would be cleaner to register some new URL factory instead of reusing the format for Entity
* Resources and have some URL of the type {@code http://server/context/webjars?resource=(resourceName)}.
* Since we don't have this now and we're using the Entity Resource Reference URL format we're using the following URL
* format:
* <code>
* http://server/context/bin/webjars/resource/path?value=(resource name)
* </code>
* (for example: http://localhost:8080/xwiki/bin/webjars/resource/path?value=angularjs/1.1.5/angular.js)
* So this means that the resource name will be parsed as a query string "value" parameter (with a fixed space of
* "resource" and a fixed page name of "path").
* </p>
*
* @version $Id$
* @since 6.1M2
*/
@Component
@Named("webjars")
@Singleton
public class WebJarsResourceReferenceHandler extends AbstractResourceReferenceHandler<EntityResourceAction>
{
/**
* The WebJars Action.
*/
public static final EntityResourceAction ACTION = new EntityResourceAction("webjars");
/**
* Prefix for locating resource files (JavaScript, CSS) in the classloader.
*/
private static final String WEBJARS_RESOURCE_PREFIX = "META-INF/resources/webjars/";
/**
* The encoding used when evaluating WebJar (text) resources.
*/
private static final String UTF8 = "UTF-8";
@Inject
private Container container;
/**
* Used to evaluate the Velocity code from the WebJar resources.
*/
@Inject
private VelocityManager velocityManager;
/**
* Used to determine the Content Type of the requested resource files.
*/
private Tika tika = new Tika();
@Override
public List<EntityResourceAction> getSupportedResourceReferences()
{
return Arrays.asList(ACTION);
}
@Override
public void handle(ResourceReference reference, ResourceReferenceHandlerChain chain)
throws ResourceReferenceHandlerException
{
if (!shouldBrowserUseCachedContent(reference)) {
String resourceName = reference.getParameterValue("value");
String resourcePath = String.format("%s%s", WEBJARS_RESOURCE_PREFIX, resourceName);
InputStream resourceStream = getClassLoader().getResourceAsStream(resourcePath);
if (resourceStream != null) {
if (shouldEvaluateResource(reference)) {
resourceStream = evaluate(resourceName, resourceStream);
}
// Make sure the resource stream supports mark & reset which is needed in order be able to detect the
// content type without affecting the stream (Tika may need to read a few bytes from the start of the
// stream, in which case it will mark & reset the stream).
if (!resourceStream.markSupported()) {
resourceStream = new BufferedInputStream(resourceStream);
}
try {
Response response = this.container.getResponse();
setResponseHeaders(response, reference);
response.setContentType(tika.detect(resourceStream, resourceName));
IOUtils.copy(resourceStream, this.container.getResponse().getOutputStream());
} catch (Exception e) {
throw new ResourceReferenceHandlerException(
String.format("Failed to read resource [%s]", resourceName), e);
} finally {
IOUtils.closeQuietly(resourceStream);
}
}
}
// Be a good citizen, continue the chain, in case some lower-priority Handler has something to do for this
// Resource Reference.
chain.handleNext(reference);
}
private void setResponseHeaders(Response response, ResourceReference reference)
{
// Send back the "Last-Modified" header in the response so that the browser will send us an
// "If-Modified-Since" request for any subsequent call for this resource. When this happens we return
// a 304 to tell the browser to use its cached version.
if (!shouldEvaluateResource(reference) && response instanceof ServletResponse) {
HttpServletResponse httpResponse = ((ServletResponse) response).getHttpServletResponse();
httpResponse.setDateHeader("Last-Modified", new Date().getTime() / 1000 * 1000);
}
}
private boolean shouldBrowserUseCachedContent(ResourceReference reference)
{
// If the request contains a "If-Modified-Since" and the referenced resource is not supposed to be evaluated
// then return a 304 so to tell the browser to use its cached version.
Request request = this.container.getRequest();
if (!shouldEvaluateResource(reference) && request instanceof ServletRequest) {
HttpServletRequest httpRequest = ((ServletRequest) request).getHttpServletRequest();
if (httpRequest.getHeader("If-Modified-Since") != null) {
// Return the 304
Response response = this.container.getResponse();
if (response instanceof ServletResponse) {
HttpServletResponse httpResponse = ((ServletResponse) response).getHttpServletResponse();
httpResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
return true;
}
}
}
return false;
}
/**
* @param reference a resource reference
* @return {@code true} if the resource should be evaluated (e.g. if the resource has Velocity code), {@code false}
* otherwise
*/
private boolean shouldEvaluateResource(ResourceReference reference)
{
return Boolean.valueOf(reference.getParameterValue("evaluate"));
}
private InputStream evaluate(String resourceName, InputStream resourceStream)
throws ResourceReferenceHandlerException
{
try {
StringWriter writer = new StringWriter();
this.velocityManager.getVelocityEngine().evaluate(this.velocityManager.getVelocityContext(), writer,
resourceName, new InputStreamReader(resourceStream, UTF8));
return new ByteArrayInputStream(writer.toString().getBytes(UTF8));
} catch (Exception e) {
throw new ResourceReferenceHandlerException("Faild to evaluate the Velocity code from WebJar resource ["
+ resourceName + "]", e);
}
}
/**
* @return the Class Loader from which to look for WebJars resources
*/
protected ClassLoader getClassLoader()
{
// Load the resource from the context class loader in order to support webjars located in XWiki Extensions
// loaded by the Extension Manager.
return Thread.currentThread().getContextClassLoader();
}
}
|
XWIKI-11372: Add support for evaluating WebJar resources that contain Velocity code
* Improve the test and the comments (thanks to Vincent)
|
xwiki-platform-core/xwiki-platform-webjars/src/main/java/org/xwiki/webjars/internal/WebJarsResourceReferenceHandler.java
|
XWIKI-11372: Add support for evaluating WebJar resources that contain Velocity code * Improve the test and the comments (thanks to Vincent)
|
<ide><path>wiki-platform-core/xwiki-platform-webjars/src/main/java/org/xwiki/webjars/internal/WebJarsResourceReferenceHandler.java
<ide>
<ide> private void setResponseHeaders(Response response, ResourceReference reference)
<ide> {
<del> // Send back the "Last-Modified" header in the response so that the browser will send us an
<del> // "If-Modified-Since" request for any subsequent call for this resource. When this happens we return
<del> // a 304 to tell the browser to use its cached version.
<del> if (!shouldEvaluateResource(reference) && response instanceof ServletResponse) {
<add> // If the resource contains Velocity code then this code must be evaluated on each request and so the resource
<add> // must not be cached. Otherwise, if the resource is static we need to send back the "Last-Modified" header in
<add> // the response so that the browser will send us an "If-Modified-Since" request for any subsequent call for this
<add> // static resource. When this happens we return a 304 to tell the browser to use its cached version.
<add> if (response instanceof ServletResponse && !shouldEvaluateResource(reference)) {
<ide> HttpServletResponse httpResponse = ((ServletResponse) response).getHttpServletResponse();
<ide> httpResponse.setDateHeader("Last-Modified", new Date().getTime() / 1000 * 1000);
<ide> }
<ide> private boolean shouldBrowserUseCachedContent(ResourceReference reference)
<ide> {
<ide> // If the request contains a "If-Modified-Since" and the referenced resource is not supposed to be evaluated
<del> // then return a 304 so to tell the browser to use its cached version.
<add> // (i.e. no Velocity code) then return a 304 so to tell the browser to use its cached version.
<ide> Request request = this.container.getRequest();
<del> if (!shouldEvaluateResource(reference) && request instanceof ServletRequest) {
<add> if (request instanceof ServletRequest && !shouldEvaluateResource(reference)) {
<ide> HttpServletRequest httpRequest = ((ServletRequest) request).getHttpServletRequest();
<ide> if (httpRequest.getHeader("If-Modified-Since") != null) {
<ide> // Return the 304
|
|
Java
|
apache-2.0
|
error: pathspec 'validation/src/main/java/net/sf/mmm/util/validation/api/Validatable.java' did not match any file(s) known to git
|
a7fefceeb460589456b2c3e9407d445eacd8915c
| 1 |
m-m-m/util,m-m-m/util
|
/* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0
* http://www.apache.org/licenses/LICENSE-2.0 */
package net.sf.mmm.util.validation.api;
/**
* This is the abstract interface for an object, that can be {@link #validate() validated}.<br>
* <b>NOTE:</b> It is a simpler and more convenient API than {@link AbstractValidatableObject} and
* {@link ValidatableObject}.
*
* @author Joerg Hohwiller (hohwille at users.sourceforge.net)
* @since 7.4.0
*/
public abstract interface Validatable {
/**
* This method performs the actual validation.
*
* @see ValueValidator#validate(Object)
*
* @return {@link ValidationFailure} the validation failure.
*/
ValidationFailure validate();
}
|
validation/src/main/java/net/sf/mmm/util/validation/api/Validatable.java
|
#211: added Validatable interface
|
validation/src/main/java/net/sf/mmm/util/validation/api/Validatable.java
|
#211: added Validatable interface
|
<ide><path>alidation/src/main/java/net/sf/mmm/util/validation/api/Validatable.java
<add>/* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0
<add> * http://www.apache.org/licenses/LICENSE-2.0 */
<add>package net.sf.mmm.util.validation.api;
<add>
<add>/**
<add> * This is the abstract interface for an object, that can be {@link #validate() validated}.<br>
<add> * <b>NOTE:</b> It is a simpler and more convenient API than {@link AbstractValidatableObject} and
<add> * {@link ValidatableObject}.
<add> *
<add> * @author Joerg Hohwiller (hohwille at users.sourceforge.net)
<add> * @since 7.4.0
<add> */
<add>public abstract interface Validatable {
<add>
<add> /**
<add> * This method performs the actual validation.
<add> *
<add> * @see ValueValidator#validate(Object)
<add> *
<add> * @return {@link ValidationFailure} the validation failure.
<add> */
<add> ValidationFailure validate();
<add>
<add>}
|
|
Java
|
bsd-3-clause
|
d52932e40b66220113ff38eca45433cfe73f68df
| 0 |
oci-pronghorn/FogLight,oci-pronghorn/PronghornIoT,oci-pronghorn/PronghornIoT,oci-pronghorn/FogLight,oci-pronghorn/FogLight
|
package com.ociweb.oe.foglight.api;
import java.util.ArrayList;
import java.util.Random;
import com.ociweb.iot.maker.FogApp;
import com.ociweb.iot.maker.FogCommandChannel;
import com.ociweb.iot.maker.FogRuntime;
import com.ociweb.iot.maker.Hardware;
public class PubSub implements FogApp
{
ArrayList<Integer> luckyNums = new ArrayList<>();
Random rand = new Random();
public static int count = 0;
@Override
public void declareConnections(Hardware c) {
}
@Override
public void declareBehavior(FogRuntime runtime) {
final FogCommandChannel channel0 = runtime.newCommandChannel(DYNAMIC_MESSAGING);
runtime.addStartupListener(()->{
System.out.println("Your lucky numbers are ...");
channel0.publishTopic("Starter", writable->{});
});
final FogCommandChannel channel1 = runtime.newCommandChannel(DYNAMIC_MESSAGING);
runtime.addPubSubListener((topic, payload)-> {
int n = rand.nextInt(101);
luckyNums.add(n);
channel1.publishTopic("Gen", writable->{});
channel1.block(500);
return true;
}).addSubscription("Print").addSubscription("Starter");
final FogCommandChannel channel2 = runtime.newCommandChannel(DYNAMIC_MESSAGING);
runtime.addPubSubListener((topic, payload) -> {
System.out.print(luckyNums.get(count) + " ");
count++;
if(count<7){
channel2.publishTopic("Print", writable->{});
}
return true;
}).addSubscription("Gen");
}
}
|
PubSub/src/main/java/com/ociweb/oe/foglight/api/PubSub.java
|
package com.ociweb.oe.foglight.api;
import static com.ociweb.iot.grove.GroveTwig.*;
import com.ociweb.iot.maker.*;
import static com.ociweb.iot.maker.Port.*;
import java.util.ArrayList;
import java.util.Random;
public class PubSub implements FogApp
{
ArrayList<Integer> luckyNums = new ArrayList<>();
Random rand = new Random();
public static int count = 0;
@Override
public void declareConnections(Hardware c) {
}
@Override
public void declareBehavior(FogRuntime runtime) {
final FogCommandChannel channel0 = runtime.newCommandChannel(DYNAMIC_MESSAGING);
runtime.addStartupListener(()->{
System.out.println("Your lucky numbers are ...");
channel0.publishTopic("Starter", writable->{});
});
final FogCommandChannel channel1 = runtime.newCommandChannel(DYNAMIC_MESSAGING);
runtime.addPubSubListener((topic, payload)-> {
int n = rand.nextInt(101);
luckyNums.add(n);
channel1.publishTopic("Gen", writable->{});
channel1.block(500);
return true;
}).addSubscription("Print").addSubscription("Starter");
final FogCommandChannel channel2 = runtime.newCommandChannel(DYNAMIC_MESSAGING);
runtime.addPubSubListener((topic, payload) -> {
System.out.print(luckyNums.get(count) + " ");
count++;
if(count<7){
channel2.publishTopic("Print", writable->{});
}
return true;
}).addSubscription("Gen");
}
}
|
remove old imports
|
PubSub/src/main/java/com/ociweb/oe/foglight/api/PubSub.java
|
remove old imports
|
<ide><path>ubSub/src/main/java/com/ociweb/oe/foglight/api/PubSub.java
<ide> package com.ociweb.oe.foglight.api;
<del>
<del>import static com.ociweb.iot.grove.GroveTwig.*;
<del>import com.ociweb.iot.maker.*;
<del>import static com.ociweb.iot.maker.Port.*;
<ide>
<ide> import java.util.ArrayList;
<ide> import java.util.Random;
<add>
<add>import com.ociweb.iot.maker.FogApp;
<add>import com.ociweb.iot.maker.FogCommandChannel;
<add>import com.ociweb.iot.maker.FogRuntime;
<add>import com.ociweb.iot.maker.Hardware;
<ide>
<ide> public class PubSub implements FogApp
<ide> {
|
|
Java
|
lgpl-2.1
|
5430d6fc0a96d0d894c510e30d8e448edb6de0da
| 0 |
ebollens/ccnmp,cawka/ndnx,cawka/ndnx,cawka/ndnx,cawka/ndnx,svartika/ccnx,ebollens/ccnmp,ebollens/ccnmp,svartika/ccnx,svartika/ccnx,svartika/ccnx,cawka/ndnx,ebollens/ccnmp,svartika/ccnx,svartika/ccnx,svartika/ccnx
|
/**
* Part of the CCNx Java Library.
*
* Copyright (C) 2008, 2009, 2010 Palo Alto Research Center, Inc.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 2.1
* as published by the Free Software Foundation.
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. You should have received
* a copy of the GNU Lesser General Public License along with this library;
* if not, write to the Free Software Foundation, Inc., 51 Franklin Street,
* Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.ccnx.ccn.profiles;
import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.logging.Level;
import org.ccnx.ccn.CCNHandle;
import org.ccnx.ccn.ContentVerifier;
import org.ccnx.ccn.config.SystemConfiguration;
import org.ccnx.ccn.impl.support.Log;
import org.ccnx.ccn.impl.support.Tuple;
import org.ccnx.ccn.protocol.CCNTime;
import org.ccnx.ccn.protocol.ContentName;
import org.ccnx.ccn.protocol.ContentObject;
import org.ccnx.ccn.protocol.ExcludeAny;
import org.ccnx.ccn.protocol.ExcludeComponent;
import org.ccnx.ccn.protocol.Exclude;
import org.ccnx.ccn.protocol.Interest;
import org.ccnx.ccn.protocol.PublisherID;
import org.ccnx.ccn.protocol.PublisherPublicKeyDigest;
/**
* Versions, when present, usually occupy the penultimate component of the CCN name,
* not counting the digest component. A name may actually incorporate multiple
* versions, where the rightmost version is the version of "this" object, if it
* has one, and previous (parent) versions are the versions of the objects of
* which this object is a part. The most common location of a version, if present,
* is in the next to last component of the name, where the last component is a
* segment number (which is generally always present; versions themselves are
* optional). More complicated segmentation profiles occur, where a versioned
* object has components that are structured and named in ways other than segments --
* and may themselves have individual versions (e.g. if the components of such
* a composite object are written as CCNNetworkObjects and automatically pick
* up an (unnecessary) version in their own right). Versioning operations therefore
* take context from their caller about where to expect to find a version,
* and attempt to ignore other versions in the name.
*
* Versions may be chosen based on time.
* The first byte of the version component is 0xFD. The remaining bytes are a
* big-endian binary number. If based on time they are expressed in units of
* 2**(-12) seconds since the start of Unix time, using the minimum number of
* bytes. The time portion will thus take 48 bits until quite a few centuries
* from now (Sun, 20 Aug 4147 07:32:16 GMT). With 12 bits of precision, it allows
* for sub-millisecond resolution. The client generating the version stamp
* should try to avoid using a stamp earlier than (or the same as) any
* version of the file, to the extent that it knows about it. It should
* also avoid generating stamps that are unreasonably far in the future.
*/
public class VersioningProfile implements CCNProfile {
public static final byte VERSION_MARKER = (byte)0xFD;
public static final byte [] FIRST_VERSION_MARKER = new byte []{VERSION_MARKER};
public static final byte FF = (byte) 0xFF;
public static final byte OO = (byte) 0x00;
/**
* Add a version field to a ContentName.
* @return ContentName with a version appended. Does not affect previous versions.
*/
public static ContentName addVersion(ContentName name, long version) {
// Need a minimum-bytes big-endian representation of version.
byte [] vcomp = null;
if (0 == version) {
vcomp = FIRST_VERSION_MARKER;
} else {
byte [] varr = BigInteger.valueOf(version).toByteArray();
vcomp = new byte[varr.length + 1];
vcomp[0] = VERSION_MARKER;
System.arraycopy(varr, 0, vcomp, 1, varr.length);
}
return new ContentName(name, vcomp);
}
/**
* Converts a timestamp into a fixed point representation, with 12 bits in the fractional
* component, and adds this to the ContentName as a version field. The timestamp is rounded
* to the nearest value in the fixed point representation.
* <p>
* This allows versions to be recorded as a timestamp with a 1/4096 second accuracy.
* @see #addVersion(ContentName, long)
*/
public static ContentName addVersion(ContentName name, CCNTime version) {
if (null == version)
throw new IllegalArgumentException("Version cannot be null!");
byte [] vcomp = timeToVersionComponent(version);
return new ContentName(name, vcomp);
}
/**
* Add a version field based on the current time, accurate to 1/4096 second.
* @see #addVersion(ContentName, CCNTime)
*/
public static ContentName addVersion(ContentName name) {
return addVersion(name, CCNTime.now());
}
public static byte [] timeToVersionComponent(CCNTime version) {
byte [] varr = version.toBinaryTime();
byte [] vcomp = new byte[varr.length + 1];
vcomp[0] = VERSION_MARKER;
System.arraycopy(varr, 0, vcomp, 1, varr.length);
return vcomp;
}
public static String printAsVersionComponent(CCNTime version) {
byte [] vcomp = timeToVersionComponent(version);
return ContentName.componentPrintURI(vcomp);
}
/**
* Adds a version to a ContentName; if there is a terminal version there already,
* first removes it.
*/
public static ContentName updateVersion(ContentName name, long version) {
return addVersion(cutTerminalVersion(name).first(), version);
}
/**
* Adds a version to a ContentName; if there is a terminal version there already,
* first removes it.
*/
public static ContentName updateVersion(ContentName name, CCNTime version) {
return addVersion(cutTerminalVersion(name).first(), version);
}
/**
* Add updates the version field based on the current time, accurate to 1/4096 second.
* @see #updateVersion(ContentName, Timestamp)
*/
public static ContentName updateVersion(ContentName name) {
return updateVersion(name, CCNTime.now());
}
/**
* Finds the last component that looks like a version in name.
* @param name
* @return the index of the last version component in the name, or -1 if there is no version
* component in the name
*/
public static int findLastVersionComponent(ContentName name) {
int i = name.count();
for (;i >= 0; i--)
if (isVersionComponent(name.component(i)))
return i;
return -1;
}
/**
* Checks to see if this name has a validly formatted version field anywhere in it.
*/
public static boolean containsVersion(ContentName name) {
return findLastVersionComponent(name) != -1;
}
/**
* Checks to see if this name has a validly formatted version field either in final
* component or in next to last component with final component being a segment marker.
*/
public static boolean hasTerminalVersion(ContentName name) {
if ((name.count() > 0) &&
((isVersionComponent(name.lastComponent()) ||
((name.count() > 1) && SegmentationProfile.isSegment(name) && isVersionComponent(name.component(name.count()-2)))))) {
return true;
}
return false;
}
/**
* Check a name component to see if it is a valid version field
*/
public static boolean isVersionComponent(byte [] nameComponent) {
return (null != nameComponent) && (0 != nameComponent.length) &&
(VERSION_MARKER == nameComponent[0]) &&
((nameComponent.length == 1) || (nameComponent[1] != 0));
}
public static boolean isBaseVersionComponent(byte [] nameComponent) {
return (isVersionComponent(nameComponent) && (1 == nameComponent.length));
}
/**
* Remove a terminal version marker (one that is either the last component of name, or
* the next to last component of name followed by a segment marker) if one exists, otherwise
* return name as it was passed in.
* @param name
* @return
*/
public static Tuple<ContentName, byte[]> cutTerminalVersion(ContentName name) {
if (name.count() > 0) {
if (isVersionComponent(name.lastComponent())) {
return new Tuple<ContentName, byte []>(name.parent(), name.lastComponent());
} else if ((name.count() > 2) && SegmentationProfile.isSegment(name) && isVersionComponent(name.component(name.count()-2))) {
return new Tuple<ContentName, byte []>(name.cut(name.count()-2), name.component(name.count()-2));
}
}
return new Tuple<ContentName, byte []>(name, null);
}
/**
* Take a name which may have one or more version components in it,
* and strips the last one and all following components. If no version components
* present, returns the name as handed in.
*/
public static ContentName cutLastVersion(ContentName name) {
int offset = findLastVersionComponent(name);
return (offset == -1) ? name : new ContentName(offset, name.components());
}
/**
* Function to get the version field as a long. Starts from the end and checks each name component for the version marker.
* @param name
* @return long
* @throws VersionMissingException
*/
public static long getLastVersionAsLong(ContentName name) throws VersionMissingException {
int i = findLastVersionComponent(name);
if (i == -1)
throw new VersionMissingException();
return getVersionComponentAsLong(name.component(i));
}
public static byte [] getLastVersionComponent(ContentName name) throws VersionMissingException {
int i = findLastVersionComponent(name);
if (i == -1)
throw new VersionMissingException();
return name.component(i);
}
public static long getVersionComponentAsLong(byte [] versionComponent) {
byte [] versionData = new byte[versionComponent.length - 1];
System.arraycopy(versionComponent, 1, versionData, 0, versionComponent.length - 1);
if (versionData.length == 0)
return 0;
return new BigInteger(versionData).longValue();
}
public static CCNTime getVersionComponentAsTimestamp(byte [] versionComponent) {
if (null == versionComponent)
return null;
return versionLongToTimestamp(getVersionComponentAsLong(versionComponent));
}
/**
* Extract the version from this name as a Timestamp.
* @throws VersionMissingException
*/
public static CCNTime getLastVersionAsTimestamp(ContentName name) throws VersionMissingException {
long time = getLastVersionAsLong(name);
return CCNTime.fromBinaryTimeAsLong(time);
}
/**
* Returns null if no version, otherwise returns the last version in the name.
* @param name
* @return
*/
public static CCNTime getLastVersionAsTimestampIfVersioned(ContentName name) {
int versionComponent = findLastVersionComponent(name);
if (versionComponent < 0)
return null;
return getVersionComponentAsTimestamp(name.component(versionComponent));
}
public static CCNTime getTerminalVersionAsTimestampIfVersioned(ContentName name) {
if (!hasTerminalVersion(name))
return null;
int versionComponent = findLastVersionComponent(name);
if (versionComponent < 0)
return null;
return getVersionComponentAsTimestamp(name.component(versionComponent));
}
public static CCNTime versionLongToTimestamp(long version) {
return CCNTime.fromBinaryTimeAsLong(version);
}
/**
* Control whether versions start at 0 or 1.
* @return
*/
public static final int baseVersion() { return 0; }
/**
* Compares terminal version (versions at the end of, or followed by only a segment
* marker) of a name to a given timestamp.
* @param left
* @param right
* @return
*/
public static int compareVersions(
CCNTime left,
ContentName right) {
if (!hasTerminalVersion(right)) {
throw new IllegalArgumentException("Both names to compare must be versioned!");
}
try {
return left.compareTo(getLastVersionAsTimestamp(right));
} catch (VersionMissingException e) {
throw new IllegalArgumentException("Name that isVersioned returns true for throws VersionMissingException!: " + right);
}
}
public static int compareVersionComponents(
byte [] left,
byte [] right) throws VersionMissingException {
// Propagate correct exception to callers.
if ((null == left) || (null == right))
throw new VersionMissingException("Must compare two versions!");
// DKS TODO -- should be able to just compare byte arrays, but would have to check version
return getVersionComponentAsTimestamp(left).compareTo(getVersionComponentAsTimestamp(right));
}
/**
* See if version is a version of parent (not commutative).
* @return
*/
public static boolean isVersionOf(ContentName version, ContentName parent) {
Tuple<ContentName, byte []>versionParts = cutTerminalVersion(version);
if (!parent.equals(versionParts.first())) {
return false; // not versions of the same thing
}
if (null == versionParts.second())
return false; // version isn't a version
return true;
}
/**
* This compares two names, with terminal versions, and determines whether one is later than the other.
* @param laterVersion
* @param earlierVersion
* @return
* @throws VersionMissingException
*/
public static boolean isLaterVersionOf(ContentName laterVersion, ContentName earlierVersion) throws VersionMissingException {
// TODO -- remove temporary warning
Log.warning("SEMANTICS CHANGED: if experiencing unexpected behavior, check to see if you want to call isLaterVerisionOf or startsWithLaterVersionOf");
Tuple<ContentName, byte []>earlierVersionParts = cutTerminalVersion(earlierVersion);
Tuple<ContentName, byte []>laterVersionParts = cutTerminalVersion(laterVersion);
if (!laterVersionParts.first().equals(earlierVersionParts.first())) {
return false; // not versions of the same thing
}
return (compareVersionComponents(laterVersionParts.second(), earlierVersionParts.second()) > 0);
}
/**
* Finds out if you have a versioned name, and a ContentObject that might have a versioned name which is
* a later version of the given name, even if that CO name might not refer to a segment of the original name.
* For example, given a name /parc/foo.txt/<version1> or /parc/foo.txt/<version1>/<segment>
* and /parc/foo.txt/<version2>/<stuff>, return true, whether <stuff> is a segment marker, a whole
* bunch of repo write information, or whatever.
* @param newName Will check to see if this name begins with something which is a later version of previousVersion.
* @param previousVersion The name to compare to, must have a terminal version or be unversioned.
* @return
*/
public static boolean startsWithLaterVersionOf(ContentName newName, ContentName previousVersion) {
// If no version, treat whole name as prefix and any version as a later version.
Tuple<ContentName, byte []>previousVersionParts = cutTerminalVersion(previousVersion);
if (!previousVersionParts.first().isPrefixOf(newName))
return false;
if (null == previousVersionParts.second()) {
return ((newName.count() > previousVersionParts.first().count()) &&
VersioningProfile.isVersionComponent(newName.component(previousVersionParts.first().count())));
}
try {
return (compareVersionComponents(newName.component(previousVersionParts.first().count()), previousVersionParts.second()) > 0);
} catch (VersionMissingException e) {
return false; // newName doesn't have to have a version there...
}
}
public static int compareTerminalVersions(ContentName laterVersion, ContentName earlierVersion) throws VersionMissingException {
Tuple<ContentName, byte []>earlierVersionParts = cutTerminalVersion(earlierVersion);
Tuple<ContentName, byte []>laterVersionParts = cutTerminalVersion(laterVersion);
if (!laterVersionParts.first().equals(earlierVersionParts.first())) {
throw new IllegalArgumentException("Names not versions of the same name!");
}
return (compareVersionComponents(laterVersionParts.second(), earlierVersionParts.second()));
}
/**
* Builds an Exclude filter that excludes components before or @ start, and components after
* the last valid version.
* @param startingVersionComponent The latest version component we know about. Can be null or
* VersioningProfile.isBaseVersionComponent() == true to indicate that we want to start
* from 0 (we don't have a known version we're trying to update). This exclude filter will
* find versions *after* the version represented in startingVersionComponent.
* @return An exclude filter.
*/
public static Exclude acceptVersions(byte [] startingVersionComponent) {
byte [] start = null;
// initially exclude name components just before the first version, whether that is the
// 0th version or the version passed in
if ((null == startingVersionComponent) || VersioningProfile.isBaseVersionComponent(startingVersionComponent)) {
start = new byte [] { VersioningProfile.VERSION_MARKER, VersioningProfile.OO, VersioningProfile.FF, VersioningProfile.FF, VersioningProfile.FF, VersioningProfile.FF, VersioningProfile.FF };
} else {
start = startingVersionComponent;
}
ArrayList<Exclude.Element> ees = new ArrayList<Exclude.Element>();
ees.add(new ExcludeAny());
ees.add(new ExcludeComponent(start));
ees.add(new ExcludeComponent(new byte [] {
VERSION_MARKER+1, OO, OO, OO, OO, OO, OO } ));
ees.add(new ExcludeAny());
return new Exclude(ees);
}
/**
* Active methods. Want to provide profile-specific methods that:
* - find the latest version without regard to what is below it
* - if no version given, gets the latest version
* - if a starting version given, gets the latest version available *after* that version;
* will time out if no such newer version exists
* Returns a content object, which may or may not be a segment of the latest version, but the
* latest version information is available from its name.
*
* - find the first segment of the latest version of a name
* - if no version given, gets the first segment of the latest version
* - if a starting version given, gets the latest version available *after* that version or times out
* Will ensure that what it returns is a segment of a version of that object.
*
* - generate an interest designed to find the first segment of the latest version
* of a name, in the above form; caller is responsible for checking and re-issuing
*/
/**
* Generate an interest that will find the leftmost child of the latest version. It
* will ensure that the next to last segment is a version, and the last segment (excluding
* digest) is the leftmost child available. But it can't guarantee that the latter is
* a segment. Because most data is segmented, length constraints will make it very
* likely, however.
* @param startingVersion
* @return
*/
public static Interest firstBlockLatestVersionInterest(ContentName startingVersion, PublisherPublicKeyDigest publisher) {
// by the time we look for extra components we will have a version on our name if it
// doesn't have one already, so look for names with 2 extra components -- segment and digest.
return latestVersionInterest(startingVersion, 3, publisher);
}
/**
* Generate an interest that will find a descendant of the latest version of startingVersion,
* after any existing version component. If additionalNameComponents is non-null, it will
* find a descendant with exactly that many name components after the version (including
* the digest). The latest version is the rightmost child of the desired prefix, however,
* this interest will find leftmost descendants of that rightmost child. With appropriate
* length limitations, can be used to find segments of the latest version (though that
* will work more effectively with appropriate segment numbering).
*/
public static Interest latestVersionInterest(ContentName startingVersion, Integer additionalNameComponents, PublisherPublicKeyDigest publisher) {
if (hasTerminalVersion(startingVersion)) {
// Has a version. Make sure it doesn't have a segment; find a version after this one.
startingVersion = SegmentationProfile.segmentRoot(startingVersion);
} else {
// Doesn't have a version. Add the "0" version, so we are finding any version after that.
ContentName firstVersionName = addVersion(startingVersion, baseVersion());
startingVersion = firstVersionName;
}
byte [] versionComponent = startingVersion.lastComponent();
Interest constructedInterest = Interest.last(startingVersion, acceptVersions(versionComponent), startingVersion.count() - 1, additionalNameComponents,
additionalNameComponents, null);
if (null != publisher) {
constructedInterest.publisherID(new PublisherID(publisher));
}
return constructedInterest;
}
/**
* Function to (best effort) get the latest version. There may be newer versions available
* if you ask again passing in the version found (i.e. each response will be the latest version
* a given responder knows about. Further queries will move past that responder to other responders,
* who may have newer information.)
*
* @param name If the name ends in a version then this method explicitly looks for a newer version
* than that, and will time out if no such later version exists. If the name does not end in a
* version then this call just looks for the latest version.
* @param publisher Currently unused, will limit query to a specific publisher.
* @param timeout This is the time to wait until you get any response. If nothing is returned, this method will return null.
* @param verifier Used to verify the returned content objects
* @param handle CCNHandle used to get the latest version
* @return A ContentObject with the latest version, or null if the query timed out.
* @result Returns a matching ContentObject, verified.
* @throws IOException
*/
public static ContentObject getLatestVersion(ContentName startingVersion,
PublisherPublicKeyDigest publisher,
long timeout,
ContentVerifier verifier,
CCNHandle handle) throws IOException {
return getLatestVersion(startingVersion, publisher, timeout, verifier, handle, null, false);
}
/**
* Function to (best effort) get the latest version. There may be newer versions available
* if you ask again passing in the version found (i.e. each response will be the latest version
* a given responder knows about. Further queries will move past that responder to other responders,
* who may have newer information.)
*
* @param name If the name ends in a version then this method explicitly looks for a newer version
* than that, and will time out if no such later version exists. If the name does not end in a
* version then this call just looks for the latest version.
* @param publisher Currently unused, will limit query to a specific publisher.
* @param timeout This is the time to wait until you get any response. If nothing is returned, this method will return null.
* @param verifier Used to verify the returned content objects.
* @param handle CCNHandle used to get the latest version.
* @param startingSegmentNumber If we are requiring content to be a segment, what segment number
* do we want. If null, and findASegment is true, uses SegmentationProfile.baseSegment().
* @param findASegment are we requiring returned content to be a segment of this version
* @return A ContentObject with the latest version, or null if the query timed out.
* @result Returns a matching ContentObject, verified.
* @throws IOException
*/
private static ContentObject getLatestVersion(ContentName startingVersion,
PublisherPublicKeyDigest publisher,
long timeout,
ContentVerifier verifier,
CCNHandle handle,
Long startingSegmentNumber,
boolean findASegment) throws IOException {
Log.info("getFirstBlockOfLatestVersion: getting version later than {0} called with timeout: {1}", startingVersion, timeout);
if (null == verifier) {
// TODO DKS normalize default behavior
verifier = handle.keyManager().getDefaultVerifier();
}
int attempts = 0;
//TODO This timeout is set to SystemConfiguration.MEDIUM_TIMEOUT to work around the problem
//in ccnd where some interests take >300ms (and sometimes longer, have seen periodic delays >800ms)
//when that bug is found and fixed, this can be reduced back to the SHORT_TIMEOUT.
//long attemptTimeout = SystemConfiguration.SHORT_TIMEOUT;
long attemptTimeout = SystemConfiguration.MEDIUM_TIMEOUT;
if (timeout == SystemConfiguration.NO_TIMEOUT) {
//the timeout sent in is equivalent to null... try till we don't hear something back
//we will reset the remaining time after each return...
} else if (timeout > 0 && timeout < attemptTimeout) {
attemptTimeout = timeout;
}
long nullTimeout = attemptTimeout;
if( timeout > attemptTimeout)
nullTimeout = timeout;
long startTime;
long respondTime;
long remainingTime = attemptTimeout;
long remainingNullTime = nullTimeout;
ContentName prefix = startingVersion;
if (hasTerminalVersion(prefix)) {
prefix = startingVersion.parent();
}
int versionedLength = prefix.count() + 1;
ContentObject result = null;
ContentObject lastResult = null;
ArrayList<byte[]> excludeList = new ArrayList<byte[]>();
while (attempts < SystemConfiguration.GET_LATEST_VERSION_ATTEMPTS && remainingTime > 0) {
Log.fine("gLV attempts: {0} attemptTimeout: {1} remainingTime: {2} (timeout: {3})", attempts, attemptTimeout, remainingTime, timeout);
lastResult = result;
attempts++;
Interest getLatestInterest = null;
if (findASegment) {
getLatestInterest = firstBlockLatestVersionInterest(startingVersion, publisher);
} else {
getLatestInterest = latestVersionInterest(startingVersion, null, publisher);
}
if (excludeList.size() > 0) {
//we have explicit excludes, add them to this interest
byte [][] e = new byte[excludeList.size()][];
excludeList.toArray(e);
getLatestInterest.exclude().add(e);
}
startTime = System.currentTimeMillis();
result = handle.get(getLatestInterest, attemptTimeout);
respondTime = System.currentTimeMillis() - startTime;
remainingTime = remainingTime - respondTime;
remainingNullTime = remainingNullTime - respondTime;
if (Log.isLoggable(Level.FINE)) {
Log.fine("gLV INTEREST: {0}", getLatestInterest);
Log.fine("gLV trying handle.get with timeout: {0}", attemptTimeout);
Log.fine("gLVTime sending Interest from gLV at {0}", startTime);
Log.fine("gLVTime returned from handle.get in {0} ms",respondTime);
Log.fine("gLV remaining time is now {0} ms", remainingTime);
}
if (null != result){
if (Log.isLoggable(Level.INFO))
Log.info("gLV getLatestVersion: retrieved latest version object {0} type: {1}", result.name(), result.signedInfo().getTypeName());
//did it verify?
//if it doesn't verify, we need to try harder to get a different content object (exclude this digest)
//make this a loop?
if (!verifier.verify(result)) {
//excludes = addVersionToExcludes(excludes, result.name());
Log.fine("gLV result did not verify, trying to find a verifiable answer");
excludeList = addVersionToExcludes(excludeList, result.name());
//note: need to use the full name, but want to exclude this particular digest. This means we can't cut off the segment marker.
//Interest retry = new Interest(SegmentationProfile.segmentRoot(result.name()), publisher);
//retry.maxSuffixComponents(1);
Interest retry = new Interest(result.name(), publisher);
boolean verifyDone = false;
while (!verifyDone) {
if (retry.exclude() == null)
retry.exclude(new Exclude());
retry.exclude().add(new byte[][] {result.digest()});
if (Log.isLoggable(Level.FINE)) {
Log.fine("gLV result did not verify! doing retry!! {0}", retry);
Log.fine("gLVTime sending retry interest at {0}", System.currentTimeMillis());
}
result = handle.get(retry, attemptTimeout);
if (result!=null) {
if (Log.isLoggable(Level.FINE))
Log.fine("gLV we got something back: {0}", result.name());
if(verifier.verify(result)) {
Log.fine("gLV the returned answer verifies");
verifyDone = true;
} else {
Log.fine("gLV this answer did not verify either... try again");
}
} else {
//result is null, we didn't find a verifiable answer
Log.fine("gLV did not get a verifiable answer back");
verifyDone = true;
}
}
//TODO if this is the latest version and we exclude it, we might not have anything to send back... we should reset the starting version
}
if (result!=null) {
//else {
//it verified! are we done?
//first check if we need to get the first segment...
if (findASegment) {
//yes, we need to have the first segment....
// Now we know the version. Did we luck out and get first block?
if (VersioningProfile.isVersionedFirstSegment(prefix, result, startingSegmentNumber)) {
if (Log.isLoggable(Level.FINE))
Log.fine("getFirstBlockOfLatestVersion: got first block on first try: " + result.name());
} else {
//not the first segment...
// This isn't the first block. Might be simply a later (cached) segment, or might be something
// crazy like a repo_start_write. So what we want is to get the version of this new block -- if getLatestVersion
// is doing its job, we now know the version we want (if we already knew that, we called super.getFirstBlock
// above. If we get here, _baseName isn't versioned yet. So instead of taking segmentRoot of what we got,
// which works fine only if we have the wrong segment rather than some other beast entirely (like metadata).
// So chop off the new name just after the (first) version, and use that. If getLatestVersion is working
// right, that should be the right thing.
ContentName notFirstBlockVersion = result.name().cut(versionedLength);
Log.info("CHILD SELECTOR FAILURE: getFirstBlockOfLatestVersion: Have version information, now querying first segment of " + startingVersion);
// this will verify
//don't count this against the gLV timeout.
result = SegmentationProfile.getSegment(notFirstBlockVersion, startingSegmentNumber, null, timeout, verifier, handle); // now that we have the latest version, go back for the first block.
//if this isn't the first segment... then we should exclude it. otherwise, we can use it!
if(result == null) {
//we couldn't get a new segment...
Log.fine("gLV could not get the first segment of the version we just found... should exclude the version");
//excludes = addVersionToExcludes(excludes, startingVersion);
excludeList = addVersionToExcludes(excludeList, notFirstBlockVersion);
}
}
} else {
//no need to get the first segment!
//this is already verified!
}
//if result is not null, we really have something to try since it also verified
if (result != null) {
//this could be our answer... set to lastResult and see if we have time to do better
lastResult = result;
if (timeout == SystemConfiguration.NO_TIMEOUT) {
//we want to keep trying for something new
remainingTime = attemptTimeout;
attempts = 0;
}
if (timeout == 0) {
//caller just wants the first answer...
attempts = SystemConfiguration.GET_LATEST_VERSION_ATTEMPTS;
remainingTime = 0;
}
if (remainingTime > 0) {
//we still have time to try for a better answer
Log.fine("gLV we still have time to try for a better answer");
attemptTimeout = remainingTime;
} else {
Log.fine("gLV time is up, return what we have");
attempts = SystemConfiguration.GET_LATEST_VERSION_ATTEMPTS;
}
} else {
//result is null
//will be handled below
}
}//the result verified
} //we got something back
if (result == null) {
Log.fine("gLV we didn't get anything");
Log.info("getFirstBlockOfLatestVersion: no block available for later version of {0}", startingVersion);
//we didn't get a new version... we can return the last one we received if it isn't null.
if (lastResult!=null) {
if (Log.isLoggable(Level.FINE)) {
Log.fine("gLV returning the last result that wasn't null... ");
Log.fine("gLV returning: {0}",lastResult.name());
}
return lastResult;
}
else {
Log.fine("gLV we didn't get anything, and we haven't had anything at all... try with remaining long timeout");
attemptTimeout = remainingNullTime;
remainingTime = remainingNullTime;
}
}
Log.fine("gLV (after) attempts: {0} attemptTimeout: {1} remainingTime: {2} (timeout: {3})", attempts, attemptTimeout, remainingTime, timeout);
if (result!=null)
startingVersion = SegmentationProfile.segmentRoot(result.name());
}
if(result!=null) {
if (Log.isLoggable(Level.FINE))
Log.fine("gLV returning: {0}", result.name());
}
return result;
}
/**
* Find a particular segment of the latest version of a name
* - if no version given, gets the desired segment of the latest version
* - if a starting version given, gets the latest version available *after* that version or times out
* Will ensure that what it returns is a segment of a version of that object.
* Also makes sure to return the latest version with a SegmentationProfile.baseSegment() marker.
* * @param desiredName The name of the object we are looking for the first segment of.
* If (VersioningProfile.hasTerminalVersion(desiredName) == false), will get latest version it can
* find of desiredName.
* If desiredName has a terminal version, will try to find the first block of content whose
* version is *after* desiredName (i.e. getLatestVersion starting from desiredName).
* @param startingSegmentNumber The desired block number, or SegmentationProfile.baseSegment() if null.
* @param publisher, if one is specified.
* @param timeout
* @return The first block of a stream with a version later than desiredName, or null if timeout is reached.
* This block is verified.
* @throws IOException
*/
public static ContentObject getFirstBlockOfLatestVersion(ContentName startingVersion,
Long startingSegmentNumber,
PublisherPublicKeyDigest publisher,
long timeout,
ContentVerifier verifier,
CCNHandle handle) throws IOException {
return getLatestVersion(startingVersion, publisher, timeout, verifier, handle, startingSegmentNumber, true);
}
/**
* Version of isFirstSegment that expects names to be versioned, and allows that desiredName
* won't know what version it wants but will want some version.
*/
public static boolean isVersionedFirstSegment(ContentName desiredName, ContentObject potentialFirstSegment, Long startingSegmentNumber) {
if ((null != potentialFirstSegment) && (SegmentationProfile.isSegment(potentialFirstSegment.name()))) {
if (Log.isLoggable(Level.INFO))
Log.info("is " + potentialFirstSegment.name() + " a first segment of " + desiredName);
// In theory, the segment should be at most a versioning component different from desiredName.
// In the case of complex segmented objects (e.g. a KeyDirectory), where there is a version,
// then some name components, then a segment, desiredName should contain all of those other
// name components -- you can't use the usual versioning mechanisms to pull first segment anyway.
if (!desiredName.isPrefixOf(potentialFirstSegment.name())) {
if (Log.isLoggable(Level.INFO))
Log.info("Desired name :" + desiredName + " is not a prefix of segment: " + potentialFirstSegment.name());
return false;
}
int difflen = potentialFirstSegment.name().count() - desiredName.count();
if (difflen > 2) {
if (Log.isLoggable(Level.INFO))
Log.info("Have " + difflen + " extra components between " + potentialFirstSegment.name() + " and desired " + desiredName);
return false;
}
// Now need to make sure that if the difference is more than 1, that difference is
// a version component.
if ((difflen == 2) && (!isVersionComponent(potentialFirstSegment.name().component(potentialFirstSegment.name().count()-2)))) {
if (Log.isLoggable(Level.INFO))
Log.info("The " + difflen + " extra component between " + potentialFirstSegment.name() + " and desired " + desiredName + " is not a version.");
}
if ((null != startingSegmentNumber) && (SegmentationProfile.baseSegment() != startingSegmentNumber)) {
return (startingSegmentNumber.longValue() == SegmentationProfile.getSegmentNumber(potentialFirstSegment.name()));
} else {
return SegmentationProfile.isFirstSegment(potentialFirstSegment.name());
}
}
return false;
}
/**
* Adds version components to the exclude list for the getLatestVersion method.
* @param excludeList current excludes
* @param name component to add to the exclude list
* @return updated exclude list
*/
private static ArrayList<byte[]> addVersionToExcludes(ArrayList<byte[]> excludeList, ContentName name) {
try {
excludeList.add(VersioningProfile.getLastVersionComponent(name));
} catch (VersionMissingException e) {
Log.warning("failed to exclude content object version that did not verify: {0}",name);
}
return excludeList;
}
public static byte[] versionComponentFromStripped(byte[] bs) {
if (null == bs)
return null;
byte [] versionComponent = new byte[bs.length + 1];
versionComponent[0] = VERSION_MARKER;
System.arraycopy(bs, 0, versionComponent, 1, bs.length);
return versionComponent;
}
public static byte[] stripVersionMarker(byte[] version) throws VersionMissingException {
if (null == version)
return null;
if (VERSION_MARKER != version[0]) {
throw new VersionMissingException("This is not a version component!");
}
byte [] stripped = new byte[version.length - 1];
System.arraycopy(version, 1, stripped, 0, stripped.length);
return stripped;
}
}
|
javasrc/src/org/ccnx/ccn/profiles/VersioningProfile.java
|
/**
* Part of the CCNx Java Library.
*
* Copyright (C) 2008, 2009, 2010 Palo Alto Research Center, Inc.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 2.1
* as published by the Free Software Foundation.
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. You should have received
* a copy of the GNU Lesser General Public License along with this library;
* if not, write to the Free Software Foundation, Inc., 51 Franklin Street,
* Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.ccnx.ccn.profiles;
import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.logging.Level;
import org.ccnx.ccn.CCNHandle;
import org.ccnx.ccn.ContentVerifier;
import org.ccnx.ccn.config.SystemConfiguration;
import org.ccnx.ccn.impl.support.Log;
import org.ccnx.ccn.impl.support.Tuple;
import org.ccnx.ccn.protocol.CCNTime;
import org.ccnx.ccn.protocol.ContentName;
import org.ccnx.ccn.protocol.ContentObject;
import org.ccnx.ccn.protocol.ExcludeAny;
import org.ccnx.ccn.protocol.ExcludeComponent;
import org.ccnx.ccn.protocol.Exclude;
import org.ccnx.ccn.protocol.Interest;
import org.ccnx.ccn.protocol.PublisherID;
import org.ccnx.ccn.protocol.PublisherPublicKeyDigest;
/**
* Versions, when present, usually occupy the penultimate component of the CCN name,
* not counting the digest component. A name may actually incorporate multiple
* versions, where the rightmost version is the version of "this" object, if it
* has one, and previous (parent) versions are the versions of the objects of
* which this object is a part. The most common location of a version, if present,
* is in the next to last component of the name, where the last component is a
* segment number (which is generally always present; versions themselves are
* optional). More complicated segmentation profiles occur, where a versioned
* object has components that are structured and named in ways other than segments --
* and may themselves have individual versions (e.g. if the components of such
* a composite object are written as CCNNetworkObjects and automatically pick
* up an (unnecessary) version in their own right). Versioning operations therefore
* take context from their caller about where to expect to find a version,
* and attempt to ignore other versions in the name.
*
* Versions may be chosen based on time.
* The first byte of the version component is 0xFD. The remaining bytes are a
* big-endian binary number. If based on time they are expressed in units of
* 2**(-12) seconds since the start of Unix time, using the minimum number of
* bytes. The time portion will thus take 48 bits until quite a few centuries
* from now (Sun, 20 Aug 4147 07:32:16 GMT). With 12 bits of precision, it allows
* for sub-millisecond resolution. The client generating the version stamp
* should try to avoid using a stamp earlier than (or the same as) any
* version of the file, to the extent that it knows about it. It should
* also avoid generating stamps that are unreasonably far in the future.
*/
public class VersioningProfile implements CCNProfile {
public static final byte VERSION_MARKER = (byte)0xFD;
public static final byte [] FIRST_VERSION_MARKER = new byte []{VERSION_MARKER};
public static final byte FF = (byte) 0xFF;
public static final byte OO = (byte) 0x00;
/**
* Add a version field to a ContentName.
* @return ContentName with a version appended. Does not affect previous versions.
*/
public static ContentName addVersion(ContentName name, long version) {
// Need a minimum-bytes big-endian representation of version.
byte [] vcomp = null;
if (0 == version) {
vcomp = FIRST_VERSION_MARKER;
} else {
byte [] varr = BigInteger.valueOf(version).toByteArray();
vcomp = new byte[varr.length + 1];
vcomp[0] = VERSION_MARKER;
System.arraycopy(varr, 0, vcomp, 1, varr.length);
}
return new ContentName(name, vcomp);
}
/**
* Converts a timestamp into a fixed point representation, with 12 bits in the fractional
* component, and adds this to the ContentName as a version field. The timestamp is rounded
* to the nearest value in the fixed point representation.
* <p>
* This allows versions to be recorded as a timestamp with a 1/4096 second accuracy.
* @see #addVersion(ContentName, long)
*/
public static ContentName addVersion(ContentName name, CCNTime version) {
if (null == version)
throw new IllegalArgumentException("Version cannot be null!");
byte [] vcomp = timeToVersionComponent(version);
return new ContentName(name, vcomp);
}
/**
* Add a version field based on the current time, accurate to 1/4096 second.
* @see #addVersion(ContentName, CCNTime)
*/
public static ContentName addVersion(ContentName name) {
return addVersion(name, CCNTime.now());
}
public static byte [] timeToVersionComponent(CCNTime version) {
byte [] varr = version.toBinaryTime();
byte [] vcomp = new byte[varr.length + 1];
vcomp[0] = VERSION_MARKER;
System.arraycopy(varr, 0, vcomp, 1, varr.length);
return vcomp;
}
public static String printAsVersionComponent(CCNTime version) {
byte [] vcomp = timeToVersionComponent(version);
return ContentName.componentPrintURI(vcomp);
}
/**
* Adds a version to a ContentName; if there is a terminal version there already,
* first removes it.
*/
public static ContentName updateVersion(ContentName name, long version) {
return addVersion(cutTerminalVersion(name).first(), version);
}
/**
* Adds a version to a ContentName; if there is a terminal version there already,
* first removes it.
*/
public static ContentName updateVersion(ContentName name, CCNTime version) {
return addVersion(cutTerminalVersion(name).first(), version);
}
/**
* Add updates the version field based on the current time, accurate to 1/4096 second.
* @see #updateVersion(ContentName, Timestamp)
*/
public static ContentName updateVersion(ContentName name) {
return updateVersion(name, CCNTime.now());
}
/**
* Finds the last component that looks like a version in name.
* @param name
* @return the index of the last version component in the name, or -1 if there is no version
* component in the name
*/
public static int findLastVersionComponent(ContentName name) {
int i = name.count();
for (;i >= 0; i--)
if (isVersionComponent(name.component(i)))
return i;
return -1;
}
/**
* Checks to see if this name has a validly formatted version field anywhere in it.
*/
public static boolean containsVersion(ContentName name) {
return findLastVersionComponent(name) != -1;
}
/**
* Checks to see if this name has a validly formatted version field either in final
* component or in next to last component with final component being a segment marker.
*/
public static boolean hasTerminalVersion(ContentName name) {
if ((name.count() > 0) &&
((isVersionComponent(name.lastComponent()) ||
((name.count() > 1) && SegmentationProfile.isSegment(name) && isVersionComponent(name.component(name.count()-2)))))) {
return true;
}
return false;
}
/**
* Check a name component to see if it is a valid version field
*/
public static boolean isVersionComponent(byte [] nameComponent) {
return (null != nameComponent) && (0 != nameComponent.length) &&
(VERSION_MARKER == nameComponent[0]) &&
((nameComponent.length == 1) || (nameComponent[1] != 0));
}
public static boolean isBaseVersionComponent(byte [] nameComponent) {
return (isVersionComponent(nameComponent) && (1 == nameComponent.length));
}
/**
* Remove a terminal version marker (one that is either the last component of name, or
* the next to last component of name followed by a segment marker) if one exists, otherwise
* return name as it was passed in.
* @param name
* @return
*/
public static Tuple<ContentName, byte[]> cutTerminalVersion(ContentName name) {
if (name.count() > 0) {
if (isVersionComponent(name.lastComponent())) {
return new Tuple<ContentName, byte []>(name.parent(), name.lastComponent());
} else if ((name.count() > 2) && SegmentationProfile.isSegment(name) && isVersionComponent(name.component(name.count()-2))) {
return new Tuple<ContentName, byte []>(name.cut(name.count()-2), name.component(name.count()-2));
}
}
return new Tuple<ContentName, byte []>(name, null);
}
/**
* Take a name which may have one or more version components in it,
* and strips the last one and all following components. If no version components
* present, returns the name as handed in.
*/
public static ContentName cutLastVersion(ContentName name) {
int offset = findLastVersionComponent(name);
return (offset == -1) ? name : new ContentName(offset, name.components());
}
/**
* Function to get the version field as a long. Starts from the end and checks each name component for the version marker.
* @param name
* @return long
* @throws VersionMissingException
*/
public static long getLastVersionAsLong(ContentName name) throws VersionMissingException {
int i = findLastVersionComponent(name);
if (i == -1)
throw new VersionMissingException();
return getVersionComponentAsLong(name.component(i));
}
public static byte [] getLastVersionComponent(ContentName name) throws VersionMissingException {
int i = findLastVersionComponent(name);
if (i == -1)
throw new VersionMissingException();
return name.component(i);
}
public static long getVersionComponentAsLong(byte [] versionComponent) {
byte [] versionData = new byte[versionComponent.length - 1];
System.arraycopy(versionComponent, 1, versionData, 0, versionComponent.length - 1);
if (versionData.length == 0)
return 0;
return new BigInteger(versionData).longValue();
}
public static CCNTime getVersionComponentAsTimestamp(byte [] versionComponent) {
if (null == versionComponent)
return null;
return versionLongToTimestamp(getVersionComponentAsLong(versionComponent));
}
/**
* Extract the version from this name as a Timestamp.
* @throws VersionMissingException
*/
public static CCNTime getLastVersionAsTimestamp(ContentName name) throws VersionMissingException {
long time = getLastVersionAsLong(name);
return CCNTime.fromBinaryTimeAsLong(time);
}
/**
* Returns null if no version, otherwise returns the last version in the name.
* @param name
* @return
*/
public static CCNTime getLastVersionAsTimestampIfVersioned(ContentName name) {
int versionComponent = findLastVersionComponent(name);
if (versionComponent < 0)
return null;
return getVersionComponentAsTimestamp(name.component(versionComponent));
}
public static CCNTime getTerminalVersionAsTimestampIfVersioned(ContentName name) {
if (!hasTerminalVersion(name))
return null;
int versionComponent = findLastVersionComponent(name);
if (versionComponent < 0)
return null;
return getVersionComponentAsTimestamp(name.component(versionComponent));
}
public static CCNTime versionLongToTimestamp(long version) {
return CCNTime.fromBinaryTimeAsLong(version);
}
/**
* Control whether versions start at 0 or 1.
* @return
*/
public static final int baseVersion() { return 0; }
/**
* Compares terminal version (versions at the end of, or followed by only a segment
* marker) of a name to a given timestamp.
* @param left
* @param right
* @return
*/
public static int compareVersions(
CCNTime left,
ContentName right) {
if (!hasTerminalVersion(right)) {
throw new IllegalArgumentException("Both names to compare must be versioned!");
}
try {
return left.compareTo(getLastVersionAsTimestamp(right));
} catch (VersionMissingException e) {
throw new IllegalArgumentException("Name that isVersioned returns true for throws VersionMissingException!: " + right);
}
}
public static int compareVersionComponents(
byte [] left,
byte [] right) throws VersionMissingException {
// Propagate correct exception to callers.
if ((null == left) || (null == right))
throw new VersionMissingException("Must compare two versions!");
// DKS TODO -- should be able to just compare byte arrays, but would have to check version
return getVersionComponentAsTimestamp(left).compareTo(getVersionComponentAsTimestamp(right));
}
/**
* See if version is a version of parent (not commutative).
* @return
*/
public static boolean isVersionOf(ContentName version, ContentName parent) {
Tuple<ContentName, byte []>versionParts = cutTerminalVersion(version);
if (!parent.equals(versionParts.first())) {
return false; // not versions of the same thing
}
if (null == versionParts.second())
return false; // version isn't a version
return true;
}
/**
* This compares two names, with terminal versions, and determines whether one is later than the other.
* @param laterVersion
* @param earlierVersion
* @return
* @throws VersionMissingException
*/
public static boolean isLaterVersionOf(ContentName laterVersion, ContentName earlierVersion) throws VersionMissingException {
// TODO -- remove temporary warning
Log.warning("SEMANTICS CHANGED: if experiencing unexpected behavior, check to see if you want to call isLaterVerisionOf or startsWithLaterVersionOf");
Tuple<ContentName, byte []>earlierVersionParts = cutTerminalVersion(earlierVersion);
Tuple<ContentName, byte []>laterVersionParts = cutTerminalVersion(laterVersion);
if (!laterVersionParts.first().equals(earlierVersionParts.first())) {
return false; // not versions of the same thing
}
return (compareVersionComponents(laterVersionParts.second(), earlierVersionParts.second()) > 0);
}
/**
* Finds out if you have a versioned name, and a ContentObject that might have a versioned name which is
* a later version of the given name, even if that CO name might not refer to a segment of the original name.
* For example, given a name /parc/foo.txt/<version1> or /parc/foo.txt/<version1>/<segment>
* and /parc/foo.txt/<version2>/<stuff>, return true, whether <stuff> is a segment marker, a whole
* bunch of repo write information, or whatever.
* @param newName Will check to see if this name begins with something which is a later version of previousVersion.
* @param previousVersion The name to compare to, must have a terminal version or be unversioned.
* @return
*/
public static boolean startsWithLaterVersionOf(ContentName newName, ContentName previousVersion) {
// If no version, treat whole name as prefix and any version as a later version.
Tuple<ContentName, byte []>previousVersionParts = cutTerminalVersion(previousVersion);
if (!previousVersionParts.first().isPrefixOf(newName))
return false;
if (null == previousVersionParts.second()) {
return ((newName.count() > previousVersionParts.first().count()) &&
VersioningProfile.isVersionComponent(newName.component(previousVersionParts.first().count())));
}
try {
return (compareVersionComponents(newName.component(previousVersionParts.first().count()), previousVersionParts.second()) > 0);
} catch (VersionMissingException e) {
return false; // newName doesn't have to have a version there...
}
}
public static int compareTerminalVersions(ContentName laterVersion, ContentName earlierVersion) throws VersionMissingException {
Tuple<ContentName, byte []>earlierVersionParts = cutTerminalVersion(earlierVersion);
Tuple<ContentName, byte []>laterVersionParts = cutTerminalVersion(laterVersion);
if (!laterVersionParts.first().equals(earlierVersionParts.first())) {
throw new IllegalArgumentException("Names not versions of the same name!");
}
return (compareVersionComponents(laterVersionParts.second(), earlierVersionParts.second()));
}
/**
* Builds an Exclude filter that excludes components before or @ start, and components after
* the last valid version.
* @param startingVersionComponent The latest version component we know about. Can be null or
* VersioningProfile.isBaseVersionComponent() == true to indicate that we want to start
* from 0 (we don't have a known version we're trying to update). This exclude filter will
* find versions *after* the version represented in startingVersionComponent.
* @return An exclude filter.
*/
public static Exclude acceptVersions(byte [] startingVersionComponent) {
byte [] start = null;
// initially exclude name components just before the first version, whether that is the
// 0th version or the version passed in
if ((null == startingVersionComponent) || VersioningProfile.isBaseVersionComponent(startingVersionComponent)) {
start = new byte [] { VersioningProfile.VERSION_MARKER, VersioningProfile.OO, VersioningProfile.FF, VersioningProfile.FF, VersioningProfile.FF, VersioningProfile.FF, VersioningProfile.FF };
} else {
start = startingVersionComponent;
}
ArrayList<Exclude.Element> ees = new ArrayList<Exclude.Element>();
ees.add(new ExcludeAny());
ees.add(new ExcludeComponent(start));
ees.add(new ExcludeComponent(new byte [] {
VERSION_MARKER+1, OO, OO, OO, OO, OO, OO } ));
ees.add(new ExcludeAny());
return new Exclude(ees);
}
/**
* Active methods. Want to provide profile-specific methods that:
* - find the latest version without regard to what is below it
* - if no version given, gets the latest version
* - if a starting version given, gets the latest version available *after* that version;
* will time out if no such newer version exists
* Returns a content object, which may or may not be a segment of the latest version, but the
* latest version information is available from its name.
*
* - find the first segment of the latest version of a name
* - if no version given, gets the first segment of the latest version
* - if a starting version given, gets the latest version available *after* that version or times out
* Will ensure that what it returns is a segment of a version of that object.
*
* - generate an interest designed to find the first segment of the latest version
* of a name, in the above form; caller is responsible for checking and re-issuing
*/
/**
* Generate an interest that will find the leftmost child of the latest version. It
* will ensure that the next to last segment is a version, and the last segment (excluding
* digest) is the leftmost child available. But it can't guarantee that the latter is
* a segment. Because most data is segmented, length constraints will make it very
* likely, however.
* @param startingVersion
* @return
*/
public static Interest firstBlockLatestVersionInterest(ContentName startingVersion, PublisherPublicKeyDigest publisher) {
// by the time we look for extra components we will have a version on our name if it
// doesn't have one already, so look for names with 2 extra components -- segment and digest.
return latestVersionInterest(startingVersion, 3, publisher);
}
/**
* Generate an interest that will find a descendant of the latest version of startingVersion,
* after any existing version component. If additionalNameComponents is non-null, it will
* find a descendant with exactly that many name components after the version (including
* the digest). The latest version is the rightmost child of the desired prefix, however,
* this interest will find leftmost descendants of that rightmost child. With appropriate
* length limitations, can be used to find segments of the latest version (though that
* will work more effectively with appropriate segment numbering).
*/
public static Interest latestVersionInterest(ContentName startingVersion, Integer additionalNameComponents, PublisherPublicKeyDigest publisher) {
if (hasTerminalVersion(startingVersion)) {
// Has a version. Make sure it doesn't have a segment; find a version after this one.
startingVersion = SegmentationProfile.segmentRoot(startingVersion);
} else {
// Doesn't have a version. Add the "0" version, so we are finding any version after that.
ContentName firstVersionName = addVersion(startingVersion, baseVersion());
startingVersion = firstVersionName;
}
byte [] versionComponent = startingVersion.lastComponent();
Interest constructedInterest = Interest.last(startingVersion, acceptVersions(versionComponent), startingVersion.count() - 1, additionalNameComponents,
additionalNameComponents, null);
if (null != publisher) {
constructedInterest.publisherID(new PublisherID(publisher));
}
return constructedInterest;
}
/**
* Function to (best effort) get the latest version. There may be newer versions available
* if you ask again passing in the version found (i.e. each response will be the latest version
* a given responder knows about. Further queries will move past that responder to other responders,
* who may have newer information.)
*
* @param name If the name ends in a version then this method explicitly looks for a newer version
* than that, and will time out if no such later version exists. If the name does not end in a
* version then this call just looks for the latest version.
* @param publisher Currently unused, will limit query to a specific publisher.
* @param timeout This is the time to wait until you get any response. If nothing is returned, this method will return null.
* @param verifier Used to verify the returned content objects
* @param handle CCNHandle used to get the latest version
* @return A ContentObject with the latest version, or null if the query timed out.
* @result Returns a matching ContentObject, verified.
* @throws IOException
*/
public static ContentObject getLatestVersion(ContentName startingVersion,
PublisherPublicKeyDigest publisher,
long timeout,
ContentVerifier verifier,
CCNHandle handle) throws IOException {
return getLatestVersion(startingVersion, publisher, timeout, verifier, handle, null, false);
}
/**
* Function to (best effort) get the latest version. There may be newer versions available
* if you ask again passing in the version found (i.e. each response will be the latest version
* a given responder knows about. Further queries will move past that responder to other responders,
* who may have newer information.)
*
* @param name If the name ends in a version then this method explicitly looks for a newer version
* than that, and will time out if no such later version exists. If the name does not end in a
* version then this call just looks for the latest version.
* @param publisher Currently unused, will limit query to a specific publisher.
* @param timeout This is the time to wait until you get any response. If nothing is returned, this method will return null.
* @param verifier Used to verify the returned content objects.
* @param handle CCNHandle used to get the latest version.
* @param startingSegmentNumber If we are requiring content to be a segment, what segment number
* do we want. If null, and findASegment is true, uses SegmentationProfile.baseSegment().
* @param findASegment are we requiring returned content to be a segment of this version
* @return A ContentObject with the latest version, or null if the query timed out.
* @result Returns a matching ContentObject, verified.
* @throws IOException
*/
private static ContentObject getLatestVersion(ContentName startingVersion,
PublisherPublicKeyDigest publisher,
long timeout,
ContentVerifier verifier,
CCNHandle handle,
Long startingSegmentNumber,
boolean findASegment) throws IOException {
Log.info("getFirstBlockOfLatestVersion: getting version later than {0} called with timeout: {1}", startingVersion, timeout);
if (null == verifier) {
// TODO DKS normalize default behavior
verifier = handle.keyManager().getDefaultVerifier();
}
int attempts = 0;
//TODO This timeout is set to SystemConfiguration.MEDIUM_TIMEOUT to work around the problem
//in ccnd where some interests take >300ms (and sometimes longer, have seen periodic delays >800ms)
//when that bug is found and fixed, this can be reduced back to the SHORT_TIMEOUT.
//long attemptTimeout = SystemConfiguration.SHORT_TIMEOUT;
long attemptTimeout = SystemConfiguration.MEDIUM_TIMEOUT;
if (timeout == SystemConfiguration.NO_TIMEOUT) {
//the timeout sent in is equivalent to null... try till we don't hear something back
//we will reset the remaining time after each return...
} else if (timeout > 0 && timeout < attemptTimeout) {
attemptTimeout = timeout;
}
long nullTimeout = attemptTimeout;
if( timeout > attemptTimeout)
nullTimeout = timeout;
long startTime;
long respondTime;
long remainingTime = attemptTimeout;
long remainingNullTime = nullTimeout;
ContentName prefix = startingVersion;
if (hasTerminalVersion(prefix)) {
prefix = startingVersion.parent();
}
int versionedLength = prefix.count() + 1;
ContentObject result = null;
ContentObject lastResult = null;
ArrayList<byte[]> excludeList = new ArrayList<byte[]>();
while (attempts < SystemConfiguration.GET_LATEST_VERSION_ATTEMPTS && remainingTime > 0) {
Log.fine("gLV attempts: {0} attemptTimeout: {1} remainingTime: {2} (timeout: {3})", attempts, attemptTimeout, remainingTime, timeout);
lastResult = result;
attempts++;
Interest getLatestInterest = null;
if (findASegment) {
getLatestInterest = firstBlockLatestVersionInterest(startingVersion, publisher);
} else {
getLatestInterest = latestVersionInterest(startingVersion, null, publisher);
}
if (excludeList.size() > 0) {
//we have explicit excludes, add them to this interest
byte [][] e = new byte[excludeList.size()][];
excludeList.toArray(e);
getLatestInterest.exclude().add(e);
}
startTime = System.currentTimeMillis();
result = handle.get(getLatestInterest, attemptTimeout);
respondTime = System.currentTimeMillis() - startTime;
remainingTime = remainingTime - respondTime;
remainingNullTime = remainingNullTime - respondTime;
if (Log.isLoggable(Level.FINE)) {
Log.fine("gLV INTEREST: {0}", getLatestInterest);
Log.fine("gLV trying handle.get with timeout: {0}", attemptTimeout);
Log.fine("gLVTime sending Interest from gLV at {0}", startTime);
Log.fine("gLVTime returned from handle.get in {0} ms",respondTime);
Log.fine("gLV remaining time is now {0} ms", remainingTime);
}
if (null != result){
if (Log.isLoggable(Level.INFO))
Log.info("gLV getLatestVersion: retrieved latest version object {0} type: {1}", result.name(), result.signedInfo().getTypeName());
//did it verify?
//if it doesn't verify, we need to try harder to get a different content object (exclude this digest)
//make this a loop?
if (!verifier.verify(result)) {
//excludes = addVersionToExcludes(excludes, result.name());
Log.fine("gLV result did not verify, trying to find a verifiable answer");
excludeList = addVersionToExcludes(excludeList, result.name());
//note: need to use the full name, but want to exclude this particular digest. This means we can't cut off the segment marker.
//Interest retry = new Interest(SegmentationProfile.segmentRoot(result.name()), publisher);
//retry.maxSuffixComponents(1);
Interest retry = new Interest(result.name(), publisher);
boolean verifyDone = false;
while (!verifyDone) {
if (retry.exclude() == null)
retry.exclude(new Exclude());
retry.exclude().add(new byte[][] {result.digest()});
if (Log.isLoggable(Level.FINE)) {
Log.fine("gLV result did not verify! doing retry!! {0}", retry);
Log.fine("gLVTime sending retry interest at {0}", System.currentTimeMillis());
}
result = handle.get(retry, attemptTimeout);
if (result!=null) {
if (Log.isLoggable(Level.FINE))
Log.fine("gLV we got something back: {0}", result.name());
if(verifier.verify(result)) {
Log.fine("gLV the returned answer verifies");
verifyDone = true;
} else {
Log.fine("gLV this answer did not verify either... try again");
}
} else {
//result is null, we didn't find a verifiable answer
Log.fine("gLV did not get a verifiable answer back");
verifyDone = true;
}
}
//TODO if this is the latest version and we exclude it, we might not have anything to send back... we should reset the starting version
}
if (result!=null) {
//else {
//it verified! are we done?
//first check if we need to get the first segment...
if (findASegment) {
//yes, we need to have the first segment....
// Now we know the version. Did we luck out and get first block?
if (VersioningProfile.isVersionedFirstSegment(prefix, result, startingSegmentNumber)) {
if (Log.isLoggable(Level.FINE))
Log.fine("getFirstBlockOfLatestVersion: got first block on first try: " + result.name());
} else {
//not the first segment...
// This isn't the first block. Might be simply a later (cached) segment, or might be something
// crazy like a repo_start_write. So what we want is to get the version of this new block -- if getLatestVersion
// is doing its job, we now know the version we want (if we already knew that, we called super.getFirstBlock
// above. If we get here, _baseName isn't versioned yet. So instead of taking segmentRoot of what we got,
// which works fine only if we have the wrong segment rather than some other beast entirely (like metadata).
// So chop off the new name just after the (first) version, and use that. If getLatestVersion is working
// right, that should be the right thing.
ContentName notFirstBlockVersion = result.name().cut(versionedLength);
Log.info("CHILD SELECTOR FAILURE: getFirstBlockOfLatestVersion: Have version information, now querying first segment of " + startingVersion);
// this will verify
//don't count this against the gLV timeout.
result = SegmentationProfile.getSegment(notFirstBlockVersion, startingSegmentNumber, null, timeout, verifier, handle); // now that we have the latest version, go back for the first block.
//if this isn't the first segment... then we should exclude it. otherwise, we can use it!
if(result == null) {
//we couldn't get a new segment...
Log.fine("gLV could not get the first segment of the version we just found... should exclude the version");
//excludes = addVersionToExcludes(excludes, startingVersion);
excludeList = addVersionToExcludes(excludeList, notFirstBlockVersion);
}
}
} else {
//no need to get the first segment!
//this is already verified!
}
//if result is not null, we really have something to try since it also verified
if (result != null) {
//this could be our answer... set to lastResult and see if we have time to do better
lastResult = result;
if (timeout == SystemConfiguration.NO_TIMEOUT) {
//we want to keep trying for something new
remainingTime = attemptTimeout;
attempts = 0;
}
if (timeout == 0) {
//caller just wants the first answer...
attempts = SystemConfiguration.GET_LATEST_VERSION_ATTEMPTS;
remainingTime = 0;
}
if (remainingTime > 0) {
//we still have time to try for a better answer
Log.fine("gLV we still have time to try for a better answer");
attemptTimeout = remainingTime;
} else {
Log.fine("gLV time is up, return what we have");
attempts = SystemConfiguration.GET_LATEST_VERSION_ATTEMPTS;
}
} else {
//result is null
//will be handled below
}
}//the result verified
} //we got something back
if (result == null) {
Log.fine("gLV we didn't get anything");
Log.info("getFirstBlockOfLatestVersion: no block available for later version of {0}", startingVersion);
//we didn't get a new version... we can return the last one we received if it isn't null.
if (lastResult!=null) {
if (Log.isLoggable(Level.FINE)) {
Log.fine("gLV returning the last result that wasn't null... ");
Log.fine("gLV returning: {0}",lastResult.name());
}
return lastResult;
}
else {
Log.fine("gLV we didn't get anything, and we haven't had anything at all... try with remaining long timeout");
attemptTimeout = remainingNullTime;
remainingTime = remainingNullTime;
}
}
Log.fine("gLV (after) attempts: {0} attemptTimeout: {1} remainingTime: {2} (timeout: {3})", attempts, attemptTimeout, remainingTime, timeout);
if (result!=null)
startingVersion = SegmentationProfile.segmentRoot(result.name());
}
if(result!=null) {
if (Log.isLoggable(Level.FINE))
Log.fine("gLV returning: {0}", result.name());
}
return result;
}
/**
* Find a particular segment of the latest version of a name
* - if no version given, gets the desired segment of the latest version
* - if a starting version given, gets the latest version available *after* that version or times out
* Will ensure that what it returns is a segment of a version of that object.
* Also makes sure to return the latest version with a SegmentationProfile.baseSegment() marker.
* * @param desiredName The name of the object we are looking for the first segment of.
* If (VersioningProfile.hasTerminalVersion(desiredName) == false), will get latest version it can
* find of desiredName.
* If desiredName has a terminal version, will try to find the first block of content whose
* version is *after* desiredName (i.e. getLatestVersion starting from desiredName).
* @param startingSegmentNumber The desired block number, or SegmentationProfile.baseSegment() if null.
* @param publisher, if one is specified.
* @param timeout
* @return The first block of a stream with a version later than desiredName, or null if timeout is reached.
* This block is verified.
* @throws IOException
*/
public static ContentObject getFirstBlockOfLatestVersion(ContentName startingVersion,
Long startingSegmentNumber,
PublisherPublicKeyDigest publisher,
long timeout,
ContentVerifier verifier,
CCNHandle handle) throws IOException {
return getLatestVersion(startingVersion, publisher, timeout, verifier, handle, startingSegmentNumber, true);
}
/**
* Version of isFirstSegment that expects names to be versioned, and allows that desiredName
* won't know what version it wants but will want some version.
*/
public static boolean isVersionedFirstSegment(ContentName desiredName, ContentObject potentialFirstSegment, Long startingSegmentNumber) {
if ((null != potentialFirstSegment) && (SegmentationProfile.isSegment(potentialFirstSegment.name()))) {
if (Log.isLoggable(Level.INFO))
Log.info("is " + potentialFirstSegment.name() + " a first segment of " + desiredName);
// In theory, the segment should be at most a versioning component different from desiredName.
// In the case of complex segmented objects (e.g. a KeyDirectory), where there is a version,
// then some name components, then a segment, desiredName should contain all of those other
// name components -- you can't use the usual versioning mechanisms to pull first segment anyway.
if (!desiredName.isPrefixOf(potentialFirstSegment.name())) {
if (Log.isLoggable(Level.INFO))
Log.info("Desired name :" + desiredName + " is not a prefix of segment: " + potentialFirstSegment.name());
return false;
}
int difflen = potentialFirstSegment.name().count() - desiredName.count();
if (difflen > 2) {
if (Log.isLoggable(Level.INFO))
Log.info("Have " + difflen + " extra components between " + potentialFirstSegment.name() + " and desired " + desiredName);
return false;
}
// Now need to make sure that if the difference is more than 1, that difference is
// a version component.
if ((difflen == 2) && (!isVersionComponent(potentialFirstSegment.name().component(potentialFirstSegment.name().count()-2)))) {
if (Log.isLoggable(Level.INFO))
Log.info("The " + difflen + " extra component between " + potentialFirstSegment.name() + " and desired " + desiredName + " is not a version.");
}
if ((null != startingSegmentNumber) && (SegmentationProfile.baseSegment() != startingSegmentNumber)) {
return (startingSegmentNumber.longValue() == SegmentationProfile.getSegmentNumber(potentialFirstSegment.name()));
} else {
return SegmentationProfile.isFirstSegment(potentialFirstSegment.name());
}
}
return false;
}
/**
* Adds version components to the exclude list for the getLatestVersion method.
* @param excludeList current excludes
* @param name component to add to the exclude list
* @return updated exclude list
*/
private static ArrayList<byte[]> addVersionToExcludes(ArrayList<byte[]> excludeList, ContentName name) {
try {
excludeList.add(VersioningProfile.getLastVersionComponent(name));
} catch (VersionMissingException e) {
Log.warning("failed to exclude content object version that did not verify: {0}",name);
}
return excludeList;
}
}
|
Helper methods to add and remove version marker.
|
javasrc/src/org/ccnx/ccn/profiles/VersioningProfile.java
|
Helper methods to add and remove version marker.
|
<ide><path>avasrc/src/org/ccnx/ccn/profiles/VersioningProfile.java
<ide> }
<ide> return excludeList;
<ide> }
<add>
<add> public static byte[] versionComponentFromStripped(byte[] bs) {
<add> if (null == bs)
<add> return null;
<add> byte [] versionComponent = new byte[bs.length + 1];
<add> versionComponent[0] = VERSION_MARKER;
<add> System.arraycopy(bs, 0, versionComponent, 1, bs.length);
<add> return versionComponent;
<add> }
<add>
<add> public static byte[] stripVersionMarker(byte[] version) throws VersionMissingException {
<add> if (null == version)
<add> return null;
<add> if (VERSION_MARKER != version[0]) {
<add> throw new VersionMissingException("This is not a version component!");
<add> }
<add> byte [] stripped = new byte[version.length - 1];
<add> System.arraycopy(version, 1, stripped, 0, stripped.length);
<add> return stripped;
<add> }
<ide>
<ide> }
|
|
Java
|
mit
|
9d2cda3d410639beaee65ae5a393e4d7f77631f6
| 0 |
iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable
|
// our package
package org.broadinstitute.sting.utils.baq;
// the imports for unit testing.
import org.broadinstitute.sting.utils.exceptions.UserException;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.testng.annotations.DataProvider;
import org.testng.annotations.BeforeMethod;
import org.broadinstitute.sting.BaseTest;
import org.broadinstitute.sting.utils.sam.ArtificialSAMUtils;
import org.broadinstitute.sting.utils.Utils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.List;
import java.util.ArrayList;
import net.sf.picard.reference.IndexedFastaSequenceFile;
import net.sf.samtools.*;
/**
* Basic unit test for GenomeLoc
*/
public class BAQUnitTest extends BaseTest {
private SAMFileHeader header;
private final int startChr = 1;
private final int numChr = 2;
private final int chrSize = 1000;
IndexedFastaSequenceFile fasta = null;
@BeforeMethod
public void before() {
header = ArtificialSAMUtils.createArtificialSamHeader(numChr, startChr, chrSize);
File referenceFile = new File(hg18Reference);
try {
fasta = new IndexedFastaSequenceFile(referenceFile);
}
catch(FileNotFoundException ex) {
throw new UserException.CouldNotReadInputFile(referenceFile,ex);
}
}
private class BAQTest {
String readBases, refBases;
byte[] quals, expected;
String cigar;
int refOffset;
int pos;
public BAQTest(String _refBases, String _readBases, String _quals, String _expected) {
this(0, -1, null, _readBases, _refBases, _quals, _expected);
}
public BAQTest(int refOffset, String _refBases, String _readBases, String _quals, String _expected) {
this(refOffset, -1, null, _refBases, _readBases, _quals, _expected);
}
public BAQTest(long pos, String cigar, String _readBases, String _quals, String _expected) {
this(0, pos, cigar, null, _readBases, _quals, _expected);
}
public BAQTest(int _refOffset, long _pos, String _cigar, String _refBases, String _readBases, String _quals, String _expected) {
refOffset = _refOffset;
pos = (int)_pos;
cigar = _cigar;
readBases = _readBases;
refBases = _refBases;
quals = new byte[_quals.getBytes().length];
expected = new byte[_quals.getBytes().length];
for ( int i = 0; i < quals.length; i++) {
quals[i] = (byte)(_quals.getBytes()[i] - 33);
expected[i] = (byte)(_expected.getBytes()[i] - 33);
}
}
public String toString() { return readBases; }
public SAMRecord createRead() {
SAMRecord read = ArtificialSAMUtils.createArtificialRead(header, "foo", 0, pos > 0 ? pos + (refOffset > 0 ? refOffset : 0): 1, readBases.getBytes(), quals);
//if ( cigar != null ) read.setAlignmentEnd(readBases.getBytes().length + pos);
read.setCigarString( cigar == null ? String.format("%dM", quals.length) : cigar);
return read;
}
}
@DataProvider(name = "data")
public Object[][] createData1() {
List<BAQTest> params = new ArrayList<BAQTest>();
params.add(new BAQTest("GCTGCTCCTGGTACTGCTGGATGAGGGCCTCGATGAAGCTAAGCTTTTTCTCCTGCTCCTGCGTGATCCGCTGCAG",
"GCTGCTCCTGGTACTGCTGGATGAGGGCCTCGATGAAGCTAAGCTTTTCCTCCTGCTCCTGCGTGATCCGCTGCAG",
"?BACCBDDDFFBCFFHHFIHFEIFHIGHHGHBFEIFGIIGEGIIHGGGIHHIIHIIHIIHGICCIGEII@IGIHCG",
"?BACCBDDDFFBCFFHHFIHFEIFHIGHHGHBFEIFGIIGEGII410..0HIIHIIHIIHGICCIGEII@IGIHCE"));
params.add(new BAQTest("GCTTTTTCTCCTCCTG",
"GCTTTTCCTCCTCCTG",
"IIHGGGIHHIIHHIIH",
"EI410..0HIIHHIIE"));
// big and complex, also does a cap from 3 to 4!
params.add(new BAQTest(-3, 9999810l, "49M1I126M1I20M1I25M",
"AAATTCAAGATTTCAAAGGCTCTTAACTGCTCAAGATAATTTTTTTTTTTTGAGACAGAGTCTTGCTGTGTTGCCCAGGCTGGAGTGCAGTGGCGTGATCTTGGCTCACTGCAAGCTCCGCCTCCCGGGTTCACGCCATTCTCCTGCCTCAGCCTCCCGAGTAGCTGGGACTACAGGCACCCACCACCACGCCTGGCCAATTTTTTTGTATTTTTAGTAGAGATAG",
"TTCAAGATTTCAAAGGCTCTTAACTGCTCAAGATAATTTTTTTTTTTTGTAGACAGAGTCTTGCTGTGTTGCCCAGGCTGGAGTGCAGTGGCGTGATCTTGGCTCACTGCAAGCTCCGCCTCCCGGGTTCACGCCATTCTCCTGCCTCAGCCTCCCGAGTAGCTGGGACTACAGGCCACCCACCACCACGCCTGGCCTAATTTTTTTGTATTTTTAGTAGAGA",
">IHFECEBDBBCBCABABAADBD?AABBACEABABC?>?B>@A@@>A?B3BBC?CBDBAABBBBBAABAABBABDACCCBCDAACBCBABBB:ABDBACBBDCCCCABCDCCBCC@@;?<B@BC;CBBBAB=;A>ACBABBBABBCA@@<?>>AAA<CA@AABBABCC?BB8@<@C<>5;<A5=A;>=64>???B>=6497<<;;<;>2?>BA@??A6<<A59",
">EHFECEBDBBCBCABABAADBD?AABBACEABABC?>?B>@A@@>A?838BC?CBDBAABBBBBAABAABBABDACCCBCDAACBCBABBB:ABDBACBBDCCCCABCDCCBCC@@;?<B@BC;CBBBAB=;A>ACBABBBABBCA@@<?>>AAA<CA@AABBABCC?BB8@<@%<>5;<A5=A;>=64>???B;86497<<;;<;>2?>BA@??A6<<A59"));
// now changes
params.add(new BAQTest(-3, 9999966l, "36M",
"CCGAGTAGCTGGGACTACAGGCACCCACCACCACGCCTGGCC",
"AGTAGCTGGGACTACAGGCACCCACCACCACGCCTG",
"A?>>@>AA?@@>A?>A@?>@>>?=>?'>?=>7=?A9",
"A?>>@>AA?@@>A?>A@?>@>>?=>?'>?=>7=?A9"));
// raw base qualities are low -- but they shouldn't be capped
params.add(new BAQTest(-3, 9999993l, "36M",
"CCACCACGCCTGGCCAATTTTTTTGTATTTTTAGTAGAGATA",
"CCACGCTTGGCAAAGTTTTCCGTACGTTTAGCCGAG",
"33'/(7+270&4),(&&-)$&,%7$',-/61(,6?8",
"33'/(7+270&4),(&&-)$&,%7$',-/61(,6?8"));
// soft clipping
// todo soft clip testing just doesn't work right now!
// params.add(new BAQTest(29, 10000109l, "29S190M",
// null, "GAAGGTTGAATCAAACCTTCGGTTCCAACGGATTACAGGTGTGAGCCACCGCGACCGGCCTGCTCAAGATAATTTTTAGGGCTAACTATGACATGAACCCCAAAATTCCTGTCCTCTAGATGGCAGAAACCAAGATAAAGTATCCCCACATGGCCACAAGGTTAAGCTCTTATGGACACAAAACAAGGCAGAGAAATGTCATTTGGCATTGGTTTCAGG",
// "3737088:858278273772:3<=;:?;5=9@>@?>@=<>8?>@=>>?>4=5>?=5====A==@?A@=@6@A><?B:A;:;>@A?>?AA>@?AA>A?>==?AAA@@A>=A<A>>A=?A>AA==@A?AA?>?AA?A@@C@:?A@<;::??AA==>@@?BB=<A?BA>>A>A?AB=???@?BBA@?BA==?A>A?BB=A:@?ABAB>>?ABB>8A@BAIGA",
// "3737088:858278273772:3<=;:?;5=9@>@?>@=<>8?>@=>>?>4=5>?=5====A==@?A@=@6@A><?B:A;:;>@A?>?AA>@?AA>A?>==?AAA@@A>=A<A>>A=?A>AA==@A?AA?>?AA?A@@C@:?A@<;::??AA==>@@?BB=<A?BA>>A>A?AB=???@?BBA@?BA==?A>A?BB=A:@?ABAB>>?ABB>8A@BAI>;"));
// params.add(new BAQTest(30, 10000373l, "30S69M1D2M",
// null, "TGAAATCCTGCCTTATAGTTCCCCTAAACCCACGTTCTATCCCCAGATACTCCCCTCTTCATTACAGAACAACAAAGAAAGACAAATTCTTAGCATCAATG",
// "###############################=89>B;6<;96*>.1799>++66=:=:8=<-.9>><;9<':-+;*+::=;8=;;.::<:;=/2=70<=?-",
// "###############################=89>B;6<;96*>.1799>++66=:=:8=<-.9>><;9<':-+;*+::=;8=;;.::<:;=/2=7000%%"));
// params.add(new BAQTest(5, 10000109l, "5S5M",
// "GAAGGTTGAA",
// null,
// "HHHHHHHHHH",
// "HHHHHHHHHE"));
// params.add(new BAQTest(10009480l, "102M1I18M1I16M1I43M1I10M1D9M1I7M1I7M1I16M1I9M1I8M1I14M2I18M",
// "AGAGATGGGGTTTCGCCATGTTGTCCAGGCTGGTCTTGAACTCCTGACCTCAAGTGATCTGCCCACCTCGGCCTCCCAAAGTGCTGGGATTACACGTGTGAAACCACCATGCCTGGTCTCTTAATTTTTCNGATTCTAATAAAATTACATTCTATTTGCTGAAAGNGTACTTTAGAGTTGAAAGAAAAAGAAAGGNGTGGAACTTCCCCTAGTAAACAAGGAAAAACNTCCATGTTATTTATTGGACCTTAAAAATAGTGAAACATCTTAAGAAAAAAAATCAATCCTA",
// "@HI@BA<?C@?CA>7>=AA>9@==??C???@?>:?BB@BA>B?=A@@<=B?AB???@@@@@?=?A==B@7<<?@>==>=<=>???>=@@A?<=B:5?413577/675;><;==@=<>>968;6;>????:#;=?>:3072077726/6;3719;9A=9;774771#30532676??=8::97<7144448/4425#65688821515986255/5601548355551#218>96/5/8<4/.2344/914/55553)1047;:30312:4:63556565631=:62610",
// "@HI@BA<?C@?CA>7>=AA>9@==??C???@?>:?BB@BA>B?=A@@<=B?AB???@@@@@?=?A==B@7<<?@>==>=<=>???>=@@A?<=B:5?413&!7/675;><;==@=<>>96!;6;>????:#;=?>:3!72077726/6;3719;9A=9;774771#30532676??=8::&!<7144448'$!25#65687421515986255/560!548355551#218>96!5/8<4/.2344/614(%!!53)1047;:30312:4:63556565631=:62610"));
List<Object[]> params2 = new ArrayList<Object[]>();
for ( BAQTest x : params ) params2.add(new Object[]{x});
return params2.toArray(new Object[][]{});
}
@Test(dataProvider = "data", enabled = true)
public void testBAQWithProvidedReference(BAQTest test) {
if ( test.refBases != null ) {
testBAQ(test, false);
}
}
@Test(dataProvider = "data", enabled = true)
public void testBAQWithCigarAndRefLookup(BAQTest test) {
if ( test.cigar != null ) {
testBAQ(test, true);
}
}
public void testBAQ(BAQTest test, boolean lookupWithFasta) {
BAQ baqHMM = new BAQ(1e-3, 0.1, 7, (byte)4, false); // matches current samtools parameters
SAMRecord read = test.createRead();
BAQ.BAQCalculationResult result;
if ( lookupWithFasta && test.cigar != null )
result = baqHMM.calcBAQFromHMM(read, fasta);
else
result = baqHMM.calcBAQFromHMM(read, test.refBases.getBytes(), test.refOffset);
System.out.println(Utils.dupString('-', 40));
System.out.println("reads : " + new String(test.readBases));
printQuals(System.out, "in-quals:", test.quals, false);
printQuals(System.out, "bq-quals:", result.bq, false);
for (int i = 0; i < test.quals.length; i++) {
//result.bq[i] = baqHMM.capBaseByBAQ(result.rawQuals[i], result.bq[i], result.state[i], i);
Assert.assertTrue(result.bq[i] >= baqHMM.getMinBaseQual() || test.expected[i] < baqHMM.getMinBaseQual(), "BQ < min base quality");
Assert.assertEquals(result.bq[i], test.expected[i], "Did not see the expected BAQ value at " + i);
}
}
public final static void printQuals( PrintStream out, String prefix, byte[] quals, boolean asInt ) {
out.print(prefix);
for ( int i = 0; i < quals.length; i++) {
if ( asInt ) {
out.printf("%2d", (int)quals[i]);
if ( i+1 != quals.length ) out.print(",");
} else
out.print((char)(quals[i]+33));
}
out.println();
}
}
|
public/java/test/org/broadinstitute/sting/utils/baq/BAQUnitTest.java
|
// our package
package org.broadinstitute.sting.utils.baq;
// the imports for unit testing.
import org.broadinstitute.sting.utils.exceptions.UserException;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.testng.annotations.DataProvider;
import org.testng.annotations.BeforeMethod;
import org.broadinstitute.sting.BaseTest;
import org.broadinstitute.sting.gatk.walkers.qc.ValidateBAQWalker;
import org.broadinstitute.sting.utils.sam.ArtificialSAMUtils;
import org.broadinstitute.sting.utils.Utils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.List;
import java.util.ArrayList;
import net.sf.picard.reference.IndexedFastaSequenceFile;
import net.sf.samtools.*;
/**
* Basic unit test for GenomeLoc
*/
public class BAQUnitTest extends BaseTest {
private SAMFileHeader header;
private final int startChr = 1;
private final int numChr = 2;
private final int chrSize = 1000;
IndexedFastaSequenceFile fasta = null;
@BeforeMethod
public void before() {
header = ArtificialSAMUtils.createArtificialSamHeader(numChr, startChr, chrSize);
File referenceFile = new File(hg18Reference);
try {
fasta = new IndexedFastaSequenceFile(referenceFile);
}
catch(FileNotFoundException ex) {
throw new UserException.CouldNotReadInputFile(referenceFile,ex);
}
}
private class BAQTest {
String readBases, refBases;
byte[] quals, expected;
String cigar;
int refOffset;
int pos;
public BAQTest(String _refBases, String _readBases, String _quals, String _expected) {
this(0, -1, null, _readBases, _refBases, _quals, _expected);
}
public BAQTest(int refOffset, String _refBases, String _readBases, String _quals, String _expected) {
this(refOffset, -1, null, _refBases, _readBases, _quals, _expected);
}
public BAQTest(long pos, String cigar, String _readBases, String _quals, String _expected) {
this(0, pos, cigar, null, _readBases, _quals, _expected);
}
public BAQTest(int _refOffset, long _pos, String _cigar, String _refBases, String _readBases, String _quals, String _expected) {
refOffset = _refOffset;
pos = (int)_pos;
cigar = _cigar;
readBases = _readBases;
refBases = _refBases;
quals = new byte[_quals.getBytes().length];
expected = new byte[_quals.getBytes().length];
for ( int i = 0; i < quals.length; i++) {
quals[i] = (byte)(_quals.getBytes()[i] - 33);
expected[i] = (byte)(_expected.getBytes()[i] - 33);
}
}
public String toString() { return readBases; }
public SAMRecord createRead() {
SAMRecord read = ArtificialSAMUtils.createArtificialRead(header, "foo", 0, pos > 0 ? pos + (refOffset > 0 ? refOffset : 0): 1, readBases.getBytes(), quals);
//if ( cigar != null ) read.setAlignmentEnd(readBases.getBytes().length + pos);
read.setCigarString( cigar == null ? String.format("%dM", quals.length) : cigar);
return read;
}
}
@DataProvider(name = "data")
public Object[][] createData1() {
List<BAQTest> params = new ArrayList<BAQTest>();
params.add(new BAQTest("GCTGCTCCTGGTACTGCTGGATGAGGGCCTCGATGAAGCTAAGCTTTTTCTCCTGCTCCTGCGTGATCCGCTGCAG",
"GCTGCTCCTGGTACTGCTGGATGAGGGCCTCGATGAAGCTAAGCTTTTCCTCCTGCTCCTGCGTGATCCGCTGCAG",
"?BACCBDDDFFBCFFHHFIHFEIFHIGHHGHBFEIFGIIGEGIIHGGGIHHIIHIIHIIHGICCIGEII@IGIHCG",
"?BACCBDDDFFBCFFHHFIHFEIFHIGHHGHBFEIFGIIGEGII410..0HIIHIIHIIHGICCIGEII@IGIHCE"));
params.add(new BAQTest("GCTTTTTCTCCTCCTG",
"GCTTTTCCTCCTCCTG",
"IIHGGGIHHIIHHIIH",
"EI410..0HIIHHIIE"));
// big and complex, also does a cap from 3 to 4!
params.add(new BAQTest(-3, 9999810l, "49M1I126M1I20M1I25M",
"AAATTCAAGATTTCAAAGGCTCTTAACTGCTCAAGATAATTTTTTTTTTTTGAGACAGAGTCTTGCTGTGTTGCCCAGGCTGGAGTGCAGTGGCGTGATCTTGGCTCACTGCAAGCTCCGCCTCCCGGGTTCACGCCATTCTCCTGCCTCAGCCTCCCGAGTAGCTGGGACTACAGGCACCCACCACCACGCCTGGCCAATTTTTTTGTATTTTTAGTAGAGATAG",
"TTCAAGATTTCAAAGGCTCTTAACTGCTCAAGATAATTTTTTTTTTTTGTAGACAGAGTCTTGCTGTGTTGCCCAGGCTGGAGTGCAGTGGCGTGATCTTGGCTCACTGCAAGCTCCGCCTCCCGGGTTCACGCCATTCTCCTGCCTCAGCCTCCCGAGTAGCTGGGACTACAGGCCACCCACCACCACGCCTGGCCTAATTTTTTTGTATTTTTAGTAGAGA",
">IHFECEBDBBCBCABABAADBD?AABBACEABABC?>?B>@A@@>A?B3BBC?CBDBAABBBBBAABAABBABDACCCBCDAACBCBABBB:ABDBACBBDCCCCABCDCCBCC@@;?<B@BC;CBBBAB=;A>ACBABBBABBCA@@<?>>AAA<CA@AABBABCC?BB8@<@C<>5;<A5=A;>=64>???B>=6497<<;;<;>2?>BA@??A6<<A59",
">EHFECEBDBBCBCABABAADBD?AABBACEABABC?>?B>@A@@>A?838BC?CBDBAABBBBBAABAABBABDACCCBCDAACBCBABBB:ABDBACBBDCCCCABCDCCBCC@@;?<B@BC;CBBBAB=;A>ACBABBBABBCA@@<?>>AAA<CA@AABBABCC?BB8@<@%<>5;<A5=A;>=64>???B;86497<<;;<;>2?>BA@??A6<<A59"));
// now changes
params.add(new BAQTest(-3, 9999966l, "36M",
"CCGAGTAGCTGGGACTACAGGCACCCACCACCACGCCTGGCC",
"AGTAGCTGGGACTACAGGCACCCACCACCACGCCTG",
"A?>>@>AA?@@>A?>A@?>@>>?=>?'>?=>7=?A9",
"A?>>@>AA?@@>A?>A@?>@>>?=>?'>?=>7=?A9"));
// raw base qualities are low -- but they shouldn't be capped
params.add(new BAQTest(-3, 9999993l, "36M",
"CCACCACGCCTGGCCAATTTTTTTGTATTTTTAGTAGAGATA",
"CCACGCTTGGCAAAGTTTTCCGTACGTTTAGCCGAG",
"33'/(7+270&4),(&&-)$&,%7$',-/61(,6?8",
"33'/(7+270&4),(&&-)$&,%7$',-/61(,6?8"));
// soft clipping
// todo soft clip testing just doesn't work right now!
// params.add(new BAQTest(29, 10000109l, "29S190M",
// null, "GAAGGTTGAATCAAACCTTCGGTTCCAACGGATTACAGGTGTGAGCCACCGCGACCGGCCTGCTCAAGATAATTTTTAGGGCTAACTATGACATGAACCCCAAAATTCCTGTCCTCTAGATGGCAGAAACCAAGATAAAGTATCCCCACATGGCCACAAGGTTAAGCTCTTATGGACACAAAACAAGGCAGAGAAATGTCATTTGGCATTGGTTTCAGG",
// "3737088:858278273772:3<=;:?;5=9@>@?>@=<>8?>@=>>?>4=5>?=5====A==@?A@=@6@A><?B:A;:;>@A?>?AA>@?AA>A?>==?AAA@@A>=A<A>>A=?A>AA==@A?AA?>?AA?A@@C@:?A@<;::??AA==>@@?BB=<A?BA>>A>A?AB=???@?BBA@?BA==?A>A?BB=A:@?ABAB>>?ABB>8A@BAIGA",
// "3737088:858278273772:3<=;:?;5=9@>@?>@=<>8?>@=>>?>4=5>?=5====A==@?A@=@6@A><?B:A;:;>@A?>?AA>@?AA>A?>==?AAA@@A>=A<A>>A=?A>AA==@A?AA?>?AA?A@@C@:?A@<;::??AA==>@@?BB=<A?BA>>A>A?AB=???@?BBA@?BA==?A>A?BB=A:@?ABAB>>?ABB>8A@BAI>;"));
// params.add(new BAQTest(30, 10000373l, "30S69M1D2M",
// null, "TGAAATCCTGCCTTATAGTTCCCCTAAACCCACGTTCTATCCCCAGATACTCCCCTCTTCATTACAGAACAACAAAGAAAGACAAATTCTTAGCATCAATG",
// "###############################=89>B;6<;96*>.1799>++66=:=:8=<-.9>><;9<':-+;*+::=;8=;;.::<:;=/2=70<=?-",
// "###############################=89>B;6<;96*>.1799>++66=:=:8=<-.9>><;9<':-+;*+::=;8=;;.::<:;=/2=7000%%"));
// params.add(new BAQTest(5, 10000109l, "5S5M",
// "GAAGGTTGAA",
// null,
// "HHHHHHHHHH",
// "HHHHHHHHHE"));
// params.add(new BAQTest(10009480l, "102M1I18M1I16M1I43M1I10M1D9M1I7M1I7M1I16M1I9M1I8M1I14M2I18M",
// "AGAGATGGGGTTTCGCCATGTTGTCCAGGCTGGTCTTGAACTCCTGACCTCAAGTGATCTGCCCACCTCGGCCTCCCAAAGTGCTGGGATTACACGTGTGAAACCACCATGCCTGGTCTCTTAATTTTTCNGATTCTAATAAAATTACATTCTATTTGCTGAAAGNGTACTTTAGAGTTGAAAGAAAAAGAAAGGNGTGGAACTTCCCCTAGTAAACAAGGAAAAACNTCCATGTTATTTATTGGACCTTAAAAATAGTGAAACATCTTAAGAAAAAAAATCAATCCTA",
// "@HI@BA<?C@?CA>7>=AA>9@==??C???@?>:?BB@BA>B?=A@@<=B?AB???@@@@@?=?A==B@7<<?@>==>=<=>???>=@@A?<=B:5?413577/675;><;==@=<>>968;6;>????:#;=?>:3072077726/6;3719;9A=9;774771#30532676??=8::97<7144448/4425#65688821515986255/5601548355551#218>96/5/8<4/.2344/914/55553)1047;:30312:4:63556565631=:62610",
// "@HI@BA<?C@?CA>7>=AA>9@==??C???@?>:?BB@BA>B?=A@@<=B?AB???@@@@@?=?A==B@7<<?@>==>=<=>???>=@@A?<=B:5?413&!7/675;><;==@=<>>96!;6;>????:#;=?>:3!72077726/6;3719;9A=9;774771#30532676??=8::&!<7144448'$!25#65687421515986255/560!548355551#218>96!5/8<4/.2344/614(%!!53)1047;:30312:4:63556565631=:62610"));
List<Object[]> params2 = new ArrayList<Object[]>();
for ( BAQTest x : params ) params2.add(new Object[]{x});
return params2.toArray(new Object[][]{});
}
@Test(dataProvider = "data", enabled = true)
public void testBAQWithProvidedReference(BAQTest test) {
if ( test.refBases != null ) {
testBAQ(test, false);
}
}
@Test(dataProvider = "data", enabled = true)
public void testBAQWithCigarAndRefLookup(BAQTest test) {
if ( test.cigar != null ) {
testBAQ(test, true);
}
}
public void testBAQ(BAQTest test, boolean lookupWithFasta) {
BAQ baqHMM = new BAQ(1e-3, 0.1, 7, (byte)4, false); // matches current samtools parameters
SAMRecord read = test.createRead();
BAQ.BAQCalculationResult result;
if ( lookupWithFasta && test.cigar != null )
result = baqHMM.calcBAQFromHMM(read, fasta);
else
result = baqHMM.calcBAQFromHMM(read, test.refBases.getBytes(), test.refOffset);
System.out.println(Utils.dupString('-', 40));
System.out.println("reads : " + new String(test.readBases));
printQuals(System.out, "in-quals:", test.quals, false);
printQuals(System.out, "bq-quals:", result.bq, false);
for (int i = 0; i < test.quals.length; i++) {
//result.bq[i] = baqHMM.capBaseByBAQ(result.rawQuals[i], result.bq[i], result.state[i], i);
Assert.assertTrue(result.bq[i] >= baqHMM.getMinBaseQual() || test.expected[i] < baqHMM.getMinBaseQual(), "BQ < min base quality");
Assert.assertEquals(result.bq[i], test.expected[i], "Did not see the expected BAQ value at " + i);
}
}
public final static void printQuals( PrintStream out, String prefix, byte[] quals, boolean asInt ) {
out.print(prefix);
for ( int i = 0; i < quals.length; i++) {
if ( asInt ) {
out.printf("%2d", (int)quals[i]);
if ( i+1 != quals.length ) out.print(",");
} else
out.print((char)(quals[i]+33));
}
out.println();
}
}
|
Removed a public -> private dependency in our test suite.
|
public/java/test/org/broadinstitute/sting/utils/baq/BAQUnitTest.java
|
Removed a public -> private dependency in our test suite.
|
<ide><path>ublic/java/test/org/broadinstitute/sting/utils/baq/BAQUnitTest.java
<ide> import org.testng.annotations.DataProvider;
<ide> import org.testng.annotations.BeforeMethod;
<ide> import org.broadinstitute.sting.BaseTest;
<del>import org.broadinstitute.sting.gatk.walkers.qc.ValidateBAQWalker;
<ide> import org.broadinstitute.sting.utils.sam.ArtificialSAMUtils;
<ide> import org.broadinstitute.sting.utils.Utils;
<ide>
|
|
Java
|
apache-2.0
|
0933c9eee125d046ea0776d57fb74d9a8df68032
| 0 |
tabish121/qpid-jms,gemmellr/qpid-jms,gemmellr/qpid-jms,apache/qpid-jms,tabish121/qpid-jms,apache/qpid-jms
|
/*
* 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.qpid.jms.provider.failover;
import static org.junit.Assert.fail;
import java.net.ServerSocket;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.net.ServerSocketFactory;
import org.apache.qpid.jms.JmsConnectionFactory;
import org.apache.qpid.jms.test.QpidJmsTestCase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Tests failover reconnect behavior when the remote side is not accepting socket connections
* in a normal manner.
*/
public class FailoverSocketLevelAcceptFailures extends QpidJmsTestCase {
private static final Logger LOG = LoggerFactory.getLogger(FailoverSocketLevelAcceptFailures.class);
private ServerSocket server;
@Override
@Before
public void setUp() throws Exception {
super.setUp();
server = ServerSocketFactory.getDefault().createServerSocket(0);
}
@Override
@After
public void tearDown() throws Exception {
try {
server.close();
server = null;
} catch (Exception ignored) {
}
super.tearDown();
}
@Test(timeout = 40000)
public void testFailoverHandlesSocketNotAccepted() throws Exception {
final String remoteURI = "failover:(amqp://localhost:" + server.getLocalPort() +
")?jms.connectTimeout=666&failover.maxReconnectAttempts=1&failover.startupMaxReconnectAttempts=1";
try {
ConnectionFactory cf = new JmsConnectionFactory(remoteURI);
Connection connection = cf.createConnection();
connection.start();
fail("Should throw error once the connection starts");
} catch (Exception ex) {
LOG.info("Error on connect:", ex);
}
}
}
|
qpid-jms-client/src/test/java/org/apache/qpid/jms/provider/failover/FailoverSocketLevelAcceptFailures.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.qpid.jms.provider.failover;
import static org.junit.Assert.fail;
import java.net.ServerSocket;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.net.ServerSocketFactory;
import org.apache.qpid.jms.JmsConnectionFactory;
import org.apache.qpid.jms.test.QpidJmsTestCase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Tests failover reconnect behavior when the remote side is not accepting socket connections
* in a normal manner.
*/
public class FailoverSocketLevelAcceptFailures extends QpidJmsTestCase {
private static final Logger LOG = LoggerFactory.getLogger(FailoverSocketLevelAcceptFailures.class);
private ServerSocket server;
@Override
@Before
public void setUp() throws Exception {
super.setUp();
server = ServerSocketFactory.getDefault().createServerSocket(0);
}
@Override
@After
public void tearDown() throws Exception {
try {
server.close();
server = null;
} catch (Exception ignored) {
}
super.tearDown();
}
@Test(timeout = 40000)
public void testFailoverHandlesRedirection() throws Exception {
final String remoteURI = "failover:(amqp://localhost:" + server.getLocalPort() +
")?jms.connectTimeout=666&failover.maxReconnectAttempts=1&failover.startupMaxReconnectAttempts=1";
try {
ConnectionFactory cf = new JmsConnectionFactory(remoteURI);
Connection connection = cf.createConnection();
connection.start();
fail("Should throw error once the connection starts");
} catch (Exception ex) {
LOG.info("Error on connect:", ex);
}
}
}
|
QPIDJMS-342: fix the test name
|
qpid-jms-client/src/test/java/org/apache/qpid/jms/provider/failover/FailoverSocketLevelAcceptFailures.java
|
QPIDJMS-342: fix the test name
|
<ide><path>pid-jms-client/src/test/java/org/apache/qpid/jms/provider/failover/FailoverSocketLevelAcceptFailures.java
<ide> }
<ide>
<ide> @Test(timeout = 40000)
<del> public void testFailoverHandlesRedirection() throws Exception {
<add> public void testFailoverHandlesSocketNotAccepted() throws Exception {
<ide> final String remoteURI = "failover:(amqp://localhost:" + server.getLocalPort() +
<ide> ")?jms.connectTimeout=666&failover.maxReconnectAttempts=1&failover.startupMaxReconnectAttempts=1";
<ide>
|
|
Java
|
mit
|
9773c49d2c6830f01faecb693398a97215a02b60
| 0 |
isis-ammo/ammo-lib,isis-ammo/ammo-lib
|
package edu.vu.isis.ammo.core.provider;
import java.util.ArrayList;
import android.provider.BaseColumns;
import edu.vu.isis.ammo.util.EnumUtils;
public enum PresenceSchema {
/** This is a locally unique identifier for the request */
ID(BaseColumns._ID,"TEXT"),
/** This is a universally unique identifier for the request */
UUID("TEXT"),
/** Device originating the request */
ORIGIN("TEXT"),
/** Who last modified the request */
OPERATOR("TEXT"),
/** Presence state: 1=available, 2=not available, etc.*/
STATE("INTEGER"),
/** The time when first observed (millisec); indicates the first time the peer was observed.*/
FIRST("INTEGER"),
/** when last observed (millisec);
* When the operator was last seen "speaking" on the channel.
* The latest field indicates the last time the peer was observed. */
LATEST("INTEGER"),
/** how many times seen since first.
* How many times the peer has been seen since FIRST.
* Each time LATEST is changed this COUNT should be incremented*/
COUNT("INTEGER"),
/** The time when no longer relevant (millisec);
* the request becomes stale and may be discarded. */
EXPIRATION("INTEGER");
/** textual field name */
final public String field;
/** type */
final public String type;
private PresenceSchema( String type) {
this.field = this.name();
this.type = type;
}
private PresenceSchema( String field, String type) {
this.field = field;
this.type = type;
}
/**
* an array of all field names
*/
public static final String[] FIELD_NAMES
= EnumUtils.buildFieldNames(PresenceSchema.class);
/**
* map an array of field names to fields.
*
* @param names an array of field names
* @return an array of fields
*/
public static ArrayList<PresenceSchema> mapFields(final String[] names) {
return EnumUtils.getFields(PresenceSchema.class, names);
}
@Override
public String toString() {
return this.field;
}
}
|
AmmoLib/src/edu/vu/isis/ammo/core/provider/PresenceSchema.java
|
package edu.vu.isis.ammo.core.provider;
import java.util.ArrayList;
import android.provider.BaseColumns;
import edu.vu.isis.ammo.util.EnumUtils;
public enum PresenceSchema {
/** This is a locally unique identifier for the request */
ID(BaseColumns._ID,"TEXT"),
/** This is a universally unique identifier for the request */
UUID("TEXT"),
/** Device originating the request */
ORIGIN("TEXT"),
/** Who last modified the request */
OPERATOR("TEXT"),
/** The time when first observed (millisec); indicates the first time the peer was observed.*/
FIRST("INTEGER"),
/** when last observed (millisec);
* When the operator was last seen "speaking" on the channel.
* The latest field indicates the last time the peer was observed. */
LATEST("INTEGER"),
/** how many times seen since first.
* How many times the peer has been seen since FIRST.
* Each time LATEST is changed this COUNT should be incremented*/
COUNT("INTEGER"),
/** The time when no longer relevant (millisec);
* the request becomes stale and may be discarded. */
EXPIRATION("INTEGER");
/** textual field name */
final public String field;
/** type */
final public String type;
private PresenceSchema( String type) {
this.field = this.name();
this.type = type;
}
private PresenceSchema( String field, String type) {
this.field = field;
this.type = type;
}
/**
* an array of all field names
*/
public static final String[] FIELD_NAMES
= EnumUtils.buildFieldNames(PresenceSchema.class);
/**
* map an array of field names to fields.
*
* @param names an array of field names
* @return an array of fields
*/
public static ArrayList<PresenceSchema> mapFields(final String[] names) {
return EnumUtils.getFields(PresenceSchema.class, names);
}
}
|
Added state field (and toString method)
|
AmmoLib/src/edu/vu/isis/ammo/core/provider/PresenceSchema.java
|
Added state field (and toString method)
|
<ide><path>mmoLib/src/edu/vu/isis/ammo/core/provider/PresenceSchema.java
<ide> /** Who last modified the request */
<ide> OPERATOR("TEXT"),
<ide>
<add> /** Presence state: 1=available, 2=not available, etc.*/
<add> STATE("INTEGER"),
<ide>
<ide> /** The time when first observed (millisec); indicates the first time the peer was observed.*/
<ide> FIRST("INTEGER"),
<ide> return EnumUtils.getFields(PresenceSchema.class, names);
<ide> }
<ide>
<add> @Override
<add> public String toString() {
<add> return this.field;
<add> }
<ide> }
|
|
Java
|
apache-2.0
|
07c00c81315b2f9f9faee369ef43c9473809981b
| 0 |
facebook/litho,facebook/litho,facebook/litho,facebook/litho,facebook/litho,facebook/litho
|
/*
* Copyright (c) 2017-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.litho;
import static android.content.Context.ACCESSIBILITY_SERVICE;
import static android.os.Build.VERSION.SDK_INT;
import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR1;
import static android.os.Build.VERSION_CODES.M;
import static android.support.v4.view.ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO;
import static android.support.v4.view.ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO;
import static com.facebook.litho.Component.isHostSpec;
import static com.facebook.litho.Component.isLayoutSpecWithSizeSpec;
import static com.facebook.litho.Component.isMountSpec;
import static com.facebook.litho.Component.isMountViewSpec;
import static com.facebook.litho.ComponentContext.NULL_LAYOUT;
import static com.facebook.litho.ComponentLifecycle.MountType.NONE;
import static com.facebook.litho.ContextUtils.getValidActivityForContext;
import static com.facebook.litho.FrameworkLogEvents.EVENT_COLLECT_RESULTS;
import static com.facebook.litho.FrameworkLogEvents.EVENT_CREATE_LAYOUT;
import static com.facebook.litho.FrameworkLogEvents.EVENT_CSS_LAYOUT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_COMPONENT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_LOG_TAG;
import static com.facebook.litho.FrameworkLogEvents.PARAM_TREE_DIFF_ENABLED;
import static com.facebook.litho.MountItem.FLAG_DISABLE_TOUCHABLE;
import static com.facebook.litho.MountItem.FLAG_DUPLICATE_PARENT_STATE;
import static com.facebook.litho.MountItem.FLAG_IS_TRANSITION_KEY_SET;
import static com.facebook.litho.MountState.ROOT_HOST_ID;
import static com.facebook.litho.NodeInfo.ENABLED_SET_FALSE;
import static com.facebook.litho.NodeInfo.ENABLED_UNSET;
import static com.facebook.litho.NodeInfo.FOCUS_SET_TRUE;
import static com.facebook.litho.SizeSpec.EXACTLY;
import static com.facebook.litho.TransitionUtils.hasBoundsAnimation;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.annotation.VisibleForTesting;
import android.support.v4.util.LongSparseArray;
import android.support.v4.util.SimpleArrayMap;
import android.support.v4.view.accessibility.AccessibilityManagerCompat;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.accessibility.AccessibilityManager;
import com.facebook.infer.annotation.ThreadConfined;
import com.facebook.infer.annotation.ThreadSafe;
import com.facebook.litho.config.ComponentsConfiguration;
import com.facebook.litho.displaylist.DisplayList;
import com.facebook.litho.displaylist.DisplayListException;
import com.facebook.litho.reference.BorderColorDrawableReference;
import com.facebook.litho.reference.DrawableReference;
import com.facebook.litho.reference.Reference;
import com.facebook.yoga.YogaConstants;
import com.facebook.yoga.YogaDirection;
import com.facebook.yoga.YogaEdge;
import com.facebook.yoga.YogaNode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.CheckReturnValue;
/**
* The main role of {@link LayoutState} is to hold the output of layout calculation. This includes
* mountable outputs and visibility outputs. A centerpiece of the class is {@link
* #collectResults(InternalNode, LayoutState, DiffNode)} which prepares the before-mentioned outputs
* based on the provided {@link InternalNode} for later use in {@link MountState}.
*/
class LayoutState {
static final Comparator<LayoutOutput> sTopsComparator =
new Comparator<LayoutOutput>() {
@Override
public int compare(LayoutOutput lhs, LayoutOutput rhs) {
final int lhsTop = lhs.getBounds().top;
final int rhsTop = rhs.getBounds().top;
return lhsTop < rhsTop
? -1
: lhsTop > rhsTop
? 1
// Hosts should be higher for tops so that they are mounted first if possible.
: isHostSpec(lhs.getComponent()) == isHostSpec(rhs.getComponent())
? 0
: isHostSpec(lhs.getComponent()) ? -1 : 1;
}
};
static final Comparator<LayoutOutput> sBottomsComparator =
new Comparator<LayoutOutput>() {
@Override
public int compare(LayoutOutput lhs, LayoutOutput rhs) {
final int lhsBottom = lhs.getBounds().bottom;
final int rhsBottom = rhs.getBounds().bottom;
return lhsBottom < rhsBottom
? -1
: lhsBottom > rhsBottom
? 1
// Hosts should be lower for bottoms so that they are mounted first if possible.
: isHostSpec(lhs.getComponent()) == isHostSpec(rhs.getComponent())
? 0
: isHostSpec(lhs.getComponent()) ? 1 : -1;
}
};
private final Map<String, Rect> mComponentKeyToBounds = new HashMap<>();
private final List<Component> mComponents = new ArrayList<>();
@ThreadConfined(ThreadConfined.UI)
private final Rect mDisplayListCreateRect = new Rect();
@ThreadConfined(ThreadConfined.ANY)
private final Rect mDisplayListQueueRect = new Rect();
private static final int[] DRAWABLE_STATE_ENABLED = new int[]{android.R.attr.state_enabled};
private static final int[] DRAWABLE_STATE_NOT_ENABLED = new int[]{};
private volatile ComponentContext mContext;
private TransitionContext mTransitionContext;
private Component<?> mComponent;
private int mWidthSpec;
private int mHeightSpec;
private final List<LayoutOutput> mMountableOutputs = new ArrayList<>(8);
private final List<VisibilityOutput> mVisibilityOutputs = new ArrayList<>(8);
private final LongSparseArray<Integer> mOutputsIdToPositionMap = new LongSparseArray<>(8);
private final LayoutStateOutputIdCalculator mLayoutStateOutputIdCalculator;
private final ArrayList<LayoutOutput> mMountableOutputTops = new ArrayList<>();
private final ArrayList<LayoutOutput> mMountableOutputBottoms = new ArrayList<>();
private final Queue<Integer> mDisplayListsToPrefetch = new LinkedList<>();
private List<TestOutput> mTestOutputs;
private InternalNode mLayoutRoot;
private DiffNode mDiffTreeRoot;
// Reference count will be initialized to 1 in init().
private final AtomicInteger mReferenceCount = new AtomicInteger(-1);
private int mWidth;
private int mHeight;
private int mCurrentX;
private int mCurrentY;
private int mCurrentLevel = 0;
// Holds the current host marker in the layout tree.
private long mCurrentHostMarker = -1;
private int mCurrentHostOutputPosition = -1;
private boolean mShouldDuplicateParentState = true;
private boolean mIsTransitionKeySet = false;
private @NodeInfo.EnabledState int mParentEnabledState = ENABLED_UNSET;
private boolean mShouldGenerateDiffTree = false;
private int mComponentTreeId = -1;
private AccessibilityManager mAccessibilityManager;
private boolean mAccessibilityEnabled = false;
private StateHandler mStateHandler;
private boolean mCanPrefetchDisplayLists;
private boolean mCanCacheDrawingDisplayLists;
private boolean mClipChildren = true;
private ArrayList<Component> mComponentsNeedingPreviousRenderData;
private SimpleArrayMap<String, LayoutOutput> mTransitionKeyMapping;
private boolean mHasLithoViewBoundsAnimation = false;
LayoutState() {
mLayoutStateOutputIdCalculator = new LayoutStateOutputIdCalculator();
}
void init(ComponentContext context) {
mContext = context;
mStateHandler = mContext.getStateHandler();
mReferenceCount.set(1);
mTestOutputs = ComponentsConfiguration.isEndToEndTestRun ? new ArrayList<TestOutput>(8) : null;
}
/**
* Acquires a new layout output for the internal node and its associated component. It returns
* null if there's no component associated with the node as the mount pass only cares about nodes
* that will potentially mount content into the component host.
*/
@Nullable
private static LayoutOutput createGenericLayoutOutput(
InternalNode node,
LayoutState layoutState) {
final Component<?> component = node.getRootComponent();
// Skip empty nodes and layout specs because they don't mount anything.
if (component == null || component.getLifecycle().getMountType() == NONE) {
return null;
}
return createLayoutOutput(
component,
layoutState,
node,
true /* useNodePadding */,
node.getImportantForAccessibility(),
layoutState.mShouldDuplicateParentState,
layoutState.mIsTransitionKeySet);
}
private static LayoutOutput createHostLayoutOutput(LayoutState layoutState, InternalNode node) {
final LayoutOutput hostOutput =
createLayoutOutput(
HostComponent.create(),
layoutState,
node,
false /* useNodePadding */,
node.getImportantForAccessibility(),
node.isDuplicateParentStateEnabled(),
layoutState.mIsTransitionKeySet);
hostOutput.getViewNodeInfo().setTransitionKey(node.getTransitionKey());
return hostOutput;
}
private static LayoutOutput createDrawableLayoutOutput(
Component<?> component,
LayoutState layoutState,
InternalNode node) {
return createLayoutOutput(
component,
layoutState,
node,
false /* useNodePadding */,
IMPORTANT_FOR_ACCESSIBILITY_NO,
layoutState.mShouldDuplicateParentState,
layoutState.mIsTransitionKeySet);
}
private static LayoutOutput createLayoutOutput(
Component<?> component,
LayoutState layoutState,
InternalNode node,
boolean useNodePadding,
int importantForAccessibility,
boolean duplicateParentState,
boolean isTransitionKeySet) {
final boolean isMountViewSpec = isMountViewSpec(component);
final LayoutOutput layoutOutput = ComponentsPools.acquireLayoutOutput();
layoutOutput.setComponent(component);
layoutOutput.setImportantForAccessibility(importantForAccessibility);
// The mount operation will need both the marker for the target host and its matching
// parent host to ensure the correct hierarchy when nesting the host views.
layoutOutput.setHostMarker(layoutState.mCurrentHostMarker);
final int hostTranslationX;
final int hostTranslationY;
if (layoutState.mCurrentHostOutputPosition >= 0) {
final LayoutOutput hostOutput =
layoutState.mMountableOutputs.get(layoutState.mCurrentHostOutputPosition);
final Rect hostBounds = hostOutput.getBounds();
hostTranslationX = hostBounds.left;
hostTranslationY = hostBounds.top;
layoutOutput.setHostTranslationX(hostTranslationX);
layoutOutput.setHostTranslationY(hostTranslationY);
} else {
hostTranslationX = 0;
hostTranslationY = 0;
}
int flags = 0;
int l = layoutState.mCurrentX + node.getX();
int t = layoutState.mCurrentY + node.getY();
int r = l + node.getWidth();
int b = t + node.getHeight();
final int paddingLeft = useNodePadding ? node.getPaddingLeft() : 0;
final int paddingTop = useNodePadding ? node.getPaddingTop() : 0;
final int paddingRight = useNodePadding ? node.getPaddingRight() : 0;
final int paddingBottom = useNodePadding ? node.getPaddingBottom() : 0;
// View mount specs are able to set their own attributes when they're mounted.
// Non-view specs (drawable and layout) always transfer their view attributes
// to their respective hosts.
// Moreover, if the component mounts a view, then we apply padding to the view itself later on.
// Otherwise, apply the padding to the bounds of the layout output.
if (isMountViewSpec) {
layoutOutput.setNodeInfo(node.getNodeInfo());
// Acquire a ViewNodeInfo, set it up and release it after passing it to the LayoutOutput.
final ViewNodeInfo viewNodeInfo = ViewNodeInfo.acquire();
viewNodeInfo.setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom);
viewNodeInfo.setLayoutDirection(node.getResolvedLayoutDirection());
viewNodeInfo.setExpandedTouchBounds(
node,
l - hostTranslationX,
t - hostTranslationY,
r - hostTranslationX,
b - hostTranslationY);
viewNodeInfo.setClipChildren(layoutState.mClipChildren);
layoutOutput.setViewNodeInfo(viewNodeInfo);
viewNodeInfo.release();
} else {
l += paddingLeft;
t += paddingTop;
r -= paddingRight;
b -= paddingBottom;
if (node.getNodeInfo() != null && node.getNodeInfo().getEnabledState() == ENABLED_SET_FALSE) {
flags |= FLAG_DISABLE_TOUCHABLE;
}
}
layoutOutput.setBounds(l, t, r, b);
if (duplicateParentState) {
flags |= FLAG_DUPLICATE_PARENT_STATE;
}
if (isTransitionKeySet) {
flags |= FLAG_IS_TRANSITION_KEY_SET;
}
layoutOutput.setFlags(flags);
final ComponentLifecycle lifecycle = component.getLifecycle();
if (isEligibleForCreatingDisplayLists() && lifecycle.shouldUseDisplayList()) {
layoutOutput.initDisplayListContainer(
lifecycle.getClass().getSimpleName(),
layoutState.mCanCacheDrawingDisplayLists);
}
return layoutOutput;
}
/**
* Acquires a {@link VisibilityOutput} object and computes the bounds for it using the information
* stored in the {@link InternalNode}.
*/
private static VisibilityOutput createVisibilityOutput(
InternalNode node,
LayoutState layoutState) {
final int l = layoutState.mCurrentX + node.getX();
final int t = layoutState.mCurrentY + node.getY();
final int r = l + node.getWidth();
final int b = t + node.getHeight();
final EventHandler<VisibleEvent> visibleHandler = node.getVisibleHandler();
final EventHandler<FocusedVisibleEvent> focusedHandler = node.getFocusedHandler();
final EventHandler<UnfocusedVisibleEvent> unfocusedHandler = node.getUnfocusedHandler();
final EventHandler<FullImpressionVisibleEvent> fullImpressionHandler =
node.getFullImpressionHandler();
final EventHandler<InvisibleEvent> invisibleHandler = node.getInvisibleHandler();
final VisibilityOutput visibilityOutput = ComponentsPools.acquireVisibilityOutput();
visibilityOutput.setComponent(node.getRootComponent());
visibilityOutput.setBounds(l, t, r, b);
visibilityOutput.setVisibleHeightRatio(node.getVisibleHeightRatio());
visibilityOutput.setVisibleWidthRatio(node.getVisibleWidthRatio());
visibilityOutput.setVisibleEventHandler(visibleHandler);
visibilityOutput.setFocusedEventHandler(focusedHandler);
visibilityOutput.setUnfocusedEventHandler(unfocusedHandler);
visibilityOutput.setFullImpressionEventHandler(fullImpressionHandler);
visibilityOutput.setInvisibleEventHandler(invisibleHandler);
return visibilityOutput;
}
private static TestOutput createTestOutput(
InternalNode node,
LayoutState layoutState,
LayoutOutput layoutOutput) {
final int l = layoutState.mCurrentX + node.getX();
final int t = layoutState.mCurrentY + node.getY();
final int r = l + node.getWidth();
final int b = t + node.getHeight();
final TestOutput output = ComponentsPools.acquireTestOutput();
output.setTestKey(node.getTestKey());
output.setBounds(l, t, r, b);
output.setHostMarker(layoutState.mCurrentHostMarker);
if (layoutOutput != null) {
output.setLayoutOutputId(layoutOutput.getId());
}
return output;
}
private static boolean isLayoutDirectionRTL(Context context) {
ApplicationInfo applicationInfo = context.getApplicationInfo();
if ((SDK_INT >= JELLY_BEAN_MR1)
&& (applicationInfo.flags & ApplicationInfo.FLAG_SUPPORTS_RTL) != 0) {
int layoutDirection = getLayoutDirection(context);
return layoutDirection == View.LAYOUT_DIRECTION_RTL;
}
return false;
}
@TargetApi(JELLY_BEAN_MR1)
private static int getLayoutDirection(Context context) {
return context.getResources().getConfiguration().getLayoutDirection();
}
/**
* Determine if a given {@link InternalNode} within the context of a given {@link LayoutState}
* requires to be wrapped inside a view.
*
* @see #needsHostView(InternalNode, LayoutState)
*/
private static boolean hasViewContent(InternalNode node, LayoutState layoutState) {
final Component<?> component = node.getRootComponent();
final NodeInfo nodeInfo = node.getNodeInfo();
final boolean implementsAccessibility =
(nodeInfo != null && nodeInfo.hasAccessibilityHandlers())
|| (component != null && component.getLifecycle().implementsAccessibility());
final int importantForAccessibility = node.getImportantForAccessibility();
// A component has accessibility content if:
// 1. Accessibility is currently enabled.
// 2. Accessibility hasn't been explicitly disabled on it
// i.e. IMPORTANT_FOR_ACCESSIBILITY_NO.
// 3. Any of these conditions are true:
// - It implements accessibility support.
// - It has a content description.
// - It has importantForAccessibility set as either IMPORTANT_FOR_ACCESSIBILITY_YES
// or IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS.
// IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS should trigger an inner host
// so that such flag is applied in the resulting view hierarchy after the component
// tree is mounted. Click handling is also considered accessibility content but
// this is already covered separately i.e. click handler is not null.
final boolean hasAccessibilityContent = layoutState.mAccessibilityEnabled
&& importantForAccessibility != IMPORTANT_FOR_ACCESSIBILITY_NO
&& (implementsAccessibility
|| (nodeInfo != null && !TextUtils.isEmpty(nodeInfo.getContentDescription()))
|| importantForAccessibility != IMPORTANT_FOR_ACCESSIBILITY_AUTO);
final boolean hasFocusChangeHandler = (nodeInfo != null && nodeInfo.hasFocusChangeHandler());
final boolean hasEnabledTouchEventHandlers =
nodeInfo != null
&& nodeInfo.hasTouchEventHandlers()
&& nodeInfo.getEnabledState() != ENABLED_SET_FALSE;
final boolean hasViewTag = (nodeInfo != null && nodeInfo.getViewTag() != null);
final boolean hasViewTags = (nodeInfo != null && nodeInfo.getViewTags() != null);
final boolean hasShadowElevation = (nodeInfo != null && nodeInfo.getShadowElevation() != 0);
final boolean hasOutlineProvider = (nodeInfo != null && nodeInfo.getOutlineProvider() != null);
final boolean hasClipToOutline = (nodeInfo != null && nodeInfo.getClipToOutline());
final boolean isFocusableSetTrue =
(nodeInfo != null && nodeInfo.getFocusState() == FOCUS_SET_TRUE);
return hasFocusChangeHandler
|| hasEnabledTouchEventHandlers
|| hasViewTag
|| hasViewTags
|| hasShadowElevation
|| hasOutlineProvider
|| hasClipToOutline
|| hasAccessibilityContent
|| isFocusableSetTrue;
}
/**
* Collects layout outputs and release the layout tree. The layout outputs hold necessary
* information to be used by {@link MountState} to mount components into a {@link ComponentHost}.
* <p/>
* Whenever a component has view content (view tags, click handler, etc), a new host 'marker'
* is added for it. The mount pass will use the markers to decide which host should be used
* for each layout output. The root node unconditionally generates a layout output corresponding
* to the root host.
* <p/>
* The order of layout outputs follows a depth-first traversal in the tree to ensure the hosts
* will be created at the right order when mounting. The host markers will be define which host
* each mounted artifacts will be attached to.
* <p/>
* At this stage all the {@link InternalNode} for which we have LayoutOutputs that can be recycled
* will have a DiffNode associated. If the CachedMeasures are valid we'll try to recycle both the
* host and the contents (including background/foreground). In all other cases instead we'll only
* try to re-use the hosts. In some cases the host's structure might change between two updates
* even if the component is of the same type. This can happen for example when a click listener is
* added. To avoid trying to re-use the wrong host type we explicitly check that after all the
* children for a subtree have been added (this is when the actual host type is resolved). If the
* host type changed compared to the one in the DiffNode we need to refresh the ids for the whole
* subtree in order to ensure that the MountState will unmount the subtree and mount it again on
* the correct host.
* <p/>
*
* @param node InternalNode to process.
* @param layoutState the LayoutState currently operating.
* @param parentDiffNode whether this method also populates the diff tree and assigns the root
* to mDiffTreeRoot.
*/
private static void collectResults(
InternalNode node,
LayoutState layoutState,
DiffNode parentDiffNode) {
if (node.hasNewLayout()) {
node.markLayoutSeen();
}
final Component<?> component = node.getRootComponent();
// Early return if collecting results of a node holding a nested tree.
if (node.isNestedTreeHolder()) {
// If the nested tree is defined, it has been resolved during a measure call during
// layout calculation.
InternalNode nestedTree = resolveNestedTree(
node,
SizeSpec.makeSizeSpec(node.getWidth(), EXACTLY),
SizeSpec.makeSizeSpec(node.getHeight(), EXACTLY));
if (nestedTree == NULL_LAYOUT) {
return;
}
// Account for position of the holder node.
layoutState.mCurrentX += node.getX();
layoutState.mCurrentY += node.getY();
collectResults(nestedTree, layoutState, parentDiffNode);
layoutState.mCurrentX -= node.getX();
layoutState.mCurrentY -= node.getY();
return;
}
final boolean shouldGenerateDiffTree = layoutState.mShouldGenerateDiffTree;
final DiffNode currentDiffNode = node.getDiffNode();
final boolean shouldUseCachedOutputs =
isMountSpec(component) && currentDiffNode != null;
final boolean isCachedOutputUpdated = shouldUseCachedOutputs && node.areCachedMeasuresValid();
final boolean isTransitionKeySet = layoutState.mIsTransitionKeySet;
layoutState.mIsTransitionKeySet = false;
final DiffNode diffNode;
if (shouldGenerateDiffTree) {
diffNode = createDiffNode(node, parentDiffNode);
if (parentDiffNode == null) {
layoutState.mDiffTreeRoot = diffNode;
}
} else {
diffNode = null;
}
// If the parent of this node is disabled, this node has to be disabled too.
if (layoutState.mParentEnabledState == ENABLED_SET_FALSE) {
node.enabled(false);
}
final boolean needsHostView = needsHostView(node, layoutState);
final long currentHostMarker = layoutState.mCurrentHostMarker;
final int currentHostOutputPosition = layoutState.mCurrentHostOutputPosition;
int hostLayoutPosition = -1;
// 1. Insert a host LayoutOutput if we have some interactive content to be attached to.
if (needsHostView) {
layoutState.mIsTransitionKeySet = !TextUtils.isEmpty(node.getTransitionKey());
hostLayoutPosition = addHostLayoutOutput(node, layoutState, diffNode);
layoutState.mCurrentLevel++;
layoutState.mCurrentHostMarker =
layoutState.mMountableOutputs.get(hostLayoutPosition).getId();
layoutState.mCurrentHostOutputPosition = hostLayoutPosition;
}
// We need to take into account flattening when setting duplicate parent state. The parent after
// flattening may no longer exist. Therefore the value of duplicate parent state should only be
// true if the path between us (inclusive) and our inner/root host (exclusive) all are
// duplicate parent state.
final boolean shouldDuplicateParentState = layoutState.mShouldDuplicateParentState;
layoutState.mShouldDuplicateParentState =
needsHostView || (shouldDuplicateParentState && node.isDuplicateParentStateEnabled());
// Generate the layoutOutput for the given node.
final LayoutOutput layoutOutput = createGenericLayoutOutput(node, layoutState);
if (layoutOutput != null) {
final long previousId = shouldUseCachedOutputs ? currentDiffNode.getContent().getId() : -1;
layoutState.mLayoutStateOutputIdCalculator.calculateAndSetLayoutOutputIdAndUpdateState(
layoutOutput,
layoutState.mCurrentLevel,
LayoutOutput.TYPE_CONTENT,
previousId,
isCachedOutputUpdated);
}
// If we don't need to update this output we can safely re-use the display list from the
// previous output.
if (ThreadUtils.isMainThread() && isCachedOutputUpdated) {
layoutOutput.setDisplayListContainer(currentDiffNode.getContent().getDisplayListContainer());
}
// 2. Add background if defined.
final Reference<? extends Drawable> background = node.getBackground();
if (background != null) {
if (layoutOutput != null && layoutOutput.hasViewNodeInfo()) {
layoutOutput.getViewNodeInfo().setBackground(background);
} else {
final LayoutOutput convertBackground = (currentDiffNode != null)
? currentDiffNode.getBackground()
: null;
final LayoutOutput backgroundOutput = addDrawableComponent(
node,
layoutState,
convertBackground,
background,
LayoutOutput.TYPE_BACKGROUND);
if (diffNode != null) {
diffNode.setBackground(backgroundOutput);
}
}
}
// 3. Now add the MountSpec (either View or Drawable) to the Outputs.
if (isMountSpec(component)) {
// Notify component about its final size.
component.getLifecycle().onBoundsDefined(layoutState.mContext, node, component);
addMountableOutput(layoutState, layoutOutput);
addLayoutOutputIdToPositionsMap(
layoutState.mOutputsIdToPositionMap,
layoutOutput,
layoutState.mMountableOutputs.size() - 1);
if (diffNode != null) {
diffNode.setContent(layoutOutput);
}
}
// 4. Add border color if defined.
if (node.shouldDrawBorders()) {
final LayoutOutput convertBorder = (currentDiffNode != null)
? currentDiffNode.getBorder()
: null;
final LayoutOutput borderOutput = addDrawableComponent(
node,
layoutState,
convertBorder,
getBorderColorDrawable(node),
LayoutOutput.TYPE_BORDER);
if (diffNode != null) {
diffNode.setBorder(borderOutput);
}
}
// 5. Extract the Transitions.
if (ComponentsConfiguration.ARE_TRANSITIONS_SUPPORTED) {
final ArrayList<Transition> transitions = node.getTransitions();
if (transitions != null) {
for (int i = 0, size = transitions.size(); i < size; i++) {
final Transition transition = transitions.get(i);
layoutState.getOrCreateTransitionContext().addTransition(transition);
if (!layoutState.mHasLithoViewBoundsAnimation
&& layoutState.mLayoutRoot.hasTransitionKey()) {
layoutState.mHasLithoViewBoundsAnimation =
hasBoundsAnimation(layoutState.mLayoutRoot.getTransitionKey(), transition);
}
}
}
final ArrayList<Component> componentsNeedingPreviousRenderData =
node.getComponentsNeedingPreviousRenderData();
if (componentsNeedingPreviousRenderData != null) {
if (layoutState.mComponentsNeedingPreviousRenderData == null) {
layoutState.mComponentsNeedingPreviousRenderData = new ArrayList<>();
}
// We'll check for animations in mount
layoutState.mComponentsNeedingPreviousRenderData.addAll(
componentsNeedingPreviousRenderData);
}
}
layoutState.mCurrentX += node.getX();
layoutState.mCurrentY += node.getY();
final @NodeInfo.EnabledState int parentEnabledState = layoutState.mParentEnabledState;
layoutState.mParentEnabledState = (node.getNodeInfo() != null)
? node.getNodeInfo().getEnabledState()
: ENABLED_UNSET;
// We must process the nodes in order so that the layout state output order is correct.
for (int i = 0, size = node.getChildCount(); i < size; i++) {
collectResults(
node.getChildAt(i),
layoutState,
diffNode);
}
layoutState.mParentEnabledState = parentEnabledState;
layoutState.mCurrentX -= node.getX();
layoutState.mCurrentY -= node.getY();
// 6. Add foreground if defined.
final Drawable foreground = node.getForeground();
if (foreground != null) {
if (layoutOutput != null && layoutOutput.hasViewNodeInfo() && SDK_INT >= M) {
layoutOutput.getViewNodeInfo().setForeground(foreground);
} else {
final LayoutOutput convertForeground = (currentDiffNode != null)
? currentDiffNode.getForeground()
: null;
final LayoutOutput foregroundOutput = addDrawableComponent(
node,
layoutState,
convertForeground,
DrawableReference.create().drawable(foreground).build(),
LayoutOutput.TYPE_FOREGROUND);
if (diffNode != null) {
diffNode.setForeground(foregroundOutput);
}
}
}
// 7. Add VisibilityOutputs if any visibility-related event handlers are present.
if (node.hasVisibilityHandlers()) {
final VisibilityOutput visibilityOutput = createVisibilityOutput(node, layoutState);
final long previousId =
shouldUseCachedOutputs && currentDiffNode.getVisibilityOutput() != null
? currentDiffNode.getVisibilityOutput().getId()
: -1;
layoutState.mLayoutStateOutputIdCalculator.calculateAndSetVisibilityOutputId(
visibilityOutput,
layoutState.mCurrentLevel,
previousId);
layoutState.mVisibilityOutputs.add(visibilityOutput);
if (diffNode != null) {
diffNode.setVisibilityOutput(visibilityOutput);
}
}
// 8. If we're in a testing environment, maintain an additional data structure with
// information about nodes that we can query later.
if (layoutState.mTestOutputs != null && !TextUtils.isEmpty(node.getTestKey())) {
final TestOutput testOutput = createTestOutput(node, layoutState, layoutOutput);
layoutState.mTestOutputs.add(testOutput);
}
// 9. Keep a list of the components we created during this layout calculation. If the layout is
// valid, the ComponentTree will update the event handlers that have been created in the
// previous ComponentTree with the new component dispatched, otherwise Section children might
// not be accessing the correct props and state on the event handlers. The null checkers cover
// tests, the scope and tree should not be null at this point of the layout calculation.
if (component != null
&& component.getScopedContext() != null
&& component.getScopedContext().getComponentTree() != null) {
layoutState.mComponents.add(component);
}
if (component != null) {
final Rect rect = ComponentsPools.acquireRect();
if (layoutOutput != null) {
rect.set(layoutOutput.getBounds());
} else {
rect.left = layoutState.mCurrentX + node.getX();
rect.top = layoutState.mCurrentY + node.getY();
rect.right = rect.left + node.getWidth();
rect.bottom = rect.top + node.getHeight();
}
for (Component delegate : node.getComponents()) {
layoutState.mComponentKeyToBounds.put(delegate.getGlobalKey(), rect);
}
}
// All children for the given host have been added, restore the previous
// host, level, and duplicate parent state value in the recursive queue.
if (layoutState.mCurrentHostMarker != currentHostMarker) {
layoutState.mCurrentHostMarker = currentHostMarker;
layoutState.mCurrentHostOutputPosition = currentHostOutputPosition;
layoutState.mCurrentLevel--;
}
layoutState.mShouldDuplicateParentState = shouldDuplicateParentState;
layoutState.mIsTransitionKeySet = isTransitionKeySet;
}
Map<String, Rect> getComponentKeyToBounds() {
return mComponentKeyToBounds;
}
List<Component> getComponents() {
return mComponents;
}
void clearComponents() {
mComponents.clear();
}
private static void calculateAndSetHostOutputIdAndUpdateState(
InternalNode node,
LayoutOutput hostOutput,
LayoutState layoutState,
boolean isCachedOutputUpdated) {
if (layoutState.isLayoutRoot(node)) {
// The root host (LithoView) always has ID 0 and is unconditionally
// set as dirty i.e. no need to use shouldComponentUpdate().
hostOutput.setId(ROOT_HOST_ID);
// Special case where the host marker of the root host is pointing to itself.
hostOutput.setHostMarker(ROOT_HOST_ID);
hostOutput.setUpdateState(LayoutOutput.STATE_DIRTY);
} else {
layoutState.mLayoutStateOutputIdCalculator.calculateAndSetLayoutOutputIdAndUpdateState(
hostOutput,
layoutState.mCurrentLevel,
LayoutOutput.TYPE_HOST,
-1,
isCachedOutputUpdated);
}
}
private static LayoutOutput addDrawableComponent(
InternalNode node,
LayoutState layoutState,
LayoutOutput recycle,
Reference<? extends Drawable> reference,
@LayoutOutput.LayoutOutputType int type) {
final Component<DrawableComponent> drawableComponent = DrawableComponent.create(reference);
drawableComponent.setScopedContext(
ComponentContext.withComponentScope(node.getContext(), drawableComponent));
final boolean isOutputUpdated;
if (recycle != null) {
isOutputUpdated = !drawableComponent.getLifecycle().shouldComponentUpdate(
recycle.getComponent(),
drawableComponent);
} else {
isOutputUpdated = false;
}
final long previousId = recycle != null ? recycle.getId() : -1;
final LayoutOutput output = addDrawableLayoutOutput(
drawableComponent,
layoutState,
node,
type,
previousId,
isOutputUpdated);
return output;
}
private static Reference<? extends Drawable> getBorderColorDrawable(InternalNode node) {
if (!node.shouldDrawBorders()) {
throw new RuntimeException("This node does not support drawing border color");
}
final YogaNode yogaNode = node.mYogaNode;
final boolean isRtl = resolveLayoutDirection(yogaNode) == YogaDirection.RTL;
final int[] borderColors = node.getBorderColors();
final YogaEdge leftEdge = isRtl ? YogaEdge.RIGHT : YogaEdge.LEFT;
final YogaEdge rightEdge = isRtl ? YogaEdge.LEFT : YogaEdge.RIGHT;
return BorderColorDrawableReference.create(node.getContext())
.pathEffect(node.getBorderPathEffect())
.borderLeftColor(Border.getEdgeColor(borderColors, leftEdge))
.borderTopColor(Border.getEdgeColor(borderColors, YogaEdge.TOP))
.borderRightColor(Border.getEdgeColor(borderColors, rightEdge))
.borderBottomColor(Border.getEdgeColor(borderColors, YogaEdge.BOTTOM))
.borderLeftWidth(FastMath.round(yogaNode.getLayoutBorder(leftEdge)))
.borderTopWidth(FastMath.round(yogaNode.getLayoutBorder(YogaEdge.TOP)))
.borderRightWidth(FastMath.round(yogaNode.getLayoutBorder(rightEdge)))
.borderBottomWidth(FastMath.round(yogaNode.getLayoutBorder(YogaEdge.BOTTOM)))
.build();
}
/** Continually walks the node hierarchy until a node returns a non inherited layout direction */
private static YogaDirection resolveLayoutDirection(YogaNode node) {
while (node != null && node.getLayoutDirection() == YogaDirection.INHERIT) {
node = node.getParent();
}
return node == null ? YogaDirection.INHERIT : node.getLayoutDirection();
}
private static void addLayoutOutputIdToPositionsMap(
LongSparseArray outputsIdToPositionMap,
LayoutOutput layoutOutput,
int position) {
if (outputsIdToPositionMap != null) {
outputsIdToPositionMap.put(layoutOutput.getId(), position);
}
}
private static LayoutOutput addDrawableLayoutOutput(
Component<DrawableComponent> drawableComponent,
LayoutState layoutState,
InternalNode node,
@LayoutOutput.LayoutOutputType int layoutOutputType,
long previousId,
boolean isCachedOutputUpdated) {
drawableComponent.getLifecycle().onBoundsDefined(
layoutState.mContext,
node,
drawableComponent);
final LayoutOutput drawableLayoutOutput = createDrawableLayoutOutput(
drawableComponent,
layoutState,
node);
layoutState.mLayoutStateOutputIdCalculator.calculateAndSetLayoutOutputIdAndUpdateState(
drawableLayoutOutput,
layoutState.mCurrentLevel,
layoutOutputType,
previousId,
isCachedOutputUpdated);
addMountableOutput(layoutState, drawableLayoutOutput);
addLayoutOutputIdToPositionsMap(
layoutState.mOutputsIdToPositionMap,
drawableLayoutOutput,
layoutState.mMountableOutputs.size() - 1);
return drawableLayoutOutput;
}
static void releaseNodeTree(InternalNode node, boolean isNestedTree) {
if (node == NULL_LAYOUT) {
throw new IllegalArgumentException("Cannot release a null node tree");
}
for (int i = node.getChildCount() - 1; i >= 0; i--) {
final InternalNode child = node.getChildAt(i);
if (isNestedTree && node.hasNewLayout()) {
node.markLayoutSeen();
}
// A node must be detached from its parent *before* being released (otherwise the parent would
// retain a reference to a node that may get re-used by another thread)
node.removeChildAt(i);
releaseNodeTree(child, isNestedTree);
}
if (node.hasNestedTree() && node.getNestedTree() != NULL_LAYOUT) {
releaseNodeTree(node.getNestedTree(), true);
}
node.release();
}
/**
* If we have an interactive LayoutSpec or a MountSpec Drawable, we need to insert an
* HostComponent in the Outputs such as it will be used as a HostView at Mount time. View
* MountSpec are not allowed.
*
* @return The position the HostLayoutOutput was inserted.
*/
private static int addHostLayoutOutput(
InternalNode node,
LayoutState layoutState,
DiffNode diffNode) {
final Component<?> component = node.getRootComponent();
// Only the root host is allowed to wrap view mount specs as a layout output
// is unconditionally added for it.
if (isMountViewSpec(component) && !layoutState.isLayoutRoot(node)) {
throw new IllegalArgumentException("We shouldn't insert a host as a parent of a View");
}
final LayoutOutput hostLayoutOutput = createHostLayoutOutput(layoutState, node);
// The component of the hostLayoutOutput will be set later after all the
// children got processed.
addMountableOutput(layoutState, hostLayoutOutput);
final int hostOutputPosition = layoutState.mMountableOutputs.size() - 1;
if (diffNode != null) {
diffNode.setHost(hostLayoutOutput);
}
calculateAndSetHostOutputIdAndUpdateState(
node,
hostLayoutOutput,
layoutState,
false);
addLayoutOutputIdToPositionsMap(
layoutState.mOutputsIdToPositionMap,
hostLayoutOutput,
hostOutputPosition);
return hostOutputPosition;
}
static <T extends ComponentLifecycle> LayoutState calculate(
ComponentContext c,
Component<T> component,
int componentTreeId,
int widthSpec,
int heightSpec) {
return calculate(
c,
component,
componentTreeId,
widthSpec,
heightSpec,
false /* shouldGenerateDiffTree */,
null /* previousDiffTreeRoot */,
false /* canPrefetchDisplayLists */,
false /* canCacheDrawingDisplayLists */,
true /* clipChildren */);
}
static <T extends ComponentLifecycle> LayoutState calculate(
ComponentContext c,
Component<T> component,
int componentTreeId,
int widthSpec,
int heightSpec,
boolean shouldGenerateDiffTree,
DiffNode previousDiffTreeRoot,
boolean canPrefetchDisplayLists,
boolean canCacheDrawingDisplayLists,
boolean clipChildren) {
// Detect errors internal to components
component.markLayoutStarted();
LayoutState layoutState = ComponentsPools.acquireLayoutState(c);
layoutState.clearComponents();
layoutState.mShouldGenerateDiffTree = shouldGenerateDiffTree;
layoutState.mComponentTreeId = componentTreeId;
layoutState.mAccessibilityManager =
(AccessibilityManager) c.getSystemService(ACCESSIBILITY_SERVICE);
layoutState.mAccessibilityEnabled = isAccessibilityEnabled(layoutState.mAccessibilityManager);
layoutState.mComponent = component;
layoutState.mWidthSpec = widthSpec;
layoutState.mHeightSpec = heightSpec;
layoutState.mCanPrefetchDisplayLists = canPrefetchDisplayLists;
layoutState.mCanCacheDrawingDisplayLists = canCacheDrawingDisplayLists;
layoutState.mClipChildren = clipChildren;
component.applyStateUpdates(c);
final InternalNode root = createAndMeasureTreeForComponent(
component.getScopedContext(),
component,
null, // nestedTreeHolder is null because this is measuring the root component tree.
widthSpec,
heightSpec,
previousDiffTreeRoot);
switch (SizeSpec.getMode(widthSpec)) {
case SizeSpec.EXACTLY:
layoutState.mWidth = SizeSpec.getSize(widthSpec);
break;
case SizeSpec.AT_MOST:
layoutState.mWidth = Math.min(root.getWidth(), SizeSpec.getSize(widthSpec));
break;
case SizeSpec.UNSPECIFIED:
layoutState.mWidth = root.getWidth();
break;
}
switch (SizeSpec.getMode(heightSpec)) {
case SizeSpec.EXACTLY:
layoutState.mHeight = SizeSpec.getSize(heightSpec);
break;
case SizeSpec.AT_MOST:
layoutState.mHeight = Math.min(root.getHeight(), SizeSpec.getSize(heightSpec));
break;
case SizeSpec.UNSPECIFIED:
layoutState.mHeight = root.getHeight();
break;
}
layoutState.mLayoutStateOutputIdCalculator.clear();
// Reset markers before collecting layout outputs.
layoutState.mCurrentHostMarker = -1;
final ComponentsLogger logger = c.getLogger();
if (root == NULL_LAYOUT) {
return layoutState;
}
layoutState.mLayoutRoot = root;
final boolean isTracing = ComponentsSystrace.isTracing();
if (isTracing) {
ComponentsSystrace.beginSection("collectResults:" + component.getSimpleName());
}
LogEvent collectResultsEvent = null;
if (logger != null) {
collectResultsEvent = logger.newPerformanceEvent(EVENT_COLLECT_RESULTS);
collectResultsEvent.addParam(PARAM_LOG_TAG, c.getLogTag());
}
collectResults(root, layoutState, null);
Collections.sort(layoutState.mMountableOutputTops, sTopsComparator);
Collections.sort(layoutState.mMountableOutputBottoms, sBottomsComparator);
if (logger != null) {
logger.log(collectResultsEvent);
}
if (isTracing) {
ComponentsSystrace.endSection();
}
if (!ComponentsConfiguration.isDebugModeEnabled
&& !ComponentsConfiguration.persistInternalNodeTree
&& layoutState.mLayoutRoot != null) {
releaseNodeTree(layoutState.mLayoutRoot, false /* isNestedTree */);
layoutState.mLayoutRoot = null;
}
final Activity activity = getValidActivityForContext(c);
if (activity != null && isEligibleForCreatingDisplayLists()) {
if (ThreadUtils.isMainThread()
&& !layoutState.mCanPrefetchDisplayLists
&& canCollectDisplayListsSync(activity)) {
collectDisplayLists(layoutState);
} else if (layoutState.mCanPrefetchDisplayLists) {
queueDisplayListsForPrefetch(layoutState);
}
}
return layoutState;
}
@ThreadSafe(enableChecks = false)
void preAllocateMountContent() {
final boolean isTracing = ComponentsSystrace.isTracing();
if (isTracing) {
ComponentsSystrace.beginSection("preAllocateMountContent:" + mComponent.getSimpleName());
}
if (mMountableOutputs != null && !mMountableOutputs.isEmpty()) {
for (int i = 0, size = mMountableOutputs.size(); i < size; i++) {
final Component component = mMountableOutputs.get(i).getComponent();
if (Component.isMountViewSpec(component)) {
if (isTracing) {
ComponentsSystrace.beginSection("preAllocateMountContent:" + component.getSimpleName());
}
component.getLifecycle().preAllocateMountContent(mContext);
if (isTracing) {
ComponentsSystrace.endSection();
}
}
}
}
if (isTracing) {
ComponentsSystrace.endSection();
}
}
private static void collectDisplayLists(LayoutState layoutState) {
final boolean isTracing = ComponentsSystrace.isTracing();
if (isTracing) {
ComponentsSystrace.beginSection(
"collectDisplayLists:" + layoutState.mComponent.getSimpleName());
}
final Rect rect = layoutState.mDisplayListCreateRect;
for (int i = 0, count = layoutState.getMountableOutputCount(); i < count; i++) {
final LayoutOutput output = layoutState.getMountableOutputAt(i);
if (shouldCreateDisplayList(output, rect)) {
layoutState.createDisplayList(output);
}
}
if (isTracing) {
ComponentsSystrace.endSection();
}
}
private static boolean shouldCreateDisplayList(LayoutOutput output, Rect rect) {
final Component component = output.getComponent();
final ComponentLifecycle lifecycle = component.getLifecycle();
if (!lifecycle.shouldUseDisplayList()) {
return false;
}
output.getMountBounds(rect);
if (!output.hasValidDisplayList()) {
return true;
}
// This output already has a valid DisplayList from diffing. No need to re-create it.
// Just update its bounds.
final DisplayList displayList = output.getDisplayList();
try {
displayList.setBounds(rect.left, rect.top, rect.right, rect.bottom);
return false;
} catch (DisplayListException e) {
// Nothing to do here.
}
return true;
}
private static boolean canCollectDisplayListsSync(Activity activity) {
// If we have no window or the hierarchy has never been drawn before we cannot guarantee that
// a valid GL context exists. In this case just bail.
final Window window = activity.getWindow();
if (window == null) {
return false;
}
final View decorView = window.getDecorView();
if (decorView == null || decorView.getDrawingTime() == 0) {
return false;
}
return true;
}
boolean isActivityValid() {
return getValidActivityForContext(mContext) != null;
}
void createDisplayList(LayoutOutput output) {
ThreadUtils.assertMainThread();
final ComponentContext context = mContext;
if (context == null) {
// This instance has been released.
return;
}
final Component component = output.getComponent();
final boolean isTracing = ComponentsSystrace.isTracing();
if (isTracing) {
ComponentsSystrace.beginSection("createDisplayList: " + component.getSimpleName());
}
final ComponentLifecycle lifecycle = component.getLifecycle();
final DisplayList displayList = DisplayList.createDisplayList(
lifecycle.getClass().getSimpleName());
if (displayList == null) {
ComponentsSystrace.endSection();
return;
}
Drawable drawable =
(Drawable) ComponentsPools.acquireMountContent(context, lifecycle.getTypeId());
if (drawable == null) {
drawable = (Drawable) lifecycle.createMountContent(context);
}
final LayoutOutput clickableOutput = findInteractiveRoot(this, output);
boolean isStateEnabled = false;
if (clickableOutput != null && clickableOutput.getNodeInfo() != null) {
final NodeInfo nodeInfo = clickableOutput.getNodeInfo();
if (nodeInfo.hasTouchEventHandlers() || nodeInfo.getFocusState() == FOCUS_SET_TRUE) {
isStateEnabled = true;
}
}
if (isStateEnabled) {
drawable.setState(DRAWABLE_STATE_ENABLED);
} else {
drawable.setState(DRAWABLE_STATE_NOT_ENABLED);
}
lifecycle.mount(
component.getScopedContext() != null ? component.getScopedContext() : context,
drawable,
component);
lifecycle.bind(context, drawable, component);
final Rect rect = mDisplayListCreateRect;
output.getMountBounds(rect);
drawable.setBounds(0, 0, rect.width(), rect.height());
try {
final Canvas canvas = displayList.start(rect.width(), rect.height());
drawable.draw(canvas);
displayList.end(canvas);
displayList.setBounds(rect.left, rect.top, rect.right, rect.bottom);
output.setDisplayList(displayList);
} catch (DisplayListException e) {
// Display list creation failed. Make sure the DisplayList for this output is set
// to null.
output.setDisplayList(null);
}
lifecycle.unbind(context, drawable, component);
lifecycle.unmount(context, drawable, component);
ComponentsPools.release(context, lifecycle, drawable);
if (isTracing) {
ComponentsSystrace.endSection();
}
}
private static void queueDisplayListsForPrefetch(LayoutState layoutState) {
final Rect rect = layoutState.mDisplayListQueueRect;
for (int i = 0, count = layoutState.getMountableOutputCount(); i < count; i++) {
final LayoutOutput output = layoutState.getMountableOutputAt(i);
if (shouldCreateDisplayList(output, rect)) {
layoutState.mDisplayListsToPrefetch.add(i);
}
}
if (!layoutState.mDisplayListsToPrefetch.isEmpty()) {
DisplayListPrefetcher.getInstance().addLayoutState(layoutState);
}
}
public static boolean isEligibleForCreatingDisplayLists() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
}
private static LayoutOutput findInteractiveRoot(LayoutState layoutState, LayoutOutput output) {
if (output.getId() == ROOT_HOST_ID) {
return output;
}
if ((output.getFlags() & FLAG_DUPLICATE_PARENT_STATE) != 0) {
final int parentPosition = layoutState.getLayoutOutputPositionForId(output.getHostMarker());
if (parentPosition >= 0) {
final LayoutOutput parent = layoutState.mMountableOutputs.get(parentPosition);
if (parent == null) {
return null;
}
return findInteractiveRoot(layoutState, parent);
}
return null;
}
return output;
}
@VisibleForTesting
static <T extends ComponentLifecycle> InternalNode createTree(
Component<T> component,
ComponentContext context) {
final ComponentsLogger logger = context.getLogger();
LogEvent createLayoutEvent = null;
if (logger != null) {
createLayoutEvent = logger.newPerformanceEvent(EVENT_CREATE_LAYOUT);
createLayoutEvent.addParam(PARAM_LOG_TAG, context.getLogTag());
createLayoutEvent.addParam(PARAM_COMPONENT, component.getSimpleName());
}
final InternalNode root = (InternalNode) component.getLifecycle().createLayout(
context,
component,
true /* resolveNestedTree */);
if (logger != null) {
logger.log(createLayoutEvent);
}
return root;
}
@VisibleForTesting
static void measureTree(
InternalNode root,
int widthSpec,
int heightSpec,
DiffNode previousDiffTreeRoot) {
final ComponentContext context = root.getContext();
final Component component = root.getRootComponent();
final boolean isTracing = ComponentsSystrace.isTracing();
if (isTracing) {
ComponentsSystrace.beginSection("measureTree:" + component.getSimpleName());
}
if (YogaConstants.isUndefined(root.getStyleWidth())) {
root.setStyleWidthFromSpec(widthSpec);
}
if (YogaConstants.isUndefined(root.getStyleHeight())) {
root.setStyleHeightFromSpec(heightSpec);
}
if (previousDiffTreeRoot != null) {
ComponentsSystrace.beginSection("applyDiffNode");
applyDiffNodeToUnchangedNodes(root, previousDiffTreeRoot);
ComponentsSystrace.endSection(/* applyDiffNode */);
}
final ComponentsLogger logger = context.getLogger();
LogEvent layoutEvent = null;
if (logger != null) {
layoutEvent = logger.newPerformanceEvent(EVENT_CSS_LAYOUT);
layoutEvent.addParam(PARAM_LOG_TAG, context.getLogTag());
layoutEvent.addParam(PARAM_TREE_DIFF_ENABLED, String.valueOf(previousDiffTreeRoot != null));
}
root.calculateLayout(
SizeSpec.getMode(widthSpec) == SizeSpec.UNSPECIFIED
? YogaConstants.UNDEFINED
: SizeSpec.getSize(widthSpec),
SizeSpec.getMode(heightSpec) == SizeSpec.UNSPECIFIED
? YogaConstants.UNDEFINED
: SizeSpec.getSize(heightSpec));
if (logger != null) {
logger.log(layoutEvent);
}
if (isTracing) {
ComponentsSystrace.endSection(/* measureTree */ );
}
}
/**
* Create and measure the nested tree or return the cached one for the same size specs.
*/
static InternalNode resolveNestedTree(
InternalNode nestedTreeHolder,
int widthSpec,
int heightSpec) {
final ComponentContext context = nestedTreeHolder.getContext();
final Component<?> component = nestedTreeHolder.getRootComponent();
InternalNode nestedTree = nestedTreeHolder.getNestedTree();
if (nestedTree == null
|| !hasCompatibleSizeSpec(
nestedTree.getLastWidthSpec(),
nestedTree.getLastHeightSpec(),
widthSpec,
heightSpec,
nestedTree.getLastMeasuredWidth(),
nestedTree.getLastMeasuredHeight())) {
if (nestedTree != null) {
if (nestedTree != NULL_LAYOUT) {
releaseNodeTree(nestedTree, true /* isNestedTree */);
}
nestedTree = null;
}
if (component.hasCachedLayout()) {
final InternalNode cachedLayout = component.getCachedLayout();
final boolean hasCompatibleLayoutDirection =
InternalNode.hasValidLayoutDirectionInNestedTree(nestedTreeHolder, cachedLayout);
// Transfer the cached layout to the node without releasing it if it's compatible.
if (hasCompatibleLayoutDirection &&
hasCompatibleSizeSpec(
cachedLayout.getLastWidthSpec(),
cachedLayout.getLastHeightSpec(),
widthSpec,
heightSpec,
cachedLayout.getLastMeasuredWidth(),
cachedLayout.getLastMeasuredHeight())) {
nestedTree = cachedLayout;
component.clearCachedLayout();
} else {
component.releaseCachedLayout();
}
}
if (nestedTree == null) {
nestedTree = createAndMeasureTreeForComponent(
context,
component,
nestedTreeHolder,
widthSpec,
heightSpec,
nestedTreeHolder.getDiffNode()); // Previously set while traversing the holder's tree.
nestedTree.setLastWidthSpec(widthSpec);
nestedTree.setLastHeightSpec(heightSpec);
nestedTree.setLastMeasuredHeight(nestedTree.getHeight());
nestedTree.setLastMeasuredWidth(nestedTree.getWidth());
}
nestedTreeHolder.setNestedTree(nestedTree);
}
// This is checking only nested tree roots however it will be moved to check all the tree roots.
InternalNode.assertContextSpecificStyleNotSet(nestedTree);
return nestedTree;
}
/**
* Create and measure a component with the given size specs.
*/
static InternalNode createAndMeasureTreeForComponent(
ComponentContext c,
Component component,
int widthSpec,
int heightSpec) {
return createAndMeasureTreeForComponent(c, component, null, widthSpec, heightSpec, null);
}
private static InternalNode createAndMeasureTreeForComponent(
ComponentContext c,
Component component,
InternalNode nestedTreeHolder, // This will be set only if we are resolving a nested tree.
int widthSpec,
int heightSpec,
DiffNode diffTreeRoot) {
final boolean isTest = "robolectric".equals(Build.FINGERPRINT);
// Copy the context so that it can have its own set of tree props.
// Robolectric tests keep the context so that tree props can be set externally.
if (!isTest) {
c = c.makeNewCopy();
}
final boolean hasNestedTreeHolder = nestedTreeHolder != null;
if (hasNestedTreeHolder) {
c.setTreeProps(nestedTreeHolder.getPendingTreeProps());
} else if (!isTest) {
c.setTreeProps(null);
}
// Account for the size specs in ComponentContext in case the tree is a NestedTree.
final int previousWidthSpec = c.getWidthSpec();
final int previousHeightSpec = c.getHeightSpec();
c.setWidthSpec(widthSpec);
c.setHeightSpec(heightSpec);
final InternalNode root = createTree(
component,
c);
if (hasNestedTreeHolder) {
c.setTreeProps(null);
}
c.setWidthSpec(previousWidthSpec);
c.setHeightSpec(previousHeightSpec);
if (root == NULL_LAYOUT) {
return root;
}
// If measuring a ComponentTree with a LayoutSpecWithSizeSpec at the root, the nested tree
// holder argument will be null.
if (hasNestedTreeHolder && isLayoutSpecWithSizeSpec(component)) {
// Transfer information from the holder node to the nested tree root before measurement.
nestedTreeHolder.copyInto(root);
diffTreeRoot = nestedTreeHolder.getDiffNode();
} else if (root.getStyleDirection() == com.facebook.yoga.YogaDirection.INHERIT
&& LayoutState.isLayoutDirectionRTL(c)) {
root.layoutDirection(YogaDirection.RTL);
}
measureTree(
root,
widthSpec,
heightSpec,
diffTreeRoot);
return root;
}
static DiffNode createDiffNode(InternalNode node, DiffNode parent) {
ComponentsSystrace.beginSection("diff_node_creation");
DiffNode diffNode = ComponentsPools.acquireDiffNode();
diffNode.setLastWidthSpec(node.getLastWidthSpec());
diffNode.setLastHeightSpec(node.getLastHeightSpec());
diffNode.setLastMeasuredWidth(node.getLastMeasuredWidth());
diffNode.setLastMeasuredHeight(node.getLastMeasuredHeight());
diffNode.setComponent(node.getRootComponent());
if (parent != null) {
parent.addChild(diffNode);
}
ComponentsSystrace.endSection();
return diffNode;
}
boolean isCompatibleSpec(int widthSpec, int heightSpec) {
final boolean widthIsCompatible =
MeasureComparisonUtils.isMeasureSpecCompatible(
mWidthSpec,
widthSpec,
mWidth);
final boolean heightIsCompatible =
MeasureComparisonUtils.isMeasureSpecCompatible(
mHeightSpec,
heightSpec,
mHeight);
return widthIsCompatible && heightIsCompatible;
}
boolean isCompatibleAccessibility() {
return isAccessibilityEnabled(mAccessibilityManager) == mAccessibilityEnabled;
}
private static boolean isAccessibilityEnabled(AccessibilityManager accessibilityManager) {
return accessibilityManager.isEnabled() &&
AccessibilityManagerCompat.isTouchExplorationEnabled(accessibilityManager);
}
/**
* Traverses the layoutTree and the diffTree recursively. If a layoutNode has a compatible host
* type {@link LayoutState#hostIsCompatible} it assigns the DiffNode to the layout node in order
* to try to re-use the LayoutOutputs that will be generated by {@link
* LayoutState#collectResults(InternalNode, LayoutState, DiffNode)}. If a layoutNode
* component returns false when shouldComponentUpdate is called with the DiffNode Component it
* also tries to re-use the old measurements and therefore marks as valid the cachedMeasures for
* the whole component subtree.
*
* @param layoutNode the root of the LayoutTree
* @param diffNode the root of the diffTree
*
* @return true if the layout node requires updating, false if it can re-use the measurements
* from the diff node.
*/
static boolean applyDiffNodeToUnchangedNodes(InternalNode layoutNode, DiffNode diffNode) {
// Root of the main tree or of a nested tree.
final boolean isTreeRoot = layoutNode.getParent() == null;
if (isLayoutSpecWithSizeSpec(layoutNode.getRootComponent()) && !isTreeRoot) {
layoutNode.setDiffNode(diffNode);
return true;
}
if (!hostIsCompatible(layoutNode, diffNode)) {
return true;
}
layoutNode.setDiffNode(diffNode);
final int layoutCount = layoutNode.getChildCount();
final int diffCount = diffNode.getChildCount();
// Layout node needs to be updated if:
// - it has a different number of children.
// - one of its children needs updating.
// - the node itself declares that it needs updating.
boolean shouldUpdate = layoutCount != diffCount;
for (int i = 0; i < layoutCount && i < diffCount; i++) {
// ensure that we always run for all children.
boolean shouldUpdateChild =
applyDiffNodeToUnchangedNodes(
layoutNode.getChildAt(i),
diffNode.getChildAt(i));
shouldUpdate |= shouldUpdateChild;
}
shouldUpdate |= shouldComponentUpdate(layoutNode, diffNode);
if (!shouldUpdate) {
applyDiffNodeToLayoutNode(layoutNode, diffNode);
}
return shouldUpdate;
}
/**
* Copies the inter stage state (if any) from the DiffNode's component to the layout node's
* component, and declares that the cached measures on the diff node are valid for the layout
* node.
*/
private static void applyDiffNodeToLayoutNode(InternalNode layoutNode, DiffNode diffNode) {
final Component component = layoutNode.getRootComponent();
if (component != null) {
component.copyInterStageImpl(diffNode.getComponent());
}
layoutNode.setCachedMeasuresValid(true);
}
/**
* Returns true either if the two nodes have the same Component type or if both don't have a
* Component.
*/
private static boolean hostIsCompatible(InternalNode node, DiffNode diffNode) {
if (diffNode == null) {
return false;
}
return isSameComponentType(node.getRootComponent(), diffNode.getComponent());
}
private static boolean isSameComponentType(Component a, Component b) {
if (a == b) {
return true;
} else if (a == null || b == null) {
return false;
}
return a.getLifecycle().getClass().equals(b.getLifecycle().getClass());
}
private static boolean shouldComponentUpdate(InternalNode layoutNode, DiffNode diffNode) {
if (diffNode == null) {
return true;
}
final Component component = layoutNode.getRootComponent();
if (component != null) {
return component.getLifecycle().shouldComponentUpdate(component, diffNode.getComponent());
}
return true;
}
boolean isCompatibleComponentAndSpec(
int componentId,
int widthSpec,
int heightSpec) {
return mComponent.getId() == componentId && isCompatibleSpec(widthSpec, heightSpec);
}
boolean isCompatibleSize(int width, int height) {
return mWidth == width && mHeight == height;
}
boolean isComponentId(int componentId) {
return mComponent.getId() == componentId;
}
int getMountableOutputCount() {
return mMountableOutputs.size();
}
LayoutOutput getMountableOutputAt(int index) {
return mMountableOutputs.get(index);
}
ArrayList<LayoutOutput> getMountableOutputTops() {
return mMountableOutputTops;
}
ArrayList<LayoutOutput> getMountableOutputBottoms() {
return mMountableOutputBottoms;
}
int getVisibilityOutputCount() {
return mVisibilityOutputs.size();
}
VisibilityOutput getVisibilityOutputAt(int index) {
return mVisibilityOutputs.get(index);
}
int getTestOutputCount() {
return mTestOutputs == null ? 0 : mTestOutputs.size();
}
TestOutput getTestOutputAt(int index) {
return mTestOutputs == null ? null : mTestOutputs.get(index);
}
public DiffNode getDiffTree() {
return mDiffTreeRoot;
}
int getWidth() {
return mWidth;
}
int getHeight() {
return mHeight;
}
/**
* @return The id of the {@link ComponentTree} that generated this {@link LayoutState}
*/
int getComponentTreeId() {
return mComponentTreeId;
}
/**
* See {@link LayoutState#acquireRef} Call this when you are done using the reference to the
* LayoutState.
*/
@ThreadSafe(enableChecks = false)
void releaseRef() {
int count = mReferenceCount.decrementAndGet();
if (count < 0) {
throw new IllegalStateException("Trying to releaseRef a recycled LayoutState");
}
if (count == 0) {
mContext = null;
mComponent = null;
mWidth = 0;
mHeight = 0;
mCurrentX = 0;
mCurrentY = 0;
mCurrentHostMarker = -1;
mCurrentHostOutputPosition = -1;
mComponentTreeId = -1;
mShouldDuplicateParentState = true;
mIsTransitionKeySet = false;
mClipChildren = true;
for (int i = 0, size = mMountableOutputs.size(); i < size; i++) {
mMountableOutputs.get(i).release();
}
mMountableOutputs.clear();
mMountableOutputTops.clear();
mMountableOutputBottoms.clear();
mOutputsIdToPositionMap.clear();
mDisplayListsToPrefetch.clear();
for (Rect rect : mComponentKeyToBounds.values()) {
// Delegate components are using the same Rect instance as the components they create since
// we don't calculate a layout output for them. We need to make sure we only release it
// once.
if (!rect.isEmpty()) {
ComponentsPools.release(rect);
}
}
mComponentKeyToBounds.clear();
for (int i = 0, size = mVisibilityOutputs.size(); i < size; i++) {
ComponentsPools.release(mVisibilityOutputs.get(i));
}
mVisibilityOutputs.clear();
if (mTestOutputs != null) {
for (int i = 0, size = mTestOutputs.size(); i < size; i++) {
ComponentsPools.release(mTestOutputs.get(i));
}
mTestOutputs.clear();
}
mShouldGenerateDiffTree = false;
mAccessibilityManager = null;
mAccessibilityEnabled = false;
if (mDiffTreeRoot != null) {
ComponentsPools.release(mDiffTreeRoot);
mDiffTreeRoot = null;
}
mLayoutStateOutputIdCalculator.clear();
if (mTransitionContext != null) {
ComponentsPools.release(mTransitionContext);
mTransitionContext = null;
}
// This should only ever be true in non-release builds as we need this for Stetho integration
// (or for as long as the ComponentsConfiguration.persistInternalNodeTree experiment runs).
// Otherwise, in release builds the node tree is released in calculateLayout().
if (mLayoutRoot != null) {
releaseNodeTree(mLayoutRoot, false /* isNestedTree */);
mLayoutRoot = null;
}
if (mComponentsNeedingPreviousRenderData != null) {
mComponentsNeedingPreviousRenderData.clear();
}
mTransitionKeyMapping = null;
mHasLithoViewBoundsAnimation = false;
ComponentsPools.release(this);
}
}
/**
* The lifecycle of LayoutState is generally controlled by ComponentTree. Since sometimes we need
* an old LayoutState to be passed to a new LayoutState to implement Tree diffing, We use
* reference counting to avoid releasing a LayoutState that is not used by ComponentTree anymore
* but could be used by another LayoutState. The rule is that whenever you need to pass the
* LayoutState outside of ComponentTree, you acquire a reference and then you release it as soon
* as you are done with it
*
* @return The same LayoutState instance with an higher reference count.
*/
@CheckReturnValue
LayoutState acquireRef() {
if (mReferenceCount.getAndIncrement() == 0) {
throw new IllegalStateException("Trying to use a released LayoutState");
}
return this;
}
/**
* Returns the state handler instance currently held by LayoutState and nulls it afterwards.
*
* @return the state handler
*/
@CheckReturnValue
StateHandler consumeStateHandler() {
final StateHandler stateHandler = mStateHandler;
mStateHandler = null;
return stateHandler;
}
InternalNode getLayoutRoot() {
return mLayoutRoot;
}
// If the layout root is a nested tree holder node, it gets skipped immediately while
// collecting the LayoutOutputs. The nested tree itself effectively becomes the layout
// root in this case.
private boolean isLayoutRoot(InternalNode node) {
return mLayoutRoot.isNestedTreeHolder()
? node == mLayoutRoot.getNestedTree()
: node == mLayoutRoot;
}
/**
* Check if a cached nested tree has compatible SizeSpec to be reused as is or
* if it needs to be recomputed.
*
* The conditions to be able to re-use previous measurements are:
* 1) The measureSpec is the same
* 2) The new measureSpec is EXACTLY and the last measured size matches the measureSpec size.
* 3) The old measureSpec is UNSPECIFIED, the new one is AT_MOST and the old measured size is
* smaller that the maximum size the new measureSpec will allow.
* 4) Both measure specs are AT_MOST. The old measure spec allows a bigger size than the new and
* the old measured size is smaller than the allowed max size for the new sizeSpec.
*/
public static boolean hasCompatibleSizeSpec(
int oldWidthSpec,
int oldHeightSpec,
int newWidthSpec,
int newHeightSpec,
float oldMeasuredWidth,
float oldMeasuredHeight) {
final boolean widthIsCompatible =
MeasureComparisonUtils.isMeasureSpecCompatible(
oldWidthSpec,
newWidthSpec,
(int) oldMeasuredWidth);
final boolean heightIsCompatible =
MeasureComparisonUtils.isMeasureSpecCompatible(
oldHeightSpec,
newHeightSpec,
(int) oldMeasuredHeight);
return widthIsCompatible && heightIsCompatible;
}
/**
* Returns true if this is the root node (which always generates a matching layout
* output), if the node has view attributes e.g. tags, content description, etc, or if
* the node has explicitly been forced to be wrapped in a view.
*/
private static boolean needsHostView(InternalNode node, LayoutState layoutState) {
return layoutState.isLayoutRoot(node)
|| (!isMountViewSpec(node.getRootComponent())
&& (hasViewContent(node, layoutState) || node.isForceViewWrapping()));
}
/**
* @return the position of the {@link LayoutOutput} with id layoutOutputId in the
* {@link LayoutState} list of outputs or -1 if no {@link LayoutOutput} with that id exists in
* the {@link LayoutState}
*/
int getLayoutOutputPositionForId(long layoutOutputId) {
return mOutputsIdToPositionMap.get(layoutOutputId, -1);
}
TransitionContext getTransitionContext() {
return mTransitionContext;
}
boolean hasTransitionContext() {
return (mTransitionContext != null);
}
/**
* Gets (or creates) a mapping from transition key to LayoutOutput.
*/
SimpleArrayMap<String, LayoutOutput> getTransitionKeyMapping() {
if (mTransitionKeyMapping != null) {
return mTransitionKeyMapping;
}
mTransitionKeyMapping = new SimpleArrayMap<>();
for (int i = 0, size = getMountableOutputCount(); i < size; i++) {
final LayoutOutput newOutput = getMountableOutputAt(i);
final String transitionKey = newOutput.getTransitionKey();
if (transitionKey == null) {
continue;
}
if (mTransitionKeyMapping.put(transitionKey, newOutput) != null) {
throw new RuntimeException(
"The transitionKey '"
+ transitionKey
+ "' was defined multiple times in the same layout. transitionKeys must be unique "
+ "identifiers per layout. If this is a reusable component that can appear in the "
+ "same layout multiple times, consider passing unique transitionKeys from above.");
}
}
return mTransitionKeyMapping;
}
LayoutOutput getLayoutOutputForTransitionKey(String transitionKey) {
return getTransitionKeyMapping().get(transitionKey);
}
private static void addMountableOutput(LayoutState layoutState, LayoutOutput layoutOutput) {
layoutState.mMountableOutputs.add(layoutOutput);
layoutState.mMountableOutputTops.add(layoutOutput);
layoutState.mMountableOutputBottoms.add(layoutOutput);
}
private TransitionContext getOrCreateTransitionContext() {
if (mTransitionContext == null) {
mTransitionContext = ComponentsPools.acquireTransitionContext();
}
return mTransitionContext;
}
/**
* @return whether the main thread layout state defines a transition that animates the bounds of
* the root component (and thus the LithoView).
*/
boolean hasLithoViewBoundsAnimation() {
return mHasLithoViewBoundsAnimation;
}
/** @return whether there are any items in the queue for Display Lists prefetching. */
boolean hasItemsForDLPrefetch() {
return !mDisplayListsToPrefetch.isEmpty();
}
/**
* Remove items that have already valid displaylist. This item might have been already drawn on
* the screen in which case we will have valid displaylist so we can skip them.
*/
void trimDisplayListItemsQueue() {
if (mMountableOutputs.isEmpty()) {
// Item has been released, remove all pending items for displaylist prefetch.
mDisplayListsToPrefetch.clear();
return;
}
Integer currentIndex = mDisplayListsToPrefetch.peek();
while (currentIndex != null) {
final LayoutOutput layoutOutput = mMountableOutputs.get(currentIndex);
if (!layoutOutput.hasDisplayListContainer() || layoutOutput.hasValidDisplayList()) {
// Either this item has been released or we have already computed displaylist for this item.
// In either case remove it from the queue.
mDisplayListsToPrefetch.remove();
currentIndex = mDisplayListsToPrefetch.peek();
} else {
break;
}
}
}
/**
* Removes and returns next {@link LayoutOutput} from the queue for Display Lists.
* Note that it is callers responsibility to make sure queue is not empty.
*/
LayoutOutput getNextLayoutOutputForDLPrefetch() {
final int layoutOutputIndex = mDisplayListsToPrefetch.poll();
return getMountableOutputAt(layoutOutputIndex);
}
/**
* @return the list of Components in this LayoutState that care about the previously mounted
* versions of their @Prop/@State params.
*/
@Nullable
List<Component> getComponentsNeedingPreviousRenderData() {
return mComponentsNeedingPreviousRenderData;
}
}
|
litho-core/src/main/java/com/facebook/litho/LayoutState.java
|
/*
* Copyright (c) 2017-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.litho;
import static android.content.Context.ACCESSIBILITY_SERVICE;
import static android.os.Build.VERSION.SDK_INT;
import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR1;
import static android.os.Build.VERSION_CODES.M;
import static android.support.v4.view.ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO;
import static android.support.v4.view.ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO;
import static com.facebook.litho.Component.isHostSpec;
import static com.facebook.litho.Component.isLayoutSpecWithSizeSpec;
import static com.facebook.litho.Component.isMountSpec;
import static com.facebook.litho.Component.isMountViewSpec;
import static com.facebook.litho.ComponentContext.NULL_LAYOUT;
import static com.facebook.litho.ComponentLifecycle.MountType.NONE;
import static com.facebook.litho.ContextUtils.getValidActivityForContext;
import static com.facebook.litho.FrameworkLogEvents.EVENT_COLLECT_RESULTS;
import static com.facebook.litho.FrameworkLogEvents.EVENT_CREATE_LAYOUT;
import static com.facebook.litho.FrameworkLogEvents.EVENT_CSS_LAYOUT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_COMPONENT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_LOG_TAG;
import static com.facebook.litho.FrameworkLogEvents.PARAM_TREE_DIFF_ENABLED;
import static com.facebook.litho.MountItem.FLAG_DISABLE_TOUCHABLE;
import static com.facebook.litho.MountItem.FLAG_DUPLICATE_PARENT_STATE;
import static com.facebook.litho.MountItem.FLAG_IS_TRANSITION_KEY_SET;
import static com.facebook.litho.MountState.ROOT_HOST_ID;
import static com.facebook.litho.NodeInfo.ENABLED_SET_FALSE;
import static com.facebook.litho.NodeInfo.ENABLED_UNSET;
import static com.facebook.litho.NodeInfo.FOCUS_SET_TRUE;
import static com.facebook.litho.SizeSpec.EXACTLY;
import static com.facebook.litho.TransitionUtils.hasBoundsAnimation;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.annotation.VisibleForTesting;
import android.support.v4.util.LongSparseArray;
import android.support.v4.util.SimpleArrayMap;
import android.support.v4.view.accessibility.AccessibilityManagerCompat;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.accessibility.AccessibilityManager;
import com.facebook.infer.annotation.ThreadConfined;
import com.facebook.infer.annotation.ThreadSafe;
import com.facebook.litho.config.ComponentsConfiguration;
import com.facebook.litho.displaylist.DisplayList;
import com.facebook.litho.displaylist.DisplayListException;
import com.facebook.litho.reference.BorderColorDrawableReference;
import com.facebook.litho.reference.DrawableReference;
import com.facebook.litho.reference.Reference;
import com.facebook.yoga.YogaConstants;
import com.facebook.yoga.YogaDirection;
import com.facebook.yoga.YogaEdge;
import com.facebook.yoga.YogaNode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.CheckReturnValue;
/**
* The main role of {@link LayoutState} is to hold the output of layout calculation. This includes
* mountable outputs and visibility outputs. A centerpiece of the class is {@link
* #collectResults(InternalNode, LayoutState, DiffNode)} which prepares the before-mentioned outputs
* based on the provided {@link InternalNode} for later use in {@link MountState}.
*/
class LayoutState {
static final Comparator<LayoutOutput> sTopsComparator =
new Comparator<LayoutOutput>() {
@Override
public int compare(LayoutOutput lhs, LayoutOutput rhs) {
final int lhsTop = lhs.getBounds().top;
final int rhsTop = rhs.getBounds().top;
return lhsTop < rhsTop
? -1
: lhsTop > rhsTop
? 1
// Hosts should be higher for tops so that they are mounted first if possible.
: isHostSpec(lhs.getComponent()) == isHostSpec(rhs.getComponent())
? 0
: isHostSpec(lhs.getComponent()) ? -1 : 1;
}
};
static final Comparator<LayoutOutput> sBottomsComparator =
new Comparator<LayoutOutput>() {
@Override
public int compare(LayoutOutput lhs, LayoutOutput rhs) {
final int lhsBottom = lhs.getBounds().bottom;
final int rhsBottom = rhs.getBounds().bottom;
return lhsBottom < rhsBottom
? -1
: lhsBottom > rhsBottom
? 1
// Hosts should be lower for bottoms so that they are mounted first if possible.
: isHostSpec(lhs.getComponent()) == isHostSpec(rhs.getComponent())
? 0
: isHostSpec(lhs.getComponent()) ? 1 : -1;
}
};
private final Map<String, Rect> mComponentKeyToBounds = new HashMap<>();
private final List<Component> mComponents = new ArrayList<>();
@ThreadConfined(ThreadConfined.UI)
private final Rect mDisplayListCreateRect = new Rect();
@ThreadConfined(ThreadConfined.ANY)
private final Rect mDisplayListQueueRect = new Rect();
private static final int[] DRAWABLE_STATE_ENABLED = new int[]{android.R.attr.state_enabled};
private static final int[] DRAWABLE_STATE_NOT_ENABLED = new int[]{};
private volatile ComponentContext mContext;
private TransitionContext mTransitionContext;
private Component<?> mComponent;
private int mWidthSpec;
private int mHeightSpec;
private final List<LayoutOutput> mMountableOutputs = new ArrayList<>(8);
private final List<VisibilityOutput> mVisibilityOutputs = new ArrayList<>(8);
private final LongSparseArray<Integer> mOutputsIdToPositionMap = new LongSparseArray<>(8);
private final LayoutStateOutputIdCalculator mLayoutStateOutputIdCalculator;
private final ArrayList<LayoutOutput> mMountableOutputTops = new ArrayList<>();
private final ArrayList<LayoutOutput> mMountableOutputBottoms = new ArrayList<>();
private final Queue<Integer> mDisplayListsToPrefetch = new LinkedList<>();
private List<TestOutput> mTestOutputs;
private InternalNode mLayoutRoot;
private DiffNode mDiffTreeRoot;
// Reference count will be initialized to 1 in init().
private final AtomicInteger mReferenceCount = new AtomicInteger(-1);
private int mWidth;
private int mHeight;
private int mCurrentX;
private int mCurrentY;
private int mCurrentLevel = 0;
// Holds the current host marker in the layout tree.
private long mCurrentHostMarker = -1;
private int mCurrentHostOutputPosition = -1;
private boolean mShouldDuplicateParentState = true;
private boolean mIsTransitionKeySet = false;
private @NodeInfo.EnabledState int mParentEnabledState = ENABLED_UNSET;
private boolean mShouldGenerateDiffTree = false;
private int mComponentTreeId = -1;
private AccessibilityManager mAccessibilityManager;
private boolean mAccessibilityEnabled = false;
private StateHandler mStateHandler;
private boolean mCanPrefetchDisplayLists;
private boolean mCanCacheDrawingDisplayLists;
private boolean mClipChildren = true;
private ArrayList<Component> mComponentsNeedingPreviousRenderData;
private SimpleArrayMap<String, LayoutOutput> mTransitionKeyMapping;
private boolean mHasLithoViewBoundsAnimation = false;
LayoutState() {
mLayoutStateOutputIdCalculator = new LayoutStateOutputIdCalculator();
}
void init(ComponentContext context) {
mContext = context;
mStateHandler = mContext.getStateHandler();
mReferenceCount.set(1);
mTestOutputs = ComponentsConfiguration.isEndToEndTestRun ? new ArrayList<TestOutput>(8) : null;
}
/**
* Acquires a new layout output for the internal node and its associated component. It returns
* null if there's no component associated with the node as the mount pass only cares about nodes
* that will potentially mount content into the component host.
*/
@Nullable
private static LayoutOutput createGenericLayoutOutput(
InternalNode node,
LayoutState layoutState) {
final Component<?> component = node.getRootComponent();
// Skip empty nodes and layout specs because they don't mount anything.
if (component == null || component.getLifecycle().getMountType() == NONE) {
return null;
}
return createLayoutOutput(
component,
layoutState,
node,
true /* useNodePadding */,
node.getImportantForAccessibility(),
layoutState.mShouldDuplicateParentState,
layoutState.mIsTransitionKeySet);
}
private static LayoutOutput createHostLayoutOutput(LayoutState layoutState, InternalNode node) {
final LayoutOutput hostOutput =
createLayoutOutput(
HostComponent.create(),
layoutState,
node,
false /* useNodePadding */,
node.getImportantForAccessibility(),
node.isDuplicateParentStateEnabled(),
layoutState.mIsTransitionKeySet);
hostOutput.getViewNodeInfo().setTransitionKey(node.getTransitionKey());
return hostOutput;
}
private static LayoutOutput createDrawableLayoutOutput(
Component<?> component,
LayoutState layoutState,
InternalNode node) {
return createLayoutOutput(
component,
layoutState,
node,
false /* useNodePadding */,
IMPORTANT_FOR_ACCESSIBILITY_NO,
layoutState.mShouldDuplicateParentState,
layoutState.mIsTransitionKeySet);
}
private static LayoutOutput createLayoutOutput(
Component<?> component,
LayoutState layoutState,
InternalNode node,
boolean useNodePadding,
int importantForAccessibility,
boolean duplicateParentState,
boolean isTransitionKeySet) {
final boolean isMountViewSpec = isMountViewSpec(component);
final LayoutOutput layoutOutput = ComponentsPools.acquireLayoutOutput();
layoutOutput.setComponent(component);
layoutOutput.setImportantForAccessibility(importantForAccessibility);
// The mount operation will need both the marker for the target host and its matching
// parent host to ensure the correct hierarchy when nesting the host views.
layoutOutput.setHostMarker(layoutState.mCurrentHostMarker);
final int hostTranslationX;
final int hostTranslationY;
if (layoutState.mCurrentHostOutputPosition >= 0) {
final LayoutOutput hostOutput =
layoutState.mMountableOutputs.get(layoutState.mCurrentHostOutputPosition);
final Rect hostBounds = hostOutput.getBounds();
hostTranslationX = hostBounds.left;
hostTranslationY = hostBounds.top;
layoutOutput.setHostTranslationX(hostTranslationX);
layoutOutput.setHostTranslationY(hostTranslationY);
} else {
hostTranslationX = 0;
hostTranslationY = 0;
}
int flags = 0;
int l = layoutState.mCurrentX + node.getX();
int t = layoutState.mCurrentY + node.getY();
int r = l + node.getWidth();
int b = t + node.getHeight();
final int paddingLeft = useNodePadding ? node.getPaddingLeft() : 0;
final int paddingTop = useNodePadding ? node.getPaddingTop() : 0;
final int paddingRight = useNodePadding ? node.getPaddingRight() : 0;
final int paddingBottom = useNodePadding ? node.getPaddingBottom() : 0;
// View mount specs are able to set their own attributes when they're mounted.
// Non-view specs (drawable and layout) always transfer their view attributes
// to their respective hosts.
// Moreover, if the component mounts a view, then we apply padding to the view itself later on.
// Otherwise, apply the padding to the bounds of the layout output.
if (isMountViewSpec) {
layoutOutput.setNodeInfo(node.getNodeInfo());
// Acquire a ViewNodeInfo, set it up and release it after passing it to the LayoutOutput.
final ViewNodeInfo viewNodeInfo = ViewNodeInfo.acquire();
viewNodeInfo.setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom);
viewNodeInfo.setLayoutDirection(node.getResolvedLayoutDirection());
viewNodeInfo.setExpandedTouchBounds(
node,
l - hostTranslationX,
t - hostTranslationY,
r - hostTranslationX,
b - hostTranslationY);
viewNodeInfo.setClipChildren(layoutState.mClipChildren);
layoutOutput.setViewNodeInfo(viewNodeInfo);
viewNodeInfo.release();
} else {
l += paddingLeft;
t += paddingTop;
r -= paddingRight;
b -= paddingBottom;
if (node.getNodeInfo() != null && node.getNodeInfo().getEnabledState() == ENABLED_SET_FALSE) {
flags |= FLAG_DISABLE_TOUCHABLE;
}
}
layoutOutput.setBounds(l, t, r, b);
if (duplicateParentState) {
flags |= FLAG_DUPLICATE_PARENT_STATE;
}
if (isTransitionKeySet) {
flags |= FLAG_IS_TRANSITION_KEY_SET;
}
layoutOutput.setFlags(flags);
final ComponentLifecycle lifecycle = component.getLifecycle();
if (isEligibleForCreatingDisplayLists() && lifecycle.shouldUseDisplayList()) {
layoutOutput.initDisplayListContainer(
lifecycle.getClass().getSimpleName(),
layoutState.mCanCacheDrawingDisplayLists);
}
return layoutOutput;
}
/**
* Acquires a {@link VisibilityOutput} object and computes the bounds for it using the information
* stored in the {@link InternalNode}.
*/
private static VisibilityOutput createVisibilityOutput(
InternalNode node,
LayoutState layoutState) {
final int l = layoutState.mCurrentX + node.getX();
final int t = layoutState.mCurrentY + node.getY();
final int r = l + node.getWidth();
final int b = t + node.getHeight();
final EventHandler<VisibleEvent> visibleHandler = node.getVisibleHandler();
final EventHandler<FocusedVisibleEvent> focusedHandler = node.getFocusedHandler();
final EventHandler<UnfocusedVisibleEvent> unfocusedHandler = node.getUnfocusedHandler();
final EventHandler<FullImpressionVisibleEvent> fullImpressionHandler =
node.getFullImpressionHandler();
final EventHandler<InvisibleEvent> invisibleHandler = node.getInvisibleHandler();
final VisibilityOutput visibilityOutput = ComponentsPools.acquireVisibilityOutput();
visibilityOutput.setComponent(node.getRootComponent());
visibilityOutput.setBounds(l, t, r, b);
visibilityOutput.setVisibleHeightRatio(node.getVisibleHeightRatio());
visibilityOutput.setVisibleWidthRatio(node.getVisibleWidthRatio());
visibilityOutput.setVisibleEventHandler(visibleHandler);
visibilityOutput.setFocusedEventHandler(focusedHandler);
visibilityOutput.setUnfocusedEventHandler(unfocusedHandler);
visibilityOutput.setFullImpressionEventHandler(fullImpressionHandler);
visibilityOutput.setInvisibleEventHandler(invisibleHandler);
return visibilityOutput;
}
private static TestOutput createTestOutput(
InternalNode node,
LayoutState layoutState,
LayoutOutput layoutOutput) {
final int l = layoutState.mCurrentX + node.getX();
final int t = layoutState.mCurrentY + node.getY();
final int r = l + node.getWidth();
final int b = t + node.getHeight();
final TestOutput output = ComponentsPools.acquireTestOutput();
output.setTestKey(node.getTestKey());
output.setBounds(l, t, r, b);
output.setHostMarker(layoutState.mCurrentHostMarker);
if (layoutOutput != null) {
output.setLayoutOutputId(layoutOutput.getId());
}
return output;
}
private static boolean isLayoutDirectionRTL(Context context) {
ApplicationInfo applicationInfo = context.getApplicationInfo();
if ((SDK_INT >= JELLY_BEAN_MR1)
&& (applicationInfo.flags & ApplicationInfo.FLAG_SUPPORTS_RTL) != 0) {
int layoutDirection = getLayoutDirection(context);
return layoutDirection == View.LAYOUT_DIRECTION_RTL;
}
return false;
}
@TargetApi(JELLY_BEAN_MR1)
private static int getLayoutDirection(Context context) {
return context.getResources().getConfiguration().getLayoutDirection();
}
/**
* Determine if a given {@link InternalNode} within the context of a given {@link LayoutState}
* requires to be wrapped inside a view.
*
* @see #needsHostView(InternalNode, LayoutState)
*/
private static boolean hasViewContent(InternalNode node, LayoutState layoutState) {
final Component<?> component = node.getRootComponent();
final NodeInfo nodeInfo = node.getNodeInfo();
final boolean implementsAccessibility =
(nodeInfo != null && nodeInfo.hasAccessibilityHandlers())
|| (component != null && component.getLifecycle().implementsAccessibility());
final int importantForAccessibility = node.getImportantForAccessibility();
// A component has accessibility content if:
// 1. Accessibility is currently enabled.
// 2. Accessibility hasn't been explicitly disabled on it
// i.e. IMPORTANT_FOR_ACCESSIBILITY_NO.
// 3. Any of these conditions are true:
// - It implements accessibility support.
// - It has a content description.
// - It has importantForAccessibility set as either IMPORTANT_FOR_ACCESSIBILITY_YES
// or IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS.
// IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS should trigger an inner host
// so that such flag is applied in the resulting view hierarchy after the component
// tree is mounted. Click handling is also considered accessibility content but
// this is already covered separately i.e. click handler is not null.
final boolean hasAccessibilityContent = layoutState.mAccessibilityEnabled
&& importantForAccessibility != IMPORTANT_FOR_ACCESSIBILITY_NO
&& (implementsAccessibility
|| (nodeInfo != null && !TextUtils.isEmpty(nodeInfo.getContentDescription()))
|| importantForAccessibility != IMPORTANT_FOR_ACCESSIBILITY_AUTO);
final boolean hasFocusChangeHandler = (nodeInfo != null && nodeInfo.hasFocusChangeHandler());
final boolean hasEnabledTouchEventHandlers =
nodeInfo != null
&& nodeInfo.hasTouchEventHandlers()
&& nodeInfo.getEnabledState() != ENABLED_SET_FALSE;
final boolean hasViewTag = (nodeInfo != null && nodeInfo.getViewTag() != null);
final boolean hasViewTags = (nodeInfo != null && nodeInfo.getViewTags() != null);
final boolean hasShadowElevation = (nodeInfo != null && nodeInfo.getShadowElevation() != 0);
final boolean hasOutlineProvider = (nodeInfo != null && nodeInfo.getOutlineProvider() != null);
final boolean hasClipToOutline = (nodeInfo != null && nodeInfo.getClipToOutline());
final boolean isFocusableSetTrue =
(nodeInfo != null && nodeInfo.getFocusState() == FOCUS_SET_TRUE);
return hasFocusChangeHandler
|| hasEnabledTouchEventHandlers
|| hasViewTag
|| hasViewTags
|| hasShadowElevation
|| hasOutlineProvider
|| hasClipToOutline
|| hasAccessibilityContent
|| isFocusableSetTrue;
}
/**
* Collects layout outputs and release the layout tree. The layout outputs hold necessary
* information to be used by {@link MountState} to mount components into a {@link ComponentHost}.
* <p/>
* Whenever a component has view content (view tags, click handler, etc), a new host 'marker'
* is added for it. The mount pass will use the markers to decide which host should be used
* for each layout output. The root node unconditionally generates a layout output corresponding
* to the root host.
* <p/>
* The order of layout outputs follows a depth-first traversal in the tree to ensure the hosts
* will be created at the right order when mounting. The host markers will be define which host
* each mounted artifacts will be attached to.
* <p/>
* At this stage all the {@link InternalNode} for which we have LayoutOutputs that can be recycled
* will have a DiffNode associated. If the CachedMeasures are valid we'll try to recycle both the
* host and the contents (including background/foreground). In all other cases instead we'll only
* try to re-use the hosts. In some cases the host's structure might change between two updates
* even if the component is of the same type. This can happen for example when a click listener is
* added. To avoid trying to re-use the wrong host type we explicitly check that after all the
* children for a subtree have been added (this is when the actual host type is resolved). If the
* host type changed compared to the one in the DiffNode we need to refresh the ids for the whole
* subtree in order to ensure that the MountState will unmount the subtree and mount it again on
* the correct host.
* <p/>
*
* @param node InternalNode to process.
* @param layoutState the LayoutState currently operating.
* @param parentDiffNode whether this method also populates the diff tree and assigns the root
* to mDiffTreeRoot.
*/
private static void collectResults(
InternalNode node,
LayoutState layoutState,
DiffNode parentDiffNode) {
if (node.hasNewLayout()) {
node.markLayoutSeen();
}
final Component<?> component = node.getRootComponent();
// Early return if collecting results of a node holding a nested tree.
if (node.isNestedTreeHolder()) {
// If the nested tree is defined, it has been resolved during a measure call during
// layout calculation.
InternalNode nestedTree = resolveNestedTree(
node,
SizeSpec.makeSizeSpec(node.getWidth(), EXACTLY),
SizeSpec.makeSizeSpec(node.getHeight(), EXACTLY));
if (nestedTree == NULL_LAYOUT) {
return;
}
// Account for position of the holder node.
layoutState.mCurrentX += node.getX();
layoutState.mCurrentY += node.getY();
collectResults(nestedTree, layoutState, parentDiffNode);
layoutState.mCurrentX -= node.getX();
layoutState.mCurrentY -= node.getY();
return;
}
final boolean shouldGenerateDiffTree = layoutState.mShouldGenerateDiffTree;
final DiffNode currentDiffNode = node.getDiffNode();
final boolean shouldUseCachedOutputs =
isMountSpec(component) && currentDiffNode != null;
final boolean isCachedOutputUpdated = shouldUseCachedOutputs && node.areCachedMeasuresValid();
final boolean isTransitionKeySet = layoutState.mIsTransitionKeySet;
layoutState.mIsTransitionKeySet = false;
final DiffNode diffNode;
if (shouldGenerateDiffTree) {
diffNode = createDiffNode(node, parentDiffNode);
if (parentDiffNode == null) {
layoutState.mDiffTreeRoot = diffNode;
}
} else {
diffNode = null;
}
// If the parent of this node is disabled, this node has to be disabled too.
if (layoutState.mParentEnabledState == ENABLED_SET_FALSE) {
node.enabled(false);
}
final boolean needsHostView = needsHostView(node, layoutState);
final long currentHostMarker = layoutState.mCurrentHostMarker;
final int currentHostOutputPosition = layoutState.mCurrentHostOutputPosition;
int hostLayoutPosition = -1;
// 1. Insert a host LayoutOutput if we have some interactive content to be attached to.
if (needsHostView) {
layoutState.mIsTransitionKeySet = !TextUtils.isEmpty(node.getTransitionKey());
hostLayoutPosition = addHostLayoutOutput(node, layoutState, diffNode);
layoutState.mCurrentLevel++;
layoutState.mCurrentHostMarker =
layoutState.mMountableOutputs.get(hostLayoutPosition).getId();
layoutState.mCurrentHostOutputPosition = hostLayoutPosition;
}
// We need to take into account flattening when setting duplicate parent state. The parent after
// flattening may no longer exist. Therefore the value of duplicate parent state should only be
// true if the path between us (inclusive) and our inner/root host (exclusive) all are
// duplicate parent state.
final boolean shouldDuplicateParentState = layoutState.mShouldDuplicateParentState;
layoutState.mShouldDuplicateParentState =
needsHostView || (shouldDuplicateParentState && node.isDuplicateParentStateEnabled());
// Generate the layoutOutput for the given node.
final LayoutOutput layoutOutput = createGenericLayoutOutput(node, layoutState);
if (layoutOutput != null) {
final long previousId = shouldUseCachedOutputs ? currentDiffNode.getContent().getId() : -1;
layoutState.mLayoutStateOutputIdCalculator.calculateAndSetLayoutOutputIdAndUpdateState(
layoutOutput,
layoutState.mCurrentLevel,
LayoutOutput.TYPE_CONTENT,
previousId,
isCachedOutputUpdated);
}
// If we don't need to update this output we can safely re-use the display list from the
// previous output.
if (ThreadUtils.isMainThread() && isCachedOutputUpdated) {
layoutOutput.setDisplayListContainer(currentDiffNode.getContent().getDisplayListContainer());
}
// 2. Add background if defined.
final Reference<? extends Drawable> background = node.getBackground();
if (background != null) {
if (layoutOutput != null && layoutOutput.hasViewNodeInfo()) {
layoutOutput.getViewNodeInfo().setBackground(background);
} else {
final LayoutOutput convertBackground = (currentDiffNode != null)
? currentDiffNode.getBackground()
: null;
final LayoutOutput backgroundOutput = addDrawableComponent(
node,
layoutState,
convertBackground,
background,
LayoutOutput.TYPE_BACKGROUND);
if (diffNode != null) {
diffNode.setBackground(backgroundOutput);
}
}
}
// 3. Now add the MountSpec (either View or Drawable) to the Outputs.
if (isMountSpec(component)) {
// Notify component about its final size.
component.getLifecycle().onBoundsDefined(layoutState.mContext, node, component);
addMountableOutput(layoutState, layoutOutput);
addLayoutOutputIdToPositionsMap(
layoutState.mOutputsIdToPositionMap,
layoutOutput,
layoutState.mMountableOutputs.size() - 1);
if (diffNode != null) {
diffNode.setContent(layoutOutput);
}
}
// 4. Add border color if defined.
if (node.shouldDrawBorders()) {
final LayoutOutput convertBorder = (currentDiffNode != null)
? currentDiffNode.getBorder()
: null;
final LayoutOutput borderOutput = addDrawableComponent(
node,
layoutState,
convertBorder,
getBorderColorDrawable(node),
LayoutOutput.TYPE_BORDER);
if (diffNode != null) {
diffNode.setBorder(borderOutput);
}
}
// 5. Extract the Transitions.
if (ComponentsConfiguration.ARE_TRANSITIONS_SUPPORTED) {
final ArrayList<Transition> transitions = node.getTransitions();
if (transitions != null) {
for (int i = 0, size = transitions.size(); i < size; i++) {
final Transition transition = transitions.get(i);
layoutState.getOrCreateTransitionContext().addTransition(transition);
if (!layoutState.mHasLithoViewBoundsAnimation
&& layoutState.mLayoutRoot.hasTransitionKey()) {
layoutState.mHasLithoViewBoundsAnimation =
hasBoundsAnimation(layoutState.mLayoutRoot.getTransitionKey(), transition);
}
}
}
final ArrayList<Component> componentsNeedingPreviousRenderData =
node.getComponentsNeedingPreviousRenderData();
if (componentsNeedingPreviousRenderData != null) {
if (layoutState.mComponentsNeedingPreviousRenderData == null) {
layoutState.mComponentsNeedingPreviousRenderData = new ArrayList<>();
}
// We'll check for animations in mount
layoutState.mComponentsNeedingPreviousRenderData.addAll(
componentsNeedingPreviousRenderData);
}
}
layoutState.mCurrentX += node.getX();
layoutState.mCurrentY += node.getY();
final @NodeInfo.EnabledState int parentEnabledState = layoutState.mParentEnabledState;
layoutState.mParentEnabledState = (node.getNodeInfo() != null)
? node.getNodeInfo().getEnabledState()
: ENABLED_UNSET;
// We must process the nodes in order so that the layout state output order is correct.
for (int i = 0, size = node.getChildCount(); i < size; i++) {
collectResults(
node.getChildAt(i),
layoutState,
diffNode);
}
layoutState.mParentEnabledState = parentEnabledState;
layoutState.mCurrentX -= node.getX();
layoutState.mCurrentY -= node.getY();
// 6. Add foreground if defined.
final Drawable foreground = node.getForeground();
if (foreground != null) {
if (layoutOutput != null && layoutOutput.hasViewNodeInfo() && SDK_INT >= M) {
layoutOutput.getViewNodeInfo().setForeground(foreground);
} else {
final LayoutOutput convertForeground = (currentDiffNode != null)
? currentDiffNode.getForeground()
: null;
final LayoutOutput foregroundOutput = addDrawableComponent(
node,
layoutState,
convertForeground,
DrawableReference.create().drawable(foreground).build(),
LayoutOutput.TYPE_FOREGROUND);
if (diffNode != null) {
diffNode.setForeground(foregroundOutput);
}
}
}
// 7. Add VisibilityOutputs if any visibility-related event handlers are present.
if (node.hasVisibilityHandlers()) {
final VisibilityOutput visibilityOutput = createVisibilityOutput(node, layoutState);
final long previousId =
shouldUseCachedOutputs && currentDiffNode.getVisibilityOutput() != null
? currentDiffNode.getVisibilityOutput().getId()
: -1;
layoutState.mLayoutStateOutputIdCalculator.calculateAndSetVisibilityOutputId(
visibilityOutput,
layoutState.mCurrentLevel,
previousId);
layoutState.mVisibilityOutputs.add(visibilityOutput);
if (diffNode != null) {
diffNode.setVisibilityOutput(visibilityOutput);
}
}
// 8. If we're in a testing environment, maintain an additional data structure with
// information about nodes that we can query later.
if (layoutState.mTestOutputs != null && !TextUtils.isEmpty(node.getTestKey())) {
final TestOutput testOutput = createTestOutput(node, layoutState, layoutOutput);
layoutState.mTestOutputs.add(testOutput);
}
// 9. Keep a list of the components we created during this layout calculation. If the layout is
// valid, the ComponentTree will update the event handlers that have been created in the
// previous ComponentTree with the new component dispatched, otherwise Section children might
// not be accessing the correct props and state on the event handlers. The null checkers cover
// tests, the scope and tree should not be null at this point of the layout calculation.
if (component != null
&& component.getScopedContext() != null
&& component.getScopedContext().getComponentTree() != null) {
layoutState.mComponents.add(component);
}
if (component != null) {
final Rect rect = ComponentsPools.acquireRect();
if (layoutOutput != null) {
rect.set(layoutOutput.getBounds());
} else {
rect.left = layoutState.mCurrentX + node.getX();
rect.top = layoutState.mCurrentY + node.getY();
rect.right = rect.left + node.getWidth();
rect.bottom = rect.top + node.getHeight();
}
layoutState.mComponentKeyToBounds.put(component.getGlobalKey(), rect);
}
// All children for the given host have been added, restore the previous
// host, level, and duplicate parent state value in the recursive queue.
if (layoutState.mCurrentHostMarker != currentHostMarker) {
layoutState.mCurrentHostMarker = currentHostMarker;
layoutState.mCurrentHostOutputPosition = currentHostOutputPosition;
layoutState.mCurrentLevel--;
}
layoutState.mShouldDuplicateParentState = shouldDuplicateParentState;
layoutState.mIsTransitionKeySet = isTransitionKeySet;
}
Map<String, Rect> getComponentKeyToBounds() {
return mComponentKeyToBounds;
}
List<Component> getComponents() {
return mComponents;
}
void clearComponents() {
mComponents.clear();
}
private static void calculateAndSetHostOutputIdAndUpdateState(
InternalNode node,
LayoutOutput hostOutput,
LayoutState layoutState,
boolean isCachedOutputUpdated) {
if (layoutState.isLayoutRoot(node)) {
// The root host (LithoView) always has ID 0 and is unconditionally
// set as dirty i.e. no need to use shouldComponentUpdate().
hostOutput.setId(ROOT_HOST_ID);
// Special case where the host marker of the root host is pointing to itself.
hostOutput.setHostMarker(ROOT_HOST_ID);
hostOutput.setUpdateState(LayoutOutput.STATE_DIRTY);
} else {
layoutState.mLayoutStateOutputIdCalculator.calculateAndSetLayoutOutputIdAndUpdateState(
hostOutput,
layoutState.mCurrentLevel,
LayoutOutput.TYPE_HOST,
-1,
isCachedOutputUpdated);
}
}
private static LayoutOutput addDrawableComponent(
InternalNode node,
LayoutState layoutState,
LayoutOutput recycle,
Reference<? extends Drawable> reference,
@LayoutOutput.LayoutOutputType int type) {
final Component<DrawableComponent> drawableComponent = DrawableComponent.create(reference);
drawableComponent.setScopedContext(
ComponentContext.withComponentScope(node.getContext(), drawableComponent));
final boolean isOutputUpdated;
if (recycle != null) {
isOutputUpdated = !drawableComponent.getLifecycle().shouldComponentUpdate(
recycle.getComponent(),
drawableComponent);
} else {
isOutputUpdated = false;
}
final long previousId = recycle != null ? recycle.getId() : -1;
final LayoutOutput output = addDrawableLayoutOutput(
drawableComponent,
layoutState,
node,
type,
previousId,
isOutputUpdated);
return output;
}
private static Reference<? extends Drawable> getBorderColorDrawable(InternalNode node) {
if (!node.shouldDrawBorders()) {
throw new RuntimeException("This node does not support drawing border color");
}
final YogaNode yogaNode = node.mYogaNode;
final boolean isRtl = resolveLayoutDirection(yogaNode) == YogaDirection.RTL;
final int[] borderColors = node.getBorderColors();
final YogaEdge leftEdge = isRtl ? YogaEdge.RIGHT : YogaEdge.LEFT;
final YogaEdge rightEdge = isRtl ? YogaEdge.LEFT : YogaEdge.RIGHT;
return BorderColorDrawableReference.create(node.getContext())
.pathEffect(node.getBorderPathEffect())
.borderLeftColor(Border.getEdgeColor(borderColors, leftEdge))
.borderTopColor(Border.getEdgeColor(borderColors, YogaEdge.TOP))
.borderRightColor(Border.getEdgeColor(borderColors, rightEdge))
.borderBottomColor(Border.getEdgeColor(borderColors, YogaEdge.BOTTOM))
.borderLeftWidth(FastMath.round(yogaNode.getLayoutBorder(leftEdge)))
.borderTopWidth(FastMath.round(yogaNode.getLayoutBorder(YogaEdge.TOP)))
.borderRightWidth(FastMath.round(yogaNode.getLayoutBorder(rightEdge)))
.borderBottomWidth(FastMath.round(yogaNode.getLayoutBorder(YogaEdge.BOTTOM)))
.build();
}
/** Continually walks the node hierarchy until a node returns a non inherited layout direction */
private static YogaDirection resolveLayoutDirection(YogaNode node) {
while (node != null && node.getLayoutDirection() == YogaDirection.INHERIT) {
node = node.getParent();
}
return node == null ? YogaDirection.INHERIT : node.getLayoutDirection();
}
private static void addLayoutOutputIdToPositionsMap(
LongSparseArray outputsIdToPositionMap,
LayoutOutput layoutOutput,
int position) {
if (outputsIdToPositionMap != null) {
outputsIdToPositionMap.put(layoutOutput.getId(), position);
}
}
private static LayoutOutput addDrawableLayoutOutput(
Component<DrawableComponent> drawableComponent,
LayoutState layoutState,
InternalNode node,
@LayoutOutput.LayoutOutputType int layoutOutputType,
long previousId,
boolean isCachedOutputUpdated) {
drawableComponent.getLifecycle().onBoundsDefined(
layoutState.mContext,
node,
drawableComponent);
final LayoutOutput drawableLayoutOutput = createDrawableLayoutOutput(
drawableComponent,
layoutState,
node);
layoutState.mLayoutStateOutputIdCalculator.calculateAndSetLayoutOutputIdAndUpdateState(
drawableLayoutOutput,
layoutState.mCurrentLevel,
layoutOutputType,
previousId,
isCachedOutputUpdated);
addMountableOutput(layoutState, drawableLayoutOutput);
addLayoutOutputIdToPositionsMap(
layoutState.mOutputsIdToPositionMap,
drawableLayoutOutput,
layoutState.mMountableOutputs.size() - 1);
return drawableLayoutOutput;
}
static void releaseNodeTree(InternalNode node, boolean isNestedTree) {
if (node == NULL_LAYOUT) {
throw new IllegalArgumentException("Cannot release a null node tree");
}
for (int i = node.getChildCount() - 1; i >= 0; i--) {
final InternalNode child = node.getChildAt(i);
if (isNestedTree && node.hasNewLayout()) {
node.markLayoutSeen();
}
// A node must be detached from its parent *before* being released (otherwise the parent would
// retain a reference to a node that may get re-used by another thread)
node.removeChildAt(i);
releaseNodeTree(child, isNestedTree);
}
if (node.hasNestedTree() && node.getNestedTree() != NULL_LAYOUT) {
releaseNodeTree(node.getNestedTree(), true);
}
node.release();
}
/**
* If we have an interactive LayoutSpec or a MountSpec Drawable, we need to insert an
* HostComponent in the Outputs such as it will be used as a HostView at Mount time. View
* MountSpec are not allowed.
*
* @return The position the HostLayoutOutput was inserted.
*/
private static int addHostLayoutOutput(
InternalNode node,
LayoutState layoutState,
DiffNode diffNode) {
final Component<?> component = node.getRootComponent();
// Only the root host is allowed to wrap view mount specs as a layout output
// is unconditionally added for it.
if (isMountViewSpec(component) && !layoutState.isLayoutRoot(node)) {
throw new IllegalArgumentException("We shouldn't insert a host as a parent of a View");
}
final LayoutOutput hostLayoutOutput = createHostLayoutOutput(layoutState, node);
// The component of the hostLayoutOutput will be set later after all the
// children got processed.
addMountableOutput(layoutState, hostLayoutOutput);
final int hostOutputPosition = layoutState.mMountableOutputs.size() - 1;
if (diffNode != null) {
diffNode.setHost(hostLayoutOutput);
}
calculateAndSetHostOutputIdAndUpdateState(
node,
hostLayoutOutput,
layoutState,
false);
addLayoutOutputIdToPositionsMap(
layoutState.mOutputsIdToPositionMap,
hostLayoutOutput,
hostOutputPosition);
return hostOutputPosition;
}
static <T extends ComponentLifecycle> LayoutState calculate(
ComponentContext c,
Component<T> component,
int componentTreeId,
int widthSpec,
int heightSpec) {
return calculate(
c,
component,
componentTreeId,
widthSpec,
heightSpec,
false /* shouldGenerateDiffTree */,
null /* previousDiffTreeRoot */,
false /* canPrefetchDisplayLists */,
false /* canCacheDrawingDisplayLists */,
true /* clipChildren */);
}
static <T extends ComponentLifecycle> LayoutState calculate(
ComponentContext c,
Component<T> component,
int componentTreeId,
int widthSpec,
int heightSpec,
boolean shouldGenerateDiffTree,
DiffNode previousDiffTreeRoot,
boolean canPrefetchDisplayLists,
boolean canCacheDrawingDisplayLists,
boolean clipChildren) {
// Detect errors internal to components
component.markLayoutStarted();
LayoutState layoutState = ComponentsPools.acquireLayoutState(c);
layoutState.clearComponents();
layoutState.mShouldGenerateDiffTree = shouldGenerateDiffTree;
layoutState.mComponentTreeId = componentTreeId;
layoutState.mAccessibilityManager =
(AccessibilityManager) c.getSystemService(ACCESSIBILITY_SERVICE);
layoutState.mAccessibilityEnabled = isAccessibilityEnabled(layoutState.mAccessibilityManager);
layoutState.mComponent = component;
layoutState.mWidthSpec = widthSpec;
layoutState.mHeightSpec = heightSpec;
layoutState.mCanPrefetchDisplayLists = canPrefetchDisplayLists;
layoutState.mCanCacheDrawingDisplayLists = canCacheDrawingDisplayLists;
layoutState.mClipChildren = clipChildren;
component.applyStateUpdates(c);
final InternalNode root = createAndMeasureTreeForComponent(
component.getScopedContext(),
component,
null, // nestedTreeHolder is null because this is measuring the root component tree.
widthSpec,
heightSpec,
previousDiffTreeRoot);
switch (SizeSpec.getMode(widthSpec)) {
case SizeSpec.EXACTLY:
layoutState.mWidth = SizeSpec.getSize(widthSpec);
break;
case SizeSpec.AT_MOST:
layoutState.mWidth = Math.min(root.getWidth(), SizeSpec.getSize(widthSpec));
break;
case SizeSpec.UNSPECIFIED:
layoutState.mWidth = root.getWidth();
break;
}
switch (SizeSpec.getMode(heightSpec)) {
case SizeSpec.EXACTLY:
layoutState.mHeight = SizeSpec.getSize(heightSpec);
break;
case SizeSpec.AT_MOST:
layoutState.mHeight = Math.min(root.getHeight(), SizeSpec.getSize(heightSpec));
break;
case SizeSpec.UNSPECIFIED:
layoutState.mHeight = root.getHeight();
break;
}
layoutState.mLayoutStateOutputIdCalculator.clear();
// Reset markers before collecting layout outputs.
layoutState.mCurrentHostMarker = -1;
final ComponentsLogger logger = c.getLogger();
if (root == NULL_LAYOUT) {
return layoutState;
}
layoutState.mLayoutRoot = root;
final boolean isTracing = ComponentsSystrace.isTracing();
if (isTracing) {
ComponentsSystrace.beginSection("collectResults:" + component.getSimpleName());
}
LogEvent collectResultsEvent = null;
if (logger != null) {
collectResultsEvent = logger.newPerformanceEvent(EVENT_COLLECT_RESULTS);
collectResultsEvent.addParam(PARAM_LOG_TAG, c.getLogTag());
}
collectResults(root, layoutState, null);
Collections.sort(layoutState.mMountableOutputTops, sTopsComparator);
Collections.sort(layoutState.mMountableOutputBottoms, sBottomsComparator);
if (logger != null) {
logger.log(collectResultsEvent);
}
if (isTracing) {
ComponentsSystrace.endSection();
}
if (!ComponentsConfiguration.isDebugModeEnabled
&& !ComponentsConfiguration.persistInternalNodeTree
&& layoutState.mLayoutRoot != null) {
releaseNodeTree(layoutState.mLayoutRoot, false /* isNestedTree */);
layoutState.mLayoutRoot = null;
}
final Activity activity = getValidActivityForContext(c);
if (activity != null && isEligibleForCreatingDisplayLists()) {
if (ThreadUtils.isMainThread()
&& !layoutState.mCanPrefetchDisplayLists
&& canCollectDisplayListsSync(activity)) {
collectDisplayLists(layoutState);
} else if (layoutState.mCanPrefetchDisplayLists) {
queueDisplayListsForPrefetch(layoutState);
}
}
return layoutState;
}
@ThreadSafe(enableChecks = false)
void preAllocateMountContent() {
final boolean isTracing = ComponentsSystrace.isTracing();
if (isTracing) {
ComponentsSystrace.beginSection("preAllocateMountContent:" + mComponent.getSimpleName());
}
if (mMountableOutputs != null && !mMountableOutputs.isEmpty()) {
for (int i = 0, size = mMountableOutputs.size(); i < size; i++) {
final Component component = mMountableOutputs.get(i).getComponent();
if (Component.isMountViewSpec(component)) {
if (isTracing) {
ComponentsSystrace.beginSection("preAllocateMountContent:" + component.getSimpleName());
}
component.getLifecycle().preAllocateMountContent(mContext);
if (isTracing) {
ComponentsSystrace.endSection();
}
}
}
}
if (isTracing) {
ComponentsSystrace.endSection();
}
}
private static void collectDisplayLists(LayoutState layoutState) {
final boolean isTracing = ComponentsSystrace.isTracing();
if (isTracing) {
ComponentsSystrace.beginSection(
"collectDisplayLists:" + layoutState.mComponent.getSimpleName());
}
final Rect rect = layoutState.mDisplayListCreateRect;
for (int i = 0, count = layoutState.getMountableOutputCount(); i < count; i++) {
final LayoutOutput output = layoutState.getMountableOutputAt(i);
if (shouldCreateDisplayList(output, rect)) {
layoutState.createDisplayList(output);
}
}
if (isTracing) {
ComponentsSystrace.endSection();
}
}
private static boolean shouldCreateDisplayList(LayoutOutput output, Rect rect) {
final Component component = output.getComponent();
final ComponentLifecycle lifecycle = component.getLifecycle();
if (!lifecycle.shouldUseDisplayList()) {
return false;
}
output.getMountBounds(rect);
if (!output.hasValidDisplayList()) {
return true;
}
// This output already has a valid DisplayList from diffing. No need to re-create it.
// Just update its bounds.
final DisplayList displayList = output.getDisplayList();
try {
displayList.setBounds(rect.left, rect.top, rect.right, rect.bottom);
return false;
} catch (DisplayListException e) {
// Nothing to do here.
}
return true;
}
private static boolean canCollectDisplayListsSync(Activity activity) {
// If we have no window or the hierarchy has never been drawn before we cannot guarantee that
// a valid GL context exists. In this case just bail.
final Window window = activity.getWindow();
if (window == null) {
return false;
}
final View decorView = window.getDecorView();
if (decorView == null || decorView.getDrawingTime() == 0) {
return false;
}
return true;
}
boolean isActivityValid() {
return getValidActivityForContext(mContext) != null;
}
void createDisplayList(LayoutOutput output) {
ThreadUtils.assertMainThread();
final ComponentContext context = mContext;
if (context == null) {
// This instance has been released.
return;
}
final Component component = output.getComponent();
final boolean isTracing = ComponentsSystrace.isTracing();
if (isTracing) {
ComponentsSystrace.beginSection("createDisplayList: " + component.getSimpleName());
}
final ComponentLifecycle lifecycle = component.getLifecycle();
final DisplayList displayList = DisplayList.createDisplayList(
lifecycle.getClass().getSimpleName());
if (displayList == null) {
ComponentsSystrace.endSection();
return;
}
Drawable drawable =
(Drawable) ComponentsPools.acquireMountContent(context, lifecycle.getTypeId());
if (drawable == null) {
drawable = (Drawable) lifecycle.createMountContent(context);
}
final LayoutOutput clickableOutput = findInteractiveRoot(this, output);
boolean isStateEnabled = false;
if (clickableOutput != null && clickableOutput.getNodeInfo() != null) {
final NodeInfo nodeInfo = clickableOutput.getNodeInfo();
if (nodeInfo.hasTouchEventHandlers() || nodeInfo.getFocusState() == FOCUS_SET_TRUE) {
isStateEnabled = true;
}
}
if (isStateEnabled) {
drawable.setState(DRAWABLE_STATE_ENABLED);
} else {
drawable.setState(DRAWABLE_STATE_NOT_ENABLED);
}
lifecycle.mount(
component.getScopedContext() != null ? component.getScopedContext() : context,
drawable,
component);
lifecycle.bind(context, drawable, component);
final Rect rect = mDisplayListCreateRect;
output.getMountBounds(rect);
drawable.setBounds(0, 0, rect.width(), rect.height());
try {
final Canvas canvas = displayList.start(rect.width(), rect.height());
drawable.draw(canvas);
displayList.end(canvas);
displayList.setBounds(rect.left, rect.top, rect.right, rect.bottom);
output.setDisplayList(displayList);
} catch (DisplayListException e) {
// Display list creation failed. Make sure the DisplayList for this output is set
// to null.
output.setDisplayList(null);
}
lifecycle.unbind(context, drawable, component);
lifecycle.unmount(context, drawable, component);
ComponentsPools.release(context, lifecycle, drawable);
if (isTracing) {
ComponentsSystrace.endSection();
}
}
private static void queueDisplayListsForPrefetch(LayoutState layoutState) {
final Rect rect = layoutState.mDisplayListQueueRect;
for (int i = 0, count = layoutState.getMountableOutputCount(); i < count; i++) {
final LayoutOutput output = layoutState.getMountableOutputAt(i);
if (shouldCreateDisplayList(output, rect)) {
layoutState.mDisplayListsToPrefetch.add(i);
}
}
if (!layoutState.mDisplayListsToPrefetch.isEmpty()) {
DisplayListPrefetcher.getInstance().addLayoutState(layoutState);
}
}
public static boolean isEligibleForCreatingDisplayLists() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
}
private static LayoutOutput findInteractiveRoot(LayoutState layoutState, LayoutOutput output) {
if (output.getId() == ROOT_HOST_ID) {
return output;
}
if ((output.getFlags() & FLAG_DUPLICATE_PARENT_STATE) != 0) {
final int parentPosition = layoutState.getLayoutOutputPositionForId(output.getHostMarker());
if (parentPosition >= 0) {
final LayoutOutput parent = layoutState.mMountableOutputs.get(parentPosition);
if (parent == null) {
return null;
}
return findInteractiveRoot(layoutState, parent);
}
return null;
}
return output;
}
@VisibleForTesting
static <T extends ComponentLifecycle> InternalNode createTree(
Component<T> component,
ComponentContext context) {
final ComponentsLogger logger = context.getLogger();
LogEvent createLayoutEvent = null;
if (logger != null) {
createLayoutEvent = logger.newPerformanceEvent(EVENT_CREATE_LAYOUT);
createLayoutEvent.addParam(PARAM_LOG_TAG, context.getLogTag());
createLayoutEvent.addParam(PARAM_COMPONENT, component.getSimpleName());
}
final InternalNode root = (InternalNode) component.getLifecycle().createLayout(
context,
component,
true /* resolveNestedTree */);
if (logger != null) {
logger.log(createLayoutEvent);
}
return root;
}
@VisibleForTesting
static void measureTree(
InternalNode root,
int widthSpec,
int heightSpec,
DiffNode previousDiffTreeRoot) {
final ComponentContext context = root.getContext();
final Component component = root.getRootComponent();
final boolean isTracing = ComponentsSystrace.isTracing();
if (isTracing) {
ComponentsSystrace.beginSection("measureTree:" + component.getSimpleName());
}
if (YogaConstants.isUndefined(root.getStyleWidth())) {
root.setStyleWidthFromSpec(widthSpec);
}
if (YogaConstants.isUndefined(root.getStyleHeight())) {
root.setStyleHeightFromSpec(heightSpec);
}
if (previousDiffTreeRoot != null) {
ComponentsSystrace.beginSection("applyDiffNode");
applyDiffNodeToUnchangedNodes(root, previousDiffTreeRoot);
ComponentsSystrace.endSection(/* applyDiffNode */);
}
final ComponentsLogger logger = context.getLogger();
LogEvent layoutEvent = null;
if (logger != null) {
layoutEvent = logger.newPerformanceEvent(EVENT_CSS_LAYOUT);
layoutEvent.addParam(PARAM_LOG_TAG, context.getLogTag());
layoutEvent.addParam(PARAM_TREE_DIFF_ENABLED, String.valueOf(previousDiffTreeRoot != null));
}
root.calculateLayout(
SizeSpec.getMode(widthSpec) == SizeSpec.UNSPECIFIED
? YogaConstants.UNDEFINED
: SizeSpec.getSize(widthSpec),
SizeSpec.getMode(heightSpec) == SizeSpec.UNSPECIFIED
? YogaConstants.UNDEFINED
: SizeSpec.getSize(heightSpec));
if (logger != null) {
logger.log(layoutEvent);
}
if (isTracing) {
ComponentsSystrace.endSection(/* measureTree */ );
}
}
/**
* Create and measure the nested tree or return the cached one for the same size specs.
*/
static InternalNode resolveNestedTree(
InternalNode nestedTreeHolder,
int widthSpec,
int heightSpec) {
final ComponentContext context = nestedTreeHolder.getContext();
final Component<?> component = nestedTreeHolder.getRootComponent();
InternalNode nestedTree = nestedTreeHolder.getNestedTree();
if (nestedTree == null
|| !hasCompatibleSizeSpec(
nestedTree.getLastWidthSpec(),
nestedTree.getLastHeightSpec(),
widthSpec,
heightSpec,
nestedTree.getLastMeasuredWidth(),
nestedTree.getLastMeasuredHeight())) {
if (nestedTree != null) {
if (nestedTree != NULL_LAYOUT) {
releaseNodeTree(nestedTree, true /* isNestedTree */);
}
nestedTree = null;
}
if (component.hasCachedLayout()) {
final InternalNode cachedLayout = component.getCachedLayout();
final boolean hasCompatibleLayoutDirection =
InternalNode.hasValidLayoutDirectionInNestedTree(nestedTreeHolder, cachedLayout);
// Transfer the cached layout to the node without releasing it if it's compatible.
if (hasCompatibleLayoutDirection &&
hasCompatibleSizeSpec(
cachedLayout.getLastWidthSpec(),
cachedLayout.getLastHeightSpec(),
widthSpec,
heightSpec,
cachedLayout.getLastMeasuredWidth(),
cachedLayout.getLastMeasuredHeight())) {
nestedTree = cachedLayout;
component.clearCachedLayout();
} else {
component.releaseCachedLayout();
}
}
if (nestedTree == null) {
nestedTree = createAndMeasureTreeForComponent(
context,
component,
nestedTreeHolder,
widthSpec,
heightSpec,
nestedTreeHolder.getDiffNode()); // Previously set while traversing the holder's tree.
nestedTree.setLastWidthSpec(widthSpec);
nestedTree.setLastHeightSpec(heightSpec);
nestedTree.setLastMeasuredHeight(nestedTree.getHeight());
nestedTree.setLastMeasuredWidth(nestedTree.getWidth());
}
nestedTreeHolder.setNestedTree(nestedTree);
}
// This is checking only nested tree roots however it will be moved to check all the tree roots.
InternalNode.assertContextSpecificStyleNotSet(nestedTree);
return nestedTree;
}
/**
* Create and measure a component with the given size specs.
*/
static InternalNode createAndMeasureTreeForComponent(
ComponentContext c,
Component component,
int widthSpec,
int heightSpec) {
return createAndMeasureTreeForComponent(c, component, null, widthSpec, heightSpec, null);
}
private static InternalNode createAndMeasureTreeForComponent(
ComponentContext c,
Component component,
InternalNode nestedTreeHolder, // This will be set only if we are resolving a nested tree.
int widthSpec,
int heightSpec,
DiffNode diffTreeRoot) {
final boolean isTest = "robolectric".equals(Build.FINGERPRINT);
// Copy the context so that it can have its own set of tree props.
// Robolectric tests keep the context so that tree props can be set externally.
if (!isTest) {
c = c.makeNewCopy();
}
final boolean hasNestedTreeHolder = nestedTreeHolder != null;
if (hasNestedTreeHolder) {
c.setTreeProps(nestedTreeHolder.getPendingTreeProps());
} else if (!isTest) {
c.setTreeProps(null);
}
// Account for the size specs in ComponentContext in case the tree is a NestedTree.
final int previousWidthSpec = c.getWidthSpec();
final int previousHeightSpec = c.getHeightSpec();
c.setWidthSpec(widthSpec);
c.setHeightSpec(heightSpec);
final InternalNode root = createTree(
component,
c);
if (hasNestedTreeHolder) {
c.setTreeProps(null);
}
c.setWidthSpec(previousWidthSpec);
c.setHeightSpec(previousHeightSpec);
if (root == NULL_LAYOUT) {
return root;
}
// If measuring a ComponentTree with a LayoutSpecWithSizeSpec at the root, the nested tree
// holder argument will be null.
if (hasNestedTreeHolder && isLayoutSpecWithSizeSpec(component)) {
// Transfer information from the holder node to the nested tree root before measurement.
nestedTreeHolder.copyInto(root);
diffTreeRoot = nestedTreeHolder.getDiffNode();
} else if (root.getStyleDirection() == com.facebook.yoga.YogaDirection.INHERIT
&& LayoutState.isLayoutDirectionRTL(c)) {
root.layoutDirection(YogaDirection.RTL);
}
measureTree(
root,
widthSpec,
heightSpec,
diffTreeRoot);
return root;
}
static DiffNode createDiffNode(InternalNode node, DiffNode parent) {
ComponentsSystrace.beginSection("diff_node_creation");
DiffNode diffNode = ComponentsPools.acquireDiffNode();
diffNode.setLastWidthSpec(node.getLastWidthSpec());
diffNode.setLastHeightSpec(node.getLastHeightSpec());
diffNode.setLastMeasuredWidth(node.getLastMeasuredWidth());
diffNode.setLastMeasuredHeight(node.getLastMeasuredHeight());
diffNode.setComponent(node.getRootComponent());
if (parent != null) {
parent.addChild(diffNode);
}
ComponentsSystrace.endSection();
return diffNode;
}
boolean isCompatibleSpec(int widthSpec, int heightSpec) {
final boolean widthIsCompatible =
MeasureComparisonUtils.isMeasureSpecCompatible(
mWidthSpec,
widthSpec,
mWidth);
final boolean heightIsCompatible =
MeasureComparisonUtils.isMeasureSpecCompatible(
mHeightSpec,
heightSpec,
mHeight);
return widthIsCompatible && heightIsCompatible;
}
boolean isCompatibleAccessibility() {
return isAccessibilityEnabled(mAccessibilityManager) == mAccessibilityEnabled;
}
private static boolean isAccessibilityEnabled(AccessibilityManager accessibilityManager) {
return accessibilityManager.isEnabled() &&
AccessibilityManagerCompat.isTouchExplorationEnabled(accessibilityManager);
}
/**
* Traverses the layoutTree and the diffTree recursively. If a layoutNode has a compatible host
* type {@link LayoutState#hostIsCompatible} it assigns the DiffNode to the layout node in order
* to try to re-use the LayoutOutputs that will be generated by {@link
* LayoutState#collectResults(InternalNode, LayoutState, DiffNode)}. If a layoutNode
* component returns false when shouldComponentUpdate is called with the DiffNode Component it
* also tries to re-use the old measurements and therefore marks as valid the cachedMeasures for
* the whole component subtree.
*
* @param layoutNode the root of the LayoutTree
* @param diffNode the root of the diffTree
*
* @return true if the layout node requires updating, false if it can re-use the measurements
* from the diff node.
*/
static boolean applyDiffNodeToUnchangedNodes(InternalNode layoutNode, DiffNode diffNode) {
// Root of the main tree or of a nested tree.
final boolean isTreeRoot = layoutNode.getParent() == null;
if (isLayoutSpecWithSizeSpec(layoutNode.getRootComponent()) && !isTreeRoot) {
layoutNode.setDiffNode(diffNode);
return true;
}
if (!hostIsCompatible(layoutNode, diffNode)) {
return true;
}
layoutNode.setDiffNode(diffNode);
final int layoutCount = layoutNode.getChildCount();
final int diffCount = diffNode.getChildCount();
// Layout node needs to be updated if:
// - it has a different number of children.
// - one of its children needs updating.
// - the node itself declares that it needs updating.
boolean shouldUpdate = layoutCount != diffCount;
for (int i = 0; i < layoutCount && i < diffCount; i++) {
// ensure that we always run for all children.
boolean shouldUpdateChild =
applyDiffNodeToUnchangedNodes(
layoutNode.getChildAt(i),
diffNode.getChildAt(i));
shouldUpdate |= shouldUpdateChild;
}
shouldUpdate |= shouldComponentUpdate(layoutNode, diffNode);
if (!shouldUpdate) {
applyDiffNodeToLayoutNode(layoutNode, diffNode);
}
return shouldUpdate;
}
/**
* Copies the inter stage state (if any) from the DiffNode's component to the layout node's
* component, and declares that the cached measures on the diff node are valid for the layout
* node.
*/
private static void applyDiffNodeToLayoutNode(InternalNode layoutNode, DiffNode diffNode) {
final Component component = layoutNode.getRootComponent();
if (component != null) {
component.copyInterStageImpl(diffNode.getComponent());
}
layoutNode.setCachedMeasuresValid(true);
}
/**
* Returns true either if the two nodes have the same Component type or if both don't have a
* Component.
*/
private static boolean hostIsCompatible(InternalNode node, DiffNode diffNode) {
if (diffNode == null) {
return false;
}
return isSameComponentType(node.getRootComponent(), diffNode.getComponent());
}
private static boolean isSameComponentType(Component a, Component b) {
if (a == b) {
return true;
} else if (a == null || b == null) {
return false;
}
return a.getLifecycle().getClass().equals(b.getLifecycle().getClass());
}
private static boolean shouldComponentUpdate(InternalNode layoutNode, DiffNode diffNode) {
if (diffNode == null) {
return true;
}
final Component component = layoutNode.getRootComponent();
if (component != null) {
return component.getLifecycle().shouldComponentUpdate(component, diffNode.getComponent());
}
return true;
}
boolean isCompatibleComponentAndSpec(
int componentId,
int widthSpec,
int heightSpec) {
return mComponent.getId() == componentId && isCompatibleSpec(widthSpec, heightSpec);
}
boolean isCompatibleSize(int width, int height) {
return mWidth == width && mHeight == height;
}
boolean isComponentId(int componentId) {
return mComponent.getId() == componentId;
}
int getMountableOutputCount() {
return mMountableOutputs.size();
}
LayoutOutput getMountableOutputAt(int index) {
return mMountableOutputs.get(index);
}
ArrayList<LayoutOutput> getMountableOutputTops() {
return mMountableOutputTops;
}
ArrayList<LayoutOutput> getMountableOutputBottoms() {
return mMountableOutputBottoms;
}
int getVisibilityOutputCount() {
return mVisibilityOutputs.size();
}
VisibilityOutput getVisibilityOutputAt(int index) {
return mVisibilityOutputs.get(index);
}
int getTestOutputCount() {
return mTestOutputs == null ? 0 : mTestOutputs.size();
}
TestOutput getTestOutputAt(int index) {
return mTestOutputs == null ? null : mTestOutputs.get(index);
}
public DiffNode getDiffTree() {
return mDiffTreeRoot;
}
int getWidth() {
return mWidth;
}
int getHeight() {
return mHeight;
}
/**
* @return The id of the {@link ComponentTree} that generated this {@link LayoutState}
*/
int getComponentTreeId() {
return mComponentTreeId;
}
/**
* See {@link LayoutState#acquireRef} Call this when you are done using the reference to the
* LayoutState.
*/
@ThreadSafe(enableChecks = false)
void releaseRef() {
int count = mReferenceCount.decrementAndGet();
if (count < 0) {
throw new IllegalStateException("Trying to releaseRef a recycled LayoutState");
}
if (count == 0) {
mContext = null;
mComponent = null;
mWidth = 0;
mHeight = 0;
mCurrentX = 0;
mCurrentY = 0;
mCurrentHostMarker = -1;
mCurrentHostOutputPosition = -1;
mComponentTreeId = -1;
mShouldDuplicateParentState = true;
mIsTransitionKeySet = false;
mClipChildren = true;
for (int i = 0, size = mMountableOutputs.size(); i < size; i++) {
mMountableOutputs.get(i).release();
}
mMountableOutputs.clear();
mMountableOutputTops.clear();
mMountableOutputBottoms.clear();
mOutputsIdToPositionMap.clear();
mDisplayListsToPrefetch.clear();
for (Rect rect : mComponentKeyToBounds.values()) {
ComponentsPools.release(rect);
}
mComponentKeyToBounds.clear();
for (int i = 0, size = mVisibilityOutputs.size(); i < size; i++) {
ComponentsPools.release(mVisibilityOutputs.get(i));
}
mVisibilityOutputs.clear();
if (mTestOutputs != null) {
for (int i = 0, size = mTestOutputs.size(); i < size; i++) {
ComponentsPools.release(mTestOutputs.get(i));
}
mTestOutputs.clear();
}
mShouldGenerateDiffTree = false;
mAccessibilityManager = null;
mAccessibilityEnabled = false;
if (mDiffTreeRoot != null) {
ComponentsPools.release(mDiffTreeRoot);
mDiffTreeRoot = null;
}
mLayoutStateOutputIdCalculator.clear();
if (mTransitionContext != null) {
ComponentsPools.release(mTransitionContext);
mTransitionContext = null;
}
// This should only ever be true in non-release builds as we need this for Stetho integration
// (or for as long as the ComponentsConfiguration.persistInternalNodeTree experiment runs).
// Otherwise, in release builds the node tree is released in calculateLayout().
if (mLayoutRoot != null) {
releaseNodeTree(mLayoutRoot, false /* isNestedTree */);
mLayoutRoot = null;
}
if (mComponentsNeedingPreviousRenderData != null) {
mComponentsNeedingPreviousRenderData.clear();
}
mTransitionKeyMapping = null;
mHasLithoViewBoundsAnimation = false;
ComponentsPools.release(this);
}
}
/**
* The lifecycle of LayoutState is generally controlled by ComponentTree. Since sometimes we need
* an old LayoutState to be passed to a new LayoutState to implement Tree diffing, We use
* reference counting to avoid releasing a LayoutState that is not used by ComponentTree anymore
* but could be used by another LayoutState. The rule is that whenever you need to pass the
* LayoutState outside of ComponentTree, you acquire a reference and then you release it as soon
* as you are done with it
*
* @return The same LayoutState instance with an higher reference count.
*/
@CheckReturnValue
LayoutState acquireRef() {
if (mReferenceCount.getAndIncrement() == 0) {
throw new IllegalStateException("Trying to use a released LayoutState");
}
return this;
}
/**
* Returns the state handler instance currently held by LayoutState and nulls it afterwards.
*
* @return the state handler
*/
@CheckReturnValue
StateHandler consumeStateHandler() {
final StateHandler stateHandler = mStateHandler;
mStateHandler = null;
return stateHandler;
}
InternalNode getLayoutRoot() {
return mLayoutRoot;
}
// If the layout root is a nested tree holder node, it gets skipped immediately while
// collecting the LayoutOutputs. The nested tree itself effectively becomes the layout
// root in this case.
private boolean isLayoutRoot(InternalNode node) {
return mLayoutRoot.isNestedTreeHolder()
? node == mLayoutRoot.getNestedTree()
: node == mLayoutRoot;
}
/**
* Check if a cached nested tree has compatible SizeSpec to be reused as is or
* if it needs to be recomputed.
*
* The conditions to be able to re-use previous measurements are:
* 1) The measureSpec is the same
* 2) The new measureSpec is EXACTLY and the last measured size matches the measureSpec size.
* 3) The old measureSpec is UNSPECIFIED, the new one is AT_MOST and the old measured size is
* smaller that the maximum size the new measureSpec will allow.
* 4) Both measure specs are AT_MOST. The old measure spec allows a bigger size than the new and
* the old measured size is smaller than the allowed max size for the new sizeSpec.
*/
public static boolean hasCompatibleSizeSpec(
int oldWidthSpec,
int oldHeightSpec,
int newWidthSpec,
int newHeightSpec,
float oldMeasuredWidth,
float oldMeasuredHeight) {
final boolean widthIsCompatible =
MeasureComparisonUtils.isMeasureSpecCompatible(
oldWidthSpec,
newWidthSpec,
(int) oldMeasuredWidth);
final boolean heightIsCompatible =
MeasureComparisonUtils.isMeasureSpecCompatible(
oldHeightSpec,
newHeightSpec,
(int) oldMeasuredHeight);
return widthIsCompatible && heightIsCompatible;
}
/**
* Returns true if this is the root node (which always generates a matching layout
* output), if the node has view attributes e.g. tags, content description, etc, or if
* the node has explicitly been forced to be wrapped in a view.
*/
private static boolean needsHostView(InternalNode node, LayoutState layoutState) {
return layoutState.isLayoutRoot(node)
|| (!isMountViewSpec(node.getRootComponent())
&& (hasViewContent(node, layoutState) || node.isForceViewWrapping()));
}
/**
* @return the position of the {@link LayoutOutput} with id layoutOutputId in the
* {@link LayoutState} list of outputs or -1 if no {@link LayoutOutput} with that id exists in
* the {@link LayoutState}
*/
int getLayoutOutputPositionForId(long layoutOutputId) {
return mOutputsIdToPositionMap.get(layoutOutputId, -1);
}
TransitionContext getTransitionContext() {
return mTransitionContext;
}
boolean hasTransitionContext() {
return (mTransitionContext != null);
}
/**
* Gets (or creates) a mapping from transition key to LayoutOutput.
*/
SimpleArrayMap<String, LayoutOutput> getTransitionKeyMapping() {
if (mTransitionKeyMapping != null) {
return mTransitionKeyMapping;
}
mTransitionKeyMapping = new SimpleArrayMap<>();
for (int i = 0, size = getMountableOutputCount(); i < size; i++) {
final LayoutOutput newOutput = getMountableOutputAt(i);
final String transitionKey = newOutput.getTransitionKey();
if (transitionKey == null) {
continue;
}
if (mTransitionKeyMapping.put(transitionKey, newOutput) != null) {
throw new RuntimeException(
"The transitionKey '"
+ transitionKey
+ "' was defined multiple times in the same layout. transitionKeys must be unique "
+ "identifiers per layout. If this is a reusable component that can appear in the "
+ "same layout multiple times, consider passing unique transitionKeys from above.");
}
}
return mTransitionKeyMapping;
}
LayoutOutput getLayoutOutputForTransitionKey(String transitionKey) {
return getTransitionKeyMapping().get(transitionKey);
}
private static void addMountableOutput(LayoutState layoutState, LayoutOutput layoutOutput) {
layoutState.mMountableOutputs.add(layoutOutput);
layoutState.mMountableOutputTops.add(layoutOutput);
layoutState.mMountableOutputBottoms.add(layoutOutput);
}
private TransitionContext getOrCreateTransitionContext() {
if (mTransitionContext == null) {
mTransitionContext = ComponentsPools.acquireTransitionContext();
}
return mTransitionContext;
}
/**
* @return whether the main thread layout state defines a transition that animates the bounds of
* the root component (and thus the LithoView).
*/
boolean hasLithoViewBoundsAnimation() {
return mHasLithoViewBoundsAnimation;
}
/** @return whether there are any items in the queue for Display Lists prefetching. */
boolean hasItemsForDLPrefetch() {
return !mDisplayListsToPrefetch.isEmpty();
}
/**
* Remove items that have already valid displaylist. This item might have been already drawn on
* the screen in which case we will have valid displaylist so we can skip them.
*/
void trimDisplayListItemsQueue() {
if (mMountableOutputs.isEmpty()) {
// Item has been released, remove all pending items for displaylist prefetch.
mDisplayListsToPrefetch.clear();
return;
}
Integer currentIndex = mDisplayListsToPrefetch.peek();
while (currentIndex != null) {
final LayoutOutput layoutOutput = mMountableOutputs.get(currentIndex);
if (!layoutOutput.hasDisplayListContainer() || layoutOutput.hasValidDisplayList()) {
// Either this item has been released or we have already computed displaylist for this item.
// In either case remove it from the queue.
mDisplayListsToPrefetch.remove();
currentIndex = mDisplayListsToPrefetch.peek();
} else {
break;
}
}
}
/**
* Removes and returns next {@link LayoutOutput} from the queue for Display Lists.
* Note that it is callers responsibility to make sure queue is not empty.
*/
LayoutOutput getNextLayoutOutputForDLPrefetch() {
final int layoutOutputIndex = mDisplayListsToPrefetch.poll();
return getMountableOutputAt(layoutOutputIndex);
}
/**
* @return the list of Components in this LayoutState that care about the previously mounted
* versions of their @Prop/@State params.
*/
@Nullable
List<Component> getComponentsNeedingPreviousRenderData() {
return mComponentsNeedingPreviousRenderData;
}
}
|
Enable setting tooltips on delegate components
Summary: this depends on android_fb4a_feed_footer.persist_all_components qe, which gives us access to all the components that were used to create an InternalNode and enables us to use delegate components as anchors
Reviewed By: IanChilds
Differential Revision: D6198268
fbshipit-source-id: a1269e0af8b76060016280389d7a47928c4f9aac
|
litho-core/src/main/java/com/facebook/litho/LayoutState.java
|
Enable setting tooltips on delegate components
|
<ide><path>itho-core/src/main/java/com/facebook/litho/LayoutState.java
<ide> rect.right = rect.left + node.getWidth();
<ide> rect.bottom = rect.top + node.getHeight();
<ide> }
<del> layoutState.mComponentKeyToBounds.put(component.getGlobalKey(), rect);
<add> for (Component delegate : node.getComponents()) {
<add> layoutState.mComponentKeyToBounds.put(delegate.getGlobalKey(), rect);
<add> }
<ide> }
<ide>
<ide> // All children for the given host have been added, restore the previous
<ide> mDisplayListsToPrefetch.clear();
<ide>
<ide> for (Rect rect : mComponentKeyToBounds.values()) {
<del> ComponentsPools.release(rect);
<add> // Delegate components are using the same Rect instance as the components they create since
<add> // we don't calculate a layout output for them. We need to make sure we only release it
<add> // once.
<add> if (!rect.isEmpty()) {
<add> ComponentsPools.release(rect);
<add> }
<ide> }
<ide> mComponentKeyToBounds.clear();
<ide>
|
|
Java
|
mit
|
4497a20ddd94e4f9077c8dcf683fd6eb60679573
| 0 |
osiam/osiam,osiam/osiam,fwilhe/osiam,tkrille/osiam-osiam,fwilhe/osiam,osiam/osiam,tkrille/osiam-osiam,fwilhe/osiam,tkrille/osiam-osiam
|
/*
* Copyright (C) 2013 tarent AG
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.osiam.storage.entities;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
/**
* User Entity
*/
@Entity(name = "scim_user")
@NamedQueries({@NamedQuery(name = "getUserByUsername", query = "SELECT u FROM scim_user u WHERE u.userName = :username")})
public class UserEntity extends ResourceEntity {
private static final String MAPPING_NAME = "user";
@Column(nullable = false, unique = true)
private String userName;
@OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)
private NameEntity name;
@Column
private String nickName;
@Column
private String profileUrl;
@Column
private String title;
@Column
private String userType;
@Column
private String preferredLanguage;
@Column
private String locale;
@Column
private String timezone;
@Column
private Boolean active = Boolean.FALSE;
@Column(nullable = false)
private String password;
@Column
private String displayName;
@OneToMany(mappedBy = MAPPING_NAME, cascade = CascadeType.ALL, orphanRemoval = true)
private Set<EmailEntity> emails = new HashSet<>();
@OneToMany(mappedBy = MAPPING_NAME, cascade = CascadeType.ALL, orphanRemoval = true)
private Set<PhoneNumberEntity> phoneNumbers = new HashSet<>();
@OneToMany(mappedBy = MAPPING_NAME, cascade = CascadeType.ALL, orphanRemoval = true)
private Set<ImEntity> ims = new HashSet<>();
@OneToMany(mappedBy = MAPPING_NAME, cascade = CascadeType.ALL, orphanRemoval = true)
private Set<PhotoEntity> photos = new HashSet<>();
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
private Set<AddressEntity> addresses = new HashSet<>();
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
private Set<EntitlementsEntity> entitlements = new HashSet<>();
@OneToMany(cascade = CascadeType.ALL)
private Set<RolesEntity> roles = new HashSet<>();
@OneToMany(mappedBy = MAPPING_NAME, cascade = CascadeType.ALL, orphanRemoval = true)
private Set<X509CertificateEntity> x509Certificates = new HashSet<>();
@OneToMany
@JoinTable(name = "scim_user_scim_extension", joinColumns = {@JoinColumn(name = "scim_user_internal_id", referencedColumnName = "internal_id")},
inverseJoinColumns = {@JoinColumn(name = "registered_extensions_internal_id", referencedColumnName = "internal_id")})
private Set<ExtensionEntity> registeredExtensions = new HashSet<>();
@OneToMany(mappedBy = MAPPING_NAME, cascade = CascadeType.ALL, orphanRemoval = true)
private Set<ExtensionFieldValueEntity> extensionFieldValues = new HashSet<>();
public UserEntity() {
getMeta().setResourceType("User");
}
/**
* @return the name entity
*/
public NameEntity getName() {
return name;
}
/**
* @param name the name entity
*/
public void setName(NameEntity name) {
this.name = name;
}
/**
* @return the nick name
*/
public String getNickName() {
return nickName;
}
/**
* @param nickName the nick name
*/
public void setNickName(String nickName) {
this.nickName = nickName;
}
/**
* @return the profile url
*/
public String getProfileUrl() {
return profileUrl;
}
/**
* @param profileUrl the profile url
*/
public void setProfileUrl(String profileUrl) {
this.profileUrl = profileUrl;
}
/**
* @return the title
*/
public String getTitle() {
return title;
}
/**
* @param title the title
*/
public void setTitle(String title) {
this.title = title;
}
/**
* @return the user type
*/
public String getUserType() {
return userType;
}
/**
* @param userType the user type
*/
public void setUserType(String userType) {
this.userType = userType;
}
/**
* @return the preferred languages
*/
public String getPreferredLanguage() {
return preferredLanguage;
}
/**
* @param preferredLanguage the preferred languages
*/
public void setPreferredLanguage(String preferredLanguage) {
this.preferredLanguage = preferredLanguage;
}
/**
* @return the locale
*/
public String getLocale() {
return locale;
}
/**
* @param locale the locale
*/
public void setLocale(String locale) {
this.locale = locale;
}
/**
* @return the timezone
*/
public String getTimezone() {
return timezone;
}
/**
* @param timezone the timezone
*/
public void setTimezone(String timezone) {
this.timezone = timezone;
}
/**
* @return the active status
*/
public Boolean getActive() {
return active;
}
/**
* @param active the active status
*/
public void setActive(Boolean active) {
this.active = active;
}
/**
* @return the password
*/
public String getPassword() {
return password;
}
/**
* @param password the password
*/
public void setPassword(String password) {
this.password = password;
}
@Override
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getUserName() {
return userName;
}
/**
* @param userName the user name
*/
public void setUserName(String userName) {
this.userName = userName;
}
/**
* @return the emails entity
*/
public Set<EmailEntity> getEmails() {
return emails;
}
/**
* @param emails the emails entity
*/
public void setEmails(Set<EmailEntity> emails) {
//Setting Foreign key in child entity because hibernate did it not automatically
if (emails != null) {
for (EmailEntity emailEntity : emails) {
emailEntity.setUser(this);
}
}
this.emails = emails;
}
/**
* @return the extensions data of the user
*/
public Set<ExtensionFieldValueEntity> getUserExtensions() {
if (extensionFieldValues == null) {
extensionFieldValues = new HashSet<>();
}
return extensionFieldValues;
}
/**
* @param userExtensions the extension data of the user
*/
public void setUserExtensions(Set<ExtensionFieldValueEntity> userExtensions) {
if (userExtensions != null) {
for (ExtensionFieldValueEntity extensionValue : userExtensions) {
extensionValue.setUser(this);
}
}
this.extensionFieldValues = userExtensions;
}
/**
* @return the phone numbers entity
*/
public Set<PhoneNumberEntity> getPhoneNumbers() {
return phoneNumbers;
}
/**
* @param phoneNumbers the phone numbers entity
*/
public void setPhoneNumbers(Set<PhoneNumberEntity> phoneNumbers) {
//Setting Foreign key in child entity because hibernate did it not automatically
if (phoneNumbers != null) {
for (PhoneNumberEntity phoneNumberEntity : phoneNumbers) {
phoneNumberEntity.setUser(this);
}
}
this.phoneNumbers = phoneNumbers;
}
/**
* @return the instant messaging entity
*/
public Set<ImEntity> getIms() {
return ims;
}
/**
* @param ims the instant messaging entity
*/
public void setIms(Set<ImEntity> ims) {
//Setting Foreign key in child entity because hibernate did it not automatically
if (ims != null) {
for (ImEntity imEntity : ims) {
imEntity.setUser(this);
}
}
this.ims = ims;
}
/**
* @return the photos entity
*/
public Set<PhotoEntity> getPhotos() {
return photos;
}
/**
* @param photos the photos entity
*/
public void setPhotos(Set<PhotoEntity> photos) {
//Setting Foreign key in child entity because hibernate did it not automatically
if (photos != null) {
for (PhotoEntity photoEntity : photos) {
photoEntity.setUser(this);
}
}
this.photos = photos;
}
/**
* @return the addresses entity
*/
public Set<AddressEntity> getAddresses() {
return addresses;
}
/**
* @param addresses the addresses entity
*/
public void setAddresses(Set<AddressEntity> addresses) {
this.addresses = addresses;
}
/**
* @return the entitlements
*/
public Set<EntitlementsEntity> getEntitlements() {
return entitlements;
}
/**
* @param entitlements the entitlements
*/
public void setEntitlements(Set<EntitlementsEntity> entitlements) {
this.entitlements = entitlements;
}
/**
* @return the roles
*/
public Set<RolesEntity> getRoles() {
return roles;
}
/**
* @param roles the roles
*/
public void setRoles(Set<RolesEntity> roles) {
this.roles = roles;
}
/**
* @return the X509 certs
*/
public Set<X509CertificateEntity> getX509Certificates() {
return x509Certificates;
}
/**
* @param x509Certificates the X509 certs
*/
public void setX509Certificates(Set<X509CertificateEntity> x509Certificates) {
//Setting Foreign key in child entity because hibernate did it not automatically
if (x509Certificates != null) {
for (X509CertificateEntity certificateEntity : x509Certificates) {
certificateEntity.setUser(this);
}
}
this.x509Certificates = x509Certificates;
}
/**
* Registers a new extension for this User. If the given extension is already registered, it will be ignored.
*
* @param extension The extension to register
*/
public void registerExtension(ExtensionEntity extension) {
if (extension == null) {
throw new IllegalArgumentException("extension must not be null");
}
registeredExtensions.add(extension);
}
/**
* Read all registered user extensions.
*
* @return A set of all registered user extensions. Never null;
*/
public Set<ExtensionEntity> getRegisteredExtensions() {
return registeredExtensions;
}
/**
* Adds or updates an extension field value for this User. When updating, the
* old value of the extension field is removed from this user and the new
* one will be added.
*
* @param extensionValue The extension field value to add or update
*/
public void addOrUpdateExtensionValue(ExtensionFieldValueEntity extensionValue) {
if (extensionValue == null) {
throw new IllegalArgumentException("extensionValue must not be null");
}
if (extensionFieldValues.contains(extensionValue)) {
extensionFieldValues.remove(extensionValue);
}
extensionValue.setUser(this);
extensionFieldValues.add(extensionValue);
}
@Override
public String toString() {
return "UserEntity{" +
"UUID='" + getId() + "\', " +
"userName='" + userName + '\'' +
'}';
}
}
|
resource-server/src/main/java/org/osiam/storage/entities/UserEntity.java
|
/*
* Copyright (C) 2013 tarent AG
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.osiam.storage.entities;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
/**
* User Entity
*/
@Entity(name = "scim_user")
@NamedQueries({@NamedQuery(name = "getUserByUsername", query = "SELECT u FROM scim_user u WHERE u.userName = :username")})
public class UserEntity extends ResourceEntity {
private static final String MAPPING_NAME = "user";
@Column(nullable = false, unique = true)
private String userName;
@OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)
private NameEntity name;
@Column
private String nickName;
@Column
private String profileUrl;
@Column
private String title;
@Column
private String userType;
@Column
private String preferredLanguage;
@Column
private String locale;
@Column
private String timezone;
@Column
private Boolean active = Boolean.FALSE;
@Column(nullable = false)
private String password;
@Column
private String displayName;
@OneToMany(mappedBy = MAPPING_NAME, cascade = CascadeType.ALL, orphanRemoval = true)
private Set<EmailEntity> emails = new HashSet<>();
@OneToMany(mappedBy = MAPPING_NAME, cascade = CascadeType.ALL, orphanRemoval = true)
private Set<PhoneNumberEntity> phoneNumbers = new HashSet<>();
@OneToMany(mappedBy = MAPPING_NAME, cascade = CascadeType.ALL, orphanRemoval = true)
private Set<ImEntity> ims = new HashSet<>();
@OneToMany(mappedBy = MAPPING_NAME, cascade = CascadeType.ALL, orphanRemoval = true)
private Set<PhotoEntity> photos = new HashSet<>();
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
private Set<AddressEntity> addresses = new HashSet<>();
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
private Set<EntitlementsEntity> entitlements = new HashSet<>();
@OneToMany(cascade = CascadeType.ALL)
private Set<RolesEntity> roles = new HashSet<>();
@OneToMany(mappedBy = MAPPING_NAME, cascade = CascadeType.ALL, orphanRemoval = true)
private Set<X509CertificateEntity> x509Certificates = new HashSet<>();
@OneToMany
@JoinTable(name = "scim_user_scim_extension", joinColumns = {@JoinColumn(name = "scim_user_internal_id", referencedColumnName = "internal_id")},
inverseJoinColumns = {@JoinColumn(name = "registered_extensions_internal_id", referencedColumnName = "internal_id")})
private Set<ExtensionEntity> registeredExtensions = new HashSet<>();
@OneToMany(mappedBy = MAPPING_NAME, cascade = CascadeType.ALL, orphanRemoval = true)
private Set<ExtensionFieldValueEntity> extensionFieldValues = new HashSet<>();
public UserEntity() {
getMeta().setResourceType("User");
}
/**
* @return the name entity
*/
public NameEntity getName() {
return name;
}
/**
* @param name the name entity
*/
public void setName(NameEntity name) {
this.name = name;
}
/**
* @return the nick name
*/
public String getNickName() {
return nickName;
}
/**
* @param nickName the nick name
*/
public void setNickName(String nickName) {
this.nickName = nickName;
}
/**
* @return the profile url
*/
public String getProfileUrl() {
return profileUrl;
}
/**
* @param profileUrl the profile url
*/
public void setProfileUrl(String profileUrl) {
this.profileUrl = profileUrl;
}
/**
* @return the title
*/
public String getTitle() {
return title;
}
/**
* @param title the title
*/
public void setTitle(String title) {
this.title = title;
}
/**
* @return the user type
*/
public String getUserType() {
return userType;
}
/**
* @param userType the user type
*/
public void setUserType(String userType) {
this.userType = userType;
}
/**
* @return the preferred languages
*/
public String getPreferredLanguage() {
return preferredLanguage;
}
/**
* @param preferredLanguage the preferred languages
*/
public void setPreferredLanguage(String preferredLanguage) {
this.preferredLanguage = preferredLanguage;
}
/**
* @return the locale
*/
public String getLocale() {
return locale;
}
/**
* @param locale the locale
*/
public void setLocale(String locale) {
this.locale = locale;
}
/**
* @return the timezone
*/
public String getTimezone() {
return timezone;
}
/**
* @param timezone the timezone
*/
public void setTimezone(String timezone) {
this.timezone = timezone;
}
/**
* @return the active status
*/
public Boolean getActive() {
return active;
}
/**
* @param active the active status
*/
public void setActive(Boolean active) {
this.active = active;
}
/**
* @return the password
*/
public String getPassword() {
return password;
}
/**
* @param password the password
*/
public void setPassword(String password) {
this.password = password;
}
@Override
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getUserName() {
return userName;
}
/**
* @param userName the user name
*/
public void setUserName(String userName) {
this.userName = userName;
}
/**
* @return the emails entity
*/
public Set<EmailEntity> getEmails() {
return emails;
}
/**
* @param emails the emails entity
*/
public void setEmails(Set<EmailEntity> emails) {
//Setting Foreign key in child entity because hibernate did it not automatically
if (emails != null) {
for (EmailEntity emailEntity : emails) {
emailEntity.setUser(this);
}
}
this.emails = emails;
}
/**
* @return the extensions data of the user
*/
public Set<ExtensionFieldValueEntity> getUserExtensions() {
if (extensionFieldValues == null) {
extensionFieldValues = new HashSet<>();
}
return extensionFieldValues;
}
/**
* @param userExtensions the extension data of the user
*/
public void setUserExtensions(Set<ExtensionFieldValueEntity> userExtensions) {
if (userExtensions != null) {
for (ExtensionFieldValueEntity extensionValue : userExtensions) {
extensionValue.setUser(this);
}
}
this.extensionFieldValues = userExtensions;
}
/**
* @return the phone numbers entity
*/
public Set<PhoneNumberEntity> getPhoneNumbers() {
return phoneNumbers;
}
/**
* @param phoneNumbers the phone numbers entity
*/
public void setPhoneNumbers(Set<PhoneNumberEntity> phoneNumbers) {
//Setting Foreign key in child entity because hibernate did it not automatically
if (phoneNumbers != null) {
for (PhoneNumberEntity phoneNumberEntity : phoneNumbers) {
phoneNumberEntity.setUser(this);
}
}
this.phoneNumbers = phoneNumbers;
}
/**
* @return the instant messaging entity
*/
public Set<ImEntity> getIms() {
return ims;
}
/**
* @param ims the instant messaging entity
*/
public void setIms(Set<ImEntity> ims) {
//Setting Foreign key in child entity because hibernate did it not automatically
if (ims != null) {
for (ImEntity imEntity : ims) {
imEntity.setUser(this);
}
}
this.ims = ims;
}
/**
* @return the photos entity
*/
public Set<PhotoEntity> getPhotos() {
return photos;
}
/**
* @param photos the photos entity
*/
public void setPhotos(Set<PhotoEntity> photos) {
//Setting Foreign key in child entity because hibernate did it not automatically
if (photos != null) {
for (PhotoEntity photoEntity : photos) {
photoEntity.setUser(this);
}
}
this.photos = photos;
}
/**
* @return the addresses entity
*/
public Set<AddressEntity> getAddresses() {
return addresses;
}
/**
* @param addresses the addresses entity
*/
public void setAddresses(Set<AddressEntity> addresses) {
this.addresses = addresses;
}
/**
* @return the entitlements
*/
public Set<EntitlementsEntity> getEntitlements() {
return entitlements;
}
/**
* @param entitlements the entitlements
*/
public void setEntitlements(Set<EntitlementsEntity> entitlements) {
this.entitlements = entitlements;
}
/**
* @return the roles
*/
public Set<RolesEntity> getRoles() {
return roles;
}
/**
* @param roles the roles
*/
public void setRoles(Set<RolesEntity> roles) {
this.roles = roles;
}
/**
* @return the X509 certs
*/
public Set<X509CertificateEntity> getX509Certificates() {
return x509Certificates;
}
/**
* @param x509Certificates the X509 certs
*/
public void setX509Certificates(Set<X509CertificateEntity> x509Certificates) {
//Setting Foreign key in child entity because hibernate did it not automatically
if (x509Certificates != null) {
for (X509CertificateEntity certificateEntity : x509Certificates) {
certificateEntity.setUser(this);
}
}
this.x509Certificates = x509Certificates;
}
/**
* Registers a new extension for this User. If the given extension is already registered, it will be ignored.
*
* @param extension The extension to register
*/
public void registerExtension(ExtensionEntity extension) {
if (extension == null) {
throw new IllegalArgumentException("extension must not be null");
}
registeredExtensions.add(extension);
}
/**
* Read all registered user extensions.
*
* @return A set of all registered user extensions. Never null;
*/
public Set<ExtensionEntity> getRegisteredExtensions() {
return registeredExtensions;
}
/**
* Adds or updates an extension field value for this User. When updating, the
* old value of the extension field is removed from this user and the new
* one will be added.
*
* @param extensionValue The extension field value to add or update
*/
public void addOrUpdateExtensionValue(ExtensionFieldValueEntity extensionValue) {
if (extensionValue == null) {
throw new IllegalArgumentException("extensionValue must not be null");
}
if (extensionFieldValues.contains(extensionValue)) {
extensionFieldValues.remove(extensionValue);
}
extensionValue.setUser(this);
extensionFieldValues.add(extensionValue);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()){
return false;
}
UserEntity that = (UserEntity) o;
return userName.equals(that.userName);
}
@Override
public int hashCode() {
return userName.hashCode();
}
@Override
public String toString() {
return "UserEntity{" +
"UUID='" + getId() + "\', " +
"userName='" + userName + '\'' +
'}';
}
}
|
[fix] removed equals and hashcode as it is implemented in ResourceEntity
|
resource-server/src/main/java/org/osiam/storage/entities/UserEntity.java
|
[fix] removed equals and hashcode as it is implemented in ResourceEntity
|
<ide><path>esource-server/src/main/java/org/osiam/storage/entities/UserEntity.java
<ide> }
<ide>
<ide> @Override
<del> public boolean equals(Object o) {
<del> if (this == o) {
<del> return true;
<del> }
<del> if (o == null || getClass() != o.getClass()){
<del> return false;
<del> }
<del>
<del> UserEntity that = (UserEntity) o;
<del>
<del> return userName.equals(that.userName);
<del>
<del> }
<del>
<del> @Override
<del> public int hashCode() {
<del> return userName.hashCode();
<del> }
<del>
<del> @Override
<ide> public String toString() {
<ide> return "UserEntity{" +
<ide> "UUID='" + getId() + "\', " +
|
|
Java
|
apache-2.0
|
b2417d95982da2ecc2a3ac9760919b959d0a1a4a
| 0 |
dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android
|
/*
* Copyright (C) 2009 University of Washington
*
* 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.odk.collect.android.activities;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.text.InputFilter;
import android.text.Spanned;
import android.util.Log;
import android.util.Pair;
import android.util.TypedValue;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.ContextThemeWrapper;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import org.commcare.android.framework.CommCareActivity;
import org.commcare.android.javarosa.AndroidLogger;
import org.commcare.android.util.FormUploadUtil;
import org.commcare.android.util.SessionUnavailableException;
import org.commcare.android.util.StringUtils;
import org.commcare.dalvik.BuildConfig;
import org.commcare.dalvik.R;
import org.commcare.dalvik.application.CommCareApplication;
import org.commcare.dalvik.activities.CommCareHomeActivity;
import org.commcare.dalvik.odk.provider.FormsProviderAPI.FormsColumns;
import org.commcare.dalvik.odk.provider.InstanceProviderAPI;
import org.commcare.dalvik.odk.provider.InstanceProviderAPI.InstanceColumns;
import org.commcare.dalvik.services.CommCareSessionService;
import org.commcare.dalvik.utils.UriToFilePath;
import org.javarosa.core.model.Constants;
import org.javarosa.core.model.FormIndex;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.services.Logger;
import org.javarosa.core.services.locale.Localization;
import org.javarosa.core.services.locale.Localizer;
import org.javarosa.form.api.FormEntryController;
import org.javarosa.form.api.FormEntryPrompt;
import org.javarosa.model.xform.XFormsModule;
import org.javarosa.xpath.XPathException;
import org.javarosa.xpath.XPathTypeMismatchException;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.jr.extensions.IntentCallout;
import org.odk.collect.android.listeners.AdvanceToNextListener;
import org.odk.collect.android.listeners.FormLoaderListener;
import org.odk.collect.android.listeners.FormSavedListener;
import org.odk.collect.android.listeners.FormSaveCallback;
import org.odk.collect.android.listeners.WidgetChangedListener;
import org.odk.collect.android.logic.FormController;
import org.odk.collect.android.logic.PropertyManager;
import org.odk.collect.android.preferences.PreferencesActivity;
import org.odk.collect.android.preferences.PreferencesActivity.ProgressBarMode;
import org.odk.collect.android.tasks.FormLoaderTask;
import org.odk.collect.android.tasks.SaveToDiskTask;
import org.odk.collect.android.utilities.Base64Wrapper;
import org.odk.collect.android.utilities.FileUtils;
import org.odk.collect.android.utilities.GeoUtils;
import org.odk.collect.android.views.ODKView;
import org.odk.collect.android.views.ResizingImageView;
import org.odk.collect.android.widgets.DateTimeWidget;
import org.odk.collect.android.widgets.IntentWidget;
import org.odk.collect.android.widgets.QuestionWidget;
import org.odk.collect.android.widgets.TimeWidget;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.LinkedList;
import java.util.Set;
import javax.crypto.spec.SecretKeySpec;
/**
* FormEntryActivity is responsible for displaying questions, animating transitions between
* questions, and allowing the user to enter data.
*
* @author Carl Hartung ([email protected])
*/
public class FormEntryActivity extends FragmentActivity implements AnimationListener, FormLoaderListener,
FormSavedListener, FormSaveCallback, AdvanceToNextListener, OnGestureListener,
WidgetChangedListener {
private static final String t = "FormEntryActivity";
// Defines for FormEntryActivity
private static final boolean EXIT = true;
private static final boolean DO_NOT_EXIT = false;
private static final boolean EVALUATE_CONSTRAINTS = true;
private static final boolean DO_NOT_EVALUATE_CONSTRAINTS = false;
// Request codes for returning data from specified intent.
public static final int IMAGE_CAPTURE = 1;
public static final int BARCODE_CAPTURE = 2;
public static final int AUDIO_CAPTURE = 3;
public static final int VIDEO_CAPTURE = 4;
public static final int LOCATION_CAPTURE = 5;
public static final int HIERARCHY_ACTIVITY = 6;
public static final int IMAGE_CHOOSER = 7;
public static final int AUDIO_CHOOSER = 8;
public static final int VIDEO_CHOOSER = 9;
public static final int INTENT_CALLOUT = 10;
public static final int HIERARCHY_ACTIVITY_FIRST_START = 11;
public static final int SIGNATURE_CAPTURE = 12;
// Extra returned from gp activity
public static final String LOCATION_RESULT = "LOCATION_RESULT";
// Identifies the gp of the form used to launch form entry
public static final String KEY_FORMPATH = "formpath";
public static final String KEY_INSTANCEDESTINATION = "instancedestination";
public static final String KEY_INSTANCES = "instances";
public static final String KEY_SUCCESS = "success";
public static final String KEY_ERROR = "error";
public static final String KEY_FORM_CONTENT_URI = "form_content_uri";
public static final String KEY_INSTANCE_CONTENT_URI = "instance_content_uri";
public static final String KEY_AES_STORAGE_KEY = "key_aes_storage";
public static final String KEY_HEADER_STRING = "form_header";
public static final String KEY_INCOMPLETE_ENABLED = "org.odk.collect.form.management";
public static final String KEY_RESIZING_ENABLED = "org.odk.collect.resizing.enabled";
public static final String KEY_HAS_SAVED = "org.odk.collect.form.has.saved";
/**
* Intent extra flag to track if this form is an archive. Used to trigger
* return logic when this activity exits to the home screen, such as
* whether to redirect to archive view or sync the form.
*/
public static final String IS_ARCHIVED_FORM = "is-archive-form";
// Identifies whether this is a new form, or reloading a form after a screen
// rotation (or similar)
private static final String NEWFORM = "newform";
private static final int MENU_LANGUAGES = Menu.FIRST;
private static final int MENU_HIERARCHY_VIEW = Menu.FIRST + 1;
private static final int MENU_SAVE = Menu.FIRST + 2;
private static final int MENU_PREFERENCES = Menu.FIRST + 3;
private static final int PROGRESS_DIALOG = 1;
private static final int SAVING_DIALOG = 2;
private String mFormPath;
// Path to a particular form instance
public static String mInstancePath;
private String mInstanceDestination;
private GestureDetector mGestureDetector;
private SecretKeySpec symetricKey = null;
public static FormController mFormController;
private Animation mInAnimation;
private Animation mOutAnimation;
private ViewGroup mViewPane;
private View mCurrentView;
private AlertDialog mRepeatDialog;
private AlertDialog mAlertDialog;
private ProgressDialog mProgressDialog;
private String mErrorMessage;
private boolean mIncompleteEnabled = true;
// used to limit forward/backward swipes to one per question
private boolean mBeenSwiped;
private FormLoaderTask mFormLoaderTask;
private SaveToDiskTask mSaveToDiskTask;
private Uri formProviderContentURI = FormsColumns.CONTENT_URI;
private Uri instanceProviderContentURI = InstanceColumns.CONTENT_URI;
private static String mHeaderString;
// Was the form saved? Used to set activity return code.
public boolean hasSaved = false;
private BroadcastReceiver mNoGPSReceiver;
// marked true if we are in the process of saving a form because the user
// database & key session are expiring. Being set causes savingComplete to
// broadcast a form saving intent.
private boolean savingFormOnKeySessionExpiration = false;
enum AnimationType {
LEFT, RIGHT, FADE
}
/*
* (non-Javadoc)
* @see android.support.v4.app.FragmentActivity#onCreate(android.os.Bundle)
*/
@Override
@SuppressLint("NewApi")
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
// CommCareSessionService will call this.formSaveCallback when the
// key session is closing down and we need to save any intermediate
// results before they become un-saveable.
CommCareApplication._().getSession().registerFormSaveCallback(this);
} catch (SessionUnavailableException e) {
Logger.log(AndroidLogger.TYPE_ERROR_WORKFLOW,
"Couldn't register form save callback because session doesn't exist");
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
final String fragmentClass = this.getIntent().getStringExtra("odk_title_fragment");
if(fragmentClass != null) {
final FragmentManager fm = this.getSupportFragmentManager();
//Add breadcrumb bar
Fragment bar = (Fragment) fm.findFragmentByTag(TITLE_FRAGMENT_TAG);
// If the state holder is null, create a new one for this activity
if (bar == null) {
try {
bar = ((Class<Fragment>)Class.forName(fragmentClass)).newInstance();
//the bar will set this up for us again if we need.
getActionBar().setDisplayShowCustomEnabled(true);
getActionBar().setDisplayShowTitleEnabled(false);
fm.beginTransaction().add(bar, TITLE_FRAGMENT_TAG).commit();
} catch(Exception e) {
Log.w("odk-collect", "couldn't instantiate fragment: " + fragmentClass);
}
}
}
}
// must be at the beginning of any activity that can be called from an external intent
try {
Collect.createODKDirs();
} catch (RuntimeException e) {
Logger.exception(e);
CommCareActivity.createErrorDialog(this, e.getMessage(), EXIT);
return;
}
setupUI();
// Load JavaRosa modules. needed to restore forms.
new XFormsModule().registerModule();
// needed to override rms property manager
org.javarosa.core.services.PropertyManager.setPropertyManager(new PropertyManager(
getApplicationContext()));
Boolean newForm = true;
if (savedInstanceState != null) {
if (savedInstanceState.containsKey(KEY_FORMPATH)) {
mFormPath = savedInstanceState.getString(KEY_FORMPATH);
}
if (savedInstanceState.containsKey(NEWFORM)) {
newForm = savedInstanceState.getBoolean(NEWFORM, true);
}
if (savedInstanceState.containsKey(KEY_ERROR)) {
mErrorMessage = savedInstanceState.getString(KEY_ERROR);
}
if (savedInstanceState.containsKey(KEY_FORM_CONTENT_URI)) {
formProviderContentURI = Uri.parse(savedInstanceState.getString(KEY_FORM_CONTENT_URI));
}
if (savedInstanceState.containsKey(KEY_INSTANCE_CONTENT_URI)) {
instanceProviderContentURI = Uri.parse(savedInstanceState.getString(KEY_INSTANCE_CONTENT_URI));
}
if (savedInstanceState.containsKey(KEY_INSTANCEDESTINATION)) {
mInstanceDestination = savedInstanceState.getString(KEY_INSTANCEDESTINATION);
}
if(savedInstanceState.containsKey(KEY_INCOMPLETE_ENABLED)) {
mIncompleteEnabled = savedInstanceState.getBoolean(KEY_INCOMPLETE_ENABLED);
}
if(savedInstanceState.containsKey(KEY_RESIZING_ENABLED)) {
ResizingImageView.resizeMethod = savedInstanceState.getString(KEY_RESIZING_ENABLED);
}
if (savedInstanceState.containsKey(KEY_AES_STORAGE_KEY)) {
String base64Key = savedInstanceState.getString(KEY_AES_STORAGE_KEY);
try {
byte[] storageKey = new Base64Wrapper().decode(base64Key);
symetricKey = new SecretKeySpec(storageKey, "AES");
} catch (ClassNotFoundException e) {
throw new RuntimeException("Base64 encoding not available on this platform");
}
}
if(savedInstanceState.containsKey(KEY_HEADER_STRING)) {
mHeaderString = savedInstanceState.getString(KEY_HEADER_STRING);
}
if(savedInstanceState.containsKey(KEY_HAS_SAVED)) {
hasSaved = savedInstanceState.getBoolean(KEY_HAS_SAVED);
}
}
// If a parse error message is showing then nothing else is loaded
// Dialogs mid form just disappear on rotation.
if (mErrorMessage != null) {
CommCareActivity.createErrorDialog(this, mErrorMessage, EXIT);
return;
}
// Check to see if this is a screen flip or a new form load.
Object data = this.getLastCustomNonConfigurationInstance();
if (data instanceof FormLoaderTask) {
mFormLoaderTask = (FormLoaderTask) data;
} else if (data instanceof SaveToDiskTask) {
mSaveToDiskTask = (SaveToDiskTask) data;
} else if (data == null) {
if (!newForm) {
refreshCurrentView();
return;
}
boolean readOnly = false;
// Not a restart from a screen orientation change (or other).
mFormController = null;
mInstancePath = null;
Intent intent = getIntent();
if (intent != null) {
Uri uri = intent.getData();
if(intent.hasExtra(KEY_FORM_CONTENT_URI)) {
this.formProviderContentURI = Uri.parse(intent.getStringExtra(KEY_FORM_CONTENT_URI));
}
if(intent.hasExtra(KEY_INSTANCE_CONTENT_URI)) {
this.instanceProviderContentURI = Uri.parse(intent.getStringExtra(KEY_INSTANCE_CONTENT_URI));
}
if(intent.hasExtra(KEY_INSTANCEDESTINATION)) {
this.mInstanceDestination = intent.getStringExtra(KEY_INSTANCEDESTINATION);
} else {
mInstanceDestination = Collect.INSTANCES_PATH;
}
if(intent.hasExtra(KEY_AES_STORAGE_KEY)) {
String base64Key = intent.getStringExtra(KEY_AES_STORAGE_KEY);
try {
byte[] storageKey = new Base64Wrapper().decode(base64Key);
symetricKey = new SecretKeySpec(storageKey, "AES");
} catch (ClassNotFoundException e) {
throw new RuntimeException("Base64 encoding not available on this platform");
}
}
if(intent.hasExtra(KEY_HEADER_STRING)) {
this.mHeaderString = intent.getStringExtra(KEY_HEADER_STRING);
}
if(intent.hasExtra(KEY_INCOMPLETE_ENABLED)) {
this.mIncompleteEnabled = intent.getBooleanExtra(KEY_INCOMPLETE_ENABLED, true);
}
if(intent.hasExtra(KEY_RESIZING_ENABLED)) {
ResizingImageView.resizeMethod = intent.getStringExtra(KEY_RESIZING_ENABLED);
}
if(mHeaderString != null) {
setTitle(mHeaderString);
} else {
setTitle(StringUtils.getStringRobust(this, R.string.app_name) + " > " + StringUtils.getStringRobust(this, R.string.loading_form));
}
//[email protected] - Jan 24, 2012
//Since these are parceled across the content resolver, there's no guarantee of reference equality.
//We need to manually check value equality on the type
final String contentType = getContentResolver().getType(uri);
Uri formUri = null;
switch (contentType) {
case InstanceColumns.CONTENT_ITEM_TYPE:
Cursor instanceCursor = null;
Cursor formCursor = null;
try {
instanceCursor = getContentResolver().query(uri, null, null, null, null);
if (instanceCursor.getCount() != 1) {
CommCareHomeActivity.createErrorDialog(this, "Bad URI: " + uri, EXIT);
return;
} else {
instanceCursor.moveToFirst();
mInstancePath =
instanceCursor.getString(instanceCursor
.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH));
final String jrFormId =
instanceCursor.getString(instanceCursor
.getColumnIndex(InstanceColumns.JR_FORM_ID));
//If this form is both already completed
if (InstanceProviderAPI.STATUS_COMPLETE.equals(instanceCursor.getString(instanceCursor.getColumnIndex(InstanceColumns.STATUS)))) {
if (!Boolean.parseBoolean(instanceCursor.getString(instanceCursor.getColumnIndex(InstanceColumns.CAN_EDIT_WHEN_COMPLETE)))) {
readOnly = true;
}
}
final String[] selectionArgs = {
jrFormId
};
final String selection = FormsColumns.JR_FORM_ID + " like ?";
formCursor = getContentResolver().query(formProviderContentURI, null, selection, selectionArgs, null);
if (formCursor.getCount() == 1) {
formCursor.moveToFirst();
mFormPath =
formCursor.getString(formCursor
.getColumnIndex(FormsColumns.FORM_FILE_PATH));
formUri = ContentUris.withAppendedId(formProviderContentURI, formCursor.getLong(formCursor.getColumnIndex(FormsColumns._ID)));
} else if (formCursor.getCount() < 1) {
CommCareHomeActivity.createErrorDialog(this, "Parent form does not exist", EXIT);
return;
} else if (formCursor.getCount() > 1) {
CommCareHomeActivity.createErrorDialog(this, "More than one possible parent form", EXIT);
return;
}
}
} finally {
if (instanceCursor != null) {
instanceCursor.close();
}
if (formCursor != null) {
formCursor.close();
}
}
break;
case FormsColumns.CONTENT_ITEM_TYPE:
Cursor c = null;
try {
c = getContentResolver().query(uri, null, null, null, null);
if (c.getCount() != 1) {
CommCareHomeActivity.createErrorDialog(this, "Bad URI: " + uri, EXIT);
return;
} else {
c.moveToFirst();
mFormPath = c.getString(c.getColumnIndex(FormsColumns.FORM_FILE_PATH));
formUri = uri;
}
} finally {
if (c != null) {
c.close();
}
}
break;
default:
Log.e(t, "unrecognized URI");
CommCareHomeActivity.createErrorDialog(this, "unrecognized URI: " + uri, EXIT);
return;
}
if(formUri == null) {
Log.e(t, "unrecognized URI");
CommCareActivity.createErrorDialog(this, "couldn't locate FormDB entry for the item at: " + uri, EXIT);
return;
}
mFormLoaderTask = new FormLoaderTask(this, symetricKey, readOnly);
mFormLoaderTask.execute(formUri);
showDialog(PROGRESS_DIALOG);
}
}
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
/*
* EventLog accepts only proper Strings as input, but prior to this version,
* Android would try to send SpannedStrings to it, thus crashing the app.
* This makes sure the title is actually a String.
* This fixes bug 174626.
*/
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2
&& item.getTitleCondensed() != null) {
if (BuildConfig.DEBUG) {
Log.v(t, "Selected item is: " + item);
}
item.setTitleCondensed(item.getTitleCondensed().toString());
}
return super.onMenuItemSelected(featureId, item);
}
@Override
public void formSaveCallback() {
// note that we have started saving the form
savingFormOnKeySessionExpiration = true;
// start saving form, which will call the key session logout completion
// function when it finishes.
saveDataToDisk(EXIT, false, null, true);
}
/**
* Setup BroadcastReceiver for asking user if they want to enable gps
*/
private void registerFormEntryReceivers() {
// See if this form needs GPS to be turned on
mNoGPSReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
context.removeStickyBroadcast(intent);
LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
Set<String> providers = GeoUtils.evaluateProviders(manager);
if (providers.isEmpty()) {
DialogInterface.OnClickListener onChangeListener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int i) {
if (i == DialogInterface.BUTTON_POSITIVE) {
Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
}
};
GeoUtils.showNoGpsDialog(FormEntryActivity.this, onChangeListener);
}
}
};
registerReceiver(mNoGPSReceiver,
new IntentFilter(GeoUtils.ACTION_CHECK_GPS_ENABLED));
}
/**
* Setup Activity's UI
*/
private void setupUI() {
setContentView(R.layout.screen_form_entry);
setNavBarVisibility();
ImageButton nextButton = (ImageButton)this.findViewById(R.id.nav_btn_next);
ImageButton prevButton = (ImageButton)this.findViewById(R.id.nav_btn_prev);
nextButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (!"done".equals(v.getTag())) {
FormEntryActivity.this.showNextView();
} else {
triggerUserFormComplete();
}
}
});
prevButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (!"quit".equals(v.getTag())) {
FormEntryActivity.this.showPreviousView();
} else {
FormEntryActivity.this.triggerUserQuitInput();
}
}
});
mViewPane = (ViewGroup)findViewById(R.id.form_entry_pane);
mBeenSwiped = false;
mAlertDialog = null;
mCurrentView = null;
mInAnimation = null;
mOutAnimation = null;
mGestureDetector = new GestureDetector(this);
}
public static final String TITLE_FRAGMENT_TAG = "odk_title_fragment";
/*
* (non-Javadoc)
* @see android.support.v4.app.FragmentActivity#onSaveInstanceState(android.os.Bundle)
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(KEY_FORMPATH, mFormPath);
outState.putBoolean(NEWFORM, false);
outState.putString(KEY_ERROR, mErrorMessage);
outState.putString(KEY_FORM_CONTENT_URI, formProviderContentURI.toString());
outState.putString(KEY_INSTANCE_CONTENT_URI, instanceProviderContentURI.toString());
outState.putString(KEY_INSTANCEDESTINATION, mInstanceDestination);
outState.putBoolean(KEY_INCOMPLETE_ENABLED, mIncompleteEnabled);
outState.putBoolean(KEY_HAS_SAVED, hasSaved);
outState.putString(KEY_RESIZING_ENABLED, ResizingImageView.resizeMethod);
if(symetricKey != null) {
try {
outState.putString(KEY_AES_STORAGE_KEY, new Base64Wrapper().encodeToString(symetricKey.getEncoded()));
} catch (ClassNotFoundException e) {
// we can't really get here anyway, since we couldn't have decoded the string to begin with
throw new RuntimeException("Base 64 encoding unavailable! Can't pass storage key");
}
}
}
/*
* (non-Javadoc)
* @see android.support.v4.app.FragmentActivity#onActivityResult(int, int, android.content.Intent)
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == RESULT_CANCELED) {
if(requestCode == HIERARCHY_ACTIVITY_FIRST_START) {
//they pressed 'back' on the first heirarchy screen. we should assume they want to
//back out of form entry all together
finishReturnInstance(false);
} else if(requestCode == INTENT_CALLOUT){
processIntentResponse(intent, true);
}
// request was canceled, so do nothing
return;
}
ContentValues values;
Uri imageURI;
switch (requestCode) {
case BARCODE_CAPTURE:
String sb = intent.getStringExtra("SCAN_RESULT");
((ODKView) mCurrentView).setBinaryData(sb);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
break;
case INTENT_CALLOUT:
processIntentResponse(intent);
break;
case IMAGE_CAPTURE:
case SIGNATURE_CAPTURE:
/*
* We saved the image to the tempfile_path, but we really want it to be in:
* /sdcard/odk/instances/[current instnace]/something.jpg so we move it there before
* inserting it into the content provider. Once the android image capture bug gets
* fixed, (read, we move on from Android 1.6) we want to handle images the audio and
* video
*/
// The intent is empty, but we know we saved the image to the temp file
File fi = new File(Collect.TMPFILE_PATH);
String mInstanceFolder =
mInstancePath.substring(0, mInstancePath.lastIndexOf("/") + 1);
String s = mInstanceFolder + "/" + System.currentTimeMillis() + ".jpg";
File nf = new File(s);
if (!fi.renameTo(nf)) {
Log.e(t, "Failed to rename " + fi.getAbsolutePath());
} else {
Log.i(t, "renamed " + fi.getAbsolutePath() + " to " + nf.getAbsolutePath());
}
// Add the new image to the Media content provider so that the
// viewing is fast in Android 2.0+
values = new ContentValues(6);
values.put(Images.Media.TITLE, nf.getName());
values.put(Images.Media.DISPLAY_NAME, nf.getName());
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/jpeg");
values.put(Images.Media.DATA, nf.getAbsolutePath());
imageURI = getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);
Log.i(t, "Inserting image returned uri = " + imageURI.toString());
((ODKView) mCurrentView).setBinaryData(imageURI);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
refreshCurrentView();
break;
case IMAGE_CHOOSER:
/*
* We have a saved image somewhere, but we really want it to be in:
* /sdcard/odk/instances/[current instnace]/something.jpg so we move it there before
* inserting it into the content provider. Once the android image capture bug gets
* fixed, (read, we move on from Android 1.6) we want to handle images the audio and
* video
*/
// get gp of chosen file
String sourceImagePath = null;
Uri selectedImage = intent.getData();
sourceImagePath = FileUtils.getPath(this, selectedImage);
// Copy file to sdcard
String mInstanceFolder1 =
mInstancePath.substring(0, mInstancePath.lastIndexOf("/") + 1);
String destImagePath = mInstanceFolder1 + "/" + System.currentTimeMillis() + ".jpg";
File source = new File(sourceImagePath);
File newImage = new File(destImagePath);
FileUtils.copyFile(source, newImage);
if (newImage.exists()) {
// Add the new image to the Media content provider so that the
// viewing is fast in Android 2.0+
values = new ContentValues(6);
values.put(Images.Media.TITLE, newImage.getName());
values.put(Images.Media.DISPLAY_NAME, newImage.getName());
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/jpeg");
values.put(Images.Media.DATA, newImage.getAbsolutePath());
imageURI =
getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);
Log.i(t, "Inserting image returned uri = " + imageURI.toString());
((ODKView) mCurrentView).setBinaryData(imageURI);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
} else {
Log.e(t, "NO IMAGE EXISTS at: " + source.getAbsolutePath());
}
refreshCurrentView();
break;
case AUDIO_CAPTURE:
case VIDEO_CAPTURE:
case AUDIO_CHOOSER:
case VIDEO_CHOOSER:
// For audio/video capture/chooser, we get the URI from the content provider
// then the widget copies the file and makes a new entry in the content provider.
Uri media = intent.getData();
String binaryPath = UriToFilePath.getPathFromUri(CommCareApplication._(), media);
if (!FormUploadUtil.isSupportedMultimediaFile(binaryPath)) {
// don't let the user select a file that won't be included in the
// upload to the server
((ODKView) mCurrentView).clearAnswer();
Toast.makeText(FormEntryActivity.this,
StringUtils.getStringSpannableRobust(FormEntryActivity.this, R.string.attachment_invalid),
Toast.LENGTH_LONG).show();
} else {
((ODKView) mCurrentView).setBinaryData(media);
}
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
refreshCurrentView();
break;
case LOCATION_CAPTURE:
String sl = intent.getStringExtra(LOCATION_RESULT);
((ODKView) mCurrentView).setBinaryData(sl);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
break;
case HIERARCHY_ACTIVITY:
// We may have jumped to a new index in hierarchy activity, so refresh
refreshCurrentView(false);
break;
}
}
private void processIntentResponse(Intent response){
processIntentResponse(response, false);
}
private void processIntentResponse(Intent response, boolean cancelled) {
// keep track of whether we should auto advance
boolean advance = false;
boolean quick = false;
//We need to go grab our intent callout object to process the results here
IntentWidget bestMatch = null;
//Ugh, copied from the odkview mostly, that's stupid
for(QuestionWidget q : ((ODKView)mCurrentView).getWidgets()) {
//Figure out if we have a pending intent widget
if (q instanceof IntentWidget) {
if(((IntentWidget) q).isWaitingForBinaryData() || bestMatch == null) {
bestMatch = (IntentWidget)q;
}
}
}
if(bestMatch != null) {
//Set our instance destination for binary data if needed
String destination = mInstancePath.substring(0, mInstancePath.lastIndexOf("/") + 1);
//get the original intent callout
IntentCallout ic = bestMatch.getIntentCallout();
quick = "quick".equals(ic.getAppearance());
//And process it
advance = ic.processResponse(response, (ODKView)mCurrentView, mFormController.getInstance(), new File(destination));
ic.setCancelled(cancelled);
}
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
// auto advance if we got a good result and are in quick mode
if(advance && quick){
showNextView();
}
}
public void updateFormRelevencies(){
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
if(!(mCurrentView instanceof ODKView)){
throw new RuntimeException("Tried to update form relevency not on compound view");
}
ODKView oldODKV = (ODKView)mCurrentView;
FormEntryPrompt[] newValidPrompts = mFormController.getQuestionPrompts();
Set<FormEntryPrompt> used = new HashSet<FormEntryPrompt>();
ArrayList<QuestionWidget> oldWidgets = oldODKV.getWidgets();
ArrayList<Integer> removeList = new ArrayList<Integer>();
for(int i=0;i<oldWidgets.size();i++){
QuestionWidget oldWidget = oldWidgets.get(i);
boolean stillRelevent = false;
for(FormEntryPrompt prompt : newValidPrompts) {
if(prompt.getIndex().equals(oldWidget.getPrompt().getIndex())) {
stillRelevent = true;
used.add(prompt);
}
}
if(!stillRelevent){
removeList.add(Integer.valueOf(i));
}
}
// remove "atomically" to not mess up iterations
oldODKV.removeQuestionsFromIndex(removeList);
//Now go through add add any new prompts that we need
for(int i = 0 ; i < newValidPrompts.length; ++i) {
FormEntryPrompt prompt = newValidPrompts[i];
if(used.contains(prompt)) {
//nothing to do here
continue;
}
oldODKV.addQuestionToIndex(prompt, mFormController.getWidgetFactory(), i);
}
}
private static class NavigationDetails {
public int totalQuestions = 0;
public int completedQuestions = 0;
public boolean relevantBeforeCurrentScreen = false;
public boolean isFirstScreen = false;
public int answeredOnScreen = 0;
public int requiredOnScreen = 0;
public int relevantAfterCurrentScreen = 0;
public FormIndex currentScreenExit = null;
}
private NavigationDetails calculateNavigationStatus() {
NavigationDetails details = new NavigationDetails();
FormIndex userFormIndex = mFormController.getFormIndex();
FormIndex currentFormIndex = FormIndex.createBeginningOfFormIndex();
mFormController.expandRepeats(currentFormIndex);
int event = mFormController.getEvent(currentFormIndex);
try {
// keep track of whether there is a question that exists before the
// current screen
boolean onCurrentScreen = false;
while (event != FormEntryController.EVENT_END_OF_FORM) {
int comparison = currentFormIndex.compareTo(userFormIndex);
if (comparison == 0) {
onCurrentScreen = true;
details.currentScreenExit = mFormController.getNextFormIndex(currentFormIndex, true);
}
if (onCurrentScreen && currentFormIndex.equals(details.currentScreenExit)) {
onCurrentScreen = false;
}
// Figure out if there are any events before this screen (either
// new repeat or relevant questions are valid)
if (event == FormEntryController.EVENT_QUESTION
|| event == FormEntryController.EVENT_PROMPT_NEW_REPEAT) {
// Figure out whether we're on the last screen
if (!details.relevantBeforeCurrentScreen && !details.isFirstScreen) {
// We got to the current screen without finding a
// relevant question,
// I guess we're on the first one.
if (onCurrentScreen
&& !details.relevantBeforeCurrentScreen) {
details.isFirstScreen = true;
} else {
// We're using the built in steps (and they take
// relevancy into account)
// so if there are prompts they have to be relevant
details.relevantBeforeCurrentScreen = true;
}
}
}
if (event == FormEntryController.EVENT_QUESTION) {
FormEntryPrompt[] prompts = mFormController.getQuestionPrompts(currentFormIndex);
if (!onCurrentScreen && details.currentScreenExit != null) {
details.relevantAfterCurrentScreen += prompts.length;
}
details.totalQuestions += prompts.length;
// Current questions are complete only if they're answered.
// Past questions are always complete.
// Future questions are never complete.
if (onCurrentScreen) {
for (FormEntryPrompt prompt : prompts) {
if (this.mCurrentView instanceof ODKView) {
ODKView odkv = (ODKView) this.mCurrentView;
prompt = getOnScreenPrompt(prompt, odkv);
}
boolean isAnswered = prompt.getAnswerValue() != null
|| prompt.getDataType() == Constants.DATATYPE_NULL;
if (prompt.isRequired()) {
details.requiredOnScreen++;
if (isAnswered) {
details.answeredOnScreen++;
}
}
if (isAnswered) {
details.completedQuestions++;
}
}
} else if (comparison < 0) {
// For previous questions, consider all "complete"
details.completedQuestions += prompts.length;
// TODO: This doesn't properly capture state to
// determine whether we will end up out of the form if
// we hit back!
// Need to test _until_ we get a question that is
// relevant, then we can skip the relevancy tests
}
}
else if (event == FormEntryController.EVENT_PROMPT_NEW_REPEAT) {
// If we've already passed the current screen, this repeat
// junction is coming up in the future and we will need to
// know
// about it
if (!onCurrentScreen && details.currentScreenExit != null) {
details.totalQuestions++;
details.relevantAfterCurrentScreen++;
} else {
// Otherwise we already passed it and it no longer
// affects the count
}
}
currentFormIndex = mFormController.getNextFormIndex(currentFormIndex, FormController.STEP_INTO_GROUP, false);
event = mFormController.getEvent(currentFormIndex);
}
} catch (XPathTypeMismatchException e) {
Logger.exception(e);
CommCareActivity.createErrorDialog(this, e.getMessage(), EXIT);
}
// Set form back to correct state
mFormController.jumpToIndex(userFormIndex);
return details;
}
/**
* Update progress bar's max and value, and the various buttons and navigation cues
* associated with navigation
*
* @param view ODKView to update
*/
public void updateNavigationCues(View view) {
updateFloatingLabels(view);
ProgressBarMode mode = PreferencesActivity.getProgressBarMode(this);
setNavBarVisibility();
if(mode == ProgressBarMode.None) { return; }
NavigationDetails details = calculateNavigationStatus();
if(mode == ProgressBarMode.ProgressOnly && view instanceof ODKView) {
((ODKView)view).updateProgressBar(details.completedQuestions, details.totalQuestions);
return;
}
ProgressBar progressBar = (ProgressBar)this.findViewById(R.id.nav_prog_bar);
ImageButton nextButton = (ImageButton)this.findViewById(R.id.nav_btn_next);
ImageButton prevButton = (ImageButton)this.findViewById(R.id.nav_btn_prev);
if(!details.relevantBeforeCurrentScreen) {
prevButton.setImageResource(R.drawable.icon_close_darkwarm);
prevButton.setTag("quit");
} else {
prevButton.setImageResource(R.drawable.icon_chevron_left_brand);
prevButton.setTag("back");
}
//Apparently in Android 2.3 setting the drawable resource for the progress bar
//causes it to lose it bounds. It's a bit cheaper to keep them around than it
//is to invalidate the view, though.
Rect bounds = progressBar.getProgressDrawable().getBounds(); //Save the drawable bound
Log.i("Questions","Total questions: " + details.totalQuestions + " | Completed questions: " + details.completedQuestions);
progressBar.getProgressDrawable().setBounds(bounds); //Set the bounds to the saved value
progressBar.setMax(details.totalQuestions);
if(details.relevantAfterCurrentScreen == 0 && (details.requiredOnScreen == details.answeredOnScreen || details.requiredOnScreen < 1)) {
nextButton.setImageResource(R.drawable.icon_chevron_right_attnpos);
//TODO: _really_? This doesn't seem right
nextButton.setTag("done");
progressBar.setProgressDrawable(this.getResources().getDrawable(R.drawable.progressbar_full));
Log.i("Questions","Form complete");
// if we get here, it means we don't have any more relevant questions after this one, so we mark it as complete
progressBar.setProgress(details.totalQuestions); // completely fills the progressbar
} else {
nextButton.setImageResource(R.drawable.icon_chevron_right_brand);
//TODO: _really_? This doesn't seem right
nextButton.setTag("next");
progressBar.setProgressDrawable(this.getResources().getDrawable(R.drawable.progressbar_modern));
progressBar.setProgress(details.completedQuestions);
}
//We should probably be doing this based on the widgets, maybe, not the model? Hard to call.
updateBadgeInfo(details.requiredOnScreen, details.answeredOnScreen);
}
private void setNavBarVisibility() {
//Make sure the nav bar visibility is set
int navBarVisibility = PreferencesActivity.getProgressBarMode(this).useNavigationBar() ? View.VISIBLE : View.GONE;
View nav = this.findViewById(R.id.nav_pane);
if(nav.getVisibility() != navBarVisibility) {
nav.setVisibility(navBarVisibility);
this.findViewById(R.id.nav_badge_border_drawer).setVisibility(navBarVisibility);
this.findViewById(R.id.nav_badge).setVisibility(navBarVisibility);
}
}
enum FloatingLabel {
good ("floating-good", R.drawable.label_floating_good, R.color.cc_attention_positive_text),
caution ("floating-caution", R.drawable.label_floating_caution, R.color.cc_light_warm_accent_color),
bad ("floating-bad", R.drawable.label_floating_bad, R.color.cc_attention_negative_color);
String label;
int resourceId;
int colorId;
FloatingLabel(String label, int resourceId, int colorId) {
this.label = label;
this.resourceId = resourceId;
this.colorId = colorId;
}
public String getAppearance() { return label;}
public int getBackgroundDrawable() { return resourceId; }
public int getColorId() { return colorId; }
};
private void updateFloatingLabels(View currentView) {
//TODO: this should actually be set up to scale per screen size.
ArrayList<Pair<String, FloatingLabel>> smallLabels = new ArrayList<Pair<String, FloatingLabel>>();
ArrayList<Pair<String, FloatingLabel>> largeLabels = new ArrayList<Pair<String, FloatingLabel>>();
FloatingLabel[] labelTypes = FloatingLabel.values();
if(currentView instanceof ODKView) {
for(QuestionWidget widget : ((ODKView)currentView).getWidgets()) {
String hint = widget.getPrompt().getAppearanceHint();
if(hint == null) { continue; }
for(FloatingLabel type : labelTypes) {
if(type.getAppearance().equals(hint)) {
String widgetText = widget.getPrompt().getQuestionText();
if(widgetText != null && widgetText.length() < 15) {
smallLabels.add(new Pair(widgetText, type));
} else {
largeLabels.add(new Pair(widgetText, type));
}
}
}
}
}
final ViewGroup parent = (ViewGroup)this.findViewById(R.id.form_entry_label_layout);
parent.removeAllViews();
int pixels = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8, getResources().getDisplayMetrics());
int minHeight = 7 * pixels;
//Ok, now go ahead and add all of the small labels
for(int i = 0 ; i < smallLabels.size(); i = i + 2 ) {
if(i + 1 < smallLabels.size()) {
LinearLayout.LayoutParams lpp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
final LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.HORIZONTAL);
layout.setLayoutParams(lpp);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1);
TextView left = (TextView)View.inflate(this, R.layout.component_floating_label, null);
left.setLayoutParams(lp);
left.setText(smallLabels.get(i).first + "; " + smallLabels.get(i + 1).first);
left.setBackgroundResource(smallLabels.get(i).second.resourceId);
left.setPadding(pixels, 2 * pixels, pixels, 2 * pixels);
left.setTextColor(smallLabels.get(i).second.colorId);
left.setMinimumHeight(minHeight);
layout.addView(left);
parent.addView(layout);
} else {
largeLabels.add(smallLabels.get(i));
}
}
for(int i = 0 ; i < largeLabels.size(); ++i ) {
final TextView view = (TextView)View.inflate(this, R.layout.component_floating_label, null);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
view.setLayoutParams(lp);
view.setPadding(pixels, 2 * pixels, pixels, 2 * pixels);
view.setText(largeLabels.get(i).first);
view.setBackgroundResource(largeLabels.get(i).second.resourceId);
view.setTextColor(largeLabels.get(i).second.colorId);
view.setMinimumHeight(minHeight);
parent.addView(view);
}
}
private void updateBadgeInfo(int requiredOnScreen, int answeredOnScreen) {
View badgeBorder = this.findViewById(R.id.nav_badge_border_drawer);
TextView badge = (TextView)this.findViewById(R.id.nav_badge);
//If we don't need this stuff, just bail
if(requiredOnScreen <= 1) {
//Hide all badge related items
badgeBorder.setVisibility(View.INVISIBLE);
badge.setVisibility(View.INVISIBLE);
return;
}
//Otherwise, update badge stuff
badgeBorder.setVisibility(View.VISIBLE);
badge.setVisibility(View.VISIBLE);
if(requiredOnScreen - answeredOnScreen == 0) {
//Unicode checkmark
badge.setText("\u2713");
badge.setBackgroundResource(R.drawable.badge_background_complete);
} else {
badge.setBackgroundResource(R.drawable.badge_background);
badge.setText(String.valueOf(requiredOnScreen - answeredOnScreen));
}
}
/**
* Takes in a form entry prompt that is obtained generically and if there
* is already one on screen (which, for isntance, may have cached some of its data)
* returns the object in use currently.
*
* @param prompt
* @return
*/
private FormEntryPrompt getOnScreenPrompt(FormEntryPrompt prompt, ODKView view) {
FormIndex index = prompt.getIndex();
for(QuestionWidget widget : view.getWidgets()) {
if(widget.getFormId().equals(index)) {
return widget.getPrompt();
}
}
return prompt;
}
/**
* Refreshes the current view. the controller and the displayed view can get out of sync due to
* dialogs and restarts caused by screen orientation changes, so they're resynchronized here.
*/
public void refreshCurrentView() {
refreshCurrentView(true);
}
/**
* Refreshes the current view. the controller and the displayed view can get out of sync due to
* dialogs and restarts caused by screen orientation changes, so they're resynchronized here.
*/
public void refreshCurrentView(boolean animateLastView) {
if(mFormController == null) { throw new RuntimeException("Form state is lost! Cannot refresh current view. This shouldn't happen, please submit a bug report."); }
int event = mFormController.getEvent();
// When we refresh, repeat dialog state isn't maintained, so step back to the previous
// question.
// Also, if we're within a group labeled 'field list', step back to the beginning of that
// group.
// That is, skip backwards over repeat prompts, groups that are not field-lists,
// repeat events, and indexes in field-lists that is not the containing group.
while (event == FormEntryController.EVENT_PROMPT_NEW_REPEAT
|| (event == FormEntryController.EVENT_GROUP && !mFormController.indexIsInFieldList())
|| event == FormEntryController.EVENT_REPEAT
|| (mFormController.indexIsInFieldList() && !(event == FormEntryController.EVENT_GROUP))) {
event = mFormController.stepToPreviousEvent();
}
//If we're at the beginning of form event, but don't show the screen for that, we need
//to get the next valid screen
if(event == FormEntryController.EVENT_BEGINNING_OF_FORM && !PreferencesActivity.showFirstScreen(this)) {
this.showNextView(true);
} else {
View current = createView(event);
showView(current, AnimationType.FADE, animateLastView);
}
}
/*
* (non-Javadoc)
* @see android.app.Activity#onPrepareOptionsMenu(android.view.Menu)
*/
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.removeItem(MENU_LANGUAGES);
menu.removeItem(MENU_HIERARCHY_VIEW);
menu.removeItem(MENU_SAVE);
menu.removeItem(MENU_PREFERENCES);
if(mIncompleteEnabled) {
menu.add(0, MENU_SAVE, 0, StringUtils.getStringRobust(this, R.string.save_all_answers)).setIcon(
android.R.drawable.ic_menu_save);
}
menu.add(0, MENU_HIERARCHY_VIEW, 0, StringUtils.getStringRobust(this, R.string.view_hierarchy)).setIcon(
R.drawable.ic_menu_goto);
menu.add(0, MENU_LANGUAGES, 0, StringUtils.getStringRobust(this, R.string.change_language))
.setIcon(R.drawable.ic_menu_start_conversation)
.setEnabled(
(mFormController == null || mFormController.getLanguages() == null || mFormController.getLanguages().length == 1) ? false
: true);
menu.add(0, MENU_PREFERENCES, 0, StringUtils.getStringRobust(this, R.string.general_preferences)).setIcon(
android.R.drawable.ic_menu_preferences);
return true;
}
/*
* (non-Javadoc)
* @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_LANGUAGES:
createLanguageDialog();
return true;
case MENU_SAVE:
// don't exit
saveDataToDisk(DO_NOT_EXIT, isInstanceComplete(false), null, false);
return true;
case MENU_HIERARCHY_VIEW:
if (currentPromptIsQuestion()) {
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
}
Intent i = new Intent(this, FormHierarchyActivity.class);
startActivityForResult(i, HIERARCHY_ACTIVITY);
return true;
case MENU_PREFERENCES:
Intent pref = new Intent(this, PreferencesActivity.class);
startActivity(pref);
return true;
case android.R.id.home:
triggerUserQuitInput();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* @return true If the current index of the form controller contains questions
*/
private boolean currentPromptIsQuestion() {
return (mFormController.getEvent() == FormEntryController.EVENT_QUESTION || mFormController
.getEvent() == FormEntryController.EVENT_GROUP);
}
private boolean saveAnswersForCurrentScreen(boolean evaluateConstraints) {
return saveAnswersForCurrentScreen(evaluateConstraints, true, false);
}
/**
* Attempt to save the answer(s) in the current screen to into the data model.
*
* @param evaluateConstraints
* @param failOnRequired Whether or not the constraint evaluation
* should return false if the question is only
* required. (this is helpful for incomplete
* saves)
* @param headless running in a process that can't display graphics
* @return false if any error occurs while saving (constraint violated,
* etc...), true otherwise.
*/
private boolean saveAnswersForCurrentScreen(boolean evaluateConstraints,
boolean failOnRequired,
boolean headless) {
// only try to save if the current event is a question or a field-list
// group
boolean success = true;
if ((mFormController.getEvent() == FormEntryController.EVENT_QUESTION)
|| ((mFormController.getEvent() == FormEntryController.EVENT_GROUP) &&
mFormController.indexIsInFieldList())) {
if (mCurrentView instanceof ODKView) {
HashMap<FormIndex, IAnswerData> answers =
((ODKView)mCurrentView).getAnswers();
// Sort the answers so if there are multiple errors, we can
// bring focus to the first one
List<FormIndex> indexKeys = new ArrayList<FormIndex>();
indexKeys.addAll(answers.keySet());
Collections.sort(indexKeys, new Comparator<FormIndex>() {
@Override
public int compare(FormIndex arg0, FormIndex arg1) {
return arg0.compareTo(arg1);
}
});
for (FormIndex index : indexKeys) {
// Within a group, you can only save for question events
if (mFormController.getEvent(index) == FormEntryController.EVENT_QUESTION) {
int saveStatus = saveAnswer(answers.get(index),
index, evaluateConstraints);
if (evaluateConstraints &&
((saveStatus != FormEntryController.ANSWER_OK) &&
(failOnRequired ||
saveStatus != FormEntryController.ANSWER_REQUIRED_BUT_EMPTY))) {
if (!headless) {
createConstraintToast(index, mFormController.getQuestionPrompt(index).getConstraintText(), saveStatus, success);
}
success = false;
}
} else {
Log.w(t,
"Attempted to save an index referencing something other than a question: "
+ index.getReference());
}
}
} else {
String viewType;
if (mCurrentView == null || mCurrentView.getClass() == null) {
viewType = "null";
} else {
viewType = mCurrentView.getClass().toString();
}
Log.w(t, "Unknown view type rendered while current event was question or group! View type: " + viewType);
}
}
return success;
}
/**
* Clears the answer on the screen.
*/
private void clearAnswer(QuestionWidget qw) {
qw.clearAnswer();
}
/*
* (non-Javadoc)
* @see android.app.Activity#onCreateContextMenu(android.view.ContextMenu, android.view.View, android.view.ContextMenu.ContextMenuInfo)
*/
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, v.getId(), 0, StringUtils.getStringSpannableRobust(this, R.string.clear_answer));
menu.setHeaderTitle(StringUtils.getStringSpannableRobust(this, R.string.edit_prompt));
}
/*
* (non-Javadoc)
* @see android.app.Activity#onContextItemSelected(android.view.MenuItem)
*/
@Override
public boolean onContextItemSelected(MenuItem item) {
// We don't have the right view here, so we store the View's ID as the
// item ID and loop through the possible views to find the one the user
// clicked on.
for (QuestionWidget qw : ((ODKView) mCurrentView).getWidgets()) {
if (item.getItemId() == qw.getId()) {
createClearDialog(qw);
}
}
return super.onContextItemSelected(item);
}
/*
* (non-Javadoc)
* @see android.support.v4.app.FragmentActivity#onRetainCustomNonConfigurationInstance()
*
* If we're loading, then we pass the loading thread to our next instance.
*/
@Override
public Object onRetainCustomNonConfigurationInstance() {
// if a form is loading, pass the loader task
if (mFormLoaderTask != null && mFormLoaderTask.getStatus() != AsyncTask.Status.FINISHED)
return mFormLoaderTask;
// if a form is writing to disk, pass the save to disk task
if (mSaveToDiskTask != null && mSaveToDiskTask.getStatus() != AsyncTask.Status.FINISHED)
return mSaveToDiskTask;
// mFormEntryController is static so we don't need to pass it.
if (mFormController != null && currentPromptIsQuestion()) {
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
}
return null;
}
private String getHeaderString() {
if(mHeaderString != null) {
//Localization?
return mHeaderString;
} else {
return StringUtils.getStringRobust(this, R.string.app_name) + " > " + mFormController.getFormTitle();
}
}
/**
* Creates a view given the View type and an event
*
* @param event
* @return newly created View
*/
private View createView(int event) {
boolean isGroup = false;
setTitle(getHeaderString());
switch (event) {
case FormEntryController.EVENT_BEGINNING_OF_FORM:
View startView = View.inflate(this, R.layout.form_entry_start, null);
setTitle(getHeaderString());
((TextView) startView.findViewById(R.id.description)).setText(StringUtils.getStringSpannableRobust(this, R.string.enter_data_description, mFormController.getFormTitle()));
((CheckBox) startView.findViewById(R.id.screen_form_entry_start_cbx_dismiss)).setText(StringUtils.getStringSpannableRobust(this, R.string.form_entry_start_hide));
((TextView) startView.findViewById(R.id.screen_form_entry_advance_text)).setText(StringUtils.getStringSpannableRobust(this, R.string.advance));
((TextView) startView.findViewById(R.id.screen_form_entry_backup_text)).setText(StringUtils.getStringSpannableRobust(this, R.string.backup));
Drawable image = null;
String[] projection = {
FormsColumns.FORM_MEDIA_PATH
};
String selection = FormsColumns.FORM_FILE_PATH + "=?";
String[] selectionArgs = {
mFormPath
};
Cursor c = null;
String mediaDir = null;
try {
c = getContentResolver().query(formProviderContentURI, projection, selection, selectionArgs, null);
if (c.getCount() < 1) {
CommCareActivity.createErrorDialog(this, "Form doesn't exist", EXIT);
return new View(this);
} else {
c.moveToFirst();
mediaDir = c.getString(c.getColumnIndex(FormsColumns.FORM_MEDIA_PATH));
}
} finally {
if (c != null) {
c.close();
}
}
BitmapDrawable bitImage = null;
// attempt to load the form-specific logo...
// this is arbitrarily silly
bitImage = new BitmapDrawable(mediaDir + "/form_logo.png");
if (bitImage != null && bitImage.getBitmap() != null
&& bitImage.getIntrinsicHeight() > 0 && bitImage.getIntrinsicWidth() > 0) {
image = bitImage;
}
if (image == null) {
// show the opendatakit zig...
// image = getResources().getDrawable(R.drawable.opendatakit_zig);
((ImageView) startView.findViewById(R.id.form_start_bling))
.setVisibility(View.GONE);
} else {
((ImageView) startView.findViewById(R.id.form_start_bling))
.setImageDrawable(image);
}
return startView;
case FormEntryController.EVENT_END_OF_FORM:
View endView = View.inflate(this, R.layout.form_entry_end, null);
((TextView) endView.findViewById(R.id.description)).setText(StringUtils.getStringSpannableRobust(this, R.string.save_enter_data_description,
mFormController.getFormTitle()));
// checkbox for if finished or ready to send
final CheckBox instanceComplete = ((CheckBox) endView.findViewById(R.id.mark_finished));
instanceComplete.setText(StringUtils.getStringSpannableRobust(this, R.string.mark_finished));
//If incomplete is not enabled, make sure this box is checked.
instanceComplete.setChecked(!mIncompleteEnabled || isInstanceComplete(true));
if(mFormController.isFormReadOnly() || !mIncompleteEnabled) {
instanceComplete.setVisibility(View.GONE);
}
// edittext to change the displayed name of the instance
final EditText saveAs = (EditText) endView.findViewById(R.id.save_name);
//TODO: Figure this out based on the content provider or some part of the context
saveAs.setVisibility(View.GONE);
endView.findViewById(R.id.save_form_as).setVisibility(View.GONE);
// disallow carriage returns in the name
InputFilter returnFilter = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
for (int i = start; i < end; i++) {
if (Character.getType((source.charAt(i))) == Character.CONTROL) {
return "";
}
}
return null;
}
};
saveAs.setFilters(new InputFilter[] {
returnFilter
});
String saveName = getDefaultFormTitle();
saveAs.setText(saveName);
// Create 'save' button
Button button = (Button) endView.findViewById(R.id.save_exit_button);
if(mFormController.isFormReadOnly()) {
button.setText(StringUtils.getStringSpannableRobust(this, R.string.exit));
button.setOnClickListener(new OnClickListener() {
/*
* (non-Javadoc)
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
@Override
public void onClick(View v) {
finishReturnInstance();
}
});
} else {
button.setText(StringUtils.getStringSpannableRobust(this, R.string.quit_entry));
button.setOnClickListener(new OnClickListener() {
/*
* (non-Javadoc)
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
@Override
public void onClick(View v) {
// Form is marked as 'saved' here.
if (saveAs.getText().length() < 1) {
Toast.makeText(FormEntryActivity.this, StringUtils.getStringSpannableRobust(FormEntryActivity.this, R.string.save_as_error),
Toast.LENGTH_SHORT).show();
} else {
saveDataToDisk(EXIT,
instanceComplete.isChecked(),
saveAs.getText().toString(),
false);
}
}
});
}
return endView;
case FormEntryController.EVENT_GROUP:
isGroup = true;
case FormEntryController.EVENT_QUESTION:
ODKView odkv = null;
// should only be a group here if the event_group is a field-list
try {
odkv =
new ODKView(this, mFormController.getQuestionPrompts(),
mFormController.getGroupsForCurrentIndex(),
mFormController.getWidgetFactory(), this, isGroup);
Log.i(t, "created view for group");
} catch (RuntimeException e) {
Logger.exception(e);
CommCareActivity.createErrorDialog(this, e.getMessage(), EXIT);
// this is badness to avoid a crash.
// really a next view should increment the formcontroller, create the view
// if the view is null, then keep the current view and pop an error.
return new View(this);
}
// Makes a "clear answer" menu pop up on long-click of
// select-one/select-multiple questions
for (QuestionWidget qw : odkv.getWidgets()) {
if (!qw.getPrompt().isReadOnly() &&
!mFormController.isFormReadOnly() &&
(qw.getPrompt().getControlType() == Constants.CONTROL_SELECT_ONE ||
qw.getPrompt().getControlType() == Constants.CONTROL_SELECT_MULTI)) {
registerForContextMenu(qw);
}
}
updateNavigationCues(odkv);
return odkv;
default:
Log.e(t, "Attempted to create a view that does not exist.");
return null;
}
}
/*
* (non-Javadoc)
* @see android.app.Activity#dispatchTouchEvent(android.view.MotionEvent)
*/
@SuppressLint("NewApi")
@Override
public boolean dispatchTouchEvent(MotionEvent mv) {
//We need to ignore this even if it's processed by the action
//bar (if one exists)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
View customView = getActionBar().getCustomView();
if(customView != null) {
if(customView.dispatchTouchEvent(mv)) {
return true;
}
}
}
boolean handled = mGestureDetector.onTouchEvent(mv);
if (!handled) {
return super.dispatchTouchEvent(mv);
}
return handled; // this is always true
}
/**
* Determines what should be displayed on the screen. Possible options are: a question, an ask
* repeat dialog, or the submit screen. Also saves answers to the data model after checking
* constraints.
*/
private void showNextView() { showNextView(false); }
private void showNextView(boolean resuming) {
if(!resuming && mFormController.getEvent() == FormEntryController.EVENT_BEGINNING_OF_FORM) {
//See if we should stop displaying the start screen
CheckBox stopShowingIntroScreen = (CheckBox)mCurrentView.findViewById(R.id.screen_form_entry_start_cbx_dismiss);
//Not sure why it would, but maybe timing issues?
if(stopShowingIntroScreen != null) {
if(stopShowingIntroScreen.isChecked()) {
//set it!
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
sharedPreferences.edit().putBoolean(PreferencesActivity.KEY_SHOW_START_SCREEN, false).commit();
}
}
}
if (currentPromptIsQuestion()) {
if (!saveAnswersForCurrentScreen(EVALUATE_CONSTRAINTS)) {
// A constraint was violated so a dialog should be showing.
return;
}
}
if (mFormController.getEvent() != FormEntryController.EVENT_END_OF_FORM) {
int event;
try{
group_skip: do {
event = mFormController.stepToNextEvent(FormController.STEP_OVER_GROUP);
switch (event) {
case FormEntryController.EVENT_QUESTION:
case FormEntryController.EVENT_END_OF_FORM:
View next = createView(event);
if(!resuming) {
showView(next, AnimationType.RIGHT);
} else {
showView(next, AnimationType.FADE, false);
}
break group_skip;
case FormEntryController.EVENT_PROMPT_NEW_REPEAT:
createRepeatDialog();
break group_skip;
case FormEntryController.EVENT_GROUP:
//We only hit this event if we're at the _opening_ of a field
//list, so it seems totally fine to do it this way, technically
//though this should test whether the index is the field list
//host.
if (mFormController.indexIsInFieldList()
&& mFormController.getQuestionPrompts().length != 0) {
View nextGroupView = createView(event);
if(!resuming) {
showView(nextGroupView, AnimationType.RIGHT);
} else {
showView(nextGroupView, AnimationType.FADE, false);
}
break group_skip;
}
// otherwise it's not a field-list group, so just skip it
break;
case FormEntryController.EVENT_REPEAT:
Log.i(t, "repeat: " + mFormController.getFormIndex().getReference());
// skip repeats
break;
case FormEntryController.EVENT_REPEAT_JUNCTURE:
Log.i(t, "repeat juncture: "
+ mFormController.getFormIndex().getReference());
// skip repeat junctures until we implement them
break;
default:
Log.w(t,
"JavaRosa added a new EVENT type and didn't tell us... shame on them.");
break;
}
} while (event != FormEntryController.EVENT_END_OF_FORM);
}catch(XPathTypeMismatchException e){
Logger.exception(e);
CommCareActivity.createErrorDialog(this, e.getMessage(), EXIT);
}
} else {
mBeenSwiped = false;
}
}
/**
* Determines what should be displayed between a question, or the start screen and displays the
* appropriate view. Also saves answers to the data model without checking constraints.
*/
private void showPreviousView() {
// The answer is saved on a back swipe, but question constraints are ignored.
if (currentPromptIsQuestion()) {
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
}
FormIndex startIndex = mFormController.getFormIndex();
FormIndex lastValidIndex = startIndex;
if (mFormController.getEvent() != FormEntryController.EVENT_BEGINNING_OF_FORM) {
int event = mFormController.stepToPreviousEvent();
//Step backwards until we either find a question, the beginning of the form,
//or a field list with valid questions inside
while (event != FormEntryController.EVENT_BEGINNING_OF_FORM
&& event != FormEntryController.EVENT_QUESTION
&& !(event == FormEntryController.EVENT_GROUP
&& mFormController.indexIsInFieldList() && mFormController
.getQuestionPrompts().length != 0)) {
event = mFormController.stepToPreviousEvent();
lastValidIndex = mFormController.getFormIndex();
}
//check if we're at the beginning and not doing the whole "First screen" thing
if(event == FormEntryController.EVENT_BEGINNING_OF_FORM && !PreferencesActivity.showFirstScreen(this)) {
//If so, we can't go all the way back here, so we've gotta hit the last index that was valid
mFormController.jumpToIndex(lastValidIndex);
//Did we jump at all? (not sure how we could have, but there might be a mismatch)
if(lastValidIndex.equals(startIndex)) {
//If not, don't even bother changing the view.
//NOTE: This needs to be the same as the
//exit condition below, in case either changes
mBeenSwiped = false;
FormEntryActivity.this.triggerUserQuitInput();
return;
}
//We might have walked all the way back still, which isn't great,
//so keep moving forward again until we find it
if(lastValidIndex.isBeginningOfFormIndex()) {
//there must be a repeat between where we started and the beginning of hte form, walk back up to it
this.showNextView(true);
return;
}
}
View next = createView(event);
showView(next, AnimationType.LEFT);
} else {
//NOTE: this needs to match the exist condition above
//when there is no start screen
mBeenSwiped = false;
FormEntryActivity.this.triggerUserQuitInput();
}
}
/**
* Displays the View specified by the parameter 'next', animating both the current view and next
* appropriately given the AnimationType. Also updates the progress bar.
*/
public void showView(View next, AnimationType from) { showView(next, from, true); }
public void showView(View next, AnimationType from, boolean animateLastView) {
switch (from) {
case RIGHT:
mInAnimation = AnimationUtils.loadAnimation(this, R.anim.push_left_in);
mOutAnimation = AnimationUtils.loadAnimation(this, R.anim.push_left_out);
break;
case LEFT:
mInAnimation = AnimationUtils.loadAnimation(this, R.anim.push_right_in);
mOutAnimation = AnimationUtils.loadAnimation(this, R.anim.push_right_out);
break;
case FADE:
mInAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_in);
mOutAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_out);
break;
}
if (mCurrentView != null) {
if(animateLastView) {
mCurrentView.startAnimation(mOutAnimation);
}
mViewPane.removeView(mCurrentView);
}
mInAnimation.setAnimationListener(this);
RelativeLayout.LayoutParams lp =
new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
mCurrentView = next;
mViewPane.addView(mCurrentView, lp);
mCurrentView.startAnimation(mInAnimation);
if (mCurrentView instanceof ODKView) {
((ODKView) mCurrentView).setFocus(this);
FrameLayout header = (FrameLayout)mCurrentView.findViewById(R.id.form_entry_header);
TextView groupLabel = ((TextView)header.findViewById(R.id.form_entry_group_label));
header.setVisibility(View.GONE);
groupLabel.setVisibility(View.GONE);
String groupLabelText = ((ODKView) mCurrentView).getGroupLabel();
if(!"".equals(groupLabelText)) {
groupLabel.setText(groupLabelText);
header.setVisibility(View.VISIBLE);
groupLabel.setVisibility(View.VISIBLE);
}
} else {
InputMethodManager inputManager =
(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(mCurrentView.getWindowToken(), 0);
}
}
// Hopefully someday we can use managed dialogs when the bugs are fixed
/*
* Ideally, we'd like to use Android to manage dialogs with onCreateDialog() and
* onPrepareDialog(), but dialogs with dynamic content are broken in 1.5 (cupcake). We do use
* managed dialogs for our static loading ProgressDialog. The main issue we noticed and are
* waiting to see fixed is: onPrepareDialog() is not called after a screen orientation change.
* http://code.google.com/p/android/issues/detail?id=1639
*/
//
/**
* Creates and displays a dialog displaying the violated constraint.
*/
private void createConstraintToast(FormIndex index, String constraintText, int saveStatus, boolean requestFocus) {
switch (saveStatus) {
case FormEntryController.ANSWER_CONSTRAINT_VIOLATED:
if (constraintText == null) {
constraintText = StringUtils.getStringRobust(this, R.string.invalid_answer_error);
}
break;
case FormEntryController.ANSWER_REQUIRED_BUT_EMPTY:
constraintText = StringUtils.getStringRobust(this, R.string.required_answer_error);
break;
}
boolean displayed = false;
//We need to see if question in violation is on the screen, so we can show this cleanly.
for(QuestionWidget q : ((ODKView)mCurrentView).getWidgets()) {
if(index.equals(q.getFormId())) {
q.notifyInvalid(constraintText, requestFocus);
displayed = true;
break;
}
}
if(!displayed) {
showCustomToast(constraintText, Toast.LENGTH_SHORT);
}
mBeenSwiped = false;
}
/**
* Creates a toast with the specified message.
*
* @param message
*/
private void showCustomToast(String message, int duration) {
LayoutInflater inflater =
(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.toast_view, null);
// set the text in the view
TextView tv = (TextView) view.findViewById(R.id.message);
tv.setText(message);
Toast t = new Toast(this);
t.setView(view);
t.setDuration(duration);
t.setGravity(Gravity.CENTER, 0, 0);
t.show();
}
/**
* Creates and displays a dialog asking the user if they'd like to create a repeat of the
* current group.
*/
private void createRepeatDialog() {
ContextThemeWrapper wrapper = new ContextThemeWrapper(this, R.style.DialogBaseTheme);
View view = LayoutInflater.from(wrapper).inflate(R.layout.component_repeat_new_dialog, null);
mRepeatDialog = new AlertDialog.Builder(wrapper).create();
final AlertDialog theDialog = mRepeatDialog;
mRepeatDialog.setView(view);
mRepeatDialog.setIcon(android.R.drawable.ic_dialog_info);
boolean hasNavBar = PreferencesActivity.getProgressBarMode(this).useNavigationBar();
//this is super gross...
NavigationDetails details = null;
if(hasNavBar) {
details = calculateNavigationStatus();
}
final boolean backExitsForm = hasNavBar && !details.relevantBeforeCurrentScreen;
final boolean nextExitsForm = hasNavBar && details.relevantAfterCurrentScreen == 0;
Button back = (Button)view.findViewById(R.id.component_repeat_back);
back.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(backExitsForm) {
FormEntryActivity.this.triggerUserQuitInput();
} else {
theDialog.dismiss();
FormEntryActivity.this.refreshCurrentView(false);
}
}
});
Button newButton = (Button)view.findViewById(R.id.component_repeat_new);
newButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
theDialog.dismiss();
try {
mFormController.newRepeat();
} catch (XPathTypeMismatchException e) {
Logger.exception(e);
CommCareActivity.createErrorDialog(FormEntryActivity.this, e.getMessage(), EXIT);
return;
}
showNextView();
}
});
Button skip = (Button)view.findViewById(R.id.component_repeat_skip);
skip.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
theDialog.dismiss();
if(!nextExitsForm) {
showNextView();
} else {
triggerUserFormComplete();
}
}
});
back.setText(StringUtils.getStringSpannableRobust(this, R.string.repeat_go_back));
//Load up our icons
Drawable exitIcon = getResources().getDrawable(R.drawable.icon_exit);
exitIcon.setBounds(0, 0, exitIcon.getIntrinsicWidth(), exitIcon.getIntrinsicHeight());
Drawable doneIcon = getResources().getDrawable(R.drawable.icon_done);
doneIcon.setBounds(0, 0, doneIcon.getIntrinsicWidth(), doneIcon.getIntrinsicHeight());
if (mFormController.getLastRepeatCount() > 0) {
mRepeatDialog.setTitle(StringUtils.getStringRobust(this, R.string.leaving_repeat_ask));
mRepeatDialog.setMessage(StringUtils.getStringSpannableRobust(this, R.string.add_another_repeat,
mFormController.getLastGroupText()));
newButton.setText(StringUtils.getStringSpannableRobust(this, R.string.add_another));
if(!nextExitsForm) {
skip.setText(StringUtils.getStringSpannableRobust(this, R.string.leave_repeat_yes));
} else {
skip.setText(StringUtils.getStringSpannableRobust(this, R.string.leave_repeat_yes_exits));
}
} else {
mRepeatDialog.setTitle(StringUtils.getStringRobust(this, R.string.entering_repeat_ask));
mRepeatDialog.setMessage(StringUtils.getStringSpannableRobust(this, R.string.add_repeat,
mFormController.getLastGroupText()));
newButton.setText(StringUtils.getStringSpannableRobust(this, R.string.entering_repeat));
if(!nextExitsForm) {
skip.setText(StringUtils.getStringSpannableRobust(this, R.string.add_repeat_no));
} else {
skip.setText(StringUtils.getStringSpannableRobust(this, R.string.add_repeat_no_exits));
}
}
mRepeatDialog.setCancelable(false);
mRepeatDialog.show();
if(nextExitsForm) {
skip.setCompoundDrawables(null, doneIcon, null, null);
}
if(backExitsForm) {
back.setCompoundDrawables(null, exitIcon, null, null);
}
mBeenSwiped = false;
}
/**
* Saves form data to disk.
*
* @param exit If set, will exit program after save.
* @param complete Has the user marked the instances as complete?
* @param updatedSaveName Set name of the instance's content provider, if
* non-null
* @param headless Disables GUI warnings and lets answers that
* violate constraints be saved.
* @return Did the data save successfully?
*/
private void saveDataToDisk(boolean exit, boolean complete, String updatedSaveName, boolean headless) {
if (!formHasLoaded()) {
return;
}
// save current answer; if headless, don't evaluate the constraints
// before doing so.
if (headless &&
(!saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS, complete, headless))) {
return;
} else if (!headless &&
!saveAnswersForCurrentScreen(EVALUATE_CONSTRAINTS, complete, headless)) {
Toast.makeText(this,
StringUtils.getStringSpannableRobust(this, R.string.data_saved_error),
Toast.LENGTH_SHORT).show();
return;
}
// If a save task is already running, just let it do its thing
if ((mSaveToDiskTask != null) &&
(mSaveToDiskTask.getStatus() != AsyncTask.Status.FINISHED)) {
return;
}
mSaveToDiskTask =
new SaveToDiskTask(getIntent().getData(), exit, complete, updatedSaveName, this, instanceProviderContentURI, symetricKey, headless);
mSaveToDiskTask.setFormSavedListener(this);
mSaveToDiskTask.execute();
if (!headless) {
showDialog(SAVING_DIALOG);
}
}
/**
* Create a dialog with options to save and exit, save, or quit without saving
*/
private void createQuitDialog() {
final String[] items = mIncompleteEnabled ?
new String[] {StringUtils.getStringRobust(this, R.string.keep_changes), StringUtils.getStringRobust(this, R.string.do_not_save)} :
new String[] {StringUtils.getStringRobust(this, R.string.do_not_save)};
mAlertDialog =
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_info)
.setTitle(StringUtils.getStringRobust(this, R.string.quit_application, mFormController.getFormTitle()))
.setNeutralButton(StringUtils.getStringSpannableRobust(this, R.string.do_not_exit),
new DialogInterface.OnClickListener() {
/*
* (non-Javadoc)
* @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int)
*/
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}).setItems(items, new DialogInterface.OnClickListener() {
/*
* (non-Javadoc)
* @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int)
*/
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0: // save and exit
if(items.length == 1) {
discardChangesAndExit();
} else {
saveDataToDisk(EXIT, isInstanceComplete(false), null, false);
}
break;
case 1: // discard changes and exit
discardChangesAndExit();
break;
case 2:// do nothing
break;
}
}
}).create();
mAlertDialog.getListView().setSelector(R.drawable.selector);
mAlertDialog.show();
}
private void discardChangesAndExit() {
String selection =
InstanceColumns.INSTANCE_FILE_PATH + " like '"
+ mInstancePath + "'";
Cursor c = null;
int instanceCount = 0;
try {
c = getContentResolver().query(instanceProviderContentURI, null, selection, null, null);
instanceCount = c.getCount();
} finally {
if (c != null) {
c.close();
}
}
// if it's not already saved, erase everything
if (instanceCount < 1) {
int images = 0;
int audio = 0;
int video = 0;
// delete media first
String instanceFolder =
mInstancePath.substring(0,
mInstancePath.lastIndexOf("/") + 1);
Log.i(t, "attempting to delete: " + instanceFolder);
String where =
Images.Media.DATA + " like '" + instanceFolder + "%'";
String[] projection = {
Images.ImageColumns._ID
};
// images
Cursor imageCursor = null;
try {
imageCursor = getContentResolver().query(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, where, null, null);
if (imageCursor.getCount() > 0) {
imageCursor.moveToFirst();
String id =
imageCursor.getString(imageCursor
.getColumnIndex(Images.ImageColumns._ID));
Log.i(
t,
"attempting to delete: "
+ Uri.withAppendedPath(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
id));
images =
getContentResolver()
.delete(
Uri.withAppendedPath(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
id), null, null);
}
} finally {
if ( imageCursor != null ) {
imageCursor.close();
}
}
// audio
Cursor audioCursor = null;
try {
audioCursor = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
projection, where, null, null);
if (audioCursor.getCount() > 0) {
audioCursor.moveToFirst();
String id =
audioCursor.getString(imageCursor
.getColumnIndex(Images.ImageColumns._ID));
Log.i(
t,
"attempting to delete: "
+ Uri.withAppendedPath(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
id));
audio =
getContentResolver()
.delete(
Uri.withAppendedPath(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
id), null, null);
}
} finally {
if ( audioCursor != null ) {
audioCursor.close();
}
}
// video
Cursor videoCursor = null;
try {
videoCursor = getContentResolver().query(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
projection, where, null, null);
if (videoCursor.getCount() > 0) {
videoCursor.moveToFirst();
String id =
videoCursor.getString(imageCursor
.getColumnIndex(Images.ImageColumns._ID));
Log.i(
t,
"attempting to delete: "
+ Uri.withAppendedPath(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
id));
video =
getContentResolver()
.delete(
Uri.withAppendedPath(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
id), null, null);
}
} finally {
if ( videoCursor != null ) {
videoCursor.close();
}
}
Log.i(t, "removed from content providers: " + images
+ " image files, " + audio + " audio files,"
+ " and " + video + " video files.");
File f = new File(instanceFolder);
if (f.exists() && f.isDirectory()) {
for (File del : f.listFiles()) {
Log.i(t, "deleting file: " + del.getAbsolutePath());
del.delete();
}
f.delete();
}
}
finishReturnInstance(false);
}
/**
* Confirm clear answer dialog
*/
private void createClearDialog(final QuestionWidget qw) {
mAlertDialog = new AlertDialog.Builder(this).create();
mAlertDialog.setIcon(android.R.drawable.ic_dialog_info);
mAlertDialog.setTitle(StringUtils.getStringRobust(this, R.string.clear_answer_ask));
String question = qw.getPrompt().getLongText();
if (question.length() > 50) {
question = question.substring(0, 50) + "...";
}
mAlertDialog.setMessage(StringUtils.getStringSpannableRobust(this, R.string.clearanswer_confirm, question));
DialogInterface.OnClickListener quitListener = new DialogInterface.OnClickListener() {
/*
* (non-Javadoc)
* @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int)
*/
@Override
public void onClick(DialogInterface dialog, int i) {
switch (i) {
case DialogInterface.BUTTON1: // yes
clearAnswer(qw);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
break;
case DialogInterface.BUTTON2: // no
break;
}
}
};
mAlertDialog.setCancelable(false);
mAlertDialog.setButton(StringUtils.getStringSpannableRobust(this, R.string.discard_answer), quitListener);
mAlertDialog.setButton2(StringUtils.getStringSpannableRobust(this, R.string.clear_answer_no), quitListener);
mAlertDialog.show();
}
/**
* Creates and displays a dialog allowing the user to set the language for the form.
*/
private void createLanguageDialog() {
final String[] languages = mFormController.getLanguages();
int selected = -1;
if (languages != null) {
String language = mFormController.getLanguage();
for (int i = 0; i < languages.length; i++) {
if (language.equals(languages[i])) {
selected = i;
}
}
}
mAlertDialog =
new AlertDialog.Builder(this)
.setSingleChoiceItems(languages, selected,
new DialogInterface.OnClickListener() {
/*
* (non-Javadoc)
* @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int)
*/
@Override
public void onClick(DialogInterface dialog, int whichButton) {
// Update the language in the content provider when selecting a new
// language
ContentValues values = new ContentValues();
values.put(FormsColumns.LANGUAGE, languages[whichButton]);
String selection = FormsColumns.FORM_FILE_PATH + "=?";
String selectArgs[] = {
mFormPath
};
int updated =
getContentResolver().update(formProviderContentURI, values,
selection, selectArgs);
Log.i(t, "Updated language to: " + languages[whichButton] + " in "
+ updated + " rows");
mFormController.setLanguage(languages[whichButton]);
dialog.dismiss();
if (currentPromptIsQuestion()) {
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
}
refreshCurrentView();
}
})
.setTitle(StringUtils.getStringRobust(this, R.string.change_language))
.setNegativeButton(StringUtils.getStringSpannableRobust(this, R.string.do_not_change),
new DialogInterface.OnClickListener() {
/*
* (non-Javadoc)
* @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int)
*/
@Override
public void onClick(DialogInterface dialog, int whichButton) {
}
}).create();
mAlertDialog.show();
}
/*
* (non-Javadoc)
* @see android.app.Activity#onCreateDialog(int)
*
* We use Android's dialog management for loading/saving progress dialogs
*/
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case PROGRESS_DIALOG:
mProgressDialog = new ProgressDialog(this);
DialogInterface.OnClickListener loadingButtonListener =
new DialogInterface.OnClickListener() {
/*
* (non-Javadoc)
* @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int)
*/
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mFormLoaderTask.setFormLoaderListener(null);
mFormLoaderTask.cancel(true);
finish();
}
};
mProgressDialog.setIcon(android.R.drawable.ic_dialog_info);
mProgressDialog.setTitle(StringUtils.getStringRobust(this, R.string.loading_form));
mProgressDialog.setMessage(StringUtils.getStringSpannableRobust(this, R.string.please_wait));
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.setButton(StringUtils.getStringSpannableRobust(this, R.string.cancel_loading_form),
loadingButtonListener);
return mProgressDialog;
case SAVING_DIALOG:
mProgressDialog = new ProgressDialog(this);
DialogInterface.OnClickListener savingButtonListener =
new DialogInterface.OnClickListener() {
/*
* (non-Javadoc)
* @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int)
*/
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mSaveToDiskTask.setFormSavedListener(null);
mSaveToDiskTask.cancel(true);
}
};
mProgressDialog.setIcon(android.R.drawable.ic_dialog_info);
mProgressDialog.setTitle(StringUtils.getStringRobust(this, R.string.saving_form));
mProgressDialog.setMessage(StringUtils.getStringSpannableRobust(this, R.string.please_wait));
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.setButton(StringUtils.getStringSpannableRobust(this, R.string.cancel), savingButtonListener);
mProgressDialog.setButton(StringUtils.getStringSpannableRobust(this, R.string.cancel_saving_form),
savingButtonListener);
return mProgressDialog;
}
return null;
}
/**
* Dismiss any showing dialogs that we manually manage.
*/
private void dismissDialogs() {
if (mAlertDialog != null && mAlertDialog.isShowing()) {
mAlertDialog.dismiss();
}
if(mRepeatDialog != null && mRepeatDialog.isShowing()) {
mRepeatDialog.dismiss();
}
}
/*
* (non-Javadoc)
* @see android.support.v4.app.FragmentActivity#onPause()
*/
@Override
protected void onPause() {
super.onPause();
dismissDialogs();
if (mCurrentView != null && currentPromptIsQuestion()) {
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
}
if (mNoGPSReceiver != null) {
unregisterReceiver(mNoGPSReceiver);
}
}
/*
* (non-Javadoc)
* @see android.support.v4.app.FragmentActivity#onResume()
*/
@Override
protected void onResume() {
super.onResume();
registerFormEntryReceivers();
if (mFormLoaderTask != null) {
mFormLoaderTask.setFormLoaderListener(this);
if (mFormController != null && mFormLoaderTask.getStatus() == AsyncTask.Status.FINISHED) {
dismissDialog(PROGRESS_DIALOG);
refreshCurrentView();
}
}
if (mSaveToDiskTask != null) {
mSaveToDiskTask.setFormSavedListener(this);
}
if (mErrorMessage != null && (mAlertDialog != null && !mAlertDialog.isShowing())) {
CommCareActivity.createErrorDialog(this, mErrorMessage, EXIT);
return;
}
//[email protected] - 22/08/2012 - For release only, fix immediately.
//There is a _horribly obnoxious_ bug in TimePickers that messes up how they work
//on screen rotation. We need to re-do any setAnswers that we perform on them after
//onResume.
try {
if(mCurrentView instanceof ODKView) {
ODKView ov = ((ODKView) mCurrentView);
if(ov.getWidgets() != null) {
for(QuestionWidget qw : ov.getWidgets()) {
if(qw instanceof DateTimeWidget) {
((DateTimeWidget)qw).setAnswer();
} else if(qw instanceof TimeWidget) {
((TimeWidget)qw).setAnswer();
}
}
}
}
} catch(Exception e) {
//if this fails, we _really_ don't want to mess anything up. this is a last minute
//fix
}
}
/**
* Call when the user provides input that they want to quit the form
*/
private void triggerUserQuitInput() {
//If we're just reviewing a read only form, don't worry about saving
//or what not, just quit
if(mFormController.isFormReadOnly()) {
//It's possible we just want to "finish" here, but
//I don't really wanna break any c compatibility
finishReturnInstance(false);
} else {
createQuitDialog();
}
}
/**
* Get the default title for ODK's "Form title" field
*
* @return
*/
private String getDefaultFormTitle() {
String saveName = mFormController.getFormTitle();
if (getContentResolver().getType(getIntent().getData()) == InstanceColumns.CONTENT_ITEM_TYPE) {
Uri instanceUri = getIntent().getData();
Cursor instance = null;
try {
instance = getContentResolver().query(instanceUri, null, null, null, null);
if (instance.getCount() == 1) {
instance.moveToFirst();
saveName =
instance.getString(instance
.getColumnIndex(InstanceColumns.DISPLAY_NAME));
}
} finally {
if (instance != null) {
instance.close();
}
}
}
return saveName;
}
/**
* Call when the user is ready to save and return the current form as complete
*/
private void triggerUserFormComplete() {
saveDataToDisk(EXIT, true, getDefaultFormTitle(), false);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
triggerUserQuitInput();
return true;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (event.isAltPressed() && !mBeenSwiped) {
mBeenSwiped = true;
showNextView();
return true;
}
break;
case KeyEvent.KEYCODE_DPAD_LEFT:
if (event.isAltPressed() && !mBeenSwiped) {
mBeenSwiped = true;
showPreviousView();
return true;
}
break;
}
return super.onKeyDown(keyCode, event);
}
/*
* (non-Javadoc)
* @see android.support.v4.app.FragmentActivity#onDestroy()
*/
@Override
protected void onDestroy() {
if (mFormLoaderTask != null) {
mFormLoaderTask.setFormLoaderListener(null);
// We have to call cancel to terminate the thread, otherwise it
// lives on and retains the FEC in memory.
// but only if it's done, otherwise the thread never returns
if (mFormLoaderTask.getStatus() == AsyncTask.Status.FINISHED) {
mFormLoaderTask.cancel(true);
mFormLoaderTask.destroy();
}
}
if (mSaveToDiskTask != null) {
mSaveToDiskTask.setFormSavedListener(null);
// We have to call cancel to terminate the thread, otherwise it
// lives on and retains the FEC in memory.
if (mSaveToDiskTask.getStatus() == AsyncTask.Status.FINISHED) {
mSaveToDiskTask.cancel(false);
}
}
super.onDestroy();
}
/*
* (non-Javadoc)
* @see android.view.animation.Animation.AnimationListener#onAnimationEnd(android.view.animation.Animation)
*/
@Override
public void onAnimationEnd(Animation arg0) {
mBeenSwiped = false;
}
/*
* (non-Javadoc)
* @see android.view.animation.Animation.AnimationListener#onAnimationRepeat(android.view.animation.Animation)
*/
@Override
public void onAnimationRepeat(Animation animation) {
// Added by AnimationListener interface.
}
/*
* (non-Javadoc)
* @see android.view.animation.Animation.AnimationListener#onAnimationStart(android.view.animation.Animation)
*/
@Override
public void onAnimationStart(Animation animation) {
// Added by AnimationListener interface.
}
/*
* (non-Javadoc)
* @see org.odk.collect.android.listeners.FormLoaderListener#loadingComplete(org.odk.collect.android.logic.FormController)
*
* loadingComplete() is called by FormLoaderTask once it has finished loading a form.
*/
@SuppressLint("NewApi")
@Override
public void loadingComplete(FormController fc) {
dismissDialog(PROGRESS_DIALOG);
mFormController = fc;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
// Newer menus may have already built the menu, before all data was ready
invalidateOptionsMenu();
}
Localizer mLocalizer = Localization.getGlobalLocalizerAdvanced();
if(mLocalizer != null){
String mLocale = mLocalizer.getLocale();
if (mLocale != null && fc.getLanguages() != null && Arrays.asList(fc.getLanguages()).contains(mLocale)){
fc.setLanguage(mLocale);
}
else{
Logger.log("formloader", "The current locale is not set");
}
} else{
Logger.log("formloader", "Could not get the localizer");
}
// Set saved answer path
if (mInstancePath == null) {
// Create new answer folder.
String time =
new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss")
.format(Calendar.getInstance().getTime());
String file =
mFormPath.substring(mFormPath.lastIndexOf('/') + 1, mFormPath.lastIndexOf('.'));
String path = mInstanceDestination + "/" + file + "_" + time;
if (FileUtils.createFolder(path)) {
mInstancePath = path + "/" + file + "_" + time + ".xml";
}
} else {
// we've just loaded a saved form, so start in the hierarchy view
Intent i = new Intent(this, FormHierarchyActivity.class);
startActivityForResult(i, HIERARCHY_ACTIVITY_FIRST_START);
return; // so we don't show the intro screen before jumping to the hierarchy
}
//mFormController.setLanguage(mFormController.getLanguage());
/* here was code that loaded cached language preferences fin the
* collect code. we've overridden that to use our language
* from the shared preferences
*/
refreshCurrentView();
updateNavigationCues(this.mCurrentView);
}
/*
* (non-Javadoc)
* @see org.odk.collect.android.listeners.FormLoaderListener#loadingError(java.lang.String)
*
* called by the FormLoaderTask if something goes wrong.
*/
@Override
public void loadingError(String errorMsg) {
dismissDialog(PROGRESS_DIALOG);
if (errorMsg != null) {
CommCareActivity.createErrorDialog(this, errorMsg, EXIT);
} else {
CommCareActivity.createErrorDialog(this, StringUtils.getStringRobust(this, R.string.parse_error), EXIT);
}
}
/**
* {@inheritDoc}
*
* Display save status notification and exit or continue on in the form.
* If form entry is being saved because key session is expiring then
* continue closing the session/logging out.
*
* @see org.odk.collect.android.listeners.FormSavedListener#savingComplete(int, boolean)
*/
@Override
public void savingComplete(int saveStatus, boolean headless) {
if (!headless) {
dismissDialog(SAVING_DIALOG);
}
// Did we just save a form because the key session
// (CommCareSessionService) is ending?
if (savingFormOnKeySessionExpiration) {
savingFormOnKeySessionExpiration = false;
// Notify the key session that the form state has been saved (or at
// least attempted to be saved) so CommCareSessionService can
// continue closing down key pool and user database.
try {
CommCareApplication._().getSession().closeSession(true);
} catch (SessionUnavailableException sue) {
// form saving took too long, so we logged out already.
Logger.log(AndroidLogger.TYPE_ERROR_WORKFLOW,
"Saving current form took too long, " +
"so data was (probably) discarded and the session closed. " +
"Save exit code: " + saveStatus);
}
} else {
switch (saveStatus) {
case SaveToDiskTask.SAVED:
Toast.makeText(this, StringUtils.getStringSpannableRobust(this, R.string.data_saved_ok), Toast.LENGTH_SHORT).show();
hasSaved = true;
break;
case SaveToDiskTask.SAVED_AND_EXIT:
Toast.makeText(this, StringUtils.getStringSpannableRobust(this, R.string.data_saved_ok), Toast.LENGTH_SHORT).show();
hasSaved = true;
finishReturnInstance();
break;
case SaveToDiskTask.SAVE_ERROR:
Toast.makeText(this, StringUtils.getStringSpannableRobust(this, R.string.data_saved_error), Toast.LENGTH_LONG).show();
break;
case FormEntryController.ANSWER_CONSTRAINT_VIOLATED:
case FormEntryController.ANSWER_REQUIRED_BUT_EMPTY:
refreshCurrentView();
// an answer constraint was violated, so do a 'swipe' to the next
// question to display the proper toast(s)
next();
break;
}
}
}
/**
* Attempts to save an answer to the specified index.
*
* @param answer
* @param index
* @param evaluateConstraints Should form contraints be checked when saving answer?
* @return status as determined in FormEntryController
*/
public int saveAnswer(IAnswerData answer, FormIndex index, boolean evaluateConstraints) {
try {
if (evaluateConstraints) {
return mFormController.answerQuestion(index, answer);
} else {
mFormController.saveAnswer(index, answer);
return FormEntryController.ANSWER_OK;
}
} catch(XPathException e) {
//this is where runtime exceptions get triggered after the form has loaded
CommCareActivity.createErrorDialog(this, "There is a bug in one of your form's XPath Expressions \n" + e.getMessage(), EXIT);
//We're exiting anyway
return FormEntryController.ANSWER_OK;
}
}
/**
* Checks the database to determine if the current instance being edited has already been
* 'marked completed'. A form can be 'unmarked' complete and then resaved.
*
* @return true if form has been marked completed, false otherwise.
*/
private boolean isInstanceComplete(boolean end) {
// default to false if we're mid form
boolean complete = false;
// if we're at the end of the form, then check the preferences
if (end) {
// First get the value from the preferences
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(this);
complete =
sharedPreferences.getBoolean(PreferencesActivity.KEY_COMPLETED_DEFAULT, true);
}
// Then see if we've already marked this form as complete before
String selection = InstanceColumns.INSTANCE_FILE_PATH + "=?";
String[] selectionArgs = {
mInstancePath
};
Cursor c = null;
try {
c = getContentResolver().query(instanceProviderContentURI, null, selection, selectionArgs, null);
if (c != null && c.getCount() > 0) {
c.moveToFirst();
String status = c.getString(c.getColumnIndex(InstanceColumns.STATUS));
if (InstanceProviderAPI.STATUS_COMPLETE.compareTo(status) == 0) {
complete = true;
}
}
} finally {
if (c != null) {
c.close();
}
}
return complete;
}
public void next() {
if (!mBeenSwiped) {
mBeenSwiped = true;
showNextView();
}
}
private void finishReturnInstance() {
finishReturnInstance(true);
}
/**
* Returns the instance that was just filled out to the calling activity,
* if requested.
*
* @param reportSaved was a form saved? Delegates the result code of the
* activity
*/
private void finishReturnInstance(boolean reportSaved) {
String action = getIntent().getAction();
if (Intent.ACTION_PICK.equals(action) || Intent.ACTION_EDIT.equals(action)) {
// caller is waiting on a picked form
String selection = InstanceColumns.INSTANCE_FILE_PATH + "=?";
String[] selectionArgs = {
mInstancePath
};
Cursor c = null;
try {
c = getContentResolver().query(instanceProviderContentURI, null, selection, selectionArgs, null);
if (c.getCount() > 0) {
// should only be one...
c.moveToFirst();
String id = c.getString(c.getColumnIndex(InstanceColumns._ID));
Uri instance = Uri.withAppendedPath(instanceProviderContentURI, id);
Intent formReturnIntent = new Intent();
formReturnIntent.putExtra(IS_ARCHIVED_FORM, mFormController.isFormReadOnly());
if (reportSaved || hasSaved) {
setResult(RESULT_OK, formReturnIntent.setData(instance));
} else {
setResult(RESULT_CANCELED, formReturnIntent.setData(instance));
}
}
} finally {
if (c != null) {
c.close();
}
}
}
try {
CommCareApplication._().getSession().unregisterFormSaveCallback();
} catch (SessionUnavailableException sue) {
// looks like the session expired
}
this.dismissDialogs();
finish();
}
/*
* (non-Javadoc)
* @see android.view.GestureDetector.OnGestureListener#onDown(android.view.MotionEvent)
*/
@Override
public boolean onDown(MotionEvent e) {
return false;
}
/*
* Looks for user swipes. If the user has swiped, move to the appropriate screen.
* (non-Javadoc)
* @see android.view.GestureDetector.OnGestureListener#onFling(android.view.MotionEvent, android.view.MotionEvent, float, float)
*/
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if (CommCareActivity.isHorizontalSwipe(this, e1, e2)) {
mBeenSwiped = true;
if (velocityX > 0) {
showPreviousView();
} else {
int event = mFormController.getEvent(mFormController.getNextFormIndex(mFormController.getFormIndex(), true));
boolean navBar = PreferencesActivity.getProgressBarMode(this).useNavigationBar();
if(!navBar || (navBar && event != FormEntryController.EVENT_END_OF_FORM)) {
showNextView();
}
}
return true;
}
return false;
}
/*
* (non-Javadoc)
* @see android.view.GestureDetector.OnGestureListener#onLongPress(android.view.MotionEvent)
*/
@Override
public void onLongPress(MotionEvent e) {
}
/*
* (non-Javadoc)
* @see android.view.GestureDetector.OnGestureListener#onScroll(android.view.MotionEvent, android.view.MotionEvent, float, float)
*/
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
// The onFling() captures the 'up' event so our view thinks it gets long pressed.
// We don't wnat that, so cancel it.
mCurrentView.cancelLongPress();
return false;
}
/*
* (non-Javadoc)
* @see android.view.GestureDetector.OnGestureListener#onShowPress(android.view.MotionEvent)
*/
@Override
public void onShowPress(MotionEvent e) {
}
/*
* (non-Javadoc)
* @see android.view.GestureDetector.OnGestureListener#onSingleTapUp(android.view.MotionEvent)
*/
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
/*
* (non-Javadoc)
* @see org.odk.collect.android.listeners.AdvanceToNextListener#advance()
*/
@Override
public void advance() {
next();
}
/*
* (non-Javadoc)
* @see org.odk.collect.android.listeners.WidgetChangedListener#widgetEntryChanged()
*/
@Override
public void widgetEntryChanged() {
updateFormRelevencies();
updateNavigationCues(this.mCurrentView);
}
/**
* Has form loading (via FormLoaderTask) completed?
*/
private boolean formHasLoaded() {
return mFormController != null;
}
}
|
app/src/org/odk/collect/android/activities/FormEntryActivity.java
|
/*
* Copyright (C) 2009 University of Washington
*
* 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.odk.collect.android.activities;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.text.InputFilter;
import android.text.Spanned;
import android.util.Log;
import android.util.Pair;
import android.util.TypedValue;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.ContextThemeWrapper;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import org.commcare.android.framework.CommCareActivity;
import org.commcare.android.javarosa.AndroidLogger;
import org.commcare.android.util.FormUploadUtil;
import org.commcare.android.util.SessionUnavailableException;
import org.commcare.android.util.StringUtils;
import org.commcare.dalvik.BuildConfig;
import org.commcare.dalvik.R;
import org.commcare.dalvik.application.CommCareApplication;
import org.commcare.dalvik.activities.CommCareHomeActivity;
import org.commcare.dalvik.odk.provider.FormsProviderAPI.FormsColumns;
import org.commcare.dalvik.odk.provider.InstanceProviderAPI;
import org.commcare.dalvik.odk.provider.InstanceProviderAPI.InstanceColumns;
import org.commcare.dalvik.services.CommCareSessionService;
import org.commcare.dalvik.utils.UriToFilePath;
import org.javarosa.core.model.Constants;
import org.javarosa.core.model.FormIndex;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.services.Logger;
import org.javarosa.core.services.locale.Localization;
import org.javarosa.core.services.locale.Localizer;
import org.javarosa.form.api.FormEntryController;
import org.javarosa.form.api.FormEntryPrompt;
import org.javarosa.model.xform.XFormsModule;
import org.javarosa.xpath.XPathException;
import org.javarosa.xpath.XPathTypeMismatchException;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.jr.extensions.IntentCallout;
import org.odk.collect.android.listeners.AdvanceToNextListener;
import org.odk.collect.android.listeners.FormLoaderListener;
import org.odk.collect.android.listeners.FormSavedListener;
import org.odk.collect.android.listeners.FormSaveCallback;
import org.odk.collect.android.listeners.WidgetChangedListener;
import org.odk.collect.android.logic.FormController;
import org.odk.collect.android.logic.PropertyManager;
import org.odk.collect.android.preferences.PreferencesActivity;
import org.odk.collect.android.preferences.PreferencesActivity.ProgressBarMode;
import org.odk.collect.android.tasks.FormLoaderTask;
import org.odk.collect.android.tasks.SaveToDiskTask;
import org.odk.collect.android.utilities.Base64Wrapper;
import org.odk.collect.android.utilities.FileUtils;
import org.odk.collect.android.utilities.GeoUtils;
import org.odk.collect.android.views.ODKView;
import org.odk.collect.android.views.ResizingImageView;
import org.odk.collect.android.widgets.DateTimeWidget;
import org.odk.collect.android.widgets.IntentWidget;
import org.odk.collect.android.widgets.QuestionWidget;
import org.odk.collect.android.widgets.TimeWidget;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.LinkedList;
import java.util.Set;
import javax.crypto.spec.SecretKeySpec;
/**
* FormEntryActivity is responsible for displaying questions, animating transitions between
* questions, and allowing the user to enter data.
*
* @author Carl Hartung ([email protected])
*/
public class FormEntryActivity extends FragmentActivity implements AnimationListener, FormLoaderListener,
FormSavedListener, FormSaveCallback, AdvanceToNextListener, OnGestureListener,
WidgetChangedListener {
private static final String t = "FormEntryActivity";
// Defines for FormEntryActivity
private static final boolean EXIT = true;
private static final boolean DO_NOT_EXIT = false;
private static final boolean EVALUATE_CONSTRAINTS = true;
private static final boolean DO_NOT_EVALUATE_CONSTRAINTS = false;
// Request codes for returning data from specified intent.
public static final int IMAGE_CAPTURE = 1;
public static final int BARCODE_CAPTURE = 2;
public static final int AUDIO_CAPTURE = 3;
public static final int VIDEO_CAPTURE = 4;
public static final int LOCATION_CAPTURE = 5;
public static final int HIERARCHY_ACTIVITY = 6;
public static final int IMAGE_CHOOSER = 7;
public static final int AUDIO_CHOOSER = 8;
public static final int VIDEO_CHOOSER = 9;
public static final int INTENT_CALLOUT = 10;
public static final int HIERARCHY_ACTIVITY_FIRST_START = 11;
public static final int SIGNATURE_CAPTURE = 12;
// Extra returned from gp activity
public static final String LOCATION_RESULT = "LOCATION_RESULT";
// Identifies the gp of the form used to launch form entry
public static final String KEY_FORMPATH = "formpath";
public static final String KEY_INSTANCEDESTINATION = "instancedestination";
public static final String KEY_INSTANCES = "instances";
public static final String KEY_SUCCESS = "success";
public static final String KEY_ERROR = "error";
public static final String KEY_FORM_CONTENT_URI = "form_content_uri";
public static final String KEY_INSTANCE_CONTENT_URI = "instance_content_uri";
public static final String KEY_AES_STORAGE_KEY = "key_aes_storage";
public static final String KEY_HEADER_STRING = "form_header";
public static final String KEY_INCOMPLETE_ENABLED = "org.odk.collect.form.management";
public static final String KEY_RESIZING_ENABLED = "org.odk.collect.resizing.enabled";
public static final String KEY_HAS_SAVED = "org.odk.collect.form.has.saved";
/**
* Intent extra flag to track if this form is an archive. Used to trigger
* return logic when this activity exits to the home screen, such as
* whether to redirect to archive view or sync the form.
*/
public static final String IS_ARCHIVED_FORM = "is-archive-form";
// Identifies whether this is a new form, or reloading a form after a screen
// rotation (or similar)
private static final String NEWFORM = "newform";
private static final int MENU_LANGUAGES = Menu.FIRST;
private static final int MENU_HIERARCHY_VIEW = Menu.FIRST + 1;
private static final int MENU_SAVE = Menu.FIRST + 2;
private static final int MENU_PREFERENCES = Menu.FIRST + 3;
private static final int PROGRESS_DIALOG = 1;
private static final int SAVING_DIALOG = 2;
private String mFormPath;
// Path to a particular form instance
public static String mInstancePath;
private String mInstanceDestination;
private GestureDetector mGestureDetector;
private SecretKeySpec symetricKey = null;
public static FormController mFormController;
private Animation mInAnimation;
private Animation mOutAnimation;
private ViewGroup mViewPane;
private View mCurrentView;
private AlertDialog mRepeatDialog;
private AlertDialog mAlertDialog;
private ProgressDialog mProgressDialog;
private String mErrorMessage;
private boolean mIncompleteEnabled = true;
// used to limit forward/backward swipes to one per question
private boolean mBeenSwiped;
private FormLoaderTask mFormLoaderTask;
private SaveToDiskTask mSaveToDiskTask;
private Uri formProviderContentURI = FormsColumns.CONTENT_URI;
private Uri instanceProviderContentURI = InstanceColumns.CONTENT_URI;
private static String mHeaderString;
// Was the form saved? Used to set activity return code.
public boolean hasSaved = false;
private BroadcastReceiver mNoGPSReceiver;
// marked true if we are in the process of saving a form because the user
// database & key session are expiring. Being set causes savingComplete to
// broadcast a form saving intent.
private boolean savingFormOnKeySessionExpiration = false;
enum AnimationType {
LEFT, RIGHT, FADE
}
/*
* (non-Javadoc)
* @see android.support.v4.app.FragmentActivity#onCreate(android.os.Bundle)
*/
@Override
@SuppressLint("NewApi")
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
// CommCareSessionService will call this.formSaveCallback when the
// key session is closing down and we need to save any intermediate
// results before they become un-saveable.
CommCareApplication._().getSession().registerFormSaveCallback(this);
} catch (SessionUnavailableException e) {
Logger.log(AndroidLogger.TYPE_ERROR_WORKFLOW,
"Couldn't register form save callback because session doesn't exist");
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
final String fragmentClass = this.getIntent().getStringExtra("odk_title_fragment");
if(fragmentClass != null) {
final FragmentManager fm = this.getSupportFragmentManager();
//Add breadcrumb bar
Fragment bar = (Fragment) fm.findFragmentByTag(TITLE_FRAGMENT_TAG);
// If the state holder is null, create a new one for this activity
if (bar == null) {
try {
bar = ((Class<Fragment>)Class.forName(fragmentClass)).newInstance();
//the bar will set this up for us again if we need.
getActionBar().setDisplayShowCustomEnabled(true);
getActionBar().setDisplayShowTitleEnabled(false);
fm.beginTransaction().add(bar, TITLE_FRAGMENT_TAG).commit();
} catch(Exception e) {
Log.w("odk-collect", "couldn't instantiate fragment: " + fragmentClass);
}
}
}
}
// must be at the beginning of any activity that can be called from an external intent
try {
Collect.createODKDirs();
} catch (RuntimeException e) {
Logger.exception(e);
CommCareActivity.createErrorDialog(this, e.getMessage(), EXIT);
return;
}
setupUI();
// Load JavaRosa modules. needed to restore forms.
new XFormsModule().registerModule();
// needed to override rms property manager
org.javarosa.core.services.PropertyManager.setPropertyManager(new PropertyManager(
getApplicationContext()));
Boolean newForm = true;
if (savedInstanceState != null) {
if (savedInstanceState.containsKey(KEY_FORMPATH)) {
mFormPath = savedInstanceState.getString(KEY_FORMPATH);
}
if (savedInstanceState.containsKey(NEWFORM)) {
newForm = savedInstanceState.getBoolean(NEWFORM, true);
}
if (savedInstanceState.containsKey(KEY_ERROR)) {
mErrorMessage = savedInstanceState.getString(KEY_ERROR);
}
if (savedInstanceState.containsKey(KEY_FORM_CONTENT_URI)) {
formProviderContentURI = Uri.parse(savedInstanceState.getString(KEY_FORM_CONTENT_URI));
}
if (savedInstanceState.containsKey(KEY_INSTANCE_CONTENT_URI)) {
instanceProviderContentURI = Uri.parse(savedInstanceState.getString(KEY_INSTANCE_CONTENT_URI));
}
if (savedInstanceState.containsKey(KEY_INSTANCEDESTINATION)) {
mInstanceDestination = savedInstanceState.getString(KEY_INSTANCEDESTINATION);
}
if(savedInstanceState.containsKey(KEY_INCOMPLETE_ENABLED)) {
mIncompleteEnabled = savedInstanceState.getBoolean(KEY_INCOMPLETE_ENABLED);
}
if(savedInstanceState.containsKey(KEY_RESIZING_ENABLED)) {
ResizingImageView.resizeMethod = savedInstanceState.getString(KEY_RESIZING_ENABLED);
}
if (savedInstanceState.containsKey(KEY_AES_STORAGE_KEY)) {
String base64Key = savedInstanceState.getString(KEY_AES_STORAGE_KEY);
try {
byte[] storageKey = new Base64Wrapper().decode(base64Key);
symetricKey = new SecretKeySpec(storageKey, "AES");
} catch (ClassNotFoundException e) {
throw new RuntimeException("Base64 encoding not available on this platform");
}
}
if(savedInstanceState.containsKey(KEY_HEADER_STRING)) {
mHeaderString = savedInstanceState.getString(KEY_HEADER_STRING);
}
if(savedInstanceState.containsKey(KEY_HAS_SAVED)) {
hasSaved = savedInstanceState.getBoolean(KEY_HAS_SAVED);
}
}
// If a parse error message is showing then nothing else is loaded
// Dialogs mid form just disappear on rotation.
if (mErrorMessage != null) {
CommCareActivity.createErrorDialog(this, mErrorMessage, EXIT);
return;
}
// Check to see if this is a screen flip or a new form load.
Object data = this.getLastCustomNonConfigurationInstance();
if (data instanceof FormLoaderTask) {
mFormLoaderTask = (FormLoaderTask) data;
} else if (data instanceof SaveToDiskTask) {
mSaveToDiskTask = (SaveToDiskTask) data;
} else if (data == null) {
if (!newForm) {
refreshCurrentView();
return;
}
boolean readOnly = false;
// Not a restart from a screen orientation change (or other).
mFormController = null;
mInstancePath = null;
Intent intent = getIntent();
if (intent != null) {
Uri uri = intent.getData();
if(intent.hasExtra(KEY_FORM_CONTENT_URI)) {
this.formProviderContentURI = Uri.parse(intent.getStringExtra(KEY_FORM_CONTENT_URI));
}
if(intent.hasExtra(KEY_INSTANCE_CONTENT_URI)) {
this.instanceProviderContentURI = Uri.parse(intent.getStringExtra(KEY_INSTANCE_CONTENT_URI));
}
if(intent.hasExtra(KEY_INSTANCEDESTINATION)) {
this.mInstanceDestination = intent.getStringExtra(KEY_INSTANCEDESTINATION);
} else {
mInstanceDestination = Collect.INSTANCES_PATH;
}
if(intent.hasExtra(KEY_AES_STORAGE_KEY)) {
String base64Key = intent.getStringExtra(KEY_AES_STORAGE_KEY);
try {
byte[] storageKey = new Base64Wrapper().decode(base64Key);
symetricKey = new SecretKeySpec(storageKey, "AES");
} catch (ClassNotFoundException e) {
throw new RuntimeException("Base64 encoding not available on this platform");
}
}
if(intent.hasExtra(KEY_HEADER_STRING)) {
this.mHeaderString = intent.getStringExtra(KEY_HEADER_STRING);
}
if(intent.hasExtra(KEY_INCOMPLETE_ENABLED)) {
this.mIncompleteEnabled = intent.getBooleanExtra(KEY_INCOMPLETE_ENABLED, true);
}
if(intent.hasExtra(KEY_RESIZING_ENABLED)) {
ResizingImageView.resizeMethod = intent.getStringExtra(KEY_RESIZING_ENABLED);
}
if(mHeaderString != null) {
setTitle(mHeaderString);
} else {
setTitle(StringUtils.getStringRobust(this, R.string.app_name) + " > " + StringUtils.getStringRobust(this, R.string.loading_form));
}
//[email protected] - Jan 24, 2012
//Since these are parceled across the content resolver, there's no guarantee of reference equality.
//We need to manually check value equality on the type
final String contentType = getContentResolver().getType(uri);
Uri formUri = null;
switch (contentType) {
case InstanceColumns.CONTENT_ITEM_TYPE:
Cursor instanceCursor = null;
Cursor formCursor = null;
try {
instanceCursor = getContentResolver().query(uri, null, null, null, null);
if (instanceCursor.getCount() != 1) {
CommCareHomeActivity.createErrorDialog(this, "Bad URI: " + uri, EXIT);
return;
} else {
instanceCursor.moveToFirst();
mInstancePath =
instanceCursor.getString(instanceCursor
.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH));
final String jrFormId =
instanceCursor.getString(instanceCursor
.getColumnIndex(InstanceColumns.JR_FORM_ID));
//If this form is both already completed
if (InstanceProviderAPI.STATUS_COMPLETE.equals(instanceCursor.getString(instanceCursor.getColumnIndex(InstanceColumns.STATUS)))) {
if (!Boolean.parseBoolean(instanceCursor.getString(instanceCursor.getColumnIndex(InstanceColumns.CAN_EDIT_WHEN_COMPLETE)))) {
readOnly = true;
}
}
final String[] selectionArgs = {
jrFormId
};
final String selection = FormsColumns.JR_FORM_ID + " like ?";
formCursor = getContentResolver().query(formProviderContentURI, null, selection, selectionArgs, null);
if (formCursor.getCount() == 1) {
formCursor.moveToFirst();
mFormPath =
formCursor.getString(formCursor
.getColumnIndex(FormsColumns.FORM_FILE_PATH));
formUri = ContentUris.withAppendedId(formProviderContentURI, formCursor.getLong(formCursor.getColumnIndex(FormsColumns._ID)));
} else if (formCursor.getCount() < 1) {
CommCareHomeActivity.createErrorDialog(this, "Parent form does not exist", EXIT);
return;
} else if (formCursor.getCount() > 1) {
CommCareHomeActivity.createErrorDialog(this, "More than one possible parent form", EXIT);
return;
}
}
} finally {
if (instanceCursor != null) {
instanceCursor.close();
}
if (formCursor != null) {
formCursor.close();
}
}
break;
case FormsColumns.CONTENT_ITEM_TYPE:
Cursor c = null;
try {
c = getContentResolver().query(uri, null, null, null, null);
if (c.getCount() != 1) {
CommCareHomeActivity.createErrorDialog(this, "Bad URI: " + uri, EXIT);
return;
} else {
c.moveToFirst();
mFormPath = c.getString(c.getColumnIndex(FormsColumns.FORM_FILE_PATH));
formUri = uri;
}
} finally {
if (c != null) {
c.close();
}
}
break;
default:
Log.e(t, "unrecognized URI");
CommCareHomeActivity.createErrorDialog(this, "unrecognized URI: " + uri, EXIT);
return;
}
if(formUri == null) {
Log.e(t, "unrecognized URI");
CommCareActivity.createErrorDialog(this, "couldn't locate FormDB entry for the item at: " + uri, EXIT);
return;
}
mFormLoaderTask = new FormLoaderTask(this, symetricKey, readOnly);
mFormLoaderTask.execute(formUri);
showDialog(PROGRESS_DIALOG);
}
}
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
/*
* EventLog accepts only proper Strings as input, but prior to this version,
* Android would try to send SpannedStrings to it, thus crashing the app.
* This makes sure the title is actually a String.
* This fixes bug 174626.
*/
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2
&& item.getTitleCondensed() != null) {
if (BuildConfig.DEBUG) {
Log.v(t, "Selected item is: " + item);
}
item.setTitleCondensed(item.getTitleCondensed().toString());
}
return super.onMenuItemSelected(featureId, item);
}
@Override
public void formSaveCallback() {
// note that we have started saving the form
savingFormOnKeySessionExpiration = true;
// start saving form, which will call the key session logout completion
// function when it finishes.
saveDataToDisk(EXIT, false, null, true);
}
/**
* Setup BroadcastReceiver for asking user if they want to enable gps
*/
private void registerFormEntryReceivers() {
// See if this form needs GPS to be turned on
mNoGPSReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
context.removeStickyBroadcast(intent);
LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
Set<String> providers = GeoUtils.evaluateProviders(manager);
if (providers.isEmpty()) {
DialogInterface.OnClickListener onChangeListener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int i) {
if (i == DialogInterface.BUTTON_POSITIVE) {
Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
}
};
GeoUtils.showNoGpsDialog(FormEntryActivity.this, onChangeListener);
}
}
};
registerReceiver(mNoGPSReceiver,
new IntentFilter(GeoUtils.ACTION_CHECK_GPS_ENABLED));
}
/**
* Setup Activity's UI
*/
private void setupUI() {
setContentView(R.layout.screen_form_entry);
setNavBarVisibility();
ImageButton nextButton = (ImageButton)this.findViewById(R.id.nav_btn_next);
ImageButton prevButton = (ImageButton)this.findViewById(R.id.nav_btn_prev);
nextButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (!"done".equals(v.getTag())) {
FormEntryActivity.this.showNextView();
} else {
triggerUserFormComplete();
}
}
});
prevButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (!"quit".equals(v.getTag())) {
FormEntryActivity.this.showPreviousView();
} else {
FormEntryActivity.this.triggerUserQuitInput();
}
}
});
mViewPane = (ViewGroup)findViewById(R.id.form_entry_pane);
mBeenSwiped = false;
mAlertDialog = null;
mCurrentView = null;
mInAnimation = null;
mOutAnimation = null;
mGestureDetector = new GestureDetector(this);
}
public static final String TITLE_FRAGMENT_TAG = "odk_title_fragment";
/*
* (non-Javadoc)
* @see android.support.v4.app.FragmentActivity#onSaveInstanceState(android.os.Bundle)
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(KEY_FORMPATH, mFormPath);
outState.putBoolean(NEWFORM, false);
outState.putString(KEY_ERROR, mErrorMessage);
outState.putString(KEY_FORM_CONTENT_URI, formProviderContentURI.toString());
outState.putString(KEY_INSTANCE_CONTENT_URI, instanceProviderContentURI.toString());
outState.putString(KEY_INSTANCEDESTINATION, mInstanceDestination);
outState.putBoolean(KEY_INCOMPLETE_ENABLED, mIncompleteEnabled);
outState.putBoolean(KEY_HAS_SAVED, hasSaved);
outState.putString(KEY_RESIZING_ENABLED, ResizingImageView.resizeMethod);
if(symetricKey != null) {
try {
outState.putString(KEY_AES_STORAGE_KEY, new Base64Wrapper().encodeToString(symetricKey.getEncoded()));
} catch (ClassNotFoundException e) {
// we can't really get here anyway, since we couldn't have decoded the string to begin with
throw new RuntimeException("Base 64 encoding unavailable! Can't pass storage key");
}
}
}
/*
* (non-Javadoc)
* @see android.support.v4.app.FragmentActivity#onActivityResult(int, int, android.content.Intent)
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == RESULT_CANCELED) {
if(requestCode == HIERARCHY_ACTIVITY_FIRST_START) {
//they pressed 'back' on the first heirarchy screen. we should assume they want to
//back out of form entry all together
finishReturnInstance(false);
} else if(requestCode == INTENT_CALLOUT){
processIntentResponse(intent, true);
}
// request was canceled, so do nothing
return;
}
ContentValues values;
Uri imageURI;
switch (requestCode) {
case BARCODE_CAPTURE:
String sb = intent.getStringExtra("SCAN_RESULT");
((ODKView) mCurrentView).setBinaryData(sb);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
break;
case INTENT_CALLOUT:
processIntentResponse(intent);
break;
case IMAGE_CAPTURE:
case SIGNATURE_CAPTURE:
/*
* We saved the image to the tempfile_path, but we really want it to be in:
* /sdcard/odk/instances/[current instnace]/something.jpg so we move it there before
* inserting it into the content provider. Once the android image capture bug gets
* fixed, (read, we move on from Android 1.6) we want to handle images the audio and
* video
*/
// The intent is empty, but we know we saved the image to the temp file
File fi = new File(Collect.TMPFILE_PATH);
String mInstanceFolder =
mInstancePath.substring(0, mInstancePath.lastIndexOf("/") + 1);
String s = mInstanceFolder + "/" + System.currentTimeMillis() + ".jpg";
File nf = new File(s);
if (!fi.renameTo(nf)) {
Log.e(t, "Failed to rename " + fi.getAbsolutePath());
} else {
Log.i(t, "renamed " + fi.getAbsolutePath() + " to " + nf.getAbsolutePath());
}
// Add the new image to the Media content provider so that the
// viewing is fast in Android 2.0+
values = new ContentValues(6);
values.put(Images.Media.TITLE, nf.getName());
values.put(Images.Media.DISPLAY_NAME, nf.getName());
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/jpeg");
values.put(Images.Media.DATA, nf.getAbsolutePath());
imageURI = getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);
Log.i(t, "Inserting image returned uri = " + imageURI.toString());
((ODKView) mCurrentView).setBinaryData(imageURI);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
refreshCurrentView();
break;
case IMAGE_CHOOSER:
/*
* We have a saved image somewhere, but we really want it to be in:
* /sdcard/odk/instances/[current instnace]/something.jpg so we move it there before
* inserting it into the content provider. Once the android image capture bug gets
* fixed, (read, we move on from Android 1.6) we want to handle images the audio and
* video
*/
// get gp of chosen file
String sourceImagePath = null;
Uri selectedImage = intent.getData();
sourceImagePath = FileUtils.getPath(this, selectedImage);
// Copy file to sdcard
String mInstanceFolder1 =
mInstancePath.substring(0, mInstancePath.lastIndexOf("/") + 1);
String destImagePath = mInstanceFolder1 + "/" + System.currentTimeMillis() + ".jpg";
File source = new File(sourceImagePath);
File newImage = new File(destImagePath);
FileUtils.copyFile(source, newImage);
if (newImage.exists()) {
// Add the new image to the Media content provider so that the
// viewing is fast in Android 2.0+
values = new ContentValues(6);
values.put(Images.Media.TITLE, newImage.getName());
values.put(Images.Media.DISPLAY_NAME, newImage.getName());
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/jpeg");
values.put(Images.Media.DATA, newImage.getAbsolutePath());
imageURI =
getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);
Log.i(t, "Inserting image returned uri = " + imageURI.toString());
((ODKView) mCurrentView).setBinaryData(imageURI);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
} else {
Log.e(t, "NO IMAGE EXISTS at: " + source.getAbsolutePath());
}
refreshCurrentView();
break;
case AUDIO_CAPTURE:
case VIDEO_CAPTURE:
case AUDIO_CHOOSER:
case VIDEO_CHOOSER:
// For audio/video capture/chooser, we get the URI from the content provider
// then the widget copies the file and makes a new entry in the content provider.
Uri media = intent.getData();
String binaryPath = UriToFilePath.getPathFromUri(CommCareApplication._(), media);
if (!FormUploadUtil.isSupportedMultimediaFile(binaryPath)) {
// don't let the user select a file that won't be included in the
// upload to the server
((ODKView) mCurrentView).clearAnswer();
Toast.makeText(FormEntryActivity.this,
StringUtils.getStringSpannableRobust(FormEntryActivity.this, R.string.attachment_invalid),
Toast.LENGTH_LONG).show();
return;
} else {
((ODKView) mCurrentView).setBinaryData(media);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
refreshCurrentView();
}
break;
case LOCATION_CAPTURE:
String sl = intent.getStringExtra(LOCATION_RESULT);
((ODKView) mCurrentView).setBinaryData(sl);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
break;
case HIERARCHY_ACTIVITY:
// We may have jumped to a new index in hierarchy activity, so refresh
refreshCurrentView(false);
break;
}
}
private void processIntentResponse(Intent response){
processIntentResponse(response, false);
}
private void processIntentResponse(Intent response, boolean cancelled) {
// keep track of whether we should auto advance
boolean advance = false;
boolean quick = false;
//We need to go grab our intent callout object to process the results here
IntentWidget bestMatch = null;
//Ugh, copied from the odkview mostly, that's stupid
for(QuestionWidget q : ((ODKView)mCurrentView).getWidgets()) {
//Figure out if we have a pending intent widget
if (q instanceof IntentWidget) {
if(((IntentWidget) q).isWaitingForBinaryData() || bestMatch == null) {
bestMatch = (IntentWidget)q;
}
}
}
if(bestMatch != null) {
//Set our instance destination for binary data if needed
String destination = mInstancePath.substring(0, mInstancePath.lastIndexOf("/") + 1);
//get the original intent callout
IntentCallout ic = bestMatch.getIntentCallout();
quick = "quick".equals(ic.getAppearance());
//And process it
advance = ic.processResponse(response, (ODKView)mCurrentView, mFormController.getInstance(), new File(destination));
ic.setCancelled(cancelled);
}
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
// auto advance if we got a good result and are in quick mode
if(advance && quick){
showNextView();
}
}
public void updateFormRelevencies(){
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
if(!(mCurrentView instanceof ODKView)){
throw new RuntimeException("Tried to update form relevency not on compound view");
}
ODKView oldODKV = (ODKView)mCurrentView;
FormEntryPrompt[] newValidPrompts = mFormController.getQuestionPrompts();
Set<FormEntryPrompt> used = new HashSet<FormEntryPrompt>();
ArrayList<QuestionWidget> oldWidgets = oldODKV.getWidgets();
ArrayList<Integer> removeList = new ArrayList<Integer>();
for(int i=0;i<oldWidgets.size();i++){
QuestionWidget oldWidget = oldWidgets.get(i);
boolean stillRelevent = false;
for(FormEntryPrompt prompt : newValidPrompts) {
if(prompt.getIndex().equals(oldWidget.getPrompt().getIndex())) {
stillRelevent = true;
used.add(prompt);
}
}
if(!stillRelevent){
removeList.add(Integer.valueOf(i));
}
}
// remove "atomically" to not mess up iterations
oldODKV.removeQuestionsFromIndex(removeList);
//Now go through add add any new prompts that we need
for(int i = 0 ; i < newValidPrompts.length; ++i) {
FormEntryPrompt prompt = newValidPrompts[i];
if(used.contains(prompt)) {
//nothing to do here
continue;
}
oldODKV.addQuestionToIndex(prompt, mFormController.getWidgetFactory(), i);
}
}
private static class NavigationDetails {
public int totalQuestions = 0;
public int completedQuestions = 0;
public boolean relevantBeforeCurrentScreen = false;
public boolean isFirstScreen = false;
public int answeredOnScreen = 0;
public int requiredOnScreen = 0;
public int relevantAfterCurrentScreen = 0;
public FormIndex currentScreenExit = null;
}
private NavigationDetails calculateNavigationStatus() {
NavigationDetails details = new NavigationDetails();
FormIndex userFormIndex = mFormController.getFormIndex();
FormIndex currentFormIndex = FormIndex.createBeginningOfFormIndex();
mFormController.expandRepeats(currentFormIndex);
int event = mFormController.getEvent(currentFormIndex);
try {
// keep track of whether there is a question that exists before the
// current screen
boolean onCurrentScreen = false;
while (event != FormEntryController.EVENT_END_OF_FORM) {
int comparison = currentFormIndex.compareTo(userFormIndex);
if (comparison == 0) {
onCurrentScreen = true;
details.currentScreenExit = mFormController.getNextFormIndex(currentFormIndex, true);
}
if (onCurrentScreen && currentFormIndex.equals(details.currentScreenExit)) {
onCurrentScreen = false;
}
// Figure out if there are any events before this screen (either
// new repeat or relevant questions are valid)
if (event == FormEntryController.EVENT_QUESTION
|| event == FormEntryController.EVENT_PROMPT_NEW_REPEAT) {
// Figure out whether we're on the last screen
if (!details.relevantBeforeCurrentScreen && !details.isFirstScreen) {
// We got to the current screen without finding a
// relevant question,
// I guess we're on the first one.
if (onCurrentScreen
&& !details.relevantBeforeCurrentScreen) {
details.isFirstScreen = true;
} else {
// We're using the built in steps (and they take
// relevancy into account)
// so if there are prompts they have to be relevant
details.relevantBeforeCurrentScreen = true;
}
}
}
if (event == FormEntryController.EVENT_QUESTION) {
FormEntryPrompt[] prompts = mFormController.getQuestionPrompts(currentFormIndex);
if (!onCurrentScreen && details.currentScreenExit != null) {
details.relevantAfterCurrentScreen += prompts.length;
}
details.totalQuestions += prompts.length;
// Current questions are complete only if they're answered.
// Past questions are always complete.
// Future questions are never complete.
if (onCurrentScreen) {
for (FormEntryPrompt prompt : prompts) {
if (this.mCurrentView instanceof ODKView) {
ODKView odkv = (ODKView) this.mCurrentView;
prompt = getOnScreenPrompt(prompt, odkv);
}
boolean isAnswered = prompt.getAnswerValue() != null
|| prompt.getDataType() == Constants.DATATYPE_NULL;
if (prompt.isRequired()) {
details.requiredOnScreen++;
if (isAnswered) {
details.answeredOnScreen++;
}
}
if (isAnswered) {
details.completedQuestions++;
}
}
} else if (comparison < 0) {
// For previous questions, consider all "complete"
details.completedQuestions += prompts.length;
// TODO: This doesn't properly capture state to
// determine whether we will end up out of the form if
// we hit back!
// Need to test _until_ we get a question that is
// relevant, then we can skip the relevancy tests
}
}
else if (event == FormEntryController.EVENT_PROMPT_NEW_REPEAT) {
// If we've already passed the current screen, this repeat
// junction is coming up in the future and we will need to
// know
// about it
if (!onCurrentScreen && details.currentScreenExit != null) {
details.totalQuestions++;
details.relevantAfterCurrentScreen++;
} else {
// Otherwise we already passed it and it no longer
// affects the count
}
}
currentFormIndex = mFormController.getNextFormIndex(currentFormIndex, FormController.STEP_INTO_GROUP, false);
event = mFormController.getEvent(currentFormIndex);
}
} catch (XPathTypeMismatchException e) {
Logger.exception(e);
CommCareActivity.createErrorDialog(this, e.getMessage(), EXIT);
}
// Set form back to correct state
mFormController.jumpToIndex(userFormIndex);
return details;
}
/**
* Update progress bar's max and value, and the various buttons and navigation cues
* associated with navigation
*
* @param view ODKView to update
*/
public void updateNavigationCues(View view) {
updateFloatingLabels(view);
ProgressBarMode mode = PreferencesActivity.getProgressBarMode(this);
setNavBarVisibility();
if(mode == ProgressBarMode.None) { return; }
NavigationDetails details = calculateNavigationStatus();
if(mode == ProgressBarMode.ProgressOnly && view instanceof ODKView) {
((ODKView)view).updateProgressBar(details.completedQuestions, details.totalQuestions);
return;
}
ProgressBar progressBar = (ProgressBar)this.findViewById(R.id.nav_prog_bar);
ImageButton nextButton = (ImageButton)this.findViewById(R.id.nav_btn_next);
ImageButton prevButton = (ImageButton)this.findViewById(R.id.nav_btn_prev);
if(!details.relevantBeforeCurrentScreen) {
prevButton.setImageResource(R.drawable.icon_close_darkwarm);
prevButton.setTag("quit");
} else {
prevButton.setImageResource(R.drawable.icon_chevron_left_brand);
prevButton.setTag("back");
}
//Apparently in Android 2.3 setting the drawable resource for the progress bar
//causes it to lose it bounds. It's a bit cheaper to keep them around than it
//is to invalidate the view, though.
Rect bounds = progressBar.getProgressDrawable().getBounds(); //Save the drawable bound
Log.i("Questions","Total questions: " + details.totalQuestions + " | Completed questions: " + details.completedQuestions);
progressBar.getProgressDrawable().setBounds(bounds); //Set the bounds to the saved value
progressBar.setMax(details.totalQuestions);
if(details.relevantAfterCurrentScreen == 0 && (details.requiredOnScreen == details.answeredOnScreen || details.requiredOnScreen < 1)) {
nextButton.setImageResource(R.drawable.icon_chevron_right_attnpos);
//TODO: _really_? This doesn't seem right
nextButton.setTag("done");
progressBar.setProgressDrawable(this.getResources().getDrawable(R.drawable.progressbar_full));
Log.i("Questions","Form complete");
// if we get here, it means we don't have any more relevant questions after this one, so we mark it as complete
progressBar.setProgress(details.totalQuestions); // completely fills the progressbar
} else {
nextButton.setImageResource(R.drawable.icon_chevron_right_brand);
//TODO: _really_? This doesn't seem right
nextButton.setTag("next");
progressBar.setProgressDrawable(this.getResources().getDrawable(R.drawable.progressbar_modern));
progressBar.setProgress(details.completedQuestions);
}
//We should probably be doing this based on the widgets, maybe, not the model? Hard to call.
updateBadgeInfo(details.requiredOnScreen, details.answeredOnScreen);
}
private void setNavBarVisibility() {
//Make sure the nav bar visibility is set
int navBarVisibility = PreferencesActivity.getProgressBarMode(this).useNavigationBar() ? View.VISIBLE : View.GONE;
View nav = this.findViewById(R.id.nav_pane);
if(nav.getVisibility() != navBarVisibility) {
nav.setVisibility(navBarVisibility);
this.findViewById(R.id.nav_badge_border_drawer).setVisibility(navBarVisibility);
this.findViewById(R.id.nav_badge).setVisibility(navBarVisibility);
}
}
enum FloatingLabel {
good ("floating-good", R.drawable.label_floating_good, R.color.cc_attention_positive_text),
caution ("floating-caution", R.drawable.label_floating_caution, R.color.cc_light_warm_accent_color),
bad ("floating-bad", R.drawable.label_floating_bad, R.color.cc_attention_negative_color);
String label;
int resourceId;
int colorId;
FloatingLabel(String label, int resourceId, int colorId) {
this.label = label;
this.resourceId = resourceId;
this.colorId = colorId;
}
public String getAppearance() { return label;}
public int getBackgroundDrawable() { return resourceId; }
public int getColorId() { return colorId; }
};
private void updateFloatingLabels(View currentView) {
//TODO: this should actually be set up to scale per screen size.
ArrayList<Pair<String, FloatingLabel>> smallLabels = new ArrayList<Pair<String, FloatingLabel>>();
ArrayList<Pair<String, FloatingLabel>> largeLabels = new ArrayList<Pair<String, FloatingLabel>>();
FloatingLabel[] labelTypes = FloatingLabel.values();
if(currentView instanceof ODKView) {
for(QuestionWidget widget : ((ODKView)currentView).getWidgets()) {
String hint = widget.getPrompt().getAppearanceHint();
if(hint == null) { continue; }
for(FloatingLabel type : labelTypes) {
if(type.getAppearance().equals(hint)) {
String widgetText = widget.getPrompt().getQuestionText();
if(widgetText != null && widgetText.length() < 15) {
smallLabels.add(new Pair(widgetText, type));
} else {
largeLabels.add(new Pair(widgetText, type));
}
}
}
}
}
final ViewGroup parent = (ViewGroup)this.findViewById(R.id.form_entry_label_layout);
parent.removeAllViews();
int pixels = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8, getResources().getDisplayMetrics());
int minHeight = 7 * pixels;
//Ok, now go ahead and add all of the small labels
for(int i = 0 ; i < smallLabels.size(); i = i + 2 ) {
if(i + 1 < smallLabels.size()) {
LinearLayout.LayoutParams lpp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
final LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.HORIZONTAL);
layout.setLayoutParams(lpp);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1);
TextView left = (TextView)View.inflate(this, R.layout.component_floating_label, null);
left.setLayoutParams(lp);
left.setText(smallLabels.get(i).first + "; " + smallLabels.get(i + 1).first);
left.setBackgroundResource(smallLabels.get(i).second.resourceId);
left.setPadding(pixels, 2 * pixels, pixels, 2 * pixels);
left.setTextColor(smallLabels.get(i).second.colorId);
left.setMinimumHeight(minHeight);
layout.addView(left);
parent.addView(layout);
} else {
largeLabels.add(smallLabels.get(i));
}
}
for(int i = 0 ; i < largeLabels.size(); ++i ) {
final TextView view = (TextView)View.inflate(this, R.layout.component_floating_label, null);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
view.setLayoutParams(lp);
view.setPadding(pixels, 2 * pixels, pixels, 2 * pixels);
view.setText(largeLabels.get(i).first);
view.setBackgroundResource(largeLabels.get(i).second.resourceId);
view.setTextColor(largeLabels.get(i).second.colorId);
view.setMinimumHeight(minHeight);
parent.addView(view);
}
}
private void updateBadgeInfo(int requiredOnScreen, int answeredOnScreen) {
View badgeBorder = this.findViewById(R.id.nav_badge_border_drawer);
TextView badge = (TextView)this.findViewById(R.id.nav_badge);
//If we don't need this stuff, just bail
if(requiredOnScreen <= 1) {
//Hide all badge related items
badgeBorder.setVisibility(View.INVISIBLE);
badge.setVisibility(View.INVISIBLE);
return;
}
//Otherwise, update badge stuff
badgeBorder.setVisibility(View.VISIBLE);
badge.setVisibility(View.VISIBLE);
if(requiredOnScreen - answeredOnScreen == 0) {
//Unicode checkmark
badge.setText("\u2713");
badge.setBackgroundResource(R.drawable.badge_background_complete);
} else {
badge.setBackgroundResource(R.drawable.badge_background);
badge.setText(String.valueOf(requiredOnScreen - answeredOnScreen));
}
}
/**
* Takes in a form entry prompt that is obtained generically and if there
* is already one on screen (which, for isntance, may have cached some of its data)
* returns the object in use currently.
*
* @param prompt
* @return
*/
private FormEntryPrompt getOnScreenPrompt(FormEntryPrompt prompt, ODKView view) {
FormIndex index = prompt.getIndex();
for(QuestionWidget widget : view.getWidgets()) {
if(widget.getFormId().equals(index)) {
return widget.getPrompt();
}
}
return prompt;
}
/**
* Refreshes the current view. the controller and the displayed view can get out of sync due to
* dialogs and restarts caused by screen orientation changes, so they're resynchronized here.
*/
public void refreshCurrentView() {
refreshCurrentView(true);
}
/**
* Refreshes the current view. the controller and the displayed view can get out of sync due to
* dialogs and restarts caused by screen orientation changes, so they're resynchronized here.
*/
public void refreshCurrentView(boolean animateLastView) {
if(mFormController == null) { throw new RuntimeException("Form state is lost! Cannot refresh current view. This shouldn't happen, please submit a bug report."); }
int event = mFormController.getEvent();
// When we refresh, repeat dialog state isn't maintained, so step back to the previous
// question.
// Also, if we're within a group labeled 'field list', step back to the beginning of that
// group.
// That is, skip backwards over repeat prompts, groups that are not field-lists,
// repeat events, and indexes in field-lists that is not the containing group.
while (event == FormEntryController.EVENT_PROMPT_NEW_REPEAT
|| (event == FormEntryController.EVENT_GROUP && !mFormController.indexIsInFieldList())
|| event == FormEntryController.EVENT_REPEAT
|| (mFormController.indexIsInFieldList() && !(event == FormEntryController.EVENT_GROUP))) {
event = mFormController.stepToPreviousEvent();
}
//If we're at the beginning of form event, but don't show the screen for that, we need
//to get the next valid screen
if(event == FormEntryController.EVENT_BEGINNING_OF_FORM && !PreferencesActivity.showFirstScreen(this)) {
this.showNextView(true);
} else {
View current = createView(event);
showView(current, AnimationType.FADE, animateLastView);
}
}
/*
* (non-Javadoc)
* @see android.app.Activity#onPrepareOptionsMenu(android.view.Menu)
*/
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.removeItem(MENU_LANGUAGES);
menu.removeItem(MENU_HIERARCHY_VIEW);
menu.removeItem(MENU_SAVE);
menu.removeItem(MENU_PREFERENCES);
if(mIncompleteEnabled) {
menu.add(0, MENU_SAVE, 0, StringUtils.getStringRobust(this, R.string.save_all_answers)).setIcon(
android.R.drawable.ic_menu_save);
}
menu.add(0, MENU_HIERARCHY_VIEW, 0, StringUtils.getStringRobust(this, R.string.view_hierarchy)).setIcon(
R.drawable.ic_menu_goto);
menu.add(0, MENU_LANGUAGES, 0, StringUtils.getStringRobust(this, R.string.change_language))
.setIcon(R.drawable.ic_menu_start_conversation)
.setEnabled(
(mFormController == null || mFormController.getLanguages() == null || mFormController.getLanguages().length == 1) ? false
: true);
menu.add(0, MENU_PREFERENCES, 0, StringUtils.getStringRobust(this, R.string.general_preferences)).setIcon(
android.R.drawable.ic_menu_preferences);
return true;
}
/*
* (non-Javadoc)
* @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_LANGUAGES:
createLanguageDialog();
return true;
case MENU_SAVE:
// don't exit
saveDataToDisk(DO_NOT_EXIT, isInstanceComplete(false), null, false);
return true;
case MENU_HIERARCHY_VIEW:
if (currentPromptIsQuestion()) {
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
}
Intent i = new Intent(this, FormHierarchyActivity.class);
startActivityForResult(i, HIERARCHY_ACTIVITY);
return true;
case MENU_PREFERENCES:
Intent pref = new Intent(this, PreferencesActivity.class);
startActivity(pref);
return true;
case android.R.id.home:
triggerUserQuitInput();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* @return true If the current index of the form controller contains questions
*/
private boolean currentPromptIsQuestion() {
return (mFormController.getEvent() == FormEntryController.EVENT_QUESTION || mFormController
.getEvent() == FormEntryController.EVENT_GROUP);
}
private boolean saveAnswersForCurrentScreen(boolean evaluateConstraints) {
return saveAnswersForCurrentScreen(evaluateConstraints, true, false);
}
/**
* Attempt to save the answer(s) in the current screen to into the data model.
*
* @param evaluateConstraints
* @param failOnRequired Whether or not the constraint evaluation
* should return false if the question is only
* required. (this is helpful for incomplete
* saves)
* @param headless running in a process that can't display graphics
* @return false if any error occurs while saving (constraint violated,
* etc...), true otherwise.
*/
private boolean saveAnswersForCurrentScreen(boolean evaluateConstraints,
boolean failOnRequired,
boolean headless) {
// only try to save if the current event is a question or a field-list
// group
boolean success = true;
if ((mFormController.getEvent() == FormEntryController.EVENT_QUESTION)
|| ((mFormController.getEvent() == FormEntryController.EVENT_GROUP) &&
mFormController.indexIsInFieldList())) {
if (mCurrentView instanceof ODKView) {
HashMap<FormIndex, IAnswerData> answers =
((ODKView)mCurrentView).getAnswers();
// Sort the answers so if there are multiple errors, we can
// bring focus to the first one
List<FormIndex> indexKeys = new ArrayList<FormIndex>();
indexKeys.addAll(answers.keySet());
Collections.sort(indexKeys, new Comparator<FormIndex>() {
@Override
public int compare(FormIndex arg0, FormIndex arg1) {
return arg0.compareTo(arg1);
}
});
for (FormIndex index : indexKeys) {
// Within a group, you can only save for question events
if (mFormController.getEvent(index) == FormEntryController.EVENT_QUESTION) {
int saveStatus = saveAnswer(answers.get(index),
index, evaluateConstraints);
if (evaluateConstraints &&
((saveStatus != FormEntryController.ANSWER_OK) &&
(failOnRequired ||
saveStatus != FormEntryController.ANSWER_REQUIRED_BUT_EMPTY))) {
if (!headless) {
createConstraintToast(index, mFormController.getQuestionPrompt(index).getConstraintText(), saveStatus, success);
}
success = false;
}
} else {
Log.w(t,
"Attempted to save an index referencing something other than a question: "
+ index.getReference());
}
}
} else {
String viewType;
if (mCurrentView == null || mCurrentView.getClass() == null) {
viewType = "null";
} else {
viewType = mCurrentView.getClass().toString();
}
Log.w(t, "Unknown view type rendered while current event was question or group! View type: " + viewType);
}
}
return success;
}
/**
* Clears the answer on the screen.
*/
private void clearAnswer(QuestionWidget qw) {
qw.clearAnswer();
}
/*
* (non-Javadoc)
* @see android.app.Activity#onCreateContextMenu(android.view.ContextMenu, android.view.View, android.view.ContextMenu.ContextMenuInfo)
*/
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, v.getId(), 0, StringUtils.getStringSpannableRobust(this, R.string.clear_answer));
menu.setHeaderTitle(StringUtils.getStringSpannableRobust(this, R.string.edit_prompt));
}
/*
* (non-Javadoc)
* @see android.app.Activity#onContextItemSelected(android.view.MenuItem)
*/
@Override
public boolean onContextItemSelected(MenuItem item) {
// We don't have the right view here, so we store the View's ID as the
// item ID and loop through the possible views to find the one the user
// clicked on.
for (QuestionWidget qw : ((ODKView) mCurrentView).getWidgets()) {
if (item.getItemId() == qw.getId()) {
createClearDialog(qw);
}
}
return super.onContextItemSelected(item);
}
/*
* (non-Javadoc)
* @see android.support.v4.app.FragmentActivity#onRetainCustomNonConfigurationInstance()
*
* If we're loading, then we pass the loading thread to our next instance.
*/
@Override
public Object onRetainCustomNonConfigurationInstance() {
// if a form is loading, pass the loader task
if (mFormLoaderTask != null && mFormLoaderTask.getStatus() != AsyncTask.Status.FINISHED)
return mFormLoaderTask;
// if a form is writing to disk, pass the save to disk task
if (mSaveToDiskTask != null && mSaveToDiskTask.getStatus() != AsyncTask.Status.FINISHED)
return mSaveToDiskTask;
// mFormEntryController is static so we don't need to pass it.
if (mFormController != null && currentPromptIsQuestion()) {
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
}
return null;
}
private String getHeaderString() {
if(mHeaderString != null) {
//Localization?
return mHeaderString;
} else {
return StringUtils.getStringRobust(this, R.string.app_name) + " > " + mFormController.getFormTitle();
}
}
/**
* Creates a view given the View type and an event
*
* @param event
* @return newly created View
*/
private View createView(int event) {
boolean isGroup = false;
setTitle(getHeaderString());
switch (event) {
case FormEntryController.EVENT_BEGINNING_OF_FORM:
View startView = View.inflate(this, R.layout.form_entry_start, null);
setTitle(getHeaderString());
((TextView) startView.findViewById(R.id.description)).setText(StringUtils.getStringSpannableRobust(this, R.string.enter_data_description, mFormController.getFormTitle()));
((CheckBox) startView.findViewById(R.id.screen_form_entry_start_cbx_dismiss)).setText(StringUtils.getStringSpannableRobust(this, R.string.form_entry_start_hide));
((TextView) startView.findViewById(R.id.screen_form_entry_advance_text)).setText(StringUtils.getStringSpannableRobust(this, R.string.advance));
((TextView) startView.findViewById(R.id.screen_form_entry_backup_text)).setText(StringUtils.getStringSpannableRobust(this, R.string.backup));
Drawable image = null;
String[] projection = {
FormsColumns.FORM_MEDIA_PATH
};
String selection = FormsColumns.FORM_FILE_PATH + "=?";
String[] selectionArgs = {
mFormPath
};
Cursor c = null;
String mediaDir = null;
try {
c = getContentResolver().query(formProviderContentURI, projection, selection, selectionArgs, null);
if (c.getCount() < 1) {
CommCareActivity.createErrorDialog(this, "Form doesn't exist", EXIT);
return new View(this);
} else {
c.moveToFirst();
mediaDir = c.getString(c.getColumnIndex(FormsColumns.FORM_MEDIA_PATH));
}
} finally {
if (c != null) {
c.close();
}
}
BitmapDrawable bitImage = null;
// attempt to load the form-specific logo...
// this is arbitrarily silly
bitImage = new BitmapDrawable(mediaDir + "/form_logo.png");
if (bitImage != null && bitImage.getBitmap() != null
&& bitImage.getIntrinsicHeight() > 0 && bitImage.getIntrinsicWidth() > 0) {
image = bitImage;
}
if (image == null) {
// show the opendatakit zig...
// image = getResources().getDrawable(R.drawable.opendatakit_zig);
((ImageView) startView.findViewById(R.id.form_start_bling))
.setVisibility(View.GONE);
} else {
((ImageView) startView.findViewById(R.id.form_start_bling))
.setImageDrawable(image);
}
return startView;
case FormEntryController.EVENT_END_OF_FORM:
View endView = View.inflate(this, R.layout.form_entry_end, null);
((TextView) endView.findViewById(R.id.description)).setText(StringUtils.getStringSpannableRobust(this, R.string.save_enter_data_description,
mFormController.getFormTitle()));
// checkbox for if finished or ready to send
final CheckBox instanceComplete = ((CheckBox) endView.findViewById(R.id.mark_finished));
instanceComplete.setText(StringUtils.getStringSpannableRobust(this, R.string.mark_finished));
//If incomplete is not enabled, make sure this box is checked.
instanceComplete.setChecked(!mIncompleteEnabled || isInstanceComplete(true));
if(mFormController.isFormReadOnly() || !mIncompleteEnabled) {
instanceComplete.setVisibility(View.GONE);
}
// edittext to change the displayed name of the instance
final EditText saveAs = (EditText) endView.findViewById(R.id.save_name);
//TODO: Figure this out based on the content provider or some part of the context
saveAs.setVisibility(View.GONE);
endView.findViewById(R.id.save_form_as).setVisibility(View.GONE);
// disallow carriage returns in the name
InputFilter returnFilter = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
for (int i = start; i < end; i++) {
if (Character.getType((source.charAt(i))) == Character.CONTROL) {
return "";
}
}
return null;
}
};
saveAs.setFilters(new InputFilter[] {
returnFilter
});
String saveName = getDefaultFormTitle();
saveAs.setText(saveName);
// Create 'save' button
Button button = (Button) endView.findViewById(R.id.save_exit_button);
if(mFormController.isFormReadOnly()) {
button.setText(StringUtils.getStringSpannableRobust(this, R.string.exit));
button.setOnClickListener(new OnClickListener() {
/*
* (non-Javadoc)
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
@Override
public void onClick(View v) {
finishReturnInstance();
}
});
} else {
button.setText(StringUtils.getStringSpannableRobust(this, R.string.quit_entry));
button.setOnClickListener(new OnClickListener() {
/*
* (non-Javadoc)
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
@Override
public void onClick(View v) {
// Form is marked as 'saved' here.
if (saveAs.getText().length() < 1) {
Toast.makeText(FormEntryActivity.this, StringUtils.getStringSpannableRobust(FormEntryActivity.this, R.string.save_as_error),
Toast.LENGTH_SHORT).show();
} else {
saveDataToDisk(EXIT,
instanceComplete.isChecked(),
saveAs.getText().toString(),
false);
}
}
});
}
return endView;
case FormEntryController.EVENT_GROUP:
isGroup = true;
case FormEntryController.EVENT_QUESTION:
ODKView odkv = null;
// should only be a group here if the event_group is a field-list
try {
odkv =
new ODKView(this, mFormController.getQuestionPrompts(),
mFormController.getGroupsForCurrentIndex(),
mFormController.getWidgetFactory(), this, isGroup);
Log.i(t, "created view for group");
} catch (RuntimeException e) {
Logger.exception(e);
CommCareActivity.createErrorDialog(this, e.getMessage(), EXIT);
// this is badness to avoid a crash.
// really a next view should increment the formcontroller, create the view
// if the view is null, then keep the current view and pop an error.
return new View(this);
}
// Makes a "clear answer" menu pop up on long-click of
// select-one/select-multiple questions
for (QuestionWidget qw : odkv.getWidgets()) {
if (!qw.getPrompt().isReadOnly() &&
!mFormController.isFormReadOnly() &&
(qw.getPrompt().getControlType() == Constants.CONTROL_SELECT_ONE ||
qw.getPrompt().getControlType() == Constants.CONTROL_SELECT_MULTI)) {
registerForContextMenu(qw);
}
}
updateNavigationCues(odkv);
return odkv;
default:
Log.e(t, "Attempted to create a view that does not exist.");
return null;
}
}
/*
* (non-Javadoc)
* @see android.app.Activity#dispatchTouchEvent(android.view.MotionEvent)
*/
@SuppressLint("NewApi")
@Override
public boolean dispatchTouchEvent(MotionEvent mv) {
//We need to ignore this even if it's processed by the action
//bar (if one exists)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
View customView = getActionBar().getCustomView();
if(customView != null) {
if(customView.dispatchTouchEvent(mv)) {
return true;
}
}
}
boolean handled = mGestureDetector.onTouchEvent(mv);
if (!handled) {
return super.dispatchTouchEvent(mv);
}
return handled; // this is always true
}
/**
* Determines what should be displayed on the screen. Possible options are: a question, an ask
* repeat dialog, or the submit screen. Also saves answers to the data model after checking
* constraints.
*/
private void showNextView() { showNextView(false); }
private void showNextView(boolean resuming) {
if(!resuming && mFormController.getEvent() == FormEntryController.EVENT_BEGINNING_OF_FORM) {
//See if we should stop displaying the start screen
CheckBox stopShowingIntroScreen = (CheckBox)mCurrentView.findViewById(R.id.screen_form_entry_start_cbx_dismiss);
//Not sure why it would, but maybe timing issues?
if(stopShowingIntroScreen != null) {
if(stopShowingIntroScreen.isChecked()) {
//set it!
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
sharedPreferences.edit().putBoolean(PreferencesActivity.KEY_SHOW_START_SCREEN, false).commit();
}
}
}
if (currentPromptIsQuestion()) {
if (!saveAnswersForCurrentScreen(EVALUATE_CONSTRAINTS)) {
// A constraint was violated so a dialog should be showing.
return;
}
}
if (mFormController.getEvent() != FormEntryController.EVENT_END_OF_FORM) {
int event;
try{
group_skip: do {
event = mFormController.stepToNextEvent(FormController.STEP_OVER_GROUP);
switch (event) {
case FormEntryController.EVENT_QUESTION:
case FormEntryController.EVENT_END_OF_FORM:
View next = createView(event);
if(!resuming) {
showView(next, AnimationType.RIGHT);
} else {
showView(next, AnimationType.FADE, false);
}
break group_skip;
case FormEntryController.EVENT_PROMPT_NEW_REPEAT:
createRepeatDialog();
break group_skip;
case FormEntryController.EVENT_GROUP:
//We only hit this event if we're at the _opening_ of a field
//list, so it seems totally fine to do it this way, technically
//though this should test whether the index is the field list
//host.
if (mFormController.indexIsInFieldList()
&& mFormController.getQuestionPrompts().length != 0) {
View nextGroupView = createView(event);
if(!resuming) {
showView(nextGroupView, AnimationType.RIGHT);
} else {
showView(nextGroupView, AnimationType.FADE, false);
}
break group_skip;
}
// otherwise it's not a field-list group, so just skip it
break;
case FormEntryController.EVENT_REPEAT:
Log.i(t, "repeat: " + mFormController.getFormIndex().getReference());
// skip repeats
break;
case FormEntryController.EVENT_REPEAT_JUNCTURE:
Log.i(t, "repeat juncture: "
+ mFormController.getFormIndex().getReference());
// skip repeat junctures until we implement them
break;
default:
Log.w(t,
"JavaRosa added a new EVENT type and didn't tell us... shame on them.");
break;
}
} while (event != FormEntryController.EVENT_END_OF_FORM);
}catch(XPathTypeMismatchException e){
Logger.exception(e);
CommCareActivity.createErrorDialog(this, e.getMessage(), EXIT);
}
} else {
mBeenSwiped = false;
}
}
/**
* Determines what should be displayed between a question, or the start screen and displays the
* appropriate view. Also saves answers to the data model without checking constraints.
*/
private void showPreviousView() {
// The answer is saved on a back swipe, but question constraints are ignored.
if (currentPromptIsQuestion()) {
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
}
FormIndex startIndex = mFormController.getFormIndex();
FormIndex lastValidIndex = startIndex;
if (mFormController.getEvent() != FormEntryController.EVENT_BEGINNING_OF_FORM) {
int event = mFormController.stepToPreviousEvent();
//Step backwards until we either find a question, the beginning of the form,
//or a field list with valid questions inside
while (event != FormEntryController.EVENT_BEGINNING_OF_FORM
&& event != FormEntryController.EVENT_QUESTION
&& !(event == FormEntryController.EVENT_GROUP
&& mFormController.indexIsInFieldList() && mFormController
.getQuestionPrompts().length != 0)) {
event = mFormController.stepToPreviousEvent();
lastValidIndex = mFormController.getFormIndex();
}
//check if we're at the beginning and not doing the whole "First screen" thing
if(event == FormEntryController.EVENT_BEGINNING_OF_FORM && !PreferencesActivity.showFirstScreen(this)) {
//If so, we can't go all the way back here, so we've gotta hit the last index that was valid
mFormController.jumpToIndex(lastValidIndex);
//Did we jump at all? (not sure how we could have, but there might be a mismatch)
if(lastValidIndex.equals(startIndex)) {
//If not, don't even bother changing the view.
//NOTE: This needs to be the same as the
//exit condition below, in case either changes
mBeenSwiped = false;
FormEntryActivity.this.triggerUserQuitInput();
return;
}
//We might have walked all the way back still, which isn't great,
//so keep moving forward again until we find it
if(lastValidIndex.isBeginningOfFormIndex()) {
//there must be a repeat between where we started and the beginning of hte form, walk back up to it
this.showNextView(true);
return;
}
}
View next = createView(event);
showView(next, AnimationType.LEFT);
} else {
//NOTE: this needs to match the exist condition above
//when there is no start screen
mBeenSwiped = false;
FormEntryActivity.this.triggerUserQuitInput();
}
}
/**
* Displays the View specified by the parameter 'next', animating both the current view and next
* appropriately given the AnimationType. Also updates the progress bar.
*/
public void showView(View next, AnimationType from) { showView(next, from, true); }
public void showView(View next, AnimationType from, boolean animateLastView) {
switch (from) {
case RIGHT:
mInAnimation = AnimationUtils.loadAnimation(this, R.anim.push_left_in);
mOutAnimation = AnimationUtils.loadAnimation(this, R.anim.push_left_out);
break;
case LEFT:
mInAnimation = AnimationUtils.loadAnimation(this, R.anim.push_right_in);
mOutAnimation = AnimationUtils.loadAnimation(this, R.anim.push_right_out);
break;
case FADE:
mInAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_in);
mOutAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_out);
break;
}
if (mCurrentView != null) {
if(animateLastView) {
mCurrentView.startAnimation(mOutAnimation);
}
mViewPane.removeView(mCurrentView);
}
mInAnimation.setAnimationListener(this);
RelativeLayout.LayoutParams lp =
new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
mCurrentView = next;
mViewPane.addView(mCurrentView, lp);
mCurrentView.startAnimation(mInAnimation);
if (mCurrentView instanceof ODKView) {
((ODKView) mCurrentView).setFocus(this);
FrameLayout header = (FrameLayout)mCurrentView.findViewById(R.id.form_entry_header);
TextView groupLabel = ((TextView)header.findViewById(R.id.form_entry_group_label));
header.setVisibility(View.GONE);
groupLabel.setVisibility(View.GONE);
String groupLabelText = ((ODKView) mCurrentView).getGroupLabel();
if(!"".equals(groupLabelText)) {
groupLabel.setText(groupLabelText);
header.setVisibility(View.VISIBLE);
groupLabel.setVisibility(View.VISIBLE);
}
} else {
InputMethodManager inputManager =
(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(mCurrentView.getWindowToken(), 0);
}
}
// Hopefully someday we can use managed dialogs when the bugs are fixed
/*
* Ideally, we'd like to use Android to manage dialogs with onCreateDialog() and
* onPrepareDialog(), but dialogs with dynamic content are broken in 1.5 (cupcake). We do use
* managed dialogs for our static loading ProgressDialog. The main issue we noticed and are
* waiting to see fixed is: onPrepareDialog() is not called after a screen orientation change.
* http://code.google.com/p/android/issues/detail?id=1639
*/
//
/**
* Creates and displays a dialog displaying the violated constraint.
*/
private void createConstraintToast(FormIndex index, String constraintText, int saveStatus, boolean requestFocus) {
switch (saveStatus) {
case FormEntryController.ANSWER_CONSTRAINT_VIOLATED:
if (constraintText == null) {
constraintText = StringUtils.getStringRobust(this, R.string.invalid_answer_error);
}
break;
case FormEntryController.ANSWER_REQUIRED_BUT_EMPTY:
constraintText = StringUtils.getStringRobust(this, R.string.required_answer_error);
break;
}
boolean displayed = false;
//We need to see if question in violation is on the screen, so we can show this cleanly.
for(QuestionWidget q : ((ODKView)mCurrentView).getWidgets()) {
if(index.equals(q.getFormId())) {
q.notifyInvalid(constraintText, requestFocus);
displayed = true;
break;
}
}
if(!displayed) {
showCustomToast(constraintText, Toast.LENGTH_SHORT);
}
mBeenSwiped = false;
}
/**
* Creates a toast with the specified message.
*
* @param message
*/
private void showCustomToast(String message, int duration) {
LayoutInflater inflater =
(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.toast_view, null);
// set the text in the view
TextView tv = (TextView) view.findViewById(R.id.message);
tv.setText(message);
Toast t = new Toast(this);
t.setView(view);
t.setDuration(duration);
t.setGravity(Gravity.CENTER, 0, 0);
t.show();
}
/**
* Creates and displays a dialog asking the user if they'd like to create a repeat of the
* current group.
*/
private void createRepeatDialog() {
ContextThemeWrapper wrapper = new ContextThemeWrapper(this, R.style.DialogBaseTheme);
View view = LayoutInflater.from(wrapper).inflate(R.layout.component_repeat_new_dialog, null);
mRepeatDialog = new AlertDialog.Builder(wrapper).create();
final AlertDialog theDialog = mRepeatDialog;
mRepeatDialog.setView(view);
mRepeatDialog.setIcon(android.R.drawable.ic_dialog_info);
boolean hasNavBar = PreferencesActivity.getProgressBarMode(this).useNavigationBar();
//this is super gross...
NavigationDetails details = null;
if(hasNavBar) {
details = calculateNavigationStatus();
}
final boolean backExitsForm = hasNavBar && !details.relevantBeforeCurrentScreen;
final boolean nextExitsForm = hasNavBar && details.relevantAfterCurrentScreen == 0;
Button back = (Button)view.findViewById(R.id.component_repeat_back);
back.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(backExitsForm) {
FormEntryActivity.this.triggerUserQuitInput();
} else {
theDialog.dismiss();
FormEntryActivity.this.refreshCurrentView(false);
}
}
});
Button newButton = (Button)view.findViewById(R.id.component_repeat_new);
newButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
theDialog.dismiss();
try {
mFormController.newRepeat();
} catch (XPathTypeMismatchException e) {
Logger.exception(e);
CommCareActivity.createErrorDialog(FormEntryActivity.this, e.getMessage(), EXIT);
return;
}
showNextView();
}
});
Button skip = (Button)view.findViewById(R.id.component_repeat_skip);
skip.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
theDialog.dismiss();
if(!nextExitsForm) {
showNextView();
} else {
triggerUserFormComplete();
}
}
});
back.setText(StringUtils.getStringSpannableRobust(this, R.string.repeat_go_back));
//Load up our icons
Drawable exitIcon = getResources().getDrawable(R.drawable.icon_exit);
exitIcon.setBounds(0, 0, exitIcon.getIntrinsicWidth(), exitIcon.getIntrinsicHeight());
Drawable doneIcon = getResources().getDrawable(R.drawable.icon_done);
doneIcon.setBounds(0, 0, doneIcon.getIntrinsicWidth(), doneIcon.getIntrinsicHeight());
if (mFormController.getLastRepeatCount() > 0) {
mRepeatDialog.setTitle(StringUtils.getStringRobust(this, R.string.leaving_repeat_ask));
mRepeatDialog.setMessage(StringUtils.getStringSpannableRobust(this, R.string.add_another_repeat,
mFormController.getLastGroupText()));
newButton.setText(StringUtils.getStringSpannableRobust(this, R.string.add_another));
if(!nextExitsForm) {
skip.setText(StringUtils.getStringSpannableRobust(this, R.string.leave_repeat_yes));
} else {
skip.setText(StringUtils.getStringSpannableRobust(this, R.string.leave_repeat_yes_exits));
}
} else {
mRepeatDialog.setTitle(StringUtils.getStringRobust(this, R.string.entering_repeat_ask));
mRepeatDialog.setMessage(StringUtils.getStringSpannableRobust(this, R.string.add_repeat,
mFormController.getLastGroupText()));
newButton.setText(StringUtils.getStringSpannableRobust(this, R.string.entering_repeat));
if(!nextExitsForm) {
skip.setText(StringUtils.getStringSpannableRobust(this, R.string.add_repeat_no));
} else {
skip.setText(StringUtils.getStringSpannableRobust(this, R.string.add_repeat_no_exits));
}
}
mRepeatDialog.setCancelable(false);
mRepeatDialog.show();
if(nextExitsForm) {
skip.setCompoundDrawables(null, doneIcon, null, null);
}
if(backExitsForm) {
back.setCompoundDrawables(null, exitIcon, null, null);
}
mBeenSwiped = false;
}
/**
* Saves form data to disk.
*
* @param exit If set, will exit program after save.
* @param complete Has the user marked the instances as complete?
* @param updatedSaveName Set name of the instance's content provider, if
* non-null
* @param headless Disables GUI warnings and lets answers that
* violate constraints be saved.
* @return Did the data save successfully?
*/
private void saveDataToDisk(boolean exit, boolean complete, String updatedSaveName, boolean headless) {
if (!formHasLoaded()) {
return;
}
// save current answer; if headless, don't evaluate the constraints
// before doing so.
if (headless &&
(!saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS, complete, headless))) {
return;
} else if (!headless &&
!saveAnswersForCurrentScreen(EVALUATE_CONSTRAINTS, complete, headless)) {
Toast.makeText(this,
StringUtils.getStringSpannableRobust(this, R.string.data_saved_error),
Toast.LENGTH_SHORT).show();
return;
}
// If a save task is already running, just let it do its thing
if ((mSaveToDiskTask != null) &&
(mSaveToDiskTask.getStatus() != AsyncTask.Status.FINISHED)) {
return;
}
mSaveToDiskTask =
new SaveToDiskTask(getIntent().getData(), exit, complete, updatedSaveName, this, instanceProviderContentURI, symetricKey, headless);
mSaveToDiskTask.setFormSavedListener(this);
mSaveToDiskTask.execute();
if (!headless) {
showDialog(SAVING_DIALOG);
}
}
/**
* Create a dialog with options to save and exit, save, or quit without saving
*/
private void createQuitDialog() {
final String[] items = mIncompleteEnabled ?
new String[] {StringUtils.getStringRobust(this, R.string.keep_changes), StringUtils.getStringRobust(this, R.string.do_not_save)} :
new String[] {StringUtils.getStringRobust(this, R.string.do_not_save)};
mAlertDialog =
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_info)
.setTitle(StringUtils.getStringRobust(this, R.string.quit_application, mFormController.getFormTitle()))
.setNeutralButton(StringUtils.getStringSpannableRobust(this, R.string.do_not_exit),
new DialogInterface.OnClickListener() {
/*
* (non-Javadoc)
* @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int)
*/
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}).setItems(items, new DialogInterface.OnClickListener() {
/*
* (non-Javadoc)
* @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int)
*/
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0: // save and exit
if(items.length == 1) {
discardChangesAndExit();
} else {
saveDataToDisk(EXIT, isInstanceComplete(false), null, false);
}
break;
case 1: // discard changes and exit
discardChangesAndExit();
break;
case 2:// do nothing
break;
}
}
}).create();
mAlertDialog.getListView().setSelector(R.drawable.selector);
mAlertDialog.show();
}
private void discardChangesAndExit() {
String selection =
InstanceColumns.INSTANCE_FILE_PATH + " like '"
+ mInstancePath + "'";
Cursor c = null;
int instanceCount = 0;
try {
c = getContentResolver().query(instanceProviderContentURI, null, selection, null, null);
instanceCount = c.getCount();
} finally {
if (c != null) {
c.close();
}
}
// if it's not already saved, erase everything
if (instanceCount < 1) {
int images = 0;
int audio = 0;
int video = 0;
// delete media first
String instanceFolder =
mInstancePath.substring(0,
mInstancePath.lastIndexOf("/") + 1);
Log.i(t, "attempting to delete: " + instanceFolder);
String where =
Images.Media.DATA + " like '" + instanceFolder + "%'";
String[] projection = {
Images.ImageColumns._ID
};
// images
Cursor imageCursor = null;
try {
imageCursor = getContentResolver().query(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, where, null, null);
if (imageCursor.getCount() > 0) {
imageCursor.moveToFirst();
String id =
imageCursor.getString(imageCursor
.getColumnIndex(Images.ImageColumns._ID));
Log.i(
t,
"attempting to delete: "
+ Uri.withAppendedPath(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
id));
images =
getContentResolver()
.delete(
Uri.withAppendedPath(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
id), null, null);
}
} finally {
if ( imageCursor != null ) {
imageCursor.close();
}
}
// audio
Cursor audioCursor = null;
try {
audioCursor = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
projection, where, null, null);
if (audioCursor.getCount() > 0) {
audioCursor.moveToFirst();
String id =
audioCursor.getString(imageCursor
.getColumnIndex(Images.ImageColumns._ID));
Log.i(
t,
"attempting to delete: "
+ Uri.withAppendedPath(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
id));
audio =
getContentResolver()
.delete(
Uri.withAppendedPath(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
id), null, null);
}
} finally {
if ( audioCursor != null ) {
audioCursor.close();
}
}
// video
Cursor videoCursor = null;
try {
videoCursor = getContentResolver().query(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
projection, where, null, null);
if (videoCursor.getCount() > 0) {
videoCursor.moveToFirst();
String id =
videoCursor.getString(imageCursor
.getColumnIndex(Images.ImageColumns._ID));
Log.i(
t,
"attempting to delete: "
+ Uri.withAppendedPath(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
id));
video =
getContentResolver()
.delete(
Uri.withAppendedPath(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
id), null, null);
}
} finally {
if ( videoCursor != null ) {
videoCursor.close();
}
}
Log.i(t, "removed from content providers: " + images
+ " image files, " + audio + " audio files,"
+ " and " + video + " video files.");
File f = new File(instanceFolder);
if (f.exists() && f.isDirectory()) {
for (File del : f.listFiles()) {
Log.i(t, "deleting file: " + del.getAbsolutePath());
del.delete();
}
f.delete();
}
}
finishReturnInstance(false);
}
/**
* Confirm clear answer dialog
*/
private void createClearDialog(final QuestionWidget qw) {
mAlertDialog = new AlertDialog.Builder(this).create();
mAlertDialog.setIcon(android.R.drawable.ic_dialog_info);
mAlertDialog.setTitle(StringUtils.getStringRobust(this, R.string.clear_answer_ask));
String question = qw.getPrompt().getLongText();
if (question.length() > 50) {
question = question.substring(0, 50) + "...";
}
mAlertDialog.setMessage(StringUtils.getStringSpannableRobust(this, R.string.clearanswer_confirm, question));
DialogInterface.OnClickListener quitListener = new DialogInterface.OnClickListener() {
/*
* (non-Javadoc)
* @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int)
*/
@Override
public void onClick(DialogInterface dialog, int i) {
switch (i) {
case DialogInterface.BUTTON1: // yes
clearAnswer(qw);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
break;
case DialogInterface.BUTTON2: // no
break;
}
}
};
mAlertDialog.setCancelable(false);
mAlertDialog.setButton(StringUtils.getStringSpannableRobust(this, R.string.discard_answer), quitListener);
mAlertDialog.setButton2(StringUtils.getStringSpannableRobust(this, R.string.clear_answer_no), quitListener);
mAlertDialog.show();
}
/**
* Creates and displays a dialog allowing the user to set the language for the form.
*/
private void createLanguageDialog() {
final String[] languages = mFormController.getLanguages();
int selected = -1;
if (languages != null) {
String language = mFormController.getLanguage();
for (int i = 0; i < languages.length; i++) {
if (language.equals(languages[i])) {
selected = i;
}
}
}
mAlertDialog =
new AlertDialog.Builder(this)
.setSingleChoiceItems(languages, selected,
new DialogInterface.OnClickListener() {
/*
* (non-Javadoc)
* @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int)
*/
@Override
public void onClick(DialogInterface dialog, int whichButton) {
// Update the language in the content provider when selecting a new
// language
ContentValues values = new ContentValues();
values.put(FormsColumns.LANGUAGE, languages[whichButton]);
String selection = FormsColumns.FORM_FILE_PATH + "=?";
String selectArgs[] = {
mFormPath
};
int updated =
getContentResolver().update(formProviderContentURI, values,
selection, selectArgs);
Log.i(t, "Updated language to: " + languages[whichButton] + " in "
+ updated + " rows");
mFormController.setLanguage(languages[whichButton]);
dialog.dismiss();
if (currentPromptIsQuestion()) {
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
}
refreshCurrentView();
}
})
.setTitle(StringUtils.getStringRobust(this, R.string.change_language))
.setNegativeButton(StringUtils.getStringSpannableRobust(this, R.string.do_not_change),
new DialogInterface.OnClickListener() {
/*
* (non-Javadoc)
* @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int)
*/
@Override
public void onClick(DialogInterface dialog, int whichButton) {
}
}).create();
mAlertDialog.show();
}
/*
* (non-Javadoc)
* @see android.app.Activity#onCreateDialog(int)
*
* We use Android's dialog management for loading/saving progress dialogs
*/
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case PROGRESS_DIALOG:
mProgressDialog = new ProgressDialog(this);
DialogInterface.OnClickListener loadingButtonListener =
new DialogInterface.OnClickListener() {
/*
* (non-Javadoc)
* @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int)
*/
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mFormLoaderTask.setFormLoaderListener(null);
mFormLoaderTask.cancel(true);
finish();
}
};
mProgressDialog.setIcon(android.R.drawable.ic_dialog_info);
mProgressDialog.setTitle(StringUtils.getStringRobust(this, R.string.loading_form));
mProgressDialog.setMessage(StringUtils.getStringSpannableRobust(this, R.string.please_wait));
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.setButton(StringUtils.getStringSpannableRobust(this, R.string.cancel_loading_form),
loadingButtonListener);
return mProgressDialog;
case SAVING_DIALOG:
mProgressDialog = new ProgressDialog(this);
DialogInterface.OnClickListener savingButtonListener =
new DialogInterface.OnClickListener() {
/*
* (non-Javadoc)
* @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int)
*/
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mSaveToDiskTask.setFormSavedListener(null);
mSaveToDiskTask.cancel(true);
}
};
mProgressDialog.setIcon(android.R.drawable.ic_dialog_info);
mProgressDialog.setTitle(StringUtils.getStringRobust(this, R.string.saving_form));
mProgressDialog.setMessage(StringUtils.getStringSpannableRobust(this, R.string.please_wait));
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.setButton(StringUtils.getStringSpannableRobust(this, R.string.cancel), savingButtonListener);
mProgressDialog.setButton(StringUtils.getStringSpannableRobust(this, R.string.cancel_saving_form),
savingButtonListener);
return mProgressDialog;
}
return null;
}
/**
* Dismiss any showing dialogs that we manually manage.
*/
private void dismissDialogs() {
if (mAlertDialog != null && mAlertDialog.isShowing()) {
mAlertDialog.dismiss();
}
if(mRepeatDialog != null && mRepeatDialog.isShowing()) {
mRepeatDialog.dismiss();
}
}
/*
* (non-Javadoc)
* @see android.support.v4.app.FragmentActivity#onPause()
*/
@Override
protected void onPause() {
super.onPause();
dismissDialogs();
if (mCurrentView != null && currentPromptIsQuestion()) {
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
}
if (mNoGPSReceiver != null) {
unregisterReceiver(mNoGPSReceiver);
}
}
/*
* (non-Javadoc)
* @see android.support.v4.app.FragmentActivity#onResume()
*/
@Override
protected void onResume() {
super.onResume();
registerFormEntryReceivers();
if (mFormLoaderTask != null) {
mFormLoaderTask.setFormLoaderListener(this);
if (mFormController != null && mFormLoaderTask.getStatus() == AsyncTask.Status.FINISHED) {
dismissDialog(PROGRESS_DIALOG);
refreshCurrentView();
}
}
if (mSaveToDiskTask != null) {
mSaveToDiskTask.setFormSavedListener(this);
}
if (mErrorMessage != null && (mAlertDialog != null && !mAlertDialog.isShowing())) {
CommCareActivity.createErrorDialog(this, mErrorMessage, EXIT);
return;
}
//[email protected] - 22/08/2012 - For release only, fix immediately.
//There is a _horribly obnoxious_ bug in TimePickers that messes up how they work
//on screen rotation. We need to re-do any setAnswers that we perform on them after
//onResume.
try {
if(mCurrentView instanceof ODKView) {
ODKView ov = ((ODKView) mCurrentView);
if(ov.getWidgets() != null) {
for(QuestionWidget qw : ov.getWidgets()) {
if(qw instanceof DateTimeWidget) {
((DateTimeWidget)qw).setAnswer();
} else if(qw instanceof TimeWidget) {
((TimeWidget)qw).setAnswer();
}
}
}
}
} catch(Exception e) {
//if this fails, we _really_ don't want to mess anything up. this is a last minute
//fix
}
}
/**
* Call when the user provides input that they want to quit the form
*/
private void triggerUserQuitInput() {
//If we're just reviewing a read only form, don't worry about saving
//or what not, just quit
if(mFormController.isFormReadOnly()) {
//It's possible we just want to "finish" here, but
//I don't really wanna break any c compatibility
finishReturnInstance(false);
} else {
createQuitDialog();
}
}
/**
* Get the default title for ODK's "Form title" field
*
* @return
*/
private String getDefaultFormTitle() {
String saveName = mFormController.getFormTitle();
if (getContentResolver().getType(getIntent().getData()) == InstanceColumns.CONTENT_ITEM_TYPE) {
Uri instanceUri = getIntent().getData();
Cursor instance = null;
try {
instance = getContentResolver().query(instanceUri, null, null, null, null);
if (instance.getCount() == 1) {
instance.moveToFirst();
saveName =
instance.getString(instance
.getColumnIndex(InstanceColumns.DISPLAY_NAME));
}
} finally {
if (instance != null) {
instance.close();
}
}
}
return saveName;
}
/**
* Call when the user is ready to save and return the current form as complete
*/
private void triggerUserFormComplete() {
saveDataToDisk(EXIT, true, getDefaultFormTitle(), false);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
triggerUserQuitInput();
return true;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (event.isAltPressed() && !mBeenSwiped) {
mBeenSwiped = true;
showNextView();
return true;
}
break;
case KeyEvent.KEYCODE_DPAD_LEFT:
if (event.isAltPressed() && !mBeenSwiped) {
mBeenSwiped = true;
showPreviousView();
return true;
}
break;
}
return super.onKeyDown(keyCode, event);
}
/*
* (non-Javadoc)
* @see android.support.v4.app.FragmentActivity#onDestroy()
*/
@Override
protected void onDestroy() {
if (mFormLoaderTask != null) {
mFormLoaderTask.setFormLoaderListener(null);
// We have to call cancel to terminate the thread, otherwise it
// lives on and retains the FEC in memory.
// but only if it's done, otherwise the thread never returns
if (mFormLoaderTask.getStatus() == AsyncTask.Status.FINISHED) {
mFormLoaderTask.cancel(true);
mFormLoaderTask.destroy();
}
}
if (mSaveToDiskTask != null) {
mSaveToDiskTask.setFormSavedListener(null);
// We have to call cancel to terminate the thread, otherwise it
// lives on and retains the FEC in memory.
if (mSaveToDiskTask.getStatus() == AsyncTask.Status.FINISHED) {
mSaveToDiskTask.cancel(false);
}
}
super.onDestroy();
}
/*
* (non-Javadoc)
* @see android.view.animation.Animation.AnimationListener#onAnimationEnd(android.view.animation.Animation)
*/
@Override
public void onAnimationEnd(Animation arg0) {
mBeenSwiped = false;
}
/*
* (non-Javadoc)
* @see android.view.animation.Animation.AnimationListener#onAnimationRepeat(android.view.animation.Animation)
*/
@Override
public void onAnimationRepeat(Animation animation) {
// Added by AnimationListener interface.
}
/*
* (non-Javadoc)
* @see android.view.animation.Animation.AnimationListener#onAnimationStart(android.view.animation.Animation)
*/
@Override
public void onAnimationStart(Animation animation) {
// Added by AnimationListener interface.
}
/*
* (non-Javadoc)
* @see org.odk.collect.android.listeners.FormLoaderListener#loadingComplete(org.odk.collect.android.logic.FormController)
*
* loadingComplete() is called by FormLoaderTask once it has finished loading a form.
*/
@SuppressLint("NewApi")
@Override
public void loadingComplete(FormController fc) {
dismissDialog(PROGRESS_DIALOG);
mFormController = fc;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
// Newer menus may have already built the menu, before all data was ready
invalidateOptionsMenu();
}
Localizer mLocalizer = Localization.getGlobalLocalizerAdvanced();
if(mLocalizer != null){
String mLocale = mLocalizer.getLocale();
if (mLocale != null && fc.getLanguages() != null && Arrays.asList(fc.getLanguages()).contains(mLocale)){
fc.setLanguage(mLocale);
}
else{
Logger.log("formloader", "The current locale is not set");
}
} else{
Logger.log("formloader", "Could not get the localizer");
}
// Set saved answer path
if (mInstancePath == null) {
// Create new answer folder.
String time =
new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss")
.format(Calendar.getInstance().getTime());
String file =
mFormPath.substring(mFormPath.lastIndexOf('/') + 1, mFormPath.lastIndexOf('.'));
String path = mInstanceDestination + "/" + file + "_" + time;
if (FileUtils.createFolder(path)) {
mInstancePath = path + "/" + file + "_" + time + ".xml";
}
} else {
// we've just loaded a saved form, so start in the hierarchy view
Intent i = new Intent(this, FormHierarchyActivity.class);
startActivityForResult(i, HIERARCHY_ACTIVITY_FIRST_START);
return; // so we don't show the intro screen before jumping to the hierarchy
}
//mFormController.setLanguage(mFormController.getLanguage());
/* here was code that loaded cached language preferences fin the
* collect code. we've overridden that to use our language
* from the shared preferences
*/
refreshCurrentView();
updateNavigationCues(this.mCurrentView);
}
/*
* (non-Javadoc)
* @see org.odk.collect.android.listeners.FormLoaderListener#loadingError(java.lang.String)
*
* called by the FormLoaderTask if something goes wrong.
*/
@Override
public void loadingError(String errorMsg) {
dismissDialog(PROGRESS_DIALOG);
if (errorMsg != null) {
CommCareActivity.createErrorDialog(this, errorMsg, EXIT);
} else {
CommCareActivity.createErrorDialog(this, StringUtils.getStringRobust(this, R.string.parse_error), EXIT);
}
}
/**
* {@inheritDoc}
*
* Display save status notification and exit or continue on in the form.
* If form entry is being saved because key session is expiring then
* continue closing the session/logging out.
*
* @see org.odk.collect.android.listeners.FormSavedListener#savingComplete(int, boolean)
*/
@Override
public void savingComplete(int saveStatus, boolean headless) {
if (!headless) {
dismissDialog(SAVING_DIALOG);
}
// Did we just save a form because the key session
// (CommCareSessionService) is ending?
if (savingFormOnKeySessionExpiration) {
savingFormOnKeySessionExpiration = false;
// Notify the key session that the form state has been saved (or at
// least attempted to be saved) so CommCareSessionService can
// continue closing down key pool and user database.
try {
CommCareApplication._().getSession().closeSession(true);
} catch (SessionUnavailableException sue) {
// form saving took too long, so we logged out already.
Logger.log(AndroidLogger.TYPE_ERROR_WORKFLOW,
"Saving current form took too long, " +
"so data was (probably) discarded and the session closed. " +
"Save exit code: " + saveStatus);
}
} else {
switch (saveStatus) {
case SaveToDiskTask.SAVED:
Toast.makeText(this, StringUtils.getStringSpannableRobust(this, R.string.data_saved_ok), Toast.LENGTH_SHORT).show();
hasSaved = true;
break;
case SaveToDiskTask.SAVED_AND_EXIT:
Toast.makeText(this, StringUtils.getStringSpannableRobust(this, R.string.data_saved_ok), Toast.LENGTH_SHORT).show();
hasSaved = true;
finishReturnInstance();
break;
case SaveToDiskTask.SAVE_ERROR:
Toast.makeText(this, StringUtils.getStringSpannableRobust(this, R.string.data_saved_error), Toast.LENGTH_LONG).show();
break;
case FormEntryController.ANSWER_CONSTRAINT_VIOLATED:
case FormEntryController.ANSWER_REQUIRED_BUT_EMPTY:
refreshCurrentView();
// an answer constraint was violated, so do a 'swipe' to the next
// question to display the proper toast(s)
next();
break;
}
}
}
/**
* Attempts to save an answer to the specified index.
*
* @param answer
* @param index
* @param evaluateConstraints Should form contraints be checked when saving answer?
* @return status as determined in FormEntryController
*/
public int saveAnswer(IAnswerData answer, FormIndex index, boolean evaluateConstraints) {
try {
if (evaluateConstraints) {
return mFormController.answerQuestion(index, answer);
} else {
mFormController.saveAnswer(index, answer);
return FormEntryController.ANSWER_OK;
}
} catch(XPathException e) {
//this is where runtime exceptions get triggered after the form has loaded
CommCareActivity.createErrorDialog(this, "There is a bug in one of your form's XPath Expressions \n" + e.getMessage(), EXIT);
//We're exiting anyway
return FormEntryController.ANSWER_OK;
}
}
/**
* Checks the database to determine if the current instance being edited has already been
* 'marked completed'. A form can be 'unmarked' complete and then resaved.
*
* @return true if form has been marked completed, false otherwise.
*/
private boolean isInstanceComplete(boolean end) {
// default to false if we're mid form
boolean complete = false;
// if we're at the end of the form, then check the preferences
if (end) {
// First get the value from the preferences
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(this);
complete =
sharedPreferences.getBoolean(PreferencesActivity.KEY_COMPLETED_DEFAULT, true);
}
// Then see if we've already marked this form as complete before
String selection = InstanceColumns.INSTANCE_FILE_PATH + "=?";
String[] selectionArgs = {
mInstancePath
};
Cursor c = null;
try {
c = getContentResolver().query(instanceProviderContentURI, null, selection, selectionArgs, null);
if (c != null && c.getCount() > 0) {
c.moveToFirst();
String status = c.getString(c.getColumnIndex(InstanceColumns.STATUS));
if (InstanceProviderAPI.STATUS_COMPLETE.compareTo(status) == 0) {
complete = true;
}
}
} finally {
if (c != null) {
c.close();
}
}
return complete;
}
public void next() {
if (!mBeenSwiped) {
mBeenSwiped = true;
showNextView();
}
}
private void finishReturnInstance() {
finishReturnInstance(true);
}
/**
* Returns the instance that was just filled out to the calling activity,
* if requested.
*
* @param reportSaved was a form saved? Delegates the result code of the
* activity
*/
private void finishReturnInstance(boolean reportSaved) {
String action = getIntent().getAction();
if (Intent.ACTION_PICK.equals(action) || Intent.ACTION_EDIT.equals(action)) {
// caller is waiting on a picked form
String selection = InstanceColumns.INSTANCE_FILE_PATH + "=?";
String[] selectionArgs = {
mInstancePath
};
Cursor c = null;
try {
c = getContentResolver().query(instanceProviderContentURI, null, selection, selectionArgs, null);
if (c.getCount() > 0) {
// should only be one...
c.moveToFirst();
String id = c.getString(c.getColumnIndex(InstanceColumns._ID));
Uri instance = Uri.withAppendedPath(instanceProviderContentURI, id);
Intent formReturnIntent = new Intent();
formReturnIntent.putExtra(IS_ARCHIVED_FORM, mFormController.isFormReadOnly());
if (reportSaved || hasSaved) {
setResult(RESULT_OK, formReturnIntent.setData(instance));
} else {
setResult(RESULT_CANCELED, formReturnIntent.setData(instance));
}
}
} finally {
if (c != null) {
c.close();
}
}
}
try {
CommCareApplication._().getSession().unregisterFormSaveCallback();
} catch (SessionUnavailableException sue) {
// looks like the session expired
}
this.dismissDialogs();
finish();
}
/*
* (non-Javadoc)
* @see android.view.GestureDetector.OnGestureListener#onDown(android.view.MotionEvent)
*/
@Override
public boolean onDown(MotionEvent e) {
return false;
}
/*
* Looks for user swipes. If the user has swiped, move to the appropriate screen.
* (non-Javadoc)
* @see android.view.GestureDetector.OnGestureListener#onFling(android.view.MotionEvent, android.view.MotionEvent, float, float)
*/
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if (CommCareActivity.isHorizontalSwipe(this, e1, e2)) {
mBeenSwiped = true;
if (velocityX > 0) {
showPreviousView();
} else {
int event = mFormController.getEvent(mFormController.getNextFormIndex(mFormController.getFormIndex(), true));
boolean navBar = PreferencesActivity.getProgressBarMode(this).useNavigationBar();
if(!navBar || (navBar && event != FormEntryController.EVENT_END_OF_FORM)) {
showNextView();
}
}
return true;
}
return false;
}
/*
* (non-Javadoc)
* @see android.view.GestureDetector.OnGestureListener#onLongPress(android.view.MotionEvent)
*/
@Override
public void onLongPress(MotionEvent e) {
}
/*
* (non-Javadoc)
* @see android.view.GestureDetector.OnGestureListener#onScroll(android.view.MotionEvent, android.view.MotionEvent, float, float)
*/
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
// The onFling() captures the 'up' event so our view thinks it gets long pressed.
// We don't wnat that, so cancel it.
mCurrentView.cancelLongPress();
return false;
}
/*
* (non-Javadoc)
* @see android.view.GestureDetector.OnGestureListener#onShowPress(android.view.MotionEvent)
*/
@Override
public void onShowPress(MotionEvent e) {
}
/*
* (non-Javadoc)
* @see android.view.GestureDetector.OnGestureListener#onSingleTapUp(android.view.MotionEvent)
*/
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
/*
* (non-Javadoc)
* @see org.odk.collect.android.listeners.AdvanceToNextListener#advance()
*/
@Override
public void advance() {
next();
}
/*
* (non-Javadoc)
* @see org.odk.collect.android.listeners.WidgetChangedListener#widgetEntryChanged()
*/
@Override
public void widgetEntryChanged() {
updateFormRelevencies();
updateNavigationCues(this.mCurrentView);
}
/**
* Has form loading (via FormLoaderTask) completed?
*/
private boolean formHasLoaded() {
return mFormController != null;
}
}
|
Save changes to view in model
|
app/src/org/odk/collect/android/activities/FormEntryActivity.java
|
Save changes to view in model
|
<ide><path>pp/src/org/odk/collect/android/activities/FormEntryActivity.java
<ide> Toast.makeText(FormEntryActivity.this,
<ide> StringUtils.getStringSpannableRobust(FormEntryActivity.this, R.string.attachment_invalid),
<ide> Toast.LENGTH_LONG).show();
<del> return;
<ide> } else {
<ide> ((ODKView) mCurrentView).setBinaryData(media);
<del> saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
<del> refreshCurrentView();
<del> }
<add> }
<add> saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
<add> refreshCurrentView();
<ide> break;
<ide> case LOCATION_CAPTURE:
<ide> String sl = intent.getStringExtra(LOCATION_RESULT);
|
|
Java
|
apache-2.0
|
d876849858be78ab98cdda7346304d6ca96dcac6
| 0 |
hal/elemento,hal/elemento
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* 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.jboss.gwt.elemento.core;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Stack;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterables;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;
import elemental.client.Browser;
import elemental.dom.Document;
import elemental.dom.Element;
import elemental.dom.NodeList;
import elemental.events.EventListener;
import elemental.html.InputElement;
import org.jetbrains.annotations.NonNls;
import static java.util.Arrays.asList;
/**
* Helper methods for working with {@link Element}s.
*
* @author Harald Pehl
*/
public final class Elements {
// this is a static helper class which must never be instantiated!
private Elements() {}
static class ElementInfo {
int level;
Element element;
boolean container;
ElementInfo(final Element element, final boolean container, final int level) {
this.container = container;
this.element = element;
this.level = level;
}
@Override
public String toString() {
return (container ? "container" : "simple") + " @ " + level + ": " + element.getTagName();
}
}
/**
* Builder to create a hierarchy of {@link Element}s. Supports convenience methods to create common elements
* and attributes. Uses a fluent API to create and append elements on the fly.
* <p>
* The builder distinguishes between elements which can contain nested elements (container) and simple element w/o
* children. The former must be closed using {@link #end()}.
* <p>
* In order to create this form,
* <pre>
* <section class="main">
* <input class="toggle-all" type="checkbox">
* <label for="toggle-all">Mark all as complete</label>
* <ul class="todo-list">
* <li>
* <div class="view">
* <input class="toggle" type="checkbox" checked>
* <label>Taste Elemento</label>
* <button class="destroy"></button>
* </div>
* <input class="edit">
* </li>
* </ul>
* </section>
* </pre>
* <p>
* use the following builder code:
* <pre>
* Element element = new Elements.Builder()
* .section().css("main")
* .input(checkbox).css("toggle-all")
* .label().attr("for", "toggle-all").textContent("Mark all as complete").end()
* .ul().css("todo-list")
* .li()
* .div().css("view")
* .input(checkbox).css("toggle")
* .label().textContent("Taste Elemento").end()
* .button().css("destroy").end()
* .end()
* .input(text).css("edit")
* .end()
* .end()
* .end().build();
* </pre>
*
* @author Harald Pehl
*/
public static class Builder extends CoreBuilder<Builder> {
public Builder() {
super("elements.builder");
}
@Override
protected Builder that() {
return this;
}
}
public static abstract class CoreBuilder<B extends CoreBuilder<B>> {
private final String id;
private final Document document;
private final Stack<ElementInfo> elements;
private final Map<String, Element> references;
private int level;
/**
* Creates a new builder.
*
* @param id an unique id which is used in error messages
*/
protected CoreBuilder(@NonNls String id) {
this(id, Browser.getDocument());
}
/**
* Creates a new builder.
*
* @param id an unique id which is used in error messages
* @param document a reference to the document
*/
protected CoreBuilder(@NonNls String id, Document document) {
this.id = id;
this.document = document;
this.elements = new Stack<>();
this.references = new HashMap<>();
}
private String logId() {
return "<" + id + "> ";
}
/**
* In order to make builders work with inheritance, sub-builders must return a reference to their instance.
*
* @return {@code this}
*/
protected abstract B that();
// ------------------------------------------------------ container elements
/**
* Starts a new {@code <header>} container. The element must be closed with {@link #end()}.
*/
public B header() {
return start("header");
}
/**
* Starts a new {@code <h&>} container. The element must be closed with {@link #end()}.
*/
public B h(int ordinal) {
return start("h" + ordinal);
}
/**
* Starts a new {@code <h&>} container with the specified inner text.
* The element must be closed with {@link #end()}.
*/
public B h(int ordinal, String text) {
return start("h" + ordinal).textContent(text);
}
/**
* Starts a new {@code <section>} container. The element must be closed with {@link #end()}.
*/
public B section() {
return start(document.createElement("section"));
}
/**
* Starts a new {@code <aside>} container. The element must be closed with {@link #end()}.
*/
public B aside() {
return start(document.createElement("aside"));
}
/**
* Starts a new {@code <footer>} container. The element must be closed with {@link #end()}.
*/
public B footer() {
return start(document.createElement("footer"));
}
/**
* Starts a new {@code <p>} container. The element must be closed with {@link #end()}.
*/
public B p() {
return start(document.createElement("p"));
}
/**
* Starts a new {@code <ol>} container. The element must be closed with {@link #end()}.
*/
public B ol() {
return start(document.createElement("ol"));
}
/**
* Starts a new {@code <ul>} container. The element must be closed with {@link #end()}.
*/
public B ul() {
return start(document.createElement("ul"));
}
/**
* Starts a new {@code <li>} container. The element must be closed with {@link #end()}.
*/
public B li() {
return start(document.createLIElement());
}
/**
* Starts a new {@code <a>} container. The element must be closed with {@link #end()}.
*/
public B a() {
return start(document.createElement("a"));
}
/**
* Starts a new {@code <a>} container with the specified href.
* The element must be closed with {@link #end()}.
*/
public B a(@NonNls String href) {
return start(document.createElement("a")).attr("href", href);
}
/**
* Starts a new {@code <div>} container. The element must be closed with {@link #end()}.
*/
public B div() {
return start(document.createDivElement());
}
/**
* Starts a new {@code <span>} container. The element must be closed with {@link #end()}.
*/
public B span() {
return start(document.createSpanElement());
}
/**
* Starts the named container. The element must be closed with {@link #end()}.
*/
public B start(@NonNls String tag) {
return start(document.createElement(tag));
}
/**
* Adds the given element as new container. The element must be closed with {@link #end()}.
*/
public B start(Element element) {
elements.push(new ElementInfo(element, true, level));
level++;
return that();
}
/**
* Closes the current container element.
*
* @throws IllegalStateException if there's no current element or if the closing element is no container.
*/
public B end() {
assertCurrent();
if (level == 0) {
throw new IllegalStateException(
logId() + "Unbalanced element hierarchy. Elements stack: " + dumpElements());
}
List<ElementInfo> children = new ArrayList<>();
while (elements.peek().level == level) {
children.add(elements.pop());
}
Collections.reverse(children);
if (!elements.peek().container) {
throw new IllegalStateException(
logId() + "Closing element " + elements.peek().element + " is no container");
}
Element closingElement = elements.peek().element;
for (ElementInfo child : children) {
closingElement.appendChild(child.element);
}
level--;
return that();
}
private String dumpElements() {
return elements.toString();
}
// ------------------------------------------------------ table elements
public B table() {
return start("table");
}
public B thead() {
return start("thead");
}
public B tbody() {
return start("tbody");
}
public B tfoot() {
return start("tfoot");
}
public B tr() {
return start("tr");
}
public B th() {
return start("th");
}
public B td() {
return start("td");
}
// ------------------------------------------------------ form elements
/**
* Starts a new form. The element must be closed with {@link #end()}.
*/
public B form() {
return start(document.createFormElement());
}
/**
* Starts a new form label. The element must be closed with {@link #end()}.
*/
public B label() {
return start(document.createLabelElement());
}
/**
* Starts a new form label with the specified inner text.
* The element must be closed with {@link #end()}.
*/
public B label(String text) {
return start(document.createLabelElement()).textContent(text);
}
/**
* Starts a new button. The element must be closed with {@link #end()}.
*/
public B button() {
return input(InputType.button);
}
/**
* Starts a new button with the specified inner text.
* The element must be closed with {@link #end()}.
*/
public B button(String text) {
return input(InputType.button).textContent(text);
}
/**
* Starts a new select box. The element must be closed with {@link #end()}.
*/
public B select() {
return input(InputType.select);
}
/**
* Starts an option to be used inside a select box. The element must be closed with {@link #end()}.
*/
public B option() {
return start(document.createOptionElement());
}
/**
* Starts an option with the specified inner text. The element must be closed with {@link #end()}.
*/
public B option(String text) {
return start(document.createOptionElement()).textContent(text);
}
/**
* Starts a new textarea. The element must be closed with {@link #end()}.
*/
public B textarea() {
return input(InputType.textarea);
}
/**
* Creates the given input field. See {@link InputType} for details
* whether a container or simple element is created.
*/
public B input(InputType type) {
switch (type) {
case button:
start(document.createButtonElement());
break;
case color:
case checkbox:
case date:
case datetime:
case email:
case file:
case hidden:
case image:
case month:
case number:
case password:
case radio:
case range:
case reset:
case search:
case tel:
case text:
case time:
case url:
case week:
InputElement inputElement = document.createInputElement();
inputElement.setType(type.name());
add(inputElement);
break;
case select:
start(document.createSelectElement());
break;
case textarea:
start(document.createTextAreaElement());
break;
}
return that();
}
// ------------------------------------------------------ simple element(s)
/**
* Creates and adds the named element. The element must not be closed using {@link #end()}.
*/
public B add(@NonNls String tag) {
return add(document.createElement(tag));
}
/**
* Add the given element by calling {@code element.asElement()}. The element must not be closed using {@link
* #end()}.
*/
public B add(IsElement element) {
return add(element.asElement());
}
/**
* Adds all elements from {@code elements.asElements()}.
*/
public B addAll(HasElements elements) {
return addAll(elements.asElements());
}
/**
* Adds all elements.
*/
public B addAll(Iterable<Element> elements) {
for (Element element : elements) {
add(element);
}
return that();
}
/**
* Adds the given element. The element must not be closed using {@link #end()}.
*/
public B add(Element element) {
assertCurrent();
elements.push(new ElementInfo(element, false, level));
return that();
}
// ------------------------------------------------------ modify current element
/**
* Sets the id of the last added element.
*/
public B id(@NonNls String id) {
assertCurrent();
elements.peek().element.setId(id);
return that();
}
/**
* Sets the title of the last added element.
*/
public B title(String title) {
assertCurrent();
elements.peek().element.setTitle(title);
return that();
}
/**
* Sets the css classes for the last added element.
*/
public B css(@NonNls String classes) {
//noinspection NullArgumentToVariableArgMethod
return css(classes, null);
}
/**
* Sets the css classes for the last added element.
*/
public B css(@NonNls String first, @NonNls String... rest) {
assertCurrent();
List<String> classes = new ArrayList<>();
classes.add(first);
if (rest != null) {
classes.addAll(asList(rest));
}
String combined = rest != null && rest.length != 0
? Joiner.on(' ').skipNulls().join(classes)
: first;
elements.peek().element.setClassName(combined);
return that();
}
/**
* Sets the css style for the last added element.
*/
public B style(@NonNls String style) {
assertCurrent();
elements.peek().element.getStyle().setCssText(style);
return that();
}
/**
* Adds an attribute to the last added element.
*/
public B attr(@NonNls String name, String value) {
assertCurrent();
elements.peek().element.setAttribute(name, value);
return that();
}
/**
* Adds a {@code data-} attribute to the last added element.
*
* @param name The name of the data attribute w/o the {@code data-} prefix. However it won't be added if it's
* already present.
*/
public B data(@NonNls String name, String value) {
String safeName = name.startsWith("data-") ? name.substring("data-".length()) : name;
elements.peek().element.getDataset().setAt(safeName, value);
return that();
}
/**
* Adds an {@code aria-} attribute to the last added element.
*
* @param name The name of the aria attribute w/o the {@code aria-} prefix. However it won't be added if it's
* already present.
*/
public B aria(@NonNls String name, String value) {
String safeName = name.startsWith("aria-") ? name : "aria-" + name;
return attr(safeName, value);
}
/**
* Sets the inner HTML on the last added element.
*/
public B innerHtml(SafeHtml html) {
assertCurrent();
elements.peek().element.setInnerHTML(html.asString());
return that();
}
/**
* Sets the inner text on the last added element using {@link Element#setTextContent(String)}.
*
* @deprecated Use {@link #textContent(String)} instead.
*/
@Deprecated
public B innerText(String text) {
assertCurrent();
elements.peek().element.setTextContent(text);
return that();
}
/**
* Sets the inner text on the last added element using {@link Element#setTextContent(String)}.
*/
public B textContent(String text) {
assertCurrent();
elements.peek().element.setTextContent(text);
return that();
}
private void assertCurrent() {
if (elements.isEmpty()) {
throw new IllegalStateException(logId() + "No current element");
}
}
// ------------------------------------------------------ event handler
/**
* Adds the given event listener to the the last added element.
*/
public B on(EventType type, EventListener listener) {
assertCurrent();
Element element = elements.peek().element;
type.register(element, listener);
return that();
}
// ------------------------------------------------------ references
/**
* Stores a named reference for the last added element. The element can be retrieved later on using
* {@link #referenceFor(String)}.
*/
public B rememberAs(@NonNls String id) {
assertCurrent();
references.put(id, elements.peek().element);
return that();
}
/**
* Returns the element which was stored using {@link #rememberAs(String)}.
*
* @throws NoSuchElementException if no element was stored under that id.
*/
@SuppressWarnings("unchecked")
public <T extends Element> T referenceFor(@NonNls String id) {
if (!references.containsKey(id)) {
throw new NoSuchElementException(logId() + "No element reference found for '" + id + "'");
}
return (T) references.get(id);
}
// ------------------------------------------------------ builder
/**
* Builds the element hierarchy and returns the top level element casted to the specified element type.
*
* @param <T> The target element type
*
* @throws IllegalStateException If the hierarchy is unbalanced.
*/
@SuppressWarnings("unchecked")
public <T extends Element> T build() {
if (level != 0 && elements.size() != 1) {
throw new IllegalStateException(
logId() + "Unbalanced element hierarchy. Elements stack: " + dumpElements());
}
return (T) elements.pop().element;
}
/**
* Returns the top level elements added so far. This is useful if you don't want to build a single root
* container, but work with a list of elements.
*/
public Iterable<Element> elements() {
if (level != 0) {
throw new IllegalStateException(
logId() + "Unbalanced element hierarchy. Elements stack: " + dumpElements());
}
if (elements.isEmpty()) {
throw new IllegalStateException(logId() + "Empty elements stack");
}
//noinspection StaticPseudoFunctionalStyleMethod
return Iterables.transform(this.elements, elementInfo -> elementInfo.element);
}
}
// ------------------------------------------------------ element helper methods
/**
* Returns an iterator over the children of the given parent element. The iterator supports the {@link
* Iterator#remove()} operation which removes the current element from its parent.
*/
public static Iterator<Element> iterator(Element parent) {
return parent != null ? new ChildrenIterator(parent) : Collections.<Element>emptyList().iterator();
}
/**
* Returns a stream for the children of the given parent element.
*/
public static Stream<Element> stream(Element parent) {
return parent != null ? StreamSupport.stream(children(parent).spliterator(), false) : Stream.empty();
}
/**
* Returns an iterable collection for the children of the given parent element.
*/
public static Iterable<Element> children(Element parent) {
return () -> iterator(parent);
}
/**
* Returns an iterator over the given node list. The iterator will only iterate over elements while skipping nodes.
* The iterator does <strong>not</strong> support the {@link Iterator#remove()} operation.
*/
public static Iterator<Element> iterator(NodeList nodes) {
return nodes != null ? new NodeListIterator(nodes) : Collections.<Element>emptyList().iterator();
}
/**
* Returns a stream for the elements in the given node list.
*/
public static Stream<Element> stream(NodeList nodes) {
return nodes != null ? StreamSupport.stream(elements(nodes).spliterator(), false) : Stream.empty();
}
/**
* Returns an iterable collection for the elements in the given node list.
*/
public static Iterable<Element> elements(NodeList nodes) {
return () -> iterator(nodes);
}
/**
* Convenience method to set the inner HTML of the given element.
*/
public static void innerHtml(Element element, SafeHtml html) {
if (element != null) {
element.setInnerHTML(html.asString());
}
}
/**
* Appends the specified element to the parent element if not already present. If parent already contains child,
* this method does nothing.
*/
public static void lazyAppend(final Element parent, final Element child) {
if (!parent.contains(child)) {
parent.appendChild(child);
}
}
/**
* Inserts the specified element into the parent element if not already present. If parent already contains child,
* this method does nothing.
*/
public static void lazyInsertBefore(final Element parent, final Element child, final Element before) {
if (!parent.contains(child)) {
parent.insertBefore(child, before);
}
}
/**
* Removes all child elements from {@code element}
*/
public static void removeChildrenFrom(final Element element) {
if (element != null) {
while (element.getFirstChild() != null) {
element.removeChild(element.getFirstChild());
}
}
}
/**
* Removes the element from its parent if the element is not null and has a parent.
*
* @return {@code true} if the the element has been removed from its parent, {@code false} otherwise.
*/
public static boolean failSafeRemoveFromParent(final Element element) {
return failSafeRemove(element != null ? element.getParentElement() : null, element);
}
/**
* Removes the child from parent if both parent and child are not null and parent contains child.
*
* @return {@code true} if the the element has been removed from its parent, {@code false} otherwise.
*/
public static boolean failSafeRemove(final Element parent, final Element child) {
if (parent != null && child != null && parent.contains(child)) {
return parent.removeChild(child) != null;
}
return false;
}
/**
* Looks for an element in the document using the CSS selector {@code [data-element=<name>]}.
*/
public static Element dataElement(@NonNls String name) {
return Browser.getDocument().querySelector("[data-element=" + name + "]");
}
/**
* Looks for an element below {@code context} using the CSS selector {@code [data-element=<name>]}
*/
public static Element dataElement(Element context, @NonNls String name) {
return context != null ? context.querySelector("[data-element=" + name + "]") : null;
}
/**
* Checks whether the given element is visible (i.e. {@code display} is not {@code none})
*/
public static boolean isVisible(Element element) {
return element != null && !"none".equals(element.getStyle().getDisplay());
}
/**
* shows / hide the specified element by modifying the {@code display} property.
*/
public static void setVisible(Element element, boolean visible) {
if (element != null) {
element.getStyle().setDisplay(visible ? "" : "none");
}
}
/**
* Adds the specified CSS class to the element if {@code flag} is {@code true}, removes it otherwise.
*/
public static void toggle(Element element, String css, boolean flag) {
if (element != null) {
if (flag) {
element.getClassList().add(css);
} else {
element.getClassList().remove(css);
}
}
}
// ------------------------------------------------------ conversions
private static class ElementWidget extends Widget {
ElementWidget(final Element element) {
setElement(com.google.gwt.dom.client.Element.as((JavaScriptObject) element));
}
}
/**
* Converts from {@link IsElement} → {@link Widget}.
*/
public static Widget asWidget(IsElement element) {
return asWidget(element.asElement());
}
/**
* Converts from {@link Element} → {@link Widget}.
*/
public static Widget asWidget(Element element) {
return new ElementWidget(element);
}
/**
* Converts from {@link IsWidget} → {@link Element}.
*/
public static Element asElement(IsWidget widget) {
return asElement(widget.asWidget());
}
/**
* Converts from {@link Widget} → {@link Element}.
*/
public static Element asElement(Widget widget) {
return asElement(widget.getElement());
}
/**
* Converts from {@link com.google.gwt.dom.client.Element} → {@link Element}.
*/
public static Element asElement(com.google.gwt.dom.client.Element element) {
return element.cast();
}
}
|
core/src/main/java/org/jboss/gwt/elemento/core/Elements.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* 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.jboss.gwt.elemento.core;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Stack;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterables;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;
import elemental.client.Browser;
import elemental.dom.Document;
import elemental.dom.Element;
import elemental.dom.NodeList;
import elemental.events.EventListener;
import elemental.html.InputElement;
import org.jetbrains.annotations.NonNls;
import static java.util.Arrays.asList;
/**
* Helper methods for working with {@link Element}s.
*
* @author Harald Pehl
*/
public final class Elements {
// this is a static helper class which must never be instantiated!
private Elements() {}
static class ElementInfo {
int level;
Element element;
boolean container;
ElementInfo(final Element element, final boolean container, final int level) {
this.container = container;
this.element = element;
this.level = level;
}
@Override
public String toString() {
return (container ? "container" : "simple") + " @ " + level + ": " + element.getTagName();
}
}
/**
* Builder to create a hierarchy of {@link Element}s. Supports convenience methods to create common elements
* and attributes. Uses a fluent API to create and append elements on the fly.
* <p>
* The builder distinguishes between elements which can contain nested elements (container) and simple element w/o
* children. The former must be closed using {@link #end()}.
* <p>
* In order to create this form,
* <pre>
* <section class="main">
* <input class="toggle-all" type="checkbox">
* <label for="toggle-all">Mark all as complete</label>
* <ul class="todo-list">
* <li>
* <div class="view">
* <input class="toggle" type="checkbox" checked>
* <label>Taste Elemento</label>
* <button class="destroy"></button>
* </div>
* <input class="edit">
* </li>
* </ul>
* </section>
* </pre>
* <p>
* use the following builder code:
* <pre>
* Element element = new Elements.Builder()
* .section().css("main")
* .input(checkbox).css("toggle-all")
* .label().attr("for", "toggle-all").textContent("Mark all as complete").end()
* .ul().css("todo-list")
* .li()
* .div().css("view")
* .input(checkbox).css("toggle")
* .label().textContent("Taste Elemento").end()
* .button().css("destroy").end()
* .end()
* .input(text).css("edit")
* .end()
* .end()
* .end().build();
* </pre>
*
* @author Harald Pehl
*/
public static class Builder extends CoreBuilder<Builder> {
public Builder() {
super("elements.builder");
}
@Override
protected Builder that() {
return this;
}
}
public static abstract class CoreBuilder<B extends CoreBuilder<B>> {
private final String id;
private final Document document;
private final Stack<ElementInfo> elements;
private final Map<String, Element> references;
private int level;
/**
* Creates a new builder.
*
* @param id an unique id which is used in error messages
*/
protected CoreBuilder(@NonNls String id) {
this(id, Browser.getDocument());
}
/**
* Creates a new builder.
*
* @param id an unique id which is used in error messages
* @param document a reference to the document
*/
protected CoreBuilder(@NonNls String id, Document document) {
this.id = id;
this.document = document;
this.elements = new Stack<>();
this.references = new HashMap<>();
}
private String logId() {
return "<" + id + "> ";
}
/**
* In order to make builders work with inheritance, sub-builders must return a reference to their instance.
*
* @return {@code this}
*/
protected abstract B that();
// ------------------------------------------------------ container elements
/**
* Starts a new {@code <header>} container. The element must be closed with {@link #end()}.
*/
public B header() {
return start("header");
}
/**
* Starts a new {@code <h&>} container. The element must be closed with {@link #end()}.
*/
public B h(int ordinal) {
return start("h" + ordinal);
}
/**
* Starts a new {@code <h&>} container with the specified inner text.
* The element must be closed with {@link #end()}.
*/
public B h(int ordinal, String text) {
return start("h" + ordinal).textContent(text);
}
/**
* Starts a new {@code <section>} container. The element must be closed with {@link #end()}.
*/
public B section() {
return start(document.createElement("section"));
}
/**
* Starts a new {@code <aside>} container. The element must be closed with {@link #end()}.
*/
public B aside() {
return start(document.createElement("aside"));
}
/**
* Starts a new {@code <footer>} container. The element must be closed with {@link #end()}.
*/
public B footer() {
return start(document.createElement("footer"));
}
/**
* Starts a new {@code <p>} container. The element must be closed with {@link #end()}.
*/
public B p() {
return start(document.createElement("p"));
}
/**
* Starts a new {@code <ol>} container. The element must be closed with {@link #end()}.
*/
public B ol() {
return start(document.createElement("ol"));
}
/**
* Starts a new {@code <ul>} container. The element must be closed with {@link #end()}.
*/
public B ul() {
return start(document.createElement("ul"));
}
/**
* Starts a new {@code <li>} container. The element must be closed with {@link #end()}.
*/
public B li() {
return start(document.createLIElement());
}
/**
* Starts a new {@code <a>} container. The element must be closed with {@link #end()}.
*/
public B a() {
return start(document.createElement("a"));
}
/**
* Starts a new {@code <a>} container with the specified href.
* The element must be closed with {@link #end()}.
*/
public B a(@NonNls String href) {
return start(document.createElement("a")).attr("href", href);
}
/**
* Starts a new {@code <div>} container. The element must be closed with {@link #end()}.
*/
public B div() {
return start(document.createDivElement());
}
/**
* Starts a new {@code <span>} container. The element must be closed with {@link #end()}.
*/
public B span() {
return start(document.createSpanElement());
}
/**
* Starts the named container. The element must be closed with {@link #end()}.
*/
public B start(@NonNls String tag) {
return start(document.createElement(tag));
}
/**
* Adds the given element as new container. The element must be closed with {@link #end()}.
*/
public B start(Element element) {
elements.push(new ElementInfo(element, true, level));
level++;
return that();
}
/**
* Closes the current container element.
*
* @throws IllegalStateException if there's no current element or if the closing element is no container.
*/
public B end() {
assertCurrent();
if (level == 0) {
throw new IllegalStateException(
logId() + "Unbalanced element hierarchy. Elements stack: " + dumpElements());
}
List<ElementInfo> children = new ArrayList<>();
while (elements.peek().level == level) {
children.add(elements.pop());
}
Collections.reverse(children);
if (!elements.peek().container) {
throw new IllegalStateException(
logId() + "Closing element " + elements.peek().element + " is no container");
}
Element closingElement = elements.peek().element;
for (ElementInfo child : children) {
closingElement.appendChild(child.element);
}
level--;
return that();
}
private String dumpElements() {
return elements.toString();
}
// ------------------------------------------------------ table elements
public B table() {
return start("table");
}
public B thead() {
return start("thead");
}
public B tbody() {
return start("tbody");
}
public B tfoot() {
return start("tfoot");
}
public B tr() {
return start("tr");
}
public B th() {
return start("th");
}
public B td() {
return start("td");
}
// ------------------------------------------------------ form elements
/**
* Starts a new form. The element must be closed with {@link #end()}.
*/
public B form() {
return start(document.createFormElement());
}
/**
* Starts a new form label. The element must be closed with {@link #end()}.
*/
public B label() {
return start(document.createLabelElement());
}
/**
* Starts a new form label with the specified inner text.
* The element must be closed with {@link #end()}.
*/
public B label(String text) {
return start(document.createLabelElement()).textContent(text);
}
/**
* Starts a new button. The element must be closed with {@link #end()}.
*/
public B button() {
return input(InputType.button);
}
/**
* Starts a new button with the specified inner text.
* The element must be closed with {@link #end()}.
*/
public B button(String text) {
return input(InputType.button).textContent(text);
}
/**
* Starts a new select box. The element must be closed with {@link #end()}.
*/
public B select() {
return input(InputType.select);
}
/**
* Starts an option to be used inside a select box. The element must be closed with {@link #end()}.
*/
public B option() {
return start(document.createOptionElement());
}
/**
* Starts an option with the specified inner text. The element must be closed with {@link #end()}.
*/
public B option(String text) {
return start(document.createOptionElement()).textContent(text);
}
/**
* Starts a new textarea. The element must be closed with {@link #end()}.
*/
public B textarea() {
return input(InputType.textarea);
}
/**
* Creates the given input field. See {@link InputType} for details
* whether a container or simple element is created.
*/
public B input(InputType type) {
switch (type) {
case button:
start(document.createButtonElement());
break;
case color:
case checkbox:
case date:
case datetime:
case email:
case file:
case hidden:
case image:
case month:
case number:
case password:
case radio:
case range:
case reset:
case search:
case tel:
case text:
case time:
case url:
case week:
InputElement inputElement = document.createInputElement();
inputElement.setType(type.name());
add(inputElement);
break;
case select:
start(document.createSelectElement());
break;
case textarea:
start(document.createTextAreaElement());
break;
}
return that();
}
// ------------------------------------------------------ simple element(s)
/**
* Creates and adds the named element. The element must not be closed using {@link #end()}.
*/
public B add(@NonNls String tag) {
return add(document.createElement(tag));
}
/**
* Add the given element by calling {@code element.asElement()}. The element must not be closed using {@link
* #end()}.
*/
public B add(IsElement element) {
return add(element.asElement());
}
/**
* Adds all elements from {@code elements.asElements()}.
*/
public B addAll(HasElements elements) {
return addAll(elements.asElements());
}
/**
* Adds all elements.
*/
public B addAll(Iterable<Element> elements) {
for (Element element : elements) {
add(element);
}
return that();
}
/**
* Adds the given element. The element must not be closed using {@link #end()}.
*/
public B add(Element element) {
assertCurrent();
elements.push(new ElementInfo(element, false, level));
return that();
}
// ------------------------------------------------------ modify current element
/**
* Sets the id of the last added element.
*/
public B id(@NonNls String id) {
assertCurrent();
elements.peek().element.setId(id);
return that();
}
/**
* Sets the title of the last added element.
*/
public B title(String title) {
assertCurrent();
elements.peek().element.setTitle(title);
return that();
}
/**
* Sets the css classes for the last added element.
*/
public B css(@NonNls String classes) {
//noinspection NullArgumentToVariableArgMethod
return css(classes, null);
}
/**
* Sets the css classes for the last added element.
*/
public B css(@NonNls String first, @NonNls String... rest) {
assertCurrent();
List<String> classes = new ArrayList<>();
classes.add(first);
if (rest != null) {
classes.addAll(asList(rest));
}
String combined = rest != null && rest.length != 0
? Joiner.on(' ').skipNulls().join(classes)
: first;
elements.peek().element.setClassName(combined);
return that();
}
/**
* Sets the css style for the last added element.
*/
public B style(@NonNls String style) {
assertCurrent();
elements.peek().element.getStyle().setCssText(style);
return that();
}
/**
* Adds an attribute to the last added element.
*/
public B attr(@NonNls String name, String value) {
assertCurrent();
elements.peek().element.setAttribute(name, value);
return that();
}
/**
* Adds a {@code data-} attribute to the last added element.
*
* @param name The name of the data attribute w/o the {@code data-} prefix. However it won't be added if it's
* already present.
*/
public B data(@NonNls String name, String value) {
String safeName = name.startsWith("data-") ? name.substring("data-".length()) : name;
elements.peek().element.getDataset().setAt(safeName, value);
return that();
}
/**
* Adds an {@code aria-} attribute to the last added element.
*
* @param name The name of the aria attribute w/o the {@code aria-} prefix. However it won't be added if it's
* already present.
*/
public B aria(@NonNls String name, String value) {
String safeName = name.startsWith("aria-") ? name : "aria-" + name;
return attr(safeName, value);
}
/**
* Sets the inner HTML on the last added element.
*/
public B innerHtml(SafeHtml html) {
assertCurrent();
elements.peek().element.setInnerHTML(html.asString());
return that();
}
/**
* Sets the inner text on the last added element using {@link Element#setTextContent(String)}.
*
* @deprecated Use {@link #textContent(String)} instead.
*/
@Deprecated
public B innerText(String text) {
assertCurrent();
elements.peek().element.setTextContent(text);
return that();
}
/**
* Sets the inner text on the last added element using {@link Element#setTextContent(String)}.
*/
public B textContent(String text) {
assertCurrent();
elements.peek().element.setTextContent(text);
return that();
}
private void assertCurrent() {
if (elements.isEmpty()) {
throw new IllegalStateException(logId() + "No current element");
}
}
// ------------------------------------------------------ event handler
/**
* Adds the given event listener to the the last added element.
*/
public B on(EventType type, EventListener listener) {
assertCurrent();
Element element = elements.peek().element;
type.register(element, listener);
return that();
}
// ------------------------------------------------------ references
/**
* Stores a named reference for the last added element. The element can be retrieved later on using
* {@link #referenceFor(String)}.
*/
public B rememberAs(@NonNls String id) {
assertCurrent();
references.put(id, elements.peek().element);
return that();
}
/**
* Returns the element which was stored using {@link #rememberAs(String)}.
*
* @throws NoSuchElementException if no element was stored under that id.
*/
@SuppressWarnings("unchecked")
public <T extends Element> T referenceFor(@NonNls String id) {
if (!references.containsKey(id)) {
throw new NoSuchElementException(logId() + "No element reference found for '" + id + "'");
}
return (T) references.get(id);
}
// ------------------------------------------------------ builder
/**
* Builds the element hierarchy and returns the top level element casted to the specified element type.
*
* @param <T> The target element type
*
* @throws IllegalStateException If the hierarchy is unbalanced.
*/
@SuppressWarnings("unchecked")
public <T extends Element> T build() {
if (level != 0 && elements.size() != 1) {
throw new IllegalStateException(
logId() + "Unbalanced element hierarchy. Elements stack: " + dumpElements());
}
return (T) elements.pop().element;
}
/**
* Returns the top level elements added so far. This is useful if you don't want to build a single root
* container, but work with a list of elements.
*/
public Iterable<Element> elements() {
if (level != 0) {
throw new IllegalStateException(
logId() + "Unbalanced element hierarchy. Elements stack: " + dumpElements());
}
if (elements.isEmpty()) {
throw new IllegalStateException(logId() + "Empty elements stack");
}
//noinspection StaticPseudoFunctionalStyleMethod
return Iterables.transform(this.elements, elementInfo -> elementInfo.element);
}
}
// ------------------------------------------------------ element helper methods
/**
* Returns an iterator over the children of the given parent element. The iterator supports the {@link
* Iterator#remove()} operation which removes the current element from its parent.
*/
public static Iterator<Element> iterator(Element parent) {
return parent != null ? new ChildrenIterator(parent) : Collections.<Element>emptyList().iterator();
}
/**
* Returns a stream for the children of the given parent element.
*/
public static Stream<Element> stream(Element parent) {
return parent != null ? StreamSupport.stream(children(parent).spliterator(), false) : Stream.empty();
}
/**
* Returns an iterable collection for the children of the given parent element.
*/
public static Iterable<Element> children(Element parent) {
return () -> iterator(parent);
}
/**
* Returns an iterator over the given node list. The iterator will only iterate over elements while skipping nodes.
* The iterator does <strong>not</strong> support the {@link Iterator#remove()} operation.
*/
public static Iterator<Element> iterator(NodeList nodes) {
return nodes != null ? new NodeListIterator(nodes) : Collections.<Element>emptyList().iterator();
}
/**
* Returns a stream for the elements in the given node list.
*/
public static Stream<Element> stream(NodeList nodes) {
return nodes != null ? StreamSupport.stream(elements(nodes).spliterator(), false) : Stream.empty();
}
/**
* Returns an iterable collection for the elements in the given node list.
*/
public static Iterable<Element> elements(NodeList nodes) {
return () -> iterator(nodes);
}
/**
* Convenience method to set the inner HTML of the given element.
*/
public static void innerHtml(Element element, SafeHtml html) {
if (element != null) {
element.setInnerHTML(html.asString());
}
}
/**
* Appends the specified element to the parent element if not already present. If parent already contains child,
* this method does nothing.
*/
public static void lazyAppend(final Element parent, final Element child) {
if (!parent.contains(child)) {
parent.appendChild(child);
}
}
/**
* Inserts the specified element into the parent element if not already present. If parent already contains child,
* this method does nothing.
*/
public static void lazyInsertBefore(final Element parent, final Element child, final Element before) {
if (!parent.contains(child)) {
parent.insertBefore(child, before);
}
}
/**
* Removes all child elements from {@code element}
*/
public static void removeChildrenFrom(final Element element) {
if (element != null) {
while (element.getFirstChild() != null) {
element.removeChild(element.getFirstChild());
}
}
}
/**
* Removes the element from its parent if the element is not null and has a parent.
*
* @return {@code true} if the the element has been removed from its parent, {@code false} otherwise.
*/
public static boolean failSafeRemoveFromParent(final Element element) {
return failSafeRemove(element, element != null ? element.getParentElement() : null);
}
/**
* Removes the child from parent if both parent and child are not null and parent contains child.
*
* @return {@code true} if the the element has been removed from its parent, {@code false} otherwise.
*/
public static boolean failSafeRemove(final Element parent, final Element child) {
if (parent != null && child != null && parent.contains(child)) {
return parent.removeChild(child) != null;
}
return false;
}
/**
* Looks for an element in the document using the CSS selector {@code [data-element=<name>]}.
*/
public static Element dataElement(@NonNls String name) {
return Browser.getDocument().querySelector("[data-element=" + name + "]");
}
/**
* Looks for an element below {@code context} using the CSS selector {@code [data-element=<name>]}
*/
public static Element dataElement(Element context, @NonNls String name) {
return context != null ? context.querySelector("[data-element=" + name + "]") : null;
}
/**
* Checks whether the given element is visible (i.e. {@code display} is not {@code none})
*/
public static boolean isVisible(Element element) {
return element != null && !"none".equals(element.getStyle().getDisplay());
}
/**
* shows / hide the specified element by modifying the {@code display} property.
*/
public static void setVisible(Element element, boolean visible) {
if (element != null) {
element.getStyle().setDisplay(visible ? "" : "none");
}
}
/**
* Adds the specified CSS class to the element if {@code flag} is {@code true}, removes it otherwise.
*/
public static void toggle(Element element, String css, boolean flag) {
if (element != null) {
if (flag) {
element.getClassList().add(css);
} else {
element.getClassList().remove(css);
}
}
}
// ------------------------------------------------------ conversions
private static class ElementWidget extends Widget {
ElementWidget(final Element element) {
setElement(com.google.gwt.dom.client.Element.as((JavaScriptObject) element));
}
}
/**
* Converts from {@link IsElement} → {@link Widget}.
*/
public static Widget asWidget(IsElement element) {
return asWidget(element.asElement());
}
/**
* Converts from {@link Element} → {@link Widget}.
*/
public static Widget asWidget(Element element) {
return new ElementWidget(element);
}
/**
* Converts from {@link IsWidget} → {@link Element}.
*/
public static Element asElement(IsWidget widget) {
return asElement(widget.asWidget());
}
/**
* Converts from {@link Widget} → {@link Element}.
*/
public static Element asElement(Widget widget) {
return asElement(widget.getElement());
}
/**
* Converts from {@link com.google.gwt.dom.client.Element} → {@link Element}.
*/
public static Element asElement(com.google.gwt.dom.client.Element element) {
return element.cast();
}
}
|
Bugfix for Elements.failSafeRemoveFromParent()
|
core/src/main/java/org/jboss/gwt/elemento/core/Elements.java
|
Bugfix for Elements.failSafeRemoveFromParent()
|
<ide><path>ore/src/main/java/org/jboss/gwt/elemento/core/Elements.java
<ide> * @return {@code true} if the the element has been removed from its parent, {@code false} otherwise.
<ide> */
<ide> public static boolean failSafeRemoveFromParent(final Element element) {
<del> return failSafeRemove(element, element != null ? element.getParentElement() : null);
<add> return failSafeRemove(element != null ? element.getParentElement() : null, element);
<ide> }
<ide>
<ide> /**
|
|
Java
|
apache-2.0
|
d9a0bf4677eefc91e5b91fa0131fb989652a56df
| 0 |
statsbiblioteket/newspaper-manualQA-flagger,statsbiblioteket/newspaper-manualQA-flagger
|
package dk.statsbiblioteket.medieplatform.newspaper.manualQA;
import dk.statsbiblioteket.medieplatform.autonomous.Batch;
import dk.statsbiblioteket.medieplatform.autonomous.ResultCollector;
import dk.statsbiblioteket.medieplatform.autonomous.iterator.common.AttributeParsingEvent;
import dk.statsbiblioteket.medieplatform.autonomous.iterator.common.NodeEndParsingEvent;
import dk.statsbiblioteket.medieplatform.newspaper.manualQA.flagging.FlaggingCollector;
import dk.statsbiblioteket.medieplatform.newspaper.manualQA.mockers.AltoMocker;
import dk.statsbiblioteket.util.xml.DOM;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
public class AltoWordAccuracyCheckerTest {
Properties properties;
@BeforeMethod
public void setUp() {
properties = new Properties();
properties.setProperty(ConfigConstants.MINIMUM_ALTO_AVERAGE_ACCURACY, "60.0");
properties.setProperty(ConfigConstants.MINIMUM_ALTO_PERFILE_ACCURACY, "20.0");
properties.setProperty(ConfigConstants.ALTO_IGNORE_ZERO_ACCURACY, "true");
}
/**
* Test that a single page with accuracy 15.0 generates a flag immediately.
* @throws Exception
*/
@Test
public void testHandleSingleBadPage() throws Exception {
ResultCollector resultCollector = new ResultCollector("foobar", "1.0");
Batch batch = new Batch();
FlaggingCollector flaggingCollector = new FlaggingCollector(batch, DOM.streamToDOM(
Thread.currentThread().getContextClassLoader().getResourceAsStream(
"batchStructure.xml")), "42.24", 100);
AltoWordAccuracyChecker altoWordAccuracyChecker =
new AltoWordAccuracyChecker(resultCollector, flaggingCollector, properties);
AttributeParsingEvent e1 = generateAttributeEvent("foo/bar/film1/edition1/1.alto.xml", "15.0");
altoWordAccuracyChecker.handleAttribute(e1);
assertTrue(flaggingCollector.hasFlags(), flaggingCollector.toReport());
}
/**
* Test that a page with accuracy exactly zero raises no flag.
* @throws Exception
*/
@Test
public void testHandleSinglePageNoText() throws Exception {
ResultCollector resultCollector = new ResultCollector("foobar", "1.0");
Batch batch = new Batch();
FlaggingCollector flaggingCollector = new FlaggingCollector(batch, DOM.streamToDOM(
Thread.currentThread().getContextClassLoader().getResourceAsStream(
"batchStructure.xml")), "42.24", 100);
AltoWordAccuracyChecker altoWordAccuracyChecker =
new AltoWordAccuracyChecker(resultCollector, flaggingCollector, properties);
AttributeParsingEvent e1 = generateAttributeEvent("foo/bar/film1/edition1/1.alto.xml", "0.0");
altoWordAccuracyChecker.handleAttribute(e1);
assertFalse(flaggingCollector.hasFlags(), flaggingCollector.toReport());
}
@Test
public void testHandleEditionEndWithFlag() throws Exception {
ResultCollector resultCollector = new ResultCollector("foobar", "1.0");
Batch batch = new Batch();
FlaggingCollector flaggingCollector = new FlaggingCollector(batch, DOM.streamToDOM(
Thread.currentThread().getContextClassLoader().getResourceAsStream("batchStructure.xml")), "42.24", 100);
AltoWordAccuracyChecker altoWordAccuracyChecker
= new AltoWordAccuracyChecker(resultCollector, flaggingCollector, properties);
AttributeParsingEvent e1 = generateAttributeEvent("foo/bar/film1/2001-01-02-03/1.alto.xml", "50.0");
AttributeParsingEvent e2 = generateAttributeEvent("foo/bar/film1/2001-01-02-03/2.alto.xml", "40.0");
NodeEndParsingEvent e3 = new NodeEndParsingEvent("foo/bar/film1/2001-01-02-03");
altoWordAccuracyChecker.handleAttribute(e1);
altoWordAccuracyChecker.handleAttribute(e2);
altoWordAccuracyChecker.handleNodeEnd(e3);
assertTrue(flaggingCollector.hasFlags(), flaggingCollector.toReport());
assertTrue(flaggingCollector.toReport().contains("Edition"), flaggingCollector.toReport());
}
@Test
public void testHandleFilmEndWithFlag() throws Exception {
ResultCollector resultCollector = new ResultCollector("foobar", "1.0");
Batch batch = new Batch();
FlaggingCollector flaggingCollector = new FlaggingCollector(batch, DOM.streamToDOM(
Thread.currentThread().getContextClassLoader().getResourceAsStream(
"batchStructure.xml")), "42.24", 100);
AltoWordAccuracyChecker altoWordAccuracyChecker =
new AltoWordAccuracyChecker(resultCollector, flaggingCollector, properties);
AttributeParsingEvent e1 = generateAttributeEvent("foo/bar/12345272-07/edition1/1.alto.xml", "65.0");
AttributeParsingEvent e2 = generateAttributeEvent("foo/bar/12345272-07/edition1/2.alto.xml", "65.0");
AttributeParsingEvent e3 = generateAttributeEvent("foo/bar/12345272-07/edition2/1.alto.xml", "40.0");
AttributeParsingEvent e4 = generateAttributeEvent("foo/bar/12345272-07/edition2/2.alto.xml", "40.0");
NodeEndParsingEvent e5 = new NodeEndParsingEvent("foo/bar/12345272-07");
altoWordAccuracyChecker.handleAttribute(e1);
altoWordAccuracyChecker.handleAttribute(e2);
altoWordAccuracyChecker.handleAttribute(e3);
altoWordAccuracyChecker.handleAttribute(e4);
altoWordAccuracyChecker.handleNodeEnd(e5);
assertTrue(flaggingCollector.hasFlags(), flaggingCollector.toReport());
assertTrue(flaggingCollector.toReport().contains("Film"), flaggingCollector.toReport());
}
/**
* Check that a film with mean accuracy>60.0 generates no flag, including test that page with
* accuracy=0 is ignored in the calculation.
* @throws Exception
*/
@Test
public void testHandleFilmEndWithoutFlag() throws Exception {
ResultCollector resultCollector = new ResultCollector("foobar", "1.0");
Batch batch = new Batch();
FlaggingCollector flaggingCollector = new FlaggingCollector(batch, DOM.streamToDOM(
Thread.currentThread().getContextClassLoader().getResourceAsStream(
"batchStructure.xml")), "42.24", 100);
AltoWordAccuracyChecker altoWordAccuracyChecker =
new AltoWordAccuracyChecker(resultCollector, flaggingCollector, properties);
AttributeParsingEvent e1 = generateAttributeEvent("foo/bar/film1/edition1/1.alto.xml", "65.0");
AttributeParsingEvent e2 = generateAttributeEvent("foo/bar/film1/edition1/2.alto.xml", "65.0");
AttributeParsingEvent e3 = generateAttributeEvent("foo/bar/film1/edition2/1.alto.xml", "58.0");
AttributeParsingEvent e4 = generateAttributeEvent("foo/bar/film1/edition2/2.alto.xml", "58.0");
AttributeParsingEvent e5 = generateAttributeEvent("foo/bar/film1/edition2/3.alto.xml", "0.0");
NodeEndParsingEvent e6 = new NodeEndParsingEvent("foo/bar/film1");
altoWordAccuracyChecker.handleAttribute(e1);
altoWordAccuracyChecker.handleAttribute(e2);
altoWordAccuracyChecker.handleAttribute(e3);
altoWordAccuracyChecker.handleAttribute(e4);
altoWordAccuracyChecker.handleAttribute(e5);
altoWordAccuracyChecker.handleNodeEnd(e6);
assertFalse(flaggingCollector.hasFlags(), flaggingCollector.toReport());
}
@Test
public void testHandleEditionEndWithoutFlag() throws Exception {
ResultCollector resultCollector = new ResultCollector("foobar", "1.0");
Batch batch = new Batch();
FlaggingCollector flaggingCollector = new FlaggingCollector(batch, DOM.streamToDOM(
Thread.currentThread().getContextClassLoader().getResourceAsStream(
"batchStructure.xml")), "42.24", 100);
AltoWordAccuracyChecker altoWordAccuracyChecker =
new AltoWordAccuracyChecker(resultCollector, flaggingCollector, properties);
AttributeParsingEvent e1 = generateAttributeEvent("foo/bar/film1/edition1/1.alto.xml", "50.0");
AttributeParsingEvent e2 = generateAttributeEvent("foo/bar/film1/edition1/2.alto.xml", "80.0");
NodeEndParsingEvent e3 = new NodeEndParsingEvent("foo/bar/film1/2001-01-01-03");
altoWordAccuracyChecker.handleAttribute(e1);
altoWordAccuracyChecker.handleAttribute(e2);
altoWordAccuracyChecker.handleNodeEnd(e3);
assertFalse(flaggingCollector.hasFlags(), flaggingCollector.toReport());
}
@Test
public void testRunningAverage() {
AltoWordAccuracyChecker.RunningAverage runningAverage = new AltoWordAccuracyChecker.RunningAverage();
runningAverage.addValue(3.0);
runningAverage.addValue(5.0);
runningAverage.addValue(6.0);
//Running average is 4 2/3, so
assertTrue(runningAverage.getCurrentValue() > 4.6666);
assertTrue(runningAverage.getCurrentValue() < 4.6667);
}
private AttributeParsingEvent generateAttributeEvent(String name, String accuracy) {
final String alto = AltoMocker.getAlto(accuracy);
return new AttributeParsingEvent(name) {
@Override
public InputStream getData() throws IOException {
return new ByteArrayInputStream(alto.getBytes());
}
@Override
public String getChecksum() throws IOException {
throw new RuntimeException("not implemented");
}
};
}
}
|
src/test/java/dk/statsbiblioteket/medieplatform/newspaper/manualQA/AltoWordAccuracyCheckerTest.java
|
package dk.statsbiblioteket.medieplatform.newspaper.manualQA;
import dk.statsbiblioteket.medieplatform.autonomous.Batch;
import dk.statsbiblioteket.medieplatform.autonomous.ResultCollector;
import dk.statsbiblioteket.medieplatform.autonomous.iterator.common.AttributeParsingEvent;
import dk.statsbiblioteket.medieplatform.autonomous.iterator.common.NodeEndParsingEvent;
import dk.statsbiblioteket.medieplatform.newspaper.manualQA.flagging.FlaggingCollector;
import dk.statsbiblioteket.medieplatform.newspaper.manualQA.mockers.AltoMocker;
import dk.statsbiblioteket.util.xml.DOM;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
public class AltoWordAccuracyCheckerTest {
Properties properties;
@BeforeMethod
public void setUp() {
properties = new Properties();
properties.setProperty(ConfigConstants.MINIMUM_ALTO_AVERAGE_ACCURACY, "60.0");
properties.setProperty(ConfigConstants.MINIMUM_ALTO_PERFILE_ACCURACY, "20.0");
properties.setProperty(ConfigConstants.ALTO_IGNORE_ZERO_ACCURACY, "true");
}
/**
* Test that a single page with accuracy 15.0 generates a flag immediately.
* @throws Exception
*/
@Test
public void testHandleSingleBadPage() throws Exception {
ResultCollector resultCollector = new ResultCollector("foobar", "1.0");
Batch batch = new Batch();
FlaggingCollector flaggingCollector = new FlaggingCollector(batch, DOM.streamToDOM(
Thread.currentThread().getContextClassLoader().getResourceAsStream(
"batchStructure.xml")), "42.24", 100);
AltoWordAccuracyChecker altoWordAccuracyChecker =
new AltoWordAccuracyChecker(resultCollector, flaggingCollector, properties);
AttributeParsingEvent e1 = generateAttributeEvent("foo/bar/film1/edition1/1.alto.xml", "15.0");
altoWordAccuracyChecker.handleAttribute(e1);
assertTrue(flaggingCollector.hasFlags(), flaggingCollector.toReport());
}
/**
* Test that a page with accuracy exactly zero raises no flag.
* @throws Exception
*/
@Test
public void testHandleSinglePageNoText() throws Exception {
ResultCollector resultCollector = new ResultCollector("foobar", "1.0");
Batch batch = new Batch();
FlaggingCollector flaggingCollector = new FlaggingCollector(batch, DOM.streamToDOM(
Thread.currentThread().getContextClassLoader().getResourceAsStream(
"batchStructure.xml")), "42.24", 100);
AltoWordAccuracyChecker altoWordAccuracyChecker =
new AltoWordAccuracyChecker(resultCollector, flaggingCollector, properties);
AttributeParsingEvent e1 = generateAttributeEvent("foo/bar/film1/edition1/1.alto.xml", "0.0");
altoWordAccuracyChecker.handleAttribute(e1);
assertFalse(flaggingCollector.hasFlags(), flaggingCollector.toReport());
}
@Test
public void testHandleEditionEndWithFlag() throws Exception {
ResultCollector resultCollector = new ResultCollector("foobar", "1.0");
Batch batch = new Batch();
FlaggingCollector flaggingCollector = new FlaggingCollector(batch, DOM.streamToDOM(
Thread.currentThread().getContextClassLoader().getResourceAsStream(
"batchStructure.xml")), "42.24", 100);
AltoWordAccuracyChecker altoWordAccuracyChecker =
new AltoWordAccuracyChecker(resultCollector, flaggingCollector, properties);
AttributeParsingEvent e1 = generateAttributeEvent("foo/bar/film1/2001-01-02-03/1.alto.xml", "50.0");
AttributeParsingEvent e2 = generateAttributeEvent("foo/bar/film1/2001-01-02-03/2.alto.xml", "40.0");
NodeEndParsingEvent e3 = new NodeEndParsingEvent("foo/bar/film1/2001-01-02-03");
altoWordAccuracyChecker.handleAttribute(e1);
altoWordAccuracyChecker.handleAttribute(e2);
altoWordAccuracyChecker.handleNodeEnd(e3);
assertTrue(flaggingCollector.hasFlags(), flaggingCollector.toReport());
assertTrue(flaggingCollector.toReport().contains("Edition"), flaggingCollector.toReport());
}
@Test
public void testHandleFilmEndWithFlag() throws Exception {
ResultCollector resultCollector = new ResultCollector("foobar", "1.0");
Batch batch = new Batch();
FlaggingCollector flaggingCollector = new FlaggingCollector(batch, DOM.streamToDOM(
Thread.currentThread().getContextClassLoader().getResourceAsStream(
"batchStructure.xml")), "42.24", 100);
AltoWordAccuracyChecker altoWordAccuracyChecker =
new AltoWordAccuracyChecker(resultCollector, flaggingCollector, properties);
AttributeParsingEvent e1 = generateAttributeEvent("foo/bar/12345272-07/edition1/1.alto.xml", "65.0");
AttributeParsingEvent e2 = generateAttributeEvent("foo/bar/12345272-07/edition1/2.alto.xml", "65.0");
AttributeParsingEvent e3 = generateAttributeEvent("foo/bar/12345272-07/edition2/1.alto.xml", "40.0");
AttributeParsingEvent e4 = generateAttributeEvent("foo/bar/12345272-07/edition2/2.alto.xml", "40.0");
NodeEndParsingEvent e5 = new NodeEndParsingEvent("foo/bar/12345272-07");
altoWordAccuracyChecker.handleAttribute(e1);
altoWordAccuracyChecker.handleAttribute(e2);
altoWordAccuracyChecker.handleAttribute(e3);
altoWordAccuracyChecker.handleAttribute(e4);
altoWordAccuracyChecker.handleNodeEnd(e5);
assertTrue(flaggingCollector.hasFlags(), flaggingCollector.toReport());
assertTrue(flaggingCollector.toReport().contains("Film"), flaggingCollector.toReport());
}
/**
* Check that a film with mean accuracy>60.0 generates no flag, including test that page with
* accuracy=0 is ignored in the calculation.
* @throws Exception
*/
@Test
public void testHandleFilmEndWithoutFlag() throws Exception {
ResultCollector resultCollector = new ResultCollector("foobar", "1.0");
Batch batch = new Batch();
FlaggingCollector flaggingCollector = new FlaggingCollector(batch, DOM.streamToDOM(
Thread.currentThread().getContextClassLoader().getResourceAsStream(
"batchStructure.xml")), "42.24", 100);
AltoWordAccuracyChecker altoWordAccuracyChecker =
new AltoWordAccuracyChecker(resultCollector, flaggingCollector, properties);
AttributeParsingEvent e1 = generateAttributeEvent("foo/bar/film1/edition1/1.alto.xml", "65.0");
AttributeParsingEvent e2 = generateAttributeEvent("foo/bar/film1/edition1/2.alto.xml", "65.0");
AttributeParsingEvent e3 = generateAttributeEvent("foo/bar/film1/edition2/1.alto.xml", "58.0");
AttributeParsingEvent e4 = generateAttributeEvent("foo/bar/film1/edition2/2.alto.xml", "58.0");
AttributeParsingEvent e5 = generateAttributeEvent("foo/bar/film1/edition2/3.alto.xml", "0.0");
NodeEndParsingEvent e6 = new NodeEndParsingEvent("foo/bar/film1");
altoWordAccuracyChecker.handleAttribute(e1);
altoWordAccuracyChecker.handleAttribute(e2);
altoWordAccuracyChecker.handleAttribute(e3);
altoWordAccuracyChecker.handleAttribute(e4);
altoWordAccuracyChecker.handleAttribute(e5);
altoWordAccuracyChecker.handleNodeEnd(e6);
assertFalse(flaggingCollector.hasFlags(), flaggingCollector.toReport());
}
@Test
public void testHandleEditionEndWithoutFlag() throws Exception {
ResultCollector resultCollector = new ResultCollector("foobar", "1.0");
Batch batch = new Batch();
FlaggingCollector flaggingCollector = new FlaggingCollector(batch, DOM.streamToDOM(
Thread.currentThread().getContextClassLoader().getResourceAsStream(
"batchStructure.xml")), "42.24", 100);
AltoWordAccuracyChecker altoWordAccuracyChecker =
new AltoWordAccuracyChecker(resultCollector, flaggingCollector, properties);
AttributeParsingEvent e1 = generateAttributeEvent("foo/bar/film1/edition1/1.alto.xml", "50.0");
AttributeParsingEvent e2 = generateAttributeEvent("foo/bar/film1/edition1/2.alto.xml", "80.0");
NodeEndParsingEvent e3 = new NodeEndParsingEvent("foo/bar/film1/2001-01-01-03");
altoWordAccuracyChecker.handleAttribute(e1);
altoWordAccuracyChecker.handleAttribute(e2);
altoWordAccuracyChecker.handleNodeEnd(e3);
assertFalse(flaggingCollector.hasFlags(), flaggingCollector.toReport());
}
@Test
public void testRunningAverage() {
AltoWordAccuracyChecker.RunningAverage runningAverage = new AltoWordAccuracyChecker.RunningAverage();
runningAverage.addValue(3.0);
runningAverage.addValue(5.0);
runningAverage.addValue(6.0);
//Running average is 4 2/3, so
assertTrue(runningAverage.getCurrentValue() > 4.6666);
assertTrue(runningAverage.getCurrentValue() < 4.6667);
}
private AttributeParsingEvent generateAttributeEvent(String name, String accuracy) {
final String alto = AltoMocker.getAlto(accuracy);
return new AttributeParsingEvent(name) {
@Override
public InputStream getData() throws IOException {
return new ByteArrayInputStream(alto.getBytes());
}
@Override
public String getChecksum() throws IOException {
throw new RuntimeException("not implemented");
}
};
}
}
|
Clarity
|
src/test/java/dk/statsbiblioteket/medieplatform/newspaper/manualQA/AltoWordAccuracyCheckerTest.java
|
Clarity
|
<ide><path>rc/test/java/dk/statsbiblioteket/medieplatform/newspaper/manualQA/AltoWordAccuracyCheckerTest.java
<ide> ResultCollector resultCollector = new ResultCollector("foobar", "1.0");
<ide> Batch batch = new Batch();
<ide> FlaggingCollector flaggingCollector = new FlaggingCollector(batch, DOM.streamToDOM(
<del> Thread.currentThread().getContextClassLoader().getResourceAsStream(
<del> "batchStructure.xml")), "42.24", 100);
<del> AltoWordAccuracyChecker altoWordAccuracyChecker =
<del> new AltoWordAccuracyChecker(resultCollector, flaggingCollector, properties);
<add> Thread.currentThread().getContextClassLoader().getResourceAsStream("batchStructure.xml")), "42.24", 100);
<add> AltoWordAccuracyChecker altoWordAccuracyChecker
<add> = new AltoWordAccuracyChecker(resultCollector, flaggingCollector, properties);
<add>
<ide> AttributeParsingEvent e1 = generateAttributeEvent("foo/bar/film1/2001-01-02-03/1.alto.xml", "50.0");
<ide> AttributeParsingEvent e2 = generateAttributeEvent("foo/bar/film1/2001-01-02-03/2.alto.xml", "40.0");
<ide> NodeEndParsingEvent e3 = new NodeEndParsingEvent("foo/bar/film1/2001-01-02-03");
<add>
<ide> altoWordAccuracyChecker.handleAttribute(e1);
<ide> altoWordAccuracyChecker.handleAttribute(e2);
<ide> altoWordAccuracyChecker.handleNodeEnd(e3);
<add>
<ide> assertTrue(flaggingCollector.hasFlags(), flaggingCollector.toReport());
<ide> assertTrue(flaggingCollector.toReport().contains("Edition"), flaggingCollector.toReport());
<ide> }
<ide> new AltoWordAccuracyChecker(resultCollector, flaggingCollector, properties);
<ide> AttributeParsingEvent e1 = generateAttributeEvent("foo/bar/12345272-07/edition1/1.alto.xml", "65.0");
<ide> AttributeParsingEvent e2 = generateAttributeEvent("foo/bar/12345272-07/edition1/2.alto.xml", "65.0");
<del> AttributeParsingEvent e3 = generateAttributeEvent("foo/bar/12345272-07/edition2/1.alto.xml", "40.0");
<add> AttributeParsingEvent e3 = generateAttributeEvent("foo/bar/12345272-07/edition2/1.alto.xml", "40.0");
<ide> AttributeParsingEvent e4 = generateAttributeEvent("foo/bar/12345272-07/edition2/2.alto.xml", "40.0");
<ide> NodeEndParsingEvent e5 = new NodeEndParsingEvent("foo/bar/12345272-07");
<ide> altoWordAccuracyChecker.handleAttribute(e1);
<ide> * accuracy=0 is ignored in the calculation.
<ide> * @throws Exception
<ide> */
<del> @Test
<add> @Test
<ide> public void testHandleFilmEndWithoutFlag() throws Exception {
<ide> ResultCollector resultCollector = new ResultCollector("foobar", "1.0");
<ide> Batch batch = new Batch();
<ide> new AltoWordAccuracyChecker(resultCollector, flaggingCollector, properties);
<ide> AttributeParsingEvent e1 = generateAttributeEvent("foo/bar/film1/edition1/1.alto.xml", "65.0");
<ide> AttributeParsingEvent e2 = generateAttributeEvent("foo/bar/film1/edition1/2.alto.xml", "65.0");
<del> AttributeParsingEvent e3 = generateAttributeEvent("foo/bar/film1/edition2/1.alto.xml", "58.0");
<add> AttributeParsingEvent e3 = generateAttributeEvent("foo/bar/film1/edition2/1.alto.xml", "58.0");
<ide> AttributeParsingEvent e4 = generateAttributeEvent("foo/bar/film1/edition2/2.alto.xml", "58.0");
<del> AttributeParsingEvent e5 = generateAttributeEvent("foo/bar/film1/edition2/3.alto.xml", "0.0");
<del> NodeEndParsingEvent e6 = new NodeEndParsingEvent("foo/bar/film1");
<add> AttributeParsingEvent e5 = generateAttributeEvent("foo/bar/film1/edition2/3.alto.xml", "0.0");
<add> NodeEndParsingEvent e6 = new NodeEndParsingEvent("foo/bar/film1");
<ide> altoWordAccuracyChecker.handleAttribute(e1);
<ide> altoWordAccuracyChecker.handleAttribute(e2);
<ide> altoWordAccuracyChecker.handleAttribute(e3);
|
|
Java
|
lgpl-2.1
|
e17bf8a90bd3fa0b60f71efbcf5e71ebf77c7854
| 0 |
sbliven/biojava,sbliven/biojava,sbliven/biojava
|
/*
* BioJava development code
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. If you do not have a copy,
* see:
*
* http://www.gnu.org/copyleft/lesser.html
*
* Copyright for this code is held jointly by the individual
* authors. These should be listed in @author doc comments.
*
* For more information on the BioJava project and its aims,
* or to join the biojava-l mailing list, visit the home page
* at:
*
* http://www.biojava.org/
*
*/
package org.biojava.bio.seq;
import org.biojava.bio.seq.io.*;
import org.biojava.bio.*;
import org.biojava.bio.symbol.*;
import org.biojava.bio.seq.impl.*;
import org.biojava.utils.*;
import java.util.*;
/**
* <p>
* A circular view onto another Sequence object. The class allows for
* reinterpretation of locations and indices onto the sequence to allow for
* overlapping of the origin. The origin is assumed to be the first symbol.
* Future versions may support changing the origin.
* </p>
*
* <p>
* This code is currently experimental
* </p>
*
* @author Mark Schreiber
* @version 1.2
* @since 1.1
*/
public class CircularView extends ViewSequence{
public CircularView(Sequence seq, FeatureRealizer fr){
super(seq, fr);
}
public CircularView(Sequence seq){
super(seq);
}
private int realValue(int val){
val = (val % length());
if(val < 1) val = length() + val;
return val;
}
/**
* <p>
* Over rides ViewSequence. Allows any integer index, positive or negative
* to return a symbol via the equation
* <CODE>val = (val % length);</CODE>
* Note that base zero is the base immediately before base 1 which is of course
* the last base of the sequence.
* </p>
* @param index the index of the <code>Symbol </code>requested.
* @return the <code>Symbol </code>specified by the <code>index.</code>
*/
public Symbol symbolAt(int index){
return super.symbolAt(realValue(index));
}
/**
* <p>
* Over rides ViewSequence. Allows any integer index, positive or negative
* to return a symbol via the equation
* <CODE>val = (val % length);</CODE>
* </p>
*
* <p>
* Will return a linear String which can, if nescessary, span the origin.
* </p>
* @param start the index of the fist base
* @param end the index of the last base
* @return a <code>String </code>representation of the tokenized <code>Symbol</code>s
*/
public String subStr(int start, int end){
start = realValue(start);
end = realValue(end);
if(start <= end){
return super.subStr(start, end);
}
else{
String toEnd = super.subStr(start,super.length());
String fromStart = super.subStr(1,end);
return toEnd + fromStart;
}
}
/**
* Over rides ViewSequence to allow the use of locations that have
* coordinates outside of the sequence length (which are needed to
* describe locations that overlap the origin of a circular sequence).
*
* @since 1.2
* @throws BioException if a non circular location is added that exceeds the
* 'boundaries' of the sequence.
* @throws ChangeVetoException if the sequence is locked.
* @param template the template of the feature to be created.
* @return the feature created you can use the template of the returned feature
* to create another of the same type.
*/
public Feature createFeature(Feature.Template template)
throws ChangeVetoException, BioException
{
Location loc = template.location;
if(loc.getMax() > length() && (loc instanceof CircularLocation == false)){
throw new BioException("Only CircularLocations may exceed sequence length");
}
Feature f = realizeFeature(this, template);
((SimpleFeatureHolder)getAddedFeatures()).addFeature(f);
return f;
}
/**
* <p>
* Over rides ViewSequence. Allows any integer index, positive or negative
* to return a symbol via the equation
* <CODE>index = ((index -1) % length)+1</CODE>
* </p>
*
* <p>
* Will return a linear SymbolList which can ,if nescessary, span the origin.
* </p>
* @param start the first base of the sublist
* @param end the last base of the sublist
* @return a <code>SymbolList </code>containing the <code>Symbols</code> from
* <code>start</code> to <code>end</code> inclusive
*/
public SymbolList subList(int start, int end){
start = realValue(start);
end = realValue(end);
if(start <= end){
return super.subList(start, end);
}
else{
SimpleSymbolList fromStart = new SimpleSymbolList(super.subList(1,end));
SimpleSymbolList toEnd = new SimpleSymbolList(super.subList(start,length()));
Edit edit = new Edit(toEnd.length() +1, 0, fromStart);
try{
toEnd.edit(edit);
}catch(Exception e){
throw new BioError(e, "Couldn't construct subList, this shouldn't happen");
}
return toEnd;
}
}
}
|
src/org/biojava/bio/seq/CircularView.java
|
/*
* BioJava development code
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. If you do not have a copy,
* see:
*
* http://www.gnu.org/copyleft/lesser.html
*
* Copyright for this code is held jointly by the individual
* authors. These should be listed in @author doc comments.
*
* For more information on the BioJava project and its aims,
* or to join the biojava-l mailing list, visit the home page
* at:
*
* http://www.biojava.org/
*
*/
package org.biojava.bio.seq;
import org.biojava.bio.seq.io.*;
import org.biojava.bio.*;
import org.biojava.bio.symbol.*;
import org.biojava.bio.seq.impl.*;
import org.biojava.utils.*;
import java.util.*;
/**
* <p>
* A circular view onto another Sequence object. The class allows for
* reinterpretation of locations and indices onto the sequence to allow for
* overlapping of the origin. The origin is assumed to be the first symbol.
* Future versions may support changing the origin.
* </p>
*
* <p>
* This code is currently experimental
* </p>
*
* @author Mark Schreiber
* @version 1.2
* @since 1.1
*/
public class CircularView extends ViewSequence{
public CircularView(Sequence seq, FeatureRealizer fr){
super(seq, fr);
}
public CircularView(Sequence seq){
super(seq);
}
private int realValue(int val){
val = (val % length());
if(val < 1) val = length() + val;
return val;
}
/**
* <p>
* Over rides ViewSequence. Allows any integer index, positive or negative
* to return a symbol via the equation
* <CODE>val = (val % length);</CODE>
* Note that base zero is the base immediately before base 1 which is of course
* the last base of the sequence.
* </p>
*/
public Symbol symbolAt(int index){
return super.symbolAt(realValue(index));
}
/**
* <p>
* Over rides ViewSequence. Allows any integer index, positive or negative
* to return a symbol via the equation
* <CODE>val = (val % length);</CODE>
* </p>
*
* <p>
* Will return a linear String which can, if nescessary, span the origin.
* </p>
*
*/
public String subStr(int start, int end){
start = realValue(start);
end = realValue(end);
if(start <= end){
return super.subStr(start, end);
}
else{
String toEnd = super.subStr(start,super.length());
String fromStart = super.subStr(1,end);
return toEnd + fromStart;
}
}
/**
* Over rides ViewSequence to allow the use of locations that have
* coordinates outside of the sequence length (which are needed to
* describe locations that overlap the origin of a circular sequence).
*
* @since 1.2
* @throws BioException if a non circular location is added that exceeds the
* 'boundaries' of the sequence.
*/
public Feature createFeature(Feature.Template template)
throws ChangeVetoException, BioException
{
Location loc = template.location;
if(loc.getMax() > length() && (loc instanceof CircularLocation == false)){
throw new BioException("Only CircularLocations may exceed sequence length");
}
Feature f = realizeFeature(this, template);
((SimpleFeatureHolder)getAddedFeatures()).addFeature(f);
return f;
}
/**
* <p>
* Over rides ViewSequence. Allows any integer index, positive or negative
* to return a symbol via the equation
* <CODE>index = ((index -1) % length)+1</CODE>
* </p>
*
* <p>
* Will return a linear SymbolList which can ,if nescessary, span the origin.
* </p>
*/
public SymbolList subList(int start, int end){
start = realValue(start);
end = realValue(end);
if(start <= end){
return super.subList(start, end);
}
else{
SimpleSymbolList fromStart = new SimpleSymbolList(super.subList(1,end));
SimpleSymbolList toEnd = new SimpleSymbolList(super.subList(start,length()));
Edit edit = new Edit(toEnd.length() +1, 0, fromStart);
try{
toEnd.edit(edit);
}catch(Exception e){
throw new BioError(e, "Couldn't construct subList, this shouldn't happen");
}
return toEnd;
}
}
}
|
Documentation improvements
git-svn-id: ed25c26de1c5325e8eb0deed0b990ab8af8a4def@2094 7c6358e6-4a41-0410-a743-a5b2a554c398
|
src/org/biojava/bio/seq/CircularView.java
|
Documentation improvements
|
<ide><path>rc/org/biojava/bio/seq/CircularView.java
<ide> * Note that base zero is the base immediately before base 1 which is of course
<ide> * the last base of the sequence.
<ide> * </p>
<add> * @param index the index of the <code>Symbol </code>requested.
<add> * @return the <code>Symbol </code>specified by the <code>index.</code>
<ide> */
<ide> public Symbol symbolAt(int index){
<ide> return super.symbolAt(realValue(index));
<ide> * <p>
<ide> * Will return a linear String which can, if nescessary, span the origin.
<ide> * </p>
<del> *
<add> * @param start the index of the fist base
<add> * @param end the index of the last base
<add> * @return a <code>String </code>representation of the tokenized <code>Symbol</code>s
<ide> */
<ide> public String subStr(int start, int end){
<ide>
<ide> * @since 1.2
<ide> * @throws BioException if a non circular location is added that exceeds the
<ide> * 'boundaries' of the sequence.
<add> * @throws ChangeVetoException if the sequence is locked.
<add> * @param template the template of the feature to be created.
<add> * @return the feature created you can use the template of the returned feature
<add> * to create another of the same type.
<ide> */
<ide> public Feature createFeature(Feature.Template template)
<ide> throws ChangeVetoException, BioException
<ide> * <p>
<ide> * Will return a linear SymbolList which can ,if nescessary, span the origin.
<ide> * </p>
<add> * @param start the first base of the sublist
<add> * @param end the last base of the sublist
<add> * @return a <code>SymbolList </code>containing the <code>Symbols</code> from
<add> * <code>start</code> to <code>end</code> inclusive
<ide> */
<ide> public SymbolList subList(int start, int end){
<ide>
|
|
Java
|
bsd-3-clause
|
360b8906734747b5c4e8f5601e324d635f64bf41
| 0 |
ahmadia/AbstractRendering,ahmadia/AbstractRendering,JosephCottam/AbstractRendering,ahmadia/AbstractRendering,JosephCottam/AbstractRendering,JosephCottam/AbstractRendering,ahmadia/AbstractRendering,ahmadia/AbstractRendering,JosephCottam/AbstractRendering,JosephCottam/AbstractRendering
|
package ar.rules;
import java.awt.Shape;
import java.awt.geom.GeneralPath;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import ar.Aggregates;
import ar.Glyphset;
import ar.Renderer;
import ar.Transfer;
import ar.glyphsets.GlyphList;
import ar.glyphsets.SimpleGlyph;
import ar.rules.combinators.Fan;
import ar.util.Util;
import ar.aggregates.Iterator2D;
//Base algorithm: http://en.wikipedia.org/wiki/Marching_squares
//Another implementation that does sub-cell interpolation for smoother contours: http://udel.edu/~mm/code/marchingSquares
//TODO: Better ISO contour picking (round numbers?)
public interface ISOContours<N> extends Transfer.Specialized<N,N> {
public ContourAggregates<N> process(Aggregates<? extends N> aggregates, Renderer rend);
/**Produce a set of ISO contours that are spaced at the given interval.**/
public static class SpacedContours<N extends Number> implements Transfer<N,N> {
final double spacing;
final N floor;
final boolean fill;
/**@param spacing How far apart to place contours
* @param floor Lowest contour value (if omitted, will be the min value in the input)
*/
public SpacedContours(double spacing, N floor, boolean fill) {
this.spacing = spacing;
this.floor = floor;
this.fill = fill;
}
public N emptyValue() {return null;}
@Override
public ar.Transfer.Specialized<N, N> specialize(Aggregates<? extends N> aggregates) {
return new Specialized<>(spacing, floor, fill, aggregates);
}
public static final class Specialized<N extends Number> extends SpacedContours<N> implements ISOContours<N> {
final List<N> contourLevels;
public Specialized(double spacing, N floor, boolean fill, Aggregates<? extends N> aggregates) {
super(spacing, floor, fill);
Util.Stats<N> stats = Util.stats(aggregates, true, true, true);
N bottom = floor == null ? (N) stats.min : floor;
contourLevels = LocalUtils.steps(bottom, stats.max, spacing);
}
@Override public ContourAggregates<N> process(Aggregates<? extends N> aggregates, Renderer rend) {
Single<N>[] ts = LocalUtils.stepTransfers(contourLevels, fill);
Transfer.Specialized<N,N> t = new Fan.Specialized<>(
new MergeContours<N>(aggregates.defaultValue()),
ts,
aggregates);
return (ContourAggregates<N>) rend.transfer(aggregates, t);
}
}
}
/**Produce N contours, evenly spaced between max and min.**/
public static class NContours<N extends Number> implements Transfer<N,N> {
final int n;
final boolean fill;
public NContours(int n, boolean fill) {
this.n = n;
this.fill = fill;
}
public N emptyValue() {return null;}
@Override
public ar.Transfer.Specialized<N, N> specialize(Aggregates<? extends N> aggregates) {
return new NContours.Specialized<>( n, fill, aggregates);
}
public static final class Specialized<N extends Number> extends NContours<N> implements ISOContours<N>, Transfer.Specialized<N, N> {
final List<N> contourLevels;
public Specialized(int n, boolean fill, Aggregates<? extends N> aggregates) {
super(n, fill);
Util.Stats<N> stats = Util.stats(aggregates, true, true, true);
double spacing = (stats.max.doubleValue()-stats.min.doubleValue())/n;
contourLevels = LocalUtils.steps(stats.min, stats.max, spacing);
}
@Override public ContourAggregates<N> process(Aggregates<? extends N> aggregates, Renderer rend) {
Single<N>[] ts = LocalUtils.stepTransfers(contourLevels, fill);
Transfer.Specialized<N,N> t = new Fan.Specialized<>(
new MergeContours<N>(aggregates.defaultValue()),
ts,
aggregates);
return (ContourAggregates<N>) rend.transfer(aggregates, t);
}
}
}
/**Produce a single ISO contour at the given division point.**/
public static class Single<N extends Number> implements ISOContours<N> {
protected final N threshold;
protected final boolean fill;
public Single(N threshold, boolean fill) {
this.threshold = threshold;
this.fill = fill;
}
@Override public N emptyValue() {return null;}
@Override public Transfer.Specialized<N, N> specialize(Aggregates<? extends N> aggregates) {return this;}
@Override public ContourAggregates<N> process(Aggregates<? extends N> aggregates, Renderer rend) {
Aggregates<? extends N> padAggs = new PadAggregates<>(aggregates, null);
Aggregates<Boolean> isoDivided = rend.transfer(padAggs, new ISOBelow<>(threshold));
Aggregates<MC_TYPE> classified = rend.transfer(isoDivided, new MCClassifier());
Shape s = Assembler.assembleContours(classified, isoDivided);
GlyphList<Shape, N> contours = new GlyphList<>();
contours.add(new SimpleGlyph<>(s, threshold));
if (!fill) {isoDivided = rend.transfer(isoDivided, new General.Simplify<>(isoDivided.defaultValue()));}
Aggregates<N> base = rend.transfer(isoDivided, new General.MapWrapper<>(true, threshold, LocalUtils.zeroLike(threshold))); //TODO: Is zero-ing the right thing to do? May cause problems for ISO contours of values crossing the zero-boundary...
return new ContourAggregates<>(base, contours);
}
}
public static class LocalUtils {
/**
* @param bottom Lowest value to be included
* @param top Highest value to be included
* @param spacing How far apart should the contours be placed?
* @return List of the contour step values
*/
public static <N extends Number> List<N> steps(N bottom, N top, double spacing) {
int stepCount = (int) Math.ceil((top.doubleValue()-bottom.doubleValue())/spacing);
ArrayList<N> steps = new ArrayList<>(stepCount);
for (int i=0; i<stepCount; i++) {steps.add(LocalUtils.addTo(bottom, (i*spacing)));}
return steps;
}
/**Create a transfer for each step in passed list.**/
public static <N extends Number> Single<N>[] stepTransfers(List<N> steps, boolean fill) {
@SuppressWarnings("unchecked")
Single<N>[] ts = new Single[steps.size()];
for (int i=0; i<steps.size(); i++) {ts[i] = new Single<>(steps.get(i), fill);}
return ts;
}
@SuppressWarnings("unchecked")
public static <N extends Number> N addTo(N val, double more) {
if (val instanceof Double) {return (N) new Double(((Double) val).doubleValue()+more);}
if (val instanceof Float) {return (N) new Float(((Float) val).floatValue()+more);}
if (val instanceof Long) {return (N) new Long((long) (((Long) val).longValue()+more));}
if (val instanceof Integer) {return (N) new Integer((int) (((Integer) val).intValue()+more));}
if (val instanceof Short) {return (N) new Short((short) (((Short) val).shortValue()+more));}
throw new IllegalArgumentException("Cannot add to " + val.getClass().getName());
}
@SuppressWarnings("unchecked")
public static <N extends Number> N zeroLike(N val) {
if (val instanceof Double) {return (N) (Double) 0d;}
if (val instanceof Float) {return (N) (Float) 0f;}
if (val instanceof Long) {return (N) (Long) 0l;}
if (val instanceof Integer) {return (N) (Integer) 0;}
if (val instanceof Short) {return (N) (Short) (short)0;}
throw new IllegalArgumentException("Cannot add to " + val.getClass().getName());
}
}
public static final class Assembler {
/** Build a single path from all of the contour parts.
*
* May be disjoint and have holes (thus GeneralPath).
*
* @param classified The line-segment classifiers
* @param isoDivided Original classification, used to disambiguate saddle conditions
* @return
*/
public static final GeneralPath assembleContours(Aggregates<MC_TYPE> classified, Aggregates<Boolean> isoDivided) {
GeneralPath isoPath = new GeneralPath(GeneralPath.WIND_EVEN_ODD);
//Find an unambiguous case of an actual line, follow it around and build the line.
//Stitching sets the line segments that have been "consumed" to MC_TYPE.empty, so segments are only processed once.
for (int x = classified.lowX(); x < classified.highX(); x++) {
for (int y = classified.lowY(); y < classified.highY(); y++) {
MC_TYPE type = classified.get(x, y);
if (type != MC_TYPE.empty
&& type != MC_TYPE.surround
&& type != MC_TYPE.diag_one
&& type != MC_TYPE.diag_two) {
stichContour(classified, isoDivided, isoPath, x, y);
}
}
}
return isoPath;
}
/**An iso level can be made of multiple regions with holes in them.
* This builds one path (into the passed GeneralPath) that represents one
* connected contour.
*
* @param isoData Marching-cubes classification at each cell
* @param isoDivided The boolean above/below classification for each cell (to disambiguate saddles)
* @param iso The path to build into
*/
public static void stichContour(Aggregates<MC_TYPE> isoData, Aggregates<Boolean> isoDivided, GeneralPath iso, int startX, int startY) {
int x=startX, y=startY;
SIDE prevSide = SIDE.NONE;
// Found an unambiguous iso line at [r][c], so start there.
MC_TYPE startCell = isoData.get(x,y);
Point2D nextPoint = startCell.firstSide(prevSide).nextPoint(x,y);
iso.moveTo(nextPoint.getX(), nextPoint.getY());
prevSide = isoData.get(x,y).secondSide(prevSide, isoDivided.get(x,y));
//System.out.printf("-------------------\n);
do {
//Process current cell
MC_TYPE curCell = isoData.get(x,y);
nextPoint = curCell.secondSide(prevSide, isoDivided.get(x,y)).nextPoint(x,y);
//System.out.printf("%d,%d: %s\n",x,y,curCell.secondSide(prevSide, isoDivided.get(x,y)));
iso.lineTo(nextPoint.getX(), nextPoint.getY());
SIDE nextSide = curCell.secondSide(prevSide, isoDivided.get(x,y));
isoData.set(x,y, curCell.clearWith()); // Erase this marching cube line entry
//Advance for next cell
prevSide = nextSide;
switch (nextSide) {
case LEFT: x -= 1; break;
case RIGHT: x += 1; break;
case BOTTOM: y += 1; break;
case TOP: y -= 1; break;
case NONE: throw new IllegalArgumentException("Encountered side NONE after starting contour line.");
}
} while (x != startX || y != startY);
iso.closePath();
}
}
/**Classifies each cell as above or below the given ISO value
*TODO: Are doubles enough? Should there be number-type-specific implementations?
**/
public static final class ISOBelow<N extends Number> implements Transfer.ItemWise<N, Boolean> {
private final Number threshold;
public ISOBelow(Number threshold) {
this.threshold = threshold;
}
@Override public Boolean emptyValue() {return Boolean.FALSE;}
@Override public Specialized<N, Boolean> specialize(Aggregates<? extends N> aggregates) {return this;}
@Override
public Boolean at(int x, int y, Aggregates<? extends N> aggregates) {
Number v = aggregates.get(x,y);
if (v == null) {return false;}
double delta = threshold.doubleValue() - v.doubleValue();
return delta < 0;
}
@Override
public Aggregates<Boolean> process(Aggregates<? extends N> aggregates,Renderer rend) {
return rend.transfer(aggregates, this);
}
}
public static enum SIDE {
NONE, LEFT, RIGHT, BOTTOM, TOP;
public Point2D nextPoint(int x, int y) {
switch (this) {
case LEFT: return new Point2D.Double(x-1, y);
case RIGHT: return new Point2D.Double(x+1, y);
case BOTTOM: return new Point2D.Double(x, y+1);
case TOP: return new Point2D.Double(x, y-1);
default: throw new IllegalArgumentException("No 'nextPoint' defiend for NONE.");
}
}
}
//Named according to scan-line convention
//ui is "up index" which is lower on the screen
//di is "down index" which is higher on the screen
public static enum MC_TYPE {
empty(0b0000),
surround(0b1111),
ui_l_out(0b1110),
ui_r_out(0b1101),
di_r_out(0b1011),
di_l_out(0b0111),
ui_l_in(0b0001),
ui_r_in(0b0010),
di_r_in(0b0100),
di_l_in(0b1000),
di_in(0b1100),
l_in(0b1001),
ui_in(0b0011),
r_in(0b0110),
diag_two(0b1010), //Ambiguous case
diag_one(0b0101); //Ambiguous case
public final int idx;
MC_TYPE(int idx) {this.idx = idx;}
public MC_TYPE clearWith() {
switch (this) {
case empty: case surround: case diag_two: case diag_one: return this;
default: return MC_TYPE.empty;
}
}
public SIDE firstSide(SIDE prev) {
switch (this) {
case ui_l_in: case ui_in: case di_l_out:
//case 1: case 3: case 7:
return SIDE.LEFT;
case ui_r_in: case r_in: case ui_l_out:
//case 2: case 6: case 14:
return SIDE.BOTTOM;
case di_r_in: case di_in: case ui_r_out:
//case 4: case 12: case 13:
return SIDE.RIGHT;
case di_l_in: case l_in: case di_r_out:
//case 8: case 9: case 11:
return SIDE.TOP;
case diag_one:
//case 5:
switch (prev) {
case LEFT:
return SIDE.RIGHT;
case RIGHT:
return SIDE.LEFT;
default:
throw new RuntimeException(String.format("Illegal previous (%s) case for current case (%s)", prev.name(), this.name()));
}
case diag_two:
//case 10:
switch (prev) {
case BOTTOM:
return SIDE.TOP;
case TOP:
return SIDE.BOTTOM;
default:
throw new RuntimeException(String.format("Illegal previous (%s) case for current case (%s)", prev.name(), this.name()));
}
default:
throw new RuntimeException("Cannot determine side for case of " + this.name());
}
}
public SIDE secondSide(SIDE prev, boolean flipped) {
switch (this) {
case di_l_in: case di_in: case ui_l_out:
//case 8: case 12: case 14:
return SIDE.LEFT;
case ui_l_in: case l_in: case ui_r_out:
//case 1: case 9: case 13:
return SIDE.BOTTOM;
case ui_r_in: case ui_in: case di_r_out:
//case 2: case 3: case 11:
return SIDE.RIGHT;
case di_r_in: case r_in: case di_l_out:
//case 4: case 6: case 7:
return SIDE.TOP;
case diag_one:
//case 5:
switch (prev) {
case LEFT:
return flipped ? SIDE.BOTTOM : SIDE.TOP;
case RIGHT:
return flipped ? SIDE.TOP : SIDE.BOTTOM;
default:
throw new RuntimeException(String.format("Illegal previous (%s) case for current case (%s)", prev.name(), this.name()));
}
case diag_two:
//case 10:
switch (prev) {
case BOTTOM:
return flipped ? SIDE.RIGHT : SIDE.LEFT;
case TOP:
return flipped ? SIDE.LEFT : SIDE.RIGHT;
default:
throw new RuntimeException(String.format("Illegal previous (%s) case for current case (%s)", prev.name(), this.name()));
}
default:
throw new RuntimeException("Cannot determine side for case of " + this.name());
}
}
private static final Map<Integer,MC_TYPE> lookup = new HashMap<>();
static {for(MC_TYPE mct : EnumSet.allOf(MC_TYPE.class))lookup.put(mct.idx, mct);}
public static MC_TYPE get(int code) {return lookup.get(code);}
}
public static final class MCClassifier implements Transfer.ItemWise<Boolean, MC_TYPE> {
private final int DOWN_INDEX_LEFT = 0b1000;
private final int DOWN_INDEX_RIGHT = 0b0100;
private final int UP_INDEX_RIGHT = 0b0010;
private final int UP_INDEX_LEFT = 0b0001;
public MC_TYPE emptyValue() {return MC_TYPE.empty;}
@Override
public Specialized<Boolean, MC_TYPE> specialize(Aggregates<? extends Boolean> aggregates) {return this;}
@Override
public MC_TYPE at(int x, int y, Aggregates<? extends Boolean> aggregates) {
int code = 0;
if (aggregates.get(x-1,y-1)) {code = code | DOWN_INDEX_LEFT;}
if (aggregates.get(x,y-1)) {code = code | DOWN_INDEX_RIGHT;}
if (aggregates.get(x-1,y)) {code = code | UP_INDEX_LEFT;}
if (aggregates.get(x,y)) {code = code | UP_INDEX_RIGHT;}
return MC_TYPE.get(code);
}
@Override
public Aggregates<MC_TYPE> process(Aggregates<? extends Boolean> aggregates, Renderer rend) {
return rend.transfer(aggregates, this);
}
}
/**Adds a row and column to each side of an aggregate set filled with a specific value.
*
* Only the original range remains set-able.**/
public static final class PadAggregates<A> implements Aggregates<A> {
private final Aggregates<? extends A> base;
private final A pad;
public PadAggregates(Aggregates<? extends A> base, A pad) {
this.base = base;
this.pad =pad;
}
@Override
public Iterator<A> iterator() {return new Iterator2D<A>(this);}
@Override
public A get(int x, int y) {
if ((x >= base.lowX() && x < base.highX())
&& (y >= base.lowY() && y < base.highY())) {
return base.get(x,y); //Its inside
} else if ((x == base.lowX()-1 || x== base.highX()+1)
&& (y >= base.lowY()-1 && y < base.highY()+1)) {
return pad; //Its immediate above or below
} else if ((y == base.lowY()-1 || y == base.highY()+1)
&& (x >= base.lowX()-1 && x < base.highX()+1)) {
return pad; //Its immediately left or right
} else {
return base.defaultValue();
}
}
public void set(int x, int y, A val) {throw new UnsupportedOperationException();}
public A defaultValue() {return base.defaultValue();}
public int lowX() {return base.lowX()-1;}
public int lowY() {return base.lowY()-1;}
public int highX() {return base.highX()+1;}
public int highY() {return base.highY()+1;}
}
/**Fan-merge that will also combine the contours.
*
* TODO: Verify or enforce contour sorting...
* **/
public static final class MergeContours<A> implements Fan.Merge<A> {
private final Fan.Merge<A> base;
public MergeContours(A defaultValue) {
this.base = new Fan.AggregatorMerge<>(new General.Last<A>(defaultValue));
}
@Override
public Aggregates<A> merge(Aggregates<A> left, Aggregates<A> right) {
Aggregates<A> raw = base.merge(left, right);
GlyphList<Shape, A> contours = new GlyphList<>();
if (left instanceof ContourAggregates) {contours.addAll(((ContourAggregates<A>) left).contours);}
if (right instanceof ContourAggregates) {contours.addAll(((ContourAggregates<A>) right).contours);}
return new ContourAggregates<>(raw, contours);
}
@Override public A identity() {return base.identity();}
}
public static final class ContourAggregates<A> implements Aggregates<A> {
private final Aggregates<A> base;
private final Glyphset.RandomAccess<Shape, A> contours;
public ContourAggregates(Aggregates<A> base, Glyphset.RandomAccess<Shape, A> contours) {
this.base = base instanceof ContourAggregates ? ((ContourAggregates<A>) base).base : base;
this.contours = contours;
}
/**List of contours from smallest value to largest value.**/
public Glyphset.RandomAccess<Shape, A> contours() {return contours;}
@Override public Iterator<A> iterator() {return base.iterator();}
@Override public A get(int x, int y) {return base.get(x,y);}
@Override public void set(int x, int y, A val) {base.set(x,y, val);}
@Override public A defaultValue() {return base.defaultValue();}
@Override public int lowX() {return base.lowX();}
@Override public int lowY() {return base.lowY();}
@Override public int highX() {return base.highX();}
@Override public int highY() {return base.highY();}
}
}
|
java/core/ar/rules/ISOContours.java
|
package ar.rules;
import java.awt.Shape;
import java.awt.geom.GeneralPath;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import ar.Aggregates;
import ar.Glyphset;
import ar.Renderer;
import ar.Transfer;
import ar.glyphsets.GlyphList;
import ar.glyphsets.SimpleGlyph;
import ar.rules.combinators.Fan;
import ar.util.Util;
import ar.aggregates.Iterator2D;
//Base algorithm: http://en.wikipedia.org/wiki/Marching_squares
//Another implementation that does sub-cell interpolation for smoother contours: http://udel.edu/~mm/code/marchingSquares
//TODO: Better ISO contour picking (round numbers?)
public interface ISOContours<N> extends Transfer.Specialized<N,N> {
public ContourAggregates<N> process(Aggregates<? extends N> aggregates, Renderer rend);
/**Produce a set of ISO contours that are spaced at the given interval.**/
public static class SpacedContours<N extends Number> implements Transfer<N,N> {
final double spacing;
final N floor;
final boolean fill;
/**@param spacing How far apart to place contours
* @param floor Lowest contour value (if omitted, will be the min value in the input)
*/
public SpacedContours(double spacing, N floor, boolean fill) {
this.spacing = spacing;
this.floor = floor;
this.fill = fill;
}
public N emptyValue() {return null;}
@Override
public ar.Transfer.Specialized<N, N> specialize(Aggregates<? extends N> aggregates) {
return new Specialized<>(spacing, floor, fill, aggregates);
}
public static final class Specialized<N extends Number> extends SpacedContours<N> implements ISOContours<N> {
final List<N> contourLevels;
public Specialized(double spacing, N floor, boolean fill, Aggregates<? extends N> aggregates) {
super(spacing, floor, fill);
Util.Stats<N> stats = Util.stats(aggregates, true, true, true);
N bottom = floor == null ? (N) stats.min : floor;
contourLevels = LocalUtils.steps(bottom, stats.max, spacing);
}
@Override public ContourAggregates<N> process(Aggregates<? extends N> aggregates, Renderer rend) {
Single<N>[] ts = LocalUtils.stepTransfers(contourLevels, fill);
Transfer.Specialized<N,N> t = new Fan.Specialized<>(
new MergeContours<N>(aggregates.defaultValue()),
ts,
aggregates);
return (ContourAggregates<N>) rend.transfer(aggregates, t);
}
}
}
/**Produce N contours, evenly spaced between max and min.**/
public static class NContours<N extends Number> implements Transfer<N,N> {
final int n;
final boolean fill;
public NContours(int n, boolean fill) {
this.n = n;
this.fill = fill;
}
public N emptyValue() {return null;}
@Override
public ar.Transfer.Specialized<N, N> specialize(Aggregates<? extends N> aggregates) {
return new NContours.Specialized<>( n, fill, aggregates);
}
public static final class Specialized<N extends Number> extends NContours<N> implements ISOContours<N>, Transfer.Specialized<N, N> {
final List<N> contourLevels;
public Specialized(int n, boolean fill, Aggregates<? extends N> aggregates) {
super(n, fill);
Util.Stats<N> stats = Util.stats(aggregates, true, true, true);
double spacing = (stats.max.doubleValue()-stats.min.doubleValue())/n;
contourLevels = LocalUtils.steps(stats.min, stats.max, spacing);
}
@Override public ContourAggregates<N> process(Aggregates<? extends N> aggregates, Renderer rend) {
Single<N>[] ts = LocalUtils.stepTransfers(contourLevels, fill);
Transfer.Specialized<N,N> t = new Fan.Specialized<>(
new MergeContours<N>(aggregates.defaultValue()),
ts,
aggregates);
return (ContourAggregates<N>) rend.transfer(aggregates, t);
}
}
}
/**Produce a single ISO contour at the given division point.**/
public static class Single<N extends Number> implements ISOContours<N> {
protected final N threshold;
protected final boolean fill;
public Single(N threshold, boolean fill) {
this.threshold = threshold;
this.fill = fill;
}
@Override public N emptyValue() {return null;}
@Override public Transfer.Specialized<N, N> specialize(Aggregates<? extends N> aggregates) {return this;}
@Override public ContourAggregates<N> process(Aggregates<? extends N> aggregates, Renderer rend) {
Aggregates<? extends N> padAggs = new PadAggregates<>(aggregates, null);
Aggregates<Boolean> isoDivided = rend.transfer(padAggs, new ISOBelow<>(threshold));
Aggregates<MC_TYPE> classified = rend.transfer(isoDivided, new MCClassifier());
Shape s = Assembler.assembleContours(classified, isoDivided);
GlyphList<Shape, N> contours = new GlyphList<>();
contours.add(new SimpleGlyph<>(s, threshold));
if (!fill) {isoDivided = rend.transfer(isoDivided, new General.Simplify<>(isoDivided.defaultValue()));}
Aggregates<N> base = rend.transfer(isoDivided, new General.MapWrapper<>(true, threshold, null));
return new ContourAggregates<>(base, contours);
}
}
public static class LocalUtils {
/**
* @param bottom Lowest value to be included
* @param top Highest value to be included
* @param spacing How far apart should the contours be placed?
* @return List of the contour step values
*/
public static <N extends Number> List<N> steps(N bottom, N top, double spacing) {
int stepCount = (int) Math.ceil((top.doubleValue()-bottom.doubleValue())/spacing);
ArrayList<N> steps = new ArrayList<>(stepCount);
for (int i=0; i<stepCount; i++) {steps.add(LocalUtils.addTo(bottom, (i*spacing)));}
return steps;
}
/**Create a transfer for each step in passed list.**/
public static <N extends Number> Single<N>[] stepTransfers(List<N> steps, boolean fill) {
@SuppressWarnings("unchecked")
Single<N>[] ts = new Single[steps.size()];
for (int i=0; i<steps.size(); i++) {ts[i] = new Single<>(steps.get(i), fill);}
return ts;
}
@SuppressWarnings("unchecked")
public static <N extends Number> N addTo(N val, double more) {
if (val instanceof Double) {return (N) new Double(((Double) val).doubleValue()+more);}
if (val instanceof Float) {return (N) new Float(((Float) val).floatValue()+more);}
if (val instanceof Long) {return (N) new Long((long) (((Long) val).longValue()+more));}
if (val instanceof Integer) {return (N) new Integer((int) (((Integer) val).intValue()+more));}
if (val instanceof Short) {return (N) new Short((short) (((Short) val).shortValue()+more));}
throw new IllegalArgumentException("Cannot add to " + val.getClass().getName());
}
}
public static final class Assembler {
/** Build a single path from all of the contour parts.
*
* May be disjoint and have holes (thus GeneralPath).
*
* @param classified The line-segment classifiers
* @param isoDivided Original classification, used to disambiguate saddle conditions
* @return
*/
public static final GeneralPath assembleContours(Aggregates<MC_TYPE> classified, Aggregates<Boolean> isoDivided) {
GeneralPath isoPath = new GeneralPath(GeneralPath.WIND_EVEN_ODD);
//Find an unambiguous case of an actual line, follow it around and build the line.
//Stitching sets the line segments that have been "consumed" to MC_TYPE.empty, so segments are only processed once.
for (int x = classified.lowX(); x < classified.highX(); x++) {
for (int y = classified.lowY(); y < classified.highY(); y++) {
MC_TYPE type = classified.get(x, y);
if (type != MC_TYPE.empty
&& type != MC_TYPE.surround
&& type != MC_TYPE.diag_one
&& type != MC_TYPE.diag_two) {
stichContour(classified, isoDivided, isoPath, x, y);
}
}
}
return isoPath;
}
/**An iso level can be made of multiple regions with holes in them.
* This builds one path (into the passed GeneralPath) that represents one
* connected contour.
*
* @param isoData Marching-cubes classification at each cell
* @param isoDivided The boolean above/below classification for each cell (to disambiguate saddles)
* @param iso The path to build into
*/
public static void stichContour(Aggregates<MC_TYPE> isoData, Aggregates<Boolean> isoDivided, GeneralPath iso, int startX, int startY) {
int x=startX, y=startY;
SIDE prevSide = SIDE.NONE;
// Found an unambiguous iso line at [r][c], so start there.
MC_TYPE startCell = isoData.get(x,y);
Point2D nextPoint = startCell.firstSide(prevSide).nextPoint(x,y);
iso.moveTo(nextPoint.getX(), nextPoint.getY());
prevSide = isoData.get(x,y).secondSide(prevSide, isoDivided.get(x,y));
//System.out.printf("-------------------\n);
do {
//Process current cell
MC_TYPE curCell = isoData.get(x,y);
nextPoint = curCell.secondSide(prevSide, isoDivided.get(x,y)).nextPoint(x,y);
//System.out.printf("%d,%d: %s\n",x,y,curCell.secondSide(prevSide, isoDivided.get(x,y)));
iso.lineTo(nextPoint.getX(), nextPoint.getY());
SIDE nextSide = curCell.secondSide(prevSide, isoDivided.get(x,y));
isoData.set(x,y, curCell.clearWith()); // Erase this marching cube line entry
//Advance for next cell
prevSide = nextSide;
switch (nextSide) {
case LEFT: x -= 1; break;
case RIGHT: x += 1; break;
case BOTTOM: y += 1; break;
case TOP: y -= 1; break;
case NONE: throw new IllegalArgumentException("Encountered side NONE after starting contour line.");
}
} while (x != startX || y != startY);
iso.closePath();
}
}
/**Classifies each cell as above or below the given ISO value
*TODO: Are doubles enough? Should there be number-type-specific implementations?
**/
public static final class ISOBelow<N extends Number> implements Transfer.ItemWise<N, Boolean> {
private final Number threshold;
public ISOBelow(Number threshold) {
this.threshold = threshold;
}
@Override public Boolean emptyValue() {return Boolean.FALSE;}
@Override public Specialized<N, Boolean> specialize(Aggregates<? extends N> aggregates) {return this;}
@Override
public Boolean at(int x, int y, Aggregates<? extends N> aggregates) {
Number v = aggregates.get(x,y);
if (v == null) {return false;}
double delta = threshold.doubleValue() - v.doubleValue();
return delta < 0;
}
@Override
public Aggregates<Boolean> process(Aggregates<? extends N> aggregates,Renderer rend) {
return rend.transfer(aggregates, this);
}
}
public static enum SIDE {
NONE, LEFT, RIGHT, BOTTOM, TOP;
public Point2D nextPoint(int x, int y) {
switch (this) {
case LEFT: return new Point2D.Double(x-1, y);
case RIGHT: return new Point2D.Double(x+1, y);
case BOTTOM: return new Point2D.Double(x, y+1);
case TOP: return new Point2D.Double(x, y-1);
default: throw new IllegalArgumentException("No 'nextPoint' defiend for NONE.");
}
}
}
//Named according to scan-line convention
//ui is "up index" which is lower on the screen
//di is "down index" which is higher on the screen
public static enum MC_TYPE {
empty(0b0000),
surround(0b1111),
ui_l_out(0b1110),
ui_r_out(0b1101),
di_r_out(0b1011),
di_l_out(0b0111),
ui_l_in(0b0001),
ui_r_in(0b0010),
di_r_in(0b0100),
di_l_in(0b1000),
di_in(0b1100),
l_in(0b1001),
ui_in(0b0011),
r_in(0b0110),
diag_two(0b1010), //Ambiguous case
diag_one(0b0101); //Ambiguous case
public final int idx;
MC_TYPE(int idx) {this.idx = idx;}
public MC_TYPE clearWith() {
switch (this) {
case empty: case surround: case diag_two: case diag_one: return this;
default: return MC_TYPE.empty;
}
}
public SIDE firstSide(SIDE prev) {
switch (this) {
case ui_l_in: case ui_in: case di_l_out:
//case 1: case 3: case 7:
return SIDE.LEFT;
case ui_r_in: case r_in: case ui_l_out:
//case 2: case 6: case 14:
return SIDE.BOTTOM;
case di_r_in: case di_in: case ui_r_out:
//case 4: case 12: case 13:
return SIDE.RIGHT;
case di_l_in: case l_in: case di_r_out:
//case 8: case 9: case 11:
return SIDE.TOP;
case diag_one:
//case 5:
switch (prev) {
case LEFT:
return SIDE.RIGHT;
case RIGHT:
return SIDE.LEFT;
default:
throw new RuntimeException(String.format("Illegal previous (%s) case for current case (%s)", prev.name(), this.name()));
}
case diag_two:
//case 10:
switch (prev) {
case BOTTOM:
return SIDE.TOP;
case TOP:
return SIDE.BOTTOM;
default:
throw new RuntimeException(String.format("Illegal previous (%s) case for current case (%s)", prev.name(), this.name()));
}
default:
throw new RuntimeException("Cannot determine side for case of " + this.name());
}
}
public SIDE secondSide(SIDE prev, boolean flipped) {
switch (this) {
case di_l_in: case di_in: case ui_l_out:
//case 8: case 12: case 14:
return SIDE.LEFT;
case ui_l_in: case l_in: case ui_r_out:
//case 1: case 9: case 13:
return SIDE.BOTTOM;
case ui_r_in: case ui_in: case di_r_out:
//case 2: case 3: case 11:
return SIDE.RIGHT;
case di_r_in: case r_in: case di_l_out:
//case 4: case 6: case 7:
return SIDE.TOP;
case diag_one:
//case 5:
switch (prev) {
case LEFT:
return flipped ? SIDE.BOTTOM : SIDE.TOP;
case RIGHT:
return flipped ? SIDE.TOP : SIDE.BOTTOM;
default:
throw new RuntimeException(String.format("Illegal previous (%s) case for current case (%s)", prev.name(), this.name()));
}
case diag_two:
//case 10:
switch (prev) {
case BOTTOM:
return flipped ? SIDE.RIGHT : SIDE.LEFT;
case TOP:
return flipped ? SIDE.LEFT : SIDE.RIGHT;
default:
throw new RuntimeException(String.format("Illegal previous (%s) case for current case (%s)", prev.name(), this.name()));
}
default:
throw new RuntimeException("Cannot determine side for case of " + this.name());
}
}
private static final Map<Integer,MC_TYPE> lookup = new HashMap<>();
static {for(MC_TYPE mct : EnumSet.allOf(MC_TYPE.class))lookup.put(mct.idx, mct);}
public static MC_TYPE get(int code) {return lookup.get(code);}
}
public static final class MCClassifier implements Transfer.ItemWise<Boolean, MC_TYPE> {
private final int DOWN_INDEX_LEFT = 0b1000;
private final int DOWN_INDEX_RIGHT = 0b0100;
private final int UP_INDEX_RIGHT = 0b0010;
private final int UP_INDEX_LEFT = 0b0001;
public MC_TYPE emptyValue() {return MC_TYPE.empty;}
@Override
public Specialized<Boolean, MC_TYPE> specialize(Aggregates<? extends Boolean> aggregates) {return this;}
@Override
public MC_TYPE at(int x, int y, Aggregates<? extends Boolean> aggregates) {
int code = 0;
if (aggregates.get(x-1,y-1)) {code = code | DOWN_INDEX_LEFT;}
if (aggregates.get(x,y-1)) {code = code | DOWN_INDEX_RIGHT;}
if (aggregates.get(x-1,y)) {code = code | UP_INDEX_LEFT;}
if (aggregates.get(x,y)) {code = code | UP_INDEX_RIGHT;}
return MC_TYPE.get(code);
}
@Override
public Aggregates<MC_TYPE> process(Aggregates<? extends Boolean> aggregates, Renderer rend) {
return rend.transfer(aggregates, this);
}
}
/**Adds a row and column to each side of an aggregate set filled with a specific value.
*
* Only the original range remains set-able.**/
public static final class PadAggregates<A> implements Aggregates<A> {
private final Aggregates<? extends A> base;
private final A pad;
public PadAggregates(Aggregates<? extends A> base, A pad) {
this.base = base;
this.pad =pad;
}
@Override
public Iterator<A> iterator() {return new Iterator2D<A>(this);}
@Override
public A get(int x, int y) {
if ((x >= base.lowX() && x < base.highX())
&& (y >= base.lowY() && y < base.highY())) {
return base.get(x,y); //Its inside
} else if ((x == base.lowX()-1 || x== base.highX()+1)
&& (y >= base.lowY()-1 && y < base.highY()+1)) {
return pad; //Its immediate above or below
} else if ((y == base.lowY()-1 || y == base.highY()+1)
&& (x >= base.lowX()-1 && x < base.highX()+1)) {
return pad; //Its immediately left or right
} else {
return base.defaultValue();
}
}
public void set(int x, int y, A val) {throw new UnsupportedOperationException();}
public A defaultValue() {return base.defaultValue();}
public int lowX() {return base.lowX()-1;}
public int lowY() {return base.lowY()-1;}
public int highX() {return base.highX()+1;}
public int highY() {return base.highY()+1;}
}
/**Fan-merge that will also combine the contours.
*
* TODO: Verify or enforce contour sorting...
* **/
public static final class MergeContours<A> implements Fan.Merge<A> {
private final Fan.Merge<A> base;
public MergeContours(A defaultValue) {
this.base = new Fan.AggregatorMerge<>(new General.Last<A>(defaultValue));
}
@Override
public Aggregates<A> merge(Aggregates<A> left, Aggregates<A> right) {
Aggregates<A> raw = base.merge(left, right);
GlyphList<Shape, A> contours = new GlyphList<>();
if (left instanceof ContourAggregates) {contours.addAll(((ContourAggregates<A>) left).contours);}
if (right instanceof ContourAggregates) {contours.addAll(((ContourAggregates<A>) right).contours);}
return new ContourAggregates<>(raw, contours);
}
@Override public A identity() {return base.identity();}
}
public static final class ContourAggregates<A> implements Aggregates<A> {
private final Aggregates<A> base;
private final Glyphset.RandomAccess<Shape, A> contours;
public ContourAggregates(Aggregates<A> base, Glyphset.RandomAccess<Shape, A> contours) {
this.base = base instanceof ContourAggregates ? ((ContourAggregates<A>) base).base : base;
this.contours = contours;
}
/**List of contours from smallest value to largest value.**/
public Glyphset.RandomAccess<Shape, A> contours() {return contours;}
@Override public Iterator<A> iterator() {return base.iterator();}
@Override public A get(int x, int y) {return base.get(x,y);}
@Override public void set(int x, int y, A val) {base.set(x,y, val);}
@Override public A defaultValue() {return base.defaultValue();}
@Override public int lowX() {return base.lowX();}
@Override public int lowY() {return base.lowY();}
@Override public int highX() {return base.highX();}
@Override public int highY() {return base.highY();}
}
}
|
Fixed contour-zero-ing issues.
|
java/core/ar/rules/ISOContours.java
|
Fixed contour-zero-ing issues.
|
<ide><path>ava/core/ar/rules/ISOContours.java
<ide>
<ide> contours.add(new SimpleGlyph<>(s, threshold));
<ide> if (!fill) {isoDivided = rend.transfer(isoDivided, new General.Simplify<>(isoDivided.defaultValue()));}
<del> Aggregates<N> base = rend.transfer(isoDivided, new General.MapWrapper<>(true, threshold, null));
<add> Aggregates<N> base = rend.transfer(isoDivided, new General.MapWrapper<>(true, threshold, LocalUtils.zeroLike(threshold))); //TODO: Is zero-ing the right thing to do? May cause problems for ISO contours of values crossing the zero-boundary...
<ide> return new ContourAggregates<>(base, contours);
<ide> }
<ide> }
<ide> if (val instanceof Long) {return (N) new Long((long) (((Long) val).longValue()+more));}
<ide> if (val instanceof Integer) {return (N) new Integer((int) (((Integer) val).intValue()+more));}
<ide> if (val instanceof Short) {return (N) new Short((short) (((Short) val).shortValue()+more));}
<add> throw new IllegalArgumentException("Cannot add to " + val.getClass().getName());
<add> }
<add>
<add>
<add> @SuppressWarnings("unchecked")
<add> public static <N extends Number> N zeroLike(N val) {
<add> if (val instanceof Double) {return (N) (Double) 0d;}
<add> if (val instanceof Float) {return (N) (Float) 0f;}
<add> if (val instanceof Long) {return (N) (Long) 0l;}
<add> if (val instanceof Integer) {return (N) (Integer) 0;}
<add> if (val instanceof Short) {return (N) (Short) (short)0;}
<ide> throw new IllegalArgumentException("Cannot add to " + val.getClass().getName());
<ide> }
<ide> }
|
|
Java
|
mit
|
daa51e63d18730898425dee7c4ff92da820f3080
| 0 |
SMOHAMMEDY/formationdta-072016,SMOHAMMEDY/formationdta-072016,SMOHAMMEDY/formationdta-072016
|
package fr.pizzeria.ihm;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.time.DateFormatUtils;
import fr.pizzeria.exception.SaisieEntierException;
public class Menu {
public static void Calendar(){
Date date = null;
Calendar.getInstance().setTime(date);
}
private static final int CHOIX_SORTIR = 99;
private Map<Integer, Action> actions = new HashMap<>();
private IhmHelper ihmHelper;
public Menu(IhmHelper helper) {
this.actions.put(1, new ListerPizzaAction(helper));
this.actions.put(2, new AjouterPizzaAction(helper));
this.actions.put(3, new ModifierPizzaAction(helper));
this.actions.put(4, new SupprimerPizzaAction(helper));
this.actions.put(5, new ListerClientAction(helper));
this.actions.put(6, new AjouterClientAction(helper));
this.actions.put(7, new CrediterClientAction(helper));
this.actions.put(8, new DebiterClientAction(helper));
this.actions.put(9, new ListerLivreurAction(helper));
this.actions.put(10, new AfficherCompteStatAction(helper));
this.actions.put(11, new VirementClientAction(helper));
this.ihmHelper = helper;
}
public void start() {
boolean result = false;
do {
affichageM();
result = choisir();
} while (!result);
}
public void affichageM() {
System.out.println("***** Super Pizzeria Administration *****");
//// maven afficher la date du jour avec la librairie du td
Calendar now = Calendar.getInstance();
DateFormatUtils.format(now, "yyyy.MM.dd G 'at' HH:mm:ss z");
System.out.println(DateFormatUtils.format(now, "dd/MM-HH:mm"));
for (Integer numero : actions.keySet()) {
Action ActionEnCours = actions.get(numero);
String libelleAction = ActionEnCours.getLibelle();
System.out.println(numero + " " + libelleAction);
}
System.out.println(CHOIX_SORTIR + ". Quitter" + "\n");
}
private void SimpleDateFormat(Calendar now) {
// TODO Auto-generated method stub
}
public boolean choisir() {
System.out.println("Veuillez choisir une option");
int choix = 0;
try {
// Instructions susceptibles de provoquer des erreurs;
choix = ihmHelper.saisirEntier();
if (!actions.containsKey(choix)) {
if (choix != CHOIX_SORTIR) {
System.out.println("Erreur de saisie, veuillez recommencer!" + "\n");
}
} else {
Action LaBonneAction = actions.get(choix);
LaBonneAction.execute();
}
} catch (SaisieEntierException e) {
System.out.println(e.getMessage());
}
return choix == CHOIX_SORTIR;
}
}
|
pizzeria-console-objet/src/main/java/fr/pizzeria/ihm/Menu.java
|
package fr.pizzeria.ihm;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.time.DateFormatUtils;
import fr.pizzeria.exception.SaisieEntierException;
public class Menu {
public static void Calendar(){
Date date = null;
Calendar.getInstance().setTime(date);
}
private static final int CHOIX_SORTIR = 99;
private Map<Integer, Action> actions = new HashMap<>();
private IhmHelper ihmHelper;
public Menu(IhmHelper helper) {
this.actions.put(1, new ListerPizzaAction(helper));
this.actions.put(2, new AjouterPizzaAction(helper));
this.actions.put(3, new ModifierPizzaAction(helper));
this.actions.put(4, new SupprimerPizzaAction(helper));
this.actions.put(5, new ListerClientAction(helper));
this.actions.put(6, new AjouterClientAction(helper));
this.actions.put(7, new CrediterClientAction(helper));
this.actions.put(8, new DebiterClientAction(helper));
this.actions.put(9, new ListerLivreurAction(helper));
this.actions.put(10, new AfficherCompteStatAction(helper));
this.actions.put(11, new VirementClientAction(helper));
this.ihmHelper = helper;
}
public void start() {
boolean result = false;
do {
affichageM();
result = choisir();
} while (!result);
}
public void affichageM() {
System.out.println("***** Pizzeria Administration *****");
//// maven afficher la date du jour avec la librairie du td
Calendar now = Calendar.getInstance();
DateFormatUtils.format(now, "yyyy.MM.dd G 'at' HH:mm:ss z");
System.out.println(DateFormatUtils.format(now, "dd/MM-HH:mm"));
for (Integer numero : actions.keySet()) {
Action ActionEnCours = actions.get(numero);
String libelleAction = ActionEnCours.getLibelle();
System.out.println(numero + " " + libelleAction);
}
System.out.println(CHOIX_SORTIR + ". Quitter" + "\n");
}
private void SimpleDateFormat(Calendar now) {
// TODO Auto-generated method stub
}
public boolean choisir() {
System.out.println("Veuillez choisir une option");
int choix = 0;
try {
// Instructions susceptibles de provoquer des erreurs;
choix = ihmHelper.saisirEntier();
if (!actions.containsKey(choix)) {
if (choix != CHOIX_SORTIR) {
System.out.println("Erreur de saisie, veuillez recommencer!" + "\n");
}
} else {
Action LaBonneAction = actions.get(choix);
LaBonneAction.execute();
}
} catch (SaisieEntierException e) {
System.out.println(e.getMessage());
}
return choix == CHOIX_SORTIR;
}
}
|
test git
|
pizzeria-console-objet/src/main/java/fr/pizzeria/ihm/Menu.java
|
test git
|
<ide><path>izzeria-console-objet/src/main/java/fr/pizzeria/ihm/Menu.java
<ide>
<ide> public void affichageM() {
<ide>
<del> System.out.println("***** Pizzeria Administration *****");
<add> System.out.println("***** Super Pizzeria Administration *****");
<ide>
<ide> //// maven afficher la date du jour avec la librairie du td
<ide> Calendar now = Calendar.getInstance();
|
|
Java
|
mit
|
114cf46f234fb92c1e78602a5242d91260f47197
| 0 |
elsennov/android-ripple-background
|
package com.skyfishjy.library;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.RelativeLayout;
import java.util.ArrayList;
/**
* Created by fyu on 11/3/14.
*/
public class RippleBackground extends RelativeLayout{
private static final int DEFAULT_RIPPLE_COUNT=6;
private static final int DEFAULT_DURATION_TIME=3000;
private static final float DEFAULT_SCALE=6.0f;
private static final int DEFAULT_FILL_TYPE=0;
private int rippleColor;
private float rippleStrokeWidth;
private float rippleRadius;
private int rippleDurationTime;
private int rippleAmount;
private int rippleDelay;
private float rippleScale;
private int rippleType;
private Paint paint;
private boolean animationRunning=false;
private AnimatorSet animatorSet;
private ArrayList<Animator> animatorList;
private LayoutParams rippleParams;
private ArrayList<RippleView> rippleViewList=new ArrayList<RippleView>();
public RippleBackground(Context context) {
super(context);
}
public RippleBackground(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public RippleBackground(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
private void init(final Context context, final AttributeSet attrs) {
if (isInEditMode())
return;
if (null == attrs) {
throw new IllegalArgumentException("Attributes should be provided to this view,");
}
final TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RippleBackground);
rippleColor=typedArray.getColor(R.styleable.RippleBackground_rb_color, getResources().getColor(R.color.rippelColor));
rippleStrokeWidth=typedArray.getDimension(R.styleable.RippleBackground_rb_strokeWidth, getResources().getDimension(R.dimen.rippleStrokeWidth));
rippleRadius=typedArray.getDimension(R.styleable.RippleBackground_rb_radius,getResources().getDimension(R.dimen.rippleRadius));
rippleDurationTime=typedArray.getInt(R.styleable.RippleBackground_rb_duration,DEFAULT_DURATION_TIME);
rippleAmount=typedArray.getInt(R.styleable.RippleBackground_rb_rippleAmount,DEFAULT_RIPPLE_COUNT);
rippleScale=typedArray.getFloat(R.styleable.RippleBackground_rb_scale,DEFAULT_SCALE);
rippleType=typedArray.getInt(R.styleable.RippleBackground_rb_type,DEFAULT_FILL_TYPE);
typedArray.recycle();
rippleDelay=rippleDurationTime/rippleAmount;
initPaint();
rippleParams=new LayoutParams((int)(2*(rippleRadius+rippleStrokeWidth)),(int)(2*(rippleRadius+rippleStrokeWidth)));
rippleParams.addRule(CENTER_IN_PARENT, TRUE);
animatorSet = new AnimatorSet();
animatorSet.setInterpolator(new AccelerateDecelerateInterpolator());
animatorList=new ArrayList<Animator>();
for(int i=0;i<rippleAmount;i++){
RippleView rippleView=new RippleView(getContext());
addView(rippleView,rippleParams);
rippleViewList.add(rippleView);
final ObjectAnimator scaleXAnimator = ObjectAnimator.ofFloat(rippleView, "ScaleX", 1.0f, rippleScale);
scaleXAnimator.setRepeatCount(ObjectAnimator.INFINITE);
scaleXAnimator.setRepeatMode(ObjectAnimator.RESTART);
scaleXAnimator.setStartDelay(i * rippleDelay);
scaleXAnimator.setDuration(rippleDurationTime);
animatorList.add(scaleXAnimator);
final ObjectAnimator scaleYAnimator = ObjectAnimator.ofFloat(rippleView, "ScaleY", 1.0f, rippleScale);
scaleYAnimator.setRepeatCount(ObjectAnimator.INFINITE);
scaleYAnimator.setRepeatMode(ObjectAnimator.RESTART);
scaleYAnimator.setStartDelay(i * rippleDelay);
scaleYAnimator.setDuration(rippleDurationTime);
animatorList.add(scaleYAnimator);
final ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(rippleView, "Alpha", 1.0f, 0f);
alphaAnimator.setRepeatCount(ObjectAnimator.INFINITE);
alphaAnimator.setRepeatMode(ObjectAnimator.RESTART);
alphaAnimator.setStartDelay(i * rippleDelay);
alphaAnimator.setDuration(rippleDurationTime);
animatorList.add(alphaAnimator);
}
animatorSet.playTogether(animatorList);
}
private class RippleView extends View{
public RippleView(Context context) {
super(context);
this.setVisibility(View.INVISIBLE);
}
@Override
protected void onDraw(Canvas canvas) {
int radius=(Math.min(getWidth(),getHeight()))/2;
canvas.drawCircle(radius,radius,radius-rippleStrokeWidth,paint);
}
}
public void startRippleAnimation(){
if(!isRippleAnimationRunning()){
for(RippleView rippleView:rippleViewList){
rippleView.setVisibility(VISIBLE);
}
animatorSet.start();
animationRunning=true;
}
}
public void stopRippleAnimation(){
if(isRippleAnimationRunning()){
animatorSet.end();
animationRunning=false;
}
}
public boolean isRippleAnimationRunning(){
return animationRunning;
}
/**
* Change the ripple color programmatically
*
* @param rippleColor This is the ripple color that must be retrieved from getResources().getColor(R.color.blabla). Not the resource id of the color.
*/
public void setRippleColor(int rippleColor) {
this.rippleColor = rippleColor;
initPaint();
for (RippleView rippleView : rippleViewList) {
rippleView.invalidate();
}
}
private void initPaint() {
paint = new Paint();
paint.setAntiAlias(true);
if(rippleType==DEFAULT_FILL_TYPE){
rippleStrokeWidth=0;
paint.setStyle(Paint.Style.FILL);
}else
paint.setStyle(Paint.Style.STROKE);
paint.setColor(rippleColor);
}
}
|
library/src/main/java/com/skyfishjy/library/RippleBackground.java
|
package com.skyfishjy.library;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.RelativeLayout;
import java.util.ArrayList;
/**
* Created by fyu on 11/3/14.
*/
public class RippleBackground extends RelativeLayout{
private static final int DEFAULT_RIPPLE_COUNT=6;
private static final int DEFAULT_DURATION_TIME=3000;
private static final float DEFAULT_SCALE=6.0f;
private static final int DEFAULT_FILL_TYPE=0;
private int rippleColor;
private float rippleStrokeWidth;
private float rippleRadius;
private int rippleDurationTime;
private int rippleAmount;
private int rippleDelay;
private float rippleScale;
private int rippleType;
private Paint paint;
private boolean animationRunning=false;
private AnimatorSet animatorSet;
private ArrayList<Animator> animatorList;
private LayoutParams rippleParams;
private ArrayList<RippleView> rippleViewList=new ArrayList<RippleView>();
public RippleBackground(Context context) {
super(context);
}
public RippleBackground(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public RippleBackground(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
private void init(final Context context, final AttributeSet attrs) {
if (isInEditMode())
return;
if (null == attrs) {
throw new IllegalArgumentException("Attributes should be provided to this view,");
}
final TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RippleBackground);
rippleColor=typedArray.getColor(R.styleable.RippleBackground_rb_color, getResources().getColor(R.color.rippelColor));
rippleStrokeWidth=typedArray.getDimension(R.styleable.RippleBackground_rb_strokeWidth, getResources().getDimension(R.dimen.rippleStrokeWidth));
rippleRadius=typedArray.getDimension(R.styleable.RippleBackground_rb_radius,getResources().getDimension(R.dimen.rippleRadius));
rippleDurationTime=typedArray.getInt(R.styleable.RippleBackground_rb_duration,DEFAULT_DURATION_TIME);
rippleAmount=typedArray.getInt(R.styleable.RippleBackground_rb_rippleAmount,DEFAULT_RIPPLE_COUNT);
rippleScale=typedArray.getFloat(R.styleable.RippleBackground_rb_scale,DEFAULT_SCALE);
rippleType=typedArray.getInt(R.styleable.RippleBackground_rb_type,DEFAULT_FILL_TYPE);
typedArray.recycle();
rippleDelay=rippleDurationTime/rippleAmount;
paint = new Paint();
paint.setAntiAlias(true);
if(rippleType==DEFAULT_FILL_TYPE){
rippleStrokeWidth=0;
paint.setStyle(Paint.Style.FILL);
}else
paint.setStyle(Paint.Style.STROKE);
paint.setColor(rippleColor);
rippleParams=new LayoutParams((int)(2*(rippleRadius+rippleStrokeWidth)),(int)(2*(rippleRadius+rippleStrokeWidth)));
rippleParams.addRule(CENTER_IN_PARENT, TRUE);
animatorSet = new AnimatorSet();
animatorSet.setInterpolator(new AccelerateDecelerateInterpolator());
animatorList=new ArrayList<Animator>();
for(int i=0;i<rippleAmount;i++){
RippleView rippleView=new RippleView(getContext());
addView(rippleView,rippleParams);
rippleViewList.add(rippleView);
final ObjectAnimator scaleXAnimator = ObjectAnimator.ofFloat(rippleView, "ScaleX", 1.0f, rippleScale);
scaleXAnimator.setRepeatCount(ObjectAnimator.INFINITE);
scaleXAnimator.setRepeatMode(ObjectAnimator.RESTART);
scaleXAnimator.setStartDelay(i * rippleDelay);
scaleXAnimator.setDuration(rippleDurationTime);
animatorList.add(scaleXAnimator);
final ObjectAnimator scaleYAnimator = ObjectAnimator.ofFloat(rippleView, "ScaleY", 1.0f, rippleScale);
scaleYAnimator.setRepeatCount(ObjectAnimator.INFINITE);
scaleYAnimator.setRepeatMode(ObjectAnimator.RESTART);
scaleYAnimator.setStartDelay(i * rippleDelay);
scaleYAnimator.setDuration(rippleDurationTime);
animatorList.add(scaleYAnimator);
final ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(rippleView, "Alpha", 1.0f, 0f);
alphaAnimator.setRepeatCount(ObjectAnimator.INFINITE);
alphaAnimator.setRepeatMode(ObjectAnimator.RESTART);
alphaAnimator.setStartDelay(i * rippleDelay);
alphaAnimator.setDuration(rippleDurationTime);
animatorList.add(alphaAnimator);
}
animatorSet.playTogether(animatorList);
}
private class RippleView extends View{
public RippleView(Context context) {
super(context);
this.setVisibility(View.INVISIBLE);
}
@Override
protected void onDraw(Canvas canvas) {
int radius=(Math.min(getWidth(),getHeight()))/2;
canvas.drawCircle(radius,radius,radius-rippleStrokeWidth,paint);
}
}
public void startRippleAnimation(){
if(!isRippleAnimationRunning()){
for(RippleView rippleView:rippleViewList){
rippleView.setVisibility(VISIBLE);
}
animatorSet.start();
animationRunning=true;
}
}
public void stopRippleAnimation(){
if(isRippleAnimationRunning()){
animatorSet.end();
animationRunning=false;
}
}
public boolean isRippleAnimationRunning(){
return animationRunning;
}
}
|
Add method to set the ripple color programmatically
|
library/src/main/java/com/skyfishjy/library/RippleBackground.java
|
Add method to set the ripple color programmatically
|
<ide><path>ibrary/src/main/java/com/skyfishjy/library/RippleBackground.java
<ide>
<ide> rippleDelay=rippleDurationTime/rippleAmount;
<ide>
<del> paint = new Paint();
<del> paint.setAntiAlias(true);
<del> if(rippleType==DEFAULT_FILL_TYPE){
<del> rippleStrokeWidth=0;
<del> paint.setStyle(Paint.Style.FILL);
<del> }else
<del> paint.setStyle(Paint.Style.STROKE);
<del> paint.setColor(rippleColor);
<add> initPaint();
<ide>
<ide> rippleParams=new LayoutParams((int)(2*(rippleRadius+rippleStrokeWidth)),(int)(2*(rippleRadius+rippleStrokeWidth)));
<ide> rippleParams.addRule(CENTER_IN_PARENT, TRUE);
<ide> public boolean isRippleAnimationRunning(){
<ide> return animationRunning;
<ide> }
<add>
<add> /**
<add> * Change the ripple color programmatically
<add> *
<add> * @param rippleColor This is the ripple color that must be retrieved from getResources().getColor(R.color.blabla). Not the resource id of the color.
<add> */
<add> public void setRippleColor(int rippleColor) {
<add> this.rippleColor = rippleColor;
<add> initPaint();
<add> for (RippleView rippleView : rippleViewList) {
<add> rippleView.invalidate();
<add> }
<add> }
<add>
<add> private void initPaint() {
<add> paint = new Paint();
<add> paint.setAntiAlias(true);
<add> if(rippleType==DEFAULT_FILL_TYPE){
<add> rippleStrokeWidth=0;
<add> paint.setStyle(Paint.Style.FILL);
<add> }else
<add> paint.setStyle(Paint.Style.STROKE);
<add> paint.setColor(rippleColor);
<add> }
<add>
<ide> }
|
|
Java
|
mit
|
e6d6b1af67095bd16c92a9f3dd9fde04d94083d4
| 0 |
strykeforce/thirdcoast,strykeforce/thirdcoast,strykeforce/thirdcoast
|
package org.strykeforce.thirdcoast.telemetry.item;
import com.ctre.phoenix.ParamEnum;
import com.ctre.phoenix.motorcontrol.ControlMode;
import com.ctre.phoenix.motorcontrol.Faults;
import com.ctre.phoenix.motorcontrol.SensorCollection;
import com.ctre.phoenix.motorcontrol.StickyFaults;
import com.ctre.phoenix.motorcontrol.can.TalonSRX;
import com.ctre.phoenix.motorcontrol.can.WPI_TalonSRX;
import com.squareup.moshi.JsonWriter;
import java.io.IOException;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Set;
import java.util.function.DoubleSupplier;
import org.strykeforce.thirdcoast.telemetry.grapher.Measure;
/** Represents a {@link TalonSRX} telemetry-enable Item. */
public class TalonItem extends AbstractItem {
public static final String TYPE = "talon";
public static final Set<Measure> MEASURES =
Collections.unmodifiableSet(
EnumSet.of(
Measure.SETPOINT,
Measure.OUTPUT_CURRENT,
Measure.OUTPUT_VOLTAGE,
Measure.OUTPUT_PERCENT,
Measure.SELECTED_SENSOR_POSITION,
Measure.SELECTED_SENSOR_VELOCITY,
Measure.ACTIVE_TRAJECTORY_POSITION,
Measure.ACTIVE_TRAJECTORY_VELOCITY,
Measure.CLOSED_LOOP_ERROR,
Measure.BUS_VOLTAGE,
Measure.ERROR_DERIVATIVE,
Measure.INTEGRAL_ACCUMULATOR,
Measure.ANALOG_IN,
Measure.ANALOG_RAW,
Measure.ANALOG_POSITION,
Measure.ANALOG_VELOCITY,
Measure.QUAD_POSITION,
Measure.QUAD_VELOCITY,
Measure.QUAD_A_PIN,
Measure.QUAD_B_PIN,
Measure.QUAD_IDX_PIN,
Measure.PULSE_WIDTH_POSITION,
Measure.PULSE_WIDTH_VELOCITY,
Measure.PULSE_WIDTH_RISE_TO_FALL,
Measure.PULSE_WIDTH_RISE_TO_RISE,
Measure.FORWARD_LIMIT_SWITCH_CLOSED,
Measure.REVERSE_LIMIT_SWITCH_CLOSED));
// TODO: getMotionProfileStatus
private static final String NA = "not available in API";
private static final double TRUE = 1;
private static final double FALSE = 0;
private final TalonSRX talon;
private final SensorCollection sensorCollection;
public TalonItem(final TalonSRX talon) {
super(TYPE, ((WPI_TalonSRX) talon).getDescription(), MEASURES);
this.talon = talon;
sensorCollection = talon.getSensorCollection();
}
public TalonSRX getTalon() {
return talon;
}
@Override
public int deviceId() {
return talon.getDeviceID();
}
@Override
public DoubleSupplier measurementFor(final Measure measure) {
if (!MEASURES.contains(measure)) {
throw new IllegalArgumentException("invalid measure: " + measure.name());
}
switch (measure) {
// TODO: should be coming in CTRE update
// case SETPOINT:
// return talon::getSetpoint;
case OUTPUT_CURRENT:
return talon::getOutputCurrent;
case OUTPUT_VOLTAGE:
return talon::getMotorOutputVoltage;
case OUTPUT_PERCENT:
return talon::getMotorOutputPercent;
case SELECTED_SENSOR_POSITION:
return () -> talon.getSelectedSensorPosition(0);
case SELECTED_SENSOR_VELOCITY:
return () -> talon.getSelectedSensorVelocity(0);
case ACTIVE_TRAJECTORY_POSITION:
return talon::getActiveTrajectoryPosition;
case ACTIVE_TRAJECTORY_VELOCITY:
return talon::getActiveTrajectoryVelocity;
case CLOSED_LOOP_ERROR:
return () -> talon.getClosedLoopError(0);
case BUS_VOLTAGE:
return talon::getBusVoltage;
case ERROR_DERIVATIVE:
return () -> talon.getErrorDerivative(0);
case INTEGRAL_ACCUMULATOR:
return () -> talon.getIntegralAccumulator(0);
case ANALOG_IN:
return sensorCollection::getAnalogIn;
case ANALOG_RAW:
return sensorCollection::getAnalogInRaw;
// case ANALOG_POSITION:
// return () -> 0;
case ANALOG_VELOCITY:
return sensorCollection::getAnalogInVel;
case QUAD_POSITION:
return sensorCollection::getQuadraturePosition;
case QUAD_VELOCITY:
return sensorCollection::getQuadratureVelocity;
case QUAD_A_PIN:
return () -> sensorCollection.getPinStateQuadA() ? TRUE : FALSE;
case QUAD_B_PIN:
return () -> sensorCollection.getPinStateQuadB() ? TRUE : FALSE;
case QUAD_IDX_PIN:
return () -> sensorCollection.getPinStateQuadIdx() ? TRUE : FALSE;
case PULSE_WIDTH_POSITION:
return sensorCollection::getPulseWidthPosition;
case PULSE_WIDTH_VELOCITY:
return sensorCollection::getPulseWidthVelocity;
case PULSE_WIDTH_RISE_TO_FALL:
return sensorCollection::getPulseWidthRiseToFallUs;
case PULSE_WIDTH_RISE_TO_RISE:
return sensorCollection::getPulseWidthRiseToRiseUs;
case FORWARD_LIMIT_SWITCH_CLOSED:
return () -> sensorCollection.isFwdLimitSwitchClosed() ? TRUE : FALSE;
case REVERSE_LIMIT_SWITCH_CLOSED:
return () -> sensorCollection.isRevLimitSwitchClosed() ? TRUE : FALSE;
default:
throw new AssertionError(measure);
}
}
@Override
public String toString() {
return "TalonItem{" + "talon=" + talon + "} " + super.toString();
}
@Override
public void toJson(JsonWriter writer) throws IOException { // FIXME: finish 2018 conversion
writer.beginObject();
writer.name("type").value(TYPE);
writer.name("baseId").value(talon.getBaseID());
writer.name("deviceId").value(talon.getDeviceID());
writer.name("description").value(((WPI_TalonSRX) talon).getDescription());
writer.name("firmwareVersion").value(talon.getFirmwareVersion());
writer.name("controlMode").value(talon.getControlMode().toString());
//writer.name("brakeEnabledDuringNeutral").value(talon.getBrakeEnableDuringNeutral());
writer
.name("onBootBrakeMode")
.value(talon.configGetParameter(ParamEnum.eOnBoot_BrakeMode, 0, 0));
writer.name("busVoltage").value(talon.getBusVoltage());
writer
.name("feedbackSensorType")
.value(talon.configGetParameter(ParamEnum.eFeedbackSensorType, 0, 0));
writer
.name("peakCurrentLimitMs")
.value(talon.configGetParameter(ParamEnum.ePeakCurrentLimitMs, 0, 0));
writer
.name("peakCurrentLimitAmps")
.value(talon.configGetParameter(ParamEnum.ePeakCurrentLimitAmps, 0, 0));
//writer.name("encoderCodesPerRef").value(NA);
writer.name("inverted").value(talon.getInverted());
//writer.name("numberOfQuadIdxRises").value(talon.getNumberOfQuadIdxRises());
writer
.name("eQuadIdxPolarity")
.value(talon.configGetParameter(ParamEnum.eQuadIdxPolarity, 0, 0));
writer.name("outputVoltage").value(talon.getMotorOutputVoltage());
writer.name("outputCurrent").value(talon.getOutputCurrent());
writer.name("analogInput");
writer.beginObject();
writer.name("position").value(talon.getSensorCollection().getAnalogIn());
writer.name("velocity").value(talon.getSensorCollection().getAnalogInVel());
writer.name("raw").value(talon.getSensorCollection().getAnalogInRaw());
writer.endObject();
writer.name("encoder");
writer.beginObject();
writer.name("position").value(talon.getSelectedSensorPosition(0));
writer.name("velocity").value(talon.getSelectedSensorVelocity(0));
writer.endObject();
writer.name("quadrature");
writer.beginObject();
writer.name("position").value(talon.getSensorCollection().getQuadraturePosition());
writer.name("velocity").value(talon.getSensorCollection().getQuadratureVelocity());
writer.endObject();
writer.name("pulseWidth");
writer.beginObject();
writer.name("position").value(talon.getSensorCollection().getPulseWidthPosition());
writer.name("velocity").value(talon.getSensorCollection().getPulseWidthVelocity());
writer.name("riseToFallUs").value(talon.getSensorCollection().getPulseWidthRiseToFallUs());
writer.name("riseToRiseUs").value(talon.getSensorCollection().getPulseWidthRiseToRiseUs());
writer.endObject();
writer.name("closedLoop");
writer.beginObject();
writer.name("enabled").value(true);
writer.name("p").value(talon.configGetParameter(ParamEnum.eProfileParamSlot_P, 0, 0));
writer.name("i").value(talon.configGetParameter(ParamEnum.eProfileParamSlot_I, 0, 0));
writer.name("d").value(talon.configGetParameter(ParamEnum.eProfileParamSlot_D, 0, 0));
writer.name("f").value(talon.configGetParameter(ParamEnum.eProfileParamSlot_F, 0, 0));
writer
.name("iAccum")
.value(talon.configGetParameter(ParamEnum.eProfileParamSlot_MaxIAccum, 0, 0));
writer.name("iZone").value(talon.configGetParameter(ParamEnum.eProfileParamSlot_IZone, 0, 0));
writer.name("errorInt").value(talon.getClosedLoopError(0));
writer.name("errorDouble").value(talon.getErrorDerivative(0));
writer.name("rampRate").value(talon.configGetParameter(ParamEnum.eOpenloopRamp, 0, 0));
writer.name("nominalVoltage").value(talon.configGetParameter(ParamEnum.eClosedloopRamp, 0, 0));
writer.endObject();
writer.name("motionMagic");
writer.beginObject();
if (talon.getControlMode() == ControlMode.MotionMagic) {
writer.name("enabled").value(true);
writer.name("acceleration").value(talon.configGetParameter(ParamEnum.eMotMag_Accel, 0, 0));
//writer.name("actTrajPosition").value(talon.getMotionMagicActTrajPosition());
//writer.name("actTrajVelocity").value(talon.getMotionMagicActTrajVelocity());
writer
.name("cruiseVelocity")
.value(talon.configGetParameter(ParamEnum.eMotMag_VelCruise, 0, 0));
} else {
writer.name("enabled").value(false);
}
writer.endObject();
writer.name("motionProfile");
writer.beginObject();
if (talon.getControlMode() == ControlMode.MotionProfile) {
writer.name("enabled").value(true);
writer.name("topLevelBufferCount").value(talon.getMotionProfileTopLevelBufferCount());
} else {
writer.name("enabled").value(false);
}
writer.endObject();
writer.name("forwardSoftLimit");
writer.beginObject();
writer.name("enabled").value(talon.configGetParameter(ParamEnum.eForwardSoftLimitEnable, 0, 0));
writer
.name("limit")
.value(talon.configGetParameter(ParamEnum.eForwardSoftLimitThreshold, 0, 0));
writer.endObject();
writer.name("reverseSoftLimit");
writer.beginObject();
writer.name("enabled").value(talon.configGetParameter(ParamEnum.eReverseSoftLimitEnable, 0, 0));
writer
.name("limit")
.value(talon.configGetParameter(ParamEnum.eReverseSoftLimitThreshold, 0, 0));
writer.endObject();
writer.name("lastError").value(talon.getLastError().toString());
writer.name("faults");
writer.beginObject();
StickyFaults stickyfaults = new StickyFaults();
Faults faults = new Faults();
talon.getStickyFaults(stickyfaults);
talon.getFaults(faults);
writer.name("lim").value(faults.ForwardLimitSwitch);
writer.name("stickyLim").value(stickyfaults.ForwardLimitSwitch);
writer.name("softLim").value(faults.ForwardSoftLimit);
writer.name("stickySoftLim").value(stickyfaults.ForwardSoftLimit);
writer.name("hardwareFailure").value(faults.HardwareFailure);
writer.name("overTemp").value(faults.SensorOverflow);
writer.name("stickyOverTemp").value(stickyfaults.SensorOverflow);
writer.name("revLim").value(faults.ReverseLimitSwitch);
writer.name("stickyRevLim").value(stickyfaults.ReverseLimitSwitch);
writer.name("revSoftLim").value(faults.ReverseSoftLimit);
writer.name("stickyRevSoftLim").value(stickyfaults.ReverseSoftLimit);
writer.name("underVoltage").value(faults.UnderVoltage);
writer.name("stickyUnderVoltage").value(stickyfaults.UnderVoltage);
writer.endObject();
writer.endObject();
}
/**
* Indicates if some other {@code TalonItem} has the same underlying Talon as this one.
*
* @param obj the reference object with which to compare.
* @return true if this TalonSRX has the same device ID, false otherwise.
*/
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof TalonItem)) {
return false;
}
TalonItem item = (TalonItem) obj;
return item.talon.getDeviceID() == talon.getDeviceID();
}
/**
* Returns a hashcode value for this TalonItem.
*
* @return a hashcode value for this TalonItem.
*/
@Override
public int hashCode() {
return talon.getDeviceID();
}
}
|
core/src/main/java/org/strykeforce/thirdcoast/telemetry/item/TalonItem.java
|
package org.strykeforce.thirdcoast.telemetry.item;
import com.ctre.phoenix.ParamEnum;
import com.ctre.phoenix.motorcontrol.ControlMode;
import com.ctre.phoenix.motorcontrol.Faults;
import com.ctre.phoenix.motorcontrol.SensorCollection;
import com.ctre.phoenix.motorcontrol.StickyFaults;
import com.ctre.phoenix.motorcontrol.can.TalonSRX;
import com.ctre.phoenix.motorcontrol.can.WPI_TalonSRX;
import com.squareup.moshi.JsonWriter;
import java.io.IOException;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Set;
import java.util.function.DoubleSupplier;
import org.strykeforce.thirdcoast.telemetry.grapher.Measure;
/** Represents a {@link TalonSRX} telemetry-enable Item. */
public class TalonItem extends AbstractItem {
public static final String TYPE = "talon";
public static final Set<Measure> MEASURES =
Collections.unmodifiableSet(
EnumSet.of(
Measure.SETPOINT,
Measure.OUTPUT_CURRENT,
Measure.OUTPUT_VOLTAGE,
Measure.OUTPUT_PERCENT,
Measure.SELECTED_SENSOR_POSITION,
Measure.SELECTED_SENSOR_VELOCITY,
Measure.ACTIVE_TRAJECTORY_POSITION,
Measure.ACTIVE_TRAJECTORY_VELOCITY,
Measure.CLOSED_LOOP_ERROR,
Measure.BUS_VOLTAGE,
Measure.ERROR_DERIVATIVE,
Measure.INTEGRAL_ACCUMULATOR,
Measure.ANALOG_IN,
Measure.ANALOG_RAW,
Measure.ANALOG_POSITION,
Measure.ANALOG_VELOCITY,
Measure.QUAD_POSITION,
Measure.QUAD_VELOCITY,
Measure.QUAD_A_PIN,
Measure.QUAD_B_PIN,
Measure.QUAD_IDX_PIN,
Measure.PULSE_WIDTH_POSITION,
Measure.PULSE_WIDTH_VELOCITY,
Measure.PULSE_WIDTH_RISE_TO_FALL,
Measure.PULSE_WIDTH_RISE_TO_RISE,
Measure.FORWARD_LIMIT_SWITCH_CLOSED,
Measure.REVERSE_LIMIT_SWITCH_CLOSED));
// TODO: getMotionProfileStatus
private static final String NA = "not available in API";
private static final double TRUE = 1;
private static final double FALSE = 0;
private final TalonSRX talon;
private final SensorCollection sensorCollection;
public TalonItem(final TalonSRX talon) {
super(TYPE, ((WPI_TalonSRX) talon).getDescription(), MEASURES);
this.talon = talon;
sensorCollection = talon.getSensorCollection();
}
public TalonSRX getTalon() {
return talon;
}
@Override
public int deviceId() {
return talon.getDeviceID();
}
@Override
public DoubleSupplier measurementFor(final Measure measure) {
if (!MEASURES.contains(measure)) {
throw new IllegalArgumentException("invalid measure: " + measure.name());
}
switch (measure) {
// TODO: should be coming in CTRE update
// case SETPOINT:
// return talon::getSetpoint;
case OUTPUT_CURRENT:
return talon::getOutputCurrent;
case OUTPUT_VOLTAGE:
return talon::getMotorOutputVoltage;
case OUTPUT_PERCENT:
return talon::getMotorOutputPercent;
case SELECTED_SENSOR_POSITION:
return () -> talon.getSelectedSensorPosition(0);
case SELECTED_SENSOR_VELOCITY:
return () -> talon.getSelectedSensorVelocity(0);
case ACTIVE_TRAJECTORY_POSITION:
return talon::getActiveTrajectoryPosition;
case ACTIVE_TRAJECTORY_VELOCITY:
return talon::getActiveTrajectoryVelocity;
case CLOSED_LOOP_ERROR:
return () -> talon.getClosedLoopError(0);
case BUS_VOLTAGE:
return talon::getBusVoltage;
case ERROR_DERIVATIVE:
return () -> talon.getErrorDerivative(0);
case INTEGRAL_ACCUMULATOR:
return () -> talon.getIntegralAccumulator(0);
case ANALOG_IN:
return sensorCollection::getAnalogIn;
case ANALOG_RAW:
return sensorCollection::getAnalogInRaw;
// case ANALOG_POSITION:
// return () -> 0;
case ANALOG_VELOCITY:
return sensorCollection::getAnalogInVel;
case QUAD_POSITION:
return sensorCollection::getQuadraturePosition;
case QUAD_VELOCITY:
return sensorCollection::getQuadratureVelocity;
case QUAD_A_PIN:
return () -> sensorCollection.getPinStateQuadA() ? TRUE : FALSE;
case QUAD_B_PIN:
return () -> sensorCollection.getPinStateQuadB() ? TRUE : FALSE;
case QUAD_IDX_PIN:
return () -> sensorCollection.getPinStateQuadIdx() ? TRUE : FALSE;
case PULSE_WIDTH_POSITION:
return sensorCollection::getPulseWidthPosition;
case PULSE_WIDTH_VELOCITY:
return sensorCollection::getPulseWidthVelocity;
case PULSE_WIDTH_RISE_TO_FALL:
return sensorCollection::getPulseWidthRiseToFallUs;
case PULSE_WIDTH_RISE_TO_RISE:
return sensorCollection::getPulseWidthRiseToRiseUs;
case FORWARD_LIMIT_SWITCH_CLOSED:
return () -> sensorCollection.isFwdLimitSwitchClosed() ? TRUE : FALSE;
case REVERSE_LIMIT_SWITCH_CLOSED:
return () -> sensorCollection.isRevLimitSwitchClosed() ? TRUE : FALSE;
default:
throw new AssertionError(measure);
}
}
@Override
public String toString() {
return "TalonItem{" + "talon=" + talon + "} " + super.toString();
}
@Override
public void toJson(JsonWriter writer) throws IOException { // FIXME: finish 2018 conversion
writer.beginObject();
writer.name("type").value(TYPE);
writer.name("baseId").value(talon.getBaseID());
writer.name("deviceId").value(talon.getDeviceID());
writer.name("description").value(((WPI_TalonSRX) talon).getDescription());
writer.name("firmwareVersion").value(talon.getFirmwareVersion());
writer.name("controlMode").value(talon.getControlMode().toString());
//writer.name("brakeEnabledDuringNeutral").value(talon.getBrakeEnableDuringNeutral());
writer
.name("onBootBrakeMode")
.value(talon.configGetParameter(ParamEnum.eOnBoot_BrakeMode, 0, 0));
writer.name("busVoltage").value(talon.getBusVoltage());
writer.name("feedbackSensorType").value(talon.configGetParameter(ParamEnum.eFeedbackSensorType, 0, 0));
writer.name("peakCurrentLimitMs").value(talon.configGetParameter(ParamEnum.ePeakCurrentLimitMs, 0, 0));
writer.name("peakCurrentLimitAmps").value(talon.configGetParameter(ParamEnum.ePeakCurrentLimitAmps, 0, 0));
//writer.name("encoderCodesPerRef").value(NA);
writer.name("inverted").value(talon.getInverted());
//writer.name("numberOfQuadIdxRises").value(talon.getNumberOfQuadIdxRises());
writer
.name("eQuadIdxPolarity")
.value(talon.configGetParameter(ParamEnum.eQuadIdxPolarity, 0, 0));
writer.name("outputVoltage").value(talon.getMotorOutputVoltage());
writer.name("outputCurrent").value(talon.getOutputCurrent());
writer.name("analogInput");
writer.beginObject();
writer.name("position").value(talon.getSensorCollection().getAnalogIn());
writer.name("velocity").value(talon.getSensorCollection().getAnalogInVel());
writer.name("raw").value(talon.getSensorCollection().getAnalogInRaw());
writer.endObject();
writer.name("encoder");
writer.beginObject();
writer.name("position").value(talon.getSelectedSensorPosition(0));
writer.name("velocity").value(talon.getSelectedSensorVelocity(0));
writer.endObject();
writer.name("quadrature");
writer.beginObject();
writer.name("position").value(talon.getSensorCollection().getQuadraturePosition());
writer.name("velocity").value(talon.getSensorCollection().getQuadratureVelocity());
writer.endObject();
writer.name("pulseWidth");
writer.beginObject();
writer.name("position").value(talon.getSensorCollection().getPulseWidthPosition());
writer.name("velocity").value(talon.getSensorCollection().getPulseWidthVelocity());
writer.name("riseToFallUs").value(talon.getSensorCollection().getPulseWidthRiseToFallUs());
writer.name("riseToRiseUs").value(talon.getSensorCollection().getPulseWidthRiseToRiseUs());
writer.endObject();
writer.name("closedLoop");
writer.beginObject();
writer.name("enabled").value(true);
writer.name("p").value(talon.configGetParameter(ParamEnum.eProfileParamSlot_P, 0, 0));
writer.name("i").value(talon.configGetParameter(ParamEnum.eProfileParamSlot_I, 0, 0));
writer.name("d").value(talon.configGetParameter(ParamEnum.eProfileParamSlot_D, 0, 0));
writer.name("f").value(talon.configGetParameter(ParamEnum.eProfileParamSlot_F, 0, 0));
writer
.name("iAccum")
.value(talon.configGetParameter(ParamEnum.eProfileParamSlot_MaxIAccum, 0, 0));
writer.name("iZone").value(talon.configGetParameter(ParamEnum.eProfileParamSlot_IZone, 0, 0));
writer.name("errorInt").value(talon.getClosedLoopError(0));
writer.name("errorDouble").value(talon.getErrorDerivative(0));
writer.name("rampRate").value(talon.configGetParameter(ParamEnum.eOpenloopRamp, 0, 0));
writer.name("nominalVoltage").value(talon.configGetParameter(ParamEnum.eClosedloopRamp, 0, 0));
writer.endObject();
writer.name("motionMagic");
writer.beginObject();
if (talon.getControlMode() == ControlMode.MotionMagic) {
writer.name("enabled").value(true);
writer.name("acceleration").value(talon.configGetParameter(ParamEnum.eMotMag_Accel, 0, 0));
//writer.name("actTrajPosition").value(talon.getMotionMagicActTrajPosition());
//writer.name("actTrajVelocity").value(talon.getMotionMagicActTrajVelocity());
writer
.name("cruiseVelocity")
.value(talon.configGetParameter(ParamEnum.eMotMag_VelCruise, 0, 0));
} else {
writer.name("enabled").value(false);
}
writer.endObject();
writer.name("motionProfile");
writer.beginObject();
if (talon.getControlMode() == ControlMode.MotionProfile) {
writer.name("enabled").value(true);
writer.name("topLevelBufferCount").value(talon.getMotionProfileTopLevelBufferCount());
} else {
writer.name("enabled").value(false);
}
writer.endObject();
writer.name("forwardSoftLimit");
writer.beginObject();
writer.name("enabled").value(talon.configGetParameter(ParamEnum.eForwardSoftLimitEnable, 0, 0));
writer
.name("limit")
.value(talon.configGetParameter(ParamEnum.eForwardSoftLimitThreshold, 0, 0));
writer.endObject();
writer.name("reverseSoftLimit");
writer.beginObject();
writer.name("enabled").value(talon.configGetParameter(ParamEnum.eReverseSoftLimitEnable, 0, 0));
writer
.name("limit")
.value(talon.configGetParameter(ParamEnum.eReverseSoftLimitThreshold, 0, 0));
writer.endObject();
writer.name("lastError").value(talon.getLastError().toString());
writer.name("faults");
writer.beginObject();
StickyFaults stickyfaults = new StickyFaults();
Faults faults = new Faults();
talon.getStickyFaults(stickyfaults);
talon.getFaults(faults);
writer.name("lim").value(faults.ForwardLimitSwitch);
writer.name("stickyLim").value(stickyfaults.ForwardLimitSwitch);
writer.name("softLim").value(faults.ForwardSoftLimit);
writer.name("stickySoftLim").value(stickyfaults.ForwardSoftLimit);
writer.name("hardwareFailure").value(faults.HardwareFailure);
writer.name("overTemp").value(faults.SensorOverflow);
writer.name("stickyOverTemp").value(stickyfaults.SensorOverflow);
writer.name("revLim").value(faults.ReverseLimitSwitch);
writer.name("stickyRevLim").value(stickyfaults.ReverseLimitSwitch);
writer.name("revSoftLim").value(faults.ReverseSoftLimit);
writer.name("stickyRevSoftLim").value(stickyfaults.ReverseSoftLimit);
writer.name("underVoltage").value(faults.UnderVoltage);
writer.name("stickyUnderVoltage").value(stickyfaults.UnderVoltage);
writer.endObject();
writer.endObject();
}
/**
* Indicates if some other {@code TalonItem} has the same underlying Talon as this one.
*
* @param obj the reference object with which to compare.
* @return true if this TalonSRX has the same device ID, false otherwise.
*/
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof TalonItem)) {
return false;
}
TalonItem item = (TalonItem) obj;
return item.talon.getDeviceID() == talon.getDeviceID();
}
/**
* Returns a hashcode value for this TalonItem.
*
* @return a hashcode value for this TalonItem.
*/
@Override
public int hashCode() {
return talon.getDeviceID();
}
}
|
Apply Spotless formatting
|
core/src/main/java/org/strykeforce/thirdcoast/telemetry/item/TalonItem.java
|
Apply Spotless formatting
|
<ide><path>ore/src/main/java/org/strykeforce/thirdcoast/telemetry/item/TalonItem.java
<ide> .name("onBootBrakeMode")
<ide> .value(talon.configGetParameter(ParamEnum.eOnBoot_BrakeMode, 0, 0));
<ide> writer.name("busVoltage").value(talon.getBusVoltage());
<del> writer.name("feedbackSensorType").value(talon.configGetParameter(ParamEnum.eFeedbackSensorType, 0, 0));
<del> writer.name("peakCurrentLimitMs").value(talon.configGetParameter(ParamEnum.ePeakCurrentLimitMs, 0, 0));
<del> writer.name("peakCurrentLimitAmps").value(talon.configGetParameter(ParamEnum.ePeakCurrentLimitAmps, 0, 0));
<add> writer
<add> .name("feedbackSensorType")
<add> .value(talon.configGetParameter(ParamEnum.eFeedbackSensorType, 0, 0));
<add> writer
<add> .name("peakCurrentLimitMs")
<add> .value(talon.configGetParameter(ParamEnum.ePeakCurrentLimitMs, 0, 0));
<add> writer
<add> .name("peakCurrentLimitAmps")
<add> .value(talon.configGetParameter(ParamEnum.ePeakCurrentLimitAmps, 0, 0));
<ide>
<ide> //writer.name("encoderCodesPerRef").value(NA);
<ide> writer.name("inverted").value(talon.getInverted());
|
|
Java
|
apache-2.0
|
42483d0de01bacbb5202e33206ffec8973b08ea1
| 0 |
statsbiblioteket/summa,statsbiblioteket/summa,statsbiblioteket/summa,statsbiblioteket/summa
|
/** 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 dk.statsbiblioteket.summa.support.summon.search;
import dk.statsbiblioteket.summa.common.configuration.Configuration;
import dk.statsbiblioteket.summa.common.lucene.index.IndexUtils;
import dk.statsbiblioteket.summa.common.unittest.ExtraAsserts;
import dk.statsbiblioteket.summa.common.util.SimplePair;
import dk.statsbiblioteket.summa.common.util.StringExtraction;
import dk.statsbiblioteket.summa.facetbrowser.api.FacetResultExternal;
import dk.statsbiblioteket.summa.facetbrowser.api.FacetResultImpl;
import dk.statsbiblioteket.summa.search.SearchNode;
import dk.statsbiblioteket.summa.search.SearchNodeFactory;
import dk.statsbiblioteket.summa.search.api.Request;
import dk.statsbiblioteket.summa.search.api.Response;
import dk.statsbiblioteket.summa.search.api.ResponseCollection;
import dk.statsbiblioteket.summa.search.api.document.DocumentKeys;
import dk.statsbiblioteket.summa.search.api.document.DocumentResponse;
import dk.statsbiblioteket.summa.search.tools.QueryRewriter;
import dk.statsbiblioteket.summa.support.api.LuceneKeys;
import dk.statsbiblioteket.summa.support.harmonise.AdjustingSearchNode;
import dk.statsbiblioteket.summa.support.harmonise.HarmoniseTestHelper;
import dk.statsbiblioteket.summa.support.harmonise.InteractionAdjuster;
import dk.statsbiblioteket.summa.support.solr.SolrSearchNode;
import dk.statsbiblioteket.util.Strings;
import dk.statsbiblioteket.util.qa.QAInfo;
import dk.statsbiblioteket.util.xml.DOM;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import javax.xml.transform.TransformerException;
import java.io.IOException;
import java.rmi.RemoteException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@QAInfo(level = QAInfo.Level.NORMAL,
state = QAInfo.State.IN_DEVELOPMENT,
author = "te")
public class SummonSearchNodeTest extends TestCase {
private static Log log = LogFactory.getLog(SummonSearchNodeTest.class);
public SummonSearchNodeTest(String name) {
super(name);
}
@Override
public void setUp() throws Exception {
super.setUp();
}
@Override
public void tearDown() throws Exception {
super.tearDown();
}
public static Test suite() {
return new TestSuite(SummonSearchNodeTest.class);
}
public void testMoreLikeThis() throws RemoteException {
SummonSearchNode summon = SummonTestHelper.createSummonSearchNode();
long standard = getHits(summon, DocumentKeys.SEARCH_QUERY, "foo");
assertTrue("A search for 'foo' should give hits", standard > 0);
long mlt = getHits(summon, DocumentKeys.SEARCH_QUERY, "foo", LuceneKeys.SEARCH_MORELIKETHIS_RECORDID, "bar");
assertEquals("A search with a MoreLikeThis ID should not give hits", 0, mlt);
}
public void testPageFault() throws RemoteException {
SummonSearchNode summon = SummonTestHelper.createSummonSearchNode();
ResponseCollection responses = new ResponseCollection();
try {
summon.search(new Request(
DocumentKeys.SEARCH_QUERY, "book", DocumentKeys.SEARCH_START_INDEX, 10000), responses);
} catch (RemoteException e) {
log.debug("Received RemoteException as expected");
}
fail("Search with large page number was expected to fail. Received response:\n" + responses.toXML());
}
public void testRecordBaseQueryRewrite() {
SummonSearchNode summon = SummonTestHelper.createSummonSearchNode();
assertNull("Queries for recordBase:summon should be reduced to null (~match all)",
summon.convertQuery("recordBase:summon", null));
assertEquals("recordBase:summon should be removed with implicit AND",
"\"foo\"", summon.convertQuery("recordBase:summon foo", null));
assertEquals("recordBase:summon should be removed with explicit AND",
"\"foo\"", summon.convertQuery("recordBase:summon AND foo", null));
assertEquals("OR with recordBase:summon and another recordBase should match",
null, summon.convertQuery("recordBase:summon OR recordBase:blah", null));
assertEquals("OR with recordBase:summon should leave the rest of the query",
"\"foo\"", summon.convertQuery("recordBase:summon OR foo", null));
assertEquals("recordBase:summon AND recordBase:nonexisting should not match anything",
SummonSearchNode.DEFAULT_NONMATCHING_QUERY.replace(":", ":\"") + "\"",
summon.convertQuery("recordBase:summon AND recordBase:nonexisting", null));
}
public void testIDResponse() throws IOException, TransformerException {
String QUERY = "gene and protein evolution";
log.debug("Creating SummonSearchNode");
SearchNode summon = SummonTestHelper.createSummonSearchNode(true);
Request req = new Request(
DocumentKeys.SEARCH_QUERY, QUERY,
DocumentKeys.SEARCH_COLLECT_DOCIDS, false);
List<String> ids = getAttributes(summon, req, "id", false);
assertTrue("There should be at least 1 result", ids.size() >= 1);
final Pattern EMBEDDED_ID_PATTERN = Pattern.compile("<field name=\"recordID\">(.+?)</field>", Pattern.DOTALL);
List<String> embeddedIDs = getPattern(summon, req, EMBEDDED_ID_PATTERN, false);
ExtraAsserts.assertEquals("The embedded IDs should match the plain IDs", ids, embeddedIDs);
System.out.println("Received IDs: " + Strings.join(ids, ", "));
summon.close();
}
public void testNegativeFacet() throws RemoteException {
final String JSON =
"{\"search.document.query\":\"darkmans barker\",\"search.document.collectdocids\":\"true\","
+ "\"solr.filterisfacet\":\"true\",\"solrparam.s.ho\":\"true\","
+ "\"search.document.filter\":\" NOT ContentType:\\\"Newspaper Article\\\"\","
+ "\"search.document.filter.purenegative\":\"true\"}";
SearchNode summon = SummonTestHelper.createSummonSearchNode();
ResponseCollection responses = new ResponseCollection();
Request request = new Request();
request.addJSON(JSON);
summon.search(request, responses);
assertFalse("The response should not have Newspaper Article as facet. total response was\n" + responses.toXML(),
responses.toXML().contains("<tag name=\"Newspaper Article\""));
summon.close();
}
public void testFacetSizeSmall() throws RemoteException {
assertFacetSize(3);
assertFacetSize(25);
}
private void assertFacetSize(int tagCount) throws RemoteException {
final String JSON = "{\"search.document.query\":\"thinking\",\"search.document.collectdocids\":\"true\"}";
Configuration conf = SummonTestHelper.getDefaultSummonConfiguration();
conf.set(SummonSearchNode.CONF_SOLR_FACETS, "ContentType (" + tagCount + " ALPHA)");
SearchNode summon = new SummonSearchNode(conf);
ResponseCollection responses = new ResponseCollection();
Request request = new Request();
request.addJSON(JSON);
summon.search(request, responses);
List<String> tags = StringExtraction.getStrings(responses.toXML(), "<tag.+?>");
assertEquals("The number of returned tags should be " + tagCount + "+1. The returned Tags were\n"
+ Strings.join(tags, "\n"),
tagCount + 1, tags.size());
summon.close();
}
public void testFacetSizeQuery() throws RemoteException {
int tagCount = 3;
final String JSON = "{\"search.document.query\":\"thinking\","
+ "\"search.document.collectdocids\":\"true\","
+ "\"search.facet.facets\":\"ContentType (" + tagCount + " ALPHA)\"}";
SearchNode summon = SummonTestHelper.createSummonSearchNode();
ResponseCollection responses = new ResponseCollection();
Request request = new Request();
request.addJSON(JSON);
summon.search(request, responses);
List<String> tags = StringExtraction.getStrings(responses.toXML(), "<tag.+?>");
assertEquals("The number of returned tags should be " + tagCount + "+1. The returned Tags were\n"
+ Strings.join(tags, "\n"),
tagCount + 1, tags.size());
summon.close();
}
public void testRecordBaseFacet() throws RemoteException {
final String JSON =
"{\"search.document.query\":\"darkmans barker\",\"search.document.collectdocids\":\"true\","
+ "\"solr.filterisfacet\":\"true\",\"solrparam.s.ho\":\"true\","
+ "\"search.document.filter\":\" recordBase:summon\"}";
SearchNode summon = SummonTestHelper.createSummonSearchNode();
ResponseCollection responses = new ResponseCollection();
Request request = new Request();
request.addJSON(JSON);
summon.search(request, responses);
assertTrue("The response should contain a summon tag from faceting\n" + responses.toXML(),
responses.toXML().contains("<tag name=\"summon\" addedobjects=\""));
summon.close();
}
public void testRecordBaseFacetWithOR() throws RemoteException {
final String JSON =
"{\"search.document.query\":\"darkmans barker\",\"search.document.collectdocids\":\"true\","
+ "\"solr.filterisfacet\":\"true\",\"solrparam.s.ho\":\"true\","
+ "\"search.document.filter\":\" recordBase:summon OR recordBase:sb_aleph\"}";
SearchNode summon = SummonTestHelper.createSummonSearchNode();
ResponseCollection responses = new ResponseCollection();
Request request = new Request();
request.addJSON(JSON);
summon.search(request, responses);
assertTrue("The response should contain a summon tag from faceting\n" + responses.toXML(),
responses.toXML().contains("<tag name=\"summon\" addedobjects=\""));
summon.close();
}
public void testBasicSearch() throws RemoteException {
log.debug("Creating SummonSearchNode");
SummonSearchNode summon = SummonTestHelper.createSummonSearchNode();
// summon.open(""); // Fake open for setting permits
ResponseCollection responses = new ResponseCollection();
Request request = new Request();
request.put(DocumentKeys.SEARCH_QUERY, "foo");
request.put(DocumentKeys.SEARCH_COLLECT_DOCIDS, true);
log.debug("Searching");
summon.search(request, responses);
log.debug("Finished searching");
//System.out.println(responses.toXML());
assertTrue("The result should contain at least one record", responses.toXML().contains("<record score"));
assertTrue("The result should contain at least one tag", responses.toXML().contains("<tag name"));
}
public void testMultiID() throws RemoteException {
List<String> IDs = Arrays.asList(
"FETCH-proquest_dll_11531932811",
"FETCH-proquest_dll_6357072911",
"FETCH-proquest_dll_15622214411"
);
SummonSearchNode searcher = SummonTestHelper.createSummonSearchNode(true);
for (String id: IDs) {
assertEquals("The number of hits for ID '" + id + "' should match", 1, getAttributes(searcher, new Request(
DocumentKeys.SEARCH_QUERY, "ID:\"" + id + "\"",
SummonSearchNode.SEARCH_PASSTHROUGH_QUERY, true
), "id", false).size());
}
String IDS_QUERY = "(ID:\"" + Strings.join(IDs, "\" OR ID:\"") + "\")";
Request req = new Request(
DocumentKeys.SEARCH_QUERY, IDS_QUERY,
SummonSearchNode.SEARCH_PASSTHROUGH_QUERY, true
);
List<String> returnedIDs = getAttributes(searcher, req, "id", false);
if (IDs.size() != returnedIDs.size()) {
ResponseCollection responses = new ResponseCollection();
searcher.search(req, responses);
System.out.println("Returned IDs: " + Strings.join(returnedIDs, ", "));
// System.out.println(responses.toXML());
}
assertEquals("There should be a result for each id from search '" + IDS_QUERY + "'",
IDs.size(), returnedIDs.size());
}
public void testShortFormat() throws RemoteException {
Configuration conf = SummonTestHelper.getDefaultSummonConfiguration();
conf.set(SummonResponseBuilder.CONF_SHORT_DATE, true);
log.debug("Creating SummonSearchNode");
SummonSearchNode summon = new SummonSearchNode(conf);
// summon.open(""); // Fake open for setting permits
final Pattern DATEPATTERN = Pattern.compile("<dc:date>(.+?)</dc:date>", Pattern.DOTALL);
Request request = new Request();
request.put(DocumentKeys.SEARCH_QUERY, "foo");
request.put(DocumentKeys.SEARCH_RESULT_FIELDS, "shortformat");
request.put(DocumentKeys.SEARCH_COLLECT_DOCIDS, true);
List<String> dates= getPattern(summon, request, DATEPATTERN, false);
assertTrue("There should be at least 1 extracted date", !dates.isEmpty());
for (String date: dates) {
assertTrue("the returned dates should be of length 4 or less, got '" + date + "'", date.length() <= 4);
}
// System.out.println("Got dates:\n" + Strings.join(dates, ", "));
}
public void testIDSearch() throws IOException, TransformerException {
String ID = "summon_FETCH-gale_primary_2105957371";
log.debug("Creating SummonSearchNode");
SearchNode summon = SummonTestHelper.createSummonSearchNode(true);
Request req = new Request(
DocumentKeys.SEARCH_QUERY, "recordID:\"" + ID + "\"",
DocumentKeys.SEARCH_MAX_RECORDS, 1,
DocumentKeys.SEARCH_COLLECT_DOCIDS, false);
List<String> ids = getAttributes(summon, req, "id", false);
assertTrue("There should be at least 1 result", ids.size() >= 1);
}
public void testTruncation() throws IOException, TransformerException {
String PLAIN = "Author:andersen";
String ESCAPED = "Author:andersen\\ christian";
String TRUNCATED = "Author:andersen*";
String ESCAPED_TRUNCATED = "Author:andersen\\ c*";
String ESCAPED_TRUNCATED2 = "lfo:andersen\\ h\\ c*";
List<String> QUERIES = Arrays.asList(PLAIN, ESCAPED, TRUNCATED, ESCAPED_TRUNCATED, ESCAPED_TRUNCATED2);
log.debug("Creating SummonSearchNode");
Configuration conf = SummonTestHelper.getDefaultSummonConfiguration();
conf.set(SolrSearchNode.CONF_SOLR_READ_TIMEOUT, 20*1000);
SearchNode summon = new SummonSearchNode(conf);
for (String query: QUERIES) {
Request req = new Request(
DocumentKeys.SEARCH_QUERY, query,
DocumentKeys.SEARCH_COLLECT_DOCIDS, false);
long searchTime = -System.currentTimeMillis();
List<String> ids = getAttributes(summon, req, "id", false);
searchTime += System.currentTimeMillis();
assertFalse("There should be at least 1 result for " + query, ids.isEmpty());
log.info("Got " + ids.size() + " from query '" + query + "' in " + searchTime + " ms");
}
}
public void testGetField() throws IOException, TransformerException {
String ID = "summon_FETCH-gale_primary_2105957371";
log.debug("Creating SummonSearchNode");
SearchNode summon = SummonTestHelper.createSummonSearchNode(true);
String fieldName = "shortformat";
String field = getField(summon, ID, fieldName);
assertTrue("The field '" + fieldName + "' from ID '" + ID + "' should have content",
field != null && !"".equals(field));
// System.out.println("'" + field + "'");
}
/* This is equivalent to SearchWS#getField */
private String getField(SearchNode searcher, String id, String fieldName) throws IOException, TransformerException {
String retXML;
Request req = new Request();
req.put(DocumentKeys.SEARCH_QUERY, "ID:\"" + id + "\"");
req.put(DocumentKeys.SEARCH_MAX_RECORDS, 1);
req.put(DocumentKeys.SEARCH_COLLECT_DOCIDS, false);
ResponseCollection res = new ResponseCollection();
searcher.search(req, res);
// System.out.println(res.toXML());
Document dom = DOM.stringToDOM(res.toXML());
Node subDom = DOM.selectNode(
dom, "/responsecollection/response/documentresult/record/field[@name='" + fieldName + "']");
retXML = DOM.domToString(subDom);
return retXML;
}
public void testNonExistingFacet() throws RemoteException {
final Request request = new Request(
"search.document.query", "foo",
"search.document.filter", "Language:abcde32542f",
"search.document.collectdocids", "true",
"solr.filterisfacet", "true"
);
SummonSearchNode summon = SummonTestHelper.createSummonSearchNode();
ResponseCollection responses = new ResponseCollection();
log.debug("Searching");
summon.search(request, responses);
log.debug("Finished searching");
for (Response response : responses) {
if (response instanceof FacetResultExternal) {
FacetResultExternal facets = (FacetResultExternal)response;
for (Map.Entry<String, List<FacetResultImpl.Tag<String>>> entry: facets.getMap().entrySet()) {
assertEquals("The number of tags for facet '" + entry.getKey()
+ "' should be 0 as there should be no hits. First tag was '"
+ (entry.getValue().isEmpty() ? "N/A" : entry.getValue().get(0).getKey()) + "',",
0, entry.getValue().size());
}
}
}
}
public void testColonSearch() throws RemoteException {
final String OK = "FETCH-proquest_dll_14482952011";
final String PROBLEM = "FETCH-doaj_primary_oai:doaj-articles:932b6445ce452a2b2a544189863c472e1";
performSearch("ID:\"" + OK + "\"");
performSearch("ID:\"" + PROBLEM + "\"");
}
private void performSearch(String query) throws RemoteException {
log.debug("Creating SummonSearchNode");
SummonSearchNode summon = SummonTestHelper.createSummonSearchNode();
ResponseCollection responses = new ResponseCollection();
Request request = new Request();
request.put(DocumentKeys.SEARCH_QUERY, query);
request.put(DocumentKeys.SEARCH_COLLECT_DOCIDS, true);
log.debug("Searching");
summon.search(request, responses);
log.debug("Finished searching");
// System.out.println(responses.toXML());
assertTrue("The result should contain at least one record for query '" + query + "'",
responses.toXML().contains("<record score"));
}
public void testFacetOrder() throws RemoteException {
Configuration conf = SummonTestHelper.getDefaultSummonConfiguration();
conf.set(DocumentKeys.SEARCH_COLLECT_DOCIDS, true);
//SummonSearchNode.CONF_SOLR_FACETS, ""
log.debug("Creating SummonSearchNode");
SummonSearchNode summon = new SummonSearchNode(conf);
// summon.open(""); // Fake open for setting permits
ResponseCollection responses = new ResponseCollection();
Request request = new Request();
request.put(DocumentKeys.SEARCH_QUERY, "foo");
request.put(DocumentKeys.SEARCH_COLLECT_DOCIDS, true);
log.debug("Searching");
summon.search(request, responses);
log.debug("Finished searching");
List<String> facets = getFacetNames(responses);
List<String> expected = new ArrayList<String>(Arrays.asList(SummonSearchNode.DEFAULT_SUMMON_FACETS.split(" ?, ?")));
expected.add("recordBase"); // We always add this when we're doing faceting
for (int i = expected.size()-1 ; i >= 0 ; i--) {
if (!facets.contains(expected.get(i))) {
expected.remove(i);
}
}
assertEquals("The order of the facets should be correct",
Strings.join(expected, ", "), Strings.join(facets, ", "));
// System.out.println(responses.toXML());
// System.out.println(Strings.join(facets, ", "));
}
public void testSpecificFacets() throws RemoteException {
Configuration conf = SummonTestHelper.getDefaultSummonConfiguration();
conf.set(DocumentKeys.SEARCH_COLLECT_DOCIDS, true);
conf.set(SummonSearchNode.CONF_SOLR_FACETS, "SubjectTerms");
log.debug("Creating SummonSearchNode");
SummonSearchNode summon = new SummonSearchNode(conf);
ResponseCollection responses = new ResponseCollection();
Request request = new Request();
request.put(DocumentKeys.SEARCH_QUERY, "foo");
request.put(DocumentKeys.SEARCH_COLLECT_DOCIDS, true);
log.debug("Searching");
summon.search(request, responses);
log.debug("Finished searching");
List<String> facets = getFacetNames(responses);
assertEquals("The number of facets should be correct", 2, facets.size()); // 2 because of recordBase
assertEquals("The returned facet should be correct",
"SubjectTerms, recordBase", Strings.join(facets, ", "));
}
public void testFacetSortingCount() throws RemoteException {
Configuration conf = SummonTestHelper.getDefaultSummonConfiguration();
conf.set(DocumentKeys.SEARCH_COLLECT_DOCIDS, true);
conf.set(SummonSearchNode.CONF_SOLR_FACETS, "SubjectTerms");
assertFacetOrder(conf, false);
}
// Summon does not support index ordering of facets so we must cheat by over-requesting and post-processing
public void testFacetSortingAlpha() throws RemoteException {
Configuration conf = SummonTestHelper.getDefaultSummonConfiguration();
conf.set(DocumentKeys.SEARCH_COLLECT_DOCIDS, true);
conf.set(SummonSearchNode.CONF_SOLR_FACETS, "SubjectTerms(ALPHA)");
assertFacetOrder(conf, true);
}
private void assertFacetOrder(Configuration summonConf, boolean alpha) throws RemoteException {
log.debug("Creating SummonSearchNode");
SummonSearchNode summon = new SummonSearchNode(summonConf);
ResponseCollection responses = new ResponseCollection();
Request request = new Request();
request.put(DocumentKeys.SEARCH_QUERY, "foo");
request.put(DocumentKeys.SEARCH_COLLECT_DOCIDS, true);
log.debug("Searching");
summon.search(request, responses);
log.debug("Finished searching");
List<String> tags = getTags(responses, "SubjectTerms");
List<String> tagsAlpha = new ArrayList<String>(tags);
Collections.sort(tagsAlpha);
if (alpha) {
ExtraAsserts.assertEquals(
"The order should be alphanumeric\nExp: "
+ Strings.join(tagsAlpha, " ") + "\nAct: " + Strings.join(tags, " "),
tagsAlpha, tags);
} else {
boolean misMatch = false;
for (int i = 0 ; i < tags.size() ; i++) {
if (!tags.get(i).equals(tagsAlpha.get(i))) {
misMatch = true;
break;
}
}
if (!misMatch) {
fail("The order should not be alphanumeric but it was");
}
}
log.debug("Received facets with alpha=" + alpha + ": " + Strings.join(tags, ", "));
}
private List<String> getTags(ResponseCollection responses, String facet) {
List<String> result = new ArrayList<String>();
for (Response response: responses) {
if (response instanceof FacetResultExternal) {
FacetResultExternal facetResult = (FacetResultExternal)response;
List<FacetResultImpl.Tag<String>> tags = facetResult.getMap().get(facet);
for (FacetResultImpl.Tag<String> tag: tags) {
result.add(tag.getKey() + "(" + tag.getCount() + ")");
}
return result;
}
}
fail("Unable to locate a FacetResponse in the ResponseCollection");
return null;
}
public void testNegativeFacets() throws RemoteException {
final String QUERY = "foo fighters NOT limits NOT (boo OR bam)";
final String FACET = "SubjectTerms:\"united states\"";
SummonSearchNode summon = SummonTestHelper.createSummonSearchNode();
assertHits("There should be at least one hit for positive faceting",
summon,
DocumentKeys.SEARCH_QUERY, QUERY,
DocumentKeys.SEARCH_FILTER, FACET);
assertHits("There should be at least one hit for parenthesized positive faceting", summon,
DocumentKeys.SEARCH_QUERY, QUERY,
DocumentKeys.SEARCH_FILTER, "(" + FACET + ")");
assertHits("There should be at least one hit for filter with pure negative faceting", summon,
DocumentKeys.SEARCH_QUERY, QUERY,
DocumentKeys.SEARCH_FILTER_PURE_NEGATIVE, "true",
DocumentKeys.SEARCH_FILTER, "NOT " + FACET);
summon.close();
}
public void testFilterFacets() throws RemoteException {
final String QUERY = "foo fighters";
final String FACET = "SubjectTerms:\"united states\"";
final String FACET_NEG = "-SubjectTerms:\"united states\"";
SummonSearchNode summon = SummonTestHelper.createSummonSearchNode();
assertHits("There should be at least one hit for standard positive faceting",
summon,
DocumentKeys.SEARCH_QUERY, QUERY,
DocumentKeys.SEARCH_FILTER, FACET);
assertHits("There should be at least one hit for facet filter positive faceting",
summon,
DocumentKeys.SEARCH_QUERY, QUERY,
DocumentKeys.SEARCH_FILTER, FACET,
SummonSearchNode.SEARCH_SOLR_FILTER_IS_FACET, "true");
assertHits("There should be at least one hit for standard negative faceting",
summon,
DocumentKeys.SEARCH_QUERY, QUERY,
DocumentKeys.SEARCH_FILTER, FACET_NEG,
DocumentKeys.SEARCH_FILTER_PURE_NEGATIVE, "true");
assertHits("There should be at least one hit for facet filter negative faceting",
summon,
DocumentKeys.SEARCH_QUERY, QUERY,
DocumentKeys.SEARCH_FILTER, FACET_NEG,
SummonSearchNode.SEARCH_SOLR_FILTER_IS_FACET, "true");
summon.close();
}
// summon used to support pure negative filters (in 2011) but apparently does not with the 2.0.0-API.
// If they change their stance on the issue, we want to switch back to using pure negative filters, as it
// does not affect ranking.
public void testNegativeFacetsSupport() throws RemoteException {
final String QUERY = "foo fighters NOT limits NOT (boo OR bam)";
final String FACET = "SubjectTerms:\"united states\"";
Configuration conf = SummonTestHelper.getDefaultSummonConfiguration();
conf.set(SummonSearchNode.CONF_SUPPORTS_PURE_NEGATIVE_FILTERS, true);
SummonSearchNode summon = new SummonSearchNode(conf);
assertEquals("There should be zero hits for filter with assumed pure negative faceting support", 0,
getHits(summon,
DocumentKeys.SEARCH_QUERY, QUERY,
DocumentKeys.SEARCH_FILTER_PURE_NEGATIVE, "true",
DocumentKeys.SEARCH_FILTER, "NOT " + FACET));
summon.close();
}
public void testQueryWithNegativeFacets() throws RemoteException {
final String QUERY = "foo";
final String FACET = "SubjectTerms:\"analysis\"";
SummonSearchNode summon = SummonTestHelper.createSummonSearchNode();
assertHits("There should be at least one hit for positive faceting", summon,
DocumentKeys.SEARCH_QUERY, QUERY,
DocumentKeys.SEARCH_FILTER, FACET);
assertHits("There should be at least one hit for query with negative facet", summon,
DocumentKeys.SEARCH_QUERY, QUERY,
DocumentKeys.SEARCH_FILTER_PURE_NEGATIVE, Boolean.TRUE.toString(),
DocumentKeys.SEARCH_FILTER, "NOT " + FACET);
summon.close();
}
public void testSortedSearch() throws RemoteException {
Configuration conf = SummonTestHelper.getDefaultSummonConfiguration();
conf.set(InteractionAdjuster.CONF_ADJUST_DOCUMENT_FIELDS, "sort_year_asc - PublicationDate");
log.debug("Creating SummonSearchNode");
SummonSearchNode summon = new SummonSearchNode(conf);
// summon.open(""); // Fake open for setting permits
ResponseCollection responses = new ResponseCollection();
Request request = new Request();
request.put(DocumentKeys.SEARCH_QUERY, "sb");
request.put(DocumentKeys.SEARCH_SORTKEY, "PublicationDate");
// request.put(DocumentKeys.SEARCH_REVERSE, true);
request.put(DocumentKeys.SEARCH_COLLECT_DOCIDS, true);
log.debug("Searching");
summon.search(request, responses);
log.debug("Finished searching");
List<String> sortValues = getAttributes(summon, request, "sortValue", true);
String lastValue = null;
for (String sortValue: sortValues) {
assertTrue("The sort values should be in unicode order but was " + Strings.join(sortValues, ", "),
lastValue == null || lastValue.compareTo(sortValue) <= 0);
// System.out.println(lastValue + " vs " + sortValue + ": " + (lastValue == null ? 0 : lastValue.compareTo(sortValue)));
lastValue = sortValue;
}
log.debug("Test passed with sort values\n" + Strings.join(sortValues, "\n"));
}
public void testSortedDate() throws RemoteException {
Configuration conf = SummonTestHelper.getDefaultSummonConfiguration();
conf.set(InteractionAdjuster.CONF_ADJUST_DOCUMENT_FIELDS, "sort_year_asc - PublicationDate");
log.debug("Creating SummonSearchNode");
SummonSearchNode summon = new SummonSearchNode(conf);
// summon.open(""); // Fake open for setting permits
Request request = new Request();
request.put(DocumentKeys.SEARCH_QUERY, "dolphin whale");
request.put(DocumentKeys.SEARCH_SORTKEY, "PublicationDate");
// request.put(DocumentKeys.SEARCH_REVERSE, true);
request.put(DocumentKeys.SEARCH_COLLECT_DOCIDS, true);
log.debug("Searching");
List<String> fields = getField(summon, request, "PublicationDate_xml_iso");
log.debug("Finished searching");
String lastValue = null;
for (String sortValue: fields) {
assertTrue("The field values should be in unicode order but was " + Strings.join(fields, ", "),
lastValue == null || lastValue.compareTo(sortValue) <= 0);
// System.out.println(lastValue + " vs " + sortValue + ": " + (lastValue == null ? 0 : lastValue.compareTo(sortValue)));
lastValue = sortValue;
}
log.debug("Test passed with field values\n" + Strings.join(fields, "\n"));
}
public void testFacetedSearchNoFaceting() throws Exception {
assertSomeHits(new Request(
DocumentKeys.SEARCH_QUERY, "first"
));
}
public void testFacetedSearchNoHits() throws Exception {
Request request = new Request(
DocumentKeys.SEARCH_FILTER, "recordBase:nothere",
DocumentKeys.SEARCH_QUERY, "first"
);
ResponseCollection responses = search(request);
assertTrue("There should be a response", responses.iterator().hasNext());
assertEquals("There should be no hits. Response was\n" + responses.toXML(),
0, ((DocumentResponse) responses.iterator().next()).getHitCount());
}
public void testFacetedSearchSomeHits() throws Exception {
assertSomeHits(new Request(
DocumentKeys.SEARCH_FILTER, "recordBase:summon",
DocumentKeys.SEARCH_QUERY, "first"
));
}
private void assertSomeHits(Request request) throws RemoteException {
ResponseCollection responses = search(request);
assertTrue("There should be a response", responses.iterator().hasNext());
assertTrue("There should be some hits. Response was\n" + responses.toXML(),
((DocumentResponse) responses.iterator().next()).getHitCount() > 0);
}
private ResponseCollection search(Request request) throws RemoteException {
SearchNode searcher = SummonTestHelper.createSummonSearchNode();
try {
ResponseCollection responses = new ResponseCollection();
searcher.search(request, responses);
return responses;
} finally {
searcher.close();
}
}
public void testSortedSearchRelevance() throws RemoteException {
Configuration conf = SummonTestHelper.getDefaultSummonConfiguration();
conf.set(InteractionAdjuster.CONF_ADJUST_DOCUMENT_FIELDS, "sort_year_asc - PublicationDate");
log.debug("Creating SummonSearchNode");
SummonSearchNode summon = new SummonSearchNode(conf);
// summon.open(""); // Fake open for setting permits
ResponseCollection responses = new ResponseCollection();
Request request = new Request();
request.put(DocumentKeys.SEARCH_QUERY, "foo");
request.put(DocumentKeys.SEARCH_SORTKEY, DocumentKeys.SORT_ON_SCORE);
request.put(DocumentKeys.SEARCH_COLLECT_DOCIDS, true);
log.debug("Searching");
summon.search(request, responses);
log.debug("Finished searching");
List<String> ids = getAttributes(summon, request, "id", false);
assertTrue("There should be some hits", !ids.isEmpty());
}
public void testPaging() throws RemoteException {
SummonSearchNode summon = SummonTestHelper.createSummonSearchNode();
// summon.open(""); // Fake open for setting permits
List<String> ids0 = getAttributes(
summon, new Request(
DocumentKeys.SEARCH_QUERY, "foo",
DocumentKeys.SEARCH_MAX_RECORDS, 20,
DocumentKeys.SEARCH_START_INDEX, 0),
"id", false);
List<String> ids1 = getAttributes(
summon, new Request(
DocumentKeys.SEARCH_QUERY, "foo",
DocumentKeys.SEARCH_MAX_RECORDS, 20,
DocumentKeys.SEARCH_START_INDEX, 20),
"id", false);
assertNotEquals("The hits should differ from page 0 and 1",
Strings.join(ids0, ", "), Strings.join(ids1, ", "));
}
private void assertNotEquals(String message, String expected, String actual) {
assertFalse(message + ".\nExpected: " + expected + "\nActual: " + actual,
expected.equals(actual));
}
private List<String> getAttributes(
SearchNode searcher, Request request, String attributeName, boolean explicitMerge) throws RemoteException {
final Pattern IDPATTERN = Pattern.compile("<record.*?" + attributeName + "=\"(.+?)\".*?>", Pattern.DOTALL);
return getPattern(searcher, request, IDPATTERN, explicitMerge);
/* ResponseCollection responses = new ResponseCollection();
searcher.search(request, responses);
responses.iterator().next().merge(responses.iterator().next());
String[] lines = responses.toXML().split("\n");
List<String> result = new ArrayList<String>();
for (String line: lines) {
Matcher matcher = IDPATTERN.matcher(line);
if (matcher.matches()) {
result.add(matcher.group(1));
}
}
return result;*/
}
private List<String> getField(SearchNode searcher, Request request, String fieldName) throws RemoteException {
final Pattern IDPATTERN = Pattern.compile(
"<field name=\"" + fieldName + "\">(.+?)</field>", Pattern.DOTALL);
return getPattern(searcher, request, IDPATTERN, false);
}
private List<String> getFacetNames(ResponseCollection responses) {
Pattern FACET = Pattern.compile(".*<facet name=\"(.+?)\">");
List<String> result = new ArrayList<String>();
String[] lines = responses.toXML().split("\n");
for (String line : lines) {
Matcher matcher = FACET.matcher(line);
if (matcher.matches()) {
result.add(matcher.group(1));
}
}
return result;
}
private List<String> getPattern(
SearchNode searcher, Request request, Pattern pattern, boolean explicitMerge) throws RemoteException {
ResponseCollection responses = new ResponseCollection();
searcher.search(request, responses);
if (explicitMerge) {
responses.iterator().next().merge(responses.iterator().next());
}
String xml = responses.toXML();
Matcher matcher = pattern.matcher(xml);
List<String> result = new ArrayList<String>();
while (matcher.find()) {
result.add(Strings.join(matcher.group(1).split("\n"), ", "));
}
return result;
}
public void testRecommendations() throws RemoteException {
SummonSearchNode summon = SummonTestHelper.createSummonSearchNode();
ResponseCollection responses = new ResponseCollection();
Request request = new Request();
request.put(DocumentKeys.SEARCH_QUERY, "PublicationTitle:jama");
// request.put(DocumentKeys.SEARCH_QUERY, "+(PublicationTitle:jama OR PublicationTitle:jama) +(ContentType:Article OR ContentType:\"Book Chapter\" OR ContentType:\"Book Review\" OR ContentType:\"Journal Article\" OR ContentType:\"Magazine Article\" OR ContentType:Newsletter OR ContentType:\"Newspaper Article\" OR ContentType:\"Publication Article\" OR ContentType:\"Trade Publication Article\")");
/*
\+\(PublicationTitle:jama\ OR\ PublicationTitle:jama\)\ \+\(ContentType:Article\ OR\ ContentType:\"Book\ Chapter\"\ OR\ ContentType:\"Book\ Review\"\ OR\ ContentType:\"Journal\ Article\"\ OR\ ContentType:\"Magazine\ Article\"\ OR\ ContentType:Newsletter\ OR\ ContentType:\"Newspaper\ Article\"\ OR\ ContentType:\"Publication\ Article\"\ OR\ ContentType:\"Trade\ Publication\ Article\"\)
*/
request.put(DocumentKeys.SEARCH_COLLECT_DOCIDS, true);
summon.search(request, responses);
// System.out.println(responses.toXML());
assertTrue("The result should contain at least one recommendation",
responses.toXML().contains("<recommendation "));
/* responses.clear();
request.put(DocumentKeys.SEARCH_QUERY, "noobddd");
summon.search(request, responses);
System.out.println(responses.toXML());
*/
}
public void testReportedTiming() throws RemoteException {
SummonSearchNode summon = SummonTestHelper.createSummonSearchNode();
ResponseCollection responses = new ResponseCollection();
Request request = new Request();
request.put(DocumentKeys.SEARCH_QUERY, "foo");
summon.search(request, responses);
Integer rawTime = getTiming(responses, "summon.rawcall");
assertNotNull("There should be raw time", rawTime);
Integer reportedTime = getTiming(responses, "summon.reportedtime");
assertNotNull("There should be reported time", reportedTime);
assertTrue("The reported time (" + reportedTime + ") should be lower than the raw time (" + rawTime + ")",
reportedTime <= rawTime);
log.debug("Timing raw=" + rawTime + ", reported=" + reportedTime);
}
private Integer getTiming(ResponseCollection responses, String key) {
String[] timings = responses.getTiming().split("[|]");
for (String timing: timings) {
String[] tokens = timing.split(":");
if (tokens.length == 2 && key.equals(tokens[0])) {
return Integer.parseInt(tokens[1]);
}
}
return null;
}
public void testFilterVsQuery() throws RemoteException {
SummonSearchNode summon = SummonTestHelper.createSummonSearchNode();
long qHitCount = getHits(summon,
DocumentKeys.SEARCH_QUERY, "PublicationTitle:jama",
SummonSearchNode.SEARCH_PASSTHROUGH_QUERY, "true");
long fHitCount = getHits(summon,
DocumentKeys.SEARCH_FILTER, "PublicationTitle:jama",
SummonSearchNode.SEARCH_PASSTHROUGH_QUERY, "true");
assertTrue("The filter hit count " + fHitCount + " should differ from query hit count " + qHitCount
+ " by less than 100",
Math.abs(fHitCount - qHitCount) < 100);
}
public void testFilterVsQuery2() throws RemoteException {
SummonSearchNode summon = SummonTestHelper.createSummonSearchNode();
long qHitCount = getHits(
summon,
DocumentKeys.SEARCH_QUERY, "PublicationTitle:jama",
DocumentKeys.SEARCH_FILTER, "old");
long fHitCount = getHits(
summon,
DocumentKeys.SEARCH_FILTER, "PublicationTitle:jama",
DocumentKeys.SEARCH_QUERY, "old");
assertTrue("The filter(old) hit count " + fHitCount + " should differ less than 100 from query(old) hit count "
+ qHitCount + " as summon API 2.0.0 does field expansion on filters",
Math.abs(fHitCount - qHitCount) < 100);
// This was only true in the pre-API 2.0.0. Apparently the new API does expands default fields for filters
// assertTrue("The filter(old) hit count " + fHitCount + " should differ from query(old) hit count " + qHitCount
// + " by more than 100 as filter query apparently does not query parse with default fields",
// Math.abs(fHitCount - qHitCount) > 100);
}
public void testDismaxAnd() throws RemoteException {
String QUERY1 = "public health policy";
String QUERY2 = "alternative medicine";
//String QUERY = "work and life balance";
//String QUERY = "Small business and Ontario";
SummonSearchNode summon = SummonTestHelper.createSummonSearchNode();
List<String> titlesLower = getField(summon, new Request(
DocumentKeys.SEARCH_QUERY, QUERY1 + " and " + QUERY2,
SummonSearchNode.SEARCH_PASSTHROUGH_QUERY, true,
SummonSearchNode.SEARCH_DISMAX_SABOTAGE, false
), "Title");
String lower = Strings.join(titlesLower, "\n").replace("<h>", "").replace("</h>", "");
List<String> titlesUpper = getField(summon, new Request(
DocumentKeys.SEARCH_QUERY, QUERY1 + " AND " + QUERY2,
SummonSearchNode.SEARCH_PASSTHROUGH_QUERY, true,
SummonSearchNode.SEARCH_DISMAX_SABOTAGE, false
), "Title");
String upper = Strings.join(titlesUpper, "\n").replace("<h>", "").replace("</h>", "");
summon.close();
if (lower.equals(upper)) {
fail("Using 'and' and 'AND' should not yield the same result\n" + lower);
} else {
System.out.println("Using 'and' and 'AND' gave different results:\nand: " +
lower.replace("\n", ", ") + "\nAND: " + upper.replace("\n", ", "));
}
}
public void testDismaxWithQuoting() throws RemoteException {
String QUERY = "public health policy and alternative medicine";
SummonSearchNode summon = SummonTestHelper.createSummonSearchNode();
List<String> titlesRaw = getField(summon, new Request(
DocumentKeys.SEARCH_QUERY, QUERY,
SummonSearchNode.SEARCH_PASSTHROUGH_QUERY, true,
SummonSearchNode.SEARCH_DISMAX_SABOTAGE, false
), "Title");
String raw = Strings.join(titlesRaw, "\n").replace("<h>", "").replace("</h>", "");
List<String> titlesQuoted = getField(summon, new Request(
DocumentKeys.SEARCH_QUERY, QUERY,
SummonSearchNode.SEARCH_PASSTHROUGH_QUERY, false, // Adds quotes around individual terms
SummonSearchNode.SEARCH_DISMAX_SABOTAGE, false
), "Title");
String quoted = Strings.join(titlesQuoted, "\n").replace("<h>", "").replace("</h>", "");
List<String> titlesNonDismaxed = getField(summon, new Request(
DocumentKeys.SEARCH_QUERY, "(" + QUERY + ")",
SummonSearchNode.SEARCH_PASSTHROUGH_QUERY, false, // Adds quotes around individual terms
SummonSearchNode.SEARCH_DISMAX_SABOTAGE, false
), "Title");
String nonDismaxed = Strings.join(titlesNonDismaxed, "\n").replace("<h>", "").replace("</h>", "");
summon.close();
System.out.println("raw " + (raw.equals(quoted) ? "=" : "!") + "= quoted");
System.out.println("raw " + (raw.equals(nonDismaxed) ? "=" : "!") + "= parenthesized");
System.out.println("quoted " + (quoted.equals(nonDismaxed) ? "=" : "!") + "= parenthesized");
System.out.println("raw = " + raw.replace("\n", ", "));
System.out.println("quoted = " + quoted.replace("\n", ", "));
System.out.println("parenthesized = " + nonDismaxed.replace("\n", ", "));
assertEquals("The result from the raw (and thus dismaxed) query should match the result from "
+ "the quoted terms query",
raw, quoted);
}
public void testFilterVsQuery3() throws RemoteException {
SummonSearchNode summon = SummonTestHelper.createSummonSearchNode();
long qCombinedHitCount = getHits(
summon,
DocumentKeys.SEARCH_QUERY,
"PublicationTitle:jama AND Language:English");
long qHitCount = getHits(
summon,
DocumentKeys.SEARCH_QUERY, "PublicationTitle:jama",
DocumentKeys.SEARCH_FILTER, "(Language:English)");
long fHitCount = getHits(
summon,
DocumentKeys.SEARCH_FILTER, "PublicationTitle:jama",
DocumentKeys.SEARCH_QUERY, "Language:English");
assertTrue("The filter(old) hit count " + fHitCount + " should differ"
+ " from query(old) hit count " + qHitCount
+ " by less than 100. Combined hit count for query is "
+ qCombinedHitCount,
Math.abs(fHitCount - qHitCount) < 100);
}
public void testCustomParams() throws RemoteException {
final String QUERY = "reactive arthritis yersinia lassen";
Configuration confInside = SummonTestHelper.getDefaultSummonConfiguration();
Configuration confOutside = SummonTestHelper.getDefaultSummonConfiguration();
confOutside.set(SummonSearchNode.CONF_SOLR_PARAM_PREFIX + "s.ho",
new ArrayList<String>(Arrays.asList("false"))
);
Request request = new Request();
request.put(DocumentKeys.SEARCH_QUERY, QUERY);
request.put(DocumentKeys.SEARCH_COLLECT_DOCIDS, true);
SummonSearchNode summonInside = new SummonSearchNode(confInside);
ResponseCollection responsesInside = new ResponseCollection();
summonInside.search(request, responsesInside);
SummonSearchNode summonOutside = new SummonSearchNode(confOutside);
ResponseCollection responsesOutside = new ResponseCollection();
summonOutside.search(request, responsesOutside);
request.put(SummonSearchNode.CONF_SOLR_PARAM_PREFIX + "s.ho",
new ArrayList<String>(Arrays.asList("false")));
ResponseCollection responsesSearchTweak = new ResponseCollection();
summonInside.search(request, responsesSearchTweak);
int countInside = countResults(responsesInside);
int countOutside = countResults(responsesOutside);
assertTrue("The number of results for a search for '" + QUERY + "' within holdings (" + confInside
+ ") should be less that outside holdings (" + confOutside + ")",
countInside < countOutside);
log.info(String.format("The search for '%s' gave %d hits within holdings and %d hits in total",
QUERY, countInside, countOutside));
int countSearchTweak = countResults(responsesSearchTweak);
assertEquals(
"Query time specification of 's.ho=false' should give the same "
+ "result as configuration time specification of the same",
countOutside, countSearchTweak);
}
public void testConvertRangeQueries() throws RemoteException {
final String QUERY = "foo bar:[10 TO 20] OR baz:[87 TO goa]";
Map<String, List<String>> params = new HashMap<String, List<String>>();
String stripped = new SummonSearchNode(getSummonConfiguration()).convertQuery(QUERY, params);
assertNotNull("RangeFilter should be defined", params.get("s.rf"));
List<String> ranges = params.get("s.rf");
assertEquals("The right number of ranges should be extracted", 2, ranges.size());
assertEquals("Range #1 should be correct", "bar,10:20", ranges.get(0));
assertEquals("Range #2 should be correct", "baz,87:goa", ranges.get(1));
assertEquals("The resulting query should be stripped of ranges", "\"foo\"", stripped);
}
public void testConvertRangeQueriesEmpty() throws RemoteException {
final String QUERY = "bar:[10 TO 20]";
Map<String, List<String>> params = new HashMap<String, List<String>>();
String stripped = new SummonSearchNode(getSummonConfiguration()).convertQuery(QUERY, params);
assertNotNull("RangeFilter should be defined", params.get("s.rf"));
List<String> ranges = params.get("s.rf");
assertEquals("The right number of ranges should be extracted", 1, ranges.size());
assertEquals("Range #1 should be correct", "bar,10:20", ranges.get(0));
assertNull("The resulting query should be null", stripped);
}
private Configuration getSummonConfiguration() {
return Configuration.newMemoryBased(
SummonSearchNode.CONF_SUMMON_ACCESSID, "foo",
SummonSearchNode.CONF_SUMMON_ACCESSKEY, "bar");
}
public void testFaultyQuoteRemoval() throws RemoteException {
final String QUERY = "bar:\"foo:zoo\"";
Map<String, List<String>> params = new HashMap<String, List<String>>();
String stripped = new SummonSearchNode(getSummonConfiguration()).convertQuery(QUERY, params);
assertNull("RangeFilter should not be defined", params.get("s.rf"));
assertEquals("The resulting query should unchanged", QUERY, stripped);
}
// This fails, but as we are really testing Summon here, there is not much
// we can do about it
@SuppressWarnings({"UnusedDeclaration"})
public void disabledtestCounts() throws RemoteException {
// final String QUERY = "reactive arthritis yersinia lassen";
final String QUERY = "author:(Helweg Larsen) abuse";
Request request = new Request();
request.addJSON(
"{search.document.query:\"" + QUERY + "\", summonparam.s.ps:\"15\", summonparam.s.ho:\"false\"}");
// String r1 = request.toString(true);
SummonSearchNode summon = SummonTestHelper.createSummonSearchNode();
ResponseCollection responses = new ResponseCollection();
summon.search(request, responses);
int count15 = countResults(responses);
request.clear();
request.addJSON(
"{search.document.query:\"" + QUERY + "\", summonparam.s.ps:\"30\", summonparam.s.ho:\"false\"}");
// String r2 = request.toString(true);
responses.clear();
summon.search(request, responses);
int count20 = countResults(responses);
/*
request.clear();
request.put(DocumentKeys.SEARCH_QUERY, QUERY);
request.put(DocumentKeys.SEARCH_COLLECT_DOCIDS, false);
request.put(SummonSearchNode.CONF_SOLR_PARAM_PREFIX + "s.ho",
new ArrayList<String>(Arrays.asList("false")));
request.put(DocumentKeys.SEARCH_MAX_RECORDS, 15);
String rOld15 = request.toString(true);
responses.clear();
summon.search(request, responses);
int countOld15 = countResults(responses);
request.clear();
request.put(DocumentKeys.SEARCH_QUERY, QUERY);
request.put(DocumentKeys.SEARCH_COLLECT_DOCIDS, false);
request.put(SummonSearchNode.CONF_SOLR_PARAM_PREFIX + "s.ho",
new ArrayList<String>(Arrays.asList("false")));
request.put(DocumentKeys.SEARCH_MAX_RECORDS, 20);
String rOld20 = request.toString(true);
responses.clear();
summon.search(request, responses);
int countOld20 = countResults(responses);
*/
// System.out.println("Request 15: " + r1 + ": " + count15);
// System.out.println("Request 20: " + r2 + ": " + count20);
// System.out.println("Request O15: " + rOld15 + ": " + countOld15);
// System.out.println("Request O20: " + rOld20 + ": " + countOld20);
assertEquals("The number of hits should not be affected by page size", count15, count20);
}
// Author can be returned in the field Author_xml (primary) and Author (secondary). If both fields are present,
// Author should be ignored.
public void testAuthorExtraction() throws IOException {
}
private int countResults(ResponseCollection responses) {
for (Response response: responses) {
if (response instanceof DocumentResponse) {
return (int)((DocumentResponse)response).getHitCount();
}
}
throw new IllegalArgumentException(
"No documentResponse in ResponseCollection");
}
public void testAdjustingSearcher() throws IOException {
SimplePair<String, String> credentials = SummonTestHelper.getCredentials();
Configuration conf = Configuration.newMemoryBased(
InteractionAdjuster.CONF_IDENTIFIER, "summon",
InteractionAdjuster.CONF_ADJUST_DOCUMENT_FIELDS, "recordID - ID");
Configuration inner = conf.createSubConfiguration(AdjustingSearchNode.CONF_INNER_SEARCHNODE);
inner.set(SearchNodeFactory.CONF_NODE_CLASS, SummonSearchNode.class.getCanonicalName());
inner.set(SummonSearchNode.CONF_SUMMON_ACCESSID, credentials.getKey());
inner.set(SummonSearchNode.CONF_SUMMON_ACCESSKEY, credentials.getValue());
log.debug("Creating adjusting SummonSearchNode");
AdjustingSearchNode adjusting = new AdjustingSearchNode(conf);
ResponseCollection responses = new ResponseCollection();
Request request = new Request(
//request.put(DocumentKeys.SEARCH_QUERY, "foo");
DocumentKeys.SEARCH_QUERY, "recursion in string theory",
DocumentKeys.SEARCH_COLLECT_DOCIDS, true);
log.debug("Searching");
adjusting.search(request, responses);
log.debug("Finished searching");
// TODO: Add proper test
// System.out.println(responses.toXML());
}
public void testExplicitMust() throws IOException {
final String QUERY = "miller genre as social action";
ResponseCollection explicitMustResponses = new ResponseCollection();
{
Configuration conf = SummonTestHelper.getDefaultSummonConfiguration();
conf.set(QueryRewriter.CONF_TERSE, false);
SearchNode summon = new SummonSearchNode(conf);
Request request = new Request(
DocumentKeys.SEARCH_QUERY, QUERY
);
summon.search(request, explicitMustResponses);
summon.close();
}
ResponseCollection implicitMustResponses = new ResponseCollection();
{
Configuration conf = SummonTestHelper.getDefaultSummonConfiguration();
conf.set(QueryRewriter.CONF_TERSE, true);
SearchNode summon = new SummonSearchNode(conf);
Request request = new Request(
DocumentKeys.SEARCH_QUERY, QUERY
);
summon.search(request, implicitMustResponses);
summon.close();
}
HarmoniseTestHelper.compareHits(QUERY, false, explicitMustResponses, implicitMustResponses);
}
/*
Tests if explicit weight-adjustment of terms influences the scores significantly.
*/
public void testExplicitWeightScoring() throws RemoteException {
assertScores("dolphin whales", "dolphin whales^1.000001", 10.0f);
}
/*
Tests if explicit weight-adjustment of terms influences the order of documents.
*/
public void testExplicitWeightOrder() throws RemoteException {
assertOrder("dolphin whales", "dolphin whales^1.0");
}
public void testExplicitWeightOrderSingleTerm() throws RemoteException {
assertOrder("whales", "whales^1.0");
}
public void testExplicitWeightOrderFoo() throws RemoteException {
assertOrder("foo", "foo^1.0"); // By some funny coincidence, foo works when whales doesn't
}
private void assertOrder(String query1, String query2) throws RemoteException {
SearchNode summon = SummonTestHelper.createSummonSearchNode();
try {
List<String> ids1 = getAttributes(summon, new Request(
DocumentKeys.SEARCH_QUERY, query1,
SummonSearchNode.SEARCH_PASSTHROUGH_QUERY, true
), "id", false);
List<String> ids2 = getAttributes(summon, new Request(
DocumentKeys.SEARCH_QUERY, query2,
SummonSearchNode.SEARCH_PASSTHROUGH_QUERY, true
), "id", false);
ExtraAsserts.assertPermutations("Query '" + query1 + "' and '" + query2 + "'", ids1, ids2);
/* assertEquals("The number of hits for '" + query1 + "' and '" + query2 + "' should be equal",
ids1.size(), ids2.size());
assertEquals("The document order for '" + query1 + "' and '" + query2 + "' should be equal",
Strings.join(ids1, ", "), Strings.join(ids2, ", "));
*/
} finally {
summon.close();
}
}
public void testDisMaxDisabling() throws RemoteException {
final String QUERY= "asian philosophy";
SearchNode summon = SummonTestHelper.createSummonSearchNode();
try {
long plainCount =
getHits(summon, DocumentKeys.SEARCH_QUERY, QUERY, SummonSearchNode.SEARCH_DISMAX_SABOTAGE, "false");
long sabotagedCount =
getHits(summon, DocumentKeys.SEARCH_QUERY, QUERY, SummonSearchNode.SEARCH_DISMAX_SABOTAGE, "true");
assertEquals("The number of hits for a DisMax-enabled and DisMax-sabotages query should match",
plainCount, sabotagedCount);
List<String> plain = getAttributes(summon, new Request(
DocumentKeys.SEARCH_QUERY, QUERY, SummonSearchNode.SEARCH_DISMAX_SABOTAGE, false), "id", false);
List<String> sabotaged = getAttributes(summon, new Request(
DocumentKeys.SEARCH_QUERY, QUERY, SummonSearchNode.SEARCH_DISMAX_SABOTAGE, true), "id", false);
assertFalse("The ids returned by DisMax-enabled and DisMax-sabotaged query should differ",
Strings.join(plain, ", ").equals(Strings.join(sabotaged, ", ")));
} finally {
summon.close();
}
}
public void testDismaxDisablingExperiment() throws RemoteException {
assertOrder("foo bar", "(foo bar)");
}
/*
Tests if quoting of terms influences the scores significantly.
*/
public void testQuotingScoring() throws RemoteException {
assertScores("dolphin whales", "\"dolphin\" \"whales\"", 10.0f);
}
private void assertScores(String query1, String query2, float maxDifference) throws RemoteException {
SearchNode summon = SummonTestHelper.createSummonSearchNode();
ResponseCollection raw = new ResponseCollection();
summon.search(new Request(
DocumentKeys.SEARCH_QUERY, query1,
SolrSearchNode.SEARCH_PASSTHROUGH_QUERY, true
), raw);
ResponseCollection weighted = new ResponseCollection();
summon.search(new Request(DocumentKeys.SEARCH_QUERY, query2), weighted);
summon.close();
List<Double> rawScores = getScores(raw);
List<Double> weightedScores = getScores(weighted);
assertEquals("The number of hits for '" + query1 + "' and '" + query2 + "' should be equal",
rawScores.size(), weightedScores.size());
for (int i = 0 ; i < rawScores.size() ; i++) {
assertTrue(String.format(
"The scores at position %d were %s and %s. Max difference allowed is %s. "
+ "All scores for '%s' and '%s':\n%s\n%s",
i, rawScores.get(i), weightedScores.get(i), maxDifference,
query1, query2, Strings.join(rawScores, ", "), Strings.join(weightedScores, ", ")),
Math.abs(rawScores.get(i) - weightedScores.get(i)) <= maxDifference);
}
}
private List<Double> getScores(ResponseCollection responses) {
DocumentResponse docs = (DocumentResponse)responses.iterator().next();
List<Double> result = new ArrayList<Double>(docs.size());
for (DocumentResponse.Record record: docs.getRecords()) {
result.add((double)record.getScore());
}
return result;
}
// Author_xml contains the authoritative order for the authors so it should override the non-XML-version
public void testAuthor_xmlExtraction() throws RemoteException {
String fieldName = "Author";
String query = "PQID:821707502";
/* {
Configuration conf = SummonTestHelper.getDefaultSummonConfiguration();
conf.set(SummonResponseBuilder.CONF_XML_OVERRIDES_NONXML, false);
SearchNode summon = new SummonSearchNode(conf);
ResponseCollection responses = new ResponseCollection();
summon.search(new Request(DocumentKeys.SEARCH_QUERY, query), responses);
DocumentResponse docs = (DocumentResponse)responses.iterator().next();
for (DocumentResponse.Record record: docs.getRecords()) {
System.out.println("\n" + record.getId());
String author = "";
String author_xml = "";
for (DocumentResponse.Field field: record.getFields()) {
if ("Author".equals(field.getName())) {
author = field.getContent().replace("\n", ", ").replace("<h>", "").replace("</h>", "");
System.out.println("Author: " + author);
} else if ("Author_xml".equals(field.getName())) {
author_xml = field.getContent().replace("\n", ", ");
System.out.println("Author_xml: " + author_xml);
} else if ("PQID".equals(field.getName())) {
System.out.println("PQID: " + field.getContent());
}
}
if (author.length() != author_xml.length()) {
fail("We finally found a difference between Author and Author_xml besides name ordering");
}
}
summon.close();
}
*/
{ // Old behaviour
String expected = "Koetse, Willem\n"
+ "Krebs, Christopher P\n"
+ "Lindquist, Christine\n"
+ "Lattimore, Pamela K\n"
+ "Cowell, Alex J";
Configuration conf = SummonTestHelper.getDefaultSummonConfiguration();
conf.set(SummonResponseBuilder.CONF_XML_OVERRIDES_NONXML, false);
SearchNode summonNonXML = new SummonSearchNode(conf);
assertFieldContent("XML no override", summonNonXML, query, fieldName, expected, false);
summonNonXML.close();
}
{ // New behaviour
String expected = "Lattimore, Pamela K\n"
+ "Krebs, Christopher P\n"
+ "Koetse, Willem\n"
+ "Lindquist, Christine\n"
+ "Cowell, Alex J";
SearchNode summonXML = SummonTestHelper.createSummonSearchNode();
assertFieldContent("XML override", summonXML, query, fieldName, expected, false);
summonXML.close();
}
}
public void testAuthor_xmlExtraction_shortformat() throws RemoteException {
String query = "ID:FETCH-LOGICAL-c937-88b9adcf681a925445118c26ea8da2ed792f182b51857048dbb48b11a133ea321";
{ // sanity-check the Author-field
String expected = "Ferlay, Jacques\n"
+ "Shin, Hai-Rim\n"
+ "Bray, Freddie\n"
+ "Forman, David\n"
+ "Mathers, Colin\n"
+ "Parkin, Donald Maxwell";
SearchNode summon = SummonTestHelper.createSummonSearchNode();
assertFieldContent("author direct", summon, query, "Author", expected, false);
summon.close();
}
{ // shortformat should match Author
String expected =
" <shortrecord>\n"
+ " <rdf:RDF xmlns:dc=\"http://purl.org/dc/elements/1.1/\" "
+ "xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n"
+ " <rdf:Description>\n"
+ " <dc:title>Estimates of worldwide burden of cancer in 2008: GLOBOCAN 2008</dc:title>\n"
+ " <dc:creator>Ferlay, Jacques</dc:creator>\n"
+ " <dc:creator>Shin, Hai-Rim</dc:creator>\n"
+ " <dc:creator>Bray, Freddie</dc:creator>\n"
+ " <dc:creator>Forman, David</dc:creator>\n"
+ " <dc:creator>Mathers, Colin</dc:creator>\n"
+ " <dc:creator>Parkin, Donald Maxwell</dc:creator>\n"
+ " <dc:type xml:lang=\"da\">Journal Article</dc:type>\n"
+ " <dc:type xml:lang=\"en\">Journal Article</dc:type>\n"
+ " <dc:date>2010</dc:date>\n"
+ " <dc:format></dc:format>\n"
+ " </rdf:Description>\n"
+ " </rdf:RDF>\n"
+ " </shortrecord>\n";
SearchNode summon = SummonTestHelper.createSummonSearchNode();
assertFieldContent("shortformat", summon, query, "shortformat", expected, false);
summon.close();
}
}
public void testAuthor_xmlExtraction_shortformat2() throws RemoteException {
String query = "ID:FETCH-LOGICAL-c1590-71216b8d44129eb55dba9244d0a7ad32261d9b5e7a00e7987e3aa5b33750b0dc1";
{ // sanity-check the Author-field
String expected = "Fallah, Mahdi\n"
+ "Kharazmi, Elham";
SearchNode summon = SummonTestHelper.createSummonSearchNode();
assertFieldContent("author direct", summon, query, "Author", expected, false);
summon.close();
}
{ // shortformat should match Author
String expected =
" <shortrecord>\n"
+ " <rdf:RDF xmlns:dc=\"http://purl.org/dc/elements/1.1/\" "
+ "xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n"
+ " <rdf:Description>\n"
+ " <dc:title>Substantial under-estimation in cancer incidence estimates for developing "
+ "countries due to under-ascertainment in elderly cancer cases</dc:title>\n"
+ " <dc:creator>Fallah, Mahdi</dc:creator>\n"
+ " <dc:creator>Kharazmi, Elham</dc:creator>\n"
+ " <dc:type xml:lang=\"da\">Journal Article</dc:type>\n"
+ " <dc:type xml:lang=\"en\">Journal Article</dc:type>\n"
+ " <dc:date>2008</dc:date>\n"
+ " <dc:format></dc:format>\n"
+ " </rdf:Description>\n"
+ " </rdf:RDF>\n"
+ " </shortrecord>\n";
SearchNode summon = SummonTestHelper.createSummonSearchNode();
assertFieldContent("shortformat", summon, query, "shortformat", expected, false);
summon.close();
}
}
public void testScoreAssignment() throws RemoteException {
String QUERY =
"The effect of multimedia on perceived equivocality and perceived usefulness of information systems";
String BAD =
"<record score=\"0.0\" "
+ "id=\"summon_FETCH-LOGICAL-j865-7bb06e292771fe19b17b4f676a0939e693be812b38d8502735ffb8ab6e46b4d21\" "
+ "source=\"Summon\">";
SearchNode summon = SummonTestHelper.createSummonSearchNode(true);
Request req = new Request(
DocumentKeys.SEARCH_QUERY, QUERY,
DocumentKeys.SEARCH_MAX_RECORDS, 10,
DocumentKeys.SEARCH_COLLECT_DOCIDS, false);
ResponseCollection responses = new ResponseCollection();
summon.search(req, responses);
assertFalse("There should be a score != 0.0 for all records in\n" + responses.iterator().next().toXML(),
responses.iterator().next().toXML().contains(BAD));
summon.close();
}
private void assertFieldContent(String message, SearchNode searchNode, String query, String fieldName,
String expected, boolean sort) throws RemoteException {
ResponseCollection responses = new ResponseCollection();
searchNode.search(new Request(DocumentKeys.SEARCH_QUERY, query), responses);
DocumentResponse docs = (DocumentResponse)responses.iterator().next();
assertEquals(message + ". There should only be a single hit", 1, docs.getHitCount());
boolean found = false;
for (DocumentResponse.Record record: docs.getRecords()) {
for (DocumentResponse.Field field: record.getFields()) {
if (fieldName.equals(field.getName())) {
String content = field.getContent();
if (sort) {
String[] tokens = content.split("\n");
Arrays.sort(tokens);
content = Strings.join(tokens, "\n");
}
assertEquals(message + ".The field '" + fieldName + "' should have the right content",
expected, content);
found = true;
}
}
}
if (!found) {
fail("Unable to locate the field '" + fieldName + "'");
}
}
public void testIDAdjustment() throws IOException {
SimplePair<String, String> credentials = SummonTestHelper.getCredentials();
Configuration conf = Configuration.newMemoryBased(
InteractionAdjuster.CONF_IDENTIFIER, "summon",
InteractionAdjuster.CONF_ADJUST_DOCUMENT_FIELDS, "recordID - ID");
Configuration inner = conf.createSubConfiguration(
AdjustingSearchNode.CONF_INNER_SEARCHNODE);
inner.set(SearchNodeFactory.CONF_NODE_CLASS, SummonSearchNode.class.getCanonicalName());
inner.set(SummonSearchNode.CONF_SUMMON_ACCESSID, credentials.getKey());
inner.set(SummonSearchNode.CONF_SUMMON_ACCESSKEY, credentials.getValue());
log.debug("Creating adjusting SummonSearchNode");
AdjustingSearchNode adjusting = new AdjustingSearchNode(conf);
Request request = new Request();
//request.put(DocumentKeys.SEARCH_QUERY, "foo");
request.put(DocumentKeys.SEARCH_QUERY, "recursion in string theory");
request.put(DocumentKeys.SEARCH_COLLECT_DOCIDS, true);
List<String> ids = getAttributes(adjusting, request, "id", false);
assertTrue("There should be at least one ID", !ids.isEmpty());
request.clear();
request.put(DocumentKeys.SEARCH_QUERY, IndexUtils.RECORD_FIELD + ":\"" + ids.get(0) + "\"");
List<String> researchIDs = getAttributes(adjusting, request, "id", false);
assertTrue("There should be at least one hit for a search for ID '"
+ ids.get(0) + "'", !researchIDs.isEmpty());
}
// TODO: "foo:bar zoo"
// It seems that "Book / eBook" is special and will be translated to s.fvgf (Book OR eBook) by summon
// This is important as it means that we cannot use filter ContentType:"Book / eBook" to get the same
// hits as a proper facet query
public void testFacetTermWithDivider() throws RemoteException {
SearchNode summon = SummonTestHelper.createSummonSearchNode(true);
long filterCount = getHits(
summon,
DocumentKeys.SEARCH_QUERY, "foo",
DocumentKeys.SEARCH_FILTER, "ContentType:\"Book / eBook\"",
SolrSearchNode.SEARCH_SOLR_FILTER_IS_FACET, "true");
long queryCount = getHits(
summon,
DocumentKeys.SEARCH_QUERY, "foo",
DocumentKeys.SEARCH_FILTER, "ContentType:Book OR ContentType:eBook");
assertTrue("There should be at least 1 hit for either query or filter request",
queryCount > 0 || filterCount > 0);
assertEquals("The number of hits for filter and query based restrictions should be the same",
filterCount, queryCount);
summon.close();
}
public void testFacetFieldValidity() throws RemoteException {
SearchNode summon = SummonTestHelper.createSummonSearchNode(true);
String[][] FACET_QUERIES = new String[][]{
//{"Ferlay", "Author", "Ferlay\\, Jacques"}, // We need a sample from the Author facet
{"foo", "Language", "German"},
{"foo", "IsScholarly", "true"},
{"foo", "IsFullText", "true"},
{"foo", "ContentType", "Book / eBook"},
{"foo", "SubjectTerms", "biology"}
};
for (String[] facetQuery: FACET_QUERIES) {
String q = facetQuery[0];
String ff = facetQuery[1] + ":\"" + facetQuery[2] + "\"";
log.debug(String.format("Searching for query '%s' with facet filter '%s'", q, ff));
long queryCount = getHits(
summon,
DocumentKeys.SEARCH_QUERY, q,
DocumentKeys.SEARCH_FILTER, ff,
SolrSearchNode.SEARCH_SOLR_FILTER_IS_FACET, "true");
assertTrue(String.format("There should be at least 1 hit for query '%s' with facet filter '%s'", q, ff),
queryCount > 0);
}
}
protected long getHits(SearchNode searcher, String... arguments) throws RemoteException {
String HITS_PATTERN = "(?s).*hitCount=\"([0-9]*)\".*";
ResponseCollection responses = new ResponseCollection();
searcher.search(new Request(arguments), responses);
if (!Pattern.compile(HITS_PATTERN).matcher(responses.toXML()).
matches()) {
return 0;
}
String hitsS = responses.toXML().replaceAll(HITS_PATTERN, "$1");
return "".equals(hitsS) ? 0L : Long.parseLong(hitsS);
}
protected void assertHits(
String message, SearchNode searcher, String... queries)
throws RemoteException {
long hits = getHits(searcher, queries);
assertTrue(message + ". Hits == " + hits, hits > 0);
}
}
|
Core/src/test/java/dk/statsbiblioteket/summa/support/summon/search/SummonSearchNodeTest.java
|
/** 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 dk.statsbiblioteket.summa.support.summon.search;
import dk.statsbiblioteket.summa.common.configuration.Configuration;
import dk.statsbiblioteket.summa.common.lucene.index.IndexUtils;
import dk.statsbiblioteket.summa.common.unittest.ExtraAsserts;
import dk.statsbiblioteket.summa.common.util.SimplePair;
import dk.statsbiblioteket.summa.common.util.StringExtraction;
import dk.statsbiblioteket.summa.facetbrowser.api.FacetResultExternal;
import dk.statsbiblioteket.summa.facetbrowser.api.FacetResultImpl;
import dk.statsbiblioteket.summa.search.SearchNode;
import dk.statsbiblioteket.summa.search.SearchNodeFactory;
import dk.statsbiblioteket.summa.search.api.Request;
import dk.statsbiblioteket.summa.search.api.Response;
import dk.statsbiblioteket.summa.search.api.ResponseCollection;
import dk.statsbiblioteket.summa.search.api.document.DocumentKeys;
import dk.statsbiblioteket.summa.search.api.document.DocumentResponse;
import dk.statsbiblioteket.summa.search.tools.QueryRewriter;
import dk.statsbiblioteket.summa.support.api.LuceneKeys;
import dk.statsbiblioteket.summa.support.harmonise.AdjustingSearchNode;
import dk.statsbiblioteket.summa.support.harmonise.HarmoniseTestHelper;
import dk.statsbiblioteket.summa.support.harmonise.InteractionAdjuster;
import dk.statsbiblioteket.summa.support.solr.SolrSearchNode;
import dk.statsbiblioteket.util.Strings;
import dk.statsbiblioteket.util.qa.QAInfo;
import dk.statsbiblioteket.util.xml.DOM;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import javax.xml.transform.TransformerException;
import java.io.IOException;
import java.rmi.RemoteException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@QAInfo(level = QAInfo.Level.NORMAL,
state = QAInfo.State.IN_DEVELOPMENT,
author = "te")
public class SummonSearchNodeTest extends TestCase {
private static Log log = LogFactory.getLog(SummonSearchNodeTest.class);
public SummonSearchNodeTest(String name) {
super(name);
}
@Override
public void setUp() throws Exception {
super.setUp();
}
@Override
public void tearDown() throws Exception {
super.tearDown();
}
public static Test suite() {
return new TestSuite(SummonSearchNodeTest.class);
}
public void testMoreLikeThis() throws RemoteException {
SummonSearchNode summon = SummonTestHelper.createSummonSearchNode();
long standard = getHits(summon, DocumentKeys.SEARCH_QUERY, "foo");
assertTrue("A search for 'foo' should give hits", standard > 0);
long mlt = getHits(summon, DocumentKeys.SEARCH_QUERY, "foo", LuceneKeys.SEARCH_MORELIKETHIS_RECORDID, "bar");
assertEquals("A search with a MoreLikeThis ID should not give hits", 0, mlt);
}
public void testPageFault() throws RemoteException {
SummonSearchNode summon = SummonTestHelper.createSummonSearchNode();
ResponseCollection responses = new ResponseCollection();
try {
summon.search(new Request(
DocumentKeys.SEARCH_QUERY, "book", DocumentKeys.SEARCH_START_INDEX, 10000), responses);
} catch (RemoteException e) {
log.debug("Received RemoteException as expected");
}
fail("Search with large page number was expected to fail. Received response:\n" + responses.toXML());
}
public void testRecordBaseQueryRewrite() {
SummonSearchNode summon = SummonTestHelper.createSummonSearchNode();
assertNull("Queries for recordBase:summon should be reduced to null (~match all)",
summon.convertQuery("recordBase:summon", null));
assertEquals("recordBase:summon should be removed with implicit AND",
"\"foo\"", summon.convertQuery("recordBase:summon foo", null));
assertEquals("recordBase:summon should be removed with explicit AND",
"\"foo\"", summon.convertQuery("recordBase:summon AND foo", null));
assertEquals("OR with recordBase:summon and another recordBase should match",
null, summon.convertQuery("recordBase:summon OR recordBase:blah", null));
assertEquals("OR with recordBase:summon should leave the rest of the query",
"\"foo\"", summon.convertQuery("recordBase:summon OR foo", null));
assertEquals("recordBase:summon AND recordBase:nonexisting should not match anything",
SummonSearchNode.DEFAULT_NONMATCHING_QUERY.replace(":", ":\"") + "\"",
summon.convertQuery("recordBase:summon AND recordBase:nonexisting", null));
}
public void testIDResponse() throws IOException, TransformerException {
String QUERY = "gene and protein evolution";
log.debug("Creating SummonSearchNode");
SearchNode summon = SummonTestHelper.createSummonSearchNode(true);
Request req = new Request(
DocumentKeys.SEARCH_QUERY, QUERY,
DocumentKeys.SEARCH_COLLECT_DOCIDS, false);
List<String> ids = getAttributes(summon, req, "id", false);
assertTrue("There should be at least 1 result", ids.size() >= 1);
final Pattern EMBEDDED_ID_PATTERN = Pattern.compile("<field name=\"recordID\">(.+?)</field>", Pattern.DOTALL);
List<String> embeddedIDs = getPattern(summon, req, EMBEDDED_ID_PATTERN, false);
ExtraAsserts.assertEquals("The embedded IDs should match the plain IDs", ids, embeddedIDs);
System.out.println("Received IDs: " + Strings.join(ids, ", "));
summon.close();
}
public void testNegativeFacet() throws RemoteException {
final String JSON =
"{\"search.document.query\":\"darkmans barker\",\"search.document.collectdocids\":\"true\","
+ "\"solr.filterisfacet\":\"true\",\"solrparam.s.ho\":\"true\","
+ "\"search.document.filter\":\" NOT ContentType:\\\"Newspaper Article\\\"\","
+ "\"search.document.filter.purenegative\":\"true\"}";
SearchNode summon = SummonTestHelper.createSummonSearchNode();
ResponseCollection responses = new ResponseCollection();
Request request = new Request();
request.addJSON(JSON);
summon.search(request, responses);
assertFalse("The response should not have Newspaper Article as facet. total response was\n" + responses.toXML(),
responses.toXML().contains("<tag name=\"Newspaper Article\""));
summon.close();
}
public void testFacetSizeSmall() throws RemoteException {
assertFacetSize(3);
assertFacetSize(25);
}
private void assertFacetSize(int tagCount) throws RemoteException {
final String JSON = "{\"search.document.query\":\"thinking\",\"search.document.collectdocids\":\"true\"}";
Configuration conf = SummonTestHelper.getDefaultSummonConfiguration();
conf.set(SummonSearchNode.CONF_SOLR_FACETS, "ContentType (" + tagCount + " ALPHA)");
SearchNode summon = new SummonSearchNode(conf);
ResponseCollection responses = new ResponseCollection();
Request request = new Request();
request.addJSON(JSON);
summon.search(request, responses);
List<String> tags = StringExtraction.getStrings(responses.toXML(), "<tag.+?>");
assertEquals("The number of returned tags should be " + tagCount + "+1. The returned Tags were\n"
+ Strings.join(tags, "\n"),
tagCount+1, tags.size());
summon.close();
}
public void testFacetSizeQuery() throws RemoteException {
int tagCount = 3;
final String JSON = "{\"search.document.query\":\"thinking\","
+ "\"search.document.collectdocids\":\"true\","
+ "\"search.facet.facets\":\"ContentType (" + tagCount + " ALPHA)\"}";
SearchNode summon = SummonTestHelper.createSummonSearchNode();
ResponseCollection responses = new ResponseCollection();
Request request = new Request();
request.addJSON(JSON);
summon.search(request, responses);
List<String> tags = StringExtraction.getStrings(responses.toXML(), "<tag.+?>");
assertEquals("The number of returned tags should be " + tagCount + "+1. The returned Tags were\n"
+ Strings.join(tags, "\n"),
tagCount + 1, tags.size());
summon.close();
}
public void testRecordBaseFacet() throws RemoteException {
final String JSON =
"{\"search.document.query\":\"darkmans barker\",\"search.document.collectdocids\":\"true\","
+ "\"solr.filterisfacet\":\"true\",\"solrparam.s.ho\":\"true\","
+ "\"search.document.filter\":\" recordBase:summon\"}";
SearchNode summon = SummonTestHelper.createSummonSearchNode();
ResponseCollection responses = new ResponseCollection();
Request request = new Request();
request.addJSON(JSON);
summon.search(request, responses);
assertTrue("The response should contain a summon tag from faceting\n" + responses.toXML(),
responses.toXML().contains("<tag name=\"summon\" addedobjects=\""));
summon.close();
}
public void testRecordBaseFacetWithOR() throws RemoteException {
final String JSON =
"{\"search.document.query\":\"darkmans barker\",\"search.document.collectdocids\":\"true\","
+ "\"solr.filterisfacet\":\"true\",\"solrparam.s.ho\":\"true\","
+ "\"search.document.filter\":\" recordBase:summon OR recordBase:sb_aleph\"}";
SearchNode summon = SummonTestHelper.createSummonSearchNode();
ResponseCollection responses = new ResponseCollection();
Request request = new Request();
request.addJSON(JSON);
summon.search(request, responses);
assertTrue("The response should contain a summon tag from faceting\n" + responses.toXML(),
responses.toXML().contains("<tag name=\"summon\" addedobjects=\""));
summon.close();
}
public void testBasicSearch() throws RemoteException {
log.debug("Creating SummonSearchNode");
SummonSearchNode summon = SummonTestHelper.createSummonSearchNode();
// summon.open(""); // Fake open for setting permits
ResponseCollection responses = new ResponseCollection();
Request request = new Request();
request.put(DocumentKeys.SEARCH_QUERY, "foo");
request.put(DocumentKeys.SEARCH_COLLECT_DOCIDS, true);
log.debug("Searching");
summon.search(request, responses);
log.debug("Finished searching");
//System.out.println(responses.toXML());
assertTrue("The result should contain at least one record", responses.toXML().contains("<record score"));
assertTrue("The result should contain at least one tag", responses.toXML().contains("<tag name"));
}
public void testMultiID() throws RemoteException {
List<String> IDs = Arrays.asList(
"FETCH-proquest_dll_11531932811",
"FETCH-proquest_dll_6357072911",
"FETCH-proquest_dll_15622214411"
);
SummonSearchNode searcher = SummonTestHelper.createSummonSearchNode(true);
for (String id: IDs) {
assertEquals("The number of hits for ID '" + id + "' should match", 1, getAttributes(searcher, new Request(
DocumentKeys.SEARCH_QUERY, "ID:\"" + id + "\"",
SummonSearchNode.SEARCH_PASSTHROUGH_QUERY, true
), "id", false).size());
}
String IDS_QUERY = "(ID:\"" + Strings.join(IDs, "\" OR ID:\"") + "\")";
Request req = new Request(
DocumentKeys.SEARCH_QUERY, IDS_QUERY,
SummonSearchNode.SEARCH_PASSTHROUGH_QUERY, true
);
List<String> returnedIDs = getAttributes(searcher, req, "id", false);
if (IDs.size() != returnedIDs.size()) {
ResponseCollection responses = new ResponseCollection();
searcher.search(req, responses);
System.out.println("Returned IDs: " + Strings.join(returnedIDs, ", "));
// System.out.println(responses.toXML());
}
assertEquals("There should be a result for each id from search '" + IDS_QUERY + "'",
IDs.size(), returnedIDs.size());
}
public void testShortFormat() throws RemoteException {
Configuration conf = SummonTestHelper.getDefaultSummonConfiguration();
conf.set(SummonResponseBuilder.CONF_SHORT_DATE, true);
log.debug("Creating SummonSearchNode");
SummonSearchNode summon = new SummonSearchNode(conf);
// summon.open(""); // Fake open for setting permits
final Pattern DATEPATTERN = Pattern.compile("<dc:date>(.+?)</dc:date>", Pattern.DOTALL);
Request request = new Request();
request.put(DocumentKeys.SEARCH_QUERY, "foo");
request.put(DocumentKeys.SEARCH_RESULT_FIELDS, "shortformat");
request.put(DocumentKeys.SEARCH_COLLECT_DOCIDS, true);
List<String> dates= getPattern(summon, request, DATEPATTERN, false);
assertTrue("There should be at least 1 extracted date", !dates.isEmpty());
for (String date: dates) {
assertTrue("the returned dates should be of length 4 or less, got '" + date + "'", date.length() <= 4);
}
// System.out.println("Got dates:\n" + Strings.join(dates, ", "));
}
public void testIDSearch() throws IOException, TransformerException {
String ID = "summon_FETCH-gale_primary_2105957371";
log.debug("Creating SummonSearchNode");
SearchNode summon = SummonTestHelper.createSummonSearchNode(true);
Request req = new Request(
DocumentKeys.SEARCH_QUERY, "recordID:\"" + ID + "\"",
DocumentKeys.SEARCH_MAX_RECORDS, 1,
DocumentKeys.SEARCH_COLLECT_DOCIDS, false);
List<String> ids = getAttributes(summon, req, "id", false);
assertTrue("There should be at least 1 result", ids.size() >= 1);
}
public void testGetField() throws IOException, TransformerException {
String ID = "summon_FETCH-gale_primary_2105957371";
log.debug("Creating SummonSearchNode");
SearchNode summon = SummonTestHelper.createSummonSearchNode(true);
String fieldName = "shortformat";
String field = getField(summon, ID, fieldName);
assertTrue("The field '" + fieldName + "' from ID '" + ID + "' should have content",
field != null && !"".equals(field));
// System.out.println("'" + field + "'");
}
/* This is equivalent to SearchWS#getField */
private String getField(SearchNode searcher, String id, String fieldName) throws IOException, TransformerException {
String retXML;
Request req = new Request();
req.put(DocumentKeys.SEARCH_QUERY, "ID:\"" + id + "\"");
req.put(DocumentKeys.SEARCH_MAX_RECORDS, 1);
req.put(DocumentKeys.SEARCH_COLLECT_DOCIDS, false);
ResponseCollection res = new ResponseCollection();
searcher.search(req, res);
// System.out.println(res.toXML());
Document dom = DOM.stringToDOM(res.toXML());
Node subDom = DOM.selectNode(
dom, "/responsecollection/response/documentresult/record/field[@name='" + fieldName + "']");
retXML = DOM.domToString(subDom);
return retXML;
}
public void testNonExistingFacet() throws RemoteException {
final Request request = new Request(
"search.document.query", "foo",
"search.document.filter", "Language:abcde32542f",
"search.document.collectdocids", "true",
"solr.filterisfacet", "true"
);
SummonSearchNode summon = SummonTestHelper.createSummonSearchNode();
ResponseCollection responses = new ResponseCollection();
log.debug("Searching");
summon.search(request, responses);
log.debug("Finished searching");
for (Response response : responses) {
if (response instanceof FacetResultExternal) {
FacetResultExternal facets = (FacetResultExternal)response;
for (Map.Entry<String, List<FacetResultImpl.Tag<String>>> entry: facets.getMap().entrySet()) {
assertEquals("The number of tags for facet '" + entry.getKey()
+ "' should be 0 as there should be no hits. First tag was '"
+ (entry.getValue().isEmpty() ? "N/A" : entry.getValue().get(0).getKey()) + "',",
0, entry.getValue().size());
}
}
}
}
public void testColonSearch() throws RemoteException {
final String OK = "FETCH-proquest_dll_14482952011";
final String PROBLEM = "FETCH-doaj_primary_oai:doaj-articles:932b6445ce452a2b2a544189863c472e1";
performSearch("ID:\"" + OK + "\"");
performSearch("ID:\"" + PROBLEM + "\"");
}
private void performSearch(String query) throws RemoteException {
log.debug("Creating SummonSearchNode");
SummonSearchNode summon = SummonTestHelper.createSummonSearchNode();
ResponseCollection responses = new ResponseCollection();
Request request = new Request();
request.put(DocumentKeys.SEARCH_QUERY, query);
request.put(DocumentKeys.SEARCH_COLLECT_DOCIDS, true);
log.debug("Searching");
summon.search(request, responses);
log.debug("Finished searching");
// System.out.println(responses.toXML());
assertTrue("The result should contain at least one record for query '" + query + "'",
responses.toXML().contains("<record score"));
}
public void testFacetOrder() throws RemoteException {
Configuration conf = SummonTestHelper.getDefaultSummonConfiguration();
conf.set(DocumentKeys.SEARCH_COLLECT_DOCIDS, true);
//SummonSearchNode.CONF_SOLR_FACETS, ""
log.debug("Creating SummonSearchNode");
SummonSearchNode summon = new SummonSearchNode(conf);
// summon.open(""); // Fake open for setting permits
ResponseCollection responses = new ResponseCollection();
Request request = new Request();
request.put(DocumentKeys.SEARCH_QUERY, "foo");
request.put(DocumentKeys.SEARCH_COLLECT_DOCIDS, true);
log.debug("Searching");
summon.search(request, responses);
log.debug("Finished searching");
List<String> facets = getFacetNames(responses);
List<String> expected = new ArrayList<String>(Arrays.asList(SummonSearchNode.DEFAULT_SUMMON_FACETS.split(" ?, ?")));
expected.add("recordBase"); // We always add this when we're doing faceting
for (int i = expected.size()-1 ; i >= 0 ; i--) {
if (!facets.contains(expected.get(i))) {
expected.remove(i);
}
}
assertEquals("The order of the facets should be correct",
Strings.join(expected, ", "), Strings.join(facets, ", "));
// System.out.println(responses.toXML());
// System.out.println(Strings.join(facets, ", "));
}
public void testSpecificFacets() throws RemoteException {
Configuration conf = SummonTestHelper.getDefaultSummonConfiguration();
conf.set(DocumentKeys.SEARCH_COLLECT_DOCIDS, true);
conf.set(SummonSearchNode.CONF_SOLR_FACETS, "SubjectTerms");
log.debug("Creating SummonSearchNode");
SummonSearchNode summon = new SummonSearchNode(conf);
ResponseCollection responses = new ResponseCollection();
Request request = new Request();
request.put(DocumentKeys.SEARCH_QUERY, "foo");
request.put(DocumentKeys.SEARCH_COLLECT_DOCIDS, true);
log.debug("Searching");
summon.search(request, responses);
log.debug("Finished searching");
List<String> facets = getFacetNames(responses);
assertEquals("The number of facets should be correct", 2, facets.size()); // 2 because of recordBase
assertEquals("The returned facet should be correct",
"SubjectTerms, recordBase", Strings.join(facets, ", "));
}
public void testFacetSortingCount() throws RemoteException {
Configuration conf = SummonTestHelper.getDefaultSummonConfiguration();
conf.set(DocumentKeys.SEARCH_COLLECT_DOCIDS, true);
conf.set(SummonSearchNode.CONF_SOLR_FACETS, "SubjectTerms");
assertFacetOrder(conf, false);
}
// Summon does not support index ordering of facets so we must cheat by over-requesting and post-processing
public void testFacetSortingAlpha() throws RemoteException {
Configuration conf = SummonTestHelper.getDefaultSummonConfiguration();
conf.set(DocumentKeys.SEARCH_COLLECT_DOCIDS, true);
conf.set(SummonSearchNode.CONF_SOLR_FACETS, "SubjectTerms(ALPHA)");
assertFacetOrder(conf, true);
}
private void assertFacetOrder(Configuration summonConf, boolean alpha) throws RemoteException {
log.debug("Creating SummonSearchNode");
SummonSearchNode summon = new SummonSearchNode(summonConf);
ResponseCollection responses = new ResponseCollection();
Request request = new Request();
request.put(DocumentKeys.SEARCH_QUERY, "foo");
request.put(DocumentKeys.SEARCH_COLLECT_DOCIDS, true);
log.debug("Searching");
summon.search(request, responses);
log.debug("Finished searching");
List<String> tags = getTags(responses, "SubjectTerms");
List<String> tagsAlpha = new ArrayList<String>(tags);
Collections.sort(tagsAlpha);
if (alpha) {
ExtraAsserts.assertEquals(
"The order should be alphanumeric\nExp: "
+ Strings.join(tagsAlpha, " ") + "\nAct: " + Strings.join(tags, " "),
tagsAlpha, tags);
} else {
boolean misMatch = false;
for (int i = 0 ; i < tags.size() ; i++) {
if (!tags.get(i).equals(tagsAlpha.get(i))) {
misMatch = true;
break;
}
}
if (!misMatch) {
fail("The order should not be alphanumeric but it was");
}
}
log.debug("Received facets with alpha=" + alpha + ": " + Strings.join(tags, ", "));
}
private List<String> getTags(ResponseCollection responses, String facet) {
List<String> result = new ArrayList<String>();
for (Response response: responses) {
if (response instanceof FacetResultExternal) {
FacetResultExternal facetResult = (FacetResultExternal)response;
List<FacetResultImpl.Tag<String>> tags = facetResult.getMap().get(facet);
for (FacetResultImpl.Tag<String> tag: tags) {
result.add(tag.getKey() + "(" + tag.getCount() + ")");
}
return result;
}
}
fail("Unable to locate a FacetResponse in the ResponseCollection");
return null;
}
public void testNegativeFacets() throws RemoteException {
final String QUERY = "foo fighters NOT limits NOT (boo OR bam)";
final String FACET = "SubjectTerms:\"united states\"";
SummonSearchNode summon = SummonTestHelper.createSummonSearchNode();
assertHits("There should be at least one hit for positive faceting",
summon,
DocumentKeys.SEARCH_QUERY, QUERY,
DocumentKeys.SEARCH_FILTER, FACET);
assertHits("There should be at least one hit for parenthesized positive faceting", summon,
DocumentKeys.SEARCH_QUERY, QUERY,
DocumentKeys.SEARCH_FILTER, "(" + FACET + ")");
assertHits("There should be at least one hit for filter with pure negative faceting", summon,
DocumentKeys.SEARCH_QUERY, QUERY,
DocumentKeys.SEARCH_FILTER_PURE_NEGATIVE, "true",
DocumentKeys.SEARCH_FILTER, "NOT " + FACET);
summon.close();
}
public void testFilterFacets() throws RemoteException {
final String QUERY = "foo fighters";
final String FACET = "SubjectTerms:\"united states\"";
final String FACET_NEG = "-SubjectTerms:\"united states\"";
SummonSearchNode summon = SummonTestHelper.createSummonSearchNode();
assertHits("There should be at least one hit for standard positive faceting",
summon,
DocumentKeys.SEARCH_QUERY, QUERY,
DocumentKeys.SEARCH_FILTER, FACET);
assertHits("There should be at least one hit for facet filter positive faceting",
summon,
DocumentKeys.SEARCH_QUERY, QUERY,
DocumentKeys.SEARCH_FILTER, FACET,
SummonSearchNode.SEARCH_SOLR_FILTER_IS_FACET, "true");
assertHits("There should be at least one hit for standard negative faceting",
summon,
DocumentKeys.SEARCH_QUERY, QUERY,
DocumentKeys.SEARCH_FILTER, FACET_NEG,
DocumentKeys.SEARCH_FILTER_PURE_NEGATIVE, "true");
assertHits("There should be at least one hit for facet filter negative faceting",
summon,
DocumentKeys.SEARCH_QUERY, QUERY,
DocumentKeys.SEARCH_FILTER, FACET_NEG,
SummonSearchNode.SEARCH_SOLR_FILTER_IS_FACET, "true");
summon.close();
}
// summon used to support pure negative filters (in 2011) but apparently does not with the 2.0.0-API.
// If they change their stance on the issue, we want to switch back to using pure negative filters, as it
// does not affect ranking.
public void testNegativeFacetsSupport() throws RemoteException {
final String QUERY = "foo fighters NOT limits NOT (boo OR bam)";
final String FACET = "SubjectTerms:\"united states\"";
Configuration conf = SummonTestHelper.getDefaultSummonConfiguration();
conf.set(SummonSearchNode.CONF_SUPPORTS_PURE_NEGATIVE_FILTERS, true);
SummonSearchNode summon = new SummonSearchNode(conf);
assertEquals("There should be zero hits for filter with assumed pure negative faceting support", 0,
getHits(summon,
DocumentKeys.SEARCH_QUERY, QUERY,
DocumentKeys.SEARCH_FILTER_PURE_NEGATIVE, "true",
DocumentKeys.SEARCH_FILTER, "NOT " + FACET));
summon.close();
}
public void testQueryWithNegativeFacets() throws RemoteException {
final String QUERY = "foo";
final String FACET = "SubjectTerms:\"analysis\"";
SummonSearchNode summon = SummonTestHelper.createSummonSearchNode();
assertHits("There should be at least one hit for positive faceting", summon,
DocumentKeys.SEARCH_QUERY, QUERY,
DocumentKeys.SEARCH_FILTER, FACET);
assertHits("There should be at least one hit for query with negative facet", summon,
DocumentKeys.SEARCH_QUERY, QUERY,
DocumentKeys.SEARCH_FILTER_PURE_NEGATIVE, Boolean.TRUE.toString(),
DocumentKeys.SEARCH_FILTER, "NOT " + FACET);
summon.close();
}
public void testSortedSearch() throws RemoteException {
Configuration conf = SummonTestHelper.getDefaultSummonConfiguration();
conf.set(InteractionAdjuster.CONF_ADJUST_DOCUMENT_FIELDS, "sort_year_asc - PublicationDate");
log.debug("Creating SummonSearchNode");
SummonSearchNode summon = new SummonSearchNode(conf);
// summon.open(""); // Fake open for setting permits
ResponseCollection responses = new ResponseCollection();
Request request = new Request();
request.put(DocumentKeys.SEARCH_QUERY, "sb");
request.put(DocumentKeys.SEARCH_SORTKEY, "PublicationDate");
// request.put(DocumentKeys.SEARCH_REVERSE, true);
request.put(DocumentKeys.SEARCH_COLLECT_DOCIDS, true);
log.debug("Searching");
summon.search(request, responses);
log.debug("Finished searching");
List<String> sortValues = getAttributes(summon, request, "sortValue", true);
String lastValue = null;
for (String sortValue: sortValues) {
assertTrue("The sort values should be in unicode order but was " + Strings.join(sortValues, ", "),
lastValue == null || lastValue.compareTo(sortValue) <= 0);
// System.out.println(lastValue + " vs " + sortValue + ": " + (lastValue == null ? 0 : lastValue.compareTo(sortValue)));
lastValue = sortValue;
}
log.debug("Test passed with sort values\n" + Strings.join(sortValues, "\n"));
}
public void testSortedDate() throws RemoteException {
Configuration conf = SummonTestHelper.getDefaultSummonConfiguration();
conf.set(InteractionAdjuster.CONF_ADJUST_DOCUMENT_FIELDS, "sort_year_asc - PublicationDate");
log.debug("Creating SummonSearchNode");
SummonSearchNode summon = new SummonSearchNode(conf);
// summon.open(""); // Fake open for setting permits
Request request = new Request();
request.put(DocumentKeys.SEARCH_QUERY, "dolphin whale");
request.put(DocumentKeys.SEARCH_SORTKEY, "PublicationDate");
// request.put(DocumentKeys.SEARCH_REVERSE, true);
request.put(DocumentKeys.SEARCH_COLLECT_DOCIDS, true);
log.debug("Searching");
List<String> fields = getField(summon, request, "PublicationDate_xml_iso");
log.debug("Finished searching");
String lastValue = null;
for (String sortValue: fields) {
assertTrue("The field values should be in unicode order but was " + Strings.join(fields, ", "),
lastValue == null || lastValue.compareTo(sortValue) <= 0);
// System.out.println(lastValue + " vs " + sortValue + ": " + (lastValue == null ? 0 : lastValue.compareTo(sortValue)));
lastValue = sortValue;
}
log.debug("Test passed with field values\n" + Strings.join(fields, "\n"));
}
public void testFacetedSearchNoFaceting() throws Exception {
assertSomeHits(new Request(
DocumentKeys.SEARCH_QUERY, "first"
));
}
public void testFacetedSearchNoHits() throws Exception {
Request request = new Request(
DocumentKeys.SEARCH_FILTER, "recordBase:nothere",
DocumentKeys.SEARCH_QUERY, "first"
);
ResponseCollection responses = search(request);
assertTrue("There should be a response", responses.iterator().hasNext());
assertEquals("There should be no hits. Response was\n" + responses.toXML(),
0, ((DocumentResponse) responses.iterator().next()).getHitCount());
}
public void testFacetedSearchSomeHits() throws Exception {
assertSomeHits(new Request(
DocumentKeys.SEARCH_FILTER, "recordBase:summon",
DocumentKeys.SEARCH_QUERY, "first"
));
}
private void assertSomeHits(Request request) throws RemoteException {
ResponseCollection responses = search(request);
assertTrue("There should be a response", responses.iterator().hasNext());
assertTrue("There should be some hits. Response was\n" + responses.toXML(),
((DocumentResponse) responses.iterator().next()).getHitCount() > 0);
}
private ResponseCollection search(Request request) throws RemoteException {
SearchNode searcher = SummonTestHelper.createSummonSearchNode();
try {
ResponseCollection responses = new ResponseCollection();
searcher.search(request, responses);
return responses;
} finally {
searcher.close();
}
}
public void testSortedSearchRelevance() throws RemoteException {
Configuration conf = SummonTestHelper.getDefaultSummonConfiguration();
conf.set(InteractionAdjuster.CONF_ADJUST_DOCUMENT_FIELDS, "sort_year_asc - PublicationDate");
log.debug("Creating SummonSearchNode");
SummonSearchNode summon = new SummonSearchNode(conf);
// summon.open(""); // Fake open for setting permits
ResponseCollection responses = new ResponseCollection();
Request request = new Request();
request.put(DocumentKeys.SEARCH_QUERY, "foo");
request.put(DocumentKeys.SEARCH_SORTKEY, DocumentKeys.SORT_ON_SCORE);
request.put(DocumentKeys.SEARCH_COLLECT_DOCIDS, true);
log.debug("Searching");
summon.search(request, responses);
log.debug("Finished searching");
List<String> ids = getAttributes(summon, request, "id", false);
assertTrue("There should be some hits", !ids.isEmpty());
}
public void testPaging() throws RemoteException {
SummonSearchNode summon = SummonTestHelper.createSummonSearchNode();
// summon.open(""); // Fake open for setting permits
List<String> ids0 = getAttributes(
summon, new Request(
DocumentKeys.SEARCH_QUERY, "foo",
DocumentKeys.SEARCH_MAX_RECORDS, 20,
DocumentKeys.SEARCH_START_INDEX, 0),
"id", false);
List<String> ids1 = getAttributes(
summon, new Request(
DocumentKeys.SEARCH_QUERY, "foo",
DocumentKeys.SEARCH_MAX_RECORDS, 20,
DocumentKeys.SEARCH_START_INDEX, 20),
"id", false);
assertNotEquals("The hits should differ from page 0 and 1",
Strings.join(ids0, ", "), Strings.join(ids1, ", "));
}
private void assertNotEquals(String message, String expected, String actual) {
assertFalse(message + ".\nExpected: " + expected + "\nActual: " + actual,
expected.equals(actual));
}
private List<String> getAttributes(
SearchNode searcher, Request request, String attributeName, boolean explicitMerge) throws RemoteException {
final Pattern IDPATTERN = Pattern.compile("<record.*?" + attributeName + "=\"(.+?)\".*?>", Pattern.DOTALL);
return getPattern(searcher, request, IDPATTERN, explicitMerge);
/* ResponseCollection responses = new ResponseCollection();
searcher.search(request, responses);
responses.iterator().next().merge(responses.iterator().next());
String[] lines = responses.toXML().split("\n");
List<String> result = new ArrayList<String>();
for (String line: lines) {
Matcher matcher = IDPATTERN.matcher(line);
if (matcher.matches()) {
result.add(matcher.group(1));
}
}
return result;*/
}
private List<String> getField(SearchNode searcher, Request request, String fieldName) throws RemoteException {
final Pattern IDPATTERN = Pattern.compile(
"<field name=\"" + fieldName + "\">(.+?)</field>", Pattern.DOTALL);
return getPattern(searcher, request, IDPATTERN, false);
}
private List<String> getFacetNames(ResponseCollection responses) {
Pattern FACET = Pattern.compile(".*<facet name=\"(.+?)\">");
List<String> result = new ArrayList<String>();
String[] lines = responses.toXML().split("\n");
for (String line : lines) {
Matcher matcher = FACET.matcher(line);
if (matcher.matches()) {
result.add(matcher.group(1));
}
}
return result;
}
private List<String> getPattern(
SearchNode searcher, Request request, Pattern pattern, boolean explicitMerge) throws RemoteException {
ResponseCollection responses = new ResponseCollection();
searcher.search(request, responses);
if (explicitMerge) {
responses.iterator().next().merge(responses.iterator().next());
}
String xml = responses.toXML();
Matcher matcher = pattern.matcher(xml);
List<String> result = new ArrayList<String>();
while (matcher.find()) {
result.add(Strings.join(matcher.group(1).split("\n"), ", "));
}
return result;
}
public void testRecommendations() throws RemoteException {
SummonSearchNode summon = SummonTestHelper.createSummonSearchNode();
ResponseCollection responses = new ResponseCollection();
Request request = new Request();
request.put(DocumentKeys.SEARCH_QUERY, "PublicationTitle:jama");
// request.put(DocumentKeys.SEARCH_QUERY, "+(PublicationTitle:jama OR PublicationTitle:jama) +(ContentType:Article OR ContentType:\"Book Chapter\" OR ContentType:\"Book Review\" OR ContentType:\"Journal Article\" OR ContentType:\"Magazine Article\" OR ContentType:Newsletter OR ContentType:\"Newspaper Article\" OR ContentType:\"Publication Article\" OR ContentType:\"Trade Publication Article\")");
/*
\+\(PublicationTitle:jama\ OR\ PublicationTitle:jama\)\ \+\(ContentType:Article\ OR\ ContentType:\"Book\ Chapter\"\ OR\ ContentType:\"Book\ Review\"\ OR\ ContentType:\"Journal\ Article\"\ OR\ ContentType:\"Magazine\ Article\"\ OR\ ContentType:Newsletter\ OR\ ContentType:\"Newspaper\ Article\"\ OR\ ContentType:\"Publication\ Article\"\ OR\ ContentType:\"Trade\ Publication\ Article\"\)
*/
request.put(DocumentKeys.SEARCH_COLLECT_DOCIDS, true);
summon.search(request, responses);
// System.out.println(responses.toXML());
assertTrue("The result should contain at least one recommendation",
responses.toXML().contains("<recommendation "));
/* responses.clear();
request.put(DocumentKeys.SEARCH_QUERY, "noobddd");
summon.search(request, responses);
System.out.println(responses.toXML());
*/
}
public void testReportedTiming() throws RemoteException {
SummonSearchNode summon = SummonTestHelper.createSummonSearchNode();
ResponseCollection responses = new ResponseCollection();
Request request = new Request();
request.put(DocumentKeys.SEARCH_QUERY, "foo");
summon.search(request, responses);
Integer rawTime = getTiming(responses, "summon.rawcall");
assertNotNull("There should be raw time", rawTime);
Integer reportedTime = getTiming(responses, "summon.reportedtime");
assertNotNull("There should be reported time", reportedTime);
assertTrue("The reported time (" + reportedTime + ") should be lower than the raw time (" + rawTime + ")",
reportedTime <= rawTime);
log.debug("Timing raw=" + rawTime + ", reported=" + reportedTime);
}
private Integer getTiming(ResponseCollection responses, String key) {
String[] timings = responses.getTiming().split("[|]");
for (String timing: timings) {
String[] tokens = timing.split(":");
if (tokens.length == 2 && key.equals(tokens[0])) {
return Integer.parseInt(tokens[1]);
}
}
return null;
}
public void testFilterVsQuery() throws RemoteException {
SummonSearchNode summon = SummonTestHelper.createSummonSearchNode();
long qHitCount = getHits(summon,
DocumentKeys.SEARCH_QUERY, "PublicationTitle:jama",
SummonSearchNode.SEARCH_PASSTHROUGH_QUERY, "true");
long fHitCount = getHits(summon,
DocumentKeys.SEARCH_FILTER, "PublicationTitle:jama",
SummonSearchNode.SEARCH_PASSTHROUGH_QUERY, "true");
assertTrue("The filter hit count " + fHitCount + " should differ from query hit count " + qHitCount
+ " by less than 100",
Math.abs(fHitCount - qHitCount) < 100);
}
public void testFilterVsQuery2() throws RemoteException {
SummonSearchNode summon = SummonTestHelper.createSummonSearchNode();
long qHitCount = getHits(
summon,
DocumentKeys.SEARCH_QUERY, "PublicationTitle:jama",
DocumentKeys.SEARCH_FILTER, "old");
long fHitCount = getHits(
summon,
DocumentKeys.SEARCH_FILTER, "PublicationTitle:jama",
DocumentKeys.SEARCH_QUERY, "old");
assertTrue("The filter(old) hit count " + fHitCount + " should differ less than 100 from query(old) hit count "
+ qHitCount + " as summon API 2.0.0 does field expansion on filters",
Math.abs(fHitCount - qHitCount) < 100);
// This was only true in the pre-API 2.0.0. Apparently the new API does expands default fields for filters
// assertTrue("The filter(old) hit count " + fHitCount + " should differ from query(old) hit count " + qHitCount
// + " by more than 100 as filter query apparently does not query parse with default fields",
// Math.abs(fHitCount - qHitCount) > 100);
}
public void testDismaxAnd() throws RemoteException {
String QUERY1 = "public health policy";
String QUERY2 = "alternative medicine";
//String QUERY = "work and life balance";
//String QUERY = "Small business and Ontario";
SummonSearchNode summon = SummonTestHelper.createSummonSearchNode();
List<String> titlesLower = getField(summon, new Request(
DocumentKeys.SEARCH_QUERY, QUERY1 + " and " + QUERY2,
SummonSearchNode.SEARCH_PASSTHROUGH_QUERY, true,
SummonSearchNode.SEARCH_DISMAX_SABOTAGE, false
), "Title");
String lower = Strings.join(titlesLower, "\n").replace("<h>", "").replace("</h>", "");
List<String> titlesUpper = getField(summon, new Request(
DocumentKeys.SEARCH_QUERY, QUERY1 + " AND " + QUERY2,
SummonSearchNode.SEARCH_PASSTHROUGH_QUERY, true,
SummonSearchNode.SEARCH_DISMAX_SABOTAGE, false
), "Title");
String upper = Strings.join(titlesUpper, "\n").replace("<h>", "").replace("</h>", "");
summon.close();
if (lower.equals(upper)) {
fail("Using 'and' and 'AND' should not yield the same result\n" + lower);
} else {
System.out.println("Using 'and' and 'AND' gave different results:\nand: " +
lower.replace("\n", ", ") + "\nAND: " + upper.replace("\n", ", "));
}
}
public void testDismaxWithQuoting() throws RemoteException {
String QUERY = "public health policy and alternative medicine";
SummonSearchNode summon = SummonTestHelper.createSummonSearchNode();
List<String> titlesRaw = getField(summon, new Request(
DocumentKeys.SEARCH_QUERY, QUERY,
SummonSearchNode.SEARCH_PASSTHROUGH_QUERY, true,
SummonSearchNode.SEARCH_DISMAX_SABOTAGE, false
), "Title");
String raw = Strings.join(titlesRaw, "\n").replace("<h>", "").replace("</h>", "");
List<String> titlesQuoted = getField(summon, new Request(
DocumentKeys.SEARCH_QUERY, QUERY,
SummonSearchNode.SEARCH_PASSTHROUGH_QUERY, false, // Adds quotes around individual terms
SummonSearchNode.SEARCH_DISMAX_SABOTAGE, false
), "Title");
String quoted = Strings.join(titlesQuoted, "\n").replace("<h>", "").replace("</h>", "");
List<String> titlesNonDismaxed = getField(summon, new Request(
DocumentKeys.SEARCH_QUERY, "(" + QUERY + ")",
SummonSearchNode.SEARCH_PASSTHROUGH_QUERY, false, // Adds quotes around individual terms
SummonSearchNode.SEARCH_DISMAX_SABOTAGE, false
), "Title");
String nonDismaxed = Strings.join(titlesNonDismaxed, "\n").replace("<h>", "").replace("</h>", "");
summon.close();
System.out.println("raw " + (raw.equals(quoted) ? "=" : "!") + "= quoted");
System.out.println("raw " + (raw.equals(nonDismaxed) ? "=" : "!") + "= parenthesized");
System.out.println("quoted " + (quoted.equals(nonDismaxed) ? "=" : "!") + "= parenthesized");
System.out.println("raw = " + raw.replace("\n", ", "));
System.out.println("quoted = " + quoted.replace("\n", ", "));
System.out.println("parenthesized = " + nonDismaxed.replace("\n", ", "));
assertEquals("The result from the raw (and thus dismaxed) query should match the result from "
+ "the quoted terms query",
raw, quoted);
}
public void testFilterVsQuery3() throws RemoteException {
SummonSearchNode summon = SummonTestHelper.createSummonSearchNode();
long qCombinedHitCount = getHits(
summon,
DocumentKeys.SEARCH_QUERY,
"PublicationTitle:jama AND Language:English");
long qHitCount = getHits(
summon,
DocumentKeys.SEARCH_QUERY, "PublicationTitle:jama",
DocumentKeys.SEARCH_FILTER, "(Language:English)");
long fHitCount = getHits(
summon,
DocumentKeys.SEARCH_FILTER, "PublicationTitle:jama",
DocumentKeys.SEARCH_QUERY, "Language:English");
assertTrue("The filter(old) hit count " + fHitCount + " should differ"
+ " from query(old) hit count " + qHitCount
+ " by less than 100. Combined hit count for query is "
+ qCombinedHitCount,
Math.abs(fHitCount - qHitCount) < 100);
}
public void testCustomParams() throws RemoteException {
final String QUERY = "reactive arthritis yersinia lassen";
Configuration confInside = SummonTestHelper.getDefaultSummonConfiguration();
Configuration confOutside = SummonTestHelper.getDefaultSummonConfiguration();
confOutside.set(SummonSearchNode.CONF_SOLR_PARAM_PREFIX + "s.ho",
new ArrayList<String>(Arrays.asList("false"))
);
Request request = new Request();
request.put(DocumentKeys.SEARCH_QUERY, QUERY);
request.put(DocumentKeys.SEARCH_COLLECT_DOCIDS, true);
SummonSearchNode summonInside = new SummonSearchNode(confInside);
ResponseCollection responsesInside = new ResponseCollection();
summonInside.search(request, responsesInside);
SummonSearchNode summonOutside = new SummonSearchNode(confOutside);
ResponseCollection responsesOutside = new ResponseCollection();
summonOutside.search(request, responsesOutside);
request.put(SummonSearchNode.CONF_SOLR_PARAM_PREFIX + "s.ho",
new ArrayList<String>(Arrays.asList("false")));
ResponseCollection responsesSearchTweak = new ResponseCollection();
summonInside.search(request, responsesSearchTweak);
int countInside = countResults(responsesInside);
int countOutside = countResults(responsesOutside);
assertTrue("The number of results for a search for '" + QUERY + "' within holdings (" + confInside
+ ") should be less that outside holdings (" + confOutside + ")",
countInside < countOutside);
log.info(String.format("The search for '%s' gave %d hits within holdings and %d hits in total",
QUERY, countInside, countOutside));
int countSearchTweak = countResults(responsesSearchTweak);
assertEquals(
"Query time specification of 's.ho=false' should give the same "
+ "result as configuration time specification of the same",
countOutside, countSearchTweak);
}
public void testConvertRangeQueries() throws RemoteException {
final String QUERY = "foo bar:[10 TO 20] OR baz:[87 TO goa]";
Map<String, List<String>> params = new HashMap<String, List<String>>();
String stripped = new SummonSearchNode(getSummonConfiguration()).convertQuery(QUERY, params);
assertNotNull("RangeFilter should be defined", params.get("s.rf"));
List<String> ranges = params.get("s.rf");
assertEquals("The right number of ranges should be extracted", 2, ranges.size());
assertEquals("Range #1 should be correct", "bar,10:20", ranges.get(0));
assertEquals("Range #2 should be correct", "baz,87:goa", ranges.get(1));
assertEquals("The resulting query should be stripped of ranges", "\"foo\"", stripped);
}
public void testConvertRangeQueriesEmpty() throws RemoteException {
final String QUERY = "bar:[10 TO 20]";
Map<String, List<String>> params = new HashMap<String, List<String>>();
String stripped = new SummonSearchNode(getSummonConfiguration()).convertQuery(QUERY, params);
assertNotNull("RangeFilter should be defined", params.get("s.rf"));
List<String> ranges = params.get("s.rf");
assertEquals("The right number of ranges should be extracted", 1, ranges.size());
assertEquals("Range #1 should be correct", "bar,10:20", ranges.get(0));
assertNull("The resulting query should be null", stripped);
}
private Configuration getSummonConfiguration() {
return Configuration.newMemoryBased(
SummonSearchNode.CONF_SUMMON_ACCESSID, "foo",
SummonSearchNode.CONF_SUMMON_ACCESSKEY, "bar");
}
public void testFaultyQuoteRemoval() throws RemoteException {
final String QUERY = "bar:\"foo:zoo\"";
Map<String, List<String>> params = new HashMap<String, List<String>>();
String stripped = new SummonSearchNode(getSummonConfiguration()).convertQuery(QUERY, params);
assertNull("RangeFilter should not be defined", params.get("s.rf"));
assertEquals("The resulting query should unchanged", QUERY, stripped);
}
// This fails, but as we are really testing Summon here, there is not much
// we can do about it
@SuppressWarnings({"UnusedDeclaration"})
public void disabledtestCounts() throws RemoteException {
// final String QUERY = "reactive arthritis yersinia lassen";
final String QUERY = "author:(Helweg Larsen) abuse";
Request request = new Request();
request.addJSON(
"{search.document.query:\"" + QUERY + "\", summonparam.s.ps:\"15\", summonparam.s.ho:\"false\"}");
// String r1 = request.toString(true);
SummonSearchNode summon = SummonTestHelper.createSummonSearchNode();
ResponseCollection responses = new ResponseCollection();
summon.search(request, responses);
int count15 = countResults(responses);
request.clear();
request.addJSON(
"{search.document.query:\"" + QUERY + "\", summonparam.s.ps:\"30\", summonparam.s.ho:\"false\"}");
// String r2 = request.toString(true);
responses.clear();
summon.search(request, responses);
int count20 = countResults(responses);
/*
request.clear();
request.put(DocumentKeys.SEARCH_QUERY, QUERY);
request.put(DocumentKeys.SEARCH_COLLECT_DOCIDS, false);
request.put(SummonSearchNode.CONF_SOLR_PARAM_PREFIX + "s.ho",
new ArrayList<String>(Arrays.asList("false")));
request.put(DocumentKeys.SEARCH_MAX_RECORDS, 15);
String rOld15 = request.toString(true);
responses.clear();
summon.search(request, responses);
int countOld15 = countResults(responses);
request.clear();
request.put(DocumentKeys.SEARCH_QUERY, QUERY);
request.put(DocumentKeys.SEARCH_COLLECT_DOCIDS, false);
request.put(SummonSearchNode.CONF_SOLR_PARAM_PREFIX + "s.ho",
new ArrayList<String>(Arrays.asList("false")));
request.put(DocumentKeys.SEARCH_MAX_RECORDS, 20);
String rOld20 = request.toString(true);
responses.clear();
summon.search(request, responses);
int countOld20 = countResults(responses);
*/
// System.out.println("Request 15: " + r1 + ": " + count15);
// System.out.println("Request 20: " + r2 + ": " + count20);
// System.out.println("Request O15: " + rOld15 + ": " + countOld15);
// System.out.println("Request O20: " + rOld20 + ": " + countOld20);
assertEquals("The number of hits should not be affected by page size", count15, count20);
}
// Author can be returned in the field Author_xml (primary) and Author (secondary). If both fields are present,
// Author should be ignored.
public void testAuthorExtraction() throws IOException {
}
private int countResults(ResponseCollection responses) {
for (Response response: responses) {
if (response instanceof DocumentResponse) {
return (int)((DocumentResponse)response).getHitCount();
}
}
throw new IllegalArgumentException(
"No documentResponse in ResponseCollection");
}
public void testAdjustingSearcher() throws IOException {
SimplePair<String, String> credentials = SummonTestHelper.getCredentials();
Configuration conf = Configuration.newMemoryBased(
InteractionAdjuster.CONF_IDENTIFIER, "summon",
InteractionAdjuster.CONF_ADJUST_DOCUMENT_FIELDS, "recordID - ID");
Configuration inner = conf.createSubConfiguration(AdjustingSearchNode.CONF_INNER_SEARCHNODE);
inner.set(SearchNodeFactory.CONF_NODE_CLASS, SummonSearchNode.class.getCanonicalName());
inner.set(SummonSearchNode.CONF_SUMMON_ACCESSID, credentials.getKey());
inner.set(SummonSearchNode.CONF_SUMMON_ACCESSKEY, credentials.getValue());
log.debug("Creating adjusting SummonSearchNode");
AdjustingSearchNode adjusting = new AdjustingSearchNode(conf);
ResponseCollection responses = new ResponseCollection();
Request request = new Request(
//request.put(DocumentKeys.SEARCH_QUERY, "foo");
DocumentKeys.SEARCH_QUERY, "recursion in string theory",
DocumentKeys.SEARCH_COLLECT_DOCIDS, true);
log.debug("Searching");
adjusting.search(request, responses);
log.debug("Finished searching");
// TODO: Add proper test
// System.out.println(responses.toXML());
}
public void testExplicitMust() throws IOException {
final String QUERY = "miller genre as social action";
ResponseCollection explicitMustResponses = new ResponseCollection();
{
Configuration conf = SummonTestHelper.getDefaultSummonConfiguration();
conf.set(QueryRewriter.CONF_TERSE, false);
SearchNode summon = new SummonSearchNode(conf);
Request request = new Request(
DocumentKeys.SEARCH_QUERY, QUERY
);
summon.search(request, explicitMustResponses);
summon.close();
}
ResponseCollection implicitMustResponses = new ResponseCollection();
{
Configuration conf = SummonTestHelper.getDefaultSummonConfiguration();
conf.set(QueryRewriter.CONF_TERSE, true);
SearchNode summon = new SummonSearchNode(conf);
Request request = new Request(
DocumentKeys.SEARCH_QUERY, QUERY
);
summon.search(request, implicitMustResponses);
summon.close();
}
HarmoniseTestHelper.compareHits(QUERY, false, explicitMustResponses, implicitMustResponses);
}
/*
Tests if explicit weight-adjustment of terms influences the scores significantly.
*/
public void testExplicitWeightScoring() throws RemoteException {
assertScores("dolphin whales", "dolphin whales^1.000001", 10.0f);
}
/*
Tests if explicit weight-adjustment of terms influences the order of documents.
*/
public void testExplicitWeightOrder() throws RemoteException {
assertOrder("dolphin whales", "dolphin whales^1.0");
}
public void testExplicitWeightOrderSingleTerm() throws RemoteException {
assertOrder("whales", "whales^1.0");
}
public void testExplicitWeightOrderFoo() throws RemoteException {
assertOrder("foo", "foo^1.0"); // By some funny coincidence, foo works when whales doesn't
}
private void assertOrder(String query1, String query2) throws RemoteException {
SearchNode summon = SummonTestHelper.createSummonSearchNode();
try {
List<String> ids1 = getAttributes(summon, new Request(
DocumentKeys.SEARCH_QUERY, query1,
SummonSearchNode.SEARCH_PASSTHROUGH_QUERY, true
), "id", false);
List<String> ids2 = getAttributes(summon, new Request(
DocumentKeys.SEARCH_QUERY, query2,
SummonSearchNode.SEARCH_PASSTHROUGH_QUERY, true
), "id", false);
ExtraAsserts.assertPermutations("Query '" + query1 + "' and '" + query2 + "'", ids1, ids2);
/* assertEquals("The number of hits for '" + query1 + "' and '" + query2 + "' should be equal",
ids1.size(), ids2.size());
assertEquals("The document order for '" + query1 + "' and '" + query2 + "' should be equal",
Strings.join(ids1, ", "), Strings.join(ids2, ", "));
*/
} finally {
summon.close();
}
}
public void testDisMaxDisabling() throws RemoteException {
final String QUERY= "asian philosophy";
SearchNode summon = SummonTestHelper.createSummonSearchNode();
try {
long plainCount =
getHits(summon, DocumentKeys.SEARCH_QUERY, QUERY, SummonSearchNode.SEARCH_DISMAX_SABOTAGE, "false");
long sabotagedCount =
getHits(summon, DocumentKeys.SEARCH_QUERY, QUERY, SummonSearchNode.SEARCH_DISMAX_SABOTAGE, "true");
assertEquals("The number of hits for a DisMax-enabled and DisMax-sabotages query should match",
plainCount, sabotagedCount);
List<String> plain = getAttributes(summon, new Request(
DocumentKeys.SEARCH_QUERY, QUERY, SummonSearchNode.SEARCH_DISMAX_SABOTAGE, false), "id", false);
List<String> sabotaged = getAttributes(summon, new Request(
DocumentKeys.SEARCH_QUERY, QUERY, SummonSearchNode.SEARCH_DISMAX_SABOTAGE, true), "id", false);
assertFalse("The ids returned by DisMax-enabled and DisMax-sabotaged query should differ",
Strings.join(plain, ", ").equals(Strings.join(sabotaged, ", ")));
} finally {
summon.close();
}
}
public void testDismaxDisablingExperiment() throws RemoteException {
assertOrder("foo bar", "(foo bar)");
}
/*
Tests if quoting of terms influences the scores significantly.
*/
public void testQuotingScoring() throws RemoteException {
assertScores("dolphin whales", "\"dolphin\" \"whales\"", 10.0f);
}
private void assertScores(String query1, String query2, float maxDifference) throws RemoteException {
SearchNode summon = SummonTestHelper.createSummonSearchNode();
ResponseCollection raw = new ResponseCollection();
summon.search(new Request(
DocumentKeys.SEARCH_QUERY, query1,
SolrSearchNode.SEARCH_PASSTHROUGH_QUERY, true
), raw);
ResponseCollection weighted = new ResponseCollection();
summon.search(new Request(DocumentKeys.SEARCH_QUERY, query2), weighted);
summon.close();
List<Double> rawScores = getScores(raw);
List<Double> weightedScores = getScores(weighted);
assertEquals("The number of hits for '" + query1 + "' and '" + query2 + "' should be equal",
rawScores.size(), weightedScores.size());
for (int i = 0 ; i < rawScores.size() ; i++) {
assertTrue(String.format(
"The scores at position %d were %s and %s. Max difference allowed is %s. "
+ "All scores for '%s' and '%s':\n%s\n%s",
i, rawScores.get(i), weightedScores.get(i), maxDifference,
query1, query2, Strings.join(rawScores, ", "), Strings.join(weightedScores, ", ")),
Math.abs(rawScores.get(i) - weightedScores.get(i)) <= maxDifference);
}
}
private List<Double> getScores(ResponseCollection responses) {
DocumentResponse docs = (DocumentResponse)responses.iterator().next();
List<Double> result = new ArrayList<Double>(docs.size());
for (DocumentResponse.Record record: docs.getRecords()) {
result.add((double)record.getScore());
}
return result;
}
// Author_xml contains the authoritative order for the authors so it should override the non-XML-version
public void testAuthor_xmlExtraction() throws RemoteException {
String fieldName = "Author";
String query = "PQID:821707502";
/* {
Configuration conf = SummonTestHelper.getDefaultSummonConfiguration();
conf.set(SummonResponseBuilder.CONF_XML_OVERRIDES_NONXML, false);
SearchNode summon = new SummonSearchNode(conf);
ResponseCollection responses = new ResponseCollection();
summon.search(new Request(DocumentKeys.SEARCH_QUERY, query), responses);
DocumentResponse docs = (DocumentResponse)responses.iterator().next();
for (DocumentResponse.Record record: docs.getRecords()) {
System.out.println("\n" + record.getId());
String author = "";
String author_xml = "";
for (DocumentResponse.Field field: record.getFields()) {
if ("Author".equals(field.getName())) {
author = field.getContent().replace("\n", ", ").replace("<h>", "").replace("</h>", "");
System.out.println("Author: " + author);
} else if ("Author_xml".equals(field.getName())) {
author_xml = field.getContent().replace("\n", ", ");
System.out.println("Author_xml: " + author_xml);
} else if ("PQID".equals(field.getName())) {
System.out.println("PQID: " + field.getContent());
}
}
if (author.length() != author_xml.length()) {
fail("We finally found a difference between Author and Author_xml besides name ordering");
}
}
summon.close();
}
*/
{ // Old behaviour
String expected = "Koetse, Willem\n"
+ "Krebs, Christopher P\n"
+ "Lindquist, Christine\n"
+ "Lattimore, Pamela K\n"
+ "Cowell, Alex J";
Configuration conf = SummonTestHelper.getDefaultSummonConfiguration();
conf.set(SummonResponseBuilder.CONF_XML_OVERRIDES_NONXML, false);
SearchNode summonNonXML = new SummonSearchNode(conf);
assertFieldContent("XML no override", summonNonXML, query, fieldName, expected, false);
summonNonXML.close();
}
{ // New behaviour
String expected = "Lattimore, Pamela K\n"
+ "Krebs, Christopher P\n"
+ "Koetse, Willem\n"
+ "Lindquist, Christine\n"
+ "Cowell, Alex J";
SearchNode summonXML = SummonTestHelper.createSummonSearchNode();
assertFieldContent("XML override", summonXML, query, fieldName, expected, false);
summonXML.close();
}
}
public void testAuthor_xmlExtraction_shortformat() throws RemoteException {
String query = "ID:FETCH-LOGICAL-c937-88b9adcf681a925445118c26ea8da2ed792f182b51857048dbb48b11a133ea321";
{ // sanity-check the Author-field
String expected = "Ferlay, Jacques\n"
+ "Shin, Hai-Rim\n"
+ "Bray, Freddie\n"
+ "Forman, David\n"
+ "Mathers, Colin\n"
+ "Parkin, Donald Maxwell";
SearchNode summon = SummonTestHelper.createSummonSearchNode();
assertFieldContent("author direct", summon, query, "Author", expected, false);
summon.close();
}
{ // shortformat should match Author
String expected =
" <shortrecord>\n"
+ " <rdf:RDF xmlns:dc=\"http://purl.org/dc/elements/1.1/\" "
+ "xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n"
+ " <rdf:Description>\n"
+ " <dc:title>Estimates of worldwide burden of cancer in 2008: GLOBOCAN 2008</dc:title>\n"
+ " <dc:creator>Ferlay, Jacques</dc:creator>\n"
+ " <dc:creator>Shin, Hai-Rim</dc:creator>\n"
+ " <dc:creator>Bray, Freddie</dc:creator>\n"
+ " <dc:creator>Forman, David</dc:creator>\n"
+ " <dc:creator>Mathers, Colin</dc:creator>\n"
+ " <dc:creator>Parkin, Donald Maxwell</dc:creator>\n"
+ " <dc:type xml:lang=\"da\">Journal Article</dc:type>\n"
+ " <dc:type xml:lang=\"en\">Journal Article</dc:type>\n"
+ " <dc:date>2010</dc:date>\n"
+ " <dc:format></dc:format>\n"
+ " </rdf:Description>\n"
+ " </rdf:RDF>\n"
+ " </shortrecord>\n";
SearchNode summon = SummonTestHelper.createSummonSearchNode();
assertFieldContent("shortformat", summon, query, "shortformat", expected, false);
summon.close();
}
}
public void testAuthor_xmlExtraction_shortformat2() throws RemoteException {
String query = "ID:FETCH-LOGICAL-c1590-71216b8d44129eb55dba9244d0a7ad32261d9b5e7a00e7987e3aa5b33750b0dc1";
{ // sanity-check the Author-field
String expected = "Fallah, Mahdi\n"
+ "Kharazmi, Elham";
SearchNode summon = SummonTestHelper.createSummonSearchNode();
assertFieldContent("author direct", summon, query, "Author", expected, false);
summon.close();
}
{ // shortformat should match Author
String expected =
" <shortrecord>\n"
+ " <rdf:RDF xmlns:dc=\"http://purl.org/dc/elements/1.1/\" "
+ "xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n"
+ " <rdf:Description>\n"
+ " <dc:title>Substantial under-estimation in cancer incidence estimates for developing "
+ "countries due to under-ascertainment in elderly cancer cases</dc:title>\n"
+ " <dc:creator>Fallah, Mahdi</dc:creator>\n"
+ " <dc:creator>Kharazmi, Elham</dc:creator>\n"
+ " <dc:type xml:lang=\"da\">Journal Article</dc:type>\n"
+ " <dc:type xml:lang=\"en\">Journal Article</dc:type>\n"
+ " <dc:date>2008</dc:date>\n"
+ " <dc:format></dc:format>\n"
+ " </rdf:Description>\n"
+ " </rdf:RDF>\n"
+ " </shortrecord>\n";
SearchNode summon = SummonTestHelper.createSummonSearchNode();
assertFieldContent("shortformat", summon, query, "shortformat", expected, false);
summon.close();
}
}
public void testScoreAssignment() throws RemoteException {
String QUERY =
"The effect of multimedia on perceived equivocality and perceived usefulness of information systems";
String BAD =
"<record score=\"0.0\" "
+ "id=\"summon_FETCH-LOGICAL-j865-7bb06e292771fe19b17b4f676a0939e693be812b38d8502735ffb8ab6e46b4d21\" "
+ "source=\"Summon\">";
SearchNode summon = SummonTestHelper.createSummonSearchNode(true);
Request req = new Request(
DocumentKeys.SEARCH_QUERY, QUERY,
DocumentKeys.SEARCH_MAX_RECORDS, 10,
DocumentKeys.SEARCH_COLLECT_DOCIDS, false);
ResponseCollection responses = new ResponseCollection();
summon.search(req, responses);
assertFalse("There should be a score != 0.0 for all records in\n" + responses.iterator().next().toXML(),
responses.iterator().next().toXML().contains(BAD));
summon.close();
}
private void assertFieldContent(String message, SearchNode searchNode, String query, String fieldName,
String expected, boolean sort) throws RemoteException {
ResponseCollection responses = new ResponseCollection();
searchNode.search(new Request(DocumentKeys.SEARCH_QUERY, query), responses);
DocumentResponse docs = (DocumentResponse)responses.iterator().next();
assertEquals(message + ". There should only be a single hit", 1, docs.getHitCount());
boolean found = false;
for (DocumentResponse.Record record: docs.getRecords()) {
for (DocumentResponse.Field field: record.getFields()) {
if (fieldName.equals(field.getName())) {
String content = field.getContent();
if (sort) {
String[] tokens = content.split("\n");
Arrays.sort(tokens);
content = Strings.join(tokens, "\n");
}
assertEquals(message + ".The field '" + fieldName + "' should have the right content",
expected, content);
found = true;
}
}
}
if (!found) {
fail("Unable to locate the field '" + fieldName + "'");
}
}
public void testIDAdjustment() throws IOException {
SimplePair<String, String> credentials = SummonTestHelper.getCredentials();
Configuration conf = Configuration.newMemoryBased(
InteractionAdjuster.CONF_IDENTIFIER, "summon",
InteractionAdjuster.CONF_ADJUST_DOCUMENT_FIELDS, "recordID - ID");
Configuration inner = conf.createSubConfiguration(
AdjustingSearchNode.CONF_INNER_SEARCHNODE);
inner.set(SearchNodeFactory.CONF_NODE_CLASS, SummonSearchNode.class.getCanonicalName());
inner.set(SummonSearchNode.CONF_SUMMON_ACCESSID, credentials.getKey());
inner.set(SummonSearchNode.CONF_SUMMON_ACCESSKEY, credentials.getValue());
log.debug("Creating adjusting SummonSearchNode");
AdjustingSearchNode adjusting = new AdjustingSearchNode(conf);
Request request = new Request();
//request.put(DocumentKeys.SEARCH_QUERY, "foo");
request.put(DocumentKeys.SEARCH_QUERY, "recursion in string theory");
request.put(DocumentKeys.SEARCH_COLLECT_DOCIDS, true);
List<String> ids = getAttributes(adjusting, request, "id", false);
assertTrue("There should be at least one ID", !ids.isEmpty());
request.clear();
request.put(DocumentKeys.SEARCH_QUERY, IndexUtils.RECORD_FIELD + ":\"" + ids.get(0) + "\"");
List<String> researchIDs = getAttributes(adjusting, request, "id", false);
assertTrue("There should be at least one hit for a search for ID '"
+ ids.get(0) + "'", !researchIDs.isEmpty());
}
// TODO: "foo:bar zoo"
// It seems that "Book / eBook" is special and will be translated to s.fvgf (Book OR eBook) by summon
// This is important as it means that we cannot use filter ContentType:"Book / eBook" to get the same
// hits as a proper facet query
public void testFacetTermWithDivider() throws RemoteException {
SearchNode summon = SummonTestHelper.createSummonSearchNode(true);
long filterCount = getHits(
summon,
DocumentKeys.SEARCH_QUERY, "foo",
DocumentKeys.SEARCH_FILTER, "ContentType:\"Book / eBook\"",
SolrSearchNode.SEARCH_SOLR_FILTER_IS_FACET, "true");
long queryCount = getHits(
summon,
DocumentKeys.SEARCH_QUERY, "foo",
DocumentKeys.SEARCH_FILTER, "ContentType:Book OR ContentType:eBook");
assertTrue("There should be at least 1 hit for either query or filter request",
queryCount > 0 || filterCount > 0);
assertEquals("The number of hits for filter and query based restrictions should be the same",
filterCount, queryCount);
summon.close();
}
public void testFacetFieldValidity() throws RemoteException {
SearchNode summon = SummonTestHelper.createSummonSearchNode(true);
String[][] FACET_QUERIES = new String[][]{
//{"Ferlay", "Author", "Ferlay\\, Jacques"}, // We need a sample from the Author facet
{"foo", "Language", "German"},
{"foo", "IsScholarly", "true"},
{"foo", "IsFullText", "true"},
{"foo", "ContentType", "Book / eBook"},
{"foo", "SubjectTerms", "biology"}
};
for (String[] facetQuery: FACET_QUERIES) {
String q = facetQuery[0];
String ff = facetQuery[1] + ":\"" + facetQuery[2] + "\"";
log.debug(String.format("Searching for query '%s' with facet filter '%s'", q, ff));
long queryCount = getHits(
summon,
DocumentKeys.SEARCH_QUERY, q,
DocumentKeys.SEARCH_FILTER, ff,
SolrSearchNode.SEARCH_SOLR_FILTER_IS_FACET, "true");
assertTrue(String.format("There should be at least 1 hit for query '%s' with facet filter '%s'", q, ff),
queryCount > 0);
}
}
protected long getHits(SearchNode searcher, String... arguments) throws RemoteException {
String HITS_PATTERN = "(?s).*hitCount=\"([0-9]*)\".*";
ResponseCollection responses = new ResponseCollection();
searcher.search(new Request(arguments), responses);
if (!Pattern.compile(HITS_PATTERN).matcher(responses.toXML()).
matches()) {
return 0;
}
String hitsS = responses.toXML().replaceAll(HITS_PATTERN, "$1");
return "".equals(hitsS) ? 0L : Long.parseLong(hitsS);
}
protected void assertHits(
String message, SearchNode searcher, String... queries)
throws RemoteException {
long hits = getHits(searcher, queries);
assertTrue(message + ". Hits == " + hits, hits > 0);
}
}
|
Testing: Added another test for timeouts with truncation
|
Core/src/test/java/dk/statsbiblioteket/summa/support/summon/search/SummonSearchNodeTest.java
|
Testing: Added another test for timeouts with truncation
|
<ide><path>ore/src/test/java/dk/statsbiblioteket/summa/support/summon/search/SummonSearchNodeTest.java
<ide> List<String> tags = StringExtraction.getStrings(responses.toXML(), "<tag.+?>");
<ide> assertEquals("The number of returned tags should be " + tagCount + "+1. The returned Tags were\n"
<ide> + Strings.join(tags, "\n"),
<del> tagCount+1, tags.size());
<add> tagCount + 1, tags.size());
<ide> summon.close();
<ide> }
<ide>
<ide> DocumentKeys.SEARCH_COLLECT_DOCIDS, false);
<ide> List<String> ids = getAttributes(summon, req, "id", false);
<ide> assertTrue("There should be at least 1 result", ids.size() >= 1);
<add> }
<add>
<add> public void testTruncation() throws IOException, TransformerException {
<add> String PLAIN = "Author:andersen";
<add> String ESCAPED = "Author:andersen\\ christian";
<add> String TRUNCATED = "Author:andersen*";
<add> String ESCAPED_TRUNCATED = "Author:andersen\\ c*";
<add> String ESCAPED_TRUNCATED2 = "lfo:andersen\\ h\\ c*";
<add>
<add> List<String> QUERIES = Arrays.asList(PLAIN, ESCAPED, TRUNCATED, ESCAPED_TRUNCATED, ESCAPED_TRUNCATED2);
<add>
<add> log.debug("Creating SummonSearchNode");
<add> Configuration conf = SummonTestHelper.getDefaultSummonConfiguration();
<add> conf.set(SolrSearchNode.CONF_SOLR_READ_TIMEOUT, 20*1000);
<add> SearchNode summon = new SummonSearchNode(conf);
<add> for (String query: QUERIES) {
<add> Request req = new Request(
<add> DocumentKeys.SEARCH_QUERY, query,
<add> DocumentKeys.SEARCH_COLLECT_DOCIDS, false);
<add> long searchTime = -System.currentTimeMillis();
<add> List<String> ids = getAttributes(summon, req, "id", false);
<add> searchTime += System.currentTimeMillis();
<add> assertFalse("There should be at least 1 result for " + query, ids.isEmpty());
<add> log.info("Got " + ids.size() + " from query '" + query + "' in " + searchTime + " ms");
<add> }
<ide> }
<ide>
<ide> public void testGetField() throws IOException, TransformerException {
|
|
Java
|
apache-2.0
|
3458fa25340df2e081447274d29b55de65a40175
| 0 |
idea4bsd/idea4bsd,allotria/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,ibinti/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,semonte/intellij-community,semonte/intellij-community,da1z/intellij-community,semonte/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,da1z/intellij-community,xfournet/intellij-community,semonte/intellij-community,asedunov/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,da1z/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,semonte/intellij-community,allotria/intellij-community,da1z/intellij-community,semonte/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,da1z/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,xfournet/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,fitermay/intellij-community,FHannes/intellij-community,da1z/intellij-community,asedunov/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,apixandru/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,asedunov/intellij-community,semonte/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,vvv1559/intellij-community,da1z/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,signed/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,apixandru/intellij-community,xfournet/intellij-community,xfournet/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,hurricup/intellij-community,signed/intellij-community,ibinti/intellij-community,FHannes/intellij-community,FHannes/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,fitermay/intellij-community,signed/intellij-community,vvv1559/intellij-community,semonte/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,semonte/intellij-community,hurricup/intellij-community,semonte/intellij-community,semonte/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,asedunov/intellij-community,fitermay/intellij-community,allotria/intellij-community,semonte/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,asedunov/intellij-community,FHannes/intellij-community,hurricup/intellij-community,apixandru/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,allotria/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,allotria/intellij-community,signed/intellij-community,apixandru/intellij-community,fitermay/intellij-community,allotria/intellij-community,da1z/intellij-community,xfournet/intellij-community,signed/intellij-community,hurricup/intellij-community,signed/intellij-community,allotria/intellij-community,da1z/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,hurricup/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,allotria/intellij-community,hurricup/intellij-community,FHannes/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,allotria/intellij-community,asedunov/intellij-community,ibinti/intellij-community,fitermay/intellij-community,asedunov/intellij-community,ibinti/intellij-community,xfournet/intellij-community,allotria/intellij-community,FHannes/intellij-community,xfournet/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,signed/intellij-community,signed/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,asedunov/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,idea4bsd/idea4bsd
|
/*
* Copyright 2000-2016 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 org.intellij.lang.regexp;
/**
* @author yole
*/
public enum RegExpCapability {
XML_SCHEMA_MODE,
DANGLING_METACHARACTERS,
NESTED_CHARACTER_CLASSES,
/**
* supports three-digit octal numbers not started with 0 (e.g. \123),
* if false \1 from \123 will be considered as a group back reference
*/
OCTAL_NO_LEADING_ZERO,
OMIT_NUMBERS_IN_QUANTIFIERS,
COMMENT_MODE,
ALLOW_HEX_DIGIT_CLASS,
/**
* supports [] to be valid character class
*/
ALLOW_EMPTY_CHARACTER_CLASS,
ALLOW_HORIZONTAL_WHITESPACE_CLASS,
/**
* allows not to wrap one-letter unicode categories with braces: \p{L} -> \pL
*/
UNICODE_CATEGORY_SHORTHAND,
/**
* supports expressions like [[:alpha:]], [^[:alpha:]], [[:^alpha:]]
*/
POSIX_BRACKET_EXPRESSIONS,
/**
* supports for property negations like \p{^Alnum}
*/
CARET_NEGATED_PROPERTIES
}
|
RegExpSupport/src/org/intellij/lang/regexp/RegExpCapability.java
|
/*
* Copyright 2000-2016 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 org.intellij.lang.regexp;
/**
* @author yole
*/
public enum RegExpCapability {
XML_SCHEMA_MODE,
DANGLING_METACHARACTERS,
NESTED_CHARACTER_CLASSES,
/**
* supports three-digit octal numbers not started with 0 (e.g. \123),
* if false \1 from \123 will be considered as a group back reference
*/
OCTAL_NO_LEADING_ZERO,
OMIT_NUMBERS_IN_QUANTIFIERS,
COMMENT_MODE,
ALLOW_HEX_DIGIT_CLASS,
/**
* supports [] to be valid character class
*/
ALLOW_EMPTY_CHARACTER_CLASS,
ALLOW_HORIZONTAL_WHITESPACE_CLASS,
UNICODE_CATEGORY_SHORTHAND,
/**
* supports expressions like [[:alpha:]], [^[:alpha:]], [[:^alpha:]]
*/
POSIX_BRACKET_EXPRESSIONS,
CARET_NEGATED_PROPERTIES
}
|
Regex: javadoc
|
RegExpSupport/src/org/intellij/lang/regexp/RegExpCapability.java
|
Regex: javadoc
|
<ide><path>egExpSupport/src/org/intellij/lang/regexp/RegExpCapability.java
<ide> */
<ide> ALLOW_EMPTY_CHARACTER_CLASS,
<ide> ALLOW_HORIZONTAL_WHITESPACE_CLASS,
<add>
<add> /**
<add> * allows not to wrap one-letter unicode categories with braces: \p{L} -> \pL
<add> */
<ide> UNICODE_CATEGORY_SHORTHAND,
<ide>
<ide> /**
<ide> */
<ide> POSIX_BRACKET_EXPRESSIONS,
<ide>
<add> /**
<add> * supports for property negations like \p{^Alnum}
<add> */
<ide> CARET_NEGATED_PROPERTIES
<ide> }
|
|
JavaScript
|
mit
|
79206257b1862b1888d3bc7793c5a2cebeb70187
| 0 |
jmarceli/generator-wp-plugin-boilerplate-powered,Mte90/generator-wp-plugin-boilerplate-powered
|
'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var fs = require('fs');
var request = require('request');
var Admzip = require('adm-zip');
var rmdir = require('rimraf');
var s = require('underscore.string');
var sys = require('sys');
var spawn = require('child_process').spawnSync || require('spawn-sync');
var colors = require('colors');
var Replacer = require('./replacer');
var cleanfolder = false;
var args = process.argv.slice(2);
var version = '1.1.1';
var is_default = false;
var verbose = false;
if (args[1] === 'dev') {
version = 'master';
}
if (args[1] === 'verbose' || args[2] === 'verbose') {
verbose = true;
}
/**
* Checks whether a path starts with or contains a hidden file or a folder.
* @param {string} path - The path of the file that needs to be validated.
* returns {boolean} - `true` if the source is blacklisted and otherwise `false`.
*/
var isUnixHiddenPath = function (path) {
return (/(^|.\/)\.+[^\/\.]/g).test(path);
};
/*
* Remove the unuseful file and folder, insert the index.php in the folders
*
* @param string path
*/
function cleanFolder(path) {
cleanParsing(path);
//Recursive scanning for the subfolder
var list = fs.readdirSync(path);
list.forEach(function (file) {
var pathrec = path + '/' + file;
var i = pathrec.lastIndexOf('.');
var ext = (i < 0) ? '' : pathrec.substr(i);
if (!isUnixHiddenPath(pathrec) && ext === '') {
var stat = fs.statSync(pathrec);
if (stat && stat.isDirectory()) {
if (verbose) {
console.log(('Parsing ' + pathrec).italic);
}
cleanParsing(path);
cleanFolder(pathrec);
}
}
});
}
function cleanParsing(pathrec) {
var default_file = [
'CONTRIBUTING.md', 'readme.md', 'phpunit.xml', 'packages.json', 'package.json', 'production.rb', 'composer.json',
'Gruntfile.js', 'README.md', 'example-functions.php', 'bower.json', 'Capfile', 'screenshot-1.png', 'component.json',
'.travis.yml', '.bowerrc', '.gitignore', 'README.txt', 'readme.txt', 'release.sh', 'pointerplus.php', '.DS_Store', 'widget-sample.php'
];
var default_folder = ['tests', 'bin', 'deploy', 'config'];
if (cleanfolder !== false) {
//Remove the unuseful files
default_file.forEach(function (element, index, array) {
if (fs.existsSync('./' + pathrec + '/' + element)) {
fs.unlink(pathrec + '/' + element, function (err) {
if (err) {
console.log(('Remove unuseful file error: ' + err).red);
}
});
if (verbose) {
console.log(('Removed ' + pathrec + '/' + element).italic);
}
}
});
//Remove the unuseful directory
default_folder.forEach(function (element, index, array) {
var isEmpty = false;
fs.stat('./' + pathrec + '/' + element, function (error, stats) {
fs.readdir('./' + pathrec + '/' + element, function (err, items) {
if (!items || !items.length) {
isEmpty = true;
}
});
if (!error || isEmpty) {
rmdir('./' + pathrec + '/' + element, function (err) {
if (err) {
console.log(('Remove unuseful directory error:' + err).red);
}
if (verbose) {
console.log(('Removed ' + pathrec + '/' + element).italic);
}
});
}
});
});
}
//Insert a blank index.php
fs.exists('./' + pathrec + '/index.php', function (exists) {
if (!exists) {
fs.writeFile('./' + pathrec + '/index.php',
"<?php // Silence is golden",
'utf8', function () {
});
if (verbose) {
console.log(('Created ' + pathrec + '/index.php').italic);
}
}
});
}
var WpPluginBoilerplateGenerator = module.exports = function WpPluginBoilerplateGenerator(args, options, config) {
var self = this,
default_file;
yeoman.generators.Base.apply(this, arguments);
this.on('end', function () {
//Generate the bash script for download the git submodules
//Initialize git and clean the submodules not required
var submodulessh = ['#!/bin/sh',
'set -e',
'git init',
"git config -f .gitmodules --get-regexp '^submodule..*.path$' |",
'while read path_key path',
' do',
" url_key=$(echo $path_key | sed 's/.path/.url/')",
' url=$(git config -f .gitmodules --get $url_key)',
' path="./$path"',
' if [ -d "$path" ]; then',
' rm -r $path',
' echo "Add $url in $path"',
' git submodule add -f $url $path >> /dev/null',
' fi',
' done',
'rm $0'
].join('\n');
fs.writeFile(self.pluginSlug + '/submodules.sh', submodulessh, 'utf8',
function (err) {
if (err) {
console.log(('Error on writing submodules.sh:' + err).red);
process.exit();
} else {
fs.chmodSync(process.cwd() + '/' + self.pluginSlug + '/submodules.sh', '0777');
console.log(('Generate git config on the fly').white);
//Execute the magic for clean, destroy, brick, brock the code
var key = null;
for (key in self.files) {
if (self.files.hasOwnProperty(key)) {
self.files[key].sed();
if (verbose) {
console.log(('Sed executed on ' + key).italic);
}
}
}
console.log(('Parsed all the files').white);
//Call the bash script
console.log(('Download submodules (wait a moment)').white);
var submodule = spawn(process.cwd() + '/' + self.pluginSlug + '/submodules.sh', [],
{
cwd: process.cwd() + '/' + self.pluginSlug + '/'
});
if (submodule.status !== 0) {
console.log(('Error on submodule:' + submodule.stderr).blue);
process.exit();
} else {
if (self.defaultValues.git !== true) {
fs.unlink(self.pluginSlug + '/.gitmodules', function (error) {
if (error) {
console.log(('Error on removing .gitmodules:' + error).red);
}
});
rmdir(self.pluginSlug + '/.git', function (error) {
if (error) {
console.log(('Error on removing .git:' + error).red);
}
});
console.log(('Remove git config generated').white);
}
//Clean all the folders!!
if (self.modules.indexOf('CPT_Core') !== -1) {
cleanFolder(self.pluginSlug + '/includes/CPT_Core');
}
if (self.modules.indexOf('Taxonomy_Core') !== -1) {
cleanFolder(self.pluginSlug + '/includes/Taxonomy_Core');
}
if (self.modules.indexOf('Widget-Boilerplate') !== -1) {
cleanFolder(self.pluginSlug + '/includes/Widget-Boilerplate');
cleanFolder(self.pluginSlug + '/includes/Widget-Boilerplate/widget-boilerplate');
}
if (self.modules.indexOf('CMB2') !== -1) {
cleanFolder(self.pluginSlug + '/admin/includes/CMB2');
}
if (self.modules.indexOf('PointerPlus') !== -1) {
cleanFolder(self.pluginSlug + '/admin/includes/PointerPlus');
}
if (self.modules.indexOf('Template system (like WooCommerce)') !== -1) {
cleanFolder(self.pluginSlug + '/templates');
}
if (self.modules.indexOf('WP-Contextual-Help') !== -1) {
if (cleanfolder !== false) {
rmdir(self.pluginSlug + +'/admin/includes/WP-Contextual-Help/assets/', function (err) {
});
}
cleanFolder(self.pluginSlug + '/admin/includes/WP-Contextual-Help');
}
//Console.log are cool and bowtie are cool!
console.log(('Inserted index.php files in all the folders').white);
console.log(('All done!').white);
}
}
}
);
});
//Yeoman greet the user.
console.log(this.yeoman);
//Check the default file for the default values, I have already said default?
if (fs.existsSync(__dirname + '/../default-values.json')) {
default_file = path.join(__dirname, '../default-values.json');
if (verbose) {
console.log(('Config loaded').yellow);
}
} else if (fs.existsSync(process.cwd() + '/default-values.json')) {
default_file = process.cwd() + '/default-values.json';
if (verbose) {
console.log(('Config loaded').yellow);
}
} else {
console.log('--------------------------');
console.log(('You can create the file ' + process.cwd() + '/default-values.json with default values in the parent folder! Use the default-values-example.json as a template.').bold);
console.log('--------------------------');
default_file = path.join(__dirname, '../default-values-example.json');
is_default = true;
}
this.defaultValues = JSON.parse(this.readFileAsString(default_file));
};
util.inherits(WpPluginBoilerplateGenerator, yeoman.generators.Base);
WpPluginBoilerplateGenerator.prototype.askFor = function askFor() {
var cb = this.async(),
prompts = [];
//The boilerplate have the steroids then there are many questions. I know I'm not funny.
prompts = [{
name: 'name',
message: 'What do you want to call your plugin?',
default: 'My New Plugin'
}, {
name: 'pluginVersion',
message: 'What is your new plugin\'s version?',
default: '1.0.0'
}, {
name: 'author',
message: 'What is your name?',
default: this.defaultValues.author.name
}, {
name: 'authorEmail',
message: 'What is your e-mail?',
default: this.defaultValues.author.email
}, {
name: 'authorURI',
message: 'What is your URL?',
default: this.defaultValues.author.url
}, {
name: 'copyright',
message: 'What goes in copyright tags?',
default: this.defaultValues.author.copyright
}, {
type: 'checkbox',
name: 'publicResources',
message: 'Which resources your public site needs?',
choices: [{name: 'JS', checked: true}, {name: 'CSS', checked: true}]
}, {
type: 'checkbox',
name: 'activateDeactivate',
message: 'Which resources your plugin needs?',
choices: [
{name: 'Activate Method', checked: true},
{name: 'Deactivate Method', checked: true},
{name: 'Uninstall File', checked: true}]
}, {
type: 'confirm',
name: 'adminPage',
message: 'Does your plugin need an admin page?'
}, {
type: 'checkbox',
name: 'modules',
message: 'Which library your plugin needs?',
choices: [
{name: 'CPT_Core', checked: true},
{name: 'CPT_Columns', checked: true},
{name: 'Taxonomy_Core', checked: true},
{name: 'Widget Helper', checked: true},
{name: 'CMB2', checked: true},
{name: 'WP-Contextual-Help', checked: true},
{name: 'WP-Admin-Notice', checked: true},
{name: 'PointerPlus', checked: true},
{name: 'Fake Page Class', checked: true},
{name: 'Template system (like WooCommerce)', checked: true},
{name: 'Language function support (WPML/Ceceppa Multilingua/Polylang)', checked: true},
{name: 'Requirements system on activation', checked: true}
]
}, {
type: 'checkbox',
name: 'snippet',
message: 'Which snippet your plugin needs?',
choices: [
{name: 'Support Dashboard At Glance Widget for CPT', checked: true},
{name: 'Javascript DOM-based Routing', checked: true},
{name: 'Bubble notification on pending CPT', checked: true},
{name: 'Import/Export settings system', checked: true},
{name: 'Capability system', checked: true},
{name: 'Debug system (Debug Bar support)', checked: true},
{name: 'Add body class', checked: true},
{name: 'wp_localize_script for PHP var to JS', checked: true},
{name: 'CPTs on search box', checked: true},
{name: 'Custom action', checked: true},
{name: 'Custom filter', checked: true},
{name: 'Custom shortcode', checked: true}
]
}, {
type: 'confirm',
name: 'git',
message: 'Do you need an initialized git repo?'
}, {
type: 'confirm',
name: 'cleanFolder',
message: 'Do you want clean the folders?'
}, {
type: 'confirm',
name: 'saveSettings',
message: 'Do you want save the configuration for reuse it?'
}];
if (is_default === false) {
if (this.defaultValues.name !== '') {
if (fs.existsSync('./' + s.slugify(this.defaultValues.name)) && this.defaultValues.name !== undefined) {
console.log(('Warning folder ' + s.slugify(this.defaultValues.name) + ' already exist, change the name of the plugin!').red);
}
prompts[0].default = this.defaultValues.name;
}
if (this.defaultValues.version !== '') {
prompts[1].default = this.defaultValues.pluginVersion;
}
if (this.defaultValues.publicResources !== '') {
if (this.defaultValues.publicResources === undefined) {
prompts[6].choices.forEach(function (element, index, array) {
prompts[6].choices[index].checked = false;
});
} else {
var defaultvalues = this.defaultValues.publicResources;
prompts[6].choices.forEach(function (element, index, array) {
prompts[6].choices[index].checked = false;
defaultvalues.forEach(function (element_z, index_z, array_z) {
if (prompts[6].choices[index].name === element_z) {
prompts[6].choices[index].checked = true;
}
});
});
}
}
if (this.defaultValues.activateDeactivate !== '') {
if (this.defaultValues.activateDeactivate === undefined) {
prompts[7].choices.forEach(function (element, index, array) {
prompts[7].choices[index].checked = false;
});
} else {
var defaultvalues = this.defaultValues.activateDeactivate;
prompts[7].choices.forEach(function (element, index, array) {
prompts[7].choices[index].checked = false;
defaultvalues.forEach(function (element_z, index_z, array_z) {
if (prompts[7].choices[index].name === element_z) {
prompts[7].choices[index].checked = true;
}
});
});
}
}
if (this.defaultValues.adminPage !== '') {
prompts[8].default = this.defaultValues.adminPage;
}
if (this.defaultValues.modules === undefined) {
prompts[9].choices.forEach(function (element, index, array) {
prompts[9].choices[index].checked = false;
});
} else {
var defaultvalues = this.defaultValues.modules;
prompts[9].choices.forEach(function (element, index, array) {
prompts[9].choices[index].checked = false;
defaultvalues.forEach(function (element_z, index_z, array_z) {
if (prompts[9].choices[index].name === element_z) {
prompts[9].choices[index].checked = true;
}
});
});
}
if (this.defaultValues.snippet === undefined) {
prompts[10].choices.forEach(function (element, index, array) {
prompts[10].choices[index].checked = false;
});
} else {
var defaultvalues = this.defaultValues.snippet;
prompts[10].choices.forEach(function (element, index, array) {
prompts[10].choices[index].checked = false;
defaultvalues.forEach(function (element_z, index_z, array_z) {
if (prompts[10].choices[index].name === element_z) {
prompts[10].choices[index].checked = true;
}
});
});
}
if (this.defaultValues.git !== '') {
prompts[11].default = this.defaultValues.git;
}
if (this.defaultValues.cleanFolder !== '') {
prompts[12].default = this.defaultValues.cleanFolder;
}
if (this.defaultValues.saveSettings !== '') {
prompts[13].default = this.defaultValues.saveSettings;
}
}
this.prompt(prompts, function (props) {
this.pluginName = props.name;
this.pluginSlug = s.slugify(props.name);
this.pluginClassName = s.titleize(props.name).replace(/ /g, "_");
this.author = props.author;
this.authorEmail = props.authorEmail;
this.authorURI = props.authorURI;
this.pluginVersion = props.pluginVersion;
this.pluginCopyright = props.copyright;
this.publicResources = props.publicResources;
this.activateDeactivate = props.activateDeactivate;
this.modules = props.modules;
this.snippet = props.snippet;
this.adminPage = props.adminPage;
//Set the path of the files
this.files = {
primary: new Replacer(this.pluginSlug + '/' + this.pluginSlug + '.php', this),
publicClass: new Replacer(this.pluginSlug + '/public/class-' + this.pluginSlug + '.php', this),
adminClass: new Replacer(this.pluginSlug + '/admin/class-' + this.pluginSlug + '-admin.php', this),
adminCss: new Replacer(this.pluginSlug + '/admin/assets/css/admin.css', this),
publicView: new Replacer(this.pluginSlug + '/public/views/public.php', this),
adminView: new Replacer(this.pluginSlug + '/admin/views/admin.php', this),
uninstall: new Replacer(this.pluginSlug + '/uninstall.php', this),
readme: new Replacer(this.pluginSlug + '/README.txt', this),
gitmodules: new Replacer(this.pluginSlug + '/.gitmodules', this),
template: new Replacer(this.pluginSlug + '/includes/template.php', this),
publicjs: new Replacer(this.pluginSlug + '/public/assets/js/public.js', this),
debug: new Replacer(this.pluginSlug + '/admin/includes/debug.php', this),
requirements: new Replacer(this.pluginSlug + '/public/includes/requirements.php', this),
language: new Replacer(this.pluginSlug + '/includes/language.php', this),
fakepage: new Replacer(this.pluginSlug + '/includes/fake-page.php', this)
};
if (props.saveSettings === true) {
var cleaned = props;
delete cleaned['authorEmail'];
delete cleaned['authorEmail'];
delete cleaned['copyright'];
cleaned.author = {'name': props.author, 'email': this.authorEmail, 'url': this.authorURI, 'copyright': this.pluginCopyright};
fs.writeFile(props.name + '.json', JSON.stringify(cleaned, null, 2), function (err) {
if (err) {
console.log('Error on save your json config file: ' + err);
} else {
console.log(("JSON saved to " + props.name + '.json').blue);
}
});
}
cb();
}.bind(this));
};
WpPluginBoilerplateGenerator.prototype.download = function download() {
var cb = this.async(),
self = this,
path = 'http://github.com/Mte90/WordPress-Plugin-Boilerplate-Powered/archive/' + version + '.zip',
zip = "";
//Force the remove of the same plugin folder
if (args[2] === 'force' || args[3] === 'force' || args[4] === 'force') {
rmdir.sync('./' + self.pluginSlug, function (error) {
if (error) {
console.log(('Error on removing plugin folder' + error).red);
}
});
rmdir.sync('./plugin_temp', function (error) {
if (error) {
console.log(('Error on removing plugin temp folder' + error).red);
}
});
//Check plugin folder if exist
} else if (fs.existsSync('./' + self.pluginSlug)) {
console.log(('Error: Folder ' + self.pluginSlug + ' already exist, change the name of the plugin!').red);
process.exit(1);
}
//Check if exist the plugin.zip
if (fs.existsSync(process.cwd() + '/plugin.zip')) {
console.log(('Extract Plugin boilerplate').white);
zip = new Admzip('./plugin.zip');
zip.extractAllTo('plugin_temp', true);
fs.rename('./plugin_temp/WordPress-Plugin-Boilerplate-Powered-' + version + '/.gitmodules', './plugin_temp/WordPress-Plugin-Boilerplate-Powered-' + version + '/plugin-name/.gitmodules', function (err) {
if (err) {
console.log(('Error: Maybe you want the development version? Call this generator with the dev parameter').red);
process.exit(1);
}
});
fs.rename('./plugin_temp/WordPress-Plugin-Boilerplate-Powered-' + version + '/plugin-name/', './' + self.pluginSlug, function () {
rmdir('plugin_temp', function (error) {
if (error) {
console.log(('Error on removing plugin temp folder' + error).red);
}
cb();
});
});
//else download the zip
} else {
console.log(('Downloading the WP Plugin Boilerplate Powered...').white);
//Do you want the development version?
if (version === 'master') {
path = 'https://github.com/Mte90/WordPress-Plugin-Boilerplate-Powered/archive/master.zip';
}
request(path)
.pipe(fs.createWriteStream('plugin.zip'))
.on('close', function () {
zip = new Admzip('./plugin.zip');
console.log(('File downloaded').white);
zip.extractAllTo('plugin_temp', true);
fs.rename('./plugin_temp/WordPress-Plugin-Boilerplate-Powered-' + version + '/.gitmodules', './plugin_temp/WordPress-Plugin-Boilerplate-Powered-' + version + '/plugin-name/.gitmodules', function (error) {
if (error) {
console.log(('Error on move gitmodules:' + error).red);
}
});
fs.rename('./plugin_temp/WordPress-Plugin-Boilerplate-Powered-' + version + '/plugin-name/', './' + self.pluginSlug, function () {
rmdir('plugin_temp', function (error) {
if (error) {
console.log(('Error on move plugin temp folder:' + error).red);
}
cb();
});
});
fs.unlink('plugin.zip');
});
}
};
WpPluginBoilerplateGenerator.prototype.setFiles = function setFiles() {
cleanfolder = this.cleanFolder;
//Change path of gitmodules
this.files.gitmodules.add(new RegExp(this.pluginSlug + '/', "g"), '');
this.files.gitmodules.add(new RegExp('[email protected]:', "g"), 'https://github.com/');
//Rename files
fs.rename(this.pluginSlug + '/plugin-name.php', this.files.primary.file, function (err) {
if (err) {
console.log(('Error on rename plugin-name.php:' + err).red);
}
});
fs.rename(this.pluginSlug + '/admin/class-plugin-name-admin.php', this.files.adminClass.file, function (err) {
if (err) {
console.log(('Error on rename class-plugin-name-admin.php:' + err).red);
}
});
fs.rename(this.pluginSlug + '/public/class-plugin-name.php', this.files.publicClass.file, function (err) {
if (err) {
console.log(('Error on rename class-plugin-name.php:' + err).red);
}
});
fs.rename(this.pluginSlug + '/languages/plugin-name.pot', this.pluginSlug + '/languages/' + this.pluginSlug + '.pot', function (err) {
if (err) {
console.log(('Error on rename plugin-name.pot:' + err).red);
}
});
console.log(('Renamed files').white);
};
WpPluginBoilerplateGenerator.prototype.setPrimary = function setPrimary() {
this.files.primary.add(/Plugin Name:( {7})@TODO/g, 'Plugin Name: ' + this.pluginName);
this.files.primary.add(/Version:( {11})1\.0\.0/g, 'Version: ' + this.pluginVersion);
this.files.primary.add(/Author:( {12})@TODO/g, 'Author: ' + this.author);
this.files.primary.add(/Author URI:( {8})@TODO/g, 'Author URI: ' + this.authorURI);
this.files.primary.rm("/*\n * @TODO:\n *\n * - replace `class-" + this.pluginSlug + ".php` with the name of the plugin's class file\n *\n */");
this.files.primary.rm(" * @TODO:\n *\n * - replace `class-" + this.pluginSlug + "-admin.php` with the name of the plugin's admin file\n");
this.files.primary.rm(" *\n * @TODO:\n *\n * - replace " + this.pluginClassName + " with the name of the class defined in\n * `class-" + this.pluginSlug + ".php`\n");
this.files.primary.rm("/*\n * @TODO:\n *\n * - replace " + this.pluginClassName + " with the name of the class defined in\n * `class-" + this.pluginSlug + ".php`\n */");
this.files.primary.rm(" * - replace " + this.pluginClassName + "_Admin with the name of the class defined in\n * `class-" + this.pluginSlug + "-admin.php`\n");
this.files.primary.rm(" * @TODO:\n *\n * - replace `class-plugin-admin.php` with the name of the plugin's admin file\n * - replace " + this.pluginClassName + "Admin with the name of the class defined in\n * `class-" + this.pluginSlug + "-admin.php`\n *\n");
if (verbose) {
console.log(('Added info marker replace on plugin.php').italic);
}
//Activate/deactivate
if (this.activateDeactivate.indexOf('Activate Method') === -1 && this.activateDeactivate.indexOf('Deactivate Method') === -1) {
this.files.primary.rm("\n/*\n * Register hooks that are fired when the plugin is activated or deactivated.\n * When the plugin is deleted, the uninstall.php file is loaded.\n */\nregister_activation_hook( __FILE__, array( '" + this.pluginClassName + "', 'activate' ) );\nregister_deactivation_hook( __FILE__, array( '" + this.pluginClassName + "', 'deactivate' ) );\n");
}
if (this.activateDeactivate.indexOf('Activate Method') === -1) {
this.files.primary.rm("\nregister_activation_hook( __FILE__, array( '" + this.pluginClassName + "', 'activate' ) );");
}
if (this.activateDeactivate.indexOf('Deactivate Method') === -1) {
this.files.primary.rm("\nregister_deactivation_hook( __FILE__, array( '" + this.pluginClassName + "', 'deactivate' ) );");
}
//Repo
if (this.modules.indexOf('CPT_Core') === -1 && this.modules.indexOf('Taxonomy_Core') === -1) {
this.files.primary.rm("\n/*\n * Load library for simple and fast creation of Taxonomy and Custom Post Type\n *\n */");
}
if (this.modules.indexOf('CPT_Core') === -1) {
rmdir(this.pluginSlug + '/includes/CPT_Core', function (error) {
if (error) {
console.log((error).red);
}
});
this.files.primary.rm("require_once( plugin_dir_path( __FILE__ ) . 'includes/CPT_Core/CPT_Core.php' );");
this.files.primary.rm("and Custom Post Type");
if (verbose) {
console.log(('CPT_Core removed').italic);
}
}
if (this.modules.indexOf('Taxonomy_Core') === -1) {
rmdir(this.pluginSlug + '/includes/Taxonomy_Core', function (error) {
if (error) {
console.log((error).red);
}
});
this.files.primary.rm("require_once( plugin_dir_path( __FILE__ ) . 'includes/Taxonomy_Core/Taxonomy_Core.php' );");
this.files.primary.rm("Taxonomy and");
if (verbose) {
console.log(('Taxnomy_Core removed').italic);
}
}
if (this.modules.indexOf('Widget Helper') === -1) {
rmdir(this.pluginSlug + '/includes/Widget-Helper', function (error) {
if (error) {
console.log((error).red);
}
});
this.files.primary.rmsearch(' * Load Widgets Helper', '', 1, 3);
if (verbose) {
console.log(('Removed Widgets Helper').italic);
}
}
//Function
if (this.modules.indexOf('Fake Page Class') === -1) {
fs.unlink(this.pluginSlug + '/includes/fake-page.php');
this.files.primary.rmsearch(' * Load Fake Page class', "'post content' => 'This is the fake page content'", 1, -3);
if (verbose) {
console.log(('Removed Fake Class').italic);
}
}
if (this.modules.indexOf('Template system (like WooCommerce)') === -1) {
fs.unlink(this.pluginSlug + '/includes/template.php');
rmdir(this.pluginSlug + '/templates', function (error) {
if (error) {
console.log((error).red);
}
});
this.files.primary.rmsearch(' * Load template system', '', 1, 3);
if (verbose) {
console.log(('Removed Template System').italic);
}
}
if (this.modules.indexOf('Language function support (WPML/Ceceppa Multilingua/Polylang)') === -1) {
fs.unlink(this.pluginSlug + '/includes/language.php');
this.files.primary.rmsearch(' * Load Language wrapper function for WPML/Ceceppa Multilingua/Polylang', '', 1, 3);
if (verbose) {
console.log(('Removed Language function').italic);
}
}
};
WpPluginBoilerplateGenerator.prototype.setAdminClass = function setAdminClass() {
this.files.adminClass.rm(" * @TODO: Rename this class to a proper name for your plugin.\n *\n");
this.files.adminClass.rm("*\n * Call $plugin_slug from public plugin class.\n *\n * @TODO:\n *\n * - Rename \"" + this.pluginClassName + "\" to the name of your initial plugin class\n *\n */\n");
this.files.adminClass.rmsearch('* Register and enqueue admin-specific style sheet.', '* - Rename "Plugin_Name" to the name your plugin', -2, -1);
this.files.adminClass.rmsearch('* Register and enqueue admin-specific JavaScript.', '* - Rename "Plugin_Name" to the name your plugin', -2, -1);
if (verbose) {
console.log(('Added info marker in admin-class*.php').italic);
}
//Repo
if (this.modules.indexOf('CMB2') === -1) {
rmdir(this.pluginSlug + '/admin/includes/CMB2', function (error) {
if (error) {
console.log((error).red);
}
});
rmdir(this.pluginSlug + '/admin/includes/CMB2-Shortcode', function (error) {
if (error) {
console.log((error).red);
}
});
this.files.adminClass.rm("$settings[ 1 ] = get_option( $this->plugin_slug . '-settings-second' );");
this.files.adminClass.rm("update_option( $this->plugin_slug . '-settings-second', get_object_vars( $settings[ 1 ] ) );");
this.files.adminClass.rmsearch('* CMB 2 for metabox and many other cool things!', "add_filter( 'cmb2_meta_boxes', array( $this, 'cmb_demo_metaboxes' ) );", 1, 0);
this.files.publicClass.rm("// Check for the CMB2 Shortcode Button");
this.files.publicClass.rm("// In bundle with the boilerplate https://github.com/jtsternberg/Shortcode_Button");
if (this.adminPage === true) {
this.files.adminView.rmsearch('<div id="tabs-1">', "cmb2_metabox_form( $option_fields, $this->plugin_slug . '-settings' );", -2, -2);
this.files.adminView.rmsearch('<div id="tabs-2">', "cmb2_metabox_form( $option_fields_second, $this->plugin_slug . '-settings-second' );", -2, -2);
}
if (verbose) {
console.log(('Removed CMB2').italic);
}
}
if (this.modules.indexOf('WP-Contextual-Help') === -1) {
rmdir(this.pluginSlug + '/admin/includes/WP-Contextual-Help', function (error) {
if (error) {
console.log((error).red);
}
});
rmdir(this.pluginSlug + '/help-docs', function (error) {
if (error) {
console.log((error).red);
}
});
this.files.adminClass.rmsearch('* Load Wp_Contextual_Help for the help tabs', "add_action( 'init', array( $this, 'contextual_help' ) );", 1, -1);
this.files.adminClass.rmsearch('* Filter for change the folder of Contextual Help', "$paths[] = plugin_dir_path( __FILE__ ) . '../help-docs/';", 1, -3);
this.files.adminClass.rmsearch('* Filter for change the folder image of Contextual Help', "$paths[] = plugin_dir_path( __FILE__ ) . '../help-docs/img';", 1, -3);
this.files.adminClass.rmsearch('* Contextual Help, docs in /help-docs folter', "'page' => 'settings_page_' . $this->plugin_slug,", 1, -1);
if (verbose) {
console.log(('Removed Wp_Contextual_Help').italic);
}
}
if (this.modules.indexOf('WP-Admin-Notice') === -1) {
rmdir(this.pluginSlug + '/admin/includes/WP-Admin-Notice', function (error) {
if (error) {
console.log((error).red);
}
});
this.files.adminClass.rmsearch('* Load Wp_Admin_Notice for the notices in the backend', "new WP_Admin_Notice( __( 'Error Messages' ), 'error' );", 1, -1);
if (verbose) {
console.log(('Removed WP-Admin-Notice').italic);
}
}
if (this.modules.indexOf('PointerPlus') === -1) {
rmdir(this.pluginSlug + '/admin/includes/PointerPlus', function (error) {
if (error) {
console.log((error).red);
}
});
this.files.adminClass.rmsearch('* Load PointerPlus for the Wp Pointer', "add_filter( 'pointerplus_list', array( $this, 'custom_initial_pointers' ), 10, 2 );", 1, 0);
this.files.adminClass.rmsearch('* Add pointers.', "'icon_class' => 'dashicons-welcome-learn-more',", 1, -3);
if (verbose) {
console.log(('Removed PointerPlus').italic);
}
}
if (this.modules.indexOf('CPT_Columns') === -1) {
fs.unlink(this.pluginSlug + '/admin/includes/CPT_Columns.php');
this.files.adminClass.rmsearch('* Load CPT_Columns', "'order' => \"-1\"", 1, -2);
if (verbose) {
console.log(('Removed CPT_Columns').italic);
}
}
//Snippet
if (this.adminPage === false) {
this.files.adminClass.rm("\n// Add an action link pointing to the options page.\n$plugin_basename = plugin_basename( plugin_dir_path( __DIR__ ) . $this->plugin_slug . '.php' );\nadd_filter( 'plugin_action_links_' . $plugin_basename, array( $this, 'add_action_links' ) );");
this.files.adminClass.rm("\n\n// Load admin style sheet and JavaScript.\nadd_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_styles' ) );\nadd_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_scripts' ) );\n\n// Add the options page and menu item.\nadd_action( 'admin_menu', array( $this, 'add_plugin_admin_menu' ) );");
this.files.adminClass.rm("\n/**\n * Register and enqueue admin-specific style sheet.\n *\n * @since 1.0.0\n *\n * @return null Return early if no settings page is registered.\n */\npublic function enqueue_admin_styles() {\n\nif ( ! isset( $this->plugin_screen_hook_suffix ) ) {\nreturn;\n}\n\n$screen = get_current_screen();\nif ( $this->plugin_screen_hook_suffix == $screen->id ) {\nwp_enqueue_style( $this->plugin_slug .'-admin-styles', plugins_url( 'assets/css/admin.css', __FILE__ ), array(), MyNewPlugin::VERSION );\n}\n\n}\n\n/**\n * Register and enqueue admin-specific JavaScript.\n *\n * @since 1.0.0\n *\n * @return null Return early if no settings page is registered.\n */\npublic function enqueue_admin_scripts() {\n\nif ( ! isset( $this->plugin_screen_hook_suffix ) ) {\nreturn;\n}\n\n$screen = get_current_screen();\nif ( $this->plugin_screen_hook_suffix == $screen->id ) {\nwp_enqueue_script( $this->plugin_slug . '-admin-script', plugins_url( 'assets/js/admin.js', __FILE__ ), array( 'jquery' ), MyNewPlugin::VERSION );\n}\n\n}\n\n/**\n * Register the administration menu for this plugin into the WordPress Dashboard menu.\n *\n * @since 1.0.0\n */\npublic function add_plugin_admin_menu() {\n\n/*\n * Add a settings page for this plugin to the Settings menu.\n *\n * NOTE: Alternative menu locations are available via WordPress administration menu functions.\n *\n * Administration Menus: http://codex.wordpress.org/Administration_Menus\n *\n * @TODO:\n *\n * - Change 'Page Title' to the title of your plugin admin page\n * - Change 'Menu Text' to the text for menu item for the plugin settings page\n * - Change 'manage_options' to the capability you see fit\n * For reference: http://codex.wordpress.org/Roles_and_Capabilities\n */\n$this->plugin_screen_hook_suffix = add_options_page(\n__( 'Page Title', $this->plugin_slug ),\n__( 'Menu Text', $this->plugin_slug ),\n'manage_options',\n$this->plugin_slug,\narray( $this, 'display_plugin_admin_page' )\n);\n\n}\n\n/**\n * Render the settings page for this plugin.\n *\n * @since 1.0.0\n */\npublic function display_plugin_admin_page() {\ninclude_once( 'views/admin.php' );\n}\n\n/**\n * Add settings action link to the plugins page.\n *\n * @since 1.0.0\n */\npublic function add_action_links( $links ) {\n\nreturn array_merge(\narray(\n'settings' => '<a href=\"' . admin_url( 'options-general.php?page=' . $this->plugin_slug ) . '\">' . __( 'Settings', $this->plugin_slug ) . '</a>'\n),\n$links\n);\n\n}");
} else {
if (this.snippet.indexOf('Support Dashboard At Glance Widget for CPT') === -1) {
this.files.adminClass.rmsearch('// Load admin style in dashboard for the At glance widget', "add_filter( 'dashboard_glance_items', array( $this, 'cpt_dashboard_support' ), 10, 1 );", 1, -1);
this.files.adminClass.rmsearch('* Add the counter of your CPTs in At Glance widget in the dashboard<br>', 'return $current_key;', 1, 5);
this.files.adminCss.rmsearch('#dashboard_right_now a.demo-count:before {', '', 0, 3);
}
}
if (verbose) {
console.log(('Cleaning in admin-class*.php').italic);
}
if (this.snippet.indexOf('Bubble notification on pending CPT') === -1) {
this.files.adminClass.rmsearch('//Add bubble notification for cpt pending', "add_action( 'admin_menu', array( $this, 'pending_cpt_bubble' ), 999 );", 1, -1);
this.files.adminClass.rmsearch("* Bubble Notification for pending cpt<br>", "return $current_key;", 1, -5);
if (verbose) {
console.log(('Removed Bubble Notification').italic);
}
}
if (this.snippet.indexOf('Import/Export settings system') === -1) {
this.files.adminClass.rmsearch("* Process a settings export from config", "wp_safe_redirect( admin_url( 'options-general.php?page=' . $this->plugin_slug ) );", 1, -3);
if (this.adminPage === true) {
this.files.adminView.rmsearch('<div id="tabs-3"', "<?php submit_button( __( 'Import' ), 'secondary', 'submit', false ); ?>", -2, -5);
}
if (verbose) {
console.log(('Removed Import/Export Settings').italic);
}
}
if (this.snippet.indexOf('Debug system (Debug Bar support)') === -1) {
fs.unlink(this.pluginSlug + '/admin/includes/debug.php');
this.files.adminClass.rmsearch("* Debug mode", "$debug->log( __( 'Plugin Loaded', $this->plugin_slug ) );", 1, -1);
if (verbose) {
console.log(('Removed Debug system').italic);
}
}
if (this.snippet.indexOf('Custom action') === -1 && this.snippet.indexOf('Custom filter') === -1 && this.snippet.indexOf('Custom shortcode') === -1) {
this.files.adminClass.rmsearch('* Define custom functionality.', '* http://codex.wordpress.org/Plugin_API#Hooks.2C_Actions_and_Filters', 1, -2);
}
if (this.snippet.indexOf('Custom action') === -1) {
this.files.adminClass.rm("add_action( '@TODO', array( $this, 'action_method_name' ) );\n");
this.files.adminClass.rmsearch('* NOTE: Actions are points in the execution of a page or process', '// @TODO: Define your action hook callback here', 1, -2);
if (verbose) {
console.log(('Removed Custom Action').italic);
}
}
if (this.snippet.indexOf('Custom filter') === -1) {
this.files.adminClass.rm("add_filter( '@TODO', array( $this, 'filter_method_name' ) );\n");
this.files.adminClass.rmsearch('* NOTE: Filters are points of execution in which WordPress modifies data', '// @TODO: Define your filter hook callback here', 1, -2);
if (verbose) {
console.log(('Removed Custom Filter').italic);
}
}
};
WpPluginBoilerplateGenerator.prototype.setPublicClass = function setPublicClass() {
this.files.publicClass.rm("* @TODO: Rename this class to a proper name for your plugin.\n *\n ");
this.files.publicClass.rm('* @TODO - Rename "' + this.pluginName + '" to the name of your plugin');
this.files.publicClass.rm('* @TODO - Rename "' + this.pluginSlug + '" to the name of your plugin' + "\n ");
//Assets - JS/CSS
if (this.publicResources.length === 0) {
this.files.publicClass.rm("\n\n// Load public-facing style sheet and JavaScript.");
}
if (this.publicResources.indexOf('JS') === -1) {
this.files.publicClass.rm("\nadd_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) );");
this.files.publicClass.rm("\n\n/**\n * Register and enqueues public-facing JavaScript files.\n *\n * @since " + this.pluginVersion + "\n */\npublic function enqueue_scripts() {\nwp_enqueue_script( $this->plugin_slug . '-plugin-script', plugins_url( 'assets/js/public.js', __FILE__ ), array( 'jquery' ), self::VERSION );\n}");
}
if (this.publicResources.indexOf('CSS') === -1) {
this.files.publicClass.rm("\nadd_action( 'wp_enqueue_scripts', array( $this, 'enqueue_styles' ) );");
this.files.publicClass.rm("\n\n/**\n * Register and enqueue public-facing style sheet.\n *\n * @since " + this.pluginVersion + "\n */\npublic function enqueue_styles() {\nwp_enqueue_style( $this->plugin_slug . '-plugin-styles', plugins_url( 'assets/css/public.css', __FILE__ ), array(), self::VERSION );\n}");
}
//Activate/deactivate
if (this.activateDeactivate.indexOf('Activate Method') === -1) {
this.files.publicClass.rmsearch('// Activate plugin when new blog is added', "add_action( 'wpmu_new_blog', array( $this, 'activate_new_site' ) );", 1, 1);
this.files.publicClass.rmsearch('* Fired when the plugin is activated.', '', 1, 32);
this.files.publicClass.rmsearch('* Fired when a new site is activated with a WPMU environment.', '', 1, 16);
this.files.publicClass.rmsearch('* Get all blog ids of blogs in the current network that are:', 'return $wpdb->get_col( $sql );', 1, -2);
this.files.publicClass.rmsearch("* Fired for each blog when the plugin is activated.", '', 1, 33);
if (verbose) {
console.log(('Removed Activate Method').italic);
}
}
if (this.activateDeactivate.indexOf('Deactivate Method') === -1) {
this.files.publicClass.rmsearch('* Fired when the plugin is deactivated.', '', 1, 32);
this.files.publicClass.rmsearch('* Fired for each blog when the plugin is deactivated.', '', 1, 10);
if (verbose) {
console.log(('Removed Deactive Method').italic);
}
}
//Repo
if (this.modules.indexOf('CPT_Core') === -1) {
this.files.publicClass.rmsearch('// Create Custom Post Type https://github.com/jtsternberg/CPT_Core/blob/master/README.md', "'map_meta_cap' => true", 0, -3);
}
if (this.modules.indexOf('Taxonomy_Core') === -1) {
this.files.publicClass.rmsearch('// Create Custom Taxonomy https://github.com/jtsternberg/Taxonomy_Core/blob/master/README.md', "), array( 'demo' )", 0, -2);
}
//Function
if (this.modules.indexOf('Template system (like WooCommerce)') === -1) {
this.files.publicClass.rm('//Override the template hierarchy for load /templates/content-demo.php');
this.files.publicClass.rm("add_filter( 'template_include', array( $this, 'load_content_demo' ) );");
this.files.publicClass.rmsearch('* Example for override the template system on the frontend', 'return $original_template;', 1, -3);
}
if (this.modules.indexOf('Requirements system on activation') === -1) {
fs.unlink(this.pluginSlug + '/public/includes/requirements.php');
fs.unlink(this.pluginSlug + '/languages/requirements.pot');
this.files.publicClass.rmsearch('//Requirements Detection System - read the doc in the library file', "'WP' => new WordPress_Requirement( '4.1.0' ),", -1, -2);
}
//Snippet
if (this.snippet.indexOf('CPTs on search box') === -1) {
this.files.publicClass.rmsearch('* Add support for custom CPT on the search box', 'return $query;', 1, 2);
this.files.publicClass.rm("add_filter( 'pre_get_posts', array( $this, 'filter_search' ) );");
if (verbose) {
console.log(('Removed CPTs on search box').italic);
}
}
if (this.snippet.indexOf('Custom action') === -1 && this.snippet.indexOf('Custom filter') === -1 && this.snippet.indexOf('Custom shortcode') === -1) {
this.files.publicClass.rmsearch('* Define custom functionality.', '* Refer To http://codex.wordpress.org/Plugin_API#Hooks.2C_Actions_and_Filters', 1, -2);
}
if (this.snippet.indexOf('Custom action') === -1) {
this.files.publicClass.rm("add_action( '@TODO', array( $this, 'action_method_name' ) );");
this.files.publicClass.rmsearch('* NOTE: Actions are points in the execution of a page or process', '// @TODO: Define your action hook callback here', 1, -2);
}
if (this.snippet.indexOf('Custom filter') === -1) {
this.files.publicClass.rm("add_filter( '@TODO', array( $this, 'filter_method_name' ) );");
this.files.publicClass.rmsearch('* NOTE: Filters are points of execution in which WordPress modifies data', '// @TODO: Define your filter hook callback here', 1, -2);
}
if (this.snippet.indexOf('Custom shortcode') === -1) {
this.files.publicClass.rm("add_shortcode( '@TODO', array( $this, 'shortcode_method_name' ) );");
this.files.publicClass.rmsearch('* NOTE: Shortcode simple set of functions for creating macro codes for use', '// @TODO: Define your shortcode here', 1, -4);
}
if (this.snippet.indexOf('Javascript DOM-based Routing') === -1) {
this.files.publicjs.rmsearch('* DOM-based Routing', '$(document).ready(UTIL.loadEvents);', 1, -1);
}
if (this.snippet.indexOf('Capability system') === -1) {
this.files.publicClass.rmsearch('* Array of capabilities by roles', '* Initialize the plugin by setting localization and loading public scripts', 1, 2);
this.files.publicClass.rmsearch('// @TODO: Define activation functionality here', '* Fired for each blog when the plugin is deactivated.', 2, 5);
this.files.publicClass.rm("'edit_others_posts' => 'edit_other_demo',");
}
if (this.snippet.indexOf('Add body class') === -1) {
this.files.publicClass.rmsearch('* Add class in the body on the frontend', 'return $classes;', 1, -2);
this.files.publicClass.rm("add_filter( 'body_class', array( $this, 'add_pn_class' ), 10, 3 );".replace(/pn_/g, this.pluginName.match(/\b(\w)/g).join('').toLowerCase() + '_'));
}
if (this.snippet.indexOf('wp_localize_script for PHP var to JS') === -1) {
this.files.publicClass.rm("add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_js_vars' ) );");
this.files.publicClass.rmsearch('* Print the PHP var in the HTML of the frontend for access by JavaScript', "'alert' => __( 'Hey! You have clicked the button!', $this->get_plugin_slug() )", 1, -4);
this.files.publicjs.rm('// Write in console log the PHP value passed in enqueue_js_vars in public/class-' + this.pluginSlug + '.php' + "\n");
this.files.publicjs.rm('console.log( tp_js_vars.alert );' + "\n");
}
};
WpPluginBoilerplateGenerator.prototype.setReadme = function setReadme() {
this.files.readme.add('@TODO: Plugin Name', this.pluginName);
};
WpPluginBoilerplateGenerator.prototype.setUninstall = function setUninstall() {
if (this.activateDeactivate.indexOf('Uninstall File') === -1) {
fs.unlink(this.files.uninstall.file);
delete this.files.uninstall;
} else if (this.snippet.indexOf('Capability system') === -1) {
this.files.uninstall.add('global $wpdb, $wp_roles;', 'global $wpdb;');
this.files.uninstall.rmsearch('$plugin_roles = array(', 'if ( is_multisite() ) {', -1, 0);
this.files.uninstall.rmsearch("switch_to_blog( $blog[ 'blog_id' ] );", 'restore_current_blog();', -19, 0);
this.files.uninstall.rmsearch('} else {', '$wp_roles->remove_cap( $cap );', -19, -4);
}
};
|
app/index.js
|
'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var fs = require('fs');
var request = require('request');
var Admzip = require('adm-zip');
var rmdir = require('rimraf');
var s = require('underscore.string');
var sys = require('sys');
var spawn = require('child_process').spawnSync || require('spawn-sync');
var colors = require('colors');
var Replacer = require('./replacer');
var cleanfolder = false;
var args = process.argv.slice(2);
var version = '1.1.1';
var is_default = false;
var verbose = false;
if (args[1] === 'dev') {
version = 'master';
}
if (args[1] === 'verbose' || args[2] === 'verbose') {
verbose = true;
}
/**
* Checks whether a path starts with or contains a hidden file or a folder.
* @param {string} path - The path of the file that needs to be validated.
* returns {boolean} - `true` if the source is blacklisted and otherwise `false`.
*/
var isUnixHiddenPath = function (path) {
return (/(^|.\/)\.+[^\/\.]/g).test(path);
};
/*
* Remove the unuseful file and folder, insert the index.php in the folders
*
* @param string path
*/
function cleanFolder(path) {
cleanParsing(path);
//Recursive scanning for the subfolder
var list = fs.readdirSync(path);
list.forEach(function (file) {
var pathrec = path + '/' + file;
var i = pathrec.lastIndexOf('.');
var ext = (i < 0) ? '' : pathrec.substr(i);
if (!isUnixHiddenPath(pathrec) && ext === '') {
var stat = fs.statSync(pathrec);
if (stat && stat.isDirectory()) {
if (verbose) {
console.log(('Parsing ' + pathrec).italic);
}
cleanParsing(path);
cleanFolder(pathrec);
}
}
});
}
function cleanParsing(pathrec) {
var default_file = [
'CONTRIBUTING.md', 'readme.md', 'phpunit.xml', 'packages.json', 'package.json', 'production.rb', 'composer.json',
'Gruntfile.js', 'README.md', 'example-functions.php', 'bower.json', 'Capfile', 'screenshot-1.png', 'component.json',
'.travis.yml', '.bowerrc', '.gitignore', 'README.txt', 'readme.txt', 'release.sh', 'pointerplus.php', '.DS_Store', 'widget-sample.php'
];
var default_folder = ['tests', 'bin', 'deploy', 'config'];
if (cleanfolder !== false) {
//Remove the unuseful files
default_file.forEach(function (element, index, array) {
if (fs.existsSync('./' + pathrec + '/' + element)) {
fs.unlink(pathrec + '/' + element, function (err) {
if (err) {
console.log(('Remove unuseful file error: ' + err).red);
}
});
if (verbose) {
console.log(('Removed ' + pathrec + '/' + element).italic);
}
}
});
//Remove the unuseful directory
default_folder.forEach(function (element, index, array) {
var isEmpty = false;
fs.stat('./' + pathrec + '/' + element, function (error, stats) {
fs.readdir('./' + pathrec + '/' + element, function (err, items) {
if (!items || !items.length) {
isEmpty = true;
}
});
if (!error || isEmpty) {
rmdir('./' + pathrec + '/' + element, function (err) {
if (err) {
console.log(('Remove unuseful directory error:' + err).red);
}
if (verbose) {
console.log(('Removed ' + pathrec + '/' + element).italic);
}
});
}
});
});
}
//Insert a blank index.php
fs.exists('./' + pathrec + '/index.php', function (exists) {
if (!exists) {
fs.writeFile('./' + pathrec + '/index.php',
"<?php // Silence is golden",
'utf8', function () {
});
if (verbose) {
console.log(('Created ' + pathrec + '/index.php').italic);
}
}
});
}
var WpPluginBoilerplateGenerator = module.exports = function WpPluginBoilerplateGenerator(args, options, config) {
var self = this,
default_file;
yeoman.generators.Base.apply(this, arguments);
this.on('end', function () {
//Generate the bash script for download the git submodules
//Initialize git and clean the submodules not required
var submodulessh = ['#!/bin/sh',
'set -e',
'git init',
"git config -f .gitmodules --get-regexp '^submodule..*.path$' |",
'while read path_key path',
' do',
" url_key=$(echo $path_key | sed 's/.path/.url/')",
' url=$(git config -f .gitmodules --get $url_key)',
' path="./$path"',
' if [ -d "$path" ]; then',
' rm -r $path',
' echo "Add $url in $path"',
' git submodule add -f $url $path >> /dev/null',
' fi',
' done',
'rm $0'
].join('\n');
fs.writeFile(self.pluginSlug + '/submodules.sh', submodulessh, 'utf8',
function (err) {
if (err) {
console.log(('Error on writing submodules.sh:' + err).red);
process.exit();
} else {
fs.chmodSync(process.cwd() + '/' + self.pluginSlug + '/submodules.sh', '0777');
console.log(('Generate git config on the fly').white);
//Execute the magic for clean, destroy, brick, brock the code
var key = null;
for (key in self.files) {
if (self.files.hasOwnProperty(key)) {
self.files[key].sed();
if (verbose) {
console.log(('Sed executed on ' + key).italic);
}
}
}
console.log(('Parsed all the files').white);
//Call the bash script
console.log(('Download submodules (wait a moment)').white);
var submodule = spawn(process.cwd() + '/' + self.pluginSlug + '/submodules.sh', [],
{
cwd: process.cwd() + '/' + self.pluginSlug + '/'
});
if (submodule.status !== 0) {
console.log(('Error on submodule:' + submodule.stderr).blue);
process.exit();
} else {
if (self.defaultValues.git !== true) {
fs.unlink(self.pluginSlug + '/.gitmodules', function (error) {
if (error) {
console.log(('Error on removing .gitmodules:' + error).red);
}
});
rmdir(self.pluginSlug + '/.git', function (error) {
if (error) {
console.log(('Error on removing .git:' + error).red);
}
});
console.log(('Remove git config generated').white);
}
//Clean all the folders!!
if (self.modules.indexOf('CPT_Core') !== -1) {
cleanFolder(self.pluginSlug + '/includes/CPT_Core');
}
if (self.modules.indexOf('Taxonomy_Core') !== -1) {
cleanFolder(self.pluginSlug + '/includes/Taxonomy_Core');
}
if (self.modules.indexOf('Widget-Boilerplate') !== -1) {
cleanFolder(self.pluginSlug + '/includes/Widget-Boilerplate');
cleanFolder(self.pluginSlug + '/includes/Widget-Boilerplate/widget-boilerplate');
}
if (self.modules.indexOf('CMB2') !== -1) {
cleanFolder(self.pluginSlug + '/admin/includes/CMB2');
}
if (self.modules.indexOf('PointerPlus') !== -1) {
cleanFolder(self.pluginSlug + '/admin/includes/PointerPlus');
}
if (self.modules.indexOf('Template system (like WooCommerce)') !== -1) {
cleanFolder(self.pluginSlug + '/templates');
}
if (self.modules.indexOf('WP-Contextual-Help') !== -1) {
if (cleanfolder !== false) {
rmdir(self.pluginSlug + +'/admin/includes/WP-Contextual-Help/assets/', function (err) {
});
}
cleanFolder(self.pluginSlug + '/admin/includes/WP-Contextual-Help');
}
//Console.log are cool and bowtie are cool!
console.log(('Inserted index.php files in all the folders').white);
console.log(('All done!').white);
}
}
}
);
});
//Yeoman greet the user.
console.log(this.yeoman);
//Check the default file for the default values, I have already said default?
if (fs.existsSync(__dirname + '/../default-values.json')) {
default_file = path.join(__dirname, '../default-values.json');
if (verbose) {
console.log(('Config loaded').yellow);
}
} else if (fs.existsSync(process.cwd() + '/default-values.json')) {
default_file = process.cwd() + '/default-values.json';
if (verbose) {
console.log(('Config loaded').yellow);
}
} else {
console.log('--------------------------');
console.log(('You can create the file ' + process.cwd() + '/default-values.json with default values in the parent folder! Use the default-values-example.json as a template.').bold);
console.log('--------------------------');
default_file = path.join(__dirname, '../default-values-example.json');
is_default = true;
}
this.defaultValues = JSON.parse(this.readFileAsString(default_file));
};
util.inherits(WpPluginBoilerplateGenerator, yeoman.generators.Base);
WpPluginBoilerplateGenerator.prototype.askFor = function askFor() {
var cb = this.async(),
prompts = [];
//The boilerplate have the steroids then there are many questions. I know I'm not funny.
prompts = [{
name: 'name',
message: 'What do you want to call your plugin?',
default: 'My New Plugin'
}, {
name: 'pluginVersion',
message: 'What is your new plugin\'s version?',
default: '1.0.0'
}, {
name: 'author',
message: 'What is your name?',
default: this.defaultValues.author.name
}, {
name: 'authorEmail',
message: 'What is your e-mail?',
default: this.defaultValues.author.email
}, {
name: 'authorURI',
message: 'What is your URL?',
default: this.defaultValues.author.url
}, {
name: 'copyright',
message: 'What goes in copyright tags?',
default: this.defaultValues.author.copyright
}, {
type: 'checkbox',
name: 'publicResources',
message: 'Which resources your public site needs?',
choices: [{name: 'JS', checked: true}, {name: 'CSS', checked: true}]
}, {
type: 'checkbox',
name: 'activateDeactivate',
message: 'Which resources your plugin needs?',
choices: [
{name: 'Activate Method', checked: true},
{name: 'Deactivate Method', checked: true},
{name: 'Uninstall File', checked: true}]
}, {
type: 'confirm',
name: 'adminPage',
message: 'Does your plugin need an admin page?'
}, {
type: 'checkbox',
name: 'modules',
message: 'Which library your plugin needs?',
choices: [
{name: 'CPT_Core', checked: true},
{name: 'CPT_Columns', checked: true},
{name: 'Taxonomy_Core', checked: true},
{name: 'Widget Helper', checked: true},
{name: 'CMB2', checked: true},
{name: 'WP-Contextual-Help', checked: true},
{name: 'WP-Admin-Notice', checked: true},
{name: 'PointerPlus', checked: true},
{name: 'Fake Page Class', checked: true},
{name: 'Template system (like WooCommerce)', checked: true},
{name: 'Language function support (WPML/Ceceppa Multilingua/Polylang)', checked: true},
{name: 'Requirements system on activation', checked: true}
]
}, {
type: 'checkbox',
name: 'snippet',
message: 'Which snippet your plugin needs?',
choices: [
{name: 'Support Dashboard At Glance Widget for CPT', checked: true},
{name: 'Javascript DOM-based Routing', checked: true},
{name: 'Bubble notification on pending CPT', checked: true},
{name: 'Import/Export settings system', checked: true},
{name: 'Capability system', checked: true},
{name: 'Debug system (Debug Bar support)', checked: true},
{name: 'Add body class', checked: true},
{name: 'wp_localize_script for PHP var to JS', checked: true},
{name: 'CPTs on search box', checked: true},
{name: 'Custom action', checked: true},
{name: 'Custom filter', checked: true},
{name: 'Custom shortcode', checked: true}
]
}, {
type: 'confirm',
name: 'git',
message: 'Do you need an initialized git repo?'
}, {
type: 'confirm',
name: 'cleanFolder',
message: 'Do you want clean the folders?'
}, {
type: 'confirm',
name: 'saveSettings',
message: 'Do you want save the configuration for reuse it?'
}];
if (is_default === false) {
if (this.defaultValues.name !== '') {
if (fs.existsSync('./' + s.slugify(this.defaultValues.name)) && this.defaultValues.name !== undefined) {
console.log(('Warning folder ' + s.slugify(this.defaultValues.name) + ' already exist, change the name of the plugin!').red);
}
prompts[0].default = this.defaultValues.name;
}
if (this.defaultValues.version !== '') {
prompts[1].default = this.defaultValues.pluginVersion;
}
if (this.defaultValues.publicResources !== '') {
if (this.defaultValues.publicResources === undefined) {
prompts[6].choices.forEach(function (element, index, array) {
prompts[6].choices[index].checked = false;
});
} else {
var defaultvalues = this.defaultValues.publicResources;
prompts[6].choices.forEach(function (element, index, array) {
prompts[6].choices[index].checked = false;
defaultvalues.forEach(function (element_z, index_z, array_z) {
if (prompts[6].choices[index].name === element_z) {
prompts[6].choices[index].checked = true;
}
});
});
}
}
if (this.defaultValues.activateDeactivate !== '') {
if (this.defaultValues.activateDeactivate === undefined) {
prompts[7].choices.forEach(function (element, index, array) {
prompts[7].choices[index].checked = false;
});
} else {
var defaultvalues = this.defaultValues.activateDeactivate;
prompts[7].choices.forEach(function (element, index, array) {
prompts[7].choices[index].checked = false;
defaultvalues.forEach(function (element_z, index_z, array_z) {
if (prompts[7].choices[index].name === element_z) {
prompts[7].choices[index].checked = true;
}
});
});
}
}
if (this.defaultValues.adminPage !== '') {
prompts[8].default = this.defaultValues.adminPage;
}
if (this.defaultValues.modules === undefined) {
prompts[9].choices.forEach(function (element, index, array) {
prompts[9].choices[index].checked = false;
});
} else {
var defaultvalues = this.defaultValues.modules;
prompts[9].choices.forEach(function (element, index, array) {
prompts[9].choices[index].checked = false;
defaultvalues.forEach(function (element_z, index_z, array_z) {
if (prompts[9].choices[index].name === element_z) {
prompts[9].choices[index].checked = true;
}
});
});
}
if (this.defaultValues.snippet === undefined) {
prompts[10].choices.forEach(function (element, index, array) {
prompts[10].choices[index].checked = false;
});
} else {
var defaultvalues = this.defaultValues.snippet;
prompts[10].choices.forEach(function (element, index, array) {
prompts[10].choices[index].checked = false;
defaultvalues.forEach(function (element_z, index_z, array_z) {
if (prompts[10].choices[index].name === element_z) {
prompts[10].choices[index].checked = true;
}
});
});
}
if (this.defaultValues.git !== '') {
prompts[11].default = this.defaultValues.git;
}
if (this.defaultValues.cleanFolder !== '') {
prompts[12].default = this.defaultValues.cleanFolder;
}
if (this.defaultValues.saveSettings !== '') {
prompts[13].default = this.defaultValues.saveSettings;
}
}
this.prompt(prompts, function (props) {
this.pluginName = props.name;
this.pluginSlug = s.slugify(props.name);
this.pluginClassName = s.titleize(props.name).replace(/ /g, "_");
this.author = props.author;
this.authorEmail = props.authorEmail;
this.authorURI = props.authorURI;
this.pluginVersion = props.pluginVersion;
this.pluginCopyright = props.copyright;
this.publicResources = props.publicResources;
this.activateDeactivate = props.activateDeactivate;
this.modules = props.modules;
this.snippet = props.snippet;
this.adminPage = props.adminPage;
//Set the path of the files
this.files = {
primary: new Replacer(this.pluginSlug + '/' + this.pluginSlug + '.php', this),
publicClass: new Replacer(this.pluginSlug + '/public/class-' + this.pluginSlug + '.php', this),
adminClass: new Replacer(this.pluginSlug + '/admin/class-' + this.pluginSlug + '-admin.php', this),
adminCss: new Replacer(this.pluginSlug + '/admin/assets/css/admin.css', this),
publicView: new Replacer(this.pluginSlug + '/public/views/public.php', this),
adminView: new Replacer(this.pluginSlug + '/admin/views/admin.php', this),
uninstall: new Replacer(this.pluginSlug + '/uninstall.php', this),
readme: new Replacer(this.pluginSlug + '/README.txt', this),
gitmodules: new Replacer(this.pluginSlug + '/.gitmodules', this),
template: new Replacer(this.pluginSlug + '/includes/template.php', this),
publicjs: new Replacer(this.pluginSlug + '/public/assets/js/public.js', this),
debug: new Replacer(this.pluginSlug + '/admin/includes/debug.php', this),
requirements: new Replacer(this.pluginSlug + '/public/includes/requirements.php', this),
language: new Replacer(this.pluginSlug + '/includes/language.php', this),
fakepage: new Replacer(this.pluginSlug + '/includes/fake-page.php', this)
};
if (props.saveSettings === true) {
var cleaned = props;
delete cleaned['authorEmail'];
delete cleaned['authorEmail'];
delete cleaned['copyright'];
cleaned.author = {'name': props.author, 'email': this.authorEmail, 'url': this.authorURI, 'copyright': this.pluginCopyright};
fs.writeFile(props.name + '.json', JSON.stringify(cleaned, null, 2), function (err) {
if (err) {
console.log('Error on save your json config file: ' + err);
} else {
console.log(("JSON saved to " + props.name + '.json').blue);
}
});
}
cb();
}.bind(this));
};
WpPluginBoilerplateGenerator.prototype.download = function download() {
var cb = this.async(),
self = this,
path = 'http://github.com/Mte90/WordPress-Plugin-Boilerplate-Powered/archive/' + version + '.zip',
zip = "";
//Force the remove of the same plugin folder
if (args[2] === 'force' || args[3] === 'force' || args[4] === 'force') {
rmdir.sync('./' + self.pluginSlug, function (error) {
if (error) {
console.log(('Error on removing plugin folder' + error).red);
}
});
rmdir.sync('./plugin_temp', function (error) {
if (error) {
console.log(('Error on removing plugin temp folder' + error).red);
}
});
//Check plugin folder if exist
} else if (fs.existsSync('./' + self.pluginSlug)) {
console.log(('Error: Folder ' + self.pluginSlug + ' already exist, change the name of the plugin!').red);
process.exit(1);
}
//Check if exist the plugin.zip
if (fs.existsSync(process.cwd() + '/plugin.zip')) {
console.log(('Extract Plugin boilerplate').white);
zip = new Admzip('./plugin.zip');
zip.extractAllTo('plugin_temp', true);
fs.rename('./plugin_temp/WordPress-Plugin-Boilerplate-Powered-' + version + '/.gitmodules', './plugin_temp/WordPress-Plugin-Boilerplate-Powered-' + version + '/plugin-name/.gitmodules', function (err) {
if (err) {
console.log(('Error: Maybe you want the development version? Call this generator with the dev parameter').red);
process.exit(1);
}
});
fs.rename('./plugin_temp/WordPress-Plugin-Boilerplate-Powered-' + version + '/plugin-name/', './' + self.pluginSlug, function () {
rmdir('plugin_temp', function (error) {
if (error) {
console.log(('Error on removing plugin temp folder' + error).red);
}
cb();
});
});
//else download the zip
} else {
console.log(('Downloading the WP Plugin Boilerplate Powered...').white);
//Do you want the development version?
if (version === 'master') {
path = 'https://github.com/Mte90/WordPress-Plugin-Boilerplate-Powered/archive/master.zip';
}
request(path)
.pipe(fs.createWriteStream('plugin.zip'))
.on('close', function () {
zip = new Admzip('./plugin.zip');
console.log(('File downloaded').white);
zip.extractAllTo('plugin_temp', true);
fs.rename('./plugin_temp/WordPress-Plugin-Boilerplate-Powered-' + version + '/.gitmodules', './plugin_temp/WordPress-Plugin-Boilerplate-Powered-' + version + '/plugin-name/.gitmodules', function (error) {
if (error) {
console.log(('Error on move gitmodules:' + error).red);
}
});
fs.rename('./plugin_temp/WordPress-Plugin-Boilerplate-Powered-' + version + '/plugin-name/', './' + self.pluginSlug, function () {
rmdir('plugin_temp', function (error) {
if (error) {
console.log(('Error on move plugin temp folder:' + error).red);
}
cb();
});
});
fs.unlink('plugin.zip');
});
}
};
WpPluginBoilerplateGenerator.prototype.setFiles = function setFiles() {
cleanfolder = this.cleanFolder;
//Change path of gitmodules
this.files.gitmodules.add(new RegExp(this.pluginSlug + '/', "g"), '');
this.files.gitmodules.add(new RegExp('[email protected]:', "g"), 'https://github.com/');
//Rename files
fs.rename(this.pluginSlug + '/plugin-name.php', this.files.primary.file, function (err) {
if (err) {
console.log(('Error on rename plugin-name.php:' + err).red);
}
});
fs.rename(this.pluginSlug + '/admin/class-plugin-name-admin.php', this.files.adminClass.file, function (err) {
if (err) {
console.log(('Error on rename class-plugin-name-admin.php:' + err).red);
}
});
fs.rename(this.pluginSlug + '/public/class-plugin-name.php', this.files.publicClass.file, function (err) {
if (err) {
console.log(('Error on rename class-plugin-name.php:' + err).red);
}
});
fs.rename(this.pluginSlug + '/languages/plugin-name.pot', this.pluginSlug + '/languages/' + this.pluginSlug + '.pot', function (err) {
if (err) {
console.log(('Error on rename plugin-name.pot:' + err).red);
}
});
console.log(('Renamed files').white);
};
WpPluginBoilerplateGenerator.prototype.setPrimary = function setPrimary() {
this.files.primary.add(/Plugin Name:( {7})@TODO/g, 'Plugin Name: ' + this.pluginName);
this.files.primary.add(/Version:( {11})1\.0\.0/g, 'Version: ' + this.pluginVersion);
this.files.primary.add(/Author:( {12})@TODO/g, 'Author: ' + this.author);
this.files.primary.add(/Author URI:( {8})@TODO/g, 'Author URI: ' + this.authorURI);
this.files.primary.rm("/*\n * @TODO:\n *\n * - replace `class-" + this.pluginSlug + ".php` with the name of the plugin's class file\n *\n */");
this.files.primary.rm(" * @TODO:\n *\n * - replace `class-" + this.pluginSlug + "-admin.php` with the name of the plugin's admin file\n");
this.files.primary.rm(" *\n * @TODO:\n *\n * - replace " + this.pluginClassName + " with the name of the class defined in\n * `class-" + this.pluginSlug + ".php`\n");
this.files.primary.rm("/*\n * @TODO:\n *\n * - replace " + this.pluginClassName + " with the name of the class defined in\n * `class-" + this.pluginSlug + ".php`\n */");
this.files.primary.rm(" * - replace " + this.pluginClassName + "_Admin with the name of the class defined in\n * `class-" + this.pluginSlug + "-admin.php`\n");
this.files.primary.rm(" * @TODO:\n *\n * - replace `class-plugin-admin.php` with the name of the plugin's admin file\n * - replace " + this.pluginClassName + "Admin with the name of the class defined in\n * `class-" + this.pluginSlug + "-admin.php`\n *\n");
if (verbose) {
console.log(('Added info marker replace on plugin.php').italic);
}
//Activate/deactivate
if (this.activateDeactivate.indexOf('Activate Method') === -1 && this.activateDeactivate.indexOf('Deactivate Method') === -1) {
this.files.primary.rm("\n/*\n * Register hooks that are fired when the plugin is activated or deactivated.\n * When the plugin is deleted, the uninstall.php file is loaded.\n */\nregister_activation_hook( __FILE__, array( '" + this.pluginClassName + "', 'activate' ) );\nregister_deactivation_hook( __FILE__, array( '" + this.pluginClassName + "', 'deactivate' ) );\n");
}
if (this.activateDeactivate.indexOf('Activate Method') === -1) {
this.files.primary.rm("\nregister_activation_hook( __FILE__, array( '" + this.pluginClassName + "', 'activate' ) );");
}
if (this.activateDeactivate.indexOf('Deactivate Method') === -1) {
this.files.primary.rm("\nregister_deactivation_hook( __FILE__, array( '" + this.pluginClassName + "', 'deactivate' ) );");
}
//Repo
if (this.modules.indexOf('CPT_Core') === -1 && this.modules.indexOf('Taxonomy_Core') === -1) {
this.files.primary.rm("\n/*\n * Load library for simple and fast creation of Taxonomy and Custom Post Type\n *\n */");
}
if (this.modules.indexOf('CPT_Core') === -1) {
rmdir(this.pluginSlug + '/includes/CPT_Core', function (error) {
if (error) {
console.log((error).red);
}
});
this.files.primary.rm("require_once( plugin_dir_path( __FILE__ ) . 'includes/CPT_Core/CPT_Core.php' );");
this.files.primary.rm("and Custom Post Type");
if (verbose) {
console.log(('CPT_Core removed').italic);
}
}
if (this.modules.indexOf('Taxonomy_Core') === -1) {
rmdir(this.pluginSlug + '/includes/Taxonomy_Core', function (error) {
if (error) {
console.log((error).red);
}
});
this.files.primary.rm("require_once( plugin_dir_path( __FILE__ ) . 'includes/Taxonomy_Core/Taxonomy_Core.php' );");
this.files.primary.rm("Taxonomy and");
if (verbose) {
console.log(('Taxnomy_Core removed').italic);
}
}
if (this.modules.indexOf('Widget Helper') === -1) {
rmdir(this.pluginSlug + '/includes/Widget-Helper', function (error) {
if (error) {
console.log((error).red);
}
});
this.files.primary.rmsearch(' * Load Widgets Helper', '', 1, 3);
if (verbose) {
console.log(('Removed Widgets Helper').italic);
}
}
//Function
if (this.modules.indexOf('Fake Page Class') === -1) {
fs.unlink(this.pluginSlug + '/includes/fake-page.php');
this.files.primary.rmsearch(' * Load Fake Page class', "'post content' => 'This is the fake page content'", 1, -3);
if (verbose) {
console.log(('Removed Fake Class').italic);
}
}
if (this.modules.indexOf('Template system (like WooCommerce)') === -1) {
fs.unlink(this.pluginSlug + '/includes/template.php');
rmdir(this.pluginSlug + '/templates', function (error) {
if (error) {
console.log((error).red);
}
});
this.files.primary.rmsearch(' * Load template system', '', 1, 3);
if (verbose) {
console.log(('Removed Template System').italic);
}
}
if (this.modules.indexOf('Language function support (WPML/Ceceppa Multilingua/Polylang)') === -1) {
fs.unlink(this.pluginSlug + '/includes/language.php');
this.files.primary.rmsearch(' * Load Language wrapper function for WPML/Ceceppa Multilingua/Polylang', '', 1, 3);
if (verbose) {
console.log(('Removed Language function').italic);
}
}
};
WpPluginBoilerplateGenerator.prototype.setAdminClass = function setAdminClass() {
this.files.adminClass.rm(" * @TODO: Rename this class to a proper name for your plugin.\n *\n");
this.files.adminClass.rm("*\n * Call $plugin_slug from public plugin class.\n *\n * @TODO:\n *\n * - Rename \"" + this.pluginClassName + "\" to the name of your initial plugin class\n *\n */\n");
this.files.adminClass.rmsearch('* Register and enqueue admin-specific style sheet.', '* - Rename "Plugin_Name" to the name your plugin', -2, -1);
this.files.adminClass.rmsearch('* Register and enqueue admin-specific JavaScript.', '* - Rename "Plugin_Name" to the name your plugin', -2, -1);
if (verbose) {
console.log(('Added info marker in admin-class*.php').italic);
}
//Repo
if (this.modules.indexOf('CMB2') === -1) {
rmdir(this.pluginSlug + '/admin/includes/CMB2', function (error) {
if (error) {
console.log((error).red);
}
});
rmdir(this.pluginSlug + '/admin/includes/CMB2-Shortcode', function (error) {
if (error) {
console.log((error).red);
}
});
this.files.adminClass.rm("$settings[ 1 ] = get_option( $this->plugin_slug . '-settings-second' );");
this.files.adminClass.rm("update_option( $this->plugin_slug . '-settings-second', get_object_vars( $settings[ 1 ] ) );");
this.files.adminClass.rmsearch('* CMB 2 for metabox and many other cool things!', "add_filter( 'cmb2_meta_boxes', array( $this, 'cmb_demo_metaboxes' ) );", 1, 0);
this.files.publicClass.rm("// Check for the CMB2 Shortcode Button");
this.files.publicClass.rm("// In bundle with the boilerplate https://github.com/jtsternberg/Shortcode_Button");
if (this.adminPage === true) {
this.files.adminView.rmsearch('<div id="tabs-1">', "cmb2_metabox_form( $option_fields, $this->plugin_slug . '-settings' );", -2, -2);
this.files.adminView.rmsearch('<div id="tabs-2">', "cmb2_metabox_form( $option_fields_second, $this->plugin_slug . '-settings-second' );", -2, -2);
}
if (verbose) {
console.log(('Removed CMB2').italic);
}
}
if (this.modules.indexOf('WP-Contextual-Help') === -1) {
rmdir(this.pluginSlug + '/admin/includes/WP-Contextual-Help', function (error) {
if (error) {
console.log((error).red);
}
});
rmdir(this.pluginSlug + '/help-docs', function (error) {
if (error) {
console.log((error).red);
}
});
this.files.adminClass.rmsearch('* Load Wp_Contextual_Help for the help tabs', "add_action( 'init', array( $this, 'contextual_help' ) );", 1, -1);
this.files.adminClass.rmsearch('* Filter for change the folder of Contextual Help', "$paths[] = plugin_dir_path( __FILE__ ) . '../help-docs/';", 1, -3);
this.files.adminClass.rmsearch('* Filter for change the folder image of Contextual Help', "$paths[] = plugin_dir_path( __FILE__ ) . '../help-docs/img';", 1, -3);
this.files.adminClass.rmsearch('* Contextual Help, docs in /help-docs folter', "'page' => 'settings_page_' . $this->plugin_slug,", 1, -4);
if (verbose) {
console.log(('Removed Wp_Contextual_Help').italic);
}
}
if (this.modules.indexOf('WP-Admin-Notice') === -1) {
rmdir(this.pluginSlug + '/admin/includes/WP-Admin-Notice', function (error) {
if (error) {
console.log((error).red);
}
});
this.files.adminClass.rmsearch('* Load Wp_Admin_Notice for the notices in the backend', "new WP_Admin_Notice( __( 'Error Messages' ), 'error' );", 1, -1);
if (verbose) {
console.log(('Removed WP-Admin-Notice').italic);
}
}
if (this.modules.indexOf('PointerPlus') === -1) {
rmdir(this.pluginSlug + '/admin/includes/PointerPlus', function (error) {
if (error) {
console.log((error).red);
}
});
this.files.adminClass.rmsearch('* Load PointerPlus for the Wp Pointer', "add_filter( 'pointerplus_list', array( $this, 'custom_initial_pointers' ), 10, 2 );", 1, -1);
this.files.adminClass.rmsearch('* Add pointers.', "'icon_class' => 'dashicons-welcome-learn-more',", 1, -3);
if (verbose) {
console.log(('Removed PointerPlus').italic);
}
}
if (this.modules.indexOf('CPT_Columns') === -1) {
fs.unlink(this.pluginSlug + '/admin/includes/CPT_Columns.php');
this.files.adminClass.rmsearch('* Load CPT_Columns', "'order' => \"-1\"", 1, -2);
if (verbose) {
console.log(('Removed CPT_Columns').italic);
}
}
//Snippet
if (this.adminPage === false) {
this.files.adminClass.rm("\n// Add an action link pointing to the options page.\n$plugin_basename = plugin_basename( plugin_dir_path( __DIR__ ) . $this->plugin_slug . '.php' );\nadd_filter( 'plugin_action_links_' . $plugin_basename, array( $this, 'add_action_links' ) );");
this.files.adminClass.rm("\n\n// Load admin style sheet and JavaScript.\nadd_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_styles' ) );\nadd_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_scripts' ) );\n\n// Add the options page and menu item.\nadd_action( 'admin_menu', array( $this, 'add_plugin_admin_menu' ) );");
this.files.adminClass.rm("\n/**\n * Register and enqueue admin-specific style sheet.\n *\n * @since 1.0.0\n *\n * @return null Return early if no settings page is registered.\n */\npublic function enqueue_admin_styles() {\n\nif ( ! isset( $this->plugin_screen_hook_suffix ) ) {\nreturn;\n}\n\n$screen = get_current_screen();\nif ( $this->plugin_screen_hook_suffix == $screen->id ) {\nwp_enqueue_style( $this->plugin_slug .'-admin-styles', plugins_url( 'assets/css/admin.css', __FILE__ ), array(), MyNewPlugin::VERSION );\n}\n\n}\n\n/**\n * Register and enqueue admin-specific JavaScript.\n *\n * @since 1.0.0\n *\n * @return null Return early if no settings page is registered.\n */\npublic function enqueue_admin_scripts() {\n\nif ( ! isset( $this->plugin_screen_hook_suffix ) ) {\nreturn;\n}\n\n$screen = get_current_screen();\nif ( $this->plugin_screen_hook_suffix == $screen->id ) {\nwp_enqueue_script( $this->plugin_slug . '-admin-script', plugins_url( 'assets/js/admin.js', __FILE__ ), array( 'jquery' ), MyNewPlugin::VERSION );\n}\n\n}\n\n/**\n * Register the administration menu for this plugin into the WordPress Dashboard menu.\n *\n * @since 1.0.0\n */\npublic function add_plugin_admin_menu() {\n\n/*\n * Add a settings page for this plugin to the Settings menu.\n *\n * NOTE: Alternative menu locations are available via WordPress administration menu functions.\n *\n * Administration Menus: http://codex.wordpress.org/Administration_Menus\n *\n * @TODO:\n *\n * - Change 'Page Title' to the title of your plugin admin page\n * - Change 'Menu Text' to the text for menu item for the plugin settings page\n * - Change 'manage_options' to the capability you see fit\n * For reference: http://codex.wordpress.org/Roles_and_Capabilities\n */\n$this->plugin_screen_hook_suffix = add_options_page(\n__( 'Page Title', $this->plugin_slug ),\n__( 'Menu Text', $this->plugin_slug ),\n'manage_options',\n$this->plugin_slug,\narray( $this, 'display_plugin_admin_page' )\n);\n\n}\n\n/**\n * Render the settings page for this plugin.\n *\n * @since 1.0.0\n */\npublic function display_plugin_admin_page() {\ninclude_once( 'views/admin.php' );\n}\n\n/**\n * Add settings action link to the plugins page.\n *\n * @since 1.0.0\n */\npublic function add_action_links( $links ) {\n\nreturn array_merge(\narray(\n'settings' => '<a href=\"' . admin_url( 'options-general.php?page=' . $this->plugin_slug ) . '\">' . __( 'Settings', $this->plugin_slug ) . '</a>'\n),\n$links\n);\n\n}");
} else {
if (this.snippet.indexOf('Support Dashboard At Glance Widget for CPT') === -1) {
this.files.adminClass.rmsearch('// Load admin style in dashboard for the At glance widget', "add_filter( 'dashboard_glance_items', array( $this, 'cpt_dashboard_support' ), 10, 1 );", 1, -1);
this.files.adminClass.rmsearch('* Add the counter of your CPTs in At Glance widget in the dashboard<br>', 'return $current_key;', 1, 5);
this.files.adminCss.rmsearch('#dashboard_right_now a.demo-count:before {', '', 0, 3);
}
}
if (verbose) {
console.log(('Cleaning in admin-class*.php').italic);
}
if (this.snippet.indexOf('Bubble notification on pending CPT') === -1) {
this.files.adminClass.rmsearch('//Add bubble notification for cpt pending', "add_action( 'admin_menu', array( $this, 'pending_cpt_bubble' ), 999 );", 1, -1);
this.files.adminClass.rmsearch("* Bubble Notification for pending cpt<br>", "return $current_key;", 1, -5);
if (verbose) {
console.log(('Removed Bubble Notification').italic);
}
}
if (this.snippet.indexOf('Import/Export settings system') === -1) {
this.files.adminClass.rmsearch("* Process a settings export from config", "wp_safe_redirect( admin_url( 'options-general.php?page=' . $this->plugin_slug ) );", 1, -3);
if (this.adminPage === true) {
this.files.adminView.rmsearch('<div id="tabs-3"', "<?php submit_button( __( 'Import' ), 'secondary', 'submit', false ); ?>", -2, -5);
}
if (verbose) {
console.log(('Removed Import/Export Settings').italic);
}
}
if (this.snippet.indexOf('Debug system (Debug Bar support)') === -1) {
fs.unlink(this.pluginSlug + '/admin/includes/debug.php');
this.files.adminClass.rmsearch("* Debug mode", "$debug->log( __( 'Plugin Loaded', $this->plugin_slug ) );", 1, -1);
if (verbose) {
console.log(('Removed Debug system').italic);
}
}
if (this.snippet.indexOf('Custom action') === -1 && this.snippet.indexOf('Custom filter') === -1 && this.snippet.indexOf('Custom shortcode') === -1) {
this.files.adminClass.rmsearch('* Define custom functionality.', '* http://codex.wordpress.org/Plugin_API#Hooks.2C_Actions_and_Filters', 1, -2);
}
if (this.snippet.indexOf('Custom action') === -1) {
this.files.adminClass.rm("add_action( '@TODO', array( $this, 'action_method_name' ) );\n");
this.files.adminClass.rmsearch('* NOTE: Actions are points in the execution of a page or process', '// @TODO: Define your action hook callback here', 1, -2);
if (verbose) {
console.log(('Removed Custom Action').italic);
}
}
if (this.snippet.indexOf('Custom filter') === -1) {
this.files.adminClass.rm("add_filter( '@TODO', array( $this, 'filter_method_name' ) );\n");
this.files.adminClass.rmsearch('* NOTE: Filters are points of execution in which WordPress modifies data', '// @TODO: Define your filter hook callback here', 1, -2);
if (verbose) {
console.log(('Removed Custom Filter').italic);
}
}
};
WpPluginBoilerplateGenerator.prototype.setPublicClass = function setPublicClass() {
this.files.publicClass.rm("* @TODO: Rename this class to a proper name for your plugin.\n *\n ");
this.files.publicClass.rm('* @TODO - Rename "' + this.pluginName + '" to the name of your plugin');
this.files.publicClass.rm('* @TODO - Rename "' + this.pluginSlug + '" to the name of your plugin' + "\n ");
//Assets - JS/CSS
if (this.publicResources.length === 0) {
this.files.publicClass.rm("\n\n// Load public-facing style sheet and JavaScript.");
}
if (this.publicResources.indexOf('JS') === -1) {
this.files.publicClass.rm("\nadd_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) );");
this.files.publicClass.rm("\n\n/**\n * Register and enqueues public-facing JavaScript files.\n *\n * @since " + this.pluginVersion + "\n */\npublic function enqueue_scripts() {\nwp_enqueue_script( $this->plugin_slug . '-plugin-script', plugins_url( 'assets/js/public.js', __FILE__ ), array( 'jquery' ), self::VERSION );\n}");
}
if (this.publicResources.indexOf('CSS') === -1) {
this.files.publicClass.rm("\nadd_action( 'wp_enqueue_scripts', array( $this, 'enqueue_styles' ) );");
this.files.publicClass.rm("\n\n/**\n * Register and enqueue public-facing style sheet.\n *\n * @since " + this.pluginVersion + "\n */\npublic function enqueue_styles() {\nwp_enqueue_style( $this->plugin_slug . '-plugin-styles', plugins_url( 'assets/css/public.css', __FILE__ ), array(), self::VERSION );\n}");
}
//Activate/deactivate
if (this.activateDeactivate.indexOf('Activate Method') === -1) {
this.files.publicClass.rmsearch('// Activate plugin when new blog is added', "add_action( 'wpmu_new_blog', array( $this, 'activate_new_site' ) );", 1, 1);
this.files.publicClass.rmsearch('* Fired when the plugin is activated.', '', 1, 32);
this.files.publicClass.rmsearch('* Fired when a new site is activated with a WPMU environment.', '', 1, 16);
this.files.publicClass.rmsearch('* Get all blog ids of blogs in the current network that are:', 'return $wpdb->get_col( $sql );', 1, -2);
this.files.publicClass.rmsearch("* Fired for each blog when the plugin is activated.", '', 1, 33);
if (verbose) {
console.log(('Removed Activate Method').italic);
}
}
if (this.activateDeactivate.indexOf('Deactivate Method') === -1) {
this.files.publicClass.rmsearch('* Fired when the plugin is deactivated.', '', 1, 32);
this.files.publicClass.rmsearch('* Fired for each blog when the plugin is deactivated.', '', 1, 10);
if (verbose) {
console.log(('Removed Deactive Method').italic);
}
}
//Repo
if (this.modules.indexOf('CPT_Core') === -1) {
this.files.publicClass.rmsearch('// Create Custom Post Type https://github.com/jtsternberg/CPT_Core/blob/master/README.md', "'map_meta_cap' => true", 0, -3);
}
if (this.modules.indexOf('Taxonomy_Core') === -1) {
this.files.publicClass.rmsearch('// Create Custom Taxonomy https://github.com/jtsternberg/Taxonomy_Core/blob/master/README.md', "), array( 'demo' )", 0, -2);
}
//Function
if (this.modules.indexOf('Template system (like WooCommerce)') === -1) {
this.files.publicClass.rm('//Override the template hierarchy for load /templates/content-demo.php');
this.files.publicClass.rm("add_filter( 'template_include', array( $this, 'load_content_demo' ) );");
this.files.publicClass.rmsearch('* Example for override the template system on the frontend', 'return $original_template;', 1, -3);
}
if (this.modules.indexOf('Requirements system on activation') === -1) {
fs.unlink(this.pluginSlug + '/public/includes/requirements.php');
fs.unlink(this.pluginSlug + '/languages/requirements.pot');
this.files.publicClass.rmsearch('//Requirements Detection System - read the doc in the library file', "'WP' => new WordPress_Requirement( '4.1.0' ),", -1, -2);
}
//Snippet
if (this.snippet.indexOf('CPTs on search box') === -1) {
this.files.publicClass.rmsearch('* Add support for custom CPT on the search box', 'return $query;', 1, 2);
this.files.publicClass.rm("add_filter( 'pre_get_posts', array( $this, 'filter_search' ) );");
if (verbose) {
console.log(('Removed CPTs on search box').italic);
}
}
if (this.snippet.indexOf('Custom action') === -1 && this.snippet.indexOf('Custom filter') === -1 && this.snippet.indexOf('Custom shortcode') === -1) {
this.files.publicClass.rmsearch('* Define custom functionality.', '* Refer To http://codex.wordpress.org/Plugin_API#Hooks.2C_Actions_and_Filters', 1, -2);
}
if (this.snippet.indexOf('Custom action') === -1) {
this.files.publicClass.rm("add_action( '@TODO', array( $this, 'action_method_name' ) );");
this.files.publicClass.rmsearch('* NOTE: Actions are points in the execution of a page or process', '// @TODO: Define your action hook callback here', 1, -2);
}
if (this.snippet.indexOf('Custom filter') === -1) {
this.files.publicClass.rm("add_filter( '@TODO', array( $this, 'filter_method_name' ) );");
this.files.publicClass.rmsearch('* NOTE: Filters are points of execution in which WordPress modifies data', '// @TODO: Define your filter hook callback here', 1, -2);
}
if (this.snippet.indexOf('Custom shortcode') === -1) {
this.files.publicClass.rm("add_shortcode( '@TODO', array( $this, 'shortcode_method_name' ) );");
this.files.publicClass.rmsearch('* NOTE: Shortcode simple set of functions for creating macro codes for use', '// @TODO: Define your shortcode here', 1, -4);
}
if (this.snippet.indexOf('Javascript DOM-based Routing') === -1) {
this.files.publicjs.rmsearch('* DOM-based Routing', '$(document).ready(UTIL.loadEvents);', 1, -1);
}
if (this.snippet.indexOf('Capability system') === -1) {
this.files.publicClass.rmsearch('* Array of capabilities by roles', '* Initialize the plugin by setting localization and loading public scripts', 1, 2);
this.files.publicClass.rmsearch('// @TODO: Define activation functionality here', '* Fired for each blog when the plugin is deactivated.', 2, 5);
this.files.publicClass.rm("'edit_others_posts' => 'edit_other_demo',");
}
if (this.snippet.indexOf('Add body class') === -1) {
this.files.publicClass.rmsearch('* Add class in the body on the frontend', 'return $classes;', 1, -2);
this.files.publicClass.rm("add_filter( 'body_class', array( $this, 'add_pn_class' ), 10, 3 );".replace(/pn_/g, this.pluginName.match(/\b(\w)/g).join('').toLowerCase() + '_'));
}
if (this.snippet.indexOf('wp_localize_script for PHP var to JS') === -1) {
this.files.publicClass.rm("add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_js_vars' ) );");
this.files.publicClass.rmsearch('* Print the PHP var in the HTML of the frontend for access by JavaScript', "'alert' => __( 'Hey! You have clicked the button!', $this->get_plugin_slug() )", 1, -4);
this.files.publicjs.rm('// Write in console log the PHP value passed in enqueue_js_vars in public/class-' + this.pluginSlug + '.php' + "\n");
this.files.publicjs.rm('console.log( tp_js_vars.alert );' + "\n");
}
};
WpPluginBoilerplateGenerator.prototype.setReadme = function setReadme() {
this.files.readme.add('@TODO: Plugin Name', this.pluginName);
};
WpPluginBoilerplateGenerator.prototype.setUninstall = function setUninstall() {
if (this.activateDeactivate.indexOf('Uninstall File') === -1) {
fs.unlink(this.files.uninstall.file);
delete this.files.uninstall;
} else if (this.snippet.indexOf('Capability system') === -1) {
this.files.uninstall.add('global $wpdb, $wp_roles;', 'global $wpdb;');
this.files.uninstall.rmsearch('$plugin_roles = array(', 'if ( is_multisite() ) {', -1, 0);
this.files.uninstall.rmsearch("switch_to_blog( $blog[ 'blog_id' ] );", 'restore_current_blog();', -19, 0);
this.files.uninstall.rmsearch('} else {', '$wp_roles->remove_cap( $cap );', -19, -4);
}
};
|
fixies
|
app/index.js
|
fixies
|
<ide><path>pp/index.js
<ide> this.files.adminClass.rmsearch('* Load Wp_Contextual_Help for the help tabs', "add_action( 'init', array( $this, 'contextual_help' ) );", 1, -1);
<ide> this.files.adminClass.rmsearch('* Filter for change the folder of Contextual Help', "$paths[] = plugin_dir_path( __FILE__ ) . '../help-docs/';", 1, -3);
<ide> this.files.adminClass.rmsearch('* Filter for change the folder image of Contextual Help', "$paths[] = plugin_dir_path( __FILE__ ) . '../help-docs/img';", 1, -3);
<del> this.files.adminClass.rmsearch('* Contextual Help, docs in /help-docs folter', "'page' => 'settings_page_' . $this->plugin_slug,", 1, -4);
<add> this.files.adminClass.rmsearch('* Contextual Help, docs in /help-docs folter', "'page' => 'settings_page_' . $this->plugin_slug,", 1, -1);
<ide> if (verbose) {
<ide> console.log(('Removed Wp_Contextual_Help').italic);
<ide> }
<ide> console.log((error).red);
<ide> }
<ide> });
<del> this.files.adminClass.rmsearch('* Load PointerPlus for the Wp Pointer', "add_filter( 'pointerplus_list', array( $this, 'custom_initial_pointers' ), 10, 2 );", 1, -1);
<add> this.files.adminClass.rmsearch('* Load PointerPlus for the Wp Pointer', "add_filter( 'pointerplus_list', array( $this, 'custom_initial_pointers' ), 10, 2 );", 1, 0);
<ide> this.files.adminClass.rmsearch('* Add pointers.', "'icon_class' => 'dashicons-welcome-learn-more',", 1, -3);
<ide> if (verbose) {
<ide> console.log(('Removed PointerPlus').italic);
|
|
Java
|
apache-2.0
|
cdba3cbdcf3ca2c223111f173b352b2b382948fd
| 0 |
codinguser/gnucash-android,lxbzmy/gnucash-android,pnemonic78/gnucash-android,lxbzmy/gnucash-android
|
/*
* Copyright (c) 2013 - 2015 Ngewi Fet <[email protected]>
* Copyright (c) 2014 Yongxin Wang <[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 org.gnucash.android.export;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ResolveInfo;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.util.Log;
import android.widget.Toast;
import com.crashlytics.android.Crashlytics;
import com.dropbox.sync.android.DbxAccountManager;
import com.dropbox.sync.android.DbxFile;
import com.dropbox.sync.android.DbxFileSystem;
import com.dropbox.sync.android.DbxPath;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveApi;
import com.google.android.gms.drive.DriveContents;
import com.google.android.gms.drive.DriveFolder;
import com.google.android.gms.drive.DriveId;
import com.google.android.gms.drive.MetadataChangeSet;
import com.owncloud.android.lib.common.OwnCloudClient;
import com.owncloud.android.lib.common.OwnCloudClientFactory;
import com.owncloud.android.lib.common.OwnCloudCredentialsFactory;
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
import com.owncloud.android.lib.resources.files.CreateRemoteFolderOperation;
import com.owncloud.android.lib.resources.files.FileUtils;
import com.owncloud.android.lib.resources.files.UploadRemoteFileOperation;
import org.gnucash.android.R;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.db.adapter.AccountsDbAdapter;
import org.gnucash.android.db.adapter.DatabaseAdapter;
import org.gnucash.android.db.adapter.SplitsDbAdapter;
import org.gnucash.android.db.adapter.TransactionsDbAdapter;
import org.gnucash.android.export.ofx.OfxExporter;
import org.gnucash.android.export.qif.QifExporter;
import org.gnucash.android.export.xml.GncXmlExporter;
import org.gnucash.android.model.Transaction;
import org.gnucash.android.ui.account.AccountsActivity;
import org.gnucash.android.ui.account.AccountsListFragment;
import org.gnucash.android.ui.settings.BackupPreferenceFragment;
import org.gnucash.android.ui.transaction.TransactionsActivity;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* Asynchronous task for exporting transactions.
*
* @author Ngewi Fet <[email protected]>
*/
public class ExportAsyncTask extends AsyncTask<ExportParams, Void, Boolean> {
/**
* App context
*/
private final Context mContext;
private ProgressDialog mProgressDialog;
private SQLiteDatabase mDb;
/**
* Log tag
*/
public static final String TAG = "ExportAsyncTask";
/**
* Export parameters
*/
private ExportParams mExportParams;
// File paths generated by the exporter
private List<String> mExportedFiles;
private Exporter mExporter;
public ExportAsyncTask(Context context, SQLiteDatabase db){
this.mContext = context;
this.mDb = db;
}
@Override
@TargetApi(11)
protected void onPreExecute() {
super.onPreExecute();
if (mContext instanceof Activity) {
mProgressDialog = new ProgressDialog(mContext);
mProgressDialog.setTitle(R.string.title_progress_exporting_transactions);
mProgressDialog.setIndeterminate(true);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
mProgressDialog.setProgressNumberFormat(null);
mProgressDialog.setProgressPercentFormat(null);
}
mProgressDialog.show();
}
}
/**
* Generates the appropriate exported transactions file for the given parameters
* @param params Export parameters
* @return <code>true</code> if export was successful, <code>false</code> otherwise
*/
@Override
protected Boolean doInBackground(ExportParams... params) {
mExportParams = params[0];
mExporter = getExporter();
try {
// FIXME: detect if there aren't transactions to export and inform the user
mExportedFiles = mExporter.generateExport();
} catch (final Exception e) {
Log.e(TAG, "Error exporting: " + e.getMessage());
Crashlytics.logException(e);
e.printStackTrace();
if (mContext instanceof Activity) {
((Activity)mContext).runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(mContext,
mContext.getString(R.string.toast_export_error, mExportParams.getExportFormat().name())
+ "\n" + e.getMessage(),
Toast.LENGTH_SHORT).show();
}
});
}
return false;
}
try {
moveToTarget();
} catch (Exporter.ExporterException e) {
Crashlytics.log(Log.ERROR, TAG, "Error sending exported files to target: " + e.getMessage());
return false;
}
return true;
}
/**
* Transmits the exported transactions to the designated location, either SD card or third-party application
* Finishes the activity if the export was starting in the context of an activity
* @param exportSuccessful Result of background export execution
*/
@Override
protected void onPostExecute(Boolean exportSuccessful) {
if (exportSuccessful) {
if (mContext instanceof Activity)
reportSuccess();
if (mExportParams.shouldDeleteTransactionsAfterExport()) {
backupAndDeleteTransactions();
refreshViews();
}
} else {
if (mContext instanceof Activity) {
Toast.makeText(mContext,
mContext.getString(R.string.toast_export_error, mExportParams.getExportFormat().name()),
Toast.LENGTH_LONG).show();
}
}
if (mContext instanceof Activity) {
if (mProgressDialog != null && mProgressDialog.isShowing())
mProgressDialog.dismiss();
((Activity) mContext).finish();
}
}
private Exporter getExporter() {
switch (mExportParams.getExportFormat()) {
case QIF:
return new QifExporter(mExportParams, mDb);
case OFX:
return new OfxExporter(mExportParams, mDb);
case XML:
default:
return new GncXmlExporter(mExportParams, mDb);
}
}
private void moveToTarget() throws Exporter.ExporterException {
switch (mExportParams.getExportTarget()) {
case SHARING:
List<String> sdCardExportedFiles = moveExportToSDCard();
shareFiles(sdCardExportedFiles);
break;
case DROPBOX:
moveExportToDropbox();
break;
case GOOGLE_DRIVE:
moveExportToGoogleDrive();
break;
case OWNCLOUD:
moveExportToOwnCloud();
break;
case SD_CARD:
moveExportToSDCard();
break;
default:
throw new Exporter.ExporterException(mExportParams, "Invalid target");
}
}
private void moveExportToGoogleDrive() throws Exporter.ExporterException {
Log.i(TAG, "Moving exported file to Google Drive");
final GoogleApiClient googleApiClient = BackupPreferenceFragment.getGoogleApiClient(GnuCashApplication.getAppContext());
googleApiClient.blockingConnect();
DriveApi.DriveContentsResult driveContentsResult =
Drive.DriveApi.newDriveContents(googleApiClient).await(1, TimeUnit.MINUTES);
if (!driveContentsResult.getStatus().isSuccess()) {
throw new Exporter.ExporterException(mExportParams,
"Error while trying to create new file contents");
}
final DriveContents driveContents = driveContentsResult.getDriveContents();
DriveFolder.DriveFileResult driveFileResult = null;
try {
// write content to DriveContents
OutputStream outputStream = driveContents.getOutputStream();
for (String exportedFilePath : mExportedFiles) {
File exportedFile = new File(exportedFilePath);
FileInputStream fileInputStream = new FileInputStream(exportedFile);
byte[] buffer = new byte[1024];
int count;
while ((count = fileInputStream.read(buffer)) >= 0) {
outputStream.write(buffer, 0, count);
}
fileInputStream.close();
outputStream.flush();
exportedFile.delete();
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle(exportedFile.getName())
.setMimeType(mExporter.getExportMimeType())
.build();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
String folderId = sharedPreferences.getString(mContext.getString(R.string.key_google_drive_app_folder_id), "");
DriveFolder folder = Drive.DriveApi.getFolder(googleApiClient, DriveId.decodeFromString(folderId));
// create a file on root folder
driveFileResult = folder.createFile(googleApiClient, changeSet, driveContents)
.await(1, TimeUnit.MINUTES);
}
} catch (IOException e) {
throw new Exporter.ExporterException(mExportParams, e);
}
if (driveFileResult == null)
throw new Exporter.ExporterException(mExportParams, "No result received");
if (!driveFileResult.getStatus().isSuccess())
throw new Exporter.ExporterException(mExportParams, "Error creating file in Google Drive");
Log.i(TAG, "Created file with id: " + driveFileResult.getDriveFile().getDriveId());
}
private void moveExportToDropbox() throws Exporter.ExporterException {
Log.i(TAG, "Copying exported file to DropBox");
String dropboxAppKey = mContext.getString(R.string.dropbox_app_key, BackupPreferenceFragment.DROPBOX_APP_KEY);
String dropboxAppSecret = mContext.getString(R.string.dropbox_app_secret, BackupPreferenceFragment.DROPBOX_APP_SECRET);
DbxAccountManager mDbxAcctMgr = DbxAccountManager.getInstance(mContext.getApplicationContext(),
dropboxAppKey, dropboxAppSecret);
DbxFile dbExportFile = null;
try {
DbxFileSystem dbxFileSystem = DbxFileSystem.forAccount(mDbxAcctMgr.getLinkedAccount());
for (String exportedFilePath : mExportedFiles) {
File exportedFile = new File(exportedFilePath);
dbExportFile = dbxFileSystem.create(new DbxPath(exportedFile.getName()));
dbExportFile.writeFromExistingFile(exportedFile, false);
exportedFile.delete();
}
} catch (IOException e) {
throw new Exporter.ExporterException(mExportParams);
} finally {
if (dbExportFile != null) {
dbExportFile.close();
}
}
}
private void moveExportToOwnCloud() throws Exporter.ExporterException {
Log.i(TAG, "Copying exported file to ownCloud");
SharedPreferences mPrefs = mContext.getSharedPreferences(mContext.getString(R.string.owncloud_pref), Context.MODE_PRIVATE);
Boolean mOC_sync = mPrefs.getBoolean(mContext.getString(R.string.owncloud_sync), false);
if (!mOC_sync) {
throw new Exporter.ExporterException(mExportParams, "ownCloud not enabled.");
}
String mOC_server = mPrefs.getString(mContext.getString(R.string.key_owncloud_server), null);
String mOC_username = mPrefs.getString(mContext.getString(R.string.key_owncloud_username), null);
String mOC_password = mPrefs.getString(mContext.getString(R.string.key_owncloud_password), null);
String mOC_dir = mPrefs.getString(mContext.getString(R.string.key_owncloud_dir), null);
Uri serverUri = Uri.parse(mOC_server);
OwnCloudClient mClient = OwnCloudClientFactory.createOwnCloudClient(serverUri, this.mContext, true);
mClient.setCredentials(
OwnCloudCredentialsFactory.newBasicCredentials(mOC_username, mOC_password)
);
if (mOC_dir.length() != 0) {
RemoteOperationResult dirResult = new CreateRemoteFolderOperation(
mOC_dir, true).execute(mClient);
if (!dirResult.isSuccess()) {
Log.w(TAG, "Error creating folder (it may happen if it already exists): "
+ dirResult.getLogMessage());
}
}
for (String exportedFilePath : mExportedFiles) {
String remotePath = mOC_dir + FileUtils.PATH_SEPARATOR + stripPathPart(exportedFilePath);
String mimeType = mExporter.getExportMimeType();
RemoteOperationResult result = new UploadRemoteFileOperation(
exportedFilePath, remotePath, mimeType).execute(mClient);
if (!result.isSuccess())
throw new Exporter.ExporterException(mExportParams, result.getLogMessage());
new File(exportedFilePath).delete();
}
}
/**
* Moves the exported files from the internal storage where they are generated to
* external storage, which is accessible to the user.
* @return The list of files moved to the SD card.
*/
private List<String> moveExportToSDCard() throws Exporter.ExporterException {
Log.i(TAG, "Moving exported file to external storage");
new File(Exporter.getExportFolderPath(mExporter.mBookUID));
List<String> dstFiles = new ArrayList<>();
for (String src: mExportedFiles) {
String dst = Exporter.getExportFolderPath(mExporter.mBookUID) + stripPathPart(src);
try {
moveFile(src, dst);
dstFiles.add(dst);
} catch (IOException e) {
throw new Exporter.ExporterException(mExportParams, e);
}
}
return dstFiles;
}
// "/some/path/filename.ext" -> "filename.ext"
private String stripPathPart(String fullPathName) {
return (new File(fullPathName)).getName();
}
/**
* Backups of the database, saves opening balances (if necessary)
* and deletes all non-template transactions in the database.
*/
private void backupAndDeleteTransactions(){
Log.i(TAG, "Backup and deleting transactions after export");
GncXmlExporter.createBackup(); //create backup before deleting everything
List<Transaction> openingBalances = new ArrayList<>();
boolean preserveOpeningBalances = GnuCashApplication.shouldSaveOpeningBalances(false);
TransactionsDbAdapter transactionsDbAdapter = new TransactionsDbAdapter(mDb, new SplitsDbAdapter(mDb));
if (preserveOpeningBalances) {
openingBalances = new AccountsDbAdapter(mDb, transactionsDbAdapter).getAllOpeningBalanceTransactions();
}
transactionsDbAdapter.deleteAllNonTemplateTransactions();
if (preserveOpeningBalances) {
transactionsDbAdapter.bulkAddRecords(openingBalances, DatabaseAdapter.UpdateMethod.insert);
}
}
/**
* Starts an intent chooser to allow the user to select an activity to receive
* the exported files.
* @param paths list of full paths of the files to send to the activity.
*/
private void shareFiles(List<String> paths) {
Intent shareIntent = new Intent(Intent.ACTION_SEND_MULTIPLE);
shareIntent.setType("text/xml");
ArrayList<Uri> exportFiles = convertFilePathsToUris(paths);
// shareIntent.putExtra(Intent.EXTRA_STREAM, exportFiles);
shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, exportFiles);
shareIntent.putExtra(Intent.EXTRA_SUBJECT, mContext.getString(R.string.title_export_email,
mExportParams.getExportFormat().name()));
String defaultEmail = PreferenceManager.getDefaultSharedPreferences(mContext)
.getString(mContext.getString(R.string.key_default_export_email), null);
if (defaultEmail != null && defaultEmail.trim().length() > 0)
shareIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{defaultEmail});
SimpleDateFormat formatter = (SimpleDateFormat) SimpleDateFormat.getDateTimeInstance();
ArrayList<CharSequence> extraText = new ArrayList<>();
extraText.add(mContext.getString(R.string.description_export_email)
+ " " + formatter.format(new Date(System.currentTimeMillis())));
shareIntent.putExtra(Intent.EXTRA_TEXT, extraText);
if (mContext instanceof Activity) {
List<ResolveInfo> activities = mContext.getPackageManager().queryIntentActivities(shareIntent, 0);
if (activities != null && !activities.isEmpty()) {
mContext.startActivity(Intent.createChooser(shareIntent,
mContext.getString(R.string.title_select_export_destination)));
} else {
Toast.makeText(mContext, R.string.toast_no_compatible_apps_to_receive_export,
Toast.LENGTH_LONG).show();
}
}
}
/**
* Convert file paths to URIs by adding the file// prefix
* <p>e.g. /some/path/file.ext --> file:///some/path/file.ext</p>
* @param paths List of file paths to convert
* @return List of file URIs
*/
@NonNull
private ArrayList<Uri> convertFilePathsToUris(List<String> paths) {
ArrayList<Uri> exportFiles = new ArrayList<>();
for (String path : paths) {
File file = new File(path);
file.setReadable(true, false);
exportFiles.add(Uri.fromFile(file));
// exportFiles.add(Uri.parse("file://" + file));
}
return exportFiles;
}
/**
* Moves a file from <code>src</code> to <code>dst</code>
* @param src Absolute path to the source file
* @param dst Absolute path to the destination file
* @throws IOException if the file could not be moved.
*/
public void moveFile(String src, String dst) throws IOException {
File srcFile = new File(src);
File dstFile = new File(dst);
FileChannel inChannel = new FileInputStream(srcFile).getChannel();
FileChannel outChannel = new FileOutputStream(dstFile).getChannel();
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} finally {
if (inChannel != null)
inChannel.close();
outChannel.close();
}
srcFile.delete();
}
private void reportSuccess() {
String targetLocation;
switch (mExportParams.getExportTarget()){
case SD_CARD:
targetLocation = "SD card";
break;
case DROPBOX:
targetLocation = "DropBox -> Apps -> GnuCash";
break;
case GOOGLE_DRIVE:
targetLocation = "Google Drive -> " + mContext.getString(R.string.app_name);
break;
case OWNCLOUD:
targetLocation = mContext.getSharedPreferences(
mContext.getString(R.string.owncloud_pref),
Context.MODE_PRIVATE).getBoolean(
mContext.getString(R.string.owncloud_sync), false) ?
"ownCloud -> " +
mContext.getSharedPreferences(
mContext.getString(R.string.owncloud_pref),
Context.MODE_PRIVATE).getString(
mContext.getString(R.string.key_owncloud_dir), null) :
"ownCloud sync not enabled";
break;
default:
targetLocation = mContext.getString(R.string.label_export_target_external_service);
}
Toast.makeText(mContext,
String.format(mContext.getString(R.string.toast_exported_to), targetLocation),
Toast.LENGTH_LONG).show();
}
private void refreshViews() {
if (mContext instanceof AccountsActivity){
AccountsListFragment fragment =
((AccountsActivity) mContext).getCurrentAccountListFragment();
if (fragment != null)
fragment.refresh();
}
if (mContext instanceof TransactionsActivity){
((TransactionsActivity) mContext).refresh();
}
}
}
|
app/src/main/java/org/gnucash/android/export/ExportAsyncTask.java
|
/*
* Copyright (c) 2013 - 2015 Ngewi Fet <[email protected]>
* Copyright (c) 2014 Yongxin Wang <[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 org.gnucash.android.export;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ResolveInfo;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.util.Log;
import android.widget.Toast;
import com.crashlytics.android.Crashlytics;
import com.dropbox.sync.android.DbxAccountManager;
import com.dropbox.sync.android.DbxFile;
import com.dropbox.sync.android.DbxFileSystem;
import com.dropbox.sync.android.DbxPath;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveApi;
import com.google.android.gms.drive.DriveContents;
import com.google.android.gms.drive.DriveFolder;
import com.google.android.gms.drive.DriveId;
import com.google.android.gms.drive.MetadataChangeSet;
import com.owncloud.android.lib.common.OwnCloudClient;
import com.owncloud.android.lib.common.OwnCloudClientFactory;
import com.owncloud.android.lib.common.OwnCloudCredentialsFactory;
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
import com.owncloud.android.lib.resources.files.CreateRemoteFolderOperation;
import com.owncloud.android.lib.resources.files.FileUtils;
import com.owncloud.android.lib.resources.files.UploadRemoteFileOperation;
import org.gnucash.android.R;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.db.adapter.AccountsDbAdapter;
import org.gnucash.android.db.adapter.DatabaseAdapter;
import org.gnucash.android.db.adapter.SplitsDbAdapter;
import org.gnucash.android.db.adapter.TransactionsDbAdapter;
import org.gnucash.android.export.ofx.OfxExporter;
import org.gnucash.android.export.qif.QifExporter;
import org.gnucash.android.export.xml.GncXmlExporter;
import org.gnucash.android.model.Transaction;
import org.gnucash.android.ui.account.AccountsActivity;
import org.gnucash.android.ui.account.AccountsListFragment;
import org.gnucash.android.ui.settings.BackupPreferenceFragment;
import org.gnucash.android.ui.transaction.TransactionsActivity;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* Asynchronous task for exporting transactions.
*
* @author Ngewi Fet <[email protected]>
*/
public class ExportAsyncTask extends AsyncTask<ExportParams, Void, Boolean> {
/**
* App context
*/
private final Context mContext;
private ProgressDialog mProgressDialog;
private SQLiteDatabase mDb;
/**
* Log tag
*/
public static final String TAG = "ExportAsyncTask";
/**
* Export parameters
*/
private ExportParams mExportParams;
// File paths generated by the exporter
private List<String> mExportedFiles;
private Exporter mExporter;
public ExportAsyncTask(Context context, SQLiteDatabase db){
this.mContext = context;
this.mDb = db;
}
@Override
@TargetApi(11)
protected void onPreExecute() {
super.onPreExecute();
if (mContext instanceof Activity) {
mProgressDialog = new ProgressDialog(mContext);
mProgressDialog.setTitle(R.string.title_progress_exporting_transactions);
mProgressDialog.setIndeterminate(true);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
mProgressDialog.setProgressNumberFormat(null);
mProgressDialog.setProgressPercentFormat(null);
}
mProgressDialog.show();
}
}
/**
* Generates the appropriate exported transactions file for the given parameters
* @param params Export parameters
* @return <code>true</code> if export was successful, <code>false</code> otherwise
*/
@Override
protected Boolean doInBackground(ExportParams... params) {
mExportParams = params[0];
mExporter = getExporter();
try {
// FIXME: detect if there aren't transactions to export and inform the user
mExportedFiles = mExporter.generateExport();
} catch (final Exception e) {
Log.e(TAG, "Error exporting: " + e.getMessage());
Crashlytics.logException(e);
e.printStackTrace();
if (mContext instanceof Activity) {
((Activity)mContext).runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(mContext,
mContext.getString(R.string.toast_export_error, mExportParams.getExportFormat().name())
+ "\n" + e.getMessage(),
Toast.LENGTH_SHORT).show();
}
});
}
return false;
}
try {
moveToTarget();
} catch (Exporter.ExporterException e) {
Crashlytics.log(Log.ERROR, TAG, "Error sending exported files to target: " + e.getMessage());
return false;
}
return true;
}
/**
* Transmits the exported transactions to the designated location, either SD card or third-party application
* Finishes the activity if the export was starting in the context of an activity
* @param exportSuccessful Result of background export execution
*/
@Override
protected void onPostExecute(Boolean exportSuccessful) {
if (exportSuccessful) {
if (mContext instanceof Activity)
reportSuccess();
if (mExportParams.shouldDeleteTransactionsAfterExport()) {
Log.i(TAG, "Backup and deleting transactions after export");
backupAndDeleteTransactions();
refreshViews();
}
} else {
if (mContext instanceof Activity) {
Toast.makeText(mContext,
mContext.getString(R.string.toast_export_error, mExportParams.getExportFormat().name()),
Toast.LENGTH_LONG).show();
}
}
if (mContext instanceof Activity) {
if (mProgressDialog != null && mProgressDialog.isShowing())
mProgressDialog.dismiss();
((Activity) mContext).finish();
}
}
private Exporter getExporter() {
switch (mExportParams.getExportFormat()) {
case QIF:
return new QifExporter(mExportParams, mDb);
case OFX:
return new OfxExporter(mExportParams, mDb);
case XML:
default:
return new GncXmlExporter(mExportParams, mDb);
}
}
private void moveToTarget() throws Exporter.ExporterException {
switch (mExportParams.getExportTarget()) {
case SHARING:
List<String> sdCardExportedFiles = moveExportToSDCard();
shareFiles(sdCardExportedFiles);
break;
case DROPBOX:
moveExportToDropbox();
break;
case GOOGLE_DRIVE:
moveExportToGoogleDrive();
break;
case OWNCLOUD:
moveExportToOwnCloud();
break;
case SD_CARD:
moveExportToSDCard();
break;
default:
throw new Exporter.ExporterException(mExportParams, "Invalid target");
}
}
private void moveExportToGoogleDrive() throws Exporter.ExporterException {
Log.i(TAG, "Moving exported file to Google Drive");
final GoogleApiClient googleApiClient = BackupPreferenceFragment.getGoogleApiClient(GnuCashApplication.getAppContext());
googleApiClient.blockingConnect();
DriveApi.DriveContentsResult driveContentsResult =
Drive.DriveApi.newDriveContents(googleApiClient).await(1, TimeUnit.MINUTES);
if (!driveContentsResult.getStatus().isSuccess()) {
throw new Exporter.ExporterException(mExportParams,
"Error while trying to create new file contents");
}
final DriveContents driveContents = driveContentsResult.getDriveContents();
DriveFolder.DriveFileResult driveFileResult = null;
try {
// write content to DriveContents
OutputStream outputStream = driveContents.getOutputStream();
for (String exportedFilePath : mExportedFiles) {
File exportedFile = new File(exportedFilePath);
FileInputStream fileInputStream = new FileInputStream(exportedFile);
byte[] buffer = new byte[1024];
int count;
while ((count = fileInputStream.read(buffer)) >= 0) {
outputStream.write(buffer, 0, count);
}
fileInputStream.close();
outputStream.flush();
exportedFile.delete();
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle(exportedFile.getName())
.setMimeType(mExporter.getExportMimeType())
.build();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
String folderId = sharedPreferences.getString(mContext.getString(R.string.key_google_drive_app_folder_id), "");
DriveFolder folder = Drive.DriveApi.getFolder(googleApiClient, DriveId.decodeFromString(folderId));
// create a file on root folder
driveFileResult = folder.createFile(googleApiClient, changeSet, driveContents)
.await(1, TimeUnit.MINUTES);
}
} catch (IOException e) {
throw new Exporter.ExporterException(mExportParams, e);
}
if (driveFileResult == null)
throw new Exporter.ExporterException(mExportParams, "No result received");
if (!driveFileResult.getStatus().isSuccess())
throw new Exporter.ExporterException(mExportParams, "Error creating file in Google Drive");
Log.i(TAG, "Created file with id: " + driveFileResult.getDriveFile().getDriveId());
}
private void moveExportToDropbox() throws Exporter.ExporterException {
Log.i(TAG, "Copying exported file to DropBox");
String dropboxAppKey = mContext.getString(R.string.dropbox_app_key, BackupPreferenceFragment.DROPBOX_APP_KEY);
String dropboxAppSecret = mContext.getString(R.string.dropbox_app_secret, BackupPreferenceFragment.DROPBOX_APP_SECRET);
DbxAccountManager mDbxAcctMgr = DbxAccountManager.getInstance(mContext.getApplicationContext(),
dropboxAppKey, dropboxAppSecret);
DbxFile dbExportFile = null;
try {
DbxFileSystem dbxFileSystem = DbxFileSystem.forAccount(mDbxAcctMgr.getLinkedAccount());
for (String exportedFilePath : mExportedFiles) {
File exportedFile = new File(exportedFilePath);
dbExportFile = dbxFileSystem.create(new DbxPath(exportedFile.getName()));
dbExportFile.writeFromExistingFile(exportedFile, false);
exportedFile.delete();
}
} catch (IOException e) {
throw new Exporter.ExporterException(mExportParams);
} finally {
if (dbExportFile != null) {
dbExportFile.close();
}
}
}
private void moveExportToOwnCloud() throws Exporter.ExporterException {
Log.i(TAG, "Copying exported file to ownCloud");
SharedPreferences mPrefs = mContext.getSharedPreferences(mContext.getString(R.string.owncloud_pref), Context.MODE_PRIVATE);
Boolean mOC_sync = mPrefs.getBoolean(mContext.getString(R.string.owncloud_sync), false);
if (!mOC_sync) {
throw new Exporter.ExporterException(mExportParams, "ownCloud not enabled.");
}
String mOC_server = mPrefs.getString(mContext.getString(R.string.key_owncloud_server), null);
String mOC_username = mPrefs.getString(mContext.getString(R.string.key_owncloud_username), null);
String mOC_password = mPrefs.getString(mContext.getString(R.string.key_owncloud_password), null);
String mOC_dir = mPrefs.getString(mContext.getString(R.string.key_owncloud_dir), null);
Uri serverUri = Uri.parse(mOC_server);
OwnCloudClient mClient = OwnCloudClientFactory.createOwnCloudClient(serverUri, this.mContext, true);
mClient.setCredentials(
OwnCloudCredentialsFactory.newBasicCredentials(mOC_username, mOC_password)
);
if (mOC_dir.length() != 0) {
RemoteOperationResult dirResult = new CreateRemoteFolderOperation(
mOC_dir, true).execute(mClient);
if (!dirResult.isSuccess()) {
Log.w(TAG, "Error creating folder (it may happen if it already exists): "
+ dirResult.getLogMessage());
}
}
for (String exportedFilePath : mExportedFiles) {
String remotePath = mOC_dir + FileUtils.PATH_SEPARATOR + stripPathPart(exportedFilePath);
String mimeType = mExporter.getExportMimeType();
RemoteOperationResult result = new UploadRemoteFileOperation(
exportedFilePath, remotePath, mimeType).execute(mClient);
if (!result.isSuccess())
throw new Exporter.ExporterException(mExportParams, result.getLogMessage());
new File(exportedFilePath).delete();
}
}
/**
* Moves the exported files from the internal storage where they are generated to
* external storage, which is accessible to the user.
* @return The list of files moved to the SD card.
*/
private List<String> moveExportToSDCard() throws Exporter.ExporterException {
Log.i(TAG, "Moving exported file to external storage");
new File(Exporter.getExportFolderPath(mExporter.mBookUID));
List<String> dstFiles = new ArrayList<>();
for (String src: mExportedFiles) {
String dst = Exporter.getExportFolderPath(mExporter.mBookUID) + stripPathPart(src);
try {
moveFile(src, dst);
dstFiles.add(dst);
} catch (IOException e) {
throw new Exporter.ExporterException(mExportParams, e);
}
}
return dstFiles;
}
// "/some/path/filename.ext" -> "filename.ext"
private String stripPathPart(String fullPathName) {
return (new File(fullPathName)).getName();
}
/**
* Backups of the database, saves opening balances (if necessary)
* and deletes all non-template transactions in the database.
*/
private void backupAndDeleteTransactions(){
GncXmlExporter.createBackup(); //create backup before deleting everything
List<Transaction> openingBalances = new ArrayList<>();
boolean preserveOpeningBalances = GnuCashApplication.shouldSaveOpeningBalances(false);
TransactionsDbAdapter transactionsDbAdapter = new TransactionsDbAdapter(mDb, new SplitsDbAdapter(mDb));
if (preserveOpeningBalances) {
openingBalances = new AccountsDbAdapter(mDb, transactionsDbAdapter).getAllOpeningBalanceTransactions();
}
transactionsDbAdapter.deleteAllNonTemplateTransactions();
if (preserveOpeningBalances) {
transactionsDbAdapter.bulkAddRecords(openingBalances, DatabaseAdapter.UpdateMethod.insert);
}
}
/**
* Starts an intent chooser to allow the user to select an activity to receive
* the exported files.
* @param paths list of full paths of the files to send to the activity.
*/
private void shareFiles(List<String> paths) {
Intent shareIntent = new Intent(Intent.ACTION_SEND_MULTIPLE);
shareIntent.setType("text/xml");
ArrayList<Uri> exportFiles = convertFilePathsToUris(paths);
// shareIntent.putExtra(Intent.EXTRA_STREAM, exportFiles);
shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, exportFiles);
shareIntent.putExtra(Intent.EXTRA_SUBJECT, mContext.getString(R.string.title_export_email,
mExportParams.getExportFormat().name()));
String defaultEmail = PreferenceManager.getDefaultSharedPreferences(mContext)
.getString(mContext.getString(R.string.key_default_export_email), null);
if (defaultEmail != null && defaultEmail.trim().length() > 0)
shareIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{defaultEmail});
SimpleDateFormat formatter = (SimpleDateFormat) SimpleDateFormat.getDateTimeInstance();
ArrayList<CharSequence> extraText = new ArrayList<>();
extraText.add(mContext.getString(R.string.description_export_email)
+ " " + formatter.format(new Date(System.currentTimeMillis())));
shareIntent.putExtra(Intent.EXTRA_TEXT, extraText);
if (mContext instanceof Activity) {
List<ResolveInfo> activities = mContext.getPackageManager().queryIntentActivities(shareIntent, 0);
if (activities != null && !activities.isEmpty()) {
mContext.startActivity(Intent.createChooser(shareIntent,
mContext.getString(R.string.title_select_export_destination)));
} else {
Toast.makeText(mContext, R.string.toast_no_compatible_apps_to_receive_export,
Toast.LENGTH_LONG).show();
}
}
}
/**
* Convert file paths to URIs by adding the file// prefix
* <p>e.g. /some/path/file.ext --> file:///some/path/file.ext</p>
* @param paths List of file paths to convert
* @return List of file URIs
*/
@NonNull
private ArrayList<Uri> convertFilePathsToUris(List<String> paths) {
ArrayList<Uri> exportFiles = new ArrayList<>();
for (String path : paths) {
File file = new File(path);
file.setReadable(true, false);
exportFiles.add(Uri.fromFile(file));
// exportFiles.add(Uri.parse("file://" + file));
}
return exportFiles;
}
/**
* Moves a file from <code>src</code> to <code>dst</code>
* @param src Absolute path to the source file
* @param dst Absolute path to the destination file
* @throws IOException if the file could not be moved.
*/
public void moveFile(String src, String dst) throws IOException {
File srcFile = new File(src);
File dstFile = new File(dst);
FileChannel inChannel = new FileInputStream(srcFile).getChannel();
FileChannel outChannel = new FileOutputStream(dstFile).getChannel();
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} finally {
if (inChannel != null)
inChannel.close();
outChannel.close();
}
srcFile.delete();
}
private void reportSuccess() {
String targetLocation;
switch (mExportParams.getExportTarget()){
case SD_CARD:
targetLocation = "SD card";
break;
case DROPBOX:
targetLocation = "DropBox -> Apps -> GnuCash";
break;
case GOOGLE_DRIVE:
targetLocation = "Google Drive -> " + mContext.getString(R.string.app_name);
break;
case OWNCLOUD:
targetLocation = mContext.getSharedPreferences(
mContext.getString(R.string.owncloud_pref),
Context.MODE_PRIVATE).getBoolean(
mContext.getString(R.string.owncloud_sync), false) ?
"ownCloud -> " +
mContext.getSharedPreferences(
mContext.getString(R.string.owncloud_pref),
Context.MODE_PRIVATE).getString(
mContext.getString(R.string.key_owncloud_dir), null) :
"ownCloud sync not enabled";
break;
default:
targetLocation = mContext.getString(R.string.label_export_target_external_service);
}
Toast.makeText(mContext,
String.format(mContext.getString(R.string.toast_exported_to), targetLocation),
Toast.LENGTH_LONG).show();
}
private void refreshViews() {
if (mContext instanceof AccountsActivity){
AccountsListFragment fragment =
((AccountsActivity) mContext).getCurrentAccountListFragment();
if (fragment != null)
fragment.refresh();
}
if (mContext instanceof TransactionsActivity){
((TransactionsActivity) mContext).refresh();
}
}
}
|
Move log call to the method it refers
|
app/src/main/java/org/gnucash/android/export/ExportAsyncTask.java
|
Move log call to the method it refers
|
<ide><path>pp/src/main/java/org/gnucash/android/export/ExportAsyncTask.java
<ide> reportSuccess();
<ide>
<ide> if (mExportParams.shouldDeleteTransactionsAfterExport()) {
<del> Log.i(TAG, "Backup and deleting transactions after export");
<ide> backupAndDeleteTransactions();
<ide> refreshViews();
<ide> }
<ide> * and deletes all non-template transactions in the database.
<ide> */
<ide> private void backupAndDeleteTransactions(){
<add> Log.i(TAG, "Backup and deleting transactions after export");
<ide> GncXmlExporter.createBackup(); //create backup before deleting everything
<ide> List<Transaction> openingBalances = new ArrayList<>();
<ide> boolean preserveOpeningBalances = GnuCashApplication.shouldSaveOpeningBalances(false);
|
|
Java
|
apache-2.0
|
10acbe7769dbfedfc23ffbd8cfc10949996041a3
| 0 |
eFaps/eFaps-WebApp-Install,eFaps/eFaps-WebApp-Install,eFaps/eFaps-WebApp-Install
|
/*
* Copyright 2003 - 2012 The eFaps Team
*
* 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.
*
* Revision: $Rev$
* Last Changed: $Date$
* Last Changed By: $Author$
*/
package org.efaps.esjp.ui.structurbrowser;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.Map;
import org.efaps.admin.datamodel.Type;
import org.efaps.admin.event.EventExecution;
import org.efaps.admin.event.Parameter;
import org.efaps.admin.event.Parameter.ParameterValues;
import org.efaps.admin.event.Return;
import org.efaps.admin.event.Return.ReturnValues;
import org.efaps.admin.program.esjp.EFapsRevision;
import org.efaps.admin.program.esjp.EFapsUUID;
import org.efaps.db.Instance;
import org.efaps.db.InstanceQuery;
import org.efaps.db.QueryBuilder;
import org.efaps.ui.wicket.models.cell.UIStructurBrowserTableCell;
import org.efaps.ui.wicket.models.objects.UIStructurBrowser;
import org.efaps.ui.wicket.models.objects.UIStructurBrowser.ExecutionStatus;
import org.efaps.util.EFapsException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* TODO description!
*
* @author The eFasp Team
* @version $Id$
*/
@EFapsUUID("d6548826-830b-4540-a46d-d861c3f21f15")
@EFapsRevision("$Rev$")
public abstract class StandartStructurBrowser_Base
implements EventExecution
{
/**
* Logger for this class.
*/
protected static final Logger LOG = LoggerFactory.getLogger(StandartStructurBrowser_Base.class);
/**
* @param _parameter Parameter
* @throws EFapsException on error
* @return Return
*/
public Return execute(final Parameter _parameter)
throws EFapsException
{
Return ret = null;
final UIStructurBrowser strBro = (UIStructurBrowser) _parameter.get(ParameterValues.CLASS);
final ExecutionStatus status = strBro.getExecutionStatus();
if (status.equals(ExecutionStatus.EXECUTE)) {
ret = internalExecute(_parameter);
} else if (status.equals(ExecutionStatus.ALLOWSCHILDREN)) {
ret = allowChildren(_parameter);
} else if (status.equals(ExecutionStatus.ALLOWSITEM)) {
ret = allowItem(_parameter);
} else if (status.equals(ExecutionStatus.CHECKFORCHILDREN)) {
ret = checkForChildren(_parameter);
} else if (status.equals(ExecutionStatus.ADDCHILDREN)) {
ret = addChildren(_parameter);
} else if (status.equals(ExecutionStatus.SORT)) {
ret = sort(_parameter);
} else if (status.equals(ExecutionStatus.CHECKHIDECOLUMN4ROW)) {
ret = checkHideColumn4Row(_parameter);
} else if (status.equals(ExecutionStatus.NODE_REMOVE)) {
ret = onNodeRemove(_parameter);
} else if (status.equals(ExecutionStatus.NODE_INSERTCHILDITEM)) {
ret = onNodeInsertChildItem(_parameter);
} else if (status.equals(ExecutionStatus.NODE_INSERTITEM)) {
ret = onNodeInsertItem(_parameter);
} else if (status.equals(ExecutionStatus.NODE_INSERTCHILDFOLDER)) {
ret = onNodeInsertChildFolder(_parameter);
} else if (status.equals(ExecutionStatus.GETJAVASCRIPT4TARGET)) {
ret = getJavaScript4Target(_parameter);
}
return ret;
}
/**
* Method is called after the insert etc. of a new node in edit mode to
* get a JavaScript that will be appended to the AjaxTarget.
* In this Step the values for the StructurBrowsers also can be altered.
*
* @param _parameter as passed from eFaps API.
* @return Return with SNIPPLET
* @throws EFapsException on error
*/
protected Return getJavaScript4Target(final Parameter _parameter)
throws EFapsException
{
final Return ret = new Return();
//EXAMPLE to be done by implementation
final StringBuilder js = new StringBuilder();
//js.append("document.getElementById..");
ret.put(ReturnValues.SNIPLETT, js.toString());
return ret;
}
/**
* Method to get a list of instances the StructurBrowser will be filled
* with.
* @param _parameter as passed from eFaps API.
* @return Return with instances
* @throws EFapsException on error
*/
protected Return internalExecute(final Parameter _parameter)
throws EFapsException
{
final Return ret = new Return();
final Instance instance = _parameter.getInstance();
final Map<Instance, Boolean> tree = new LinkedHashMap<Instance, Boolean>();
final Map<?, ?> properties = (Map<?, ?>) _parameter.get(ParameterValues.PROPERTIES);
final String typesStr = (String) properties.get("Types");
final String linkFromsStr = (String) properties.get("LinkFroms");
final boolean includeChildTypes = !"false".equalsIgnoreCase((String) properties.get("ExpandChildTypes"));
if (StandartStructurBrowser_Base.LOG.isDebugEnabled()) {
StandartStructurBrowser_Base.LOG.debug("Types: {}\n LinkFroms: {}\n ExpandChildTypes: {}",
new Object[]{typesStr, linkFromsStr, includeChildTypes});
}
if (typesStr != null && !typesStr.isEmpty()) {
final String[] typesArray = typesStr.split(";");
for (int i = 0; i < typesArray.length; i++) {
final Type type = Type.get(typesArray[i]);
final QueryBuilder queryBldr = new QueryBuilder(type);
if (linkFromsStr != null && instance != null && instance.isValid()) {
final String[] linkFroms = linkFromsStr.split(";");
queryBldr.addWhereAttrEqValue(linkFroms[i], instance.getId());
}
addCriteria(_parameter, queryBldr);
final InstanceQuery query = queryBldr.getQuery();
query.execute();
while (query.next()) {
tree.put(query.getCurrentValue(), null);
}
}
}
ret.put(ReturnValues.VALUES, tree);
return ret;
}
/**
* Add additional Criteria to the QueryBuilder.
* To be used by implementation.
*
* @param _parameter Parameter as passed from the eFaps API
* @param _queryBldr QueryBuilder the criteria will be added to
* @throws EFapsException on error
*/
protected void addCriteria(final Parameter _parameter,
final QueryBuilder _queryBldr)
throws EFapsException
{
// used by implementation
}
/**
* Add additional Criteria to the QueryBuilder.
* To be used by implementation.
*
* @param _parameter Parameter as passed from the eFaps API
* @param _queryBldr QueryBuilder the criteria will be added to
* @throws EFapsException on error
*/
protected void addCriteria4Children(final Parameter _parameter,
final QueryBuilder _queryBldr)
throws EFapsException
{
// used by implementation
}
/**
* Method to check if an instance allows children. It is used in the tree to
* determine "folder" or an "item" must be rendered and if the checkForChildren
* method must be executed.
*
* @param _parameter Parameter as passed from the eFaps API
* @return Return with true or false
* @throws EFapsException on error
*/
protected Return allowChildren(final Parameter _parameter)
throws EFapsException
{
final Return ret = new Return();
ret.put(ReturnValues.TRUE, true);
return ret;
}
/**
* Method to check if an instance allows children of type item. It is used in the
* tree to determine if "item" can be rendered. It will only be executed if
* the {@link #allowChildren(Parameter)} method returned true.
*
* @param _parameter Parameter as passed from the eFaps API
* @return Return with true or false
* @throws EFapsException on error
*/
protected Return allowItem(final Parameter _parameter)
throws EFapsException
{
final Return ret = new Return();
ret.put(ReturnValues.TRUE, true);
return ret;
}
/**
* Method to check if an instance has children. It is used in the tree to
* determine if a "plus" to open the children must be rendered.
*
* @param _parameter Parameter as passed from the eFaps API
* @return Return with true or false
* @throws EFapsException on error
*/
protected Return checkForChildren(final Parameter _parameter)
throws EFapsException
{
final Return ret = new Return();
final Map<Instance, Boolean> map = getChildren(_parameter, true);
if (!map.isEmpty()) {
ret.put(ReturnValues.TRUE, true);
}
return ret;
}
/**
* @param _parameter Parameter as passed from the eFaps API
* @param _check check only?
* @return map with instances
* @throws EFapsException on error
*/
protected Map<Instance, Boolean> getChildren(final Parameter _parameter,
final boolean _check)
throws EFapsException
{
final Map<Instance, Boolean> ret = new LinkedHashMap<Instance, Boolean>();
final Instance instance = _parameter.getInstance();
final Map<?, ?> properties = (Map<?, ?>) _parameter.get(ParameterValues.PROPERTIES);
final String typesStr = (String) properties.get("Child_Types");
final String linkFromsStr = (String) properties.get("Child_LinkFroms");
final boolean includeChildTypes = !"false".equalsIgnoreCase((String) properties.get("Child_ExpandChildTypes"));
if (StandartStructurBrowser_Base.LOG.isDebugEnabled()) {
StandartStructurBrowser_Base.LOG.debug("Child_Types: {}\n Child_LinkFroms: {}\n Child_ExpandChildTypes: {}",
new Object[]{typesStr, linkFromsStr, includeChildTypes});
}
if (typesStr != null && !typesStr.isEmpty()) {
final String[] typesArray = typesStr.split(";");
for (int i = 0; i < typesArray.length; i++) {
final Type type = Type.get(typesArray[i]);
final QueryBuilder queryBldr = new QueryBuilder(type);
if (linkFromsStr != null && instance != null && instance.isValid()) {
final String[] linkFroms = linkFromsStr.split(";");
queryBldr.addWhereAttrEqValue(linkFroms[i], instance.getId());
}
addCriteria4Children(_parameter, queryBldr);
final InstanceQuery query = queryBldr.getQuery();
query.setIncludeChildTypes(includeChildTypes);
if (_check) {
query.setLimit(1);
}
query.execute();
while (query.next()) {
ret.put(query.getCurrentValue(), null);
}
}
}
return ret;
}
/**
* Method to add the children to an instance. It is used to expand the
* children of a node in the tree.
*
* @param _parameter Paraemter as passed from the eFasp API
* @return Return with instances
* @throws EFapsException on error
*/
protected Return addChildren(final Parameter _parameter)
throws EFapsException
{
final Return ret = new Return();
final Map<Instance, Boolean> map = getChildren(_parameter, false);
ret.put(ReturnValues.VALUES, map);
return ret;
}
/**
* Method is called from the StructurBrowser in edit mode before rendering
* the columns for row to be able to hide the columns for different rows by
* setting the cell model to hide.
* In this implementation all columns except the StructurBrowser column is
* hidden for the folders.
* @param _parameter Paraemter as passed from the eFasp API
* @return empty Return;
* @throws EFapsException on error
*/
protected Return checkHideColumn4Row(final Parameter _parameter)
throws EFapsException
{
final UIStructurBrowser strBrws = (UIStructurBrowser) _parameter.get(ParameterValues.CLASS);
for (final UIStructurBrowserTableCell cell : strBrws.getColumns()) {
if (strBrws.isAllowChildren() && !cell.isBrowserField()) {
cell.setHide(true);
}
}
return new Return();
}
/**
* Executed on insert of a folder node as an listener and does not
* effect directly the tree, but allows to manipulate it.
*
* @param _parameter _parameter as passed from eFaps API.
* @return empty Return
* @throws EFapsException on error
*/
protected Return onNodeInsertChildFolder(final Parameter _parameter)
throws EFapsException
{
return new Return();
}
/**
* Executed on insert of an new item node as an listener and does not
* effect directly the tree, but allows to manipulate it.
*
* @param _parameter _parameter as passed from eFaps API.
* @return empty Return
* @throws EFapsException on error
*/
protected Return onNodeInsertItem(final Parameter _parameter)
throws EFapsException
{
return new Return();
}
/**
* Executed on insert of an item as child as an listener and does not
* effect directly the tree, but allows to manipulate it.
*
* @param _parameter _parameter as passed from eFaps API.
* @return empty Return
* @throws EFapsException on error
*/
protected Return onNodeInsertChildItem(final Parameter _parameter)
throws EFapsException
{
return new Return();
}
/**
* Executed on removal of a node as an listener and does not
* effect directly the tree, but allows to manipulate it.
*
* @param _parameter _parameter as passed from eFaps API.
* @return empty Return
* @throws EFapsException on error
*/
protected Return onNodeRemove(final Parameter _parameter)
throws EFapsException
{
return new Return();
}
/**
* Method to sort the values of the StructurBrowser.
*
* @param _parameter Paraemter as passed from the eFasp API
* @return empty Return
* @throws EFapsException on error
*/
protected Return sort(final Parameter _parameter)
throws EFapsException
{
final UIStructurBrowser strBro = (UIStructurBrowser) _parameter.get(ParameterValues.CLASS);
Collections.sort(strBro.getChildren(), new Comparator<UIStructurBrowser>() {
@SuppressWarnings({ "rawtypes", "unchecked" })
public int compare(final UIStructurBrowser _structurBrowser1,
final UIStructurBrowser _structurBrowser2)
{
final Comparable value1 = getComparable(_parameter, _structurBrowser1);
final Comparable value2 = getComparable(_parameter, _structurBrowser2);
return value1.compareTo(value2);
}
});
return new Return();
}
/**
* @param _parameter Paraemter as passed from the eFasp API
* @return Comparable value
*/
@SuppressWarnings("rawtypes")
protected Comparable getComparable(final Parameter _parameter,
final UIStructurBrowser _structurBrowser)
{
final StringBuilder ret = new StringBuilder();
ret.append(_structurBrowser.getLabel());
return ret.toString();
}
}
|
src/main/efaps/ESJP/org/efaps/esjp/ui/structurbrowser/StandartStructurBrowser_Base.java
|
/*
* Copyright 2003 - 2012 The eFaps Team
*
* 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.
*
* Revision: $Rev$
* Last Changed: $Date$
* Last Changed By: $Author$
*/
package org.efaps.esjp.ui.structurbrowser;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.Map;
import org.efaps.admin.datamodel.Type;
import org.efaps.admin.event.EventExecution;
import org.efaps.admin.event.Parameter;
import org.efaps.admin.event.Parameter.ParameterValues;
import org.efaps.admin.event.Return;
import org.efaps.admin.event.Return.ReturnValues;
import org.efaps.admin.program.esjp.EFapsRevision;
import org.efaps.admin.program.esjp.EFapsUUID;
import org.efaps.db.Instance;
import org.efaps.db.InstanceQuery;
import org.efaps.db.QueryBuilder;
import org.efaps.ui.wicket.models.cell.UIStructurBrowserTableCell;
import org.efaps.ui.wicket.models.objects.UIStructurBrowser;
import org.efaps.ui.wicket.models.objects.UIStructurBrowser.ExecutionStatus;
import org.efaps.util.EFapsException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* TODO description!
*
* @author The eFasp Team
* @version $Id$
*/
@EFapsUUID("d6548826-830b-4540-a46d-d861c3f21f15")
@EFapsRevision("$Rev$")
public abstract class StandartStructurBrowser_Base
implements EventExecution
{
/**
* Logger for this class.
*/
protected static final Logger LOG = LoggerFactory.getLogger(StandartStructurBrowser_Base.class);
/**
* @param _parameter Parameter
* @throws EFapsException on error
* @return Return
*/
public Return execute(final Parameter _parameter)
throws EFapsException
{
Return ret = null;
final UIStructurBrowser strBro = (UIStructurBrowser) _parameter.get(ParameterValues.CLASS);
final ExecutionStatus status = strBro.getExecutionStatus();
if (status.equals(ExecutionStatus.EXECUTE)) {
ret = internalExecute(_parameter);
} else if (status.equals(ExecutionStatus.ALLOWSCHILDREN)) {
ret = allowChildren(_parameter);
} else if (status.equals(ExecutionStatus.ALLOWSITEM)) {
ret = allowItem(_parameter);
} else if (status.equals(ExecutionStatus.CHECKFORCHILDREN)) {
ret = checkForChildren(_parameter);
} else if (status.equals(ExecutionStatus.ADDCHILDREN)) {
ret = addChildren(_parameter);
} else if (status.equals(ExecutionStatus.SORT)) {
ret = sort(_parameter);
} else if (status.equals(ExecutionStatus.CHECKHIDECOLUMN4ROW)) {
ret = checkHideColumn4Row(_parameter);
} else if (status.equals(ExecutionStatus.NODE_REMOVE)) {
ret = onNodeRemove(_parameter);
} else if (status.equals(ExecutionStatus.NODE_INSERTCHILDITEM)) {
ret = onNodeInsertChildItem(_parameter);
} else if (status.equals(ExecutionStatus.NODE_INSERTITEM)) {
ret = onNodeInsertItem(_parameter);
} else if (status.equals(ExecutionStatus.NODE_INSERTCHILDFOLDER)) {
ret = onNodeInsertChildFolder(_parameter);
} else if (status.equals(ExecutionStatus.GETJAVASCRIPT4TARGET)) {
ret = getJavaScript4Target(_parameter);
}
return ret;
}
/**
* Method is called after the insert etc. of a new node in edit mode to
* get a JavaScript that will be appended to the AjaxTarget.
* In this Step the values for the StructurBrowsers also can be altered.
*
* @param _parameter as passed from eFaps API.
* @return Return with SNIPPLET
* @throws EFapsException on error
*/
protected Return getJavaScript4Target(final Parameter _parameter)
throws EFapsException
{
final Return ret = new Return();
//EXAMPLE to be done by implementation
final StringBuilder js = new StringBuilder();
//js.append("document.getElementById..");
ret.put(ReturnValues.SNIPLETT, js.toString());
return ret;
}
/**
* Method to get a list of instances the StructurBrowser will be filled
* with.
* @param _parameter as passed from eFaps API.
* @return Return with instances
* @throws EFapsException on error
*/
protected Return internalExecute(final Parameter _parameter)
throws EFapsException
{
final Return ret = new Return();
final Instance instance = _parameter.getInstance();
final Map<Instance, Boolean> tree = new LinkedHashMap<Instance, Boolean>();
final Map<?, ?> properties = (Map<?, ?>) _parameter.get(ParameterValues.PROPERTIES);
final String typesStr = (String) properties.get("Types");
final String linkFromsStr = (String) properties.get("LinkFroms");
final boolean includeChildTypes = !"false".equalsIgnoreCase((String) properties.get("ExpandChildTypes"));
if (StandartStructurBrowser_Base.LOG.isDebugEnabled()) {
StandartStructurBrowser_Base.LOG.debug("Types: {}\n LinkFroms: {}\n ExpandChildTypes: {}",
new Object[]{typesStr, linkFromsStr, includeChildTypes});
}
if (typesStr != null && !typesStr.isEmpty()) {
final String[] typesArray = typesStr.split(";");
for (int i = 0; i < typesArray.length; i++) {
final Type type = Type.get(typesArray[i]);
final QueryBuilder queryBldr = new QueryBuilder(type);
if (linkFromsStr != null && instance != null && instance.isValid()) {
final String[] linkFroms = linkFromsStr.split(";");
queryBldr.addWhereAttrEqValue(linkFroms[i], instance.getId());
}
addCriteria(_parameter, queryBldr);
final InstanceQuery query = queryBldr.getQuery();
query.execute();
while (query.next()) {
tree.put(query.getCurrentValue(), null);
}
}
}
ret.put(ReturnValues.VALUES, tree);
return ret;
}
/**
* Add additional Criteria to the QueryBuilder.
* To be used by implementation.
*
* @param _parameter Parameter as passed from the eFaps API
* @param _queryBldr QueryBuilder the criteria will be added to
* @throws EFapsException on error
*/
protected void addCriteria(final Parameter _parameter,
final QueryBuilder _queryBldr)
throws EFapsException
{
// used by implementation
}
/**
* Add additional Criteria to the QueryBuilder.
* To be used by implementation.
*
* @param _parameter Parameter as passed from the eFaps API
* @param _queryBldr QueryBuilder the criteria will be added to
* @throws EFapsException on error
*/
protected void addCriteria4Children(final Parameter _parameter,
final QueryBuilder _queryBldr)
throws EFapsException
{
// used by implementation
}
/**
* Method to check if an instance allows children. It is used in the tree to
* determine "folder" or an "item" must be rendered and if the checkForChildren
* method must be executed.
*
* @param _parameter Parameter as passed from the eFaps API
* @return Return with true or false
* @throws EFapsException on error
*/
protected Return allowChildren(final Parameter _parameter)
throws EFapsException
{
final Return ret = new Return();
ret.put(ReturnValues.TRUE, true);
return ret;
}
/**
* Method to check if an instance allows children of type item. It is used in the
* tree to determine if "item" can be rendered. It will only be executed if
* the {@link #allowChildren(Parameter)} method returned true.
*
* @param _parameter Parameter as passed from the eFaps API
* @return Return with true or false
* @throws EFapsException on error
*/
protected Return allowItem(final Parameter _parameter)
throws EFapsException
{
final Return ret = new Return();
ret.put(ReturnValues.TRUE, true);
return ret;
}
/**
* Method to check if an instance has children. It is used in the tree to
* determine if a "plus" to open the children must be rendered.
*
* @param _parameter Parameter as passed from the eFaps API
* @return Return with true or false
* @throws EFapsException on error
*/
protected Return checkForChildren(final Parameter _parameter)
throws EFapsException
{
final Return ret = new Return();
final Map<Instance, Boolean> map = getChildren(_parameter, true);
if (!map.isEmpty()) {
ret.put(ReturnValues.TRUE, true);
}
return ret;
}
/**
* @param _parameter Parameter as passed from the eFaps API
* @param _check check only?
* @return map with instances
* @throws EFapsException on error
*/
protected Map<Instance, Boolean> getChildren(final Parameter _parameter,
final boolean _check)
throws EFapsException
{
final Map<Instance, Boolean> ret = new LinkedHashMap<Instance, Boolean>();
final Instance instance = _parameter.getInstance();
final Map<?, ?> properties = (Map<?, ?>) _parameter.get(ParameterValues.PROPERTIES);
final String typesStr = (String) properties.get("Child_Types");
final String linkFromsStr = (String) properties.get("Child_LinkFroms");
final boolean includeChildTypes = !"false".equalsIgnoreCase((String) properties.get("Child_ExpandChildTypes"));
if (StandartStructurBrowser_Base.LOG.isDebugEnabled()) {
StandartStructurBrowser_Base.LOG.debug("Child_Types: {}\n Child_LinkFroms: {}\n Child_ExpandChildTypes: {}",
new Object[]{typesStr, linkFromsStr, includeChildTypes});
}
if (typesStr != null && !typesStr.isEmpty()) {
final String[] typesArray = typesStr.split(";");
for (int i = 0; i < typesArray.length; i++) {
final Type type = Type.get(typesArray[i]);
final QueryBuilder queryBldr = new QueryBuilder(type);
if (linkFromsStr != null && instance != null && instance.isValid()) {
final String[] linkFroms = linkFromsStr.split(";");
queryBldr.addWhereAttrEqValue(linkFroms[i], instance.getId());
}
addCriteria4Children(_parameter, queryBldr);
final InstanceQuery query = queryBldr.getQuery();
query.setIncludeChildTypes(includeChildTypes);
if (_check) {
query.setLimit(1);
}
query.execute();
while (query.next()) {
ret.put(query.getCurrentValue(), null);
}
}
}
return ret;
}
/**
* Method to add the children to an instance. It is used to expand the
* children of a node in the tree.
*
* @param _parameter Paraemter as passed from the eFasp API
* @return Return with instances
* @throws EFapsException on error
*/
protected Return addChildren(final Parameter _parameter)
throws EFapsException
{
final Return ret = new Return();
final Map<Instance, Boolean> map = getChildren(_parameter, false);
ret.put(ReturnValues.VALUES, map);
return ret;
}
/**
* Method is called from the StructurBrowser in edit mode before rendering
* the columns for row to be able to hide the columns for different rows by
* setting the cell model to hide.
* In this implementation all columns except the StructurBrowser column is
* hidden for the folders.
* @param _parameter Paraemter as passed from the eFasp API
* @return empty Return;
* @throws EFapsException on error
*/
protected Return checkHideColumn4Row(final Parameter _parameter)
throws EFapsException
{
final UIStructurBrowser strBrws = (UIStructurBrowser) _parameter.get(ParameterValues.CLASS);
for (final UIStructurBrowserTableCell cell : strBrws.getColumns()) {
if (strBrws.isAllowChildren() && !cell.isBrowserField()) {
cell.setHide(true);
}
}
return new Return();
}
/**
* Executed on insert of a folder node as an listener and does not
* effect directly the tree, but allows to manipulate it.
*
* @param _parameter _parameter as passed from eFaps API.
* @return empty Return
* @throws EFapsException on error
*/
protected Return onNodeInsertChildFolder(final Parameter _parameter)
throws EFapsException
{
return new Return();
}
/**
* Executed on insert of an new item node as an listener and does not
* effect directly the tree, but allows to manipulate it.
*
* @param _parameter _parameter as passed from eFaps API.
* @return empty Return
* @throws EFapsException on error
*/
protected Return onNodeInsertItem(final Parameter _parameter)
throws EFapsException
{
return new Return();
}
/**
* Executed on insert of an item as child as an listener and does not
* effect directly the tree, but allows to manipulate it.
*
* @param _parameter _parameter as passed from eFaps API.
* @return empty Return
* @throws EFapsException on error
*/
protected Return onNodeInsertChildItem(final Parameter _parameter)
throws EFapsException
{
return new Return();
}
/**
* Executed on removal of a node as an listener and does not
* effect directly the tree, but allows to manipulate it.
*
* @param _parameter _parameter as passed from eFaps API.
* @return empty Return
* @throws EFapsException on error
*/
protected Return onNodeRemove(final Parameter _parameter)
throws EFapsException
{
return new Return();
}
/**
* Method to sort the values of the StructurBrowser.
*
* @param _parameter Paraemter as passed from the eFasp API
* @return empty Return
* @throws EFapsException on error
*/
protected Return sort(final Parameter _parameter)
throws EFapsException
{
final UIStructurBrowser strBro = (UIStructurBrowser) _parameter.get(ParameterValues.CLASS);
Collections.sort(strBro.getChildren(), new Comparator<UIStructurBrowser>() {
public int compare(final UIStructurBrowser _structurBrowser1,
final UIStructurBrowser _structurBrowser2)
{
final String value1 = getSortString(_structurBrowser1);
final String value2 = getSortString(_structurBrowser2);
return value1.compareTo(value2);
}
protected String getSortString(final UIStructurBrowser _structurBrowser)
{
final StringBuilder ret = new StringBuilder();
try {
if (_structurBrowser.getInstance() != null) {
_structurBrowser.getInstance().getType();
}
} catch (final EFapsException e) {
StandartStructurBrowser_Base.LOG.error("error during sorting", e);
}
ret.append(_structurBrowser.getLabel());
return ret.toString();
}
});
return new Return();
}
}
|
- webapp-install: update of StandartStructurBrowser
git-svn-id: 956e271c4e657b06317b2cdcce00231d39cfb789@9074 fee104cc-1dfa-8c0f-632d-d3b7e6b59fb0
|
src/main/efaps/ESJP/org/efaps/esjp/ui/structurbrowser/StandartStructurBrowser_Base.java
|
- webapp-install: update of StandartStructurBrowser
|
<ide><path>rc/main/efaps/ESJP/org/efaps/esjp/ui/structurbrowser/StandartStructurBrowser_Base.java
<ide>
<ide> Collections.sort(strBro.getChildren(), new Comparator<UIStructurBrowser>() {
<ide>
<add> @SuppressWarnings({ "rawtypes", "unchecked" })
<ide> public int compare(final UIStructurBrowser _structurBrowser1,
<ide> final UIStructurBrowser _structurBrowser2)
<ide> {
<del> final String value1 = getSortString(_structurBrowser1);
<del> final String value2 = getSortString(_structurBrowser2);
<add> final Comparable value1 = getComparable(_parameter, _structurBrowser1);
<add> final Comparable value2 = getComparable(_parameter, _structurBrowser2);
<ide> return value1.compareTo(value2);
<ide> }
<del>
<del> protected String getSortString(final UIStructurBrowser _structurBrowser)
<del> {
<del> final StringBuilder ret = new StringBuilder();
<del> try {
<del> if (_structurBrowser.getInstance() != null) {
<del> _structurBrowser.getInstance().getType();
<del> }
<del> } catch (final EFapsException e) {
<del> StandartStructurBrowser_Base.LOG.error("error during sorting", e);
<del> }
<del> ret.append(_structurBrowser.getLabel());
<del> return ret.toString();
<del> }
<ide> });
<ide> return new Return();
<ide> }
<add>
<add> /**
<add> * @param _parameter Paraemter as passed from the eFasp API
<add> * @return Comparable value
<add> */
<add> @SuppressWarnings("rawtypes")
<add> protected Comparable getComparable(final Parameter _parameter,
<add> final UIStructurBrowser _structurBrowser)
<add> {
<add> final StringBuilder ret = new StringBuilder();
<add> ret.append(_structurBrowser.getLabel());
<add> return ret.toString();
<add> }
<ide> }
|
|
Java
|
apache-2.0
|
0fb90ab9f01666e92320b2ed6e0da95ac78208c7
| 0 |
SparklingComet/FakeTrollPlus
|
FakeTrollPlus/src/org/shanerx/faketrollplus/commands/Murder.java
|
package org.shanerx.faketrollplus.commands;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.shanerx.faketrollplus.FakeTrollPlus;
public class Murder implements CommandExecutor {
FakeTrollPlus plugin;
public Murder(FakeTrollPlus instance) {
plugin = instance;
}
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (cmd.getName().equalsIgnoreCase("murder")) {
if (!this.plugin.getConfig().getBoolean("enable-murder")) {
sender.sendMessage(ChatColor.translateAlternateColorCodes('&', this.plugin.getConfig().getString("message-for-disabled-cmds")));
return true;
}
if (!sender.hasPermission("faketroll.murder")) {
sender.sendMessage(ChatColor.RED + "You do not have access to that command!");
return true;
}
if (args.length != 1) {
sender.sendMessage(ChatColor.GOLD + "Usage: /murder <target>");
return true;
}
Player target = this.plugin.getServer().getPlayer(args[0]);
if (target == null) {
sender.sendMessage(ChatColor.translateAlternateColorCodes('&', this.plugin.getConfig().getString("invalid-target")));
return true;
}
String target_name = target.getName();
target.getGameMode();
if (GameMode.CREATIVE != null) {
target.setGameMode(GameMode.SURVIVAL);
target.damage(20.0D);
target.setGameMode(GameMode.CREATIVE);
}
else {
target.damage(20.0D);
}
sender.sendMessage(ChatColor.GOLD + "Why did you do this to " + target_name + "?");
}
return true;
}
}
|
Delete Murder.java
|
FakeTrollPlus/src/org/shanerx/faketrollplus/commands/Murder.java
|
Delete Murder.java
|
<ide><path>akeTrollPlus/src/org/shanerx/faketrollplus/commands/Murder.java
<del>package org.shanerx.faketrollplus.commands;
<del>
<del>import org.bukkit.ChatColor;
<del>import org.bukkit.GameMode;
<del>import org.bukkit.command.Command;
<del>import org.bukkit.command.CommandExecutor;
<del>import org.bukkit.command.CommandSender;
<del>import org.bukkit.entity.Player;
<del>import org.shanerx.faketrollplus.FakeTrollPlus;
<del>
<del>public class Murder implements CommandExecutor {
<del>
<del> FakeTrollPlus plugin;
<del>
<del> public Murder(FakeTrollPlus instance) {
<del>
<del> plugin = instance;
<del>
<del> }
<del>
<del> public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
<del>
<del> if (cmd.getName().equalsIgnoreCase("murder")) {
<del> if (!this.plugin.getConfig().getBoolean("enable-murder")) {
<del> sender.sendMessage(ChatColor.translateAlternateColorCodes('&', this.plugin.getConfig().getString("message-for-disabled-cmds")));
<del> return true;
<del> }
<del> if (!sender.hasPermission("faketroll.murder")) {
<del> sender.sendMessage(ChatColor.RED + "You do not have access to that command!");
<del> return true;
<del> }
<del> if (args.length != 1) {
<del> sender.sendMessage(ChatColor.GOLD + "Usage: /murder <target>");
<del> return true;
<del> }
<del> Player target = this.plugin.getServer().getPlayer(args[0]);
<del> if (target == null) {
<del> sender.sendMessage(ChatColor.translateAlternateColorCodes('&', this.plugin.getConfig().getString("invalid-target")));
<del> return true;
<del> }
<del> String target_name = target.getName();
<del> target.getGameMode();
<del> if (GameMode.CREATIVE != null) {
<del> target.setGameMode(GameMode.SURVIVAL);
<del> target.damage(20.0D);
<del> target.setGameMode(GameMode.CREATIVE);
<del> }
<del> else {
<del> target.damage(20.0D);
<del> }
<del> sender.sendMessage(ChatColor.GOLD + "Why did you do this to " + target_name + "?");
<del> }
<del>
<del> return true;
<del> }
<del>
<del>}
|
||
JavaScript
|
mit
|
0f25bd3bff97330bf19ceea9ad11604f4ca9b551
| 0 |
aspectron/iris-app,aspectron/iris-app
|
#!/usr/bin/env node
//
// -- Zetta Toolkit - Application Framework
//
// Copyright (c) 2011-2014 ASPECTRON Inc.
// All Rights Reserved.
//
// 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 _ = require('underscore');
var fs = require('fs');
var os = require('os');
var util = require('util');
var events = require('events');
var http = require('http');
var https = require('https');
var connect = require('connect');
var express = require('express');
var socketio = require("socket.io");
var path = require('path');
var UUID = require('node-uuid');
var zutils = require('zetta-utils');
var zstats = require('zetta-stats');
var zrpc = require('zetta-rpc');
var zlogin = require('zetta-login');
var exec = require('child_process').exec;
var getmac = require('getmac');
var mongo = require('mongodb');
var bcrypt = require('bcrypt-nodejs');
var os = require('os');
var child_process = require('child_process');
var Translator = require('zetta-translator');
var _cl = console.log;
console.log = function() {
var args = Array.prototype.slice.call(arguments, 0);
args.unshift(zutils.tsString()+' ');
return _cl.apply(console, args);
}
function getConfig(name) {
var filename = name+'.conf';
var host_filename = name+'.'+os.hostname()+'.conf';
var local_filename = name+'.local.conf';
var data = [ ]; // undefined;
fs.existsSync(filename) && data.push(fs.readFileSync(filename) || null);
fs.existsSync(host_filename) && data.push(fs.readFileSync(host_filename) || null);
fs.existsSync(local_filename) && data.push(fs.readFileSync(local_filename) || null);
if(!data[0] && !data[1])
throw new Error("Unable to read config file:"+(filename+'').magenta.bold)
function merge(dst, src) {
_.each(src, function(v, k) {
if(_.isArray(v)) { dst[k] = [ ]; merge(dst[k], v); }
// if(_.isArray(v)) { if(!_.isArray(dst[k])) dst[k] = [ ]; merge(dst[k], v); }
else if(_.isObject(v)) { if(!dst[k]) dst[k] = { }; merge(dst[k], v); }
else { if(_.isArray(src)) dst.push(v); else dst[k] = v; }
})
}
var o = { }
_.each(data, function(conf) {
if(!conf || !conf.toString('utf-8').length)
return;
var layer = eval('('+conf.toString('utf-8')+')');
merge(o, layer);
})
return o;
}
function readJSON(filename) {
if(!fs.existsSync(filename))
return undefined;
var text = fs.readFileSync(filename, { encoding : 'utf-8' });
if(!text)
return undefined;
try {
return JSON.parse(text);
} catch(ex) {
console.log("Error parsing file:",filename);
console.log(ex);
console.log('Offending content follows:',text);
}
return undefined;
}
function writeJSON(filename, data) {
fs.writeFileSync(filename, JSON.stringify(data, null, '\t'));
}
function Application(appFolder, appConfig) {
var self = this;
events.EventEmitter.call(this);
self.readJSON = readJSON;
self.writeJSON = writeJSON;
self.appFolder = appFolder;
self.pkg = self.readJSON(path.join(appFolder,'package.json'));
if(!self.pkg)
throw new Error("Application Unable to read package.json");
if(!self.pkg.name)
throw new Error("package.json must contain module 'name' field");
self.getConfig = function(name) {
return getConfig(path.join(appFolder,'config', name))
}
self.config = self.getConfig(self.pkg.name);
self.settings = { }
http.globalAgent.maxSockets = self.config.maxHttpSockets || 1024; // 1024;
https.globalAgent.maxSockets = self.config.maxHttpSockets || 1024;
if(process.platform != 'win32' && self.config.maxSockets) {
if(fs.existsSync('node_modules/posix')) {
try { require('posix').setrlimit('nofile', self.config.maxSockets); } catch(ex) {
console.error(ex.stack);
}
}
else
console.log("WARNING - Please install POSIX module (npm install posix)".red.bold);
}
self.pingDataObject = { }
// ---
self.restoreDefaultSettings = function(name, force) {
var filename = path.join(self.appFolder,'config', name+'.settings');
if(!fs.existsSync(filename)) {
self.settings = { }
return;
}
var data = fs.readFileSync(filename);
self.settings = eval('('+data.toString('utf-8')+')');
}
self.restoreSettings = function(name) {
self.restoreDefaultSettings(name);
var host_filename = path.join(self.appFolder,'config', name+'.'+os.hostname().toLowerCase()+'.settings');
if(!fs.existsSync(host_filename))
return;
var data = fs.readFileSync(host_filename);
var settings = eval('('+data.toString('utf-8')+')');
_.each(settings, function(o, key) {
if(self.settings[key])
self.settings[key].value = o.value;
})
}
self.storeSettings = function(name) {
var host_filename = path.join(self.appFolder,'config', name+'.'+os.hostname().toLowerCase()+'.settings');
fs.writeFileSync(host_filename, JSON.stringify(self.settings, null, '\t'));
}
// ---
self.initTranslator = function(callback) {
if(self.config.translator) {
var options = {
storagePath: path.join(appFolder,'config'),
rootFolderPath: appFolder
};
options = _.extend(self.config.translator, options);
self.translator = new Translator(options, function() {
self.translator.separateEditor();
});
}
callback();
}
self.initCertificates = function(callback) {
if(self.verbose)
console.log('zetta-app: loading certificates from ',appFolder+'/'+self.config.certificates);
if(self.certificates)
callback && callback();
self.certificates = {
key: fs.readFileSync(path.join(appFolder,self.config.certificates)+'.key').toString(),
cert: fs.readFileSync(path.join(appFolder,self.config.certificates)+'.crt').toString(),
ca: [ ]
}
/* var cert = [ ]
var chain = fs.readFileSync(__dirname + '/certificates/gd_bundle-g2.crt').toString().split('\n');
_.each(chain, function(line) {
cert.push(line);
if(line.match('/-END CERTIFICATE-/')) {
certificates.ca.push(cert.join('\n'));
cert = [ ]
}
})
*/
callback && callback();
}
self.initMonitoringInterfaces = function(callback) {
self.stats = new zstats.StatsD(self.config.statsd, self.uuid, self.pkg.name);
// self.stats = new zstats.StatsD(self.config.statsd, self.uuid, self.config.application);
self.profiler = new zstats.Profiler(self.stats);
self.monitor = new zstats.Monitor(self.stats, self.config.monitor);
callback();
}
/* var databaseConfig = [
{
config: 'main',
collections: [
{collection: 'resources', indexes: 'owner'},
{collection: 'users', indexes: 'email->unique|google.id|facebook.id'}
]
}
];
*/
self.initDatabaseConfig = function(callback) {
var dbconf = self.databaseConfig;
console.log("Connecting to database...".bold);
self.db = { }
self.databases = { }
initDatabaseConnection();
function initDatabaseConnection() {
var config = dbconf.shift();
if (!config)
return callback();
var name = config.config;
var db = self.config.mongodb[name];
if(!db)
throw new Error("Config missing database configuration for '"+name+"'");
mongo.Db.connect(db, function (err, database) {
if (err)
return callback(err);
self.databases[name] = database;
console.log("DB '" + (name) + "' connected", self.config.mongodb[name].bold);
zutils.bind_database_config(database, config.collections, function (err, db) {
if (err)
return callback(err);
_.extend(self.db, db);
initDatabaseConnection();
})
})
}
}
self.initDatabaseCollections = function(callback) {
console.log("Connecting to database...".bold);
self.db = { }
self.databases = { }
mongo.Db.connect(self.config.mongodb, function (err, database) {
if (err)
return callback(err);
self.database = database;
console.log("Database connected", self.config.mongodb);
zutils.bind_database_config(database, self.databaseCollections, function (err, db) {
if (err)
return callback(err);
_.extend(self.db, db);
callback();
})
})
}
self.initExpressConfig = function(callback) {
var ExpressSession = require('express-session');
self.app = express();
self.app.set('views', path.join(appFolder,'views'));
self.app.set('view engine', 'ejs');
self.app.engine('html', require('ejs').renderFile);
self.app.use(require('body-parser')());//express.json());
self.app.use(require('method-override')());
self.app.use(require('cookie-parser')(self.config.http.session.secret));
if(self.config.mongodb) {
var MongoStore = require('connect-mongo')(ExpressSession);
self.app.sessionStore = new MongoStore({url: self.config.mongodb.main || self.config.mongodb}, function() {
self.app.use(ExpressSession({
secret: self.config.http.session.secret,
key: self.config.http.session.key,
cookie: self.config.http.session.cookie,
store: self.app.sessionStore
}));
return callback();
});
}
else
if(self.config.http && self.config.http.session) {
self.app.sessionSecret = self.config.http.session.secret;
var CookieSession = require('cookie-session');
self.app.use(CookieSession({
secret: self.config.http.session.secret,
key: self.config.http.session.key,
}));
return callback();
}
}
self.initExpressHandlers = function(callback) {
var ErrorHandler = require('errorhandler')();
var isErrorView = fs.existsSync(path.join(self.appFolder,'views','error.ejs'));
self.handleHttpError = function(response, req, res, next) {
if(req.xhr) {
res.json({errors: _.isArray(response.errors) ? response.errors : [response.errors]});
return;
}
else
if(isErrorView) {
res.render('error', { error : error });
return;
}
else {
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.end("Server Error");
return;
}
}
if(self.config.translator)
self.app.use(self.translator.useSession);
/**
* response = {
* status: {Number}
* errors: {String | Array}
* }
*/
function HttpError(response) {
res.status(response.status);
self.handleHttpError(respo)
}
self.app.use(function(req, res, next) {
res.sendHttpError = function (response) {
self.handleHttpError(response, req, res, next);
}
next();
})
var loginConfig = self.config.http.login;
if(loginConfig && loginConfig.authenticator) {
switch(loginConfig.authenticator.type) {
case 'basic' : {
console.log("AUTHENTICATOR CONFIG:", loginConfig.authenticator);
console.log("LOGIN CONFIG:", loginConfig);
self.authenticator = new zlogin.BasicAuthenticator(self, loginConfig.authenticator);
self.login = new zlogin.Login(self, self.authenticator, loginConfig);
self.login.init(self.app);
} break;
}
}
if(self.router)
self.router.init(self.app);
self.emit('init::express', self.app);
if(self.config.http.static) {
var ServeStatic = require('serve-static');
_.each(self.config.http.static, function(dst, src) {
console.log('HTTP serving '+src.cyan.bold+' -> '+dst.cyan.bold);
self.app.use(src, ServeStatic(path.join(appFolder, dst)));
})
}
/**
* Handles errors were sent via next() method
*
* following formats are supported:
* next(new Error('Something blew up'));
* next(400);
* next({status: 400, errors: 'Activation code is wrong'});
* next({status: 400, errors: ['Activation code is wrong']});
*
*/
self.app.use(function (err, req, res, next) {
if (typeof err == 'number') {
err = {
status: err,
errors: http.STATUS_CODES[err] || "Error"
};
}
else
if (typeof err == 'string') {
console.error(err);
err = {
status: 500,
errors: 'Internal Server Error'
};
}
else
if (err instanceof Error) {
if (self.config.development) {
err.status = 500;
return ErrorHandler(err, req, res, next);
}
else
{
console.error(err.stack);
err = {
status: 500,
errors: 'Internal Server Error'
};
}
}
res.sendHttpError(err);
});
finish();
function finish() {
callback();
}
};
self.initHttpServer = function(callback) {
var CERTIFICATES = (self.config.http.ssl && self.config.certificates) ? self.certificates : null;
var https_server = CERTIFICATES ? https.createServer(CERTIFICATES, self.app) : http.createServer(self.app);
self.io = socketio.listen(https_server, { 'log level': 0, 'secure': CERTIFICATES ? true : false });
if(self.router && self.router.initWebSocket)
self.router.initWebSocket(self.io);
self.config.websocket && self.initWebsocket(function(){});
self.emit('init::websockets');
self.emit('init::http::done');
https_server.listen(self.config.http.port, function (err) {
if (err) {
console.error("Unable to start HTTP(S) server on port" + self.config.http.port);
return callback(err);
}
console.log('HTTP server listening on port ' + (self.config.http.port+'').bold);
if (!CERTIFICATES)
console.log(("WARNING - SSL is currently disabled").magenta.bold);
if (self.config.secure_under_username) {
console.log("Securing run-time to user '" + self.config.secure_under_username + "'");
zutils.secure_under_username(self.config.secure_under_username);
}
self.emit('init::http-server')
callback();
});
};
self.initSupervisors = function(callback) {
// console.log("initSupervisors");
if(!self.certificates)
throw new Error("Application supervisor requires configured certificates");
console.log("Connecting to supervisor(s)...".bold, self.config.supervisor.address);
self.supervisor = new zrpc.Client({
address: self.config.supervisor.address,
auth: self.config.supervisor.auth,
certificates: self.certificates,
node: self.mac,
mac: self.mac,
uuid : self.uuid,
designation: self.pkg.name, // self.config.application,
pingDataObject : self.pingDataObject
});
self.supervisor.registerListener(self);
callback();
self.on('package::info::get', function(msg) {
console.log(msg.op.yellow.bold);
self.supervisor.dispatch({ op : 'package::info::data', uuid : self.uuid, pkg : self.pkg })
})
}
self.initWebsocket = function(callback) {
self.webSocketMap = [ ]
self.webSockets = self.io.of(self.config.websocket.path).on('connection', function(socket) {
console.log("websocket "+socket.id+" connected");
self.emit('websocket::connect', socket);
self.webSocketMap[socket.id] = socket;
socket.on('disconnect', function() {
self.emit('websocket::disconnect', socket);
delete self.webSocketMap[socket.id];
console.log("websocket "+socket.id+" disconnected");
})
socket.on('rpc::request', function(msg) {
try {
var listeners = self.listeners(msg.req.op);
if(listeners.length == 1) {
listeners[0].call(socket, msg.req, function(err, resp) {
socket.emit('rpc::response', {
_resp : msg._req,
err : err,
resp : resp,
});
})
}
else
if(listeners.length)
{
socket.emit('rpc::response', {
_resp : msg._req,
err : { error : "Too many handlers for '"+msg.req.op+"'" }
});
}
else
{
socket.emit('rpc::response', {
_resp : msg._req,
err : { error : "No such handler '"+msg.req.op+"'" }
});
}
}
catch(ex) { console.error(ex.stack); }
});
socket.on('message', function(msg) {
try {
self.emit(msg.op, msg, socket);
}
catch(ex) { console.error(ex.stack); }
});
});
callback();
}
// --
function updateServerStats() {
self.pingDataObject.loadAvg = self.monitor.stats.loadAvg;
self.pingDataObject.memory = self.monitor.stats.memory;
dpc(5 * 1000, updateServerStats)
}
// --
var initStepsBeforeHttp_ = [ ]
var initSteps_ = [ ]
self.initBeforeHttp = function(fn) {
initStepsBeforeHttp_.push(fn);
}
self.init = function(fn) {
initSteps_.push(fn);
}
self.run = function(callback) {
var steps = new zutils.Steps();
self.config.translator && steps.push(self.initTranslator);
self.config.certificates && steps.push(self.initCertificates);
self.config.statsd && steps.push(self.initMonitoringInterfaces);
self.config.mongodb && self.databaseConfig && steps.push(self.initDatabaseConfig);
self.config.mongodb && self.databaseCollections && steps.push(self.initDatabaseCollections);
self.emit('init::database', steps);
_.each(initStepsBeforeHttp_, function(fn) {
steps.push(fn);
})
if(self.config.http) {
steps.push(self.initExpressConfig);
steps.push(self.initExpressHandlers);
steps.push(self.initHttpServer);
}
//self.config.mailer && steps.push(initMailer);
self.config.supervisor && self.config.supervisor.address && steps.push(self.initSupervisors);
getmac.getMac(function (err, mac) {
if (err) return callback(err);
self.mac = mac.split(process.platform == 'win32' ? '-' : ':').join('').toLowerCase();
self.macBytes = _.map(self.mac.match(/.{1,2}/g), function(v) { return parseInt(v, 16); })
var uuid = self.appFolder.replace(/\\/g,'/').split('/').pop();
if(!uuid || uuid.length != 36) {
var local = self.readJSON('uuid');
if(local && local.uuid)
uuid = local.uuid;
else {
uuid = UUID.v1({ node : self.macBytes });
self.writeJSON("uuid", { uuid : uuid });
}
}
self.uuid = uuid;
console.log("App UUID:".bold,self.uuid.bold);
_.each(initSteps_, function(fn) {
steps.push(fn);
})
self.emit('init::build', steps);
steps.run(function (err) {
if (err)
throw err;
self.config.statsd && updateServerStats();
console.log("init OK".bold);
self.emit('init::done');
callback && callback();
})
})
return self;
}
self.caption = self.pkg.name;
dpc(function() {
if(self.caption) {
zutils.render(self.caption.replace('-',' '), null, function(err, caption) {
console.log('\n'+caption);
dpc(function() {
self.run();
})
})
}
else {
self.run();
}
})
}
util.inherits(Application, events.EventEmitter);
Application.getConfig = getConfig;
module.exports = {
Application : Application
}
|
zetta-app.js
|
#!/usr/bin/env node
//
// -- Zetta Toolkit - Application Framework
//
// Copyright (c) 2011-2014 ASPECTRON Inc.
// All Rights Reserved.
//
// 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 _ = require('underscore');
var fs = require('fs');
var os = require('os');
var util = require('util');
var events = require('events');
var http = require('http');
var https = require('https');
var connect = require('connect');
var express = require('express');
var socketio = require("socket.io");
var path = require('path');
var UUID = require('node-uuid');
var zutils = require('zetta-utils');
var zstats = require('zetta-stats');
var zrpc = require('zetta-rpc');
var zlogin = require('zetta-login');
var exec = require('child_process').exec;
var getmac = require('getmac');
var mongo = require('mongodb');
var bcrypt = require('bcrypt-nodejs');
// var Mailer = require('./lib/mailer');
// temporary hack while working on translation module
var os = require('os');
var child_process = require('child_process');
//var translator = require('zetta-translator');
var Translator = require('zetta-translator');
var _cl = console.log;
console.log = function() {
var args = Array.prototype.slice.call(arguments, 0);
args.unshift(zutils.tsString()+' ');
return _cl.apply(console, args);
}
function getConfig(name) {
var filename = name+'.conf';
var host_filename = name+'.'+os.hostname()+'.conf';
var local_filename = name+'.local.conf';
var data = [ ]; // undefined;
fs.existsSync(filename) && data.push(fs.readFileSync(filename) || null);
fs.existsSync(host_filename) && data.push(fs.readFileSync(host_filename) || null);
fs.existsSync(local_filename) && data.push(fs.readFileSync(local_filename) || null);
if(!data[0] && !data[1])
throw new Error("Unable to read config file:"+(filename+'').magenta.bold)
function merge(dst, src) {
_.each(src, function(v, k) {
if(_.isArray(v)) { dst[k] = [ ]; merge(dst[k], v); }
// if(_.isArray(v)) { if(!_.isArray(dst[k])) dst[k] = [ ]; merge(dst[k], v); }
else if(_.isObject(v)) { if(!dst[k]) dst[k] = { }; merge(dst[k], v); }
else { if(_.isArray(src)) dst.push(v); else dst[k] = v; }
})
}
var o = { }
_.each(data, function(conf) {
if(!conf || !conf.toString('utf-8').length)
return;
var layer = eval('('+conf.toString('utf-8')+')');
merge(o, layer);
})
return o;
}
function readJSON(filename) {
if(!fs.existsSync(filename))
return undefined;
var text = fs.readFileSync(filename, { encoding : 'utf-8' });
if(!text)
return undefined;
try {
return JSON.parse(text);
} catch(ex) {
console.log("Error parsing file:",filename);
console.log(ex);
console.log('Offending content follows:',text);
}
return undefined;
}
function writeJSON(filename, data) {
fs.writeFileSync(filename, JSON.stringify(data, null, '\t'));
}
function Application(appFolder, appConfig) {
var self = this;
events.EventEmitter.call(this);
self.readJSON = readJSON;
self.writeJSON = writeJSON;
self.appFolder = appFolder;
self.pkg = self.readJSON(path.join(appFolder,'package.json'));
if(!self.pkg)
throw new Error("Application Unable to read package.json");
if(!self.pkg.name)
throw new Error("package.json must contain module 'name' field");
self.getConfig = function(name) {
return getConfig(path.join(appFolder,'config', name))
}
self.config = self.getConfig(self.pkg.name);
self.settings = { }
/*if(_.isString(appConfig))
self.config = getConfig(path.join(appFolder,'config', appConfig));
else
if(_.isObject(appConfig))
self.config = appConfig;
else
throw new Error("Application() requires config object as argument");
if(!self.config.application)
throw new Error("Application() requires 'application' attribute in the config");
*/
//if(self.config.caption)
// zutils.render(self.config.caption);
http.globalAgent.maxSockets = self.config.maxHttpSockets || 1024; // 1024;
https.globalAgent.maxSockets = self.config.maxHttpSockets || 1024;
if(process.platform != 'win32' && self.config.maxSockets) {
if(fs.existsSync('node_modules/posix')) {
try { require('posix').setrlimit('nofile', self.config.maxSockets); } catch(ex) {
console.error(ex.stack);
}
}
else
console.log("WARNING - Please install POSIX module (npm install posix)".red.bold);
}
self.pingDataObject = { }
// ---
self.restoreDefaultSettings = function(name, force) {
var filename = path.join(self.appFolder,'config', name+'.settings');
if(!fs.existsSync(filename)) {
self.settings = { }
return;
}
var data = fs.readFileSync(filename);
self.settings = eval('('+data.toString('utf-8')+')');
}
self.restoreSettings = function(name) {
self.restoreDefaultSettings(name);
var host_filename = path.join(self.appFolder,'config', name+'.'+os.hostname().toLowerCase()+'.settings');
if(!fs.existsSync(host_filename))
return;
var data = fs.readFileSync(host_filename);
var settings = eval('('+data.toString('utf-8')+')');
_.each(settings, function(o, key) {
if(self.settings[key])
self.settings[key].value = o.value;
})
}
self.storeSettings = function(name) {
var host_filename = path.join(self.appFolder,'config', name+'.'+os.hostname().toLowerCase()+'.settings');
fs.writeFileSync(host_filename, JSON.stringify(self.settings, null, '\t'));
}
// ---
self.initTranslator = function(callback) {
if(self.config.translator) {
var options = {
storagePath: path.join(appFolder,'config'),
rootFolderPath: appFolder
};
options = _.extend(self.config.translator, options);
self.translator = new Translator(options, function() {
self.translator.separateEditor();
});
}
callback();
}
// ---
self.initCertificates = function(callback) {
if(self.verbose)
console.log('zetta-app: loading certificates from ',appFolder+'/'+self.config.certificates);
if(self.certificates)
callback && callback();
self.certificates = {
key: fs.readFileSync(path.join(appFolder,self.config.certificates)+'.key').toString(),
cert: fs.readFileSync(path.join(appFolder,self.config.certificates)+'.crt').toString(),
ca: [ ]
}
/* var cert = [ ]
var chain = fs.readFileSync(__dirname + '/certificates/gd_bundle-g2.crt').toString().split('\n');
_.each(chain, function(line) {
cert.push(line);
if(line.match('/-END CERTIFICATE-/')) {
certificates.ca.push(cert.join('\n'));
cert = [ ]
}
})
*/
callback && callback();
}
self.initMonitoringInterfaces = function(callback) {
self.stats = new zstats.StatsD(self.config.statsd, self.uuid, self.pkg.name);
// self.stats = new zstats.StatsD(self.config.statsd, self.uuid, self.config.application);
self.profiler = new zstats.Profiler(self.stats);
self.monitor = new zstats.Monitor(self.stats, self.config.monitor);
callback();
}
/* var databaseConfig = [
{
config: 'main',
collections: [
{collection: 'resources', indexes: 'owner'},
{collection: 'users', indexes: 'email->unique|google.id|facebook.id'}
]
}
];
*/
self.initDatabaseConfig = function(callback) {
var dbconf = self.databaseConfig;
console.log("Connecting to database...".bold);
self.db = { }
self.databases = { }
initDatabaseConnection();
function initDatabaseConnection() {
var config = dbconf.shift();
if (!config)
return callback();
var name = config.config;// || config.alias;
/*if (typeof(self.config.db) != 'object' || !self.config.db[name]) {
console.error(("Unable to find DB configuration for " + name).red.bold);
return callback(new Error("Unable to find DB configuration (Update local config file!)"));
}*/
var db = self.config.mongodb[name];
if(!db)
throw new Error("Config missing database configuration for '"+name+"'");
mongo.Db.connect(db, function (err, database) {
if (err)
return callback(err);
self.databases[name] = database;
console.log("DB '" + (name) + "' connected", self.config.mongodb[name].bold);
zutils.bind_database_config(database, config.collections, function (err, db) {
if (err)
return callback(err);
_.extend(self.db, db);
initDatabaseConnection();
})
})
}
}
self.initDatabaseCollections = function(callback) {
console.log("Connecting to database...".bold);
self.db = { }
self.databases = { }
mongo.Db.connect(self.config.mongodb, function (err, database) {
if (err)
return callback(err);
self.database = database;
console.log("Database connected", self.config.mongodb);
zutils.bind_database_config(database, self.databaseCollections, function (err, db) {
if (err)
return callback(err);
_.extend(self.db, db);
callback();
})
})
}
/* self.initMailer = function(callback) {
self.mailer = Mailer(self);
callback();
}
*/
self.initExpressConfig = function(callback) {
// console.log("initExpress");
var ExpressSession = require('express-session');
self.app = express();
self.app.set('views', path.join(appFolder,'views'));
self.app.set('view engine', 'ejs');
self.app.engine('html', require('ejs').renderFile);
self.app.use(require('body-parser')());//express.json());
self.app.use(require('method-override')());
self.app.use(require('cookie-parser')(self.config.http.session.secret));
if(self.config.mongodb) {
var MongoStore = require('connect-mongo')(ExpressSession);
self.app.sessionStore = new MongoStore({url: self.config.mongodb.main || self.config.mongodb}, function() {
self.app.use(ExpressSession({
secret: self.config.http.session.secret,
key: self.config.http.session.key,
cookie: self.config.http.session.cookie,
store: self.app.sessionStore
}));
return callback();
});
}
else
if(self.config.http && self.config.http.session) {
self.app.sessionSecret = self.config.http.session.secret;
var CookieSession = require('cookie-session');
self.app.use(CookieSession({
secret: self.config.http.session.secret,
key: self.config.http.session.key,
}));
return callback();
}
}
self.initExpressHandlers = function(callback) {
var ErrorHandler = require('errorhandler')();
var isErrorView = fs.existsSync(path.join(self.appFolder,'views','error.ejs'));
self.handleHttpError = function(response, req, res, next) {
if(req.xhr) {
res.json({errors: _.isArray(response.errors) ? response.errors : [response.errors]});
return;
}
else
if(isErrorView) {
res.render('error', { error : error });
return;
}
else {
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.end("Server Error");
return;
}
}
if(self.config.translator)
self.app.use(self.translator.useSession);
/**
* response = {
* status: {Number}
* errors: {String | Array}
* }
*/
function HttpError(response) {
res.status(response.status);
self.handleHttpError(respo)
}
self.app.use(function(req, res, next) {
res.sendHttpError = function (response) {
self.handleHttpError(response, req, res, next);
}
next();
})
var loginConfig = self.config.http.login;
if(loginConfig && loginConfig.authenticator) {
switch(loginConfig.authenticator.type) {
case 'basic' : {
console.log("AUTHENTICATOR CONFIG:", loginConfig.authenticator);
console.log("LOGIN CONFIG:", loginConfig);
self.authenticator = new zlogin.BasicAuthenticator(self, loginConfig.authenticator);
self.login = new zlogin.Login(self, self.authenticator, loginConfig);
self.login.init(self.app);
} break;
}
}
if(self.router)
self.router.init(self.app);
self.emit('init::express', self.app);
if(self.config.http.static) {
var ServeStatic = require('serve-static');
_.each(self.config.http.static, function(dst, src) {
console.log('HTTP serving '+src.cyan.bold+' -> '+dst.cyan.bold);
self.app.use(src, ServeStatic(path.join(appFolder, dst)));
})
}
/**
* Handles errors were sent via next() method
*
* following formats are supported:
* next(new Error('Something blew up'));
* next(400);
* next({status: 400, errors: 'Activation code is wrong'});
* next({status: 400, errors: ['Activation code is wrong']});
*
*/
self.app.use(function (err, req, res, next) {
if (typeof err == 'number') {
err = {
status: err,
errors: http.STATUS_CODES[err] || "Error"
};
}
else
if (typeof err == 'string') {
console.error(err);
err = {
status: 500,
errors: 'Internal Server Error'
};
}
else
if (err instanceof Error) {
if (self.config.development) {
err.status = 500;
return ErrorHandler(err, req, res, next);
}
else
{
console.error(err.stack);
err = {
status: 500,
errors: 'Internal Server Error'
};
}
}
res.sendHttpError(err);
});
finish();
function finish() {
callback();
}
};
self.initRedirect = function(callback) {
/* var http_app = express();
http_app.get('*', function (req, res) {
res.redirect("https://" + req.headers.host + req.url);
})
var http_server = http.createServer(http_app);
http_server.listen(self.config.http.port, function (err) {
if (err) {
console.error("Unable to start HTTP server on port" + self.config.http.port);
return callback(err);
}
console.log("HTTP Server listening on port " + self.config.http.port);
callback && callback();
})
*/
}
self.initHttpServer = function(callback) {
var CERTIFICATES = (self.config.http.ssl && self.config.certificates) ? self.certificates : null;
var https_server = CERTIFICATES ? https.createServer(CERTIFICATES, self.app) : http.createServer(self.app);
self.io = socketio.listen(https_server, { 'log level': 0, 'secure': CERTIFICATES ? true : false });
if(self.router && self.router.initWebSocket)
self.router.initWebSocket(self.io);
//console.log("init::websockets".yellow.bold);
self.config.websocket && self.initWebsocket(function(){});
self.emit('init::websockets');
//console.log("init::http::done".yellow.bold);
self.emit('init::http::done');
//console.log("Starting listening...".yellow.bold);
//console.log("PORT IS:",self.config.http.port);
//console.log("CONFIG IS:", self.config);
https_server.listen(self.config.http.port, function (err) {
if (err) {
console.error("Unable to start HTTP(S) server on port" + self.config.http.port);
return callback(err);
}
console.log('HTTP server listening on port ' + (self.config.http.port+'').bold);
if (!CERTIFICATES)
console.log(("WARNING - SSL is currently disabled").magenta.bold);
if (self.config.secure_under_username) {
console.log("Securing run-time to user '" + self.config.secure_under_username + "'");
zutils.secure_under_username(self.config.secure_under_username);
}
self.emit('init::http-server')
callback();
});
};
self.initSupervisors = function(callback) {
// console.log("initSupervisors");
if(!self.certificates)
throw new Error("Application supervisor requires configured certificates");
console.log("Connecting to supervisor(s)...".bold, self.config.supervisor.address);
self.supervisor = new zrpc.Client({
address: self.config.supervisor.address,
auth: self.config.supervisor.auth,
certificates: self.certificates,
node: self.mac,
mac: self.mac,
uuid : self.uuid,
designation: self.pkg.name, // self.config.application,
pingDataObject : self.pingDataObject
});
self.supervisor.registerListener(self);
callback();
self.on('package::info::get', function(msg) {
console.log(msg.op.yellow.bold);
self.supervisor.dispatch({ op : 'package::info::data', uuid : self.uuid, pkg : self.pkg })
})
/*
self.on('git-pull', function () {
console.log("Executing git pull");
exec("git pull", function (err, stdout, stderr) {
console.log(stdout);
})
})
self.on('git-pull-restart', function () {
console.log("Executing git pull & restarting on user request");
exec("git pull", function (err, stdout, stderr) {
console.log(stdout);
dpc(5000, function () {
process.exit(0);
})
})
})
self.on('package::config::set', function(msg) {
var config = path.join(self.appFolder,'config',self.config.application+'.local.conf');
fs.writeFileSync(config, JSON.stringify(msg.config, null, '\t'));
dpc(function() {
// process.exit(0);
})
})
self.on('package::config::get', function(msg) {
var config = path.join(self.appFolder,'config',self.config.application+'.local.conf');
var text = fs.readFileSync(config, { encoding : 'utf-8'});
try {
var o = JSON.parse(text);
o && self.rpc.dispatch({ op : 'package::config::set', config : o })
} catch(ex) { return console.log(ex.stack); }
})
self.on('package::info::get', function(msg) {
self.rpc.dispatch({ op : 'package::info::set', pkg : self.pkg })
})
self.on('node::get-runtime-info', function() {
var o = {
// TODO - READ CONFIG FILES?
// TODO - READ CONFIG FILES?
// TODO - READ CONFIG FILES?
// TODO - READ CONFIG FILES?
// TODO - READ CONFIG FILES?
// TODO - READ CONFIG FILES?
// TODO - READ CONFIG FILES?
// TODO - READ CONFIG FILES?
// TODO - READ CONFIG FILES?
}
})
*/
}
self.initWebsocket = function(callback) {
self.webSocketMap = [ ]
self.webSockets = self.io.of(self.config.websocket.path).on('connection', function(socket) {
console.log("websocket "+socket.id+" connected");
self.emit('websocket::connect', socket);
self.webSocketMap[socket.id] = socket;
socket.on('disconnect', function() {
self.emit('websocket::disconnect', socket);
delete self.webSocketMap[socket.id];
console.log("websocket "+socket.id+" disconnected");
})
socket.on('rpc::request', function(msg) {
try {
var listeners = self.listeners(msg.req.op);
if(listeners.length == 1) {
listeners[0].call(socket, msg.req, function(err, resp) {
socket.emit('rpc::response', {
_resp : msg._req,
err : err,
resp : resp,
});
})
}
else
if(listeners.length)
{
socket.emit('rpc::response', {
_resp : msg._req,
err : { error : "Too many handlers for '"+msg.req.op+"'" }
});
}
else
{
socket.emit('rpc::response', {
_resp : msg._req,
err : { error : "No such handler '"+msg.req.op+"'" }
});
}
}
catch(ex) { console.error(ex.stack); }
});
socket.on('message', function(msg) {
try {
self.emit(msg.op, msg, socket);
}
catch(ex) { console.error(ex.stack); }
});
});
callback();
}
// --
function updateServerStats() {
self.pingDataObject.loadAvg = self.monitor.stats.loadAvg;
self.pingDataObject.memory = self.monitor.stats.memory;
dpc(5 * 1000, updateServerStats)
}
// --
var initStepsBeforeHttp_ = [ ]
var initSteps_ = [ ]
self.initBeforeHttp = function(fn) {
initStepsBeforeHttp_.push(fn);
}
self.init = function(fn) {
initSteps_.push(fn);
}
self.run = function(callback) {
var steps = new zutils.Steps();
self.config.translator && steps.push(self.initTranslator);
self.config.certificates && steps.push(self.initCertificates);
self.config.statsd && steps.push(self.initMonitoringInterfaces);
self.config.mongodb && self.databaseConfig && steps.push(self.initDatabaseConfig);
self.config.mongodb && self.databaseCollections && steps.push(self.initDatabaseCollections);
self.emit('init::database', steps);
_.each(initStepsBeforeHttp_, function(fn) {
steps.push(fn);
})
if(self.config.http) {
steps.push(self.initExpressConfig);
steps.push(self.initExpressHandlers);
steps.push(self.initHttpServer);
}
//self.config.mailer && steps.push(initMailer);
self.config.supervisor && self.config.supervisor.address && steps.push(self.initSupervisors);
getmac.getMac(function (err, mac) {
if (err) return callback(err);
self.mac = mac.split(process.platform == 'win32' ? '-' : ':').join('').toLowerCase();
self.macBytes = _.map(self.mac.match(/.{1,2}/g), function(v) { return parseInt(v, 16); })
var uuid = self.appFolder.replace(/\\/g,'/').split('/').pop();
if(!uuid || uuid.length != 36) {
var local = self.readJSON('uuid');
if(local && local.uuid)
uuid = local.uuid;
else {
uuid = UUID.v1({ node : self.macBytes });
self.writeJSON("uuid", { uuid : uuid });
}
}
self.uuid = uuid;
console.log("App UUID:".bold,self.uuid.bold);
_.each(initSteps_, function(fn) {
steps.push(fn);
})
self.emit('init::build', steps);
steps.run(function (err) {
if (err)
throw err;
self.config.statsd && updateServerStats();
console.log("init OK".bold);
self.emit('init::done');
callback && callback();
})
})
return self;
}
self.caption = self.pkg.name;
dpc(function() {
if(self.caption) {
zutils.render(self.caption.replace('-',' '), null, function(err, caption) {
console.log('\n'+caption);
dpc(function() {
self.run();
})
})
}
else {
self.run();
}
})
}
util.inherits(Application, events.EventEmitter);
Application.getConfig = getConfig;
module.exports = {
Application : Application
}
|
Cleanup
|
zetta-app.js
|
Cleanup
|
<ide><path>etta-app.js
<ide> var getmac = require('getmac');
<ide> var mongo = require('mongodb');
<ide> var bcrypt = require('bcrypt-nodejs');
<del>// var Mailer = require('./lib/mailer');
<del>
<del>// temporary hack while working on translation module
<ide> var os = require('os');
<ide> var child_process = require('child_process');
<del>//var translator = require('zetta-translator');
<ide> var Translator = require('zetta-translator');
<ide>
<ide> var _cl = console.log;
<ide>
<ide> self.settings = { }
<ide>
<del> /*if(_.isString(appConfig))
<del> self.config = getConfig(path.join(appFolder,'config', appConfig));
<del> else
<del> if(_.isObject(appConfig))
<del> self.config = appConfig;
<del> else
<del> throw new Error("Application() requires config object as argument");
<del>
<del> if(!self.config.application)
<del> throw new Error("Application() requires 'application' attribute in the config");
<del>*/
<del> //if(self.config.caption)
<del> // zutils.render(self.config.caption);
<del>
<del>
<del>
<ide> http.globalAgent.maxSockets = self.config.maxHttpSockets || 1024; // 1024;
<ide> https.globalAgent.maxSockets = self.config.maxHttpSockets || 1024;
<ide> if(process.platform != 'win32' && self.config.maxSockets) {
<ide> self.pingDataObject = { }
<ide>
<ide> // ---
<del>
<del>
<ide>
<ide> self.restoreDefaultSettings = function(name, force) {
<ide> var filename = path.join(self.appFolder,'config', name+'.settings');
<ide>
<ide> callback();
<ide> }
<del>
<del> // ---
<ide>
<ide> self.initCertificates = function(callback) {
<ide> if(self.verbose)
<ide> if (!config)
<ide> return callback();
<ide>
<del>
<del>
<del> var name = config.config;// || config.alias;
<del>
<del> /*if (typeof(self.config.db) != 'object' || !self.config.db[name]) {
<del> console.error(("Unable to find DB configuration for " + name).red.bold);
<del> return callback(new Error("Unable to find DB configuration (Update local config file!)"));
<del> }*/
<del>
<del>
<add> var name = config.config;
<ide> var db = self.config.mongodb[name];
<ide>
<ide> if(!db)
<ide> }
<ide>
<ide>
<del>/* self.initMailer = function(callback) {
<del> self.mailer = Mailer(self);
<del>
<del> callback();
<del> }
<del>*/
<del>
<del>
<ide> self.initExpressConfig = function(callback) {
<del> // console.log("initExpress");
<ide> var ExpressSession = require('express-session');
<ide>
<ide> self.app = express();
<ide>
<ide> };
<ide>
<del> self.initRedirect = function(callback) {
<del>
<del>/* var http_app = express();
<del> http_app.get('*', function (req, res) {
<del> res.redirect("https://" + req.headers.host + req.url);
<del> })
<del> var http_server = http.createServer(http_app);
<del>
<del> http_server.listen(self.config.http.port, function (err) {
<del> if (err) {
<del> console.error("Unable to start HTTP server on port" + self.config.http.port);
<del> return callback(err);
<del> }
<del> console.log("HTTP Server listening on port " + self.config.http.port);
<del> callback && callback();
<del> })
<del>*/
<del> }
<del>
<ide> self.initHttpServer = function(callback) {
<ide>
<ide> var CERTIFICATES = (self.config.http.ssl && self.config.certificates) ? self.certificates : null;
<ide> self.io = socketio.listen(https_server, { 'log level': 0, 'secure': CERTIFICATES ? true : false });
<ide> if(self.router && self.router.initWebSocket)
<ide> self.router.initWebSocket(self.io);
<del> //console.log("init::websockets".yellow.bold);
<ide> self.config.websocket && self.initWebsocket(function(){});
<ide> self.emit('init::websockets');
<del> //console.log("init::http::done".yellow.bold);
<ide> self.emit('init::http::done');
<del> //console.log("Starting listening...".yellow.bold);
<del> //console.log("PORT IS:",self.config.http.port);
<del> //console.log("CONFIG IS:", self.config);
<ide> https_server.listen(self.config.http.port, function (err) {
<ide> if (err) {
<ide> console.error("Unable to start HTTP(S) server on port" + self.config.http.port);
<ide> console.log(msg.op.yellow.bold);
<ide> self.supervisor.dispatch({ op : 'package::info::data', uuid : self.uuid, pkg : self.pkg })
<ide> })
<del>
<del>/*
<del> self.on('git-pull', function () {
<del> console.log("Executing git pull");
<del> exec("git pull", function (err, stdout, stderr) {
<del> console.log(stdout);
<del> })
<del> })
<del>
<del> self.on('git-pull-restart', function () {
<del> console.log("Executing git pull & restarting on user request");
<del> exec("git pull", function (err, stdout, stderr) {
<del> console.log(stdout);
<del> dpc(5000, function () {
<del> process.exit(0);
<del> })
<del> })
<del> })
<del>
<del> self.on('package::config::set', function(msg) {
<del> var config = path.join(self.appFolder,'config',self.config.application+'.local.conf');
<del> fs.writeFileSync(config, JSON.stringify(msg.config, null, '\t'));
<del> dpc(function() {
<del> // process.exit(0);
<del> })
<del> })
<del>
<del> self.on('package::config::get', function(msg) {
<del> var config = path.join(self.appFolder,'config',self.config.application+'.local.conf');
<del> var text = fs.readFileSync(config, { encoding : 'utf-8'});
<del> try {
<del> var o = JSON.parse(text);
<del> o && self.rpc.dispatch({ op : 'package::config::set', config : o })
<del> } catch(ex) { return console.log(ex.stack); }
<del>
<del> })
<del>
<del> self.on('package::info::get', function(msg) {
<del> self.rpc.dispatch({ op : 'package::info::set', pkg : self.pkg })
<del> })
<del>
<del> self.on('node::get-runtime-info', function() {
<del> var o = {
<del> // TODO - READ CONFIG FILES?
<del> // TODO - READ CONFIG FILES?
<del> // TODO - READ CONFIG FILES?
<del> // TODO - READ CONFIG FILES?
<del>
<del> // TODO - READ CONFIG FILES?
<del> // TODO - READ CONFIG FILES?
<del> // TODO - READ CONFIG FILES?
<del> // TODO - READ CONFIG FILES?
<del> // TODO - READ CONFIG FILES?
<del> }
<del> })
<del>*/
<ide> }
<ide>
<ide> self.initWebsocket = function(callback) {
|
|
JavaScript
|
apache-2.0
|
e2cfffbbe41601f96970b87a74706105ea3be284
| 0 |
windmill/windmill,windmill/windmill,windmill/windmill,windmill/windmill,windmill/windmill,windmill/windmill
|
/*
Copyright 2006-2007, Open Source Applications Foundation
2006, Open Source Applications Foundation
Copyright 2004 ThoughtWorks, 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.
*/
/*
Functionality that works for every browser
Mozilla specific functionality abstracted to mozcontroller.js
Safari specific functionality abstracted to safcontroller.js
IE specific functionality abstracted to iecontroller.js
The reason for this is that the start page only includes the one corresponding
to the current browser, this means that the functionality in the controller
object is only for the current browser, and there is only one copy of the code being
loaded into the browser for performance.
*/
windmill.controller = new function () {
//Some namespacing for controller functionality
this.extensions = {};
this.commands = {};
this.asserts = {};
this.waits = {};
this._getDocumentStr = function () { return windmill.testWindowStr + '.document'; }
this._getWindowStr = function() { return windmill.testWindowStr; }
this._getDocument = function () { return windmill.testWindow.document; }
this._getWindow = function() { return windmill.testWindow; }
/************************************
/* User facing windmill functionality
/************************************/
/**
* Does absolutely nothing
*/
this.defer = function (){
//At some point we may want to display somewhere that we continually get deferred
//when the backend has nothing for us to do
};
/**
* Creates a windmill variable antry from a DOM element attribute
* @param {Object} paramObject The JavaScript object providing the necessary options
*/
this.storeVarFromLocAttrib = function (paramObject) {
var element = lookupNode(paramObject);
var arr = paramObject.options.split('|');
var varName = arr[0];
var attrib = arr[1];
var attribValue = element[attrib];
if (windmill.varRegistry.hasKey('{$'+varName+'}')){
windmill.varRegistry.removeItem('{$'+varName +'}');
windmill.varRegistry.addItem('{$'+varName +'}', attribValue);
}
else{
windmill.varRegistry.addItem('{$'+varName +'}', attribValue);
}
};
/**
* Creates a windmill variable antry from evaluated JavaScript
* @param {Object} paramObject The JavaScript providing the necessary options
* @throws SyntaxError JavaScript eval exception
*/
this.storeVarFromJS = function (paramObject) {
//extract the options
var arr = paramObject.options.split('|');
paramObject.name = arr[0];
paramObject.js = arr[1];
paramObject.value = eval.call(windmill.testWin(), paramObject.js);
//if the code evaled and returned a value add it
if (windmill.varRegistry.hasKey('{$'+paramObject.name +'}')){
windmill.varRegistry.removeItem('{$'+paramObject.name +'}');
windmill.varRegistry.addItem('{$'+paramObject.name +'}',paramObject.value);
}
else{
windmill.varRegistry.addItem('{$'+paramObject.name +'}',paramObject.value);
}
};
/**
* Navigates the Windmill testing applicatoin to the provided url
* @param {Object} paramObject The JavaScript object used to provide the necessary options
*/
this.open = function (paramObject) {
//clear the domain forwarding cache
if (paramObject.reset == undefined){
windmill.service.setTestURL(windmill.initialHost);
}
//We need to tell the service where we are before we
//head to a new page
windmill.testWin().location = paramObject.url;
};
/**
* Select an option from a Select element by either value or innerHTML
* @param {Object} paramObject The JavaScript providing: Locator, option or value
* @throws Exception Unable to select the specified option.
*/
this.select = function (paramObject) {
//lookup
var element = lookupNode(paramObject);
//if the index selector was used, select by index
if (paramObject.index){
element.options[paramObject.index].selected = true;
return true;
}
//Sometimes we can't directly access these at this point, not sure why
try {
if (element.options[element.options.selectedIndex].text == paramObject['option']){
return true;
}
} catch(err){ windmill.err(err)}
try {
if (element.options[element.options.selectedIndex].value == paramObject['val']){
return true;
}
} catch(err){ windmill.err(err)}
windmill.events.triggerEvent(element, 'focus', false);
var optionToSelect = null;
for (opt = 0; opt < element.options.length; opt++){
try {
var el = element.options[opt];
if (paramObject.option != undefined){
if(el.innerHTML.indexOf(paramObject.option) != -1){
if (el.selected && el.options[opt] == optionToSelect){
continue;
}
optionToSelect = el;
optionToSelect.selected = true;
windmill.events.triggerEvent(element, 'change', true);
break;
}
}
else {
if(el.value.indexOf(paramObject.val) != -1){
if (el.selected && el.options[opt] == optionToSelect){
continue;
}
optionToSelect = el;
optionToSelect.selected = true;
windmill.events.triggerEvent(element, 'change', true);
break;
}
}
}
catch(err){}
}
if (optionToSelect == null){
throw "Unable to select the specified option.";
}
};
/**
* Drag one DOM element to the top x,y coords of another specified DOM element
* @param {Object} paramObject The JavaScript object providing: Locator, option or value
*/
this.dragDropElemToElem = function(paramObject){
var p = paramObject;
//Get the drag and dest
var drag = lookupNode(p);
//create the params for the destination
var destParams = {};
for (attrib in p) {
if (attrib.indexOf('opt') != -1){
destParams[attrib.replace('opt', '')] = p[attrib];
break;
}
}
var dest = lookupNode(destParams);
windmill.pauseLoop();
windmill.controller.dragElem = drag;
windmill.controller.destElem = dest;
//get the bounding objects we want for starting and ending places
//for the drag
function getBounding(elem){
//backup way to get the coords
function getCoords(obj) {
var curleft = curtop = 0;
if (obj.offsetParent) {
do {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
}
return {left:curleft,top:curtop};
}
//get the coords and divide to find the middle
if ( windmill.browser.isIE || windmill.browser.isGecko ) {
var bound = elem.getBoundingClientRect();
bound = {left:parseInt((bound.left+bound.right)/
2),top:parseInt((bound.top+bound.bottom)/2)};
}
else {
var bound = getCoords(elem);
bound = {left:parseInt(bound.left+elem.offsetWidth/
2),top:parseInt(bound.top+elem.offsetHeight/2)}
}
return bound;
};
var dragCoords = null;
var destCoords = null;
dragCoords = getBounding(drag);
destCoords = getBounding(dest);
//Do the initial move to the drag element position
windmill.events.triggerMouseEvent(windmill.testWin().document.body, 'mousemove', true, dragCoords.left, dragCoords.top);
windmill.events.triggerMouseEvent(drag, 'mousedown', true, dragCoords.left, dragCoords.top);
windmill.controller.doRem = function() {
windmill.continueLoop();
}
windmill.controller.doMove = function(attrib, startx, starty) {
windmill.events.triggerMouseEvent(windmill.testWin().document.body, 'mousemove', true, startx, starty);
windmill.controller.moveCount--;
if (windmill.controller.moveCount == 0){
windmill.events.triggerMouseEvent(windmill.controller.dragElem, 'mouseup', true, startx, starty);
if (!windmill.browser.isIE){
windmill.events.triggerMouseEvent(windmill.controller.dragElem, 'click', true, startx, starty);
}
setTimeout('windmill.controller.doRem()', 1000);
}
}
windmill.controller.moveCount = 0;
var startx = dragCoords.left;
var starty = dragCoords.top;
var endx = destCoords.left;
var endy = destCoords.top;
var delay = 0;
while (startx != endx){
if (startx < endx){ startx++; }
else{ startx--; }
setTimeout("windmill.controller.doMove('left',"+startx+","+starty+")", delay)
windmill.controller.moveCount++;
delay = delay + 5;
}
//move the y
while (starty != endy){
if (starty < endy){ starty++; }
else{ starty--; }
setTimeout("windmill.controller.doMove('top',"+startx+","+starty+")", delay);
windmill.controller.moveCount++;
delay = delay + 5;
}
};
/**
* Drag a specified DOM element a specified amount of pixels
* @param {Object} paramObject The JavaScript object providing: Locator and pixels (x,y)
*/
this.dragDropElem = function(paramObject) {
var p = paramObject;
var el = lookupNode(p);
windmill.pauseLoop();
windmill.controller.moveCount = 0;
windmill.controller.dragElem = el;
//ie specific drag and drop simulation
if (windmill.browser.isIE){
var dist = p.pixels.split(',');
dist[0] = dist[0].replace('(','');
dist[1] = dist[1].replace(')','');
var box = el.getBoundingClientRect();
var left = box.left;
var top = box.top + 2;
windmill.events.triggerMouseEvent(windmill.testWin().document.body, 'mousemove', true, left, top);
windmill.events.triggerMouseEvent(el, 'mousedown', true, left, top);
// windmill.events.triggerMouseEvent(windmill.testWin().document.body, 'mousemove', true, left+100, top);
// windmill.events.triggerMouseEvent(el, 'mouseup', true, left, top);
windmill.controller.doRem = function(x,y) {
try{
windmill.events.triggerMouseEvent(windmill.controller.dragElem, 'mouseup', true, x, y);
}
catch(err){}
windmill.continueLoop();
}
windmill.controller.doMove = function(x,y) {
windmill.events.triggerMouseEvent(windmill.testWin().document.body, 'mousemove', true, x, y);
windmill.controller.moveCount--;
if (windmill.controller.moveCount == 0){
setTimeout('windmill.controller.doRem('+x+','+y+')', 1000);
}
}
var delay = 0;
var i = 0;
var newX = left;
while(i != dist[0]){
if (i < dist[0]){ newX++; }
else{ newX--; }
setTimeout("windmill.controller.doMove("+newX+","+top+")", delay)
if (i < dist[0]){ i++; }
else{ i--; }
windmill.controller.moveCount++;
delay = delay + 5;
}
//var delay = 0;
var i = 0;
var newBox = el.getBoundingClientRect();
var newY = top;
while(i != dist[1]){
if (i < dist[1]){ newY++; }
else{ newY--; }
setTimeout("windmill.controller.doMove("+newX+", "+newY+")", delay)
if (i < dist[1]){ i++; }
else{ i--; }
windmill.controller.moveCount++;
delay = delay + 5;
}
}
//all other browsers with sane event models
else {
// var i = windmill.testWindow.document.createElement('img');
// i.id = "mc";
// i.style.border = "0px";
// i.style.left = '0px';
// i.style.top = '0px';
// i.style.position = "absolute";
// i.zIndex = "100000000000";
// el.appendChild(i);
// i.src = "/windmill-serv/img/mousecursor.png";
//takes a coordinates param (x,y),(x,y) start, end
var dist = p.pixels.split(',');
dist[0] = dist[0].replace('(','');
dist[1] = dist[1].replace(')','');
windmill.events.triggerMouseEvent(windmill.testWin().document.body, 'mousemove', true, el.offsetLeft, el.offsetTop);
windmill.events.triggerMouseEvent(el, 'mousedown', true);
windmill.controller.doRem = function() {
windmill.events.triggerMouseEvent(windmill.controller.dragElem, 'mouseup', true);
windmill.events.triggerMouseEvent(windmill.controller.dragElem, 'click', true);
windmill.continueLoop();
}
windmill.controller.doMove = function(x,y) {
windmill.events.triggerMouseEvent(windmill.testWin().document.body, 'mousemove', true, x, y);
windmill.controller.moveCount--;
if (windmill.controller.moveCount == 0){
setTimeout('windmill.controller.doRem()', 1000);
}
}
var delay = 0;
var i = 0;
while(i != dist[0]) {
setTimeout("windmill.controller.doMove("+i+", 0)", delay)
if (i < dist[0]){ i++; }
else{ i--; }
windmill.controller.moveCount++;
delay = delay + 5;
}
var newX = i;
//var delay = 0;
var i = 0;
while(i != dist[1]) {
setTimeout("windmill.controller.doMove("+newX+", "+i+")", delay)
if (i < dist[1]){ i++; }
else{ i--; }
windmill.controller.moveCount++;
delay = delay + 5;
}
}
};
/**
* Use absolute coordinates to click an element, and move it from one set of coords to another.
* @param {Object} paramObject The JavaScript object providing: Locator, coords ( Format; ex. '(100,100),(300,350)' )
*/
this.dragDropAbs = function (paramObject) {
var p = paramObject;
var el = lookupNode(p);
windmill.pauseLoop();
windmill.controller.moveCount = 0;
windmill.controller.ddeParamObj = paramObject;
var webApp = windmill.testWin();
//takes a coordinates param (x,y),(x,y) start, end
var coords = p.coords.split('),(');
var start = coords[0].split(',');
start[0] = start[0].replace('(','');
var end = coords[1].split(',');
end[1] = end[1].replace(')','');
//get to the starting point
var i = windmill.testWin().document.createElement('img');
i.id = "mc";
i.style.border = "0px";
i.style.left = start[0]+'px';
i.style.top = start[1]+'px';
i.style.position = "absolute";
i.zIndex = "100000000000";
windmill.testWin().document.body.appendChild(i);
i.src = "/windmill-serv/img/mousecursor.png";
windmill.events.triggerMouseEvent(webApp.document.body, 'mousemove', true, start[0], start[1]);
windmill.events.triggerMouseEvent(lookupNode(p), 'mousedown', true, start[0], start[1]);
var startx = start[0];
var starty = start[1];
windmill.controller.remMouse = function(x,y) {
windmill.events.triggerMouseEvent(lookupNode(p), 'mouseup', true, x, y);
windmill.events.triggerMouseEvent(lookupNode(p), 'click', true);
var c = windmill.testWin().document.getElementById('mc');
windmill.testWin().document.body.removeChild(c);
windmill.continueLoop();
}
windmill.controller.doMove = function(attrib, startx, starty) {
var w = windmill.testWin().document;
if (attrib == "left"){ w.getElementById('mc').style['left'] = startx+'px'; }
else{ w.getElementById('mc').style['top'] = starty+'px'; }
windmill.events.triggerMouseEvent(w.body, 'mousemove', true, startx, starty);
windmill.controller.moveCount--;
if (windmill.controller.moveCount == 0){
w.getElementById('mc').src = "/windmill-serv/img/mousecursorred.png";
setTimeout('windmill.controller.remMouse('+startx+','+starty+')', 1500);
}
}
//move the x
var delay = 0;
while (startx != end[0]) {
if (startx < end[0]){ startx++; }
else{ startx--; }
setTimeout("windmill.controller.doMove('left',"+startx+","+starty+")", delay)
windmill.controller.moveCount++;
delay = delay + 5;
}
//move the y
//var delay = 0;
while (starty != end[1]){
if (starty < end[1]){ starty++; }
else{ starty--; }
setTimeout("windmill.controller.doMove('top',"+startx+","+starty+")", delay);
windmill.controller.moveCount++;
delay = delay + 5;
}
};
/**
* Use absolute coordinates to click an element, and move it from one set of coords to another.
* @param {Object} paramObject The JavaScript object providing: Locator, destination paramObject
*/
this.dragDrop = function (paramObject) {
var p = paramObject;
var hash_key;
eval ("hash_key=" + p.dragged.jsid + ";");
p.dragged.id = hash_key;
delete p.dragged.jsid;
function getPos(elem, evType) {
// paramObject.mouseDownPos or param_obj.mouseUpPos
var t = evType + 'Pos';
var res = [];
// Explicit function for getting XY of both
// start and end position for drag start
// to be calculated from the initial pos of the
// dragged, and end to be calculated from the
// position of the destination
if (p[t]) {
var f = eval(p[t]);
res = f(elem);
}
// Otherwise naively assume top/left XY for both
// start (dragged) and end (destination)
else {
res = [elem.offsetLeft, elem.offsetTop];
}
return res;
};
var dragged = lookupNode(p.dragged);
var dest = lookupNode(p.destination);
var mouseDownPos = getPos(dragged, 'mouseDown');
var mouseUpPos = getPos(dest, 'mouseUp');
var webApp = windmill.testWin();
windmill.events.triggerMouseEvent(webApp.document.body, 'mousemove', true, mouseDownPos[0], mouseDownPos[1]);
windmill.events.triggerMouseEvent(dragged, 'mousedown', true);
windmill.events.triggerMouseEvent(webApp.document.body, 'mousemove', true, mouseUpPos[0], mouseUpPos[1]);
windmill.events.triggerMouseEvent(dragged, 'mouseup', true);
windmill.events.triggerMouseEvent(dragged, 'click', true);
};
/**
* Raw drag drop using abs x,y
* @param {Object} paramObject The JavaScript object providing: Locator, source paramObject, dest paramObj
*/
this.dragDropXY = function (paramObject) {
var p = paramObject;
var webApp = windmill.testWin();
windmill.events.triggerMouseEvent(webApp.document.body, 'mousemove', true, p.source[0], p.source[1]);
windmill.events.triggerMouseEvent(webApp.document.body, 'mousedown', true);
windmill.events.triggerMouseEvent(webApp.document.body, 'mousemove', true, p.destination[0], p.destination[1]);
windmill.events.triggerMouseEvent(webApp.document.body, 'mouseup', true);
windmill.events.triggerMouseEvent(webApp.document.body, 'click', true);
};
/**
* Create a Windmill variable registry entry from the href of a provided locator
* @param {Object} paramObject The JavaScript object providing: Locator
*/
this.storeURL = function(paramObject) {
var linkNode = lookupNode(paramObject);
windmill.varRegistry.addItem('{$'+paramObject.link +'}',linkNode.href);
}
/**
* Manually change the document.domain of the windmill IDE window
* @param {Object} paramObject The JavaScript object providing: domain
*/
this.setDocDomain = function(paramObject) {
document.domain = paramObject.domain;
};
/**
* Fire a mousedown event on the provided node
* @param {Object} paramObject The JavaScript object providing: Locator
*/
this.mouseDown = function (paramObject) {
var mupElement = lookupNode(paramObject);
if (mupElement == null){
mupElement = windmill.testWin().document.body;
}
if (windmill.browser.isIE){
var box = mupElement.getBoundingClientRect();
var left = box.left;
var top = box.top + 2;
windmill.events.triggerMouseEvent(mupElement, 'mousedown', true, left, top);
}
else { windmill.events.triggerMouseEvent(mupElement, 'mousedown', true); }
};
/**
* Fire a mousemove event ending at a specified set of coordinates
* @param {Object} paramObject The JavaScript object providing: coords
*/
this.mouseMoveTo = function (paramObject) {
var p = paramObject;
var webApp = windmill.testWin();
var coords = p.coords.split(',');
coords[0] = coords[0].replace('(','');
coords[1] = coords[1].replace(')','');
windmill.events.triggerMouseEvent(webApp.document.body, 'mousemove', true, coords[0], coords[1]);
};
// this.mouseMove = function (paramObject){
// var p = paramObject;
// var webApp = windmill.testWin();
// var coords = p.coords.split('),(');
//
// var start = coords[0].split(',');
// start[0] = start[0].replace('(','');
//
// var end = coords[1].split(',');
// end[1] = end[1].replace(')','');
// windmill.events.triggerMouseEvent(webApp.document.body, 'mousemove', true, start[0], start[1]);
// windmill.events.triggerMouseEvent(webApp.document.body, 'mousemove', true, end[0], end[1]);
// alert('mooch??');
//
// return true;
// };
/**
* Fire the mousemove event starting at one point and ending at another
* @param {Object} paramObject The JavaScript object providing: coords (Format: '(x,y),(x,y)' )
*/
this.mouseMove = function (paramObject) {
windmill.pauseLoop();
windmill.controller.moveCount = 0;
var p = paramObject;
var webApp = windmill.testWin();
//takes a coordinates param (x,y),(x,y) start, end
var coords = p.coords.split('),(');
var start = coords[0].split(',');
start[0] = start[0].replace('(','');
var end = coords[1].split(',');
end[1] = end[1].replace(')','');
//get to the starting point
var i = windmill.testWin().document.createElement('img');
i.id = "mc";
i.style.border = "0px";
i.style.left = start[0]+'px';
i.style.top = start[1]+'px';
i.style.position = "absolute";
i.zIndex = "100000000000";
windmill.testWin().document.body.appendChild(i);
i.src = "/windmill-serv/img/mousecursor.png";
windmill.events.triggerMouseEvent(webApp.document.body, 'mousemove', true, start[0], start[1]);
var startx = start[0];
var starty = start[1];
windmill.controller.remMouse = function() {
var c = windmill.testWin().document.getElementById('mc');
windmill.testWin().document.body.removeChild(c);
windmill.continueLoop();
}
windmill.controller.doMove = function(attrib, startx, starty) {
var w = windmill.testWin().document;
if (attrib == "left"){ w.getElementById('mc').style['left'] = startx+'px'; }
else{ w.getElementById('mc').style['top'] = starty+'px'; }
windmill.events.triggerMouseEvent(w.body, 'mousemove', true, startx, starty);
windmill.controller.moveCount--;
if (windmill.controller.moveCount == 0){
w.getElementById('mc').src = "/windmill-serv/img/mousecursorred.png";
setTimeout('windmill.controller.remMouse()', 1000);
}
}
//move the x
var delay = 0;
while (startx != end[0]){
if (startx < end[0]){ startx++; }
else{ startx--; }
setTimeout("windmill.controller.doMove('left',"+startx+","+starty+")", delay)
windmill.controller.moveCount++;
delay = delay + 5;
}
//move the y
//var delay = 0;
while (starty != end[1]){
if (starty < end[1]){ starty++; }
else{ starty--; }
setTimeout("windmill.controller.doMove('top',"+startx+","+starty+")", delay);
windmill.controller.moveCount++;
delay = delay + 5;
}
};
/**
* Fire the mouseup event against a specified node, defaulting to document.body
* @param {Object} paramObject The JavaScript object providing: Locator
*/
this.mouseUp = function (paramObject){
try {
var mupElement = lookupNode(paramObject);
} catch(err){}
if (mupElement == null){
mupElement = windmill.testWin().document.body;
}
if(windmill.browser.isIE){
var box = mupElement.getBoundingClientRect();
var left = box.left;
var top = box.top + 2;
windmill.events.triggerMouseEvent(mupElement, 'mouseup', true, left, top);
}
else{
windmill.events.triggerMouseEvent(mupElement, 'mouseup', true);
}
};
/**
* Fire the mouseover event against a specified DOM element
* @param {Object} paramObject The JavaScript object providing: Locator
*/
this.mouseOver = function (paramObject){
var mdnElement = lookupNode(paramObject);
windmill.events.triggerMouseEvent(mdnElement, 'mouseover', true);
};
/**
* Fire the mouseout event against a specified DOM element
* @param {Object} paramObject The JavaScript object providing: Locator
*/
this.mouseOut = function (paramObject){
var mdnElement = lookupNode(paramObject);
windmill.events.triggerMouseEvent(mdnElement, 'mouseout', true);
};
/**
* Fire keypress event
* @param
*/
this.keyPress = function(paramObject){
try {
var element = lookupNode(paramObject);
} catch(err){ var element = windmill.testWin().document.body; }
paramObject.options = paramObject.options.replace(/ /g, "");
var opts = paramObject.options.split(",");
windmill.events.triggerEvent(element, 'focus', false);
//element, eventType, keySequence, canBubble, controlKeyDown, altKeyDown, shiftKeyDown, metaKeyDown
windmill.events.triggerKeyEvent(element, "keypress", opts[0], eval(opts[1]), eval(opts[2]), eval(opts[3]), eval(opts[4]), eval(opts[5]));
};
/**
* Fire keydown event
* @param
*/
this.keyDown = function(paramObject){
try {
var element = lookupNode(paramObject);
} catch(err){ var element = windmill.testWin().document.body; }
paramObject.options = paramObject.options.replace(/ /g, "");
var opts = paramObject.options.split(",");
windmill.events.triggerEvent(element, 'focus', false);
//element, eventType, keySequence, canBubble, controlKeyDown, altKeyDown, shiftKeyDown, metaKeyDown
windmill.events.triggerKeyEvent(element, "keyDown", opts[0], eval(opts[1]), eval(opts[2]), eval(opts[3]), eval(opts[4]), eval(opts[5]));
};
/**
* Fire keydown event
* @param
*/
this.keyUp = function(paramObject){
try {
var element = lookupNode(paramObject);
} catch(err){ var element = windmill.testWin().document.body; }
paramObject.options = paramObject.options.replace(/ /g, "");
var opts = paramObject.options.split(",");
windmill.events.triggerEvent(element, 'focus', false);
//element, eventType, keySequence, canBubble, controlKeyDown, altKeyDown, shiftKeyDown, metaKeyDown
windmill.events.triggerKeyEvent(element, "keyUp", opts[0], eval(opts[1]), eval(opts[2]), eval(opts[3]), eval(opts[4]), eval(opts[5]));
};
/**
* Trigger the back function in the Windmill Testing Application Window
*/
this.goBack = function(paramObject){
windmill.testWin().history.back();
}
/**
* Trigger the forward function in the Windmill Testing Application Window
*/
this.goForward = function(paramObject){
windmill.testWin().history.forward();
}
/**
* Trigger the refresh function in the Windmill Testing Application Window
*/
this.refresh = function(paramObject){
windmill.testWin().location.reload(true);
}
/**
* Trigger the scroll function in the Windmill Testing Application Window
* @param {Object} paramObject The JavaScript object providing: coords
*/
this.scroll = function(paramObject){
var d = paramObject.coords;
d = d.replace('(','');
d = d.replace(')','');
var cArr = d.split(',');
windmill.testWin().scrollTo(cArr[0],cArr[1]);
}
/**
* Re-write the window alert function to instead send it's output to the output tab
*/
this.reWriteAlert = function(paramObject){
try {
windmill.testWin().alert = function(s){
windmill.alertStore.push(s);
windmill.out("<br>Alert: <b><font color=\"#fff32c\">" + s + "</font>.</b>");
};
} catch(err){ windmill.err(err); }
rwaRecurse = function(frame){
var iframeCount = frame.frames.length;
var iframeArray = frame.frames;
for (var i=0;i<iframeCount;i++){
try{
iframeArray[i].alert = function(s){
windmill.alertStore.push(s);
windmill.out("<br>Alert: <b><font color=\"#fff32c\">" + s + "</font>.</b>");
};
rwaRecurse(iframeArray[i]);
}
catch(error){
windmill.err('Could not bind to iframe number '+ iframeCount +' '+error);
}
}
};
rwaRecurse(windmill.testWin());
};
/**
* Re-write the window alert function to instead send it's output to the output tab
*/
this.reWriteConfirm = function(paramObject){
try {
windmill.testWin().confirm = function(s){
windmill.confirmStore.push(s);
return windmill.confirmAnswer;
};
} catch(err){ windmill.err(err); }
rwcRecurse = function(frame){
var iframeCount = frame.frames.length;
var iframeArray = frame.frames;
for (var i=0;i<iframeCount;i++){
try{
iframeArray[i].confirm = function(s){
windmill.confirmStore.push(s);
return windmill.confirmAnswer;
};
rwaRecurse(iframeArray[i]);
}
catch(error){
windmill.err('Could not bind to iframe number '+ iframeCount +' '+error);
}
}
};
rwcRecurse(windmill.testWin());
};
this.reWritePopups = function(paramObject){
if (typeof windmill.testWin().oldOpen == "function"){
return;
}
//Window popup wrapper
try { windmill.testWin().oldOpen = windmill.testWin().open; }
catch(err){
windmill.err("Did you close a popup window, without using closeWindow?");
windmill.err("We can no longer access test windows, start over and don't close windows manually.");
return;
}
//re-define the open function
windmill.testWin().open = function(){
if (windmill.browser.isIE){
var str = '';
var arg;
for (var i = 0; i < arguments.length; i++) {
arg = arguments[i];
if (typeof arg == 'string') {
str += '"' + arg + '"';
}
else {
str += arg;
}
str += ","
}
str = str.substr(0, str.length-1);
eval('var newWindow = windmill.testWin().oldOpen(' + str + ');');
}
else {
var newWindow = windmill.testWin().oldOpen.apply(windmill.testWin(), arguments);
}
var newReg = [];
for (var i = 0; i < windmill.windowReg.length; i++){
try{
var wDoc = windmill.windowReg[i].document;
newReg.push(windmill.windowReg[i]);
} catch(err){}
windmill.windowReg = newReg;
}
windmill.windowReg.push(newWindow);
};
};
/**
* Update the windmill.testWindow reference to point to a different window
* @param {Object} paramObject The JavaScript object providing: path
* @throws EvalException "Error setting the test window, undefined."
*/
this.setTestWindow = function(paramObject){
var res = eval ('windmill.testWindow ='+ paramObject.path +';');
if (typeof(res) == 'undefined'){
throw "Error setting the test window, undefined."
}
};
/**
* Set the windmill.testWindow by iterating through the windowReg to find a matching title
* @param {Object} paramObject The JavaScript object providing: title
*/
this.setWindowByTitle = function(paramObject){
var title = paramObject.title;
var newW = windmill.testWin();
for (var i = 0; i < windmill.windowReg.length; i++){
if (windmill.windowReg[i].document.title == title){
newW = windmill.windowReg[i];
}
}
windmill.testWindow = newW;
};
/**
* Revert the windmill.testWindow to the original when the page was loaded
* @param {Object} paramObject The JavaScript object providing: title
*/
this.revertWindow = function(paramObject){
windmill.testWindow = windmill.baseTestWindow;
};
/**
* If the windmill.testWindow is not the original opener, close it.
*/
this.closeWindow = function(paramObject){
if (windmill.testWin() != windmill.baseTestWindow){
windmill.testWin().close();
windmill.testWindow = windmill.baseTestWindow;
}
};
/**
* Execute some arbitrary JS in the testing app window
* @param {Object} paramObject The JavaScript object providing: js
*/
this.execArbTestWinJS = function(paramObject){
var js = paramObject.js;
eval.call(windmill.testWin(), js);
};
/**
* Execute some arbitrary JS
* @param {Object} paramObject The JavaScript object providing: js
*/
this.execIDEJS = function(paramObject){
var js = paramObject.js;
eval.call(window, js);
};
};
|
windmill/html/js/controller/controller.js
|
/*
Copyright 2006-2007, Open Source Applications Foundation
2006, Open Source Applications Foundation
Copyright 2004 ThoughtWorks, 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.
*/
/*
Functionality that works for every browser
Mozilla specific functionality abstracted to mozcontroller.js
Safari specific functionality abstracted to safcontroller.js
IE specific functionality abstracted to iecontroller.js
The reason for this is that the start page only includes the one corresponding
to the current browser, this means that the functionality in the controller
object is only for the current browser, and there is only one copy of the code being
loaded into the browser for performance.
*/
windmill.controller = new function () {
//Some namespacing for controller functionality
this.extensions = {};
this.commands = {};
this.asserts = {};
this.waits = {};
this._getDocumentStr = function () { return windmill.testWindowStr + '.document'; }
this._getWindowStr = function() { return windmill.testWindowStr; }
this._getDocument = function () { return windmill.testWindow.document; }
this._getWindow = function() { return windmill.testWindow; }
/************************************
/* User facing windmill functionality
/************************************/
/**
* Does absolutely nothing
*/
this.defer = function (){
//At some point we may want to display somewhere that we continually get deferred
//when the backend has nothing for us to do
};
/**
* Creates a windmill variable antry from a DOM element attribute
* @param {Object} paramObject The JavaScript object providing the necessary options
*/
this.storeVarFromLocAttrib = function (paramObject) {
var element = lookupNode(paramObject);
var arr = paramObject.options.split('|');
var varName = arr[0];
var attrib = arr[1];
var attribValue = element[attrib];
if (windmill.varRegistry.hasKey('{$'+varName+'}')){
windmill.varRegistry.removeItem('{$'+varName +'}');
windmill.varRegistry.addItem('{$'+varName +'}', attribValue);
}
else{
windmill.varRegistry.addItem('{$'+varName +'}', attribValue);
}
};
/**
* Creates a windmill variable antry from evaluated JavaScript
* @param {Object} paramObject The JavaScript providing the necessary options
* @throws SyntaxError JavaScript eval exception
*/
this.storeVarFromJS = function (paramObject) {
//extract the options
var arr = paramObject.options.split('|');
paramObject.name = arr[0];
paramObject.js = arr[1];
paramObject.value = eval.call(windmill.testWin(), paramObject.js);
//if the code evaled and returned a value add it
if (windmill.varRegistry.hasKey('{$'+paramObject.name +'}')){
windmill.varRegistry.removeItem('{$'+paramObject.name +'}');
windmill.varRegistry.addItem('{$'+paramObject.name +'}',paramObject.value);
}
else{
windmill.varRegistry.addItem('{$'+paramObject.name +'}',paramObject.value);
}
};
/**
* Navigates the Windmill testing applicatoin to the provided url
* @param {Object} paramObject The JavaScript object used to provide the necessary options
*/
this.open = function (paramObject) {
//clear the domain forwarding cache
if (paramObject.reset == undefined){
windmill.service.setTestURL(windmill.initialHost);
}
//We need to tell the service where we are before we
//head to a new page
windmill.testWin().location = paramObject.url;
};
/**
* Select an option from a Select element by either value or innerHTML
* @param {Object} paramObject The JavaScript providing: Locator, option or value
* @throws Exception Unable to select the specified option.
*/
this.select = function (paramObject) {
//lookup
var element = lookupNode(paramObject);
//if the index selector was used, select by index
if (paramObject.index){
element.options[paramObject.index].selected = true;
return true;
}
//Sometimes we can't directly access these at this point, not sure why
try {
if (element.options[element.options.selectedIndex].text == paramObject['option']){
return true;
}
} catch(err){ windmill.err(err)}
try {
if (element.options[element.options.selectedIndex].value == paramObject['val']){
return true;
}
} catch(err){ windmill.err(err)}
windmill.events.triggerEvent(element, 'focus', false);
var optionToSelect = null;
for (opt = 0; opt < element.options.length; opt++){
try {
var el = element.options[opt];
if (paramObject.option != undefined){
if(el.innerHTML.indexOf(paramObject.option) != -1){
if (el.selected && el.options[opt] == optionToSelect){
continue;
}
optionToSelect = el;
optionToSelect.selected = true;
windmill.events.triggerEvent(element, 'change', true);
break;
}
}
else {
if(el.value.indexOf(paramObject.val) != -1){
if (el.selected && el.options[opt] == optionToSelect){
continue;
}
optionToSelect = el;
optionToSelect.selected = true;
windmill.events.triggerEvent(element, 'change', true);
break;
}
}
}
catch(err){}
}
if (optionToSelect == null){
throw "Unable to select the specified option.";
}
};
/**
* Drag one DOM element to the top x,y coords of another specified DOM element
* @param {Object} paramObject The JavaScript object providing: Locator, option or value
*/
this.dragDropElemToElem = function(paramObject){
var p = paramObject;
//Get the drag and dest
var drag = lookupNode(p);
//create the params for the destination
var destParams = {};
for (attrib in p) {
if (attrib.indexOf('opt') != -1){
destParams[attrib.replace('opt', '')] = p[attrib];
break;
}
}
var dest = lookupNode(destParams);
windmill.pauseLoop();
windmill.controller.dragElem = drag;
windmill.controller.destElem = dest;
function getCoords(obj) {
var curleft = curtop = 0;
if (obj.offsetParent) {
do {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
}
return {left:curleft,top:curtop};
}
var dragCoords = null;
var destCoords = null;
//in IE and Mozilla we can use the getBoundingClientRect()
if ( windmill.browser.isIE || windmill.browser.isGecko) {
dragCoords = drag.getBoundingClientRect();
destCoords = dest.getBoundingClientRect();
}
else {
dragCoords = getCoords(drag);
destCoords = getCoords(dest);
}
//Do the initial move to the drag element position
windmill.events.triggerMouseEvent(windmill.testWin().document.body, 'mousemove', true, dragCoords.left, dragCoords.top);
windmill.events.triggerMouseEvent(drag, 'mousedown', true, dragCoords.left, dragCoords.top); //do the mousedown
//windmill.events.triggerMouseEvent(windmill.testWin().document.body, 'mousemove', true, destCoords.left, destCoords.top); //do the move
//windmill.events.triggerMouseEvent(dest, 'mouseup', true, destCoords.left, destCoords.top);
//IE doesn't appear to expect a click to complete the simulation
// if (!windmill.browser.isIE){
// windmill.events.triggerMouseEvent(dest, 'click', true, destCoords.left, destCoords.top);
// }
windmill.controller.doRem = function() {
windmill.continueLoop();
}
windmill.controller.doMove = function(attrib, startx, starty) {
windmill.events.triggerMouseEvent(windmill.testWin().document.body, 'mousemove', true, startx, starty);
windmill.controller.moveCount--;
if (windmill.controller.moveCount == 0){
windmill.events.triggerMouseEvent(windmill.controller.dragElem, 'mouseup', true, startx, starty);
if (!windmill.browser.isIE){
windmill.events.triggerMouseEvent(windmill.controller.dragElem, 'click', true, startx, starty);
}
setTimeout('windmill.controller.doRem()', 1000);
}
}
windmill.controller.moveCount = 0;
var startx = dragCoords.left;
var starty = dragCoords.top;
var endx = destCoords.left;
var endy = destCoords.top;
var delay = 0;
while (startx != endx){
if (startx < endx){ startx++; }
else{ startx--; }
setTimeout("windmill.controller.doMove('left',"+startx+","+starty+")", delay)
windmill.controller.moveCount++;
delay = delay + 5;
}
//move the y
//var delay = 0;
while (starty != endy){
if (starty < endy){ starty++; }
else{ starty--; }
setTimeout("windmill.controller.doMove('top',"+startx+","+starty+")", delay);
windmill.controller.moveCount++;
delay = delay + 5;
}
};
/**
* Drag a specified DOM element a specified amount of pixels
* @param {Object} paramObject The JavaScript object providing: Locator and pixels (x,y)
*/
this.dragDropElem = function(paramObject) {
var p = paramObject;
var el = lookupNode(p);
windmill.pauseLoop();
windmill.controller.moveCount = 0;
windmill.controller.dragElem = el;
//ie specific drag and drop simulation
if (windmill.browser.isIE){
var dist = p.pixels.split(',');
dist[0] = dist[0].replace('(','');
dist[1] = dist[1].replace(')','');
var box = el.getBoundingClientRect();
var left = box.left;
var top = box.top + 2;
windmill.events.triggerMouseEvent(windmill.testWin().document.body, 'mousemove', true, left, top);
windmill.events.triggerMouseEvent(el, 'mousedown', true, left, top);
// windmill.events.triggerMouseEvent(windmill.testWin().document.body, 'mousemove', true, left+100, top);
// windmill.events.triggerMouseEvent(el, 'mouseup', true, left, top);
windmill.controller.doRem = function(x,y) {
try{
windmill.events.triggerMouseEvent(windmill.controller.dragElem, 'mouseup', true, x, y);
}
catch(err){}
windmill.continueLoop();
}
windmill.controller.doMove = function(x,y) {
windmill.events.triggerMouseEvent(windmill.testWin().document.body, 'mousemove', true, x, y);
windmill.controller.moveCount--;
if (windmill.controller.moveCount == 0){
setTimeout('windmill.controller.doRem('+x+','+y+')', 1000);
}
}
var delay = 0;
var i = 0;
var newX = left;
while(i != dist[0]){
if (i < dist[0]){ newX++; }
else{ newX--; }
setTimeout("windmill.controller.doMove("+newX+","+top+")", delay)
if (i < dist[0]){ i++; }
else{ i--; }
windmill.controller.moveCount++;
delay = delay + 5;
}
//var delay = 0;
var i = 0;
var newBox = el.getBoundingClientRect();
var newY = top;
while(i != dist[1]){
if (i < dist[1]){ newY++; }
else{ newY--; }
setTimeout("windmill.controller.doMove("+newX+", "+newY+")", delay)
if (i < dist[1]){ i++; }
else{ i--; }
windmill.controller.moveCount++;
delay = delay + 5;
}
}
//all other browsers with sane event models
else {
// var i = windmill.testWindow.document.createElement('img');
// i.id = "mc";
// i.style.border = "0px";
// i.style.left = '0px';
// i.style.top = '0px';
// i.style.position = "absolute";
// i.zIndex = "100000000000";
// el.appendChild(i);
// i.src = "/windmill-serv/img/mousecursor.png";
//takes a coordinates param (x,y),(x,y) start, end
var dist = p.pixels.split(',');
dist[0] = dist[0].replace('(','');
dist[1] = dist[1].replace(')','');
windmill.events.triggerMouseEvent(windmill.testWin().document.body, 'mousemove', true, el.offsetLeft, el.offsetTop);
windmill.events.triggerMouseEvent(el, 'mousedown', true);
windmill.controller.doRem = function() {
windmill.events.triggerMouseEvent(windmill.controller.dragElem, 'mouseup', true);
windmill.events.triggerMouseEvent(windmill.controller.dragElem, 'click', true);
windmill.continueLoop();
}
windmill.controller.doMove = function(x,y) {
windmill.events.triggerMouseEvent(windmill.testWin().document.body, 'mousemove', true, x, y);
windmill.controller.moveCount--;
if (windmill.controller.moveCount == 0){
setTimeout('windmill.controller.doRem()', 1000);
}
}
var delay = 0;
var i = 0;
while(i != dist[0]) {
setTimeout("windmill.controller.doMove("+i+", 0)", delay)
if (i < dist[0]){ i++; }
else{ i--; }
windmill.controller.moveCount++;
delay = delay + 5;
}
var newX = i;
//var delay = 0;
var i = 0;
while(i != dist[1]) {
setTimeout("windmill.controller.doMove("+newX+", "+i+")", delay)
if (i < dist[1]){ i++; }
else{ i--; }
windmill.controller.moveCount++;
delay = delay + 5;
}
}
};
/**
* Use absolute coordinates to click an element, and move it from one set of coords to another.
* @param {Object} paramObject The JavaScript object providing: Locator, coords ( Format; ex. '(100,100),(300,350)' )
*/
this.dragDropAbs = function (paramObject) {
var p = paramObject;
var el = lookupNode(p);
windmill.pauseLoop();
windmill.controller.moveCount = 0;
windmill.controller.ddeParamObj = paramObject;
var webApp = windmill.testWin();
//takes a coordinates param (x,y),(x,y) start, end
var coords = p.coords.split('),(');
var start = coords[0].split(',');
start[0] = start[0].replace('(','');
var end = coords[1].split(',');
end[1] = end[1].replace(')','');
//get to the starting point
var i = windmill.testWin().document.createElement('img');
i.id = "mc";
i.style.border = "0px";
i.style.left = start[0]+'px';
i.style.top = start[1]+'px';
i.style.position = "absolute";
i.zIndex = "100000000000";
windmill.testWin().document.body.appendChild(i);
i.src = "/windmill-serv/img/mousecursor.png";
windmill.events.triggerMouseEvent(webApp.document.body, 'mousemove', true, start[0], start[1]);
windmill.events.triggerMouseEvent(lookupNode(p), 'mousedown', true, start[0], start[1]);
var startx = start[0];
var starty = start[1];
windmill.controller.remMouse = function(x,y) {
windmill.events.triggerMouseEvent(lookupNode(p), 'mouseup', true, x, y);
windmill.events.triggerMouseEvent(lookupNode(p), 'click', true);
var c = windmill.testWin().document.getElementById('mc');
windmill.testWin().document.body.removeChild(c);
windmill.continueLoop();
}
windmill.controller.doMove = function(attrib, startx, starty) {
var w = windmill.testWin().document;
if (attrib == "left"){ w.getElementById('mc').style['left'] = startx+'px'; }
else{ w.getElementById('mc').style['top'] = starty+'px'; }
windmill.events.triggerMouseEvent(w.body, 'mousemove', true, startx, starty);
windmill.controller.moveCount--;
if (windmill.controller.moveCount == 0){
w.getElementById('mc').src = "/windmill-serv/img/mousecursorred.png";
setTimeout('windmill.controller.remMouse('+startx+','+starty+')', 1500);
}
}
//move the x
var delay = 0;
while (startx != end[0]) {
if (startx < end[0]){ startx++; }
else{ startx--; }
setTimeout("windmill.controller.doMove('left',"+startx+","+starty+")", delay)
windmill.controller.moveCount++;
delay = delay + 5;
}
//move the y
//var delay = 0;
while (starty != end[1]){
if (starty < end[1]){ starty++; }
else{ starty--; }
setTimeout("windmill.controller.doMove('top',"+startx+","+starty+")", delay);
windmill.controller.moveCount++;
delay = delay + 5;
}
};
/**
* Use absolute coordinates to click an element, and move it from one set of coords to another.
* @param {Object} paramObject The JavaScript object providing: Locator, destination paramObject
*/
this.dragDrop = function (paramObject) {
var p = paramObject;
var hash_key;
eval ("hash_key=" + p.dragged.jsid + ";");
p.dragged.id = hash_key;
delete p.dragged.jsid;
function getPos(elem, evType) {
// paramObject.mouseDownPos or param_obj.mouseUpPos
var t = evType + 'Pos';
var res = [];
// Explicit function for getting XY of both
// start and end position for drag start
// to be calculated from the initial pos of the
// dragged, and end to be calculated from the
// position of the destination
if (p[t]) {
var f = eval(p[t]);
res = f(elem);
}
// Otherwise naively assume top/left XY for both
// start (dragged) and end (destination)
else {
res = [elem.offsetLeft, elem.offsetTop];
}
return res;
};
var dragged = lookupNode(p.dragged);
var dest = lookupNode(p.destination);
var mouseDownPos = getPos(dragged, 'mouseDown');
var mouseUpPos = getPos(dest, 'mouseUp');
var webApp = windmill.testWin();
windmill.events.triggerMouseEvent(webApp.document.body, 'mousemove', true, mouseDownPos[0], mouseDownPos[1]);
windmill.events.triggerMouseEvent(dragged, 'mousedown', true);
windmill.events.triggerMouseEvent(webApp.document.body, 'mousemove', true, mouseUpPos[0], mouseUpPos[1]);
windmill.events.triggerMouseEvent(dragged, 'mouseup', true);
windmill.events.triggerMouseEvent(dragged, 'click', true);
};
/**
* Raw drag drop using abs x,y
* @param {Object} paramObject The JavaScript object providing: Locator, source paramObject, dest paramObj
*/
this.dragDropXY = function (paramObject) {
var p = paramObject;
var webApp = windmill.testWin();
windmill.events.triggerMouseEvent(webApp.document.body, 'mousemove', true, p.source[0], p.source[1]);
windmill.events.triggerMouseEvent(webApp.document.body, 'mousedown', true);
windmill.events.triggerMouseEvent(webApp.document.body, 'mousemove', true, p.destination[0], p.destination[1]);
windmill.events.triggerMouseEvent(webApp.document.body, 'mouseup', true);
windmill.events.triggerMouseEvent(webApp.document.body, 'click', true);
};
/**
* Create a Windmill variable registry entry from the href of a provided locator
* @param {Object} paramObject The JavaScript object providing: Locator
*/
this.storeURL = function(paramObject) {
var linkNode = lookupNode(paramObject);
windmill.varRegistry.addItem('{$'+paramObject.link +'}',linkNode.href);
}
/**
* Manually change the document.domain of the windmill IDE window
* @param {Object} paramObject The JavaScript object providing: domain
*/
this.setDocDomain = function(paramObject) {
document.domain = paramObject.domain;
};
/**
* Fire a mousedown event on the provided node
* @param {Object} paramObject The JavaScript object providing: Locator
*/
this.mouseDown = function (paramObject) {
var mupElement = lookupNode(paramObject);
if (mupElement == null){
mupElement = windmill.testWin().document.body;
}
if (windmill.browser.isIE){
var box = mupElement.getBoundingClientRect();
var left = box.left;
var top = box.top + 2;
windmill.events.triggerMouseEvent(mupElement, 'mousedown', true, left, top);
}
else { windmill.events.triggerMouseEvent(mupElement, 'mousedown', true); }
};
/**
* Fire a mousemove event ending at a specified set of coordinates
* @param {Object} paramObject The JavaScript object providing: coords
*/
this.mouseMoveTo = function (paramObject) {
var p = paramObject;
var webApp = windmill.testWin();
var coords = p.coords.split(',');
coords[0] = coords[0].replace('(','');
coords[1] = coords[1].replace(')','');
windmill.events.triggerMouseEvent(webApp.document.body, 'mousemove', true, coords[0], coords[1]);
};
// this.mouseMove = function (paramObject){
// var p = paramObject;
// var webApp = windmill.testWin();
// var coords = p.coords.split('),(');
//
// var start = coords[0].split(',');
// start[0] = start[0].replace('(','');
//
// var end = coords[1].split(',');
// end[1] = end[1].replace(')','');
// windmill.events.triggerMouseEvent(webApp.document.body, 'mousemove', true, start[0], start[1]);
// windmill.events.triggerMouseEvent(webApp.document.body, 'mousemove', true, end[0], end[1]);
// alert('mooch??');
//
// return true;
// };
/**
* Fire the mousemove event starting at one point and ending at another
* @param {Object} paramObject The JavaScript object providing: coords (Format: '(x,y),(x,y)' )
*/
this.mouseMove = function (paramObject) {
windmill.pauseLoop();
windmill.controller.moveCount = 0;
var p = paramObject;
var webApp = windmill.testWin();
//takes a coordinates param (x,y),(x,y) start, end
var coords = p.coords.split('),(');
var start = coords[0].split(',');
start[0] = start[0].replace('(','');
var end = coords[1].split(',');
end[1] = end[1].replace(')','');
//get to the starting point
var i = windmill.testWin().document.createElement('img');
i.id = "mc";
i.style.border = "0px";
i.style.left = start[0]+'px';
i.style.top = start[1]+'px';
i.style.position = "absolute";
i.zIndex = "100000000000";
windmill.testWin().document.body.appendChild(i);
i.src = "/windmill-serv/img/mousecursor.png";
windmill.events.triggerMouseEvent(webApp.document.body, 'mousemove', true, start[0], start[1]);
var startx = start[0];
var starty = start[1];
windmill.controller.remMouse = function() {
var c = windmill.testWin().document.getElementById('mc');
windmill.testWin().document.body.removeChild(c);
windmill.continueLoop();
}
windmill.controller.doMove = function(attrib, startx, starty) {
var w = windmill.testWin().document;
if (attrib == "left"){ w.getElementById('mc').style['left'] = startx+'px'; }
else{ w.getElementById('mc').style['top'] = starty+'px'; }
windmill.events.triggerMouseEvent(w.body, 'mousemove', true, startx, starty);
windmill.controller.moveCount--;
if (windmill.controller.moveCount == 0){
w.getElementById('mc').src = "/windmill-serv/img/mousecursorred.png";
setTimeout('windmill.controller.remMouse()', 1000);
}
}
//move the x
var delay = 0;
while (startx != end[0]){
if (startx < end[0]){ startx++; }
else{ startx--; }
setTimeout("windmill.controller.doMove('left',"+startx+","+starty+")", delay)
windmill.controller.moveCount++;
delay = delay + 5;
}
//move the y
//var delay = 0;
while (starty != end[1]){
if (starty < end[1]){ starty++; }
else{ starty--; }
setTimeout("windmill.controller.doMove('top',"+startx+","+starty+")", delay);
windmill.controller.moveCount++;
delay = delay + 5;
}
};
/**
* Fire the mouseup event against a specified node, defaulting to document.body
* @param {Object} paramObject The JavaScript object providing: Locator
*/
this.mouseUp = function (paramObject){
try {
var mupElement = lookupNode(paramObject);
} catch(err){}
if (mupElement == null){
mupElement = windmill.testWin().document.body;
}
if(windmill.browser.isIE){
var box = mupElement.getBoundingClientRect();
var left = box.left;
var top = box.top + 2;
windmill.events.triggerMouseEvent(mupElement, 'mouseup', true, left, top);
}
else{
windmill.events.triggerMouseEvent(mupElement, 'mouseup', true);
}
};
/**
* Fire the mouseover event against a specified DOM element
* @param {Object} paramObject The JavaScript object providing: Locator
*/
this.mouseOver = function (paramObject){
var mdnElement = lookupNode(paramObject);
windmill.events.triggerMouseEvent(mdnElement, 'mouseover', true);
};
/**
* Fire the mouseout event against a specified DOM element
* @param {Object} paramObject The JavaScript object providing: Locator
*/
this.mouseOut = function (paramObject){
var mdnElement = lookupNode(paramObject);
windmill.events.triggerMouseEvent(mdnElement, 'mouseout', true);
};
/**
* Fire keypress event
* @param
*/
this.keyPress = function(paramObject){
try {
var element = lookupNode(paramObject);
} catch(err){ var element = windmill.testWin().document.body; }
paramObject.options = paramObject.options.replace(/ /g, "");
var opts = paramObject.options.split(",");
windmill.events.triggerEvent(element, 'focus', false);
//element, eventType, keySequence, canBubble, controlKeyDown, altKeyDown, shiftKeyDown, metaKeyDown
windmill.events.triggerKeyEvent(element, "keypress", opts[0], eval(opts[1]), eval(opts[2]), eval(opts[3]), eval(opts[4]), eval(opts[5]));
};
/**
* Fire keydown event
* @param
*/
this.keyDown = function(paramObject){
try {
var element = lookupNode(paramObject);
} catch(err){ var element = windmill.testWin().document.body; }
paramObject.options = paramObject.options.replace(/ /g, "");
var opts = paramObject.options.split(",");
windmill.events.triggerEvent(element, 'focus', false);
//element, eventType, keySequence, canBubble, controlKeyDown, altKeyDown, shiftKeyDown, metaKeyDown
windmill.events.triggerKeyEvent(element, "keyDown", opts[0], eval(opts[1]), eval(opts[2]), eval(opts[3]), eval(opts[4]), eval(opts[5]));
};
/**
* Fire keydown event
* @param
*/
this.keyUp = function(paramObject){
try {
var element = lookupNode(paramObject);
} catch(err){ var element = windmill.testWin().document.body; }
paramObject.options = paramObject.options.replace(/ /g, "");
var opts = paramObject.options.split(",");
windmill.events.triggerEvent(element, 'focus', false);
//element, eventType, keySequence, canBubble, controlKeyDown, altKeyDown, shiftKeyDown, metaKeyDown
windmill.events.triggerKeyEvent(element, "keyUp", opts[0], eval(opts[1]), eval(opts[2]), eval(opts[3]), eval(opts[4]), eval(opts[5]));
};
/**
* Trigger the back function in the Windmill Testing Application Window
*/
this.goBack = function(paramObject){
windmill.testWin().history.back();
}
/**
* Trigger the forward function in the Windmill Testing Application Window
*/
this.goForward = function(paramObject){
windmill.testWin().history.forward();
}
/**
* Trigger the refresh function in the Windmill Testing Application Window
*/
this.refresh = function(paramObject){
windmill.testWin().location.reload(true);
}
/**
* Trigger the scroll function in the Windmill Testing Application Window
* @param {Object} paramObject The JavaScript object providing: coords
*/
this.scroll = function(paramObject){
var d = paramObject.coords;
d = d.replace('(','');
d = d.replace(')','');
var cArr = d.split(',');
windmill.testWin().scrollTo(cArr[0],cArr[1]);
}
/**
* Re-write the window alert function to instead send it's output to the output tab
*/
this.reWriteAlert = function(paramObject){
try {
windmill.testWin().alert = function(s){
windmill.alertStore.push(s);
windmill.out("<br>Alert: <b><font color=\"#fff32c\">" + s + "</font>.</b>");
};
} catch(err){ windmill.err(err); }
rwaRecurse = function(frame){
var iframeCount = frame.frames.length;
var iframeArray = frame.frames;
for (var i=0;i<iframeCount;i++){
try{
iframeArray[i].alert = function(s){
windmill.alertStore.push(s);
windmill.out("<br>Alert: <b><font color=\"#fff32c\">" + s + "</font>.</b>");
};
rwaRecurse(iframeArray[i]);
}
catch(error){
windmill.err('Could not bind to iframe number '+ iframeCount +' '+error);
}
}
};
rwaRecurse(windmill.testWin());
};
/**
* Re-write the window alert function to instead send it's output to the output tab
*/
this.reWriteConfirm = function(paramObject){
try {
windmill.testWin().confirm = function(s){
windmill.confirmStore.push(s);
return windmill.confirmAnswer;
};
} catch(err){ windmill.err(err); }
rwcRecurse = function(frame){
var iframeCount = frame.frames.length;
var iframeArray = frame.frames;
for (var i=0;i<iframeCount;i++){
try{
iframeArray[i].confirm = function(s){
windmill.confirmStore.push(s);
return windmill.confirmAnswer;
};
rwaRecurse(iframeArray[i]);
}
catch(error){
windmill.err('Could not bind to iframe number '+ iframeCount +' '+error);
}
}
};
rwcRecurse(windmill.testWin());
};
this.reWritePopups = function(paramObject){
if (typeof windmill.testWin().oldOpen == "function"){
return;
}
//Window popup wrapper
try { windmill.testWin().oldOpen = windmill.testWin().open; }
catch(err){
windmill.err("Did you close a popup window, without using closeWindow?");
windmill.err("We can no longer access test windows, start over and don't close windows manually.");
return;
}
//re-define the open function
windmill.testWin().open = function(){
if (windmill.browser.isIE){
var str = '';
var arg;
for (var i = 0; i < arguments.length; i++) {
arg = arguments[i];
if (typeof arg == 'string') {
str += '"' + arg + '"';
}
else {
str += arg;
}
str += ","
}
str = str.substr(0, str.length-1);
eval('var newWindow = windmill.testWin().oldOpen(' + str + ');');
}
else {
var newWindow = windmill.testWin().oldOpen.apply(windmill.testWin(), arguments);
}
var newReg = [];
for (var i = 0; i < windmill.windowReg.length; i++){
try{
var wDoc = windmill.windowReg[i].document;
newReg.push(windmill.windowReg[i]);
} catch(err){}
windmill.windowReg = newReg;
}
windmill.windowReg.push(newWindow);
};
};
/**
* Update the windmill.testWindow reference to point to a different window
* @param {Object} paramObject The JavaScript object providing: path
* @throws EvalException "Error setting the test window, undefined."
*/
this.setTestWindow = function(paramObject){
var res = eval ('windmill.testWindow ='+ paramObject.path +';');
if (typeof(res) == 'undefined'){
throw "Error setting the test window, undefined."
}
};
/**
* Set the windmill.testWindow by iterating through the windowReg to find a matching title
* @param {Object} paramObject The JavaScript object providing: title
*/
this.setWindowByTitle = function(paramObject){
var title = paramObject.title;
var newW = windmill.testWin();
for (var i = 0; i < windmill.windowReg.length; i++){
if (windmill.windowReg[i].document.title == title){
newW = windmill.windowReg[i];
}
}
windmill.testWindow = newW;
};
/**
* Revert the windmill.testWindow to the original when the page was loaded
* @param {Object} paramObject The JavaScript object providing: title
*/
this.revertWindow = function(paramObject){
windmill.testWindow = windmill.baseTestWindow;
};
/**
* If the windmill.testWindow is not the original opener, close it.
*/
this.closeWindow = function(paramObject){
if (windmill.testWin() != windmill.baseTestWindow){
windmill.testWin().close();
windmill.testWindow = windmill.baseTestWindow;
}
};
/**
* Execute some arbitrary JS in the testing app window
* @param {Object} paramObject The JavaScript object providing: js
*/
this.execArbTestWinJS = function(paramObject){
var js = paramObject.js;
eval.call(windmill.testWin(), js);
};
/**
* Execute some arbitrary JS
* @param {Object} paramObject The JavaScript object providing: js
*/
this.execIDEJS = function(paramObject){
var js = paramObject.js;
eval.call(window, js);
};
};
|
Updating the dragDropElemToElem per Brandon's contribution, thanks! (tested in FF3,Saf3,IE7 and Opera)
git-svn-id: 87d19257dd11500985d055ec4730e446075a5f07@1108 78c7df6f-8922-0410-bcd3-9426b1ad491b
|
windmill/html/js/controller/controller.js
|
Updating the dragDropElemToElem per Brandon's contribution, thanks! (tested in FF3,Saf3,IE7 and Opera)
|
<ide><path>indmill/html/js/controller/controller.js
<ide> windmill.controller.dragElem = drag;
<ide> windmill.controller.destElem = dest;
<ide>
<del> function getCoords(obj) {
<del> var curleft = curtop = 0;
<del> if (obj.offsetParent) {
<del> do {
<del> curleft += obj.offsetLeft;
<del> curtop += obj.offsetTop;
<del> } while (obj = obj.offsetParent);
<del> }
<del> return {left:curleft,top:curtop};
<del> }
<add> //get the bounding objects we want for starting and ending places
<add> //for the drag
<add> function getBounding(elem){
<add> //backup way to get the coords
<add> function getCoords(obj) {
<add> var curleft = curtop = 0;
<add> if (obj.offsetParent) {
<add> do {
<add> curleft += obj.offsetLeft;
<add> curtop += obj.offsetTop;
<add> } while (obj = obj.offsetParent);
<add> }
<add> return {left:curleft,top:curtop};
<add> }
<add>
<add> //get the coords and divide to find the middle
<add> if ( windmill.browser.isIE || windmill.browser.isGecko ) {
<add> var bound = elem.getBoundingClientRect();
<add> bound = {left:parseInt((bound.left+bound.right)/
<add> 2),top:parseInt((bound.top+bound.bottom)/2)};
<add> }
<add> else {
<add> var bound = getCoords(elem);
<add> bound = {left:parseInt(bound.left+elem.offsetWidth/
<add> 2),top:parseInt(bound.top+elem.offsetHeight/2)}
<add> }
<add> return bound;
<add> };
<add>
<ide>
<ide> var dragCoords = null;
<ide> var destCoords = null;
<del>
<del> //in IE and Mozilla we can use the getBoundingClientRect()
<del> if ( windmill.browser.isIE || windmill.browser.isGecko) {
<del> dragCoords = drag.getBoundingClientRect();
<del> destCoords = dest.getBoundingClientRect();
<del> }
<del> else {
<del> dragCoords = getCoords(drag);
<del> destCoords = getCoords(dest);
<del> }
<add>
<add> dragCoords = getBounding(drag);
<add> destCoords = getBounding(dest);
<add>
<ide>
<ide> //Do the initial move to the drag element position
<ide> windmill.events.triggerMouseEvent(windmill.testWin().document.body, 'mousemove', true, dragCoords.left, dragCoords.top);
<del> windmill.events.triggerMouseEvent(drag, 'mousedown', true, dragCoords.left, dragCoords.top); //do the mousedown
<del> //windmill.events.triggerMouseEvent(windmill.testWin().document.body, 'mousemove', true, destCoords.left, destCoords.top); //do the move
<del> //windmill.events.triggerMouseEvent(dest, 'mouseup', true, destCoords.left, destCoords.top);
<del> //IE doesn't appear to expect a click to complete the simulation
<del> // if (!windmill.browser.isIE){
<del> // windmill.events.triggerMouseEvent(dest, 'click', true, destCoords.left, destCoords.top);
<del> // }
<add> windmill.events.triggerMouseEvent(drag, 'mousedown', true, dragCoords.left, dragCoords.top);
<ide>
<ide> windmill.controller.doRem = function() {
<ide> windmill.continueLoop();
<ide> }
<ide> windmill.controller.doMove = function(attrib, startx, starty) {
<ide> windmill.events.triggerMouseEvent(windmill.testWin().document.body, 'mousemove', true, startx, starty);
<del>
<add>
<ide> windmill.controller.moveCount--;
<ide> if (windmill.controller.moveCount == 0){
<ide> windmill.events.triggerMouseEvent(windmill.controller.dragElem, 'mouseup', true, startx, starty);
<ide> windmill.controller.moveCount++;
<ide> delay = delay + 5;
<ide> }
<del> //move the y
<del> //var delay = 0;
<add>
<add> //move the y
<ide> while (starty != endy){
<ide> if (starty < endy){ starty++; }
<ide> else{ starty--; }
|
|
Java
|
epl-1.0
|
error: pathspec 'applications/plugins/org.csstudio.utility.adlParser/src/org/csstudio/utility/adlparser/fileParser/widgetParts/ADLLimits.java' did not match any file(s) known to git
|
6628545bde184f9f14821e6d8a0c2fd8c56b6729
| 1 |
ESSICS/cs-studio,ESSICS/cs-studio,ControlSystemStudio/cs-studio,ESSICS/cs-studio,ControlSystemStudio/cs-studio,css-iter/cs-studio,ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,ControlSystemStudio/cs-studio,css-iter/cs-studio,ControlSystemStudio/cs-studio,css-iter/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,css-iter/cs-studio
|
package org.csstudio.utility.adlparser.fileParser.widgetParts;
import org.csstudio.utility.adlparser.fileParser.ADLResource;
import org.csstudio.utility.adlparser.fileParser.ADLWidget;
import org.csstudio.utility.adlparser.fileParser.FileLine;
import org.csstudio.utility.adlparser.fileParser.WrongADLFormatException;
import org.csstudio.utility.adlparser.internationalization.Messages;
public class ADLLimits extends WidgetPart {
/**Source of LOPR */
private String _loprSrc;
/**Default value for LOPR */
private float _loprDefault;
/**Source of HOPR */
private String _hoprSrc;
/**Default value for HOPR */
private float _hoprDefault;
/**Source of PREC */
private String _precSrc;
/**Default value for PREC */
private float _precDefault;
public ADLLimits(ADLWidget widgetPart) throws WrongADLFormatException {
super(widgetPart);
// TODO Auto-generated constructor stub
}
@Override
public Object[] getChildren() {
Object[] ret = new Object[6];
ret[0] = new ADLResource(ADLResource.LOPR_SRC, new String(_loprSrc));
ret[1] = new ADLResource(ADLResource.LOPR_DEFAULT, new Float(_loprDefault));
ret[2] = new ADLResource(ADLResource.HOPR_SRC, new String(_hoprSrc));
ret[3] = new ADLResource(ADLResource.HOPR_DEFAULT, new Float(_hoprDefault));
ret[4] = new ADLResource(ADLResource.PREC_SRC, new String(_precSrc));
ret[5] = new ADLResource(ADLResource.PREC_DEFAULT, new Float(_precDefault));
return ret;
}
@Override
void init() {
_loprSrc = new String("Channel");
_hoprSrc = new String("Channel");
_precSrc = new String("Channel");
}
@Override
void parseWidgetPart(ADLWidget adlObject) throws WrongADLFormatException {
assert adlObject.isType("object") : Messages.ADLObject_AssertError_Begin+adlObject.getType()+Messages.ADLObject_AssertError_End+"\r\n"+adlObject; //$NON-NLS-1$
for (FileLine fileLine : adlObject.getBody()) {
String parameter = fileLine.getLine();
if(parameter.trim().startsWith("//")){ //$NON-NLS-1$
continue;
}
String[] row = parameter.split("=");
if (row.length !=2){
throw new WrongADLFormatException(Messages.ADLObject_WrongADLFormatException_Begin+parameter+Messages.ADLObject_WrongADLFormatException_End);
}
row[1] = row[1].replaceAll("\"", "").trim();
System.out.println(row[0] + ", " + row[1]);
if (row[0].trim().toLowerCase().equals("loprsrc")){
if (row[1].startsWith("$")){
//TODO ADLLimits Figure out what to do with macro in loprSrc
_loprSrc = "Channel";
}
else {
_loprSrc = row[1].toString();
}
}
if (row[0].trim().toLowerCase().equals("loprdefault")){
if (row[1].startsWith("$")){
//TODO ADLLimits Figure out what to do with macro in loprSrc
_loprDefault = 0;
}
else {
_loprDefault = Float.parseFloat(row[1]);
}
}
if (row[0].trim().toLowerCase().equals("hoprsrc")){
if (row[1].startsWith("$")){
//TODO ADLLimits Figure out what to do with macro in hoprSrc
_hoprSrc = "Channel";
}
else {
_hoprSrc = row[1].toString();
}
}
if (row[0].trim().toLowerCase().equals("hoprdefault")){
if (row[1].startsWith("$")){
//TODO ADLLimits Figure out what to do with macro in hoprSrc
_hoprDefault = 0;
}
else {
_hoprDefault = Float.parseFloat(row[1]);
}
}
if (row[0].trim().toLowerCase().equals("precsrc")){
if (row[1].startsWith("$")){
//TODO ADLLimits Figure out what to do with macro in precSrc
_precSrc = "Channel";
}
else {
_precSrc = row[1].toString();
}
}
if (row[0].trim().toLowerCase().equals("precdefault")){
if (row[1].startsWith("$")){
//TODO Figure out what to do with macro in precDefault
_precDefault = 0;
}
else {
_precDefault = Float.parseFloat(row[1]);
}
}
}
}
}
|
applications/plugins/org.csstudio.utility.adlParser/src/org/csstudio/utility/adlparser/fileParser/widgetParts/ADLLimits.java
|
Add to handle limits
|
applications/plugins/org.csstudio.utility.adlParser/src/org/csstudio/utility/adlparser/fileParser/widgetParts/ADLLimits.java
|
Add to handle limits
|
<ide><path>pplications/plugins/org.csstudio.utility.adlParser/src/org/csstudio/utility/adlparser/fileParser/widgetParts/ADLLimits.java
<add>package org.csstudio.utility.adlparser.fileParser.widgetParts;
<add>
<add>import org.csstudio.utility.adlparser.fileParser.ADLResource;
<add>import org.csstudio.utility.adlparser.fileParser.ADLWidget;
<add>import org.csstudio.utility.adlparser.fileParser.FileLine;
<add>import org.csstudio.utility.adlparser.fileParser.WrongADLFormatException;
<add>import org.csstudio.utility.adlparser.internationalization.Messages;
<add>
<add>public class ADLLimits extends WidgetPart {
<add> /**Source of LOPR */
<add> private String _loprSrc;
<add> /**Default value for LOPR */
<add> private float _loprDefault;
<add> /**Source of HOPR */
<add> private String _hoprSrc;
<add> /**Default value for HOPR */
<add> private float _hoprDefault;
<add> /**Source of PREC */
<add> private String _precSrc;
<add> /**Default value for PREC */
<add> private float _precDefault;
<add>
<add> public ADLLimits(ADLWidget widgetPart) throws WrongADLFormatException {
<add> super(widgetPart);
<add> // TODO Auto-generated constructor stub
<add> }
<add>
<add> @Override
<add> public Object[] getChildren() {
<add> Object[] ret = new Object[6];
<add> ret[0] = new ADLResource(ADLResource.LOPR_SRC, new String(_loprSrc));
<add> ret[1] = new ADLResource(ADLResource.LOPR_DEFAULT, new Float(_loprDefault));
<add> ret[2] = new ADLResource(ADLResource.HOPR_SRC, new String(_hoprSrc));
<add> ret[3] = new ADLResource(ADLResource.HOPR_DEFAULT, new Float(_hoprDefault));
<add> ret[4] = new ADLResource(ADLResource.PREC_SRC, new String(_precSrc));
<add> ret[5] = new ADLResource(ADLResource.PREC_DEFAULT, new Float(_precDefault));
<add>
<add> return ret;
<add> }
<add>
<add> @Override
<add> void init() {
<add> _loprSrc = new String("Channel");
<add> _hoprSrc = new String("Channel");
<add> _precSrc = new String("Channel");
<add> }
<add>
<add> @Override
<add> void parseWidgetPart(ADLWidget adlObject) throws WrongADLFormatException {
<add> assert adlObject.isType("object") : Messages.ADLObject_AssertError_Begin+adlObject.getType()+Messages.ADLObject_AssertError_End+"\r\n"+adlObject; //$NON-NLS-1$
<add> for (FileLine fileLine : adlObject.getBody()) {
<add> String parameter = fileLine.getLine();
<add> if(parameter.trim().startsWith("//")){ //$NON-NLS-1$
<add> continue;
<add> }
<add> String[] row = parameter.split("=");
<add> if (row.length !=2){
<add> throw new WrongADLFormatException(Messages.ADLObject_WrongADLFormatException_Begin+parameter+Messages.ADLObject_WrongADLFormatException_End);
<add> }
<add> row[1] = row[1].replaceAll("\"", "").trim();
<add> System.out.println(row[0] + ", " + row[1]);
<add> if (row[0].trim().toLowerCase().equals("loprsrc")){
<add> if (row[1].startsWith("$")){
<add> //TODO ADLLimits Figure out what to do with macro in loprSrc
<add> _loprSrc = "Channel";
<add> }
<add> else {
<add> _loprSrc = row[1].toString();
<add> }
<add> }
<add> if (row[0].trim().toLowerCase().equals("loprdefault")){
<add> if (row[1].startsWith("$")){
<add> //TODO ADLLimits Figure out what to do with macro in loprSrc
<add> _loprDefault = 0;
<add> }
<add> else {
<add> _loprDefault = Float.parseFloat(row[1]);
<add> }
<add> }
<add> if (row[0].trim().toLowerCase().equals("hoprsrc")){
<add> if (row[1].startsWith("$")){
<add> //TODO ADLLimits Figure out what to do with macro in hoprSrc
<add> _hoprSrc = "Channel";
<add> }
<add> else {
<add> _hoprSrc = row[1].toString();
<add> }
<add> }
<add> if (row[0].trim().toLowerCase().equals("hoprdefault")){
<add> if (row[1].startsWith("$")){
<add> //TODO ADLLimits Figure out what to do with macro in hoprSrc
<add> _hoprDefault = 0;
<add> }
<add> else {
<add> _hoprDefault = Float.parseFloat(row[1]);
<add> }
<add> }
<add> if (row[0].trim().toLowerCase().equals("precsrc")){
<add> if (row[1].startsWith("$")){
<add> //TODO ADLLimits Figure out what to do with macro in precSrc
<add> _precSrc = "Channel";
<add> }
<add> else {
<add> _precSrc = row[1].toString();
<add> }
<add> }
<add> if (row[0].trim().toLowerCase().equals("precdefault")){
<add> if (row[1].startsWith("$")){
<add> //TODO Figure out what to do with macro in precDefault
<add> _precDefault = 0;
<add> }
<add> else {
<add> _precDefault = Float.parseFloat(row[1]);
<add> }
<add> }
<add> }
<add> }
<add>
<add>}
|
|
JavaScript
|
bsd-3-clause
|
3b37e52319c825680166c04a565adddf03fcf42a
| 0 |
dgw/textual-theme-Equinox,dgw/textual-theme-Equinox
|
/* jslint browser: true */
/* global app, Textual */
/* Defined in: "Textual.app -> Contents -> Resources -> JavaScript -> API -> core.js" */
/* Theme-wide preferences, as per milky's request */
var Equinox = {
fadeNicks: true, // fade out nicknames when they appear multiple times in a row
fadeNicksFreq: 10, // how frequently to display a nick if they have fadeNickCounts lines in a row
showDateChanges: true, // show date changes
squashModes: true, // if a duplicate mode gets posted to the channel, squash it
squashTopics: true // if a duplicate topic gets posted to the channel, squash it
};
/* Set the default statuses for everything tracked in the roomState */
var mappedSelectedUsers = [];
var rs = { // room state
date: {
year: 0,
month: 0,
day: 0
},
mode: {
mode: undefined
},
nick: {
count: 1,
delete: false,
id: undefined,
nick: undefined
},
topic: {
delete: false,
topic: undefined
}
};
var NickColorGenerator = (function () {
'use strict';
function NickColorGenerator(message) {
var i, inlineNicks, nick;
// Start alternative nick colouring procedure
var selectNick = message.querySelector('.sender');
selectNick.removeAttribute('colornumber');
inlineNicks = message.querySelectorAll('.inline_nickname');
this.generateColorFromNickname(selectNick.getAttribute('nickname'),
function(nickcolor) {
selectNick.style.color = nickcolor;
if (message.getAttribute('ltype') === 'action') {
message.querySelector('.message').style.color = nickcolor;
}
}
);
var self = this;
for (i = 0; i < inlineNicks.length; i++) {
inlineNicks[i].removeAttribute('colornumber');
nick = inlineNicks[i].textContent;
if (inlineNicks[i].getAttribute('mode').length > 0) {
nick = nick.replace(inlineNicks[i].getAttribute('mode'), '');
}
var inlineNick = inlineNicks[i];
(function(inlineNickname) {
self.generateColorFromNickname(nick,
function(nickcolor) {
inlineNickname.style.color = nickcolor;
}
);
})(inlineNick);
}
}
NickColorGenerator.prototype.generateColorFromNickname = function (nick, callbackFunction) {
// First, sanitize the nicknames
nick = nick.toLowerCase(); // make them lowercase (so that April and april produce the same color)
nick = nick.replace(/[`_-]+$/, ''); // typically `, _, and - are used on the end of a nick
nick = nick.replace(/|.*$/, ''); // remove |<anything> from the end
// Generate the hashes
app.nicknameColorStyleHash(nick, 'HSL-dark',
function(hhash) {
var shash = hhash >>> 1;
var lhash = hhash >>> 2;
var h = hhash % 360;
var s = shash % 50 + 45; // 50 - 95
var l = lhash % 36 + 45; // 45 - 81
// give the pinks a wee bit more lightness
if (h >= 280 && h < 335) {
l = lhash % 36 + 50; // 50 - 86
}
// Give the blues a smaller (but lighter) range
if (h >= 210 && h < 280) {
l = lhash % 25 + 65; // 65 - 90
}
// Give the reds a bit less saturation
if (h <= 25 || h >= 335) {
s = shash % 33 + 45; // 45 - 78
}
// Give the yellows and greens a bit less saturation as well
if (h >= 50 && h <= 150) {
s = shash % 50 + 40; // 40 - 90
}
var nickcolor = 'hsl(' + String(h) + ',' + String(s) + '%,' + String(l) + '%)';
callbackFunction(nickcolor);
}
);
};
return NickColorGenerator;
})();
function isMessageInViewport(elem) {
'use strict';
if (!elem.getBoundingClientRect) {
return true;
}
console.log(Math.floor(elem.getBoundingClientRect().bottom), Math.floor(document.documentElement.clientHeight));
// Have to use Math.floor() because sometimes the getBoundingClientRect().bottom is a fraction of a pixel (!!!)
return (Math.floor(elem.getBoundingClientRect().bottom - 1) <= Math.floor(document.documentElement.clientHeight));
}
function toggleSelectionStatusForNicknameInsideElement(e) {
'use strict';
/* e is nested as the .sender so we have to go three parents
up in order to reach the parent div that owns it. */
var parentSelector = e.parentNode.parentNode.parentNode.parentNode;
parentSelector.classList.toggle('selectedUser');
}
function updateNicknameAssociatedWithNewMessage(e) {
'use strict';
/* We only want to target plain text messages. */
var acceptedElementTypes = ['privmsg', 'action', 'notice'], elementType = e.getAttribute('ltype'), nickname, senderSelector;
if (acceptedElementTypes.indexOf(elementType) !== -1) {
/* Get the nickname information. */
senderSelector = e.querySelector('.sender');
if (senderSelector) {
/* Is this a mapped user? */
nickname = senderSelector.getAttribute('nickname');
/* If mapped, toggle status on for new message. */
if (mappedSelectedUsers.indexOf(nickname) > -1) {
toggleSelectionStatusForNicknameInsideElement(senderSelector);
}
}
}
}
/* Insert a date, if the date has changed from the previous message */
function dateChange(e) {
'use strict';
var timestamp, datetime, year, month, day, id, ltype;
var MAXTIMEOFFSET = 30000; // 30 seconds
// Only show date changes if the option is enabled
if (!Equinox.showDateChanges) {
return;
}
timestamp = parseFloat(e.getAttribute('timestamp')) * 1000;
datetime = new Date(timestamp);
year = datetime.getFullYear();
month = datetime.getMonth();
day = datetime.getDate();
id = 'date-' + String(year) + '-' + String(month + 1) + '-' + String(day);
// Occasionally when replaying, Textual will post messages in the future, and then jump backwards
// As such, we'll ignore all joins, modes, and topics, if they're more than MAXTIMEOFFSET milliseconds
// from the current time
ltype = e.getAttribute('ltype');
if (ltype !== 'privmsg') {
if (Date.now() - timestamp > MAXTIMEOFFSET) {
return;
}
}
// If the date is the same, then there's nothing to do here
if (year === rs.date.year && month === rs.date.month && day === rs.date.day) {
return;
}
var deleteLastlineDate = function (ll) {
if (ll) {
if ((ll.id === 'mark') || (ll.className === 'date')) {
ll.parentNode.removeChild(ll);
}
}
};
// First, let's get the last line posted
var lastline = e.previousSibling;
if (lastline) {
// And if it's a mark or a previous date entry, let's remove it, we can use css + selectors for marks that follow
deleteLastlineDate(lastline);
// If the last line is the historic_messages div and its last child or previous sibling is a date, remove that too
if (lastline.id === 'historic_messages') {
deleteLastlineDate(lastline.lastChild);
deleteLastlineDate(lastline.previousSibling);
}
}
// Create the date element: <div class="date"><hr /><span>...</span><hr /></div>
var div = document.createElement('div');
var span = document.createElement('span');
div.className = 'date';
div.id = id;
div.appendChild(document.createElement('hr'));
div.appendChild(span);
div.appendChild(document.createElement('hr'));
// Set the span's content to the current date (Friday, October 14th)
span.textContent = datetime.toLocaleDateString();
// Insert the date before the newly posted message
e.parentElement.insertBefore(div, e);
// Update the previous state
rs.date = {
year: year,
month: month,
day: day
};
// Reset the nick count back to 1, so the nick always shows up after a date change
rs.nick.count = 1;
rs.nick.nick = undefined;
}
/* When you join a channel, delete all the old disconnected messages */
Textual.handleEvent = function (event) {
'use strict';
var i, messages;
if (event === 'channelJoined') {
messages = document.querySelectorAll('div[command="-100"]');
for (i = 0; i < messages.length; i++) {
if (messages[i].getElementsByClassName('message')[0].textContent.search('Disconnect') !== -1) {
messages[i].parentNode.removeChild(messages[i]);
}
}
}
};
Textual.newMessagePostedToView = function (line) {
'use strict';
var message = document.getElementById('line-' + line);
var clone, elem, getEmbeddedImages, i, mode, messageText, sender, topic;
// reset the message count and previous nick, when you rejoin a channel
if (message.getAttribute('ltype') !== 'privmsg') {
rs.nick.count = 1;
rs.nick.nick = undefined;
}
// if it's a private message, colorize the nick and then track the state and fade away the nicks if needed
if (message.getAttribute('ltype') === 'privmsg' || message.getAttribute('ltype') === 'action') {
sender = message.getElementsByClassName('sender')[0];
if (sender.getAttribute('coloroverride') !== 'true') {
new NickColorGenerator(message); // colorized the nick
}
// Delete (ie, make foreground and background color identical) the previous line's nick, if it was set to be deleted
if (rs.nick.delete === true) {
elem = document.getElementById(rs.nick.id).getElementsByClassName('sender')[0];
elem.className += ' f';
}
// Track the nicks that submit messages, so that we can space out everything
if ((rs.nick.nick === sender.textContent) && (rs.nick.count < Equinox.fadeNicksFreq)
&& (message.getAttribute('ltype') !== 'action') && (Equinox.fadeNicks === true)) {
rs.nick.delete = true;
rs.nick.count += 1;
} else {
rs.nick.nick = sender.textContent;
rs.nick.count = 1;
rs.nick.delete = false;
}
// Track the previous message's id
rs.nick.id = message.getAttribute('id');
// Copy the message into the hidden history
clone = message.cloneNode(true);
clone.removeAttribute('id');
rs.history.appendChild(clone);
// Colorize it as well
if (sender.getAttribute('coloroverride') !== 'true') {
new NickColorGenerator(clone); // colorized the nick
}
// Remove old messages, if the history is longer than three messages
if (rs.history.childElementCount > 2) {
rs.history.removeChild(rs.history.childNodes[0]);
// Hide the first nick in the hidden history, if it's the same as the second
if ((rs.nick.count > 1) && (message.getAttribute('ltype') !== 'action')) {
rs.history.getElementsByClassName('sender')[0].style.visibility = 'hidden';
}
}
}
/* Let's kill topics that appear where they had already been set before
This happens when you join a room (like a reconnect) that you had been in and seen the topic before */
if (Equinox.squashTopics === true && message.getAttribute('ltype') === 'topic') {
topic = message.getElementsByClassName('message')[0].textContent.replace('Topic is ', '').replace(/\s+/, '');
if (message.getAttribute('command') === '332') { // an actual topic change
// hide the topic if it's the same topic again
if (topic === rs.topic.topic) {
message.parentNode.removeChild(message);
rs.topic.delete = true;
}
rs.topic.topic = topic;
}
if ((message.getAttribute('command') === '333') && (rs.topic.delete === true)) {
message.parentNode.removeChild(message);
rs.topic.delete = false;
}
}
// much like we suppress duplicate topics, we want to suppress duplicate modes
if (Equinox.squashModes === true && message.getAttribute('ltype') === 'mode') {
mode = message.getElementsByClassName('message')[0].textContent.replace(/\s+/, '');
if (mode === rs.mode.mode) {
message.parentNode.removeChild(message);
} else {
rs.mode.mode = mode;
}
}
// hide messages about yourself joining
if ((message.getAttribute('ltype') === 'join') || (message.getAttribute('ltype') === 'part')) {
app.localUserNickname(
function(returnValue) {
if (returnValue == message.getElementsByClassName('message')[0].getElementsByTagName('b')[0].textContent) {
message.parentNode.removeChild(message);
}
}
);
}
/* clear out all the old disconnect messages, if you're currently connected to the channel
note that normally Textual.handleEvent will catch this, but if you reload a theme, they will reappear */
if ((message.getAttribute('ltype') === 'debug') && (message.getAttribute('command') === '-100')) {
app.channelIsJoined(
function(returnValue) {
if (returnValue && message.getElementsByClassName('message')[0].textContent.search('Disconnect') !== -1) {
message.parentNode.removeChild(message);
}
}
);
} else {
// call the dateChange() function, for any message with a timestamp that's not a debug message
if (message.getAttribute('timestamp')) {
dateChange(message);
}
}
if (message.getAttribute('encrypted') === 'true') {
messageText = message.querySelector('.innerMessage');
if (messageText.innerText.indexOf('+OK') !== -1) {
message.setAttribute('encrypted', 'failed');
}
}
getEmbeddedImages = message.querySelectorAll('img');
if (getEmbeddedImages) {
for (i = 0; i < getEmbeddedImages.length; i++) {
getEmbeddedImages[i].onload = function (e) {
setTimeout(function () {
if (e.target.offsetHeight > (window.innerHeight - 150)) {
e.target.style.height = (window.innerHeight - 150);
}
}, 1000);
};
}
}
updateNicknameAssociatedWithNewMessage(message);
};
/* This is called when a .sender is clicked */
Textual.nicknameSingleClicked = function (e) {
'use strict';
var allLines, documentBody, i, sender;
var nickname = e.getAttribute('nickname');
var mappedIndex = mappedSelectedUsers.indexOf(nickname);
if (mappedIndex === -1) {
mappedSelectedUsers.push(nickname);
} else {
mappedSelectedUsers.splice(mappedIndex, 1);
}
/* Gather basic information. */
documentBody = document.getElementById('body_home');
allLines = documentBody.querySelectorAll('div[ltype="privmsg"], div[ltype="action"]');
/* Update all elements of the DOM matching conditions. */
for (i = 0; i < allLines.length; i++) {
sender = allLines[i].querySelectorAll('.sender');
if (sender.length > 0) {
if (sender[0].getAttribute('nickname') === nickname) {
/* e is nested as the .sender so we have to go three parents
up in order to reach the parent div that owns it. */
toggleSelectionStatusForNicknameInsideElement(sender[0]);
}
}
}
};
Textual.viewBodyDidLoad = function () {
'use strict';
Textual.fadeOutLoadingScreen(1.00, 0.95);
setTimeout(function () {
Textual.scrollToBottomOfView();
}, 500);
/* Disable date changes on OS X Mountain Lion because WebKit does not have some of
the features that this feature depends on (e.g. -webkit-flex) */
if (document.documentElement.getAttribute("systemversion").indexOf("10.8.") === 0) {
Equinox.showDateChanges = false;
}
};
Textual.viewInitiated = function () {
'use strict';
/* When the view is loaded, create a hidden history div which we display if there is scrollback */
var body = document.getElementById('body_home'), div = document.createElement('div');
div.id = 'scrolling_history';
document.getElementsByTagName('body')[0].appendChild(div);
rs.history = div;
/* setup the scrolling event to display the hidden history if the bottom element isn't in the viewport
also hide the topic bar when scrolling */
window.addEventListener('scroll', function () {
var line, lines;
var topic = document.getElementById('topic_bar');
lines = body.getElementsByClassName('line');
if (lines.length < 2) {
return;
}
line = lines[lines.length - 1];
if (isMessageInViewport(line) === false) {
// scrollback
rs.history.style.display = 'inline';
if (topic) { topic.style.visibility = 'hidden'; }
} else {
// at the bottom
rs.history.style.display = 'none';
if (topic) { topic.style.visibility = 'visible'; }
}
});
};
|
scripts.js
|
/* jslint browser: true */
/* global app, Textual */
/* Defined in: "Textual.app -> Contents -> Resources -> JavaScript -> API -> core.js" */
/* Theme-wide preferences, as per milky's request */
var Equinox = {
fadeNicks: true, // fade out nicknames when they appear multiple times in a row
fadeNicksFreq: 10, // how frequently to display a nick if they have fadeNickCounts lines in a row
showDateChanges: true, // show date changes
squashModes: true, // if a duplicate mode gets posted to the channel, squash it
squashTopics: true // if a duplicate topic gets posted to the channel, squash it
};
/* Set the default statuses for everything tracked in the roomState */
var mappedSelectedUsers = [];
var rs = { // room state
date: {
year: 0,
month: 0,
day: 0
},
mode: {
mode: undefined
},
nick: {
count: 1,
delete: false,
id: undefined,
nick: undefined
},
topic: {
delete: false,
topic: undefined
}
};
var NickColorGenerator = (function () {
'use strict';
function NickColorGenerator(message) {
var i, inlineNicks, nick;
// Start alternative nick colouring procedure
var selectNick = message.querySelector('.sender');
selectNick.removeAttribute('colornumber');
inlineNicks = message.querySelectorAll('.inline_nickname');
this.generateColorFromNickname(selectNick.getAttribute('nickname'),
function(nickcolor) {
selectNick.style.color = nickcolor;
if (message.getAttribute('ltype') === 'action') {
message.querySelector('.message').style.color = nickcolor;
}
}
);
var self = this;
for (i = 0; i < inlineNicks.length; i++) {
inlineNicks[i].removeAttribute('colornumber');
nick = inlineNicks[i].textContent;
if (inlineNicks[i].getAttribute('mode').length > 0) {
nick = nick.replace(inlineNicks[i].getAttribute('mode'), '');
}
var inlineNick = inlineNicks[i];
(function(inlineNickname) {
self.generateColorFromNickname(nick,
function(nickcolor) {
inlineNickname.style.color = nickcolor;
}
);
})(inlineNick);
}
}
NickColorGenerator.prototype.generateColorFromNickname = function (nick, callbackFunction) {
// First, sanitize the nicknames
nick = nick.toLowerCase(); // make them lowercase (so that April and april produce the same color)
nick = nick.replace(/[`_-]+$/, ''); // typically `, _, and - are used on the end of a nick
nick = nick.replace(/|.*$/, ''); // remove |<anything> from the end
// Generate the hashes
app.nicknameColorStyleHash(nick, 'HSL-dark',
function(hhash) {
var shash = hhash >>> 1;
var lhash = hhash >>> 2;
var h = hhash % 360;
var s = shash % 50 + 45; // 50 - 95
var l = lhash % 36 + 45; // 45 - 81
// give the pinks a wee bit more lightness
if (h >= 280 && h < 335) {
l = lhash % 36 + 50; // 50 - 86
}
// Give the blues a smaller (but lighter) range
if (h >= 210 && h < 280) {
l = lhash % 25 + 65; // 65 - 90
}
// Give the reds a bit less saturation
if (h <= 25 || h >= 335) {
s = shash % 33 + 45; // 45 - 78
}
// Give the yellows and greens a bit less saturation as well
if (h >= 50 && h <= 150) {
s = shash % 50 + 40; // 40 - 90
}
var nickcolor = 'hsl(' + String(h) + ',' + String(s) + '%,' + String(l) + '%)';
callbackFunction(nickcolor);
}
);
};
return NickColorGenerator;
})();
function isMessageInViewport(elem) {
'use strict';
if (!elem.getBoundingClientRect) {
return true;
}
// Have to use Math.floor() because sometimes the getBoundingClientRect().bottom is a fraction of a pixel (!!!)
return (Math.floor(elem.getBoundingClientRect().bottom) <= Math.floor(document.documentElement.clientHeight));
}
function toggleSelectionStatusForNicknameInsideElement(e) {
'use strict';
/* e is nested as the .sender so we have to go three parents
up in order to reach the parent div that owns it. */
var parentSelector = e.parentNode.parentNode.parentNode.parentNode;
parentSelector.classList.toggle('selectedUser');
}
function updateNicknameAssociatedWithNewMessage(e) {
'use strict';
/* We only want to target plain text messages. */
var acceptedElementTypes = ['privmsg', 'action', 'notice'], elementType = e.getAttribute('ltype'), nickname, senderSelector;
if (acceptedElementTypes.indexOf(elementType) !== -1) {
/* Get the nickname information. */
senderSelector = e.querySelector('.sender');
if (senderSelector) {
/* Is this a mapped user? */
nickname = senderSelector.getAttribute('nickname');
/* If mapped, toggle status on for new message. */
if (mappedSelectedUsers.indexOf(nickname) > -1) {
toggleSelectionStatusForNicknameInsideElement(senderSelector);
}
}
}
}
/* Insert a date, if the date has changed from the previous message */
function dateChange(e) {
'use strict';
var timestamp, datetime, year, month, day, id, ltype;
var MAXTIMEOFFSET = 30000; // 30 seconds
// Only show date changes if the option is enabled
if (!Equinox.showDateChanges) {
return;
}
timestamp = parseFloat(e.getAttribute('timestamp')) * 1000;
datetime = new Date(timestamp);
year = datetime.getFullYear();
month = datetime.getMonth();
day = datetime.getDate();
id = 'date-' + String(year) + '-' + String(month + 1) + '-' + String(day);
// Occasionally when replaying, Textual will post messages in the future, and then jump backwards
// As such, we'll ignore all joins, modes, and topics, if they're more than MAXTIMEOFFSET milliseconds
// from the current time
ltype = e.getAttribute('ltype');
if (ltype !== 'privmsg') {
if (Date.now() - timestamp > MAXTIMEOFFSET) {
return;
}
}
// If the date is the same, then there's nothing to do here
if (year === rs.date.year && month === rs.date.month && day === rs.date.day) {
return;
}
var deleteLastlineDate = function (ll) {
if (ll) {
if ((ll.id === 'mark') || (ll.className === 'date')) {
ll.parentNode.removeChild(ll);
}
}
};
// First, let's get the last line posted
var lastline = e.previousSibling;
if (lastline) {
// And if it's a mark or a previous date entry, let's remove it, we can use css + selectors for marks that follow
deleteLastlineDate(lastline);
// If the last line is the historic_messages div and its last child or previous sibling is a date, remove that too
if (lastline.id === 'historic_messages') {
deleteLastlineDate(lastline.lastChild);
deleteLastlineDate(lastline.previousSibling);
}
}
// Create the date element: <div class="date"><hr /><span>...</span><hr /></div>
var div = document.createElement('div');
var span = document.createElement('span');
div.className = 'date';
div.id = id;
div.appendChild(document.createElement('hr'));
div.appendChild(span);
div.appendChild(document.createElement('hr'));
// Set the span's content to the current date (Friday, October 14th)
span.textContent = datetime.toLocaleDateString();
// Insert the date before the newly posted message
e.parentElement.insertBefore(div, e);
// Update the previous state
rs.date = {
year: year,
month: month,
day: day
};
// Reset the nick count back to 1, so the nick always shows up after a date change
rs.nick.count = 1;
rs.nick.nick = undefined;
}
/* When you join a channel, delete all the old disconnected messages */
Textual.handleEvent = function (event) {
'use strict';
var i, messages;
if (event === 'channelJoined') {
messages = document.querySelectorAll('div[command="-100"]');
for (i = 0; i < messages.length; i++) {
if (messages[i].getElementsByClassName('message')[0].textContent.search('Disconnect') !== -1) {
messages[i].parentNode.removeChild(messages[i]);
}
}
}
};
Textual.newMessagePostedToView = function (line) {
'use strict';
var message = document.getElementById('line-' + line);
var clone, elem, getEmbeddedImages, i, mode, messageText, sender, topic;
// reset the message count and previous nick, when you rejoin a channel
if (message.getAttribute('ltype') !== 'privmsg') {
rs.nick.count = 1;
rs.nick.nick = undefined;
}
// if it's a private message, colorize the nick and then track the state and fade away the nicks if needed
if (message.getAttribute('ltype') === 'privmsg' || message.getAttribute('ltype') === 'action') {
sender = message.getElementsByClassName('sender')[0];
if (sender.getAttribute('coloroverride') !== 'true') {
new NickColorGenerator(message); // colorized the nick
}
// Delete (ie, make foreground and background color identical) the previous line's nick, if it was set to be deleted
if (rs.nick.delete === true) {
elem = document.getElementById(rs.nick.id).getElementsByClassName('sender')[0];
elem.className += ' f';
}
// Track the nicks that submit messages, so that we can space out everything
if ((rs.nick.nick === sender.textContent) && (rs.nick.count < Equinox.fadeNicksFreq)
&& (message.getAttribute('ltype') !== 'action') && (Equinox.fadeNicks === true)) {
rs.nick.delete = true;
rs.nick.count += 1;
} else {
rs.nick.nick = sender.textContent;
rs.nick.count = 1;
rs.nick.delete = false;
}
// Track the previous message's id
rs.nick.id = message.getAttribute('id');
// Copy the message into the hidden history
clone = message.cloneNode(true);
clone.removeAttribute('id');
rs.history.appendChild(clone);
// Colorize it as well
if (sender.getAttribute('coloroverride') !== 'true') {
new NickColorGenerator(clone); // colorized the nick
}
// Remove old messages, if the history is longer than three messages
if (rs.history.childElementCount > 2) {
rs.history.removeChild(rs.history.childNodes[0]);
// Hide the first nick in the hidden history, if it's the same as the second
if ((rs.nick.count > 1) && (message.getAttribute('ltype') !== 'action')) {
rs.history.getElementsByClassName('sender')[0].style.visibility = 'hidden';
}
}
}
/* Let's kill topics that appear where they had already been set before
This happens when you join a room (like a reconnect) that you had been in and seen the topic before */
if (Equinox.squashTopics === true && message.getAttribute('ltype') === 'topic') {
topic = message.getElementsByClassName('message')[0].textContent.replace('Topic is ', '').replace(/\s+/, '');
if (message.getAttribute('command') === '332') { // an actual topic change
// hide the topic if it's the same topic again
if (topic === rs.topic.topic) {
message.parentNode.removeChild(message);
rs.topic.delete = true;
}
rs.topic.topic = topic;
}
if ((message.getAttribute('command') === '333') && (rs.topic.delete === true)) {
message.parentNode.removeChild(message);
rs.topic.delete = false;
}
}
// much like we suppress duplicate topics, we want to suppress duplicate modes
if (Equinox.squashModes === true && message.getAttribute('ltype') === 'mode') {
mode = message.getElementsByClassName('message')[0].textContent.replace(/\s+/, '');
if (mode === rs.mode.mode) {
message.parentNode.removeChild(message);
} else {
rs.mode.mode = mode;
}
}
// hide messages about yourself joining
if ((message.getAttribute('ltype') === 'join') || (message.getAttribute('ltype') === 'part')) {
app.localUserNickname(
function(returnValue) {
if (returnValue == message.getElementsByClassName('message')[0].getElementsByTagName('b')[0].textContent) {
message.parentNode.removeChild(message);
}
}
);
}
/* clear out all the old disconnect messages, if you're currently connected to the channel
note that normally Textual.handleEvent will catch this, but if you reload a theme, they will reappear */
if ((message.getAttribute('ltype') === 'debug') && (message.getAttribute('command') === '-100')) {
app.channelIsJoined(
function(returnValue) {
if (returnValue && message.getElementsByClassName('message')[0].textContent.search('Disconnect') !== -1) {
message.parentNode.removeChild(message);
}
}
);
} else {
// call the dateChange() function, for any message with a timestamp that's not a debug message
if (message.getAttribute('timestamp')) {
dateChange(message);
}
}
if (message.getAttribute('encrypted') === 'true') {
messageText = message.querySelector('.innerMessage');
if (messageText.innerText.indexOf('+OK') !== -1) {
message.setAttribute('encrypted', 'failed');
}
}
getEmbeddedImages = message.querySelectorAll('img');
if (getEmbeddedImages) {
for (i = 0; i < getEmbeddedImages.length; i++) {
getEmbeddedImages[i].onload = function (e) {
setTimeout(function () {
if (e.target.offsetHeight > (window.innerHeight - 150)) {
e.target.style.height = (window.innerHeight - 150);
}
}, 1000);
};
}
}
updateNicknameAssociatedWithNewMessage(message);
};
/* This is called when a .sender is clicked */
Textual.nicknameSingleClicked = function (e) {
'use strict';
var allLines, documentBody, i, sender;
var nickname = e.getAttribute('nickname');
var mappedIndex = mappedSelectedUsers.indexOf(nickname);
if (mappedIndex === -1) {
mappedSelectedUsers.push(nickname);
} else {
mappedSelectedUsers.splice(mappedIndex, 1);
}
/* Gather basic information. */
documentBody = document.getElementById('body_home');
allLines = documentBody.querySelectorAll('div[ltype="privmsg"], div[ltype="action"]');
/* Update all elements of the DOM matching conditions. */
for (i = 0; i < allLines.length; i++) {
sender = allLines[i].querySelectorAll('.sender');
if (sender.length > 0) {
if (sender[0].getAttribute('nickname') === nickname) {
/* e is nested as the .sender so we have to go three parents
up in order to reach the parent div that owns it. */
toggleSelectionStatusForNicknameInsideElement(sender[0]);
}
}
}
};
Textual.viewBodyDidLoad = function () {
'use strict';
Textual.fadeOutLoadingScreen(1.00, 0.95);
setTimeout(function () {
Textual.scrollToBottomOfView();
}, 500);
/* Disable date changes on OS X Mountain Lion because WebKit does not have some of
the features that this feature depends on (e.g. -webkit-flex) */
if (document.documentElement.getAttribute("systemversion").indexOf("10.8.") === 0) {
Equinox.showDateChanges = false;
}
};
Textual.viewInitiated = function () {
'use strict';
/* When the view is loaded, create a hidden history div which we display if there is scrollback */
var body = document.getElementById('body_home'), div = document.createElement('div');
div.id = 'scrolling_history';
document.getElementsByTagName('body')[0].appendChild(div);
rs.history = div;
/* setup the scrolling event to display the hidden history if the bottom element isn't in the viewport
also hide the topic bar when scrolling */
window.onscroll = function () {
var line, lines;
var topic = document.getElementById('topic_bar');
lines = body.getElementsByClassName('line');
if (lines.length < 2) {
return;
}
line = lines[lines.length - 1];
if (isMessageInViewport(line) === false) {
// scrollback
rs.history.style.display = 'inline';
if (topic) { topic.style.visibility = 'hidden'; }
} else {
// at the bottom
rs.history.style.display = 'none';
if (topic) { topic.style.visibility = 'visible'; }
}
};
};
|
fix issue with webkit triggering scroll and messing up the viewport
|
scripts.js
|
fix issue with webkit triggering scroll and messing up the viewport
|
<ide><path>cripts.js
<ide> return true;
<ide> }
<ide>
<add> console.log(Math.floor(elem.getBoundingClientRect().bottom), Math.floor(document.documentElement.clientHeight));
<add>
<ide> // Have to use Math.floor() because sometimes the getBoundingClientRect().bottom is a fraction of a pixel (!!!)
<del> return (Math.floor(elem.getBoundingClientRect().bottom) <= Math.floor(document.documentElement.clientHeight));
<add> return (Math.floor(elem.getBoundingClientRect().bottom - 1) <= Math.floor(document.documentElement.clientHeight));
<ide> }
<ide>
<ide> function toggleSelectionStatusForNicknameInsideElement(e) {
<ide> setTimeout(function () {
<ide> Textual.scrollToBottomOfView();
<ide> }, 500);
<del>
<add>
<ide> /* Disable date changes on OS X Mountain Lion because WebKit does not have some of
<ide> the features that this feature depends on (e.g. -webkit-flex) */
<ide> if (document.documentElement.getAttribute("systemversion").indexOf("10.8.") === 0) {
<ide>
<ide> /* setup the scrolling event to display the hidden history if the bottom element isn't in the viewport
<ide> also hide the topic bar when scrolling */
<del> window.onscroll = function () {
<add> window.addEventListener('scroll', function () {
<ide> var line, lines;
<ide> var topic = document.getElementById('topic_bar');
<ide>
<ide> rs.history.style.display = 'none';
<ide> if (topic) { topic.style.visibility = 'visible'; }
<ide> }
<del> };
<del>};
<add> });
<add>};
|
|
JavaScript
|
apache-2.0
|
fb063666e1cd7eb517a5a21aaa9b635740c02909
| 0 |
andygup/offline-editor-js,guo7711/offline-editor-js,andygup/offline-editor-js,plaxdan/offline-editor-js,plaxdan/offline-editor-js,eregn001/test5,EnzeZY/offline-editor-js,Ricardh522/offline-editor-js,plaxdan/offline-editor-js,Esri/offline-editor-js,EnzeZY/offline-editor-js,Ricardh522/offline-editor-js,andygup/offline-editor-js,Esri/offline-editor-js,EnzeZY/offline-editor-js,Ricardh522/offline-editor-js,Esri/offline-editor-js,eregn001/test5,degathem/offline-editor-js,degathem/offline-editor-js,guo7711/offline-editor-js,degathem/offline-editor-js,eregn001/TPSEricTest1,eregn001/test5,eregn001/TPSEricTest1,eregn001/TPSEricTest1,guo7711/offline-editor-js
|
"use strict";
define([
"edit/editsStore",
"edit/attachmentsStore",
"dojo/Evented",
"dojo/_base/Deferred",
"dojo/promise/all",
"dojo/_base/declare",
"dojo/_base/array",
"dojo/dom-attr",
"dojo/dom-style",
"dojo/query",
"esri/layers/GraphicsLayer",
"esri/graphic",
"esri/symbols/SimpleMarkerSymbol",
"esri/symbols/SimpleLineSymbol",
"esri/symbols/SimpleFillSymbol",
"esri/urlUtils"],
function(editsStore, AttachmentsStore,
Evented,Deferred,all,declare,array,domAttr,domStyle,query,
GraphicsLayer,Graphic,SimpleMarkerSymbol,SimpleLineSymbol,SimpleFillSymbol,urlUtils)
{
return declare([Evented],
{
_onlineStatus: "online",
_featureLayers: {},
ONLINE: "online", // all edits will directly go to the server
OFFLINE: "offline", // edits will be enqueued
RECONNECTING: "reconnecting", // sending stored edits to the server
// manager emits event when...
events: {
EDITS_SENT: 'edits-sent', // ...whenever any edit is actually sent to the server
EDITS_ENQUEUED: 'edits-enqueued', // ...when an edit is enqueued (and not sent to the server)
ALL_EDITS_SENT: 'all-edits-sent', // ...after going online and there are no pending edits in the queue
ATTACHMENT_ENQUEUED: 'attachment-enqueued',
ATTACHMENTS_SENT: 'attachments-sent'
},
/**
* Need to call this method only if you want to support offline attachments
* it is optional
* @param callback(success)
* @returns void
*/
initAttachments: function(callback)
{
callback = callback || function(success) { console.log("attachments inited ", success? "ok" : "failed"); };
if( !this._checkFileAPIs())
{
return callback(false, "File APIs not supported");
}
try
{
this.attachmentsStore = new AttachmentsStore();
if( /*false &&*/ this.attachmentsStore.isSupported() )
{
this.attachmentsStore.init(callback);
}
else
{
return callback(false, "indexedDB not supported");
}
}
catch(err)
{
console.log("problem! " + err.toString());
}
},
/**
* internal method that checks if this browser supports everything that is needed to handle offline attachments
* it also extends XMLHttpRequest with sendAsBinary() method, needed in Chrome
*/
_checkFileAPIs: function()
{
if( window.File && window.FileReader && window.FileList && window.Blob )
{
console.log("All APIs supported!");
if(!XMLHttpRequest.prototype.sendAsBinary )
{
// https://code.google.com/p/chromium/issues/detail?id=35705#c40
XMLHttpRequest.prototype.sendAsBinary = function(datastr)
{
function byteValue(x) {
return x.charCodeAt(0) & 0xff;
}
var ords = Array.prototype.map.call(datastr, byteValue);
var ui8a = new Uint8Array(ords);
this.send(ui8a.buffer);
};
console.log("extending XMLHttpRequest");
}
return true;
}
alert('The File APIs are not fully supported in this browser.');
return false;
},
/**
* internal method that extends an object with sendAsBinary() method
* sometimes extending XMLHttpRequest.prototype is not enough, as ArcGIS JS lib seems to mess with this object too
* @param oAjaxReq object to extend
*/
_extendAjaxReq: function(oAjaxReq)
{
oAjaxReq.sendAsBinary = XMLHttpRequest.prototype.sendAsBinary;
console.log("extending XMLHttpRequest");
},
/**
* Overrides a feature layer.
* @param layer
* @returns deferred
*/
extend: function(layer)
{
var self = this;
// we keep track of the FeatureLayer object
this._featureLayers[ layer.url ] = layer;
// replace the applyEdits() method
layer._applyEdits = layer.applyEdits;
// attachments
layer._addAttachment = layer.addAttachment;
layer._queryAttachmentInfos = layer.queryAttachmentInfos;
layer._deleteAttachments = layer.deleteAttachments;
/*
operations supported offline:
1. add a new attachment to an existing feature (DONE)
2. add a new attachment to a new feature (DONE)
3. remove an attachment that is already in the server... (NOT YET)
4. remove an attachment that is not in the server yet (DONE)
5. update an existing attachment to an existing feature (NOT YET)
6. update a new attachment (NOT YET)
concerns:
- manage the relationship between offline features and attachments: what if the user wants to add
an attachment to a feature that is still offline? we need to keep track of objectids so that when
the feature is sent to the server and receives a final objectid we replace the temporary negative id
by its final objectid (DONE)
- what if the user deletes an offline feature that had offline attachments? we need to discard the attachment (DONE)
pending tasks:
- delete attachment (DONE)
- send attachments to server when reconnecting (DONE)
- check for hasAttachments attribute in the FeatureLayer (NOT YET)
*/
//
// attachments
//
layer.queryAttachmentInfos = function(objectId,callback,errback)
{
if( self.getOnlineStatus() === self.ONLINE)
{
var def = this._queryAttachmentInfos(objectId,
function()
{
console.log(arguments);
self.emit(self.events.ATTACHMENTS_INFO,arguments);
callback && callback.apply(this,arguments);
},
errback);
return def;
}
if( !self.attachmentsStore )
{
console.log("in order to support attachments you need to call initAttachments() method of offlineFeaturesManager");
return;
}
// will only return LOCAL attachments
var deferred = new Deferred();
self.attachmentsStore.getAttachmentsByFeatureId(this.url, objectId, function(attachments)
{
callback && callback(attachments);
deferred.resolve(attachments);
});
return deferred;
};
layer.addAttachment = function(objectId,formNode,callback,errback)
{
if( self.getOnlineStatus() === self.ONLINE)
{
return this._addAttachment(objectId,formNode,
function()
{
console.log(arguments);
self.emit(self.events.ATTACHMENTS_SENT,arguments);
callback && callback.apply(this,arguments);
},
function(err)
{
console.log("addAttachment: " + err);
errback && errback.apply(this,arguments);
}
);
}
if( !self.attachmentsStore )
{
console.log("in order to support attachments you need to call initAttachments() method of offlineFeaturesManager");
return;
}
var files = this._getFilesFromForm(formNode);
var file = files[0]; // addAttachment can only add one file, so the rest -if any- are ignored
var deferred = new Deferred();
var attachmentId = this._getNextTempId();
self.attachmentsStore.store(this.url, attachmentId, objectId, file, function(success, newAttachment)
{
var returnValue = { attachmentId: attachmentId, objectId:objectId, success:success };
if( success )
{
self.emit(self.events.ATTACHMENT_ENQUEUED,returnValue);
callback && callback(returnValue);
deferred.resolve(returnValue);
// replace the default URL that is set by attachmentEditor with the local file URL
var attachmentUrl = this._url.path + "/" + objectId + "/attachments/" + attachmentId;
var attachmentElement = query("[href=" + attachmentUrl + "]");
attachmentElement.attr("href", newAttachment.url);
}
else
{
returnValue.error = "can't store attachment";
errback && errback(returnValue);
deferred.reject(returnValue);
}
}.bind(this));
return deferred;
};
layer.deleteAttachments = function(objectId,attachmentsIds,callback,errback)
{
if( self.getOnlineStatus() === self.ONLINE)
{
var def = this._deleteAttachments(objectId,attachmentsIds,
function()
{
callback && callback.apply(this,arguments);
},
function(err)
{
console.log("deleteAttachments: " + err);
errback && errback.apply(this,arguments);
});
return def;
}
if( !self.attachmentsStore )
{
console.log("in order to support attachments you need to call initAttachments() method of offlineFeaturesManager");
return;
}
// case 1.- it is a new attachment
// case 2.- it is an already existing attachment
// only case 1 is supported right now
// asynchronously delete each of the attachments
var promises = [];
attachmentsIds.forEach(function(attachmentId)
{
attachmentId = parseInt(attachmentId,10); // to number
console.assert( attachmentId<0 , "we only support deleting local attachments");
var deferred = new Deferred();
self.attachmentsStore.delete(attachmentId, function(success)
{
var result = { objectId: objectId, attachmentId: attachmentId, success: success };
deferred.resolve(result);
});
promises.push(deferred);
}, this);
// call callback once all deletes have finished
var allPromises = all(promises);
allPromises.then( function(results)
{
callback && callback(results);
});
return allPromises;
};
//
// other functions
//
/**
* Overrides the ArcGIS API for JavaSccript applyEdits() method.
* @param adds Creates a new edit entry.
* @param updates Updates an existing entry.
* @param deletes Deletes an existing entry.
* @param callback Called when the operation is complete.
* @param errback An error object is returned if an error occurs
* @returns {*} deferred
*/
layer.applyEdits = function(adds,updates,deletes,callback,errback)
{
// inside this method, 'this' will be the FeatureLayer
// and 'self' will be the offlineFeatureLayer object
if( self.getOnlineStatus() === self.ONLINE)
{
var def = this._applyEdits(adds,updates,deletes,
function()
{
self.emit(self.events.EDITS_SENT,arguments);
callback && callback.apply(this,arguments);
},
errback);
return def;
}
var deferred = new Deferred();
var results = { addResults:[],updateResults:[], deleteResults:[] };
var updatesMap = {};
this.onBeforeApplyEdits(adds, updates, deletes);
adds = adds || [];
adds.forEach(function(addEdit)
{
var objectId = this._getNextTempId();
addEdit.attributes[ this.objectIdField ] = objectId;
var result = editsStore.pushEdit(editsStore.ADD, this.url, addEdit);
results.addResults.push({ success:result.success, error: result.error, objectId: objectId});
if(result.success)
{
var phantomAdd = new Graphic(
addEdit.geometry,
self._getPhantomSymbol(addEdit.geometry, editsStore.ADD),
{
objectId: objectId
});
this._phantomLayer.add(phantomAdd);
domAttr.set(phantomAdd.getNode(),"stroke-dasharray","10,4");
domStyle.set(phantomAdd.getNode(), "pointer-events","none");
}
},this);
updates = updates || [];
updates.forEach(function(updateEdit)
{
var objectId = updateEdit.attributes[ this.objectIdField ];
var result = editsStore.pushEdit(editsStore.UPDATE, this.url, updateEdit);
results.updateResults.push({success:result.success, error: result.error, objectId: objectId});
updatesMap[ objectId ] = updateEdit;
if(result.success)
{
var phantomUpdate = new Graphic(
updateEdit.geometry,
self._getPhantomSymbol(updateEdit.geometry, editsStore.UPDATE),
{
objectId: objectId
});
this._phantomLayer.add(phantomUpdate);
domAttr.set(phantomUpdate.getNode(),"stroke-dasharray","5,2");
domStyle.set(phantomUpdate.getNode(), "pointer-events","none");
}
},this);
deletes = deletes || [];
deletes.forEach(function(deleteEdit)
{
var objectId = deleteEdit.attributes[ this.objectIdField ];
var result = editsStore.pushEdit(editsStore.DELETE, this.url, deleteEdit);
results.deleteResults.push({success:result.success, error: result.error, objectId: objectId});
if(result.success)
{
var phantomDelete = new Graphic(
deleteEdit.geometry,
self._getPhantomSymbol(deleteEdit.geometry, editsStore.DELETE),
{
objectId: objectId
});
this._phantomLayer.add(phantomDelete);
domAttr.set(phantomDelete.getNode(),"stroke-dasharray","4,4");
domStyle.set(phantomDelete.getNode(), "pointer-events","none");
}
if( self.attachmentsStore )
{
// delete local attachments of this feature, if any... we just launch the delete and don't wait for it to complete
self.attachmentsStore.deleteAttachmentsByFeatureId(this.url, objectId, function(deletedCount)
{
console.log("deleted",deletedCount,"attachments of feature",objectId);
});
}
},this);
/* we already pushed the edits into the local store, now we let the FeatureLayer to do the local updating of the layer graphics */
setTimeout(function()
{
this._editHandler(results, adds, updatesMap, callback, errback, deferred);
self.emit(self.events.EDITS_ENQUEUED, results);
}.bind(this),0);
return deferred;
}; // layer.applyEdits()
/* internal methods */
layer._getFilesFromForm = function(formNode)
{
var files = [];
var inputNodes = array.filter(formNode.elements, function(node) { return node.type === "file"; });
inputNodes.forEach(function(inputNode)
{
files.push.apply(files,inputNode.files);
},this);
return files;
};
layer._replaceFeatureIds = function(tempObjectIds,newObjectIds,callback)
{
console.log("replacing ids of attachments",tempObjectIds, newObjectIds);
console.assert( tempObjectIds.length === newObjectIds.length, "arrays must be the same length");
if(!tempObjectIds.length)
{
console.log("no ids to replace!");
callback(0);
}
var i, n = tempObjectIds.length;
var count = n;
var successCount = 0;
for(i=0; i<n; i++)
{
self.attachmentsStore.replaceFeatureId(this.url, tempObjectIds[i], newObjectIds[i], function(success)
{
--count;
successCount += (success? 1:0);
if( count === 0)
{
callback(successCount);
}
}.bind(this));
}
};
// we need to identify ADDs before sending them to the server
// we assign temporary ids (using negative numbers to distinguish them from real ids)
layer._nextTempId = -1;
layer._getNextTempId = function()
{
return this._nextTempId--;
};
function _initPhantomLayer()
{
try
{
layer._phantomLayer = new GraphicsLayer({opacity:0.8});
layer._map.addLayer(layer._phantomLayer);
}
catch(err)
{
console.log("Unable to init PhantomLayer");
}
}
_initPhantomLayer();
}, // extend
/**
* Forces library into an offline state. Any edits applied during this condition will be stored locally
*/
goOffline: function()
{
console.log('going offline');
this._onlineStatus = this.OFFLINE;
},
/**
* Forces library to return to an online state. If there are pending edits,
* an attempt will be made to sync them with the remote feature server
* @param callback callback( boolean, errors )
*/
goOnline: function(callback)
{
console.log('going online');
this._onlineStatus = this.RECONNECTING;
this._replayStoredEdits(function(success,responses)
{
var result = { features: { success:success, responses: responses} };
if( this.attachmentsStore )
{
console.log("sending attachments");
this._sendStoredAttachments(function(success, responses)
{
this._onlineStatus = this.ONLINE;
result.attachments = { success: success, responses:responses } ;
callback && callback(result);
}.bind(this));
}
else
{
this._onlineStatus = this.ONLINE;
callback && callback(result);
}
}.bind(this));
},
/**
* Determines if offline or online condition exists
* @returns {string} ONLINE or OFFLINE
*/
getOnlineStatus: function()
{
return this._onlineStatus;
},
/**
* A string value representing human readable information on pending edits
* @param edit
* @returns {string}
*/
getReadableEdit: function(edit)
{
var layer = this._featureLayers[ edit.layer ];
var graphic = editsStore._deserialize(edit.graphic);
var readableGraphic = graphic.geometry.type;
var layerId = edit.layer.substring(edit.layer.lastIndexOf('/')+1);
if(layer)
{
readableGraphic += " [id=" + graphic.attributes[layer.objectIdField] + "]";
}
return "o:" + edit.operation + ", l:" + layerId + ", g:" + readableGraphic;
},
/* internal methods */
//
// phantom symbols
//
_phantomSymbols: [],
_getPhantomSymbol: function(geometry, operation)
{
if( this._phantomSymbols.length === 0)
{
var color = [0,255,0,255];
var width = 1.5;
this._phantomSymbols['point'] = [];
this._phantomSymbols['point'][editsStore.ADD] = new SimpleMarkerSymbol({
"type": "esriSMS", "style": "esriSMSCross",
"xoffset": 10, "yoffset": 10,
"color": [255,255,255,0], "size": 15,
"outline": { "color": color, "width": width, "type": "esriSLS", "style": "esriSLSSolid" }
});
this._phantomSymbols['point'][editsStore.UPDATE] = new SimpleMarkerSymbol({
"type": "esriSMS", "style": "esriSMSCircle",
"xoffset": 0, "yoffset": 0,
"color": [255,255,255,0], "size": 15,
"outline": { "color": color, "width": width, "type": "esriSLS", "style": "esriSLSSolid" }
});
this._phantomSymbols['point'][editsStore.DELETE] = new SimpleMarkerSymbol({
"type": "esriSMS", "style": "esriSMSX",
"xoffset": 0, "yoffset": 0,
"color": [255,255,255,0], "size": 15,
"outline": { "color": color, "width": width, "type": "esriSLS", "style": "esriSLSSolid" }
});
this._phantomSymbols['multipoint'] = null;
this._phantomSymbols['polyline'] = [];
this._phantomSymbols['polyline'][editsStore.ADD] = new SimpleLineSymbol({
"type": "esriSLS", "style": "esriSLSSolid",
"color": color,"width": width
});
this._phantomSymbols['polyline'][editsStore.UPDATE] = new SimpleLineSymbol({
"type": "esriSLS", "style": "esriSLSSolid",
"color": color,"width": width
});
this._phantomSymbols['polyline'][editsStore.DELETE] = new SimpleLineSymbol({
"type": "esriSLS", "style": "esriSLSSolid",
"color": color,"width": width
});
this._phantomSymbols['polygon'] = [];
this._phantomSymbols['polygon'][editsStore.ADD] = new SimpleFillSymbol({
"type": "esriSFS",
"style": "esriSFSSolid",
"color": [255,255,255,0],
"outline": { "type": "esriSLS", "style": "esriSLSSolid", "color": color, "width": width }
});
this._phantomSymbols['polygon'][editsStore.UPDATE] = new SimpleFillSymbol({
"type": "esriSFS",
"style": "esriSFSSolid",
"color": [255,255,255,0],
"outline": { "type": "esriSLS", "style": "esriSLSDash", "color": color, "width": width }
});
this._phantomSymbols['polygon'][editsStore.DELETE] = new SimpleFillSymbol({
"type": "esriSFS",
"style": "esriSFSSolid",
"color": [255,255,255,0],
"outline": { "type": "esriSLS", "style": "esriSLSDot", "color": color, "width": width }
});
}
return this._phantomSymbols[ geometry.type ][ operation ];
},
//
// methods to handle attachment uploads
//
_fieldSegment: function(name,value)
{
return "Content-Disposition: form-data; name=\"" + name + "\"\r\n\r\n" + value + "\r\n";
},
_fileSegment: function(fieldName,fileName,fileType,fileContent)
{
return "Content-Disposition: form-data; name=\"" + fieldName +
"\"; filename=\""+ fileName +
"\"\r\nContent-Type: " + fileType + "\r\n\r\n" +
fileContent + "\r\n";
},
_uploadAttachment: function(attachment)
{
var dfd = new Deferred();
var segments = [];
segments.push( this._fieldSegment("f","json") );
segments.push( this._fileSegment("attachment", attachment.name,attachment.contentType,attachment.content ));
var oAjaxReq = new XMLHttpRequest();
// surprisingly, sometimes the oAjaxReq object doesn't have the sendAsBinary() method, even if we added it to the XMLHttpRequest.prototype
if( ! oAjaxReq.sendAsBinary )
{
this._extendAjaxReq(oAjaxReq);
}
oAjaxReq.onload = function(result)
{
dfd.resolve(JSON.parse(result.target.response));
};
oAjaxReq.onerror = function(err)
{
dfd.reject(err);
};
var proxy = esriConfig.defaults.io.proxyUrl || "";
if(proxy !== "")
proxy += "?"
console.log("proxy:", proxy);
oAjaxReq.open("post", proxy + attachment.featureId + "/addAttachment", true);
var sBoundary = "---------------------------" + Date.now().toString(16);
oAjaxReq.setRequestHeader("Content-Type", "multipart\/form-data; boundary=" + sBoundary);
oAjaxReq.sendAsBinary("--" + sBoundary + "\r\n" + segments.join("--" + sBoundary + "\r\n") + "--" + sBoundary + "--\r\n");
return dfd;
},
_deleteAttachment: function(attachmentId, uploadResult)
{
var dfd = new Deferred();
console.log("upload complete", uploadResult, attachmentId);
this.attachmentsStore.delete(attachmentId, function(success)
{
console.assert(success===true, "can't delete attachment already uploaded");
console.log("delete complete", success);
dfd.resolve(uploadResult);
});
return dfd;
},
_sendStoredAttachments: function(callback)
{
this.attachmentsStore.getAllAttachments(function(attachments)
{
console.log("we have",attachments.length,"attachments to upload");
var promises = [];
attachments.forEach(function(attachment)
{
console.log("sending attachment", attachment.id, "to feature", attachment.featureId);
var deleteCompleted =
this._uploadAttachment(attachment)
.then(function(uploadResult)
{
if( uploadResult.addAttachmentResult && uploadResult.addAttachmentResult.success === true)
{
console.log("upload success", uploadResult.addAttachmentResult.success);
return this._deleteAttachment(attachment.id, uploadResult);
}
else
{
console.log("upload failed", uploadResult);
return null;
}
}.bind(this),
function(err)
{
console.log("failed uploading attachment", attachment);
}
);
promises.push( deleteCompleted );
},this);
console.log("promises", promises.length);
var allPromises = all(promises);
allPromises.then(function(results)
{
console.log(results);
callback && callback(true, results);
},
function(err)
{
console.log("error!",err);
callback && callback(false, err);
});
}.bind(this));
},
//
// methods to send features back to the server
//
_optimizeEditsQueue: function()
{
var optimizedEdits = {},
editCount = editsStore.pendingEditsCount(),
optimizedCount = 0;
var edit, layer;
var layerEdits, objectId;
while( editsStore.hasPendingEdits() )
{
edit = editsStore.popFirstEdit();
layer = this._featureLayers[ edit.layer ];
if( ! (edit.layer in optimizedEdits) )
{
optimizedEdits[edit.layer] = {};
}
layerEdits = optimizedEdits[edit.layer];
objectId = edit.graphic.attributes[ layer.objectIdField ];
if( !( objectId in layerEdits) )
{
// first edit we see of this feature, no optimization to apply
layerEdits[ objectId ] = edit;
optimizedCount += 1;
}
else
{
// we already have seen one edit for this same feature... we can merge the two edits in a single operation
switch( edit.operation )
{
case editsStore.ADD:
/* impossible!! */
throw("can't add the same feature twice!");
break;
case editsStore.UPDATE:
layerEdits[ objectId ].graphic = edit.graphic;
break;
case editsStore.DELETE:
if(objectId < 0)
{
delete layerEdits[ objectId ];
optimizedCount -= 1;
}
else
{
layerEdits[objectId].operation = editsStore.DELETE;
}
break;
}
}
if( Object.keys(layerEdits).length === 0 )
{
delete optimizedEdits[edit.layer];
}
}
console.log("optimized", editCount, "edits into", optimizedCount,"edits of", Object.keys(optimizedEdits).length ,"layers");
return optimizedEdits;
},
_replayStoredEdits: function(callback)
{
if( editsStore.hasPendingEdits() )
{
//
// flatten the queue into unique edits for each feature, grouped by FeatureLayer
//
var optimizedEdits = this._optimizeEditsQueue();
var promises = {};
if( Object.keys(optimizedEdits).length === 0 )
{
this.emit(this.events.ALL_EDITS_SENT);
callback && callback(true, {});
return;
}
//
// send edits for each of the layers
//
var layerUrl, layer, layerEdits;
var adds, updates, deletes;
var tempObjectIds;
var objectId;
var edit;
var i,g;
for(layerUrl in optimizedEdits)
{
if(optimizedEdits.hasOwnProperty(layerUrl))
{
layer = this._featureLayers[ layerUrl ];
layerEdits = optimizedEdits[layerUrl];
console.assert(Object.keys(layerEdits).length !== 0);
layer.__onEditsComplete = layer.onEditsComplete;
layer.onEditsComplete = function() { console.log("intercepting events onEditsComplete"); };
layer.__onBeforeApplyEdits = layer.onBeforeApplyEdits;
layer.onBeforeApplyEdits = function() { console.log("intercepting events onBeforeApplyEdits");};
adds = []; updates = []; deletes = [];
tempObjectIds = [];
for(objectId in layerEdits)
{
if(layerEdits.hasOwnProperty(objectId))
{
edit = layerEdits[objectId];
switch(edit.operation)
{
case editsStore.ADD:
for(i=0; i<layer.graphics.length; i++)
{
g = layer.graphics[i];
if( g.attributes[layer.objectIdField] === edit.graphic.attributes[layer.objectIdField] )
{
layer.remove(g);
break;
}
}
tempObjectIds.push(edit.graphic.attributes[ layer.objectIdField ]);
delete edit.graphic.attributes[ layer.objectIdField ];
adds.push(edit.graphic);
break;
case editsStore.UPDATE:
updates.push(edit.graphic);
break;
case editsStore.DELETE:
deletes.push(edit.graphic);
break;
}
}
}
// closure to keep layer and tempObjectIds values
promises[layerUrl] = (function(layer,tempObjectIds)
{
// unfortunately we can't use the promise that is returned from layer._applyEdits()
// because it returns 3 result parameters (addResults,updateResults,deleteResults)
// and when we combine all promises in the dojo/promise/all() method below this only
// supports promises that return one value
var dfd = new Deferred();
layer._applyEdits(adds,updates,deletes,
function(addResults,updateResults,deleteResults)
{
layer._phantomLayer.clear();
layer.onEditsComplete = layer.__onEditsComplete; delete layer.__onEditsComplete;
layer.onBeforeApplyEdits = layer.__onBeforeApplyEdits; delete layer.__onBeforeApplyEdits;
var newObjectIds = addResults.map(function(r){ return r.objectId; });
if( layer.hasAttachments && tempObjectIds.length > 0)
{
layer._replaceFeatureIds(tempObjectIds,newObjectIds,function(success)
{
dfd.resolve({addResults:addResults,updateResults:updateResults,deleteResults:deleteResults}); // wrap three arguments in a single object
});
}
else
{
dfd.resolve({addResults:addResults,updateResults:updateResults,deleteResults:deleteResults}); // wrap three arguments in a single object
}
},
function(error)
{
layer.onEditsComplete = layer.__onEditsComplete; delete layer.__onEditsComplete;
layer.onBeforeApplyEdits = layer.__onBeforeApplyEdits; delete layer.__onBeforeApplyEdits;
dfd.reject(error);
}
);
return dfd;
}(layer,tempObjectIds));
}
}
//
// wait for all requests to finish
//
var allPromises = all(promises);
allPromises.then(
function(responses)
{
console.log("all responses are back");
this.emit(this.events.EDITS_SENT);
this.emit(this.events.ALL_EDITS_SENT);
callback && callback(true,responses);
}.bind(this),
function(errors)
{
console.log("ERROR!!");
console.log(errors);
callback && callback(false,errors);
}.bind(this));
} // hasPendingEdits()
else
{
this.emit(this.events.ALL_EDITS_SENT);
callback && callback(true, {});
}
}
}); // declare
}); // define
|
lib/edit/offlineFeaturesManager.js
|
"use strict";
define([
"edit/editsStore",
"edit/attachmentsStore",
"dojo/Evented",
"dojo/_base/Deferred",
"dojo/promise/all",
"dojo/_base/declare",
"dojo/_base/array",
"dojo/dom-attr",
"dojo/dom-style",
"dojo/query",
"esri/layers/GraphicsLayer",
"esri/graphic",
"esri/symbols/SimpleMarkerSymbol",
"esri/symbols/SimpleLineSymbol",
"esri/symbols/SimpleFillSymbol",
"esri/urlUtils"],
function(editsStore, AttachmentsStore,
Evented,Deferred,all,declare,array,domAttr,domStyle,query,
GraphicsLayer,Graphic,SimpleMarkerSymbol,SimpleLineSymbol,SimpleFillSymbol,urlUtils)
{
return declare([Evented],
{
_onlineStatus: "online",
_featureLayers: {},
ONLINE: "online", // all edits will directly go to the server
OFFLINE: "offline", // edits will be enqueued
RECONNECTING: "reconnecting", // sending stored edits to the server
// manager emits event when...
events: {
EDITS_SENT: 'edits-sent', // ...whenever any edit is actually sent to the server
EDITS_ENQUEUED: 'edits-enqueued', // ...when an edit is enqueued (and not sent to the server)
ALL_EDITS_SENT: 'all-edits-sent', // ...after going online and there are no pending edits in the queue
ATTACHMENT_ENQUEUED: 'attachment-enqueued',
ATTACHMENTS_SENT: 'attachments-sent'
},
/**
* Need to call this method only if you want to support offline attachments
* it is optional
* @param callback(success)
* @returns void
*/
initAttachments: function(callback)
{
callback = callback || function(success) { console.log("attachments inited ", success? "ok" : "failed"); };
if( !this._checkFileAPIs())
{
return callback(false, "File APIs not supported");
}
try
{
this.attachmentsStore = new AttachmentsStore();
if( /*false &&*/ this.attachmentsStore.isSupported() )
{
this.attachmentsStore.init(callback);
}
else
{
return callback(false, "indexedDB not supported");
}
}
catch(err)
{
console.log("problem! " + err.toString());
}
},
/**
* internal method that checks if this browser supports everything that is needed to handle offline attachments
* it also extends XMLHttpRequest with sendAsBinary() method, needed in Chrome
*/
_checkFileAPIs: function()
{
if( window.File && window.FileReader && window.FileList && window.Blob )
{
console.log("All APIs supported!");
if(!XMLHttpRequest.prototype.sendAsBinary )
{
// https://code.google.com/p/chromium/issues/detail?id=35705#c40
XMLHttpRequest.prototype.sendAsBinary = function(datastr)
{
function byteValue(x) {
return x.charCodeAt(0) & 0xff;
}
var ords = Array.prototype.map.call(datastr, byteValue);
var ui8a = new Uint8Array(ords);
this.send(ui8a.buffer);
};
console.log("extending XMLHttpRequest");
}
return true;
}
alert('The File APIs are not fully supported in this browser.');
return false;
},
/**
* internal method that extends an object with sendAsBinary() method
* sometimes extending XMLHttpRequest.prototype is not enough, as ArcGIS JS lib seems to mess with this object too
* @param oAjaxReq object to extend
*/
_extendAjaxReq: function(oAjaxReq)
{
oAjaxReq.sendAsBinary = XMLHttpRequest.prototype.sendAsBinary;
console.log("extending XMLHttpRequest");
},
/**
* Overrides a feature layer.
* @param layer
* @returns deferred
*/
extend: function(layer)
{
var self = this;
// we keep track of the FeatureLayer object
this._featureLayers[ layer.url ] = layer;
// replace the applyEdits() method
layer._applyEdits = layer.applyEdits;
// attachments
layer._addAttachment = layer.addAttachment;
layer._queryAttachmentInfos = layer.queryAttachmentInfos;
layer._deleteAttachments = layer.deleteAttachments;
/*
operations supported offline:
1. add a new attachment to an existing feature (DONE)
2. add a new attachment to a new feature (DONE)
3. remove an attachment that is already in the server... (NOT YET)
4. remove an attachment that is not in the server yet (DONE)
5. update an existing attachment to an existing feature (NOT YET)
6. update a new attachment (NOT YET)
concerns:
- manage the relationship between offline features and attachments: what if the user wants to add
an attachment to a feature that is still offline? we need to keep track of objectids so that when
the feature is sent to the server and receives a final objectid we replace the temporary negative id
by its final objectid (DONE)
- what if the user deletes an offline feature that had offline attachments? we need to discard the attachment (DONE)
pending tasks:
- delete attachment (DONE)
- send attachments to server when reconnecting (DONE)
- check for hasAttachments attribute in the FeatureLayer (NOT YET)
*/
//
// attachments
//
layer.queryAttachmentInfos = function(objectId,callback,errback)
{
if( self.getOnlineStatus() === self.ONLINE)
{
var def = this._queryAttachmentInfos(objectId,
function()
{
console.log(arguments);
self.emit(self.events.ATTACHMENTS_INFO,arguments);
callback && callback.apply(this,arguments);
},
errback);
return def;
}
if( !self.attachmentsStore )
{
console.log("in order to support attachments you need to call initAttachments() method of offlineFeaturesManager");
return;
}
// will only return LOCAL attachments
var deferred = new Deferred();
self.attachmentsStore.getAttachmentsByFeatureId(this.url, objectId, function(attachments)
{
callback && callback(attachments);
deferred.resolve(attachments);
});
return deferred;
};
layer.addAttachment = function(objectId,formNode,callback,errback)
{
if( self.getOnlineStatus() === self.ONLINE)
{
return this._addAttachment(objectId,formNode,
function()
{
console.log(arguments);
self.emit(self.events.ATTACHMENTS_SENT,arguments);
callback && callback.apply(this,arguments);
},
function(err)
{
console.log("addAttachment: " + err);
errback && errback.apply(this,arguments);
}
);
}
if( !self.attachmentsStore )
{
console.log("in order to support attachments you need to call initAttachments() method of offlineFeaturesManager");
return;
}
var files = this._getFilesFromForm(formNode);
var file = files[0]; // addAttachment can only add one file, so the rest -if any- are ignored
var deferred = new Deferred();
var attachmentId = this._getNextTempId();
self.attachmentsStore.store(this.url, attachmentId, objectId, file, function(success, newAttachment)
{
var returnValue = { attachmentId: attachmentId, objectId:objectId, success:success };
if( success )
{
self.emit(self.events.ATTACHMENT_ENQUEUED,returnValue);
callback && callback(returnValue);
deferred.resolve(returnValue);
// replace the default URL that is set by attachmentEditor with the local file URL
var attachmentUrl = this._url.path + "/" + objectId + "/attachments/" + attachmentId;
var attachmentElement = query("[href=" + attachmentUrl + "]");
attachmentElement.attr("href", newAttachment.url);
}
else
{
returnValue.error = "can't store attachment";
errback && errback(returnValue);
deferred.reject(returnValue);
}
}.bind(this));
return deferred;
};
layer.deleteAttachments = function(objectId,attachmentsIds,callback,errback)
{
if( self.getOnlineStatus() === self.ONLINE)
{
var def = this._deleteAttachments(objectId,attachmentsIds,
function()
{
callback && callback.apply(this,arguments);
},
function(err)
{
console.log("deleteAttachments: " + err);
errback && errback.apply(this,arguments);
});
return def;
}
if( !self.attachmentsStore )
{
console.log("in order to support attachments you need to call initAttachments() method of offlineFeaturesManager");
return;
}
// case 1.- it is a new attachment
// case 2.- it is an already existing attachment
// only case 1 is supported right now
// asynchronously delete each of the attachments
var promises = [];
attachmentsIds.forEach(function(attachmentId)
{
attachmentId = parseInt(attachmentId,10); // to number
console.assert( attachmentId<0 , "we only support deleting local attachments");
var deferred = new Deferred();
self.attachmentsStore.delete(attachmentId, function(success)
{
var result = { objectId: objectId, attachmentId: attachmentId, success: success };
deferred.resolve(result);
});
promises.push(deferred);
}, this);
// call callback once all deletes have finished
var allPromises = all(promises);
allPromises.then( function(results)
{
callback && callback(results);
});
return allPromises;
};
//
// other functions
//
/**
* Overrides the ArcGIS API for JavaSccript applyEdits() method.
* @param adds Creates a new edit entry.
* @param updates Updates an existing entry.
* @param deletes Deletes an existing entry.
* @param callback Called when the operation is complete.
* @param errback An error object is returned if an error occurs
* @returns {*} deferred
*/
layer.applyEdits = function(adds,updates,deletes,callback,errback)
{
// inside this method, 'this' will be the FeatureLayer
// and 'self' will be the offlineFeatureLayer object
if( self.getOnlineStatus() === self.ONLINE)
{
var def = this._applyEdits(adds,updates,deletes,
function()
{
self.emit(self.events.EDITS_SENT,arguments);
callback && callback.apply(this,arguments);
},
errback);
return def;
}
var deferred = new Deferred();
var results = { addResults:[],updateResults:[], deleteResults:[] };
var updatesMap = {};
this.onBeforeApplyEdits(adds, updates, deletes);
adds = adds || [];
adds.forEach(function(addEdit)
{
var objectId = this._getNextTempId();
addEdit.attributes[ this.objectIdField ] = objectId;
var result = editsStore.pushEdit(editsStore.ADD, this.url, addEdit);
results.addResults.push({ success:result.success, error: result.error, objectId: objectId});
if(result.success)
{
var phantomAdd = new Graphic(
addEdit.geometry,
self._getPhantomSymbol(addEdit.geometry, editsStore.ADD),
{
objectId: objectId
});
this._phantomLayer.add(phantomAdd);
domAttr.set(phantomAdd.getNode(),"stroke-dasharray","10,4");
domStyle.set(phantomAdd.getNode(), "pointer-events","none");
}
},this);
updates = updates || [];
updates.forEach(function(updateEdit)
{
var objectId = updateEdit.attributes[ this.objectIdField ];
var result = editsStore.pushEdit(editsStore.UPDATE, this.url, updateEdit);
results.updateResults.push({success:result.success, error: result.error, objectId: objectId});
updatesMap[ objectId ] = updateEdit;
if(result.success)
{
var phantomUpdate = new Graphic(
updateEdit.geometry,
self._getPhantomSymbol(updateEdit.geometry, editsStore.UPDATE),
{
objectId: objectId
});
this._phantomLayer.add(phantomUpdate);
domAttr.set(phantomUpdate.getNode(),"stroke-dasharray","5,2");
domStyle.set(phantomUpdate.getNode(), "pointer-events","none");
}
},this);
deletes = deletes || [];
deletes.forEach(function(deleteEdit)
{
var objectId = deleteEdit.attributes[ this.objectIdField ];
var result = editsStore.pushEdit(editsStore.DELETE, this.url, deleteEdit);
results.deleteResults.push({success:result.success, error: result.error, objectId: objectId});
if(result.success)
{
var phantomDelete = new Graphic(
deleteEdit.geometry,
self._getPhantomSymbol(deleteEdit.geometry, editsStore.DELETE),
{
objectId: objectId
});
this._phantomLayer.add(phantomDelete);
domAttr.set(phantomDelete.getNode(),"stroke-dasharray","4,4");
domStyle.set(phantomDelete.getNode(), "pointer-events","none");
}
if( self.attachmentsStore )
{
// delete local attachments of this feature, if any... we just launch the delete and don't wait for it to complete
self.attachmentsStore.deleteAttachmentsByFeatureId(this.url, objectId, function(deletedCount)
{
console.log("deleted",deletedCount,"attachments of feature",objectId);
});
}
},this);
/* we already pushed the edits into the local store, now we let the FeatureLayer to do the local updating of the layer graphics */
setTimeout(function()
{
this._editHandler(results, adds, updatesMap, callback, errback, deferred);
self.emit(self.events.EDITS_ENQUEUED, results);
}.bind(this),0);
return deferred;
}; // layer.applyEdits()
/* internal methods */
layer._getFilesFromForm = function(formNode)
{
var files = [];
var inputNodes = array.filter(formNode.elements, function(node) { return node.type === "file"; });
inputNodes.forEach(function(inputNode)
{
files.push.apply(files,inputNode.files);
},this);
return files;
};
layer._replaceFeatureIds = function(tempObjectIds,newObjectIds,callback)
{
console.log("replacing ids of attachments",tempObjectIds, newObjectIds);
console.assert( tempObjectIds.length === newObjectIds.length, "arrays must be the same length");
if(!tempObjectIds.length)
{
console.log("no ids to replace!");
callback(0);
}
var i, n = tempObjectIds.length;
var count = n;
var successCount = 0;
for(i=0; i<n; i++)
{
self.attachmentsStore.replaceFeatureId(this.url, tempObjectIds[i], newObjectIds[i], function(success)
{
--count;
successCount += (success? 1:0);
if( count === 0)
{
callback(successCount);
}
}.bind(this));
}
};
// we need to identify ADDs before sending them to the server
// we assign temporary ids (using negative numbers to distinguish them from real ids)
layer._nextTempId = -1;
layer._getNextTempId = function()
{
return this._nextTempId--;
};
function _initPhantomLayer()
{
try
{
layer._phantomLayer = new GraphicsLayer({opacity:0.8});
layer._map.addLayer(layer._phantomLayer);
}
catch(err)
{
console.log("Unable to init PhantomLayer");
}
}
_initPhantomLayer();
}, // extend
/**
* Forces library into an offline state. Any edits applied during this condition will be stored locally
*/
goOffline: function()
{
console.log('going offline');
this._onlineStatus = this.OFFLINE;
},
/**
* Forces library to return to an online state. If there are pending edits,
* an attempt will be made to sync them with the remote feature server
* @param callback callback( boolean, errors )
*/
goOnline: function(callback)
{
console.log('going online');
this._onlineStatus = this.RECONNECTING;
this._replayStoredEdits(function(success,responses)
{
var result = { features: { success:success, responses: responses} };
if( this.attachmentsStore )
{
console.log("sending attachments");
this._sendStoredAttachments(function(success, responses)
{
this._onlineStatus = this.ONLINE;
result.attachments = { success: success, responses:responses } ;
callback && callback(result);
}.bind(this));
}
else
{
this._onlineStatus = this.ONLINE;
callback && callback(result);
}
}.bind(this));
},
/**
* Determines if offline or online condition exists
* @returns {string} ONLINE or OFFLINE
*/
getOnlineStatus: function()
{
return this._onlineStatus;
},
/**
* A string value representing human readable information on pending edits
* @param edit
* @returns {string}
*/
getReadableEdit: function(edit)
{
var layer = this._featureLayers[ edit.layer ];
var graphic = editsStore._deserialize(edit.graphic);
var readableGraphic = graphic.geometry.type;
var layerId = edit.layer.substring(edit.layer.lastIndexOf('/')+1);
if(layer)
{
readableGraphic += " [id=" + graphic.attributes[layer.objectIdField] + "]";
}
return "o:" + edit.operation + ", l:" + layerId + ", g:" + readableGraphic;
},
/* internal methods */
//
// phantom symbols
//
_phantomSymbols: [],
_getPhantomSymbol: function(geometry, operation)
{
if( this._phantomSymbols.length === 0)
{
var color = [0,255,0,255];
var width = 1.5;
this._phantomSymbols['point'] = [];
this._phantomSymbols['point'][editsStore.ADD] = new SimpleMarkerSymbol({
"type": "esriSMS", "style": "esriSMSCross",
"xoffset": 10, "yoffset": 10,
"color": [255,255,255,0], "size": 15,
"outline": { "color": color, "width": width, "type": "esriSLS", "style": "esriSLSSolid" }
});
this._phantomSymbols['point'][editsStore.UPDATE] = new SimpleMarkerSymbol({
"type": "esriSMS", "style": "esriSMSCircle",
"xoffset": 0, "yoffset": 0,
"color": [255,255,255,0], "size": 15,
"outline": { "color": color, "width": width, "type": "esriSLS", "style": "esriSLSSolid" }
});
this._phantomSymbols['point'][editsStore.DELETE] = new SimpleMarkerSymbol({
"type": "esriSMS", "style": "esriSMSX",
"xoffset": 0, "yoffset": 0,
"color": [255,255,255,0], "size": 15,
"outline": { "color": color, "width": width, "type": "esriSLS", "style": "esriSLSSolid" }
});
this._phantomSymbols['multipoint'] = null;
this._phantomSymbols['polyline'] = [];
this._phantomSymbols['polyline'][editsStore.ADD] = new SimpleLineSymbol({
"type": "esriSLS", "style": "esriSLSSolid",
"color": color,"width": width
});
this._phantomSymbols['polyline'][editsStore.UPDATE] = new SimpleLineSymbol({
"type": "esriSLS", "style": "esriSLSSolid",
"color": color,"width": width
});
this._phantomSymbols['polyline'][editsStore.DELETE] = new SimpleLineSymbol({
"type": "esriSLS", "style": "esriSLSSolid",
"color": color,"width": width
});
this._phantomSymbols['polygon'] = [];
this._phantomSymbols['polygon'][editsStore.ADD] = new SimpleFillSymbol({
"type": "esriSFS",
"style": "esriSFSSolid",
"color": [255,255,255,0],
"outline": { "type": "esriSLS", "style": "esriSLSSolid", "color": color, "width": width }
});
this._phantomSymbols['polygon'][editsStore.UPDATE] = new SimpleFillSymbol({
"type": "esriSFS",
"style": "esriSFSSolid",
"color": [255,255,255,0],
"outline": { "type": "esriSLS", "style": "esriSLSDash", "color": color, "width": width }
});
this._phantomSymbols['polygon'][editsStore.DELETE] = new SimpleFillSymbol({
"type": "esriSFS",
"style": "esriSFSSolid",
"color": [255,255,255,0],
"outline": { "type": "esriSLS", "style": "esriSLSDot", "color": color, "width": width }
});
}
return this._phantomSymbols[ geometry.type ][ operation ];
},
//
// methods to handle attachment uploads
//
_fieldSegment: function(name,value)
{
return "Content-Disposition: form-data; name=\"" + name + "\"\r\n\r\n" + value + "\r\n";
},
_fileSegment: function(fieldName,fileName,fileType,fileContent)
{
return "Content-Disposition: form-data; name=\"" + fieldName +
"\"; filename=\""+ fileName +
"\"\r\nContent-Type: " + fileType + "\r\n\r\n" +
fileContent + "\r\n";
},
_uploadAttachment: function(attachment)
{
var dfd = new Deferred();
var segments = [];
segments.push( this._fieldSegment("f","json") );
segments.push( this._fileSegment("attachment", attachment.name,attachment.contentType,attachment.content ));
var oAjaxReq = new XMLHttpRequest();
// surprisingly, sometimes the oAjaxReq object doesn't have the sendAsBinary() method, even if we added it to the XMLHttpRequest.prototype
if( ! oAjaxReq.sendAsBinary )
{
this._extendAjaxReq(oAjaxReq);
}
oAjaxReq.onload = function(result)
{
dfd.resolve(JSON.parse(result.target.response));
};
oAjaxReq.onerror = function(err)
{
dfd.reject(err);
};
var proxy = esriConfig.defaults.io.proxyUrl || "";
if(proxy !== "")
proxy += "?"
console.log("proxy:", proxy);
oAjaxReq.open("post", proxy + attachment.featureId + "/addAttachment", true);
var sBoundary = "---------------------------" + Date.now().toString(16);
oAjaxReq.setRequestHeader("Content-Type", "multipart\/form-data; boundary=" + sBoundary);
oAjaxReq.sendAsBinary("--" + sBoundary + "\r\n" + segments.join("--" + sBoundary + "\r\n") + "--" + sBoundary + "--\r\n");
return dfd;
},
_deleteAttachment: function(attachmentId, uploadCompleted)
{
var dfd = new Deferred();
uploadCompleted.then(
function(result)
{
console.log("upload complete",result,attachmentId);
this.attachmentsStore.delete(attachmentId, function(success)
{
console.log("delete complete", success);
dfd.resolve(result);
});
}.bind(this),
function(err)
{
dfd.reject(err);
}
);
return dfd;
},
_sendStoredAttachments: function(callback)
{
this.attachmentsStore.getAllAttachments(function(attachments)
{
console.log("we have",attachments.length,"attachments to upload");
var promises = [];
attachments.forEach(function(attachment)
{
console.log("sending attachment", attachment.id, "to feature", attachment.featureId);
var uploadCompleted = this._uploadAttachment(attachment);
var deleteCompleted = this._deleteAttachment(attachment.id, uploadCompleted);
promises.push( deleteCompleted );
}.bind(this));
console.log("promises", promises.length);
var allPromises = all(promises);
allPromises.then(function(results)
{
console.log(results);
callback && callback(true, results);
},
function(err)
{
console.log("error!",err);
callback && callback(false, err);
});
}.bind(this));
},
//
// methods to send features back to the server
//
_optimizeEditsQueue: function()
{
var optimizedEdits = {},
editCount = editsStore.pendingEditsCount(),
optimizedCount = 0;
var edit, layer;
var layerEdits, objectId;
while( editsStore.hasPendingEdits() )
{
edit = editsStore.popFirstEdit();
layer = this._featureLayers[ edit.layer ];
if( ! (edit.layer in optimizedEdits) )
{
optimizedEdits[edit.layer] = {};
}
layerEdits = optimizedEdits[edit.layer];
objectId = edit.graphic.attributes[ layer.objectIdField ];
if( !( objectId in layerEdits) )
{
// first edit we see of this feature, no optimization to apply
layerEdits[ objectId ] = edit;
optimizedCount += 1;
}
else
{
// we already have seen one edit for this same feature... we can merge the two edits in a single operation
switch( edit.operation )
{
case editsStore.ADD:
/* impossible!! */
throw("can't add the same feature twice!");
break;
case editsStore.UPDATE:
layerEdits[ objectId ].graphic = edit.graphic;
break;
case editsStore.DELETE:
if(objectId < 0)
{
delete layerEdits[ objectId ];
optimizedCount -= 1;
}
else
{
layerEdits[objectId].operation = editsStore.DELETE;
}
break;
}
}
if( Object.keys(layerEdits).length === 0 )
{
delete optimizedEdits[edit.layer];
}
}
console.log("optimized", editCount, "edits into", optimizedCount,"edits of", Object.keys(optimizedEdits).length ,"layers");
return optimizedEdits;
},
_replayStoredEdits: function(callback)
{
if( editsStore.hasPendingEdits() )
{
//
// flatten the queue into unique edits for each feature, grouped by FeatureLayer
//
var optimizedEdits = this._optimizeEditsQueue();
var promises = {};
if( Object.keys(optimizedEdits).length === 0 )
{
this.emit(this.events.ALL_EDITS_SENT);
callback && callback(true, {});
return;
}
//
// send edits for each of the layers
//
var layerUrl, layer, layerEdits;
var adds, updates, deletes;
var tempObjectIds;
var objectId;
var edit;
var i,g;
for(layerUrl in optimizedEdits)
{
if(optimizedEdits.hasOwnProperty(layerUrl))
{
layer = this._featureLayers[ layerUrl ];
layerEdits = optimizedEdits[layerUrl];
console.assert(Object.keys(layerEdits).length !== 0);
layer.__onEditsComplete = layer.onEditsComplete;
layer.onEditsComplete = function() { console.log("intercepting events onEditsComplete"); };
layer.__onBeforeApplyEdits = layer.onBeforeApplyEdits;
layer.onBeforeApplyEdits = function() { console.log("intercepting events onBeforeApplyEdits");};
adds = []; updates = []; deletes = [];
tempObjectIds = [];
for(objectId in layerEdits)
{
if(layerEdits.hasOwnProperty(objectId))
{
edit = layerEdits[objectId];
switch(edit.operation)
{
case editsStore.ADD:
for(i=0; i<layer.graphics.length; i++)
{
g = layer.graphics[i];
if( g.attributes[layer.objectIdField] === edit.graphic.attributes[layer.objectIdField] )
{
layer.remove(g);
break;
}
}
tempObjectIds.push(edit.graphic.attributes[ layer.objectIdField ]);
delete edit.graphic.attributes[ layer.objectIdField ];
adds.push(edit.graphic);
break;
case editsStore.UPDATE:
updates.push(edit.graphic);
break;
case editsStore.DELETE:
deletes.push(edit.graphic);
break;
}
}
}
// closure to keep layer and tempObjectIds values
promises[layerUrl] = (function(layer,tempObjectIds)
{
// unfortunately we can't use the promise that is returned from layer._applyEdits()
// because it returns 3 result parameters (addResults,updateResults,deleteResults)
// and when we combine all promises in the dojo/promise/all() method below this only
// supports promises that return one value
var dfd = new Deferred();
layer._applyEdits(adds,updates,deletes,
function(addResults,updateResults,deleteResults)
{
layer._phantomLayer.clear();
layer.onEditsComplete = layer.__onEditsComplete; delete layer.__onEditsComplete;
layer.onBeforeApplyEdits = layer.__onBeforeApplyEdits; delete layer.__onBeforeApplyEdits;
var newObjectIds = addResults.map(function(r){ return r.objectId; });
if( layer.hasAttachments && tempObjectIds.length > 0)
{
layer._replaceFeatureIds(tempObjectIds,newObjectIds,function(success)
{
dfd.resolve({addResults:addResults,updateResults:updateResults,deleteResults:deleteResults}); // wrap three arguments in a single object
});
}
else
{
dfd.resolve({addResults:addResults,updateResults:updateResults,deleteResults:deleteResults}); // wrap three arguments in a single object
}
},
function(error)
{
layer.onEditsComplete = layer.__onEditsComplete; delete layer.__onEditsComplete;
layer.onBeforeApplyEdits = layer.__onBeforeApplyEdits; delete layer.__onBeforeApplyEdits;
dfd.reject(error);
}
);
return dfd;
}(layer,tempObjectIds));
}
}
//
// wait for all requests to finish
//
var allPromises = all(promises);
allPromises.then(
function(responses)
{
console.log("all responses are back");
this.emit(this.events.EDITS_SENT);
this.emit(this.events.ALL_EDITS_SENT);
callback && callback(true,responses);
}.bind(this),
function(errors)
{
console.log("ERROR!!");
console.log(errors);
callback && callback(false,errors);
}.bind(this));
} // hasPendingEdits()
else
{
this.emit(this.events.ALL_EDITS_SENT);
callback && callback(true, {});
}
}
}); // declare
}); // define
|
refactored promises
|
lib/edit/offlineFeaturesManager.js
|
refactored promises
|
<ide><path>ib/edit/offlineFeaturesManager.js
<ide> return dfd;
<ide> },
<ide>
<del> _deleteAttachment: function(attachmentId, uploadCompleted)
<add> _deleteAttachment: function(attachmentId, uploadResult)
<ide> {
<ide> var dfd = new Deferred();
<ide>
<del> uploadCompleted.then(
<del> function(result)
<del> {
<del> console.log("upload complete",result,attachmentId);
<del> this.attachmentsStore.delete(attachmentId, function(success)
<del> {
<del> console.log("delete complete", success);
<del> dfd.resolve(result);
<del> });
<del> }.bind(this),
<del> function(err)
<del> {
<del> dfd.reject(err);
<del> }
<del> );
<add> console.log("upload complete", uploadResult, attachmentId);
<add> this.attachmentsStore.delete(attachmentId, function(success)
<add> {
<add> console.assert(success===true, "can't delete attachment already uploaded");
<add> console.log("delete complete", success);
<add> dfd.resolve(uploadResult);
<add> });
<ide>
<ide> return dfd;
<ide> },
<ide> attachments.forEach(function(attachment)
<ide> {
<ide> console.log("sending attachment", attachment.id, "to feature", attachment.featureId);
<del> var uploadCompleted = this._uploadAttachment(attachment);
<del> var deleteCompleted = this._deleteAttachment(attachment.id, uploadCompleted);
<add> var deleteCompleted =
<add> this._uploadAttachment(attachment)
<add> .then(function(uploadResult)
<add> {
<add> if( uploadResult.addAttachmentResult && uploadResult.addAttachmentResult.success === true)
<add> {
<add> console.log("upload success", uploadResult.addAttachmentResult.success);
<add> return this._deleteAttachment(attachment.id, uploadResult);
<add> }
<add> else
<add> {
<add> console.log("upload failed", uploadResult);
<add> return null;
<add> }
<add> }.bind(this),
<add> function(err)
<add> {
<add> console.log("failed uploading attachment", attachment);
<add> }
<add> );
<ide> promises.push( deleteCompleted );
<del> }.bind(this));
<add> },this);
<ide> console.log("promises", promises.length);
<ide> var allPromises = all(promises);
<ide> allPromises.then(function(results)
|
|
Java
|
agpl-3.0
|
b04a8054f760791fc8cf912a3804b9fdfadee977
| 0 |
tfrdidi/MigrateWahlzeitIntoTheCloud,tfrdidi/MigrateWahlzeitIntoTheCloud,tfrdidi/MigrateWahlzeitIntoTheCloud
|
/*
* Copyright (c) 2006-2009 by Dirk Riehle, http://dirkriehle.com
*
* This file is part of the Wahlzeit photo rating application.
*
* 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. If not, see
* <http://www.gnu.org/licenses/>.
*/
package org.wahlzeit.handlers;
/**
* @author dirkriehle
*/
public interface PartUtil {
String DEFAULT_PAGE_NAME = "index";
String NULL_INFO_NAME = "nullInfo";
String NULL_INFO_FILE = "infos/NullInfo";
String NULL_FORM_NAME = "nullForm";
String NULL_FORM_FILE = "forms/NullForm";
String SHOW_INFO_PAGE_FILE = "pages/ShowInfoPage";
String SHOW_PART_PAGE_FILE = "pages/ShowPartPage";
String SHOW_NOTE_PAGE_NAME = "note";
String SHOW_NOTE_PAGE_FILE = "pages/ShowNotePage";
String SHOW_PHOTO_PAGE_NAME = "index";
String SHOW_PHOTO_PAGE_FILE = "pages/ShowPhotoPage";
String CAPTION_INFO_FILE = "infos/CaptionInfo";
String BLURP_INFO_FILE = "infos/BlurpInfo";
String PHOTO_INFO_FILE = "infos/PhotoInfo";
String LINKS_INFO_FILE = "infos/LinksInfo";
String BANNER_INFO_FILE = "infos/BannerInfo";
String FILTER_PHOTOS_FORM_NAME = "filterPhotosForm";
String FILTER_PHOTOS_FORM_FILE = "forms/FilterPhotosForm";
String PRAISE_PHOTO_FORM_NAME = "praisePhotoForm";
String PRAISE_PHOTO_FORM_FILE = "forms/PraisePhotoForm";
String ENGAGE_GUEST_FORM_NAME = "engageGuestForm";
String ENGAGE_GUEST_FORM_FILE = "forms/EngageGuestForm";
String ABOUT_PAGE_NAME = "about";
String ABOUT_INFO_FILE = "infos/AboutInfo";
String CONTACT_PAGE_NAME = "contact";
String CONTACT_INFO_FILE = "infos/ContactInfo";
String IMPRINT_PAGE_NAME = "imprint";
String IMPRINT_INFO_FILE = "infos/ImprintInfo";
String TERMS_PAGE_NAME = "terms";
String TERMS_INFO_FILE = "infos/TermsInfo";
String HIDDEN_INFO_FILE = "infos/HiddenInfo";
String DONE_INFO_FILE = "infos/DoneInfo";
String FILTER_PHOTOS_PAGE_NAME = "filter";
String FLAG_PHOTO_PAGE_NAME = "flag";
String FLAG_PHOTO_FORM_NAME = "flagPhotoForm";
String FLAG_PHOTO_FORM_FILE = "forms/FlagPhotoForm";
String TELL_FRIEND_PAGE_NAME = "tell";
String TELL_FRIEND_FORM_NAME = "tellFriendForm";
String TELL_FRIEND_FORM_FILE = "forms/TellFriendForm";
String SEND_EMAIL_PAGE_NAME = "connect";
String SEND_EMAIL_FORM_NAME = "sendEmailForm";
String SEND_EMAIL_FORM_FILE = "forms/SendEmailForm";
String SET_OPTIONS_PAGE_NAME = "options";
String SET_OPTIONS_FORM_NAME = "setOptionsForm";
String SET_OPTIONS_FORM_FILE = "forms/SetOptionsForm";
String SIGNUP_PAGE_NAME = "signup";
String SIGNUP_FORM_NAME = "signupForm";
String SIGNUP_FORM_FILE = "forms/SignupForm";
String CONFIRM_ACCOUNT_PAGE_NAME = "confirm";
String LOGIN_PAGE_NAME = "login";
String LOGIN_FORM_NAME = "loginForm";
String LOGIN_FORM_FILE = "forms/LoginForm";
String EMAIL_USER_NAME_PAGE_NAME = "emailun";
String EMAIL_USER_NAME_FORM_NAME = "emailUserNameForm";
String EMAIL_USER_NAME_FORM_FILE = "forms/EmailUserNameForm";
String EMAIL_PASSWORD_PAGE_NAME = "emailpw";
String EMAIL_PASSWORD_FORM_NAME = "emailPasswordForm";
String EMAIL_PASSWORD_FORM_FILE = "forms/EmailPasswordForm";
String RESET_SESSION_PAGE_NAME = "reset";
String LOGOUT_PAGE_NAME = "logout";
String SET_ENGLISH_LANGUAGE_PAGE_NAME = "langen";
String SET_GERMAN_LANGUAGE_PAGE_NAME = "langde";
String SET_SPANISH_LANGUAGE_PAGE_NAME = "langes";
String SET_JAPANESE_LANGUAGE_PAGE_NAME = "langja";
String SET_EXTRA_SMALL_PHOTO_SIZE_PAGE_NAME = "psizexs";
String SET_SMALL_PHOTO_SIZE_PAGE_NAME = "psizes";
String SET_MEDIUM_PHOTO_SIZE_PAGE_NAME = "psizem";
String SET_LARGE_PHOTO_SIZE_PAGE_NAME = "psizel";
String SET_EXTRA_LARGE_PHOTO_SIZE_PAGE_NAME = "psizexl";
String SHOW_USER_HOME_PAGE_NAME = "home";
String SHOW_USER_HOME_PAGE_FILE = "pages/ShowUserHomePage";
String SHOW_USER_PROFILE_FORM_NAME = "showUserProfileForm";
String SHOW_USER_PROFILE_FORM_FILE = "forms/ShowUserProfileForm";
String SHOW_USER_PHOTO_FORM_NAME = "showUserPhotoForm";
String SHOW_USER_PHOTO_FORM_FILE = "forms/ShowUserPhotoForm";
String EDIT_USER_PROFILE_PAGE_NAME = "profile";
String EDIT_USER_PROFILE_FORM_NAME = "editUserProfileForm";
String EDIT_USER_PROFILE_FORM_FILE = "forms/EditUserProfileForm";
String CHANGE_PASSWORD_PAGE_NAME = "password";
String CHANGE_PASSWORD_FORM_NAME = "changePasswordForm";
String CHANGE_PASSWORD_FORM_FILE = "forms/ChangePasswordForm";
String UPLOAD_PHOTO_PAGE_NAME = "upload";
String UPLOAD_PHOTO_FORM_NAME = "uploadPhotoForm";
String UPLOAD_PHOTO_FORM_FILE = "forms/UploadPhotoForm";
String EDIT_USER_PHOTO_PAGE_NAME = "photo";
String EDIT_USER_PHOTO_FORM_NAME = "editUserPhotoForm";
String EDIT_USER_PHOTO_FORM_FILE = "forms/EditUserPhotoForm";
String SHOW_PHOTO_CASES_PAGE_NAME = "cases";
String SHOW_PHOTO_CASES_PAGE_FILE = "pages/ShowPhotoCasesPage";
String EDIT_PHOTO_CASE_FORM_NAME = "editPhotoCaseForm";
String EDIT_PHOTO_CASE_FORM_FILE = "forms/EditPhotoCaseForm";
String SHOW_ADMIN_PAGE_NAME = "admin";
String SHOW_ADMIN_PAGE_FILE = "pages/ShowAdminPage";
String SHOW_ADMIN_MENU_FORM_NAME = "showAdminMenuForm";
String ADMIN_USER_PROFILE_FORM_NAME = "adminUserProfileForm";
String ADMIN_USER_PROFILE_FORM_FILE = "forms/AdminUserProfileForm";
String ADMIN_USER_PHOTO_FORM_NAME = "adminUserPhotoForm";
String ADMIN_USER_PHOTO_FORM_FILE = "forms/AdminUserPhotoForm";
}
|
src/main/java/org/wahlzeit/handlers/PartUtil.java
|
/*
* Copyright (c) 2006-2009 by Dirk Riehle, http://dirkriehle.com
*
* This file is part of the Wahlzeit photo rating application.
*
* 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. If not, see
* <http://www.gnu.org/licenses/>.
*/
package org.wahlzeit.handlers;
/**
* @author dirkriehle
*/
public interface PartUtil {
public static final String DEFAULT_PAGE_NAME = "index";
public static final String NULL_INFO_NAME = "nullInfo";
public static final String NULL_INFO_FILE = "infos/NullInfo";
public static final String NULL_FORM_NAME = "nullForm";
public static final String NULL_FORM_FILE = "forms/NullForm";
public static final String SHOW_INFO_PAGE_FILE = "pages/ShowInfoPage";
public static final String SHOW_PART_PAGE_FILE = "pages/ShowPartPage";
public static final String SHOW_NOTE_PAGE_NAME = "note";
public static final String SHOW_NOTE_PAGE_FILE = "pages/ShowNotePage";
public static final String SHOW_PHOTO_PAGE_NAME = "index";
public static final String SHOW_PHOTO_PAGE_FILE = "pages/ShowPhotoPage";
public static final String CAPTION_INFO_FILE = "infos/CaptionInfo";
public static final String BLURP_INFO_FILE = "infos/BlurpInfo";
public static final String PHOTO_INFO_FILE = "infos/PhotoInfo";
public static final String LINKS_INFO_FILE = "infos/LinksInfo";
public static final String BANNER_INFO_FILE = "infos/BannerInfo";
public static final String FILTER_PHOTOS_FORM_NAME = "filterPhotosForm";
public static final String FILTER_PHOTOS_FORM_FILE = "forms/FilterPhotosForm";
public static final String PRAISE_PHOTO_FORM_NAME = "praisePhotoForm";
public static final String PRAISE_PHOTO_FORM_FILE = "forms/PraisePhotoForm";
public static final String ENGAGE_GUEST_FORM_NAME = "engageGuestForm";
public static final String ENGAGE_GUEST_FORM_FILE = "forms/EngageGuestForm";
public static final String ABOUT_PAGE_NAME = "about";
public static final String ABOUT_INFO_FILE = "infos/AboutInfo";
public static final String CONTACT_PAGE_NAME = "contact";
public static final String CONTACT_INFO_FILE = "infos/ContactInfo";
public static final String IMPRINT_PAGE_NAME = "imprint";
public static final String IMPRINT_INFO_FILE = "infos/ImprintInfo";
public static final String TERMS_PAGE_NAME = "terms";
public static final String TERMS_INFO_FILE = "infos/TermsInfo";
public static final String HIDDEN_INFO_FILE = "infos/HiddenInfo";
public static final String DONE_INFO_FILE = "infos/DoneInfo";
public static final String FILTER_PHOTOS_PAGE_NAME = "filter";
public static final String FLAG_PHOTO_PAGE_NAME = "flag";
public static final String FLAG_PHOTO_FORM_NAME = "flagPhotoForm";
public static final String FLAG_PHOTO_FORM_FILE = "forms/FlagPhotoForm";
public static final String TELL_FRIEND_PAGE_NAME = "tell";
public static final String TELL_FRIEND_FORM_NAME = "tellFriendForm";
public static final String TELL_FRIEND_FORM_FILE = "forms/TellFriendForm";
public static final String SEND_EMAIL_PAGE_NAME = "connect";
public static final String SEND_EMAIL_FORM_NAME = "sendEmailForm";
public static final String SEND_EMAIL_FORM_FILE = "forms/SendEmailForm";
public static final String SET_OPTIONS_PAGE_NAME = "options";
public static final String SET_OPTIONS_FORM_NAME = "setOptionsForm";
public static final String SET_OPTIONS_FORM_FILE = "forms/SetOptionsForm";
public static final String SIGNUP_PAGE_NAME = "signup";
public static final String SIGNUP_FORM_NAME = "signupForm";
public static final String SIGNUP_FORM_FILE = "forms/SignupForm";
public static final String CONFIRM_ACCOUNT_PAGE_NAME = "confirm";
public static final String LOGIN_PAGE_NAME = "login";
public static final String LOGIN_FORM_NAME = "loginForm";
public static final String LOGIN_FORM_FILE = "forms/LoginForm";
public static final String EMAIL_USER_NAME_PAGE_NAME = "emailun";
public static final String EMAIL_USER_NAME_FORM_NAME = "emailUserNameForm";
public static final String EMAIL_USER_NAME_FORM_FILE = "forms/EmailUserNameForm";
public static final String EMAIL_PASSWORD_PAGE_NAME = "emailpw";
public static final String EMAIL_PASSWORD_FORM_NAME = "emailPasswordForm";
public static final String EMAIL_PASSWORD_FORM_FILE = "forms/EmailPasswordForm";
public static final String RESET_SESSION_PAGE_NAME = "reset";
public static final String LOGOUT_PAGE_NAME = "logout";
public static final String SET_ENGLISH_LANGUAGE_PAGE_NAME = "langen";
public static final String SET_GERMAN_LANGUAGE_PAGE_NAME = "langde";
public static final String SET_SPANISH_LANGUAGE_PAGE_NAME = "langes";
public static final String SET_JAPANESE_LANGUAGE_PAGE_NAME = "langja";
public static final String SET_EXTRA_SMALL_PHOTO_SIZE_PAGE_NAME = "psizexs";
public static final String SET_SMALL_PHOTO_SIZE_PAGE_NAME = "psizes";
public static final String SET_MEDIUM_PHOTO_SIZE_PAGE_NAME = "psizem";
public static final String SET_LARGE_PHOTO_SIZE_PAGE_NAME = "psizel";
public static final String SET_EXTRA_LARGE_PHOTO_SIZE_PAGE_NAME = "psizexl";
public static final String SHOW_USER_HOME_PAGE_NAME = "home";
public static final String SHOW_USER_HOME_PAGE_FILE = "pages/ShowUserHomePage";
public static final String SHOW_USER_PROFILE_FORM_NAME = "showUserProfileForm";
public static final String SHOW_USER_PROFILE_FORM_FILE = "forms/ShowUserProfileForm";
public static final String SHOW_USER_PHOTO_FORM_NAME = "showUserPhotoForm";
public static final String SHOW_USER_PHOTO_FORM_FILE = "forms/ShowUserPhotoForm";
public static final String EDIT_USER_PROFILE_PAGE_NAME = "profile";
public static final String EDIT_USER_PROFILE_FORM_NAME = "editUserProfileForm";
public static final String EDIT_USER_PROFILE_FORM_FILE = "forms/EditUserProfileForm";
public static final String CHANGE_PASSWORD_PAGE_NAME = "password";
public static final String CHANGE_PASSWORD_FORM_NAME = "changePasswordForm";
public static final String CHANGE_PASSWORD_FORM_FILE = "forms/ChangePasswordForm";
public static final String UPLOAD_PHOTO_PAGE_NAME = "upload";
public static final String UPLOAD_PHOTO_FORM_NAME = "uploadPhotoForm";
public static final String UPLOAD_PHOTO_FORM_FILE = "forms/UploadPhotoForm";
public static final String EDIT_USER_PHOTO_PAGE_NAME = "photo";
public static final String EDIT_USER_PHOTO_FORM_NAME = "editUserPhotoForm";
public static final String EDIT_USER_PHOTO_FORM_FILE = "forms/EditUserPhotoForm";
public static final String SHOW_PHOTO_CASES_PAGE_NAME = "cases";
public static final String SHOW_PHOTO_CASES_PAGE_FILE = "pages/ShowPhotoCasesPage";
public static final String EDIT_PHOTO_CASE_FORM_NAME = "editPhotoCaseForm";
public static final String EDIT_PHOTO_CASE_FORM_FILE = "forms/EditPhotoCaseForm";
public static final String SHOW_ADMIN_PAGE_NAME = "admin";
public static final String SHOW_ADMIN_PAGE_FILE = "pages/ShowAdminPage";
public static final String SHOW_ADMIN_MENU_FORM_NAME = "showAdminMenuForm";
public static final String ADMIN_USER_PROFILE_FORM_NAME = "adminUserProfileForm";
public static final String ADMIN_USER_PROFILE_FORM_FILE = "forms/AdminUserProfileForm";
public static final String ADMIN_USER_PHOTO_FORM_NAME = "adminUserPhotoForm";
public static final String ADMIN_USER_PHOTO_FORM_FILE = "forms/AdminUserPhotoForm";
}
|
Removed public static final from all constants in PartUtil because a String member in an interface is by default public static final
|
src/main/java/org/wahlzeit/handlers/PartUtil.java
|
Removed public static final from all constants in PartUtil because a String member in an interface is by default public static final
|
<ide><path>rc/main/java/org/wahlzeit/handlers/PartUtil.java
<ide> */
<ide> public interface PartUtil {
<ide>
<del> public static final String DEFAULT_PAGE_NAME = "index";
<add> String DEFAULT_PAGE_NAME = "index";
<ide>
<del> public static final String NULL_INFO_NAME = "nullInfo";
<del> public static final String NULL_INFO_FILE = "infos/NullInfo";
<del> public static final String NULL_FORM_NAME = "nullForm";
<del> public static final String NULL_FORM_FILE = "forms/NullForm";
<add> String NULL_INFO_NAME = "nullInfo";
<add> String NULL_INFO_FILE = "infos/NullInfo";
<add> String NULL_FORM_NAME = "nullForm";
<add> String NULL_FORM_FILE = "forms/NullForm";
<ide>
<del> public static final String SHOW_INFO_PAGE_FILE = "pages/ShowInfoPage";
<del> public static final String SHOW_PART_PAGE_FILE = "pages/ShowPartPage";
<add> String SHOW_INFO_PAGE_FILE = "pages/ShowInfoPage";
<add> String SHOW_PART_PAGE_FILE = "pages/ShowPartPage";
<ide>
<del> public static final String SHOW_NOTE_PAGE_NAME = "note";
<del> public static final String SHOW_NOTE_PAGE_FILE = "pages/ShowNotePage";
<add> String SHOW_NOTE_PAGE_NAME = "note";
<add> String SHOW_NOTE_PAGE_FILE = "pages/ShowNotePage";
<ide>
<del> public static final String SHOW_PHOTO_PAGE_NAME = "index";
<del> public static final String SHOW_PHOTO_PAGE_FILE = "pages/ShowPhotoPage";
<del> public static final String CAPTION_INFO_FILE = "infos/CaptionInfo";
<del> public static final String BLURP_INFO_FILE = "infos/BlurpInfo";
<del> public static final String PHOTO_INFO_FILE = "infos/PhotoInfo";
<del> public static final String LINKS_INFO_FILE = "infos/LinksInfo";
<del> public static final String BANNER_INFO_FILE = "infos/BannerInfo";
<del> public static final String FILTER_PHOTOS_FORM_NAME = "filterPhotosForm";
<del> public static final String FILTER_PHOTOS_FORM_FILE = "forms/FilterPhotosForm";
<del> public static final String PRAISE_PHOTO_FORM_NAME = "praisePhotoForm";
<del> public static final String PRAISE_PHOTO_FORM_FILE = "forms/PraisePhotoForm";
<del> public static final String ENGAGE_GUEST_FORM_NAME = "engageGuestForm";
<del> public static final String ENGAGE_GUEST_FORM_FILE = "forms/EngageGuestForm";
<add> String SHOW_PHOTO_PAGE_NAME = "index";
<add> String SHOW_PHOTO_PAGE_FILE = "pages/ShowPhotoPage";
<add> String CAPTION_INFO_FILE = "infos/CaptionInfo";
<add> String BLURP_INFO_FILE = "infos/BlurpInfo";
<add> String PHOTO_INFO_FILE = "infos/PhotoInfo";
<add> String LINKS_INFO_FILE = "infos/LinksInfo";
<add> String BANNER_INFO_FILE = "infos/BannerInfo";
<add> String FILTER_PHOTOS_FORM_NAME = "filterPhotosForm";
<add> String FILTER_PHOTOS_FORM_FILE = "forms/FilterPhotosForm";
<add> String PRAISE_PHOTO_FORM_NAME = "praisePhotoForm";
<add> String PRAISE_PHOTO_FORM_FILE = "forms/PraisePhotoForm";
<add> String ENGAGE_GUEST_FORM_NAME = "engageGuestForm";
<add> String ENGAGE_GUEST_FORM_FILE = "forms/EngageGuestForm";
<ide>
<del> public static final String ABOUT_PAGE_NAME = "about";
<del> public static final String ABOUT_INFO_FILE = "infos/AboutInfo";
<add> String ABOUT_PAGE_NAME = "about";
<add> String ABOUT_INFO_FILE = "infos/AboutInfo";
<ide>
<del> public static final String CONTACT_PAGE_NAME = "contact";
<del> public static final String CONTACT_INFO_FILE = "infos/ContactInfo";
<add> String CONTACT_PAGE_NAME = "contact";
<add> String CONTACT_INFO_FILE = "infos/ContactInfo";
<ide>
<del> public static final String IMPRINT_PAGE_NAME = "imprint";
<del> public static final String IMPRINT_INFO_FILE = "infos/ImprintInfo";
<add> String IMPRINT_PAGE_NAME = "imprint";
<add> String IMPRINT_INFO_FILE = "infos/ImprintInfo";
<ide>
<del> public static final String TERMS_PAGE_NAME = "terms";
<del> public static final String TERMS_INFO_FILE = "infos/TermsInfo";
<add> String TERMS_PAGE_NAME = "terms";
<add> String TERMS_INFO_FILE = "infos/TermsInfo";
<ide>
<del> public static final String HIDDEN_INFO_FILE = "infos/HiddenInfo";
<del> public static final String DONE_INFO_FILE = "infos/DoneInfo";
<add> String HIDDEN_INFO_FILE = "infos/HiddenInfo";
<add> String DONE_INFO_FILE = "infos/DoneInfo";
<ide>
<del> public static final String FILTER_PHOTOS_PAGE_NAME = "filter";
<add> String FILTER_PHOTOS_PAGE_NAME = "filter";
<ide>
<del> public static final String FLAG_PHOTO_PAGE_NAME = "flag";
<del> public static final String FLAG_PHOTO_FORM_NAME = "flagPhotoForm";
<del> public static final String FLAG_PHOTO_FORM_FILE = "forms/FlagPhotoForm";
<add> String FLAG_PHOTO_PAGE_NAME = "flag";
<add> String FLAG_PHOTO_FORM_NAME = "flagPhotoForm";
<add> String FLAG_PHOTO_FORM_FILE = "forms/FlagPhotoForm";
<ide>
<del> public static final String TELL_FRIEND_PAGE_NAME = "tell";
<del> public static final String TELL_FRIEND_FORM_NAME = "tellFriendForm";
<del> public static final String TELL_FRIEND_FORM_FILE = "forms/TellFriendForm";
<add> String TELL_FRIEND_PAGE_NAME = "tell";
<add> String TELL_FRIEND_FORM_NAME = "tellFriendForm";
<add> String TELL_FRIEND_FORM_FILE = "forms/TellFriendForm";
<ide>
<del> public static final String SEND_EMAIL_PAGE_NAME = "connect";
<del> public static final String SEND_EMAIL_FORM_NAME = "sendEmailForm";
<del> public static final String SEND_EMAIL_FORM_FILE = "forms/SendEmailForm";
<add> String SEND_EMAIL_PAGE_NAME = "connect";
<add> String SEND_EMAIL_FORM_NAME = "sendEmailForm";
<add> String SEND_EMAIL_FORM_FILE = "forms/SendEmailForm";
<ide>
<del> public static final String SET_OPTIONS_PAGE_NAME = "options";
<del> public static final String SET_OPTIONS_FORM_NAME = "setOptionsForm";
<del> public static final String SET_OPTIONS_FORM_FILE = "forms/SetOptionsForm";
<add> String SET_OPTIONS_PAGE_NAME = "options";
<add> String SET_OPTIONS_FORM_NAME = "setOptionsForm";
<add> String SET_OPTIONS_FORM_FILE = "forms/SetOptionsForm";
<ide>
<del> public static final String SIGNUP_PAGE_NAME = "signup";
<del> public static final String SIGNUP_FORM_NAME = "signupForm";
<del> public static final String SIGNUP_FORM_FILE = "forms/SignupForm";
<add> String SIGNUP_PAGE_NAME = "signup";
<add> String SIGNUP_FORM_NAME = "signupForm";
<add> String SIGNUP_FORM_FILE = "forms/SignupForm";
<ide>
<del> public static final String CONFIRM_ACCOUNT_PAGE_NAME = "confirm";
<add> String CONFIRM_ACCOUNT_PAGE_NAME = "confirm";
<ide>
<del> public static final String LOGIN_PAGE_NAME = "login";
<del> public static final String LOGIN_FORM_NAME = "loginForm";
<del> public static final String LOGIN_FORM_FILE = "forms/LoginForm";
<add> String LOGIN_PAGE_NAME = "login";
<add> String LOGIN_FORM_NAME = "loginForm";
<add> String LOGIN_FORM_FILE = "forms/LoginForm";
<ide>
<del> public static final String EMAIL_USER_NAME_PAGE_NAME = "emailun";
<del> public static final String EMAIL_USER_NAME_FORM_NAME = "emailUserNameForm";
<del> public static final String EMAIL_USER_NAME_FORM_FILE = "forms/EmailUserNameForm";
<add> String EMAIL_USER_NAME_PAGE_NAME = "emailun";
<add> String EMAIL_USER_NAME_FORM_NAME = "emailUserNameForm";
<add> String EMAIL_USER_NAME_FORM_FILE = "forms/EmailUserNameForm";
<ide>
<del> public static final String EMAIL_PASSWORD_PAGE_NAME = "emailpw";
<del> public static final String EMAIL_PASSWORD_FORM_NAME = "emailPasswordForm";
<del> public static final String EMAIL_PASSWORD_FORM_FILE = "forms/EmailPasswordForm";
<add> String EMAIL_PASSWORD_PAGE_NAME = "emailpw";
<add> String EMAIL_PASSWORD_FORM_NAME = "emailPasswordForm";
<add> String EMAIL_PASSWORD_FORM_FILE = "forms/EmailPasswordForm";
<ide>
<del> public static final String RESET_SESSION_PAGE_NAME = "reset";
<add> String RESET_SESSION_PAGE_NAME = "reset";
<ide>
<del> public static final String LOGOUT_PAGE_NAME = "logout";
<add> String LOGOUT_PAGE_NAME = "logout";
<ide>
<del> public static final String SET_ENGLISH_LANGUAGE_PAGE_NAME = "langen";
<del> public static final String SET_GERMAN_LANGUAGE_PAGE_NAME = "langde";
<del> public static final String SET_SPANISH_LANGUAGE_PAGE_NAME = "langes";
<del> public static final String SET_JAPANESE_LANGUAGE_PAGE_NAME = "langja";
<add> String SET_ENGLISH_LANGUAGE_PAGE_NAME = "langen";
<add> String SET_GERMAN_LANGUAGE_PAGE_NAME = "langde";
<add> String SET_SPANISH_LANGUAGE_PAGE_NAME = "langes";
<add> String SET_JAPANESE_LANGUAGE_PAGE_NAME = "langja";
<ide>
<del> public static final String SET_EXTRA_SMALL_PHOTO_SIZE_PAGE_NAME = "psizexs";
<del> public static final String SET_SMALL_PHOTO_SIZE_PAGE_NAME = "psizes";
<del> public static final String SET_MEDIUM_PHOTO_SIZE_PAGE_NAME = "psizem";
<del> public static final String SET_LARGE_PHOTO_SIZE_PAGE_NAME = "psizel";
<del> public static final String SET_EXTRA_LARGE_PHOTO_SIZE_PAGE_NAME = "psizexl";
<add> String SET_EXTRA_SMALL_PHOTO_SIZE_PAGE_NAME = "psizexs";
<add> String SET_SMALL_PHOTO_SIZE_PAGE_NAME = "psizes";
<add> String SET_MEDIUM_PHOTO_SIZE_PAGE_NAME = "psizem";
<add> String SET_LARGE_PHOTO_SIZE_PAGE_NAME = "psizel";
<add> String SET_EXTRA_LARGE_PHOTO_SIZE_PAGE_NAME = "psizexl";
<ide>
<del> public static final String SHOW_USER_HOME_PAGE_NAME = "home";
<del> public static final String SHOW_USER_HOME_PAGE_FILE = "pages/ShowUserHomePage";
<del> public static final String SHOW_USER_PROFILE_FORM_NAME = "showUserProfileForm";
<del> public static final String SHOW_USER_PROFILE_FORM_FILE = "forms/ShowUserProfileForm";
<del> public static final String SHOW_USER_PHOTO_FORM_NAME = "showUserPhotoForm";
<del> public static final String SHOW_USER_PHOTO_FORM_FILE = "forms/ShowUserPhotoForm";
<add> String SHOW_USER_HOME_PAGE_NAME = "home";
<add> String SHOW_USER_HOME_PAGE_FILE = "pages/ShowUserHomePage";
<add> String SHOW_USER_PROFILE_FORM_NAME = "showUserProfileForm";
<add> String SHOW_USER_PROFILE_FORM_FILE = "forms/ShowUserProfileForm";
<add> String SHOW_USER_PHOTO_FORM_NAME = "showUserPhotoForm";
<add> String SHOW_USER_PHOTO_FORM_FILE = "forms/ShowUserPhotoForm";
<ide>
<del> public static final String EDIT_USER_PROFILE_PAGE_NAME = "profile";
<del> public static final String EDIT_USER_PROFILE_FORM_NAME = "editUserProfileForm";
<del> public static final String EDIT_USER_PROFILE_FORM_FILE = "forms/EditUserProfileForm";
<add> String EDIT_USER_PROFILE_PAGE_NAME = "profile";
<add> String EDIT_USER_PROFILE_FORM_NAME = "editUserProfileForm";
<add> String EDIT_USER_PROFILE_FORM_FILE = "forms/EditUserProfileForm";
<ide>
<del> public static final String CHANGE_PASSWORD_PAGE_NAME = "password";
<del> public static final String CHANGE_PASSWORD_FORM_NAME = "changePasswordForm";
<del> public static final String CHANGE_PASSWORD_FORM_FILE = "forms/ChangePasswordForm";
<add> String CHANGE_PASSWORD_PAGE_NAME = "password";
<add> String CHANGE_PASSWORD_FORM_NAME = "changePasswordForm";
<add> String CHANGE_PASSWORD_FORM_FILE = "forms/ChangePasswordForm";
<ide>
<del> public static final String UPLOAD_PHOTO_PAGE_NAME = "upload";
<del> public static final String UPLOAD_PHOTO_FORM_NAME = "uploadPhotoForm";
<del> public static final String UPLOAD_PHOTO_FORM_FILE = "forms/UploadPhotoForm";
<add> String UPLOAD_PHOTO_PAGE_NAME = "upload";
<add> String UPLOAD_PHOTO_FORM_NAME = "uploadPhotoForm";
<add> String UPLOAD_PHOTO_FORM_FILE = "forms/UploadPhotoForm";
<ide>
<del> public static final String EDIT_USER_PHOTO_PAGE_NAME = "photo";
<del> public static final String EDIT_USER_PHOTO_FORM_NAME = "editUserPhotoForm";
<del> public static final String EDIT_USER_PHOTO_FORM_FILE = "forms/EditUserPhotoForm";
<add> String EDIT_USER_PHOTO_PAGE_NAME = "photo";
<add> String EDIT_USER_PHOTO_FORM_NAME = "editUserPhotoForm";
<add> String EDIT_USER_PHOTO_FORM_FILE = "forms/EditUserPhotoForm";
<ide>
<del> public static final String SHOW_PHOTO_CASES_PAGE_NAME = "cases";
<del> public static final String SHOW_PHOTO_CASES_PAGE_FILE = "pages/ShowPhotoCasesPage";
<del> public static final String EDIT_PHOTO_CASE_FORM_NAME = "editPhotoCaseForm";
<del> public static final String EDIT_PHOTO_CASE_FORM_FILE = "forms/EditPhotoCaseForm";
<add> String SHOW_PHOTO_CASES_PAGE_NAME = "cases";
<add> String SHOW_PHOTO_CASES_PAGE_FILE = "pages/ShowPhotoCasesPage";
<add> String EDIT_PHOTO_CASE_FORM_NAME = "editPhotoCaseForm";
<add> String EDIT_PHOTO_CASE_FORM_FILE = "forms/EditPhotoCaseForm";
<ide>
<del> public static final String SHOW_ADMIN_PAGE_NAME = "admin";
<del> public static final String SHOW_ADMIN_PAGE_FILE = "pages/ShowAdminPage";
<del> public static final String SHOW_ADMIN_MENU_FORM_NAME = "showAdminMenuForm";
<del> public static final String ADMIN_USER_PROFILE_FORM_NAME = "adminUserProfileForm";
<del> public static final String ADMIN_USER_PROFILE_FORM_FILE = "forms/AdminUserProfileForm";
<del> public static final String ADMIN_USER_PHOTO_FORM_NAME = "adminUserPhotoForm";
<del> public static final String ADMIN_USER_PHOTO_FORM_FILE = "forms/AdminUserPhotoForm";
<add> String SHOW_ADMIN_PAGE_NAME = "admin";
<add> String SHOW_ADMIN_PAGE_FILE = "pages/ShowAdminPage";
<add> String SHOW_ADMIN_MENU_FORM_NAME = "showAdminMenuForm";
<add> String ADMIN_USER_PROFILE_FORM_NAME = "adminUserProfileForm";
<add> String ADMIN_USER_PROFILE_FORM_FILE = "forms/AdminUserProfileForm";
<add> String ADMIN_USER_PHOTO_FORM_NAME = "adminUserPhotoForm";
<add> String ADMIN_USER_PHOTO_FORM_FILE = "forms/AdminUserPhotoForm";
<ide>
<ide> }
|
|
Java
|
lgpl-2.1
|
bd2591befbdef8b0c21b2a3774752dd290e2b4bb
| 0 |
julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine
|
package org.intermine.web.logic.profile;
/*
* Copyright (C) 2002-2007 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import java.io.StringReader;
import javax.servlet.ServletContext;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.collections.keyvalue.MultiKey;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.intermine.metadata.ClassDescriptor;
import org.intermine.metadata.FieldDescriptor;
import org.intermine.metadata.Model;
import org.intermine.model.InterMineObject;
import org.intermine.model.userprofile.SavedBag;
import org.intermine.model.userprofile.SavedQuery;
import org.intermine.model.userprofile.SavedTemplateQuery;
import org.intermine.model.userprofile.Tag;
import org.intermine.model.userprofile.TemplateSummary;
import org.intermine.model.userprofile.UserProfile;
import org.intermine.objectstore.ObjectStore;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.objectstore.ObjectStoreWriter;
import org.intermine.objectstore.proxy.ProxyReference;
import org.intermine.objectstore.query.ConstraintOp;
import org.intermine.objectstore.query.ConstraintSet;
import org.intermine.objectstore.query.ContainsConstraint;
import org.intermine.objectstore.query.Query;
import org.intermine.objectstore.query.QueryClass;
import org.intermine.objectstore.query.QueryField;
import org.intermine.objectstore.query.QueryObjectReference;
import org.intermine.objectstore.query.QueryValue;
import org.intermine.objectstore.query.Results;
import org.intermine.objectstore.query.SimpleConstraint;
import org.intermine.objectstore.query.SingletonResults;
import org.intermine.util.CacheMap;
import org.intermine.util.DynamicUtil;
import org.intermine.web.logic.bag.InterMineBag;
import org.intermine.web.logic.query.PathQuery;
import org.intermine.web.logic.query.PathQueryBinding;
import org.intermine.web.logic.query.SavedQueryBinding;
import org.intermine.web.logic.search.WebSearchable;
import org.intermine.web.logic.tagging.TagTypes;
import org.intermine.web.logic.template.TemplateQuery;
import org.intermine.web.logic.template.TemplateQueryBinding;
import net.sourceforge.iharder.Base64;
/**
* Class to manage and persist user profile data such as saved bags
* @author Mark Woodbridge
*/
public class ProfileManager
{
private static final Logger LOG = Logger.getLogger(ProfileManager.class);
protected ObjectStore os;
protected ObjectStoreWriter osw;
protected TemplateQueryBinding templateBinding = new TemplateQueryBinding();
protected CacheMap profileCache = new CacheMap();
private Map<String, TagChecker> tagCheckers = null;
private HashMap<MultiKey, List<Tag>> tagCache = null;
private final ServletContext servletContext;
/**
* Construct a ProfileManager for the webapp
* @param os the ObjectStore to which the webapp is providing an interface
* @param userProfileOS the object store that hold user profile information
* @param servletContext global ServletContext object
*/
public ProfileManager(ObjectStore os, ObjectStoreWriter userProfileOS,
ServletContext servletContext) {
this.os = os;
this.servletContext = servletContext;
tagCheckers = makeTagCheckers(os.getModel());
this.osw = userProfileOS;
}
/**
* Return the ObjectStore that was passed to the constructor.
* @return the ObjectStore from the constructor
*/
public ObjectStore getObjectStore() {
return os;
}
/**
* Return the userprofile ObjectStoreWriter that was passed to the constructor.
* @return the userprofile ObjectStoreWriter from the constructor
*/
public ObjectStoreWriter getUserProfileObjectStore() {
return osw;
}
/**
* Close this ProfileManager
*
* @throws ObjectStoreException in exceptional circumstances
*/
public void close() throws ObjectStoreException {
osw.close();
}
/**
* Check whether a user already has a Profile
* @param username the username
* @return true if a profile exists
*/
public boolean hasProfile(String username) {
return getUserProfile(username) != null;
}
/**
* Validate a user's password
* A check should be made prior to this call to ensure a Profile exists
* @param username the username
* @param password the password
* @return true if password is valid
*/
public boolean validPassword(String username, String password) {
return getUserProfile(username).getPassword().equals(password);
}
/**
* Change a user's password
* A check should be made prior to this call to ensure a Profile exists
* @param username the username
* @param password the password
*/
public void setPassword(String username, String password) {
UserProfile userProfile = getUserProfile(username);
userProfile.setPassword(password);
try {
osw.store(userProfile);
} catch (ObjectStoreException e) {
throw new RuntimeException(e);
}
}
/**
* Get a user's password
* A check should be made prior to this call to ensure a Profile exists
* @param username the username
* @return password the password
*/
public String getPassword(String username) {
UserProfile userProfile = getUserProfile(username);
return userProfile.getPassword();
}
/**
* Get a user's Profile using a username and password.
* @param username the username
* @param password the password
* @return the Profile, or null if one doesn't exist
*/
public Profile getProfile(String username, String password) {
if (hasProfile(username) && validPassword(username, password)) {
return getProfile(username);
} else {
return null;
}
}
/**
* Get a user's Profile using a username
* @param username the username
* @return the Profile, or null if one doesn't exist
*/
public synchronized Profile getProfile(String username) {
Profile profile = (Profile) profileCache.get(username);
if (profile != null) {
return profile;
}
UserProfile userProfile = getUserProfile(username);
if (userProfile == null) {
return null;
}
Map<String, InterMineBag> savedBags = new HashMap<String, InterMineBag>();
Query q = new Query();
QueryClass qc = new QueryClass(SavedBag.class);
q.addFrom(qc);
q.addToSelect(new QueryField(qc, "id"));
q.addToSelect(qc); // This loads the objects into the cache
q.setConstraint(new ContainsConstraint(new QueryObjectReference(qc, "userProfile"),
ConstraintOp.CONTAINS, new ProxyReference(null, userProfile.getId(),
UserProfile.class)));
Results bags;
try {
bags = osw.execute(q);
bags.setNoOptimise();
bags.setNoExplain();
for (Iterator i = bags.iterator(); i.hasNext();) {
List row = (List) i.next();
Integer bagId = (Integer) row.get(0);
InterMineBag bag = new InterMineBag(os, bagId, osw);
savedBags.put(bag.getName(), bag);
}
} catch (ObjectStoreException e) {
throw new RuntimeException(e);
}
Map<String, org.intermine.web.logic.query.SavedQuery> savedQueries =
new HashMap<String, org.intermine.web.logic.query.SavedQuery>();
for (Iterator i = userProfile.getSavedQuerys().iterator(); i.hasNext();) {
SavedQuery query = (SavedQuery) i.next();
try {
Map queries =
SavedQueryBinding.unmarshal(new StringReader(query.getQuery()), savedBags,
servletContext);
if (queries.size() == 0) {
queries =
PathQueryBinding.unmarshal(new StringReader(query.getQuery()), savedBags,
servletContext);
if (queries.size() == 1) {
Map.Entry entry = (Map.Entry) queries.entrySet().iterator().next();
String name = (String) entry.getKey();
savedQueries.put(name,
new org.intermine.web.logic.query.SavedQuery(name, null,
(PathQuery) entry.getValue()));
}
} else {
savedQueries.putAll(queries);
}
} catch (Exception err) {
// Ignore rows that don't unmarshal (they probably reference
// another model.
LOG.warn("Failed to unmarshal saved query: " + query.getQuery());
}
}
Map<String, TemplateQuery> savedTemplates = new HashMap<String, TemplateQuery>();
for (Iterator i = userProfile.getSavedTemplateQuerys().iterator(); i.hasNext();) {
SavedTemplateQuery template = (SavedTemplateQuery) i.next();
try {
StringReader sr = new StringReader(template.getTemplateQuery());
Map templateMap = templateBinding.unmarshal(sr, savedBags, servletContext);
String templateName = (String) templateMap.keySet().iterator().next();
TemplateQuery templateQuery = (TemplateQuery) templateMap.get(templateName);
templateQuery.setSavedTemplateQuery(template);
savedTemplates.put(templateName, templateQuery);
Iterator summaryIter = template.getSummaries().iterator();
if (summaryIter.hasNext()) {
TemplateSummary summary = (TemplateSummary) summaryIter.next();
templateQuery.setPossibleValues((HashMap) Base64.decodeToObject(summary
.getSummary()));
}
} catch (Exception err) {
// Ignore rows that don't unmarshal (they probably reference
// another model.
LOG.warn("Failed to unmarshal saved template query: "
+ template.getTemplateQuery(), err);
}
}
convertTemplateKeywordsToTags(savedTemplates, username);
profile = new Profile(this, username, userProfile.getId(), userProfile.getPassword(),
savedQueries, savedBags, savedTemplates);
profileCache.put(username, profile);
return profile;
}
/**
* Create 'aspect:xxx' tags for each keyword of each template.
* Public so that LoadDefaultTemplates task can call in.
* @param savedTemplates Map from template name to TemplateQuery
* @param username username under which to store tags
*/
public void convertTemplateKeywordsToTags(Map<String, TemplateQuery> savedTemplates,
String username) {
for (Iterator<TemplateQuery> iter = savedTemplates.values().iterator(); iter.hasNext(); ) {
TemplateQuery tq = iter.next();
String keywords = tq.getKeywords();
if (StringUtils.isNotEmpty(keywords)) {
String aspects[] = keywords.split(",");
for (int i = 0; i < aspects.length; i++) {
String aspect = aspects[i].trim();
String tag = "aspect:" + aspect;
if (getTags(tag, tq.getName(), TagTypes.TEMPLATE, username).size() == 0) {
addTag(tag, tq.getName(), TagTypes.TEMPLATE, username);
}
}
}
}
}
/**
* Synchronise a user's Profile with the backing store
* @param profile the Profile
*/
public void saveProfile(Profile profile) {
Integer userId = profile.getUserId();
try {
UserProfile userProfile = getUserProfile(userId);
if (userProfile != null) {
for (Iterator i = userProfile.getSavedQuerys().iterator(); i.hasNext();) {
osw.delete((InterMineObject) i.next());
}
for (Iterator i = userProfile.getSavedTemplateQuerys().iterator();
i.hasNext();) {
osw.delete((InterMineObject) i.next());
}
} else {
// Should not happen
throw new RuntimeException("The UserProfile is null");
// userProfile = new UserProfile();
// userProfile.setUsername(profile.getUsername());
// userProfile.setPassword(profile.getPassword());
// userProfile.setId(userId);
}
for (Iterator i = profile.getSavedQueries().entrySet().iterator(); i.hasNext();) {
org.intermine.web.logic.query.SavedQuery query = null;
try {
Map.Entry entry = (Map.Entry) i.next();
query = (org.intermine.web.logic.query.SavedQuery) entry.getValue();
SavedQuery savedQuery = new SavedQuery();
savedQuery.setQuery(SavedQueryBinding.marshal(query));
savedQuery.setUserProfile(userProfile);
osw.store(savedQuery);
} catch (Exception e) {
LOG.error("Failed to marshal and save query: " + query, e);
}
}
for (Iterator i = profile.getSavedTemplates().entrySet().iterator(); i.hasNext();) {
TemplateQuery template = null;
try {
Map.Entry entry = (Map.Entry) i.next();
template = (TemplateQuery) entry.getValue();
SavedTemplateQuery savedTemplate = template.getSavedTemplateQuery();
if (savedTemplate == null) {
savedTemplate = new SavedTemplateQuery();
}
savedTemplate.setTemplateQuery(templateBinding.marshal(template));
savedTemplate.setUserProfile(userProfile);
osw.store(savedTemplate);
template.setSavedTemplateQuery(savedTemplate);
} catch (Exception e) {
LOG.error("Failed to marshal and save template: " + template, e);
}
}
osw.store(userProfile);
profile.setUserId(userProfile.getId());
} catch (ObjectStoreException e) {
throw new RuntimeException(e);
}
}
/**
* Creates a profile in the userprofile database.
*
* @param profile a Profile object
*/
public void createProfile(Profile profile) {
UserProfile userProfile = new UserProfile();
userProfile.setUsername(profile.getUsername());
userProfile.setPassword(profile.getPassword());
//userProfile.setId(userId);
try {
osw.store(userProfile);
profile.setUserId(userProfile.getId());
for (InterMineBag bag : profile.getSavedBags().values()) {
bag.setProfileId(userProfile.getId(), osw);
}
} catch (ObjectStoreException e) {
throw new RuntimeException(e);
}
saveProfile(profile);
}
/**
* Perform a query to retrieve a user's backing UserProfile
* @param username the username
* @return the relevant UserProfile
*/
public UserProfile getUserProfile(String username) {
UserProfile profile = new UserProfile();
profile.setUsername(username);
Set<String> fieldNames = new HashSet<String>();
fieldNames.add("username");
try {
profile = (UserProfile) osw.getObjectByExample(profile, fieldNames);
} catch (ObjectStoreException e) {
throw new RuntimeException("Unable to load user profile", e);
}
return profile;
}
/**
* Perform a query to retrieve a user's backing UserProfile
*
* @param userId the id of the user
* @return the relevant UserProfile
*/
public UserProfile getUserProfile(Integer userId) {
if (userId == null) {
return null;
}
try {
return (UserProfile) osw.getObjectById(userId, UserProfile.class);
} catch (ObjectStoreException e) {
throw new RuntimeException("Unable to load user profile", e);
}
}
/**
* Return a List of the usernames in all of the stored profiles.
* @return the usernames
*/
public List getProfileUserNames() {
Query q = new Query();
QueryClass qcUserProfile = new QueryClass(UserProfile.class);
QueryField qfUserName = new QueryField(qcUserProfile, "username");
q.addFrom(qcUserProfile);
q.addToSelect(qfUserName);
SingletonResults res = osw.executeSingleton(q);
List usernames = new ArrayList();
Iterator resIter = res.iterator();
while (resIter.hasNext()) {
usernames.add(resIter.next());
}
return usernames;
}
/**
* Delete a tag object from the database.
* @param tag Tag object
*/
public synchronized void deleteTag(Tag tag) {
try {
tagCache = null;
getUserProfileObjectStore().delete(tag);
} catch (ObjectStoreException err) {
LOG.error("deleteTag(): " + err);
}
}
/**
* Get Tag by object id.
* @param id intermine object id
* @return Tag
* @throws ObjectStoreException if something goes wrong
*/
public synchronized Tag getTagById(int id) throws ObjectStoreException {
return (Tag) getUserProfileObjectStore().getObjectById(new Integer(id), Tag.class);
}
/**
* Return a List of Tags that match all the arguments. Any null arguments will be treated as
* wildcards.
* @param tagName the tag name - any String
* @param objectIdentifier an object identifier that is appropriate for the given tag type
* (eg. "Department.name" for the "collection" type)
* @param type the tag type (eg. "collection", "reference", "attribute", "bag")
* @param userName the use name this tag is associated with
* @return the matching Tags
*/
public synchronized List<Tag> getTags(String tagName, String objectIdentifier, String type,
String userName) {
Map<MultiKey, List<Tag>> cache = getTagCache();
MultiKey key = makeKey(tagName, objectIdentifier, type, userName);
if (cache.containsKey(key)) {
return cache.get(key);
}
Query q = new Query();
QueryClass qc = new QueryClass(Tag.class);
q.addFrom(qc);
q.addToSelect(qc);
QueryField orderByField = new QueryField(qc, "tagName");
q.addToOrderBy(orderByField);
ConstraintSet cs = new ConstraintSet(ConstraintOp.AND);
if (tagName != null) {
QueryValue qv = new QueryValue(tagName);
QueryField qf = new QueryField(qc, "tagName");
SimpleConstraint c = new SimpleConstraint(qf, ConstraintOp.MATCHES, qv);
cs.addConstraint(c);
}
if (objectIdentifier != null) {
QueryValue qv = new QueryValue(objectIdentifier);
QueryField qf = new QueryField(qc, "objectIdentifier");
SimpleConstraint c = new SimpleConstraint(qf, ConstraintOp.MATCHES, qv);
cs.addConstraint(c);
}
if (type != null) {
QueryValue qv = new QueryValue(type);
QueryField qf = new QueryField(qc, "type");
SimpleConstraint c = new SimpleConstraint(qf, ConstraintOp.MATCHES, qv);
cs.addConstraint(c);
}
if (userName != null) {
QueryClass userProfileQC = new QueryClass(UserProfile.class);
q.addFrom(userProfileQC);
QueryValue qv = new QueryValue(userName);
QueryField qf = new QueryField(userProfileQC, "username");
SimpleConstraint c = new SimpleConstraint(qf, ConstraintOp.MATCHES, qv);
cs.addConstraint(c);
QueryObjectReference qr = new QueryObjectReference(qc, "userProfile");
ContainsConstraint cc =
new ContainsConstraint(qr, ConstraintOp.CONTAINS, userProfileQC);
cs.addConstraint(cc);
}
q.setConstraint(cs);
ObjectStore userprofileOS = osw.getObjectStore();
SingletonResults results = userprofileOS.executeSingleton(q);
addToCache(cache, key, results);
return results;
}
/**
* Given a Map from name to WebSearchable, return a Map that contains only those name,
* WebSearchable pairs where the name is tagged with all of the tags listed.
* @param webSearchables the Map to filter
* @param tagNames the tag names to use for filtering
* @param tagType the tag type (from TagTypes)
* @param userName the user name to pass to getTags()
* @return the filtered Map
*/
public Map<String, WebSearchable>
filterByTags(Map<String, ? extends WebSearchable> webSearchables,
List<String> tagNames, String tagType, String userName) {
Map<String, WebSearchable> returnMap = new HashMap<String, WebSearchable>(webSearchables);
// prime the cache
for (String tagName: tagNames) {
getTags(tagName, null, tagType, userName);
}
for (String tagName: tagNames) {
for (Map.Entry<String, ? extends WebSearchable> entry: webSearchables.entrySet()) {
String webSearchableName = entry.getKey();
if (getTags(tagName, webSearchableName, tagType, userName).size() == 0) {
returnMap.remove(webSearchableName);
}
}
}
return returnMap;
}
private MultiKey makeKey(String tagName, String objectIdentifier, String type,
String userName) {
return new MultiKey(tagName, objectIdentifier, type, userName);
}
private void addToCache(Map<MultiKey, List<Tag>> cache, MultiKey key, List<Tag> results) {
cache.put(key, new ArrayList<Tag>(results));
int keyNullPartCount = 0;
for (int i = 0; i < 4; i++) {
if (key.getKey(i) == null) {
keyNullPartCount++;
}
}
Iterator resIter = results.iterator();
while (resIter.hasNext()) {
Tag tag = (Tag) resIter.next();
Object[] tagKeys = new Object[4];
tagKeys[0] = tag.getTagName();
tagKeys[1] = tag.getObjectIdentifier();
tagKeys[2] = tag.getType();
tagKeys[3] = tag.getUserProfile().getUsername();
// if (keyNullPartCount == 2) {
// // special case that allows the cache to be primed in a struts controller
// // eg. calling getTags(null, null, "template", "superuser@flymine") will prime the
// // cache so that getTags(null, "some_id", "template", "superuser@flymine") and
// // getTags("some_tag", null, "template", "superuser@flymine") will be fast
// for (int i = 0; i < 4; i++) {
// if (key.getKey(i) == null) {
// Object[] keysCopy = (Object[]) tagKeys.clone();
// keysCopy[i] = null;
// MultiKey keyCopy = new MultiKey(keysCopy);
// if (cache.containsKey(keyCopy)) {
// List existingList = (List) cache.get(keyCopy);
// if (existingList instanceof ArrayList) {
// existingList.add(tag);
// } else {
// ArrayList listCopy = new ArrayList(existingList);
// listCopy.add(tag);
// cache.put(keyCopy, listCopy);
// }
// } else {
// List newList = new ArrayList();
// newList.add(tag);
// cache.put(keyCopy, newList);
// }
// }
// }
//
// }
}
}
private Map<MultiKey, List<Tag>> getTagCache() {
if (tagCache == null) {
tagCache = new HashMap<MultiKey, List<Tag>>();
}
return tagCache;
}
/**
* Add a new tag. The format of objectIdentifier depends on the tag type.
* For types "attribute", "reference" and "collection" the objectIdentifier should have the form
* "ClassName.fieldName".
* @param tagName the tag name - any String
* @param objectIdentifier an object identifier that is appropriate for the given tag type
* (eg. "Department.name" for the "collection" type)
* @param type the tag type (eg. "collection", "reference", "attribute", "bag")
* @param userName the name of the UserProfile to associate this tag with
* @return the new Tag
*/
public synchronized Tag addTag(String tagName, String objectIdentifier, String type,
String userName) {
tagCache = null;
if (tagName == null) {
throw new IllegalArgumentException("tagName cannot be null");
}
if (objectIdentifier == null) {
throw new IllegalArgumentException("objectIdentifier cannot be null");
}
if (type == null) {
throw new IllegalArgumentException("type cannot be null");
}
if (userName == null) {
throw new IllegalArgumentException("userName cannot be null");
}
if (!tagCheckers.containsKey(type)) {
throw new IllegalArgumentException("unknown tag type: " + type);
}
UserProfile userProfile = getUserProfile(userName);
if (userProfile == null) {
throw new RuntimeException("no such user " + userName);
}
tagCheckers.get(type).isValid(tagName, objectIdentifier, type, userProfile);
Tag tag = (Tag) DynamicUtil.createObject(Collections.singleton(Tag.class));
tag.setTagName(tagName);
tag.setObjectIdentifier(objectIdentifier);
tag.setType(type);
tag.setUserProfile(userProfile);
try {
osw.store(tag);
return tag;
} catch (ObjectStoreException e) {
throw new RuntimeException("cannot set tag", e);
}
}
/**
* Make TagChecker objects for this ProfileManager.
* @param model the Model
* @return a map from tag type ("template", "reference", "attribute", etc.) to TagChecker
*/
protected Map<String, TagChecker> makeTagCheckers(final Model model) {
Map<String, TagChecker> newTagCheckers = new HashMap<String, TagChecker>();
TagChecker fieldChecker = new TagChecker() {
public void isValid(@SuppressWarnings("unused") String tagName,
String objectIdentifier, String type,
@SuppressWarnings("unused") UserProfile userProfile) {
int dotIndex = objectIdentifier.indexOf('.');
if (dotIndex == -1) {
throw new RuntimeException("tried to tag an unknown field: "
+ objectIdentifier);
}
String className = objectIdentifier.substring(0, dotIndex);
String fieldName = objectIdentifier.substring(dotIndex + 1);
ClassDescriptor cd =
model.getClassDescriptorByName(model.getPackageName() + "." + className);
if (cd == null) {
throw new RuntimeException("unknown class name \"" + className
+ "\" while tagging: " + objectIdentifier);
}
FieldDescriptor fd = cd.getFieldDescriptorByName(fieldName);
if (fd == null) {
throw new RuntimeException("unknown field name \"" + fieldName
+ "\" in class \"" + className
+ "\" while tagging: " + objectIdentifier);
}
if (type.equals("collection") && !fd.isCollection()) {
throw new RuntimeException(objectIdentifier + " is not a collection");
}
if (type.equals("reference") && !fd.isReference()) {
throw new RuntimeException(objectIdentifier + " is not a reference");
}
if (type.equals("attribute") && !fd.isAttribute()) {
throw new RuntimeException(objectIdentifier + " is not a attribute");
}
}
};
newTagCheckers.put("collection", fieldChecker);
newTagCheckers.put("reference", fieldChecker);
newTagCheckers.put("attribute", fieldChecker);
TagChecker templateChecker = new TagChecker() {
public void isValid(@SuppressWarnings("unused") String tagName,
@SuppressWarnings("unused") String objectIdentifier,
@SuppressWarnings("unused") String type,
@SuppressWarnings("unused") UserProfile userProfile) {
// OK
}
};
newTagCheckers.put("template", templateChecker);
TagChecker bagChecker = new TagChecker() {
public void isValid(String tagName, String objectIdentifier, String type,
UserProfile userProfile) {
// OK
}
};
newTagCheckers.put("bag", bagChecker);
TagChecker classChecker = new TagChecker() {
public void isValid(@SuppressWarnings("unused") String tagName,
String objectIdentifier,
@SuppressWarnings("unused") String type,
@SuppressWarnings("unused") UserProfile userProfile) {
String className = objectIdentifier;
ClassDescriptor cd = model.getClassDescriptorByName(className);
if (cd == null) {
throw new RuntimeException("unknown class name \"" + className
+ "\" while tagging: " + objectIdentifier);
}
}
};
newTagCheckers.put("class", classChecker);
return newTagCheckers;
}
}
|
intermine/web/main/src/org/intermine/web/logic/profile/ProfileManager.java
|
package org.intermine.web.logic.profile;
/*
* Copyright (C) 2002-2007 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import java.io.StringReader;
import javax.servlet.ServletContext;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.collections.keyvalue.MultiKey;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.intermine.metadata.ClassDescriptor;
import org.intermine.metadata.FieldDescriptor;
import org.intermine.metadata.Model;
import org.intermine.model.InterMineObject;
import org.intermine.model.userprofile.SavedBag;
import org.intermine.model.userprofile.SavedQuery;
import org.intermine.model.userprofile.SavedTemplateQuery;
import org.intermine.model.userprofile.Tag;
import org.intermine.model.userprofile.TemplateSummary;
import org.intermine.model.userprofile.UserProfile;
import org.intermine.objectstore.ObjectStore;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.objectstore.ObjectStoreWriter;
import org.intermine.objectstore.proxy.ProxyReference;
import org.intermine.objectstore.query.ConstraintOp;
import org.intermine.objectstore.query.ConstraintSet;
import org.intermine.objectstore.query.ContainsConstraint;
import org.intermine.objectstore.query.Query;
import org.intermine.objectstore.query.QueryClass;
import org.intermine.objectstore.query.QueryField;
import org.intermine.objectstore.query.QueryObjectReference;
import org.intermine.objectstore.query.QueryValue;
import org.intermine.objectstore.query.Results;
import org.intermine.objectstore.query.SimpleConstraint;
import org.intermine.objectstore.query.SingletonResults;
import org.intermine.util.CacheMap;
import org.intermine.util.DynamicUtil;
import org.intermine.web.logic.bag.InterMineBag;
import org.intermine.web.logic.query.PathQuery;
import org.intermine.web.logic.query.PathQueryBinding;
import org.intermine.web.logic.query.SavedQueryBinding;
import org.intermine.web.logic.search.WebSearchable;
import org.intermine.web.logic.tagging.TagTypes;
import org.intermine.web.logic.template.TemplateQuery;
import org.intermine.web.logic.template.TemplateQueryBinding;
import net.sourceforge.iharder.Base64;
/**
* Class to manage and persist user profile data such as saved bags
* @author Mark Woodbridge
*/
public class ProfileManager
{
private static final Logger LOG = Logger.getLogger(ProfileManager.class);
protected ObjectStore os;
protected ObjectStoreWriter osw;
protected TemplateQueryBinding templateBinding = new TemplateQueryBinding();
protected CacheMap profileCache = new CacheMap();
private Map<String, TagChecker> tagCheckers = null;
private HashMap<MultiKey, List<Tag>> tagCache = null;
private final ServletContext servletContext;
/**
* Construct a ProfileManager for the webapp
* @param os the ObjectStore to which the webapp is providing an interface
* @param userProfileOS the object store that hold user profile information
* @param servletContext global ServletContext object
*/
public ProfileManager(ObjectStore os, ObjectStoreWriter userProfileOS,
ServletContext servletContext) {
this.os = os;
this.servletContext = servletContext;
tagCheckers = makeTagCheckers(os.getModel());
this.osw = userProfileOS;
}
/**
* Return the ObjectStore that was passed to the constructor.
* @return the ObjectStore from the constructor
*/
public ObjectStore getObjectStore() {
return os;
}
/**
* Return the userprofile ObjectStoreWriter that was passed to the constructor.
* @return the userprofile ObjectStoreWriter from the constructor
*/
public ObjectStoreWriter getUserProfileObjectStore() {
return osw;
}
/**
* Close this ProfileManager
*
* @throws ObjectStoreException in exceptional circumstances
*/
public void close() throws ObjectStoreException {
osw.close();
}
/**
* Check whether a user already has a Profile
* @param username the username
* @return true if a profile exists
*/
public boolean hasProfile(String username) {
return getUserProfile(username) != null;
}
/**
* Validate a user's password
* A check should be made prior to this call to ensure a Profile exists
* @param username the username
* @param password the password
* @return true if password is valid
*/
public boolean validPassword(String username, String password) {
return getUserProfile(username).getPassword().equals(password);
}
/**
* Change a user's password
* A check should be made prior to this call to ensure a Profile exists
* @param username the username
* @param password the password
*/
public void setPassword(String username, String password) {
UserProfile userProfile = getUserProfile(username);
userProfile.setPassword(password);
try {
osw.store(userProfile);
} catch (ObjectStoreException e) {
throw new RuntimeException(e);
}
}
/**
* Get a user's password
* A check should be made prior to this call to ensure a Profile exists
* @param username the username
* @return password the password
*/
public String getPassword(String username) {
UserProfile userProfile = getUserProfile(username);
return userProfile.getPassword();
}
/**
* Get a user's Profile using a username and password.
* @param username the username
* @param password the password
* @return the Profile, or null if one doesn't exist
*/
public Profile getProfile(String username, String password) {
if (hasProfile(username) && validPassword(username, password)) {
return getProfile(username);
} else {
return null;
}
}
/**
* Get a user's Profile using a username
* @param username the username
* @return the Profile, or null if one doesn't exist
*/
public synchronized Profile getProfile(String username) {
Profile profile = (Profile) profileCache.get(username);
if (profile != null) {
return profile;
}
UserProfile userProfile = getUserProfile(username);
if (userProfile == null) {
return null;
}
Map<String, InterMineBag> savedBags = new HashMap<String, InterMineBag>();
Query q = new Query();
QueryClass qc = new QueryClass(SavedBag.class);
q.addFrom(qc);
q.addToSelect(new QueryField(qc, "id"));
q.addToSelect(qc); // This loads the objects into the cache
q.setConstraint(new ContainsConstraint(new QueryObjectReference(qc, "userProfile"),
ConstraintOp.CONTAINS, new ProxyReference(null, userProfile.getId(),
UserProfile.class)));
Results bags;
try {
bags = osw.execute(q);
bags.setNoOptimise();
bags.setNoExplain();
for (Iterator i = bags.iterator(); i.hasNext();) {
List row = (List) i.next();
Integer bagId = (Integer) row.get(0);
InterMineBag bag = new InterMineBag(os, bagId, osw);
savedBags.put(bag.getName(), bag);
}
} catch (ObjectStoreException e) {
throw new RuntimeException(e);
}
Map<String, org.intermine.web.logic.query.SavedQuery> savedQueries =
new HashMap<String, org.intermine.web.logic.query.SavedQuery>();
for (Iterator i = userProfile.getSavedQuerys().iterator(); i.hasNext();) {
SavedQuery query = (SavedQuery) i.next();
try {
Map queries =
SavedQueryBinding.unmarshal(new StringReader(query.getQuery()), savedBags,
servletContext);
if (queries.size() == 0) {
queries =
PathQueryBinding.unmarshal(new StringReader(query.getQuery()), savedBags,
servletContext);
if (queries.size() == 1) {
Map.Entry entry = (Map.Entry) queries.entrySet().iterator().next();
String name = (String) entry.getKey();
savedQueries.put(name,
new org.intermine.web.logic.query.SavedQuery(name, null,
(PathQuery) entry.getValue()));
}
} else {
savedQueries.putAll(queries);
}
} catch (Exception err) {
// Ignore rows that don't unmarshal (they probably reference
// another model.
LOG.warn("Failed to unmarshal saved query: " + query.getQuery());
}
}
Map<String, TemplateQuery> savedTemplates = new HashMap<String, TemplateQuery>();
for (Iterator i = userProfile.getSavedTemplateQuerys().iterator(); i.hasNext();) {
SavedTemplateQuery template = (SavedTemplateQuery) i.next();
try {
StringReader sr = new StringReader(template.getTemplateQuery());
Map templateMap = templateBinding.unmarshal(sr, savedBags, servletContext);
String templateName = (String) templateMap.keySet().iterator().next();
TemplateQuery templateQuery = (TemplateQuery) templateMap.get(templateName);
templateQuery.setSavedTemplateQuery(template);
savedTemplates.put(templateName, templateQuery);
Iterator summaryIter = template.getSummaries().iterator();
if (summaryIter.hasNext()) {
TemplateSummary summary = (TemplateSummary) summaryIter.next();
templateQuery.setPossibleValues((HashMap) Base64.decodeToObject(summary
.getSummary()));
}
} catch (Exception err) {
// Ignore rows that don't unmarshal (they probably reference
// another model.
LOG.warn("Failed to unmarshal saved template query: "
+ template.getTemplateQuery(), err);
}
}
convertTemplateKeywordsToTags(savedTemplates, username);
profile = new Profile(this, username, userProfile.getId(), userProfile.getPassword(),
savedQueries, savedBags, savedTemplates);
profileCache.put(username, profile);
return profile;
}
/**
* Create 'aspect:xxx' tags for each keyword of each template.
* Public so that LoadDefaultTemplates task can call in.
* @param savedTemplates Map from template name to TemplateQuery
* @param username username under which to store tags
*/
public void convertTemplateKeywordsToTags(Map<String, TemplateQuery> savedTemplates,
String username) {
for (Iterator<TemplateQuery> iter = savedTemplates.values().iterator(); iter.hasNext(); ) {
TemplateQuery tq = iter.next();
String keywords = tq.getKeywords();
if (StringUtils.isNotEmpty(keywords)) {
String aspects[] = keywords.split(",");
for (int i = 0; i < aspects.length; i++) {
String aspect = aspects[i].trim();
String tag = "aspect:" + aspect;
if (getTags(tag, tq.getName(), TagTypes.TEMPLATE, username).size() == 0) {
addTag(tag, tq.getName(), TagTypes.TEMPLATE, username);
}
}
}
}
}
/**
* Synchronise a user's Profile with the backing store
* @param profile the Profile
*/
public void saveProfile(Profile profile) {
Integer userId = profile.getUserId();
try {
UserProfile userProfile = getUserProfile(userId);
if (userProfile != null) {
for (Iterator i = userProfile.getSavedQuerys().iterator(); i.hasNext();) {
osw.delete((InterMineObject) i.next());
}
for (Iterator i = userProfile.getSavedTemplateQuerys().iterator();
i.hasNext();) {
osw.delete((InterMineObject) i.next());
}
} else {
// Should not happen
throw new RuntimeException("The UserProfile is null");
// userProfile = new UserProfile();
// userProfile.setUsername(profile.getUsername());
// userProfile.setPassword(profile.getPassword());
// userProfile.setId(userId);
}
for (Iterator i = profile.getSavedQueries().entrySet().iterator(); i.hasNext();) {
org.intermine.web.logic.query.SavedQuery query = null;
try {
Map.Entry entry = (Map.Entry) i.next();
query = (org.intermine.web.logic.query.SavedQuery) entry.getValue();
SavedQuery savedQuery = new SavedQuery();
savedQuery.setQuery(SavedQueryBinding.marshal(query));
savedQuery.setUserProfile(userProfile);
osw.store(savedQuery);
} catch (Exception e) {
LOG.error("Failed to marshal and save query: " + query, e);
}
}
for (Iterator i = profile.getSavedTemplates().entrySet().iterator(); i.hasNext();) {
TemplateQuery template = null;
try {
Map.Entry entry = (Map.Entry) i.next();
template = (TemplateQuery) entry.getValue();
SavedTemplateQuery savedTemplate = template.getSavedTemplateQuery();
if (savedTemplate == null) {
savedTemplate = new SavedTemplateQuery();
}
savedTemplate.setTemplateQuery(templateBinding.marshal(template));
savedTemplate.setUserProfile(userProfile);
osw.store(savedTemplate);
template.setSavedTemplateQuery(savedTemplate);
} catch (Exception e) {
LOG.error("Failed to marshal and save template: " + template, e);
}
}
osw.store(userProfile);
profile.setUserId(userProfile.getId());
} catch (ObjectStoreException e) {
throw new RuntimeException(e);
}
}
/**
* Creates a profile in the userprofile database.
*
* @param profile a Profile object
*/
public void createProfile(Profile profile) {
UserProfile userProfile = new UserProfile();
userProfile.setUsername(profile.getUsername());
userProfile.setPassword(profile.getPassword());
//userProfile.setId(userId);
try {
osw.store(userProfile);
profile.setUserId(userProfile.getId());
for (InterMineBag bag : profile.getSavedBags().values()) {
bag.setProfileId(userProfile.getId(), osw);
}
} catch (ObjectStoreException e) {
throw new RuntimeException(e);
}
saveProfile(profile);
}
/**
* Perform a query to retrieve a user's backing UserProfile
* @param username the username
* @return the relevant UserProfile
*/
public UserProfile getUserProfile(String username) {
UserProfile profile = new UserProfile();
profile.setUsername(username);
Set<String> fieldNames = new HashSet<String>();
fieldNames.add("username");
try {
profile = (UserProfile) osw.getObjectByExample(profile, fieldNames);
} catch (ObjectStoreException e) {
throw new RuntimeException("Unable to load user profile", e);
}
return profile;
}
/**
* Perform a query to retrieve a user's backing UserProfile
*
* @param userId the id of the user
* @return the relevant UserProfile
*/
public UserProfile getUserProfile(Integer userId) {
if (userId == null) {
return null;
}
try {
return (UserProfile) osw.getObjectById(userId, UserProfile.class);
} catch (ObjectStoreException e) {
throw new RuntimeException("Unable to load user profile", e);
}
}
/**
* Return a List of the usernames in all of the stored profiles.
* @return the usernames
*/
public List getProfileUserNames() {
Query q = new Query();
QueryClass qcUserProfile = new QueryClass(UserProfile.class);
QueryField qfUserName = new QueryField(qcUserProfile, "username");
q.addFrom(qcUserProfile);
q.addToSelect(qfUserName);
SingletonResults res = osw.executeSingleton(q);
List usernames = new ArrayList();
Iterator resIter = res.iterator();
while (resIter.hasNext()) {
usernames.add(resIter.next());
}
return usernames;
}
/**
* Delete a tag object from the database.
* @param tag Tag object
*/
public synchronized void deleteTag(Tag tag) {
try {
LOG.error("deleteTag() removing cache");
tagCache = null;
getUserProfileObjectStore().delete(tag);
} catch (ObjectStoreException err) {
LOG.error(err);
}
}
/**
* Get Tag by object id.
* @param id intermine object id
* @return Tag
* @throws ObjectStoreException if something goes wrong
*/
public synchronized Tag getTagById(int id) throws ObjectStoreException {
return (Tag) getUserProfileObjectStore().getObjectById(new Integer(id), Tag.class);
}
/**
* Return a List of Tags that match all the arguments. Any null arguments will be treated as
* wildcards.
* @param tagName the tag name - any String
* @param objectIdentifier an object identifier that is appropriate for the given tag type
* (eg. "Department.name" for the "collection" type)
* @param type the tag type (eg. "collection", "reference", "attribute", "bag")
* @param userName the use name this tag is associated with
* @return the matching Tags
*/
public synchronized List<Tag> getTags(String tagName, String objectIdentifier, String type,
String userName) {
Map<MultiKey, List<Tag>> cache = getTagCache();
MultiKey key = makeKey(tagName, objectIdentifier, type, userName);
if (cache.containsKey(key)) {
return cache.get(key);
}
Query q = new Query();
QueryClass qc = new QueryClass(Tag.class);
q.addFrom(qc);
q.addToSelect(qc);
QueryField orderByField = new QueryField(qc, "tagName");
q.addToOrderBy(orderByField);
ConstraintSet cs = new ConstraintSet(ConstraintOp.AND);
if (tagName != null) {
QueryValue qv = new QueryValue(tagName);
QueryField qf = new QueryField(qc, "tagName");
SimpleConstraint c = new SimpleConstraint(qf, ConstraintOp.MATCHES, qv);
cs.addConstraint(c);
}
if (objectIdentifier != null) {
QueryValue qv = new QueryValue(objectIdentifier);
QueryField qf = new QueryField(qc, "objectIdentifier");
SimpleConstraint c = new SimpleConstraint(qf, ConstraintOp.MATCHES, qv);
cs.addConstraint(c);
}
if (type != null) {
QueryValue qv = new QueryValue(type);
QueryField qf = new QueryField(qc, "type");
SimpleConstraint c = new SimpleConstraint(qf, ConstraintOp.MATCHES, qv);
cs.addConstraint(c);
}
if (userName != null) {
QueryClass userProfileQC = new QueryClass(UserProfile.class);
q.addFrom(userProfileQC);
QueryValue qv = new QueryValue(userName);
QueryField qf = new QueryField(userProfileQC, "username");
SimpleConstraint c = new SimpleConstraint(qf, ConstraintOp.MATCHES, qv);
cs.addConstraint(c);
QueryObjectReference qr = new QueryObjectReference(qc, "userProfile");
ContainsConstraint cc =
new ContainsConstraint(qr, ConstraintOp.CONTAINS, userProfileQC);
cs.addConstraint(cc);
}
q.setConstraint(cs);
ObjectStore userprofileOS = osw.getObjectStore();
SingletonResults results = userprofileOS.executeSingleton(q);
addToCache(cache, key, results);
return results;
}
/**
* Given a Map from name to WebSearchable, return a Map that contains only those name,
* WebSearchable pairs where the name is tagged with all of the tags listed.
* @param webSearchables the Map to filter
* @param tagNames the tag names to use for filtering
* @param tagType the tag type (from TagTypes)
* @param userName the user name to pass to getTags()
* @return the filtered Map
*/
public Map<String, WebSearchable>
filterByTags(Map<String, ? extends WebSearchable> webSearchables,
List<String> tagNames, String tagType, String userName) {
Map<String, WebSearchable> returnMap = new HashMap<String, WebSearchable>(webSearchables);
// prime the cache
for (String tagName: tagNames) {
getTags(tagName, null, tagType, userName);
}
for (String tagName: tagNames) {
for (Map.Entry<String, ? extends WebSearchable> entry: webSearchables.entrySet()) {
String webSearchableName = entry.getKey();
if (getTags(tagName, webSearchableName, tagType, userName).size() == 0) {
returnMap.remove(webSearchableName);
}
}
}
return returnMap;
}
private MultiKey makeKey(String tagName, String objectIdentifier, String type,
String userName) {
return new MultiKey(tagName, objectIdentifier, type, userName);
}
private void addToCache(Map<MultiKey, List<Tag>> cache, MultiKey key, List<Tag> results) {
LOG.error("adding to cache: " + key);
cache.put(key, new ArrayList<Tag>(results));
int keyNullPartCount = 0;
for (int i = 0; i < 4; i++) {
if (key.getKey(i) == null) {
keyNullPartCount++;
}
}
Iterator resIter = results.iterator();
while (resIter.hasNext()) {
Tag tag = (Tag) resIter.next();
Object[] tagKeys = new Object[4];
tagKeys[0] = tag.getTagName();
tagKeys[1] = tag.getObjectIdentifier();
tagKeys[2] = tag.getType();
tagKeys[3] = tag.getUserProfile().getUsername();
// if (keyNullPartCount == 2) {
// // special case that allows the cache to be primed in a struts controller
// // eg. calling getTags(null, null, "template", "superuser@flymine") will prime the
// // cache so that getTags(null, "some_id", "template", "superuser@flymine") and
// // getTags("some_tag", null, "template", "superuser@flymine") will be fast
// for (int i = 0; i < 4; i++) {
// if (key.getKey(i) == null) {
// Object[] keysCopy = (Object[]) tagKeys.clone();
// keysCopy[i] = null;
// MultiKey keyCopy = new MultiKey(keysCopy);
// if (cache.containsKey(keyCopy)) {
// List existingList = (List) cache.get(keyCopy);
// if (existingList instanceof ArrayList) {
// existingList.add(tag);
// } else {
// ArrayList listCopy = new ArrayList(existingList);
// listCopy.add(tag);
// cache.put(keyCopy, listCopy);
// }
// } else {
// List newList = new ArrayList();
// newList.add(tag);
// cache.put(keyCopy, newList);
// }
// }
// }
//
// }
}
}
private Map<MultiKey, List<Tag>> getTagCache() {
if (tagCache == null) {
tagCache = new HashMap<MultiKey, List<Tag>>();
}
return tagCache;
}
/**
* Add a new tag. The format of objectIdentifier depends on the tag type.
* For types "attribute", "reference" and "collection" the objectIdentifier should have the form
* "ClassName.fieldName".
* @param tagName the tag name - any String
* @param objectIdentifier an object identifier that is appropriate for the given tag type
* (eg. "Department.name" for the "collection" type)
* @param type the tag type (eg. "collection", "reference", "attribute", "bag")
* @param userName the name of the UserProfile to associate this tag with
* @return the new Tag
*/
public synchronized Tag addTag(String tagName, String objectIdentifier, String type,
String userName) {
LOG.error("addTag() deleting cache");
tagCache = null;
if (tagName == null) {
throw new IllegalArgumentException("tagName cannot be null");
}
if (objectIdentifier == null) {
throw new IllegalArgumentException("objectIdentifier cannot be null");
}
if (type == null) {
throw new IllegalArgumentException("type cannot be null");
}
if (userName == null) {
throw new IllegalArgumentException("userName cannot be null");
}
if (!tagCheckers.containsKey(type)) {
throw new IllegalArgumentException("unknown tag type: " + type);
}
UserProfile userProfile = getUserProfile(userName);
if (userProfile == null) {
throw new RuntimeException("no such user " + userName);
}
tagCheckers.get(type).isValid(tagName, objectIdentifier, type, userProfile);
Tag tag = (Tag) DynamicUtil.createObject(Collections.singleton(Tag.class));
tag.setTagName(tagName);
tag.setObjectIdentifier(objectIdentifier);
tag.setType(type);
tag.setUserProfile(userProfile);
try {
osw.store(tag);
return tag;
} catch (ObjectStoreException e) {
throw new RuntimeException("cannot set tag", e);
}
}
/**
* Make TagChecker objects for this ProfileManager.
* @param model the Model
* @return a map from tag type ("template", "reference", "attribute", etc.) to TagChecker
*/
protected Map<String, TagChecker> makeTagCheckers(final Model model) {
Map<String, TagChecker> newTagCheckers = new HashMap<String, TagChecker>();
TagChecker fieldChecker = new TagChecker() {
public void isValid(@SuppressWarnings("unused") String tagName,
String objectIdentifier, String type,
@SuppressWarnings("unused") UserProfile userProfile) {
int dotIndex = objectIdentifier.indexOf('.');
if (dotIndex == -1) {
throw new RuntimeException("tried to tag an unknown field: "
+ objectIdentifier);
}
String className = objectIdentifier.substring(0, dotIndex);
String fieldName = objectIdentifier.substring(dotIndex + 1);
ClassDescriptor cd =
model.getClassDescriptorByName(model.getPackageName() + "." + className);
if (cd == null) {
throw new RuntimeException("unknown class name \"" + className
+ "\" while tagging: " + objectIdentifier);
}
FieldDescriptor fd = cd.getFieldDescriptorByName(fieldName);
if (fd == null) {
throw new RuntimeException("unknown field name \"" + fieldName
+ "\" in class \"" + className
+ "\" while tagging: " + objectIdentifier);
}
if (type.equals("collection") && !fd.isCollection()) {
throw new RuntimeException(objectIdentifier + " is not a collection");
}
if (type.equals("reference") && !fd.isReference()) {
throw new RuntimeException(objectIdentifier + " is not a reference");
}
if (type.equals("attribute") && !fd.isAttribute()) {
throw new RuntimeException(objectIdentifier + " is not a attribute");
}
}
};
newTagCheckers.put("collection", fieldChecker);
newTagCheckers.put("reference", fieldChecker);
newTagCheckers.put("attribute", fieldChecker);
TagChecker templateChecker = new TagChecker() {
public void isValid(@SuppressWarnings("unused") String tagName,
@SuppressWarnings("unused") String objectIdentifier,
@SuppressWarnings("unused") String type,
@SuppressWarnings("unused") UserProfile userProfile) {
// OK
}
};
newTagCheckers.put("template", templateChecker);
TagChecker bagChecker = new TagChecker() {
public void isValid(String tagName, String objectIdentifier, String type,
UserProfile userProfile) {
// OK
}
};
newTagCheckers.put("bag", bagChecker);
TagChecker classChecker = new TagChecker() {
public void isValid(@SuppressWarnings("unused") String tagName,
String objectIdentifier,
@SuppressWarnings("unused") String type,
@SuppressWarnings("unused") UserProfile userProfile) {
String className = objectIdentifier;
ClassDescriptor cd = model.getClassDescriptorByName(className);
if (cd == null) {
throw new RuntimeException("unknown class name \"" + className
+ "\" while tagging: " + objectIdentifier);
}
}
};
newTagCheckers.put("class", classChecker);
return newTagCheckers;
}
}
|
Removed debugging output.
Former-commit-id: a4a74cb5824b9c529eafce2d47f497b6481fa7a6
|
intermine/web/main/src/org/intermine/web/logic/profile/ProfileManager.java
|
Removed debugging output.
|
<ide><path>ntermine/web/main/src/org/intermine/web/logic/profile/ProfileManager.java
<ide> */
<ide> public synchronized void deleteTag(Tag tag) {
<ide> try {
<del> LOG.error("deleteTag() removing cache");
<ide> tagCache = null;
<ide> getUserProfileObjectStore().delete(tag);
<ide> } catch (ObjectStoreException err) {
<del> LOG.error(err);
<add> LOG.error("deleteTag(): " + err);
<ide> }
<ide> }
<ide>
<ide> }
<ide>
<ide> private void addToCache(Map<MultiKey, List<Tag>> cache, MultiKey key, List<Tag> results) {
<del> LOG.error("adding to cache: " + key);
<add>
<ide> cache.put(key, new ArrayList<Tag>(results));
<ide>
<ide> int keyNullPartCount = 0;
<ide> */
<ide> public synchronized Tag addTag(String tagName, String objectIdentifier, String type,
<ide> String userName) {
<del> LOG.error("addTag() deleting cache");
<add>
<ide> tagCache = null;
<ide> if (tagName == null) {
<ide> throw new IllegalArgumentException("tagName cannot be null");
|
|
Java
|
apache-2.0
|
b930a001c7fd500a71d61bb031bf812a8036e921
| 0 |
borisdty/jMatRW
|
package common;
import java.nio.ByteOrder;
/**
* Provides static conversion function from byte-array (byte[]) to
* - byte (1 byte)
* - unsigned byte (returned as short) (1 byte)
* - char (2 bytes)
* - short (2 bytes)
* - unsigned short (returned as int) (2 bytes)
* - int (4 bytes)
* - unsigned int (returned as long) (4 bytes)
* - long (8 bytes)
* - float (4 bytes) acc. to IEEE754
* - double (8 bytes) acc. to IEEE754
*
* Byte order can be chosen between BIG_ENDIAN and LITTLE_ENDIAN
*
* @author Boris Dortschy (<a href="mailto:[email protected]">[email protected]</a>)
*/
public class Bytes
{
public static byte toByte(byte[] in, int offset, ByteOrder byte_order)
{
byte out = in[offset];
return out;
}
public static short toUByte(byte[] in, int offset, ByteOrder byte_order)
{
short out = (short)(in[offset]&0xFF);
return out;
}
public static char toChar(byte[] in, int offset, ByteOrder byte_order)
{
char out = 0;
if ( byte_order == ByteOrder.BIG_ENDIAN )
{
out |= (in[offset+0]&0xFF) << 8;
out |= (in[offset+1]&0xFF) << 0;
}
else
{
out |= (in[offset+1]&0xFF) << 8;
out |= (in[offset+0]&0xFF) << 0;
}
return out;
}
public static short toShort(byte[] in, int offset, ByteOrder byte_order)
{
short out = 0;
if ( byte_order == ByteOrder.BIG_ENDIAN )
{
out |= (in[offset+0]&0xFF) << 8;
out |= (in[offset+1]&0xFF) << 0;
}
else
{
out |= (in[offset+1]&0xFF) << 8;
out |= (in[offset+0]&0xFF) << 0;
}
return out;
}
public static int toUShort(byte[] in, int offset, ByteOrder byte_order)
{
int out = 0;
if ( byte_order == ByteOrder.BIG_ENDIAN )
{
out |= (in[offset+0]&0xFF) << 8;
out |= (in[offset+1]&0xFF) << 0;
}
else
{
out |= (in[offset+1]&0xFF) << 8;
out |= (in[offset+0]&0xFF) << 0;
}
return out;
}
public static int toInt(byte[] in, int offset, ByteOrder byte_order)
{
if (offset + Integer.BYTES > in.length)
throw new IndexOutOfBoundsException("Bytes::toInt: " +
"Not enough bytes available for complete conversion.");
int out = 0;
if ( byte_order == ByteOrder.BIG_ENDIAN )
{
for(int i = offset; i < (offset + Integer.BYTES); i++)
{
out <<= 8;
out ^= in[i] & 0xFF;
}
}
else
{
for(int i = offset + Integer.BYTES-1; i >= offset; i--)
{
out <<= 8;
out ^= in[i] & 0xFF;
}
}
return out;
}
public static long toUInt(byte[] in, int offset, ByteOrder byte_order)
{
long out = 0;
if ( byte_order == ByteOrder.BIG_ENDIAN )
{
out |= (in[offset+0]&0xFFL) << 24;
out |= (in[offset+1]&0xFFL) << 16;
out |= (in[offset+2]&0xFFL) << 8;
out |= (in[offset+3]&0xFFL) << 0;
}
else
{
out |= (in[offset+3]&0xFFL) << 24;
out |= (in[offset+2]&0xFFL) << 16;
out |= (in[offset+1]&0xFFL) << 8;
out |= (in[offset+0]&0xFFL) << 0;
}
return out;
}
public static long toLong(byte[] in, int offset, ByteOrder byte_order)
{
if (offset + Long.BYTES > in.length)
throw new IndexOutOfBoundsException("Bytes::toLong: " +
"Not enough bytes available for complete conversion.");
long out = 0;
if ( byte_order == ByteOrder.BIG_ENDIAN )
{
for(int i = offset; i < offset + Long.BYTES; i++)
{
out <<= 8;
//out ^= in[i] & 0xFFL;
out ^= in[i] & 0xFF;
}
}
else
{
for(int i = offset + Long.BYTES-1; i >= offset; i--)
{
out <<= 8;
//out ^= in[i] & 0xFFL;
out ^= in[i] & 0xFF;
}
}
return out;
}
public static float toFloat(byte[] in, int offset, ByteOrder byte_order)
{
int bits = toInt(in, offset, byte_order);
return Float.intBitsToFloat(bits);
}
public static double toDouble(byte[] in, int offset, ByteOrder byte_order)
{
long bits = toLong(in, offset, byte_order);
return Double.longBitsToDouble(bits);
}
}
|
src/common/Bytes.java
|
package common;
import java.nio.ByteOrder;
/**
* Provides static conversion function from byte-array (byte[]) to
* - byte (1 byte)
* - unsigned byte (returned as short) (1 byte)
* - char (2 bytes)
* - short (2 bytes)
* - unsigned short (returned as int) (2 bytes)
* - int (4 bytes)
* - unsigned int (returned as long) (4 bytes)
* - long (8 bytes)
* - float (4 bytes) acc. to IEEE754
* - double (8 bytes) acc. to IEEE754
*
* Byte order can be chosen between BIG_ENDIAN and LITTLE_ENDIAN
*
* @author Boris Dortschy (<a href="mailto:[email protected]">[email protected]</a>)
*/
public class Bytes
{
public static byte toByte(byte[] in, int offset, ByteOrder byte_order)
{
byte out = in[offset];
return out;
}
public static short toUByte(byte[] in, int offset, ByteOrder byte_order)
{
short out = (short)(in[offset]&0xFF);
return out;
}
public static char toChar(byte[] in, int offset, ByteOrder byte_order)
{
char out = 0;
if ( byte_order.equals(ByteOrder.BIG_ENDIAN) )
{
out |= (in[offset+0]&0xFF) << 8;
out |= (in[offset+1]&0xFF) << 0;
}
else
{
out |= (in[offset+1]&0xFF) << 8;
out |= (in[offset+0]&0xFF) << 0;
}
return out;
}
public static short toShort(byte[] in, int offset, ByteOrder byte_order)
{
short out = 0;
if ( byte_order.equals(ByteOrder.BIG_ENDIAN) )
{
out |= (in[offset+0]&0xFF) << 8;
out |= (in[offset+1]&0xFF) << 0;
}
else
{
out |= (in[offset+1]&0xFF) << 8;
out |= (in[offset+0]&0xFF) << 0;
}
return out;
}
public static int toUShort(byte[] in, int offset, ByteOrder byte_order)
{
int out = 0;
if ( byte_order.equals(ByteOrder.BIG_ENDIAN) )
{
out |= (in[offset+0]&0xFF) << 8;
out |= (in[offset+1]&0xFF) << 0;
}
else
{
out |= (in[offset+1]&0xFF) << 8;
out |= (in[offset+0]&0xFF) << 0;
}
return out;
}
public static int toInt(byte[] in, int offset, ByteOrder byte_order)
{
if (offset + Integer.BYTES > in.length)
throw new IndexOutOfBoundsException("Bytes::toInt: " +
"Not enough bytes available for complete conversion.");
int out = 0;
if ( byte_order.equals(ByteOrder.BIG_ENDIAN) )
{
for(int i = offset; i < (offset + Integer.BYTES); i++)
{
out <<= 8;
out ^= in[i] & 0xFF;
}
}
else
{
for(int i = offset + Integer.BYTES-1; i >= offset; i--)
{
out <<= 8;
out ^= in[i] & 0xFF;
}
}
return out;
}
public static long toUInt(byte[] in, int offset, ByteOrder byte_order)
{
long out = 0;
if ( byte_order.equals(ByteOrder.BIG_ENDIAN) )
{
out |= (in[offset+0]&0xFFL) << 24;
out |= (in[offset+1]&0xFFL) << 16;
out |= (in[offset+2]&0xFFL) << 8;
out |= (in[offset+3]&0xFFL) << 0;
}
else
{
out |= (in[offset+3]&0xFFL) << 24;
out |= (in[offset+2]&0xFFL) << 16;
out |= (in[offset+1]&0xFFL) << 8;
out |= (in[offset+0]&0xFFL) << 0;
}
return out;
}
public static long toLong(byte[] in, int offset, ByteOrder byte_order)
{
if (offset + Long.BYTES > in.length)
throw new IndexOutOfBoundsException("Bytes::toLong: " +
"Not enough bytes available for complete conversion.");
long out = 0;
if ( byte_order.equals(ByteOrder.BIG_ENDIAN) )
{
for(int i = offset; i < offset + Long.BYTES; i++)
{
out <<= 8;
//out ^= in[i] & 0xFFL;
out ^= in[i] & 0xFF;
}
}
else
{
for(int i = offset + Long.BYTES-1; i >= offset; i--)
{
out <<= 8;
//out ^= in[i] & 0xFFL;
out ^= in[i] & 0xFF;
}
}
return out;
}
public static float toFloat(byte[] in, int offset, ByteOrder byte_order)
{
int bits = toInt(in, offset, byte_order);
return Float.intBitsToFloat(bits);
}
public static double toDouble(byte[] in, int offset, ByteOrder byte_order)
{
long bits = toLong(in, offset, byte_order);
return Double.longBitsToDouble(bits);
}
}
|
Changed comparing enum-types from .equal() to using ==
|
src/common/Bytes.java
|
Changed comparing enum-types from .equal() to using ==
|
<ide><path>rc/common/Bytes.java
<ide> {
<ide> char out = 0;
<ide>
<del> if ( byte_order.equals(ByteOrder.BIG_ENDIAN) )
<add> if ( byte_order == ByteOrder.BIG_ENDIAN )
<ide> {
<ide> out |= (in[offset+0]&0xFF) << 8;
<ide> out |= (in[offset+1]&0xFF) << 0;
<ide> {
<ide> short out = 0;
<ide>
<del> if ( byte_order.equals(ByteOrder.BIG_ENDIAN) )
<add> if ( byte_order == ByteOrder.BIG_ENDIAN )
<ide> {
<ide> out |= (in[offset+0]&0xFF) << 8;
<ide> out |= (in[offset+1]&0xFF) << 0;
<ide> {
<ide> int out = 0;
<ide>
<del> if ( byte_order.equals(ByteOrder.BIG_ENDIAN) )
<add> if ( byte_order == ByteOrder.BIG_ENDIAN )
<ide> {
<ide> out |= (in[offset+0]&0xFF) << 8;
<ide> out |= (in[offset+1]&0xFF) << 0;
<ide>
<ide> int out = 0;
<ide>
<del> if ( byte_order.equals(ByteOrder.BIG_ENDIAN) )
<add> if ( byte_order == ByteOrder.BIG_ENDIAN )
<ide> {
<ide> for(int i = offset; i < (offset + Integer.BYTES); i++)
<ide> {
<ide> {
<ide> long out = 0;
<ide>
<del> if ( byte_order.equals(ByteOrder.BIG_ENDIAN) )
<add> if ( byte_order == ByteOrder.BIG_ENDIAN )
<ide> {
<ide> out |= (in[offset+0]&0xFFL) << 24;
<ide> out |= (in[offset+1]&0xFFL) << 16;
<ide>
<ide> long out = 0;
<ide>
<del> if ( byte_order.equals(ByteOrder.BIG_ENDIAN) )
<add> if ( byte_order == ByteOrder.BIG_ENDIAN )
<ide> {
<ide> for(int i = offset; i < offset + Long.BYTES; i++)
<ide> {
|
|
JavaScript
|
bsd-3-clause
|
64d873d81daf76f117c24a14bc738333532edec7
| 0 |
gerco/webmin,rcuvgd/Webmin,rcuvgd/Webmin22.01.2016,youprofit/webmin,mikaoras/webmin,HasClass0/webmin,BangL/webmin,rcuvgd/Webmin22.01.2016,BangL/webmin,mikaoras/webmin,BangL/webmin,rcuvgd/Webmin,HasClass0/webmin,BangL/webmin,nawawi/webmin,rcuvgd/Webmin,BangL/webmin,youprofit/webmin,rcuvgd/Webmin22.01.2016,rcuvgd/Webmin22.01.2016,BangL/webmin,BangL/webmin,webdev1001/webmin,youprofit/webmin,webdev1001/webmin,nawawi/webmin,gerco/webmin,rcuvgd/Webmin,webdev1001/webmin,rcuvgd/Webmin,nawawi/webmin,nawawi/webmin,rcuvgd/Webmin22.01.2016,HasClass0/webmin,nawawi/webmin,mikaoras/webmin,webmin/webmin,gerco/webmin,rcuvgd/Webmin22.01.2016,webdev1001/webmin,webmin/webmin,webmin/webmin,webdev1001/webmin,nawawi/webmin,webdev1001/webmin,webdev1001/webmin,rcuvgd/Webmin22.01.2016,rcuvgd/Webmin22.01.2016,youprofit/webmin,BangL/webmin,mikaoras/webmin,gerco/webmin,mikaoras/webmin,BangL/webmin,HasClass0/webmin,gerco/webmin,rcuvgd/Webmin,nawawi/webmin,HasClass0/webmin,mikaoras/webmin,rcuvgd/Webmin22.01.2016,HasClass0/webmin,gerco/webmin,HasClass0/webmin,rcuvgd/Webmin,gerco/webmin,webmin/webmin,youprofit/webmin,BangL/webmin,mikaoras/webmin,webdev1001/webmin,webmin/webmin,HasClass0/webmin,HasClass0/webmin,rcuvgd/Webmin,nawawi/webmin,youprofit/webmin,rcuvgd/Webmin22.01.2016,gerco/webmin,mikaoras/webmin,rcuvgd/Webmin,rcuvgd/Webmin,youprofit/webmin,nawawi/webmin,mikaoras/webmin,webdev1001/webmin,webmin/webmin,webmin/webmin,youprofit/webmin,webdev1001/webmin,gerco/webmin,youprofit/webmin,HasClass0/webmin,nawawi/webmin,mikaoras/webmin,webmin/webmin,gerco/webmin,webmin/webmin,youprofit/webmin,webmin/webmin
|
addEvent(window, "load", sortables_init);
var SORT_COLUMN_INDEX;
function sortables_init() {
var lastAssignedId = 0;
// Find all tables with class sortable and make them sortable
if (!document.getElementsByTagName) return;
tbls = document.getElementsByTagName("table");
for (ti=0;ti<tbls.length;ti++) {
thisTbl = tbls[ti];
if (!thisTbl.id) {
thisTbl.id = 'sortableTable'+this.lastAssignedId++;
}
if (((' '+thisTbl.className+' ').indexOf("sortable") != -1) && (thisTbl.id)) {
//initTable(thisTbl.id);
ts_makeSortable(thisTbl);
}
}
}
function ts_makeSortable(table) {
if (table.rows && table.rows.length > 0) {
var firstRow = table.rows[0];
}
if (!firstRow) return;
// We have a first row: assume it's the header, and make its contents clickable links
for (var i=0;i<firstRow.cells.length;i++) {
var cell = firstRow.cells[i];
var txt = ts_getInnerText(cell);
cell.innerHTML = '<b><a href="#" class="sortheader" '+
'onclick="ts_resortTable(this, '+i+');return false;">' +
txt+'<span class="sortarrow"> </span></a></b>';
}
}
function ts_getInnerText(el) {
if (typeof el == "string") return el;
if (typeof el == "undefined") { return el };
if (el.innerText) return el.innerText; //Not needed but it is faster
var str = "";
var cs = el.childNodes;
var l = cs.length;
for (var i = 0; i < l; i++) {
switch (cs[i].nodeType) {
case 1: //ELEMENT_NODE
str += ts_getInnerText(cs[i]);
break;
case 3: //TEXT_NODE
str += cs[i].nodeValue;
break;
}
}
return str;
}
function ts_resortTable(lnk,clid) {
// get the span
var span;
for (var ci=0;ci<lnk.childNodes.length;ci++) {
if (lnk.childNodes[ci].tagName && lnk.childNodes[ci].tagName.toLowerCase() == 'span') span = lnk.childNodes[ci];
}
var spantext = ts_getInnerText(span);
var td = lnk.parentNode;
var column = clid || td.cellIndex;
var table = getParent(td,'TABLE');
// Work out a type for the column
if (table.rows.length <= 1) return;
var itm = ts_getInnerText(table.rows[1].cells[column]);
sortfn = ts_sort_caseinsensitive;
if (itm.match(/^\d\d[\/-]\d\d[\/-]\d\d\d\d$/)) sortfn = ts_sort_date;
if (itm.match(/^\d\d[\/-]\d\d[\/-]\d\d$/)) sortfn = ts_sort_date;
if (itm.match(/^[$]/)) sortfn = ts_sort_currency;
//if (itm.match(/^[\d\.]+$/)) sortfn = ts_sort_numeric;
if (itm.match(/^[\d\.]+\s*(bytes|b|kb|tb|gb|mb)$/i)) sortfn = ts_sort_filesize;
// Special cases for our mailbox lists
if (itm.match(/^(None|Empty|Unlimited)$/)) sortfn = ts_sort_filesize;
SORT_COLUMN_INDEX = column;
var firstRow = new Array();
var newRows = new Array();
for (i=0;i<table.rows[0].length;i++) { firstRow[i] = table.rows[0][i]; }
for (j=1;j<table.rows.length;j++) { newRows[j-1] = table.rows[j]; }
newRows.sort(sortfn);
if (span.getAttribute("sortdir") == 'down') {
ARROW = ' ↑';
newRows.reverse();
span.setAttribute('sortdir','up');
} else {
ARROW = ' ↓';
span.setAttribute('sortdir','down');
}
// We appendChild rows that already exist to the tbody, so it moves them rather than creating new ones
// don't do sortbottom rows
for (i=0;i<newRows.length;i++) { if (!newRows[i].className || (newRows[i].className && (newRows[i].className.indexOf('sortbottom') == -1))) table.tBodies[0].appendChild(newRows[i]);}
// do sortbottom rows only
for (i=0;i<newRows.length;i++) { if (newRows[i].className && (newRows[i].className.indexOf('sortbottom') != -1)) table.tBodies[0].appendChild(newRows[i]);}
// Delete any other arrows there may be showing
var allspans = document.getElementsByTagName("span");
for (var ci=0;ci<allspans.length;ci++) {
if (allspans[ci].className == 'sortarrow') {
if (getParent(allspans[ci],"table") == getParent(lnk,"table")) { // in the same table as us?
allspans[ci].innerHTML = ' ';
}
}
}
span.innerHTML = ARROW;
}
function getParent(el, pTagName) {
if (el == null) return null;
else if (el.nodeType == 1 && el.tagName.toLowerCase() == pTagName.toLowerCase()) // Gecko bug, supposed to be uppercase
return el;
else
return getParent(el.parentNode, pTagName);
}
function ts_sort_date(a,b) {
// y2k notes: two digit years less than 50 are treated as 20XX, greater than 50 are treated as 19XX
aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]);
bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]);
if (aa.length == 10) {
dt1 = aa.substr(6,4)+aa.substr(3,2)+aa.substr(0,2);
} else {
yr = aa.substr(6,2);
if (parseInt(yr) < 50) { yr = '20'+yr; } else { yr = '19'+yr; }
dt1 = yr+aa.substr(3,2)+aa.substr(0,2);
}
if (bb.length == 10) {
dt2 = bb.substr(6,4)+bb.substr(3,2)+bb.substr(0,2);
} else {
yr = bb.substr(6,2);
if (parseInt(yr) < 50) { yr = '20'+yr; } else { yr = '19'+yr; }
dt2 = yr+bb.substr(3,2)+bb.substr(0,2);
}
if (dt1==dt2) return 0;
if (dt1<dt2) return -1;
return 1;
}
function ts_sort_currency(a,b) {
aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]).replace(/[^0-9.]/g,'');
bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]).replace(/[^0-9.]/g,'');
return parseFloat(aa) - parseFloat(bb);
}
// handles file sizes, simple numerics, and Unlimited/Empty/None special cases
function ts_sort_filesize(a,b) {
aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]).toLowerCase();
bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]).toLowerCase();
if (aa.length == 0) return -1;
else if (bb.length == 0) return 1;
var regex = /^([\d\.]*|none|empty|unlimited)\s*(bytes|b|kb|tb|gb|mb)?$/i;
matchA = aa.match(regex);
matchB = bb.match(regex);
// Give file size class an integer value, if we don't already have one
if (matchA[1] == 'none') valA = -999;
else if (matchA[1] == 'empty') valA = 0;
else if (matchA[1] == '0') valA = 0;
else if (matchA[1] == 'unlimited') valA = 999;
else if (matchA[2] == 'b' || matchA[2] == 'bytes') valA = 1;
else if (matchA[2] == undefined || matchA[2] == '') valA = 1;
else if (matchA[2] == 'kb') valA = 2;
else if (matchA[2] == 'mb') valA = 3;
else if (matchA[2] == 'gb') valA = 4;
else if (matchA[2] == 'tb') valA = 5;
if (matchB[1] == 'none') valB = -999;
else if (matchB[1] == 'empty') valB = 0;
else if (matchB[1] == '0') valB = 0;
else if (matchB[1] == 'unlimited') valB = 999;
else if (matchB[2] == 'b' || matchB[2] == 'bytes') valB = 1;
else if (matchB[2] == undefined || matchB[2] == '') valB = 1;
else if (matchB[2] == 'kb') valB = 2;
else if (matchB[2] == 'mb') valB = 3;
else if (matchB[2] == 'gb') valB = 4;
else if (matchB[2] == 'tb') valB = 5;
if (valA == valB) {
if ( isNaN(matchA[1])) return -1;
if ( isNaN(matchB[1])) return 1;
// Files are in the same size class kb/gb/mb/etc
// just do a numeric sort on the file size
return matchA[1]-matchB[1];
} else if (valA < valB) {
return -1;
} else if (valA > valB) {
return 1;
}
}
function ts_sort_numeric(a,b) {
aa = parseFloat(ts_getInnerText(a.cells[SORT_COLUMN_INDEX]));
if (isNaN(aa)) aa = 0;
bb = parseFloat(ts_getInnerText(b.cells[SORT_COLUMN_INDEX]));
if (isNaN(bb)) bb = 0;
return aa-bb;
}
function ts_sort_caseinsensitive(a,b) {
aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]).toLowerCase();
bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]).toLowerCase();
if (aa==bb) return 0;
if (aa<bb) return -1;
return 1;
}
function ts_sort_default(a,b) {
aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]);
bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]);
if (aa==bb) return 0;
if (aa<bb) return -1;
return 1;
}
function addEvent(elm, evType, fn, useCapture)
// addEvent and removeEvent
// cross-browser event handling for IE5+, NS6 and Mozilla
// By Scott Andrew
{
if (elm.addEventListener){
elm.addEventListener(evType, fn, useCapture);
return true;
} else if (elm.attachEvent){
var r = elm.attachEvent("on"+evType, fn);
return r;
} else {
alert("Handler could not be removed");
}
}
|
blue-theme/unauthenticated/sorttable.js
|
addEvent(window, "load", sortables_init);
var SORT_COLUMN_INDEX;
function sortables_init() {
var lastAssignedId = 0;
// Find all tables with class sortable and make them sortable
if (!document.getElementsByTagName) return;
tbls = document.getElementsByTagName("table");
for (ti=0;ti<tbls.length;ti++) {
thisTbl = tbls[ti];
if (!thisTbl.id) {
thisTbl.id = 'sortableTable'+this.lastAssignedId++;
}
if (((' '+thisTbl.className+' ').indexOf("sortable") != -1) && (thisTbl.id)) {
//initTable(thisTbl.id);
ts_makeSortable(thisTbl);
}
}
}
function ts_makeSortable(table) {
if (table.rows && table.rows.length > 0) {
var firstRow = table.rows[0];
}
if (!firstRow) return;
// We have a first row: assume it's the header, and make its contents clickable links
for (var i=0;i<firstRow.cells.length;i++) {
var cell = firstRow.cells[i];
var txt = ts_getInnerText(cell);
cell.innerHTML = '<b><a href="#" class="sortheader" '+
'onclick="ts_resortTable(this, '+i+');return false;">' +
txt+'<span class="sortarrow"> </span></a></b>';
}
}
function ts_getInnerText(el) {
if (typeof el == "string") return el;
if (typeof el == "undefined") { return el };
if (el.innerText) return el.innerText; //Not needed but it is faster
var str = "";
var cs = el.childNodes;
var l = cs.length;
for (var i = 0; i < l; i++) {
switch (cs[i].nodeType) {
case 1: //ELEMENT_NODE
str += ts_getInnerText(cs[i]);
break;
case 3: //TEXT_NODE
str += cs[i].nodeValue;
break;
}
}
return str;
}
function ts_resortTable(lnk,clid) {
// get the span
var span;
for (var ci=0;ci<lnk.childNodes.length;ci++) {
if (lnk.childNodes[ci].tagName && lnk.childNodes[ci].tagName.toLowerCase() == 'span') span = lnk.childNodes[ci];
}
var spantext = ts_getInnerText(span);
var td = lnk.parentNode;
var column = clid || td.cellIndex;
var table = getParent(td,'TABLE');
// Work out a type for the column
if (table.rows.length <= 1) return;
var itm = ts_getInnerText(table.rows[1].cells[column]);
sortfn = ts_sort_caseinsensitive;
if (itm.match(/^\d\d[\/-]\d\d[\/-]\d\d\d\d$/)) sortfn = ts_sort_date;
if (itm.match(/^\d\d[\/-]\d\d[\/-]\d\d$/)) sortfn = ts_sort_date;
if (itm.match(/^[$]/)) sortfn = ts_sort_currency;
//if (itm.match(/^[\d\.]+$/)) sortfn = ts_sort_numeric;
if (itm.match(/^[\d\.]+\s*(bytes|b|kb|tb|gb|mb)*$/i)) sortfn = ts_sort_filesize;
// Special cases for our mailbox lists
if (itm.match(/^(None|Empty|Unlimited)$/)) sortfn = ts_sort_filesize;
SORT_COLUMN_INDEX = column;
var firstRow = new Array();
var newRows = new Array();
for (i=0;i<table.rows[0].length;i++) { firstRow[i] = table.rows[0][i]; }
for (j=1;j<table.rows.length;j++) { newRows[j-1] = table.rows[j]; }
newRows.sort(sortfn);
if (span.getAttribute("sortdir") == 'down') {
ARROW = ' ↑';
newRows.reverse();
span.setAttribute('sortdir','up');
} else {
ARROW = ' ↓';
span.setAttribute('sortdir','down');
}
// We appendChild rows that already exist to the tbody, so it moves them rather than creating new ones
// don't do sortbottom rows
for (i=0;i<newRows.length;i++) { if (!newRows[i].className || (newRows[i].className && (newRows[i].className.indexOf('sortbottom') == -1))) table.tBodies[0].appendChild(newRows[i]);}
// do sortbottom rows only
for (i=0;i<newRows.length;i++) { if (newRows[i].className && (newRows[i].className.indexOf('sortbottom') != -1)) table.tBodies[0].appendChild(newRows[i]);}
// Delete any other arrows there may be showing
var allspans = document.getElementsByTagName("span");
for (var ci=0;ci<allspans.length;ci++) {
if (allspans[ci].className == 'sortarrow') {
if (getParent(allspans[ci],"table") == getParent(lnk,"table")) { // in the same table as us?
allspans[ci].innerHTML = ' ';
}
}
}
span.innerHTML = ARROW;
}
function getParent(el, pTagName) {
if (el == null) return null;
else if (el.nodeType == 1 && el.tagName.toLowerCase() == pTagName.toLowerCase()) // Gecko bug, supposed to be uppercase
return el;
else
return getParent(el.parentNode, pTagName);
}
function ts_sort_date(a,b) {
// y2k notes: two digit years less than 50 are treated as 20XX, greater than 50 are treated as 19XX
aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]);
bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]);
if (aa.length == 10) {
dt1 = aa.substr(6,4)+aa.substr(3,2)+aa.substr(0,2);
} else {
yr = aa.substr(6,2);
if (parseInt(yr) < 50) { yr = '20'+yr; } else { yr = '19'+yr; }
dt1 = yr+aa.substr(3,2)+aa.substr(0,2);
}
if (bb.length == 10) {
dt2 = bb.substr(6,4)+bb.substr(3,2)+bb.substr(0,2);
} else {
yr = bb.substr(6,2);
if (parseInt(yr) < 50) { yr = '20'+yr; } else { yr = '19'+yr; }
dt2 = yr+bb.substr(3,2)+bb.substr(0,2);
}
if (dt1==dt2) return 0;
if (dt1<dt2) return -1;
return 1;
}
function ts_sort_currency(a,b) {
aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]).replace(/[^0-9.]/g,'');
bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]).replace(/[^0-9.]/g,'');
return parseFloat(aa) - parseFloat(bb);
}
// handles file sizes, simple numerics, and Unlimited/Empty/None special cases
function ts_sort_filesize(a,b) {
aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]).toLowerCase();
bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]).toLowerCase();
if (aa.length == 0) return -1;
else if (bb.length == 0) return 1;
var regex = /^([\d\.]*|none|empty|unlimited)\s*(bytes|b|kb|tb|gb|mb)?$/i;
matchA = aa.match(regex);
matchB = bb.match(regex);
// Give file size class an integer value, if we don't already have one
if (matchA[1] == 'none') valA = -999;
else if (matchA[1] == 'empty') valA = 0;
else if (matchA[1] == '0') valA = 0;
else if (matchA[1] == 'unlimited') valA = 999;
else if (matchA[2] == 'b' || matchA[2] == 'bytes') valA = 1;
else if (matchA[2] == undefined || matchA[2] == '') valA = 1;
else if (matchA[2] == 'kb') valA = 2;
else if (matchA[2] == 'mb') valA = 3;
else if (matchA[2] == 'gb') valA = 4;
else if (matchA[2] == 'tb') valA = 5;
if (matchB[1] == 'none') valB = -999;
else if (matchB[1] == 'empty') valB = 0;
else if (matchB[1] == '0') valB = 0;
else if (matchB[1] == 'unlimited') valB = 999;
else if (matchB[2] == 'b' || matchB[2] == 'bytes') valB = 1;
else if (matchB[2] == undefined || matchB[2] == '') valB = 1;
else if (matchB[2] == 'kb') valB = 2;
else if (matchB[2] == 'mb') valB = 3;
else if (matchB[2] == 'gb') valB = 4;
else if (matchB[2] == 'tb') valB = 5;
if (valA == valB) {
if ( isNaN(matchA[1])) return -1;
if ( isNaN(matchB[1])) return 1;
// Files are in the same size class kb/gb/mb/etc
// just do a numeric sort on the file size
return matchA[1]-matchB[1];
} else if (valA < valB) {
return -1;
} else if (valA > valB) {
return 1;
}
}
function ts_sort_numeric(a,b) {
aa = parseFloat(ts_getInnerText(a.cells[SORT_COLUMN_INDEX]));
if (isNaN(aa)) aa = 0;
bb = parseFloat(ts_getInnerText(b.cells[SORT_COLUMN_INDEX]));
if (isNaN(bb)) bb = 0;
return aa-bb;
}
function ts_sort_caseinsensitive(a,b) {
aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]).toLowerCase();
bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]).toLowerCase();
if (aa==bb) return 0;
if (aa<bb) return -1;
return 1;
}
function ts_sort_default(a,b) {
aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]);
bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]);
if (aa==bb) return 0;
if (aa<bb) return -1;
return 1;
}
function addEvent(elm, evType, fn, useCapture)
// addEvent and removeEvent
// cross-browser event handling for IE5+, NS6 and Mozilla
// By Scott Andrew
{
if (elm.addEventListener){
elm.addEventListener(evType, fn, useCapture);
return true;
} else if (elm.attachEvent){
var r = elm.attachEvent("on"+evType, fn);
return r;
} else {
alert("Handler could not be removed");
}
}
|
Correct file size sort regexp
|
blue-theme/unauthenticated/sorttable.js
|
Correct file size sort regexp
|
<ide><path>lue-theme/unauthenticated/sorttable.js
<ide> if (itm.match(/^\d\d[\/-]\d\d[\/-]\d\d$/)) sortfn = ts_sort_date;
<ide> if (itm.match(/^[$]/)) sortfn = ts_sort_currency;
<ide> //if (itm.match(/^[\d\.]+$/)) sortfn = ts_sort_numeric;
<del> if (itm.match(/^[\d\.]+\s*(bytes|b|kb|tb|gb|mb)*$/i)) sortfn = ts_sort_filesize;
<add> if (itm.match(/^[\d\.]+\s*(bytes|b|kb|tb|gb|mb)$/i)) sortfn = ts_sort_filesize;
<ide> // Special cases for our mailbox lists
<del> if (itm.match(/^(None|Empty|Unlimited)$/)) sortfn = ts_sort_filesize;
<add> if (itm.match(/^(None|Empty|Unlimited)$/)) sortfn = ts_sort_filesize;
<ide> SORT_COLUMN_INDEX = column;
<ide> var firstRow = new Array();
<ide> var newRows = new Array();
|
|
Java
|
mit
|
3cc585d14305f03cad79e4c586a70857e7cdcf95
| 0 |
ksmonkey123/awaeUtils
|
package ch.awae.utils.statemachine;
import java.util.ArrayList;
import java.util.Objects;
import java.util.UUID;
/**
* Builder for constructing state machine cores. multiple of these builders can
* be combined in a {@link StateMachineBuilder} to construct a state machine.
*
* <p>
* A machine core describes a single state machine with exactly one active state
* at any time. Multiple cores can be combined into a {@link StateMachine} at
* which point they are combined into a state machine cluster with common event
* and command queues.
* </p>
* <p>
* The builder does perform some preliminary data validation on every mutation.
* A full data validation is performed by the {@link StateMachineBuilder}
* whenever a core is added.
* </p>
*
* @author Andreas Wälchli
* @since awaeUtils 0.0.3
* @version 1.3 (0.0.4)
*
* @see StateMachine
* @see StateMachineBuilder
*/
public final class MachineCoreBuilder {
private ArrayList<Transition> transitions = new ArrayList<>();
private String initialState = null;
private final Object LOCK = new Object();
/**
* creates a new empty builder
*/
public MachineCoreBuilder() {
super();
}
/**
* copy constructor
*
* @param builder
* the builder to copy
* @throws NullPointerException
* {@code builder} is {@code null}
* @since 1.2
*/
public MachineCoreBuilder(MachineCoreBuilder builder) {
Objects.requireNonNull(builder);
// copy data
initialState = builder.initialState;
synchronized (builder.LOCK) {
transitions.addAll(builder.transitions);
}
}
/**
* Adds a new transition between two states.
*
* @param from
* the state the transition originates from. may not be
* {@code null}
* @param event
* the event that triggers the transition. may not be
* {@code null}
* @param to
* the state the transition leads to. may be identical to
* {@code from}. may not be {@code null}
* @param events
* an array of all events that shall be triggered by the
* transition. may be {@code null}. no element may be
* {@code null}
* @param commands
* an array of all commands that shall be triggered by the
* transition. may be {@code null}. no element may be
* {@code null}
* @return the builder itself
* @throws NullPointerException
* if any {@code String} parameter or any array element is
* {@code null}
*/
public MachineCoreBuilder addTransition(String from, String event, String to, String[] events, String[] commands) {
// recursive resolution of null arrays
if (events == null)
return addTransition(from, event, to, new String[0], commands);
if (commands == null)
return addTransition(from, event, to, events, new String[0]);
// preliminary input validation
Objects.requireNonNull(from, "'from' may not be null");
Objects.requireNonNull(event, "'event' may not be null");
Objects.requireNonNull(commands, "'commands' may not be null");
// construct command array
Command[] cmds = new Command[events.length + commands.length];
for (int i = 0; i < events.length; i++)
cmds[i] = new Command(CommandType.EVENT,
Objects.requireNonNull(events[i], "'events[" + i + "]' may not be null"));
for (int i = 0; i < commands.length; i++)
cmds[i + events.length] = new Command(CommandType.COMMAND,
Objects.requireNonNull(commands[i], "'commands[" + i + "]' may not be null"));
// add transition
Transition transition = new Transition(from, event, to, cmds);
synchronized (LOCK) {
transitions.add(transition);
}
return this;
}
/**
* Adds a sequence of state transitions with anonymous states for the
* intermediate steps. The triggered events and commands will all be added
* to the last transition in the sequence.
*
* @param from
* the state the transition originates from. may not be
* {@code null}
* @param sequence
* the sequence of events that triggers the transitions. may not
* be {@code null} and must have at least one item.
* @param to
* the state the transition leads to. may be identical to
* {@code from}. may not be {@code null}
* @param events
* an array of all events that shall be triggered by the
* transition. may be {@code null}. no element may be
* {@code null}
* @param commands
* an array of all commands that shall be triggered by the
* transition. may be {@code null}. no element may be
* {@code null}
* @return the builder itself
* @throws NullPointerException
* if any {@code String} parameter or any array element is
* {@code null}
* @throws IllegalArgumentException
* the sequence is empty
* @since 1.3 (0.0.5)
*/
public MachineCoreBuilder addSequence(String from, String[] sequence, String to, String[] events,
String[] commands) {
// recursive resolution of null arrays
if (events == null)
return addSequence(from, sequence, to, new String[0], commands);
if (commands == null)
return addSequence(from, sequence, to, events, new String[0]);
// preliminary input validation
Objects.requireNonNull(from, "'from' may not be null");
Objects.requireNonNull(sequence, "'seqence' may not be null");
Objects.requireNonNull(commands, "'commands' may not be null");
if (sequence.length == 0)
throw new IllegalArgumentException("empty sequence is not allowed");
for (int i = 0; i < sequence.length; i++)
Objects.requireNonNull(sequence[i], "'sequence[" + i + "]' may not be null");
// sequence of length 1 is just a transition
if (sequence.length == 1)
return addTransition(from, sequence[0], to, events, commands);
// build sequence
String state = from;
for (int i = 0; i < sequence.length - 1; i++) {
// intermediate state
String uuid = UUID.randomUUID().toString();
addTransition(state, sequence[i], uuid, null, null);
state = uuid;
}
// build last transition
addTransition(state, sequence[sequence.length - 1], to, events, commands);
return this;
}
/**
* Sets the initial state of the state machine core. The initial state is
* the state the state machine will start at and return to whenever it is
* reset.
*
* @param state
* the initial state. may not be {@code null}
* @return the builder itself
* @throws NullPointerException
* {@code state} is {@code null}
*/
public MachineCoreBuilder setInitialState(String state) {
initialState = Objects.requireNonNull(state, "'state' may not be null");
return this;
}
/**
* creates a copy of this builder instance.
*
* @return a copy
* @since 1.2
* @see #MachineCoreBuilder(MachineCoreBuilder)
*/
public MachineCoreBuilder copy() {
return new MachineCoreBuilder(this);
}
MachineCore build() {
synchronized (LOCK) {
return new MachineCore(initialState, transitions.toArray(new Transition[0]));
}
}
}
|
src/main/java/ch/awae/utils/statemachine/MachineCoreBuilder.java
|
package ch.awae.utils.statemachine;
import java.util.ArrayList;
import java.util.Objects;
/**
* Builder for constructing state machine cores. multiple of these builders can
* be combined in a {@link StateMachineBuilder} to construct a state machine.
*
* <p>
* A machine core describes a single state machine with exactly one active state
* at any time. Multiple cores can be combined into a {@link StateMachine} at
* which point they are combined into a state machine cluster with common event
* and command queues.
* </p>
* <p>
* The builder does perform some preliminary data validation on every mutation.
* A full data validation is performed by the {@link StateMachineBuilder}
* whenever a core is added.
* </p>
*
* @author Andreas Wälchli
* @since awaeUtils 0.0.3
* @version 1.2 (0.0.4)
*
* @see StateMachine
* @see StateMachineBuilder
*/
public final class MachineCoreBuilder {
private ArrayList<Transition> transitions = new ArrayList<>();
private String initialState = null;
private final Object LOCK = new Object();
/**
* creates a new empty builder
*/
public MachineCoreBuilder() {
super();
}
/**
* copy constructor
*
* @param builder
* the builder to copy
* @throws NullPointerException
* {@code builder} is {@code null}
* @since 1.2
*/
public MachineCoreBuilder(MachineCoreBuilder builder) {
Objects.requireNonNull(builder);
// copy data
initialState = builder.initialState;
synchronized (builder.LOCK) {
transitions.addAll(builder.transitions);
}
}
/**
* Adds a new transition between two states.
*
* @param from
* the state the transition originates from. may not be
* {@code null}
* @param event
* the event that triggers the transition. may not be
* {@code null}
* @param to
* the state the transition leads to. may be identical to
* {@code from}. may not be {@code null}
* @param events
* an array of all events that shall be triggered by the
* transition. may be {@code null}. no element may be
* {@code null}
* @param commands
* an array of all commands that shall be triggered by the
* transition. may be {@code null}. no element may be
* {@code null}
* @return the builder itself
* @throws NullPointerException
* if any {@code String} parameter or any array element is
* {@code null}
*/
public MachineCoreBuilder addTransition(String from, String event, String to, String[] events, String[] commands) {
// recursive resolution of null arrays
if (events == null)
return addTransition(from, event, to, new String[0], commands);
if (commands == null)
return addTransition(from, event, to, events, new String[0]);
// preliminary input validation
Objects.requireNonNull(from, "'from' may not be null");
Objects.requireNonNull(event, "'event' may not be null");
Objects.requireNonNull(commands, "'commands' may not be null");
// construct command array
Command[] cmds = new Command[events.length + commands.length];
for (int i = 0; i < events.length; i++)
cmds[i] = new Command(CommandType.EVENT,
Objects.requireNonNull(events[i], "'events[" + i + "]' may not be null"));
for (int i = 0; i < commands.length; i++)
cmds[i + events.length] = new Command(CommandType.COMMAND,
Objects.requireNonNull(commands[i], "'commands[" + i + "]' may not be null"));
// add transition
Transition transition = new Transition(from, event, to, cmds);
synchronized (LOCK) {
transitions.add(transition);
}
return this;
}
/**
* Sets the initial state of the state machine core. The initial state is
* the state the state machine will start at and return to whenever it is
* reset.
*
* @param state
* the initial state. may not be {@code null}
* @return the builder itself
* @throws NullPointerException
* {@code state} is {@code null}
*/
public MachineCoreBuilder setInitialState(String state) {
initialState = Objects.requireNonNull(state, "'state' may not be null");
return this;
}
/**
* creates a copy of this builder instance.
*
* @return a copy
* @since 1.2
* @see #MachineCoreBuilder(MachineCoreBuilder)
*/
public MachineCoreBuilder copy() {
return new MachineCoreBuilder(this);
}
MachineCore build() {
synchronized (LOCK) {
return new MachineCore(initialState, transitions.toArray(new Transition[0]));
}
}
}
|
sequence helper
|
src/main/java/ch/awae/utils/statemachine/MachineCoreBuilder.java
|
sequence helper
|
<ide><path>rc/main/java/ch/awae/utils/statemachine/MachineCoreBuilder.java
<ide>
<ide> import java.util.ArrayList;
<ide> import java.util.Objects;
<add>import java.util.UUID;
<ide>
<ide> /**
<ide> * Builder for constructing state machine cores. multiple of these builders can
<ide> *
<ide> * @author Andreas Wälchli
<ide> * @since awaeUtils 0.0.3
<del> * @version 1.2 (0.0.4)
<add> * @version 1.3 (0.0.4)
<ide> *
<ide> * @see StateMachine
<ide> * @see StateMachineBuilder
<ide> }
<ide>
<ide> /**
<add> * Adds a sequence of state transitions with anonymous states for the
<add> * intermediate steps. The triggered events and commands will all be added
<add> * to the last transition in the sequence.
<add> *
<add> * @param from
<add> * the state the transition originates from. may not be
<add> * {@code null}
<add> * @param sequence
<add> * the sequence of events that triggers the transitions. may not
<add> * be {@code null} and must have at least one item.
<add> * @param to
<add> * the state the transition leads to. may be identical to
<add> * {@code from}. may not be {@code null}
<add> * @param events
<add> * an array of all events that shall be triggered by the
<add> * transition. may be {@code null}. no element may be
<add> * {@code null}
<add> * @param commands
<add> * an array of all commands that shall be triggered by the
<add> * transition. may be {@code null}. no element may be
<add> * {@code null}
<add> * @return the builder itself
<add> * @throws NullPointerException
<add> * if any {@code String} parameter or any array element is
<add> * {@code null}
<add> * @throws IllegalArgumentException
<add> * the sequence is empty
<add> * @since 1.3 (0.0.5)
<add> */
<add> public MachineCoreBuilder addSequence(String from, String[] sequence, String to, String[] events,
<add> String[] commands) {
<add> // recursive resolution of null arrays
<add> if (events == null)
<add> return addSequence(from, sequence, to, new String[0], commands);
<add> if (commands == null)
<add> return addSequence(from, sequence, to, events, new String[0]);
<add>
<add> // preliminary input validation
<add> Objects.requireNonNull(from, "'from' may not be null");
<add> Objects.requireNonNull(sequence, "'seqence' may not be null");
<add> Objects.requireNonNull(commands, "'commands' may not be null");
<add> if (sequence.length == 0)
<add> throw new IllegalArgumentException("empty sequence is not allowed");
<add> for (int i = 0; i < sequence.length; i++)
<add> Objects.requireNonNull(sequence[i], "'sequence[" + i + "]' may not be null");
<add> // sequence of length 1 is just a transition
<add> if (sequence.length == 1)
<add> return addTransition(from, sequence[0], to, events, commands);
<add> // build sequence
<add> String state = from;
<add> for (int i = 0; i < sequence.length - 1; i++) {
<add> // intermediate state
<add> String uuid = UUID.randomUUID().toString();
<add> addTransition(state, sequence[i], uuid, null, null);
<add> state = uuid;
<add> }
<add> // build last transition
<add> addTransition(state, sequence[sequence.length - 1], to, events, commands);
<add> return this;
<add> }
<add>
<add> /**
<ide> * Sets the initial state of the state machine core. The initial state is
<ide> * the state the state machine will start at and return to whenever it is
<ide> * reset.
|
|
Java
|
apache-2.0
|
54a885f2086db8832bfa90e6a151cabb7cc2ac49
| 0 |
dadoz/UnCafe,dadoz/TakeACoffee_v2
|
package com.application.material.takeacoffee.app;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import butterknife.Bind;
import butterknife.ButterKnife;
import com.application.material.takeacoffee.app.adapters.PlacesGridViewAdapter;
import com.application.material.takeacoffee.app.models.CoffeePlace;
import com.application.material.takeacoffee.app.singletons.PlaceApiManager;
import com.application.material.takeacoffee.app.utils.SharedPrefManager;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import static com.application.material.takeacoffee.app.singletons.PlaceApiManager.BAR_PLACE_TYPE;
import static com.application.material.takeacoffee.app.singletons.PlaceApiManager.PLACE_RANKBY;
public class MapActivity extends AppCompatActivity implements OnMapReadyCallback, PlaceApiManager.OnHandlePlaceApiResult {
private static final float ZOOM_LEVEL = 16;
@Bind(R.id.mapToolbarId)
public Toolbar toolbar;
private PlaceApiManager placesApiManager;
private GoogleMap map;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
ButterKnife.bind(this);
placesApiManager = PlaceApiManager
.getInstance(new WeakReference<PlaceApiManager.OnHandlePlaceApiResult>(this),
new WeakReference<>(getApplicationContext()));
initView();
}
/**
* init actionbar
*/
public void initActionBar() {
setSupportActionBar(toolbar);
ActionBar actionbar = getSupportActionBar();
if (actionbar != null) {
actionbar.setDisplayHomeAsUpEnabled(true);
actionbar.setTitle(getString(R.string.map_name));
}
}
/**
* init view
*/
public void initView() {
initActionBar();
initMap();
}
/**
*
*/
private void initMap() {
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
//TODO add marker
//getAsyncMarker();
final String latLngString = SharedPrefManager.getInstance(new WeakReference<>(getApplicationContext()))
.getValueByKey(SharedPrefManager.LATLNG_SHAREDPREF_KEY);
placesApiManager.retrievePlacesAsync(latLngString, PLACE_RANKBY, BAR_PLACE_TYPE);
map = googleMap;
}
/**
*
*/
public void addMarkerOnMap(float lat, float lng, String title) {
if (map != null) {
map.addMarker(new MarkerOptions().position(new LatLng(lat, lng))
.title(title));
}
}
/**
*
* @param lat
* @param lng
*/
private void centerCameraMapOnLatLng(float lat, float lng) {
CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(lat, lng));
map.moveCamera(center);
CameraUpdate zoom = CameraUpdateFactory.zoomTo(ZOOM_LEVEL);
map.animateCamera(zoom);
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public void onPlaceApiSuccess(Object list, PlaceApiManager.RequestType type) {
if (type == PlaceApiManager.RequestType.PLACE_INFO) {
final String pageToken = ((ArrayList<CoffeePlace>) list).get(0).getPageToken().getToken();
if (pageToken != null) {
placesApiManager.retrieveMorePlacesAsync(pageToken);
}
}
setMarkerByCoffeePlaceList((ArrayList<CoffeePlace>) list);
}
/**
*
* @param list
*/
private void setMarkerByCoffeePlaceList(ArrayList<CoffeePlace> list) {
//TODO move to observer
int k = 0;
for (CoffeePlace coffeePlace : list) {
float lat = coffeePlace.getGeometry().getLocation().getLat();
float lng = coffeePlace.getGeometry().getLocation().getLng();
addMarkerOnMap(lat, lng, coffeePlace.getName());
if (k == 0) {
centerCameraMapOnLatLng(lat, lng);
k++;
}
}
}
@Override
public void onEmptyResult() {
}
@Override
public void onErrorResult() {
}
}
|
app/src/main/java/com/application/material/takeacoffee/app/MapActivity.java
|
package com.application.material.takeacoffee.app;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import butterknife.Bind;
import butterknife.ButterKnife;
import com.application.material.takeacoffee.app.models.CoffeePlace;
import com.application.material.takeacoffee.app.singletons.PlaceApiManager;
import com.application.material.takeacoffee.app.utils.SharedPrefManager;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import static com.application.material.takeacoffee.app.singletons.PlaceApiManager.BAR_PLACE_TYPE;
import static com.application.material.takeacoffee.app.singletons.PlaceApiManager.PLACE_RANKBY;
public class MapActivity extends AppCompatActivity implements OnMapReadyCallback, PlaceApiManager.OnHandlePlaceApiResult {
private static final float ZOOM_LEVEL = 16;
@Bind(R.id.mapToolbarId)
public Toolbar toolbar;
private PlaceApiManager placesApiManager;
private GoogleMap map;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
ButterKnife.bind(this);
placesApiManager = PlaceApiManager
.getInstance(new WeakReference<PlaceApiManager.OnHandlePlaceApiResult>(this),
new WeakReference<>(getApplicationContext()));
initView();
}
/**
* init actionbar
*/
public void initActionBar() {
setSupportActionBar(toolbar);
ActionBar actionbar = getSupportActionBar();
if (actionbar != null) {
actionbar.setDisplayHomeAsUpEnabled(true);
actionbar.setTitle(getString(R.string.map_name));
}
}
/**
* init view
*/
public void initView() {
initActionBar();
initMap();
}
/**
*
*/
private void initMap() {
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
//TODO add marker
//getAsyncMarker();
final String latLngString = SharedPrefManager.getInstance(new WeakReference<>(getApplicationContext()))
.getValueByKey(SharedPrefManager.LATLNG_SHAREDPREF_KEY);
placesApiManager.retrievePlacesAsync(latLngString, PLACE_RANKBY, BAR_PLACE_TYPE);
map = googleMap;
}
/**
*
*/
public void addMarkerOnMap(float lat, float lng, String title) {
if (map != null) {
map.addMarker(new MarkerOptions().position(new LatLng(lat, lng))
.title(title));
}
}
/**
*
* @param lat
* @param lng
*/
private void centerCameraMapOnLatLng(float lat, float lng) {
CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(lat, lng));
map.moveCamera(center);
CameraUpdate zoom = CameraUpdateFactory.zoomTo(ZOOM_LEVEL);
map.animateCamera(zoom);
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public void onPlaceApiSuccess(Object list, PlaceApiManager.RequestType type) {
setMarkerByCoffeePlaceList((ArrayList<CoffeePlace>) list);
}
/**
*
* @param list
*/
private void setMarkerByCoffeePlaceList(ArrayList<CoffeePlace> list) {
//TODO move to observer
int k = 0;
for (CoffeePlace coffeePlace : list) {
float lat = coffeePlace.getGeometry().getLocation().getLat();
float lng = coffeePlace.getGeometry().getLocation().getLng();
addMarkerOnMap(lat, lng, coffeePlace.getName());
if (k == 0) {
centerCameraMapOnLatLng(lat, lng);
k++;
}
}
}
@Override
public void onEmptyResult() {
}
@Override
public void onErrorResult() {
}
}
|
added retrieve more places by pageToken and added markers on map
|
app/src/main/java/com/application/material/takeacoffee/app/MapActivity.java
|
added retrieve more places by pageToken and added markers on map
|
<ide><path>pp/src/main/java/com/application/material/takeacoffee/app/MapActivity.java
<ide> import butterknife.Bind;
<ide> import butterknife.ButterKnife;
<ide>
<add>import com.application.material.takeacoffee.app.adapters.PlacesGridViewAdapter;
<ide> import com.application.material.takeacoffee.app.models.CoffeePlace;
<ide> import com.application.material.takeacoffee.app.singletons.PlaceApiManager;
<ide> import com.application.material.takeacoffee.app.utils.SharedPrefManager;
<ide>
<ide> @Override
<ide> public void onPlaceApiSuccess(Object list, PlaceApiManager.RequestType type) {
<add> if (type == PlaceApiManager.RequestType.PLACE_INFO) {
<add> final String pageToken = ((ArrayList<CoffeePlace>) list).get(0).getPageToken().getToken();
<add> if (pageToken != null) {
<add> placesApiManager.retrieveMorePlacesAsync(pageToken);
<add> }
<add> }
<ide> setMarkerByCoffeePlaceList((ArrayList<CoffeePlace>) list);
<ide> }
<ide>
|
|
Java
|
apache-2.0
|
45b19ec46aa80ef7df9196cefd989918b3ad699f
| 0 |
benmccann/pdfbox,mdamt/pdfbox,mdamt/pdfbox,mathieufortin01/pdfbox,veraPDF/veraPDF-pdfbox,ChunghwaTelecom/pdfbox,gavanx/pdflearn,joansmith/pdfbox,ZhenyaM/veraPDF-pdfbox,mathieufortin01/pdfbox,joansmith/pdfbox,torakiki/sambox,torakiki/sambox,BezrukovM/veraPDF-pdfbox,veraPDF/veraPDF-pdfbox,ChunghwaTelecom/pdfbox,ZhenyaM/veraPDF-pdfbox,gavanx/pdflearn,benmccann/pdfbox,BezrukovM/veraPDF-pdfbox
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.pdfbox.pdmodel.graphics.shading;
import java.awt.PaintContext;
import java.awt.Transparency;
import java.awt.color.ColorSpace;
import java.awt.geom.AffineTransform;
import java.awt.image.ColorModel;
import java.awt.image.ComponentColorModel;
import java.awt.image.DataBuffer;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.pdfbox.cos.COSArray;
import org.apache.pdfbox.cos.COSBoolean;
import org.apache.pdfbox.pdmodel.common.function.PDFunction;
import org.apache.pdfbox.pdmodel.graphics.color.PDColorSpace;
import org.apache.pdfbox.util.Matrix;
/**
* AWT PaintContext for radial shading.
*
* Performance improvement done as part of GSoC2014, Tilman Hausherr is the
* mentor.
*
* @author Andreas Lehmkhler
* @author Shaola Ren
*/
public class RadialShadingContext implements PaintContext
{
private static final Log LOG = LogFactory.getLog(RadialShadingContext.class);
private ColorModel outputColorModel;
private PDColorSpace shadingColorSpace;
private PDShadingType3 shading;
private float[] coords;
private float[] domain;
private float[] background;
private int rgbBackground;
private boolean[] extend;
private double x1x0;
private double y1y0;
private double r1r0;
private double x1x0pow2;
private double y1y0pow2;
private double r0pow2;
private float d1d0;
private double denom;
private final double longestDistance;
private int[] colorTable;
/**
* Constructor creates an instance to be used for fill operations.
* @param shading the shading type to be used
* @param cm the color model to be used
* @param xform transformation for user to device space
* @param ctm the transformation matrix
* @param pageHeight height of the current page
*/
public RadialShadingContext(PDShadingType3 shading, ColorModel cm, AffineTransform xform,
Matrix ctm, int pageHeight) throws IOException
{
this.shading = shading;
coords = this.shading.getCoords().toFloatArray();
if (ctm != null)
{
// transform the coords using the given matrix
AffineTransform at = ctm.createAffineTransform();
at.transform(coords, 0, coords, 0, 1);
at.transform(coords, 3, coords, 3, 1);
coords[2] *= ctm.getXScale();
coords[5] *= ctm.getXScale();
}
// transform coords to device space
xform.transform(coords, 0, coords, 0, 1);
xform.transform(coords, 3, coords, 3, 1);
// scale radius to device space
coords[2] *= xform.getScaleX();
coords[5] *= xform.getScaleX();
// get the shading colorSpace
shadingColorSpace = this.shading.getColorSpace();
// create the output colormodel using RGB+alpha as colorspace
ColorSpace outputCS = ColorSpace.getInstance(ColorSpace.CS_sRGB);
outputColorModel = new ComponentColorModel(outputCS, true, false, Transparency.TRANSLUCENT,
DataBuffer.TYPE_BYTE);
// domain values
if (this.shading.getDomain() != null)
{
domain = this.shading.getDomain().toFloatArray();
}
else
{
// set default values
domain = new float[] { 0, 1 };
}
// extend values
COSArray extendValues = this.shading.getExtend();
if (this.shading.getExtend() != null)
{
extend = new boolean[2];
extend[0] = ((COSBoolean) extendValues.get(0)).getValue();
extend[1] = ((COSBoolean) extendValues.get(1)).getValue();
}
else
{
// set default values
extend = new boolean[] { false, false };
}
// calculate some constants to be used in getRaster
x1x0 = coords[3] - coords[0];
y1y0 = coords[4] - coords[1];
r1r0 = coords[5] - coords[2];
x1x0pow2 = Math.pow(x1x0, 2);
y1y0pow2 = Math.pow(y1y0, 2);
r0pow2 = Math.pow(coords[2], 2);
denom = x1x0pow2 + y1y0pow2 - Math.pow(r1r0, 2);
d1d0 = domain[1] - domain[0];
// get background values if available
COSArray bg = shading.getBackground();
if (bg != null)
{
background = bg.toFloatArray();
rgbBackground = convertToRGB(background);
}
longestDistance = getLongestDis();
colorTable = calcColorTable();
}
// get the longest distance of two points which are located on these two circles
private double getLongestDis()
{
double centerToCenter = Math.sqrt(x1x0pow2 + y1y0pow2);
double rmin, rmax;
if (coords[2] < coords[5])
{
rmin = coords[2];
rmax = coords[5];
}
else
{
rmin = coords[5];
rmax = coords[2];
}
if (centerToCenter + rmin <= rmax)
{
return 2 * rmax;
}
else
{
return rmin + centerToCenter + coords[5];
}
}
/**
* Calculate the color on the line connects two circles' centers and store the result in an array.
* @return an array, index denotes the relative position, the corresponding value the color
*/
private int[] calcColorTable()
{
int[] map = new int[(int) longestDistance + 1];
if (longestDistance == 0 || d1d0 == 0)
{
try
{
float[] values = shading.evalFunction(domain[0]);
map[0] = convertToRGB(values);
}
catch (IOException exception)
{
LOG.error("error while processing a function", exception);
}
}
else
{
for (int i = 0; i <= longestDistance; i++)
{
float t = domain[0] + d1d0 * i / (float)longestDistance;
try
{
float[] values = shading.evalFunction(t);
map[i] = convertToRGB(values);
}
catch (IOException exception)
{
LOG.error("error while processing a function", exception);
}
}
}
return map;
}
// convert color to RGB color values
private int convertToRGB(float[] values)
{
float[] rgbValues;
int normRGBValues = 0;
try
{
rgbValues = shadingColorSpace.toRGB(values);
normRGBValues = (int) (rgbValues[0] * 255);
normRGBValues |= (((int) (rgbValues[1] * 255)) << 8);
normRGBValues |= (((int) (rgbValues[2] * 255)) << 16);
}
catch (IOException exception)
{
LOG.error("error processing color space", exception);
}
return normRGBValues;
}
@Override
public void dispose()
{
outputColorModel = null;
shading = null;
shadingColorSpace = null;
}
@Override
public ColorModel getColorModel()
{
return outputColorModel;
}
@Override
public Raster getRaster(int x, int y, int w, int h)
{
// create writable raster
WritableRaster raster = getColorModel().createCompatibleWritableRaster(w, h);
float inputValue = -1;
boolean useBackground;
int[] data = new int[w * h * 4];
for (int j = 0; j < h; j++)
{
for (int i = 0; i < w; i++)
{
useBackground = false;
float[] inputValues = calculateInputValues(x + i, y + j);
if (Float.isNaN(inputValues[0]) && Float.isNaN(inputValues[1]))
{
if (background != null)
{
useBackground = true;
}
else
{
continue;
}
}
else
{
// choose 1 of the 2 values
if (inputValues[0] >= 0 && inputValues[0] <= 1)
{
// both values are in the range -> choose the larger one
if (inputValues[1] >= 0 && inputValues[1] <= 1)
{
inputValue = Math.max(inputValues[0], inputValues[1]);
}
// first value is in the range, the second not -> choose first value
else
{
inputValue = inputValues[0];
}
}
else
{
// first value is not in the range,
// but the second -> choose second value
if (inputValues[1] >= 0 && inputValues[1] <= 1)
{
inputValue = inputValues[1];
}
// both are not in the range
else
{
if (extend[0] && extend[1])
{
inputValue = Math.max(inputValues[0], inputValues[1]);
}
else if (extend[0])
{
inputValue = inputValues[0];
}
else if (extend[1])
{
inputValue = inputValues[1];
}
else if (background != null)
{
useBackground = true;
}
else
{
continue;
}
}
}
// input value is out of range
if (inputValue > 1)
{
// extend shading if extend[1] is true and nonzero radius
if (extend[1] && coords[5] > 0)
{
inputValue = 1;
}
else
{
if (background != null)
{
useBackground = true;
}
else
{
continue;
}
}
}
// input value is out of range
else if (inputValue < 0)
{
// extend shading if extend[0] is true and nonzero radius
if (extend[0] && coords[2] > 0)
{
inputValue = 0;
}
else
{
if (background != null)
{
useBackground = true;
}
else
{
continue;
}
}
}
}
int value;
if (useBackground)
{
// use the given backgound color values
value = rgbBackground;
}
else
{
int key = (int) (inputValue * longestDistance);
value = colorTable[key];
}
int index = (j * w + i) * 4;
data[index] = value & 255;
value >>= 8;
data[index + 1] = value & 255;
value >>= 8;
data[index + 2] = value & 255;
data[index + 3] = 255;
}
}
raster.setPixels(0, 0, w, h, data);
return raster;
}
private float[] calculateInputValues(int x, int y)
{
// According to Adobes Technical Note #5600 we have to do the following
//
// x0, y0, r0 defines the start circle x1, y1, r1 defines the end circle
//
// The parametric equations for the center and radius of the gradient fill circle moving
// between the start circle and the end circle as a function of s are as follows:
//
// xc(s) = x0 + s * (x1 - x0) yc(s) = y0 + s * (y1 - y0) r(s) = r0 + s * (r1 - r0)
//
// Given a geometric coordinate position (x, y) in or along the gradient fill, the
// corresponding value of s can be determined by solving the quadratic constraint equation:
//
// [x - xc(s)]2 + [y - yc(s)]2 = [r(s)]2
//
// The following code calculates the 2 possible values of s
//
double p = -(x - coords[0]) * x1x0 - (y - coords[1]) * y1y0 - coords[2] * r1r0;
double q = (Math.pow(x - coords[0], 2) + Math.pow(y - coords[1], 2) - r0pow2);
double root = Math.sqrt(p * p - denom * q);
float root1 = (float) ((-p + root) / denom);
float root2 = (float) ((-p - root) / denom);
if (denom < 0)
{
return new float[] { root1, root2 };
}
else
{
return new float[] { root2, root1 };
}
}
/**
* Returns the coords values.
* @return the coords values as array
*/
public float[] getCoords()
{
return coords;
}
/**
* Returns the domain values.
* @return the domain values as array
*/
public float[] getDomain()
{
return domain;
}
/**
* Returns the extend values.
* @return the extend values as array
*/
public boolean[] getExtend()
{
return extend;
}
/**
* Returns the function.
*
* @return the function
* @throws IOException if something goes wrong
*/
public PDFunction getFunction() throws IOException
{
return shading.getFunction();
}
}
|
pdfbox/src/main/java/org/apache/pdfbox/pdmodel/graphics/shading/RadialShadingContext.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.pdfbox.pdmodel.graphics.shading;
import java.awt.PaintContext;
import java.awt.Transparency;
import java.awt.color.ColorSpace;
import java.awt.geom.AffineTransform;
import java.awt.image.ColorModel;
import java.awt.image.ComponentColorModel;
import java.awt.image.DataBuffer;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.pdfbox.cos.COSArray;
import org.apache.pdfbox.cos.COSBoolean;
import org.apache.pdfbox.pdmodel.common.function.PDFunction;
import org.apache.pdfbox.pdmodel.graphics.color.PDColorSpace;
import org.apache.pdfbox.util.Matrix;
/**
* AWT PaintContext for radial shading.
*
* Performance improvement done as part of GSoC2014, Tilman Hausherr is the
* mentor.
*
* @author Andreas Lehmkhler
* @author Shaola Ren
*/
public class RadialShadingContext implements PaintContext
{
private static final Log LOG = LogFactory.getLog(RadialShadingContext.class);
private ColorModel outputColorModel;
private PDColorSpace shadingColorSpace;
private PDShadingType3 shading;
private float[] coords;
private float[] domain;
private float[] background;
private int rgbBackground;
private boolean[] extend;
private double x1x0;
private double y1y0;
private double r1r0;
private double x1x0pow2;
private double y1y0pow2;
private double r0pow2;
private float d1d0;
private double denom;
private final double longestDistance;
private int[] colorTable;
/**
* Constructor creates an instance to be used for fill operations.
* @param shading the shading type to be used
* @param cm the color model to be used
* @param xform transformation for user to device space
* @param ctm the transformation matrix
* @param pageHeight height of the current page
*/
public RadialShadingContext(PDShadingType3 shading, ColorModel cm, AffineTransform xform,
Matrix ctm, int pageHeight) throws IOException
{
this.shading = shading;
coords = this.shading.getCoords().toFloatArray();
if (ctm != null)
{
// transform the coords using the given matrix
AffineTransform at = ctm.createAffineTransform();
at.transform(coords, 0, coords, 0, 1);
at.transform(coords, 3, coords, 3, 1);
coords[2] *= ctm.getXScale();
coords[5] *= ctm.getXScale();
}
// transform coords to device space
xform.transform(coords, 0, coords, 0, 1);
xform.transform(coords, 3, coords, 3, 1);
// scale radius to device space
coords[2] *= xform.getScaleX();
coords[5] *= xform.getScaleX();
// get the shading colorSpace
shadingColorSpace = this.shading.getColorSpace();
// create the output colormodel using RGB+alpha as colorspace
ColorSpace outputCS = ColorSpace.getInstance(ColorSpace.CS_sRGB);
outputColorModel = new ComponentColorModel(outputCS, true, false, Transparency.TRANSLUCENT,
DataBuffer.TYPE_BYTE);
// domain values
if (this.shading.getDomain() != null)
{
domain = this.shading.getDomain().toFloatArray();
}
else
{
// set default values
domain = new float[] { 0, 1 };
}
// extend values
COSArray extendValues = this.shading.getExtend();
if (this.shading.getExtend() != null)
{
extend = new boolean[2];
extend[0] = ((COSBoolean) extendValues.get(0)).getValue();
extend[1] = ((COSBoolean) extendValues.get(1)).getValue();
}
else
{
// set default values
extend = new boolean[] { false, false };
}
// calculate some constants to be used in getRaster
x1x0 = coords[3] - coords[0];
y1y0 = coords[4] - coords[1];
r1r0 = coords[5] - coords[2];
x1x0pow2 = Math.pow(x1x0, 2);
y1y0pow2 = Math.pow(y1y0, 2);
r0pow2 = Math.pow(coords[2], 2);
denom = x1x0pow2 + y1y0pow2 - Math.pow(r1r0, 2);
d1d0 = domain[1] - domain[0];
// get background values if available
COSArray bg = shading.getBackground();
if (bg != null)
{
background = bg.toFloatArray();
rgbBackground = convertToRGB(background);
}
longestDistance = getLongestDis();
colorTable = calcColorTable();
}
// get the longest distance of two points which are located on these two circles
private double getLongestDis()
{
double centerToCenter = Math.sqrt(x1x0pow2 + y1y0pow2);
double rmin, rmax;
if (coords[2] < coords[5])
{
rmin = coords[2];
rmax = coords[5];
}
else
{
rmin = coords[5];
rmax = coords[2];
}
if (centerToCenter + rmin <= rmax)
{
return 2 * rmax;
}
else
{
return rmin + centerToCenter + coords[5];
}
}
/**
* Calculate the color on the line connects two circles' centers and store the result in an array.
* @return an array, index denotes the relative position, the corresponding value the color
*/
private int[] calcColorTable()
{
int[] map = new int[(int) longestDistance + 1];
if (longestDistance == 0 || d1d0 == 0)
{
try
{
float[] values = shading.evalFunction(domain[0]);
map[0] = convertToRGB(values);
}
catch (IOException exception)
{
LOG.error("error while processing a function", exception);
}
}
else
{
for (int i = 0; i <= longestDistance; i++)
{
float t = domain[0] + d1d0 * i / (float)longestDistance;
try
{
float[] values = shading.evalFunction(t);
map[i] = convertToRGB(values);
}
catch (IOException exception)
{
LOG.error("error while processing a function", exception);
}
}
}
return map;
}
// convert color to RGB color values
private int convertToRGB(float[] values)
{
float[] rgbValues;
int normRGBValues = 0;
try
{
rgbValues = shadingColorSpace.toRGB(values);
normRGBValues = (int) (rgbValues[0] * 255);
normRGBValues |= (((int) (rgbValues[1] * 255)) << 8);
normRGBValues |= (((int) (rgbValues[2] * 255)) << 16);
}
catch (IOException exception)
{
LOG.error("error processing color space", exception);
}
return normRGBValues;
}
@Override
public void dispose()
{
outputColorModel = null;
shading = null;
shadingColorSpace = null;
}
@Override
public ColorModel getColorModel()
{
return outputColorModel;
}
@Override
public Raster getRaster(int x, int y, int w, int h)
{
// create writable raster
WritableRaster raster = getColorModel().createCompatibleWritableRaster(w, h);
float inputValue = -1;
boolean useBackground;
int[] data = new int[w * h * 4];
for (int j = 0; j < h; j++)
{
for (int i = 0; i < w; i++)
{
useBackground = false;
float[] inputValues = calculateInputValues(x + i, y + j);
if (Float.isNaN(inputValues[0]) && Float.isNaN(inputValues[1]))
{
if (background != null)
{
useBackground = true;
}
else
{
continue;
}
}
else
{
// choose 1 of the 2 values
if (inputValues[0] >= 0 && inputValues[0] <= 1)
{
// both values are in the range -> choose the larger one
if (inputValues[1] >= 0 && inputValues[1] <= 1)
{
inputValue = Math.max(inputValues[0], inputValues[1]);
}
// first value is in the range, the second not -> choose first value
else
{
inputValue = inputValues[0];
}
}
else
{
// first value is not in the range,
// but the second -> choose second value
if (inputValues[1] >= 0 && inputValues[1] <= 1)
{
inputValue = inputValues[1];
}
// both are not in the range
else
{
if (extend[0] && extend[1])
{
inputValue = Math.max(inputValues[0], inputValues[1]);
}
else if (extend[0])
{
inputValue = inputValues[0];
}
else if (extend[1])
{
inputValue = inputValues[1];
}
else if (background != null)
{
useBackground = true;
}
else
{
continue;
}
}
}
// input value is out of range
if (inputValue > 1)
{
// the shading has to be extended if extend[1] == true
if (extend[1])
{
inputValue = 1;
}
else
{
if (background != null)
{
useBackground = true;
}
else
{
continue;
}
}
}
// input value is out of range
else if (inputValue < 0)
{
// the shading has to be extended if extend[0] == true
if (extend[0])
{
inputValue = 0;
}
else
{
if (background != null)
{
useBackground = true;
}
else
{
continue;
}
}
}
}
int value;
if (useBackground)
{
// use the given backgound color values
value = rgbBackground;
}
else
{
int key = (int) (inputValue * longestDistance);
value = colorTable[key];
}
int index = (j * w + i) * 4;
data[index] = value & 255;
value >>= 8;
data[index + 1] = value & 255;
value >>= 8;
data[index + 2] = value & 255;
data[index + 3] = 255;
}
}
raster.setPixels(0, 0, w, h, data);
return raster;
}
private float[] calculateInputValues(int x, int y)
{
// According to Adobes Technical Note #5600 we have to do the following
//
// x0, y0, r0 defines the start circle x1, y1, r1 defines the end circle
//
// The parametric equations for the center and radius of the gradient fill circle moving
// between the start circle and the end circle as a function of s are as follows:
//
// xc(s) = x0 + s * (x1 - x0) yc(s) = y0 + s * (y1 - y0) r(s) = r0 + s * (r1 - r0)
//
// Given a geometric coordinate position (x, y) in or along the gradient fill, the
// corresponding value of s can be determined by solving the quadratic constraint equation:
//
// [x - xc(s)]2 + [y - yc(s)]2 = [r(s)]2
//
// The following code calculates the 2 possible values of s
//
double p = -(x - coords[0]) * x1x0 - (y - coords[1]) * y1y0 - coords[2] * r1r0;
double q = (Math.pow(x - coords[0], 2) + Math.pow(y - coords[1], 2) - r0pow2);
double root = Math.sqrt(p * p - denom * q);
float root1 = (float) ((-p + root) / denom);
float root2 = (float) ((-p - root) / denom);
if (denom < 0)
{
return new float[] { root1, root2 };
}
else
{
return new float[] { root2, root1 };
}
}
/**
* Returns the coords values.
* @return the coords values as array
*/
public float[] getCoords()
{
return coords;
}
/**
* Returns the domain values.
* @return the domain values as array
*/
public float[] getDomain()
{
return domain;
}
/**
* Returns the extend values.
* @return the extend values as array
*/
public boolean[] getExtend()
{
return extend;
}
/**
* Returns the function.
*
* @return the function
* @throws IOException if something goes wrong
*/
public PDFunction getFunction() throws IOException
{
return shading.getFunction();
}
}
|
PDFBOX-1915: extend radial shadings only if radius > 0
git-svn-id: c3ad59981690829a43dc34c293c4e2cd04bcd994@1615145 13f79535-47bb-0310-9956-ffa450edef68
|
pdfbox/src/main/java/org/apache/pdfbox/pdmodel/graphics/shading/RadialShadingContext.java
|
PDFBOX-1915: extend radial shadings only if radius > 0
|
<ide><path>dfbox/src/main/java/org/apache/pdfbox/pdmodel/graphics/shading/RadialShadingContext.java
<ide> // input value is out of range
<ide> if (inputValue > 1)
<ide> {
<del> // the shading has to be extended if extend[1] == true
<del> if (extend[1])
<add> // extend shading if extend[1] is true and nonzero radius
<add> if (extend[1] && coords[5] > 0)
<ide> {
<ide> inputValue = 1;
<ide> }
<ide> // input value is out of range
<ide> else if (inputValue < 0)
<ide> {
<del> // the shading has to be extended if extend[0] == true
<del> if (extend[0])
<add> // extend shading if extend[0] is true and nonzero radius
<add> if (extend[0] && coords[2] > 0)
<ide> {
<ide> inputValue = 0;
<ide> }
|
|
Java
|
apache-2.0
|
bc06ca963017ddd8ba0a595c1ece4ecbbe2610fb
| 0 |
nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/scratch
|
import java.util.*;
public class Droid
{
public Droid (Vector<String> values, boolean debug)
{
_theComputer = new Intcode(values, debug);
_debug = debug;
}
/*
* Move around automatically. TBD.
*/
public void traverse ()
{
}
public void stepTraverse ()
{
boolean finished = false;
while (!finished)
{
_theComputer.executeUntilInput();
LinkedList<String> outputs = _theComputer.getOutputs();
String theOutput = Util.outputToString(outputs);
System.out.println(theOutput);
System.out.println(Commands.getCommands());
finished = true;
}
}
private Intcode _theComputer;
private boolean _debug;
}
|
AdventOfCode/2019/day25/Droid.java
|
import java.util.*;
public class Droid
{
public Droid (Vector<String> values, boolean debug)
{
_theComputer = new Intcode(values, debug);
_debug = debug;
}
/*
* Move around automatically. TBD.
*/
public void traverse ()
{
}
public void stepTraverse ()
{
boolean finished = false;
while (!finished)
{
_theComputer.executeUntilInput();
LinkedList<String> outputs = _theComputer.getOutputs();
String theOutput = Util.outputToString(outputs);
System.out.println(theOutput);
finished = true;
}
}
private Intcode _theComputer;
private boolean _debug;
}
|
Update Droid.java
|
AdventOfCode/2019/day25/Droid.java
|
Update Droid.java
|
<ide><path>dventOfCode/2019/day25/Droid.java
<ide> String theOutput = Util.outputToString(outputs);
<ide>
<ide> System.out.println(theOutput);
<del>
<add> System.out.println(Commands.getCommands());
<add>
<ide> finished = true;
<ide> }
<ide> }
|
|
Java
|
apache-2.0
|
7a6ed4732bbca63e96a1b70e25bdb0bebc7f79f3
| 0 |
mihaip/react-closure-compiler,mihaip/react-closure-compiler,mihaip/react-closure-compiler
|
package info.persistent.react.jscomp;
import info.persistent.jscomp.Debug;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.io.ByteStreams;
import com.google.common.io.Resources;
import com.google.javascript.jscomp.AbstractCommandLineRunner;
import com.google.javascript.jscomp.CheckLevel;
import com.google.javascript.jscomp.CodePrinter;
import com.google.javascript.jscomp.CompilationLevel;
import com.google.javascript.jscomp.Compiler;
import com.google.javascript.jscomp.CompilerOptions;
import com.google.javascript.jscomp.CustomPassExecutionTime;
import com.google.javascript.jscomp.DiagnosticGroups;
import com.google.javascript.jscomp.DiagnosticType;
import com.google.javascript.jscomp.JSError;
import com.google.javascript.jscomp.Result;
import com.google.javascript.jscomp.SourceFile;
import com.google.javascript.jscomp.StrictWarningsGuard;
import com.google.javascript.jscomp.WarningLevel;
import org.junit.Test;
import java.io.IOException;
import java.io.PrintStream;
import java.util.List;
/**
* Test {@link ReactCompilerPass}.
*/
public class ReactCompilerPassTest {
// Used to find the test output (and separate it from the injected API
// aliases source)
private static final String ACTUAL_JS_INPUT_MARKER = "// Input 1\n";
// Used to allow test cases to have multiple input files (so that ES6
// modules can be tested).
private static String FILE_SEPARATOR = "\n\n/* --file-separator-- */\n\n";
private static String REACT_SUPPORT_CODE = "var ReactSupport={" +
"declareMixin(mixin){}," +
"mixin(comp,...mixins){comp.mixins=mixins}" +
"};";
@Test public void testMinimalComponent() {
test(
"var Comp = React.createClass({" +
"render: function() {" +
"return React.createElement(" +
"\"div\", null, React.createElement(\"span\", null, \"child\"));" +
"}" +
"});" +
"ReactDOM.render(React.createElement(Comp), document.body);",
// createClass and other React methods should not get renamed.
"ReactDOM.render(React.createElement(React.createClass({" +
"render:function(){" +
"return React.createElement(" +
"\"div\",null,React.createElement(\"span\",null,\"child\"))" +
"}" +
"})),document.body);");
}
@Test public void testMinimalComponentClass() {
test(
"class Comp extends React.Component {" +
"render() {" +
"return React.createElement(" +
"\"div\", null, React.createElement(\"span\", null, \"child\"));" +
"}" +
"}" +
"ReactDOM.render(React.createElement(Comp), document.body);",
// React.Component and other React methods should not get renamed.
"class $Comp$$ extends React.Component{" +
"render(){" +
"return React.createElement(\"div\",null,React.createElement(\"span\",null,\"child\"))" +
"}" +
"}" +
"ReactDOM.render(React.createElement($Comp$$),document.body);");
// ClassExpression using VariableDeclaration
test(
"var Comp = class extends React.Component {" +
"render() {" +
"return React.createElement(" +
"\"div\", null, React.createElement(\"span\", null, \"child\"));" +
"}" +
"};" +
"ReactDOM.render(React.createElement(Comp), document.body);",
// React.Component and other React methods should not get renamed.
"ReactDOM.render(" +
"React.createElement(" +
"class extends React.Component{" +
"render(){" +
"return React.createElement(\"div\",null,React.createElement(\"span\",null,\"child\"))" +
"}" +
"})," +
"document.body);");
// ClassExpression using AssignmnentExpression
test(
"var Comp;" +
"Comp = class extends React.Component {" +
"render() {" +
"return React.createElement(" +
"\"div\", null, React.createElement(\"span\", null, \"child\"));" +
"}" +
"};" +
"ReactDOM.render(React.createElement(Comp), document.body);",
// React.Component and other React methods should not get renamed.
"ReactDOM.render(" +
"React.createElement(" +
"class extends React.Component{" +
"render(){" +
"return React.createElement(\"div\",null,React.createElement(\"span\",null,\"child\"))" +
"}" +
"})," +
"document.body);");
}
@Test public void testEs6Modules() {
test(
"export const Comp = React.createClass({" +
"render: function() {" +
"return React.createElement(" +
"\"div\", null, React.createElement(\"span\", null, \"child\"));" +
"}" +
"});" +
FILE_SEPARATOR +
// Test that we can use the component and associated types from another
// module (i.e. that exports are generated for them).
"import * as file1 from './file1.js';\n" +
"const /** file1.CompElement */ compElement = React.createElement(file1.Comp);\n" +
"const /** file1.CompInterface */ compInstance = ReactDOM.render(compElement, document.body);",
"const $compElement$$module$src$file2$$=React.createElement(React.createClass({" +
"render:function(){" +
"return React.createElement(" +
"\"div\",null,React.createElement(\"span\",null,\"child\"))" +
"}" +
"}));" +
"ReactDOM.render($compElement$$module$src$file2$$,document.body);");
// Cross-module type checking works for props...
testError(
"export const Comp = React.createClass({" +
"propTypes: {aNumber: React.PropTypes.number.isRequired}," +
"render: function() {return null;}" +
"});\n" +
FILE_SEPARATOR +
"import * as file1 from './file1.js';\n" +
"React.createElement(file1.Comp, {aNumber: 'notANumber'});",
"JSC_TYPE_MISMATCH");
// ...and methods.
testError(
"export const Comp = React.createClass({" +
"render: function() {return null;},\n" +
"/** @param {number} a */" +
"method: function(a) {window.foo = a;}" +
"});\n" +
FILE_SEPARATOR +
"import * as file1 from './file1.js';\n" +
"const inst = ReactDOM.render(" +
"React.createElement(file1.Comp), document.body);\n" +
"inst.method('notanumber');",
"JSC_TYPE_MISMATCH");
}
@Test public void testEs6ModulesClass() {
test(
"export class Comp extends React.Component {" +
"render() {" +
"return React.createElement(" +
"\"div\", null, React.createElement(\"span\", null, \"child\"));" +
"}" +
"}" +
FILE_SEPARATOR +
// Test that we can use the component and associated types from another
// module (i.e. that exports are generated for them).
"import * as file1 from './file1.js';\n" +
"const /** file1.CompElement */ compElement = React.createElement(file1.Comp);\n" +
"const /** file1.Comp */ compInstance = ReactDOM.render(compElement, document.body);",
"class $Comp$$module$src$file1$$ extends React.Component{" +
"render(){" +
"return React.createElement(\"div\",null,React.createElement(\"span\",null,\"child\"))" +
"}" +
"};" +
"const $compElement$$module$src$file2$$=React.createElement($Comp$$module$src$file1$$);" +
"ReactDOM.render($compElement$$module$src$file2$$,document.body);");
// Cross-module type checking works for props...
testError(
"export class Comp extends React.Component {\n" +
"render() {return null;}\n" +
"}\n" +
"Comp.propTypes = {aNumber: React.PropTypes.number.isRequired};" +
FILE_SEPARATOR +
"import * as file1 from './file1.js';\n" +
"React.createElement(file1.Comp, {aNumber: 'notANumber'});",
"JSC_TYPE_MISMATCH");
// ...and methods.
testError(
"export class Comp extends React.Component {" +
"render() {return null;}\n" +
"/** @param {number} a */" +
"method(a) {window.foo = a;}" +
"}\n" +
FILE_SEPARATOR +
"import * as file1 from './file1.js';\n" +
"const inst = ReactDOM.render(" +
"React.createElement(file1.Comp), document.body);\n" +
"inst.method('notanumber');",
"JSC_TYPE_MISMATCH");
}
@Test public void testEs6ModulesScoping() {
// Comp being defined as a local variable in the second file should not
// be confused with the Comp from the first file.
testNoError(
"export const Comp = React.createClass({" +
"propTypes: {children: React.PropTypes.element.isRequired}," +
"render: function() {return null;}" +
"});\n" +
FILE_SEPARATOR +
"import * as file1 from './file1.js';\n" +
"const AnotherComp1 = React.createClass({render() {return null}});\n" +
"const AnotherComp2 = React.createClass({render() {return null}});\n" +
"const Comp = Math.random() < 0.5 ? AnotherComp1 : AnotherComp2;" +
"React.createElement(Comp, {});");
// But Comp can be used as a local variable (and is checked correctly) even
// when it's exported.
testError(
"export const Comp = React.createClass({" +
"propTypes: {aNumber: React.PropTypes.number.isRequired}," +
"render: function() {return null;}" +
"});\n" +
"React.createElement(Comp, {aNumber: 'notANumber'});",
"JSC_TYPE_MISMATCH");
}
@Test public void testEs6ModulesScopingClass() {
// Comp being defined as a local variable in the second file should not
// be confused with the Comp from the first file.
testNoError(
"export class Comp extends React.Component {" +
"render() {return null;}" +
"}\n" +
"Comp.propTypes = {children: React.PropTypes.element.isRequired};" +
FILE_SEPARATOR +
"import * as file1 from './file1.js';\n" +
"const AnotherComp1 = React.createClass({render() {return null}});\n" +
"const AnotherComp2 = React.createClass({render() {return null}});\n" +
"const Comp = Math.random() < 0.5 ? AnotherComp1 : AnotherComp2;" +
"React.createElement(Comp, {});");
// But Comp can be used as a local variable (and is checked correctly) even
// when it's exported.
testError(
"export class Comp extends React.Component {" +
"render() {return null;}" +
"}\n" +
"Comp.propTypes = {aNumber: React.PropTypes.number.isRequired};" +
"React.createElement(Comp, {aNumber: 'notANumber'});",
"JSC_TYPE_MISMATCH");
}
@Test public void testEs6ModulesMixins() {
// Mixin references across modules work
testNoError(
"export const Mixin = React.createMixin({" +
"mixinMethod: function() {window.foo = 123}" +
"});\n" +
FILE_SEPARATOR +
"import * as file1 from './file1.js';\n" +
"export const Comp = React.createClass({" +
"mixins: [file1.Mixin]," +
"render: function() {" +
"this.mixinMethod();" +
"return React.createElement(\"div\");" +
"}" +
"});");
// Mixins can be imported directly
testNoError(
"export const Mixin = React.createMixin({" +
"mixinMethod: function() {window.foo = 123}" +
"});\n" +
FILE_SEPARATOR +
"import {Mixin} from './file1.js';\n" +
"export const Comp = React.createClass({" +
"mixins: [Mixin]," +
"render: function() {" +
"this.mixinMethod();" +
"return React.createElement(\"div\");" +
"}" +
"});");
// Or under a different name
testNoError(
"export const Mixin = React.createMixin({" +
"mixinMethod: function() {window.foo = 123}" +
"});\n" +
FILE_SEPARATOR +
"import {Mixin as m} from './file1.js';\n" +
"export const Comp = React.createClass({" +
"mixins: [m]," +
"render: function() {" +
"this.mixinMethod();" +
"return React.createElement(\"div\");" +
"}" +
"});");
// Mixin references can be chained too.
testNoError(
"export const Mixin1 = React.createMixin({" +
"mixinMethod1: function() {window.foo = 123}" +
"});\n" +
FILE_SEPARATOR +
"import * as file1 from './file1.js';\n" +
"export const Mixin2 = React.createMixin({" +
"mixins: [file1.Mixin1]," +
"mixinMethod2: function() {window.foo = 123}" +
"});\n" +
FILE_SEPARATOR +
"import * as file2 from './file2.js';\n" +
"export const Comp = React.createClass({" +
"mixins: [file2.Mixin2]," +
"render: function() {" +
"this.mixinMethod1();" +
"this.mixinMethod2();" +
"return React.createElement(\"div\");" +
"}" +
"});");
// propTypes from imported mixins are handled correctly
testNoError(
"export const Mixin = React.createMixin({" +
"propTypes: {" +
"mixinFuncProp: React.PropTypes.func.isRequired" +
"}" +
"});\n" +
FILE_SEPARATOR +
"import * as file1 from './file1.js';\n" +
"var Comp = React.createClass({" +
"mixins: [file1.Mixin],\n" +
"render: function() {return this.props.mixinFuncProp();}" +
"});\n");
// Including those that reference types from the mixin's file
testNoError(
"export const Obj = class {};\n" +
"export const Mixin = React.createMixin({" +
"propTypes: {" +
"mixinProp: React.PropTypes.instanceOf(Obj).isRequired" +
"}" +
"});\n" +
FILE_SEPARATOR +
"import * as file1 from './file1.js';\n" +
"var Comp = React.createClass({" +
"mixins: [file1.Mixin],\n" +
"render: function() {return null;}" +
"});\n");
}
@Test public void testEs6ModulesMixinsClass() {
// Mixin references across modules work
testNoError(
REACT_SUPPORT_CODE +
"export class Mixin extends React.Component {" +
"mixinMethod() {window.foo = 123}" +
"}" +
"ReactSupport.declareMixin(Mixin);" +
FILE_SEPARATOR +
REACT_SUPPORT_CODE +
"import * as file1 from './file1.js';\n" +
"export class Comp extends React.Component {" +
"render() {" +
"this.mixinMethod();" +
"return React.createElement(\"div\");" +
"}" +
"}" +
"ReactSupport.mixin(Comp, file1.Mixin);");
// Mixins can be imported directly
testNoError(
REACT_SUPPORT_CODE +
"export class Mixin extends React.Component {" +
"mixinMethod() {window.foo = 123}" +
"}" +
"ReactSupport.declareMixin(Mixin);" +
FILE_SEPARATOR +
REACT_SUPPORT_CODE +
"import {Mixin} from './file1.js';" +
"export class Comp extends React.Component {" +
"render() {" +
"this.mixinMethod();" +
"return React.createElement(\"div\");" +
"}" +
"}" +
"ReactSupport.mixin(Comp, Mixin);");
// Make sure we can use the mixin twice without adding an import twice
testNoError(
REACT_SUPPORT_CODE +
"export class Mixin extends React.Component {" +
"mixinMethod() {window.foo = 123}" +
"}" +
"ReactSupport.declareMixin(Mixin);" +
FILE_SEPARATOR +
REACT_SUPPORT_CODE +
"import {Mixin} from './file1.js';" +
"export class Comp extends React.Component {" +
"render() {" +
"this.mixinMethod();" +
"return React.createElement(\"div\");" +
"}" +
"}" +
"ReactSupport.mixin(Comp, Mixin);" +
"export class Comp2 extends React.Component {" +
"render() {" +
"this.mixinMethod();" +
"return null;" +
"}" +
"}" +
"ReactSupport.mixin(Comp2, Mixin);");
// Or under a different name
testNoError(
REACT_SUPPORT_CODE +
"export class Mixin extends React.Component {" +
"mixinMethod() {window.foo = 123}" +
"}" +
"ReactSupport.declareMixin(Mixin);" +
FILE_SEPARATOR +
REACT_SUPPORT_CODE +
"import {Mixin as m} from './file1.js';\n" +
"export class Comp extends React.Component {" +
"render() {" +
"this.mixinMethod();" +
"return React.createElement(\"div\");" +
"}" +
"}" +
"ReactSupport.mixin(Comp, m);");
// Mixin references can be chained too.
testNoError(
REACT_SUPPORT_CODE +
"export class Mixin1 extends React.Component {" +
"mixinMethod1() {window.foo = 123}" +
"}" +
"ReactSupport.declareMixin(Mixin1);" +
FILE_SEPARATOR +
REACT_SUPPORT_CODE +
"import * as file1 from './file1.js';\n" +
"export class Mixin2 extends React.Component {" +
"mixinMethod2() {window.foo = 123}" +
"}" +
"ReactSupport.declareMixin(Mixin2);" +
"ReactSupport.mixin(Mixin2, file1.Mixin1);" +
FILE_SEPARATOR +
REACT_SUPPORT_CODE +
"import * as file2 from './file2.js';\n" +
"export class Comp extends React.Component {" +
"render() {" +
"this.mixinMethod1();" +
"this.mixinMethod2();" +
"return React.createElement(\"div\");" +
"}" +
"}" +
"ReactSupport.mixin(Comp, file2.Mixin2);");
// propTypes from imported mixins are handled correctly
testNoError(
REACT_SUPPORT_CODE +
"export class Mixin extends React.Component {}" +
"ReactSupport.declareMixin(Mixin);" +
"Mixin.propTypes = {" +
"mixinFuncProp: React.PropTypes.func.isRequired" +
"};" +
FILE_SEPARATOR +
REACT_SUPPORT_CODE +
"import * as file1 from './file1.js';" +
"class Comp extends React.Component {" +
"render() {return this.props.mixinFuncProp();}" +
"}" +
"ReactSupport.mixin(Comp, file1.Mixin);");
// Including those that reference types from the mixin's file
testNoError(
REACT_SUPPORT_CODE +
"export const Obj = class {};\n" +
"export class Mixin extends React.Component {}" +
"ReactSupport.declareMixin(Mixin);" +
"Mixin.propTypes = {" +
"mixinProp: React.PropTypes.instanceOf(Obj).isRequired" +
"};" +
FILE_SEPARATOR +
REACT_SUPPORT_CODE +
"import * as file1 from './file1.js';\n" +
"class Comp extends React.Component {" +
"render() {return null;}" +
"}" +
"ReactSupport.mixin(Comp, file1.Mixin);");
}
@Test public void testInstanceMethods() {
test(
"var Comp = React.createClass({" +
"render: function() {return React.createElement(\"div\");}," +
"method: function() {window.foo = 123;}" +
"});" +
"var inst = ReactDOM.render(React.createElement(Comp), document.body);" +
"inst.method();",
// Method invocations should not result in warnings if they're known.
"ReactDOM.render(React.createElement(React.createClass({" +
"render:function(){return React.createElement(\"div\")}," +
"$method$:function(){window.$foo$=123}" +
"})),document.body).$method$();");
test(
"var Comp = React.createClass({" +
"render: function() {return React.createElement(\"div\");}," +
"/** @private */" +
"privateMethod1_: function(a) {window.foo = 123 + a;}," +
"/** @private */" +
"privateMethod2_: function() {this.privateMethod1_(1);}" +
"});" +
"ReactDOM.render(React.createElement(Comp), document.body);",
// Private methods should be invokable.
"ReactDOM.render(React.createElement(React.createClass({" +
"render:function(){return React.createElement(\"div\")}," +
"$privateMethod1_$:function($a$jscomp$1$$){window.$foo$=123+$a$jscomp$1$$}," +
"$privateMethod2_$:function(){this.$privateMethod1_$(1)}" +
"})),document.body);");
testError(
"var Comp = React.createClass({" +
"render: function() {return React.createElement(\"div\");}," +
"/** @param {number} a */" +
"method: function(a) {window.foo = a;}" +
"});" +
"var inst = ReactDOM.render(React.createElement(Comp), document.body);" +
"inst.method('notanumber');",
// Their arguments should be validated.
"JSC_TYPE_MISMATCH");
testError(
"var Comp = React.createClass({" +
"render: function() {return React.createElement(\"div\");}" +
"});" +
"var inst = ReactDOM.render(React.createElement(Comp), document.body);" +
"inst.unknownMethod()",
// And unknown methods should be flagged.
"JSC_INEXISTENT_PROPERTY");
}
@Test public void testInstanceMethodsClass() {
test(
"class Comp extends React.Component {" +
"render() {return React.createElement(\"div\");}" +
"method() {window.foo = 123;}" +
"}" +
"var inst = ReactDOM.render(React.createElement(Comp), document.body);" +
"inst.method();",
// Method invocations should not result in warnings if they're known.
"class $Comp$$ extends React.Component{" +
"render(){return React.createElement(\"div\")}" +
"}" +
"ReactDOM.render(React.createElement($Comp$$),document.body);" +
"window.$foo$=123;");
test(
"class Comp extends React.Component {" +
"render() {return React.createElement(\"div\");}" +
"/** @private */" +
"privateMethod1_(a) {window.foo = 123 + a;}" +
"/** @private */" +
"privateMethod2_() {this.privateMethod1_(1);}" +
"}" +
"ReactDOM.render(React.createElement(Comp), document.body);",
// Private methods should be invokable.
"class $Comp$$ extends React.Component{" +
"render(){return React.createElement(\"div\")}"+
"}" +
"ReactDOM.render(React.createElement($Comp$$),document.body);");
testError(
"class Comp extends React.Component {" +
"render() {return React.createElement(\"div\");}" +
"/** @param {number} a */" +
"method(a) {window.foo = a;}" +
"}" +
"var inst = ReactDOM.render(React.createElement(Comp), document.body);" +
"inst.method('notanumber');",
// Their arguments should be validated.
"JSC_TYPE_MISMATCH");
testError(
"class Comp extends React.Component {" +
"render() {return React.createElement(\"div\");}" +
"}" +
"var inst = ReactDOM.render(React.createElement(Comp), document.body);" +
"inst.unknownMethod()",
// And unknown methods should be flagged.
"JSC_INEXISTENT_PROPERTY");
}
@Test public void testMixins() {
test(
"var ChainedMixin = React.createMixin({" +
"chainedMixinMethod: function() {window.foo = 456}" +
"});\n" +
"var Mixin = React.createMixin({" +
"mixins: [ChainedMixin]," +
"mixinMethod: function() {window.foo = 123}" +
"});\n" +
"var Comp = React.createClass({" +
"mixins: [Mixin]," +
"render: function() {" +
"this.mixinMethod();" +
"this.chainedMixinMethod();" +
"return React.createElement(\"div\");" +
"}" +
"});" +
"var inst = ReactDOM.render(React.createElement(Comp), document.body);" +
"inst.mixinMethod();" +
"inst.chainedMixinMethod();",
// Mixin method invocations should not result in warnings if they're
// known, either directly or via chained mixins.
"var $inst$$=ReactDOM.render(React.createElement(React.createClass({" +
"mixins:[{" +
"mixins:[{" +
"$chainedMixinMethod$:function(){window.$foo$=456}" +
"}]," +
"$mixinMethod$:function(){window.$foo$=123}" +
"}]," +
"render:function(){" +
"this.$mixinMethod$();" +
"this.$chainedMixinMethod$();" +
"return React.createElement(\"div\")" +
"}" +
"})),document.body);" +
"$inst$$.$mixinMethod$();" +
"$inst$$.$chainedMixinMethod$();");
test(
"var Mixin = React.createMixin({" +
"mixinMethod: function() {window.foo=this.mixinAbstractMethod()}" +
"});" +
"/** @return {number} @protected */" +
"Mixin.mixinAbstractMethod;" +
"var Comp = React.createClass({" +
"mixins: [Mixin]," +
"render: function() {" +
"this.mixinMethod();" +
"return React.createElement(\"div\");" +
"}," +
"mixinAbstractMethod: function() {return 123;}" +
"});" +
"ReactDOM.render(React.createElement(Comp), document.body);",
// Mixins can support abstract methods via additional properties.
"ReactDOM.render(React.createElement(React.createClass({" +
"mixins:[{" +
"$mixinMethod$:function(){window.$foo$=123}" +
"}]," +
"render:function(){" +
"this.$mixinMethod$();" +
"return React.createElement(\"div\")" +
"}," +
"$mixinAbstractMethod$:function(){return 123}" +
"})),document.body);");
testError(
"var Mixin = React.createMixin({" +
"/** @param {number} a */" +
"mixinMethod: function(a) {window.foo = 123}" +
"});\n" +
"var Comp = React.createClass({" +
"mixins: [Mixin]," +
"render: function() {" +
"this.mixinMethod(\"notanumber\");" +
"return React.createElement(\"div\");" +
"}" +
"});" +
"var inst = ReactDOM.render(React.createElement(Comp), document.body);" +
"inst.mixinMethod(\"notanumber\");",
// Mixin methods should have their parameter types check when invoked from
// the component.
"JSC_TYPE_MISMATCH");
testError(
"var Mixin = React.createMixin({" +
"/** @private */" +
"privateMixinMethod_: function() {}" +
"});\n" +
"var Comp = React.createClass({" +
"mixins: [Mixin]," +
"render: function() {" +
"this.privateMixinMethod_();" +
"return null;" +
"}" +
"});",
// Private mixin methods should not be exposed to the component.
"JSC_INEXISTENT_PROPERTY");
testError(
"var Mixin = React.createMixin({" +
"mixinMethod: function() {" +
"window.foo = this.mixinAbstractMethod().noSuchMethod()" +
"}" +
"});" +
"/** @return {number} */" +
"Mixin.mixinAbstractMethod;" +
"var Comp = React.createClass({" +
"mixins: [Mixin]," +
"render: function() {" +
"this.mixinMethod();" +
"return React.createElement(\"div\");" +
"}," +
"mixinAbstractMethod: function() {return 123;}" +
"});",
// Abstract methods have their types checked too, on both the mixin
// side...
"JSC_INEXISTENT_PROPERTY");
testError(
"var Mixin = React.createMixin({" +
"mixinMethod: function() {window.foo = this.mixinAbstractMethod()}" +
"});" +
"/** @return {number} */" +
"Mixin.mixinAbstractMethod;" +
"var Comp = React.createClass({" +
"mixins: [Mixin]," +
"render: function() {" +
"this.mixinMethod();" +
"return React.createElement(\"div\");" +
"}," +
"mixinAbstractMethod: function() {return \"notanumber\";}" +
"});",
// ...and the component side
"JSC_TYPE_MISMATCH");
test(
"var Mixin = React.createMixin({});" +
"/** @param {number} param1 */" +
"Mixin.mixinAbstractMethod;" +
"var Comp = React.createClass({" +
"mixins: [Mixin]," +
"render: function() {" +
"return React.createElement(\"div\");" +
"}," +
"mixinAbstractMethod: function() {}" +
"});",
// But implementations should be OK if they omit parameters...
"");
test(
"var Mixin = React.createMixin({});" +
"/** @param {number} param1 */" +
"Mixin.mixinAbstractMethod;" +
"var Comp = React.createClass({" +
"mixins: [Mixin]," +
"render: function() {" +
"return React.createElement(\"div\");" +
"}," +
"mixinAbstractMethod: function(renamedParam1) {}" +
"});",
// ...or rename them.
"");
test(
"var Mixin = React.createMixin({});" +
"/**\n" +
" * @param {T} param1\n" +
" * @return {T}\n" +
" * @template T\n" +
" */" +
"Mixin.mixinAbstractMethod;" +
"var Comp = React.createClass({" +
"mixins: [Mixin]," +
"render: function() {" +
"return React.createElement(\"div\");" +
"}," +
"mixinAbstractMethod: function(param1) {return param1}" +
"});",
// Template types are copied over.
"");
}
@Test public void testMixinsClass() {
testError(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {}" +
"ReactSupport.declareMixin(42);",
"DECLARE_MIXIN_PARAM_NOT_VALID");
testError(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {}" +
"ReactSupport.declareMixin(x, y);",
"DECLARE_MIXIN_UNEXPECTED_NUMBER_OF_PARAMS");
testError(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {}" +
"ReactSupport.declareMixin();",
"DECLARE_MIXIN_UNEXPECTED_NUMBER_OF_PARAMS");
testError(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {}" +
"ReactSupport.declareMixin(Unknown);",
"REACT_MIXIN_UNKNOWN");
testError(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {}" +
"ReactSupport.mixin();",
"MIXIN_UNEXPECTED_NUMBER_OF_PARAMS");
testError(
REACT_SUPPORT_CODE +
"class Comp extends React.Component {}" +
"ReactSupport.mixin(Comp);",
"MIXIN_UNEXPECTED_NUMBER_OF_PARAMS");
test(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {}" +
"ReactSupport.declareMixin(Mixin);" +
"class Comp extends React.Component {}" +
"ReactSupport.mixin(Comp, Mixin);",
"");
test(
REACT_SUPPORT_CODE +
"class MixinA extends React.Component {}" +
"ReactSupport.declareMixin(MixinA);" +
"class MixinB extends React.Component {}" +
"ReactSupport.declareMixin(MixinB);" +
"class Comp extends React.Component {}" +
"ReactSupport.mixin(Comp, MixinA, MixinB);",
"");
testError(
REACT_SUPPORT_CODE +
"class Comp extends React.Component {}" +
"class NotAMixin extends React.Component {}" +
"ReactSupport.mixin(Comp, NotAMixin);",
"MIXIN_PARAM_IS_NOT_MIXIN");
// It is a bit surprising that Closure Compiler can inline this. It probably
// works because there is only one implementation of the method.
test(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {" +
"/** @return {*} */" +
"mixinMethod() {window.foo=this.mixinAbstractMethod()}" +
"}" +
"ReactSupport.declareMixin(Mixin);" +
"/** @return {number} @protected */" +
"Mixin.mixinAbstractMethod;" +
"class Comp extends React.Component {" +
"mixinAbstractMethod() {" +
"return 42;" +
"}" +
"}" +
"ReactSupport.mixin(Comp, Mixin);" +
"var inst = ReactDOM.render(React.createElement(Comp), document.body);" +
"inst.mixinMethod();",
"class $Mixin$$ extends React.Component{}" +
"class $Comp$$ extends React.Component{}" +
"$Comp$$.mixins=[$Mixin$$];" +
"ReactDOM.render(React.createElement($Comp$$),document.body);" +
"window.$foo$=42;");
test(
REACT_SUPPORT_CODE +
"class ChainedMixin extends React.Component {" +
"chainedMixinMethod() {window.foo = 456}" +
"}" +
"ReactSupport.declareMixin(ChainedMixin);" +
"class Mixin extends React.Component {" +
"mixinMethod() {window.foo = 123}" +
"}" +
"ReactSupport.declareMixin(Mixin);" +
"ReactSupport.mixin(Mixin, ChainedMixin);" +
"class Comp extends React.Component {" +
"render() {" +
"this.mixinMethod();" +
"this.chainedMixinMethod();" +
"return React.createElement(\"div\");" +
"}" +
"}" +
"ReactSupport.mixin(Comp, Mixin);" +
"var inst = ReactDOM.render(React.createElement(Comp), document.body);" +
"inst.mixinMethod();" +
"inst.chainedMixinMethod();",
// Mixin method invocations should not result in warnings if they're
// known, either directly or via chained mixins.
"class $ChainedMixin$$ extends React.Component{}" +
"class $Mixin$$ extends React.Component{}" +
"$Mixin$$.mixins=[$ChainedMixin$$];" +
"class $Comp$$ extends React.Component{" +
"render(){" +
"window.$foo$=456;" +
"return React.createElement(\"div\")" +
"}" +
"}" +
"$Comp$$.mixins=[$Mixin$$];" +
"ReactDOM.render(React.createElement($Comp$$),document.body);" +
"window.$foo$=123;" +
"window.$foo$=456;");
test(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {" +
"mixinMethod() {window.foo=this.mixinAbstractMethod()}" +
"}" +
"ReactSupport.declareMixin(Mixin);" +
"/** @return {number} @protected */" +
"Mixin.mixinAbstractMethod;" +
"class Comp extends React.Component {" +
"render() {" +
"this.mixinMethod();" +
"return React.createElement(\"div\");" +
"}" +
"mixinAbstractMethod() {return 123;}" +
"}" +
"ReactSupport.mixin(Comp, Mixin);" +
"ReactDOM.render(React.createElement(Comp), document.body);",
// Mixins can support abstract methods via additional properties.
"class $Mixin$$ extends React.Component{}" +
"class $Comp$$ extends React.Component{" +
"render(){" +
"window.$foo$=123;" +
"return React.createElement(\"div\")" +
"}" +
"}" +
"$Comp$$.mixins=[$Mixin$$];" +
"ReactDOM.render(React.createElement($Comp$$),document.body);");
testError(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {" +
"/** @param {number} a */" +
"mixinMethod(a) {window.foo = 123}" +
"}" +
"ReactSupport.declareMixin(Mixin);" +
"class Comp extends React.Component {" +
"render() {" +
"this.mixinMethod(\"notanumber\");" +
"return React.createElement(\"div\");" +
"}" +
"}" +
"ReactSupport.mixin(Comp, Mixin);" +
"var inst = ReactDOM.render(React.createElement(Comp), document.body);" +
"inst.mixinMethod(\"notanumber\");",
// Mixin methods should have their parameter types check when invoked from
// the component.
"JSC_TYPE_MISMATCH");
testError(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {" +
"/** @private */" +
"privateMixinMethod_() {}" +
"}" +
"ReactSupport.declareMixin(Mixin);" +
"class Comp extends React.Component {" +
"render() {" +
"this.privateMixinMethod_();" +
"return null;" +
"}" +
"}" +
"ReactSupport.mixin(Comp, Mixin);",
// Private mixin methods should not be exposed to the component.
"JSC_INEXISTENT_PROPERTY");
testError(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {" +
"mixinMethod() {" +
"window.foo = this.mixinAbstractMethod().noSuchMethod()" +
"}" +
"}" +
"ReactSupport.declareMixin(Mixin);" +
"/** @return {number} */" +
"Mixin.mixinAbstractMethod;" +
"class Comp extends React.Component {" +
"render() {" +
"this.mixinMethod();" +
"return React.createElement(\"div\");" +
"}" +
"mixinAbstractMethod() {return 123;}" +
"}" +
"ReactSupport.mixin(Comp, Mixin);",
// Abstract methods have their types checked too, on both the mixin
// side...
"JSC_INEXISTENT_PROPERTY");
testError(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {" +
"mixinMethod() {window.foo = this.mixinAbstractMethod()}" +
"}" +
"ReactSupport.declareMixin(Mixin);" +
"/** @return {number} */" +
"Mixin.mixinAbstractMethod;" +
"class Comp extends React.Component {" +
"render() {" +
"this.mixinMethod();" +
"return React.createElement(\"div\");" +
"}" +
"mixinAbstractMethod() {return \"notanumber\";}" +
"}" +
"ReactSupport.mixin(Comp, Mixin);",
// ...and the component side
"JSC_TYPE_MISMATCH");
test(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {}" +
"ReactSupport.declareMixin(Mixin);" +
"/** @param {number} param1 */" +
"Mixin.mixinAbstractMethod;" +
"class Comp extends React.Component {" +
"render() {" +
"return React.createElement(\"div\");" +
"}" +
"mixinAbstractMethod() {}" +
"}" +
"ReactSupport.mixin(Comp, Mixin);",
// But implementations should be OK if they omit parameters...
"");
test(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {}" +
"ReactSupport.declareMixin(Mixin);" +
"/** @param {number} param1 */" +
"Mixin.mixinAbstractMethod;" +
"class Comp extends React.Component {" +
"render() {" +
"return React.createElement(\"div\");" +
"}" +
"mixinAbstractMethod(renamedParam1) {}" +
"}" +
"ReactSupport.mixin(Comp, Mixin);",
// ...or rename them.
"");
test(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {}" +
"ReactSupport.declareMixin(Mixin);" +
"/**\n" +
" * @param {T} param1\n" +
" * @return {T}\n" +
" * @template T\n" +
" */" +
"Mixin.mixinAbstractMethod;" +
"class Comp extends React.Component {" +
"render() {" +
"return React.createElement(\"div\");" +
"}" +
"mixinAbstractMethod(param1) {return param1}" +
"}" +
"ReactSupport.mixin(Comp, Mixin);",
// Template types are copied over.
"");
}
@Test public void testMixinOnExportClass() {
// The real error here was that SymbolTable uses a HashMap but we need an
// Map that iterates in the insertion order.
testNoError(
REACT_SUPPORT_CODE +
"class TestMixin extends React.Component {" +
"/** @return {string} */" +
"d1() {" +
"return \"M12\";" +
"}" +
"}" +
"ReactSupport.declareMixin(TestMixin);" +
"export class AddCommentIcon extends React.Component {" +
"/** @override */" +
"render() {" +
"this.d1();" +
"return null;" +
"}" +
"}" +
"ReactSupport.mixin(AddCommentIcon, TestMixin);");
}
@Test public void testMixinImplementsClass() {
test(
REACT_SUPPORT_CODE +
"/** @interface */" +
"class I {" +
"/**\n" +
" *@param {number} x\n" +
" *@return {string} x\n" +
" */\n" +
"m(x) {}" +
"}" +
"/** @implements {I} */" +
"class Mixin extends React.Component {" +
"/** @override */" +
"m(x) { return \"x\"; }" +
"}" +
"ReactSupport.declareMixin(Mixin);" +
"class Comp extends React.Component {}" +
"ReactSupport.mixin(Comp, Mixin);",
"");
}
@Test public void testMixinsRepeatedMethods() {
test(
"var Mixin = React.createMixin({" +
"componentDidMount: function() {}" +
"});\n" +
"var Comp = React.createClass({" +
"mixins: [Mixin]," +
"componentDidMount: function() {}," +
"render: function() {" +
"return React.createElement(\"div\");" +
"}" +
"});",
// It's OK for a base class to redefine a mixin's method component
// lifecycle method.
"");
}
@Test public void testMixinsRepeatedMethodsClass() {
test(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {" +
"componentDidMount() {}" +
"}" +
"ReactSupport.declareMixin(Mixin);" +
"class Comp extends React.Component {" +
"componentDidMount() {}" +
"render() {" +
"return React.createElement(\"div\");" +
"}" +
"}" +
"ReactSupport.mixin(Comp, Mixin);",
// It's OK for a base class to redefine a mixin's method component
// lifecycle method.
"");
}
@Test public void testNamespacedComponent() {
test(
"var ns = {};ns.Comp = React.createClass({" +
"render: function() {return React.createElement(\"div\");}" +
"});" +
"ReactDOM.render(React.createElement(ns.Comp), document.body);",
"ReactDOM.render(React.createElement(React.createClass({" +
"render:function(){return React.createElement(\"div\")}" +
"})),document.body);");
}
@Test public void testNamespacedComponentClass() {
test(
"var ns = {};ns.Comp = class extends React.Component {" +
"render() {return React.createElement(\"div\");}" +
"};" +
"ReactDOM.render(React.createElement(ns.Comp), document.body);",
"ReactDOM.render(React.createElement(" +
"class extends React.Component{" +
"render(){" +
"return React.createElement(\"div\")" +
"}" +
"})," +
"document.body);");
}
@Test public void testUnusedComponent() {
test(
// Unused components should not appear in the output.
"var Unused = React.createClass({" +
"render: function() {return React.createElement(\"div\", null);}" +
"});",
"");
}
@Test public void testUnusedComponentClass() {
test(
// Unused components should not appear in the output.
"class Unused extends React.Component {" +
"render() {return React.createElement(\"div\", null);}" +
"}",
"");
}
@Test public void testThisUsage() {
test(
"var Comp = React.createClass({" +
"render: function() {return React.createElement(\"div\");}," +
"method: function() {this.setState({foo: 123});}" +
"});" +
"ReactDOM.render(React.createElement(Comp), document.body);",
// Use of "this" should not cause any warnings.
"ReactDOM.render(React.createElement(React.createClass({" +
"render:function(){return React.createElement(\"div\")}," +
"$method$:function(){this.setState({$foo$:123})}" +
"})),document.body);");
}
@Test public void testThisUsageClass() {
test(
"class Comp extends React.Component {" +
"render() {return React.createElement(\"div\");}" +
"method() {this.setState({foo: 123});}" +
"}" +
"ReactDOM.render(React.createElement(Comp), document.body);",
// Use of "this" should not cause any warnings.
"class $Comp$$ extends React.Component{" +
"render(){return React.createElement(\"div\")}" +
"}" +
"ReactDOM.render(React.createElement($Comp$$),document.body);");
}
/**
* Tests React.createClass() validation done by the compiler pass (as opposed
* to type-based validation).
*/
@Test public void testCreateClassValidation() {
testError(
"var Comp = React.createClass(1)",
ReactCompilerPass.CREATE_TYPE_SPEC_NOT_VALID);
testError(
"var Comp = React.createClass({}, 1)",
ReactCompilerPass.CREATE_TYPE_UNEXPECTED_PARAMS);
testError(
"var a = 1 + React.createClass({})",
ReactCompilerPass.CREATE_TYPE_TARGET_INVALID);
}
/**
* Tests React.createMixin() validation done by the compiler pass (as opposed
* to type-based validation).
*/
@Test public void testCreateMixinValidation() {
testError(
"var Mixin = React.createMixin(1)",
ReactCompilerPass.CREATE_TYPE_SPEC_NOT_VALID);
testError(
"var Mixin = React.createMixin({}, 1)",
ReactCompilerPass.CREATE_TYPE_UNEXPECTED_PARAMS);
testError(
"var a = 1 + React.createMixin({})",
ReactCompilerPass.CREATE_TYPE_TARGET_INVALID);
}
/**
* Tests "mixins" spec property validation done by the compiler pass (as
* opposed to type-based validation).
*/
@Test public void testMixinsValidation() {
testError(
"var Comp = React.createClass({mixins: 1})",
ReactCompilerPass.MIXINS_UNEXPECTED_TYPE);
testError(
"var Comp = React.createClass({mixins: [1]})",
ReactCompilerPass.MIXIN_EXPECTED_NAME);
testError(
"var Comp = React.createClass({mixins: [NonExistent]})",
ReactCompilerPass.MIXIN_UNKNOWN);
}
/**
* Tests React.createElement() validation done by the compiler pass (as
* opposed to type-based validation).
*/
@Test public void testCreateElementValidation() {
testError(
"React.createElement()",
ReactCompilerPass.CREATE_ELEMENT_UNEXPECTED_PARAMS);
}
/**
* Tests that React.createElement calls have their return type cast to either
* ReactDOMElement or ReactElement.<ClassType>
*/
@Test public void testCreateElementCasting() {
// Tests that element.type is a string
test(
"window.type = React.createElement(\"div\").type.charAt(0)",
"window.type=React.createElement(\"div\").type.charAt(0);");
// Tests that element.type is not a string...
testError(
"var Comp = React.createClass({" +
"render: function() {return React.createElement(\"div\");}" +
"});" +
"React.createElement(Comp).type.charAt(0)",
"JSC_INEXISTENT_PROPERTY");
// ...but is present...
test(
"var Comp = React.createClass({" +
"render: function() {return React.createElement(\"div\");}" +
"});" +
"window.type = React.createElement(Comp).type;",
"window.type=React.createElement(React.createClass({" +
"render:function(){return React.createElement(\"div\")}" +
"})).type;");
// ...unlike other properties.
testError(
"var Comp = React.createClass({" +
"render: function() {return React.createElement(\"div\");}" +
"});" +
"window.foo = React.createElement(Comp).notAnElementProperty;",
"JSC_INEXISTENT_PROPERTY");
}
@Test public void testCreateElementCastingClass() {
// Tests that element.type is not a string...
testError(
"class Comp extends React.Component {" +
"render() {return React.createElement(\"div\");}" +
"}" +
"React.createElement(Comp).type.charAt(0)",
"JSC_INEXISTENT_PROPERTY");
// ...but is present...
test(
"class Comp extends React.Component {" +
"render() {return React.createElement(\"div\");}" +
"}" +
"window.type = React.createElement(Comp).type;",
"class $Comp$$ extends React.Component{" +
"render(){return React.createElement(\"div\")}" +
"}" +
"window.type=React.createElement($Comp$$).type;");
// ...unlike other properties.
testError(
"class Comp extends React.Component {" +
"render() {return React.createElement(\"div\");}" +
"}" +
"window.foo = React.createElement(Comp).notAnElementProperty;",
"JSC_INEXISTENT_PROPERTY");
}
/**
* Tests validation done by the types declared in the types.js file. Not
* exhaustive, just tests that the type declarations are included.
*/
@Test public void testTypeValidation() {
testError(
"var Comp = React.createClass({render: \"notafunction\"});",
"JSC_TYPE_MISMATCH");
testError(
"var Comp = React.createClass({displayName: function() {}});",
"JSC_TYPE_MISMATCH");
test(
"var Comp = React.createClass({" +
"render: function() {return React.createElement(\"div\");}" +
"});" +
"window.foo = Comp.displayName.charAt(0);",
// displayName is a valid string property of classes
"window.$foo$=React.createClass({" +
"render:function(){return React.createElement(\"div\")}" +
"}).displayName.charAt(0);");
// Stopped working in v20190513
// testError(
// "var Comp = React.createClass({" +
// "render: function() {return React.createElement(\"div\");}" +
// "});" +
// "window.foo = Comp.displayName.notAStringMethod();",
// "JSC_POSSIBLE_INEXISTENT_PROPERTY");
// testError(
// "var Comp = React.createClass({" +
// "render: function() {return React.createElement(\"div\");}" +
// "});" +
// "window.foo = Comp.nonExistentProperty;",
// "JSC_POSSIBLE_INEXISTENT_PROPERTY");
testError(
"var Comp = React.createClass({" +
"render: function() {return React.createElement(\"div\");}" +
"});" +
"ReactDOM.render(React.createElement(Comp), document.body, 123);",
"JSC_TYPE_MISMATCH");
testError(
"var Comp = React.createClass({" +
"render: function() {return React.createElement(\"div\");}," +
"shouldComponentUpdate: function(nextProps, nextState) {return 123;}" +
"});",
// Overrides/implemementations of built-in methods should conform to the
// type annotations added in types.js, even if they're not explicitly
// present in the spec.
"JSC_TYPE_MISMATCH");
test(
"var Comp = React.createClass({" +
"render: function() {return React.createElement(\"div\");}," +
"shouldComponentUpdate: function() {return false;}" +
"});",
// But implementations should be OK if they omit parameters...
"");
test(
"var Comp = React.createClass({" +
"render: function() {return React.createElement(\"div\");}," +
"shouldComponentUpdate: function(param1, param2) {return false;}" +
"});",
// ...or rename them.
"");
testError(
"var Comp = React.createClass({" +
"render: function() {return 123;}" +
"});",
"JSC_TYPE_MISMATCH");
testError(
"var Mixin = React.createMixin({" +
"shouldComponentUpdate: function(nextProps, nextState) {return 123;}" +
"});",
// Same for mixins
"JSC_TYPE_MISMATCH");
testError(
"var Comp = React.createClass({" +
"render: function() {" +
"this.isMounted().indexOf(\"true\");" +
"return React.createElement(\"div\");" +
"}" +
"});",
// Same for invocations of built-in component methods.
"JSC_INEXISTENT_PROPERTY");
test(
"var Comp = React.createClass({" +
"refAccess: function() {return this.refs[\"foo\"];}" +
"});",
// Refs can be accessed via quoted strings.
"");
testError(
"var Comp = React.createClass({" +
"refAccess: function() {return this.refs.foo;}" +
"});",
// ...but not as property accesses (since they may get renamed)
"JSC_ILLEGAL_PROPERTY_ACCESS");
}
@Test public void testTypeValidationClass() {
testError(
"class Comp extends React.Component {}" +
"Comp.prototype.render = \"notafunction\";",
"JSC_TYPE_MISMATCH");
testError(
"class Comp extends React.Component {" +
"constructor(props) {" +
"super(props);" +
"this.render = \"notafunction\";" +
"}" +
"}",
"JSC_TYPE_MISMATCH");
// displayName is not a property on Comp but not sure why this is not caught.
// testError(
// "class Comp extends React.Component {" +
// "render() {return null;}" +
// "}" +
// "window.foo = Comp.displayName.charAt(0);",
// "JSC_POSSIBLE_INEXISTENT_PROPERTY");
testError(
"class Comp extends React.Component {" +
"render() {return React.createElement(\"div\");}" +
"}" +
"ReactDOM.render(React.createElement(Comp), document.body, 123);",
"JSC_TYPE_MISMATCH");
testError(
"class Comp extends React.Component {" +
"render() {return React.createElement(\"div\");}" +
"shouldComponentUpdate(nextProps, nextState) {return 123;}" +
"}",
// Overrides/implemementations of built-in methods should conform to the
// type annotations added in types.js, even if they're not explicitly
// present in the spec.
"JSC_TYPE_MISMATCH");
test(
"class Comp extends React.Component {" +
"render() {return React.createElement(\"div\");}" +
"shouldComponentUpdate() {return false;}" +
"}",
// But implementations should be OK if they omit parameters...
"");
test(
"class Comp extends React.Component {" +
"render() {return React.createElement(\"div\");}" +
"shouldComponentUpdate(param1, param2) {return false;}" +
"}",
// ...or rename them.
"");
testError(
"class Comp extends React.Component {" +
"render() {return 123;}" +
"}",
"JSC_TYPE_MISMATCH");
testError(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {" +
"shouldComponentUpdate(nextProps, nextState) {return 123;}" +
"}" +
"ReactSupport.declareMixin(Mixin);",
// Same for mixins
"JSC_TYPE_MISMATCH");
testError(
"class Comp extends React.Component {" +
"render() {" +
"this.isMounted().indexOf(\"true\");" +
"return React.createElement(\"div\");" +
"}" +
"}",
// Same for invocations of built-in component methods.
"JSC_INEXISTENT_PROPERTY");
test(
"class Comp extends React.Component {" +
"refAccess() {return this.refs[\"foo\"];}" +
"}",
// Refs can be accessed via quoted strings.
"");
testError(
"class Comp extends React.Component {" +
"refAccess() {return this.refs.foo;}" +
"}",
// ...but not as property accesses (since they may get renamed)
"JSC_ILLEGAL_PROPERTY_ACCESS");
}
/**
* Tests that JSDoc type annotations on custom methods are checked.
*/
@Test public void testMethodJsDoc() {
testError(
"var Comp = React.createClass({" +
"render: function() {return React.createElement(\"div\");}," +
"/** @param {number} numberParam */" +
"someMethod: function(numberParam) {numberParam.notAMethod();}" +
"});",
"JSC_INEXISTENT_PROPERTY");
testError(
"var Comp = React.createClass({" +
"render: function() {return React.createElement(" +
"\"div\", null, this.someMethod(\"notanumber\"));}," +
"/** @param {number} numberParam */" +
"someMethod: function(numberParam) {return numberParam + 1;}" +
"});",
"JSC_TYPE_MISMATCH");
}
@Test public void testMethodJsDocClass() {
testError(
"class Comp extends React.Component {" +
"render() {return React.createElement(\"div\");}" +
"/** @param {number} numberParam */" +
"someMethod(numberParam) {numberParam.notAMethod();}" +
"}",
"JSC_INEXISTENT_PROPERTY");
testError(
"class Comp extends React.Component {" +
"render() {return React.createElement(" +
"\"div\", null, this.someMethod(\"notanumber\"));}" +
"/** @param {number} numberParam */" +
"someMethod(numberParam) {return numberParam + 1;}" +
"}",
"JSC_TYPE_MISMATCH");
}
/**
* Tests that component methods can have default parameters.
*/
@Test public void testMethodDefaultParameters() {
test(
"var Comp = React.createClass({" +
"render: function() {return React.createElement(\"div\");}," +
"/** @param {number=} numberParam @return {number}*/" +
"someMethod: function(numberParam = 1) {return numberParam * 2;}" +
"});",
"");
}
@Test public void testMethodDefaultParametersClass() {
test(
"class Comp extends React.Component {" +
"render() {return React.createElement(\"div\");}" +
"/** @param {number=} numberParam @return {number}*/" +
"someMethod(numberParam = 1) {return numberParam * 2;}" +
"}",
"");
}
/**
* Tests that components can be marked as implementing interfaces.
*/
@Test public void testInterfaces() {
test(
"/** @interface */ function AnInterface() {}\n" +
"/** @return {number} */\n" +
"AnInterface.prototype.interfaceMethod = function() {};\n" +
"/** @implements {AnInterface} */" +
"var Comp = React.createClass({" +
"/** @override */ interfaceMethod: function() {\n" +
"return 1;\n" +
"},\n" +
"render: function() {\n" +
"return React.createElement(\"div\");\n" +
"}" +
"});" +
"ReactDOM.render(React.createElement(Comp), document.body);",
"ReactDOM.render(React.createElement(React.createClass({" +
"$interfaceMethod$:function(){" +
"return 1" +
"}," +
"render:function(){" +
"return React.createElement(\"div\")" +
"}" +
"})),document.body);");
// We can't test that missing methods cause compiler warnings since we're
// declaring CompInterface as extending AnInterface, thus the methods
// assumed to be there.
}
@Test public void testInterfacesClass() {
test(
"/** @interface */ function AnInterface() {}\n" +
"/** @return {number} */\n" +
"AnInterface.prototype.interfaceMethod = function() {};\n" +
"/** @implements {AnInterface} */" +
"class Comp extends React.Component {" +
"/** @override */ interfaceMethod() {\n" +
"return 1;\n" +
"}\n" +
"render() {\n" +
"return React.createElement(\"div\");\n" +
"}" +
"};" +
"ReactDOM.render(React.createElement(Comp), document.body);",
"class $Comp$$ extends React.Component{" +
"render(){" +
"return React.createElement(\"div\")" +
"}" +
"}" +
"ReactDOM.render(React.createElement($Comp$$),document.body);");
// We can't test that missing methods cause compiler warnings since we're
// declaring CompInterface as extending AnInterface, thus the methods
// assumed to be there.
}
@Test public void testState() {
// this.state accesses are checked
testError(
"var Comp = React.createClass({" +
"/** @return {{enabled: boolean}} */ getInitialState() {" +
"return {enabled: false};" +
"},\n" +
"render() {" +
"this.state.enabled.toFixed(2);" +
"return null" +
"}" +
"});",
"JSC_INEXISTENT_PROPERTY");
// this.setState() calls are checked
testError(
"var Comp = React.createClass({" +
"/** @return {{enabled: boolean}} */ getInitialState() {" +
"return {enabled: false};" +
"},\n" +
"render() {" +
"this.setState({enabled: 123});" +
"return null;" +
"},\n" +
"});",
"JSC_TYPE_MISMATCH");
// this.setState() calls with an updater function should be checked
testError(
"var Comp = React.createClass({" +
"/** @return {{enabled: boolean}} */ getInitialState() {" +
"return {enabled: false};" +
"},\n" +
"render() {" +
"this.setState((state, props) => ({enabled: 123}));" +
"return null;" +
"},\n" +
"});",
"JSC_TYPE_MISMATCH");
// this.setState() accepts a subset of state fields
testNoError(
"var Comp = React.createClass({" +
"/** @return {{f1: boolean, f2: number, f3: (number|boolean)}} */" +
"getInitialState() {" +
"return {f1: false, f2: 1, f3: 2};" +
"},\n" +
"render() {" +
"this.setState({f1: true});" +
"return null;" +
"},\n" +
"});");
// return type for getInitialState must be a record
testError(
"var Comp = React.createClass({" +
"/** @return {number} */ getInitialState() {" +
"return {enabled: false};" +
"},\n" +
"render() {" +
"return null;" +
"}" +
"});",
"REACT_UNEXPECTED_STATE_TYPE");
// component methods that take state parameters are checked
testError(
"var Comp = React.createClass({" +
"/** @return {{enabled: boolean}} */ getInitialState() {" +
"return {enabled: false};" +
"},\n" +
"componentWillUpdate(nextProps, nextState) {" +
"nextState.enabled.toFixed(2);" +
"},\n" +
"render() {" +
"return null;" +
"}" +
"});",
"JSC_INEXISTENT_PROPERTY");
// Mixin methods that take state parameters are checked
testError(
"var Mixin = React.createMixin({});\n" +
"/** @param {!ReactState} state */" +
"Mixin.mixinMethod;\n" +
"var Comp = React.createClass({" +
"mixins: [Mixin],\n" +
"/** @return {{enabled: boolean}} */ getInitialState() {" +
"return {enabled: false};" +
"},\n" +
"mixinMethod(state) {" +
"state.enabled.toFixed(2);" +
"},\n" +
"render: function() {" +
"return null;" +
"}" +
"});",
"JSC_INEXISTENT_PROPERTY");
}
@Test public void testStateClass() {
// this.state accesses are checked
testError(
"class Comp extends React.Component {" +
"constructor(props) {" +
"super(props);" +
"/** @type {Comp.State} */" +
"this.state = this.initialState();" +
"}" +
"/** @return {{enabled: boolean}} */" +
"initialState() {" +
"return {enabled: false};" +
"}" +
"render() {" +
"this.state.enabled.toFixed(2);" +
"return null" +
"}" +
"}",
"JSC_INEXISTENT_PROPERTY");
// this.setState() calls are checked
testError(
"class Comp extends React.Component {" +
"constructor(props) {" +
"super(props);" +
"/** @type {Comp.State} */" +
"this.state = this.initialState()" +
"}" +
"/** @return {{enabled: boolean}} */" +
"initialState() {" +
"return {enabled: false};" +
"}" +
"render() {" +
"this.setState({enabled: 123});" +
"return null;" +
"}" +
"}",
"JSC_TYPE_MISMATCH");
// this.setState() calls with an updater function should be checked, but the
// compiler does not appear to be doing this.
testError(
"class Comp extends React.Component {" +
"constructor(props) {" +
"super(props);" +
"/** @type {Comp.State} */" +
"this.state = this.initialState();" +
"}" +
"/** @return {{enabled: boolean}} */" +
"initialState() {" +
"return {enabled: false};" +
"}" +
"render() {" +
"this.setState((state, props) => ({enabled: 123}));" +
"return null;" +
"}" +
"}",
"JSC_TYPE_MISMATCH");
// this.setState() accepts a subset of state fields
testNoError(
"class Comp extends React.Component {" +
"constructor(props) {" +
"super(props);" +
"/** @type {Comp.State} */" +
"this.state = this.initialState();" +
"}" +
"/** @return {{f1: boolean, f2: number, f3: (number|boolean)}} */" +
"initialState() {" +
"return {f1: false, f2: 1, f3: 2};" +
"}" +
"render() {" +
"this.setState({f1: true});" +
"return null;" +
"}" +
"}");
// type for this.state must be a record
testError(
"class Comp extends React.Component {" +
"constructor(props) {" +
"super(props);" +
"/** @type {number} */" +
"this.state = this.initialState();" +
"}" +
"/** @return {number} */" +
"initialState() {" +
"return {enabled: false};" +
"}" +
"render() {" +
"return null;" +
"}" +
"}",
"REACT_UNEXPECTED_STATE_TYPE");
// component methods that take state parameters are checked
testError(
"class Comp extends React.Component {" +
"constructor(props) {" +
"super(props);" +
"/** @type {Comp.State} */" +
"this.state = this.initialState();" +
"}" +
"/** @return {{enabled: boolean}} */" +
"initialState() {" +
"return {enabled: false};" +
"}" +
"componentWillUpdate(nextProps, nextState) {" +
"nextState.enabled.toFixed(2);" +
"}" +
"render() {" +
"return null;" +
"}" +
"}",
"JSC_INEXISTENT_PROPERTY");
// Mixin methods that take state parameters are checked
testError(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {}" +
"ReactSupport.declareMixin(Mixin);" +
"/** @param {!ReactState} state */" +
"Mixin.mixinMethod;" +
"class Comp extends React.Component {" +
"constructor(props) {" +
"super(props);" +
"/** @type {Comp.State} */" +
"this.state = this.initialState();" +
"}" +
"/** @return {{enabled: boolean}} */" +
"initialState() {" +
"return {enabled: false};" +
"}" +
"mixinMethod(state) {" +
"state.enabled.toFixed(2);" +
"}" +
"render() {" +
"return null;" +
"}" +
"}" +
"ReactSupport.mixin(Comp, Mixin);",
"JSC_INEXISTENT_PROPERTY");
}
@Test public void testFields() {
// Fields defined in getInitialState are checked
testError(
"var Comp = React.createClass({" +
"getInitialState() {" +
"/** @private {boolean} */" +
"this.field_ = true;\n" +
"return null;" +
"},\n" +
"render() {" +
"this.field_.toFixed(2);" +
"return null" +
"}" +
"});",
"JSC_INEXISTENT_PROPERTY");
// Even if they don't have a value assigned.
testError(
"var Comp = React.createClass({" +
"getInitialState() {" +
"/** @private {boolean|undefined} */" +
"this.field_;\n" +
"return null;" +
"},\n" +
"render() {" +
"this.field_.toFixed(2);" +
"return null" +
"}" +
"});",
"JSC_INEXISTENT_PROPERTY");
}
@Test public void testPropTypes() {
// Basic prop types
test(
"var Comp = React.createClass({" +
"propTypes: {aProp: React.PropTypes.string}," +
"render: function() {" +
"return React.createElement(\"div\", null, this.props.aProp);" +
"}" +
"});" +
"ReactDOM.render(React.createElement(Comp), document.body);",
"ReactDOM.render(React.createElement(React.createClass({" +
"propTypes:{$aProp$:React.PropTypes.string}," +
"render:function(){" +
"return React.createElement(\"div\",null,this.props.$aProp$)" +
"}" +
"})),document.body);");
// isRequired variant
test(
"window.foo=React.PropTypes.string.isRequired;",
"window.$foo$=React.PropTypes.string.isRequired;");
// Other variants are rejected
testError(
"window.foo=React.PropTypes.string.isSortOfRequired;",
"JSC_INEXISTENT_PROPERTY");
// arrayOf
test(
"window.foo=React.PropTypes.arrayOf(React.PropTypes.string);",
"window.$foo$=React.PropTypes.arrayOf(React.PropTypes.string);");
test(
"window.foo=React.PropTypes.arrayOf(React.PropTypes.string).isRequired;",
"window.$foo$=React.PropTypes.arrayOf(React.PropTypes.string).isRequired;");
testError(
"window.foo=React.PropTypes.arrayOf(123);",
"JSC_TYPE_MISMATCH");
testError(
"window.foo=React.PropTypes.arrayOf(React.PropTypes.string).isSortOfRequired;",
"JSC_INEXISTENT_PROPERTY");
// instanceOf
test(
"window.foo=React.PropTypes.instanceOf(Element);",
"window.$foo$=React.PropTypes.instanceOf(Element);");
testError(
"window.foo=React.PropTypes.instanceOf(123);",
"JSC_TYPE_MISMATCH");
// oneOf
test(
"window.foo=React.PropTypes.oneOf([1,2,3]);",
"window.$foo$=React.PropTypes.oneOf([1,2,3]);");
testError(
"window.foo=React.PropTypes.oneOf(123);",
"JSC_TYPE_MISMATCH");
// oneOfType
test(
"window.foo=React.PropTypes.oneOfType([React.PropTypes.string]);",
"window.$foo$=React.PropTypes.oneOfType([React.PropTypes.string]);");
testError(
"window.foo=React.PropTypes.oneOfType(123);",
"JSC_TYPE_MISMATCH");
// shape
test(
"window.foo=React.PropTypes.shape({str: React.PropTypes.string});",
"window.$foo$=React.PropTypes.shape({$str$:React.PropTypes.string});");
testError(
"window.foo=React.PropTypes.shape(123);",
"JSC_TYPE_MISMATCH");
}
@Test public void testPropTypesClass() {
// Basic prop types
test(
"class Comp extends React.Component {" +
"render() {" +
"return React.createElement(\"div\", null, this.props.aProp);" +
"}" +
"}" +
"Comp.propTypes = {aProp: React.PropTypes.string};" +
"ReactDOM.render(React.createElement(Comp), document.body);",
"class $Comp$$ extends React.Component{" +
"render(){" +
"return React.createElement(\"div\",null,this.props.$aProp$)" +
"}" +
"}" +
"$Comp$$.propTypes={$aProp$:React.PropTypes.string};" +
"ReactDOM.render(React.createElement($Comp$$),document.body);");
}
@Test public void testOptimizeForSize() {
ReactCompilerPass.Options passOptions =
new ReactCompilerPass.Options();
passOptions.optimizeForSize = true;
passOptions.propTypesTypeChecking = true;
// - propTypes should get stripped
// - React.createMixin() calls should be inlined with just the spec
// - React.createClass and React.createElement calls should be replaced with
// React$createClass and React$createElement aliases (which can get fully
// renamed).
test(
"var Mixin = React.createMixin({" +
"mixinMethod: function() {return 'foo'}" +
"});\n" +
"var Comp = React.createClass({" +
"mixins: [Mixin]," +
"propTypes: {aProp: React.PropTypes.string}," +
"render: function() {return React.createElement(\"div\", null, this.mixinMethod());}" +
"});" +
"ReactDOM.render(React.createElement(Comp), document.body);",
"ReactDOM.render($React$createElement$$($React$createClass$$({" +
"mixins:[{$mixinMethod$:function(){return\"foo\"}}]," +
"render:function(){return $React$createElement$$(\"div\",null,\"foo\")}" +
"})),document.body);",
passOptions,
null);
// This should also work when using ES6 modules
test(
"export const anExport = 9;\n" +
"var Comp = React.createClass({" +
"propTypes: {aProp: React.PropTypes.string}," +
"render: function() {return React.createElement(\"div\");}" +
"});" +
"ReactDOM.render(React.createElement(Comp), document.body);",
"ReactDOM.render($React$createElement$$($React$createClass$$({" +
"render:function(){return $React$createElement$$(\"div\")}" +
"})),document.body);",
passOptions,
null);
// But propTypes tagged with @struct should be preserved (React.PropTypes
// is replaced with an alias so that it can also be represented more
// compactly).
test(
"var Comp = React.createClass({" +
"/** @struct */" +
"propTypes: {aProp: React.PropTypes.string}," +
"render: function() {return React.createElement(\"div\");}" +
"});" +
"ReactDOM.render(React.createElement(Comp), document.body);",
"ReactDOM.render($React$createElement$$($React$createClass$$({" +
"propTypes:{$aProp$:$React$PropTypes$$.string}," +
"render:function(){return $React$createElement$$(\"div\")}" +
"})),document.body);",
passOptions,
null);
}
@Test public void testOptimizeForSizeClass() {
ReactCompilerPass.Options passOptions =
new ReactCompilerPass.Options();
passOptions.optimizeForSize = true;
passOptions.propTypesTypeChecking = true;
// - propTypes should get stripped
// - React.Component and React.createElement calls should be replaced with
// React$Component and React$createElement aliases (which can get fully
// renamed).
test(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {" +
"mixinMethod() {return 'foo'}" +
"}" +
"ReactSupport.declareMixin(Mixin);" +
"class Comp extends React.Component {" +
"render() {" +
"return React.createElement(\"div\", null, this.mixinMethod());" +
"}" +
"}" +
"ReactSupport.mixin(Comp, Mixin);" +
"Comp.propTypes = {aProp: React.PropTypes.string};" +
"ReactDOM.render(React.createElement(Comp), document.body);",
"class $Mixin$$ extends $React$Component$${}" +
"class $Comp$$ extends $React$Component$${" +
"render(){" +
"return $React$createElement$$(\"div\",null,\"foo\")" +
"}" +
"}" +
"$Comp$$.mixins=[$Mixin$$];" +
"ReactDOM.render($React$createElement$$($Comp$$),document.body);",
passOptions,
null);
// This should also work when using ES6 modules
test(
"export const anExport = 9;" +
"class Comp extends React.Component {" +
"render() {" +
"return React.createElement(\"div\");" +
"}" +
"}" +
"Comp.propTypes = {aProp: React.PropTypes.string};" +
"Comp.defaultProps = {aProp: \"hi\"};" +
"Comp.contextTypes = {aContext: React.PropTypes.number};" +
"ReactDOM.render(React.createElement(Comp), document.body);",
"class $Comp$$module$src$file1$$ extends $React$Component$${" +
"render(){" +
"return $React$createElement$$(\"div\")" +
"}" +
"}" +
"$Comp$$module$src$file1$$.defaultProps={$aProp$:\"hi\"};" +
"ReactDOM.render($React$createElement$$($Comp$$module$src$file1$$),document.body);",
passOptions,
null);
}
@Test public void testNoRenameReactApi() {
// Even when optimizing for size there is no renaming.
ReactCompilerPass.Options passOptions = new ReactCompilerPass.Options();
passOptions.optimizeForSize = true;
test(
"var Comp = React.createClass({" +
"propTypes: {aProp: React.PropTypes.string}," +
"render: function() {\n" +
"return React.createElement(\"div\", {onClick: null});\n" +
"}" +
"});" +
"ReactDOM.render(React.createElement(Comp), document.body);",
"ReactDOM.render($React$createElement$$($React$createClass$$({" +
"render:function(){" +
"return $React$createElement$$(\"div\",{onClick:null})" +
"}" +
"})),document.body);",
passOptions,
null);
// Other API symbols are not renamed either.
List<String> reactApiSymbols = ImmutableList.of("React", "React.Component",
"React.PureComponent", "React.cloneElement", "ReactDOM.findDOMNode",
"ReactDOM.unmountComponentAtNode");
for (String reactApiSymbol : reactApiSymbols) {
test(
"window['test'] = " + reactApiSymbol + ";",
"window.test=" + reactApiSymbol + ";",
passOptions,
null);
}
}
@Test public void testExport() {
String CLOSURE_EXPORT_FUNCTIONS =
"/** @const */ const goog = {};" +
"goog.exportSymbol = function(publicPath, object) {};\n" +
"goog.exportProperty = function(object, publicName, symbol) {};\n";
// Props where the class is tagged with @export should not get renamed,
// nor should methods explicitly tagged with @public.
test(
CLOSURE_EXPORT_FUNCTIONS +
"/** @export */" +
"var Comp = React.createClass({" +
"propTypes: {aProp: React.PropTypes.string},\n" +
"/** @public */ publicFunction: function() {\n" +
"return \"dont_rename_me_bro\";\n" +
"},\n" +
"/** @private */ privateFunction_: function() {\n" +
"return 1;\n" +
"},\n" +
"render: function() {\n" +
"return React.createElement(\"div\", null, this.props.aProp);\n" +
"}" +
"});" +
"ReactDOM.render(React.createElement(" +
"Comp, {aProp: \"foo\"}), document.body);",
"ReactDOM.render(React.createElement(React.createClass({" +
"propTypes:{aProp:React.PropTypes.string}," +
"publicFunction:function(){" +
"return\"dont_rename_me_bro\"" +
"}," +
"$privateFunction_$:function(){" +
"return 1" +
"}," +
"render:function(){" +
"return React.createElement(\"div\",null,this.props.aProp)" +
"}" +
"}),{aProp:\"foo\"}),document.body);");
// Even with a minified build there is no renaming.
ReactCompilerPass.Options minifiedReactPassOptions =
new ReactCompilerPass.Options();
minifiedReactPassOptions.optimizeForSize = true;
test(
CLOSURE_EXPORT_FUNCTIONS +
"/** @export */" +
"var Comp = React.createClass({" +
"propTypes: {aProp: React.PropTypes.string}," +
"/** @public */ publicFunction: function() {\n" +
"return \"dont_rename_me_bro\";\n" +
"},\n" +
"/** @private */ privateFunction_: function() {\n" +
"return 1;\n" +
"},\n" +
"render: function() {\n" +
"return React.createElement(\"div\", null, this.props.aProp);\n" +
"}" +
"});" +
"ReactDOM.render(React.createElement(" +
"Comp, {aProp: \"foo\"}), document.body);",
"ReactDOM.render($React$createElement$$($React$createClass$$({" +
"publicFunction:function(){" +
"return\"dont_rename_me_bro\"" +
"}," +
"$privateFunction_$:function(){" +
"return 1" +
"}," +
"render:function(){" +
"return $React$createElement$$(\"div\",null,this.props.aProp)" +
"}" +
"}),{aProp:\"foo\"}),document.body);",
minifiedReactPassOptions,
null);
}
@Test public void testExportClass () {
String CLOSURE_EXPORT_FUNCTIONS =
"/** @const */ const goog = {};" +
"goog.exportSymbol = function(publicPath, object) {};\n" +
"goog.exportProperty = function(object, publicName, symbol) {};\n";
// Props where the class is tagged with @export should not get renamed,
// nor should methods explicitly tagged with @export.
test(
CLOSURE_EXPORT_FUNCTIONS +
"/** @export */" +
"class Comp extends React.Component {" +
"/** @export */ publicFunction() {\n" +
"return \"dont_rename_me_bro\";\n" +
"}\n" +
"/** @private */ privateFunction_() {\n" +
"return 1;\n" +
"}\n" +
"render() {\n" +
"return React.createElement(\"div\", null, this.props.aProp);\n" +
"}" +
"}" +
"Comp.propTypes = {aProp: React.PropTypes.string};\n" +
"ReactDOM.render(React.createElement(Comp, {aProp: \"foo\"}), document.body);",
"class $Comp$$ extends React.Component{" +
"publicFunction(){" +
"return\"dont_rename_me_bro\"" +
"}" +
"render(){" +
"return React.createElement(\"div\",null,this.props.aProp)" +
"}" +
"}" +
"$Comp$$.propTypes={aProp:React.PropTypes.string};" +
"ReactDOM.render(React.createElement($Comp$$,{aProp:\"foo\"}),document.body);");
// Even with a minified build there is no renaming.
ReactCompilerPass.Options minifiedReactPassOptions =
new ReactCompilerPass.Options();
minifiedReactPassOptions.optimizeForSize = true;
test(
CLOSURE_EXPORT_FUNCTIONS +
"/** @export */" +
"class Comp extends React.Component {" +
"/** @export */ publicFunction() {\n" +
"return \"dont_rename_me_bro\";\n" +
"}\n" +
"/** @private */ privateFunction_() {\n" +
"return 1;\n" +
"}\n" +
"render() {\n" +
"return React.createElement(\"div\", null, this.props.aProp);\n" +
"}" +
"}" +
"Comp.propTypes = {aProp: React.PropTypes.string};" +
"ReactDOM.render(React.createElement(Comp, {aProp: \"foo\"}), document.body);",
"class $Comp$$ extends $React$Component$${" +
"publicFunction(){" +
"return\"dont_rename_me_bro\"" +
"}" +
"render(){" +
"return $React$createElement$$(\"div\",null,this.props.aProp)" +
"}" +
"}" +
"ReactDOM.render($React$createElement$$($Comp$$,{aProp:\"foo\"}),document.body);",
minifiedReactPassOptions,
null);
}
@Test public void testPropTypesTypeChecking() {
// Validate use of props within methods.
testError(
"var Comp = React.createClass({" +
"propTypes: {numberProp: React.PropTypes.number}," +
"render: function() {" +
"this.props.numberProp();" +
"return null;" +
"}" +
"});",
"JSC_NOT_FUNCTION_TYPE");
// Validate props at creation time.
testPropTypesError(
"{strProp: React.PropTypes.string}",
"{strProp: 1}",
"JSC_TYPE_MISMATCH");
// Required props cannot be null
testPropTypesError(
"{strProp: React.PropTypes.string.isRequired}",
"{strProp: null}",
"JSC_TYPE_MISMATCH");
// Required props cannot be omitted
testPropTypesError(
"{strProp: React.PropTypes.string.isRequired}",
"{}",
"JSC_TYPE_MISMATCH");
testPropTypesError(
"{strProp: React.PropTypes.string.isRequired}",
"null",
"JSC_TYPE_MISMATCH");
// Optional props can be null
testPropTypesNoError(
"{strProp: React.PropTypes.string}",
"null");
// Optional props can be omitted
testPropTypesNoError(
"{strProp: React.PropTypes.string}",
"{}");
testPropTypesNoError(
"{strProp: React.PropTypes.string}",
"null");
// Validate object prop
testPropTypesError(
"{objProp: React.PropTypes.instanceOf(Message).isRequired}",
"{objProp: \"foo\"}",
"JSC_TYPE_MISMATCH");
// Required object prop cannot be null
testPropTypesError(
"{objProp: React.PropTypes.instanceOf(Message).isRequired}",
"{objProp: null}",
"JSC_TYPE_MISMATCH");
// Required object prop cannot be omitted
testPropTypesError(
"{objProp: React.PropTypes.instanceOf(Message).isRequired}",
"{}",
"JSC_TYPE_MISMATCH");
// Optional object prop can be null
testPropTypesNoError(
"{objProp: React.PropTypes.instanceOf(Message)}",
"{objProp: null}");
// Optional object prop can be ommitted
testPropTypesNoError(
"{objProp: React.PropTypes.instanceOf(Message)}",
"{}");
// Validate array prop
testPropTypesError(
"{arrayProp: React.PropTypes.arrayOf(React.PropTypes.string)}",
"{arrayProp: 1}",
"JSC_TYPE_MISMATCH");
// Validate object prop
testPropTypesError(
"{objProp: React.PropTypes.objectOf(React.PropTypes.string)}",
"{objProp: 1}",
"JSC_TYPE_MISMATCH");
// Validate oneOfType prop
testPropTypesError(
"{unionProp: React.PropTypes.oneOfType([" +
"React.PropTypes.string," +
"React.PropTypes.number" +
"])}",
"{unionProp: false}",
"JSC_TYPE_MISMATCH");
testPropTypesNoError(
"{unionProp: React.PropTypes.oneOfType([" +
"React.PropTypes.string," +
"React.PropTypes.number" +
"])}",
"{unionProp: 1}");
// Validate children prop
testNoError(
"var Comp = React.createClass({" +
"propTypes: {" +
"children: React.PropTypes.element.isRequired" +
"}," +
"render: function() {return null;}" +
"});\n" +
"React.createElement(Comp, {}, React.createElement(\"div\"));");
testNoError(
"var Comp = React.createClass({" +
"propTypes: {" +
"children: React.PropTypes.element.isRequired" +
"}," +
"render: function() {return null;}" +
"});\n" +
"React.createElement(Comp, {}, React.createElement(Comp));");
// Multiple children
testNoError(
"var Comp = React.createClass({" +
"propTypes: {" +
"children: React.PropTypes.arrayOf(React.PropTypes.element).isRequired" +
"}," +
"render: function() {return null;}" +
"});\n" +
"React.createElement(Comp, {}, React.createElement(Comp), React.createElement(Comp));");
// Children required but not passed in
testError(
"var Comp = React.createClass({" +
"propTypes: {" +
"children: React.PropTypes.element.isRequired" +
"}," +
"render: function() {return null;}" +
"});\n" +
"React.createElement(Comp, {});",
"REACT_NO_CHILDREN_ARGUMENT");
// Children not required and not passed in
testNoError(
"var Comp = React.createClass({" +
"propTypes: {" +
"children: React.PropTypes.element" +
"}," +
"render: function() {return null;}" +
"});\n" +
"React.createElement(Comp, {});");
// Children required and wrong type passed in
testError(
"var Comp = React.createClass({" +
"propTypes: {" +
"children: React.PropTypes.element.isRequired" +
"}," +
"render: function() {return null;}" +
"});\n" +
"React.createElement(Comp, {}, null);",
"JSC_TYPE_MISMATCH");
// Handle spread operator when creating elements
testPropTypesError(
"{aProp: React.PropTypes.number.isRequired}",
"Object.assign({aProp: '1'}, {})",
"JSC_TYPE_MISMATCH");
testPropTypesError(
"{aProp: React.PropTypes.number.isRequired}",
"{aProp: '1', ...{}}",
"JSC_TYPE_MISMATCH");
testPropTypesNoError(
"{aProp: React.PropTypes.number.isRequired}",
"Object.assign({aProp: 1}, {})");
testPropTypesNoError(
"{aProp: React.PropTypes.number.isRequired}",
"{aProp: 1, ...{}}");
testPropTypesNoError(
"{aProp: React.PropTypes.number.isRequired}",
"Object.assign({}, {})");
testPropTypesError(
"{aProp: React.PropTypes.number.isRequired}",
"{...{}}",
"JSC_TYPE_MISMATCH");
testPropTypesNoError(
"{aProp: React.PropTypes.number.isRequired," +
"bProp: React.PropTypes.number.isRequired}",
"Object.assign({}, {aProp: 1})");
testPropTypesError(
"{aProp: React.PropTypes.number.isRequired," +
"bProp: React.PropTypes.number.isRequired}",
"{...{aProp: 1}}",
"JSC_TYPE_MISMATCH");
testPropTypesError(
"{aProp: React.PropTypes.number.isRequired," +
"bProp: React.PropTypes.number.isRequired}",
"Object.assign({}, {aProp: '1'})",
"JSC_TYPE_MISMATCH");
testPropTypesError(
"{aProp: React.PropTypes.number.isRequired," +
"bProp: React.PropTypes.number.isRequired}",
"{...{aProp: '1'}}",
"JSC_TYPE_MISMATCH");
testNoError(
"var Comp = React.createClass({" +
"propTypes: {" +
"aProp: React.PropTypes.string.isRequired" +
"}," +
"getDefaultProps: function() {" +
"return {aProp: \"1\"};" +
"}," +
"render: function() {return null;}" +
"});\n" +
"React.createElement(Comp, Object.assign({aProp: \"1\"}, {}))");
testNoError(
"var Comp = React.createClass({" +
"propTypes: {" +
"aProp: React.PropTypes.string.isRequired" +
"}," +
"getDefaultProps: function() {" +
"return {aProp: \"1\"};" +
"}," +
"render: function() {return null;}" +
"});\n" +
"React.createElement(Comp, {aProp: \"1\",...{}})");
// Custom type expressions
testPropTypesError(
"{/** @type {boolean} */ boolProp: function() {}}",
"{boolProp: 1}",
"JSC_TYPE_MISMATCH");
testPropTypesNoError(
"{/** @type {boolean} */ boolProp: function() {}}",
"{boolProp: true}");
testPropTypesNoError(
"{/** @type {(boolean|undefined|null)} */ boolProp: function() {}}",
"null");
// Required props with default values can be ommitted.
testNoError(
"var Comp = React.createClass({" +
"propTypes: {" +
"strProp: React.PropTypes.string.isRequired" +
"}," +
"getDefaultProps: function() {" +
"return {strProp: \"1\"};" +
"}," +
"render: function() {return null;}" +
"});\n" +
"React.createElement(Comp, {});");
testNoError(
"var Comp = React.createClass({" +
"propTypes: {" +
"strProp: React.PropTypes.string.isRequired" +
"}," +
"getDefaultProps: function() {" +
"return {strProp: \"1\"};" +
"}," +
"render: function() {return null;}" +
"});\n" +
"React.createElement(Comp, null);");
// Applies to custom type expressions too
testNoError(
"var Comp = React.createClass({" +
"propTypes: {" +
"/** @type {boolean} */ boolProp: function() {}" +
"}," +
"getDefaultProps: function() {" +
"return {boolProp: true};" +
"}," +
"render: function() {return null;}" +
"});\n" +
"React.createElement(Comp, {});");
// But if they are provided their types are still checked.
testError(
"var Comp = React.createClass({" +
"propTypes: {" +
"strProp: React.PropTypes.string.isRequired" +
"}," +
"getDefaultProps: function() {" +
"return {strProp: \"1\"};" +
"}," +
"render: function() {return null;}" +
"});\n" +
"React.createElement(Comp, {strProp: 1});",
"JSC_TYPE_MISMATCH");
// Even if not required, if they have a default value their value inside
// the component is not null or undefined.
testNoError(
"var Comp = React.createClass({" +
"propTypes: {" +
"strProp: React.PropTypes.string" +
"}," +
"getDefaultProps: function() {" +
"return {strProp: \"1\"};" +
"}," +
"render: function() {" +
"this.strMethod_(this.props.strProp);" +
"return null;" +
"},\n" +
"/**" +
" * @param {string} param" +
" * @return {string}" +
" * @private" +
" */" +
"strMethod_: function(param) {return param;}" +
"});\n" +
"React.createElement(Comp, null);");
}
@Test public void testPropTypesTypeCheckingClass() {
// Validate use of props within methods.
testError(
"export{};class Comp extends React.Component {" +
"render() {" +
"this.props.numberProp();" +
"return null;" +
"}" +
"}" +
"Comp.propTypes = {numberProp: React.PropTypes.number};",
"JSC_NOT_FUNCTION_TYPE");
// Validate children prop
testNoError(
"class Comp extends React.Component {" +
"render() {return null;}" +
"}" +
"Comp.propTypes= {" +
"children: React.PropTypes.element.isRequired" +
"};" +
"React.createElement(Comp, {}, React.createElement(\"div\"));");
testNoError(
"class Comp extends React.Component {" +
"render() {return null;}" +
"}" +
"Comp.propTypes = {" +
"children: React.PropTypes.element.isRequired" +
"};" +
"React.createElement(Comp, {}, React.createElement(Comp));");
// Multiple children
testNoError(
"class Comp extends React.Component {" +
"render() {return null;}" +
"}" +
"Comp.propTypes = {" +
"children: React.PropTypes.arrayOf(React.PropTypes.element).isRequired" +
"};" +
"React.createElement(Comp, {}, React.createElement(Comp), React.createElement(Comp));");
// Children required but not passed in
testError(
"class Comp extends React.Component {" +
"render() {return null;}" +
"}" +
"Comp.propTypes = {" +
"children: React.PropTypes.element.isRequired" +
"};" +
"React.createElement(Comp, {});",
"REACT_NO_CHILDREN_ARGUMENT");
// Children not required and not passed in
testNoError(
"class Comp extends React.Component {" +
"render() {return null;}" +
"}" +
"Comp.propTypes = {" +
"children: React.PropTypes.element" +
"};" +
"React.createElement(Comp, {});");
// Children required and wrong type passed in
testError(
"class Comp extends React.Component {" +
"render() {return null;}" +
"}" +
"Comp.propTypes = {" +
"children: React.PropTypes.element.isRequired" +
"};" +
"React.createElement(Comp, {}, null);",
"JSC_TYPE_MISMATCH");
test(
"class Comp extends React.Component {" +
"render() {return null;}" +
"}\n" +
"Comp.propTypes = {" +
"aProp: React.PropTypes.string.isRequired" +
"};" +
"Comp.defaultProps = {aProp: \"1\"};" +
"React.createElement(Comp, Object.assign({aProp: \"1\"}, {}))",
"class $Comp$$ extends React.Component{" +
"render(){" +
"return null" +
"}" +
"}" +
"$Comp$$.propTypes={$aProp$:React.PropTypes.string.isRequired};" +
"$Comp$$.defaultProps={$aProp$:\"1\"};" +
"React.createElement($Comp$$,Object.assign({$aProp$:\"1\"},{}));");
testNoError(
"class Comp extends React.Component {" +
"render() {return null;}" +
"}\n" +
"Comp.propTypes = {" +
"aProp: React.PropTypes.string.isRequired" +
"};" +
"Comp.defaultProps = {aProp: \"1\"};" +
"React.createElement(Comp, {aProp: \"1\",...{}})");
// Required props with default values can be ommitted.
testNoError(
"class Comp extends React.Component {" +
"render() {return null;}" +
"}\n" +
"Comp.propTypes = {" +
"strProp: React.PropTypes.string.isRequired" +
"};" +
"Comp.defaultProps = {strProp: \"1\"};" +
"React.createElement(Comp, {});");
testNoError(
"class Comp extends React.Component {" +
"render() {return null;}" +
"}\n" +
"Comp.propTypes = {" +
"strProp: React.PropTypes.string.isRequired" +
"};" +
"Comp.defaultProps = {strProp: \"1\"};" +
"React.createElement(Comp, null);");
// Applies to custom type expressions too
testNoError(
"class Comp extends React.Component {" +
"render() {return null;}" +
"}\n" +
"Comp.propTypes = {" +
"/** @type {boolean} */ boolProp: function() {}" +
"};" +
"Comp.defaultProps = {boolProp: true};" +
"React.createElement(Comp, {});");
// But if they are provided their types are still checked.
testError(
"class Comp extends React.Component {" +
"render() {return null;}" +
"}\n" +
"Comp.propTypes = {" +
"strProp: React.PropTypes.string.isRequired" +
"};" +
"Comp.defaultProps = {strProp: \"1\"};" +
"React.createElement(Comp, {strProp: 1});",
"JSC_TYPE_MISMATCH");
// Even if not required, if they have a default value their value inside
// the component is not null or undefined.
testNoError(
"class Comp extends React.Component {" +
"render() {" +
"this.strMethod_(this.props.strProp);" +
"return null;" +
"}\n" +
"/**" +
" * @param {string} param" +
" * @return {string}" +
" * @private" +
" */" +
"strMethod_(param) {return param;}" +
"}\n" +
"Comp.propTypes = {" +
"strProp: React.PropTypes.string" +
"};\n" +
"Comp.defaultProps = {strProp: \"1\"};\n" +
"React.createElement(Comp, null);");
}
@Test public void testPropTypesMixins() {
testError(
"var Mixin = React.createMixin({" +
"propTypes: {" +
"mixinNumberProp: React.PropTypes.number.isRequired" +
"}" +
"});\n" +
"var Comp = React.createClass({" +
"mixins: [Mixin],\n" +
"propTypes: {" +
"numberProp: React.PropTypes.number.isRequired" +
"}," +
"render: function() {return this.props.mixinNumberProp();}" +
"});\n",
"JSC_NOT_FUNCTION_TYPE");
// Even when the component doesn't have its own propTypes those of the
// mixin are considered.
testError(
"var Mixin = React.createMixin({" +
"propTypes: {" +
"mixinNumberProp: React.PropTypes.number.isRequired" +
"}" +
"});\n" +
"var Comp = React.createClass({" +
"mixins: [Mixin],\n" +
"render: function() {return this.props.mixinNumberProp();}" +
"});\n",
"JSC_NOT_FUNCTION_TYPE");
testNoError(
"var Mixin = React.createMixin({" +
"propTypes: {" +
"mixinFuncProp: React.PropTypes.func.isRequired" +
"}" +
"});\n" +
"var Comp = React.createClass({" +
"mixins: [Mixin],\n" +
"render: function() {return this.props.mixinFuncProp();}" +
"});\n");
// The same propTypes can be in both mixins and components (and the
// component one has precedence).
testNoError(
"var Mixin = React.createMixin({" +
"propTypes: {" +
"aProp: React.PropTypes.number.isRequired" +
"}" +
"});\n" +
"var Comp = React.createClass({" +
"mixins: [Mixin],\n" +
"propTypes: {" +
"aProp: React.PropTypes.number.isRequired" +
"},\n" +
"render: function() {return null;}" +
"});\n");
// Custom type expressions are handled
testNoError(
"var Mixin = React.createMixin({" +
"propTypes: {" +
"/** @type {boolean} */ boolProp: function() {}" +
"}" +
"});\n" +
"var Comp = React.createClass({" +
"mixins: [Mixin],\n" +
"render: function() {return null;}" +
"});\n" +
"React.createElement(Comp, {boolProp: true});");
}
@Test public void testPropTypesMixinsClass() {
testError(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {" +
"}" +
"ReactSupport.declareMixin(Mixin);" +
"Mixin.propTypes = {" +
"mixinNumberProp: React.PropTypes.number.isRequired" +
"};" +
"class Comp extends React.Component {" +
"render() {return this.props.mixinNumberProp();}" +
"}" +
"ReactSupport.mixin(Comp, Mixin);" +
"Comp.propTypes = {" +
"numberProp: React.PropTypes.number.isRequired" +
"};",
"JSC_NOT_FUNCTION_TYPE");
// Even when the component doesn't have its own propTypes those of the
// mixin are considered.
testError(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {}" +
"ReactSupport.declareMixin(Mixin);" +
"Mixin.propTypes = {" +
"mixinNumberProp: React.PropTypes.number.isRequired" +
"};" +
"class Comp extends React.Component {" +
"render() {return this.props.mixinNumberProp();}" +
"}" +
"ReactSupport.mixin(Comp, Mixin);",
"JSC_NOT_FUNCTION_TYPE");
testNoError(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {}" +
"ReactSupport.declareMixin(Mixin);" +
"Mixin.propTypes = {" +
"mixinFuncProp: React.PropTypes.func.isRequired" +
"};" +
"class Comp extends React.Component {" +
"render() {return this.props.mixinFuncProp();}" +
"}"+
"ReactSupport.mixin(Comp, Mixin);");
// The same propTypes can be in both mixins and components (and the
// component one has precedence).
testNoError(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {}" +
"ReactSupport.declareMixin(Mixin);" +
"Mixin.propTypes = {" +
"aProp: React.PropTypes.number.isRequired" +
"};" +
"class Comp extends React.Component {" +
"render() {return null;}" +
"}" +
"ReactSupport.mixin(Comp, Mixin);" +
"Comp.propTypes = {" +
"aProp: React.PropTypes.number.isRequired" +
"};");
// Custom type expressions are handled
testNoError(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {}" +
"ReactSupport.declareMixin(Mixin);" +
"Mixin.propTypes = {" +
"/** @type {boolean} */ boolProp: function() {}" +
"};" +
"class Comp extends React.Component {" +
"render() {return null;}" +
"}" +
"ReactSupport.mixin(Comp, Mixin);" +
"React.createElement(Comp, {boolProp: true});");
}
@Test public void testPropTypesComponentMethods() {
// React component/lifecycle methods automatically get the specific prop
// type injected.
testError(
"var Comp = React.createClass({" +
"propTypes: {" +
"numberProp: React.PropTypes.number.isRequired" +
"}," +
"componentWillReceiveProps: function(nextProps) {" +
"nextProps.numberProp();" +
"},\n" +
"render: function() {return null;}" +
"});\n" +
"React.createElement(Comp, {numberProp: 1});",
"JSC_NOT_FUNCTION_TYPE");
// As do abstract mixin methods that use ReactProps as the type.
testError(
"var Mixin = React.createMixin({" +
"});" +
"/** @param {ReactProps} props @protected */" +
"Mixin.mixinAbstractMethod;\n" +
"var Comp = React.createClass({" +
"mixins: [Mixin],\n" +
"propTypes: {" +
"numberProp: React.PropTypes.number.isRequired" +
"}," +
"mixinAbstractMethod: function(props) {" +
"props.numberProp();" +
"},\n" +
"render: function() {return null;}" +
"});\n" +
"React.createElement(Comp, {numberProp: 1});",
"JSC_NOT_FUNCTION_TYPE");
}
@Test public void testPropTypesComponentMethodsClass() {
// React component/lifecycle methods automatically get the specific prop
// type injected.
testError(
"class Comp extends React.Component {" +
"componentWillReceiveProps(nextProps) {" +
"nextProps.numberProp();" +
"}\n" +
"render() {return null;}" +
"}\n" +
"Comp.propTypes = {" +
"numberProp: React.PropTypes.number.isRequired" +
"};\n" +
"React.createElement(Comp, {numberProp: 1});",
"JSC_NOT_FUNCTION_TYPE");
// As do abstract mixin methods that use ReactProps as the type.
testError(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {}" +
"ReactSupport.declareMixin(Mixin);" +
"/** @param {ReactProps} props @protected */" +
"Mixin.mixinAbstractMethod;" +
"class Comp extends React.Component {" +
"mixinAbstractMethod(props) {" +
"props.numberProp();" +
"}" +
"render() {return null;}" +
"}" +
"ReactSupport.mixin(Comp, Mixin);" +
"Comp.propTypes = {" +
"numberProp: React.PropTypes.number.isRequired" +
"};" +
"React.createElement(Comp, {numberProp: 1});",
"JSC_NOT_FUNCTION_TYPE");
}
private void testPropTypesError(String propTypes, String props, String error) {
testError(
"/** @constructor */ function Message() {};\n" +
"var Comp = React.createClass({" +
"propTypes: " + propTypes + "," +
"render: function() {return null;}" +
"});\n" +
"React.createElement(Comp, " + props + ");",
error);
testError(
"class Message {}\n" +
"class Comp extends React.Component {" +
"render() {return null;}" +
"}\n" +
"Comp.propTypes = " + propTypes + ";\n" +
"React.createElement(Comp, " + props + ");",
error);
}
private void testPropTypesNoError(String propTypes, String props) {
testNoError(
"/** @constructor */ function Message() {};\n" +
"var Comp = React.createClass({" +
"propTypes: " + propTypes + "," +
"render: function() {return null;}" +
"});\n" +
"React.createElement(Comp, " + props + ");");
testNoError(
"class Message {}\n" +
"class Comp extends React.Component {" +
"render() {return null;}" +
"}\n" +
"Comp.propTypes = " + propTypes + ";\n" +
"React.createElement(Comp, " + props + ");");
}
@Test public void testChildren() {
// Non-comprehensive test that the React.Children namespace functions exist.
test(
"var Comp = React.createClass({" +
"propTypes: {" +
"children: React.PropTypes.element.isRequired" +
"}," +
"render: function() {" +
"return React.createElement(" +
"\"div\", null, React.Children.only(this.props.children));" +
"}" +
"});" +
"ReactDOM.render(React.createElement(Comp), document.body);",
"ReactDOM.render(React.createElement(React.createClass({" +
"propTypes:{" +
"children:React.PropTypes.element.isRequired" +
"}," +
"render:function(){" +
"return React.createElement(" +
"\"div\",null,React.Children.only(this.props.children))" +
"}" +
"})),document.body);");
}
@Test public void testChildrenClass() {
// Non-comprehensive test that the React.Children namespace functions exist.
test(
"class Comp extends React.Component {" +
"render() {" +
"return React.createElement(" +
"\"div\", null, React.Children.only(this.props.children));" +
"}" +
"}" +
"Comp.propTypes = {" +
"children: React.PropTypes.element.isRequired" +
"};" +
"ReactDOM.render(React.createElement(Comp), document.body);",
"class $Comp$$ extends React.Component{" +
"render(){" +
"return React.createElement(\"div\",null,React.Children.only(this.props.children))" +
"}" +
"}" +
"$Comp$$.propTypes={children:React.PropTypes.element.isRequired};" +
"ReactDOM.render(React.createElement($Comp$$),document.body);");
}
@Test public void testContextTypesTypeChecking() {
// Validate use of context within methods.
testError(
"var Comp = React.createClass({" +
"contextTypes: {numberProp: React.PropTypes.number}," +
"render: function() {" +
"this.context.numberProp();" +
"return null;" +
"}" +
"});",
"JSC_NOT_FUNCTION_TYPE");
// Both props and context are checked
testNoError(
"var Comp = React.createClass({" +
"contextTypes: {\n" +
"/** @type {function(number)} */\n" +
"functionProp: React.PropTypes.func," +
"}," +
"propTypes: {numberProp: React.PropTypes.number.isRequired}," +
"render: function() {" +
"this.context.functionProp(this.props.numberProp);" +
"return null;" +
"}" +
"});");
testError(
"var Comp = React.createClass({" +
"contextTypes: {\n" +
"/** @type {function(number)} */\n" +
"functionProp: React.PropTypes.func," +
"}," +
"propTypes: {stringProp: React.PropTypes.string.isRequired}," +
"render: function() {" +
"this.context.functionProp(this.props.stringProp);" +
"return null;" +
"}" +
"});",
"JSC_TYPE_MISMATCH");
}
@Test public void testContextTypesTypeCheckingClass() {
// Validate use of context within methods.
testError(
"class Comp extends React.Component {" +
"render() {" +
"this.context.numberProp();" +
"return null;" +
"}" +
"}" +
"Comp.contextTypes = {numberProp: React.PropTypes.number};",
"JSC_NOT_FUNCTION_TYPE");
// Both props and context are checked
test(
"class Comp extends React.Component {" +
"render() {" +
"this.context.functionProp(this.props.numberProp);" +
"return null;" +
"}" +
"}" +
"Comp.contextTypes = {\n" +
"/** @type {function(number)} */\n" +
"functionProp: React.PropTypes.func," +
"};" +
"Comp.propTypes = {numberProp: React.PropTypes.number.isRequired};" +
"ReactDOM.render(React.createElement(Comp), document.body);",
"class $Comp$$ extends React.Component{" +
"render(){" +
"this.context.$functionProp$(this.props.$numberProp$);" +
"return null" +
"}" +
"}" +
"$Comp$$.contextTypes={$functionProp$:React.PropTypes.func};" +
"$Comp$$.propTypes={$numberProp$:React.PropTypes.number.isRequired};" +
"ReactDOM.render(React.createElement($Comp$$),document.body);");
testError(
"class Comp extends React.Component {" +
"render() {" +
"this.context.functionProp(this.props.stringProp);" +
"return null;" +
"}" +
"}" +
"Comp.contextTypes = {\n" +
"/** @type {function(number)} */\n" +
"functionProp: React.PropTypes.func," +
"};\n" +
"Comp.propTypes = {stringProp: React.PropTypes.string.isRequired};",
"JSC_TYPE_MISMATCH");
}
@Test public void testReactDOM() {
test("var Comp = React.createClass({});" +
"ReactDOM.render(React.createElement(Comp), document.body);",
"ReactDOM.render(React.createElement(" +
"React.createClass({})" +
"),document.body);");
test("ReactDOM.findDOMNode(document.body);",
"ReactDOM.findDOMNode(document.body);");
testError("ReactDOM.findDOMNode([document.body]);", "JSC_TYPE_MISMATCH");
test("ReactDOM.unmountComponentAtNode(document.body);",
"ReactDOM.unmountComponentAtNode(document.body);");
testError("ReactDOM.unmountComponentAtNode(\"notanode\");",
"JSC_TYPE_MISMATCH");
}
@Test public void testReactDOMClass() {
test("class Comp extends React.Component {}" +
"ReactDOM.render(React.createElement(Comp), document.body);",
"class $Comp$$ extends React.Component{}" +
"ReactDOM.render(React.createElement($Comp$$),document.body);");
}
@Test public void testReactDOMServer() {
test("var Comp = React.createClass({});" +
"ReactDOMServer.renderToString(React.createElement(Comp));",
"ReactDOMServer.renderToString(" +
"React.createElement(React.createClass({})));");
testError("ReactDOMServer.renderToString(\"notanelement\");",
"JSC_TYPE_MISMATCH");
test("var Comp = React.createClass({});" +
"ReactDOMServer.renderToStaticMarkup(React.createElement(Comp));",
"ReactDOMServer.renderToStaticMarkup(" +
"React.createElement(React.createClass({})));");
testError("ReactDOMServer.renderToStaticMarkup(\"notanelement\");",
"JSC_TYPE_MISMATCH");
}
@Test public void testReactDOMServerClass() {
test("class Comp extends React.Component {}" +
"ReactDOMServer.renderToString(React.createElement(Comp));",
"class $Comp$$ extends React.Component{}" +
"ReactDOMServer.renderToString(React.createElement($Comp$$));");
test("class Comp extends React.Component {}" +
"ReactDOMServer.renderToStaticMarkup(React.createElement(Comp));",
"class $Comp$$ extends React.Component{}" +
"ReactDOMServer.renderToStaticMarkup(React.createElement($Comp$$));");
}
/**
* Tests static methods and properties.
*/
@Test public void testStatics() {
test(
"var Comp = React.createClass({" +
"statics: {" +
"/** @const {number} */" +
"aNumber: 123,\n" +
"/** @const {string} */" +
"aString: \"456\",\n" +
"/** @return {number} */" +
"aFunction: function() {return 123}" +
"},\n" +
"render: function() {return React.createElement(\"div\");}" +
"});\n" +
"window.aNumber = Comp.aNumber;\n" +
"window.aString = Comp.aString;\n" +
"window.aFunctionResult = Comp.aFunction();\n",
"var $Comp$$=React.createClass({" +
"statics:{" +
"$aNumber$:123," +
"$aString$:\"456\"," +
"$aFunction$:function(){return 123}" +
"}," +
"render:function(){return React.createElement(\"div\")}" +
"});" +
"window.$aNumber$=$Comp$$.$aNumber$;" +
"window.$aString$=$Comp$$.$aString$;" +
"window.$aFunctionResult$=123;");
// JSDoc is required
testError(
"var Comp = React.createClass({" +
"statics: {" +
"aFunction: function(aNumber) {window.foo = aNumber}" +
"}," +
"render: function() {return React.createElement(\"div\");}" +
"});",
"REACT_JSDOC_REQUIRED_FOR_STATICS");
// JSDoc is used to validate.
testError(
"var Comp = React.createClass({" +
"statics: {" +
"/** @param {number} aNumber */" +
"aFunction: function(aNumber) {window.foo = aNumber}" +
"}," +
"render: function() {return React.createElement(\"div\");}" +
"});" +
"window.foo = Comp.aFunction('notANumber');",
"JSC_TYPE_MISMATCH");
}
@Test public void testStaticsClass() {
test(
"class Comp extends React.Component {" +
"render() {return React.createElement(\"div\");}" +
"/** @return {number} */" +
"static aFunction() {return 123}" +
"}\n" +
"/** @const {number} */" +
"Comp.aNumber = 123;\n" +
"/** @const {string} */" +
"Comp.aString = \"456\";\n" +
"window.aNumber = Comp.aNumber;\n" +
"window.aString = Comp.aString;\n" +
"window.aFunctionResult = Comp.aFunction();\n",
"window.$aNumber$=123;" +
"window.$aString$=\"456\";" +
"window.$aFunctionResult$=123;");
// JSDoc is used to validate.
testError(
"class Comp extends React.Component {" +
"/** @param {number} aNumber */" +
"static aFunction(aNumber) {window.foo = aNumber}" +
"render() {return React.createElement(\"div\");}" +
"}" +
"window.foo = Comp.aFunction('notANumber');",
"JSC_TYPE_MISMATCH");
}
@Test public void testPureRenderMixin() {
test(
"var Comp = React.createClass({" +
"mixins: [React.addons.PureRenderMixin]," +
"render: function() {" +
"return React.createElement(\"div\");" +
"}" +
"});" +
"ReactDOM.render(React.createElement(Comp), document.body);",
// Should be fine to use React.addons.PureRenderMixin.
"ReactDOM.render(React.createElement(React.createClass({" +
"mixins:[React.addons.PureRenderMixin]," +
"render:function(){" +
"return React.createElement(\"div\")" +
"}" +
"})),document.body);");
testError(
"var Comp = React.createClass({" +
"mixins: [React.addons.PureRenderMixin]," +
"shouldComponentUpdate: function(nextProps, nextState) {" +
"return true;" +
"}," +
"render: function() {" +
"return React.createElement(\"div\");" +
"}" +
"});",
// But there should be a warning if using PureRenderMixin yet
// shouldComponentUpdate is specified.
ReactCompilerPass.PURE_RENDER_MIXIN_SHOULD_COMPONENT_UPDATE_OVERRIDE);
}
@Test public void testExtendsPureComponent() {
test(
"class Comp extends React.PureComponent {" +
"render() {" +
"return React.createElement(\"div\");" +
"}" +
"}" +
"ReactDOM.render(React.createElement(Comp), document.body);",
// Should be fine to use React.PureComponent.
"class $Comp$$ extends React.PureComponent{" +
"render(){" +
"return React.createElement(\"div\")" +
"}" +
"}" +
"ReactDOM.render(React.createElement($Comp$$),document.body);");
testError(
"class Comp extends React.PureComponent {" +
"shouldComponentUpdate(nextProps, nextState) {" +
"return true;" +
"}" +
"render() {" +
"return React.createElement(\"div\");" +
"}" +
"}",
// But there should be a warning if using PureComponent and
// shouldComponentUpdate is specified.
ReactCompilerPass.PURE_COMPONENT_SHOULD_COMPONENT_UPDATE_OVERRIDE);
}
@Test public void testElementTypedef() {
test(
"var Comp = React.createClass({" +
"render: function() {" +
"return React.createElement(\"div\");" +
"}" +
"});\n" +
"/** @return {CompElement} */\n" +
"function create() {return React.createElement(Comp);}",
"");
test(
"var ns = {};" +
"ns.Comp = React.createClass({" +
"render: function() {" +
"return React.createElement(\"div\");" +
"}" +
"});\n" +
"/** @return {ns.CompElement} */\n" +
"function create() {return React.createElement(ns.Comp);}",
"");
}
@Test public void testElementTypedefClass() {
test(
"class Comp extends React.Component {" +
"render() {" +
"return React.createElement(\"div\");" +
"}" +
"}\n" +
"/** @return {CompElement} */\n" +
"function create() {return React.createElement(Comp);}",
"");
test(
"const ns = {};" +
"ns.Comp = class extends React.Component {" +
"render() {" +
"return React.createElement(\"div\");" +
"}" +
"}\n" +
"/** @return {ns.CompElement} */\n" +
"function create() {return React.createElement(ns.Comp);}",
"");
}
@Test public void testPropsSpreadInlining() {
test(
"var Comp = React.createClass({" +
"render: function() {" +
"var props = {a: \"1\"};\n" +
"return React.createElement(\"div\", {...props});" +
"}" +
"});" +
"ReactDOM.render(React.createElement(Comp), document.body);",
"ReactDOM.render(React.createElement(React.createClass({" +
"render:function(){" +
"return React.createElement(\"div\",{$a$:\"1\"})" +
"}" +
"})),document.body);");
}
@Test public void testPropsSpreadInliningClass() {
test(
"class Comp extends React.Component {" +
"render() {" +
"var props = {a: \"1\"};\n" +
"return React.createElement(\"div\", {...props});" +
"}" +
"}" +
"ReactDOM.render(React.createElement(Comp), document.body);",
"class $Comp$$ extends React.Component{" +
"render(){" +
"return React.createElement(\"div\",{$a$:\"1\"})" +
"}" +
"}" +
"ReactDOM.render(React.createElement($Comp$$),document.body);");
}
private static void test(String inputJs, String expectedJs) {
test(inputJs, expectedJs, null, null);
}
private static void testError(String inputJs, String expectedErrorName) {
test(inputJs, "", null, DiagnosticType.error(expectedErrorName, ""));
}
private static void testError(String inputJs, DiagnosticType expectedError) {
test(inputJs, "", null, expectedError);
}
private static void testNoError(String inputJs) {
test(inputJs, null, null, null);
}
private static void test(
String inputJs,
String expectedJs,
ReactCompilerPass.Options passOptions,
DiagnosticType expectedError) {
if (passOptions == null) {
passOptions = new ReactCompilerPass.Options();
passOptions.propTypesTypeChecking = true;
}
Compiler compiler = new Compiler(
new PrintStream(ByteStreams.nullOutputStream())); // Silence logging
compiler.disableThreads(); // Makes errors easier to track down.
CompilerOptions options = new CompilerOptions();
CompilationLevel.ADVANCED_OPTIMIZATIONS
.setOptionsForCompilationLevel(options);
WarningLevel.VERBOSE.setOptionsForWarningLevel(options);
options.setLanguage(CompilerOptions.LanguageMode.ECMASCRIPT_2018);
options.setEmitUseStrict(false); // It is just noise
if (!passOptions.optimizeForSize) {
// We assume that when optimizing for size we don't care about property
// checks (they rely on propTypes being extracted, which we don't do).
options.setWarningLevel(
DiagnosticGroups.MISSING_PROPERTIES, CheckLevel.ERROR);
options.setWarningLevel(
DiagnosticGroups.STRICT_MISSING_PROPERTIES, CheckLevel.ERROR);
}
options.setGenerateExports(true);
options.setExportLocalPropertyDefinitions(true);
options.setGeneratePseudoNames(true);
options.addWarningsGuard(new ReactWarningsGuard());
// Report warnings as errors to make tests simpler
options.addWarningsGuard(new StrictWarningsGuard());
options.addCustomPass(
CustomPassExecutionTime.BEFORE_CHECKS,
new ReactCompilerPass(compiler, passOptions));
List<SourceFile> inputs = Lists.newArrayList();
for (String fileJs : Splitter.on(FILE_SEPARATOR).split(inputJs)) {
inputs.add(
SourceFile.fromCode("/src/file" + (inputs.size() + 1) + ".js", fileJs));
}
List<SourceFile> builtInExterns;
try {
// We need the built-in externs so that Error and other built-in types
// are defined.
builtInExterns = AbstractCommandLineRunner.getBuiltinExterns(
CompilerOptions.Environment.CUSTOM);
} catch (IOException err) {
throw new RuntimeException(err);
}
List<SourceFile> externs = new ImmutableList.Builder()
.addAll(builtInExterns)
.add(SourceFile.fromCode("externs.js",
"/** @constructor */ function Element() {};" +
"/** @constructor */ function Event() {};" +
"var document;" +
"document.body;" +
"var window;"))
.build();
if (passOptions.optimizeForSize) {
options.setPrintInputDelimiter(true);
}
ReactCompilerPass.saveLastOutputForTests = true;
Result result = compiler.compile(externs, inputs, options);
String lastOutput = "\n\nInput:\n" + inputJs + "\nCompiler pass output:\n" +
ReactCompilerPass.lastOutputForTests + "\n";
if (compiler.getRoot() != null) {
// Use getSecondChild to skip over the externs root
lastOutput += "Final compiler output:\n" +
Debug.toTypeAnnotatedSource(
compiler, compiler.getRoot().getSecondChild()) +
"\n";
}
if (expectedError == null) {
assertEquals(
"Unexpected errors: " + Joiner.on(",").join(result.errors) +
lastOutput,
0, result.errors.size());
assertEquals(
"Unexpected warnings: " + Joiner.on(",").join(result.warnings) +
lastOutput,
0, result.warnings.size());
assertTrue(result.success);
if (expectedJs != null) {
String actualJs = compiler.toSource();
if (passOptions.optimizeForSize) {
int inputIndex = actualJs.indexOf(ACTUAL_JS_INPUT_MARKER);
assertNotEquals(-1, inputIndex);
actualJs = actualJs.substring(
inputIndex + ACTUAL_JS_INPUT_MARKER.length());
}
assertEquals(expectedJs, actualJs);
}
} else {
assertFalse(
"Expected failure, instead got output: " + compiler.toSource(),
result.success);
assertTrue(result.errors.size() > 0);
boolean foundError = false;
for (JSError error : result.errors) {
if (error.getType().equals(expectedError)) {
foundError = true;
break;
}
}
assertTrue(
"Did not find expected error " + expectedError +
", instead found " + Joiner.on(",").join(result.errors) +
lastOutput,
foundError);
assertEquals(
"Unexpected warnings: " + Joiner.on(",").join(result.warnings) +
lastOutput,
0, result.warnings.size());
}
}
}
|
test/info/persistent/react/jscomp/ReactCompilerPassTest.java
|
package info.persistent.react.jscomp;
import info.persistent.jscomp.Debug;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.io.ByteStreams;
import com.google.common.io.Resources;
import com.google.javascript.jscomp.AbstractCommandLineRunner;
import com.google.javascript.jscomp.CheckLevel;
import com.google.javascript.jscomp.CodePrinter;
import com.google.javascript.jscomp.CompilationLevel;
import com.google.javascript.jscomp.Compiler;
import com.google.javascript.jscomp.CompilerOptions;
import com.google.javascript.jscomp.CustomPassExecutionTime;
import com.google.javascript.jscomp.DiagnosticGroups;
import com.google.javascript.jscomp.DiagnosticType;
import com.google.javascript.jscomp.JSError;
import com.google.javascript.jscomp.Result;
import com.google.javascript.jscomp.SourceFile;
import com.google.javascript.jscomp.StrictWarningsGuard;
import com.google.javascript.jscomp.WarningLevel;
import org.junit.Test;
import java.io.IOException;
import java.io.PrintStream;
import java.util.List;
/**
* Test {@link ReactCompilerPass}.
*/
public class ReactCompilerPassTest {
// Used to find the test output (and separate it from the injected API
// aliases source)
private static final String ACTUAL_JS_INPUT_MARKER = "// Input 1\n";
// Used to allow test cases to have multiple input files (so that ES6
// modules can be tested).
private static String FILE_SEPARATOR = "\n\n/* --file-separator-- */\n\n";
private static String REACT_SUPPORT_CODE = "var ReactSupport={" +
"declareMixin(mixin){}," +
"mixin(comp,...mixins){comp.mixins=mixins}" +
"};";
@Test public void testMinimalComponent() {
test(
"var Comp = React.createClass({" +
"render: function() {" +
"return React.createElement(" +
"\"div\", null, React.createElement(\"span\", null, \"child\"));" +
"}" +
"});" +
"ReactDOM.render(React.createElement(Comp), document.body);",
// createClass and other React methods should not get renamed.
"ReactDOM.render(React.createElement(React.createClass({" +
"render:function(){" +
"return React.createElement(" +
"\"div\",null,React.createElement(\"span\",null,\"child\"))" +
"}" +
"})),document.body);");
}
@Test public void testMinimalComponentClass() {
test(
"class Comp extends React.Component {" +
"render() {" +
"return React.createElement(" +
"\"div\", null, React.createElement(\"span\", null, \"child\"));" +
"}" +
"}" +
"ReactDOM.render(React.createElement(Comp), document.body);",
// React.Component and other React methods should not get renamed.
"class $Comp$$ extends React.Component{" +
"render(){" +
"return React.createElement(\"div\",null,React.createElement(\"span\",null,\"child\"))" +
"}" +
"}" +
"ReactDOM.render(React.createElement($Comp$$),document.body);");
// ClassExpression using VariableDeclaration
test(
"var Comp = class extends React.Component {" +
"render() {" +
"return React.createElement(" +
"\"div\", null, React.createElement(\"span\", null, \"child\"));" +
"}" +
"};" +
"ReactDOM.render(React.createElement(Comp), document.body);",
// React.Component and other React methods should not get renamed.
"ReactDOM.render(" +
"React.createElement(" +
"class extends React.Component{" +
"render(){" +
"return React.createElement(\"div\",null,React.createElement(\"span\",null,\"child\"))" +
"}" +
"})," +
"document.body);");
// ClassExpression using AssignmnentExpression
test(
"var Comp;" +
"Comp = class extends React.Component {" +
"render() {" +
"return React.createElement(" +
"\"div\", null, React.createElement(\"span\", null, \"child\"));" +
"}" +
"};" +
"ReactDOM.render(React.createElement(Comp), document.body);",
// React.Component and other React methods should not get renamed.
"ReactDOM.render(" +
"React.createElement(" +
"class extends React.Component{" +
"render(){" +
"return React.createElement(\"div\",null,React.createElement(\"span\",null,\"child\"))" +
"}" +
"})," +
"document.body);");
}
@Test public void testEs6Modules() {
test(
"export const Comp = React.createClass({" +
"render: function() {" +
"return React.createElement(" +
"\"div\", null, React.createElement(\"span\", null, \"child\"));" +
"}" +
"});" +
FILE_SEPARATOR +
// Test that we can use the component and associated types from another
// module (i.e. that exports are generated for them).
"import * as file1 from './file1.js';\n" +
"const /** file1.CompElement */ compElement = React.createElement(file1.Comp);\n" +
"const /** file1.CompInterface */ compInstance = ReactDOM.render(compElement, document.body);",
"const $compElement$$module$src$file2$$=React.createElement(React.createClass({" +
"render:function(){" +
"return React.createElement(" +
"\"div\",null,React.createElement(\"span\",null,\"child\"))" +
"}" +
"}));" +
"ReactDOM.render($compElement$$module$src$file2$$,document.body);");
// Cross-module type checking works for props...
testError(
"export const Comp = React.createClass({" +
"propTypes: {aNumber: React.PropTypes.number.isRequired}," +
"render: function() {return null;}" +
"});\n" +
FILE_SEPARATOR +
"import * as file1 from './file1.js';\n" +
"React.createElement(file1.Comp, {aNumber: 'notANumber'});",
"JSC_TYPE_MISMATCH");
// ...and methods.
testError(
"export const Comp = React.createClass({" +
"render: function() {return null;},\n" +
"/** @param {number} a */" +
"method: function(a) {window.foo = a;}" +
"});\n" +
FILE_SEPARATOR +
"import * as file1 from './file1.js';\n" +
"const inst = ReactDOM.render(" +
"React.createElement(file1.Comp), document.body);\n" +
"inst.method('notanumber');",
"JSC_TYPE_MISMATCH");
}
@Test public void testEs6ModulesClass() {
test(
"export class Comp extends React.Component {" +
"render() {" +
"return React.createElement(" +
"\"div\", null, React.createElement(\"span\", null, \"child\"));" +
"}" +
"}" +
FILE_SEPARATOR +
// Test that we can use the component and associated types from another
// module (i.e. that exports are generated for them).
"import * as file1 from './file1.js';\n" +
"const /** file1.CompElement */ compElement = React.createElement(file1.Comp);\n" +
"const /** file1.Comp */ compInstance = ReactDOM.render(compElement, document.body);",
"class $Comp$$module$src$file1$$ extends React.Component{" +
"render(){" +
"return React.createElement(\"div\",null,React.createElement(\"span\",null,\"child\"))" +
"}" +
"};" +
"const $compElement$$module$src$file2$$=React.createElement($Comp$$module$src$file1$$);" +
"ReactDOM.render($compElement$$module$src$file2$$,document.body);");
// Cross-module type checking works for props...
testError(
"export class Comp extends React.Component {\n" +
"render() {return null;}\n" +
"}\n" +
"Comp.propTypes = {aNumber: React.PropTypes.number.isRequired};" +
FILE_SEPARATOR +
"import * as file1 from './file1.js';\n" +
"React.createElement(file1.Comp, {aNumber: 'notANumber'});",
"JSC_TYPE_MISMATCH");
// ...and methods.
testError(
"export class Comp extends React.Component {" +
"render() {return null;}\n" +
"/** @param {number} a */" +
"method(a) {window.foo = a;}" +
"}\n" +
FILE_SEPARATOR +
"import * as file1 from './file1.js';\n" +
"const inst = ReactDOM.render(" +
"React.createElement(file1.Comp), document.body);\n" +
"inst.method('notanumber');",
"JSC_TYPE_MISMATCH");
}
@Test public void testEs6ModulesScoping() {
// Comp being defined as a local variable in the second file should not
// be confused with the Comp from the first file.
testNoError(
"export const Comp = React.createClass({" +
"propTypes: {children: React.PropTypes.element.isRequired}," +
"render: function() {return null;}" +
"});\n" +
FILE_SEPARATOR +
"import * as file1 from './file1.js';\n" +
"const AnotherComp1 = React.createClass({render() {return null}});\n" +
"const AnotherComp2 = React.createClass({render() {return null}});\n" +
"const Comp = Math.random() < 0.5 ? AnotherComp1 : AnotherComp2;" +
"React.createElement(Comp, {});");
// But Comp can be used as a local variable (and is checked correctly) even
// when it's exported.
testError(
"export const Comp = React.createClass({" +
"propTypes: {aNumber: React.PropTypes.number.isRequired}," +
"render: function() {return null;}" +
"});\n" +
"React.createElement(Comp, {aNumber: 'notANumber'});",
"JSC_TYPE_MISMATCH");
}
@Test public void testEs6ModulesScopingClass() {
// Comp being defined as a local variable in the second file should not
// be confused with the Comp from the first file.
testNoError(
"export class Comp extends React.Component {" +
"render() {return null;}" +
"}\n" +
"Comp.propTypes = {children: React.PropTypes.element.isRequired};" +
FILE_SEPARATOR +
"import * as file1 from './file1.js';\n" +
"const AnotherComp1 = React.createClass({render() {return null}});\n" +
"const AnotherComp2 = React.createClass({render() {return null}});\n" +
"const Comp = Math.random() < 0.5 ? AnotherComp1 : AnotherComp2;" +
"React.createElement(Comp, {});");
// But Comp can be used as a local variable (and is checked correctly) even
// when it's exported.
testError(
"export class Comp extends React.Component {" +
"render() {return null;}" +
"}\n" +
"Comp.propTypes = {aNumber: React.PropTypes.number.isRequired};" +
"React.createElement(Comp, {aNumber: 'notANumber'});",
"JSC_TYPE_MISMATCH");
}
@Test public void testEs6ModulesMixins() {
// Mixin references across modules work
testNoError(
"export const Mixin = React.createMixin({" +
"mixinMethod: function() {window.foo = 123}" +
"});\n" +
FILE_SEPARATOR +
"import * as file1 from './file1.js';\n" +
"export const Comp = React.createClass({" +
"mixins: [file1.Mixin]," +
"render: function() {" +
"this.mixinMethod();" +
"return React.createElement(\"div\");" +
"}" +
"});");
// Mixins can be imported directly
testNoError(
"export const Mixin = React.createMixin({" +
"mixinMethod: function() {window.foo = 123}" +
"});\n" +
FILE_SEPARATOR +
"import {Mixin} from './file1.js';\n" +
"export const Comp = React.createClass({" +
"mixins: [Mixin]," +
"render: function() {" +
"this.mixinMethod();" +
"return React.createElement(\"div\");" +
"}" +
"});");
// Or under a different name
testNoError(
"export const Mixin = React.createMixin({" +
"mixinMethod: function() {window.foo = 123}" +
"});\n" +
FILE_SEPARATOR +
"import {Mixin as m} from './file1.js';\n" +
"export const Comp = React.createClass({" +
"mixins: [m]," +
"render: function() {" +
"this.mixinMethod();" +
"return React.createElement(\"div\");" +
"}" +
"});");
// Mixin references can be chained too.
testNoError(
"export const Mixin1 = React.createMixin({" +
"mixinMethod1: function() {window.foo = 123}" +
"});\n" +
FILE_SEPARATOR +
"import * as file1 from './file1.js';\n" +
"export const Mixin2 = React.createMixin({" +
"mixins: [file1.Mixin1]," +
"mixinMethod2: function() {window.foo = 123}" +
"});\n" +
FILE_SEPARATOR +
"import * as file2 from './file2.js';\n" +
"export const Comp = React.createClass({" +
"mixins: [file2.Mixin2]," +
"render: function() {" +
"this.mixinMethod1();" +
"this.mixinMethod2();" +
"return React.createElement(\"div\");" +
"}" +
"});");
// propTypes from imported mixins are handled correctly
testNoError(
"export const Mixin = React.createMixin({" +
"propTypes: {" +
"mixinFuncProp: React.PropTypes.func.isRequired" +
"}" +
"});\n" +
FILE_SEPARATOR +
"import * as file1 from './file1.js';\n" +
"var Comp = React.createClass({" +
"mixins: [file1.Mixin],\n" +
"render: function() {return this.props.mixinFuncProp();}" +
"});\n");
// Including those that reference types from the mixin's file
testNoError(
"export const Obj = class {};\n" +
"export const Mixin = React.createMixin({" +
"propTypes: {" +
"mixinProp: React.PropTypes.instanceOf(Obj).isRequired" +
"}" +
"});\n" +
FILE_SEPARATOR +
"import * as file1 from './file1.js';\n" +
"var Comp = React.createClass({" +
"mixins: [file1.Mixin],\n" +
"render: function() {return null;}" +
"});\n");
}
@Test public void testEs6ModulesMixinsClass() {
// Mixin references across modules work
testNoError(
REACT_SUPPORT_CODE +
"export class Mixin extends React.Component {" +
"mixinMethod() {window.foo = 123}" +
"}" +
"ReactSupport.declareMixin(Mixin);" +
FILE_SEPARATOR +
REACT_SUPPORT_CODE +
"import * as file1 from './file1.js';\n" +
"export class Comp extends React.Component {" +
"render() {" +
"this.mixinMethod();" +
"return React.createElement(\"div\");" +
"}" +
"}" +
"ReactSupport.mixin(Comp, file1.Mixin);");
// Mixins can be imported directly
testNoError(
REACT_SUPPORT_CODE +
"export class Mixin extends React.Component {" +
"mixinMethod() {window.foo = 123}" +
"}" +
"ReactSupport.declareMixin(Mixin);" +
FILE_SEPARATOR +
REACT_SUPPORT_CODE +
"import {Mixin} from './file1.js';" +
"export class Comp extends React.Component {" +
"render() {" +
"this.mixinMethod();" +
"return React.createElement(\"div\");" +
"}" +
"}" +
"ReactSupport.mixin(Comp, Mixin);");
// Make sure we can use the mixin twice without adding an import twice
testNoError(
REACT_SUPPORT_CODE +
"export class Mixin extends React.Component {" +
"mixinMethod() {window.foo = 123}" +
"}" +
"ReactSupport.declareMixin(Mixin);" +
FILE_SEPARATOR +
REACT_SUPPORT_CODE +
"import {Mixin} from './file1.js';" +
"export class Comp extends React.Component {" +
"render() {" +
"this.mixinMethod();" +
"return React.createElement(\"div\");" +
"}" +
"}" +
"ReactSupport.mixin(Comp, Mixin);" +
"export class Comp2 extends React.Component {" +
"render() {" +
"this.mixinMethod();" +
"return null;" +
"}" +
"}" +
"ReactSupport.mixin(Comp2, Mixin);");
// Or under a different name
testNoError(
REACT_SUPPORT_CODE +
"export class Mixin extends React.Component {" +
"mixinMethod() {window.foo = 123}" +
"}" +
"ReactSupport.declareMixin(Mixin);" +
FILE_SEPARATOR +
REACT_SUPPORT_CODE +
"import {Mixin as m} from './file1.js';\n" +
"export class Comp extends React.Component {" +
"render() {" +
"this.mixinMethod();" +
"return React.createElement(\"div\");" +
"}" +
"}" +
"ReactSupport.mixin(Comp, m);");
// Mixin references can be chained too.
testNoError(
REACT_SUPPORT_CODE +
"export class Mixin1 extends React.Component {" +
"mixinMethod1() {window.foo = 123}" +
"}" +
"ReactSupport.declareMixin(Mixin1);" +
FILE_SEPARATOR +
REACT_SUPPORT_CODE +
"import * as file1 from './file1.js';\n" +
"export class Mixin2 extends React.Component {" +
"mixinMethod2() {window.foo = 123}" +
"}" +
"ReactSupport.declareMixin(Mixin2);" +
"ReactSupport.mixin(Mixin2, file1.Mixin1);" +
FILE_SEPARATOR +
REACT_SUPPORT_CODE +
"import * as file2 from './file2.js';\n" +
"export class Comp extends React.Component {" +
"render() {" +
"this.mixinMethod1();" +
"this.mixinMethod2();" +
"return React.createElement(\"div\");" +
"}" +
"}" +
"ReactSupport.mixin(Comp, file2.Mixin2);");
// propTypes from imported mixins are handled correctly
testNoError(
REACT_SUPPORT_CODE +
"export class Mixin extends React.Component {}" +
"ReactSupport.declareMixin(Mixin);" +
"Mixin.propTypes = {" +
"mixinFuncProp: React.PropTypes.func.isRequired" +
"};" +
FILE_SEPARATOR +
REACT_SUPPORT_CODE +
"import * as file1 from './file1.js';" +
"class Comp extends React.Component {" +
"render() {return this.props.mixinFuncProp();}" +
"}" +
"ReactSupport.mixin(Comp, file1.Mixin);");
// Including those that reference types from the mixin's file
testNoError(
REACT_SUPPORT_CODE +
"export const Obj = class {};\n" +
"export class Mixin extends React.Component {}" +
"ReactSupport.declareMixin(Mixin);" +
"Mixin.propTypes = {" +
"mixinProp: React.PropTypes.instanceOf(Obj).isRequired" +
"};" +
FILE_SEPARATOR +
REACT_SUPPORT_CODE +
"import * as file1 from './file1.js';\n" +
"class Comp extends React.Component {" +
"render() {return null;}" +
"}" +
"ReactSupport.mixin(Comp, file1.Mixin);");
}
@Test public void testInstanceMethods() {
test(
"var Comp = React.createClass({" +
"render: function() {return React.createElement(\"div\");}," +
"method: function() {window.foo = 123;}" +
"});" +
"var inst = ReactDOM.render(React.createElement(Comp), document.body);" +
"inst.method();",
// Method invocations should not result in warnings if they're known.
"ReactDOM.render(React.createElement(React.createClass({" +
"render:function(){return React.createElement(\"div\")}," +
"$method$:function(){window.$foo$=123}" +
"})),document.body).$method$();");
test(
"var Comp = React.createClass({" +
"render: function() {return React.createElement(\"div\");}," +
"/** @private */" +
"privateMethod1_: function(a) {window.foo = 123 + a;}," +
"/** @private */" +
"privateMethod2_: function() {this.privateMethod1_(1);}" +
"});" +
"ReactDOM.render(React.createElement(Comp), document.body);",
// Private methods should be invokable.
"ReactDOM.render(React.createElement(React.createClass({" +
"render:function(){return React.createElement(\"div\")}," +
"$privateMethod1_$:function($a$jscomp$1$$){window.$foo$=123+$a$jscomp$1$$}," +
"$privateMethod2_$:function(){this.$privateMethod1_$(1)}" +
"})),document.body);");
testError(
"var Comp = React.createClass({" +
"render: function() {return React.createElement(\"div\");}," +
"/** @param {number} a */" +
"method: function(a) {window.foo = a;}" +
"});" +
"var inst = ReactDOM.render(React.createElement(Comp), document.body);" +
"inst.method('notanumber');",
// Their arguments should be validated.
"JSC_TYPE_MISMATCH");
testError(
"var Comp = React.createClass({" +
"render: function() {return React.createElement(\"div\");}" +
"});" +
"var inst = ReactDOM.render(React.createElement(Comp), document.body);" +
"inst.unknownMethod()",
// And unknown methods should be flagged.
"JSC_INEXISTENT_PROPERTY");
}
@Test public void testInstanceMethodsClass() {
test(
"class Comp extends React.Component {" +
"render() {return React.createElement(\"div\");}" +
"method() {window.foo = 123;}" +
"}" +
"var inst = ReactDOM.render(React.createElement(Comp), document.body);" +
"inst.method();",
// Method invocations should not result in warnings if they're known.
"class $Comp$$ extends React.Component{" +
"render(){return React.createElement(\"div\")}" +
"}" +
"ReactDOM.render(React.createElement($Comp$$),document.body);" +
"window.$foo$=123;");
test(
"class Comp extends React.Component {" +
"render() {return React.createElement(\"div\");}" +
"/** @private */" +
"privateMethod1_(a) {window.foo = 123 + a;}" +
"/** @private */" +
"privateMethod2_() {this.privateMethod1_(1);}" +
"}" +
"ReactDOM.render(React.createElement(Comp), document.body);",
// Private methods should be invokable.
"class $Comp$$ extends React.Component{" +
"render(){return React.createElement(\"div\")}"+
"}" +
"ReactDOM.render(React.createElement($Comp$$),document.body);");
testError(
"class Comp extends React.Component {" +
"render() {return React.createElement(\"div\");}" +
"/** @param {number} a */" +
"method(a) {window.foo = a;}" +
"}" +
"var inst = ReactDOM.render(React.createElement(Comp), document.body);" +
"inst.method('notanumber');",
// Their arguments should be validated.
"JSC_TYPE_MISMATCH");
testError(
"class Comp extends React.Component {" +
"render() {return React.createElement(\"div\");}" +
"}" +
"var inst = ReactDOM.render(React.createElement(Comp), document.body);" +
"inst.unknownMethod()",
// And unknown methods should be flagged.
"JSC_INEXISTENT_PROPERTY");
}
@Test public void testMixins() {
test(
"var ChainedMixin = React.createMixin({" +
"chainedMixinMethod: function() {window.foo = 456}" +
"});\n" +
"var Mixin = React.createMixin({" +
"mixins: [ChainedMixin]," +
"mixinMethod: function() {window.foo = 123}" +
"});\n" +
"var Comp = React.createClass({" +
"mixins: [Mixin]," +
"render: function() {" +
"this.mixinMethod();" +
"this.chainedMixinMethod();" +
"return React.createElement(\"div\");" +
"}" +
"});" +
"var inst = ReactDOM.render(React.createElement(Comp), document.body);" +
"inst.mixinMethod();" +
"inst.chainedMixinMethod();",
// Mixin method invocations should not result in warnings if they're
// known, either directly or via chained mixins.
"var $inst$$=ReactDOM.render(React.createElement(React.createClass({" +
"mixins:[{" +
"mixins:[{" +
"$chainedMixinMethod$:function(){window.$foo$=456}" +
"}]," +
"$mixinMethod$:function(){window.$foo$=123}" +
"}]," +
"render:function(){" +
"this.$mixinMethod$();" +
"this.$chainedMixinMethod$();" +
"return React.createElement(\"div\")" +
"}" +
"})),document.body);" +
"$inst$$.$mixinMethod$();" +
"$inst$$.$chainedMixinMethod$();");
test(
"var Mixin = React.createMixin({" +
"mixinMethod: function() {window.foo=this.mixinAbstractMethod()}" +
"});" +
"/** @return {number} @protected */" +
"Mixin.mixinAbstractMethod;" +
"var Comp = React.createClass({" +
"mixins: [Mixin]," +
"render: function() {" +
"this.mixinMethod();" +
"return React.createElement(\"div\");" +
"}," +
"mixinAbstractMethod: function() {return 123;}" +
"});" +
"ReactDOM.render(React.createElement(Comp), document.body);",
// Mixins can support abstract methods via additional properties.
"ReactDOM.render(React.createElement(React.createClass({" +
"mixins:[{" +
"$mixinMethod$:function(){window.$foo$=123}" +
"}]," +
"render:function(){" +
"this.$mixinMethod$();" +
"return React.createElement(\"div\")" +
"}," +
"$mixinAbstractMethod$:function(){return 123}" +
"})),document.body);");
testError(
"var Mixin = React.createMixin({" +
"/** @param {number} a */" +
"mixinMethod: function(a) {window.foo = 123}" +
"});\n" +
"var Comp = React.createClass({" +
"mixins: [Mixin]," +
"render: function() {" +
"this.mixinMethod(\"notanumber\");" +
"return React.createElement(\"div\");" +
"}" +
"});" +
"var inst = ReactDOM.render(React.createElement(Comp), document.body);" +
"inst.mixinMethod(\"notanumber\");",
// Mixin methods should have their parameter types check when invoked from
// the component.
"JSC_TYPE_MISMATCH");
testError(
"var Mixin = React.createMixin({" +
"/** @private */" +
"privateMixinMethod_: function() {}" +
"});\n" +
"var Comp = React.createClass({" +
"mixins: [Mixin]," +
"render: function() {" +
"this.privateMixinMethod_();" +
"return null;" +
"}" +
"});",
// Private mixin methods should not be exposed to the component.
"JSC_INEXISTENT_PROPERTY");
testError(
"var Mixin = React.createMixin({" +
"mixinMethod: function() {" +
"window.foo = this.mixinAbstractMethod().noSuchMethod()" +
"}" +
"});" +
"/** @return {number} */" +
"Mixin.mixinAbstractMethod;" +
"var Comp = React.createClass({" +
"mixins: [Mixin]," +
"render: function() {" +
"this.mixinMethod();" +
"return React.createElement(\"div\");" +
"}," +
"mixinAbstractMethod: function() {return 123;}" +
"});",
// Abstract methods have their types checked too, on both the mixin
// side...
"JSC_INEXISTENT_PROPERTY");
testError(
"var Mixin = React.createMixin({" +
"mixinMethod: function() {window.foo = this.mixinAbstractMethod()}" +
"});" +
"/** @return {number} */" +
"Mixin.mixinAbstractMethod;" +
"var Comp = React.createClass({" +
"mixins: [Mixin]," +
"render: function() {" +
"this.mixinMethod();" +
"return React.createElement(\"div\");" +
"}," +
"mixinAbstractMethod: function() {return \"notanumber\";}" +
"});",
// ...and the component side
"JSC_TYPE_MISMATCH");
test(
"var Mixin = React.createMixin({});" +
"/** @param {number} param1 */" +
"Mixin.mixinAbstractMethod;" +
"var Comp = React.createClass({" +
"mixins: [Mixin]," +
"render: function() {" +
"return React.createElement(\"div\");" +
"}," +
"mixinAbstractMethod: function() {}" +
"});",
// But implementations should be OK if they omit parameters...
"");
test(
"var Mixin = React.createMixin({});" +
"/** @param {number} param1 */" +
"Mixin.mixinAbstractMethod;" +
"var Comp = React.createClass({" +
"mixins: [Mixin]," +
"render: function() {" +
"return React.createElement(\"div\");" +
"}," +
"mixinAbstractMethod: function(renamedParam1) {}" +
"});",
// ...or rename them.
"");
test(
"var Mixin = React.createMixin({});" +
"/**\n" +
" * @param {T} param1\n" +
" * @return {T}\n" +
" * @template T\n" +
" */" +
"Mixin.mixinAbstractMethod;" +
"var Comp = React.createClass({" +
"mixins: [Mixin]," +
"render: function() {" +
"return React.createElement(\"div\");" +
"}," +
"mixinAbstractMethod: function(param1) {return param1}" +
"});",
// Template types are copied over.
"");
}
@Test public void testMixinsClass() {
testError(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {}" +
"ReactSupport.declareMixin(42);",
"DECLARE_MIXIN_PARAM_NOT_VALID");
testError(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {}" +
"ReactSupport.declareMixin(x, y);",
"DECLARE_MIXIN_UNEXPECTED_NUMBER_OF_PARAMS");
testError(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {}" +
"ReactSupport.declareMixin();",
"DECLARE_MIXIN_UNEXPECTED_NUMBER_OF_PARAMS");
testError(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {}" +
"ReactSupport.declareMixin(Unknown);",
"REACT_MIXIN_UNKNOWN");
testError(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {}" +
"ReactSupport.mixin();",
"MIXIN_UNEXPECTED_NUMBER_OF_PARAMS");
testError(
REACT_SUPPORT_CODE +
"class Comp extends React.Component {}" +
"ReactSupport.mixin(Comp);",
"MIXIN_UNEXPECTED_NUMBER_OF_PARAMS");
test(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {}" +
"ReactSupport.declareMixin(Mixin);" +
"class Comp extends React.Component {}" +
"ReactSupport.mixin(Comp, Mixin);",
"");
test(
REACT_SUPPORT_CODE +
"class MixinA extends React.Component {}" +
"ReactSupport.declareMixin(MixinA);" +
"class MixinB extends React.Component {}" +
"ReactSupport.declareMixin(MixinB);" +
"class Comp extends React.Component {}" +
"ReactSupport.mixin(Comp, MixinA, MixinB);",
"");
testError(
REACT_SUPPORT_CODE +
"class Comp extends React.Component {}" +
"class NotAMixin extends React.Component {}" +
"ReactSupport.mixin(Comp, NotAMixin);",
"MIXIN_PARAM_IS_NOT_MIXIN");
// It is a bit surprising that Closure Compiler can inline this. It probably
// works because there is only one implementation of the method.
test(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {" +
"/** @return {*} */" +
"mixinMethod() {window.foo=this.mixinAbstractMethod()}" +
"}" +
"ReactSupport.declareMixin(Mixin);" +
"/** @return {number} @protected */" +
"Mixin.mixinAbstractMethod;" +
"class Comp extends React.Component {" +
"mixinAbstractMethod() {" +
"return 42;" +
"}" +
"}" +
"ReactSupport.mixin(Comp, Mixin);" +
"var inst = ReactDOM.render(React.createElement(Comp), document.body);" +
"inst.mixinMethod();",
"class $Mixin$$ extends React.Component{}" +
"class $Comp$$ extends React.Component{}" +
"$Comp$$.mixins=[$Mixin$$];" +
"ReactDOM.render(React.createElement($Comp$$),document.body);" +
"window.$foo$=42;");
test(
REACT_SUPPORT_CODE +
"class ChainedMixin extends React.Component {" +
"chainedMixinMethod() {window.foo = 456}" +
"}" +
"ReactSupport.declareMixin(ChainedMixin);" +
"class Mixin extends React.Component {" +
"mixinMethod() {window.foo = 123}" +
"}" +
"ReactSupport.declareMixin(Mixin);" +
"ReactSupport.mixin(Mixin, ChainedMixin);" +
"class Comp extends React.Component {" +
"render() {" +
"this.mixinMethod();" +
"this.chainedMixinMethod();" +
"return React.createElement(\"div\");" +
"}" +
"}" +
"ReactSupport.mixin(Comp, Mixin);" +
"var inst = ReactDOM.render(React.createElement(Comp), document.body);" +
"inst.mixinMethod();" +
"inst.chainedMixinMethod();",
// Mixin method invocations should not result in warnings if they're
// known, either directly or via chained mixins.
"class $ChainedMixin$$ extends React.Component{}" +
"class $Mixin$$ extends React.Component{}" +
"$Mixin$$.mixins=[$ChainedMixin$$];" +
"class $Comp$$ extends React.Component{" +
"render(){" +
"window.$foo$=456;" +
"return React.createElement(\"div\")" +
"}" +
"}" +
"$Comp$$.mixins=[$Mixin$$];" +
"ReactDOM.render(React.createElement($Comp$$),document.body);" +
"window.$foo$=123;" +
"window.$foo$=456;");
test(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {" +
"mixinMethod() {window.foo=this.mixinAbstractMethod()}" +
"}" +
"ReactSupport.declareMixin(Mixin);" +
"/** @return {number} @protected */" +
"Mixin.mixinAbstractMethod;" +
"class Comp extends React.Component {" +
"render() {" +
"this.mixinMethod();" +
"return React.createElement(\"div\");" +
"}" +
"mixinAbstractMethod() {return 123;}" +
"}" +
"ReactSupport.mixin(Comp, Mixin);" +
"ReactDOM.render(React.createElement(Comp), document.body);",
// Mixins can support abstract methods via additional properties.
"class $Mixin$$ extends React.Component{}" +
"class $Comp$$ extends React.Component{" +
"render(){" +
"window.$foo$=123;" +
"return React.createElement(\"div\")" +
"}" +
"}" +
"$Comp$$.mixins=[$Mixin$$];" +
"ReactDOM.render(React.createElement($Comp$$),document.body);");
testError(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {" +
"/** @param {number} a */" +
"mixinMethod(a) {window.foo = 123}" +
"}" +
"ReactSupport.declareMixin(Mixin);" +
"class Comp extends React.Component {" +
"render() {" +
"this.mixinMethod(\"notanumber\");" +
"return React.createElement(\"div\");" +
"}" +
"}" +
"ReactSupport.mixin(Comp, Mixin);" +
"var inst = ReactDOM.render(React.createElement(Comp), document.body);" +
"inst.mixinMethod(\"notanumber\");",
// Mixin methods should have their parameter types check when invoked from
// the component.
"JSC_TYPE_MISMATCH");
testError(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {" +
"/** @private */" +
"privateMixinMethod_() {}" +
"}" +
"ReactSupport.declareMixin(Mixin);" +
"class Comp extends React.Component {" +
"render() {" +
"this.privateMixinMethod_();" +
"return null;" +
"}" +
"}" +
"ReactSupport.mixin(Comp, Mixin);",
// Private mixin methods should not be exposed to the component.
"JSC_INEXISTENT_PROPERTY");
testError(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {" +
"mixinMethod() {" +
"window.foo = this.mixinAbstractMethod().noSuchMethod()" +
"}" +
"}" +
"ReactSupport.declareMixin(Mixin);" +
"/** @return {number} */" +
"Mixin.mixinAbstractMethod;" +
"class Comp extends React.Component {" +
"render() {" +
"this.mixinMethod();" +
"return React.createElement(\"div\");" +
"}" +
"mixinAbstractMethod() {return 123;}" +
"}" +
"ReactSupport.mixin(Comp, Mixin);",
// Abstract methods have their types checked too, on both the mixin
// side...
"JSC_INEXISTENT_PROPERTY");
testError(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {" +
"mixinMethod() {window.foo = this.mixinAbstractMethod()}" +
"}" +
"ReactSupport.declareMixin(Mixin);" +
"/** @return {number} */" +
"Mixin.mixinAbstractMethod;" +
"class Comp extends React.Component {" +
"render() {" +
"this.mixinMethod();" +
"return React.createElement(\"div\");" +
"}" +
"mixinAbstractMethod() {return \"notanumber\";}" +
"}" +
"ReactSupport.mixin(Comp, Mixin);",
// ...and the component side
"JSC_TYPE_MISMATCH");
test(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {}" +
"ReactSupport.declareMixin(Mixin);" +
"/** @param {number} param1 */" +
"Mixin.mixinAbstractMethod;" +
"class Comp extends React.Component {" +
"render() {" +
"return React.createElement(\"div\");" +
"}" +
"mixinAbstractMethod() {}" +
"}" +
"ReactSupport.mixin(Comp, Mixin);",
// But implementations should be OK if they omit parameters...
"");
test(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {}" +
"ReactSupport.declareMixin(Mixin);" +
"/** @param {number} param1 */" +
"Mixin.mixinAbstractMethod;" +
"class Comp extends React.Component {" +
"render() {" +
"return React.createElement(\"div\");" +
"}" +
"mixinAbstractMethod(renamedParam1) {}" +
"}" +
"ReactSupport.mixin(Comp, Mixin);",
// ...or rename them.
"");
test(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {}" +
"ReactSupport.declareMixin(Mixin);" +
"/**\n" +
" * @param {T} param1\n" +
" * @return {T}\n" +
" * @template T\n" +
" */" +
"Mixin.mixinAbstractMethod;" +
"class Comp extends React.Component {" +
"render() {" +
"return React.createElement(\"div\");" +
"}" +
"mixinAbstractMethod(param1) {return param1}" +
"}" +
"ReactSupport.mixin(Comp, Mixin);",
// Template types are copied over.
"");
}
@Test public void testMixinOnExportClass() {
// The real error here was that SymbolTable uses a HashMap but we need an
// Map that iterates in th insertion order.
testNoError(
REACT_SUPPORT_CODE +
"class TestMixin extends React.Component {" +
"/** @return {string} */" +
"d1() {" +
"return \"M12\";" +
"}" +
"}" +
"ReactSupport.declareMixin(TestMixin);" +
"export class AddCommentIcon extends React.Component {" +
"/** @override */" +
"render() {" +
"this.d1();" +
"return null;" +
"}" +
"}" +
"ReactSupport.mixin(AddCommentIcon, TestMixin);");
}
@Test public void testMixinImplementsClass() {
test(
REACT_SUPPORT_CODE +
"/** @interface */" +
"class I {" +
"/**\n" +
" *@param {number} x\n" +
" *@return {string} x\n" +
" */\n" +
"m(x) {}" +
"}" +
"/** @implements {I} */" +
"class Mixin extends React.Component {" +
"/** @override */" +
"m(x) { return \"x\"; }" +
"}" +
"ReactSupport.declareMixin(Mixin);" +
"class Comp extends React.Component {}" +
"ReactSupport.mixin(Comp, Mixin);",
"");
}
@Test public void testMixinsRepeatedMethods() {
test(
"var Mixin = React.createMixin({" +
"componentDidMount: function() {}" +
"});\n" +
"var Comp = React.createClass({" +
"mixins: [Mixin]," +
"componentDidMount: function() {}," +
"render: function() {" +
"return React.createElement(\"div\");" +
"}" +
"});",
// It's OK for a base class to redefine a mixin's method component
// lifecycle method.
"");
}
@Test public void testMixinsRepeatedMethodsClass() {
test(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {" +
"componentDidMount() {}" +
"}" +
"ReactSupport.declareMixin(Mixin);" +
"class Comp extends React.Component {" +
"componentDidMount() {}" +
"render() {" +
"return React.createElement(\"div\");" +
"}" +
"}" +
"ReactSupport.mixin(Comp, Mixin);",
// It's OK for a base class to redefine a mixin's method component
// lifecycle method.
"");
}
@Test public void testNamespacedComponent() {
test(
"var ns = {};ns.Comp = React.createClass({" +
"render: function() {return React.createElement(\"div\");}" +
"});" +
"ReactDOM.render(React.createElement(ns.Comp), document.body);",
"ReactDOM.render(React.createElement(React.createClass({" +
"render:function(){return React.createElement(\"div\")}" +
"})),document.body);");
}
@Test public void testNamespacedComponentClass() {
test(
"var ns = {};ns.Comp = class extends React.Component {" +
"render() {return React.createElement(\"div\");}" +
"};" +
"ReactDOM.render(React.createElement(ns.Comp), document.body);",
"ReactDOM.render(React.createElement(" +
"class extends React.Component{" +
"render(){" +
"return React.createElement(\"div\")" +
"}" +
"})," +
"document.body);");
}
@Test public void testUnusedComponent() {
test(
// Unused components should not appear in the output.
"var Unused = React.createClass({" +
"render: function() {return React.createElement(\"div\", null);}" +
"});",
"");
}
@Test public void testUnusedComponentClass() {
test(
// Unused components should not appear in the output.
"class Unused extends React.Component {" +
"render() {return React.createElement(\"div\", null);}" +
"}",
"");
}
@Test public void testThisUsage() {
test(
"var Comp = React.createClass({" +
"render: function() {return React.createElement(\"div\");}," +
"method: function() {this.setState({foo: 123});}" +
"});" +
"ReactDOM.render(React.createElement(Comp), document.body);",
// Use of "this" should not cause any warnings.
"ReactDOM.render(React.createElement(React.createClass({" +
"render:function(){return React.createElement(\"div\")}," +
"$method$:function(){this.setState({$foo$:123})}" +
"})),document.body);");
}
@Test public void testThisUsageClass() {
test(
"class Comp extends React.Component {" +
"render() {return React.createElement(\"div\");}" +
"method() {this.setState({foo: 123});}" +
"}" +
"ReactDOM.render(React.createElement(Comp), document.body);",
// Use of "this" should not cause any warnings.
"class $Comp$$ extends React.Component{" +
"render(){return React.createElement(\"div\")}" +
"}" +
"ReactDOM.render(React.createElement($Comp$$),document.body);");
}
/**
* Tests React.createClass() validation done by the compiler pass (as opposed
* to type-based validation).
*/
@Test public void testCreateClassValidation() {
testError(
"var Comp = React.createClass(1)",
ReactCompilerPass.CREATE_TYPE_SPEC_NOT_VALID);
testError(
"var Comp = React.createClass({}, 1)",
ReactCompilerPass.CREATE_TYPE_UNEXPECTED_PARAMS);
testError(
"var a = 1 + React.createClass({})",
ReactCompilerPass.CREATE_TYPE_TARGET_INVALID);
}
/**
* Tests React.createMixin() validation done by the compiler pass (as opposed
* to type-based validation).
*/
@Test public void testCreateMixinValidation() {
testError(
"var Mixin = React.createMixin(1)",
ReactCompilerPass.CREATE_TYPE_SPEC_NOT_VALID);
testError(
"var Mixin = React.createMixin({}, 1)",
ReactCompilerPass.CREATE_TYPE_UNEXPECTED_PARAMS);
testError(
"var a = 1 + React.createMixin({})",
ReactCompilerPass.CREATE_TYPE_TARGET_INVALID);
}
/**
* Tests "mixins" spec property validation done by the compiler pass (as
* opposed to type-based validation).
*/
@Test public void testMixinsValidation() {
testError(
"var Comp = React.createClass({mixins: 1})",
ReactCompilerPass.MIXINS_UNEXPECTED_TYPE);
testError(
"var Comp = React.createClass({mixins: [1]})",
ReactCompilerPass.MIXIN_EXPECTED_NAME);
testError(
"var Comp = React.createClass({mixins: [NonExistent]})",
ReactCompilerPass.MIXIN_UNKNOWN);
}
/**
* Tests React.createElement() validation done by the compiler pass (as
* opposed to type-based validation).
*/
@Test public void testCreateElementValidation() {
testError(
"React.createElement()",
ReactCompilerPass.CREATE_ELEMENT_UNEXPECTED_PARAMS);
}
/**
* Tests that React.createElement calls have their return type cast to either
* ReactDOMElement or ReactElement.<ClassType>
*/
@Test public void testCreateElementCasting() {
// Tests that element.type is a string
test(
"window.type = React.createElement(\"div\").type.charAt(0)",
"window.type=React.createElement(\"div\").type.charAt(0);");
// Tests that element.type is not a string...
testError(
"var Comp = React.createClass({" +
"render: function() {return React.createElement(\"div\");}" +
"});" +
"React.createElement(Comp).type.charAt(0)",
"JSC_INEXISTENT_PROPERTY");
// ...but is present...
test(
"var Comp = React.createClass({" +
"render: function() {return React.createElement(\"div\");}" +
"});" +
"window.type = React.createElement(Comp).type;",
"window.type=React.createElement(React.createClass({" +
"render:function(){return React.createElement(\"div\")}" +
"})).type;");
// ...unlike other properties.
testError(
"var Comp = React.createClass({" +
"render: function() {return React.createElement(\"div\");}" +
"});" +
"window.foo = React.createElement(Comp).notAnElementProperty;",
"JSC_INEXISTENT_PROPERTY");
}
@Test public void testCreateElementCastingClass() {
// Tests that element.type is not a string...
testError(
"class Comp extends React.Component {" +
"render() {return React.createElement(\"div\");}" +
"}" +
"React.createElement(Comp).type.charAt(0)",
"JSC_INEXISTENT_PROPERTY");
// ...but is present...
test(
"class Comp extends React.Component {" +
"render() {return React.createElement(\"div\");}" +
"}" +
"window.type = React.createElement(Comp).type;",
"class $Comp$$ extends React.Component{" +
"render(){return React.createElement(\"div\")}" +
"}" +
"window.type=React.createElement($Comp$$).type;");
// ...unlike other properties.
testError(
"class Comp extends React.Component {" +
"render() {return React.createElement(\"div\");}" +
"}" +
"window.foo = React.createElement(Comp).notAnElementProperty;",
"JSC_INEXISTENT_PROPERTY");
}
/**
* Tests validation done by the types declared in the types.js file. Not
* exhaustive, just tests that the type declarations are included.
*/
@Test public void testTypeValidation() {
testError(
"var Comp = React.createClass({render: \"notafunction\"});",
"JSC_TYPE_MISMATCH");
testError(
"var Comp = React.createClass({displayName: function() {}});",
"JSC_TYPE_MISMATCH");
test(
"var Comp = React.createClass({" +
"render: function() {return React.createElement(\"div\");}" +
"});" +
"window.foo = Comp.displayName.charAt(0);",
// displayName is a valid string property of classes
"window.$foo$=React.createClass({" +
"render:function(){return React.createElement(\"div\")}" +
"}).displayName.charAt(0);");
// Stopped working in v20190513
// testError(
// "var Comp = React.createClass({" +
// "render: function() {return React.createElement(\"div\");}" +
// "});" +
// "window.foo = Comp.displayName.notAStringMethod();",
// "JSC_POSSIBLE_INEXISTENT_PROPERTY");
// testError(
// "var Comp = React.createClass({" +
// "render: function() {return React.createElement(\"div\");}" +
// "});" +
// "window.foo = Comp.nonExistentProperty;",
// "JSC_POSSIBLE_INEXISTENT_PROPERTY");
testError(
"var Comp = React.createClass({" +
"render: function() {return React.createElement(\"div\");}" +
"});" +
"ReactDOM.render(React.createElement(Comp), document.body, 123);",
"JSC_TYPE_MISMATCH");
testError(
"var Comp = React.createClass({" +
"render: function() {return React.createElement(\"div\");}," +
"shouldComponentUpdate: function(nextProps, nextState) {return 123;}" +
"});",
// Overrides/implemementations of built-in methods should conform to the
// type annotations added in types.js, even if they're not explicitly
// present in the spec.
"JSC_TYPE_MISMATCH");
test(
"var Comp = React.createClass({" +
"render: function() {return React.createElement(\"div\");}," +
"shouldComponentUpdate: function() {return false;}" +
"});",
// But implementations should be OK if they omit parameters...
"");
test(
"var Comp = React.createClass({" +
"render: function() {return React.createElement(\"div\");}," +
"shouldComponentUpdate: function(param1, param2) {return false;}" +
"});",
// ...or rename them.
"");
testError(
"var Comp = React.createClass({" +
"render: function() {return 123;}" +
"});",
"JSC_TYPE_MISMATCH");
testError(
"var Mixin = React.createMixin({" +
"shouldComponentUpdate: function(nextProps, nextState) {return 123;}" +
"});",
// Same for mixins
"JSC_TYPE_MISMATCH");
testError(
"var Comp = React.createClass({" +
"render: function() {" +
"this.isMounted().indexOf(\"true\");" +
"return React.createElement(\"div\");" +
"}" +
"});",
// Same for invocations of built-in component methods.
"JSC_INEXISTENT_PROPERTY");
test(
"var Comp = React.createClass({" +
"refAccess: function() {return this.refs[\"foo\"];}" +
"});",
// Refs can be accessed via quoted strings.
"");
testError(
"var Comp = React.createClass({" +
"refAccess: function() {return this.refs.foo;}" +
"});",
// ...but not as property accesses (since they may get renamed)
"JSC_ILLEGAL_PROPERTY_ACCESS");
}
@Test public void testTypeValidationClass() {
testError(
"class Comp extends React.Component {}" +
"Comp.prototype.render = \"notafunction\";",
"JSC_TYPE_MISMATCH");
testError(
"class Comp extends React.Component {" +
"constructor(props) {" +
"super(props);" +
"this.render = \"notafunction\";" +
"}" +
"}",
"JSC_TYPE_MISMATCH");
// displayName is not a property on Comp but not sure why this is not caught.
// testError(
// "class Comp extends React.Component {" +
// "render() {return null;}" +
// "}" +
// "window.foo = Comp.displayName.charAt(0);",
// "JSC_POSSIBLE_INEXISTENT_PROPERTY");
testError(
"class Comp extends React.Component {" +
"render() {return React.createElement(\"div\");}" +
"}" +
"ReactDOM.render(React.createElement(Comp), document.body, 123);",
"JSC_TYPE_MISMATCH");
testError(
"class Comp extends React.Component {" +
"render() {return React.createElement(\"div\");}" +
"shouldComponentUpdate(nextProps, nextState) {return 123;}" +
"}",
// Overrides/implemementations of built-in methods should conform to the
// type annotations added in types.js, even if they're not explicitly
// present in the spec.
"JSC_TYPE_MISMATCH");
test(
"class Comp extends React.Component {" +
"render() {return React.createElement(\"div\");}" +
"shouldComponentUpdate() {return false;}" +
"}",
// But implementations should be OK if they omit parameters...
"");
test(
"class Comp extends React.Component {" +
"render() {return React.createElement(\"div\");}" +
"shouldComponentUpdate(param1, param2) {return false;}" +
"}",
// ...or rename them.
"");
testError(
"class Comp extends React.Component {" +
"render() {return 123;}" +
"}",
"JSC_TYPE_MISMATCH");
testError(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {" +
"shouldComponentUpdate(nextProps, nextState) {return 123;}" +
"}" +
"ReactSupport.declareMixin(Mixin);",
// Same for mixins
"JSC_TYPE_MISMATCH");
testError(
"class Comp extends React.Component {" +
"render() {" +
"this.isMounted().indexOf(\"true\");" +
"return React.createElement(\"div\");" +
"}" +
"}",
// Same for invocations of built-in component methods.
"JSC_INEXISTENT_PROPERTY");
test(
"class Comp extends React.Component {" +
"refAccess() {return this.refs[\"foo\"];}" +
"}",
// Refs can be accessed via quoted strings.
"");
testError(
"class Comp extends React.Component {" +
"refAccess() {return this.refs.foo;}" +
"}",
// ...but not as property accesses (since they may get renamed)
"JSC_ILLEGAL_PROPERTY_ACCESS");
}
/**
* Tests that JSDoc type annotations on custom methods are checked.
*/
@Test public void testMethodJsDoc() {
testError(
"var Comp = React.createClass({" +
"render: function() {return React.createElement(\"div\");}," +
"/** @param {number} numberParam */" +
"someMethod: function(numberParam) {numberParam.notAMethod();}" +
"});",
"JSC_INEXISTENT_PROPERTY");
testError(
"var Comp = React.createClass({" +
"render: function() {return React.createElement(" +
"\"div\", null, this.someMethod(\"notanumber\"));}," +
"/** @param {number} numberParam */" +
"someMethod: function(numberParam) {return numberParam + 1;}" +
"});",
"JSC_TYPE_MISMATCH");
}
@Test public void testMethodJsDocClass() {
testError(
"class Comp extends React.Component {" +
"render() {return React.createElement(\"div\");}" +
"/** @param {number} numberParam */" +
"someMethod(numberParam) {numberParam.notAMethod();}" +
"}",
"JSC_INEXISTENT_PROPERTY");
testError(
"class Comp extends React.Component {" +
"render() {return React.createElement(" +
"\"div\", null, this.someMethod(\"notanumber\"));}" +
"/** @param {number} numberParam */" +
"someMethod(numberParam) {return numberParam + 1;}" +
"}",
"JSC_TYPE_MISMATCH");
}
/**
* Tests that component methods can have default parameters.
*/
@Test public void testMethodDefaultParameters() {
test(
"var Comp = React.createClass({" +
"render: function() {return React.createElement(\"div\");}," +
"/** @param {number=} numberParam @return {number}*/" +
"someMethod: function(numberParam = 1) {return numberParam * 2;}" +
"});",
"");
}
@Test public void testMethodDefaultParametersClass() {
test(
"class Comp extends React.Component {" +
"render() {return React.createElement(\"div\");}" +
"/** @param {number=} numberParam @return {number}*/" +
"someMethod(numberParam = 1) {return numberParam * 2;}" +
"}",
"");
}
/**
* Tests that components can be marked as implementing interfaces.
*/
@Test public void testInterfaces() {
test(
"/** @interface */ function AnInterface() {}\n" +
"/** @return {number} */\n" +
"AnInterface.prototype.interfaceMethod = function() {};\n" +
"/** @implements {AnInterface} */" +
"var Comp = React.createClass({" +
"/** @override */ interfaceMethod: function() {\n" +
"return 1;\n" +
"},\n" +
"render: function() {\n" +
"return React.createElement(\"div\");\n" +
"}" +
"});" +
"ReactDOM.render(React.createElement(Comp), document.body);",
"ReactDOM.render(React.createElement(React.createClass({" +
"$interfaceMethod$:function(){" +
"return 1" +
"}," +
"render:function(){" +
"return React.createElement(\"div\")" +
"}" +
"})),document.body);");
// We can't test that missing methods cause compiler warnings since we're
// declaring CompInterface as extending AnInterface, thus the methods
// assumed to be there.
}
@Test public void testInterfacesClass() {
test(
"/** @interface */ function AnInterface() {}\n" +
"/** @return {number} */\n" +
"AnInterface.prototype.interfaceMethod = function() {};\n" +
"/** @implements {AnInterface} */" +
"class Comp extends React.Component {" +
"/** @override */ interfaceMethod() {\n" +
"return 1;\n" +
"}\n" +
"render() {\n" +
"return React.createElement(\"div\");\n" +
"}" +
"};" +
"ReactDOM.render(React.createElement(Comp), document.body);",
"class $Comp$$ extends React.Component{" +
"render(){" +
"return React.createElement(\"div\")" +
"}" +
"}" +
"ReactDOM.render(React.createElement($Comp$$),document.body);");
// We can't test that missing methods cause compiler warnings since we're
// declaring CompInterface as extending AnInterface, thus the methods
// assumed to be there.
}
@Test public void testState() {
// this.state accesses are checked
testError(
"var Comp = React.createClass({" +
"/** @return {{enabled: boolean}} */ getInitialState() {" +
"return {enabled: false};" +
"},\n" +
"render() {" +
"this.state.enabled.toFixed(2);" +
"return null" +
"}" +
"});",
"JSC_INEXISTENT_PROPERTY");
// this.setState() calls are checked
testError(
"var Comp = React.createClass({" +
"/** @return {{enabled: boolean}} */ getInitialState() {" +
"return {enabled: false};" +
"},\n" +
"render() {" +
"this.setState({enabled: 123});" +
"return null;" +
"},\n" +
"});",
"JSC_TYPE_MISMATCH");
// this.setState() calls with an updater function should be checked
testError(
"var Comp = React.createClass({" +
"/** @return {{enabled: boolean}} */ getInitialState() {" +
"return {enabled: false};" +
"},\n" +
"render() {" +
"this.setState((state, props) => ({enabled: 123}));" +
"return null;" +
"},\n" +
"});",
"JSC_TYPE_MISMATCH");
// this.setState() accepts a subset of state fields
testNoError(
"var Comp = React.createClass({" +
"/** @return {{f1: boolean, f2: number, f3: (number|boolean)}} */" +
"getInitialState() {" +
"return {f1: false, f2: 1, f3: 2};" +
"},\n" +
"render() {" +
"this.setState({f1: true});" +
"return null;" +
"},\n" +
"});");
// return type for getInitialState must be a record
testError(
"var Comp = React.createClass({" +
"/** @return {number} */ getInitialState() {" +
"return {enabled: false};" +
"},\n" +
"render() {" +
"return null;" +
"}" +
"});",
"REACT_UNEXPECTED_STATE_TYPE");
// component methods that take state parameters are checked
testError(
"var Comp = React.createClass({" +
"/** @return {{enabled: boolean}} */ getInitialState() {" +
"return {enabled: false};" +
"},\n" +
"componentWillUpdate(nextProps, nextState) {" +
"nextState.enabled.toFixed(2);" +
"},\n" +
"render() {" +
"return null;" +
"}" +
"});",
"JSC_INEXISTENT_PROPERTY");
// Mixin methods that take state parameters are checked
testError(
"var Mixin = React.createMixin({});\n" +
"/** @param {!ReactState} state */" +
"Mixin.mixinMethod;\n" +
"var Comp = React.createClass({" +
"mixins: [Mixin],\n" +
"/** @return {{enabled: boolean}} */ getInitialState() {" +
"return {enabled: false};" +
"},\n" +
"mixinMethod(state) {" +
"state.enabled.toFixed(2);" +
"},\n" +
"render: function() {" +
"return null;" +
"}" +
"});",
"JSC_INEXISTENT_PROPERTY");
}
@Test public void testStateClass() {
// this.state accesses are checked
testError(
"class Comp extends React.Component {" +
"constructor(props) {" +
"super(props);" +
"/** @type {Comp.State} */" +
"this.state = this.initialState();" +
"}" +
"/** @return {{enabled: boolean}} */" +
"initialState() {" +
"return {enabled: false};" +
"}" +
"render() {" +
"this.state.enabled.toFixed(2);" +
"return null" +
"}" +
"}",
"JSC_INEXISTENT_PROPERTY");
// this.setState() calls are checked
testError(
"class Comp extends React.Component {" +
"constructor(props) {" +
"super(props);" +
"/** @type {Comp.State} */" +
"this.state = this.initialState()" +
"}" +
"/** @return {{enabled: boolean}} */" +
"initialState() {" +
"return {enabled: false};" +
"}" +
"render() {" +
"this.setState({enabled: 123});" +
"return null;" +
"}" +
"}",
"JSC_TYPE_MISMATCH");
// this.setState() calls with an updater function should be checked, but the
// compiler does not appear to be doing this.
testError(
"class Comp extends React.Component {" +
"constructor(props) {" +
"super(props);" +
"/** @type {Comp.State} */" +
"this.state = this.initialState();" +
"}" +
"/** @return {{enabled: boolean}} */" +
"initialState() {" +
"return {enabled: false};" +
"}" +
"render() {" +
"this.setState((state, props) => ({enabled: 123}));" +
"return null;" +
"}" +
"}",
"JSC_TYPE_MISMATCH");
// this.setState() accepts a subset of state fields
testNoError(
"class Comp extends React.Component {" +
"constructor(props) {" +
"super(props);" +
"/** @type {Comp.State} */" +
"this.state = this.initialState();" +
"}" +
"/** @return {{f1: boolean, f2: number, f3: (number|boolean)}} */" +
"initialState() {" +
"return {f1: false, f2: 1, f3: 2};" +
"}" +
"render() {" +
"this.setState({f1: true});" +
"return null;" +
"}" +
"}");
// type for this.state must be a record
testError(
"class Comp extends React.Component {" +
"constructor(props) {" +
"super(props);" +
"/** @type {number} */" +
"this.state = this.initialState();" +
"}" +
"/** @return {number} */" +
"initialState() {" +
"return {enabled: false};" +
"}" +
"render() {" +
"return null;" +
"}" +
"}",
"REACT_UNEXPECTED_STATE_TYPE");
// component methods that take state parameters are checked
testError(
"class Comp extends React.Component {" +
"constructor(props) {" +
"super(props);" +
"/** @type {Comp.State} */" +
"this.state = this.initialState();" +
"}" +
"/** @return {{enabled: boolean}} */" +
"initialState() {" +
"return {enabled: false};" +
"}" +
"componentWillUpdate(nextProps, nextState) {" +
"nextState.enabled.toFixed(2);" +
"}" +
"render() {" +
"return null;" +
"}" +
"}",
"JSC_INEXISTENT_PROPERTY");
// Mixin methods that take state parameters are checked
testError(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {}" +
"ReactSupport.declareMixin(Mixin);" +
"/** @param {!ReactState} state */" +
"Mixin.mixinMethod;" +
"class Comp extends React.Component {" +
"constructor(props) {" +
"super(props);" +
"/** @type {Comp.State} */" +
"this.state = this.initialState();" +
"}" +
"/** @return {{enabled: boolean}} */" +
"initialState() {" +
"return {enabled: false};" +
"}" +
"mixinMethod(state) {" +
"state.enabled.toFixed(2);" +
"}" +
"render() {" +
"return null;" +
"}" +
"}" +
"ReactSupport.mixin(Comp, Mixin);",
"JSC_INEXISTENT_PROPERTY");
}
@Test public void testFields() {
// Fields defined in getInitialState are checked
testError(
"var Comp = React.createClass({" +
"getInitialState() {" +
"/** @private {boolean} */" +
"this.field_ = true;\n" +
"return null;" +
"},\n" +
"render() {" +
"this.field_.toFixed(2);" +
"return null" +
"}" +
"});",
"JSC_INEXISTENT_PROPERTY");
// Even if they don't have a value assigned.
testError(
"var Comp = React.createClass({" +
"getInitialState() {" +
"/** @private {boolean|undefined} */" +
"this.field_;\n" +
"return null;" +
"},\n" +
"render() {" +
"this.field_.toFixed(2);" +
"return null" +
"}" +
"});",
"JSC_INEXISTENT_PROPERTY");
}
@Test public void testPropTypes() {
// Basic prop types
test(
"var Comp = React.createClass({" +
"propTypes: {aProp: React.PropTypes.string}," +
"render: function() {" +
"return React.createElement(\"div\", null, this.props.aProp);" +
"}" +
"});" +
"ReactDOM.render(React.createElement(Comp), document.body);",
"ReactDOM.render(React.createElement(React.createClass({" +
"propTypes:{$aProp$:React.PropTypes.string}," +
"render:function(){" +
"return React.createElement(\"div\",null,this.props.$aProp$)" +
"}" +
"})),document.body);");
// isRequired variant
test(
"window.foo=React.PropTypes.string.isRequired;",
"window.$foo$=React.PropTypes.string.isRequired;");
// Other variants are rejected
testError(
"window.foo=React.PropTypes.string.isSortOfRequired;",
"JSC_INEXISTENT_PROPERTY");
// arrayOf
test(
"window.foo=React.PropTypes.arrayOf(React.PropTypes.string);",
"window.$foo$=React.PropTypes.arrayOf(React.PropTypes.string);");
test(
"window.foo=React.PropTypes.arrayOf(React.PropTypes.string).isRequired;",
"window.$foo$=React.PropTypes.arrayOf(React.PropTypes.string).isRequired;");
testError(
"window.foo=React.PropTypes.arrayOf(123);",
"JSC_TYPE_MISMATCH");
testError(
"window.foo=React.PropTypes.arrayOf(React.PropTypes.string).isSortOfRequired;",
"JSC_INEXISTENT_PROPERTY");
// instanceOf
test(
"window.foo=React.PropTypes.instanceOf(Element);",
"window.$foo$=React.PropTypes.instanceOf(Element);");
testError(
"window.foo=React.PropTypes.instanceOf(123);",
"JSC_TYPE_MISMATCH");
// oneOf
test(
"window.foo=React.PropTypes.oneOf([1,2,3]);",
"window.$foo$=React.PropTypes.oneOf([1,2,3]);");
testError(
"window.foo=React.PropTypes.oneOf(123);",
"JSC_TYPE_MISMATCH");
// oneOfType
test(
"window.foo=React.PropTypes.oneOfType([React.PropTypes.string]);",
"window.$foo$=React.PropTypes.oneOfType([React.PropTypes.string]);");
testError(
"window.foo=React.PropTypes.oneOfType(123);",
"JSC_TYPE_MISMATCH");
// shape
test(
"window.foo=React.PropTypes.shape({str: React.PropTypes.string});",
"window.$foo$=React.PropTypes.shape({$str$:React.PropTypes.string});");
testError(
"window.foo=React.PropTypes.shape(123);",
"JSC_TYPE_MISMATCH");
}
@Test public void testPropTypesClass() {
// Basic prop types
test(
"class Comp extends React.Component {" +
"render() {" +
"return React.createElement(\"div\", null, this.props.aProp);" +
"}" +
"}" +
"Comp.propTypes = {aProp: React.PropTypes.string};" +
"ReactDOM.render(React.createElement(Comp), document.body);",
"class $Comp$$ extends React.Component{" +
"render(){" +
"return React.createElement(\"div\",null,this.props.$aProp$)" +
"}" +
"}" +
"$Comp$$.propTypes={$aProp$:React.PropTypes.string};" +
"ReactDOM.render(React.createElement($Comp$$),document.body);");
}
@Test public void testOptimizeForSize() {
ReactCompilerPass.Options passOptions =
new ReactCompilerPass.Options();
passOptions.optimizeForSize = true;
passOptions.propTypesTypeChecking = true;
// - propTypes should get stripped
// - React.createMixin() calls should be inlined with just the spec
// - React.createClass and React.createElement calls should be replaced with
// React$createClass and React$createElement aliases (which can get fully
// renamed).
test(
"var Mixin = React.createMixin({" +
"mixinMethod: function() {return 'foo'}" +
"});\n" +
"var Comp = React.createClass({" +
"mixins: [Mixin]," +
"propTypes: {aProp: React.PropTypes.string}," +
"render: function() {return React.createElement(\"div\", null, this.mixinMethod());}" +
"});" +
"ReactDOM.render(React.createElement(Comp), document.body);",
"ReactDOM.render($React$createElement$$($React$createClass$$({" +
"mixins:[{$mixinMethod$:function(){return\"foo\"}}]," +
"render:function(){return $React$createElement$$(\"div\",null,\"foo\")}" +
"})),document.body);",
passOptions,
null);
// This should also work when using ES6 modules
test(
"export const anExport = 9;\n" +
"var Comp = React.createClass({" +
"propTypes: {aProp: React.PropTypes.string}," +
"render: function() {return React.createElement(\"div\");}" +
"});" +
"ReactDOM.render(React.createElement(Comp), document.body);",
"ReactDOM.render($React$createElement$$($React$createClass$$({" +
"render:function(){return $React$createElement$$(\"div\")}" +
"})),document.body);",
passOptions,
null);
// But propTypes tagged with @struct should be preserved (React.PropTypes
// is replaced with an alias so that it can also be represented more
// compactly).
test(
"var Comp = React.createClass({" +
"/** @struct */" +
"propTypes: {aProp: React.PropTypes.string}," +
"render: function() {return React.createElement(\"div\");}" +
"});" +
"ReactDOM.render(React.createElement(Comp), document.body);",
"ReactDOM.render($React$createElement$$($React$createClass$$({" +
"propTypes:{$aProp$:$React$PropTypes$$.string}," +
"render:function(){return $React$createElement$$(\"div\")}" +
"})),document.body);",
passOptions,
null);
}
@Test public void testOptimizeForSizeClass() {
ReactCompilerPass.Options passOptions =
new ReactCompilerPass.Options();
passOptions.optimizeForSize = true;
passOptions.propTypesTypeChecking = true;
// - propTypes should get stripped
// - React.Component and React.createElement calls should be replaced with
// React$Component and React$createElement aliases (which can get fully
// renamed).
test(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {" +
"mixinMethod() {return 'foo'}" +
"}" +
"ReactSupport.declareMixin(Mixin);" +
"class Comp extends React.Component {" +
"render() {" +
"return React.createElement(\"div\", null, this.mixinMethod());" +
"}" +
"}" +
"ReactSupport.mixin(Comp, Mixin);" +
"Comp.propTypes = {aProp: React.PropTypes.string};" +
"ReactDOM.render(React.createElement(Comp), document.body);",
"class $Mixin$$ extends $React$Component$${}" +
"class $Comp$$ extends $React$Component$${" +
"render(){" +
"return $React$createElement$$(\"div\",null,\"foo\")" +
"}" +
"}" +
"$Comp$$.mixins=[$Mixin$$];" +
"ReactDOM.render($React$createElement$$($Comp$$),document.body);",
passOptions,
null);
// This should also work when using ES6 modules
test(
"export const anExport = 9;" +
"class Comp extends React.Component {" +
"render() {" +
"return React.createElement(\"div\");" +
"}" +
"}" +
"Comp.propTypes = {aProp: React.PropTypes.string};" +
"Comp.defaultProps = {aProp: \"hi\"};" +
"Comp.contextTypes = {aContext: React.PropTypes.number};" +
"ReactDOM.render(React.createElement(Comp), document.body);",
"class $Comp$$module$src$file1$$ extends $React$Component$${" +
"render(){" +
"return $React$createElement$$(\"div\")" +
"}" +
"}" +
"$Comp$$module$src$file1$$.defaultProps={$aProp$:\"hi\"};" +
"ReactDOM.render($React$createElement$$($Comp$$module$src$file1$$),document.body);",
passOptions,
null);
}
@Test public void testNoRenameReactApi() {
// Even when optimizing for size there is no renaming.
ReactCompilerPass.Options passOptions = new ReactCompilerPass.Options();
passOptions.optimizeForSize = true;
test(
"var Comp = React.createClass({" +
"propTypes: {aProp: React.PropTypes.string}," +
"render: function() {\n" +
"return React.createElement(\"div\", {onClick: null});\n" +
"}" +
"});" +
"ReactDOM.render(React.createElement(Comp), document.body);",
"ReactDOM.render($React$createElement$$($React$createClass$$({" +
"render:function(){" +
"return $React$createElement$$(\"div\",{onClick:null})" +
"}" +
"})),document.body);",
passOptions,
null);
// Other API symbols are not renamed either.
List<String> reactApiSymbols = ImmutableList.of("React", "React.Component",
"React.PureComponent", "React.cloneElement", "ReactDOM.findDOMNode",
"ReactDOM.unmountComponentAtNode");
for (String reactApiSymbol : reactApiSymbols) {
test(
"window['test'] = " + reactApiSymbol + ";",
"window.test=" + reactApiSymbol + ";",
passOptions,
null);
}
}
@Test public void testExport() {
String CLOSURE_EXPORT_FUNCTIONS =
"/** @const */ const goog = {};" +
"goog.exportSymbol = function(publicPath, object) {};\n" +
"goog.exportProperty = function(object, publicName, symbol) {};\n";
// Props where the class is tagged with @export should not get renamed,
// nor should methods explicitly tagged with @public.
test(
CLOSURE_EXPORT_FUNCTIONS +
"/** @export */" +
"var Comp = React.createClass({" +
"propTypes: {aProp: React.PropTypes.string},\n" +
"/** @public */ publicFunction: function() {\n" +
"return \"dont_rename_me_bro\";\n" +
"},\n" +
"/** @private */ privateFunction_: function() {\n" +
"return 1;\n" +
"},\n" +
"render: function() {\n" +
"return React.createElement(\"div\", null, this.props.aProp);\n" +
"}" +
"});" +
"ReactDOM.render(React.createElement(" +
"Comp, {aProp: \"foo\"}), document.body);",
"ReactDOM.render(React.createElement(React.createClass({" +
"propTypes:{aProp:React.PropTypes.string}," +
"publicFunction:function(){" +
"return\"dont_rename_me_bro\"" +
"}," +
"$privateFunction_$:function(){" +
"return 1" +
"}," +
"render:function(){" +
"return React.createElement(\"div\",null,this.props.aProp)" +
"}" +
"}),{aProp:\"foo\"}),document.body);");
// Even with a minified build there is no renaming.
ReactCompilerPass.Options minifiedReactPassOptions =
new ReactCompilerPass.Options();
minifiedReactPassOptions.optimizeForSize = true;
test(
CLOSURE_EXPORT_FUNCTIONS +
"/** @export */" +
"var Comp = React.createClass({" +
"propTypes: {aProp: React.PropTypes.string}," +
"/** @public */ publicFunction: function() {\n" +
"return \"dont_rename_me_bro\";\n" +
"},\n" +
"/** @private */ privateFunction_: function() {\n" +
"return 1;\n" +
"},\n" +
"render: function() {\n" +
"return React.createElement(\"div\", null, this.props.aProp);\n" +
"}" +
"});" +
"ReactDOM.render(React.createElement(" +
"Comp, {aProp: \"foo\"}), document.body);",
"ReactDOM.render($React$createElement$$($React$createClass$$({" +
"publicFunction:function(){" +
"return\"dont_rename_me_bro\"" +
"}," +
"$privateFunction_$:function(){" +
"return 1" +
"}," +
"render:function(){" +
"return $React$createElement$$(\"div\",null,this.props.aProp)" +
"}" +
"}),{aProp:\"foo\"}),document.body);",
minifiedReactPassOptions,
null);
}
@Test public void testExportClass () {
String CLOSURE_EXPORT_FUNCTIONS =
"/** @const */ const goog = {};" +
"goog.exportSymbol = function(publicPath, object) {};\n" +
"goog.exportProperty = function(object, publicName, symbol) {};\n";
// Props where the class is tagged with @export should not get renamed,
// nor should methods explicitly tagged with @export.
test(
CLOSURE_EXPORT_FUNCTIONS +
"/** @export */" +
"class Comp extends React.Component {" +
"/** @export */ publicFunction() {\n" +
"return \"dont_rename_me_bro\";\n" +
"}\n" +
"/** @private */ privateFunction_() {\n" +
"return 1;\n" +
"}\n" +
"render() {\n" +
"return React.createElement(\"div\", null, this.props.aProp);\n" +
"}" +
"}" +
"Comp.propTypes = {aProp: React.PropTypes.string};\n" +
"ReactDOM.render(React.createElement(Comp, {aProp: \"foo\"}), document.body);",
"class $Comp$$ extends React.Component{" +
"publicFunction(){" +
"return\"dont_rename_me_bro\"" +
"}" +
"render(){" +
"return React.createElement(\"div\",null,this.props.aProp)" +
"}" +
"}" +
"$Comp$$.propTypes={aProp:React.PropTypes.string};" +
"ReactDOM.render(React.createElement($Comp$$,{aProp:\"foo\"}),document.body);");
// Even with a minified build there is no renaming.
ReactCompilerPass.Options minifiedReactPassOptions =
new ReactCompilerPass.Options();
minifiedReactPassOptions.optimizeForSize = true;
test(
CLOSURE_EXPORT_FUNCTIONS +
"/** @export */" +
"class Comp extends React.Component {" +
"/** @export */ publicFunction() {\n" +
"return \"dont_rename_me_bro\";\n" +
"}\n" +
"/** @private */ privateFunction_() {\n" +
"return 1;\n" +
"}\n" +
"render() {\n" +
"return React.createElement(\"div\", null, this.props.aProp);\n" +
"}" +
"}" +
"Comp.propTypes = {aProp: React.PropTypes.string};" +
"ReactDOM.render(React.createElement(Comp, {aProp: \"foo\"}), document.body);",
"class $Comp$$ extends $React$Component$${" +
"publicFunction(){" +
"return\"dont_rename_me_bro\"" +
"}" +
"render(){" +
"return $React$createElement$$(\"div\",null,this.props.aProp)" +
"}" +
"}" +
"ReactDOM.render($React$createElement$$($Comp$$,{aProp:\"foo\"}),document.body);",
minifiedReactPassOptions,
null);
}
@Test public void testPropTypesTypeChecking() {
// Validate use of props within methods.
testError(
"var Comp = React.createClass({" +
"propTypes: {numberProp: React.PropTypes.number}," +
"render: function() {" +
"this.props.numberProp();" +
"return null;" +
"}" +
"});",
"JSC_NOT_FUNCTION_TYPE");
// Validate props at creation time.
testPropTypesError(
"{strProp: React.PropTypes.string}",
"{strProp: 1}",
"JSC_TYPE_MISMATCH");
// Required props cannot be null
testPropTypesError(
"{strProp: React.PropTypes.string.isRequired}",
"{strProp: null}",
"JSC_TYPE_MISMATCH");
// Required props cannot be omitted
testPropTypesError(
"{strProp: React.PropTypes.string.isRequired}",
"{}",
"JSC_TYPE_MISMATCH");
testPropTypesError(
"{strProp: React.PropTypes.string.isRequired}",
"null",
"JSC_TYPE_MISMATCH");
// Optional props can be null
testPropTypesNoError(
"{strProp: React.PropTypes.string}",
"null");
// Optional props can be omitted
testPropTypesNoError(
"{strProp: React.PropTypes.string}",
"{}");
testPropTypesNoError(
"{strProp: React.PropTypes.string}",
"null");
// Validate object prop
testPropTypesError(
"{objProp: React.PropTypes.instanceOf(Message).isRequired}",
"{objProp: \"foo\"}",
"JSC_TYPE_MISMATCH");
// Required object prop cannot be null
testPropTypesError(
"{objProp: React.PropTypes.instanceOf(Message).isRequired}",
"{objProp: null}",
"JSC_TYPE_MISMATCH");
// Required object prop cannot be omitted
testPropTypesError(
"{objProp: React.PropTypes.instanceOf(Message).isRequired}",
"{}",
"JSC_TYPE_MISMATCH");
// Optional object prop can be null
testPropTypesNoError(
"{objProp: React.PropTypes.instanceOf(Message)}",
"{objProp: null}");
// Optional object prop can be ommitted
testPropTypesNoError(
"{objProp: React.PropTypes.instanceOf(Message)}",
"{}");
// Validate array prop
testPropTypesError(
"{arrayProp: React.PropTypes.arrayOf(React.PropTypes.string)}",
"{arrayProp: 1}",
"JSC_TYPE_MISMATCH");
// Validate object prop
testPropTypesError(
"{objProp: React.PropTypes.objectOf(React.PropTypes.string)}",
"{objProp: 1}",
"JSC_TYPE_MISMATCH");
// Validate oneOfType prop
testPropTypesError(
"{unionProp: React.PropTypes.oneOfType([" +
"React.PropTypes.string," +
"React.PropTypes.number" +
"])}",
"{unionProp: false}",
"JSC_TYPE_MISMATCH");
testPropTypesNoError(
"{unionProp: React.PropTypes.oneOfType([" +
"React.PropTypes.string," +
"React.PropTypes.number" +
"])}",
"{unionProp: 1}");
// Validate children prop
testNoError(
"var Comp = React.createClass({" +
"propTypes: {" +
"children: React.PropTypes.element.isRequired" +
"}," +
"render: function() {return null;}" +
"});\n" +
"React.createElement(Comp, {}, React.createElement(\"div\"));");
testNoError(
"var Comp = React.createClass({" +
"propTypes: {" +
"children: React.PropTypes.element.isRequired" +
"}," +
"render: function() {return null;}" +
"});\n" +
"React.createElement(Comp, {}, React.createElement(Comp));");
// Multiple children
testNoError(
"var Comp = React.createClass({" +
"propTypes: {" +
"children: React.PropTypes.arrayOf(React.PropTypes.element).isRequired" +
"}," +
"render: function() {return null;}" +
"});\n" +
"React.createElement(Comp, {}, React.createElement(Comp), React.createElement(Comp));");
// Children required but not passed in
testError(
"var Comp = React.createClass({" +
"propTypes: {" +
"children: React.PropTypes.element.isRequired" +
"}," +
"render: function() {return null;}" +
"});\n" +
"React.createElement(Comp, {});",
"REACT_NO_CHILDREN_ARGUMENT");
// Children not required and not passed in
testNoError(
"var Comp = React.createClass({" +
"propTypes: {" +
"children: React.PropTypes.element" +
"}," +
"render: function() {return null;}" +
"});\n" +
"React.createElement(Comp, {});");
// Children required and wrong type passed in
testError(
"var Comp = React.createClass({" +
"propTypes: {" +
"children: React.PropTypes.element.isRequired" +
"}," +
"render: function() {return null;}" +
"});\n" +
"React.createElement(Comp, {}, null);",
"JSC_TYPE_MISMATCH");
// Handle spread operator when creating elements
testPropTypesError(
"{aProp: React.PropTypes.number.isRequired}",
"Object.assign({aProp: '1'}, {})",
"JSC_TYPE_MISMATCH");
testPropTypesError(
"{aProp: React.PropTypes.number.isRequired}",
"{aProp: '1', ...{}}",
"JSC_TYPE_MISMATCH");
testPropTypesNoError(
"{aProp: React.PropTypes.number.isRequired}",
"Object.assign({aProp: 1}, {})");
testPropTypesNoError(
"{aProp: React.PropTypes.number.isRequired}",
"{aProp: 1, ...{}}");
testPropTypesNoError(
"{aProp: React.PropTypes.number.isRequired}",
"Object.assign({}, {})");
testPropTypesError(
"{aProp: React.PropTypes.number.isRequired}",
"{...{}}",
"JSC_TYPE_MISMATCH");
testPropTypesNoError(
"{aProp: React.PropTypes.number.isRequired," +
"bProp: React.PropTypes.number.isRequired}",
"Object.assign({}, {aProp: 1})");
testPropTypesError(
"{aProp: React.PropTypes.number.isRequired," +
"bProp: React.PropTypes.number.isRequired}",
"{...{aProp: 1}}",
"JSC_TYPE_MISMATCH");
testPropTypesError(
"{aProp: React.PropTypes.number.isRequired," +
"bProp: React.PropTypes.number.isRequired}",
"Object.assign({}, {aProp: '1'})",
"JSC_TYPE_MISMATCH");
testPropTypesError(
"{aProp: React.PropTypes.number.isRequired," +
"bProp: React.PropTypes.number.isRequired}",
"{...{aProp: '1'}}",
"JSC_TYPE_MISMATCH");
testNoError(
"var Comp = React.createClass({" +
"propTypes: {" +
"aProp: React.PropTypes.string.isRequired" +
"}," +
"getDefaultProps: function() {" +
"return {aProp: \"1\"};" +
"}," +
"render: function() {return null;}" +
"});\n" +
"React.createElement(Comp, Object.assign({aProp: \"1\"}, {}))");
testNoError(
"var Comp = React.createClass({" +
"propTypes: {" +
"aProp: React.PropTypes.string.isRequired" +
"}," +
"getDefaultProps: function() {" +
"return {aProp: \"1\"};" +
"}," +
"render: function() {return null;}" +
"});\n" +
"React.createElement(Comp, {aProp: \"1\",...{}})");
// Custom type expressions
testPropTypesError(
"{/** @type {boolean} */ boolProp: function() {}}",
"{boolProp: 1}",
"JSC_TYPE_MISMATCH");
testPropTypesNoError(
"{/** @type {boolean} */ boolProp: function() {}}",
"{boolProp: true}");
testPropTypesNoError(
"{/** @type {(boolean|undefined|null)} */ boolProp: function() {}}",
"null");
// Required props with default values can be ommitted.
testNoError(
"var Comp = React.createClass({" +
"propTypes: {" +
"strProp: React.PropTypes.string.isRequired" +
"}," +
"getDefaultProps: function() {" +
"return {strProp: \"1\"};" +
"}," +
"render: function() {return null;}" +
"});\n" +
"React.createElement(Comp, {});");
testNoError(
"var Comp = React.createClass({" +
"propTypes: {" +
"strProp: React.PropTypes.string.isRequired" +
"}," +
"getDefaultProps: function() {" +
"return {strProp: \"1\"};" +
"}," +
"render: function() {return null;}" +
"});\n" +
"React.createElement(Comp, null);");
// Applies to custom type expressions too
testNoError(
"var Comp = React.createClass({" +
"propTypes: {" +
"/** @type {boolean} */ boolProp: function() {}" +
"}," +
"getDefaultProps: function() {" +
"return {boolProp: true};" +
"}," +
"render: function() {return null;}" +
"});\n" +
"React.createElement(Comp, {});");
// But if they are provided their types are still checked.
testError(
"var Comp = React.createClass({" +
"propTypes: {" +
"strProp: React.PropTypes.string.isRequired" +
"}," +
"getDefaultProps: function() {" +
"return {strProp: \"1\"};" +
"}," +
"render: function() {return null;}" +
"});\n" +
"React.createElement(Comp, {strProp: 1});",
"JSC_TYPE_MISMATCH");
// Even if not required, if they have a default value their value inside
// the component is not null or undefined.
testNoError(
"var Comp = React.createClass({" +
"propTypes: {" +
"strProp: React.PropTypes.string" +
"}," +
"getDefaultProps: function() {" +
"return {strProp: \"1\"};" +
"}," +
"render: function() {" +
"this.strMethod_(this.props.strProp);" +
"return null;" +
"},\n" +
"/**" +
" * @param {string} param" +
" * @return {string}" +
" * @private" +
" */" +
"strMethod_: function(param) {return param;}" +
"});\n" +
"React.createElement(Comp, null);");
}
@Test public void testPropTypesTypeCheckingClass() {
// Validate use of props within methods.
testError(
"export{};class Comp extends React.Component {" +
"render() {" +
"this.props.numberProp();" +
"return null;" +
"}" +
"}" +
"Comp.propTypes = {numberProp: React.PropTypes.number};",
"JSC_NOT_FUNCTION_TYPE");
// Validate children prop
testNoError(
"class Comp extends React.Component {" +
"render() {return null;}" +
"}" +
"Comp.propTypes= {" +
"children: React.PropTypes.element.isRequired" +
"};" +
"React.createElement(Comp, {}, React.createElement(\"div\"));");
testNoError(
"class Comp extends React.Component {" +
"render() {return null;}" +
"}" +
"Comp.propTypes = {" +
"children: React.PropTypes.element.isRequired" +
"};" +
"React.createElement(Comp, {}, React.createElement(Comp));");
// Multiple children
testNoError(
"class Comp extends React.Component {" +
"render() {return null;}" +
"}" +
"Comp.propTypes = {" +
"children: React.PropTypes.arrayOf(React.PropTypes.element).isRequired" +
"};" +
"React.createElement(Comp, {}, React.createElement(Comp), React.createElement(Comp));");
// Children required but not passed in
testError(
"class Comp extends React.Component {" +
"render() {return null;}" +
"}" +
"Comp.propTypes = {" +
"children: React.PropTypes.element.isRequired" +
"};" +
"React.createElement(Comp, {});",
"REACT_NO_CHILDREN_ARGUMENT");
// Children not required and not passed in
testNoError(
"class Comp extends React.Component {" +
"render() {return null;}" +
"}" +
"Comp.propTypes = {" +
"children: React.PropTypes.element" +
"};" +
"React.createElement(Comp, {});");
// Children required and wrong type passed in
testError(
"class Comp extends React.Component {" +
"render() {return null;}" +
"}" +
"Comp.propTypes = {" +
"children: React.PropTypes.element.isRequired" +
"};" +
"React.createElement(Comp, {}, null);",
"JSC_TYPE_MISMATCH");
test(
"class Comp extends React.Component {" +
"render() {return null;}" +
"}\n" +
"Comp.propTypes = {" +
"aProp: React.PropTypes.string.isRequired" +
"};" +
"Comp.defaultProps = {aProp: \"1\"};" +
"React.createElement(Comp, Object.assign({aProp: \"1\"}, {}))",
"class $Comp$$ extends React.Component{" +
"render(){" +
"return null" +
"}" +
"}" +
"$Comp$$.propTypes={$aProp$:React.PropTypes.string.isRequired};" +
"$Comp$$.defaultProps={$aProp$:\"1\"};" +
"React.createElement($Comp$$,Object.assign({$aProp$:\"1\"},{}));");
testNoError(
"class Comp extends React.Component {" +
"render() {return null;}" +
"}\n" +
"Comp.propTypes = {" +
"aProp: React.PropTypes.string.isRequired" +
"};" +
"Comp.defaultProps = {aProp: \"1\"};" +
"React.createElement(Comp, {aProp: \"1\",...{}})");
// Required props with default values can be ommitted.
testNoError(
"class Comp extends React.Component {" +
"render() {return null;}" +
"}\n" +
"Comp.propTypes = {" +
"strProp: React.PropTypes.string.isRequired" +
"};" +
"Comp.defaultProps = {strProp: \"1\"};" +
"React.createElement(Comp, {});");
testNoError(
"class Comp extends React.Component {" +
"render() {return null;}" +
"}\n" +
"Comp.propTypes = {" +
"strProp: React.PropTypes.string.isRequired" +
"};" +
"Comp.defaultProps = {strProp: \"1\"};" +
"React.createElement(Comp, null);");
// Applies to custom type expressions too
testNoError(
"class Comp extends React.Component {" +
"render() {return null;}" +
"}\n" +
"Comp.propTypes = {" +
"/** @type {boolean} */ boolProp: function() {}" +
"};" +
"Comp.defaultProps = {boolProp: true};" +
"React.createElement(Comp, {});");
// But if they are provided their types are still checked.
testError(
"class Comp extends React.Component {" +
"render() {return null;}" +
"}\n" +
"Comp.propTypes = {" +
"strProp: React.PropTypes.string.isRequired" +
"};" +
"Comp.defaultProps = {strProp: \"1\"};" +
"React.createElement(Comp, {strProp: 1});",
"JSC_TYPE_MISMATCH");
// Even if not required, if they have a default value their value inside
// the component is not null or undefined.
testNoError(
"class Comp extends React.Component {" +
"render() {" +
"this.strMethod_(this.props.strProp);" +
"return null;" +
"}\n" +
"/**" +
" * @param {string} param" +
" * @return {string}" +
" * @private" +
" */" +
"strMethod_(param) {return param;}" +
"}\n" +
"Comp.propTypes = {" +
"strProp: React.PropTypes.string" +
"};\n" +
"Comp.defaultProps = {strProp: \"1\"};\n" +
"React.createElement(Comp, null);");
}
@Test public void testPropTypesMixins() {
testError(
"var Mixin = React.createMixin({" +
"propTypes: {" +
"mixinNumberProp: React.PropTypes.number.isRequired" +
"}" +
"});\n" +
"var Comp = React.createClass({" +
"mixins: [Mixin],\n" +
"propTypes: {" +
"numberProp: React.PropTypes.number.isRequired" +
"}," +
"render: function() {return this.props.mixinNumberProp();}" +
"});\n",
"JSC_NOT_FUNCTION_TYPE");
// Even when the component doesn't have its own propTypes those of the
// mixin are considered.
testError(
"var Mixin = React.createMixin({" +
"propTypes: {" +
"mixinNumberProp: React.PropTypes.number.isRequired" +
"}" +
"});\n" +
"var Comp = React.createClass({" +
"mixins: [Mixin],\n" +
"render: function() {return this.props.mixinNumberProp();}" +
"});\n",
"JSC_NOT_FUNCTION_TYPE");
testNoError(
"var Mixin = React.createMixin({" +
"propTypes: {" +
"mixinFuncProp: React.PropTypes.func.isRequired" +
"}" +
"});\n" +
"var Comp = React.createClass({" +
"mixins: [Mixin],\n" +
"render: function() {return this.props.mixinFuncProp();}" +
"});\n");
// The same propTypes can be in both mixins and components (and the
// component one has precedence).
testNoError(
"var Mixin = React.createMixin({" +
"propTypes: {" +
"aProp: React.PropTypes.number.isRequired" +
"}" +
"});\n" +
"var Comp = React.createClass({" +
"mixins: [Mixin],\n" +
"propTypes: {" +
"aProp: React.PropTypes.number.isRequired" +
"},\n" +
"render: function() {return null;}" +
"});\n");
// Custom type expressions are handled
testNoError(
"var Mixin = React.createMixin({" +
"propTypes: {" +
"/** @type {boolean} */ boolProp: function() {}" +
"}" +
"});\n" +
"var Comp = React.createClass({" +
"mixins: [Mixin],\n" +
"render: function() {return null;}" +
"});\n" +
"React.createElement(Comp, {boolProp: true});");
}
@Test public void testPropTypesMixinsClass() {
testError(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {" +
"}" +
"ReactSupport.declareMixin(Mixin);" +
"Mixin.propTypes = {" +
"mixinNumberProp: React.PropTypes.number.isRequired" +
"};" +
"class Comp extends React.Component {" +
"render() {return this.props.mixinNumberProp();}" +
"}" +
"ReactSupport.mixin(Comp, Mixin);" +
"Comp.propTypes = {" +
"numberProp: React.PropTypes.number.isRequired" +
"};",
"JSC_NOT_FUNCTION_TYPE");
// Even when the component doesn't have its own propTypes those of the
// mixin are considered.
testError(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {}" +
"ReactSupport.declareMixin(Mixin);" +
"Mixin.propTypes = {" +
"mixinNumberProp: React.PropTypes.number.isRequired" +
"};" +
"class Comp extends React.Component {" +
"render() {return this.props.mixinNumberProp();}" +
"}" +
"ReactSupport.mixin(Comp, Mixin);",
"JSC_NOT_FUNCTION_TYPE");
testNoError(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {}" +
"ReactSupport.declareMixin(Mixin);" +
"Mixin.propTypes = {" +
"mixinFuncProp: React.PropTypes.func.isRequired" +
"};" +
"class Comp extends React.Component {" +
"render() {return this.props.mixinFuncProp();}" +
"}"+
"ReactSupport.mixin(Comp, Mixin);");
// The same propTypes can be in both mixins and components (and the
// component one has precedence).
testNoError(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {}" +
"ReactSupport.declareMixin(Mixin);" +
"Mixin.propTypes = {" +
"aProp: React.PropTypes.number.isRequired" +
"};" +
"class Comp extends React.Component {" +
"render() {return null;}" +
"}" +
"ReactSupport.mixin(Comp, Mixin);" +
"Comp.propTypes = {" +
"aProp: React.PropTypes.number.isRequired" +
"};");
// Custom type expressions are handled
testNoError(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {}" +
"ReactSupport.declareMixin(Mixin);" +
"Mixin.propTypes = {" +
"/** @type {boolean} */ boolProp: function() {}" +
"};" +
"class Comp extends React.Component {" +
"render() {return null;}" +
"}" +
"ReactSupport.mixin(Comp, Mixin);" +
"React.createElement(Comp, {boolProp: true});");
}
@Test public void testPropTypesComponentMethods() {
// React component/lifecycle methods automatically get the specific prop
// type injected.
testError(
"var Comp = React.createClass({" +
"propTypes: {" +
"numberProp: React.PropTypes.number.isRequired" +
"}," +
"componentWillReceiveProps: function(nextProps) {" +
"nextProps.numberProp();" +
"},\n" +
"render: function() {return null;}" +
"});\n" +
"React.createElement(Comp, {numberProp: 1});",
"JSC_NOT_FUNCTION_TYPE");
// As do abstract mixin methods that use ReactProps as the type.
testError(
"var Mixin = React.createMixin({" +
"});" +
"/** @param {ReactProps} props @protected */" +
"Mixin.mixinAbstractMethod;\n" +
"var Comp = React.createClass({" +
"mixins: [Mixin],\n" +
"propTypes: {" +
"numberProp: React.PropTypes.number.isRequired" +
"}," +
"mixinAbstractMethod: function(props) {" +
"props.numberProp();" +
"},\n" +
"render: function() {return null;}" +
"});\n" +
"React.createElement(Comp, {numberProp: 1});",
"JSC_NOT_FUNCTION_TYPE");
}
@Test public void testPropTypesComponentMethodsClass() {
// React component/lifecycle methods automatically get the specific prop
// type injected.
testError(
"class Comp extends React.Component {" +
"componentWillReceiveProps(nextProps) {" +
"nextProps.numberProp();" +
"}\n" +
"render() {return null;}" +
"}\n" +
"Comp.propTypes = {" +
"numberProp: React.PropTypes.number.isRequired" +
"};\n" +
"React.createElement(Comp, {numberProp: 1});",
"JSC_NOT_FUNCTION_TYPE");
// As do abstract mixin methods that use ReactProps as the type.
testError(
REACT_SUPPORT_CODE +
"class Mixin extends React.Component {}" +
"ReactSupport.declareMixin(Mixin);" +
"/** @param {ReactProps} props @protected */" +
"Mixin.mixinAbstractMethod;" +
"class Comp extends React.Component {" +
"mixinAbstractMethod(props) {" +
"props.numberProp();" +
"}" +
"render() {return null;}" +
"}" +
"ReactSupport.mixin(Comp, Mixin);" +
"Comp.propTypes = {" +
"numberProp: React.PropTypes.number.isRequired" +
"};" +
"React.createElement(Comp, {numberProp: 1});",
"JSC_NOT_FUNCTION_TYPE");
}
private void testPropTypesError(String propTypes, String props, String error) {
testError(
"/** @constructor */ function Message() {};\n" +
"var Comp = React.createClass({" +
"propTypes: " + propTypes + "," +
"render: function() {return null;}" +
"});\n" +
"React.createElement(Comp, " + props + ");",
error);
testError(
"class Message {}\n" +
"class Comp extends React.Component {" +
"render() {return null;}" +
"}\n" +
"Comp.propTypes = " + propTypes + ";\n" +
"React.createElement(Comp, " + props + ");",
error);
}
private void testPropTypesNoError(String propTypes, String props) {
testNoError(
"/** @constructor */ function Message() {};\n" +
"var Comp = React.createClass({" +
"propTypes: " + propTypes + "," +
"render: function() {return null;}" +
"});\n" +
"React.createElement(Comp, " + props + ");");
testNoError(
"class Message {}\n" +
"class Comp extends React.Component {" +
"render() {return null;}" +
"}\n" +
"Comp.propTypes = " + propTypes + ";\n" +
"React.createElement(Comp, " + props + ");");
}
@Test public void testChildren() {
// Non-comprehensive test that the React.Children namespace functions exist.
test(
"var Comp = React.createClass({" +
"propTypes: {" +
"children: React.PropTypes.element.isRequired" +
"}," +
"render: function() {" +
"return React.createElement(" +
"\"div\", null, React.Children.only(this.props.children));" +
"}" +
"});" +
"ReactDOM.render(React.createElement(Comp), document.body);",
"ReactDOM.render(React.createElement(React.createClass({" +
"propTypes:{" +
"children:React.PropTypes.element.isRequired" +
"}," +
"render:function(){" +
"return React.createElement(" +
"\"div\",null,React.Children.only(this.props.children))" +
"}" +
"})),document.body);");
}
@Test public void testChildrenClass() {
// Non-comprehensive test that the React.Children namespace functions exist.
test(
"class Comp extends React.Component {" +
"render() {" +
"return React.createElement(" +
"\"div\", null, React.Children.only(this.props.children));" +
"}" +
"}" +
"Comp.propTypes = {" +
"children: React.PropTypes.element.isRequired" +
"};" +
"ReactDOM.render(React.createElement(Comp), document.body);",
"class $Comp$$ extends React.Component{" +
"render(){" +
"return React.createElement(\"div\",null,React.Children.only(this.props.children))" +
"}" +
"}" +
"$Comp$$.propTypes={children:React.PropTypes.element.isRequired};" +
"ReactDOM.render(React.createElement($Comp$$),document.body);");
}
@Test public void testContextTypesTypeChecking() {
// Validate use of context within methods.
testError(
"var Comp = React.createClass({" +
"contextTypes: {numberProp: React.PropTypes.number}," +
"render: function() {" +
"this.context.numberProp();" +
"return null;" +
"}" +
"});",
"JSC_NOT_FUNCTION_TYPE");
// Both props and context are checked
testNoError(
"var Comp = React.createClass({" +
"contextTypes: {\n" +
"/** @type {function(number)} */\n" +
"functionProp: React.PropTypes.func," +
"}," +
"propTypes: {numberProp: React.PropTypes.number.isRequired}," +
"render: function() {" +
"this.context.functionProp(this.props.numberProp);" +
"return null;" +
"}" +
"});");
testError(
"var Comp = React.createClass({" +
"contextTypes: {\n" +
"/** @type {function(number)} */\n" +
"functionProp: React.PropTypes.func," +
"}," +
"propTypes: {stringProp: React.PropTypes.string.isRequired}," +
"render: function() {" +
"this.context.functionProp(this.props.stringProp);" +
"return null;" +
"}" +
"});",
"JSC_TYPE_MISMATCH");
}
@Test public void testContextTypesTypeCheckingClass() {
// Validate use of context within methods.
testError(
"class Comp extends React.Component {" +
"render() {" +
"this.context.numberProp();" +
"return null;" +
"}" +
"}" +
"Comp.contextTypes = {numberProp: React.PropTypes.number};",
"JSC_NOT_FUNCTION_TYPE");
// Both props and context are checked
test(
"class Comp extends React.Component {" +
"render() {" +
"this.context.functionProp(this.props.numberProp);" +
"return null;" +
"}" +
"}" +
"Comp.contextTypes = {\n" +
"/** @type {function(number)} */\n" +
"functionProp: React.PropTypes.func," +
"};" +
"Comp.propTypes = {numberProp: React.PropTypes.number.isRequired};" +
"ReactDOM.render(React.createElement(Comp), document.body);",
"class $Comp$$ extends React.Component{" +
"render(){" +
"this.context.$functionProp$(this.props.$numberProp$);" +
"return null" +
"}" +
"}" +
"$Comp$$.contextTypes={$functionProp$:React.PropTypes.func};" +
"$Comp$$.propTypes={$numberProp$:React.PropTypes.number.isRequired};" +
"ReactDOM.render(React.createElement($Comp$$),document.body);");
testError(
"class Comp extends React.Component {" +
"render() {" +
"this.context.functionProp(this.props.stringProp);" +
"return null;" +
"}" +
"}" +
"Comp.contextTypes = {\n" +
"/** @type {function(number)} */\n" +
"functionProp: React.PropTypes.func," +
"};\n" +
"Comp.propTypes = {stringProp: React.PropTypes.string.isRequired};",
"JSC_TYPE_MISMATCH");
}
@Test public void testReactDOM() {
test("var Comp = React.createClass({});" +
"ReactDOM.render(React.createElement(Comp), document.body);",
"ReactDOM.render(React.createElement(" +
"React.createClass({})" +
"),document.body);");
test("ReactDOM.findDOMNode(document.body);",
"ReactDOM.findDOMNode(document.body);");
testError("ReactDOM.findDOMNode([document.body]);", "JSC_TYPE_MISMATCH");
test("ReactDOM.unmountComponentAtNode(document.body);",
"ReactDOM.unmountComponentAtNode(document.body);");
testError("ReactDOM.unmountComponentAtNode(\"notanode\");",
"JSC_TYPE_MISMATCH");
}
@Test public void testReactDOMClass() {
test("class Comp extends React.Component {}" +
"ReactDOM.render(React.createElement(Comp), document.body);",
"class $Comp$$ extends React.Component{}" +
"ReactDOM.render(React.createElement($Comp$$),document.body);");
}
@Test public void testReactDOMServer() {
test("var Comp = React.createClass({});" +
"ReactDOMServer.renderToString(React.createElement(Comp));",
"ReactDOMServer.renderToString(" +
"React.createElement(React.createClass({})));");
testError("ReactDOMServer.renderToString(\"notanelement\");",
"JSC_TYPE_MISMATCH");
test("var Comp = React.createClass({});" +
"ReactDOMServer.renderToStaticMarkup(React.createElement(Comp));",
"ReactDOMServer.renderToStaticMarkup(" +
"React.createElement(React.createClass({})));");
testError("ReactDOMServer.renderToStaticMarkup(\"notanelement\");",
"JSC_TYPE_MISMATCH");
}
@Test public void testReactDOMServerClass() {
test("class Comp extends React.Component {}" +
"ReactDOMServer.renderToString(React.createElement(Comp));",
"class $Comp$$ extends React.Component{}" +
"ReactDOMServer.renderToString(React.createElement($Comp$$));");
test("class Comp extends React.Component {}" +
"ReactDOMServer.renderToStaticMarkup(React.createElement(Comp));",
"class $Comp$$ extends React.Component{}" +
"ReactDOMServer.renderToStaticMarkup(React.createElement($Comp$$));");
}
/**
* Tests static methods and properties.
*/
@Test public void testStatics() {
test(
"var Comp = React.createClass({" +
"statics: {" +
"/** @const {number} */" +
"aNumber: 123,\n" +
"/** @const {string} */" +
"aString: \"456\",\n" +
"/** @return {number} */" +
"aFunction: function() {return 123}" +
"},\n" +
"render: function() {return React.createElement(\"div\");}" +
"});\n" +
"window.aNumber = Comp.aNumber;\n" +
"window.aString = Comp.aString;\n" +
"window.aFunctionResult = Comp.aFunction();\n",
"var $Comp$$=React.createClass({" +
"statics:{" +
"$aNumber$:123," +
"$aString$:\"456\"," +
"$aFunction$:function(){return 123}" +
"}," +
"render:function(){return React.createElement(\"div\")}" +
"});" +
"window.$aNumber$=$Comp$$.$aNumber$;" +
"window.$aString$=$Comp$$.$aString$;" +
"window.$aFunctionResult$=123;");
// JSDoc is required
testError(
"var Comp = React.createClass({" +
"statics: {" +
"aFunction: function(aNumber) {window.foo = aNumber}" +
"}," +
"render: function() {return React.createElement(\"div\");}" +
"});",
"REACT_JSDOC_REQUIRED_FOR_STATICS");
// JSDoc is used to validate.
testError(
"var Comp = React.createClass({" +
"statics: {" +
"/** @param {number} aNumber */" +
"aFunction: function(aNumber) {window.foo = aNumber}" +
"}," +
"render: function() {return React.createElement(\"div\");}" +
"});" +
"window.foo = Comp.aFunction('notANumber');",
"JSC_TYPE_MISMATCH");
}
@Test public void testStaticsClass() {
test(
"class Comp extends React.Component {" +
"render() {return React.createElement(\"div\");}" +
"/** @return {number} */" +
"static aFunction() {return 123}" +
"}\n" +
"/** @const {number} */" +
"Comp.aNumber = 123;\n" +
"/** @const {string} */" +
"Comp.aString = \"456\";\n" +
"window.aNumber = Comp.aNumber;\n" +
"window.aString = Comp.aString;\n" +
"window.aFunctionResult = Comp.aFunction();\n",
"window.$aNumber$=123;" +
"window.$aString$=\"456\";" +
"window.$aFunctionResult$=123;");
// JSDoc is used to validate.
testError(
"class Comp extends React.Component {" +
"/** @param {number} aNumber */" +
"static aFunction(aNumber) {window.foo = aNumber}" +
"render() {return React.createElement(\"div\");}" +
"}" +
"window.foo = Comp.aFunction('notANumber');",
"JSC_TYPE_MISMATCH");
}
@Test public void testPureRenderMixin() {
test(
"var Comp = React.createClass({" +
"mixins: [React.addons.PureRenderMixin]," +
"render: function() {" +
"return React.createElement(\"div\");" +
"}" +
"});" +
"ReactDOM.render(React.createElement(Comp), document.body);",
// Should be fine to use React.addons.PureRenderMixin.
"ReactDOM.render(React.createElement(React.createClass({" +
"mixins:[React.addons.PureRenderMixin]," +
"render:function(){" +
"return React.createElement(\"div\")" +
"}" +
"})),document.body);");
testError(
"var Comp = React.createClass({" +
"mixins: [React.addons.PureRenderMixin]," +
"shouldComponentUpdate: function(nextProps, nextState) {" +
"return true;" +
"}," +
"render: function() {" +
"return React.createElement(\"div\");" +
"}" +
"});",
// But there should be a warning if using PureRenderMixin yet
// shouldComponentUpdate is specified.
ReactCompilerPass.PURE_RENDER_MIXIN_SHOULD_COMPONENT_UPDATE_OVERRIDE);
}
@Test public void testExtendsPureComponent() {
test(
"class Comp extends React.PureComponent {" +
"render() {" +
"return React.createElement(\"div\");" +
"}" +
"}" +
"ReactDOM.render(React.createElement(Comp), document.body);",
// Should be fine to use React.PureComponent.
"class $Comp$$ extends React.PureComponent{" +
"render(){" +
"return React.createElement(\"div\")" +
"}" +
"}" +
"ReactDOM.render(React.createElement($Comp$$),document.body);");
testError(
"class Comp extends React.PureComponent {" +
"shouldComponentUpdate(nextProps, nextState) {" +
"return true;" +
"}" +
"render() {" +
"return React.createElement(\"div\");" +
"}" +
"}",
// But there should be a warning if using PureComponent and
// shouldComponentUpdate is specified.
ReactCompilerPass.PURE_COMPONENT_SHOULD_COMPONENT_UPDATE_OVERRIDE);
}
@Test public void testElementTypedef() {
test(
"var Comp = React.createClass({" +
"render: function() {" +
"return React.createElement(\"div\");" +
"}" +
"});\n" +
"/** @return {CompElement} */\n" +
"function create() {return React.createElement(Comp);}",
"");
test(
"var ns = {};" +
"ns.Comp = React.createClass({" +
"render: function() {" +
"return React.createElement(\"div\");" +
"}" +
"});\n" +
"/** @return {ns.CompElement} */\n" +
"function create() {return React.createElement(ns.Comp);}",
"");
}
@Test public void testElementTypedefClass() {
test(
"class Comp extends React.Component {" +
"render() {" +
"return React.createElement(\"div\");" +
"}" +
"}\n" +
"/** @return {CompElement} */\n" +
"function create() {return React.createElement(Comp);}",
"");
test(
"const ns = {};" +
"ns.Comp = class extends React.Component {" +
"render() {" +
"return React.createElement(\"div\");" +
"}" +
"}\n" +
"/** @return {ns.CompElement} */\n" +
"function create() {return React.createElement(ns.Comp);}",
"");
}
@Test public void testPropsSpreadInlining() {
test(
"var Comp = React.createClass({" +
"render: function() {" +
"var props = {a: \"1\"};\n" +
"return React.createElement(\"div\", {...props});" +
"}" +
"});" +
"ReactDOM.render(React.createElement(Comp), document.body);",
"ReactDOM.render(React.createElement(React.createClass({" +
"render:function(){" +
"return React.createElement(\"div\",{$a$:\"1\"})" +
"}" +
"})),document.body);");
}
@Test public void testPropsSpreadInliningClass() {
test(
"class Comp extends React.Component {" +
"render() {" +
"var props = {a: \"1\"};\n" +
"return React.createElement(\"div\", {...props});" +
"}" +
"}" +
"ReactDOM.render(React.createElement(Comp), document.body);",
"class $Comp$$ extends React.Component{" +
"render(){" +
"return React.createElement(\"div\",{$a$:\"1\"})" +
"}" +
"}" +
"ReactDOM.render(React.createElement($Comp$$),document.body);");
}
private static void test(String inputJs, String expectedJs) {
test(inputJs, expectedJs, null, null);
}
private static void testError(String inputJs, String expectedErrorName) {
test(inputJs, "", null, DiagnosticType.error(expectedErrorName, ""));
}
private static void testError(String inputJs, DiagnosticType expectedError) {
test(inputJs, "", null, expectedError);
}
private static void testNoError(String inputJs) {
test(inputJs, null, null, null);
}
private static void test(
String inputJs,
String expectedJs,
ReactCompilerPass.Options passOptions,
DiagnosticType expectedError) {
if (passOptions == null) {
passOptions = new ReactCompilerPass.Options();
passOptions.propTypesTypeChecking = true;
}
Compiler compiler = new Compiler(
new PrintStream(ByteStreams.nullOutputStream())); // Silence logging
compiler.disableThreads(); // Makes errors easier to track down.
CompilerOptions options = new CompilerOptions();
CompilationLevel.ADVANCED_OPTIMIZATIONS
.setOptionsForCompilationLevel(options);
WarningLevel.VERBOSE.setOptionsForWarningLevel(options);
options.setLanguage(CompilerOptions.LanguageMode.ECMASCRIPT_2018);
options.setEmitUseStrict(false); // It is just noise
if (!passOptions.optimizeForSize) {
// We assume that when optimizing for size we don't care about property
// checks (they rely on propTypes being extracted, which we don't do).
options.setWarningLevel(
DiagnosticGroups.MISSING_PROPERTIES, CheckLevel.ERROR);
options.setWarningLevel(
DiagnosticGroups.STRICT_MISSING_PROPERTIES, CheckLevel.ERROR);
}
options.setGenerateExports(true);
options.setExportLocalPropertyDefinitions(true);
options.setGeneratePseudoNames(true);
options.addWarningsGuard(new ReactWarningsGuard());
// Report warnings as errors to make tests simpler
options.addWarningsGuard(new StrictWarningsGuard());
options.addCustomPass(
CustomPassExecutionTime.BEFORE_CHECKS,
new ReactCompilerPass(compiler, passOptions));
List<SourceFile> inputs = Lists.newArrayList();
for (String fileJs : Splitter.on(FILE_SEPARATOR).split(inputJs)) {
inputs.add(
SourceFile.fromCode("/src/file" + (inputs.size() + 1) + ".js", fileJs));
}
List<SourceFile> builtInExterns;
try {
// We need the built-in externs so that Error and other built-in types
// are defined.
builtInExterns = AbstractCommandLineRunner.getBuiltinExterns(
CompilerOptions.Environment.CUSTOM);
} catch (IOException err) {
throw new RuntimeException(err);
}
List<SourceFile> externs = new ImmutableList.Builder()
.addAll(builtInExterns)
.add(SourceFile.fromCode("externs.js",
"/** @constructor */ function Element() {};" +
"/** @constructor */ function Event() {};" +
"var document;" +
"document.body;" +
"var window;"))
.build();
if (passOptions.optimizeForSize) {
options.setPrintInputDelimiter(true);
}
ReactCompilerPass.saveLastOutputForTests = true;
Result result = compiler.compile(externs, inputs, options);
String lastOutput = "\n\nInput:\n" + inputJs + "\nCompiler pass output:\n" +
ReactCompilerPass.lastOutputForTests + "\n";
if (compiler.getRoot() != null) {
// Use getSecondChild to skip over the externs root
lastOutput += "Final compiler output:\n" +
Debug.toTypeAnnotatedSource(
compiler, compiler.getRoot().getSecondChild()) +
"\n";
}
if (expectedError == null) {
assertEquals(
"Unexpected errors: " + Joiner.on(",").join(result.errors) +
lastOutput,
0, result.errors.size());
assertEquals(
"Unexpected warnings: " + Joiner.on(",").join(result.warnings) +
lastOutput,
0, result.warnings.size());
assertTrue(result.success);
if (expectedJs != null) {
String actualJs = compiler.toSource();
if (passOptions.optimizeForSize) {
int inputIndex = actualJs.indexOf(ACTUAL_JS_INPUT_MARKER);
assertNotEquals(-1, inputIndex);
actualJs = actualJs.substring(
inputIndex + ACTUAL_JS_INPUT_MARKER.length());
}
assertEquals(expectedJs, actualJs);
}
} else {
assertFalse(
"Expected failure, instead got output: " + compiler.toSource(),
result.success);
assertTrue(result.errors.size() > 0);
boolean foundError = false;
for (JSError error : result.errors) {
if (error.getType().equals(expectedError)) {
foundError = true;
break;
}
}
assertTrue(
"Did not find expected error " + expectedError +
", instead found " + Joiner.on(",").join(result.errors) +
lastOutput,
foundError);
assertEquals(
"Unexpected warnings: " + Joiner.on(",").join(result.warnings) +
lastOutput,
0, result.warnings.size());
}
}
}
|
Fix typo in comment
|
test/info/persistent/react/jscomp/ReactCompilerPassTest.java
|
Fix typo in comment
|
<ide><path>est/info/persistent/react/jscomp/ReactCompilerPassTest.java
<ide>
<ide> @Test public void testMixinOnExportClass() {
<ide> // The real error here was that SymbolTable uses a HashMap but we need an
<del> // Map that iterates in th insertion order.
<add> // Map that iterates in the insertion order.
<ide> testNoError(
<ide> REACT_SUPPORT_CODE +
<ide> "class TestMixin extends React.Component {" +
|
|
Java
|
lgpl-2.1
|
36b46b4bd15ff1ab5f70fe580ed64306f5568d53
| 0 |
ethaneldridge/vassal,ethaneldridge/vassal,ethaneldridge/vassal
|
/*
* Copyright (c) 2020 Vassalengine.org Brian Reynolds
* Inspired by VASL piece finder by David Sullivan
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License (LGPL) as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, copies are available
* at http://www.opensource.org.
*/
package VASSAL.build.module.map;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Point;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import VASSAL.build.BadDataReport;
import VASSAL.build.module.Chatter;
import VASSAL.build.module.map.boardPicker.board.mapgrid.Zone;
import VASSAL.command.NullCommand;
import VASSAL.configure.Configurer;
import VASSAL.configure.TranslatableStringEnum;
import VASSAL.i18n.TranslatableConfigurerFactory;
import VASSAL.tools.ErrorDialog;
import VASSAL.tools.FormattedString;
import VASSAL.tools.SequenceEncoder;
import VASSAL.tools.UniqueIdManager;
import org.jdesktop.animation.timing.Animator;
import org.jdesktop.animation.timing.TimingTargetAdapter;
import org.apache.commons.lang3.SystemUtils;
import VASSAL.build.AbstractConfigurable;
import VASSAL.build.AutoConfigurable;
import VASSAL.build.Buildable;
import VASSAL.build.GameModule;
import VASSAL.build.module.documentation.HelpFile;
import VASSAL.build.module.GameComponent;
import VASSAL.build.module.GlobalOptions;
import VASSAL.build.module.Map;
import VASSAL.command.Command;
import VASSAL.command.CommandEncoder;
import VASSAL.command.FlareCommand;
import VASSAL.configure.ColorConfigurer;
import VASSAL.configure.FlareFormattedStringConfigurer;
import VASSAL.i18n.Resources;
import VASSAL.tools.swing.SwingUtils;
/**
* Allows a player to ping a location ("send up a flare") by clicking on a map with the correct modifier key
* combination held down (default: Alt+LeftClick). Can be shown as an animated colored circle, or a plain one.
* If reportFormat field is provided, a message is also displayed in the chat log.
*
* Flare will work with both online play and PBEM play.
*/
public class Flare extends AbstractConfigurable
implements CommandEncoder, GameComponent, Drawable, MouseListener, UniqueIdManager.Identifyable {
private static final char DELIMITER = '\t'; //$NON-NLS-1$
public static final String COMMAND_PREFIX = "FLARE" + DELIMITER; //$NON-NLS-1$
protected static final UniqueIdManager idMgr = new UniqueIdManager("Flare"); //$NON-NLS-1$
protected String id = ""; // Our unique ID
// Attributes
private int circleSize; // Maximum circle size in pixels
private boolean circleScale; // If true, scale circle to map zoom
private int pulses; // How many total "pulses" to animate, or 0 for steady w/o animation
private int pulsesPerSec; // How many pulses per second, or 0 for steady w/o animation
private String flareKey; // Configures which set of modifier keys and click will produce the flare
private Color color; // Color for the flare circle
private FormattedString reportFormat = new FormattedString(); // Report format for reporting the flare to the chat log
// Internal properties
private Map map; // The map for this Flare
private Point clickPoint; // Clicked point where this Flare is to appear
private boolean animate; // Internal flag if we should be animating
private volatile boolean active; // Internal flag if we're currently active
// Attribute names
public static final String CIRCLE_SIZE = "circleSize"; //$NON-NLS-1$
public static final String CIRCLE_SCALE = "circleScale"; //$NON-NLS-1$
public static final String CIRCLE_COLOR = "circleColor"; //$NON-NLS-1$
public static final String FLARE_KEY = "flareKey"; //$NON-NLS-1$
public static final String PULSES = "flarePulses"; //$NON-NLS-1$
public static final String PULSES_PER_SEC = "flarePulsesPerSec"; //$NON-NLS-1$
public static final String REPORT_FORMAT = "reportFormat"; //$NON-NLS-1$
public static final String NAME = "flareName"; //$NON-NLS-1$
// Friendly (localizable) names for modifier key combinations
public static final String FLARE_ALT_LOCAL = Resources.getString("Editor.Flare.flare_key_desc", Resources.getString("Keys.alt")); //$NON-NLS-1$ //$NON-NLS-2$
public static final String FLARE_CTRL_LOCAL = Resources.getString("Editor.Flare.flare_key_desc", Resources.getString("Keys.ctrl")); //$NON-NLS-1$ //$NON-NLS-2$
public static final String FLARE_COMMAND_LOCAL = Resources.getString("Editor.Flare.flare_key_desc", Resources.getString("Keys.meta")); //$NON-NLS-1$ //$NON-NLS-2$
public static final String FLARE_ALT_SHIFT_LOCAL = Resources.getString("Editor.Flare.flare_key_desc", Resources.getString("Keys.alt_shift")); //$NON-NLS-1$ //$NON-NLS-2$
public static final String FLARE_SHIFT_COMMAND_LOCAL = Resources.getString("Editor.Flare.flare_key_desc", Resources.getString("Keys.shift_command")); //$NON-NLS-1$ //$NON-NLS-2$
public static final String FLARE_CTRL_SHIFT_LOCAL = Resources.getString("Editor.Flare.flare_key_desc", Resources.getString("Keys.ctrl_shift")); //$NON-NLS-1$ //$NON-NLS-2$
public static final String FLARE_ALT_COMMAND_LOCAL = Resources.getString("Editor.Flare.flare_key_desc", Resources.getString("Keys.alt_command")); //$NON-NLS-1$ //$NON-NLS-2$
public static final String FLARE_CTRL_ALT_LOCAL = Resources.getString("Editor.Flare.flare_key_desc", Resources.getString("Keys.ctrl_alt")); //$NON-NLS-1$ //$NON-NLS-2$
public static final String FLARE_ALT_SHIFT_COMMAND_LOCAL = Resources.getString("Editor.Flare.flare_key_desc", Resources.getString("Keys.alt_shift_command")); //$NON-NLS-1$ //$NON-NLS-2$
public static final String FLARE_CTRL_ALT_SHIFT_LOCAL = Resources.getString("Editor.Flare.flare_key_desc", Resources.getString("Keys.ctrl_alt_shift")); //$NON-NLS-1$ //$NON-NLS-2$
// The modifier key codes we actually store
public static final String FLARE_ALT = "keyAlt"; //$NON-NLS-1$
public static final String FLARE_CTRL = "keyCtrl"; //$NON-NLS-1$
public static final String FLARE_ALT_SHIFT = "keyAltShift"; //$NON-NLS-1$
public static final String FLARE_CTRL_SHIFT = "keyCtrlShift"; //$NON-NLS-1$
public static final String FLARE_CTRL_ALT = "keyCtrlAlt"; //$NON-NLS-1$
public static final String FLARE_CTRL_ALT_SHIFT = "keyCtrlAltShift"; //$NON-NLS-1$
// Special properties for our FormattedString reportFormat
public static final String FLARE_NAME = "FlareName"; //$NON-NLS-1$
public static final String FLARE_LOCATION = "FlareLocation"; //$NON-NLS-1$
public static final String FLARE_ZONE = "FlareZone"; //$NON-NLS-1$
public static final String FLARE_MAP = "FlareMap"; //$NON-NLS-1$
private static final int STROKE = 3;
public Flare() {
circleSize = 100;
circleScale = true;
color = Color.RED;
active = false;
flareKey = FLARE_ALT;
pulses = 6;
pulsesPerSec = 3;
setConfigureName(Resources.getString("Editor.Flare.desc"));
}
/**
* @return String description of this component, displayed in Editor.
*/
public String getDescription() {
return Resources.getString("Editor.Flare.desc"); //$NON-NLS-1$
}
/**
* @return String name of component class. The part in [..] in the Editor.
*/
public static String getConfigureTypeName() {
return Resources.getString("Editor.Flare.configure"); //$NON-NLS-1$
}
/**
* @return the Map associated with this Flare component.
*/
public Map getMap() {
return map;
}
/**
* Attribute types for this component's buildFile (xml) entry. These launch the proper configurers when the component is edited in the Editor.
* @return list of classes for attributes
*/
public Class<?>[] getAttributeTypes() {
return new Class[] { String.class, FlareKeyConfig.class, Integer.class, Color.class, Boolean.class, Integer.class, Integer.class, ReportFormatConfig.class };
}
/**
* Attribute names for this component's buildFile (xml) entry.
* @return list of names for attributes
*/
public String[] getAttributeNames() {
return new String[] { NAME, FLARE_KEY, CIRCLE_SIZE, CIRCLE_COLOR, CIRCLE_SCALE, PULSES, PULSES_PER_SEC, REPORT_FORMAT };
}
/**
* Attribute names for this component's buildFile (xml) entry. These show up in the Editor next to the configurers for each attribute.
* @return list of names for attributes
*/
public String[] getAttributeDescriptions() {
return new String[] {
Resources.getString("Editor.name_label"), //$NON-NLS-1$
Resources.getString("Editor.Flare.flare_key"), //$NON-NLS-1$
Resources.getString("Editor.Flare.circle_size"), //$NON-NLS-1$
Resources.getString("Editor.Flare.circle_color"), //$NON-NLS-1$
Resources.getString("Editor.Flare.circle_scale"), //$NON-NLS-1$
Resources.getString("Editor.Flare.pulses"), //$NON-NLS-1$
Resources.getString("Editor.Flare.pulses_per_sec"), //$NON-NLS-1$
Resources.getString("Editor.report_format")}; //$NON-NLS-1$
}
/**
* Gets current attribute value in string form.
*
* @param key - attribute name
*
* @return current the value of one of this component's attributes, in string form.
*/
public String getAttributeValueString(final String key) {
if (NAME.equals(key)) {
return getConfigureName();
}
else if (FLARE_KEY.equals(key)) {
return flareKey;
}
else if (CIRCLE_SIZE.equals(key)) {
return String.valueOf(circleSize);
}
else if (CIRCLE_COLOR.equals(key)) {
return ColorConfigurer.colorToString(color);
}
else if (CIRCLE_SCALE.equals(key)) {
return String.valueOf(circleScale);
}
else if (PULSES.equals(key)) {
return String.valueOf(pulses);
}
else if (PULSES_PER_SEC.equals(key)) {
return String.valueOf(pulsesPerSec);
}
else if (REPORT_FORMAT.equals(key)) {
return reportFormat.getFormat();
}
return null;
}
/**
* Sets the value of one of this component's attributes.
*
* @param key the name of the attribute
*
* @param value new value for attribute. Can pass either the Object itself or the String version.
*/
public void setAttribute(String key, Object value) {
if (NAME.equals(key)) {
setConfigureName((String) value);
}
else if (FLARE_KEY.equals(key)) {
if (FLARE_ALT_LOCAL.equals(value)) {
flareKey = FLARE_ALT;
}
else if (FLARE_COMMAND_LOCAL.equals(value) || FLARE_CTRL_LOCAL.equals(value)) {
flareKey = FLARE_CTRL;
}
else if (FLARE_ALT_SHIFT_LOCAL.equals(value)) {
flareKey = FLARE_ALT_SHIFT;
}
else if (FLARE_SHIFT_COMMAND_LOCAL.equals(value) || FLARE_CTRL_SHIFT_LOCAL.equals(value)) {
flareKey = FLARE_CTRL_SHIFT;
}
else if (FLARE_ALT_COMMAND_LOCAL.equals(value) || FLARE_CTRL_ALT_LOCAL.equals(value)) {
flareKey = FLARE_CTRL_ALT;
}
else if (FLARE_ALT_SHIFT_COMMAND_LOCAL.equals(value) || FLARE_CTRL_ALT_SHIFT_LOCAL.equals(value)) {
flareKey = FLARE_CTRL_ALT_SHIFT;
}
else {
flareKey = (String) value;
}
}
else if (CIRCLE_SIZE.equals(key)) {
if (value instanceof String) {
circleSize = Integer.parseInt((String) value);
}
else if (value instanceof Integer) {
circleSize = (Integer) value;
}
}
else if (CIRCLE_COLOR.equals(key)) {
if (value instanceof String) {
value = ColorConfigurer.stringToColor((String) value);
}
color = (Color)value;
}
else if (CIRCLE_SCALE.equals(key)) {
if (value instanceof String) {
value = Boolean.valueOf((String) value);
}
circleScale = (Boolean)value;
}
else if (PULSES.equals(key)) {
if (value instanceof String) {
pulses = Integer.parseInt((String) value);
}
else {
pulses = (Integer) value;
}
}
else if (PULSES_PER_SEC.equals(key)) {
if (value instanceof String) {
pulsesPerSec = Integer.parseInt((String) value);
}
else {
pulsesPerSec = (Integer) value;
}
}
else if (REPORT_FORMAT.equals(key)) {
if (value instanceof String) {
reportFormat.setFormat((String)value);
}
else {
reportFormat = (FormattedString)value;
}
}
}
/**
* @return Help file for this component, accessed when "Help" button in Editor is clicked while configuring component.
*/
@Override
public HelpFile getHelpFile() {
return HelpFile.getReferenceManualPage("Flare.htm"); //$NON-NLS-1$
}
/**
* Adds this component to a Buildable component. In this case, a Map.
* @param parent - the Map to add the Flare to.
*/
public void addTo(final Buildable parent) {
idMgr.add(this);
if (parent instanceof Map) {
map = (Map) parent;
GameModule.getGameModule().addCommandEncoder(this);
map.addDrawComponent(this);
map.addLocalMouseListener(this);
}
else {
ErrorDialog.dataWarning(new BadDataReport("Flare - can only be added to a Map. ", reportFormat.getFormat()));
}
}
/**
* Removes this component from a Buildable parent.
* @param parent - the Map to remove the Flare from.
*/
public void removeFrom(final Buildable parent) {
if (parent instanceof Map) {
GameModule.getGameModule().removeCommandEncoder(this);
}
idMgr.remove(this);
}
private double os_scale = 1.0;
private volatile float animfrac;
/**
* Repaint only the necessary area
*/
private void repaintArea() {
map.repaint(new Rectangle(
(int)(clickPoint.x - circleSize / 2.0 - 2 * STROKE * os_scale),
(int)(clickPoint.y - circleSize / 2.0 - 2 * STROKE * os_scale),
(int)(circleSize + 4 * STROKE * os_scale + 0.5),
(int)(circleSize + 4 * STROKE * os_scale + 0.5)
));
}
/**
* Animator to loop the Flare animation. Use the LOOP behavior so that it's always shrinking bullseye rings.
*/
private final Animator animator = new Animator(0, 1, Animator.RepeatBehavior.LOOP, new TimingTargetAdapter() {
@Override
public void begin() {
active = true;
animfrac = 0.0f;
repaintArea();
}
/**
* Animator tells us when to update the image.
* @param fraction Animator lets us know how far we are through our cycle
*/
@Override
public void timingEvent(float fraction) {
animfrac = fraction;
repaintArea();
}
/**
* Animator tells us we're done.
*/
@Override
public void end() {
active = false;
repaintArea();
}
});
/**
* Start the Flare animation.
* @param isLocal - true if this Flare was launched on this client (i.e. by this player). Otherwise, center on
* the ping location if user preferences are set for centering on opponent moves.
*/
public void startAnimation(final boolean isLocal) {
if (map == null) {
return; // Means we already mentioned BadModuleData earlier. Now we simply avoid crashing.
}
if (!isLocal) {
if (GlobalOptions.getInstance().centerOnOpponentsMove()) {
map.centerAt(clickPoint);
}
}
animator.stop();
animate = pulses > 0 && pulsesPerSec > 0;
animator.setRepeatCount(Math.max(pulses, 1));
animator.setDuration(1000 / Math.max(pulsesPerSec, 1));
animator.start();
}
/**
* Draw the Flare at current animation frame
* @param g - Graphics
* @param map - Map component
*/
public void draw(final Graphics g, final Map map) {
if (!active || (clickPoint == null)) {
return;
}
final Graphics2D g2d = (Graphics2D) g;
os_scale = g2d.getDeviceConfiguration().getDefaultTransform().getScaleX();
double diameter = (circleScale ? map.getZoom() : 1.0) * os_scale * circleSize;
if (animate) {
diameter *= (1.0 - animfrac);
}
if (diameter <= 0.0) {
return;
}
// translate the click location for current zoom
final Point p = map.mapToDrawing(clickPoint, os_scale);
// draw a circle around the selected point
g2d.setColor(color);
g2d.setStroke(new BasicStroke((float)(STROKE * os_scale)));
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.drawOval(
(int)(p.x - diameter / 2.0),
(int)(p.y - diameter / 2.0),
(int)(diameter + 0.5),
(int)(diameter + 0.5)
);
}
/**
* Flare is always drawn above counters
* @return true
*/
public boolean drawAboveCounters() {
return true;
}
/**
* Serializes Flare commands into string form.
* @param c Command
* @return String version of Flare Command, or null if not a Flare Command.
*/
public String encode(final Command c) {
if (c instanceof FlareCommand) {
SequenceEncoder se = new SequenceEncoder(DELIMITER);
se
.append(((FlareCommand)c).getId())
.append(((FlareCommand)c).getClickPoint().x)
.append(((FlareCommand)c).getClickPoint().y);
return COMMAND_PREFIX + se.getValue();
}
return null;
}
/**
* Deserializes string command info into a Flare Command.
* @param s String for a Flare Command
* @return Flare Command object
*/
public Command decode(final String s) {
if (s.startsWith(COMMAND_PREFIX + getId())) { // Make sure this command is for this flare
SequenceEncoder.Decoder sd = new SequenceEncoder.Decoder(s, DELIMITER);
sd.nextToken(); // Skip over the Command Prefix
sd.nextToken(); // Skip over the Id
final int x = sd.nextInt(0);
final int y = sd.nextInt(0);
clickPoint = new Point(x, y);
return new FlareCommand(this);
}
return null;
}
public Class<?>[] getAllowableConfigureComponents() {
return new Class[0];
}
/**
* @param e MouseEvent
*/
public void mouseClicked(final MouseEvent e) {
}
/**
* Check for our modifier key, and if so launch a Flare sequence on our map, and send a command to other players' along
* with a Chat Log message if a Report Format has been specified in the component.
* @param e - a MouseEvent
*/
public void mousePressed(final MouseEvent e) {
if (!SwingUtils.isMainMouseButtonDown(e)) {
return;
}
if (FLARE_CTRL.equals(flareKey)) {
if (!SwingUtils.isSelectionToggle(e) || e.isAltDown() || e.isShiftDown()) {
return;
}
}
else if (FLARE_ALT.equals(flareKey)) {
if (!e.isAltDown() || e.isShiftDown() || SwingUtils.isSelectionToggle(e)) {
return;
}
}
else if (FLARE_ALT_SHIFT.equals(flareKey)) {
if (!e.isAltDown() || !e.isShiftDown() || SwingUtils.isSelectionToggle(e)) {
return;
}
}
else if (FLARE_CTRL_SHIFT.equals(flareKey)) {
if (!e.isShiftDown() || !SwingUtils.isSelectionToggle(e) || e.isAltDown()) {
return;
}
}
else if (FLARE_CTRL_ALT.equals(flareKey)) {
if (!e.isAltDown() || !SwingUtils.isSelectionToggle(e) || e.isShiftDown()) {
return;
}
}
else if (FLARE_CTRL_ALT_SHIFT.equals(flareKey)) {
if (!e.isAltDown() || !e.isShiftDown() || !SwingUtils.isSelectionToggle(e)) {
return;
}
}
clickPoint = new Point(e.getX(), e.getY());
final GameModule mod = GameModule.getGameModule();
Command c = new NullCommand();
// Set special properties for our reportFormat to use ($FlareLocation$, $FlareZone$, $FlareMap$)
reportFormat.setProperty(FLARE_NAME, getAttributeValueString(NAME));
reportFormat.setProperty(FLARE_LOCATION, map.locationName(clickPoint));
Point sacrificialPoint = new Point(clickPoint); // findZone murderously writes back into the point it is passed, so we will pass it a sacrificialPoint rather than our precious one.
final Zone z = map.findZone(sacrificialPoint);
reportFormat.setProperty(FLARE_ZONE, (z != null) ? z.getName() : "");
reportFormat.setProperty(FLARE_MAP, map.getMapName());
String reportText = reportFormat.getLocalizedText(map); // Map and global properties also available (e.g. PlayerName, PlayerSide)
if (reportText.trim().length() > 0) {
c = new Chatter.DisplayText(mod.getChatter(), "* " + reportText);
c.execute();
}
// Send to other players
c = c.append(new FlareCommand(this));
mod.sendAndLog(c);
// Start animation on our own client
startAnimation(true);
}
/**
* @param e MouseEvent
*/
public void mouseReleased(final MouseEvent e) {
}
/**
* @param e MouseEvent
*/
public void mouseEntered(final MouseEvent e) {
}
/**
* @param e MouseEvent
*/
public void mouseExited(final MouseEvent e) {
}
/**
* @param gameStarting
*/
public void setup(final boolean gameStarting) {
}
/**
* @return Theoretically returns the command to "restore" this from a saved game or when adding a new player, but of
* course Flare doesn't need to be "restored", so null.
*/
public Command getRestoreCommand() {
return null;
}
/**
* Record our clicked point on the map
* @param p - point where player clicked and where flare should be shown
*/
public void setClickPoint(final Point p) {
clickPoint = p;
}
/**
* @return point where player clicked and where flare should be shown
*/
public Point getClickPoint() {
return clickPoint;
}
/**
* Sets our unique ID (among Flares), so that multiple Flares don't inadvertently start each other when we
* send commands to other clients.
* @param id Sets our unique ID
*/
@Override
public void setId(String id) {
this.id = id;
}
/**
* @return unique ID of this flare, for purposes of distinguishing between Flare commands
*/
@Override
public String getId() {
return id;
}
/**
* A configurer for different combinations of modifier key
*/
public static class FlareKeyConfig extends TranslatableStringEnum {
@Override
public String[] getValidValues(AutoConfigurable target) {
return new String[] {
FLARE_ALT,
FLARE_CTRL,
FLARE_ALT_SHIFT,
FLARE_CTRL_SHIFT,
FLARE_CTRL_ALT,
FLARE_CTRL_ALT_SHIFT
};
}
public String[] getI18nKeys(AutoConfigurable target) {
boolean macLegacy = GlobalOptions.getInstance().getPrefMacLegacy();
return new String[] {
FLARE_ALT_LOCAL,
SystemUtils.IS_OS_MAC_OSX && !macLegacy ? FLARE_COMMAND_LOCAL : FLARE_CTRL_LOCAL,
FLARE_ALT_SHIFT_LOCAL,
SystemUtils.IS_OS_MAC_OSX && !macLegacy ? FLARE_SHIFT_COMMAND_LOCAL : FLARE_CTRL_SHIFT_LOCAL,
SystemUtils.IS_OS_MAC_OSX && !macLegacy ? FLARE_ALT_COMMAND_LOCAL : FLARE_CTRL_ALT_LOCAL,
SystemUtils.IS_OS_MAC_OSX && !macLegacy ? FLARE_ALT_SHIFT_COMMAND_LOCAL : FLARE_CTRL_ALT_SHIFT_LOCAL,
};
}
}
/**
* A configurer for our reportFormat, which includes the unique $FlareLocation$, $FlareZone$, $FlareMap$ properties as
* well as $PlayerName$ and $PlayerSide$ in the "Insert" pulldown.
*/
public static class ReportFormatConfig implements TranslatableConfigurerFactory {
@Override
public Configurer getConfigurer(AutoConfigurable c, String key, String name) {
return new FlareFormattedStringConfigurer(key, name, new String[0]);
}
}
}
|
vassal-app/src/main/java/VASSAL/build/module/map/Flare.java
|
/*
* Copyright (c) 2020 Vassalengine.org Brian Reynolds
* Inspired by VASL piece finder by David Sullivan
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License (LGPL) as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, copies are available
* at http://www.opensource.org.
*/
package VASSAL.build.module.map;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Point;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import VASSAL.build.BadDataReport;
import VASSAL.build.module.Chatter;
import VASSAL.build.module.map.boardPicker.board.mapgrid.Zone;
import VASSAL.command.NullCommand;
import VASSAL.configure.Configurer;
import VASSAL.configure.TranslatableStringEnum;
import VASSAL.i18n.TranslatableConfigurerFactory;
import VASSAL.tools.ErrorDialog;
import VASSAL.tools.FormattedString;
import VASSAL.tools.SequenceEncoder;
import VASSAL.tools.UniqueIdManager;
import org.jdesktop.animation.timing.Animator;
import org.jdesktop.animation.timing.TimingTargetAdapter;
import org.apache.commons.lang3.SystemUtils;
import VASSAL.build.AbstractConfigurable;
import VASSAL.build.AutoConfigurable;
import VASSAL.build.Buildable;
import VASSAL.build.GameModule;
import VASSAL.build.module.documentation.HelpFile;
import VASSAL.build.module.GameComponent;
import VASSAL.build.module.GlobalOptions;
import VASSAL.build.module.Map;
import VASSAL.command.Command;
import VASSAL.command.CommandEncoder;
import VASSAL.command.FlareCommand;
import VASSAL.configure.ColorConfigurer;
import VASSAL.configure.FlareFormattedStringConfigurer;
import VASSAL.i18n.Resources;
import VASSAL.tools.swing.SwingUtils;
/**
* Allows a player to ping a location ("send up a flare") by clicking on a map with the correct modifier key
* combination held down (default: Alt+LeftClick). Can be shown as an animated colored circle, or a plain one.
* If reportFormat field is provided, a message is also displayed in the chat log.
*
* Flare will work with both online play and PBEM play.
*/
public class Flare extends AbstractConfigurable
implements CommandEncoder, GameComponent, Drawable, MouseListener, UniqueIdManager.Identifyable {
private static final char DELIMITER = '\t'; //$NON-NLS-1$
public static final String COMMAND_PREFIX = "FLARE" + DELIMITER; //$NON-NLS-1$
protected static final UniqueIdManager idMgr = new UniqueIdManager("Flare"); //$NON-NLS-1$
protected String id = ""; // Our unique ID
// Attributes
private int circleSize; // Maximum circle size in pixels
private boolean circleScale; // If true, scale circle to map zoom
private int pulses; // How many total "pulses" to animate, or 0 for steady w/o animation
private int pulsesPerSec; // How many pulses per second, or 0 for steady w/o animation
private String flareKey; // Configures which set of modifier keys and click will produce the flare
private Color color; // Color for the flare circle
private FormattedString reportFormat = new FormattedString(); // Report format for reporting the flare to the chat log
// Internal properties
private Map map; // The map for this Flare
private Point clickPoint; // Clicked point where this Flare is to appear
private boolean animate; // Internal flag if we should be animating
private volatile boolean active; // Internal flag if we're currently active
// Attribute names
public static final String CIRCLE_SIZE = "circleSize"; //$NON-NLS-1$
public static final String CIRCLE_SCALE = "circleScale"; //$NON-NLS-1$
public static final String CIRCLE_COLOR = "circleColor"; //$NON-NLS-1$
public static final String FLARE_KEY = "flareKey"; //$NON-NLS-1$
public static final String PULSES = "flarePulses"; //$NON-NLS-1$
public static final String PULSES_PER_SEC = "flarePulsesPerSec"; //$NON-NLS-1$
public static final String REPORT_FORMAT = "reportFormat"; //$NON-NLS-1$
public static final String NAME = "flareName"; //$NON-NLS-1$
// Friendly (localizable) names for modifier key combinations
public static final String FLARE_ALT_LOCAL = Resources.getString("Editor.Flare.flare_key_desc", Resources.getString("Keys.alt")); //$NON-NLS-1$ //$NON-NLS-2$
public static final String FLARE_CTRL_LOCAL = Resources.getString("Editor.Flare.flare_key_desc", Resources.getString("Keys.ctrl")); //$NON-NLS-1$ //$NON-NLS-2$
public static final String FLARE_COMMAND_LOCAL = Resources.getString("Editor.Flare.flare_key_desc", Resources.getString("Keys.meta")); //$NON-NLS-1$ //$NON-NLS-2$
public static final String FLARE_ALT_SHIFT_LOCAL = Resources.getString("Editor.Flare.flare_key_desc", Resources.getString("Keys.alt_shift")); //$NON-NLS-1$ //$NON-NLS-2$
public static final String FLARE_SHIFT_COMMAND_LOCAL = Resources.getString("Editor.Flare.flare_key_desc", Resources.getString("Keys.shift_command")); //$NON-NLS-1$ //$NON-NLS-2$
public static final String FLARE_CTRL_SHIFT_LOCAL = Resources.getString("Editor.Flare.flare_key_desc", Resources.getString("Keys.ctrl_shift")); //$NON-NLS-1$ //$NON-NLS-2$
public static final String FLARE_ALT_COMMAND_LOCAL = Resources.getString("Editor.Flare.flare_key_desc", Resources.getString("Keys.alt_command")); //$NON-NLS-1$ //$NON-NLS-2$
public static final String FLARE_CTRL_ALT_LOCAL = Resources.getString("Editor.Flare.flare_key_desc", Resources.getString("Keys.ctrl_alt")); //$NON-NLS-1$ //$NON-NLS-2$
public static final String FLARE_ALT_SHIFT_COMMAND_LOCAL = Resources.getString("Editor.Flare.flare_key_desc", Resources.getString("Keys.alt_shift_command")); //$NON-NLS-1$ //$NON-NLS-2$
public static final String FLARE_CTRL_ALT_SHIFT_LOCAL = Resources.getString("Editor.Flare.flare_key_desc", Resources.getString("Keys.ctrl_alt_shift")); //$NON-NLS-1$ //$NON-NLS-2$
// The modifier key codes we actually store
public static final String FLARE_ALT = "keyAlt"; //$NON-NLS-1$
public static final String FLARE_CTRL = "keyCtrl"; //$NON-NLS-1$
public static final String FLARE_ALT_SHIFT = "keyAltShift"; //$NON-NLS-1$
public static final String FLARE_CTRL_SHIFT = "keyCtrlShift"; //$NON-NLS-1$
public static final String FLARE_CTRL_ALT = "keyCtrlAlt"; //$NON-NLS-1$
public static final String FLARE_CTRL_ALT_SHIFT = "keyCtrlAltShift"; //$NON-NLS-1$
// Special properties for our FormattedString reportFormat
public static final String FLARE_NAME = "FlareName"; //$NON-NLS-1$
public static final String FLARE_LOCATION = "FlareLocation"; //$NON-NLS-1$
public static final String FLARE_ZONE = "FlareZone"; //$NON-NLS-1$
public static final String FLARE_MAP = "FlareMap"; //$NON-NLS-1$
private static final int STROKE = 3;
public Flare() {
circleSize = 100;
circleScale = true;
color = Color.RED;
active = false;
flareKey = FLARE_ALT;
pulses = 6;
pulsesPerSec = 3;
setConfigureName(Resources.getString("Editor.Flare.desc"));
}
/**
* @return String description of this component, displayed in Editor.
*/
public String getDescription() {
return Resources.getString("Editor.Flare.desc"); //$NON-NLS-1$
}
/**
* @return String name of component class. The part in [..] in the Editor.
*/
public static String getConfigureTypeName() {
return Resources.getString("Editor.Flare.configure"); //$NON-NLS-1$
}
/**
* @return the Map associated with this Flare component.
*/
public Map getMap() {
return map;
}
/**
* Attribute types for this component's buildFile (xml) entry. These launch the proper configurers when the component is edited in the Editor.
* @return list of classes for attributes
*/
public Class<?>[] getAttributeTypes() {
return new Class[] { String.class, FlareKeyConfig.class, Integer.class, Color.class, Boolean.class, Integer.class, Integer.class, ReportFormatConfig.class };
}
/**
* Attribute names for this component's buildFile (xml) entry.
* @return list of names for attributes
*/
public String[] getAttributeNames() {
return new String[] { NAME, FLARE_KEY, CIRCLE_SIZE, CIRCLE_COLOR, CIRCLE_SCALE, PULSES, PULSES_PER_SEC, REPORT_FORMAT };
}
/**
* Attribute names for this component's buildFile (xml) entry. These show up in the Editor next to the configurers for each attribute.
* @return list of names for attributes
*/
public String[] getAttributeDescriptions() {
return new String[] {
Resources.getString("Editor.name_label"), //$NON-NLS-1$
Resources.getString("Editor.Flare.flare_key"), //$NON-NLS-1$
Resources.getString("Editor.Flare.circle_size"), //$NON-NLS-1$
Resources.getString("Editor.Flare.circle_color"), //$NON-NLS-1$
Resources.getString("Editor.Flare.circle_scale"), //$NON-NLS-1$
Resources.getString("Editor.Flare.pulses"), //$NON-NLS-1$
Resources.getString("Editor.Flare.pulses_per_sec"), //$NON-NLS-1$
Resources.getString("Editor.report_format")}; //$NON-NLS-1$
}
/**
* Gets current attribute value in string form.
*
* @param key - attribute name
*
* @return current the value of one of this component's attributes, in string form.
*/
public String getAttributeValueString(final String key) {
if (NAME.equals(key)) {
return getConfigureName();
}
else if (FLARE_KEY.equals(key)) {
return flareKey;
}
else if (CIRCLE_SIZE.equals(key)) {
return String.valueOf(circleSize);
}
else if (CIRCLE_COLOR.equals(key)) {
return ColorConfigurer.colorToString(color);
}
else if (CIRCLE_SCALE.equals(key)) {
return String.valueOf(circleScale);
}
else if (PULSES.equals(key)) {
return String.valueOf(pulses);
}
else if (PULSES_PER_SEC.equals(key)) {
return String.valueOf(pulsesPerSec);
}
else if (REPORT_FORMAT.equals(key)) {
return reportFormat.getFormat();
}
return null;
}
/**
* Sets the value of one of this component's attributes.
*
* @param key the name of the attribute
*
* @param value new value for attribute. Can pass either the Object itself or the String version.
*/
public void setAttribute(String key, Object value) {
if (NAME.equals(key)) {
setConfigureName((String) value);
}
else if (FLARE_KEY.equals(key)) {
if (FLARE_ALT_LOCAL.equals(value)) {
flareKey = FLARE_ALT;
}
else if (FLARE_COMMAND_LOCAL.equals(value) || FLARE_CTRL_LOCAL.equals(value)) {
flareKey = FLARE_CTRL;
}
else if (FLARE_ALT_SHIFT_LOCAL.equals(value)) {
flareKey = FLARE_ALT_SHIFT;
}
else if (FLARE_SHIFT_COMMAND_LOCAL.equals(value) || FLARE_CTRL_SHIFT_LOCAL.equals(value)) {
flareKey = FLARE_CTRL_SHIFT;
}
else if (FLARE_ALT_COMMAND_LOCAL.equals(value) || FLARE_CTRL_ALT_LOCAL.equals(value)) {
flareKey = FLARE_CTRL_ALT;
}
else if (FLARE_ALT_SHIFT_COMMAND_LOCAL.equals(value) || FLARE_CTRL_ALT_SHIFT_LOCAL.equals(value)) {
flareKey = FLARE_CTRL_ALT_SHIFT;
}
else {
flareKey = (String) value;
}
}
else if (CIRCLE_SIZE.equals(key)) {
if (value instanceof String) {
circleSize = Integer.parseInt((String) value);
}
else if (value instanceof Integer) {
circleSize = (Integer) value;
}
}
else if (CIRCLE_COLOR.equals(key)) {
if (value instanceof String) {
value = ColorConfigurer.stringToColor((String) value);
}
color = (Color)value;
}
else if (CIRCLE_SCALE.equals(key)) {
if (value instanceof String) {
value = Boolean.valueOf((String) value);
}
circleScale = (Boolean)value;
}
else if (PULSES.equals(key)) {
if (value instanceof String) {
pulses = Integer.parseInt((String) value);
}
else {
pulses = (Integer) value;
}
}
else if (PULSES_PER_SEC.equals(key)) {
if (value instanceof String) {
pulsesPerSec = Integer.parseInt((String) value);
}
else {
pulsesPerSec = (Integer) value;
}
}
else if (REPORT_FORMAT.equals(key)) {
if (value instanceof String) {
reportFormat.setFormat((String)value);
}
else {
reportFormat = (FormattedString)value;
}
}
}
/**
* @return Help file for this component, accessed when "Help" button in Editor is clicked while configuring component.
*/
@Override
public HelpFile getHelpFile() {
return HelpFile.getReferenceManualPage("Flare.htm"); //$NON-NLS-1$
}
/**
* Adds this component to a Buildable component. In this case, a Map.
* @param parent - the Map to add the Flare to.
*/
public void addTo(final Buildable parent) {
idMgr.add(this);
if (parent instanceof Map) {
map = (Map) parent;
GameModule.getGameModule().addCommandEncoder(this);
map.addDrawComponent(this);
map.addLocalMouseListener(this);
}
else {
ErrorDialog.dataWarning(new BadDataReport("Flare - can only be added to a Map. ", reportFormat.getFormat()));
}
}
/**
* Removes this component from a Buildable parent.
* @param parent - the Map to remove the Flare from.
*/
public void removeFrom(final Buildable parent) {
if (parent instanceof Map) {
GameModule.getGameModule().removeCommandEncoder(this);
}
idMgr.remove(this);
}
private double os_scale = 1.0;
private volatile float animfrac;
/**
* Repaint only the necessary area
*/
private void repaintArea() {
map.repaint(new Rectangle(
(int)(clickPoint.x - circleSize / 2.0 - 2 * STROKE * os_scale),
(int)(clickPoint.y - circleSize / 2.0 - 2 * STROKE * os_scale),
(int)(circleSize + 4 * STROKE * os_scale + 0.5),
(int)(circleSize + 4 * STROKE * os_scale + 0.5)
));
}
/**
* Animator to loop the Flare animation. Use the LOOP behavior so that it's always shrinking bullseye rings.
*/
private final Animator animator = new Animator(0, 1, Animator.RepeatBehavior.LOOP, new TimingTargetAdapter() {
@Override
public void begin() {
active = true;
animfrac = 0.0f;
repaintArea();
}
/**
* Animator tells us when to update the image.
* @param fraction Animator lets us know how far we are through our cycle
*/
@Override
public void timingEvent(float fraction) {
animfrac = fraction;
repaintArea();
}
/**
* Animator tells us we're done.
*/
@Override
public void end() {
active = false;
repaintArea();
}
});
/**
* Start the Flare animation.
* @param isLocal - true if this Flare was launched on this client (i.e. by this player). Otherwise, center on
* the ping location if user preferences are set for centering on opponent moves.
*/
public void startAnimation(final boolean isLocal) {
if (map == null) {
return; // Means we already mentioned BadModuleData earlier. Now we simply avoid crashing.
}
if (!isLocal) {
if (GlobalOptions.getInstance().centerOnOpponentsMove()) {
map.centerAt(clickPoint);
}
}
animator.stop();
animate = pulses > 0 && pulsesPerSec > 0;
animator.setRepeatCount(Math.max(pulses, 1));
animator.setDuration(1000 / Math.max(pulsesPerSec, 1));
animator.start();
}
/**
* Draw the Flare at current animation frame
* @param g - Graphics
* @param map - Map component
*/
public void draw(final Graphics g, final Map map) {
if (!active || (clickPoint == null)) {
return;
}
final Graphics2D g2d = (Graphics2D) g;
os_scale = g2d.getDeviceConfiguration().getDefaultTransform().getScaleX();
double diameter = (circleScale ? map.getZoom() : 1.0) * os_scale * circleSize;
if (animate) {
diameter *= (1.0 - animfrac);
}
if (diameter <= 0.0) {
return;
}
// translate the click location for current zoom
final Point p = map.mapToDrawing(clickPoint, os_scale);
// draw a circle around the selected point
g2d.setColor(color);
g2d.setStroke(new BasicStroke((float)(STROKE * os_scale)));
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.drawOval(
(int)(p.x - diameter / 2.0),
(int)(p.y - diameter / 2.0),
(int)(diameter + 0.5),
(int)(diameter + 0.5)
);
}
/**
* Flare is always drawn above counters
* @return true
*/
public boolean drawAboveCounters() {
return true;
}
/**
* Serializes Flare commands into string form.
* @param c Command
* @return String version of Flare Command, or null if not a Flare Command.
*/
public String encode(final Command c) {
if (c instanceof FlareCommand) {
SequenceEncoder se = new SequenceEncoder(DELIMITER);
se
.append(((FlareCommand)c).getId())
.append(((FlareCommand)c).getClickPoint().x)
.append(((FlareCommand)c).getClickPoint().y);
return COMMAND_PREFIX + se.getValue();
}
return null;
}
/**
* Deserializes string command info into a Flare Command.
* @param s String for a Flare Command
* @return Flare Command object
*/
public Command decode(final String s) {
if (s.startsWith(COMMAND_PREFIX + getId())) { // Make sure this command is for this flare
SequenceEncoder.Decoder sd = new SequenceEncoder.Decoder(s, DELIMITER);
sd.nextToken(); // Skip over the Command Prefix
sd.nextToken(); // Skip over the Id
final int x = sd.nextInt(0);
final int y = sd.nextInt(0);
clickPoint = new Point(x, y);
return new FlareCommand(this);
}
return null;
}
public Class<?>[] getAllowableConfigureComponents() {
return new Class[0];
}
/**
* @param e MouseEvent
*/
public void mouseClicked(final MouseEvent e) {
}
/**
* Check for our modifier key, and if so launch a Flare sequence on our map, and send a command to other players' along
* with a Chat Log message if a Report Format has been specified in the component.
* @param e - a MouseEvent
*/
public void mousePressed(final MouseEvent e) {
if (!SwingUtils.isMainMouseButtonDown(e)) {
return;
}
if (FLARE_CTRL.equals(flareKey)) {
if (!SwingUtils.isSelectionToggle(e) || e.isAltDown() || e.isShiftDown()) {
return;
}
}
else if (FLARE_ALT.equals(flareKey)) {
if (!e.isAltDown() || e.isShiftDown() || SwingUtils.isSelectionToggle(e)) {
return;
}
}
else if (FLARE_ALT_SHIFT.equals(flareKey)) {
if (!e.isAltDown() || !e.isShiftDown() || SwingUtils.isSelectionToggle(e)) {
return;
}
}
else if (FLARE_CTRL_SHIFT.equals(flareKey)) {
if (!e.isShiftDown() || !SwingUtils.isSelectionToggle(e) || e.isAltDown()) {
return;
}
}
else if (FLARE_CTRL_ALT.equals(flareKey)) {
if (!e.isAltDown() || !SwingUtils.isSelectionToggle(e) || e.isShiftDown()) {
return;
}
}
else if (FLARE_CTRL_ALT_SHIFT.equals(flareKey)) {
if (!e.isAltDown() || !e.isShiftDown() || !SwingUtils.isSelectionToggle(e)) {
return;
}
}
clickPoint = new Point(e.getX(), e.getY());
final GameModule mod = GameModule.getGameModule();
Command c = new NullCommand();
// Set special properties for our reportFormat to use ($FlareLocation$, $FlareZone$, $FlareMap$)
reportFormat.setProperty(FLARE_NAME, getAttributeValueString(NAME));
reportFormat.setProperty(FLARE_LOCATION, map.locationName(clickPoint));
final Zone z = map.findZone(clickPoint);
reportFormat.setProperty(FLARE_ZONE, (z != null) ? z.getName() : "");
reportFormat.setProperty(FLARE_MAP, map.getMapName());
String reportText = reportFormat.getLocalizedText(map); // Map and global properties also available (e.g. PlayerName, PlayerSide)
if (reportText.trim().length() > 0) {
c = new Chatter.DisplayText(mod.getChatter(), "* " + reportText);
c.execute();
}
// Send to other players
c = c.append(new FlareCommand(this));
mod.sendAndLog(c);
// Start animation on our own client
startAnimation(true);
}
/**
* @param e MouseEvent
*/
public void mouseReleased(final MouseEvent e) {
}
/**
* @param e MouseEvent
*/
public void mouseEntered(final MouseEvent e) {
}
/**
* @param e MouseEvent
*/
public void mouseExited(final MouseEvent e) {
}
/**
* @param gameStarting
*/
public void setup(final boolean gameStarting) {
}
/**
* @return Theoretically returns the command to "restore" this from a saved game or when adding a new player, but of
* course Flare doesn't need to be "restored", so null.
*/
public Command getRestoreCommand() {
return null;
}
/**
* Record our clicked point on the map
* @param p - point where player clicked and where flare should be shown
*/
public void setClickPoint(final Point p) {
clickPoint = p;
}
/**
* @return point where player clicked and where flare should be shown
*/
public Point getClickPoint() {
return clickPoint;
}
/**
* Sets our unique ID (among Flares), so that multiple Flares don't inadvertently start each other when we
* send commands to other clients.
* @param id Sets our unique ID
*/
@Override
public void setId(String id) {
this.id = id;
}
/**
* @return unique ID of this flare, for purposes of distinguishing between Flare commands
*/
@Override
public String getId() {
return id;
}
/**
* A configurer for different combinations of modifier key
*/
public static class FlareKeyConfig extends TranslatableStringEnum {
@Override
public String[] getValidValues(AutoConfigurable target) {
return new String[] {
FLARE_ALT,
FLARE_CTRL,
FLARE_ALT_SHIFT,
FLARE_CTRL_SHIFT,
FLARE_CTRL_ALT,
FLARE_CTRL_ALT_SHIFT
};
}
public String[] getI18nKeys(AutoConfigurable target) {
boolean macLegacy = GlobalOptions.getInstance().getPrefMacLegacy();
return new String[] {
FLARE_ALT_LOCAL,
SystemUtils.IS_OS_MAC_OSX && !macLegacy ? FLARE_COMMAND_LOCAL : FLARE_CTRL_LOCAL,
FLARE_ALT_SHIFT_LOCAL,
SystemUtils.IS_OS_MAC_OSX && !macLegacy ? FLARE_SHIFT_COMMAND_LOCAL : FLARE_CTRL_SHIFT_LOCAL,
SystemUtils.IS_OS_MAC_OSX && !macLegacy ? FLARE_ALT_COMMAND_LOCAL : FLARE_CTRL_ALT_LOCAL,
SystemUtils.IS_OS_MAC_OSX && !macLegacy ? FLARE_ALT_SHIFT_COMMAND_LOCAL : FLARE_CTRL_ALT_SHIFT_LOCAL,
};
}
}
/**
* A configurer for our reportFormat, which includes the unique $FlareLocation$, $FlareZone$, $FlareMap$ properties as
* well as $PlayerName$ and $PlayerSide$ in the "Insert" pulldown.
*/
public static class ReportFormatConfig implements TranslatableConfigurerFactory {
@Override
public Configurer getConfigurer(AutoConfigurable c, String key, String name) {
return new FlareFormattedStringConfigurer(key, name, new String[0]);
}
}
}
|
accounted for MURDEROUS BEHAVIOR by Map.findZone
|
vassal-app/src/main/java/VASSAL/build/module/map/Flare.java
|
accounted for MURDEROUS BEHAVIOR by Map.findZone
|
<ide><path>assal-app/src/main/java/VASSAL/build/module/map/Flare.java
<ide> // Set special properties for our reportFormat to use ($FlareLocation$, $FlareZone$, $FlareMap$)
<ide> reportFormat.setProperty(FLARE_NAME, getAttributeValueString(NAME));
<ide> reportFormat.setProperty(FLARE_LOCATION, map.locationName(clickPoint));
<del> final Zone z = map.findZone(clickPoint);
<add> Point sacrificialPoint = new Point(clickPoint); // findZone murderously writes back into the point it is passed, so we will pass it a sacrificialPoint rather than our precious one.
<add> final Zone z = map.findZone(sacrificialPoint);
<ide> reportFormat.setProperty(FLARE_ZONE, (z != null) ? z.getName() : "");
<ide> reportFormat.setProperty(FLARE_MAP, map.getMapName());
<ide> String reportText = reportFormat.getLocalizedText(map); // Map and global properties also available (e.g. PlayerName, PlayerSide)
|
|
Java
|
apache-2.0
|
ab12309f7c69a565ceced368dfff0421b63287da
| 0 |
hhclam/bazel,hhclam/bazel,hhclam/bazel,hhclam/bazel,hhclam/bazel,hhclam/bazel
|
// Copyright 2016 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.remote;
import com.google.devtools.common.options.Option;
import com.google.devtools.common.options.OptionsBase;
/**
* Options for remote execution and distributed caching.
*/
public class RemoteOptions extends OptionsBase {
@Option(
name = "memcache_uri",
defaultValue = "null",
category = "remote",
help = "Implementation specific URI for the memcache provider."
)
public String memcacheUri;
@Option(
name = "memcache_provider",
defaultValue = "null",
category = "remote",
help = "Class name of the cache provider."
)
public String memcacheProvider;
@Option(
name = "hazelcast_configuration",
defaultValue = "null",
category = "remote",
help = "The location of configuration file when using hazelcast for memcache. When using " +
" Hazelcast in server mode a value (anything) for --memcache_uri needs to be specified." +
" Hazelcast clients must have the same value for --memcache_uri."
)
public String hazelcastConfiguration;
@Option(
name = "hazelcast_node",
defaultValue = "null",
category = "remote",
help = "A comma separated list of hostnames of hazelcast nodes. For client mode only."
)
public String hazelcastNode;
@Option(
name = "rest_worker_url",
defaultValue = "null",
category = "remote",
help = "URL for the REST worker."
)
public String restWorkerUrl;
}
|
src/main/java/com/google/devtools/build/lib/remote/RemoteOptions.java
|
// Copyright 2016 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.remote;
import com.google.devtools.common.options.Option;
import com.google.devtools.common.options.OptionsBase;
/**
* Options for remote execution and distributed caching.
*/
public class RemoteOptions extends OptionsBase {
@Option(
name = "memcache_uri",
defaultValue = "null",
category = "remote",
help = "URI for the memcache."
)
public String memcacheUri;
@Option(
name = "memcache_provider",
defaultValue = "null",
category = "remote",
help = "Class name of the cache provider."
)
public String memcacheProvider;
@Option(
name = "hazelcast_configuration",
defaultValue = "null",
category = "remote",
help = "The location of configuration file when using hazelcast for memcache. When using " +
" Hazelcast in server mode a value (anything) for --memcache_uri needs to be specified."
)
public String hazelcastConfiguration;
@Option(
name = "hazelcast_node",
defaultValue = "null",
category = "remote",
help = "A comma separated list of hostnames of hazelcast nodes. For client mode only."
)
public String hazelcastNode;
@Option(
name = "rest_worker_url",
defaultValue = "null",
category = "remote",
help = "URL for the REST worker."
)
public String restWorkerUrl;
}
|
More comments for RemoteOptions
Make it clean what the options for --memcache_uri do.
Change-Id: I45a9c9d58a8b1ffe86840f217ac8eb88fac95961
|
src/main/java/com/google/devtools/build/lib/remote/RemoteOptions.java
|
More comments for RemoteOptions
|
<ide><path>rc/main/java/com/google/devtools/build/lib/remote/RemoteOptions.java
<ide> name = "memcache_uri",
<ide> defaultValue = "null",
<ide> category = "remote",
<del> help = "URI for the memcache."
<add> help = "Implementation specific URI for the memcache provider."
<ide> )
<ide> public String memcacheUri;
<ide>
<ide> defaultValue = "null",
<ide> category = "remote",
<ide> help = "The location of configuration file when using hazelcast for memcache. When using " +
<del> " Hazelcast in server mode a value (anything) for --memcache_uri needs to be specified."
<add> " Hazelcast in server mode a value (anything) for --memcache_uri needs to be specified." +
<add> " Hazelcast clients must have the same value for --memcache_uri."
<ide> )
<ide> public String hazelcastConfiguration;
<ide>
|
|
Java
|
apache-2.0
|
a1f53160b4b793775cbaccaf0a2813c80c1a0048
| 0 |
everit-org/ecm-annotation-metadatabuilder,zsigmond-czine-everit/ecm-annotation-metadatabuilder
|
/**
* This file is part of Everit - Component Annotations Metadata Builder.
*
* Everit - Component Annotations Metadata Builder is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Everit - Component Annotations Metadata Builder 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 Everit - Component Annotations Metadata Builder. If not, see <http://www.gnu.org/licenses/>.
*/
package org.everit.osgi.ecm.annotation.metadatabuilder;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.everit.osgi.ecm.annotation.Activate;
import org.everit.osgi.ecm.annotation.AttributeOrder;
import org.everit.osgi.ecm.annotation.AutoDetect;
import org.everit.osgi.ecm.annotation.BundleCapabilityReference;
import org.everit.osgi.ecm.annotation.BundleCapabilityReferences;
import org.everit.osgi.ecm.annotation.Component;
import org.everit.osgi.ecm.annotation.Deactivate;
import org.everit.osgi.ecm.annotation.ServiceReference;
import org.everit.osgi.ecm.annotation.ServiceReferences;
import org.everit.osgi.ecm.annotation.Update;
import org.everit.osgi.ecm.annotation.attribute.BooleanAttribute;
import org.everit.osgi.ecm.annotation.attribute.BooleanAttributes;
import org.everit.osgi.ecm.annotation.attribute.ByteAttribute;
import org.everit.osgi.ecm.annotation.attribute.ByteAttributes;
import org.everit.osgi.ecm.annotation.attribute.CharacterAttribute;
import org.everit.osgi.ecm.annotation.attribute.CharacterAttributes;
import org.everit.osgi.ecm.annotation.attribute.DoubleAttribute;
import org.everit.osgi.ecm.annotation.attribute.DoubleAttributes;
import org.everit.osgi.ecm.annotation.attribute.FloatAttribute;
import org.everit.osgi.ecm.annotation.attribute.FloatAttributes;
import org.everit.osgi.ecm.annotation.attribute.IntegerAttribute;
import org.everit.osgi.ecm.annotation.attribute.IntegerAttributes;
import org.everit.osgi.ecm.annotation.attribute.LongAttribute;
import org.everit.osgi.ecm.annotation.attribute.LongAttributes;
import org.everit.osgi.ecm.annotation.attribute.PasswordAttribute;
import org.everit.osgi.ecm.annotation.attribute.PasswordAttributes;
import org.everit.osgi.ecm.annotation.attribute.ShortAttribute;
import org.everit.osgi.ecm.annotation.attribute.ShortAttributes;
import org.everit.osgi.ecm.annotation.attribute.StringAttribute;
import org.everit.osgi.ecm.annotation.attribute.StringAttributes;
import org.everit.osgi.ecm.metadata.AttributeMetadata;
import org.everit.osgi.ecm.metadata.AttributeMetadata.AttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.BooleanAttributeMetadata.BooleanAttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.BundleCapabilityReferenceMetadata.BundleCapabilityReferenceMetadataBuilder;
import org.everit.osgi.ecm.metadata.ByteAttributeMetadata.ByteAttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.CharacterAttributeMetadata.CharacterAttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.ComponentMetadata;
import org.everit.osgi.ecm.metadata.ComponentMetadata.ComponentMetadataBuilder;
import org.everit.osgi.ecm.metadata.ConfigurationPolicy;
import org.everit.osgi.ecm.metadata.DoubleAttributeMetadata.DoubleAttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.FloatAttributeMetadata.FloatAttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.Icon;
import org.everit.osgi.ecm.metadata.IntegerAttributeMetadata.IntegerAttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.LongAttributeMetadata.LongAttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.MetadataValidationException;
import org.everit.osgi.ecm.metadata.PasswordAttributeMetadata.PasswordAttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.PropertyAttributeMetadata.PropertyAttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.ReferenceConfigurationType;
import org.everit.osgi.ecm.metadata.ReferenceMetadata.ReferenceMetadataBuilder;
import org.everit.osgi.ecm.metadata.SelectablePropertyAttributeMetadata.SelectablePropertyAttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.ServiceReferenceMetadata.ServiceReferenceMetadataBuilder;
import org.everit.osgi.ecm.metadata.ShortAttributeMetadata.ShortAttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.StringAttributeMetadata.StringAttributeMetadataBuilder;
import org.everit.osgi.ecm.util.method.MethodDescriptor;
import org.everit.osgi.ecm.util.method.MethodUtil;
public class MetadataBuilder<C> {
private static final Set<Class<?>> ANNOTATION_CONTAINER_TYPES;
static {
ANNOTATION_CONTAINER_TYPES = new HashSet<Class<?>>();
ANNOTATION_CONTAINER_TYPES.add(ServiceReferences.class);
ANNOTATION_CONTAINER_TYPES.add(BundleCapabilityReferences.class);
ANNOTATION_CONTAINER_TYPES.add(BooleanAttributes.class);
ANNOTATION_CONTAINER_TYPES.add(ByteAttributes.class);
ANNOTATION_CONTAINER_TYPES.add(CharacterAttributes.class);
ANNOTATION_CONTAINER_TYPES.add(DoubleAttributes.class);
ANNOTATION_CONTAINER_TYPES.add(FloatAttributes.class);
ANNOTATION_CONTAINER_TYPES.add(IntegerAttributes.class);
ANNOTATION_CONTAINER_TYPES.add(LongAttributes.class);
ANNOTATION_CONTAINER_TYPES.add(PasswordAttributes.class);
ANNOTATION_CONTAINER_TYPES.add(ShortAttributes.class);
ANNOTATION_CONTAINER_TYPES.add(StringAttributes.class);
}
public static <C> ComponentMetadata buildComponentMetadata(Class<C> clazz) {
MetadataBuilder<C> metadataBuilder = new MetadataBuilder<C>(clazz);
return metadataBuilder.build();
}
private static <O> O[] convertPrimitiveArray(Object primitiveArray, Class<O> targetType) {
int length = Array.getLength(primitiveArray);
if (length == 0) {
return null;
}
@SuppressWarnings("unchecked")
O[] result = (O[]) Array.newInstance(targetType, length);
for (int i = 0; i < length; i++) {
@SuppressWarnings("unchecked")
O element = (O) Array.get(primitiveArray, i);
result[i] = element;
}
return result;
}
private LinkedHashMap<String, AttributeMetadata<?>> attributes =
new LinkedHashMap<String, AttributeMetadata<?>>();
private Class<C> clazz;
private MetadataBuilder() {
}
private MetadataBuilder(Class<C> clazz) {
this.clazz = clazz;
}
private ComponentMetadata build() {
Component componentAnnotation = clazz.getAnnotation(Component.class);
if (componentAnnotation == null) {
throw new ComponentAnnotationMissingException("Component annotation is missing on type " + clazz.toString());
}
ComponentMetadataBuilder componentMetaBuilder = new ComponentMetadataBuilder()
.withComponentId(makeStringNullIfEmpty(componentAnnotation.componentId()))
.withConfigurationPid(makeStringNullIfEmpty(componentAnnotation.configurationPid()))
.withConfigurationPolicy(convertConfigurationPolicy(componentAnnotation.configurationPolicy()))
.withDescription(makeStringNullIfEmpty(componentAnnotation.description()))
.withIcons(convertIcons(componentAnnotation.icons()))
.withMetatype(componentAnnotation.metatype())
.withLabel(makeStringNullIfEmpty(componentAnnotation.label()))
.withLocalizationBase(makeStringNullIfEmpty(componentAnnotation.localizationBase()))
.withType(clazz.getName())
.withActivate(findMethodWithAnnotation(Activate.class))
.withDeactivate(findMethodWithAnnotation(Deactivate.class))
.withUpdate(findMethodWithAnnotation(Update.class));
generateMetaForAttributeHolders();
orderedAttributes();
componentMetaBuilder.withAttributes(attributes.values().toArray(
new AttributeMetadata<?>[0]));
return componentMetaBuilder.build();
}
private <R> R callMethodOfAnnotation(Annotation annotation, String fieldName) {
Class<? extends Annotation> annotationType = annotation.getClass();
Method method;
try {
method = annotationType.getMethod(fieldName);
@SuppressWarnings("unchecked")
R result = (R) method.invoke(annotation);
return result;
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
throw new RuntimeException(e);
}
}
private ConfigurationPolicy convertConfigurationPolicy(
org.everit.osgi.ecm.annotation.ConfigurationPolicy configurationPolicy) {
switch (configurationPolicy) {
case IGNORE:
return ConfigurationPolicy.IGNORE;
case REQUIRE:
return ConfigurationPolicy.REQUIRE;
case FACTORY:
return ConfigurationPolicy.FACTORY;
default:
return ConfigurationPolicy.OPTIONAL;
}
}
private Icon[] convertIcons(org.everit.osgi.ecm.annotation.Icon[] icons) {
if (icons == null) {
return null;
}
Icon[] result = new Icon[icons.length];
for (int i = 0; i < icons.length; i++) {
result[i] = new Icon(icons[i].path(), icons[i].size());
}
return result;
}
private ReferenceConfigurationType convertReferenceConfigurationType(
org.everit.osgi.ecm.annotation.ReferenceConfigurationType attributeType) {
if (attributeType.equals(org.everit.osgi.ecm.annotation.ReferenceConfigurationType.CLAUSE)) {
return ReferenceConfigurationType.CLAUSE;
} else {
return ReferenceConfigurationType.FILTER;
}
}
private String deriveReferenceId(Member member, Annotation annotation) {
String name = callMethodOfAnnotation(annotation, "referenceId");
name = makeStringNullIfEmpty(name);
if (name != null) {
return name;
}
if (member != null) {
String memberName = member.getName();
if (member instanceof Field) {
return memberName;
} else if (member instanceof Method) {
String referenceId = resolveIdIfMethodNameStartsWith(memberName, "bind");
if (referenceId != null) {
return referenceId;
}
return resolveIdIfMethodNameStartsWith(memberName, "set");
}
}
return null;
}
private Class<?> deriveServiceInterface(Member member, ServiceReference annotation) {
Class<?> referenceInterface = annotation.referenceInterface();
if (!AutoDetect.class.equals(referenceInterface)) {
return referenceInterface;
}
if (member != null && member instanceof Field) {
return ((Field) member).getType();
}
return null;
}
private <V, B extends AttributeMetadataBuilder<V, B>> void fillAttributeMetaBuilder(
Member member,
Annotation annotation,
AttributeMetadataBuilder<V, B> builder) {
Boolean dynamic = callMethodOfAnnotation(annotation, "dynamic");
Boolean optional = callMethodOfAnnotation(annotation, "optional");
Boolean multiple = callMethodOfAnnotation(annotation, "multiple");
Boolean metatype = callMethodOfAnnotation(annotation, "metatype");
String label = callMethodOfAnnotation(annotation, "label");
String description = callMethodOfAnnotation(annotation, "description");
Object defaultValueArray = callMethodOfAnnotation(annotation, "defaultValue");
V[] convertedDefaultValues = convertPrimitiveArray(defaultValueArray, builder.getValueType());
builder.withDynamic(dynamic)
.withOptional(optional)
.withMultiple(multiple)
.withMetatype(metatype)
.withLabel(makeStringNullIfEmpty(label))
.withDescription(makeStringNullIfEmpty(description))
.withDefaultValue(convertedDefaultValues);
}
private <V, B extends PropertyAttributeMetadataBuilder<V, B>> void fillPropertyAttributeBuilder(
Member member,
Annotation annotation,
PropertyAttributeMetadataBuilder<V, B> builder) {
String attributeId = callMethodOfAnnotation(annotation, "attributeId");
attributeId = makeStringNullIfEmpty(attributeId);
if (attributeId == null && member != null) {
String memberName = member.getName();
if (member instanceof Field) {
attributeId = memberName;
} else if (member instanceof Method) {
attributeId = resolveIdIfMethodNameStartsWith(memberName, "set");
}
}
builder.withAttributeId(attributeId);
fillAttributeMetaBuilder(member, annotation, builder);
String setter = callMethodOfAnnotation(annotation, "setter");
setter = makeStringNullIfEmpty(setter);
if (setter != null) {
builder.withSetter(new MethodDescriptor(setter));
} else if (member != null) {
if (member instanceof Method) {
builder.withSetter(new MethodDescriptor((Method) member));
} else if (member instanceof Field) {
String fieldName = member.getName();
String setterName = "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
MethodDescriptor methodDescriptor = resolveSetter(annotation, builder, setterName);
if (methodDescriptor != null) {
builder.withSetter(methodDescriptor);
}
}
}
}
private <B extends ReferenceMetadataBuilder<B>> void fillReferenceBuilder(Member member,
Annotation annotation, ReferenceMetadataBuilder<B> builder) {
fillAttributeMetaBuilder(member, annotation, builder);
org.everit.osgi.ecm.annotation.ReferenceConfigurationType configurationType = callMethodOfAnnotation(
annotation, "configurationType");
ReferenceConfigurationType convertedConfigurationType = convertReferenceConfigurationType(configurationType);
String referenceId = deriveReferenceId(member, annotation);
if (referenceId == null) {
throw new MetadataValidationException(
"Reference id for one of the references could not be determined in class " + clazz.getName());
}
String bindName = makeStringNullIfEmpty((String) callMethodOfAnnotation(annotation, "bind"));
if (bindName != null) {
builder.withBind(new MethodDescriptor(bindName));
} else if (member instanceof Method) {
builder.withBind(new MethodDescriptor((Method) member));
}
String unbindName = makeStringNullIfEmpty((String) callMethodOfAnnotation(annotation, "unbind"));
if (unbindName != null) {
builder.withUnbind(new MethodDescriptor(unbindName));
}
builder.withReferenceId(referenceId)
.withAttributeId(makeStringNullIfEmpty((String) callMethodOfAnnotation(annotation, "attributeId")))
.withReferenceConfigurationType(convertedConfigurationType);
}
private <V, B extends SelectablePropertyAttributeMetadataBuilder<V, B>> void fillSelectablePropertyAttributeBuilder(
Member member, Annotation annotation,
SelectablePropertyAttributeMetadataBuilder<V, B> builder) {
fillPropertyAttributeBuilder(member, annotation, builder);
Object optionAnnotationArray = callMethodOfAnnotation(annotation, "options");
int length = Array.getLength(optionAnnotationArray);
if (length == 0) {
builder.withOptions(null);
return;
}
Map<V, String> options = new LinkedHashMap<V, String>();
for (int i = 0; i < length; i++) {
Annotation optionAnnotation = (Annotation) Array.get(optionAnnotationArray, i);
String label = callMethodOfAnnotation(optionAnnotation, "label");
V value = callMethodOfAnnotation(optionAnnotation, "value");
label = makeStringNullIfEmpty(label);
if (label == null) {
label = value.toString();
}
options.put(value, label);
}
builder.withOptions(options);
}
private MethodDescriptor findMethodWithAnnotation(Class<? extends Annotation> annotationClass) {
Method foundMethod = null;
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
Annotation annotation = method.getAnnotation(annotationClass);
if (annotation != null) {
if (foundMethod != null) {
throw new InconsistentAnnotationException("The '" + annotationClass.getName()
+ "' annotation is attached to more than one method in class '" + clazz.getName() + "'.");
}
foundMethod = method;
}
}
if (foundMethod != null) {
return new MethodDescriptor(foundMethod);
} else {
return null;
}
}
private void generateAttributeMetaForAnnotatedElements(AnnotatedElement[] annotatedElements) {
for (AnnotatedElement annotatedElement : annotatedElements) {
Annotation[] annotations = annotatedElement.getAnnotations();
for (Annotation annotation : annotations) {
if (annotatedElement instanceof Member) {
processAttributeHolderAnnotation((Member) annotatedElement, annotation);
} else {
processAttributeHolderAnnotation(null, annotation);
}
}
}
}
private void generateMetaForAttributeHolders() {
generateAttributeMetaForAnnotatedElements(new AnnotatedElement[] { clazz });
generateAttributeMetaForAnnotatedElements(clazz.getDeclaredFields());
generateAttributeMetaForAnnotatedElements(clazz.getDeclaredMethods());
}
private String makeStringNullIfEmpty(String text) {
if (text == null) {
return null;
}
if (text.trim().equals("")) {
return null;
}
return text;
}
private void orderedAttributes() {
AttributeOrder attributeOrder = clazz.getAnnotation(AttributeOrder.class);
if (attributeOrder == null) {
return;
}
String[] orderArray = attributeOrder.value();
if (orderArray.length == 0) {
return;
}
LinkedHashMap<String, AttributeMetadata<?>> orderedAttributes =
new LinkedHashMap<String, AttributeMetadata<?>>();
for (String attributeId : orderArray) {
AttributeMetadata<?> attributeMetadata = attributes.remove(attributeId);
if (attributeMetadata == null) {
throw new InconsistentAnnotationException("Attribute with id '" + attributeId
+ "' that is defined in AttributeOrder on the class '" + clazz.getName() + "' does not exist.");
}
orderedAttributes.put(attributeId, attributeMetadata);
}
Set<Entry<String, AttributeMetadata<?>>> attributeEntries = attributes.entrySet();
for (Entry<String, AttributeMetadata<?>> attributeEntry : attributeEntries) {
orderedAttributes.put(attributeEntry.getKey(), attributeEntry.getValue());
}
this.attributes = orderedAttributes;
}
private void processAnnotationContainer(Annotation annotationContainer) {
try {
Method method = annotationContainer.annotationType().getMethod("value");
Annotation[] annotations = (Annotation[]) method.invoke(annotationContainer);
for (Annotation annotation : annotations) {
processAttributeHolderAnnotation(null, annotation);
}
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
throw new RuntimeException(e);
}
}
private void processAttributeHolderAnnotation(Member element, Annotation annotation) {
Class<? extends Annotation> annotationType = annotation.annotationType();
if (ANNOTATION_CONTAINER_TYPES.contains(annotationType)) {
processAnnotationContainer(annotation);
} else if (annotationType.equals(ServiceReference.class)) {
processServiceReferenceAnnotation(element, (ServiceReference) annotation);
} else if (annotationType.equals(BundleCapabilityReference.class)) {
processBundleCapabilityReferenceAnnotation(element, (BundleCapabilityReference) annotation);
} else if (annotationType.equals(BooleanAttribute.class)) {
processBooleanAttributeAnnotation(element, annotation);
} else if (annotationType.equals(ByteAttribute.class)) {
processByteAttributeAnnotation(element, annotation);
} else if (annotationType.equals(CharacterAttribute.class)) {
processCharacterAttributeAnnotation(element, annotation);
} else if (annotationType.equals(DoubleAttribute.class)) {
processDoubleAttributeAnnotation(element, annotation);
} else if (annotationType.equals(FloatAttribute.class)) {
processFloatAttributeAnnotation(element, annotation);
} else if (annotationType.equals(IntegerAttribute.class)) {
processIntegerAttributeAnnotation(element, annotation);
} else if (annotationType.equals(LongAttribute.class)) {
processLongAttributeAnnotation(element, annotation);
} else if (annotationType.equals(PasswordAttribute.class)) {
processPasswordAttributeAnnotation(element, annotation);
} else if (annotationType.equals(ShortAttribute.class)) {
processShortAttributeAnnotation(element, annotation);
} else if (annotationType.equals(StringAttribute.class)) {
processStringAttributeAnnotation(element, annotation);
}
}
private void processBooleanAttributeAnnotation(Member element, Annotation annotation) {
BooleanAttributeMetadataBuilder builder = new BooleanAttributeMetadataBuilder();
fillPropertyAttributeBuilder(element, annotation, builder);
putIntoAttributes(builder);
}
private void processBundleCapabilityReferenceAnnotation(Member member, BundleCapabilityReference annotation) {
BundleCapabilityReferenceMetadataBuilder builder = new BundleCapabilityReferenceMetadataBuilder();
fillReferenceBuilder(member, annotation, builder);
builder.withNamespace(annotation.namespace());
putIntoAttributes(builder);
}
private void processByteAttributeAnnotation(Member element, Annotation annotation) {
ByteAttributeMetadataBuilder builder = new ByteAttributeMetadataBuilder();
fillSelectablePropertyAttributeBuilder(element, annotation, builder);
putIntoAttributes(builder);
}
private void processCharacterAttributeAnnotation(Member element, Annotation annotation) {
CharacterAttributeMetadataBuilder builder = new CharacterAttributeMetadataBuilder();
fillSelectablePropertyAttributeBuilder(element, annotation, builder);
putIntoAttributes(builder);
}
private void processDoubleAttributeAnnotation(Member element, Annotation annotation) {
DoubleAttributeMetadataBuilder builder = new DoubleAttributeMetadataBuilder();
fillSelectablePropertyAttributeBuilder(element, annotation, builder);
putIntoAttributes(builder);
}
private void processFloatAttributeAnnotation(Member element, Annotation annotation) {
FloatAttributeMetadataBuilder builder = new FloatAttributeMetadataBuilder();
fillSelectablePropertyAttributeBuilder(element, annotation, builder);
putIntoAttributes(builder);
}
private void processIntegerAttributeAnnotation(Member element, Annotation annotation) {
IntegerAttributeMetadataBuilder builder = new IntegerAttributeMetadataBuilder();
fillSelectablePropertyAttributeBuilder(element, annotation, builder);
putIntoAttributes(builder);
}
private void processLongAttributeAnnotation(Member element, Annotation annotation) {
LongAttributeMetadataBuilder builder = new LongAttributeMetadataBuilder();
fillSelectablePropertyAttributeBuilder(element, annotation, builder);
putIntoAttributes(builder);
}
private void processPasswordAttributeAnnotation(Member element, Annotation annotation) {
PasswordAttributeMetadataBuilder builder = new PasswordAttributeMetadataBuilder();
fillPropertyAttributeBuilder(element, annotation, builder);
putIntoAttributes(builder);
}
private void processServiceReferenceAnnotation(Member member, ServiceReference annotation) {
ServiceReferenceMetadataBuilder builder = new ServiceReferenceMetadataBuilder();
fillReferenceBuilder(member, annotation, builder);
builder.withServiceInterface(deriveServiceInterface(member, annotation));
putIntoAttributes(builder);
}
private void processShortAttributeAnnotation(Member element, Annotation annotation) {
ShortAttributeMetadataBuilder builder = new ShortAttributeMetadataBuilder();
fillSelectablePropertyAttributeBuilder(element, annotation, builder);
putIntoAttributes(builder);
}
private void processStringAttributeAnnotation(Member element, Annotation annotation) {
StringAttributeMetadataBuilder builder = new StringAttributeMetadataBuilder();
fillSelectablePropertyAttributeBuilder(element, annotation, builder);
Boolean multiLine = callMethodOfAnnotation(annotation, "multiLine");
builder.withMultiLine(multiLine);
putIntoAttributes(builder);
}
private void putIntoAttributes(AttributeMetadataBuilder<?, ?> builder) {
AttributeMetadata<?> attributeMetadata = builder.build();
AttributeMetadata<?> existing = attributes.put(attributeMetadata.getAttributeId(), builder.build());
if (existing != null) {
throw new MetadataValidationException("Duplicate attribute id '" + attributeMetadata.getAttributeId()
+ "' found in class '" + clazz.getName() + "'.");
}
}
private String resolveIdIfMethodNameStartsWith(String memberName, String prefix) {
int prefixLength = prefix.length();
if (memberName.startsWith(prefix) && memberName.length() > prefixLength) {
return memberName.substring(prefixLength, prefixLength + 1).toLowerCase()
+ memberName.substring(prefixLength + 1);
} else {
return null;
}
}
private <V, B extends PropertyAttributeMetadataBuilder<V, B>> MethodDescriptor resolveSetter(
Annotation annotation, PropertyAttributeMetadataBuilder<V, B> builder, String setterName) {
List<MethodDescriptor> potentialDescriptors = new ArrayList<MethodDescriptor>();
Class<?> primitiveType = builder.getPrimitiveType();
Boolean multiple = callMethodOfAnnotation(annotation, "multiple");
if (multiple) {
Class<?> multipleType = primitiveType;
if (primitiveType == null) {
multipleType = builder.getValueType();
}
String parameterTypeName = multipleType.getCanonicalName() + "[]";
potentialDescriptors.add(new MethodDescriptor(setterName, new String[] { parameterTypeName }));
} else {
if (primitiveType != null) {
potentialDescriptors.add(new MethodDescriptor(setterName,
new String[] { primitiveType.getSimpleName() }));
}
potentialDescriptors.add(new MethodDescriptor(setterName, new String[] { builder.getValueType()
.getCanonicalName() }));
}
Method method = MethodUtil.locateMethodByPreference(clazz, false,
potentialDescriptors.toArray(new MethodDescriptor[potentialDescriptors.size()]));
if (method == null) {
return null;
}
return new MethodDescriptor(method);
}
}
|
src/main/java/org/everit/osgi/ecm/annotation/metadatabuilder/MetadataBuilder.java
|
/**
* This file is part of Everit - Component Annotations Metadata Builder.
*
* Everit - Component Annotations Metadata Builder is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Everit - Component Annotations Metadata Builder 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 Everit - Component Annotations Metadata Builder. If not, see <http://www.gnu.org/licenses/>.
*/
package org.everit.osgi.ecm.annotation.metadatabuilder;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.everit.osgi.ecm.annotation.Activate;
import org.everit.osgi.ecm.annotation.AttributeOrder;
import org.everit.osgi.ecm.annotation.AutoDetect;
import org.everit.osgi.ecm.annotation.BundleCapabilityReference;
import org.everit.osgi.ecm.annotation.BundleCapabilityReferences;
import org.everit.osgi.ecm.annotation.Component;
import org.everit.osgi.ecm.annotation.Deactivate;
import org.everit.osgi.ecm.annotation.ServiceReference;
import org.everit.osgi.ecm.annotation.ServiceReferences;
import org.everit.osgi.ecm.annotation.Update;
import org.everit.osgi.ecm.annotation.attribute.BooleanAttribute;
import org.everit.osgi.ecm.annotation.attribute.BooleanAttributes;
import org.everit.osgi.ecm.annotation.attribute.ByteAttribute;
import org.everit.osgi.ecm.annotation.attribute.ByteAttributes;
import org.everit.osgi.ecm.annotation.attribute.CharacterAttribute;
import org.everit.osgi.ecm.annotation.attribute.CharacterAttributes;
import org.everit.osgi.ecm.annotation.attribute.DoubleAttribute;
import org.everit.osgi.ecm.annotation.attribute.DoubleAttributes;
import org.everit.osgi.ecm.annotation.attribute.FloatAttribute;
import org.everit.osgi.ecm.annotation.attribute.FloatAttributes;
import org.everit.osgi.ecm.annotation.attribute.IntegerAttribute;
import org.everit.osgi.ecm.annotation.attribute.IntegerAttributes;
import org.everit.osgi.ecm.annotation.attribute.LongAttribute;
import org.everit.osgi.ecm.annotation.attribute.LongAttributes;
import org.everit.osgi.ecm.annotation.attribute.PasswordAttribute;
import org.everit.osgi.ecm.annotation.attribute.PasswordAttributes;
import org.everit.osgi.ecm.annotation.attribute.ShortAttribute;
import org.everit.osgi.ecm.annotation.attribute.ShortAttributes;
import org.everit.osgi.ecm.annotation.attribute.StringAttribute;
import org.everit.osgi.ecm.annotation.attribute.StringAttributes;
import org.everit.osgi.ecm.metadata.AttributeMetadata;
import org.everit.osgi.ecm.metadata.AttributeMetadata.AttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.BooleanAttributeMetadata.BooleanAttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.BundleCapabilityReferenceMetadata.BundleCapabilityReferenceMetadataBuilder;
import org.everit.osgi.ecm.metadata.ByteAttributeMetadata.ByteAttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.CharacterAttributeMetadata.CharacterAttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.ComponentMetadata;
import org.everit.osgi.ecm.metadata.ComponentMetadata.ComponentMetadataBuilder;
import org.everit.osgi.ecm.metadata.ConfigurationPolicy;
import org.everit.osgi.ecm.metadata.DoubleAttributeMetadata.DoubleAttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.FloatAttributeMetadata.FloatAttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.Icon;
import org.everit.osgi.ecm.metadata.IntegerAttributeMetadata.IntegerAttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.LongAttributeMetadata.LongAttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.MetadataValidationException;
import org.everit.osgi.ecm.metadata.PasswordAttributeMetadata.PasswordAttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.PropertyAttributeMetadata.PropertyAttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.ReferenceConfigurationType;
import org.everit.osgi.ecm.metadata.ReferenceMetadata.ReferenceMetadataBuilder;
import org.everit.osgi.ecm.metadata.SelectablePropertyAttributeMetadata.SelectablePropertyAttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.ServiceReferenceMetadata.ServiceReferenceMetadataBuilder;
import org.everit.osgi.ecm.metadata.ShortAttributeMetadata.ShortAttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.StringAttributeMetadata.StringAttributeMetadataBuilder;
import org.everit.osgi.ecm.util.method.MethodDescriptor;
import org.everit.osgi.ecm.util.method.MethodUtil;
public class MetadataBuilder<C> {
private static final Set<Class<?>> ANNOTATION_CONTAINER_TYPES;
static {
ANNOTATION_CONTAINER_TYPES = new HashSet<Class<?>>();
ANNOTATION_CONTAINER_TYPES.add(ServiceReferences.class);
ANNOTATION_CONTAINER_TYPES.add(BundleCapabilityReferences.class);
ANNOTATION_CONTAINER_TYPES.add(BooleanAttributes.class);
ANNOTATION_CONTAINER_TYPES.add(ByteAttributes.class);
ANNOTATION_CONTAINER_TYPES.add(CharacterAttributes.class);
ANNOTATION_CONTAINER_TYPES.add(DoubleAttributes.class);
ANNOTATION_CONTAINER_TYPES.add(FloatAttributes.class);
ANNOTATION_CONTAINER_TYPES.add(IntegerAttributes.class);
ANNOTATION_CONTAINER_TYPES.add(LongAttributes.class);
ANNOTATION_CONTAINER_TYPES.add(PasswordAttributes.class);
ANNOTATION_CONTAINER_TYPES.add(ShortAttributes.class);
ANNOTATION_CONTAINER_TYPES.add(StringAttributes.class);
}
public static <C> ComponentMetadata buildComponentMetadata(Class<C> clazz) {
MetadataBuilder<C> metadataBuilder = new MetadataBuilder<C>(clazz);
return metadataBuilder.build();
}
private static <O> O[] convertPrimitiveArray(Object primitiveArray, Class<O> targetType) {
int length = Array.getLength(primitiveArray);
if (length == 0) {
return null;
}
@SuppressWarnings("unchecked")
O[] result = (O[]) Array.newInstance(targetType, length);
for (int i = 0; i < length; i++) {
@SuppressWarnings("unchecked")
O element = (O) Array.get(primitiveArray, i);
result[i] = element;
}
return result;
}
private LinkedHashMap<String, AttributeMetadata<?>> attributes =
new LinkedHashMap<String, AttributeMetadata<?>>();
private Class<C> clazz;
private MetadataBuilder() {
}
private MetadataBuilder(Class<C> clazz) {
this.clazz = clazz;
}
private ComponentMetadata build() {
Component componentAnnotation = clazz.getAnnotation(Component.class);
if (componentAnnotation == null) {
throw new ComponentAnnotationMissingException("Component annotation is missing on type " + clazz.toString());
}
ComponentMetadataBuilder componentMetaBuilder = new ComponentMetadataBuilder()
.withComponentId(makeStringNullIfEmpty(componentAnnotation.componentId()))
.withConfigurationPid(makeStringNullIfEmpty(componentAnnotation.configurationPid()))
.withConfigurationPolicy(convertConfigurationPolicy(componentAnnotation.configurationPolicy()))
.withDescription(makeStringNullIfEmpty(componentAnnotation.description()))
.withIcons(convertIcons(componentAnnotation.icons()))
.withMetatype(componentAnnotation.metatype())
.withLabel(makeStringNullIfEmpty(componentAnnotation.label()))
.withLocalizationBase(makeStringNullIfEmpty(componentAnnotation.localizationBase()))
.withType(clazz.getName())
.withActivate(findMethodWithAnnotation(Activate.class))
.withDeactivate(findMethodWithAnnotation(Deactivate.class))
.withUpdate(findMethodWithAnnotation(Update.class));
generateMetaForAttributeHolders();
orderedAttributes();
componentMetaBuilder.withAttributes(attributes.values().toArray(
new AttributeMetadata<?>[0]));
return componentMetaBuilder.build();
}
private <R> R callMethodOfAnnotation(Annotation annotation, String fieldName) {
Class<? extends Annotation> annotationType = annotation.getClass();
Method method;
try {
method = annotationType.getMethod(fieldName);
@SuppressWarnings("unchecked")
R result = (R) method.invoke(annotation);
return result;
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
throw new RuntimeException(e);
}
}
private ConfigurationPolicy convertConfigurationPolicy(
org.everit.osgi.ecm.annotation.ConfigurationPolicy configurationPolicy) {
switch (configurationPolicy) {
case IGNORE:
return ConfigurationPolicy.IGNORE;
case REQUIRE:
return ConfigurationPolicy.REQUIRE;
case FACTORY:
return ConfigurationPolicy.FACTORY;
default:
return ConfigurationPolicy.OPTIONAL;
}
}
private Icon[] convertIcons(org.everit.osgi.ecm.annotation.Icon[] icons) {
if (icons == null) {
return null;
}
Icon[] result = new Icon[icons.length];
for (int i = 0; i < icons.length; i++) {
result[i] = new Icon(icons[i].path(), icons[i].size());
}
return result;
}
private ReferenceConfigurationType convertReferenceConfigurationType(
org.everit.osgi.ecm.annotation.ReferenceConfigurationType attributeType) {
if (attributeType.equals(org.everit.osgi.ecm.annotation.ReferenceConfigurationType.CLAUSE)) {
return ReferenceConfigurationType.CLAUSE;
} else {
return ReferenceConfigurationType.FILTER;
}
}
private String deriveReferenceId(Member member, Annotation annotation) {
String name = callMethodOfAnnotation(annotation, "referenceId");
name = makeStringNullIfEmpty(name);
if (name != null) {
return name;
}
if (member != null && member instanceof Field) {
return member.getName();
}
return null;
}
private Class<?> deriveServiceInterface(Member member, ServiceReference annotation) {
Class<?> referenceInterface = annotation.referenceInterface();
if (!AutoDetect.class.equals(referenceInterface)) {
return referenceInterface;
}
if (member != null && member instanceof Field) {
return ((Field) member).getType();
}
return null;
}
private <V, B extends AttributeMetadataBuilder<V, B>> void fillAttributeMetaBuilder(
Member member,
Annotation annotation,
AttributeMetadataBuilder<V, B> builder) {
Boolean dynamic = callMethodOfAnnotation(annotation, "dynamic");
Boolean optional = callMethodOfAnnotation(annotation, "optional");
Boolean multiple = callMethodOfAnnotation(annotation, "multiple");
Boolean metatype = callMethodOfAnnotation(annotation, "metatype");
String label = callMethodOfAnnotation(annotation, "label");
String description = callMethodOfAnnotation(annotation, "description");
Object defaultValueArray = callMethodOfAnnotation(annotation, "defaultValue");
V[] convertedDefaultValues = convertPrimitiveArray(defaultValueArray, builder.getValueType());
builder.withDynamic(dynamic)
.withOptional(optional)
.withMultiple(multiple)
.withMetatype(metatype)
.withLabel(makeStringNullIfEmpty(label))
.withDescription(makeStringNullIfEmpty(description))
.withDefaultValue(convertedDefaultValues);
}
private <V, B extends PropertyAttributeMetadataBuilder<V, B>> void fillPropertyAttributeBuilder(
Member member,
Annotation annotation,
PropertyAttributeMetadataBuilder<V, B> builder) {
String attributeId = callMethodOfAnnotation(annotation, "attributeId");
attributeId = makeStringNullIfEmpty(attributeId);
if (attributeId == null && member != null) {
String memberName = member.getName();
if (member instanceof Field) {
attributeId = memberName;
} else if (member instanceof Method && memberName.startsWith("set") && memberName.length() > 3) {
attributeId = memberName.substring(3, 4).toLowerCase() + memberName.substring(4);
}
}
fillAttributeMetaBuilder(member, annotation, builder);
String setter = callMethodOfAnnotation(annotation, "setter");
setter = makeStringNullIfEmpty(setter);
if (setter != null) {
builder.withSetter(new MethodDescriptor(setter));
} else if (member != null) {
if (member instanceof Method) {
builder.withSetter(new MethodDescriptor((Method) member));
} else if (member instanceof Field) {
String fieldName = member.getName();
String setterName = "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
MethodDescriptor methodDescriptor = resolveSetter(annotation, builder, setterName);
if (methodDescriptor != null) {
builder.withSetter(methodDescriptor);
}
}
}
}
private <B extends ReferenceMetadataBuilder<B>> void fillReferenceBuilder(Member member,
Annotation annotation, ReferenceMetadataBuilder<B> builder) {
fillAttributeMetaBuilder(member, annotation, builder);
org.everit.osgi.ecm.annotation.ReferenceConfigurationType configurationType = callMethodOfAnnotation(
annotation, "configurationType");
String bindName = makeStringNullIfEmpty((String) callMethodOfAnnotation(annotation, "bind"));
if (bindName != null) {
builder.withBind(new MethodDescriptor(bindName));
} else if (member instanceof Method) {
builder.withBind(new MethodDescriptor((Method) member));
}
String unbindName = makeStringNullIfEmpty((String) callMethodOfAnnotation(annotation, "unbind"));
if (unbindName != null) {
builder.withUnbind(new MethodDescriptor(unbindName));
}
builder.withReferenceId(deriveReferenceId(member, annotation))
.withAttributeId(makeStringNullIfEmpty((String) callMethodOfAnnotation(annotation, "attributeId")))
.withReferenceConfigurationType(convertReferenceConfigurationType(configurationType));
}
private <V, B extends SelectablePropertyAttributeMetadataBuilder<V, B>> void fillSelectablePropertyAttributeBuilder(
Member member, Annotation annotation,
SelectablePropertyAttributeMetadataBuilder<V, B> builder) {
fillPropertyAttributeBuilder(member, annotation, builder);
Object optionAnnotationArray = callMethodOfAnnotation(annotation, "options");
int length = Array.getLength(optionAnnotationArray);
if (length == 0) {
builder.withOptions(null);
return;
}
Map<V, String> options = new LinkedHashMap<V, String>();
for (int i = 0; i < length; i++) {
Annotation optionAnnotation = (Annotation) Array.get(optionAnnotationArray, i);
String label = callMethodOfAnnotation(optionAnnotation, "label");
V value = callMethodOfAnnotation(optionAnnotation, "value");
label = makeStringNullIfEmpty(label);
if (label == null) {
label = value.toString();
}
options.put(value, label);
}
builder.withOptions(options);
}
private MethodDescriptor findMethodWithAnnotation(Class<? extends Annotation> annotationClass) {
Method foundMethod = null;
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
Annotation annotation = method.getAnnotation(annotationClass);
if (annotation != null) {
if (foundMethod != null) {
throw new InconsistentAnnotationException("The '" + annotationClass.getName()
+ "' annotation is attached to more than one method in class '" + clazz.getName() + "'.");
}
foundMethod = method;
}
}
if (foundMethod != null) {
return new MethodDescriptor(foundMethod);
} else {
return null;
}
}
private void generateAttributeMetaForAnnotatedElements(AnnotatedElement[] annotatedElements) {
for (AnnotatedElement annotatedElement : annotatedElements) {
Annotation[] annotations = annotatedElement.getAnnotations();
for (Annotation annotation : annotations) {
if (annotatedElement instanceof Member) {
processAttributeHolderAnnotation((Member) annotatedElement, annotation);
} else {
processAttributeHolderAnnotation(null, annotation);
}
}
}
}
private void generateMetaForAttributeHolders() {
generateAttributeMetaForAnnotatedElements(new AnnotatedElement[] { clazz });
generateAttributeMetaForAnnotatedElements(clazz.getDeclaredFields());
generateAttributeMetaForAnnotatedElements(clazz.getDeclaredMethods());
}
private String makeStringNullIfEmpty(String text) {
if (text == null) {
return null;
}
if (text.trim().equals("")) {
return null;
}
return text;
}
private void orderedAttributes() {
AttributeOrder attributeOrder = clazz.getAnnotation(AttributeOrder.class);
if (attributeOrder == null) {
return;
}
String[] orderArray = attributeOrder.value();
if (orderArray.length == 0) {
return;
}
LinkedHashMap<String, AttributeMetadata<?>> orderedAttributes =
new LinkedHashMap<String, AttributeMetadata<?>>();
for (String attributeId : orderArray) {
AttributeMetadata<?> attributeMetadata = attributes.remove(attributeId);
if (attributeMetadata == null) {
throw new InconsistentAnnotationException("Attribute with id '" + attributeId
+ "' that is defined in AttributeOrder on the class '" + clazz.getName() + "' does not exist.");
}
orderedAttributes.put(attributeId, attributeMetadata);
}
Set<Entry<String, AttributeMetadata<?>>> attributeEntries = attributes.entrySet();
for (Entry<String, AttributeMetadata<?>> attributeEntry : attributeEntries) {
orderedAttributes.put(attributeEntry.getKey(), attributeEntry.getValue());
}
this.attributes = orderedAttributes;
}
private void processAnnotationContainer(Annotation annotationContainer) {
try {
Method method = annotationContainer.annotationType().getMethod("value");
Annotation[] annotations = (Annotation[]) method.invoke(annotationContainer);
for (Annotation annotation : annotations) {
processAttributeHolderAnnotation(null, annotation);
}
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
throw new RuntimeException(e);
}
}
private void processAttributeHolderAnnotation(Member element, Annotation annotation) {
Class<? extends Annotation> annotationType = annotation.annotationType();
if (ANNOTATION_CONTAINER_TYPES.contains(annotationType)) {
processAnnotationContainer(annotation);
} else if (annotationType.equals(ServiceReference.class)) {
processServiceReferenceAnnotation(element, (ServiceReference) annotation);
} else if (annotationType.equals(BundleCapabilityReference.class)) {
processBundleCapabilityReferenceAnnotation(element, (BundleCapabilityReference) annotation);
} else if (annotationType.equals(BooleanAttribute.class)) {
processBooleanAttributeAnnotation(element, annotation);
} else if (annotationType.equals(ByteAttribute.class)) {
processByteAttributeAnnotation(element, annotation);
} else if (annotationType.equals(CharacterAttribute.class)) {
processCharacterAttributeAnnotation(element, annotation);
} else if (annotationType.equals(DoubleAttribute.class)) {
processDoubleAttributeAnnotation(element, annotation);
} else if (annotationType.equals(FloatAttribute.class)) {
processFloatAttributeAnnotation(element, annotation);
} else if (annotationType.equals(IntegerAttribute.class)) {
processIntegerAttributeAnnotation(element, annotation);
} else if (annotationType.equals(LongAttribute.class)) {
processLongAttributeAnnotation(element, annotation);
} else if (annotationType.equals(PasswordAttribute.class)) {
processPasswordAttributeAnnotation(element, annotation);
} else if (annotationType.equals(ShortAttribute.class)) {
processShortAttributeAnnotation(element, annotation);
} else if (annotationType.equals(StringAttribute.class)) {
processStringAttributeAnnotation(element, annotation);
}
}
private void processBooleanAttributeAnnotation(Member element, Annotation annotation) {
BooleanAttributeMetadataBuilder builder = new BooleanAttributeMetadataBuilder();
fillPropertyAttributeBuilder(element, annotation, builder);
putIntoAttributes(builder);
}
private void processBundleCapabilityReferenceAnnotation(Member member, BundleCapabilityReference annotation) {
BundleCapabilityReferenceMetadataBuilder builder = new BundleCapabilityReferenceMetadataBuilder();
fillReferenceBuilder(member, annotation, builder);
builder.withNamespace(annotation.namespace());
putIntoAttributes(builder);
}
private void processByteAttributeAnnotation(Member element, Annotation annotation) {
ByteAttributeMetadataBuilder builder = new ByteAttributeMetadataBuilder();
fillSelectablePropertyAttributeBuilder(element, annotation, builder);
putIntoAttributes(builder);
}
private void processCharacterAttributeAnnotation(Member element, Annotation annotation) {
CharacterAttributeMetadataBuilder builder = new CharacterAttributeMetadataBuilder();
fillSelectablePropertyAttributeBuilder(element, annotation, builder);
putIntoAttributes(builder);
}
private void processDoubleAttributeAnnotation(Member element, Annotation annotation) {
DoubleAttributeMetadataBuilder builder = new DoubleAttributeMetadataBuilder();
fillSelectablePropertyAttributeBuilder(element, annotation, builder);
putIntoAttributes(builder);
}
private void processFloatAttributeAnnotation(Member element, Annotation annotation) {
FloatAttributeMetadataBuilder builder = new FloatAttributeMetadataBuilder();
fillSelectablePropertyAttributeBuilder(element, annotation, builder);
putIntoAttributes(builder);
}
private void processIntegerAttributeAnnotation(Member element, Annotation annotation) {
IntegerAttributeMetadataBuilder builder = new IntegerAttributeMetadataBuilder();
fillSelectablePropertyAttributeBuilder(element, annotation, builder);
putIntoAttributes(builder);
}
private void processLongAttributeAnnotation(Member element, Annotation annotation) {
LongAttributeMetadataBuilder builder = new LongAttributeMetadataBuilder();
fillSelectablePropertyAttributeBuilder(element, annotation, builder);
putIntoAttributes(builder);
}
private void processPasswordAttributeAnnotation(Member element, Annotation annotation) {
PasswordAttributeMetadataBuilder builder = new PasswordAttributeMetadataBuilder();
fillPropertyAttributeBuilder(element, annotation, builder);
putIntoAttributes(builder);
}
private void processServiceReferenceAnnotation(Member member, ServiceReference annotation) {
ServiceReferenceMetadataBuilder builder = new ServiceReferenceMetadataBuilder();
fillReferenceBuilder(member, annotation, builder);
builder.withServiceInterface(deriveServiceInterface(member, annotation));
putIntoAttributes(builder);
}
private void processShortAttributeAnnotation(Member element, Annotation annotation) {
ShortAttributeMetadataBuilder builder = new ShortAttributeMetadataBuilder();
fillSelectablePropertyAttributeBuilder(element, annotation, builder);
putIntoAttributes(builder);
}
private void processStringAttributeAnnotation(Member element, Annotation annotation) {
StringAttributeMetadataBuilder builder = new StringAttributeMetadataBuilder();
fillSelectablePropertyAttributeBuilder(element, annotation, builder);
Boolean multiLine = callMethodOfAnnotation(annotation, "multiLine");
builder.withMultiLine(multiLine);
putIntoAttributes(builder);
}
private void putIntoAttributes(AttributeMetadataBuilder<?, ?> builder) {
AttributeMetadata<?> attributeMetadata = builder.build();
AttributeMetadata<?> existing = attributes.put(attributeMetadata.getAttributeId(), builder.build());
if (existing != null) {
throw new MetadataValidationException("Duplicate attribute id '" + attributeMetadata.getAttributeId()
+ "' found in class '" + clazz.getName() + "'.");
}
}
private <V, B extends PropertyAttributeMetadataBuilder<V, B>> MethodDescriptor resolveSetter(
Annotation annotation, PropertyAttributeMetadataBuilder<V, B> builder, String setterName) {
List<MethodDescriptor> potentialDescriptors = new ArrayList<MethodDescriptor>();
Class<?> primitiveType = builder.getPrimitiveType();
Boolean multiple = callMethodOfAnnotation(annotation, "multiple");
if (multiple) {
Class<?> multipleType = primitiveType;
if (primitiveType == null) {
multipleType = builder.getValueType();
}
String parameterTypeName = multipleType.getCanonicalName() + "[]";
potentialDescriptors.add(new MethodDescriptor(setterName, new String[] { parameterTypeName }));
} else {
if (primitiveType != null) {
potentialDescriptors.add(new MethodDescriptor(setterName,
new String[] { primitiveType.getSimpleName() }));
}
potentialDescriptors.add(new MethodDescriptor(setterName, new String[] { builder.getValueType()
.getCanonicalName() }));
}
Method method = MethodUtil.locateMethodByPreference(clazz, false,
potentialDescriptors.toArray(new MethodDescriptor[potentialDescriptors.size()]));
if (method == null) {
return null;
}
return new MethodDescriptor(method);
}
}
|
Better reference attribute resolution
|
src/main/java/org/everit/osgi/ecm/annotation/metadatabuilder/MetadataBuilder.java
|
Better reference attribute resolution
|
<ide><path>rc/main/java/org/everit/osgi/ecm/annotation/metadatabuilder/MetadataBuilder.java
<ide> return name;
<ide> }
<ide>
<del> if (member != null && member instanceof Field) {
<del> return member.getName();
<add> if (member != null) {
<add> String memberName = member.getName();
<add> if (member instanceof Field) {
<add> return memberName;
<add> } else if (member instanceof Method) {
<add> String referenceId = resolveIdIfMethodNameStartsWith(memberName, "bind");
<add> if (referenceId != null) {
<add> return referenceId;
<add> }
<add> return resolveIdIfMethodNameStartsWith(memberName, "set");
<add> }
<ide> }
<ide>
<ide> return null;
<ide> String memberName = member.getName();
<ide> if (member instanceof Field) {
<ide> attributeId = memberName;
<del> } else if (member instanceof Method && memberName.startsWith("set") && memberName.length() > 3) {
<del> attributeId = memberName.substring(3, 4).toLowerCase() + memberName.substring(4);
<del> }
<del> }
<add> } else if (member instanceof Method) {
<add> attributeId = resolveIdIfMethodNameStartsWith(memberName, "set");
<add> }
<add> }
<add> builder.withAttributeId(attributeId);
<ide>
<ide> fillAttributeMetaBuilder(member, annotation, builder);
<ide>
<ide> org.everit.osgi.ecm.annotation.ReferenceConfigurationType configurationType = callMethodOfAnnotation(
<ide> annotation, "configurationType");
<ide>
<add> ReferenceConfigurationType convertedConfigurationType = convertReferenceConfigurationType(configurationType);
<add>
<add> String referenceId = deriveReferenceId(member, annotation);
<add>
<add> if (referenceId == null) {
<add> throw new MetadataValidationException(
<add> "Reference id for one of the references could not be determined in class " + clazz.getName());
<add> }
<add>
<ide> String bindName = makeStringNullIfEmpty((String) callMethodOfAnnotation(annotation, "bind"));
<ide>
<ide> if (bindName != null) {
<ide> builder.withUnbind(new MethodDescriptor(unbindName));
<ide> }
<ide>
<del> builder.withReferenceId(deriveReferenceId(member, annotation))
<add> builder.withReferenceId(referenceId)
<ide> .withAttributeId(makeStringNullIfEmpty((String) callMethodOfAnnotation(annotation, "attributeId")))
<del> .withReferenceConfigurationType(convertReferenceConfigurationType(configurationType));
<add> .withReferenceConfigurationType(convertedConfigurationType);
<ide> }
<ide>
<ide> private <V, B extends SelectablePropertyAttributeMetadataBuilder<V, B>> void fillSelectablePropertyAttributeBuilder(
<ide> }
<ide> }
<ide>
<add> private String resolveIdIfMethodNameStartsWith(String memberName, String prefix) {
<add> int prefixLength = prefix.length();
<add> if (memberName.startsWith(prefix) && memberName.length() > prefixLength) {
<add> return memberName.substring(prefixLength, prefixLength + 1).toLowerCase()
<add> + memberName.substring(prefixLength + 1);
<add> } else {
<add> return null;
<add> }
<add> }
<add>
<ide> private <V, B extends PropertyAttributeMetadataBuilder<V, B>> MethodDescriptor resolveSetter(
<ide> Annotation annotation, PropertyAttributeMetadataBuilder<V, B> builder, String setterName) {
<ide>
|
|
Java
|
apache-2.0
|
9d004089e4617586de1544a653b0f8ad542b69ac
| 0 |
ChinaQuants/OG-Platform,jeorme/OG-Platform,codeaudit/OG-Platform,jeorme/OG-Platform,ChinaQuants/OG-Platform,DevStreet/FinanceAnalytics,ChinaQuants/OG-Platform,jeorme/OG-Platform,DevStreet/FinanceAnalytics,McLeodMoores/starling,McLeodMoores/starling,codeaudit/OG-Platform,McLeodMoores/starling,ChinaQuants/OG-Platform,nssales/OG-Platform,McLeodMoores/starling,nssales/OG-Platform,jeorme/OG-Platform,jerome79/OG-Platform,DevStreet/FinanceAnalytics,jerome79/OG-Platform,nssales/OG-Platform,nssales/OG-Platform,jerome79/OG-Platform,codeaudit/OG-Platform,codeaudit/OG-Platform,DevStreet/FinanceAnalytics,jerome79/OG-Platform
|
/**
* Copyright (C) 2013 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.web.analytics;
import com.opengamma.financial.security.FinancialSecurityVisitorSameValueAdapter;
import com.opengamma.financial.security.capfloor.CapFloorCMSSpreadSecurity;
import com.opengamma.financial.security.capfloor.CapFloorSecurity;
import com.opengamma.financial.security.cds.CreditDefaultSwapIndexSecurity;
import com.opengamma.financial.security.cds.LegacyFixedRecoveryCDSSecurity;
import com.opengamma.financial.security.cds.LegacyRecoveryLockCDSSecurity;
import com.opengamma.financial.security.cds.LegacyVanillaCDSSecurity;
import com.opengamma.financial.security.cds.StandardFixedRecoveryCDSSecurity;
import com.opengamma.financial.security.cds.StandardRecoveryLockCDSSecurity;
import com.opengamma.financial.security.cds.StandardVanillaCDSSecurity;
import com.opengamma.financial.security.equity.EquityVarianceSwapSecurity;
import com.opengamma.financial.security.fra.FRASecurity;
import com.opengamma.financial.security.fx.FXForwardSecurity;
import com.opengamma.financial.security.option.CreditDefaultSwapOptionSecurity;
import com.opengamma.financial.security.option.FXBarrierOptionSecurity;
import com.opengamma.financial.security.option.FXDigitalOptionSecurity;
import com.opengamma.financial.security.option.FXOptionSecurity;
import com.opengamma.financial.security.option.NonDeliverableFXOptionSecurity;
import com.opengamma.financial.security.option.SwaptionSecurity;
import com.opengamma.financial.security.swap.SwapSecurity;
import com.opengamma.financial.security.swap.YearOnYearInflationSwapSecurity;
import com.opengamma.financial.security.swap.ZeroCouponInflationSwapSecurity;
/**
* Visits a security and returns true if it's an OTC security type.
*/
public class OtcSecurityVisitor extends FinancialSecurityVisitorSameValueAdapter<Boolean> {
/**
* Creates a new instance.
*/
public OtcSecurityVisitor() {
super(false);
}
@Override
public Boolean visitSwapSecurity(SwapSecurity security) {
return true;
}
@Override
public Boolean visitSwaptionSecurity(SwaptionSecurity security) {
return true;
}
@Override
public Boolean visitCapFloorCMSSpreadSecurity(CapFloorCMSSpreadSecurity security) {
return true;
}
@Override
public Boolean visitNonDeliverableFXOptionSecurity(NonDeliverableFXOptionSecurity security) {
return true;
}
@Override
public Boolean visitFRASecurity(FRASecurity security) {
return true;
}
@Override
public Boolean visitCapFloorSecurity(CapFloorSecurity security) {
return true;
}
@Override
public Boolean visitEquityVarianceSwapSecurity(EquityVarianceSwapSecurity security) {
return true;
}
@Override
public Boolean visitFXBarrierOptionSecurity(FXBarrierOptionSecurity security) {
return true;
}
@Override
public Boolean visitFXOptionSecurity(FXOptionSecurity security) {
return true;
}
@Override
public Boolean visitFXDigitalOptionSecurity(FXDigitalOptionSecurity security) {
return true;
}
@Override
public Boolean visitFXForwardSecurity(FXForwardSecurity security) {
return true;
}
@Override
public Boolean visitLegacyVanillaCDSSecurity(LegacyVanillaCDSSecurity security) {
return true;
}
@Override
public Boolean visitLegacyRecoveryLockCDSSecurity(LegacyRecoveryLockCDSSecurity security) {
return true;
}
@Override
public Boolean visitLegacyFixedRecoveryCDSSecurity(LegacyFixedRecoveryCDSSecurity security) {
return true;
}
@Override
public Boolean visitStandardVanillaCDSSecurity(StandardVanillaCDSSecurity security) {
return true;
}
@Override
public Boolean visitStandardRecoveryLockCDSSecurity(StandardRecoveryLockCDSSecurity security) {
return true;
}
@Override
public Boolean visitStandardFixedRecoveryCDSSecurity(StandardFixedRecoveryCDSSecurity security) {
return true;
}
@Override
public Boolean visitCreditDefaultSwapIndexSecurity(CreditDefaultSwapIndexSecurity security) {
return true;
}
@Override
public Boolean visitCreditDefaultSwapOptionSecurity(CreditDefaultSwapOptionSecurity security) {
return true;
}
@Override
public Boolean visitZeroCouponInflationSwapSecurity(ZeroCouponInflationSwapSecurity security) {
return true;
}
@Override
public Boolean visitYearOnYearInflationSwapSecurity(YearOnYearInflationSwapSecurity security) {
return true;
}
}
|
projects/OG-Web/src/main/java/com/opengamma/web/analytics/OtcSecurityVisitor.java
|
/**
* Copyright (C) 2013 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.web.analytics;
import com.opengamma.financial.security.FinancialSecurityVisitorSameValueAdapter;
import com.opengamma.financial.security.capfloor.CapFloorCMSSpreadSecurity;
import com.opengamma.financial.security.capfloor.CapFloorSecurity;
import com.opengamma.financial.security.cds.CreditDefaultSwapIndexSecurity;
import com.opengamma.financial.security.cds.LegacyFixedRecoveryCDSSecurity;
import com.opengamma.financial.security.cds.LegacyRecoveryLockCDSSecurity;
import com.opengamma.financial.security.cds.LegacyVanillaCDSSecurity;
import com.opengamma.financial.security.cds.StandardFixedRecoveryCDSSecurity;
import com.opengamma.financial.security.cds.StandardRecoveryLockCDSSecurity;
import com.opengamma.financial.security.cds.StandardVanillaCDSSecurity;
import com.opengamma.financial.security.equity.EquityVarianceSwapSecurity;
import com.opengamma.financial.security.fra.FRASecurity;
import com.opengamma.financial.security.fx.FXForwardSecurity;
import com.opengamma.financial.security.option.CreditDefaultSwapOptionSecurity;
import com.opengamma.financial.security.option.FXBarrierOptionSecurity;
import com.opengamma.financial.security.option.FXOptionSecurity;
import com.opengamma.financial.security.option.NonDeliverableFXOptionSecurity;
import com.opengamma.financial.security.option.SwaptionSecurity;
import com.opengamma.financial.security.swap.SwapSecurity;
import com.opengamma.financial.security.swap.YearOnYearInflationSwapSecurity;
import com.opengamma.financial.security.swap.ZeroCouponInflationSwapSecurity;
/**
* Visits a security and returns true if it's an OTC security type.
*/
public class OtcSecurityVisitor extends FinancialSecurityVisitorSameValueAdapter<Boolean> {
/**
* Creates a new instance.
*/
public OtcSecurityVisitor() {
super(false);
}
@Override
public Boolean visitSwapSecurity(SwapSecurity security) {
return true;
}
@Override
public Boolean visitSwaptionSecurity(SwaptionSecurity security) {
return true;
}
@Override
public Boolean visitCapFloorCMSSpreadSecurity(CapFloorCMSSpreadSecurity security) {
return true;
}
@Override
public Boolean visitNonDeliverableFXOptionSecurity(NonDeliverableFXOptionSecurity security) {
return true;
}
@Override
public Boolean visitFRASecurity(FRASecurity security) {
return true;
}
@Override
public Boolean visitCapFloorSecurity(CapFloorSecurity security) {
return true;
}
@Override
public Boolean visitEquityVarianceSwapSecurity(EquityVarianceSwapSecurity security) {
return true;
}
@Override
public Boolean visitFXBarrierOptionSecurity(FXBarrierOptionSecurity security) {
return true;
}
@Override
public Boolean visitFXOptionSecurity(FXOptionSecurity security) {
return true;
}
@Override
public Boolean visitFXForwardSecurity(FXForwardSecurity security) {
return true;
}
@Override
public Boolean visitLegacyVanillaCDSSecurity(LegacyVanillaCDSSecurity security) {
return true;
}
@Override
public Boolean visitLegacyRecoveryLockCDSSecurity(LegacyRecoveryLockCDSSecurity security) {
return true;
}
@Override
public Boolean visitLegacyFixedRecoveryCDSSecurity(LegacyFixedRecoveryCDSSecurity security) {
return true;
}
@Override
public Boolean visitStandardVanillaCDSSecurity(StandardVanillaCDSSecurity security) {
return true;
}
@Override
public Boolean visitStandardRecoveryLockCDSSecurity(StandardRecoveryLockCDSSecurity security) {
return true;
}
@Override
public Boolean visitStandardFixedRecoveryCDSSecurity(StandardFixedRecoveryCDSSecurity security) {
return true;
}
@Override
public Boolean visitCreditDefaultSwapIndexSecurity(CreditDefaultSwapIndexSecurity security) {
return true;
}
@Override
public Boolean visitCreditDefaultSwapOptionSecurity(CreditDefaultSwapOptionSecurity security) {
return true;
}
@Override
public Boolean visitZeroCouponInflationSwapSecurity(ZeroCouponInflationSwapSecurity security) {
return true;
}
@Override
public Boolean visitYearOnYearInflationSwapSecurity(YearOnYearInflationSwapSecurity security) {
return true;
}
}
|
[PLAT-4681] added FXDigitalOptionSecurity to OtcSecurityVisitor
|
projects/OG-Web/src/main/java/com/opengamma/web/analytics/OtcSecurityVisitor.java
|
[PLAT-4681] added FXDigitalOptionSecurity to OtcSecurityVisitor
|
<ide><path>rojects/OG-Web/src/main/java/com/opengamma/web/analytics/OtcSecurityVisitor.java
<ide> import com.opengamma.financial.security.fx.FXForwardSecurity;
<ide> import com.opengamma.financial.security.option.CreditDefaultSwapOptionSecurity;
<ide> import com.opengamma.financial.security.option.FXBarrierOptionSecurity;
<add>import com.opengamma.financial.security.option.FXDigitalOptionSecurity;
<ide> import com.opengamma.financial.security.option.FXOptionSecurity;
<ide> import com.opengamma.financial.security.option.NonDeliverableFXOptionSecurity;
<ide> import com.opengamma.financial.security.option.SwaptionSecurity;
<ide> }
<ide>
<ide> @Override
<add> public Boolean visitFXDigitalOptionSecurity(FXDigitalOptionSecurity security) {
<add> return true;
<add> }
<add>
<add> @Override
<ide> public Boolean visitFXForwardSecurity(FXForwardSecurity security) {
<ide> return true;
<ide> }
|
|
Java
|
apache-2.0
|
5554f5e6f79a014ee5647d10c9c4780b60487a18
| 0 |
smartloli/kafka-eagle,smartloli/kafka-eagle,smartloli/kafka-eagle
|
/**
* 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.smartloli.kafka.eagle.core.factory.v2;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import org.apache.kafka.clients.CommonClientConfigs;
import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.NewPartitions;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smartloli.kafka.eagle.common.protocol.MetadataInfo;
import org.smartloli.kafka.eagle.common.protocol.PartitionsInfo;
import org.smartloli.kafka.eagle.common.util.CalendarUtils;
import org.smartloli.kafka.eagle.common.util.KConstants.Kafka;
import org.smartloli.kafka.eagle.common.util.KafkaZKPoolUtils;
import org.smartloli.kafka.eagle.common.util.MathUtils;
import org.smartloli.kafka.eagle.common.util.SystemConfigUtils;
import org.smartloli.kafka.eagle.core.factory.KafkaFactory;
import org.smartloli.kafka.eagle.core.factory.KafkaService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.google.common.base.Strings;
import kafka.zk.KafkaZkClient;
import scala.Option;
import scala.Tuple2;
import scala.collection.JavaConversions;
import scala.collection.Seq;
/**
* Implements {@link BrokerService} all method.
*
* @author smartloli.
*
* Created by Jun 13, 2019
*/
public class BrokerServiceImpl implements BrokerService {
private final String BROKER_IDS_PATH = "/brokers/ids";
private final String BROKER_TOPICS_PATH = "/brokers/topics";
private final String TOPIC_ISR = "/brokers/topics/%s/partitions/%s/state";
private final Logger LOG = LoggerFactory.getLogger(BrokerServiceImpl.class);
/** Instance Kafka Zookeeper client pool. */
private KafkaZKPoolUtils kafkaZKPool = KafkaZKPoolUtils.getInstance();
/** Kafka service interface. */
private KafkaService kafkaService = new KafkaFactory().create();
/** Statistics topic total used as page. */
public long topicNumbers(String clusterAlias) {
return topicList(clusterAlias).size();
}
/** Exclude kafka topic(__consumer_offsets). */
private void excludeTopic(List<String> topics) {
if (topics.contains(Kafka.CONSUMER_OFFSET_TOPIC)) {
topics.remove(Kafka.CONSUMER_OFFSET_TOPIC);
}
}
/** Get search topic list numbers. */
public long topicNumbers(String clusterAlias, String topic) {
long count = 0L;
List<String> topics = topicList(clusterAlias);
for (String name : topics) {
if (topic != null && name.contains(topic)) {
count++;
}
}
return count;
}
/** Statistics topic partitions total used as page. */
public long partitionNumbers(String clusterAlias, String topic) {
long count = 0L;
if (Kafka.CONSUMER_OFFSET_TOPIC.equals(topic)) {
return count;
}
KafkaZkClient zkc = kafkaZKPool.getZkClient(clusterAlias);
try {
if (zkc.pathExists(BROKER_TOPICS_PATH + "/" + topic + "/partitions")) {
Seq<String> subBrokerTopicsPaths = zkc.getChildren(BROKER_TOPICS_PATH + "/" + topic + "/partitions");
count = JavaConversions.seqAsJavaList(subBrokerTopicsPaths).size();
}
} catch (Exception e) {
LOG.error("Get topic partition numbers has error, msg is " + e.getCause().getMessage());
e.printStackTrace();
}
if (zkc != null) {
kafkaZKPool.release(clusterAlias, zkc);
zkc = null;
}
return count;
}
/** Get the number of page records for topic. */
public List<PartitionsInfo> topicRecords(String clusterAlias, Map<String, Object> params) {
KafkaZkClient zkc = kafkaZKPool.getZkClient(clusterAlias);
List<PartitionsInfo> targets = new ArrayList<PartitionsInfo>();
List<String> topics = topicList(clusterAlias);
try {
int start = Integer.parseInt(params.get("start").toString());
int length = Integer.parseInt(params.get("length").toString());
if (params.containsKey("search") && params.get("search").toString().length() > 0) {
String search = params.get("search").toString();
int offset = 0;
int id = start + 1;
for (String topic : topics) {
if (search != null && topic.contains(search)) {
if (offset < (start + length) && offset >= start) {
try {
if (zkc.pathExists(BROKER_TOPICS_PATH + "/" + topic)) {
Tuple2<Option<byte[]>, Stat> tuple = zkc.getDataAndStat(BROKER_TOPICS_PATH + "/" + topic);
PartitionsInfo partition = new PartitionsInfo();
partition.setId(id++);
partition.setCreated(CalendarUtils.convertUnixTime2Date(tuple._2.getCtime()));
partition.setModify(CalendarUtils.convertUnixTime2Date(tuple._2.getMtime()));
partition.setTopic(topic);
String tupleString = new String(tuple._1.get());
JSONObject partitionObject = JSON.parseObject(tupleString).getJSONObject("partitions");
partition.setPartitionNumbers(partitionObject.size());
partition.setPartitions(partitionObject.keySet());
getBrokerSpreadByTopic(clusterAlias, topic, partition);
getBrokerSkewedByTopic(clusterAlias, topic, partition);
getBrokerSkewedLeaderByTopic(clusterAlias, topic, partition);
targets.add(partition);
}
} catch (Exception ex) {
ex.printStackTrace();
LOG.error("Scan topic search from zookeeper has error, msg is " + ex.getMessage());
}
}
offset++;
}
}
} else {
int offset = 0;
int id = start + 1;
for (String topic : topics) {
if (offset < (start + length) && offset >= start) {
try {
if (zkc.pathExists(BROKER_TOPICS_PATH + "/" + topic)) {
Tuple2<Option<byte[]>, Stat> tuple = zkc.getDataAndStat(BROKER_TOPICS_PATH + "/" + topic);
PartitionsInfo partition = new PartitionsInfo();
partition.setId(id++);
partition.setCreated(CalendarUtils.convertUnixTime2Date(tuple._2.getCtime()));
partition.setModify(CalendarUtils.convertUnixTime2Date(tuple._2.getMtime()));
partition.setTopic(topic);
String tupleString = new String(tuple._1.get());
JSONObject partitionObject = JSON.parseObject(tupleString).getJSONObject("partitions");
partition.setPartitionNumbers(partitionObject.size());
partition.setPartitions(partitionObject.keySet());
getBrokerSpreadByTopic(clusterAlias, topic, partition);
getBrokerSkewedByTopic(clusterAlias, topic, partition);
getBrokerSkewedLeaderByTopic(clusterAlias, topic, partition);
targets.add(partition);
}
} catch (Exception ex) {
ex.printStackTrace();
LOG.error("Scan topic page from zookeeper has error, msg is " + ex.getMessage());
}
}
offset++;
}
}
} catch (Exception e) {
LOG.error("Get topic records has error, msg is " + e.getCause().getMessage());
e.printStackTrace();
}
if (zkc != null) {
kafkaZKPool.release(clusterAlias, zkc);
zkc = null;
}
return targets;
}
/** Get broker spread by topic. */
private void getBrokerSpreadByTopic(String clusterAlias, String topic, PartitionsInfo partition) {
try {
List<MetadataInfo> topicMetas = topicMetadata(clusterAlias, topic);
Set<Integer> brokerLeaders = new HashSet<>();
Set<Integer> brokerSizes = new HashSet<>();
for (MetadataInfo meta : topicMetas) {
brokerLeaders.add(meta.getLeader());
List<Integer> replicasIntegers = new ArrayList<>();
try {
replicasIntegers = JSON.parseObject(meta.getReplicas(), new TypeReference<ArrayList<Integer>>() {
});
} catch (Exception e) {
e.printStackTrace();
LOG.error("Parse string to int list has error, msg is " + e.getCause().getMessage());
}
brokerSizes.addAll(replicasIntegers);
}
int brokerSize = brokerSizes.size();
partition.setBrokersSpread(String.format("%.2f", (brokerLeaders.size() * 100.0 / brokerSize)));
} catch (Exception e) {
e.printStackTrace();
LOG.error("Get topic skewed info has error, msg is ", e);
}
}
/** Get broker skewed by topic. */
private void getBrokerSkewedByTopic(String clusterAlias, String topic, PartitionsInfo partition) {
try {
List<MetadataInfo> topicMetas = topicMetadata(clusterAlias, topic);
int partitionAndReplicaTopics = 0;
Set<Integer> brokerSizes = new HashSet<>();
Map<Integer, Integer> brokers = new HashMap<>();
for (MetadataInfo meta : topicMetas) {
List<Integer> replicasIntegers = new ArrayList<>();
try {
replicasIntegers = JSON.parseObject(meta.getReplicas(), new TypeReference<ArrayList<Integer>>() {
});
} catch (Exception e) {
e.printStackTrace();
LOG.error("Parse string to int list has error, msg is " + e.getCause().getMessage());
}
brokerSizes.addAll(replicasIntegers);
partitionAndReplicaTopics += replicasIntegers.size();
for (Integer brokerId : replicasIntegers) {
if (brokers.containsKey(brokerId)) {
int value = brokers.get(brokerId);
brokers.put(brokerId, value + 1);
} else {
brokers.put(brokerId, 1);
}
}
}
int brokerSize = brokerSizes.size();
int normalSkewedValue = MathUtils.ceil(brokerSize, partitionAndReplicaTopics);
int brokerSkewSize = 0;
for (Entry<Integer, Integer> entry : brokers.entrySet()) {
if (entry.getValue() > normalSkewedValue) {
brokerSkewSize++;
}
}
partition.setBrokersSkewed(String.format("%.2f", (brokerSkewSize * 100.0 / brokerSize)));
} catch (Exception e) {
e.printStackTrace();
LOG.error("Get topic skewed info has error, msg is ", e);
}
}
/** Get broker skewed leader by topic. */
private void getBrokerSkewedLeaderByTopic(String clusterAlias, String topic, PartitionsInfo partition) {
try {
List<MetadataInfo> topicMetas = topicMetadata(clusterAlias, topic);
Map<Integer, Integer> brokerLeaders = new HashMap<>();
Set<Integer> brokerSizes = new HashSet<>();
for (MetadataInfo meta : topicMetas) {
List<Integer> replicasIntegers = new ArrayList<>();
try {
replicasIntegers = JSON.parseObject(meta.getReplicas(), new TypeReference<ArrayList<Integer>>() {
});
} catch (Exception e) {
e.printStackTrace();
LOG.error("Parse string to int list has error, msg is " + e.getCause().getMessage());
}
brokerSizes.addAll(replicasIntegers);
if (brokerLeaders.containsKey(meta.getLeader())) {
int value = brokerLeaders.get(meta.getLeader());
brokerLeaders.put(meta.getLeader(), value + 1);
} else {
brokerLeaders.put(meta.getLeader(), 1);
}
}
int brokerSize = brokerSizes.size();
int brokerSkewLeaderNormal = MathUtils.ceil(brokerSize, partition.getPartitionNumbers());
int brokerSkewLeaderSize = 0;
for (Entry<Integer, Integer> entry : brokerLeaders.entrySet()) {
if (entry.getValue() > brokerSkewLeaderNormal) {
brokerSkewLeaderSize++;
}
}
partition.setBrokersLeaderSkewed(String.format("%.2f", (brokerSkewLeaderSize * 100.0 / brokerSize)));
} catch (Exception e) {
e.printStackTrace();
LOG.error("Get topic skewed info has error, msg is ", e);
}
}
/** Check topic from zookeeper metadata. */
public boolean findKafkaTopic(String clusterAlias, String topic) {
return topicList(clusterAlias).contains(topic);
}
/** Get kafka broker numbers from zookeeper. */
public long brokerNumbers(String clusterAlias) {
long count = 0;
KafkaZkClient zkc = kafkaZKPool.getZkClient(clusterAlias);
try {
if (zkc.pathExists(BROKER_IDS_PATH)) {
Seq<String> subBrokerIdsPaths = zkc.getChildren(BROKER_IDS_PATH);
count = JavaConversions.seqAsJavaList(subBrokerIdsPaths).size();
}
} catch (Exception e) {
LOG.error("Get kafka broker numbers has error, msg is " + e.getCause().getMessage());
e.printStackTrace();
}
if (zkc != null) {
kafkaZKPool.release(clusterAlias, zkc);
zkc = null;
}
return count;
}
/** Get topic list from zookeeper. */
public List<String> topicList(String clusterAlias) {
List<String> topics = new ArrayList<>();
if (SystemConfigUtils.getBooleanProperty(clusterAlias + ".kafka.eagle.sasl.cgroup.enable")) {
topics = SystemConfigUtils.getPropertyArrayList(clusterAlias + ".kafka.eagle.sasl.cgroup.topics", ",");
} else {
KafkaZkClient zkc = kafkaZKPool.getZkClient(clusterAlias);
try {
if (zkc.pathExists(BROKER_TOPICS_PATH)) {
Seq<String> subBrokerTopicsPaths = zkc.getChildren(BROKER_TOPICS_PATH);
topics = JavaConversions.seqAsJavaList(subBrokerTopicsPaths);
excludeTopic(topics);
}
} catch (Exception e) {
LOG.error("Get topic list has error, msg is " + e.getCause().getMessage());
e.printStackTrace();
}
if (zkc != null) {
kafkaZKPool.release(clusterAlias, zkc);
zkc = null;
}
}
return topics;
}
/** Get select topic list from zookeeper. */
public String topicListParams(String clusterAlias, String search) {
JSONArray targets = new JSONArray();
int limit = 15;
List<String> topics = topicList(clusterAlias);
try {
if (Strings.isNullOrEmpty(search)) {
int id = 1;
for (String topic : topics) {
if (id <= limit) {
JSONObject object = new JSONObject();
object.put("id", id);
object.put("name", topic);
targets.add(object);
id++;
}
}
} else {
int id = 1;
for (String topic : topics) {
if (topic.contains(search)) {
if (id <= limit) {
JSONObject object = new JSONObject();
object.put("id", id);
object.put("name", topic);
targets.add(object);
id++;
}
}
}
}
} catch (Exception e) {
LOG.error("Get topic list has error, msg is " + e.getCause().getMessage());
e.printStackTrace();
}
return targets.toJSONString();
}
/** Scan topic meta page display from zookeeper and kafka. */
public List<MetadataInfo> topicMetadataRecords(String clusterAlias, String topic, Map<String, Object> params) {
List<MetadataInfo> targets = new ArrayList<>();
KafkaZkClient zkc = kafkaZKPool.getZkClient(clusterAlias);
try {
if (zkc.pathExists(BROKER_TOPICS_PATH)) {
List<String> topics = topicList(clusterAlias);
if (topics.contains(topic)) {
int start = Integer.parseInt(params.get("start").toString());
int length = Integer.parseInt(params.get("length").toString());
int offset = 0;
Tuple2<Option<byte[]>, Stat> tuple = zkc.getDataAndStat(BROKER_TOPICS_PATH + "/" + topic);
String tupleString = new String(tuple._1.get());
JSONObject partitionObject = JSON.parseObject(tupleString).getJSONObject("partitions");
for (String partition : partitionObject.keySet()) {
if (offset < (start + length) && offset >= start) {
String path = String.format(TOPIC_ISR, topic, Integer.valueOf(partition));
Tuple2<Option<byte[]>, Stat> tuple2 = zkc.getDataAndStat(path);
String tupleString2 = new String(tuple2._1.get());
JSONObject topicMetadata = JSON.parseObject(tupleString2);
MetadataInfo metadate = new MetadataInfo();
metadate.setIsr(topicMetadata.getString("isr"));
metadate.setLeader(topicMetadata.getInteger("leader"));
metadate.setPartitionId(Integer.valueOf(partition));
metadate.setReplicas(kafkaService.getReplicasIsr(clusterAlias, topic, Integer.valueOf(partition)));
long logSize = 0L;
if ("kafka".equals(SystemConfigUtils.getProperty(clusterAlias + ".kafka.eagle.offset.storage"))) {
logSize = kafkaService.getKafkaRealLogSize(clusterAlias, topic, Integer.valueOf(partition));
} else {
logSize = kafkaService.getRealLogSize(clusterAlias, topic, Integer.valueOf(partition));
}
List<Integer> isrIntegers = new ArrayList<>();
List<Integer> replicasIntegers = new ArrayList<>();
try {
isrIntegers = JSON.parseObject(metadate.getIsr(), new TypeReference<ArrayList<Integer>>() {
});
replicasIntegers = JSON.parseObject(metadate.getReplicas(), new TypeReference<ArrayList<Integer>>() {
});
} catch (Exception e) {
e.printStackTrace();
LOG.error("Parse string to int list has error, msg is " + e.getCause().getMessage());
}
if (isrIntegers.size() != replicasIntegers.size()) {
// replicas lost
metadate.setUnderReplicated(true);
} else {
// replicas normal
metadate.setUnderReplicated(false);
}
if (replicasIntegers != null && replicasIntegers.size() > 0 && replicasIntegers.get(0) == metadate.getLeader()) {
// partition preferred leader
metadate.setPreferredLeader(true);
} else {
// partition occurs preferred leader exception
metadate.setPreferredLeader(false);
}
metadate.setLogSize(logSize);
targets.add(metadate);
}
offset++;
}
}
}
} catch (Exception e) {
LOG.error("Get topic metadata records has error, msg is " + e.getCause().getMessage());
e.printStackTrace();
}
if (zkc != null) {
kafkaZKPool.release(clusterAlias, zkc);
zkc = null;
}
return targets;
}
private List<MetadataInfo> topicMetadata(String clusterAlias, String topic) {
List<MetadataInfo> targets = new ArrayList<>();
KafkaZkClient zkc = kafkaZKPool.getZkClient(clusterAlias);
try {
if (zkc.pathExists(BROKER_TOPICS_PATH)) {
List<String> topics = topicList(clusterAlias);
if (topics.contains(topic)) {
Tuple2<Option<byte[]>, Stat> tuple = zkc.getDataAndStat(BROKER_TOPICS_PATH + "/" + topic);
String tupleString = new String(tuple._1.get());
JSONObject partitionObject = JSON.parseObject(tupleString).getJSONObject("partitions");
for (String partition : partitionObject.keySet()) {
String path = String.format(TOPIC_ISR, topic, Integer.valueOf(partition));
Tuple2<Option<byte[]>, Stat> tuple2 = zkc.getDataAndStat(path);
String tupleString2 = new String(tuple2._1.get());
JSONObject topicMetadata = JSON.parseObject(tupleString2);
MetadataInfo metadate = new MetadataInfo();
metadate.setIsr(topicMetadata.getString("isr"));
metadate.setLeader(topicMetadata.getInteger("leader"));
metadate.setPartitionId(Integer.valueOf(partition));
metadate.setReplicas(kafkaService.getReplicasIsr(clusterAlias, topic, Integer.valueOf(partition)));
targets.add(metadate);
}
}
}
} catch (Exception e) {
LOG.error("Get topic metadata records has error, msg is " + e.getCause().getMessage());
e.printStackTrace();
}
if (zkc != null) {
kafkaZKPool.release(clusterAlias, zkc);
zkc = null;
}
return targets;
}
/** Get topic producer logsize total. */
public long getTopicLogSizeTotal(String clusterAlias, String topic) {
long logSize = 0L;
if (Kafka.CONSUMER_OFFSET_TOPIC.equals(topic)) {
return logSize;
}
KafkaZkClient zkc = kafkaZKPool.getZkClient(clusterAlias);
try {
if (zkc.pathExists(BROKER_TOPICS_PATH + "/" + topic)) {
Tuple2<Option<byte[]>, Stat> tuple = zkc.getDataAndStat(BROKER_TOPICS_PATH + "/" + topic);
String tupleString = new String(tuple._1.get());
JSONObject partitionObject = JSON.parseObject(tupleString).getJSONObject("partitions");
Set<Integer> partitions = new HashSet<>();
for (String partition : partitionObject.keySet()) {
try {
partitions.add(Integer.valueOf(partition));
} catch (Exception e) {
LOG.error("Convert partition string to integer has error, msg is " + e.getCause().getMessage());
e.printStackTrace();
}
}
if ("kafka".equals(SystemConfigUtils.getProperty(clusterAlias + ".kafka.eagle.offset.storage"))) {
logSize = kafkaService.getKafkaRealLogSize(clusterAlias, topic, partitions);
} else {
logSize = kafkaService.getLogSize(clusterAlias, topic, partitions);
}
}
} catch (Exception e) {
LOG.error("Get topic logsize total has error, msg is " + e.getCause().getMessage());
e.printStackTrace();
}
if (zkc != null) {
kafkaZKPool.release(clusterAlias, zkc);
zkc = null;
}
return logSize;
}
/** Get topic real logsize records. */
public long getTopicRealLogSize(String clusterAlias, String topic) {
long logSize = 0L;
if (Kafka.CONSUMER_OFFSET_TOPIC.equals(topic)) {
return logSize;
}
KafkaZkClient zkc = kafkaZKPool.getZkClient(clusterAlias);
try {
if (zkc.pathExists(BROKER_TOPICS_PATH + "/" + topic)) {
Tuple2<Option<byte[]>, Stat> tuple = zkc.getDataAndStat(BROKER_TOPICS_PATH + "/" + topic);
String tupleString = new String(tuple._1.get());
JSONObject partitionObject = JSON.parseObject(tupleString).getJSONObject("partitions");
Set<Integer> partitions = new HashSet<>();
for (String partition : partitionObject.keySet()) {
try {
partitions.add(Integer.valueOf(partition));
} catch (Exception e) {
LOG.error("Convert partition string to integer has error, msg is " + e.getCause().getMessage());
e.printStackTrace();
}
}
if ("kafka".equals(SystemConfigUtils.getProperty(clusterAlias + ".kafka.eagle.offset.storage"))) {
logSize = kafkaService.getKafkaRealLogSize(clusterAlias, topic, partitions);
} else {
logSize = kafkaService.getLogSize(clusterAlias, topic, partitions);
}
}
} catch (Exception e) {
LOG.error("Get topic real logsize has error, msg is " + e.getCause().getMessage());
e.printStackTrace();
}
if (zkc != null) {
kafkaZKPool.release(clusterAlias, zkc);
zkc = null;
}
return logSize;
}
/** Get topic producer send logsize records. */
public long getTopicProducerLogSize(String clusterAlias, String topic) {
long logSize = 0L;
if (Kafka.CONSUMER_OFFSET_TOPIC.equals(topic)) {
return logSize;
}
KafkaZkClient zkc = kafkaZKPool.getZkClient(clusterAlias);
try {
if (zkc.pathExists(BROKER_TOPICS_PATH + "/" + topic)) {
Tuple2<Option<byte[]>, Stat> tuple = zkc.getDataAndStat(BROKER_TOPICS_PATH + "/" + topic);
String tupleString = new String(tuple._1.get());
JSONObject partitionObject = JSON.parseObject(tupleString).getJSONObject("partitions");
Set<Integer> partitions = new HashSet<>();
for (String partition : partitionObject.keySet()) {
try {
partitions.add(Integer.valueOf(partition));
} catch (Exception e) {
LOG.error("Convert partition string to integer has error, msg is " + e.getCause().getMessage());
e.printStackTrace();
}
}
if ("kafka".equals(SystemConfigUtils.getProperty(clusterAlias + ".kafka.eagle.offset.storage"))) {
logSize = kafkaService.getKafkaProducerLogSize(clusterAlias, topic, partitions);
} else {
logSize = kafkaService.getLogSize(clusterAlias, topic, partitions);
}
}
} catch (Exception e) {
LOG.error("Get topic real logsize has error, msg is " + e.getCause().getMessage());
e.printStackTrace();
}
if (zkc != null) {
kafkaZKPool.release(clusterAlias, zkc);
zkc = null;
}
return logSize;
}
/** Add topic partitions. */
public Map<String, Object> createTopicPartitions(String clusterAlias, String topic, int totalCount) {
Map<String, Object> targets = new HashMap<String, Object>();
int existPartitions = (int) partitionNumbers(clusterAlias, topic);
Properties prop = new Properties();
prop.put(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, kafkaService.getKafkaBrokerServer(clusterAlias));
if (SystemConfigUtils.getBooleanProperty(clusterAlias + ".kafka.eagle.sasl.enable")) {
kafkaService.sasl(prop, clusterAlias);
}
AdminClient adminClient = null;
try {
adminClient = AdminClient.create(prop);
Map<String, NewPartitions> newPartitions = new HashMap<String, NewPartitions>();
newPartitions.put(topic, NewPartitions.increaseTo(existPartitions + totalCount));
adminClient.createPartitions(newPartitions);
targets.put("status", "success");
targets.put("info", "Add topic[" + topic + "], before partition[" + existPartitions + "], after partition[" + (existPartitions + totalCount) + "] has successed.");
} catch (Exception e) {
LOG.info("Add kafka topic partitions has error, msg is " + e.getMessage());
e.printStackTrace();
targets.put("status", "failed");
targets.put("info", "Add kafka topic partitions has error, msg is " + e.getMessage());
} finally {
adminClient.close();
}
return targets;
}
}
|
kafka-eagle-core/src/main/java/org/smartloli/kafka/eagle/core/factory/v2/BrokerServiceImpl.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.smartloli.kafka.eagle.core.factory.v2;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import org.apache.kafka.clients.CommonClientConfigs;
import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.NewPartitions;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smartloli.kafka.eagle.common.protocol.MetadataInfo;
import org.smartloli.kafka.eagle.common.protocol.PartitionsInfo;
import org.smartloli.kafka.eagle.common.util.CalendarUtils;
import org.smartloli.kafka.eagle.common.util.KConstants.Kafka;
import org.smartloli.kafka.eagle.common.util.KafkaZKPoolUtils;
import org.smartloli.kafka.eagle.common.util.MathUtils;
import org.smartloli.kafka.eagle.common.util.SystemConfigUtils;
import org.smartloli.kafka.eagle.core.factory.KafkaFactory;
import org.smartloli.kafka.eagle.core.factory.KafkaService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.google.common.base.Strings;
import kafka.zk.KafkaZkClient;
import scala.Option;
import scala.Tuple2;
import scala.collection.JavaConversions;
import scala.collection.Seq;
/**
* Implements {@link BrokerService} all method.
*
* @author smartloli.
*
* Created by Jun 13, 2019
*/
public class BrokerServiceImpl implements BrokerService {
private final String BROKER_IDS_PATH = "/brokers/ids";
private final String BROKER_TOPICS_PATH = "/brokers/topics";
private final String TOPIC_ISR = "/brokers/topics/%s/partitions/%s/state";
private final Logger LOG = LoggerFactory.getLogger(BrokerServiceImpl.class);
/** Instance Kafka Zookeeper client pool. */
private KafkaZKPoolUtils kafkaZKPool = KafkaZKPoolUtils.getInstance();
/** Kafka service interface. */
private KafkaService kafkaService = new KafkaFactory().create();
/** Statistics topic total used as page. */
public long topicNumbers(String clusterAlias) {
return topicList(clusterAlias).size();
}
/** Exclude kafka topic(__consumer_offsets). */
private void excludeTopic(List<String> topics) {
if (topics.contains(Kafka.CONSUMER_OFFSET_TOPIC)) {
topics.remove(Kafka.CONSUMER_OFFSET_TOPIC);
}
}
/** Get search topic list numbers. */
public long topicNumbers(String clusterAlias, String topic) {
long count = 0L;
List<String> topics = topicList(clusterAlias);
for (String name : topics) {
if (topic != null && name.contains(topic)) {
count++;
}
}
return count;
}
/** Statistics topic partitions total used as page. */
public long partitionNumbers(String clusterAlias, String topic) {
long count = 0L;
if (Kafka.CONSUMER_OFFSET_TOPIC.equals(topic)) {
return count;
}
KafkaZkClient zkc = kafkaZKPool.getZkClient(clusterAlias);
try {
if (zkc.pathExists(BROKER_TOPICS_PATH + "/" + topic + "/partitions")) {
Seq<String> subBrokerTopicsPaths = zkc.getChildren(BROKER_TOPICS_PATH + "/" + topic + "/partitions");
count = JavaConversions.seqAsJavaList(subBrokerTopicsPaths).size();
}
} catch (Exception e) {
LOG.error("Get topic partition numbers has error, msg is " + e.getCause().getMessage());
e.printStackTrace();
}
if (zkc != null) {
kafkaZKPool.release(clusterAlias, zkc);
zkc = null;
}
return count;
}
/** Get the number of page records for topic. */
public List<PartitionsInfo> topicRecords(String clusterAlias, Map<String, Object> params) {
KafkaZkClient zkc = kafkaZKPool.getZkClient(clusterAlias);
List<PartitionsInfo> targets = new ArrayList<PartitionsInfo>();
List<String> topics = topicList(clusterAlias);
try {
int start = Integer.parseInt(params.get("start").toString());
int length = Integer.parseInt(params.get("length").toString());
if (params.containsKey("search") && params.get("search").toString().length() > 0) {
String search = params.get("search").toString();
int offset = 0;
int id = start + 1;
for (String topic : topics) {
if (search != null && topic.contains(search)) {
if (offset < (start + length) && offset >= start) {
try {
if (zkc.pathExists(BROKER_TOPICS_PATH + "/" + topic)) {
Tuple2<Option<byte[]>, Stat> tuple = zkc.getDataAndStat(BROKER_TOPICS_PATH + "/" + topic);
PartitionsInfo partition = new PartitionsInfo();
partition.setId(id++);
partition.setCreated(CalendarUtils.convertUnixTime2Date(tuple._2.getCtime()));
partition.setModify(CalendarUtils.convertUnixTime2Date(tuple._2.getMtime()));
partition.setTopic(topic);
String tupleString = new String(tuple._1.get());
JSONObject partitionObject = JSON.parseObject(tupleString).getJSONObject("partitions");
partition.setPartitionNumbers(partitionObject.size());
partition.setPartitions(partitionObject.keySet());
getBrokerSpreadByTopic(clusterAlias, topic, partition);
getBrokerSkewedByTopic(clusterAlias, topic, partition);
getBrokerSkewedLeaderByTopic(clusterAlias, topic, partition);
targets.add(partition);
}
} catch (Exception ex) {
ex.printStackTrace();
LOG.error("Scan topic search from zookeeper has error, msg is " + ex.getMessage());
}
}
offset++;
}
}
} else {
int offset = 0;
int id = start + 1;
for (String topic : topics) {
if (offset < (start + length) && offset >= start) {
try {
if (zkc.pathExists(BROKER_TOPICS_PATH + "/" + topic)) {
Tuple2<Option<byte[]>, Stat> tuple = zkc.getDataAndStat(BROKER_TOPICS_PATH + "/" + topic);
PartitionsInfo partition = new PartitionsInfo();
partition.setId(id++);
partition.setCreated(CalendarUtils.convertUnixTime2Date(tuple._2.getCtime()));
partition.setModify(CalendarUtils.convertUnixTime2Date(tuple._2.getMtime()));
partition.setTopic(topic);
String tupleString = new String(tuple._1.get());
JSONObject partitionObject = JSON.parseObject(tupleString).getJSONObject("partitions");
partition.setPartitionNumbers(partitionObject.size());
partition.setPartitions(partitionObject.keySet());
getBrokerSpreadByTopic(clusterAlias, topic, partition);
getBrokerSkewedByTopic(clusterAlias, topic, partition);
getBrokerSkewedLeaderByTopic(clusterAlias, topic, partition);
targets.add(partition);
}
} catch (Exception ex) {
ex.printStackTrace();
LOG.error("Scan topic page from zookeeper has error, msg is " + ex.getMessage());
}
}
offset++;
}
}
} catch (Exception e) {
LOG.error("Get topic records has error, msg is " + e.getCause().getMessage());
e.printStackTrace();
}
if (zkc != null) {
kafkaZKPool.release(clusterAlias, zkc);
zkc = null;
}
return targets;
}
/** Get broker spread by topic. */
private void getBrokerSpreadByTopic(String clusterAlias, String topic, PartitionsInfo partition) {
try {
List<MetadataInfo> topicMetas = topicMetadata(clusterAlias, topic);
Set<Integer> brokerLeaders = new HashSet<>();
for (MetadataInfo meta : topicMetas) {
brokerLeaders.add(meta.getLeader());
}
int brokerSize = kafkaService.getAllBrokersInfo(clusterAlias).size();
partition.setBrokersSpread(String.format("%.2f", (brokerLeaders.size() * 100.0 / brokerSize)));
} catch (Exception e) {
e.printStackTrace();
LOG.error("Get topic skewed info has error, msg is ", e);
}
}
/** Get broker skewed by topic. */
private void getBrokerSkewedByTopic(String clusterAlias, String topic, PartitionsInfo partition) {
try {
List<MetadataInfo> topicMetas = topicMetadata(clusterAlias, topic);
int partitionAndReplicaTopics = 0;
Map<Integer, Integer> brokers = new HashMap<>();
for (MetadataInfo meta : topicMetas) {
List<Integer> replicasIntegers = new ArrayList<>();
try {
replicasIntegers = JSON.parseObject(meta.getReplicas(), new TypeReference<ArrayList<Integer>>() {
});
} catch (Exception e) {
e.printStackTrace();
LOG.error("Parse string to int list has error, msg is " + e.getCause().getMessage());
}
partitionAndReplicaTopics += replicasIntegers.size();
for (Integer brokerId : replicasIntegers) {
if (brokers.containsKey(brokerId)) {
int value = brokers.get(brokerId);
brokers.put(brokerId, value + 1);
} else {
brokers.put(brokerId, 1);
}
}
}
int brokerSize = kafkaService.getAllBrokersInfo(clusterAlias).size();
int normalSkewedValue = MathUtils.ceil(brokerSize, partitionAndReplicaTopics);
int brokerSkewSize = 0;
for (Entry<Integer, Integer> entry : brokers.entrySet()) {
if (entry.getValue() > normalSkewedValue) {
brokerSkewSize++;
}
}
partition.setBrokersSkewed(String.format("%.2f", (brokerSkewSize * 100.0 / brokerSize)));
} catch (Exception e) {
e.printStackTrace();
LOG.error("Get topic skewed info has error, msg is ", e);
}
}
/** Get broker skewed leader by topic. */
private void getBrokerSkewedLeaderByTopic(String clusterAlias, String topic, PartitionsInfo partition) {
try {
List<MetadataInfo> topicMetas = topicMetadata(clusterAlias, topic);
Map<Integer, Integer> brokerLeaders = new HashMap<>();
for (MetadataInfo meta : topicMetas) {
if (brokerLeaders.containsKey(meta.getLeader())) {
int value = brokerLeaders.get(meta.getLeader());
brokerLeaders.put(meta.getLeader(), value + 1);
} else {
brokerLeaders.put(meta.getLeader(), 1);
}
}
int brokerSize = kafkaService.getAllBrokersInfo(clusterAlias).size();
int brokerSkewLeaderNormal = MathUtils.ceil(brokerSize, partition.getPartitionNumbers());
int brokerSkewLeaderSize = 0;
for (Entry<Integer, Integer> entry : brokerLeaders.entrySet()) {
if (entry.getValue() > brokerSkewLeaderNormal) {
brokerSkewLeaderSize++;
}
}
partition.setBrokersLeaderSkewed(String.format("%.2f", (brokerSkewLeaderSize * 100.0 / brokerSize)));
} catch (Exception e) {
e.printStackTrace();
LOG.error("Get topic skewed info has error, msg is ", e);
}
}
/** Check topic from zookeeper metadata. */
public boolean findKafkaTopic(String clusterAlias, String topic) {
return topicList(clusterAlias).contains(topic);
}
/** Get kafka broker numbers from zookeeper. */
public long brokerNumbers(String clusterAlias) {
long count = 0;
KafkaZkClient zkc = kafkaZKPool.getZkClient(clusterAlias);
try {
if (zkc.pathExists(BROKER_IDS_PATH)) {
Seq<String> subBrokerIdsPaths = zkc.getChildren(BROKER_IDS_PATH);
count = JavaConversions.seqAsJavaList(subBrokerIdsPaths).size();
}
} catch (Exception e) {
LOG.error("Get kafka broker numbers has error, msg is " + e.getCause().getMessage());
e.printStackTrace();
}
if (zkc != null) {
kafkaZKPool.release(clusterAlias, zkc);
zkc = null;
}
return count;
}
/** Get topic list from zookeeper. */
public List<String> topicList(String clusterAlias) {
List<String> topics = new ArrayList<>();
if (SystemConfigUtils.getBooleanProperty(clusterAlias + ".kafka.eagle.sasl.cgroup.enable")) {
topics = SystemConfigUtils.getPropertyArrayList(clusterAlias + ".kafka.eagle.sasl.cgroup.topics", ",");
} else {
KafkaZkClient zkc = kafkaZKPool.getZkClient(clusterAlias);
try {
if (zkc.pathExists(BROKER_TOPICS_PATH)) {
Seq<String> subBrokerTopicsPaths = zkc.getChildren(BROKER_TOPICS_PATH);
topics = JavaConversions.seqAsJavaList(subBrokerTopicsPaths);
excludeTopic(topics);
}
} catch (Exception e) {
LOG.error("Get topic list has error, msg is " + e.getCause().getMessage());
e.printStackTrace();
}
if (zkc != null) {
kafkaZKPool.release(clusterAlias, zkc);
zkc = null;
}
}
return topics;
}
/** Get select topic list from zookeeper. */
public String topicListParams(String clusterAlias, String search) {
JSONArray targets = new JSONArray();
int limit = 15;
List<String> topics = topicList(clusterAlias);
try {
if (Strings.isNullOrEmpty(search)) {
int id = 1;
for (String topic : topics) {
if (id <= limit) {
JSONObject object = new JSONObject();
object.put("id", id);
object.put("name", topic);
targets.add(object);
id++;
}
}
} else {
int id = 1;
for (String topic : topics) {
if (topic.contains(search)) {
if (id <= limit) {
JSONObject object = new JSONObject();
object.put("id", id);
object.put("name", topic);
targets.add(object);
id++;
}
}
}
}
} catch (Exception e) {
LOG.error("Get topic list has error, msg is " + e.getCause().getMessage());
e.printStackTrace();
}
return targets.toJSONString();
}
/** Scan topic meta page display from zookeeper and kafka. */
public List<MetadataInfo> topicMetadataRecords(String clusterAlias, String topic, Map<String, Object> params) {
List<MetadataInfo> targets = new ArrayList<>();
KafkaZkClient zkc = kafkaZKPool.getZkClient(clusterAlias);
try {
if (zkc.pathExists(BROKER_TOPICS_PATH)) {
List<String> topics = topicList(clusterAlias);
if (topics.contains(topic)) {
int start = Integer.parseInt(params.get("start").toString());
int length = Integer.parseInt(params.get("length").toString());
int offset = 0;
Tuple2<Option<byte[]>, Stat> tuple = zkc.getDataAndStat(BROKER_TOPICS_PATH + "/" + topic);
String tupleString = new String(tuple._1.get());
JSONObject partitionObject = JSON.parseObject(tupleString).getJSONObject("partitions");
for (String partition : partitionObject.keySet()) {
if (offset < (start + length) && offset >= start) {
String path = String.format(TOPIC_ISR, topic, Integer.valueOf(partition));
Tuple2<Option<byte[]>, Stat> tuple2 = zkc.getDataAndStat(path);
String tupleString2 = new String(tuple2._1.get());
JSONObject topicMetadata = JSON.parseObject(tupleString2);
MetadataInfo metadate = new MetadataInfo();
metadate.setIsr(topicMetadata.getString("isr"));
metadate.setLeader(topicMetadata.getInteger("leader"));
metadate.setPartitionId(Integer.valueOf(partition));
metadate.setReplicas(kafkaService.getReplicasIsr(clusterAlias, topic, Integer.valueOf(partition)));
long logSize = 0L;
if ("kafka".equals(SystemConfigUtils.getProperty(clusterAlias + ".kafka.eagle.offset.storage"))) {
logSize = kafkaService.getKafkaRealLogSize(clusterAlias, topic, Integer.valueOf(partition));
} else {
logSize = kafkaService.getRealLogSize(clusterAlias, topic, Integer.valueOf(partition));
}
List<Integer> isrIntegers = new ArrayList<>();
List<Integer> replicasIntegers = new ArrayList<>();
try {
isrIntegers = JSON.parseObject(metadate.getIsr(), new TypeReference<ArrayList<Integer>>() {
});
replicasIntegers = JSON.parseObject(metadate.getReplicas(), new TypeReference<ArrayList<Integer>>() {
});
} catch (Exception e) {
e.printStackTrace();
LOG.error("Parse string to int list has error, msg is " + e.getCause().getMessage());
}
if (isrIntegers.size() != replicasIntegers.size()) {
// replicas lost
metadate.setUnderReplicated(true);
} else {
// replicas normal
metadate.setUnderReplicated(false);
}
if (replicasIntegers != null && replicasIntegers.size() > 0 && replicasIntegers.get(0) == metadate.getLeader()) {
// partition preferred leader
metadate.setPreferredLeader(true);
} else {
// partition occurs preferred leader exception
metadate.setPreferredLeader(false);
}
metadate.setLogSize(logSize);
targets.add(metadate);
}
offset++;
}
}
}
} catch (Exception e) {
LOG.error("Get topic metadata records has error, msg is " + e.getCause().getMessage());
e.printStackTrace();
}
if (zkc != null) {
kafkaZKPool.release(clusterAlias, zkc);
zkc = null;
}
return targets;
}
private List<MetadataInfo> topicMetadata(String clusterAlias, String topic) {
List<MetadataInfo> targets = new ArrayList<>();
KafkaZkClient zkc = kafkaZKPool.getZkClient(clusterAlias);
try {
if (zkc.pathExists(BROKER_TOPICS_PATH)) {
List<String> topics = topicList(clusterAlias);
if (topics.contains(topic)) {
Tuple2<Option<byte[]>, Stat> tuple = zkc.getDataAndStat(BROKER_TOPICS_PATH + "/" + topic);
String tupleString = new String(tuple._1.get());
JSONObject partitionObject = JSON.parseObject(tupleString).getJSONObject("partitions");
for (String partition : partitionObject.keySet()) {
String path = String.format(TOPIC_ISR, topic, Integer.valueOf(partition));
Tuple2<Option<byte[]>, Stat> tuple2 = zkc.getDataAndStat(path);
String tupleString2 = new String(tuple2._1.get());
JSONObject topicMetadata = JSON.parseObject(tupleString2);
MetadataInfo metadate = new MetadataInfo();
metadate.setIsr(topicMetadata.getString("isr"));
metadate.setLeader(topicMetadata.getInteger("leader"));
metadate.setPartitionId(Integer.valueOf(partition));
metadate.setReplicas(kafkaService.getReplicasIsr(clusterAlias, topic, Integer.valueOf(partition)));
targets.add(metadate);
}
}
}
} catch (Exception e) {
LOG.error("Get topic metadata records has error, msg is " + e.getCause().getMessage());
e.printStackTrace();
}
if (zkc != null) {
kafkaZKPool.release(clusterAlias, zkc);
zkc = null;
}
return targets;
}
/** Get topic producer logsize total. */
public long getTopicLogSizeTotal(String clusterAlias, String topic) {
long logSize = 0L;
if (Kafka.CONSUMER_OFFSET_TOPIC.equals(topic)) {
return logSize;
}
KafkaZkClient zkc = kafkaZKPool.getZkClient(clusterAlias);
try {
if (zkc.pathExists(BROKER_TOPICS_PATH + "/" + topic)) {
Tuple2<Option<byte[]>, Stat> tuple = zkc.getDataAndStat(BROKER_TOPICS_PATH + "/" + topic);
String tupleString = new String(tuple._1.get());
JSONObject partitionObject = JSON.parseObject(tupleString).getJSONObject("partitions");
Set<Integer> partitions = new HashSet<>();
for (String partition : partitionObject.keySet()) {
try {
partitions.add(Integer.valueOf(partition));
} catch (Exception e) {
LOG.error("Convert partition string to integer has error, msg is " + e.getCause().getMessage());
e.printStackTrace();
}
}
if ("kafka".equals(SystemConfigUtils.getProperty(clusterAlias + ".kafka.eagle.offset.storage"))) {
logSize = kafkaService.getKafkaRealLogSize(clusterAlias, topic, partitions);
} else {
logSize = kafkaService.getLogSize(clusterAlias, topic, partitions);
}
}
} catch (Exception e) {
LOG.error("Get topic logsize total has error, msg is " + e.getCause().getMessage());
e.printStackTrace();
}
if (zkc != null) {
kafkaZKPool.release(clusterAlias, zkc);
zkc = null;
}
return logSize;
}
/** Get topic real logsize records. */
public long getTopicRealLogSize(String clusterAlias, String topic) {
long logSize = 0L;
if (Kafka.CONSUMER_OFFSET_TOPIC.equals(topic)) {
return logSize;
}
KafkaZkClient zkc = kafkaZKPool.getZkClient(clusterAlias);
try {
if (zkc.pathExists(BROKER_TOPICS_PATH + "/" + topic)) {
Tuple2<Option<byte[]>, Stat> tuple = zkc.getDataAndStat(BROKER_TOPICS_PATH + "/" + topic);
String tupleString = new String(tuple._1.get());
JSONObject partitionObject = JSON.parseObject(tupleString).getJSONObject("partitions");
Set<Integer> partitions = new HashSet<>();
for (String partition : partitionObject.keySet()) {
try {
partitions.add(Integer.valueOf(partition));
} catch (Exception e) {
LOG.error("Convert partition string to integer has error, msg is " + e.getCause().getMessage());
e.printStackTrace();
}
}
if ("kafka".equals(SystemConfigUtils.getProperty(clusterAlias + ".kafka.eagle.offset.storage"))) {
logSize = kafkaService.getKafkaRealLogSize(clusterAlias, topic, partitions);
} else {
logSize = kafkaService.getLogSize(clusterAlias, topic, partitions);
}
}
} catch (Exception e) {
LOG.error("Get topic real logsize has error, msg is " + e.getCause().getMessage());
e.printStackTrace();
}
if (zkc != null) {
kafkaZKPool.release(clusterAlias, zkc);
zkc = null;
}
return logSize;
}
/** Get topic producer send logsize records. */
public long getTopicProducerLogSize(String clusterAlias, String topic) {
long logSize = 0L;
if (Kafka.CONSUMER_OFFSET_TOPIC.equals(topic)) {
return logSize;
}
KafkaZkClient zkc = kafkaZKPool.getZkClient(clusterAlias);
try {
if (zkc.pathExists(BROKER_TOPICS_PATH + "/" + topic)) {
Tuple2<Option<byte[]>, Stat> tuple = zkc.getDataAndStat(BROKER_TOPICS_PATH + "/" + topic);
String tupleString = new String(tuple._1.get());
JSONObject partitionObject = JSON.parseObject(tupleString).getJSONObject("partitions");
Set<Integer> partitions = new HashSet<>();
for (String partition : partitionObject.keySet()) {
try {
partitions.add(Integer.valueOf(partition));
} catch (Exception e) {
LOG.error("Convert partition string to integer has error, msg is " + e.getCause().getMessage());
e.printStackTrace();
}
}
if ("kafka".equals(SystemConfigUtils.getProperty(clusterAlias + ".kafka.eagle.offset.storage"))) {
logSize = kafkaService.getKafkaProducerLogSize(clusterAlias, topic, partitions);
} else {
logSize = kafkaService.getLogSize(clusterAlias, topic, partitions);
}
}
} catch (Exception e) {
LOG.error("Get topic real logsize has error, msg is " + e.getCause().getMessage());
e.printStackTrace();
}
if (zkc != null) {
kafkaZKPool.release(clusterAlias, zkc);
zkc = null;
}
return logSize;
}
/** Add topic partitions. */
public Map<String, Object> createTopicPartitions(String clusterAlias, String topic, int totalCount) {
Map<String, Object> targets = new HashMap<String, Object>();
int existPartitions = (int) partitionNumbers(clusterAlias, topic);
Properties prop = new Properties();
prop.put(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, kafkaService.getKafkaBrokerServer(clusterAlias));
if (SystemConfigUtils.getBooleanProperty(clusterAlias + ".kafka.eagle.sasl.enable")) {
kafkaService.sasl(prop, clusterAlias);
}
AdminClient adminClient = null;
try {
adminClient = AdminClient.create(prop);
Map<String, NewPartitions> newPartitions = new HashMap<String, NewPartitions>();
newPartitions.put(topic, NewPartitions.increaseTo(existPartitions + totalCount));
adminClient.createPartitions(newPartitions);
targets.put("status", "success");
targets.put("info", "Add topic[" + topic + "], before partition[" + existPartitions + "], after partition[" + (existPartitions + totalCount) + "] has successed.");
} catch (Exception e) {
LOG.info("Add kafka topic partitions has error, msg is " + e.getMessage());
e.printStackTrace();
targets.put("status", "failed");
targets.put("info", "Add kafka topic partitions has error, msg is " + e.getMessage());
} finally {
adminClient.close();
}
return targets;
}
}
|
fixed broker size
|
kafka-eagle-core/src/main/java/org/smartloli/kafka/eagle/core/factory/v2/BrokerServiceImpl.java
|
fixed broker size
|
<ide><path>afka-eagle-core/src/main/java/org/smartloli/kafka/eagle/core/factory/v2/BrokerServiceImpl.java
<ide> try {
<ide> List<MetadataInfo> topicMetas = topicMetadata(clusterAlias, topic);
<ide> Set<Integer> brokerLeaders = new HashSet<>();
<add> Set<Integer> brokerSizes = new HashSet<>();
<ide> for (MetadataInfo meta : topicMetas) {
<ide> brokerLeaders.add(meta.getLeader());
<del> }
<del> int brokerSize = kafkaService.getAllBrokersInfo(clusterAlias).size();
<add> List<Integer> replicasIntegers = new ArrayList<>();
<add> try {
<add> replicasIntegers = JSON.parseObject(meta.getReplicas(), new TypeReference<ArrayList<Integer>>() {
<add> });
<add> } catch (Exception e) {
<add> e.printStackTrace();
<add> LOG.error("Parse string to int list has error, msg is " + e.getCause().getMessage());
<add> }
<add> brokerSizes.addAll(replicasIntegers);
<add> }
<add> int brokerSize = brokerSizes.size();
<ide> partition.setBrokersSpread(String.format("%.2f", (brokerLeaders.size() * 100.0 / brokerSize)));
<ide> } catch (Exception e) {
<ide> e.printStackTrace();
<ide> try {
<ide> List<MetadataInfo> topicMetas = topicMetadata(clusterAlias, topic);
<ide> int partitionAndReplicaTopics = 0;
<add> Set<Integer> brokerSizes = new HashSet<>();
<ide> Map<Integer, Integer> brokers = new HashMap<>();
<ide> for (MetadataInfo meta : topicMetas) {
<ide> List<Integer> replicasIntegers = new ArrayList<>();
<ide> e.printStackTrace();
<ide> LOG.error("Parse string to int list has error, msg is " + e.getCause().getMessage());
<ide> }
<add> brokerSizes.addAll(replicasIntegers);
<ide> partitionAndReplicaTopics += replicasIntegers.size();
<ide> for (Integer brokerId : replicasIntegers) {
<ide> if (brokers.containsKey(brokerId)) {
<ide> }
<ide> }
<ide> }
<del> int brokerSize = kafkaService.getAllBrokersInfo(clusterAlias).size();
<add> int brokerSize = brokerSizes.size();
<ide> int normalSkewedValue = MathUtils.ceil(brokerSize, partitionAndReplicaTopics);
<ide> int brokerSkewSize = 0;
<ide> for (Entry<Integer, Integer> entry : brokers.entrySet()) {
<ide> try {
<ide> List<MetadataInfo> topicMetas = topicMetadata(clusterAlias, topic);
<ide> Map<Integer, Integer> brokerLeaders = new HashMap<>();
<add> Set<Integer> brokerSizes = new HashSet<>();
<ide> for (MetadataInfo meta : topicMetas) {
<add> List<Integer> replicasIntegers = new ArrayList<>();
<add> try {
<add> replicasIntegers = JSON.parseObject(meta.getReplicas(), new TypeReference<ArrayList<Integer>>() {
<add> });
<add> } catch (Exception e) {
<add> e.printStackTrace();
<add> LOG.error("Parse string to int list has error, msg is " + e.getCause().getMessage());
<add> }
<add> brokerSizes.addAll(replicasIntegers);
<ide> if (brokerLeaders.containsKey(meta.getLeader())) {
<ide> int value = brokerLeaders.get(meta.getLeader());
<ide> brokerLeaders.put(meta.getLeader(), value + 1);
<ide> brokerLeaders.put(meta.getLeader(), 1);
<ide> }
<ide> }
<del> int brokerSize = kafkaService.getAllBrokersInfo(clusterAlias).size();
<add> int brokerSize = brokerSizes.size();
<ide> int brokerSkewLeaderNormal = MathUtils.ceil(brokerSize, partition.getPartitionNumbers());
<ide> int brokerSkewLeaderSize = 0;
<ide> for (Entry<Integer, Integer> entry : brokerLeaders.entrySet()) {
|
|
Java
|
mit
|
error: pathspec 'src/main/java/com/freetymekiyan/algorithms/level/medium/ContiguousArray.java' did not match any file(s) known to git
|
bde7322433ac4ef8feb0e568139ed3714fe54ee3
| 1 |
FreeTymeKiyan/LeetCode-Sol-Res,FreeTymeKiyan/LeetCode-Sol-Res
|
package com.freetymekiyan.algorithms.level.medium;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* 525. Contiguous Array
* <p>
* Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.
* <p>
* Example 1:
* Input: [0,1]
* Output: 2
* Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1.
* Example 2:
* Input: [0,1,0]
* Output: 2
* Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.
* Note: The length of the given binary array will not exceed 50,000.
* <p>
* Related Topics: Hash Table
* Similar Questions: (M) Maximum Size Subarray Sum Equals k
*/
public class ContiguousArray {
/**
* Hash Table.
* Use an integer, count, to track the difference between # of 0s and # of 1s.
* Whenever the difference is the same, there are equal # of 0s and 1s in between.
* The count ranges from -n (all 1s) to n (all 0s).
* So we can create a 2*n + 1 long array, as a map, to store the first index of this count.
* When there is another count, we can subtract and check the length.
* Note that when there is no element in the array, count = 0 still holds.
* This is a special case that when 0s and 1s are equal from the beginning to current index.
*/
public int findMaxLength(int[] nums) {
int n = nums.length;
int[] countToIndex = new int[2 * n + 1];
Arrays.fill(countToIndex, -2); // Fills with -2 since countToIndex[n] is -1.
countToIndex[n] = -1; // When # of 0s and # of 1s are the same from beginning to i, the length should be i + 1.
int maxLength = 0;
int count = 0;
for (int i = 0; i < n; i++) {
count += (nums[i] == 0 ? 1 : -1);
if (countToIndex[count + n] > -2) {
maxLength = Math.max(maxLength, i - countToIndex[count + n]);
} else { // No such count appeared yet.
countToIndex[count + n] = i;
}
}
return maxLength;
}
/**
* Hash Table.
* Use map directly.
*/
public int findMaxLength2(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
map.put(0, -1);
int count = 0;
int maxLength = 0;
for (int i = 0; i < nums.length; i++) {
count += (nums[i] == 0 ? 1 : -1);
if (map.containsKey(count)) {
maxLength = Math.max(maxLength, i - map.get(count));
} else {
map.put(count, i);
}
}
return maxLength;
}
}
|
src/main/java/com/freetymekiyan/algorithms/level/medium/ContiguousArray.java
|
add 525. Contiguous Array
|
src/main/java/com/freetymekiyan/algorithms/level/medium/ContiguousArray.java
|
add 525. Contiguous Array
|
<ide><path>rc/main/java/com/freetymekiyan/algorithms/level/medium/ContiguousArray.java
<add>package com.freetymekiyan.algorithms.level.medium;
<add>
<add>import java.util.Arrays;
<add>import java.util.HashMap;
<add>import java.util.Map;
<add>
<add>/**
<add> * 525. Contiguous Array
<add> * <p>
<add> * Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.
<add> * <p>
<add> * Example 1:
<add> * Input: [0,1]
<add> * Output: 2
<add> * Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1.
<add> * Example 2:
<add> * Input: [0,1,0]
<add> * Output: 2
<add> * Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.
<add> * Note: The length of the given binary array will not exceed 50,000.
<add> * <p>
<add> * Related Topics: Hash Table
<add> * Similar Questions: (M) Maximum Size Subarray Sum Equals k
<add> */
<add>public class ContiguousArray {
<add>
<add> /**
<add> * Hash Table.
<add> * Use an integer, count, to track the difference between # of 0s and # of 1s.
<add> * Whenever the difference is the same, there are equal # of 0s and 1s in between.
<add> * The count ranges from -n (all 1s) to n (all 0s).
<add> * So we can create a 2*n + 1 long array, as a map, to store the first index of this count.
<add> * When there is another count, we can subtract and check the length.
<add> * Note that when there is no element in the array, count = 0 still holds.
<add> * This is a special case that when 0s and 1s are equal from the beginning to current index.
<add> */
<add> public int findMaxLength(int[] nums) {
<add> int n = nums.length;
<add> int[] countToIndex = new int[2 * n + 1];
<add> Arrays.fill(countToIndex, -2); // Fills with -2 since countToIndex[n] is -1.
<add> countToIndex[n] = -1; // When # of 0s and # of 1s are the same from beginning to i, the length should be i + 1.
<add> int maxLength = 0;
<add> int count = 0;
<add> for (int i = 0; i < n; i++) {
<add> count += (nums[i] == 0 ? 1 : -1);
<add> if (countToIndex[count + n] > -2) {
<add> maxLength = Math.max(maxLength, i - countToIndex[count + n]);
<add> } else { // No such count appeared yet.
<add> countToIndex[count + n] = i;
<add> }
<add> }
<add> return maxLength;
<add> }
<add>
<add> /**
<add> * Hash Table.
<add> * Use map directly.
<add> */
<add> public int findMaxLength2(int[] nums) {
<add> Map<Integer, Integer> map = new HashMap<>();
<add> map.put(0, -1);
<add> int count = 0;
<add> int maxLength = 0;
<add> for (int i = 0; i < nums.length; i++) {
<add> count += (nums[i] == 0 ? 1 : -1);
<add> if (map.containsKey(count)) {
<add> maxLength = Math.max(maxLength, i - map.get(count));
<add> } else {
<add> map.put(count, i);
<add> }
<add> }
<add> return maxLength;
<add> }
<add>}
|
|
Java
|
mit
|
error: pathspec 'content-resources/src/main/java/flyway/oskari/V1_33_4__register_publisher2_bundle.java' did not match any file(s) known to git
|
f1218b9fc4271e72c7787fbc7a782e95b8d56203
| 1 |
nls-oskari/oskari-server,nls-oskari/oskari-server,nls-oskari/oskari-server
|
package flyway.oskari;
import fi.nls.oskari.db.BundleHelper;
import fi.nls.oskari.domain.map.view.Bundle;
import org.flywaydb.core.api.migration.jdbc.JdbcMigration;
import java.sql.Connection;
import java.sql.SQLException;
/**
* Created by SMAKINEN on 25.8.2015.
*/
public class V1_33_4__register_publisher2_bundle implements JdbcMigration {
private static final String NAMESPACE = "framework";
private static final String BUNDLE_ID = "publisher2";
public void migrate(Connection connection) throws SQLException {
// BundleHelper checks if these bundles are already registered
Bundle bundle = new Bundle();
bundle.setName(BUNDLE_ID);
bundle.setStartup(BundleHelper.getDefaultBundleStartup(NAMESPACE, BUNDLE_ID, "Publisher"));
BundleHelper.registerBundle(bundle, connection);
}
}
|
content-resources/src/main/java/flyway/oskari/V1_33_4__register_publisher2_bundle.java
|
Register script for publisher2 bundle
|
content-resources/src/main/java/flyway/oskari/V1_33_4__register_publisher2_bundle.java
|
Register script for publisher2 bundle
|
<ide><path>ontent-resources/src/main/java/flyway/oskari/V1_33_4__register_publisher2_bundle.java
<add>package flyway.oskari;
<add>
<add>import fi.nls.oskari.db.BundleHelper;
<add>import fi.nls.oskari.domain.map.view.Bundle;
<add>import org.flywaydb.core.api.migration.jdbc.JdbcMigration;
<add>
<add>import java.sql.Connection;
<add>import java.sql.SQLException;
<add>
<add>/**
<add> * Created by SMAKINEN on 25.8.2015.
<add> */
<add>public class V1_33_4__register_publisher2_bundle implements JdbcMigration {
<add>
<add> private static final String NAMESPACE = "framework";
<add> private static final String BUNDLE_ID = "publisher2";
<add>
<add> public void migrate(Connection connection) throws SQLException {
<add> // BundleHelper checks if these bundles are already registered
<add> Bundle bundle = new Bundle();
<add> bundle.setName(BUNDLE_ID);
<add> bundle.setStartup(BundleHelper.getDefaultBundleStartup(NAMESPACE, BUNDLE_ID, "Publisher"));
<add> BundleHelper.registerBundle(bundle, connection);
<add>
<add> }
<add>}
|
|
Java
|
mit
|
209e8b25535e96dafab35fe5fdaae7b493a55123
| 0 |
jglick/plugin-compat-tester,jglick/plugin-compat-tester,jglick/plugin-compat-tester,jenkinsci/plugin-compat-tester,jenkinsci/plugin-compat-tester
|
/*
* The MIT License
*
* Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi,
* Erik Ramfelt, Koichi Fujikawa, Red Hat, Inc., Seiji Sogabe,
* Stephen Connolly, Tom Huybrechts, Yahoo! Inc., Alan Harder, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jenkins.tools.test.model;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import java.util.Date;
import java.util.List;
/**
* POJO storing a plugin compatibiliy test result
* @author Frederic Camblor
*/
public class PluginCompatResult implements Comparable<PluginCompatResult> {
public final MavenCoordinates coreCoordinates;
public final TestStatus status;
public final Date compatTestExecutedOn;
public final String errorMessage;
public final List<String> warningMessages;
private String buildLogPath = "";
public PluginCompatResult(MavenCoordinates coreCoordinates, TestStatus status,
String errorMessage, List<String> warningMessages,
String buildLogPath){
// Create new result with current date
this(coreCoordinates, status, errorMessage, warningMessages, buildLogPath, new Date());
}
public PluginCompatResult(MavenCoordinates coreCoordinates, TestStatus status,
String errorMessage, List<String> warningMessages,
String buildLogPath, Date compatTestExecutedOn){
this.coreCoordinates = coreCoordinates;
this.status = status;
this.errorMessage = errorMessage;
this.warningMessages = warningMessages;
this.buildLogPath = buildLogPath;
this.compatTestExecutedOn = compatTestExecutedOn;
}
public boolean equals(Object o){
if(o==null || !(o instanceof PluginCompatResult)){
return false;
}
PluginCompatResult res = (PluginCompatResult)o;
return new EqualsBuilder().append(coreCoordinates, res.coreCoordinates).isEquals();
}
public int hashCode(){
return new HashCodeBuilder().append(coreCoordinates).toHashCode();
}
public int compareTo(PluginCompatResult o) {
return coreCoordinates.compareTo(o.coreCoordinates);
}
public String getBuildLogPath() {
return buildLogPath;
}
public void setBuildLogPath(String buildLogPath) {
this.buildLogPath = buildLogPath;
}
}
|
plugins-compat-tester-model/src/main/java/org/jenkins/tools/test/model/PluginCompatResult.java
|
/*
* The MIT License
*
* Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi,
* Erik Ramfelt, Koichi Fujikawa, Red Hat, Inc., Seiji Sogabe,
* Stephen Connolly, Tom Huybrechts, Yahoo! Inc., Alan Harder, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jenkins.tools.test.model;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import java.util.Date;
import java.util.List;
/**
* POJO storing a plugin compatibiliy test result
* @author Frederic Camblor
*/
public class PluginCompatResult implements Comparable<PluginCompatResult> {
public final MavenCoordinates coreCoordinates;
public final TestStatus status;
public final Date compatTestExecutedOn;
public final String errorMessage;
public final List<String> warningMessages;
private String buildLogPath = "";
public PluginCompatResult(MavenCoordinates coreCoordinates, TestStatus status,
String errorMessage, List<String> warningMessages,
String buildLogPath){
this.coreCoordinates = coreCoordinates;
this.status = status;
this.errorMessage = errorMessage;
this.warningMessages = warningMessages;
this.buildLogPath = buildLogPath;
this.compatTestExecutedOn = new Date(); // now !
}
public boolean equals(Object o){
if(o==null || !(o instanceof PluginCompatResult)){
return false;
}
PluginCompatResult res = (PluginCompatResult)o;
return new EqualsBuilder().append(coreCoordinates, res.coreCoordinates).isEquals();
}
public int hashCode(){
return new HashCodeBuilder().append(coreCoordinates).toHashCode();
}
public int compareTo(PluginCompatResult o) {
return coreCoordinates.compareTo(o.coreCoordinates);
}
public String getBuildLogPath() {
return buildLogPath;
}
public void setBuildLogPath(String buildLogPath) {
this.buildLogPath = buildLogPath;
}
}
|
Added PluginCompatResult constructor allowing to provide a date instead of setting it to "now"
|
plugins-compat-tester-model/src/main/java/org/jenkins/tools/test/model/PluginCompatResult.java
|
Added PluginCompatResult constructor allowing to provide a date instead of setting it to "now"
|
<ide><path>lugins-compat-tester-model/src/main/java/org/jenkins/tools/test/model/PluginCompatResult.java
<ide> public PluginCompatResult(MavenCoordinates coreCoordinates, TestStatus status,
<ide> String errorMessage, List<String> warningMessages,
<ide> String buildLogPath){
<add> // Create new result with current date
<add> this(coreCoordinates, status, errorMessage, warningMessages, buildLogPath, new Date());
<add> }
<add> public PluginCompatResult(MavenCoordinates coreCoordinates, TestStatus status,
<add> String errorMessage, List<String> warningMessages,
<add> String buildLogPath, Date compatTestExecutedOn){
<ide> this.coreCoordinates = coreCoordinates;
<ide>
<ide> this.status = status;
<ide>
<ide> this.buildLogPath = buildLogPath;
<ide>
<del> this.compatTestExecutedOn = new Date(); // now !
<add> this.compatTestExecutedOn = compatTestExecutedOn;
<ide> }
<ide>
<ide> public boolean equals(Object o){
|
|
Java
|
apache-2.0
|
c19cbfd5a3844913c43615879aa60c4e8ecb0c64
| 0 |
Xlythe/CameraView
|
package com.xlythe.view.camera.v2;
import android.Manifest;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.params.MeteringRectangle;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresPermission;
import android.util.Log;
import android.view.Surface;
import com.xlythe.view.camera.CameraView;
import com.xlythe.view.camera.ICameraModule;
import java.io.File;
import java.util.List;
/**
* A wrapper around the Camera2 APIs. Camera2 has some peculiarities, such as crashing if you attach
* too many surfaces (or too large a surface) to a capture session. To get around that, we define
* {@link Session}s that list out compatible surfaces and creates capture requests for them.
*/
@TargetApi(21)
public class Camera2Module extends ICameraModule {
/**
* This is how we'll talk to the camera.
*/
private final CameraManager mCameraManager;
/**
* This is the id of the camera (eg. front or back facing) that we're currently using.
*/
private String mActiveCamera;
/**
* The current capture session. There is one capture session per {@link Session}.
*/
private CameraCaptureSession mCaptureSession;
/**
* The currently active camera. This may be a front facing camera or a back facing one.
*/
private CameraDevice mCameraDevice;
/**
* A background thread to receive callbacks from the camera on.
*/
private HandlerThread mBackgroundThread;
/**
* A handler pointing to the background thread.
*/
private Handler mBackgroundHandler;
/**
* The currently active session. See {@link PictureSession} and {@link VideoSession}.
*/
private Session mActiveSession;
/**
* Callbacks for when the camera is available / unavailable
*/
private final CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback() {
@Override
public void onOpened(@NonNull CameraDevice cameraDevice) {
// The camera has opened. Start the preview now.
synchronized (Camera2Module.this) {
mCameraDevice = cameraDevice;
setSession(new PictureSession(Camera2Module.this));
}
}
@Override
public void onDisconnected(@NonNull CameraDevice cameraDevice) {
Log.w(TAG, "Camera disconnected");
synchronized (Camera2Module.this) {
cameraDevice.close();
mCameraDevice = null;
mBackgroundHandler.removeCallbacksAndMessages(null);
}
}
@Override
public void onError(@NonNull CameraDevice cameraDevice, int error) {
Log.e(TAG, "Camera crashed: " + error);
onDisconnected(cameraDevice);
}
};
public Camera2Module(CameraView cameraView) {
super(cameraView);
mCameraManager = (CameraManager) getContext().getSystemService(Context.CAMERA_SERVICE);
}
private synchronized void setSession(final Session session) {
if (mCameraDevice == null) {
return;
}
// Clean up any previous sessions
if (mCaptureSession != null) {
mCaptureSession.close();
mCaptureSession = null;
}
if (mActiveSession != null) {
mActiveSession.close();
mActiveSession = null;
}
try {
// Assume this is a brand new session that's never been set up. Initialize it so that
// it can decide what size to set its surfaces to.
CameraCharacteristics characteristics = mCameraManager.getCameraCharacteristics(mActiveCamera);
StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
session.initialize(map);
// Now, with all of our surfaces, we'll ask for a new session
mCameraDevice.createCaptureSession(session.getSurfaces(), new CameraCaptureSession.StateCallback() {
@Override
public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
synchronized (Camera2Module.this) {
if (mCameraDevice == null) {
return;
}
try {
mCaptureSession = cameraCaptureSession;
mActiveSession = session;
session.onAvailable(mCameraDevice, mCaptureSession);
} catch (CameraAccessException | IllegalStateException | IllegalArgumentException | NullPointerException e) {
e.printStackTrace();
}
}
}
@Override
public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
Log.e(TAG, "Configure failed");
}
}, mBackgroundHandler);
} catch (CameraAccessException | IllegalStateException | IllegalArgumentException | NullPointerException e) {
// Crashes if the Camera is interacted with while still loading
e.printStackTrace();
}
}
@RequiresPermission(Manifest.permission.CAMERA)
@Override
public void open() {
startBackgroundThread();
try {
mActiveCamera = getActiveCamera();
mCameraManager.openCamera(mActiveCamera, mStateCallback, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
@Override
public void close() {
if (mCaptureSession != null) {
mCaptureSession.close();
mCaptureSession = null;
}
if (mActiveSession != null) {
mActiveSession.close();
mActiveSession = null;
}
if (mCameraDevice != null) {
mCameraDevice.close();
mCameraDevice = null;
}
stopBackgroundThread();
}
@Override
public boolean hasFrontFacingCamera() {
try {
for (String cameraId : mCameraManager.getCameraIdList()) {
boolean frontFacing = isFrontFacing(cameraId);
if (frontFacing) return true;
}
} catch (CameraAccessException e) {
e.printStackTrace();
}
return false;
}
@Override
public boolean isUsingFrontFacingCamera() {
try {
return isFrontFacing(getActiveCamera());
} catch (CameraAccessException e) {
e.printStackTrace();
}
return false;
}
@RequiresPermission(Manifest.permission.CAMERA)
@Override
public void toggleCamera() {
int position = 0;
try {
for (String cameraId : mCameraManager.getCameraIdList()) {
if (cameraId.equals(mActiveCamera)) {
break;
}
position++;
}
close();
mActiveCamera = mCameraManager.getCameraIdList()[(position + 1) % mCameraManager.getCameraIdList().length];
open();
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
@Override
public void focus(Rect focus, Rect metering) {
try {
if (!supportsFocus(getActiveCamera())) {
Log.w(TAG, "Focus not available on this camera");
return;
}
if (mActiveSession == null) {
Log.w(TAG, "No active session available");
return;
}
// Our metering Rect ranges from -1000 to 1000. We need to remap it to fit the camera dimensions (0 to width).
CameraCharacteristics characteristics = mCameraManager.getCameraCharacteristics(getActiveCamera());
Rect arraySize = characteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE);
if (arraySize == null) {
Log.w(TAG, "Unable to load the active array size");
return;
}
resize(metering, arraySize.width(), arraySize.height());
// Now we can update our request
mActiveSession.setMeteringRectangle(new MeteringRectangle(metering, MeteringRectangle.METERING_WEIGHT_MAX));
mActiveSession.onInvalidate(mCameraDevice, mCaptureSession);
} catch (CameraAccessException | NullPointerException e) {
// Crashes if the Camera is interacted with while still loading
e.printStackTrace();
}
}
/**
* Resizes a Rect from its original dimensions of -1000 to 1000 to 0 to width/height.
*/
private static void resize(Rect metering, int maxWidth, int maxHeight) {
// We can calculate the new width by scaling it to its new dimensions
int newWidth = metering.width() * maxWidth / 2000;
int newHeight = metering.height() * maxHeight / 2000;
// Then we calculate how far from the top/left corner it should be
int leftOffset = (metering.left + 1000) * maxWidth / 2000;
int topOffset = (metering.top + 1000) * maxHeight / 2000;
// And now we can resize the Rect to its new dimensions
metering.left = leftOffset;
metering.top = topOffset;
metering.right = metering.left + newWidth;
metering.bottom = metering.top + newHeight;
}
@Override
public void takePicture(File file) {
if (mActiveSession != null && mActiveSession instanceof PictureSession) {
PictureSession pictureSession = (PictureSession) mActiveSession;
pictureSession.takePicture(file, mCameraDevice, mCaptureSession);
}
}
@RequiresPermission(Manifest.permission.RECORD_AUDIO)
@Override
public void startRecording(File file) {
setSession(new VideoSession(this, file));
}
@Override
public void stopRecording() {
setSession(new PictureSession(this));
}
@Override
public boolean isRecording() {
return mActiveSession != null && mActiveSession instanceof VideoSession;
}
void transformPreview(int previewWidth, int previewHeight) throws CameraAccessException {
int viewWidth = getWidth();
int viewHeight = getHeight();
int displayOrientation = getDisplayRotation();
int cameraOrientation = getSensorOrientation(getActiveCamera());
if (DEBUG) {
Log.d(TAG, String.format("Configuring SurfaceView matrix: "
+ "viewWidth=%s, viewHeight=%s, previewWidth=%s, previewHeight=%s, displayOrientation=%s, cameraOrientation=%s",
viewWidth, viewHeight, previewWidth, previewHeight, displayOrientation, cameraOrientation));
}
Matrix matrix = new Matrix();
getTransform(matrix);
// Camera2 reverses the preview width/height. Why? No idea.
if (cameraOrientation != 0 && cameraOrientation != 180) {
int temp = previewWidth;
previewWidth = previewHeight;
previewHeight = temp;
}
double aspectRatio = (double) previewHeight / (double) previewWidth;
int newWidth, newHeight;
if (viewHeight > viewWidth * aspectRatio) {
newWidth = (int) (viewHeight / aspectRatio);
newHeight = viewHeight;
} else {
newWidth = viewWidth;
newHeight = (int) (viewWidth * aspectRatio);
}
float scaleX = (float) newWidth / (float) viewWidth;
float scaleY = (float) newHeight / (float) viewHeight;
int translateX = (viewWidth - newWidth) / 2;
int translateY = (viewHeight - newHeight) / 2;
int rotation = -displayOrientation;
matrix.setScale(scaleX, scaleY);
matrix.postTranslate(translateX, translateY);
matrix.postRotate(rotation, viewWidth / 2, viewHeight / 2);
if (DEBUG) {
Log.d(TAG, String.format("Result: aspectRatio=%s, scaleX=%s, scaleY=%s, translateX=%s, translateY=%s, rotation=%s",
aspectRatio, scaleX, scaleY, translateX, translateY, rotation));
}
setTransform(matrix);
}
@Override
protected int getRelativeCameraOrientation() {
try {
return getRelativeImageOrientation(getDisplayRotation(), getSensorOrientation(getActiveCamera()), isUsingFrontFacingCamera(), false);
} catch (CameraAccessException e) {
e.printStackTrace();
return 0;
}
}
private String getActiveCamera() throws CameraAccessException {
return mActiveCamera == null ? getDefaultCamera() : mActiveCamera;
}
private String getDefaultCamera() throws CameraAccessException {
for (String cameraId : mCameraManager.getCameraIdList()) {
if (isBackFacing(cameraId)) {
return cameraId;
}
}
return mCameraManager.getCameraIdList()[0];
}
private boolean supportsFocus(String cameraId) throws CameraAccessException {
CameraCharacteristics characteristics = mCameraManager.getCameraCharacteristics(cameraId);
Integer maxRegions = characteristics.get(CameraCharacteristics.CONTROL_MAX_REGIONS_AF);
return maxRegions != null && maxRegions >= 1;
}
private boolean isFrontFacing(String cameraId) throws CameraAccessException {
CameraCharacteristics characteristics = mCameraManager.getCameraCharacteristics(cameraId);
Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
return facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT;
}
private boolean isBackFacing(String cameraId) throws CameraAccessException {
CameraCharacteristics characteristics = mCameraManager.getCameraCharacteristics(cameraId);
Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
return facing != null && facing == CameraCharacteristics.LENS_FACING_BACK;
}
private int getSensorOrientation(String cameraId) throws CameraAccessException {
CameraCharacteristics characteristics = mCameraManager.getCameraCharacteristics(cameraId);
Integer orientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
return orientation == null ? 0 : orientation;
}
private void startBackgroundThread() {
mBackgroundThread = new HandlerThread("CameraBackground");
mBackgroundThread.start();
mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
}
private void stopBackgroundThread() {
if (mBackgroundThread == null) {
return;
}
mBackgroundThread.quitSafely();
try {
mBackgroundThread.join();
mBackgroundThread = null;
mBackgroundHandler = null;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Handler getBackgroundHandler() {
return mBackgroundHandler;
}
/**
* A session has multiple surfaces for the camera to draw to.
*/
interface Session {
void initialize(StreamConfigurationMap map) throws CameraAccessException;
List<Surface> getSurfaces();
void setMeteringRectangle(MeteringRectangle meteringRectangle);
void onAvailable(CameraDevice cameraDevice, CameraCaptureSession session) throws CameraAccessException;
void onInvalidate(CameraDevice cameraDevice, CameraCaptureSession session) throws CameraAccessException;
void close();
}
}
|
camera-view/src/main/java/com/xlythe/view/camera/v2/Camera2Module.java
|
package com.xlythe.view.camera.v2;
import android.Manifest;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.params.MeteringRectangle;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresPermission;
import android.util.Log;
import android.view.Surface;
import com.xlythe.view.camera.CameraView;
import com.xlythe.view.camera.ICameraModule;
import java.io.File;
import java.util.List;
/**
* A wrapper around the Camera2 APIs. Camera2 has some peculiarities, such as crashing if you attach
* too many surfaces (or too large a surface) to a capture session. To get around that, we define
* {@link Session}s that list out compatible surfaces and creates capture requests for them.
*/
@TargetApi(21)
public class Camera2Module extends ICameraModule {
/**
* This is how we'll talk to the camera.
*/
private final CameraManager mCameraManager;
/**
* This is the id of the camera (eg. front or back facing) that we're currently using.
*/
private String mActiveCamera;
/**
* The current capture session. There is one capture session per {@link Session}.
*/
private CameraCaptureSession mCaptureSession;
/**
* The currently active camera. This may be a front facing camera or a back facing one.
*/
private CameraDevice mCameraDevice;
/**
* A background thread to receive callbacks from the camera on.
*/
private HandlerThread mBackgroundThread;
/**
* A handler pointing to the background thread.
*/
private Handler mBackgroundHandler;
/**
* The currently active session. See {@link PictureSession} and {@link VideoSession}.
*/
private Session mActiveSession;
/**
* Callbacks for when the camera is available / unavailable
*/
private final CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback() {
@Override
public void onOpened(@NonNull CameraDevice cameraDevice) {
// The camera has opened. Start the preview now.
synchronized (Camera2Module.this) {
mCameraDevice = cameraDevice;
setSession(new PictureSession(Camera2Module.this));
}
}
@Override
public void onDisconnected(@NonNull CameraDevice cameraDevice) {
Log.w(TAG, "Camera disconnected");
synchronized (Camera2Module.this) {
cameraDevice.close();
mCameraDevice = null;
mBackgroundHandler.removeCallbacksAndMessages(null);
}
}
@Override
public void onError(@NonNull CameraDevice cameraDevice, int error) {
Log.e(TAG, "Camera crashed: " + error);
onDisconnected(cameraDevice);
}
};
public Camera2Module(CameraView cameraView) {
super(cameraView);
mCameraManager = (CameraManager) getContext().getSystemService(Context.CAMERA_SERVICE);
}
private synchronized void setSession(final Session session) {
if (mCameraDevice == null) {
return;
}
// Clean up any previous sessions
if (mCaptureSession != null) {
mCaptureSession.close();
mCaptureSession = null;
}
if (mActiveSession != null) {
mActiveSession.close();
mActiveSession = null;
}
try {
// Assume this is a brand new session that's never been set up. Initialize it so that
// it can decide what size to set its surfaces to.
CameraCharacteristics characteristics = mCameraManager.getCameraCharacteristics(mActiveCamera);
StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
session.initialize(map);
// Now, with all of our surfaces, we'll ask for a new session
mCameraDevice.createCaptureSession(session.getSurfaces(), new CameraCaptureSession.StateCallback() {
@Override
public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
synchronized (Camera2Module.this) {
if (mCameraDevice == null) {
return;
}
try {
mCaptureSession = cameraCaptureSession;
mActiveSession = session;
session.onAvailable(mCameraDevice, mCaptureSession);
} catch (CameraAccessException | IllegalStateException | IllegalArgumentException | NullPointerException e) {
e.printStackTrace();
}
}
}
@Override
public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
Log.e(TAG, "Configure failed");
}
}, mBackgroundHandler);
} catch (CameraAccessException | IllegalStateException | IllegalArgumentException | NullPointerException e) {
// Crashes if the Camera is interacted with while still loading
e.printStackTrace();
}
}
@RequiresPermission(Manifest.permission.CAMERA)
@Override
public void open() {
startBackgroundThread();
try {
mActiveCamera = getActiveCamera();
mCameraManager.openCamera(mActiveCamera, mStateCallback, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
@Override
public void close() {
if (mCaptureSession != null) {
mCaptureSession.close();
mCaptureSession = null;
}
if (mActiveSession != null) {
mActiveSession.close();
mActiveSession = null;
}
if (mCameraDevice != null) {
mCameraDevice.close();
mCameraDevice = null;
}
stopBackgroundThread();
}
@Override
public boolean hasFrontFacingCamera() {
try {
for (String cameraId : mCameraManager.getCameraIdList()) {
boolean frontFacing = isFrontFacing(cameraId);
if (frontFacing) return true;
}
} catch (CameraAccessException e) {
e.printStackTrace();
}
return false;
}
@Override
public boolean isUsingFrontFacingCamera() {
try {
return isFrontFacing(getActiveCamera());
} catch (CameraAccessException e) {
e.printStackTrace();
}
return false;
}
@RequiresPermission(Manifest.permission.CAMERA)
@Override
public void toggleCamera() {
int position = 0;
try {
for (String cameraId : mCameraManager.getCameraIdList()) {
if (cameraId.equals(mActiveCamera)) {
break;
}
position++;
}
close();
mActiveCamera = mCameraManager.getCameraIdList()[(position + 1) % mCameraManager.getCameraIdList().length];
open();
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
@Override
public void focus(Rect focus, Rect metering) {
try {
if (!supportsFocus(getActiveCamera())) {
Log.w(TAG, "Focus not available on this camera");
return;
}
if (mActiveSession == null) {
Log.w(TAG, "No active session available");
return;
}
// Our metering Rect ranges from -1000 to 1000. We need to remap it to fit the camera dimensions (0 to width).
CameraCharacteristics characteristics = mCameraManager.getCameraCharacteristics(getActiveCamera());
Rect arraySize = characteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE);
if (arraySize == null) {
Log.w(TAG, "Unable to load the active array size");
return;
}
resize(metering, arraySize.width(), arraySize.height());
// Now we can update our request
mActiveSession.setMeteringRectangle(new MeteringRectangle(metering, MeteringRectangle.METERING_WEIGHT_MAX));
mActiveSession.onInvalidate(mCameraDevice, mCaptureSession);
} catch (CameraAccessException | NullPointerException e) {
// Crashes if the Camera is interacted with while still loading
e.printStackTrace();
}
}
/**
* Resizes a Rect from its original dimensions of -1000 to 1000 to 0 to width/height.
*/
private static void resize(Rect metering, int maxWidth, int maxHeight) {
// We can calculate the new width by scaling it to its new dimensions
int newWidth = metering.width() * maxWidth / 2000;
int newHeight = metering.height() * maxHeight / 2000;
// Then we calculate how far from the top/left corner it should be
int leftOffset = (metering.left + 1000) * maxWidth / 2000;
int topOffset = (metering.top + 1000) * maxHeight / 2000;
// And now we can resize the Rect to its new dimensions
metering.left = leftOffset;
metering.top = topOffset;
metering.right = metering.left + newWidth;
metering.bottom = metering.top + newHeight;
}
@Override
public void takePicture(File file) {
if (mActiveSession != null && mActiveSession instanceof PictureSession) {
PictureSession pictureSession = (PictureSession) mActiveSession;
pictureSession.takePicture(file, mCameraDevice, mCaptureSession);
}
}
@RequiresPermission(Manifest.permission.RECORD_AUDIO)
@Override
public void startRecording(File file) {
setSession(new VideoSession(this, file));
}
@Override
public void stopRecording() {
setSession(new PictureSession(this));
}
@Override
public boolean isRecording() {
return mActiveSession != null && mActiveSession instanceof VideoSession;
}
void transformPreview(int previewWidth, int previewHeight) throws CameraAccessException {
int viewWidth = getWidth();
int viewHeight = getHeight();
int displayOrientation = getDisplayRotation();
int cameraOrientation = getSensorOrientation(getActiveCamera());
if (DEBUG) {
Log.d(TAG, String.format("Configuring SurfaceView matrix: "
+ "viewWidth=%s, viewHeight=%s, previewWidth=%s, previewHeight=%s, displayOrientation=%s, cameraOrientation=%s",
viewWidth, viewHeight, previewWidth, previewHeight, displayOrientation, cameraOrientation));
}
Matrix matrix = new Matrix();
getTransform(matrix);
// Camera2 tries to be smart, and will rotate the display automatically to portrait mode.
// It, unfortunately, forgets that phones may also be held sideways.
// We'll reverse the preview width/height if the camera did end up being rotated.
if ((displayOrientation == 90 || displayOrientation == 270)
&& (cameraOrientation != 0 && cameraOrientation != 180)) {
int temp = previewWidth;
previewWidth = previewHeight;
previewHeight = temp;
}
double aspectRatio = (double) previewHeight / (double) previewWidth;
int newWidth, newHeight;
if (getHeight() > viewWidth * aspectRatio) {
newWidth = (int) (viewHeight / aspectRatio);
newHeight = viewHeight;
} else {
newWidth = viewWidth;
newHeight = (int) (viewWidth * aspectRatio);
}
float scaleX = (float) newWidth / (float) viewWidth;
float scaleY = (float) newHeight / (float) viewHeight;
int translateX = (viewWidth - newWidth) / 2;
int translateY = (viewHeight - newHeight) / 2;
int rotation = -displayOrientation;
matrix.setScale(scaleX, scaleY);
matrix.postTranslate(translateX, translateY);
matrix.postRotate(rotation, viewWidth / 2, viewHeight / 2);
if (DEBUG) {
Log.d(TAG, String.format("Result: scaleX=%s, scaleY=%s, translateX=%s, translateY=%s, rotation=%s",
scaleX, scaleY, translateX, translateY, rotation));
}
setTransform(matrix);
}
@Override
protected int getRelativeCameraOrientation() {
try {
return getRelativeImageOrientation(getDisplayRotation(), getSensorOrientation(getActiveCamera()), isUsingFrontFacingCamera(), false);
} catch (CameraAccessException e) {
e.printStackTrace();
return 0;
}
}
private String getActiveCamera() throws CameraAccessException {
return mActiveCamera == null ? getDefaultCamera() : mActiveCamera;
}
private String getDefaultCamera() throws CameraAccessException {
for (String cameraId : mCameraManager.getCameraIdList()) {
if (isBackFacing(cameraId)) {
return cameraId;
}
}
return mCameraManager.getCameraIdList()[0];
}
private boolean supportsFocus(String cameraId) throws CameraAccessException {
CameraCharacteristics characteristics = mCameraManager.getCameraCharacteristics(cameraId);
Integer maxRegions = characteristics.get(CameraCharacteristics.CONTROL_MAX_REGIONS_AF);
return maxRegions != null && maxRegions >= 1;
}
private boolean isFrontFacing(String cameraId) throws CameraAccessException {
CameraCharacteristics characteristics = mCameraManager.getCameraCharacteristics(cameraId);
Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
return facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT;
}
private boolean isBackFacing(String cameraId) throws CameraAccessException {
CameraCharacteristics characteristics = mCameraManager.getCameraCharacteristics(cameraId);
Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
return facing != null && facing == CameraCharacteristics.LENS_FACING_BACK;
}
private int getSensorOrientation(String cameraId) throws CameraAccessException {
CameraCharacteristics characteristics = mCameraManager.getCameraCharacteristics(cameraId);
Integer orientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
return orientation == null ? 0 : orientation;
}
private void startBackgroundThread() {
mBackgroundThread = new HandlerThread("CameraBackground");
mBackgroundThread.start();
mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
}
private void stopBackgroundThread() {
if (mBackgroundThread == null) {
return;
}
mBackgroundThread.quitSafely();
try {
mBackgroundThread.join();
mBackgroundThread = null;
mBackgroundHandler = null;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Handler getBackgroundHandler() {
return mBackgroundHandler;
}
/**
* A session has multiple surfaces for the camera to draw to.
*/
interface Session {
void initialize(StreamConfigurationMap map) throws CameraAccessException;
List<Surface> getSurfaces();
void setMeteringRectangle(MeteringRectangle meteringRectangle);
void onAvailable(CameraDevice cameraDevice, CameraCaptureSession session) throws CameraAccessException;
void onInvalidate(CameraDevice cameraDevice, CameraCaptureSession session) throws CameraAccessException;
void close();
}
}
|
fix portrait mode being squished
|
camera-view/src/main/java/com/xlythe/view/camera/v2/Camera2Module.java
|
fix portrait mode being squished
|
<ide><path>amera-view/src/main/java/com/xlythe/view/camera/v2/Camera2Module.java
<ide> Matrix matrix = new Matrix();
<ide> getTransform(matrix);
<ide>
<del> // Camera2 tries to be smart, and will rotate the display automatically to portrait mode.
<del> // It, unfortunately, forgets that phones may also be held sideways.
<del> // We'll reverse the preview width/height if the camera did end up being rotated.
<del> if ((displayOrientation == 90 || displayOrientation == 270)
<del> && (cameraOrientation != 0 && cameraOrientation != 180)) {
<add> // Camera2 reverses the preview width/height. Why? No idea.
<add> if (cameraOrientation != 0 && cameraOrientation != 180) {
<ide> int temp = previewWidth;
<ide> previewWidth = previewHeight;
<ide> previewHeight = temp;
<ide>
<ide> double aspectRatio = (double) previewHeight / (double) previewWidth;
<ide> int newWidth, newHeight;
<del> if (getHeight() > viewWidth * aspectRatio) {
<add> if (viewHeight > viewWidth * aspectRatio) {
<ide> newWidth = (int) (viewHeight / aspectRatio);
<ide> newHeight = viewHeight;
<ide> } else {
<ide> matrix.postRotate(rotation, viewWidth / 2, viewHeight / 2);
<ide>
<ide> if (DEBUG) {
<del> Log.d(TAG, String.format("Result: scaleX=%s, scaleY=%s, translateX=%s, translateY=%s, rotation=%s",
<del> scaleX, scaleY, translateX, translateY, rotation));
<add> Log.d(TAG, String.format("Result: aspectRatio=%s, scaleX=%s, scaleY=%s, translateX=%s, translateY=%s, rotation=%s",
<add> aspectRatio, scaleX, scaleY, translateX, translateY, rotation));
<ide> }
<ide>
<ide> setTransform(matrix);
|
|
JavaScript
|
mit
|
1ea81e75a3c71b6fb56b1249c69cf047e26b3789
| 0 |
arnarthor/dohop-hackathon,arnarthor/dohop-hackathon
|
'use strict';
var superagent = require('superagent');
var config = require('../../config');
var _ = require("lodash");
var moment = require('moment');
exports.index = function(req, res) {
res.send({data: req.params.fromCountry});
};
exports.searchAirport = function(req, res) {
superagent.get(config.api + '/picker/en/' + req.params.airport)
.set('Accept', 'application/json')
.end(function(err, response) {
if (err) {
return res.status(500).send('Something went wrong :(');
}
res.send(JSON.parse(response.text));
});
};
exports.findCheapestFlight = function(travelingInfo, socket) {
var url = '';
// Init the duration and change the departure
if (travelingInfo.flights.length === 0) {
var duration = createStopDuration(travelingInfo.departure.from, travelingInfo.departure.to);
travelingInfo.stopDuration = duration;
console.log('duration', duration);
// Try to find a flight within 3 days of the request.
travelingInfo.departure.to = moment(travelingInfo.departure.from).add(3, 'days');
travelingInfo.endDate = travelingInfo.departure.to;
}
// start going home after 5 days TODO DODISBETTER
if (travelingInfo.stopDuration.totalDays - 5 < moment(travelingInfo.departure.from).diff(moment(travelingInfo.endDate), 'days')) {
console.log('hallo');
travelingInfo.goHome = true;
travelingInfo.departure.to = moment(travelingInfo.departure.to).add(100, 'days').format('YYYY-MM-DD');
console.log(travelingInfo.departure.to + ' wewedw');
console.log(travelingInfo.departure.from);
console.log('bla' + moment(travelingInfo.departure.to).diff(moment(travelingInfo.endDate), 'days'));
}
if (travelingInfo.goHome) {
url = [
config.api,
'livestore',
'en',
travelingInfo.departure.country,
'per-airport',
travelingInfo.departure.airportCode,
travelingInfo.startingPoint.airportCode,
travelingInfo.departure.from,
travelingInfo.departure.to
].join('/') + '?currency=USD&stay=1-365&include_split=true&airport-format=full&fare-format=full&id=H4cK3r';
} else {
url = [
config.api,
'livestore',
'en',
travelingInfo.departure.country,
'per-country',
travelingInfo.departure.airportCode,
travelingInfo.departure.from,
travelingInfo.departure.to
].join('/') + '?currency=USD&airport-format=full&fare-format=full&id=H4cK3r';
}
console.log(url);
superagent.get(url)
.end(function(err, response) {
if (err) {
socket.emit('error', 'something went wrong in the socket');
return;
}
var responseData = JSON.parse(response.text);
var fares = responseData.fares;
var airports = responseData.airports;
var cheapest = 0;
var countries = _.map(travelingInfo.flights, function(item) {
return item['departureCountry'].country;
});
//check if we have travled there before
for (;!travelingInfo.goHome && cheapest < fares.length; cheapest++) {
if (countries.indexOf(airports[fares[cheapest].b].cc_c) > -1) {
continue;
}
if (findDistance(airports[fares[cheapest].a].lat,airports[fares[cheapest].a].lon,airports[fares[cheapest].b].lat,airports[fares[cheapest].b].lon)<config.minDistance){
continue;
}
break;
};
console.log(fares.length)
//go home
if (travelingInfo.flights.length && fares.length === cheapest) {
console.log("home")
socket.emit('go-home', true);
return;
}
//HANDLE EDGE CASE IF NO FLIGHT IS HOME HERE
var cheapestFlight = fares[cheapest];
if (fares.length) {
//console.log(fares[chosenIndex])
//MABY NO FLIGHT TO ICELAND HERE
console.log(travelingInfo.departure);
var travelInfo = {
fromAirport: cheapestFlight.a,
destAirport: cheapestFlight.b,
price: cheapestFlight.conv_fare,
departure: cheapestFlight.d1,
departureCountry: travelingInfo.departure,
stopDuration: travelingInfo.stopDuration,
endDate:travelingInfo.endDate,
};
if (airports[cheapestFlight.b]) {
travelInfo.arrivalCountry = {
airportCode: airports[cheapestFlight.b].a_i,
airportName: airports[cheapestFlight.b].a_n,
countryCode: airports[cheapestFlight.b].cc_c,
countryName: airports[cheapestFlight.b].cc_n,
city: airports[cheapestFlight.b].ci_n,
lat: airports[cheapestFlight.b].lat,
lon: airports[cheapestFlight.b].lon,
state: airports[cheapestFlight.b].r_n,
state_short: airports[cheapestFlight.b].r_c,
};
}
socket.emit('new-flight', travelInfo);
}
//whattodo
else{
}
});
};
function findDistance(lat1,lon1,lat2,lon2){
//HAVERSIN FORMULA
var dLat = deg2rad(lat2-lat1);
var dLon = deg2rad(lon2-lon1);
var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.sin(dLon/2) * Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = config.earthRadius * c; //distance in km
return d;
}
function deg2rad(deg) {
return deg * (Math.PI/180);
}
//derp
function createStopDuration(startDate, endDate){
var days = moment(endDate).diff(moment(startDate),'days');
var duration = {
lowBound: '',
highBound: '',
totalDays: days,
};
if (days >= 24*7) {
duration.lowBound = 7;
duration.highBound = 21;
} else if (days >=12*7) {
duration.lowBound = 5;
duration.highBound = 10;
} else if (days >= 4*7) {
duration.lowBound = 3;
duration.highBound = 8;
} else {
duration.lowBound = 2;
duration.highBound = 4;
}
return duration;
};
|
server/routes/flights/flight-controller.js
|
'use strict';
var superagent = require('superagent');
var config = require('../../config');
var _ = require("lodash");
var moment = require('moment');
exports.index = function(req, res) {
res.send({data: req.params.fromCountry});
};
exports.searchAirport = function(req, res) {
superagent.get(config.api + '/picker/en/' + req.params.airport)
.set('Accept', 'application/json')
.end(function(err, response) {
if (err) {
return res.status(500).send('Something went wrong :(');
}
res.send(JSON.parse(response.text));
});
};
exports.findCheapestFlight = function(travelingInfo, socket) {
var url = '';
//Init the duration and change the departure
if (travelingInfo.flights.length === 0){
var duration = createStopDuration(travelingInfo.departure.from,travelingInfo.departure.to);
travelingInfo.stopDuration = duration;
console.log('duration', duration);
//FLY ON THE DAY THAT HE WANTS
travelingInfo.departure.to = travelingInfo.departure.from;
travelingInfo.endDate = travelingInfo.departure.to;
}
//start going home after 5 days TODO DODISBETTER
if(travelingInfo.stopDuration.totalDays-5<moment(travelingInfo.departure.from).diff(moment(travelingInfo.endDate),'days')){
console.log("hallo")
travelingInfo.goHome = true;
travelingInfo.departure.to = moment(travelingInfo.departure.to).add(100,'days').format('YYYY-MM-DD')
console.log(travelingInfo.departure.to + " wewedw");
console.log(travelingInfo.departure.from)
console.log("bla" + moment(travelingInfo.departure.to).diff(moment(travelingInfo.endDate),'days'));
};
if (travelingInfo.goHome) {
url = [
config.api,
'livestore',
'en',
travelingInfo.departure.country,
'per-airport',
travelingInfo.departure.airportCode,
travelingInfo.startingPoint.airportCode,
travelingInfo.departure.from,
travelingInfo.departure.to
].join('/') + '?currency=USD&stay=1-365&include_split=true&airport-format=full&fare-format=full&id=H4cK3r';
} else {
url = [
config.api,
'livestore',
'en',
travelingInfo.departure.country,
'per-country',
travelingInfo.departure.airportCode,
travelingInfo.departure.from,
travelingInfo.departure.to
].join('/') + '?currency=USD&airport-format=full&fare-format=full&id=H4cK3r';
}
superagent.get(url)
.end(function(err, response) {
if (err) {
socket.emit('error', 'something went wrong in the socket');
return;
}
var responseData = JSON.parse(response.text);
var fares = responseData.fares;
var airports = responseData.airports;
var cheapest = 0;
var countries = _.map(travelingInfo.flights, function(item) {
return item['departureCountry'].country;
});
//check if we have travled there before
for (;!travelingInfo.goHome && cheapest < fares.length; cheapest++) {
if (countries.indexOf(airports[fares[cheapest].b].cc_c) > -1) {
continue;
}
if (findDistance(airports[fares[cheapest].a].lat,airports[fares[cheapest].a].lon,airports[fares[cheapest].b].lat,airports[fares[cheapest].b].lon)<config.minDistance){
continue;
}
break;
};
console.log(fares.length)
//go home
if (travelingInfo.flights.length && fares.length === cheapest) {
console.log("home")
socket.emit('go-home', true);
return;
}
//HANDLE EDGE CASE IF NO FLIGHT IS HOME HERE
var cheapestFlight = fares[cheapest];
if (fares.length) {
//console.log(fares[chosenIndex])
//MABY NO FLIGHT TO ICELAND HERE
console.log(travelingInfo.departure);
var travelInfo = {
fromAirport: cheapestFlight.a,
destAirport: cheapestFlight.b,
price: cheapestFlight.conv_fare,
departure: cheapestFlight.d1,
departureCountry: travelingInfo.departure,
stopDuration: travelingInfo.stopDuration,
endDate:travelingInfo.endDate,
};
if (airports[cheapestFlight.b]) {
travelInfo.arrivalCountry = {
airportCode: airports[cheapestFlight.b].a_i,
airportName: airports[cheapestFlight.b].a_n,
countryCode: airports[cheapestFlight.b].cc_c,
countryName: airports[cheapestFlight.b].cc_n,
city: airports[cheapestFlight.b].ci_n,
lat: airports[cheapestFlight.b].lat,
lon: airports[cheapestFlight.b].lon,
state: airports[cheapestFlight.b].r_n,
state_short: airports[cheapestFlight.b].r_c,
};
}
socket.emit('new-flight', travelInfo);
}
//whattodo
else{
}
});
};
function findDistance(lat1,lon1,lat2,lon2){
//HAVERSIN FORMULA
var dLat = deg2rad(lat2-lat1);
var dLon = deg2rad(lon2-lon1);
var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.sin(dLon/2) * Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = config.earthRadius * c; //distance in km
return d;
}
function deg2rad(deg) {
return deg * (Math.PI/180);
}
//derp
function createStopDuration(startDate, endDate){
var days = moment(endDate).diff(moment(startDate),'days');
var duration = {
lowBound: '',
highBound: '',
totalDays: days,
};
if (days >= 24*7) {
duration.lowBound = 7;
duration.highBound = 21;
} else if (days >=12*7) {
duration.lowBound = 5;
duration.highBound = 10;
} else if (days >= 4*7) {
duration.lowBound = 3;
duration.highBound = 8;
} else {
duration.lowBound = 2;
duration.highBound = 4;
}
return duration;
};
|
Search for flights within 3 days of request
|
server/routes/flights/flight-controller.js
|
Search for flights within 3 days of request
|
<ide><path>erver/routes/flights/flight-controller.js
<ide> exports.findCheapestFlight = function(travelingInfo, socket) {
<ide> var url = '';
<ide>
<del> //Init the duration and change the departure
<del> if (travelingInfo.flights.length === 0){
<del> var duration = createStopDuration(travelingInfo.departure.from,travelingInfo.departure.to);
<del>
<del> travelingInfo.stopDuration = duration;
<del> console.log('duration', duration);
<del>
<del> //FLY ON THE DAY THAT HE WANTS
<del> travelingInfo.departure.to = travelingInfo.departure.from;
<del> travelingInfo.endDate = travelingInfo.departure.to;
<del> }
<del>
<del>
<del> //start going home after 5 days TODO DODISBETTER
<del> if(travelingInfo.stopDuration.totalDays-5<moment(travelingInfo.departure.from).diff(moment(travelingInfo.endDate),'days')){
<del> console.log("hallo")
<add> // Init the duration and change the departure
<add> if (travelingInfo.flights.length === 0) {
<add> var duration = createStopDuration(travelingInfo.departure.from, travelingInfo.departure.to);
<add>
<add> travelingInfo.stopDuration = duration;
<add> console.log('duration', duration);
<add>
<add> // Try to find a flight within 3 days of the request.
<add> travelingInfo.departure.to = moment(travelingInfo.departure.from).add(3, 'days');
<add> travelingInfo.endDate = travelingInfo.departure.to;
<add> }
<add>
<add>
<add> // start going home after 5 days TODO DODISBETTER
<add> if (travelingInfo.stopDuration.totalDays - 5 < moment(travelingInfo.departure.from).diff(moment(travelingInfo.endDate), 'days')) {
<add> console.log('hallo');
<ide> travelingInfo.goHome = true;
<del> travelingInfo.departure.to = moment(travelingInfo.departure.to).add(100,'days').format('YYYY-MM-DD')
<del> console.log(travelingInfo.departure.to + " wewedw");
<del> console.log(travelingInfo.departure.from)
<del> console.log("bla" + moment(travelingInfo.departure.to).diff(moment(travelingInfo.endDate),'days'));
<del>
<del>
<del> };
<del>
<add> travelingInfo.departure.to = moment(travelingInfo.departure.to).add(100, 'days').format('YYYY-MM-DD');
<add> console.log(travelingInfo.departure.to + ' wewedw');
<add> console.log(travelingInfo.departure.from);
<add> console.log('bla' + moment(travelingInfo.departure.to).diff(moment(travelingInfo.endDate), 'days'));
<add> }
<add>
<ide>
<ide>
<ide>
<ide> travelingInfo.departure.to
<ide> ].join('/') + '?currency=USD&airport-format=full&fare-format=full&id=H4cK3r';
<ide> }
<add> console.log(url);
<ide> superagent.get(url)
<ide> .end(function(err, response) {
<ide> if (err) {
<ide>
<ide>
<ide> //check if we have travled there before
<del> for (;!travelingInfo.goHome && cheapest < fares.length; cheapest++) {
<del>
<del>
<del> if (countries.indexOf(airports[fares[cheapest].b].cc_c) > -1) {
<add> for (;!travelingInfo.goHome && cheapest < fares.length; cheapest++) {
<add>
<add>
<add> if (countries.indexOf(airports[fares[cheapest].b].cc_c) > -1) {
<ide> continue;
<ide> }
<ide>
<ide> };
<ide>
<ide> console.log(fares.length)
<del> //go home
<add> //go home
<ide> if (travelingInfo.flights.length && fares.length === cheapest) {
<ide> console.log("home")
<ide> socket.emit('go-home', true);
<ide> return;
<ide> }
<ide>
<del>
<add>
<ide> //HANDLE EDGE CASE IF NO FLIGHT IS HOME HERE
<ide>
<ide>
<ide> if (days >= 24*7) {
<ide> duration.lowBound = 7;
<ide> duration.highBound = 21;
<del> } else if (days >=12*7) {
<add> } else if (days >=12*7) {
<ide> duration.lowBound = 5;
<ide> duration.highBound = 10;
<ide> } else if (days >= 4*7) {
|
|
Java
|
bsd-3-clause
|
187e249f487a4ec99a3ee6c5834763b9c1ae670e
| 0 |
muloem/xins,muloem/xins,muloem/xins
|
/*
* $Id$
*/
package org.xins.server;
import java.util.HashMap;
import java.util.Map;
import org.xins.util.collections.FastStack;
/**
* Response validator that just performs some common checks. The following
* checks are performed:
*
* <ul>
* <li>No duplicate parameter names
* <li>No duplicate attribute names
* </ul>
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:[email protected]">[email protected]</a>)
*
* @since XINS 0.50
*/
public class BasicResponseValidator
extends Object
implements ResponseValidator {
//-------------------------------------------------------------------------
// Class fields
//-------------------------------------------------------------------------
/**
* Singleton instance.
*/
public static final BasicResponseValidator SINGLETON = new BasicResponseValidator();
//-------------------------------------------------------------------------
// Class functions
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
// Constructors
//-------------------------------------------------------------------------
/**
* Constructs a new <code>BasicResponseValidator</code>.
*/
protected BasicResponseValidator() {
_threadLocals = new ThreadLocal();
}
//-------------------------------------------------------------------------
// Fields
//-------------------------------------------------------------------------
/**
* Thread-local variables.
*
* <p>Per thread this {@link ThreadLocal} contains a
* {@link Object}<code>[3]</code>, if it is already initialized. If so,
* then the first element is the parameter {@link Map}, the second is the
* attribute {@link Map} and the third is the element {@link FastStack}.
* All are initially <code>null</code>.
*/
private final ThreadLocal _threadLocals;
//-------------------------------------------------------------------------
// Methods
//-------------------------------------------------------------------------
/**
* Gets the 3-size <code>Object[]</code> array for this thread. If there is
* no array yet, then it is created and stored in {@link #_threadLocals}.
*
* @return
* the {@link Object}<code>[]</code> array for this thread, never
* <code>null</code>.
*/
private final Object[] getThreadLocals() {
Object o = _threadLocals.get();
Object[] arr;
if (o == null) {
arr = new Object[3];
_threadLocals.set(arr);
} else {
arr = (Object[]) o;
}
return arr;
}
/**
* Cleans up the current response.
*/
private final void reset() {
Object o = _threadLocals.get();
if (o != null) {
Object[] arr = (Object[]) o;
// Clean the parameter map, if any
o = arr[0];
if (o != null) {
((Map) o).clear();
}
// Clean the attribute map, if any
o = arr[1];
if (o != null) {
((Map) o).clear();
}
// Clean the stack, if any
o = arr[2];
if (o != null) {
((FastStack) o).clear();
}
}
}
private final void resetAttributes() {
Object o = _threadLocals.get();
if (o != null) {
Object[] arr = (Object[]) o;
o = arr[1];
if (o != null) {
((Map) o).clear();
}
}
}
/**
* Gets the parameter <code>Map</code> for the current response. If there
* is none, then one will be created and stored.
*
* @return
* the parameter {@link Map}, never <code>null</code>.
*/
protected final Map getParameters() {
// Get the 3-size Map array
Object[] arr = getThreadLocals();
// Get the parameter Map
Object o = arr[0];
Map parameters;
if (o == null) {
parameters = new HashMap();
arr[0] = parameters;
} else {
parameters = (Map) o;
}
return parameters;
}
/**
* Gets the attributes <code>Map</code> for the current element. If there
* is none, then one will be created and stored.
*
* @return
* the attributes {@link Map}, never <code>null</code>.
*/
protected final Map getAttributes() {
// Get the 3-size Map array
Object[] arr = getThreadLocals();
// Get the attributes Map
Object o = arr[1];
Map attributes;
if (o == null) {
attributes = new HashMap();
arr[1] = attributes;
} else {
attributes = (Map) o;
}
return attributes;
}
/**
* Gets the element stack for the current response. If there is none, then
* one will be created and stored.
*
* @return
* the {@link FastStack} with the element names, never
* <code>null</code>.
*/
protected final FastStack getElements() {
// Get the 3-size Map array
Object[] arr = getThreadLocals();
// Get the stack of elements
Object o = arr[2];
FastStack elements;
if (o == null) {
elements = new FastStack(3);
arr[2] = elements;
} else {
elements = (FastStack) arr[2];
}
return elements;
}
/**
* Fails with an <code>InvalidResponseException</code> after cleaning up.
* Subclasses should use this method if they find that the response is
* invalid.
*
* @param message
* the message, can be <code>null</code>.
*
* @throws InvalidResponseException
* always thrown, right after cleanup is performed.
*/
protected final void fail(String message)
throws InvalidResponseException {
reset();
throw new InvalidResponseException(message);
}
public final void startResponse(boolean success, String code)
throws InvalidResponseException {
// Reset in case endResponse() or cancelResponse() were not called
reset();
boolean succeeded = false;
try {
startResponseImpl(success, code);
succeeded = true;
} finally {
// If an exception is thrown, then reset, just in case the subclass
// threw something other than an InvalidResponseException
if (succeeded == false) {
reset();
}
}
}
protected void startResponseImpl(boolean success, String code)
throws InvalidResponseException {
// empty
}
public final void param(String name, String value)
throws InvalidResponseException {
Map parameters = getParameters();
Object o = parameters.get(name);
if (o != null) {
fail("Duplicate parameter named \"" + name + "\".");
}
boolean succeeded = false;
try {
paramImpl(name, value);
succeeded = true;
} finally {
// If an exception is thrown, then reset, just in case the subclass
// threw something other than an InvalidResponseException
if (succeeded == false) {
reset();
}
}
parameters.put(name, value);
}
protected void paramImpl(String name, String value)
throws InvalidResponseException {
// empty
}
public final void startTag(String name)
throws InvalidResponseException {
resetAttributes();
boolean succeeded = false;
try {
startTagImpl(name);
succeeded = true;
} finally {
// If an exception is thrown, then reset, just in case the subclass
// threw something other than an InvalidResponseException
if (succeeded == false) {
reset();
}
}
getElements().push(name);
}
protected void startTagImpl(String name)
throws InvalidResponseException {
// empty
}
public final void attribute(String name, String value)
throws InvalidResponseException {
Map attributes = getAttributes();
if (attributes.containsKey(name)) {
String element = (String) getElements().peek();
fail("Duplicate attribute named \"" + name + "\" for element named \"" + element + "\".");
}
attributes.put(name, value);
}
public final void pcdata(String text)
throws InvalidResponseException {
// empty
}
public final void endTag()
throws InvalidResponseException {
boolean succeeded = false;
try {
endTagImpl(name);
succeeded = true;
} finally {
// If an exception is thrown, then reset, just in case the subclass
// threw something other than an InvalidResponseException
if (succeeded == false) {
reset();
}
}
getElements().pop();
}
protected void endTagImpl()
throws InvalidResponseException {
// empty
}
public final void endResponse()
throws InvalidResponseException {
try {
endResponseImpl();
} finally {
reset();
}
}
protected void endResponseImpl()
throws InvalidResponseException {
// empty
}
public final void cancelResponse() {
try {
cancelResponseImpl();
} finally {
reset();
}
}
protected void cancelResponseImpl() {
// empty
}
}
|
src/java-server-framework/org/xins/server/BasicResponseValidator.java
|
/*
* $Id$
*/
package org.xins.server;
import java.util.HashMap;
import java.util.Map;
import org.xins.util.collections.FastStack;
/**
* Response validator that just performs some common checks. The following
* checks are performed:
*
* <ul>
* <li>No duplicate parameter names
* <li>No duplicate attribute names
* </ul>
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:[email protected]">[email protected]</a>)
*
* @since XINS 0.50
*/
public class BasicResponseValidator
extends Object
implements ResponseValidator {
//-------------------------------------------------------------------------
// Class fields
//-------------------------------------------------------------------------
/**
* Singleton instance.
*/
public static final BasicResponseValidator SINGLETON = new BasicResponseValidator();
//-------------------------------------------------------------------------
// Class functions
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
// Constructors
//-------------------------------------------------------------------------
/**
* Constructs a new <code>BasicResponseValidator</code>.
*/
protected BasicResponseValidator() {
_threadLocals = new ThreadLocal();
}
//-------------------------------------------------------------------------
// Fields
//-------------------------------------------------------------------------
/**
* Thread-local variables.
*
* <p>Per thread this {@link ThreadLocal} contains a
* {@link Object}<code>[3]</code>, if it is already initialized. If so,
* then the first element is the parameter {@link Map}, the second is the
* attribute {@link Map} and the third is the element {@link FastStack}.
* All are initially <code>null</code>.
*/
private final ThreadLocal _threadLocals;
//-------------------------------------------------------------------------
// Methods
//-------------------------------------------------------------------------
/**
* Gets the 3-size <code>Object[]</code> array for this thread. If there is
* no array yet, then it is created and stored in {@link #_threadLocals}.
*
* @return
* the {@link Object}<code>[]</code> array for this thread, never
* <code>null</code>.
*/
private final Object[] getThreadLocals() {
Object o = _threadLocals.get();
Object[] arr;
if (o == null) {
arr = new Object[3];
_threadLocals.set(arr);
} else {
arr = (Object[]) o;
}
return arr;
}
/**
* Cleans up the current response.
*/
private final void reset() {
Object o = _threadLocals.get();
if (o != null) {
Object[] arr = (Object[]) o;
// Clean the parameter map, if any
o = arr[0];
if (o != null) {
((Map) o).clear();
}
// Clean the attribute map, if any
o = arr[1];
if (o != null) {
((Map) o).clear();
}
// Clean the stack, if any
o = arr[2];
if (o != null) {
((FastStack) o).clear();
}
}
}
private final void resetAttributes() {
Object o = _threadLocals.get();
if (o != null) {
Object[] arr = (Object[]) o;
o = arr[1];
if (o != null) {
((Map) o).clear();
}
}
}
/**
* Gets the parameter <code>Map</code> for the current response. If there
* is none, then one will be created and stored.
*
* @return
* the parameter {@link Map}, never <code>null</code>.
*/
protected final Map getParameters() {
// Get the 3-size Map array
Object[] arr = getThreadLocals();
// Get the parameter Map
Object o = arr[0];
Map parameters;
if (o == null) {
parameters = new HashMap();
arr[0] = parameters;
} else {
parameters = (Map) o;
}
return parameters;
}
/**
* Gets the attributes <code>Map</code> for the current element. If there
* is none, then one will be created and stored.
*
* @return
* the attributes {@link Map}, never <code>null</code>.
*/
protected final Map getAttributes() {
// Get the 3-size Map array
Object[] arr = getThreadLocals();
// Get the attributes Map
Object o = arr[1];
Map attributes;
if (o == null) {
attributes = new HashMap();
arr[1] = attributes;
} else {
attributes = (Map) o;
}
return attributes;
}
/**
* Gets the element stack for the current response. If there is none, then
* one will be created and stored.
*
* @return
* the {@link FastStack} with the element names, never
* <code>null</code>.
*/
protected final FastStack getElements() {
// Get the 3-size Map array
Object[] arr = getThreadLocals();
// Get the stack of elements
Object o = arr[2];
FastStack elements;
if (o == null) {
elements = new FastStack(3);
arr[2] = elements;
} else {
elements = (FastStack) arr[2];
}
return elements;
}
/**
* Fails with an <code>InvalidResponseException</code> after cleaning up.
* Subclasses should use this method if they find that the response is
* invalid.
*
* @param message
* the message, can be <code>null</code>.
*
* @throws InvalidResponseException
* always thrown, right after cleanup is performed.
*/
protected final void fail(String message)
throws InvalidResponseException {
reset();
throw new InvalidResponseException(message);
}
public final void startResponse(boolean success, String code)
throws InvalidResponseException {
// Reset in case endResponse() or cancelResponse() were not called
reset();
boolean succeeded = false;
try {
startResponseImpl(success, code);
succeeded = true;
} finally {
// If an exception is thrown, then reset, just in case the subclass
// threw something other than an InvalidResponseException
if (succeeded == false) {
reset();
}
}
}
protected void startResponseImpl(boolean success, String code)
throws InvalidResponseException {
// empty
}
public final void param(String name, String value)
throws InvalidResponseException {
Map parameters = getParameters();
Object o = parameters.get(name);
if (o != null) {
fail("Duplicate parameter named \"" + name + "\".");
}
boolean succeeded = false;
try {
paramImpl(name, value);
succeeded = true;
} finally {
// If an exception is thrown, then reset, just in case the subclass
// threw something other than an InvalidResponseException
if (succeeded == false) {
reset();
}
}
parameters.put(name, value);
}
protected void paramImpl(String name, String value)
throws InvalidResponseException {
// empty
}
public final void startTag(String name)
throws InvalidResponseException {
resetAttributes();
FastStack elements = getElements();
elements.push(name);
}
public final void attribute(String name, String value)
throws InvalidResponseException {
Map attributes = getAttributes();
if (attributes.containsKey(name)) {
String element = (String) getElements().peek();
fail("Duplicate attribute named \"" + name + "\" for element named \"" + element + "\".");
}
attributes.put(name, value);
}
public final void pcdata(String text)
throws InvalidResponseException {
// empty
}
public final void endTag()
throws InvalidResponseException {
FastStack elements = getElements();
String element = (String) elements.pop();
}
public final void endResponse()
throws InvalidResponseException {
try {
endResponseImpl();
} finally {
reset();
}
}
protected void endResponseImpl()
throws InvalidResponseException {
// empty
}
public final void cancelResponse() {
try {
cancelResponseImpl();
} finally {
reset();
}
}
protected void cancelResponseImpl() {
// empty
}
}
|
Added startTagImpl(String) and endTagImpl().
|
src/java-server-framework/org/xins/server/BasicResponseValidator.java
|
Added startTagImpl(String) and endTagImpl().
|
<ide><path>rc/java-server-framework/org/xins/server/BasicResponseValidator.java
<ide> public final void startTag(String name)
<ide> throws InvalidResponseException {
<ide> resetAttributes();
<del> FastStack elements = getElements();
<del> elements.push(name);
<add> boolean succeeded = false;
<add> try {
<add> startTagImpl(name);
<add> succeeded = true;
<add> } finally {
<add> // If an exception is thrown, then reset, just in case the subclass
<add> // threw something other than an InvalidResponseException
<add> if (succeeded == false) {
<add> reset();
<add> }
<add> }
<add> getElements().push(name);
<add> }
<add>
<add> protected void startTagImpl(String name)
<add> throws InvalidResponseException {
<add> // empty
<ide> }
<ide>
<ide> public final void attribute(String name, String value)
<ide>
<ide> public final void endTag()
<ide> throws InvalidResponseException {
<del> FastStack elements = getElements();
<del> String element = (String) elements.pop();
<add> boolean succeeded = false;
<add> try {
<add> endTagImpl(name);
<add> succeeded = true;
<add> } finally {
<add> // If an exception is thrown, then reset, just in case the subclass
<add> // threw something other than an InvalidResponseException
<add> if (succeeded == false) {
<add> reset();
<add> }
<add> }
<add> getElements().pop();
<add> }
<add>
<add> protected void endTagImpl()
<add> throws InvalidResponseException {
<add> // empty
<ide> }
<ide>
<ide> public final void endResponse()
|
|
Java
|
apache-2.0
|
a0a79e91d9749db9477702e2811dac5460cb832b
| 0 |
apache/felix-dev,apache/felix-dev,apache/felix-dev,apache/felix-dev
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.felix.framework;
import org.apache.felix.framework.cache.ConnectContentContent;
import org.apache.felix.framework.cache.Content;
import org.apache.felix.framework.capabilityset.SimpleFilter;
import org.apache.felix.framework.resolver.ResourceNotFoundException;
import org.apache.felix.framework.util.CompoundEnumeration;
import org.apache.felix.framework.util.FelixConstants;
import org.apache.felix.framework.util.SecurityManagerEx;
import org.apache.felix.framework.util.Util;
import org.apache.felix.framework.util.manifestparser.ManifestParser;
import org.apache.felix.framework.util.manifestparser.NativeLibrary;
import org.apache.felix.framework.wiring.BundleRequirementImpl;
import org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleException;
import org.osgi.framework.BundleReference;
import org.osgi.framework.CapabilityPermission;
import org.osgi.framework.Constants;
import org.osgi.framework.FrameworkEvent;
import org.osgi.framework.PackagePermission;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.hooks.weaving.WeavingException;
import org.osgi.framework.hooks.weaving.WeavingHook;
import org.osgi.framework.hooks.weaving.WovenClass;
import org.osgi.framework.hooks.weaving.WovenClassListener;
import org.osgi.framework.namespace.IdentityNamespace;
import org.osgi.framework.wiring.BundleCapability;
import org.osgi.framework.wiring.BundleRequirement;
import org.osgi.framework.wiring.BundleRevision;
import org.osgi.framework.wiring.BundleWire;
import org.osgi.framework.wiring.BundleWiring;
import org.osgi.resource.Capability;
import org.osgi.resource.Requirement;
import org.osgi.resource.Wire;
import org.osgi.service.resolver.ResolutionException;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.security.SecureClassLoader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
public class BundleWiringImpl implements BundleWiring
{
public final static int LISTRESOURCES_DEBUG = 1048576;
public final static int EAGER_ACTIVATION = 0;
public final static int LAZY_ACTIVATION = 1;
public static final ClassLoader CNFE_CLASS_LOADER = new ClassLoader()
{
@Override
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException
{
throw new ClassNotFoundException("Unable to load class '" + name + "'");
}
};
private final Logger m_logger;
private final Map m_configMap;
private final StatefulResolver m_resolver;
private final BundleRevisionImpl m_revision;
private final List<BundleRevision> m_fragments;
// Wire list is copy-on-write since it may change due to
// dynamic imports.
private volatile List<BundleWire> m_wires;
// Imported package map is copy-on-write since it may change
// due to dynamic imports.
private volatile Map<String, BundleRevision> m_importedPkgs;
private final Map<String, List<BundleRevision>> m_requiredPkgs;
private final List<BundleCapability> m_resolvedCaps;
private final Map<String, List<List<String>>> m_includedPkgFilters;
private final Map<String, List<List<String>>> m_excludedPkgFilters;
private final List<BundleRequirement> m_resolvedReqs;
private final List<NativeLibrary> m_resolvedNativeLibs;
private final List<Content> m_fragmentContents;
private volatile List<BundleRequirement> m_wovenReqs = null;
private volatile ClassLoader m_classLoader;
// Bundle-specific class loader for boot delegation.
private final ClassLoader m_bootClassLoader;
// Default class loader for boot delegation.
private final static ClassLoader m_defBootClassLoader;
// Statically define the default class loader for boot delegation.
static
{
ClassLoader cl = null;
try
{
cl = (ClassLoader) BundleRevisionImpl.getSecureAction().invokeDirect(
BundleRevisionImpl.getSecureAction().getMethod(ClassLoader.class, "getPlatformClassLoader", null)
,null, null);
}
catch (Throwable t)
{
// Not on Java9
try
{
Constructor ctor = BundleRevisionImpl.getSecureAction().getDeclaredConstructor(
SecureClassLoader.class, new Class[]{ClassLoader.class});
BundleRevisionImpl.getSecureAction().setAccesssible(ctor);
cl = (ClassLoader) BundleRevisionImpl.getSecureAction().invoke(
ctor, new Object[]{null});
}
catch (Throwable ex)
{
// On Android we get an exception if we set the parent class loader
// to null, so we will work around that case by setting the parent
// class loader to the system class loader in getClassLoader() below.
cl = null;
System.err.println("Problem creating boot delegation class loader: " + ex);
}
}
m_defBootClassLoader = cl;
}
// Boolean flag to enable/disable implicit boot delegation.
private final boolean m_implicitBootDelegation;
// Boolean flag to enable/disable local URLs.
private final boolean m_useLocalURLs;
// Re-usable security manager for accessing class context.
private static SecurityManagerEx m_sm = new SecurityManagerEx();
// Thread local to detect class loading cycles.
private final ThreadLocal m_cycleCheck = new ThreadLocal();
// Thread local to keep track of deferred activation.
private static final ThreadLocal m_deferredActivation = new ThreadLocal();
// Flag indicating whether this wiring has been disposed.
private volatile boolean m_isDisposed = false;
private volatile ConcurrentHashMap<String, ClassLoader> m_accessorLookupCache;
BundleWiringImpl(
Logger logger, Map configMap, StatefulResolver resolver,
BundleRevisionImpl revision, List<BundleRevision> fragments,
List<BundleWire> wires,
Map<String, BundleRevision> importedPkgs,
Map<String, List<BundleRevision>> requiredPkgs) throws Exception
{
m_logger = logger;
m_configMap = configMap;
m_resolver = resolver;
m_revision = revision;
m_importedPkgs = importedPkgs;
m_requiredPkgs = requiredPkgs;
m_wires = Util.newImmutableList(wires);
// We need to sort the fragments and add ourself as a dependent of each one.
// We also need to create an array of fragment contents to attach to our
// content path.
List<Content> fragmentContents = null;
if (fragments != null)
{
// Sort fragments according to ID order, if necessary.
// Note that this sort order isn't 100% correct since
// it uses a string, but it is likely close enough and
// avoids having to create more objects.
if (fragments.size() > 1)
{
SortedMap<String, BundleRevision> sorted = new TreeMap<String, BundleRevision>();
for (BundleRevision f : fragments)
{
sorted.put(((BundleRevisionImpl) f).getId(), f);
}
fragments = new ArrayList(sorted.values());
}
fragmentContents = new ArrayList<Content>(fragments.size());
for (int i = 0; (fragments != null) && (i < fragments.size()); i++)
{
fragmentContents.add(
((BundleRevisionImpl) fragments.get(i)).getContent()
.getEntryAsContent(FelixConstants.CLASS_PATH_DOT));
}
}
m_fragments = fragments;
m_fragmentContents = fragmentContents;
// Calculate resolved list of requirements, which includes:
// 1. All requirements for which we have a wire.
// 2. All dynamic imports from the host and any fragments.
// Also create set of imported packages so we can eliminate any
// substituted exports from our resolved capabilities.
Set<String> imports = new HashSet<String>();
List<BundleRequirement> reqList = new ArrayList<BundleRequirement>();
// First add resolved requirements from wires.
for (BundleWire bw : wires)
{
// Fragments may have multiple wires for the same requirement, so we
// need to check for and avoid duplicates in that case.
if (!bw.getRequirement().getNamespace().equals(BundleRevision.HOST_NAMESPACE)
|| !reqList.contains(bw.getRequirement()))
{
reqList.add(bw.getRequirement());
if (bw.getRequirement().getNamespace().equals(BundleRevision.PACKAGE_NAMESPACE))
{
imports.add((String)
bw.getCapability().getAttributes().get(BundleRevision.PACKAGE_NAMESPACE));
}
}
}
// Next add dynamic requirements from host.
for (BundleRequirement req : m_revision.getDeclaredRequirements(null))
{
if (req.getNamespace().equals(BundleRevision.PACKAGE_NAMESPACE))
{
String resolution = req.getDirectives().get(Constants.RESOLUTION_DIRECTIVE);
if ((resolution != null) && (resolution.equals("dynamic")))
{
reqList.add(req);
}
}
}
// Finally, add dynamic requirements from fragments.
if (m_fragments != null)
{
for (BundleRevision fragment : m_fragments)
{
for (BundleRequirement req : fragment.getDeclaredRequirements(null))
{
if (req.getNamespace().equals(BundleRevision.PACKAGE_NAMESPACE))
{
String resolution = req.getDirectives().get(Constants.RESOLUTION_DIRECTIVE);
if ((resolution != null) && (resolution.equals("dynamic")))
{
reqList.add(req);
}
}
}
}
}
m_resolvedReqs = Util.newImmutableList(reqList);
// Calculate resolved list of capabilities, which includes:
// 1. All capabilities from host and any fragments except for exported
// packages that we have an import (i.e., the export was substituted).
// 2. For fragments the identity capability only.
// And nothing else at this time.
boolean isFragment = Util.isFragment(revision);
List<BundleCapability> capList = new ArrayList<BundleCapability>();
// Also keep track of whether any resolved package capabilities are filtered.
Map<String, List<List<String>>> includedPkgFilters =
new HashMap<String, List<List<String>>>();
Map<String, List<List<String>>> excludedPkgFilters =
new HashMap<String, List<List<String>>>();
if (isFragment)
{
// This is a fragment, add its identity capability
for (BundleCapability cap : m_revision.getDeclaredCapabilities(null))
{
if (IdentityNamespace.IDENTITY_NAMESPACE.equals(cap.getNamespace()))
{
String effective = cap.getDirectives().get(Constants.EFFECTIVE_DIRECTIVE);
if ((effective == null) || (effective.equals(Constants.EFFECTIVE_RESOLVE)))
{
capList.add(cap);
}
}
}
}
else
{
for (BundleCapability cap : m_revision.getDeclaredCapabilities(null))
{
if (!cap.getNamespace().equals(BundleRevision.PACKAGE_NAMESPACE)
|| (cap.getNamespace().equals(BundleRevision.PACKAGE_NAMESPACE)
&& !imports.contains(cap.getAttributes()
.get(BundleRevision.PACKAGE_NAMESPACE).toString())))
{
// TODO: OSGi R4.4 - We may need to make this more flexible since in the future it may
// be possible to consider other effective values via OBR's Environment.isEffective().
String effective = cap.getDirectives().get(Constants.EFFECTIVE_DIRECTIVE);
if ((effective == null) || (effective.equals(Constants.EFFECTIVE_RESOLVE)))
{
capList.add(cap);
if (cap.getNamespace().equals(BundleRevision.PACKAGE_NAMESPACE))
{
List<List<String>> filters =
parsePkgFilters(cap, Constants.INCLUDE_DIRECTIVE);
if (filters != null)
{
includedPkgFilters.put((String)
cap.getAttributes().get(BundleRevision.PACKAGE_NAMESPACE),
filters);
}
filters = parsePkgFilters(cap, Constants.EXCLUDE_DIRECTIVE);
if (filters != null)
{
excludedPkgFilters.put((String)
cap.getAttributes().get(BundleRevision.PACKAGE_NAMESPACE),
filters);
}
}
}
}
}
if (m_fragments != null)
{
for (BundleRevision fragment : m_fragments)
{
for (BundleCapability cap : fragment.getDeclaredCapabilities(null))
{
if (IdentityNamespace.IDENTITY_NAMESPACE.equals(cap.getNamespace())) {
// The identity capability is not transferred from the fragment to the bundle
continue;
}
if (!cap.getNamespace().equals(BundleRevision.PACKAGE_NAMESPACE)
|| (cap.getNamespace().equals(BundleRevision.PACKAGE_NAMESPACE)
&& !imports.contains(cap.getAttributes()
.get(BundleRevision.PACKAGE_NAMESPACE).toString())))
{
// TODO: OSGi R4.4 - We may need to make this more flexible since in the future it may
// be possible to consider other effective values via OBR's Environment.isEffective().
String effective = cap.getDirectives().get(Constants.EFFECTIVE_DIRECTIVE);
if ((effective == null) || (effective.equals(Constants.EFFECTIVE_RESOLVE)))
{
capList.add(cap);
if (cap.getNamespace().equals(
BundleRevision.PACKAGE_NAMESPACE))
{
List<List<String>> filters =
parsePkgFilters(
cap, Constants.INCLUDE_DIRECTIVE);
if (filters != null)
{
includedPkgFilters.put((String)
cap.getAttributes()
.get(BundleRevision.PACKAGE_NAMESPACE),
filters);
}
filters = parsePkgFilters(cap, Constants.EXCLUDE_DIRECTIVE);
if (filters != null)
{
excludedPkgFilters.put((String)
cap.getAttributes()
.get(BundleRevision.PACKAGE_NAMESPACE),
filters);
}
}
}
}
}
}
}
}
if (System.getSecurityManager() != null)
{
for (Iterator<BundleCapability> iter = capList.iterator(); iter.hasNext();)
{
BundleCapability cap = iter.next();
String bundleNamespace = cap.getNamespace();
if (bundleNamespace.isEmpty())
{
iter.remove();
}
else if (bundleNamespace.equals(BundleRevision.PACKAGE_NAMESPACE))
{
if (!((BundleProtectionDomain) ((BundleRevisionImpl) cap.getRevision()).getProtectionDomain()).impliesDirect(
new PackagePermission((String) cap.getAttributes().get(BundleRevision.PACKAGE_NAMESPACE), PackagePermission.EXPORTONLY)))
{
iter.remove();
}
}
else if (!bundleNamespace.equals(BundleRevision.HOST_NAMESPACE)
&& !bundleNamespace.equals(BundleRevision.BUNDLE_NAMESPACE)
&& !bundleNamespace.equals("osgi.ee"))
{
CapabilityPermission permission = new CapabilityPermission(bundleNamespace, CapabilityPermission.PROVIDE);
if (!((BundleProtectionDomain) ((BundleRevisionImpl) cap.getRevision()).getProtectionDomain()).impliesDirect(permission))
{
iter.remove();
}
}
}
}
m_resolvedCaps = Util.newImmutableList(capList);
m_includedPkgFilters = (includedPkgFilters.isEmpty())
? Collections.EMPTY_MAP : includedPkgFilters;
m_excludedPkgFilters = (excludedPkgFilters.isEmpty())
? Collections.EMPTY_MAP : excludedPkgFilters;
List<NativeLibrary> libList = (m_revision.getDeclaredNativeLibraries() == null)
? new ArrayList<NativeLibrary>()
: new ArrayList<NativeLibrary>(m_revision.getDeclaredNativeLibraries());
for (int fragIdx = 0;
(m_fragments != null) && (fragIdx < m_fragments.size());
fragIdx++)
{
List<NativeLibrary> libs =
((BundleRevisionImpl) m_fragments.get(fragIdx))
.getDeclaredNativeLibraries();
for (int reqIdx = 0;
(libs != null) && (reqIdx < libs.size());
reqIdx++)
{
libList.add(libs.get(reqIdx));
}
}
// We need to return null here if we don't have any libraries, since a
// zero-length array is used to indicate that matching native libraries
// could not be found when resolving the bundle.
m_resolvedNativeLibs = (libList.isEmpty()) ? null : Util.newImmutableList(libList);
ClassLoader bootLoader = m_defBootClassLoader;
if (revision.getBundle().getBundleId() != 0)
{
Object map = m_configMap.get(FelixConstants.BOOT_CLASSLOADERS_PROP);
if (map instanceof Map)
{
Object l = ((Map) map).get(m_revision.getBundle());
if (l instanceof ClassLoader)
{
bootLoader = (ClassLoader) l;
}
}
}
m_bootClassLoader = bootLoader;
m_implicitBootDelegation =
(m_configMap.get(FelixConstants.IMPLICIT_BOOT_DELEGATION_PROP) == null)
|| Boolean.valueOf(
(String) m_configMap.get(
FelixConstants.IMPLICIT_BOOT_DELEGATION_PROP));
m_useLocalURLs =
m_configMap.get(FelixConstants.USE_LOCALURLS_PROP) != null;
}
private static List<List<String>> parsePkgFilters(BundleCapability cap, String filtername)
{
List<List<String>> filters = null;
String include = cap.getDirectives().get(filtername);
if (include != null)
{
List<String> filterStrings = ManifestParser.parseDelimitedString(include, ",");
filters = new ArrayList<List<String>>(filterStrings.size());
for (int filterIdx = 0; filterIdx < filterStrings.size(); filterIdx++)
{
List<String> substrings =
SimpleFilter.parseSubstring(filterStrings.get(filterIdx));
filters.add(substrings);
}
}
return filters;
}
@Override
public String toString()
{
return m_revision.getBundle().toString();
}
public synchronized void dispose()
{
if (m_fragmentContents != null)
{
for (Content content : m_fragmentContents)
{
content.close();
}
}
m_classLoader = null;
m_isDisposed = true;
m_accessorLookupCache = null;
}
// TODO: OSGi R4.3 - This really shouldn't be public, but it is needed by the
// resolver to determine if a bundle can dynamically import.
public boolean hasPackageSource(String pkgName)
{
return (m_importedPkgs.containsKey(pkgName) || m_requiredPkgs.containsKey(pkgName));
}
// TODO: OSGi R4.3 - This really shouldn't be public, but it is needed by the
// to implement dynamic imports.
public BundleRevision getImportedPackageSource(String pkgName)
{
return m_importedPkgs.get(pkgName);
}
List<BundleRevision> getFragments()
{
return m_fragments;
}
List<Content> getFragmentContents()
{
return m_fragmentContents;
}
@Override
public boolean isCurrent()
{
BundleRevision current = getBundle().adapt(BundleRevision.class);
return (current != null) && (current.getWiring() == this);
}
@Override
public boolean isInUse()
{
return !m_isDisposed;
}
@Override
public List<Capability> getResourceCapabilities(String namespace)
{
return BundleRevisionImpl.asCapabilityList(getCapabilities(namespace));
}
@Override
public List<BundleCapability> getCapabilities(String namespace)
{
if (isInUse())
{
List<BundleCapability> result = m_resolvedCaps;
if (namespace != null)
{
result = new ArrayList<BundleCapability>();
for (BundleCapability cap : m_resolvedCaps)
{
if (cap.getNamespace().equals(namespace))
{
result.add(cap);
}
}
}
return result;
}
return null;
}
@Override
public List<Requirement> getResourceRequirements(String namespace)
{
return BundleRevisionImpl.asRequirementList(getRequirements(namespace));
}
@Override
public List<BundleRequirement> getRequirements(String namespace)
{
if (isInUse())
{
List<BundleRequirement> searchReqs = m_resolvedReqs;
List<BundleRequirement> wovenReqs = m_wovenReqs;
List<BundleRequirement> result = m_resolvedReqs;
if (wovenReqs != null)
{
searchReqs = new ArrayList<BundleRequirement>(m_resolvedReqs);
searchReqs.addAll(wovenReqs);
result = searchReqs;
}
if (namespace != null)
{
result = new ArrayList<BundleRequirement>();
for (BundleRequirement req : searchReqs)
{
if (req.getNamespace().equals(namespace))
{
result.add(req);
}
}
}
return result;
}
return null;
}
public List<NativeLibrary> getNativeLibraries()
{
return m_resolvedNativeLibs;
}
private static List<Wire> asWireList(List wires)
{
return wires;
}
@Override
public List<Wire> getProvidedResourceWires(String namespace)
{
return asWireList(getProvidedWires(namespace));
}
@Override
public List<BundleWire> getProvidedWires(String namespace)
{
if (isInUse())
{
return m_revision.getBundle()
.getFramework().getDependencies().getProvidedWires(m_revision, namespace);
}
return null;
}
@Override
public List<Wire> getRequiredResourceWires(String namespace)
{
return asWireList(getRequiredWires(namespace));
}
@Override
public List<BundleWire> getRequiredWires(String namespace)
{
if (isInUse())
{
List<BundleWire> result = m_wires;
if (namespace != null)
{
result = new ArrayList<BundleWire>();
for (BundleWire bw : m_wires)
{
if (bw.getRequirement().getNamespace().equals(namespace))
{
result.add(bw);
}
}
}
return result;
}
return null;
}
public synchronized void addDynamicWire(BundleWire wire)
{
// Make new wires list.
List<BundleWire> wires = new ArrayList<BundleWire>(m_wires);
wires.add(wire);
if (wire.getCapability().getAttributes().get(BundleRevision.PACKAGE_NAMESPACE) != null)
{
// Make new imported package map.
Map<String, BundleRevision> importedPkgs =
new HashMap<String, BundleRevision>(m_importedPkgs);
importedPkgs.put(
(String) wire.getCapability().getAttributes().get(BundleRevision.PACKAGE_NAMESPACE),
wire.getProviderWiring().getRevision());
m_importedPkgs = importedPkgs;
}
// Update associated member values.
// Technically, there is a window here where readers won't see
// both values updates at the same time, but it seems unlikely
// to cause any issues.
m_wires = Util.newImmutableList(wires);
}
@Override
public BundleRevision getResource()
{
return m_revision;
}
@Override
public BundleRevision getRevision()
{
return m_revision;
}
@Override
public ClassLoader getClassLoader()
{
if (m_isDisposed || Util.isFragment(m_revision))
{
return null;
}
return getClassLoaderInternal();
}
private ClassLoader getClassLoaderInternal()
{
ClassLoader classLoader = m_classLoader;
if (classLoader != null)
{
return classLoader;
}
else
{
return _getClassLoaderInternal();
}
}
private synchronized ClassLoader _getClassLoaderInternal()
{
// Only try to create the class loader if the bundle
// is not disposed.
if (!m_isDisposed && (m_classLoader == null))
{
if (m_revision.getContent() instanceof ConnectContentContent)
{
m_classLoader = ((ConnectContentContent) m_revision.getContent()).getClassLoader();
}
if (m_classLoader == null)
{
m_classLoader = BundleRevisionImpl.getSecureAction().run(
new PrivilegedAction<BundleClassLoader>()
{
@Override
public BundleClassLoader run()
{
return new BundleClassLoader(BundleWiringImpl.this, determineParentClassLoader(), m_logger);
}
}
);
}
}
return m_classLoader;
}
@Override
public List<URL> findEntries(String path, String filePattern, int options)
{
if (isInUse())
{
if (!Util.isFragment(m_revision))
{
Enumeration<URL> e =
m_revision.getBundle().getFramework()
.findBundleEntries(m_revision, path, filePattern,
(options & BundleWiring.FINDENTRIES_RECURSE) > 0);
List<URL> entries = new ArrayList<URL>();
while ((e != null) && e.hasMoreElements())
{
entries.add(e.nextElement());
}
return Util.newImmutableList(entries);
}
return Collections.EMPTY_LIST;
}
return null;
}
// Thread local to detect class loading cycles.
private final ThreadLocal m_listResourcesCycleCheck = new ThreadLocal();
@Override
public Collection<String> listResources(
String path, String filePattern, int options)
{
// Implementation note: If you enable the DEBUG option for
// listResources() to print from where each resource comes,
// it will not give 100% accurate answers in the face of
// Require-Bundle cycles with overlapping content since
// the actual source will depend on who does the class load
// first. Further, normal class loaders cache class load
// results so it is always the same subsequently, but we
// don't do that here so it will always return a different
// result depending upon who is asking. Moral to the story:
// don't do cycles and certainly don't do them with
// overlapping content.
Collection<String> resources = null;
// Normalize path.
if ((path.length() > 0) && (path.charAt(0) == '/'))
{
path = path.substring(1);
}
if ((path.length() > 0) && (path.charAt(path.length() - 1) != '/'))
{
path = path + '/';
}
// Parse the file filter.
filePattern = (filePattern == null) ? "*" : filePattern;
List<String> pattern = SimpleFilter.parseSubstring(filePattern);
// We build an internal collection of ResourceSources, since this
// allows us to print out additional debug information.
Collection<ResourceSource> sources = listResourcesInternal(path, pattern, options);
if (sources != null)
{
boolean debug = (options & LISTRESOURCES_DEBUG) > 0;
resources = new TreeSet<String>();
for (ResourceSource source : sources)
{
if (debug)
{
resources.add(source.toString());
}
else
{
resources.add(source.m_resource);
}
}
}
return resources;
}
private synchronized Collection<ResourceSource> listResourcesInternal(
String path, List<String> pattern, int options)
{
if (isInUse())
{
boolean recurse = (options & BundleWiring.LISTRESOURCES_RECURSE) > 0;
boolean localOnly = (options & BundleWiring.LISTRESOURCES_LOCAL) > 0;
// Check for cycles, which can happen with Require-Bundle.
Set<String> cycles = (Set<String>) m_listResourcesCycleCheck.get();
if (cycles == null)
{
cycles = new HashSet<String>();
m_listResourcesCycleCheck.set(cycles);
}
if (cycles.contains(path))
{
return Collections.EMPTY_LIST;
}
cycles.add(path);
try
{
// Calculate set of remote resources (i.e., those either
// imported or required).
Collection<ResourceSource> remoteResources = new TreeSet<ResourceSource>();
// Imported packages cannot have merged content, so we need to
// keep track of these packages.
Set<String> noMerging = new HashSet<String>();
// Loop through wires to compute remote resources.
for (BundleWire bw : m_wires)
{
if (bw.getCapability().getNamespace()
.equals(BundleRevision.PACKAGE_NAMESPACE))
{
// For imported packages, we only need to calculate
// the remote resources of the specific imported package.
remoteResources.addAll(
calculateRemotePackageResources(
bw, bw.getCapability(), recurse,
path, pattern, noMerging));
}
else if (bw.getCapability().getNamespace()
.equals(BundleRevision.BUNDLE_NAMESPACE))
{
// For required bundles, all declared package capabilities
// from the required bundle will be available to requirers,
// so get the target required bundle's declared packages
// and handle them in a similar fashion to a normal import
// except that their content can be merged with local
// packages.
List<BundleCapability> exports =
bw.getProviderWiring().getRevision()
.getDeclaredCapabilities(BundleRevision.PACKAGE_NAMESPACE);
for (BundleCapability export : exports)
{
remoteResources.addAll(
calculateRemotePackageResources(
bw, export, recurse, path, pattern, null));
}
// Since required bundle may reexport bundles it requires,
// check its wires for this case.
List<BundleWire> requiredBundles =
bw.getProviderWiring().getRequiredWires(
BundleRevision.BUNDLE_NAMESPACE);
for (BundleWire rbWire : requiredBundles)
{
String visibility =
rbWire.getRequirement().getDirectives()
.get(Constants.VISIBILITY_DIRECTIVE);
if ((visibility != null)
&& (visibility.equals(Constants.VISIBILITY_REEXPORT)))
{
// For each reexported required bundle, treat them
// in a similar fashion as a normal required bundle
// by including all of their declared package
// capabilities in the requiring bundle's class
// space.
List<BundleCapability> reexports =
rbWire.getProviderWiring().getRevision()
.getDeclaredCapabilities(BundleRevision.PACKAGE_NAMESPACE);
for (BundleCapability reexport : reexports)
{
remoteResources.addAll(
calculateRemotePackageResources(
bw, reexport, recurse, path, pattern, null));
}
}
}
}
}
// Calculate set of local resources (i.e., those contained
// in the revision or its fragments).
Collection<ResourceSource> localResources = new TreeSet<ResourceSource>();
// Get the revision's content path, which includes contents
// from fragments.
List<Content> contentPath = m_revision.getContentPath();
for (Content content : contentPath)
{
Enumeration<String> e = content.getEntries();
if (e != null)
{
while (e.hasMoreElements())
{
String resource = e.nextElement();
String resourcePath = getTrailingPath(resource);
if (!noMerging.contains(resourcePath))
{
if ((!recurse && resourcePath.equals(path))
|| (recurse && resourcePath.startsWith(path)))
{
if (matchesPattern(pattern, getPathHead(resource)))
{
localResources.add(
new ResourceSource(resource, m_revision));
}
}
}
}
}
}
if (localOnly)
{
return localResources;
}
else
{
remoteResources.addAll(localResources);
return remoteResources;
}
}
finally
{
cycles.remove(path);
if (cycles.isEmpty())
{
m_listResourcesCycleCheck.set(null);
}
}
}
return null;
}
private Collection<ResourceSource> calculateRemotePackageResources(
BundleWire bw, BundleCapability cap, boolean recurse,
String path, List<String> pattern, Set<String> noMerging)
{
Collection<ResourceSource> resources = Collections.EMPTY_SET;
// Convert package name to a path.
String subpath = (String) cap.getAttributes().get(BundleRevision.PACKAGE_NAMESPACE);
subpath = subpath.replace('.', '/') + '/';
// If necessary, record that this package should not be merged
// with local content.
if (noMerging != null)
{
noMerging.add(subpath);
}
// If we are not recuring, check for path equality or if
// we are recursing, check that the subpath starts with
// the target path.
if ((!recurse && subpath.equals(path))
|| (recurse && subpath.startsWith(path)))
{
// Delegate to the original provider wiring to have it calculate
// the list of resources in the package. In this case, we don't
// want to recurse since we want the precise package.
resources =
((BundleWiringImpl) bw.getProviderWiring()).listResourcesInternal(
subpath, pattern, 0);
// The delegatedResources result will include subpackages
// which need to be filtered out, since imported packages
// do not give access to subpackages. If a subpackage is
// imported, it will be added by its own wire.
for (Iterator<ResourceSource> it = resources.iterator();
it.hasNext(); )
{
ResourceSource reqResource = it.next();
if (reqResource.m_resource.charAt(
reqResource.m_resource.length() - 1) == '/')
{
it.remove();
}
}
}
// If we are not recursing, but the required package
// is a child of the desired path, then include its
// immediate child package. We do this so that it is
// possible to use listResources() to walk the resource
// tree similar to doing a directory walk one level
// at a time.
else if (!recurse && subpath.startsWith(path))
{
int idx = subpath.indexOf('/', path.length());
if (idx >= 0)
{
subpath = subpath.substring(0, idx + 1);
}
if (matchesPattern(pattern, getPathHead(subpath)))
{
resources = Collections.singleton(
new ResourceSource(subpath, bw.getProviderWiring().getRevision()));
}
}
return resources;
}
private static String getPathHead(String resource)
{
if (resource.length() == 0)
{
return resource;
}
int idx = (resource.charAt(resource.length() - 1) == '/')
? resource.lastIndexOf('/', resource.length() - 2)
: resource.lastIndexOf('/');
if (idx < 0)
{
return resource;
}
return resource.substring(idx + 1);
}
private static String getTrailingPath(String resource)
{
if (resource.length() == 0)
{
return null;
}
int idx = (resource.charAt(resource.length() - 1) == '/')
? resource.lastIndexOf('/', resource.length() - 2)
: resource.lastIndexOf('/');
if (idx < 0)
{
return "";
}
return resource.substring(0, idx + 1);
}
private static boolean matchesPattern(List<String> pattern, String resource)
{
if (resource.charAt(resource.length() - 1) == '/')
{
resource = resource.substring(0, resource.length() - 1);
}
return SimpleFilter.compareSubstring(pattern, resource);
}
@Override
public BundleImpl getBundle()
{
return m_revision.getBundle();
}
public Enumeration getResourcesByDelegation(String name)
{
Set requestSet = (Set) m_cycleCheck.get();
if (requestSet == null)
{
requestSet = new HashSet();
m_cycleCheck.set(requestSet);
}
if (!requestSet.contains(name))
{
requestSet.add(name);
try
{
return findResourcesByDelegation(name);
}
finally
{
requestSet.remove(name);
}
}
return null;
}
private Enumeration findResourcesByDelegation(String name)
{
Enumeration urls = null;
List completeUrlList = new ArrayList();
// Get the package of the target class/resource.
String pkgName = Util.getResourcePackage(name);
// Delegate any packages listed in the boot delegation
// property to the parent class loader.
if (shouldBootDelegate(pkgName))
{
try
{
// Get the appropriate class loader for delegation.
ClassLoader bdcl = getBootDelegationClassLoader();
urls = bdcl.getResources(name);
}
catch (IOException ex)
{
// This shouldn't happen and even if it does, there
// is nothing we can do, so just ignore it.
}
// If this is a java.* package, then always terminate the
// search; otherwise, continue to look locally.
if (pkgName.startsWith("java."))
{
return urls;
}
completeUrlList.add(urls);
}
// Look in the revisions's imported packages. If the package is
// imported, then we stop searching no matter the result since
// imported packages cannot be split.
BundleRevision provider = m_importedPkgs.get(pkgName);
if (provider != null)
{
// Delegate to the provider revision.
urls = ((BundleWiringImpl) provider.getWiring()).getResourcesByDelegation(name);
// If we find any resources, then add them.
if ((urls != null) && (urls.hasMoreElements()))
{
completeUrlList.add(urls);
}
// Always return here since imported packages cannot be split
// across required bundles or the revision's content.
return new CompoundEnumeration((Enumeration[])
completeUrlList.toArray(new Enumeration[completeUrlList.size()]));
}
// See whether we can get the resource from the required bundles and
// regardless of whether or not this is the case continue to the next
// step potentially passing on the result of this search (if any).
List<BundleRevision> providers = m_requiredPkgs.get(pkgName);
if (providers != null)
{
for (BundleRevision p : providers)
{
// Delegate to the provider revision.
urls = ((BundleWiringImpl) p.getWiring()).getResourcesByDelegation(name);
// If we find any resources, then add them.
if ((urls != null) && (urls.hasMoreElements()))
{
completeUrlList.add(urls);
}
// Do not return here, since required packages can be split
// across the revision's content.
}
}
// Try the module's own class path. If we can find the resource then
// return it together with the results from the other searches else
// try to look into the dynamic imports.
urls = m_revision.getResourcesLocal(name);
if ((urls != null) && (urls.hasMoreElements()))
{
completeUrlList.add(urls);
}
else
{
// If not found, then try the module's dynamic imports.
// At this point, the module's imports were searched and so was the
// the module's content. Now we make an attempt to load the
// class/resource via a dynamic import, if possible.
try
{
provider = m_resolver.resolve(m_revision, pkgName);
}
catch (ResolutionException ex)
{
// Ignore this since it is likely normal.
}
catch (BundleException ex)
{
// Ignore this since it is likely the result of a resolver hook.
}
if (provider != null)
{
// Delegate to the provider revision.
urls = ((BundleWiringImpl) provider.getWiring()).getResourcesByDelegation(name);
// If we find any resources, then add them.
if ((urls != null) && (urls.hasMoreElements()))
{
completeUrlList.add(urls);
}
}
}
return new CompoundEnumeration((Enumeration[])
completeUrlList.toArray(new Enumeration[completeUrlList.size()]));
}
private ClassLoader determineParentClassLoader()
{
// Determine the class loader's parent based on the
// configuration property; use boot class loader by
// default.
String cfg = (String) m_configMap.get(Constants.FRAMEWORK_BUNDLE_PARENT);
cfg = (cfg == null) ? Constants.FRAMEWORK_BUNDLE_PARENT_BOOT : cfg;
final ClassLoader parent;
if (cfg.equalsIgnoreCase(Constants.FRAMEWORK_BUNDLE_PARENT_APP))
{
parent = BundleRevisionImpl.getSecureAction().getSystemClassLoader();
}
else if (cfg.equalsIgnoreCase(Constants.FRAMEWORK_BUNDLE_PARENT_EXT))
{
parent = BundleRevisionImpl.getSecureAction().getParentClassLoader(
BundleRevisionImpl.getSecureAction().getSystemClassLoader());
}
else if (cfg.equalsIgnoreCase(Constants.FRAMEWORK_BUNDLE_PARENT_FRAMEWORK))
{
parent = BundleRevisionImpl.getSecureAction()
.getClassLoader(BundleRevisionImpl.class);
}
// On Android we cannot set the parent class loader to be null, so
// we special case that situation here and set it to the system
// class loader by default instead, which is not really spec.
else if (m_bootClassLoader == null)
{
parent = BundleRevisionImpl.getSecureAction().getSystemClassLoader();
}
else
{
parent = null;
}
return parent;
}
boolean shouldBootDelegate(String pkgName)
{
// Always boot delegate if the bundle has a configured
// boot class loader.
if (m_bootClassLoader != m_defBootClassLoader)
{
return true;
}
boolean result = false;
// Only consider delegation if we have a package name, since
// we don't want to promote the default package. The spec does
// not take a stand on this issue.
if (pkgName.length() > 0)
{
for (int i = 0;
!result
&& (i < getBundle()
.getFramework().getBootPackages().length);
i++)
{
// Check if the boot package is wildcarded.
// A wildcarded boot package will be in the form "foo.",
// so a matching subpackage will start with "foo.", e.g.,
// "foo.bar".
if (getBundle().getFramework().getBootPackageWildcards()[i]
&& pkgName.startsWith(
getBundle().getFramework().getBootPackages()[i]))
{
return true;
}
// If not wildcarded, then check for an exact match.
else if (getBundle()
.getFramework().getBootPackages()[i].equals(pkgName))
{
return true;
}
}
}
return result;
}
ClassLoader getBootDelegationClassLoader()
{
ClassLoader loader = m_classLoader;
// Get the appropriate class loader for delegation.
ClassLoader parent = (loader == null) ?
determineParentClassLoader() :
BundleRevisionImpl.getSecureAction().getParentClassLoader(loader);
return (parent == null) ? m_bootClassLoader : parent;
}
public Class getClassByDelegation(String name) throws ClassNotFoundException
{
// We do not call getClassLoader().loadClass() for arrays because
// it does not correctly handle array types, which is necessary in
// cases like deserialization using a wrapper class loader.
if ((name != null) && (name.length() > 0) && (name.charAt(0) == '['))
{
return Class.forName(name, false, getClassLoader());
}
// Check to see if the requested class is filtered.
if (isFiltered(name))
{
throw new ClassNotFoundException(name);
}
ClassLoader cl = getClassLoaderInternal();
if (cl == null)
{
throw new ClassNotFoundException(
"Unable to load class '"
+ name
+ "' because the bundle wiring for "
+ m_revision.getSymbolicName()
+ " is no longer valid.");
}
return cl.loadClass(name);
}
private boolean isFiltered(String name)
{
String pkgName = Util.getClassPackage(name);
List<List<String>> includeFilters = m_includedPkgFilters.get(pkgName);
List<List<String>> excludeFilters = m_excludedPkgFilters.get(pkgName);
if ((includeFilters == null) && (excludeFilters == null))
{
return false;
}
// Get the class name portion of the target class.
String className = Util.getClassName(name);
// If there are no include filters then all classes are included
// by default, otherwise try to find one match.
boolean included = (includeFilters == null);
for (int i = 0;
(!included) && (includeFilters != null) && (i < includeFilters.size());
i++)
{
included = SimpleFilter.compareSubstring(includeFilters.get(i), className);
}
// If there are no exclude filters then no classes are excluded
// by default, otherwise try to find one match.
boolean excluded = false;
for (int i = 0;
(!excluded) && (excludeFilters != null) && (i < excludeFilters.size());
i++)
{
excluded = SimpleFilter.compareSubstring(excludeFilters.get(i), className);
}
return !included || excluded;
}
public URL getResourceByDelegation(String name)
{
try
{
return (URL) findClassOrResourceByDelegation(name, false);
}
catch (ClassNotFoundException ex)
{
// This should never be thrown because we are loading resources.
}
catch (ResourceNotFoundException ex)
{
m_logger.log(m_revision.getBundle(),
Logger.LOG_DEBUG,
ex.getMessage());
}
return null;
}
private Object findClassOrResourceByDelegation(String name, boolean isClass)
throws ClassNotFoundException, ResourceNotFoundException
{
Object result = null;
Set requestSet = (Set) m_cycleCheck.get();
if (requestSet == null)
{
requestSet = new HashSet();
m_cycleCheck.set(requestSet);
}
if (requestSet.add(name))
{
try
{
// Get the package of the target class/resource.
String pkgName = (isClass) ? Util.getClassPackage(name) : Util.getResourcePackage(name);
boolean accessor = name.startsWith("sun.reflect.Generated") || name.startsWith("jdk.internal.reflect.");
if (accessor)
{
if (m_accessorLookupCache == null)
{
m_accessorLookupCache = new ConcurrentHashMap<String, ClassLoader>();
}
ClassLoader loader = m_accessorLookupCache.get(name);
if (loader != null)
{
return loader.loadClass(name);
}
}
// Delegate any packages listed in the boot delegation
// property to the parent class loader.
if (shouldBootDelegate(pkgName))
{
try
{
// Get the appropriate class loader for delegation.
ClassLoader bdcl = getBootDelegationClassLoader();
result = (isClass) ? (Object) bdcl.loadClass(name) : (Object) bdcl.getResource(name);
// If this is a java.* package, then always terminate the
// search; otherwise, continue to look locally if not found.
if (pkgName.startsWith("java.") || (result != null))
{
if (accessor)
{
m_accessorLookupCache.put(name, bdcl);
}
return result;
}
}
catch (ClassNotFoundException ex)
{
// If this is a java.* package, then always terminate the
// search; otherwise, continue to look locally if not found.
if (pkgName.startsWith("java."))
{
throw ex;
}
}
}
if (accessor)
{
List<Collection<BundleRevision>> allRevisions = new ArrayList<Collection<BundleRevision>>( 1 + m_requiredPkgs.size());
allRevisions.add(m_importedPkgs.values());
allRevisions.addAll(m_requiredPkgs.values());
for (Collection<BundleRevision> revisions : allRevisions)
{
for (BundleRevision revision : revisions)
{
ClassLoader loader = revision.getWiring().getClassLoader();
if (loader != null && loader instanceof BundleClassLoader)
{
BundleClassLoader bundleClassLoader = (BundleClassLoader) loader;
result = bundleClassLoader.findLoadedClassInternal(name);
if (result != null)
{
m_accessorLookupCache.put(name, bundleClassLoader);
return result;
}
}
}
}
try
{
// Get the appropriate class loader for delegation.
ClassLoader bdcl = getBootDelegationClassLoader();
result = (isClass) ? (Object) bdcl.loadClass(name) : (Object) bdcl.getResource(name);
if (result != null)
{
m_accessorLookupCache.put(name, bdcl);
return result;
}
}
catch (ClassNotFoundException ex)
{
}
m_accessorLookupCache.put(name, CNFE_CLASS_LOADER);
CNFE_CLASS_LOADER.loadClass(name);
}
// Look in the revision's imports. Note that the search may
// be aborted if this method throws an exception, otherwise
// it continues if a null is returned.
result = searchImports(pkgName, name, isClass);
// If not found, try the revision's own class path.
if (result == null)
{
ClassLoader cl = getClassLoaderInternal();
if (cl == null)
{
if (isClass)
{
throw new ClassNotFoundException(
"Unable to load class '"
+ name
+ "' because the bundle wiring for "
+ m_revision.getSymbolicName()
+ " is no longer valid.");
}
else
{
throw new ResourceNotFoundException("Unable to load resource '"
+ name
+ "' because the bundle wiring for "
+ m_revision.getSymbolicName()
+ " is no longer valid.");
}
}
if (cl instanceof BundleClassLoader)
{
result = isClass ? ((BundleClassLoader) cl).findClass(name) :
((BundleClassLoader) cl).findResource(name);
}
else
{
result = isClass ? cl.loadClass(name) : !name.startsWith("/") ? cl.getResource(name) :
cl.getResource(name.substring(1));
}
// If still not found, then try the revision's dynamic imports.
if (result == null)
{
result = searchDynamicImports(pkgName, name, isClass);
}
}
}
finally
{
requestSet.remove(name);
}
}
else
{
// If a cycle is detected, we should return null to break the
// cycle. This should only ever be return to internal class
// loading code and not to the actual instigator of the class load.
return null;
}
if (result == null)
{
if (isClass)
{
throw new ClassNotFoundException(
name + " not found by " + this.getBundle());
}
else
{
throw new ResourceNotFoundException(
name + " not found by " + this.getBundle());
}
}
return result;
}
private Object searchImports(String pkgName, String name, boolean isClass)
throws ClassNotFoundException, ResourceNotFoundException
{
// Check if the package is imported.
BundleRevision provider = m_importedPkgs.get(pkgName);
if (provider != null)
{
// If we find the class or resource, then return it.
Object result = (isClass)
? (Object) ((BundleWiringImpl) provider.getWiring()).getClassByDelegation(name)
: (Object) ((BundleWiringImpl) provider.getWiring()).getResourceByDelegation(name);
if (result != null)
{
return result;
}
// If no class or resource was found, then we must throw an exception
// since the provider of this package did not contain the
// requested class and imported packages are atomic.
if (isClass)
{
throw new ClassNotFoundException(name);
}
throw new ResourceNotFoundException(name);
}
// Check if the package is required.
List<BundleRevision> providers = m_requiredPkgs.get(pkgName);
if (providers != null)
{
for (BundleRevision p : providers)
{
// If we find the class or resource, then return it.
try
{
Object result = (isClass)
? (Object) ((BundleWiringImpl) p.getWiring()).getClassByDelegation(name)
: (Object) ((BundleWiringImpl) p.getWiring()).getResourceByDelegation(name);
if (result != null)
{
return result;
}
}
catch (ClassNotFoundException ex)
{
// Since required packages can be split, don't throw an
// exception here if it is not found. Instead, we'll just
// continue searching other required bundles and the
// revision's local content.
}
}
}
return null;
}
private Object searchDynamicImports(
final String pkgName, final String name, final boolean isClass)
throws ClassNotFoundException, ResourceNotFoundException
{
// At this point, the module's imports were searched and so was the
// the module's content. Now we make an attempt to load the
// class/resource via a dynamic import, if possible.
BundleRevision provider = null;
try
{
provider = m_resolver.resolve(m_revision, pkgName);
}
catch (ResolutionException ex)
{
// Ignore this since it is likely normal.
}
catch (BundleException ex)
{
// Ignore this since it is likely the result of a resolver hook.
}
// If the dynamic import was successful, then this initial
// time we must directly return the result from dynamically
// created package sources, but subsequent requests for
// classes/resources in the associated package will be
// processed as part of normal static imports.
if (provider != null)
{
// Return the class or resource.
return (isClass)
? (Object) ((BundleWiringImpl) provider.getWiring()).getClassByDelegation(name)
: (Object) ((BundleWiringImpl) provider.getWiring()).getResourceByDelegation(name);
}
return tryImplicitBootDelegation(name, isClass);
}
private Object tryImplicitBootDelegation(final String name, final boolean isClass)
throws ClassNotFoundException, ResourceNotFoundException
{
// If implicit boot delegation is enabled, then try to guess whether
// we should boot delegate.
if (m_implicitBootDelegation)
{
// At this point, the class/resource could not be found by the bundle's
// static or dynamic imports, nor its own content. Before we throw
// an exception, we will try to determine if the instigator of the
// class/resource load was a class from a bundle or not. This is necessary
// because the specification mandates that classes on the class path
// should be hidden (except for java.*), but it does allow for these
// classes/resources to be exposed by the system bundle as an export.
// However, in some situations classes on the class path make the faulty
// assumption that they can access everything on the class path from
// every other class loader that they come in contact with. This is
// not true if the class loader in question is from a bundle. Thus,
// this code tries to detect that situation. If the class instigating
// the load request was NOT from a bundle, then we will make the
// assumption that the caller actually wanted to use the parent class
// loader and we will delegate to it. If the class was
// from a bundle, then we will enforce strict class loading rules
// for the bundle and throw an exception.
// Get the class context to see the classes on the stack.
final Class[] classes = m_sm.getClassContext();
try
{
if (System.getSecurityManager() != null)
{
return AccessController
.doPrivileged(new PrivilegedExceptionAction()
{
@Override
public Object run() throws Exception
{
return doImplicitBootDelegation(classes, name,
isClass);
}
});
}
else
{
return doImplicitBootDelegation(classes, name, isClass);
}
}
catch (PrivilegedActionException ex)
{
Exception cause = ex.getException();
if (cause instanceof ClassNotFoundException)
{
throw (ClassNotFoundException) cause;
}
else
{
throw (ResourceNotFoundException) cause;
}
}
}
return null;
}
private Object doImplicitBootDelegation(Class[] classes, String name, boolean isClass)
throws ClassNotFoundException, ResourceNotFoundException
{
// Start from 1 to skip security manager class.
for (int i = 1; i < classes.length; i++)
{
// Find the first class on the call stack that is not from
// the class loader that loaded the Felix classes or is not
// a class loader or class itself, because we want to ignore
// calls to ClassLoader.loadClass() and Class.forName() since
// we are trying to find out who instigated the class load.
// Also ignore inner classes of class loaders, since we can
// assume they are a class loader too.
// TODO: FRAMEWORK - This check is a hack and we should see if we can think
// of another way to do it, since it won't necessarily work in all situations.
// Since Felix uses threads for changing the start level
// and refreshing packages, it is possible that there are no
// bundle classes on the call stack; therefore, as soon as we
// see Thread on the call stack we exit this loop. Other cases
// where bundles actually use threads are not an issue because
// the bundle classes will be on the call stack before the
// Thread class.
if (Thread.class.equals(classes[i]))
{
break;
}
// Break if the current class came from a bundle, since we should
// not implicitly boot delegate in that case.
else if (isClassLoadedFromBundleRevision(classes[i]))
{
break;
}
// Break if this goes through BundleImpl because it must be a call
// to Bundle.loadClass() which should not implicitly boot delegate.
else if (BundleImpl.class.equals(classes[i]))
{
break;
}
// Break if this goes through ServiceRegistrationImpl.ServiceReferenceImpl
// because it must be a assignability check which should not implicitly boot delegate
else if (ServiceRegistrationImpl.ServiceReferenceImpl.class.equals(classes[i]))
{
break;
}
else if (isClassExternal(classes[i]))
{
try
{
// Return the class or resource from the parent class loader.
return (isClass)
? (Object) BundleRevisionImpl.getSecureAction()
.getClassLoader(this.getClass()).loadClass(name)
: (Object) BundleRevisionImpl.getSecureAction()
.getClassLoader(this.getClass()).getResource(name);
}
catch (NoClassDefFoundError ex)
{
// Ignore, will return null
}
break;
}
}
return null;
}
private boolean isClassLoadedFromBundleRevision(Class clazz)
{
// The target class is loaded by a bundle class loader,
// then return true.
if (BundleClassLoader.class.isInstance(
BundleRevisionImpl.getSecureAction().getClassLoader(clazz)))
{
return true;
}
// If the target class was loaded from a class loader that
// came from a bundle, then return true.
ClassLoader last = null;
for (ClassLoader cl = BundleRevisionImpl.getSecureAction().getClassLoader(clazz);
(cl != null) && (last != cl);
cl = BundleRevisionImpl.getSecureAction().getClassLoader(cl.getClass()))
{
last = cl;
if (BundleClassLoader.class.isInstance(cl))
{
return true;
}
}
return false;
}
/**
* Tries to determine whether the given class is part of the framework or not.
* Framework classes include everything in org.apache.felix.framework.* and
* org.osgi.framework.*. We also consider ClassLoader and Class to be internal
* classes, because they are inserted into the stack trace as a result of
* method overloading. Typically, ClassLoader or Class will be mixed in
* between framework classes or will be at the point where the class loading
* request enters the framework class loading mechanism, which will then be
* followed by either bundle or external code, which will then exit our
* attempt to determine if we should boot delegate or not. Other standard
* class loaders, like URLClassLoader, are considered external classes and
* should trigger boot delegation. This means that bundles can create standard
* class loaders to get access to boot packages, but this is the standard
* behavior of class loaders.
* @param clazz the class to determine if it is external or not.
* @return <tt>true</tt> if the class is external, otherwise <tt>false</tt>.
*/
private boolean isClassExternal(Class clazz)
{
if (clazz.getName().startsWith("org.apache.felix.framework."))
{
return false;
}
else if (clazz.getName().startsWith("org.osgi.framework."))
{
return false;
}
else if (ClassLoader.class.equals(clazz))
{
return false;
}
else if (Class.class.equals(clazz))
{
return false;
}
return true;
}
static class ToLocalUrlEnumeration implements Enumeration
{
final Enumeration m_enumeration;
ToLocalUrlEnumeration(Enumeration enumeration)
{
m_enumeration = enumeration;
}
@Override
public boolean hasMoreElements()
{
return m_enumeration.hasMoreElements();
}
@Override
public Object nextElement()
{
return convertToLocalUrl((URL) m_enumeration.nextElement());
}
}
public static class BundleClassLoader extends SecureClassLoader implements BundleReference
{
static final boolean m_isParallel;
static
{
m_isParallel = registerAsParallel();
}
@IgnoreJRERequirement
private static boolean registerAsParallel()
{
boolean registered = false;
try
{
registered = ClassLoader.registerAsParallelCapable();
}
catch (Throwable th)
{
// This is OK on older java versions
}
return registered;
}
// Flag used to determine if a class has been loaded from this class
// loader or not.
private volatile boolean m_isActivationTriggered = false;
private Object[][] m_cachedLibs = new Object[0][];
private static final int LIBNAME_IDX = 0;
private static final int LIBPATH_IDX = 1;
private final ConcurrentHashMap<String, Thread> m_classLocks = new ConcurrentHashMap<String, Thread>();
private final BundleWiringImpl m_wiring;
private final Logger m_logger;
public BundleClassLoader(BundleWiringImpl wiring, ClassLoader parent, Logger logger)
{
super(parent);
m_wiring = wiring;
m_logger = logger;
}
public boolean isActivationTriggered()
{
return m_isActivationTriggered;
}
@Override
public BundleImpl getBundle()
{
return m_wiring.getBundle();
}
@Override
protected Class loadClass(String name, boolean resolve)
throws ClassNotFoundException
{
Class clazz = findLoadedClass(name);
if (clazz == null)
{
try
{
clazz = (Class) m_wiring.findClassOrResourceByDelegation(name, true);
}
catch (ResourceNotFoundException ex)
{
// This should never happen since we are asking for a class,
// so just ignore it.
}
catch (ClassNotFoundException cnfe)
{
ClassNotFoundException ex = cnfe;
if (m_logger.getLogLevel() >= Logger.LOG_DEBUG)
{
String msg = diagnoseClassLoadError(m_wiring.m_resolver, m_wiring.m_revision, name);
ex = (msg != null)
? new ClassNotFoundException(msg, cnfe)
: ex;
}
throw ex;
}
if (clazz == null)
{
// We detected a cycle
throw new ClassNotFoundException("Cycle detected while trying to load class: " + name);
}
}
// Resolve the class and return it.
if (resolve)
{
resolveClass(clazz);
}
return clazz;
}
@Override
protected Class findClass(String name) throws ClassNotFoundException
{
Class clazz = findLoadedClass(name);
// Search for class in bundle revision.
if (clazz == null)
{
// Do a quick check to try to avoid searching for classes on a
// disposed class loader, which will avoid some odd exception.
// This won't prevent all weird exception, since the wiring could
// still get disposed of after this check, but it will prevent
// some, perhaps.
if (m_wiring.m_isDisposed)
{
throw new ClassNotFoundException(
"Unable to load class '"
+ name
+ "' because the bundle wiring for "
+ m_wiring.m_revision.getSymbolicName()
+ " is no longer valid.");
}
String actual = name.replace('.', '/') + ".class";
byte[] bytes = null;
// Check the bundle class path.
List<Content> contentPath = m_wiring.m_revision.getContentPath();
Content content = null;
for (int i = 0;
(bytes == null) &&
(i < contentPath.size()); i++)
{
bytes = contentPath.get(i).getEntryAsBytes(actual);
content = contentPath.get(i);
}
if (bytes != null)
{
// Get package name.
String pkgName = Util.getClassPackage(name);
// Get weaving hooks and invoke them to give them a
// chance to weave the class' byte code before we
// define it.
// NOTE: We don't try to dynamically track hook addition
// or removal, we just get a snapshot and leave any changes
// as a race condition, doing any necessary clean up in
// the error handling.
Felix felix = m_wiring.m_revision.getBundle().getFramework();
Set<ServiceReference<WeavingHook>> hooks =
felix.getHookRegistry().getHooks(WeavingHook.class);
Set<ServiceReference<WovenClassListener>> wovenClassListeners =
felix.getHookRegistry().getHooks(WovenClassListener.class);
WovenClassImpl wci = null;
if (!hooks.isEmpty())
{
// Create woven class to be used for hooks.
wci = new WovenClassImpl(name, m_wiring, bytes);
try
{
transformClass(felix, wci, hooks, wovenClassListeners,
name, bytes);
}
catch (Error e)
{
// Mark the woven class as incomplete.
wci.complete();
wci.setState(WovenClass.TRANSFORMING_FAILED);
callWovenClassListeners(felix, wovenClassListeners, wci);
throw e;
}
}
try
{
clazz = isParallel() ? defineClassParallel(name, felix, wovenClassListeners, wci, bytes, content, pkgName) :
defineClassNotParallel(name, felix, wovenClassListeners, wci, bytes, content, pkgName);
}
catch (ClassFormatError e)
{
if (wci != null)
{
wci.setState(WovenClass.DEFINE_FAILED);
callWovenClassListeners(felix, wovenClassListeners, wci);
}
throw e;
}
// Perform deferred activation without holding the class loader lock,
// if the class we are returning is the instigating class.
List deferredList = (List) m_deferredActivation.get();
if ((deferredList != null)
&& (deferredList.size() > 0)
&& ((Object[]) deferredList.get(0))[0].equals(name))
{
// Null the deferred list.
m_deferredActivation.set(null);
while (!deferredList.isEmpty())
{
// Lazy bundles should be activated in the reverse order
// of when they were added to the deferred list, so grab
// them from the end of the deferred list.
Object[] lazy = (Object[]) deferredList.remove(deferredList.size() - 1);
try
{
felix.getFramework().activateBundle((BundleImpl) (lazy)[1], true);
}
catch (Throwable ex)
{
m_logger.log((BundleImpl) (lazy)[1],
Logger.LOG_WARNING,
"Unable to lazily start bundle.",
ex);
}
}
}
}
}
return clazz;
}
Class defineClassParallel(String name, Felix felix, Set<ServiceReference<WovenClassListener>> wovenClassListeners, WovenClassImpl wci, byte[] bytes,
Content content, String pkgName) throws ClassFormatError
{
Class clazz = null;
Thread me = Thread.currentThread();
while (clazz == null && m_classLocks.putIfAbsent(name, me) != me)
{
clazz = findLoadedClass(name);
}
if (clazz == null)
{
try
{
clazz = findLoadedClass(name);
if (clazz == null)
{
clazz = defineClass(felix, wovenClassListeners, wci, name,
bytes, content, pkgName);
}
}
finally
{
m_classLocks.remove(name);
}
}
return clazz;
}
Class defineClassNotParallel(String name, Felix felix, Set<ServiceReference<WovenClassListener>> wovenClassListeners, WovenClassImpl wci, byte[] bytes,
Content content, String pkgName) throws ClassFormatError
{
Class clazz = findLoadedClass(name);
if (clazz == null)
{
synchronized (m_classLocks)
{
clazz = findLoadedClass(name);
if (clazz == null)
{
clazz = defineClass(felix, wovenClassListeners, wci, name,
bytes, content, pkgName);
}
}
}
return clazz;
}
Class defineClass(Felix felix,
Set<ServiceReference<WovenClassListener>> wovenClassListeners,
WovenClassImpl wci, String name, byte[] bytes, Content content, String pkgName)
throws ClassFormatError
{
// If we have a woven class then get the class bytes from
// it since they may have changed.
// NOTE: We are taking a snapshot of these values and
// are not preventing a malbehaving weaving hook from
// modifying them after the fact. The price of preventing
// this isn't worth it, since they can already wreck
// havoc via weaving anyway. However, we do pass the
// snapshot values into the woven class when we mark it
// as complete so that it will refect the actual values
// we used to define the class.
if (wci != null)
{
bytes = wci._getBytes();
List<String> wovenImports = wci.getDynamicImportsInternal();
// Try to add any woven dynamic imports, since they
// could potentially be needed when defining the class.
List<BundleRequirement> allWovenReqs =
new ArrayList<BundleRequirement>();
for (String s : wovenImports)
{
try
{
List<BundleRequirement> wovenReqs =
ManifestParser.parseDynamicImportHeader(
m_logger, m_wiring.m_revision, s);
allWovenReqs.addAll(wovenReqs);
}
catch (BundleException ex)
{
// There should be no exception here
// since we checked syntax before adding
// dynamic import strings to list.
}
}
// Add the dynamic requirements.
if (!allWovenReqs.isEmpty())
{
// Check for duplicate woven imports.
// First grab existing woven imports, if any.
Set<String> filters = new HashSet<String>();
if (m_wiring.m_wovenReqs != null)
{
for (BundleRequirement req : m_wiring.m_wovenReqs)
{
filters.add(
((BundleRequirementImpl) req)
.getFilter().toString());
}
}
// Then check new woven imports for duplicates
// against existing and self.
int idx = allWovenReqs.size();
while (idx < allWovenReqs.size())
{
BundleRequirement wovenReq = allWovenReqs.get(idx);
String filter = ((BundleRequirementImpl)
wovenReq).getFilter().toString();
if (!filters.contains(filter))
{
filters.add(filter);
idx++;
}
else
{
allWovenReqs.remove(idx);
}
}
// Merge existing with new imports, if any.
if (!allWovenReqs.isEmpty())
{
if (m_wiring.m_wovenReqs != null)
{
allWovenReqs.addAll(0, m_wiring.m_wovenReqs);
}
m_wiring.m_wovenReqs = allWovenReqs;
}
}
}
int activationPolicy =
getBundle().isDeclaredActivationPolicyUsed()
? getBundle()
.adapt(BundleRevisionImpl.class).getDeclaredActivationPolicy()
: EAGER_ACTIVATION;
// If the revision is using deferred activation, then if
// we load this class from this revision we need to activate
// the bundle before returning the class. We will short
// circuit the trigger matching if the trigger is already
// tripped.
boolean isTriggerClass = m_isActivationTriggered
? false : m_wiring.m_revision.isActivationTrigger(pkgName);
if (!m_isActivationTriggered
&& isTriggerClass
&& (activationPolicy == BundleRevisionImpl.LAZY_ACTIVATION)
&& (getBundle().getState() == Bundle.STARTING))
{
List deferredList = (List) m_deferredActivation.get();
if (deferredList == null)
{
deferredList = new ArrayList();
m_deferredActivation.set(deferredList);
}
deferredList.add(new Object[]{name, getBundle()});
}
// We need to try to define a Package object for the class
// before we call defineClass() if we haven't already
// created it.
if (pkgName.length() > 0)
{
if (getPackage(pkgName) == null)
{
Object[] params = definePackage(pkgName);
// This is a harmless check-then-act situation,
// where threads might be racing to create different
// classes in the same package, so catch and ignore
// any IAEs that may occur.
try
{
definePackage(
pkgName,
(String) params[0],
(String) params[1],
(String) params[2],
(String) params[3],
(String) params[4],
(String) params[5],
null);
}
catch (IllegalArgumentException ex)
{
// Ignore.
}
}
}
Class clazz = null;
// If we have a security context, then use it to
// define the class with it for security purposes,
// otherwise define the class without a protection domain.
if (m_wiring.m_revision.getProtectionDomain() != null)
{
clazz = defineClass(name, bytes, 0, bytes.length,
m_wiring.m_revision.getProtectionDomain());
}
else
{
clazz = defineClass(name, bytes, 0, bytes.length);
}
if (wci != null)
{
wci.completeDefine(clazz);
wci.setState(WovenClass.DEFINED);
callWovenClassListeners(felix, wovenClassListeners, wci);
}
// At this point if we have a trigger class, then the deferred
// activation trigger has tripped.
if (!m_isActivationTriggered && isTriggerClass && (clazz != null))
{
m_isActivationTriggered = true;
}
return clazz;
}
void transformClass(Felix felix, WovenClassImpl wci,
Set<ServiceReference<WeavingHook>> hooks,
Set<ServiceReference<WovenClassListener>> wovenClassListeners,
String name, byte[] bytes) throws Error {
// Loop through hooks in service ranking order.
for (ServiceReference<WeavingHook> sr : hooks)
{
// Only use the hook if it is not black listed.
if (!felix.getHookRegistry().isHookBlackListed(sr))
{
// Get the hook service object.
// Note that we don't use the bundle context
// to get the service object since that would
// perform sercurity checks.
WeavingHook wh = felix.getService(felix, sr, false);
if (wh != null)
{
try
{
BundleRevisionImpl.getSecureAction()
.invokeWeavingHook(wh, wci);
}
catch (Throwable th)
{
if (!(th instanceof WeavingException))
{
felix.getHookRegistry().blackListHook(sr);
}
felix.fireFrameworkEvent(
FrameworkEvent.ERROR,
sr.getBundle(),
th);
// Throw class format exception per spec.
Error error = new ClassFormatError("Weaving hook failed.");
error.initCause(th);
throw error;
}
finally
{
felix.ungetService(felix, sr, null);
}
}
}
}
wci.setState(WovenClass.TRANSFORMED);
callWovenClassListeners(felix, wovenClassListeners, wci);
}
protected void callWovenClassListeners(Felix felix, Set<ServiceReference<WovenClassListener>> wovenClassListeners, WovenClass wovenClass)
{
if(wovenClassListeners != null)
{
for(ServiceReference<WovenClassListener> currentWovenClassListenerRef : wovenClassListeners)
{
WovenClassListener currentWovenClassListner = felix.getService(felix, currentWovenClassListenerRef, false);
try
{
BundleRevisionImpl.getSecureAction().invokeWovenClassListener(currentWovenClassListner, wovenClass);
}
catch (Exception e)
{
m_logger.log(Logger.LOG_ERROR, "Woven Class Listner failed.", e);
}
finally
{
felix.ungetService(felix, currentWovenClassListenerRef, null);
}
}
}
}
private Object[] definePackage(String pkgName)
{
String spectitle = (String) m_wiring.m_revision.getHeaders().get("Specification-Title");
String specversion = (String) m_wiring.m_revision.getHeaders().get("Specification-Version");
String specvendor = (String) m_wiring.m_revision.getHeaders().get("Specification-Vendor");
String impltitle = (String) m_wiring.m_revision.getHeaders().get("Implementation-Title");
String implversion = (String) m_wiring.m_revision.getHeaders().get("Implementation-Version");
String implvendor = (String) m_wiring.m_revision.getHeaders().get("Implementation-Vendor");
if ((spectitle != null)
|| (specversion != null)
|| (specvendor != null)
|| (impltitle != null)
|| (implversion != null)
|| (implvendor != null))
{
return new Object[] {
spectitle, specversion, specvendor, impltitle, implversion, implvendor
};
}
return new Object[] {null, null, null, null, null, null};
}
@Override
public URL getResource(String name)
{
URL url = m_wiring.getResourceByDelegation(name);
if (m_wiring.m_useLocalURLs)
{
url = convertToLocalUrl(url);
}
return url;
}
@Override
protected URL findResource(String name)
{
return m_wiring.m_revision.getResourceLocal(name);
}
@Override
protected Enumeration findResources(String name)
{
return m_wiring.m_revision.getResourcesLocal(name);
}
@Override
protected String findLibrary(String name)
{
// Remove leading slash, if present.
if (name.startsWith("/"))
{
name = name.substring(1);
}
String result = null;
// CONCURRENCY: In the long run, we might want to break this
// sync block in two to avoid manipulating the cache while
// holding the lock, but for now we will do it the simple way.
synchronized (this)
{
// Check to make sure we haven't already found this library.
for (int i = 0; (result == null) && (i < m_cachedLibs.length); i++)
{
if (m_cachedLibs[i][LIBNAME_IDX].equals(name))
{
result = (String) m_cachedLibs[i][LIBPATH_IDX];
}
}
// If we don't have a cached result, see if we have a matching
// native library.
if (result == null)
{
List<NativeLibrary> libs = m_wiring.getNativeLibraries();
for (int libIdx = 0; (libs != null) && (libIdx < libs.size()); libIdx++)
{
if (libs.get(libIdx).match(m_wiring.m_configMap, name))
{
// Search bundle content first for native library.
result = m_wiring.m_revision.getContent().getEntryAsNativeLibrary(
libs.get(libIdx).getEntryName());
// If not found, then search fragments in order.
for (int i = 0;
(result == null) && (m_wiring.m_fragmentContents != null)
&& (i < m_wiring.m_fragmentContents.size());
i++)
{
result = m_wiring.m_fragmentContents.get(i).getEntryAsNativeLibrary(
libs.get(libIdx).getEntryName());
}
}
}
// Remember the result for future requests.
if (result != null)
{
Object[][] tmp = new Object[m_cachedLibs.length + 1][];
System.arraycopy(m_cachedLibs, 0, tmp, 0, m_cachedLibs.length);
tmp[m_cachedLibs.length] = new Object[] { name, result };
m_cachedLibs = tmp;
}
}
}
return result;
}
protected boolean isParallel()
{
return m_isParallel;
}
@Override
public Enumeration getResources(String name)
{
Enumeration urls = m_wiring.getResourcesByDelegation(name);
if (m_wiring.m_useLocalURLs)
{
urls = new ToLocalUrlEnumeration(urls);
}
return urls;
}
@Override
public String toString()
{
return m_wiring.toString();
}
Class<?> findLoadedClassInternal(String name)
{
return super.findLoadedClass(name);
}
}
static URL convertToLocalUrl(URL url)
{
if (url.getProtocol().equals("bundle"))
{
try
{
url = ((URLHandlersBundleURLConnection)
url.openConnection()).getLocalURL();
}
catch (IOException ex)
{
// Ignore and add original url.
}
}
return url;
}
private static class ResourceSource implements Comparable<ResourceSource>
{
public final String m_resource;
public final BundleRevision m_revision;
public ResourceSource(String resource, BundleRevision revision)
{
m_resource = resource;
m_revision = revision;
}
@Override
public boolean equals(Object o)
{
if (o instanceof ResourceSource)
{
return m_resource.equals(((ResourceSource) o).m_resource);
}
return false;
}
@Override
public int hashCode()
{
return m_resource.hashCode();
}
@Override
public int compareTo(ResourceSource t)
{
return m_resource.compareTo(t.m_resource);
}
@Override
public String toString()
{
return m_resource
+ " -> "
+ m_revision.getSymbolicName()
+ " [" + m_revision + "]";
}
}
private static String diagnoseClassLoadError(
StatefulResolver resolver, BundleRevision revision, String name)
{
// We will try to do some diagnostics here to help the developer
// deal with this exception.
// Get package name.
String pkgName = Util.getClassPackage(name);
if (pkgName.length() == 0)
{
return null;
}
// First, get the bundle string of the revision doing the class loader.
String importer = revision.getBundle().toString();
// Next, check to see if the revision imports the package.
List<BundleWire> wires = (revision.getWiring() == null)
? null : revision.getWiring().getProvidedWires(null);
for (int i = 0; (wires != null) && (i < wires.size()); i++)
{
if (wires.get(i).getCapability().getNamespace().equals(BundleRevision.PACKAGE_NAMESPACE) &&
wires.get(i).getCapability().getAttributes().get(BundleRevision.PACKAGE_NAMESPACE).equals(pkgName))
{
String exporter = wires.get(i).getProviderWiring().getBundle().toString();
StringBuilder sb = new StringBuilder("*** Package '");
sb.append(pkgName);
sb.append("' is imported by bundle ");
sb.append(importer);
sb.append(" from bundle ");
sb.append(exporter);
sb.append(", but the exported package from bundle ");
sb.append(exporter);
sb.append(" does not contain the requested class '");
sb.append(name);
sb.append("'. Please verify that the class name is correct in the importing bundle ");
sb.append(importer);
sb.append(" and/or that the exported package is correctly bundled in ");
sb.append(exporter);
sb.append(". ***");
return sb.toString();
}
}
// Next, check to see if the package was optionally imported and
// whether or not there is an exporter available.
List<BundleRequirement> reqs = revision.getWiring().getRequirements(null);
/*
* TODO: RB - Fix diagnostic message for optional imports.
for (int i = 0; (reqs != null) && (i < reqs.length); i++)
{
if (reqs[i].getName().equals(pkgName) && reqs[i].isOptional())
{
// Try to see if there is an exporter available.
IModule[] exporters = getResolvedExporters(reqs[i], true);
exporters = (exporters.length == 0)
? getUnresolvedExporters(reqs[i], true) : exporters;
// An exporter might be available, but it may have attributes
// that do not match the importer's required attributes, so
// check that case by simply looking for an exporter of the
// desired package without any attributes.
if (exporters.length == 0)
{
IRequirement pkgReq = new Requirement(
ICapability.PACKAGE_NAMESPACE, "(package=" + pkgName + ")");
exporters = getResolvedExporters(pkgReq, true);
exporters = (exporters.length == 0)
? getUnresolvedExporters(pkgReq, true) : exporters;
}
long expId = (exporters.length == 0)
? -1 : Util.getBundleIdFromModuleId(exporters[0].getId());
StringBuilder sb = new StringBuilder("*** Class '");
sb.append(name);
sb.append("' was not found, but this is likely normal since package '");
sb.append(pkgName);
sb.append("' is optionally imported by bundle ");
sb.append(impId);
sb.append(".");
if (exporters.length > 0)
{
sb.append(" However, bundle ");
sb.append(expId);
if (reqs[i].isSatisfied(
Util.getExportPackage(exporters[0], reqs[i].getName())))
{
sb.append(" does export this package. Bundle ");
sb.append(expId);
sb.append(" must be installed before bundle ");
sb.append(impId);
sb.append(" is resolved or else the optional import will be ignored.");
}
else
{
sb.append(" does export this package with attributes that do not match.");
}
}
sb.append(" ***");
return sb.toString();
}
}
*/
// Next, check to see if the package is dynamically imported by the revision.
if (resolver.isAllowedDynamicImport(revision, pkgName))
{
// Try to see if there is an exporter available.
Map<String, String> dirs = Collections.EMPTY_MAP;
Map<String, Object> attrs = Collections.singletonMap(
BundleRevision.PACKAGE_NAMESPACE, (Object) pkgName);
BundleRequirementImpl req = new BundleRequirementImpl(
revision, BundleRevision.PACKAGE_NAMESPACE, dirs, attrs);
List<BundleCapability> exporters = resolver.findProviders(req, false);
BundleRevision provider = null;
try
{
provider = resolver.resolve(revision, pkgName);
}
catch (Exception ex)
{
provider = null;
}
String exporter = (exporters.isEmpty())
? null : exporters.iterator().next().toString();
StringBuilder sb = new StringBuilder("*** Class '");
sb.append(name);
sb.append("' was not found, but this is likely normal since package '");
sb.append(pkgName);
sb.append("' is dynamically imported by bundle ");
sb.append(importer);
sb.append(".");
if ((exporters.size() > 0) && (provider == null))
{
sb.append(" However, bundle ");
sb.append(exporter);
sb.append(" does export this package with attributes that do not match.");
}
sb.append(" ***");
return sb.toString();
}
// Next, check to see if there are any exporters for the package at all.
Map<String, String> dirs = Collections.EMPTY_MAP;
Map<String, Object> attrs = Collections.singletonMap(
BundleRevision.PACKAGE_NAMESPACE, (Object) pkgName);
BundleRequirementImpl req = new BundleRequirementImpl(
revision, BundleRevision.PACKAGE_NAMESPACE, dirs, attrs);
List<BundleCapability> exports = resolver.findProviders(req, false);
if (exports.size() > 0)
{
boolean classpath = false;
try
{
BundleRevisionImpl.getSecureAction()
.getClassLoader(BundleClassLoader.class).loadClass(name);
classpath = true;
}
catch (NoClassDefFoundError err)
{
// Ignore
}
catch (Exception ex)
{
// Ignore
}
String exporter = exports.iterator().next().toString();
StringBuilder sb = new StringBuilder("*** Class '");
sb.append(name);
sb.append("' was not found because bundle ");
sb.append(importer);
sb.append(" does not import '");
sb.append(pkgName);
sb.append("' even though bundle ");
sb.append(exporter);
sb.append(" does export it.");
if (classpath)
{
sb.append(" Additionally, the class is also available from the system class loader. There are two fixes: 1) Add an import for '");
sb.append(pkgName);
sb.append("' to bundle ");
sb.append(importer);
sb.append("; imports are necessary for each class directly touched by bundle code or indirectly touched, such as super classes if their methods are used. ");
sb.append("2) Add package '");
sb.append(pkgName);
sb.append("' to the '");
sb.append(Constants.FRAMEWORK_BOOTDELEGATION);
sb.append("' property; a library or VM bug can cause classes to be loaded by the wrong class loader. The first approach is preferable for preserving modularity.");
}
else
{
sb.append(" To resolve this issue, add an import for '");
sb.append(pkgName);
sb.append("' to bundle ");
sb.append(importer);
sb.append(".");
}
sb.append(" ***");
return sb.toString();
}
// Next, try to see if the class is available from the system
// class loader.
try
{
BundleRevisionImpl.getSecureAction()
.getClassLoader(BundleClassLoader.class).loadClass(name);
StringBuilder sb = new StringBuilder("*** Package '");
sb.append(pkgName);
sb.append("' is not imported by bundle ");
sb.append(importer);
sb.append(", nor is there any bundle that exports package '");
sb.append(pkgName);
sb.append("'. However, the class '");
sb.append(name);
sb.append("' is available from the system class loader. There are two fixes: 1) Add package '");
sb.append(pkgName);
sb.append("' to the '");
sb.append(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA);
sb.append("' property and modify bundle ");
sb.append(importer);
sb.append(" to import this package; this causes the system bundle to export class path packages. 2) Add package '");
sb.append(pkgName);
sb.append("' to the '");
sb.append(Constants.FRAMEWORK_BOOTDELEGATION);
sb.append("' property; a library or VM bug can cause classes to be loaded by the wrong class loader. The first approach is preferable for preserving modularity.");
sb.append(" ***");
return sb.toString();
}
catch (Exception ex2)
{
}
// Finally, if there are no imports or exports for the package
// and it is not available on the system class path, simply
// log a message saying so.
StringBuilder sb = new StringBuilder("*** Class '");
sb.append(name);
sb.append("' was not found. Bundle ");
sb.append(importer);
sb.append(" does not import package '");
sb.append(pkgName);
sb.append("', nor is the package exported by any other bundle or available from the system class loader.");
sb.append(" ***");
return sb.toString();
}
}
|
framework/src/main/java/org/apache/felix/framework/BundleWiringImpl.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.felix.framework;
import org.apache.felix.framework.cache.ConnectContentContent;
import org.apache.felix.framework.cache.Content;
import org.apache.felix.framework.capabilityset.SimpleFilter;
import org.apache.felix.framework.resolver.ResourceNotFoundException;
import org.apache.felix.framework.util.CompoundEnumeration;
import org.apache.felix.framework.util.FelixConstants;
import org.apache.felix.framework.util.SecurityManagerEx;
import org.apache.felix.framework.util.Util;
import org.apache.felix.framework.util.manifestparser.ManifestParser;
import org.apache.felix.framework.util.manifestparser.NativeLibrary;
import org.apache.felix.framework.wiring.BundleRequirementImpl;
import org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleException;
import org.osgi.framework.BundleReference;
import org.osgi.framework.CapabilityPermission;
import org.osgi.framework.Constants;
import org.osgi.framework.FrameworkEvent;
import org.osgi.framework.PackagePermission;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.hooks.weaving.WeavingException;
import org.osgi.framework.hooks.weaving.WeavingHook;
import org.osgi.framework.hooks.weaving.WovenClass;
import org.osgi.framework.hooks.weaving.WovenClassListener;
import org.osgi.framework.namespace.IdentityNamespace;
import org.osgi.framework.wiring.BundleCapability;
import org.osgi.framework.wiring.BundleRequirement;
import org.osgi.framework.wiring.BundleRevision;
import org.osgi.framework.wiring.BundleWire;
import org.osgi.framework.wiring.BundleWiring;
import org.osgi.resource.Capability;
import org.osgi.resource.Requirement;
import org.osgi.resource.Wire;
import org.osgi.service.resolver.ResolutionException;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.security.SecureClassLoader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
public class BundleWiringImpl implements BundleWiring
{
public final static int LISTRESOURCES_DEBUG = 1048576;
public final static int EAGER_ACTIVATION = 0;
public final static int LAZY_ACTIVATION = 1;
public static final ClassLoader CNFE_CLASS_LOADER = new ClassLoader()
{
@Override
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException
{
throw new ClassNotFoundException("Unable to load class '" + name + "'");
}
};
private final Logger m_logger;
private final Map m_configMap;
private final StatefulResolver m_resolver;
private final BundleRevisionImpl m_revision;
private final List<BundleRevision> m_fragments;
// Wire list is copy-on-write since it may change due to
// dynamic imports.
private volatile List<BundleWire> m_wires;
// Imported package map is copy-on-write since it may change
// due to dynamic imports.
private volatile Map<String, BundleRevision> m_importedPkgs;
private final Map<String, List<BundleRevision>> m_requiredPkgs;
private final List<BundleCapability> m_resolvedCaps;
private final Map<String, List<List<String>>> m_includedPkgFilters;
private final Map<String, List<List<String>>> m_excludedPkgFilters;
private final List<BundleRequirement> m_resolvedReqs;
private final List<NativeLibrary> m_resolvedNativeLibs;
private final List<Content> m_fragmentContents;
private volatile List<BundleRequirement> m_wovenReqs = null;
private volatile ClassLoader m_classLoader;
// Bundle-specific class loader for boot delegation.
private final ClassLoader m_bootClassLoader;
// Default class loader for boot delegation.
private final static ClassLoader m_defBootClassLoader;
// Statically define the default class loader for boot delegation.
static
{
ClassLoader cl = null;
try
{
cl = (ClassLoader) BundleRevisionImpl.getSecureAction().invokeDirect(
BundleRevisionImpl.getSecureAction().getMethod(ClassLoader.class, "getPlatformClassLoader", null)
,null, null);
}
catch (Throwable t)
{
// Not on Java9
try
{
Constructor ctor = BundleRevisionImpl.getSecureAction().getDeclaredConstructor(
SecureClassLoader.class, new Class[]{ClassLoader.class});
BundleRevisionImpl.getSecureAction().setAccesssible(ctor);
cl = (ClassLoader) BundleRevisionImpl.getSecureAction().invoke(
ctor, new Object[]{null});
}
catch (Throwable ex)
{
// On Android we get an exception if we set the parent class loader
// to null, so we will work around that case by setting the parent
// class loader to the system class loader in getClassLoader() below.
cl = null;
System.err.println("Problem creating boot delegation class loader: " + ex);
}
}
m_defBootClassLoader = cl;
}
// Boolean flag to enable/disable implicit boot delegation.
private final boolean m_implicitBootDelegation;
// Boolean flag to enable/disable local URLs.
private final boolean m_useLocalURLs;
// Re-usable security manager for accessing class context.
private static SecurityManagerEx m_sm = new SecurityManagerEx();
// Thread local to detect class loading cycles.
private final ThreadLocal m_cycleCheck = new ThreadLocal();
// Thread local to keep track of deferred activation.
private static final ThreadLocal m_deferredActivation = new ThreadLocal();
// Flag indicating whether this wiring has been disposed.
private volatile boolean m_isDisposed = false;
private volatile ConcurrentHashMap<String, ClassLoader> m_accessorLookupCache;
BundleWiringImpl(
Logger logger, Map configMap, StatefulResolver resolver,
BundleRevisionImpl revision, List<BundleRevision> fragments,
List<BundleWire> wires,
Map<String, BundleRevision> importedPkgs,
Map<String, List<BundleRevision>> requiredPkgs) throws Exception
{
m_logger = logger;
m_configMap = configMap;
m_resolver = resolver;
m_revision = revision;
m_importedPkgs = importedPkgs;
m_requiredPkgs = requiredPkgs;
m_wires = Util.newImmutableList(wires);
// We need to sort the fragments and add ourself as a dependent of each one.
// We also need to create an array of fragment contents to attach to our
// content path.
List<Content> fragmentContents = null;
if (fragments != null)
{
// Sort fragments according to ID order, if necessary.
// Note that this sort order isn't 100% correct since
// it uses a string, but it is likely close enough and
// avoids having to create more objects.
if (fragments.size() > 1)
{
SortedMap<String, BundleRevision> sorted = new TreeMap<String, BundleRevision>();
for (BundleRevision f : fragments)
{
sorted.put(((BundleRevisionImpl) f).getId(), f);
}
fragments = new ArrayList(sorted.values());
}
fragmentContents = new ArrayList<Content>(fragments.size());
for (int i = 0; (fragments != null) && (i < fragments.size()); i++)
{
fragmentContents.add(
((BundleRevisionImpl) fragments.get(i)).getContent()
.getEntryAsContent(FelixConstants.CLASS_PATH_DOT));
}
}
m_fragments = fragments;
m_fragmentContents = fragmentContents;
// Calculate resolved list of requirements, which includes:
// 1. All requirements for which we have a wire.
// 2. All dynamic imports from the host and any fragments.
// Also create set of imported packages so we can eliminate any
// substituted exports from our resolved capabilities.
Set<String> imports = new HashSet<String>();
List<BundleRequirement> reqList = new ArrayList<BundleRequirement>();
// First add resolved requirements from wires.
for (BundleWire bw : wires)
{
// Fragments may have multiple wires for the same requirement, so we
// need to check for and avoid duplicates in that case.
if (!bw.getRequirement().getNamespace().equals(BundleRevision.HOST_NAMESPACE)
|| !reqList.contains(bw.getRequirement()))
{
reqList.add(bw.getRequirement());
if (bw.getRequirement().getNamespace().equals(BundleRevision.PACKAGE_NAMESPACE))
{
imports.add((String)
bw.getCapability().getAttributes().get(BundleRevision.PACKAGE_NAMESPACE));
}
}
}
// Next add dynamic requirements from host.
for (BundleRequirement req : m_revision.getDeclaredRequirements(null))
{
if (req.getNamespace().equals(BundleRevision.PACKAGE_NAMESPACE))
{
String resolution = req.getDirectives().get(Constants.RESOLUTION_DIRECTIVE);
if ((resolution != null) && (resolution.equals("dynamic")))
{
reqList.add(req);
}
}
}
// Finally, add dynamic requirements from fragments.
if (m_fragments != null)
{
for (BundleRevision fragment : m_fragments)
{
for (BundleRequirement req : fragment.getDeclaredRequirements(null))
{
if (req.getNamespace().equals(BundleRevision.PACKAGE_NAMESPACE))
{
String resolution = req.getDirectives().get(Constants.RESOLUTION_DIRECTIVE);
if ((resolution != null) && (resolution.equals("dynamic")))
{
reqList.add(req);
}
}
}
}
}
m_resolvedReqs = Util.newImmutableList(reqList);
// Calculate resolved list of capabilities, which includes:
// 1. All capabilities from host and any fragments except for exported
// packages that we have an import (i.e., the export was substituted).
// 2. For fragments the identity capability only.
// And nothing else at this time.
boolean isFragment = Util.isFragment(revision);
List<BundleCapability> capList = new ArrayList<BundleCapability>();
// Also keep track of whether any resolved package capabilities are filtered.
Map<String, List<List<String>>> includedPkgFilters =
new HashMap<String, List<List<String>>>();
Map<String, List<List<String>>> excludedPkgFilters =
new HashMap<String, List<List<String>>>();
if (isFragment)
{
// This is a fragment, add its identity capability
for (BundleCapability cap : m_revision.getDeclaredCapabilities(null))
{
if (IdentityNamespace.IDENTITY_NAMESPACE.equals(cap.getNamespace()))
{
String effective = cap.getDirectives().get(Constants.EFFECTIVE_DIRECTIVE);
if ((effective == null) || (effective.equals(Constants.EFFECTIVE_RESOLVE)))
{
capList.add(cap);
}
}
}
}
else
{
for (BundleCapability cap : m_revision.getDeclaredCapabilities(null))
{
if (!cap.getNamespace().equals(BundleRevision.PACKAGE_NAMESPACE)
|| (cap.getNamespace().equals(BundleRevision.PACKAGE_NAMESPACE)
&& !imports.contains(cap.getAttributes()
.get(BundleRevision.PACKAGE_NAMESPACE).toString())))
{
// TODO: OSGi R4.4 - We may need to make this more flexible since in the future it may
// be possible to consider other effective values via OBR's Environment.isEffective().
String effective = cap.getDirectives().get(Constants.EFFECTIVE_DIRECTIVE);
if ((effective == null) || (effective.equals(Constants.EFFECTIVE_RESOLVE)))
{
capList.add(cap);
if (cap.getNamespace().equals(BundleRevision.PACKAGE_NAMESPACE))
{
List<List<String>> filters =
parsePkgFilters(cap, Constants.INCLUDE_DIRECTIVE);
if (filters != null)
{
includedPkgFilters.put((String)
cap.getAttributes().get(BundleRevision.PACKAGE_NAMESPACE),
filters);
}
filters = parsePkgFilters(cap, Constants.EXCLUDE_DIRECTIVE);
if (filters != null)
{
excludedPkgFilters.put((String)
cap.getAttributes().get(BundleRevision.PACKAGE_NAMESPACE),
filters);
}
}
}
}
}
if (m_fragments != null)
{
for (BundleRevision fragment : m_fragments)
{
for (BundleCapability cap : fragment.getDeclaredCapabilities(null))
{
if (IdentityNamespace.IDENTITY_NAMESPACE.equals(cap.getNamespace())) {
// The identity capability is not transferred from the fragment to the bundle
continue;
}
if (!cap.getNamespace().equals(BundleRevision.PACKAGE_NAMESPACE)
|| (cap.getNamespace().equals(BundleRevision.PACKAGE_NAMESPACE)
&& !imports.contains(cap.getAttributes()
.get(BundleRevision.PACKAGE_NAMESPACE).toString())))
{
// TODO: OSGi R4.4 - We may need to make this more flexible since in the future it may
// be possible to consider other effective values via OBR's Environment.isEffective().
String effective = cap.getDirectives().get(Constants.EFFECTIVE_DIRECTIVE);
if ((effective == null) || (effective.equals(Constants.EFFECTIVE_RESOLVE)))
{
capList.add(cap);
if (cap.getNamespace().equals(
BundleRevision.PACKAGE_NAMESPACE))
{
List<List<String>> filters =
parsePkgFilters(
cap, Constants.INCLUDE_DIRECTIVE);
if (filters != null)
{
includedPkgFilters.put((String)
cap.getAttributes()
.get(BundleRevision.PACKAGE_NAMESPACE),
filters);
}
filters = parsePkgFilters(cap, Constants.EXCLUDE_DIRECTIVE);
if (filters != null)
{
excludedPkgFilters.put((String)
cap.getAttributes()
.get(BundleRevision.PACKAGE_NAMESPACE),
filters);
}
}
}
}
}
}
}
}
if (System.getSecurityManager() != null)
{
for (Iterator<BundleCapability> iter = capList.iterator();iter.hasNext();)
{
BundleCapability cap = iter.next();
if (cap.getNamespace().equals(BundleRevision.PACKAGE_NAMESPACE))
{
if (!((BundleProtectionDomain) ((BundleRevisionImpl) cap.getRevision()).getProtectionDomain()).impliesDirect(
new PackagePermission((String) cap.getAttributes().get(BundleRevision.PACKAGE_NAMESPACE), PackagePermission.EXPORTONLY)))
{
iter.remove();
}
}
else if (!cap.getNamespace().equals(BundleRevision.HOST_NAMESPACE) && !cap.getNamespace().equals(BundleRevision.BUNDLE_NAMESPACE) &&
!cap.getNamespace().equals("osgi.ee"))
{
if (!((BundleProtectionDomain) ((BundleRevisionImpl) cap.getRevision()).getProtectionDomain()).impliesDirect(
new CapabilityPermission(cap.getNamespace(), CapabilityPermission.PROVIDE)))
{
iter.remove();
}
}
}
}
m_resolvedCaps = Util.newImmutableList(capList);
m_includedPkgFilters = (includedPkgFilters.isEmpty())
? Collections.EMPTY_MAP : includedPkgFilters;
m_excludedPkgFilters = (excludedPkgFilters.isEmpty())
? Collections.EMPTY_MAP : excludedPkgFilters;
List<NativeLibrary> libList = (m_revision.getDeclaredNativeLibraries() == null)
? new ArrayList<NativeLibrary>()
: new ArrayList<NativeLibrary>(m_revision.getDeclaredNativeLibraries());
for (int fragIdx = 0;
(m_fragments != null) && (fragIdx < m_fragments.size());
fragIdx++)
{
List<NativeLibrary> libs =
((BundleRevisionImpl) m_fragments.get(fragIdx))
.getDeclaredNativeLibraries();
for (int reqIdx = 0;
(libs != null) && (reqIdx < libs.size());
reqIdx++)
{
libList.add(libs.get(reqIdx));
}
}
// We need to return null here if we don't have any libraries, since a
// zero-length array is used to indicate that matching native libraries
// could not be found when resolving the bundle.
m_resolvedNativeLibs = (libList.isEmpty()) ? null : Util.newImmutableList(libList);
ClassLoader bootLoader = m_defBootClassLoader;
if (revision.getBundle().getBundleId() != 0)
{
Object map = m_configMap.get(FelixConstants.BOOT_CLASSLOADERS_PROP);
if (map instanceof Map)
{
Object l = ((Map) map).get(m_revision.getBundle());
if (l instanceof ClassLoader)
{
bootLoader = (ClassLoader) l;
}
}
}
m_bootClassLoader = bootLoader;
m_implicitBootDelegation =
(m_configMap.get(FelixConstants.IMPLICIT_BOOT_DELEGATION_PROP) == null)
|| Boolean.valueOf(
(String) m_configMap.get(
FelixConstants.IMPLICIT_BOOT_DELEGATION_PROP));
m_useLocalURLs =
m_configMap.get(FelixConstants.USE_LOCALURLS_PROP) != null;
}
private static List<List<String>> parsePkgFilters(BundleCapability cap, String filtername)
{
List<List<String>> filters = null;
String include = cap.getDirectives().get(filtername);
if (include != null)
{
List<String> filterStrings = ManifestParser.parseDelimitedString(include, ",");
filters = new ArrayList<List<String>>(filterStrings.size());
for (int filterIdx = 0; filterIdx < filterStrings.size(); filterIdx++)
{
List<String> substrings =
SimpleFilter.parseSubstring(filterStrings.get(filterIdx));
filters.add(substrings);
}
}
return filters;
}
@Override
public String toString()
{
return m_revision.getBundle().toString();
}
public synchronized void dispose()
{
if (m_fragmentContents != null)
{
for (Content content : m_fragmentContents)
{
content.close();
}
}
m_classLoader = null;
m_isDisposed = true;
m_accessorLookupCache = null;
}
// TODO: OSGi R4.3 - This really shouldn't be public, but it is needed by the
// resolver to determine if a bundle can dynamically import.
public boolean hasPackageSource(String pkgName)
{
return (m_importedPkgs.containsKey(pkgName) || m_requiredPkgs.containsKey(pkgName));
}
// TODO: OSGi R4.3 - This really shouldn't be public, but it is needed by the
// to implement dynamic imports.
public BundleRevision getImportedPackageSource(String pkgName)
{
return m_importedPkgs.get(pkgName);
}
List<BundleRevision> getFragments()
{
return m_fragments;
}
List<Content> getFragmentContents()
{
return m_fragmentContents;
}
@Override
public boolean isCurrent()
{
BundleRevision current = getBundle().adapt(BundleRevision.class);
return (current != null) && (current.getWiring() == this);
}
@Override
public boolean isInUse()
{
return !m_isDisposed;
}
@Override
public List<Capability> getResourceCapabilities(String namespace)
{
return BundleRevisionImpl.asCapabilityList(getCapabilities(namespace));
}
@Override
public List<BundleCapability> getCapabilities(String namespace)
{
if (isInUse())
{
List<BundleCapability> result = m_resolvedCaps;
if (namespace != null)
{
result = new ArrayList<BundleCapability>();
for (BundleCapability cap : m_resolvedCaps)
{
if (cap.getNamespace().equals(namespace))
{
result.add(cap);
}
}
}
return result;
}
return null;
}
@Override
public List<Requirement> getResourceRequirements(String namespace)
{
return BundleRevisionImpl.asRequirementList(getRequirements(namespace));
}
@Override
public List<BundleRequirement> getRequirements(String namespace)
{
if (isInUse())
{
List<BundleRequirement> searchReqs = m_resolvedReqs;
List<BundleRequirement> wovenReqs = m_wovenReqs;
List<BundleRequirement> result = m_resolvedReqs;
if (wovenReqs != null)
{
searchReqs = new ArrayList<BundleRequirement>(m_resolvedReqs);
searchReqs.addAll(wovenReqs);
result = searchReqs;
}
if (namespace != null)
{
result = new ArrayList<BundleRequirement>();
for (BundleRequirement req : searchReqs)
{
if (req.getNamespace().equals(namespace))
{
result.add(req);
}
}
}
return result;
}
return null;
}
public List<NativeLibrary> getNativeLibraries()
{
return m_resolvedNativeLibs;
}
private static List<Wire> asWireList(List wires)
{
return wires;
}
@Override
public List<Wire> getProvidedResourceWires(String namespace)
{
return asWireList(getProvidedWires(namespace));
}
@Override
public List<BundleWire> getProvidedWires(String namespace)
{
if (isInUse())
{
return m_revision.getBundle()
.getFramework().getDependencies().getProvidedWires(m_revision, namespace);
}
return null;
}
@Override
public List<Wire> getRequiredResourceWires(String namespace)
{
return asWireList(getRequiredWires(namespace));
}
@Override
public List<BundleWire> getRequiredWires(String namespace)
{
if (isInUse())
{
List<BundleWire> result = m_wires;
if (namespace != null)
{
result = new ArrayList<BundleWire>();
for (BundleWire bw : m_wires)
{
if (bw.getRequirement().getNamespace().equals(namespace))
{
result.add(bw);
}
}
}
return result;
}
return null;
}
public synchronized void addDynamicWire(BundleWire wire)
{
// Make new wires list.
List<BundleWire> wires = new ArrayList<BundleWire>(m_wires);
wires.add(wire);
if (wire.getCapability().getAttributes().get(BundleRevision.PACKAGE_NAMESPACE) != null)
{
// Make new imported package map.
Map<String, BundleRevision> importedPkgs =
new HashMap<String, BundleRevision>(m_importedPkgs);
importedPkgs.put(
(String) wire.getCapability().getAttributes().get(BundleRevision.PACKAGE_NAMESPACE),
wire.getProviderWiring().getRevision());
m_importedPkgs = importedPkgs;
}
// Update associated member values.
// Technically, there is a window here where readers won't see
// both values updates at the same time, but it seems unlikely
// to cause any issues.
m_wires = Util.newImmutableList(wires);
}
@Override
public BundleRevision getResource()
{
return m_revision;
}
@Override
public BundleRevision getRevision()
{
return m_revision;
}
@Override
public ClassLoader getClassLoader()
{
if (m_isDisposed || Util.isFragment(m_revision))
{
return null;
}
return getClassLoaderInternal();
}
private ClassLoader getClassLoaderInternal()
{
ClassLoader classLoader = m_classLoader;
if (classLoader != null)
{
return classLoader;
}
else
{
return _getClassLoaderInternal();
}
}
private synchronized ClassLoader _getClassLoaderInternal()
{
// Only try to create the class loader if the bundle
// is not disposed.
if (!m_isDisposed && (m_classLoader == null))
{
if (m_revision.getContent() instanceof ConnectContentContent)
{
m_classLoader = ((ConnectContentContent) m_revision.getContent()).getClassLoader();
}
if (m_classLoader == null)
{
m_classLoader = BundleRevisionImpl.getSecureAction().run(
new PrivilegedAction<BundleClassLoader>()
{
@Override
public BundleClassLoader run()
{
return new BundleClassLoader(BundleWiringImpl.this, determineParentClassLoader(), m_logger);
}
}
);
}
}
return m_classLoader;
}
@Override
public List<URL> findEntries(String path, String filePattern, int options)
{
if (isInUse())
{
if (!Util.isFragment(m_revision))
{
Enumeration<URL> e =
m_revision.getBundle().getFramework()
.findBundleEntries(m_revision, path, filePattern,
(options & BundleWiring.FINDENTRIES_RECURSE) > 0);
List<URL> entries = new ArrayList<URL>();
while ((e != null) && e.hasMoreElements())
{
entries.add(e.nextElement());
}
return Util.newImmutableList(entries);
}
return Collections.EMPTY_LIST;
}
return null;
}
// Thread local to detect class loading cycles.
private final ThreadLocal m_listResourcesCycleCheck = new ThreadLocal();
@Override
public Collection<String> listResources(
String path, String filePattern, int options)
{
// Implementation note: If you enable the DEBUG option for
// listResources() to print from where each resource comes,
// it will not give 100% accurate answers in the face of
// Require-Bundle cycles with overlapping content since
// the actual source will depend on who does the class load
// first. Further, normal class loaders cache class load
// results so it is always the same subsequently, but we
// don't do that here so it will always return a different
// result depending upon who is asking. Moral to the story:
// don't do cycles and certainly don't do them with
// overlapping content.
Collection<String> resources = null;
// Normalize path.
if ((path.length() > 0) && (path.charAt(0) == '/'))
{
path = path.substring(1);
}
if ((path.length() > 0) && (path.charAt(path.length() - 1) != '/'))
{
path = path + '/';
}
// Parse the file filter.
filePattern = (filePattern == null) ? "*" : filePattern;
List<String> pattern = SimpleFilter.parseSubstring(filePattern);
// We build an internal collection of ResourceSources, since this
// allows us to print out additional debug information.
Collection<ResourceSource> sources = listResourcesInternal(path, pattern, options);
if (sources != null)
{
boolean debug = (options & LISTRESOURCES_DEBUG) > 0;
resources = new TreeSet<String>();
for (ResourceSource source : sources)
{
if (debug)
{
resources.add(source.toString());
}
else
{
resources.add(source.m_resource);
}
}
}
return resources;
}
private synchronized Collection<ResourceSource> listResourcesInternal(
String path, List<String> pattern, int options)
{
if (isInUse())
{
boolean recurse = (options & BundleWiring.LISTRESOURCES_RECURSE) > 0;
boolean localOnly = (options & BundleWiring.LISTRESOURCES_LOCAL) > 0;
// Check for cycles, which can happen with Require-Bundle.
Set<String> cycles = (Set<String>) m_listResourcesCycleCheck.get();
if (cycles == null)
{
cycles = new HashSet<String>();
m_listResourcesCycleCheck.set(cycles);
}
if (cycles.contains(path))
{
return Collections.EMPTY_LIST;
}
cycles.add(path);
try
{
// Calculate set of remote resources (i.e., those either
// imported or required).
Collection<ResourceSource> remoteResources = new TreeSet<ResourceSource>();
// Imported packages cannot have merged content, so we need to
// keep track of these packages.
Set<String> noMerging = new HashSet<String>();
// Loop through wires to compute remote resources.
for (BundleWire bw : m_wires)
{
if (bw.getCapability().getNamespace()
.equals(BundleRevision.PACKAGE_NAMESPACE))
{
// For imported packages, we only need to calculate
// the remote resources of the specific imported package.
remoteResources.addAll(
calculateRemotePackageResources(
bw, bw.getCapability(), recurse,
path, pattern, noMerging));
}
else if (bw.getCapability().getNamespace()
.equals(BundleRevision.BUNDLE_NAMESPACE))
{
// For required bundles, all declared package capabilities
// from the required bundle will be available to requirers,
// so get the target required bundle's declared packages
// and handle them in a similar fashion to a normal import
// except that their content can be merged with local
// packages.
List<BundleCapability> exports =
bw.getProviderWiring().getRevision()
.getDeclaredCapabilities(BundleRevision.PACKAGE_NAMESPACE);
for (BundleCapability export : exports)
{
remoteResources.addAll(
calculateRemotePackageResources(
bw, export, recurse, path, pattern, null));
}
// Since required bundle may reexport bundles it requires,
// check its wires for this case.
List<BundleWire> requiredBundles =
bw.getProviderWiring().getRequiredWires(
BundleRevision.BUNDLE_NAMESPACE);
for (BundleWire rbWire : requiredBundles)
{
String visibility =
rbWire.getRequirement().getDirectives()
.get(Constants.VISIBILITY_DIRECTIVE);
if ((visibility != null)
&& (visibility.equals(Constants.VISIBILITY_REEXPORT)))
{
// For each reexported required bundle, treat them
// in a similar fashion as a normal required bundle
// by including all of their declared package
// capabilities in the requiring bundle's class
// space.
List<BundleCapability> reexports =
rbWire.getProviderWiring().getRevision()
.getDeclaredCapabilities(BundleRevision.PACKAGE_NAMESPACE);
for (BundleCapability reexport : reexports)
{
remoteResources.addAll(
calculateRemotePackageResources(
bw, reexport, recurse, path, pattern, null));
}
}
}
}
}
// Calculate set of local resources (i.e., those contained
// in the revision or its fragments).
Collection<ResourceSource> localResources = new TreeSet<ResourceSource>();
// Get the revision's content path, which includes contents
// from fragments.
List<Content> contentPath = m_revision.getContentPath();
for (Content content : contentPath)
{
Enumeration<String> e = content.getEntries();
if (e != null)
{
while (e.hasMoreElements())
{
String resource = e.nextElement();
String resourcePath = getTrailingPath(resource);
if (!noMerging.contains(resourcePath))
{
if ((!recurse && resourcePath.equals(path))
|| (recurse && resourcePath.startsWith(path)))
{
if (matchesPattern(pattern, getPathHead(resource)))
{
localResources.add(
new ResourceSource(resource, m_revision));
}
}
}
}
}
}
if (localOnly)
{
return localResources;
}
else
{
remoteResources.addAll(localResources);
return remoteResources;
}
}
finally
{
cycles.remove(path);
if (cycles.isEmpty())
{
m_listResourcesCycleCheck.set(null);
}
}
}
return null;
}
private Collection<ResourceSource> calculateRemotePackageResources(
BundleWire bw, BundleCapability cap, boolean recurse,
String path, List<String> pattern, Set<String> noMerging)
{
Collection<ResourceSource> resources = Collections.EMPTY_SET;
// Convert package name to a path.
String subpath = (String) cap.getAttributes().get(BundleRevision.PACKAGE_NAMESPACE);
subpath = subpath.replace('.', '/') + '/';
// If necessary, record that this package should not be merged
// with local content.
if (noMerging != null)
{
noMerging.add(subpath);
}
// If we are not recuring, check for path equality or if
// we are recursing, check that the subpath starts with
// the target path.
if ((!recurse && subpath.equals(path))
|| (recurse && subpath.startsWith(path)))
{
// Delegate to the original provider wiring to have it calculate
// the list of resources in the package. In this case, we don't
// want to recurse since we want the precise package.
resources =
((BundleWiringImpl) bw.getProviderWiring()).listResourcesInternal(
subpath, pattern, 0);
// The delegatedResources result will include subpackages
// which need to be filtered out, since imported packages
// do not give access to subpackages. If a subpackage is
// imported, it will be added by its own wire.
for (Iterator<ResourceSource> it = resources.iterator();
it.hasNext(); )
{
ResourceSource reqResource = it.next();
if (reqResource.m_resource.charAt(
reqResource.m_resource.length() - 1) == '/')
{
it.remove();
}
}
}
// If we are not recursing, but the required package
// is a child of the desired path, then include its
// immediate child package. We do this so that it is
// possible to use listResources() to walk the resource
// tree similar to doing a directory walk one level
// at a time.
else if (!recurse && subpath.startsWith(path))
{
int idx = subpath.indexOf('/', path.length());
if (idx >= 0)
{
subpath = subpath.substring(0, idx + 1);
}
if (matchesPattern(pattern, getPathHead(subpath)))
{
resources = Collections.singleton(
new ResourceSource(subpath, bw.getProviderWiring().getRevision()));
}
}
return resources;
}
private static String getPathHead(String resource)
{
if (resource.length() == 0)
{
return resource;
}
int idx = (resource.charAt(resource.length() - 1) == '/')
? resource.lastIndexOf('/', resource.length() - 2)
: resource.lastIndexOf('/');
if (idx < 0)
{
return resource;
}
return resource.substring(idx + 1);
}
private static String getTrailingPath(String resource)
{
if (resource.length() == 0)
{
return null;
}
int idx = (resource.charAt(resource.length() - 1) == '/')
? resource.lastIndexOf('/', resource.length() - 2)
: resource.lastIndexOf('/');
if (idx < 0)
{
return "";
}
return resource.substring(0, idx + 1);
}
private static boolean matchesPattern(List<String> pattern, String resource)
{
if (resource.charAt(resource.length() - 1) == '/')
{
resource = resource.substring(0, resource.length() - 1);
}
return SimpleFilter.compareSubstring(pattern, resource);
}
@Override
public BundleImpl getBundle()
{
return m_revision.getBundle();
}
public Enumeration getResourcesByDelegation(String name)
{
Set requestSet = (Set) m_cycleCheck.get();
if (requestSet == null)
{
requestSet = new HashSet();
m_cycleCheck.set(requestSet);
}
if (!requestSet.contains(name))
{
requestSet.add(name);
try
{
return findResourcesByDelegation(name);
}
finally
{
requestSet.remove(name);
}
}
return null;
}
private Enumeration findResourcesByDelegation(String name)
{
Enumeration urls = null;
List completeUrlList = new ArrayList();
// Get the package of the target class/resource.
String pkgName = Util.getResourcePackage(name);
// Delegate any packages listed in the boot delegation
// property to the parent class loader.
if (shouldBootDelegate(pkgName))
{
try
{
// Get the appropriate class loader for delegation.
ClassLoader bdcl = getBootDelegationClassLoader();
urls = bdcl.getResources(name);
}
catch (IOException ex)
{
// This shouldn't happen and even if it does, there
// is nothing we can do, so just ignore it.
}
// If this is a java.* package, then always terminate the
// search; otherwise, continue to look locally.
if (pkgName.startsWith("java."))
{
return urls;
}
completeUrlList.add(urls);
}
// Look in the revisions's imported packages. If the package is
// imported, then we stop searching no matter the result since
// imported packages cannot be split.
BundleRevision provider = m_importedPkgs.get(pkgName);
if (provider != null)
{
// Delegate to the provider revision.
urls = ((BundleWiringImpl) provider.getWiring()).getResourcesByDelegation(name);
// If we find any resources, then add them.
if ((urls != null) && (urls.hasMoreElements()))
{
completeUrlList.add(urls);
}
// Always return here since imported packages cannot be split
// across required bundles or the revision's content.
return new CompoundEnumeration((Enumeration[])
completeUrlList.toArray(new Enumeration[completeUrlList.size()]));
}
// See whether we can get the resource from the required bundles and
// regardless of whether or not this is the case continue to the next
// step potentially passing on the result of this search (if any).
List<BundleRevision> providers = m_requiredPkgs.get(pkgName);
if (providers != null)
{
for (BundleRevision p : providers)
{
// Delegate to the provider revision.
urls = ((BundleWiringImpl) p.getWiring()).getResourcesByDelegation(name);
// If we find any resources, then add them.
if ((urls != null) && (urls.hasMoreElements()))
{
completeUrlList.add(urls);
}
// Do not return here, since required packages can be split
// across the revision's content.
}
}
// Try the module's own class path. If we can find the resource then
// return it together with the results from the other searches else
// try to look into the dynamic imports.
urls = m_revision.getResourcesLocal(name);
if ((urls != null) && (urls.hasMoreElements()))
{
completeUrlList.add(urls);
}
else
{
// If not found, then try the module's dynamic imports.
// At this point, the module's imports were searched and so was the
// the module's content. Now we make an attempt to load the
// class/resource via a dynamic import, if possible.
try
{
provider = m_resolver.resolve(m_revision, pkgName);
}
catch (ResolutionException ex)
{
// Ignore this since it is likely normal.
}
catch (BundleException ex)
{
// Ignore this since it is likely the result of a resolver hook.
}
if (provider != null)
{
// Delegate to the provider revision.
urls = ((BundleWiringImpl) provider.getWiring()).getResourcesByDelegation(name);
// If we find any resources, then add them.
if ((urls != null) && (urls.hasMoreElements()))
{
completeUrlList.add(urls);
}
}
}
return new CompoundEnumeration((Enumeration[])
completeUrlList.toArray(new Enumeration[completeUrlList.size()]));
}
private ClassLoader determineParentClassLoader()
{
// Determine the class loader's parent based on the
// configuration property; use boot class loader by
// default.
String cfg = (String) m_configMap.get(Constants.FRAMEWORK_BUNDLE_PARENT);
cfg = (cfg == null) ? Constants.FRAMEWORK_BUNDLE_PARENT_BOOT : cfg;
final ClassLoader parent;
if (cfg.equalsIgnoreCase(Constants.FRAMEWORK_BUNDLE_PARENT_APP))
{
parent = BundleRevisionImpl.getSecureAction().getSystemClassLoader();
}
else if (cfg.equalsIgnoreCase(Constants.FRAMEWORK_BUNDLE_PARENT_EXT))
{
parent = BundleRevisionImpl.getSecureAction().getParentClassLoader(
BundleRevisionImpl.getSecureAction().getSystemClassLoader());
}
else if (cfg.equalsIgnoreCase(Constants.FRAMEWORK_BUNDLE_PARENT_FRAMEWORK))
{
parent = BundleRevisionImpl.getSecureAction()
.getClassLoader(BundleRevisionImpl.class);
}
// On Android we cannot set the parent class loader to be null, so
// we special case that situation here and set it to the system
// class loader by default instead, which is not really spec.
else if (m_bootClassLoader == null)
{
parent = BundleRevisionImpl.getSecureAction().getSystemClassLoader();
}
else
{
parent = null;
}
return parent;
}
boolean shouldBootDelegate(String pkgName)
{
// Always boot delegate if the bundle has a configured
// boot class loader.
if (m_bootClassLoader != m_defBootClassLoader)
{
return true;
}
boolean result = false;
// Only consider delegation if we have a package name, since
// we don't want to promote the default package. The spec does
// not take a stand on this issue.
if (pkgName.length() > 0)
{
for (int i = 0;
!result
&& (i < getBundle()
.getFramework().getBootPackages().length);
i++)
{
// Check if the boot package is wildcarded.
// A wildcarded boot package will be in the form "foo.",
// so a matching subpackage will start with "foo.", e.g.,
// "foo.bar".
if (getBundle().getFramework().getBootPackageWildcards()[i]
&& pkgName.startsWith(
getBundle().getFramework().getBootPackages()[i]))
{
return true;
}
// If not wildcarded, then check for an exact match.
else if (getBundle()
.getFramework().getBootPackages()[i].equals(pkgName))
{
return true;
}
}
}
return result;
}
ClassLoader getBootDelegationClassLoader()
{
ClassLoader loader = m_classLoader;
// Get the appropriate class loader for delegation.
ClassLoader parent = (loader == null) ?
determineParentClassLoader() :
BundleRevisionImpl.getSecureAction().getParentClassLoader(loader);
return (parent == null) ? m_bootClassLoader : parent;
}
public Class getClassByDelegation(String name) throws ClassNotFoundException
{
// We do not call getClassLoader().loadClass() for arrays because
// it does not correctly handle array types, which is necessary in
// cases like deserialization using a wrapper class loader.
if ((name != null) && (name.length() > 0) && (name.charAt(0) == '['))
{
return Class.forName(name, false, getClassLoader());
}
// Check to see if the requested class is filtered.
if (isFiltered(name))
{
throw new ClassNotFoundException(name);
}
ClassLoader cl = getClassLoaderInternal();
if (cl == null)
{
throw new ClassNotFoundException(
"Unable to load class '"
+ name
+ "' because the bundle wiring for "
+ m_revision.getSymbolicName()
+ " is no longer valid.");
}
return cl.loadClass(name);
}
private boolean isFiltered(String name)
{
String pkgName = Util.getClassPackage(name);
List<List<String>> includeFilters = m_includedPkgFilters.get(pkgName);
List<List<String>> excludeFilters = m_excludedPkgFilters.get(pkgName);
if ((includeFilters == null) && (excludeFilters == null))
{
return false;
}
// Get the class name portion of the target class.
String className = Util.getClassName(name);
// If there are no include filters then all classes are included
// by default, otherwise try to find one match.
boolean included = (includeFilters == null);
for (int i = 0;
(!included) && (includeFilters != null) && (i < includeFilters.size());
i++)
{
included = SimpleFilter.compareSubstring(includeFilters.get(i), className);
}
// If there are no exclude filters then no classes are excluded
// by default, otherwise try to find one match.
boolean excluded = false;
for (int i = 0;
(!excluded) && (excludeFilters != null) && (i < excludeFilters.size());
i++)
{
excluded = SimpleFilter.compareSubstring(excludeFilters.get(i), className);
}
return !included || excluded;
}
public URL getResourceByDelegation(String name)
{
try
{
return (URL) findClassOrResourceByDelegation(name, false);
}
catch (ClassNotFoundException ex)
{
// This should never be thrown because we are loading resources.
}
catch (ResourceNotFoundException ex)
{
m_logger.log(m_revision.getBundle(),
Logger.LOG_DEBUG,
ex.getMessage());
}
return null;
}
private Object findClassOrResourceByDelegation(String name, boolean isClass)
throws ClassNotFoundException, ResourceNotFoundException
{
Object result = null;
Set requestSet = (Set) m_cycleCheck.get();
if (requestSet == null)
{
requestSet = new HashSet();
m_cycleCheck.set(requestSet);
}
if (requestSet.add(name))
{
try
{
// Get the package of the target class/resource.
String pkgName = (isClass) ? Util.getClassPackage(name) : Util.getResourcePackage(name);
boolean accessor = name.startsWith("sun.reflect.Generated") || name.startsWith("jdk.internal.reflect.");
if (accessor)
{
if (m_accessorLookupCache == null)
{
m_accessorLookupCache = new ConcurrentHashMap<String, ClassLoader>();
}
ClassLoader loader = m_accessorLookupCache.get(name);
if (loader != null)
{
return loader.loadClass(name);
}
}
// Delegate any packages listed in the boot delegation
// property to the parent class loader.
if (shouldBootDelegate(pkgName))
{
try
{
// Get the appropriate class loader for delegation.
ClassLoader bdcl = getBootDelegationClassLoader();
result = (isClass) ? (Object) bdcl.loadClass(name) : (Object) bdcl.getResource(name);
// If this is a java.* package, then always terminate the
// search; otherwise, continue to look locally if not found.
if (pkgName.startsWith("java.") || (result != null))
{
if (accessor)
{
m_accessorLookupCache.put(name, bdcl);
}
return result;
}
}
catch (ClassNotFoundException ex)
{
// If this is a java.* package, then always terminate the
// search; otherwise, continue to look locally if not found.
if (pkgName.startsWith("java."))
{
throw ex;
}
}
}
if (accessor)
{
List<Collection<BundleRevision>> allRevisions = new ArrayList<Collection<BundleRevision>>( 1 + m_requiredPkgs.size());
allRevisions.add(m_importedPkgs.values());
allRevisions.addAll(m_requiredPkgs.values());
for (Collection<BundleRevision> revisions : allRevisions)
{
for (BundleRevision revision : revisions)
{
ClassLoader loader = revision.getWiring().getClassLoader();
if (loader != null && loader instanceof BundleClassLoader)
{
BundleClassLoader bundleClassLoader = (BundleClassLoader) loader;
result = bundleClassLoader.findLoadedClassInternal(name);
if (result != null)
{
m_accessorLookupCache.put(name, bundleClassLoader);
return result;
}
}
}
}
try
{
// Get the appropriate class loader for delegation.
ClassLoader bdcl = getBootDelegationClassLoader();
result = (isClass) ? (Object) bdcl.loadClass(name) : (Object) bdcl.getResource(name);
if (result != null)
{
m_accessorLookupCache.put(name, bdcl);
return result;
}
}
catch (ClassNotFoundException ex)
{
}
m_accessorLookupCache.put(name, CNFE_CLASS_LOADER);
CNFE_CLASS_LOADER.loadClass(name);
}
// Look in the revision's imports. Note that the search may
// be aborted if this method throws an exception, otherwise
// it continues if a null is returned.
result = searchImports(pkgName, name, isClass);
// If not found, try the revision's own class path.
if (result == null)
{
ClassLoader cl = getClassLoaderInternal();
if (cl == null)
{
if (isClass)
{
throw new ClassNotFoundException(
"Unable to load class '"
+ name
+ "' because the bundle wiring for "
+ m_revision.getSymbolicName()
+ " is no longer valid.");
}
else
{
throw new ResourceNotFoundException("Unable to load resource '"
+ name
+ "' because the bundle wiring for "
+ m_revision.getSymbolicName()
+ " is no longer valid.");
}
}
if (cl instanceof BundleClassLoader)
{
result = isClass ? ((BundleClassLoader) cl).findClass(name) :
((BundleClassLoader) cl).findResource(name);
}
else
{
result = isClass ? cl.loadClass(name) : !name.startsWith("/") ? cl.getResource(name) :
cl.getResource(name.substring(1));
}
// If still not found, then try the revision's dynamic imports.
if (result == null)
{
result = searchDynamicImports(pkgName, name, isClass);
}
}
}
finally
{
requestSet.remove(name);
}
}
else
{
// If a cycle is detected, we should return null to break the
// cycle. This should only ever be return to internal class
// loading code and not to the actual instigator of the class load.
return null;
}
if (result == null)
{
if (isClass)
{
throw new ClassNotFoundException(
name + " not found by " + this.getBundle());
}
else
{
throw new ResourceNotFoundException(
name + " not found by " + this.getBundle());
}
}
return result;
}
private Object searchImports(String pkgName, String name, boolean isClass)
throws ClassNotFoundException, ResourceNotFoundException
{
// Check if the package is imported.
BundleRevision provider = m_importedPkgs.get(pkgName);
if (provider != null)
{
// If we find the class or resource, then return it.
Object result = (isClass)
? (Object) ((BundleWiringImpl) provider.getWiring()).getClassByDelegation(name)
: (Object) ((BundleWiringImpl) provider.getWiring()).getResourceByDelegation(name);
if (result != null)
{
return result;
}
// If no class or resource was found, then we must throw an exception
// since the provider of this package did not contain the
// requested class and imported packages are atomic.
if (isClass)
{
throw new ClassNotFoundException(name);
}
throw new ResourceNotFoundException(name);
}
// Check if the package is required.
List<BundleRevision> providers = m_requiredPkgs.get(pkgName);
if (providers != null)
{
for (BundleRevision p : providers)
{
// If we find the class or resource, then return it.
try
{
Object result = (isClass)
? (Object) ((BundleWiringImpl) p.getWiring()).getClassByDelegation(name)
: (Object) ((BundleWiringImpl) p.getWiring()).getResourceByDelegation(name);
if (result != null)
{
return result;
}
}
catch (ClassNotFoundException ex)
{
// Since required packages can be split, don't throw an
// exception here if it is not found. Instead, we'll just
// continue searching other required bundles and the
// revision's local content.
}
}
}
return null;
}
private Object searchDynamicImports(
final String pkgName, final String name, final boolean isClass)
throws ClassNotFoundException, ResourceNotFoundException
{
// At this point, the module's imports were searched and so was the
// the module's content. Now we make an attempt to load the
// class/resource via a dynamic import, if possible.
BundleRevision provider = null;
try
{
provider = m_resolver.resolve(m_revision, pkgName);
}
catch (ResolutionException ex)
{
// Ignore this since it is likely normal.
}
catch (BundleException ex)
{
// Ignore this since it is likely the result of a resolver hook.
}
// If the dynamic import was successful, then this initial
// time we must directly return the result from dynamically
// created package sources, but subsequent requests for
// classes/resources in the associated package will be
// processed as part of normal static imports.
if (provider != null)
{
// Return the class or resource.
return (isClass)
? (Object) ((BundleWiringImpl) provider.getWiring()).getClassByDelegation(name)
: (Object) ((BundleWiringImpl) provider.getWiring()).getResourceByDelegation(name);
}
return tryImplicitBootDelegation(name, isClass);
}
private Object tryImplicitBootDelegation(final String name, final boolean isClass)
throws ClassNotFoundException, ResourceNotFoundException
{
// If implicit boot delegation is enabled, then try to guess whether
// we should boot delegate.
if (m_implicitBootDelegation)
{
// At this point, the class/resource could not be found by the bundle's
// static or dynamic imports, nor its own content. Before we throw
// an exception, we will try to determine if the instigator of the
// class/resource load was a class from a bundle or not. This is necessary
// because the specification mandates that classes on the class path
// should be hidden (except for java.*), but it does allow for these
// classes/resources to be exposed by the system bundle as an export.
// However, in some situations classes on the class path make the faulty
// assumption that they can access everything on the class path from
// every other class loader that they come in contact with. This is
// not true if the class loader in question is from a bundle. Thus,
// this code tries to detect that situation. If the class instigating
// the load request was NOT from a bundle, then we will make the
// assumption that the caller actually wanted to use the parent class
// loader and we will delegate to it. If the class was
// from a bundle, then we will enforce strict class loading rules
// for the bundle and throw an exception.
// Get the class context to see the classes on the stack.
final Class[] classes = m_sm.getClassContext();
try
{
if (System.getSecurityManager() != null)
{
return AccessController
.doPrivileged(new PrivilegedExceptionAction()
{
@Override
public Object run() throws Exception
{
return doImplicitBootDelegation(classes, name,
isClass);
}
});
}
else
{
return doImplicitBootDelegation(classes, name, isClass);
}
}
catch (PrivilegedActionException ex)
{
Exception cause = ex.getException();
if (cause instanceof ClassNotFoundException)
{
throw (ClassNotFoundException) cause;
}
else
{
throw (ResourceNotFoundException) cause;
}
}
}
return null;
}
private Object doImplicitBootDelegation(Class[] classes, String name, boolean isClass)
throws ClassNotFoundException, ResourceNotFoundException
{
// Start from 1 to skip security manager class.
for (int i = 1; i < classes.length; i++)
{
// Find the first class on the call stack that is not from
// the class loader that loaded the Felix classes or is not
// a class loader or class itself, because we want to ignore
// calls to ClassLoader.loadClass() and Class.forName() since
// we are trying to find out who instigated the class load.
// Also ignore inner classes of class loaders, since we can
// assume they are a class loader too.
// TODO: FRAMEWORK - This check is a hack and we should see if we can think
// of another way to do it, since it won't necessarily work in all situations.
// Since Felix uses threads for changing the start level
// and refreshing packages, it is possible that there are no
// bundle classes on the call stack; therefore, as soon as we
// see Thread on the call stack we exit this loop. Other cases
// where bundles actually use threads are not an issue because
// the bundle classes will be on the call stack before the
// Thread class.
if (Thread.class.equals(classes[i]))
{
break;
}
// Break if the current class came from a bundle, since we should
// not implicitly boot delegate in that case.
else if (isClassLoadedFromBundleRevision(classes[i]))
{
break;
}
// Break if this goes through BundleImpl because it must be a call
// to Bundle.loadClass() which should not implicitly boot delegate.
else if (BundleImpl.class.equals(classes[i]))
{
break;
}
// Break if this goes through ServiceRegistrationImpl.ServiceReferenceImpl
// because it must be a assignability check which should not implicitly boot delegate
else if (ServiceRegistrationImpl.ServiceReferenceImpl.class.equals(classes[i]))
{
break;
}
else if (isClassExternal(classes[i]))
{
try
{
// Return the class or resource from the parent class loader.
return (isClass)
? (Object) BundleRevisionImpl.getSecureAction()
.getClassLoader(this.getClass()).loadClass(name)
: (Object) BundleRevisionImpl.getSecureAction()
.getClassLoader(this.getClass()).getResource(name);
}
catch (NoClassDefFoundError ex)
{
// Ignore, will return null
}
break;
}
}
return null;
}
private boolean isClassLoadedFromBundleRevision(Class clazz)
{
// The target class is loaded by a bundle class loader,
// then return true.
if (BundleClassLoader.class.isInstance(
BundleRevisionImpl.getSecureAction().getClassLoader(clazz)))
{
return true;
}
// If the target class was loaded from a class loader that
// came from a bundle, then return true.
ClassLoader last = null;
for (ClassLoader cl = BundleRevisionImpl.getSecureAction().getClassLoader(clazz);
(cl != null) && (last != cl);
cl = BundleRevisionImpl.getSecureAction().getClassLoader(cl.getClass()))
{
last = cl;
if (BundleClassLoader.class.isInstance(cl))
{
return true;
}
}
return false;
}
/**
* Tries to determine whether the given class is part of the framework or not.
* Framework classes include everything in org.apache.felix.framework.* and
* org.osgi.framework.*. We also consider ClassLoader and Class to be internal
* classes, because they are inserted into the stack trace as a result of
* method overloading. Typically, ClassLoader or Class will be mixed in
* between framework classes or will be at the point where the class loading
* request enters the framework class loading mechanism, which will then be
* followed by either bundle or external code, which will then exit our
* attempt to determine if we should boot delegate or not. Other standard
* class loaders, like URLClassLoader, are considered external classes and
* should trigger boot delegation. This means that bundles can create standard
* class loaders to get access to boot packages, but this is the standard
* behavior of class loaders.
* @param clazz the class to determine if it is external or not.
* @return <tt>true</tt> if the class is external, otherwise <tt>false</tt>.
*/
private boolean isClassExternal(Class clazz)
{
if (clazz.getName().startsWith("org.apache.felix.framework."))
{
return false;
}
else if (clazz.getName().startsWith("org.osgi.framework."))
{
return false;
}
else if (ClassLoader.class.equals(clazz))
{
return false;
}
else if (Class.class.equals(clazz))
{
return false;
}
return true;
}
static class ToLocalUrlEnumeration implements Enumeration
{
final Enumeration m_enumeration;
ToLocalUrlEnumeration(Enumeration enumeration)
{
m_enumeration = enumeration;
}
@Override
public boolean hasMoreElements()
{
return m_enumeration.hasMoreElements();
}
@Override
public Object nextElement()
{
return convertToLocalUrl((URL) m_enumeration.nextElement());
}
}
public static class BundleClassLoader extends SecureClassLoader implements BundleReference
{
static final boolean m_isParallel;
static
{
m_isParallel = registerAsParallel();
}
@IgnoreJRERequirement
private static boolean registerAsParallel()
{
boolean registered = false;
try
{
registered = ClassLoader.registerAsParallelCapable();
}
catch (Throwable th)
{
// This is OK on older java versions
}
return registered;
}
// Flag used to determine if a class has been loaded from this class
// loader or not.
private volatile boolean m_isActivationTriggered = false;
private Object[][] m_cachedLibs = new Object[0][];
private static final int LIBNAME_IDX = 0;
private static final int LIBPATH_IDX = 1;
private final ConcurrentHashMap<String, Thread> m_classLocks = new ConcurrentHashMap<String, Thread>();
private final BundleWiringImpl m_wiring;
private final Logger m_logger;
public BundleClassLoader(BundleWiringImpl wiring, ClassLoader parent, Logger logger)
{
super(parent);
m_wiring = wiring;
m_logger = logger;
}
public boolean isActivationTriggered()
{
return m_isActivationTriggered;
}
@Override
public BundleImpl getBundle()
{
return m_wiring.getBundle();
}
@Override
protected Class loadClass(String name, boolean resolve)
throws ClassNotFoundException
{
Class clazz = findLoadedClass(name);
if (clazz == null)
{
try
{
clazz = (Class) m_wiring.findClassOrResourceByDelegation(name, true);
}
catch (ResourceNotFoundException ex)
{
// This should never happen since we are asking for a class,
// so just ignore it.
}
catch (ClassNotFoundException cnfe)
{
ClassNotFoundException ex = cnfe;
if (m_logger.getLogLevel() >= Logger.LOG_DEBUG)
{
String msg = diagnoseClassLoadError(m_wiring.m_resolver, m_wiring.m_revision, name);
ex = (msg != null)
? new ClassNotFoundException(msg, cnfe)
: ex;
}
throw ex;
}
if (clazz == null)
{
// We detected a cycle
throw new ClassNotFoundException("Cycle detected while trying to load class: " + name);
}
}
// Resolve the class and return it.
if (resolve)
{
resolveClass(clazz);
}
return clazz;
}
@Override
protected Class findClass(String name) throws ClassNotFoundException
{
Class clazz = findLoadedClass(name);
// Search for class in bundle revision.
if (clazz == null)
{
// Do a quick check to try to avoid searching for classes on a
// disposed class loader, which will avoid some odd exception.
// This won't prevent all weird exception, since the wiring could
// still get disposed of after this check, but it will prevent
// some, perhaps.
if (m_wiring.m_isDisposed)
{
throw new ClassNotFoundException(
"Unable to load class '"
+ name
+ "' because the bundle wiring for "
+ m_wiring.m_revision.getSymbolicName()
+ " is no longer valid.");
}
String actual = name.replace('.', '/') + ".class";
byte[] bytes = null;
// Check the bundle class path.
List<Content> contentPath = m_wiring.m_revision.getContentPath();
Content content = null;
for (int i = 0;
(bytes == null) &&
(i < contentPath.size()); i++)
{
bytes = contentPath.get(i).getEntryAsBytes(actual);
content = contentPath.get(i);
}
if (bytes != null)
{
// Get package name.
String pkgName = Util.getClassPackage(name);
// Get weaving hooks and invoke them to give them a
// chance to weave the class' byte code before we
// define it.
// NOTE: We don't try to dynamically track hook addition
// or removal, we just get a snapshot and leave any changes
// as a race condition, doing any necessary clean up in
// the error handling.
Felix felix = m_wiring.m_revision.getBundle().getFramework();
Set<ServiceReference<WeavingHook>> hooks =
felix.getHookRegistry().getHooks(WeavingHook.class);
Set<ServiceReference<WovenClassListener>> wovenClassListeners =
felix.getHookRegistry().getHooks(WovenClassListener.class);
WovenClassImpl wci = null;
if (!hooks.isEmpty())
{
// Create woven class to be used for hooks.
wci = new WovenClassImpl(name, m_wiring, bytes);
try
{
transformClass(felix, wci, hooks, wovenClassListeners,
name, bytes);
}
catch (Error e)
{
// Mark the woven class as incomplete.
wci.complete();
wci.setState(WovenClass.TRANSFORMING_FAILED);
callWovenClassListeners(felix, wovenClassListeners, wci);
throw e;
}
}
try
{
clazz = isParallel() ? defineClassParallel(name, felix, wovenClassListeners, wci, bytes, content, pkgName) :
defineClassNotParallel(name, felix, wovenClassListeners, wci, bytes, content, pkgName);
}
catch (ClassFormatError e)
{
if (wci != null)
{
wci.setState(WovenClass.DEFINE_FAILED);
callWovenClassListeners(felix, wovenClassListeners, wci);
}
throw e;
}
// Perform deferred activation without holding the class loader lock,
// if the class we are returning is the instigating class.
List deferredList = (List) m_deferredActivation.get();
if ((deferredList != null)
&& (deferredList.size() > 0)
&& ((Object[]) deferredList.get(0))[0].equals(name))
{
// Null the deferred list.
m_deferredActivation.set(null);
while (!deferredList.isEmpty())
{
// Lazy bundles should be activated in the reverse order
// of when they were added to the deferred list, so grab
// them from the end of the deferred list.
Object[] lazy = (Object[]) deferredList.remove(deferredList.size() - 1);
try
{
felix.getFramework().activateBundle((BundleImpl) (lazy)[1], true);
}
catch (Throwable ex)
{
m_logger.log((BundleImpl) (lazy)[1],
Logger.LOG_WARNING,
"Unable to lazily start bundle.",
ex);
}
}
}
}
}
return clazz;
}
Class defineClassParallel(String name, Felix felix, Set<ServiceReference<WovenClassListener>> wovenClassListeners, WovenClassImpl wci, byte[] bytes,
Content content, String pkgName) throws ClassFormatError
{
Class clazz = null;
Thread me = Thread.currentThread();
while (clazz == null && m_classLocks.putIfAbsent(name, me) != me)
{
clazz = findLoadedClass(name);
}
if (clazz == null)
{
try
{
clazz = findLoadedClass(name);
if (clazz == null)
{
clazz = defineClass(felix, wovenClassListeners, wci, name,
bytes, content, pkgName);
}
}
finally
{
m_classLocks.remove(name);
}
}
return clazz;
}
Class defineClassNotParallel(String name, Felix felix, Set<ServiceReference<WovenClassListener>> wovenClassListeners, WovenClassImpl wci, byte[] bytes,
Content content, String pkgName) throws ClassFormatError
{
Class clazz = findLoadedClass(name);
if (clazz == null)
{
synchronized (m_classLocks)
{
clazz = findLoadedClass(name);
if (clazz == null)
{
clazz = defineClass(felix, wovenClassListeners, wci, name,
bytes, content, pkgName);
}
}
}
return clazz;
}
Class defineClass(Felix felix,
Set<ServiceReference<WovenClassListener>> wovenClassListeners,
WovenClassImpl wci, String name, byte[] bytes, Content content, String pkgName)
throws ClassFormatError
{
// If we have a woven class then get the class bytes from
// it since they may have changed.
// NOTE: We are taking a snapshot of these values and
// are not preventing a malbehaving weaving hook from
// modifying them after the fact. The price of preventing
// this isn't worth it, since they can already wreck
// havoc via weaving anyway. However, we do pass the
// snapshot values into the woven class when we mark it
// as complete so that it will refect the actual values
// we used to define the class.
if (wci != null)
{
bytes = wci._getBytes();
List<String> wovenImports = wci.getDynamicImportsInternal();
// Try to add any woven dynamic imports, since they
// could potentially be needed when defining the class.
List<BundleRequirement> allWovenReqs =
new ArrayList<BundleRequirement>();
for (String s : wovenImports)
{
try
{
List<BundleRequirement> wovenReqs =
ManifestParser.parseDynamicImportHeader(
m_logger, m_wiring.m_revision, s);
allWovenReqs.addAll(wovenReqs);
}
catch (BundleException ex)
{
// There should be no exception here
// since we checked syntax before adding
// dynamic import strings to list.
}
}
// Add the dynamic requirements.
if (!allWovenReqs.isEmpty())
{
// Check for duplicate woven imports.
// First grab existing woven imports, if any.
Set<String> filters = new HashSet<String>();
if (m_wiring.m_wovenReqs != null)
{
for (BundleRequirement req : m_wiring.m_wovenReqs)
{
filters.add(
((BundleRequirementImpl) req)
.getFilter().toString());
}
}
// Then check new woven imports for duplicates
// against existing and self.
int idx = allWovenReqs.size();
while (idx < allWovenReqs.size())
{
BundleRequirement wovenReq = allWovenReqs.get(idx);
String filter = ((BundleRequirementImpl)
wovenReq).getFilter().toString();
if (!filters.contains(filter))
{
filters.add(filter);
idx++;
}
else
{
allWovenReqs.remove(idx);
}
}
// Merge existing with new imports, if any.
if (!allWovenReqs.isEmpty())
{
if (m_wiring.m_wovenReqs != null)
{
allWovenReqs.addAll(0, m_wiring.m_wovenReqs);
}
m_wiring.m_wovenReqs = allWovenReqs;
}
}
}
int activationPolicy =
getBundle().isDeclaredActivationPolicyUsed()
? getBundle()
.adapt(BundleRevisionImpl.class).getDeclaredActivationPolicy()
: EAGER_ACTIVATION;
// If the revision is using deferred activation, then if
// we load this class from this revision we need to activate
// the bundle before returning the class. We will short
// circuit the trigger matching if the trigger is already
// tripped.
boolean isTriggerClass = m_isActivationTriggered
? false : m_wiring.m_revision.isActivationTrigger(pkgName);
if (!m_isActivationTriggered
&& isTriggerClass
&& (activationPolicy == BundleRevisionImpl.LAZY_ACTIVATION)
&& (getBundle().getState() == Bundle.STARTING))
{
List deferredList = (List) m_deferredActivation.get();
if (deferredList == null)
{
deferredList = new ArrayList();
m_deferredActivation.set(deferredList);
}
deferredList.add(new Object[]{name, getBundle()});
}
// We need to try to define a Package object for the class
// before we call defineClass() if we haven't already
// created it.
if (pkgName.length() > 0)
{
if (getPackage(pkgName) == null)
{
Object[] params = definePackage(pkgName);
// This is a harmless check-then-act situation,
// where threads might be racing to create different
// classes in the same package, so catch and ignore
// any IAEs that may occur.
try
{
definePackage(
pkgName,
(String) params[0],
(String) params[1],
(String) params[2],
(String) params[3],
(String) params[4],
(String) params[5],
null);
}
catch (IllegalArgumentException ex)
{
// Ignore.
}
}
}
Class clazz = null;
// If we have a security context, then use it to
// define the class with it for security purposes,
// otherwise define the class without a protection domain.
if (m_wiring.m_revision.getProtectionDomain() != null)
{
clazz = defineClass(name, bytes, 0, bytes.length,
m_wiring.m_revision.getProtectionDomain());
}
else
{
clazz = defineClass(name, bytes, 0, bytes.length);
}
if (wci != null)
{
wci.completeDefine(clazz);
wci.setState(WovenClass.DEFINED);
callWovenClassListeners(felix, wovenClassListeners, wci);
}
// At this point if we have a trigger class, then the deferred
// activation trigger has tripped.
if (!m_isActivationTriggered && isTriggerClass && (clazz != null))
{
m_isActivationTriggered = true;
}
return clazz;
}
void transformClass(Felix felix, WovenClassImpl wci,
Set<ServiceReference<WeavingHook>> hooks,
Set<ServiceReference<WovenClassListener>> wovenClassListeners,
String name, byte[] bytes) throws Error {
// Loop through hooks in service ranking order.
for (ServiceReference<WeavingHook> sr : hooks)
{
// Only use the hook if it is not black listed.
if (!felix.getHookRegistry().isHookBlackListed(sr))
{
// Get the hook service object.
// Note that we don't use the bundle context
// to get the service object since that would
// perform sercurity checks.
WeavingHook wh = felix.getService(felix, sr, false);
if (wh != null)
{
try
{
BundleRevisionImpl.getSecureAction()
.invokeWeavingHook(wh, wci);
}
catch (Throwable th)
{
if (!(th instanceof WeavingException))
{
felix.getHookRegistry().blackListHook(sr);
}
felix.fireFrameworkEvent(
FrameworkEvent.ERROR,
sr.getBundle(),
th);
// Throw class format exception per spec.
Error error = new ClassFormatError("Weaving hook failed.");
error.initCause(th);
throw error;
}
finally
{
felix.ungetService(felix, sr, null);
}
}
}
}
wci.setState(WovenClass.TRANSFORMED);
callWovenClassListeners(felix, wovenClassListeners, wci);
}
protected void callWovenClassListeners(Felix felix, Set<ServiceReference<WovenClassListener>> wovenClassListeners, WovenClass wovenClass)
{
if(wovenClassListeners != null)
{
for(ServiceReference<WovenClassListener> currentWovenClassListenerRef : wovenClassListeners)
{
WovenClassListener currentWovenClassListner = felix.getService(felix, currentWovenClassListenerRef, false);
try
{
BundleRevisionImpl.getSecureAction().invokeWovenClassListener(currentWovenClassListner, wovenClass);
}
catch (Exception e)
{
m_logger.log(Logger.LOG_ERROR, "Woven Class Listner failed.", e);
}
finally
{
felix.ungetService(felix, currentWovenClassListenerRef, null);
}
}
}
}
private Object[] definePackage(String pkgName)
{
String spectitle = (String) m_wiring.m_revision.getHeaders().get("Specification-Title");
String specversion = (String) m_wiring.m_revision.getHeaders().get("Specification-Version");
String specvendor = (String) m_wiring.m_revision.getHeaders().get("Specification-Vendor");
String impltitle = (String) m_wiring.m_revision.getHeaders().get("Implementation-Title");
String implversion = (String) m_wiring.m_revision.getHeaders().get("Implementation-Version");
String implvendor = (String) m_wiring.m_revision.getHeaders().get("Implementation-Vendor");
if ((spectitle != null)
|| (specversion != null)
|| (specvendor != null)
|| (impltitle != null)
|| (implversion != null)
|| (implvendor != null))
{
return new Object[] {
spectitle, specversion, specvendor, impltitle, implversion, implvendor
};
}
return new Object[] {null, null, null, null, null, null};
}
@Override
public URL getResource(String name)
{
URL url = m_wiring.getResourceByDelegation(name);
if (m_wiring.m_useLocalURLs)
{
url = convertToLocalUrl(url);
}
return url;
}
@Override
protected URL findResource(String name)
{
return m_wiring.m_revision.getResourceLocal(name);
}
@Override
protected Enumeration findResources(String name)
{
return m_wiring.m_revision.getResourcesLocal(name);
}
@Override
protected String findLibrary(String name)
{
// Remove leading slash, if present.
if (name.startsWith("/"))
{
name = name.substring(1);
}
String result = null;
// CONCURRENCY: In the long run, we might want to break this
// sync block in two to avoid manipulating the cache while
// holding the lock, but for now we will do it the simple way.
synchronized (this)
{
// Check to make sure we haven't already found this library.
for (int i = 0; (result == null) && (i < m_cachedLibs.length); i++)
{
if (m_cachedLibs[i][LIBNAME_IDX].equals(name))
{
result = (String) m_cachedLibs[i][LIBPATH_IDX];
}
}
// If we don't have a cached result, see if we have a matching
// native library.
if (result == null)
{
List<NativeLibrary> libs = m_wiring.getNativeLibraries();
for (int libIdx = 0; (libs != null) && (libIdx < libs.size()); libIdx++)
{
if (libs.get(libIdx).match(m_wiring.m_configMap, name))
{
// Search bundle content first for native library.
result = m_wiring.m_revision.getContent().getEntryAsNativeLibrary(
libs.get(libIdx).getEntryName());
// If not found, then search fragments in order.
for (int i = 0;
(result == null) && (m_wiring.m_fragmentContents != null)
&& (i < m_wiring.m_fragmentContents.size());
i++)
{
result = m_wiring.m_fragmentContents.get(i).getEntryAsNativeLibrary(
libs.get(libIdx).getEntryName());
}
}
}
// Remember the result for future requests.
if (result != null)
{
Object[][] tmp = new Object[m_cachedLibs.length + 1][];
System.arraycopy(m_cachedLibs, 0, tmp, 0, m_cachedLibs.length);
tmp[m_cachedLibs.length] = new Object[] { name, result };
m_cachedLibs = tmp;
}
}
}
return result;
}
protected boolean isParallel()
{
return m_isParallel;
}
@Override
public Enumeration getResources(String name)
{
Enumeration urls = m_wiring.getResourcesByDelegation(name);
if (m_wiring.m_useLocalURLs)
{
urls = new ToLocalUrlEnumeration(urls);
}
return urls;
}
@Override
public String toString()
{
return m_wiring.toString();
}
Class<?> findLoadedClassInternal(String name)
{
return super.findLoadedClass(name);
}
}
static URL convertToLocalUrl(URL url)
{
if (url.getProtocol().equals("bundle"))
{
try
{
url = ((URLHandlersBundleURLConnection)
url.openConnection()).getLocalURL();
}
catch (IOException ex)
{
// Ignore and add original url.
}
}
return url;
}
private static class ResourceSource implements Comparable<ResourceSource>
{
public final String m_resource;
public final BundleRevision m_revision;
public ResourceSource(String resource, BundleRevision revision)
{
m_resource = resource;
m_revision = revision;
}
@Override
public boolean equals(Object o)
{
if (o instanceof ResourceSource)
{
return m_resource.equals(((ResourceSource) o).m_resource);
}
return false;
}
@Override
public int hashCode()
{
return m_resource.hashCode();
}
@Override
public int compareTo(ResourceSource t)
{
return m_resource.compareTo(t.m_resource);
}
@Override
public String toString()
{
return m_resource
+ " -> "
+ m_revision.getSymbolicName()
+ " [" + m_revision + "]";
}
}
private static String diagnoseClassLoadError(
StatefulResolver resolver, BundleRevision revision, String name)
{
// We will try to do some diagnostics here to help the developer
// deal with this exception.
// Get package name.
String pkgName = Util.getClassPackage(name);
if (pkgName.length() == 0)
{
return null;
}
// First, get the bundle string of the revision doing the class loader.
String importer = revision.getBundle().toString();
// Next, check to see if the revision imports the package.
List<BundleWire> wires = (revision.getWiring() == null)
? null : revision.getWiring().getProvidedWires(null);
for (int i = 0; (wires != null) && (i < wires.size()); i++)
{
if (wires.get(i).getCapability().getNamespace().equals(BundleRevision.PACKAGE_NAMESPACE) &&
wires.get(i).getCapability().getAttributes().get(BundleRevision.PACKAGE_NAMESPACE).equals(pkgName))
{
String exporter = wires.get(i).getProviderWiring().getBundle().toString();
StringBuilder sb = new StringBuilder("*** Package '");
sb.append(pkgName);
sb.append("' is imported by bundle ");
sb.append(importer);
sb.append(" from bundle ");
sb.append(exporter);
sb.append(", but the exported package from bundle ");
sb.append(exporter);
sb.append(" does not contain the requested class '");
sb.append(name);
sb.append("'. Please verify that the class name is correct in the importing bundle ");
sb.append(importer);
sb.append(" and/or that the exported package is correctly bundled in ");
sb.append(exporter);
sb.append(". ***");
return sb.toString();
}
}
// Next, check to see if the package was optionally imported and
// whether or not there is an exporter available.
List<BundleRequirement> reqs = revision.getWiring().getRequirements(null);
/*
* TODO: RB - Fix diagnostic message for optional imports.
for (int i = 0; (reqs != null) && (i < reqs.length); i++)
{
if (reqs[i].getName().equals(pkgName) && reqs[i].isOptional())
{
// Try to see if there is an exporter available.
IModule[] exporters = getResolvedExporters(reqs[i], true);
exporters = (exporters.length == 0)
? getUnresolvedExporters(reqs[i], true) : exporters;
// An exporter might be available, but it may have attributes
// that do not match the importer's required attributes, so
// check that case by simply looking for an exporter of the
// desired package without any attributes.
if (exporters.length == 0)
{
IRequirement pkgReq = new Requirement(
ICapability.PACKAGE_NAMESPACE, "(package=" + pkgName + ")");
exporters = getResolvedExporters(pkgReq, true);
exporters = (exporters.length == 0)
? getUnresolvedExporters(pkgReq, true) : exporters;
}
long expId = (exporters.length == 0)
? -1 : Util.getBundleIdFromModuleId(exporters[0].getId());
StringBuilder sb = new StringBuilder("*** Class '");
sb.append(name);
sb.append("' was not found, but this is likely normal since package '");
sb.append(pkgName);
sb.append("' is optionally imported by bundle ");
sb.append(impId);
sb.append(".");
if (exporters.length > 0)
{
sb.append(" However, bundle ");
sb.append(expId);
if (reqs[i].isSatisfied(
Util.getExportPackage(exporters[0], reqs[i].getName())))
{
sb.append(" does export this package. Bundle ");
sb.append(expId);
sb.append(" must be installed before bundle ");
sb.append(impId);
sb.append(" is resolved or else the optional import will be ignored.");
}
else
{
sb.append(" does export this package with attributes that do not match.");
}
}
sb.append(" ***");
return sb.toString();
}
}
*/
// Next, check to see if the package is dynamically imported by the revision.
if (resolver.isAllowedDynamicImport(revision, pkgName))
{
// Try to see if there is an exporter available.
Map<String, String> dirs = Collections.EMPTY_MAP;
Map<String, Object> attrs = Collections.singletonMap(
BundleRevision.PACKAGE_NAMESPACE, (Object) pkgName);
BundleRequirementImpl req = new BundleRequirementImpl(
revision, BundleRevision.PACKAGE_NAMESPACE, dirs, attrs);
List<BundleCapability> exporters = resolver.findProviders(req, false);
BundleRevision provider = null;
try
{
provider = resolver.resolve(revision, pkgName);
}
catch (Exception ex)
{
provider = null;
}
String exporter = (exporters.isEmpty())
? null : exporters.iterator().next().toString();
StringBuilder sb = new StringBuilder("*** Class '");
sb.append(name);
sb.append("' was not found, but this is likely normal since package '");
sb.append(pkgName);
sb.append("' is dynamically imported by bundle ");
sb.append(importer);
sb.append(".");
if ((exporters.size() > 0) && (provider == null))
{
sb.append(" However, bundle ");
sb.append(exporter);
sb.append(" does export this package with attributes that do not match.");
}
sb.append(" ***");
return sb.toString();
}
// Next, check to see if there are any exporters for the package at all.
Map<String, String> dirs = Collections.EMPTY_MAP;
Map<String, Object> attrs = Collections.singletonMap(
BundleRevision.PACKAGE_NAMESPACE, (Object) pkgName);
BundleRequirementImpl req = new BundleRequirementImpl(
revision, BundleRevision.PACKAGE_NAMESPACE, dirs, attrs);
List<BundleCapability> exports = resolver.findProviders(req, false);
if (exports.size() > 0)
{
boolean classpath = false;
try
{
BundleRevisionImpl.getSecureAction()
.getClassLoader(BundleClassLoader.class).loadClass(name);
classpath = true;
}
catch (NoClassDefFoundError err)
{
// Ignore
}
catch (Exception ex)
{
// Ignore
}
String exporter = exports.iterator().next().toString();
StringBuilder sb = new StringBuilder("*** Class '");
sb.append(name);
sb.append("' was not found because bundle ");
sb.append(importer);
sb.append(" does not import '");
sb.append(pkgName);
sb.append("' even though bundle ");
sb.append(exporter);
sb.append(" does export it.");
if (classpath)
{
sb.append(" Additionally, the class is also available from the system class loader. There are two fixes: 1) Add an import for '");
sb.append(pkgName);
sb.append("' to bundle ");
sb.append(importer);
sb.append("; imports are necessary for each class directly touched by bundle code or indirectly touched, such as super classes if their methods are used. ");
sb.append("2) Add package '");
sb.append(pkgName);
sb.append("' to the '");
sb.append(Constants.FRAMEWORK_BOOTDELEGATION);
sb.append("' property; a library or VM bug can cause classes to be loaded by the wrong class loader. The first approach is preferable for preserving modularity.");
}
else
{
sb.append(" To resolve this issue, add an import for '");
sb.append(pkgName);
sb.append("' to bundle ");
sb.append(importer);
sb.append(".");
}
sb.append(" ***");
return sb.toString();
}
// Next, try to see if the class is available from the system
// class loader.
try
{
BundleRevisionImpl.getSecureAction()
.getClassLoader(BundleClassLoader.class).loadClass(name);
StringBuilder sb = new StringBuilder("*** Package '");
sb.append(pkgName);
sb.append("' is not imported by bundle ");
sb.append(importer);
sb.append(", nor is there any bundle that exports package '");
sb.append(pkgName);
sb.append("'. However, the class '");
sb.append(name);
sb.append("' is available from the system class loader. There are two fixes: 1) Add package '");
sb.append(pkgName);
sb.append("' to the '");
sb.append(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA);
sb.append("' property and modify bundle ");
sb.append(importer);
sb.append(" to import this package; this causes the system bundle to export class path packages. 2) Add package '");
sb.append(pkgName);
sb.append("' to the '");
sb.append(Constants.FRAMEWORK_BOOTDELEGATION);
sb.append("' property; a library or VM bug can cause classes to be loaded by the wrong class loader. The first approach is preferable for preserving modularity.");
sb.append(" ***");
return sb.toString();
}
catch (Exception ex2)
{
}
// Finally, if there are no imports or exports for the package
// and it is not available on the system class path, simply
// log a message saying so.
StringBuilder sb = new StringBuilder("*** Class '");
sb.append(name);
sb.append("' was not found. Bundle ");
sb.append(importer);
sb.append(" does not import package '");
sb.append(pkgName);
sb.append("', nor is the package exported by any other bundle or available from the system class loader.");
sb.append(" ***");
return sb.toString();
}
}
|
FELIX-6522 Empty name is not allowed in permissions. (#143)
- presumption: such capability can be removed as impliesDirect would return
false too.
|
framework/src/main/java/org/apache/felix/framework/BundleWiringImpl.java
|
FELIX-6522 Empty name is not allowed in permissions. (#143)
|
<ide><path>ramework/src/main/java/org/apache/felix/framework/BundleWiringImpl.java
<ide>
<ide> if (System.getSecurityManager() != null)
<ide> {
<del> for (Iterator<BundleCapability> iter = capList.iterator();iter.hasNext();)
<add> for (Iterator<BundleCapability> iter = capList.iterator(); iter.hasNext();)
<ide> {
<ide> BundleCapability cap = iter.next();
<del> if (cap.getNamespace().equals(BundleRevision.PACKAGE_NAMESPACE))
<add> String bundleNamespace = cap.getNamespace();
<add> if (bundleNamespace.isEmpty())
<add> {
<add> iter.remove();
<add> }
<add> else if (bundleNamespace.equals(BundleRevision.PACKAGE_NAMESPACE))
<ide> {
<ide> if (!((BundleProtectionDomain) ((BundleRevisionImpl) cap.getRevision()).getProtectionDomain()).impliesDirect(
<ide> new PackagePermission((String) cap.getAttributes().get(BundleRevision.PACKAGE_NAMESPACE), PackagePermission.EXPORTONLY)))
<ide> iter.remove();
<ide> }
<ide> }
<del> else if (!cap.getNamespace().equals(BundleRevision.HOST_NAMESPACE) && !cap.getNamespace().equals(BundleRevision.BUNDLE_NAMESPACE) &&
<del> !cap.getNamespace().equals("osgi.ee"))
<del> {
<del> if (!((BundleProtectionDomain) ((BundleRevisionImpl) cap.getRevision()).getProtectionDomain()).impliesDirect(
<del> new CapabilityPermission(cap.getNamespace(), CapabilityPermission.PROVIDE)))
<add> else if (!bundleNamespace.equals(BundleRevision.HOST_NAMESPACE)
<add> && !bundleNamespace.equals(BundleRevision.BUNDLE_NAMESPACE)
<add> && !bundleNamespace.equals("osgi.ee"))
<add> {
<add> CapabilityPermission permission = new CapabilityPermission(bundleNamespace, CapabilityPermission.PROVIDE);
<add> if (!((BundleProtectionDomain) ((BundleRevisionImpl) cap.getRevision()).getProtectionDomain()).impliesDirect(permission))
<ide> {
<ide> iter.remove();
<ide> }
|
|
Java
|
agpl-3.0
|
263bfe2ed958aa10e93f35e3258bf87631db0ae3
| 0 |
KinshipSoftware/KinOathKinshipArchiver,KinshipSoftware/KinOathKinshipArchiver,PeterWithers/temp-to-delete1,PeterWithers/temp-to-delete1
|
package nl.mpi.kinnate.svg;
import nl.mpi.kinnate.kindata.EntityData;
import nl.mpi.kinnate.ui.GraphPanelContextMenu;
import java.awt.BorderLayout;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.geom.AffineTransform;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import javax.swing.JPanel;
import javax.xml.parsers.DocumentBuilderFactory;
import nl.mpi.arbil.data.ArbilComponentBuilder;
import nl.mpi.arbil.ui.GuiHelper;
import nl.mpi.kinnate.entityindexer.IndexerParameters;
import nl.mpi.kinnate.SavePanel;
import nl.mpi.kinnate.kindata.GraphSorter;
import nl.mpi.kinnate.uniqueidentifiers.UniqueIdentifier;
import nl.mpi.kinnate.kintypestrings.KinTermGroup;
import nl.mpi.kinnate.ui.KinDiagramPanel;
import nl.mpi.kinnate.ui.MetadataPanel;
import org.apache.batik.dom.svg.SAXSVGDocumentFactory;
import org.apache.batik.dom.svg.SVGDOMImplementation;
import org.apache.batik.swing.JSVGCanvas;
import org.apache.batik.swing.JSVGScrollPane;
import org.apache.batik.util.XMLResourceDescriptor;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.events.EventTarget;
import org.w3c.dom.svg.SVGDocument;
/**
* Document : GraphPanel
* Created on : Aug 16, 2010, 5:31:33 PM
* Author : Peter Withers
*/
public class GraphPanel extends JPanel implements SavePanel {
private JSVGScrollPane jSVGScrollPane;
protected JSVGCanvas svgCanvas;
protected SVGDocument doc;
public MetadataPanel metadataPanel;
private boolean requiresSave = false;
private File svgFile = null;
protected GraphPanelSize graphPanelSize;
protected LineLookUpTable lineLookUpTable;
protected ArrayList<UniqueIdentifier> selectedGroupId;
protected String svgNameSpace = SVGDOMImplementation.SVG_NAMESPACE_URI;
public DataStoreSvg dataStoreSvg;
protected EntitySvg entitySvg;
// private URI[] egoPathsTemp = null;
public SvgUpdateHandler svgUpdateHandler;
public MouseListenerSvg mouseListenerSvg;
public GraphPanel(KinDiagramPanel kinDiagramPanel) {
dataStoreSvg = new DataStoreSvg();
entitySvg = new EntitySvg();
dataStoreSvg.setDefaults();
svgUpdateHandler = new SvgUpdateHandler(this, kinDiagramPanel);
selectedGroupId = new ArrayList<UniqueIdentifier>();
graphPanelSize = new GraphPanelSize();
this.setLayout(new BorderLayout());
boolean eventsEnabled = true;
boolean selectableText = false;
svgCanvas = new JSVGCanvas(new GraphUserAgent(this), eventsEnabled, selectableText);
// svgCanvas.setMySize(new Dimension(600, 400));
svgCanvas.setDocumentState(JSVGCanvas.ALWAYS_DYNAMIC);
// drawNodes();
svgCanvas.setEnableImageZoomInteractor(false);
svgCanvas.setEnablePanInteractor(false);
svgCanvas.setEnableRotateInteractor(false);
svgCanvas.setEnableZoomInteractor(false);
svgCanvas.addMouseWheelListener(new MouseWheelListener() {
public void mouseWheelMoved(MouseWheelEvent e) {
double scale = 1 - e.getUnitsToScroll() / 10.0;
double tx = -e.getX() * (scale - 1);
double ty = -e.getY() * (scale - 1);
// System.out.println("scale: " + scale);
// System.out.println("scale: " + svgCanvas.getRenderingTransform().getScaleX());
if (scale > 1 || svgCanvas.getRenderingTransform().getScaleX() > 0.01) {
AffineTransform at = new AffineTransform();
at.translate(tx, ty);
at.scale(scale, scale);
at.concatenate(svgCanvas.getRenderingTransform());
svgCanvas.setRenderingTransform(at);
}
}
});
// svgCanvas.setEnableResetTransformInteractor(true);
// svgCanvas.setDoubleBufferedRendering(true); // todo: look into reducing the noticable aliasing on the canvas
mouseListenerSvg = new MouseListenerSvg(kinDiagramPanel, this);
svgCanvas.addMouseListener(mouseListenerSvg);
svgCanvas.addMouseMotionListener(mouseListenerSvg);
jSVGScrollPane = new JSVGScrollPane(svgCanvas);
// svgCanvas.setBackground(Color.LIGHT_GRAY);
this.add(BorderLayout.CENTER, jSVGScrollPane);
svgCanvas.setComponentPopupMenu(new GraphPanelContextMenu(kinDiagramPanel, this, graphPanelSize));
}
// private void zoomDrawing() {
// AffineTransform scaleTransform = new AffineTransform();
// scaleTransform.scale(1 - currentZoom / 10.0, 1 - currentZoom / 10.0);
// System.out.println("currentZoom: " + currentZoom);
//// svgCanvas.setRenderingTransform(scaleTransform);
// Rectangle canvasBounds = this.getBounds();
// SVGRect bbox = ((SVGLocatable) doc.getRootElement()).getBBox();
// if (bbox != null) {
// System.out.println("previousZoomedWith: " + bbox.getWidth());
// }
//// SVGElement rootElement = doc.getRootElement();
//// if (currentWidth < canvasBounds.width) {
// float drawingCenter = (currentWidth / 2);
//// float drawingCenter = (bbox.getX() + (bbox.getWidth() / 2));
// float canvasCenter = (canvasBounds.width / 2);
// zoomAffineTransform = new AffineTransform();
// zoomAffineTransform.translate((canvasCenter - drawingCenter), 1);
// zoomAffineTransform.concatenate(scaleTransform);
// svgCanvas.setRenderingTransform(zoomAffineTransform);
// }
public void setArbilTableModel(MetadataPanel metadataPanel) {
this.metadataPanel = metadataPanel;
}
public void readSvg(URI svgFilePath, boolean savableType) {
if (savableType) {
svgFile = new File(svgFilePath);
} else {
svgFile = null;
}
String parser = XMLResourceDescriptor.getXMLParserClassName();
SAXSVGDocumentFactory documentFactory = new SAXSVGDocumentFactory(parser);
try {
doc = (SVGDocument) documentFactory.createDocument(svgFilePath.toString());
svgCanvas.setDocument(doc);
dataStoreSvg = DataStoreSvg.loadDataFromSvg(doc);
if (dataStoreSvg.indexParameters == null) {
dataStoreSvg.setDefaults();
}
requiresSave = false;
entitySvg.readEntityPositions(doc.getElementById("EntityGroup"));
entitySvg.readEntityPositions(doc.getElementById("LabelsGroup"));
entitySvg.readEntityPositions(doc.getElementById("GraphicsGroup"));
configureDiagramGroups();
dataStoreSvg.indexParameters.symbolFieldsFields.setAvailableValues(entitySvg.listSymbolNames(doc, this.svgNameSpace));
// if (dataStoreSvg.graphData == null) {
// return null;
// }
} catch (IOException ioe) {
GuiHelper.linorgBugCatcher.logError(ioe);
}
// svgCanvas.setSVGDocument(doc);
return; // dataStoreSvg.graphData.getDataNodes();
}
private void configureDiagramGroups() {
Element svgRoot = doc.getDocumentElement();
// make sure the diagram group exisits
Element diagramGroup = doc.getElementById("DiagramGroup");
if (diagramGroup == null) {
diagramGroup = doc.createElementNS(svgNameSpace, "g");
diagramGroup.setAttribute("id", "DiagramGroup");
// add the diagram group to the root element (the 'svg' element)
svgRoot.appendChild(diagramGroup);
}
Element previousElement = null;
// add the graphics group below the entities and relations
// add the relation symbols in a group below the relation lines
// add the entity symbols in a group on top of the relation lines
// add the labels group on top, also added on svg load if missing
for (String groupForMouseListener : new String[]{"LabelsGroup", "EntityGroup", "RelationGroup", "GraphicsGroup"}) {
// add any groups that are required and add them in the required order
Element parentElement = doc.getElementById(groupForMouseListener);
if (parentElement == null) {
parentElement = doc.createElementNS(svgNameSpace, "g");
parentElement.setAttribute("id", groupForMouseListener);
diagramGroup.insertBefore(parentElement, previousElement);
} else {
diagramGroup.insertBefore(parentElement, previousElement); // insert the node to make sure that it is in the diagram group and not in any other location
// set up the mouse listeners that were lost in the save/re-open process
if (!groupForMouseListener.equals("RelationGroup")) {
// do not add mouse listeners to the relation group
Node currentNode = parentElement.getFirstChild();
while (currentNode != null) {
((EventTarget) currentNode).addEventListener("mousedown", mouseListenerSvg, false);
currentNode = currentNode.getNextSibling();
}
}
}
previousElement = parentElement;
}
}
public void generateDefaultSvg() {
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
// set up a kinnate namespace so that the ego list and kin type strings can have more permanent storage places
// in order to add the extra namespaces to the svg document we use a string and parse it
// other methods have been tried but this is the most readable and the only one that actually works
// I think this is mainly due to the way the svg dom would otherwise be constructed
// others include:
// doc.getDomConfig()
// doc.getDocumentElement().setAttributeNS(DataStoreSvg.kinDataNameSpaceLocation, "kin:version", "");
// doc.getDocumentElement().setAttribute("xmlns:" + DataStoreSvg.kinDataNameSpace, DataStoreSvg.kinDataNameSpaceLocation); // this method of declaring multiple namespaces looks to me to be wrong but it is the only method that does not get stripped out by the transformer on save
// Document doc = impl.createDocument(svgNS, "svg", null);
// SVGDocument doc = svgCanvas.getSVGDocument();
String templateXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<svg xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns:kin=\"http://mpi.nl/tla/kin\" "
+ "xmlns=\"http://www.w3.org/2000/svg\" contentScriptType=\"text/ecmascript\" "
+ " zoomAndPan=\"magnify\" contentStyleType=\"text/css\" "
+ "preserveAspectRatio=\"xMidYMid meet\" version=\"1.0\"/>";
// DOMImplementation impl = SVGDOMImplementation.getDOMImplementation();
// doc = (SVGDocument) impl.createDocument(svgNameSpace, "svg", null);
String parser = XMLResourceDescriptor.getXMLParserClassName();
SAXSVGDocumentFactory documentFactory = new SAXSVGDocumentFactory(parser);
doc = (SVGDocument) documentFactory.createDocument(svgNameSpace, new StringReader(templateXml));
entitySvg.insertSymbols(doc, svgNameSpace);
configureDiagramGroups();
dataStoreSvg.indexParameters.symbolFieldsFields.setAvailableValues(entitySvg.listSymbolNames(doc, this.svgNameSpace));
svgCanvas.setSVGDocument(doc);
dataStoreSvg.graphData = new GraphSorter();
} catch (IOException exception) {
GuiHelper.linorgBugCatcher.logError(exception);
}
}
private void saveSvg(File svgFilePath) {
svgFile = svgFilePath;
selectedGroupId.clear();
svgUpdateHandler.clearHighlights();
// todo: make sure that any data changes such as the title/description in the kin term groups get updated into the file on save
ArbilComponentBuilder.savePrettyFormatting(doc, svgFile);
requiresSave = false;
}
private void printNodeNames(Node nodeElement) {
System.out.println(nodeElement.getLocalName());
System.out.println(nodeElement.getNamespaceURI());
Node childNode = nodeElement.getFirstChild();
while (childNode != null) {
printNodeNames(childNode);
childNode = childNode.getNextSibling();
}
}
public String[] getKinTypeStrigs() {
return dataStoreSvg.kinTypeStrings;
}
public void setKinTypeStrigs(String[] kinTypeStringArray) {
// strip out any white space, blank lines and remove duplicates
// this has set has been removed because it creates a discrepancy between what the user types and what is processed
// HashSet<String> kinTypeStringSet = new HashSet<String>();
// for (String kinTypeString : kinTypeStringArray) {
// if (kinTypeString != null && kinTypeString.trim().length() > 0) {
// kinTypeStringSet.add(kinTypeString.trim());
// }
// }
// dataStoreSvg.kinTypeStrings = kinTypeStringSet.toArray(new String[]{});
dataStoreSvg.kinTypeStrings = kinTypeStringArray;
}
public IndexerParameters getIndexParameters() {
return dataStoreSvg.indexParameters;
}
public KinTermGroup[] getkinTermGroups() {
return dataStoreSvg.kinTermGroups;
}
public KinTermGroup addKinTermGroup() {
ArrayList<KinTermGroup> kinTermsList = new ArrayList<KinTermGroup>(Arrays.asList(dataStoreSvg.kinTermGroups));
final KinTermGroup kinTermGroup = new KinTermGroup();
kinTermsList.add(kinTermGroup);
dataStoreSvg.kinTermGroups = kinTermsList.toArray(new KinTermGroup[]{});
return kinTermGroup;
}
// public String[] getEgoUniquiIdentifiersList() {
// return dataStoreSvg.egoIdentifierSet.toArray(new String[]{});
// }
// public String[] getEgoIdList() {
// return dataStoreSvg.egoIdentifierSet.toArray(new String[]{});
// }
// public URI[] getEgoPaths() {
// if (egoPathsTemp != null) {
// return egoPathsTemp;
// }
// ArrayList<URI> returnPaths = new ArrayList<URI>();
// for (String egoId : dataStoreSvg.egoIdentifierSet) {
// try {
// String entityPath = getPathForElementId(egoId);
//// if (entityPath != null) {
// returnPaths.add(new URI(entityPath));
//// }
// } catch (URISyntaxException ex) {
// GuiHelper.linorgBugCatcher.logError(ex);
// // todo: warn user with a dialog
// }
// }
// return returnPaths.toArray(new URI[]{});
// }
// public void setRequiredEntities(URI[] egoPathArray, String[] egoIdentifierArray) {
//// egoPathsTemp = egoPathArray; // egoPathsTemp is only required if the ego nodes are not already on the graph (otherwise the path can be obtained from the graph elements)
// dataStoreSvg.requiredEntities = new HashSet<String>(Arrays.asList(egoIdentifierArray));
// }
//
// public void addRequiredEntity(URI[] egoPathArray, String[] egoIdentifierArray) {
//// egoPathsTemp = egoPathArray; // egoPathsTemp is only required if the ego nodes are not already on the graph (otherwise the path can be obtained from the graph elements)
// dataStoreSvg.requiredEntities.addAll(Arrays.asList(egoIdentifierArray));
// }
// public void removeEgo(String[] egoIdentifierArray) {
// dataStoreSvg.egoIdentifierSet.removeAll(Arrays.asList(egoIdentifierArray));
// }
public void setSelectedIds(UniqueIdentifier[] uniqueIdentifiers) {
selectedGroupId.clear();
selectedGroupId.addAll(Arrays.asList(uniqueIdentifiers));
svgUpdateHandler.updateSvgSelectionHighlights();
// mouseListenerSvg.updateSelectionDisplay();
}
public UniqueIdentifier[] getSelectedIds() {
return selectedGroupId.toArray(new UniqueIdentifier[]{});
}
public EntityData getEntityForElementId(UniqueIdentifier uniqueIdentifier) {
for (EntityData entityData : dataStoreSvg.graphData.getDataNodes()) {
if (uniqueIdentifier.equals(entityData.getUniqueIdentifier())) {
return entityData;
}
}
return null;
}
public HashMap<UniqueIdentifier, EntityData> getEntitiesById(UniqueIdentifier[] uniqueIdentifiers) {
ArrayList<UniqueIdentifier> identifierList = new ArrayList<UniqueIdentifier>(Arrays.asList(uniqueIdentifiers));
HashMap<UniqueIdentifier, EntityData> returnMap = new HashMap<UniqueIdentifier, EntityData>();
for (EntityData entityData : dataStoreSvg.graphData.getDataNodes()) {
if (identifierList.contains(entityData.getUniqueIdentifier())) {
returnMap.put(entityData.getUniqueIdentifier(), entityData);
}
}
return returnMap;
}
// public boolean selectionContainsEgo() {
// for (String selectedId : selectedGroupId) {
// if (dataStoreSvg.egoIdentifierSet.contains(selectedId)) {
// return true;
// }
// }
// return false;
// }
public String getPathForElementId(UniqueIdentifier elementId) {
// NamedNodeMap namedNodeMap = doc.getElementById(elementId).getAttributes();
// for (int attributeCounter = 0; attributeCounter < namedNodeMap.getLength(); attributeCounter++) {
// System.out.println(namedNodeMap.item(attributeCounter).getNodeName());
// System.out.println(namedNodeMap.item(attributeCounter).getNamespaceURI());
// System.out.println(namedNodeMap.item(attributeCounter).getNodeValue());
// }
Element entityElement = doc.getElementById(elementId.getAttributeIdentifier());
if (entityElement == null) {
return null;
} else {
return entityElement.getAttributeNS(DataStoreSvg.kinDataNameSpaceLocation, "path");
}
}
public String getKinTypeForElementId(UniqueIdentifier elementId) {
Element entityElement = doc.getElementById(elementId.getAttributeIdentifier());
if (entityElement != null) {
return entityElement.getAttributeNS(DataStoreSvg.kinDataNameSpaceLocation, "kintype");
} else {
return "";
}
}
public void resetZoom() {
// todo: this should be moved to the svg update handler and put into a runnable
AffineTransform at = new AffineTransform();
at.scale(1, 1);
at.setToTranslation(1, 1);
svgCanvas.setRenderingTransform(at);
}
public void resetLayout() {
entitySvg = new EntitySvg();
dataStoreSvg.graphData.setEntitys(dataStoreSvg.graphData.getDataNodes());
dataStoreSvg.graphData.placeAllNodes(entitySvg.entityPositions);
drawNodes();
}
public void clearEntityLocations(UniqueIdentifier[] selectedIdentifiers) {
entitySvg.clearEntityLocations(selectedIdentifiers);
}
public void drawNodes() {
requiresSave = true;
selectedGroupId.clear();
svgUpdateHandler.updateEntities();
}
public void drawNodes(GraphSorter graphDataLocal) {
dataStoreSvg.graphData = graphDataLocal;
drawNodes();
if (graphDataLocal.getDataNodes().length == 0) {
// if all entities have been removed then reset the zoom so that new nodes are going to been centered
// todo: it would be better to move the window to cover the drawing area but not change the zoom
// resetZoom();
}
}
public boolean hasSaveFileName() {
return svgFile != null;
}
public File getFileName() {
return svgFile;
}
public boolean requiresSave() {
return requiresSave;
}
public void setRequiresSave() {
requiresSave = true;
}
public void saveToFile() {
saveSvg(svgFile);
}
public void saveToFile(File saveAsFile) {
saveSvg(saveAsFile);
}
public void updateGraph() {
throw new UnsupportedOperationException("Not supported yet.");
}
public void doActionCommand(MouseListenerSvg.ActionCode actionCode) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
|
desktop/src/main/java/nl/mpi/kinnate/svg/GraphPanel.java
|
package nl.mpi.kinnate.svg;
import nl.mpi.kinnate.kindata.EntityData;
import nl.mpi.kinnate.ui.GraphPanelContextMenu;
import java.awt.BorderLayout;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.geom.AffineTransform;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import javax.swing.JPanel;
import javax.xml.parsers.DocumentBuilderFactory;
import nl.mpi.arbil.data.ArbilComponentBuilder;
import nl.mpi.arbil.ui.GuiHelper;
import nl.mpi.kinnate.entityindexer.IndexerParameters;
import nl.mpi.kinnate.SavePanel;
import nl.mpi.kinnate.kindata.GraphSorter;
import nl.mpi.kinnate.uniqueidentifiers.UniqueIdentifier;
import nl.mpi.kinnate.kintypestrings.KinTermGroup;
import nl.mpi.kinnate.ui.KinDiagramPanel;
import nl.mpi.kinnate.ui.MetadataPanel;
import org.apache.batik.dom.svg.SAXSVGDocumentFactory;
import org.apache.batik.dom.svg.SVGDOMImplementation;
import org.apache.batik.swing.JSVGCanvas;
import org.apache.batik.swing.JSVGScrollPane;
import org.apache.batik.util.XMLResourceDescriptor;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.events.EventTarget;
import org.w3c.dom.svg.SVGDocument;
/**
* Document : GraphPanel
* Created on : Aug 16, 2010, 5:31:33 PM
* Author : Peter Withers
*/
public class GraphPanel extends JPanel implements SavePanel {
private JSVGScrollPane jSVGScrollPane;
protected JSVGCanvas svgCanvas;
protected SVGDocument doc;
public MetadataPanel metadataPanel;
private boolean requiresSave = false;
private File svgFile = null;
protected GraphPanelSize graphPanelSize;
protected LineLookUpTable lineLookUpTable;
protected ArrayList<UniqueIdentifier> selectedGroupId;
protected String svgNameSpace = SVGDOMImplementation.SVG_NAMESPACE_URI;
public DataStoreSvg dataStoreSvg;
protected EntitySvg entitySvg;
// private URI[] egoPathsTemp = null;
public SvgUpdateHandler svgUpdateHandler;
public MouseListenerSvg mouseListenerSvg;
public GraphPanel(KinDiagramPanel kinDiagramPanel) {
dataStoreSvg = new DataStoreSvg();
entitySvg = new EntitySvg();
dataStoreSvg.setDefaults();
svgUpdateHandler = new SvgUpdateHandler(this, kinDiagramPanel);
selectedGroupId = new ArrayList<UniqueIdentifier>();
graphPanelSize = new GraphPanelSize();
this.setLayout(new BorderLayout());
boolean eventsEnabled = true;
boolean selectableText = false;
svgCanvas = new JSVGCanvas(new GraphUserAgent(this), eventsEnabled, selectableText);
// svgCanvas.setMySize(new Dimension(600, 400));
svgCanvas.setDocumentState(JSVGCanvas.ALWAYS_DYNAMIC);
// drawNodes();
svgCanvas.setEnableImageZoomInteractor(false);
svgCanvas.setEnablePanInteractor(false);
svgCanvas.setEnableRotateInteractor(false);
svgCanvas.setEnableZoomInteractor(false);
svgCanvas.addMouseWheelListener(new MouseWheelListener() {
public void mouseWheelMoved(MouseWheelEvent e) {
double scale = 1 - e.getUnitsToScroll() / 10.0;
double tx = -e.getX() * (scale - 1);
double ty = -e.getY() * (scale - 1);
// System.out.println("scale: " + scale);
// System.out.println("scale: " + svgCanvas.getRenderingTransform().getScaleX());
if (scale > 1 || svgCanvas.getRenderingTransform().getScaleX() > 0.01) {
AffineTransform at = new AffineTransform();
at.translate(tx, ty);
at.scale(scale, scale);
at.concatenate(svgCanvas.getRenderingTransform());
svgCanvas.setRenderingTransform(at);
}
}
});
// svgCanvas.setEnableResetTransformInteractor(true);
// svgCanvas.setDoubleBufferedRendering(true); // todo: look into reducing the noticable aliasing on the canvas
mouseListenerSvg = new MouseListenerSvg(kinDiagramPanel, this);
svgCanvas.addMouseListener(mouseListenerSvg);
svgCanvas.addMouseMotionListener(mouseListenerSvg);
jSVGScrollPane = new JSVGScrollPane(svgCanvas);
// svgCanvas.setBackground(Color.LIGHT_GRAY);
this.add(BorderLayout.CENTER, jSVGScrollPane);
svgCanvas.setComponentPopupMenu(new GraphPanelContextMenu(kinDiagramPanel, this, graphPanelSize));
}
// private void zoomDrawing() {
// AffineTransform scaleTransform = new AffineTransform();
// scaleTransform.scale(1 - currentZoom / 10.0, 1 - currentZoom / 10.0);
// System.out.println("currentZoom: " + currentZoom);
//// svgCanvas.setRenderingTransform(scaleTransform);
// Rectangle canvasBounds = this.getBounds();
// SVGRect bbox = ((SVGLocatable) doc.getRootElement()).getBBox();
// if (bbox != null) {
// System.out.println("previousZoomedWith: " + bbox.getWidth());
// }
//// SVGElement rootElement = doc.getRootElement();
//// if (currentWidth < canvasBounds.width) {
// float drawingCenter = (currentWidth / 2);
//// float drawingCenter = (bbox.getX() + (bbox.getWidth() / 2));
// float canvasCenter = (canvasBounds.width / 2);
// zoomAffineTransform = new AffineTransform();
// zoomAffineTransform.translate((canvasCenter - drawingCenter), 1);
// zoomAffineTransform.concatenate(scaleTransform);
// svgCanvas.setRenderingTransform(zoomAffineTransform);
// }
public void setArbilTableModel(MetadataPanel metadataPanel) {
this.metadataPanel = metadataPanel;
}
public void readSvg(URI svgFilePath, boolean savableType) {
if (savableType) {
svgFile = new File(svgFilePath);
} else {
svgFile = null;
}
String parser = XMLResourceDescriptor.getXMLParserClassName();
SAXSVGDocumentFactory documentFactory = new SAXSVGDocumentFactory(parser);
try {
doc = (SVGDocument) documentFactory.createDocument(svgFilePath.toString());
svgCanvas.setDocument(doc);
dataStoreSvg = DataStoreSvg.loadDataFromSvg(doc);
if (dataStoreSvg.indexParameters == null) {
dataStoreSvg.setDefaults();
}
requiresSave = false;
entitySvg.readEntityPositions(doc.getElementById("EntityGroup"));
entitySvg.readEntityPositions(doc.getElementById("LabelsGroup"));
entitySvg.readEntityPositions(doc.getElementById("GraphicsGroup"));
configureDiagramGroups();
dataStoreSvg.indexParameters.symbolFieldsFields.setAvailableValues(entitySvg.listSymbolNames(doc, this.svgNameSpace));
// if (dataStoreSvg.graphData == null) {
// return null;
// }
} catch (IOException ioe) {
GuiHelper.linorgBugCatcher.logError(ioe);
}
// svgCanvas.setSVGDocument(doc);
return; // dataStoreSvg.graphData.getDataNodes();
}
private void configureDiagramGroups() {
Element svgRoot = doc.getDocumentElement();
// make sure the diagram group exisits
Element diagramGroup = doc.getElementById("DiagramGroup");
if (diagramGroup == null) {
diagramGroup = doc.createElementNS(svgNameSpace, "g");
diagramGroup.setAttribute("id", "DiagramGroup");
// add the diagram group to the root element (the 'svg' element)
svgRoot.appendChild(diagramGroup);
}
Element previousElement = null;
// add the graphics group below the entities and relations
// add the relation symbols in a group below the relation lines
// add the entity symbols in a group on top of the relation lines
// add the labels group on top, also added on svg load if missing
for (String groupForMouseListener : new String[]{"LabelsGroup", "EntityGroup", "RelationGroup", "GraphicsGroup"}) {
// add any groups that are required and add them in the required order
Element parentElement = doc.getElementById(groupForMouseListener);
if (parentElement == null) {
parentElement = doc.createElementNS(svgNameSpace, "g");
parentElement.setAttribute("id", groupForMouseListener);
diagramGroup.insertBefore(parentElement, previousElement);
} else {
diagramGroup.insertBefore(parentElement, previousElement); // insert the node to make sure that it is in the diagram group and not in any other location
// set up the mouse listeners that were lost in the save/re-open process
if (!groupForMouseListener.equals("RelationGroup")) {
// do not add mouse listeners to the relation group
Node currentNode = parentElement.getFirstChild();
while (currentNode != null) {
((EventTarget) currentNode).addEventListener("mousedown", mouseListenerSvg, false);
currentNode = currentNode.getNextSibling();
}
}
}
previousElement = parentElement;
}
}
public void generateDefaultSvg() {
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
// set up a kinnate namespace so that the ego list and kin type strings can have more permanent storage places
// in order to add the extra namespaces to the svg document we use a string and parse it
// other methods have been tried but this is the most readable and the only one that actually works
// I think this is mainly due to the way the svg dom would otherwise be constructed
// others include:
// doc.getDomConfig()
// doc.getDocumentElement().setAttributeNS(DataStoreSvg.kinDataNameSpaceLocation, "kin:version", "");
// doc.getDocumentElement().setAttribute("xmlns:" + DataStoreSvg.kinDataNameSpace, DataStoreSvg.kinDataNameSpaceLocation); // this method of declaring multiple namespaces looks to me to be wrong but it is the only method that does not get stripped out by the transformer on save
// Document doc = impl.createDocument(svgNS, "svg", null);
// SVGDocument doc = svgCanvas.getSVGDocument();
String templateXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<svg xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns:kin=\"http://mpi.nl/tla/kin\" "
+ "xmlns=\"http://www.w3.org/2000/svg\" contentScriptType=\"text/ecmascript\" "
+ " zoomAndPan=\"magnify\" contentStyleType=\"text/css\" "
+ "preserveAspectRatio=\"xMidYMid meet\" version=\"1.0\"/>";
// DOMImplementation impl = SVGDOMImplementation.getDOMImplementation();
// doc = (SVGDocument) impl.createDocument(svgNameSpace, "svg", null);
String parser = XMLResourceDescriptor.getXMLParserClassName();
SAXSVGDocumentFactory documentFactory = new SAXSVGDocumentFactory(parser);
doc = (SVGDocument) documentFactory.createDocument(svgNameSpace, new StringReader(templateXml));
entitySvg.insertSymbols(doc, svgNameSpace);
configureDiagramGroups();
dataStoreSvg.indexParameters.symbolFieldsFields.setAvailableValues(entitySvg.listSymbolNames(doc, this.svgNameSpace));
svgCanvas.setSVGDocument(doc);
dataStoreSvg.graphData = new GraphSorter();
} catch (IOException exception) {
GuiHelper.linorgBugCatcher.logError(exception);
}
}
private void saveSvg(File svgFilePath) {
svgFile = svgFilePath;
selectedGroupId.clear();
svgUpdateHandler.clearHighlights();
// todo: make sure that any data changes such as the title/description in the kin term groups get updated into the file on save
ArbilComponentBuilder.savePrettyFormatting(doc, svgFile);
requiresSave = false;
}
private void printNodeNames(Node nodeElement) {
System.out.println(nodeElement.getLocalName());
System.out.println(nodeElement.getNamespaceURI());
Node childNode = nodeElement.getFirstChild();
while (childNode != null) {
printNodeNames(childNode);
childNode = childNode.getNextSibling();
}
}
public String[] getKinTypeStrigs() {
return dataStoreSvg.kinTypeStrings;
}
public void setKinTypeStrigs(String[] kinTypeStringArray) {
// strip out any white space, blank lines and remove duplicates
// this has set has been removed because it creates a discrepancy between what the user types and what is processed
// HashSet<String> kinTypeStringSet = new HashSet<String>();
// for (String kinTypeString : kinTypeStringArray) {
// if (kinTypeString != null && kinTypeString.trim().length() > 0) {
// kinTypeStringSet.add(kinTypeString.trim());
// }
// }
// dataStoreSvg.kinTypeStrings = kinTypeStringSet.toArray(new String[]{});
dataStoreSvg.kinTypeStrings = kinTypeStringArray;
}
public IndexerParameters getIndexParameters() {
return dataStoreSvg.indexParameters;
}
public KinTermGroup[] getkinTermGroups() {
return dataStoreSvg.kinTermGroups;
}
public KinTermGroup addKinTermGroup() {
ArrayList<KinTermGroup> kinTermsList = new ArrayList<KinTermGroup>(Arrays.asList(dataStoreSvg.kinTermGroups));
final KinTermGroup kinTermGroup = new KinTermGroup();
kinTermsList.add(kinTermGroup);
dataStoreSvg.kinTermGroups = kinTermsList.toArray(new KinTermGroup[]{});
return kinTermGroup;
}
// public String[] getEgoUniquiIdentifiersList() {
// return dataStoreSvg.egoIdentifierSet.toArray(new String[]{});
// }
// public String[] getEgoIdList() {
// return dataStoreSvg.egoIdentifierSet.toArray(new String[]{});
// }
// public URI[] getEgoPaths() {
// if (egoPathsTemp != null) {
// return egoPathsTemp;
// }
// ArrayList<URI> returnPaths = new ArrayList<URI>();
// for (String egoId : dataStoreSvg.egoIdentifierSet) {
// try {
// String entityPath = getPathForElementId(egoId);
//// if (entityPath != null) {
// returnPaths.add(new URI(entityPath));
//// }
// } catch (URISyntaxException ex) {
// GuiHelper.linorgBugCatcher.logError(ex);
// // todo: warn user with a dialog
// }
// }
// return returnPaths.toArray(new URI[]{});
// }
// public void setRequiredEntities(URI[] egoPathArray, String[] egoIdentifierArray) {
//// egoPathsTemp = egoPathArray; // egoPathsTemp is only required if the ego nodes are not already on the graph (otherwise the path can be obtained from the graph elements)
// dataStoreSvg.requiredEntities = new HashSet<String>(Arrays.asList(egoIdentifierArray));
// }
//
// public void addRequiredEntity(URI[] egoPathArray, String[] egoIdentifierArray) {
//// egoPathsTemp = egoPathArray; // egoPathsTemp is only required if the ego nodes are not already on the graph (otherwise the path can be obtained from the graph elements)
// dataStoreSvg.requiredEntities.addAll(Arrays.asList(egoIdentifierArray));
// }
// public void removeEgo(String[] egoIdentifierArray) {
// dataStoreSvg.egoIdentifierSet.removeAll(Arrays.asList(egoIdentifierArray));
// }
public void setSelectedIds(UniqueIdentifier[] uniqueIdentifiers) {
selectedGroupId.clear();
selectedGroupId.addAll(Arrays.asList(uniqueIdentifiers));
svgUpdateHandler.updateSvgSelectionHighlights();
// mouseListenerSvg.updateSelectionDisplay();
}
public UniqueIdentifier[] getSelectedIds() {
return selectedGroupId.toArray(new UniqueIdentifier[]{});
}
public EntityData getEntityForElementId(UniqueIdentifier uniqueIdentifier) {
for (EntityData entityData : dataStoreSvg.graphData.getDataNodes()) {
if (uniqueIdentifier.equals(entityData.getUniqueIdentifier())) {
return entityData;
}
}
return null;
}
public HashMap<UniqueIdentifier, EntityData> getEntitiesById(UniqueIdentifier[] uniqueIdentifiers) {
ArrayList<UniqueIdentifier> identifierList = new ArrayList<UniqueIdentifier>(Arrays.asList(uniqueIdentifiers));
HashMap<UniqueIdentifier, EntityData> returnMap = new HashMap<UniqueIdentifier, EntityData>();
for (EntityData entityData : dataStoreSvg.graphData.getDataNodes()) {
if (identifierList.contains(entityData.getUniqueIdentifier())) {
returnMap.put(entityData.getUniqueIdentifier(), entityData);
}
}
return returnMap;
}
// public boolean selectionContainsEgo() {
// for (String selectedId : selectedGroupId) {
// if (dataStoreSvg.egoIdentifierSet.contains(selectedId)) {
// return true;
// }
// }
// return false;
// }
public String getPathForElementId(UniqueIdentifier elementId) {
// NamedNodeMap namedNodeMap = doc.getElementById(elementId).getAttributes();
// for (int attributeCounter = 0; attributeCounter < namedNodeMap.getLength(); attributeCounter++) {
// System.out.println(namedNodeMap.item(attributeCounter).getNodeName());
// System.out.println(namedNodeMap.item(attributeCounter).getNamespaceURI());
// System.out.println(namedNodeMap.item(attributeCounter).getNodeValue());
// }
Element entityElement = doc.getElementById(elementId.getAttributeIdentifier());
if (entityElement == null) {
return null;
} else {
return entityElement.getAttributeNS(DataStoreSvg.kinDataNameSpaceLocation, "path");
}
}
public String getKinTypeForElementId(UniqueIdentifier elementId) {
Element entityElement = doc.getElementById(elementId.getAttributeIdentifier());
if (entityElement != null) {
return entityElement.getAttributeNS(DataStoreSvg.kinDataNameSpaceLocation, "kintype");
} else {
return "";
}
}
public void resetZoom() {
// todo: this should be moved to the svg update handler and put into a runnable
AffineTransform at = new AffineTransform();
at.scale(1, 1);
at.setToTranslation(1, 1);
svgCanvas.setRenderingTransform(at);
}
public void resetLayout() {
entitySvg = new EntitySvg();
dataStoreSvg.graphData.setEntitys(dataStoreSvg.graphData.getDataNodes());
dataStoreSvg.graphData.placeAllNodes(entitySvg.entityPositions);
drawNodes();
}
public void clearEntityLocations(UniqueIdentifier[] selectedIdentifiers) {
entitySvg.clearEntityLocations(selectedIdentifiers);
}
public void drawNodes() {
requiresSave = true;
selectedGroupId.clear();
svgUpdateHandler.updateEntities();
}
public void drawNodes(GraphSorter graphDataLocal) {
dataStoreSvg.graphData = graphDataLocal;
drawNodes();
if (graphDataLocal.getDataNodes().length == 0) {
// if all entities have been removed then reset the zoom so that new nodes are going to been centered
// todo: it would be better to move the window to cover the drawing area but not change the zoom
// resetZoom();
}
}
public boolean hasSaveFileName() {
return svgFile != null;
}
public File getFileName() {
return svgFile;
}
public boolean requiresSave() {
return requiresSave;
}
public void setRequiresSave() {
requiresSave = true;
}
public void saveToFile() {
saveSvg(svgFile);
}
public void saveToFile(File saveAsFile) {
saveSvg(saveAsFile);
}
public void updateGraph() {
throw new UnsupportedOperationException("Not supported yet.");
}
}
|
Separated the file menu from the MainFrame class.
Created a diagram window manager class and moved relevant code out of the MainFrame into the new class.
Added a check for unsaved diagrams on application close.
Separated out the edit menu into a different class.
Updated the import data menu.
Updated the edit menu to use the SavePanel and better handle hot keys.
|
desktop/src/main/java/nl/mpi/kinnate/svg/GraphPanel.java
|
Separated the file menu from the MainFrame class. Created a diagram window manager class and moved relevant code out of the MainFrame into the new class. Added a check for unsaved diagrams on application close. Separated out the edit menu into a different class. Updated the import data menu. Updated the edit menu to use the SavePanel and better handle hot keys.
|
<ide><path>esktop/src/main/java/nl/mpi/kinnate/svg/GraphPanel.java
<ide> public void updateGraph() {
<ide> throw new UnsupportedOperationException("Not supported yet.");
<ide> }
<add>
<add> public void doActionCommand(MouseListenerSvg.ActionCode actionCode) {
<add> throw new UnsupportedOperationException("Not supported yet.");
<add> }
<ide> }
|
|
Java
|
apache-2.0
|
4108f5f35e22db3401a11fbbf93f85be21394f5c
| 0 |
apache/commons-math,apache/commons-math,apache/commons-math,apache/commons-math
|
/*
* 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.commons.math4.optim.linear;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.junit.Test;
import org.junit.Ignore;
import org.junit.Assert;
import org.apache.commons.numbers.core.Precision;
import org.apache.commons.math4.exception.DimensionMismatchException;
import org.apache.commons.math4.exception.TooManyIterationsException;
import org.apache.commons.math4.optim.MaxIter;
import org.apache.commons.math4.optim.PointValuePair;
import org.apache.commons.math4.optim.linear.LinearConstraint;
import org.apache.commons.math4.optim.linear.LinearConstraintSet;
import org.apache.commons.math4.optim.linear.LinearObjectiveFunction;
import org.apache.commons.math4.optim.linear.NoFeasibleSolutionException;
import org.apache.commons.math4.optim.linear.NonNegativeConstraint;
import org.apache.commons.math4.optim.linear.PivotSelectionRule;
import org.apache.commons.math4.optim.linear.Relationship;
import org.apache.commons.math4.optim.linear.SimplexSolver;
import org.apache.commons.math4.optim.linear.SolutionCallback;
import org.apache.commons.math4.optim.linear.UnboundedSolutionException;
import org.apache.commons.math4.optim.nonlinear.scalar.GoalType;
public class SimplexSolverTest {
private static final MaxIter DEFAULT_MAX_ITER = new MaxIter(100);
@Test
public void testMath842Cycle() {
// from http://www.math.toronto.edu/mpugh/Teaching/APM236_04/bland
// maximize 10 x1 - 57 x2 - 9 x3 - 24 x4
// subject to
// 1/2 x1 - 11/2 x2 - 5/2 x3 + 9 x4 <= 0
// 1/2 x1 - 3/2 x2 - 1/2 x3 + x4 <= 0
// x1 <= 1
// x1,x2,x3,x4 >= 0
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 10, -57, -9, -24}, 0);
ArrayList<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] {0.5, -5.5, -2.5, 9}, Relationship.LEQ, 0));
constraints.add(new LinearConstraint(new double[] {0.5, -1.5, -0.5, 1}, Relationship.LEQ, 0));
constraints.add(new LinearConstraint(new double[] { 1, 0, 0, 0}, Relationship.LEQ, 1));
double epsilon = 1e-6;
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(f, new LinearConstraintSet(constraints),
GoalType.MAXIMIZE,
new NonNegativeConstraint(true),
PivotSelectionRule.BLAND);
Assert.assertEquals(1.0d, solution.getValue(), epsilon);
Assert.assertTrue(validSolution(solution, constraints, epsilon));
}
@Test
public void testMath828() {
LinearObjectiveFunction f = new LinearObjectiveFunction(
new double[] { 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, 0.0);
ArrayList <LinearConstraint>constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] {0.0, 39.0, 23.0, 96.0, 15.0, 48.0, 9.0, 21.0, 48.0, 36.0, 76.0, 19.0, 88.0, 17.0, 16.0, 36.0,}, Relationship.GEQ, 15.0));
constraints.add(new LinearConstraint(new double[] {0.0, 59.0, 93.0, 12.0, 29.0, 78.0, 73.0, 87.0, 32.0, 70.0, 68.0, 24.0, 11.0, 26.0, 65.0, 25.0,}, Relationship.GEQ, 29.0));
constraints.add(new LinearConstraint(new double[] {0.0, 74.0, 5.0, 82.0, 6.0, 97.0, 55.0, 44.0, 52.0, 54.0, 5.0, 93.0, 91.0, 8.0, 20.0, 97.0,}, Relationship.GEQ, 6.0));
constraints.add(new LinearConstraint(new double[] {8.0, -3.0, -28.0, -72.0, -8.0, -31.0, -31.0, -74.0, -47.0, -59.0, -24.0, -57.0, -56.0, -16.0, -92.0, -59.0,}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {25.0, -7.0, -99.0, -78.0, -25.0, -14.0, -16.0, -89.0, -39.0, -56.0, -53.0, -9.0, -18.0, -26.0, -11.0, -61.0,}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {33.0, -95.0, -15.0, -4.0, -33.0, -3.0, -20.0, -96.0, -27.0, -13.0, -80.0, -24.0, -3.0, -13.0, -57.0, -76.0,}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {7.0, -95.0, -39.0, -93.0, -7.0, -94.0, -94.0, -62.0, -76.0, -26.0, -53.0, -57.0, -31.0, -76.0, -53.0, -52.0,}, Relationship.GEQ, 0.0));
double epsilon = 1e-6;
PointValuePair solution = new SimplexSolver().optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MINIMIZE, new NonNegativeConstraint(true));
Assert.assertEquals(1.0d, solution.getValue(), epsilon);
Assert.assertTrue(validSolution(solution, constraints, epsilon));
}
@Test
public void testMath828Cycle() {
LinearObjectiveFunction f = new LinearObjectiveFunction(
new double[] { 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, 0.0);
ArrayList <LinearConstraint>constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] {0.0, 16.0, 14.0, 69.0, 1.0, 85.0, 52.0, 43.0, 64.0, 97.0, 14.0, 74.0, 89.0, 28.0, 94.0, 58.0, 13.0, 22.0, 21.0, 17.0, 30.0, 25.0, 1.0, 59.0, 91.0, 78.0, 12.0, 74.0, 56.0, 3.0, 88.0,}, Relationship.GEQ, 91.0));
constraints.add(new LinearConstraint(new double[] {0.0, 60.0, 40.0, 81.0, 71.0, 72.0, 46.0, 45.0, 38.0, 48.0, 40.0, 17.0, 33.0, 85.0, 64.0, 32.0, 84.0, 3.0, 54.0, 44.0, 71.0, 67.0, 90.0, 95.0, 54.0, 99.0, 99.0, 29.0, 52.0, 98.0, 9.0,}, Relationship.GEQ, 54.0));
constraints.add(new LinearConstraint(new double[] {0.0, 41.0, 12.0, 86.0, 90.0, 61.0, 31.0, 41.0, 23.0, 89.0, 17.0, 74.0, 44.0, 27.0, 16.0, 47.0, 80.0, 32.0, 11.0, 56.0, 68.0, 82.0, 11.0, 62.0, 62.0, 53.0, 39.0, 16.0, 48.0, 1.0, 63.0,}, Relationship.GEQ, 62.0));
constraints.add(new LinearConstraint(new double[] {83.0, -76.0, -94.0, -19.0, -15.0, -70.0, -72.0, -57.0, -63.0, -65.0, -22.0, -94.0, -22.0, -88.0, -86.0, -89.0, -72.0, -16.0, -80.0, -49.0, -70.0, -93.0, -95.0, -17.0, -83.0, -97.0, -31.0, -47.0, -31.0, -13.0, -23.0,}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {41.0, -96.0, -41.0, -48.0, -70.0, -43.0, -43.0, -43.0, -97.0, -37.0, -85.0, -70.0, -45.0, -67.0, -87.0, -69.0, -94.0, -54.0, -54.0, -92.0, -79.0, -10.0, -35.0, -20.0, -41.0, -41.0, -65.0, -25.0, -12.0, -8.0, -46.0,}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {27.0, -42.0, -65.0, -49.0, -53.0, -42.0, -17.0, -2.0, -61.0, -31.0, -76.0, -47.0, -8.0, -93.0, -86.0, -62.0, -65.0, -63.0, -22.0, -43.0, -27.0, -23.0, -32.0, -74.0, -27.0, -63.0, -47.0, -78.0, -29.0, -95.0, -73.0,}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {15.0, -46.0, -41.0, -83.0, -98.0, -99.0, -21.0, -35.0, -7.0, -14.0, -80.0, -63.0, -18.0, -42.0, -5.0, -34.0, -56.0, -70.0, -16.0, -18.0, -74.0, -61.0, -47.0, -41.0, -15.0, -79.0, -18.0, -47.0, -88.0, -68.0, -55.0,}, Relationship.GEQ, 0.0));
double epsilon = 1e-6;
PointValuePair solution = new SimplexSolver().optimize(DEFAULT_MAX_ITER, f,
new LinearConstraintSet(constraints),
GoalType.MINIMIZE, new NonNegativeConstraint(true),
PivotSelectionRule.BLAND);
Assert.assertEquals(1.0d, solution.getValue(), epsilon);
Assert.assertTrue(validSolution(solution, constraints, epsilon));
}
@Test
public void testMath781() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 2, 6, 7 }, 0);
ArrayList<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] { 1, 2, 1 }, Relationship.LEQ, 2));
constraints.add(new LinearConstraint(new double[] { -1, 1, 1 }, Relationship.LEQ, -1));
constraints.add(new LinearConstraint(new double[] { 2, -3, 1 }, Relationship.LEQ, -1));
double epsilon = 1e-6;
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MAXIMIZE, new NonNegativeConstraint(false));
Assert.assertTrue(Precision.compareTo(solution.getPoint()[0], 0.0d, epsilon) > 0);
Assert.assertTrue(Precision.compareTo(solution.getPoint()[1], 0.0d, epsilon) > 0);
Assert.assertTrue(Precision.compareTo(solution.getPoint()[2], 0.0d, epsilon) < 0);
Assert.assertEquals(2.0d, solution.getValue(), epsilon);
}
@Test
public void testMath713NegativeVariable() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] {1.0, 1.0}, 0.0d);
ArrayList<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] {1, 0}, Relationship.EQ, 1));
double epsilon = 1e-6;
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MINIMIZE, new NonNegativeConstraint(true));
Assert.assertTrue(Precision.compareTo(solution.getPoint()[0], 0.0d, epsilon) >= 0);
Assert.assertTrue(Precision.compareTo(solution.getPoint()[1], 0.0d, epsilon) >= 0);
}
@Test
public void testMath434NegativeVariable() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] {0.0, 0.0, 1.0}, 0.0d);
ArrayList<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] {1, 1, 0}, Relationship.EQ, 5));
constraints.add(new LinearConstraint(new double[] {0, 0, 1}, Relationship.GEQ, -10));
double epsilon = 1e-6;
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MINIMIZE, new NonNegativeConstraint(false));
Assert.assertEquals(5.0, solution.getPoint()[0] + solution.getPoint()[1], epsilon);
Assert.assertEquals(-10.0, solution.getPoint()[2], epsilon);
Assert.assertEquals(-10.0, solution.getValue(), epsilon);
}
@Test(expected = NoFeasibleSolutionException.class)
public void testMath434UnfeasibleSolution() {
double epsilon = 1e-6;
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] {1.0, 0.0}, 0.0);
ArrayList<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] {epsilon/2, 0.5}, Relationship.EQ, 0));
constraints.add(new LinearConstraint(new double[] {1e-3, 0.1}, Relationship.EQ, 10));
SimplexSolver solver = new SimplexSolver();
// allowing only non-negative values, no feasible solution shall be found
solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MINIMIZE, new NonNegativeConstraint(true));
}
@Test
public void testMath434PivotRowSelection() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] {1.0}, 0.0);
double epsilon = 1e-6;
ArrayList<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] {200}, Relationship.GEQ, 1));
constraints.add(new LinearConstraint(new double[] {100}, Relationship.GEQ, 0.499900001));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MINIMIZE, new NonNegativeConstraint(false));
Assert.assertTrue(Precision.compareTo(solution.getPoint()[0] * 200.d, 1.d, epsilon) >= 0);
Assert.assertEquals(0.0050, solution.getValue(), epsilon);
}
@Test
public void testMath434PivotRowSelection2() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] {0.0d, 1.0d, 1.0d, 0.0d, 0.0d, 0.0d, 0.0d}, 0.0d);
ArrayList<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] {1.0d, -0.1d, 0.0d, 0.0d, 0.0d, 0.0d, 0.0d}, Relationship.EQ, -0.1d));
constraints.add(new LinearConstraint(new double[] {1.0d, 0.0d, 0.0d, 0.0d, 0.0d, 0.0d, 0.0d}, Relationship.GEQ, -1e-18d));
constraints.add(new LinearConstraint(new double[] {0.0d, 1.0d, 0.0d, 0.0d, 0.0d, 0.0d, 0.0d}, Relationship.GEQ, 0.0d));
constraints.add(new LinearConstraint(new double[] {0.0d, 0.0d, 0.0d, 1.0d, 0.0d, -0.0128588d, 1e-5d}, Relationship.EQ, 0.0d));
constraints.add(new LinearConstraint(new double[] {0.0d, 0.0d, 0.0d, 0.0d, 1.0d, 1e-5d, -0.0128586d}, Relationship.EQ, 1e-10d));
constraints.add(new LinearConstraint(new double[] {0.0d, 0.0d, 1.0d, -1.0d, 0.0d, 0.0d, 0.0d}, Relationship.GEQ, 0.0d));
constraints.add(new LinearConstraint(new double[] {0.0d, 0.0d, 1.0d, 1.0d, 0.0d, 0.0d, 0.0d}, Relationship.GEQ, 0.0d));
constraints.add(new LinearConstraint(new double[] {0.0d, 0.0d, 1.0d, 0.0d, -1.0d, 0.0d, 0.0d}, Relationship.GEQ, 0.0d));
constraints.add(new LinearConstraint(new double[] {0.0d, 0.0d, 1.0d, 0.0d, 1.0d, 0.0d, 0.0d}, Relationship.GEQ, 0.0d));
double epsilon = 1e-7;
SimplexSolver simplex = new SimplexSolver();
PointValuePair solution = simplex.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MINIMIZE, new NonNegativeConstraint(false));
Assert.assertTrue(Precision.compareTo(solution.getPoint()[0], -1e-18d, epsilon) >= 0);
Assert.assertEquals(1.0d, solution.getPoint()[1], epsilon);
Assert.assertEquals(0.0d, solution.getPoint()[2], epsilon);
Assert.assertEquals(1.0d, solution.getValue(), epsilon);
}
@Test
public void testMath272() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 2, 2, 1 }, 0);
Collection<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] { 1, 1, 0 }, Relationship.GEQ, 1));
constraints.add(new LinearConstraint(new double[] { 1, 0, 1 }, Relationship.GEQ, 1));
constraints.add(new LinearConstraint(new double[] { 0, 1, 0 }, Relationship.GEQ, 1));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MINIMIZE, new NonNegativeConstraint(true));
Assert.assertEquals(0.0, solution.getPoint()[0], .0000001);
Assert.assertEquals(1.0, solution.getPoint()[1], .0000001);
Assert.assertEquals(1.0, solution.getPoint()[2], .0000001);
Assert.assertEquals(3.0, solution.getValue(), .0000001);
}
@Test
public void testMath286() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 0.8, 0.2, 0.7, 0.3, 0.6, 0.4 }, 0 );
Collection<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] { 1, 0, 1, 0, 1, 0 }, Relationship.EQ, 23.0));
constraints.add(new LinearConstraint(new double[] { 0, 1, 0, 1, 0, 1 }, Relationship.EQ, 23.0));
constraints.add(new LinearConstraint(new double[] { 1, 0, 0, 0, 0, 0 }, Relationship.GEQ, 10.0));
constraints.add(new LinearConstraint(new double[] { 0, 0, 1, 0, 0, 0 }, Relationship.GEQ, 8.0));
constraints.add(new LinearConstraint(new double[] { 0, 0, 0, 0, 1, 0 }, Relationship.GEQ, 5.0));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MAXIMIZE, new NonNegativeConstraint(true));
Assert.assertEquals(25.8, solution.getValue(), .0000001);
Assert.assertEquals(23.0, solution.getPoint()[0] + solution.getPoint()[2] + solution.getPoint()[4], 0.0000001);
Assert.assertEquals(23.0, solution.getPoint()[1] + solution.getPoint()[3] + solution.getPoint()[5], 0.0000001);
Assert.assertTrue(solution.getPoint()[0] >= 10.0 - 0.0000001);
Assert.assertTrue(solution.getPoint()[2] >= 8.0 - 0.0000001);
Assert.assertTrue(solution.getPoint()[4] >= 5.0 - 0.0000001);
}
@Test
public void testDegeneracy() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 0.8, 0.7 }, 0 );
Collection<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.LEQ, 18.0));
constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.GEQ, 10.0));
constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.GEQ, 8.0));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MINIMIZE, new NonNegativeConstraint(true));
Assert.assertEquals(13.6, solution.getValue(), .0000001);
}
@Test
public void testMath288() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 7, 3, 0, 0 }, 0 );
Collection<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] { 3, 0, -5, 0 }, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] { 2, 0, 0, -5 }, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] { 0, 3, 0, -5 }, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] { 1, 0, 0, 0 }, Relationship.LEQ, 1.0));
constraints.add(new LinearConstraint(new double[] { 0, 1, 0, 0 }, Relationship.LEQ, 1.0));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MAXIMIZE, new NonNegativeConstraint(true));
Assert.assertEquals(10.0, solution.getValue(), .0000001);
}
@Test
public void testMath290GEQ() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 1, 5 }, 0 );
Collection<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] { 2, 0 }, Relationship.GEQ, -1.0));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MINIMIZE, new NonNegativeConstraint(true));
Assert.assertEquals(0, solution.getValue(), .0000001);
Assert.assertEquals(0, solution.getPoint()[0], .0000001);
Assert.assertEquals(0, solution.getPoint()[1], .0000001);
}
@Test(expected=NoFeasibleSolutionException.class)
public void testMath290LEQ() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 1, 5 }, 0 );
Collection<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] { 2, 0 }, Relationship.LEQ, -1.0));
SimplexSolver solver = new SimplexSolver();
solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MINIMIZE, new NonNegativeConstraint(true));
}
@Test
public void testMath293() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 0.8, 0.2, 0.7, 0.3, 0.4, 0.6}, 0 );
Collection<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] { 1, 0, 1, 0, 1, 0 }, Relationship.EQ, 30.0));
constraints.add(new LinearConstraint(new double[] { 0, 1, 0, 1, 0, 1 }, Relationship.EQ, 30.0));
constraints.add(new LinearConstraint(new double[] { 0.8, 0.2, 0.0, 0.0, 0.0, 0.0 }, Relationship.GEQ, 10.0));
constraints.add(new LinearConstraint(new double[] { 0.0, 0.0, 0.7, 0.3, 0.0, 0.0 }, Relationship.GEQ, 10.0));
constraints.add(new LinearConstraint(new double[] { 0.0, 0.0, 0.0, 0.0, 0.4, 0.6 }, Relationship.GEQ, 10.0));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution1 = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MAXIMIZE, new NonNegativeConstraint(true));
Assert.assertEquals(15.7143, solution1.getPoint()[0], .0001);
Assert.assertEquals(0.0, solution1.getPoint()[1], .0001);
Assert.assertEquals(14.2857, solution1.getPoint()[2], .0001);
Assert.assertEquals(0.0, solution1.getPoint()[3], .0001);
Assert.assertEquals(0.0, solution1.getPoint()[4], .0001);
Assert.assertEquals(30.0, solution1.getPoint()[5], .0001);
Assert.assertEquals(40.57143, solution1.getValue(), .0001);
double valA = 0.8 * solution1.getPoint()[0] + 0.2 * solution1.getPoint()[1];
double valB = 0.7 * solution1.getPoint()[2] + 0.3 * solution1.getPoint()[3];
double valC = 0.4 * solution1.getPoint()[4] + 0.6 * solution1.getPoint()[5];
f = new LinearObjectiveFunction(new double[] { 0.8, 0.2, 0.7, 0.3, 0.4, 0.6}, 0 );
constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] { 1, 0, 1, 0, 1, 0 }, Relationship.EQ, 30.0));
constraints.add(new LinearConstraint(new double[] { 0, 1, 0, 1, 0, 1 }, Relationship.EQ, 30.0));
constraints.add(new LinearConstraint(new double[] { 0.8, 0.2, 0.0, 0.0, 0.0, 0.0 }, Relationship.GEQ, valA));
constraints.add(new LinearConstraint(new double[] { 0.0, 0.0, 0.7, 0.3, 0.0, 0.0 }, Relationship.GEQ, valB));
constraints.add(new LinearConstraint(new double[] { 0.0, 0.0, 0.0, 0.0, 0.4, 0.6 }, Relationship.GEQ, valC));
PointValuePair solution2 = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MAXIMIZE, new NonNegativeConstraint(true));
Assert.assertEquals(40.57143, solution2.getValue(), .0001);
}
@Test
public void testMath930() {
Collection<LinearConstraint> constraints = createMath930Constraints();
double[] objFunctionCoeff = new double[33];
objFunctionCoeff[3] = 1;
LinearObjectiveFunction f = new LinearObjectiveFunction(objFunctionCoeff, 0);
SimplexSolver solver = new SimplexSolver(1e-4, 10, 1e-6);
PointValuePair solution = solver.optimize(new MaxIter(1000), f, new LinearConstraintSet(constraints),
GoalType.MINIMIZE, new NonNegativeConstraint(true));
Assert.assertEquals(0.3752298, solution.getValue(), 1e-4);
}
private List<LinearConstraint> createMath930Constraints() {
List<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] {1, -1, -1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, -1, -1, 1, 1, -1, -1, 1, -1, 1, 1, -1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 1, 0, -1, 0, -1, 0, 1, 0, -1, 0, 1, 0, 1, 0, -1, 0, -1, 0, 1, 0, 1, 0, -1, 0, 1, 0, -1, 0, -1, 0, 1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.628803}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.676993}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 1, -1, 0, 0, -1, 1, 0, 0, -1, 1, 0, 0, 1, -1, 0, 0, -1, 1, 0, 0, 1, -1, 0, 0, 1, -1, 0, 0, -1, 1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.136677}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.444434}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, 1, 0, 0, 0, -1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, -1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.254028}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.302218}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 1, -1, -1, 1, 0, 0, 0, 0, -1, 1, 1, -1, 0, 0, 0, 0, -1, 1, 1, -1, 0, 0, 0, 0, 1, -1, -1, 1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.653981}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.690437}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 1, 0, -1, 0, 0, 0, 0, 0, -1, 0, 1, 0, 0, 0, 0, 0, -1, 0, 1, 0, 0, 0, 0, 0, 1, 0, -1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.423786}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.486717}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 0, 0, -1, 1, 0, 0, 0, 0, 0, 0, -1, 1, 0, 0, 0, 0, 0, 0, 1, -1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.049232}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.304747}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.129826}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.205625}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 1, -1, 1, 1, -1, 0, 0, 0, 0, 0, 0, 0, 0, -1, 1, 1, -1, 1, -1, -1, 1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.621944}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.764385}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1, 0, -1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 1, 0, 1, 0, -1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.432572}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.480762}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0, -1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 1, 0, 0, 1, -1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.055983}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.11378}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.009607}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.057797}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 1, 1, -1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.407308}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.452749}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.269677}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.321806}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.049232}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.06902}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.028754}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.484254}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.524607}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1, 0, -1, 0, 1, 0, -1, 0, 1, 0, 1, 0, -1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.385492}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.430134}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0, -1, 1, 0, 0, -1, 1, 0, 0, 1, -1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.34983}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.375781}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, 1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.254028}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.281308}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 1, 0, 0, 0, 0, -1, 1, 1, -1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.304995}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.345347}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1, 0, 0, 0, 0, 0, -1, 0, 1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.288899}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.332212}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 0, 0, -1, 1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.14351}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.17057}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, -1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, -0.129826}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, -0.157435}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 1, -1, 1, 1, -1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, -0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, -1}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1, 0, -1, 0, 1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, -0.141071}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, -0.232574}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0, -1, 1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, -0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, -1}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, -1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, -0.009607}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, -0.057797}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, -0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, -1}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, -0.091644}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, -0.203531}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -0.028754}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, Relationship.EQ, 1.0));
return constraints;
}
@Test
public void testSimplexSolver() {
LinearObjectiveFunction f =
new LinearObjectiveFunction(new double[] { 15, 10 }, 7);
Collection<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.LEQ, 2));
constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.LEQ, 3));
constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.EQ, 4));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MAXIMIZE, new NonNegativeConstraint(true));
Assert.assertEquals(2.0, solution.getPoint()[0], 0.0);
Assert.assertEquals(2.0, solution.getPoint()[1], 0.0);
Assert.assertEquals(57.0, solution.getValue(), 0.0);
}
@Test
public void testSingleVariableAndConstraint() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 3 }, 0);
Collection<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] { 1 }, Relationship.LEQ, 10));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MAXIMIZE, new NonNegativeConstraint(false));
Assert.assertEquals(10.0, solution.getPoint()[0], 0.0);
Assert.assertEquals(30.0, solution.getValue(), 0.0);
}
/**
* With no artificial variables needed (no equals and no greater than
* constraints) we can go straight to Phase 2.
*/
@Test
public void testModelWithNoArtificialVars() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15, 10 }, 0);
Collection<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.LEQ, 2));
constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.LEQ, 3));
constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.LEQ, 4));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MAXIMIZE, new NonNegativeConstraint(false));
Assert.assertEquals(2.0, solution.getPoint()[0], 0.0);
Assert.assertEquals(2.0, solution.getPoint()[1], 0.0);
Assert.assertEquals(50.0, solution.getValue(), 0.0);
}
@Test
public void testMinimization() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { -2, 1 }, -5);
Collection<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] { 1, 2 }, Relationship.LEQ, 6));
constraints.add(new LinearConstraint(new double[] { 3, 2 }, Relationship.LEQ, 12));
constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.GEQ, 0));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MINIMIZE, new NonNegativeConstraint(false));
Assert.assertEquals(4.0, solution.getPoint()[0], 0.0);
Assert.assertEquals(0.0, solution.getPoint()[1], 0.0);
Assert.assertEquals(-13.0, solution.getValue(), 0.0);
}
@Test
public void testSolutionWithNegativeDecisionVariable() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { -2, 1 }, 0);
Collection<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.GEQ, 6));
constraints.add(new LinearConstraint(new double[] { 1, 2 }, Relationship.LEQ, 14));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MAXIMIZE, new NonNegativeConstraint(false));
Assert.assertEquals(-2.0, solution.getPoint()[0], 0.0);
Assert.assertEquals(8.0, solution.getPoint()[1], 0.0);
Assert.assertEquals(12.0, solution.getValue(), 0.0);
}
@Test(expected = NoFeasibleSolutionException.class)
public void testInfeasibleSolution() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15 }, 0);
Collection<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] { 1 }, Relationship.LEQ, 1));
constraints.add(new LinearConstraint(new double[] { 1 }, Relationship.GEQ, 3));
SimplexSolver solver = new SimplexSolver();
solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MAXIMIZE, new NonNegativeConstraint(false));
}
@Test(expected = UnboundedSolutionException.class)
public void testUnboundedSolution() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15, 10 }, 0);
Collection<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.EQ, 2));
SimplexSolver solver = new SimplexSolver();
solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MAXIMIZE, new NonNegativeConstraint(false));
}
@Test
public void testRestrictVariablesToNonNegative() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 409, 523, 70, 204, 339 }, 0);
Collection<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] { 43, 56, 345, 56, 5 }, Relationship.LEQ, 4567456));
constraints.add(new LinearConstraint(new double[] { 12, 45, 7, 56, 23 }, Relationship.LEQ, 56454));
constraints.add(new LinearConstraint(new double[] { 8, 768, 0, 34, 7456 }, Relationship.LEQ, 1923421));
constraints.add(new LinearConstraint(new double[] { 12342, 2342, 34, 678, 2342 }, Relationship.GEQ, 4356));
constraints.add(new LinearConstraint(new double[] { 45, 678, 76, 52, 23 }, Relationship.EQ, 456356));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MAXIMIZE, new NonNegativeConstraint(true));
Assert.assertEquals(2902.92783505155, solution.getPoint()[0], .0000001);
Assert.assertEquals(480.419243986254, solution.getPoint()[1], .0000001);
Assert.assertEquals(0.0, solution.getPoint()[2], .0000001);
Assert.assertEquals(0.0, solution.getPoint()[3], .0000001);
Assert.assertEquals(0.0, solution.getPoint()[4], .0000001);
Assert.assertEquals(1438556.7491409, solution.getValue(), .0000001);
}
@Test
public void testEpsilon() {
LinearObjectiveFunction f =
new LinearObjectiveFunction(new double[] { 10, 5, 1 }, 0);
Collection<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] { 9, 8, 0 }, Relationship.EQ, 17));
constraints.add(new LinearConstraint(new double[] { 0, 7, 8 }, Relationship.LEQ, 7));
constraints.add(new LinearConstraint(new double[] { 10, 0, 2 }, Relationship.LEQ, 10));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MAXIMIZE, new NonNegativeConstraint(false));
Assert.assertEquals(1.0, solution.getPoint()[0], 0.0);
Assert.assertEquals(1.0, solution.getPoint()[1], 0.0);
Assert.assertEquals(0.0, solution.getPoint()[2], 0.0);
Assert.assertEquals(15.0, solution.getValue(), 0.0);
}
@Test
public void testTrivialModel() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 1, 1 }, 0);
Collection<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.EQ, 0));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MAXIMIZE, new NonNegativeConstraint(true));
Assert.assertEquals(0, solution.getValue(), .0000001);
}
@Test
public void testLargeModel() {
double[] objective = new double[] {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 12, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
12, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 12, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 12, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 12, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 12, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1};
LinearObjectiveFunction f = new LinearObjectiveFunction(objective, 0);
Collection<LinearConstraint> constraints = new ArrayList<>();
constraints.add(equationFromString(objective.length, "x0 + x1 + x2 + x3 - x12 = 0"));
constraints.add(equationFromString(objective.length, "x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 - x13 = 0"));
constraints.add(equationFromString(objective.length, "x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 >= 49"));
constraints.add(equationFromString(objective.length, "x0 + x1 + x2 + x3 >= 42"));
constraints.add(equationFromString(objective.length, "x14 + x15 + x16 + x17 - x26 = 0"));
constraints.add(equationFromString(objective.length, "x18 + x19 + x20 + x21 + x22 + x23 + x24 + x25 - x27 = 0"));
constraints.add(equationFromString(objective.length, "x14 + x15 + x16 + x17 - x12 = 0"));
constraints.add(equationFromString(objective.length, "x18 + x19 + x20 + x21 + x22 + x23 + x24 + x25 - x13 = 0"));
constraints.add(equationFromString(objective.length, "x28 + x29 + x30 + x31 - x40 = 0"));
constraints.add(equationFromString(objective.length, "x32 + x33 + x34 + x35 + x36 + x37 + x38 + x39 - x41 = 0"));
constraints.add(equationFromString(objective.length, "x32 + x33 + x34 + x35 + x36 + x37 + x38 + x39 >= 49"));
constraints.add(equationFromString(objective.length, "x28 + x29 + x30 + x31 >= 42"));
constraints.add(equationFromString(objective.length, "x42 + x43 + x44 + x45 - x54 = 0"));
constraints.add(equationFromString(objective.length, "x46 + x47 + x48 + x49 + x50 + x51 + x52 + x53 - x55 = 0"));
constraints.add(equationFromString(objective.length, "x42 + x43 + x44 + x45 - x40 = 0"));
constraints.add(equationFromString(objective.length, "x46 + x47 + x48 + x49 + x50 + x51 + x52 + x53 - x41 = 0"));
constraints.add(equationFromString(objective.length, "x56 + x57 + x58 + x59 - x68 = 0"));
constraints.add(equationFromString(objective.length, "x60 + x61 + x62 + x63 + x64 + x65 + x66 + x67 - x69 = 0"));
constraints.add(equationFromString(objective.length, "x60 + x61 + x62 + x63 + x64 + x65 + x66 + x67 >= 51"));
constraints.add(equationFromString(objective.length, "x56 + x57 + x58 + x59 >= 44"));
constraints.add(equationFromString(objective.length, "x70 + x71 + x72 + x73 - x82 = 0"));
constraints.add(equationFromString(objective.length, "x74 + x75 + x76 + x77 + x78 + x79 + x80 + x81 - x83 = 0"));
constraints.add(equationFromString(objective.length, "x70 + x71 + x72 + x73 - x68 = 0"));
constraints.add(equationFromString(objective.length, "x74 + x75 + x76 + x77 + x78 + x79 + x80 + x81 - x69 = 0"));
constraints.add(equationFromString(objective.length, "x84 + x85 + x86 + x87 - x96 = 0"));
constraints.add(equationFromString(objective.length, "x88 + x89 + x90 + x91 + x92 + x93 + x94 + x95 - x97 = 0"));
constraints.add(equationFromString(objective.length, "x88 + x89 + x90 + x91 + x92 + x93 + x94 + x95 >= 51"));
constraints.add(equationFromString(objective.length, "x84 + x85 + x86 + x87 >= 44"));
constraints.add(equationFromString(objective.length, "x98 + x99 + x100 + x101 - x110 = 0"));
constraints.add(equationFromString(objective.length, "x102 + x103 + x104 + x105 + x106 + x107 + x108 + x109 - x111 = 0"));
constraints.add(equationFromString(objective.length, "x98 + x99 + x100 + x101 - x96 = 0"));
constraints.add(equationFromString(objective.length, "x102 + x103 + x104 + x105 + x106 + x107 + x108 + x109 - x97 = 0"));
constraints.add(equationFromString(objective.length, "x112 + x113 + x114 + x115 - x124 = 0"));
constraints.add(equationFromString(objective.length, "x116 + x117 + x118 + x119 + x120 + x121 + x122 + x123 - x125 = 0"));
constraints.add(equationFromString(objective.length, "x116 + x117 + x118 + x119 + x120 + x121 + x122 + x123 >= 49"));
constraints.add(equationFromString(objective.length, "x112 + x113 + x114 + x115 >= 42"));
constraints.add(equationFromString(objective.length, "x126 + x127 + x128 + x129 - x138 = 0"));
constraints.add(equationFromString(objective.length, "x130 + x131 + x132 + x133 + x134 + x135 + x136 + x137 - x139 = 0"));
constraints.add(equationFromString(objective.length, "x126 + x127 + x128 + x129 - x124 = 0"));
constraints.add(equationFromString(objective.length, "x130 + x131 + x132 + x133 + x134 + x135 + x136 + x137 - x125 = 0"));
constraints.add(equationFromString(objective.length, "x140 + x141 + x142 + x143 - x152 = 0"));
constraints.add(equationFromString(objective.length, "x144 + x145 + x146 + x147 + x148 + x149 + x150 + x151 - x153 = 0"));
constraints.add(equationFromString(objective.length, "x144 + x145 + x146 + x147 + x148 + x149 + x150 + x151 >= 59"));
constraints.add(equationFromString(objective.length, "x140 + x141 + x142 + x143 >= 42"));
constraints.add(equationFromString(objective.length, "x154 + x155 + x156 + x157 - x166 = 0"));
constraints.add(equationFromString(objective.length, "x158 + x159 + x160 + x161 + x162 + x163 + x164 + x165 - x167 = 0"));
constraints.add(equationFromString(objective.length, "x154 + x155 + x156 + x157 - x152 = 0"));
constraints.add(equationFromString(objective.length, "x158 + x159 + x160 + x161 + x162 + x163 + x164 + x165 - x153 = 0"));
constraints.add(equationFromString(objective.length, "x83 + x82 - x168 = 0"));
constraints.add(equationFromString(objective.length, "x111 + x110 - x169 = 0"));
constraints.add(equationFromString(objective.length, "x170 - x182 = 0"));
constraints.add(equationFromString(objective.length, "x171 - x183 = 0"));
constraints.add(equationFromString(objective.length, "x172 - x184 = 0"));
constraints.add(equationFromString(objective.length, "x173 - x185 = 0"));
constraints.add(equationFromString(objective.length, "x174 - x186 = 0"));
constraints.add(equationFromString(objective.length, "x175 + x176 - x187 = 0"));
constraints.add(equationFromString(objective.length, "x177 - x188 = 0"));
constraints.add(equationFromString(objective.length, "x178 - x189 = 0"));
constraints.add(equationFromString(objective.length, "x179 - x190 = 0"));
constraints.add(equationFromString(objective.length, "x180 - x191 = 0"));
constraints.add(equationFromString(objective.length, "x181 - x192 = 0"));
constraints.add(equationFromString(objective.length, "x170 - x26 = 0"));
constraints.add(equationFromString(objective.length, "x171 - x27 = 0"));
constraints.add(equationFromString(objective.length, "x172 - x54 = 0"));
constraints.add(equationFromString(objective.length, "x173 - x55 = 0"));
constraints.add(equationFromString(objective.length, "x174 - x168 = 0"));
constraints.add(equationFromString(objective.length, "x177 - x169 = 0"));
constraints.add(equationFromString(objective.length, "x178 - x138 = 0"));
constraints.add(equationFromString(objective.length, "x179 - x139 = 0"));
constraints.add(equationFromString(objective.length, "x180 - x166 = 0"));
constraints.add(equationFromString(objective.length, "x181 - x167 = 0"));
constraints.add(equationFromString(objective.length, "x193 - x205 = 0"));
constraints.add(equationFromString(objective.length, "x194 - x206 = 0"));
constraints.add(equationFromString(objective.length, "x195 - x207 = 0"));
constraints.add(equationFromString(objective.length, "x196 - x208 = 0"));
constraints.add(equationFromString(objective.length, "x197 - x209 = 0"));
constraints.add(equationFromString(objective.length, "x198 + x199 - x210 = 0"));
constraints.add(equationFromString(objective.length, "x200 - x211 = 0"));
constraints.add(equationFromString(objective.length, "x201 - x212 = 0"));
constraints.add(equationFromString(objective.length, "x202 - x213 = 0"));
constraints.add(equationFromString(objective.length, "x203 - x214 = 0"));
constraints.add(equationFromString(objective.length, "x204 - x215 = 0"));
constraints.add(equationFromString(objective.length, "x193 - x182 = 0"));
constraints.add(equationFromString(objective.length, "x194 - x183 = 0"));
constraints.add(equationFromString(objective.length, "x195 - x184 = 0"));
constraints.add(equationFromString(objective.length, "x196 - x185 = 0"));
constraints.add(equationFromString(objective.length, "x197 - x186 = 0"));
constraints.add(equationFromString(objective.length, "x198 + x199 - x187 = 0"));
constraints.add(equationFromString(objective.length, "x200 - x188 = 0"));
constraints.add(equationFromString(objective.length, "x201 - x189 = 0"));
constraints.add(equationFromString(objective.length, "x202 - x190 = 0"));
constraints.add(equationFromString(objective.length, "x203 - x191 = 0"));
constraints.add(equationFromString(objective.length, "x204 - x192 = 0"));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MINIMIZE, new NonNegativeConstraint(true));
Assert.assertEquals(7518.0, solution.getValue(), .0000001);
}
@Test
public void testSolutionCallback() {
// re-use the problem from testcase for MATH-288
// it normally requires 5 iterations
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 7, 3, 0, 0 }, 0 );
List<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] { 3, 0, -5, 0 }, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] { 2, 0, 0, -5 }, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] { 0, 3, 0, -5 }, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] { 1, 0, 0, 0 }, Relationship.LEQ, 1.0));
constraints.add(new LinearConstraint(new double[] { 0, 1, 0, 0 }, Relationship.LEQ, 1.0));
final SimplexSolver solver = new SimplexSolver();
final SolutionCallback callback = new SolutionCallback();
Assert.assertNull(callback.getSolution());
Assert.assertFalse(callback.isSolutionOptimal());
try {
solver.optimize(new MaxIter(4), f, new LinearConstraintSet(constraints),
GoalType.MAXIMIZE, new NonNegativeConstraint(true), callback);
Assert.fail("expected TooManyIterationsException");
} catch (TooManyIterationsException ex) {
// expected
}
final PointValuePair solution = callback.getSolution();
Assert.assertNotNull(solution);
Assert.assertTrue(validSolution(solution, constraints, 1e-4));
Assert.assertFalse(callback.isSolutionOptimal());
// the solution is clearly not optimal: optimal = 10.0
Assert.assertEquals(7.0, solution.getValue(), 1e-4);
}
@Test(expected=DimensionMismatchException.class)
public void testDimensionMatch() {
// min 2x1 +15x2 +18x3
// Subject to
// -x1 +2x2 -6x3 <=-10
// x2 +2x3 <= 6
// 2x1 +10x3 <= 19
// -x1 +x2 <= -2
// x1,x2,x3 >= 0
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 2, 15, 18 }, 0);
Collection<LinearConstraint> constraints = new ArrayList<>();
// this constraint is wrong, the dimension is less than expected one
constraints.add(new LinearConstraint(new double[] { -1, 2 - 6 }, Relationship.LEQ, -10));
constraints.add(new LinearConstraint(new double[] { 0, 1, 2 }, Relationship.LEQ, 6));
constraints.add(new LinearConstraint(new double[] { 2, 0, 10 }, Relationship.LEQ, 19));
constraints.add(new LinearConstraint(new double[] { -1, 1, 0 }, Relationship.LEQ, -2));
SimplexSolver solver = new SimplexSolver();
solver.optimize(f,
new LinearConstraintSet(constraints),
new NonNegativeConstraint(true),
PivotSelectionRule.BLAND);
}
/* XXX Skipped until issue is solved: https://issues.apache.org/jira/browse/MATH-1549 */
@Ignore@Test
public void testMath1549() {
final double m = 10;
double scale = 1;
int numFailures = 0;
for (int pow = 0; pow < 13; pow++) {
try {
tryMath1549(scale);
} catch (RuntimeException e) {
e.printStackTrace();
++numFailures;
}
scale *= m;
}
if (numFailures > 0) {
Assert.fail(numFailures + " failures");
}
}
/* See JIRA issue: MATH-1549 */
private void tryMath1549(double scale) {
final NonNegativeConstraint nnegconstr = new NonNegativeConstraint(true);
final int ulps = 10;
final double cutoff = 1e-10;
final double eps = 1e-6;
final SimplexSolver solver = new SimplexSolver(eps, ulps, cutoff);
final LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] {1, 1}, 0);
final List<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] {scale * 9000, scale * 1}, Relationship.GEQ, 0));
constraints.add(new LinearConstraint(new double[] {scale * 10000, scale}, Relationship.GEQ, scale * 2000));
constraints.add(new LinearConstraint(new double[] {scale, 0}, Relationship.GEQ, scale * 2));
final LinearConstraintSet constraintSet = new LinearConstraintSet(constraints);
final PointValuePair solution = solver.optimize(f, constraintSet, GoalType.MINIMIZE, nnegconstr);
System.out.println("scale=" + scale + ": sol=" + java.util.Arrays.toString(solution.getPoint()));
}
/**
* Converts a test string to a {@link LinearConstraint}.
* Ex: x0 + x1 + x2 + x3 - x12 = 0
*/
private LinearConstraint equationFromString(int numCoefficients, String s) {
Relationship relationship;
if (s.contains(">=")) {
relationship = Relationship.GEQ;
} else if (s.contains("<=")) {
relationship = Relationship.LEQ;
} else if (s.contains("=")) {
relationship = Relationship.EQ;
} else {
throw new IllegalArgumentException();
}
String[] equationParts = s.split("[>|<]?=");
double rhs = Double.parseDouble(equationParts[1].trim());
double[] lhs = new double[numCoefficients];
String left = equationParts[0].replaceAll(" ?x", "");
String[] coefficients = left.split(" ");
for (String coefficient : coefficients) {
double value = coefficient.charAt(0) == '-' ? -1 : 1;
int index = Integer.parseInt(coefficient.replaceFirst("[+|-]", "").trim());
lhs[index] = value;
}
return new LinearConstraint(lhs, relationship, rhs);
}
private static boolean validSolution(PointValuePair solution, List<LinearConstraint> constraints, double epsilon) {
double[] vals = solution.getPoint();
for (LinearConstraint c : constraints) {
double[] coeffs = c.getCoefficients().toArray();
double result = 0.0d;
for (int i = 0; i < vals.length; i++) {
result += vals[i] * coeffs[i];
}
switch (c.getRelationship()) {
case EQ:
if (!Precision.equals(result, c.getValue(), epsilon)) {
return false;
}
break;
case GEQ:
if (Precision.compareTo(result, c.getValue(), epsilon) < 0) {
return false;
}
break;
case LEQ:
if (Precision.compareTo(result, c.getValue(), epsilon) > 0) {
return false;
}
break;
}
}
return true;
}
}
|
src/test/java/org/apache/commons/math4/optim/linear/SimplexSolverTest.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.commons.math4.optim.linear;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.commons.math4.exception.DimensionMismatchException;
import org.apache.commons.math4.exception.TooManyIterationsException;
import org.apache.commons.math4.optim.MaxIter;
import org.apache.commons.math4.optim.PointValuePair;
import org.apache.commons.math4.optim.linear.LinearConstraint;
import org.apache.commons.math4.optim.linear.LinearConstraintSet;
import org.apache.commons.math4.optim.linear.LinearObjectiveFunction;
import org.apache.commons.math4.optim.linear.NoFeasibleSolutionException;
import org.apache.commons.math4.optim.linear.NonNegativeConstraint;
import org.apache.commons.math4.optim.linear.PivotSelectionRule;
import org.apache.commons.math4.optim.linear.Relationship;
import org.apache.commons.math4.optim.linear.SimplexSolver;
import org.apache.commons.math4.optim.linear.SolutionCallback;
import org.apache.commons.math4.optim.linear.UnboundedSolutionException;
import org.apache.commons.math4.optim.nonlinear.scalar.GoalType;
import org.apache.commons.numbers.core.Precision;
import org.junit.Test;
import org.junit.Assert;
public class SimplexSolverTest {
private static final MaxIter DEFAULT_MAX_ITER = new MaxIter(100);
@Test
public void testMath842Cycle() {
// from http://www.math.toronto.edu/mpugh/Teaching/APM236_04/bland
// maximize 10 x1 - 57 x2 - 9 x3 - 24 x4
// subject to
// 1/2 x1 - 11/2 x2 - 5/2 x3 + 9 x4 <= 0
// 1/2 x1 - 3/2 x2 - 1/2 x3 + x4 <= 0
// x1 <= 1
// x1,x2,x3,x4 >= 0
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 10, -57, -9, -24}, 0);
ArrayList<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] {0.5, -5.5, -2.5, 9}, Relationship.LEQ, 0));
constraints.add(new LinearConstraint(new double[] {0.5, -1.5, -0.5, 1}, Relationship.LEQ, 0));
constraints.add(new LinearConstraint(new double[] { 1, 0, 0, 0}, Relationship.LEQ, 1));
double epsilon = 1e-6;
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(f, new LinearConstraintSet(constraints),
GoalType.MAXIMIZE,
new NonNegativeConstraint(true),
PivotSelectionRule.BLAND);
Assert.assertEquals(1.0d, solution.getValue(), epsilon);
Assert.assertTrue(validSolution(solution, constraints, epsilon));
}
@Test
public void testMath828() {
LinearObjectiveFunction f = new LinearObjectiveFunction(
new double[] { 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, 0.0);
ArrayList <LinearConstraint>constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] {0.0, 39.0, 23.0, 96.0, 15.0, 48.0, 9.0, 21.0, 48.0, 36.0, 76.0, 19.0, 88.0, 17.0, 16.0, 36.0,}, Relationship.GEQ, 15.0));
constraints.add(new LinearConstraint(new double[] {0.0, 59.0, 93.0, 12.0, 29.0, 78.0, 73.0, 87.0, 32.0, 70.0, 68.0, 24.0, 11.0, 26.0, 65.0, 25.0,}, Relationship.GEQ, 29.0));
constraints.add(new LinearConstraint(new double[] {0.0, 74.0, 5.0, 82.0, 6.0, 97.0, 55.0, 44.0, 52.0, 54.0, 5.0, 93.0, 91.0, 8.0, 20.0, 97.0,}, Relationship.GEQ, 6.0));
constraints.add(new LinearConstraint(new double[] {8.0, -3.0, -28.0, -72.0, -8.0, -31.0, -31.0, -74.0, -47.0, -59.0, -24.0, -57.0, -56.0, -16.0, -92.0, -59.0,}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {25.0, -7.0, -99.0, -78.0, -25.0, -14.0, -16.0, -89.0, -39.0, -56.0, -53.0, -9.0, -18.0, -26.0, -11.0, -61.0,}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {33.0, -95.0, -15.0, -4.0, -33.0, -3.0, -20.0, -96.0, -27.0, -13.0, -80.0, -24.0, -3.0, -13.0, -57.0, -76.0,}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {7.0, -95.0, -39.0, -93.0, -7.0, -94.0, -94.0, -62.0, -76.0, -26.0, -53.0, -57.0, -31.0, -76.0, -53.0, -52.0,}, Relationship.GEQ, 0.0));
double epsilon = 1e-6;
PointValuePair solution = new SimplexSolver().optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MINIMIZE, new NonNegativeConstraint(true));
Assert.assertEquals(1.0d, solution.getValue(), epsilon);
Assert.assertTrue(validSolution(solution, constraints, epsilon));
}
@Test
public void testMath828Cycle() {
LinearObjectiveFunction f = new LinearObjectiveFunction(
new double[] { 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, 0.0);
ArrayList <LinearConstraint>constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] {0.0, 16.0, 14.0, 69.0, 1.0, 85.0, 52.0, 43.0, 64.0, 97.0, 14.0, 74.0, 89.0, 28.0, 94.0, 58.0, 13.0, 22.0, 21.0, 17.0, 30.0, 25.0, 1.0, 59.0, 91.0, 78.0, 12.0, 74.0, 56.0, 3.0, 88.0,}, Relationship.GEQ, 91.0));
constraints.add(new LinearConstraint(new double[] {0.0, 60.0, 40.0, 81.0, 71.0, 72.0, 46.0, 45.0, 38.0, 48.0, 40.0, 17.0, 33.0, 85.0, 64.0, 32.0, 84.0, 3.0, 54.0, 44.0, 71.0, 67.0, 90.0, 95.0, 54.0, 99.0, 99.0, 29.0, 52.0, 98.0, 9.0,}, Relationship.GEQ, 54.0));
constraints.add(new LinearConstraint(new double[] {0.0, 41.0, 12.0, 86.0, 90.0, 61.0, 31.0, 41.0, 23.0, 89.0, 17.0, 74.0, 44.0, 27.0, 16.0, 47.0, 80.0, 32.0, 11.0, 56.0, 68.0, 82.0, 11.0, 62.0, 62.0, 53.0, 39.0, 16.0, 48.0, 1.0, 63.0,}, Relationship.GEQ, 62.0));
constraints.add(new LinearConstraint(new double[] {83.0, -76.0, -94.0, -19.0, -15.0, -70.0, -72.0, -57.0, -63.0, -65.0, -22.0, -94.0, -22.0, -88.0, -86.0, -89.0, -72.0, -16.0, -80.0, -49.0, -70.0, -93.0, -95.0, -17.0, -83.0, -97.0, -31.0, -47.0, -31.0, -13.0, -23.0,}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {41.0, -96.0, -41.0, -48.0, -70.0, -43.0, -43.0, -43.0, -97.0, -37.0, -85.0, -70.0, -45.0, -67.0, -87.0, -69.0, -94.0, -54.0, -54.0, -92.0, -79.0, -10.0, -35.0, -20.0, -41.0, -41.0, -65.0, -25.0, -12.0, -8.0, -46.0,}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {27.0, -42.0, -65.0, -49.0, -53.0, -42.0, -17.0, -2.0, -61.0, -31.0, -76.0, -47.0, -8.0, -93.0, -86.0, -62.0, -65.0, -63.0, -22.0, -43.0, -27.0, -23.0, -32.0, -74.0, -27.0, -63.0, -47.0, -78.0, -29.0, -95.0, -73.0,}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {15.0, -46.0, -41.0, -83.0, -98.0, -99.0, -21.0, -35.0, -7.0, -14.0, -80.0, -63.0, -18.0, -42.0, -5.0, -34.0, -56.0, -70.0, -16.0, -18.0, -74.0, -61.0, -47.0, -41.0, -15.0, -79.0, -18.0, -47.0, -88.0, -68.0, -55.0,}, Relationship.GEQ, 0.0));
double epsilon = 1e-6;
PointValuePair solution = new SimplexSolver().optimize(DEFAULT_MAX_ITER, f,
new LinearConstraintSet(constraints),
GoalType.MINIMIZE, new NonNegativeConstraint(true),
PivotSelectionRule.BLAND);
Assert.assertEquals(1.0d, solution.getValue(), epsilon);
Assert.assertTrue(validSolution(solution, constraints, epsilon));
}
@Test
public void testMath781() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 2, 6, 7 }, 0);
ArrayList<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] { 1, 2, 1 }, Relationship.LEQ, 2));
constraints.add(new LinearConstraint(new double[] { -1, 1, 1 }, Relationship.LEQ, -1));
constraints.add(new LinearConstraint(new double[] { 2, -3, 1 }, Relationship.LEQ, -1));
double epsilon = 1e-6;
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MAXIMIZE, new NonNegativeConstraint(false));
Assert.assertTrue(Precision.compareTo(solution.getPoint()[0], 0.0d, epsilon) > 0);
Assert.assertTrue(Precision.compareTo(solution.getPoint()[1], 0.0d, epsilon) > 0);
Assert.assertTrue(Precision.compareTo(solution.getPoint()[2], 0.0d, epsilon) < 0);
Assert.assertEquals(2.0d, solution.getValue(), epsilon);
}
@Test
public void testMath713NegativeVariable() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] {1.0, 1.0}, 0.0d);
ArrayList<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] {1, 0}, Relationship.EQ, 1));
double epsilon = 1e-6;
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MINIMIZE, new NonNegativeConstraint(true));
Assert.assertTrue(Precision.compareTo(solution.getPoint()[0], 0.0d, epsilon) >= 0);
Assert.assertTrue(Precision.compareTo(solution.getPoint()[1], 0.0d, epsilon) >= 0);
}
@Test
public void testMath434NegativeVariable() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] {0.0, 0.0, 1.0}, 0.0d);
ArrayList<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] {1, 1, 0}, Relationship.EQ, 5));
constraints.add(new LinearConstraint(new double[] {0, 0, 1}, Relationship.GEQ, -10));
double epsilon = 1e-6;
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MINIMIZE, new NonNegativeConstraint(false));
Assert.assertEquals(5.0, solution.getPoint()[0] + solution.getPoint()[1], epsilon);
Assert.assertEquals(-10.0, solution.getPoint()[2], epsilon);
Assert.assertEquals(-10.0, solution.getValue(), epsilon);
}
@Test(expected = NoFeasibleSolutionException.class)
public void testMath434UnfeasibleSolution() {
double epsilon = 1e-6;
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] {1.0, 0.0}, 0.0);
ArrayList<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] {epsilon/2, 0.5}, Relationship.EQ, 0));
constraints.add(new LinearConstraint(new double[] {1e-3, 0.1}, Relationship.EQ, 10));
SimplexSolver solver = new SimplexSolver();
// allowing only non-negative values, no feasible solution shall be found
solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MINIMIZE, new NonNegativeConstraint(true));
}
@Test
public void testMath434PivotRowSelection() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] {1.0}, 0.0);
double epsilon = 1e-6;
ArrayList<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] {200}, Relationship.GEQ, 1));
constraints.add(new LinearConstraint(new double[] {100}, Relationship.GEQ, 0.499900001));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MINIMIZE, new NonNegativeConstraint(false));
Assert.assertTrue(Precision.compareTo(solution.getPoint()[0] * 200.d, 1.d, epsilon) >= 0);
Assert.assertEquals(0.0050, solution.getValue(), epsilon);
}
@Test
public void testMath434PivotRowSelection2() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] {0.0d, 1.0d, 1.0d, 0.0d, 0.0d, 0.0d, 0.0d}, 0.0d);
ArrayList<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] {1.0d, -0.1d, 0.0d, 0.0d, 0.0d, 0.0d, 0.0d}, Relationship.EQ, -0.1d));
constraints.add(new LinearConstraint(new double[] {1.0d, 0.0d, 0.0d, 0.0d, 0.0d, 0.0d, 0.0d}, Relationship.GEQ, -1e-18d));
constraints.add(new LinearConstraint(new double[] {0.0d, 1.0d, 0.0d, 0.0d, 0.0d, 0.0d, 0.0d}, Relationship.GEQ, 0.0d));
constraints.add(new LinearConstraint(new double[] {0.0d, 0.0d, 0.0d, 1.0d, 0.0d, -0.0128588d, 1e-5d}, Relationship.EQ, 0.0d));
constraints.add(new LinearConstraint(new double[] {0.0d, 0.0d, 0.0d, 0.0d, 1.0d, 1e-5d, -0.0128586d}, Relationship.EQ, 1e-10d));
constraints.add(new LinearConstraint(new double[] {0.0d, 0.0d, 1.0d, -1.0d, 0.0d, 0.0d, 0.0d}, Relationship.GEQ, 0.0d));
constraints.add(new LinearConstraint(new double[] {0.0d, 0.0d, 1.0d, 1.0d, 0.0d, 0.0d, 0.0d}, Relationship.GEQ, 0.0d));
constraints.add(new LinearConstraint(new double[] {0.0d, 0.0d, 1.0d, 0.0d, -1.0d, 0.0d, 0.0d}, Relationship.GEQ, 0.0d));
constraints.add(new LinearConstraint(new double[] {0.0d, 0.0d, 1.0d, 0.0d, 1.0d, 0.0d, 0.0d}, Relationship.GEQ, 0.0d));
double epsilon = 1e-7;
SimplexSolver simplex = new SimplexSolver();
PointValuePair solution = simplex.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MINIMIZE, new NonNegativeConstraint(false));
Assert.assertTrue(Precision.compareTo(solution.getPoint()[0], -1e-18d, epsilon) >= 0);
Assert.assertEquals(1.0d, solution.getPoint()[1], epsilon);
Assert.assertEquals(0.0d, solution.getPoint()[2], epsilon);
Assert.assertEquals(1.0d, solution.getValue(), epsilon);
}
@Test
public void testMath272() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 2, 2, 1 }, 0);
Collection<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] { 1, 1, 0 }, Relationship.GEQ, 1));
constraints.add(new LinearConstraint(new double[] { 1, 0, 1 }, Relationship.GEQ, 1));
constraints.add(new LinearConstraint(new double[] { 0, 1, 0 }, Relationship.GEQ, 1));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MINIMIZE, new NonNegativeConstraint(true));
Assert.assertEquals(0.0, solution.getPoint()[0], .0000001);
Assert.assertEquals(1.0, solution.getPoint()[1], .0000001);
Assert.assertEquals(1.0, solution.getPoint()[2], .0000001);
Assert.assertEquals(3.0, solution.getValue(), .0000001);
}
@Test
public void testMath286() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 0.8, 0.2, 0.7, 0.3, 0.6, 0.4 }, 0 );
Collection<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] { 1, 0, 1, 0, 1, 0 }, Relationship.EQ, 23.0));
constraints.add(new LinearConstraint(new double[] { 0, 1, 0, 1, 0, 1 }, Relationship.EQ, 23.0));
constraints.add(new LinearConstraint(new double[] { 1, 0, 0, 0, 0, 0 }, Relationship.GEQ, 10.0));
constraints.add(new LinearConstraint(new double[] { 0, 0, 1, 0, 0, 0 }, Relationship.GEQ, 8.0));
constraints.add(new LinearConstraint(new double[] { 0, 0, 0, 0, 1, 0 }, Relationship.GEQ, 5.0));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MAXIMIZE, new NonNegativeConstraint(true));
Assert.assertEquals(25.8, solution.getValue(), .0000001);
Assert.assertEquals(23.0, solution.getPoint()[0] + solution.getPoint()[2] + solution.getPoint()[4], 0.0000001);
Assert.assertEquals(23.0, solution.getPoint()[1] + solution.getPoint()[3] + solution.getPoint()[5], 0.0000001);
Assert.assertTrue(solution.getPoint()[0] >= 10.0 - 0.0000001);
Assert.assertTrue(solution.getPoint()[2] >= 8.0 - 0.0000001);
Assert.assertTrue(solution.getPoint()[4] >= 5.0 - 0.0000001);
}
@Test
public void testDegeneracy() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 0.8, 0.7 }, 0 );
Collection<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.LEQ, 18.0));
constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.GEQ, 10.0));
constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.GEQ, 8.0));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MINIMIZE, new NonNegativeConstraint(true));
Assert.assertEquals(13.6, solution.getValue(), .0000001);
}
@Test
public void testMath288() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 7, 3, 0, 0 }, 0 );
Collection<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] { 3, 0, -5, 0 }, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] { 2, 0, 0, -5 }, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] { 0, 3, 0, -5 }, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] { 1, 0, 0, 0 }, Relationship.LEQ, 1.0));
constraints.add(new LinearConstraint(new double[] { 0, 1, 0, 0 }, Relationship.LEQ, 1.0));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MAXIMIZE, new NonNegativeConstraint(true));
Assert.assertEquals(10.0, solution.getValue(), .0000001);
}
@Test
public void testMath290GEQ() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 1, 5 }, 0 );
Collection<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] { 2, 0 }, Relationship.GEQ, -1.0));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MINIMIZE, new NonNegativeConstraint(true));
Assert.assertEquals(0, solution.getValue(), .0000001);
Assert.assertEquals(0, solution.getPoint()[0], .0000001);
Assert.assertEquals(0, solution.getPoint()[1], .0000001);
}
@Test(expected=NoFeasibleSolutionException.class)
public void testMath290LEQ() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 1, 5 }, 0 );
Collection<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] { 2, 0 }, Relationship.LEQ, -1.0));
SimplexSolver solver = new SimplexSolver();
solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MINIMIZE, new NonNegativeConstraint(true));
}
@Test
public void testMath293() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 0.8, 0.2, 0.7, 0.3, 0.4, 0.6}, 0 );
Collection<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] { 1, 0, 1, 0, 1, 0 }, Relationship.EQ, 30.0));
constraints.add(new LinearConstraint(new double[] { 0, 1, 0, 1, 0, 1 }, Relationship.EQ, 30.0));
constraints.add(new LinearConstraint(new double[] { 0.8, 0.2, 0.0, 0.0, 0.0, 0.0 }, Relationship.GEQ, 10.0));
constraints.add(new LinearConstraint(new double[] { 0.0, 0.0, 0.7, 0.3, 0.0, 0.0 }, Relationship.GEQ, 10.0));
constraints.add(new LinearConstraint(new double[] { 0.0, 0.0, 0.0, 0.0, 0.4, 0.6 }, Relationship.GEQ, 10.0));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution1 = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MAXIMIZE, new NonNegativeConstraint(true));
Assert.assertEquals(15.7143, solution1.getPoint()[0], .0001);
Assert.assertEquals(0.0, solution1.getPoint()[1], .0001);
Assert.assertEquals(14.2857, solution1.getPoint()[2], .0001);
Assert.assertEquals(0.0, solution1.getPoint()[3], .0001);
Assert.assertEquals(0.0, solution1.getPoint()[4], .0001);
Assert.assertEquals(30.0, solution1.getPoint()[5], .0001);
Assert.assertEquals(40.57143, solution1.getValue(), .0001);
double valA = 0.8 * solution1.getPoint()[0] + 0.2 * solution1.getPoint()[1];
double valB = 0.7 * solution1.getPoint()[2] + 0.3 * solution1.getPoint()[3];
double valC = 0.4 * solution1.getPoint()[4] + 0.6 * solution1.getPoint()[5];
f = new LinearObjectiveFunction(new double[] { 0.8, 0.2, 0.7, 0.3, 0.4, 0.6}, 0 );
constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] { 1, 0, 1, 0, 1, 0 }, Relationship.EQ, 30.0));
constraints.add(new LinearConstraint(new double[] { 0, 1, 0, 1, 0, 1 }, Relationship.EQ, 30.0));
constraints.add(new LinearConstraint(new double[] { 0.8, 0.2, 0.0, 0.0, 0.0, 0.0 }, Relationship.GEQ, valA));
constraints.add(new LinearConstraint(new double[] { 0.0, 0.0, 0.7, 0.3, 0.0, 0.0 }, Relationship.GEQ, valB));
constraints.add(new LinearConstraint(new double[] { 0.0, 0.0, 0.0, 0.0, 0.4, 0.6 }, Relationship.GEQ, valC));
PointValuePair solution2 = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MAXIMIZE, new NonNegativeConstraint(true));
Assert.assertEquals(40.57143, solution2.getValue(), .0001);
}
@Test
public void testMath930() {
Collection<LinearConstraint> constraints = createMath930Constraints();
double[] objFunctionCoeff = new double[33];
objFunctionCoeff[3] = 1;
LinearObjectiveFunction f = new LinearObjectiveFunction(objFunctionCoeff, 0);
SimplexSolver solver = new SimplexSolver(1e-4, 10, 1e-6);
PointValuePair solution = solver.optimize(new MaxIter(1000), f, new LinearConstraintSet(constraints),
GoalType.MINIMIZE, new NonNegativeConstraint(true));
Assert.assertEquals(0.3752298, solution.getValue(), 1e-4);
}
private List<LinearConstraint> createMath930Constraints() {
List<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] {1, -1, -1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, -1, -1, 1, 1, -1, -1, 1, -1, 1, 1, -1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 1, 0, -1, 0, -1, 0, 1, 0, -1, 0, 1, 0, 1, 0, -1, 0, -1, 0, 1, 0, 1, 0, -1, 0, 1, 0, -1, 0, -1, 0, 1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.628803}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.676993}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 1, -1, 0, 0, -1, 1, 0, 0, -1, 1, 0, 0, 1, -1, 0, 0, -1, 1, 0, 0, 1, -1, 0, 0, 1, -1, 0, 0, -1, 1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.136677}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.444434}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, 1, 0, 0, 0, -1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, -1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.254028}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.302218}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 1, -1, -1, 1, 0, 0, 0, 0, -1, 1, 1, -1, 0, 0, 0, 0, -1, 1, 1, -1, 0, 0, 0, 0, 1, -1, -1, 1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.653981}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.690437}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 1, 0, -1, 0, 0, 0, 0, 0, -1, 0, 1, 0, 0, 0, 0, 0, -1, 0, 1, 0, 0, 0, 0, 0, 1, 0, -1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.423786}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.486717}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 0, 0, -1, 1, 0, 0, 0, 0, 0, 0, -1, 1, 0, 0, 0, 0, 0, 0, 1, -1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.049232}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.304747}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.129826}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.205625}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 1, -1, 1, 1, -1, 0, 0, 0, 0, 0, 0, 0, 0, -1, 1, 1, -1, 1, -1, -1, 1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.621944}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.764385}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1, 0, -1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 1, 0, 1, 0, -1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.432572}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.480762}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0, -1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 1, 0, 0, 1, -1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.055983}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.11378}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.009607}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.057797}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 1, 1, -1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.407308}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.452749}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.269677}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.321806}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.049232}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.06902}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.028754}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.484254}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.524607}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1, 0, -1, 0, 1, 0, -1, 0, 1, 0, 1, 0, -1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.385492}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.430134}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0, -1, 1, 0, 0, -1, 1, 0, 0, 1, -1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.34983}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.375781}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, 1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.254028}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.281308}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 1, 0, 0, 0, 0, -1, 1, 1, -1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.304995}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.345347}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1, 0, 0, 0, 0, 0, -1, 0, 1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.288899}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.332212}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 0, 0, -1, 1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.14351}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.17057}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, -1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, -0.129826}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, -0.157435}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 1, -1, 1, 1, -1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, -0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, -1}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1, 0, -1, 0, 1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, -0.141071}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, -0.232574}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0, -1, 1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, -0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, -1}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, -1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, -0.009607}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, -0.057797}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, -0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, -1}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, -0.091644}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, -0.203531}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0}, Relationship.GEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -0.028754}, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] {0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, Relationship.EQ, 1.0));
return constraints;
}
@Test
public void testSimplexSolver() {
LinearObjectiveFunction f =
new LinearObjectiveFunction(new double[] { 15, 10 }, 7);
Collection<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.LEQ, 2));
constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.LEQ, 3));
constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.EQ, 4));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MAXIMIZE, new NonNegativeConstraint(true));
Assert.assertEquals(2.0, solution.getPoint()[0], 0.0);
Assert.assertEquals(2.0, solution.getPoint()[1], 0.0);
Assert.assertEquals(57.0, solution.getValue(), 0.0);
}
@Test
public void testSingleVariableAndConstraint() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 3 }, 0);
Collection<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] { 1 }, Relationship.LEQ, 10));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MAXIMIZE, new NonNegativeConstraint(false));
Assert.assertEquals(10.0, solution.getPoint()[0], 0.0);
Assert.assertEquals(30.0, solution.getValue(), 0.0);
}
/**
* With no artificial variables needed (no equals and no greater than
* constraints) we can go straight to Phase 2.
*/
@Test
public void testModelWithNoArtificialVars() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15, 10 }, 0);
Collection<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.LEQ, 2));
constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.LEQ, 3));
constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.LEQ, 4));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MAXIMIZE, new NonNegativeConstraint(false));
Assert.assertEquals(2.0, solution.getPoint()[0], 0.0);
Assert.assertEquals(2.0, solution.getPoint()[1], 0.0);
Assert.assertEquals(50.0, solution.getValue(), 0.0);
}
@Test
public void testMinimization() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { -2, 1 }, -5);
Collection<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] { 1, 2 }, Relationship.LEQ, 6));
constraints.add(new LinearConstraint(new double[] { 3, 2 }, Relationship.LEQ, 12));
constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.GEQ, 0));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MINIMIZE, new NonNegativeConstraint(false));
Assert.assertEquals(4.0, solution.getPoint()[0], 0.0);
Assert.assertEquals(0.0, solution.getPoint()[1], 0.0);
Assert.assertEquals(-13.0, solution.getValue(), 0.0);
}
@Test
public void testSolutionWithNegativeDecisionVariable() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { -2, 1 }, 0);
Collection<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.GEQ, 6));
constraints.add(new LinearConstraint(new double[] { 1, 2 }, Relationship.LEQ, 14));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MAXIMIZE, new NonNegativeConstraint(false));
Assert.assertEquals(-2.0, solution.getPoint()[0], 0.0);
Assert.assertEquals(8.0, solution.getPoint()[1], 0.0);
Assert.assertEquals(12.0, solution.getValue(), 0.0);
}
@Test(expected = NoFeasibleSolutionException.class)
public void testInfeasibleSolution() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15 }, 0);
Collection<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] { 1 }, Relationship.LEQ, 1));
constraints.add(new LinearConstraint(new double[] { 1 }, Relationship.GEQ, 3));
SimplexSolver solver = new SimplexSolver();
solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MAXIMIZE, new NonNegativeConstraint(false));
}
@Test(expected = UnboundedSolutionException.class)
public void testUnboundedSolution() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15, 10 }, 0);
Collection<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.EQ, 2));
SimplexSolver solver = new SimplexSolver();
solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MAXIMIZE, new NonNegativeConstraint(false));
}
@Test
public void testRestrictVariablesToNonNegative() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 409, 523, 70, 204, 339 }, 0);
Collection<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] { 43, 56, 345, 56, 5 }, Relationship.LEQ, 4567456));
constraints.add(new LinearConstraint(new double[] { 12, 45, 7, 56, 23 }, Relationship.LEQ, 56454));
constraints.add(new LinearConstraint(new double[] { 8, 768, 0, 34, 7456 }, Relationship.LEQ, 1923421));
constraints.add(new LinearConstraint(new double[] { 12342, 2342, 34, 678, 2342 }, Relationship.GEQ, 4356));
constraints.add(new LinearConstraint(new double[] { 45, 678, 76, 52, 23 }, Relationship.EQ, 456356));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MAXIMIZE, new NonNegativeConstraint(true));
Assert.assertEquals(2902.92783505155, solution.getPoint()[0], .0000001);
Assert.assertEquals(480.419243986254, solution.getPoint()[1], .0000001);
Assert.assertEquals(0.0, solution.getPoint()[2], .0000001);
Assert.assertEquals(0.0, solution.getPoint()[3], .0000001);
Assert.assertEquals(0.0, solution.getPoint()[4], .0000001);
Assert.assertEquals(1438556.7491409, solution.getValue(), .0000001);
}
@Test
public void testEpsilon() {
LinearObjectiveFunction f =
new LinearObjectiveFunction(new double[] { 10, 5, 1 }, 0);
Collection<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] { 9, 8, 0 }, Relationship.EQ, 17));
constraints.add(new LinearConstraint(new double[] { 0, 7, 8 }, Relationship.LEQ, 7));
constraints.add(new LinearConstraint(new double[] { 10, 0, 2 }, Relationship.LEQ, 10));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MAXIMIZE, new NonNegativeConstraint(false));
Assert.assertEquals(1.0, solution.getPoint()[0], 0.0);
Assert.assertEquals(1.0, solution.getPoint()[1], 0.0);
Assert.assertEquals(0.0, solution.getPoint()[2], 0.0);
Assert.assertEquals(15.0, solution.getValue(), 0.0);
}
@Test
public void testTrivialModel() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 1, 1 }, 0);
Collection<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.EQ, 0));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MAXIMIZE, new NonNegativeConstraint(true));
Assert.assertEquals(0, solution.getValue(), .0000001);
}
@Test
public void testLargeModel() {
double[] objective = new double[] {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 12, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
12, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 12, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 12, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 12, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 12, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1};
LinearObjectiveFunction f = new LinearObjectiveFunction(objective, 0);
Collection<LinearConstraint> constraints = new ArrayList<>();
constraints.add(equationFromString(objective.length, "x0 + x1 + x2 + x3 - x12 = 0"));
constraints.add(equationFromString(objective.length, "x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 - x13 = 0"));
constraints.add(equationFromString(objective.length, "x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 >= 49"));
constraints.add(equationFromString(objective.length, "x0 + x1 + x2 + x3 >= 42"));
constraints.add(equationFromString(objective.length, "x14 + x15 + x16 + x17 - x26 = 0"));
constraints.add(equationFromString(objective.length, "x18 + x19 + x20 + x21 + x22 + x23 + x24 + x25 - x27 = 0"));
constraints.add(equationFromString(objective.length, "x14 + x15 + x16 + x17 - x12 = 0"));
constraints.add(equationFromString(objective.length, "x18 + x19 + x20 + x21 + x22 + x23 + x24 + x25 - x13 = 0"));
constraints.add(equationFromString(objective.length, "x28 + x29 + x30 + x31 - x40 = 0"));
constraints.add(equationFromString(objective.length, "x32 + x33 + x34 + x35 + x36 + x37 + x38 + x39 - x41 = 0"));
constraints.add(equationFromString(objective.length, "x32 + x33 + x34 + x35 + x36 + x37 + x38 + x39 >= 49"));
constraints.add(equationFromString(objective.length, "x28 + x29 + x30 + x31 >= 42"));
constraints.add(equationFromString(objective.length, "x42 + x43 + x44 + x45 - x54 = 0"));
constraints.add(equationFromString(objective.length, "x46 + x47 + x48 + x49 + x50 + x51 + x52 + x53 - x55 = 0"));
constraints.add(equationFromString(objective.length, "x42 + x43 + x44 + x45 - x40 = 0"));
constraints.add(equationFromString(objective.length, "x46 + x47 + x48 + x49 + x50 + x51 + x52 + x53 - x41 = 0"));
constraints.add(equationFromString(objective.length, "x56 + x57 + x58 + x59 - x68 = 0"));
constraints.add(equationFromString(objective.length, "x60 + x61 + x62 + x63 + x64 + x65 + x66 + x67 - x69 = 0"));
constraints.add(equationFromString(objective.length, "x60 + x61 + x62 + x63 + x64 + x65 + x66 + x67 >= 51"));
constraints.add(equationFromString(objective.length, "x56 + x57 + x58 + x59 >= 44"));
constraints.add(equationFromString(objective.length, "x70 + x71 + x72 + x73 - x82 = 0"));
constraints.add(equationFromString(objective.length, "x74 + x75 + x76 + x77 + x78 + x79 + x80 + x81 - x83 = 0"));
constraints.add(equationFromString(objective.length, "x70 + x71 + x72 + x73 - x68 = 0"));
constraints.add(equationFromString(objective.length, "x74 + x75 + x76 + x77 + x78 + x79 + x80 + x81 - x69 = 0"));
constraints.add(equationFromString(objective.length, "x84 + x85 + x86 + x87 - x96 = 0"));
constraints.add(equationFromString(objective.length, "x88 + x89 + x90 + x91 + x92 + x93 + x94 + x95 - x97 = 0"));
constraints.add(equationFromString(objective.length, "x88 + x89 + x90 + x91 + x92 + x93 + x94 + x95 >= 51"));
constraints.add(equationFromString(objective.length, "x84 + x85 + x86 + x87 >= 44"));
constraints.add(equationFromString(objective.length, "x98 + x99 + x100 + x101 - x110 = 0"));
constraints.add(equationFromString(objective.length, "x102 + x103 + x104 + x105 + x106 + x107 + x108 + x109 - x111 = 0"));
constraints.add(equationFromString(objective.length, "x98 + x99 + x100 + x101 - x96 = 0"));
constraints.add(equationFromString(objective.length, "x102 + x103 + x104 + x105 + x106 + x107 + x108 + x109 - x97 = 0"));
constraints.add(equationFromString(objective.length, "x112 + x113 + x114 + x115 - x124 = 0"));
constraints.add(equationFromString(objective.length, "x116 + x117 + x118 + x119 + x120 + x121 + x122 + x123 - x125 = 0"));
constraints.add(equationFromString(objective.length, "x116 + x117 + x118 + x119 + x120 + x121 + x122 + x123 >= 49"));
constraints.add(equationFromString(objective.length, "x112 + x113 + x114 + x115 >= 42"));
constraints.add(equationFromString(objective.length, "x126 + x127 + x128 + x129 - x138 = 0"));
constraints.add(equationFromString(objective.length, "x130 + x131 + x132 + x133 + x134 + x135 + x136 + x137 - x139 = 0"));
constraints.add(equationFromString(objective.length, "x126 + x127 + x128 + x129 - x124 = 0"));
constraints.add(equationFromString(objective.length, "x130 + x131 + x132 + x133 + x134 + x135 + x136 + x137 - x125 = 0"));
constraints.add(equationFromString(objective.length, "x140 + x141 + x142 + x143 - x152 = 0"));
constraints.add(equationFromString(objective.length, "x144 + x145 + x146 + x147 + x148 + x149 + x150 + x151 - x153 = 0"));
constraints.add(equationFromString(objective.length, "x144 + x145 + x146 + x147 + x148 + x149 + x150 + x151 >= 59"));
constraints.add(equationFromString(objective.length, "x140 + x141 + x142 + x143 >= 42"));
constraints.add(equationFromString(objective.length, "x154 + x155 + x156 + x157 - x166 = 0"));
constraints.add(equationFromString(objective.length, "x158 + x159 + x160 + x161 + x162 + x163 + x164 + x165 - x167 = 0"));
constraints.add(equationFromString(objective.length, "x154 + x155 + x156 + x157 - x152 = 0"));
constraints.add(equationFromString(objective.length, "x158 + x159 + x160 + x161 + x162 + x163 + x164 + x165 - x153 = 0"));
constraints.add(equationFromString(objective.length, "x83 + x82 - x168 = 0"));
constraints.add(equationFromString(objective.length, "x111 + x110 - x169 = 0"));
constraints.add(equationFromString(objective.length, "x170 - x182 = 0"));
constraints.add(equationFromString(objective.length, "x171 - x183 = 0"));
constraints.add(equationFromString(objective.length, "x172 - x184 = 0"));
constraints.add(equationFromString(objective.length, "x173 - x185 = 0"));
constraints.add(equationFromString(objective.length, "x174 - x186 = 0"));
constraints.add(equationFromString(objective.length, "x175 + x176 - x187 = 0"));
constraints.add(equationFromString(objective.length, "x177 - x188 = 0"));
constraints.add(equationFromString(objective.length, "x178 - x189 = 0"));
constraints.add(equationFromString(objective.length, "x179 - x190 = 0"));
constraints.add(equationFromString(objective.length, "x180 - x191 = 0"));
constraints.add(equationFromString(objective.length, "x181 - x192 = 0"));
constraints.add(equationFromString(objective.length, "x170 - x26 = 0"));
constraints.add(equationFromString(objective.length, "x171 - x27 = 0"));
constraints.add(equationFromString(objective.length, "x172 - x54 = 0"));
constraints.add(equationFromString(objective.length, "x173 - x55 = 0"));
constraints.add(equationFromString(objective.length, "x174 - x168 = 0"));
constraints.add(equationFromString(objective.length, "x177 - x169 = 0"));
constraints.add(equationFromString(objective.length, "x178 - x138 = 0"));
constraints.add(equationFromString(objective.length, "x179 - x139 = 0"));
constraints.add(equationFromString(objective.length, "x180 - x166 = 0"));
constraints.add(equationFromString(objective.length, "x181 - x167 = 0"));
constraints.add(equationFromString(objective.length, "x193 - x205 = 0"));
constraints.add(equationFromString(objective.length, "x194 - x206 = 0"));
constraints.add(equationFromString(objective.length, "x195 - x207 = 0"));
constraints.add(equationFromString(objective.length, "x196 - x208 = 0"));
constraints.add(equationFromString(objective.length, "x197 - x209 = 0"));
constraints.add(equationFromString(objective.length, "x198 + x199 - x210 = 0"));
constraints.add(equationFromString(objective.length, "x200 - x211 = 0"));
constraints.add(equationFromString(objective.length, "x201 - x212 = 0"));
constraints.add(equationFromString(objective.length, "x202 - x213 = 0"));
constraints.add(equationFromString(objective.length, "x203 - x214 = 0"));
constraints.add(equationFromString(objective.length, "x204 - x215 = 0"));
constraints.add(equationFromString(objective.length, "x193 - x182 = 0"));
constraints.add(equationFromString(objective.length, "x194 - x183 = 0"));
constraints.add(equationFromString(objective.length, "x195 - x184 = 0"));
constraints.add(equationFromString(objective.length, "x196 - x185 = 0"));
constraints.add(equationFromString(objective.length, "x197 - x186 = 0"));
constraints.add(equationFromString(objective.length, "x198 + x199 - x187 = 0"));
constraints.add(equationFromString(objective.length, "x200 - x188 = 0"));
constraints.add(equationFromString(objective.length, "x201 - x189 = 0"));
constraints.add(equationFromString(objective.length, "x202 - x190 = 0"));
constraints.add(equationFromString(objective.length, "x203 - x191 = 0"));
constraints.add(equationFromString(objective.length, "x204 - x192 = 0"));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MINIMIZE, new NonNegativeConstraint(true));
Assert.assertEquals(7518.0, solution.getValue(), .0000001);
}
@Test
public void testSolutionCallback() {
// re-use the problem from testcase for MATH-288
// it normally requires 5 iterations
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 7, 3, 0, 0 }, 0 );
List<LinearConstraint> constraints = new ArrayList<>();
constraints.add(new LinearConstraint(new double[] { 3, 0, -5, 0 }, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] { 2, 0, 0, -5 }, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] { 0, 3, 0, -5 }, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] { 1, 0, 0, 0 }, Relationship.LEQ, 1.0));
constraints.add(new LinearConstraint(new double[] { 0, 1, 0, 0 }, Relationship.LEQ, 1.0));
final SimplexSolver solver = new SimplexSolver();
final SolutionCallback callback = new SolutionCallback();
Assert.assertNull(callback.getSolution());
Assert.assertFalse(callback.isSolutionOptimal());
try {
solver.optimize(new MaxIter(4), f, new LinearConstraintSet(constraints),
GoalType.MAXIMIZE, new NonNegativeConstraint(true), callback);
Assert.fail("expected TooManyIterationsException");
} catch (TooManyIterationsException ex) {
// expected
}
final PointValuePair solution = callback.getSolution();
Assert.assertNotNull(solution);
Assert.assertTrue(validSolution(solution, constraints, 1e-4));
Assert.assertFalse(callback.isSolutionOptimal());
// the solution is clearly not optimal: optimal = 10.0
Assert.assertEquals(7.0, solution.getValue(), 1e-4);
}
@Test(expected=DimensionMismatchException.class)
public void testDimensionMatch() {
// min 2x1 +15x2 +18x3
// Subject to
// -x1 +2x2 -6x3 <=-10
// x2 +2x3 <= 6
// 2x1 +10x3 <= 19
// -x1 +x2 <= -2
// x1,x2,x3 >= 0
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 2, 15, 18 }, 0);
Collection<LinearConstraint> constraints = new ArrayList<>();
// this constraint is wrong, the dimension is less than expected one
constraints.add(new LinearConstraint(new double[] { -1, 2 - 6 }, Relationship.LEQ, -10));
constraints.add(new LinearConstraint(new double[] { 0, 1, 2 }, Relationship.LEQ, 6));
constraints.add(new LinearConstraint(new double[] { 2, 0, 10 }, Relationship.LEQ, 19));
constraints.add(new LinearConstraint(new double[] { -1, 1, 0 }, Relationship.LEQ, -2));
SimplexSolver solver = new SimplexSolver();
solver.optimize(f,
new LinearConstraintSet(constraints),
new NonNegativeConstraint(true),
PivotSelectionRule.BLAND);
}
/**
* Converts a test string to a {@link LinearConstraint}.
* Ex: x0 + x1 + x2 + x3 - x12 = 0
*/
private LinearConstraint equationFromString(int numCoefficients, String s) {
Relationship relationship;
if (s.contains(">=")) {
relationship = Relationship.GEQ;
} else if (s.contains("<=")) {
relationship = Relationship.LEQ;
} else if (s.contains("=")) {
relationship = Relationship.EQ;
} else {
throw new IllegalArgumentException();
}
String[] equationParts = s.split("[>|<]?=");
double rhs = Double.parseDouble(equationParts[1].trim());
double[] lhs = new double[numCoefficients];
String left = equationParts[0].replaceAll(" ?x", "");
String[] coefficients = left.split(" ");
for (String coefficient : coefficients) {
double value = coefficient.charAt(0) == '-' ? -1 : 1;
int index = Integer.parseInt(coefficient.replaceFirst("[+|-]", "").trim());
lhs[index] = value;
}
return new LinearConstraint(lhs, relationship, rhs);
}
private static boolean validSolution(PointValuePair solution, List<LinearConstraint> constraints, double epsilon) {
double[] vals = solution.getPoint();
for (LinearConstraint c : constraints) {
double[] coeffs = c.getCoefficients().toArray();
double result = 0.0d;
for (int i = 0; i < vals.length; i++) {
result += vals[i] * coeffs[i];
}
switch (c.getRelationship()) {
case EQ:
if (!Precision.equals(result, c.getValue(), epsilon)) {
return false;
}
break;
case GEQ:
if (Precision.compareTo(result, c.getValue(), epsilon) < 0) {
return false;
}
break;
case LEQ:
if (Precision.compareTo(result, c.getValue(), epsilon) > 0) {
return false;
}
break;
}
}
return true;
}
}
|
MATH-1549: Added unit test based on the demo code provided on the report page.
Unit test is set to "@Ignore" as the issue is still present.
|
src/test/java/org/apache/commons/math4/optim/linear/SimplexSolverTest.java
|
MATH-1549: Added unit test based on the demo code provided on the report page.
|
<ide><path>rc/test/java/org/apache/commons/math4/optim/linear/SimplexSolverTest.java
<ide> import java.util.ArrayList;
<ide> import java.util.Collection;
<ide> import java.util.List;
<del>
<add>import org.junit.Test;
<add>import org.junit.Ignore;
<add>import org.junit.Assert;
<add>
<add>import org.apache.commons.numbers.core.Precision;
<ide> import org.apache.commons.math4.exception.DimensionMismatchException;
<ide> import org.apache.commons.math4.exception.TooManyIterationsException;
<ide> import org.apache.commons.math4.optim.MaxIter;
<ide> import org.apache.commons.math4.optim.linear.SolutionCallback;
<ide> import org.apache.commons.math4.optim.linear.UnboundedSolutionException;
<ide> import org.apache.commons.math4.optim.nonlinear.scalar.GoalType;
<del>import org.apache.commons.numbers.core.Precision;
<del>import org.junit.Test;
<del>import org.junit.Assert;
<ide>
<ide> public class SimplexSolverTest {
<ide> private static final MaxIter DEFAULT_MAX_ITER = new MaxIter(100);
<ide> PivotSelectionRule.BLAND);
<ide> }
<ide>
<add> /* XXX Skipped until issue is solved: https://issues.apache.org/jira/browse/MATH-1549 */
<add> @Ignore@Test
<add> public void testMath1549() {
<add> final double m = 10;
<add> double scale = 1;
<add> int numFailures = 0;
<add> for (int pow = 0; pow < 13; pow++) {
<add> try {
<add> tryMath1549(scale);
<add> } catch (RuntimeException e) {
<add> e.printStackTrace();
<add> ++numFailures;
<add> }
<add> scale *= m;
<add> }
<add>
<add> if (numFailures > 0) {
<add> Assert.fail(numFailures + " failures");
<add> }
<add> }
<add>
<add> /* See JIRA issue: MATH-1549 */
<add> private void tryMath1549(double scale) {
<add> final NonNegativeConstraint nnegconstr = new NonNegativeConstraint(true);
<add> final int ulps = 10;
<add> final double cutoff = 1e-10;
<add> final double eps = 1e-6;
<add> final SimplexSolver solver = new SimplexSolver(eps, ulps, cutoff);
<add>
<add> final LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] {1, 1}, 0);
<add> final List<LinearConstraint> constraints = new ArrayList<>();
<add> constraints.add(new LinearConstraint(new double[] {scale * 9000, scale * 1}, Relationship.GEQ, 0));
<add> constraints.add(new LinearConstraint(new double[] {scale * 10000, scale}, Relationship.GEQ, scale * 2000));
<add> constraints.add(new LinearConstraint(new double[] {scale, 0}, Relationship.GEQ, scale * 2));
<add> final LinearConstraintSet constraintSet = new LinearConstraintSet(constraints);
<add> final PointValuePair solution = solver.optimize(f, constraintSet, GoalType.MINIMIZE, nnegconstr);
<add>
<add> System.out.println("scale=" + scale + ": sol=" + java.util.Arrays.toString(solution.getPoint()));
<add> }
<add>
<ide> /**
<ide> * Converts a test string to a {@link LinearConstraint}.
<ide> * Ex: x0 + x1 + x2 + x3 - x12 = 0
|
|
Java
|
agpl-3.0
|
100c540bfc473746d793755ac305cd58b02beca6
| 0 |
EhsanTang/ApiManager,EhsanTang/ApiManager,EhsanTang/ApiManager
|
package cn.crap.utils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import cn.crap.dto.DictionaryDto;
import cn.crap.enumeration.ArticleType;
import cn.crap.enumeration.DictionaryPropertyType;
import cn.crap.framework.MyException;
import cn.crap.model.Article;
import net.sf.json.JSONArray;
public class SqlToDictionaryUtil {
public static Article mysqlToDictionary(String sql, String brief, String moduleId, String name) throws MyException{
if(!sql.toLowerCase().replaceAll(" ", "").startsWith("createtable")){
throw new MyException("000046");
}
// 联合主键等被切分
sql = sql.replace("`,`", "");
Article article = new Article();
article.setType(ArticleType.DICTIONARY.name());
article.setBrief(brief);
article.setModuleId(moduleId);
article.setMarkdown("");
article.setName(name);
article.setCanDelete(Byte.valueOf("1"));
sql = sql.replace("\n", " ");
if(MyString.isEmpty(name)){
String tableName = sql.substring(sql.toLowerCase().indexOf("table") + 5, sql.indexOf("(")).replaceAll("`", "").replaceAll("'", "").trim();
article.setName(tableName);
}
String fields = sql.substring(sql.indexOf("(") + 1, sql.lastIndexOf(")") + 1);
Map<String, DictionaryDto> propertys = new HashMap<String, DictionaryDto>();
String[] fieldsArray = fields.split(",");
for(int i=0; i<fieldsArray.length; i++){
String field = fieldsArray[i];
// decimal(18,2) 被分隔
try{
Integer.parseInt(fieldsArray[i+1].substring(0,1));
fieldsArray[i+1] = fieldsArray[i] +","+ fieldsArray[i+1];
continue;
}catch(Exception e){
}
try{
// 字段
DictionaryDto dto = null;
if(field.trim().startsWith("`")){
String property = field.trim().split(" ")[0].replaceAll("`", "").replaceAll("'", "");
dto = propertys.get(property);
if(dto == null) {
dto = new DictionaryDto();
dto.setName(property);
}
dto.setType(field.trim().split(" ")[1]);
dto.setNotNull(field.trim().replace(" ", "").toLowerCase().indexOf("notnull") > 0?"false" : "true");
if(field.toLowerCase().indexOf(" default ") > 0){
String def = field.substring(field.toLowerCase().indexOf(" default "));
// 默认值
if(def.trim().startsWith("'")){
dto.setDef(def.split("'")[1].replace("'", ""));
}else{
dto.setDef(def.trim().split(" ")[1].replace("'", ""));
}
}
if(field.toLowerCase().indexOf(" comment ") > 0){
String remark = field.substring(field.toLowerCase().indexOf(" comment "));
// 默认值
if(remark.trim().startsWith("'")){
remark = remark.split("'")[1].replace("'", "");
dto.setRemark(remark);
}else{
remark = remark.trim().split(" ")[1].replace("'", "");
dto.setRemark(remark);
}
}
propertys.put(dto.getName(), dto);
}else{
if(field.replaceAll(" ", "").toLowerCase().indexOf("primarykey") >= 0){
String primaryKeys = field.substring( field.indexOf("(") + 1, field.indexOf(")")).replaceAll("`", "").replaceAll("'", "");
for(String primaryKey : primaryKeys.split(",")){
dto = propertys.get(primaryKey);
if(dto == null) {
dto = new DictionaryDto();
}
dto.setName(primaryKey);
dto.setFlag(DictionaryPropertyType.primary.getName());
propertys.put(dto.getName(), dto);
}
}
if(field.replaceAll(" ", "").toLowerCase().indexOf("foreignkey") >= 0){
String foreignKey = field.substring( field.indexOf("(") + 1, field.indexOf(")")).replaceAll("`", "").replaceAll("'", "");
dto = propertys.get(foreignKey);
if(dto == null) {
dto = new DictionaryDto();
}
dto.setName(foreignKey);
dto.setFlag(DictionaryPropertyType.foreign.getName());
propertys.put(dto.getName(), dto);
}
}
}catch(Exception e){
if(i+1 < fieldsArray.length )
fieldsArray[i+1] = fieldsArray[i] +"," + fieldsArray[i+1];
continue;
}
}
List<DictionaryDto> fieldList = new ArrayList<DictionaryDto>();
for(String key: propertys.keySet()){
if( propertys.get(key).getFlag().equals( DictionaryPropertyType.primary.getName() )
|| propertys.get(key).getFlag().equals( DictionaryPropertyType.foreign.getName() )
|| propertys.get(key).getFlag().equals( DictionaryPropertyType.associate.getName() ) ){
fieldList.add(0,propertys.get(key));
}else{
fieldList.add(propertys.get(key));
}
}
article.setContent(JSONArray.fromObject(fieldList).toString());
return article;
}
public static Article sqlserviceToDictionary(String sql, String brief, String moduleId, String name) throws MyException{
if(!sql.toLowerCase().replaceAll(" ", "").startsWith("createtable")){
throw new MyException("000046");
}
String[] descriptions = null;
sql = sql.replace("\n", " ");
if(sql.indexOf(" GO ")>0){
descriptions = sql.split("@value = N");
sql = sql.split(" GO ")[0];
}
Article article = new Article();
article.setType(ArticleType.DICTIONARY.name());
article.setBrief(brief);
article.setModuleId(moduleId);
article.setMarkdown("");
article.setName(name);
article.setCanDelete(Byte.valueOf("1"));
if(MyString.isEmpty(name)){
String tableName = sql.substring(sql.toLowerCase().indexOf("table") + 5, sql.indexOf("(")).replaceAll("\\[", "").replaceAll("\\]", "").trim();
article.setName(tableName);
}
String fields = sql.substring(sql.indexOf("(") + 1, sql.lastIndexOf(")") + 1);
Map<String, DictionaryDto> propertys = new HashMap<String, DictionaryDto>();
String[] fieldsArray = fields.split(",");
for(int i=0; i<fieldsArray.length; i++){
String field = fieldsArray[i];
// decimal(18,2) 被分隔
try{
Integer.parseInt(fieldsArray[i+1].substring(0,1));
fieldsArray[i+1] = fieldsArray[i] +","+ fieldsArray[i+1];
continue;
}catch(Exception e){
}
try{
// 字段
DictionaryDto dto = null;
if(field.trim().startsWith("[")){
String property = field.trim().split(" ")[0].replaceAll("\\[", "").replaceAll("\\]", "");
dto = propertys.get(property);
if(dto == null) {
dto = new DictionaryDto();
dto.setName(property);
}
dto.setType(field.trim().split(" ")[1]);
dto.setNotNull(field.trim().replace(" ", "").toLowerCase().indexOf("notnull") > 0?"false" : "true");
if(field.toLowerCase().indexOf(" default ") > 0){
String def = field.substring(field.toLowerCase().indexOf(" default ") + 9);
// 默认值
dto.setDef(def);
}
// 备注
if(descriptions != null){
for(String des:descriptions){
if(des.indexOf("@level2type = 'COLUMN', @level2name = N'"+dto.getName()+"'") > 0){
dto.setRemark(des.split(",")[0].replaceAll("'", ""));
}
}
}
propertys.put(dto.getName(), dto);
}else{
if(field.replaceAll(" ", "").toLowerCase().indexOf("primarykey") >= 0){
String primaryKeys = field.substring( field.indexOf("(") + 1, field.indexOf(")")).replaceAll("\\[", "").replaceAll("\\]", "");
for(String primaryKey : primaryKeys.split(",")){
dto = propertys.get(primaryKey);
if(dto == null) {
dto = new DictionaryDto();
}
dto.setName(primaryKey);
dto.setFlag(DictionaryPropertyType.primary.getName());
propertys.put(dto.getName(), dto);
}
}
if(field.replaceAll(" ", "").toLowerCase().indexOf("foreignkey") >= 0){
String foreignKey = field.substring( field.indexOf("(") + 1, field.indexOf(")")).replaceAll("\\[", "").replaceAll("\\]", "");
dto = propertys.get(foreignKey);
if(dto == null) {
dto = new DictionaryDto();
}
dto.setName(foreignKey);
dto.setFlag(DictionaryPropertyType.foreign.getName());
propertys.put(dto.getName(), dto);
}
}
}catch(Exception e){
e.printStackTrace();
continue;
}
}
List<DictionaryDto> fieldList = new ArrayList<DictionaryDto>();
for(String key: propertys.keySet()){
if( propertys.get(key).getFlag().equals( DictionaryPropertyType.primary.getName() )
|| propertys.get(key).getFlag().equals( DictionaryPropertyType.foreign.getName() )
|| propertys.get(key).getFlag().equals( DictionaryPropertyType.associate.getName() ) ){
fieldList.add(0,propertys.get(key));
}else{
fieldList.add(propertys.get(key));
}
}
article.setContent(JSONArray.fromObject(fieldList).toString());
return article;
}
// sqlservice test
// public static void main(String args[]) throws MyException{
// String sql = "CREATE TABLE [dbo].[addr_city] ("+
// "[ADDR_ID] varchar(12) NOT NULL ,"+
// "[ADDR_NAME] varchar(48) NOT NULL ,"+
// "[FATHER_ID] varchar(12) NOT NULL ,"+
// "[IS_ENABLED] int NULL ,"+
// "[estimated_delivery_time] datetime NULL,"+
// "[create_by] varchar(50) NOT NULL ,"+
// "[create_time] datetime NOT NULL ,"+
// "[update_by] varchar(50) NOT NULL ,"+
// "[update_time] datetime NOT NULL ,"+
// "[orderType] int NULL ,"+
// "[orderSource] int NULL ,"+
// "[freeExpress] bit NULL ,"+
// "[promotionId] int NULL ,"+
// "[platform] nvarchar(32) NULL ,"+
// "[source] nvarchar(64) NULL ,"+
// "[test_order] bit NULL ,"+
// "[createtime] datetime NOT NULL, "+
// "[bbb] varchar NULL DEFAULT 默认 ,"+
// "[ccc] bigint NULL DEFAULT 10 ,"+
// "PRIMARY KEY ([aaa]),"+
// "CONSTRAINT [dd] FOREIGN KEY ([ccc]) REFERENCES [dbo].[customer_order_base] ([order_id])"+
// ")"+
// "\nGO\n"+
// "IF ((SELECT COUNT(*) from fn_listextendedproperty('MS_Description', "+
// "'SCHEMA', N'dbo', "+
// "'TABLE', N'customer_order_base', "+
// "'COLUMN', N'order_id')) > 0) "+
// "EXEC sp_updateextendedproperty @name = N'MS_Description', @value = N'订单编号'"+
// ", @level0type = 'SCHEMA', @level0name = N'dbo'"+
// ", @level1type = 'TABLE', @level1name = N'customer_order_base'"+
// ", @level2type = 'COLUMN', @level2name = N'order_id'"+
// "ELSE"+
// "EXEC sp_addextendedproperty @name = N'MS_Description', @value = N'订单编号'"+
// ", @level0type = 'SCHEMA', @level0name = N'dbo'"+
// ", @level1type = 'TABLE', @level1name = N'customer_order_base'"+
// ", @level2type = 'COLUMN', @level2name = N'test_order'"+
// "GO;";
// Article table = sqlserviceToDictionary(sql,"","","");
// System.out.println("-----------"+table.getContent());
// }
}
|
api/src/main/java/cn/crap/utils/SqlToDictionaryUtil.java
|
package cn.crap.utils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import cn.crap.dto.DictionaryDto;
import cn.crap.enumeration.ArticleType;
import cn.crap.enumeration.DictionaryPropertyType;
import cn.crap.framework.MyException;
import cn.crap.model.Article;
import net.sf.json.JSONArray;
public class SqlToDictionaryUtil {
public static Article mysqlToDictionary(String sql, String brief, String moduleId, String name) throws MyException{
if(!sql.toLowerCase().replaceAll(" ", "").startsWith("createtable")){
throw new MyException("000046");
}
Article article = new Article();
article.setType(ArticleType.DICTIONARY.name());
article.setBrief(brief);
article.setModuleId(moduleId);
article.setMarkdown("");
article.setName(name);
article.setCanDelete(Byte.valueOf("1"));
sql = sql.replace("\n", " ");
if(MyString.isEmpty(name)){
String tableName = sql.substring(sql.toLowerCase().indexOf("table") + 5, sql.indexOf("(")).replaceAll("`", "").replaceAll("'", "").trim();
article.setName(tableName);
}
String fields = sql.substring(sql.indexOf("(") + 1, sql.lastIndexOf(")") + 1);
Map<String, DictionaryDto> propertys = new HashMap<String, DictionaryDto>();
String[] fieldsArray = fields.split(",");
for(int i=0; i<fieldsArray.length; i++){
String field = fieldsArray[i];
// decimal(18,2) 被分隔
try{
Integer.parseInt(fieldsArray[i+1].substring(0,1));
fieldsArray[i+1] = fieldsArray[i] +","+ fieldsArray[i+1];
continue;
}catch(Exception e){
}
try{
// 字段
DictionaryDto dto = null;
if(field.trim().startsWith("`")){
String property = field.trim().split(" ")[0].replaceAll("`", "").replaceAll("'", "");
dto = propertys.get(property);
if(dto == null) {
dto = new DictionaryDto();
dto.setName(property);
}
dto.setType(field.trim().split(" ")[1]);
dto.setNotNull(field.trim().replace(" ", "").toLowerCase().indexOf("notnull") > 0?"false" : "true");
if(field.toLowerCase().indexOf(" default ") > 0){
String def = field.substring(field.toLowerCase().indexOf(" default "));
// 默认值
if(def.trim().startsWith("'")){
dto.setDef(def.split("'")[1].replace("'", ""));
}else{
dto.setDef(def.trim().split(" ")[1].replace("'", ""));
}
}
if(field.toLowerCase().indexOf(" comment ") > 0){
String remark = field.substring(field.toLowerCase().indexOf(" comment "));
// 默认值
if(remark.trim().startsWith("'")){
remark = remark.split("'")[1].replace("'", "");
dto.setRemark(remark);
}else{
remark = remark.trim().split(" ")[1].replace("'", "");
dto.setRemark(remark);
}
}
propertys.put(dto.getName(), dto);
}else{
if(field.replaceAll(" ", "").toLowerCase().indexOf("primarykey") >= 0){
String primaryKeys = field.substring( field.indexOf("(") + 1, field.indexOf(")")).replaceAll("`", "").replaceAll("'", "");
for(String primaryKey : primaryKeys.split(",")){
dto = propertys.get(primaryKey);
if(dto == null) {
dto = new DictionaryDto();
}
dto.setName(primaryKey);
dto.setFlag(DictionaryPropertyType.primary.getName());
propertys.put(dto.getName(), dto);
}
}
if(field.replaceAll(" ", "").toLowerCase().indexOf("foreignkey") >= 0){
String foreignKey = field.substring( field.indexOf("(") + 1, field.indexOf(")")).replaceAll("`", "").replaceAll("'", "");
dto = propertys.get(foreignKey);
if(dto == null) {
dto = new DictionaryDto();
}
dto.setName(foreignKey);
dto.setFlag(DictionaryPropertyType.foreign.getName());
propertys.put(dto.getName(), dto);
}
}
}catch(Exception e){
if(i+1 < fieldsArray.length )
fieldsArray[i+1] = fieldsArray[i] +"," + fieldsArray[i+1];
continue;
}
}
List<DictionaryDto> fieldList = new ArrayList<DictionaryDto>();
for(String key: propertys.keySet()){
fieldList.add(propertys.get(key));
}
article.setContent(JSONArray.fromObject(fieldList).toString());
return article;
}
public static Article sqlserviceToDictionary(String sql, String brief, String moduleId, String name) throws MyException{
if(!sql.toLowerCase().replaceAll(" ", "").startsWith("createtable")){
throw new MyException("000046");
}
String[] descriptions = null;
sql = sql.replace("\n", " ");
if(sql.indexOf(" GO ")>0){
descriptions = sql.split("@value = N");
sql = sql.split(" GO ")[0];
}
Article article = new Article();
article.setType(ArticleType.DICTIONARY.name());
article.setBrief(brief);
article.setModuleId(moduleId);
article.setMarkdown("");
article.setName(name);
article.setCanDelete(Byte.valueOf("1"));
if(MyString.isEmpty(name)){
String tableName = sql.substring(sql.toLowerCase().indexOf("table") + 5, sql.indexOf("(")).replaceAll("\\[", "").replaceAll("\\]", "").trim();
article.setName(tableName);
}
String fields = sql.substring(sql.indexOf("(") + 1, sql.lastIndexOf(")") + 1);
Map<String, DictionaryDto> propertys = new HashMap<String, DictionaryDto>();
String[] fieldsArray = fields.split(",");
for(int i=0; i<fieldsArray.length; i++){
String field = fieldsArray[i];
// decimal(18,2) 被分隔
try{
Integer.parseInt(fieldsArray[i+1].substring(0,1));
fieldsArray[i+1] = fieldsArray[i] +","+ fieldsArray[i+1];
continue;
}catch(Exception e){
}
try{
// 字段
DictionaryDto dto = null;
if(field.trim().startsWith("[")){
String property = field.trim().split(" ")[0].replaceAll("\\[", "").replaceAll("\\]", "");
dto = propertys.get(property);
if(dto == null) {
dto = new DictionaryDto();
dto.setName(property);
}
dto.setType(field.trim().split(" ")[1]);
dto.setNotNull(field.trim().replace(" ", "").toLowerCase().indexOf("notnull") > 0?"false" : "true");
if(field.toLowerCase().indexOf(" default ") > 0){
String def = field.substring(field.toLowerCase().indexOf(" default ") + 9);
// 默认值
dto.setDef(def);
}
// 备注
if(descriptions != null){
for(String des:descriptions){
if(des.indexOf("@level2type = 'COLUMN', @level2name = N'"+dto.getName()+"'") > 0){
dto.setRemark(des.split(",")[0].replaceAll("'", ""));
}
}
}
propertys.put(dto.getName(), dto);
}else{
if(field.replaceAll(" ", "").toLowerCase().indexOf("primarykey") >= 0){
String primaryKeys = field.substring( field.indexOf("(") + 1, field.indexOf(")")).replaceAll("\\[", "").replaceAll("\\]", "");
for(String primaryKey : primaryKeys.split(",")){
dto = propertys.get(primaryKey);
if(dto == null) {
dto = new DictionaryDto();
}
dto.setName(primaryKey);
dto.setFlag(DictionaryPropertyType.primary.getName());
propertys.put(dto.getName(), dto);
}
}
if(field.replaceAll(" ", "").toLowerCase().indexOf("foreignkey") >= 0){
String foreignKey = field.substring( field.indexOf("(") + 1, field.indexOf(")")).replaceAll("\\[", "").replaceAll("\\]", "");
dto = propertys.get(foreignKey);
if(dto == null) {
dto = new DictionaryDto();
}
dto.setName(foreignKey);
dto.setFlag(DictionaryPropertyType.foreign.getName());
propertys.put(dto.getName(), dto);
}
}
}catch(Exception e){
e.printStackTrace();
continue;
}
}
List<DictionaryDto> fieldList = new ArrayList<DictionaryDto>();
for(String key: propertys.keySet()){
fieldList.add(propertys.get(key));
}
article.setContent(JSONArray.fromObject(fieldList).toString());
return article;
}
// sqlservice test
// public static void main(String args[]) throws MyException{
// String sql = "CREATE TABLE [dbo].[addr_city] ("+
// "[ADDR_ID] varchar(12) NOT NULL ,"+
// "[ADDR_NAME] varchar(48) NOT NULL ,"+
// "[FATHER_ID] varchar(12) NOT NULL ,"+
// "[IS_ENABLED] int NULL ,"+
// "[estimated_delivery_time] datetime NULL,"+
// "[create_by] varchar(50) NOT NULL ,"+
// "[create_time] datetime NOT NULL ,"+
// "[update_by] varchar(50) NOT NULL ,"+
// "[update_time] datetime NOT NULL ,"+
// "[orderType] int NULL ,"+
// "[orderSource] int NULL ,"+
// "[freeExpress] bit NULL ,"+
// "[promotionId] int NULL ,"+
// "[platform] nvarchar(32) NULL ,"+
// "[source] nvarchar(64) NULL ,"+
// "[test_order] bit NULL ,"+
// "[createtime] datetime NOT NULL, "+
// "[bbb] varchar NULL DEFAULT 默认 ,"+
// "[ccc] bigint NULL DEFAULT 10 ,"+
// "PRIMARY KEY ([aaa]),"+
// "CONSTRAINT [dd] FOREIGN KEY ([ccc]) REFERENCES [dbo].[customer_order_base] ([order_id])"+
// ")"+
// "\nGO\n"+
// "IF ((SELECT COUNT(*) from fn_listextendedproperty('MS_Description', "+
// "'SCHEMA', N'dbo', "+
// "'TABLE', N'customer_order_base', "+
// "'COLUMN', N'order_id')) > 0) "+
// "EXEC sp_updateextendedproperty @name = N'MS_Description', @value = N'订单编号'"+
// ", @level0type = 'SCHEMA', @level0name = N'dbo'"+
// ", @level1type = 'TABLE', @level1name = N'customer_order_base'"+
// ", @level2type = 'COLUMN', @level2name = N'order_id'"+
// "ELSE"+
// "EXEC sp_addextendedproperty @name = N'MS_Description', @value = N'订单编号'"+
// ", @level0type = 'SCHEMA', @level0name = N'dbo'"+
// ", @level1type = 'TABLE', @level1name = N'customer_order_base'"+
// ", @level2type = 'COLUMN', @level2name = N'test_order'"+
// "GO;";
// Article table = sqlserviceToDictionary(sql,"","","");
// System.out.println("-----------"+table.getContent());
// }
}
|
索引导致导入异常,主键、外键排序至第一位
|
api/src/main/java/cn/crap/utils/SqlToDictionaryUtil.java
|
索引导致导入异常,主键、外键排序至第一位
|
<ide><path>pi/src/main/java/cn/crap/utils/SqlToDictionaryUtil.java
<ide> if(!sql.toLowerCase().replaceAll(" ", "").startsWith("createtable")){
<ide> throw new MyException("000046");
<ide> }
<add> // 联合主键等被切分
<add> sql = sql.replace("`,`", "");
<ide> Article article = new Article();
<ide> article.setType(ArticleType.DICTIONARY.name());
<ide> article.setBrief(brief);
<ide> }
<ide> List<DictionaryDto> fieldList = new ArrayList<DictionaryDto>();
<ide> for(String key: propertys.keySet()){
<del> fieldList.add(propertys.get(key));
<add> if( propertys.get(key).getFlag().equals( DictionaryPropertyType.primary.getName() )
<add> || propertys.get(key).getFlag().equals( DictionaryPropertyType.foreign.getName() )
<add> || propertys.get(key).getFlag().equals( DictionaryPropertyType.associate.getName() ) ){
<add> fieldList.add(0,propertys.get(key));
<add> }else{
<add> fieldList.add(propertys.get(key));
<add> }
<ide> }
<ide> article.setContent(JSONArray.fromObject(fieldList).toString());
<ide> return article;
<ide> }
<ide> List<DictionaryDto> fieldList = new ArrayList<DictionaryDto>();
<ide> for(String key: propertys.keySet()){
<del> fieldList.add(propertys.get(key));
<add> if( propertys.get(key).getFlag().equals( DictionaryPropertyType.primary.getName() )
<add> || propertys.get(key).getFlag().equals( DictionaryPropertyType.foreign.getName() )
<add> || propertys.get(key).getFlag().equals( DictionaryPropertyType.associate.getName() ) ){
<add> fieldList.add(0,propertys.get(key));
<add> }else{
<add> fieldList.add(propertys.get(key));
<add> }
<ide> }
<ide> article.setContent(JSONArray.fromObject(fieldList).toString());
<ide> return article;
|
|
Java
|
apache-2.0
|
2851806365330332f42fdc56d610eb20c8233233
| 0 |
weston100721/commons-lang,vanta/commons-lang,arbasha/commons-lang,weston100721/commons-lang,PascalSchumacher/commons-lang,jankill/commons-lang,apache/commons-lang,weston100721/commons-lang,vanta/commons-lang,mohanaraosv/commons-lang,suntengteng/commons-lang,MuShiiii/commons-lang,jankill/commons-lang,chaoyi66/commons-lang,longestname1/commonslang,jacktan1991/commons-lang,lovecindy/commons-lang,britter/commons-lang,Ajeet-Ganga/commons-lang,byMan/naya279,PascalSchumacher/commons-lang,britter/commons-lang,mohanaraosv/commons-lang,suntengteng/commons-lang,MuShiiii/commons-lang,britter/commons-lang,vanta/commons-lang,byMan/naya279,xiwc/commons-lang,longestname1/commonslang,apache/commons-lang,MarkDacek/commons-lang,xuerenlv/commons-lang,longestname1/commonslang,mohanaraosv/commons-lang,lovecindy/commons-lang,MuShiiii/commons-lang,chaoyi66/commons-lang,suntengteng/commons-lang,jacktan1991/commons-lang,xiwc/commons-lang,lovecindy/commons-lang,jankill/commons-lang,hollycroxton/commons-lang,PascalSchumacher/commons-lang,xiwc/commons-lang,MarkDacek/commons-lang,hollycroxton/commons-lang,byMan/naya279,hollycroxton/commons-lang,apache/commons-lang,xuerenlv/commons-lang,arbasha/commons-lang,xuerenlv/commons-lang,Ajeet-Ganga/commons-lang,Ajeet-Ganga/commons-lang,arbasha/commons-lang,chaoyi66/commons-lang,jacktan1991/commons-lang,MarkDacek/commons-lang
|
/*
* 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.commons.lang3.text;
import java.io.Reader;
import java.io.Writer;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.SystemUtils;
/**
* Builds a string from constituent parts providing a more flexible and powerful API
* than StringBuffer.
* <p>
* The main differences from StringBuffer/StringBuilder are:
* <ul>
* <li>Not synchronized</li>
* <li>Not final</li>
* <li>Subclasses have direct access to character array</li>
* <li>Additional methods
* <ul>
* <li>appendWithSeparators - adds an array of values, with a separator</li>
* <li>appendPadding - adds a length padding characters</li>
* <li>appendFixedLength - adds a fixed width field to the builder</li>
* <li>toCharArray/getChars - simpler ways to get a range of the character array</li>
* <li>delete - delete char or string</li>
* <li>replace - search and replace for a char or string</li>
* <li>leftString/rightString/midString - substring without exceptions</li>
* <li>contains - whether the builder contains a char or string</li>
* <li>size/clear/isEmpty - collections style API methods</li>
* </ul>
* </li>
* </ul>
* <li>Views
* <ul>
* <li>asTokenizer - uses the internal buffer as the source of a StrTokenizer</li>
* <li>asReader - uses the internal buffer as the source of a Reader</li>
* <li>asWriter - allows a Writer to write directly to the internal buffer</li>
* </ul>
* </li>
* </ul>
* <p>
* The aim has been to provide an API that mimics very closely what StringBuffer
* provides, but with additional methods. It should be noted that some edge cases,
* with invalid indices or null input, have been altered - see individual methods.
* The biggest of these changes is that by default, null will not output the text
* 'null'. This can be controlled by a property, {@link #setNullText(String)}.
* <p>
* Prior to 3.0, this class implemented Cloneable but did not implement the
* clone method so could not be used. From 3.0 onwards it no longer implements
* the interface.
*
* @author Apache Software Foundation
* @author Robert Scholte
* @since 2.2
* @version $Id$
*/
public class StrBuilder implements CharSequence, Appendable {
/**
* The extra capacity for new builders.
*/
static final int CAPACITY = 32;
/**
* Required for serialization support.
*
* @see java.io.Serializable
*/
private static final long serialVersionUID = 7628716375283629643L;
/** Internal data storage. */
protected char[] buffer; // TODO make private?
/** Current size of the buffer. */
protected int size; // TODO make private?
/** The new line. */
private String newLine;
/** The null text. */
private String nullText;
//-----------------------------------------------------------------------
/**
* Constructor that creates an empty builder initial capacity 32 characters.
*/
public StrBuilder() {
this(CAPACITY);
}
/**
* Constructor that creates an empty builder the specified initial capacity.
*
* @param initialCapacity the initial capacity, zero or less will be converted to 32
*/
public StrBuilder(int initialCapacity) {
super();
if (initialCapacity <= 0) {
initialCapacity = CAPACITY;
}
buffer = new char[initialCapacity];
}
/**
* Constructor that creates a builder from the string, allocating
* 32 extra characters for growth.
*
* @param str the string to copy, null treated as blank string
*/
public StrBuilder(String str) {
super();
if (str == null) {
buffer = new char[CAPACITY];
} else {
buffer = new char[str.length() + CAPACITY];
append(str);
}
}
//-----------------------------------------------------------------------
/**
* Gets the text to be appended when a new line is added.
*
* @return the new line text, null means use system default
*/
public String getNewLineText() {
return newLine;
}
/**
* Sets the text to be appended when a new line is added.
*
* @param newLine the new line text, null means use system default
* @return this, to enable chaining
*/
public StrBuilder setNewLineText(String newLine) {
this.newLine = newLine;
return this;
}
//-----------------------------------------------------------------------
/**
* Gets the text to be appended when null is added.
*
* @return the null text, null means no append
*/
public String getNullText() {
return nullText;
}
/**
* Sets the text to be appended when null is added.
*
* @param nullText the null text, null means no append
* @return this, to enable chaining
*/
public StrBuilder setNullText(String nullText) {
if (nullText != null && nullText.length() == 0) {
nullText = null;
}
this.nullText = nullText;
return this;
}
//-----------------------------------------------------------------------
/**
* Gets the length of the string builder.
*
* @return the length
*/
public int length() {
return size;
}
/**
* Updates the length of the builder by either dropping the last characters
* or adding filler of unicode zero.
*
* @param length the length to set to, must be zero or positive
* @return this, to enable chaining
* @throws IndexOutOfBoundsException if the length is negative
*/
public StrBuilder setLength(int length) {
if (length < 0) {
throw new StringIndexOutOfBoundsException(length);
}
if (length < size) {
size = length;
} else if (length > size) {
ensureCapacity(length);
int oldEnd = size;
int newEnd = length;
size = length;
for (int i = oldEnd; i < newEnd; i++) {
buffer[i] = '\0';
}
}
return this;
}
//-----------------------------------------------------------------------
/**
* Gets the current size of the internal character array buffer.
*
* @return the capacity
*/
public int capacity() {
return buffer.length;
}
/**
* Checks the capacity and ensures that it is at least the size specified.
*
* @param capacity the capacity to ensure
* @return this, to enable chaining
*/
public StrBuilder ensureCapacity(int capacity) {
if (capacity > buffer.length) {
char[] old = buffer;
buffer = new char[capacity * 2];
System.arraycopy(old, 0, buffer, 0, size);
}
return this;
}
/**
* Minimizes the capacity to the actual length of the string.
*
* @return this, to enable chaining
*/
public StrBuilder minimizeCapacity() {
if (buffer.length > length()) {
char[] old = buffer;
buffer = new char[length()];
System.arraycopy(old, 0, buffer, 0, size);
}
return this;
}
//-----------------------------------------------------------------------
/**
* Gets the length of the string builder.
* <p>
* This method is the same as {@link #length()} and is provided to match the
* API of Collections.
*
* @return the length
*/
public int size() {
return size;
}
/**
* Checks is the string builder is empty (convenience Collections API style method).
* <p>
* This method is the same as checking {@link #length()} and is provided to match the
* API of Collections.
*
* @return <code>true</code> if the size is <code>0</code>.
*/
public boolean isEmpty() {
return size == 0;
}
/**
* Clears the string builder (convenience Collections API style method).
* <p>
* This method does not reduce the size of the internal character buffer.
* To do that, call <code>clear()</code> followed by {@link #minimizeCapacity()}.
* <p>
* This method is the same as {@link #setLength(int)} called with zero
* and is provided to match the API of Collections.
*
* @return this, to enable chaining
*/
public StrBuilder clear() {
size = 0;
return this;
}
//-----------------------------------------------------------------------
/**
* Gets the character at the specified index.
*
* @see #setCharAt(int, char)
* @see #deleteCharAt(int)
* @param index the index to retrieve, must be valid
* @return the character at the index
* @throws IndexOutOfBoundsException if the index is invalid
*/
public char charAt(int index) {
if (index < 0 || index >= length()) {
throw new StringIndexOutOfBoundsException(index);
}
return buffer[index];
}
/**
* Sets the character at the specified index.
*
* @see #charAt(int)
* @see #deleteCharAt(int)
* @param index the index to set
* @param ch the new character
* @return this, to enable chaining
* @throws IndexOutOfBoundsException if the index is invalid
*/
public StrBuilder setCharAt(int index, char ch) {
if (index < 0 || index >= length()) {
throw new StringIndexOutOfBoundsException(index);
}
buffer[index] = ch;
return this;
}
/**
* Deletes the character at the specified index.
*
* @see #charAt(int)
* @see #setCharAt(int, char)
* @param index the index to delete
* @return this, to enable chaining
* @throws IndexOutOfBoundsException if the index is invalid
*/
public StrBuilder deleteCharAt(int index) {
if (index < 0 || index >= size) {
throw new StringIndexOutOfBoundsException(index);
}
deleteImpl(index, index + 1, 1);
return this;
}
//-----------------------------------------------------------------------
/**
* Copies the builder's character array into a new character array.
*
* @return a new array that represents the contents of the builder
*/
public char[] toCharArray() {
if (size == 0) {
return ArrayUtils.EMPTY_CHAR_ARRAY;
}
char chars[] = new char[size];
System.arraycopy(buffer, 0, chars, 0, size);
return chars;
}
/**
* Copies part of the builder's character array into a new character array.
*
* @param startIndex the start index, inclusive, must be valid
* @param endIndex the end index, exclusive, must be valid except that
* if too large it is treated as end of string
* @return a new array that holds part of the contents of the builder
* @throws IndexOutOfBoundsException if startIndex is invalid,
* or if endIndex is invalid (but endIndex greater than size is valid)
*/
public char[] toCharArray(int startIndex, int endIndex) {
endIndex = validateRange(startIndex, endIndex);
int len = endIndex - startIndex;
if (len == 0) {
return ArrayUtils.EMPTY_CHAR_ARRAY;
}
char chars[] = new char[len];
System.arraycopy(buffer, startIndex, chars, 0, len);
return chars;
}
/**
* Copies the character array into the specified array.
*
* @param destination the destination array, null will cause an array to be created
* @return the input array, unless that was null or too small
*/
public char[] getChars(char[] destination) {
int len = length();
if (destination == null || destination.length < len) {
destination = new char[len];
}
System.arraycopy(buffer, 0, destination, 0, len);
return destination;
}
/**
* Copies the character array into the specified array.
*
* @param startIndex first index to copy, inclusive, must be valid
* @param endIndex last index, exclusive, must be valid
* @param destination the destination array, must not be null or too small
* @param destinationIndex the index to start copying in destination
* @throws NullPointerException if the array is null
* @throws IndexOutOfBoundsException if any index is invalid
*/
public void getChars(int startIndex, int endIndex, char destination[], int destinationIndex) {
if (startIndex < 0) {
throw new StringIndexOutOfBoundsException(startIndex);
}
if (endIndex < 0 || endIndex > length()) {
throw new StringIndexOutOfBoundsException(endIndex);
}
if (startIndex > endIndex) {
throw new StringIndexOutOfBoundsException("end < start");
}
System.arraycopy(buffer, startIndex, destination, destinationIndex, endIndex - startIndex);
}
//-----------------------------------------------------------------------
/**
* Appends the new line string to this string builder.
* <p>
* The new line string can be altered using {@link #setNewLineText(String)}.
* This might be used to force the output to always use Unix line endings
* even when on Windows.
*
* @return this, to enable chaining
*/
public StrBuilder appendNewLine() {
if (newLine == null) {
append(SystemUtils.LINE_SEPARATOR);
return this;
}
return append(newLine);
}
/**
* Appends the text representing <code>null</code> to this string builder.
*
* @return this, to enable chaining
*/
public StrBuilder appendNull() {
if (nullText == null) {
return this;
}
return append(nullText);
}
/**
* Appends an object to this string builder.
* Appending null will call {@link #appendNull()}.
*
* @param obj the object to append
* @return this, to enable chaining
*/
public StrBuilder append(Object obj) {
if (obj == null) {
return appendNull();
}
return append(obj.toString());
}
/**
* Appends a CharSequence to this string builder.
* Appending null will call {@link #appendNull()}.
*
* @param seq the CharSequence to append
* @return this, to enable chaining
*/
public StrBuilder append(CharSequence seq) {
if (seq == null) {
return appendNull();
}
return append(seq.toString());
}
/**
* Appends part of a CharSequence to this string builder.
* Appending null will call {@link #appendNull()}.
*
* @param seq the CharSequence to append
* @param startIndex the start index, inclusive, must be valid
* @param length the length to append, must be valid
* @return this, to enable chaining
*/
public StrBuilder append(CharSequence seq, int startIndex, int length) {
if (seq == null) {
return appendNull();
}
return append(seq.toString(), startIndex, length);
}
/**
* Appends a string to this string builder.
* Appending null will call {@link #appendNull()}.
*
* @param str the string to append
* @return this, to enable chaining
*/
public StrBuilder append(String str) {
if (str == null) {
return appendNull();
}
int strLen = str.length();
if (strLen > 0) {
int len = length();
ensureCapacity(len + strLen);
str.getChars(0, strLen, buffer, len);
size += strLen;
}
return this;
}
/**
* Appends part of a string to this string builder.
* Appending null will call {@link #appendNull()}.
*
* @param str the string to append
* @param startIndex the start index, inclusive, must be valid
* @param length the length to append, must be valid
* @return this, to enable chaining
*/
public StrBuilder append(String str, int startIndex, int length) {
if (str == null) {
return appendNull();
}
if (startIndex < 0 || startIndex > str.length()) {
throw new StringIndexOutOfBoundsException("startIndex must be valid");
}
if (length < 0 || (startIndex + length) > str.length()) {
throw new StringIndexOutOfBoundsException("length must be valid");
}
if (length > 0) {
int len = length();
ensureCapacity(len + length);
str.getChars(startIndex, startIndex + length, buffer, len);
size += length;
}
return this;
}
/**
* Appends a string buffer to this string builder.
* Appending null will call {@link #appendNull()}.
*
* @param str the string buffer to append
* @return this, to enable chaining
*/
public StrBuilder append(StringBuffer str) {
if (str == null) {
return appendNull();
}
int strLen = str.length();
if (strLen > 0) {
int len = length();
ensureCapacity(len + strLen);
str.getChars(0, strLen, buffer, len);
size += strLen;
}
return this;
}
/**
* Appends part of a string buffer to this string builder.
* Appending null will call {@link #appendNull()}.
*
* @param str the string to append
* @param startIndex the start index, inclusive, must be valid
* @param length the length to append, must be valid
* @return this, to enable chaining
*/
public StrBuilder append(StringBuffer str, int startIndex, int length) {
if (str == null) {
return appendNull();
}
if (startIndex < 0 || startIndex > str.length()) {
throw new StringIndexOutOfBoundsException("startIndex must be valid");
}
if (length < 0 || (startIndex + length) > str.length()) {
throw new StringIndexOutOfBoundsException("length must be valid");
}
if (length > 0) {
int len = length();
ensureCapacity(len + length);
str.getChars(startIndex, startIndex + length, buffer, len);
size += length;
}
return this;
}
/**
* Appends another string builder to this string builder.
* Appending null will call {@link #appendNull()}.
*
* @param str the string builder to append
* @return this, to enable chaining
*/
public StrBuilder append(StrBuilder str) {
if (str == null) {
return appendNull();
}
int strLen = str.length();
if (strLen > 0) {
int len = length();
ensureCapacity(len + strLen);
System.arraycopy(str.buffer, 0, buffer, len, strLen);
size += strLen;
}
return this;
}
/**
* Appends part of a string builder to this string builder.
* Appending null will call {@link #appendNull()}.
*
* @param str the string to append
* @param startIndex the start index, inclusive, must be valid
* @param length the length to append, must be valid
* @return this, to enable chaining
*/
public StrBuilder append(StrBuilder str, int startIndex, int length) {
if (str == null) {
return appendNull();
}
if (startIndex < 0 || startIndex > str.length()) {
throw new StringIndexOutOfBoundsException("startIndex must be valid");
}
if (length < 0 || (startIndex + length) > str.length()) {
throw new StringIndexOutOfBoundsException("length must be valid");
}
if (length > 0) {
int len = length();
ensureCapacity(len + length);
str.getChars(startIndex, startIndex + length, buffer, len);
size += length;
}
return this;
}
/**
* Appends a char array to the string builder.
* Appending null will call {@link #appendNull()}.
*
* @param chars the char array to append
* @return this, to enable chaining
*/
public StrBuilder append(char[] chars) {
if (chars == null) {
return appendNull();
}
int strLen = chars.length;
if (strLen > 0) {
int len = length();
ensureCapacity(len + strLen);
System.arraycopy(chars, 0, buffer, len, strLen);
size += strLen;
}
return this;
}
/**
* Appends a char array to the string builder.
* Appending null will call {@link #appendNull()}.
*
* @param chars the char array to append
* @param startIndex the start index, inclusive, must be valid
* @param length the length to append, must be valid
* @return this, to enable chaining
*/
public StrBuilder append(char[] chars, int startIndex, int length) {
if (chars == null) {
return appendNull();
}
if (startIndex < 0 || startIndex > chars.length) {
throw new StringIndexOutOfBoundsException("Invalid startIndex: " + length);
}
if (length < 0 || (startIndex + length) > chars.length) {
throw new StringIndexOutOfBoundsException("Invalid length: " + length);
}
if (length > 0) {
int len = length();
ensureCapacity(len + length);
System.arraycopy(chars, startIndex, buffer, len, length);
size += length;
}
return this;
}
/**
* Appends a boolean value to the string builder.
*
* @param value the value to append
* @return this, to enable chaining
*/
public StrBuilder append(boolean value) {
if (value) {
ensureCapacity(size + 4);
buffer[size++] = 't';
buffer[size++] = 'r';
buffer[size++] = 'u';
buffer[size++] = 'e';
} else {
ensureCapacity(size + 5);
buffer[size++] = 'f';
buffer[size++] = 'a';
buffer[size++] = 'l';
buffer[size++] = 's';
buffer[size++] = 'e';
}
return this;
}
/**
* Appends a char value to the string builder.
*
* @param ch the value to append
* @return this, to enable chaining
*/
public StrBuilder append(char ch) {
int len = length();
ensureCapacity(len + 1);
buffer[size++] = ch;
return this;
}
/**
* Appends an int value to the string builder using <code>String.valueOf</code>.
*
* @param value the value to append
* @return this, to enable chaining
*/
public StrBuilder append(int value) {
return append(String.valueOf(value));
}
/**
* Appends a long value to the string builder using <code>String.valueOf</code>.
*
* @param value the value to append
* @return this, to enable chaining
*/
public StrBuilder append(long value) {
return append(String.valueOf(value));
}
/**
* Appends a float value to the string builder using <code>String.valueOf</code>.
*
* @param value the value to append
* @return this, to enable chaining
*/
public StrBuilder append(float value) {
return append(String.valueOf(value));
}
/**
* Appends a double value to the string builder using <code>String.valueOf</code>.
*
* @param value the value to append
* @return this, to enable chaining
*/
public StrBuilder append(double value) {
return append(String.valueOf(value));
}
//-----------------------------------------------------------------------
/**
* Appends an object followed by a new line to this string builder.
* Appending null will call {@link #appendNull()}.
*
* @param obj the object to append
* @return this, to enable chaining
* @since 2.3
*/
public StrBuilder appendln(Object obj) {
return append(obj).appendNewLine();
}
/**
* Appends a string followed by a new line to this string builder.
* Appending null will call {@link #appendNull()}.
*
* @param str the string to append
* @return this, to enable chaining
* @since 2.3
*/
public StrBuilder appendln(String str) {
return append(str).appendNewLine();
}
/**
* Appends part of a string followed by a new line to this string builder.
* Appending null will call {@link #appendNull()}.
*
* @param str the string to append
* @param startIndex the start index, inclusive, must be valid
* @param length the length to append, must be valid
* @return this, to enable chaining
* @since 2.3
*/
public StrBuilder appendln(String str, int startIndex, int length) {
return append(str, startIndex, length).appendNewLine();
}
/**
* Appends a string buffer followed by a new line to this string builder.
* Appending null will call {@link #appendNull()}.
*
* @param str the string buffer to append
* @return this, to enable chaining
* @since 2.3
*/
public StrBuilder appendln(StringBuffer str) {
return append(str).appendNewLine();
}
/**
* Appends part of a string buffer followed by a new line to this string builder.
* Appending null will call {@link #appendNull()}.
*
* @param str the string to append
* @param startIndex the start index, inclusive, must be valid
* @param length the length to append, must be valid
* @return this, to enable chaining
* @since 2.3
*/
public StrBuilder appendln(StringBuffer str, int startIndex, int length) {
return append(str, startIndex, length).appendNewLine();
}
/**
* Appends another string builder followed by a new line to this string builder.
* Appending null will call {@link #appendNull()}.
*
* @param str the string builder to append
* @return this, to enable chaining
* @since 2.3
*/
public StrBuilder appendln(StrBuilder str) {
return append(str).appendNewLine();
}
/**
* Appends part of a string builder followed by a new line to this string builder.
* Appending null will call {@link #appendNull()}.
*
* @param str the string to append
* @param startIndex the start index, inclusive, must be valid
* @param length the length to append, must be valid
* @return this, to enable chaining
* @since 2.3
*/
public StrBuilder appendln(StrBuilder str, int startIndex, int length) {
return append(str, startIndex, length).appendNewLine();
}
/**
* Appends a char array followed by a new line to the string builder.
* Appending null will call {@link #appendNull()}.
*
* @param chars the char array to append
* @return this, to enable chaining
* @since 2.3
*/
public StrBuilder appendln(char[] chars) {
return append(chars).appendNewLine();
}
/**
* Appends a char array followed by a new line to the string builder.
* Appending null will call {@link #appendNull()}.
*
* @param chars the char array to append
* @param startIndex the start index, inclusive, must be valid
* @param length the length to append, must be valid
* @return this, to enable chaining
* @since 2.3
*/
public StrBuilder appendln(char[] chars, int startIndex, int length) {
return append(chars, startIndex, length).appendNewLine();
}
/**
* Appends a boolean value followed by a new line to the string builder.
*
* @param value the value to append
* @return this, to enable chaining
* @since 2.3
*/
public StrBuilder appendln(boolean value) {
return append(value).appendNewLine();
}
/**
* Appends a char value followed by a new line to the string builder.
*
* @param ch the value to append
* @return this, to enable chaining
* @since 2.3
*/
public StrBuilder appendln(char ch) {
return append(ch).appendNewLine();
}
/**
* Appends an int value followed by a new line to the string builder using <code>String.valueOf</code>.
*
* @param value the value to append
* @return this, to enable chaining
* @since 2.3
*/
public StrBuilder appendln(int value) {
return append(value).appendNewLine();
}
/**
* Appends a long value followed by a new line to the string builder using <code>String.valueOf</code>.
*
* @param value the value to append
* @return this, to enable chaining
* @since 2.3
*/
public StrBuilder appendln(long value) {
return append(value).appendNewLine();
}
/**
* Appends a float value followed by a new line to the string builder using <code>String.valueOf</code>.
*
* @param value the value to append
* @return this, to enable chaining
* @since 2.3
*/
public StrBuilder appendln(float value) {
return append(value).appendNewLine();
}
/**
* Appends a double value followed by a new line to the string builder using <code>String.valueOf</code>.
*
* @param value the value to append
* @return this, to enable chaining
* @since 2.3
*/
public StrBuilder appendln(double value) {
return append(value).appendNewLine();
}
//-----------------------------------------------------------------------
/**
* Appends each item in an array to the builder without any separators.
* Appending a null array will have no effect.
* Each object is appended using {@link #append(Object)}.
*
* @param array the array to append
* @return this, to enable chaining
* @since 2.3
*/
public StrBuilder appendAll(Object[] array) {
if (array != null && array.length > 0) {
for (int i = 0; i < array.length; i++) {
append(array[i]);
}
}
return this;
}
/**
* Appends each item in a iterable to the builder without any separators.
* Appending a null iterable will have no effect.
* Each object is appended using {@link #append(Object)}.
*
* @param iterable the iterable to append
* @return this, to enable chaining
* @since 2.3
*/
public StrBuilder appendAll(Iterable<?> iterable) {
if (iterable != null) {
Iterator<?> it = iterable.iterator();
while (it.hasNext()) {
append(it.next());
}
}
return this;
}
/**
* Appends each item in an iterator to the builder without any separators.
* Appending a null iterator will have no effect.
* Each object is appended using {@link #append(Object)}.
*
* @param it the iterator to append
* @return this, to enable chaining
* @since 2.3
*/
public StrBuilder appendAll(Iterator<?> it) {
if (it != null) {
while (it.hasNext()) {
append(it.next());
}
}
return this;
}
//-----------------------------------------------------------------------
/**
* Appends an array placing separators between each value, but
* not before the first or after the last.
* Appending a null array will have no effect.
* Each object is appended using {@link #append(Object)}.
*
* @param array the array to append
* @param separator the separator to use, null means no separator
* @return this, to enable chaining
*/
public StrBuilder appendWithSeparators(Object[] array, String separator) {
if (array != null && array.length > 0) {
separator = (separator == null ? "" : separator);
append(array[0]);
for (int i = 1; i < array.length; i++) {
append(separator);
append(array[i]);
}
}
return this;
}
/**
* Appends a iterable placing separators between each value, but
* not before the first or after the last.
* Appending a null iterable will have no effect.
* Each object is appended using {@link #append(Object)}.
*
* @param iterable the iterable to append
* @param separator the separator to use, null means no separator
* @return this, to enable chaining
*/
public StrBuilder appendWithSeparators(Iterable<?> iterable, String separator) {
if (iterable != null) {
separator = (separator == null ? "" : separator);
Iterator<?> it = iterable.iterator();
while (it.hasNext()) {
append(it.next());
if (it.hasNext()) {
append(separator);
}
}
}
return this;
}
/**
* Appends an iterator placing separators between each value, but
* not before the first or after the last.
* Appending a null iterator will have no effect.
* Each object is appended using {@link #append(Object)}.
*
* @param it the iterator to append
* @param separator the separator to use, null means no separator
* @return this, to enable chaining
*/
public StrBuilder appendWithSeparators(Iterator<?> it, String separator) {
if (it != null) {
separator = (separator == null ? "" : separator);
while (it.hasNext()) {
append(it.next());
if (it.hasNext()) {
append(separator);
}
}
}
return this;
}
//-----------------------------------------------------------------------
/**
* Appends a separator if the builder is currently non-empty.
* Appending a null separator will have no effect.
* The separator is appended using {@link #append(String)}.
* <p>
* This method is useful for adding a separator each time around the
* loop except the first.
* <pre>
* for (Iterator it = list.iterator(); it.hasNext(); ) {
* appendSeparator(",");
* append(it.next());
* }
* </pre>
* Note that for this simple example, you should use
* {@link #appendWithSeparators(Collection, String)}.
*
* @param separator the separator to use, null means no separator
* @return this, to enable chaining
* @since 2.3
*/
public StrBuilder appendSeparator(String separator) {
return appendSeparator(separator, null);
}
/**
* Appends one of both separators to the StrBuilder.
* If the builder is currently empty it will append the defaultIfEmpty-separator
* Otherwise it will append the standard-separator
*
* Appending a null separator will have no effect.
* The separator is appended using {@link #append(String)}.
* <p>
* This method is for example useful for constructing queries
* <pre>
* StrBuilder whereClause = new StrBuilder();
* if(searchCommand.getPriority() != null) {
* whereClause.appendSeparator(" and", " where");
* whereClause.append(" priority = ?")
* }
* if(searchCommand.getComponent() != null) {
* whereClause.appendSeparator(" and", " where");
* whereClause.append(" component = ?")
* }
* selectClause.append(whereClause)
* </pre>
*
* @param standard the separator if builder is not empty, null means no separator
* @param defaultIfEmpty the separator if builder is empty, null means no separator
* @return this, to enable chaining
* @since 3.0
*/
public StrBuilder appendSeparator(String standard, String defaultIfEmpty) {
String str = isEmpty() ? defaultIfEmpty : standard;
if (str != null) {
append(str);
}
return this;
}
/**
* Appends a separator if the builder is currently non-empty.
* The separator is appended using {@link #append(char)}.
* <p>
* This method is useful for adding a separator each time around the
* loop except the first.
* <pre>
* for (Iterator it = list.iterator(); it.hasNext(); ) {
* appendSeparator(',');
* append(it.next());
* }
* </pre>
* Note that for this simple example, you should use
* {@link #appendWithSeparators(Collection, String)}.
*
* @param separator the separator to use
* @return this, to enable chaining
* @since 2.3
*/
public StrBuilder appendSeparator(char separator) {
if (size() > 0) {
append(separator);
}
return this;
}
/**
* Append one of both separators to the builder
* If the builder is currently empty it will append the defaultIfEmpty-separator
* Otherwise it will append the standard-separator
*
* The separator is appended using {@link #append(char)}.
* @param standard the separator if builder is not empty
* @param defaultIfEmpty the separator if builder is empty
* @return this, to enable chaining
* @since 3.0
*/
public StrBuilder appendSeparator(char standard, char defaultIfEmpty) {
if (size() > 0) {
append(standard);
}
else {
append(defaultIfEmpty);
}
return this;
}
/**
* Appends a separator to the builder if the loop index is greater than zero.
* Appending a null separator will have no effect.
* The separator is appended using {@link #append(String)}.
* <p>
* This method is useful for adding a separator each time around the
* loop except the first.
* <pre>
* for (int i = 0; i < list.size(); i++) {
* appendSeparator(",", i);
* append(list.get(i));
* }
* </pre>
* Note that for this simple example, you should use
* {@link #appendWithSeparators(Collection, String)}.
*
* @param separator the separator to use, null means no separator
* @param loopIndex the loop index
* @return this, to enable chaining
* @since 2.3
*/
public StrBuilder appendSeparator(String separator, int loopIndex) {
if (separator != null && loopIndex > 0) {
append(separator);
}
return this;
}
/**
* Appends a separator to the builder if the loop index is greater than zero.
* The separator is appended using {@link #append(char)}.
* <p>
* This method is useful for adding a separator each time around the
* loop except the first.
* <pre>
* for (int i = 0; i < list.size(); i++) {
* appendSeparator(",", i);
* append(list.get(i));
* }
* </pre>
* Note that for this simple example, you should use
* {@link #appendWithSeparators(Collection, String)}.
*
* @param separator the separator to use
* @param loopIndex the loop index
* @return this, to enable chaining
* @since 2.3
*/
public StrBuilder appendSeparator(char separator, int loopIndex) {
if (loopIndex > 0) {
append(separator);
}
return this;
}
//-----------------------------------------------------------------------
/**
* Appends the pad character to the builder the specified number of times.
*
* @param length the length to append, negative means no append
* @param padChar the character to append
* @return this, to enable chaining
*/
public StrBuilder appendPadding(int length, char padChar) {
if (length >= 0) {
ensureCapacity(size + length);
for (int i = 0; i < length; i++) {
buffer[size++] = padChar;
}
}
return this;
}
//-----------------------------------------------------------------------
/**
* Appends an object to the builder padding on the left to a fixed width.
* The <code>toString</code> of the object is used.
* If the object is larger than the length, the left hand side is lost.
* If the object is null, the null text value is used.
*
* @param obj the object to append, null uses null text
* @param width the fixed field width, zero or negative has no effect
* @param padChar the pad character to use
* @return this, to enable chaining
*/
public StrBuilder appendFixedWidthPadLeft(Object obj, int width, char padChar) {
if (width > 0) {
ensureCapacity(size + width);
String str = (obj == null ? getNullText() : obj.toString());
if (str == null) {
str = "";
}
int strLen = str.length();
if (strLen >= width) {
str.getChars(strLen - width, strLen, buffer, size);
} else {
int padLen = width - strLen;
for (int i = 0; i < padLen; i++) {
buffer[size + i] = padChar;
}
str.getChars(0, strLen, buffer, size + padLen);
}
size += width;
}
return this;
}
/**
* Appends an object to the builder padding on the left to a fixed width.
* The <code>String.valueOf</code> of the <code>int</code> value is used.
* If the formatted value is larger than the length, the left hand side is lost.
*
* @param value the value to append
* @param width the fixed field width, zero or negative has no effect
* @param padChar the pad character to use
* @return this, to enable chaining
*/
public StrBuilder appendFixedWidthPadLeft(int value, int width, char padChar) {
return appendFixedWidthPadLeft(String.valueOf(value), width, padChar);
}
/**
* Appends an object to the builder padding on the right to a fixed length.
* The <code>toString</code> of the object is used.
* If the object is larger than the length, the right hand side is lost.
* If the object is null, null text value is used.
*
* @param obj the object to append, null uses null text
* @param width the fixed field width, zero or negative has no effect
* @param padChar the pad character to use
* @return this, to enable chaining
*/
public StrBuilder appendFixedWidthPadRight(Object obj, int width, char padChar) {
if (width > 0) {
ensureCapacity(size + width);
String str = (obj == null ? getNullText() : obj.toString());
if (str == null) {
str = "";
}
int strLen = str.length();
if (strLen >= width) {
str.getChars(0, width, buffer, size);
} else {
int padLen = width - strLen;
str.getChars(0, strLen, buffer, size);
for (int i = 0; i < padLen; i++) {
buffer[size + strLen + i] = padChar;
}
}
size += width;
}
return this;
}
/**
* Appends an object to the builder padding on the right to a fixed length.
* The <code>String.valueOf</code> of the <code>int</code> value is used.
* If the object is larger than the length, the right hand side is lost.
*
* @param value the value to append
* @param width the fixed field width, zero or negative has no effect
* @param padChar the pad character to use
* @return this, to enable chaining
*/
public StrBuilder appendFixedWidthPadRight(int value, int width, char padChar) {
return appendFixedWidthPadRight(String.valueOf(value), width, padChar);
}
//-----------------------------------------------------------------------
/**
* Inserts the string representation of an object into this builder.
* Inserting null will use the stored null text value.
*
* @param index the index to add at, must be valid
* @param obj the object to insert
* @return this, to enable chaining
* @throws IndexOutOfBoundsException if the index is invalid
*/
public StrBuilder insert(int index, Object obj) {
if (obj == null) {
return insert(index, nullText);
}
return insert(index, obj.toString());
}
/**
* Inserts the string into this builder.
* Inserting null will use the stored null text value.
*
* @param index the index to add at, must be valid
* @param str the string to insert
* @return this, to enable chaining
* @throws IndexOutOfBoundsException if the index is invalid
*/
@SuppressWarnings("null") // str cannot be null
public StrBuilder insert(int index, String str) {
validateIndex(index);
if (str == null) {
str = nullText;
}
int strLen = (str == null ? 0 : str.length());
if (strLen > 0) {
int newSize = size + strLen;
ensureCapacity(newSize);
System.arraycopy(buffer, index, buffer, index + strLen, size - index);
size = newSize;
str.getChars(0, strLen, buffer, index); // str cannot be null here
}
return this;
}
/**
* Inserts the character array into this builder.
* Inserting null will use the stored null text value.
*
* @param index the index to add at, must be valid
* @param chars the char array to insert
* @return this, to enable chaining
* @throws IndexOutOfBoundsException if the index is invalid
*/
public StrBuilder insert(int index, char chars[]) {
validateIndex(index);
if (chars == null) {
return insert(index, nullText);
}
int len = chars.length;
if (len > 0) {
ensureCapacity(size + len);
System.arraycopy(buffer, index, buffer, index + len, size - index);
System.arraycopy(chars, 0, buffer, index, len);
size += len;
}
return this;
}
/**
* Inserts part of the character array into this builder.
* Inserting null will use the stored null text value.
*
* @param index the index to add at, must be valid
* @param chars the char array to insert
* @param offset the offset into the character array to start at, must be valid
* @param length the length of the character array part to copy, must be positive
* @return this, to enable chaining
* @throws IndexOutOfBoundsException if any index is invalid
*/
public StrBuilder insert(int index, char chars[], int offset, int length) {
validateIndex(index);
if (chars == null) {
return insert(index, nullText);
}
if (offset < 0 || offset > chars.length) {
throw new StringIndexOutOfBoundsException("Invalid offset: " + offset);
}
if (length < 0 || offset + length > chars.length) {
throw new StringIndexOutOfBoundsException("Invalid length: " + length);
}
if (length > 0) {
ensureCapacity(size + length);
System.arraycopy(buffer, index, buffer, index + length, size - index);
System.arraycopy(chars, offset, buffer, index, length);
size += length;
}
return this;
}
/**
* Inserts the value into this builder.
*
* @param index the index to add at, must be valid
* @param value the value to insert
* @return this, to enable chaining
* @throws IndexOutOfBoundsException if the index is invalid
*/
public StrBuilder insert(int index, boolean value) {
validateIndex(index);
if (value) {
ensureCapacity(size + 4);
System.arraycopy(buffer, index, buffer, index + 4, size - index);
buffer[index++] = 't';
buffer[index++] = 'r';
buffer[index++] = 'u';
buffer[index] = 'e';
size += 4;
} else {
ensureCapacity(size + 5);
System.arraycopy(buffer, index, buffer, index + 5, size - index);
buffer[index++] = 'f';
buffer[index++] = 'a';
buffer[index++] = 'l';
buffer[index++] = 's';
buffer[index] = 'e';
size += 5;
}
return this;
}
/**
* Inserts the value into this builder.
*
* @param index the index to add at, must be valid
* @param value the value to insert
* @return this, to enable chaining
* @throws IndexOutOfBoundsException if the index is invalid
*/
public StrBuilder insert(int index, char value) {
validateIndex(index);
ensureCapacity(size + 1);
System.arraycopy(buffer, index, buffer, index + 1, size - index);
buffer[index] = value;
size++;
return this;
}
/**
* Inserts the value into this builder.
*
* @param index the index to add at, must be valid
* @param value the value to insert
* @return this, to enable chaining
* @throws IndexOutOfBoundsException if the index is invalid
*/
public StrBuilder insert(int index, int value) {
return insert(index, String.valueOf(value));
}
/**
* Inserts the value into this builder.
*
* @param index the index to add at, must be valid
* @param value the value to insert
* @return this, to enable chaining
* @throws IndexOutOfBoundsException if the index is invalid
*/
public StrBuilder insert(int index, long value) {
return insert(index, String.valueOf(value));
}
/**
* Inserts the value into this builder.
*
* @param index the index to add at, must be valid
* @param value the value to insert
* @return this, to enable chaining
* @throws IndexOutOfBoundsException if the index is invalid
*/
public StrBuilder insert(int index, float value) {
return insert(index, String.valueOf(value));
}
/**
* Inserts the value into this builder.
*
* @param index the index to add at, must be valid
* @param value the value to insert
* @return this, to enable chaining
* @throws IndexOutOfBoundsException if the index is invalid
*/
public StrBuilder insert(int index, double value) {
return insert(index, String.valueOf(value));
}
//-----------------------------------------------------------------------
/**
* Internal method to delete a range without validation.
*
* @param startIndex the start index, must be valid
* @param endIndex the end index (exclusive), must be valid
* @param len the length, must be valid
* @throws IndexOutOfBoundsException if any index is invalid
*/
private void deleteImpl(int startIndex, int endIndex, int len) {
System.arraycopy(buffer, endIndex, buffer, startIndex, size - endIndex);
size -= len;
}
/**
* Deletes the characters between the two specified indices.
*
* @param startIndex the start index, inclusive, must be valid
* @param endIndex the end index, exclusive, must be valid except
* that if too large it is treated as end of string
* @return this, to enable chaining
* @throws IndexOutOfBoundsException if the index is invalid
*/
public StrBuilder delete(int startIndex, int endIndex) {
endIndex = validateRange(startIndex, endIndex);
int len = endIndex - startIndex;
if (len > 0) {
deleteImpl(startIndex, endIndex, len);
}
return this;
}
//-----------------------------------------------------------------------
/**
* Deletes the character wherever it occurs in the builder.
*
* @param ch the character to delete
* @return this, to enable chaining
*/
public StrBuilder deleteAll(char ch) {
for (int i = 0; i < size; i++) {
if (buffer[i] == ch) {
int start = i;
while (++i < size) {
if (buffer[i] != ch) {
break;
}
}
int len = i - start;
deleteImpl(start, i, len);
i -= len;
}
}
return this;
}
/**
* Deletes the character wherever it occurs in the builder.
*
* @param ch the character to delete
* @return this, to enable chaining
*/
public StrBuilder deleteFirst(char ch) {
for (int i = 0; i < size; i++) {
if (buffer[i] == ch) {
deleteImpl(i, i + 1, 1);
break;
}
}
return this;
}
//-----------------------------------------------------------------------
/**
* Deletes the string wherever it occurs in the builder.
*
* @param str the string to delete, null causes no action
* @return this, to enable chaining
*/
public StrBuilder deleteAll(String str) {
int len = (str == null ? 0 : str.length());
if (len > 0) {
int index = indexOf(str, 0);
while (index >= 0) {
deleteImpl(index, index + len, len);
index = indexOf(str, index);
}
}
return this;
}
/**
* Deletes the string wherever it occurs in the builder.
*
* @param str the string to delete, null causes no action
* @return this, to enable chaining
*/
public StrBuilder deleteFirst(String str) {
int len = (str == null ? 0 : str.length());
if (len > 0) {
int index = indexOf(str, 0);
if (index >= 0) {
deleteImpl(index, index + len, len);
}
}
return this;
}
//-----------------------------------------------------------------------
/**
* Deletes all parts of the builder that the matcher matches.
* <p>
* Matchers can be used to perform advanced deletion behaviour.
* For example you could write a matcher to delete all occurances
* where the character 'a' is followed by a number.
*
* @param matcher the matcher to use to find the deletion, null causes no action
* @return this, to enable chaining
*/
public StrBuilder deleteAll(StrMatcher matcher) {
return replace(matcher, null, 0, size, -1);
}
/**
* Deletes the first match within the builder using the specified matcher.
* <p>
* Matchers can be used to perform advanced deletion behaviour.
* For example you could write a matcher to delete
* where the character 'a' is followed by a number.
*
* @param matcher the matcher to use to find the deletion, null causes no action
* @return this, to enable chaining
*/
public StrBuilder deleteFirst(StrMatcher matcher) {
return replace(matcher, null, 0, size, 1);
}
//-----------------------------------------------------------------------
/**
* Internal method to delete a range without validation.
*
* @param startIndex the start index, must be valid
* @param endIndex the end index (exclusive), must be valid
* @param removeLen the length to remove (endIndex - startIndex), must be valid
* @param insertStr the string to replace with, null means delete range
* @param insertLen the length of the insert string, must be valid
* @throws IndexOutOfBoundsException if any index is invalid
*/
private void replaceImpl(int startIndex, int endIndex, int removeLen, String insertStr, int insertLen) {
int newSize = size - removeLen + insertLen;
if (insertLen != removeLen) {
ensureCapacity(newSize);
System.arraycopy(buffer, endIndex, buffer, startIndex + insertLen, size - endIndex);
size = newSize;
}
if (insertLen > 0) {
insertStr.getChars(0, insertLen, buffer, startIndex);
}
}
/**
* Replaces a portion of the string builder with another string.
* The length of the inserted string does not have to match the removed length.
*
* @param startIndex the start index, inclusive, must be valid
* @param endIndex the end index, exclusive, must be valid except
* that if too large it is treated as end of string
* @param replaceStr the string to replace with, null means delete range
* @return this, to enable chaining
* @throws IndexOutOfBoundsException if the index is invalid
*/
public StrBuilder replace(int startIndex, int endIndex, String replaceStr) {
endIndex = validateRange(startIndex, endIndex);
int insertLen = (replaceStr == null ? 0 : replaceStr.length());
replaceImpl(startIndex, endIndex, endIndex - startIndex, replaceStr, insertLen);
return this;
}
//-----------------------------------------------------------------------
/**
* Replaces the search character with the replace character
* throughout the builder.
*
* @param search the search character
* @param replace the replace character
* @return this, to enable chaining
*/
public StrBuilder replaceAll(char search, char replace) {
if (search != replace) {
for (int i = 0; i < size; i++) {
if (buffer[i] == search) {
buffer[i] = replace;
}
}
}
return this;
}
/**
* Replaces the first instance of the search character with the
* replace character in the builder.
*
* @param search the search character
* @param replace the replace character
* @return this, to enable chaining
*/
public StrBuilder replaceFirst(char search, char replace) {
if (search != replace) {
for (int i = 0; i < size; i++) {
if (buffer[i] == search) {
buffer[i] = replace;
break;
}
}
}
return this;
}
//-----------------------------------------------------------------------
/**
* Replaces the search string with the replace string throughout the builder.
*
* @param searchStr the search string, null causes no action to occur
* @param replaceStr the replace string, null is equivalent to an empty string
* @return this, to enable chaining
*/
public StrBuilder replaceAll(String searchStr, String replaceStr) {
int searchLen = (searchStr == null ? 0 : searchStr.length());
if (searchLen > 0) {
int replaceLen = (replaceStr == null ? 0 : replaceStr.length());
int index = indexOf(searchStr, 0);
while (index >= 0) {
replaceImpl(index, index + searchLen, searchLen, replaceStr, replaceLen);
index = indexOf(searchStr, index + replaceLen);
}
}
return this;
}
/**
* Replaces the first instance of the search string with the replace string.
*
* @param searchStr the search string, null causes no action to occur
* @param replaceStr the replace string, null is equivalent to an empty string
* @return this, to enable chaining
*/
public StrBuilder replaceFirst(String searchStr, String replaceStr) {
int searchLen = (searchStr == null ? 0 : searchStr.length());
if (searchLen > 0) {
int index = indexOf(searchStr, 0);
if (index >= 0) {
int replaceLen = (replaceStr == null ? 0 : replaceStr.length());
replaceImpl(index, index + searchLen, searchLen, replaceStr, replaceLen);
}
}
return this;
}
//-----------------------------------------------------------------------
/**
* Replaces all matches within the builder with the replace string.
* <p>
* Matchers can be used to perform advanced replace behaviour.
* For example you could write a matcher to replace all occurances
* where the character 'a' is followed by a number.
*
* @param matcher the matcher to use to find the deletion, null causes no action
* @param replaceStr the replace string, null is equivalent to an empty string
* @return this, to enable chaining
*/
public StrBuilder replaceAll(StrMatcher matcher, String replaceStr) {
return replace(matcher, replaceStr, 0, size, -1);
}
/**
* Replaces the first match within the builder with the replace string.
* <p>
* Matchers can be used to perform advanced replace behaviour.
* For example you could write a matcher to replace
* where the character 'a' is followed by a number.
*
* @param matcher the matcher to use to find the deletion, null causes no action
* @param replaceStr the replace string, null is equivalent to an empty string
* @return this, to enable chaining
*/
public StrBuilder replaceFirst(StrMatcher matcher, String replaceStr) {
return replace(matcher, replaceStr, 0, size, 1);
}
// -----------------------------------------------------------------------
/**
* Advanced search and replaces within the builder using a matcher.
* <p>
* Matchers can be used to perform advanced behaviour.
* For example you could write a matcher to delete all occurances
* where the character 'a' is followed by a number.
*
* @param matcher the matcher to use to find the deletion, null causes no action
* @param replaceStr the string to replace the match with, null is a delete
* @param startIndex the start index, inclusive, must be valid
* @param endIndex the end index, exclusive, must be valid except
* that if too large it is treated as end of string
* @param replaceCount the number of times to replace, -1 for replace all
* @return this, to enable chaining
* @throws IndexOutOfBoundsException if start index is invalid
*/
public StrBuilder replace(
StrMatcher matcher, String replaceStr,
int startIndex, int endIndex, int replaceCount) {
endIndex = validateRange(startIndex, endIndex);
return replaceImpl(matcher, replaceStr, startIndex, endIndex, replaceCount);
}
/**
* Replaces within the builder using a matcher.
* <p>
* Matchers can be used to perform advanced behaviour.
* For example you could write a matcher to delete all occurances
* where the character 'a' is followed by a number.
*
* @param matcher the matcher to use to find the deletion, null causes no action
* @param replaceStr the string to replace the match with, null is a delete
* @param from the start index, must be valid
* @param to the end index (exclusive), must be valid
* @param replaceCount the number of times to replace, -1 for replace all
* @return this, to enable chaining
* @throws IndexOutOfBoundsException if any index is invalid
*/
private StrBuilder replaceImpl(
StrMatcher matcher, String replaceStr,
int from, int to, int replaceCount) {
if (matcher == null || size == 0) {
return this;
}
int replaceLen = (replaceStr == null ? 0 : replaceStr.length());
char[] buf = buffer;
for (int i = from; i < to && replaceCount != 0; i++) {
int removeLen = matcher.isMatch(buf, i, from, to);
if (removeLen > 0) {
replaceImpl(i, i + removeLen, removeLen, replaceStr, replaceLen);
to = to - removeLen + replaceLen;
i = i + replaceLen - 1;
if (replaceCount > 0) {
replaceCount--;
}
}
}
return this;
}
//-----------------------------------------------------------------------
/**
* Reverses the string builder placing each character in the opposite index.
*
* @return this, to enable chaining
*/
public StrBuilder reverse() {
if (size == 0) {
return this;
}
int half = size / 2;
char[] buf = buffer;
for (int leftIdx = 0, rightIdx = size - 1; leftIdx < half; leftIdx++,rightIdx--) {
char swap = buf[leftIdx];
buf[leftIdx] = buf[rightIdx];
buf[rightIdx] = swap;
}
return this;
}
//-----------------------------------------------------------------------
/**
* Trims the builder by removing characters less than or equal to a space
* from the beginning and end.
*
* @return this, to enable chaining
*/
public StrBuilder trim() {
if (size == 0) {
return this;
}
int len = size;
char[] buf = buffer;
int pos = 0;
while (pos < len && buf[pos] <= ' ') {
pos++;
}
while (pos < len && buf[len - 1] <= ' ') {
len--;
}
if (len < size) {
delete(len, size);
}
if (pos > 0) {
delete(0, pos);
}
return this;
}
//-----------------------------------------------------------------------
/**
* Checks whether this builder starts with the specified string.
* <p>
* Note that this method handles null input quietly, unlike String.
*
* @param str the string to search for, null returns false
* @return true if the builder starts with the string
*/
public boolean startsWith(String str) {
if (str == null) {
return false;
}
int len = str.length();
if (len == 0) {
return true;
}
if (len > size) {
return false;
}
for (int i = 0; i < len; i++) {
if (buffer[i] != str.charAt(i)) {
return false;
}
}
return true;
}
/**
* Checks whether this builder ends with the specified string.
* <p>
* Note that this method handles null input quietly, unlike String.
*
* @param str the string to search for, null returns false
* @return true if the builder ends with the string
*/
public boolean endsWith(String str) {
if (str == null) {
return false;
}
int len = str.length();
if (len == 0) {
return true;
}
if (len > size) {
return false;
}
int pos = size - len;
for (int i = 0; i < len; i++,pos++) {
if (buffer[pos] != str.charAt(i)) {
return false;
}
}
return true;
}
//-----------------------------------------------------------------------
/**
* {@inheritDoc}
*/
public CharSequence subSequence(int startIndex, int endIndex) {
if (startIndex < 0) {
throw new StringIndexOutOfBoundsException(startIndex);
}
if (endIndex > size) {
throw new StringIndexOutOfBoundsException(endIndex);
}
if (startIndex > endIndex) {
throw new StringIndexOutOfBoundsException(endIndex - startIndex);
}
return substring(startIndex, endIndex);
}
/**
* Extracts a portion of this string builder as a string.
*
* @param start the start index, inclusive, must be valid
* @return the new string
* @throws IndexOutOfBoundsException if the index is invalid
*/
public String substring(int start) {
return substring(start, size);
}
/**
* Extracts a portion of this string builder as a string.
* <p>
* Note: This method treats an endIndex greater than the length of the
* builder as equal to the length of the builder, and continues
* without error, unlike StringBuffer or String.
*
* @param startIndex the start index, inclusive, must be valid
* @param endIndex the end index, exclusive, must be valid except
* that if too large it is treated as end of string
* @return the new string
* @throws IndexOutOfBoundsException if the index is invalid
*/
public String substring(int startIndex, int endIndex) {
endIndex = validateRange(startIndex, endIndex);
return new String(buffer, startIndex, endIndex - startIndex);
}
/**
* Extracts the leftmost characters from the string builder without
* throwing an exception.
* <p>
* This method extracts the left <code>length</code> characters from
* the builder. If this many characters are not available, the whole
* builder is returned. Thus the returned string may be shorter than the
* length requested.
*
* @param length the number of characters to extract, negative returns empty string
* @return the new string
*/
public String leftString(int length) {
if (length <= 0) {
return "";
} else if (length >= size) {
return new String(buffer, 0, size);
} else {
return new String(buffer, 0, length);
}
}
/**
* Extracts the rightmost characters from the string builder without
* throwing an exception.
* <p>
* This method extracts the right <code>length</code> characters from
* the builder. If this many characters are not available, the whole
* builder is returned. Thus the returned string may be shorter than the
* length requested.
*
* @param length the number of characters to extract, negative returns empty string
* @return the new string
*/
public String rightString(int length) {
if (length <= 0) {
return "";
} else if (length >= size) {
return new String(buffer, 0, size);
} else {
return new String(buffer, size - length, length);
}
}
/**
* Extracts some characters from the middle of the string builder without
* throwing an exception.
* <p>
* This method extracts <code>length</code> characters from the builder
* at the specified index.
* If the index is negative it is treated as zero.
* If the index is greater than the builder size, it is treated as the builder size.
* If the length is negative, the empty string is returned.
* If insufficient characters are available in the builder, as much as possible is returned.
* Thus the returned string may be shorter than the length requested.
*
* @param index the index to start at, negative means zero
* @param length the number of characters to extract, negative returns empty string
* @return the new string
*/
public String midString(int index, int length) {
if (index < 0) {
index = 0;
}
if (length <= 0 || index >= size) {
return "";
}
if (size <= index + length) {
return new String(buffer, index, size - index);
} else {
return new String(buffer, index, length);
}
}
//-----------------------------------------------------------------------
/**
* Checks if the string builder contains the specified char.
*
* @param ch the character to find
* @return true if the builder contains the character
*/
public boolean contains(char ch) {
char[] thisBuf = buffer;
for (int i = 0; i < this.size; i++) {
if (thisBuf[i] == ch) {
return true;
}
}
return false;
}
/**
* Checks if the string builder contains the specified string.
*
* @param str the string to find
* @return true if the builder contains the string
*/
public boolean contains(String str) {
return indexOf(str, 0) >= 0;
}
/**
* Checks if the string builder contains a string matched using the
* specified matcher.
* <p>
* Matchers can be used to perform advanced searching behaviour.
* For example you could write a matcher to search for the character
* 'a' followed by a number.
*
* @param matcher the matcher to use, null returns -1
* @return true if the matcher finds a match in the builder
*/
public boolean contains(StrMatcher matcher) {
return indexOf(matcher, 0) >= 0;
}
//-----------------------------------------------------------------------
/**
* Searches the string builder to find the first reference to the specified char.
*
* @param ch the character to find
* @return the first index of the character, or -1 if not found
*/
public int indexOf(char ch) {
return indexOf(ch, 0);
}
/**
* Searches the string builder to find the first reference to the specified char.
*
* @param ch the character to find
* @param startIndex the index to start at, invalid index rounded to edge
* @return the first index of the character, or -1 if not found
*/
public int indexOf(char ch, int startIndex) {
startIndex = (startIndex < 0 ? 0 : startIndex);
if (startIndex >= size) {
return -1;
}
char[] thisBuf = buffer;
for (int i = startIndex; i < size; i++) {
if (thisBuf[i] == ch) {
return i;
}
}
return -1;
}
/**
* Searches the string builder to find the first reference to the specified string.
* <p>
* Note that a null input string will return -1, whereas the JDK throws an exception.
*
* @param str the string to find, null returns -1
* @return the first index of the string, or -1 if not found
*/
public int indexOf(String str) {
return indexOf(str, 0);
}
/**
* Searches the string builder to find the first reference to the specified
* string starting searching from the given index.
* <p>
* Note that a null input string will return -1, whereas the JDK throws an exception.
*
* @param str the string to find, null returns -1
* @param startIndex the index to start at, invalid index rounded to edge
* @return the first index of the string, or -1 if not found
*/
public int indexOf(String str, int startIndex) {
startIndex = (startIndex < 0 ? 0 : startIndex);
if (str == null || startIndex >= size) {
return -1;
}
int strLen = str.length();
if (strLen == 1) {
return indexOf(str.charAt(0), startIndex);
}
if (strLen == 0) {
return startIndex;
}
if (strLen > size) {
return -1;
}
char[] thisBuf = buffer;
int len = size - strLen + 1;
outer:
for (int i = startIndex; i < len; i++) {
for (int j = 0; j < strLen; j++) {
if (str.charAt(j) != thisBuf[i + j]) {
continue outer;
}
}
return i;
}
return -1;
}
/**
* Searches the string builder using the matcher to find the first match.
* <p>
* Matchers can be used to perform advanced searching behaviour.
* For example you could write a matcher to find the character 'a'
* followed by a number.
*
* @param matcher the matcher to use, null returns -1
* @return the first index matched, or -1 if not found
*/
public int indexOf(StrMatcher matcher) {
return indexOf(matcher, 0);
}
/**
* Searches the string builder using the matcher to find the first
* match searching from the given index.
* <p>
* Matchers can be used to perform advanced searching behaviour.
* For example you could write a matcher to find the character 'a'
* followed by a number.
*
* @param matcher the matcher to use, null returns -1
* @param startIndex the index to start at, invalid index rounded to edge
* @return the first index matched, or -1 if not found
*/
public int indexOf(StrMatcher matcher, int startIndex) {
startIndex = (startIndex < 0 ? 0 : startIndex);
if (matcher == null || startIndex >= size) {
return -1;
}
int len = size;
char[] buf = buffer;
for (int i = startIndex; i < len; i++) {
if (matcher.isMatch(buf, i, startIndex, len) > 0) {
return i;
}
}
return -1;
}
//-----------------------------------------------------------------------
/**
* Searches the string builder to find the last reference to the specified char.
*
* @param ch the character to find
* @return the last index of the character, or -1 if not found
*/
public int lastIndexOf(char ch) {
return lastIndexOf(ch, size - 1);
}
/**
* Searches the string builder to find the last reference to the specified char.
*
* @param ch the character to find
* @param startIndex the index to start at, invalid index rounded to edge
* @return the last index of the character, or -1 if not found
*/
public int lastIndexOf(char ch, int startIndex) {
startIndex = (startIndex >= size ? size - 1 : startIndex);
if (startIndex < 0) {
return -1;
}
for (int i = startIndex; i >= 0; i--) {
if (buffer[i] == ch) {
return i;
}
}
return -1;
}
/**
* Searches the string builder to find the last reference to the specified string.
* <p>
* Note that a null input string will return -1, whereas the JDK throws an exception.
*
* @param str the string to find, null returns -1
* @return the last index of the string, or -1 if not found
*/
public int lastIndexOf(String str) {
return lastIndexOf(str, size - 1);
}
/**
* Searches the string builder to find the last reference to the specified
* string starting searching from the given index.
* <p>
* Note that a null input string will return -1, whereas the JDK throws an exception.
*
* @param str the string to find, null returns -1
* @param startIndex the index to start at, invalid index rounded to edge
* @return the last index of the string, or -1 if not found
*/
public int lastIndexOf(String str, int startIndex) {
startIndex = (startIndex >= size ? size - 1 : startIndex);
if (str == null || startIndex < 0) {
return -1;
}
int strLen = str.length();
if (strLen > 0 && strLen <= size) {
if (strLen == 1) {
return lastIndexOf(str.charAt(0), startIndex);
}
outer:
for (int i = startIndex - strLen + 1; i >= 0; i--) {
for (int j = 0; j < strLen; j++) {
if (str.charAt(j) != buffer[i + j]) {
continue outer;
}
}
return i;
}
} else if (strLen == 0) {
return startIndex;
}
return -1;
}
/**
* Searches the string builder using the matcher to find the last match.
* <p>
* Matchers can be used to perform advanced searching behaviour.
* For example you could write a matcher to find the character 'a'
* followed by a number.
*
* @param matcher the matcher to use, null returns -1
* @return the last index matched, or -1 if not found
*/
public int lastIndexOf(StrMatcher matcher) {
return lastIndexOf(matcher, size);
}
/**
* Searches the string builder using the matcher to find the last
* match searching from the given index.
* <p>
* Matchers can be used to perform advanced searching behaviour.
* For example you could write a matcher to find the character 'a'
* followed by a number.
*
* @param matcher the matcher to use, null returns -1
* @param startIndex the index to start at, invalid index rounded to edge
* @return the last index matched, or -1 if not found
*/
public int lastIndexOf(StrMatcher matcher, int startIndex) {
startIndex = (startIndex >= size ? size - 1 : startIndex);
if (matcher == null || startIndex < 0) {
return -1;
}
char[] buf = buffer;
int endIndex = startIndex + 1;
for (int i = startIndex; i >= 0; i--) {
if (matcher.isMatch(buf, i, 0, endIndex) > 0) {
return i;
}
}
return -1;
}
//-----------------------------------------------------------------------
/**
* Creates a tokenizer that can tokenize the contents of this builder.
* <p>
* This method allows the contents of this builder to be tokenized.
* The tokenizer will be setup by default to tokenize on space, tab,
* newline and formfeed (as per StringTokenizer). These values can be
* changed on the tokenizer class, before retrieving the tokens.
* <p>
* The returned tokenizer is linked to this builder. You may intermix
* calls to the buider and tokenizer within certain limits, however
* there is no synchronization. Once the tokenizer has been used once,
* it must be {@link StrTokenizer#reset() reset} to pickup the latest
* changes in the builder. For example:
* <pre>
* StrBuilder b = new StrBuilder();
* b.append("a b ");
* StrTokenizer t = b.asTokenizer();
* String[] tokens1 = t.getTokenArray(); // returns a,b
* b.append("c d ");
* String[] tokens2 = t.getTokenArray(); // returns a,b (c and d ignored)
* t.reset(); // reset causes builder changes to be picked up
* String[] tokens3 = t.getTokenArray(); // returns a,b,c,d
* </pre>
* In addition to simply intermixing appends and tokenization, you can also
* call the set methods on the tokenizer to alter how it tokenizes. Just
* remember to call reset when you want to pickup builder changes.
* <p>
* Calling {@link StrTokenizer#reset(String)} or {@link StrTokenizer#reset(char[])}
* with a non-null value will break the link with the builder.
*
* @return a tokenizer that is linked to this builder
*/
public StrTokenizer asTokenizer() {
return new StrBuilderTokenizer();
}
//-----------------------------------------------------------------------
/**
* Gets the contents of this builder as a Reader.
* <p>
* This method allows the contents of the builder to be read
* using any standard method that expects a Reader.
* <p>
* To use, simply create a <code>StrBuilder</code>, populate it with
* data, call <code>asReader</code>, and then read away.
* <p>
* The internal character array is shared between the builder and the reader.
* This allows you to append to the builder after creating the reader,
* and the changes will be picked up.
* Note however, that no synchronization occurs, so you must perform
* all operations with the builder and the reader in one thread.
* <p>
* The returned reader supports marking, and ignores the flush method.
*
* @return a reader that reads from this builder
*/
public Reader asReader() {
return new StrBuilderReader();
}
//-----------------------------------------------------------------------
/**
* Gets this builder as a Writer that can be written to.
* <p>
* This method allows you to populate the contents of the builder
* using any standard method that takes a Writer.
* <p>
* To use, simply create a <code>StrBuilder</code>,
* call <code>asWriter</code>, and populate away. The data is available
* at any time using the methods of the <code>StrBuilder</code>.
* <p>
* The internal character array is shared between the builder and the writer.
* This allows you to intermix calls that append to the builder and
* write using the writer and the changes will be occur correctly.
* Note however, that no synchronization occurs, so you must perform
* all operations with the builder and the writer in one thread.
* <p>
* The returned writer ignores the close and flush methods.
*
* @return a writer that populates this builder
*/
public Writer asWriter() {
return new StrBuilderWriter();
}
//-----------------------------------------------------------------------
// /**
// * Gets a String version of the string builder by calling the internal
// * constructor of String by reflection.
// * <p>
// * WARNING: You must not use the StrBuilder after calling this method
// * as the buffer is now shared with the String object. To ensure this,
// * the internal character array is set to null, so you will get
// * NullPointerExceptions on all method calls.
// *
// * @return the builder as a String
// */
// public String toSharedString() {
// try {
// Constructor con = String.class.getDeclaredConstructor(
// new Class[] {int.class, int.class, char[].class});
// con.setAccessible(true);
// char[] buffer = buf;
// buf = null;
// size = -1;
// nullText = null;
// return (String) con.newInstance(
// new Object[] {new Integer(0), new Integer(size), buffer});
//
// } catch (Exception ex) {
// ex.printStackTrace();
// throw new UnsupportedOperationException("StrBuilder.toSharedString is unsupported: " + ex.getMessage());
// }
// }
//-----------------------------------------------------------------------
/**
* Checks the contents of this builder against another to see if they
* contain the same character content ignoring case.
*
* @param other the object to check, null returns false
* @return true if the builders contain the same characters in the same order
*/
public boolean equalsIgnoreCase(StrBuilder other) {
if (this == other) {
return true;
}
if (this.size != other.size) {
return false;
}
char thisBuf[] = this.buffer;
char otherBuf[] = other.buffer;
for (int i = size - 1; i >= 0; i--) {
char c1 = thisBuf[i];
char c2 = otherBuf[i];
if (c1 != c2 && Character.toUpperCase(c1) != Character.toUpperCase(c2)) {
return false;
}
}
return true;
}
/**
* Checks the contents of this builder against another to see if they
* contain the same character content.
*
* @param other the object to check, null returns false
* @return true if the builders contain the same characters in the same order
*/
public boolean equals(StrBuilder other) {
if (this == other) {
return true;
}
if (this.size != other.size) {
return false;
}
char thisBuf[] = this.buffer;
char otherBuf[] = other.buffer;
for (int i = size - 1; i >= 0; i--) {
if (thisBuf[i] != otherBuf[i]) {
return false;
}
}
return true;
}
/**
* Checks the contents of this builder against another to see if they
* contain the same character content.
*
* @param obj the object to check, null returns false
* @return true if the builders contain the same characters in the same order
*/
@Override
public boolean equals(Object obj) {
if (obj instanceof StrBuilder) {
return equals((StrBuilder) obj);
}
return false;
}
/**
* Gets a suitable hash code for this builder.
*
* @return a hash code
*/
@Override
public int hashCode() {
char buf[] = buffer;
int hash = 0;
for (int i = size - 1; i >= 0; i--) {
hash = 31 * hash + buf[i];
}
return hash;
}
//-----------------------------------------------------------------------
/**
* Gets a String version of the string builder, creating a new instance
* each time the method is called.
* <p>
* Note that unlike StringBuffer, the string version returned is
* independent of the string builder.
*
* @return the builder as a String
*/
@Override
public String toString() {
return new String(buffer, 0, size);
}
/**
* Gets a StringBuffer version of the string builder, creating a
* new instance each time the method is called.
*
* @return the builder as a StringBuffer
*/
public StringBuffer toStringBuffer() {
return new StringBuffer(size).append(buffer, 0, size);
}
//-----------------------------------------------------------------------
/**
* Validates parameters defining a range of the builder.
*
* @param startIndex the start index, inclusive, must be valid
* @param endIndex the end index, exclusive, must be valid except
* that if too large it is treated as end of string
* @return the new string
* @throws IndexOutOfBoundsException if the index is invalid
*/
protected int validateRange(int startIndex, int endIndex) {
if (startIndex < 0) {
throw new StringIndexOutOfBoundsException(startIndex);
}
if (endIndex > size) {
endIndex = size;
}
if (startIndex > endIndex) {
throw new StringIndexOutOfBoundsException("end < start");
}
return endIndex;
}
/**
* Validates parameters defining a single index in the builder.
*
* @param index the index, must be valid
* @throws IndexOutOfBoundsException if the index is invalid
*/
protected void validateIndex(int index) {
if (index < 0 || index > size) {
throw new StringIndexOutOfBoundsException(index);
}
}
//-----------------------------------------------------------------------
/**
* Inner class to allow StrBuilder to operate as a tokenizer.
*/
class StrBuilderTokenizer extends StrTokenizer {
StrBuilderTokenizer() {
super();
}
/** {@inheritDoc} */
@Override
protected List<String> tokenize(char[] chars, int offset, int count) {
if (chars == null) {
return super.tokenize(StrBuilder.this.buffer, 0, StrBuilder.this.size());
} else {
return super.tokenize(chars, offset, count);
}
}
/** {@inheritDoc} */
@Override
public String getContent() {
String str = super.getContent();
if (str == null) {
return StrBuilder.this.toString();
} else {
return str;
}
}
}
//-----------------------------------------------------------------------
/**
* Inner class to allow StrBuilder to operate as a writer.
*/
class StrBuilderReader extends Reader {
/** The current stream position. */
private int pos;
/** The last mark position. */
private int mark;
StrBuilderReader() {
super();
}
/** {@inheritDoc} */
@Override
public void close() {
// do nothing
}
/** {@inheritDoc} */
@Override
public int read() {
if (ready() == false) {
return -1;
}
return StrBuilder.this.charAt(pos++);
}
/** {@inheritDoc} */
@Override
public int read(char b[], int off, int len) {
if (off < 0 || len < 0 || off > b.length ||
(off + len) > b.length || (off + len) < 0) {
throw new IndexOutOfBoundsException();
}
if (len == 0) {
return 0;
}
if (pos >= StrBuilder.this.size()) {
return -1;
}
if (pos + len > size()) {
len = StrBuilder.this.size() - pos;
}
StrBuilder.this.getChars(pos, pos + len, b, off);
pos += len;
return len;
}
/** {@inheritDoc} */
@Override
public long skip(long n) {
if (pos + n > StrBuilder.this.size()) {
n = StrBuilder.this.size() - pos;
}
if (n < 0) {
return 0;
}
pos += n;
return n;
}
/** {@inheritDoc} */
@Override
public boolean ready() {
return pos < StrBuilder.this.size();
}
/** {@inheritDoc} */
@Override
public boolean markSupported() {
return true;
}
/** {@inheritDoc} */
@Override
public void mark(int readAheadLimit) {
mark = pos;
}
/** {@inheritDoc} */
@Override
public void reset() {
pos = mark;
}
}
//-----------------------------------------------------------------------
/**
* Inner class to allow StrBuilder to operate as a writer.
*/
class StrBuilderWriter extends Writer {
StrBuilderWriter() {
super();
}
/** {@inheritDoc} */
@Override
public void close() {
// do nothing
}
/** {@inheritDoc} */
@Override
public void flush() {
// do nothing
}
/** {@inheritDoc} */
@Override
public void write(int c) {
StrBuilder.this.append((char) c);
}
/** {@inheritDoc} */
@Override
public void write(char[] cbuf) {
StrBuilder.this.append(cbuf);
}
/** {@inheritDoc} */
@Override
public void write(char[] cbuf, int off, int len) {
StrBuilder.this.append(cbuf, off, len);
}
/** {@inheritDoc} */
@Override
public void write(String str) {
StrBuilder.this.append(str);
}
/** {@inheritDoc} */
@Override
public void write(String str, int off, int len) {
StrBuilder.this.append(str, off, len);
}
}
}
|
src/java/org/apache/commons/lang3/text/StrBuilder.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.commons.lang3.text;
import java.io.Reader;
import java.io.Writer;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.SystemUtils;
/**
* Builds a string from constituent parts providing a more flexible and powerful API
* than StringBuffer.
* <p>
* The main differences from StringBuffer/StringBuilder are:
* <ul>
* <li>Not synchronized</li>
* <li>Not final</li>
* <li>Subclasses have direct access to character array</li>
* <li>Additional methods
* <ul>
* <li>appendWithSeparators - adds an array of values, with a separator</li>
* <li>appendPadding - adds a length padding characters</li>
* <li>appendFixedLength - adds a fixed width field to the builder</li>
* <li>toCharArray/getChars - simpler ways to get a range of the character array</li>
* <li>delete - delete char or string</li>
* <li>replace - search and replace for a char or string</li>
* <li>leftString/rightString/midString - substring without exceptions</li>
* <li>contains - whether the builder contains a char or string</li>
* <li>size/clear/isEmpty - collections style API methods</li>
* </ul>
* </li>
* </ul>
* <li>Views
* <ul>
* <li>asTokenizer - uses the internal buffer as the source of a StrTokenizer</li>
* <li>asReader - uses the internal buffer as the source of a Reader</li>
* <li>asWriter - allows a Writer to write directly to the internal buffer</li>
* </ul>
* </li>
* </ul>
* <p>
* The aim has been to provide an API that mimics very closely what StringBuffer
* provides, but with additional methods. It should be noted that some edge cases,
* with invalid indices or null input, have been altered - see individual methods.
* The biggest of these changes is that by default, null will not output the text
* 'null'. This can be controlled by a property, {@link #setNullText(String)}.
* <p>
* Prior to 3.0, this class implemented Cloneable but did not implement the
* clone method so could not be used. From 3.0 onwards it no longer implements
* the interface.
*
* @author Apache Software Foundation
* @author Robert Scholte
* @since 2.2
* @version $Id$
*/
public class StrBuilder implements CharSequence, Appendable {
/**
* The extra capacity for new builders.
*/
static final int CAPACITY = 32;
/**
* Required for serialization support.
*
* @see java.io.Serializable
*/
private static final long serialVersionUID = 7628716375283629643L;
/** Internal data storage. */
protected char[] buffer; // TODO make private?
/** Current size of the buffer. */
protected int size; // TODO make private?
/** The new line. */
private String newLine;
/** The null text. */
private String nullText;
//-----------------------------------------------------------------------
/**
* Constructor that creates an empty builder initial capacity 32 characters.
*/
public StrBuilder() {
this(CAPACITY);
}
/**
* Constructor that creates an empty builder the specified initial capacity.
*
* @param initialCapacity the initial capacity, zero or less will be converted to 32
*/
public StrBuilder(int initialCapacity) {
super();
if (initialCapacity <= 0) {
initialCapacity = CAPACITY;
}
buffer = new char[initialCapacity];
}
/**
* Constructor that creates a builder from the string, allocating
* 32 extra characters for growth.
*
* @param str the string to copy, null treated as blank string
*/
public StrBuilder(String str) {
super();
if (str == null) {
buffer = new char[CAPACITY];
} else {
buffer = new char[str.length() + CAPACITY];
append(str);
}
}
//-----------------------------------------------------------------------
/**
* Gets the text to be appended when a new line is added.
*
* @return the new line text, null means use system default
*/
public String getNewLineText() {
return newLine;
}
/**
* Sets the text to be appended when a new line is added.
*
* @param newLine the new line text, null means use system default
* @return this, to enable chaining
*/
public StrBuilder setNewLineText(String newLine) {
this.newLine = newLine;
return this;
}
//-----------------------------------------------------------------------
/**
* Gets the text to be appended when null is added.
*
* @return the null text, null means no append
*/
public String getNullText() {
return nullText;
}
/**
* Sets the text to be appended when null is added.
*
* @param nullText the null text, null means no append
* @return this, to enable chaining
*/
public StrBuilder setNullText(String nullText) {
if (nullText != null && nullText.length() == 0) {
nullText = null;
}
this.nullText = nullText;
return this;
}
//-----------------------------------------------------------------------
/**
* Gets the length of the string builder.
*
* @return the length
*/
public int length() {
return size;
}
/**
* Updates the length of the builder by either dropping the last characters
* or adding filler of unicode zero.
*
* @param length the length to set to, must be zero or positive
* @return this, to enable chaining
* @throws IndexOutOfBoundsException if the length is negative
*/
public StrBuilder setLength(int length) {
if (length < 0) {
throw new StringIndexOutOfBoundsException(length);
}
if (length < size) {
size = length;
} else if (length > size) {
ensureCapacity(length);
int oldEnd = size;
int newEnd = length;
size = length;
for (int i = oldEnd; i < newEnd; i++) {
buffer[i] = '\0';
}
}
return this;
}
//-----------------------------------------------------------------------
/**
* Gets the current size of the internal character array buffer.
*
* @return the capacity
*/
public int capacity() {
return buffer.length;
}
/**
* Checks the capacity and ensures that it is at least the size specified.
*
* @param capacity the capacity to ensure
* @return this, to enable chaining
*/
public StrBuilder ensureCapacity(int capacity) {
if (capacity > buffer.length) {
char[] old = buffer;
buffer = new char[capacity * 2];
System.arraycopy(old, 0, buffer, 0, size);
}
return this;
}
/**
* Minimizes the capacity to the actual length of the string.
*
* @return this, to enable chaining
*/
public StrBuilder minimizeCapacity() {
if (buffer.length > length()) {
char[] old = buffer;
buffer = new char[length()];
System.arraycopy(old, 0, buffer, 0, size);
}
return this;
}
//-----------------------------------------------------------------------
/**
* Gets the length of the string builder.
* <p>
* This method is the same as {@link #length()} and is provided to match the
* API of Collections.
*
* @return the length
*/
public int size() {
return size;
}
/**
* Checks is the string builder is empty (convenience Collections API style method).
* <p>
* This method is the same as checking {@link #length()} and is provided to match the
* API of Collections.
*
* @return <code>true</code> if the size is <code>0</code>.
*/
public boolean isEmpty() {
return size == 0;
}
/**
* Clears the string builder (convenience Collections API style method).
* <p>
* This method does not reduce the size of the internal character buffer.
* To do that, call <code>clear()</code> followed by {@link #minimizeCapacity()}.
* <p>
* This method is the same as {@link #setLength(int)} called with zero
* and is provided to match the API of Collections.
*
* @return this, to enable chaining
*/
public StrBuilder clear() {
size = 0;
return this;
}
//-----------------------------------------------------------------------
/**
* Gets the character at the specified index.
*
* @see #setCharAt(int, char)
* @see #deleteCharAt(int)
* @param index the index to retrieve, must be valid
* @return the character at the index
* @throws IndexOutOfBoundsException if the index is invalid
*/
public char charAt(int index) {
if (index < 0 || index >= length()) {
throw new StringIndexOutOfBoundsException(index);
}
return buffer[index];
}
/**
* Sets the character at the specified index.
*
* @see #charAt(int)
* @see #deleteCharAt(int)
* @param index the index to set
* @param ch the new character
* @return this, to enable chaining
* @throws IndexOutOfBoundsException if the index is invalid
*/
public StrBuilder setCharAt(int index, char ch) {
if (index < 0 || index >= length()) {
throw new StringIndexOutOfBoundsException(index);
}
buffer[index] = ch;
return this;
}
/**
* Deletes the character at the specified index.
*
* @see #charAt(int)
* @see #setCharAt(int, char)
* @param index the index to delete
* @return this, to enable chaining
* @throws IndexOutOfBoundsException if the index is invalid
*/
public StrBuilder deleteCharAt(int index) {
if (index < 0 || index >= size) {
throw new StringIndexOutOfBoundsException(index);
}
deleteImpl(index, index + 1, 1);
return this;
}
//-----------------------------------------------------------------------
/**
* Copies the builder's character array into a new character array.
*
* @return a new array that represents the contents of the builder
*/
public char[] toCharArray() {
if (size == 0) {
return ArrayUtils.EMPTY_CHAR_ARRAY;
}
char chars[] = new char[size];
System.arraycopy(buffer, 0, chars, 0, size);
return chars;
}
/**
* Copies part of the builder's character array into a new character array.
*
* @param startIndex the start index, inclusive, must be valid
* @param endIndex the end index, exclusive, must be valid except that
* if too large it is treated as end of string
* @return a new array that holds part of the contents of the builder
* @throws IndexOutOfBoundsException if startIndex is invalid,
* or if endIndex is invalid (but endIndex greater than size is valid)
*/
public char[] toCharArray(int startIndex, int endIndex) {
endIndex = validateRange(startIndex, endIndex);
int len = endIndex - startIndex;
if (len == 0) {
return ArrayUtils.EMPTY_CHAR_ARRAY;
}
char chars[] = new char[len];
System.arraycopy(buffer, startIndex, chars, 0, len);
return chars;
}
/**
* Copies the character array into the specified array.
*
* @param destination the destination array, null will cause an array to be created
* @return the input array, unless that was null or too small
*/
public char[] getChars(char[] destination) {
int len = length();
if (destination == null || destination.length < len) {
destination = new char[len];
}
System.arraycopy(buffer, 0, destination, 0, len);
return destination;
}
/**
* Copies the character array into the specified array.
*
* @param startIndex first index to copy, inclusive, must be valid
* @param endIndex last index, exclusive, must be valid
* @param destination the destination array, must not be null or too small
* @param destinationIndex the index to start copying in destination
* @throws NullPointerException if the array is null
* @throws IndexOutOfBoundsException if any index is invalid
*/
public void getChars(int startIndex, int endIndex, char destination[], int destinationIndex) {
if (startIndex < 0) {
throw new StringIndexOutOfBoundsException(startIndex);
}
if (endIndex < 0 || endIndex > length()) {
throw new StringIndexOutOfBoundsException(endIndex);
}
if (startIndex > endIndex) {
throw new StringIndexOutOfBoundsException("end < start");
}
System.arraycopy(buffer, startIndex, destination, destinationIndex, endIndex - startIndex);
}
//-----------------------------------------------------------------------
/**
* Appends the new line string to this string builder.
* <p>
* The new line string can be altered using {@link #setNewLineText(String)}.
* This might be used to force the output to always use Unix line endings
* even when on Windows.
*
* @return this, to enable chaining
*/
public StrBuilder appendNewLine() {
if (newLine == null) {
append(SystemUtils.LINE_SEPARATOR);
return this;
}
return append(newLine);
}
/**
* Appends the text representing <code>null</code> to this string builder.
*
* @return this, to enable chaining
*/
public StrBuilder appendNull() {
if (nullText == null) {
return this;
}
return append(nullText);
}
/**
* Appends an object to this string builder.
* Appending null will call {@link #appendNull()}.
*
* @param obj the object to append
* @return this, to enable chaining
*/
public StrBuilder append(Object obj) {
if (obj == null) {
return appendNull();
}
return append(obj.toString());
}
/**
* Appends a CharSequence to this string builder.
* Appending null will call {@link #appendNull()}.
*
* @param seq the CharSequence to append
* @return this, to enable chaining
*/
public StrBuilder append(CharSequence seq) {
if (seq == null) {
return appendNull();
}
return append(seq.toString());
}
/**
* Appends part of a CharSequence to this string builder.
* Appending null will call {@link #appendNull()}.
*
* @param seq the CharSequence to append
* @param startIndex the start index, inclusive, must be valid
* @param length the length to append, must be valid
* @return this, to enable chaining
*/
public StrBuilder append(CharSequence seq, int startIndex, int length) {
if (seq == null) {
return appendNull();
}
return append(seq.toString(), startIndex, length);
}
/**
* Appends a string to this string builder.
* Appending null will call {@link #appendNull()}.
*
* @param str the string to append
* @return this, to enable chaining
*/
public StrBuilder append(String str) {
if (str == null) {
return appendNull();
}
int strLen = str.length();
if (strLen > 0) {
int len = length();
ensureCapacity(len + strLen);
str.getChars(0, strLen, buffer, len);
size += strLen;
}
return this;
}
/**
* Appends part of a string to this string builder.
* Appending null will call {@link #appendNull()}.
*
* @param str the string to append
* @param startIndex the start index, inclusive, must be valid
* @param length the length to append, must be valid
* @return this, to enable chaining
*/
public StrBuilder append(String str, int startIndex, int length) {
if (str == null) {
return appendNull();
}
if (startIndex < 0 || startIndex > str.length()) {
throw new StringIndexOutOfBoundsException("startIndex must be valid");
}
if (length < 0 || (startIndex + length) > str.length()) {
throw new StringIndexOutOfBoundsException("length must be valid");
}
if (length > 0) {
int len = length();
ensureCapacity(len + length);
str.getChars(startIndex, startIndex + length, buffer, len);
size += length;
}
return this;
}
/**
* Appends a string buffer to this string builder.
* Appending null will call {@link #appendNull()}.
*
* @param str the string buffer to append
* @return this, to enable chaining
*/
public StrBuilder append(StringBuffer str) {
if (str == null) {
return appendNull();
}
int strLen = str.length();
if (strLen > 0) {
int len = length();
ensureCapacity(len + strLen);
str.getChars(0, strLen, buffer, len);
size += strLen;
}
return this;
}
/**
* Appends part of a string buffer to this string builder.
* Appending null will call {@link #appendNull()}.
*
* @param str the string to append
* @param startIndex the start index, inclusive, must be valid
* @param length the length to append, must be valid
* @return this, to enable chaining
*/
public StrBuilder append(StringBuffer str, int startIndex, int length) {
if (str == null) {
return appendNull();
}
if (startIndex < 0 || startIndex > str.length()) {
throw new StringIndexOutOfBoundsException("startIndex must be valid");
}
if (length < 0 || (startIndex + length) > str.length()) {
throw new StringIndexOutOfBoundsException("length must be valid");
}
if (length > 0) {
int len = length();
ensureCapacity(len + length);
str.getChars(startIndex, startIndex + length, buffer, len);
size += length;
}
return this;
}
/**
* Appends another string builder to this string builder.
* Appending null will call {@link #appendNull()}.
*
* @param str the string builder to append
* @return this, to enable chaining
*/
public StrBuilder append(StrBuilder str) {
if (str == null) {
return appendNull();
}
int strLen = str.length();
if (strLen > 0) {
int len = length();
ensureCapacity(len + strLen);
System.arraycopy(str.buffer, 0, buffer, len, strLen);
size += strLen;
}
return this;
}
/**
* Appends part of a string builder to this string builder.
* Appending null will call {@link #appendNull()}.
*
* @param str the string to append
* @param startIndex the start index, inclusive, must be valid
* @param length the length to append, must be valid
* @return this, to enable chaining
*/
public StrBuilder append(StrBuilder str, int startIndex, int length) {
if (str == null) {
return appendNull();
}
if (startIndex < 0 || startIndex > str.length()) {
throw new StringIndexOutOfBoundsException("startIndex must be valid");
}
if (length < 0 || (startIndex + length) > str.length()) {
throw new StringIndexOutOfBoundsException("length must be valid");
}
if (length > 0) {
int len = length();
ensureCapacity(len + length);
str.getChars(startIndex, startIndex + length, buffer, len);
size += length;
}
return this;
}
/**
* Appends a char array to the string builder.
* Appending null will call {@link #appendNull()}.
*
* @param chars the char array to append
* @return this, to enable chaining
*/
public StrBuilder append(char[] chars) {
if (chars == null) {
return appendNull();
}
int strLen = chars.length;
if (strLen > 0) {
int len = length();
ensureCapacity(len + strLen);
System.arraycopy(chars, 0, buffer, len, strLen);
size += strLen;
}
return this;
}
/**
* Appends a char array to the string builder.
* Appending null will call {@link #appendNull()}.
*
* @param chars the char array to append
* @param startIndex the start index, inclusive, must be valid
* @param length the length to append, must be valid
* @return this, to enable chaining
*/
public StrBuilder append(char[] chars, int startIndex, int length) {
if (chars == null) {
return appendNull();
}
if (startIndex < 0 || startIndex > chars.length) {
throw new StringIndexOutOfBoundsException("Invalid startIndex: " + length);
}
if (length < 0 || (startIndex + length) > chars.length) {
throw new StringIndexOutOfBoundsException("Invalid length: " + length);
}
if (length > 0) {
int len = length();
ensureCapacity(len + length);
System.arraycopy(chars, startIndex, buffer, len, length);
size += length;
}
return this;
}
/**
* Appends a boolean value to the string builder.
*
* @param value the value to append
* @return this, to enable chaining
*/
public StrBuilder append(boolean value) {
if (value) {
ensureCapacity(size + 4);
buffer[size++] = 't';
buffer[size++] = 'r';
buffer[size++] = 'u';
buffer[size++] = 'e';
} else {
ensureCapacity(size + 5);
buffer[size++] = 'f';
buffer[size++] = 'a';
buffer[size++] = 'l';
buffer[size++] = 's';
buffer[size++] = 'e';
}
return this;
}
/**
* Appends a char value to the string builder.
*
* @param ch the value to append
* @return this, to enable chaining
*/
public StrBuilder append(char ch) {
int len = length();
ensureCapacity(len + 1);
buffer[size++] = ch;
return this;
}
/**
* Appends an int value to the string builder using <code>String.valueOf</code>.
*
* @param value the value to append
* @return this, to enable chaining
*/
public StrBuilder append(int value) {
return append(String.valueOf(value));
}
/**
* Appends a long value to the string builder using <code>String.valueOf</code>.
*
* @param value the value to append
* @return this, to enable chaining
*/
public StrBuilder append(long value) {
return append(String.valueOf(value));
}
/**
* Appends a float value to the string builder using <code>String.valueOf</code>.
*
* @param value the value to append
* @return this, to enable chaining
*/
public StrBuilder append(float value) {
return append(String.valueOf(value));
}
/**
* Appends a double value to the string builder using <code>String.valueOf</code>.
*
* @param value the value to append
* @return this, to enable chaining
*/
public StrBuilder append(double value) {
return append(String.valueOf(value));
}
//-----------------------------------------------------------------------
/**
* Appends an object followed by a new line to this string builder.
* Appending null will call {@link #appendNull()}.
*
* @param obj the object to append
* @return this, to enable chaining
* @since 2.3
*/
public StrBuilder appendln(Object obj) {
return append(obj).appendNewLine();
}
/**
* Appends a string followed by a new line to this string builder.
* Appending null will call {@link #appendNull()}.
*
* @param str the string to append
* @return this, to enable chaining
* @since 2.3
*/
public StrBuilder appendln(String str) {
return append(str).appendNewLine();
}
/**
* Appends part of a string followed by a new line to this string builder.
* Appending null will call {@link #appendNull()}.
*
* @param str the string to append
* @param startIndex the start index, inclusive, must be valid
* @param length the length to append, must be valid
* @return this, to enable chaining
* @since 2.3
*/
public StrBuilder appendln(String str, int startIndex, int length) {
return append(str, startIndex, length).appendNewLine();
}
/**
* Appends a string buffer followed by a new line to this string builder.
* Appending null will call {@link #appendNull()}.
*
* @param str the string buffer to append
* @return this, to enable chaining
* @since 2.3
*/
public StrBuilder appendln(StringBuffer str) {
return append(str).appendNewLine();
}
/**
* Appends part of a string buffer followed by a new line to this string builder.
* Appending null will call {@link #appendNull()}.
*
* @param str the string to append
* @param startIndex the start index, inclusive, must be valid
* @param length the length to append, must be valid
* @return this, to enable chaining
* @since 2.3
*/
public StrBuilder appendln(StringBuffer str, int startIndex, int length) {
return append(str, startIndex, length).appendNewLine();
}
/**
* Appends another string builder followed by a new line to this string builder.
* Appending null will call {@link #appendNull()}.
*
* @param str the string builder to append
* @return this, to enable chaining
* @since 2.3
*/
public StrBuilder appendln(StrBuilder str) {
return append(str).appendNewLine();
}
/**
* Appends part of a string builder followed by a new line to this string builder.
* Appending null will call {@link #appendNull()}.
*
* @param str the string to append
* @param startIndex the start index, inclusive, must be valid
* @param length the length to append, must be valid
* @return this, to enable chaining
* @since 2.3
*/
public StrBuilder appendln(StrBuilder str, int startIndex, int length) {
return append(str, startIndex, length).appendNewLine();
}
/**
* Appends a char array followed by a new line to the string builder.
* Appending null will call {@link #appendNull()}.
*
* @param chars the char array to append
* @return this, to enable chaining
* @since 2.3
*/
public StrBuilder appendln(char[] chars) {
return append(chars).appendNewLine();
}
/**
* Appends a char array followed by a new line to the string builder.
* Appending null will call {@link #appendNull()}.
*
* @param chars the char array to append
* @param startIndex the start index, inclusive, must be valid
* @param length the length to append, must be valid
* @return this, to enable chaining
* @since 2.3
*/
public StrBuilder appendln(char[] chars, int startIndex, int length) {
return append(chars, startIndex, length).appendNewLine();
}
/**
* Appends a boolean value followed by a new line to the string builder.
*
* @param value the value to append
* @return this, to enable chaining
* @since 2.3
*/
public StrBuilder appendln(boolean value) {
return append(value).appendNewLine();
}
/**
* Appends a char value followed by a new line to the string builder.
*
* @param ch the value to append
* @return this, to enable chaining
* @since 2.3
*/
public StrBuilder appendln(char ch) {
return append(ch).appendNewLine();
}
/**
* Appends an int value followed by a new line to the string builder using <code>String.valueOf</code>.
*
* @param value the value to append
* @return this, to enable chaining
* @since 2.3
*/
public StrBuilder appendln(int value) {
return append(value).appendNewLine();
}
/**
* Appends a long value followed by a new line to the string builder using <code>String.valueOf</code>.
*
* @param value the value to append
* @return this, to enable chaining
* @since 2.3
*/
public StrBuilder appendln(long value) {
return append(value).appendNewLine();
}
/**
* Appends a float value followed by a new line to the string builder using <code>String.valueOf</code>.
*
* @param value the value to append
* @return this, to enable chaining
* @since 2.3
*/
public StrBuilder appendln(float value) {
return append(value).appendNewLine();
}
/**
* Appends a double value followed by a new line to the string builder using <code>String.valueOf</code>.
*
* @param value the value to append
* @return this, to enable chaining
* @since 2.3
*/
public StrBuilder appendln(double value) {
return append(value).appendNewLine();
}
//-----------------------------------------------------------------------
/**
* Appends each item in an array to the builder without any separators.
* Appending a null array will have no effect.
* Each object is appended using {@link #append(Object)}.
*
* @param array the array to append
* @return this, to enable chaining
* @since 2.3
*/
public StrBuilder appendAll(Object[] array) {
if (array != null && array.length > 0) {
for (int i = 0; i < array.length; i++) {
append(array[i]);
}
}
return this;
}
/**
* Appends each item in a collection to the builder without any separators.
* Appending a null collection will have no effect.
* Each object is appended using {@link #append(Object)}.
*
* @param coll the collection to append
* @return this, to enable chaining
* @since 2.3
*/
public StrBuilder appendAll(Collection<?> coll) {
if (coll != null && coll.size() > 0) {
Iterator<?> it = coll.iterator();
while (it.hasNext()) {
append(it.next());
}
}
return this;
}
/**
* Appends each item in an iterator to the builder without any separators.
* Appending a null iterator will have no effect.
* Each object is appended using {@link #append(Object)}.
*
* @param it the iterator to append
* @return this, to enable chaining
* @since 2.3
*/
public StrBuilder appendAll(Iterator<?> it) {
if (it != null) {
while (it.hasNext()) {
append(it.next());
}
}
return this;
}
//-----------------------------------------------------------------------
/**
* Appends an array placing separators between each value, but
* not before the first or after the last.
* Appending a null array will have no effect.
* Each object is appended using {@link #append(Object)}.
*
* @param array the array to append
* @param separator the separator to use, null means no separator
* @return this, to enable chaining
*/
public StrBuilder appendWithSeparators(Object[] array, String separator) {
if (array != null && array.length > 0) {
separator = (separator == null ? "" : separator);
append(array[0]);
for (int i = 1; i < array.length; i++) {
append(separator);
append(array[i]);
}
}
return this;
}
/**
* Appends a collection placing separators between each value, but
* not before the first or after the last.
* Appending a null collection will have no effect.
* Each object is appended using {@link #append(Object)}.
*
* @param coll the collection to append
* @param separator the separator to use, null means no separator
* @return this, to enable chaining
*/
public StrBuilder appendWithSeparators(Collection<?> coll, String separator) {
if (coll != null && coll.size() > 0) {
separator = (separator == null ? "" : separator);
Iterator<?> it = coll.iterator();
while (it.hasNext()) {
append(it.next());
if (it.hasNext()) {
append(separator);
}
}
}
return this;
}
/**
* Appends an iterator placing separators between each value, but
* not before the first or after the last.
* Appending a null iterator will have no effect.
* Each object is appended using {@link #append(Object)}.
*
* @param it the iterator to append
* @param separator the separator to use, null means no separator
* @return this, to enable chaining
*/
public StrBuilder appendWithSeparators(Iterator<?> it, String separator) {
if (it != null) {
separator = (separator == null ? "" : separator);
while (it.hasNext()) {
append(it.next());
if (it.hasNext()) {
append(separator);
}
}
}
return this;
}
//-----------------------------------------------------------------------
/**
* Appends a separator if the builder is currently non-empty.
* Appending a null separator will have no effect.
* The separator is appended using {@link #append(String)}.
* <p>
* This method is useful for adding a separator each time around the
* loop except the first.
* <pre>
* for (Iterator it = list.iterator(); it.hasNext(); ) {
* appendSeparator(",");
* append(it.next());
* }
* </pre>
* Note that for this simple example, you should use
* {@link #appendWithSeparators(Collection, String)}.
*
* @param separator the separator to use, null means no separator
* @return this, to enable chaining
* @since 2.3
*/
public StrBuilder appendSeparator(String separator) {
return appendSeparator(separator, null);
}
/**
* Appends one of both separators to the StrBuilder.
* If the builder is currently empty it will append the defaultIfEmpty-separator
* Otherwise it will append the standard-separator
*
* Appending a null separator will have no effect.
* The separator is appended using {@link #append(String)}.
* <p>
* This method is for example useful for constructing queries
* <pre>
* StrBuilder whereClause = new StrBuilder();
* if(searchCommand.getPriority() != null) {
* whereClause.appendSeparator(" and", " where");
* whereClause.append(" priority = ?")
* }
* if(searchCommand.getComponent() != null) {
* whereClause.appendSeparator(" and", " where");
* whereClause.append(" component = ?")
* }
* selectClause.append(whereClause)
* </pre>
*
* @param standard the separator if builder is not empty, null means no separator
* @param defaultIfEmpty the separator if builder is empty, null means no separator
* @return this, to enable chaining
* @since 3.0
*/
public StrBuilder appendSeparator(String standard, String defaultIfEmpty) {
String str = isEmpty() ? defaultIfEmpty : standard;
if (str != null) {
append(str);
}
return this;
}
/**
* Appends a separator if the builder is currently non-empty.
* The separator is appended using {@link #append(char)}.
* <p>
* This method is useful for adding a separator each time around the
* loop except the first.
* <pre>
* for (Iterator it = list.iterator(); it.hasNext(); ) {
* appendSeparator(',');
* append(it.next());
* }
* </pre>
* Note that for this simple example, you should use
* {@link #appendWithSeparators(Collection, String)}.
*
* @param separator the separator to use
* @return this, to enable chaining
* @since 2.3
*/
public StrBuilder appendSeparator(char separator) {
if (size() > 0) {
append(separator);
}
return this;
}
/**
* Append one of both separators to the builder
* If the builder is currently empty it will append the defaultIfEmpty-separator
* Otherwise it will append the standard-separator
*
* The separator is appended using {@link #append(char)}.
* @param standard the separator if builder is not empty
* @param defaultIfEmpty the separator if builder is empty
* @return this, to enable chaining
* @since 3.0
*/
public StrBuilder appendSeparator(char standard, char defaultIfEmpty) {
if (size() > 0) {
append(standard);
}
else {
append(defaultIfEmpty);
}
return this;
}
/**
* Appends a separator to the builder if the loop index is greater than zero.
* Appending a null separator will have no effect.
* The separator is appended using {@link #append(String)}.
* <p>
* This method is useful for adding a separator each time around the
* loop except the first.
* <pre>
* for (int i = 0; i < list.size(); i++) {
* appendSeparator(",", i);
* append(list.get(i));
* }
* </pre>
* Note that for this simple example, you should use
* {@link #appendWithSeparators(Collection, String)}.
*
* @param separator the separator to use, null means no separator
* @param loopIndex the loop index
* @return this, to enable chaining
* @since 2.3
*/
public StrBuilder appendSeparator(String separator, int loopIndex) {
if (separator != null && loopIndex > 0) {
append(separator);
}
return this;
}
/**
* Appends a separator to the builder if the loop index is greater than zero.
* The separator is appended using {@link #append(char)}.
* <p>
* This method is useful for adding a separator each time around the
* loop except the first.
* <pre>
* for (int i = 0; i < list.size(); i++) {
* appendSeparator(",", i);
* append(list.get(i));
* }
* </pre>
* Note that for this simple example, you should use
* {@link #appendWithSeparators(Collection, String)}.
*
* @param separator the separator to use
* @param loopIndex the loop index
* @return this, to enable chaining
* @since 2.3
*/
public StrBuilder appendSeparator(char separator, int loopIndex) {
if (loopIndex > 0) {
append(separator);
}
return this;
}
//-----------------------------------------------------------------------
/**
* Appends the pad character to the builder the specified number of times.
*
* @param length the length to append, negative means no append
* @param padChar the character to append
* @return this, to enable chaining
*/
public StrBuilder appendPadding(int length, char padChar) {
if (length >= 0) {
ensureCapacity(size + length);
for (int i = 0; i < length; i++) {
buffer[size++] = padChar;
}
}
return this;
}
//-----------------------------------------------------------------------
/**
* Appends an object to the builder padding on the left to a fixed width.
* The <code>toString</code> of the object is used.
* If the object is larger than the length, the left hand side is lost.
* If the object is null, the null text value is used.
*
* @param obj the object to append, null uses null text
* @param width the fixed field width, zero or negative has no effect
* @param padChar the pad character to use
* @return this, to enable chaining
*/
public StrBuilder appendFixedWidthPadLeft(Object obj, int width, char padChar) {
if (width > 0) {
ensureCapacity(size + width);
String str = (obj == null ? getNullText() : obj.toString());
if (str == null) {
str = "";
}
int strLen = str.length();
if (strLen >= width) {
str.getChars(strLen - width, strLen, buffer, size);
} else {
int padLen = width - strLen;
for (int i = 0; i < padLen; i++) {
buffer[size + i] = padChar;
}
str.getChars(0, strLen, buffer, size + padLen);
}
size += width;
}
return this;
}
/**
* Appends an object to the builder padding on the left to a fixed width.
* The <code>String.valueOf</code> of the <code>int</code> value is used.
* If the formatted value is larger than the length, the left hand side is lost.
*
* @param value the value to append
* @param width the fixed field width, zero or negative has no effect
* @param padChar the pad character to use
* @return this, to enable chaining
*/
public StrBuilder appendFixedWidthPadLeft(int value, int width, char padChar) {
return appendFixedWidthPadLeft(String.valueOf(value), width, padChar);
}
/**
* Appends an object to the builder padding on the right to a fixed length.
* The <code>toString</code> of the object is used.
* If the object is larger than the length, the right hand side is lost.
* If the object is null, null text value is used.
*
* @param obj the object to append, null uses null text
* @param width the fixed field width, zero or negative has no effect
* @param padChar the pad character to use
* @return this, to enable chaining
*/
public StrBuilder appendFixedWidthPadRight(Object obj, int width, char padChar) {
if (width > 0) {
ensureCapacity(size + width);
String str = (obj == null ? getNullText() : obj.toString());
if (str == null) {
str = "";
}
int strLen = str.length();
if (strLen >= width) {
str.getChars(0, width, buffer, size);
} else {
int padLen = width - strLen;
str.getChars(0, strLen, buffer, size);
for (int i = 0; i < padLen; i++) {
buffer[size + strLen + i] = padChar;
}
}
size += width;
}
return this;
}
/**
* Appends an object to the builder padding on the right to a fixed length.
* The <code>String.valueOf</code> of the <code>int</code> value is used.
* If the object is larger than the length, the right hand side is lost.
*
* @param value the value to append
* @param width the fixed field width, zero or negative has no effect
* @param padChar the pad character to use
* @return this, to enable chaining
*/
public StrBuilder appendFixedWidthPadRight(int value, int width, char padChar) {
return appendFixedWidthPadRight(String.valueOf(value), width, padChar);
}
//-----------------------------------------------------------------------
/**
* Inserts the string representation of an object into this builder.
* Inserting null will use the stored null text value.
*
* @param index the index to add at, must be valid
* @param obj the object to insert
* @return this, to enable chaining
* @throws IndexOutOfBoundsException if the index is invalid
*/
public StrBuilder insert(int index, Object obj) {
if (obj == null) {
return insert(index, nullText);
}
return insert(index, obj.toString());
}
/**
* Inserts the string into this builder.
* Inserting null will use the stored null text value.
*
* @param index the index to add at, must be valid
* @param str the string to insert
* @return this, to enable chaining
* @throws IndexOutOfBoundsException if the index is invalid
*/
@SuppressWarnings("null") // str cannot be null
public StrBuilder insert(int index, String str) {
validateIndex(index);
if (str == null) {
str = nullText;
}
int strLen = (str == null ? 0 : str.length());
if (strLen > 0) {
int newSize = size + strLen;
ensureCapacity(newSize);
System.arraycopy(buffer, index, buffer, index + strLen, size - index);
size = newSize;
str.getChars(0, strLen, buffer, index); // str cannot be null here
}
return this;
}
/**
* Inserts the character array into this builder.
* Inserting null will use the stored null text value.
*
* @param index the index to add at, must be valid
* @param chars the char array to insert
* @return this, to enable chaining
* @throws IndexOutOfBoundsException if the index is invalid
*/
public StrBuilder insert(int index, char chars[]) {
validateIndex(index);
if (chars == null) {
return insert(index, nullText);
}
int len = chars.length;
if (len > 0) {
ensureCapacity(size + len);
System.arraycopy(buffer, index, buffer, index + len, size - index);
System.arraycopy(chars, 0, buffer, index, len);
size += len;
}
return this;
}
/**
* Inserts part of the character array into this builder.
* Inserting null will use the stored null text value.
*
* @param index the index to add at, must be valid
* @param chars the char array to insert
* @param offset the offset into the character array to start at, must be valid
* @param length the length of the character array part to copy, must be positive
* @return this, to enable chaining
* @throws IndexOutOfBoundsException if any index is invalid
*/
public StrBuilder insert(int index, char chars[], int offset, int length) {
validateIndex(index);
if (chars == null) {
return insert(index, nullText);
}
if (offset < 0 || offset > chars.length) {
throw new StringIndexOutOfBoundsException("Invalid offset: " + offset);
}
if (length < 0 || offset + length > chars.length) {
throw new StringIndexOutOfBoundsException("Invalid length: " + length);
}
if (length > 0) {
ensureCapacity(size + length);
System.arraycopy(buffer, index, buffer, index + length, size - index);
System.arraycopy(chars, offset, buffer, index, length);
size += length;
}
return this;
}
/**
* Inserts the value into this builder.
*
* @param index the index to add at, must be valid
* @param value the value to insert
* @return this, to enable chaining
* @throws IndexOutOfBoundsException if the index is invalid
*/
public StrBuilder insert(int index, boolean value) {
validateIndex(index);
if (value) {
ensureCapacity(size + 4);
System.arraycopy(buffer, index, buffer, index + 4, size - index);
buffer[index++] = 't';
buffer[index++] = 'r';
buffer[index++] = 'u';
buffer[index] = 'e';
size += 4;
} else {
ensureCapacity(size + 5);
System.arraycopy(buffer, index, buffer, index + 5, size - index);
buffer[index++] = 'f';
buffer[index++] = 'a';
buffer[index++] = 'l';
buffer[index++] = 's';
buffer[index] = 'e';
size += 5;
}
return this;
}
/**
* Inserts the value into this builder.
*
* @param index the index to add at, must be valid
* @param value the value to insert
* @return this, to enable chaining
* @throws IndexOutOfBoundsException if the index is invalid
*/
public StrBuilder insert(int index, char value) {
validateIndex(index);
ensureCapacity(size + 1);
System.arraycopy(buffer, index, buffer, index + 1, size - index);
buffer[index] = value;
size++;
return this;
}
/**
* Inserts the value into this builder.
*
* @param index the index to add at, must be valid
* @param value the value to insert
* @return this, to enable chaining
* @throws IndexOutOfBoundsException if the index is invalid
*/
public StrBuilder insert(int index, int value) {
return insert(index, String.valueOf(value));
}
/**
* Inserts the value into this builder.
*
* @param index the index to add at, must be valid
* @param value the value to insert
* @return this, to enable chaining
* @throws IndexOutOfBoundsException if the index is invalid
*/
public StrBuilder insert(int index, long value) {
return insert(index, String.valueOf(value));
}
/**
* Inserts the value into this builder.
*
* @param index the index to add at, must be valid
* @param value the value to insert
* @return this, to enable chaining
* @throws IndexOutOfBoundsException if the index is invalid
*/
public StrBuilder insert(int index, float value) {
return insert(index, String.valueOf(value));
}
/**
* Inserts the value into this builder.
*
* @param index the index to add at, must be valid
* @param value the value to insert
* @return this, to enable chaining
* @throws IndexOutOfBoundsException if the index is invalid
*/
public StrBuilder insert(int index, double value) {
return insert(index, String.valueOf(value));
}
//-----------------------------------------------------------------------
/**
* Internal method to delete a range without validation.
*
* @param startIndex the start index, must be valid
* @param endIndex the end index (exclusive), must be valid
* @param len the length, must be valid
* @throws IndexOutOfBoundsException if any index is invalid
*/
private void deleteImpl(int startIndex, int endIndex, int len) {
System.arraycopy(buffer, endIndex, buffer, startIndex, size - endIndex);
size -= len;
}
/**
* Deletes the characters between the two specified indices.
*
* @param startIndex the start index, inclusive, must be valid
* @param endIndex the end index, exclusive, must be valid except
* that if too large it is treated as end of string
* @return this, to enable chaining
* @throws IndexOutOfBoundsException if the index is invalid
*/
public StrBuilder delete(int startIndex, int endIndex) {
endIndex = validateRange(startIndex, endIndex);
int len = endIndex - startIndex;
if (len > 0) {
deleteImpl(startIndex, endIndex, len);
}
return this;
}
//-----------------------------------------------------------------------
/**
* Deletes the character wherever it occurs in the builder.
*
* @param ch the character to delete
* @return this, to enable chaining
*/
public StrBuilder deleteAll(char ch) {
for (int i = 0; i < size; i++) {
if (buffer[i] == ch) {
int start = i;
while (++i < size) {
if (buffer[i] != ch) {
break;
}
}
int len = i - start;
deleteImpl(start, i, len);
i -= len;
}
}
return this;
}
/**
* Deletes the character wherever it occurs in the builder.
*
* @param ch the character to delete
* @return this, to enable chaining
*/
public StrBuilder deleteFirst(char ch) {
for (int i = 0; i < size; i++) {
if (buffer[i] == ch) {
deleteImpl(i, i + 1, 1);
break;
}
}
return this;
}
//-----------------------------------------------------------------------
/**
* Deletes the string wherever it occurs in the builder.
*
* @param str the string to delete, null causes no action
* @return this, to enable chaining
*/
public StrBuilder deleteAll(String str) {
int len = (str == null ? 0 : str.length());
if (len > 0) {
int index = indexOf(str, 0);
while (index >= 0) {
deleteImpl(index, index + len, len);
index = indexOf(str, index);
}
}
return this;
}
/**
* Deletes the string wherever it occurs in the builder.
*
* @param str the string to delete, null causes no action
* @return this, to enable chaining
*/
public StrBuilder deleteFirst(String str) {
int len = (str == null ? 0 : str.length());
if (len > 0) {
int index = indexOf(str, 0);
if (index >= 0) {
deleteImpl(index, index + len, len);
}
}
return this;
}
//-----------------------------------------------------------------------
/**
* Deletes all parts of the builder that the matcher matches.
* <p>
* Matchers can be used to perform advanced deletion behaviour.
* For example you could write a matcher to delete all occurances
* where the character 'a' is followed by a number.
*
* @param matcher the matcher to use to find the deletion, null causes no action
* @return this, to enable chaining
*/
public StrBuilder deleteAll(StrMatcher matcher) {
return replace(matcher, null, 0, size, -1);
}
/**
* Deletes the first match within the builder using the specified matcher.
* <p>
* Matchers can be used to perform advanced deletion behaviour.
* For example you could write a matcher to delete
* where the character 'a' is followed by a number.
*
* @param matcher the matcher to use to find the deletion, null causes no action
* @return this, to enable chaining
*/
public StrBuilder deleteFirst(StrMatcher matcher) {
return replace(matcher, null, 0, size, 1);
}
//-----------------------------------------------------------------------
/**
* Internal method to delete a range without validation.
*
* @param startIndex the start index, must be valid
* @param endIndex the end index (exclusive), must be valid
* @param removeLen the length to remove (endIndex - startIndex), must be valid
* @param insertStr the string to replace with, null means delete range
* @param insertLen the length of the insert string, must be valid
* @throws IndexOutOfBoundsException if any index is invalid
*/
private void replaceImpl(int startIndex, int endIndex, int removeLen, String insertStr, int insertLen) {
int newSize = size - removeLen + insertLen;
if (insertLen != removeLen) {
ensureCapacity(newSize);
System.arraycopy(buffer, endIndex, buffer, startIndex + insertLen, size - endIndex);
size = newSize;
}
if (insertLen > 0) {
insertStr.getChars(0, insertLen, buffer, startIndex);
}
}
/**
* Replaces a portion of the string builder with another string.
* The length of the inserted string does not have to match the removed length.
*
* @param startIndex the start index, inclusive, must be valid
* @param endIndex the end index, exclusive, must be valid except
* that if too large it is treated as end of string
* @param replaceStr the string to replace with, null means delete range
* @return this, to enable chaining
* @throws IndexOutOfBoundsException if the index is invalid
*/
public StrBuilder replace(int startIndex, int endIndex, String replaceStr) {
endIndex = validateRange(startIndex, endIndex);
int insertLen = (replaceStr == null ? 0 : replaceStr.length());
replaceImpl(startIndex, endIndex, endIndex - startIndex, replaceStr, insertLen);
return this;
}
//-----------------------------------------------------------------------
/**
* Replaces the search character with the replace character
* throughout the builder.
*
* @param search the search character
* @param replace the replace character
* @return this, to enable chaining
*/
public StrBuilder replaceAll(char search, char replace) {
if (search != replace) {
for (int i = 0; i < size; i++) {
if (buffer[i] == search) {
buffer[i] = replace;
}
}
}
return this;
}
/**
* Replaces the first instance of the search character with the
* replace character in the builder.
*
* @param search the search character
* @param replace the replace character
* @return this, to enable chaining
*/
public StrBuilder replaceFirst(char search, char replace) {
if (search != replace) {
for (int i = 0; i < size; i++) {
if (buffer[i] == search) {
buffer[i] = replace;
break;
}
}
}
return this;
}
//-----------------------------------------------------------------------
/**
* Replaces the search string with the replace string throughout the builder.
*
* @param searchStr the search string, null causes no action to occur
* @param replaceStr the replace string, null is equivalent to an empty string
* @return this, to enable chaining
*/
public StrBuilder replaceAll(String searchStr, String replaceStr) {
int searchLen = (searchStr == null ? 0 : searchStr.length());
if (searchLen > 0) {
int replaceLen = (replaceStr == null ? 0 : replaceStr.length());
int index = indexOf(searchStr, 0);
while (index >= 0) {
replaceImpl(index, index + searchLen, searchLen, replaceStr, replaceLen);
index = indexOf(searchStr, index + replaceLen);
}
}
return this;
}
/**
* Replaces the first instance of the search string with the replace string.
*
* @param searchStr the search string, null causes no action to occur
* @param replaceStr the replace string, null is equivalent to an empty string
* @return this, to enable chaining
*/
public StrBuilder replaceFirst(String searchStr, String replaceStr) {
int searchLen = (searchStr == null ? 0 : searchStr.length());
if (searchLen > 0) {
int index = indexOf(searchStr, 0);
if (index >= 0) {
int replaceLen = (replaceStr == null ? 0 : replaceStr.length());
replaceImpl(index, index + searchLen, searchLen, replaceStr, replaceLen);
}
}
return this;
}
//-----------------------------------------------------------------------
/**
* Replaces all matches within the builder with the replace string.
* <p>
* Matchers can be used to perform advanced replace behaviour.
* For example you could write a matcher to replace all occurances
* where the character 'a' is followed by a number.
*
* @param matcher the matcher to use to find the deletion, null causes no action
* @param replaceStr the replace string, null is equivalent to an empty string
* @return this, to enable chaining
*/
public StrBuilder replaceAll(StrMatcher matcher, String replaceStr) {
return replace(matcher, replaceStr, 0, size, -1);
}
/**
* Replaces the first match within the builder with the replace string.
* <p>
* Matchers can be used to perform advanced replace behaviour.
* For example you could write a matcher to replace
* where the character 'a' is followed by a number.
*
* @param matcher the matcher to use to find the deletion, null causes no action
* @param replaceStr the replace string, null is equivalent to an empty string
* @return this, to enable chaining
*/
public StrBuilder replaceFirst(StrMatcher matcher, String replaceStr) {
return replace(matcher, replaceStr, 0, size, 1);
}
// -----------------------------------------------------------------------
/**
* Advanced search and replaces within the builder using a matcher.
* <p>
* Matchers can be used to perform advanced behaviour.
* For example you could write a matcher to delete all occurances
* where the character 'a' is followed by a number.
*
* @param matcher the matcher to use to find the deletion, null causes no action
* @param replaceStr the string to replace the match with, null is a delete
* @param startIndex the start index, inclusive, must be valid
* @param endIndex the end index, exclusive, must be valid except
* that if too large it is treated as end of string
* @param replaceCount the number of times to replace, -1 for replace all
* @return this, to enable chaining
* @throws IndexOutOfBoundsException if start index is invalid
*/
public StrBuilder replace(
StrMatcher matcher, String replaceStr,
int startIndex, int endIndex, int replaceCount) {
endIndex = validateRange(startIndex, endIndex);
return replaceImpl(matcher, replaceStr, startIndex, endIndex, replaceCount);
}
/**
* Replaces within the builder using a matcher.
* <p>
* Matchers can be used to perform advanced behaviour.
* For example you could write a matcher to delete all occurances
* where the character 'a' is followed by a number.
*
* @param matcher the matcher to use to find the deletion, null causes no action
* @param replaceStr the string to replace the match with, null is a delete
* @param from the start index, must be valid
* @param to the end index (exclusive), must be valid
* @param replaceCount the number of times to replace, -1 for replace all
* @return this, to enable chaining
* @throws IndexOutOfBoundsException if any index is invalid
*/
private StrBuilder replaceImpl(
StrMatcher matcher, String replaceStr,
int from, int to, int replaceCount) {
if (matcher == null || size == 0) {
return this;
}
int replaceLen = (replaceStr == null ? 0 : replaceStr.length());
char[] buf = buffer;
for (int i = from; i < to && replaceCount != 0; i++) {
int removeLen = matcher.isMatch(buf, i, from, to);
if (removeLen > 0) {
replaceImpl(i, i + removeLen, removeLen, replaceStr, replaceLen);
to = to - removeLen + replaceLen;
i = i + replaceLen - 1;
if (replaceCount > 0) {
replaceCount--;
}
}
}
return this;
}
//-----------------------------------------------------------------------
/**
* Reverses the string builder placing each character in the opposite index.
*
* @return this, to enable chaining
*/
public StrBuilder reverse() {
if (size == 0) {
return this;
}
int half = size / 2;
char[] buf = buffer;
for (int leftIdx = 0, rightIdx = size - 1; leftIdx < half; leftIdx++,rightIdx--) {
char swap = buf[leftIdx];
buf[leftIdx] = buf[rightIdx];
buf[rightIdx] = swap;
}
return this;
}
//-----------------------------------------------------------------------
/**
* Trims the builder by removing characters less than or equal to a space
* from the beginning and end.
*
* @return this, to enable chaining
*/
public StrBuilder trim() {
if (size == 0) {
return this;
}
int len = size;
char[] buf = buffer;
int pos = 0;
while (pos < len && buf[pos] <= ' ') {
pos++;
}
while (pos < len && buf[len - 1] <= ' ') {
len--;
}
if (len < size) {
delete(len, size);
}
if (pos > 0) {
delete(0, pos);
}
return this;
}
//-----------------------------------------------------------------------
/**
* Checks whether this builder starts with the specified string.
* <p>
* Note that this method handles null input quietly, unlike String.
*
* @param str the string to search for, null returns false
* @return true if the builder starts with the string
*/
public boolean startsWith(String str) {
if (str == null) {
return false;
}
int len = str.length();
if (len == 0) {
return true;
}
if (len > size) {
return false;
}
for (int i = 0; i < len; i++) {
if (buffer[i] != str.charAt(i)) {
return false;
}
}
return true;
}
/**
* Checks whether this builder ends with the specified string.
* <p>
* Note that this method handles null input quietly, unlike String.
*
* @param str the string to search for, null returns false
* @return true if the builder ends with the string
*/
public boolean endsWith(String str) {
if (str == null) {
return false;
}
int len = str.length();
if (len == 0) {
return true;
}
if (len > size) {
return false;
}
int pos = size - len;
for (int i = 0; i < len; i++,pos++) {
if (buffer[pos] != str.charAt(i)) {
return false;
}
}
return true;
}
//-----------------------------------------------------------------------
/**
* {@inheritDoc}
*/
public CharSequence subSequence(int startIndex, int endIndex) {
if (startIndex < 0) {
throw new StringIndexOutOfBoundsException(startIndex);
}
if (endIndex > size) {
throw new StringIndexOutOfBoundsException(endIndex);
}
if (startIndex > endIndex) {
throw new StringIndexOutOfBoundsException(endIndex - startIndex);
}
return substring(startIndex, endIndex);
}
/**
* Extracts a portion of this string builder as a string.
*
* @param start the start index, inclusive, must be valid
* @return the new string
* @throws IndexOutOfBoundsException if the index is invalid
*/
public String substring(int start) {
return substring(start, size);
}
/**
* Extracts a portion of this string builder as a string.
* <p>
* Note: This method treats an endIndex greater than the length of the
* builder as equal to the length of the builder, and continues
* without error, unlike StringBuffer or String.
*
* @param startIndex the start index, inclusive, must be valid
* @param endIndex the end index, exclusive, must be valid except
* that if too large it is treated as end of string
* @return the new string
* @throws IndexOutOfBoundsException if the index is invalid
*/
public String substring(int startIndex, int endIndex) {
endIndex = validateRange(startIndex, endIndex);
return new String(buffer, startIndex, endIndex - startIndex);
}
/**
* Extracts the leftmost characters from the string builder without
* throwing an exception.
* <p>
* This method extracts the left <code>length</code> characters from
* the builder. If this many characters are not available, the whole
* builder is returned. Thus the returned string may be shorter than the
* length requested.
*
* @param length the number of characters to extract, negative returns empty string
* @return the new string
*/
public String leftString(int length) {
if (length <= 0) {
return "";
} else if (length >= size) {
return new String(buffer, 0, size);
} else {
return new String(buffer, 0, length);
}
}
/**
* Extracts the rightmost characters from the string builder without
* throwing an exception.
* <p>
* This method extracts the right <code>length</code> characters from
* the builder. If this many characters are not available, the whole
* builder is returned. Thus the returned string may be shorter than the
* length requested.
*
* @param length the number of characters to extract, negative returns empty string
* @return the new string
*/
public String rightString(int length) {
if (length <= 0) {
return "";
} else if (length >= size) {
return new String(buffer, 0, size);
} else {
return new String(buffer, size - length, length);
}
}
/**
* Extracts some characters from the middle of the string builder without
* throwing an exception.
* <p>
* This method extracts <code>length</code> characters from the builder
* at the specified index.
* If the index is negative it is treated as zero.
* If the index is greater than the builder size, it is treated as the builder size.
* If the length is negative, the empty string is returned.
* If insufficient characters are available in the builder, as much as possible is returned.
* Thus the returned string may be shorter than the length requested.
*
* @param index the index to start at, negative means zero
* @param length the number of characters to extract, negative returns empty string
* @return the new string
*/
public String midString(int index, int length) {
if (index < 0) {
index = 0;
}
if (length <= 0 || index >= size) {
return "";
}
if (size <= index + length) {
return new String(buffer, index, size - index);
} else {
return new String(buffer, index, length);
}
}
//-----------------------------------------------------------------------
/**
* Checks if the string builder contains the specified char.
*
* @param ch the character to find
* @return true if the builder contains the character
*/
public boolean contains(char ch) {
char[] thisBuf = buffer;
for (int i = 0; i < this.size; i++) {
if (thisBuf[i] == ch) {
return true;
}
}
return false;
}
/**
* Checks if the string builder contains the specified string.
*
* @param str the string to find
* @return true if the builder contains the string
*/
public boolean contains(String str) {
return indexOf(str, 0) >= 0;
}
/**
* Checks if the string builder contains a string matched using the
* specified matcher.
* <p>
* Matchers can be used to perform advanced searching behaviour.
* For example you could write a matcher to search for the character
* 'a' followed by a number.
*
* @param matcher the matcher to use, null returns -1
* @return true if the matcher finds a match in the builder
*/
public boolean contains(StrMatcher matcher) {
return indexOf(matcher, 0) >= 0;
}
//-----------------------------------------------------------------------
/**
* Searches the string builder to find the first reference to the specified char.
*
* @param ch the character to find
* @return the first index of the character, or -1 if not found
*/
public int indexOf(char ch) {
return indexOf(ch, 0);
}
/**
* Searches the string builder to find the first reference to the specified char.
*
* @param ch the character to find
* @param startIndex the index to start at, invalid index rounded to edge
* @return the first index of the character, or -1 if not found
*/
public int indexOf(char ch, int startIndex) {
startIndex = (startIndex < 0 ? 0 : startIndex);
if (startIndex >= size) {
return -1;
}
char[] thisBuf = buffer;
for (int i = startIndex; i < size; i++) {
if (thisBuf[i] == ch) {
return i;
}
}
return -1;
}
/**
* Searches the string builder to find the first reference to the specified string.
* <p>
* Note that a null input string will return -1, whereas the JDK throws an exception.
*
* @param str the string to find, null returns -1
* @return the first index of the string, or -1 if not found
*/
public int indexOf(String str) {
return indexOf(str, 0);
}
/**
* Searches the string builder to find the first reference to the specified
* string starting searching from the given index.
* <p>
* Note that a null input string will return -1, whereas the JDK throws an exception.
*
* @param str the string to find, null returns -1
* @param startIndex the index to start at, invalid index rounded to edge
* @return the first index of the string, or -1 if not found
*/
public int indexOf(String str, int startIndex) {
startIndex = (startIndex < 0 ? 0 : startIndex);
if (str == null || startIndex >= size) {
return -1;
}
int strLen = str.length();
if (strLen == 1) {
return indexOf(str.charAt(0), startIndex);
}
if (strLen == 0) {
return startIndex;
}
if (strLen > size) {
return -1;
}
char[] thisBuf = buffer;
int len = size - strLen + 1;
outer:
for (int i = startIndex; i < len; i++) {
for (int j = 0; j < strLen; j++) {
if (str.charAt(j) != thisBuf[i + j]) {
continue outer;
}
}
return i;
}
return -1;
}
/**
* Searches the string builder using the matcher to find the first match.
* <p>
* Matchers can be used to perform advanced searching behaviour.
* For example you could write a matcher to find the character 'a'
* followed by a number.
*
* @param matcher the matcher to use, null returns -1
* @return the first index matched, or -1 if not found
*/
public int indexOf(StrMatcher matcher) {
return indexOf(matcher, 0);
}
/**
* Searches the string builder using the matcher to find the first
* match searching from the given index.
* <p>
* Matchers can be used to perform advanced searching behaviour.
* For example you could write a matcher to find the character 'a'
* followed by a number.
*
* @param matcher the matcher to use, null returns -1
* @param startIndex the index to start at, invalid index rounded to edge
* @return the first index matched, or -1 if not found
*/
public int indexOf(StrMatcher matcher, int startIndex) {
startIndex = (startIndex < 0 ? 0 : startIndex);
if (matcher == null || startIndex >= size) {
return -1;
}
int len = size;
char[] buf = buffer;
for (int i = startIndex; i < len; i++) {
if (matcher.isMatch(buf, i, startIndex, len) > 0) {
return i;
}
}
return -1;
}
//-----------------------------------------------------------------------
/**
* Searches the string builder to find the last reference to the specified char.
*
* @param ch the character to find
* @return the last index of the character, or -1 if not found
*/
public int lastIndexOf(char ch) {
return lastIndexOf(ch, size - 1);
}
/**
* Searches the string builder to find the last reference to the specified char.
*
* @param ch the character to find
* @param startIndex the index to start at, invalid index rounded to edge
* @return the last index of the character, or -1 if not found
*/
public int lastIndexOf(char ch, int startIndex) {
startIndex = (startIndex >= size ? size - 1 : startIndex);
if (startIndex < 0) {
return -1;
}
for (int i = startIndex; i >= 0; i--) {
if (buffer[i] == ch) {
return i;
}
}
return -1;
}
/**
* Searches the string builder to find the last reference to the specified string.
* <p>
* Note that a null input string will return -1, whereas the JDK throws an exception.
*
* @param str the string to find, null returns -1
* @return the last index of the string, or -1 if not found
*/
public int lastIndexOf(String str) {
return lastIndexOf(str, size - 1);
}
/**
* Searches the string builder to find the last reference to the specified
* string starting searching from the given index.
* <p>
* Note that a null input string will return -1, whereas the JDK throws an exception.
*
* @param str the string to find, null returns -1
* @param startIndex the index to start at, invalid index rounded to edge
* @return the last index of the string, or -1 if not found
*/
public int lastIndexOf(String str, int startIndex) {
startIndex = (startIndex >= size ? size - 1 : startIndex);
if (str == null || startIndex < 0) {
return -1;
}
int strLen = str.length();
if (strLen > 0 && strLen <= size) {
if (strLen == 1) {
return lastIndexOf(str.charAt(0), startIndex);
}
outer:
for (int i = startIndex - strLen + 1; i >= 0; i--) {
for (int j = 0; j < strLen; j++) {
if (str.charAt(j) != buffer[i + j]) {
continue outer;
}
}
return i;
}
} else if (strLen == 0) {
return startIndex;
}
return -1;
}
/**
* Searches the string builder using the matcher to find the last match.
* <p>
* Matchers can be used to perform advanced searching behaviour.
* For example you could write a matcher to find the character 'a'
* followed by a number.
*
* @param matcher the matcher to use, null returns -1
* @return the last index matched, or -1 if not found
*/
public int lastIndexOf(StrMatcher matcher) {
return lastIndexOf(matcher, size);
}
/**
* Searches the string builder using the matcher to find the last
* match searching from the given index.
* <p>
* Matchers can be used to perform advanced searching behaviour.
* For example you could write a matcher to find the character 'a'
* followed by a number.
*
* @param matcher the matcher to use, null returns -1
* @param startIndex the index to start at, invalid index rounded to edge
* @return the last index matched, or -1 if not found
*/
public int lastIndexOf(StrMatcher matcher, int startIndex) {
startIndex = (startIndex >= size ? size - 1 : startIndex);
if (matcher == null || startIndex < 0) {
return -1;
}
char[] buf = buffer;
int endIndex = startIndex + 1;
for (int i = startIndex; i >= 0; i--) {
if (matcher.isMatch(buf, i, 0, endIndex) > 0) {
return i;
}
}
return -1;
}
//-----------------------------------------------------------------------
/**
* Creates a tokenizer that can tokenize the contents of this builder.
* <p>
* This method allows the contents of this builder to be tokenized.
* The tokenizer will be setup by default to tokenize on space, tab,
* newline and formfeed (as per StringTokenizer). These values can be
* changed on the tokenizer class, before retrieving the tokens.
* <p>
* The returned tokenizer is linked to this builder. You may intermix
* calls to the buider and tokenizer within certain limits, however
* there is no synchronization. Once the tokenizer has been used once,
* it must be {@link StrTokenizer#reset() reset} to pickup the latest
* changes in the builder. For example:
* <pre>
* StrBuilder b = new StrBuilder();
* b.append("a b ");
* StrTokenizer t = b.asTokenizer();
* String[] tokens1 = t.getTokenArray(); // returns a,b
* b.append("c d ");
* String[] tokens2 = t.getTokenArray(); // returns a,b (c and d ignored)
* t.reset(); // reset causes builder changes to be picked up
* String[] tokens3 = t.getTokenArray(); // returns a,b,c,d
* </pre>
* In addition to simply intermixing appends and tokenization, you can also
* call the set methods on the tokenizer to alter how it tokenizes. Just
* remember to call reset when you want to pickup builder changes.
* <p>
* Calling {@link StrTokenizer#reset(String)} or {@link StrTokenizer#reset(char[])}
* with a non-null value will break the link with the builder.
*
* @return a tokenizer that is linked to this builder
*/
public StrTokenizer asTokenizer() {
return new StrBuilderTokenizer();
}
//-----------------------------------------------------------------------
/**
* Gets the contents of this builder as a Reader.
* <p>
* This method allows the contents of the builder to be read
* using any standard method that expects a Reader.
* <p>
* To use, simply create a <code>StrBuilder</code>, populate it with
* data, call <code>asReader</code>, and then read away.
* <p>
* The internal character array is shared between the builder and the reader.
* This allows you to append to the builder after creating the reader,
* and the changes will be picked up.
* Note however, that no synchronization occurs, so you must perform
* all operations with the builder and the reader in one thread.
* <p>
* The returned reader supports marking, and ignores the flush method.
*
* @return a reader that reads from this builder
*/
public Reader asReader() {
return new StrBuilderReader();
}
//-----------------------------------------------------------------------
/**
* Gets this builder as a Writer that can be written to.
* <p>
* This method allows you to populate the contents of the builder
* using any standard method that takes a Writer.
* <p>
* To use, simply create a <code>StrBuilder</code>,
* call <code>asWriter</code>, and populate away. The data is available
* at any time using the methods of the <code>StrBuilder</code>.
* <p>
* The internal character array is shared between the builder and the writer.
* This allows you to intermix calls that append to the builder and
* write using the writer and the changes will be occur correctly.
* Note however, that no synchronization occurs, so you must perform
* all operations with the builder and the writer in one thread.
* <p>
* The returned writer ignores the close and flush methods.
*
* @return a writer that populates this builder
*/
public Writer asWriter() {
return new StrBuilderWriter();
}
//-----------------------------------------------------------------------
// /**
// * Gets a String version of the string builder by calling the internal
// * constructor of String by reflection.
// * <p>
// * WARNING: You must not use the StrBuilder after calling this method
// * as the buffer is now shared with the String object. To ensure this,
// * the internal character array is set to null, so you will get
// * NullPointerExceptions on all method calls.
// *
// * @return the builder as a String
// */
// public String toSharedString() {
// try {
// Constructor con = String.class.getDeclaredConstructor(
// new Class[] {int.class, int.class, char[].class});
// con.setAccessible(true);
// char[] buffer = buf;
// buf = null;
// size = -1;
// nullText = null;
// return (String) con.newInstance(
// new Object[] {new Integer(0), new Integer(size), buffer});
//
// } catch (Exception ex) {
// ex.printStackTrace();
// throw new UnsupportedOperationException("StrBuilder.toSharedString is unsupported: " + ex.getMessage());
// }
// }
//-----------------------------------------------------------------------
/**
* Checks the contents of this builder against another to see if they
* contain the same character content ignoring case.
*
* @param other the object to check, null returns false
* @return true if the builders contain the same characters in the same order
*/
public boolean equalsIgnoreCase(StrBuilder other) {
if (this == other) {
return true;
}
if (this.size != other.size) {
return false;
}
char thisBuf[] = this.buffer;
char otherBuf[] = other.buffer;
for (int i = size - 1; i >= 0; i--) {
char c1 = thisBuf[i];
char c2 = otherBuf[i];
if (c1 != c2 && Character.toUpperCase(c1) != Character.toUpperCase(c2)) {
return false;
}
}
return true;
}
/**
* Checks the contents of this builder against another to see if they
* contain the same character content.
*
* @param other the object to check, null returns false
* @return true if the builders contain the same characters in the same order
*/
public boolean equals(StrBuilder other) {
if (this == other) {
return true;
}
if (this.size != other.size) {
return false;
}
char thisBuf[] = this.buffer;
char otherBuf[] = other.buffer;
for (int i = size - 1; i >= 0; i--) {
if (thisBuf[i] != otherBuf[i]) {
return false;
}
}
return true;
}
/**
* Checks the contents of this builder against another to see if they
* contain the same character content.
*
* @param obj the object to check, null returns false
* @return true if the builders contain the same characters in the same order
*/
@Override
public boolean equals(Object obj) {
if (obj instanceof StrBuilder) {
return equals((StrBuilder) obj);
}
return false;
}
/**
* Gets a suitable hash code for this builder.
*
* @return a hash code
*/
@Override
public int hashCode() {
char buf[] = buffer;
int hash = 0;
for (int i = size - 1; i >= 0; i--) {
hash = 31 * hash + buf[i];
}
return hash;
}
//-----------------------------------------------------------------------
/**
* Gets a String version of the string builder, creating a new instance
* each time the method is called.
* <p>
* Note that unlike StringBuffer, the string version returned is
* independent of the string builder.
*
* @return the builder as a String
*/
@Override
public String toString() {
return new String(buffer, 0, size);
}
/**
* Gets a StringBuffer version of the string builder, creating a
* new instance each time the method is called.
*
* @return the builder as a StringBuffer
*/
public StringBuffer toStringBuffer() {
return new StringBuffer(size).append(buffer, 0, size);
}
//-----------------------------------------------------------------------
/**
* Validates parameters defining a range of the builder.
*
* @param startIndex the start index, inclusive, must be valid
* @param endIndex the end index, exclusive, must be valid except
* that if too large it is treated as end of string
* @return the new string
* @throws IndexOutOfBoundsException if the index is invalid
*/
protected int validateRange(int startIndex, int endIndex) {
if (startIndex < 0) {
throw new StringIndexOutOfBoundsException(startIndex);
}
if (endIndex > size) {
endIndex = size;
}
if (startIndex > endIndex) {
throw new StringIndexOutOfBoundsException("end < start");
}
return endIndex;
}
/**
* Validates parameters defining a single index in the builder.
*
* @param index the index, must be valid
* @throws IndexOutOfBoundsException if the index is invalid
*/
protected void validateIndex(int index) {
if (index < 0 || index > size) {
throw new StringIndexOutOfBoundsException(index);
}
}
//-----------------------------------------------------------------------
/**
* Inner class to allow StrBuilder to operate as a tokenizer.
*/
class StrBuilderTokenizer extends StrTokenizer {
StrBuilderTokenizer() {
super();
}
/** {@inheritDoc} */
@Override
protected List<String> tokenize(char[] chars, int offset, int count) {
if (chars == null) {
return super.tokenize(StrBuilder.this.buffer, 0, StrBuilder.this.size());
} else {
return super.tokenize(chars, offset, count);
}
}
/** {@inheritDoc} */
@Override
public String getContent() {
String str = super.getContent();
if (str == null) {
return StrBuilder.this.toString();
} else {
return str;
}
}
}
//-----------------------------------------------------------------------
/**
* Inner class to allow StrBuilder to operate as a writer.
*/
class StrBuilderReader extends Reader {
/** The current stream position. */
private int pos;
/** The last mark position. */
private int mark;
StrBuilderReader() {
super();
}
/** {@inheritDoc} */
@Override
public void close() {
// do nothing
}
/** {@inheritDoc} */
@Override
public int read() {
if (ready() == false) {
return -1;
}
return StrBuilder.this.charAt(pos++);
}
/** {@inheritDoc} */
@Override
public int read(char b[], int off, int len) {
if (off < 0 || len < 0 || off > b.length ||
(off + len) > b.length || (off + len) < 0) {
throw new IndexOutOfBoundsException();
}
if (len == 0) {
return 0;
}
if (pos >= StrBuilder.this.size()) {
return -1;
}
if (pos + len > size()) {
len = StrBuilder.this.size() - pos;
}
StrBuilder.this.getChars(pos, pos + len, b, off);
pos += len;
return len;
}
/** {@inheritDoc} */
@Override
public long skip(long n) {
if (pos + n > StrBuilder.this.size()) {
n = StrBuilder.this.size() - pos;
}
if (n < 0) {
return 0;
}
pos += n;
return n;
}
/** {@inheritDoc} */
@Override
public boolean ready() {
return pos < StrBuilder.this.size();
}
/** {@inheritDoc} */
@Override
public boolean markSupported() {
return true;
}
/** {@inheritDoc} */
@Override
public void mark(int readAheadLimit) {
mark = pos;
}
/** {@inheritDoc} */
@Override
public void reset() {
pos = mark;
}
}
//-----------------------------------------------------------------------
/**
* Inner class to allow StrBuilder to operate as a writer.
*/
class StrBuilderWriter extends Writer {
StrBuilderWriter() {
super();
}
/** {@inheritDoc} */
@Override
public void close() {
// do nothing
}
/** {@inheritDoc} */
@Override
public void flush() {
// do nothing
}
/** {@inheritDoc} */
@Override
public void write(int c) {
StrBuilder.this.append((char) c);
}
/** {@inheritDoc} */
@Override
public void write(char[] cbuf) {
StrBuilder.this.append(cbuf);
}
/** {@inheritDoc} */
@Override
public void write(char[] cbuf, int off, int len) {
StrBuilder.this.append(cbuf, off, len);
}
/** {@inheritDoc} */
@Override
public void write(String str) {
StrBuilder.this.append(str);
}
/** {@inheritDoc} */
@Override
public void write(String str, int off, int len) {
StrBuilder.this.append(str, off, len);
}
}
}
|
Changing appendAll and appendWithSeparators methods to take Iterable instead of Collection. LANG-548
git-svn-id: bab3daebc4e66440cbcc4aded890e63215874748@889236 13f79535-47bb-0310-9956-ffa450edef68
|
src/java/org/apache/commons/lang3/text/StrBuilder.java
|
Changing appendAll and appendWithSeparators methods to take Iterable instead of Collection. LANG-548
|
<ide><path>rc/java/org/apache/commons/lang3/text/StrBuilder.java
<ide> }
<ide>
<ide> /**
<del> * Appends each item in a collection to the builder without any separators.
<del> * Appending a null collection will have no effect.
<add> * Appends each item in a iterable to the builder without any separators.
<add> * Appending a null iterable will have no effect.
<ide> * Each object is appended using {@link #append(Object)}.
<ide> *
<del> * @param coll the collection to append
<add> * @param iterable the iterable to append
<ide> * @return this, to enable chaining
<ide> * @since 2.3
<ide> */
<del> public StrBuilder appendAll(Collection<?> coll) {
<del> if (coll != null && coll.size() > 0) {
<del> Iterator<?> it = coll.iterator();
<add> public StrBuilder appendAll(Iterable<?> iterable) {
<add> if (iterable != null) {
<add> Iterator<?> it = iterable.iterator();
<ide> while (it.hasNext()) {
<ide> append(it.next());
<ide> }
<ide> }
<ide>
<ide> /**
<del> * Appends a collection placing separators between each value, but
<add> * Appends a iterable placing separators between each value, but
<ide> * not before the first or after the last.
<del> * Appending a null collection will have no effect.
<add> * Appending a null iterable will have no effect.
<ide> * Each object is appended using {@link #append(Object)}.
<ide> *
<del> * @param coll the collection to append
<add> * @param iterable the iterable to append
<ide> * @param separator the separator to use, null means no separator
<ide> * @return this, to enable chaining
<ide> */
<del> public StrBuilder appendWithSeparators(Collection<?> coll, String separator) {
<del> if (coll != null && coll.size() > 0) {
<add> public StrBuilder appendWithSeparators(Iterable<?> iterable, String separator) {
<add> if (iterable != null) {
<ide> separator = (separator == null ? "" : separator);
<del> Iterator<?> it = coll.iterator();
<add> Iterator<?> it = iterable.iterator();
<ide> while (it.hasNext()) {
<ide> append(it.next());
<ide> if (it.hasNext()) {
|
|
JavaScript
|
mit
|
9fc50003bb8b395f6416aa1b8fae99b22c943e73
| 0 |
ryanaghdam/has-key-deep
|
// hasKeyDeep(key, object) -> boolean
//
// Key is one of:
// - an array of key names, or
// - a single, dot-separated string.
//
// Return true of the object has a matching key.
function hasKeyDeep(key, object) {
// key is a string, then call the function with an array representation of
// the value
if (typeof key === 'string') {
return hasKeyDeep(key.split('.'), object);
}
// Termination case (1)
if (key.length === 0) {
return true;
}
// Termination case (2)
if (!object) {
return false;
}
// Termination case (3)
if (key.length === 1) {
return object.hasOwnProperty(key[0]);
}
// Recursive case
if (object.hasOwnProperty(key[0])) {
return hasKeyDeep(key.slice(1), object[key[0]]);
}
return false;
}
module.exports = function () {
const args = arguments;
if (args.length === 1) {
return function (o) {
return hasKeyDeep(args[0], o);
};
}
return hasKeyDeep(args[0], args[1]);
};
|
index.js
|
// hasKeyDeep(key, object) -> boolean
//
// Key is one of:
// - an array of key names, or
// - a single, dot-separated string.
//
// Return true of the object has a matching key.
function hasKeyDeep(key, object) {
// key is a string, then call the function with an array representation of
// the value
if (typeof key === 'string') {
return hasKeyDeep(key.split('.'), object);
}
// Termination case (1)
if (key.length === 0) {
return true;
}
// Termination case (2)
if (!object) {
return false;
}
// Termination case (3)
if (key.length === 1) {
return object.hasOwnProperty(key[0]);
}
// Recursive case
if (object.hasOwnProperty(key[0])) {
return hasKeyDeep(key.slice(1), object[key[0]]);
}
return false;
}
module.exports = function (...args) {
if (args.length === 1) {
return function (o) {
return hasKeyDeep(args[0], o);
};
}
return hasKeyDeep(...args);
};
|
remove rest params since we're not transpiling ES6
|
index.js
|
remove rest params since we're not transpiling ES6
|
<ide><path>ndex.js
<ide> return false;
<ide> }
<ide>
<del>module.exports = function (...args) {
<add>module.exports = function () {
<add> const args = arguments;
<ide> if (args.length === 1) {
<ide> return function (o) {
<ide> return hasKeyDeep(args[0], o);
<ide> };
<ide> }
<ide>
<del> return hasKeyDeep(...args);
<add> return hasKeyDeep(args[0], args[1]);
<ide> };
|
|
JavaScript
|
mit
|
281b554262a3a000ac3f19bc5cb7399538e0903b
| 0 |
heissmusik/step-sequencer,heissmusik/step-sequencer
|
module.exports = function(grunt) {
modRewrite = require('connect-modrewrite')
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
connect: {
server: {
options: {
port: 8765,
open: true,
base: ['./app'],
middleware: function(connect, options) {
var middlewares;
middlewares = [];
middlewares.push(modRewrite(['^[^\\.]*$ /index.html [L]']));
options.base.forEach(function(base) {
return middlewares.push(connect["static"](base));
});
return middlewares;
}
}
}
},
watch: {
// why bother to refresh your page?
// https://chrome.google.com/webstore/detail/livereload/jnihajbhpnppcggbcgedagnkighmdlei?hl=en
html: { files: 'app/index.html' },
less: {
files: 'app/src/less/*',
tasks: ['less']
},
js: {
files: ['app/src/js/*', 'app/src/js/models/*', 'app/src/js/collections/*', 'app/src/js/views/*'],
tasks: ['concat:app']
},
options: {
livereload: true
},
},
// TODO: use require.js already
concat: {
options: {
separator: ';'
},
lib: {
src: [
'node_modules/jquery/dist/jquery.js',
'node_modules/underscore/underscore.js',
'node_modules/backbone/backbone.js',
'node_modules/jquery-ui/jquery-ui.js'
],
dest: 'app/assets/scripts/lib.js'
},
app: {
src: [
'app/src/js/models/clock.js',
'app/src/js/models/sequence.js',
'app/src/js/models/step.js',
'app/src/js/collections/steps.js',
'app/src/js/views/step.js',
'app/src/js/views/sequence.js',
'app/src/js/app.js'
],
dest: 'app/assets/scripts/app.js'
}
},
less: {
compile: {
options: {
expand: true,
flatten: true,
compress: true,
strictImports: true,
yuicompress: true,
optimization: 2,
// cwd: 'app/src/less',
// src: [
// 'test.less'
// ],
// dest: 'app/assets/stylesheets/test',
// ext: '.css',
// preExt: '.less',
// filter: 'isFile',
},
files: {
// target.css file: source.less file
"app/assets/stylesheets/main.css": "app/src/less/main.less"
}
}
},
});
// Load tasks
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-less');
// Register tasks
grunt.registerTask('default', [ 'connect', 'watch' ]);
grunt.registerTask('compile', [ 'concat:app'] );
grunt.registerTask('vendors', [ 'concat:lib'] );
grunt.event.on('watch', function() {
console.log('watch fire');
// grunt.task.run('less');
});
};
|
Gruntfile.js
|
module.exports = function(grunt) {
modRewrite = require('connect-modrewrite')
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
connect: {
server: {
options: {
port: 8765,
open: true,
base: ['./app'],
middleware: function(connect, options) {
var middlewares;
middlewares = [];
middlewares.push(modRewrite(['^[^\\.]*$ /index.html [L]']));
options.base.forEach(function(base) {
return middlewares.push(connect["static"](base));
});
return middlewares;
}
}
}
},
watch: {
// why bother to refresh your page?
// https://chrome.google.com/webstore/detail/livereload/jnihajbhpnppcggbcgedagnkighmdlei?hl=en
html: { files: 'app/index.html' },
less: {
files: 'app/src/less/*',
tasks: ['less']
},
js: {
files: ['app/src/js/*', 'app/src/js/models/*', 'app/src/js/collections/*', 'app/src/js/views/*'],
tasks: ['concat:app']
},
options: {
livereload: true
},
},
// TODO: use require.js already
concat: {
options: {
separator: ';'
},
lib: {
src: [
'node_modules/jquery/dist/jquery.js',
'node_modules/underscore/underscore.js',
'node_modules/backbone/backbone.js'
],
dest: 'app/assets/scripts/lib.js'
},
app: {
src: [
'app/src/js/models/clock.js',
'app/src/js/models/sequence.js',
'app/src/js/models/step.js',
'app/src/js/collections/steps.js',
'app/src/js/views/step.js',
'app/src/js/views/sequence.js',
'app/src/js/app.js'
],
dest: 'app/assets/scripts/app.js'
}
},
less: {
compile: {
options: {
expand: true,
flatten: true,
compress: true,
strictImports: true,
yuicompress: true,
optimization: 2,
// cwd: 'app/src/less',
// src: [
// 'test.less'
// ],
// dest: 'app/assets/stylesheets/test',
// ext: '.css',
// preExt: '.less',
// filter: 'isFile',
},
files: {
// target.css file: source.less file
"app/assets/stylesheets/main.css": "app/src/less/main.less"
}
}
},
});
// Load tasks
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-less');
// Register tasks
grunt.registerTask('default', [ 'connect', 'watch' ]);
grunt.registerTask('compile', [ 'concat:app'] );
grunt.registerTask('vendors', [ 'concat:lib'] );
grunt.event.on('watch', function() {
console.log('watch fire');
// grunt.task.run('less');
});
};
|
jquery-ui in grunt concat
|
Gruntfile.js
|
jquery-ui in grunt concat
|
<ide><path>runtfile.js
<ide> src: [
<ide> 'node_modules/jquery/dist/jquery.js',
<ide> 'node_modules/underscore/underscore.js',
<del> 'node_modules/backbone/backbone.js'
<add> 'node_modules/backbone/backbone.js',
<add> 'node_modules/jquery-ui/jquery-ui.js'
<ide> ],
<ide> dest: 'app/assets/scripts/lib.js'
<ide> },
|
|
Java
|
apache-2.0
|
0b80b4f44fdfc67051cd21a5a651b3b51f876268
| 0 |
mglukhikh/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,signed/intellij-community,semonte/intellij-community,semonte/intellij-community,apixandru/intellij-community,FHannes/intellij-community,allotria/intellij-community,ibinti/intellij-community,semonte/intellij-community,semonte/intellij-community,apixandru/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,FHannes/intellij-community,ibinti/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,allotria/intellij-community,ibinti/intellij-community,da1z/intellij-community,xfournet/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,semonte/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,asedunov/intellij-community,apixandru/intellij-community,asedunov/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,vvv1559/intellij-community,signed/intellij-community,FHannes/intellij-community,xfournet/intellij-community,ibinti/intellij-community,FHannes/intellij-community,apixandru/intellij-community,signed/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,allotria/intellij-community,ibinti/intellij-community,signed/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,allotria/intellij-community,FHannes/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,allotria/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,da1z/intellij-community,da1z/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,allotria/intellij-community,ibinti/intellij-community,asedunov/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,xfournet/intellij-community,da1z/intellij-community,xfournet/intellij-community,asedunov/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,signed/intellij-community,da1z/intellij-community,xfournet/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,FHannes/intellij-community,semonte/intellij-community,asedunov/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,suncycheng/intellij-community,allotria/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,da1z/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,signed/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,semonte/intellij-community,signed/intellij-community,allotria/intellij-community,asedunov/intellij-community,allotria/intellij-community,signed/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,FHannes/intellij-community,da1z/intellij-community,vvv1559/intellij-community,signed/intellij-community,xfournet/intellij-community,semonte/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,da1z/intellij-community,xfournet/intellij-community,semonte/intellij-community,da1z/intellij-community,xfournet/intellij-community,xfournet/intellij-community,signed/intellij-community,da1z/intellij-community,semonte/intellij-community,asedunov/intellij-community,apixandru/intellij-community,signed/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community
|
/*
* Copyright 2000-2016 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.application.options.schemes;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ApplicationBundle;
import com.intellij.openapi.options.Scheme;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.ui.popup.Balloon;
import com.intellij.openapi.ui.popup.BalloonBuilder;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.util.Disposer;
import com.intellij.ui.JBColor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.util.Collection;
/**
* Base panel for schemes combo box and related actions. When settings change, {@link #updateOnCurrentSettingsChange()} method must be
* called to reflect the change in schemes panel. The method should be added to settings model listener.
*
* @param <T> The actual scheme type.
* @see AbstractSchemeActions
* @see SchemesModel
*/
public abstract class AbstractSchemesPanel<T extends Scheme> extends JPanel {
private SchemesCombo<T> mySchemesCombo;
private AbstractSchemeActions<T> myActions;
private JComponent myToolbar;
private JLabel myInfoLabel;
public AbstractSchemesPanel() {
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
createUIComponents();
}
private void createUIComponents() {
JPanel controlsPanel = new JPanel();
controlsPanel.setLayout(new BoxLayout(controlsPanel, BoxLayout.LINE_AXIS));
controlsPanel.add(new JLabel(getTitle()));
controlsPanel.add(Box.createRigidArea(new Dimension(10, 0)));
myActions = createSchemeActions();
mySchemesCombo = new SchemesCombo<>(this);
controlsPanel.add(mySchemesCombo.getComponent());
myToolbar = createToolbar();
controlsPanel.add(myToolbar);
myInfoLabel = new JLabel();
controlsPanel.add(myInfoLabel);
controlsPanel.add(Box.createHorizontalGlue());
controlsPanel.setMaximumSize(new Dimension(controlsPanel.getMaximumSize().width, mySchemesCombo.getComponent().getPreferredSize().height));
add(controlsPanel);
add(Box.createRigidArea(new Dimension(0, 12)));
add(new JSeparator());
add(Box.createVerticalGlue());
add(Box.createRigidArea(new Dimension(0, 10)));
}
private JComponent createToolbar() {
DefaultActionGroup toolbarActionGroup = new DefaultActionGroup();
toolbarActionGroup.add(new TopActionGroup());
ActionToolbar toolbar = ActionManager.getInstance().createActionToolbar(ActionPlaces.TOOLBAR, toolbarActionGroup, true);
JComponent toolbarComponent = toolbar.getComponent();
toolbarComponent.setMaximumSize(new Dimension(toolbarComponent.getPreferredSize().width, Short.MAX_VALUE));
return toolbarComponent;
}
private class TopActionGroup extends ActionGroup implements DumbAware {
public TopActionGroup() {
super("", true);
}
@NotNull
@Override
public AnAction[] getChildren(@Nullable AnActionEvent e) {
Collection<AnAction> actions = myActions.getActions();
return actions.toArray(new AnAction[actions.size()]);
}
@Override
public void update(AnActionEvent e) {
Presentation p = e.getPresentation();
p.setIcon(AllIcons.General.GearPlain);
}
}
public final JComponent getToolbar() {
return myToolbar;
}
/**
* Creates schemes actions. Used when panel UI components are created.
* @return Scheme actions associated with the panel.
* @see AbstractSchemeActions
*/
protected abstract AbstractSchemeActions<T> createSchemeActions();
public final T getSelectedScheme() {
return mySchemesCombo.getSelectedScheme();
}
public final void selectScheme(@Nullable T scheme) {
mySchemesCombo.selectScheme(scheme);
}
public final void resetSchemes(@NotNull Collection<T> schemes) {
mySchemesCombo.resetSchemes(schemes);
}
public void disposeUIResources() {
removeAll();
}
public final void startEdit() {
mySchemesCombo.startEdit();
}
public final void cancelEdit() {
mySchemesCombo.cancelEdit();
}
public final void showInfo(@Nullable String message, @NotNull MessageType messageType) {
myInfoLabel.setText(message);
myInfoLabel.setForeground(messageTypeToColor(messageType));
}
public final void clearInfo() {
myInfoLabel.setText(null);
}
public final AbstractSchemeActions<T> getActions() {
return myActions;
}
protected String getTitle() {
return ApplicationBundle.message("editbox.scheme.name");
}
/**
* @return Schemes model implementation.
* @see SchemesModel
*/
@NotNull
public abstract SchemesModel<T> getModel();
/**
* Must be called when any settings are changed.
*/
public final void updateOnCurrentSettingsChange() {
mySchemesCombo.updateSelected();
}
public void showStatus(final String message, MessageType messageType) {
BalloonBuilder balloonBuilder = JBPopupFactory.getInstance()
.createHtmlTextBalloonBuilder(message, messageType.getDefaultIcon(),
messageType.getPopupBackground(), null);
balloonBuilder.setFadeoutTime(5000);
final Balloon balloon = balloonBuilder.createBalloon();
balloon.showInCenterOf(myToolbar);
Disposer.register(ProjectManager.getInstance().getDefaultProject(), balloon);
}
@SuppressWarnings("UseJBColor")
private static Color messageTypeToColor(@NotNull MessageType messageType) {
if (messageType == MessageType.INFO) {
return Color.GRAY;
}
else if (messageType == MessageType.ERROR) {
return Color.RED;
}
return JBColor.BLACK;
}
}
|
platform/lang-impl/src/com/intellij/application/options/schemes/AbstractSchemesPanel.java
|
/*
* Copyright 2000-2016 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.application.options.schemes;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ApplicationBundle;
import com.intellij.openapi.options.Scheme;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.ui.popup.Balloon;
import com.intellij.openapi.ui.popup.BalloonBuilder;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.util.Disposer;
import com.intellij.ui.JBColor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.util.Collection;
/**
* Base panel for schemes combo box and related actions. When settings change, {@link #updateOnCurrentSettingsChange()} method must be
* called to reflect the change in schemes panel. The method should be added to settings model listener.
*
* @param <T> The actual scheme type.
* @see AbstractSchemeActions
* @see SchemesModel
*/
public abstract class AbstractSchemesPanel<T extends Scheme> extends JPanel {
private SchemesCombo<T> mySchemesCombo;
private AbstractSchemeActions<T> myActions;
private JComponent myToolbar;
private JLabel myInfoLabel;
public AbstractSchemesPanel() {
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
createUIComponents();
}
private void createUIComponents() {
JPanel controlsPanel = new JPanel();
controlsPanel.setLayout(new BoxLayout(controlsPanel, BoxLayout.LINE_AXIS));
controlsPanel.add(new JLabel(ApplicationBundle.message("editbox.scheme.name")));
controlsPanel.add(Box.createRigidArea(new Dimension(10, 0)));
myActions = createSchemeActions();
mySchemesCombo = new SchemesCombo<>(this);
controlsPanel.add(mySchemesCombo.getComponent());
myToolbar = createToolbar();
controlsPanel.add(myToolbar);
myInfoLabel = new JLabel();
controlsPanel.add(myInfoLabel);
controlsPanel.add(Box.createHorizontalGlue());
controlsPanel.setMaximumSize(new Dimension(controlsPanel.getMaximumSize().width, mySchemesCombo.getComponent().getPreferredSize().height));
add(controlsPanel);
add(Box.createRigidArea(new Dimension(0, 12)));
add(new JSeparator());
add(Box.createVerticalGlue());
add(Box.createRigidArea(new Dimension(0, 10)));
}
private JComponent createToolbar() {
DefaultActionGroup toolbarActionGroup = new DefaultActionGroup();
toolbarActionGroup.add(new TopActionGroup());
ActionToolbar toolbar = ActionManager.getInstance().createActionToolbar(ActionPlaces.TOOLBAR, toolbarActionGroup, true);
JComponent toolbarComponent = toolbar.getComponent();
toolbarComponent.setMaximumSize(new Dimension(toolbarComponent.getPreferredSize().width, Short.MAX_VALUE));
return toolbarComponent;
}
private class TopActionGroup extends ActionGroup implements DumbAware {
public TopActionGroup() {
super("", true);
}
@NotNull
@Override
public AnAction[] getChildren(@Nullable AnActionEvent e) {
Collection<AnAction> actions = myActions.getActions();
return actions.toArray(new AnAction[actions.size()]);
}
@Override
public void update(AnActionEvent e) {
Presentation p = e.getPresentation();
p.setIcon(AllIcons.General.GearPlain);
}
}
public final JComponent getToolbar() {
return myToolbar;
}
/**
* Creates schemes actions. Used when panel UI components are created.
* @return Scheme actions associated with the panel.
* @see AbstractSchemeActions
*/
protected abstract AbstractSchemeActions<T> createSchemeActions();
public final T getSelectedScheme() {
return mySchemesCombo.getSelectedScheme();
}
public final void selectScheme(@Nullable T scheme) {
mySchemesCombo.selectScheme(scheme);
}
public final void resetSchemes(@NotNull Collection<T> schemes) {
mySchemesCombo.resetSchemes(schemes);
}
public void disposeUIResources() {
removeAll();
}
public final void startEdit() {
mySchemesCombo.startEdit();
}
public final void cancelEdit() {
mySchemesCombo.cancelEdit();
}
public final void showInfo(@Nullable String message, @NotNull MessageType messageType) {
myInfoLabel.setText(message);
myInfoLabel.setForeground(messageTypeToColor(messageType));
}
public final void clearInfo() {
myInfoLabel.setText(null);
}
public final AbstractSchemeActions<T> getActions() {
return myActions;
}
/**
* @return Schemes model implementation.
* @see SchemesModel
*/
@NotNull
public abstract SchemesModel<T> getModel();
/**
* Must be called when any settings are changed.
*/
public final void updateOnCurrentSettingsChange() {
mySchemesCombo.updateSelected();
}
public void showStatus(final String message, MessageType messageType) {
BalloonBuilder balloonBuilder = JBPopupFactory.getInstance()
.createHtmlTextBalloonBuilder(message, messageType.getDefaultIcon(),
messageType.getPopupBackground(), null);
balloonBuilder.setFadeoutTime(5000);
final Balloon balloon = balloonBuilder.createBalloon();
balloon.showInCenterOf(myToolbar);
Disposer.register(ProjectManager.getInstance().getDefaultProject(), balloon);
}
@SuppressWarnings("UseJBColor")
private static Color messageTypeToColor(@NotNull MessageType messageType) {
if (messageType == MessageType.INFO) {
return Color.GRAY;
}
else if (messageType == MessageType.ERROR) {
return Color.RED;
}
return JBColor.BLACK;
}
}
|
scheme ui: make panel's text customizable
|
platform/lang-impl/src/com/intellij/application/options/schemes/AbstractSchemesPanel.java
|
scheme ui: make panel's text customizable
|
<ide><path>latform/lang-impl/src/com/intellij/application/options/schemes/AbstractSchemesPanel.java
<ide> private void createUIComponents() {
<ide> JPanel controlsPanel = new JPanel();
<ide> controlsPanel.setLayout(new BoxLayout(controlsPanel, BoxLayout.LINE_AXIS));
<del> controlsPanel.add(new JLabel(ApplicationBundle.message("editbox.scheme.name")));
<add> controlsPanel.add(new JLabel(getTitle()));
<ide> controlsPanel.add(Box.createRigidArea(new Dimension(10, 0)));
<ide> myActions = createSchemeActions();
<ide> mySchemesCombo = new SchemesCombo<>(this);
<ide> add(Box.createVerticalGlue());
<ide> add(Box.createRigidArea(new Dimension(0, 10)));
<ide> }
<del>
<add>
<ide> private JComponent createToolbar() {
<ide> DefaultActionGroup toolbarActionGroup = new DefaultActionGroup();
<ide> toolbarActionGroup.add(new TopActionGroup());
<ide> return myActions;
<ide> }
<ide>
<add> protected String getTitle() {
<add> return ApplicationBundle.message("editbox.scheme.name");
<add> }
<add>
<ide> /**
<ide> * @return Schemes model implementation.
<ide> * @see SchemesModel
|
|
Java
|
mit
|
50150a08fa72a28e605a5c979735e44c325df999
| 0 |
NCI-Agency/anet,NCI-Agency/anet,NCI-Agency/anet,NCI-Agency/anet,NCI-Agency/anet
|
package mil.dds.anet.beans;
import io.leangen.graphql.annotations.GraphQLIgnore;
import io.leangen.graphql.annotations.GraphQLQuery;
import io.leangen.graphql.annotations.GraphQLRootContext;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import javax.ws.rs.WebApplicationException;
import com.fasterxml.jackson.annotation.JsonIgnore;
import mil.dds.anet.AnetObjectEngine;
import mil.dds.anet.beans.Person.Role;
import mil.dds.anet.beans.AuthorizationGroup;
import mil.dds.anet.utils.DaoUtils;
import mil.dds.anet.utils.Utils;
import mil.dds.anet.views.AbstractAnetBean;
import mil.dds.anet.views.UuidFetcher;
public class Report extends AbstractAnetBean {
public enum ReportState { DRAFT, PENDING_APPROVAL, PUBLISHED, REJECTED, CANCELLED, FUTURE, APPROVED }
public enum Atmosphere { POSITIVE, NEUTRAL, NEGATIVE }
public enum ReportCancelledReason { CANCELLED_BY_ADVISOR,
CANCELLED_BY_PRINCIPAL,
CANCELLED_DUE_TO_TRANSPORTATION,
CANCELLED_DUE_TO_FORCE_PROTECTION,
CANCELLED_DUE_TO_ROUTES,
CANCELLED_DUE_TO_THREAT,
NO_REASON_GIVEN }
private ForeignObjectHolder<ApprovalStep> approvalStep = new ForeignObjectHolder<>();
ReportState state;
Instant releasedAt;
Instant engagementDate;
private Integer engagementDayOfWeek;
private ForeignObjectHolder<Location> location = new ForeignObjectHolder<>();
String intent;
String exsum; //can be null to autogenerate
Atmosphere atmosphere;
String atmosphereDetails;
ReportCancelledReason cancelledReason;
List<ReportPerson> attendees;
List<Task> tasks;
String keyOutcomes;
String nextSteps;
String reportText;
private ForeignObjectHolder<Person> author = new ForeignObjectHolder<>();
private ForeignObjectHolder<Organization> advisorOrg = new ForeignObjectHolder<>();
private ForeignObjectHolder<Organization> principalOrg = new ForeignObjectHolder<>();
private ForeignObjectHolder<ReportPerson> primaryAdvisor = new ForeignObjectHolder<>();
private ForeignObjectHolder<ReportPerson> primaryPrincipal = new ForeignObjectHolder<>();
List<Comment> comments;
private List<Tag> tags;
private ReportSensitiveInformation reportSensitiveInformation;
// The user who instantiated this; needed to determine access to sensitive information
private Person user;
private List<AuthorizationGroup> authorizationGroups;
private List<ReportAction> workflow;
@GraphQLQuery(name="approvalStep")
public CompletableFuture<ApprovalStep> loadApprovalStep(@GraphQLRootContext Map<String, Object> context) {
if (approvalStep.hasForeignObject()) {
return CompletableFuture.completedFuture(approvalStep.getForeignObject());
}
return new UuidFetcher<ApprovalStep>().load(context, "approvalSteps", approvalStep.getForeignUuid())
.thenApply(o -> { approvalStep.setForeignObject(o); return o; });
}
@JsonIgnore
@GraphQLIgnore
public void setApprovalStepUuid(String approvalStepUuid) {
this.approvalStep = new ForeignObjectHolder<>(approvalStepUuid);
}
@JsonIgnore
@GraphQLIgnore
public String getApprovalStepUuid() {
return approvalStep.getForeignUuid();
}
public void setApprovalStep(ApprovalStep approvalStep) {
this.approvalStep = new ForeignObjectHolder<>(approvalStep);
}
@GraphQLIgnore
public ApprovalStep getApprovalStep() {
return approvalStep.getForeignObject();
}
@GraphQLQuery(name="state")
public ReportState getState() {
return state;
}
public void setState(ReportState state) {
this.state = state;
}
@GraphQLQuery(name="releasedAt")
public Instant getReleasedAt() {
return releasedAt;
}
public void setReleasedAt(Instant releasedAt) {
this.releasedAt = releasedAt;
}
@GraphQLQuery(name="engagementDate")
public Instant getEngagementDate() {
return engagementDate;
}
public void setEngagementDate(Instant engagementDate) {
this.engagementDate = engagementDate;
}
/**
* Returns an Integer value from the set (1,2,3,4,5,6,7) in accordance with
* week days [Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday].
*
* @return Integer engagement day of week
*/
@GraphQLQuery(name="engagementDayOfWeek")
public Integer getEngagementDayOfWeek() {
return engagementDayOfWeek;
}
public void setEngagementDayOfWeek(Integer engagementDayOfWeek) {
this.engagementDayOfWeek = engagementDayOfWeek;
}
@GraphQLQuery(name="location")
public CompletableFuture<Location> loadLocation(@GraphQLRootContext Map<String, Object> context) {
if (location.hasForeignObject()) {
return CompletableFuture.completedFuture(location.getForeignObject());
}
return new UuidFetcher<Location>().load(context, "locations", location.getForeignUuid())
.thenApply(o -> { location.setForeignObject(o); return o; });
}
@JsonIgnore
@GraphQLIgnore
public void setLocationUuid(String locationUuid) {
this.location = new ForeignObjectHolder<>(locationUuid);
}
@JsonIgnore
@GraphQLIgnore
public String getLocationUuid() {
return location.getForeignUuid();
}
public void setLocation(Location location) {
this.location = new ForeignObjectHolder<>(location);
}
@GraphQLIgnore
public Location getLocation() {
return location.getForeignObject();
}
@GraphQLQuery(name="intent")
public String getIntent() {
return intent;
}
@GraphQLQuery(name="exsum")
public String getExsum() {
return exsum;
}
public void setExsum(String exsum) {
this.exsum = Utils.trimStringReturnNull(exsum);
}
@GraphQLQuery(name="atmosphere")
public Atmosphere getAtmosphere() {
return atmosphere;
}
public void setAtmosphere(Atmosphere atmosphere) {
this.atmosphere = atmosphere;
}
@GraphQLQuery(name="atmosphereDetails")
public String getAtmosphereDetails() {
return atmosphereDetails;
}
public void setAtmosphereDetails(String atmosphereDetails) {
this.atmosphereDetails = Utils.trimStringReturnNull(atmosphereDetails);
}
@GraphQLQuery(name="cancelledReason")
public ReportCancelledReason getCancelledReason() {
return cancelledReason;
}
public void setCancelledReason(ReportCancelledReason cancelledReason) {
this.cancelledReason = cancelledReason;
}
public void setIntent(String intent) {
this.intent = Utils.trimStringReturnNull(intent);
}
@GraphQLQuery(name="attendees")
public CompletableFuture<List<ReportPerson>> loadAttendees(@GraphQLRootContext Map<String, Object> context) {
if (attendees != null) {
return CompletableFuture.completedFuture(attendees);
}
return AnetObjectEngine.getInstance().getReportDao().getAttendeesForReport(context, uuid)
.thenApply(o -> { attendees = o; return o; });
}
@GraphQLIgnore
public List<ReportPerson> getAttendees() {
return attendees;
}
public void setAttendees(List<ReportPerson> attendees) {
this.attendees = attendees;
}
@GraphQLQuery(name="primaryAdvisor")
public CompletableFuture<ReportPerson> loadPrimaryAdvisor(@GraphQLRootContext Map<String, Object> context) {
if (primaryAdvisor.hasForeignObject()) {
return CompletableFuture.completedFuture(primaryAdvisor.getForeignObject());
}
return loadAttendees(context) //Force the load of attendees
.thenApply(l ->
{
final ReportPerson o = l.stream().filter(p -> p.isPrimary() && p.getRole().equals(Role.ADVISOR))
.findFirst().orElse(null);
primaryAdvisor.setForeignObject(o);
return o;
});
}
@JsonIgnore
@GraphQLIgnore
public ReportPerson getPrimaryAdvisor() {
return primaryAdvisor.getForeignObject();
}
@GraphQLQuery(name="primaryPrincipal")
public CompletableFuture<ReportPerson> loadPrimaryPrincipal(@GraphQLRootContext Map<String, Object> context) {
if (primaryPrincipal.hasForeignObject()) {
return CompletableFuture.completedFuture(primaryPrincipal.getForeignObject());
}
return loadAttendees(context) //Force the load of attendees
.thenApply(l ->
{
final ReportPerson o = l.stream().filter(p -> p.isPrimary() && p.getRole().equals(Role.PRINCIPAL))
.findFirst().orElse(null);
primaryPrincipal.setForeignObject(o);
return o;
});
}
@JsonIgnore
@GraphQLIgnore
public ReportPerson getPrimaryPrincipal() {
return primaryPrincipal.getForeignObject();
}
@GraphQLQuery(name="tasks")
public CompletableFuture<List<Task>> loadTasks(@GraphQLRootContext Map<String, Object> context) {
if (tasks != null) {
return CompletableFuture.completedFuture(tasks);
}
return AnetObjectEngine.getInstance().getReportDao().getTasksForReport(context, uuid)
.thenApply(o -> { tasks = o; return o; });
}
public void setTasks(List<Task> tasks) {
this.tasks = tasks;
}
@GraphQLIgnore
public List<Task> getTasks() {
return tasks;
}
@GraphQLQuery(name="keyOutcomes")
public String getKeyOutcomes() {
return keyOutcomes;
}
public void setKeyOutcomes(String keyOutcomes) {
this.keyOutcomes = Utils.trimStringReturnNull(keyOutcomes);
}
@GraphQLQuery(name="reportText")
public String getReportText() {
return reportText;
}
public void setReportText(String reportText) {
this.reportText = Utils.trimStringReturnNull(reportText);
}
@GraphQLQuery(name="nextSteps")
public String getNextSteps() {
return nextSteps;
}
public void setNextSteps(String nextSteps) {
this.nextSteps = Utils.trimStringReturnNull(nextSteps);
}
@GraphQLQuery(name="author")
public CompletableFuture<Person> loadAuthor(@GraphQLRootContext Map<String, Object> context) {
if (author.hasForeignObject()) {
return CompletableFuture.completedFuture(author.getForeignObject());
}
return new UuidFetcher<Person>().load(context, "people", author.getForeignUuid())
.thenApply(o -> { author.setForeignObject(o); return o; });
}
@JsonIgnore
@GraphQLIgnore
public void setAuthorUuid(String authorUuid) {
this.author = new ForeignObjectHolder<>(authorUuid);
}
@JsonIgnore
@GraphQLIgnore
public String getAuthorUuid() {
return author.getForeignUuid();
}
public void setAuthor(Person author) {
this.author = new ForeignObjectHolder<>(author);
}
@GraphQLIgnore
public Person getAuthor() {
return author.getForeignObject();
}
@GraphQLQuery(name="advisorOrg")
public CompletableFuture<Organization> loadAdvisorOrg(@GraphQLRootContext Map<String, Object> context) {
if (advisorOrg.hasForeignObject()) {
return CompletableFuture.completedFuture(advisorOrg.getForeignObject());
}
return new UuidFetcher<Organization>().load(context, "organizations", advisorOrg.getForeignUuid())
.thenApply(o -> { advisorOrg.setForeignObject(o); return o; });
}
@JsonIgnore
@GraphQLIgnore
public void setAdvisorOrgUuid(String advisorOrgUuid) {
this.advisorOrg = new ForeignObjectHolder<>(advisorOrgUuid);
}
@JsonIgnore
@GraphQLIgnore
public String getAdvisorOrgUuid() {
return advisorOrg.getForeignUuid();
}
public void setAdvisorOrg(Organization advisorOrg) {
this.advisorOrg = new ForeignObjectHolder<>(advisorOrg);
}
@GraphQLIgnore
public Organization getAdvisorOrg() {
return advisorOrg.getForeignObject();
}
@GraphQLQuery(name="principalOrg")
public CompletableFuture<Organization> loadPrincipalOrg(@GraphQLRootContext Map<String, Object> context) {
if (principalOrg.hasForeignObject()) {
return CompletableFuture.completedFuture(principalOrg.getForeignObject());
}
return new UuidFetcher<Organization>().load(context, "organizations", principalOrg.getForeignUuid())
.thenApply(o -> { principalOrg.setForeignObject(o); return o; });
}
@JsonIgnore
@GraphQLIgnore
public void setPrincipalOrgUuid(String principalOrgUuid) {
this.principalOrg = new ForeignObjectHolder<>(principalOrgUuid);
}
@JsonIgnore
@GraphQLIgnore
public String getPrincipalOrgUuid() {
return principalOrg.getForeignUuid();
}
@GraphQLIgnore
public Organization getPrincipalOrg() {
return principalOrg.getForeignObject();
}
public void setPrincipalOrg(Organization principalOrg) {
this.principalOrg = new ForeignObjectHolder<>(principalOrg);
}
@GraphQLQuery(name="comments") // TODO: batch load? (used in reports/{Minimal,Show}.js
public synchronized List<Comment> loadComments() {
if (comments == null) {
comments = AnetObjectEngine.getInstance().getCommentDao().getCommentsForReport(uuid);
}
return comments;
}
public void setComments(List<Comment> comments) {
this.comments = comments;
}
@GraphQLIgnore
public List<Comment> getComments() {
return comments;
}
/*Returns a list of report actions. It depends on the report status:
* - for APPROVED or PUBLISHED reports, it returns all report actions
* - for reports in other steps it only returns report actions related to
* approval steps, and for each of the steps only the latest report action
*/
@GraphQLQuery(name="workflow")
public CompletableFuture<List<ReportAction>> loadWorkflow(@GraphQLRootContext Map<String, Object> context) {
if (workflow != null) {
return CompletableFuture.completedFuture(workflow);
}
AnetObjectEngine engine = AnetObjectEngine.getInstance();
return engine.getReportActionDao().getActionsForReport(context, uuid)
.thenApply(actions -> {
if (state == ReportState.APPROVED || state == ReportState.PUBLISHED) {
//For APPROVED and PUBLISHED reports, show the whole workflow of actions
workflow = actions;
} else {
final Organization ao = engine.getOrganizationForPerson(context, author.getForeignUuid()).join();
final String aoUuid = DaoUtils.getUuid(ao);
List<ApprovalStep> steps = getWorkflowForOrg(context, engine, aoUuid).join();
if (Utils.isEmptyOrNull(steps)) {
final String defaultOrgUuid = engine.getDefaultOrgUuid();
if (aoUuid == null || !Objects.equals(aoUuid, defaultOrgUuid)) {
steps = getDefaultWorkflow(context, engine, defaultOrgUuid).join();
}
}
workflow = createWorkflow(actions, steps);
}
return workflow;
});
}
@GraphQLIgnore
public List<ReportAction> getWorkflow() {
return workflow;
}
public void setWorkflow(List<ReportAction> workflow) {
this.workflow = workflow;
}
private List<ReportAction> createWorkflow(List<ReportAction> actions, List<ApprovalStep> steps) {
final List<ReportAction> workflow = new LinkedList<ReportAction>();
for (final ApprovalStep step : steps) {
//If there is an Action for this step, grab the last one (date wise)
final Optional<ReportAction> existing = actions.stream().filter(a ->
Objects.equals(DaoUtils.getUuid(step), a.getStepUuid())
).max(new Comparator<ReportAction>() {
public int compare(ReportAction a, ReportAction b) {
return a.getCreatedAt().compareTo(b.getCreatedAt());
}
});
final ReportAction action;
if (existing.isPresent()) {
action = existing.get();
} else {
//If not then create a new one and attach this step
action = new ReportAction();
}
action.setStep(step);
workflow.add(action);
}
return workflow;
}
private CompletableFuture<List<ApprovalStep>> getWorkflowForOrg(Map<String, Object> context, AnetObjectEngine engine, String aoUuid) {
if (aoUuid == null) {
return CompletableFuture.completedFuture(new ArrayList<ApprovalStep>());
}
return engine.getApprovalStepsForOrg(context, aoUuid);
}
private CompletableFuture<List<ApprovalStep>> getDefaultWorkflow(Map<String, Object> context, AnetObjectEngine engine, String defaultOrgUuid) {
if (defaultOrgUuid == null) {
throw new WebApplicationException("Missing the DEFAULT_APPROVAL_ORGANIZATION admin setting");
}
return getWorkflowForOrg(context, engine, defaultOrgUuid);
}
@GraphQLQuery(name="tags")
public CompletableFuture<List<Tag>> loadTags(@GraphQLRootContext Map<String, Object> context) {
if (tags != null) {
return CompletableFuture.completedFuture(tags);
}
return AnetObjectEngine.getInstance().getReportDao().getTagsForReport(context, uuid)
.thenApply(o -> { tags = o; return o; });
}
@GraphQLIgnore
public List<Tag> getTags() {
return tags;
}
public void setTags(List<Tag> tags) {
this.tags = tags;
}
@GraphQLQuery(name="reportSensitiveInformation")
public CompletableFuture<ReportSensitiveInformation> loadReportSensitiveInformation(@GraphQLRootContext Map<String, Object> context) {
if (reportSensitiveInformation != null) {
return CompletableFuture.completedFuture(reportSensitiveInformation);
}
return AnetObjectEngine.getInstance().getReportSensitiveInformationDao().getForReport(context, this, user)
.thenApply(o -> { reportSensitiveInformation = o; return o; });
}
@GraphQLIgnore
public ReportSensitiveInformation getReportSensitiveInformation() {
return reportSensitiveInformation;
}
public void setReportSensitiveInformation(ReportSensitiveInformation reportSensitiveInformation) {
this.reportSensitiveInformation = reportSensitiveInformation;
}
@JsonIgnore
@GraphQLIgnore
public Person getUser() {
return user;
}
@JsonIgnore
@GraphQLIgnore
public void setUser(Person user) {
this.user = user;
}
@GraphQLQuery(name="authorizationGroups") // TODO: batch load? (used in reports/{Edit,Show}.js)
public synchronized List<AuthorizationGroup> loadAuthorizationGroups() {
if (authorizationGroups == null && uuid != null) {
authorizationGroups = AnetObjectEngine.getInstance().getReportDao().getAuthorizationGroupsForReport(uuid);
}
return authorizationGroups;
}
public void setAuthorizationGroups(List<AuthorizationGroup> authorizationGroups) {
this.authorizationGroups = authorizationGroups;
}
@GraphQLIgnore
public List<AuthorizationGroup> getAuthorizationGroups() {
return authorizationGroups;
}
@Override
public boolean equals(Object other) {
if (other == null || other.getClass() != this.getClass()) {
return false;
}
Report r = (Report) other;
return Objects.equals(r.getUuid(), uuid)
&& Objects.equals(r.getState(), state)
&& Objects.equals(r.getApprovalStepUuid(), getApprovalStepUuid())
&& Objects.equals(r.getCreatedAt(), createdAt)
&& Objects.equals(r.getUpdatedAt(), updatedAt)
&& Objects.equals(r.getEngagementDate(), engagementDate)
&& Objects.equals(r.getLocationUuid(), getLocationUuid())
&& Objects.equals(r.getIntent(), intent)
&& Objects.equals(r.getExsum(), exsum)
&& Objects.equals(r.getAtmosphere(), atmosphere)
&& Objects.equals(r.getAtmosphereDetails(), atmosphereDetails)
&& Objects.equals(r.getAttendees(), attendees)
&& Objects.equals(r.getTasks(), tasks)
&& Objects.equals(r.getReportText(), reportText)
&& Objects.equals(r.getNextSteps(), nextSteps)
&& Objects.equals(r.getAuthorUuid(), getAuthorUuid())
&& Objects.equals(r.getComments(), comments)
&& Objects.equals(r.getTags(), tags)
&& Objects.equals(r.getReportSensitiveInformation(), reportSensitiveInformation)
&& Objects.equals(r.getAuthorizationGroups(), authorizationGroups);
}
@Override
public int hashCode() {
return Objects.hash(uuid, state, approvalStep, createdAt, updatedAt,
location, intent, exsum, attendees, tasks, reportText,
nextSteps, author, comments, atmosphere, atmosphereDetails, engagementDate,
tags, reportSensitiveInformation, authorizationGroups);
}
public static Report createWithUuid(String uuid) {
final Report r = new Report();
r.setUuid(uuid);
return r;
}
@Override
public String toString() {
return String.format("[uuid:%s, intent:%s]", uuid, intent);
}
}
|
src/main/java/mil/dds/anet/beans/Report.java
|
package mil.dds.anet.beans;
import io.leangen.graphql.annotations.GraphQLIgnore;
import io.leangen.graphql.annotations.GraphQLQuery;
import io.leangen.graphql.annotations.GraphQLRootContext;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import javax.ws.rs.WebApplicationException;
import com.fasterxml.jackson.annotation.JsonIgnore;
import mil.dds.anet.AnetObjectEngine;
import mil.dds.anet.beans.Person.Role;
import mil.dds.anet.beans.AuthorizationGroup;
import mil.dds.anet.utils.DaoUtils;
import mil.dds.anet.utils.Utils;
import mil.dds.anet.views.AbstractAnetBean;
import mil.dds.anet.views.UuidFetcher;
public class Report extends AbstractAnetBean {
public enum ReportState { DRAFT, PENDING_APPROVAL, PUBLISHED, REJECTED, CANCELLED, FUTURE, APPROVED }
public enum Atmosphere { POSITIVE, NEUTRAL, NEGATIVE }
public enum ReportCancelledReason { CANCELLED_BY_ADVISOR,
CANCELLED_BY_PRINCIPAL,
CANCELLED_DUE_TO_TRANSPORTATION,
CANCELLED_DUE_TO_FORCE_PROTECTION,
CANCELLED_DUE_TO_ROUTES,
CANCELLED_DUE_TO_THREAT,
NO_REASON_GIVEN }
private ForeignObjectHolder<ApprovalStep> approvalStep = new ForeignObjectHolder<>();
ReportState state;
Instant releasedAt;
Instant engagementDate;
private Integer engagementDayOfWeek;
private ForeignObjectHolder<Location> location = new ForeignObjectHolder<>();
String intent;
String exsum; //can be null to autogenerate
Atmosphere atmosphere;
String atmosphereDetails;
ReportCancelledReason cancelledReason;
List<ReportPerson> attendees;
List<Task> tasks;
String keyOutcomes;
String nextSteps;
String reportText;
private ForeignObjectHolder<Person> author = new ForeignObjectHolder<>();
private ForeignObjectHolder<Organization> advisorOrg = new ForeignObjectHolder<>();
private ForeignObjectHolder<Organization> principalOrg = new ForeignObjectHolder<>();
private ForeignObjectHolder<ReportPerson> primaryAdvisor = new ForeignObjectHolder<>();
private ForeignObjectHolder<ReportPerson> primaryPrincipal = new ForeignObjectHolder<>();
List<Comment> comments;
private List<Tag> tags;
private ReportSensitiveInformation reportSensitiveInformation;
// The user who instantiated this; needed to determine access to sensitive information
private Person user;
private List<AuthorizationGroup> authorizationGroups;
private List<ReportAction> workflow;
@GraphQLQuery(name="approvalStep")
public CompletableFuture<ApprovalStep> loadApprovalStep(@GraphQLRootContext Map<String, Object> context) {
if (approvalStep.hasForeignObject()) {
return CompletableFuture.completedFuture(approvalStep.getForeignObject());
}
return new UuidFetcher<ApprovalStep>().load(context, "approvalSteps", approvalStep.getForeignUuid())
.thenApply(o -> { approvalStep.setForeignObject(o); return o; });
}
@JsonIgnore
@GraphQLIgnore
public void setApprovalStepUuid(String approvalStepUuid) {
this.approvalStep = new ForeignObjectHolder<>(approvalStepUuid);
}
@JsonIgnore
@GraphQLIgnore
public String getApprovalStepUuid() {
return approvalStep.getForeignUuid();
}
public void setApprovalStep(ApprovalStep approvalStep) {
this.approvalStep = new ForeignObjectHolder<>(approvalStep);
}
@GraphQLIgnore
public ApprovalStep getApprovalStep() {
return approvalStep.getForeignObject();
}
@GraphQLQuery(name="state")
public ReportState getState() {
return state;
}
public void setState(ReportState state) {
this.state = state;
}
@GraphQLQuery(name="releasedAt")
public Instant getReleasedAt() {
return releasedAt;
}
public void setReleasedAt(Instant releasedAt) {
this.releasedAt = releasedAt;
}
@GraphQLQuery(name="engagementDate")
public Instant getEngagementDate() {
return engagementDate;
}
public void setEngagementDate(Instant engagementDate) {
this.engagementDate = engagementDate;
}
/**
* Returns an Integer value from the set (1,2,3,4,5,6,7) in accordance with
* week days [Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday].
*
* @return Integer engagement day of week
*/
@GraphQLQuery(name="engagementDayOfWeek")
public Integer getEngagementDayOfWeek() {
return engagementDayOfWeek;
}
public void setEngagementDayOfWeek(Integer engagementDayOfWeek) {
this.engagementDayOfWeek = engagementDayOfWeek;
}
@GraphQLQuery(name="location")
public CompletableFuture<Location> loadLocation(@GraphQLRootContext Map<String, Object> context) {
if (location.hasForeignObject()) {
return CompletableFuture.completedFuture(location.getForeignObject());
}
return new UuidFetcher<Location>().load(context, "locations", location.getForeignUuid())
.thenApply(o -> { location.setForeignObject(o); return o; });
}
@JsonIgnore
@GraphQLIgnore
public void setLocationUuid(String locationUuid) {
this.location = new ForeignObjectHolder<>(locationUuid);
}
@JsonIgnore
@GraphQLIgnore
public String getLocationUuid() {
return location.getForeignUuid();
}
public void setLocation(Location location) {
this.location = new ForeignObjectHolder<>(location);
}
@GraphQLIgnore
public Location getLocation() {
return location.getForeignObject();
}
@GraphQLQuery(name="intent")
public String getIntent() {
return intent;
}
@GraphQLQuery(name="exsum")
public String getExsum() {
return exsum;
}
public void setExsum(String exsum) {
this.exsum = Utils.trimStringReturnNull(exsum);
}
@GraphQLQuery(name="atmosphere")
public Atmosphere getAtmosphere() {
return atmosphere;
}
public void setAtmosphere(Atmosphere atmosphere) {
this.atmosphere = atmosphere;
}
@GraphQLQuery(name="atmosphereDetails")
public String getAtmosphereDetails() {
return atmosphereDetails;
}
public void setAtmosphereDetails(String atmosphereDetails) {
this.atmosphereDetails = Utils.trimStringReturnNull(atmosphereDetails);
}
@GraphQLQuery(name="cancelledReason")
public ReportCancelledReason getCancelledReason() {
return cancelledReason;
}
public void setCancelledReason(ReportCancelledReason cancelledReason) {
this.cancelledReason = cancelledReason;
}
public void setIntent(String intent) {
this.intent = Utils.trimStringReturnNull(intent);
}
@GraphQLQuery(name="attendees")
public CompletableFuture<List<ReportPerson>> loadAttendees(@GraphQLRootContext Map<String, Object> context) {
if (attendees != null) {
return CompletableFuture.completedFuture(attendees);
}
return AnetObjectEngine.getInstance().getReportDao().getAttendeesForReport(context, uuid)
.thenApply(o -> { attendees = o; return o; });
}
@GraphQLIgnore
public List<ReportPerson> getAttendees() {
return attendees;
}
public void setAttendees(List<ReportPerson> attendees) {
this.attendees = attendees;
}
@GraphQLQuery(name="primaryAdvisor")
public CompletableFuture<ReportPerson> loadPrimaryAdvisor(@GraphQLRootContext Map<String, Object> context) {
if (primaryAdvisor.hasForeignObject()) {
return CompletableFuture.completedFuture(primaryAdvisor.getForeignObject());
}
return loadAttendees(context) //Force the load of attendees
.thenApply(l ->
{
final ReportPerson o = l.stream().filter(p -> p.isPrimary() && p.getRole().equals(Role.ADVISOR))
.findFirst().orElse(null);
primaryAdvisor.setForeignObject(o);
return o;
});
}
@JsonIgnore
@GraphQLIgnore
public ReportPerson getPrimaryAdvisor() {
return primaryAdvisor.getForeignObject();
}
@GraphQLQuery(name="primaryPrincipal")
public CompletableFuture<ReportPerson> loadPrimaryPrincipal(@GraphQLRootContext Map<String, Object> context) {
if (primaryPrincipal.hasForeignObject()) {
return CompletableFuture.completedFuture(primaryPrincipal.getForeignObject());
}
return loadAttendees(context) //Force the load of attendees
.thenApply(l ->
{
final ReportPerson o = l.stream().filter(p -> p.isPrimary() && p.getRole().equals(Role.PRINCIPAL))
.findFirst().orElse(null);
primaryPrincipal.setForeignObject(o);
return o;
});
}
@JsonIgnore
@GraphQLIgnore
public ReportPerson getPrimaryPrincipal() {
return primaryPrincipal.getForeignObject();
}
@GraphQLQuery(name="tasks")
public CompletableFuture<List<Task>> loadTasks(@GraphQLRootContext Map<String, Object> context) {
if (tasks != null) {
return CompletableFuture.completedFuture(tasks);
}
return AnetObjectEngine.getInstance().getReportDao().getTasksForReport(context, uuid)
.thenApply(o -> { tasks = o; return o; });
}
public void setTasks(List<Task> tasks) {
this.tasks = tasks;
}
@GraphQLIgnore
public List<Task> getTasks() {
return tasks;
}
@GraphQLQuery(name="keyOutcomes")
public String getKeyOutcomes() {
return keyOutcomes;
}
public void setKeyOutcomes(String keyOutcomes) {
this.keyOutcomes = Utils.trimStringReturnNull(keyOutcomes);
}
@GraphQLQuery(name="reportText")
public String getReportText() {
return reportText;
}
public void setReportText(String reportText) {
this.reportText = Utils.trimStringReturnNull(reportText);
}
@GraphQLQuery(name="nextSteps")
public String getNextSteps() {
return nextSteps;
}
public void setNextSteps(String nextSteps) {
this.nextSteps = Utils.trimStringReturnNull(nextSteps);
}
@GraphQLQuery(name="author")
public CompletableFuture<Person> loadAuthor(@GraphQLRootContext Map<String, Object> context) {
if (author.hasForeignObject()) {
return CompletableFuture.completedFuture(author.getForeignObject());
}
return new UuidFetcher<Person>().load(context, "people", author.getForeignUuid())
.thenApply(o -> { author.setForeignObject(o); return o; });
}
@JsonIgnore
@GraphQLIgnore
public void setAuthorUuid(String authorUuid) {
this.author = new ForeignObjectHolder<>(authorUuid);
}
@JsonIgnore
@GraphQLIgnore
public String getAuthorUuid() {
return author.getForeignUuid();
}
public void setAuthor(Person author) {
this.author = new ForeignObjectHolder<>(author);
}
@GraphQLIgnore
public Person getAuthor() {
return author.getForeignObject();
}
@GraphQLQuery(name="advisorOrg")
public CompletableFuture<Organization> loadAdvisorOrg(@GraphQLRootContext Map<String, Object> context) {
if (advisorOrg.hasForeignObject()) {
return CompletableFuture.completedFuture(advisorOrg.getForeignObject());
}
return new UuidFetcher<Organization>().load(context, "organizations", advisorOrg.getForeignUuid())
.thenApply(o -> { advisorOrg.setForeignObject(o); return o; });
}
@JsonIgnore
@GraphQLIgnore
public void setAdvisorOrgUuid(String advisorOrgUuid) {
this.advisorOrg = new ForeignObjectHolder<>(advisorOrgUuid);
}
@JsonIgnore
@GraphQLIgnore
public String getAdvisorOrgUuid() {
return advisorOrg.getForeignUuid();
}
public void setAdvisorOrg(Organization advisorOrg) {
this.advisorOrg = new ForeignObjectHolder<>(advisorOrg);
}
@GraphQLIgnore
public Organization getAdvisorOrg() {
return advisorOrg.getForeignObject();
}
@GraphQLQuery(name="principalOrg")
public CompletableFuture<Organization> loadPrincipalOrg(@GraphQLRootContext Map<String, Object> context) {
if (principalOrg.hasForeignObject()) {
return CompletableFuture.completedFuture(principalOrg.getForeignObject());
}
return new UuidFetcher<Organization>().load(context, "organizations", principalOrg.getForeignUuid())
.thenApply(o -> { principalOrg.setForeignObject(o); return o; });
}
@JsonIgnore
@GraphQLIgnore
public void setPrincipalOrgUuid(String principalOrgUuid) {
this.principalOrg = new ForeignObjectHolder<>(principalOrgUuid);
}
@JsonIgnore
@GraphQLIgnore
public String getPrincipalOrgUuid() {
return principalOrg.getForeignUuid();
}
@GraphQLIgnore
public Organization getPrincipalOrg() {
return principalOrg.getForeignObject();
}
public void setPrincipalOrg(Organization principalOrg) {
this.principalOrg = new ForeignObjectHolder<>(principalOrg);
}
@GraphQLQuery(name="comments") // TODO: batch load? (used in reports/{Minimal,Show}.js
public synchronized List<Comment> loadComments() {
if (comments == null) {
comments = AnetObjectEngine.getInstance().getCommentDao().getCommentsForReport(uuid);
}
return comments;
}
public void setComments(List<Comment> comments) {
this.comments = comments;
}
@GraphQLIgnore
public List<Comment> getComments() {
return comments;
}
/*Returns a full list of the approval steps and statuses for this report
* There will be an approval action for each approval step for this report
* With information about the
*/
@GraphQLQuery(name="workflow")
public CompletableFuture<List<ReportAction>> loadWorkflow(@GraphQLRootContext Map<String, Object> context) {
if (workflow != null) {
return CompletableFuture.completedFuture(workflow);
}
AnetObjectEngine engine = AnetObjectEngine.getInstance();
return engine.getReportActionDao().getActionsForReport(context, uuid)
.thenApply(actions -> {
if (state == ReportState.APPROVED || state == ReportState.PUBLISHED) {
//For APPROVED and PUBLISHED reports, show the whole workflow of actions
workflow = actions;
} else {
final Organization ao = engine.getOrganizationForPerson(context, author.getForeignUuid()).join();
final String aoUuid = DaoUtils.getUuid(ao);
List<ApprovalStep> steps = getWorkflowForOrg(context, engine, aoUuid).join();
if (Utils.isEmptyOrNull(steps)) {
final String defaultOrgUuid = engine.getDefaultOrgUuid();
if (aoUuid == null || !Objects.equals(aoUuid, defaultOrgUuid)) {
steps = getDefaultWorkflow(context, engine, defaultOrgUuid).join();
}
}
workflow = createWorkflow(actions, steps);
}
return workflow;
});
}
@GraphQLIgnore
public List<ReportAction> getWorkflow() {
return workflow;
}
public void setWorkflow(List<ReportAction> workflow) {
this.workflow = workflow;
}
private List<ReportAction> createWorkflow(List<ReportAction> actions, List<ApprovalStep> steps) {
final List<ReportAction> workflow = new LinkedList<ReportAction>();
for (final ApprovalStep step : steps) {
//If there is an Action for this step, grab the last one (date wise)
final Optional<ReportAction> existing = actions.stream().filter(a ->
Objects.equals(DaoUtils.getUuid(step), a.getStepUuid())
).max(new Comparator<ReportAction>() {
public int compare(ReportAction a, ReportAction b) {
return a.getCreatedAt().compareTo(b.getCreatedAt());
}
});
final ReportAction action;
if (existing.isPresent()) {
action = existing.get();
} else {
//If not then create a new one and attach this step
action = new ReportAction();
}
action.setStep(step);
workflow.add(action);
}
return workflow;
}
private CompletableFuture<List<ApprovalStep>> getWorkflowForOrg(Map<String, Object> context, AnetObjectEngine engine, String aoUuid) {
if (aoUuid == null) {
return CompletableFuture.completedFuture(new ArrayList<ApprovalStep>());
}
return engine.getApprovalStepsForOrg(context, aoUuid);
}
private CompletableFuture<List<ApprovalStep>> getDefaultWorkflow(Map<String, Object> context, AnetObjectEngine engine, String defaultOrgUuid) {
if (defaultOrgUuid == null) {
throw new WebApplicationException("Missing the DEFAULT_APPROVAL_ORGANIZATION admin setting");
}
return getWorkflowForOrg(context, engine, defaultOrgUuid);
}
@GraphQLQuery(name="tags")
public CompletableFuture<List<Tag>> loadTags(@GraphQLRootContext Map<String, Object> context) {
if (tags != null) {
return CompletableFuture.completedFuture(tags);
}
return AnetObjectEngine.getInstance().getReportDao().getTagsForReport(context, uuid)
.thenApply(o -> { tags = o; return o; });
}
@GraphQLIgnore
public List<Tag> getTags() {
return tags;
}
public void setTags(List<Tag> tags) {
this.tags = tags;
}
@GraphQLQuery(name="reportSensitiveInformation")
public CompletableFuture<ReportSensitiveInformation> loadReportSensitiveInformation(@GraphQLRootContext Map<String, Object> context) {
if (reportSensitiveInformation != null) {
return CompletableFuture.completedFuture(reportSensitiveInformation);
}
return AnetObjectEngine.getInstance().getReportSensitiveInformationDao().getForReport(context, this, user)
.thenApply(o -> { reportSensitiveInformation = o; return o; });
}
@GraphQLIgnore
public ReportSensitiveInformation getReportSensitiveInformation() {
return reportSensitiveInformation;
}
public void setReportSensitiveInformation(ReportSensitiveInformation reportSensitiveInformation) {
this.reportSensitiveInformation = reportSensitiveInformation;
}
@JsonIgnore
@GraphQLIgnore
public Person getUser() {
return user;
}
@JsonIgnore
@GraphQLIgnore
public void setUser(Person user) {
this.user = user;
}
@GraphQLQuery(name="authorizationGroups") // TODO: batch load? (used in reports/{Edit,Show}.js)
public synchronized List<AuthorizationGroup> loadAuthorizationGroups() {
if (authorizationGroups == null && uuid != null) {
authorizationGroups = AnetObjectEngine.getInstance().getReportDao().getAuthorizationGroupsForReport(uuid);
}
return authorizationGroups;
}
public void setAuthorizationGroups(List<AuthorizationGroup> authorizationGroups) {
this.authorizationGroups = authorizationGroups;
}
@GraphQLIgnore
public List<AuthorizationGroup> getAuthorizationGroups() {
return authorizationGroups;
}
@Override
public boolean equals(Object other) {
if (other == null || other.getClass() != this.getClass()) {
return false;
}
Report r = (Report) other;
return Objects.equals(r.getUuid(), uuid)
&& Objects.equals(r.getState(), state)
&& Objects.equals(r.getApprovalStepUuid(), getApprovalStepUuid())
&& Objects.equals(r.getCreatedAt(), createdAt)
&& Objects.equals(r.getUpdatedAt(), updatedAt)
&& Objects.equals(r.getEngagementDate(), engagementDate)
&& Objects.equals(r.getLocationUuid(), getLocationUuid())
&& Objects.equals(r.getIntent(), intent)
&& Objects.equals(r.getExsum(), exsum)
&& Objects.equals(r.getAtmosphere(), atmosphere)
&& Objects.equals(r.getAtmosphereDetails(), atmosphereDetails)
&& Objects.equals(r.getAttendees(), attendees)
&& Objects.equals(r.getTasks(), tasks)
&& Objects.equals(r.getReportText(), reportText)
&& Objects.equals(r.getNextSteps(), nextSteps)
&& Objects.equals(r.getAuthorUuid(), getAuthorUuid())
&& Objects.equals(r.getComments(), comments)
&& Objects.equals(r.getTags(), tags)
&& Objects.equals(r.getReportSensitiveInformation(), reportSensitiveInformation)
&& Objects.equals(r.getAuthorizationGroups(), authorizationGroups);
}
@Override
public int hashCode() {
return Objects.hash(uuid, state, approvalStep, createdAt, updatedAt,
location, intent, exsum, attendees, tasks, reportText,
nextSteps, author, comments, atmosphere, atmosphereDetails, engagementDate,
tags, reportSensitiveInformation, authorizationGroups);
}
public static Report createWithUuid(String uuid) {
final Report r = new Report();
r.setUuid(uuid);
return r;
}
@Override
public String toString() {
return String.format("[uuid:%s, intent:%s]", uuid, intent);
}
}
|
NCI-Agency/anet#1252: Update report loadWorkflow documentation
|
src/main/java/mil/dds/anet/beans/Report.java
|
NCI-Agency/anet#1252: Update report loadWorkflow documentation
|
<ide><path>rc/main/java/mil/dds/anet/beans/Report.java
<ide> return comments;
<ide> }
<ide>
<del> /*Returns a full list of the approval steps and statuses for this report
<del> * There will be an approval action for each approval step for this report
<del> * With information about the
<add> /*Returns a list of report actions. It depends on the report status:
<add> * - for APPROVED or PUBLISHED reports, it returns all report actions
<add> * - for reports in other steps it only returns report actions related to
<add> * approval steps, and for each of the steps only the latest report action
<ide> */
<ide> @GraphQLQuery(name="workflow")
<ide> public CompletableFuture<List<ReportAction>> loadWorkflow(@GraphQLRootContext Map<String, Object> context) {
|
|
JavaScript
|
agpl-3.0
|
54837a5aa3f395af3f0a7f6d90a04eb4e2b496a5
| 0 |
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
|
a42f83bc-2e63-11e5-9284-b827eb9e62be
|
helloWorld.js
|
a42a046e-2e63-11e5-9284-b827eb9e62be
|
a42f83bc-2e63-11e5-9284-b827eb9e62be
|
helloWorld.js
|
a42f83bc-2e63-11e5-9284-b827eb9e62be
|
<ide><path>elloWorld.js
<del>a42a046e-2e63-11e5-9284-b827eb9e62be
<add>a42f83bc-2e63-11e5-9284-b827eb9e62be
|
|
Java
|
apache-2.0
|
c8178b4ad0ced5cc85375fef4022bf5e876055d5
| 0 |
Thellmann/callimachus,Thellmann/callimachus,jimmccusker/callimachus,edwardsph/callimachus,Thellmann/callimachus,3-Round-Stones/callimachus,jimmccusker/callimachus,3-Round-Stones/callimachus,edwardsph/callimachus,3-Round-Stones/callimachus,3-Round-Stones/callimachus,edwardsph/callimachus,jimmccusker/callimachus,jimmccusker/callimachus,Thellmann/callimachus,edwardsph/callimachus,edwardsph/callimachus,jimmccusker/callimachus,Thellmann/callimachus,3-Round-Stones/callimachus,edwardsph/callimachus,Thellmann/callimachus,jimmccusker/callimachus,3-Round-Stones/callimachus
|
/*
* Copyright 2010, Zepheira LLC Some rights reserved.
* Copyright (c) 2011 Talis Inc., Some 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 openrdf.org nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
package org.callimachusproject.concurrent;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* Common Executors used.
*
* @author James Leigh
*
*/
public class ManagedExecutors {
private static final ManagedExecutors instance = new ManagedExecutors();
public static ManagedExecutors getInstance() {
return instance;
}
private final Map<String, WeakReference<? extends ManagedThreadPool>> pools = new LinkedHashMap<String, WeakReference<? extends ManagedThreadPool>>();
private final List<ManagedThreadPoolListener> listeners = new ArrayList<ManagedThreadPoolListener>();
private ExecutorService producerThreadPool = newCachedPool("Producer");
private ExecutorService parserThreadPool = newCachedPool("Parser");
private ScheduledExecutorService timeoutThreadPool = newSingleScheduler("Timeout");
public ExecutorService getProducerThreadPool() {
return producerThreadPool;
}
public ExecutorService getParserThreadPool() {
return parserThreadPool;
}
public ScheduledExecutorService getTimeoutThreadPool() {
return timeoutThreadPool;
}
public ExecutorService newCachedPool(String name) {
return register(new ManagedThreadPool(name, true));
}
public ExecutorService newFixedThreadPool(int nThreads, String name) {
return newFixedThreadPool(nThreads,
new LinkedBlockingDeque<Runnable>(), name);
}
public ExecutorService newFixedThreadPool(int nThreads,
BlockingQueue<Runnable> queue, String name) {
return register(new ManagedThreadPool(nThreads, nThreads, 0L,
TimeUnit.MILLISECONDS, queue, name, true));
}
public ScheduledExecutorService newSingleScheduler(String name) {
return register(new ManagedScheduledThreadPool(name, true));
}
public ExecutorService newAntiDeadlockThreadPool(
BlockingQueue<Runnable> queue, String name) {
return newAntiDeadlockThreadPool(Runtime.getRuntime()
.availableProcessors() * 2 + 1, Runtime.getRuntime()
.availableProcessors() * 100, queue, name);
}
public ExecutorService newAntiDeadlockThreadPool(int corePoolSize,
int maximumPoolSize, BlockingQueue<Runnable> queue, String name) {
return register(new AntiDeadlockThreadPool(corePoolSize,
maximumPoolSize, queue, name));
}
public synchronized void addListener(ManagedThreadPoolListener listener) {
cleanup(null);
Iterator<String> iter = pools.keySet().iterator();
while (iter.hasNext()) {
String name = iter.next();
WeakReference<? extends ManagedThreadPool> ref = pools.get(name);
ManagedThreadPool pool = ref.get();
if (pool != null && !pool.isTerminated()) {
listener.threadPoolStarted(name, pool);
}
}
listeners.add(listener);
}
public synchronized void removeListener(ManagedThreadPoolListener listener) {
listeners.remove(listener);
cleanup(null);
}
public synchronized void cleanup() {
cleanup(null);
Iterator<String> iter = pools.keySet().iterator();
while (iter.hasNext()) {
String name = iter.next();
WeakReference<? extends ManagedThreadPool> ref = pools.get(name);
ManagedThreadPool get = ref.get();
if (get == null || get.isTerminated() || get.isTerminating()) {
if (get != null && !get.isTerminated() && get.isTerminating()) {
try {
get.awaitTermination(1, TimeUnit.HOURS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
for (ManagedThreadPoolListener listener : listeners) {
listener.threadPoolTerminated(name);
}
iter.remove();
}
}
}
private synchronized <T extends ManagedThreadPool> T register(T pool) {
String key = pool.toString();
assert key != null;
cleanup(key);
pools.put(key, new WeakReference<T>(pool));
for (ManagedThreadPoolListener listener : listeners) {
listener.threadPoolStarted(key, pool);
}
return pool;
}
private synchronized void cleanup(String nameToTerminate) {
Iterator<String> iter = pools.keySet().iterator();
while (iter.hasNext()) {
String name = iter.next();
WeakReference<? extends ManagedThreadPool> ref = pools.get(name);
ManagedThreadPool get = ref.get();
if (get == null || get.isTerminated() || name.equals(nameToTerminate)) {
if (name.equals(nameToTerminate) && get != null && !get.isTerminated()) {
get.shutdownNow();
try {
get.awaitTermination(1, TimeUnit.HOURS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
for (ManagedThreadPoolListener listener : listeners) {
listener.threadPoolTerminated(name);
}
iter.remove();
}
}
}
private ManagedExecutors() {
// singleton
}
}
|
src/org/callimachusproject/concurrent/ManagedExecutors.java
|
/*
* Copyright 2010, Zepheira LLC Some rights reserved.
* Copyright (c) 2011 Talis Inc., Some 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 openrdf.org nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
package org.callimachusproject.concurrent;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* Common Executors used.
*
* @author James Leigh
*
*/
public class ManagedExecutors {
private static final ManagedExecutors instance = new ManagedExecutors();
public static ManagedExecutors getInstance() {
return instance;
}
private final Map<String, WeakReference<? extends ManagedThreadPool>> pools = new LinkedHashMap<String, WeakReference<? extends ManagedThreadPool>>();
private final List<ManagedThreadPoolListener> listeners = new ArrayList<ManagedThreadPoolListener>();
private ExecutorService producerThreadPool = newCachedPool("Producer");
private ExecutorService parserThreadPool = newCachedPool("Parser");
private ScheduledExecutorService timeoutThreadPool = newSingleScheduler("Timeout");
public ExecutorService getProducerThreadPool() {
return producerThreadPool;
}
public ExecutorService getParserThreadPool() {
return parserThreadPool;
}
public ScheduledExecutorService getTimeoutThreadPool() {
return timeoutThreadPool;
}
public ExecutorService newCachedPool(String name) {
return register(new ManagedThreadPool(name, true));
}
public ExecutorService newFixedThreadPool(int nThreads,
BlockingQueue<Runnable> queue, String name) {
return register(new ManagedThreadPool(nThreads, nThreads, 0L,
TimeUnit.MILLISECONDS, queue, "HttpTriage", true));
}
public ScheduledExecutorService newSingleScheduler(String name) {
return register(new ManagedScheduledThreadPool(name, true));
}
public ExecutorService newAntiDeadlockThreadPool(
BlockingQueue<Runnable> queue, String name) {
return newAntiDeadlockThreadPool(Runtime.getRuntime()
.availableProcessors() * 2 + 1, Runtime.getRuntime()
.availableProcessors() * 100, queue, name);
}
public ExecutorService newAntiDeadlockThreadPool(int corePoolSize,
int maximumPoolSize, BlockingQueue<Runnable> queue, String name) {
return register(new AntiDeadlockThreadPool(corePoolSize,
maximumPoolSize, queue, name));
}
public synchronized void addListener(ManagedThreadPoolListener listener) {
cleanup(null);
Iterator<String> iter = pools.keySet().iterator();
while (iter.hasNext()) {
String name = iter.next();
WeakReference<? extends ManagedThreadPool> ref = pools.get(name);
ManagedThreadPool pool = ref.get();
if (pool != null && !pool.isTerminated()) {
listener.threadPoolStarted(name, pool);
}
}
listeners.add(listener);
}
public synchronized void removeListener(ManagedThreadPoolListener listener) {
listeners.remove(listener);
cleanup(null);
}
public synchronized void cleanup() {
cleanup(null);
Iterator<String> iter = pools.keySet().iterator();
while (iter.hasNext()) {
String name = iter.next();
WeakReference<? extends ManagedThreadPool> ref = pools.get(name);
ManagedThreadPool get = ref.get();
if (get == null || get.isTerminated() || get.isTerminating()) {
if (get != null && !get.isTerminated() && get.isTerminating()) {
try {
get.awaitTermination(1, TimeUnit.HOURS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
for (ManagedThreadPoolListener listener : listeners) {
listener.threadPoolTerminated(name);
}
iter.remove();
}
}
}
private synchronized <T extends ManagedThreadPool> T register(T pool) {
String key = pool.toString();
assert key != null;
cleanup(key);
pools.put(key, new WeakReference<T>(pool));
for (ManagedThreadPoolListener listener : listeners) {
listener.threadPoolStarted(key, pool);
}
return pool;
}
private synchronized void cleanup(String nameToTerminate) {
Iterator<String> iter = pools.keySet().iterator();
while (iter.hasNext()) {
String name = iter.next();
WeakReference<? extends ManagedThreadPool> ref = pools.get(name);
ManagedThreadPool get = ref.get();
if (get == null || get.isTerminated() || name.equals(nameToTerminate)) {
if (name.equals(nameToTerminate) && get != null && !get.isTerminated()) {
get.shutdownNow();
try {
get.awaitTermination(1, TimeUnit.HOURS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
for (ManagedThreadPoolListener listener : listeners) {
listener.threadPoolTerminated(name);
}
iter.remove();
}
}
}
private ManagedExecutors() {
// singleton
}
}
|
Limit the number of setup threads
|
src/org/callimachusproject/concurrent/ManagedExecutors.java
|
Limit the number of setup threads
|
<ide><path>rc/org/callimachusproject/concurrent/ManagedExecutors.java
<ide> import java.util.Map;
<ide> import java.util.concurrent.BlockingQueue;
<ide> import java.util.concurrent.ExecutorService;
<add>import java.util.concurrent.LinkedBlockingDeque;
<ide> import java.util.concurrent.ScheduledExecutorService;
<ide> import java.util.concurrent.TimeUnit;
<ide>
<ide> return register(new ManagedThreadPool(name, true));
<ide> }
<ide>
<add> public ExecutorService newFixedThreadPool(int nThreads, String name) {
<add> return newFixedThreadPool(nThreads,
<add> new LinkedBlockingDeque<Runnable>(), name);
<add> }
<add>
<ide> public ExecutorService newFixedThreadPool(int nThreads,
<ide> BlockingQueue<Runnable> queue, String name) {
<ide> return register(new ManagedThreadPool(nThreads, nThreads, 0L,
<del> TimeUnit.MILLISECONDS, queue, "HttpTriage", true));
<add> TimeUnit.MILLISECONDS, queue, name, true));
<ide> }
<ide>
<ide> public ScheduledExecutorService newSingleScheduler(String name) {
|
|
Java
|
apache-2.0
|
error: pathspec 'anno4j-core/src/test/java/com/github/anno4j/persisting/CRUDTest.java' did not match any file(s) known to git
|
78cbf5922c91922f7fe518b76088fd6c06ebb4fd
| 1 |
anno4j/anno4j,anno4j/anno4j
|
package com.github.anno4j.persisting;
import com.github.anno4j.Anno4j;
import com.github.anno4j.Transaction;
import com.github.anno4j.model.Agent;
import com.github.anno4j.model.Annotation;
import com.github.anno4j.model.Audience;
import com.github.anno4j.model.Body;
import com.github.anno4j.model.impl.ResourceObject;
import com.github.anno4j.model.impl.agent.Person;
import com.github.anno4j.model.namespaces.*;
import com.google.common.collect.Sets;
import org.junit.Test;
import org.openrdf.model.Resource;
import org.openrdf.model.Statement;
import org.openrdf.model.URI;
import org.openrdf.model.Value;
import org.openrdf.model.impl.LiteralImpl;
import org.openrdf.model.impl.StatementImpl;
import org.openrdf.model.impl.URIImpl;
import org.openrdf.repository.RepositoryConnection;
import org.openrdf.repository.RepositoryException;
import org.openrdf.repository.RepositoryResult;
import org.openrdf.repository.object.ObjectConnection;
import org.openrdf.repository.sail.SailRepository;
import org.openrdf.sail.memory.MemoryStore;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import static org.junit.Assert.*;
/**
* Basic test for the CRUD operations of Anno4j - Create, Read, Update, Delete.
* Thus these tests cover vary basic behaviour of Anno4j under different assumptions.
*/
public class CRUDTest {
/**
* Returns all statements that are present in any context of a repository.
* The returned set does not contain any inferred triples.
* @param connection A connection to the repository to query.
* @return Returns the set of all triples present in the connected repository.
* @throws RepositoryException Thrown if an error occurs while querying the repository.
*/
private Collection<Statement> getStatements(RepositoryConnection connection) throws RepositoryException {
return getStatements(connection, null, null, null);
}
/**
* Returns all statements that are present in any context of a repository having the specified subject, predicate and/or object.
* @param connection A connection to the repository to query.
* @param subject The subject the returned triples should have or null for any subject.
* @param predicate The predicate the returned triples should have or null for any predicate.
* @param object The object the returned triples should have or null for any object.
* @return Returns the set of all triples present in the repository having the desired spo-structure.
* @throws RepositoryException Thrown if an error occurs while querying the repository.
*/
private Collection<Statement> getStatements(RepositoryConnection connection, Resource subject, URI predicate, Value object) throws RepositoryException {
// Query the repository:
RepositoryResult<Statement> result = connection.getStatements(subject, predicate, object, false);
// Fetch all statements from the result:
Collection<Statement> statements = new HashSet<>();
while (result.hasNext()) {
statements.add(result.next());
}
return statements;
}
/**
* Tests basic object creation and persistence of triples.
*/
@Test
public void testCreate() throws Exception {
// Create an Anno4j instance and get its repository connection for direct triple access:
Anno4j anno4j = new Anno4j(new SailRepository(new MemoryStore()), null, false);
RepositoryConnection repoConnection = anno4j.getRepository().getConnection();
// Test simple object creation:
Person p = anno4j.createObject(Person.class, (Resource) new URIImpl("urn:anno4j_test:p1"));
p.setMbox("[email protected]");
// Two statments (rdf:type, foaf:mbox) should be created:
Collection<Statement> statements = getStatements(repoConnection);
assertEquals(2, statements.size());
assertTrue(statements.contains(new StatementImpl(new URIImpl("urn:anno4j_test:p1"),
new URIImpl(RDF.TYPE),
new URIImpl(FOAF.PERSON))));
assertTrue(statements.contains(new StatementImpl(new URIImpl("urn:anno4j_test:p1"),
new URIImpl(FOAF.MBOX),
new LiteralImpl("[email protected]"))));
}
/**
* Tests re-creation of already created objects in the same context.
*/
@Test
public void testCreateExisting() throws Exception {
// Create an Anno4j instance and get its object connection:
Anno4j anno4j = new Anno4j(new SailRepository(new MemoryStore()), null, false);
ObjectConnection connection = anno4j.getObjectRepository().getConnection();
// Create an object:
Person a = anno4j.createObject(Person.class, (Resource) new URIImpl("urn:anno4j_test:p1"));
a.setMbox("[email protected]");
// Create another object with the same IRI:
Person b = anno4j.createObject(Person.class, (Resource) new URIImpl("urn:anno4j_test:p1"));
// The new object should have the same value for the property foaf:mbox:
assertEquals("[email protected]", b.getMbox());
// The objects should be comparable:
assertTrue(a.equals(b) && b.equals(a));
// Modification done to the second object should persist to the first (after refreshing):
b.setMbox("[email protected]");
connection.refresh(a);
assertEquals("[email protected]", a.getMbox());
}
/**
* Tests re-creation of already created objects in a different context.
*/
@Test
public void testCreateExistingOtherContext() throws Exception {
// Create an Anno4j instance and get its object connection:
Anno4j anno4j = new Anno4j(new SailRepository(new MemoryStore()), null, false);
ObjectConnection connection = anno4j.getObjectRepository().getConnection();
// Create an object:
Person a = anno4j.createObject(Person.class, (Resource) new URIImpl("urn:anno4j_test:p1"));
a.setMbox("[email protected]");
// Create another object with the same IRI:
Person b = anno4j.createObject(Person.class, new URIImpl("urn:anno4j_test:context1"), new URIImpl("urn:anno4j_test:p1"));
// The new object should NOT have a value for the property foaf:mbox:
assertNull(b.getMbox());
// The objects should be comparable (because the resource identified by an IRI is always the same):
assertTrue(a.equals(b) && b.equals(a));
// Modification done to the second object should NOT persist to the first (after refreshing):
b.setMbox("[email protected]");
connection.refresh(a);
assertEquals("[email protected]", a.getMbox());
}
/**
* Tests reading objects and their property values from the repository.
*/
@Test
public void testRead() throws Exception {
// Create an Anno4j instance and get its repository connection for direct triple access:
Anno4j anno4j = new Anno4j(new SailRepository(new MemoryStore()), null, false);
RepositoryConnection repoConnection = anno4j.getRepository().getConnection();
// Add some triples to the repository:
repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:p1"),
new URIImpl(RDF.TYPE),
new URIImpl(FOAF.PERSON)));
repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:p1"),
new URIImpl(FOAF.MBOX),
new LiteralImpl("[email protected]")));
Person p = anno4j.findByID(Person.class, "urn:anno4j_test:p1");
assertNotNull(p);
assertEquals("[email protected]", p.getMbox());
}
/**
* Tests behaviour of Anno4j when the type of resources in the repository are different from the ones in the Java domain model.
*/
@Test
public void testReadWrongType() throws Exception {
// Create an Anno4j instance and get its repository connection for direct triple access:
Anno4j anno4j = new Anno4j(new SailRepository(new MemoryStore()), null, false);
RepositoryConnection repoConnection = anno4j.getRepository().getConnection();
// Add some triples to the repository:
repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:p1"),
new URIImpl(RDF.TYPE),
new URIImpl("urn:anno4j_test:some_other_class")));
repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:a2"),
new URIImpl(RDF.TYPE),
new URIImpl(OADM.ANNOTATION)));
repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:a2"),
new URIImpl(OADM.HAS_BODY),
new LiteralImpl("I'm not an IRI.")));
// Test retrieving a resource with a different type:
Person p1 = anno4j.findByID(Person.class, "urn:anno4j_test:p1");
assertNull(p1);
// Test retrieving a property value with wrong type:
boolean exceptionThrown = false;
try {
Annotation a2 = anno4j.findByID(Annotation.class, "urn:anno4j_test:a2");
Set<Body> bodies = a2.getBodies();
Body body = bodies.iterator().next();
body.getResourceAsString(); // Prevent code elimination
} catch (ClassCastException e) {
exceptionThrown = true;
}
assertTrue(exceptionThrown);
}
/**
* Tests reading and modifying the same resource in different contexts.
*/
@Test
public void testReadUpdateOtherContext() throws Exception {
// Create an Anno4j instance and get its repository connection for direct triple access:
Anno4j anno4j = new Anno4j(new SailRepository(new MemoryStore()), null, false);
RepositoryConnection repoConnection = anno4j.getRepository().getConnection();
// Add some triples to the repository:
repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:p1"),
new URIImpl(RDF.TYPE),
new URIImpl(FOAF.PERSON)));
repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:p1"),
new URIImpl(FOAF.MBOX),
new LiteralImpl("[email protected]")));
repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:p1"),
new URIImpl(RDF.TYPE),
new URIImpl(FOAF.PERSON)), new URIImpl("urn:anno4j_test:context1"));
repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:p1"),
new URIImpl(FOAF.MBOX),
new LiteralImpl("[email protected]")), new URIImpl("urn:anno4j_test:context1"));
Person a = anno4j.findByID(Person.class, "urn:anno4j_test:p1");
// Use a transaction to access objects from the other context:
Transaction transaction = anno4j.createTransaction(new URIImpl("urn:anno4j_test:context1"));
transaction.begin();
Person b = transaction.findByID(Person.class, "urn:anno4j_test:p1");
assertEquals("[email protected]", a.getMbox());
assertEquals("[email protected]", b.getMbox());
a.setMbox("[email protected]");
assertEquals("[email protected]", a.getMbox());
assertEquals("[email protected]", b.getMbox());
}
/**
* Tests reading of resources that do not have a type assigned in the repository.
*/
@Test
public void testReadNoType() throws Exception {
// Create an Anno4j instance and get its repository connection for direct triple access:
Anno4j anno4j = new Anno4j(new SailRepository(new MemoryStore()), null, false);
RepositoryConnection repoConnection = anno4j.getRepository().getConnection();
// Resource urn:anno4j_test:p1 is present but does not have a rdf:type
repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:p1"),
new URIImpl(FOAF.MBOX),
new LiteralImpl("[email protected]")));
// Try retrieving the resource with a specific type:
Person p = anno4j.findByID(Person.class, "urn:anno4j_test:p1");
assertNull(p);
}
/**
* Tests retrieving resources with a more general type than specified in the repository.
*/
@Test
public void testReadGeneralType() throws Exception {
// Create an Anno4j instance and get its repository connection for direct triple access:
Anno4j anno4j = new Anno4j(new SailRepository(new MemoryStore()), null, false);
RepositoryConnection repoConnection = anno4j.getRepository().getConnection();
// Add some triples to the repository:
repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:p1"),
new URIImpl(RDF.TYPE),
new URIImpl(FOAF.PERSON)));
ResourceObject p = anno4j.findByID(Person.class, "urn:anno4j_test:p1");
assertNotNull(p);
p = anno4j.findByID(Agent.class, "urn:anno4j_test:p1");
assertNotNull(p);
p = anno4j.findByID(ResourceObject.class, "urn:anno4j_test:p1");
assertNotNull(p);
}
/**
* Tests the triples contained in the repository after updating property values via resource objects.
*/
@Test
public void testUpdate() throws Exception {
// Create an Anno4j instance and get its repository connection for direct triple access:
Anno4j anno4j = new Anno4j(new SailRepository(new MemoryStore()), null, false);
RepositoryConnection repoConnection = anno4j.getRepository().getConnection();
// Add some triples to the repository:
repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:p1"),
new URIImpl(RDF.TYPE),
new URIImpl(FOAF.PERSON)));
repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:p1"),
new URIImpl(FOAF.MBOX),
new LiteralImpl("[email protected]")));
repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:a1"),
new URIImpl(RDF.TYPE),
new URIImpl(OADM.ANNOTATION)));
repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:a1"),
new URIImpl(OADM.BODY_TEXT),
new LiteralImpl("Text 1")));
repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:a1"),
new URIImpl(OADM.BODY_TEXT),
new LiteralImpl("Text 2")));
// Modified single-valued property of p1:
Person p1 = anno4j.findByID(Person.class, "urn:anno4j_test:p1");
p1.setMbox("[email protected]");
// Get all triples with p1 as subject. There should be exavtly two (rdf:type and new foaf:mbox):
Collection<Statement> p1Statements = getStatements(repoConnection, new URIImpl("urn:anno4j_test:p1"), null, null);
assertEquals(2, p1Statements.size());
assertTrue(p1Statements.contains(new StatementImpl(new URIImpl("urn:anno4j_test:p1"),
new URIImpl(RDF.TYPE),
new URIImpl(FOAF.PERSON))));
assertTrue(p1Statements.contains(new StatementImpl(new URIImpl("urn:anno4j_test:p1"),
new URIImpl(FOAF.MBOX),
new LiteralImpl("[email protected]"))));
// Modify multi-valued property of a1:
Annotation a1 = anno4j.findByID(Annotation.class, "urn:anno4j_test:a1");
a1.setBodyTexts(Sets.newHashSet("Text 1"));
// Get the triples with a1 as subject. There should be only two now (rdf:type and the oadm:body_text just set):
Collection<Statement> a1Statements = getStatements(repoConnection, new URIImpl("urn:anno4j_test:a1"), null, null);
assertEquals(2, a1Statements.size());
assertTrue(a1Statements.contains(new StatementImpl(new URIImpl("urn:anno4j_test:a1"),
new URIImpl(RDF.TYPE),
new URIImpl(OADM.ANNOTATION))));
assertTrue(a1Statements.contains(new StatementImpl(new URIImpl("urn:anno4j_test:a1"),
new URIImpl(OADM.BODY_TEXT),
new LiteralImpl("Text 1"))));
}
/**
* Tests propagation of updates across different objects for the same resource.
*/
@Test
public void testUpgradePropagation() throws Exception {
// Create an Anno4j instance and get its object connection:
Anno4j anno4j = new Anno4j(new SailRepository(new MemoryStore()), null, false);
ObjectConnection connection = anno4j.getObjectRepository().getConnection();
// Get two objects for the same resource:
Annotation a = anno4j.createObject(Annotation.class, (Resource) new URIImpl("urn:anno4j_test:a1"));
Annotation b = anno4j.findByID(Annotation.class, "urn:anno4j_test:a1");
// Test that both objects have the same values after setting at one:
a.setBodyTexts(Sets.newHashSet("a"));
assertEquals(Sets.newHashSet("a"), a.getBodyTexts());
assertEquals(Sets.newHashSet("a"), b.getBodyTexts());
// Refresh objects:
connection.refresh(a);
connection.refresh(b);
// Test other way round (after values have been cached):
b.setBodyTexts(Sets.newHashSet("a", "b"));
assertEquals(Sets.newHashSet("a", "b"), new HashSet<>(a.getBodyTexts()));
assertEquals(Sets.newHashSet("a", "b"), new HashSet<>(b.getBodyTexts()));
}
/**
* Tests deletion of resource objects and its effect on the repository.
*/
@Test
public void testDelete() throws Exception {
// Create an Anno4j instance and get its repository connection for direct triple access:
Anno4j anno4j = new Anno4j(new SailRepository(new MemoryStore()), null, false);
RepositoryConnection repoConnection = anno4j.getRepository().getConnection();
// Add some triples to the repository:
/*
Persisted triples:
:p1 a foaf:Person ;
foaf:mbox "[email protected]" .
:a1 a oadm:Annotation ;
oadm:bodyText "Text 1", "Text 2" ;
schema:audience :b1, :b2 .
:b1 a schema:Audience .
*/
repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:p1"),
new URIImpl(RDF.TYPE),
new URIImpl(FOAF.PERSON)));
repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:p1"),
new URIImpl(FOAF.MBOX),
new LiteralImpl("[email protected]")));
repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:a1"),
new URIImpl(RDF.TYPE),
new URIImpl(OADM.ANNOTATION)));
repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:a1"),
new URIImpl(OADM.BODY_TEXT),
new LiteralImpl("Text 1")));
repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:a1"),
new URIImpl(OADM.BODY_TEXT),
new LiteralImpl("Text 2")));
repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:a1"),
new URIImpl(SCHEMA.AUDIENCE_RELATIONSHIP),
new URIImpl("urn:anno4j_test:b1")));
repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:a1"),
new URIImpl(SCHEMA.AUDIENCE_RELATIONSHIP),
new URIImpl("urn:anno4j_test:b2")));
repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:b1"),
new URIImpl(RDF.TYPE),
new URIImpl(SCHEMA.AUDIENCE_CLASS)));
// Test that all triples are removed:
Person p1 = anno4j.findByID(Person.class, "urn:anno4j_test:p1");
p1.delete();
Collection<Statement> p1Statements = getStatements(repoConnection, new URIImpl("urn:anno4j_test:p1"), null, null);
assertEquals(0, p1Statements.size());
// Test that all triples are removed that have a1 as subject. b1 should be still retrievable:
Annotation a1 = anno4j.findByID(Annotation.class, "urn:anno4j_test:a1");
a1.delete();
Collection<Statement> a1Statements = getStatements(repoConnection, new URIImpl("urn:anno4j_test:a1"), null, null);
assertEquals(0, a1Statements.size());
Audience b1 = anno4j.findByID(Audience.class, "urn:anno4j_test:b1");
assertNotNull(b1);
// After removing :b1 the repository should be empty. :b2 is removed because it didn't occur as a subject:
b1.delete();
Collection<Statement> allStatements = getStatements(repoConnection);
assertEquals(0, allStatements.size());
}
}
|
anno4j-core/src/test/java/com/github/anno4j/persisting/CRUDTest.java
|
Tests for CRUD behaviour of Anno4j.
|
anno4j-core/src/test/java/com/github/anno4j/persisting/CRUDTest.java
|
Tests for CRUD behaviour of Anno4j.
|
<ide><path>nno4j-core/src/test/java/com/github/anno4j/persisting/CRUDTest.java
<add>package com.github.anno4j.persisting;
<add>
<add>import com.github.anno4j.Anno4j;
<add>import com.github.anno4j.Transaction;
<add>import com.github.anno4j.model.Agent;
<add>import com.github.anno4j.model.Annotation;
<add>import com.github.anno4j.model.Audience;
<add>import com.github.anno4j.model.Body;
<add>import com.github.anno4j.model.impl.ResourceObject;
<add>import com.github.anno4j.model.impl.agent.Person;
<add>import com.github.anno4j.model.namespaces.*;
<add>import com.google.common.collect.Sets;
<add>import org.junit.Test;
<add>import org.openrdf.model.Resource;
<add>import org.openrdf.model.Statement;
<add>import org.openrdf.model.URI;
<add>import org.openrdf.model.Value;
<add>import org.openrdf.model.impl.LiteralImpl;
<add>import org.openrdf.model.impl.StatementImpl;
<add>import org.openrdf.model.impl.URIImpl;
<add>import org.openrdf.repository.RepositoryConnection;
<add>import org.openrdf.repository.RepositoryException;
<add>import org.openrdf.repository.RepositoryResult;
<add>import org.openrdf.repository.object.ObjectConnection;
<add>import org.openrdf.repository.sail.SailRepository;
<add>import org.openrdf.sail.memory.MemoryStore;
<add>
<add>import java.util.Collection;
<add>import java.util.HashSet;
<add>import java.util.Set;
<add>
<add>import static org.junit.Assert.*;
<add>
<add>/**
<add> * Basic test for the CRUD operations of Anno4j - Create, Read, Update, Delete.
<add> * Thus these tests cover vary basic behaviour of Anno4j under different assumptions.
<add> */
<add>public class CRUDTest {
<add>
<add> /**
<add> * Returns all statements that are present in any context of a repository.
<add> * The returned set does not contain any inferred triples.
<add> * @param connection A connection to the repository to query.
<add> * @return Returns the set of all triples present in the connected repository.
<add> * @throws RepositoryException Thrown if an error occurs while querying the repository.
<add> */
<add> private Collection<Statement> getStatements(RepositoryConnection connection) throws RepositoryException {
<add> return getStatements(connection, null, null, null);
<add> }
<add>
<add> /**
<add> * Returns all statements that are present in any context of a repository having the specified subject, predicate and/or object.
<add> * @param connection A connection to the repository to query.
<add> * @param subject The subject the returned triples should have or null for any subject.
<add> * @param predicate The predicate the returned triples should have or null for any predicate.
<add> * @param object The object the returned triples should have or null for any object.
<add> * @return Returns the set of all triples present in the repository having the desired spo-structure.
<add> * @throws RepositoryException Thrown if an error occurs while querying the repository.
<add> */
<add> private Collection<Statement> getStatements(RepositoryConnection connection, Resource subject, URI predicate, Value object) throws RepositoryException {
<add> // Query the repository:
<add> RepositoryResult<Statement> result = connection.getStatements(subject, predicate, object, false);
<add>
<add> // Fetch all statements from the result:
<add> Collection<Statement> statements = new HashSet<>();
<add> while (result.hasNext()) {
<add> statements.add(result.next());
<add> }
<add> return statements;
<add> }
<add>
<add>
<add> /**
<add> * Tests basic object creation and persistence of triples.
<add> */
<add> @Test
<add> public void testCreate() throws Exception {
<add> // Create an Anno4j instance and get its repository connection for direct triple access:
<add> Anno4j anno4j = new Anno4j(new SailRepository(new MemoryStore()), null, false);
<add> RepositoryConnection repoConnection = anno4j.getRepository().getConnection();
<add>
<add> // Test simple object creation:
<add> Person p = anno4j.createObject(Person.class, (Resource) new URIImpl("urn:anno4j_test:p1"));
<add> p.setMbox("[email protected]");
<add>
<add> // Two statments (rdf:type, foaf:mbox) should be created:
<add> Collection<Statement> statements = getStatements(repoConnection);
<add> assertEquals(2, statements.size());
<add> assertTrue(statements.contains(new StatementImpl(new URIImpl("urn:anno4j_test:p1"),
<add> new URIImpl(RDF.TYPE),
<add> new URIImpl(FOAF.PERSON))));
<add> assertTrue(statements.contains(new StatementImpl(new URIImpl("urn:anno4j_test:p1"),
<add> new URIImpl(FOAF.MBOX),
<add> new LiteralImpl("[email protected]"))));
<add> }
<add>
<add> /**
<add> * Tests re-creation of already created objects in the same context.
<add> */
<add> @Test
<add> public void testCreateExisting() throws Exception {
<add> // Create an Anno4j instance and get its object connection:
<add> Anno4j anno4j = new Anno4j(new SailRepository(new MemoryStore()), null, false);
<add> ObjectConnection connection = anno4j.getObjectRepository().getConnection();
<add>
<add> // Create an object:
<add> Person a = anno4j.createObject(Person.class, (Resource) new URIImpl("urn:anno4j_test:p1"));
<add> a.setMbox("[email protected]");
<add>
<add> // Create another object with the same IRI:
<add> Person b = anno4j.createObject(Person.class, (Resource) new URIImpl("urn:anno4j_test:p1"));
<add>
<add> // The new object should have the same value for the property foaf:mbox:
<add> assertEquals("[email protected]", b.getMbox());
<add>
<add> // The objects should be comparable:
<add> assertTrue(a.equals(b) && b.equals(a));
<add>
<add> // Modification done to the second object should persist to the first (after refreshing):
<add> b.setMbox("[email protected]");
<add> connection.refresh(a);
<add> assertEquals("[email protected]", a.getMbox());
<add> }
<add>
<add> /**
<add> * Tests re-creation of already created objects in a different context.
<add> */
<add> @Test
<add> public void testCreateExistingOtherContext() throws Exception {
<add> // Create an Anno4j instance and get its object connection:
<add> Anno4j anno4j = new Anno4j(new SailRepository(new MemoryStore()), null, false);
<add> ObjectConnection connection = anno4j.getObjectRepository().getConnection();
<add>
<add> // Create an object:
<add> Person a = anno4j.createObject(Person.class, (Resource) new URIImpl("urn:anno4j_test:p1"));
<add> a.setMbox("[email protected]");
<add>
<add> // Create another object with the same IRI:
<add> Person b = anno4j.createObject(Person.class, new URIImpl("urn:anno4j_test:context1"), new URIImpl("urn:anno4j_test:p1"));
<add>
<add> // The new object should NOT have a value for the property foaf:mbox:
<add> assertNull(b.getMbox());
<add>
<add> // The objects should be comparable (because the resource identified by an IRI is always the same):
<add> assertTrue(a.equals(b) && b.equals(a));
<add>
<add> // Modification done to the second object should NOT persist to the first (after refreshing):
<add> b.setMbox("[email protected]");
<add> connection.refresh(a);
<add> assertEquals("[email protected]", a.getMbox());
<add> }
<add>
<add> /**
<add> * Tests reading objects and their property values from the repository.
<add> */
<add> @Test
<add> public void testRead() throws Exception {
<add> // Create an Anno4j instance and get its repository connection for direct triple access:
<add> Anno4j anno4j = new Anno4j(new SailRepository(new MemoryStore()), null, false);
<add> RepositoryConnection repoConnection = anno4j.getRepository().getConnection();
<add>
<add> // Add some triples to the repository:
<add> repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:p1"),
<add> new URIImpl(RDF.TYPE),
<add> new URIImpl(FOAF.PERSON)));
<add> repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:p1"),
<add> new URIImpl(FOAF.MBOX),
<add> new LiteralImpl("[email protected]")));
<add>
<add> Person p = anno4j.findByID(Person.class, "urn:anno4j_test:p1");
<add> assertNotNull(p);
<add> assertEquals("[email protected]", p.getMbox());
<add> }
<add>
<add> /**
<add> * Tests behaviour of Anno4j when the type of resources in the repository are different from the ones in the Java domain model.
<add> */
<add> @Test
<add> public void testReadWrongType() throws Exception {
<add> // Create an Anno4j instance and get its repository connection for direct triple access:
<add> Anno4j anno4j = new Anno4j(new SailRepository(new MemoryStore()), null, false);
<add> RepositoryConnection repoConnection = anno4j.getRepository().getConnection();
<add>
<add> // Add some triples to the repository:
<add> repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:p1"),
<add> new URIImpl(RDF.TYPE),
<add> new URIImpl("urn:anno4j_test:some_other_class")));
<add> repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:a2"),
<add> new URIImpl(RDF.TYPE),
<add> new URIImpl(OADM.ANNOTATION)));
<add> repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:a2"),
<add> new URIImpl(OADM.HAS_BODY),
<add> new LiteralImpl("I'm not an IRI.")));
<add>
<add> // Test retrieving a resource with a different type:
<add> Person p1 = anno4j.findByID(Person.class, "urn:anno4j_test:p1");
<add> assertNull(p1);
<add>
<add> // Test retrieving a property value with wrong type:
<add> boolean exceptionThrown = false;
<add> try {
<add> Annotation a2 = anno4j.findByID(Annotation.class, "urn:anno4j_test:a2");
<add> Set<Body> bodies = a2.getBodies();
<add> Body body = bodies.iterator().next();
<add> body.getResourceAsString(); // Prevent code elimination
<add> } catch (ClassCastException e) {
<add> exceptionThrown = true;
<add> }
<add> assertTrue(exceptionThrown);
<add> }
<add>
<add> /**
<add> * Tests reading and modifying the same resource in different contexts.
<add> */
<add> @Test
<add> public void testReadUpdateOtherContext() throws Exception {
<add> // Create an Anno4j instance and get its repository connection for direct triple access:
<add> Anno4j anno4j = new Anno4j(new SailRepository(new MemoryStore()), null, false);
<add> RepositoryConnection repoConnection = anno4j.getRepository().getConnection();
<add>
<add> // Add some triples to the repository:
<add> repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:p1"),
<add> new URIImpl(RDF.TYPE),
<add> new URIImpl(FOAF.PERSON)));
<add> repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:p1"),
<add> new URIImpl(FOAF.MBOX),
<add> new LiteralImpl("[email protected]")));
<add> repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:p1"),
<add> new URIImpl(RDF.TYPE),
<add> new URIImpl(FOAF.PERSON)), new URIImpl("urn:anno4j_test:context1"));
<add> repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:p1"),
<add> new URIImpl(FOAF.MBOX),
<add> new LiteralImpl("[email protected]")), new URIImpl("urn:anno4j_test:context1"));
<add>
<add> Person a = anno4j.findByID(Person.class, "urn:anno4j_test:p1");
<add>
<add> // Use a transaction to access objects from the other context:
<add> Transaction transaction = anno4j.createTransaction(new URIImpl("urn:anno4j_test:context1"));
<add> transaction.begin();
<add> Person b = transaction.findByID(Person.class, "urn:anno4j_test:p1");
<add> assertEquals("[email protected]", a.getMbox());
<add> assertEquals("[email protected]", b.getMbox());
<add> a.setMbox("[email protected]");
<add> assertEquals("[email protected]", a.getMbox());
<add> assertEquals("[email protected]", b.getMbox());
<add> }
<add>
<add> /**
<add> * Tests reading of resources that do not have a type assigned in the repository.
<add> */
<add> @Test
<add> public void testReadNoType() throws Exception {
<add> // Create an Anno4j instance and get its repository connection for direct triple access:
<add> Anno4j anno4j = new Anno4j(new SailRepository(new MemoryStore()), null, false);
<add> RepositoryConnection repoConnection = anno4j.getRepository().getConnection();
<add>
<add> // Resource urn:anno4j_test:p1 is present but does not have a rdf:type
<add> repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:p1"),
<add> new URIImpl(FOAF.MBOX),
<add> new LiteralImpl("[email protected]")));
<add>
<add> // Try retrieving the resource with a specific type:
<add> Person p = anno4j.findByID(Person.class, "urn:anno4j_test:p1");
<add> assertNull(p);
<add> }
<add>
<add> /**
<add> * Tests retrieving resources with a more general type than specified in the repository.
<add> */
<add> @Test
<add> public void testReadGeneralType() throws Exception {
<add> // Create an Anno4j instance and get its repository connection for direct triple access:
<add> Anno4j anno4j = new Anno4j(new SailRepository(new MemoryStore()), null, false);
<add> RepositoryConnection repoConnection = anno4j.getRepository().getConnection();
<add>
<add> // Add some triples to the repository:
<add> repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:p1"),
<add> new URIImpl(RDF.TYPE),
<add> new URIImpl(FOAF.PERSON)));
<add>
<add> ResourceObject p = anno4j.findByID(Person.class, "urn:anno4j_test:p1");
<add> assertNotNull(p);
<add> p = anno4j.findByID(Agent.class, "urn:anno4j_test:p1");
<add> assertNotNull(p);
<add> p = anno4j.findByID(ResourceObject.class, "urn:anno4j_test:p1");
<add> assertNotNull(p);
<add> }
<add>
<add> /**
<add> * Tests the triples contained in the repository after updating property values via resource objects.
<add> */
<add> @Test
<add> public void testUpdate() throws Exception {
<add> // Create an Anno4j instance and get its repository connection for direct triple access:
<add> Anno4j anno4j = new Anno4j(new SailRepository(new MemoryStore()), null, false);
<add> RepositoryConnection repoConnection = anno4j.getRepository().getConnection();
<add>
<add> // Add some triples to the repository:
<add> repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:p1"),
<add> new URIImpl(RDF.TYPE),
<add> new URIImpl(FOAF.PERSON)));
<add> repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:p1"),
<add> new URIImpl(FOAF.MBOX),
<add> new LiteralImpl("[email protected]")));
<add> repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:a1"),
<add> new URIImpl(RDF.TYPE),
<add> new URIImpl(OADM.ANNOTATION)));
<add> repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:a1"),
<add> new URIImpl(OADM.BODY_TEXT),
<add> new LiteralImpl("Text 1")));
<add> repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:a1"),
<add> new URIImpl(OADM.BODY_TEXT),
<add> new LiteralImpl("Text 2")));
<add>
<add> // Modified single-valued property of p1:
<add> Person p1 = anno4j.findByID(Person.class, "urn:anno4j_test:p1");
<add> p1.setMbox("[email protected]");
<add> // Get all triples with p1 as subject. There should be exavtly two (rdf:type and new foaf:mbox):
<add> Collection<Statement> p1Statements = getStatements(repoConnection, new URIImpl("urn:anno4j_test:p1"), null, null);
<add> assertEquals(2, p1Statements.size());
<add> assertTrue(p1Statements.contains(new StatementImpl(new URIImpl("urn:anno4j_test:p1"),
<add> new URIImpl(RDF.TYPE),
<add> new URIImpl(FOAF.PERSON))));
<add> assertTrue(p1Statements.contains(new StatementImpl(new URIImpl("urn:anno4j_test:p1"),
<add> new URIImpl(FOAF.MBOX),
<add> new LiteralImpl("[email protected]"))));
<add>
<add> // Modify multi-valued property of a1:
<add> Annotation a1 = anno4j.findByID(Annotation.class, "urn:anno4j_test:a1");
<add> a1.setBodyTexts(Sets.newHashSet("Text 1"));
<add> // Get the triples with a1 as subject. There should be only two now (rdf:type and the oadm:body_text just set):
<add> Collection<Statement> a1Statements = getStatements(repoConnection, new URIImpl("urn:anno4j_test:a1"), null, null);
<add> assertEquals(2, a1Statements.size());
<add> assertTrue(a1Statements.contains(new StatementImpl(new URIImpl("urn:anno4j_test:a1"),
<add> new URIImpl(RDF.TYPE),
<add> new URIImpl(OADM.ANNOTATION))));
<add> assertTrue(a1Statements.contains(new StatementImpl(new URIImpl("urn:anno4j_test:a1"),
<add> new URIImpl(OADM.BODY_TEXT),
<add> new LiteralImpl("Text 1"))));
<add> }
<add>
<add> /**
<add> * Tests propagation of updates across different objects for the same resource.
<add> */
<add> @Test
<add> public void testUpgradePropagation() throws Exception {
<add> // Create an Anno4j instance and get its object connection:
<add> Anno4j anno4j = new Anno4j(new SailRepository(new MemoryStore()), null, false);
<add> ObjectConnection connection = anno4j.getObjectRepository().getConnection();
<add>
<add> // Get two objects for the same resource:
<add> Annotation a = anno4j.createObject(Annotation.class, (Resource) new URIImpl("urn:anno4j_test:a1"));
<add> Annotation b = anno4j.findByID(Annotation.class, "urn:anno4j_test:a1");
<add>
<add> // Test that both objects have the same values after setting at one:
<add> a.setBodyTexts(Sets.newHashSet("a"));
<add> assertEquals(Sets.newHashSet("a"), a.getBodyTexts());
<add> assertEquals(Sets.newHashSet("a"), b.getBodyTexts());
<add>
<add> // Refresh objects:
<add> connection.refresh(a);
<add> connection.refresh(b);
<add>
<add> // Test other way round (after values have been cached):
<add> b.setBodyTexts(Sets.newHashSet("a", "b"));
<add> assertEquals(Sets.newHashSet("a", "b"), new HashSet<>(a.getBodyTexts()));
<add> assertEquals(Sets.newHashSet("a", "b"), new HashSet<>(b.getBodyTexts()));
<add> }
<add>
<add> /**
<add> * Tests deletion of resource objects and its effect on the repository.
<add> */
<add> @Test
<add> public void testDelete() throws Exception {
<add> // Create an Anno4j instance and get its repository connection for direct triple access:
<add> Anno4j anno4j = new Anno4j(new SailRepository(new MemoryStore()), null, false);
<add> RepositoryConnection repoConnection = anno4j.getRepository().getConnection();
<add>
<add> // Add some triples to the repository:
<add> /*
<add> Persisted triples:
<add> :p1 a foaf:Person ;
<add> foaf:mbox "[email protected]" .
<add> :a1 a oadm:Annotation ;
<add> oadm:bodyText "Text 1", "Text 2" ;
<add> schema:audience :b1, :b2 .
<add> :b1 a schema:Audience .
<add>
<add> */
<add> repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:p1"),
<add> new URIImpl(RDF.TYPE),
<add> new URIImpl(FOAF.PERSON)));
<add> repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:p1"),
<add> new URIImpl(FOAF.MBOX),
<add> new LiteralImpl("[email protected]")));
<add> repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:a1"),
<add> new URIImpl(RDF.TYPE),
<add> new URIImpl(OADM.ANNOTATION)));
<add> repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:a1"),
<add> new URIImpl(OADM.BODY_TEXT),
<add> new LiteralImpl("Text 1")));
<add> repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:a1"),
<add> new URIImpl(OADM.BODY_TEXT),
<add> new LiteralImpl("Text 2")));
<add> repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:a1"),
<add> new URIImpl(SCHEMA.AUDIENCE_RELATIONSHIP),
<add> new URIImpl("urn:anno4j_test:b1")));
<add> repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:a1"),
<add> new URIImpl(SCHEMA.AUDIENCE_RELATIONSHIP),
<add> new URIImpl("urn:anno4j_test:b2")));
<add> repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:b1"),
<add> new URIImpl(RDF.TYPE),
<add> new URIImpl(SCHEMA.AUDIENCE_CLASS)));
<add>
<add>
<add> // Test that all triples are removed:
<add> Person p1 = anno4j.findByID(Person.class, "urn:anno4j_test:p1");
<add> p1.delete();
<add> Collection<Statement> p1Statements = getStatements(repoConnection, new URIImpl("urn:anno4j_test:p1"), null, null);
<add> assertEquals(0, p1Statements.size());
<add>
<add> // Test that all triples are removed that have a1 as subject. b1 should be still retrievable:
<add> Annotation a1 = anno4j.findByID(Annotation.class, "urn:anno4j_test:a1");
<add> a1.delete();
<add> Collection<Statement> a1Statements = getStatements(repoConnection, new URIImpl("urn:anno4j_test:a1"), null, null);
<add> assertEquals(0, a1Statements.size());
<add> Audience b1 = anno4j.findByID(Audience.class, "urn:anno4j_test:b1");
<add> assertNotNull(b1);
<add> // After removing :b1 the repository should be empty. :b2 is removed because it didn't occur as a subject:
<add> b1.delete();
<add> Collection<Statement> allStatements = getStatements(repoConnection);
<add> assertEquals(0, allStatements.size());
<add> }
<add>}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.