diff
stringlengths 164
2.11M
| is_single_chunk
bool 2
classes | is_single_function
bool 2
classes | buggy_function
stringlengths 0
335k
⌀ | fixed_function
stringlengths 23
335k
⌀ |
---|---|---|---|---|
diff --git a/src/main/org/codehaus/groovy/tools/shell/util/AnsiPrintWriter.java b/src/main/org/codehaus/groovy/tools/shell/util/AnsiPrintWriter.java
index 69c690462..fcf80cfba 100644
--- a/src/main/org/codehaus/groovy/tools/shell/util/AnsiPrintWriter.java
+++ b/src/main/org/codehaus/groovy/tools/shell/util/AnsiPrintWriter.java
@@ -1,82 +1,81 @@
/*
* Copyright 2003-2007 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.codehaus.groovy.tools.shell.util;
-import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import java.io.PrintWriter;
import java.lang.reflect.Method;
// import org.codehaus.groovy.tools.shell.util.AnsiString;
/**
* Automatically renders printed strings for {@link AnsiString} formated expressions.
*
* @version $Id$
* @author <a href="mailto:[email protected]">Jason Dillon</a>
*/
public class AnsiPrintWriter
extends PrintWriter
{
public AnsiPrintWriter(final OutputStream out) {
super(out);
}
public AnsiPrintWriter(final OutputStream out, final boolean autoFlush) {
super(out, autoFlush);
}
public AnsiPrintWriter(final Writer out) {
super(out);
}
public AnsiPrintWriter(final Writer out, final boolean autoFlush) {
super(out, autoFlush);
}
public void write(String text) {
if (text != null && text.indexOf("@|") >=0) {
text = render(text);
}
super.write(text);
}
//
// HACK: Invoke the AnsiString.render() method using reflection to avoid problems building...
// come on ubercompile already folks :-P
//
private Method renderMethod;
private String render(final String text) {
try {
if (renderMethod == null) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
Class type = cl.loadClass("org.codehaus.groovy.tools.shell.util.AnsiString");
renderMethod = type.getMethod("render", new Class[]{ String.class });
}
return (String)renderMethod.invoke(null, new Object[]{ text });
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| true | false | null | null |
diff --git a/yarb-service/src/test/java/ch/yarb/service/impl/YarbServiceImplTest.java b/yarb-service/src/test/java/ch/yarb/service/impl/YarbServiceImplTest.java
index ca574e8..1622fc0 100644
--- a/yarb-service/src/test/java/ch/yarb/service/impl/YarbServiceImplTest.java
+++ b/yarb-service/src/test/java/ch/yarb/service/impl/YarbServiceImplTest.java
@@ -1,86 +1,87 @@
package ch.yarb.service.impl;
+import java.io.File;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import ch.yarb.service.api.YarbService;
import ch.yarb.service.to.ChangeType;
import ch.yarb.service.to.ChangedPath;
import ch.yarb.service.to.LogEntry;
import ch.yarb.service.to.RepoConfiguration;
import ch.yarb.service.to.RevisionRange;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* Tests for {@link YarbServiceImpl}.
*
* @author pellaton
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/test-context.xml", inheritLocations = false)
public class YarbServiceImplTest {
@Autowired
private YarbService service;
/**
* Tests {@link YarbServiceImpl#ping()}.
*/
@Test
public void ping() {
assertEquals("yarb", this.service.ping());
}
/**
* Tests the {@code null} check of the {@code logRepoConfigurationNull}
* {@link YarbServiceImpl#getRepositoryLog(RepoConfiguration, RevisionRange)}.
*/
@Test(expected = IllegalArgumentException.class)
public void getRepositoryLogRepoConfigurationNull() {
this.service.getRepositoryLog(null, RevisionRange.ALL);
}
/**
* Tests the {@code null} check of the {@code revisionRange}
* {@link YarbServiceImpl#getRepositoryLog(RepoConfiguration, RevisionRange)}.
*/
@Test(expected = IllegalArgumentException.class)
public void getRepositoryLogRevisionRangeNull() {
this.service.getRepositoryLog(new RepoConfiguration(null, null, null), null);
}
/**
* Tests {@link YarbServiceImpl#getRepositoryLog(RepoConfiguration, RevisionRange)}.
*/
@Test
public void getRepositoryLogRevision() {
List<LogEntry> repositoryLog = this.service.getRepositoryLog(new RepoConfiguration(
- "file:///Users/michael/.gitrepositories/yarb/yarb-service/src/test/resources/svntestrepo/",
+ "file://" + new File("./src/test/resources/svntestrepo").getAbsolutePath(),
"anonymous", "anonymous"),
RevisionRange.ALL);
assertNotNull(repositoryLog);
assertFalse(repositoryLog.isEmpty());
assertTrue(repositoryLog.size() >= 8);
LogEntry logEntry = repositoryLog.get(1);
assertNotNull(logEntry);
assertEquals("commit revision", "1", logEntry.getRevision());
assertEquals("commit author", "michael", logEntry.getAuthor());
assertEquals("commit comment", "bump basic directory structure", logEntry.getComment());
assertNotNull("commit timestamp", logEntry.getTimestamp());
List<ChangedPath> changedPathList = logEntry.getChangedPathList();
assertNotNull(changedPathList);
assertFalse(changedPathList.isEmpty());
assertEquals(3, changedPathList.size());
assertEquals("/branches", changedPathList.get(0).getPath());
assertEquals(ChangeType.ADDED, changedPathList.get(0).getChangeType());
}
}
| false | false | null | null |
diff --git a/jbi/src/main/java/org/apache/ode/jbi/OdeConsumer.java b/jbi/src/main/java/org/apache/ode/jbi/OdeConsumer.java
index 6b88587d7..f3e2a18b9 100644
--- a/jbi/src/main/java/org/apache/ode/jbi/OdeConsumer.java
+++ b/jbi/src/main/java/org/apache/ode/jbi/OdeConsumer.java
@@ -1,266 +1,266 @@
/*
* 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.ode.jbi;
import org.apache.ode.bpel.iapi.ContextException;
import org.apache.ode.bpel.iapi.Message;
import org.apache.ode.bpel.iapi.PartnerRoleMessageExchange;
import org.apache.ode.bpel.iapi.Scheduler;
import org.apache.ode.bpel.iapi.MessageExchange.FailureType;
import org.apache.ode.jbi.msgmap.Mapper;
import org.apache.ode.jbi.msgmap.MessageTranslationException;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import javax.jbi.messaging.*;
import javax.jbi.servicedesc.ServiceEndpoint;
import javax.xml.namespace.QName;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Bridge between ODE (consumers) and JBI (providers). An single object of this type handles all communications initiated by ODE
* that is destined for other JBI providers.
*/
abstract class OdeConsumer extends ServiceBridge implements JbiMessageExchangeProcessor {
private static final Log __log = LogFactory.getLog(OdeConsumer.class);
private static final long DEFAULT_RESPONSE_TIMEOUT = Long.getLong("org.apache.ode.jbi.timeout", 2 * 60 * 1000L);
protected OdeContext _ode;
protected long _responseTimeout = DEFAULT_RESPONSE_TIMEOUT;
protected Map<String, PartnerRoleMessageExchange> _outstandingExchanges = new ConcurrentHashMap<String, PartnerRoleMessageExchange>();
OdeConsumer(OdeContext ode) {
_ode = ode;
}
/**
* This is where we handle invocation where the ODE BPEL engine is the <em>client</em> and some other JBI service is the
* <em>provider</em>.
*/
public void invokePartner(final PartnerRoleMessageExchange odeMex) throws ContextException {
// Cast the EndpointReference to a JbiEndpointReference. This is the
// only type it can be (since we control the creation of these things).
JbiEndpointReference targetEndpoint = (JbiEndpointReference) odeMex.getEndpointReference();
if (targetEndpoint == null) {
String errmsg = "No endpoint for mex: " + odeMex;
__log.error(errmsg);
odeMex.replyWithFailure(FailureType.INVALID_ENDPOINT, errmsg, null);
return;
}
ServiceEndpoint se = targetEndpoint.getServiceEndpoint();
boolean isTwoWay = odeMex.getMessageExchangePattern() == org.apache.ode.bpel.iapi.MessageExchange.MessageExchangePattern.REQUEST_RESPONSE;
QName opname = new QName(se.getServiceName().getNamespaceURI(), odeMex.getOperation().getName());
MessageExchangeFactory mexf = _ode.getChannel().createExchangeFactory(se);
final MessageExchange jbiMex;
try {
jbiMex = mexf.createExchange(isTwoWay ? MessageExchangePattern.IN_OUT : MessageExchangePattern.IN_ONLY);
jbiMex.setEndpoint(se);
jbiMex.setService(se.getServiceName());
jbiMex.setOperation(opname);
} catch (MessagingException e) {
String errmsg = "Unable to create JBI message exchange for ODE message exchange " + odeMex;
__log.error(errmsg, e);
odeMex.replyWithFailure(FailureType.COMMUNICATION_ERROR, errmsg, null);
return;
}
Mapper mapper = _ode.getDefaultMapper();
odeMex.setProperty(Mapper.class.getName(), mapper.getClass().getName());
try {
if (!isTwoWay) {
final InOnly inonly = ((InOnly) jbiMex);
NormalizedMessage nmsg = inonly.createMessage();
mapper.toNMS(nmsg, odeMex.getRequest(), odeMex.getOperation().getInput().getMessage(), null);
inonly.setInMessage(nmsg);
copyMexProperties(jbiMex, odeMex);
_ode._scheduler.registerSynchronizer(new Scheduler.Synchronizer() {
public void afterCompletion(boolean success) {
if (success) {
doSendOneWay(odeMex, inonly);
}
}
public void beforeCompletion() {
}
});
odeMex.replyOneWayOk();
} else {
final InOut inout = (InOut) jbiMex;
NormalizedMessage nmsg = inout.createMessage();
mapper.toNMS(nmsg, odeMex.getRequest(), odeMex.getOperation().getInput().getMessage(), null);
inout.setInMessage(nmsg);
copyMexProperties(jbiMex, odeMex);
_ode._scheduler.registerSynchronizer(new Scheduler.Synchronizer() {
public void afterCompletion(boolean success) {
if (success) {
doSendTwoWay(odeMex, inout);
}
}
public void beforeCompletion() {
}
});
odeMex.replyAsync();
}
} catch (MessagingException me) {
String errmsg = "JBI messaging error for ODE MEX " + odeMex;
__log.error(errmsg, me);
odeMex.replyWithFailure(FailureType.COMMUNICATION_ERROR, errmsg, null);
} catch (MessageTranslationException e) {
String errmsg = "Error converting ODE message to JBI format for mex " + odeMex;
__log.error(errmsg, e);
odeMex.replyWithFailure(FailureType.FORMAT_ERROR, errmsg, null);
}
}
protected abstract void doSendOneWay(PartnerRoleMessageExchange odeMex, InOnly inonly);
protected abstract void doSendTwoWay(PartnerRoleMessageExchange odeMex, InOut inout);
protected abstract void inOutDone(InOut inout);
public void onJbiMessageExchange(MessageExchange jbiMex) throws MessagingException {
if (!jbiMex.getPattern().equals(MessageExchangePattern.IN_ONLY) &&
!jbiMex.getPattern().equals(MessageExchangePattern.IN_OUT)) {
__log.error("JBI MessageExchange " + jbiMex.getExchangeId() + " is of an unsupported pattern " + jbiMex.getPattern());
return;
}
if (jbiMex.getStatus() == ExchangeStatus.ACTIVE) {
if (jbiMex.getPattern().equals(MessageExchangePattern.IN_OUT)) {
inOutDone((InOut) jbiMex);
outResponse((InOut) jbiMex);
}
jbiMex.setStatus(ExchangeStatus.DONE);
_ode.getChannel().send(jbiMex);
} else if (jbiMex.getStatus() == ExchangeStatus.ERROR) {
inOutDone((InOut) jbiMex);
outFailure((InOut) jbiMex);
} else if (jbiMex.getStatus() == ExchangeStatus.DONE) {
_outstandingExchanges.remove(jbiMex.getExchangeId());
} else {
__log.error("Unexpected status " + jbiMex.getStatus() + " for JBI message exchange: " + jbiMex.getExchangeId());
}
}
private void outFailure(final InOut jbiMex) {
final PartnerRoleMessageExchange pmex = _outstandingExchanges.remove(jbiMex.getExchangeId());
if (pmex == null) {
__log.warn("Received a response for unknown JBI message exchange " + jbiMex.getExchangeId());
return;
}
try {
_ode._scheduler.execTransaction(new Callable<Boolean>() {
public Boolean call() throws Exception {
pmex.replyWithFailure(FailureType.OTHER, "Error: " + jbiMex.getError(), null);
return null;
}
});
} catch (Exception ex) {
__log.error("error delivering failure: ", ex);
}
}
private void outResponse(final InOut jbiMex) {
final PartnerRoleMessageExchange outstanding = _outstandingExchanges.remove(jbiMex.getExchangeId());
if (outstanding == null) {
__log.warn("Received a response for unknown JBI message exchange " + jbiMex.getExchangeId());
return;
}
try {
_ode._scheduler.execTransaction(new Callable<Boolean>() {
@SuppressWarnings("unchecked")
public Boolean call() throws Exception {
// need to reload mex since we're in a different transaction
PartnerRoleMessageExchange pmex = (PartnerRoleMessageExchange) _ode._server.getEngine().getMessageExchange(outstanding.getMessageExchangeId());
if (pmex == null) {
- __log.warn("Received a response for unknown partner role message exchange " + pmex.getMessageExchangeId());
+ __log.warn("Received a response for unknown partner role message exchange " + outstanding.getMessageExchangeId());
return Boolean.FALSE;
}
String mapperName = pmex.getProperty(Mapper.class.getName());
Mapper mapper = mapperName == null ? _ode.getDefaultMapper() : _ode.getMapper(mapperName);
if (mapper == null) {
String errmsg = "Mapper not found.";
__log.error(errmsg);
pmex.replyWithFailure(FailureType.FORMAT_ERROR, errmsg, null);
} else {
try {
Fault jbiFlt = jbiMex.getFault();
if (jbiFlt != null) {
javax.wsdl.Fault wsdlFlt = mapper.toFaultType(jbiFlt, (Collection<javax.wsdl.Fault>) pmex.getOperation().getFaults().values());
if (wsdlFlt == null) {
pmex.replyWithFailure(FailureType.FORMAT_ERROR, "Unrecognized fault message.", null);
} else {
if (wsdlFlt.getMessage() != null) {
Message faultResponse = pmex.createMessage(wsdlFlt.getMessage().getQName());
mapper.toODE(faultResponse, jbiFlt, wsdlFlt.getMessage());
pmex.replyWithFault(new QName(pmex.getPortType().getQName().getNamespaceURI(), wsdlFlt
.getName()), faultResponse);
} else {
// Can this even happen?
__log.fatal("Internal Error: fault found without a message type: " + wsdlFlt);
pmex.replyWithFailure(FailureType.FORMAT_ERROR, "Fault has no message: "
+ wsdlFlt.getName(), null);
}
}
} else {
Message response = pmex.createMessage(pmex.getOperation().getOutput().getMessage().getQName());
mapper.toODE(response, jbiMex.getOutMessage(), pmex.getOperation().getOutput().getMessage());
pmex.reply(response);
}
} catch (MessageTranslationException mte) {
__log.error("Error translating message.", mte);
pmex.replyWithFailure(FailureType.FORMAT_ERROR, mte.getMessage(), null);
}
}
return null;
}
});
} catch (Exception ex) {
__log.error("error delivering RESPONSE: ", ex);
}
}
public void setResponseTimeout(long timeout) {
_responseTimeout = timeout;
}
public long getResponseTimeout() {
return _responseTimeout;
}
}
| true | false | null | null |
diff --git a/src/main/java/archimulator/model/Benchmark.java b/src/main/java/archimulator/model/Benchmark.java
index 7bf57704..a954e4c7 100644
--- a/src/main/java/archimulator/model/Benchmark.java
+++ b/src/main/java/archimulator/model/Benchmark.java
@@ -1,125 +1,129 @@
/*******************************************************************************
* Copyright (c) 2010-2012 by Min Cai ([email protected]).
*
* This file is part of the Archimulator multicore architectural simulator.
*
* Archimulator is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Archimulator is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Archimulator. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package archimulator.model;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
import net.pickapack.dateTime.DateHelper;
import net.pickapack.model.ModelElement;
import java.util.Date;
@DatabaseTable(tableName = "Benchmark")
public class Benchmark implements ModelElement {
@DatabaseField(generatedId = true)
private long id;
@DatabaseField
private String title;
@DatabaseField
private long createTime;
@DatabaseField
private String workingDirectory;
@DatabaseField
private String executable;
@DatabaseField
private String defaultArguments;
@DatabaseField
private String standardIn;
@DatabaseField
private boolean helperThreadEnabled;
@DatabaseField
private boolean locked;
public Benchmark() {
}
public Benchmark(String title, String workingDirectory, String executable, String defaultArguments) {
this(title, workingDirectory, executable, defaultArguments, "", false);
}
public Benchmark(String title, String workingDirectory, String executable, String defaultArguments, String standardIn, boolean helperThreadEnabled) {
this.title = title;
this.workingDirectory = workingDirectory;
this.executable = executable;
this.defaultArguments = defaultArguments;
this.standardIn = standardIn;
this.helperThreadEnabled = helperThreadEnabled;
this.createTime = DateHelper.toTick(new Date());
}
public long getId() {
return id;
}
@Override
public long getParentId() {
return -1;
}
public String getTitle() {
return title;
}
public long getCreateTime() {
return createTime;
}
public String getWorkingDirectory() {
return workingDirectory;
}
public String getExecutable() {
return executable;
}
public String getDefaultArguments() {
return defaultArguments;
}
public String getStandardIn() {
+ if(standardIn == null) {
+ standardIn = "";
+ }
+
return standardIn;
}
public boolean getHelperThreadEnabled() {
return helperThreadEnabled;
}
public boolean getLocked() {
return locked;
}
public void setLocked(boolean locked) {
this.locked = locked;
}
@Override
public String toString() {
return String.format("Benchmark{id=%d, title='%s', workingDirectory='%s', executable='%s', standardIn='%s', helperThreadEnabled=%s, locked=%s}", id, title, workingDirectory, executable, standardIn, helperThreadEnabled, locked);
}
}
diff --git a/src/main/java/archimulator/model/ContextMapping.java b/src/main/java/archimulator/model/ContextMapping.java
index ffc034a6..4f121dcd 100644
--- a/src/main/java/archimulator/model/ContextMapping.java
+++ b/src/main/java/archimulator/model/ContextMapping.java
@@ -1,134 +1,134 @@
/*******************************************************************************
* Copyright (c) 2010-2012 by Min Cai ([email protected]).
*
* This file is part of the Archimulator multicore architectural simulator.
*
* Archimulator is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Archimulator is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Archimulator. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package archimulator.model;
import archimulator.service.ServiceManager;
import java.io.Serializable;
public class ContextMapping implements Serializable {
- private Integer threadId;
+ private int threadId;
private long benchmarkId;
private String arguments;
private String standardOut;
private int helperThreadLookahead;
private int helperThreadStride;
private boolean dynamicHelperThreadParams;
private transient Benchmark benchmark;
public ContextMapping(int threadId, Benchmark benchmark, String arguments) {
this(threadId, benchmark, arguments, getDefaultStandardOut(threadId));
}
public ContextMapping(int threadId, Benchmark benchmark, String arguments, String standardOut) {
this.threadId = threadId;
this.benchmarkId = benchmark.getId();
this.arguments = arguments;
this.standardOut = standardOut;
}
- public Integer getThreadId() {
+ public int getThreadId() {
return threadId;
}
- public void setThreadId(Integer threadId) {
+ public void setThreadId(int threadId) {
this.threadId = threadId;
}
public long getBenchmarkId() {
return benchmarkId;
}
public void setBenchmarkId(long benchmarkId) {
this.benchmarkId = benchmarkId;
this.benchmark = ServiceManager.getBenchmarkService().getBenchmarkById(benchmarkId);
}
public String getArguments() {
if(arguments == null) {
arguments = "";
}
return arguments;
}
public void setArguments(String arguments) {
this.arguments = arguments;
}
public String getStandardOut() {
if(standardOut == null) {
standardOut = "";
}
return standardOut;
}
public void setStandardOut(String standardOut) {
this.standardOut = standardOut;
}
public int getHelperThreadLookahead() {
return helperThreadLookahead;
}
public void setHelperThreadLookahead(int helperThreadLookahead) {
this.helperThreadLookahead = helperThreadLookahead;
}
public int getHelperThreadStride() {
return helperThreadStride;
}
public void setHelperThreadStride(int helperThreadStride) {
this.helperThreadStride = helperThreadStride;
}
public boolean getDynamicHelperThreadParams() {
return dynamicHelperThreadParams;
}
public void setDynamicHelperThreadParams(boolean dynamicHelperThreadParams) {
this.dynamicHelperThreadParams = dynamicHelperThreadParams;
}
public Benchmark getBenchmark() {
if (benchmark == null) {
benchmark = ServiceManager.getBenchmarkService().getBenchmarkById(benchmarkId);
}
return benchmark;
}
@Override
public String toString() {
return String.format("thread #%d->'%s'", threadId, getBenchmark().getTitle() + "_" + arguments + "-lookahead_" + helperThreadLookahead + "-stride_" + helperThreadStride);
}
- public static String getDefaultStandardOut(Integer threadId) {
+ public static String getDefaultStandardOut(int threadId) {
return "ctx" + threadId + "_out.txt";
}
}
diff --git a/src/main/java/archimulator/service/RunExperimentJob.java b/src/main/java/archimulator/service/RunExperimentJob.java
index aba539cf..4ee3abb8 100644
--- a/src/main/java/archimulator/service/RunExperimentJob.java
+++ b/src/main/java/archimulator/service/RunExperimentJob.java
@@ -1,76 +1,80 @@
/*******************************************************************************
* Copyright (c) 2010-2012 by Min Cai ([email protected]).
*
* This file is part of the Archimulator multicore architectural simulator.
*
* Archimulator is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Archimulator is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Archimulator. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package archimulator.service;
import archimulator.model.Experiment;
import archimulator.model.ExperimentState;
import archimulator.model.ExperimentType;
import archimulator.sim.common.*;
import archimulator.sim.os.Kernel;
import net.pickapack.Reference;
import net.pickapack.event.BlockingEventDispatcher;
import net.pickapack.event.CycleAccurateEventQueue;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class RunExperimentJob implements Job {
public void execute(JobExecutionContext context) throws JobExecutionException {
if (!ServiceManager.getSystemSettingService().getSystemSettingSingleton().isRunningExperimentsEnabled()) {
return;
}
Experiment experiment = ServiceManager.getExperimentService().getFirstExperimentToRun();
if (experiment != null) {
experiment.setState(ExperimentState.RUNNING);
ServiceManager.getExperimentService().updateExperiment(experiment);
- runExperiment(experiment);
+ try {
+ runExperiment(experiment);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
}
}
private void runExperiment(Experiment experiment) {
CycleAccurateEventQueue cycleAccurateEventQueue = new CycleAccurateEventQueue();
if (experiment.getType() == ExperimentType.FUNCTIONAL) {
BlockingEventDispatcher<SimulationEvent> blockingEventDispatcher = new BlockingEventDispatcher<SimulationEvent>();
new FunctionalSimulation(experiment.getTitle() + "/functional", experiment, blockingEventDispatcher, cycleAccurateEventQueue, experiment.getNumMaxInstructions()).simulate();
} else if (experiment.getType() == ExperimentType.DETAILED) {
BlockingEventDispatcher<SimulationEvent> blockingEventDispatcher = new BlockingEventDispatcher<SimulationEvent>();
new DetailedSimulation(experiment.getTitle() + "/detailed", experiment, blockingEventDispatcher, cycleAccurateEventQueue, experiment.getNumMaxInstructions()).simulate();
} else if (experiment.getType() == ExperimentType.TWO_PHASE) {
Reference<Kernel> kernelRef = new Reference<Kernel>();
BlockingEventDispatcher<SimulationEvent> blockingEventDispatcher = new BlockingEventDispatcher<SimulationEvent>();
new ToRoiFastForwardSimulation(experiment.getTitle() + "/twoPhase/phase0", experiment, blockingEventDispatcher, cycleAccurateEventQueue, experiment.getArchitecture().getHelperThreadPthreadSpawnIndex(), kernelRef).simulate();
blockingEventDispatcher.clearListeners();
cycleAccurateEventQueue.resetCurrentCycle();
new FromRoiDetailedSimulation(experiment.getTitle() + "/twoPhase/phase1", experiment, blockingEventDispatcher, cycleAccurateEventQueue, experiment.getNumMaxInstructions(), kernelRef).simulate();
}
experiment.setState(ExperimentState.COMPLETED);
experiment.setFailedReason("");
ServiceManager.getExperimentService().updateExperiment(experiment);
}
}
| false | false | null | null |
diff --git a/src/simpleserver/command/MyAreaCommand.java b/src/simpleserver/command/MyAreaCommand.java
index 0607c10..015754e 100644
--- a/src/simpleserver/command/MyAreaCommand.java
+++ b/src/simpleserver/command/MyAreaCommand.java
@@ -1,143 +1,145 @@
/*
* Copyright (c) 2010 SimpleServer authors (see CONTRIBUTORS)
*
* 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 simpleserver.command;
import static simpleserver.lang.Translations.t;
import java.util.Set;
import simpleserver.Color;
import simpleserver.Player;
import simpleserver.config.xml.AllBlocks;
import simpleserver.config.xml.Area;
import simpleserver.config.xml.Chests;
import simpleserver.config.xml.Config;
import simpleserver.config.xml.DimensionConfig;
import simpleserver.config.xml.Permission;
import simpleserver.config.xml.Config.AreaStoragePair;
public class MyAreaCommand extends AbstractCommand implements PlayerCommand {
public MyAreaCommand() {
super("myarea [start|end|save|unsave|rename]",
"Manage your personal area");
}
private boolean areaSizeOk(Player player) {
return (Math.abs(player.areastart.x() - player.areaend.x()) < 50)
&& (Math.abs(player.areastart.z() - player.areaend.z()) < 50)
&& player.areaend.dimension() == player.areastart.dimension();
}
public void execute(Player player, String message) {
Config config = player.getServer().config;
String arguments[] = extractArguments(message);
if (arguments.length == 0) {
player.addTCaptionedMessage("Usage", commandPrefix() + "myarea [start|end|save|unsave|rename]");
return;
}
if (arguments[0].equals("start")) {
player.areastart = player.position();
player.areastart = player.areastart.setY((byte) 0); // no height limit
player.addTMessage(Color.GRAY, "Start coordinate set.");
} else if (arguments[0].equals("end")) {
player.areaend = player.position();
player.areaend = player.areaend.setY((byte) 127); // no height limit
player.addTMessage(Color.GRAY, "End coordinate set.");
} else if (arguments[0].equals("save")) {
if (player.areastart == null || player.areaend == null) {
player.addTMessage(Color.RED, "Define start and end coordinates for your area first!");
return;
}
if (!areaSizeOk(player)) {
player.addTMessage(Color.RED, "Your area is allowed to have a maximum size of 50x50!");
return;
}
if (player.getServer().config.playerArea(player) != null) {
player.addTMessage(Color.RED, "New area can not be saved before you remove your old one!");
return;
}
Area area = createPlayerArea(player);
Set<Area> overlaps = config.dimensions.overlaps(area);
if (!overlaps.isEmpty()) {
player.addTMessage(Color.RED, "Your area overlaps with other areas and could therefore not be saved!");
StringBuilder str = new StringBuilder();
for (Area overlap : overlaps) {
str.append(overlap.name);
str.append(", ");
}
str.delete(str.length() - 2, str.length() - 1);
player.addTCaptionedMessage("Overlapping areas", "%s", str);
return;
}
saveArea(area, player);
player.addTMessage(Color.GRAY, "Your area has been saved!");
- } else if (arguments[0].equals("unsave")) {
+ } else if (arguments[0].equals("unsave") || arguments[0].equals("remove")) {
AreaStoragePair area = config.playerArea(player);
if (area == null) {
player.addTMessage(Color.RED, "You currently have no personal area which can be removed!");
return;
}
area.storage.remove(area.area);
player.addTMessage(Color.GRAY, "Your area has been removed!");
+ player.getServer().saveConfig();
} else if (arguments[0].equals("rename")) {
AreaStoragePair area = config.playerArea(player);
if (area == null) {
player.addTMessage(Color.RED, "You currently have no personal area which can be renamed!");
return;
}
String label = extractArgument(message, 1);
if (label != null) {
area.area.name = label;
player.addTMessage(Color.GRAY, "Your area has been renamed!");
+ player.getServer().saveConfig();
} else {
player.addTMessage(Color.RED, "Please supply an area name.");
}
} else {
player.addTMessage(Color.RED, "You entered an invalid argument.");
}
}
private Area createPlayerArea(Player player) {
Area area = new Area(t("%s's area", player.getName()), player.areastart, player.areaend);
area.owner = player.getName().toLowerCase();
Permission perm = new Permission(player);
AllBlocks blocks = new AllBlocks();
blocks.destroy = perm;
blocks.place = perm;
blocks.use = perm;
area.allblocks.blocks = blocks;
area.chests.chests = new Chests(perm);
return area;
}
private void saveArea(Area area, Player player) {
DimensionConfig dimension = player.getServer().config.dimensions.get(area.start.dimension());
if (dimension == null) {
dimension = player.getServer().config.dimensions.add(area.start.dimension());
}
dimension.add(area);
player.getServer().saveConfig();
}
}
diff --git a/src/simpleserver/config/xml/AreaStorage.java b/src/simpleserver/config/xml/AreaStorage.java
index 85ca9a3..6340596 100644
--- a/src/simpleserver/config/xml/AreaStorage.java
+++ b/src/simpleserver/config/xml/AreaStorage.java
@@ -1,55 +1,59 @@
/*
* Copyright (c) 2010 SimpleServer authors (see CONTRIBUTORS)
*
* 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 simpleserver.config.xml;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class AreaStorage extends Storage implements Iterable<Area> {
private DimensionAreaStorage globalStorage = DimensionAreaStorage.getInstance();
private List<Area> localStorage = new ArrayList<Area>();
void setOwner(Area owner) {
globalStorage.addTag(owner);
}
@Override
void add(XMLTag child) {
localStorage.add((Area) child);
}
public void add(Area area) {
localStorage.add(area);
globalStorage.add(area);
}
@Override
public Iterator<Area> iterator() {
return localStorage.iterator();
}
public void remove(Area area) {
localStorage.remove(area);
globalStorage.remove(area);
}
+ public boolean isEmpty() {
+ return localStorage.isEmpty();
+ }
+
}
diff --git a/src/simpleserver/config/xml/DimensionConfig.java b/src/simpleserver/config/xml/DimensionConfig.java
index 1ddad30..d118a90 100644
--- a/src/simpleserver/config/xml/DimensionConfig.java
+++ b/src/simpleserver/config/xml/DimensionConfig.java
@@ -1,64 +1,71 @@
/*
* Copyright (c) 2010 SimpleServer authors (see CONTRIBUTORS)
*
* 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 simpleserver.config.xml;
+import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import simpleserver.Coordinate.Dimension;
public class DimensionConfig extends PermissionContainer {
Dimension dimension;
AreaStorage topAreas;
public DimensionAreaStorage areas;
DimensionConfig() {
super("dimension");
}
@Override
public void finish() {
areas.buildTree();
}
@Override
void addStorages() {
areas = DimensionAreaStorage.newInstance();
addStorage("area", topAreas = new AreaStorage());
super.addStorages();
}
@Override
void setAttribute(String name, String value) throws SAXException {
if (name.equals("name")) {
dimension = Dimension.get(value);
}
}
@Override
void saveAttributes(AttributeList attributes) {
attributes.addAttribute("name", dimension);
}
+ @Override
+ protected void save(ContentHandler handler, boolean childs, boolean pcdata) throws SAXException {
+ if (!topAreas.isEmpty()) {
+ super.save(handler, childs, pcdata);
+ }
+ }
+
public void add(Area area) {
topAreas.add(area);
- areas.add(area);
}
}
| false | false | null | null |
diff --git a/src/main/java/org/generationcp/breeding/manager/crosses/NurseryTemplateConditionsComponent.java b/src/main/java/org/generationcp/breeding/manager/crosses/NurseryTemplateConditionsComponent.java
index 5adf483..db95c7d 100644
--- a/src/main/java/org/generationcp/breeding/manager/crosses/NurseryTemplateConditionsComponent.java
+++ b/src/main/java/org/generationcp/breeding/manager/crosses/NurseryTemplateConditionsComponent.java
@@ -1,619 +1,622 @@
/*******************************************************************************
* Copyright (c) 2012, All Rights Reserved.
*
* Generation Challenge Programme (GCP)
*
*
* This software is licensed for use under the terms of the GNU General Public
* License (http://bit.ly/8Ztv8M) and the provisions of Part F of the Generation
* Challenge Programme Amended Consortium Agreement (http://bit.ly/KQX1nL)
*
*******************************************************************************/
package org.generationcp.breeding.manager.crosses;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import org.generationcp.breeding.manager.application.Message;
import org.generationcp.breeding.manager.crossingmanager.SelectGermplasmListWindow;
import org.generationcp.breeding.manager.crossingmanager.util.CrossingManagerExporterException;
import org.generationcp.breeding.manager.nurserytemplate.listeners.NurseryTemplateButtonClickListener;
import org.generationcp.breeding.manager.nurserytemplate.util.NurseryTemplateManagerExporter;
import org.generationcp.breeding.manager.pojos.ImportedGermplasmCrosses;
import org.generationcp.commons.util.FileDownloadResource;
import org.generationcp.commons.vaadin.spring.InternationalizableComponent;
import org.generationcp.commons.vaadin.spring.SimpleResourceBundleMessageSource;
import org.generationcp.commons.vaadin.util.MessageNotifier;
import org.generationcp.middleware.exceptions.MiddlewareQueryException;
import org.generationcp.middleware.manager.api.GermplasmDataManager;
import org.generationcp.middleware.manager.api.UserDataManager;
import org.generationcp.middleware.manager.api.WorkbenchDataManager;
import org.generationcp.middleware.pojos.Location;
import org.generationcp.middleware.pojos.Method;
import org.generationcp.middleware.pojos.Person;
import org.generationcp.middleware.pojos.User;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.vaadin.dialogs.ConfirmDialog;
import com.vaadin.data.Property;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.event.LayoutEvents.LayoutClickEvent;
import com.vaadin.event.LayoutEvents.LayoutClickListener;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.Component;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Table;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;
/**
*
* @author Mark Agarrado
*
*/
@Configurable
public class NurseryTemplateConditionsComponent extends VerticalLayout implements InitializingBean, InternationalizableComponent{
/**
*
*/
private static final long serialVersionUID = 6926035577490148208L;
public static final String BACK_BUTTON_ID = "NurseryTemplateConditionsComponent Back Button";
public static final String DONE_BUTTON_ID = "NurseryTemplateConditionsComponent Done Button";
public static final String CONDITION_COLUMN = "Condition Column";
public static final String DESCRIPTION_COLUMN = "Description Column";
public static final String PROPERTY_COLUMN = "Property Column";
public static final String SCALE_COLUMN = "Scale Column";
public static final String VALUE_COLUMN = "Value Column";
public static final String FEMALE_LIST="Female";
public static final String MALE_LIST="Male";
private Table nurseryConditionsTable;
private Component buttonArea;
private Button backButton;
private Button doneButton;
private TextField nid;
private ComboBox comboBoxBreedingMethod;
private TextField methodId;
private ComboBox comboBoxSiteName;
private TextField siteId;
private ComboBox comboBoxBreedersName;
private TextField breederId;
private TextField femaleListName;
private TextField femaleListId;
private TextField maleListName;
private TextField maleListId;
@Autowired
private SimpleResourceBundleMessageSource messageSource;
@Autowired
private GermplasmDataManager germplasmDataManager;
@Autowired
private WorkbenchDataManager workbenchDataManager;
@Autowired
private UserDataManager userDataManager;
private List<Method> method;
private List<Location> locations;
private List<User> users;
private HashMap<String, Integer> mapBreedingMethod;
private HashMap<String, Integer> mapSiteName;
private HashMap<String, Integer> mapBreedersName;
private NurseryTemplateMain source;
public NurseryTemplateConditionsComponent(NurseryTemplateMain source) {
this.source=source;
}
@Override
public void afterPropertiesSet() throws Exception {
assemble();
}
protected void assemble() {
initializeComponents();
initializeValues();
initializeLayout();
initializeActions();
}
protected void initializeComponents() {
nid=new TextField();
comboBoxBreedingMethod= new ComboBox();
comboBoxBreedingMethod.setImmediate(true);
methodId=new TextField();
methodId.setImmediate(true);
comboBoxSiteName= new ComboBox();
comboBoxSiteName.setImmediate(true);
siteId=new TextField();
siteId.setImmediate(true);
comboBoxBreedersName= new ComboBox();
comboBoxBreedersName.setImmediate(true);
breederId=new TextField();
breederId.setImmediate(true);
femaleListName=new TextField();
femaleListId=new TextField();
maleListName=new TextField();
maleListId=new TextField();
generateConditionsTable();
addComponent(nurseryConditionsTable);
buttonArea = layoutButtonArea();
addComponent(buttonArea);
}
protected void initializeValues() {
}
protected void initializeLayout() {
setMargin(true);
setSpacing(true);
setComponentAlignment(buttonArea, Alignment.MIDDLE_RIGHT);
}
protected void initializeActions() {
backButton.addListener(new NurseryTemplateButtonClickListener(this));
doneButton.addListener(new NurseryTemplateButtonClickListener(this));
}
protected Component layoutButtonArea() {
HorizontalLayout buttonLayout = new HorizontalLayout();
buttonLayout.setSpacing(true);
buttonLayout.setMargin(true, false, false, false);
backButton = new Button();
backButton.setData(BACK_BUTTON_ID);
buttonLayout.addComponent(backButton);
doneButton = new Button();
doneButton.setData(DONE_BUTTON_ID);
buttonLayout.addComponent(doneButton);
return buttonLayout;
}
private void generateConditionsTable() {
nurseryConditionsTable = new Table();
nurseryConditionsTable.setStyleName("condition-rows");
nurseryConditionsTable.setSizeFull();
nurseryConditionsTable.addContainerProperty(CONDITION_COLUMN, String.class, null);
nurseryConditionsTable.addContainerProperty(DESCRIPTION_COLUMN, String.class, null);
nurseryConditionsTable.addContainerProperty(PROPERTY_COLUMN, String.class, null);
nurseryConditionsTable.addContainerProperty(SCALE_COLUMN, String.class, null);
nurseryConditionsTable.addContainerProperty(VALUE_COLUMN, Component.class, null);
addConditionRows();
nurseryConditionsTable.setPageLength(nurseryConditionsTable.size());
}
private void addConditionRows() {
//TODO: populate this table using values read from the Nursery Template file
nurseryConditionsTable.addItem(new Object[] {
"NID", "NURSERY SEQUENCE NUMBER", "NURSERY", "NUMBER", nid
},
"nid");
nurseryConditionsTable.addItem(new Object[] {
"BREEDER NAME", "PRINCIPAL INVESTIGATOR", "PERSON", "DBCV", getComboBoxBreedersName()
},
"breederName");
nurseryConditionsTable.addItem(new Object[] {
"BREEDER ID", "PRINCIPAL INVESTIGATOR", "PERSON", "DBID", getTextFieldBreederId()
},
"breederId");
nurseryConditionsTable.addItem(new Object[] {
"SITE", "NURSERY SITE NAME", "LOCATION", "DBCV", getComboBoxSiteName()
},
"site");
nurseryConditionsTable.addItem(new Object[] {
"SITE ID", "NURSERY SITE ID", "LOCATION", "DBID", getTextFieldSiteId()
},
"siteId");
nurseryConditionsTable.addItem(new Object[] {
"BREEDING METHOD", "Breeding method to be applied to this nursery", "METHOD", "DBCV", getComboBoxBreedingMethod()
},
"breedingMethod");
nurseryConditionsTable.addItem(new Object[] {
"BREEDING METHOD ID", "ID of Breeding Method", "METHOD", "DBID", getTextFieldMethodId()
},
"breedingMethodId");
nurseryConditionsTable.addItem(new Object[] {
"FEMALE LIST NAME", "FEMALE LIST NAME", "GERMPLASM LIST", "DBCV", getLayoutGermplasmListTextField(femaleListName,FEMALE_LIST)
},
"femaleListName");
nurseryConditionsTable.addItem(new Object[] {
"FEMALE LIST ID", "FEMALE LIST ID", "GERMPLASM LIST", "DBID", getLayoutGermplasmListTextField(femaleListId,FEMALE_LIST)
},
"femaleListId");
nurseryConditionsTable.addItem(new Object[] {
"MALE LIST NAME", "MALE LIST NAME", "GERMPLASM LIST", "DBCV", getLayoutGermplasmListTextField(maleListName,MALE_LIST)
},
"maleListName");
nurseryConditionsTable.addItem(new Object[] {
"MALE LIST ID", "MALE LIST ID", "GERMPLASM LIST", "DBID", getLayoutGermplasmListTextField(maleListId,MALE_LIST)
},
"maleListId");
}
private ComboBox getComboBoxSiteName() {
mapSiteName = new HashMap<String, Integer>();
try {
locations=germplasmDataManager.getAllBreedingLocations();
} catch (MiddlewareQueryException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
comboBoxSiteName.addItem("");
for (Location loc : locations) {
if(loc.getLname().length()>0){
comboBoxSiteName.addItem(loc.getLname());
mapSiteName.put(loc.getLname(), new Integer(loc.getLocid()));
}
}
comboBoxSiteName.addListener(new Property.ValueChangeListener() {
private static final long serialVersionUID = 1L;
@Override
public void valueChange(ValueChangeEvent event) {
siteId.setValue(String.valueOf(mapSiteName.get(comboBoxSiteName.getValue())));
}
});
comboBoxSiteName.select("");
siteId.setValue("");
return comboBoxSiteName;
}
private TextField getTextFieldSiteId(){
siteId.addListener(new Property.ValueChangeListener() {
private static final long serialVersionUID = 1L;
@Override
public void valueChange(ValueChangeEvent event) {
Location loc = new Location();
boolean noError=true;
try {
loc = germplasmDataManager.getLocationByID(Integer.valueOf(siteId.getValue().toString()));
} catch (NumberFormatException e) {
noError=false;
} catch (MiddlewareQueryException e) {
noError=false;
}
if(loc!=null && noError){
comboBoxSiteName.setValue(loc.getLname());
}else{
getWindow().showNotification(messageSource.getMessage(Message.INVALID_SITE_ID));
comboBoxSiteName.select("");
siteId.setValue("");
}
}
});
return siteId;
}
private ComboBox getComboBoxBreedersName() {
mapBreedersName = new HashMap<String, Integer>();
try {
users=userDataManager.getAllUsers();
} catch (MiddlewareQueryException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
comboBoxBreedersName.addItem("");
setComboBoxBreederDefaultValue();
for (User u : users) {
Person p = new Person();
try {
p = userDataManager.getPersonById(u.getPersonid());
} catch (MiddlewareQueryException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
- String name=p.getFirstName()+" "+p.getMiddleName() + " "+p.getLastName();
+ String name= u.getName();
+ if(p != null){
+ name = p.getFirstName()+" "+p.getMiddleName() + " "+p.getLastName();
+ }
comboBoxBreedersName.addItem(name);
mapBreedersName.put(name, new Integer(u.getUserid()));
}
comboBoxBreedersName.addListener(new Property.ValueChangeListener() {
private static final long serialVersionUID = 1L;
@Override
public void valueChange(ValueChangeEvent event) {
breederId.setValue(String.valueOf(mapBreedersName.get(comboBoxBreedersName.getValue())));
}
});
return comboBoxBreedersName;
}
private void setComboBoxBreederDefaultValue() {
try {
User user =workbenchDataManager.getUserById(workbenchDataManager.getWorkbenchRuntimeData().getUserId());
Integer projectId= workbenchDataManager.getLastOpenedProject(workbenchDataManager.getWorkbenchRuntimeData().getUserId()).getProjectId().intValue();
Integer ibdbUserId=workbenchDataManager.getLocalIbdbUserId(user.getUserid(),Long.valueOf(projectId));
User u=userDataManager.getUserById(ibdbUserId);
Person p=userDataManager.getPersonById(u.getPersonid());
String name=p.getFirstName()+" "+p.getMiddleName() + " "+p.getLastName();
comboBoxBreedersName.addItem(name);
mapBreedersName.put(name, new Integer(u.getUserid()));
comboBoxBreedersName.select(name);
breederId.setValue(String.valueOf(u.getUserid()));
} catch (MiddlewareQueryException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private TextField getTextFieldBreederId(){
breederId.addListener(new Property.ValueChangeListener() {
private static final long serialVersionUID = 1L;
@Override
public void valueChange(ValueChangeEvent event) {
Person p = new Person();
User u= new User();
String name="";
boolean noError=true;
try {
u=userDataManager.getUserById(Integer.valueOf(breederId.getValue().toString()));
} catch (NumberFormatException e) {
noError=false;
} catch (MiddlewareQueryException e) {
noError=false;
}
if(u!=null && noError){
try {
p = userDataManager.getPersonById(u.getPersonid());
name=p.getFirstName()+" "+p.getMiddleName() + " "+p.getLastName();
} catch (MiddlewareQueryException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
comboBoxBreedersName.setValue(name);
}else{
getWindow().showNotification(messageSource.getMessage(Message.INVALID_BREEDER_ID));
comboBoxBreedersName.select("");
breederId.setValue("");
}
}
});
return breederId;
}
private ComboBox getComboBoxBreedingMethod() {
mapBreedingMethod = new HashMap<String, Integer>();
try {
method=germplasmDataManager.getMethodsByType("GEN");
} catch (MiddlewareQueryException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
comboBoxBreedingMethod.addItem("");
for (Method m : method) {
if(m.getMname().length()>0){
comboBoxBreedingMethod.addItem(m.getMname());
mapBreedingMethod.put(m.getMname(), new Integer(m.getMid()));
}
}
comboBoxBreedingMethod.addListener(new Property.ValueChangeListener() {
private static final long serialVersionUID = 1L;
@Override
public void valueChange(ValueChangeEvent event) {
methodId.setValue(String.valueOf(mapBreedingMethod.get(comboBoxBreedingMethod.getValue())));
}
});
comboBoxBreedingMethod.select("");
methodId.setValue("");
return comboBoxBreedingMethod;
}
private TextField getTextFieldMethodId(){
methodId.addListener(new Property.ValueChangeListener() {
private static final long serialVersionUID = 1L;
@Override
public void valueChange(ValueChangeEvent event) {
Method m = new Method();
boolean noError=true;
try {
m=germplasmDataManager.getMethodByID(Integer.valueOf(methodId.getValue().toString()));
} catch (NumberFormatException e) {
noError=false;
} catch (MiddlewareQueryException e) {
noError=false;
}
if(m!=null && noError){
comboBoxBreedingMethod.setValue(m.getMname());
}else{
getWindow().showNotification(messageSource.getMessage(Message.INVALID_METHOD_ID));
comboBoxBreedingMethod.select("");
methodId.setValue("");
}
}
});
return methodId;
}
private VerticalLayout getLayoutGermplasmListTextField(final TextField txtField,final String germplasmListFor){
VerticalLayout germplasmListTextFieldLayout = new VerticalLayout();
germplasmListTextFieldLayout.addComponent(txtField);
germplasmListTextFieldLayout.addListener(new LayoutClickListener() {
public void layoutClick(LayoutClickEvent event) {
if (event.getChildComponent() == txtField) {
SelectGermplasmListWindow selectListWindow = new SelectGermplasmListWindow(getMainClass(),germplasmListFor);
getWindow().addWindow(selectListWindow);
}
}
});
return germplasmListTextFieldLayout;
}
@Override
public void attach() {
super.attach();
updateLabels();
}
@Override
public void updateLabels() {
messageSource.setColumnHeader(nurseryConditionsTable, CONDITION_COLUMN, Message.CONDITION_HEADER);
messageSource.setColumnHeader(nurseryConditionsTable, DESCRIPTION_COLUMN, Message.DESCRIPTION_HEADER);
messageSource.setColumnHeader(nurseryConditionsTable, PROPERTY_COLUMN, Message.PROPERTY_HEADER);
messageSource.setColumnHeader(nurseryConditionsTable, SCALE_COLUMN, Message.SCALE_HEADER);
messageSource.setColumnHeader(nurseryConditionsTable, VALUE_COLUMN, Message.VALUE_HEADER);
messageSource.setCaption(backButton, Message.BACK);
messageSource.setCaption(doneButton, Message.DONE);
}
public void backButtonClickAction() {
source.disableNurseryTemplateConditionsComponent();
}
public void doneButtonClickAction() {
String confirmDialogCaption=messageSource.getMessage(Message.CONFIRM_DIALOG_CAPTION_EXPORT_NURSERY_FILE);
String confirmDialogMessage=messageSource.getMessage(Message.CONFIRM_DIALOG_MESSAGE_EXPORT_NURSERY_FILE);
ConfirmDialog.show(this.getWindow(),confirmDialogCaption ,confirmDialogMessage ,
messageSource.getMessage(Message.OK), messageSource.getMessage(Message.CANCEL_LABEL), new ConfirmDialog.Listener() {
private static final long serialVersionUID = 1L;
public void onClose(ConfirmDialog dialog) {
if (dialog.isConfirmed()) {
createAndDownloadNurseryTemplateFile();
}
}
});
}
protected void createAndDownloadNurseryTemplateFile() {
// TODO Auto-generated method stub
ImportedGermplasmCrosses nurseryTemplateData=source.getSelectNurseryTemplateScreen().getCrossingManagerUploader().getImportedGermplasmCrosses();
String tempFileName = System.getProperty( "user.home" ) + "/temp.xls";
NurseryTemplateManagerExporter exporter = new NurseryTemplateManagerExporter(nurseryTemplateData,getNurseryConditionValue());
try {
exporter.exportNurseryTemplateManagerExcel(tempFileName);
FileDownloadResource fileDownloadResource = new FileDownloadResource(new File(tempFileName), this.getApplication());
fileDownloadResource.setFilename(nurseryTemplateData.getFilename());
this.getWindow().open(fileDownloadResource);
} catch (CrossingManagerExporterException e) {
MessageNotifier.showError(getWindow(), e.getMessage(), "");
}
}
private HashMap<String, String> getNurseryConditionValue() {
HashMap<String, String> conditionValue=new HashMap<String,String>();
conditionValue.put("NID", nid.getValue().toString());
conditionValue.put("BREEDER NAME", comboBoxBreedersName.getValue().toString());
conditionValue.put("BREEDER ID", breederId.getValue().toString());
conditionValue.put("SITE", comboBoxSiteName.getValue().toString());
conditionValue.put("SITE ID", siteId.getValue().toString());
conditionValue.put("BREEDING METHOD", comboBoxBreedingMethod.getValue().toString());
conditionValue.put("BREEDING METHOD ID", methodId.getValue().toString());
conditionValue.put("FEMALE LIST NAME", femaleListName.getValue().toString());
conditionValue.put("FEMALE LIST ID", femaleListId.getValue().toString());
conditionValue.put("MALE LIST NAME", maleListName.getValue().toString());
conditionValue.put("MALE LIST ID", maleListId.getValue().toString());
return conditionValue;
}
private NurseryTemplateConditionsComponent getMainClass(){
return this;
}
public TextField getFemaleListName() {
return femaleListName;
}
public TextField getFemaleListId() {
return femaleListId;
}
public TextField getMaleListName() {
return maleListName;
}
public TextField getMaleListId() {
return maleListId;
}
}
| true | false | null | null |
diff --git a/src/com/matburt/mobileorg/Synchronizers/SSHSynchronizer.java b/src/com/matburt/mobileorg/Synchronizers/SSHSynchronizer.java
index b263103..484b9d7 100644
--- a/src/com/matburt/mobileorg/Synchronizers/SSHSynchronizer.java
+++ b/src/com/matburt/mobileorg/Synchronizers/SSHSynchronizer.java
@@ -1,199 +1,202 @@
package com.matburt.mobileorg.Synchronizers;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.matburt.mobileorg.util.OrgUtils;
public class SSHSynchronizer implements SynchronizerInterface {
private final String LT = "MobileOrg";
private String user;
private String host;
private String path;
private String pass;
private int port;
private String pubFile;
private Session session;
private SharedPreferences appSettings;
private Context context;
public SSHSynchronizer(Context context) {
this.context = context;
this.appSettings = PreferenceManager
.getDefaultSharedPreferences(context.getApplicationContext());
path = appSettings.getString("scpPath", "");
user = appSettings.getString("scpUser", "");
host = appSettings.getString("scpHost", "");
pubFile = appSettings.getString("scpPubFile", "");
String tmpPort = appSettings.getString("scpPort", "");
if (tmpPort.equals("")) {
port = 22;
}
else {
port = Integer.parseInt(tmpPort);
}
pass = appSettings.getString("scpPass", "");
try {
this.connect();
} catch (Exception e) {
Log.e("MobileOrg", "SSH Connection failed");
}
}
public String testConnection(String path, String user, String pass, String host, int port, String pubFile) {
this.path = path;
this.user = user;
this.pass = pass;
this.host = host;
this.port = port;
this.pubFile = pubFile;
if (this.path.indexOf("index.org") < 0) {
Log.i("MobileOrg", "Invalid ssh path, must point to index.org");
return "Invalid ssh path, must point to index.org";
}
if (this.path.equals("") ||
this.user.equals("") ||
this.host.equals("") ||
(this.pass.equals("") && this.pubFile.equals(""))) {
Log.i("MobileOrg", "Test Connection Failed for not being configured");
return "Missing configuration values";
}
try {
this.connect();
BufferedReader r = this.getRemoteFile(this.getFileName());
r.close();
}
catch (Exception e) {
Log.i("MobileOrg", "SSH Get index file failed");
return "Failed to find index file with error: " + e.toString();
}
this.postSynchronize();
return null;
}
private String getFileName() {
String[] pathElements = this.path.split("/");
if (pathElements.length > 0) {
return pathElements[pathElements.length-1];
}
return "";
}
private String getRootUrl() {
String[] pathElements = this.path.split("/");
String directoryActual = "/";
if (pathElements.length > 1) {
for (int i = 0; i < pathElements.length - 1; i++) {
if (pathElements[i].length() > 0) {
directoryActual += pathElements[i] + "/";
}
}
}
return directoryActual;
}
@Override
public boolean isConfigured() {
if (this.appSettings.getString("scpPath", "").equals("")
|| this.appSettings.getString("scpUser", "").equals("")
|| this.appSettings.getString("scpHost", "").equals("")
|| (this.appSettings.getString("scpPass", "").equals("") && this.appSettings
.getString("scpPubFile", "").equals("")))
return false;
return true;
}
public void connect() throws JSchException {
JSch jsch = new JSch();
try {
session = jsch.getSession(user, host, port);
- if (!pubFile.equals("")) {
+ if (!pubFile.equals("") && !pass.equals("")) {
+ jsch.addIdentity(pubFile, pass);
+ }
+ else if (!pubFile.equals("")) {
jsch.addIdentity(pubFile);
}
else {
session.setPassword(pass);
}
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
Log.d(LT, "SSH Connected");
} catch (JSchException e) {
Log.d(LT, e.getLocalizedMessage());
throw e;
}
}
public void putRemoteFile(String filename, String contents) throws IOException {
try {
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftpChannel = (ChannelSftp) channel;
ByteArrayInputStream bas = new ByteArrayInputStream(contents.getBytes());
sftpChannel.put(bas, this.getRootUrl() + filename);
sftpChannel.exit();
} catch (Exception e) {
Log.e("MobileOrg", "Exception in putRemoteFile: " + e.toString());
throw new IOException(e);
}
}
public BufferedReader getRemoteFile(String filename) throws IOException {
StringBuilder contents = null;
try {
Channel channel = session.openChannel( "sftp" );
channel.connect();
ChannelSftp sftpChannel = (ChannelSftp) channel;
Log.i("MobileOrg", "SFTP Getting: " + this.getRootUrl() + filename);
InputStream in = sftpChannel.get(this.getRootUrl() + filename);
BufferedReader r = new BufferedReader(new InputStreamReader(in));
contents = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
contents.append(line + "\n");
}
sftpChannel.exit();
} catch (Exception e) {
Log.e("MobileOrg", "Exception in getRemoteFile: " + e.toString());
throw new IOException(e);
}
return new BufferedReader(new StringReader(contents.toString()));
}
@Override
public void postSynchronize() {
if(this.session != null)
this.session.disconnect();
}
@Override
public boolean isConnectable() {
return OrgUtils.isNetworkOnline(context);
}
}
| true | false | null | null |
diff --git a/tests/tests/org.jboss.tools.test/src/org/jboss/tools/tests/AbstractResourceMarkerTest.java b/tests/tests/org.jboss.tools.test/src/org/jboss/tools/tests/AbstractResourceMarkerTest.java
index 56e4256ea..88eeca69a 100644
--- a/tests/tests/org.jboss.tools.test/src/org/jboss/tools/tests/AbstractResourceMarkerTest.java
+++ b/tests/tests/org.jboss.tools.test/src/org/jboss/tools/tests/AbstractResourceMarkerTest.java
@@ -1,212 +1,212 @@
/*******************************************************************************
* Copyright (c) 2007 Red Hat, Inc.
* Distributed under license by Red Hat, Inc. All rights reserved.
* This program is made available under the terms of the
* Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
******************************************************************************/
package org.jboss.tools.tests;
import java.util.ArrayList;
import java.util.List;
import junit.framework.TestCase;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.jboss.tools.test.util.JUnitUtils;
/**
* @author eskimo
*
*/
public class AbstractResourceMarkerTest extends TestCase {
/**
*
*/
public AbstractResourceMarkerTest() {
}
/**
*
*/
public AbstractResourceMarkerTest(String name) {
super(name);
}
protected int findMarkerLine(IResource resource, String type, String pattern)
throws CoreException {
int number = -1;
IMarker[] markers = findMarkers(resource, type, pattern);
for (int i = 0; i < markers.length; i++) {
number = markers[i].getAttribute(IMarker.LINE_NUMBER, -1);
}
return number;
}
protected IMarker[] findMarkers(IResource resource, String type, String pattern) throws CoreException {
List<IMarker> result = new ArrayList<IMarker>();
IMarker[] markers = resource.findMarkers(type, true, IResource.DEPTH_INFINITE);
for (int i = 0; i < markers.length; i++) {
String message = markers[i].getAttribute(IMarker.MESSAGE, ""); //$NON-NLS-1$
if (message.matches(pattern) && markers[i].exists()) {
result.add(markers[i]);
}
}
return result.toArray(new IMarker[0]);
}
protected void assertMarkerIsCreated(IResource resource, MarkerData markerData) throws CoreException {
assertMarkerIsCreated(resource, markerData.type, markerData.pattern, markerData.line);
}
protected void assertMarkerIsCreated(IResource resource, String type, String pattern, int expectedLine)
throws CoreException {
int line = findMarkerLine(
resource, type, pattern);
assertTrue("Marker matches the '" + pattern + "' pattern wasn't found", //$NON-NLS-1$ //$NON-NLS-2$
line != -1);
assertEquals("Marker matches the '" + pattern + "' pattern was found at wrong line", //$NON-NLS-1$//$NON-NLS-2$
expectedLine,line);
}
protected void assertMarkerIsNotCreated(IResource resource, String type, String pattern) throws CoreException {
IMarker[] markers = findMarkers(resource, type, pattern);
assertFalse("Marker matches the '" + pattern + "' pattern was found", markers.length>0); //$NON-NLS-1$ //$NON-NLS-2$
}
protected void assertMarkerIsNotCreated(IResource resource, String type, String pattern, int expectedLine) throws CoreException {
int line = findMarkerLine(resource, type, pattern);
assertFalse("Marker matches the '" + pattern + "' pattern was found", line != -1); //$NON-NLS-1$ //$NON-NLS-2$
}
protected void assertMarkerIsCreated(IResource resource, String type, String pattern) throws CoreException {
IMarker[] markers = findMarkers(resource, type, pattern);
assertTrue("Marker matches the '" + pattern + "' pattern wasn't found", //$NON-NLS-1$ //$NON-NLS-2$
markers.length>0);
}
protected void assertMarkersIsCreated(IResource resource, MarkerData[] markersData) throws CoreException {
for (MarkerData markerData : markersData) {
assertMarkerIsCreated(resource, markerData);
}
}
public static int getMarkersNumber(IResource resource) {
return getMarkersNumber(resource, null);
}
public static int getMarkersNumber(IResource resource, IMarkerFilter filter) {
try{
IMarker[] markers = resource.findMarkers(null, true, IResource.DEPTH_INFINITE);
int length = markers.length;
for(int i=0;i<markers.length;i++){
// System.out.println("Marker - "+markers[i].getAttribute(IMarker.MESSAGE, "")); //$NON-NLS-1$//$NON-NLS-2$
- if(markers[i].exists() && (filter==null || filter.accept(markers[i]))) {
+ if(markers[i].exists() && (filter==null || !filter.accept(markers[i]))) {
length--;
}
}
return length;
}catch(CoreException ex){
JUnitUtils.fail("Can't get problem markers", ex); //$NON-NLS-1$
}
return -1;
}
public static String[] getMarkersMessage(IResource resource) {
return getMarkersMessage(resource, null);
}
public static String[] getMarkersMessage(IResource resource, IMarkerFilter filter) {
List<String> messages = new ArrayList<String>();
try{
IMarker[] markers = resource.findMarkers(null, true, IResource.DEPTH_INFINITE);
// System.out.println("Marker - "+markers[i].getAttribute(IMarker.MESSAGE, "")); //$NON-NLS-1$//$NON-NLS-2$
for(int i=0;i<markers.length;i++){
if(markers[i].exists() && (filter==null || filter.accept(markers[i]))) {
messages.add(markers[i].getAttribute(IMarker.MESSAGE, "")); //$NON-NLS-1$
}
}
}catch(CoreException ex){
JUnitUtils.fail("Can't get problem markers", ex); //$NON-NLS-1$
}
return messages.toArray(new String[0]);
}
public static Integer[] getMarkersNumbersOfLine(IResource resource) {
return getMarkersNumbersOfLine(resource, null);
}
public static Integer[] getMarkersNumbersOfLine(IResource resource, IMarkerFilter filter) {
List<Integer> numbers = new ArrayList<Integer>();
try{
IMarker[] markers = resource.findMarkers(null, true, IResource.DEPTH_INFINITE);
for(int i=0;i<markers.length;i++){
// System.out.println("Marker line number - "+markers[i].getAttribute(IMarker.LINE_NUMBER, 0)); //$NON-NLS-1$
if(markers[i].exists() && (filter==null || filter.accept(markers[i]))) {
numbers.add(markers[i].getAttribute(IMarker.LINE_NUMBER, 0));
}
}
}catch(CoreException ex){
JUnitUtils.fail("Can't get problem markers.", ex); //$NON-NLS-1$
}
return numbers.toArray(new Integer[0]);
}
/**
*
* @author eskimo
*
*/
public static class MarkerData {
private String type;
private String pattern;
private int line = -1;
public MarkerData(String type, String pattern, int line) {
this.type = type;
this.pattern = pattern;
this.line = line;
}
public int getLine() {
return line;
}
public void setLine(int line) {
this.line = line;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getPattern() {
return pattern;
}
public void setPattern(String pattern) {
this.pattern = pattern;
}
}
}
\ No newline at end of file
| true | false | null | null |
diff --git a/src/java/org/jdesktop/swingx/plaf/basic/BasicDatePickerUI.java b/src/java/org/jdesktop/swingx/plaf/basic/BasicDatePickerUI.java
index 0d040a9f..71fca240 100644
--- a/src/java/org/jdesktop/swingx/plaf/basic/BasicDatePickerUI.java
+++ b/src/java/org/jdesktop/swingx/plaf/basic/BasicDatePickerUI.java
@@ -1,1564 +1,1567 @@
/*
* $Id$
*
* Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle,
* Santa Clara, California 95054, U.S.A. All rights reserved.
*
* 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 St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.jdesktop.swingx.plaf.basic;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Insets;
import java.awt.KeyboardFocusManager;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyVetoException;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.Icon;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFormattedTextField;
import javax.swing.JPopupMenu;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.JFormattedTextField.AbstractFormatter;
import javax.swing.JFormattedTextField.AbstractFormatterFactory;
import javax.swing.border.Border;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.UIResource;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.View;
import org.jdesktop.swingx.JXDatePicker;
import org.jdesktop.swingx.JXMonthView;
import org.jdesktop.swingx.SwingXUtilities;
import org.jdesktop.swingx.calendar.CalendarUtils;
import org.jdesktop.swingx.calendar.DatePickerFormatter;
import org.jdesktop.swingx.calendar.DateSelectionModel;
import org.jdesktop.swingx.calendar.DatePickerFormatter.DatePickerFormatterUIResource;
import org.jdesktop.swingx.event.DateSelectionEvent;
import org.jdesktop.swingx.event.DateSelectionListener;
import org.jdesktop.swingx.event.DateSelectionEvent.EventType;
import org.jdesktop.swingx.plaf.DatePickerUI;
/**
* The basic implementation of a <code>DatePickerUI</code>.
* <p>
*
*
* @author Joshua Outwater
* @author Jeanette Winzenburg
*/
public class BasicDatePickerUI extends DatePickerUI {
@SuppressWarnings("all")
private static final Logger LOG = Logger.getLogger(BasicDatePickerUI.class
.getName());
protected JXDatePicker datePicker;
private JButton popupButton;
private BasicDatePickerPopup popup;
private Handler handler;
/*
* shared listeners
*/
protected PropertyChangeListener propertyChangeListener;
private FocusListener focusListener;
/*
* listener's for the arrow button
*/
protected MouseListener mouseListener;
protected MouseMotionListener mouseMotionListener;
/*
* listeners for the picker's editor
*/
private ActionListener editorActionListener;
private EditorCancelAction editorCancelAction;
private PropertyChangeListener editorPropertyListener;
/**
* listeners for the picker's monthview
*/
private DateSelectionListener monthViewSelectionListener;
private ActionListener monthViewActionListener;
private PropertyChangeListener monthViewPropertyListener;
private PopupRemover popupRemover;
@SuppressWarnings({"UnusedDeclaration"})
public static ComponentUI createUI(JComponent c) {
return new BasicDatePickerUI();
}
@Override
public void installUI(JComponent c) {
datePicker = (JXDatePicker)c;
datePicker.setLayout(createLayoutManager());
installComponents();
installDefaults();
installKeyboardActions();
installListeners();
}
@Override
public void uninstallUI(JComponent c) {
uninstallListeners();
uninstallKeyboardActions();
uninstallDefaults();
uninstallComponents();
datePicker.setLayout(null);
datePicker = null;
}
protected void installComponents() {
JFormattedTextField editor = datePicker.getEditor();
if (SwingXUtilities.isUIInstallable(editor)) {
DateFormat[] formats = getCustomFormats(editor);
// we are not yet listening ...
datePicker.setEditor(createEditor());
if (formats != null) {
datePicker.setFormats(formats);
}
}
updateFromEditorChanged(null, false);
popupButton = createPopupButton();
if (popupButton != null) {
// this is a trick to get hold of the client prop which
// prevents closing of the popup
JComboBox box = new JComboBox();
Object preventHide = box.getClientProperty("doNotCancelPopup");
popupButton.putClientProperty("doNotCancelPopup", preventHide);
datePicker.add(popupButton);
}
updateChildLocale(datePicker.getLocale());
}
/**
* Checks and returns custom formats on the editor, if any.
*
* @param editor the editor to check
* @return the custom formats uses in the editor or null if it had
* used defaults as defined in the datepicker properties
*/
private DateFormat[] getCustomFormats(JFormattedTextField editor) {
DateFormat[] formats = null;
if (editor != null) {
AbstractFormatterFactory factory = editor.getFormatterFactory();
if (factory != null) {
AbstractFormatter formatter = factory.getFormatter(editor);
- if (!(formatter instanceof DatePickerFormatterUIResource)) {
+ // fix for #1144: classCastException for custom formatters
+ // PENDING JW: revisit for #1138
+ if ((formatter instanceof DatePickerFormatter) && !(formatter instanceof UIResource)) {
+// if (!(formatter instanceof DatePickerFormatterUIResource)) {
formats = ((DatePickerFormatter) formatter).getFormats();
}
}
}
return formats;
}
protected void uninstallComponents() {
JFormattedTextField editor = datePicker.getEditor();
if (editor != null) {
datePicker.remove(editor);
}
if (popupButton != null) {
datePicker.remove(popupButton);
popupButton = null;
}
}
/**
* Installs DatePicker default properties.
*/
protected void installDefaults() {
// PENDING JW: currently this is for testing only.
boolean zoomable = Boolean.TRUE.equals(UIManager.get("JXDatePicker.forceZoomable"));
if (zoomable) {
datePicker.getMonthView().setZoomable(true);
}
}
protected void uninstallDefaults() {
}
protected void installKeyboardActions() {
// install picker's actions
ActionMap pickerMap = datePicker.getActionMap();
pickerMap.put(JXDatePicker.CANCEL_KEY, createCancelAction());
pickerMap.put(JXDatePicker.COMMIT_KEY, createCommitAction());
pickerMap.put(JXDatePicker.HOME_NAVIGATE_KEY, createHomeAction(false));
pickerMap.put(JXDatePicker.HOME_COMMIT_KEY, createHomeAction(true));
TogglePopupAction popupAction = createTogglePopupAction();
pickerMap.put("TOGGLE_POPUP", popupAction);
InputMap pickerInputMap = datePicker.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
pickerInputMap.put(KeyStroke.getKeyStroke("ENTER"), JXDatePicker.COMMIT_KEY);
pickerInputMap.put(KeyStroke.getKeyStroke("ESCAPE"), JXDatePicker.CANCEL_KEY);
// PENDING: get from LF
pickerInputMap.put(KeyStroke.getKeyStroke("F5"), JXDatePicker.HOME_COMMIT_KEY);
pickerInputMap.put(KeyStroke.getKeyStroke("shift F5"), JXDatePicker.HOME_NAVIGATE_KEY);
pickerInputMap.put(KeyStroke.getKeyStroke("alt DOWN"), "TOGGLE_POPUP");
installLinkPanelKeyboardActions();
}
protected void uninstallKeyboardActions() {
uninstallLinkPanelKeyboardActions(datePicker.getLinkPanel());
}
/**
* Installs actions and key bindings on the datePicker's linkPanel. Does
* nothing if the linkPanel is null.
*
* PRE: keybindings installed on picker.
*/
protected void installLinkPanelKeyboardActions() {
if (datePicker.getLinkPanel() == null)
return;
ActionMap map = datePicker.getLinkPanel().getActionMap();
map.put(JXDatePicker.HOME_COMMIT_KEY, datePicker.getActionMap().get(
JXDatePicker.HOME_COMMIT_KEY));
map.put(JXDatePicker.HOME_NAVIGATE_KEY, datePicker.getActionMap().get(
JXDatePicker.HOME_NAVIGATE_KEY));
InputMap inputMap = datePicker.getLinkPanel().getInputMap(
JComponent.WHEN_IN_FOCUSED_WINDOW);
// PENDING: get from LF
inputMap.put(KeyStroke.getKeyStroke("F5"),
JXDatePicker.HOME_COMMIT_KEY);
inputMap.put(KeyStroke.getKeyStroke("shift F5"),
JXDatePicker.HOME_NAVIGATE_KEY);
}
/**
* Uninstalls actions and key bindings from linkPanel. Does nothing if the
* linkPanel is null.
*
* @param panel the component to uninstall
*
*/
protected void uninstallLinkPanelKeyboardActions(JComponent panel) {
if (panel == null) return;
ActionMap map = panel.getActionMap();
map.remove(JXDatePicker.HOME_COMMIT_KEY);
map.remove(JXDatePicker.HOME_NAVIGATE_KEY);
InputMap inputMap = panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
// PENDING: get from LF
inputMap.remove(KeyStroke.getKeyStroke("F5"));
inputMap.remove(KeyStroke.getKeyStroke("shift F5"));
}
/**
* Creates and installs all listeners to all components.
*
*/
protected void installListeners() {
/*
* create the listeners.
*/
// propertyListener for datePicker
propertyChangeListener = createPropertyChangeListener();
// mouseListener (for popup button only) ?
mouseListener = createMouseListener();
mouseMotionListener = createMouseMotionListener();
// shared focuslistener (installed to picker and editor)
focusListener = createFocusListener();
// editor related listeners
editorActionListener = createEditorActionListener();
editorPropertyListener = createEditorPropertyListener();
// montheView related listeners
monthViewSelectionListener = createMonthViewSelectionListener();
monthViewActionListener = createMonthViewActionListener();
monthViewPropertyListener = createMonthViewPropertyListener();
popupRemover = new PopupRemover();
/*
* install the listeners
*/
// picker
datePicker.addPropertyChangeListener(propertyChangeListener);
datePicker.addFocusListener(focusListener);
if (popupButton != null) {
// JW: which property do we want to monitor?
popupButton.addPropertyChangeListener(propertyChangeListener);
popupButton.addMouseListener(mouseListener);
popupButton.addMouseMotionListener(mouseMotionListener);
}
updateEditorListeners(null);
// JW the following does more than installing the listeners ..
// synchs properties of datepicker to monthView's
// prepares monthview for usage in popup
// synch the date
// Relies on being the last thing done in the install ..
//
updateFromMonthViewChanged(null);
}
/**
* Uninstalls and nulls all listeners which had been installed
* by this delegate.
*
*/
protected void uninstallListeners() {
// datePicker
datePicker.removePropertyChangeListener(propertyChangeListener);
datePicker.removeFocusListener(focusListener);
// monthView
datePicker.getMonthView().getSelectionModel().removeDateSelectionListener(monthViewSelectionListener);
datePicker.getMonthView().removeActionListener(monthViewActionListener);
datePicker.getMonthView().removePropertyChangeListener(propertyChangeListener);
// JW: when can that be null?
// maybe in the very beginning? if some code calls ui.uninstall
// before ui.install? The editor is created by the ui.
if (datePicker.getEditor() != null) {
uninstallEditorListeners(datePicker.getEditor());
}
if (popupButton != null) {
popupButton.removePropertyChangeListener(propertyChangeListener);
popupButton.removeMouseListener(mouseListener);
popupButton.removeMouseMotionListener(mouseMotionListener);
}
popupRemover.unload();
popupRemover = null;
propertyChangeListener = null;
mouseListener = null;
mouseMotionListener = null;
editorActionListener = null;
editorPropertyListener = null;
monthViewSelectionListener = null;
monthViewActionListener = null;
monthViewPropertyListener = null;
handler = null;
}
// --------------------- wiring listeners
/**
* Wires the picker's monthView related listening. Removes all
* listeners from the given old view and adds the listeners to
* the current monthView. <p>
*
* @param oldMonthView
*/
protected void updateMonthViewListeners(JXMonthView oldMonthView) {
DateSelectionModel oldModel = null;
if (oldMonthView != null) {
oldMonthView.removePropertyChangeListener(monthViewPropertyListener);
oldMonthView.removeActionListener(monthViewActionListener);
oldModel = oldMonthView.getSelectionModel();
}
datePicker.getMonthView().addPropertyChangeListener(monthViewPropertyListener);
datePicker.getMonthView().addActionListener(monthViewActionListener);
updateSelectionModelListeners(oldModel);
}
/**
* Wires the picker's editor related listening and actions. Removes
* listeners/actions from the old editor and adds them to
* the new editor. <p>
*
* @param oldEditor the pickers editor before the change
*/
protected void updateEditorListeners(JFormattedTextField oldEditor) {
if (oldEditor != null) {
uninstallEditorListeners(oldEditor);
}
datePicker.getEditor().addPropertyChangeListener(editorPropertyListener);
datePicker.getEditor().addActionListener(editorActionListener);
datePicker.getEditor().addFocusListener(focusListener);
editorCancelAction = new EditorCancelAction(datePicker.getEditor());
}
/**
* Uninstalls all listeners and actions which have been installed
* by this delegate from the given editor.
*
* @param oldEditor the editor to uninstall.
*/
private void uninstallEditorListeners(JFormattedTextField oldEditor) {
oldEditor.removePropertyChangeListener(editorPropertyListener);
oldEditor.removeActionListener(editorActionListener);
oldEditor.removeFocusListener(focusListener);
if (editorCancelAction != null) {
editorCancelAction.uninstall();
editorCancelAction = null;
}
}
/**
* Wires monthView's selection model listening. Removes the
* selection listener from the old model and add to the new model.
*
* @param oldModel the dateSelectionModel before the change, may be null.
*/
protected void updateSelectionModelListeners(DateSelectionModel oldModel) {
if (oldModel != null) {
oldModel.removeDateSelectionListener(monthViewSelectionListener);
}
datePicker.getMonthView().getSelectionModel()
.addDateSelectionListener(monthViewSelectionListener);
}
// ---------------- component creation
/**
* Creates the editor used to edit the date selection. The editor is
* configured with the default DatePickerFormatter marked as UIResource.
*
* @return an instance of a JFormattedTextField
*/
protected JFormattedTextField createEditor() {
JFormattedTextField f = new DefaultEditor(
new DatePickerFormatterUIResource(datePicker.getLocale()));
f.setName("dateField");
// this produces a fixed pref widths, looking a bit funny
// int columns = UIManagerExt.getInt("JXDatePicker.numColumns", null);
// if (columns > 0) {
// f.setColumns(columns);
// }
// that's always 0 as it comes from the resourcebundle
// f.setColumns(UIManager.getInt("JXDatePicker.numColumns"));
Border border = UIManager.getBorder("JXDatePicker.border");
if (border != null) {
f.setBorder(border);
}
return f;
}
protected JButton createPopupButton() {
JButton b = new JButton();
b.setName("popupButton");
b.setRolloverEnabled(false);
b.setMargin(new Insets(0, 3, 0, 3));
Icon icon = UIManager.getIcon("JXDatePicker.arrowIcon");
if (icon == null) {
icon = (Icon)UIManager.get("Tree.expandedIcon");
}
b.setIcon(icon);
b.setFocusable(false);
return b;
}
private class DefaultEditor extends JFormattedTextField implements UIResource {
private Dimension prefSizeCache;
private int prefEmptyInset;
public DefaultEditor(AbstractFormatter formatter) {
super(formatter);
}
@Override
public Dimension getPreferredSize() {
Dimension preferredSize = super.getPreferredSize();
if (getColumns() <= 0) {
if (getValue() == null) {
if (prefSizeCache != null) {
preferredSize.width = prefSizeCache.width;
preferredSize.height = prefSizeCache.height;
} else {
prefEmptyInset = preferredSize.width;
preferredSize.width = prefEmptyInset + getNullWidth();
}
} else {
preferredSize.width += Math.max(prefEmptyInset, 4);
prefSizeCache = new Dimension(preferredSize);
}
}
return preferredSize;
}
/**
* @return
*/
private int getNullWidth() {
JFormattedTextField field = new JFormattedTextField(getFormatter());
field.setMargin(getMargin());
field.setBorder(getBorder());
field.setFont(getFont());
field.setValue(new Date());
return field.getPreferredSize().width;
}
}
// ---------------- Layout
/**
* {@inheritDoc}
*/
@Override
public Dimension getMinimumSize(JComponent c) {
return getPreferredSize(c);
}
/**
* {@inheritDoc}
*/
@Override
public Dimension getPreferredSize(JComponent c) {
Dimension dim = getEditorPreferredSize();
if (popupButton != null) {
dim.width += popupButton.getPreferredSize().width;
}
Insets insets = datePicker.getInsets();
dim.width += insets.left + insets.right;
dim.height += insets.top + insets.bottom;
return (Dimension)dim.clone();
}
/**
* Returns a preferred size for the editor. If the selected date
* is null, returns a reasonable minimal width. <p>
*
* PENDING: how to find the "reasonable" width is open to discussion.
* This implementation creates another datepicker, feeds it with
* the formats and asks its prefWidth. <p>
*
* That hack blows in some contexts (see Issue #763) - as a very quick
* replacement create a editor only.
*
* PENDING: there's a resource property JXDatePicker.numColumns - why
* don't we use it?
*
* @return the editor's preferred size
*/
private Dimension getEditorPreferredSize() {
Dimension dim = datePicker.getEditor().getPreferredSize();
if (datePicker.getDate() == null) {
// JFormattedTextField field = createEditor(new DatePickerFormatterUIResource(
// datePicker.getFormats(),
// datePicker.getLocale()));
// field.setValue(new Date());
// dim.width = Math.max(field.getPreferredSize().width, dim.width);
// the editor tends to collapsing for empty values
// JW: better do this in a custom editor?
// seems to produce #763
// JXDatePicker picker = new JXDatePicker(new Date());
// picker.setFormats(datePicker.getFormats());
// dim.width = picker.getEditor().getPreferredSize().width;
}
return dim;
}
@Override
public int getBaseline(int width, int height) {
JFormattedTextField editor = datePicker.getEditor();
View rootView = editor.getUI().getRootView(editor);
if (rootView.getViewCount() > 0) {
Insets insets = editor.getInsets();
Insets insetsOut = datePicker.getInsets();
int nh = height - insets.top - insets.bottom
- insetsOut.top - insetsOut.bottom;
int y = insets.top + insetsOut.top;
View fieldView = rootView.getView(0);
int vspan = (int) fieldView.getPreferredSpan(View.Y_AXIS);
if (nh != vspan) {
int slop = nh - vspan;
y += slop / 2;
}
FontMetrics fm = editor.getFontMetrics(editor.getFont());
y += fm.getAscent();
return y;
}
return -1;
}
//------------------------------- controller methods/classes
/**
* {@inheritDoc}
*/
@Override
public Date getSelectableDate(Date date) throws PropertyVetoException {
Date cleaned = date == null ? null :
datePicker.getMonthView().getSelectionModel().getNormalizedDate(date);
if (CalendarUtils.areEqual(cleaned, datePicker.getDate())) {
// one place to interrupt the update spiral
throw new PropertyVetoException("date not selectable", null);
}
if (cleaned == null) return cleaned;
if (datePicker.getMonthView().isUnselectableDate(cleaned)) {
throw new PropertyVetoException("date not selectable", null);
}
return cleaned;
}
//-------------------- update methods called from listeners
/**
* Updates internals after picker's date property changed.
*/
protected void updateFromDateChanged() {
Date visibleHook = datePicker.getDate() != null ?
datePicker.getDate() : datePicker.getLinkDay();
datePicker.getMonthView().ensureDateVisible(visibleHook);
datePicker.getEditor().setValue(datePicker.getDate());
}
/**
* Updates date related properties in picker/monthView
* after a change in the editor's value. Reverts the
* value if the new date is unselectable.
*
* @param oldDate the editor value before the change
* @param newDate the editor value after the change
*/
protected void updateFromValueChanged(Date oldDate, Date newDate) {
if ((newDate != null) && datePicker.getMonthView().isUnselectableDate(newDate)) {
revertValue(oldDate);
return;
}
// the other place to interrupt the update spiral
if (!CalendarUtils.areEqual(newDate, datePicker.getMonthView().getSelectionDate())) {
datePicker.getMonthView().setSelectionDate(newDate);
}
datePicker.setDate(newDate);
}
/**
* PENDING: currently this resets at once - but it's a no-no,
* because it happens during notification
*
* @param oldDate the old date to revert to
*/
private void revertValue(Date oldDate) {
datePicker.getEditor().setValue(oldDate);
}
/**
* Updates date related properties picker/editor
* after a change in the monthView's
* selection.
*
* Here: does nothing if the change is intermediate.
*
* PENDNG JW: shouldn't we listen to actionEvents then?
*
* @param eventType the type of the selection change
* @param adjusting flag to indicate whether the the selection change
* is intermediate
*/
protected void updateFromSelectionChanged(EventType eventType, boolean adjusting) {
if (adjusting) return;
updateEditorValue();
}
/**
* Updates internals after the picker's monthView has changed. <p>
*
* Cleans to popup. Wires the listeners. Updates date.
* Updates formats' timezone.
*
* @param oldMonthView the picker's monthView before the change,
* may be null.
*/
protected void updateFromMonthViewChanged(JXMonthView oldMonthView) {
popup = null;
updateMonthViewListeners(oldMonthView);
TimeZone oldTimeZone = null;
if (oldMonthView != null) {
oldMonthView.setComponentInputMapEnabled(false);
oldTimeZone = oldMonthView.getTimeZone();
}
datePicker.getMonthView().setComponentInputMapEnabled(true);
updateTimeZone(oldTimeZone);
updateEditorValue();
}
/**
* Updates internals after the picker's editor property
* has changed. <p>
*
* Updates the picker's children. Removes the old editor and
* adds the new editor. Wires the editor listeners, it the flag
* set. Typically, this method is called during installing the
* componentUI with the flag set to false and true at all other
* moments.
*
*
* @param oldEditor the picker's editor before the change,
* may be null.
* @param updateListeners a flag to indicate whether the listeners
* are ready for usage.
*/
protected void updateFromEditorChanged(JFormattedTextField oldEditor,
boolean updateListeners) {
if (oldEditor != null) {
datePicker.remove(oldEditor);
oldEditor.putClientProperty("doNotCancelPopup", null);
}
datePicker.add(datePicker.getEditor());
// this is a trick to get hold of the client prop which
// prevents closing of the popup
JComboBox box = new JComboBox();
Object preventHide = box.getClientProperty("doNotCancelPopup");
datePicker.getEditor().putClientProperty("doNotCancelPopup", preventHide);
updateEditorValue();
if (updateListeners) {
updateEditorListeners(oldEditor);
datePicker.revalidate();
}
}
/**
* Updates internals after the selection model changed.
*
* @param oldModel the model before the change.
*/
protected void updateFromSelectionModelChanged(DateSelectionModel oldModel) {
updateSelectionModelListeners(oldModel);
updateEditorValue();
}
/**
* Sets the editor value to the model's selectedDate.
*/
private void updateEditorValue() {
datePicker.getEditor().setValue(datePicker.getMonthView().getSelectionDate());
}
//---------------------- updating other properties
/**
* Updates properties which depend on the picker's editable. <p>
*
*/
protected void updateFromEditableChanged() {
boolean isEditable = datePicker.isEditable();
datePicker.getMonthView().setEnabled(isEditable);
datePicker.getEditor().setEditable(isEditable);
/*
* PatrykRy: Commit today date is not allowed if datepicker is not editable!
*/
setActionEnabled(JXDatePicker.HOME_COMMIT_KEY, isEditable);
// for consistency, synch navigation as well
setActionEnabled(JXDatePicker.HOME_NAVIGATE_KEY, isEditable);
}
/**
*
* @param key
* @param enabled
*/
private void setActionEnabled(String key, boolean enabled) {
Action action = datePicker.getActionMap().get(key);
if (action != null) {
action.setEnabled(enabled);
}
}
/**
* Updates the picker's formats to the given TimeZone.
* @param zone the timezone to set on the formats.
*/
protected void updateFormatsFromTimeZone(TimeZone zone) {
for (DateFormat format : datePicker.getFormats()) {
format.setTimeZone(zone);
}
}
/**
* Updates picker's timezone dependent properties on change notification
* from the associated monthView.
*
* PENDING JW: DatePicker needs to send notification on timezone change?
*
* @param old the timezone before the change.
*/
protected void updateTimeZone(TimeZone old) {
updateFormatsFromTimeZone(datePicker.getTimeZone());
updateLinkDate();
}
/**
* Updates the picker's linkDate to be in synch with monthView's today.
*/
protected void updateLinkDate() {
datePicker.setLinkDay(datePicker.getMonthView().getToday());
}
/**
* Called form property listener, updates all components locale, formats
* etc.
*
* @author PeS
*/
protected void updateLocale() {
Locale locale = datePicker.getLocale();
updateFormatLocale(locale);
updateChildLocale(locale);
}
private void updateFormatLocale(Locale locale) {
if (locale != null) {
// PENDING JW: timezone?
if (getCustomFormats(datePicker.getEditor()) == null) {
datePicker.getEditor().setFormatterFactory(
new DefaultFormatterFactory(
new DatePickerFormatterUIResource(locale)));
}
}
}
private void updateChildLocale(Locale locale) {
if (locale != null) {
datePicker.getEditor().setLocale(locale);
datePicker.getLinkPanel().setLocale(locale);
datePicker.getMonthView().setLocale(locale);
}
}
/**
* @param oldLinkPanel
*
*/
protected void updateLinkPanel(JComponent oldLinkPanel) {
if (oldLinkPanel != null) {
uninstallLinkPanelKeyboardActions(oldLinkPanel);
}
installLinkPanelKeyboardActions();
if (popup != null) {
popup.updateLinkPanel(oldLinkPanel);
}
}
//------------------- methods called by installed actions
/**
*
*/
protected void commit() {
hidePopup();
try {
datePicker.commitEdit();
} catch (ParseException ex) {
// can't help it
}
}
/**
*
*/
protected void cancel() {
hidePopup();
datePicker.cancelEdit();
}
/**
* PENDING: widened access for debugging - need api to
* control popup visibility?
*/
public void hidePopup() {
if (popup != null) popup.setVisible(false);
}
public boolean isPopupVisible() {
if (popup != null) {
return popup.isVisible();
}
return false;
}
/**
* Navigates to linkDate. If commit, the linkDate is selected
* and committed. If not commit, the linkDate is scrolled to visible, if the
* monthview is open, does nothing for invisible monthView.
*
* @param commit boolean to indicate whether the linkDate should be
* selected and committed
*/
protected void home(boolean commit) {
if (commit) {
Calendar cal = datePicker.getMonthView().getCalendar();
cal.setTime(datePicker.getLinkDay());
datePicker.getMonthView().setSelectionDate(cal.getTime());
datePicker.getMonthView().commitSelection();
} else {
datePicker.getMonthView().ensureDateVisible(datePicker.getLinkDay());
}
}
//---------------------- other stuff
/**
* Creates and returns the action for committing the picker's
* input.
*
* @return
*/
private Action createCommitAction() {
Action action = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
commit();
}
};
return action;
}
/**
* Creates and returns the action for cancel the picker's
* edit.
*
* @return
*/
private Action createCancelAction() {
Action action = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
cancel();
}
};
return action;
}
private Action createHomeAction(final boolean commit) {
Action action = new AbstractAction( ) {
public void actionPerformed(ActionEvent e) {
home(commit);
}
};
return action ;
}
/**
* The wrapper for the editor cancel action.
*
* PENDING: Need to extend TestAction?
*
*/
public class EditorCancelAction extends AbstractAction {
private JFormattedTextField editor;
private Action cancelAction;
public static final String TEXT_CANCEL_KEY = "reset-field-edit";
public EditorCancelAction(JFormattedTextField field) {
install(field);
}
/**
* Resets the contained editors actionMap to original and
* nulls all fields. <p>
* NOTE: after calling this method the action must not be
* used! Create a new one for the same or another editor.
*
*/
public void uninstall() {
editor.getActionMap().remove(TEXT_CANCEL_KEY);
cancelAction = null;
editor = null;
}
/**
* @param editor
*/
private void install(JFormattedTextField editor) {
this.editor = editor;
cancelAction = editor.getActionMap().get(TEXT_CANCEL_KEY);
editor.getActionMap().put(TEXT_CANCEL_KEY, this);
}
public void actionPerformed(ActionEvent e) {
cancelAction.actionPerformed(null);
cancel();
}
}
/**
* Creates and returns the action which toggles the visibility of the popup.
*
* @return the action which toggles the visibility of the popup.
*/
protected TogglePopupAction createTogglePopupAction() {
return new TogglePopupAction();
}
/**
* Toggles the popups visibility after preparing internal state.
*
*
*/
public void toggleShowPopup() {
if (popup == null) {
popup = createMonthViewPopup();
}
if (popup.isVisible()) {
popup.setVisible(false);
} else {
// PENDING JW: Issue 757-swing - datePicker firing focusLost on opening
// not with following line - but need to run tests
datePicker.getEditor().requestFocusInWindow();
// datePicker.requestFocusInWindow();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
popup.show(datePicker,
0, datePicker.getHeight());
}
});
}
}
/**
*
*/
private BasicDatePickerPopup createMonthViewPopup() {
BasicDatePickerPopup popup = new BasicDatePickerPopup();
popup.setLightWeightPopupEnabled(datePicker.isLightWeightPopupEnabled());
return popup;
}
/**
* Action used to commit the current value in the JFormattedTextField.
* This action is used by the keyboard bindings.
*/
private class TogglePopupAction extends AbstractAction {
public TogglePopupAction() {
super("TogglePopup");
}
public void actionPerformed(ActionEvent ev) {
toggleShowPopup();
}
}
/**
* Popup component that shows a JXMonthView component along with controlling
* buttons to allow traversal of the months. Upon selection of a date the
* popup will automatically hide itself and enter the selection into the
* editable field of the JXDatePicker.
*
*/
protected class BasicDatePickerPopup extends JPopupMenu {
public BasicDatePickerPopup() {
setLayout(new BorderLayout());
add(datePicker.getMonthView(), BorderLayout.CENTER);
updateLinkPanel(null);
}
/**
* @param oldLinkPanel
*/
public void updateLinkPanel(JComponent oldLinkPanel) {
if (oldLinkPanel != null) {
remove(oldLinkPanel);
}
if (datePicker.getLinkPanel() != null) {
add(datePicker.getLinkPanel(), BorderLayout.SOUTH);
}
}
}
/**
* PENDING: JW - I <b>really</b> hate the one-in-all. Wont touch
* it for now, maybe later. As long as we have it, the new
* listeners (dateSelection) are here too, for consistency.
* Adding the Layout here as well is ... , IMO.
*/
private class Handler implements LayoutManager, MouseListener, MouseMotionListener,
PropertyChangeListener, DateSelectionListener, ActionListener, FocusListener {
//------------- implement Mouse/MotionListener
private boolean _forwardReleaseEvent = false;
public void mouseClicked(MouseEvent ev) {
}
public void mousePressed(MouseEvent ev) {
if (!datePicker.isEnabled()) {
return;
}
// PENDING JW: why do we need a mouseListener? the
// arrowbutton should have the toggleAction installed?
// Hmm... maybe doesn't ... check!
// reason might be that we want to open on pressed
// typically (or LF-dependent?),
// the button's action is invoked on released.
toggleShowPopup();
}
public void mouseReleased(MouseEvent ev) {
if (!datePicker.isEnabled() || !datePicker.isEditable()) {
return;
}
// Retarget mouse event to the month view.
if (_forwardReleaseEvent) {
JXMonthView monthView = datePicker.getMonthView();
ev = SwingUtilities.convertMouseEvent(popupButton, ev,
monthView);
monthView.dispatchEvent(ev);
_forwardReleaseEvent = false;
}
}
public void mouseEntered(MouseEvent ev) {
}
public void mouseExited(MouseEvent ev) {
}
public void mouseDragged(MouseEvent ev) {
if (!datePicker.isEnabled() || !datePicker.isEditable()) {
return;
}
_forwardReleaseEvent = true;
if (!popup.isShowing()) {
return;
}
// Retarget mouse event to the month view.
JXMonthView monthView = datePicker.getMonthView();
ev = SwingUtilities.convertMouseEvent(popupButton, ev, monthView);
monthView.dispatchEvent(ev);
}
public void mouseMoved(MouseEvent ev) {
}
//------------------ implement DateSelectionListener
public void valueChanged(DateSelectionEvent ev) {
updateFromSelectionChanged(ev.getEventType(), ev.isAdjusting());
}
//------------------ implement propertyChangeListener
/**
* {@inheritDoc}
*/
public void propertyChange(PropertyChangeEvent e) {
if (e.getSource() == datePicker) {
datePickerPropertyChange(e);
} else
if (e.getSource() == datePicker.getEditor()) {
editorPropertyChange(e);
} else
if (e.getSource() == datePicker.getMonthView()) {
monthViewPropertyChange(e);
} else
if (e.getSource() == popupButton) {
buttonPropertyChange(e);
} else
// PENDING - move back, ...
if ("value".equals(e.getPropertyName())) {
throw new IllegalStateException(
"editor listening is moved to dedicated propertyChangeLisener");
}
}
/**
* Handles property changes from datepicker's editor.
*
* @param e the PropertyChangeEvent object describing the event source
* and the property that has changed
*/
private void editorPropertyChange(PropertyChangeEvent evt) {
if ("value".equals(evt.getPropertyName())) {
updateFromValueChanged((Date) evt.getOldValue(), (Date) evt
.getNewValue());
}
}
/**
* Handles property changes from DatePicker.
* @param e the PropertyChangeEvent object describing the
* event source and the property that has changed
*/
private void datePickerPropertyChange(PropertyChangeEvent e) {
String property = e.getPropertyName();
if ("date".equals(property)) {
updateFromDateChanged();
} else if ("enabled".equals(property)) {
boolean isEnabled = datePicker.isEnabled();
popupButton.setEnabled(isEnabled);
datePicker.getEditor().setEnabled(isEnabled);
} else if ("editable".equals(property)) {
updateFromEditableChanged();
} else if (JComponent.TOOL_TIP_TEXT_KEY.equals(property)) {
String tip = datePicker.getToolTipText();
datePicker.getEditor().setToolTipText(tip);
popupButton.setToolTipText(tip);
} else if (JXDatePicker.MONTH_VIEW.equals(property)) {
updateFromMonthViewChanged((JXMonthView) e.getOldValue());
} else if (JXDatePicker.LINK_PANEL.equals(property)) {
updateLinkPanel((JComponent) e.getOldValue());
} else if (JXDatePicker.EDITOR.equals(property)) {
updateFromEditorChanged((JFormattedTextField) e.getOldValue(), true);
} else if ("componentOrientation".equals(property)) {
datePicker.revalidate();
} else if ("lightWeightPopupEnabled".equals(property)) {
// Force recreation of the popup when this property changes.
if (popup != null) {
popup.setVisible(false);
}
popup = null;
} else if ("formats".equals(property)) {
updateFormatsFromTimeZone(datePicker.getTimeZone());
}
else if ("locale".equals(property)) {
updateLocale();
}
}
/**
* Handles propertyChanges from the picker's monthView.
*
* @param e the PropertyChangeEvent object describing the event source
* and the property that has changed
*/
private void monthViewPropertyChange(PropertyChangeEvent e) {
if ("selectionModel".equals(e.getPropertyName())) {
updateFromSelectionModelChanged((DateSelectionModel) e.getOldValue());
} else if ("timeZone".equals(e.getPropertyName())) {
updateTimeZone((TimeZone) e.getOldValue());
} else if ("today".equals(e.getPropertyName())) {
updateLinkDate();
}
}
/**
* Handles propertyChanges from the picker's popupButton.
*
* PENDING: does nothing, kept while refactoring .. which
* properties from the button do we want to handle?
*
* @param e the PropertyChangeEvent object describing the event source
* and the property that has changed.
*/
private void buttonPropertyChange(PropertyChangeEvent e) {
}
//-------------- implement LayoutManager
public void addLayoutComponent(String name, Component comp) { }
public void removeLayoutComponent(Component comp) { }
public Dimension preferredLayoutSize(Container parent) {
return parent.getPreferredSize();
}
public Dimension minimumLayoutSize(Container parent) {
return parent.getMinimumSize();
}
public void layoutContainer(Container parent) {
Insets insets = datePicker.getInsets();
int width = datePicker.getWidth() - insets.left - insets.right;
int height = datePicker.getHeight() - insets.top - insets.bottom;
int popupButtonWidth = popupButton != null ? popupButton.getPreferredSize().width : 0;
boolean ltr = datePicker.getComponentOrientation().isLeftToRight();
datePicker.getEditor().setBounds(ltr ? insets.left : insets.left + popupButtonWidth,
insets.top,
width - popupButtonWidth,
height);
if (popupButton != null) {
popupButton.setBounds(ltr ? width - popupButtonWidth + insets.left : insets.left,
insets.top,
popupButtonWidth,
height);
}
}
// ------------- implement actionListener (listening to monthView actionEvent)
public void actionPerformed(ActionEvent e) {
if (e == null) return;
if (e.getSource() == datePicker.getMonthView()) {
monthViewActionPerformed(e);
} else if (e.getSource() == datePicker.getEditor()) {
editorActionPerformed(e);
}
}
/**
* Listening to actionEvents fired by the picker's editor.
*
* @param e
*/
private void editorActionPerformed(ActionEvent e) {
// pass the commit on to the picker.
commit();
}
/**
* Listening to actionEvents fired by the picker's monthView.
*
* @param e
*/
private void monthViewActionPerformed(ActionEvent e) {
if (JXMonthView.CANCEL_KEY.equals(e.getActionCommand())) {
cancel();
} else if (JXMonthView.COMMIT_KEY.equals(e.getActionCommand())) {
commit();
}
}
//------------------- focusListener
/**
* Issue #573-swingx - F2 in table doesn't focus the editor.
*
* Do the same as combo: manually pass-on the focus to the editor.
*
*/
public void focusGained(FocusEvent e) {
if (e.isTemporary()) return;
popupRemover.load();
if (e.getSource() == datePicker) {
datePicker.getEditor().requestFocusInWindow();
}
}
/**
* #565-swingx: popup not hidden if clicked into combo.
* The problem is that the combo uses the same trick as
* this datepicker to prevent auto-closing of the popup
* if focus is transfered back to the picker's editor.
*
* The idea is to hide the popup manually when the
* permanentFocusOwner changes to somewhere else.
*
* JW: doesn't work - we only get the temporary lost,
* but no permanent loss if the focus is transfered from
* the focusOwner to a new permanentFocusOwner.
*
* OOOkaay ... looks like exclusively related to a combo:
* we do get the expected focusLost if the focus is
* transferred permanently from the temporary focusowner
* to a new "normal" permanentFocusOwner (like a textfield),
* we don't get it if transfered to a tricksing owner (like
* a combo or picker). So can't do anything here.
*
* listen to keyboardFocusManager?
*/
public void focusLost(FocusEvent e) {
}
}
public class PopupRemover implements PropertyChangeListener {
private KeyboardFocusManager manager;
private boolean loaded;
public void load() {
if (manager != KeyboardFocusManager.getCurrentKeyboardFocusManager()) {
unload();
manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
}
if (!loaded) {
manager.addPropertyChangeListener("permanentFocusOwner", this);
loaded = true;
}
}
/**
* @param b
*/
private void unload(boolean nullManager) {
if (manager != null) {
manager.removePropertyChangeListener("permanentFocusOwner", this);
if (nullManager) {
manager = null;
}
}
loaded = false;
}
public void unload() {
unload(true);
}
public void propertyChange(PropertyChangeEvent evt) {
if (!isPopupVisible()) {
unload(false);
return;
}
Component comp = manager.getPermanentFocusOwner();
if ((comp != null) && !SwingXUtilities.isDescendingFrom(comp, datePicker)) {
unload(false);
// on hiding the popup the focusmanager transfers
// focus back to the old permanentFocusOwner
// before showing the popup, that is the picker
// or the editor. So we have to force it back ...
hidePopup();
comp.requestFocusInWindow();
// this has no effect as focus changes are asynchronous
// inHide = false;
}
}
}
// ------------------ listener creation
/**
* Creates and returns the property change listener for the
* picker's monthView
* @return the listener for monthView properties
*/
protected PropertyChangeListener createMonthViewPropertyListener() {
return getHandler();
}
/**
* Creates and returns the focuslistener for picker and editor.
* @return the focusListener
*/
protected FocusListener createFocusListener() {
return getHandler();
}
/**
* Creates and returns the ActionListener for the picker's editor.
* @return the Actionlistener for the editor.
*/
protected ActionListener createEditorActionListener() {
return getHandler();
}
/**
* Creates and returns the ActionListener for the picker's monthView.
*
* @return the Actionlistener for the monthView.
*/
protected ActionListener createMonthViewActionListener() {
return getHandler();
}
/**
* Returns the listener for the dateSelection.
*
* @return the date selection listener
*/
protected DateSelectionListener createMonthViewSelectionListener() {
return getHandler();
}
/**
* @return a propertyChangeListener listening to
* editor property changes
*/
protected PropertyChangeListener createEditorPropertyListener() {
return getHandler();
}
/**
* Lazily creates and returns the shared all-mighty listener of everything
*
* @return the shared listener.
*/
private Handler getHandler() {
if (handler == null) {
handler = new Handler();
}
return handler;
}
protected PropertyChangeListener createPropertyChangeListener() {
return getHandler();
}
protected LayoutManager createLayoutManager() {
return getHandler();
}
protected MouseListener createMouseListener() {
return getHandler();
}
protected MouseMotionListener createMouseMotionListener() {
return getHandler();
}
//------------ utility methods
}
diff --git a/src/test/org/jdesktop/swingx/JXDatePickerTest.java b/src/test/org/jdesktop/swingx/JXDatePickerTest.java
index 7a121362..b7eeaf9b 100644
--- a/src/test/org/jdesktop/swingx/JXDatePickerTest.java
+++ b/src/test/org/jdesktop/swingx/JXDatePickerTest.java
@@ -1,1750 +1,1775 @@
/*
* $Id$
*
* Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle,
* Santa Clara, California 95054, U.S.A. All rights reserved.
*
* 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 St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.jdesktop.swingx;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionListener;
import java.text.DateFormat;
import java.text.Format;
import java.text.MessageFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.logging.Logger;
import javax.swing.Action;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFormattedTextField;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.plaf.UIResource;
+import javax.swing.text.DateFormatter;
import javax.swing.text.DefaultFormatterFactory;
import org.jdesktop.swingx.calendar.CalendarUtils;
import org.jdesktop.swingx.calendar.DatePickerFormatter;
import org.jdesktop.swingx.calendar.DateSelectionModel;
import org.jdesktop.swingx.calendar.DefaultDateSelectionModel;
import org.jdesktop.swingx.calendar.SingleDaySelectionModel;
import org.jdesktop.swingx.plaf.UIManagerExt;
import org.jdesktop.swingx.plaf.basic.BasicDatePickerUI.EditorCancelAction;
import org.jdesktop.swingx.test.XTestUtils;
import org.jdesktop.test.ActionReport;
import org.jdesktop.test.PropertyChangeReport;
import org.jdesktop.test.TestUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Unit tests for JXDatePicker.
*/
@RunWith(JUnit4.class)
public class JXDatePickerTest extends InteractiveTestCase {
private static final Logger LOG = Logger.getLogger(JXDatePickerTest.class
.getName());
private Calendar calendar;
@Override
@Before
public void setUp() {
calendar = Calendar.getInstance();
}
@Override
@After
public void tearDown() {
}
+ /**
+ * Issue #1144-swingx: JXDatePicker must accept custom formatter.
+ * Pathological .. but anyway: formatter may be null.
+ * Issue manifests in throwing NPE.
+ */
+ @Test
+ public void testCustomFormatterNull() {
+ JXDatePicker picker = new JXDatePicker();
+ DefaultFormatterFactory factory = new DefaultFormatterFactory();
+ assertEquals("sanity (null formatter): ", null, factory.getFormatter(picker.getEditor()));
+ picker.getEditor().setFormatterFactory(factory);
+ picker.updateUI();
+ }
+ /**
+ * Issue #1144-swingx: JXDatePicker must accept custom formatter.
+ * Use core DateFormatter - issue manifests in throwing classcastEx
+ */
+ @Test
+ public void testCustomFormatterCore() {
+ JXDatePicker picker = new JXDatePicker();
+ DefaultFormatterFactory factory = new DefaultFormatterFactory(new DateFormatter());
+ picker.getEditor().setFormatterFactory(factory);
+ picker.updateUI();
+ }
/**
* Issue #910-swingx: home commit must be disabled if picker not editable.
*
*/
@Test
public void testNotEditableNullHomeNavigate() {
JXDatePicker picker = new JXDatePicker();
picker.getActionMap().remove(JXDatePicker.HOME_NAVIGATE_KEY);
picker.setEditable(!picker.isEditable());
}
/**
* Issue #910-swingx: home commit must be disabled if picker not editable.
*
*/
@Test
public void testNotEditableDisabledHomeNavigate() {
JXDatePicker picker = new JXDatePicker();
Action delegate = picker.getActionMap().get(JXDatePicker.HOME_NAVIGATE_KEY);
assertEquals(picker.isEditable(), delegate.isEnabled());
picker.setEditable(!picker.isEditable());
assertEquals(picker.isEditable(), delegate.isEnabled());
}
/**
* Issue #910-swingx: home commit must be disabled if picker not editable.
*
*/
@Test
public void testNotEditableNullHomeCommit() {
JXDatePicker picker = new JXDatePicker();
picker.getActionMap().remove(JXDatePicker.HOME_COMMIT_KEY);
picker.setEditable(!picker.isEditable());
}
/**
* Issue #910-swingx: home commit must be disabled if picker not editable.
*
*/
@Test
public void testNotEditableDisabledHomeCommit() {
JXDatePicker picker = new JXDatePicker();
Action delegate = picker.getActionMap().get(JXDatePicker.HOME_COMMIT_KEY);
assertEquals(picker.isEditable(), delegate.isEnabled());
picker.setEditable(!picker.isEditable());
assertEquals(picker.isEditable(), delegate.isEnabled());
}
/**
* Sanity: report in forum that editor not disabled if picker disabled.
* Looks okay.
*/
@Test
public void testEnabled() {
JXDatePicker picker = new JXDatePicker();
picker.setEnabled(false);
assertFalse("sanity: picker disabled", picker.isEnabled());
assertEquals("editor enabled must follow picker enabled",
picker.isEnabled(), picker.getEditor().isEnabled());
}
/**
* Issue #764-swingx: JXDatePicker sizing
*
* editor must respect columns.
*/
@Test
public void testDatePickerColumns50() {
JXDatePicker picker = new JXDatePicker();
picker.getEditor().setColumns(50);
JXDatePicker other = new JXDatePicker(new Date());
other.getEditor().setColumns(50);
assertEquals(other.getEditor().getPreferredSize(), picker.getEditor().getPreferredSize());
}
/**
* Issue #764-swingx: JXDatePicker sizing
*
* editor must respect columns.
*/
@Test
public void testDatePickerColumns5() {
JXDatePicker picker = new JXDatePicker();
picker.getEditor().setColumns(5);
JXDatePicker other = new JXDatePicker(new Date());
other.getEditor().setColumns(5);
assertEquals(other.getEditor().getPreferredSize(), picker.getEditor().getPreferredSize());
}
/**
* Issue #667-swingx: don't install the datepicker border for gtk.
*
* Here we are testing that the BasicPickerUI doesn't touch the
* editors border if it finds a null.
*
*/
@Test
public void testPickerBorder() {
// force loading of addon
new JXDatePicker();
Border pickerBorder = UIManager.getBorder("JXDatePicker.border");
if (pickerBorder == null) {
LOG.info("cant run test - no pickerborder");
return;
}
try {
UIManager.put("JXDatePicker.border", "none");
assertNull(UIManager.getBorder("JXDatePicker.border"));
JXDatePicker picker = new JXDatePicker();
JTextField field = new JFormattedTextField();
assertEquals(field.getBorder(), picker.getEditor().getBorder());
} finally {
// restore LAF border
UIManager.put("JXDatePicker.border", null);
assertEquals(pickerBorder, UIManager.getBorder("JXDatePicker.border"));
}
}
/**
* Issue #724-swingx: picker must notify about timezone changes.
* Here: change the timezone on the monthView - can't guarantee the notification.
* At least not without hacks...
*/
@Test
public void testTimeZoneChangeNotificationChangeOnMonthView() {
JXDatePicker picker = new JXDatePicker();
TimeZone timeZone = picker.getTimeZone();
TimeZone alternative = getSafeAlternativeTimeZone(timeZone);
PropertyChangeReport report = new PropertyChangeReport();
picker.addPropertyChangeListener(report);
picker.getMonthView().setTimeZone(alternative);
TestUtils.assertPropertyChangeEvent(report, "timeZone", timeZone, alternative, false);
}
/**
* Issue #724-swingx: picker must notify about timezone changes.
* Here: change the timezon on the picker - can guarantee the notification.
*/
@Test
public void testTimeZoneChangeNotification() {
JXDatePicker picker = new JXDatePicker();
TimeZone timeZone = picker.getTimeZone();
TimeZone alternative = getSafeAlternativeTimeZone(timeZone);
PropertyChangeReport report = new PropertyChangeReport();
picker.addPropertyChangeListener(report);
picker.setTimeZone(alternative);
TestUtils.assertPropertyChangeEvent(report, "timeZone", timeZone, alternative, false);
}
/**
* Issue #724-swingx: picker must notify about timezone changes.
* Here: setMonthView must update the picker's timezone if different and
* fire a notification.
*/
@Test
public void testTimeZoneSetMonthView() {
JXDatePicker picker = new JXDatePicker();
TimeZone timeZone = picker.getTimeZone();
TimeZone alternative = getSafeAlternativeTimeZone(timeZone);
// prepare a new monthView with different TimeZone
JXMonthView monthView = new JXMonthView();
monthView.setTimeZone(alternative);
PropertyChangeReport report = new PropertyChangeReport();
picker.addPropertyChangeListener(report);
picker.setMonthView(monthView);
TestUtils.assertPropertyChangeEvent(report, "timeZone", timeZone, alternative, false);
report.clear();
TimeZone another = getSafeAlternativeTimeZone(alternative);
monthView.setTimeZone(another);
TestUtils.assertPropertyChangeEvent(report, "timeZone", alternative, another, false);
}
/**
* Issue #568-swingx: picker must respect selection model (as of time fields).
*
* Behaviour defined by selection model of monthView. While the default
* (DaySelectionModel) normalizes the dates to the start of the day in the
* model's calendar coordinates, a SingleDaySelectionModel keeps the date as-is.
* For now, need to explicitly set.
*/
@Test
public void testSetDateKeepsTime() {
JXDatePicker picker = new JXDatePicker();
DateSelectionModel selectionModel = new SingleDaySelectionModel();
picker.getMonthView().setSelectionModel(selectionModel);
Date date = new Date();
selectionModel.setSelectionInterval(date, date);
Date first = selectionModel.getFirstSelectionDate();
assertEquals("formats diff: " + (date.getTime() - first.getTime())
, date, first);
}
/**
* Issue #??-swingx: JXDatePicker must keep monthView's firstDisplayedDate
* in synch with selection/today.
* Issue #705-swingx: JXMonthView must not scroll in layoutContainer.
*
* The implication is that client code (such as JXDatePicker/UI) is
* responsible to do the scrolling.
*/
@Test
public void testVisibleMonthContainsSelectionOpenSet() {
if (GraphicsEnvironment.isHeadless()) {
LOG.fine("cannot run testLinkPanelNull - headless");
return;
}
calendar.set(2008, Calendar.JULY, 15);
JXDatePicker picker = new JXDatePicker();
picker.setDate(calendar.getTime());
JXFrame frame = new JXFrame("showing", false);
frame.add(picker);
frame.pack();
frame.setVisible(true);
Action togglePopup = picker.getActionMap().get("TOGGLE_POPUP");
togglePopup.actionPerformed(null);
CalendarUtils.startOfMonth(calendar);
assertEquals(calendar.getTime(), picker.getMonthView().getFirstDisplayedDay());
frame.dispose();
}
/**
* Issue #??-swingx: JXDatePicker must keep monthView's firstDisplayedDate
* in synch with selection/today.
* Issue #705-swingx: JXMonthView must not scroll in layoutContainer.
*
* The implication is that client code (such as JXDatePicker/UI) is
* responsible to do the scrolling.
*/
@Test
public void testVisibleMonthContainsSelectionOpenInitial() {
if (GraphicsEnvironment.isHeadless()) {
LOG.fine("cannot run testLinkPanelNull - headless");
return;
}
calendar.set(2008, Calendar.JULY, 15);
JXDatePicker picker = new JXDatePicker(calendar.getTime());
JXFrame frame = new JXFrame("showing", false);
frame.add(picker);
frame.setVisible(true);
Action togglePopup = picker.getActionMap().get("TOGGLE_POPUP");
togglePopup.actionPerformed(null);
CalendarUtils.startOfMonth(calendar);
assertEquals(calendar.getTime(), picker.getMonthView().getFirstDisplayedDay());
frame.dispose();
}
/**
* Issue #??-swingx: JXDatePicker must keep monthView's firstDisplayedDate
* in synch with selection/today.
* Issue #705-swingx: JXMonthView must not scroll in layoutContainer.
*
* The implication is that client code (such as JXDatePicker/UI) is
* responsible to do the scrolling.
*/
@Test
public void testVisibleMonthContainsSelectionIinitial() {
calendar.set(2008, Calendar.JULY, 15);
JXDatePicker picker = new JXDatePicker(calendar.getTime());
CalendarUtils.startOfMonth(calendar);
assertEquals(calendar.getTime(), picker.getMonthView().getFirstDisplayedDay());
}
/**
* Issue #??-swingx: JXDatePicker must keep monthView's firstDisplayedDate
* in synch with selection/today.
* Issue #705-swingx: JXMonthView must not scroll in layoutContainer.
*
* The implication is that client code (such as JXDatePicker/UI) is
* responsible to do the scrolling.
*/
@Test
public void testVisibleMonthContainsSelectionSet() {
JXDatePicker picker = new JXDatePicker();
calendar.set(2008, Calendar.JULY, 15);
picker.setDate(calendar.getTime());
CalendarUtils.startOfMonth(calendar);
assertEquals(calendar.getTime(), picker.getMonthView().getFirstDisplayedDay());
}
/**
* Issue #693-swingx: format of custom locale.
* Here: test constructor with locale parameter.
*/
@Test
public void testCustomLocaleConstructor() {
Locale german = Locale.GERMAN;
JXDatePicker picker = new JXDatePicker(german);
SimpleDateFormat format = (SimpleDateFormat) picker.getFormats()[0];
String pattern = UIManagerExt.getString("JXDatePicker.longFormat", german);
assertEquals(pattern , format.toPattern());
}
/**
* Issue #693-swingx: format of custom locale.
* Here: test setLocale.
*/
@Test
public void testCustomLocaleSet() {
Locale german = Locale.GERMAN;
JXDatePicker picker = new JXDatePicker();
picker.setLocale(german);
SimpleDateFormat format = (SimpleDateFormat) picker.getFormats()[0];
String pattern = UIManagerExt.getString("JXDatePicker.longFormat", german);
assertEquals(pattern , format.toPattern());
}
/**
* Issue #690-swingx: custom dateformats lost on switching LF.
*
* Here: default formats re-set.
*/
@Test
public void testDefaultFormats() {
JXDatePicker picker = new JXDatePicker();
DateFormat[] formats = picker.getFormats();
assertEquals(formats.length, picker.getFormats().length);
picker.updateUI();
assertNotSame(formats[0], picker.getFormats()[0]);
}
/**
* Issue #690-swingx: custom dateformats lost on switching LF.
*
* Sanity test: custom format set as expected.
*/
@Test
public void testCustomFormatsSet() {
JXDatePicker picker = new JXDatePicker();
DateFormat format = DateFormat.getDateInstance(DateFormat.MEDIUM,Locale.UK);
picker.setFormats(format);
DateFormat[] formats = picker.getFormats();
// sanity
assertEquals(1, formats.length);
assertSame(format, formats[0]);
}
/**
* Issue #690-swingx: custom dateformats lost on switching LF.
*
* Here: test that custom format is unchanged after updateUI
*/
@Test
public void testCustomFormatsKept() {
JXDatePicker picker = new JXDatePicker();
DateFormat format = DateFormat.getDateInstance(DateFormat.MEDIUM,Locale.UK);
picker.setFormats(format);
picker.updateUI();
DateFormat[] formats = picker.getFormats();
assertEquals(1, formats.length);
assertSame(format, formats[0]);
}
/**
* Issue #542-swingx: NPE in init if linkFormat not set.
*
* After plaf cleanup no longer as virulent as earlier: with
* addResourceBundle, there's always at least the fall-back value in the
* bundle, so as long as the bundle is loaded at all, we have a not-null
* value (and no way to remove which is okay).
*
*/
@Test
public void testLinkFormatStringNull() {
// force loading
new JXDatePicker();
String key = "JXDatePicker.linkFormat";
String oldLinkFormat = UIManagerExt.getString(key);
// sanity: the addon was loaded
assertNotNull(oldLinkFormat);
UIManager.put(key, null);
assertEquals("no null overwrite", oldLinkFormat, UIManagerExt.getString(key));
UIManager.getLookAndFeelDefaults().remove(key);
assertEquals("no remove", oldLinkFormat, UIManagerExt.getString(key));
new JXDatePicker();
}
/**
* Issue #584-swingx: need to clarify null handling.
*
* Forum report: NPE under certain initial conditions.
*
*/
@Test
public void testPickerFormatSetFormats() {
JXDatePicker picker = new JXDatePicker();
picker.setFormats((DateFormat[])null);
}
/**
* Issue #584-swingx: need to clarify null handling.
*
* Forum report: NPE under certain initial conditions.
*
*/
@Test
public void testPickerFormatSetFormatsNullElements() {
JXDatePicker picker = new JXDatePicker();
try {
picker.setFormats(new DateFormat[] { null});
fail("must not accept null elements in format array");
} catch (NullPointerException e) {
// doc'ed behaviour
}
}
/**
* Issue #584-swingx: need to clarify null handling.
*
* Forum report: NPE under certain initial conditions.
*
*/
@Test
public void testPickerFormatSetFormatStrings() {
JXDatePicker picker = new JXDatePicker();
picker.setFormats((String[])null);
}
/**
* Issue #584-swingx: need to clarify null handling.
*
* Forum report: NPE under certain initial conditions.
*
*/
@Test
public void testPickerFormatSetFormatStringsNullElements() {
JXDatePicker picker = new JXDatePicker();
try {
picker.setFormats(new String[] {null});
fail("must not accept null elements in format array");
} catch (NullPointerException e) {
// doc'ed behaviour
}
}
/**
* Issue #584-swingx: need to clarify null handling.
*
* Forum report: NPE under certain initial conditions.
* This produced exactly the stacktrace as reported.
*
*/
@Test
public void testPickerFormatsNotNull() {
JXDatePicker picker = new JXDatePicker();
// trick the picker - no formats
picker.getEditor().setFormatterFactory(new DefaultFormatterFactory(
new DatePickerFormatter((DateFormat[]) null)));
assertNotNull("picker format array must not be null",
picker.getFormats());
}
/**
* Issue #584-swingx: need to clarify null handling.
*
*
*/
@Test
public void testPickerFormatsNotNullUnknownFormatter() {
JXDatePicker picker = new JXDatePicker();
// trick the picker - no formats
picker.getEditor().setFormatterFactory(new DefaultFormatterFactory());
assertNotNull("picker format array must not be null",
picker.getFormats());
}
/**
* Issue #565-swingx: popup not closed when focus moved to Combo
* Issue #573-swingx: datePicker editor not focused on F2 (in table)
*
* testing internals: need focus listener add/remove
*
*/
@Test
public void testFocusListenerOnPicker() {
JXDatePicker picker = new JXDatePicker();
assertEquals(1, picker.getFocusListeners().length);
picker.getUI().uninstallUI(picker);
assertEquals(0, picker.getFocusListeners().length);
}
/**
* Issue #565-swingx: popup not closed when focus moved to Combo
* Issue #573-swingx: datePicker editor not focused on F2 (in table)
*
* testing internals: need focus listener add/remove
*
*/
@Test
public void testFocusListenerOnEditor() {
JFormattedTextField field = new JFormattedTextField(new DatePickerFormatter());
int listenerCount = field.getFocusListeners().length;
JXDatePicker picker = new JXDatePicker();
assertEquals(listenerCount + 1, picker.getEditor().getFocusListeners().length);
picker.getUI().uninstallUI(picker);
assertEquals(listenerCount, picker.getEditor().getFocusListeners().length);
}
/**
* tests LinkPanel set to null after showing.
* Was: NPE.
*/
@Test
public void testLinkPanelSetNull() {
if (GraphicsEnvironment.isHeadless()) {
LOG.fine("cannot run testLinkPanelNull - headless");
return;
}
JXDatePicker picker = new JXDatePicker();
JXFrame frame = new JXFrame("showing", false);
frame.add(picker);
frame.setVisible(true);
Action togglePopup = picker.getActionMap().get("TOGGLE_POPUP");
togglePopup.actionPerformed(null);
picker.setLinkPanel(null);
frame.dispose();
}
/**
* tests initial null linkPanel.
*
*/
@Test
public void testLinkPanelInitalNull() {
if (GraphicsEnvironment.isHeadless()) {
LOG.fine("cannot run testLinkPanelNull - headless");
return;
}
JXDatePicker picker = new JXDatePicker();
picker.setLinkPanel(null);
JXFrame frame = new JXFrame("showing", false);
frame.add(picker);
frame.setVisible(true);
Action togglePopup = picker.getActionMap().get("TOGGLE_POPUP");
togglePopup.actionPerformed(null);
frame.dispose();
}
/**
* Test install/uninstall of LinkPanel when popup is showing.
* - removed/added from parent
* - bindings initially installed/uninstalled/re-installed
*/
@Test
public void testLinkPanelRemovedAdded() {
if (GraphicsEnvironment.isHeadless()) {
LOG.fine("cannot run testLinkPanelNull - headless");
return;
}
JXDatePicker picker = new JXDatePicker();
JXFrame frame = new JXFrame("showing", false);
frame.add(picker);
frame.setVisible(true);
// show the popup ... PENDING: need api on picker.
Action togglePopup = picker.getActionMap().get("TOGGLE_POPUP");
togglePopup.actionPerformed(null);
JPanel linkPanel = picker.getLinkPanel();
// assert the bindings are installed
assertLinkPanelBindings(linkPanel, true);
Container oldParent = linkPanel.getParent();
// sanity
assertNotNull(oldParent);
// remove
picker.setLinkPanel(null);
// assert it is removed
assertNull("linkPanel must be removed", linkPanel.getParent());
// assert bindings removed
assertLinkPanelBindings(linkPanel, false);
// set again
picker.setLinkPanel(linkPanel);
// assert the bindings are installed again
assertLinkPanelBindings(linkPanel, true);
assertSame("linkPanel must be added to same parent",
oldParent, linkPanel.getParent());
frame.dispose();
}
/**
* Tests that the linkPanel bindings and actions
* are removed (no popup)
*
*/
@Test
public void testLinkPanelBindingUninstalled() {
JXDatePicker picker = new JXDatePicker();
JComponent linkPanel = picker.getLinkPanel();
picker.setLinkPanel(null);
assertLinkPanelBindings(linkPanel, false);
}
/**
* Tests that the linkPanel has actions and keybindings
* for homeCommit/-Cancel (initially, no popup)
*
*/
@Test
public void testLinkPanelAction() {
JXDatePicker picker = new JXDatePicker();
JComponent linkPanel = picker.getLinkPanel();
assertLinkPanelBindings(linkPanel, true);
}
/**
* @param linkPanel
*/
private void assertLinkPanelBindings(JComponent linkPanel, boolean bound) {
if (bound) {
assertNotNull("home commit action must be registered",
linkPanel.getActionMap().get(JXDatePicker.HOME_COMMIT_KEY));
assertNotNull("home navigate action must be registered",
linkPanel.getActionMap().get(JXDatePicker.HOME_NAVIGATE_KEY));
} else {
assertNull("home commit action must not be registered",
linkPanel.getActionMap().get(JXDatePicker.HOME_COMMIT_KEY));
assertNull("home navigate action must not be registered",
linkPanel.getActionMap().get(JXDatePicker.HOME_NAVIGATE_KEY));
}
assertKeyBindings(linkPanel, JXDatePicker.HOME_COMMIT_KEY, bound);
assertKeyBindings(linkPanel, JXDatePicker.HOME_NAVIGATE_KEY, bound);
}
/**
* PENDING: move to testUtils.
* @param comp
* @param actionKey
*/
public void assertKeyBindings(JComponent comp, Object actionKey, boolean bound) {
boolean hasAncestorBinding = hasBinding(
comp.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT),
actionKey);
boolean hasFocusedBinding = hasBinding(
comp.getInputMap(JComponent.WHEN_FOCUSED),
actionKey);
boolean hasInFocusedBinding = hasBinding(
comp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW),
actionKey);
boolean hasBinding = hasAncestorBinding || hasFocusedBinding || hasInFocusedBinding;
assertEquals("component has keybinding for " + actionKey,
bound,
hasBinding);
}
/**
*
* PENDING: move to testutils.
* @param map
* @param actionKey
*/
public boolean hasBinding(InputMap map, Object actionKey) {
KeyStroke[] keyStrokes = map.keys();
if (keyStrokes != null) {
for (KeyStroke stroke : keyStrokes) {
if (actionKey.equals(map.get(stroke))) {
return true;
}
}
}
return false;
}
/**
* test that the toggle popup is registered in the
* picker's actionMap.
*
* Issue #596-swingx: don't use space to open popup.
*/
@Test
public void testTogglePopupAction() {
JXDatePicker picker = new JXDatePicker();
Action togglePopup = picker.getActionMap().get("TOGGLE_POPUP");
assertNotNull(togglePopup);
KeyStroke space = KeyStroke.getKeyStroke("alt DOWN");
Object actionKey = picker.getInputMap(
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
.get(space);
assertEquals(actionKey, "TOGGLE_POPUP");
}
/**
* Characterization: when does picker fire action events?
*
* Test that set date programmatically (directly or indirectly)
* does not fire an actionEvent.
*/
@Test
public void testSetDateSilently() {
JXDatePicker picker = new JXDatePicker();
ActionReport report = new ActionReport();
picker.addActionListener(report);
// via editor
Date value = XTestUtils.getStartOfToday(3);
picker.getEditor().setValue(value);
assertEquals(value, picker.getDate());
// via selection
Date selected = XTestUtils.getStartOfToday(4);
picker.getMonthView().setSelectionInterval(selected, selected);
assertEquals(selected, picker.getDate());
Date date = XTestUtils.getStartOfToday(5);
// directly
picker.setDate(date);
assertEquals(date, picker.getDate());
assertEquals(0, report.getEventCount());
}
/**
* Enhanced commit/cancel.
*
* test the cancel produced by the monthview trigger
* cancel in the picker.
*
*/
@Test
public void testCommitCancelFromMonthViewCancel() {
JXDatePicker picker = new JXDatePicker();
final ActionReport report = new ActionReport();
picker.addActionListener(report);
Action cancelAction = picker.getMonthView().getActionMap().get(JXMonthView.CANCEL_KEY);
cancelAction.actionPerformed(null);
assertEquals("must have receive 1 event after monthView cancel",
1, report.getEventCount());
assertEquals(JXDatePicker.CANCEL_KEY, report.getLastActionCommand());
}
/**
* Enhanced commit/cancel.
*
* test the commit produced by the monthview trigger
* commit in the picker.
*
*/
@Test
public void testCommitCancelFromMonthViewCommit() {
JXDatePicker picker = new JXDatePicker();
Action commitAction = picker.getMonthView().getActionMap().get(JXMonthView.COMMIT_KEY);
final ActionReport report = new ActionReport();
picker.addActionListener(report);
commitAction.actionPerformed(null);
assertEquals("must have receive 1 event after monthView commit",
1, report.getEventCount());
assertEquals(JXDatePicker.COMMIT_KEY, report.getLastActionCommand());
}
/**
* Enhanced commit/cancel.
*
* test that the ui installed a listener.
*/
@Test
public void testCommitCancelListeningToMonthView() {
JXMonthView monthView = new JXMonthView();
int standalone = monthView.getListeners(ActionListener.class).length;
assertEquals(0, standalone);
JXDatePicker picker = new JXDatePicker();
int contained = picker.getMonthView().getListeners(ActionListener.class).length;
assertEquals(standalone + 1, contained);
}
/**
* test wrapping and resetting the editors cancel action.
* internals ... mostly to be sure about cleanup and re-wire.
*/
@Test
public void testCancelEditorAction() {
JFormattedTextField field = new JFormattedTextField(new DatePickerFormatter());
// original action
Action original = field.getActionMap().get(EditorCancelAction.TEXT_CANCEL_KEY);
assertNotNull(original);
JXDatePicker picker = new JXDatePicker();
JFormattedTextField editor = picker.getEditor();
Action wrapper = editor.getActionMap().get(EditorCancelAction.TEXT_CANCEL_KEY);
// wrapper installed
assertTrue("PickerUI installed the wrapper action", wrapper instanceof EditorCancelAction);
// set editor to field
picker.setEditor(field);
// old editor back to original
assertSame("original action must be reset on setEditor", original,
editor.getActionMap().get(EditorCancelAction.TEXT_CANCEL_KEY));
Action otherWrapper = field.getActionMap().get(EditorCancelAction.TEXT_CANCEL_KEY);
assertTrue(otherWrapper instanceof EditorCancelAction);
// created a new one
assertNotSame(wrapper, otherWrapper);
// uninstall
picker.getUI().uninstallUI(picker);
assertSame("original action must be reset on uninstall", original,
field.getActionMap().get(EditorCancelAction.TEXT_CANCEL_KEY));
}
/**
* Enhanced commit/cancel.
*
* test that cancel action reverts silently: date related
* state unchanged and no events fired (except the actionEvent).
*
*/
@Test
public void testCancelEditRevertsSilently() {
JXDatePicker picker = new JXDatePicker(new Date());
String text = picker.getEditor().getText();
// manipulate the text, not entirely safe ...
String changed = text.replace('0', '1');
picker.getEditor().setText(changed);
final ActionReport actionReport = new ActionReport();
picker.addActionListener(actionReport);
picker.getEditor().addActionListener(actionReport);
picker.getMonthView().addActionListener(actionReport);
final PropertyChangeReport propertyReport = new PropertyChangeReport();
picker.addPropertyChangeListener(propertyReport);
picker.getEditor().addPropertyChangeListener(propertyReport);
picker.cancelEdit();
assertEquals(0, propertyReport.getEventCount());
assertEquals(1, actionReport.getEventCount());
}
/**
* Enhanced commit/cancel.
*
* test that cancel fires as expected.
* PENDING: need to invoke ... safe test?
*
*/
@Test
public void testCommitCancelActionsFireCancel() {
JXDatePicker picker = new JXDatePicker();
final ActionReport report = new ActionReport();
picker.addActionListener(report);
Action cancelAction = picker.getActionMap().get(JXDatePicker.CANCEL_KEY);
cancelAction.actionPerformed(null);
assertEquals(1, report.getEventCount());
assertEquals(JXDatePicker.CANCEL_KEY, report.getLastActionCommand());
}
/**
* Enhanced commit/cancel.
*
* test that commit fires as expected.
* PENDING: need to invoke ... safe test?
*/
@Test
public void testCommitCancelActionsFireCommit() {
JXDatePicker picker = new JXDatePicker();
Action commitAction = picker.getActionMap().get(JXDatePicker.COMMIT_KEY);
final ActionReport report = new ActionReport();
picker.addActionListener(report);
commitAction.actionPerformed(null);
assertEquals(1, report.getEventCount());
assertEquals(JXDatePicker.COMMIT_KEY, report.getLastActionCommand());
}
/**
* Enhanced commit/cancel.
*
* test that actions are registered.
*
*/
@Test
public void testCommitCancelActionExist() {
JXDatePicker picker = new JXDatePicker();
assertNotNull(picker.getActionMap().get(JXDatePicker.CANCEL_KEY));
assertNotNull(picker.getActionMap().get(JXDatePicker.COMMIT_KEY));
}
/**
* Issue #658-swingx: timezone in linkformat updated.
*
* linkDate synced with monthView's today after setting.
*/
@Test
public void testLinkDateSetToday() {
JXDatePicker picker = new JXDatePicker();
Calendar cal = picker.getMonthView().getCalendar();
cal.setTime(picker.getMonthView().getToday());
cal.add(Calendar.MONTH, 1);
CalendarUtils.endOfDay(cal);
// NOTE: no public api, testing to guarantee the synch in all cases
picker.getMonthView().setToday(cal.getTime());
assertEquals(picker.getMonthView().getToday(), picker.getLinkDay());
}
/**
* Issue #658-swingx: timezone in linkformat updated.
*
* Initial linkDate synced with monthView's today.
*/
@Test
public void testLinkDateInitial() {
JXDatePicker picker = new JXDatePicker();
assertEquals(picker.getMonthView().getToday(), picker.getLinkDay());
}
/**
* Issue #658-swingx: timezone in linkformat updated.
*
* Here: set timezone in picker.
*/
@Test
public void testSynchTimeZoneLinkFormatOnModified() {
JXDatePicker picker = new JXDatePicker();
TimeZone alternative = getSafeAlternativeTimeZone(picker.getTimeZone());
picker.setTimeZone(alternative);
assertTimeZoneLinkFormat(picker, alternative);
}
/**
* Issue #554-swingx: timezone of formats and picker must be synched.
* Here: set monthView with alternative timezone
*/
@Test
public void testSynchTimeZoneLinkFormatOnSetMonthView() {
JXDatePicker picker = new JXDatePicker();
TimeZone defaultZone = picker.getTimeZone();
TimeZone alternative = getSafeAlternativeTimeZone(defaultZone);
JXMonthView monthView = new JXMonthView();
monthView.setTimeZone(alternative);
picker.setMonthView(monthView);
assertTimeZoneLinkFormat(picker, alternative);
}
/**
* Assert that all DateFormats in the picker's linkFormat have the same
* timezone as the picker.
*
* @param picker the JXDatePicker to test
* @param alternative the expected timeZone of the picker (for sanity only)
*/
private void assertTimeZoneLinkFormat(JXDatePicker picker,
TimeZone alternative) {
// sanity: picker has timezone as expected
assertEquals("expected timezone in picker", alternative, picker.getTimeZone());
MessageFormat format = picker.getLinkFormat();
for (Format subFormat : format.getFormats()) {
if (subFormat instanceof DateFormat) {
assertEquals(picker.getTimeZone(), ((DateFormat) subFormat).getTimeZone());
}
}
}
/**
* Issue #554-swingx: timezone of formats and picker must be synched.
* Here: set the timezone in the monthView.
*/
@Test
public void testSynchTimeZoneModifiedInMonthView() {
JXDatePicker picker = new JXDatePicker();
TimeZone defaultZone = picker.getTimeZone();
TimeZone alternative = getSafeAlternativeTimeZone(defaultZone);
picker.getMonthView().setTimeZone(alternative);
assertTimeZoneDateFormats(picker, alternative);
}
/**
* Issue #554-swingx: timezone of formats and picker must be synched.
*
* Here: set the timezone in the picker.
*/
@Test
public void testSynchTimeZoneModifiedInPicker() {
JXDatePicker picker = new JXDatePicker();
TimeZone defaultZone = picker.getTimeZone();
TimeZone alternative = getSafeAlternativeTimeZone(defaultZone);
picker.setTimeZone(alternative);
assertTimeZoneDateFormats(picker, alternative);
}
/**
* Issue #554-swingx: timezone of formats and picker must be synched.
* Here: set the timezone in the picker.
*/
@Test
public void testSynchTimeZoneOnSetMonthView() {
JXDatePicker picker = new JXDatePicker();
TimeZone defaultZone = picker.getTimeZone();
TimeZone alternative = getSafeAlternativeTimeZone(defaultZone);
JXMonthView monthView = new JXMonthView();
monthView.setTimeZone(alternative);
picker.setMonthView(monthView);
assertTimeZoneDateFormats(picker, alternative);
}
/**
* Issue #554-swingx: timezone of formats and picker must be synched.
*
* Here: initialize the formats with the pickers timezone on setting.
*/
@Test
public void testSynchTimeZoneOnSetFormats() {
JXDatePicker picker = new JXDatePicker();
TimeZone defaultZone = picker.getTimeZone();
TimeZone alternative = getSafeAlternativeTimeZone(defaultZone);
picker.setTimeZone(alternative);
picker.setFormats(DateFormat.getDateInstance());
assertTimeZoneDateFormats(picker, alternative);
}
/**
* Assert that all DateFormats in the picker's linkFormat have the same
* timezone as the picker.
*
* @param picker the JXDatePicker to test
* @param alternative the expected timeZone of the picker (for sanity only)
*/
private void assertTimeZoneDateFormats(JXDatePicker picker,
TimeZone alternative) {
assertEquals(alternative, picker.getTimeZone());
for (DateFormat format : picker.getFormats()) {
assertEquals("timezone must be synched", picker.getTimeZone(), format.getTimeZone());
}
}
/**
* Issue #554-swingx: timezone of formats and picker must be synched.
*/
@Test
public void testSynchTimeZoneInitial() {
JXDatePicker picker = new JXDatePicker();
assertNotNull(picker.getTimeZone());
for (DateFormat format : picker.getFormats()) {
assertEquals("timezone must be synched", picker.getTimeZone(), format.getTimeZone());
}
}
/**
* setFormats should fire a propertyChange.
*
*/
@Test
public void testFormatsProperty() {
JXDatePicker picker = new JXDatePicker();
PropertyChangeReport report = new PropertyChangeReport();
picker.addPropertyChangeListener(report);
DateFormat[] oldFormats = picker.getFormats();
DateFormat[] newFormats = new DateFormat[] {DateFormat.getDateInstance()};
picker.setFormats(newFormats);
TestUtils.assertPropertyChangeEvent(report, "formats", oldFormats, newFormats);
}
/**
* Test doc'ed behaviour: editor must not be null.
*/
@Test
public void testEditorNull() {
JXDatePicker picker = new JXDatePicker();
assertNotNull(picker.getEditor());
try {
picker.setEditor(null);
fail("picker must throw NPE if editor is null");
} catch (NullPointerException e) {
// nothing to do - doc'ed behaviour
}
}
/**
* Test doc'ed behaviour: editor must not be null.
*/
@Test
public void testMonthViewNull() {
JXDatePicker picker = new JXDatePicker();
assertNotNull(picker.getMonthView());
try {
picker.setMonthView(null);
fail("picker must throw NPE if monthView is null");
} catch (NullPointerException e) {
// nothing to do - doc'ed behaviour
}
}
/**
* picker has cleaned date, clarified doc.
* The test is not exactly true, the details
* are up for the DatePickerUI to decide.
*
*/
@Test
public void testSetDateCleansDate() {
JXDatePicker picker = new JXDatePicker();
Date date = calendar.getTime();
picker.setDate(date);
assertEquals(CalendarUtils.startOfDay(calendar, date), picker.getDate());
}
/**
* Regression testing: make sure the passed-in date is not changed.
*
*/
@Test
public void testSetDateDoesNotChangeOriginal() {
JXDatePicker picker = new JXDatePicker();
Date date = calendar.getTime();
Date copy = new Date(date.getTime());
picker.setDate(date);
assertEquals(copy, date);
}
/**
* date is a bound property of DatePicker.
*/
@Test
public void testDateProperty() {
JXDatePicker picker = new JXDatePicker();
Date date = XTestUtils.getStartOfToday(5);
PropertyChangeReport report = new PropertyChangeReport();
picker.addPropertyChangeListener("date", report);
picker.setDate(date);
TestUtils.assertPropertyChangeEvent(report, "date", null, date);
}
/**
* date is a bound property of DatePicker.
* test indirect event firing: changed editor value
*/
@Test
public void testDatePropertyThroughEditor() {
JXDatePicker picker = new JXDatePicker();
Date date = XTestUtils.getStartOfToday(5);
PropertyChangeReport report = new PropertyChangeReport();
picker.addPropertyChangeListener("date", report);
picker.getEditor().setValue(date);
TestUtils.assertPropertyChangeEvent(report, "date", null, date);
}
/**
* date is a bound property of DatePicker.
* test indirect event firing: changed monthView selection
*/
@Test
public void testDatePropertyThroughSelection() {
JXDatePicker picker = new JXDatePicker();
Date date = XTestUtils.getStartOfToday(5);
PropertyChangeReport report = new PropertyChangeReport();
picker.addPropertyChangeListener("date", report);
picker.getMonthView().setSelectionInterval(date, date);
TestUtils.assertPropertyChangeEvent(report, "date", null, date);
}
/**
* date is a bound property of DatePicker.
* test indirect event firing: commit edited value
* @throws ParseException
*
*/
@Test
public void testDatePropertyThroughCommit() throws ParseException {
JXDatePicker picker = new JXDatePicker(new Date());
Date initialDate = picker.getDate();
String text = picker.getEditor().getText();
Format[] formats = picker.getFormats();
assertEquals(picker.getDate(), formats[0].parseObject(text));
// manipulate the text, not entirely safe ...
String changed = text.replace('0', '1');
picker.getEditor().setText(changed);
Date date;
try {
date = (Date) formats[0].parseObject(changed);
} catch (ParseException e) {
LOG.info("cannot run DatePropertyThroughCommit - parseException in manipulated text");
return;
}
// sanity ...
assertFalse("", date.equals(picker.getDate()));
PropertyChangeReport report = new PropertyChangeReport();
picker.addPropertyChangeListener("date", report);
picker.commitEdit();
TestUtils.assertPropertyChangeEvent(report, "date", initialDate, date);
}
/**
* last piece: removed synch control from picker.commit.
* @throws ParseException
*
*/
@Test
public void testSynchAllAfterCommit() throws ParseException {
JXDatePicker picker = new JXDatePicker(new Date());
String text = picker.getEditor().getText();
Format[] formats = picker.getFormats();
assertEquals(picker.getDate(), formats[0].parseObject(text));
// manipulate the text, not entirely safe ...
String changed = text.replace('0', '1');
picker.getEditor().setText(changed);
Date date;
try {
date = (Date) formats[0].parseObject(changed);
} catch (ParseException e) {
LOG.info("cannot run testSynchAllAfterCommit - parseException in manipulated text");
return;
}
// sanity ...
assertFalse("", date.equals(picker.getDate()));
picker.commitEdit();
assertSynchAll(picker, date);
}
/**
* Issue #559-swingX: date must be synched in all parts.
* here: initial.
*
*/
@Test
public void testSynchAllInitialDate() {
Date date = XTestUtils.getStartOfToday(5);
JXDatePicker picker = new JXDatePicker(date);
assertSynchAll(picker, date);
}
/**
* Issue #559-swingX: date must be synched in all parts.
* here: set date in picker
*
* Note: test uses a cleaned date, do same with uncleaned.
*/
@Test
public void testSynchAllOnDateModified() {
JXDatePicker picker = new JXDatePicker();
Date date = XTestUtils.getStartOfToday(5);
picker.setDate(date);
assertSynchAll(picker, date);
}
/**
* Issue #559-swingX: date must be synched in all parts.
* here: set selected date in monthview
* Note: test uses a cleaned date, do same with uncleaned.
*/
@Test
public void testSynchAllOnSelectionChange() {
JXDatePicker picker = new JXDatePicker();
Date date = XTestUtils.getStartOfToday(5);
picker.getMonthView().setSelectionInterval(date, date);
assertSynchAll(picker, date);
}
/**
* Issue #559-swingX: date must be synched in all parts.
* here: set value in editor.
*
* Note: test uses a cleaned date, do same with uncleaned.
*/
@Test
public void testSynchAllOnEditorSetValue() {
JXDatePicker picker = new JXDatePicker();
Date date = XTestUtils.getStartOfToday(5);
picker.getEditor().setValue(date);
assertSynchAll(picker, date);
}
/**
* Issue #559-swingX: date must be synched in all parts.
* here: modify value must work after changing the editor.
*
* Note: this started to fail during listener cleanup.
*/
@Test
public void testSynchAllOnEditorSetValueAfterSetEditor() {
JXDatePicker picker = new JXDatePicker();
picker.setEditor(new JFormattedTextField(DateFormat.getInstance()));
Date date = XTestUtils.getStartOfToday(5);
picker.getEditor().setValue(date);
assertSynchAll(picker, date);
}
/**
* Issue #559-swingX: date must be synched in all parts.
* here: set selection must work after changing the monthView.
*
* Note: this started to fail during listener cleanup.
*/
@Test
public void testSynchAllOnSelectionChangeAfterSetMonthView() {
JXDatePicker picker = new JXDatePicker();
picker.setMonthView(new JXMonthView());
Date date = XTestUtils.getStartOfToday(5);
picker.getMonthView().setSelectionInterval(date, date);
assertSynchAll(picker, date);
}
/**
* Issue #559-swingX: date must be synched in all parts.
* <p>
*
* here: set selection must work after changing the monthView's selection
* model.
*
* Note: this started to fail during listener cleanup.
*/
@Test
public void testSynchAllOnSelectionChangeAfterSetSelectionModel() {
JXDatePicker picker = new JXDatePicker();
picker.getMonthView().setSelectionModel(new DefaultDateSelectionModel());
Date date = XTestUtils.getStartOfToday(5);
picker.getMonthView().setSelectionInterval(date, date);
assertSynchAll(picker, date);
}
/**
* Asserts that all date related values in the picker are synched.
*
* @param picker the picker to
* @param date the common date
*/
private void assertSynchAll(JXDatePicker picker, Date date) {
assertEquals(date, picker.getEditor().getValue());
assertEquals(date, picker.getDate());
assertEquals(date, picker.getMonthView().getSelectionDate());
// @KEEP JW - currently unused, not yet sure if it's the right place
// for checking against ripples produced by fixing #705-swingx
Calendar cal = picker.getMonthView().getCalendar();
if (date == null) {
cal.setTime(picker.getLinkDay());
CalendarUtils.startOfMonth(cal);
} else {
cal.setTime(date);
CalendarUtils.startOfMonth(cal);
}
assertEquals(cal.getTime(), picker.getMonthView().getFirstDisplayedDay());
}
/**
* test that input of unselectable dates reverts editors value.
*/
@Test
public void testRejectSetValueUnselectable() {
JXDatePicker picker = new JXDatePicker();
Date upperBound = XTestUtils.getStartOfToday(1);
picker.getMonthView().setUpperBound(upperBound);
Date future = XTestUtils.getStartOfToday(2);
// sanity
assertTrue(picker.getMonthView().isUnselectableDate(future));
Date current = picker.getDate();
// sanity:
assertEquals(current, picker.getEditor().getValue());
// set the editors value to something invalid
picker.getEditor().setValue(future);
// ui must not allow an invalid value in the editor
assertEquals(current, picker.getEditor().getValue());
// okay ..
assertEquals(current, picker.getDate());
}
/**
* PickerUI listened to editable (meant: datePicker) and resets
* the editors property. Accidentally? Even if meant to, it's
* brittle because done during the notification.
* Changed to use dedicated listener.
*/
@Test
public void testSpuriousEditableListening() {
JXDatePicker picker = new JXDatePicker();
picker.getEditor().setEditable(false);
// sanity - that at least the other views are uneffected
assertTrue(picker.isEditable());
assertTrue(picker.getMonthView().isEnabled());
assertFalse("Do not change the state of the sender during notification processing",
picker.getEditor().isEditable());
}
/**
* PickerUI listened to enabled of button (meant: datePicker) and resets
* the buttons property.
*/
@Test
public void testSpuriousEnabledListening() {
JXDatePicker picker = new JXDatePicker();
Component button = null;
for (int i = 0; i < picker.getComponentCount(); i++) {
if (picker.getComponent(i) instanceof JButton) {
button = picker.getComponent(i);
}
}
if (button == null) {
LOG.info("cannot run testEnabledListening - no button found");
return;
}
button.setEnabled(false);
// sanity - that at least the other views are uneffected
assertTrue(picker.isEnabled());
assertTrue(picker.getEditor().isEnabled());
assertFalse("Do not change the state of the sender during notification processing",
button.isEnabled());
}
/**
* Sanity during revision: be sure we don't loose the
* ui listening to picker property changes.
*
*/
@Test
public void testDatePickerPropertyListening() {
JXDatePicker picker = new JXDatePicker();
picker.setEnabled(false);
assertFalse(picker.getEditor().isEnabled());
picker.setEditable(false);
assertFalse(picker.getEditor().isEditable());
picker.setToolTipText("dummy");
assertEquals("dummy", picker.getEditor().getToolTipText());
}
/**
* Issue ??-swingx: uninstallUI does not release propertyChangeListener
* to editor. Reason is that the de-install was not done in
* uninstallListeners but later in uninstallComponents - at that time
* the handler is already nulled, removing will actually create a new one.
*/
@Test
public void testEditorListeners() {
JFormattedTextField field = new JFormattedTextField(DateFormat.getInstance());
JXDatePicker picker = new JXDatePicker();
int defaultListenerCount = field.getPropertyChangeListeners().length;
// sanity: we added one listener ...
assertEquals(defaultListenerCount + 1,
picker.getEditor().getPropertyChangeListeners().length);
picker.getUI().uninstallUI(picker);
assertEquals("the ui installe listener must be removed",
defaultListenerCount,
// right now we can access the editor even after uninstall
// because the picker keeps a reference
// TODO: after cleanup, this will be done through the ui
picker.getEditor().getPropertyChangeListeners().length);
}
/**
* Issue #551-swingX: editor value not updated after setMonthView.
*
* quick&dirty fix: let the picker manually update.
*
*/
@Test
public void testEditorValueOnSetMonthView() {
JXDatePicker picker = new JXDatePicker(new Date());
// set unselected monthView
picker.setMonthView(new JXMonthView());
// sanity: picker takes it
assertNull(picker.getDate());
assertEquals(picker.getDate(), picker.getEditor().getValue());
}
/**
* Issue #551-swingx: editor value not updated after setEditor.
*
* quick&dirty fix: let the picker manually update.
*
* who should set it? ui-delegate when listening to editor property change?
* or picker in setEditor?
*
* Compare to JComboBox: BasicComboUI listens to editor change, does internal
* wiring to editor and call's comboBox configureEditor with the value of the
* old editor.
*
*
*/
@Test
public void testEditorValueOnSetEditor() {
JXDatePicker picker = new JXDatePicker();
Object value = picker.getEditor().getValue();
picker.setEditor(new JFormattedTextField(new DatePickerFormatter()));
assertEquals(value, picker.getEditor().getValue());
}
/**
* Issue #551-swingx: editor value must preserve value on LF switch.
*
* This is a side-effect of picker not updating the editor's value
* on setEditor.
*
* @see #testEditorValueOnSetEditor
*/
@Test
public void testEditorUpdateOnLF() {
JXDatePicker picker = new JXDatePicker();
Object date = picker.getEditor().getValue();
picker.updateUI();
assertEquals(date, picker.getEditor().getValue());
}
@Test
public void testEditorUIResource() {
JXDatePicker picker = new JXDatePicker();
// this is safe: ui must install an editor and it must be of type UIResource
assertEquals("default editor is UIResource ", true, picker.getEditor() instanceof UIResource);
JFormattedTextField editor = new JFormattedTextField();
picker.setEditor(editor);
assertEquals("sanity: custom editor not UIResource ", false, picker.getEditor() instanceof UIResource);
picker.updateUI();
assertSame("updateUI must not touch custom editor", editor, picker.getEditor());
}
/**
* Characterization: setting the monthview's selection model updates
* the datePicker's date to the monthView's current
* selection.
*
* Here: model with selection.
*
*/
@Test
public void testSynchAllAfterSetSelectionModelNotEmpty() {
JXDatePicker picker = new JXDatePicker();
Date date = XTestUtils.getStartOfToday(5);
DateSelectionModel model = new DefaultDateSelectionModel();
model.setSelectionInterval(date, date);
// sanity
assertFalse(date.equals(picker.getDate()));
picker.getMonthView().setSelectionModel(model);
assertSynchAll(picker, date);
}
/**
* Characterization: setting the monthview's selection model updates
* the datePicker's date to the monthView's current
* selection.
*
* Here: model with empty selection.
*
*/
@Test
public void testSynchAllAfterSetSelectionModelEmpty() {
JXDatePicker picker = new JXDatePicker(new Date());
assertNotNull(picker.getDate());
DateSelectionModel model = new DefaultDateSelectionModel();
assertTrue(model.isSelectionEmpty());
picker.getMonthView().setSelectionModel(model);
assertSynchAll(picker, null);
}
/**
* Characterization: setting the monthview updates
* the datePicker's date to the monthView's current
* selection.
* Here: monthview with selection.
*
*/
@Test
public void testSynchAllSetMonthViewWithSelection() {
JXDatePicker picker = new JXDatePicker();
JXMonthView monthView = new JXMonthView();
Date date = XTestUtils.getStartOfToday(5);
monthView.setSelectionInterval(date, date);
// sanity
assertFalse(date.equals(picker.getDate()));
picker.setMonthView(monthView);
assertSynchAll(picker, date);
}
/**
* Characterization: setting the monthview updates
* the datePicker's date to the monthView's current
* selection.
* Here: monthview with empty selection.
*
*/
@Test
public void testSynchAllSetMonthViewWithEmptySelection() {
JXDatePicker picker = new JXDatePicker(new Date());
// sanity
assertNotNull(picker.getDate());
JXMonthView monthView = new JXMonthView();
Date selectedDate = monthView.getSelectionDate();
assertNull(selectedDate);
picker.setMonthView(monthView);
assertSynchAll(picker, selectedDate);
}
/**
* PrefSize should be independent of empty/filled picker.
* If not, the initial size might appear kind of collapsed.
*
*/
@Test
public void testPrefSizeEmptyEditor() {
JXDatePicker picker = new JXDatePicker(new Date());
// sanity
assertNotNull(picker.getDate());
Dimension filled = picker.getPreferredSize();
picker.setDate(null);
Dimension empty = picker.getPreferredSize();
assertEquals("pref width must be same for empty/filled", filled.width, empty.width);
}
@Test
public void testDefaultConstructor() {
JXDatePicker datePicker = new JXDatePicker();
assertNull(datePicker.getDate());
}
@Test
public void testConstructor() {
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.DAY_OF_MONTH, 5);
Date expectedDate = cleanupDate(calendar);
JXDatePicker datePicker = new JXDatePicker(calendar.getTime());
assertTrue(expectedDate.equals(datePicker.getDate()));
}
@Test
public void testNullSelection() {
JXDatePicker datePicker = new JXDatePicker();
assertTrue(null == datePicker.getDate());
}
@Test
public void testSetDate() {
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.DAY_OF_MONTH, 5);
Date expectedDate = cleanupDate(calendar);
JXDatePicker datePicker = new JXDatePicker();
datePicker.setDate(calendar.getTime());
assertTrue(expectedDate.equals(datePicker.getDate()));
assertTrue(expectedDate.equals(datePicker.getEditor().getValue()));
datePicker.setDate(null);
assertTrue(null == datePicker.getDate());
assertTrue(null == datePicker.getEditor().getValue());
}
//------------------ test helpers
/**
* Returns a timezone different from the given.
* @param defaultZone
* @return
*/
private TimeZone getSafeAlternativeTimeZone(TimeZone defaultZone) {
TimeZone alternative = TimeZone.getTimeZone("GMT-6");
// sanity
assertNotNull(alternative);
if (alternative.equals(defaultZone)) {
alternative = TimeZone.getTimeZone("GMT-7");
// paranoid ... but shit happens
assertNotNull(alternative);
assertFalse(alternative.equals(defaultZone));
}
return alternative;
}
private Date cleanupDate(Calendar cal) {
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/src/groovy/org/pillarone/riskanalytics/domain/pc/reinsurance/contracts/MultiCompanyCoverAttributeReinsuranceContract.java b/src/groovy/org/pillarone/riskanalytics/domain/pc/reinsurance/contracts/MultiCompanyCoverAttributeReinsuranceContract.java
index 0315e24..d94b708 100644
--- a/src/groovy/org/pillarone/riskanalytics/domain/pc/reinsurance/contracts/MultiCompanyCoverAttributeReinsuranceContract.java
+++ b/src/groovy/org/pillarone/riskanalytics/domain/pc/reinsurance/contracts/MultiCompanyCoverAttributeReinsuranceContract.java
@@ -1,239 +1,232 @@
package org.pillarone.riskanalytics.domain.pc.reinsurance.contracts;
import org.apache.commons.lang.ArrayUtils;
import org.pillarone.riskanalytics.core.packets.PacketList;
import org.pillarone.riskanalytics.core.parameterization.ConstrainedMultiDimensionalParameter;
import org.pillarone.riskanalytics.core.parameterization.ConstraintsFactory;
import org.pillarone.riskanalytics.core.simulation.engine.SimulationScope;
import org.pillarone.riskanalytics.core.util.GroovyUtils;
import org.pillarone.riskanalytics.domain.pc.claims.Claim;
import org.pillarone.riskanalytics.domain.pc.claims.ClaimFilterUtilities;
import org.pillarone.riskanalytics.domain.pc.claims.ClaimUtilities;
import org.pillarone.riskanalytics.domain.pc.claims.SortClaimsByFractionOfPeriod;
import org.pillarone.riskanalytics.domain.pc.company.ICompanyMarker;
import org.pillarone.riskanalytics.domain.pc.constants.IncludeType;
import org.pillarone.riskanalytics.domain.pc.constants.LogicArguments;
import org.pillarone.riskanalytics.domain.pc.constants.ReinsuranceContractBase;
import org.pillarone.riskanalytics.domain.pc.constraints.CompanyPortion;
import org.pillarone.riskanalytics.domain.pc.creditrisk.ReinsurerDefault;
import org.pillarone.riskanalytics.domain.pc.generators.claims.PerilMarker;
import org.pillarone.riskanalytics.domain.pc.lob.LobMarker;
import org.pillarone.riskanalytics.domain.pc.reinsurance.ReinsuranceResultWithCommissionPacket;
import org.pillarone.riskanalytics.domain.pc.reinsurance.contracts.cover.*;
import org.pillarone.riskanalytics.domain.pc.reserves.IReserveMarker;
import org.pillarone.riskanalytics.domain.pc.reserves.fasttrack.ClaimDevelopmentLeanPacket;
import org.pillarone.riskanalytics.domain.pc.underwriting.UnderwritingFilterUtilities;
import org.pillarone.riskanalytics.domain.pc.underwriting.UnderwritingInfo;
import org.pillarone.riskanalytics.domain.pc.underwriting.UnderwritingInfoUtilities;
import org.pillarone.riskanalytics.domain.utils.InputFormatConverter;
import java.util.*;
/**
* This reinsurance contract allows to specify the portions covered by each reinsurer. Furthermore it considers if
* a specific reinsurer has gone default and reduces the cover correspondingly.
*
* @author stefan.kunz (at) intuitive-collaboration (dot) com
*/
public class MultiCompanyCoverAttributeReinsuranceContract extends ReinsuranceContract {
private SimulationScope simulationScope;
private ReinsuranceContractBase parmBasedOn = ReinsuranceContractBase.NET;
private ICoverAttributeStrategy parmCover = CompanyCoverAttributeStrategyType.getStrategy(
CompanyCoverAttributeStrategyType.ALL, ArrayUtils.toMap(new Object[][]{{"reserves", IncludeType.NOTINCLUDED}}));
private PacketList<Claim> outFilteredClaims = new PacketList<Claim>(Claim.class);
private PacketList<UnderwritingInfo> outFilteredUnderwritingInfo = new PacketList<UnderwritingInfo>(UnderwritingInfo.class);
private PacketList<ReinsurerDefault> inReinsurersDefault = new PacketList<ReinsurerDefault>(ReinsurerDefault.class);
private ConstrainedMultiDimensionalParameter parmReinsurers = new ConstrainedMultiDimensionalParameter(
GroovyUtils.convertToListOfList(new Object[]{"", 1d}),
- Arrays.asList(getReinsurer(), getPortion()),
+ Arrays.asList(REINSURER, PORTION),
ConstraintsFactory.getConstraints(CompanyPortion.IDENTIFIER));
private static final String REINSURER = "Reinsurer";
private static final String PORTION = "Covered Portion";
/**
* Evaluate the received default information and adjust the coveredByReinsurer factor accordingly
* before applying the contract.
*/
@Override
public void doCalculation() {
if (parmContractStrategy == null) {
throw new IllegalStateException("MultiCompanyCoverAttributeReinsuranceContract.missingContractStrategy");
}
if (parmCover == null) {
throw new IllegalStateException("MultiCompanyCoverAttributeReinsuranceContract.missingCoverStrategy");
}
Map<String, Double> reinsurersDefault = new HashMap<String, Double>(inReinsurersDefault.size());
for (ReinsurerDefault reinsurerDefault : inReinsurersDefault) {
reinsurersDefault.put(reinsurerDefault.getReinsurer(), reinsurerDefault.isDefaultOccurred() ? 0d : 1d);
}
double coveredByReinsurers = 0d;
for (int row = parmReinsurers.getTitleRowCount(); row < parmReinsurers.getRowCount(); row++) {
- double portion = InputFormatConverter.getDouble(parmReinsurers.getValueAt(row, parmReinsurers.getColumnIndex(getPortion())));
- String reinsurer = InputFormatConverter.getString(parmReinsurers.getValueAt(row, parmReinsurers.getColumnIndex(getReinsurer())));
+ double portion = InputFormatConverter.getDouble(parmReinsurers.getValueAt(row, parmReinsurers.getColumnIndex(PORTION)));
+ String reinsurer = InputFormatConverter.getString(parmReinsurers.getValueAt(row, parmReinsurers.getColumnIndex(REINSURER)));
double reinsurerDefault = reinsurersDefault.get(reinsurer) == null ? 1d : reinsurersDefault.get(reinsurer);
coveredByReinsurers += portion * reinsurerDefault;
}
parmContractStrategy.adjustCovered(coveredByReinsurers);
filterInChannels();
// initialize contract details
parmContractStrategy.initBookkeepingFigures(outFilteredClaims, outFilteredUnderwritingInfo);
Collections.sort(outFilteredClaims, SortClaimsByFractionOfPeriod.getInstance());
if (isSenderWired(getOutUncoveredClaims()) || isSenderWired(getOutClaimsDevelopmentLeanNet())) {
calculateClaims(outFilteredClaims, outCoveredClaims, outUncoveredClaims, this);
}
else {
calculateCededClaims(outFilteredClaims, outCoveredClaims, this);
}
if (isSenderWired(outCoverUnderwritingInfo) || isSenderWired(outContractFinancials) || isSenderWired(outNetAfterCoverUnderwritingInfo)) {
calculateCededUnderwritingInfos(outFilteredUnderwritingInfo, outCoverUnderwritingInfo, outCoveredClaims);
}
parmCommissionStrategy.calculateCommission(outCoveredClaims, outCoverUnderwritingInfo, false, false);
if (isSenderWired(outNetAfterCoverUnderwritingInfo)) {
calculateNetUnderwritingInfos(UnderwritingFilterUtilities.filterUnderwritingInfoByLobWithoutScaling(
inUnderwritingInfo, ClaimFilterUtilities.getLinesOfBusiness(outFilteredClaims)),
outCoverUnderwritingInfo, outNetAfterCoverUnderwritingInfo, outCoveredClaims);
}
if (inClaims.size() > 0 && inClaims.get(0) instanceof ClaimDevelopmentLeanPacket) {
for (Claim claim : outFilteredClaims) {
getOutClaimsDevelopmentLeanGross().add((ClaimDevelopmentLeanPacket) claim);
}
}
if (outCoveredClaims.size() > 0 && outCoveredClaims.get(0) instanceof ClaimDevelopmentLeanPacket) {
for (Claim claim : outUncoveredClaims) {
getOutClaimsDevelopmentLeanNet().add((ClaimDevelopmentLeanPacket) claim);
}
for (Claim claim : outCoveredClaims) {
getOutClaimsDevelopmentLeanCeded().add((ClaimDevelopmentLeanPacket) claim);
}
}
if (isSenderWired(outContractFinancials)) {
ReinsuranceResultWithCommissionPacket result = new ReinsuranceResultWithCommissionPacket();
UnderwritingInfo underwritingInfo = UnderwritingInfoUtilities.aggregate(outCoverUnderwritingInfo);
if (underwritingInfo != null) {
result.setCededPremium(-underwritingInfo.getPremiumWritten());
result.setCededCommission(-underwritingInfo.getCommission());
}
if (outCoveredClaims.size() > 0) {
result.setCededClaim(ClaimUtilities.aggregateClaims(outCoveredClaims, this).getUltimate());
}
if (result.getCededPremium() != 0) {
result.setCededLossRatio(result.getCededClaim() / -result.getCededPremium());
}
outContractFinancials.add(result);
}
for (UnderwritingInfo outCoverUnderwritingInfoPacket : outCoverUnderwritingInfo) {
outCoverUnderwritingInfoPacket.setReinsuranceContract(this);
}
parmContractStrategy.resetCovered();
}
protected void filterInChannels() {
if (parmCover instanceof NoneCompanyCoverAttributeStrategy) {
// leave outFiltered* lists void
}
else if (parmCover instanceof AllCompanyCoverAttributeStrategy) {
outFilteredClaims.addAll(inClaims);
outFilteredUnderwritingInfo.addAll(inUnderwritingInfo);
}
else if (parmCover instanceof CompaniesCompanyCoverAttributeStrategy) {
List<ICompanyMarker> coveredCompanies = (List<ICompanyMarker>) (((CompaniesCompanyCoverAttributeStrategy) parmCover).getCompanies().getValuesAsObjects());
outFilteredClaims.addAll(ClaimFilterUtilities.filterClaimsByCompanies(inClaims, coveredCompanies, false));
List<LobMarker> coveredLines = ClaimFilterUtilities.getLinesOfBusiness(outFilteredClaims);
outFilteredUnderwritingInfo.addAll(UnderwritingFilterUtilities.filterUnderwritingInfoByLobWithoutScaling(inUnderwritingInfo, coveredLines));
}
else {
List<LobMarker> coveredLines = parmCover instanceof ILinesOfBusinessCoverAttributeStrategy
? (List<LobMarker>) (((ILinesOfBusinessCoverAttributeStrategy) parmCover).getLines().getValuesAsObjects()) : null;
List<PerilMarker> coveredPerils = parmCover instanceof IPerilCoverAttributeStrategy
? (List<PerilMarker>) ((IPerilCoverAttributeStrategy) parmCover).getPerils().getValuesAsObjects() : null;
List<IReserveMarker> coveredReserves = parmCover instanceof IReservesCoverAttributeStrategy
? (List<IReserveMarker>) ((IReservesCoverAttributeStrategy) parmCover).getReserves().getValuesAsObjects() : null;
LogicArguments connection = parmCover instanceof ICombinedCoverAttributeStrategy
? ((ICombinedCoverAttributeStrategy) parmCover).getConnection() : null;
outFilteredClaims.addAll(ClaimFilterUtilities.filterClaimsByPerilLobReserve(inClaims, coveredPerils, coveredLines, coveredReserves, connection));
// extend coveredLines such that they additionally consist of the segments which are associated with the selected perils
coveredLines = ClaimFilterUtilities.getLinesOfBusiness(outFilteredClaims);
outFilteredUnderwritingInfo.addAll(UnderwritingFilterUtilities.filterUnderwritingInfoByLobAndScaleByPerilsInLob(inUnderwritingInfo, coveredLines, inClaims, coveredPerils));
}
}
public ConstrainedMultiDimensionalParameter getParmReinsurers() {
return parmReinsurers;
}
public void setParmReinsurers(ConstrainedMultiDimensionalParameter parmReinsurers) {
this.parmReinsurers = parmReinsurers;
}
public PacketList<ReinsurerDefault> getInReinsurersDefault() {
return inReinsurersDefault;
}
public void setInReinsurersDefault(PacketList<ReinsurerDefault> inReinsurersDefault) {
this.inReinsurersDefault = inReinsurersDefault;
}
public SimulationScope getSimulationScope() {
return simulationScope;
}
public void setSimulationScope(SimulationScope simulationScope) {
this.simulationScope = simulationScope;
}
public ReinsuranceContractBase getParmBasedOn() {
return parmBasedOn;
}
public void setParmBasedOn(ReinsuranceContractBase parmBasedOn) {
this.parmBasedOn = parmBasedOn;
}
public ICoverAttributeStrategy getParmCover() {
return parmCover;
}
public void setParmCover(ICoverAttributeStrategy parmCover) {
this.parmCover = parmCover;
}
/**
* claims whose source is a covered line
*/
public PacketList<Claim> getOutFilteredClaims() {
return outFilteredClaims;
}
public void setOutFilteredClaims(PacketList<Claim> outFilteredClaims) {
this.outFilteredClaims = outFilteredClaims;
}
public PacketList<UnderwritingInfo> getOutFilteredUnderwritingInfo() {
return outFilteredUnderwritingInfo;
}
public void setOutFilteredUnderwritingInfo(PacketList<UnderwritingInfo> outFilteredUnderwritingInfo) {
this.outFilteredUnderwritingInfo = outFilteredUnderwritingInfo;
}
- public static String getReinsurer() {
- return REINSURER;
- }
-
- public static String getPortion() {
- return PORTION;
- }
}
| false | false | null | null |
diff --git a/Android/Data_Collector/src/edu/uml/cs/isense/collector/dialogs/Step1Setup.java b/Android/Data_Collector/src/edu/uml/cs/isense/collector/dialogs/Step1Setup.java
index a21952c8..cf5cdc07 100644
--- a/Android/Data_Collector/src/edu/uml/cs/isense/collector/dialogs/Step1Setup.java
+++ b/Android/Data_Collector/src/edu/uml/cs/isense/collector/dialogs/Step1Setup.java
@@ -1,418 +1,420 @@
package edu.uml.cs.isense.collector.dialogs;
import java.util.LinkedList;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.TextView;
import edu.uml.cs.isense.collector.DataCollector;
import edu.uml.cs.isense.collector.R;
import edu.uml.cs.isense.comm.API;
import edu.uml.cs.isense.dfm.DataFieldManager;
import edu.uml.cs.isense.dfm.FieldMatching;
import edu.uml.cs.isense.dfm.Fields;
import edu.uml.cs.isense.proj.Setup;
import edu.uml.cs.isense.supplements.OrientationManager;
import edu.uml.cs.isense.waffle.Waffle;
public class Step1Setup extends Activity {
private static Button cancel, ok, selProj;
private static CheckBox projCheck, remember;
private static EditText dataSetName, sInterval, testLen;
private static TextView projLabel;
private static Context mContext;
private static Waffle w;
private SharedPreferences mPrefs;
private SharedPreferences.Editor mEdit;
private static final int SETUP_REQUESTED = 100;
private static final int FIELD_MATCHING_REQUESTED = 101;
public static final int S_INTERVAL = 50;
public static final int TEST_LENGTH = 600;
public static final int MAX_DATA_POINTS = (1000 / S_INTERVAL) * TEST_LENGTH;
public static API api;
public static LinkedList<String> acceptedFields;
public static DataFieldManager dfm;
public static Fields f;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.step1setup);
if (android.os.Build.VERSION.SDK_INT < 11)
getWindow().setLayout(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
mContext = this;
w = new Waffle(this);
api = API.getInstance(getApplicationContext());
f = new Fields();
mPrefs = getSharedPreferences("PROJID", 0);
mEdit = mPrefs.edit();
cancel = (Button) findViewById(R.id.step1_cancel);
cancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
setResult(RESULT_CANCELED);
finish();
}
});
ok = (Button) findViewById(R.id.step1_ok);
ok.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (dataSetName.getText().toString().equals("")) {
dataSetName.setError("Enter a data set name");
w.make("Please enter a data set name first",
Waffle.LENGTH_SHORT, Waffle.IMAGE_WARN);
return;
} else {
dataSetName.setError(null);
}
long sint;
if (sInterval.getText().toString().equals("")) {
sint = S_INTERVAL;
} else {
sint = Integer.parseInt(sInterval.getText().toString());
}
if (sint < S_INTERVAL) {
sInterval.setError("Enter a sample interval >= "
+ S_INTERVAL + " ms");
w.make("Please enter a valid sample interval",
Waffle.LENGTH_SHORT, Waffle.IMAGE_WARN);
return;
} else {
sInterval.setError(null);
}
long tlen;
if (testLen.getText().toString().equals("")) {
tlen = TEST_LENGTH;
} else {
tlen = Integer.parseInt(testLen.getText().toString());
}
if (tlen * (1000 / sint) > MAX_DATA_POINTS) {
testLen.setError("Enter a test length <= "
+ (long) MAX_DATA_POINTS / (1000 / sint) + " s");
w.make("Please enter a valid test length",
Waffle.LENGTH_SHORT, Waffle.IMAGE_WARN);
return;
} else {
testLen.setError(null);
}
if (!projCheck.isChecked()) {
String projID = mPrefs.getString("project_id", "");
String fields = mPrefs.getString("accepted_fields", "");
String acceptedProj = mPrefs.getString("accepted_proj",
"-1");
if (projID.equals("") || projID.equals("-1") || projID.equals("0")) {
w.make("Please select a project", Waffle.LENGTH_SHORT,
Waffle.IMAGE_WARN);
return;
} else if (fields.equals("")
|| (!projID.equals(acceptedProj))) {
w.make("Please select your project fields",
Waffle.LENGTH_SHORT, Waffle.IMAGE_WARN);
new SensorCheckTask().execute();
return;
}
}
if (projCheck.isChecked())
mEdit.putString("project_id", "-1").commit();
mEdit.putString("data_set_name",
dataSetName.getText().toString()).commit();
if (remember.isChecked()) {
mEdit.putString("s_interval",
sInterval.getText().toString()).commit();
mEdit.putString("t_length", testLen.getText().toString())
.commit();
mEdit.putBoolean("remember", true).commit();
} else {
mEdit.putBoolean("remember", false).commit();
}
Intent iRet = new Intent();
iRet.putExtra(DataCollector.STEP_1_DATASET_NAME, dataSetName
.getText().toString());
iRet.putExtra(DataCollector.STEP_1_SAMPLE_INTERVAL, sint);
iRet.putExtra(DataCollector.STEP_1_TEST_LENGTH, tlen);
setResult(RESULT_OK, iRet);
finish();
}
});
selProj = (Button) findViewById(R.id.step1_select_proj);
selProj.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// if (!api.hasConnectivity())
// w.make("No internet connectivity found - searching only cached projects",
// Waffle.LENGTH_LONG, Waffle.IMAGE_WARN);
Intent iSetup = new Intent(mContext, Setup.class);
iSetup.putExtra("from_where", "automatic");
startActivityForResult(iSetup, SETUP_REQUESTED);
}
});
projCheck = (CheckBox) findViewById(R.id.step1_checkbox);
projCheck.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (projCheck.isChecked()) {
selProj.setEnabled(false);
projLabel.setText("Project");
} else {
selProj.setEnabled(true);
String proj = mPrefs.getString("project_id", "");
if (!(proj.equals("") || proj.equals("-1"))) {
projLabel.setText("Project (currently " + proj + ")");
} else {
projLabel.setText("Project");
}
}
}
});
dataSetName = (EditText) findViewById(R.id.step1_data_set_name);
dataSetName.setText(mPrefs.getString("data_set_name", ""));
sInterval = (EditText) findViewById(R.id.step1_sample_interval);
testLen = (EditText) findViewById(R.id.step1_test_length);
projLabel = (TextView) findViewById(R.id.step1_proj_num_label);
SharedPreferences globalProjPrefs = getSharedPreferences("GLOBAL_PROJ",
0);
SharedPreferences.Editor gppEdit = globalProjPrefs.edit();
String proj = globalProjPrefs.getString("project_id_dc", "");
if (!(proj.equals(""))) {
projLabel.setText("Project (currently " + proj + ")");
dfm = new DataFieldManager(Integer.parseInt(proj), api, mContext, f);
// reset the global project id so we don't pull it again
gppEdit.putString("project_id_dc", "").commit();
// switch the global project id to the local project id
mEdit.putString("project_id", proj).commit();
} else {
proj = mPrefs.getString("project_id", "");
if (!(proj.equals("") || proj.equals("-1"))) {
projLabel.setText("Project (currently " + proj + ")");
dfm = new DataFieldManager(Integer.parseInt(proj), api,
mContext, f);
} else {
dfm = new DataFieldManager(-1, api, mContext, f);
projCheck.toggle();
}
}
remember = (CheckBox) findViewById(R.id.step1_remember);
remember.setChecked(mPrefs.getBoolean("remember", false));
if (remember.isChecked()) {
sInterval.setText(mPrefs.getString("s_interval", ""));
testLen.setText(mPrefs.getString("t_length", ""));
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SETUP_REQUESTED) {
if (resultCode == RESULT_OK) {
String projID = mPrefs.getString("project_id", "");
if (!(projID.equals("") || projID.equals("-1"))) {
projLabel.setText("Project (currently " + projID + ")");
} else {
projLabel.setText("Project");
}
new SensorCheckTask().execute();
}
} else if (requestCode == FIELD_MATCHING_REQUESTED) {
if (resultCode == RESULT_OK) {
if (FieldMatching.acceptedFields.isEmpty()) {
Intent iSetup = new Intent(mContext, Setup.class);
iSetup.putExtra("from_where", "automatic");
startActivityForResult(iSetup, SETUP_REQUESTED);
} else if (!FieldMatching.compatible) {
Intent iSetup = new Intent(mContext, Setup.class);
iSetup.putExtra("from_where", "automatic");
startActivityForResult(iSetup, SETUP_REQUESTED);
} else {
acceptedFields = FieldMatching.acceptedFields;
getEnabledFields();
}
} else if (resultCode == RESULT_CANCELED) {
Intent iSetup = new Intent(mContext, Setup.class);
iSetup.putExtra("from_where", "automatic");
startActivityForResult(iSetup, SETUP_REQUESTED);
}
}
}
private void getEnabledFields() {
try {
for (String s : acceptedFields) {
if (s.length() != 0)
break;
}
} catch (NullPointerException e) {
SharedPreferences mPrefs = getSharedPreferences("PROJID", 0);
String fields = mPrefs.getString("accepted_fields", "");
getFieldsFromPrefsString(fields);
}
for (String s : acceptedFields) {
System.out.println("Got back: " + s);
if (s.equals(getString(R.string.time)))
dfm.enabledFields[Fields.TIME] = true;
if (s.equals(getString(R.string.accel_x)))
dfm.enabledFields[Fields.ACCEL_X] = true;
if (s.equals(getString(R.string.accel_y)))
dfm.enabledFields[Fields.ACCEL_Y] = true;
if (s.equals(getString(R.string.accel_z)))
dfm.enabledFields[Fields.ACCEL_Z] = true;
if (s.equals(getString(R.string.accel_total)))
dfm.enabledFields[Fields.ACCEL_TOTAL] = true;
if (s.equals(getString(R.string.latitude)))
dfm.enabledFields[Fields.LATITUDE] = true;
if (s.equals(getString(R.string.longitude)))
dfm.enabledFields[Fields.LONGITUDE] = true;
if (s.equals(getString(R.string.magnetic_x)))
dfm.enabledFields[Fields.MAG_X] = true;
if (s.equals(getString(R.string.magnetic_y)))
dfm.enabledFields[Fields.MAG_Y] = true;
if (s.equals(getString(R.string.magnetic_z)))
dfm.enabledFields[Fields.MAG_Z] = true;
if (s.equals(getString(R.string.magnetic_total)))
dfm.enabledFields[Fields.MAG_TOTAL] = true;
if (s.equals(getString(R.string.heading_deg)))
dfm.enabledFields[Fields.HEADING_DEG] = true;
if (s.equals(getString(R.string.heading_rad)))
dfm.enabledFields[Fields.HEADING_RAD] = true;
if (s.equals(getString(R.string.temperature_c)))
dfm.enabledFields[Fields.TEMPERATURE_C] = true;
if (s.equals(getString(R.string.temperature_f)))
dfm.enabledFields[Fields.TEMPERATURE_F] = true;
if (s.equals(getString(R.string.temperature_k)))
dfm.enabledFields[Fields.TEMPERATURE_K] = true;
if (s.equals(getString(R.string.pressure)))
dfm.enabledFields[Fields.PRESSURE] = true;
if (s.equals(getString(R.string.altitude)))
dfm.enabledFields[Fields.ALTITUDE] = true;
if (s.equals(getString(R.string.luminous_flux)))
dfm.enabledFields[Fields.LIGHT] = true;
}
}
private void getFieldsFromPrefsString(String fieldList) {
String[] fields = fieldList.split(",");
acceptedFields = new LinkedList<String>();
for (String f : fields) {
acceptedFields.add(f);
}
}
// Task for checking sensor availability along with enabling/disabling
private class SensorCheckTask extends AsyncTask<Void, Integer, Void> {
ProgressDialog dia;
@Override
protected void onPreExecute() {
OrientationManager.disableRotation(Step1Setup.this);
dia = new ProgressDialog(Step1Setup.this);
dia.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dia.setMessage("Gathering project fields...");
dia.setCancelable(false);
dia.show();
}
@Override
protected Void doInBackground(Void... voids) {
SharedPreferences mPrefs = getSharedPreferences("PROJID", 0);
String projectInput = mPrefs.getString("project_id", "");
Log.d("SensorCheck", "ProjectId = " + projectInput);
dfm = new DataFieldManager(Integer.parseInt(projectInput), api,
mContext, f);
dfm.getOrderWithExternalAsyncTask();
dfm.writeProjectFields();
publishProgress(100);
return null;
}
@Override
protected void onPostExecute(Void voids) {
dia.setMessage("Done");
dia.cancel();
OrientationManager.enableRotation(Step1Setup.this);
Intent iFieldMatch = new Intent(mContext, FieldMatching.class);
- String[] dfmOrderList = dfm.convertOrderToStringArray();
+ String[] dfmOrderList = dfm.convertLinkedListToStringArray(dfm.getOrderList());
+ String[] dfmRealOrderList = dfm.convertLinkedListToStringArray(dfm.getRealOrderList());
iFieldMatch.putExtra(FieldMatching.DFM_ORDER_LIST,dfmOrderList);
+ iFieldMatch.putExtra(FieldMatching.DFM_REAL_ORDER_LIST, dfmRealOrderList);
startActivityForResult(iFieldMatch, FIELD_MATCHING_REQUESTED);
}
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/src/main/java/hudson/remoting/PingThread.java b/src/main/java/hudson/remoting/PingThread.java
index e673326d..7efc3c65 100644
--- a/src/main/java/hudson/remoting/PingThread.java
+++ b/src/main/java/hudson/remoting/PingThread.java
@@ -1,150 +1,150 @@
/*
* The MIT License
*
* Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi, 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 hudson.remoting;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import java.util.concurrent.TimeoutException;
import java.util.logging.Logger;
/**
* Periodically perform a ping.
*
* <p>
* Useful when a connection needs to be kept alive by sending data,
* or when the disconnection is not properly detected.
*
* <p>
* {@link #onDead()} method needs to be overrided to define
* what to do when a connection appears to be dead.
*
* @author Kohsuke Kawaguchi
* @since 1.170
*/
public abstract class PingThread extends Thread {
private final Channel channel;
/**
* Time out in milliseconds.
* If the response doesn't come back by then, the channel is considered dead.
*/
private final long timeout;
/**
* Performs a check every this milliseconds.
*/
private final long interval;
public PingThread(Channel channel, long timeout, long interval) {
super("Ping thread for channel "+channel);
this.channel = channel;
this.timeout = timeout;
this.interval = interval;
setDaemon(true);
}
public PingThread(Channel channel, long interval) {
this(channel, 4*60*1000/*4 mins*/, interval);
}
public PingThread(Channel channel) {
this(channel,10*60*1000/*10 mins*/);
}
public void run() {
try {
while(true) {
long nextCheck = System.currentTimeMillis()+interval;
ping();
// wait until the next check
long diff;
while((diff=nextCheck-System.currentTimeMillis())>0)
Thread.sleep(diff);
}
} catch (ChannelClosedException e) {
LOGGER.fine(getName()+" is closed. Terminating");
} catch (IOException e) {
onDead(e);
} catch (InterruptedException e) {
// use interruption as a way to terminate the ping thread.
LOGGER.fine(getName()+" is interrupted. Terminating");
}
}
private void ping() throws IOException, InterruptedException {
Future<?> f = channel.callAsync(new Ping());
long start = System.currentTimeMillis();
long end = start +timeout;
long remaining;
do {
remaining = end-System.currentTimeMillis();
try {
f.get(Math.max(0,remaining),MILLISECONDS);
return;
} catch (ExecutionException e) {
if (e.getCause() instanceof RequestAbortedException)
return; // connection has shut down orderly.
onDead(e);
return;
} catch (TimeoutException e) {
// get method waits "at most the amount specified in the timeout",
// so let's make sure that it really waited enough
}
} while(remaining>0);
- onDead(new TimeoutException("Ping started on "+start+" hasn't completed at "+System.currentTimeMillis()).initCause(e));
+ onDead(new TimeoutException("Ping started on "+start+" hasn't completed at "+System.currentTimeMillis()));//.initCause(e)
}
/**
* Called when ping failed.
*
* @deprecated as of 2.9
* Override {@link #onDead(Throwable)} to receive the cause, but also override this method
* and provide a fallback behaviour to be backward compatible with earlier version of remoting library.
*/
protected abstract void onDead();
/**
* Called when ping failed.
*
* @since 2.9
*/
protected void onDead(Throwable diagnosis) {
onDead(); // fall back
}
private static final class Ping implements Callable<Void, IOException> {
private static final long serialVersionUID = 1L;
public Void call() throws IOException {
return null;
}
}
private static final Logger LOGGER = Logger.getLogger(PingThread.class.getName());
}
| true | true | private void ping() throws IOException, InterruptedException {
Future<?> f = channel.callAsync(new Ping());
long start = System.currentTimeMillis();
long end = start +timeout;
long remaining;
do {
remaining = end-System.currentTimeMillis();
try {
f.get(Math.max(0,remaining),MILLISECONDS);
return;
} catch (ExecutionException e) {
if (e.getCause() instanceof RequestAbortedException)
return; // connection has shut down orderly.
onDead(e);
return;
} catch (TimeoutException e) {
// get method waits "at most the amount specified in the timeout",
// so let's make sure that it really waited enough
}
} while(remaining>0);
onDead(new TimeoutException("Ping started on "+start+" hasn't completed at "+System.currentTimeMillis()).initCause(e));
}
| private void ping() throws IOException, InterruptedException {
Future<?> f = channel.callAsync(new Ping());
long start = System.currentTimeMillis();
long end = start +timeout;
long remaining;
do {
remaining = end-System.currentTimeMillis();
try {
f.get(Math.max(0,remaining),MILLISECONDS);
return;
} catch (ExecutionException e) {
if (e.getCause() instanceof RequestAbortedException)
return; // connection has shut down orderly.
onDead(e);
return;
} catch (TimeoutException e) {
// get method waits "at most the amount specified in the timeout",
// so let's make sure that it really waited enough
}
} while(remaining>0);
onDead(new TimeoutException("Ping started on "+start+" hasn't completed at "+System.currentTimeMillis()));//.initCause(e)
}
|
diff --git a/src/java/se/idega/idegaweb/commune/childcare/presentation/ChildCareAdminWindow.java b/src/java/se/idega/idegaweb/commune/childcare/presentation/ChildCareAdminWindow.java
index 80aa5b13..b50c2ca7 100644
--- a/src/java/se/idega/idegaweb/commune/childcare/presentation/ChildCareAdminWindow.java
+++ b/src/java/se/idega/idegaweb/commune/childcare/presentation/ChildCareAdminWindow.java
@@ -1,1881 +1,1883 @@
package se.idega.idegaweb.commune.childcare.presentation;
import java.rmi.RemoteException;
import java.text.DateFormat;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.ejb.EJBException;
import javax.ejb.FinderException;
import se.idega.block.pki.business.NBSLoginBusinessBean;
import se.idega.block.pki.data.NBSSignedEntity;
import se.idega.block.pki.presentation.NBSSigningBlock;
import se.idega.idegaweb.commune.childcare.business.NoPlacementFoundException;
import se.idega.idegaweb.commune.childcare.data.ChildCareApplication;
import se.idega.idegaweb.commune.childcare.data.ChildCareContract;
import se.idega.idegaweb.commune.childcare.data.ChildCarePrognosis;
import se.idega.idegaweb.commune.school.business.SchoolCommuneBusiness;
import com.idega.block.contract.data.Contract;
import com.idega.block.contract.data.ContractHome;
import com.idega.block.contract.data.ContractTag;
import com.idega.block.contract.data.ContractTagHome;
import com.idega.block.school.data.School;
import com.idega.block.school.data.SchoolClass;
import com.idega.block.school.data.SchoolClassMember;
import com.idega.block.school.data.SchoolType;
import com.idega.block.school.presentation.SchoolClassDropdownDouble;
import com.idega.builder.business.BuilderLogic;
import com.idega.business.IBOLookup;
import com.idega.core.builder.data.ICPage;
import com.idega.core.contact.data.Email;
import com.idega.core.contact.data.Phone;
import com.idega.core.user.business.UserBusiness;
import com.idega.data.IDOLookup;
import com.idega.data.IDOLookupException;
import com.idega.data.IDORelationshipException;
import com.idega.presentation.IWContext;
import com.idega.presentation.Table;
import com.idega.presentation.text.Break;
import com.idega.presentation.text.Text;
import com.idega.presentation.ui.CloseButton;
import com.idega.presentation.ui.DateInput;
import com.idega.presentation.ui.DropdownMenu;
import com.idega.presentation.ui.Form;
import com.idega.presentation.ui.HiddenInput;
import com.idega.presentation.ui.RadioButton;
import com.idega.presentation.ui.SubmitButton;
import com.idega.presentation.ui.TextArea;
import com.idega.presentation.ui.TextInput;
import com.idega.presentation.ui.Window;
import com.idega.user.business.NoPhoneFoundException;
import com.idega.user.data.User;
import com.idega.util.IWTimestamp;
import com.idega.util.URLUtil;
import com.idega.util.text.TextSoap;
/**
* @author laddi
*/
public class ChildCareAdminWindow extends ChildCareBlock {
public static final String PARAMETER_ACTION = "cc_admin_action";
public static final String PARAMETER_METHOD = "cc_admin_method";
public static final String PARAMETER_USER_ID = "cc_user_id";
public static final String PARAMETER_APPLICATION_ID = "cc_application_id";
public static final String PARAMETER_PAGE_ID = "cc_page_id";
public static final String PARAMETER_REJECT_MESSAGE = "cc_reject_message";
public static final String PARAMETER_OFFER_MESSAGE = "cc_offer_message";
public static final String PARAMETER_PRIORITY_MESSAGE = "cc_priority_message";
public static final String PARAMETER_CHANGE_DATE = "cc_change_date";
public static final String PARAMETER_CHILDCARE_TIME = "cc_childcare_time";
public static final String PARAMETER_GROUP_NAME = "cc_group_name";
public static final String PARAMETER_OLD_GROUP = "cc_old_group";
public static final String PARAMETER_THREE_MONTHS_PROGNOSIS = "cc_three_months";
public static final String PARAMETER_ONE_YEAR_PROGNOSIS = "cc_one_year";
public static final String PARAMETER_THREE_MONTHS_PRIORITY = "cc_three_months_priority";
public static final String PARAMETER_ONE_YEAR_PRIORITY = "cc_one_year_priority";
public static final String PARAMETER_PROVIDER_CAPACITY = "cc_provider_capacity";
public static final String PARAMETER_OFFER_VALID_UNTIL = "cc_offer_valid_until";
public static final String PARAMETER_CANCEL_REASON = "cc_cancel_reason";
public static final String PARAMETER_CANCEL_MESSAGE = "cc_cancel_message";
public static final String PARAMETER_CANCEL_DATE = "cc_cancel_date";
public static final String PARAMETER_EARLIEST_DATE = "cc_earliest_date";
public static final String PARAMETER_CONTRACT_ID = "cc_contract_id";
public static final String PARAMETER_TEXT_FIELD = "cc_xml_signing_text_field";
public static final String PARAMETER_PRE_SCHOOL = "cc_pre_school";
public static final String PARAMETER_SCHOOL_TYPES = "cc_school_types";
public static final String PARAMETER_EMPLOYMENT_TYPE = "cc_employment_type";
public static final String PARAMETER_PLACEMENT_ID = "cc_placement_id";
public static final String PARAMETER_SCHOOL_CLASS = "cc_sch_class";
private static final String PROPERTY_RESTRICT_DATES = "child_care_restrict_alter_date";
public static final String FIELD_CURRENT_DATE = "currentdate";
//private final static String USER_MESSAGE_SUBJECT = "child_care.application_received_subject";
//private final static String USER_MESSAGE_BODY = "child_care.application_received_body";
public static final int METHOD_GRANT_PRIORITY = 2;
public static final int METHOD_OFFER = 3;
public static final int METHOD_CHANGE_DATE = 4;
public static final int METHOD_CREATE_CONTRACT = 5;
public static final int METHOD_CREATE_GROUP = 6;
public static final int METHOD_PLACE_IN_GROUP = 7;
public static final int METHOD_MOVE_TO_GROUP = 8;
public static final int METHOD_UPDATE_PROGNOSIS = 9;
public static final int METHOD_ALTER_CARE_TIME = 10;
public static final int METHOD_CANCEL_CONTRACT = 11;
public static final int METHOD_CHANGE_OFFER = 12;
public static final int METHOD_RETRACT_OFFER = 13;
public static final int METHOD_ALTER_VALID_FROM_DATE = 14;
public static final int METHOD_VIEW_PROVIDER_QUEUE = 15;
public static final int METHOD_END_CONTRACT = 16;
public static final int METHOD_NEW_CARE_TIME = 17;
public static final int METHOD_SIGN_CONTRACT = 18;
public static final int METHOD_REJECT_APPLICATION = 19;
public static final int ACTION_CLOSE = 0;
public static final int ACTION_GRANT_PRIORITY = 1;
public static final int ACTION_OFFER = 2;
public static final int ACTION_CHANGE_DATE = 3;
public static final int ACTION_PARENTS_AGREE = 4;
public static final int ACTION_CREATE_CONTRACT = 5;
public static final int ACTION_CREATE_GROUP = 6;
public static final int ACTION_PLACE_IN_GROUP = 7;
public static final int ACTION_MOVE_TO_GROUP = 8;
public static final int ACTION_CANCEL_CONTRACT = 9;
public static final int ACTION_UPDATE_PROGNOSIS = 10;
public static final int ACTION_ALTER_CARE_TIME = 11;
public static final int ACTION_DELETE_GROUP = 12;
public static final int ACTION_RETRACT_OFFER = 13;
public static final int ACTION_REMOVE_FUTURE_CONTRACTS = 14;
public static final int ACTION_CREATE_CONTRACT_FOR_BANKID = 15;
public static final int ACTION_ALTER_VALID_FROM_DATE = 16;
public static final int ACTION_END_CONTRACT = 17;
public static final int ACTION_NEW_CARE_TIME = 18;
public static final int ACTION_SIGN_CONTRACT = 19;
public static final int ACTION_REJECT_APPLICATION = 20;
private int _method = -1;
private int _action = -1;
private int _userID = -1;
private int _applicationID = -1;
private int _placementID = -1;
private int _pageID;
private IWTimestamp earliestDate;
private CloseButton close;
private Form form;
private boolean restrictDates = false;
boolean onlyAllowFutureCareDate = true; //Changed according to #nacc149
/**
* @see se.idega.idegaweb.commune.childcare.presentation.ChildCareBlock#init(com.idega.presentation.IWContext)
*/
public void init(IWContext iwc) throws Exception {
parse(iwc);
switch (_action) {
case ACTION_CLOSE :
close();
break;
case ACTION_GRANT_PRIORITY :
grantPriority(iwc);
break;
case ACTION_OFFER :
makeOffer(iwc);
break;
case ACTION_CHANGE_DATE :
changeDate(iwc);
break;
case ACTION_PARENTS_AGREE :
parentsAgree(iwc);
break;
case ACTION_CREATE_CONTRACT :
createContract(iwc);
break;
case ACTION_CREATE_GROUP :
createGroup(iwc);
break;
case ACTION_PLACE_IN_GROUP :
placeInGroup(iwc);
break;
case ACTION_MOVE_TO_GROUP :
moveToGroup(iwc);
break;
case ACTION_CANCEL_CONTRACT :
cancelContract(iwc);
break;
case ACTION_UPDATE_PROGNOSIS :
updatePrognosis(iwc);
break;
case ACTION_ALTER_CARE_TIME :
alterCareTime(iwc);
break;
case ACTION_DELETE_GROUP :
deleteGroup(iwc);
break;
case ACTION_RETRACT_OFFER :
retractOffer(iwc);
break;
case ACTION_REMOVE_FUTURE_CONTRACTS :
removeFutureContracts(iwc);
break;
case ACTION_CREATE_CONTRACT_FOR_BANKID :
createContractForBankID(iwc);
break;
case ACTION_ALTER_VALID_FROM_DATE :
alterValidFromDate(iwc);
break;
case ACTION_END_CONTRACT :
sendEndContractRequest(iwc);
break;
case ACTION_NEW_CARE_TIME :
sendNewCareTimeRequest(iwc);
break;
case ACTION_SIGN_CONTRACT :
processSignContract(iwc);
break;
case ACTION_REJECT_APPLICATION :
rejectApplication(iwc);
break;
}
if (_method != -1)
drawForm(iwc);
}
private void drawForm(IWContext iwc) throws RemoteException, Exception {
form = new Form();
form.maintainParameter(PARAMETER_USER_ID);
form.maintainParameter(PARAMETER_APPLICATION_ID);
form.maintainParameter(PARAMETER_PAGE_ID);
form.maintainParameter(PARAMETER_CONTRACT_ID);
form.maintainParameter(PARAMETER_PLACEMENT_ID);
form.setStyleAttribute("height:100%");
Table table = new Table(3, 5);
table.setRowColor(1, "#000000");
table.setRowColor(3, "#000000");
table.setRowColor(5, "#000000");
table.setColumnColor(1, "#000000");
table.setColumnColor(3, "#000000");
table.setColor(2, 2, "#CCCCCC");
table.setWidth(Table.HUNDRED_PERCENT);
table.setWidth(2, Table.HUNDRED_PERCENT);
table.setHeight(Table.HUNDRED_PERCENT);
table.setHeight(4, Table.HUNDRED_PERCENT);
table.setCellpadding(0);
table.setCellspacing(0);
form.add(table);
Table headerTable = new Table(1, 1);
headerTable.setCellpadding(6);
table.add(headerTable, 2, 2);
Table contentTable = new Table(1, 1);
contentTable.setCellpadding(10);
contentTable.setWidth(Table.HUNDRED_PERCENT);
contentTable.setHeight(Table.HUNDRED_PERCENT);
table.add(contentTable, 2, 4);
close = (CloseButton) getStyledInterface(new CloseButton(localize("close_window", "Close")));
//close.setPageToOpen(getParentPageID());
//close.addParameterToPage(PARAMETER_ACTION, ACTION_CLOSE);
String userName= null;
String personalId = null;
String personalIdUserName = "";
ChildCareApplication application = getBusiness().getApplication(_applicationID);
User child;
if (application != null && userName == null) {
child = application.getChild();
if (child != null){
personalId = child.getPersonalID();
userName = getBusiness().getUserBusiness().getNameLastFirst(child, true);
}
}
else if (_userID != -1){
child = getBusiness().getUserBusiness().getUser(_userID);
if (child != null){
personalId = child.getPersonalID();
userName = getBusiness().getUserBusiness().getNameLastFirst(child, true);
}
}
if (userName != null){
personalIdUserName = " - " + userName + " " + personalId;
}
switch (_method) {
case METHOD_GRANT_PRIORITY :
headerTable.add(getHeader(localize("child_care.grant_priority", "Grant priority")+ personalIdUserName));
contentTable.add(getPriorityForm(iwc));
break;
case METHOD_OFFER :
headerTable.add(getHeader(localize("child_care.offer_placing", "Offer placing")+ personalIdUserName));
contentTable.add(getOfferForm(iwc));
break;
case METHOD_CHANGE_DATE :
headerTable.add(getHeader(localize("child_care.change_date", "Change date")+ personalIdUserName));
contentTable.add(getChangeDateForm(iwc, false));
break;
case METHOD_PLACE_IN_GROUP :
headerTable.add(getHeader(localize("child_care.place_in_group", "Place in group")+ personalIdUserName));
contentTable.add(getPlaceInGroupForm());
break;
case METHOD_MOVE_TO_GROUP :
headerTable.add(getHeader(localize("child_care.move_to_group", "Move to group")+ personalIdUserName));
contentTable.add(getMoveGroupForm(iwc));
break;
case METHOD_CREATE_GROUP :
if (getSession().getGroupID() != -1)
headerTable.add(getHeader(localize("child_care.change_group", "Change group")+ personalIdUserName));
else
headerTable.add(getHeader(localize("child_care.create_group", "Create group")));
contentTable.add(getCreateGroupForm());
break;
case METHOD_UPDATE_PROGNOSIS :
headerTable.add(getHeader(localize("child_care.set_prognosis", "Set prognosis")));
contentTable.add(getUpdatePrognosisForm());
break;
case METHOD_ALTER_CARE_TIME :
//headerTable.add(getHeader(localize("child_care.alter_care_time", "Alter care time")));
headerTable.add(getHeader(localize("child_care.alter_contract_or_schooltype_for_child","Alter the contract/schooltype for this child.") + personalIdUserName));
contentTable.add(getAlterCareTimeForm(iwc));
break;
case METHOD_CANCEL_CONTRACT :
headerTable.add(getHeader(localize("child_care.cancel_contract", "Cancel contract") + personalIdUserName));
contentTable.add(getCancelContractForm(iwc));
break;
case METHOD_CHANGE_OFFER :
headerTable.add(getHeader(localize("child_care.change_offer_placing", "Change offer placing") + personalIdUserName));
contentTable.add(getChangeOfferForm(iwc));
break;
case METHOD_RETRACT_OFFER :
headerTable.add(getHeader(localize("child_care.retract_offer", "Retract offer") + personalIdUserName));
contentTable.add(getRetractOfferForm(iwc));
break;
case METHOD_ALTER_VALID_FROM_DATE :
headerTable.add(getHeader(localize("child_care.alter_valid_from_date", "Change placement date") + personalIdUserName));
contentTable.add(getChangeDateForm(iwc, true));
break;
case METHOD_VIEW_PROVIDER_QUEUE :
headerTable.add(getHeader(localize("child_care.view_provider_queue", "Provider queue")));
contentTable.add(getProviderQueueForm(iwc));
break;
case METHOD_END_CONTRACT :
headerTable.add(getHeader(localize("child_care.end_contract", "End contract") + personalIdUserName));
contentTable.add(getEndContractForm());
break;
case METHOD_NEW_CARE_TIME :
headerTable.add(getHeader(localize("child_care.new_care_time", "New care time") + personalIdUserName));
contentTable.add(getNewCareTimeForm());
break;
case METHOD_SIGN_CONTRACT :
Object[] contractFormResult = getContractSignerForm(iwc);
contentTable.add(contractFormResult[1]);
if (((Boolean) contractFormResult[0]).booleanValue()) {
headerTable.add(getHeader(localize("child_care.sign_contract", "Sign contract") + personalIdUserName));
} else {
headerTable.add(getHeader(localize("child_care.fill_in_fields", "Fill in contract fields") + personalIdUserName));
}
break;
case METHOD_REJECT_APPLICATION :
headerTable.add(getHeader(localize("child_care.reject_application", "Reject application") + personalIdUserName));
contentTable.add(getRejectApplicationForm(iwc));
break;
}
add(form);
}
private Table getPriorityForm(IWContext iwc) throws RemoteException {
Table table = new Table();
table.setCellpadding(5);
table.setWidth(Table.HUNDRED_PERCENT);
table.setHeight(Table.HUNDRED_PERCENT);
int row = 1;
String message = MessageFormat.format(localize("child_care.priority_message", "Because of special circumstances, {0} has been granted priority in our queue for a childcare placing.\n\nRegards,\n{1}\n{2}\n{3}"), getArguments(iwc));
TextArea textArea = (TextArea) getStyledInterface(new TextArea(PARAMETER_PRIORITY_MESSAGE, message));
textArea.setWidth(Table.HUNDRED_PERCENT);
textArea.setRows(7);
textArea.setAsNotEmpty(localize("child_care.priority_message_required","You must fill in the message."));
table.add(getSmallHeader(localize("child_care.priority_message_info", "The following message will be sent to BUN.")), 1, row++);
table.add(textArea, 1, row++);
SubmitButton grantPriority = (SubmitButton) getStyledInterface(new SubmitButton(localize("child_care.grant_priority", "Grant priority"), PARAMETER_ACTION, String.valueOf(ACTION_GRANT_PRIORITY)));
form.setToDisableOnSubmit(grantPriority, true);
table.add(grantPriority, 1, row);
table.add(Text.getNonBrakingSpace(), 1, row);
table.add(close, 1, row);
table.setHeight(row, Table.HUNDRED_PERCENT);
table.setRowVerticalAlignment(row, Table.VERTICAL_ALIGN_BOTTOM);
return table;
}
private Table getOfferForm(IWContext iwc) throws RemoteException {
Table table = new Table();
table.setCellpadding(5);
table.setWidth(Table.HUNDRED_PERCENT);
table.setHeight(Table.HUNDRED_PERCENT);
int row = 1;
String message = null;
if (getBusiness().isAfterSchoolApplication(_applicationID)) {
message = MessageFormat.format(localize("after_school_care.offer_message", "We can offer {0} a placing in {5} from {4}.\n\nRegards,\n{1}\n{2}\n{3}"), getArguments(iwc));
}
else {
message = MessageFormat.format(localize("child_care.offer_message", "We can offer {0} a placing in {5} from {4}.\n\nRegards,\n{1}\n{2}\n{3}"), getArguments(iwc));
}
TextArea textArea = (TextArea) getStyledInterface(new TextArea(PARAMETER_OFFER_MESSAGE, message));
textArea.setWidth(Table.HUNDRED_PERCENT);
textArea.setRows(7);
textArea.setAsNotEmpty(localize("child_care.offer_message_required","You must fill in the message."));
table.add(getSmallHeader(localize("child_care.offer_message_info", "The following message will be sent to the child's parents.")), 1, row++);
table.add(textArea, 1, row++);
IWTimestamp stamp = new IWTimestamp();
stamp.addDays(14);
IWTimestamp tomorrow = new IWTimestamp();
tomorrow.addDays(1);
DateInput dateInput = (DateInput) getStyledInterface(new DateInput(PARAMETER_OFFER_VALID_UNTIL));
dateInput.setEarliestPossibleDate(tomorrow.getDate(), localize("child_care.cant_choose_earlier_date", "You can't choose a date back in time."));
dateInput.setDate(stamp.getDate());
table.add(getSmallHeader(localize("child_care.offer_valid_until", "Offer valid until")+":"), 1, row++);
table.add(dateInput, 1, row++);
HiddenInput action = new HiddenInput(PARAMETER_ACTION);
action.setValue(String.valueOf(ACTION_OFFER));
table.add(action);
SubmitButton offer = (SubmitButton) getStyledInterface(new SubmitButton(localize("child_care.make_offer", "Make offer")));
form.setToDisableOnSubmit(offer, true);
table.add(offer, 1, row);
table.add(Text.getNonBrakingSpace(), 1, row);
table.add(close, 1, row);
table.setHeight(row, Table.HUNDRED_PERCENT);
table.setRowVerticalAlignment(row, Table.VERTICAL_ALIGN_BOTTOM);
return table;
}
private Table getChangeOfferForm(IWContext iwc) throws RemoteException {
Table table = new Table();
table.setCellpadding(5);
table.setWidth(Table.HUNDRED_PERCENT);
table.setHeight(Table.HUNDRED_PERCENT);
int row = 1;
String message = MessageFormat.format(localize("child_care.change_offer_message", "We are extending our offer for a placing for {0} in our childcare since you haven't answered our previous offer.\n\nRegards,\n{1}\n{2}\n{3}"), getArguments(iwc));
TextArea textArea = (TextArea) getStyledInterface(new TextArea(PARAMETER_OFFER_MESSAGE, message));
textArea.setWidth(Table.HUNDRED_PERCENT);
textArea.setRows(7);
textArea.setAsNotEmpty(localize("child_care.offer_message_required","You must fill in the message."));
table.add(getSmallHeader(localize("child_care.offer_message_info", "The following message will be sent to the child's parents.")), 1, row++);
table.add(textArea, 1, row++);
IWTimestamp stamp = new IWTimestamp();
stamp.addDays(14);
DateInput dateInput = (DateInput) getStyledInterface(new DateInput(PARAMETER_OFFER_VALID_UNTIL));
dateInput.setDate(stamp.getDate());
table.add(getSmallHeader(localize("child_care.offer_valid_until", "Offer valid until")+":"), 1, row++);
table.add(dateInput, 1, row++);
SubmitButton changeOffer = (SubmitButton) getStyledInterface(new SubmitButton(localize("child_care.change_offer", "Change offer"), PARAMETER_ACTION, String.valueOf(ACTION_OFFER)));
form.setToDisableOnSubmit(changeOffer, true);
table.add(changeOffer, 1, row);
table.add(Text.getNonBrakingSpace(), 1, row);
table.add(close, 1, row);
table.setHeight(row, Table.HUNDRED_PERCENT);
table.setRowVerticalAlignment(row, Table.VERTICAL_ALIGN_BOTTOM);
return table;
}
private Table getRetractOfferForm(IWContext iwc) throws RemoteException {
Table table = new Table();
table.setCellpadding(5);
table.setWidth(Table.HUNDRED_PERCENT);
table.setHeight(Table.HUNDRED_PERCENT);
int row = 1;
String message = MessageFormat.format(localize("child_care.retract_offer_message", "We have retracted our offer for {0} for a placing in our childcare because you haven't replied to our offer.\n\nRegards,\n{1}\n{2}\n{3}"), getArguments(iwc));
TextArea textArea = (TextArea) getStyledInterface(new TextArea(PARAMETER_OFFER_MESSAGE, message));
textArea.setWidth(Table.HUNDRED_PERCENT);
textArea.setRows(7);
textArea.setAsNotEmpty(localize("child_care.offer_message_required","You must fill in the message."));
table.add(getSmallHeader(localize("child_care.offer_message_info", "The following message will be sent to the child's parents.")), 1, row++);
table.add(textArea, 1, row++);
SubmitButton retract = (SubmitButton) getStyledInterface(new SubmitButton(localize("child_care.retract_offer", "Retract offer"), PARAMETER_ACTION, String.valueOf(ACTION_RETRACT_OFFER)));
form.setToDisableOnSubmit(retract, true);
table.add(retract, 1, row);
table.add(Text.getNonBrakingSpace(), 1, row);
table.add(close, 1, row);
table.setHeight(row, Table.HUNDRED_PERCENT);
table.setRowVerticalAlignment(row, Table.VERTICAL_ALIGN_BOTTOM);
return table;
}
private Table getRejectApplicationForm(IWContext iwc) throws RemoteException {
Table table = new Table();
table.setCellpadding(5);
table.setWidth(Table.HUNDRED_PERCENT);
table.setHeight(Table.HUNDRED_PERCENT);
int row = 1;
String message = MessageFormat.format(localize("child_care.reject_application_message", "We have rejected your application for {0} for a placing in {5}.\n\nRegards,\n{1}\n{2}\n{3}"), getArguments(iwc));
TextArea textArea = (TextArea) getStyledInterface(new TextArea(PARAMETER_REJECT_MESSAGE, message));
textArea.setWidth(Table.HUNDRED_PERCENT);
textArea.setRows(7);
textArea.setAsNotEmpty(localize("child_care.rejected_message_required","You must fill in the message."));
table.add(getSmallHeader(localize("child_care.offer_message_info", "The following message will be sent to the child's parents.")), 1, row++);
table.add(textArea, 1, row++);
SubmitButton reject = (SubmitButton) getStyledInterface(new SubmitButton(localize("child_care.reject_application", "Reject application"), PARAMETER_ACTION, String.valueOf(ACTION_REJECT_APPLICATION)));
table.add(reject, 1, row);
table.add(Text.getNonBrakingSpace(), 1, row);
table.add(close, 1, row);
table.setHeight(row, Table.HUNDRED_PERCENT);
table.setRowVerticalAlignment(row, Table.VERTICAL_ALIGN_BOTTOM);
return table;
}
private Table getChangeDateForm(IWContext iwc, boolean isAlteration) throws RemoteException {
Table table = new Table();
table.setCellpadding(5);
table.setWidth(Table.HUNDRED_PERCENT);
table.setHeight(Table.HUNDRED_PERCENT);
int row = 1;
ChildCareApplication application = getBusiness().getApplication(_applicationID);
DateInput dateInput = (DateInput) getStyledInterface(new DateInput(PARAMETER_CHANGE_DATE));
IWTimestamp stampNow = new IWTimestamp();
boolean oldPlacementTerminated = false;
IWTimestamp terminationDate = null;
if (restrictDates) {
if (earliestDate != null) {
dateInput.setEarliestPossibleDate(earliestDate.getDate(), localize("child_care.contract_dates_overlap", "You can not choose a date which overlaps another contract."));
dateInput.setDate(earliestDate.getDate());
terminationDate = new IWTimestamp(earliestDate);
oldPlacementTerminated = true;
}
else {
ChildCareContract archive = getBusiness().getLatestContract(_userID);
if (archive != null && archive.getTerminatedDate() != null) {
IWTimestamp stamp = new IWTimestamp(archive.getTerminatedDate());
terminationDate = new IWTimestamp(stamp);
oldPlacementTerminated = true;
stamp.addDays(1);
if (stamp.isEarlierThan(stampNow)) {
dateInput.setEarliestPossibleDate(stampNow.getDate(), localize("child_care.not_a_valid_date", "You can not choose a date back in time."));
dateInput.setDate(stampNow.getDate());
}
else {
dateInput.setEarliestPossibleDate(stamp.getDate(), localize("child_care.contract_dates_overlap", "You can not choose a date which overlaps another contract."));
dateInput.setDate(stamp.getDate());
}
}
else {
dateInput.setEarliestPossibleDate(stampNow.getDate(), localize("child_care.not_a_valid_date", "You can not choose a date back in time."));
if (application != null) {
IWTimestamp fromDate = new IWTimestamp(application.getFromDate());
if (fromDate.isLaterThan(stampNow))
dateInput.setDate(fromDate.getDate());
else
dateInput.setDate(stampNow.getDate());
}
else
dateInput.setDate(stampNow.getDate());
}
}
}
else {
dateInput.setDate(stampNow.getDate());
}
String dateHeader = null;
if (isAlteration) {
dateHeader = localize("child_care.new_date", "Select the new placement date");
} else {
dateHeader = localize("child_care.change_date", "Change date");
}
table.add(getSmallHeader(dateHeader), 1, row++);
table.add(dateInput, 1, row++);
if (oldPlacementTerminated) {
table.add(getSmallHeader(localize("child_care.old_placement_terminated", "Old placement terminated") + ":"), 1, row);
- table.add(Text.getNonBrakingSpace(), 1, row);
- table.add(getSmallErrorText(terminationDate.getLocaleDate(iwc.getCurrentLocale(), IWTimestamp.SHORT)));
+ table.add(Text.NON_BREAKING_SPACE, 1, row);
+ table.add(getSmallErrorText(terminationDate.getLocaleDate(iwc.getCurrentLocale(), IWTimestamp.SHORT)), 1, row);
+ table.add(new Break(2), 1, row);
}
if (isAlteration) {
TextInput textInput = (TextInput) getStyledInterface(new TextInput(PARAMETER_CHILDCARE_TIME));
textInput.setLength(2);
if (application != null)
textInput.setContent(String.valueOf(application.getCareTime()));
textInput.setAsNotEmpty(localize("child_care.child_care_time_required","You must fill in the child care time."));
textInput.setAsIntegers(localize("child_care.only_integers_allowed","Not a valid child care time."));
table.add(getSmallHeader(localize("child_care.enter_child_care_time", "Enter child care time:")), 1, row++);
table.add(getSmallText(localize("child_care.child_care_time", "Time")+":"), 1, row);
table.add(textInput, 1, row++);
}
//Pre-school
if (!getBusiness().isAfterSchoolApplication(application)) {
table.add(getSmallHeader(localize("child_care.pre_school", "Specify pre-school:")), 1, row++);
TextInput preSchool = (TextInput) getStyledInterface(new TextInput(PARAMETER_PRE_SCHOOL));
preSchool.setLength(40);
if (application.getPreSchool() != null)
preSchool.setContent(application.getPreSchool());
table.add(preSchool, 1, row++);
}
SubmitButton changeDate = null;
if (isAlteration)
changeDate = (SubmitButton) getStyledInterface(new SubmitButton(localize("child_care.alter_placing", "Change placing"), PARAMETER_ACTION, String.valueOf(ACTION_ALTER_VALID_FROM_DATE)));
else
changeDate = (SubmitButton) getStyledInterface(new SubmitButton(localize("child_care.change_date", "Change date"), PARAMETER_ACTION, String.valueOf(ACTION_CHANGE_DATE)));
form.setToDisableOnSubmit(changeDate, true);
table.add(changeDate, 1, row);
table.add(Text.getNonBrakingSpace(), 1, row);
table.add(close, 1, row);
table.setHeight(row, Table.HUNDRED_PERCENT);
table.setRowVerticalAlignment(row, Table.VERTICAL_ALIGN_BOTTOM);
return table;
}
private Table getPlaceInGroupForm() throws RemoteException {
Table table = new Table();
table.setCellpadding(5);
table.setWidth(Table.HUNDRED_PERCENT);
table.setHeight(Table.HUNDRED_PERCENT);
int row = 1;
ChildCareApplication application = getBusiness().getApplication(_applicationID);
+
boolean hasBankId = false;
hasBankId = new NBSLoginBusinessBean().hasBankLogin(application.getOwner());
if (hasBankId){
table.add(getSmallText(localize("child_care.child_care_time", "Time")+":"), 1, row);
table.add(getSmallText("" + application.getCareTime()), 1, row++);
table.add(new HiddenInput(PARAMETER_CHILDCARE_TIME, "" + application.getCareTime()));
} else {
TextInput textInput = (TextInput) getStyledInterface(new TextInput(PARAMETER_CHILDCARE_TIME));
textInput.setLength(2);
textInput.setAsNotEmpty(localize("child_care.child_care_time_required","You must fill in the child care time."));
textInput.setAsIntegers(localize("child_care.only_integers_allowed","Not a valid child care time."));
table.add(getSmallHeader(localize("child_care.enter_child_care_time", "Enter child care time:")), 1, row++);
table.add(getSmallText(localize("child_care.child_care_time", "Time")+":"), 1, row);
table.add(textInput, 1, row++);
}
Table dropdownTable = new Table(2, 3);
int dropRow = 1;
DropdownMenu groups = getGroups(-1, -1);
groups.addMenuElementFirst("-1","");
groups.setAsNotEmpty(localize("child_care.must_select_a_group","You must select a group. If one does not exist, you will have to create one first."), "-1");
dropdownTable.add(getSmallText(localize("child_care.group", "Group")+":"), 1, dropRow);
dropdownTable.add(groups, 2, dropRow++);
DropdownMenu schoolTypes = getSchoolTypes(-1, -1);
schoolTypes.addMenuElementFirst("-1","");
schoolTypes.setAsNotEmpty(localize("child_care.must_select_a_type","You must select a type."), "-1");
dropdownTable.add(getSmallText(localize("child_care.schooltype", "Type")+":"), 1, dropRow);
dropdownTable.add(schoolTypes, 2, dropRow++);
DropdownMenu employmentTypes = getEmploymentTypes(PARAMETER_EMPLOYMENT_TYPE, -1);
employmentTypes.setAsNotEmpty(localize("child_care.must_select_employment_type","You must select employment type."), "-1");
dropdownTable.add(getSmallText(localize("child_care.employment_type", "Employment type")+":"), 1, dropRow);
dropdownTable.add(employmentTypes, 2, dropRow);
table.add(dropdownTable, 1, row++);
SubmitButton placeInGroup = (SubmitButton) getStyledInterface(new SubmitButton(localize("child_care.place_in_group", "Place in group"), PARAMETER_ACTION, String.valueOf(ACTION_PLACE_IN_GROUP)));
form.setToDisableOnSubmit(placeInGroup, true);
table.add(placeInGroup, 1, row);
table.add(Text.getNonBrakingSpace(), 1, row);
table.add(close, 1, row);
table.setHeight(row, Table.HUNDRED_PERCENT);
table.setRowVerticalAlignment(row, Table.VERTICAL_ALIGN_BOTTOM);
return table;
}
private Table getAlterCareTimeForm(IWContext iwc) throws RemoteException {
Table table = new Table();
table.setCellpadding(5);
table.setWidth(Table.HUNDRED_PERCENT);
table.setHeight(Table.HUNDRED_PERCENT);
int row = 1;
ChildCareApplication application = getBusiness().getApplication(_applicationID);
ChildCareContract archive = getBusiness().getValidContract(((Integer)application.getPrimaryKey()).intValue());
//getBusiness().getContractFile(application.getContractFileId());
TextInput textInput = (TextInput) getStyledInterface(new TextInput(PARAMETER_CHILDCARE_TIME));
textInput.setLength(2);
textInput.setAsNotEmpty(localize("child_care.child_care_time_required","You must fill in the child care time."));
textInput.setAsIntegers(localize("child_care.only_integers_allowed","Not a valid child care time."));
if(archive.getCareTime()>0)
textInput.setContent(String.valueOf(archive.getCareTime()));
table.add(new HiddenInput("ccc_old_archive_id",archive.getPrimaryKey().toString()));
table.add(getSmallHeader(localize("child_care.enter_child_care_time", "Enter child care time:")), 1, row++);
table.add(getSmallText(localize("child_care.child_care_time", "Time")+":"), 1, row);
table.add(textInput, 1, row++);
DateInput dateInput = (DateInput) getStyledInterface(new DateInput(PARAMETER_CHANGE_DATE));
IWTimestamp validFrom = new IWTimestamp(archive.getValidFromDate());
//validFrom.addDays(1);
dateInput.setDate(validFrom.getDate());
if (restrictDates) {
IWTimestamp stamp = new IWTimestamp();
if (archive != null) {
//IWTimestamp validFrom = new IWTimestamp(archive.getValidFromDate());
//validFrom.addDays(1);
//dateInput.setDate(validFrom.getDate());
if (validFrom.isEarlierThan(stamp))
{
if(onlyAllowFutureCareDate){
dateInput.setEarliestPossibleDate(stamp.getDate(), localize("child_care.not_a_valid_date", "You can not choose a date back in time."));
}
}
else{
dateInput.setEarliestPossibleDate(validFrom.getDate(), localize("child_care.contract_dates_overlap", "You can not choose a date which overlaps another contract."));
}
if (archive.getTerminatedDate() != null) {
IWTimestamp terminated = new IWTimestamp(archive.getTerminatedDate());
dateInput.setLatestPossibleDate(terminated.getDate(), localize("child_care.contract_date_expired", "You can not choose a date after the contract has been terminated."));
}
}
else {
dateInput.setDate(new IWTimestamp().getDate());
dateInput.setEarliestPossibleDate(stamp.getDate(), localize("child_care.not_a_valid_date", "You can not choose a date back in time."));
}
}
else {
if (archive.getTerminatedDate() != null) {
IWTimestamp terminated = new IWTimestamp(archive.getTerminatedDate());
dateInput.setLatestPossibleDate(terminated.getDate(), localize("child_care.contract_date_expired", "You can not choose a date after the contract has been terminated."));
}
}
dateInput.setAsNotEmpty(localize("child_care.must_select_date","You must select a date."));
IWTimestamp earliestDate = IWTimestamp.RightNow();
dateInput.setEarliestPossibleDate(earliestDate.getDate(), localize("child_care.not_a_valid_date", "You can not choose a date back in time."));
table.add(getSmallHeader(localize("child_care.new_date", "Select the new placement date")), 1, row++);
table.add(dateInput, 1, row++);
/* New requirements: Add Schooltype and Group dropdowns */
// Schooltype change :
// Group change, (school class)
//DropdownMenu schoolTypes = new DropdownMenu(PARAMETER_SCHOOL_TYPES);
Collection types = null;
try {
types = application.getProvider().findRelatedSchoolTypes();
} catch (IDORelationshipException e) {
e.printStackTrace();
} catch (EJBException e) {
e.printStackTrace();
}
SchoolClassDropdownDouble schoolClasses = new SchoolClassDropdownDouble(PARAMETER_SCHOOL_TYPES,PARAMETER_SCHOOL_CLASS);
schoolClasses.setLayoutVertical(true);
schoolClasses.setPrimaryLabel(getSmallText(localize("child_care.school_type", "School type")));
schoolClasses.setSecondaryLabel(getSmallText(localize("child_care.school_class", "School class")));
schoolClasses.setVerticalSpaceBetween(15);
schoolClasses.setSpaceBetween(15);
schoolClasses.setNoDataListEntry(localize("child_care.no_school_classes","No school classes"));
schoolClasses = (SchoolClassDropdownDouble) getStyledInterface(schoolClasses);
//int classID = archive.getSchoolClassMember().getSchoolClassId();
if (getChildcareID() != -1) {
if (!types.isEmpty()) {
SchoolCommuneBusiness sb = (SchoolCommuneBusiness) IBOLookup.getServiceInstance(iwc,SchoolCommuneBusiness.class);
Map typeGroupMap = sb.getSchoolTypeClassMap(types,application.getProviderId() , getSession().getSeasonID(), null,null,localize("child_care.no_school_classes","No school classes"));
if (typeGroupMap != null) {
Iterator iter = typeGroupMap.keySet().iterator();
while (iter.hasNext()) {
SchoolType schoolType = (SchoolType) iter.next();
schoolClasses.addMenuElement(schoolType.getPrimaryKey().toString(), schoolType.getSchoolTypeName(), (Map) typeGroupMap.get(schoolType));
}
}
}
}
SchoolClassMember currentClassMember = archive.getSchoolClassMember();
if (currentClassMember !=null)
schoolClasses.setSelectedValues(String.valueOf(currentClassMember.getSchoolTypeId()),String.valueOf(currentClassMember.getSchoolClassId()));
table.add(schoolClasses, 1, row++);
DropdownMenu employmentTypes = getEmploymentTypes(PARAMETER_EMPLOYMENT_TYPE, -1);
if(archive.getEmploymentTypeId()>0)
employmentTypes.setSelectedElement(archive.getEmploymentTypeId());
employmentTypes.setAsNotEmpty(localize("child_care.must_select_employment_type","You must select employment type."), "-1");
employmentTypes = (DropdownMenu) getStyledInterface(employmentTypes);
table.add(getSmallText(localize("child_care.employment_type", "Employment type")+":"), 1, row);
table.add(Text.getNonBrakingSpace(), 1, row);
table.add(employmentTypes, 1, row++);
SubmitButton placeInGroup = (SubmitButton) getStyledInterface(new SubmitButton(localize("child_care.alter_care_time", "Alter care time"), PARAMETER_ACTION, String.valueOf(ACTION_ALTER_CARE_TIME)));
form.setToDisableOnSubmit(placeInGroup, true);
table.add(placeInGroup, 1, row);
table.add(Text.getNonBrakingSpace(), 1, row);
table.add(close, 1, row);
table.setHeight(row, Table.HUNDRED_PERCENT);
table.setRowVerticalAlignment(row, Table.VERTICAL_ALIGN_BOTTOM);
return table;
}
private Table getCancelContractForm(IWContext iwc) throws RemoteException {
Table table = new Table();
table.setCellpadding(5);
table.setWidth(Table.HUNDRED_PERCENT);
table.setHeight(Table.HUNDRED_PERCENT);
int row = 1;
ChildCareApplication application = getBusiness().getApplicationForChildAndProvider(_userID, getSession().getChildCareID());
boolean canCancel = getBusiness().canCancelContract(((Integer)application.getPrimaryKey()).intValue());
if (canCancel) {
RadioButton parentalLeave = this.getRadioButton(PARAMETER_CANCEL_REASON, String.valueOf(true));
parentalLeave.keepStatusOnAction(true);
RadioButton other = getRadioButton(PARAMETER_CANCEL_REASON, String.valueOf(false));
other.keepStatusOnAction(true);
if (!iwc.isParameterSet(PARAMETER_CANCEL_REASON))
other.setSelected(true);
table.add(getSmallHeader(localize("child_care.enter_cancel_information", "Enter cancel information:")), 1, row++);
table.add(parentalLeave, 1, row);
table.add(getSmallText(Text.NON_BREAKING_SPACE + localize("child_care.cancel_parental_leave", "Cancel because of parental leave")), 1, row);
table.add(new Break(), 1, row);
table.add(other, 1, row);
table.add(getSmallText(Text.NON_BREAKING_SPACE + localize("child_care.cancel_other", "Other reason")), 1, row++);
TextArea textArea = (TextArea) getStyledInterface(new TextArea(PARAMETER_CANCEL_MESSAGE));
textArea.setWidth(Table.HUNDRED_PERCENT);
textArea.setRows(4);
textArea.setAsNotEmpty(localize("child_care.offer_message_required","You must fill in the message."));
textArea.keepStatusOnAction(true);
table.add(getSmallHeader(localize("child_care.cancel_reason_message", "Reason for cancel")+":"), 1, row++);
table.add(textArea, 1, row++);
IWTimestamp stampNow = new IWTimestamp();
stampNow.addDays(-1);
IWTimestamp stamp = new IWTimestamp();
stamp.addMonths(2);
DateInput dateInput = (DateInput) getStyledInterface(new DateInput(PARAMETER_CANCEL_DATE));
dateInput.setDate(stamp.getDate());
if (restrictDates)
dateInput.setEarliestPossibleDate(stampNow.getDate(), localize("child_care.not_a_valid_date", "You can not choose a date back in time."));
dateInput.setAsNotEmpty(localize("child_care.must_select_date","You must select a date."));
dateInput.keepStatusOnAction(true);
table.add(getSmallHeader(localize("child_care.cancel_date", "Cancel date")+":"), 1, row++);
table.add(dateInput, 1, row++);
SubmitButton placeInGroup = (SubmitButton) getStyledInterface(new SubmitButton(localize("child_care.cancel_contract", "Cancel contract"), PARAMETER_ACTION, String.valueOf(ACTION_CANCEL_CONTRACT)));
form.setToDisableOnSubmit(placeInGroup, true);
table.add(placeInGroup, 1, row);
table.add(Text.getNonBrakingSpace(), 1, row);
}
else {
table.add(getSmallErrorText(localize("child_care.must_remove_future_contracts", "Future contracts must be removed before cancel is possible.")), 1, row++);
}
table.add(close, 1, row);
table.setHeight(row, Table.HUNDRED_PERCENT);
table.setRowVerticalAlignment(row, Table.VERTICAL_ALIGN_BOTTOM);
return table;
}
private Table getCreateGroupForm() throws RemoteException {
Table table = new Table();
table.setCellpadding(5);
table.setWidth(Table.HUNDRED_PERCENT);
table.setHeight(Table.HUNDRED_PERCENT);
int row = 1;
TextInput textInput = (TextInput) getStyledInterface(new TextInput(PARAMETER_GROUP_NAME));
textInput.setLength(24);
textInput.setAsNotEmpty(localize("child_care.group_name_required","You must fill in a name for the group."));
SchoolType currentType = null;
if (getSession().getGroupID() != -1) {
SchoolClass group = getBusiness().getSchoolBusiness().findSchoolClass(new Integer(getSession().getGroupID()));
currentType = group.getSchoolType();
if (group.getSchoolClassName() != null)
textInput.setContent(group.getSchoolClassName());
}
table.add(getSmallHeader(localize("child_care.enter_group_name", "Enter group name:")), 1, row++);
table.add(getSmallText(localize("child_care.group_name", "Name")), 1, row);
table.add(textInput, 1, row++);
//school types
School school = getSession().getProvider();
Collection availableTypes = new ArrayList();
try{
availableTypes = school.getSchoolTypes();
}catch(IDORelationshipException ex){
ex.printStackTrace();
}
DropdownMenu types = getDropdownMenuLocalized(PARAMETER_SCHOOL_TYPES, availableTypes, "getLocalizationKey", "");
if (currentType != null){
types.setSelectedElement(localize(currentType.getLocalizationKey(), ""));
}
table.add(getSmallHeader(localize("child_care.choose_school_type", "Choose school type:")), 1, row++);
table.add(getSmallText(localize("child_care.school_type", "School type")), 1, row);
table.add(types, 1, row++);
String localized = "";
if (getSession().getGroupID() != -1)
localized = localize("child_care.change_group", "Change group");
else
localized = localize("child_care.create_group", "Create group");
SubmitButton createGroup = (SubmitButton) getStyledInterface(new SubmitButton(localized, PARAMETER_ACTION, String.valueOf(ACTION_CREATE_GROUP)));
form.setToDisableOnSubmit(createGroup, true);
table.add(createGroup, 1, row);
table.add(Text.getNonBrakingSpace(), 1, row);
table.add(close, 1, row);
table.setHeight(row, Table.HUNDRED_PERCENT);
table.setRowVerticalAlignment(row, Table.VERTICAL_ALIGN_BOTTOM);
return table;
}
private Table getMoveGroupForm(IWContext iwc) throws RemoteException {
Table table = new Table();
table.setCellpadding(5);
table.setWidth(Table.HUNDRED_PERCENT);
table.setHeight(Table.HUNDRED_PERCENT);
int row = 1;
int oldGroup = Integer.parseInt(iwc.getParameter(PARAMETER_OLD_GROUP));
DropdownMenu groups = getGroups(-1, oldGroup);
groups.addMenuElementFirst("-1","");
groups.setAsNotEmpty(localize("child_care.must_select_a_group","You must select a group. If one does not exist, you will have to create one first."), "-1");
table.add(getSmallHeader(localize("child_care.select_group", "Select group to move child to")), 1, row++);
table.add(getSmallText(localize("child_care.group", "Group")+":"), 1, row);
table.add(groups, 1, row++);
SubmitButton placeInGroup = (SubmitButton) getStyledInterface(new SubmitButton(localize("child_care.move_group", "Move to group"), PARAMETER_ACTION, String.valueOf(ACTION_MOVE_TO_GROUP)));
form.setToDisableOnSubmit(placeInGroup, true);
table.add(placeInGroup, 1, row);
table.add(Text.getNonBrakingSpace(), 1, row);
table.add(close, 1, row);
table.setHeight(row, Table.HUNDRED_PERCENT);
table.setRowVerticalAlignment(row, Table.VERTICAL_ALIGN_BOTTOM);
return table;
}
private Table getUpdatePrognosisForm() throws RemoteException {
Table table = new Table();
table.setCellpadding(5);
table.setWidth(Table.HUNDRED_PERCENT);
table.setHeight(Table.HUNDRED_PERCENT);
int row = 1;
ChildCarePrognosis prognosis = getBusiness().getPrognosis(getSession().getChildCareID());
table.mergeCells(1, row, 4, row);
table.add(getSmallHeader(localize("child_care.prognosis_information","Enter the prognosis information for your childcare.")), 1, row++);
table.mergeCells(1, row, 2, row);
table.add(getSmallHeader(localize("child_care.enter_prognosis", "Enter prognosis:")), 1, row++);
TextInput threeMonths = (TextInput) getStyledInterface(new TextInput(PARAMETER_THREE_MONTHS_PROGNOSIS));
threeMonths.setLength(3);
threeMonths.setAsNotEmpty(localize("child_care.three_months_prognosis_required","You must fill in the three months prognosis."));
threeMonths.setAsIntegers(localize("child_care.only_integers_allowed","Not a valid prognosis."));
if (prognosis != null)
threeMonths.setContent(String.valueOf(prognosis.getThreeMonthsPrognosis()));
TextInput threeMonthsPriority = (TextInput) getStyledInterface(new TextInput(PARAMETER_THREE_MONTHS_PRIORITY));
threeMonthsPriority.setLength(3);
threeMonthsPriority.setAsNotEmpty(localize("child_care.three_months_priority_required","You must fill in the three months priority."));
threeMonthsPriority.setAsIntegers(localize("child_care.only_integers_allowed","Not a valid prognosis."));
if (prognosis != null && prognosis.getThreeMonthsPriority() != -1)
threeMonthsPriority.setContent(String.valueOf(prognosis.getThreeMonthsPriority()));
table.add(getSmallText(localize("child_care.three_months_prognosis", "Three months prognosis")+":"), 1, row);
table.add(threeMonths, 2, row);
table.add(getSmallText(localize("child_care.thereof_priority", "there of priority")+":"), 3, row);
table.add(threeMonthsPriority, 4, row++);
TextInput oneYear = (TextInput) getStyledInterface(new TextInput(PARAMETER_ONE_YEAR_PROGNOSIS));
oneYear.setLength(3);
oneYear.setAsNotEmpty(localize("child_care.one_year_prognosis_required","You must fill in the one year prognosis."));
oneYear.setAsIntegers(localize("child_care.only_integers_allowed","Not a valid prognosis."));
if (prognosis != null)
oneYear.setContent(String.valueOf(prognosis.getOneYearPrognosis()));
TextInput oneYearPriority = (TextInput) getStyledInterface(new TextInput(PARAMETER_ONE_YEAR_PRIORITY));
oneYearPriority.setLength(3);
oneYearPriority.setAsNotEmpty(localize("child_care.one_year_priority_required","You must fill in the one year priority."));
oneYearPriority.setAsIntegers(localize("child_care.only_integers_allowed","Not a valid prognosis."));
if (prognosis != null && prognosis.getOneYearPriority() != -1)
oneYearPriority.setContent(String.valueOf(prognosis.getOneYearPriority()));
table.add(getSmallText(localize("child_care.one_year_prognosis", "Twelve months prognosis")+":"), 1, row);
table.add(oneYear, 2, row);
table.add(getSmallText(localize("child_care.thereof_priority", "there of priority")+":"), 3, row);
table.add(oneYearPriority, 4, row++);
////////////////// added provider capacity 040402 Malin
table.mergeCells(1, row, 4, row);
table.add(getSmallHeader(localize("child_care.capacity_information","Enter the provider capacity.")), 1, row++);
table.mergeCells(2, row, 4, row);
TextInput providerCapacity = (TextInput) getStyledInterface(new TextInput(PARAMETER_PROVIDER_CAPACITY));
providerCapacity.setLength(3);
providerCapacity.setAsNotEmpty(localize("child_care.capacity_required","You must fill in the provider capacity."));
providerCapacity.setAsIntegers(localize("child_care.capacity_only_integers_allowed","Not a valid number."));
if (prognosis != null && prognosis.getProviderCapacity() != -1)
providerCapacity.setContent(String.valueOf(prognosis.getProviderCapacity()));
table.add(getSmallText(localize("child_care.provider_capacity", "Provider capacity")+":"), 1, row);
table.add(providerCapacity, 2, row);
table.add("", 3, row++);
SubmitButton updatePrognosis = (SubmitButton) getStyledInterface(new SubmitButton(localize("child_care.set_prognosis", "Set prognosis"), PARAMETER_ACTION, String.valueOf(ACTION_UPDATE_PROGNOSIS)));
form.setToDisableOnSubmit(updatePrognosis, true);
table.add(updatePrognosis, 1, row);
table.add(Text.getNonBrakingSpace(), 1, row);
table.add(close, 1, row);
table.mergeCells(1, row, 2, row);
table.setHeight(row, Table.HUNDRED_PERCENT);
table.setRowVerticalAlignment(row, Table.VERTICAL_ALIGN_BOTTOM);
return table;
}
/**
* Shows the providerqueue without personal information. Used by citizen.
* @param iwc
* @return
* @throws Exception
*/
private Table getProviderQueueForm(IWContext iwc) throws RemoteException {
String providerId = iwc.getParameter(CCConstants.PROVIDER_ID);
String appId = iwc.getParameter(CCConstants.APPID);
School school = getBusiness().getSchoolBusiness().getSchool(providerId);
ChildCarePrognosis prognosis = getBusiness().getPrognosis(Integer.parseInt(providerId));
String prognosisText = prognosis == null ? localize("ccpqw_no_prognosis", "No prognosis available") :
localize("ccpqw_three_months", "Three months:") +" " + prognosis.getThreeMonthsPrognosis()+ " " +
localize("ccpqw_one_year", "One year:") + " " + prognosis.getOneYearPrognosis() + " " +
localize("ccpqw_updated_date", "Updated date:") + " " + prognosis.getUpdatedDate();
Table appTbl = new Table();
// add(new Text("ProviderId: " + providerId));
if (providerId != null){
Collection applications = getBusiness().getOpenAndGrantedApplicationsByProvider(new Integer(providerId).intValue());
Iterator i = applications.iterator();
appTbl.add(getSmallHeader(localize("ccpqw_order", "Queue number")), 1, 1);
appTbl.add(getSmallHeader(localize("ccpqw_queue_date", "Queue date")), 2, 1);
appTbl.add(getSmallHeader(localize("ccpqw_from_date", "Placement date")), 3, 1);
appTbl.setRowColor(1, getHeaderColor());
int row = 2;
while(i.hasNext()){
ChildCareApplication app = (ChildCareApplication) i.next();
Text queueOrder = getSmallText("" + getBusiness().getNumberInQueue(app)),
queueDate = getSmallText(app.getQueueDate().toString()),
fromDate = getSmallText(app.getFromDate().toString());
// currentAppId = style.getSmallText(""+app.getNodeID()); //debug only
appTbl.add(queueOrder, 1, row);
appTbl.add(queueDate, 2, row);
appTbl.add(fromDate, 3, row);
// appTbl.add(currentAppId, 4, row); //debug only
if (app.getNodeID() == new Integer(appId).intValue()){
makeBlueAndBold(queueOrder);
makeBlueAndBold(queueDate);
makeBlueAndBold(fromDate);
}
if (row % 2 == 0) {
appTbl.setRowColor(row, getZebraColor1());
} else {
appTbl.setRowColor(row, getZebraColor2());
}
row++;
}
}
Table layoutTbl = new Table();
layoutTbl.setCellpadding(5);
layoutTbl.setWidth(Table.HUNDRED_PERCENT);
layoutTbl.setHeight(Table.HUNDRED_PERCENT);
int row = 1;
layoutTbl.add(getSmallHeader(localize("ccpqw_provider", "Provider") + ":"), 1, row);
layoutTbl.add(getSmallText(school.getName()), 2, row++);
layoutTbl.setRowHeight(2, "20px");
layoutTbl.add(getSmallHeader(localize("ccpqw_prognosisr", "Prognosis") + ":"), 1, row);
layoutTbl.add(getSmallText(prognosisText), 2, row++);
layoutTbl.setRowHeight(row++, "20px");
layoutTbl.add(appTbl, 1, row);
layoutTbl.mergeCells(1, row, 2, row);
row++;
layoutTbl.add(close, 1, row);
layoutTbl.setHeight(row, Table.HUNDRED_PERCENT);
layoutTbl.setRowVerticalAlignment(row, Table.VERTICAL_ALIGN_BOTTOM);
// CloseButton closeBtn = (CloseButton) getStyledInterface(new CloseButton(localize("ccpqw_close", "Close")));
// layoutTbl.add(closeBtn, 1, 6);
// layoutTbl.setAlignment(1, 6, "left");
return layoutTbl;
}
private Text makeBlueAndBold(Text t){
t.setBold(true);
t.setStyleAttribute("color:blue");
return t;
}
private Table getEndContractForm() {
Table layoutTbl = new Table();
layoutTbl.setCellpadding(5);
layoutTbl.setWidth(Table.HUNDRED_PERCENT);
layoutTbl.setHeight(Table.HUNDRED_PERCENT);
int row = 1;
layoutTbl.add(getSmallHeader(localize("ccnctw_from_date", "From date") + ":"), 1, row);
DateInput fromDate = (DateInput) getStyledInterface(new DateInput(PARAMETER_CHANGE_DATE));
fromDate.setAsNotEmpty(localize("ccecw_date_format_alert", "Please choose a valid from date."));
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 2);
fromDate.setEarliestPossibleDate(cal.getTime(), localize("ccecw_date_alert", "Date must be not earlier than two months from today."));
layoutTbl.add(fromDate, 2, row++);
SubmitButton submit = (SubmitButton) getStyledInterface(new SubmitButton(localize("cc_ok", "Submit"), PARAMETER_ACTION, String.valueOf(ACTION_END_CONTRACT)));
form.setToDisableOnSubmit(submit, true);
layoutTbl.add(submit, 1, row);
layoutTbl.add(Text.getNonBrakingSpace(), 1, row);
layoutTbl.add(close, 1, row);
layoutTbl.setHeight(row, Table.HUNDRED_PERCENT);
layoutTbl.setRowVerticalAlignment(row, Table.VERTICAL_ALIGN_BOTTOM);
return layoutTbl;
}
private Table getNewCareTimeForm() throws RemoteException {
Table layoutTbl = new Table();
layoutTbl.setCellpadding(5);
layoutTbl.setWidth(Table.HUNDRED_PERCENT);
layoutTbl.setHeight(Table.HUNDRED_PERCENT);
ChildCareApplication application = getBusiness().getApplication(_applicationID);
int row = 1;
layoutTbl.add(getSmallHeader(localize("ccnctw_info", "Info about care time.")), 1, row++);
layoutTbl.add(
getSmallHeader(localize("ccnctw_care_time", "Care time") + ":"),
1,
row);
TextInput careTime = (TextInput) getStyledInterface(new TextInput(PARAMETER_CHILDCARE_TIME));
careTime.setValue(application.getCareTime());
careTime.setAsIntegers(localize("ccnctw_alert_care_time_format", "Care time must be an integer"));
careTime.setLength(4);
layoutTbl.add(careTime, 2, row++);
layoutTbl.add(
getSmallHeader(localize("ccnctw_from_date", "From date") + ":"),
1,
row);
DateInput fromDate = (DateInput) getStyledInterface(new DateInput(PARAMETER_CHANGE_DATE));
fromDate.setAsNotEmpty(localize("ccnctw_unvalid_date_format_alert", "Please choose a valid from date."));
if(onlyAllowFutureCareDate){
fromDate.setEarliestPossibleDate(
new Date(),
localize("ccnctw_unvalid_date_alert", "The date most be in the future."));
}
layoutTbl.add(fromDate, 2, row++);
row++;
SubmitButton submit = (SubmitButton) getStyledInterface(new SubmitButton(localize("cc_ok", "Submit"), PARAMETER_ACTION, String.valueOf(ACTION_NEW_CARE_TIME)));
form.setToDisableOnSubmit(submit, true);
layoutTbl.add(submit, 1, row);
layoutTbl.add(Text.getNonBrakingSpace(), 1, row);
layoutTbl.add(close, 1, row);
layoutTbl.setHeight(row, Table.HUNDRED_PERCENT);
layoutTbl.setRowVerticalAlignment(row, Table.VERTICAL_ALIGN_BOTTOM);
return layoutTbl;
}
/**
*
* @param iwc
* @return Object array of size 2, first (Boolean) is true iff signwindow is shown, second is the Table containing the form
* @throws Exception
*/
private Object[] getContractSignerForm(IWContext iwc) throws Exception {
Table table = null;
Contract contract = getContract(iwc);
if (contract.isSigned()) {
table = new Table();
table.setCellpadding(5);
table.setWidth(Table.HUNDRED_PERCENT);
table.setHeight(Table.HUNDRED_PERCENT);
table.add(getHeader(localize("ccconsign_issigned", "The contract is signed.")), 1, 1);
table.add(close, 1, 2);
table.setHeight(2, Table.HUNDRED_PERCENT);
table.setRowVerticalAlignment(2, Table.VERTICAL_ALIGN_BOTTOM);
((Window) getParentObject()).setParentToReload();
return new Object[]{new Boolean(false), table};
} else {
//Storing all fields set in this request
Map fieldValues = new HashMap();
Enumeration parameters = iwc.getRequest().getParameterNames();
while(parameters.hasMoreElements()){
String name = (String) parameters.nextElement();
if (name.startsWith(PARAMETER_TEXT_FIELD)){
String value = iwc.getParameter(name);
if (value != null && value.length() != 0) {
fieldValues.put(name.substring(PARAMETER_TEXT_FIELD.length()), iwc.getParameter(name));
ChildCareApplication application = getBusiness().getChildCareContractArchiveHome().findApplicationByContract(((Integer)contract.getPrimaryKey()).intValue()).getApplication();
if (name.equals(PARAMETER_TEXT_FIELD + "care-time")){
application.setCareTime(Integer.parseInt(value));
application.store();
}
}
}
}
contract.setUnsetFields(fieldValues);
ContractTagHome contractHome = (ContractTagHome) IDOLookup.getHome(ContractTag.class);
Collection tags = contractHome.findAllByCategory(contract.getCategoryId().intValue());
//create form for still unset fields
table = getContractFieldsForm(contract.getUnsetFields(), tags);
if (table != null && table.getRows() > 1){
return new Object[]{new Boolean(false), table};
} else {
//TODO: (Roar) Not working...
((Window) getParentObject()).setWidth(700);
((Window) getParentObject()).setHeight(400);
return new Object[]{new Boolean(true), initSignContract(iwc)};
}
}
}
private Table getContractFieldsForm(Set fields, Collection tags) {
Table table = null;
if (fields.size() != 0){
int row = 1;
Iterator i = fields.iterator();
//loops through contract fields and add them to the form
while (i.hasNext()) {
String field = (String) i.next();
if (! field.equalsIgnoreCase(FIELD_CURRENT_DATE)) { ///the currentdate field is given value when signing
if (table == null){
table = new Table();
table.setCellpadding(5);
table.setWidth(Table.HUNDRED_PERCENT);
table.setHeight(Table.HUNDRED_PERCENT);
table.add(getHeader(localize("ccconsign_formHeading", "Please, fill out the contract fields")), 1, row++);
table.mergeCells(1, 1, 2, 1);
}
Iterator itags = tags.iterator();
TextInput input = new TextInput(PARAMETER_TEXT_FIELD + field);
//search for tag with same name and look up type information
while (itags.hasNext()) {
ContractTag tag = (ContractTag) itags.next();
if (tag.getName().equals(field)) {
if (tag.getType() != null && tag.getType().equals(java.lang.Integer.class)){
input.setAsIntegers(localize("ccconsign_integer", "Use numbers only for " + field + "."));
}
}
}
String fieldPrompt = field.substring(0, 1).toUpperCase() + field.substring(1).toLowerCase();
table.add(getSmallHeader(localize("ccconsign_ " + fieldPrompt, fieldPrompt) + ":"), 1, row);
table.add(getStyledInterface(input), 2, row);
row ++;
}
}
if (table != null){
HiddenInput action = new HiddenInput(PARAMETER_METHOD, String.valueOf(METHOD_SIGN_CONTRACT));
table.add(action);
SubmitButton submit = (SubmitButton) getStyledInterface(new SubmitButton(localize("cc_ok", "Submit")));
table.add(submit, 1, row);
table.add(Text.getNonBrakingSpace(), 1, row);
table.add(close, 1, row);
table.setHeight(row, Table.HUNDRED_PERCENT);
table.setRowVerticalAlignment(row, Table.VERTICAL_ALIGN_BOTTOM);
}
}
return table;
}
private Table initSignContract(IWContext iwc){
Contract contract = getContract(iwc);
//Setting current date
Map fields = new HashMap();
final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, iwc.getCurrentLocale());
fields.put(FIELD_CURRENT_DATE, dateFormat.format(new Date()));
contract.setUnsetFields(fields);
contract.store();
iwc.setSessionAttribute(NBSSigningBlock.NBS_SIGNED_ENTITY,
new NBSSignedEntity() {
private Contract _contract = null;
public Object init(Contract contract){
_contract = contract;
return this;
}
public void setXmlSignedData(String data) {
_contract.setXmlSignedData(data);
}
public void setSignedBy(int userId) {
_contract.setSignedBy(new Integer(userId));
}
public void setSignedDate(java.sql.Date time) {
_contract.setSignedDate(time);
}
public void setSignedFlag(boolean flag) {
_contract.setSignedFlag(new Boolean(flag));
}
public void setText(String text) {
_contract.setText(text);
}
public void store() {
_contract.store();
}
public String getText() {
return _contract.getText();
}
}
.init(contract)
);
Table table = new Table();
Text heading = getLocalizedHeader("ccconsign_read_before_sign", "Read through the contrat and sign by using your BankId password. Then click OK.");
table.add(heading, 1, 1);
//table.setHeight(1, 1, Table.HUNDRED_PERCENT);
table.setVerticalAlignment(1, 1, "MIDDLE");
NBSSigningBlock nbsSigningBlock = new NBSSigningBlock();
nbsSigningBlock.setParameter(PARAMETER_ACTION, ""+ACTION_SIGN_CONTRACT);
nbsSigningBlock.setParameter(PARAMETER_METHOD, ""+METHOD_SIGN_CONTRACT);
nbsSigningBlock.setParameter(PARAMETER_CONTRACT_ID, contract.getPrimaryKey().toString());
table.add(nbsSigningBlock, 1, 2);
CloseButton closeBtn = new CloseButton(localize("ccconsign_CANCEL", "avbryt"));
closeBtn.setAsImageButton(true);
table.add(closeBtn, 1, 3);
table.setHeight(3, Table.HUNDRED_PERCENT);
table.setRowVerticalAlignment(3, Table.VERTICAL_ALIGN_BOTTOM);
return table;
}
private void processSignContract(IWContext iwc) throws Exception{
NBSSigningBlock nbsSigningBlock = new NBSSigningBlock();
nbsSigningBlock.processSignContract(iwc);
ChildCareApplication application = getBusiness().getChildCareContractArchiveHome().findApplicationByContract(((Integer)getContract(iwc).getPrimaryKey()).intValue()).getApplication();
User owner = application.getOwner();
com.idega.core.user.data.User child = UserBusiness.getUser(application.getChildId());
getBusiness().sendMessageToProvider(
application,
localize("ccecw_signcon_subject", "Contract signed"),
owner.getName() + " " + localize("ccecw_signcon_body", " has signed the contract for ") + " " +
child.getName() + " " + child.getPersonalID() + ".");
}
/**
*
* @param iwc
* @return the contract specified by the ChildCareContractSigner_CONTRACT_ID parameter, null if errors or no contract
*/
private Contract getContract(IWContext iwc) {
int contractId;
Contract contract = null;
try {
contractId = Integer.parseInt(iwc.getParameter(PARAMETER_CONTRACT_ID));
contract = ((ContractHome) IDOLookup.getHome(Contract.class))
.findByPrimaryKey(new Integer(contractId));
}catch(NumberFormatException ex){
ex.printStackTrace();
} catch(FinderException ex){
ex.printStackTrace();
} catch(IDOLookupException ex){
ex.printStackTrace();
}
return contract;
}
private void parse(IWContext iwc) {
if (iwc.isParameterSet(PARAMETER_METHOD))
_method = Integer.parseInt(iwc.getParameter(PARAMETER_METHOD));
if (iwc.isParameterSet(PARAMETER_ACTION))
_action = Integer.parseInt(iwc.getParameter(PARAMETER_ACTION));
if (iwc.isParameterSet(PARAMETER_USER_ID))
_userID = Integer.parseInt(iwc.getParameter(PARAMETER_USER_ID));
if (iwc.isParameterSet(PARAMETER_APPLICATION_ID))
_applicationID = Integer.parseInt(iwc.getParameter(PARAMETER_APPLICATION_ID));
if (iwc.isParameterSet(PARAMETER_PLACEMENT_ID))
_placementID = Integer.parseInt(iwc.getParameter(PARAMETER_PLACEMENT_ID));
if (iwc.isParameterSet(PARAMETER_PAGE_ID))
_pageID = Integer.parseInt(iwc.getParameter(PARAMETER_PAGE_ID));
if (iwc.isParameterSet(PARAMETER_EARLIEST_DATE))
earliestDate = new IWTimestamp(iwc.getParameter(PARAMETER_EARLIEST_DATE));
String restrict = getBundle().getProperty(PROPERTY_RESTRICT_DATES, "false");
restrictDates = false;
if (restrict != null) {
restrictDates = Boolean.valueOf(restrict).booleanValue();
}
}
private void alterCareTime(IWContext iwc) throws RemoteException {
IWTimestamp validFrom = new IWTimestamp(iwc.getParameter(PARAMETER_CHANGE_DATE));
int childCareTime = Integer.parseInt(iwc.getParameter(PARAMETER_CHILDCARE_TIME));
int employmentType = Integer.parseInt(iwc.getParameter(PARAMETER_EMPLOYMENT_TYPE));
int schoolTypeId = -1;
if(iwc.isParameterSet(PARAMETER_SCHOOL_TYPES))
schoolTypeId = Integer.parseInt(iwc.getParameter(PARAMETER_SCHOOL_TYPES));
int schoolClassId = -1;
if(iwc.isParameterSet(PARAMETER_SCHOOL_CLASS))
schoolClassId = Integer.parseInt(iwc.getParameter(PARAMETER_SCHOOL_CLASS));
int oldArchiveId = -1;
if(iwc.isParameterSet("ccc_old_archive_id"))
oldArchiveId = Integer.parseInt(iwc.getParameter("ccc_old_archive_id"));
/*
ChildCareApplication application = getBusiness().getApplication(_applicationID);
ChildCareContract archive = getBusiness().getContractFile(application.getContractFileId());
SchoolClassMember classMember = null;
/* included in business assignContractToApplication
if(archive!=null){
classMember = archive.getSchoolClassMember();
if(schoolTypeId != classMember.getSchoolTypeId() || schoolClassId!= classMember.getSchoolClassId()){
// end old placement with the chosen date -1 and create new placement
classMember = getBusiness().createNewPlacement(_applicationID,schoolTypeId,schoolClassId,validFrom,iwc.getCurrentUser());
}
}*/
//Add a control that says IF schooltypeid !=oldschooltypeid && schoolclassid == oldschoolclassid message: "You are trying to change the school type but keep the child in the same group"
//+
//Add control that they in the future only can place in groups with correct school type
if(!getBusiness().isTryingToChangeSchoolTypeButNotSchoolClass(oldArchiveId,schoolTypeId,schoolClassId)){
if(getBusiness().isSchoolClassBelongingToSchooltype(schoolClassId,schoolTypeId)){
getBusiness().assignContractToApplication(_applicationID,oldArchiveId, childCareTime, validFrom, employmentType, iwc.getCurrentUser(), iwc.getCurrentLocale(), false,true,schoolTypeId,schoolClassId);
close();
}
else{
// add a message : "Chosen school group does not belong to chosen school type"
getParentPage().setAlertOnLoad(localize("child_care.warning.group_not_belonging_to_type","Chosen school group does not belong to chosen school type"));
}
}
else{
// add a message : "You are trying to change the school type but keep the child in the same group"
getParentPage().setAlertOnLoad(localize("child_care.warning.change_school_type_but_keep_same_group","You are trying to change the school type but keep the child in the same group"));
}
}
private void alterValidFromDate(IWContext iwc) throws RemoteException , NoPlacementFoundException{
IWTimestamp validFrom = new IWTimestamp(iwc.getParameter(PARAMETER_CHANGE_DATE));
int careTime = Integer.parseInt(iwc.getParameter(PARAMETER_CHILDCARE_TIME));
getBusiness().alterValidFromDate(_applicationID, validFrom.getDate(), -1, iwc.getCurrentLocale(), iwc.getCurrentUser());
getBusiness().placeApplication(_applicationID, null, null, careTime, -1, -1, -1, iwc.getCurrentUser(), iwc.getCurrentLocale());
getParentPage().setParentToRedirect(BuilderLogic.getInstance().getIBPageURL(iwc, _pageID));
getParentPage().close();
}
private void makeOffer(IWContext iwc) throws RemoteException {
String messageHeader = localize("child_care.application_accepted_subject", "Child care application accepted.");
String messageBody = iwc.getParameter(PARAMETER_OFFER_MESSAGE);
User child = getBusiness().getUserBusiness().getUser(_userID);
int pageID = -1;
String theUrl = null;
ICPage page = null;
URLUtil url = new URLUtil(iwc.getServerURL());
String linkName = null;
String link = null;
//get page to childcareOverview to add to the link in the childcare offer message
if (getBusiness().isAfterSchoolApplication(_applicationID)) {
page = ChildCareAdminApplication.ascOverviewPage;
linkName = localize("after_school_care.overview","after school care overview");
}
else {
page = ChildCareAdminApplication.ccOverviewPage;
linkName = localize("child_care.overview","childcare overview");
}
if (page != null)
pageID =((Integer) page.getPrimaryKey()).intValue();
if (pageID != -1)
url.setPage(pageID);
if (pageID != -1){
url.addParameter("comm_child_id",child.getPrimaryKey().toString());
theUrl = "javascript:openChildcareParentWindow(''" + url.toString() + "'');window.close();";
}
else {
theUrl = "#";
}
//link which is set in makeOffer(iwc), $link$ is replaced by this
link = "<a href=" + theUrl + " class=commune_SmallLink>"+ linkName +"</a>";
if (messageBody.indexOf("$datum$") != -1) {
messageBody = TextSoap.findAndReplace(messageBody, "$datum$", "{4}");
}
if (messageBody.indexOf("$link$") != -1) {
messageBody = TextSoap.findAndReplace(messageBody, "$link$", link);
}
IWTimestamp validUntil = new IWTimestamp(iwc.getParameter(PARAMETER_OFFER_VALID_UNTIL));
getBusiness().acceptApplication(_applicationID, validUntil, messageHeader, messageBody, iwc.getCurrentUser());
close();
}
private void retractOffer(IWContext iwc) throws RemoteException {
String messageHeader = localize("child_care.offer_retracted_subject", "Offer for child care retracted.");
String messageBody = iwc.getParameter(PARAMETER_OFFER_MESSAGE);
getBusiness().retractOffer(_applicationID, messageHeader, messageBody, iwc.getCurrentUser());
getParentPage().setParentToRedirect(BuilderLogic.getInstance().getIBPageURL(iwc, _pageID));
getParentPage().close();
}
private void rejectApplication(IWContext iwc) throws RemoteException {
String messageHeader = localize("child_care.application_rejected_subject", "Application for after school placing rejected.");
String messageBody = iwc.getParameter(PARAMETER_REJECT_MESSAGE);
getBusiness().rejectApplication(_applicationID, messageHeader, messageBody, iwc.getCurrentUser());
getParentPage().setParentToRedirect(BuilderLogic.getInstance().getIBPageURL(iwc, _pageID));
getParentPage().close();
}
private void changeDate(IWContext iwc) throws RemoteException {
String placingDate = iwc.getParameter(PARAMETER_CHANGE_DATE);
String preSchool = iwc.getParameter(PARAMETER_PRE_SCHOOL);
IWTimestamp stamp = new IWTimestamp(placingDate);
getBusiness().changePlacingDate(_applicationID, stamp.getDate(), preSchool);
close();
}
private void grantPriority(IWContext iwc) throws RemoteException {
String messageHeader = localize("child_care.priority_subject", "Child care application priority.");
String messageBody = iwc.getParameter(PARAMETER_PRIORITY_MESSAGE);
getBusiness().setAsPriorityApplication(_applicationID, messageHeader, messageBody);
close();
}
private void parentsAgree(IWContext iwc) throws RemoteException {
String subject = localize("child_care.parents_agree_subject", "Parents accept placing offer.");
String message = localize("child_care.parents_agree_body", "The parents of {0} accept your offer for a placing in {1} from {2}.");
getBusiness().parentsAgree(_applicationID, iwc.getCurrentUser(), subject, message);
close();
}
private void createContract(IWContext iwc) throws RemoteException {
getBusiness().assignContractToApplication(_applicationID, -1,-1, null, -1, iwc.getCurrentUser(), iwc.getCurrentLocale(), true);
close();
}
private void createContractForBankID(IWContext iwc) throws RemoteException {
getBusiness().assignContractToApplication(_applicationID, -1,-1, null, -1, iwc.getCurrentUser(), iwc.getCurrentLocale(), true);
close();
}
private void createGroup(IWContext iwc) throws RemoteException {
String groupName = iwc.getParameter(PARAMETER_GROUP_NAME);
int schoolTypeId = new Integer(iwc.getParameter(PARAMETER_SCHOOL_TYPES)).intValue();
getBusiness().getSchoolBusiness().storeSchoolClass(getSession().getGroupID(), groupName, getSession().getChildCareID(), schoolTypeId, -1, null, null);
getParentPage().setParentToRedirect(BuilderLogic.getInstance().getIBPageURL(iwc, _pageID));
getParentPage().close();
}
private void deleteGroup(IWContext iwc) throws RemoteException {
getBusiness().getSchoolBusiness().removeSchoolClass(getSession().getGroupID());
getSession().setGroupID(-1);
getParentPage().setParentToRedirect(BuilderLogic.getInstance().getIBPageURL(iwc, _pageID));
getParentPage().close();
}
private void placeInGroup(IWContext iwc) throws RemoteException {
int childCareTime = Integer.parseInt(iwc.getParameter(PARAMETER_CHILDCARE_TIME));
int groupID = Integer.parseInt(iwc.getParameter(getSession().getParameterGroupID()));
int typeID = Integer.parseInt(iwc.getParameter(getSession().getParameterSchoolTypeID()));
int employmentType = Integer.parseInt(iwc.getParameter(PARAMETER_EMPLOYMENT_TYPE));
String subject = localize("child_care.placing_subject","Your child placed in child care.");
String body = localize("child_care.placing_body","{0} has been placed in a group at {1}.");
getBusiness().placeApplication(getSession().getApplicationID(), subject, body, childCareTime, groupID, typeID, employmentType, iwc.getCurrentUser(), iwc.getCurrentLocale());
getParentPage().setParentToRedirect(BuilderLogic.getInstance().getIBPageURL(iwc, _pageID));
close();
}
private void cancelContract(IWContext iwc) throws RemoteException {
ChildCareApplication application = getBusiness().getApplicationForChildAndProvider(_userID, getSession().getChildCareID());
if (application != null) {
boolean reason = Boolean.valueOf(iwc.getParameter(PARAMETER_CANCEL_REASON)).booleanValue();
String message = iwc.getParameter(PARAMETER_CANCEL_MESSAGE);
IWTimestamp date = new IWTimestamp(iwc.getParameter(PARAMETER_CANCEL_DATE));
String reasonMessage = "";
if (reason)
reasonMessage = localize("child_care.parental_leave", "Parental leave");
else
reasonMessage = message;
Object[] arguments = { "{0}", "{1}", reasonMessage, date.getLocaleDate(iwc.getCurrentLocale(), IWTimestamp.SHORT) };
String subject = localize("child_care.cancel_contract_subject","Your child care contract has been terminated.");
String body = localize("child_care.cancel_contract_body","Your contract for {0} at {1} has been terminated because of {2}. The termination will be active on {3}.");
getBusiness().cancelContract(application, reason, date, message, subject, MessageFormat.format(body, arguments), iwc.getCurrentUser());
}
getParentPage().setParentToRedirect(BuilderLogic.getInstance().getIBPageURL(iwc, _pageID));
getParentPage().close();
}
private void moveToGroup(IWContext iwc) throws RemoteException {
int groupID = Integer.parseInt(iwc.getParameter(getSession().getParameterGroupID()));
getBusiness().moveToGroup(_placementID, groupID);
getParentPage().setParentToRedirect(BuilderLogic.getInstance().getIBPageURL(iwc, _pageID));
getParentPage().close();
}
private void removeFutureContracts(IWContext iwc) throws RemoteException {
getBusiness().removeFutureContracts(_applicationID);
getParentPage().setParentToRedirect(BuilderLogic.getInstance().getIBPageURL(iwc, _pageID));
getParentPage().close();
}
private void updatePrognosis(IWContext iwc) throws RemoteException {
int threeMonths = Integer.parseInt(iwc.getParameter(PARAMETER_THREE_MONTHS_PROGNOSIS));
int oneYear = Integer.parseInt(iwc.getParameter(PARAMETER_ONE_YEAR_PROGNOSIS));
int threeMonthsPriority = Integer.parseInt(iwc.getParameter(PARAMETER_THREE_MONTHS_PRIORITY));
int oneYearPriority = Integer.parseInt(iwc.getParameter(PARAMETER_ONE_YEAR_PRIORITY));
int providerCapacity = Integer.parseInt(iwc.getParameter(PARAMETER_PROVIDER_CAPACITY));
getBusiness().updatePrognosis(getSession().getChildCareID(), threeMonths, oneYear, threeMonthsPriority, oneYearPriority, providerCapacity);
getSession().setHasPrognosis(true);
getSession().setHasOutdatedPrognosis(false);
getParentPage().setParentToRedirect(BuilderLogic.getInstance().getIBPageURL(iwc, _pageID));
getParentPage().close();
}
private void sendEndContractRequest(IWContext iwc) throws RemoteException{
ChildCareApplication application = getBusiness().getApplication(_applicationID);
User owner = application.getOwner();
com.idega.core.user.data.User child = UserBusiness.getUser(application.getChildId());
getBusiness().sendMessageToParents(
application,
localize("ccecw_encon_par1", "Beg�ran om upps�gning av kontrakt gjord"),
localize("ccecw_encon_par2", "Du har skickat en beg�ran om upps�gning av kontrakt f�r") + " " +
child.getName() + " " + child.getPersonalID() + " " +
localize("ccecw_encon_par3", "fr.o.m.")+ " " + iwc.getParameter(PARAMETER_CHANGE_DATE) + ".");
getBusiness().sendMessageToProvider(
application,
localize("ccecw_encon_prov1", "Upps�gning av kontrakt"),
owner.getName() + " " + localize("ccecw_encon_prov2", "har beg�rt upps�gning av kontrakt f�r") + " " +
child.getName() + " " + child.getPersonalID() + ". " +
localize("ccecw_encon_prov3", "Kontraktet ska upph�ra fr.o.m.") + " " + iwc.getParameter(PARAMETER_CHANGE_DATE) + ".",
application.getOwner());
getParentPage().setParentToRedirect(BuilderLogic.getInstance().getIBPageURL(iwc, _pageID));
getParentPage().close();
}
private void sendNewCareTimeRequest(IWContext iwc) throws RemoteException {
ChildCareApplication application = getBusiness().getApplication(_applicationID);
User owner = application.getOwner();
com.idega.core.user.data.User child = UserBusiness.getUser(application.getChildId());
getBusiness().sendMessageToParents(
application,
localize(
"ccnctw_new_caretime_msg_parents_subject",
"Beg�ran om �ndrad omsorgstid gjord"),
localize(
"ccnctw_new_caretime_msg_parents_message",
"Du har skickat en beg�ran om �ndrad omsorgstid f�r ")
+ child.getName()
+ " "
+ child.getPersonalID());
getBusiness().sendMessageToProvider(
application,
localize(
"ccnctw_new_caretime_msg_provider_subject",
"Beg�ran om �ndrad omsorgstid"),
owner.getName()
+ " "
+ localize(
"ccnctw_new_caretime_msg_provider_message1",
"har beg�rt �ndrad omsorgstid till")
+ " "
+ iwc.getParameter(PARAMETER_CHILDCARE_TIME)
+ " "
+ localize(
"ccnctw_new_caretime_msg_provider_message2",
"tim/vecka f�r")
+ " "
+ child.getName()
+ " "
+ child.getPersonalID()
+ ". "
+ localize(
"ccnctw_new_caretime_msg_provider_message3",
"Den nya omsorgstiden skall g�lla fr.o.m.")
+ " "
+ iwc.getParameter(PARAMETER_CHANGE_DATE)
+ ".",
application.getOwner());
getParentPage().setParentToRedirect(BuilderLogic.getInstance().getIBPageURL(iwc, _pageID));
getParentPage().close();
}
private void close() {
getParentPage().setParentToReload();
getParentPage().close();
}
private Object[] getArguments(IWContext iwc) throws RemoteException {
User user = iwc.getCurrentUser();
User child = getBusiness().getUserBusiness().getUser(_userID);
Email mail = getBusiness().getUserBusiness().getUserMail(user);
ChildCareApplication application = getBusiness().getApplication(_applicationID);
String email = "";
if (mail != null && mail.getEmailAddress() != null)
email = mail.getEmailAddress();
String workphone = "";
try {
Phone phone = getBusiness().getUserBusiness().getUsersWorkPhone(user);
workphone = phone.getNumber();
}
catch (NoPhoneFoundException npfe) {
workphone = "";
}
Object[] arguments = { child.getName(), user.getName(), email, workphone, new IWTimestamp(application.getFromDate()).getLocaleDate(iwc.getCurrentLocale()), application.getProvider().getName()};
return arguments;
}
}
| false | false | null | null |
diff --git a/src/main/java/org/cloudifysource/quality/iTests/test/cli/cloudify/cloud/byon/BootstrapManagementScriptTest.java b/src/main/java/org/cloudifysource/quality/iTests/test/cli/cloudify/cloud/byon/BootstrapManagementScriptTest.java
index 61b673dd..97c05abe 100644
--- a/src/main/java/org/cloudifysource/quality/iTests/test/cli/cloudify/cloud/byon/BootstrapManagementScriptTest.java
+++ b/src/main/java/org/cloudifysource/quality/iTests/test/cli/cloudify/cloud/byon/BootstrapManagementScriptTest.java
@@ -1,163 +1,164 @@
/*
* ******************************************************************************
* * Copyright (c) 2012 GigaSpaces Technologies Ltd. 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 org.cloudifysource.quality.iTests.test.cli.cloudify.cloud.byon;
import iTests.framework.utils.AssertUtils;
import iTests.framework.utils.IOUtils;
import iTests.framework.utils.ScriptUtils;
import org.apache.commons.io.FileUtils;
import org.cloudifysource.domain.cloud.ScriptLanguages;
import org.cloudifysource.esc.installer.EnvironmentFileBuilder;
import org.cloudifysource.quality.iTests.test.AbstractTestSupport;
import org.cloudifysource.quality.iTests.test.cli.cloudify.cloud.services.byon.ByonCloudService;
import org.cloudifysource.utilitydomain.openspaces.OpenspacesConstants;
import org.cloudifysource.utilitydomain.openspaces.OpenspacesDomainUtils;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.io.File;
import java.util.HashMap;
import java.util.concurrent.TimeoutException;
/**
* Tests the functionality of the generic bootstrap-management script we provide.
*
* NOTE : This test cannot run a windows machine.
*
* @author Eli Polonsky
* @since 3.0.0
*/
public class BootstrapManagementScriptTest {
/**
* We use byon since it use tarzan as the storage for java and cloudify installations.
* This will also serve as our running directory.
*/
private static ByonCloudService byonCloudService;
/**
* Create the {@link ByonCloudService} we will use.
*
* @throws Exception In case of an initialization error.
*/
@BeforeClass
public static void prepareService() throws Exception {
if (ScriptUtils.isWindows()) {
throw new UnsupportedOperationException("Cannot run this test on a windows box since it runs a shell "
+ "script");
}
byonCloudService = new ByonCloudService();
byonCloudService.init(BootstrapManagementScriptTest.class.getSimpleName());
byonCloudService.injectCloudAuthenticationDetails();
// replace text in cloud driver
IOUtils.replaceTextInFile(byonCloudService.getPathToCloudGroovy(),
byonCloudService.getAdditionalPropsToReplace());
// create the properties file with the credentails.
IOUtils.writePropertiesToFile(byonCloudService.getProperties(),
new File(byonCloudService.getPathToCloudFolder() + "/" + byonCloudService.getCloudName()
+ "-cloud.properties"));
}
/**
*
* CLOUDIFY-2204.
*
* Run the bootstrap-management script and verify:
*
* 1. Gigaspaces tarball is deleted from the home directory.
* 2. Java is deleted from the home directory.
*
* @throws Exception In case of an unexpected failure.
*/
@Test(timeOut = AbstractTestSupport.DEFAULT_TEST_TIMEOUT)
public void testCleanHomeDirectory() throws Exception {
runBootstrapScript("management");
File gigaspacesTar = new File(byonCloudService.getPathToCloudFolder(), "gigaspaces.tar.gz");
AssertUtils.assertFalse("Found " + gigaspacesTar.getAbsolutePath() + " after the bootstrap-management script"
+ " ended", gigaspacesTar.exists());
File javaBin = new File(byonCloudService.getPathToCloudFolder(), "java.bin");
AssertUtils.assertFalse("Found " + javaBin.getAbsolutePath() + " after the bootstrap-management script"
+ " ended", javaBin.exists());
}
/**
* Cleans the /tmp/${user} directory from the host.
* @throws TimeoutException In case the delete operation times out.
*/
@AfterMethod
public void cleanup() throws TimeoutException {
ScriptUtils.executeCommandLine("rm -rf /tmp/" + System.getProperty("user.name"),
AbstractTestSupport.DEFAULT_TEST_TIMEOUT);
}
/**
* Setup the shared runtime env for running the script.
*
* 1. Copy the script to a temp folder
* 2. Copy the cloud file to the same temp folder
* 3. Prepare shared environment variables.
* 4. Source this environment to the bootstrap-management script.
* 5. Run the script.
*
* NOTE : We run the script so that it will fail fast.
* We are not interested in actually launching the agent. // TODO - Are we?
*
*
* @param mode The mode to run the script in. 'agent' or 'management'.
*
* @throws Exception In case one of the operations failed.
*/
private void runBootstrapScript(final String mode) throws Exception {
EnvironmentFileBuilder environmentFileBuilder = new EnvironmentFileBuilder(ScriptLanguages.LINUX_SHELL,
new HashMap<String, String>());
+ String newCloudifyURL = byonCloudService.replaceCloudifyURL();
+
environmentFileBuilder.exportVar("LUS_IP_ADDRESS", "127.0.0.1:" + OpenspacesConstants.DEFAULT_LUS_PORT);
environmentFileBuilder.exportVar("GSA_MODE", mode);
environmentFileBuilder.exportVar("MACHINE_IP_ADDRESS", "127.0.0.1");
- environmentFileBuilder.exportVar("GIGASPACES_LINK",
- OpenspacesDomainUtils.getCloudDependentConfig().getDownloadUrl());
+ environmentFileBuilder.exportVar("GIGASPACES_LINK", newCloudifyURL);
environmentFileBuilder.exportVar("WORKING_HOME_DIRECTORY", byonCloudService.getPathToCloudFolder());
environmentFileBuilder.exportVar("CLOUD_FILE", new File(byonCloudService.getPathToCloudGroovy())
.getAbsolutePath());
environmentFileBuilder.build();
String environmentFileName = environmentFileBuilder.getEnvironmentFileName();
File envFile = new File(byonCloudService.getPathToCloudFolder(), environmentFileName);
FileUtils.writeStringToFile(envFile, environmentFileBuilder.toString());
File pathToScript = new File(byonCloudService.getPathToCloudFolder() + File.separator + "upload",
"bootstrap-management.sh");
ScriptUtils.executeCommandLine("bash " + pathToScript.getAbsolutePath(),
AbstractTestSupport.DEFAULT_TEST_TIMEOUT);
}
}
diff --git a/src/main/java/org/cloudifysource/quality/iTests/test/cli/cloudify/cloud/services/byon/ByonCloudService.java b/src/main/java/org/cloudifysource/quality/iTests/test/cli/cloudify/cloud/services/byon/ByonCloudService.java
index 5e350242..2a73d084 100644
--- a/src/main/java/org/cloudifysource/quality/iTests/test/cli/cloudify/cloud/services/byon/ByonCloudService.java
+++ b/src/main/java/org/cloudifysource/quality/iTests/test/cli/cloudify/cloud/services/byon/ByonCloudService.java
@@ -1,362 +1,363 @@
/*******************************************************************************
* Copyright (c) 2012 GigaSpaces Technologies Ltd. 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 org.cloudifysource.quality.iTests.test.cli.cloudify.cloud.services.byon;
import iTests.framework.tools.SGTestHelper;
import iTests.framework.utils.IOUtils;
import iTests.framework.utils.LogUtils;
import iTests.framework.utils.SSHUtils;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.cloudifysource.quality.iTests.test.AbstractTestSupport;
import org.cloudifysource.quality.iTests.test.cli.cloudify.cloud.services.AbstractCloudService;
import com.j_spaces.kernel.PlatformVersion;
public class ByonCloudService extends AbstractCloudService {
private static final String BYON_CERT_PROPERTIES = CREDENTIALS_FOLDER + "/cloud/byon/byon-cred.properties";
private Properties certProperties = getCloudProperties(BYON_CERT_PROPERTIES);
private String user = certProperties.getProperty("user");
private String password = certProperties.getProperty("password");
private String keyFile = certProperties.getProperty("keyFile");
public static final String IP_LIST_PROPERTY = "ipList";
protected static final String NEW_URL_PREFIX = "http://tarzan/builds/GigaSpacesBuilds/cloudify";
protected static final String NEW_XAP_URL_PREFIX = "http://tarzan/builds/GigaSpacesBuilds";
public static final String ENV_VARIABLE_NAME = "GIGASPACES_TEST_ENV";
public static final String ENV_VARIABLE_VALUE = "DEFAULT_ENV_VARIABLE";
private boolean sudo;
/**
* this folder is where Cloudify will be downloaded to and extracted from. NOTE - this is not the WORKING_HOME_DIRECTORY.
* if is also defined in the custom bootstrap-management.sh script we use in our tests.
*/
public static final String BYON_HOME_FOLDER = "/tmp/tgrid";
private String ipList;
private String[] machines;
public ByonCloudService() {
this("byon");
}
public ByonCloudService(final String name) {
super(name);
if (SGTestHelper.isDevMode()) {
this.sudo = false;
this.ipList = getIpListFromPropsFile();
} else {
this.ipList = System.getProperty(IP_LIST_PROPERTY);
this.sudo = true;
}
if (this.ipList == null || this.ipList.isEmpty()) {
throw new IllegalStateException("ipList is empty! , please populate ipList property in the byon.properties file with the machines you wish to use");
}
this.machines = ipList.split(",");
}
public void setUser(String user) {
this.user = user;
}
@Override
public String getUser() {
return user;
}
@Override
public String getApiKey() {
return password;
}
public void setApiKey(final String apiKey) {
this.password = apiKey;
}
public String getKeyFile() {
return keyFile;
}
public void setKeyFile(String keyFile) {
this.keyFile = keyFile;
}
public boolean isSudo() {
return sudo;
}
public void setSudo(boolean sudo) {
this.sudo = sudo;
}
public void setIpList(String ipList) {
this.ipList = ipList;
}
public String getIpList() {
return ipList;
}
public String[] getMachines() {
return machines;
}
public void setMachines(final String[] machines) {
this.machines = machines;
}
@Override
public String getRegion() {
// TODO Auto-generated method stub
return null;
}
@Override
public void afterTeardown() throws Exception {
super.afterTeardown();
cleanCronTasks();
}
@Override
public void injectCloudAuthenticationDetails() throws IOException {
getProperties().put("username", user);
getProperties().put("password", password);
getProperties().put("keyFile", keyFile);
Map<String, String> propsToReplace = new HashMap<String,String>();
propsToReplace.put("cloudify_agent_", getMachinePrefix() + "cloudify-agent");
propsToReplace.put("cloudify_manager", getMachinePrefix() + "cloudify-manager");
propsToReplace.put("// cloudifyUrl", "cloudifyUrl");
if (!sudo) {
propsToReplace.put("privileged true", "privileged false");
}
if (StringUtils.isNotBlank(ipList)) {
propsToReplace.put("0\\.0\\.0\\.0", ipList);
}
propsToReplace.put("numberOfManagementMachines 1", "numberOfManagementMachines " + getNumberOfManagementMachines());
propsToReplace.put("\"org.cloudifysource.clearRemoteDirectoryOnStart\":\"false\"", "\"org.cloudifysource.clearRemoteDirectoryOnStart\":\"true\"");
propsToReplace.put("/tmp/gs-files", "/tmp/tgrid/gs-files");
this.getAdditionalPropsToReplace().putAll(propsToReplace);
// add a pem file
final File fileToCopy = new File(CREDENTIALS_FOLDER + "/cloud/" + getCloudName() + "/" + keyFile);
final File targetLocation = new File(getPathToCloudFolder() + "/upload/");
FileUtils.copyFileToDirectory(fileToCopy, targetLocation);
replaceCloudifyURL();
replaceBootstrapManagementScript();
replacePreBootstrapScript();
// byon-cloud.groovy in SGTest has this variable defined for cloud overrides tests.
// that why we need to add a properties file with a default value so that bootstrap will work
// on other tests.
getProperties().put("myEnvVariable", ENV_VARIABLE_VALUE);
}
private void replaceBootstrapManagementScript() throws IOException {
// use a script that does not install java
File standardBootstrapManagement = new File(this.getPathToCloudFolder() + "/upload", "bootstrap-management.sh");
File customBootstrapManagement = new File(SGTestHelper.getSGTestRootDir() + "/src/main/resources/apps/cloudify/cloud/byon/bootstrap-management.sh");
IOUtils.replaceFile(standardBootstrapManagement, customBootstrapManagement);
}
private void replacePreBootstrapScript() throws IOException {
// use a script that does not install java
File standardCustomization = new File(this.getPathToCloudFolder() + "/upload", "pre-bootstrap.sh");
File customCustomization;
if(enableLogstash){
String pathToLogstash = SGTestHelper.getSGTestRootDir() + "/src/main/resources/logstash";
customCustomization = new File(pathToLogstash + "/byon/pre-bootstrap.sh");
}
else{
customCustomization = new File(SGTestHelper.getSGTestRootDir() + "/src/main/resources/apps/cloudify/cloud/byon/pre-bootstrap.sh");
}
IOUtils.replaceFile(standardCustomization, customCustomization);
}
- public void replaceCloudifyURL() throws IOException {
+ public String replaceCloudifyURL() throws IOException {
String buildNumber = PlatformVersion.getBuildNumber();
String version = PlatformVersion.getVersion();
String milestone = PlatformVersion.getMilestone();
// TODO : replace hard coded 'cloudify' string with method to determine weather or no we are running xap or cloudify
String newCloudifyURL;
//running byon on ec2 env
if ("ec2-user".equals(user)) {
createCompressedDestribution();
newCloudifyURL = createEc2CloudifyURL();
}
else if(getBootstrapper().isNoWebServices()){
newCloudifyURL =NEW_XAP_URL_PREFIX+ "/" +version +"/build_" + buildNumber + "/xap-bigdata/1.5/gigaspaces-xap-premium-" + version + "-" + milestone + "-b" + buildNumber;
}
else {
newCloudifyURL = NEW_URL_PREFIX + "/" + version + "/build_" + buildNumber + "/cloudify/1.5/gigaspaces-cloudify-" + version + "-" + milestone + "-b" + buildNumber;
}
Map<String, String> propsToReplace = new HashMap<String, String>();
LogUtils.log("replacing cloudify url with : " + newCloudifyURL);
propsToReplace.put("cloudifyUrl \".+\"", "cloudifyUrl \"" + newCloudifyURL + '"');
this.getAdditionalPropsToReplace().putAll(propsToReplace);
+ return newCloudifyURL;
}
//used for byon running on ec2
public void createCompressedDestribution() throws UnknownHostException {
final File pemFile = new File("/home/cloudify/workspace/Cloudify-iTests/src/main/resources/credentials/cloud/byon/adaml_env");
File destFile = new File("/var/www/gigaspaces-" + PlatformVersion.getBuildNumber() + ".tar.gz");
final File buildDir = new File(SGTestHelper.getBuildDir());
if (!destFile.exists()) {
final String tarCommand = "sudo tar -cvzf /var/www/gigaspaces-" + PlatformVersion.getBuildNumber() + ".tar.gz --directory=" + SGTestHelper.getBuildDir() + " " + buildDir.getName();
SSHUtils.runCommand(InetAddress.getLocalHost().getHostAddress(), 60000, tarCommand, "ubuntu", pemFile);
//change permissions
final String chmodCommand = "sudo chmod 777 gigaspaces-" + PlatformVersion.getBuildNumber() + ".tar.gz";
SSHUtils.runCommand(InetAddress.getLocalHost().getHostAddress(), 60000, chmodCommand, "ubuntu", pemFile);
}
}
//used for byon running on ec2
private String createEc2CloudifyURL() throws UnknownHostException {
String privateIP = InetAddress.getLocalHost().getHostAddress();
return "http://" + privateIP + "/gigaspaces-" + PlatformVersion.getBuildNumber();
}
@Override
public void beforeBootstrap() {
cleanMachines();
}
private void cleanMachines() {
if(getBootstrapper().isFreshBootstrap()){
killAllJavaOnAllHosts();
removePersistencyFolder();
}
cleanGSFilesOnAllHosts();
cleanCloudifyTempDir();
cleanCronTasks();
}
public void cleanCronTasks() {
String command = "crontab -r";
String[] hosts = this.getMachines();
for (String host : hosts) {
try {
LogUtils.log("Removing scheduled task from "+host);
LogUtils.log(SSHUtils.runCommand(host, AbstractTestSupport.OPERATION_TIMEOUT, command, user, password));
} catch (AssertionError e) {
LogUtils.log("Failed to clean cron tasks on host " + host + " .Reason --> " + e.getMessage());
}
}
}
private void cleanCloudifyTempDir() {
String command = "rm -rf /export/tgrid/.cloudify/";
if (sudo) {
command = "sudo " + command;
}
try {
LogUtils.log(SSHUtils.runCommand(this.getMachines()[0], AbstractTestSupport.OPERATION_TIMEOUT, command, user, password));
} catch (AssertionError e) {
LogUtils.log("Failed to clean files .cloudify folder Reason --> " + e.getMessage());
}
}
private void cleanGSFilesOnAllHosts() {
String command = "rm -rf /tmp/tgrid/gs-files";
if (sudo) {
command = "sudo " + command;
}
String[] hosts = this.getMachines();
for (String host : hosts) {
try {
LogUtils.log(SSHUtils.runCommand(host, AbstractTestSupport.OPERATION_TIMEOUT, command, user, password));
} catch (AssertionError e) {
LogUtils.log("Failed to clean files on host " + host + " .Reason --> " + e.getMessage());
}
}
}
public void removePersistencyFolder() {
String command = "rm -rf " + getCloud().getConfiguration().getPersistentStoragePath();
if (sudo) {
command = "sudo " + command;
}
String[] hosts = this.getMachines();
for (String host : hosts) {
try {
LogUtils.log(SSHUtils.runCommand(host, AbstractTestSupport.OPERATION_TIMEOUT, command, user, password));
} catch (AssertionError e) {
LogUtils.log("Failed to clean files on host " + host + " .Reason --> " + e.getMessage());
}
}
}
private void killAllJavaOnAllHosts() {
String command = "killall -9 java";
if (sudo) {
command = "sudo " + command;
}
String[] hosts = this.getMachines();
for (String host : hosts) {
try {
LogUtils.log("Trying to kill: "+host);
LogUtils.log(SSHUtils.runCommand(host, AbstractTestSupport.OPERATION_TIMEOUT, command, user, password));
} catch (AssertionError e) {
LogUtils.log("Failed to kill java processes on host " + host + " .Reason --> " + e.getMessage());
}
}
}
private String getIpListFromPropsFile() {
File propsFile = new File(SGTestHelper.getSGTestRootDir() + "/src/main/resources/apps/cloudify/cloud/byon/byon.properties");
Properties props;
try {
props = IOUtils.readPropertiesFromFile(propsFile);
} catch (final Exception e) {
throw new IllegalStateException("Failed reading properties file : " + e.getMessage());
}
return props.getProperty(IP_LIST_PROPERTY);
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/src/main/java/org/kevoree/resolver/util/MavenVersionResolver.java b/src/main/java/org/kevoree/resolver/util/MavenVersionResolver.java
index 975a225..ea693e3 100644
--- a/src/main/java/org/kevoree/resolver/util/MavenVersionResolver.java
+++ b/src/main/java/org/kevoree/resolver/util/MavenVersionResolver.java
@@ -1,360 +1,356 @@
package org.kevoree.resolver.util;
import org.kevoree.log.Log;
import org.kevoree.resolver.api.MavenArtefact;
import org.kevoree.resolver.api.MavenVersionResult;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by duke on 16/05/13.
*/
public class MavenVersionResolver {
private static final String buildLatestTag = "<latest>";
private static final String buildEndLatestTag = "</latest>";
private static final String buildReleaseTag = "<release>";
private static final String buildEndreleaseTag = "</release>";
private static final String buildMavenTag = "<buildNumber>";
private static final String buildEndMavenTag = "</buildNumber>";
private static final String timestampMavenTag = "<timestamp>";
private static final String timestampEndMavenTag = "</timestamp>";
private static final String lastUpdatedMavenTag = "<lastUpdated>";
private static final String lastUpdatedEndMavenTag = "</lastUpdated>";
private static final String snapshotVersionClassifierMavenTag = "<classifier>";
private static final String snapshotVersionClassifierEndMavenTag = "</classifier>";
private static final String snapshotVersionExtensionMavenTag = "<extension>";
private static final String snapshotVersionExtensionEndMavenTag = "</extension>";
private static final String snapshotVersionValueMavenTag = "<value>";
private static final String snapshotVersionValueEndMavenTag = "</value>";
private static final String snapshotVersionUpdatedMavenTag = "<updated>";
private static final String snapshotVersionUpdatedEndMavenTag = "</updated>";
public static final String metaFile = "maven-metadata.xml";
private static final String localmetaFile = "maven-metadata-local.xml";
public Set<String> listVersions(MavenArtefact artefact, String basePath, String remoteURL, boolean localDeploy) {
Set<String> versions = new HashSet<String>();
//force update of caches
try {
resolveVersion(artefact, remoteURL, localDeploy);
} catch (Exception e) {
//ignore
}
//build directory path
StringBuilder builder = new StringBuilder();
builder.append(basePath);
String sep = File.separator;
if (!basePath.endsWith(sep)) {
builder.append(sep);
}
builder.append(artefact.getGroup().replace(".", File.separator));
builder.append(sep);
builder.append(artefact.getName());
File cacheDir = new File(builder.toString());
if (cacheDir.exists() && cacheDir.isDirectory()) {
for (File child : cacheDir.listFiles()) {
try {
if (child.getName().startsWith("maven-metadata")) {
StringBuffer stringBuffer = new StringBuffer();
BufferedReader bufferedReader = new BufferedReader(new FileReader(child));
String line = null;
while((line =bufferedReader.readLine())!=null){
stringBuffer.append(line).append("\n");
}
String flatFile = stringBuffer.toString();
- Pattern pattern = Pattern.compile("<versions>(\\s|.)*</versions>");
- Matcher matcher = pattern.matcher(flatFile);
- while (matcher.find()) {
- Pattern patternVersion = Pattern.compile("(<version>)((\\d|\\w|[-]|\\S)*)</version>");
- Matcher matcher2 = patternVersion.matcher(matcher.group());
- while (matcher2.find()) {
- for (int i = 2; i < matcher2.groupCount(); i++) {
- String loopVersion = matcher2.group(i).trim();
- versions.add(loopVersion);
- }
+ Pattern patternVersion = Pattern.compile("(<version>)((\\d|\\w|[-]|\\S)*)</version>");
+ Matcher matcher2 = patternVersion.matcher(flatFile);
+ while (matcher2.find()) {
+ for (int i = 2; i < matcher2.groupCount(); i++) {
+ String loopVersion = matcher2.group(i).trim();
+ versions.add(loopVersion);
}
}
}
} catch (Exception e) {
//ingore
}
}
}
return versions;
}
public MavenVersionResult resolveVersion(MavenArtefact artefact, String remoteURL, boolean localDeploy) throws IOException {
StringBuilder builder = new StringBuilder();
builder.append(remoteURL);
String sep = File.separator;
if (remoteURL.startsWith("http")) {
sep = "/";
}
if (!remoteURL.endsWith(sep)) {
builder.append(sep);
}
if (remoteURL.startsWith("http") || remoteURL.startsWith("https")) {
builder.append(artefact.getGroup().replace(".", "/"));
} else {
builder.append(artefact.getGroup().replace(".", File.separator));
}
builder.append(sep);
builder.append(artefact.getName());
builder.append(sep);
builder.append(artefact.getVersion());
builder.append(sep);
if (localDeploy) {
builder.append(localmetaFile);
} else {
builder.append(metaFile);
}
URL metadataURL = new URL("file:///" + builder.toString());
if (remoteURL.startsWith("http") || remoteURL.startsWith("https")) {
metadataURL = new URL(builder.toString());
}
URLConnection c = metadataURL.openConnection();
c.setRequestProperty("User-Agent", "Kevoree");
InputStream in = c.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder resultBuilder = new StringBuilder();
String line = reader.readLine();
resultBuilder.append(line);
while ((line = reader.readLine()) != null) {
resultBuilder.append(line);
}
String result = resultBuilder.toString();
in.close();
MavenVersionResult versionResult = new MavenVersionResult();
boolean found = false;
Pattern pattern = Pattern.compile("<snapshotVersion> *(.(?!(</snapshotVersion>)))* *</snapshotVersion>");
Matcher matcher = pattern.matcher(result);
int index = 0;
while (matcher.find(index) && !found) {
String snapshotVersion = matcher.group().trim();
if ((!snapshotVersion.contains(snapshotVersionClassifierMavenTag)
|| (snapshotVersion.contains(snapshotVersionClassifierMavenTag)
&& !"sources".equalsIgnoreCase(snapshotVersion.substring(snapshotVersion.indexOf(snapshotVersionClassifierMavenTag) + snapshotVersionClassifierMavenTag.length(), snapshotVersion.indexOf(snapshotVersionClassifierEndMavenTag)))))
&& snapshotVersion.contains(snapshotVersionValueMavenTag)
&& snapshotVersion.contains(snapshotVersionUpdatedMavenTag)
&& (!snapshotVersion.contains(snapshotVersionExtensionMavenTag)
|| artefact.getExtension().equalsIgnoreCase(snapshotVersion.substring(snapshotVersion.indexOf(snapshotVersionExtensionMavenTag) + snapshotVersionExtensionMavenTag.length(), snapshotVersion.indexOf(snapshotVersionExtensionEndMavenTag))))
) {
versionResult.setValue(snapshotVersion.substring(snapshotVersion.indexOf(snapshotVersionValueMavenTag) + snapshotVersionValueMavenTag.length(), snapshotVersion.indexOf(snapshotVersionValueEndMavenTag)));
versionResult.setLastUpdate(snapshotVersion.substring(snapshotVersion.indexOf(snapshotVersionUpdatedMavenTag) + snapshotVersionUpdatedMavenTag.length(), snapshotVersion.indexOf(snapshotVersionUpdatedEndMavenTag)));
found = true;
}
index += snapshotVersion.length();
}
versionResult.setUrl_origin(remoteURL);
versionResult.setNotDeployed(localDeploy);
if (!found) {
if (result.contains(timestampMavenTag) && result.contains(timestampEndMavenTag) && result.contains(buildMavenTag) && result.contains(buildEndMavenTag) && result.contains(lastUpdatedMavenTag) && result.contains(lastUpdatedEndMavenTag)) {
versionResult.setValue(result.substring(result.indexOf(timestampMavenTag) + timestampMavenTag.length(), result.indexOf(timestampEndMavenTag)) + "-" + result.substring(result.indexOf(buildMavenTag) + buildMavenTag.length(), result.indexOf(buildEndMavenTag)));
versionResult.setLastUpdate(result.substring(result.indexOf(lastUpdatedMavenTag) + lastUpdatedMavenTag.length(), result.indexOf(lastUpdatedEndMavenTag)));
return versionResult;
} else {
return null;
}
} else {
return versionResult;
}
}
private File buildCacheFile(MavenArtefact artefact, String basePath, String remoteURL) {
StringBuilder builder = new StringBuilder();
builder.append(basePath);
String sep = File.separator;
if (!basePath.endsWith(sep)) {
builder.append(sep);
}
builder.append(artefact.getGroup().replace(".", File.separator));
builder.append(sep);
builder.append(artefact.getName());
builder.append(sep);
builder.append(metaFile);
builder.append("-");
String cleaned = remoteURL.replace("/", "_").replace(":", "_").replace(".", "_");
builder.append(cleaned);
return new File(builder.toString());
}
public String foundRelevantVersion(MavenArtefact artefact, String cachePath, String remoteURL, boolean localDeploy) {
String askedVersion = artefact.getVersion().toLowerCase();
Boolean release = false;
Boolean lastest = false;
if (askedVersion.equalsIgnoreCase("release")) {
release = true;
}
if (askedVersion.equalsIgnoreCase("latest")) {
lastest = true;
}
if (!release && !lastest) {
return null;
}
StringBuilder builder = new StringBuilder();
builder.append(remoteURL);
String sep = File.separator;
if (remoteURL.startsWith("http") || remoteURL.startsWith("https")) {
sep = "/";
}
if (!remoteURL.endsWith(sep)) {
builder.append(sep);
}
if (remoteURL.startsWith("http") || remoteURL.startsWith("https")) {
builder.append(artefact.getGroup().replace(".", "/"));
} else {
builder.append(artefact.getGroup().replace(".", File.separator));
}
builder.append(sep);
builder.append(artefact.getName());
builder.append(sep);
if (localDeploy) {
builder.append(localmetaFile);
} else {
builder.append(metaFile);
}
File cacheFile = null;
FileWriter resultBuilder = null;
if (remoteURL.startsWith("http://") || remoteURL.startsWith("https://")) {
cacheFile = buildCacheFile(artefact, cachePath, remoteURL);
cacheFile.getParentFile().mkdirs();
}
StringBuffer buffer = new StringBuffer();
try {
URL metadataURL = new URL("file:///" + builder.toString());
if (remoteURL.startsWith("http") || remoteURL.startsWith("https")) {
metadataURL = new URL(builder.toString());
}
URLConnection c = metadataURL.openConnection();
c.setRequestProperty("User-Agent", "Kevoree");
InputStream in = c.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = reader.readLine();
if (line != null) {
if (remoteURL.startsWith("http://") || remoteURL.startsWith("https://")) {
try {
resultBuilder = new FileWriter(cacheFile);
} catch (IOException e) {
Log.error("Can't create cache file {}", e, cacheFile.getAbsolutePath());
}
}
}
buffer.append(line);
buffer.append("\n");
if (resultBuilder != null) {
resultBuilder.append(line);
resultBuilder.append("\n");
}
while ((line = reader.readLine()) != null) {
buffer.append(line);
buffer.append("\n");
if (resultBuilder != null) {
resultBuilder.append(line);
resultBuilder.append("\n");
}
}
in.close();
if (resultBuilder != null) {
resultBuilder.flush();
resultBuilder.close();
}
} catch (MalformedURLException ignored) {
} catch (IOException ignored) {
} finally {
String flatFile = null;
if (buffer.length() != 0) {
flatFile = buffer.toString();
} else {
if (cacheFile != null && cacheFile.exists()) {
BufferedReader br;
try {
br = new BufferedReader(new FileReader(cacheFile));
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
buffer.append(sCurrentLine);
buffer.append("\n");
}
flatFile = buffer.toString();
} catch (Exception e) {
Log.error("Maven Resolver internal error !", e);
}
} else {
return null;
}
}
try {
if (release) {
if (flatFile.contains(buildReleaseTag) && flatFile.contains(buildEndreleaseTag)) {
return flatFile.substring(flatFile.indexOf(buildReleaseTag) + buildReleaseTag.length(), flatFile.indexOf(buildEndreleaseTag));
}
}
if (lastest) {
if (flatFile.contains(buildLatestTag) && flatFile.contains(buildEndLatestTag)) {
return flatFile.substring(flatFile.indexOf(buildLatestTag) + buildLatestTag.length(), flatFile.indexOf(buildEndLatestTag));
}
}
//still not resolve try the local resolution
if (localDeploy) {
Pattern pattern = Pattern.compile("<versions>(\\s|.)*</versions>");
Matcher matcher = pattern.matcher(flatFile);
String bestVersion = "-1";
while (matcher.find()) {
Pattern patternVersion = Pattern.compile("(<version>)((\\d|\\w|[-]|\\S)*)</version>");
Matcher matcher2 = patternVersion.matcher(matcher.group());
while (matcher2.find()) {
for (int i = 2; i < matcher2.groupCount(); i++) {
String loopVersion = matcher2.group(i).trim();
if (release) {
if (!loopVersion.toLowerCase().contains("snapshot")) {
bestVersion = MavenVersionComparator.max(bestVersion, loopVersion);
}
} else {
bestVersion = MavenVersionComparator.max(bestVersion, loopVersion);
}
}
}
}
if (!bestVersion.equals("-1")) {
return bestVersion;
}
}
} catch (Exception e) {
Log.error("Maven Resolver internal error !", e);
}
}
return null;
}
}
| true | false | null | null |
diff --git a/core/src/main/java/org/apache/directory/server/core/partition/DefaultPartitionNexus.java b/core/src/main/java/org/apache/directory/server/core/partition/DefaultPartitionNexus.java
index f90c030737..4670c67455 100644
--- a/core/src/main/java/org/apache/directory/server/core/partition/DefaultPartitionNexus.java
+++ b/core/src/main/java/org/apache/directory/server/core/partition/DefaultPartitionNexus.java
@@ -1,1124 +1,1125 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.server.core.partition;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
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.Properties;
import java.util.Set;
import javax.naming.ConfigurationException;
import javax.naming.NameNotFoundException;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.LdapContext;
import org.apache.directory.server.core.DirectoryServiceConfiguration;
import org.apache.directory.server.core.configuration.PartitionConfiguration;
import org.apache.directory.server.core.interceptor.context.AddContextPartitionOperationContext;
import org.apache.directory.server.core.interceptor.context.CompareOperationContext;
import org.apache.directory.server.core.interceptor.context.EntryOperationContext;
import org.apache.directory.server.core.interceptor.context.LookupOperationContext;
import org.apache.directory.server.core.interceptor.context.RemoveContextPartitionOperationContext;
import org.apache.directory.server.core.interceptor.context.OperationContext;
import org.apache.directory.server.core.interceptor.context.SearchOperationContext;
import org.apache.directory.server.core.partition.impl.btree.MutableBTreePartitionConfiguration;
import org.apache.directory.server.core.partition.impl.btree.jdbm.JdbmPartition;
import org.apache.directory.server.core.partition.tree.LeafNode;
import org.apache.directory.server.core.partition.tree.Node;
import org.apache.directory.server.core.partition.tree.BranchNode;
import org.apache.directory.server.ldap.constants.SupportedSASLMechanisms;
import org.apache.directory.server.schema.registries.AttributeTypeRegistry;
import org.apache.directory.server.schema.registries.OidRegistry;
import org.apache.directory.shared.ldap.MultiException;
import org.apache.directory.shared.ldap.NotImplementedException;
import org.apache.directory.shared.ldap.constants.SchemaConstants;
import org.apache.directory.shared.ldap.exception.LdapInvalidAttributeIdentifierException;
import org.apache.directory.shared.ldap.exception.LdapNameNotFoundException;
import org.apache.directory.shared.ldap.exception.LdapNoSuchAttributeException;
import org.apache.directory.shared.ldap.filter.ExprNode;
import org.apache.directory.shared.ldap.filter.PresenceNode;
import org.apache.directory.shared.ldap.message.EntryChangeControl;
import org.apache.directory.shared.ldap.message.AttributeImpl;
import org.apache.directory.shared.ldap.message.AttributesImpl;
import org.apache.directory.shared.ldap.message.ManageDsaITControl;
import org.apache.directory.shared.ldap.message.PersistentSearchControl;
import org.apache.directory.shared.ldap.message.ServerSearchResult;
import org.apache.directory.shared.ldap.message.SubentriesControl;
import org.apache.directory.shared.ldap.message.extended.NoticeOfDisconnect;
import org.apache.directory.shared.ldap.name.LdapDN;
import org.apache.directory.shared.ldap.schema.AttributeType;
import org.apache.directory.shared.ldap.schema.Normalizer;
import org.apache.directory.shared.ldap.schema.UsageEnum;
import org.apache.directory.shared.ldap.util.DateUtils;
import org.apache.directory.shared.ldap.util.NamespaceTools;
import org.apache.directory.shared.ldap.util.SingletonEnumeration;
import org.apache.directory.shared.ldap.util.StringTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A nexus for partitions dedicated for storing entries specific to a naming
* context.
*
* @author <a href="mailto:[email protected]">Apache Directory Project</a>
* @version $Rev$
*/
public class DefaultPartitionNexus extends PartitionNexus
{
private static final Logger log = LoggerFactory.getLogger( DefaultPartitionNexus.class );
/** Speedup for logs */
private static final boolean IS_DEBUG = log.isDebugEnabled();
/** the vendorName string proudly set to: Apache Software Foundation*/
private static final String ASF = "Apache Software Foundation";
/** the vendorName DSE operational attribute */
private static final String VENDORNAME_ATTR = "vendorName";
/** the vendorVersion DSE operational attribute */
private static final String VENDORVERSION_ATTR = "vendorVersion";
/** the namingContexts DSE operational attribute */
private static final String NAMINGCTXS_ATTR = "namingContexts";
/** the closed state of this partition */
private boolean initialized;
private DirectoryServiceConfiguration factoryCfg;
/** the system partition */
private Partition system;
/** the partitions keyed by normalized suffix strings */
private Map<String, Partition> partitions = new HashMap<String, Partition>();
/** A structure to hold all the partitions */
private BranchNode partitionLookupTree = new BranchNode();
/** the read only rootDSE attributes */
private final Attributes rootDSE;
private AttributeTypeRegistry attrRegistry;
private OidRegistry oidRegistry;
/**
* Creates the root nexus singleton of the entire system. The root DSE has
* several attributes that are injected into it besides those that may
* already exist. As partitions are added to the system more namingContexts
* attributes are added to the rootDSE.
*
* @see <a href="http://www.faqs.org/rfcs/rfc3045.html">Vendor Information</a>
*/
public DefaultPartitionNexus( Attributes rootDSE )
{
// setup that root DSE
this.rootDSE = rootDSE;
Attribute attr = new AttributeImpl( SchemaConstants.SUBSCHEMA_SUBENTRY_AT );
attr.add( GLOBAL_SCHEMA_SUBENTRY_DN );
rootDSE.put( attr );
attr = new AttributeImpl( "supportedLDAPVersion" );
rootDSE.put( attr );
attr.add( "3" );
attr = new AttributeImpl( "supportedFeatures" );
rootDSE.put( attr );
attr.add( "1.3.6.1.4.1.4203.1.5.1" );
attr = new AttributeImpl( "supportedExtension" );
rootDSE.put( attr );
attr.add( NoticeOfDisconnect.EXTENSION_OID );
// Add the supportedSASLMechanisms attribute to rootDSE
attr = new AttributeImpl( SupportedSASLMechanisms.ATTRIBUTE );
rootDSE.put( attr );
attr.add( SupportedSASLMechanisms.GSSAPI );
attr.add( SupportedSASLMechanisms.DIGEST_MD5 );
attr.add( SupportedSASLMechanisms.CRAM_MD5 );
attr = new AttributeImpl( "supportedControl" );
rootDSE.put( attr );
attr.add( PersistentSearchControl.CONTROL_OID );
attr.add( EntryChangeControl.CONTROL_OID );
attr.add( SubentriesControl.CONTROL_OID );
attr.add( ManageDsaITControl.CONTROL_OID );
attr = new AttributeImpl( SchemaConstants.OBJECT_CLASS_AT );
rootDSE.put( attr );
attr.add( SchemaConstants.TOP_OC );
attr.add( SchemaConstants.EXTENSIBLE_OBJECT_OC );
attr = new AttributeImpl( NAMINGCTXS_ATTR );
rootDSE.put( attr );
attr = new AttributeImpl( VENDORNAME_ATTR );
attr.add( ASF );
rootDSE.put( attr );
Properties props = new Properties();
try
{
props.load( getClass().getResourceAsStream( "version.properties" ) );
}
catch ( IOException e )
{
log.error( "failed to log version properties" );
}
attr = new AttributeImpl( VENDORVERSION_ATTR );
attr.add( props.getProperty( "apacheds.version", "UNKNOWN" ) );
rootDSE.put( attr );
}
public PartitionConfiguration getConfiguration()
{
throw new UnsupportedOperationException( "The NEXUS partition does not have a " +
"standard partition configuration associated with it." );
}
public String getId()
{
return "NEXUS";
}
public void init( DirectoryServiceConfiguration factoryCfg, PartitionConfiguration cfg )
throws NamingException
{
// NOTE: We ignore ContextPartitionConfiguration parameter here.
if ( initialized )
{
return;
}
this.factoryCfg = factoryCfg;
this.attrRegistry = this.factoryCfg.getRegistries().getAttributeTypeRegistry();
this.oidRegistry = this.factoryCfg.getRegistries().getOidRegistry();
initializeSystemPartition();
List<Partition> initializedPartitions = new ArrayList<Partition>();
initializedPartitions.add( 0, this.system );
Iterator i = factoryCfg.getStartupConfiguration().getPartitionConfigurations().iterator();
try
{
while ( i.hasNext() )
{
PartitionConfiguration c = ( PartitionConfiguration ) i.next();
AddContextPartitionOperationContext opCtx = new AddContextPartitionOperationContext( c );
addContextPartition( opCtx );
initializedPartitions.add( opCtx.getPartition() );
}
initialized = true;
}
finally
{
if ( !initialized )
{
i = initializedPartitions.iterator();
while ( i.hasNext() )
{
Partition partition = ( Partition ) i.next();
i.remove();
try
{
partition.destroy();
}
catch ( Exception e )
{
log.warn( "Failed to destroy a partition: " + partition.getSuffix(), e );
}
finally
{
unregister( partition );
}
}
}
}
}
private PartitionConfiguration initializeSystemPartition() throws NamingException
{
// initialize system partition first
MutableBTreePartitionConfiguration systemCfg;
PartitionConfiguration overrides = factoryCfg.getStartupConfiguration().getSystemPartitionConfiguration();
if ( overrides != null )
{
systemCfg = MutableBTreePartitionConfiguration.getConfiguration( overrides );
// ---------------------------------------------------------------
// Add some attributes w/ some only if they're missing. Allows
// users to add more attributes to the system namingConext root
// ---------------------------------------------------------------
Attributes systemEntry = systemCfg.getContextEntry();
Attribute objectClassAttr = systemEntry.get( SchemaConstants.OBJECT_CLASS_AT );
if ( objectClassAttr == null )
{
objectClassAttr = new AttributeImpl( SchemaConstants.OBJECT_CLASS_AT );
systemEntry.put( objectClassAttr );
}
objectClassAttr.add( SchemaConstants.TOP_OC );
objectClassAttr.add( SchemaConstants.ORGANIZATIONAL_UNIT_OC );
objectClassAttr.add( SchemaConstants.EXTENSIBLE_OBJECT_OC );
systemEntry.put( SchemaConstants.CREATORS_NAME_AT, PartitionNexus.ADMIN_PRINCIPAL );
systemEntry.put( SchemaConstants.CREATE_TIMESTAMP_AT, DateUtils.getGeneralizedTime() );
systemEntry.put( NamespaceTools.getRdnAttribute( PartitionNexus.SYSTEM_PARTITION_SUFFIX ),
NamespaceTools.getRdnValue( PartitionNexus.SYSTEM_PARTITION_SUFFIX ) );
systemCfg.setContextEntry( systemEntry );
// ---------------------------------------------------------------
// check a few things to make sure users configured it properly
// ---------------------------------------------------------------
if ( ! systemCfg.getId().equals( "system" ) )
{
throw new ConfigurationException( "System partition has wrong name: should be 'system'." );
}
// add all attribute oids of index configs to a hashset
Set<Object> indices = systemCfg.getIndexedAttributes();
Set<String> indexOids = new HashSet<String>();
OidRegistry registry = factoryCfg.getRegistries().getOidRegistry();
for ( Object index : indices )
{
indexOids.add( registry.getOid( index.toString() ) );
}
if ( ! indexOids.contains( Oid.ALIAS ) )
{
indices.add( Oid.ALIAS );
}
if ( ! indexOids.contains( Oid.EXISTANCE ) )
{
indices.add( Oid.EXISTANCE );
}
if ( ! indexOids.contains( Oid.HIERARCHY ) )
{
indices.add( Oid.HIERARCHY );
}
if ( ! indexOids.contains( Oid.NDN ) )
{
indices.add( Oid.NDN );
}
if ( ! indexOids.contains( Oid.ONEALIAS ) )
{
indices.add( Oid.ONEALIAS );
}
if ( ! indexOids.contains( Oid.SUBALIAS ) )
{
indices.add( Oid.SUBALIAS );
}
if ( ! indexOids.contains( Oid.UPDN ) )
{
indices.add( Oid.UPDN );
}
if ( ! indexOids.contains( registry.getOid( SchemaConstants.OBJECT_CLASS_AT ) ) )
{
log.warn( "CAUTION: You have not included objectClass as an indexed attribute" +
"in the system partition configuration. This will lead to poor " +
"performance. The server is automatically adding this index for you." );
indices.add( SchemaConstants.OBJECT_CLASS_AT );
}
}
else
{
systemCfg = new MutableBTreePartitionConfiguration();
systemCfg.setId( "system" );
// @TODO need to make this configurable for the system partition
systemCfg.setCacheSize( 500 );
systemCfg.setSuffix( PartitionNexus.SYSTEM_PARTITION_SUFFIX );
// Add indexed attributes for system partition
Set<Object> indexedSystemAttrs = new HashSet<Object>();
indexedSystemAttrs.add( Oid.ALIAS );
indexedSystemAttrs.add( Oid.EXISTANCE );
indexedSystemAttrs.add( Oid.HIERARCHY );
indexedSystemAttrs.add( Oid.NDN );
indexedSystemAttrs.add( Oid.ONEALIAS );
indexedSystemAttrs.add( Oid.SUBALIAS );
indexedSystemAttrs.add( Oid.UPDN );
indexedSystemAttrs.add( SchemaConstants.OBJECT_CLASS_AT );
systemCfg.setIndexedAttributes( indexedSystemAttrs );
// Add context entry for system partition
Attributes systemEntry = new AttributesImpl();
Attribute objectClassAttr = new AttributeImpl( SchemaConstants.OBJECT_CLASS_AT );
objectClassAttr.add( SchemaConstants.TOP_OC );
objectClassAttr.add( SchemaConstants.ORGANIZATIONAL_UNIT_OC );
objectClassAttr.add( SchemaConstants.EXTENSIBLE_OBJECT_OC );
systemEntry.put( objectClassAttr );
systemEntry.put( SchemaConstants.CREATORS_NAME_AT, PartitionNexus.ADMIN_PRINCIPAL );
systemEntry.put( SchemaConstants.CREATE_TIMESTAMP_AT, DateUtils.getGeneralizedTime() );
systemEntry.put( NamespaceTools.getRdnAttribute( PartitionNexus.SYSTEM_PARTITION_SUFFIX ),
NamespaceTools.getRdnValue( PartitionNexus.SYSTEM_PARTITION_SUFFIX ) );
systemCfg.setContextEntry( systemEntry );
}
system = new JdbmPartition(); // using default implementation.
system.init( factoryCfg, systemCfg );
String key = system.getSuffix().toString();
if ( partitions.containsKey( key ) )
{
throw new ConfigurationException( "Duplicate partition suffix: " + key );
}
synchronized ( partitionLookupTree )
{
partitions.put( key, system );
partitionLookupTree.recursivelyAddPartition( partitionLookupTree, system.getSuffix(), 0, system );
Attribute namingContexts = rootDSE.get( NAMINGCTXS_ATTR );
namingContexts.add( system.getUpSuffix().getUpName() );
}
return systemCfg;
}
public boolean isInitialized()
{
return initialized;
}
public synchronized void destroy()
{
if ( !initialized )
{
return;
}
Iterator<String> suffixes = new HashSet<String>( this.partitions.keySet() ).iterator();
// make sure this loop is not fail fast so all backing stores can
// have an attempt at closing down and synching their cached entries
while ( suffixes.hasNext() )
{
String suffix = suffixes.next();
try
{
removeContextPartition( new RemoveContextPartitionOperationContext( new LdapDN( suffix ) ) );
}
catch ( NamingException e )
{
log.warn( "Failed to destroy a partition: " + suffix, e );
}
}
initialized = false;
}
/**
* @see Partition#sync()
*/
public void sync() throws NamingException
{
MultiException error = null;
Iterator list = this.partitions.values().iterator();
while ( list.hasNext() )
{
Partition partition = ( Partition ) list.next();
try
{
partition.sync();
}
catch ( NamingException e )
{
log.warn( "Failed to flush partition data out.", e );
if ( error == null )
{
error = new MultiException( "Grouping many exceptions on root nexus sync()" );
}
// @todo really need to send this info to a monitor
error.addThrowable( e );
}
}
if ( error != null )
{
String msg = "Encountered failures while performing a sync() operation on backing stores";
NamingException total = new NamingException( msg );
total.setRootCause( error );
}
}
// ------------------------------------------------------------------------
// ContextPartitionNexus Method Implementations
// ------------------------------------------------------------------------
public boolean compare( OperationContext compareContext ) throws NamingException
{
Partition partition = getPartition( compareContext.getDn() );
AttributeTypeRegistry registry = factoryCfg.getRegistries().getAttributeTypeRegistry();
CompareOperationContext ctx = (CompareOperationContext)compareContext;
// complain if we do not recognize the attribute being compared
if ( !registry.hasAttributeType( ctx.getOid() ) )
{
throw new LdapInvalidAttributeIdentifierException( ctx.getOid() + " not found within the attributeType registry" );
}
AttributeType attrType = registry.lookup( ctx.getOid() );
Attribute attr = partition.lookup( new LookupOperationContext( ctx.getDn() ) ).get( attrType.getName() );
// complain if the attribute being compared does not exist in the entry
if ( attr == null )
{
throw new LdapNoSuchAttributeException();
}
// see first if simple match without normalization succeeds
+ // TODO Fix DIRSERVER-832
if ( attr.contains( ctx.getValue() ) )
{
return true;
}
// now must apply normalization to all values (attr and in request) to compare
/*
* Get ahold of the normalizer for the attribute and normalize the request
* assertion value for comparisons with normalized attribute values. Loop
* through all values looking for a match.
*/
Normalizer normalizer = attrType.getEquality().getNormalizer();
Object reqVal = normalizer.normalize( ctx.getValue() );
for ( int ii = 0; ii < attr.size(); ii++ )
{
Object attrValObj = normalizer.normalize( attr.get( ii ) );
if ( attrValObj instanceof String )
{
String attrVal = ( String ) attrValObj;
if ( ( reqVal instanceof String ) && attrVal.equals( reqVal ) )
{
return true;
}
}
else
{
byte[] attrVal = ( byte[] ) attrValObj;
if ( reqVal instanceof byte[] )
{
return Arrays.equals( attrVal, ( byte[] ) reqVal );
}
else if ( reqVal instanceof String )
{
return Arrays.equals( attrVal, StringTools.getBytesUtf8( ( String ) reqVal ) );
}
}
}
return false;
}
public synchronized void addContextPartition( OperationContext addContextPartitionContext ) throws NamingException
{
AddContextPartitionOperationContext operationContext =
( AddContextPartitionOperationContext ) addContextPartitionContext;
PartitionConfiguration config = operationContext.getPartitionConfiguration();
Partition partition = operationContext.getPartition();
// Turn on default indices
String key = config.getSuffix();
if ( partitions.containsKey( key ) )
{
throw new ConfigurationException( "Duplicate partition suffix: " + key );
}
if ( ! partition.isInitialized() )
{
partition.init( factoryCfg, config );
}
synchronized ( partitionLookupTree )
{
LdapDN partitionSuffix = partition.getSuffix();
if ( partitionSuffix == null )
{
throw new ConfigurationException( "The current partition does not have any suffix: " + partition.getId() );
}
partitions.put( partitionSuffix.toString(), partition );
partitionLookupTree.recursivelyAddPartition( partitionLookupTree, partition.getSuffix(), 0, partition );
Attribute namingContexts = rootDSE.get( NAMINGCTXS_ATTR );
if ( partitionSuffix == null )
{
throw new ConfigurationException( "The current partition does not have any suffix: " + partition.getId() );
}
LdapDN partitionUpSuffix = partition.getUpSuffix();
if ( partitionUpSuffix == null )
{
throw new ConfigurationException( "The current partition does not have any user provided suffix: " + partition.getId() );
}
namingContexts.add( partitionUpSuffix.getUpName() );
}
}
public synchronized void removeContextPartition( OperationContext removeContextPartition ) throws NamingException
{
String key = removeContextPartition.getDn().getNormName();
Partition partition = partitions.get( key );
if ( partition == null )
{
throw new NameNotFoundException( "No partition with suffix: " + key );
}
Attribute namingContexts = rootDSE.get( NAMINGCTXS_ATTR );
namingContexts.remove( partition.getUpSuffix().getUpName() );
// Create a new partition list.
// This is easier to create a new structure from scratch than to reorganize
// the current structure. As this strcuture is not modified often
// this is an acceptable solution.
synchronized (partitionLookupTree)
{
partitions.remove( key );
partitionLookupTree = new BranchNode();
for ( Partition part:partitions.values() )
{
partitionLookupTree.recursivelyAddPartition( partitionLookupTree, part.getSuffix(), 0, partition );
}
partition.sync();
partition.destroy();
}
}
public Partition getSystemPartition()
{
return system;
}
/**
* @see PartitionNexus#getLdapContext()
*/
public LdapContext getLdapContext()
{
throw new NotImplementedException();
}
/**
* @see PartitionNexus#getMatchedName( OperationContext )
*/
public LdapDN getMatchedName ( OperationContext getMatchedNameContext ) throws NamingException
{
LdapDN dn = ( LdapDN ) getMatchedNameContext.getDn().clone();
while ( dn.size() > 0 )
{
if ( hasEntry( new EntryOperationContext( dn ) ) )
{
return dn;
}
dn.remove( dn.size() - 1 );
}
return dn;
}
public LdapDN getSuffix()
{
return LdapDN.EMPTY_LDAPDN;
}
public LdapDN getUpSuffix()
{
return LdapDN.EMPTY_LDAPDN;
}
/**
* @see PartitionNexus#getSuffix( OperationContext )
*/
public LdapDN getSuffix ( OperationContext getSuffixContext ) throws NamingException
{
Partition backend = getPartition( getSuffixContext.getDn() );
return backend.getSuffix();
}
/**
* @see PartitionNexus#listSuffixes( OperationContext )
*/
public Iterator listSuffixes ( OperationContext emptyContext ) throws NamingException
{
return Collections.unmodifiableSet( partitions.keySet() ).iterator();
}
public Attributes getRootDSE( OperationContext getRootDSEContext )
{
return rootDSE;
}
/**
* Unregisters an ContextPartition with this BackendManager. Called for each
* registered Backend right befor it is to be stopped. This prevents
* protocol server requests from reaching the Backend and effectively puts
* the ContextPartition's naming context offline.
*
* Operations against the naming context should result in an LDAP BUSY
* result code in the returnValue if the naming context is not online.
*
* @param partition ContextPartition component to unregister with this
* BackendNexus.
*/
private void unregister( Partition partition ) throws NamingException
{
Attribute namingContexts = rootDSE.get( NAMINGCTXS_ATTR );
namingContexts.remove( partition.getSuffix().getUpName() );
partitions.remove( partition.getSuffix().toString() );
}
// ------------------------------------------------------------------------
// DirectoryPartition Interface Method Implementations
// ------------------------------------------------------------------------
public void bind( OperationContext bindContext ) throws NamingException
{
Partition partition = getPartition( bindContext.getDn() );
partition.bind( bindContext );
}
public void unbind( OperationContext unbindContext ) throws NamingException
{
Partition partition = getPartition( unbindContext.getDn() );
partition.unbind( unbindContext );
}
/**
* @see Partition#delete(org.apache.directory.shared.ldap.name.LdapDN)
*/
public void delete( OperationContext deleteContext ) throws NamingException
{
Partition backend = getPartition( deleteContext.getDn() );
backend.delete( deleteContext );
}
/**
* Looks up the backend corresponding to the entry first, then checks to
* see if the entry already exists. If so an exception is thrown. If not
* the add operation against the backend proceeds. This check is performed
* here so backend implementors do not have to worry about performing these
* kinds of checks.
*
* @see Partition#add( OperationContext )
*/
public void add( OperationContext addContext ) throws NamingException
{
Partition backend = getPartition( addContext.getDn() );
backend.add( addContext );
}
/**
* @see Partition#modify(org.apache.directory.shared.ldap.name.LdapDN,int,javax.naming.directory.Attributes)
*/
public void modify( OperationContext modifyContext ) throws NamingException
{
Partition backend = getPartition( modifyContext.getDn() );
backend.modify( modifyContext );
}
/**
* @see Partition#list(org.apache.directory.shared.ldap.name.LdapDN)
*/
public NamingEnumeration list( OperationContext opContext ) throws NamingException
{
Partition backend = getPartition( opContext.getDn() );
return backend.list( opContext );
}
/**
* @see Partition#search(org.apache.directory.shared.ldap.name.LdapDN,java.util.Map,org.apache.directory.shared.ldap.filter.ExprNode,javax.naming.directory.SearchControls)
*/
public NamingEnumeration<SearchResult> search( OperationContext opContext )
throws NamingException
{
LdapDN base = opContext.getDn();
SearchControls searchCtls = ((SearchOperationContext)opContext).getSearchControls();
ExprNode filter = ((SearchOperationContext)opContext).getFilter();
if ( base.size() == 0 )
{
boolean isObjectScope = searchCtls.getSearchScope() == SearchControls.OBJECT_SCOPE;
// test for (objectClass=*)
boolean isSearchAll = ( ( PresenceNode ) filter ).getAttribute().equals( SchemaConstants.OBJECT_CLASS_AT_OID );
/*
* if basedn is "", filter is "(objectclass=*)" and scope is object
* then we have a request for the rootDSE
*/
if ( filter instanceof PresenceNode && isObjectScope && isSearchAll )
{
String[] ids = searchCtls.getReturningAttributes();
// -----------------------------------------------------------
// If nothing is asked for then we just return the entry asis.
// We let other mechanisms filter out operational attributes.
// -----------------------------------------------------------
if ( ids == null || ids.length == 0 )
{
SearchResult result = new ServerSearchResult( "", null, ( Attributes ) getRootDSE( null ).clone(), false );
return new SingletonEnumeration( result );
}
// -----------------------------------------------------------
// Collect all the real attributes besides 1.1, +, and * and
// note if we've seen these special attributes as well.
// -----------------------------------------------------------
Set<String> realIds = new HashSet<String>();
boolean containsAsterisk = false;
boolean containsPlus = false;
boolean containsOneDotOne = false;
for ( int ii = 0; ii < ids.length; ii++ )
{
String id = ids[ii].trim();
if ( id.equals( "*" ) )
{
containsAsterisk = true;
}
else if ( id.equals( "+" ) )
{
containsPlus = true;
}
else if ( id.equals( "1.1" ) )
{
containsOneDotOne = true;
}
else
{
try
{
realIds.add( oidRegistry.getOid( id ) );
}
catch ( NamingException e )
{
realIds.add( id );
}
}
}
// return nothing
if ( containsOneDotOne )
{
SearchResult result = new ServerSearchResult( "", null, new AttributesImpl(), false );
return new SingletonEnumeration( result );
}
// return everything
if ( containsAsterisk && containsPlus )
{
SearchResult result = new ServerSearchResult( "", null, ( Attributes ) getRootDSE( null ).clone(), false );
return new SingletonEnumeration( result );
}
Attributes attrs = new AttributesImpl();
if ( containsAsterisk )
{
for ( NamingEnumeration ii = getRootDSE( null ).getAll(); ii.hasMore(); /**/ )
{
// add all user attribute
Attribute attr = ( Attribute ) ii.next();
AttributeType type = attrRegistry.lookup( attr.getID() );
if ( type.getUsage() == UsageEnum.USER_APPLICATIONS )
{
attrs.put( attr );
}
// add attributes specifically asked for
else if ( realIds.contains( type.getOid() ) )
{
attrs.put( attr );
}
}
}
else if ( containsPlus )
{
for ( NamingEnumeration ii = getRootDSE( null ).getAll(); ii.hasMore(); /**/ )
{
// add all operational attributes
Attribute attr = ( Attribute ) ii.next();
AttributeType type = attrRegistry.lookup( attr.getID() );
if ( type.getUsage() != UsageEnum.USER_APPLICATIONS )
{
attrs.put( attr );
}
// add user attributes specifically asked for
else if ( realIds.contains( type.getOid() ) )
{
attrs.put( attr );
}
}
}
else
{
for ( NamingEnumeration ii = getRootDSE( null ).getAll(); ii.hasMore(); /**/ )
{
// add user attributes specifically asked for
Attribute attr = ( Attribute ) ii.next();
AttributeType type = attrRegistry.lookup( attr.getID() );
if ( realIds.contains( type.getOid() ) )
{
attrs.put( attr );
}
}
}
SearchResult result = new ServerSearchResult( "", null, attrs, false );
return new SingletonEnumeration( result );
}
throw new LdapNameNotFoundException();
}
Partition backend = getPartition( base );
return backend.search( opContext );
}
/**
* @see Partition#lookup(org.apache.directory.shared.ldap.name.LdapDN,String[])
*/
public Attributes lookup( OperationContext opContext ) throws NamingException
{
LookupOperationContext ctx = (LookupOperationContext)opContext;
LdapDN dn = ctx.getDn();
if ( dn.size() == 0 )
{
Attributes retval = new AttributesImpl();
NamingEnumeration list = rootDSE.getIDs();
if ( ctx.getAttrsId() != null )
{
while ( list.hasMore() )
{
String id = ( String ) list.next();
if ( ctx.getAttrsId().contains( id ) )
{
Attribute attr = rootDSE.get( id );
retval.put( ( Attribute ) attr.clone() );
}
}
}
else
{
while ( list.hasMore() )
{
String id = ( String ) list.next();
Attribute attr = rootDSE.get( id );
retval.put( ( Attribute ) attr.clone() );
}
}
return retval;
}
Partition backend = getPartition( dn );
return backend.lookup( ctx );
}
/**
* @see Partition#hasEntry(OperationContext)
*/
public boolean hasEntry( OperationContext opContext ) throws NamingException
{
LdapDN dn = opContext.getDn();
if ( IS_DEBUG )
{
log.debug( "Check if DN '" + dn + "' exists." );
}
if ( dn.size() == 0 )
{
return true;
}
Partition backend = getPartition( dn );
return backend.hasEntry( opContext );
}
/**
* @see Partition#rename(OperationContext)
*/
public void rename( OperationContext opContext ) throws NamingException
{
Partition backend = getPartition( opContext.getDn() );
backend.rename( opContext );
}
/**
* @see Partition#move(OperationContext)
*/
public void move( OperationContext opContext ) throws NamingException
{
Partition backend = getPartition( opContext.getDn() );
backend.move( opContext );
}
/**
* @see Partition#moveAndRename( OperationContext )
*/
public void moveAndRename( OperationContext opContext ) throws NamingException
{
Partition backend = getPartition( opContext.getDn() );
backend.moveAndRename( opContext );
}
/**
* Gets the partition associated with a normalized dn.
*
* @param dn the normalized distinguished name to resolve to a partition
* @return the backend partition associated with the normalized dn
* @throws NamingException if the name cannot be resolved to a partition
*/
public Partition getPartition( LdapDN dn ) throws NamingException
{
Enumeration<String> rdns = dn.getAll();
Node currentNode = partitionLookupTree;
// This is synchronized so that we can't read the
// partitionList when it is modified.
synchronized ( partitionLookupTree )
{
// Iterate through all the RDN until we find the associated partition
while ( rdns.hasMoreElements() )
{
String rdn = rdns.nextElement();
if ( currentNode == null )
{
break;
}
if ( currentNode instanceof LeafNode )
{
return ( ( LeafNode ) currentNode ).getPartition();
}
BranchNode currentBranch = ( BranchNode ) currentNode;
if ( currentBranch.contains( rdn ) )
{
currentNode = currentBranch.getChild( rdn );
if ( currentNode instanceof LeafNode )
{
return ( ( LeafNode ) currentNode ).getPartition();
}
}
}
}
throw new LdapNameNotFoundException( dn.getUpName() );
}
// ------------------------------------------------------------------------
// Private Methods
// ------------------------------------------------------------------------
public void registerSupportedExtensions( Set extensionOids )
{
Attribute supportedExtension = rootDSE.get( "supportedExtension" );
if ( supportedExtension == null )
{
supportedExtension = new AttributeImpl( "supportedExtension" );
rootDSE.put( supportedExtension );
}
for ( Iterator oids = extensionOids.iterator(); oids.hasNext(); )
{
supportedExtension.add( oids.next() );
}
}
}
| true | false | null | null |
diff --git a/baixing_quanleimu/src/com/xiaomi/mipush/MiPushService.java b/baixing_quanleimu/src/com/xiaomi/mipush/MiPushService.java
index 3fc5234b..00af01a9 100644
--- a/baixing_quanleimu/src/com/xiaomi/mipush/MiPushService.java
+++ b/baixing_quanleimu/src/com/xiaomi/mipush/MiPushService.java
@@ -1,49 +1,49 @@
package com.xiaomi.mipush;
import android.content.Context;
import android.util.Log;
import com.xiaomi.mipush.sdk.MiPushClient;
public class MiPushService {
public static final String TOPIC_BROADCAST = "topic_all";
private static final String TAG = MiPushService.class.getSimpleName();
private static final String MiPush_APP_ID = "1001139";
private static final String MiPush_APP_TOKEN = "800100193139";
private static Context context;
public static void initialize(Context context, MiPushCallback callback) {
Log.d(TAG, "initializing");
MiPushService.context = context;
callback.setCategory(null);
callback.setContext(context);
MiPushClient.initialize(context, MiPush_APP_ID, MiPush_APP_TOKEN,
callback);
}
public static void subscribe(Context context, String topic) {
if (topic != null) {
Log.d(TAG, "subscribe topic: " + topic);
MiPushClient.subscribe(context, topic, null);
}
}
public static void unsubscribe(Context context, String topic) {
if (topic != null) {
Log.d(TAG, "unsubscribe topic: " + topic);
MiPushClient.unsubscribe(context, topic, null);
}
}
public static void setAlias(Context context, String alias) {
if (alias != null) {
Log.d(TAG, "set alias: " + alias);
- MiPushClient.unsubscribe(context, alias, null);
+ MiPushClient.setAlias(context, alias, null);
}
}
}
\ No newline at end of file
| true | false | null | null |
diff --git a/choco-parser/src/main/java/parser/flatzinc/para/ParaserMaster.java b/choco-parser/src/main/java/parser/flatzinc/para/ParaserMaster.java
index 10c7831a1..302d79c51 100644
--- a/choco-parser/src/main/java/parser/flatzinc/para/ParaserMaster.java
+++ b/choco-parser/src/main/java/parser/flatzinc/para/ParaserMaster.java
@@ -1,151 +1,151 @@
/**
* Copyright (c) 1999-2011, Ecole des Mines de Nantes
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Ecole des Mines de Nantes 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 REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND 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 parser.flatzinc.para;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import solver.ResolutionPolicy;
import solver.thread.AbstractParallelMaster;
import util.tools.ArrayUtils;
public class ParaserMaster extends AbstractParallelMaster<ParaserSlave> {
protected static final Logger LOGGER = LoggerFactory.getLogger("fzn");
//***********************************************************************************
// VARIABLES
//***********************************************************************************
int bestVal;
int nbSol;
boolean closeWithSuccess;
ResolutionPolicy policy;
public final static String[][] config = new String[][]{
{"-lf"}, // fix+lf
{"-lf", "-lns", "PGLNS"}, // LNS propag + fix + lf
{"-lf", "-lns", "RLNS"}, // LNS random + fix + lf
{}, // fix
// {"-lf","-i","-bbss","1","-dv"}, // ABS on dec vars + lf
// {"-lf","-i","-bbss","2","-dv"}, // IBS on dec vars + lf
// {"-lf","-i","-bbss","3","-dv"}, // WDeg on dec vars + lf
};
//***********************************************************************************
// CONSTRUCTORS
//***********************************************************************************
public ParaserMaster(int nbCores, String[] args) {
nbCores = Math.min(nbCores, config.length);
slaves = new ParaserSlave[nbCores];
for (int i = 0; i < nbCores; i++) {
String[] options = ArrayUtils.append(args, config[i]);
slaves[i] = new ParaserSlave(this, i, options);
slaves[i].workInParallel();
}
wait = true;
try {
while (wait)
mainThread.sleep(20);
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
}
//***********************************************************************************
// METHODS
//***********************************************************************************
/**
* A slave has CLOSED ITS SEARCH TREE, every one should stop!
*/
public synchronized void wishGranted() {
if (LOGGER.isInfoEnabled()) {
if (nbSol == 0) {
if (!closeWithSuccess) {
LOGGER.info("=====UNKNOWN=====");
} else {
LOGGER.info("=====UNSATISFIABLE=====");
}
} else {
if (!closeWithSuccess && (policy != null && policy != ResolutionPolicy.SATISFACTION)) {
LOGGER.info("=====UNBOUNDED=====");
} else {
LOGGER.info("==========");
}
}
}
System.exit(0);
}
/**
* A solution of cost val has been found
* informs slaves that they must find better
*
* @param val
* @param policy
*/
public synchronized boolean newSol(int val, ResolutionPolicy policy) {
this.policy = policy;
if (nbSol == 0) {
bestVal = val;
}
nbSol++;
boolean isBetter = false;
switch (policy) {
case MINIMIZE:
- if (bestVal > val) {
+ if (bestVal > val || nbSol==1) {
bestVal = val;
isBetter = true;
}
break;
case MAXIMIZE:
- if (bestVal < val) {
+ if (bestVal < val || nbSol==1) {
bestVal = val;
isBetter = true;
}
break;
case SATISFACTION:
bestVal = 1;
isBetter = nbSol == 1;
break;
}
if (isBetter)
for (int i = 0; i < slaves.length; i++)
if(slaves[i]!=null)
slaves[i].findBetterThan(val, policy);
return isBetter;
}
public synchronized void closeWithSuccess() {
this.closeWithSuccess = true;
}
}
| false | true | public synchronized boolean newSol(int val, ResolutionPolicy policy) {
this.policy = policy;
if (nbSol == 0) {
bestVal = val;
}
nbSol++;
boolean isBetter = false;
switch (policy) {
case MINIMIZE:
if (bestVal > val) {
bestVal = val;
isBetter = true;
}
break;
case MAXIMIZE:
if (bestVal < val) {
bestVal = val;
isBetter = true;
}
break;
case SATISFACTION:
bestVal = 1;
isBetter = nbSol == 1;
break;
}
if (isBetter)
for (int i = 0; i < slaves.length; i++)
if(slaves[i]!=null)
slaves[i].findBetterThan(val, policy);
return isBetter;
}
| public synchronized boolean newSol(int val, ResolutionPolicy policy) {
this.policy = policy;
if (nbSol == 0) {
bestVal = val;
}
nbSol++;
boolean isBetter = false;
switch (policy) {
case MINIMIZE:
if (bestVal > val || nbSol==1) {
bestVal = val;
isBetter = true;
}
break;
case MAXIMIZE:
if (bestVal < val || nbSol==1) {
bestVal = val;
isBetter = true;
}
break;
case SATISFACTION:
bestVal = 1;
isBetter = nbSol == 1;
break;
}
if (isBetter)
for (int i = 0; i < slaves.length; i++)
if(slaves[i]!=null)
slaves[i].findBetterThan(val, policy);
return isBetter;
}
|
diff --git a/src/commons/org/codehaus/groovy/grails/commons/ServiceArtefactHandler.java b/src/commons/org/codehaus/groovy/grails/commons/ServiceArtefactHandler.java
index d1284ce82..61507afad 100644
--- a/src/commons/org/codehaus/groovy/grails/commons/ServiceArtefactHandler.java
+++ b/src/commons/org/codehaus/groovy/grails/commons/ServiceArtefactHandler.java
@@ -1,29 +1,33 @@
/*
* Copyright 2004-2005 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.codehaus.groovy.grails.commons;
/**
* @author Marc Palmer ([email protected])
*/
public class ServiceArtefactHandler extends ArtefactHandlerAdapter {
public static final String TYPE = "Service";
public ServiceArtefactHandler() {
super(TYPE, GrailsServiceClass.class, DefaultGrailsServiceClass.class, DefaultGrailsServiceClass.SERVICE,
false);
}
+
+ public boolean isArtefactClass(Class clazz) {
+ return super.isArtefactClass(clazz) && !DomainClassArtefactHandler.isDomainClass(clazz);
+ }
}
| true | false | null | null |
diff --git a/src/main/java/org/jboss/msc/_private/StartingServiceTasks.java b/src/main/java/org/jboss/msc/_private/StartingServiceTasks.java
index 5134321..2bcf26f 100644
--- a/src/main/java/org/jboss/msc/_private/StartingServiceTasks.java
+++ b/src/main/java/org/jboss/msc/_private/StartingServiceTasks.java
@@ -1,310 +1,310 @@
/*
* JBoss, Home of Professional Open Source
*
* Copyright 2013 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.msc._private;
import static org.jboss.msc._private.ServiceController.STATE_FAILED;
import static org.jboss.msc._private.ServiceController.STATE_UP;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceContainer;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceRegistry;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.txn.AttachmentKey;
import org.jboss.msc.txn.Executable;
import org.jboss.msc.txn.ExecuteContext;
import org.jboss.msc.txn.Factory;
import org.jboss.msc.txn.Problem;
import org.jboss.msc.txn.Problem.Severity;
import org.jboss.msc.txn.ServiceContext;
import org.jboss.msc.txn.TaskBuilder;
import org.jboss.msc.txn.TaskController;
import org.jboss.msc.txn.Transaction;
/**
* Tasks executed when a service is starting.
*
* @author <a href="mailto:[email protected]">Flavia Rainone</a>
*
*/
final class StartingServiceTasks {
// keep track of services that have failed to start at current transaction
static final AttachmentKey<Set<Service<?>>> FAILED_SERVICES = AttachmentKey.<Set<Service<?>>>create(new Factory<Set<Service<?>>>() {
@Override
public Set<Service<?>> create() {
return new HashSet<Service<?>>();
}
});
/**
* Creates starting service tasks. When all created tasks finish execution, {@code service} will enter {@code UP}
* state.
*
* @param serviceController starting service
* @param taskDependencies the tasks that must be first concluded before service can start
* @param transaction the active transaction
* @param context the service context
* @return the final task to be executed. Can be used for creating tasks that depend on the
* conclusion of starting transition.
*/
static <T> TaskController<Void> create(ServiceController<T> serviceController,
Collection<TaskController<?>> taskDependencies, Transaction transaction, ServiceContext context) {
final Service<T> serviceValue = serviceController.getService();
// start service task builder
final TaskBuilder<T> startBuilder = context.newTask(new StartServiceTask<T>(serviceValue, transaction)).setTraits(serviceValue);
if (hasDependencies(serviceController)) {
// notify dependent is starting to dependencies
- final TaskController<Void> notifyDependentStart = context.newTask(new NotifyDependentStartTask(transaction, serviceController)).release();
+ final TaskController<Void> notifyDependentStart = context.newTask(new NotifyDependentStartTask(transaction, serviceController)).addDependencies(taskDependencies).release();
startBuilder.addDependency(notifyDependentStart);
} else {
startBuilder.addDependencies(taskDependencies);
}
// start service
final TaskController<T> start = startBuilder.release();
return context.newTask(new SetServiceUpTask<T>(serviceController, start, transaction)).addDependency(start).release();
}
/**
* Creates starting service tasks. When all created tasks finish execution, {@code service} will enter {@code UP}
* state.
*
* @param serviceController starting service
* @param taskDependency the task that must be first concluded before service can start
* @param transaction the active transaction
* @param context the service context
* @return the final task to be executed. Can be used for creating tasks that depend on the
* conclusion of starting transition.
*/
static <T> TaskController<Void> create(ServiceController<T> serviceController,
TaskController<?> taskDependency, Transaction transaction, ServiceContext context) {
assert taskDependency != null;
final List<TaskController<?>> taskDependencies = new ArrayList<TaskController<?>>(1);
taskDependencies.add(taskDependency);
return create(serviceController, taskDependencies, transaction, context);
}
private static boolean hasDependencies(ServiceController<?> service) {
return service.getDependencies().length > 0;
}
/**
* Task that notifies dependencies that a dependent service is about to start
*/
private static class NotifyDependentStartTask implements Executable<Void> {
private final Transaction transaction;
private final ServiceController<?> serviceController;
public NotifyDependentStartTask(Transaction transaction, ServiceController<?> serviceController) {
this.transaction = transaction;
this.serviceController = serviceController;
}
@Override
public void execute(ExecuteContext<Void> context) {
for (AbstractDependency<?> dependency: serviceController.getDependencies()) {
ServiceController<?> dependencyController = dependency.getDependencyRegistration().getController();
if (dependencyController != null) {
dependencyController.dependentStarted(transaction, context);
}
}
context.complete();
}
}
/**
* Task that starts service.
*
* @author <a href="mailto:[email protected]">David M. Lloyd</a>
* @author <a href="mailto:[email protected]">Flavia Rainone</a>
*/
static class StartServiceTask<T> implements Executable<T> {
private final Service<T> service;
private final Transaction transaction;
StartServiceTask(final Service<T> service, final Transaction transaction) {
this.service = service;
this.transaction = transaction;
}
/**
* Perform the task.
*
* @param context
*/
public void execute(final ExecuteContext<T> context) {
service.start(new StartContext<T>() {
@Override
public void complete(T result) {
context.complete(result);
}
@Override
public void complete() {
context.complete();
}
@Override
public void addProblem(Problem reason) {
context.addProblem(reason);
}
@Override
public void addProblem(Severity severity, String message) {
context.addProblem(severity, message);
}
@Override
public void addProblem(Severity severity, String message, Throwable cause) {
context.addProblem(severity, message, cause);
}
@Override
public void addProblem(String message, Throwable cause) {
context.addProblem(message, cause);
}
@Override
public void addProblem(String message) {
context.addProblem(message);
}
@Override
public void addProblem(Throwable cause) {
context.addProblem(cause);
}
@Override
public boolean isCancelRequested() {
return context.isCancelRequested();
}
@Override
public void cancelled() {
context.cancelled();
}
@Override
public <K> TaskBuilder<K> newTask(Executable<K> task) throws IllegalStateException {
return context.newTask(task);
}
@Override
public TaskBuilder<Void> newTask() throws IllegalStateException {
return context.newTask();
}
public <T> ServiceBuilder<T> addService(ServiceRegistry registry, ServiceName name) {
return context.addService(registry, name);
}
@Override
public void enableService(ServiceRegistry registry, ServiceName name) throws IllegalStateException {
context.enableService(registry, name);
}
@Override
public void disableService(ServiceRegistry registry, ServiceName name) throws IllegalStateException {
context.disableService(registry, name);
}
@Override
public void removeService(ServiceRegistry registry, ServiceName name) throws IllegalStateException {
context.removeService(registry, name);
}
@Override
public void enableRegistry(ServiceRegistry registry) {
context.enableRegistry(registry);
}
@Override
public void disableRegistry(ServiceRegistry registry) {
context.disableRegistry(registry);
}
@Override
public void removeRegistry(ServiceRegistry registry) {
context.removeRegistry(registry);
}
@Override
public void shutdownContainer(ServiceContainer container) {
context.shutdownContainer(container);
}
@Override
public void fail() {
transaction.getAttachment(StartingServiceTasks.FAILED_SERVICES).add(service);
complete();
}
});
}
}
/**
* Task that sets service at UP state, and performs service value injection.
*/
private static class SetServiceUpTask<T> implements Executable<Void> {
private final ServiceController<T> service;
private final TaskController<T> serviceStartTask;
private final Transaction transaction;
private SetServiceUpTask (ServiceController<T> service, TaskController<T> serviceStartTask, Transaction transaction) {
this.service = service;
this.serviceStartTask = serviceStartTask;
this.transaction = transaction;
}
@Override
public void execute(ExecuteContext<Void> context) {
try {
T result = serviceStartTask.getResult();
// service failed
if (result == null && transaction.getAttachment(FAILED_SERVICES).contains(service.getService())) {
MSCLogger.FAIL.startFailed(service.getServiceName());
service.setTransition(STATE_FAILED, transaction, context);
} else {
service.setValue(result);
service.setTransition(STATE_UP, transaction, context);
}
} finally {
context.complete();
}
}
}
}
| true | false | null | null |
diff --git a/scm-webapp/src/main/java/sonia/scm/plugin/DefaultPluginLoader.java b/scm-webapp/src/main/java/sonia/scm/plugin/DefaultPluginLoader.java
index c14e4e0cf..adbfc353e 100644
--- a/scm-webapp/src/main/java/sonia/scm/plugin/DefaultPluginLoader.java
+++ b/scm-webapp/src/main/java/sonia/scm/plugin/DefaultPluginLoader.java
@@ -1,379 +1,379 @@
/**
* Copyright (c) 2010, Sebastian Sdorra
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of SCM-Manager; nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* http://bitbucket.org/sdorra/scm-manager
*
*/
package sonia.scm.plugin;
//~--- non-JDK imports --------------------------------------------------------
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sonia.scm.SCMContext;
import sonia.scm.plugin.ext.DefaultExtensionScanner;
import sonia.scm.plugin.ext.ExtensionObject;
import sonia.scm.plugin.ext.ExtensionProcessor;
import sonia.scm.util.IOUtil;
//~--- JDK imports ------------------------------------------------------------
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import javax.xml.bind.JAXB;
/**
*
* @author Sebastian Sdorra
*/
public class DefaultPluginLoader implements PluginLoader
{
/** Field description */
public static final String ENCODING = "UTF-8";
/** Field description */
public static final String PATH_PLUGINCONFIG = "META-INF/scm/plugin.xml";
/** Field description */
public static final String REGE_COREPLUGIN =
"^.*(?:/|\\\\)WEB-INF(?:/|\\\\)lib(?:/|\\\\).*\\.jar$";
/** the logger for DefaultPluginLoader */
private static final Logger logger =
LoggerFactory.getLogger(DefaultPluginLoader.class);
//~--- constructors ---------------------------------------------------------
/**
* Constructs ...
*
*/
public DefaultPluginLoader()
{
ClassLoader classLoader = getClassLoader();
try
{
load(classLoader);
}
catch (IOException ex)
{
throw new RuntimeException(ex);
}
}
//~--- methods --------------------------------------------------------------
/**
* Method description
*
*
* @param processor
*/
@Override
public void processExtensions(ExtensionProcessor processor)
{
Set<ExtensionObject> extensions = new HashSet<ExtensionObject>();
ClassLoader classLoader = getClassLoader();
DefaultExtensionScanner scanner = new DefaultExtensionScanner();
for (Plugin plugin : installedPlugins)
{
if (logger.isDebugEnabled())
{
logger.debug("search extensions from plugin {}",
plugin.getInformation().getId());
}
InputStream input = null;
try
{
Set<String> packageSet = plugin.getPackageSet();
if (packageSet == null)
{
packageSet = new HashSet<String>();
}
packageSet.add(SCMContext.DEFAULT_PACKAGE);
File pluginFile = new File(plugin.getPath());
if (pluginFile.exists())
{
if (logger.isTraceEnabled())
{
String type = pluginFile.isDirectory()
? "directory"
: "jar";
logger.trace("search extensions in packages {} of {} plugin {}",
- new Object[] { extensions,
+ new Object[] { packageSet,
type, pluginFile });
}
if (pluginFile.isDirectory())
{
scanner.processExtensions(classLoader, extensions, pluginFile,
packageSet);
}
else
{
input = new FileInputStream(plugin.getPath());
scanner.processExtensions(classLoader, extensions, input,
packageSet);
}
}
else
{
logger.error("could not find plugin file {}", plugin.getPath());
}
}
catch (IOException ex)
{
logger.error("error during extension processing", ex);
}
finally
{
IOUtil.close(input);
}
}
if (logger.isTraceEnabled())
{
logger.trace("start processing {} extensions", extensions.size());
}
for (ExtensionObject exo : extensions)
{
if (logger.isTraceEnabled())
{
logger.trace("process extension {}", exo.getExtensionClass());
}
processor.processExtension(exo.getExtension(), exo.getExtensionClass());
}
}
//~--- get methods ----------------------------------------------------------
/**
* Method description
*
*
* @return
*/
@Override
public Collection<Plugin> getInstalledPlugins()
{
return installedPlugins;
}
//~--- methods --------------------------------------------------------------
/**
* Method description
*
*
* @param path
*
* @return
*/
private String decodePath(String path)
{
File file = new File(path);
if (!file.exists())
{
try
{
path = URLDecoder.decode(path, ENCODING);
}
catch (IOException ex)
{
logger.error("could not decode path ".concat(path), ex);
}
}
else if (logger.isTraceEnabled())
{
logger.trace(
"{} seems not to be a file path or the file does not exists", path);
}
return path;
}
/**
* Method description
*
*
* @param classLoader
*
* @throws IOException
*/
private void load(ClassLoader classLoader) throws IOException
{
Enumeration<URL> urlEnum = classLoader.getResources(PATH_PLUGINCONFIG);
if (urlEnum != null)
{
while (urlEnum.hasMoreElements())
{
URL url = urlEnum.nextElement();
loadPlugin(url);
}
if (logger.isDebugEnabled())
{
logger.debug("loaded {} plugins", installedPlugins.size());
}
}
else if (logger.isWarnEnabled())
{
logger.warn("no plugin descriptor found");
}
}
/**
* Method description
*
*
* @param url
*/
private void loadPlugin(URL url)
{
String path = url.toExternalForm();
if (logger.isTraceEnabled())
{
logger.trace("try to load plugin from {}", path);
}
try
{
if (path.startsWith("file:"))
{
path = path.substring("file:".length(),
path.length()
- "/META-INF/scm/plugin.xml".length());
}
else
{
// jar:file:/some/path/file.jar!/META-INF/scm/plugin.xml
path = path.substring("jar:file:".length(), path.lastIndexOf("!"));
path = decodePath(path);
}
boolean corePlugin = path.matches(REGE_COREPLUGIN);
if (logger.isInfoEnabled())
{
- logger.info("load {} plugin {}", corePlugin
+ logger.info("load {}plugin {}", corePlugin
? "core "
: " ", path);
}
Plugin plugin = JAXB.unmarshal(url, Plugin.class);
PluginInformation info = plugin.getInformation();
PluginCondition condition = plugin.getCondition();
if (condition != null)
{
info.setCondition(condition);
}
if (info != null)
{
info.setState(corePlugin
? PluginState.CORE
: PluginState.INSTALLED);
}
plugin.setPath(path);
if (logger.isDebugEnabled())
{
logger.debug("add plugin {} to installed plugins", info.getId());
}
installedPlugins.add(plugin);
}
catch (Exception ex)
{
logger.error("could not load plugin ".concat(path), ex);
}
}
//~--- get methods ----------------------------------------------------------
/**
* TODO create util method
*
*
* @return
*/
private ClassLoader getClassLoader()
{
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader == null)
{
if (logger.isWarnEnabled())
{
logger.warn("could not use context classloader, try to use default");
}
classLoader = DefaultPluginManager.class.getClassLoader();
}
return classLoader;
}
//~--- fields ---------------------------------------------------------------
/** Field description */
private Set<Plugin> installedPlugins = new HashSet<Plugin>();
}
| false | false | null | null |
diff --git a/jodd-joy/src/test/java/jodd/joy/jspp/JsppTest.java b/jodd-joy/src/test/java/jodd/joy/jspp/JsppTest.java
index 9d742ee21..e4647b73d 100644
--- a/jodd-joy/src/test/java/jodd/joy/jspp/JsppTest.java
+++ b/jodd-joy/src/test/java/jodd/joy/jspp/JsppTest.java
@@ -1,26 +1,26 @@
// Copyright (c) 2003-2014, Jodd Team (jodd.org). All Rights Reserved.
package jodd.joy.jspp;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class JsppTest {
@Test
public void testJspp() {
String content = "<h1>hello</h1><pp:go /><pp:go name=\'jpp\'/>";
Jspp jspp = new Jspp() {
@Override
protected String loadMacro(String macroName) {
- return "Hello $name";
+ return "Hello ${name}";
}
};
String result = jspp.process(content);
- assertEquals("<h1>hello</h1>Hello $nameHello jpp", result);
+ assertEquals("<h1>hello</h1>Hello ${name}Hello jpp", result);
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/src/org/python/core/PyUnicode.java b/src/org/python/core/PyUnicode.java
index 544eed20..03c610d5 100644
--- a/src/org/python/core/PyUnicode.java
+++ b/src/org/python/core/PyUnicode.java
@@ -1,370 +1,370 @@
package org.python.core;
import org.python.expose.ExposedMethod;
import org.python.expose.ExposedNew;
import org.python.expose.ExposedType;
import org.python.expose.MethodType;
import org.python.modules._codecs;
/**
* a builtin python unicode string.
*/
@ExposedType(name = "unicode", base = PyBaseString.class)
public class PyUnicode extends PyString {
public static final PyType TYPE = PyType.fromClass(PyUnicode.class);
// for PyJavaClass.init()
public PyUnicode() {
this(TYPE, "");
}
public PyUnicode(String string) {
this(TYPE, string);
}
public PyUnicode(PyType subtype, String string) {
super(subtype, string);
}
public PyUnicode(PyString pystring) {
this(TYPE, pystring);
}
public PyUnicode(PyType subtype, PyString pystring) {
this(subtype, pystring instanceof PyUnicode ? pystring.string : pystring.decode()
.toString());
}
public PyUnicode(char c) {
this(TYPE,String.valueOf(c));
}
/**
* Creates a PyUnicode from an already interned String. Just means it won't
* be reinterned if used in a place that requires interned Strings.
*/
public static PyUnicode fromInterned(String interned) {
PyUnicode uni = new PyUnicode(TYPE, interned);
uni.interned = true;
return uni;
}
@ExposedNew
final static PyObject unicode_new(PyNewWrapper new_, boolean init, PyType subtype,
PyObject[] args, String[] keywords) {
ArgParser ap = new ArgParser("unicode",
args,
keywords,
new String[] {"string",
"encoding",
"errors"},
0);
PyObject S = ap.getPyObject(0, null);
String encoding = ap.getString(1, null);
String errors = ap.getString(2, null);
if (new_.for_type == subtype) {
if (S == null) {
return new PyUnicode("");
}
if (S instanceof PyUnicode) {
return new PyUnicode(((PyUnicode)S).string);
}
if (S instanceof PyString) {
return new PyUnicode(codecs.decode((PyString)S, encoding, errors).toString());
}
return S.__unicode__();
} else {
if (S == null) {
return new PyUnicodeDerived(subtype, Py.EmptyString);
}
if (S instanceof PyUnicode) {
return new PyUnicodeDerived(subtype, (PyUnicode)S);
} else {
return new PyUnicodeDerived(subtype, S.__str__());
}
}
}
public PyString createInstance(String str){
return new PyUnicode(str);
}
public PyObject __mod__(PyObject other) {
return unicode___mod__(other);
}
@ExposedMethod
final PyObject unicode___mod__(PyObject other){
StringFormatter fmt = new StringFormatter(string, true);
return fmt.format(other).__unicode__();
}
@ExposedMethod
final PyUnicode unicode___unicode__() {
return str___unicode__();
}
public PyString __str__() {
return unicode___str__();
}
@ExposedMethod
final PyString unicode___str__() {
return new PyString(encode());
}
final int unicode___len__() {
return str___len__();
}
public PyString __repr__() {
return unicode___repr__();
}
@ExposedMethod
final PyString unicode___repr__() {
- return new PyString("u'" + encode_UnicodeEscape(string, false) + "'");
+ return new PyString("u" + encode_UnicodeEscape(string, true));
}
@ExposedMethod(type = MethodType.CMP)
final int unicode___cmp__(PyObject other) {
return str___cmp__(other);
}
@ExposedMethod(type = MethodType.BINARY)
final PyObject unicode___eq__(PyObject other) {
return str___eq__(other);
}
@ExposedMethod(type = MethodType.BINARY)
final PyObject unicode___ne__(PyObject other) {
return str___ne__(other);
}
@ExposedMethod
final int unicode___hash__() {
return str___hash__();
}
protected PyObject pyget(int i) {
return Py.makeCharacter(string.charAt(i), true);
}
@ExposedMethod
final boolean unicode___contains__(PyObject o) {
return str___contains__(o);
}
@ExposedMethod(type = MethodType.BINARY)
final PyObject unicode___mul__(PyObject o) {
return str___mul__(o);
}
@ExposedMethod(type = MethodType.BINARY)
final PyObject unicode___rmul__(PyObject o) {
return str___rmul__(o);
}
@ExposedMethod(type = MethodType.BINARY)
final PyObject unicode___add__(PyObject generic_other) {
return str___add__(generic_other);
}
@ExposedMethod
final PyObject unicode_lower() {
return new PyUnicode(str_lower());
}
@ExposedMethod
final PyObject unicode_upper() {
return new PyUnicode(str_upper());
}
@ExposedMethod
final PyObject unicode_title() {
return new PyUnicode(str_title());
}
@ExposedMethod
final PyObject unicode_swapcase() {
return new PyUnicode(str_swapcase());
}
@ExposedMethod(defaults = "null")
final PyObject unicode_strip(String sep) {
return new PyUnicode(str_strip(sep));
}
@ExposedMethod(defaults = "null")
final PyObject unicode_lstrip(String sep) {
return new PyUnicode(str_lstrip(sep));
}
@ExposedMethod(defaults = "null")
final PyObject unicode_rstrip(String sep) {
return new PyUnicode(str_rstrip(sep));
}
@ExposedMethod(defaults = {"null", "-1"})
final PyList unicode_split(String sep, int maxsplit) {
return str_split(sep, maxsplit);
}
@ExposedMethod(defaults = "false")
final PyList unicode_splitlines(boolean keepends) {
return str_splitlines(keepends);
}
protected PyString fromSubstring(int begin, int end) {
return new PyUnicode(string.substring(begin, end));
}
@ExposedMethod(defaults = {"0", "null"})
final int unicode_index(String sub, int start, PyObject end) {
return str_index(sub, start, end);
}
@ExposedMethod(defaults = {"0", "null"})
final int unicode_rindex(String sub, int start, PyObject end) {
return str_rindex(sub, start, end);
}
@ExposedMethod(defaults = {"0", "null"})
final int unicode_count(String sub, int start, PyObject end) {
return str_count(sub, start, end);
}
@ExposedMethod(defaults = {"0", "null"})
final int unicode_find(String sub, int start, PyObject end) {
return str_find(sub, start, end);
}
@ExposedMethod(defaults = {"0", "null"})
final int unicode_rfind(String sub, int start, PyObject end) {
return str_rfind(sub, start, end);
}
@ExposedMethod
final PyObject unicode_ljust(int width) {
return new PyUnicode(str_ljust(width));
}
@ExposedMethod
final PyObject unicode_rjust(int width) {
return new PyUnicode(str_rjust(width));
}
@ExposedMethod
final PyObject unicode_center(int width) {
return new PyUnicode(str_center(width));
}
@ExposedMethod
final PyObject unicode_zfill(int width) {
return new PyUnicode(str_zfill(width));
}
@ExposedMethod(defaults = "8")
final PyObject unicode_expandtabs(int tabsize) {
return new PyUnicode(str_expandtabs(tabsize));
}
@ExposedMethod
final PyObject unicode_capitalize() {
return new PyUnicode(str_capitalize());
}
@ExposedMethod(defaults = "null")
final PyObject unicode_replace(PyObject oldPiece, PyObject newPiece, PyObject maxsplit) {
return str_replace(oldPiece, newPiece, maxsplit);
}
@ExposedMethod
final PyString unicode_join(PyObject seq) {
return str_join(seq);
}
@ExposedMethod(defaults = {"0", "null"})
final boolean unicode_startswith(String prefix, int start, PyObject end) {
return str_startswith(prefix, start, end);
}
@ExposedMethod(defaults = {"0", "null"})
final boolean unicode_endswith(String suffix, int start, PyObject end) {
return str_endswith(suffix, start, end);
}
@ExposedMethod
final PyObject unicode_translate(PyObject table) {
String trans = _codecs.charmap_decode(string, "ignore", table, true).__getitem__(0).toString();
return new PyUnicode(trans);
}
@ExposedMethod
final boolean unicode_islower() {
return str_islower();
}
@ExposedMethod
final boolean unicode_isupper() {
return str_isupper();
}
@ExposedMethod
final boolean unicode_isalpha() {
return str_isalpha();
}
@ExposedMethod
final boolean unicode_isalnum() {
return str_isalnum();
}
@ExposedMethod
final boolean unicode_isdecimal() {
return str_isdecimal();
}
@ExposedMethod
final boolean unicode_isdigit() {
return str_isdigit();
}
@ExposedMethod
final boolean unicode_isnumeric() {
return str_isnumeric();
}
@ExposedMethod
final boolean unicode_istitle() {
return str_istitle();
}
@ExposedMethod
final boolean unicode_isspace() {
return str_isspace();
}
@ExposedMethod
final boolean unicode_isunicode() {
return true;
}
@ExposedMethod(defaults = {"null", "null"})
final String unicode_encode(String encoding, String errors) {
return str_encode(encoding, errors);
}
@ExposedMethod(defaults = {"null", "null"})
final PyObject unicode_decode(String encoding, String errors) {
return str_decode(encoding, errors);
}
@ExposedMethod
final PyTuple unicode___getnewargs__() {
return new PyTuple(new PyUnicode(this.string));
}
}
| true | false | null | null |
diff --git a/activejdbc-instrumentation/src/main/java/org/javalite/instrumentation/ModelInstrumentation.java b/activejdbc-instrumentation/src/main/java/org/javalite/instrumentation/ModelInstrumentation.java
index 9a9e0eba..c4e51aed 100644
--- a/activejdbc-instrumentation/src/main/java/org/javalite/instrumentation/ModelInstrumentation.java
+++ b/activejdbc-instrumentation/src/main/java/org/javalite/instrumentation/ModelInstrumentation.java
@@ -1,137 +1,138 @@
/*
Copyright 2009-2010 Igor Polevoy
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.javalite.instrumentation;
import javassist.*;
import java.net.URISyntaxException;
-import java.net.URL;
+import java.net.URI;
+import java.io.File;
public class ModelInstrumentation{
private CtClass modelClass;
public ModelInstrumentation() throws NotFoundException {
ClassPool cp = ClassPool.getDefault();
cp.insertClassPath(new ClassClassPath(this.getClass()));
modelClass = ClassPool.getDefault().get("org.javalite.activejdbc.Model");
}
public void instrument(CtClass modelClass) throws InstrumentationException {
try {
addDelegates(modelClass);
CtMethod m = CtNewMethod.make("public static String getClassName() { return \"" + modelClass.getName() + "\"; }", modelClass);
CtMethod getClassNameMethod = modelClass.getDeclaredMethod("getClassName");
modelClass.removeMethod(getClassNameMethod);
modelClass.addMethod(m);
String out = getOutputDirectory(modelClass);
//addSerializationSupport(modelClass);
System.out.println("Instrumented class: " + modelClass.getName() + " in directory: " + out);
modelClass.writeFile(out);
}
catch (Exception e) {
throw new InstrumentationException(e);
}
}
private String getOutputDirectory(CtClass modelClass) throws NotFoundException, URISyntaxException {
- URL u = modelClass.getURL();
- String file = u.getFile();
- file = file.substring(0, file.length() - 6);
+ URI u = modelClass.getURL().toURI();
+ File f = new File(u);
+ String fp = f.getPath();
String className = modelClass.getName();
className = className.replace(".", "/");
- return file.substring(0, file.indexOf(className));
+ return fp.substring(0, fp.indexOf(className));
}
private void addDelegates(CtClass target) throws NotFoundException, CannotCompileException {
CtMethod[] modelMethods = modelClass.getDeclaredMethods();
CtMethod[] targetMethods = target.getDeclaredMethods();
for (CtMethod method : modelMethods) {
if(Modifier.PRIVATE == method.getModifiers()){
continue;
}
CtMethod newMethod = CtNewMethod.delegator(method, target);
// Include the generic signature
for (Object attr : method.getMethodInfo().getAttributes()) {
if (attr instanceof javassist.bytecode.SignatureAttribute) {
javassist.bytecode.SignatureAttribute signatureAttribute = (javassist.bytecode.SignatureAttribute) attr;
newMethod.getMethodInfo().addAttribute(signatureAttribute);
}
}
if (!targetHasMethod(targetMethods, newMethod)) {
target.addMethod(newMethod);
}
else{
System.out.println("Detected method: " + newMethod.getName() + ", skipping delegate.");
}
}
}
//TODO: remove unused methods later
private void addSerializationSupport(CtClass target) throws CannotCompileException, NotFoundException {
CtMethod m = CtNewMethod.make(
"private void writeObject(java.io.ObjectOutputStream out) {\n" +
" out.writeObject(toMap());\n" +
"}", target);
CtClass ioException = ClassPool.getDefault().get("java.io.IOException");
CtClass classNotFoundException = ClassPool.getDefault().get("java.lang.ClassNotFoundException");
m.setExceptionTypes(new CtClass[]{ioException});
target.addMethod(m);
m = CtNewMethod.make(
"private void readObject(java.io.ObjectInputStream in) {\n" +
" fromMap((java.util.Map)in.readObject());\n" +
" }", target);
m.setExceptionTypes(new CtClass[]{ioException, classNotFoundException});
target.addMethod(m);
}
private CtMethod createFindById(CtClass clazz) throws CannotCompileException {
String body = "public static "+ clazz.getName() +" findById(Object obj)\n" +
" {\n" +
" return (" + clazz.getName() + ")org.javalite.activejdbc.Model.findById(obj);\n" +
" }";
return CtNewMethod.make(body, clazz);
}
private CtMethod createFindFirst(CtClass clazz) throws CannotCompileException {
String body = " public static " + clazz.getName() + " findFirst(String s, Object params[])\n" +
" {\n" +
" return (" + clazz.getName() + ")org.javalite.activejdbc.Model.findFirst(s, params);\n" +
" }";
return CtNewMethod.make(body, clazz);
}
private boolean targetHasMethod(CtMethod[] targetMethods, CtMethod delegate) {
for (CtMethod targetMethod : targetMethods) {
if (targetMethod.equals(delegate)) {
return true;
}
}
return false;
}
}
| false | false | null | null |
diff --git a/src/com/ludumdare/evolution/domain/entities/Player.java b/src/com/ludumdare/evolution/domain/entities/Player.java
index 5ddda60..c1c06b6 100644
--- a/src/com/ludumdare/evolution/domain/entities/Player.java
+++ b/src/com/ludumdare/evolution/domain/entities/Player.java
@@ -1,140 +1,140 @@
package com.ludumdare.evolution.domain.entities;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.*;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.ludumdare.evolution.app.Constants;
import java.util.List;
public class Player extends Actor {
private static final float MAX_VELOCITY = 14.0f;
private Body body;
private Fixture playerPhysicsFixture;
private Fixture playerSensorFixture;
private Object groundedPlatform;
public Player(World world) {
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyDef.BodyType.DynamicBody;
body = world.createBody(bodyDef);
PolygonShape poly = new PolygonShape();
poly.setAsBox(0.45f, 1.4f);
playerPhysicsFixture = body.createFixture(poly, 1);
poly.dispose();
CircleShape circle = new CircleShape();
circle.setRadius(0.45f);
circle.setPosition(new Vector2(0, -1.4f));
playerSensorFixture = body.createFixture(circle, 0);
circle.dispose();
body.setBullet(true);
body.setFixedRotation(true);
}
@Override
public void act(float delta) {
super.act(delta);
x = body.getPosition().x * Constants.BOX2D_SCALE_FACTOR;
y = body.getPosition().y * Constants.BOX2D_SCALE_FACTOR;
}
@Override
public void draw(SpriteBatch batch, float parentAlpha) {
}
@Override
public Actor hit(float x, float y) {
return null;
}
public Vector2 getLinearVelocity() {
return body.getLinearVelocity();
}
public Vector2 getBox2dPosition() {
return body.getPosition();
}
public boolean isPlayerGrounded (float deltaTime, World world) {
groundedPlatform = null;
List<Contact> contactList = world.getContactList();
for (int i = 0; i < contactList.size(); i++) {
Contact contact = contactList.get(i);
if (contact.isTouching()
&& (contact.getFixtureA() == playerSensorFixture || contact.getFixtureB() == playerSensorFixture)) {
Vector2 pos = body.getPosition();
WorldManifold manifold = contact.getWorldManifold();
boolean below = true;
for (int j = 0; j < manifold.getNumberOfContactPoints(); j++) {
below &= (manifold.getPoints()[j].y < pos.y - 1.5f);
}
if (below) {
//@todo this user data constant sucks.
if (contact.getFixtureA().getUserData() != null && contact.getFixtureA().getUserData().equals("p")) {
groundedPlatform = contact.getFixtureA().getBody().getUserData();
}
if (contact.getFixtureB().getUserData() != null && contact.getFixtureB().getUserData().equals("p")) {
groundedPlatform = contact.getFixtureB().getBody().getUserData();
}
return true;
}
return false;
}
}
return false;
}
public Object getGroundedPlatform() {
return groundedPlatform;
}
public float getMaxVelocity() {
return MAX_VELOCITY;
}
public void limitLinearVelocity(Vector2 vel) {
vel.x = Math.signum(vel.x) * MAX_VELOCITY;
body.setLinearVelocity(vel.x, vel.y);
}
public void setLinearVelocity(float v, float y) {
- body.setLinearVelocity(x, y);
+ body.setLinearVelocity(v, y);
}
public void setFriction(float friction) {
playerPhysicsFixture.setFriction(friction);
playerSensorFixture.setFriction(friction);
}
public void applyLinearImpulse(float i, float i1, float x, float y) {
body.applyLinearImpulse(i, i1, x, y);
}
public void setTransform(float x, float v, int i) {
body.setTransform(x, v, i);
}
public void setAwake(boolean awake) {
body.setAwake(awake);
}
}
diff --git a/src/com/ludumdare/evolution/domain/screens/GameScreen.java b/src/com/ludumdare/evolution/domain/screens/GameScreen.java
index 39bb63e..18e2712 100644
--- a/src/com/ludumdare/evolution/domain/screens/GameScreen.java
+++ b/src/com/ludumdare/evolution/domain/screens/GameScreen.java
@@ -1,195 +1,199 @@
package com.ludumdare.evolution.domain.screens;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.physics.box2d.*;
import com.badlogic.gdx.utils.TimeUtils;
import com.ludumdare.evolution.LudumDareMain;
import com.ludumdare.evolution.domain.controllers.GameController;
import com.ludumdare.evolution.domain.entities.Player;
import com.ludumdare.evolution.domain.scene2d.AbstractScreen;
import java.util.List;
public class GameScreen extends AbstractScreen {
private World world;
private Box2DDebugRenderer renderer;
private OrthographicCamera cam;
private long lastGroundTime = 0;
private float stillTime = 0;
private boolean jump;
private Vector3 point = new Vector3();
@Override
- public void dispose () {
+ public void dispose() {
world.dispose();
renderer.dispose();
batch.dispose();
super.dispose();
}
public GameScreen(LudumDareMain game) {
super(game);
world = new World(new Vector2(0, -40), true);
float y1 = -1; // (float)Math.random() * 0.1f + 1;
float y2 = y1;
for (int i = 0; i < 50; i++) {
Body ground = createEdge(BodyDef.BodyType.StaticBody, -50 + i * 2, y1, -50 + i * 2 + 2, y2, 0);
y1 = y2;
y2 = -1; // (float)Math.random() + 1;
}
renderer = new Box2DDebugRenderer();
Gdx.input.setInputProcessor(this);
cam = new OrthographicCamera(28, 20);
Player player = new Player(world);
GameController.getInstance().setCurrentPlayer(player);
}
- private Body createEdge (BodyDef.BodyType type, float x1, float y1, float x2, float y2, float density) {
+ private Body createEdge(BodyDef.BodyType type, float x1, float y1, float x2, float y2, float density) {
BodyDef def = new BodyDef();
def.type = type;
Body box = world.createBody(def);
EdgeShape poly = new EdgeShape();
poly.set(new Vector2(0, 0), new Vector2(x2 - x1, y2 - y1));
box.createFixture(poly, density);
box.setTransform(x1, y1, 0);
poly.dispose();
return box;
}
@Override
public void render(float delta) {
- Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
-
Player currentPlayer = GameController.getInstance().getCurrentPlayer();
- cam.position.set(currentPlayer.x, currentPlayer.y, 0);
+ Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
+
+ cam.position.set(currentPlayer.getBox2dPosition().x, currentPlayer.getBox2dPosition().y, 0);
cam.update();
renderer.render(world, cam.combined);
Vector2 vel = currentPlayer.getLinearVelocity();
Vector2 pos = currentPlayer.getBox2dPosition();
boolean grounded = currentPlayer.isPlayerGrounded(Gdx.graphics.getDeltaTime(), world);
if (grounded) {
lastGroundTime = TimeUtils.nanoTime();
} else {
if (TimeUtils.nanoTime() - lastGroundTime < 100000000) {
grounded = true;
}
}
// cap max velocity on x
if (Math.abs(vel.x) > currentPlayer.getMaxVelocity()) {
- currentPlayer.limitLinearVelocity(vel);
+
+ vel.x = Math.signum(vel.x) * currentPlayer.getMaxVelocity();
+ currentPlayer.setLinearVelocity(vel.x, vel.y);
+
}
// calculate stilltime & damp
if (!Gdx.input.isKeyPressed(Input.Keys.A) && !Gdx.input.isKeyPressed(Input.Keys.D)) {
stillTime += Gdx.graphics.getDeltaTime();
currentPlayer.setLinearVelocity(vel.x * 0.9f, vel.y);
} else {
stillTime = 0;
}
// disable friction while jumping
if (!grounded) {
currentPlayer.setFriction(0.0f);
} else {
if (!Gdx.input.isKeyPressed(Input.Keys.A) && !Gdx.input.isKeyPressed(Input.Keys.D) && stillTime > 0.2) {
currentPlayer.setFriction(1000f);
} else {
currentPlayer.setFriction(0.2f);
}
// dampen sudden changes in x/y of a MovingPlatform a little bit, otherwise
// character hops :)
Object groundedPlatform = currentPlayer.getGroundedPlatform();
// if (groundedPlatform != null && groundedPlatform instanceof MovingPlatform
// && ((MovingPlatform) groundedPlatform).dist == 0) {
// currentPlayer.applyLinearImpulse(0, -24, pos.x, pos.y);
// }
}
// since Box2D 2.2 we need to reset the friction of any existing contacts
List<Contact> contacts = world.getContactList();
for (int i = 0; i < world.getContactCount(); i++) {
Contact contact = contacts.get(i);
contact.resetFriction();
}
// apply left impulse, but only if max velocity is not reached yet
if (Gdx.input.isKeyPressed(Input.Keys.A) && vel.x > -currentPlayer.getMaxVelocity()) {
currentPlayer.applyLinearImpulse(-2f, 0, pos.x, pos.y);
}
// apply right impulse, but only if max velocity is not reached yet
if (Gdx.input.isKeyPressed(Input.Keys.D) && vel.x < currentPlayer.getMaxVelocity()) {
currentPlayer.applyLinearImpulse(2f, 0, pos.x, pos.y);
}
// jump, but only when grounded
if (jump) {
jump = false;
if (grounded) {
currentPlayer.setLinearVelocity(vel.x, 0);
+ System.out.println("vel before: " + vel.x);
System.out.println("jump before: " + currentPlayer.getLinearVelocity());
currentPlayer.setTransform(pos.x, pos.y + 0.01f, 0);
currentPlayer.applyLinearImpulse(0, 40, pos.x, pos.y);
System.out.println("jump, " + currentPlayer.getLinearVelocity());
}
}
// // update platforms
// for (int i = 0; i < platforms.size; i++) {
// Platform platform = platforms.get(i);
// platform.update(Math.max(1 / 30.0f, Gdx.graphics.getDeltaTime()));
// }
- world.step(delta, 4, 4);
+ world.step(Gdx.graphics.getDeltaTime(), 4, 4);
currentPlayer.setAwake(true);
cam.project(point.set(pos.x, pos.y, 0));
}
@Override
- public boolean keyDown (int keycode) {
+ public boolean keyDown(int keycode) {
if (keycode == Input.Keys.W) jump = true;
return false;
}
@Override
- public boolean keyUp (int keycode) {
+ public boolean keyUp(int keycode) {
if (keycode == Input.Keys.W) jump = false;
return false;
}
}
| false | false | null | null |
diff --git a/src/com/commonsware/cwac/sacklist/SackOfViewsAdapter.java b/src/com/commonsware/cwac/sacklist/SackOfViewsAdapter.java
index bc16a07..727d907 100644
--- a/src/com/commonsware/cwac/sacklist/SackOfViewsAdapter.java
+++ b/src/com/commonsware/cwac/sacklist/SackOfViewsAdapter.java
@@ -1,168 +1,174 @@
/***
Copyright (c) 2008-2009 CommonsWare, LLC
Portions (c) 2009 Google, Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may
not use this file except in compliance with the License. You may obtain
a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.commonsware.cwac.sacklist;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListAdapter;
import java.util.ArrayList;
import java.util.List;
/**
* Adapter that simply returns row views from a list.
*
* If you supply a size, you must implement newView(), to
* create a required view. The adapter will then cache these
* views.
*
* If you supply a list of views in the constructor, that
* list will be used directly. If any elements in the list
* are null, then newView() will be called just for those
* slots.
*
* Subclasses may also wish to override areAllItemsEnabled()
* (default: false) and isEnabled() (default: false), if some
* of their rows should be selectable.
*
* It is assumed each view is unique, and therefore will not
* get recycled.
*
* Note that this adapter is not designed for long lists. It
* is more for screens that should behave like a list. This
* is particularly useful if you combine this with other
* adapters (e.g., SectionedAdapter) that might have an
* arbitrary number of rows, so it all appears seamless.
*/
public class SackOfViewsAdapter extends BaseAdapter {
private List<View> views=null;
/**
* Constructor creating an empty list of views, but with
* a specified count. Subclasses must override newView().
*/
public SackOfViewsAdapter(int count) {
super();
views=new ArrayList<View>(count);
for (int i=0;i<count;i++) {
views.add(null);
}
}
/**
* Constructor wrapping a supplied list of views.
* Subclasses must override newView() if any of the elements
* in the list are null.
*/
public SackOfViewsAdapter(List<View> views) {
super();
this.views=views;
}
/**
* Get the data item associated with the specified
* position in the data set.
* @param position Position of the item whose data we want
*/
+ @Override
public Object getItem(int position) {
return(views.get(position));
}
/**
* How many items are in the data set represented by this
* Adapter.
*/
+ @Override
public int getCount() {
return(views.size());
}
/**
* Returns the number of types of Views that will be
* created by getView().
*/
+ @Override
public int getViewTypeCount() {
return(getCount());
}
/**
* Get the type of View that will be created by getView()
* for the specified item.
* @param position Position of the item whose data we want
*/
+ @Override
public int getItemViewType(int position) {
return(position);
}
/**
* Are all items in this ListAdapter enabled? If yes it
* means all items are selectable and clickable.
*/
- public boolean areAllItemsSelectable() {
+ @Override
+ public boolean areAllItemsEnabled() {
return(false);
}
/**
* Returns true if the item at the specified position is
* not a separator.
* @param position Position of the item whose data we want
*/
+ @Override
public boolean isEnabled(int position) {
return(false);
}
/**
* Get a View that displays the data at the specified
* position in the data set.
* @param position Position of the item whose data we want
* @param convertView View to recycle, if not null
* @param parent ViewGroup containing the returned View
*/
@Override
public View getView(int position, View convertView,
ViewGroup parent) {
View result=views.get(position);
if (result==null) {
result=newView(position, parent);
views.set(position, result);
}
return(result);
}
/**
* Get the row id associated with the specified position
* in the list.
* @param position Position of the item whose data we want
*/
@Override
public long getItemId(int position) {
return(position);
}
/**
* Create a new View to go into the list at the specified
* position.
* @param position Position of the item whose data we want
* @param parent ViewGroup containing the returned View
*/
protected View newView(int position, ViewGroup parent) {
throw new RuntimeException("You must override newView()!");
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/layr-commons/src/main/java/org/layr/commons/FileUtils.java b/layr-commons/src/main/java/org/layr/commons/FileUtils.java
index d1ce162..b89b18c 100644
--- a/layr-commons/src/main/java/org/layr/commons/FileUtils.java
+++ b/layr-commons/src/main/java/org/layr/commons/FileUtils.java
@@ -1,40 +1,43 @@
package org.layr.commons;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
public class FileUtils {
public static String readFileAsString(String fileName)
throws IOException {
InputStream stream = getResourceAsStream(fileName);
try {
return readFileAsString(stream);
} finally {
if ( stream != null )
stream.close();
}
}
public static InputStream getResourceAsStream(String fileName)
throws FileNotFoundException {
return Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
}
public static String readFileAsString(InputStream stream)
throws UnsupportedEncodingException, IOException {
+ if ( stream == null )
+ return null;
+
Reader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
StringBuilder builder = new StringBuilder();
char[] buffer = new char[8192];
int read;
while ((read = reader.read(buffer, 0, buffer.length)) > 0)
builder.append(buffer, 0, read);
return builder.toString();
}
}
diff --git a/layr-commons/src/test/java/org/layr/commons/commons/FileUtilsTest.java b/layr-commons/src/test/java/org/layr/commons/commons/FileUtilsTest.java
new file mode 100644
index 0000000..75f1663
--- /dev/null
+++ b/layr-commons/src/test/java/org/layr/commons/commons/FileUtilsTest.java
@@ -0,0 +1,24 @@
+package org.layr.commons.commons;
+
+import java.io.IOException;
+
+import org.junit.Test;
+import org.layr.commons.FileUtils;
+
+import static org.junit.Assert.*;
+
+public class FileUtilsTest {
+
+ @Test
+ public void grantThatReadTheFile() throws IOException{
+ String fileAsString = FileUtils.readFileAsString("file.txt");
+ assertEquals("<h1>It really works!</h1>", fileAsString);
+ }
+
+ @Test
+ public void grantThatCantFindTheFile() throws IOException{
+ String fileAsString = FileUtils.readFileAsString("another.file.txt");
+ assertNull(fileAsString);
+ }
+
+}
| false | false | null | null |
diff --git a/src/com/evervolv/widgets/AutoRotateWidgetProvider.java b/src/com/evervolv/widgets/AutoRotateWidgetProvider.java
index 34279e7..a671232 100644
--- a/src/com/evervolv/widgets/AutoRotateWidgetProvider.java
+++ b/src/com/evervolv/widgets/AutoRotateWidgetProvider.java
@@ -1,203 +1,203 @@
/*
* Copyright (C) 2012 The Evervolv Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.evervolv.widgets;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.provider.Settings;
import android.util.Log;
import android.view.IWindowManager;
import android.widget.RemoteViews;
import com.evervolv.widgets.R;
public class AutoRotateWidgetProvider extends AppWidgetProvider{
// TAG
public static final String TAG = "Evervolv_AutoRotateWidget";
private boolean DBG = false;
// Intent Actions
public static String AUTOROTATE_CHANGED = "com.evervolv.widgets.ORIENTATION_CLICKED";
private Context mContext;
private WidgetSettingsObserver mObserver = null;
@Override
public void onEnabled(Context context){
mContext = context;
mObserver = new WidgetSettingsObserver(new Handler());
mObserver.observe();
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(new ComponentName("com.evervolv.widgets",
".AutoRotateWidgetProvider"),
PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager
.DONT_KILL_APP);
}
@Override
public void onDisabled(Context context) {
if (DBG) Log.d(TAG,"Received request to remove last widget");
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(new ComponentName("com.evervolv.widgets",
".AutoRotateWidgetProvider"),
PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager
.DONT_KILL_APP);
if (mObserver != null) {
mObserver.unobserve();
}
}
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
super.onDeleted(context,appWidgetIds);
if (DBG) Log.d(TAG,"Received request to remove a widget");
if (mObserver != null) {
mObserver.unobserve();
}
}
@Override
public void onUpdate(Context context,
AppWidgetManager appWidgetManager,
int[] appWidgetIds){
if (DBG) Log.d(TAG, "onUpdate");
super.onUpdate(context, appWidgetManager, appWidgetIds);
updateWidget(context, appWidgetManager, appWidgetIds);
}
/**
* this method will receive all Intents that it registers for in
* the android manifest file.
*/
@Override
public void onReceive(Context context, Intent intent){
if (DBG) Log.d(TAG, "onReceive - " + intent.toString());
super.onReceive(context, intent);
if (AUTOROTATE_CHANGED.equals(intent.getAction())){
toggleOrientationState(context);
}
}
/**
* this method is called when the widget is added to the home
* screen, and so it contains the initial setup of the widget.
*/
public void updateWidget(Context context,
AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
for (int i=0;i<appWidgetIds.length;++i){
int appWidgetId = appWidgetIds[i];
//on or off
boolean orientationState = getAutoRotationState(context);
updateWidgetView(context, orientationState ? 1 : 0);
}
}
/**
* Method to update the widgets GUI
*/
private void updateWidgetView(Context context, int state) {
Intent intent = new Intent(context, AutoRotateWidgetProvider.class);
intent.setAction(AUTOROTATE_CHANGED);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
0, intent, 0);
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.power_widget);
views.setOnClickPendingIntent(R.id.widget_mask,pendingIntent);
views.setImageViewResource(R.id.widget_icon, R.drawable
.widget_auto_rotate_icon);
if (state == StateTracker.STATE_DISABLED){
views.setImageViewResource(R.id.widget_indic, 0);
} else if (state == StateTracker.STATE_ENABLED) {
views.setImageViewResource(R.id.widget_indic,R
.drawable.widget_indic_on);
}
ComponentName cn = new ComponentName(context,
AutoRotateWidgetProvider.class);
AppWidgetManager.getInstance(context).updateAppWidget(cn, views);
}
protected static void toggleOrientationState(Context context) {
setAutoRotation(!getAutoRotationState(context));
}
private static boolean getAutoRotationState(Context context) {
ContentResolver cr = context.getContentResolver();
return 0 != Settings.System.getInt(cr, Settings.System
.ACCELEROMETER_ROTATION, 0);
}
private static void setAutoRotation(final boolean autorotate) {
AsyncTask.execute(new Runnable() {
public void run() {
try {
IWindowManager wm = IWindowManager.Stub.asInterface(
ServiceManager.getService(Context
.WINDOW_SERVICE));
if (autorotate) {
wm.thawRotation();
} else {
wm.freezeRotation(-1);
}
} catch (RemoteException exc) {
Log.w(TAG, "Unable to save auto-rotate setting");
}
}
});
}
private class WidgetSettingsObserver extends ContentObserver {
public WidgetSettingsObserver(Handler handler) {
super(handler);
}
public void observe() {
ContentResolver resolver = mContext.getContentResolver();
resolver.registerContentObserver(Settings.System.getUriFor(Settings
.System.ACCELEROMETER_ROTATION), false, this);
}
public void unobserve() {
ContentResolver resolver = mContext.getContentResolver();
resolver.unregisterContentObserver(this);
}
@Override
- public void onChangeUri(Uri uri, boolean selfChange) {
+ public void onChange(boolean selfChange, Uri uri) {
updateWidgetView(mContext, getAutoRotationState(mContext) ? 1 : 0);
}
}
}
\ No newline at end of file
| true | false | null | null |
diff --git a/src/orego/mcts/TimePlayer.java b/src/orego/mcts/TimePlayer.java
index 9a646eb5..f3a7d6a8 100644
--- a/src/orego/mcts/TimePlayer.java
+++ b/src/orego/mcts/TimePlayer.java
@@ -1,197 +1,197 @@
package orego.mcts;
import static java.lang.Math.max;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;
import orego.play.UnknownPropertyException;
import static orego.core.Coordinates.*;
public class TimePlayer extends Lgrf2Player {
/**
* The value of timeFormula when we are uniformly distributing our remaining
* time.
*/
public static final int TIME_FORMULA_UNIFORM = 0;
/**
* The value of timeFormula when we are using Aja's basic formula
* (allocating more time to earlier moves).
*/
public static final int TIME_FORMULA_BASIC = 1;
/**
* The value of timeFormula when we are using Aja's enhanced formula
* (allocating more time to middle-game moves).
*/
public static final int TIME_FORMULA_ENHANCED = 2;
/**
* The formula we use for time management: to allocate our time for each
* move.
*/
- private int timeFormula = 0;
+ private int timeFormula = TIME_FORMULA_UNIFORM;
/** The constant C to use in the time management formula. */
- private double timeC = 80.0;
+ private double timeC = 0.20;
/**
* The constant MaxPly to use in the time management formula, where
* applicable.
*/
private double timeMaxPly = 80.0;
/**
* This is true if we should think for longer when the highest winrate <
* behindThreshold.
*/
- private boolean thinkLongerWhenBehind;
+ private boolean thinkLongerWhenBehind = false;
/**
* This is what we should multiply the time by if we are going to think
* longer for a particular move. A reasonable value is 1.0 (think for twice
* as long).
*/
- private double longerMultiple;
+ private double longerMultiple = 1.0;
/**
* We are considered "behind" if the maximum winrate of any node is less
* than this value. A reasonable value is 0.4.
*/
- private double behindThreshold;
+ private double behindThreshold = 0.4;
/**
* This is true if we should think for longer when the move with the most
* wins and the move with the highest win rate are not the same.
*/
- private boolean unstableEvaluation;
+ private boolean unstableEvaluation = false;
/**
* This is what we should multiply the time by if we are going to think
* longer due to the unstable-evaluation heuristic. A reasonable value is
* 0.5 (think for 50% longer).
*/
- private double unstableMultiple;
+ private double unstableMultiple = 0.5;
@Override
public int bestMove() {
int m = super.bestMove();
if (unstableEvaluation) {
- // Find the move with the highest win rate
+ // Find the move with the most runs
int moveWithMostRuns = 0;
int mostRuns = 0;
- for (int i = 0; i < 400; i++) {
+ for (int i = 0; i < orego.core.Coordinates.getFirstPointBeyondBoard(); i++) {
int thisMovesRuns = getRoot().getRuns(i);
if (thisMovesRuns > mostRuns) {
moveWithMostRuns = i;
mostRuns = thisMovesRuns;
}
}
// If it's not the move with the most wins, think a bit longer
if (moveWithMostRuns != getRoot().getMoveWithMostWins()) {
setMillisecondsPerMove((int) (getMillisecondsPerMove() * unstableMultiple));
return super.bestMove();
}
}
if (thinkLongerWhenBehind
&& ((getRoot().getWinRate(m) < behindThreshold) || (m == RESIGN))) {
setMillisecondsPerMove((int) (getMillisecondsPerMove() * longerMultiple));
return super.bestMove();
}
return m;
}
@Override
public void setProperty(String property, String value)
throws UnknownPropertyException {
if (property.equals("timeformula")) {
if (value.equals("uniform")) {
timeFormula = TIME_FORMULA_UNIFORM;
} else if (value.equals("basic")) {
timeFormula = TIME_FORMULA_BASIC;
} else if (value.equals("enhanced")) {
timeFormula = TIME_FORMULA_ENHANCED;
} else {
timeFormula = TIME_FORMULA_UNIFORM;
}
} else if (property.equals("c")) {
timeC = Double.parseDouble(value);
} else if (property.equals("maxply")) {
timeMaxPly = Integer.parseInt(value);
} else if (property.equals("thinklonger")) {
thinkLongerWhenBehind = true;
} else if (property.equals("behindthreshold")) {
behindThreshold = Double.parseDouble(value);
} else if (property.equals("longermultiple")) {
longerMultiple = Double.parseDouble(value);
} else if (property.equals("unstableeval")) {
unstableEvaluation = true;
} else if (property.equals("unstablemult")) {
unstableMultiple = Double.parseDouble(value);
} else {
super.setProperty(property, value);
}
}
@Override
public void setRemainingTime(int seconds) {
/*
* Here we decide how much time to spend on each move, given the amount
* of time we have left for the game.
*/
// don't crash if we're sent < 0 seconds
if (seconds < 0) {
seconds = 0;
}
int msPerMove;
switch (timeFormula) {
case TIME_FORMULA_UNIFORM:
int movesLeft = max(10,
(int) (getBoard().getVacantPoints().size() * timeC));
msPerMove = max(1, (seconds * 1000) / movesLeft);
break;
case TIME_FORMULA_BASIC:
msPerMove = (int) (seconds * 1000 / timeC);
break;
case TIME_FORMULA_ENHANCED:
msPerMove = (int) (seconds * 1000.0 / (timeC + max(timeMaxPly
- getTurn(), 0)));
break;
default:
msPerMove = 0;
}
// never allocate < 1 ms to a move
if (msPerMove < 1) {
msPerMove = 1;
}
setMillisecondsPerMove(msPerMove);
/*
* To ensure we are setting reasonable values, we output a debug
* statement, but not to stderr, since this will be redirected to stdout
* during experiments and be interpreted as (malformed) GTP responses.
*/
File file = new File("timeinfo.txt");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file, true);
} catch (Exception e) {
}
PrintStream ps = new PrintStream(fos);
ps.println("Move#: " + getTurn() + " Secs-Left: " + seconds
+ " Secs-Allocated: " + (msPerMove / 1000.0) + " Fmla: "
+ timeFormula + " C: " + timeC + " MaxPly: " + timeMaxPly
+ " ThinkLonger: " + thinkLongerWhenBehind
+ " BehindThreshold: " + behindThreshold + " LongerMultiple: "
+ longerMultiple + " UnstableEvaluation: " + unstableEvaluation
+ " UnstableMultiple: " + unstableMultiple);
}
}
| false | false | null | null |
diff --git a/org.dsource.ddt.dtool/src/dtool/ast/declarations/DeclarationAliasThis.java b/org.dsource.ddt.dtool/src/dtool/ast/declarations/DeclarationAliasThis.java
index c27c3b3b..842e4934 100644
--- a/org.dsource.ddt.dtool/src/dtool/ast/declarations/DeclarationAliasThis.java
+++ b/org.dsource.ddt.dtool/src/dtool/ast/declarations/DeclarationAliasThis.java
@@ -1,28 +1,29 @@
package dtool.ast.declarations;
import melnorme.utilbox.tree.TreeVisitor;
import descent.internal.compiler.parser.AliasThis;
import dtool.ast.ASTNeoNode;
import dtool.ast.IASTNeoVisitor;
import dtool.ast.references.RefIdentifier;
+import dtool.ast.statements.IStatement;
-public class DeclarationAliasThis extends ASTNeoNode {
+public class DeclarationAliasThis extends ASTNeoNode implements IStatement {
public final RefIdentifier targetDef;
public DeclarationAliasThis(AliasThis elem) {
convertNode(elem);
this.targetDef = new RefIdentifier(new String(elem.ident.ident));
}
@Override
public void accept0(IASTNeoVisitor visitor) {
boolean children = visitor.visit(this);
if (children) {
TreeVisitor.acceptChildren(visitor, targetDef);
}
visitor.endVisit(this);
}
}
diff --git a/org.dsource.ddt.dtool/src/dtool/descentadapter/DescentASTConverter.java b/org.dsource.ddt.dtool/src/dtool/descentadapter/DescentASTConverter.java
index 7a696525..897cb365 100644
--- a/org.dsource.ddt.dtool/src/dtool/descentadapter/DescentASTConverter.java
+++ b/org.dsource.ddt.dtool/src/dtool/descentadapter/DescentASTConverter.java
@@ -1,103 +1,103 @@
package dtool.descentadapter;
import static melnorme.utilbox.core.Assert.AssertNamespace.assertTrue;
import java.util.Collection;
import melnorme.utilbox.misc.ArrayUtil;
import descent.internal.compiler.parser.ast.ASTNode;
import descent.internal.compiler.parser.ast.IASTNode;
import dtool.ast.ASTNeoNode;
import dtool.ast.definitions.ArrayView;
import dtool.ast.definitions.Module;
public class DescentASTConverter extends StatementConverterVisitor {
public DescentASTConverter(ASTConversionContext convContext) {
this.convContext = convContext;
}
public static class ASTConversionContext {
public ASTConversionContext(descent.internal.compiler.parser.Module module) {
this.module = module;
}
public final descent.internal.compiler.parser.Module module;
public boolean hasSyntaxErrors() {
return module.hasSyntaxErrors();
}
}
public static Module convertModule(ASTNode cumodule) {
ASTConversionContext convCtx = new ASTConversionContext((descent.internal.compiler.parser.Module) cumodule);
Module module = DefinitionConverter.createModule(convCtx.module, convCtx);
module.accept(new PostConvertionAdapter());
return module;
}
public static ASTNeoNode convertElem(ASTNode elem, ASTConversionContext convContext) {
if(elem == null) return null;
DescentASTConverter conv = new DescentASTConverter(convContext);
elem.accept(conv);
return conv.ret;
}
public static ASTNeoNode[] convertMany(Collection<? extends IASTNode> children, ASTConversionContext convContext) {
if(children == null) return null;
ASTNeoNode[] rets = new ASTNeoNode[children.size()];
convertMany(children.toArray(), rets, convContext);
return rets;
}
- public static <T extends IASTNode> T[] convertMany(Collection<? extends IASTNode> children, Class<T> klass,
+ public static <T extends IASTNode> T[] convertMany(Collection<? extends IASTNode> children, Class<T> elemClass,
ASTConversionContext convContext) {
if(children == null) return null;
- T[] rets = ArrayUtil.create(children.size(), klass);
+ T[] rets = ArrayUtil.create(children.size(), elemClass);
convertMany(children.toArray(), rets, convContext);
return rets;
}
public static <T extends IASTNode> ArrayView<T> convertManyToView(Collection<? extends IASTNode> children,
- Class<T> klass, ASTConversionContext convContext) {
+ Class<T> elemClass, ASTConversionContext convContext) {
if(children == null) return null;
- return ArrayView.create(convertMany(children, klass, convContext));
+ return ArrayView.create(convertMany(children, elemClass, convContext));
}
public static ArrayView<ASTNeoNode> convertManyNoNulls(Collection<? extends IASTNode> children,
ASTConversionContext convContext) {
if(children == null) return null;
ArrayView<ASTNeoNode> res = convertManyToView(children, ASTNeoNode.class, convContext);
if(true) {
assertTrue(ArrayUtil.contains(res.getInternalArray(), null) == false);
}
return res;
}
- public static <T extends IASTNode> ArrayView<T> convertManyToView(Object[] children, Class<T> klass,
+ public static <T extends IASTNode> ArrayView<T> convertManyToView(Object[] children, Class<T> elemClass,
ASTConversionContext convContext) {
if(children == null) return null;
- return ArrayView.create(convertMany(children, klass, convContext));
+ return ArrayView.create(convertMany(children, elemClass, convContext));
}
- public static <T extends IASTNode> T[] convertMany(Object[] children, Class<T> klass,
+ public static <T extends IASTNode> T[] convertMany(Object[] children, Class<T> elemClass,
ASTConversionContext convContext) {
if(children == null) return null;
- T[] rets = ArrayUtil.create(children.length, klass);
+ T[] rets = ArrayUtil.create(children.length, elemClass);
convertMany(children, rets, convContext);
return rets;
}
@SuppressWarnings("unchecked")
protected static <T extends IASTNode> T[] convertMany(Object[] children, T[] rets,
ASTConversionContext convContext) {
for(int i = 0; i < children.length; ++i) {
ASTNode elem = (ASTNode) children[i];
rets[i] = (T) convertElem(elem, convContext);
}
return rets;
}
}
| false | false | null | null |
diff --git a/src/wikipathways-swt/org/pathvisio/wikipathways/swt/MainWindowWikipathways.java b/src/wikipathways-swt/org/pathvisio/wikipathways/swt/MainWindowWikipathways.java
index 541a402f..5b6811c7 100644
--- a/src/wikipathways-swt/org/pathvisio/wikipathways/swt/MainWindowWikipathways.java
+++ b/src/wikipathways-swt/org/pathvisio/wikipathways/swt/MainWindowWikipathways.java
@@ -1,46 +1,54 @@
package org.pathvisio.wikipathways.swt;
+import java.net.MalformedURLException;
+import java.net.URL;
+
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Display;
import org.pathvisio.Engine;
import org.pathvisio.Globals;
+import org.pathvisio.debug.Logger;
import org.pathvisio.gui.swt.MainWindow;
import org.pathvisio.gui.swt.SwtEngine;
import org.pathvisio.model.Pathway;
import org.pathvisio.wikipathways.WikiPathways;
public class MainWindowWikipathways extends MainWindow {
WikiPathways wiki;
public MainWindowWikipathways(WikiPathways w) {
super();
wiki = w;
}
void setReadOnly(final boolean readOnly) {
threadSave(new Runnable() {
public void run() {
((Action)switchEditModeAction).setEnabled(!readOnly);
}
});
}
protected boolean canHandleShellCloseEvent() {
Pathway p = Engine.getCurrent().getActivePathway();
if(p != null && p.hasChanged()) {
Display.getCurrent().syncExec(new Runnable() {
public void run() {
boolean doit = MessageDialog.openQuestion(SwtEngine.getCurrent().getWindow().getShell(), "Save pathway?",
"Do you want to save the changes to " + wiki.getPwName() + " on " + Globals.SERVER_NAME + "?");
if(doit) {
boolean saved = wiki.saveUI();
- wiki.getUserInterfaceHandler().showDocument(WebstartMain.getDocumentBase(), "_this");
+ try {
+ wiki.getUserInterfaceHandler().showDocument(new URL("javascript:window.location.reload();"), "_top");
+ } catch (MalformedURLException ex) {
+ Logger.log.error("Unable to refresh pathway page", ex);
+ }
}
}
});
}
return true;
}
}
diff --git a/src/wikipathways/org/pathvisio/gui/wikipathways/Actions.java b/src/wikipathways/org/pathvisio/gui/wikipathways/Actions.java
index c1b698d5..97c82102 100644
--- a/src/wikipathways/org/pathvisio/gui/wikipathways/Actions.java
+++ b/src/wikipathways/org/pathvisio/gui/wikipathways/Actions.java
@@ -1,87 +1,94 @@
// PathVisio,
// a tool for data visualization and analysis using Biological Pathways
// Copyright 2006-2007 BiGCaT Bioinformatics
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package org.pathvisio.gui.wikipathways;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
+import java.net.MalformedURLException;
+import java.net.URL;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import org.pathvisio.Engine;
import org.pathvisio.Globals;
import org.pathvisio.debug.Logger;
import org.pathvisio.wikipathways.UserInterfaceHandler;
import org.pathvisio.wikipathways.WikiPathways;
public class Actions {
public static abstract class WikiAction extends AbstractAction {
UserInterfaceHandler uiHandler;
WikiPathways wiki;
public WikiAction(UserInterfaceHandler uih, WikiPathways w, String name, ImageIcon icon) {
super(name, icon);
uiHandler = uih;
wiki = w;
}
}
public static class ExitAction extends WikiAction {
boolean doSave;
public ExitAction(UserInterfaceHandler h, WikiPathways w, boolean save) {
super(h, w, "Finish", new ImageIcon(save ? Engine.getCurrent().getResourceURL("icons/apply.gif") : Engine.getCurrent().getResourceURL("icons/cancel.gif")));
doSave = save;
String descr = doSave ? "Save pathway and close editor" : "Discard pathway and close editor";
putValue(Action.SHORT_DESCRIPTION, descr);
}
public void actionPerformed(ActionEvent e) {
boolean saved = true;
try {
if(doSave) {
saved = wiki.saveUI();
}
} catch(Exception ex) {
Logger.log.error("Unable to save pathway", ex);
JOptionPane.showMessageDialog(null, "Unable to save pathway:\n" + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
if(saved) {
uiHandler.showExitMessage("Please wait while you'll be redirected to the pathway page");
+ try {
+ uiHandler.showDocument(new URL("javascript:window.location.reload();"), "_top");
+ } catch (MalformedURLException ex) {
+ Logger.log.error("Unable to refresh pathway page", ex);
+ }
}
}
}
public static class SaveToServerAction extends WikiAction {
public SaveToServerAction(UserInterfaceHandler h, WikiPathways w) {
super(h, w, "Save to ", new ImageIcon(Engine.getCurrent().getResourceURL("icons/save.gif")));
putValue(Action.SHORT_DESCRIPTION, "Save the pathway to " + Globals.SERVER_NAME);
putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK));
}
public void actionPerformed(ActionEvent e) {
try {
wiki.saveUI();
} catch(Exception ex) {
Logger.log.error("Unable to save pathway", ex);
JOptionPane.showMessageDialog(null, "Unable to save pathway:\n" + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
}
| false | false | null | null |
diff --git a/org.eclipse.mylyn.tasks.core/src/org/eclipse/mylyn/tasks/search/BugzillaReferencesProvider.java b/org.eclipse.mylyn.tasks.core/src/org/eclipse/mylyn/tasks/search/BugzillaReferencesProvider.java
index 12b76f43f..1ff8b2e3e 100644
--- a/org.eclipse.mylyn.tasks.core/src/org/eclipse/mylyn/tasks/search/BugzillaReferencesProvider.java
+++ b/org.eclipse.mylyn.tasks.core/src/org/eclipse/mylyn/tasks/search/BugzillaReferencesProvider.java
@@ -1,143 +1,150 @@
/*******************************************************************************
* Copyright (c) 2004 - 2005 University Of British Columbia and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* University Of British Columbia - initial API and implementation
*******************************************************************************/
/*
* Created on Feb 2, 2005
*/
package org.eclipse.mylar.tasks.search;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.mylar.bugzilla.BugzillaStructureBridge;
import org.eclipse.mylar.bugzilla.MylarBugzillaPlugin;
import org.eclipse.mylar.bugzilla.ui.tasks.BugzillaReportNode;
+import org.eclipse.mylar.core.IDegreeOfSeparation;
import org.eclipse.mylar.core.IMylarContextNode;
import org.eclipse.mylar.core.search.IActiveSearchListener;
import org.eclipse.mylar.core.search.IMylarSearchOperation;
import org.eclipse.mylar.core.search.RelationshipProvider;
/**
* @author Shawn Minto
*/
public class BugzillaReferencesProvider extends RelationshipProvider {
public static final String ID = "org.eclipse.mylar.bugzilla.search.references";
public static final String NAME = "Bugilla report references";
public BugzillaReferencesProvider() {
super(BugzillaStructureBridge.EXTENSION, ID);
}
protected boolean acceptElement(IJavaElement javaElement) {
return javaElement != null
&& (javaElement instanceof IMember || javaElement instanceof IType);
}
/**
* HACK: checking kind as string - don't want the dependancy to mylar.java
*/
@Override
protected void findRelated(final IMylarContextNode node, int degreeOfSeparation) {
if (!node.getStructureKind().equals("java")) return;
IJavaElement javaElement = JavaCore.create(node.getElementHandle());
if (!acceptElement(javaElement)) {
return;
}
runJob(node, degreeOfSeparation);
//XXX what if degreeOfSeparation is 5?
}
@Override
public IMylarSearchOperation getSearchOperation(IMylarContextNode node, int limitTo, int degreeOfSepatation) {
IJavaElement javaElement = JavaCore.create(node.getElementHandle());
return new BugzillaMylarSearch(degreeOfSepatation, javaElement);
}
private void runJob(final IMylarContextNode node, final int degreeOfSeparation) {
BugzillaMylarSearch search = (BugzillaMylarSearch)getSearchOperation(node, 0, degreeOfSeparation);
search.addListener(new IActiveSearchListener(){
private boolean gathered = false;
public void searchCompleted(List<?> nodes) {
Iterator<?> itr = nodes.iterator();
BugzillaStructureBridge bridge = MylarBugzillaPlugin.getDefault().getStructureBridge();
while(itr.hasNext()) {
Object o = itr.next();
if(o instanceof BugzillaReportNode){
BugzillaReportNode bugzillaNode = (BugzillaReportNode)o;
String handle = bugzillaNode.getElementHandle();
if(bridge.getCached(handle) == null)
cache(handle, bugzillaNode);
incrementInterest(degreeOfSeparation, BugzillaStructureBridge.EXTENSION, handle);
}
}
gathered = true;
}
public boolean resultsGathered() {
return gathered;
}
});
search.run(new NullProgressMonitor());
}
@Override
protected String getSourceId() {
return ID;
}
@Override
public String getName() {
return NAME;
}
/*
*
* STUFF FOR TEMPORARILY CACHING A PROXY REPORT
*
* TODO remove the proxys and update the BugzillaStructureBridge cache so that on restart,
* we dont have to get all of the bugs
*
*/
private static final Map<String, BugzillaReportNode> reports = new HashMap<String, BugzillaReportNode>();
public BugzillaReportNode getCached(String handle){
return reports.get(handle);
}
protected void cache(String handle, BugzillaReportNode bugzillaNode) {
reports.put(handle, bugzillaNode);
}
public void clearCachedReports(){
reports.clear();
}
public Collection<? extends String> getCachedHandles() {
return reports.keySet();
}
+ @Override
+ public List<IDegreeOfSeparation> getDegreesOfSeparation() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
}
| false | false | null | null |
diff --git a/HW1/src/edu/nyu/cs/cs2580/Ranker.java b/HW1/src/edu/nyu/cs/cs2580/Ranker.java
index a045f83..8bb6335 100644
--- a/HW1/src/edu/nyu/cs/cs2580/Ranker.java
+++ b/HW1/src/edu/nyu/cs/cs2580/Ranker.java
@@ -1,253 +1,259 @@
/*************************************************************************
> File Name: Ranker.java
> Author: Xiao Cui
> Mail: [email protected]
> Modified Time: Fri Feb 22 16:44:00 2013
> Add ranking function: vector space model, language model(query likehood)
> phrase, numviews, linear model.
************************************************************************/
package edu.nyu.cs.cs2580;
import java.util.Vector;
import java.util.Scanner;
import java.lang.Math;
import java.util.HashMap;
import java.util.Collections;
class Ranker {
private Index _index;
private HashMap < String, Integer > doc_frequency = new HashMap< String, Integer >();
//private HashMap < String, Integer > query_frequency = new HashMap< String, Integer>();
private String mark = "hw1.1-";
public Ranker(String index_source){
_index = new Index(index_source);
}
public Vector < ScoredDocument > runquery(String query, String ranker_type){
Vector < ScoredDocument > retrieval_results = new Vector < ScoredDocument > ();
for (int i = 0; i < _index.numDocs(); ++i){
retrieval_results.add(runquery(query, i, ranker_type));
}
Collections.sort(retrieval_results, new ScoreCompare());
/*for(ScoredDocument s: retrieval_results){
Writer.getInstance().writeToFile(ranker_type, s.asString()+"\n", mark);
}*/
//write to file
//writer.writeTofile(results, ranker_type);
return retrieval_results;
}
public ScoredDocument runquery(String query, int did, String ranker_type){
// Build query vector
Scanner s = new Scanner(query);
Vector < String > qv = new Vector < String > ();
while (s.hasNext()){
String term = s.next();
qv.add(term);
}
// Get the document vector. For hw1, you don't have to worry about the
// details of how index works.
Document d = _index.getDoc(did);
Vector < String > dv = d.get_title_vector();
Vector < String > db = d.get_body_vector();
/*get current document term and frequency*/
for(int i = 0; i < dv.size(); i++){
if(doc_frequency.containsKey(dv.get(i))){
doc_frequency.put(dv.get(i), doc_frequency.get(dv.get(i))+1);
}else{
doc_frequency.put(dv.get(i), 1);
}
}
for(int i = 0; i < db.size(); i++){
if(doc_frequency.containsKey(db.get(i))){
doc_frequency.put(db.get(i), doc_frequency.get(db.get(i))+1);
}else{
doc_frequency.put(db.get(i), 1);
}
}
double score = 0.0;
if(ranker_type.equals("vsm")){
score = vectorSpaceModel(qv, did);
return new ScoredDocument(did, d.get_title_string(), score);
}else if(ranker_type.equals("ql")){
score = languageModel(qv, did);
return new ScoredDocument(did, d.get_title_string(), score);
}else if(ranker_type.equals("phrase")){
score = phraseRanker(qv, did);
return new ScoredDocument(did, d.get_title_string(), score);
}else if(ranker_type.equals("linear")){
score = linearModel(qv, did);
mark = "hw1.2-";
return new ScoredDocument(did, d.get_title_string(), score);
}else if(ranker_type.equals("numviews")){
score = num_views(did);
return new ScoredDocument(did, d.get_title_string(), score);
}else{
return new ScoredDocument(did, d.get_title_string(), score);
}
}
/* Similarity(Q, D) = cosine(theta)D
* Similarity(Q, D) = Zigma Weight(Q)*Weight(Term)/Zigma Sqrt(Weight(Q)*Weight(Q))* Sqrt(Weight(Term)*Weight(Term))
* term_weight vector --- store all terms' weight of a doc
* quert_weight vector --- store query terms' weight of a doc
*
*/
public double vectorSpaceModel(Vector < String > qv, int did){
Document d = _index.getDoc(did);
double query_w = 0.0;
double weight = 0.0;
int doc_num = _index.numDocs();
double IDF = 0.0;
double all_termw = 0.0;
double all_queryw = 0.0;
double all_dot_product = 0.0;
double cosine = 0.0;
Vector < Double > term_weight = new Vector < Double >();
Vector < Double > query_weight = new Vector < Double >();
Vector < String > db = d.get_body_vector();
for (int i = 0; i < db.size(); ++i){
int doc_f = Document.documentFrequency(db.get(i));
IDF = 1+Math.log((double)(doc_num/doc_f))/Math.log((double) 2);
int term_f = 0;
if(doc_frequency.containsKey(db.get(i))){
term_f = doc_frequency.get(db.get(i));
}
weight = term_f*IDF;
term_weight.add(weight);
for(int j = 0; j < qv.size(); ++j){
if(db.get(i).equals((qv.get(j)))){
query_w += IDF;
query_weight.add(query_w);
}
}
query_weight.add(0.0);
}
for(int i = 0; i < term_weight.size(); i++){
if(term_weight.get(i) != 0.0){
all_termw += Math.pow(term_weight.get(i),2.0);
}
}
all_termw = Math.sqrt(all_termw);
for(int i = 0; i < query_weight.size(); i++){
if(query_weight.get(i) != 0.0){
all_queryw += Math.pow(query_weight.get(i),2.0);
}
}
all_queryw = Math.sqrt(all_queryw);
for(int i = 0; i < term_weight.size(); i++){
all_dot_product += term_weight.get(i)*query_weight.get(i);
}
if((all_queryw*all_termw) != 0){
cosine = all_dot_product/(all_termw*all_queryw);
}else{
cosine = 0.0;
}
return cosine;
}
/*Language model*/
public double languageModel(Vector< String > qv, int did){
Document d = _index.getDoc(did);
Vector < String > db = d.get_body_vector();
Vector < String > dv = d.get_title_vector();
int size = db.size() + dv.size();
double score = 0.0;
double lambda = 0.5;
for(int i = 0; i < qv.size(); i++){
int count = 0;
/*if(doc_frequency.containsKey(qv.get(i))){
count = doc_frequency.get(qv.get(i));
}*/
for(int j = 0; j < db.size(); j++){
if(db.get(j).equals(qv.get(i))){
count++;
}
}
double termlike = (double)Document.termFrequency(qv.get(i)) / (double)Document.termFrequency();
double doclike = (double) count/ (double)size; // doc terms
score += Math.log((1 - lambda)*doclike + lambda*termlike);
}
score = Math.pow(Math.E, score);
return score;
}
/*phrase rank: check qv[i]qv[i+1] match*/
public double phraseRanker(Vector < String > qv, int did){
Document d = _index.getDoc(did);
Vector < String > db = d.get_body_vector();
double score = 0.0;
if(qv.size() == 1){
- if(doc_frequency.containsKey(qv.get(0))){
+ /*if(doc_frequency.containsKey(qv.get(0))){
score = doc_frequency.get(qv.get(0));
}else{
score = 0.0;
+ }*/
+ // for loop check the count of qv.get(0) in db
+ for(int i = 0; i<db.size(); i++){
+ if(db.get(i).equals(qv.get(0))){
+ score = score+1;
+ }
}
}else{
for(int i = 0; i <qv.size()- 1; i++){
for(int j = 0; j<db.size() - 1; j++){
if(db.get(j).equals(qv.get(i)) && db.get(j+1).equals(qv.get(i+1)))
score = score + 1;
}
}
}
return score;
}
/*numviews: just return the number of views as score*/
public double num_views(int did){
double score = 0.0;
Document d = _index.getDoc(did);
score = d.get_numviews();
return score;
}
/*Simple implement as combination of vsm+ql+phrase+views*/
public double linearModel(Vector < String > qv, int did){
// score = 0.55*cos+0.4*ql+0.0499*phrase+0.0001numviews
double score = 0.0;
score += 0.55*vectorSpaceModel(qv, did) + 0.4*languageModel(qv, did) + 0.0499*phraseRanker(qv, did) + 0.0001*num_views(did);
return score;
}
/*implement a writer class
has function write(results, ranker_type) --- write results to csv after rank;
can use the same function for evaluate.
public void writeToCSV(Vector < ScoredDocument > results, String ranker_type){
String finlename = "../results" + "hw1.1-" + ranker_type + ".tsv";
try{
File file = new File(filename);
if(!file.exists()){
}
}
}*/
}
| false | false | null | null |
diff --git a/src/java/com/mockey/storage/InMemoryMockeyStorage.java b/src/java/com/mockey/storage/InMemoryMockeyStorage.java
index 626386a..21e79b3 100755
--- a/src/java/com/mockey/storage/InMemoryMockeyStorage.java
+++ b/src/java/com/mockey/storage/InMemoryMockeyStorage.java
@@ -1,850 +1,854 @@
/*
* This file is part of Mockey, a tool for testing application
* interactions over HTTP, with a focus on testing web services,
* specifically web applications that consume XML, JSON, and HTML.
*
* Copyright (C) 2009-2010 Authors:
*
* chad.lafontaine (chad.lafontaine AT gmail DOT com)
* neil.cronin (neil AT rackle DOT com)
* lorin.kobashigawa (lkb AT kgawa DOT com)
* rob.meyer (rob AT bigdis DOT com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
package com.mockey.storage;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.apache.http.Header;
import org.apache.log4j.Logger;
import com.mockey.OrderedMap;
import com.mockey.model.FulfilledClientRequest;
import com.mockey.model.PersistableItem;
import com.mockey.model.PlanItem;
import com.mockey.model.ProxyServerModel;
import com.mockey.model.Scenario;
import com.mockey.model.ScenarioRef;
import com.mockey.model.Service;
import com.mockey.model.ServicePlan;
import com.mockey.model.ServiceRef;
import com.mockey.model.TwistInfo;
import com.mockey.model.Url;
import com.mockey.model.UrlPatternMatchResult;
import com.mockey.model.UrlUtil;
import com.mockey.storage.xml.MockeyXmlFactory;
import com.mockey.storage.xml.MockeyXmlFileManager;
/**
* In memory implementation to the storage of mock services and scenarios.
*
* @author chad.lafontaine
*/
public class InMemoryMockeyStorage implements IMockeyStorage {
- private OrderedMap<FulfilledClientRequest> historyStore = new OrderedMap<FulfilledClientRequest>();
+ private OrderedMap<FulfilledClientRequest> historyStore;
private OrderedMap<Service> mockServiceStore = new OrderedMap<Service>();
private OrderedMap<ServiceRef> serviceRefStore = new OrderedMap<ServiceRef>();
private OrderedMap<ServicePlan> servicePlanStore = new OrderedMap<ServicePlan>();
private OrderedMap<TwistInfo> twistInfoStore = new OrderedMap<TwistInfo>();
private static Logger logger = Logger.getLogger(InMemoryMockeyStorage.class);
private ProxyServerModel proxyInfoBean = new ProxyServerModel();
private Long univeralTwistInfoId = null;
private Long defaultServicePlanId = null;
private Long universalErrorServiceId = null;
private Long universalErrorScenarioId = null;
private static InMemoryMockeyStorage store = new InMemoryMockeyStorage();
// Yes, by default, we need this as TRUE.
private Boolean transientState = new Boolean(true);
private String globalFilterTag = null;
/**
*
* @return
*/
static InMemoryMockeyStorage getInstance() {
return store;
}
/**
*
* @return
*/
public void setReadOnlyMode(Boolean transientState) {
if (transientState != null) {
this.transientState = transientState;
}
if (!transientState) {
this.writeMemoryToFile();
}
}
/**
*
* @return empty string if service plan id is null, otherwise long value as
* string.
*/
public String getDefaultServicePlanId() {
if (defaultServicePlanId != null) {
return defaultServicePlanId.toString();
} else {
return "";
}
}
/**
*
* @return empty string if service plan id is null, otherwise long value as
* string.
*/
public void setDefaultServicePlanId(String v) {
try {
this.defaultServicePlanId = new Long(v);
this.writeMemoryToFile();
} catch (Exception e) {
// Do nothing. Leave value as is.
}
}
public Long getDefaultServicePlanIdAsLong() {
return this.defaultServicePlanId;
}
/**
* HACK: this class is supposed to be a singleton but making this public for
* XML parsing (Digester)
*
* Error is:
*
* Class org.apache.commons.digester.ObjectCreateRule can not access a
* member of class com.mockey.storage.InMemoryMockeyStorage with modifiers
* "private"
*
* Possible Fix: write/implement objectcreatefactory classes.
*
* Example:
*
* <pre>
* http://jsp.codefetch.com/example/fr/storefront-source/com/oreilly/struts/storefront/service/memory/StorefrontMemoryDatabase.java?qy=parse+xml
* </pre>
*/
public InMemoryMockeyStorage() {
- this.historyStore.setMaxSize(new Integer(25)); // Careful, more than ~45
+ initHistoryStore(); // Careful, more than ~45
// and AJAX /JavaScript
// gets funky.
}
public Service getServiceById(Long id) {
return mockServiceStore.get(id);
}
public Service getServiceByName(String name) {
if (name != null) {
for (Service service : getServices()) {
if (service.getServiceName() != null && service.getServiceName().trim().equalsIgnoreCase(name.trim())) {
return service;
}
}
}
return null;
}
/**
* This will only return a Service
*
* @see #getGlobalStateSystemFilterTag()
*/
public Service getServiceByUrl(String url) {
Service service = null;
String filterTag = this.getGlobalStateSystemFilterTag();
try {
// **************************************************
// Be sure to include Filter match if non-empty
// **************************************************
Iterator<Service> iter = getServices().iterator();
while (iter.hasNext()) {
Service serviceTmp = iter.next();
service = findServiceBasedOnUrlPattern(url, serviceTmp);
if (service != null) {
break;
}
}
} catch (Exception e) {
logger.error("Unable to retrieve service w/ url pattern: " + url, e);
}
if (service != null && filterTag != null && filterTag.trim().length() > 0 && service.hasTag(filterTag)) {
logger.debug("Found service with Service path: " + url + ", with tag filter '" + filterTag + "'.");
return service;
} else if (service != null && filterTag != null && filterTag.trim().length() > 0 && !service.hasTag(filterTag)) {
logger.debug("Found service with Service path: " + url + ", but DOES NOT have a matching tag filter of '"
+ filterTag + "', so Mockey is returning not-found.");
service = null;
} else if (service != null) {
logger.debug("Found service with Service path: " + url + ". No tag filter. ");
return service;
} else {
logger.debug("Didn't find service with Service path: " + url + ". Creating a new one.");
}
service = new Service();
try {
Url newUrl = new Url(Url.getSchemeHostPortPathFromURL(url));
service.setUrl(newUrl.getFullUrl());
service.saveOrUpdateRealServiceUrl(newUrl);
store.saveOrUpdateService(service);
} catch (MalformedURLException e) {
logger.error("Unable to build a Service with URL '" + url + "'", e);
}
service.setTag(this.getGlobalStateSystemFilterTag());
return service;
}
/**
* This will return a Service with a matching URL pattern, a Service's
* filter tags, and is RESTful aware
*
* For example, we need to support the following:
*
* <pre>
* http://www.service.com/customers - returns a list of customers.
* http://www.service.com/customers/{ID} - returns a customer
* http://www.service.com/customers/{ID}/subscription - returns a customer's subscriptions entity
* </pre>
*
*
* @param url
* - Incoming URL being requested.
* @param serviceToEvaluate
* service state to compare to the url
* @return service if url pattern matches
*/
private Service findServiceBasedOnUrlPattern(String url, Service serviceToEvaluate) {
Url fullUrl = new Url(serviceToEvaluate.getUrl());
UrlPatternMatchResult result = UrlUtil.evaluateUrlPattern(url, fullUrl.getFullUrl());
Service foundService = null;
if (!result.isMatchingUrlPattern()) {
// OK, not found based on primary Mock url.
// Let's look at secondary list of real URLs
List<Url> serviceUrlList = serviceToEvaluate.getRealServiceUrls();
Iterator<Url> altUrlIter = serviceUrlList.iterator();
while (altUrlIter.hasNext()) {
Url altUrl = altUrlIter.next();
result = UrlUtil.evaluateUrlPattern(url, altUrl.getFullUrl());
if (result.isMatchingUrlPattern()) {
foundService = serviceToEvaluate;
break;
}
}
} else {
foundService = serviceToEvaluate;
}
return foundService;
}
/**
* Deep clone of a Service.
*
* @param service
*/
public Service duplicateService(Service service) {
Service newService = new Service();
newService.setHangTime(service.getHangTime());
newService.setHttpMethod(service.getHttpMethod());
newService.setServiceName(service.getServiceName());
newService.setServiceResponseTypeByString(service.getServiceResponseTypeAsString());
newService.setDefaultRealUrlIndex(service.getDefaultRealUrlIndex());
newService.setUrl(service.getUrl());
// We don't do this because the Default scenario ID is not guaranteed to
// be the same as the duplicate items are created.
// newService.setDefaultScenarioId(service.getDefaultScenarioId());
newService.setDescription(service.getDescription());
// Meta data
for (Url url : service.getRealServiceUrls()) {
newService.saveOrUpdateRealServiceUrl(url);
}
// Why save, and save again below?
// - The first save gets a Service ID created.
// - Scenario's refer to the Service ID
newService = this.saveOrUpdateService(newService);
// Now add scenarios
for (Scenario scenario : service.getScenarios()) {
Scenario newScenario = new Scenario();
newScenario.setHttpResponseStatusCode(scenario.getHttpResponseStatusCode());
newScenario.setMatchStringArg(scenario.getMatchStringArg());
newScenario.setResponseHeader(scenario.getResponseHeader());
newScenario.setResponseMessage(scenario.getResponseMessage());
newScenario.setScenarioName(scenario.getScenarioName());
newScenario.setTag(scenario.getTag());
newService.saveOrUpdateScenario(newScenario);
}
// Save AGAIN.
newService = this.saveOrUpdateService(newService);
return newService;
}
public Service saveOrUpdateService(Service mockServiceBean) {
// System.out.println("XXXXXXXXXXXXX Saving Service. Name is: " +
// mockServiceBean.getServiceName());
PersistableItem item = mockServiceStore.save(mockServiceBean);
if (mockServiceBean != null && !mockServiceBean.getTransientState()) {
this.writeMemoryToFile();
}
return (Service) item;
}
public void deleteService(Service mockServiceBean) {
if (mockServiceBean != null) {
mockServiceStore.remove(mockServiceBean.getId());
if (mockServiceBean != null && !mockServiceBean.getTransientState()) {
this.writeMemoryToFile();
}
}
}
public List<Long> getServiceIds() {
List<Long> ids = new ArrayList<Long>();
for (Service service : this.getServices()) {
ids.add(service.getId());
}
return ids;
}
public List<Service> getServices() {
return this.mockServiceStore.getOrderedList();
}
// public String toString() {
// return new MockeyStorageWriter().StorageAsString(this);
// }
/**
* @return list of FulfilledClientRequest objects
*/
public List<FulfilledClientRequest> getFulfilledClientRequests() {
return this.historyStore.getOrderedList();
}
public void deleteFulfilledClientRequestsFromIP(Long scenarioId) {
historyStore.remove(scenarioId);
}
public void saveOrUpdateFulfilledClientRequest(FulfilledClientRequest request) {
logger.debug("saving a request.");
historyStore.save(request);
}
public void deleteFulfilledClientRequestsForService(Long serviceId) {
for (FulfilledClientRequest req : historyStore.getOrderedList()) {
if (req.getServiceId().equals(serviceId)) {
this.historyStore.remove(req.getId());
}
}
}
public ProxyServerModel getProxy() {
return this.proxyInfoBean;
}
public void setProxy(ProxyServerModel proxyInfoBean) {
this.proxyInfoBean = proxyInfoBean;
this.writeMemoryToFile();
}
public void deleteServicePlan(ServicePlan servicePlan) {
if (servicePlan != null) {
this.servicePlanStore.remove(servicePlan.getId());
this.writeMemoryToFile();
}
}
public void updateServicePlansWithNewServiceName(String oldServiceName, String newServiceName) {
for (ServicePlan servicePlan : this.getServicePlans()) {
for (PlanItem planItem : servicePlan.getPlanItemList()) {
if (planItem.getServiceName() != null && planItem.getServiceName().equals(oldServiceName)) {
planItem.setServiceName(newServiceName);
// 'Add' will 'update' too.
servicePlan.addPlanItem(planItem);
}
}
}
this.writeMemoryToFile();
}
public void updateServicePlansWithNewScenarioName(Long serviceId, String oldScenarioName, String newScenarioName) {
Service service = this.getServiceById(serviceId);
if (service != null) {
for (ServicePlan servicePlan : this.getServicePlans()) {
for (PlanItem planItem : servicePlan.getPlanItemList()) {
if (planItem.getServiceName() != null && planItem.getServiceName().equals(service.getServiceName())
&& planItem.getScenarioName().equals(oldScenarioName)) {
planItem.setScenarioName(newScenarioName);
// 'Add' will 'update' too.
servicePlan.addPlanItem(planItem);
}
}
}
}
this.writeMemoryToFile();
}
public ServicePlan getServicePlanById(Long servicePlanId) {
return servicePlanStore.get(servicePlanId);
}
public ServicePlan getServicePlanByName(String servicePlanName) {
ServicePlan sp = null;
for (ServicePlan servicePlan : this.getServicePlans()) {
if (servicePlan.getName() != null && servicePlan.getName().equalsIgnoreCase(servicePlanName)) {
sp = servicePlan;
break;
}
}
return sp;
}
public List<ServicePlan> getServicePlans() {
return this.servicePlanStore.getOrderedList();
}
public ServicePlan saveOrUpdateServicePlan(ServicePlan servicePlan) {
PersistableItem item = this.servicePlanStore.save(servicePlan);
if (servicePlan != null && !servicePlan.getTransientState()) {
this.writeMemoryToFile();
}
return (ServicePlan) item;
}
public ScenarioRef getUniversalErrorScenarioRef() {
ScenarioRef scenarioRef = null; // new ScenarioRef();
if (this.universalErrorScenarioId != null && this.universalErrorServiceId != null) {
scenarioRef = new ScenarioRef(this.universalErrorScenarioId, this.universalErrorServiceId);
}
return scenarioRef;
}
public Scenario getUniversalErrorScenario() {
Scenario error = null;
Service service = getServiceById(this.universalErrorServiceId);
if (service != null) {
error = service.getScenario(this.universalErrorScenarioId);
}
return error;
}
public void setUniversalErrorScenarioRef(ScenarioRef scenarioRef) {
if (scenarioRef != null) {
this.universalErrorServiceId = scenarioRef.getServiceId();
this.universalErrorScenarioId = scenarioRef.getId();
this.writeMemoryToFile();
} else {
this.universalErrorServiceId = null;
this.universalErrorScenarioId = null;
this.writeMemoryToFile();
}
}
/**
* Convenience Method for the XML writers...
*/
public void setUniversalErrorScenarioId(String id) {
try {
this.universalErrorScenarioId = new Long(id);
} catch (Exception e) {
// By design, ignore.
}
}
/**
* Convenience Method for the XML writers...
*/
public void setUniversalErrorServiceId(String id) {
try {
this.universalErrorServiceId = new Long(id);
} catch (Exception e) {
// By design, ignore.
}
}
public void deleteEverything() {
- historyStore = new OrderedMap<FulfilledClientRequest>();
+ initHistoryStore();
mockServiceStore = new OrderedMap<Service>();
servicePlanStore = new OrderedMap<ServicePlan>();
twistInfoStore = new OrderedMap<TwistInfo>();
this.proxyInfoBean = new ProxyServerModel();
this.globalFilterTag = "";
this.universalErrorServiceId = null;
this.universalErrorScenarioId = null;
this.writeMemoryToFile();
}
public List<String> uniqueClientIPs() {
List<String> uniqueIPs = new ArrayList<String>();
for (FulfilledClientRequest tx : this.historyStore.getOrderedList()) {
String tmpIP = tx.getRequestorIP();
if (!uniqueIPs.contains(tmpIP)) {
uniqueIPs.add(tmpIP);
}
}
return uniqueIPs;
}
public List<String> uniqueClientIPsForService(Long serviceId) {
logger.debug("getting IPs for serviceId: " + serviceId + ". there are a total of " + this.historyStore.size()
+ " requests currently stored.");
List<String> uniqueIPs = new ArrayList<String>();
for (FulfilledClientRequest tx : this.historyStore.getOrderedList()) {
String ip = tx.getRequestorIP();
if (!uniqueIPs.contains(ip) && tx.getServiceId().equals(serviceId)) {
uniqueIPs.add(ip);
}
}
return uniqueIPs;
}
public FulfilledClientRequest getFulfilledClientRequestsById(Long fulfilledClientRequestId) {
return this.historyStore.get(fulfilledClientRequestId);
}
public List<FulfilledClientRequest> getFulfilledClientRequestsForService(Long serviceId) {
logger.debug("getting requests for serviceId: " + serviceId + ". there are a total of "
+ this.historyStore.size() + " requests currently stored.");
List<FulfilledClientRequest> rv = new ArrayList<FulfilledClientRequest>();
for (FulfilledClientRequest req : this.historyStore.getOrderedList()) {
if (req.getServiceId().equals(serviceId)) {
rv.add(req);
}
}
return rv;
}
public List<FulfilledClientRequest> getFulfilledClientRequestsFromIP(String ip) {
List<FulfilledClientRequest> rv = new ArrayList<FulfilledClientRequest>();
for (FulfilledClientRequest req : this.historyStore.getOrderedList()) {
if (req.getRequestorIP().equals(ip)) {
rv.add(req);
}
}
return rv;
}
public List<FulfilledClientRequest> getFulfilledClientRequestsFromIPForService(String ip, Long serviceId) {
List<FulfilledClientRequest> rv = new ArrayList<FulfilledClientRequest>();
for (FulfilledClientRequest req : this.historyStore.getOrderedList()) {
if (req.getServiceId().equals(serviceId) && req.getRequestorIP().equals(ip)) {
rv.add(req);
}
}
return rv;
}
public void deleteFulfilledClientRequests() {
- historyStore = new OrderedMap<FulfilledClientRequest>();
-
+ initHistoryStore();
}
- public void deleteFulfilledClientRequestsFromIPForService(String ip, Long serviceId) {
+ private void initHistoryStore() {
+ historyStore = new OrderedMap<FulfilledClientRequest>();
+ historyStore.setMaxSize(new Integer(25));
+ }
+
+ public void deleteFulfilledClientRequestsFromIPForService(String ip, Long serviceId) {
for (FulfilledClientRequest req : historyStore.getOrderedList()) {
if (req.getServiceId().equals(serviceId) && req.getRequestorIP().equals(ip)) {
this.historyStore.remove(req.getId());
}
}
}
public void deleteFulfilledClientRequestById(Long fulfilledRequestID) {
for (FulfilledClientRequest req : historyStore.getOrderedList()) {
if (req.getId().equals(fulfilledRequestID)) {
this.historyStore.remove(req.getId());
}
}
}
/**
* Filters list with AND not OR. If string starts with "!", we consider it
* NOT.
*/
public List<FulfilledClientRequest> getFulfilledClientRequest(Collection<String> filterArguments) {
List<FulfilledClientRequest> rv = new ArrayList<FulfilledClientRequest>();
if (filterArguments.size() == 0) {
rv = this.getFulfilledClientRequests();
} else {
for (FulfilledClientRequest req : this.historyStore.getOrderedList()) {
boolean allFilterTokensPresentInReq = true;
for (String filterArg : filterArguments) {
boolean notValue = filterArg.startsWith("!");
boolean tokenFound = hasToken(req, filterArg);
if (notValue && tokenFound) {
allFilterTokensPresentInReq = false;
break;
} else if (!tokenFound && !notValue) {
allFilterTokensPresentInReq = false;
break;
} else if (!tokenFound && notValue) {
allFilterTokensPresentInReq = true;
}
}
if (allFilterTokensPresentInReq) {
rv.add(req);
}
}
}
return rv;
}
/**
* Filters list with AND not OR. If string starts with "!", we consider it
* NOT.
*/
private boolean hasToken(FulfilledClientRequest req, String filterArg) {
boolean notValue = filterArg.startsWith("!");
if (notValue) {
try {
// get the value
filterArg = filterArg.substring(1);
} catch (Exception e) {
// do nothing. exception may occur
// with out of index
}
}
boolean tokenFound = false;
if (req.getServiceId().toString().indexOf(filterArg) > -1) {
tokenFound = true;
} else if (req.getClientRequestBody().indexOf(filterArg) > -1) {
tokenFound = true;
} else if (req.getClientRequestHeaders().indexOf(filterArg) > -1) {
tokenFound = true;
} else if (req.getClientRequestParameters().indexOf(filterArg) > -1) {
tokenFound = true;
} else if (req.getRequestorIP().indexOf(filterArg) > -1) {
tokenFound = true;
} else if (req.getRawRequest().indexOf(filterArg) > -1) {
tokenFound = true;
} else if (req.getResponseMessage().getBody().indexOf(filterArg) > -1) {
tokenFound = true;
} else if (req.getResponseMessage().getHeaderInfo().indexOf(filterArg) > -1) {
tokenFound = true;
} else if (req.getServiceName().indexOf(filterArg) > -1) {
tokenFound = true;
} else {
Header[] headers = req.getResponseMessage().getHeaders();
if (headers != null) {
for (Header header : headers) {
if (header.getName().indexOf(filterArg) > -1) {
tokenFound = true;
break;
} else if (header.getValue().indexOf(filterArg) > -1) {
tokenFound = true;
break;
}
}
}
}
return tokenFound;
}
/**
* Every time something gets saved, we write to memory.
*/
private synchronized void writeMemoryToFile() {
if (!transientState) {
MockeyXmlFactory g = new MockeyXmlFactory();
g.writeStoreToXML(store, MockeyXmlFileManager.MOCK_SERVICE_DEFINITION);
}
}
public List<TwistInfo> getTwistInfoList() {
return this.twistInfoStore.getOrderedList();
}
public TwistInfo getTwistInfoById(Long id) {
return (TwistInfo) this.twistInfoStore.get(id);
}
public TwistInfo getTwistInfoByName(String name) {
TwistInfo item = null;
for (TwistInfo i : getTwistInfoList()) {
if (i.getName() != null && i.getName().equals(name)) {
item = i;
break;
}
}
return item;
}
public TwistInfo saveOrUpdateTwistInfo(TwistInfo twistInfo) {
PersistableItem item = twistInfoStore.save(twistInfo);
this.writeMemoryToFile();
return (TwistInfo) item;
}
public void deleteTwistInfo(TwistInfo twistInfo) {
if (twistInfo != null) {
this.twistInfoStore.remove(twistInfo.getId());
this.writeMemoryToFile();
}
}
public Long getUniversalTwistInfoId() {
return this.univeralTwistInfoId;
}
public void setUniversalTwistInfoId(Long twistInfoId) {
this.univeralTwistInfoId = twistInfoId;
this.writeMemoryToFile();
}
public List<ServiceRef> getServiceRefs() {
return this.serviceRefStore.getOrderedList();
}
public ServiceRef saveOrUpdateServiceRef(ServiceRef serviceRef) {
PersistableItem item = this.serviceRefStore.save(serviceRef);
this.writeMemoryToFile();
return (ServiceRef) item;
}
public Boolean getReadOnlyMode() {
if (this.transientState == null) {
this.transientState = new Boolean(true);
}
return this.transientState;
}
public void deleteTagFromStore(String tag) {
if (tag != null && tag.trim().length() > 0) {
for (Service service : mockServiceStore.getOrderedList()) {
service.removeTagFromList(tag);
for (Scenario scenario : service.getScenarios()) {
scenario.removeTagFromList(tag);
if (tag.trim().toLowerCase().equals(scenario.getLastVisitSimple())) {
scenario.setLastVisit(null);
}
}
if (tag.trim().toLowerCase().equals(service.getLastVisitSimple())) {
service.setLastVisit(null);
}
}
for (ServicePlan servicePlan : servicePlanStore.getOrderedList()) {
servicePlan.removeTagFromList(tag);
if (tag.trim().toLowerCase().equals(servicePlan.getLastVisitSimple())) {
servicePlan.setLastVisit(null);
}
}
this.writeMemoryToFile();
}
}
public String getGlobalStateSystemFilterTag() {
if (this.globalFilterTag == null) {
this.globalFilterTag = "";
} else {
this.globalFilterTag = this.globalFilterTag.toLowerCase().trim();
}
return this.globalFilterTag;
}
public void setGlobalStateSystemFilterTag(String filterTag) {
if (filterTag == null) {
this.globalFilterTag = "";
} else {
this.globalFilterTag = filterTag.toLowerCase().trim();
}
}
@Override
public void setServicePlan(ServicePlan servicePlan) {
if (servicePlan != null) {
for (PlanItem planItem : servicePlan.getPlanItemList()) {
Service service = this.getServiceByName(planItem.getServiceName());
if (service != null) {
service.setHangTime(planItem.getHangTime());
service.setDefaultScenarioByName(planItem.getScenarioName());
service.setServiceResponseType(planItem.getServiceResponseType());
this.saveOrUpdateService(service);
}
}
// Why do we save the Plan here?
// To save the lastVisit time
servicePlan.setLastVisit(new Long(Calendar.getInstance().getTimeInMillis()));
this.saveOrUpdateServicePlan(servicePlan);
}
}
}
| false | false | null | null |
diff --git a/org.eclipse.emf.emfstore.client.ui/src/org/eclipse/emf/emfstore/client/ui/views/emfstorebrowser/views/CertificateSelectionDialog.java b/org.eclipse.emf.emfstore.client.ui/src/org/eclipse/emf/emfstore/client/ui/views/emfstorebrowser/views/CertificateSelectionDialog.java
index 52895399..6c814b46 100644
--- a/org.eclipse.emf.emfstore.client.ui/src/org/eclipse/emf/emfstore/client/ui/views/emfstorebrowser/views/CertificateSelectionDialog.java
+++ b/org.eclipse.emf.emfstore.client.ui/src/org/eclipse/emf/emfstore/client/ui/views/emfstorebrowser/views/CertificateSelectionDialog.java
@@ -1,263 +1,268 @@
/*******************************************************************************
* Copyright (c) 2008-2011 Chair for Applied Software Engineering,
* Technische Universitaet Muenchen.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
******************************************************************************/
package org.eclipse.emf.emfstore.client.ui.views.emfstorebrowser.views;
import java.security.cert.X509Certificate;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.emfstore.client.model.connectionmanager.KeyStoreManager;
import org.eclipse.emf.emfstore.client.model.exceptions.CertificateStoreException;
import org.eclipse.emf.emfstore.client.model.exceptions.InvalidCertificateException;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.layout.GridLayoutFactory;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.dialogs.ElementListSelectionDialog;
/**
* The modified ElementListSelectionDialog. Includes further functionality to
* import certificates from files instead of choosing from the list.
*
* @author pfeifferc
*/
public class CertificateSelectionDialog extends ElementListSelectionDialog {
private TableItem selectedTableItem;
private String alias = "";
/**
* The constructor.
*
* @param parent
* Parent
* @param renderer
* Renderer
*/
public CertificateSelectionDialog(Shell parent, ILabelProvider renderer) {
super(parent, renderer);
setShellStyle(SWT.CLOSE | SWT.TITLE | SWT.MIN | SWT.MAX);
}
/**
* Overridden method to allow adding further elements onto the dialog
* composite.
*
* @see org.eclipse.ui.dialogs.ElementListSelectionDialog#createDialogArea(org.eclipse.swt.widgets.Composite)
* @return Control
* @param parent
* Parent
*/
@Override
protected Control createDialogArea(Composite parent) {
// standard layout used by dialogue area
GridLayout layout = new GridLayout();
layout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
layout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
// two column layout composite
Composite grid = new Composite(parent, SWT.NONE);
GridLayoutFactory.fillDefaults().numColumns(2).equalWidth(false).applyTo(grid);
// left column composite
Composite left = new Composite(grid, SWT.NONE);
GridLayoutFactory.fillDefaults().applyTo(left);
// right column composite
Composite right = new Composite(grid, SWT.NONE);
GridLayoutFactory.createFrom(layout).margins(layout.marginWidth, 35).applyTo(right);
GridDataFactory.fillDefaults().grab(true, true).hint(300, 200).applyTo(right);
applyDialogFont(right);
// right column: certificate details
new Label(right, SWT.NONE).setText("Certificate Alias: ");
final Text certAlias = new Text(right, SWT.NONE);
GridDataFactory.fillDefaults().grab(true, false).applyTo(certAlias);
certAlias.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));
certAlias.setEditable(false);
new Label(right, SWT.NONE).setText("Certificate Details: ");
final Text certDetails = new Text(right, SWT.MULTI | SWT.WRAP | SWT.V_SCROLL);
GridDataFactory.fillDefaults().grab(true, false).hint(300, 230).applyTo(certDetails);
certDetails.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));
certDetails.setEditable(false);
// left column: dialogue area composite (displays certificates and
// filter)
Composite dialogArea = new Composite(left, SWT.NONE);
GridLayoutFactory.fillDefaults().applyTo(dialogArea);
Control control = super.createDialogArea(dialogArea);
GridDataFactory.fillDefaults().grab(true, true).applyTo(control);
// left column: import button, composite used to ensure correct
// alignment
Composite certButtonsComposite = new Composite(grid, SWT.NONE);
GridLayoutFactory.createFrom(layout).numColumns(3).equalWidth(true).margins(layout.marginWidth, 0)
.applyTo(certButtonsComposite);
applyDialogFont(certButtonsComposite);
Button browse = new Button(certButtonsComposite, SWT.NONE);
browse.setText("Import...");
browse.addSelectionListener(new CertificateSelectionListener());
// Delete certificate
Button delete = new Button(certButtonsComposite, SWT.NONE);
delete.setText("Delete");
delete.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
// nothing to do
}
public void widgetSelected(SelectionEvent e) {
if (selectedTableItem != null && !selectedTableItem.equals("")) {
String alias = selectedTableItem.getText();
try {
KeyStoreManager.getInstance().deleteCertificate(alias);
setListElements(KeyStoreManager.getInstance().getCertificates().toArray());
} catch (CertificateStoreException e1) {
setErrorMessage(e1.getMessage());
}
}
}
});
fFilteredList.addSelectionListener(new SelectionListenerImplementation(certDetails, certAlias));
return control;
}
/**
- * @return alias
+ * Returns the alias of the certificate
+ *
+ * @return the certificate alias
*/
- protected String getCertificateAlias() {
+ public String getCertificateAlias() {
return alias;
}
/**
- * @param message
- * error message
+ * Opens up an information {@link MessageDialog} with the given <code>errorMessage</code>.
+ *
+ * @param errorMessage
+ * the error message
*/
- protected void setErrorMessage(String message) {
- MessageDialog.openInformation(Display.getDefault().getActiveShell(), "Attention", message);
+ // TODO: rename method
+ public void setErrorMessage(String errorMessage) {
+ MessageDialog.openInformation(Display.getDefault().getActiveShell(), "Attention", errorMessage);
}
/**
* Certificate Selection Listener.
*
* @author koegel
*
*/
private final class SelectionListenerImplementation implements SelectionListener {
private final Text certDetails;
private final Text certAlias;
private SelectionListenerImplementation(Text certDetails, Text certAlias) {
this.certDetails = certDetails;
this.certAlias = certAlias;
}
public void widgetDefaultSelected(SelectionEvent e) {
// nothing to do
}
public void widgetSelected(SelectionEvent e) {
if (((Table) e.getSource()).getItems().length > 0) {
selectedTableItem = ((Table) e.getSource()).getItems()[((Table) e.getSource()).getSelectionIndex()];
alias = selectedTableItem.getText();
try {
X509Certificate selectedCertificate = (X509Certificate) KeyStoreManager.getInstance()
.getCertificate(alias);
String[] details = selectedCertificate.toString().split("\n");
String tmp = "";
for (int i = 2; i < 14; i++) {
tmp += (i == 7 || i == 8) ? "" : details[i].trim() + "\n";
}
certAlias.setText(alias);
certDetails.setText(tmp);
} catch (CertificateStoreException e1) {
setErrorMessage(e1.getMessage());
}
}
}
}
/**
* Choose certificate from file system and name it.
*
* @author pfeifferc
*/
class CertificateSelectionListener implements SelectionListener {
/**
* Add a certificate specified by the user.
*
* @param e
* selection event
*/
public void widgetSelected(SelectionEvent e) {
FileDialog fileDialog = new FileDialog(Display.getCurrent().getActiveShell());
fileDialog.open();
if (!fileDialog.getFileName().equals("")) {
String location = fileDialog.getFilterPath() + System.getProperty("file.separator")
+ fileDialog.getFileName();
InputDialog inputDialog = new InputDialog(Display.getCurrent().getActiveShell(),
"Select certificate designation",
"Please choose a designation for the previously selected certificate: ", "", null);
inputDialog.setBlockOnOpen(true);
if (inputDialog.open() != Window.OK) {
return;
}
String alias = inputDialog.getValue();
if (alias.equals("")) {
alias = "unnamed:" + EcoreUtil.generateUUID();
}
try {
KeyStoreManager.getInstance().addCertificate(alias, location);
} catch (final InvalidCertificateException e1) {
setErrorMessage("Invalid certificate!");
} catch (CertificateStoreException e1) {
setErrorMessage(e1.getMessage());
}
try {
setListElements(KeyStoreManager.getInstance().getCertificates().toArray());
} catch (CertificateStoreException e1) {
setErrorMessage(e1.getMessage());
}
}
}
/**
* @see org.eclipse.swt.events.SelectionListener#widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent)
* @param e
* selection event
*/
public void widgetDefaultSelected(SelectionEvent e) {
// nothing to do
}
}
}
| false | false | null | null |
diff --git a/lucene/src/test/org/apache/lucene/util/TestCollectionUtil.java b/lucene/src/test/org/apache/lucene/util/TestCollectionUtil.java
index 159bc899a..1c59c887d 100644
--- a/lucene/src/test/org/apache/lucene/util/TestCollectionUtil.java
+++ b/lucene/src/test/org/apache/lucene/util/TestCollectionUtil.java
@@ -1,103 +1,103 @@
package org.apache.lucene.util;
/**
* 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.
*/
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class TestCollectionUtil extends LuceneTestCase {
private List<Integer> createRandomList(int maxSize) {
final Integer[] a = new Integer[random.nextInt(maxSize) + 1];
for (int i = 0; i < a.length; i++) {
a[i] = Integer.valueOf(random.nextInt(a.length));
}
return Arrays.asList(a);
}
public void testQuickSort() {
for (int i = 0, c = 500 * RANDOM_MULTIPLIER; i < c; i++) {
List<Integer> list1 = createRandomList(1000), list2 = new ArrayList<Integer>(list1);
CollectionUtil.quickSort(list1);
Collections.sort(list2);
assertEquals(list2, list1);
list1 = createRandomList(1000);
list2 = new ArrayList<Integer>(list1);
CollectionUtil.quickSort(list1, Collections.reverseOrder());
Collections.sort(list2, Collections.reverseOrder());
assertEquals(list2, list1);
// reverse back, so we can test that completely backwards sorted array (worst case) is working:
CollectionUtil.quickSort(list1);
Collections.sort(list2);
assertEquals(list2, list1);
}
}
public void testMergeSort() {
for (int i = 0, c = 500 * RANDOM_MULTIPLIER; i < c; i++) {
List<Integer> list1 = createRandomList(1000), list2 = new ArrayList<Integer>(list1);
CollectionUtil.mergeSort(list1);
Collections.sort(list2);
assertEquals(list2, list1);
list1 = createRandomList(1000);
list2 = new ArrayList<Integer>(list1);
CollectionUtil.mergeSort(list1, Collections.reverseOrder());
Collections.sort(list2, Collections.reverseOrder());
assertEquals(list2, list1);
// reverse back, so we can test that completely backwards sorted array (worst case) is working:
CollectionUtil.mergeSort(list1);
Collections.sort(list2);
assertEquals(list2, list1);
}
}
public void testInsertionSort() {
for (int i = 0, c = 500 * RANDOM_MULTIPLIER; i < c; i++) {
List<Integer> list1 = createRandomList(30), list2 = new ArrayList<Integer>(list1);
CollectionUtil.insertionSort(list1);
Collections.sort(list2);
assertEquals(list2, list1);
list1 = createRandomList(30);
list2 = new ArrayList<Integer>(list1);
CollectionUtil.insertionSort(list1, Collections.reverseOrder());
Collections.sort(list2, Collections.reverseOrder());
assertEquals(list2, list1);
// reverse back, so we can test that completely backwards sorted array (worst case) is working:
CollectionUtil.insertionSort(list1);
Collections.sort(list2);
assertEquals(list2, list1);
}
}
// should produce no exceptions
public void testEmptyArraySort() {
- List<Integer> list = Collections.emptyList();
+ List<Integer> list = Arrays.asList(new Integer[0]);
CollectionUtil.quickSort(list);
CollectionUtil.mergeSort(list);
CollectionUtil.insertionSort(list);
CollectionUtil.quickSort(list, Collections.reverseOrder());
CollectionUtil.mergeSort(list, Collections.reverseOrder());
CollectionUtil.insertionSort(list, Collections.reverseOrder());
}
}
| true | false | null | null |
diff --git a/spring-me-core/src/test/java/me/springframework/di/spring/ParentBeanTest.java b/spring-me-core/src/test/java/me/springframework/di/spring/ParentBeanTest.java
index d4657fc..061a83a 100644
--- a/spring-me-core/src/test/java/me/springframework/di/spring/ParentBeanTest.java
+++ b/spring-me-core/src/test/java/me/springframework/di/spring/ParentBeanTest.java
@@ -1,117 +1,117 @@
/**
* Copyright (C) 2009 Original Authors
*
* This file is part of Spring ME.
*
* Spring ME is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2, or (at your option) any
* later version.
*
* Spring ME is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Spring ME; see the file COPYING. If not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* Linking this library statically or dynamically with other modules is
* making a combined work based on this library. Thus, the terms and
* conditions of the GNU General Public License cover the whole
* combination.
*
* As a special exception, the copyright holders of this library give you
* permission to link this library with independent modules to produce an
* executable, regardless of the license terms of these independent
* modules, and to copy and distribute the resulting executable under
* terms of your choice, provided that you also meet, for each linked
* independent module, the terms and conditions of the license of that
* module. An independent module is a module which is not derived from or
* based on this library. If you modify this library, you may extend this
* exception to your version of the library, but you are not obligated to
* do so. If you do not wish to do so, delete this exception statement
* from your version.
*/
package me.springframework.di.spring;
import static me.springframework.di.gen.factory.BeanFactoryTypes.MINIMAL_JAVA_SE;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.List;
import me.springframework.di.Configuration;
import me.springframework.di.Instance;
import me.springframework.di.PropertySetter;
import me.springframework.di.gen.factory.BeanFactoryGenerator;
import me.springframework.test.Paths;
import org.junit.Test;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import com.thoughtworks.qdox.JavaDocBuilder;
public class ParentBeanTest {
@Test
public void beanShouldInheritTypeOfParentBeanIfNotSpecified() {
Resource resource = new ClassPathResource("/parent.xml", getClass());
Configuration configuration = readConfiguration(resource);
InMemoryDestination dest = new InMemoryDestination("test");
BeanFactoryGenerator.generate(dest, configuration, MINIMAL_JAVA_SE);
// Abstract bean definitions should not be included in Configuration
assertNull(configuration.get("type-person-base"));
assertNull(configuration.get("type-teacher-base"));
Instance type = configuration.get("type-bob");
assertEquals(Teacher.class.getName(), type.getType());
// Abstract bean definitions should not be included in Configuration
assertNull(configuration.get("prop-name-base"));
assertNull(configuration.get("prop-age-base"));
Instance prop = configuration.get("prop-bob");
assertEquals(Person.class.getName(), prop.getType());
List<PropertySetter> setters = new ArrayList<PropertySetter>(prop.getSetters());
assertEquals(2, setters.size());
}
@Test
- public void validateAnonymousBeansConfigWorksInSpring() {
+ public void validateParentBeansConfigWorksInSpring() {
ClassPathResource res = new ClassPathResource("/parent.xml");
XmlBeanFactory beanFactory = new XmlBeanFactory(res);
Person typePerson = (Person) beanFactory.getBean("type-bob");
assertEquals(Teacher.class, typePerson.getClass());
Person propPerson = (Person) beanFactory.getBean("prop-bob");
assertEquals("Bob", propPerson.getName());
assertEquals(-1, propPerson.getAge());
try {
beanFactory.getBean("type-teacher-base");
fail("Did not expect getBean to succeed on with name of abstract bean");
} catch (Exception ex) {
// Expected
}
}
private static Configuration readConfiguration(Resource resource) {
JavaDocBuilder builder = new JavaDocBuilder();
builder.addSourceTree(Paths.getFile("src/test/java"));
Augmentation[] augmentations = {
new QDoxAugmentation(builder),
new AutowiringAugmentation(builder)
};
SpringConfigurationLoader loader = new SpringConfigurationLoader(augmentations);
Configuration configuration = loader.load(resource);
return configuration;
}
}
| true | false | null | null |
diff --git a/SIMSOnline/src/test/Student.java b/SIMSOnline/src/test/Student.java
index 7c004c7..a0877ee 100644
--- a/SIMSOnline/src/test/Student.java
+++ b/SIMSOnline/src/test/Student.java
@@ -1,112 +1,111 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package test;
/**
*
* @author Joerg Woditschka
* @author Nadir Yuldashev
*/
public class Student {
private int id;
private double knowledge=0;
private double knowledgeIncreasement;
private final double intelligence = initIntelligence();
private double tiredness;
private double motivation;
/**
*
* @param id
*/
public Student(int id){
this.id=id;
initTiredness();
initMotivation();
}
/**
*
* @return a double of value between 0 and 40 This functions initializes the
* value of the tiredness attribute.
*/
private void initTiredness() {
this.tiredness=Math.round(Math.random()*40);
}
/**
*
* @return a double of value between 50 and 90 This functions initializes the
* value of the motivation attribute.
*/
private void initMotivation() {
this.motivation=Math.round(50+Math.random()*40);
}
/**
*
* @return a double of value between 1,30 and 2,00 This functions initializes the
* value of the intelligence attribute. This is only done once for each
* student.
*/
private double initIntelligence() {
double result = Math.round((1.3 + Math.random() % 0.7) * 100);
result = result / 100;
return result;
}
/**
* This functions updates the knowledge and the knowledgeincreasement values
* of the student. It should be run once every second.
*/
void updateKnowledge() {
this.knowledgeIncreasement = (this.motivation - this.tiredness) * this.intelligence * 0.000375;
-
if(this.knowledgeIncreasement<0) // this if belongs above the this.knowledge
this.knowledgeIncreasement = 0;
this.knowledge = this.knowledge + this.knowledgeIncreasement;
}
/**
*
* @return the id attribute of the student is returned
*/
public double getId() {
return this.id;
}
/**
*
* @return the knowledge attribute of the student is returned
*/
public double getKnowledge() {
return this.knowledge;
}
/**
*
* @return the intelligence attribute of the student is returned
*/
public double getIntelligence() {
return this.intelligence;
}
/**
*
* @return the tiredness attribute of the student is returned
*/
public double getTiredness() {
return this.tiredness;
}
/**
*
* @return the motivation attribute of the student is returned
*/
public double getMotivation() {
return this.motivation;
}
}
| true | false | null | null |
diff --git a/finance/swing/src/main/java/com/lavida/swing/handler/RefundDialogHandler.java b/finance/swing/src/main/java/com/lavida/swing/handler/RefundDialogHandler.java
index 83477d5..28759b1 100644
--- a/finance/swing/src/main/java/com/lavida/swing/handler/RefundDialogHandler.java
+++ b/finance/swing/src/main/java/com/lavida/swing/handler/RefundDialogHandler.java
@@ -1,56 +1,60 @@
package com.lavida.swing.handler;
import com.lavida.service.entity.ArticleJdo;
import com.lavida.swing.LocaleHolder;
import com.lavida.swing.dialog.RefundDialog;
import com.lavida.swing.service.ArticleServiceSwingWrapper;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Date;
/**
* Created: 21:50 18.08.13
* The RefundDialogHandler is a handler for the RefundDialog.
* @author Ruslan
*/
@Component
public class RefundDialogHandler {
@Resource
RefundDialog refundDialog;
@Resource
protected LocaleHolder localeHolder;
@Resource
private ArticleServiceSwingWrapper articleServiceSwingWrapper;
/**
* Refunds article from a consumer to the stock. Makes the article not sold.
* @param articleJdo the selected articleJdo to be refunded.
*/
public void refundButtonClicked (ArticleJdo articleJdo){
articleJdo.setSold(null);
articleJdo.setSellType(null);
articleJdo.setRefundDate(new Date());
articleJdo.setComment(articleJdo.getComment());
articleServiceSwingWrapper.update(articleJdo);
try {
articleServiceSwingWrapper.updateToSpreadsheet(articleJdo, new Boolean(false));
} catch (Exception e) { // todo change to Custom exception
e.printStackTrace();
articleJdo.setPostponedOperationDate(new Date());
articleServiceSwingWrapper.update(articleJdo);
refundDialog.getMainForm().getHandler().showPostponedOperationsMessage();
+ refundDialog.getSoldProductsDialog().getArticleTableComponent().getArticleFiltersComponent().updateAnalyzeComponent();
+ refundDialog.getSoldProductsDialog().getMainForm().getArticleTableComponent().getArticleFiltersComponent().updateAnalyzeComponent();
refundDialog.showMessage("mainForm.exception.message.dialog.title", "sellDialog.handler.sold.article.not.saved.to.worksheet");
refundDialog.hide();
refundDialog.getSoldProductsDialog().getDialog().repaint();
refundDialog.getSoldProductsDialog().show();
}
refundDialog.hide();
+ refundDialog.getSoldProductsDialog().getArticleTableComponent().getArticleFiltersComponent().updateAnalyzeComponent();
+ refundDialog.getSoldProductsDialog().getMainForm().getArticleTableComponent().getArticleFiltersComponent().updateAnalyzeComponent();
refundDialog.getSoldProductsDialog().getDialog().repaint();
refundDialog.getSoldProductsDialog().show();
}
}
diff --git a/finance/swing/src/main/java/com/lavida/swing/handler/SellDialogHandler.java b/finance/swing/src/main/java/com/lavida/swing/handler/SellDialogHandler.java
index 2eecd0d..f6475a6 100644
--- a/finance/swing/src/main/java/com/lavida/swing/handler/SellDialogHandler.java
+++ b/finance/swing/src/main/java/com/lavida/swing/handler/SellDialogHandler.java
@@ -1,108 +1,116 @@
package com.lavida.swing.handler;
import com.lavida.service.entity.ArticleJdo;
import com.lavida.swing.LocaleHolder;
import com.lavida.swing.dialog.SellDialog;
import com.lavida.swing.service.ArticleServiceSwingWrapper;
import com.lavida.swing.service.ArticlesTableModel;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.swing.*;
import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.Date;
/**
* Created: 12:04 12.08.13
* The SellFormHandler is the handler for logic methods for selling goods.
*
* @author Ruslan
*/
@Component
public class SellDialogHandler {
@Resource
private SellDialog dialog;
@Resource
private MessageSource messageSource;
@Resource
protected LocaleHolder localeHolder;
@Resource
private ArticleServiceSwingWrapper articleServiceSwingWrapper;
@Resource(name = "notSoldArticleTableModel")
private ArticlesTableModel tableModel;
/**
* Performs selling operation.
*
* @param articleJdo // * @param articlesTableModel
*/
public void sellButtonClicked(ArticleJdo articleJdo) {
articleJdo.setSaleDate(Calendar.getInstance());
articleJdo.setSold(messageSource.getMessage("sellDialog.button.sell.clicked.sold", null, localeHolder.getLocale()));
articleJdo.setComment(dialog.getCommentTextField().getText().trim());
+ dialog.getCommentTextField().setText("");
if (dialog.getOursCheckBox().isSelected()) {
articleJdo.setSalePrice(Double.parseDouble(dialog.getPriceField().getText()));
articleJdo.setSellType(dialog.getOursCheckBox().getActionCommand());
+ dialog.getOursCheckBox().setSelected(false);
} else if (dialog.getPresentCheckBox().isSelected()) {
articleJdo.setSalePrice(Double.parseDouble(dialog.getPriceField().getText()));
articleJdo.setSellType(dialog.getPresentCheckBox().getActionCommand());
+ dialog.getPresentCheckBox().setSelected(false);
}
StringBuilder tagsBuilder = new StringBuilder();
for (JCheckBox checkBox : dialog.getTagCheckBoxes()) {
if (checkBox.isSelected()) {
- tagsBuilder.append(checkBox.getActionCommand() + "; ");
+ tagsBuilder.append(checkBox.getActionCommand() + "; ");
+ checkBox.setSelected(false);
}
}
articleJdo.setTags(new String(tagsBuilder));
- articleJdo.setShop((dialog.getShopTextField().getText().trim() == null)? null :
+ articleJdo.setShop((dialog.getShopTextField().getText().trim() == null) ? null :
dialog.getShopTextField().getText().trim());
-
+ dialog.getShopTextField().setText(messageSource.getMessage("sellDialog.text.field.shop.text", null, localeHolder.getLocale()));
articleServiceSwingWrapper.update(articleJdo);
try {
articleServiceSwingWrapper.updateToSpreadsheet(articleJdo, new Boolean(true));
} catch (Exception e) { // todo change to Custom exception
e.printStackTrace();
articleJdo.setPostponedOperationDate(new Date());
articleServiceSwingWrapper.update(articleJdo);
+ dialog.hide();
dialog.getMainForm().getHandler().showPostponedOperationsMessage();
dialog.showMessage("mainForm.exception.message.dialog.title", "sellDialog.handler.sold.article.not.saved.to.worksheet");
- dialog.hide();
+ dialog.getMainForm().getArticleTableComponent().getArticleFiltersComponent().updateAnalyzeComponent();
+ dialog.getMainForm().getSoldProductsDialog().getArticleTableComponent().getArticleFiltersComponent().updateAnalyzeComponent();
dialog.getMainForm().update();
dialog.getMainForm().show();
}
dialog.hide();
+ dialog.getMainForm().getArticleTableComponent().getArticleFiltersComponent().updateAnalyzeComponent();
+ dialog.getMainForm().getSoldProductsDialog().getArticleTableComponent().getArticleFiltersComponent().updateAnalyzeComponent();
dialog.getMainForm().update();
dialog.getMainForm().show();
}
public void oursCheckBoxSelected() {
dialog.getPriceField().setText(String.valueOf(0));
dialog.getDiscountTextField().setText(String.valueOf(0));
}
public void checkBoxDeSelected() {
ArticleJdo articleJdo = tableModel.getSelectedArticle();
dialog.getPriceField().setText(String.valueOf(articleJdo.getSalePrice()));
}
public void presentCheckBoxSelected() {
dialog.getPriceField().setText(String.valueOf(0));
dialog.getDiscountTextField().setText(String.valueOf(0));
}
public void discountTextEntered() {
- String inputStr = (dialog.getDiscountTextField().getText().trim().equals(""))? "0.0" : dialog.getDiscountTextField().getText().trim();
+ String inputStr = (dialog.getDiscountTextField().getText().trim().equals("")) ? "0.0" : dialog.getDiscountTextField().getText().trim();
String discountStr = inputStr.replace(",", ".").replaceAll("[^0-9.]", "");
double discount = Double.parseDouble(discountStr);
double price = Double.parseDouble(dialog.getPriceField().getText());
double totalCost = price - discount;
dialog.getTotalCostTextField().setText(new DecimalFormat("##.##").format(totalCost));
}
}
| false | false | null | null |
diff --git a/src/App.java b/src/App.java
index cd3e4b9..57eb7a2 100644
--- a/src/App.java
+++ b/src/App.java
@@ -1,83 +1,84 @@
import conf.BootStrap;
import driver.Mongo;
import org.vertx.java.core.json.JsonArray;
import org.vertx.java.core.json.JsonObject;
import org.vertx.java.deploy.Verticle;
/**
* @author victor benarbia
*/
public class App extends Verticle
{
@Override
public void start() throws Exception
{
WebServerConfig config = new WebServerConfig();
config.addInbound(Dashboard.findAll);
config.addInbound(Editor.save);
config.addOutbound(Dashboard.refresh);
+ config.addOutbound(Dashboard.changes);
// Database
JsonObject mongoConf = new JsonObject();
mongoConf.putString("host", "localhost");
mongoConf.putNumber("port", 27017);
mongoConf.putString("db_name", "unhook");
container.deployModule("vertx.mongo-persistor-v1.1", mongoConf, 1, new BootStrap(vertx.eventBus()));
container.deployModule("vertx.web-server-v1.0", config.getConf());
// Start verticles
container.deployVerticle("src/Editor.java");
container.deployVerticle("src/Dashboard.java");
}
private class WebServerConfig
{
JsonObject conf;
public WebServerConfig()
{
// Start http server
JsonObject webServerConf = new JsonObject();
webServerConf.putNumber("port", 8080);
webServerConf.putString("host", "localhost");
webServerConf.putBoolean("bridge", true);
JsonArray inbound_permitted = new JsonArray();
/* Set security mechanism in place */
JsonObject mongo = new JsonObject();
mongo.putString("address", Mongo.address);
inbound_permitted.add(mongo);
webServerConf.putArray("inbound_permitted", inbound_permitted);
JsonArray outbound_permitted = new JsonArray();
webServerConf.putArray("outbound_permitted", outbound_permitted);
conf = webServerConf;
}
public void addInbound(String address)
{
JsonObject inbound = new JsonObject();
inbound.putString("address", address);
conf.getArray("inbound_permitted").add(inbound);
}
public void addOutbound(String address)
{
JsonObject outbound = new JsonObject();
outbound.putString("address", address);
conf.getArray("outbound_permitted").add(outbound);
}
public JsonObject getConf()
{
System.out.println(this.conf.toString());
return this.conf;
}
}
}
diff --git a/src/Dashboard.java b/src/Dashboard.java
index 11769e5..143ada4 100644
--- a/src/Dashboard.java
+++ b/src/Dashboard.java
@@ -1,58 +1,60 @@
import driver.Mongo;
import json.JsonOk;
import model.Article;
import org.vertx.java.core.Handler;
import org.vertx.java.core.eventbus.EventBus;
import org.vertx.java.core.eventbus.Message;
import org.vertx.java.core.json.JsonObject;
import org.vertx.java.deploy.Verticle;
/**
* @author victor benarbia
*/
public class Dashboard extends Verticle
{
- public static final String refresh = "client.refresh";
- public static String findAll = "server.findall";
- private final int limit = 10;
+ public static final String changes = "client.changes"; // Something has changes
+ public static final String refresh = "client.refresh"; // Refresh view
+ public static String findAll = "server.findall"; // Find articles
+ private final int limit = 9;
private EventBus eb;
@Override
public void start() throws Exception
{
System.out.println("Start dashboard verticle");
eb = vertx.eventBus();
eb.registerHandler(findAll, findAll());
}
private Handler<? extends Message> findAll()
{
return new Handler<Message<JsonObject>>()
{
@Override
public void handle(Message message)
{
int page = ((JsonObject)message.body).getInteger("page");
System.out.println("Find all with page = " + page);
if(page == -1)
{
page = 0;
}
// Find all articles
eb.send(Mongo.address, Mongo.findAll(Article.name, page * limit, limit), new Handler<Message<JsonObject>>()
{
@Override
public void handle(Message<JsonObject> jsonObjectMessage)
{
+ System.out.println("refresh dashboard with " + jsonObjectMessage.body);
eb.send(Dashboard.refresh, jsonObjectMessage.body);
}
});
// Ack
message.reply(new JsonOk());
}
};
}
}
diff --git a/src/Editor.java b/src/Editor.java
index 360905a..5ddb91f 100644
--- a/src/Editor.java
+++ b/src/Editor.java
@@ -1,57 +1,57 @@
import model.Article;
import driver.Mongo;
import json.JsonOk;
import org.vertx.java.core.Handler;
import org.vertx.java.core.eventbus.EventBus;
import org.vertx.java.core.eventbus.Message;
import org.vertx.java.core.json.JsonObject;
import org.vertx.java.deploy.Verticle;
/**
* Manage interaction with the editor
*/
public class Editor extends Verticle
{
private EventBus eb;
public static final String save = "server.save";
@Override
public void start() throws Exception
{
System.out.println("Start editor verticle.");
// EventBus
eb = vertx.eventBus();
eb.registerHandler(save, save());
}
private Handler<? extends Message> save()
{
return new Handler<Message<JsonObject>>()
{
@Override
public void handle(Message<JsonObject> message)
{
System.out.println("Save message received : " + message.body.toString());
// Create message to save an article
JsonObject msg = Mongo.save(Article.name, (JsonObject)message.body);
// Run mongo
eb.send(Mongo.address, msg, new Handler<Message<JsonObject>>()
{
@Override
public void handle(Message<JsonObject> jsonObjectMessage)
{
// Refresh article
- eb.send(Dashboard.findAll, jsonObjectMessage.body);
+ eb.send(Dashboard.changes, new JsonOk());
}
});
// Ack
message.reply(new JsonOk());
}
};
}
}
diff --git a/src/model/Article.java b/src/model/Article.java
index 89ae4a2..e07cfe4 100644
--- a/src/model/Article.java
+++ b/src/model/Article.java
@@ -1,58 +1,64 @@
package model;
import org.vertx.java.core.json.JsonArray;
import org.vertx.java.core.json.JsonObject;
import java.util.Date;
/**
* Create an article from definition
*/
public class Article
{
public final static String name = "article";
public static JsonObject create(String title, String content, String tags)
{
JsonObject doc = new JsonObject();
doc.putString("title", title);
doc.putString("content", content);
doc.putString("startTime", new Date().toString());
doc.putString("lastUpdate", null);
doc.putArray("tags", toTag(tags));
return doc;
}
+ public static JsonObject update(String title, String content, String tags)
+ {
+ JsonObject doc = create(title, content, tags).putString("lastUpdate", new Date().toString());
+ return doc;
+ }
+
public static JsonObject create(JsonObject article)
{
String tags = article.getString("tags");
article.removeField("tags");
article.putArray("tags", toTag(tags));
return article;
}
private static JsonObject findByTags(String[] tags)
{
//TODO Find all articles who matchs with the current tags
JsonArray criteria = new JsonArray();
for(String tag : tags)
{
criteria.add(tag);
}
//TODO Sort by date
//TODO Enable pagination
return new JsonObject();
}
private static JsonArray toTag(String tags)
{
JsonArray json = new JsonArray();
for (String s : tags.split(","))
{
json.add(s.trim());
}
return json; //To change body of created methods use File | Settings | File Templates.
}
}
| false | false | null | null |
diff --git a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/edgetype/SimpleTransfer.java b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/edgetype/SimpleTransfer.java
index f7f102354..b102125e6 100644
--- a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/edgetype/SimpleTransfer.java
+++ b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/edgetype/SimpleTransfer.java
@@ -1,47 +1,51 @@
package org.opentripplanner.routing.edgetype;
import org.opentripplanner.routing.core.RoutingRequest;
import org.opentripplanner.routing.core.State;
import org.opentripplanner.routing.core.StateEditor;
import org.opentripplanner.routing.graph.Edge;
import org.opentripplanner.routing.vertextype.TransitStop;
/**
* Represents a transfer between stops that does not take the street network into account.
*/
public class SimpleTransfer extends Edge {
private static final long serialVersionUID = 1L;
private int distance;
public SimpleTransfer(TransitStop from, TransitStop to, int distance) {
super(from, to);
this.distance = distance;
}
@Override
public State traverse(State s0) {
+ // use transfer edges only to transfer
+ // otherwise they are used as shortcuts or break the itinerary generator
+ if ( ! s0.isEverBoarded())
+ return null;
if (s0.getBackEdge() instanceof SimpleTransfer)
return null;
RoutingRequest rr = s0.getOptions();
double walkspeed = rr.getWalkSpeed();
StateEditor se = s0.edit(this);
int time = (int) (distance / walkspeed);
se.incrementTimeInSeconds(time);
se.incrementWeight(time * rr.walkReluctance);
return se.makeState();
}
@Override
public String getName() {
return "Simple Transfer";
}
@Override
public double weightLowerBound(RoutingRequest rr) {
int time = (int) (distance / rr.getWalkSpeed());
return (time * rr.walkReluctance);
}
}
| true | true | public State traverse(State s0) {
if (s0.getBackEdge() instanceof SimpleTransfer)
return null;
RoutingRequest rr = s0.getOptions();
double walkspeed = rr.getWalkSpeed();
StateEditor se = s0.edit(this);
int time = (int) (distance / walkspeed);
se.incrementTimeInSeconds(time);
se.incrementWeight(time * rr.walkReluctance);
return se.makeState();
}
| public State traverse(State s0) {
// use transfer edges only to transfer
// otherwise they are used as shortcuts or break the itinerary generator
if ( ! s0.isEverBoarded())
return null;
if (s0.getBackEdge() instanceof SimpleTransfer)
return null;
RoutingRequest rr = s0.getOptions();
double walkspeed = rr.getWalkSpeed();
StateEditor se = s0.edit(this);
int time = (int) (distance / walkspeed);
se.incrementTimeInSeconds(time);
se.incrementWeight(time * rr.walkReluctance);
return se.makeState();
}
|
diff --git a/com.itsolut.mantis.core/src/com/itsolut/mantis/core/MantisRepositoryLocations.java b/com.itsolut.mantis.core/src/com/itsolut/mantis/core/MantisRepositoryLocations.java
index 7e91997..556cf53 100644
--- a/com.itsolut.mantis.core/src/com/itsolut/mantis/core/MantisRepositoryLocations.java
+++ b/com.itsolut.mantis.core/src/com/itsolut/mantis/core/MantisRepositoryLocations.java
@@ -1,95 +1,107 @@
/*******************************************************************************
* Copyright (c) 2004, 2010 Robert Munteanu and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Robert Munteanu - initial API and implementation
*******************************************************************************/
package com.itsolut.mantis.core;
import org.eclipse.core.runtime.Assert;
/**
* @author Robert Munteanu
*
*/
public class MantisRepositoryLocations {
private static final String TICKET_ATTACHMENT_URL = "/file_download.php?type=bug&file_id=";
private static final String URL_SHOW_BUG = "/view.php?id=";
private final String baseRepositoryUrl;
public static Integer extractTaskId(String rawUrl) {
Assert.isNotNull(rawUrl);
- int index = rawUrl.lastIndexOf(URL_SHOW_BUG);
+ int start = rawUrl.lastIndexOf(URL_SHOW_BUG);
+ if ( start == - 1)
+ return null;
- return index == -1 ? null : Integer.parseInt(rawUrl.substring(index + URL_SHOW_BUG.length()));
+ start = start + URL_SHOW_BUG.length();
+ int end = rawUrl.indexOf('#');
+
+ String urlString;
+
+ if ( end == - 1)
+ urlString = rawUrl.substring(start);
+ else
+ urlString = rawUrl.substring(start, end);
+
+ return Integer.parseInt(urlString);
}
public static MantisRepositoryLocations create(String rawUrl) {
Assert.isNotNull(rawUrl);
String repositoryUrl;
if (rawUrl.endsWith(MantisAxis1SOAPClient.SOAP_API_LOCATION))
repositoryUrl = rawUrl.substring(0, rawUrl.length() - MantisAxis1SOAPClient.SOAP_API_LOCATION.length() + 1);
else if (rawUrl.indexOf(URL_SHOW_BUG) != -1)
repositoryUrl = rawUrl.substring(0, rawUrl.indexOf(URL_SHOW_BUG) + 1);
else
repositoryUrl = rawUrl;
return new MantisRepositoryLocations(repositoryUrl);
}
private MantisRepositoryLocations(String baseRepositoryUrl) {
this.baseRepositoryUrl = baseRepositoryUrl;
}
public String getBaseRepositoryLocation() {
return baseRepositoryUrl;
}
public String getSoapApiLocation() {
return join(baseRepositoryUrl, MantisAxis1SOAPClient.SOAP_API_LOCATION);
}
private String join(String first, String second) {
if (first.endsWith("/") && second.startsWith("/"))
return first + second.substring(1);
return first + second;
}
public String getTaskLocation(Integer taskId) {
return join(baseRepositoryUrl, URL_SHOW_BUG + taskId);
}
public String getAttachmentDownloadLocation(Integer attachmentId) {
return join(baseRepositoryUrl, TICKET_ATTACHMENT_URL + attachmentId);
}
public String getSignupLocation() {
return join(baseRepositoryUrl, "/signup_page.php");
}
public String getAccountManagementLocation() {
return join(baseRepositoryUrl, "/account_page.php");
}
}
diff --git a/com.itsolut.mantis.tests/src/com/itsolut/mantis/tests/MantisRepositoryLocationsTest.java b/com.itsolut.mantis.tests/src/com/itsolut/mantis/tests/MantisRepositoryLocationsTest.java
index 4618f8c..035f66b 100644
--- a/com.itsolut.mantis.tests/src/com/itsolut/mantis/tests/MantisRepositoryLocationsTest.java
+++ b/com.itsolut.mantis.tests/src/com/itsolut/mantis/tests/MantisRepositoryLocationsTest.java
@@ -1,89 +1,96 @@
/*******************************************************************************
* Copyright (c) 2004, 2010 Robert Munteanu and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Robert Munteanu - initial API and implementation
*******************************************************************************/
package com.itsolut.mantis.tests;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.itsolut.mantis.core.MantisRepositoryLocations;
/**
* @author Robert Munteanu
*/
public class MantisRepositoryLocationsTest {
@Test(expected=RuntimeException.class)
public void testInvalidValue() {
MantisRepositoryLocations.create(null);
}
@Test
public void testParseFromBaseUrl() {
String baseUrl = "http://mylyn-mantis.sourceforge.net/Mantis/";
assertEquals("http://mylyn-mantis.sourceforge.net/Mantis/", MantisRepositoryLocations.create(baseUrl).getBaseRepositoryLocation());
}
@Test
public void testParseFromSoapUrl() {
String baseUrl = "http://mylyn-mantis.sourceforge.net/Mantis/api/soap/mantisconnect.php";
assertEquals("http://mylyn-mantis.sourceforge.net/Mantis/", MantisRepositoryLocations.create(baseUrl).getBaseRepositoryLocation());
}
@Test
public void testParseFromIssueUrl() {
String baseUrl = "http://mylyn-mantis.sourceforge.net/Mantis/view.php?id=163";
assertEquals("http://mylyn-mantis.sourceforge.net/Mantis/", MantisRepositoryLocations.create(baseUrl).getBaseRepositoryLocation());
}
@Test
public void testGetUrlWhenBaseHasTrailingSlash() {
verifyLocationsAreCorrect("http://mylyn-mantis.sourceforge.net/Mantis/");
}
private void verifyLocationsAreCorrect(String baseUrl) {
MantisRepositoryLocations locations = MantisRepositoryLocations.create(baseUrl);
assertEquals("http://mylyn-mantis.sourceforge.net/Mantis/api/soap/mantisconnect.php", locations.getSoapApiLocation());
assertEquals("http://mylyn-mantis.sourceforge.net/Mantis/view.php?id=1", locations.getTaskLocation(1));
assertEquals("http://mylyn-mantis.sourceforge.net/Mantis/file_download.php?type=bug&file_id=2", locations.getAttachmentDownloadLocation(2));
assertEquals("http://mylyn-mantis.sourceforge.net/Mantis/signup_page.php", locations.getSignupLocation());
assertEquals("http://mylyn-mantis.sourceforge.net/Mantis/account_page.php", locations.getAccountManagementLocation());
}
@Test
public void testGetUrlWhenBaseDoesNotHaveTrailingSlash() {
verifyLocationsAreCorrect("http://mylyn-mantis.sourceforge.net/Mantis");
}
@Test(expected = RuntimeException.class )
public void testInvalidTaskUrl () {
MantisRepositoryLocations.extractTaskId(null);
}
@Test
public void testGetTaskIdFromUrl() {
assertEquals(MantisRepositoryLocations.extractTaskId("http://mylyn-mantis.sourceforge.net/Mantis/view.php?id=1"), Integer.valueOf(1));
}
+
+ @Test
+ public void getTaskIdFromUrlWithHash() {
+
+ assertEquals(MantisRepositoryLocations.extractTaskId("http://mylyn-mantis.sourceforge.net/Mantis/view.php?id=56#comments"), Integer.valueOf(56));
+ }
+
}
| false | false | null | null |
diff --git a/trunk/Line_Wars/src/linewars/gamestate/tech/TechGraph.java b/trunk/Line_Wars/src/linewars/gamestate/tech/TechGraph.java
index c80f436..218010a 100644
--- a/trunk/Line_Wars/src/linewars/gamestate/tech/TechGraph.java
+++ b/trunk/Line_Wars/src/linewars/gamestate/tech/TechGraph.java
@@ -1,366 +1,369 @@
package linewars.gamestate.tech;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import linewars.gamestate.Player;
public class TechGraph implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 2266882489087536100L;
private List<TechNode> roots;
private int rootIndex;
private int maxX;
private int maxY;
private String name;
private boolean enabled;
public TechGraph()
{
this("tech");
}
public TechGraph(String name)
{
roots = new ArrayList<TechNode>();
rootIndex = 0;
this.name = name;
enabled = true;
}
public TechNode addNode()
{
TechNode node = new TechNode();
roots.add(node);
return node;
}
public TechNode getRoot()
{
rootIndex = 0;
return getNextRoot();
}
public TechNode getNextRoot()
{
if(rootIndex < roots.size())
return roots.get(rootIndex++);
return null;
}
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public void setEnabled(boolean enabled)
{
this.enabled = enabled;
}
public boolean isEnabled()
{
return enabled;
}
public void unmarkAll()
{
TechNode root = getRoot();
while(root != null)
{
root.unmarkAll();
root = getNextRoot();
}
}
public List<TechNode> getOrderedList()
{
List<TechNode> orderedList = new ArrayList<TechGraph.TechNode>(roots);
if(orderedList.isEmpty())
return orderedList;
unmarkAll();
int i = 0;
while(i < orderedList.size())
{
TechNode current = orderedList.get(i++);
TechNode child = current.getChild();
while(child != null)
{
if(!child.isMarked())
{
child.mark();
orderedList.add(child);
}
child = current.getNextChild();
}
}
unmarkAll();
Collections.sort(orderedList);
return orderedList;
}
public int getMaxX()
{
return maxX;
}
public int getMaxY()
{
return maxY;
}
public void pruneEmptyNodes()
{
TechNode node = getRoot();
while(node != null)
{
if(node.getTechConfig() == null)
{
roots.remove(node);
--rootIndex;
}
node = getNextRoot();
}
unmarkAll();
}
public class TechNode implements Comparable<TechNode>, Serializable
{
/**
*
*/
private static final long serialVersionUID = 3939573324785222598L;
private TechConfiguration techConfig;
private UnlockStrategy strat;
private List<TechNode> parents;
private List<TechNode> children;
private int parentIndex;
private int childIndex;
private boolean marked;
private boolean researched;
private int x;
private int y;
private TechNode()
{
this.x = -1;
this.y = -1;
this.techConfig = null;
this.strat = null;
this.parents = new ArrayList<TechNode>();
this.children = new ArrayList<TechNode>();
this.parentIndex = 0;
this.childIndex = 0;
}
private TechNode(int x, int y)
{
this();
this.x = x;
this.y = y;
if(maxX < x)
maxX = x;
if(maxY < y)
maxY = y;
}
private TechNode(TechConfiguration techConfig, UnlockStrategy strat)
{
this();
this.techConfig = techConfig;
this.strat = strat;
}
private TechNode(TechConfiguration techConfig, UnlockStrategy strat, List<TechNode> parents)
{
this();
this.techConfig = techConfig;
this.strat = strat;
this.parents = parents;
}
@Override
public int compareTo(TechNode o)
{
if(this.y - o.y != 0)
return this.y - o.y;
return this.x - o.x;
}
public void mark()
{
marked = true;
}
public boolean isMarked()
{
return marked;
}
private void unmarkAll()
{
marked = false;
TechNode child = getChild();
while(child != null)
{
child.unmarkAll();
child = getNextChild();
}
}
public boolean isResearched()
{
return researched;
}
public void research(Player owner)
{
researched = techConfig.research(owner);
}
public void setPosition(int x, int y)
{
this.x = x;
this.y = y;
if(maxX < x)
maxX = x;
if(maxY < y)
maxY = y;
}
public void setTech(TechConfiguration techConfig)
{
this.techConfig = techConfig;
}
public void setUnlockStrategy(UnlockStrategy strat)
{
this.strat = strat;
}
public boolean isUnlocked()
{
- return getUnlockStrategy().isUnlocked(this);
+ if(getUnlockStrategy() != null)
+ return getUnlockStrategy().isUnlocked(this);
+ else
+ return true;
}
public void addChild(TechNode node) throws CycleException
{
TechGraph.this.unmarkAll();
if(this == node || node.isAncestor(this))
{
TechGraph.this.unmarkAll();
throw new CycleException("Adding that child to this node will create a cycle.");
}
TechGraph.this.unmarkAll();
children.add(node);
node.parents.add(this);
TechGraph.this.roots.remove(node);
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public TechConfiguration getTechConfig()
{
return techConfig;
}
public UnlockStrategy getUnlockStrategy()
{
return strat;
}
public TechNode getParent()
{
parentIndex = 0;
return getNextParent();
}
public TechNode getChild()
{
childIndex = 0;
return getNextChild();
}
public TechNode getNextParent()
{
if(parentIndex < parents.size())
return parents.get(parentIndex++);
return null;
}
public TechNode getNextChild()
{
if(childIndex < children.size())
return children.get(childIndex++);
return null;
}
/**
* Checks to see if this TechNode is an ancestor of the potential child.
* @param potentialChild The TechNode that is potentially a child of this TechNode
* @return true if this TechNode is an ancestor of the potential child,
* false otherwise.
*/
private boolean isAncestor(TechNode potentialChild)
{
mark();
TechNode child = getChild();
while(child != null)
{
if(potentialChild == child)
return true;
if(child.isAncestor(potentialChild))
return true;
child = getNextChild();
}
return false;
}
}
}
| true | false | null | null |
diff --git a/src/schmoller/tubes/api/helpers/TubeHelper.java b/src/schmoller/tubes/api/helpers/TubeHelper.java
index b8e23d4..7801455 100644
--- a/src/schmoller/tubes/api/helpers/TubeHelper.java
+++ b/src/schmoller/tubes/api/helpers/TubeHelper.java
@@ -1,138 +1,146 @@
package schmoller.tubes.api.helpers;
import java.util.Random;
import schmoller.tubes.api.Position;
import schmoller.tubes.api.TubeItem;
import schmoller.tubes.api.TubesAPI;
import schmoller.tubes.api.interfaces.ITube;
import schmoller.tubes.api.interfaces.ITubeConnectable;
import codechicken.multipart.TileMultipart;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.ISidedInventory;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.IBlockAccess;
import net.minecraftforge.common.ForgeDirection;
public class TubeHelper
{
public static final Random rand = new Random();
public static ITubeConnectable getTubeConnectable(IBlockAccess world, int x, int y, int z)
{
return getTubeConnectable(world.getBlockTileEntity(x, y, z));
}
public static ITubeConnectable getTubeConnectable(TileEntity entity)
{
if(entity instanceof TileMultipart)
{
if(((TileMultipart)entity).partMap(6) instanceof ITubeConnectable)
return ((ITubeConnectable)((TileMultipart)entity).partMap(6));
}
else if(entity instanceof ITubeConnectable)
return ((ITubeConnectable)entity);
return null;
}
+ private static boolean isNullOrEmpty(int[] array)
+ {
+ if(array == null)
+ return true;
+
+ return array.length == 0;
+ }
+
public static boolean isTubeConnectable(ITubeConnectable other, IBlockAccess world, int x, int y, int z, int side)
{
TileEntity ent = world.getBlockTileEntity(x, y, z);
if(ent == null)
return false;
ITubeConnectable con = getTubeConnectable(ent);
if(con != null)
{
if((con.getConnectableMask() & (1 << side)) == 0)
return false;
if(other instanceof ITube)
{
if(!((ITube)other).canConnectTo(con))
return false;
if(con instanceof ITube)
{
if(!((ITube)con).canConnectTo(other))
return false;
}
}
return true;
}
else
{
if(other instanceof ITube)
{
if(!((ITube)other).canConnectToInventories())
return false;
}
if(ent instanceof ISidedInventory)
- return ((ISidedInventory)ent).getAccessibleSlotsFromSide(side).length != 0;
+ return !isNullOrEmpty(((ISidedInventory)ent).getAccessibleSlotsFromSide(side));
else if (ent instanceof IInventory)
return true;
}
return false;
}
public static int getConnectivity(IBlockAccess world, Position position)
{
return getConnectivity(world, position.x, position.y, position.z);
}
public static int getConnectivity(IBlockAccess world, int x, int y, int z)
{
int map = 0;
ITubeConnectable tube = getTubeConnectable(world, x, y, z);
if(tube == null)
return 0;
int mask = tube.getConnectableMask();
for(int side = 0; side < 6; ++side)
{
if((mask & (1 << side)) != 0 && isTubeConnectable(tube, world, x + ForgeDirection.getOrientation(side).offsetX, y + ForgeDirection.getOrientation(side).offsetY, z + ForgeDirection.getOrientation(side).offsetZ, side ^ 1))
map |= 1 << side;
}
return map;
}
/**
* Returns the next direction that the item must travel to reach its destination.
* @return The direction or -1 if there is no path
*/
public static int findNextDirection(IBlockAccess world, int x, int y, int z, TubeItem item)
{
BaseRouter.PathLocation path = null;
if(item.state == TubeItem.NORMAL)
path = TubesAPI.instance.getOutputRouter(world, new Position(x, y, z), item).route();
else if(item.state == TubeItem.IMPORT)
{
path = TubesAPI.instance.getImportRouter(world, new Position(x, y, z), item).route();
if(path == null)
{
path = TubesAPI.instance.getOutputRouter(world, new Position(x, y, z), item).route();
item.state = TubeItem.NORMAL;
}
}
else if(item.state == TubeItem.BLOCKED)
{
path = TubesAPI.instance.getOutputRouter(world, new Position(x,y,z), item).route();
if(path == null)
path = TubesAPI.instance.getOverflowRouter(world, new Position(x,y,z), item).route();
else
item.state = TubeItem.NORMAL;
}
if(path != null)
return path.initialDir;
return -1;
}
}
| false | false | null | null |
diff --git a/src/java/davmail/ldap/LdapConnection.java b/src/java/davmail/ldap/LdapConnection.java
index d26eca4..a3a1d43 100644
--- a/src/java/davmail/ldap/LdapConnection.java
+++ b/src/java/davmail/ldap/LdapConnection.java
@@ -1,1549 +1,1549 @@
/*
* DavMail POP/IMAP/SMTP/CalDav/LDAP Exchange Gateway
* Copyright (C) 2009 Mickael Guessant
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package davmail.ldap;
import com.sun.jndi.ldap.Ber;
import com.sun.jndi.ldap.BerDecoder;
import com.sun.jndi.ldap.BerEncoder;
import davmail.AbstractConnection;
import davmail.BundleMessage;
import davmail.Settings;
import davmail.exception.DavMailException;
import davmail.exchange.ExchangeSession;
import davmail.exchange.ExchangeSessionFactory;
import davmail.ui.tray.DavGatewayTray;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* Handle a caldav connection.
*/
public class LdapConnection extends AbstractConnection {
/**
* Davmail base context
*/
static final String BASE_CONTEXT = "ou=people";
static final String OD_BASE_CONTEXT = "o=od";
static final String OD_USER_CONTEXT = "cn=users, o=od";
static final String COMPUTER_CONTEXT = "cn=computers, o=od";
static final List<String> NAMING_CONTEXTS = new ArrayList<String>();
static {
NAMING_CONTEXTS.add(BASE_CONTEXT);
NAMING_CONTEXTS.add(OD_BASE_CONTEXT);
}
static final List<String> PERSON_OBJECT_CLASSES = new ArrayList<String>();
static {
PERSON_OBJECT_CLASSES.add("top");
PERSON_OBJECT_CLASSES.add("person");
PERSON_OBJECT_CLASSES.add("organizationalPerson");
PERSON_OBJECT_CLASSES.add("inetOrgPerson");
// OpenDirectory class for iCal
PERSON_OBJECT_CLASSES.add("apple-user");
}
/**
* Exchange to LDAP attribute map
*/
static final HashMap<String, String> ATTRIBUTE_MAP = new HashMap<String, String>();
static {
ATTRIBUTE_MAP.put("uid", "AN");
ATTRIBUTE_MAP.put("mail", "EM");
ATTRIBUTE_MAP.put("cn", "DN");
ATTRIBUTE_MAP.put("displayName", "DN");
ATTRIBUTE_MAP.put("telephoneNumber", "PH");
ATTRIBUTE_MAP.put("l", "OFFICE");
ATTRIBUTE_MAP.put("company", "CP");
ATTRIBUTE_MAP.put("title", "TL");
ATTRIBUTE_MAP.put("givenName", "first");
ATTRIBUTE_MAP.put("initials", "initials");
ATTRIBUTE_MAP.put("sn", "last");
ATTRIBUTE_MAP.put("street", "street");
ATTRIBUTE_MAP.put("st", "state");
ATTRIBUTE_MAP.put("postalCode", "zip");
ATTRIBUTE_MAP.put("c", "country");
ATTRIBUTE_MAP.put("departement", "department");
ATTRIBUTE_MAP.put("mobile", "mobile");
}
static final HashMap<String, String> CONTACT_TO_LDAP_ATTRIBUTE_MAP = new HashMap<String, String>();
static {
CONTACT_TO_LDAP_ATTRIBUTE_MAP.put("imapUid", "uid");
CONTACT_TO_LDAP_ATTRIBUTE_MAP.put("co", "countryname");
CONTACT_TO_LDAP_ATTRIBUTE_MAP.put("extensionattribute1", "custom1");
CONTACT_TO_LDAP_ATTRIBUTE_MAP.put("extensionattribute2", "custom2");
CONTACT_TO_LDAP_ATTRIBUTE_MAP.put("extensionattribute3", "custom3");
CONTACT_TO_LDAP_ATTRIBUTE_MAP.put("extensionattribute4", "custom4");
CONTACT_TO_LDAP_ATTRIBUTE_MAP.put("smtpemail1", "mail");
CONTACT_TO_LDAP_ATTRIBUTE_MAP.put("smtpemail2", "xmozillasecondemail");
CONTACT_TO_LDAP_ATTRIBUTE_MAP.put("homeCountry", "mozillahomecountryname");
CONTACT_TO_LDAP_ATTRIBUTE_MAP.put("homeCity", "mozillahomelocalityname");
CONTACT_TO_LDAP_ATTRIBUTE_MAP.put("homePostalCode", "mozillahomepostalcode");
CONTACT_TO_LDAP_ATTRIBUTE_MAP.put("homeState", "mozillahomestate");
CONTACT_TO_LDAP_ATTRIBUTE_MAP.put("homeStreet", "mozillahomestreet");
CONTACT_TO_LDAP_ATTRIBUTE_MAP.put("businesshomepage", "mozillaworkurl");
CONTACT_TO_LDAP_ATTRIBUTE_MAP.put("description", "description");
CONTACT_TO_LDAP_ATTRIBUTE_MAP.put("nickname", "mozillanickname");
}
static final HashMap<String, String> STATIC_ATTRIBUTE_MAP = new HashMap<String, String>();
static final String COMPUTER_GUID = "52486C30-F0AB-48E3-9C37-37E9B28CDD7B";
static final String VIRTUALHOST_GUID = "D6DD8A10-1098-11DE-8C30-0800200C9A66";
static final String SERVICEINFO =
"<?xml version='1.0' encoding='UTF-8'?>" +
"<!DOCTYPE plist PUBLIC '-//Apple//DTD PLIST 1.0//EN' 'http://www.apple.com/DTDs/PropertyList-1.0.dtd'>" +
"<plist version='1.0'>" +
"<dict>" +
"<key>com.apple.macosxserver.host</key>" +
"<array>" +
"<string>localhost</string>" + // NOTE: Will be replaced by real hostname
"</array>" +
"<key>com.apple.macosxserver.virtualhosts</key>" +
"<dict>" +
"<key>" + VIRTUALHOST_GUID + "</key>" +
"<dict>" +
"<key>hostDetails</key>" +
"<dict>" +
"<key>http</key>" +
"<dict>" +
"<key>enabled</key>" +
"<true/>" +
"<key>port</key>" +
"<integer>9999</integer>" + // NOTE: Will be replaced by real port number
"</dict>" +
"<key>https</key>" +
"<dict>" +
"<key>disabled</key>" +
"<false/>" +
"<key>port</key>" +
"<integer>0</integer>" +
"</dict>" +
"</dict>" +
"<key>hostname</key>" +
"<string>localhost</string>" + // NOTE: Will be replaced by real hostname
"<key>serviceInfo</key>" +
"<dict>" +
"<key>calendar</key>" +
"<dict>" +
"<key>enabled</key>" +
"<true/>" +
"<key>templates</key>" +
"<dict>" +
"<key>calendarUserAddresses</key>" +
"<array>" +
"<string>%(principaluri)s</string>" +
"<string>mailto:%(email)s</string>" +
"<string>urn:uuid:%(guid)s</string>" +
"</array>" +
"<key>principalPath</key>" +
"<string>/principals/__uuids__/%(guid)s/</string>" +
"</dict>" +
"</dict>" +
"</dict>" +
"<key>serviceType</key>" +
"<array>" +
"<string>calendar</string>" +
"</array>" +
"</dict>" +
"</dict>" +
"</dict>" +
"</plist>";
static {
STATIC_ATTRIBUTE_MAP.put("apple-serviceslocator", COMPUTER_GUID + ':' + VIRTUALHOST_GUID + ":calendar");
}
/**
* LDAP to Exchange Criteria Map
*/
static final HashMap<String, String> CRITERIA_MAP = new HashMap<String, String>();
static {
// assume mail starts with firstname
CRITERIA_MAP.put("uid", "AN");
CRITERIA_MAP.put("mail", "FN");
CRITERIA_MAP.put("displayname", "DN");
CRITERIA_MAP.put("cn", "DN");
CRITERIA_MAP.put("givenname", "FN");
CRITERIA_MAP.put("sn", "LN");
CRITERIA_MAP.put("title", "TL");
CRITERIA_MAP.put("company", "CP");
CRITERIA_MAP.put("o", "CP");
CRITERIA_MAP.put("l", "OF");
CRITERIA_MAP.put("department", "DP");
CRITERIA_MAP.put("apple-group-realname", "DP");
}
static final HashMap<String, String> LDAP_TO_CONTACT_ATTRIBUTE_MAP = new HashMap<String, String>();
static {
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("uid", "imapUid");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("mail", "smtpemail1");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("displayname", "cn");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("commonname", "cn");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("givenname", "givenName");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("surname", "sn");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("company", "o");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("apple-group-realname", "department");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("mozillahomelocalityname", "homeCity");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("c", "co");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("countryname", "co");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("custom1", "extensionattribute1");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("custom2", "extensionattribute2");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("custom3", "extensionattribute3");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("custom4", "extensionattribute4");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("mozillacustom1", "extensionattribute1");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("mozillacustom2", "extensionattribute2");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("mozillacustom3", "extensionattribute3");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("mozillacustom4", "extensionattribute4");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("telephonenumber", "telephoneNumber");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("orgunit", "department");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("departmentnumber", "department");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("ou", "department");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("mozillaworkstreet2", null);
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("mozillahomestreet", "homeStreet");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("xmozillanickname", "nickname");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("mozillanickname", "nickname");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("cellphone", "mobile");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("homeurl", "personalHomePage");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("mozillahomeurl", "personalHomePage");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("mozillahomepostalcode", "homePostalCode");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("fax", "facsimiletelephonenumber");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("mozillahomecountryname", "homeCountry");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("streetaddress", "street");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("mozillaworkurl", "businesshomepage");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("workurl", "businesshomepage");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("region", "st");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("birthmonth", "bday");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("birthday", "bday");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("birthyear", "bday");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("carphone", "othermobile");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("nsaimid", "im");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("nscpaimscreenname", "im");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("xmozillasecondemail", "email2");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("notes", "description");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("pagerphone", "pager");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("locality", "l");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("homephone", "homePhone");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("mozillasecondemail", "email2");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("zip", "postalcode");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("mozillahomestate", "homeState");
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("modifytimestamp", "lastmodified");
// ignore attribute
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("objectclass", null);
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("mozillausehtmlmail", null);
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("xmozillausehtmlmail", null);
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("mozillahomestreet2", null);
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("labeleduri", null);
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("apple-generateduid", null);
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("apple-serviceslocator", null);
LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("uidnumber", null);
}
/**
* LDAP filter attributes ignore map
*/
static final HashSet<String> IGNORE_MAP = new HashSet<String>();
static {
IGNORE_MAP.add("objectclass");
IGNORE_MAP.add("apple-generateduid");
IGNORE_MAP.add("augmentconfiguration");
IGNORE_MAP.add("ou");
IGNORE_MAP.add("apple-realname");
IGNORE_MAP.add("apple-group-nestedgroup");
IGNORE_MAP.add("apple-group-memberguid");
IGNORE_MAP.add("macaddress");
IGNORE_MAP.add("memberuid");
}
// LDAP version
// static final int LDAP_VERSION2 = 0x02;
static final int LDAP_VERSION3 = 0x03;
// LDAP request operations
static final int LDAP_REQ_BIND = 0x60;
static final int LDAP_REQ_SEARCH = 0x63;
static final int LDAP_REQ_UNBIND = 0x42;
static final int LDAP_REQ_ABANDON = 0x50;
// LDAP response operations
static final int LDAP_REP_BIND = 0x61;
static final int LDAP_REP_SEARCH = 0x64;
static final int LDAP_REP_RESULT = 0x65;
// LDAP return codes
static final int LDAP_OTHER = 80;
static final int LDAP_SUCCESS = 0;
static final int LDAP_SIZE_LIMIT_EXCEEDED = 4;
static final int LDAP_INVALID_CREDENTIALS = 49;
static final int LDAP_FILTER_AND = 0xa0;
static final int LDAP_FILTER_OR = 0xa1;
// LDAP filter operators (only LDAP_FILTER_SUBSTRINGS is supported)
static final int LDAP_FILTER_SUBSTRINGS = 0xa4;
//static final int LDAP_FILTER_GE = 0xa5;
//static final int LDAP_FILTER_LE = 0xa6;
static final int LDAP_FILTER_PRESENT = 0x87;
//static final int LDAP_FILTER_APPROX = 0xa8;
static final int LDAP_FILTER_EQUALITY = 0xa3;
// LDAP filter mode (only startsWith supported by galfind)
static final int LDAP_SUBSTRING_INITIAL = 0x80;
static final int LDAP_SUBSTRING_ANY = 0x81;
static final int LDAP_SUBSTRING_FINAL = 0x82;
// BER data types
static final int LBER_ENUMERATED = 0x0a;
static final int LBER_SET = 0x31;
static final int LBER_SEQUENCE = 0x30;
// LDAP search scope
static final int SCOPE_BASE_OBJECT = 0;
//static final int SCOPE_ONE_LEVEL = 1;
//static final int SCOPE_SUBTREE = 2;
/**
* For some unknow reaseon parseIntWithTag is private !
*/
static final Method PARSE_INT_WITH_TAG_METHOD;
static {
try {
PARSE_INT_WITH_TAG_METHOD = BerDecoder.class.getDeclaredMethod("parseIntWithTag", int.class);
PARSE_INT_WITH_TAG_METHOD.setAccessible(true);
} catch (NoSuchMethodException e) {
DavGatewayTray.error(new BundleMessage("LOG_UNABLE_TO_GET_PARSEINTWITHTAG"));
throw new RuntimeException(e);
}
}
/**
* raw connection inputStream
*/
protected BufferedInputStream is;
/**
* reusable BER encoder
*/
protected final BerEncoder responseBer = new BerEncoder();
/**
* Current LDAP version (used for String encoding)
*/
int ldapVersion = LDAP_VERSION3;
/**
* Search threads map
*/
protected final HashMap<Integer, SearchThread> searchThreadMap = new HashMap<Integer, SearchThread>();
/**
* Initialize the streams and start the thread.
*
* @param clientSocket LDAP client socket
*/
public LdapConnection(Socket clientSocket) {
super(LdapConnection.class.getSimpleName(), clientSocket);
try {
is = new BufferedInputStream(client.getInputStream());
os = new BufferedOutputStream(client.getOutputStream());
} catch (IOException e) {
close();
DavGatewayTray.error(new BundleMessage("LOG_EXCEPTION_GETTING_SOCKET_STREAMS"), e);
}
}
protected boolean isLdapV3() {
return ldapVersion == LDAP_VERSION3;
}
@Override
public void run() {
byte[] inbuf = new byte[2048]; // Buffer for reading incoming bytes
int bytesread; // Number of bytes in inbuf
int bytesleft; // Number of bytes that need to read for completing resp
int br; // Temp; number of bytes read from stream
int offset; // Offset of where to store bytes in inbuf
boolean eos; // End of stream
try {
ExchangeSessionFactory.checkConfig();
while (true) {
offset = 0;
// check that it is the beginning of a sequence
bytesread = is.read(inbuf, offset, 1);
if (bytesread < 0) {
break; // EOF
}
if (inbuf[offset++] != (Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR)) {
continue;
}
// get length of sequence
bytesread = is.read(inbuf, offset, 1);
if (bytesread < 0) {
break; // EOF
}
int seqlen = inbuf[offset++]; // Length of ASN sequence
// if high bit is on, length is encoded in the
// subsequent length bytes and the number of length bytes
// is equal to & 0x80 (i.e. length byte with high bit off).
if ((seqlen & 0x80) == 0x80) {
int seqlenlen = seqlen & 0x7f; // number of length bytes
bytesread = 0;
eos = false;
// Read all length bytes
while (bytesread < seqlenlen) {
br = is.read(inbuf, offset + bytesread,
seqlenlen - bytesread);
if (br < 0) {
eos = true;
break; // EOF
}
bytesread += br;
}
// end-of-stream reached before length bytes are read
if (eos) {
break; // EOF
}
// Add contents of length bytes to determine length
seqlen = 0;
for (int i = 0; i < seqlenlen; i++) {
seqlen = (seqlen << 8) + (inbuf[offset + i] & 0xff);
}
offset += bytesread;
}
// read in seqlen bytes
bytesleft = seqlen;
if ((offset + bytesleft) > inbuf.length) {
byte[] nbuf = new byte[offset + bytesleft];
System.arraycopy(inbuf, 0, nbuf, 0, offset);
inbuf = nbuf;
}
while (bytesleft > 0) {
bytesread = is.read(inbuf, offset, bytesleft);
if (bytesread < 0) {
break; // EOF
}
offset += bytesread;
bytesleft -= bytesread;
}
DavGatewayTray.switchIcon();
//Ber.dumpBER(System.out, "request\n", inbuf, 0, offset);
handleRequest(new BerDecoder(inbuf, 0, offset));
}
} catch (SocketException e) {
DavGatewayTray.debug(new BundleMessage("LOG_CONNECTION_CLOSED"));
} catch (SocketTimeoutException e) {
DavGatewayTray.debug(new BundleMessage("LOG_CLOSE_CONNECTION_ON_TIMEOUT"));
} catch (Exception e) {
DavGatewayTray.log(e);
try {
sendErr(0, LDAP_REP_BIND, e);
} catch (IOException e2) {
DavGatewayTray.warn(new BundleMessage("LOG_EXCEPTION_SENDING_ERROR_TO_CLIENT"), e2);
}
} finally {
close();
}
DavGatewayTray.resetIcon();
}
protected void handleRequest(BerDecoder reqBer) throws IOException {
int currentMessageId = 0;
try {
reqBer.parseSeq(null);
currentMessageId = reqBer.parseInt();
int requestOperation = reqBer.peekByte();
if (requestOperation == LDAP_REQ_BIND) {
reqBer.parseSeq(null);
ldapVersion = reqBer.parseInt();
userName = reqBer.parseString(isLdapV3());
password = reqBer.parseStringWithTag(Ber.ASN_CONTEXT, isLdapV3(), null);
if (userName.length() > 0 && password.length() > 0) {
DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_BIND_USER", currentMessageId, userName));
try {
session = ExchangeSessionFactory.getInstance(userName, password);
DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_BIND_SUCCESS"));
sendClient(currentMessageId, LDAP_REP_BIND, LDAP_SUCCESS, "");
} catch (IOException e) {
DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_BIND_INVALID_CREDENTIALS"));
sendClient(currentMessageId, LDAP_REP_BIND, LDAP_INVALID_CREDENTIALS, "");
}
} else {
DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_BIND_ANONYMOUS", currentMessageId));
// anonymous bind
sendClient(currentMessageId, LDAP_REP_BIND, LDAP_SUCCESS, "");
}
} else if (requestOperation == LDAP_REQ_UNBIND) {
DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_UNBIND", currentMessageId));
if (session != null) {
session = null;
}
} else if (requestOperation == LDAP_REQ_SEARCH) {
reqBer.parseSeq(null);
String dn = reqBer.parseString(isLdapV3());
int scope = reqBer.parseEnumeration();
/*int derefAliases =*/
reqBer.parseEnumeration();
int sizeLimit = reqBer.parseInt();
if (sizeLimit > 100 || sizeLimit == 0) {
sizeLimit = 100;
}
int timelimit = reqBer.parseInt();
/*boolean typesOnly =*/
reqBer.parseBoolean();
LdapFilter ldapFilter = parseFilter(reqBer);
Set<String> returningAttributes = parseReturningAttributes(reqBer);
// launch search in a separate thread
SearchThread searchThread = new SearchThread(getName(), currentMessageId, dn, scope, sizeLimit, timelimit, ldapFilter, returningAttributes);
synchronized (searchThreadMap) {
searchThreadMap.put(currentMessageId, searchThread);
}
searchThread.start();
} else if (requestOperation == LDAP_REQ_ABANDON) {
int abandonMessageId = 0;
try {
abandonMessageId = (Integer) PARSE_INT_WITH_TAG_METHOD.invoke(reqBer, LDAP_REQ_ABANDON);
synchronized (searchThreadMap) {
SearchThread searchThread = searchThreadMap.get(abandonMessageId);
if (searchThread != null) {
searchThread.abandon();
searchThreadMap.remove(currentMessageId);
}
}
} catch (IllegalAccessException e) {
DavGatewayTray.error(e);
} catch (InvocationTargetException e) {
DavGatewayTray.error(e);
}
DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_ABANDON_SEARCH", currentMessageId, abandonMessageId));
} else {
DavGatewayTray.debug(new BundleMessage("LOG_LDAP_UNSUPPORTED_OPERATION", requestOperation));
sendClient(currentMessageId, LDAP_REP_RESULT, LDAP_OTHER, "Unsupported operation");
}
} catch (IOException e) {
try {
sendErr(currentMessageId, LDAP_REP_RESULT, e);
} catch (IOException e2) {
DavGatewayTray.debug(new BundleMessage("LOG_EXCEPTION_SENDING_ERROR_TO_CLIENT"), e2);
}
throw e;
}
}
protected LdapFilter parseFilter(BerDecoder reqBer) throws IOException {
LdapFilter ldapFilter;
if (reqBer.peekByte() == LDAP_FILTER_PRESENT) {
String attributeName = reqBer.parseStringWithTag(LDAP_FILTER_PRESENT, isLdapV3(), null).toLowerCase();
ldapFilter = new SimpleFilter(attributeName);
} else {
int[] seqSize = new int[1];
int ldapFilterType = reqBer.parseSeq(seqSize);
int end = reqBer.getParsePosition() + seqSize[0];
ldapFilter = parseNestedFilter(reqBer, ldapFilterType, end);
}
return ldapFilter;
}
protected LdapFilter parseNestedFilter(BerDecoder reqBer, int ldapFilterType, int end) throws IOException {
LdapFilter nestedFilter;
if ((ldapFilterType == LDAP_FILTER_OR) || (ldapFilterType == LDAP_FILTER_AND)) {
nestedFilter = new CompoundFilter(ldapFilterType);
while (reqBer.getParsePosition() < end && reqBer.bytesLeft() > 0) {
if (reqBer.peekByte() == LDAP_FILTER_PRESENT) {
String attributeName = reqBer.parseStringWithTag(LDAP_FILTER_PRESENT, isLdapV3(), null).toLowerCase();
nestedFilter.add(new SimpleFilter(attributeName));
} else {
int[] seqSize = new int[1];
int ldapFilterOperator = reqBer.parseSeq(seqSize);
int subEnd = reqBer.getParsePosition() + seqSize[0];
nestedFilter.add(parseNestedFilter(reqBer, ldapFilterOperator, subEnd));
}
}
} else {
// simple filter
nestedFilter = parseSimpleFilter(reqBer, ldapFilterType);
}
return nestedFilter;
}
protected LdapFilter parseSimpleFilter(BerDecoder reqBer, int ldapFilterOperator) throws IOException {
String attributeName = reqBer.parseString(isLdapV3()).toLowerCase();
int ldapFilterMode = 0;
StringBuilder value = new StringBuilder();
if (ldapFilterOperator == LDAP_FILTER_SUBSTRINGS) {
// Thunderbird sends values with space as separate strings, rebuild value
int[] seqSize = new int[1];
/*LBER_SEQUENCE*/
reqBer.parseSeq(seqSize);
int end = reqBer.getParsePosition() + seqSize[0];
while (reqBer.getParsePosition() < end && reqBer.bytesLeft() > 0) {
ldapFilterMode = reqBer.peekByte();
if (value.length() > 0) {
value.append(' ');
}
value.append(reqBer.parseStringWithTag(ldapFilterMode, isLdapV3(), null));
}
} else if (ldapFilterOperator == LDAP_FILTER_EQUALITY) {
value.append(reqBer.parseString(isLdapV3()));
} else {
DavGatewayTray.warn(new BundleMessage("LOG_LDAP_UNSUPPORTED_FILTER_VALUE"));
}
String sValue = value.toString();
if ("uid".equalsIgnoreCase(attributeName) && sValue.equals(userName)) {
// replace with actual alias instead of login name search
if (sValue.equals(userName)) {
sValue = session.getAlias();
DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REPLACED_UID_FILTER", userName, sValue));
}
}
return new SimpleFilter(attributeName, sValue, ldapFilterOperator, ldapFilterMode);
}
protected Set<String> parseReturningAttributes(BerDecoder reqBer) throws IOException {
Set<String> returningAttributes = new HashSet<String>();
int[] seqSize = new int[1];
reqBer.parseSeq(seqSize);
int end = reqBer.getParsePosition() + seqSize[0];
while (reqBer.getParsePosition() < end && reqBer.bytesLeft() > 0) {
returningAttributes.add(reqBer.parseString(isLdapV3()).toLowerCase());
}
return returningAttributes;
}
/**
* Send Root DSE
*
* @param currentMessageId current message id
* @throws IOException on error
*/
protected void sendRootDSE(int currentMessageId) throws IOException {
DavGatewayTray.debug(new BundleMessage("LOG_LDAP_SEND_ROOT_DSE"));
Map<String, Object> attributes = new HashMap<String, Object>();
attributes.put("objectClass", "top");
attributes.put("namingContexts", NAMING_CONTEXTS);
sendEntry(currentMessageId, "Root DSE", attributes);
}
protected void addIf(Map<String, Object> attributes, Set<String> returningAttributes, String name, Object value) {
if ((returningAttributes.isEmpty()) || returningAttributes.contains(name)) {
attributes.put(name, value);
}
}
protected String hostName() throws UnknownHostException {
if (client.getInetAddress().isLoopbackAddress()) {
// local address, probably using localhost in iCal URL
return "localhost";
} else {
// remote address, send fully qualified domain name
return InetAddress.getLocalHost().getCanonicalHostName();
}
}
/**
* Send ComputerContext
*
* @param currentMessageId current message id
* @param returningAttributes attributes to return
* @throws IOException on error
*/
protected void sendComputerContext(int currentMessageId, Set<String> returningAttributes) throws IOException {
String customServiceInfo = SERVICEINFO.replaceAll("localhost", hostName());
customServiceInfo = customServiceInfo.replaceAll("9999", Settings.getProperty("davmail.caldavPort"));
List<String> objectClasses = new ArrayList<String>();
objectClasses.add("top");
objectClasses.add("apple-computer");
Map<String, Object> attributes = new HashMap<String, Object>();
addIf(attributes, returningAttributes, "objectClass", objectClasses);
addIf(attributes, returningAttributes, "apple-generateduid", COMPUTER_GUID);
addIf(attributes, returningAttributes, "apple-serviceinfo", customServiceInfo);
addIf(attributes, returningAttributes, "apple-serviceslocator", "::anyService");
addIf(attributes, returningAttributes, "cn", hostName());
String dn = "cn=" + hostName() + ", " + COMPUTER_CONTEXT;
DavGatewayTray.debug(new BundleMessage("LOG_LDAP_SEND_COMPUTER_CONTEXT", dn, attributes));
sendEntry(currentMessageId, dn, attributes);
}
/**
* Send Base Context
*
* @param currentMessageId current message id
* @throws IOException on error
*/
protected void sendBaseContext(int currentMessageId) throws IOException {
List<String> objectClasses = new ArrayList<String>();
objectClasses.add("top");
objectClasses.add("organizationalUnit");
Map<String, Object> attributes = new HashMap<String, Object>();
attributes.put("objectClass", objectClasses);
attributes.put("description", "DavMail Gateway LDAP for " + Settings.getProperty("davmail.url"));
sendEntry(currentMessageId, BASE_CONTEXT, attributes);
}
protected void sendEntry(int currentMessageId, String dn, Map<String, Object> attributes) throws IOException {
// synchronize on responseBer
synchronized (responseBer) {
responseBer.reset();
responseBer.beginSeq(Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR);
responseBer.encodeInt(currentMessageId);
responseBer.beginSeq(LDAP_REP_SEARCH);
responseBer.encodeString(dn, isLdapV3());
responseBer.beginSeq(LBER_SEQUENCE);
for (Map.Entry<String, Object> entry : attributes.entrySet()) {
responseBer.beginSeq(LBER_SEQUENCE);
responseBer.encodeString(entry.getKey(), isLdapV3());
responseBer.beginSeq(LBER_SET);
Object values = entry.getValue();
if (values instanceof String) {
responseBer.encodeString((String) values, isLdapV3());
} else if (values instanceof List) {
for (Object value : (List) values) {
responseBer.encodeString((String) value, isLdapV3());
}
} else {
throw new DavMailException("EXCEPTION_UNSUPPORTED_VALUE", values);
}
responseBer.endSeq();
responseBer.endSeq();
}
responseBer.endSeq();
responseBer.endSeq();
responseBer.endSeq();
sendResponse();
}
}
protected void sendErr(int currentMessageId, int responseOperation, Exception e) throws IOException {
String message = e.getMessage();
if (message == null) {
message = e.toString();
}
sendClient(currentMessageId, responseOperation, LDAP_OTHER, message);
}
protected void sendClient(int currentMessageId, int responseOperation, int status, String message) throws IOException {
responseBer.reset();
responseBer.beginSeq(Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR);
responseBer.encodeInt(currentMessageId);
responseBer.beginSeq(responseOperation);
responseBer.encodeInt(status, LBER_ENUMERATED);
// dn
responseBer.encodeString("", isLdapV3());
// error message
responseBer.encodeString(message, isLdapV3());
responseBer.endSeq();
responseBer.endSeq();
sendResponse();
}
protected void sendResponse() throws IOException {
//Ber.dumpBER(System.out, ">\n", responseBer.getBuf(), 0, responseBer.getDataLen());
os.write(responseBer.getBuf(), 0, responseBer.getDataLen());
os.flush();
}
static interface LdapFilter {
ExchangeSession.Condition getContactSearchFilter();
Map<String, ExchangeSession.Contact> findInGAL(ExchangeSession session, Set<String> returningAttributes, int sizeLimit) throws IOException;
void add(LdapFilter filter);
boolean isFullSearch();
boolean isMatch(Map<String, String> person);
}
class CompoundFilter implements LdapFilter {
final Set<LdapFilter> criteria = new HashSet<LdapFilter>();
final int type;
CompoundFilter(int filterType) {
type = filterType;
}
@Override
public String toString() {
StringBuilder buffer = new StringBuilder();
if (type == LDAP_FILTER_OR) {
buffer.append("(|");
} else {
buffer.append("(&");
}
for (LdapFilter child : criteria) {
buffer.append(child.toString());
}
buffer.append(')');
return buffer.toString();
}
/**
* Add child filter
*
* @param filter inner filter
*/
public void add(LdapFilter filter) {
criteria.add(filter);
}
/**
* This is only a full search if every child
* is also a full search
*
* @return true if full search filter
*/
public boolean isFullSearch() {
for (LdapFilter child : criteria) {
if (!child.isFullSearch()) {
return false;
}
}
return true;
}
/**
* Build search filter for Contacts folder search.
* Use Exchange SEARCH syntax
*
* @return contact search filter
*/
public ExchangeSession.Condition getContactSearchFilter() {
ExchangeSession.MultiCondition condition;
if (type == LDAP_FILTER_OR) {
condition = session.or();
} else {
condition = session.and();
}
for (LdapFilter child : criteria) {
condition.add(child.getContactSearchFilter());
}
return condition;
}
/**
* Test if person matches the current filter.
*
* @param person person attributes map
* @return true if filter match
*/
public boolean isMatch(Map<String, String> person) {
if (type == LDAP_FILTER_OR) {
for (LdapFilter child : criteria) {
if (!child.isFullSearch()) {
if (child.isMatch(person)) {
// We've found a match
return true;
}
}
}
// No subconditions are met
return false;
} else if (type == LDAP_FILTER_AND) {
for (LdapFilter child : criteria) {
if (!child.isFullSearch()) {
if (!child.isMatch(person)) {
// We've found a miss
return false;
}
}
}
// All subconditions are met
return true;
}
return false;
}
/**
* Find persons in Exchange GAL matching filter.
* Iterate over child filters to build results.
*
* @param session Exchange session
* @return persons map
* @throws IOException on error
*/
public Map<String, ExchangeSession.Contact> findInGAL(ExchangeSession session, Set<String> returningAttributes, int sizeLimit) throws IOException {
Map<String, ExchangeSession.Contact> persons = null;
for (LdapFilter child : criteria) {
int currentSizeLimit = sizeLimit;
if (persons != null) {
currentSizeLimit -= persons.size();
}
Map<String, ExchangeSession.Contact> childFind = child.findInGAL(session, returningAttributes, currentSizeLimit);
if (childFind != null) {
if (persons == null) {
persons = childFind;
} else if (type == LDAP_FILTER_OR) {
// Create the union of the existing results and the child found results
persons.putAll(childFind);
} else if (type == LDAP_FILTER_AND) {
// Append current child filter results that match all child filters to persons.
// The hard part is that, due to the 100-item-returned galFind limit
// we may catch new items that match all child filters in each child search.
// Thus, instead of building the intersection, we check each result against
// all filters.
for (ExchangeSession.Contact result : childFind.values()) {
if (isMatch(result)) {
// This item from the child result set matches all sub-criteria, add it
persons.put(result.get("uid"), result);
}
}
}
}
}
if ((persons == null) && !isFullSearch()) {
// return an empty map (indicating no results were found)
return new HashMap<String, ExchangeSession.Contact>();
}
return persons;
}
}
class SimpleFilter implements LdapFilter {
static final String STAR = "*";
final String attributeName;
final String value;
final int mode;
final int operator;
final boolean canIgnore;
SimpleFilter(String attributeName) {
this.attributeName = attributeName;
this.value = SimpleFilter.STAR;
this.operator = LDAP_FILTER_SUBSTRINGS;
this.mode = 0;
this.canIgnore = checkIgnore();
}
SimpleFilter(String attributeName, String value, int ldapFilterOperator, int ldapFilterMode) {
this.attributeName = attributeName;
this.value = value;
this.operator = ldapFilterOperator;
this.mode = ldapFilterMode;
this.canIgnore = checkIgnore();
}
private boolean checkIgnore() {
if ("objectclass".equals(attributeName) && STAR.equals(value)) {
// ignore cases where any object class can match
return true;
} else if (IGNORE_MAP.contains(attributeName)) {
// Ignore this specific attribute
return true;
} else if (CRITERIA_MAP.get(attributeName) == null && getContactAttributeName(attributeName) == null) {
DavGatewayTray.debug(new BundleMessage("LOG_LDAP_UNSUPPORTED_FILTER_ATTRIBUTE",
attributeName, value));
return true;
}
return false;
}
public boolean isFullSearch() {
// only (objectclass=*) is a full search
return "objectclass".equals(attributeName) && STAR.equals(value);
}
@Override
public String toString() {
StringBuilder buffer = new StringBuilder();
buffer.append('(');
buffer.append(attributeName);
buffer.append('=');
if (SimpleFilter.STAR.equals(value)) {
buffer.append(SimpleFilter.STAR);
} else if (operator == LDAP_FILTER_SUBSTRINGS) {
if (mode == LDAP_SUBSTRING_FINAL || mode == LDAP_SUBSTRING_ANY) {
buffer.append(SimpleFilter.STAR);
}
buffer.append(value);
if (mode == LDAP_SUBSTRING_INITIAL || mode == LDAP_SUBSTRING_ANY) {
buffer.append(SimpleFilter.STAR);
}
} else {
buffer.append(value);
}
buffer.append(')');
return buffer.toString();
}
public ExchangeSession.Condition getContactSearchFilter() {
String contactAttributeName = getContactAttributeName(attributeName);
if (canIgnore || (contactAttributeName == null)) {
return null;
}
ExchangeSession.Condition condition = null;
if (operator == LDAP_FILTER_EQUALITY) {
condition = session.isEqualTo(contactAttributeName, value);
} else if ("*".equals(value)) {
condition = session.not(session.isNull(contactAttributeName));
// do not allow substring search on integer field imapUid
} else if (!"imapUid".equals(contactAttributeName)) {
// endsWith not supported by exchange, convert to contains
if (mode == LDAP_SUBSTRING_FINAL || mode == LDAP_SUBSTRING_ANY) {
condition = session.contains(contactAttributeName, value);
} else {
condition = session.startsWith(contactAttributeName, value);
}
}
return condition;
}
public boolean isMatch(Map<String, String> person) {
if (canIgnore) {
// Ignore this filter
return true;
}
String personAttributeValue = person.get(attributeName);
if (personAttributeValue == null) {
// No value to allow for filter match
return false;
} else if (value == null) {
// This is a presence filter: found
return true;
} else if ((operator == LDAP_FILTER_EQUALITY) && personAttributeValue.equalsIgnoreCase(value)) {
// Found an exact match
return true;
} else if ((operator == LDAP_FILTER_SUBSTRINGS) && (personAttributeValue.toLowerCase().indexOf(value.toLowerCase()) >= 0)) {
// Found a substring match
return true;
}
return false;
}
public Map<String, ExchangeSession.Contact> findInGAL(ExchangeSession session, Set<String> returningAttributes, int sizeLimit) throws IOException {
if (canIgnore) {
return null;
}
String galFindAttributeName = getGalFindAttributeName();
if (galFindAttributeName != null) {
// quick fix for cn=* filter
Map<String, ExchangeSession.Contact> galPersons = session.galFind(session.startsWith(attributeName, "*".equals(value) ? "A" : value), returningAttributes, sizeLimit);
if (operator == LDAP_FILTER_EQUALITY) {
// Make sure only exact matches are returned
Map<String, ExchangeSession.Contact> results = new HashMap<String, ExchangeSession.Contact>();
for (ExchangeSession.Contact person : galPersons.values()) {
if (isMatch(person)) {
// Found an exact match
results.put(person.get("uid"), person);
}
}
return results;
} else {
return galPersons;
}
}
return null;
}
public void add(LdapFilter filter) {
// Should never be called
DavGatewayTray.error(new BundleMessage("LOG_LDAP_UNSUPPORTED_FILTER", "nested simple filters"));
}
public String getGalFindAttributeName() {
return CRITERIA_MAP.get(attributeName);
}
}
/**
* Convert contact attribute name to LDAP attribute name.
*
* @param ldapAttributeName ldap attribute name
* @return contact attribute name
*/
protected static String getContactAttributeName(String ldapAttributeName) {
String contactAttributeName = null;
// first look in contact attributes
if (ExchangeSession.CONTACT_ATTRIBUTES.contains(ldapAttributeName)) {
contactAttributeName = ldapAttributeName;
} else if (LDAP_TO_CONTACT_ATTRIBUTE_MAP.containsKey(ldapAttributeName)) {
String mappedAttribute = LDAP_TO_CONTACT_ATTRIBUTE_MAP.get(ldapAttributeName);
if (mappedAttribute != null) {
contactAttributeName = mappedAttribute;
}
} else {
DavGatewayTray.debug(new BundleMessage("UNKNOWN_ATTRIBUTE", ldapAttributeName));
}
return contactAttributeName;
}
/**
* Convert LDAP attribute name to contact attribute name.
*
* @param contactAttributeName ldap attribute name
* @return contact attribute name
*/
protected static String getLdapAttributeName(String contactAttributeName) {
String mappedAttributeName = CONTACT_TO_LDAP_ATTRIBUTE_MAP.get(contactAttributeName);
if (mappedAttributeName != null) {
return mappedAttributeName;
} else {
return contactAttributeName;
}
}
protected class SearchThread extends Thread {
private final int currentMessageId;
private final String dn;
private final int scope;
private final int sizeLimit;
private final int timelimit;
private final LdapFilter ldapFilter;
private final Set<String> returningAttributes;
private boolean abandon;
protected SearchThread(String threadName, int currentMessageId, String dn, int scope, int sizeLimit, int timelimit, LdapFilter ldapFilter, Set<String> returningAttributes) {
super(threadName + "-Search-" + currentMessageId);
this.currentMessageId = currentMessageId;
this.dn = dn;
this.scope = scope;
this.sizeLimit = sizeLimit;
this.timelimit = timelimit;
this.ldapFilter = ldapFilter;
this.returningAttributes = returningAttributes;
}
/**
* Abandon search.
*/
protected void abandon() {
abandon = true;
}
@Override
public void run() {
try {
int size = 0;
DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH", currentMessageId, dn, scope, sizeLimit, timelimit, ldapFilter.toString(), returningAttributes));
if (scope == SCOPE_BASE_OBJECT) {
if ("".equals(dn)) {
size = 1;
sendRootDSE(currentMessageId);
} else if (BASE_CONTEXT.equals(dn)) {
size = 1;
// root
sendBaseContext(currentMessageId);
} else if (dn.startsWith("uid=") && dn.indexOf(',') > 0) {
if (session != null) {
// single user request
String uid = dn.substring("uid=".length(), dn.indexOf(','));
Map<String, ExchangeSession.Contact> persons = null;
// first search in contact
try {
// check if this is a contact uid
Integer.parseInt(uid);
persons = contactFind(session.isEqualTo("imapUid", uid), returningAttributes, sizeLimit);
} catch (NumberFormatException e) {
// ignore, this is not a contact uid
}
// then in GAL
if (persons == null || persons.isEmpty()) {
persons = session.galFind(session.isEqualTo("uid", uid), returningAttributes, sizeLimit);
ExchangeSession.Contact person = persons.get(uid.toLowerCase());
// filter out non exact results
if (persons.size() > 1 || person == null) {
persons = new HashMap<String, ExchangeSession.Contact>();
if (person != null) {
persons.put(uid.toLowerCase(), person);
}
}
}
size = persons.size();
sendPersons(currentMessageId, dn.substring(dn.indexOf(',')), persons, returningAttributes);
} else {
DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_ANONYMOUS_ACCESS_FORBIDDEN", currentMessageId, dn));
}
} else {
DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_INVALID_DN", currentMessageId, dn));
}
} else if (COMPUTER_CONTEXT.equals(dn)) {
size = 1;
// computer context for iCal
sendComputerContext(currentMessageId, returningAttributes);
} else if ((BASE_CONTEXT.equalsIgnoreCase(dn) || OD_USER_CONTEXT.equalsIgnoreCase(dn))) {
if (session != null) {
Map<String, ExchangeSession.Contact> persons = new HashMap<String, ExchangeSession.Contact>();
if (ldapFilter.isFullSearch()) {
// append personal contacts first
for (ExchangeSession.Contact person : contactFind(null, returningAttributes, sizeLimit).values()) {
persons.put(person.get("imapUid"), person);
if (persons.size() == sizeLimit) {
break;
}
}
// full search
- for (char c = 'A'; c < 'Z'; c++) {
+ for (char c = 'A'; c <= 'Z'; c++) {
if (!abandon && persons.size() < sizeLimit) {
for (ExchangeSession.Contact person : session.galFind(session.startsWith("uid", String.valueOf(c)), returningAttributes, sizeLimit).values()) {
persons.put(person.get("uid"), person);
if (persons.size() == sizeLimit) {
break;
}
}
}
if (persons.size() == sizeLimit) {
break;
}
}
} else {
// append personal contacts first
ExchangeSession.Condition filter = ldapFilter.getContactSearchFilter();
// if ldapfilter is not a full search and filter is null,
// ignored all attribute filters => return empty results
if (ldapFilter.isFullSearch() || filter != null) {
for (ExchangeSession.Contact person : contactFind(filter, returningAttributes, sizeLimit).values()) {
persons.put(person.get("imapUid"), person);
if (persons.size() == sizeLimit) {
break;
}
}
if (!abandon && persons.size() < sizeLimit) {
for (ExchangeSession.Contact person : ldapFilter.findInGAL(session, returningAttributes, sizeLimit - persons.size()).values()) {
if (persons.size() == sizeLimit) {
break;
}
persons.put(person.get("uid"), person);
}
}
}
}
size = persons.size();
DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_FOUND_RESULTS", currentMessageId, size));
sendPersons(currentMessageId, ", " + dn, persons, returningAttributes);
DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_END", currentMessageId));
} else {
DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_ANONYMOUS_ACCESS_FORBIDDEN", currentMessageId, dn));
}
} else if (dn != null && dn.length() > 0) {
DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_INVALID_DN", currentMessageId, dn));
}
// iCal: do not send LDAP_SIZE_LIMIT_EXCEEDED on apple-computer search by cn with sizelimit 1
if (size > 1 && size == sizeLimit) {
DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_SIZE_LIMIT_EXCEEDED", currentMessageId));
sendClient(currentMessageId, LDAP_REP_RESULT, LDAP_SIZE_LIMIT_EXCEEDED, "");
} else {
DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_SUCCESS", currentMessageId));
sendClient(currentMessageId, LDAP_REP_RESULT, LDAP_SUCCESS, "");
}
} catch (SocketException e) {
// client closed connection
DavGatewayTray.debug(new BundleMessage("LOG_CLIENT_CLOSED_CONNECTION"));
} catch (IOException e) {
DavGatewayTray.log(e);
try {
sendErr(currentMessageId, LDAP_REP_RESULT, e);
} catch (IOException e2) {
DavGatewayTray.debug(new BundleMessage("LOG_EXCEPTION_SENDING_ERROR_TO_CLIENT"), e2);
}
} finally {
synchronized (searchThreadMap) {
searchThreadMap.remove(currentMessageId);
}
}
}
/**
* Search users in contacts folder
*
* @param condition search filter
* @param returningAttributes requested attributes
* @param maxCount maximum item count
* @return List of users
* @throws IOException on error
*/
public Map<String, ExchangeSession.Contact> contactFind(ExchangeSession.Condition condition, Set<String> returningAttributes, int maxCount) throws IOException {
Set<String> contactReturningAttributes;
if (returningAttributes != null && !returningAttributes.isEmpty()) {
contactReturningAttributes = new HashSet<String>();
// always return uid
contactReturningAttributes.add("imapUid");
for (String attribute : returningAttributes) {
String contactAttributeName = getContactAttributeName(attribute);
if (contactAttributeName != null) {
contactReturningAttributes.add(contactAttributeName);
}
}
} else {
contactReturningAttributes = ExchangeSession.CONTACT_ATTRIBUTES;
}
Map<String, ExchangeSession.Contact> results = new HashMap<String, ExchangeSession.Contact>();
List<ExchangeSession.Contact> contacts = session.searchContacts(ExchangeSession.CONTACTS, contactReturningAttributes, condition, maxCount);
for (ExchangeSession.Contact contact : contacts) {
// use imapUid as uid
String imapUid = contact.get("imapUid");
if (imapUid != null) {
contact.put("uid", imapUid);
contact.remove("imapUid");
results.put(imapUid, contact);
}
}
return results;
}
/**
* Convert to LDAP attributes and send entry
*
* @param currentMessageId current Message Id
* @param baseContext request base context (BASE_CONTEXT or OD_BASE_CONTEXT)
* @param persons persons Map
* @param returningAttributes returning attributes
* @throws IOException on error
*/
protected void sendPersons(int currentMessageId, String baseContext, Map<String, ExchangeSession.Contact> persons, Set<String> returningAttributes) throws IOException {
boolean needObjectClasses = returningAttributes.contains("objectclass") || returningAttributes.isEmpty();
boolean returnAllAttributes = returningAttributes.isEmpty();
for (ExchangeSession.Contact person : persons.values()) {
if (abandon) {
break;
}
Map<String, Object> ldapPerson = new HashMap<String, Object>();
// convert GAL entries
/*if (person.get("uid") != null) {
// TODO: move to galFind
// add detailed information, only for GAL entries
if (needDetails) {
session.galLookup(person);
}
// Process all attributes that are mapped from exchange
for (Map.Entry<String, String> entry : ATTRIBUTE_MAP.entrySet()) {
String ldapAttribute = entry.getKey();
String exchangeAttribute = entry.getValue();
String value = person.get(exchangeAttribute);
// contactFind return ldap attributes directly
if (value == null) {
value = person.get(ldapAttribute);
}
if (value != null
&& (returnAllAttributes || returningAttributes.contains(ldapAttribute.toLowerCase()))) {
ldapPerson.put(ldapAttribute, value);
}
}
// TODO
// iCal fix to suit both iCal 3 and 4: move cn to sn, remove cn
if (iCalSearch && ldapPerson.get("cn") != null && returningAttributes.contains("sn")) {
ldapPerson.put("sn", ldapPerson.get("cn"));
ldapPerson.remove("cn");
}
} else {*/
// convert Contact entries
if (returnAllAttributes) {
// just convert contact attributes to default ldap names
for (Map.Entry<String, String> entry : person.entrySet()) {
String ldapAttribute = getLdapAttributeName(entry.getKey());
String value = entry.getValue();
if (value != null) {
ldapPerson.put(ldapAttribute, value);
}
}
} else {
// always map uid
ldapPerson.put("uid", person.get("uid"));
// iterate over requested attributes
for (String ldapAttribute : returningAttributes) {
String contactAttribute = getContactAttributeName(ldapAttribute);
String value = person.get(contactAttribute);
if (value != null) {
if (ldapAttribute.startsWith("birth")) {
SimpleDateFormat parser = ExchangeSession.getZuluDateFormat();
Calendar calendar = Calendar.getInstance();
try {
calendar.setTime(parser.parse(value));
} catch (ParseException e) {
throw new IOException(e);
}
if ("birthday".equals(ldapAttribute)) {
value = String.valueOf(calendar.get(Calendar.DAY_OF_MONTH));
} else if ("birthmonth".equals(ldapAttribute)) {
value = String.valueOf(calendar.get(Calendar.MONTH) + 1);
} else if ("birthyear".equals(ldapAttribute)) {
value = String.valueOf(calendar.get(Calendar.YEAR));
}
}
ldapPerson.put(ldapAttribute, value);
}
}
}
//}
// Process all attributes which have static mappings
for (Map.Entry<String, String> entry : STATIC_ATTRIBUTE_MAP.entrySet()) {
String ldapAttribute = entry.getKey();
String value = entry.getValue();
if (value != null
&& (returnAllAttributes || returningAttributes.contains(ldapAttribute.toLowerCase()))) {
ldapPerson.put(ldapAttribute, value);
}
}
if (needObjectClasses) {
ldapPerson.put("objectClass", PERSON_OBJECT_CLASSES);
}
// iCal: copy email to apple-generateduid, encode @
if (returnAllAttributes || returningAttributes.contains("apple-generateduid")) {
String mail = (String) ldapPerson.get("mail");
if (mail != null) {
ldapPerson.put("apple-generateduid", mail.replaceAll("@", "__AT__"));
} else {
// failover, should not happen
ldapPerson.put("apple-generateduid", ldapPerson.get("uid"));
}
}
// iCal: replace current user alias with login name
if (session.getAlias().equals(ldapPerson.get("uid"))) {
if (returningAttributes.contains("uidnumber")) {
ldapPerson.put("uidnumber", userName);
}
}
DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_SEND_PERSON", currentMessageId, ldapPerson.get("uid"), baseContext, ldapPerson));
sendEntry(currentMessageId, "uid=" + ldapPerson.get("uid") + baseContext, ldapPerson);
}
}
}
}
| true | true | public void run() {
try {
int size = 0;
DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH", currentMessageId, dn, scope, sizeLimit, timelimit, ldapFilter.toString(), returningAttributes));
if (scope == SCOPE_BASE_OBJECT) {
if ("".equals(dn)) {
size = 1;
sendRootDSE(currentMessageId);
} else if (BASE_CONTEXT.equals(dn)) {
size = 1;
// root
sendBaseContext(currentMessageId);
} else if (dn.startsWith("uid=") && dn.indexOf(',') > 0) {
if (session != null) {
// single user request
String uid = dn.substring("uid=".length(), dn.indexOf(','));
Map<String, ExchangeSession.Contact> persons = null;
// first search in contact
try {
// check if this is a contact uid
Integer.parseInt(uid);
persons = contactFind(session.isEqualTo("imapUid", uid), returningAttributes, sizeLimit);
} catch (NumberFormatException e) {
// ignore, this is not a contact uid
}
// then in GAL
if (persons == null || persons.isEmpty()) {
persons = session.galFind(session.isEqualTo("uid", uid), returningAttributes, sizeLimit);
ExchangeSession.Contact person = persons.get(uid.toLowerCase());
// filter out non exact results
if (persons.size() > 1 || person == null) {
persons = new HashMap<String, ExchangeSession.Contact>();
if (person != null) {
persons.put(uid.toLowerCase(), person);
}
}
}
size = persons.size();
sendPersons(currentMessageId, dn.substring(dn.indexOf(',')), persons, returningAttributes);
} else {
DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_ANONYMOUS_ACCESS_FORBIDDEN", currentMessageId, dn));
}
} else {
DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_INVALID_DN", currentMessageId, dn));
}
} else if (COMPUTER_CONTEXT.equals(dn)) {
size = 1;
// computer context for iCal
sendComputerContext(currentMessageId, returningAttributes);
} else if ((BASE_CONTEXT.equalsIgnoreCase(dn) || OD_USER_CONTEXT.equalsIgnoreCase(dn))) {
if (session != null) {
Map<String, ExchangeSession.Contact> persons = new HashMap<String, ExchangeSession.Contact>();
if (ldapFilter.isFullSearch()) {
// append personal contacts first
for (ExchangeSession.Contact person : contactFind(null, returningAttributes, sizeLimit).values()) {
persons.put(person.get("imapUid"), person);
if (persons.size() == sizeLimit) {
break;
}
}
// full search
for (char c = 'A'; c < 'Z'; c++) {
if (!abandon && persons.size() < sizeLimit) {
for (ExchangeSession.Contact person : session.galFind(session.startsWith("uid", String.valueOf(c)), returningAttributes, sizeLimit).values()) {
persons.put(person.get("uid"), person);
if (persons.size() == sizeLimit) {
break;
}
}
}
if (persons.size() == sizeLimit) {
break;
}
}
} else {
// append personal contacts first
ExchangeSession.Condition filter = ldapFilter.getContactSearchFilter();
// if ldapfilter is not a full search and filter is null,
// ignored all attribute filters => return empty results
if (ldapFilter.isFullSearch() || filter != null) {
for (ExchangeSession.Contact person : contactFind(filter, returningAttributes, sizeLimit).values()) {
persons.put(person.get("imapUid"), person);
if (persons.size() == sizeLimit) {
break;
}
}
if (!abandon && persons.size() < sizeLimit) {
for (ExchangeSession.Contact person : ldapFilter.findInGAL(session, returningAttributes, sizeLimit - persons.size()).values()) {
if (persons.size() == sizeLimit) {
break;
}
persons.put(person.get("uid"), person);
}
}
}
}
size = persons.size();
DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_FOUND_RESULTS", currentMessageId, size));
sendPersons(currentMessageId, ", " + dn, persons, returningAttributes);
DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_END", currentMessageId));
} else {
DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_ANONYMOUS_ACCESS_FORBIDDEN", currentMessageId, dn));
}
} else if (dn != null && dn.length() > 0) {
DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_INVALID_DN", currentMessageId, dn));
}
// iCal: do not send LDAP_SIZE_LIMIT_EXCEEDED on apple-computer search by cn with sizelimit 1
if (size > 1 && size == sizeLimit) {
DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_SIZE_LIMIT_EXCEEDED", currentMessageId));
sendClient(currentMessageId, LDAP_REP_RESULT, LDAP_SIZE_LIMIT_EXCEEDED, "");
} else {
DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_SUCCESS", currentMessageId));
sendClient(currentMessageId, LDAP_REP_RESULT, LDAP_SUCCESS, "");
}
} catch (SocketException e) {
// client closed connection
DavGatewayTray.debug(new BundleMessage("LOG_CLIENT_CLOSED_CONNECTION"));
} catch (IOException e) {
DavGatewayTray.log(e);
try {
sendErr(currentMessageId, LDAP_REP_RESULT, e);
} catch (IOException e2) {
DavGatewayTray.debug(new BundleMessage("LOG_EXCEPTION_SENDING_ERROR_TO_CLIENT"), e2);
}
} finally {
synchronized (searchThreadMap) {
searchThreadMap.remove(currentMessageId);
}
}
}
| public void run() {
try {
int size = 0;
DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH", currentMessageId, dn, scope, sizeLimit, timelimit, ldapFilter.toString(), returningAttributes));
if (scope == SCOPE_BASE_OBJECT) {
if ("".equals(dn)) {
size = 1;
sendRootDSE(currentMessageId);
} else if (BASE_CONTEXT.equals(dn)) {
size = 1;
// root
sendBaseContext(currentMessageId);
} else if (dn.startsWith("uid=") && dn.indexOf(',') > 0) {
if (session != null) {
// single user request
String uid = dn.substring("uid=".length(), dn.indexOf(','));
Map<String, ExchangeSession.Contact> persons = null;
// first search in contact
try {
// check if this is a contact uid
Integer.parseInt(uid);
persons = contactFind(session.isEqualTo("imapUid", uid), returningAttributes, sizeLimit);
} catch (NumberFormatException e) {
// ignore, this is not a contact uid
}
// then in GAL
if (persons == null || persons.isEmpty()) {
persons = session.galFind(session.isEqualTo("uid", uid), returningAttributes, sizeLimit);
ExchangeSession.Contact person = persons.get(uid.toLowerCase());
// filter out non exact results
if (persons.size() > 1 || person == null) {
persons = new HashMap<String, ExchangeSession.Contact>();
if (person != null) {
persons.put(uid.toLowerCase(), person);
}
}
}
size = persons.size();
sendPersons(currentMessageId, dn.substring(dn.indexOf(',')), persons, returningAttributes);
} else {
DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_ANONYMOUS_ACCESS_FORBIDDEN", currentMessageId, dn));
}
} else {
DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_INVALID_DN", currentMessageId, dn));
}
} else if (COMPUTER_CONTEXT.equals(dn)) {
size = 1;
// computer context for iCal
sendComputerContext(currentMessageId, returningAttributes);
} else if ((BASE_CONTEXT.equalsIgnoreCase(dn) || OD_USER_CONTEXT.equalsIgnoreCase(dn))) {
if (session != null) {
Map<String, ExchangeSession.Contact> persons = new HashMap<String, ExchangeSession.Contact>();
if (ldapFilter.isFullSearch()) {
// append personal contacts first
for (ExchangeSession.Contact person : contactFind(null, returningAttributes, sizeLimit).values()) {
persons.put(person.get("imapUid"), person);
if (persons.size() == sizeLimit) {
break;
}
}
// full search
for (char c = 'A'; c <= 'Z'; c++) {
if (!abandon && persons.size() < sizeLimit) {
for (ExchangeSession.Contact person : session.galFind(session.startsWith("uid", String.valueOf(c)), returningAttributes, sizeLimit).values()) {
persons.put(person.get("uid"), person);
if (persons.size() == sizeLimit) {
break;
}
}
}
if (persons.size() == sizeLimit) {
break;
}
}
} else {
// append personal contacts first
ExchangeSession.Condition filter = ldapFilter.getContactSearchFilter();
// if ldapfilter is not a full search and filter is null,
// ignored all attribute filters => return empty results
if (ldapFilter.isFullSearch() || filter != null) {
for (ExchangeSession.Contact person : contactFind(filter, returningAttributes, sizeLimit).values()) {
persons.put(person.get("imapUid"), person);
if (persons.size() == sizeLimit) {
break;
}
}
if (!abandon && persons.size() < sizeLimit) {
for (ExchangeSession.Contact person : ldapFilter.findInGAL(session, returningAttributes, sizeLimit - persons.size()).values()) {
if (persons.size() == sizeLimit) {
break;
}
persons.put(person.get("uid"), person);
}
}
}
}
size = persons.size();
DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_FOUND_RESULTS", currentMessageId, size));
sendPersons(currentMessageId, ", " + dn, persons, returningAttributes);
DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_END", currentMessageId));
} else {
DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_ANONYMOUS_ACCESS_FORBIDDEN", currentMessageId, dn));
}
} else if (dn != null && dn.length() > 0) {
DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_INVALID_DN", currentMessageId, dn));
}
// iCal: do not send LDAP_SIZE_LIMIT_EXCEEDED on apple-computer search by cn with sizelimit 1
if (size > 1 && size == sizeLimit) {
DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_SIZE_LIMIT_EXCEEDED", currentMessageId));
sendClient(currentMessageId, LDAP_REP_RESULT, LDAP_SIZE_LIMIT_EXCEEDED, "");
} else {
DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_SUCCESS", currentMessageId));
sendClient(currentMessageId, LDAP_REP_RESULT, LDAP_SUCCESS, "");
}
} catch (SocketException e) {
// client closed connection
DavGatewayTray.debug(new BundleMessage("LOG_CLIENT_CLOSED_CONNECTION"));
} catch (IOException e) {
DavGatewayTray.log(e);
try {
sendErr(currentMessageId, LDAP_REP_RESULT, e);
} catch (IOException e2) {
DavGatewayTray.debug(new BundleMessage("LOG_EXCEPTION_SENDING_ERROR_TO_CLIENT"), e2);
}
} finally {
synchronized (searchThreadMap) {
searchThreadMap.remove(currentMessageId);
}
}
}
|
diff --git a/src/main/java/com/bergerkiller/bukkit/common/internal/CommonPlugin.java b/src/main/java/com/bergerkiller/bukkit/common/internal/CommonPlugin.java
index 1ae7e5c..a48a46c 100644
--- a/src/main/java/com/bergerkiller/bukkit/common/internal/CommonPlugin.java
+++ b/src/main/java/com/bergerkiller/bukkit/common/internal/CommonPlugin.java
@@ -1,656 +1,660 @@
package com.bergerkiller.bukkit.common.internal;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import me.snowleo.bleedingmobs.BleedingMobs;
import net.milkbowl.vault.permission.Permission;
import net.minecraft.server.v1_5_R2.Entity;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;
import regalowl.hyperconomy.HyperConomy;
import com.bergerkiller.bukkit.common.Common;
import com.bergerkiller.bukkit.common.MessageBuilder;
import com.bergerkiller.bukkit.common.ModuleLogger;
import com.bergerkiller.bukkit.common.PluginBase;
import com.bergerkiller.bukkit.common.Task;
import com.bergerkiller.bukkit.common.TypedValue;
import com.bergerkiller.bukkit.common.collections.EntityMap;
import com.bergerkiller.bukkit.common.events.EntityMoveEvent;
import com.bergerkiller.bukkit.common.events.EntityRemoveFromServerEvent;
import com.bergerkiller.bukkit.common.internal.network.CommonPacketHandler;
import com.bergerkiller.bukkit.common.internal.network.ProtocolLibPacketHandler;
import com.bergerkiller.bukkit.common.internal.network.SpigotPacketHandler;
import com.bergerkiller.bukkit.common.metrics.MyDependingPluginsGraph;
import com.bergerkiller.bukkit.common.metrics.SoftDependenciesGraph;
import com.bergerkiller.bukkit.common.utils.CommonUtil;
import com.bergerkiller.bukkit.common.utils.StringUtil;
import com.bergerkiller.bukkit.common.utils.WorldUtil;
import com.bergerkiller.bukkit.common.wrappers.LongHashSet;
import com.kellerkindt.scs.ShowCaseStandalone;
import com.narrowtux.showcase.Showcase;
@SuppressWarnings({"rawtypes", "unchecked"})
public class CommonPlugin extends PluginBase {
/**
* BKCommonLib Minecraft versioning
*/
public static final String DEPENDENT_MC_VERSION = "v1_5_R2";
public static final boolean IS_COMPATIBLE = Common.isMCVersionCompatible(DEPENDENT_MC_VERSION);
/*
* Loggers for internal BKCommonLib processes
*/
public static final ModuleLogger LOGGER = new ModuleLogger("BKCommonLib");
public static final ModuleLogger LOGGER_CONVERSION = LOGGER.getModule("Conversion");
public static final ModuleLogger LOGGER_REFLECTION = LOGGER.getModule("Reflection");
public static final ModuleLogger LOGGER_NETWORK = LOGGER.getModule("Network");
/*
* Remaining internal variables
*/
private static CommonPlugin instance;
public final List<PluginBase> plugins = new ArrayList<PluginBase>();
private EntityMap<Player, LongHashSet> playerVisibleChunks;
protected final Map<World, CommonWorldListener> worldListeners = new HashMap<World, CommonWorldListener>();
private final ArrayList<SoftReference<EntityMap>> maps = new ArrayList<SoftReference<EntityMap>>();
private final List<Runnable> nextTickTasks = new ArrayList<Runnable>();
private final List<Runnable> nextTickSync = new ArrayList<Runnable>();
private final List<NextTickListener> nextTickListeners = new ArrayList<NextTickListener>(1);
private final List<Task> startedTasks = new ArrayList<Task>();
private final HashSet<org.bukkit.entity.Entity> entitiesToRemove = new HashSet<org.bukkit.entity.Entity>();
private final HashMap<String, TypedValue> debugVariables = new HashMap<String, TypedValue>();
private boolean vaultEnabled = false;
private Permission vaultPermission = null;
private boolean isShowcaseEnabled = false;
private boolean isSCSEnabled = false;
private boolean isHyperConomyEnabled = false;
private Plugin bleedingMobsInstance = null;
private PacketHandler packetHandler = null;
public static boolean hasInstance() {
return instance != null;
}
public static CommonPlugin getInstance() {
if (instance == null) {
throw new RuntimeException("BKCommonLib is not enabled - Plugin Instance can not be obtained! (disjointed Class state?)");
}
return instance;
}
/**
* Handles the message and/or stack trace logging when something related to reflection is missing
*
* @param type of thing that is missing
* @param name of the thing that is missing
* @param source class in which it is missing
*/
public void handleReflectionMissing(String type, String name, Class<?> source) {
String msg = type + " '" + name + "' does not exist in class file " + source.getName();
Exception ex = new Exception(msg);
for (StackTraceElement elem : ex.getStackTrace()) {
if (elem.getClassName().startsWith(Common.COMMON_ROOT + ".reflection.classes")) {
LOGGER_REFLECTION.log(Level.SEVERE, msg + " (Update BKCommonLib?)");
for (StackTraceElement ste : ex.getStackTrace()) {
log(Level.SEVERE, "at " + ste.toString());
}
return;
}
}
ex.printStackTrace();
}
public void registerMap(EntityMap map) {
this.maps.add(new SoftReference(map));
}
public void nextTick(Runnable runnable) {
synchronized (this.nextTickTasks) {
this.nextTickTasks.add(runnable);
}
}
public <T> TypedValue<T> getDebugVariable(String name, Class<T> type, T value) {
TypedValue typed = debugVariables.get(name);
if (typed == null || typed.type != type) {
typed = new TypedValue(type, value);
debugVariables.put(name, typed);
}
return typed;
}
public void addNextTickListener(NextTickListener listener) {
nextTickListeners.add(listener);
}
public void removeNextTickListener(NextTickListener listener) {
nextTickListeners.remove(listener);
}
public void notifyAdded(org.bukkit.entity.Entity e) {
this.entitiesToRemove.remove(e);
}
public void notifyRemoved(org.bukkit.entity.Entity e) {
this.entitiesToRemove.add(e);
}
public void notifyWorldAdded(org.bukkit.World world) {
if (worldListeners.containsKey(world)) {
return;
}
CommonWorldListener listener = new CommonWorldListener(world);
listener.enable();
worldListeners.put(world, listener);
}
@SuppressWarnings("deprecation")
public boolean isEntityIgnored(org.bukkit.entity.Entity entity) {
if (entity instanceof Item) {
Item item = (Item) entity;
if (this.isShowcaseEnabled) {
try {
if (Showcase.instance.getItemByDrop(item) != null) {
return true;
}
} catch (Throwable t) {
log(Level.SEVERE, "Showcase item verification failed (update needed?), contact the authors!");
handle(t);
this.isShowcaseEnabled = false;
}
}
if (this.isSCSEnabled) {
try {
if (ShowCaseStandalone.get().getShopHandler().isShopItem(item)) {
return true;
}
} catch (Throwable t) {
log(Level.SEVERE, "ShowcaseStandalone item verification failed (update needed?), contact the authors!");
handle(t);
this.isSCSEnabled = false;
}
}
if (this.isHyperConomyEnabled) {
try {
if (HyperConomy.hyperAPI.isItemDisplay(item)) {
return true;
}
} catch (Throwable t) {
log(Level.SEVERE, "HyperConomy item verification failed (update needed?), contact the authors!");
handle(t);
this.isHyperConomyEnabled = false;
}
}
if (this.bleedingMobsInstance != null) {
try {
BleedingMobs bm = (BleedingMobs) this.bleedingMobsInstance;
if (bm.isSpawning() || (bm.isWorldEnabled(item.getWorld()) && bm.isParticleItem(item.getUniqueId()))) {
return true;
}
} catch (Throwable t) {
Bukkit.getLogger().log(Level.SEVERE, "Bleeding Mobs item verification failed (update needed?), contact the authors!");
t.printStackTrace();
this.bleedingMobsInstance = null;
}
}
}
return false;
}
private boolean permCheck(CommandSender sender, String node) {
+ // This check avoids the *-permissions granting all OP-players permission for everything
+ if (Bukkit.getPluginManager().getPermission(node) == null) {
+ return false;
+ }
if (this.vaultEnabled) {
return this.vaultPermission.has(sender, node);
} else {
return sender.hasPermission(node);
}
}
private boolean permCheck(CommandSender sender, StringBuilder root, String[] args, int argIndex) {
// End of the sequence?
if (argIndex >= args.length) {
return permCheck(sender, root.toString());
}
int rootLength = root.length();
if (rootLength != 0) {
root.append('.');
rootLength++;
}
final int newArgIndex = argIndex + 1;
// Check permission with original name
root.append(args[argIndex].toLowerCase(Locale.ENGLISH));
if (permCheck(sender, root, args, newArgIndex)) {
return true;
}
// Try with *-signs
root.setLength(rootLength);
root.append('*');
return permCheck(sender, root, args, newArgIndex);
}
public boolean hasPermission(CommandSender sender, String[] permissionNode) {
int expectedLength = permissionNode.length;
for (String node : permissionNode) {
expectedLength += node.length();
}
return permCheck(sender, new StringBuilder(expectedLength), permissionNode, 0);
}
public boolean hasPermission(CommandSender sender, String permissionNode) {
return permCheck(sender, permissionNode.toLowerCase(Locale.ENGLISH)) || hasPermission(sender, permissionNode.split("\\."));
}
public boolean isChunkVisible(Player player, int chunkX, int chunkZ) {
synchronized (playerVisibleChunks) {
LongHashSet chunks = playerVisibleChunks.get(player);
return chunks == null ? false : chunks.contains(chunkX, chunkZ);
}
}
public void setChunksAsVisible(Player player, int[] chunkX, int[] chunkZ) {
if (chunkX.length != chunkZ.length) {
throw new IllegalArgumentException("Chunk X and Z coordinate count is not the same");
}
synchronized (playerVisibleChunks) {
LongHashSet chunks = playerVisibleChunks.get(player);
if (chunks == null) {
chunks = new LongHashSet();
playerVisibleChunks.put(player, chunks);
}
for (int i = 0; i < chunkX.length; i++) {
chunks.add(chunkX[i], chunkZ[i]);
}
}
}
public void setChunkVisible(Player player, int chunkX, int chunkZ, boolean visible) {
synchronized (playerVisibleChunks) {
LongHashSet chunks = playerVisibleChunks.get(player);
if (chunks == null) {
if (!visible) {
return;
}
chunks = new LongHashSet();
playerVisibleChunks.put(player, chunks);
}
if (visible) {
chunks.add(chunkX, chunkZ);
} else {
chunks.remove(chunkX, chunkZ);
}
}
}
/**
* Obtains the Packet Handler used for packet listeners/monitors and packet sending
*
* @return packet handler instance
*/
public PacketHandler getPacketHandler() {
return packetHandler;
}
private boolean updatePacketHandler() {
try {
final Class<? extends PacketHandler> handlerClass;
if (CommonUtil.isPluginEnabled("ProtocolLib")) {
handlerClass = ProtocolLibPacketHandler.class;
} else if (Common.IS_SPIGOT_SERVER) {
handlerClass = SpigotPacketHandler.class;
} else {
handlerClass = CommonPacketHandler.class;
}
// Register the packet handler
if (this.packetHandler != null && this.packetHandler.getClass() == handlerClass) {
return true;
}
final PacketHandler handler = handlerClass.newInstance();
if (this.packetHandler != null) {
this.packetHandler.transfer(handler);
if (!this.packetHandler.onDisable()) {
return false;
}
}
this.packetHandler = handler;
if (!this.packetHandler.onEnable()) {
return false;
}
LOGGER_NETWORK.log(Level.INFO, "Now using " + handler.getName() + " to provide Packet Listener and Monitor support");
return true;
} catch (Throwable t) {
LOGGER_NETWORK.log(Level.SEVERE, "Failed to register a valid Packet Handler:");
t.printStackTrace();
return false;
}
}
/**
* Should be called when BKCommonLib is unable to continue running as it does
*/
public void onCriticalFailure() {
log(Level.SEVERE, "BKCommonLib and all depending plugins will now disable...");
Bukkit.getPluginManager().disablePlugin(this);
}
@Override
public void permissions() {
}
@Override
public void updateDependency(Plugin plugin, String pluginName, boolean enabled) {
if (!enabled) {
packetHandler.removePacketListeners(plugin);
}
if (pluginName.equals("Showcase")) {
if (this.isShowcaseEnabled = enabled) {
log(Level.INFO, "Showcase detected: Showcased items will be ignored");
}
} else if (pluginName.equals("ShowCaseStandalone")) {
if (this.isSCSEnabled = enabled) {
log(Level.INFO, "Showcase Standalone detected: Showcased items will be ignored");
}
} else if (pluginName.equals("HyperConomy")) {
if (this.isHyperConomyEnabled = enabled) {
log(Level.INFO, "HyperConomy detected: Showcased items will be ignored");
}
} else if (pluginName.equals("BleedingMobs")) {
this.bleedingMobsInstance = enabled ? plugin : null;
if (enabled) {
log(Level.INFO, "Bleeding Mobs detected: Particle items will be ignored");
}
} else if (pluginName.equals("Vault")) {
if (enabled) {
RegisteredServiceProvider<Permission> permissionProvider = getServer().getServicesManager().getRegistration(Permission.class);
if (permissionProvider != null) {
this.vaultPermission = permissionProvider.getProvider();
this.vaultEnabled = this.vaultPermission != null;
}
} else {
this.vaultPermission = null;
this.vaultEnabled = false;
}
}
if (!this.updatePacketHandler()) {
this.onCriticalFailure();
}
}
@Override
public int getMinimumLibVersion() {
return 0;
}
@Override
public void onLoad() {
instance = this;
if (!IS_COMPATIBLE) {
return;
}
// Load the classes contained in this library
CommonClasses.init();
}
@Override
public void disable() {
instance = null;
for (CommonWorldListener listener : worldListeners.values()) {
listener.disable();
}
worldListeners.clear();
// Clear running tasks
for (Task task : startedTasks) {
task.stop();
}
startedTasks.clear();
// Disable the packet handlers
try {
packetHandler.onDisable();
} catch (Throwable t) {
log(Level.SEVERE, "Failed to properly disable the Packet Handler:");
t.printStackTrace();
}
packetHandler = null;
}
@Override
public void enable() {
// Validate version
if (IS_COMPATIBLE) {
String version = "Minecraft " + Common.MC_VERSION;
if (Common.MC_VERSION_PACKAGEPART.isEmpty()) {
version += " (Non-versioned package)";
} else {
version += " (" + DEPENDENT_MC_VERSION + ")";
}
log(Level.INFO, "BKCommonLib is running on " + version);
} else {
log(Level.SEVERE, "BKCommonLib can only run on a CraftBukkit build compatible with Minecraft " + DEPENDENT_MC_VERSION);
log(Level.SEVERE, "Please look for an available BKCommonLib update that is compatible with Minecraft " + Common.MC_VERSION + ":");
log(Level.SEVERE, "http://dev.bukkit.org/server-mods/bkcommonlib/");
this.onCriticalFailure();
return;
}
// Set the packet handler to use before enabling further - it could fail!
if (!this.updatePacketHandler()) {
this.onCriticalFailure();
return;
}
// Welcome message
setDisableMessage(null);
final List<String> welcomeMessages = Arrays.asList(
"This library is written with stability in mind.",
"No Bukkit moderators were harmed while compiling this piece of art.",
"Have a problem Bukkit can't fix? Write a library!",
"Bringing home the bacon since 2011!",
"Completely virus-free and scanned by various Bukkit-dev-staff watching eyes.",
"Hosts all the features that are impossible to include in a single Class",
"CraftBukkit: redone, reworked, translated and interfaced.",
"Having an error? *gasp* Don't forget to file a ticket on dev.bukkit.org!",
"Package versioning is what brought BKCommonLib and CraftBukkit closer together!",
"For all the haters out there: BKCommonLib at least tries!",
"Want fries with that? We have hidden fries in the FoodUtil class.",
"Not enough wrappers. Needs more wrappers. Moooreee...",
"Reflection can open the way to everyone's heart, including CraftBukkit.",
"Our love is not permitted by the overlords. We must flee...",
"Now a plugin, a new server implementation tomorrow???");
log(Level.INFO, welcomeMessages.get((int) (Math.random() * welcomeMessages.size())));
// Initialize entity map (needs to be here because of CommonPlugin instance needed)
playerVisibleChunks = new EntityMap<Player, LongHashSet>();
// Register events and tasks, initialize
register(new CommonListener());
register(new CommonPacketMonitor(), CommonPacketMonitor.TYPES);
startedTasks.add(new NextTickHandler(this).start(1, 1));
startedTasks.add(new MoveEventHandler(this).start(1, 1));
startedTasks.add(new EntityRemovalHandler(this).start(1, 1));
// Register world listeners
for (World world : WorldUtil.getWorlds()) {
notifyWorldAdded(world);
}
// BKCommonLib Metrics
if (hasMetrics()) {
// Soft dependencies
getMetrics().addGraph(new SoftDependenciesGraph());
// Depending
getMetrics().addGraph(new MyDependingPluginsGraph());
}
// Parse BKCommonLib version to int
int version = this.getVersionNumber();
if (version != Common.VERSION) {
log(Level.SEVERE, "Common.VERSION needs to be updated to contain '" + version + "'!");
}
}
private static class EntityRemovalHandler extends Task {
public EntityRemovalHandler(JavaPlugin plugin) {
super(plugin);
}
@Override
public void run() {
Set<org.bukkit.entity.Entity> removed = getInstance().entitiesToRemove;
if (!removed.isEmpty()) {
// Remove from maps
Iterator<SoftReference<EntityMap>> iter = CommonPlugin.getInstance().maps.iterator();
while (iter.hasNext()) {
EntityMap map = iter.next().get();
if (map == null) {
iter.remove();
} else if (!map.isEmpty()) {
map.keySet().removeAll(removed);
}
}
// Fire events
if (CommonUtil.hasHandlers(EntityRemoveFromServerEvent.getHandlerList())) {
for (org.bukkit.entity.Entity e : removed) {
CommonUtil.callEvent(new EntityRemoveFromServerEvent(e));
}
}
// Clear for next run
removed.clear();
}
}
}
private static class NextTickHandler extends Task {
public NextTickHandler(JavaPlugin plugin) {
super(plugin);
}
@Override
public void run() {
List<Runnable> nextTick = getInstance().nextTickTasks;
List<Runnable> nextSync = getInstance().nextTickSync;
List<NextTickListener> nextTickListeners = getInstance().nextTickListeners;
synchronized (nextTick) {
if (nextTick.isEmpty()) {
return;
}
nextSync.addAll(nextTick);
nextTick.clear();
}
if (nextTickListeners.isEmpty()) {
// No time measurement needed
for (Runnable task : nextSync) {
try {
task.run();
} catch (Throwable t) {
instance.log(Level.SEVERE, "An error occurred in next-tick task '" + task.getClass().getName() + "':");
CommonUtil.filterStackTrace(t).printStackTrace();
}
}
} else {
// Perform time measurement and call next-tick listeners
int i;
final int listenerCount = nextTickListeners.size();
long startTime, delta, endTime = System.nanoTime();
for (Runnable task : nextSync) {
startTime = endTime;
try {
task.run();
} catch (Throwable t) {
instance.log(Level.SEVERE, "An error occurred in next-tick task '" + task.getClass().getName() + "':");
CommonUtil.filterStackTrace(t).printStackTrace();
}
endTime = System.nanoTime();
delta = endTime - startTime;
for (i = 0; i < listenerCount; i++) {
nextTickListeners.get(i).onNextTicked(task, delta);
}
}
}
nextSync.clear();
}
}
private static class MoveEventHandler extends Task {
private final List<Entity> entityBuffer = new ArrayList<Entity>();
public MoveEventHandler(JavaPlugin plugin) {
super(plugin);
}
@Override
public void run() {
if (CommonUtil.hasHandlers(EntityMoveEvent.getHandlerList())) {
EntityMoveEvent event = new EntityMoveEvent();
for (World world : WorldUtil.getWorlds()) {
entityBuffer.addAll(CommonNMS.getNative(world).entityList);
for (Entity entity : entityBuffer) {
if (entity.locX != entity.lastX || entity.locY != entity.lastY || entity.locZ != entity.lastZ
|| entity.yaw != entity.lastYaw || entity.pitch != entity.lastPitch) {
event.setEntity(entity);
CommonUtil.callEvent(event);
}
}
entityBuffer.clear();
}
}
}
}
@Override
public boolean command(CommandSender sender, String command, String[] args) {
if (debugVariables.isEmpty()) {
return false;
}
if (command.equals("commondebug") || command.equals("debug")) {
MessageBuilder message = new MessageBuilder();
if (args.length == 0) {
message.green("This command allows you to tweak debug settings in plugins").newLine();
message.green("All debug variables should be cleared in official builds").newLine();
message.green("Available debug variables:").newLine();
message.setSeparator(ChatColor.YELLOW, " \\ ").setIndent(4);
for (String variable : debugVariables.keySet()) {
message.green(variable);
}
} else {
final String varname = args[0];
final TypedValue value = debugVariables.get(varname);
if (value == null) {
message.red("No debug variable of name '").yellow(varname).red("'!");
} else {
message.green("Value of variable '").yellow(varname).green("' ");
if (args.length == 1) {
message.green("= ");
} else {
message.green("set to ");
value.parseSet(StringUtil.combine(" ", StringUtil.remove(args, 0)));
}
message.white(value.toString());
}
}
message.send(sender);
return true;
}
return false;
}
}
\ No newline at end of file
| true | false | null | null |
diff --git a/org.osate.aadl2.errormodel.analysis/src/org/osate/aadl2/errormodel/analysis/actions/RBDAction.java b/org.osate.aadl2.errormodel.analysis/src/org/osate/aadl2/errormodel/analysis/actions/RBDAction.java
index 8f76bc42..8b606e31 100644
--- a/org.osate.aadl2.errormodel.analysis/src/org/osate/aadl2/errormodel/analysis/actions/RBDAction.java
+++ b/org.osate.aadl2.errormodel.analysis/src/org/osate/aadl2/errormodel/analysis/actions/RBDAction.java
@@ -1,270 +1,274 @@
/*
* <copyright>
* Copyright 2012 by Carnegie Mellon University, all rights reserved.
*
* Use of the Open Source AADL Tool Environment (OSATE) is subject to the terms of the license set forth
* at http://www.eclipse.org/org/documents/epl-v10.html.
*
* NO WARRANTY
*
* ANY INFORMATION, MATERIALS, SERVICES, INTELLECTUAL PROPERTY OR OTHER PROPERTY OR RIGHTS GRANTED OR PROVIDED BY
* CARNEGIE MELLON UNIVERSITY PURSUANT TO THIS LICENSE (HEREINAFTER THE "DELIVERABLES") ARE ON AN "AS-IS" BASIS.
* CARNEGIE MELLON UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED AS TO ANY MATTER INCLUDING,
* BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, INFORMATIONAL CONTENT,
* NONINFRINGEMENT, OR ERROR-FREE OPERATION. CARNEGIE MELLON UNIVERSITY SHALL NOT BE LIABLE FOR INDIRECT, SPECIAL OR
* CONSEQUENTIAL DAMAGES, SUCH AS LOSS OF PROFITS OR INABILITY TO USE SAID INTELLECTUAL PROPERTY, UNDER THIS LICENSE,
* REGARDLESS OF WHETHER SUCH PARTY WAS AWARE OF THE POSSIBILITY OF SUCH DAMAGES. LICENSEE AGREES THAT IT WILL NOT
* MAKE ANY WARRANTY ON BEHALF OF CARNEGIE MELLON UNIVERSITY, EXPRESS OR IMPLIED, TO ANY PERSON CONCERNING THE
* APPLICATION OF OR THE RESULTS TO BE OBTAINED WITH THE DELIVERABLES UNDER THIS LICENSE.
*
* Licensee hereby agrees to defend, indemnify, and hold harmless Carnegie Mellon University, its trustees, officers,
* employees, and agents from all claims or demands made against them (and any related losses, expenses, or
* attorney's fees) arising out of, or relating to Licensee's and/or its sub licensees' negligent use or willful
* misuse of or negligent conduct or willful misconduct regarding the Software, facilities, or other rights or
* assistance granted by Carnegie Mellon University under this License, including, but not limited to, any claims of
* product liability, personal injury, death, damage to property, or violation of any laws or regulations.
*
* Carnegie Mellon Carnegie Mellon University Software Engineering Institute authored documents are sponsored by the U.S. Department
* of Defense under Contract F19628-00-C-0003. Carnegie Mellon University retains copyrights in all material produced
* under this contract. The U.S. Government retains a non-exclusive, royalty-free license to publish or reproduce these
* documents, or allow others to do so, for U.S. Government purposes only pursuant to the copyright license
* under the contract clause at 252.227.7013.
* </copyright>
*/
package org.osate.aadl2.errormodel.analysis.actions;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.emf.common.util.EList;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.osate.aadl2.ContainedNamedElement;
import org.osate.aadl2.Element;
import org.osate.aadl2.Subcomponent;
import org.osate.aadl2.instance.ComponentInstance;
import org.osate.aadl2.instance.InstanceObject;
import org.osate.aadl2.instance.SystemInstance;
import org.osate.ui.actions.AaxlReadOnlyActionAsJob;
import org.osate.ui.dialogs.Dialog;
import org.osate.xtext.aadl2.errormodel.errorModel.CompositeErrorBehavior;
import org.osate.xtext.aadl2.errormodel.errorModel.CompositeState;
import org.osate.xtext.aadl2.errormodel.errorModel.ConditionElement;
import org.osate.xtext.aadl2.errormodel.errorModel.ConditionExpression;
import org.osate.xtext.aadl2.errormodel.errorModel.ErrorBehaviorState;
import org.osate.xtext.aadl2.errormodel.errorModel.ErrorModelSubclause;
import org.osate.xtext.aadl2.errormodel.errorModel.SAndExpression;
import org.osate.xtext.aadl2.errormodel.errorModel.SOrExpression;
import org.osate.xtext.aadl2.errormodel.errorModel.SubcomponentElement;
import org.osate.xtext.aadl2.errormodel.util.EMV2Util;
public final class RBDAction extends AaxlReadOnlyActionAsJob {
private double finalResult;
private List<ComponentInstance> componentsNames;
private static String ERROR_STATE_NAME = null;
protected String getMarkerType() {
return "org.osate.analysis.errormodel.FaultImpactMarker";
}
protected String getActionName() {
return "RBD";
}
private static ComponentInstance findInstance (EList<ComponentInstance> instances, String name)
{
for (ComponentInstance ci : instances)
{
if (ci.getName().equalsIgnoreCase(name))
{
return ci;
}
}
return null;
}
private double handleElement (final ConditionElement conditionElement, final EList<ComponentInstance> componentInstances)
{
double result = 0;
ErrorBehaviorState behaviorState = conditionElement.getReference();
for (SubcomponentElement subcomponentElement : conditionElement.getSubcomponents())
{
Subcomponent subcomponent = subcomponentElement.getSubcomponent();
//OsateDebug.osateDebug(" subcomponent " + subcomponent);
ComponentInstance relatedInstance = findInstance(componentInstances, subcomponent.getName());
//OsateDebug.osateDebug(" instance " + relatedInstance);
if (relatedInstance != null && ! this.componentsNames.contains(relatedInstance))
{
this.componentsNames.add (relatedInstance);
}
if (behaviorState != null)
{
//OsateDebug.osateDebug(" behaviorState " + behaviorState);
ContainedNamedElement PA = EMV2Util.getOccurenceDistributionProperty(relatedInstance,null,behaviorState,null);
//OsateDebug.osateDebug(" PA " + PA);
result = EMV2Util.getOccurenceValue (PA);
}
}
return result;
}
private double handleCondition (final ConditionExpression cond, final EList<ComponentInstance> componentInstances)
{
double result = 0;
double tmp;
//OsateDebug.osateDebug("cond="+cond);
if (cond instanceof ConditionElement)
{
return handleElement((ConditionElement)cond, componentInstances);
}
if (cond instanceof SOrExpression)
{
SOrExpression sor = (SOrExpression)cond;
for (ConditionExpression conditionExpression : sor.getOperands())
{
//OsateDebug.osateDebug(" operand=" + conditionExpression);
result += handleCondition (conditionExpression, componentInstances);
}
}
if (cond instanceof SAndExpression)
{
SAndExpression sae = (SAndExpression)cond;
for (ConditionExpression conditionExpression : sae.getOperands())
{
tmp = handleCondition (conditionExpression, componentInstances);
if (result == 0)
{
result = tmp;
}
else
{
result = result * tmp;
}
}
}
return result;
}
public void processRootSystem (SystemInstance systemInstance)
{
EList<CompositeState> states;
CompositeErrorBehavior ceb;
EList<ComponentInstance> componentInstances;
double probabilityTemp;
double toRemove;
ErrorModelSubclause ems = EMV2Util.getFirstEMV2Subclause(systemInstance.getComponentClassifier());
ceb = ems.getCompositeBehavior();
componentInstances = EMV2Util.getComponentInstancesWithEMV2Subclause(systemInstance);
// TODO may need to be updated to handle inherits from classifier extensions
states = ceb.getStates();
probabilityTemp = 0;
toRemove = 0;
for (CompositeState state : states)
{
if (state.getState().getName().equalsIgnoreCase(ERROR_STATE_NAME))
{
probabilityTemp = handleCondition (state.getCondition(), componentInstances);
// OsateDebug.osateDebug("temp=" + probabilityTemp);
finalResult = finalResult + probabilityTemp;
if (toRemove == 0)
{
toRemove = probabilityTemp;
}
else
{
toRemove = toRemove * probabilityTemp;
}
}
}
- finalResult = finalResult - toRemove;
+ // seems to reset the fa
+ if (finalResult > toRemove)
+ {
+ finalResult = finalResult - toRemove;
+ }
}
public void doAaxlAction(IProgressMonitor monitor, Element obj) {
SystemInstance si;
String message;
monitor.beginTask("RBD", IProgressMonitor.UNKNOWN);
si = null;
this.componentsNames = new ArrayList<ComponentInstance>();
this.finalResult = 0;
if (obj instanceof InstanceObject){
si = ((InstanceObject)obj).getSystemInstance();
}
if (si == null)
{
Dialog.showInfo("RDB", "Please choose an instance model");
monitor.done();
}
if (! EMV2Util.hasCompositeErrorBehavior (si))
{
Dialog.showInfo("RDB", "Your system instance does not have a composite error behavior");
monitor.done();
}
final Display d = PlatformUI.getWorkbench().getDisplay();
d.syncExec(new Runnable(){
public void run() {
IWorkbenchWindow window;
Shell sh;
List<String> modulesList;
window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
sh = window.getShell();
InputDialog fd = new InputDialog(sh, "Error State name", "Please specify the name of the error state name", "failed", null);
if (fd.open() == Window.OK)
{
ERROR_STATE_NAME = fd.getValue();
}
else
{
ERROR_STATE_NAME = null;
}
}});
if (ERROR_STATE_NAME != null)
{
processRootSystem (si);
message = "Failure probability: " + this.finalResult + "\n";
message += "Components involved:\n";
for (ComponentInstance ci : this.componentsNames)
{
message += " * " + ci.getName() + " ("+ci.getCategory().toString()+")\n";
}
Dialog.showInfo("Reliability Block Diagram", message);
}
monitor.done();
}
}
| true | false | null | null |
diff --git a/src/com/android/settings/SettingsPreferenceFragment.java b/src/com/android/settings/SettingsPreferenceFragment.java
index 39ffcb4e1..da56cc4dc 100644
--- a/src/com/android/settings/SettingsPreferenceFragment.java
+++ b/src/com/android/settings/SettingsPreferenceFragment.java
@@ -1,334 +1,332 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.Fragment;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Button;
/**
* Base class for Settings fragments, with some helper functions and dialog management.
*/
public class SettingsPreferenceFragment extends PreferenceFragment implements DialogCreatable {
private static final String TAG = "SettingsPreferenceFragment";
protected Context mContext;
private static final int MENU_HELP = Menu.FIRST + 100;
private SettingsDialogFragment mDialogFragment;
- protected boolean hasFastCharge;
protected ContentResolver mContentRes;
private String mHelpUrl;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
- hasFastCharge = getResources().getBoolean(R.bool.has_fast_charge);
mContext = getActivity();
mContentRes = getActivity().getContentResolver();
// Prepare help url and enable menu if necessary
int helpResource = getHelpResource();
if (helpResource != 0) {
mHelpUrl = getResources().getString(helpResource);
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (!TextUtils.isEmpty(mHelpUrl)) {
setHasOptionsMenu(true);
}
}
protected void removePreference(String key) {
Preference pref = findPreference(key);
if (pref != null) {
getPreferenceScreen().removePreference(pref);
}
}
/**
* Override this if you want to show a help item in the menu, by returning the resource id.
* @return the resource id for the help url
*/
protected int getHelpResource() {
return 0;
}
public static boolean isTablet(Context context) {
return Settings.System.getInt(context.getContentResolver(),
Settings.System.CURRENT_UI_MODE,0) == 1;
}
public static boolean isSW600DPScreen(Context context) {
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
int widthPixels = displayMetrics.widthPixels;
float density = displayMetrics.density;
return ((widthPixels / density) >= 600);
}
public void setTitle(int resId) {
getActivity().setTitle(resId);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
if (mHelpUrl != null && getActivity() != null) {
MenuItem helpItem = menu.add(0, MENU_HELP, 0, R.string.help_label);
HelpUtils.prepareHelpMenuItem(getActivity(), helpItem, mHelpUrl);
}
}
/*
* The name is intentionally made different from Activity#finish(), so that
* users won't misunderstand its meaning.
*/
public final void finishFragment() {
getActivity().onBackPressed();
}
// Some helpers for functions used by the settings fragments when they were activities
/**
* Returns the ContentResolver from the owning Activity.
*/
protected ContentResolver getContentResolver() {
return getActivity().getContentResolver();
}
/**
* Returns the specified system service from the owning Activity.
*/
protected Object getSystemService(final String name) {
return getActivity().getSystemService(name);
}
/**
* Returns the PackageManager from the owning Activity.
*/
protected PackageManager getPackageManager() {
return getActivity().getPackageManager();
}
@Override
public void onDetach() {
if (isRemoving()) {
if (mDialogFragment != null) {
mDialogFragment.dismiss();
mDialogFragment = null;
}
}
super.onDetach();
}
// Dialog management
protected void showDialog(int dialogId) {
if (mDialogFragment != null) {
Log.e(TAG, "Old dialog fragment not null!");
}
mDialogFragment = new SettingsDialogFragment(this, dialogId);
mDialogFragment.show(getActivity().getFragmentManager(), Integer.toString(dialogId));
}
public Dialog onCreateDialog(int dialogId) {
return null;
}
protected void removeDialog(int dialogId) {
// mDialogFragment may not be visible yet in parent fragment's onResume().
// To be able to dismiss dialog at that time, don't check
// mDialogFragment.isVisible().
if (mDialogFragment != null && mDialogFragment.getDialogId() == dialogId) {
mDialogFragment.dismiss();
}
mDialogFragment = null;
}
/**
* Sets the OnCancelListener of the dialog shown. This method can only be
* called after showDialog(int) and before removeDialog(int). The method
* does nothing otherwise.
*/
protected void setOnCancelListener(DialogInterface.OnCancelListener listener) {
if (mDialogFragment != null) {
mDialogFragment.mOnCancelListener = listener;
}
}
/**
* Sets the OnDismissListener of the dialog shown. This method can only be
* called after showDialog(int) and before removeDialog(int). The method
* does nothing otherwise.
*/
protected void setOnDismissListener(DialogInterface.OnDismissListener listener) {
if (mDialogFragment != null) {
mDialogFragment.mOnDismissListener = listener;
}
}
public void onDialogShowing() {
// override in subclass to attach a dismiss listener, for instance
}
public static class SettingsDialogFragment extends DialogFragment {
private static final String KEY_DIALOG_ID = "key_dialog_id";
private static final String KEY_PARENT_FRAGMENT_ID = "key_parent_fragment_id";
private int mDialogId;
private Fragment mParentFragment;
private DialogInterface.OnCancelListener mOnCancelListener;
private DialogInterface.OnDismissListener mOnDismissListener;
public SettingsDialogFragment() {
/* do nothing */
}
public SettingsDialogFragment(DialogCreatable fragment, int dialogId) {
mDialogId = dialogId;
if (!(fragment instanceof Fragment)) {
throw new IllegalArgumentException("fragment argument must be an instance of "
+ Fragment.class.getName());
}
mParentFragment = (Fragment) fragment;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mParentFragment != null) {
outState.putInt(KEY_DIALOG_ID, mDialogId);
outState.putInt(KEY_PARENT_FRAGMENT_ID, mParentFragment.getId());
}
}
@Override
public void onStart() {
super.onStart();
if (mParentFragment != null && mParentFragment instanceof SettingsPreferenceFragment) {
((SettingsPreferenceFragment) mParentFragment).onDialogShowing();
}
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
if (savedInstanceState != null) {
mDialogId = savedInstanceState.getInt(KEY_DIALOG_ID, 0);
int mParentFragmentId = savedInstanceState.getInt(KEY_PARENT_FRAGMENT_ID, -1);
if (mParentFragmentId > -1) {
mParentFragment = getFragmentManager().findFragmentById(mParentFragmentId);
if (!(mParentFragment instanceof DialogCreatable)) {
throw new IllegalArgumentException(
KEY_PARENT_FRAGMENT_ID + " must implement "
+ DialogCreatable.class.getName());
}
}
// This dialog fragment could be created from non-SettingsPreferenceFragment
if (mParentFragment instanceof SettingsPreferenceFragment) {
// restore mDialogFragment in mParentFragment
((SettingsPreferenceFragment) mParentFragment).mDialogFragment = this;
}
}
return ((DialogCreatable) mParentFragment).onCreateDialog(mDialogId);
}
@Override
public void onCancel(DialogInterface dialog) {
super.onCancel(dialog);
if (mOnCancelListener != null) {
mOnCancelListener.onCancel(dialog);
}
}
@Override
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
if (mOnDismissListener != null) {
mOnDismissListener.onDismiss(dialog);
}
}
public int getDialogId() {
return mDialogId;
}
@Override
public void onDetach() {
super.onDetach();
// This dialog fragment could be created from non-SettingsPreferenceFragment
if (mParentFragment instanceof SettingsPreferenceFragment) {
// in case the dialog is not explicitly removed by removeDialog()
if (((SettingsPreferenceFragment) mParentFragment).mDialogFragment == this) {
((SettingsPreferenceFragment) mParentFragment).mDialogFragment = null;
}
}
}
}
protected boolean hasNextButton() {
return ((ButtonBarHandler)getActivity()).hasNextButton();
}
protected Button getNextButton() {
return ((ButtonBarHandler)getActivity()).getNextButton();
}
public void finish() {
getActivity().onBackPressed();
}
public boolean startFragment(
Fragment caller, String fragmentClass, int requestCode, Bundle extras) {
if (getActivity() instanceof PreferenceActivity) {
PreferenceActivity preferenceActivity = (PreferenceActivity)getActivity();
preferenceActivity.startPreferencePanel(fragmentClass, extras,
R.string.lock_settings_picker_title, null, caller, requestCode);
return true;
} else {
Log.w(TAG, "Parent isn't PreferenceActivity, thus there's no way to launch the "
+ "given Fragment (name: " + fragmentClass + ", requestCode: " + requestCode
+ ")");
return false;
}
}
}
diff --git a/src/com/android/settings/carbon/Navbar.java b/src/com/android/settings/carbon/Navbar.java
index e3fc02467..122c3cde7 100644
--- a/src/com/android/settings/carbon/Navbar.java
+++ b/src/com/android/settings/carbon/Navbar.java
@@ -1,1023 +1,1017 @@
package com.android.settings.carbon;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.net.URISyntaxException;
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.FragmentTransaction;
import android.app.ListFragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PorterDuff;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.PowerManager;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceGroup;
import android.preference.PreferenceScreen;
import android.provider.MediaStore;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.util.StateSet;
import android.util.TypedValue;
import android.view.IWindowManager;
import android.view.HapticFeedbackConstants;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.internal.util.carbon.AwesomeConstants;
import com.android.internal.util.carbon.AwesomeConstants.AwesomeConstant;
import com.android.internal.util.carbon.BackgroundAlphaColorDrawable;
import com.android.internal.util.carbon.NavBarHelpers;
import com.android.settings.SettingsPreferenceFragment;
import com.android.settings.R;
import com.android.settings.util.Helpers;
import com.android.settings.SettingsActivity;
import com.android.settings.util.ShortcutPickerHelper;
-import com.android.settings.widgets.NavBarItemPreference;
import com.android.settings.widgets.SeekBarPreference;
import com.android.settings.carbon.NavRingTargets;
import net.margaritov.preference.colorpicker.ColorPickerPreference;
public class Navbar extends SettingsPreferenceFragment implements
OnPreferenceChangeListener, ShortcutPickerHelper.OnPickListener {
// move these later
private static final String PREF_MENU_UNLOCK = "pref_menu_display";
private static final String PREF_NAVBAR_MENU_DISPLAY = "navbar_menu_display";
private static final String NAVIGATION_BAR_COLOR = "nav_bar_color";
private static final String PREF_NAV_COLOR = "nav_button_color";
private static final String NAVIGATION_BAR_ALLCOLOR = "navigation_bar_allcolor";
private static final String PREF_NAV_GLOW_COLOR = "nav_button_glow_color";
private static final String PREF_GLOW_TIMES = "glow_times";
private static final String PREF_NAVBAR_QTY = "navbar_qty";
private static final String ENABLE_NAVIGATION_BAR = "enable_nav_bar";
private static final String NAVIGATION_BAR_HEIGHT = "navigation_bar_height";
private static final String NAVIGATION_BAR_HEIGHT_LANDSCAPE = "navigation_bar_height_landscape";
private static final String NAVIGATION_BAR_WIDTH = "navigation_bar_width";
private static final String NAVIGATION_BAR_WIDGETS = "navigation_bar_widgets";
private static final String KEY_HARDWARE_KEYS = "hardware_keys";
private static final String PREF_MENU_ARROWS = "navigation_bar_menu_arrow_keys";
private static final String NAVBAR_HIDE_ENABLE = "navbar_hide_enable";
private static final String NAVBAR_HIDE_TIMEOUT = "navbar_hide_timeout";
private static final String DRAG_HANDLE_OPACITY = "drag_handle_opacity";
private static final String DRAG_HANDLE_WIDTH = "drag_handle_width";
public static final int REQUEST_PICK_CUSTOM_ICON = 200;
public static final int REQUEST_PICK_LANDSCAPE_ICON = 201;
private static final int DIALOG_NAVBAR_ENABLE = 203;
public static final String PREFS_NAV_BAR = "navbar";
// move these later
ColorPickerPreference mNavigationColor;
ColorPickerPreference mNavigationBarColor;
CheckBoxPreference mColorizeAllIcons;
ColorPickerPreference mNavigationBarGlowColor;
ListPreference mGlowTimes;
ListPreference menuDisplayLocation;
ListPreference mNavBarMenuDisplay;
ListPreference mNavBarButtonQty;
CheckBoxPreference mEnableNavigationBar;
ListPreference mNavigationBarHeight;
ListPreference mNavigationBarHeightLandscape;
ListPreference mNavigationBarWidth;
SeekBarPreference mButtonAlpha;
Preference mWidthHelp;
SeekBarPreference mWidthPort;
SeekBarPreference mWidthLand;
CheckBoxPreference mMenuArrowKeysCheckBox;
Preference mConfigureWidgets;
CheckBoxPreference mNavBarHideEnable;
ListPreference mNavBarHideTimeout;
SeekBarPreference mDragHandleOpacity;
SeekBarPreference mDragHandleWidth;
// NavBar Buttons Stuff
Resources mResources;
private ImageView mLeftMenu, mRightMenu;
private ImageButton mResetButton, mAddButton,mSaveButton;
private LinearLayout mNavBarContainer;
private LinearLayout mNavButtonsContainer;
private int mNumberofButtons = 0;
private PackageManager mPackMan;
ArrayList<NavBarButton> mButtons = new ArrayList<NavBarButton>();
ArrayList<ImageButton> mButtonViews = new ArrayList<ImageButton>();
String[] mActions;
String[] mActionCodes;
private int mPendingButton = -1;
public final static int SHOW_LEFT_MENU = 1;
public final static int SHOW_RIGHT_MENU = 0;
public final static int SHOW_BOTH_MENU = 2;
public final static int SHOW_DONT = 4;
public static final float STOCK_ALPHA = .7f;
private ShortcutPickerHelper mPicker;
private static final String TAG = "Navbar";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(R.string.title_navbar);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.navbar_settings);
PreferenceScreen prefs = getPreferenceScreen();
mPicker = new ShortcutPickerHelper(this, this);
mPackMan = getPackageManager();
mResources = mContext.getResources();
// Get NavBar Actions
mActionCodes = NavBarHelpers.getNavBarActions();
mActions = new String[mActionCodes.length];
int actionqty = mActions.length;
for (int i = 0; i < actionqty; i++) {
mActions[i] = AwesomeConstants.getProperName(mContext, mActionCodes[i]);
}
menuDisplayLocation = (ListPreference) findPreference(PREF_MENU_UNLOCK);
menuDisplayLocation.setOnPreferenceChangeListener(this);
menuDisplayLocation.setValue(Settings.System.getInt(mContentRes,
Settings.System.MENU_LOCATION,0) + "");
mNavBarMenuDisplay = (ListPreference) findPreference(PREF_NAVBAR_MENU_DISPLAY);
mNavBarMenuDisplay.setOnPreferenceChangeListener(this);
mNavBarMenuDisplay.setValue(Settings.System.getInt(mContentRes,
Settings.System.MENU_VISIBILITY,0) + "");
mNavBarHideEnable = (CheckBoxPreference) findPreference(NAVBAR_HIDE_ENABLE);
mNavBarHideEnable.setChecked(Settings.System.getBoolean(mContentRes,
Settings.System.NAV_HIDE_ENABLE, false));
final int defaultDragOpacity = Settings.System.getInt(mContentRes,
Settings.System.DRAG_HANDLE_OPACITY,50);
mDragHandleOpacity = (SeekBarPreference) findPreference(DRAG_HANDLE_OPACITY);
mDragHandleOpacity.setInitValue((int) (defaultDragOpacity));
mDragHandleOpacity.setOnPreferenceChangeListener(this);
final int defaultDragWidth = Settings.System.getInt(mContentRes,
Settings.System.DRAG_HANDLE_WEIGHT, 5);
mDragHandleWidth = (SeekBarPreference) findPreference(DRAG_HANDLE_WIDTH);
mDragHandleWidth.setInitValue((int) (defaultDragWidth));
mDragHandleWidth.setOnPreferenceChangeListener(this);
mNavBarHideTimeout = (ListPreference) findPreference(NAVBAR_HIDE_TIMEOUT);
mNavBarHideTimeout.setOnPreferenceChangeListener(this);
mNavBarHideTimeout.setValue(Settings.System.getInt(mContentRes,
Settings.System.NAV_HIDE_TIMEOUT, 3000) + "");
boolean hasNavBarByDefault = mContext.getResources().getBoolean(
com.android.internal.R.bool.config_showNavigationBar);
mEnableNavigationBar = (CheckBoxPreference) findPreference(ENABLE_NAVIGATION_BAR);
mEnableNavigationBar.setChecked(Settings.System.getBoolean(mContentRes,
Settings.System.NAVIGATION_BAR_SHOW, hasNavBarByDefault));
mNavigationColor = (ColorPickerPreference) findPreference(NAVIGATION_BAR_COLOR);
mNavigationColor.setOnPreferenceChangeListener(this);
mNavigationBarColor = (ColorPickerPreference) findPreference(PREF_NAV_COLOR);
mNavigationBarColor.setOnPreferenceChangeListener(this);
mColorizeAllIcons = (CheckBoxPreference) findPreference("navigation_bar_allcolor");
mColorizeAllIcons.setChecked(Settings.System.getBoolean(mContentRes,
Settings.System.NAVIGATION_BAR_ALLCOLOR, false));
mNavigationBarGlowColor = (ColorPickerPreference) findPreference(PREF_NAV_GLOW_COLOR);
mNavigationBarGlowColor.setOnPreferenceChangeListener(this);
mGlowTimes = (ListPreference) findPreference(PREF_GLOW_TIMES);
mGlowTimes.setOnPreferenceChangeListener(this);
final float defaultButtonAlpha = Settings.System.getFloat(mContentRes,
Settings.System.NAVIGATION_BAR_BUTTON_ALPHA,0.6f);
mButtonAlpha = (SeekBarPreference) findPreference("button_transparency");
mButtonAlpha.setInitValue((int) (defaultButtonAlpha * 100));
mButtonAlpha.setOnPreferenceChangeListener(this);
mWidthHelp = (Preference) findPreference("width_help");
float defaultPort = Settings.System.getFloat(mContentRes,
Settings.System.NAVIGATION_BAR_WIDTH_PORT,0f);
mWidthPort = (SeekBarPreference) findPreference("width_port");
mWidthPort.setInitValue((int) (defaultPort * 2.5f));
mWidthPort.setOnPreferenceChangeListener(this);
float defaultLand = Settings.System.getFloat(mContentRes,
Settings.System.NAVIGATION_BAR_WIDTH_LAND,0f);
mWidthLand = (SeekBarPreference) findPreference("width_land");
mWidthLand.setInitValue((int) (defaultLand * 2.5f));
mWidthLand.setOnPreferenceChangeListener(this);
mNavigationBarHeight = (ListPreference) findPreference("navigation_bar_height");
mNavigationBarHeight.setOnPreferenceChangeListener(this);
mNavigationBarHeightLandscape = (ListPreference) findPreference("navigation_bar_height_landscape");
mNavigationBarHeightLandscape.setOnPreferenceChangeListener(this);
mNavigationBarWidth = (ListPreference) findPreference("navigation_bar_width");
mNavigationBarWidth.setOnPreferenceChangeListener(this);
mConfigureWidgets = findPreference(NAVIGATION_BAR_WIDGETS);
mMenuArrowKeysCheckBox = (CheckBoxPreference) findPreference(PREF_MENU_ARROWS);
mMenuArrowKeysCheckBox.setChecked(Settings.System.getBoolean(mContentRes,
Settings.System.NAVIGATION_BAR_MENU_ARROW_KEYS, true));
// don't allow devices that must use a navigation bar to disable it
if (hasNavBarByDefault) {
prefs.removePreference(mEnableNavigationBar);
}
PreferenceGroup pg = (PreferenceGroup) prefs.findPreference("advanced_cat");
if (isTablet(mContext)) { // Tablets don't set NavBar Height
pg.removePreference(mNavigationBarHeight);
pg.removePreference(mNavigationBarHeightLandscape);
pg.removePreference(mNavigationBarWidth);
} else { // Phones&Phablets don't have SystemBar
pg.removePreference(mWidthPort);
pg.removePreference(mWidthLand);
pg.removePreference(mWidthHelp);
- if (isPhablet(mContext)) { // Phablets don't have NavBar onside
- pg.removePreference(mNavigationBarWidth);
- } else {
- pg.removePreference(mNavigationBarHeightLandscape);
- }
}
// Only show the hardware keys config on a device that does not have a navbar
IWindowManager windowManager = IWindowManager.Stub.asInterface(
ServiceManager.getService(Context.WINDOW_SERVICE));
if (hasNavBarByDefault) {
// Let's assume they don't have hardware keys
getPreferenceScreen().removePreference(findPreference(KEY_HARDWARE_KEYS));
}
refreshSettings();
setHasOptionsMenu(true);
updateGlowTimesSummary();
}
@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedinstanceState){
View ll = inflater.inflate(R.layout.navbar, container, false);
mResetButton = (ImageButton) ll.findViewById(R.id.reset_button);
mResetButton.setOnClickListener(mCommandButtons);
mAddButton = (ImageButton) ll.findViewById(R.id.add_button);
mAddButton.setOnClickListener(mCommandButtons);
mSaveButton = (ImageButton) ll.findViewById(R.id.save_button);
mSaveButton.setOnClickListener(mCommandButtons);
mLeftMenu = (ImageView) ll.findViewById(R.id.left_menu);
mNavBarContainer = (LinearLayout) ll.findViewById(R.id.navbar_container);
mNavButtonsContainer = (LinearLayout) ll.findViewById(R.id.button_container);
mButtonViews.clear();
for (int i = 0; i < mNavButtonsContainer.getChildCount(); i++) {
ImageButton ib = (ImageButton) mNavButtonsContainer.getChildAt(i);
mButtonViews.add(ib);
}
mRightMenu = (ImageView) ll.findViewById(R.id.right_menu);
if (mButtons.size() == 0){
loadButtons();
}
refreshButtons();
return ll;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.nav_bar, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.reset:
Settings.System.putInt(mContentRes,
Settings.System.NAVIGATION_BAR_COLOR, -1);
Settings.System.putInt(mContentRes,
Settings.System.NAVIGATION_BAR_TINT, -1);
Settings.System.putInt(mContentRes,
Settings.System.NAVIGATION_BAR_GLOW_TINT, -1);
Settings.System.putInt(mContentRes,
Settings.System.NAVIGATION_BAR_BUTTONS_QTY, 3);
Settings.System.putString(mContentRes,
Settings.System.NAVIGATION_CUSTOM_ACTIVITIES[0], "**back**");
Settings.System.putString(mContentRes,
Settings.System.NAVIGATION_CUSTOM_ACTIVITIES[1], "**home**");
Settings.System.putString(mContentRes,
Settings.System.NAVIGATION_CUSTOM_ACTIVITIES[2], "**recents**");
Settings.System.putString(mContentRes,
Settings.System.NAVIGATION_LONGPRESS_ACTIVITIES[0], "**null**");
Settings.System.putString(mContentRes,
Settings.System.NAVIGATION_LONGPRESS_ACTIVITIES[1], "**null**");
Settings.System.putString(mContentRes,
Settings.System.NAVIGATION_LONGPRESS_ACTIVITIES[2], "**null**");
Settings.System.putString(mContentRes,
Settings.System.NAVIGATION_CUSTOM_APP_ICONS[0], "");
Settings.System.putString(mContentRes,
Settings.System.NAVIGATION_CUSTOM_APP_ICONS[1], "");
Settings.System.putString(mContentRes,
Settings.System.NAVIGATION_CUSTOM_APP_ICONS[2], "");
refreshSettings();
return true;
default:
return super.onContextItemSelected(item);
}
}
@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen,
Preference preference) {
if (preference == mEnableNavigationBar) {
Settings.System.putInt(mContentRes,
Settings.System.NAVIGATION_BAR_SHOW,
((CheckBoxPreference) preference).isChecked() ? 1 : 0);
Helpers.restartSystemUI();
return true;
} else if (preference == mColorizeAllIcons) {
Settings.System.putBoolean(mContentRes,
Settings.System.NAVIGATION_BAR_ALLCOLOR,
((CheckBoxPreference) preference).isChecked() ? true : false);
return true;
} else if (preference == mNavBarHideEnable) {
Settings.System.putBoolean(mContentRes,
Settings.System.NAV_HIDE_ENABLE,
((CheckBoxPreference) preference).isChecked());
mDragHandleOpacity.setInitValue(Settings.System.getInt(getActivity().getContentResolver(),
Settings.System.DRAG_HANDLE_OPACITY,50));
mDragHandleWidth.setInitValue(Settings.System.getInt(getActivity().getContentResolver(),
Settings.System.DRAG_HANDLE_WEIGHT,5));
mNavBarHideTimeout.setValue(Settings.System.getInt(getActivity().getContentResolver(),
Settings.System.NAV_HIDE_TIMEOUT, 3000) + "");
refreshSettings();
return true;
} else if (preference == mConfigureWidgets) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
WidgetConfigurationFragment fragment = new WidgetConfigurationFragment();
ft.addToBackStack("config_widgets");
ft.replace(this.getId(), fragment);
ft.commit();
return true;
} else if (preference == mMenuArrowKeysCheckBox) {
Settings.System.putBoolean(mContentRes,
Settings.System.NAVIGATION_BAR_MENU_ARROW_KEYS,
((CheckBoxPreference) preference).isChecked());
return true;
}
return super.onPreferenceTreeClick(preferenceScreen, preference);
}
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (preference == menuDisplayLocation) {
Settings.System.putInt(mContentRes,
Settings.System.MENU_LOCATION, Integer.parseInt((String) newValue));
refreshSettings();
return true;
} else if (preference == mNavBarMenuDisplay) {
Settings.System.putInt(mContentRes,
Settings.System.MENU_VISIBILITY, Integer.parseInt((String) newValue));
return true;
} else if (preference == mNavigationBarWidth) {
String newVal = (String) newValue;
int dp = Integer.parseInt(newVal);
int width = mapChosenDpToPixels(dp);
Settings.System.putInt(mContentRes, Settings.System.NAVIGATION_BAR_WIDTH,
width);
return true;
} else if (preference == mNavigationBarHeight) {
String newVal = (String) newValue;
int dp = Integer.parseInt(newVal);
int height = mapChosenDpToPixels(dp);
Settings.System.putInt(mContentRes, Settings.System.NAVIGATION_BAR_HEIGHT,
height);
return true;
} else if (preference == mNavBarHideTimeout) {
int val = Integer.parseInt((String) newValue);
Settings.System.putInt(mContentRes,
Settings.System.NAV_HIDE_TIMEOUT, val);
return true;
} else if (preference == mNavigationBarHeightLandscape) {
String newVal = (String) newValue;
int dp = Integer.parseInt(newVal);
int height = mapChosenDpToPixels(dp);
Settings.System.putInt(mContentRes,
Settings.System.NAVIGATION_BAR_HEIGHT_LANDSCAPE,
height);
return true;
} else if (preference == mNavigationColor) {
String hex = ColorPickerPreference.convertToARGB(
Integer.valueOf(String.valueOf(newValue)));
preference.setSummary(hex);
int intHex = ColorPickerPreference.convertToColorInt(hex) & 0x00FFFFFF;
Settings.System.putInt(mContentRes,
Settings.System.NAVIGATION_BAR_COLOR, intHex);
refreshSettings();
return true;
} else if (preference == mNavigationBarColor) {
String hex = ColorPickerPreference.convertToARGB(
Integer.valueOf(String.valueOf(newValue)));
preference.setSummary(hex);
int intHex = ColorPickerPreference.convertToColorInt(hex);
Settings.System.putInt(mContentRes,
Settings.System.NAVIGATION_BAR_TINT, intHex);
refreshSettings();
return true;
} else if (preference == mNavigationBarGlowColor) {
String hex = ColorPickerPreference.convertToARGB(
Integer.valueOf(String.valueOf(newValue)));
preference.setSummary(hex);
int intHex = ColorPickerPreference.convertToColorInt(hex);
Settings.System.putInt(mContentRes,
Settings.System.NAVIGATION_BAR_GLOW_TINT, intHex);
refreshSettings();
return true;
} else if (preference == mGlowTimes) {
// format is (on|off) both in MS
String value = (String) newValue;
String[] breakIndex = value.split("\\|");
int onTime = Integer.valueOf(breakIndex[0]);
int offTime = Integer.valueOf(breakIndex[1]);
Settings.System.putInt(mContentRes,
Settings.System.NAVIGATION_BAR_GLOW_DURATION[0], offTime);
Settings.System.putInt(mContentRes,
Settings.System.NAVIGATION_BAR_GLOW_DURATION[1], onTime);
updateGlowTimesSummary();
return true;
} else if (preference == mButtonAlpha) {
float val = Float.parseFloat((String) newValue);
Settings.System.putFloat(mContentRes,
Settings.System.NAVIGATION_BAR_BUTTON_ALPHA,
val * 0.01f);
refreshSettings();
return true;
} else if (preference == mDragHandleOpacity) {
String newVal = (String) newValue;
int op = Integer.parseInt(newVal);
Settings.System.putInt(mContentRes,
Settings.System.DRAG_HANDLE_OPACITY, op);
return true;
} else if (preference == mDragHandleWidth) {
String newVal = (String) newValue;
int dp = Integer.parseInt(newVal);
//int height = mapChosenDpToPixels(dp);
Settings.System.putInt(mContentRes,
Settings.System.DRAG_HANDLE_WEIGHT, dp);
return true;
} else if (preference == mWidthPort) {
float val = Float.parseFloat((String) newValue);
Settings.System.putFloat(mContentRes,
Settings.System.NAVIGATION_BAR_WIDTH_PORT,
val * 0.4f);
return true;
} else if (preference == mWidthLand) {
float val = Float.parseFloat((String) newValue);
Settings.System.putFloat(mContentRes,
Settings.System.NAVIGATION_BAR_WIDTH_LAND,
val * 0.4f);
return true;
}
return false;
}
@Override
public Dialog onCreateDialog(int dialogId) {
return null;
}
private void updateGlowTimesSummary() {
int resId;
String combinedTime = Settings.System.getString(mContentRes,
Settings.System.NAVIGATION_BAR_GLOW_DURATION[1]) + "|" +
Settings.System.getString(mContentRes,
Settings.System.NAVIGATION_BAR_GLOW_DURATION[0]);
String[] glowArray = getResources().getStringArray(R.array.glow_times_values);
if (glowArray[0].equals(combinedTime)) {
resId = R.string.glow_times_off;
mGlowTimes.setValueIndex(0);
} else if (glowArray[1].equals(combinedTime)) {
resId = R.string.glow_times_superquick;
mGlowTimes.setValueIndex(1);
} else if (glowArray[2].equals(combinedTime)) {
resId = R.string.glow_times_quick;
mGlowTimes.setValueIndex(2);
} else {
resId = R.string.glow_times_normal;
mGlowTimes.setValueIndex(3);
}
mGlowTimes.setSummary(getResources().getString(resId));
}
public int mapChosenDpToPixels(int dp) {
switch (dp) {
case 48:
return getResources().getDimensionPixelSize(R.dimen.navigation_bar_48);
case 44:
return getResources().getDimensionPixelSize(R.dimen.navigation_bar_44);
case 42:
return getResources().getDimensionPixelSize(R.dimen.navigation_bar_42);
case 40:
return getResources().getDimensionPixelSize(R.dimen.navigation_bar_40);
case 36:
return getResources().getDimensionPixelSize(R.dimen.navigation_bar_36);
case 30:
return getResources().getDimensionPixelSize(R.dimen.navigation_bar_30);
case 24:
return getResources().getDimensionPixelSize(R.dimen.navigation_bar_24);
}
return -1;
}
public void refreshSettings() {
refreshButtons();
mDragHandleOpacity.setEnabled(mNavBarHideEnable.isChecked());
mDragHandleWidth.setEnabled(mNavBarHideEnable.isChecked());
mNavBarHideTimeout.setEnabled(mNavBarHideEnable.isChecked());
}
private Uri getTempFileUri() {
return Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
"tmp_icon_" + mPendingButton + ".png"));
}
private String getIconFileName(int index) {
return "navbar_icon_" + index + ".png";
}
@Override
public void onResume() {
super.onResume();
}
private View.OnClickListener mNavBarClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
mPendingButton = mButtonViews.indexOf(v);
if (mPendingButton > -1 && mPendingButton < mNumberofButtons) {
createDialog(mButtons.get(mPendingButton));
}
}
};
private void loadButtons(){
mNumberofButtons = Settings.System.getInt(mContentRes,
Settings.System.NAVIGATION_BAR_BUTTONS_QTY, 3);
mButtons.clear();
for (int i = 0; i < mNumberofButtons; i++) {
String click = Settings.System.getString(mContentRes,
Settings.System.NAVIGATION_CUSTOM_ACTIVITIES[i]);
String longclick = Settings.System.getString(mContentRes,
Settings.System.NAVIGATION_LONGPRESS_ACTIVITIES[i]);
String iconuri = Settings.System.getString(mContentRes,
Settings.System.NAVIGATION_CUSTOM_APP_ICONS[i]);
mButtons.add(new NavBarButton(click, longclick, iconuri));
}
}
public void refreshButtons() {
if (mNumberofButtons == 0) {
return;
}
int navBarColor = Settings.System.getInt(mContentRes,
Settings.System.NAVIGATION_BAR_COLOR, -1);
int navButtonColor = Settings.System.getInt(mContentRes,
Settings.System.NAVIGATION_BAR_TINT, -1);
float navButtonAlpha = Settings.System.getFloat(mContentRes,
Settings.System.NAVIGATION_BAR_BUTTON_ALPHA, STOCK_ALPHA);
int glowColor = Settings.System.getInt(mContentRes,
Settings.System.NAVIGATION_BAR_GLOW_TINT, 0);
float BarAlpha = 1.0f;
String alphas[];
String settingValue = Settings.System.getString(mContentRes,
Settings.System.NAVIGATION_BAR_ALPHA_CONFIG);
if (!TextUtils.isEmpty(settingValue)) {
alphas = settingValue.split(";");
BarAlpha = Float.parseFloat(alphas[0]) / 255;
}
int a = Math.round(BarAlpha * 255);
Drawable mBackground = AwesomeConstants.getSystemUIDrawable(mContext, "com.android.systemui:drawable/nav_bar_bg");
if (mBackground instanceof ColorDrawable) {
BackgroundAlphaColorDrawable bacd = new BackgroundAlphaColorDrawable(
navBarColor > 0 ? navBarColor : ((ColorDrawable) mBackground).getColor());
bacd.setAlpha(a);
mNavBarContainer.setBackground(bacd);
} else {
mBackground.setAlpha(a);
mNavBarContainer.setBackground(mBackground);
}
for (int i = 0; i < mNumberofButtons; i++) {
ImageButton ib = mButtonViews.get(i);
Drawable d = mButtons.get(i).getIcon();
if (navButtonColor != -1) {
d.setColorFilter(navButtonColor, PorterDuff.Mode.SRC_ATOP);
}
ib.setImageDrawable(d);
ib.setOnClickListener(mNavBarClickListener);
ib.setVisibility(View.VISIBLE);
ib.setAlpha(navButtonAlpha);
StateListDrawable sld = new StateListDrawable();
sld.addState(new int[] { android.R.attr.state_pressed }, new ColorDrawable(glowColor));
sld.addState(StateSet.WILD_CARD, mNavBarContainer.getBackground());
ib.setBackground(sld);
}
for (int i = mNumberofButtons; i < mButtonViews.size(); i++){
ImageButton ib = mButtonViews.get(i);
ib.setVisibility(View.GONE);
}
int menuloc = Settings.System.getInt(mContentRes,
Settings.System.MENU_LOCATION, 0);
switch (menuloc) {
case SHOW_BOTH_MENU:
mLeftMenu.setVisibility(View.VISIBLE);
mRightMenu.setVisibility(View.VISIBLE);
break;
case SHOW_LEFT_MENU:
mLeftMenu.setVisibility(View.VISIBLE);
mRightMenu.setVisibility(View.INVISIBLE);
break;
case SHOW_RIGHT_MENU:
mLeftMenu.setVisibility(View.INVISIBLE);
mRightMenu.setVisibility(View.VISIBLE);
break;
case SHOW_DONT:
mLeftMenu.setVisibility(View.GONE);
mRightMenu.setVisibility(View.GONE);
break;
}
if (navButtonColor != -1) {
mLeftMenu.setColorFilter(navButtonColor);
mRightMenu.setColorFilter(navButtonColor);
}
}
private void saveButtons(){
Settings.System.putInt(mContentRes,Settings.System.NAVIGATION_BAR_BUTTONS_QTY,
mNumberofButtons);
for (int i = 0; i < mNumberofButtons; i++) {
NavBarButton button = mButtons.get(i);
Settings.System.putString(mContentRes, Settings.System.NAVIGATION_CUSTOM_ACTIVITIES[i],
button.getClickAction());
Settings.System.putString(mContentRes, Settings.System.NAVIGATION_LONGPRESS_ACTIVITIES[i],
button.getLongAction());
Settings.System.putString(mContentRes, Settings.System.NAVIGATION_CUSTOM_APP_ICONS[i],
button.getIconURI());
}
}
private void createDialog(final NavBarButton button) {
final DialogInterface.OnClickListener l = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
onDialogClick(button, item);
dialog.dismiss();
}
};
String action = mResources.getString(R.string.navbar_actiontitle_menu);
action = String.format(action, button.getClickName());
String longpress = mResources.getString(R.string.navbar_longpress_menu);
longpress = String.format(longpress, button.getLongName());
String[] items = {action,longpress,
mResources.getString(R.string.navbar_icon_menu),
mResources.getString(R.string.navbar_delete_menu)};
final AlertDialog dialog = new AlertDialog.Builder(mContext)
.setTitle(mResources.getString(R.string.navbar_title_menu))
.setSingleChoiceItems(items, -1, l)
.create();
dialog.show();
}
private void createActionDialog(final NavBarButton button) {
final DialogInterface.OnClickListener l = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
onActionDialogClick(button, item);
dialog.dismiss();
}
};
final AlertDialog dialog = new AlertDialog.Builder(mContext)
.setTitle(mResources.getString(R.string.navbar_title_menu))
.setSingleChoiceItems(mActions, -1, l)
.create();
dialog.show();
}
private void onDialogClick(NavBarButton button, int command){
switch (command) {
case 0: // Set Click Action
button.setPickLongPress(false);
createActionDialog(button);
break;
case 1: // Set Long Press Action
button.setPickLongPress(true);
createActionDialog(button);
break;
case 2: // set Custom Icon
int width = 100;
int height = width;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
intent.setType("image/*");
intent.putExtra("crop", "true");
intent.putExtra("aspectX", width);
intent.putExtra("aspectY", height);
intent.putExtra("outputX", width);
intent.putExtra("outputY", height);
intent.putExtra("scale", true);
intent.putExtra(MediaStore.EXTRA_OUTPUT, getTempFileUri());
intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
Log.i(TAG, "started for result, should output to: " + getTempFileUri());
startActivityForResult(intent,REQUEST_PICK_CUSTOM_ICON);
break;
case 3: // Delete Button
mButtons.remove(mPendingButton);
mNumberofButtons--;
break;
}
refreshButtons();
}
private void onActionDialogClick(NavBarButton button, int command){
if (command == mActions.length -1) {
// This is the last action - should be **app**
mPicker.pickShortcut();
} else { // This should be any other defined action.
if (button.getPickLongPress()) {
button.setLongPress(AwesomeConstants.AwesomeActions()[command]);
} else {
button.setClickAction(AwesomeConstants.AwesomeActions()[command]);
}
}
refreshButtons();
}
private View.OnClickListener mCommandButtons = new View.OnClickListener() {
@Override
public void onClick(View v) {
int command = v.getId();
switch (command) {
case R.id.reset_button:
loadButtons();
break;
case R.id.add_button:
if (mNumberofButtons < 7) { // Maximum buttons is 7
mButtons.add(new NavBarButton("**null**","**null**",""));
mNumberofButtons++;
}
break;
case R.id.save_button:
saveButtons();
break;
}
refreshButtons();
}
};
private Drawable setIcon(String uri, String action) {
if (uri != null && uri.length() > 0) {
File f = new File(Uri.parse(uri).getPath());
if (f.exists())
return resize(new BitmapDrawable(mResources, f.getAbsolutePath()));
}
if (uri != null && !uri.equals("")
&& uri.startsWith("file")) {
// it's an icon the user chose from the gallery here
File icon = new File(Uri.parse(uri).getPath());
if (icon.exists())
return resize(new BitmapDrawable(mResources, icon
.getAbsolutePath()));
} else if (uri != null && !uri.equals("")) {
// here they chose another app icon
try {
return resize(mPackMan.getActivityIcon(Intent.parseUri(uri, 0)));
} catch (NameNotFoundException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
// ok use default icons here
}
return resize(getNavbarIconImage(action));
}
private Drawable getNavbarIconImage(String uri) {
if (uri == null)
uri = AwesomeConstant.ACTION_NULL.value();
if (uri.startsWith("**")) {
return AwesomeConstants.getActionIcon(mContext, uri);
} else {
try {
return mPackMan.getActivityIcon(Intent.parseUri(uri, 0));
} catch (NameNotFoundException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
return mResources.getDrawable(R.drawable.ic_sysbar_null);
}
@Override
public void shortcutPicked(String uri, String friendlyName, Bitmap bmp, boolean isApplication) {
NavBarButton button = mButtons.get(mPendingButton);
boolean longpress = button.getPickLongPress();
if (!longpress) {
button.setClickAction(uri);
if (bmp == null) {
button.setIconURI("");
} else {
String iconName = getIconFileName(mPendingButton);
FileOutputStream iconStream = null;
try {
iconStream = mContext.openFileOutput(iconName, Context.MODE_WORLD_READABLE);
} catch (FileNotFoundException e) {
return; // NOOOOO
}
bmp.compress(Bitmap.CompressFormat.PNG, 100, iconStream);
button.setIconURI(Uri.fromFile(mContext.getFileStreamPath(iconName)).toString());
}
} else {
button.setLongPress(uri);
}
refreshButtons();
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i(TAG, "RequestCode:"+resultCode);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == ShortcutPickerHelper.REQUEST_PICK_SHORTCUT
|| requestCode == ShortcutPickerHelper.REQUEST_PICK_APPLICATION
|| requestCode == ShortcutPickerHelper.REQUEST_CREATE_SHORTCUT) {
mPicker.onActivityResult(requestCode, resultCode, data);
} else if (requestCode == REQUEST_PICK_CUSTOM_ICON) {
String iconName = getIconFileName(mPendingButton);
FileOutputStream iconStream = null;
try {
iconStream = mContext.openFileOutput(iconName, Context.MODE_WORLD_READABLE);
} catch (FileNotFoundException e) {
return; // NOOOOO
}
Uri selectedImageUri = getTempFileUri();
try {
Log.e(TAG, "Selected image path: " + selectedImageUri.getPath());
Bitmap bitmap = BitmapFactory.decodeFile(selectedImageUri.getPath());
bitmap.compress(Bitmap.CompressFormat.PNG, 100, iconStream);
} catch (NullPointerException npe) {
Log.e(TAG, "SeletedImageUri was null.");
return;
}
mButtons.get(mPendingButton).setIconURI(Uri.fromFile(
new File(mContext.getFilesDir(), iconName)).getPath());
File f = new File(selectedImageUri.getPath());
if (f.exists())
f.delete();
refreshButtons();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private String getProperSummary(String uri) {
if (uri == null)
return AwesomeConstants.getProperName(mContext, "**null**");
if (uri.startsWith("**")) {
return AwesomeConstants.getProperName(mContext, uri);
} else {
return mPicker.getFriendlyNameForUri(uri);
}
}
private Drawable resize(Drawable image) {
int size = 50;
int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, size,
mResources.getDisplayMetrics());
Bitmap d = ((BitmapDrawable) image).getBitmap();
if (d == null) {
return mResources.getDrawable(R.drawable.ic_sysbar_null);
} else {
Bitmap bitmapOrig = Bitmap.createScaledBitmap(d, px, px, false);
return new BitmapDrawable(mResources, bitmapOrig);
}
}
public class NavBarButton {
String mClickAction;
String mLongPressAction;
String mIconURI;
String mClickFriendlyName;
String mLongPressFriendlyName;
Drawable mIcon;
boolean mPickingLongPress;
public NavBarButton(String clickaction, String longpress, String iconuri ) {
mClickAction = clickaction;
mLongPressAction = longpress;
mIconURI = iconuri;
mClickFriendlyName = getProperSummary(mClickAction);
mLongPressFriendlyName = getProperSummary (mLongPressAction);
mIcon = setIcon(mIconURI,mClickAction);
}
public void setClickAction(String click) {
mClickAction = click;
mClickFriendlyName = getProperSummary(mClickAction);
// ClickAction was reset - so we should default to stock Icon for now
mIconURI = "";
mIcon = setIcon(mIconURI,mClickAction);
}
public void setLongPress(String action) {
mLongPressAction = action;
mLongPressFriendlyName = getProperSummary (mLongPressAction);
}
public void setPickLongPress(boolean pick) {
mPickingLongPress = pick;
}
public boolean getPickLongPress() {
return mPickingLongPress;
}
public void setIconURI (String uri) {
mIconURI = uri;
mIcon = setIcon(mIconURI,mClickAction);
}
public String getClickName() {
return mClickFriendlyName;
}
public String getLongName() {
return mLongPressFriendlyName;
}
public Drawable getIcon() {
return mIcon;
}
public String getClickAction() {
return mClickAction;
}
public String getLongAction() {
return mLongPressAction;
}
public String getIconURI() {
return mIconURI;
}
}
}
| false | false | null | null |
diff --git a/src/com/smarthome/LightGesture.java b/src/com/smarthome/LightGesture.java
index e4779e0..12b2f70 100644
--- a/src/com/smarthome/LightGesture.java
+++ b/src/com/smarthome/LightGesture.java
@@ -1,19 +1,19 @@
package com.smarthome;
public class LightGesture extends Gesture {
private boolean on = false;
private String action;
public LightGesture() {}
public LightGesture(float x1, float y1, float x2, float y2, String action) {
super(x1, y1, x2, y2);
this.action = action;
}
public void click(SmartHomeActivity activity) {
System.out.println("Light "+(on ? "on" : "off"));
on = !on;
sendMessageToProxy send = new sendMessageToProxy();
- send.doInBackground("172.16.0.200", "12349", "LP.LIGHTCONTROL", "topic", JSONBuilder.light(action, on ? 255 : 0, on ? 255 : 0, on ? 255 : 0, 0));
+ send.execute("172.16.0.200", "12349", "LP.LIGHTCONTROL", "topic", JSONBuilder.light(action, on ? 255 : 0, on ? 255 : 0, on ? 255 : 0, 0));
}
}
diff --git a/src/com/smarthome/sendMessageToProxy.java b/src/com/smarthome/sendMessageToProxy.java
index 7d11ce0..545cba5 100644
--- a/src/com/smarthome/sendMessageToProxy.java
+++ b/src/com/smarthome/sendMessageToProxy.java
@@ -1,29 +1,30 @@
package com.smarthome;
import java.io.IOException;
import android.os.AsyncTask;
import android.util.Log;
-public class sendMessageToProxy extends AsyncTask {
+public class sendMessageToProxy extends AsyncTask<String, Void, String> {
// params [0] Server; [1] Port; [2] TopicName; [3] topic/queue;
// [4] message;
@Override
- protected Object doInBackground(Object... params) {
+ protected String doInBackground(String... params) {
try {
- AndroidPublisher publisher = new AndroidPublisher((String)params[0],
- Integer.valueOf((String)params[1]), (String)params[2]);
- publisher.setMessage((String)params[4]);
+ AndroidPublisher publisher = new AndroidPublisher(params[0],
+ Integer.valueOf(params[1]), params[2]);
+ publisher.setMessage(params[4]);
if (params[3].equals("topic")) {
publisher.publishToTopic();
} else {
publisher.publishToQueue();
}
} catch (IOException e) {
Log.e("Publisher", "Can't publish the message");
}
return null;
}
+
}
| false | false | null | null |
diff --git a/src/com/orangeleap/tangerine/web/common/TangerineListHelper.java b/src/com/orangeleap/tangerine/web/common/TangerineListHelper.java
index b0219dbd..d95ee447 100644
--- a/src/com/orangeleap/tangerine/web/common/TangerineListHelper.java
+++ b/src/com/orangeleap/tangerine/web/common/TangerineListHelper.java
@@ -1,144 +1,151 @@
/*
* Copyright (c) 2009. Orange Leap Inc. Active Constituent
* Relationship Management Platform.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.orangeleap.tangerine.web.common;
import com.orangeleap.tangerine.controller.TangerineForm;
import com.orangeleap.tangerine.domain.customization.CustomField;
import com.orangeleap.tangerine.domain.customization.SectionField;
import com.orangeleap.tangerine.service.customization.PageCustomizationService;
import com.orangeleap.tangerine.type.AccessType;
import com.orangeleap.tangerine.type.PageType;
import com.orangeleap.tangerine.util.HttpUtil;
import com.orangeleap.tangerine.util.StringConstants;
import com.orangeleap.tangerine.util.TangerineUserHelper;
import com.orangeleap.tangerine.web.customization.tag.fields.handlers.ExtTypeHandler;
import com.orangeleap.tangerine.web.customization.tag.fields.handlers.FieldHandler;
import com.orangeleap.tangerine.web.customization.tag.fields.handlers.FieldHandlerHelper;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.PropertyAccessorFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.util.WebUtils;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@Component("tangerineListHelper")
public class TangerineListHelper {
@Resource(name = "pageCustomizationService")
protected PageCustomizationService pageCustomizationService;
@Resource(name = "fieldHandlerHelper")
protected FieldHandlerHelper fieldHandlerHelper;
@Resource(name = "tangerineUserHelper")
protected TangerineUserHelper tangerineUserHelper;
public static final String SORT_KEY_PREFIX = "a";
@SuppressWarnings("unchecked")
// TODO: move to annotation
public boolean isAccessAllowed(HttpServletRequest request, PageType pageType) {
Map<String, AccessType> pageAccess = (Map<String, AccessType>) WebUtils.getSessionAttribute(request, "pageAccess");
return pageAccess.get(pageType.getPageName()) == AccessType.ALLOWED;
}
// TODO: move to annotation
public void checkAccess(HttpServletRequest request, PageType pageType) {
if ( ! isAccessAllowed(request, pageType)) {
throw new RuntimeException("You are not authorized to access this page");
}
}
public void addListFieldsToMap(HttpServletRequest request, List<SectionField> sectionFields, List entities,
List<Map<String, Object>> paramMapList, boolean useAliasName, boolean useAliasId) {
int sequence = 0;
if (entities != null) {
for (Object thisEntity : entities) {
BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(thisEntity);
/**
* If useAliasId == true, set the aliasId to the ID and reset to ID to the next sequence number
*/
if (useAliasId && beanWrapper.isWritableProperty(StringConstants.ALIAS_ID) && beanWrapper.isReadableProperty(StringConstants.ID)) {
beanWrapper.setPropertyValue(StringConstants.ALIAS_ID, beanWrapper.getPropertyValue(StringConstants.ID));
beanWrapper.setPropertyValue(StringConstants.ID, sequence++);
}
Map<String, Object> paramMap = new HashMap<String, Object>();
int x = 0;
for (SectionField field : sectionFields) {
String fieldPropertyName = field.getFieldPropertyName();
if (beanWrapper.isReadableProperty(fieldPropertyName)) {
FieldHandler handler = fieldHandlerHelper.lookupFieldHandler(field.getFieldType());
+ boolean isCustomField = false;
Object displayValue = StringConstants.EMPTY;
if (beanWrapper.isReadableProperty(field.getFieldPropertyName())) {
Object fieldValue = beanWrapper.getPropertyValue(field.getFieldPropertyName());
if (fieldValue instanceof CustomField) {
fieldValue = ((CustomField) fieldValue).getValue();
+ isCustomField = true;
}
if (field.getFieldPropertyName().equals(StringConstants.ID) || field.getFieldPropertyName().equals(StringConstants.ALIAS_ID)) {
displayValue = fieldValue;
}
else {
displayValue = handler.resolveDisplayValue(request, PropertyAccessorFactory.forBeanPropertyAccess(thisEntity), field, fieldValue);
}
}
if (displayValue instanceof String) {
displayValue = HttpUtil.escapeDoubleQuoteReturns((String) displayValue);
String extType = ExtTypeHandler.findExtDataType(beanWrapper.getPropertyType(field.getFieldPropertyName()));
if (ExtTypeHandler.EXT_BOOLEAN.equals(extType) && ("Y".equalsIgnoreCase((String) displayValue) ||
"yes".equalsIgnoreCase((String) displayValue) ||
"T".equalsIgnoreCase((String) displayValue) ||
"true".equalsIgnoreCase((String) displayValue))) {
displayValue = "true";
}
}
- String key = useAliasName && ! StringConstants.ID.equals(fieldPropertyName) && ! StringConstants.ALIAS_ID.equals(fieldPropertyName)
- ? new StringBuilder(SORT_KEY_PREFIX).append(x++).toString() : TangerineForm.escapeFieldName(fieldPropertyName);
+ String key;
+ if (useAliasName && ! StringConstants.ID.equals(fieldPropertyName) && ! StringConstants.ALIAS_ID.equals(fieldPropertyName)) {
+ key = new StringBuilder(SORT_KEY_PREFIX).append(x++).toString();
+ }
+ else {
+ key = TangerineForm.escapeFieldName(isCustomField ? fieldPropertyName + StringConstants.DOT_VALUE : fieldPropertyName);
+ }
paramMap.put(key, displayValue);
}
}
paramMapList.add(paramMap);
}
}
}
public Map<String, Object> initMetaData(int start, int limit) {
final Map<String, Object> metaDataMap = new LinkedHashMap<String, Object>();
metaDataMap.put(StringConstants.ID_PROPERTY, StringConstants.ID);
metaDataMap.put(StringConstants.ROOT, StringConstants.ROWS);
metaDataMap.put(StringConstants.TOTAL_PROPERTY, StringConstants.TOTAL_ROWS);
metaDataMap.put(StringConstants.SUCCESS_PROPERTY, StringConstants.SUCCESS);
metaDataMap.put(StringConstants.START, start);
metaDataMap.put(StringConstants.LIMIT, limit);
return metaDataMap;
}
public List<SectionField> findSectionFields(String listPageName) {
return pageCustomizationService.readSectionFieldsByPageTypeRoles(PageType.valueOf(listPageName), tangerineUserHelper.lookupUserRoles());
}
}
| false | true | public void addListFieldsToMap(HttpServletRequest request, List<SectionField> sectionFields, List entities,
List<Map<String, Object>> paramMapList, boolean useAliasName, boolean useAliasId) {
int sequence = 0;
if (entities != null) {
for (Object thisEntity : entities) {
BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(thisEntity);
/**
* If useAliasId == true, set the aliasId to the ID and reset to ID to the next sequence number
*/
if (useAliasId && beanWrapper.isWritableProperty(StringConstants.ALIAS_ID) && beanWrapper.isReadableProperty(StringConstants.ID)) {
beanWrapper.setPropertyValue(StringConstants.ALIAS_ID, beanWrapper.getPropertyValue(StringConstants.ID));
beanWrapper.setPropertyValue(StringConstants.ID, sequence++);
}
Map<String, Object> paramMap = new HashMap<String, Object>();
int x = 0;
for (SectionField field : sectionFields) {
String fieldPropertyName = field.getFieldPropertyName();
if (beanWrapper.isReadableProperty(fieldPropertyName)) {
FieldHandler handler = fieldHandlerHelper.lookupFieldHandler(field.getFieldType());
Object displayValue = StringConstants.EMPTY;
if (beanWrapper.isReadableProperty(field.getFieldPropertyName())) {
Object fieldValue = beanWrapper.getPropertyValue(field.getFieldPropertyName());
if (fieldValue instanceof CustomField) {
fieldValue = ((CustomField) fieldValue).getValue();
}
if (field.getFieldPropertyName().equals(StringConstants.ID) || field.getFieldPropertyName().equals(StringConstants.ALIAS_ID)) {
displayValue = fieldValue;
}
else {
displayValue = handler.resolveDisplayValue(request, PropertyAccessorFactory.forBeanPropertyAccess(thisEntity), field, fieldValue);
}
}
if (displayValue instanceof String) {
displayValue = HttpUtil.escapeDoubleQuoteReturns((String) displayValue);
String extType = ExtTypeHandler.findExtDataType(beanWrapper.getPropertyType(field.getFieldPropertyName()));
if (ExtTypeHandler.EXT_BOOLEAN.equals(extType) && ("Y".equalsIgnoreCase((String) displayValue) ||
"yes".equalsIgnoreCase((String) displayValue) ||
"T".equalsIgnoreCase((String) displayValue) ||
"true".equalsIgnoreCase((String) displayValue))) {
displayValue = "true";
}
}
String key = useAliasName && ! StringConstants.ID.equals(fieldPropertyName) && ! StringConstants.ALIAS_ID.equals(fieldPropertyName)
? new StringBuilder(SORT_KEY_PREFIX).append(x++).toString() : TangerineForm.escapeFieldName(fieldPropertyName);
paramMap.put(key, displayValue);
}
}
paramMapList.add(paramMap);
}
}
}
| public void addListFieldsToMap(HttpServletRequest request, List<SectionField> sectionFields, List entities,
List<Map<String, Object>> paramMapList, boolean useAliasName, boolean useAliasId) {
int sequence = 0;
if (entities != null) {
for (Object thisEntity : entities) {
BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(thisEntity);
/**
* If useAliasId == true, set the aliasId to the ID and reset to ID to the next sequence number
*/
if (useAliasId && beanWrapper.isWritableProperty(StringConstants.ALIAS_ID) && beanWrapper.isReadableProperty(StringConstants.ID)) {
beanWrapper.setPropertyValue(StringConstants.ALIAS_ID, beanWrapper.getPropertyValue(StringConstants.ID));
beanWrapper.setPropertyValue(StringConstants.ID, sequence++);
}
Map<String, Object> paramMap = new HashMap<String, Object>();
int x = 0;
for (SectionField field : sectionFields) {
String fieldPropertyName = field.getFieldPropertyName();
if (beanWrapper.isReadableProperty(fieldPropertyName)) {
FieldHandler handler = fieldHandlerHelper.lookupFieldHandler(field.getFieldType());
boolean isCustomField = false;
Object displayValue = StringConstants.EMPTY;
if (beanWrapper.isReadableProperty(field.getFieldPropertyName())) {
Object fieldValue = beanWrapper.getPropertyValue(field.getFieldPropertyName());
if (fieldValue instanceof CustomField) {
fieldValue = ((CustomField) fieldValue).getValue();
isCustomField = true;
}
if (field.getFieldPropertyName().equals(StringConstants.ID) || field.getFieldPropertyName().equals(StringConstants.ALIAS_ID)) {
displayValue = fieldValue;
}
else {
displayValue = handler.resolveDisplayValue(request, PropertyAccessorFactory.forBeanPropertyAccess(thisEntity), field, fieldValue);
}
}
if (displayValue instanceof String) {
displayValue = HttpUtil.escapeDoubleQuoteReturns((String) displayValue);
String extType = ExtTypeHandler.findExtDataType(beanWrapper.getPropertyType(field.getFieldPropertyName()));
if (ExtTypeHandler.EXT_BOOLEAN.equals(extType) && ("Y".equalsIgnoreCase((String) displayValue) ||
"yes".equalsIgnoreCase((String) displayValue) ||
"T".equalsIgnoreCase((String) displayValue) ||
"true".equalsIgnoreCase((String) displayValue))) {
displayValue = "true";
}
}
String key;
if (useAliasName && ! StringConstants.ID.equals(fieldPropertyName) && ! StringConstants.ALIAS_ID.equals(fieldPropertyName)) {
key = new StringBuilder(SORT_KEY_PREFIX).append(x++).toString();
}
else {
key = TangerineForm.escapeFieldName(isCustomField ? fieldPropertyName + StringConstants.DOT_VALUE : fieldPropertyName);
}
paramMap.put(key, displayValue);
}
}
paramMapList.add(paramMap);
}
}
}
|
diff --git a/plugins/org.jboss.tools.esb.project.ui/src/org/jboss/tools/esb/project/ui/utils/UIUtils.java b/plugins/org.jboss.tools.esb.project.ui/src/org/jboss/tools/esb/project/ui/utils/UIUtils.java
index 345fbd6..4d5a7bc 100644
--- a/plugins/org.jboss.tools.esb.project.ui/src/org/jboss/tools/esb/project/ui/utils/UIUtils.java
+++ b/plugins/org.jboss.tools.esb.project.ui/src/org/jboss/tools/esb/project/ui/utils/UIUtils.java
@@ -1,502 +1,502 @@
/*******************************************************************************
* Copyright (c) 2008 Red Hat, Inc.
* Distributed under license by Red Hat, Inc. All rights reserved.
* This program is made available under the terms of the
* Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
******************************************************************************/
package org.jboss.tools.esb.project.ui.utils;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.ui.PlatformUI;
/**
* @author Grid Qian
*/
public class UIUtils {
/**
* A default padding value for horizontalResize().
*/
public final static int DEFAULT_PADDING = 35;
String infoPopid_;
public UIUtils(String infoPopid) {
infoPopid_ = infoPopid;
}
public Button createRadioButton(Composite parent, String labelName,
String tooltip, String infopop) {
return createButton(SWT.RADIO, parent, labelName, tooltip, infopop);
}
public Button createCheckbox(Composite parent, String labelName,
String tooltip, String infopop) {
return createButton(SWT.CHECK, parent, labelName, tooltip, infopop);
}
public Button createPushButton(Composite parent, String labelName,
String tooltip, String infopop) {
return createButton(SWT.NONE, parent, labelName, tooltip, infopop);
}
public Button createButton(int kind, Composite parent, String labelName,
String tooltip, String infopop) {
Button button = new Button(parent, kind);
tooltip = tooltip == null ? labelName : tooltip;
button.setText(labelName);
button.setToolTipText(tooltip);
if (infopop != null)
PlatformUI.getWorkbench().getHelpSystem().setHelp(button,
infoPopid_ + "." + infopop);
return button;
}
public Combo createCombo(Composite parent, String labelName,
String tooltip, String infopop, int style) {
tooltip = tooltip == null ? labelName : tooltip;
if (labelName != null) {
Label label = new Label(parent, SWT.WRAP);
label.setText(labelName);
label.setToolTipText(tooltip);
}
Combo combo = new Combo(parent, style);
GridData griddata = new GridData(GridData.HORIZONTAL_ALIGN_FILL
| GridData.GRAB_HORIZONTAL);
combo.setLayoutData(griddata);
combo.setToolTipText(tooltip);
if (infopop != null)
PlatformUI.getWorkbench().getHelpSystem().setHelp(combo,
infoPopid_ + "." + infopop);
return combo;
}
public Text createText(Composite parent, String labelName, String tooltip,
String infopop, int style) {
tooltip = tooltip == null ? labelName : tooltip;
if (labelName != null) {
Label label = new Label(parent, SWT.WRAP);
label.setText(labelName);
label.setToolTipText(tooltip);
}
Text text = new Text(parent, style);
GridData griddata = new GridData(GridData.HORIZONTAL_ALIGN_FILL
| GridData.GRAB_HORIZONTAL);
text.setLayoutData(griddata);
text.setToolTipText(tooltip);
if (infopop != null)
PlatformUI.getWorkbench().getHelpSystem().setHelp(text,
infoPopid_ + "." + infopop);
return text;
}
public Composite createComposite(Composite parent, int columns) {
return createComposite(parent, columns, -1, -1);
}
public Composite createComposite(Composite parent, int columns,
int marginHeight, int marginWidth) {
Composite composite = new Composite(parent, SWT.NONE);
GridLayout gridlayout = new GridLayout();
gridlayout.numColumns = columns;
if (marginHeight >= 0)
gridlayout.marginHeight = marginHeight;
if (marginWidth >= 0)
gridlayout.marginWidth = marginWidth;
composite.setLayout(gridlayout);
GridData griddata = new GridData(GridData.HORIZONTAL_ALIGN_FILL
| GridData.GRAB_HORIZONTAL);
composite.setLayoutData(griddata);
return composite;
}
public Group createGroup(Composite parent, String groupName,
String tooltip, String infopop) {
return createGroup(parent, groupName, tooltip, infopop, 1, -1, -1);
}
public Group createGroup(Composite parent, String groupName,
String tooltip, String infopop, int columns, int marginHeight,
int marginWidth) {
Group newGroup = new Group(parent, SWT.NONE);
GridData griddata = new GridData(GridData.HORIZONTAL_ALIGN_FILL
| GridData.GRAB_HORIZONTAL);
GridLayout gridlayout = new GridLayout();
gridlayout.numColumns = columns;
if (marginHeight >= 0)
gridlayout.marginHeight = marginHeight;
if (marginWidth >= 0)
gridlayout.marginWidth = marginWidth;
tooltip = tooltip == null ? groupName : tooltip;
newGroup.setLayout(gridlayout);
newGroup.setText(groupName);
newGroup.setLayoutData(griddata);
newGroup.setToolTipText(tooltip);
if (infopop != null)
PlatformUI.getWorkbench().getHelpSystem().setHelp(newGroup,
infoPopid_ + "." + infopop);
return newGroup;
}
public Tree createTree(Composite parent, String tooltip, String infopop,
int style) {
tooltip = tooltip == null ? "" : tooltip;
Tree tree = new Tree(parent, style);
tree.setLayoutData(createFillAll());
tree.setToolTipText(tooltip);
if (infopop != null)
PlatformUI.getWorkbench().getHelpSystem().setHelp(tree,
infoPopid_ + "." + infopop);
return tree;
}
public Table createTable(Composite parent, String tooltip, String infopop,
int style) {
tooltip = tooltip == null ? "" : tooltip;
Table table = new Table(parent, style);
// table.setLayoutData( createFillAll() );
table.setToolTipText(tooltip);
if (infopop != null)
PlatformUI.getWorkbench().getHelpSystem().setHelp(table,
infoPopid_ + "." + infopop);
return table;
}
public Label createHorizontalSeparator(Composite parent, int spacing) {
Composite composite = createComposite(parent, 1, spacing, -1);
Label separator = new Label(composite, SWT.SEPARATOR | SWT.HORIZONTAL);
GridData griddata = new GridData(GridData.HORIZONTAL_ALIGN_FILL
| GridData.GRAB_HORIZONTAL);
separator.setLayoutData(griddata);
return separator;
}
public GridData createFillAll() {
GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL
| GridData.GRAB_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL
| GridData.GRAB_VERTICAL);
return data;
}
public void createInfoPop(Control ctrl, String infopop) {
if (infopop != null)
PlatformUI.getWorkbench().getHelpSystem().setHelp(ctrl,
infoPopid_ + "." + infopop);
}
/**
* Resizes the width of the target composite so that it is as wide as the
* reference composite plus a padding value.
*
* @param target
* The composite to resize.
* @param reference
* The reference composite
* @param padding
* The padding value
*/
public void horizontalResize(Composite target, Composite reference,
int padding) {
Point originalSize = target.getSize();
Point referenceSize = reference.getSize();
padding = padding >= 0 ? padding : DEFAULT_PADDING;
if (referenceSize.x + padding > originalSize.x)
target.setSize(referenceSize.x + padding, originalSize.y);
}
public static void writePropertyToFile(File file,String key, String value) throws IOException {
Writer out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(file), "8859_1"));
out.write(key+"="+value+"\n");
out.close();
}
// file util
public static void copyFile(String src, String dest) {
InputStream is = null;
FileOutputStream fos = null;
try
{
is = new FileInputStream(src);
fos = new FileOutputStream(dest);
int c = 0;
byte[] array = new byte[1024];
while ((c = is.read(array)) >= 0){
fos.write(array, 0, c);
}
}
- catch (Exception e) {
+ catch (IOException e) {
e.printStackTrace();
}
finally {
try {
fos.close();
is.close();
}
- catch (Exception e) {
+ catch (IOException e) {
e.printStackTrace();
}
}
}
public static File createFileAndParentDirectories(String fileName) throws Exception {
File file = new File(fileName);
File parent = file.getParentFile();
if (!parent.exists()){
parent.mkdirs();
}
file.createNewFile();
return file;
}
public static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i=0; i<children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
return dir.delete();
}
public static void deleteDirectories(File dir) {
File[] children = dir.listFiles();
for (int i = 0; i < children.length; i++){
if (children[i].list() != null && children[i].list().length > 0){
deleteDirectories(children[i]);
}
else{
children[i].delete();
}
}
dir.delete();
}
public static void deleteDirectories(String dir) {
File directory = new File(dir);
deleteDirectories(directory);
}
public static void createTargetFile(String sourceFileName, String targetFileName)
throws Exception {
createTargetFile(sourceFileName, targetFileName, false);
}
public static void createTargetFile(String sourceFileName, String targetFileName,
boolean overwrite) throws Exception{
File idealResultFile = new File(targetFileName);
if (overwrite || !idealResultFile.exists())
{
createFileAndParentDirectories(targetFileName);
copyFile(sourceFileName, targetFileName);
}
}
public static boolean createDirectory(String directory){
// Create a directory; all ancestor directories must exist
boolean success = (new File(directory)).mkdir();
if (!success) {
// Directory creation failed
}
return success;
}
public static boolean createDirectorys(String directory){
// Create a directory; all ancestor directories must exist
boolean success = (new File(directory)).mkdirs();
if (!success) {
// Directory creation failed
}
return success;
}
//Copies all files under srcDir to dstDir.
// If dstDir does not exist, it will be created.
public static void copyDirectory(File srcDir, File dstDir) throws IOException {
if (srcDir.isDirectory()) {
if (!dstDir.exists()) {
dstDir.mkdir();
}
String[] children = srcDir.list();
for (int i=0; i<children.length; i++) {
copyDirectory(new File(srcDir, children[i]),
new File(dstDir, children[i]));
}
} else {
copy(srcDir, dstDir);
}
}
//Copies src file to dst file.
// If the dst file does not exist, it is created
public static void copy(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
public static String addAnotherNodeToPath(String currentPath, String newNode) {
return currentPath + File.separator + newNode;
}
public static String addNodesToPath(String currentPath, String[] newNode) {
String returnPath=currentPath;
for (int i = 0; i < newNode.length; i++) {
returnPath = returnPath + File.separator + newNode[i];
}
return returnPath;
}
public static String addNodesToPath(StringBuffer currentPath, String[] pathNodes) {
for (int i = 0; i < pathNodes.length; i++){
currentPath.append(File.separator);
currentPath.append(pathNodes[i]);
}
return currentPath.toString();
}
public static String addNodesToURL(String currentPath, String[] newNode) {
String returnPath=currentPath;
for (int i = 0; i < newNode.length; i++) {
returnPath = returnPath + "/" + newNode[i];
}
return returnPath;
}
/**
* Get the list of file with a prefix of <code>fileNamePrefix</code> & an extension of
* <code>extension</code>
*
* @param sourceDir The directory in which to search the files
* @param fileNamePrefix The prefix to look for
* @param extension The extension to look for
* @return The list of file with a prefix of <code>fileNamePrefix</code> & an extension of
* <code>extension</code>
*/
public static File[] getMatchingFiles(String sourceDir, String fileNamePrefix, String extension) {
List<File> fileList = new ArrayList<File>();
File libDir = new File(sourceDir);
String libDirPath = libDir.getAbsolutePath();
String[] items = libDir.list();
if (items != null) {
for (int i = 0; i < items.length; i++) {
String item = items[i];
if (fileNamePrefix != null && extension != null) {
if (item.startsWith(fileNamePrefix) && item.endsWith(extension)) {
fileList.add(new File(libDirPath + File.separator + item));
}
} else if (fileNamePrefix == null && extension != null) {
if (item.endsWith(extension)) {
fileList.add(new File(libDirPath + File.separator + item));
}
} else if (fileNamePrefix != null && extension == null) {
if (item.startsWith(fileNamePrefix)) {
fileList.add(new File(libDirPath + File.separator + item));
}
} else {
fileList.add(new File(libDirPath + File.separator + item));
}
}
return (File[]) fileList.toArray(new File[fileList.size()]);
}
return new File[0];
}
/**
* Filter out files inside a <code>sourceDir</code> with matching <codefileNamePrefix></code>
* and <code>extension</code>
* @param sourceDir The directory to filter the files
* @param fileNamePrefix The filtering filename prefix
* @param extension The filtering file extension
*/
public static void filterOutRestrictedFiles(String sourceDir, String fileNamePrefix, String extension){
File[] resultedMatchingFiles = getMatchingFiles(sourceDir, fileNamePrefix, extension);
for (int i = 0; i < resultedMatchingFiles.length; i++) {
File matchingFilePath = new File(resultedMatchingFiles[i].getAbsolutePath());
matchingFilePath.delete();
}
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/src/main/java/ch/o2it/weblounge/common/language/Language.java b/src/main/java/ch/o2it/weblounge/common/language/Language.java
index 8e3735e1e..0adcd8c6c 100644
--- a/src/main/java/ch/o2it/weblounge/common/language/Language.java
+++ b/src/main/java/ch/o2it/weblounge/common/language/Language.java
@@ -1,77 +1,78 @@
/*
* Weblounge: Web Content Management System
* Copyright (c) 2009 The Weblounge Team
* http://weblounge.o2it.ch
*
* This program 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
* 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package ch.o2it.weblounge.common.language;
+import java.io.Serializable;
import java.util.Locale;
/**
* A <code>Language</code> consists of a language identifier, e.g.
* <code>de</code> to identify the German language, and of the language
* description in the various supported languages. There is also a connection
* to the associate <code>Locale</code>.
*
* @see Locale
*/
-public interface Language extends Comparable<Language> {
+public interface Language extends Serializable, Comparable<Language> {
/**
* Returns the locale that is associated with the language.
*
* @return the locale
*/
Locale getLocale();
/**
* Returns the name of this language in its own language, e.g
* <ul>
* <li><code>English</code> for English</li>
* <li><code>Deutsch</code> for German</li>
* <li><code>Français</code> for French</li>
* </ul>
*
* @return the language name in its own language
*/
String getDescription();
/**
* Returns the name of this language in the specified language, e.g given that
* <code>language</code> was <code>German</code>, this method would return:
* <ul>
* <li><code>Englisch</code> for English</li>
* <li><code>Deutsch</code> for German</li>
* <li><code>Französisch</code> for French</li>
* </ul>
*
* @param language
* the language version of this language
* @return the language name in the specified language
*/
String getDescription(Language language);
/**
* Returns the language's identifier, which corresponds to the locales
* name for this language.
*
* @return the language identifier
*/
String getIdentifier();
}
\ No newline at end of file
| false | false | null | null |
diff --git a/samples/showcase/showcase/src/main/java/org/icefaces/samples/showcase/example/ace/dataExporter/DataExporterBean.java b/samples/showcase/showcase/src/main/java/org/icefaces/samples/showcase/example/ace/dataExporter/DataExporterBean.java
index d48d883e2..83642b2a6 100644
--- a/samples/showcase/showcase/src/main/java/org/icefaces/samples/showcase/example/ace/dataExporter/DataExporterBean.java
+++ b/samples/showcase/showcase/src/main/java/org/icefaces/samples/showcase/example/ace/dataExporter/DataExporterBean.java
@@ -1,71 +1,71 @@
/*
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations under
* the License.
*
* The Original Code is ICEfaces 1.5 open source software code, released
* November 5, 2006. The Initial Developer of the Original Code is ICEsoft
* Technologies Canada, Corp. Portions created by ICEsoft are Copyright (C)
* 2004-2011 ICEsoft Technologies Canada, Corp. All Rights Reserved.
*
* Contributor(s): _____________________.
*/
package org.icefaces.samples.showcase.example.ace.dataExporter;
import org.icefaces.samples.showcase.metadata.annotation.*;
import org.icefaces.samples.showcase.metadata.context.ComponentExampleImpl;
import javax.faces.bean.CustomScoped;
import javax.faces.bean.ManagedBean;
import java.io.Serializable;
@ComponentExample(
title = "example.ace.dataExporter.title",
description = "example.ace.dataExporter.description",
example = "/resources/examples/ace/dataExporter/dataExporter.xhtml"
)
@ExampleResources(
resources ={
// xhtml
@ExampleResource(type = ResourceType.xhtml,
title="dataExporter.xhtml",
resource = "/resources/examples/ace/dataExporter/dataExporter.xhtml"),
// Java Source
@ExampleResource(type = ResourceType.java,
title="DataExporterBean.java",
resource = "/WEB-INF/classes/org/icefaces/samples/showcase"+
"/example/ace/dataExporter/DataExporterBean.java")
}
)
@Menu(
title = "menu.ace.dataExporter.subMenu.title",
menuLinks = {
@MenuLink(title = "menu.ace.dataExporter.subMenu.main",
isDefault = true,
exampleBeanName = DataExporterBean.BEAN_NAME),
@MenuLink(title = "menu.ace.dataExporter.subMenu.columns",
exampleBeanName = DataExporterColumns.BEAN_NAME)
}
)
@ManagedBean(name= DataExporterBean.BEAN_NAME)
@CustomScoped(value = "#{window}")
public class DataExporterBean extends ComponentExampleImpl<DataExporterBean> implements Serializable {
public static final String BEAN_NAME = "dataExporterBean";
private String type;
public DataExporterBean() {
super(DataExporterBean.class);
- this.type = "xls";
+ this.type = "csv";
}
public String getType() { return type; }
public void setType(String type) { this.type = type; }
}
\ No newline at end of file
| true | false | null | null |
diff --git a/src/rs/pedjaapps/KernelTuner/KernelTuner.java b/src/rs/pedjaapps/KernelTuner/KernelTuner.java
index f416481..7585655 100755
--- a/src/rs/pedjaapps/KernelTuner/KernelTuner.java
+++ b/src/rs/pedjaapps/KernelTuner/KernelTuner.java
@@ -1,2302 +1,2304 @@
package rs.pedjaapps.KernelTuner;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
import java.util.TimeZone;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.RemoteViews;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.ads.AdRequest;
import com.google.ads.AdView;
//EndImports
@SuppressLint("WorldReadableFiles")
public class KernelTuner extends Activity {
private TextView batteryLevel;
private TextView batteryTemp;
private TextView cputemptxt;
public SharedPreferences sharedPrefs;
String tempPref;
boolean tempMonitor;
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent intent) {
int level = intent.getIntExtra("level", 0);
double temperature = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0)/10;
if (tempPref.equals("fahrenheit"))
{
temperature = (temperature*1.8)+32;
batteryTemp.setText(String.valueOf((int)temperature) + "°F");
if(temperature<=104){
batteryTemp.setTextColor(Color.GREEN);
battTempWarningStop();
}
else if(temperature>104 && temperature<131){
batteryTemp.setTextColor(Color.YELLOW);
battTempWarningStop();
}
else if(temperature>=131 && temperature < 140 ){
batteryTemp.setTextColor(Color.RED);
battTempWarningStop();
}
else if(temperature>=140){
// Log.e("Battery warning","start animation");
batteryTemp.setTextColor(Color.RED);
battTempWarning();
}
}
else if(tempPref.equals("celsius")){
batteryTemp.setText(String.valueOf(temperature) + "°C");
if(temperature<45){
batteryTemp.setTextColor(Color.GREEN);
battTempWarningStop();
}
else if(temperature>45 && temperature<55){
batteryTemp.setTextColor(Color.YELLOW);
battTempWarningStop();
}
else if(temperature>=55 && temperature < 60 ){
batteryTemp.setTextColor(Color.RED);
battTempWarningStop();
}
else if(temperature>=60){
// Log.e("Battery warning","start animation");
batteryTemp.setTextColor(Color.RED);
battTempWarning();
}
}
///F = (C x 1.8) + 32
batteryLevel.setText(String.valueOf(level) + "%");
if(level<15 && level>=5){
batteryLevel.setTextColor(Color.RED);
battLevelWarningStop();
}
else if(level>15 && level<=30){
batteryLevel.setTextColor(Color.YELLOW);
battLevelWarningStop();
}
else if(level>30 ){
batteryLevel.setTextColor(Color.GREEN);
battLevelWarningStop();
}
else if(level<5){
batteryLevel.setTextColor(Color.RED);
battLevelWarning();
}
}
};
boolean thread = true;
private Button button2;
public String iscVa = "offline";
public String iscVa2 = "offline";
public String governors;
public String governorscpu1;
public String curentgovernorcpu0;
public String curentgovernorcpu1;
public String curentgovernorcpu2;
public String curentgovernorcpu3;
public String led;
SeekBar mSeekBar;
TextView progresstext;
public String cpu0freqs;
public String cpu1freqs;
public String cpu2freqs;
public String cpu3freqs;
public String cpu0max = " ";
public String cpu1max = " ";
public String cpu0min = " ";
public String cpu1min = " ";
public String cpu2max = " ";
public String cpu3max = " ";
public String cpu2min = " ";
public String cpu3min = " ";
public String gpu2d = " ";
public String gpu3d = " ";
public int countcpu0;
public int countcpu1;
public String vsync = " ";
public String fastcharge = " ";
public String out;
public String cdepth ;
public String kernel = " ";
public String remoteversion;
public String schedulers;
public String scheduler;
public String sdcache;
public String curentidlefreq;
public String delay;
public String pause;
public String thrupload;
public String thrupms;
public String thrdownload;
public String thrdownms;
public boolean cpu1check;
public String sdcacheinfo;
public String ioschedulerinfo;
List<String> list;
public String ldt;
public String freqcpu2;
public String freqcpu3;
public String p1low;
public String p1high;
public String p2low;
public String p2high;
public String p3low;
public String p3high;
public String p1freq;
public String p2freq;
public String p3freq;
public String cputemp;
public static String cpu0online = CPUInfo.cpu0online;
public static String cpu1online = CPUInfo.cpu1online;
public static String cpu2online = CPUInfo.cpu2online;
public static String cpu3online = CPUInfo.cpu3online;
public static String CPU0_FREQS = CPUInfo.CPU0_FREQS;
public static String CPU0_CURR_FREQ = CPUInfo.CPU0_CURR_FREQ;
public static String CPU1_CURR_FREQ = CPUInfo.CPU1_CURR_FREQ;
public static String CPU2_CURR_FREQ = CPUInfo.CPU2_CURR_FREQ;
public static String CPU3_CURR_FREQ = CPUInfo.CPU3_CURR_FREQ;
public static String CPU0_MAX_FREQ = CPUInfo.CPU0_MAX_FREQ;
public static String CPU1_MAX_FREQ = CPUInfo.CPU1_MAX_FREQ;
public static String CPU2_MAX_FREQ = CPUInfo.CPU2_MAX_FREQ;
public static String CPU3_MAX_FREQ = CPUInfo.CPU3_MAX_FREQ;
public static String CPU0_MIN_FREQ = CPUInfo.CPU0_MIN_FREQ;
public static String CPU1_MIN_FREQ = CPUInfo.CPU1_MIN_FREQ;
public static String CPU2_MIN_FREQ = CPUInfo.CPU2_MIN_FREQ;
public static String CPU3_MIN_FREQ = CPUInfo.CPU3_MIN_FREQ;
public static String CPU0_CURR_GOV = CPUInfo.CPU0_CURR_GOV;
public static String CPU1_CURR_GOV = CPUInfo.CPU1_CURR_GOV;
public static String CPU2_CURR_GOV = CPUInfo.CPU2_CURR_GOV;
public static String CPU3_CURR_GOV = CPUInfo.CPU3_CURR_GOV;
public static String CPU0_GOVS = CPUInfo.CPU0_GOVS;
public static String CPU1_GOVS = CPUInfo.CPU1_GOVS;
public static String CPU2_GOVS = CPUInfo.CPU2_GOVS;
public static String CPU3_GOVS = CPUInfo.CPU3_GOVS;
String mpdec;
List<String> frequencies3 = new ArrayList<String>();
List<String> frequencies4 = new ArrayList<String>();
List<String> frequencies5 = new ArrayList<String>();
public String[] delims;
String freqs;
List<String> vdd = new ArrayList<String>();
List<String> frequencies = new ArrayList<String>();
List<String> frequencies2 = new ArrayList<String>();
List<Integer> perint = new ArrayList<Integer>();
String[] freqarray;
String[] freqarray2;
String[] vddarray;
public String govs;
public String currentscrofffreq;
public String currentscroffgov;
public String govselected;
public String maxfreqselected;
public String onoff;
public String scroff_profile;
public String mpdecisionidle;
public String version;
public String changelog;
public List<String> freqlist;
public SharedPreferences preferences;
private ProgressDialog pd = null;
public String s2w;
Handler mHandler = new Handler();
public static boolean isDownloadManagerAvailable(Context context) {
try {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {
return false;
}
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setClassName("com.android.providers.downloads.ui", "com.android.providers.downloads.ui.DownloadList");
List<ResolveInfo> list = context.getPackageManager().queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
} catch (Exception e) {
return false;
}
}
class updateCheck extends AsyncTask<String, Void, Object> {
@Override
protected Object doInBackground(String... args) {
try {
// Create a URL for the desired page
URL url = new URL("http://kerneltuner.pedjaapps.in.rs/ktuner/version");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
remoteversion = in.readLine();
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
remoteversion=null;
}
try {
// Create a URL for the desired page
URL url = new URL("http://kerneltuner.pedjaapps.in.rs/ktuner/changelog");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = in.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
changelog = aBuffer;
// changelog = in.readLine();
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
changelog=null;
}
return "";
}
@Override
protected void onPreExecute() {
super.onPreExecute();
pd = ProgressDialog.show(
KernelTuner.this,
"Working...",
"Checking for updates...",
true,
true,
new DialogInterface.OnCancelListener(){
@Override
public void onCancel(DialogInterface dialog) {
updateCheck.this.cancel(true);
}
}
);
}
@Override
protected void onPostExecute(Object result) {
KernelTuner.this.pd.dismiss();
try {
PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
version = pInfo.versionName;
} catch (NameNotFoundException e1) {
e1.printStackTrace();
}
if (remoteversion!= null && !remoteversion.equals(version)){
AlertDialog.Builder builder = new AlertDialog.Builder(
KernelTuner.this);
builder.setTitle("New Version Available");
builder.setMessage("New version of the application is available!\n\n" +
"\"Kernel Tuner-"+ remoteversion+"\"\n\n"+
"Changelog:\n"+ changelog + "\n\n"+
"Would you like to download?");
builder.setIcon(R.drawable.icon);
builder.setPositiveButton("Download", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
download();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
else if(remoteversion==null){
Toast.makeText(getApplicationContext(), "Problem connecting to server", Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getApplicationContext(), "You have the latest version", Toast.LENGTH_LONG).show();
}
}
}
private class mountDebugFs extends AsyncTask<String, Void, Object> {
@Override
protected Object doInBackground(String... args) {
Process localProcess;
try {
localProcess = Runtime.getRuntime().exec("su");
DataOutputStream localDataOutputStream = new DataOutputStream(localProcess.getOutputStream());
localDataOutputStream.writeBytes("mount -t debugfs debugfs /sys/kernel/debug\n");
localDataOutputStream.writeBytes("exit\n");
localDataOutputStream.flush();
localDataOutputStream.close();
localProcess.waitFor();
localProcess.destroy();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
@Override
protected void onPostExecute(Object result) {
}
}
private class cpu1Toggle extends AsyncTask<String, Void, Object> {
@Override
protected Object doInBackground(String... args) {
File file = new File(CPU1_CURR_GOV);
try{
InputStream fIn = new FileInputStream(file);
Process localProcess;
try {
localProcess = Runtime.getRuntime().exec("su");
DataOutputStream localDataOutputStream = new DataOutputStream(localProcess.getOutputStream());
localDataOutputStream.writeBytes("echo 1 > /sys/kernel/msm_mpdecision/conf/enabled\n");
localDataOutputStream.writeBytes("chmod 777 " + cpu1online+"\n");
localDataOutputStream.writeBytes("echo 0 > " +cpu1online +"\n");
localDataOutputStream.writeBytes("chown system " +cpu1online +"\n");
localDataOutputStream.writeBytes("exit\n");
localDataOutputStream.flush();
localDataOutputStream.close();
localProcess.waitFor();
localProcess.destroy();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("cputoggle", false);
editor.commit();
}
catch(FileNotFoundException e){
//enable cpu1
Process localProcess;
try {
localProcess = Runtime.getRuntime().exec("su");
DataOutputStream localDataOutputStream = new DataOutputStream(localProcess.getOutputStream());
localDataOutputStream.writeBytes("echo 0 > /sys/kernel/msm_mpdecision/conf/enabled\n");
localDataOutputStream.writeBytes("chmod 666 "+cpu1online+"\n");
localDataOutputStream.writeBytes("echo 1 > "+cpu1online+"\n");
localDataOutputStream.writeBytes("chmod 444 "+cpu1online+"\n");
localDataOutputStream.writeBytes("chown system "+cpu1online+"\n");
localDataOutputStream.writeBytes("exit\n");
localDataOutputStream.flush();
localDataOutputStream.close();
localProcess.waitFor();
localProcess.destroy();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("cputoggle", true);
editor.commit();
}
return "";
}
@Override
protected void onPostExecute(Object result) {
KernelTuner.this.pd.dismiss();
}
}
private class cpu2Toggle extends AsyncTask<String, Void, Object> {
@Override
protected Object doInBackground(String... args) {
// Log.i("MyApp", "Background thread starting");
File file = new File(CPU2_CURR_GOV);
try{
InputStream fIn = new FileInputStream(file);
Process localProcess;
try {
localProcess = Runtime.getRuntime().exec("su");
DataOutputStream localDataOutputStream = new DataOutputStream(localProcess.getOutputStream());
localDataOutputStream.writeBytes("echo 1 > /sys/kernel/msm_mpdecision/conf/enabled\n");
localDataOutputStream.writeBytes("chmod 777 " + cpu2online+"\n");
localDataOutputStream.writeBytes("echo 0 > " +cpu2online +"\n");
localDataOutputStream.writeBytes("chown system " +cpu2online +"\n");
localDataOutputStream.writeBytes("exit\n");
localDataOutputStream.flush();
localDataOutputStream.close();
localProcess.waitFor();
localProcess.destroy();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("cpu2toggle", false);
editor.commit();
}
catch(FileNotFoundException e){
//enable cpu1
Process localProcess;
try {
localProcess = Runtime.getRuntime().exec("su");
DataOutputStream localDataOutputStream = new DataOutputStream(localProcess.getOutputStream());
localDataOutputStream.writeBytes("echo 0 > /sys/kernel/msm_mpdecision/conf/enabled\n");
localDataOutputStream.writeBytes("chmod 666 "+cpu2online+"\n");
localDataOutputStream.writeBytes("echo 1 > "+cpu2online+"\n");
localDataOutputStream.writeBytes("chmod 444 "+cpu2online+"\n");
localDataOutputStream.writeBytes("chown system "+cpu2online+"\n");
localDataOutputStream.writeBytes("exit\n");
localDataOutputStream.flush();
localDataOutputStream.close();
localProcess.waitFor();
localProcess.destroy();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("cpu2toggle", true);
editor.commit();
}
return "";
}
@Override
protected void onPostExecute(Object result) {
KernelTuner.this.pd.dismiss();
}
}
private class cpu3Toggle extends AsyncTask<String, Void, Object> {
@Override
protected Object doInBackground(String... args) {
//Log.i("MyApp", "Background thread starting");
File file = new File(CPU3_CURR_GOV);
try{
InputStream fIn = new FileInputStream(file);
Process localProcess;
try {
localProcess = Runtime.getRuntime().exec("su");
DataOutputStream localDataOutputStream = new DataOutputStream(localProcess.getOutputStream());
localDataOutputStream.writeBytes("echo 1 > /sys/kernel/msm_mpdecision/conf/enabled\n");
localDataOutputStream.writeBytes("chmod 777 " + cpu3online+"\n");
localDataOutputStream.writeBytes("echo 0 > " +cpu3online +"\n");
localDataOutputStream.writeBytes("chown system " +cpu3online +"\n");
localDataOutputStream.writeBytes("exit\n");
localDataOutputStream.flush();
localDataOutputStream.close();
localProcess.waitFor();
localProcess.destroy();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("cpu3toggle", false);
editor.commit();
}
catch(FileNotFoundException e){
//enable cpu1
Process localProcess;
try {
localProcess = Runtime.getRuntime().exec("su");
DataOutputStream localDataOutputStream = new DataOutputStream(localProcess.getOutputStream());
localDataOutputStream.writeBytes("echo 0 > /sys/kernel/msm_mpdecision/conf/enabled\n");
localDataOutputStream.writeBytes("chmod 666 "+cpu3online+"\n");
localDataOutputStream.writeBytes("echo 1 > "+cpu3online+"\n");
localDataOutputStream.writeBytes("chmod 444 "+cpu3online+"\n");
localDataOutputStream.writeBytes("chown system "+cpu3online+"\n");
localDataOutputStream.writeBytes("exit\n");
localDataOutputStream.flush();
localDataOutputStream.close();
localProcess.waitFor();
localProcess.destroy();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("cpu3toggle", true);
editor.commit();
}
return "";
}
@Override
protected void onPostExecute(Object result) {
KernelTuner.this.pd.dismiss();
}
}
private class cpuLoad extends AsyncTask<String, Void, Float> {
@Override
protected Float doInBackground(String... params) {
// TODO Auto-generated method stub
try {
RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r");
String load = reader.readLine();
String[] toks = load.split(" ");
long idle1 = Long.parseLong(toks[5]);
long cpu1 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4])
+ Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);
try {
Thread.sleep(360);
} catch (Exception e) {}
reader.seek(0);
load = reader.readLine();
reader.close();
toks = load.split(" ");
long idle2 = Long.parseLong(toks[5]);
long cpu2 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4])
+ Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);
return ((float)(cpu2 - cpu1) / ((cpu2 + idle2) - (cpu1 + idle1)))*100;
} catch (IOException ex) {
ex.printStackTrace();
}
return (float)0;
}
@Override
protected void onPostExecute(Float result) {
TextView cpuLoadTxt = (TextView)findViewById(R.id.textView1);
ProgressBar cpuLoad = (ProgressBar)findViewById(R.id.progressBar5);
cpuLoad.setProgress(Math.round(result));
cpuLoadTxt.setText(String.valueOf(Math.round(result))+"%");
}
}
private class enableTempMonitor extends AsyncTask<String, Void, Object> {
@Override
protected Object doInBackground(String... args) {
Process localProcess;
try {
localProcess = Runtime.getRuntime().exec("su");
DataOutputStream localDataOutputStream = new DataOutputStream(localProcess.getOutputStream());
- localDataOutputStream.writeBytes("chmod 777 /sys/class/thermal/thermal_zone1/mode\n");
- localDataOutputStream.writeBytes("echo enabled > /sys/class/thermal/thermal_zone1/mode\n");
+ localDataOutputStream.writeBytes("chmod 777 /sys/devices/virtual/thermal/thermal_zone1/mode\n");
+ System.out.println("enabling cpu temp");
+ localDataOutputStream.writeBytes("echo enabled > /sys/devices/virtual/thermal/thermal_zone1/mode\n");
localDataOutputStream.writeBytes("exit\n");
localDataOutputStream.flush();
localDataOutputStream.close();
localProcess.waitFor();
localProcess.destroy();
+ System.out.println("cpu temp enabled");
}
catch(Exception e){
}
return "";
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
new enableTempMonitor().execute();
batteryLevel = (TextView) this.findViewById(R.id.textView42);
batteryTemp = (TextView) this.findViewById(R.id.textView40);
tempPref = sharedPrefs.getString("temp", "celsius");
boolean ads = sharedPrefs.getBoolean("ads", true);
if (ads==true){AdView adView = (AdView)this.findViewById(R.id.ad);
adView.loadAd(new AdRequest());}
changelog();
File file = new File("/sys/kernel/debug/msm_fb/0/vsync_enable");
try{
InputStream fIn = new FileInputStream(file);
}
catch(FileNotFoundException e){
new mountDebugFs().execute();
}
Button gpu = (Button)findViewById(R.id.button3);
gpu.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
Intent myIntent = new Intent(KernelTuner.this, gpu.class);
KernelTuner.this.startActivity(myIntent);
}
});
Button voltage = (Button)findViewById(R.id.button6);
voltage.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
Intent intent = new Intent(KernelTuner.this,
CPUTuner.class);
intent.putExtra("item", "VOLTAGE");
KernelTuner.this.startActivity(intent);
}
});
readFreqs();
initialCheck();
new Thread(new Runnable() {
@Override
public void run() {
while (thread) {
try {
Thread.sleep(1000);
mHandler.post(new Runnable() {
@Override
public void run() {
ReadCPU0Clock();
ReadCPU0maxfreq();
cpuTemp();
new cpuLoad().execute();
//times();
if(new File(cpu1online).exists()){
ReadCPU1Clock();
ReadCPU1maxfreq();
}
if(new File(cpu2online).exists()){
ReadCPU2Clock();
ReadCPU2maxfreq();
}
if(new File(cpu3online).exists()){
ReadCPU3Clock();
ReadCPU3maxfreq();
}
}
});
} catch (Exception e) {
}
}
}
}).start();
Button cpu = (Button)this.findViewById(R.id.button2);
cpu.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
Intent intent = new Intent(KernelTuner.this,
CPUTuner.class);
intent.putExtra("item", "CPU TWEAKS");
KernelTuner.this.startActivity(intent);
}
});
Button tis = (Button)this.findViewById(R.id.button5);
tis.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
Intent intent = new Intent(KernelTuner.this,
CPUTuner.class);
intent.putExtra("item", "TIMES IN STATE");
KernelTuner.this.startActivity(intent);
}
});
Button mpdec = (Button)this.findViewById(R.id.button7);
mpdec.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
Intent myIntent = new Intent(KernelTuner.this, mpdecision.class);
KernelTuner.this.startActivity(myIntent);
}
});
Button buttongpu = (Button)this.findViewById(R.id.button4);
buttongpu.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
Intent myIntent = new Intent(KernelTuner.this, miscTweaks.class);
KernelTuner.this.startActivity(myIntent);
}
});
Button cpu1toggle = (Button)this.findViewById(R.id.button1);
cpu1toggle.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v) {
KernelTuner.this.pd = ProgressDialog.show(KernelTuner.this, "Working..", "Applying settings...", true, false);
new cpu1Toggle().execute();
}});
Button cpu2toggle = (Button)this.findViewById(R.id.button8);
cpu2toggle.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v) {
KernelTuner.this.pd = ProgressDialog.show(KernelTuner.this, "Working..", "Applying settings...", true, false);
new cpu2Toggle().execute();
}});
Button cpu3toggle = (Button)this.findViewById(R.id.button9);
cpu3toggle.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v) {
KernelTuner.this.pd = ProgressDialog.show(KernelTuner.this, "Working..", "Applying settings...", true, false);
new cpu3Toggle().execute();
}});
Button governor = (Button)findViewById(R.id.button10);
governor.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
Intent intent = new Intent(KernelTuner.this,
CPUTuner.class);
intent.putExtra("item", "GOVERNOR SETTINGS");
KernelTuner.this.startActivity(intent);
}
});
Button swap = (Button)this.findViewById(R.id.button13);
swap.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
Intent myIntent = new Intent(KernelTuner.this, Swap.class);
KernelTuner.this.startActivity(myIntent);
}
});
Button profiles = (Button)this.findViewById(R.id.button12);
profiles.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
Intent myIntent = new Intent(KernelTuner.this, profiles.class);
KernelTuner.this.startActivity(myIntent);
}
});
Button thermald = (Button)this.findViewById(R.id.button11);
thermald.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
Intent myIntent = new Intent(KernelTuner.this, thermald.class);
KernelTuner.this.startActivity(myIntent);
}
});
Button about = (Button)this.findViewById(R.id.button15);
about.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
Intent myIntent = new Intent(KernelTuner.this, about.class);
KernelTuner.this.startActivity(myIntent);
}
});
Button sys = (Button)this.findViewById(R.id.button14);
sys.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
Intent myIntent = new Intent(KernelTuner.this, SystemInfo.class);
KernelTuner.this.startActivity(myIntent);
}
});
}
@Override
public void onPause() {
super.onPause();
}
@Override
protected void onResume()
{
this.registerReceiver(this.mBatInfoReceiver,
new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
initialCheck();
//new info().execute();
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
String boot = sharedPrefs.getString("boot", "");
if(boot.equals("init.d")){
initdExport();
}
else{
new Initd().execute(new String[] {"rm"});
}
super.onResume();
}
@Override
public void onStop() {
if (mBatInfoReceiver != null){
unregisterReceiver(mBatInfoReceiver);
mBatInfoReceiver = null;
}
super.onStop();
}
@Override
public void onDestroy() {
thread=false;
AppWidgetBig updateBig = new AppWidgetBig();
Context context = this;
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_4x4);
ComponentName thisWidget = new ComponentName(context, AppWidgetBig.class);
appWidgetManager.updateAppWidget(thisWidget, remoteViews);
int[] appWidgetIds = null;
updateBig.onUpdate(context, appWidgetManager, appWidgetIds);
AppWidget updateSmall = new AppWidget();
RemoteViews remoteViewsSmall = new RemoteViews(context.getPackageName(), R.layout.widget_2x1);
ComponentName thisWidgetSmall = new ComponentName(context, AppWidget.class);
appWidgetManager.updateAppWidget(thisWidgetSmall, remoteViewsSmall);
updateSmall.onUpdate(context, appWidgetManager, appWidgetIds);
super.onDestroy();
}
public void download(){
BroadcastReceiver onComplete=new BroadcastReceiver() {
@Override
public void onReceive(Context ctxt, Intent intent) {
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/" + "KernelTuner-" + remoteversion + ".apk")), "application/vnd.android.package-archive");
startActivity(intent);
}
};
String url = "http://kerneltuner.pedjaapps.in.rs/ktuner/KernelTuner-" + remoteversion + ".php";
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDescription("Downloading new version");
request.setTitle("Kernel Tuner-" + remoteversion + ".apk");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
try{
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "KernelTuner-" + remoteversion + ".apk");
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_NOTIFICATION_CLICKED));
}catch(Exception e){
Toast.makeText(getApplicationContext(), "SD card is not mounted", Toast.LENGTH_LONG).show();
}
}
public void changelog(){
preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String versionpref = preferences.getString("version", "");
try
{
PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
String version = pInfo.versionName;
if (!versionpref.equals(version)){
Intent myIntent = new Intent(KernelTuner.this, changelog.class);
KernelTuner.this.startActivity(myIntent);
}
SharedPreferences.Editor editor = preferences.edit();
editor.putString("version", version);
editor.commit();
}
catch (PackageManager.NameNotFoundException e)
{}
}
public void battTempWarning(){
Animation anim = new AlphaAnimation(0.0f, 1.0f);
anim.setDuration(500);
anim.setStartOffset(20);
anim.setRepeatMode(Animation.REVERSE);
anim.setRepeatCount(Animation.INFINITE);
batteryTemp.startAnimation(anim);
}
public void battTempWarningStop(){
batteryTemp.clearAnimation();
}
public void battLevelWarning(){
Animation anim = new AlphaAnimation(0.0f, 1.0f);
anim.setDuration(500);
anim.setStartOffset(20);
anim.setRepeatMode(Animation.REVERSE);
anim.setRepeatCount(Animation.INFINITE);
batteryLevel.startAnimation(anim);
}
public void battLevelWarningStop(){
batteryLevel.clearAnimation();
}
public void cpuTempWarning(){
Animation anim = new AlphaAnimation(0.0f, 1.0f);
anim.setDuration(500);
anim.setStartOffset(20);
anim.setRepeatMode(Animation.REVERSE);
anim.setRepeatCount(Animation.INFINITE);
cputemptxt.startAnimation(anim);
}
public void cpuTempWarningStop(){
cputemptxt.clearAnimation();
}
public void times(){
TextView deepSleep = (TextView)findViewById(R.id.textView31);
TextView uptime = (TextView)findViewById(R.id.textView30);
uptime.setText(CPUInfo.uptime());
deepSleep.setText(CPUInfo.deepSleep());
}
public void cpuTemp(){
cputemptxt = (TextView)findViewById(R.id.textView38);
TextView cputemptxte = (TextView)findViewById(R.id.textView37);
try {
File myFile = new File(
"/sys/class/thermal/thermal_zone1/temp");
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(new InputStreamReader(
fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
cputemp = aBuffer.trim();
if (tempPref.equals("fahrenheit"))
{
cputemp = String.valueOf((int)(Double.parseDouble(cputemp)*1.8)+32);
cputemptxt.setText(cputemp+"°F");
int temp = Integer.parseInt(cputemp);
if(temp<113){
cputemptxt.setTextColor(Color.GREEN);
cpuTempWarningStop();
}
else if(temp>=113 && temp<138){
cputemptxt.setTextColor(Color.YELLOW);
cpuTempWarningStop();
}
else if(temp>=138){
cpuTempWarning();
cputemptxt.setTextColor(Color.RED);
}
}
else if(tempPref.equals("celsius")){
cputemptxt.setVisibility(View.VISIBLE);
cputemptxte.setVisibility(View.VISIBLE);
cputemptxt.setText(cputemp+"°C");
int temp = Integer.parseInt(cputemp);
if(temp<45){
cputemptxt.setTextColor(Color.GREEN);
cpuTempWarningStop();
}
else if(temp>=45 && temp<=59){
cputemptxt.setTextColor(Color.YELLOW);
cpuTempWarningStop();
}
else if(temp>59){
cpuTempWarning();
cputemptxt.setTextColor(Color.RED);
}
}
myReader.close();
} catch (Exception e2) {
}
}
public void initialCheck(){
if(CPUInfo.cpu1Online()==true){
Button b2 = (Button) findViewById(R.id.button1);
b2.setVisibility(View.VISIBLE);
ProgressBar cpu1progbar = (ProgressBar)findViewById(R.id.progressBar2);
cpu1progbar.setVisibility(View.VISIBLE);
TextView tv1 = (TextView) findViewById(R.id.ptextView2);
tv1.setVisibility(View.VISIBLE);
TextView tv4 = (TextView) findViewById(R.id.ptextView4);
tv4.setVisibility(View.VISIBLE);
}
else{
Button b2 = (Button) findViewById(R.id.button1);
b2.setVisibility(View.GONE);
ProgressBar cpu1progbar = (ProgressBar)findViewById(R.id.progressBar2);
cpu1progbar.setVisibility(View.GONE);
TextView tv1 = (TextView) findViewById(R.id.ptextView2);
tv1.setVisibility(View.GONE);
TextView tv4 = (TextView) findViewById(R.id.ptextView4);
tv4.setVisibility(View.GONE);
}
if(CPUInfo.cpu2Online()==true){
Button b3 = (Button) findViewById(R.id.button8);
b3.setVisibility(View.VISIBLE);
ProgressBar cpu1progbar = (ProgressBar)findViewById(R.id.progressBar3);
cpu1progbar.setVisibility(View.VISIBLE);
TextView tv1 = (TextView) findViewById(R.id.ptextView5);
tv1.setVisibility(View.VISIBLE);
TextView tv4 = (TextView) findViewById(R.id.ptextView7);
tv4.setVisibility(View.VISIBLE);
}
else{
Button b3 = (Button) findViewById(R.id.button8);
b3.setVisibility(View.GONE);
ProgressBar cpu1progbar = (ProgressBar)findViewById(R.id.progressBar3);
cpu1progbar.setVisibility(View.GONE);
TextView tv1 = (TextView) findViewById(R.id.ptextView5);
tv1.setVisibility(View.GONE);
TextView tv4 = (TextView) findViewById(R.id.ptextView7);
tv4.setVisibility(View.GONE);
}
if(CPUInfo.cpu3Online()==true){
Button b4 = (Button) findViewById(R.id.button9);
b4.setVisibility(View.VISIBLE);
ProgressBar cpu1progbar = (ProgressBar)findViewById(R.id.progressBar4);
cpu1progbar.setVisibility(View.VISIBLE);
TextView tv1 = (TextView) findViewById(R.id.ptextView6);
tv1.setVisibility(View.VISIBLE);
TextView tv4 = (TextView) findViewById(R.id.ptextView8);
tv4.setVisibility(View.VISIBLE);
}
else{
Button b4 = (Button) findViewById(R.id.button9);
b4.setVisibility(View.GONE);
ProgressBar cpu1progbar = (ProgressBar)findViewById(R.id.progressBar4);
cpu1progbar.setVisibility(View.GONE);
TextView tv1 = (TextView) findViewById(R.id.ptextView6);
tv1.setVisibility(View.GONE);
TextView tv4 = (TextView) findViewById(R.id.ptextView8);
tv4.setVisibility(View.GONE);
}
File file4 = new File("/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies");
File file5 = new File("/sys/devices/system/cpu/cpu0/cpufreq/stats/time_in_state");
try{
InputStream fIn = new FileInputStream(file4);
}
catch(FileNotFoundException e){
try{
InputStream fIn = new FileInputStream(file5);
}
catch(FileNotFoundException e2){
Button cpu = (Button)findViewById(R.id.button2);
cpu.setVisibility(View.GONE);
}
}
File file = new File(CPUInfo.VOLTAGE_PATH);
try{
InputStream fIn = new FileInputStream(file);
}
catch(FileNotFoundException e){
File file2 = new File(CPUInfo.VOLTAGE_PATH_TEGRA_3);
try{
InputStream fIn = new FileInputStream(file2);
}
catch(FileNotFoundException ex){
Button voltage = (Button)findViewById(R.id.button6);
voltage.setVisibility(View.GONE);
}
}
File file2 = new File("/sys/devices/system/cpu/cpu0/cpufreq/stats/time_in_state");
try{
InputStream fIn = new FileInputStream(file2);
}
catch(FileNotFoundException e){
Button times = (Button)findViewById(R.id.button5);
times.setVisibility(View.GONE);
}
File file3 = new File("/sys/devices/platform/kgsl-3d0.0/kgsl/kgsl-3d0/gpuclk");
try{
InputStream fIn = new FileInputStream(file3);
}
catch(FileNotFoundException e){
Button gpu = (Button)findViewById(R.id.button3);
gpu.setVisibility(View.GONE);
}
File file6 = new File("/sys/kernel/msm_mpdecision/conf/enabled");
try{
InputStream fIn = new FileInputStream(file6);
}
catch(FileNotFoundException e){
Button mpdec = (Button)findViewById(R.id.button7);
mpdec.setVisibility(View.GONE);
}
File file7 = new File("/sys/kernel/msm_thermal/conf/allowed_low_freq");
try{
InputStream fIn = new FileInputStream(file7);
}
catch(FileNotFoundException e){
Button td = (Button)findViewById(R.id.button11);
td.setVisibility(View.GONE);
}
}
public void ReadCPU0Clock()
{
try {
File myFile = new File(CPU0_CURR_FREQ);
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
iscVa = aBuffer;
myReader.close();
} catch (Exception e) {
iscVa = "offline";
}
cpu0progress();
cpu0update();
}
public void ReadCPU1Clock()
{
try {
File myFile = new File(CPU1_CURR_FREQ);
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
iscVa2 = aBuffer;
myReader.close();
} catch (Exception e) {
iscVa2 = "offline";
}
cpu1progress();
cpu1update();
}
public void ReadCPU2Clock()
{
try {
File myFile = new File(CPU2_CURR_FREQ);
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
freqcpu2 = aBuffer;
myReader.close();
} catch (Exception e) {
freqcpu2="offline";
}
cpu2progress();
cpu2update();
}
public void ReadCPU3Clock()
{
try {
File myFile = new File(CPU3_CURR_FREQ);
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
freqcpu3 = aBuffer;
myReader.close();
} catch (Exception e) {
freqcpu3 = "offline";
}
cpu3progress();
cpu3update();
}
public void initdExport(){
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
String gpu3d = sharedPrefs.getString("gpu3d", "");
String gpu2d = sharedPrefs.getString("gpu2d", "");
String hw = sharedPrefs.getString("hw", "");
String cdepth = sharedPrefs.getString("cdepth", "");
String cpu1min = sharedPrefs.getString("cpu1min", "");
String cpu1max = sharedPrefs.getString("cpu1max", "");
String cpu0max = sharedPrefs.getString("cpu0max", "");
String cpu0min = sharedPrefs.getString("cpu0min", "");
String cpu3min = sharedPrefs.getString("cpu3min", "");
String cpu3max = sharedPrefs.getString("cpu3max", "");
String cpu2max = sharedPrefs.getString("cpu2max", "");
String cpu2min = sharedPrefs.getString("cpu2min", "");
String fastcharge = sharedPrefs.getString("fastcharge", "");
String mpdecisionscroff = sharedPrefs.getString("mpdecisionscroff", "");
String backbuff = sharedPrefs.getString("backbuf", "");
String vsync = sharedPrefs.getString("vsync", "");
String led = sharedPrefs.getString("led", "");
String cpu0gov = sharedPrefs.getString("cpu0gov", "");
String cpu1gov = sharedPrefs.getString("cpu1gov", "");
String cpu2gov = sharedPrefs.getString("cpu2gov", "");
String cpu3gov = sharedPrefs.getString("cpu3gov", "");
String io = sharedPrefs.getString("io", "");
String sdcache = sharedPrefs.getString("sdcache", "");
String delaynew = sharedPrefs.getString("delaynew", "");
String pausenew = sharedPrefs.getString("pausenew", "");
String thruploadnew = sharedPrefs.getString("thruploadnew", "");
String thrupmsnew = sharedPrefs.getString("thrupmsnew", "");
String thrdownloadnew = sharedPrefs.getString("thrdownloadnew", "");
String thrdownmsnew = sharedPrefs.getString("thrdownmsnew", "");
String ldt = sharedPrefs.getString("ldt", "");
String s2w = sharedPrefs.getString("s2w", "");
String s2wStart = sharedPrefs.getString("s2wStart","");
String s2wEnd = sharedPrefs.getString("s2wEnd","");
String p1freq = sharedPrefs.getString("p1freq", "");
String p2freq = sharedPrefs.getString("p2freq", "");
String p3freq = sharedPrefs.getString("p3freq", "");
String p1low = sharedPrefs.getString("p1low", "");
String p1high = sharedPrefs.getString("p1high", "");
String p2low = sharedPrefs.getString("p2low", "");
String p2high = sharedPrefs.getString("p2high", "");
String p3low = sharedPrefs.getString("p3low", "");
String p3high = sharedPrefs.getString("p3high", "");
boolean swap = sharedPrefs.getBoolean("swap",false);
String swapLocation = sharedPrefs.getString("swap_location","");
String swappiness = sharedPrefs.getString("swappiness","");
StringBuilder gpubuilder = new StringBuilder();
gpubuilder.append("#!/system/bin/sh");
gpubuilder.append("\n");
if(!gpu3d.equals("")){
gpubuilder.append("echo " + "\""+gpu3d + "\""+" > /sys/devices/platform/kgsl-3d0.0/kgsl/kgsl-3d0/max_gpuclk");
gpubuilder.append("\n");
}
if(!gpu2d.equals("")){
gpubuilder.append("echo " + "\""+gpu2d + "\""+" > /sys/devices/platform/kgsl-2d0.0/kgsl/kgsl-2d0/max_gpuclk");
gpubuilder.append("\n");
gpubuilder.append("echo " + "\""+gpu2d + "\""+" > /sys/devices/platform/kgsl-2d1.1/kgsl/kgsl-2d1/max_gpuclk");
gpubuilder.append("\n");
}
String gpu = gpubuilder.toString();
StringBuilder cpubuilder = new StringBuilder();
cpubuilder.append("#!/system/bin/sh");
cpubuilder.append("\n");
/**
* cpu0
* */
if(!cpu0gov.equals("")){
cpubuilder.append("chmod 666 /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor \n" +
"echo " + "\""+cpu0gov+"\"" + " > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor\n");
}
if(!cpu0max.equals("")){
cpubuilder.append("chmod 666 /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq \n" +
"echo " + "\""+cpu0max + "\""+" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq \n");
}
if(!cpu0min.equals("")){
cpubuilder.append("chmod 666 /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq \n" +
"echo " + "\""+cpu0min + "\""+" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq \n\n");
}
/**
* cpu1
* */
if(!cpu1gov.equals("")){
cpubuilder.append("chmod 666 /sys/devices/system/cpu/cpu1/cpufreq/scaling_governor \n" +
"echo " + "\""+cpu1gov+"\"" + " > /sys/devices/system/cpu/cpu1/cpufreq/scaling_governor\n");
}
if(!cpu1max.equals("")){
cpubuilder.append("chmod 666 /sys/devices/system/cpu/cpu1/cpufreq/scaling_max_freq \n" +
"echo " + "\""+cpu1max + "\""+" > /sys/devices/system/cpu/cpu1/cpufreq/scaling_max_freq \n");
}
if(!cpu1min.equals("")){
cpubuilder.append("chmod 666 /sys/devices/system/cpu/cpu1/cpufreq/scaling_min_freq \n" +
"echo " + "\""+cpu1min + "\""+" > /sys/devices/system/cpu/cpu1/cpufreq/scaling_min_freq \n\n");
}
/**
* cpu2
* */
if(!cpu2gov.equals("")){
cpubuilder.append("chmod 666 /sys/devices/system/cpu/cpu2/cpufreq/scaling_governor \n" +
"echo " + "\""+cpu2gov+"\"" + " > /sys/devices/system/cpu/cpu2/cpufreq/scaling_governor\n");
}
if(!cpu2max.equals("")){
cpubuilder.append("chmod 666 /sys/devices/system/cpu/cpu2/cpufreq/scaling_max_freq \n" +
"echo " + "\""+cpu2max + "\""+" > /sys/devices/system/cpu/cpu2/cpufreq/scaling_max_freq \n");
}
if(!cpu2min.equals("")){
cpubuilder.append("chmod 666 /sys/devices/system/cpu/cpu2/cpufreq/scaling_min_freq \n" +
"echo " + "\""+cpu2min + "\""+" > /sys/devices/system/cpu/cpu2/cpufreq/scaling_min_freq \n\n");
}
/**
* cpu3
* */
if(!cpu3gov.equals("")){
cpubuilder.append("chmod 666 /sys/devices/system/cpu/cpu3/cpufreq/scaling_governor \n" +
"echo " + "\""+cpu3gov+"\"" + " > /sys/devices/system/cpu/cpu3/cpufreq/scaling_governor\n");
}
if(!cpu3max.equals("")){
cpubuilder.append("chmod 666 /sys/devices/system/cpu/cpu3/cpufreq/scaling_max_freq \n" +
"echo " + "\""+cpu3max + "\""+" > /sys/devices/system/cpu/cpu3/cpufreq/scaling_max_freq \n");
}
if(!cpu3min.equals("")){
cpubuilder.append("chmod 666 /sys/devices/system/cpu/cpu3/cpufreq/scaling_min_freq \n" +
"echo " + "\""+cpu3min + "\""+" > /sys/devices/system/cpu/cpu3/cpufreq/scaling_min_freq \n\n");
}
List<String> govSettings = CPUInfo.govSettings();
List<String> availableGovs = CPUInfo.availableGovs();
for(String s : availableGovs){
for(String st : govSettings){
String temp = sharedPrefs.getString(s+"_"+st, "");
if(!temp.equals("")){
cpubuilder.append("chmod 777 /sys/devices/system/cpu/cpufreq/" + s + "/" + st + "\n");
cpubuilder.append("echo " + "\""+temp+"\"" + " > /sys/devices/system/cpu/cpufreq/" + s + "/" + st + "\n");
}
}
}
String cpu = cpubuilder.toString();
StringBuilder miscbuilder = new StringBuilder();
miscbuilder.append("#!/system/bin/sh \n\n"+"#mount debug filesystem\n"+
"mount -t debugfs debugfs /sys/kernel/debug \n\n");
if(!vsync.equals("")){
miscbuilder.append("#vsync\n"+
"chmod 777 /sys/kernel/debug/msm_fb/0/vsync_enable \n"+
"chmod 777 /sys/kernel/debug/msm_fb/0/hw_vsync_mode \n"+
"chmod 777 /sys/kernel/debug/msm_fb/0/backbuff \n"+
"echo " + "\""+vsync + "\""+" > /sys/kernel/debug/msm_fb/0/vsync_enable \n"+
"echo " + "\""+hw + "\""+" > /sys/kernel/debug/msm_fb/0/hw_vsync_mode \n" +
"echo " + "\""+backbuff + "\""+" > /sys/kernel/debug/msm_fb/0/backbuff \n\n");
}
if(!led.equals("")){
miscbuilder.append("#capacitive buttons backlight\n"+"chmod 777 /sys/devices/platform/leds-pm8058/leds/button-backlight/currents \n"+
"echo " +"\""+ led + "\""+" > /sys/devices/platform/leds-pm8058/leds/button-backlight/currents \n\n");
}
if(!fastcharge.equals("")){
miscbuilder.append("#fastcharge\n"+"chmod 777 /sys/kernel/fast_charge/force_fast_charge \n"+
"echo " + "\""+fastcharge + "\""+" > /sys/kernel/fast_charge/force_fast_charge \n\n" );
}
if(!cdepth.equals("")){
miscbuilder.append("#color depth\n"+"chmod 777 /sys/kernel/debug/msm_fb/0/bpp \n"+
"echo " + "\""+cdepth + "\""+" > /sys/kernel/debug/msm_fb/0/bpp \n\n");
}
if(!mpdecisionscroff.equals("")){
miscbuilder.append("chmod 777 /sys/kernel/msm_mpdecision/conf/scroff_single_core \n"+
"echo " + "\""+mpdecisionscroff + "\""+" > /sys/kernel/msm_mpdecision/conf/scroff_single_core \n");
}
if(!delaynew.equals("")){
miscbuilder.append("chmod 777 /sys/kernel/msm_mpdecision/conf/delay \n"+
"echo " + "\""+delaynew.trim() + "\""+" > /sys/kernel/msm_mpdecision/conf/delay \n");
}
if(!pausenew.equals("")){
miscbuilder.append("chmod 777 /sys/kernel/msm_mpdecision/conf/pause \n"+
"echo " + "\""+pausenew.trim() + "\""+" > /sys/kernel/msm_mpdecision/conf/pause \n");
}
if(!thruploadnew.equals("")){
miscbuilder.append("chmod 777 /sys/kernel/msm_mpdecision/conf/nwns_threshold_up \n"+
"echo " + "\""+thruploadnew.trim() + "\""+" > /sys/kernel/msm_mpdecision/conf/nwns_threshold_up \n");
}
if(!thrdownloadnew.equals("")){
miscbuilder.append("chmod 777 /sys/kernel/msm_mpdecision/conf/nwns_threshold_down \n"+
"echo " + "\""+thrdownloadnew.trim() + "\""+" > /sys/kernel/msm_mpdecision/conf/nwns_threshold_down \n");
}
if(!thrupmsnew.equals("")){
miscbuilder.append("chmod 777 /sys/kernel/msm_mpdecision/conf/twts_threshold_up"+
"echo " + "\""+thrupmsnew.trim() + "\""+" > /sys/kernel/msm_mpdecision/conf/twts_threshold_up \n");
}
if(!thrdownmsnew.equals("")){
miscbuilder.append("chmod 777 /sys/kernel/msm_mpdecision/conf/twts_threshold_down"+
"echo " + "\""+thrdownmsnew.trim() + "\""+" > /sys/kernel/msm_mpdecision/conf/twts_threshold_down \n\n");
}
if(!sdcache.equals("")){
miscbuilder.append("#sd card cache size\n"+
"chmod 777 /sys/block/mmcblk1/queue/read_ahead_kb \n" +
"chmod 777 /sys/block/mmcblk0/queue/read_ahead_kb \n" +
"chmod 777 /sys/devices/virtual/bdi/179:0/read_ahead_kb \n" +
"echo " + "\""+sdcache + "\""+" > /sys/block/mmcblk1/queue/read_ahead_kb \n"+
"echo " + "\""+sdcache + "\""+" > /sys/block/mmcblk0/queue/read_ahead_kb \n"+
"echo " + "\""+sdcache + "\""+" > /sys/devices/virtual/bdi/179:0/read_ahead_kb \n\n");
}
if(!io.equals("")){
miscbuilder.append("#IO scheduler\n"+
"chmod 777 /sys/block/mmcblk0/queue/scheduler \n"+
"chmod 777 /sys/block/mmcblk1/queue/scheduler \n"+
"echo " + "\""+io + "\""+" > /sys/block/mmcblk0/queue/scheduler \n"+
"echo " +"\""+ io + "\""+" > /sys/block/mmcblk1/queue/scheduler \n\n");
}
if(!ldt.equals("")){
miscbuilder.append("#Notification LED Timeout\n"+
"chmod 777 /sys/kernel/notification_leds/off_timer_multiplier\n"+
"echo " + "\""+ldt + "\""+" > /sys/kernel/notification_leds/off_timer_multiplier\n\n");
}
if(!s2w.equals("")){
miscbuilder.append("#Sweep2Wake\n"+
"chmod 777 /sys/android_touch/sweep2wake\n"+
"echo " + "\""+s2w + "\""+" > /sys/android_touch/sweep2wake\n\n");
}
if(!s2wStart.equals("")){
miscbuilder.append("chmod 777 /sys/android_touch/sweep2wake_startbutton\n"+
"echo "+ s2wStart + " > /sys/android_touch/sweep2wake_startbutton\n"+
"chmod 777 /sys/android_touch/sweep2wake_endbutton\n"+
"echo "+ s2wEnd + " > /sys/android_touch/sweep2wake_endbutton\n\n");
}
if(!p1freq.trim().equals("")){
miscbuilder.append("chmod 777 /sys/kernel/msm_thermal/conf/allowed_low_freq\n"+
"echo " + "\""+p1freq.trim() + "\"" + " > /sys/kernel/msm_thermal/conf/allowed_low_freq\n");
}
if(!p2freq.trim().equals("")){
miscbuilder.append("chmod 777 /sys/kernel/msm_thermal/conf/allowed_mid_freq\n"+
"echo " + "\""+p2freq.trim() + "\"" + " > /sys/kernel/msm_thermal/conf/allowed_mid_freq\n");
}
if(!p3freq.trim().equals("")){
miscbuilder.append("chmod 777 /sys/kernel/msm_thermal/conf/allowed_max_freq\n"+
"echo " + "\""+p3freq.trim() + "\"" + " > /sys/kernel/msm_thermal/conf/allowed_max_freq\n");
}
if(!p1low.trim().equals("")){
miscbuilder.append("chmod 777 /sys/kernel/msm_thermal/conf/allowed_low_low\n"+
"echo " + "\""+p1low.trim() + "\"" + " > /sys/kernel/msm_thermal/conf/allowed_low_low\n");
}
if(!p1high.trim().equals("")){
miscbuilder.append("chmod 777 /sys/kernel/msm_thermal/conf/allowed_low_high\n"+
"echo " + "\""+p1high.trim() + "\"" + " > /sys/kernel/msm_thermal/conf/allowed_low_high\n");
}
if(!p2low.trim().equals("")){
miscbuilder.append("chmod 777 /sys/kernel/msm_thermal/conf/allowed_mid_low\n"+
"echo " + "\""+p2low.trim() + "\"" + " > /sys/kernel/msm_thermal/conf/allowed_mid_low\n");
}
if(!p2high.trim().equals("")){
miscbuilder.append("chmod 777 /sys/kernel/msm_thermal/conf/allowed_mid_high\n"+
"echo " + "\""+p2high.trim() + "\"" + " > /sys/kernel/msm_thermal/conf/allowed_mid_high\n");
}
if(!p3low.trim().equals("")){
miscbuilder.append("chmod 777 /sys/kernel/msm_thermal/conf/allowed_high_low\n"+
"echo " + "\""+p3low.trim() + "\"" + " > /sys/kernel/msm_thermal/conf/allowed_high_low\n");
}
if(!p3high.trim().equals("")){
miscbuilder.append("chmod 777 /sys/kernel/msm_thermal/conf/allowed_high_high\n"+
"echo " + "\""+p3high.trim() + "\"" + " > /sys/kernel/msm_thermal/conf/allowed_high_high\n\n");
}
if(swap==true){
miscbuilder.append("echo "+swappiness+" > /proc/sys/vm/swappiness\n"
+"swapon "+swapLocation.trim()+"/swap"+"\n"
);
}
else if(swap==false){
miscbuilder.append("swapoff "+swapLocation.trim()+"/swap"+"\n\n");
}
miscbuilder.append("#Umount debug filesystem\n"+
"umount /sys/kernel/debug \n");
String misc = miscbuilder.toString();
StringBuilder voltagebuilder = new StringBuilder();
voltagebuilder.append("#!/system/bin/sh \n");
for(String s : CPUInfo.voltageFreqs()){
String temp = sharedPrefs.getString("voltage_"+s, "");
if(!temp.equals("")){
voltagebuilder.append("echo " + "\""+temp+"\"" + " > /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n");
}
}
String voltage = voltagebuilder.toString();
try {
FileOutputStream fOut = openFileOutput("99ktcputweaks",
MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(cpu);
osw.flush();
osw.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
try {
FileOutputStream fOut = openFileOutput("99ktgputweaks",
MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(gpu);
osw.flush();
osw.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
try {
FileOutputStream fOut = openFileOutput("99ktmisctweaks",
MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(misc);
osw.flush();
osw.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
try {
FileOutputStream fOut = openFileOutput("99ktvoltage",
MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(voltage);
osw.flush();
osw.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
new Initd().execute(new String[] {"apply"});
}
public void readFreqs()
{
try {
File myFile = new File(CPU0_FREQS);
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
freqs = aBuffer;
myReader.close();
freqlist = Arrays.asList(freqs.split("\\s"));
if(Integer.parseInt(frequencies.get(0))>Integer.parseInt(frequencies.get(frequencies.size()))){
Collections.reverse(freqlist);
}
} catch (Exception e) {
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("/sys/devices/system/cpu/cpu0/cpufreq/stats/time_in_state");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
delims = strLine.split(" ");
String freq = delims[0];
//freq= freq.substring(0, freq.length()-3)+"Mhz";
frequencies.add(freq);
}
/*SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean ov = sharedPrefs.getBoolean("override", false);
if(ov==true){
Collections.reverse(frequencies);
}*/
if(frequencies.get(0).length()>frequencies.get(frequencies.size()-1).length()){
Collections.reverse(frequencies);
}
//System.out.println();
String[] strarray = frequencies.toArray(new String[0]);
frequencies.clear();
//System.out.println(frequencies);
StringBuilder builder = new StringBuilder();
for(String s : strarray) {
builder.append(s);
builder.append(" ");
}
freqs = builder.toString();
freqlist = Arrays.asList(freqs.split("\\s"));
in.close();
}
catch(Exception ee){
//System.out.println("failed to read frequencies");
}
}
}
public void ReadCPU0maxfreq()
{
try {
File myFile = new File(CPU0_MAX_FREQ);
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
cpu0max = aBuffer;
myReader.close();
;
} catch (Exception e) {
}
}
public void ReadCPU1maxfreq()
{
try {
File myFile = new File(CPU1_MAX_FREQ);
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
cpu1max = aBuffer;
myReader.close();
;
} catch (Exception e) {
}
}
public void ReadCPU2maxfreq()
{
try {
File myFile = new File(CPU2_MAX_FREQ);
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
cpu2max = aBuffer;
myReader.close();
;
} catch (Exception e) {
}
}
public void ReadCPU3maxfreq()
{
try {
File myFile = new File(CPU3_MAX_FREQ);
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
cpu3max = aBuffer;
myReader.close();
;
} catch (Exception e) {
}
}
public void cpu0update()
{
TextView cpu0prog = (TextView)this.findViewById(R.id.ptextView3);
cpu0prog.setText(iscVa.trim());
}
public void cpu0progress()
{
ProgressBar cpu0progbar = (ProgressBar)findViewById(R.id.progressBar1);
cpu0progbar.setMax(freqlist.indexOf(cpu0max.trim())+1);
cpu0progbar.setProgress(freqlist.indexOf(iscVa.trim())+1);
}
public void cpu1update()
{
TextView cpu1prog = (TextView)this.findViewById(R.id.ptextView4);
cpu1prog.setText(iscVa2.trim());
}
public void cpu1progress()
{
ProgressBar cpu1progbar = (ProgressBar)findViewById(R.id.progressBar2);
cpu1progbar.setMax(freqlist.indexOf(cpu1max.trim())+1);
cpu1progbar.setProgress(freqlist.indexOf(iscVa2.trim())+1);
}
public void cpu2update()
{
TextView cpu2prog = (TextView)this.findViewById(R.id.ptextView7);
cpu2prog.setText(freqcpu2.trim());
}
public void cpu2progress()
{
ProgressBar cpu2progbar = (ProgressBar)findViewById(R.id.progressBar3);
cpu2progbar.setMax(freqlist.indexOf(cpu2max.trim())+1);
cpu2progbar.setProgress(freqlist.indexOf(freqcpu2.trim())+1);
}
public void cpu3update()
{
TextView cpu3prog = (TextView)this.findViewById(R.id.ptextView8);
cpu3prog.setText(freqcpu3.trim());
}
public void cpu3progress()
{
ProgressBar cpu3progbar = (ProgressBar)findViewById(R.id.progressBar4);
cpu3progbar.setMax(freqlist.indexOf(cpu3max.trim())+1);
cpu3progbar.setProgress(freqlist.indexOf(freqcpu3.trim())+1);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options, menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu (Menu menu) {
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.settings) {
startActivity(new Intent(this, Preferences.class));
}
if (item.getItemId() == R.id.changelog) {
startActivity(new Intent(this, changelog.class));
}
if (item.getItemId() == R.id.update) {
new updateCheck().execute();
Calendar updateTime = Calendar.getInstance();
updateTime.setTimeZone(TimeZone.getTimeZone("GMT"));
updateTime.set(Calendar.HOUR_OF_DAY, 13);
updateTime.set(Calendar.MINUTE, 00);
Intent updateService = new Intent(this, AlarmReceiver.class);
PendingIntent recurringDownload = PendingIntent.getBroadcast(this,
0, updateService, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarms = (AlarmManager) getSystemService(
ALARM_SERVICE);
alarms.setInexactRepeating(AlarmManager.RTC_WAKEUP,
updateTime.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, recurringDownload);
}
if (item.getItemId() == R.id.check) {
startActivity(new Intent(this, check.class));
}
return super.onOptionsItemSelected(item);
}
}
| false | false | null | null |
diff --git a/framework/src/play/i18n/Messages.java b/framework/src/play/i18n/Messages.java
index 287af7eb..6d7971a8 100644
--- a/framework/src/play/i18n/Messages.java
+++ b/framework/src/play/i18n/Messages.java
@@ -1,178 +1,177 @@
package play.i18n;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import play.Logger;
import play.Play;
import play.data.binding.Binder;
/**
* I18n Helper
* <p>
* translation are defined as properties in /conf/messages.<em>locale</em> files
* with locale being the i18n country code fr, en, fr_FR
*
* <pre>
* # /conf/messages.fr
* hello=Bonjour, %s !
* </pre>
* <code>
* Messages.get( "hello", "World"); // => "Bonjour, World !"
* </code>
*
*/
public class Messages {
- private static final Object[] NO_ARGS = new Object[]{""};
+ private static final Object[] NO_ARGS = new Object[]{null};
static public Properties defaults;
static public Map<String, Properties> locales = new HashMap<String, Properties>();
static Pattern recursive = Pattern.compile("&\\{(.*?)\\}");
/**
* Given a message code, translate it using current locale.
* If there is no message in the current locale for the given key, the key
* is returned.
*
* @param key the message code
* @param args optional message format arguments
* @return translated message
*/
public static String get(Object key, Object... args) {
return getMessage(Lang.get(), key, args);
}
/**
* Return several messages for a locale
* @param locale the locale code, e.g. fr, fr_FR
* @param keys the keys to get messages from. Wildcards can be used at the end: {'title', 'login.*'}
* @returnmessages as a {@link java.util.Properties java.util.Properties}
*/
public static Properties find(String locale, Set<String> keys) {
Properties result = new Properties();
Properties all = all(locale);
// Expand the set for wildcards
Set<String> wildcards = new HashSet<String>();
for (String key: keys) {
if (key.endsWith("*")) wildcards.add(key);
}
for (String key: wildcards) {
keys.remove(key);
String start = key.substring(0, key.length() - 1);
for (Object key2: all.keySet()) {
if (((String)key2).startsWith(start)) {
keys.add((String)key2);
}
}
}
// Build the result
for (Object key: all.keySet()) {
if (keys.contains(key)) {
result.put(key, all.get(key));
}
}
return result;
}
public static String getMessage(String locale, Object key, Object... args) {
// Check if there is a plugin that handles translation
String message = Play.pluginCollection.getMessage(locale, key, args);
if(message != null) {
return message;
}
String value = null;
if( key == null ) {
return "";
}
if (locales.containsKey(locale)) {
value = locales.get(locale).getProperty(key.toString());
}
if (value == null) {
value = defaults.getProperty(key.toString());
}
if (value == null) {
value = key.toString();
}
return formatString(value, args);
}
public static String formatString(String value, Object... args) {
String message = String.format(value, coolStuff(value, args));
Matcher matcher = recursive.matcher(message);
StringBuffer sb = new StringBuffer();
while(matcher.find()) {
matcher.appendReplacement(sb, get(matcher.group(1)));
}
matcher.appendTail(sb);
return sb.toString();
}
static Pattern formatterPattern = Pattern.compile("%((\\d+)\\$)?([-#+ 0,(]+)?(\\d+)?([.]\\d+)?([bBhHsScCdoxXeEfgGaAtT])");
@SuppressWarnings("unchecked")
static Object[] coolStuff(String pattern, Object[] args) {
// when invoked with a null argument we get a null args instead of an array with a null value.
- if(args == null || args.length == 0)
+ if(args == null)
return NO_ARGS;
Class<? extends Number>[] conversions = new Class[args.length];
Matcher matcher = formatterPattern.matcher(pattern);
int incrementalPosition = 1;
while(matcher.find()) {
String conversion = matcher.group(6);
Integer position;
if(matcher.group(2) == null) {
position = incrementalPosition++;
} else {
position = Integer.parseInt(matcher.group(2));
}
if(conversion.equals("d") && position <= conversions.length) {
conversions[position-1] = Long.class;
}
if(conversion.equals("f") && position <= conversions.length) {
conversions[position-1] = Double.class;
}
}
- List<Object> result = new ArrayList<Object>();
- for(int i = 0; i < args.length; i++) {
+ Object[] result = new Object[args.length];
+ for(int i=0; i<args.length; i++) {
if(args[i] == null) {
continue;
}
if(conversions[i] == null) {
- result.add(args[i]);
+ result[i] = args[i];
} else {
try {
// TODO: I think we need to type of direct bind -> primitive and object binder
- result.add(Binder.directBind(null, args[i] + "", conversions[i], null));
+ result[i] = Binder.directBind(null, args[i] + "", conversions[i], null);
} catch(Exception e) {
// Ignore
+ result[i] = null;
}
}
}
- if (result.size() > 0)
- return result.toArray(new Object[result.size()]);
- return NO_ARGS;
+ return result;
}
/**
* return all messages for a locale
* @param locale the locale code eg. fr, fr_FR
* @return messages as a {@link java.util.Properties java.util.Properties}
*/
public static Properties all(String locale) {
if(locale == null || "".equals(locale))
return defaults;
return locales.get(locale);
}
}
| false | false | null | null |
diff --git a/FoundItMobile/src/com/example/foundit/FoundItActivity.java b/FoundItMobile/src/com/example/foundit/FoundItActivity.java
index b4236e8..9d86cf6 100644
--- a/FoundItMobile/src/com/example/foundit/FoundItActivity.java
+++ b/FoundItMobile/src/com/example/foundit/FoundItActivity.java
@@ -1,249 +1,259 @@
package com.example.foundit;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
+import org.apache.http.params.BasicHttpParams;
+import org.apache.http.params.HttpConnectionParams;
+import org.apache.http.params.HttpParams;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class FoundItActivity extends Activity {
File f;
Boolean tookPhoto = false;
EditText nameField;
EditText descField;
ImageView takenPhoto;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_found_it);
ActionBar actionBar = getActionBar();
actionBar.setIcon(R.drawable.foundit_final_small);
actionBar.setTitle("");
actionBar.setBackgroundDrawable(new ColorDrawable(Color.rgb(117, 150, 194)));
takenPhoto = (ImageView) findViewById(R.id.takenPhoto);
takenPhoto.setVisibility(8);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_found_it, menu);
return true;
}
public void uploadItem(View view){
//boolean cool = false;
String name = ((EditText)findViewById(R.id.nameField)).getText().toString();
String description = ((EditText)findViewById(R.id.descriptionField)).getText().toString();
if(name.length() < 3)
{
Toast toast = Toast.makeText(FoundItActivity.this, "Length of the name must be greater than 3 characters", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
TextView v = (TextView) toast.getView().findViewById(android.R.id.message);
v.setGravity(Gravity.CENTER);
toast.show();
}
else if(description.length() <10)
{
Toast toast = Toast.makeText(FoundItActivity.this, "Length of the description must be greater than 10 characters", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
TextView v = (TextView) toast.getView().findViewById(android.R.id.message);
v.setGravity(Gravity.CENTER);
toast.show();
}
else if(tookPhoto == false){
Toast toast = Toast.makeText(FoundItActivity.this, "Please select an image to upload", Toast.LENGTH_LONG);
TextView v = (TextView) toast.getView().findViewById(android.R.id.message);
v.setGravity(Gravity.CENTER);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
else
{
InfoTask info = new InfoTask();
info.execute();
}
}
//called to launch camera application
public void uploadPhoto(View view){
Uri imgUri = null;
//this is how to handle the photo upload
try {
f = File.createTempFile("tmp", ".jpg", Environment.getExternalStorageDirectory());
imgUri = Uri.fromFile(f);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imgUri);
takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
startActivityForResult(takePictureIntent, 1);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
tookPhoto = true;
takenPhoto.setVisibility(1);
Bitmap image = BitmapFactory.decodeFile(f.toString());
float width = image.getWidth();
float height = image.getHeight();
Bitmap compressedImage;
if(width > height){
compressedImage = Bitmap.createScaledBitmap(image, 600, 400, false);
}
else{
compressedImage = Bitmap.createScaledBitmap(image, 400, 600, false);
}
//ByteArrayOutputStream out = new ByteArrayOutputStream();
System.out.println(image.getByteCount());
/*image.compress(Bitmap.CompressFormat.PNG, 5, out);
Bitmap compressedImage = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));*/
System.out.println(compressedImage.getByteCount());
takenPhoto.setImageBitmap(compressedImage);
}
}
private class InfoTask extends AsyncTask<Void, Void, String[]> {
ProgressDialog progress;
Boolean uploadSuccessful = false;
@Override
protected void onPostExecute(String[] result) {
progress.dismiss();
String message;
if(!tookPhoto){
message = "Please take a photo to upload";
AlertDialog.Builder builder = new AlertDialog.Builder(FoundItActivity.this);
builder.setMessage(message);
builder.setCancelable(false);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do things
//finish();
}
});
AlertDialog alert = builder.create();
//alert.show();
}
else{
if (uploadSuccessful){
message = "Your upload was successful!";
}
else {
message = "Your upload failed :(";
}
AlertDialog.Builder builder = new AlertDialog.Builder(FoundItActivity.this);
builder.setMessage(message);
builder.setCancelable(false);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do things
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
@Override
protected void onPreExecute() {
progress = ProgressDialog.show(FoundItActivity.this, "","Loading...");
}
@Override
protected String[] doInBackground(Void... params) {
// TODO Auto-generated method stub
nameField = (EditText)findViewById(R.id.nameField);
String name = nameField.getText().toString();
descField = (EditText)findViewById(R.id.descriptionField);
String description = descField.getText().toString();
String noNewLineDescription;
if((description.length() - (description.replaceAll("\\n","").length())) > 6){
noNewLineDescription = description.replaceAll("\\n", " ");
}
else
noNewLineDescription = description;
- HttpClient client = new DefaultHttpClient();
+ //two different timeouts 1 for the tsp connection, the other after if has been established and there is failure to deliver byte stream
+ final HttpParams httpParams = new BasicHttpParams();
+ HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
+ HttpConnectionParams.setSoTimeout(httpParams, 15000);
+
+ HttpClient client = new DefaultHttpClient(httpParams);
HttpPost post = new HttpPost("http://foundit.andrewl.ca/postings");
-
+
+
try {
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("posting[name]", new StringBody(name));
entity.addPart("posting[posting_type]", new StringBody("2"));
entity.addPart("posting[description]", new StringBody(noNewLineDescription));
if(tookPhoto){
entity.addPart("posting[photo]", new FileBody(f));
post.setEntity(entity);
HttpResponse response = client.execute(post);
+ int test = response.getStatusLine().getStatusCode();
if (response.getStatusLine().getStatusCode() == 200) {
uploadSuccessful = true;
}
}
else
{
}
} catch (IOException e) {
e.printStackTrace();
}
return new String[1];
}
}
public void closeKeyboard(View view){
InputMethodManager inputMethodManager = (InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
}
}
| false | false | null | null |
diff --git a/src/main/java/org/basex/query/path/AxisPath.java b/src/main/java/org/basex/query/path/AxisPath.java
index c1fb00ac9..a032b59d8 100644
--- a/src/main/java/org/basex/query/path/AxisPath.java
+++ b/src/main/java/org/basex/query/path/AxisPath.java
@@ -1,456 +1,454 @@
package org.basex.query.path;
import static org.basex.query.QueryText.*;
import org.basex.data.Data;
import org.basex.index.Stats;
import org.basex.index.path.PathNode;
import org.basex.query.QueryContext;
import org.basex.query.QueryException;
import org.basex.query.expr.Expr;
import org.basex.query.expr.Filter;
import org.basex.query.expr.Pos;
import org.basex.query.item.Bln;
import org.basex.query.item.Empty;
import org.basex.query.item.ANode;
import org.basex.query.item.NodeType;
import org.basex.query.item.SeqType;
import org.basex.query.item.Value;
import org.basex.query.iter.Iter;
import org.basex.query.iter.NodeCache;
import org.basex.query.iter.NodeIter;
import org.basex.query.path.Test.Name;
import static org.basex.query.util.Err.*;
import org.basex.query.util.IndexContext;
import org.basex.query.util.Var;
import org.basex.util.Array;
import org.basex.util.InputInfo;
import org.basex.util.list.ObjList;
/**
* Axis path expression.
*
* @author BaseX Team 2005-12, BSD License
* @author Christian Gruen
*/
public class AxisPath extends Path {
/** Flag for result caching. */
private boolean cache;
/** Cached result. */
private NodeCache citer;
/** Last visited item. */
private Value lvalue;
/**
* Constructor.
* @param ii input info
* @param r root expression; can be a {@code null} reference
* @param s axis steps
*/
AxisPath(final InputInfo ii, final Expr r, final Expr... s) {
super(ii, r, s);
}
/**
* If possible, converts this path expression to a path iterator.
* @param ctx query context
* @return resulting operator
*/
final AxisPath finish(final QueryContext ctx) {
// evaluate number of results
size = size(ctx);
type = SeqType.get(steps[steps.length - 1].type().type, size);
return useIterator() ? new IterPath(input, root, steps, type, size) : this;
}
/**
* Checks if the path can be rewritten for iterative evaluation.
* @return resulting operator
*/
private boolean useIterator() {
if(root == null || root.uses(Use.VAR) || !root.iterable()) return false;
final int sl = steps.length;
for(int s = 0; s < sl; ++s) {
switch(step(s).axis) {
// reverse axes - don't iterate
case ANC: case ANCORSELF: case PREC: case PRECSIBL:
return false;
// multiple, unsorted results - only iterate at last step,
// or if last step uses attribute axis
case DESC: case DESCORSELF: case FOLL: case FOLLSIBL:
return s + 1 == sl || s + 2 == sl && step(s + 1).axis == Axis.ATTR;
// allow iteration for CHILD, ATTR, PARENT and SELF
default:
}
}
return true;
}
@Override
protected final Expr compPath(final QueryContext ctx) throws QueryException {
for(final Expr s : steps) checkUp(s, ctx);
// merge two axis paths
if(root instanceof AxisPath) {
Expr[] st = ((AxisPath) root).steps;
root = ((AxisPath) root).root;
for(final Expr s : steps) st = Array.add(st, s);
steps = st;
// refresh root context
ctx.compInfo(OPTMERGE);
ctx.value = root(ctx);
}
final AxisStep s = voidStep(steps);
if(s != null) COMPSELF.thrw(input, s);
for(int i = 0; i != steps.length; ++i) {
final Expr e = steps[i].comp(ctx);
if(!(e instanceof AxisStep)) return e;
steps[i] = e;
}
optSteps(ctx);
// retrieve data reference
final Data data = ctx.data();
if(data != null && ctx.value.type == NodeType.DOC) {
// check index access
Expr e = index(ctx, data);
// check children path rewriting
if(e == this) e = children(ctx, data);
// return optimized expression
if(e != this) return e.comp(ctx);
}
// analyze if result set can be cached - no predicates/variables...
cache = root != null && !uses(Use.VAR);
// if applicable, use iterative evaluation
final Path path = finish(ctx);
// heuristics: wrap with filter expression if only one result is expected
return size() != 1 ? path :
new Filter(input, this, Pos.get(1, size(), input)).comp2(ctx);
}
/**
* If possible, returns an expression which accesses the index.
* Otherwise, returns the original expression.
* @param ctx query context
* @param data data reference
* @return resulting expression
* @throws QueryException query exception
*/
private Expr index(final QueryContext ctx, final Data data)
throws QueryException {
// disallow relative paths and numeric predicates
if(root == null || uses(Use.POS)) return this;
// cache index access costs
IndexContext ics = null;
// cheapest predicate and step
int pmin = 0;
int smin = 0;
// check if path can be converted to an index access
for(int s = 0; s < steps.length; ++s) {
// find cheapest index access
final AxisStep stp = step(s);
if(!stp.axis.down) break;
// check if resulting index path will be duplicate free
final boolean i = pathNodes(data, s) != null;
// choose cheapest index access
for(int p = 0; p < stp.preds.length; ++p) {
final IndexContext ic = new IndexContext(ctx, data, stp, i);
if(!stp.preds[p].indexAccessible(ic)) continue;
if(ic.costs() == 0) {
if(ic.not) {
// not operator... accept all results
stp.preds[p] = Bln.TRUE;
continue;
}
// no results...
ctx.compInfo(OPTNOINDEX, this);
return Empty.SEQ;
}
if(ics == null || ics.costs() > ic.costs()) {
ics = ic;
pmin = p;
smin = s;
}
}
}
// skip if no index access is possible, or if it is too expensive
if(ics == null || ics.costs() > data.meta.size) return this;
// replace expressions for index access
final AxisStep stp = step(smin);
final Expr ie = stp.preds[pmin].indexEquivalent(ics);
if(ics.seq) {
// sequential evaluation; do not invert path
stp.preds[pmin] = ie;
} else {
// inverted path, which will be represented as predicate
AxisStep[] invSteps = {};
// collect remaining predicates
final Expr[] newPreds = new Expr[stp.preds.length - 1];
int c = 0;
for(int p = 0; p != stp.preds.length; ++p) {
if(p != pmin) newPreds[c++] = stp.preds[p];
}
// check if path before index step needs to be inverted and traversed
final Test test = DocTest.get(ctx, data);
boolean inv = true;
if(test == Test.DOC && data.meta.pathindex && data.meta.uptodate) {
int j = 0;
for(; j <= smin; ++j) {
- // invert if axis is not a child or has predicates
final AxisStep s = axisStep(j);
- if(s == null) break;
- if(s.axis != Axis.CHILD || s.preds.length > 0 && j != smin) break;
- if(s.test.test == Name.ALL || s.test.test == null) continue;
- if(s.test.test != Name.NAME) break;
+ // step must use child axis and name test, and have no predicates
+ if(s == null || s.test.test != Name.NAME || s.axis != Axis.CHILD ||
+ j != smin && s.preds.length > 0) break;
// support only unique paths with nodes on the correct level
final int name = data.tagindex.id(s.test.name.local());
final ObjList<PathNode> pn = data.paths.desc(name, Data.ELEM);
if(pn.size() != 1 || pn.get(0).level() != j + 1) break;
}
inv = j <= smin;
}
// invert path before index step
if(inv) {
for(int j = smin; j >= 0; --j) {
final Axis ax = step(j).axis.invert();
if(ax == null) break;
if(j != 0) {
final AxisStep prev = step(j - 1);
invSteps = Array.add(invSteps,
AxisStep.get(input, ax, prev.test, prev.preds));
} else {
// add document test for collections and axes other than ancestors
if(test != Test.DOC || ax != Axis.ANC && ax != Axis.ANCORSELF)
invSteps = Array.add(invSteps, AxisStep.get(input, ax, test));
}
}
}
// create resulting expression
final AxisPath result;
final boolean simple = invSteps.length == 0 && newPreds.length == 0;
if(ie instanceof AxisPath) {
result = (AxisPath) ie;
} else if(smin + 1 < steps.length || !simple) {
result = simple ? new AxisPath(input, ie) :
new AxisPath(input, ie, AxisStep.get(input, Axis.SELF, Test.NOD));
} else {
return ie;
}
// add remaining predicates to last step
final int ls = result.steps.length - 1;
if(ls >= 0) {
result.steps[ls] = result.step(ls).addPreds(newPreds);
// add inverted path as predicate to last step
if(invSteps.length != 0) result.steps[ls] =
result.step(ls).addPreds(Path.get(input, null, invSteps));
}
// add remaining steps
for(int s = smin + 1; s < steps.length; ++s) {
result.steps = Array.add(result.steps, steps[s]);
}
return result;
}
return this;
}
@Override
public Iter iter(final QueryContext ctx) throws QueryException {
final Value cv = ctx.value;
final long cs = ctx.size;
final long cp = ctx.pos;
try {
Value r = root != null ? ctx.value(root) : cv;
if(!cache || citer == null || lvalue.type != NodeType.DOC ||
r.type != NodeType.DOC || !((ANode) lvalue).is((ANode) r)) {
lvalue = r;
citer = new NodeCache().random();
if(r != null) {
final Iter ir = ctx.iter(r);
while((r = ir.next()) != null) {
ctx.value = r;
iter(0, citer, ctx);
}
} else {
ctx.value = null;
iter(0, citer, ctx);
}
citer.sort();
} else {
citer.reset();
}
return citer;
} finally {
ctx.value = cv;
ctx.size = cs;
ctx.pos = cp;
}
}
/**
* Recursive step iterator.
* @param l current step
* @param nc node cache
* @param ctx query context
* @throws QueryException query exception
*/
private void iter(final int l, final NodeCache nc, final QueryContext ctx)
throws QueryException {
// cast is safe (steps will always return a {@link NodIter} instance
final NodeIter ni = (NodeIter) ctx.iter(steps[l]);
final boolean more = l + 1 != steps.length;
for(ANode node; (node = ni.next()) != null;) {
if(more) {
ctx.value = node;
iter(l + 1, nc, ctx);
} else {
ctx.checkStop();
nc.add(node);
}
}
}
/**
* Inverts a location path.
* @param r new root node
* @param curr current location step
* @return inverted path
*/
public final AxisPath invertPath(final Expr r, final AxisStep curr) {
// hold the steps to the end of the inverted path
int s = steps.length;
final Expr[] e = new Expr[s--];
// add predicates of last step to new root node
final Expr rt = step(s).preds.length != 0 ?
new Filter(input, r, step(s).preds) : r;
// add inverted steps in a backward manner
int c = 0;
while(--s >= 0) {
e[c++] = AxisStep.get(input, step(s + 1).axis.invert(),
step(s).test, step(s).preds);
}
e[c] = AxisStep.get(input, step(s + 1).axis.invert(), curr.test);
return new AxisPath(input, rt, e);
}
@Override
public final Expr addText(final QueryContext ctx) {
final AxisStep s = step(steps.length - 1);
if(s.preds.length != 0 || !s.axis.down || s.test.type == NodeType.ATT ||
s.test.test != Name.NAME && s.test.test != Name.STD) return this;
final Data data = ctx.data();
if(data == null || !data.meta.uptodate) return this;
final Stats stats = data.tagindex.stat(
data.tagindex.id(s.test.name.local()));
if(stats != null && stats.isLeaf()) {
steps = Array.add(steps, AxisStep.get(input, Axis.CHILD, Test.TXT));
ctx.compInfo(OPTTEXT, this);
}
return this;
}
/**
* Returns the specified axis step.
* @param i index
* @return step
*/
public final AxisStep step(final int i) {
return (AxisStep) steps[i];
}
/**
* Returns a copy of the path expression.
* @return copy
*/
public final Path copy() {
final Expr[] stps = new Expr[steps.length];
for(int s = 0; s < steps.length; ++s) stps[s] = AxisStep.get(step(s));
return get(input, root, stps);
}
/**
* Returns the path nodes that will result from this path.
* @param ctx query context
* @return path nodes, or {@code null} if nodes cannot be evaluated
*/
public ObjList<PathNode> nodes(final QueryContext ctx) {
final Value rt = root(ctx);
final Data data = rt != null && rt.type == NodeType.DOC ? rt.data() : null;
if(data == null || !data.meta.pathindex || !data.meta.uptodate) return null;
ObjList<PathNode> nodes = data.paths.root();
for(int s = 0; s < steps.length; s++) {
final AxisStep curr = axisStep(s);
if(curr == null) return null;
nodes = curr.nodes(nodes, data);
if(nodes == null) return null;
}
return nodes;
}
@Override
public final int count(final Var v) {
int c = 0;
for(final Expr s : steps) c += s.count(v);
return c + super.count(v);
}
@Override
public final boolean removable(final Var v) {
for(final Expr s : steps) if(!s.removable(v)) return false;
return super.removable(v);
}
@Override
public final Expr remove(final Var v) {
for(int s = 0; s != steps.length; ++s) steps[s].remove(v);
return super.remove(v);
}
@Override
public final boolean iterable() {
return true;
}
@Override
public final boolean sameAs(final Expr cmp) {
if(!(cmp instanceof AxisPath)) return false;
final AxisPath ap = (AxisPath) cmp;
if((root == null || ap.root == null) && root != ap.root ||
steps.length != ap.steps.length ||
root != null && !root.sameAs(ap.root)) return false;
for(int s = 0; s < steps.length; ++s) {
if(!steps[s].sameAs(ap.steps[s])) return false;
}
return true;
}
}
| false | true | private Expr index(final QueryContext ctx, final Data data)
throws QueryException {
// disallow relative paths and numeric predicates
if(root == null || uses(Use.POS)) return this;
// cache index access costs
IndexContext ics = null;
// cheapest predicate and step
int pmin = 0;
int smin = 0;
// check if path can be converted to an index access
for(int s = 0; s < steps.length; ++s) {
// find cheapest index access
final AxisStep stp = step(s);
if(!stp.axis.down) break;
// check if resulting index path will be duplicate free
final boolean i = pathNodes(data, s) != null;
// choose cheapest index access
for(int p = 0; p < stp.preds.length; ++p) {
final IndexContext ic = new IndexContext(ctx, data, stp, i);
if(!stp.preds[p].indexAccessible(ic)) continue;
if(ic.costs() == 0) {
if(ic.not) {
// not operator... accept all results
stp.preds[p] = Bln.TRUE;
continue;
}
// no results...
ctx.compInfo(OPTNOINDEX, this);
return Empty.SEQ;
}
if(ics == null || ics.costs() > ic.costs()) {
ics = ic;
pmin = p;
smin = s;
}
}
}
// skip if no index access is possible, or if it is too expensive
if(ics == null || ics.costs() > data.meta.size) return this;
// replace expressions for index access
final AxisStep stp = step(smin);
final Expr ie = stp.preds[pmin].indexEquivalent(ics);
if(ics.seq) {
// sequential evaluation; do not invert path
stp.preds[pmin] = ie;
} else {
// inverted path, which will be represented as predicate
AxisStep[] invSteps = {};
// collect remaining predicates
final Expr[] newPreds = new Expr[stp.preds.length - 1];
int c = 0;
for(int p = 0; p != stp.preds.length; ++p) {
if(p != pmin) newPreds[c++] = stp.preds[p];
}
// check if path before index step needs to be inverted and traversed
final Test test = DocTest.get(ctx, data);
boolean inv = true;
if(test == Test.DOC && data.meta.pathindex && data.meta.uptodate) {
int j = 0;
for(; j <= smin; ++j) {
// invert if axis is not a child or has predicates
final AxisStep s = axisStep(j);
if(s == null) break;
if(s.axis != Axis.CHILD || s.preds.length > 0 && j != smin) break;
if(s.test.test == Name.ALL || s.test.test == null) continue;
if(s.test.test != Name.NAME) break;
// support only unique paths with nodes on the correct level
final int name = data.tagindex.id(s.test.name.local());
final ObjList<PathNode> pn = data.paths.desc(name, Data.ELEM);
if(pn.size() != 1 || pn.get(0).level() != j + 1) break;
}
inv = j <= smin;
}
// invert path before index step
if(inv) {
for(int j = smin; j >= 0; --j) {
final Axis ax = step(j).axis.invert();
if(ax == null) break;
if(j != 0) {
final AxisStep prev = step(j - 1);
invSteps = Array.add(invSteps,
AxisStep.get(input, ax, prev.test, prev.preds));
} else {
// add document test for collections and axes other than ancestors
if(test != Test.DOC || ax != Axis.ANC && ax != Axis.ANCORSELF)
invSteps = Array.add(invSteps, AxisStep.get(input, ax, test));
}
}
}
// create resulting expression
final AxisPath result;
final boolean simple = invSteps.length == 0 && newPreds.length == 0;
if(ie instanceof AxisPath) {
result = (AxisPath) ie;
} else if(smin + 1 < steps.length || !simple) {
result = simple ? new AxisPath(input, ie) :
new AxisPath(input, ie, AxisStep.get(input, Axis.SELF, Test.NOD));
} else {
return ie;
}
// add remaining predicates to last step
final int ls = result.steps.length - 1;
if(ls >= 0) {
result.steps[ls] = result.step(ls).addPreds(newPreds);
// add inverted path as predicate to last step
if(invSteps.length != 0) result.steps[ls] =
result.step(ls).addPreds(Path.get(input, null, invSteps));
}
// add remaining steps
for(int s = smin + 1; s < steps.length; ++s) {
result.steps = Array.add(result.steps, steps[s]);
}
return result;
}
return this;
}
| private Expr index(final QueryContext ctx, final Data data)
throws QueryException {
// disallow relative paths and numeric predicates
if(root == null || uses(Use.POS)) return this;
// cache index access costs
IndexContext ics = null;
// cheapest predicate and step
int pmin = 0;
int smin = 0;
// check if path can be converted to an index access
for(int s = 0; s < steps.length; ++s) {
// find cheapest index access
final AxisStep stp = step(s);
if(!stp.axis.down) break;
// check if resulting index path will be duplicate free
final boolean i = pathNodes(data, s) != null;
// choose cheapest index access
for(int p = 0; p < stp.preds.length; ++p) {
final IndexContext ic = new IndexContext(ctx, data, stp, i);
if(!stp.preds[p].indexAccessible(ic)) continue;
if(ic.costs() == 0) {
if(ic.not) {
// not operator... accept all results
stp.preds[p] = Bln.TRUE;
continue;
}
// no results...
ctx.compInfo(OPTNOINDEX, this);
return Empty.SEQ;
}
if(ics == null || ics.costs() > ic.costs()) {
ics = ic;
pmin = p;
smin = s;
}
}
}
// skip if no index access is possible, or if it is too expensive
if(ics == null || ics.costs() > data.meta.size) return this;
// replace expressions for index access
final AxisStep stp = step(smin);
final Expr ie = stp.preds[pmin].indexEquivalent(ics);
if(ics.seq) {
// sequential evaluation; do not invert path
stp.preds[pmin] = ie;
} else {
// inverted path, which will be represented as predicate
AxisStep[] invSteps = {};
// collect remaining predicates
final Expr[] newPreds = new Expr[stp.preds.length - 1];
int c = 0;
for(int p = 0; p != stp.preds.length; ++p) {
if(p != pmin) newPreds[c++] = stp.preds[p];
}
// check if path before index step needs to be inverted and traversed
final Test test = DocTest.get(ctx, data);
boolean inv = true;
if(test == Test.DOC && data.meta.pathindex && data.meta.uptodate) {
int j = 0;
for(; j <= smin; ++j) {
final AxisStep s = axisStep(j);
// step must use child axis and name test, and have no predicates
if(s == null || s.test.test != Name.NAME || s.axis != Axis.CHILD ||
j != smin && s.preds.length > 0) break;
// support only unique paths with nodes on the correct level
final int name = data.tagindex.id(s.test.name.local());
final ObjList<PathNode> pn = data.paths.desc(name, Data.ELEM);
if(pn.size() != 1 || pn.get(0).level() != j + 1) break;
}
inv = j <= smin;
}
// invert path before index step
if(inv) {
for(int j = smin; j >= 0; --j) {
final Axis ax = step(j).axis.invert();
if(ax == null) break;
if(j != 0) {
final AxisStep prev = step(j - 1);
invSteps = Array.add(invSteps,
AxisStep.get(input, ax, prev.test, prev.preds));
} else {
// add document test for collections and axes other than ancestors
if(test != Test.DOC || ax != Axis.ANC && ax != Axis.ANCORSELF)
invSteps = Array.add(invSteps, AxisStep.get(input, ax, test));
}
}
}
// create resulting expression
final AxisPath result;
final boolean simple = invSteps.length == 0 && newPreds.length == 0;
if(ie instanceof AxisPath) {
result = (AxisPath) ie;
} else if(smin + 1 < steps.length || !simple) {
result = simple ? new AxisPath(input, ie) :
new AxisPath(input, ie, AxisStep.get(input, Axis.SELF, Test.NOD));
} else {
return ie;
}
// add remaining predicates to last step
final int ls = result.steps.length - 1;
if(ls >= 0) {
result.steps[ls] = result.step(ls).addPreds(newPreds);
// add inverted path as predicate to last step
if(invSteps.length != 0) result.steps[ls] =
result.step(ls).addPreds(Path.get(input, null, invSteps));
}
// add remaining steps
for(int s = smin + 1; s < steps.length; ++s) {
result.steps = Array.add(result.steps, steps[s]);
}
return result;
}
return this;
}
|
diff --git a/pixi/src/main/java/org/openpixi/pixi/ui/util/Parser.java b/pixi/src/main/java/org/openpixi/pixi/ui/util/Parser.java
index f2ab7e2e..7d2353d3 100644
--- a/pixi/src/main/java/org/openpixi/pixi/ui/util/Parser.java
+++ b/pixi/src/main/java/org/openpixi/pixi/ui/util/Parser.java
@@ -1,310 +1,310 @@
/*
* OpenPixi - Open Particle-In-Cell (PIC) Simulator
* Copyright (C) 2012 OpenPixi.org
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.openpixi.pixi.ui.util;
import java.io.IOException;
import org.xml.sax.SAXException;
import javax.xml.parsers.ParserConfigurationException;
import java.lang.NumberFormatException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;
import org.openpixi.pixi.physics.Settings;
import org.openpixi.pixi.physics.grid.*;
import org.openpixi.pixi.physics.solver.*;
import org.openpixi.pixi.diagnostics.methods.*;
public class Parser extends DefaultHandler {
SAXParserFactory factory;
Settings settings;
private boolean numberOfParticles;
private boolean simulationWidth;
private boolean simulationHeight;
private boolean timeStep;
private boolean interpolator;
private boolean particleMover;
private boolean diagnostics;
private boolean iterations;
private boolean runid;
private String attribute = null;
public Parser(Settings settings){
factory = SAXParserFactory.newInstance();
this.settings = settings;
}
public void parse(String path) {
try {
SAXParser parser = factory.newSAXParser();
parser.parse(path, this);
} catch (ParserConfigurationException e) {
System.out.println("ParserConfig error");
} catch (SAXException e) {
System.out.println("Parsing aborted!\n" +
"Probably the xml file is not formated correctly!\n" +
"Not all parameters were processed!");
} catch (IOException e) {
System.out.println("IO error! Settings file was not parsed!\n" +
"Probably the settings file is missing or is in the wrong path!\n" +
"Reverting to defaults...");
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
try {
if (qName.equalsIgnoreCase("numberOfParticles")) {
numberOfParticles = true;
} else if (qName.equalsIgnoreCase("simulationWidth")){
simulationWidth = true;
} else if (qName.equalsIgnoreCase("simulationHeight")) {
simulationHeight = true;
} else if (qName.equalsIgnoreCase("timeStep")) {
timeStep = true;
} else if (qName.equalsIgnoreCase("interpolatorAlgorithm")) {
interpolator = true;
} else if (qName.equalsIgnoreCase("particleSolver")) {
particleMover = true;
} else if(qName.equalsIgnoreCase("diagnostics")) {
diagnostics = true;
try {
attribute = attributes.getValue(0);
} catch (Exception e) {
System.err.println("You need to specify a diagnostics interval (as an attribute)" +
" for each diagnostic method you specify! Choose 0 if you only want it" +
" to be performed at the beginning! Skipping those diagnostics where no" +
" attributes were found.");
diagnostics = false;
}
} else if(qName.equalsIgnoreCase("iterations")) {
iterations = true;
} else if(qName.equalsIgnoreCase("runid")) {
runid = true;
} else if (qName.equalsIgnoreCase("settings")) {
//DO NOTHING
}
else throw new Exception();
} catch (Exception e) {
System.out.println(qName + " can not be parsed!");
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
}
@Override
public void characters(char ch[], int start, int length) throws SAXException {
if (runid) {
setRunid(ch, start, length);
runid = false;
}
if (iterations) {
setIterations(ch, start, length);
iterations = false;
}
if (numberOfParticles) {
setNumberOfParticles(ch, start, length);
numberOfParticles = false;
}
if (simulationWidth) {
setSimulationWidth(ch, start, length);
simulationWidth = false;
}
if (simulationHeight) {
setSimulationHeight(ch, start, length);
simulationHeight = false;
}
if (timeStep) {
setTimeStep(ch, start, length);
timeStep = false;
}
if (interpolator) {
setInterpolator(ch, start, length);
interpolator = false;
}
if (particleMover) {
setParticleSolver(ch, start, length);
particleMover = false;
}
if (diagnostics) {
addDiagnostics(ch, start, length);
diagnostics = false;
attribute = null;
}
}
private void setRunid(char ch[], int start, int length) {
settings.setRunid(new String(ch, start, length));
}
private void setIterations(char ch[], int start, int length) {
int n;
try{
n = Integer.parseInt(new String(ch, start, length));
if ( n < 0) throw new NumberFormatException();
} catch (NumberFormatException e){
System.out.println("Error: the number of iterations is not a positive integer! " +
"Setting it to 100.");
n = 100;
}
settings.setIterations(n);
}
private void addDiagnostics(char ch[], int start, int length) {
- Diagnostics methodd;
+ Diagnostics method;
String mtdname = new String(ch, start, length);
int n;
try{
n = Integer.parseInt(attribute);
if ( n < 0) throw new NumberFormatException();
} catch (NumberFormatException e){
System.err.println("Error: the interval you specified is not a positive integer! " +
"Setting it to 0. The diagnostic will only be performed only at the beginning.");
n = 0;
}
try{
if (mtdname.equalsIgnoreCase("Kinetic Energy")) {
- methodd = new KineticEnergy(n);
+ method = new KineticEnergy(n);
} else if (mtdname.equalsIgnoreCase("Potential")) {
- methodd = new Potential(n);
+ method = new Potential(n);
} else throw new Exception();
} catch (Exception e){
System.err.println("OpenPixi does not know about the " + mtdname + " diagnostic" +
" method. Skipping this setting!");
return;
}
- settings.getDiagnostics().add(methodd);
+ settings.getDiagnostics().add(method);
}
private void setNumberOfParticles(char ch[], int start, int length) {
int n;
try{
n = Integer.parseInt(new String(ch, start, length));
if ( n < 0) throw new NumberFormatException();
} catch (NumberFormatException e){
System.out.println("Error: particle number is not a positive integer! Setting n = 100.");
n = 100;
}
settings.setNumOfParticles(n);
}
private void setTimeStep(char ch[], int start, int length) {
double t;
try{
t = Double.parseDouble(new String(ch, start, length));
if ( t < 0) throw new NumberFormatException();
} catch (NumberFormatException e){
System.out.println("Error: time step is not a positive value! Setting it to 1.");
t = 1;
}
settings.setTimeStep(t);
}
private void setSimulationWidth(char ch[], int start, int length) {
double w;
try{
w = Double.parseDouble(new String(ch, start, length));
if ( w < 0) throw new NumberFormatException();
} catch (NumberFormatException e){
System.out.println("Error: simulation width is not a positive value! Setting it to 100.");
w = 100;
}
settings.setTimeStep(w);
}
private void setSimulationHeight(char ch[], int start, int length) {
double h;
try{
h = Double.parseDouble(new String(ch, start, length));
if ( h < 0) throw new NumberFormatException();
} catch (NumberFormatException e){
System.out.println("Error: simulation height is not a positive value! Setting it to 100.");
h = 100;
}
settings.setTimeStep(h);
}
private void setInterpolator(char ch[], int start, int length) {
InterpolatorAlgorithm alg;
String algname = new String(ch, start, length);
try{
if (algname.equalsIgnoreCase("Cloud In Cell")) {
alg = new CloudInCell();
} else if (algname.equalsIgnoreCase("Charge Conserving CIC")) {
alg = new ChargeConservingCIC();
} else throw new Exception();
} catch (Exception e){
System.out.println("Error: OpenPixi does not know about the " + algname + " interpolation" +
" algorithm. Setting it to CloudInCell.");
alg = new CloudInCell();
}
settings.setInterpolator(alg);
}
private void setParticleSolver(char ch[], int start, int length) {
Solver alg;
String algname = new String(ch, start, length);
try{
if (algname.equalsIgnoreCase("Boris")) {
alg = new Boris();
} else if (algname.equalsIgnoreCase("Boris Damped")) {
alg = new BorisDamped();
} else if (algname.equalsIgnoreCase("Empty Solver")) {
alg = new EmptySolver();
} else if (algname.equalsIgnoreCase("Euler")) {
alg = new Euler();
} else if (algname.equalsIgnoreCase("Euler Richardson")) {
alg = new EulerRichardson();
} else if (algname.equalsIgnoreCase("Leap Frog")) {
alg = new LeapFrog();
} else if (algname.equalsIgnoreCase("Leap Frog Damped")) {
alg = new LeapFrogDamped();
} else if (algname.equalsIgnoreCase("Leap Frog Half Step")) {
alg = new LeapFrogHalfStep();
} else if (algname.equalsIgnoreCase("SemiImplicit Euler")) {
alg = new SemiImplicitEuler();
}
else throw new Exception();
} catch (Exception e){
System.out.println("Error: OpenPixi does not know about the " + algname + " solver" +
" mover. Setting it to Boris.");
alg = new Boris();
}
settings.setParticleSolver(alg);
}
}
| false | false | null | null |
diff --git a/src/org/knix/amnotbot/DeliciousThread.java b/src/org/knix/amnotbot/DeliciousThread.java
index 7a6cb85..d293b58 100644
--- a/src/org/knix/amnotbot/DeliciousThread.java
+++ b/src/org/knix/amnotbot/DeliciousThread.java
@@ -1,125 +1,127 @@
package org.knix.amnotbot;
import java.util.Date;
public class DeliciousThread extends Thread
{
private BotConnection con;
private String chan;
private String url;
private String nick;
private DeliciousBookmarks delicious;
private AmnotbotHTMLParser parser;
private boolean showTitle;
private CommandOptions opts;
public DeliciousThread(DeliciousBookmarks delicious, BotConnection con,
String chan,
String nick,
String url,
String msg,
boolean showTitle)
{
this.con = con;
this.chan = chan;
this.nick = nick;
this.url = url;
this.delicious = delicious;
this.showTitle = showTitle;
opts = new CommandOptions(msg);
opts.addOption( new CmdCommaSeparatedOption("tags") );
opts.addOption( new CmdStringOption("title", '"') );
opts.addOption( new CmdStringOption("comment", '"') );
this.parser = new AmnotbotHTMLParser(this.url);
start();
}
private String getPageTags()
{
String tags = "";
String keywords;
keywords = this.parser.getKeywords();
if (keywords != null) {
String [] str = keywords.split(",");
+ if (str.length == 1)
+ str = keywords.split(" ");
for (int i = 0; i < str.length; ++i) {
tags += " " + str[i].trim().replace(" ", ".");
}
}
return tags;
}
private String getTags()
{
String tags = "";
CmdCommaSeparatedOption tagOption;
tagOption = (CmdCommaSeparatedOption)this.opts.getOption("tags");
if (tagOption.hasValue())
tags += tagOption.stringValue(" ", ".");
tags += this.getPageTags();
if (tags.trim().length() > 0)
tags += " " + this.nick;
else
tags = this.nick;
return tags;
}
private String getTitle()
{
CmdStringOption titleOption;
titleOption = (CmdStringOption)this.opts.getOption("title");
if (titleOption.hasValue())
return titleOption.stringValue();
String title = this.parser.getTitle();
if (title != null)
return title;
return this.url;
}
private boolean isPageTitle()
{
if (!this.opts.getOption("title").hasValue() && this.parser.getTitle() != null)
return true;
return false;
}
public void run()
{
Boolean success;
String tags;
String title;
String comment;
this.opts.buildArgs();
tags = this.getTags();
title = this.getTitle();
comment = this.opts.getOption("comment").stringValue();
System.out.println("DeliciousThread: tags:" + tags + ":title:" + title + ":length(" + title.length() + ")" + ":comment:" + comment + ":");
success = false;
if (this.showTitle && this.isPageTitle())
this.con.doPrivmsg(this.chan, title);
success = this.delicious.addPost(this.url, title, comment, tags.trim(), new Date());
if (!success)
System.out.println("Post failed! :-(");
else
System.out.println("Posted!");
}
}
| true | false | null | null |
diff --git a/src/main/java/unquietcode/tools/esm/IStateMachine.java b/src/main/java/unquietcode/tools/esm/IStateMachine.java
index 7f023d3..116052d 100644
--- a/src/main/java/unquietcode/tools/esm/IStateMachine.java
+++ b/src/main/java/unquietcode/tools/esm/IStateMachine.java
@@ -1,104 +1,87 @@
package unquietcode.tools.esm;
/**
* @author Ben Fagin
* @version 2013-07-07
*/
-public interface IStateMachine<T> {
-
- /**
- * Transition to the provided state.
- * If the transition is not valid, an exception is thrown.
- * @param state next state to transition to
- * @return true if transitioned, false if already in this state
- */
- boolean transition(T state);
-
- /**
- * Resets the state machine to its initial state and clears
- * the transition count.
- */
- void reset();
+public interface IStateMachine<T> extends StateMachineController<T> {
/**
* Get the total number of transitions performed by the state machine, since
* construction or the most recent call to {@link #reset()}. Transitions which
* are in progress do not count towards the overall count. In progress means
* that the exit callbacks, transition callbacks, and entry callbacks have all
* been completed for a given transition.
*
* @return the current number of transitions performed
*/
long transitionCount();
- T initialState();
- T currentState();
-
/**
* Will not reset, just sets the initial state.
*
* @param state initial state to be set after next reset
*/
void setInitialState(T state);
/**
* Adds a callback which will be executed whenever the specified state
* is entered, via any transition.
*/
CallbackRegistration onEntering(T state, StateMachineCallback callback);
/**
* Adds a callback which will be executed whenever the specified state
* is exited, via any transition.
*/
CallbackRegistration onExiting(T state, StateMachineCallback callback);
/**
* Adds a callback which will be executed whenever the specified state
* is exited, via any transition.
*/
CallbackRegistration onTransition(T from, T to, StateMachineCallback callback);
boolean addTransition(T fromState, T toState);
boolean addTransition(T fromState, T toState, StateMachineCallback callback);
/**
* Add a transition between two states.
* @param fromState the initial state
* @param toStates one or more states to move to
*/
boolean addTransitions(T fromState, T...toStates);
/**
* Add a transition from one state to 0..n other states. The callback
* will be executed as the transition is occurring. If the state machine
* is modified during this operation, it will be reset. Adding a new
* callback to an existing transition will not be perceived as modification.
*
* @param callback callback, can be null
* @param fromState state moving from
* @param toStates states moving to
* @return true if the state machine was modified and a reset occurred, false otherwise
*/
boolean addTransitions(T fromState, T[] toStates, StateMachineCallback callback);
/*
Gets around the inability to create generic arrays by flipping the
callback parameter position, thus freeing up the vararg parameter.
*/
boolean addTransitions(StateMachineCallback callback, T fromState, T...toStates);
/**
* Removes the set of transitions from the given state.
* When the state machine is modified, this method will
* return true and the state machine will be reset.
*
* @param fromState from state
* @param toStates to states
* @return true if the transitions were modified, false otherwise
*/
boolean removeTransitions(T fromState, T... toStates);
void setTransitions(T fromState, T... toStates);
void setTransitions(StateMachineCallback callback, T fromState, T... toStates);
}
diff --git a/src/main/java/unquietcode/tools/esm/StateMachineController.java b/src/main/java/unquietcode/tools/esm/StateMachineController.java
index fd58d48..76a1f0f 100644
--- a/src/main/java/unquietcode/tools/esm/StateMachineController.java
+++ b/src/main/java/unquietcode/tools/esm/StateMachineController.java
@@ -1,42 +1,42 @@
package unquietcode.tools.esm;
/**
* Provides methods for controlling a state machine without providing direct access to the
* underlying object. Essentially an immutable {@link EnumStateMachine} instance.
*
* @author Ben Fagin
* @version 2013-04-02
*/
-public interface StateMachineController {
+public interface StateMachineController<T> {
/**
* Transition the state machine to the next state.
*
* @param state to transition to
* @return true if moved to another state, false if continuing on the same state
*
* @throws TransitionException if a violation of the available transitions occurs
*/
- boolean transition(Enum state) throws TransitionException;
+ boolean transition(T state) throws TransitionException;
/**
* Returns the current state for this state machine.
* The value could change if manipulated externally.
*
* @return the current state
*/
- <T extends Enum> T currentState();
+ T currentState();
/**
* Returns the initial state set for this state machine.
* The value could change if manipulated externally.
*
* @return the initial state
*/
- <T extends Enum> T initialState();
+ T initialState();
/**
* Resets the state machine to its initial state and clears the transition count.
*/
void reset();
}
| false | false | null | null |
diff --git a/src/com/android/gallery3d/filtershow/FilterShowActivity.java b/src/com/android/gallery3d/filtershow/FilterShowActivity.java
index 80849b174..f2fb3da9d 100644
--- a/src/com/android/gallery3d/filtershow/FilterShowActivity.java
+++ b/src/com/android/gallery3d/filtershow/FilterShowActivity.java
@@ -1,647 +1,663 @@
package com.android.gallery3d.filtershow;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.ShareActionProvider;
import android.widget.ShareActionProvider.OnShareTargetSelectedListener;
import com.android.gallery3d.R;
import com.android.gallery3d.filtershow.cache.ImageLoader;
import com.android.gallery3d.filtershow.filters.ImageFilter;
import com.android.gallery3d.filtershow.filters.ImageFilterBorder;
import com.android.gallery3d.filtershow.filters.ImageFilterParametricBorder;
import com.android.gallery3d.filtershow.filters.ImageFilterRS;
import com.android.gallery3d.filtershow.imageshow.ImageBorder;
import com.android.gallery3d.filtershow.imageshow.ImageCrop;
import com.android.gallery3d.filtershow.imageshow.ImageFlip;
import com.android.gallery3d.filtershow.imageshow.ImageRotate;
import com.android.gallery3d.filtershow.imageshow.ImageShow;
import com.android.gallery3d.filtershow.imageshow.ImageSmallFilter;
import com.android.gallery3d.filtershow.imageshow.ImageStraighten;
import com.android.gallery3d.filtershow.imageshow.ImageZoom;
import com.android.gallery3d.filtershow.presets.ImagePreset;
import com.android.gallery3d.filtershow.presets.ImagePresetBW;
import com.android.gallery3d.filtershow.presets.ImagePresetBWBlue;
import com.android.gallery3d.filtershow.presets.ImagePresetBWGreen;
import com.android.gallery3d.filtershow.presets.ImagePresetBWRed;
import com.android.gallery3d.filtershow.presets.ImagePresetOld;
import com.android.gallery3d.filtershow.presets.ImagePresetSaturated;
import com.android.gallery3d.filtershow.presets.ImagePresetXProcessing;
import com.android.gallery3d.filtershow.provider.SharedImageProvider;
import com.android.gallery3d.filtershow.tools.SaveCopyTask;
import com.android.gallery3d.filtershow.ui.ImageCurves;
import java.io.File;
import java.lang.ref.WeakReference;
import java.util.Vector;
@TargetApi(16)
public class FilterShowActivity extends Activity implements OnItemClickListener,
OnShareTargetSelectedListener {
private final PanelController mPanelController = new PanelController();
private ImageLoader mImageLoader = null;
private ImageShow mImageShow = null;
private ImageCurves mImageCurves = null;
private ImageBorder mImageBorders = null;
private ImageStraighten mImageStraighten = null;
private ImageZoom mImageZoom = null;
private ImageCrop mImageCrop = null;
private ImageRotate mImageRotate = null;
private ImageFlip mImageFlip = null;
private View mListFx = null;
private View mListBorders = null;
private View mListGeometry = null;
private View mListColors = null;
private View mListFilterButtons = null;
private ImageButton mFxButton = null;
private ImageButton mBorderButton = null;
private ImageButton mGeometryButton = null;
private ImageButton mColorsButton = null;
private static final int SELECT_PICTURE = 1;
private static final String LOGTAG = "FilterShowActivity";
protected static final boolean ANIMATE_PANELS = true;
private boolean mShowingHistoryPanel = false;
private boolean mShowingImageStatePanel = false;
private final Vector<ImageShow> mImageViews = new Vector<ImageShow>();
private final Vector<View> mListViews = new Vector<View>();
private final Vector<ImageButton> mBottomPanelButtons = new Vector<ImageButton>();
private ShareActionProvider mShareActionProvider;
private File mSharedOutputFile = null;
private boolean mSharingImage = false;
private WeakReference<ProgressDialog> mSavingProgressDialog;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ImageFilterRS.setRenderScriptContext(this);
setContentView(R.layout.filtershow_activity);
ActionBar actionBar = getActionBar();
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
actionBar.setCustomView(R.layout.filtershow_actionbar);
actionBar.getCustomView().setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
saveImage();
}
});
mImageLoader = new ImageLoader(getApplicationContext());
LinearLayout listFilters = (LinearLayout) findViewById(R.id.listFilters);
LinearLayout listBorders = (LinearLayout) findViewById(R.id.listBorders);
mImageShow = (ImageShow) findViewById(R.id.imageShow);
mImageCurves = (ImageCurves) findViewById(R.id.imageCurves);
mImageBorders = (ImageBorder) findViewById(R.id.imageBorder);
mImageStraighten = (ImageStraighten) findViewById(R.id.imageStraighten);
mImageZoom = (ImageZoom) findViewById(R.id.imageZoom);
mImageCrop = (ImageCrop) findViewById(R.id.imageCrop);
mImageRotate = (ImageRotate) findViewById(R.id.imageRotate);
mImageFlip = (ImageFlip) findViewById(R.id.imageFlip);
mImageViews.add(mImageShow);
mImageViews.add(mImageCurves);
mImageViews.add(mImageBorders);
mImageViews.add(mImageStraighten);
mImageViews.add(mImageZoom);
mImageViews.add(mImageCrop);
mImageViews.add(mImageRotate);
mImageViews.add(mImageFlip);
mListFx = findViewById(R.id.fxList);
mListBorders = findViewById(R.id.bordersList);
mListGeometry = findViewById(R.id.geometryList);
mListFilterButtons = findViewById(R.id.filterButtonsList);
mListColors = findViewById(R.id.colorsFxList);
mListViews.add(mListFx);
mListViews.add(mListBorders);
mListViews.add(mListGeometry);
mListViews.add(mListFilterButtons);
mListViews.add(mListColors);
mFxButton = (ImageButton) findViewById(R.id.fxButton);
mBorderButton = (ImageButton) findViewById(R.id.borderButton);
mGeometryButton = (ImageButton) findViewById(R.id.geometryButton);
mColorsButton = (ImageButton) findViewById(R.id.colorsButton);
mImageShow.setImageLoader(mImageLoader);
mImageCurves.setImageLoader(mImageLoader);
mImageCurves.setMaster(mImageShow);
mImageBorders.setImageLoader(mImageLoader);
mImageBorders.setMaster(mImageShow);
mImageStraighten.setImageLoader(mImageLoader);
mImageStraighten.setMaster(mImageShow);
mImageZoom.setImageLoader(mImageLoader);
mImageZoom.setMaster(mImageShow);
mImageCrop.setImageLoader(mImageLoader);
mImageCrop.setMaster(mImageShow);
mImageRotate.setImageLoader(mImageLoader);
mImageRotate.setMaster(mImageShow);
mImageFlip.setImageLoader(mImageLoader);
mImageFlip.setMaster(mImageShow);
mPanelController.addImageView(findViewById(R.id.imageShow));
mPanelController.addImageView(findViewById(R.id.imageCurves));
mPanelController.addImageView(findViewById(R.id.imageBorder));
mPanelController.addImageView(findViewById(R.id.imageStraighten));
mPanelController.addImageView(findViewById(R.id.imageCrop));
mPanelController.addImageView(findViewById(R.id.imageRotate));
mPanelController.addImageView(findViewById(R.id.imageFlip));
mPanelController.addImageView(findViewById(R.id.imageZoom));
mPanelController.addPanel(mFxButton, mListFx, 0);
mPanelController.addPanel(mBorderButton, mListBorders, 1);
mPanelController.addPanel(mGeometryButton, mListGeometry, 2);
mPanelController.addComponent(mGeometryButton, findViewById(R.id.straightenButton));
mPanelController.addComponent(mGeometryButton, findViewById(R.id.cropButton));
mPanelController.addComponent(mGeometryButton, findViewById(R.id.rotateButton));
mPanelController.addComponent(mGeometryButton, findViewById(R.id.flipButton));
mPanelController.addPanel(mColorsButton, mListColors, 3);
mPanelController.addComponent(mColorsButton, findViewById(R.id.vignetteButton));
mPanelController.addComponent(mColorsButton, findViewById(R.id.curvesButtonRGB));
mPanelController.addComponent(mColorsButton, findViewById(R.id.sharpenButton));
mPanelController.addComponent(mColorsButton, findViewById(R.id.vibranceButton));
mPanelController.addComponent(mColorsButton, findViewById(R.id.contrastButton));
mPanelController.addComponent(mColorsButton, findViewById(R.id.saturationButton));
mPanelController.addComponent(mColorsButton, findViewById(R.id.tintButton));
mPanelController.addComponent(mColorsButton, findViewById(R.id.exposureButton));
mPanelController.addComponent(mColorsButton, findViewById(R.id.shadowRecoveryButton));
mPanelController.addComponent(mColorsButton, findViewById(R.id.redEyeButton));
mPanelController.addView(findViewById(R.id.resetEffect));
mPanelController.addView(findViewById(R.id.applyEffect));
findViewById(R.id.compareWithOriginalImage).setOnTouchListener(createOnTouchShowOriginalButton());
findViewById(R.id.resetOperationsButton).setOnClickListener(
createOnClickResetOperationsButton());
ListView operationsList = (ListView) findViewById(R.id.operationsList);
operationsList.setAdapter(mImageShow.getHistoryAdapter());
operationsList.setOnItemClickListener(this);
ListView imageStateList = (ListView) findViewById(R.id.imageStateList);
imageStateList.setAdapter(mImageShow.getImageStateAdapter());
mImageLoader.setAdapter((HistoryAdapter) mImageShow.getHistoryAdapter());
fillListImages(listFilters);
fillListBorders(listBorders);
SeekBar seekBar = (SeekBar) findViewById(R.id.filterSeekBar);
seekBar.setMax(200);
mImageShow.setSeekBar(seekBar);
mImageZoom.setSeekBar(seekBar);
mPanelController.setRowPanel(findViewById(R.id.secondRowPanel));
mPanelController.setUtilityPanel(this, findViewById(R.id.filterButtonsList),
findViewById(R.id.compareWithOriginalImage),
findViewById(R.id.applyEffect));
mPanelController.setMasterImage(mImageShow);
mPanelController.setCurrentPanel(mFxButton);
Intent intent = getIntent();
String data = intent.getDataString();
if (data != null) {
Uri uri = Uri.parse(data);
mImageLoader.loadBitmap(uri);
} else {
pickImage();
}
}
private void showSavingProgress() {
ProgressDialog progress;
if (mSavingProgressDialog != null) {
progress = mSavingProgressDialog.get();
if (progress != null) {
progress.show();
return;
}
}
// TODO: Allow cancellation of the saving process
progress = ProgressDialog.show(this, "", getString(R.string.saving_image), true, false);
mSavingProgressDialog = new WeakReference<ProgressDialog>(progress);
}
private void hideSavingProgress() {
if (mSavingProgressDialog != null) {
ProgressDialog progress = mSavingProgressDialog.get();
if (progress != null) progress.dismiss();
}
}
public void completeSaveImage(Uri saveUri) {
if (mSharingImage && mSharedOutputFile != null) {
// Image saved, we unblock the content provider
Uri uri = Uri.withAppendedPath(SharedImageProvider.CONTENT_URI,
Uri.encode(mSharedOutputFile.getAbsolutePath()));
ContentValues values = new ContentValues();
values.put(SharedImageProvider.PREPARE, false);
getContentResolver().insert(uri, values);
}
setResult(RESULT_OK, new Intent().setData(saveUri));
hideSavingProgress();
finish();
}
@Override
public boolean onShareTargetSelected(ShareActionProvider arg0, Intent arg1) {
// First, let's tell the SharedImageProvider that it will need to wait
// for the image
Uri uri = Uri.withAppendedPath(SharedImageProvider.CONTENT_URI,
Uri.encode(mSharedOutputFile.getAbsolutePath()));
ContentValues values = new ContentValues();
values.put(SharedImageProvider.PREPARE, true);
getContentResolver().insert(uri, values);
mSharingImage = true;
// Process and save the image in the background.
showSavingProgress();
mImageShow.saveImage(this, mSharedOutputFile);
return true;
}
private Intent getDefaultShareIntent() {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setType(SharedImageProvider.MIME_TYPE);
mSharedOutputFile = SaveCopyTask.getNewFile(this, mImageLoader.getUri());
Uri uri = Uri.withAppendedPath(SharedImageProvider.CONTENT_URI,
Uri.encode(mSharedOutputFile.getAbsolutePath()));
intent.putExtra(Intent.EXTRA_STREAM, uri);
return intent;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.filtershow_activity_menu, menu);
MenuItem showHistory = menu.findItem(R.id.operationsButton);
if (mShowingHistoryPanel) {
showHistory.setTitle(R.string.hide_history_panel);
} else {
showHistory.setTitle(R.string.show_history_panel);
}
MenuItem showState = menu.findItem(R.id.showImageStateButton);
if (mShowingImageStatePanel) {
showState.setTitle(R.string.hide_imagestate_panel);
} else {
showState.setTitle(R.string.show_imagestate_panel);
}
mShareActionProvider = (ShareActionProvider) menu.findItem(R.id.menu_share)
.getActionProvider();
mShareActionProvider.setShareIntent(getDefaultShareIntent());
mShareActionProvider.setOnShareTargetSelectedListener(this);
return true;
}
@Override
+ public void onPause() {
+ super.onPause();
+ if (mShareActionProvider != null) {
+ mShareActionProvider.setOnShareTargetSelectedListener(null);
+ }
+ }
+
+ @Override
+ public void onResume() {
+ super.onResume();
+ if (mShareActionProvider != null) {
+ mShareActionProvider.setOnShareTargetSelectedListener(this);
+ }
+ }
+
+ @Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.undoButton: {
HistoryAdapter adapter = (HistoryAdapter) mImageShow
.getHistoryAdapter();
int position = adapter.undo();
mImageShow.onItemClick(position);
mImageShow.showToast("Undo");
invalidateViews();
return true;
}
case R.id.redoButton: {
HistoryAdapter adapter = (HistoryAdapter) mImageShow
.getHistoryAdapter();
int position = adapter.redo();
mImageShow.onItemClick(position);
mImageShow.showToast("Redo");
invalidateViews();
return true;
}
case R.id.resetHistoryButton: {
resetHistory();
return true;
}
case R.id.showImageStateButton: {
toggleImageStatePanel();
return true;
}
case R.id.operationsButton: {
toggleHistoryPanel();
return true;
}
case android.R.id.home: {
saveImage();
return true;
}
}
return false;
}
private void fillListImages(LinearLayout listFilters) {
// TODO: use listview
// TODO: load the filters straight from the filesystem
ImagePreset[] preset = new ImagePreset[9];
int p = 0;
preset[p++] = new ImagePreset();
preset[p++] = new ImagePresetSaturated();
preset[p++] = new ImagePresetOld();
preset[p++] = new ImagePresetXProcessing();
preset[p++] = new ImagePresetBW();
preset[p++] = new ImagePresetBWRed();
preset[p++] = new ImagePresetBWGreen();
preset[p++] = new ImagePresetBWBlue();
for (int i = 0; i < p; i++) {
ImageSmallFilter filter = new ImageSmallFilter(getBaseContext());
preset[i].setIsFx(true);
filter.setImagePreset(preset[i]);
filter.setController(this);
filter.setImageLoader(mImageLoader);
listFilters.addView(filter);
}
// Default preset (original)
mImageShow.setImagePreset(preset[0]);
}
private void fillListBorders(LinearLayout listBorders) {
// TODO: use listview
// TODO: load the borders straight from the filesystem
int p = 0;
ImageFilter[] borders = new ImageFilter[7];
borders[p++] = new ImageFilterBorder(null);
borders[p++] = new ImageFilterParametricBorder(Color.WHITE, 100, 0);
borders[p++] = new ImageFilterParametricBorder(Color.BLACK, 100, 0);
borders[p++] = new ImageFilterParametricBorder(Color.WHITE, 100, 100);
borders[p++] = new ImageFilterParametricBorder(Color.BLACK, 100, 100);
Drawable npd3 = getResources().getDrawable(R.drawable.filtershow_border_film3);
borders[p++] = new ImageFilterBorder(npd3);
Drawable npd = getResources().getDrawable(
R.drawable.filtershow_border_scratch3);
borders[p++] = new ImageFilterBorder(npd);
for (int i = 0; i < p; i++) {
ImageSmallFilter filter = new ImageSmallFilter(getBaseContext());
filter.setImageFilter(borders[i]);
filter.setController(this);
filter.setBorder(true);
filter.setImageLoader(mImageLoader);
filter.setShowTitle(false);
listBorders.addView(filter);
}
}
// //////////////////////////////////////////////////////////////////////////////
// Some utility functions
// TODO: finish the cleanup.
public void showOriginalViews(boolean value) {
for (ImageShow views : mImageViews) {
views.showOriginal(value);
}
}
public void invalidateViews() {
for (ImageShow views : mImageViews) {
views.invalidate();
views.updateImage();
}
}
public void hideListViews() {
for (View view : mListViews) {
view.setVisibility(View.GONE);
}
}
public void hideImageViews() {
mImageShow.setShowControls(false); // reset
for (View view : mImageViews) {
view.setVisibility(View.GONE);
}
}
public void unselectBottomPanelButtons() {
for (ImageButton button : mBottomPanelButtons) {
button.setSelected(false);
}
}
public void unselectPanelButtons(Vector<ImageButton> buttons) {
for (ImageButton button : buttons) {
button.setSelected(false);
}
}
// //////////////////////////////////////////////////////////////////////////////
// Click handlers for the top row buttons
private OnTouchListener createOnTouchShowOriginalButton() {
return new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
boolean show = false;
if ((event.getActionMasked() != MotionEvent.ACTION_UP)
|| (event.getActionMasked() == MotionEvent.ACTION_CANCEL)) {
show = true;
}
showOriginalViews(show);
return true;
}
};
}
// //////////////////////////////////////////////////////////////////////////////
// imageState panel...
private void toggleImageStatePanel() {
final View view = findViewById(R.id.mainPanel);
final View viewList = findViewById(R.id.imageStatePanel);
if (mShowingHistoryPanel) {
findViewById(R.id.historyPanel).setVisibility(View.INVISIBLE);
mShowingHistoryPanel = false;
}
if (!mShowingImageStatePanel) {
mShowingImageStatePanel = true;
view.animate().setDuration(200).x(-viewList.getWidth())
.withLayer().withEndAction(new Runnable() {
@Override
public void run() {
viewList.setAlpha(0);
viewList.setVisibility(View.VISIBLE);
viewList.animate().setDuration(100)
.alpha(1.0f).start();
}
}).start();
} else {
mShowingImageStatePanel = false;
viewList.setVisibility(View.INVISIBLE);
view.animate().setDuration(200).x(0).withLayer()
.start();
}
invalidateOptionsMenu();
}
// //////////////////////////////////////////////////////////////////////////////
// history panel...
private void toggleHistoryPanel() {
final View view = findViewById(R.id.mainPanel);
final View viewList = findViewById(R.id.historyPanel);
if (mShowingImageStatePanel) {
findViewById(R.id.imageStatePanel).setVisibility(View.INVISIBLE);
mShowingImageStatePanel = false;
}
if (!mShowingHistoryPanel) {
mShowingHistoryPanel = true;
view.animate().setDuration(200).x(-viewList.getWidth())
.withLayer().withEndAction(new Runnable() {
@Override
public void run() {
viewList.setAlpha(0);
viewList.setVisibility(View.VISIBLE);
viewList.animate().setDuration(100)
.alpha(1.0f).start();
}
}).start();
} else {
mShowingHistoryPanel = false;
viewList.setVisibility(View.INVISIBLE);
view.animate().setDuration(200).x(0).withLayer()
.start();
}
invalidateOptionsMenu();
}
private void resetHistory() {
HistoryAdapter adapter = (HistoryAdapter) mImageShow
.getHistoryAdapter();
adapter.reset();
ImagePreset original = new ImagePreset(adapter.getItem(0));
mImageShow.setImagePreset(original);
invalidateViews();
}
// reset button in the history panel.
private OnClickListener createOnClickResetOperationsButton() {
return new View.OnClickListener() {
@Override
public void onClick(View v) {
resetHistory();
}
};
}
// //////////////////////////////////////////////////////////////////////////////
public float getPixelsFromDip(float value) {
Resources r = getResources();
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value,
r.getDisplayMetrics());
}
public void useImagePreset(ImagePreset preset) {
if (preset == null) {
return;
}
ImagePreset copy = new ImagePreset(preset);
mImageShow.setImagePreset(copy);
if (preset.isFx()) {
// if it's an FX we rest the curve adjustment too
mImageCurves.resetCurve();
}
invalidateViews();
}
public void useImageFilter(ImageFilter imageFilter, boolean setBorder) {
if (imageFilter == null) {
return;
}
ImagePreset oldPreset = mImageShow.getImagePreset();
ImagePreset copy = new ImagePreset(oldPreset);
// TODO: use a numerical constant instead.
if (setBorder) {
copy.setHistoryName("Border");
copy.setBorder(imageFilter);
} else {
copy.add(imageFilter);
}
mImageShow.setImagePreset(copy);
invalidateViews();
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
mImageShow.onItemClick(position);
invalidateViews();
}
public void pickImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, getString(R.string.select_image)),
SELECT_PICTURE);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.v(LOGTAG, "onActivityResult");
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
mImageLoader.loadBitmap(selectedImageUri);
}
}
}
public void saveImage() {
showSavingProgress();
mImageShow.saveImage(this, null);
}
static {
System.loadLibrary("jni_filtershow_filters");
}
}
| true | false | null | null |
diff --git a/src/main/org/codehaus/groovy/syntax/lexer/StringLexer.java b/src/main/org/codehaus/groovy/syntax/lexer/StringLexer.java
index fdfefeb13..5f975e624 100644
--- a/src/main/org/codehaus/groovy/syntax/lexer/StringLexer.java
+++ b/src/main/org/codehaus/groovy/syntax/lexer/StringLexer.java
@@ -1,401 +1,404 @@
package org.codehaus.groovy.syntax.lexer;
//{{{ imports
import org.codehaus.groovy.syntax.ReadException;
import org.codehaus.groovy.syntax.Token;
import org.codehaus.groovy.GroovyBugError;
//}}}
/**
* A Lexer for processing standard strings.
*
* @author Chris Poirier
*/
public class StringLexer extends TextLexerBase
{
protected String delimiter = null;
protected char watchFor;
protected boolean allowGStrings = false;
protected boolean emptyString = true; // If set, we need to send an empty string
/**
* If set true, the filter will allow \\ and \$ to pass through unchanged.
* You should set this appropriately BEFORE setting source!
*/
public void allowGStrings( boolean allow )
{
allowGStrings = allow;
}
/**
* Returns a single STRING, then null. The STRING is all of the processed
* input. Backslashes are stripped, with the \r, \n, and \t converted
* appropriately.
*/
public Token undelegatedNextToken( ) throws ReadException, LexerException
{
if( emptyString )
{
emptyString = false;
return Token.newString( "", getStartLine(), getStartColumn() );
}
else if( finished )
{
return null;
}
else
{
StringBuffer string = new StringBuffer();
while( la(1) != CharStream.EOS )
{
string.append( consume() );
}
if( la(1) == CharStream.EOS && string.length() == 0 )
{
finished = true;
}
return Token.newString( string.toString(), getStartLine(), getStartColumn() );
}
}
/**
* Controls delimiter search. When turned on, the first thing we do
* is check for and eat our delimiter.
*/
public void delimit( boolean delimit )
{
super.delimit( delimit );
if( delimit )
{
try
{
if( !finished && la(1) == CharStream.EOS )
{
finishUp();
//
// The GStringLexer will correctly handle the empty string.
// We don't. In order to ensure that an empty string is
// supplied, we set a flag that is checked during
// undelegatedNextToken().
if( !allowGStrings )
{
emptyString = true;
}
}
}
catch( Exception e )
{
finished = true;
}
}
}
/**
* Sets the source lexer and identifies and consumes the opening delimiter.
*/
public void setSource( Lexer source )
{
super.setSource( source );
emptyString = false;
try
{
char c = source.la();
switch( c )
{
case '\'':
case '"':
mark();
source.consume();
if( source.la() == c && source.la(2) == c )
{
source.consume(); source.consume();
delimiter = new StringBuffer().append(c).append(c).append(c).toString();
}
else
{
delimiter = new StringBuffer().append(c).toString();
}
watchFor = delimiter.charAt(0);
break;
default:
{
throw new GroovyBugError( "at the time of StringLexer.setSource(), the source must be on a single or double quote" );
}
}
restart();
delimit( true );
}
catch( Exception e )
{
//
// If we couldn't read our delimiter, we'll just
// cancel our source. nextToken() will return null.
e.printStackTrace();
unsetSource( );
}
}
/**
* Unsets our source.
*/
public void unsetSource()
{
super.unsetSource();
delimiter = null;
finished = true;
emptyString = false;
}
//---------------------------------------------------------------------------
// STREAM ROUTINES
private int lookahead = 0; // the number of characters identified
private char[] characters = new char[3]; // the next characters identified by la()
private int[] widths = new int[3]; // the source widths of the next characters
/**
* Returns the next <code>k</code>th character, without consuming any.
*/
public char la(int k) throws LexerException, ReadException
{
if( !finished && source != null )
{
if( delimited )
{
if( k > characters.length )
{
throw new GroovyBugError( "StringLexer lookahead tolerance exceeded" );
}
if( lookahead >= k )
{
return characters[k-1];
}
lookahead = 0;
char c = ' ', c1 = ' ', c2 = ' ';
int offset = 1, width = 0;
for( int i = 1; i <= k; i++ )
{
c1 = source.la(offset);
C1_SWITCH: switch( c1 )
{
case CharStream.EOS:
{
return c1;
}
case '\\':
{
c2 = source.la( offset + 1 );
ESCAPE_SWITCH: switch( c2 )
{
case CharStream.EOS:
return c2;
case '\\':
+ c = '\\';
+ width = 2;
+ break ESCAPE_SWITCH;
case '$':
{
if( allowGStrings )
{
c = c1;
width = 1;
}
else
{
c = c2;
width = 2;
}
break ESCAPE_SWITCH;
}
case 'r':
c = '\r';
width = 2;
break ESCAPE_SWITCH;
case 't':
c = '\t';
width = 2;
break ESCAPE_SWITCH;
case 'n':
c = '\n';
width = 2;
break ESCAPE_SWITCH;
default:
c = c2;
width = 2;
break ESCAPE_SWITCH;
}
break C1_SWITCH;
}
default:
{
if( c1 == watchFor )
{
boolean atEnd = true;
for( int j = 1; j < delimiter.length(); j++ )
{
if( source.la(offset+j) != delimiter.charAt(j) )
{
atEnd = false;
break;
}
}
if( atEnd )
{
return CharStream.EOS;
}
}
c = c1;
width = 1;
break C1_SWITCH;
}
}
characters[lookahead] = c;
widths[lookahead] = width;
offset += width;
lookahead += 1;
}
return c; // <<< FLOW CONTROL <<<<<<<<<
}
lookahead = 0;
return source.la(k);
}
return CharStream.EOS;
}
/**
* Eats a character from the input stream. Searches for the delimiter if
* delimited. Note that turning delimiting on also checks if we are at the
* delimiter, so if we aren't finished, there is something to consume.
*/
public char consume() throws LexerException, ReadException
{
if( !finished && source != null )
{
char c = CharStream.EOS;
if( delimited )
{
if( lookahead < 1 )
{
la( 1 );
}
if( lookahead >= 1 )
{
c = characters[0];
for( int i = 0; i < widths[0]; i++ )
{
source.consume();
}
lookahead = 0;
}
if( la(1) == CharStream.EOS )
{
finishUp();
}
}
else
{
c = source.consume();
}
lookahead = 0;
return c;
}
return CharStream.EOS;
}
/**
* Eats our delimiter from the stream and marks us finished.
*/
protected void finishUp() throws LexerException, ReadException
{
for( int i = 0; i < delimiter.length(); i++ )
{
char c = source.la(1);
if( c == CharStream.EOS )
{
throw new UnterminatedStringLiteralException(getStartLine(), getStartColumn());
}
else if( c == delimiter.charAt(i) )
{
source.consume();
}
else
{
throw new GroovyBugError( "la() said delimiter [" + delimiter + "], finishUp() found [" + c + "]" );
}
}
finish();
}
}
| true | true | public char la(int k) throws LexerException, ReadException
{
if( !finished && source != null )
{
if( delimited )
{
if( k > characters.length )
{
throw new GroovyBugError( "StringLexer lookahead tolerance exceeded" );
}
if( lookahead >= k )
{
return characters[k-1];
}
lookahead = 0;
char c = ' ', c1 = ' ', c2 = ' ';
int offset = 1, width = 0;
for( int i = 1; i <= k; i++ )
{
c1 = source.la(offset);
C1_SWITCH: switch( c1 )
{
case CharStream.EOS:
{
return c1;
}
case '\\':
{
c2 = source.la( offset + 1 );
ESCAPE_SWITCH: switch( c2 )
{
case CharStream.EOS:
return c2;
case '\\':
case '$':
{
if( allowGStrings )
{
c = c1;
width = 1;
}
else
{
c = c2;
width = 2;
}
break ESCAPE_SWITCH;
}
case 'r':
c = '\r';
width = 2;
break ESCAPE_SWITCH;
case 't':
c = '\t';
width = 2;
break ESCAPE_SWITCH;
case 'n':
c = '\n';
width = 2;
break ESCAPE_SWITCH;
default:
c = c2;
width = 2;
break ESCAPE_SWITCH;
}
break C1_SWITCH;
}
default:
{
if( c1 == watchFor )
{
boolean atEnd = true;
for( int j = 1; j < delimiter.length(); j++ )
{
if( source.la(offset+j) != delimiter.charAt(j) )
{
atEnd = false;
break;
}
}
if( atEnd )
{
return CharStream.EOS;
}
}
c = c1;
width = 1;
break C1_SWITCH;
}
}
characters[lookahead] = c;
widths[lookahead] = width;
offset += width;
lookahead += 1;
}
return c; // <<< FLOW CONTROL <<<<<<<<<
}
lookahead = 0;
return source.la(k);
}
return CharStream.EOS;
}
| public char la(int k) throws LexerException, ReadException
{
if( !finished && source != null )
{
if( delimited )
{
if( k > characters.length )
{
throw new GroovyBugError( "StringLexer lookahead tolerance exceeded" );
}
if( lookahead >= k )
{
return characters[k-1];
}
lookahead = 0;
char c = ' ', c1 = ' ', c2 = ' ';
int offset = 1, width = 0;
for( int i = 1; i <= k; i++ )
{
c1 = source.la(offset);
C1_SWITCH: switch( c1 )
{
case CharStream.EOS:
{
return c1;
}
case '\\':
{
c2 = source.la( offset + 1 );
ESCAPE_SWITCH: switch( c2 )
{
case CharStream.EOS:
return c2;
case '\\':
c = '\\';
width = 2;
break ESCAPE_SWITCH;
case '$':
{
if( allowGStrings )
{
c = c1;
width = 1;
}
else
{
c = c2;
width = 2;
}
break ESCAPE_SWITCH;
}
case 'r':
c = '\r';
width = 2;
break ESCAPE_SWITCH;
case 't':
c = '\t';
width = 2;
break ESCAPE_SWITCH;
case 'n':
c = '\n';
width = 2;
break ESCAPE_SWITCH;
default:
c = c2;
width = 2;
break ESCAPE_SWITCH;
}
break C1_SWITCH;
}
default:
{
if( c1 == watchFor )
{
boolean atEnd = true;
for( int j = 1; j < delimiter.length(); j++ )
{
if( source.la(offset+j) != delimiter.charAt(j) )
{
atEnd = false;
break;
}
}
if( atEnd )
{
return CharStream.EOS;
}
}
c = c1;
width = 1;
break C1_SWITCH;
}
}
characters[lookahead] = c;
widths[lookahead] = width;
offset += width;
lookahead += 1;
}
return c; // <<< FLOW CONTROL <<<<<<<<<
}
lookahead = 0;
return source.la(k);
}
return CharStream.EOS;
}
|
diff --git a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/custom/EditorUtils.java b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/custom/EditorUtils.java
index 14c818fa6..bde566193 100755
--- a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/custom/EditorUtils.java
+++ b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/custom/EditorUtils.java
@@ -1,687 +1,688 @@
/*
* Copyright 2012 WSO2, Inc. (http://wso2.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.synapse.Mediator;
import org.apache.synapse.mediators.base.SequenceMediator;
import org.apache.synapse.mediators.builtin.SendMediator;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.RootEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editparts.GraphicalEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editparts.ShapeCompartmentEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editparts.ShapeNodeEditPart;
import org.eclipse.gmf.runtime.notation.Diagram;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.PlatformUI;
import org.wso2.developerstudio.eclipse.gmf.esb.APIResource;
import org.wso2.developerstudio.eclipse.gmf.esb.EsbDiagram;
import org.wso2.developerstudio.eclipse.gmf.esb.EsbServer;
import org.wso2.developerstudio.eclipse.gmf.esb.ProxyService;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.APIResourceEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.APIResourceFaultInputConnectorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.APIResourceOutSequenceOutputConnectorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.CloneMediatorContainerEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.CloneMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.ComplexEndpointsEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.ComplexEndpointsOutputConnectorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.EsbDiagramEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.EsbLinkEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.FilterContainerEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.FilterMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.MediatorFlowMediatorFlowCompartment10EditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.MediatorFlowMediatorFlowCompartment11EditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.MediatorFlowMediatorFlowCompartment2EditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.MediatorFlowMediatorFlowCompartment4EditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.MediatorFlowMediatorFlowCompartment7EditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.MediatorFlowMediatorFlowCompartment8EditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.MediatorFlowMediatorFlowCompartment9EditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.MediatorFlowMediatorFlowCompartmentEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.ProxyFaultInputConnectorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.ProxyOutSequenceOutputConnectorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.ProxyServiceEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.Sequences2EditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.SequencesEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.SwitchMediatorContainerEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.SwitchMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.ThrottleContainerEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.ThrottleMediatorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.part.EsbDiagramEditor;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.part.EsbMultiPageEditor;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.part.EsbPaletteFactory;
public class EditorUtils {
public static final String DIAGRAM_FILE_EXTENSION = ".esb_diagram";
public static final String DOMAIN_FILE_EXTENSION = ".esb";
public static final String SYNAPSE_CONFIG_DIR = "src/main/synapse-config";
public static final String SYNAPSE_RESOURCE_DIR = "src/main/graphical-synapse-config";
public static final String SEQUENCE_RESOURCE_DIR = "src/main/graphical-synapse-config/sequences";
public static final String PROXY_RESOURCE_DIR = "src/main/graphical-synapse-config/proxy-services";
public static final String ENDPOINT_RESOURCE_DIR = "src/main/graphical-synapse-config/endpoints";
public static final String LOCAL_ENTRY_RESOURCE_DIR = "src/main/graphical-synapse-config/local-entries";
public static final String TEMPLATE_RESOURCE_DIR = "src/main/graphical-synapse-config/templates";
public static final String TASK_RESOURCE_DIR = "src/main/graphical-synapse-config/tasks";
public static final String API_RESOURCE_DIR = "src/main/graphical-synapse-config/api";
public static final String COMPLEX_ENDPOINT_RESOURCE_DIR = "src/main/graphical-synapse-config/complex_endpoints";
public static AbstractInputConnectorEditPart getInputConnector(ShapeNodeEditPart parent){
for(int i=0;i<parent.getChildren().size();++i){
if(parent.getChildren().get(i) instanceof AbstractInputConnectorEditPart){
return (AbstractInputConnectorEditPart) parent.getChildren().get(i);
}
}
return null;
}
public static AbstractOutputConnectorEditPart getOutputConnector(ShapeNodeEditPart parent){
for(int i=0;i<parent.getChildren().size();++i){
if(parent.getChildren().get(i) instanceof AbstractOutputConnectorEditPart){
return (AbstractOutputConnectorEditPart) parent.getChildren().get(i);
}
}
return null;
}
/**
* Look up OutputConnector by EditPart and type
* @param <T>
* @param parent
* @param type
* @return
*/
public static <T extends AbstractOutputConnectorEditPart> T getOutputConnector(
ShapeNodeEditPart parent, Class<T> type) {
for (int i = 0; i < parent.getChildren().size(); ++i) {
if (type.isInstance(parent.getChildren().get(i))) {
return type.cast(parent.getChildren().get(i));
}
}
return null;
}
public static AbstractMediatorInputConnectorEditPart getMediatorInputConnector(ShapeNodeEditPart parent){
if(parent!=null){
for(int i=0;i<parent.getChildren().size();++i){
if(parent.getChildren().get(i) instanceof AbstractMediatorInputConnectorEditPart){
return (AbstractMediatorInputConnectorEditPart) parent.getChildren().get(i);
}
}
}
return null;
}
public static AbstractMediatorOutputConnectorEditPart getMediatorOutputConnector(ShapeNodeEditPart parent){
for(int i=0;i<parent.getChildren().size();++i){
if(parent.getChildren().get(i) instanceof AbstractMediatorOutputConnectorEditPart){
return (AbstractMediatorOutputConnectorEditPart) parent.getChildren().get(i);
}
}
return null;
}
public static ArrayList<AdditionalOutputConnector> getMediatorAdditionalOutputConnectors(ShapeNodeEditPart parent){
ArrayList<AdditionalOutputConnector> connectors=new ArrayList<AdditionalOutputConnector>();
for(int i=0;i<parent.getChildren().size();++i){
if(parent.getChildren().get(i) instanceof AdditionalOutputConnector){
connectors.add((AdditionalOutputConnector) parent.getChildren().get(i));
}
}
return connectors;
}
public static AbstractEndpointInputConnectorEditPart getEndpointInputConnector(ShapeNodeEditPart parent){
for(int i=0;i<parent.getChildren().size();++i){
if(parent.getChildren().get(i) instanceof AbstractEndpointInputConnectorEditPart){
return (AbstractEndpointInputConnectorEditPart) parent.getChildren().get(i);
}
}
return null;
}
public static AbstractEndpointOutputConnectorEditPart getEndpointOutputConnector(ShapeNodeEditPart parent){
for(int i=0;i<parent.getChildren().size();++i){
if(parent.getChildren().get(i) instanceof AbstractEndpointOutputConnectorEditPart){
return (AbstractEndpointOutputConnectorEditPart) parent.getChildren().get(i);
}
}
return null;
}
public static AbstractProxyServiceContainerEditPart getProxyContainer(ShapeNodeEditPart parent){
for(int i=0;i<parent.getChildren().size();++i){
if(parent.getChildren().get(i) instanceof AbstractProxyServiceContainerEditPart){
return (AbstractProxyServiceContainerEditPart) parent.getChildren().get(i);
}
}
return null;
}
public static AbstractInputConnectorEditPart getProxyFaultInputConnector(ShapeNodeEditPart parent){
for(int i=0;i<parent.getChildren().size();++i){
if(parent.getChildren().get(i) instanceof ProxyFaultInputConnectorEditPart){
return (ProxyFaultInputConnectorEditPart) parent.getChildren().get(i);
}else if(parent.getChildren().get(i) instanceof APIResourceFaultInputConnectorEditPart){
return (APIResourceFaultInputConnectorEditPart) parent.getChildren().get(i);
}
}
return null;
}
public static AbstractOutputConnectorEditPart getProxyOutSequenceOutputConnector(ShapeNodeEditPart parent){
for(int i=0;i<parent.getChildren().size();++i){
if(parent.getChildren().get(i) instanceof ProxyOutSequenceOutputConnectorEditPart){
return (ProxyOutSequenceOutputConnectorEditPart) parent.getChildren().get(i);
}else if(parent.getChildren().get(i) instanceof APIResourceOutSequenceOutputConnectorEditPart){
return (APIResourceOutSequenceOutputConnectorEditPart) parent.getChildren().get(i);
}
}
return null;
}
public static ArrayList<ComplexEndpointsOutputConnectorEditPart> getComplexEndpointsOutputConnectors(ComplexEndpointsEditPart parent){
ArrayList<ComplexEndpointsOutputConnectorEditPart> outputConnectors=new ArrayList<ComplexEndpointsOutputConnectorEditPart>();
for(int i=0;i<parent.getChildren().size();++i){
if(parent.getChildren().get(i) instanceof ComplexEndpointsOutputConnectorEditPart){
outputConnectors.add((ComplexEndpointsOutputConnectorEditPart) parent.getChildren().get(i));
}
}
return outputConnectors;
}
public static AbstractMediator getMediator(EditPart compartment){
EditPart child=compartment;
while ((child.getParent()!=null)&&!(child.getParent() instanceof AbstractMediator)){
child=child.getParent();
}
if(child.getParent()!=null){
return (AbstractMediator) child.getParent();
}else{
return null;
}
}
public static EditPart getComplexMediator(EditPart compartment){
EditPart editPart=compartment;
if(editPart instanceof MediatorFlowMediatorFlowCompartment7EditPart // filter pass
|| editPart instanceof MediatorFlowMediatorFlowCompartment8EditPart // filter fail
|| editPart instanceof MediatorFlowMediatorFlowCompartment9EditPart // throttle onaccept
|| editPart instanceof MediatorFlowMediatorFlowCompartment10EditPart // throttle onreject
|| editPart instanceof MediatorFlowMediatorFlowCompartment2EditPart // switch case
|| editPart instanceof MediatorFlowMediatorFlowCompartment4EditPart // switch default
|| editPart instanceof MediatorFlowMediatorFlowCompartment11EditPart) { // clone target
return editPart.getParent().getParent().getParent().getParent();
}
else {
return null;
}
}
/*
* You can get the MediatorEditPart of the entered ConnectorEditPart using this method.
*/
public static AbstractMediator getMediator(AbstractConnectorEditPart connector){
EditPart temp=connector;
while((temp !=null)&&(!(temp instanceof AbstractMediator))){
temp=temp.getParent();
}
if(temp instanceof AbstractMediator){
return (AbstractMediator) temp;
}
else{
return null;
}
}
public static AbstractEndpoint getEndpoint(AbstractConnectorEditPart connector){
EditPart temp=connector;
while((temp !=null)&&(!(temp instanceof AbstractEndpoint))){
temp=temp.getParent();
}
if(temp instanceof AbstractEndpoint){
return (AbstractEndpoint) temp;
}
else{
return null;
}
}
public static ProxyServiceEditPart getProxy(AbstractConnectorEditPart connector){
EditPart temp=connector;
while((temp !=null)&&(!(temp instanceof ProxyServiceEditPart))){
temp=temp.getParent();
}
if(temp instanceof ProxyServiceEditPart){
return (ProxyServiceEditPart) temp;
}
else{
return null;
}
}
public static ProxyServiceEditPart getProxy(EditPart child){
while ((child.getParent()!=null)&&!(child.getParent() instanceof ProxyServiceEditPart)){
child=child.getParent();
}
if(child.getParent()!=null){
return (ProxyServiceEditPart) child.getParent();
}else{
return null;
}
}
public static AbstractBaseFigureEditPart getAbstractBaseFigureEditPart(EditPart child){
while ((child.getParent()!=null)&&!(child.getParent() instanceof AbstractBaseFigureEditPart)){
child=child.getParent();
}
if(child.getParent()!=null){
return (AbstractBaseFigureEditPart) child.getParent();
}else{
return null;
}
}
public static IGraphicalEditPart getRootContainer(EditPart child) {
while ((child.getParent() != null)
&& !(child.getParent() instanceof AbstractBaseFigureEditPart)) {
child = child.getParent();
}
if (child.getParent() != null) {
return (IGraphicalEditPart) child.getParent();
} else {
return null;
}
}
public static EObject getRootContainerModel(EObject child) {
while ((child.eContainer() != null)
&& !(child.eContainer() instanceof ProxyService || child.eContainer() instanceof APIResource)) {
child = child.eContainer();
}
if (child.eContainer() != null) {
return (EObject) child.eContainer();
} else {
return null;
}
}
public static MediatorFlowMediatorFlowCompartmentEditPart getSequenceAndEndpointCompartmentEditPart(EditPart child){
while ((child.getParent()!=null)&&!(child.getParent() instanceof MediatorFlowMediatorFlowCompartmentEditPart)){
child=child.getParent();
}
if(child.getParent()!=null){
return (MediatorFlowMediatorFlowCompartmentEditPart) child.getParent();
}else{
return null;
}
}
public static AbstractSequencesEditPart getSequence(AbstractConnectorEditPart connector){
EditPart temp=connector;
while((temp !=null)&&(!(temp instanceof AbstractSequencesEditPart))){
temp=temp.getParent();
}
if(temp instanceof AbstractSequencesEditPart){
return (AbstractSequencesEditPart) temp;
}
else{
return null;
}
}
public static ComplexEndpointsEditPart getComplexEndpoint(AbstractConnectorEditPart connector){
EditPart temp=connector;
while((temp !=null)&&(!(temp instanceof ComplexEndpointsEditPart))){
temp=temp.getParent();
}
if(temp instanceof ComplexEndpointsEditPart){
return (ComplexEndpointsEditPart) temp;
}
else{
return null;
}
}
public static APIResourceEditPart getAPIResource(AbstractConnectorEditPart connector){
EditPart temp=connector;
while((temp !=null)&&(!(temp instanceof APIResourceEditPart))){
temp=temp.getParent();
}
if(temp instanceof APIResourceEditPart){
return (APIResourceEditPart) temp;
}
else{
return null;
}
}
/**
* Sets the status of the lock attribute.
* @param editor
* @param lockmode
*/
public static void setLockmode(EsbDiagramEditor editor, boolean lockmode) {
EsbServer esbServer = getEsbServer(editor);
if (esbServer != null) {
esbServer.setLockmode(lockmode);
}
}
/**
* Returns the status of the lock attribute.
* @param editor
* @return
*/
public static boolean isLockmode(EsbDiagramEditor editor) {
EsbServer esbServer = getEsbServer(editor);
if (esbServer != null) {
return esbServer.isLockmode();
}
return false;
}
/**
* Sets the status of the lock attribute.
* @param editPart
* @param lockmode
*/
public static void setLockmode(GraphicalEditPart editPart, boolean lockmode) {
EsbServer esbServer = getEsbServer(editPart);
if (esbServer != null) {
esbServer.setLockmode(lockmode);
}
}
/**
* Returns the status of the lock attribute.
* @param editPart
* @return
*/
public static boolean isLockmode(GraphicalEditPart editPart) {
EsbServer esbServer = getEsbServer(editPart);
if (esbServer != null) {
return esbServer.isLockmode();
}
return false;
}
/**
* Returns the EsbServer model
* @param editor
* @return
*/
public static EsbServer getEsbServer(EsbDiagramEditor editor) {
Diagram diagram = editor.getDiagram();
EsbDiagram esbDiagram = (EsbDiagram) diagram.getElement();
EsbServer esbServer = esbDiagram.getServer();
return esbServer;
}
/**
* Returns the EsbServer model
* @param editPart
* @return
*/
public static EsbServer getEsbServer(GraphicalEditPart editPart) {
RootEditPart root = editPart.getRoot();
if (root.getChildren().size() == 1
&& root.getChildren().get(0) instanceof EsbDiagramEditPart) {
EsbDiagramEditPart EsbDiagramEditPart = (EsbDiagramEditPart) root.getChildren().get(0);
EsbDiagram esbDiagram = (EsbDiagram) ((View) EsbDiagramEditPart.getModel())
.getElement();
EsbServer esbServer = esbDiagram.getServer();
return esbServer;
}
return null;
}
public static void updateToolpalette() {
Display.getCurrent().asyncExec(new Runnable() {
public void run() {
IEditorReference editorReferences[] = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
.getActivePage().getEditorReferences();
IEditorPart activeEditor=PlatformUI.getWorkbench().getActiveWorkbenchWindow()
.getActivePage().getActiveEditor();
for (int i = 0; i < editorReferences.length; i++) {
IEditorPart editor = editorReferences[i].getEditor(false);
if ((editor instanceof EsbMultiPageEditor)) {
/*
* This must be altered. 'addDefinedSequences' and 'addDefinedEndpoints' methods should not exist inside EsbPaletteFactory class.
* Creating new instance of 'EsbPaletteFactory' must be avoided.
*/
EsbPaletteFactory esbPaletteFactory=new EsbPaletteFactory();
if(!editor.equals(activeEditor)){
esbPaletteFactory.addDefinedSequences(((EsbMultiPageEditor) editor).getGraphicalEditor());
esbPaletteFactory.addDefinedEndpoints(((EsbMultiPageEditor) editor).getGraphicalEditor());
}else{
//esbPaletteFactory.addCloudConnectorOperations(((EsbMultiPageEditor) editor).getGraphicalEditor());
}
}
}
}
});
}
/**
* A utility method to remove currently unsupported mediators/flows from a
* sequence
*
* @param sequence
* @return
*/
public static SequenceMediator stripUnsupportedMediators(SequenceMediator sequence) {
SequenceMediator newSequence = new SequenceMediator();
for (Iterator<Mediator> i = sequence.getList().iterator(); i.hasNext();) {
Mediator next = i.next();
newSequence.addChild(next);
if (next instanceof SendMediator) {
/*
* current impemetaion does not support any mediator after send
* mediator in given sequence, this might be changed in next
* releases
*/
break;
}
}
return newSequence;
}
/**
* Returns true if the flow has a cycle. but returning false does not
* guarantee that it hasn't cycles
* @param source
* @param target
* @return
*/
public static boolean hasCycle(EditPart source, EditPart target) {
for (EditPart next = target; next != null; next = getNextNode(next)) {
if (next instanceof AbstractEndpoint || next instanceof SequencesEditPart
|| next instanceof Sequences2EditPart) {
break;
}
if (next == source) {
return true;
}
}
return false;
}
/**
* Returns the next element in the node flow.
*/
private static EditPart getNextNode(EditPart node) {
EditPart next = null;
if (node instanceof ShapeNodeEditPart) {
AbstractOutputConnectorEditPart nextOutputConnector = EditorUtils
.getOutputConnector((ShapeNodeEditPart) node);
if (nextOutputConnector != null) {
/*
* List<EsbLinkEditPart> connections = nextOutputConnector
* .getTargetConnections(); for (EsbLinkEditPart object :
* connections) { if(object.getTarget() instanceof EditPart){
* return object.getTarget().getParent(); } }
*/
@SuppressWarnings("unchecked")
List<EsbLinkEditPart> connections = nextOutputConnector.getSourceConnections();
for (EsbLinkEditPart object : connections) {
/* At the moment, we are not going to handle multipe links */
if (object.getTarget() instanceof EditPart) {
return object.getTarget().getParent();
}
}
}
}
return next;
}
/**
* Returns true if source and target are connectable
* @param source
* @param target
* @return
* FIXME: please improve
*/
public static boolean isConnectableTarget(EditPart source, EditPart target) {
if (source.getParent() instanceof ShapeCompartmentEditPart
&& target.getParent() instanceof ShapeCompartmentEditPart) {
ShapeCompartmentEditPart sourceCompartment = (ShapeCompartmentEditPart) source
.getParent();
ShapeCompartmentEditPart targetCompartment = (ShapeCompartmentEditPart) target
.getParent();
if (sourceCompartment == targetCompartment) {
return true;
} else if (isChildOfTarget(sourceCompartment, targetCompartment)
|| isChildOfTarget(targetCompartment, sourceCompartment)) {
return true;
}
}
return false;
}
/**
* Returns true if the source is a child of target.
* FIXME: please improve
*/
private static boolean isChildOfTarget(EditPart source, EditPart target) {
EditPart parent = target;
while ((parent = parent.getParent()) != null) {
if (parent == source) {
return true;
}
}
return false;
}
/**
* Return the active editor
*/
public static IProject getActiveProject() {
IEditorPart editorPart = null;
IProject activeProject = null;
IEditorReference editorReferences[] = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
.getActivePage().getEditorReferences();
for (int i = 0; i < editorReferences.length; i++) {
IEditorPart editor = editorReferences[i].getEditor(false);
if (editor != null) {
editorPart = editor.getSite().getWorkbenchWindow().getActivePage()
.getActiveEditor();
}
if (editorPart != null) {
IFileEditorInput input = (IFileEditorInput) editorPart.getEditorInput();
IFile file = input.getFile();
activeProject = file.getProject();
}
}
return activeProject;
}
public static ShapeNodeEditPart getChildContainer(MultipleCompartmentComplexFiguredAbstractMediator mediator) {
if (mediator instanceof SwitchMediatorEditPart) {
for(int i=0;i<mediator.getChildren().size();++i){
if(mediator.getChildren().get(i) instanceof SwitchMediatorContainerEditPart){
return (SwitchMediatorContainerEditPart) mediator.getChildren().get(i);
}
}
}else if (mediator instanceof FilterMediatorEditPart) {
for(int i=0;i<mediator.getChildren().size();++i){
if(mediator.getChildren().get(i) instanceof FilterContainerEditPart){
return (FilterContainerEditPart) mediator.getChildren().get(i);
}
}
}else if (mediator instanceof ThrottleMediatorEditPart) {
for(int i=0;i<mediator.getChildren().size();++i){
if(mediator.getChildren().get(i) instanceof ThrottleContainerEditPart){
return (ThrottleContainerEditPart) mediator.getChildren().get(i);
}
}
}else if (mediator instanceof CloneMediatorEditPart) {
for(int i=0;i<mediator.getChildren().size();++i){
if(mediator.getChildren().get(i) instanceof CloneMediatorContainerEditPart){
return (CloneMediatorContainerEditPart) mediator.getChildren().get(i);
}
}
}
return null;
}
public static boolean isAChildOf(AbstractMediator parentMediator, AbstractMediator thisMediator) {
- ShapeNodeEditPart childContainer = getChildContainer((MultipleCompartmentComplexFiguredAbstractMediator)parentMediator);
- List<EditPart> childEditParts = childContainer.getChildren();
- for (EditPart editPart : childEditParts) {
- IGraphicalEditPart mediatorFlow = (IGraphicalEditPart)editPart.getChildren().get(0);
- IGraphicalEditPart mediatorFlowCompartment = (IGraphicalEditPart)mediatorFlow.getChildren().get(0);
- if (mediatorFlowCompartment.getChildren().size() >= 1) {
- for (int i = 0; i < mediatorFlowCompartment.getChildren().size(); ++i) {
- AbstractMediator gep = (AbstractMediator) mediatorFlowCompartment.getChildren().get(i);
- if (gep.equals(thisMediator)) {
- return true;
+ if (parentMediator instanceof MultipleCompartmentComplexFiguredAbstractMediator) {
+ ShapeNodeEditPart childContainer = getChildContainer((MultipleCompartmentComplexFiguredAbstractMediator)parentMediator);
+ List<EditPart> childEditParts = childContainer.getChildren();
+ for (EditPart editPart : childEditParts) {
+ IGraphicalEditPart mediatorFlow = (IGraphicalEditPart)editPart.getChildren().get(0);
+ IGraphicalEditPart mediatorFlowCompartment = (IGraphicalEditPart)mediatorFlow.getChildren().get(0);
+ if (mediatorFlowCompartment.getChildren().size() >= 1) {
+ for (int i = 0; i < mediatorFlowCompartment.getChildren().size(); ++i) {
+ AbstractMediator gep = (AbstractMediator) mediatorFlowCompartment.getChildren().get(i);
+ if (gep.equals(thisMediator)) {
+ return true;
+ }
}
}
}
}
-
return false;
}
}
| false | false | null | null |
diff --git a/idl-frontend/src/main/java/org/ow2/mind/idl/IncludeHeaderResolver.java b/idl-frontend/src/main/java/org/ow2/mind/idl/IncludeHeaderResolver.java
index cf1ac20..344ee2c 100644
--- a/idl-frontend/src/main/java/org/ow2/mind/idl/IncludeHeaderResolver.java
+++ b/idl-frontend/src/main/java/org/ow2/mind/idl/IncludeHeaderResolver.java
@@ -1,121 +1,123 @@
/**
* Copyright (C) 2009 STMicroelectronics
*
* This file is part of "Mind Compiler" 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.
*
* 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 Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact: [email protected]
*
* Authors: Matthieu Leclercq
* Contributors:
*/
package org.ow2.mind.idl;
import static org.ow2.mind.PathHelper.getExtension;
import static org.ow2.mind.PathHelper.toAbsolute;
import static org.ow2.mind.idl.ast.IDLASTHelper.getIncludedPath;
import static org.ow2.mind.idl.ast.Include.HEADER_EXTENSION;
import java.net.URL;
import java.util.Map;
import org.objectweb.fractal.adl.ADLException;
import org.objectweb.fractal.adl.NodeFactory;
import org.ow2.mind.CommonASTHelper;
import org.ow2.mind.PathHelper;
import org.ow2.mind.PathHelper.InvalidRelativPathException;
import org.ow2.mind.error.ErrorManager;
import org.ow2.mind.idl.IncludeResolver.AbstractDelegatingIncludeResolver;
import org.ow2.mind.idl.ast.Header;
import org.ow2.mind.idl.ast.IDL;
import org.ow2.mind.idl.ast.IDLASTHelper;
import org.ow2.mind.idl.ast.Include;
import com.google.inject.Inject;
public class IncludeHeaderResolver extends AbstractDelegatingIncludeResolver {
@Inject
protected ErrorManager errorManagerItf;
@Inject
protected NodeFactory nodeFactoryItf;
@Inject
protected IDLLocator idlLocatorItf;
// ---------------------------------------------------------------------------
// Implementation of the UsedIDLResolver interface
// ---------------------------------------------------------------------------
public IDL resolve(final Include include, final IDL encapsulatingIDL,
final String encapsulatingName, final Map<Object, Object> context)
throws ADLException {
String path = getIncludedPath(include);
if (getExtension(path).equals(HEADER_EXTENSION)) {
// include node references a header C file.
if (IDLASTHelper.getIncludeDelimiter(include) == IDLASTHelper.IncludeDelimiter.QUOTE) {
// try to find header file and update the path if needed
- final String encapsulatingIDLName = encapsulatingIDL.getName();
+ final String encapsulatingIDLName = (encapsulatingIDL != null)
+ ? encapsulatingIDL.getName()
+ : encapsulatingName;
final String encapsulatingDir;
if (encapsulatingIDLName.startsWith("/")) {
encapsulatingDir = PathHelper.getParent(encapsulatingIDLName);
} else {
encapsulatingDir = PathHelper
.fullyQualifiedNameToDirName(encapsulatingIDLName);
}
if (!path.startsWith("/")) {
// look-for header relatively to encapsulatingDir
String relPath;
try {
relPath = toAbsolute(encapsulatingDir, path);
} catch (final InvalidRelativPathException e) {
errorManagerItf.logError(IDLErrors.INVALID_INCLUDE, include, path);
return IDLASTHelper.newUnresolvedIDLNode(nodeFactoryItf, path);
}
URL url = idlLocatorItf.findSourceHeader(relPath, context);
if (url != null) {
// IDL found with relPath
path = relPath;
IDLASTHelper.setIncludePathPreserveDelimiter(include, path);
} else if (path.startsWith("./") || path.startsWith("../")) {
// the path starts with "./" or "../" which force a resolution
// relatively to encapsulatingDir. the file has not been found.
errorManagerItf.logError(IDLErrors.IDL_NOT_FOUND, include, path);
return IDLASTHelper.newUnresolvedIDLNode(nodeFactoryItf, path);
} else {
// look-for header relatively to source-path
path = "/" + path;
url = idlLocatorItf.findSourceHeader(path, context);
if (url != null) {
IDLASTHelper.setIncludePathPreserveDelimiter(include, path);
}
}
}
}
// create a new Header AST node
final Header header = CommonASTHelper.newNode(nodeFactoryItf, "header",
Header.class);
header.setName(path);
return header;
} else {
return clientResolverItf.resolve(include, encapsulatingIDL,
encapsulatingName, context);
}
}
}
| true | true | public IDL resolve(final Include include, final IDL encapsulatingIDL,
final String encapsulatingName, final Map<Object, Object> context)
throws ADLException {
String path = getIncludedPath(include);
if (getExtension(path).equals(HEADER_EXTENSION)) {
// include node references a header C file.
if (IDLASTHelper.getIncludeDelimiter(include) == IDLASTHelper.IncludeDelimiter.QUOTE) {
// try to find header file and update the path if needed
final String encapsulatingIDLName = encapsulatingIDL.getName();
final String encapsulatingDir;
if (encapsulatingIDLName.startsWith("/")) {
encapsulatingDir = PathHelper.getParent(encapsulatingIDLName);
} else {
encapsulatingDir = PathHelper
.fullyQualifiedNameToDirName(encapsulatingIDLName);
}
if (!path.startsWith("/")) {
// look-for header relatively to encapsulatingDir
String relPath;
try {
relPath = toAbsolute(encapsulatingDir, path);
} catch (final InvalidRelativPathException e) {
errorManagerItf.logError(IDLErrors.INVALID_INCLUDE, include, path);
return IDLASTHelper.newUnresolvedIDLNode(nodeFactoryItf, path);
}
URL url = idlLocatorItf.findSourceHeader(relPath, context);
if (url != null) {
// IDL found with relPath
path = relPath;
IDLASTHelper.setIncludePathPreserveDelimiter(include, path);
} else if (path.startsWith("./") || path.startsWith("../")) {
// the path starts with "./" or "../" which force a resolution
// relatively to encapsulatingDir. the file has not been found.
errorManagerItf.logError(IDLErrors.IDL_NOT_FOUND, include, path);
return IDLASTHelper.newUnresolvedIDLNode(nodeFactoryItf, path);
} else {
// look-for header relatively to source-path
path = "/" + path;
url = idlLocatorItf.findSourceHeader(path, context);
if (url != null) {
IDLASTHelper.setIncludePathPreserveDelimiter(include, path);
}
}
}
}
// create a new Header AST node
final Header header = CommonASTHelper.newNode(nodeFactoryItf, "header",
Header.class);
header.setName(path);
return header;
} else {
return clientResolverItf.resolve(include, encapsulatingIDL,
encapsulatingName, context);
}
}
| public IDL resolve(final Include include, final IDL encapsulatingIDL,
final String encapsulatingName, final Map<Object, Object> context)
throws ADLException {
String path = getIncludedPath(include);
if (getExtension(path).equals(HEADER_EXTENSION)) {
// include node references a header C file.
if (IDLASTHelper.getIncludeDelimiter(include) == IDLASTHelper.IncludeDelimiter.QUOTE) {
// try to find header file and update the path if needed
final String encapsulatingIDLName = (encapsulatingIDL != null)
? encapsulatingIDL.getName()
: encapsulatingName;
final String encapsulatingDir;
if (encapsulatingIDLName.startsWith("/")) {
encapsulatingDir = PathHelper.getParent(encapsulatingIDLName);
} else {
encapsulatingDir = PathHelper
.fullyQualifiedNameToDirName(encapsulatingIDLName);
}
if (!path.startsWith("/")) {
// look-for header relatively to encapsulatingDir
String relPath;
try {
relPath = toAbsolute(encapsulatingDir, path);
} catch (final InvalidRelativPathException e) {
errorManagerItf.logError(IDLErrors.INVALID_INCLUDE, include, path);
return IDLASTHelper.newUnresolvedIDLNode(nodeFactoryItf, path);
}
URL url = idlLocatorItf.findSourceHeader(relPath, context);
if (url != null) {
// IDL found with relPath
path = relPath;
IDLASTHelper.setIncludePathPreserveDelimiter(include, path);
} else if (path.startsWith("./") || path.startsWith("../")) {
// the path starts with "./" or "../" which force a resolution
// relatively to encapsulatingDir. the file has not been found.
errorManagerItf.logError(IDLErrors.IDL_NOT_FOUND, include, path);
return IDLASTHelper.newUnresolvedIDLNode(nodeFactoryItf, path);
} else {
// look-for header relatively to source-path
path = "/" + path;
url = idlLocatorItf.findSourceHeader(path, context);
if (url != null) {
IDLASTHelper.setIncludePathPreserveDelimiter(include, path);
}
}
}
}
// create a new Header AST node
final Header header = CommonASTHelper.newNode(nodeFactoryItf, "header",
Header.class);
header.setName(path);
return header;
} else {
return clientResolverItf.resolve(include, encapsulatingIDL,
encapsulatingName, context);
}
}
|
diff --git a/tea/src/main/java/org/teatrove/tea/compiler/CompilationUnit.java b/tea/src/main/java/org/teatrove/tea/compiler/CompilationUnit.java
index ce300e8..06e1ea8 100644
--- a/tea/src/main/java/org/teatrove/tea/compiler/CompilationUnit.java
+++ b/tea/src/main/java/org/teatrove/tea/compiler/CompilationUnit.java
@@ -1,406 +1,407 @@
/*
* Copyright 1997-2011 teatrove.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.teatrove.tea.compiler;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.util.Arrays;
import org.teatrove.tea.parsetree.Template;
import org.teatrove.tea.parsetree.Variable;
import org.teatrove.trove.classfile.TypeDesc;
import org.teatrove.trove.io.DualOutput;
import org.teatrove.trove.io.SourceReader;
import org.teatrove.trove.util.ClassInjector;
/**
* A compilation unit is a unit of compilation for a given template that
* provides source details and outputs the compiled result to a given set of
* output streams (class files, injectors, etc). It works hand-in-hand with the
* associated compiler during compilation.
*
* @author Brian S O'Neill
*/
public class CompilationUnit implements ErrorListener {
private String mName;
private Compiler mCompiler;
private Template mTree;
private CompilationSource mSource;
private int mErrorCount;
private File mDestDir;
private File mDestFile;
public CompilationUnit(String name, CompilationSource source,
Compiler compiler) {
mName = name;
mSource = source;
mCompiler = compiler;
initialize();
}
private void initialize() {
String slashPath = mName.replace('.', '/');
if (slashPath.endsWith("/")) {
slashPath = slashPath.substring(0, slashPath.length() - 1);
}
File rootDestDir = mCompiler.getRootDestDir();
if (rootDestDir != null) {
if (slashPath.lastIndexOf('/') >= 0) {
mDestDir = new File
(rootDestDir,
slashPath.substring(0,slashPath.lastIndexOf('/')));
}
else {
mDestDir = rootDestDir;
}
mDestDir.mkdirs();
mDestFile = new File(
mDestDir,
slashPath.substring(slashPath.lastIndexOf('/') + 1) +
".class"
);
}
}
public String getName() {
return mName;
}
public String getShortName() {
String name = getName();
int index = name.lastIndexOf('.');
if (index >= 0) {
return name.substring(index + 1);
}
return name;
}
public String getSourcePath() {
return mSource == null ? null : mSource.getSourcePath();
}
/**
* Get the associated compiler for this unit.
*
* @return The associated compiler for this compilation unit
*/
protected Compiler getCompiler() {
return mCompiler;
}
/**
* The retrieves the runtime context. The default behavior is to delegate
* this call to the compiler. This is overriden to implement compiled
* templates.
*/
public Class<?> getRuntimeContext() {
return mCompiler.getRuntimeContext();
}
/**
* Called when there is an error when compiling this CompilationUnit.
*/
public void compileError(ErrorEvent e) {
mErrorCount++;
}
/**
* Returns the number of errors generated while compiling this
* CompilationUnit.
*/
public int getErrorCount() {
return mErrorCount;
}
public Template getParseTree() {
if (mTree == null && mCompiler != null) {
return mCompiler.getParseTree(this);
}
return mTree;
}
public void setParseTree(Template tree) {
mTree = tree;
}
/**
* Current implementation returns only the same packages as the compiler.
*
* @see Compiler#getImportedPackages()
*/
public final String[] getImportedPackages() {
return mCompiler.getImportedPackages();
}
/**
* Return the package name that this CompilationUnit should be compiled
* into. Default implementation returns null, or no package.
*/
public String getTargetPackage() {
return mCompiler.getRootPackage();
}
public Reader getReader() throws IOException {
Reader reader = null;
InputStream in = getTemplateSource();
String encoding = mCompiler.getEncoding();
if (encoding == null) {
reader = new InputStreamReader(in);
}
else {
reader = new InputStreamReader(in, encoding);
}
return reader;
}
public void syncTimes() {
if (mDestFile != null) {
mDestFile.setLastModified(getLastModified());
}
}
public boolean shouldCompile() {
- return shouldCompile(getDestinationLastModified());
+ return getCompiler().isForceCompile() ||
+ shouldCompile(getDestinationLastModified());
}
protected boolean shouldCompile(long timestamp) {
if (mDestFile != null && !mDestFile.exists()) {
return true;
}
long precompiledTolerance = mCompiler.getPrecompiledTolerance();
long lastModified = getLastModified();
if (timestamp > 0 && lastModified > 0 &&
gteq(timestamp, lastModified, precompiledTolerance)) {
return false;
}
return true;
}
public long getLastModified() {
return mSource == null ? -1 : mSource.getLastModified();
}
protected long getDestinationLastModified() {
if (mDestFile != null && mDestFile.exists()) {
return mDestFile.lastModified();
}
return 0L;
}
/**
* Returns the truth that a is greater than or equal to b assuming the given tolerance.
* <p>
* ex. tolerance = 10, a = 1000 and b = 2000, returns false<br/>
* ex. tolerance = 10, a = 1989 and b = 2000, returns false<br/>
* ex. tolerance = 10, a = 1990 and b = 2000, returns true<br/>
* ex. tolerance = 10, a = 2000 and b = 2000, returns true<br/>
* ex. tolerance = 10, a = 3000 and b = 2000, returns true<br/>
* </p>
*
* @param a
* @param b
* @param tolerance
* @return
*/
private boolean gteq(long a, long b, long tolerance) {
return a >= b - tolerance;
}
/**
* @return the file that gets written by the compiler.
*/
public File getDestinationFile() {
return mDestFile;
}
public OutputStream getOutputStream() throws IOException {
OutputStream out1 = null;
OutputStream out2 = null;
if (mDestDir != null) {
if (!mDestDir.exists()) {
mDestDir.mkdirs();
}
out1 = new FileOutputStream(mDestFile);
}
ClassInjector injector = mCompiler.getInjector();
if (injector != null) {
String className = getName();
String pack = getTargetPackage();
if (pack != null && pack.length() > 0) {
className = pack + '.' + className;
}
out2 = injector.getStream(className);
}
OutputStream out;
if (out1 != null) {
if (out2 != null) {
out = new DualOutput(out1, out2);
}
else {
out = out1;
}
}
else if (out2 != null) {
out = out2;
}
else {
out = new OutputStream() {
public void write(int b) {}
public void write(byte[] b, int off, int len) {}
};
}
return new BufferedOutputStream(out);
}
public void resetOutputStream() {
if (mDestFile != null) {
mDestFile.delete();
}
ClassInjector injector = mCompiler.getInjector();
if (injector != null) {
injector.resetStream(getClassName());
}
}
protected String getClassName() {
return getClassName(null);
}
protected String getClassName(String innerClass) {
String className = getName();
String pack = getTargetPackage();
if (pack != null && pack.length() > 0) {
className = pack + '.' + className;
}
if (innerClass != null) {
className = className + '$' + innerClass;
}
return className;
}
protected InputStream getTemplateSource()
throws IOException {
if (mSource == null) {
throw new IOException("no source defined for " + mName);
}
return mSource.getSource();
}
public boolean signatureEquals(String templateName, TypeDesc[] params, TypeDesc returnType) throws IOException {
if(!getName().equals(templateName)) {
return false;
}
Reader r = new BufferedReader(getReader());
SourceReader srcReader = new SourceReader(r, "<%", "%>");
Template tree = null;
try {
Scanner s = new Scanner(srcReader, this);
s.addErrorListener(this);
Parser p = new Parser(s, this);
p.addErrorListener(this);
tree = p.parse();
s.close();
} finally {
r.close();
}
// fill sourceParams
Variable[] vars = tree.getParams();
TypeDesc[] sourceParams = new TypeDesc[vars.length];
for (int i = 0; i < vars.length; i++) {
String type = classNameFromVariable(
vars[i].getTypeName().getName(), vars[i].getTypeName().getDimensions());
sourceParams[i] = TypeDesc.forClass(type);
}
// strip off merged class since it may be different for remote compiler
TypeDesc[] temp = new TypeDesc[params.length-1];
System.arraycopy(params, 1, temp, 0, temp.length);
// compare params
if(! Arrays.equals(temp, sourceParams)) {
return false;
}
// compare return types (null is default from Template.getReturnType())
if(null!=tree.getReturnType()) {
TypeDesc srcReturnType = TypeDesc.forClass(tree.getReturnType().getSimpleName());
if(! returnType.equals(srcReturnType) ) {
return false;
}
}
return true;
}
private String classNameFromVariable(String type, int dimensions) {
if("short".equals(type)
|| "long".equals(type)
|| "double".equals(type)) {
type = type.substring(0, 1).toUpperCase()+ type.substring(1);
}
if("int".equals(type)) {
type = "Integer";
}
if("Short".equals(type)
|| "Integer".equals(type)
|| "Long".equals(type)
|| "Double".equals(type)
|| "String".equals(type)) {
type = "java.lang."+type;
}
for (int j = 0; j < dimensions; j++) {
type = type + "[]";
}
return type;
}
}
diff --git a/tea/src/main/java/org/teatrove/tea/compiler/Compiler.java b/tea/src/main/java/org/teatrove/tea/compiler/Compiler.java
index a1bc834..60d8aa0 100644
--- a/tea/src/main/java/org/teatrove/tea/compiler/Compiler.java
+++ b/tea/src/main/java/org/teatrove/tea/compiler/Compiler.java
@@ -1,984 +1,994 @@
/*
* Copyright 1997-2011 teatrove.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.teatrove.tea.compiler;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Reader;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import org.teatrove.tea.parsetree.Template;
import org.teatrove.trove.io.SourceReader;
import org.teatrove.trove.util.ClassInjector;
/**
* The Tea compiler. This class is abstract, and a few concrete
* implementations can be found in the org.teatrove.tea.util package.
*
* <p>A Compiler instance should be used for only one "build" because
* some information is cached internally like parse trees and error count.
*
* @author Brian S O'Neill
* @see org.teatrove.tea.util.FileCompilationProvider
* @see org.teatrove.tea.util.ResourceCompilationProvider
*/
public class Compiler {
protected static final String TEMPLATE_PKG = "org.teatrove.tea.templates";
// Maps qualified names to CompilationProviders
private Map<String, CompilationProvider> mTemplateProviderMap;
// Maps qualified names to ParseTrees.
private final Map<String, Template> mParseTreeMap;
// Maps qualified names to CompilationUnits.
private final Map<String, CompilationUnit> mCompilationUnitMap =
new HashMap<String, CompilationUnit>();
// Set of names for CompilationUnits that have already been compiled.
private final Set<String> mCompiled = new HashSet<String>();
// List of compilation providers
private final List<CompilationProvider> mCompilationProviders =
new ArrayList<CompilationProvider>();
protected boolean mForce;
private Set<String> mPreserveTree;
private Class<?> mContextClass =
org.teatrove.tea.runtime.Context.class;
private Method[] mRuntimeMethods;
private Method[] mStringConverters;
private ErrorListener mErrorListener;
private Vector<ErrorListener> mErrorListeners =
new Vector<ErrorListener>(4);
private int mErrorCount = 0;
private Vector<StatusListener> mStatusListeners =
new Vector<StatusListener>();
protected String mRootPackage;
protected File mRootDestDir;
protected ClassInjector mInjector;
protected String mEncoding;
protected long mPrecompiledTolerance;
private boolean mGenerateCode = true;
private boolean mExceptionGuardian = false;
private ClassLoader mClassLoader;
private MessageFormatter mFormatter;
private Set<String> mImports = new HashSet<String>();
{ mImports.add("java.lang"); mImports.add("java.util"); }
public Compiler() {
this(ClassInjector.getInstance());
}
public Compiler(ClassInjector injector) {
this(injector, TEMPLATE_PKG);
}
public Compiler(String rootPackage) {
this(ClassInjector.getInstance(), rootPackage);
}
public Compiler(ClassInjector injector, String rootPackage) {
this(ClassInjector.getInstance(), rootPackage, null);
}
public Compiler(String rootPackage, File rootDestDir) {
this(ClassInjector.getInstance(), rootPackage, rootDestDir);
}
public Compiler(ClassInjector injector,
String rootPackage, File rootDestDir) {
this(injector, rootPackage, rootDestDir, "UTF-8", 0);
}
public Compiler(String rootPackage, File rootDestDir, String encoding,
long precompiledTolerance) {
this(ClassInjector.getInstance(), rootPackage, rootDestDir,
encoding, precompiledTolerance);
}
public Compiler(ClassInjector injector, String rootPackage,
File rootDestDir, String encoding,
long precompiledTolerance) {
this(injector, rootPackage, rootDestDir, encoding, precompiledTolerance,
Collections.synchronizedMap(new HashMap<String, Template>()));
}
/**
* This constructor allows template signatures to be shared among compiler
* instances. This is useful in interactive environments, where compilation
* is occurring on a regular basis, but most called templates are not
* being modified. The Compiler will map qualified template names to
* ParseTree objects that have their code removed. Removing a template
* entry from the map will force the compiler to re-parse the template if
* it is called. Any template passed into the compile method will always be
* re-parsed, even if its parse tree is already present in the map.
*
* @param rootDestDir The optional directory to write class-files to
* @param rootPackage The root package to store generate classes to
* @param parseTreeMap map should be thread-safe
*/
public Compiler(ClassInjector injector, String rootPackage,
File rootDestDir, String encoding,
long precompiledTolerance,
Map<String, Template> parseTreeMap) {
mInjector = injector;
mRootPackage = rootPackage;
mRootDestDir = rootDestDir;
mEncoding = encoding;
mParseTreeMap = parseTreeMap;
mPrecompiledTolerance = precompiledTolerance;
mErrorListener = new ErrorListener() {
public void compileError(ErrorEvent e) {
dispatchCompileError(e);
}
};
mFormatter = MessageFormatter.lookup(this);
if (!TemplateRepository.isInitialized()) {
TemplateRepository.init(rootDestDir, rootPackage);
}
}
/**
* Get the root destination directory where class files should be written
* to. If no root destination directory is provided, <code>null</code> will
* be returned.
*
* @return The root destination directory or <code>null</code>
*/
public File getRootDestDir() {
return mRootDestDir;
}
/**
* Get the root package that all templates should be packaged under.
*
* @return The root package of templates
*/
public String getRootPackage() {
return mRootPackage;
}
/**
* Get the class injector to write classes to in order to generate and load
* class structures.
*
* @return The class injector
*/
public ClassInjector getInjector() {
return mInjector;
}
/**
* Get the encoding of the source files to use.
*
* @return The encoding of the source files to use
*/
public String getEncoding() {
return mEncoding;
}
/**
* Get the precompiled tolerance to use in detecting last modifications.
*
* @return The precompiled tolerance in milliseconds
*/
public long getPrecompiledTolerance() {
return mPrecompiledTolerance;
}
/**
* Add the specified compilation provider as a supported provider for
* finding and compiling templates.
*
* @param provider The compilation provider to add
*/
public void addCompilationProvider(CompilationProvider provider) {
this.mTemplateProviderMap = null;
this.mCompilationProviders.add(provider);
}
/**
* Add the specified compilation providers as supported providers for
* finding and compiling templates.
*
* @param provider The compilation providers to add
*/
public void addCompilationProviders(Collection<CompilationProvider> providers) {
this.mTemplateProviderMap = null;
this.mCompilationProviders.addAll(providers);
}
/**
* Add an ErrorListener in order receive events of compile-time errors.
* @see org.teatrove.tea.util.ConsoleErrorReporter
*/
public void addErrorListener(ErrorListener listener) {
mErrorListeners.addElement(listener);
}
public void removeErrorListener(ErrorListener listener) {
mErrorListeners.removeElement(listener);
}
private void dispatchCompileError(ErrorEvent e) {
mErrorCount++;
synchronized (mErrorListeners) {
for (int i = 0; i < mErrorListeners.size(); i++) {
mErrorListeners.elementAt(i).compileError(e);
}
}
}
/**
* Add a StatusListener in order to receive events of compilation progress.
*/
public void addStatusListener(StatusListener listener) {
mStatusListeners.addElement(listener);
}
public void removeStatusListener(StatusListener listener) {
mStatusListeners.removeElement(listener);
}
private void dispatchCompileStatus(StatusEvent e) {
synchronized (mStatusListeners) {
for(int i = 0; i < mStatusListeners.size(); i++) {
mStatusListeners.elementAt(i).statusUpdate(e);
}
}
}
private void uncaughtException(Throwable e) {
Thread t = Thread.currentThread();
t.getThreadGroup().uncaughtException(t, e);
}
/**
* By default, code generation is enabled. Passing false disables the
* code generation phase of the compiler.
*/
public void setCodeGenerationEnabled(boolean flag) {
mGenerateCode = flag;
}
/**
* Returns true if code generation is enabled. The default setting is true.
*/
public boolean isCodeGenerationEnabled() {
return mGenerateCode;
}
public void setExceptionGuardianEnabled(boolean flag) {
mExceptionGuardian = flag;
}
/**
* Returns true if the exception guardian is enabled. The default setting
* is false.
*/
public boolean isExceptionGuardianEnabled() {
return mExceptionGuardian;
}
/**
* Sets the ClassLoader to use to load classes with. If set to null,
* then classes are loaded using Class.forName.
*/
public void setClassLoader(ClassLoader loader) {
mClassLoader = loader;
}
/**
* Returns the ClassLoader used by the Compiler, or null if none set.
*/
public ClassLoader getClassLoader() {
return mClassLoader;
}
/**
* Loads and returns a class by the fully qualified name given. If a
* ClassLoader is specified, it is used to load the class. Otherwise,
* the class is loaded via Class.forName.
*
* @see #setClassLoader(ClassLoader)
*/
public Class<?> loadClass(String name) throws ClassNotFoundException {
while (true) {
try {
if (mClassLoader == null) {
return Class.forName(name);
} else {
return mClassLoader.loadClass(name);
}
} catch (ClassNotFoundException e) {
int index = name.lastIndexOf('.');
if (index < 0) {
throw e;
}
// Search for inner class.
name = name.substring(0, index) + '$' +
name.substring(index + 1);
}
}
}
/**
* After a template is compiled, all but the root node of its parse tree
* is clipped, in order to save memory. Applications that wish to traverse
* CompilationUnit parse trees should call this method to preserve them.
* This method must be called prior to compilation and prior to requesting
* a parse tree from a CompilationUnit.
*
* @param name fully qualified name of template whose parse tree is to be
* preserved.
*/
public void preserveParseTree(String name) {
if (mPreserveTree == null) {
mPreserveTree = new HashSet<String>();
}
mPreserveTree.add(name);
}
/**
+ * Get the flag of whether to force all templates to be compiled even if
+ * up-to-date.
+ *
+ * @return true to compile all source, even if up-to-date
+ */
+ public boolean isForceCompile() {
+ return mForce;
+ }
+
+ /**
* Set the flag of whether to force all templates to be compiled even if
* up-to-date.
*
* @param force When true, compile all source, even if up-to-date
*/
public void setForceCompile(boolean force) {
mForce = force;
}
protected void loadTemplates() {
if (mTemplateProviderMap == null) {
try { getAllTemplateNames(true); }
catch (IOException ioe) {
mTemplateProviderMap = new HashMap<String, CompilationProvider>();
}
}
}
/**
* Get the list of all known templates to this compiler. If the list of
* known templates cannot be easily resolved, then <code>null</code> should
* be returned.
*
* @return The list of all known templates.
*/
public String[] getAllTemplateNames() throws IOException {
return getAllTemplateNames(true);
}
/**
* Get the list of all known templates to this compiler. If the list of
* known templates cannot be easily resolved, then <code>null</code> should
* be returned.
*
* @param recurse The flag of whether to recurse into sub-directories
*
* @return The list of all known templates.
*/
public String[] getAllTemplateNames(boolean recurse)
throws IOException {
if (mTemplateProviderMap == null) {
synchronized (this) {
mTemplateProviderMap = new HashMap<String, CompilationProvider>();
for (CompilationProvider provider : mCompilationProviders) {
String[] templates = provider.getKnownTemplateNames(recurse);
for (String template : templates) {
if (!mTemplateProviderMap.containsKey(template)) {
mTemplateProviderMap.put(template, provider);
}
}
}
}
}
return mTemplateProviderMap.keySet().toArray(
new String[mTemplateProviderMap.size()]);
}
/**
* Recursively compiles all files in the source directory.
*
* @return The names of all the compiled sources
*/
public String[] compileAll() throws IOException {
return compileAll(true);
}
/**
* Compiles all files in the source directory recursively or not.
*
* @param recurse The flag of whether to recurse all sub-directories
*
* @return The names of all the compiled sources
*/
public String[] compileAll(boolean recurse) throws IOException {
return compile(getAllTemplateNames(recurse));
}
/**
* Compile a single compilation unit. This method can be called multiple
* times, but it will not compile compilation units that have already been
* compiled.
*
* @param name the fully qualified template name
*
* @return The names of all the sources compiled by this compiler
* @exception IOException
*/
public String[] compile(String name) throws IOException {
return compile(new String[] {name});
}
/**
* Compile a list of compilation units. This method can be called multiple
* times, but it will not compile compilation units that have already been
* compiled.
*
* @param names an array of fully qualified template names
*
* @return The names of all the sources compiled by this compiler
* @exception IOException
*/
public String[] compile(String[] names) throws IOException {
if (!TemplateRepository.isInitialized()) {
return compile0(names);
}
String[] compNames = compile0(names);
ArrayList<String> compList =
new ArrayList<String>(Arrays.asList(compNames));
TemplateRepository rep = TemplateRepository.getInstance();
String[] callers = rep.getCallersNeedingRecompile(compNames, this);
if (callers.length > 0)
compList.addAll(Arrays.asList(compile0(callers)));
String[] compiled = compList.toArray(new String[compList.size()]);
// JoshY - There's a VM bug in JVM 1.4.2 that can cause the repository
// update to throw a NullPointerException when it shouldn't. There's a
// workaround in place and we also put a catch here, to allow the
// TeaServlet init to finish just in case
try { rep.update(compiled); } catch (Exception e) {
System.err.println("Unable to update repository");
e.printStackTrace(System.err);
}
return compiled;
}
protected String[] compile0(String[] names) throws IOException {
synchronized (mParseTreeMap) {
for (int i=0; i<names.length; i++) {
if(Thread.interrupted()) {
break;
}
dispatchCompileStatus(new StatusEvent(this, i, names.length,
names[i]));
CompilationUnit unit = getCompilationUnit(names[i], null);
if (unit == null) {
String msg = mFormatter.format("not.found", names[i]);
dispatchCompileError
(new ErrorEvent(this, msg, (SourceInfo)null, null));
} else if (!mCompiled.contains(names[i]) &&
unit.shouldCompile()) {
mParseTreeMap.remove(names[i]);
getParseTree(unit);
}
}
}
names = new String[mCompiled.size()];
Iterator<String> it = mCompiled.iterator();
int i = 0;
while (it.hasNext()) {
names[i++] = it.next();
}
return names;
}
public int getErrorCount() {
return mErrorCount;
}
/**
* Returns a compilation unit associated with the given name, or null if
* not found.
*
* @param name the requested name
*/
public CompilationUnit getCompilationUnit(String name) {
return getCompilationUnit(name, null);
}
/**
* Returns a compilation unit associated with the given name, or null if
* not found.
*
* @param name the requested name
* @param from optional CompilationUnit is passed because requested name
* should be found relative to it.
*/
public CompilationUnit getCompilationUnit(String name,
CompilationUnit from) {
String fqName = determineQualifiedName(name, from);
// Templates with source will always override compiled templates
boolean compiled = false;
if (fqName == null && (compiled = CompiledTemplate.exists(this, name, from))) {
fqName = CompiledTemplate.getFullyQualifiedName(name);
}
if (fqName == null)
return null;
CompilationUnit unit = mCompilationUnitMap.get(fqName);
if (unit == null) {
if (!compiled) {
unit = createCompilationUnit(fqName);
if (unit != null)
mCompilationUnitMap.put(fqName, unit);
} else {
unit = new CompiledTemplate(name, this, from);
// if the CompiledTemplate class was precompiled (is valid) return the unit, otherwise return null to signify 'not found'
if( ((CompiledTemplate)unit).isValid() ) {
mCompilationUnitMap.put(fqName, unit);
} else {
// TODO: flag the template class for removal
unit = null;
}
}
}
return unit;
}
/**
* Returns the list of imported packages that all templates have. Template
* parameters can abbreviate the names of all classes in these packages.
*/
public String[] getImportedPackages() {
return mImports.toArray(new String[mImports.size()]);
}
/**
* Add an imported package that all templates will have.
*
* @param imported The fully-qualified package name
*/
public void addImportedPackage(String imported) {
this.mImports.add(imported);
}
/**
* Add all imported packages that all templates will have.
*
* @param imports The fully-qualified package name
*/
public void addImportedPackages(String[] imports) {
if (imports == null) { return; }
for (String imported : imports) {
this.mImports.add(imported);
}
}
/**
* Return a class that defines a template's runtime context. The runtime
* context contains methods that are callable by templates. A template
* is compiled such that the first parameter of its execute method must
* be an instance of the runtime context.
*
* <p>Default implementation returns org.teatrove.tea.runtime.Context.</p>
*
* @see org.teatrove.tea.runtime.Context
*/
public Class<?> getRuntimeContext() {
return mContextClass;
}
/**
* Call to override the default runtime context class that a template is
* compiled to use.
*
* @see org.teatrove.tea.runtime.Context
*/
public void setRuntimeContext(Class<?> contextClass) {
mContextClass = contextClass;
mRuntimeMethods = null;
mStringConverters = null;
}
/**
* Returns all the methods available in the runtime context.
*/
public final Method[] getRuntimeContextMethods() {
if (mRuntimeMethods == null) {
mRuntimeMethods = getRuntimeContext().getMethods();
}
return mRuntimeMethods.clone();
}
/**
* Return the name of a method in the runtime context to bind to for
* receiving objects emitted by templates. The compiler will bind to the
* closest matching public method based on the type of its single
* parameter.
*
* <p>Default implementation returns "print".
*/
public String getRuntimeReceiver() {
return "print";
}
/**
* Return the name of a method in the runtime context to bind to for
* converting objects and primitives to strings. The compiler will bind to
* the closest matching public method based on the type of its single
* parameter.
*
* <p>Default implementation returns "toString". Returning null indicates
* that a static String.valueOf method should be invoked.
*/
public String getRuntimeStringConverter() {
return "toString";
}
/**
* Returns the set of methods that are used to perform conversion to
* strings. The compiler will bind to the closest matching method based
* on its parameter type.
*/
public final Method[] getStringConverterMethods() {
if (mStringConverters == null) {
String name = getRuntimeStringConverter();
Vector<Method> methods = new Vector<Method>();
if (name != null) {
Method[] contextMethods = getRuntimeContextMethods();
for (int i=0; i<contextMethods.length; i++) {
Method m = contextMethods[i];
if (m.getName().equals(name) &&
m.getReturnType() == String.class &&
m.getParameterTypes().length == 1) {
methods.addElement(m);
}
}
}
int customSize = methods.size();
Method[] stringMethods = String.class.getMethods();
for (int i=0; i<stringMethods.length; i++) {
Method m = stringMethods[i];
if (m.getName().equals("valueOf") &&
m.getReturnType() == String.class &&
m.getParameterTypes().length == 1 &&
Modifier.isStatic(m.getModifiers())) {
// Don't add to list if a custom converter already handles
// this method's parameter type.
Class<?> type = m.getParameterTypes()[0];
int j;
for (j=0; j<customSize; j++) {
Method cm = methods.elementAt(j);
if (cm.getParameterTypes()[0] == type) {
break;
}
}
if (j == customSize) {
methods.addElement(m);
}
}
}
mStringConverters = new Method[methods.size()];
methods.copyInto(mStringConverters);
}
return mStringConverters.clone();
}
/**
* Given a name, as requested by the given CompilationUnit, return a
* fully qualified name or null if the name could not be found.
*
* @param name requested name
* @param from optional CompilationUnit
*/
private String determineQualifiedName(String name, CompilationUnit from) {
if (from != null) {
// Determine qualified name as being relative to "from"
String fromName = from.getName();
int index = fromName.lastIndexOf('.');
if (index >= 0) {
String qual = fromName.substring(0, index + 1) + name;
if (sourceExists(qual)) {
return qual;
}
}
}
if (sourceExists(name)) {
return name;
}
return null;
}
/**
* @return true if source exists for the given qualified name
*/
public boolean sourceExists(String name) {
loadTemplates();
// check if already known template and delegate to provider
CompilationProvider provider = mTemplateProviderMap.get(name);
if (provider != null) {
return provider.sourceExists(name);
}
// search for a suitable provider and delegate
for (CompilationProvider provider2 : mCompilationProviders) {
if (provider2.sourceExists(name)) {
mTemplateProviderMap.put(name, provider2);
return true;
}
}
// none found
return false;
}
protected CompilationUnit createCompilationUnit(String name) {
loadTemplates();
// check if source exists and delegate to provider
if (sourceExists(name)) {
CompilationProvider provider = mTemplateProviderMap.get(name);
if (provider != null) {
CompilationSource source = provider.createCompilationSource(name);
return (source == null ? null :
new CompilationUnit(name, source, this));
}
}
// none found
return null;
}
/**
* Default implementation returns a SourceReader that uses "<%" and "%>"
* as code delimiters.
*/
protected SourceReader createSourceReader(CompilationUnit unit)
throws IOException {
Reader r = new BufferedReader(unit.getReader());
return new SourceReader(r, "<%", "%>");
}
protected Scanner createScanner(SourceReader reader, CompilationUnit unit)
throws IOException {
return new Scanner(reader, unit);
}
protected Parser createParser(Scanner scanner, CompilationUnit unit)
throws IOException {
return new Parser(scanner, unit);
}
protected TypeChecker createTypeChecker(CompilationUnit unit) {
TypeChecker tc = new TypeChecker(unit);
tc.setClassLoader(getClassLoader());
tc.setExceptionGuardianEnabled(isExceptionGuardianEnabled());
return tc;
}
/**
* Default implementation returns a new JavaClassGenerator.
*
* @see JavaClassGenerator
*/
protected CodeGenerator createCodeGenerator(CompilationUnit unit)
throws IOException {
return new JavaClassGenerator(unit);
}
/**
* Called by the Compiler or by a CompilationUnit when its parse tree is
* requested. Requesting a parse tree may cause template code to be
* generated.
*/
public Template getParseTree(CompilationUnit unit) {
synchronized (mParseTreeMap) {
return getParseTree0(unit);
}
}
private Template getParseTree0(CompilationUnit unit) {
String name = unit.getName();
Template tree = mParseTreeMap.get(name);
if (tree != null) {
return tree;
}
try {
// Parse and type check the parse tree.
// Direct all compile errors into the CompilationUnit.
// Remove the unit as an ErrorListener in the finally block
// at the end of this method.
addErrorListener(unit);
try {
Scanner s = createScanner(createSourceReader(unit), unit);
s.addErrorListener(mErrorListener);
Parser p = createParser(s, unit);
p.addErrorListener(mErrorListener);
tree = p.parse();
mParseTreeMap.put(name, tree);
s.close();
} catch (IOException e) {
uncaughtException(e);
String msg = mFormatter.format("read.error", e.toString());
dispatchCompileError
(new ErrorEvent(this, msg, (SourceInfo)null, unit));
return tree;
}
TypeChecker tc = createTypeChecker(unit);
tc.setClassLoader(getClassLoader());
tc.addErrorListener(mErrorListener);
tc.typeCheck();
if (mCompiled.contains(name) || !unit.shouldCompile()) {
return tree;
} else {
mCompiled.add(name);
}
// Code generate the CompilationUnit only if no errors and
// the code generate option is enabled.
if (unit.getErrorCount() == 0 && mGenerateCode) {
OutputStream out = null;
try {
out = unit.getOutputStream();
if (out != null) {
tree = (Template)new BasicOptimizer(tree).optimize();
mParseTreeMap.put(name, tree);
CodeGenerator codegen = createCodeGenerator(unit);
codegen.writeTo(out);
out.flush();
out.close();
// sync times so class file matches last modified of
// source file to ensure times are in sync
unit.syncTimes();
}
} catch (Throwable e) {
// attempt to close stream
// NOTE: we must call this here as well as in the try block
// above rather than solely in a finally block since
// the unit.resetOutputStream expects the stream to
// already be closed. For example, if the unit uses
// ClassInjector.getStream, then close must be called
// on that stream to ensure it is defined so that
// the reset method can undefine it.
if (out != null) {
try { out.close(); }
catch (Throwable err) { uncaughtException(err); }
}
// reset the output stream
unit.resetOutputStream();
// output error
uncaughtException(e);
String msg = mFormatter.format
("write.error", e.toString());
dispatchCompileError
(new ErrorEvent(this, msg, (SourceInfo)null, unit));
return tree;
}
}
} catch (Throwable e) {
uncaughtException(e);
String msg = mFormatter.format("internal.error", e.toString());
dispatchCompileError
(new ErrorEvent(this, msg, (SourceInfo)null, unit));
} finally {
removeErrorListener(unit);
// Conserve memory by removing the bulk of the parse tree after
// compilation. This preserves the signature for templates that
// may need to call this one.
if (tree != null &&
(mPreserveTree == null || !mPreserveTree.contains(name))) {
tree.setStatement(null);
}
}
return tree;
}
}
| false | false | null | null |
diff --git a/de.jutzig.jabylon.rest.ui/src/main/java/de/jutzig/jabylon/rest/ui/wicket/config/sections/ProjectVersionsConfigSection.java b/de.jutzig.jabylon.rest.ui/src/main/java/de/jutzig/jabylon/rest/ui/wicket/config/sections/ProjectVersionsConfigSection.java
index 5c9b07be..aacba32c 100644
--- a/de.jutzig.jabylon.rest.ui/src/main/java/de/jutzig/jabylon/rest/ui/wicket/config/sections/ProjectVersionsConfigSection.java
+++ b/de.jutzig.jabylon.rest.ui/src/main/java/de/jutzig/jabylon/rest/ui/wicket/config/sections/ProjectVersionsConfigSection.java
@@ -1,330 +1,346 @@
package de.jutzig.jabylon.rest.ui.wicket.config.sections;
import java.io.File;
import java.text.MessageFormat;
import java.util.Collection;
import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.extensions.ajax.markup.html.IndicatingAjaxButton;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.html.link.ExternalLink;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.GenericPanel;
import org.apache.wicket.model.AbstractReadOnlyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.emf.cdo.CDOState;
import org.eclipse.emf.cdo.transaction.CDOTransaction;
import org.eclipse.emf.cdo.util.CommitException;
import org.osgi.service.prefs.Preferences;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import de.jutzig.jabylon.common.progress.RunnableWithProgress;
import de.jutzig.jabylon.common.team.TeamProvider;
import de.jutzig.jabylon.common.team.TeamProviderException;
import de.jutzig.jabylon.common.team.TeamProviderUtil;
import de.jutzig.jabylon.common.util.FileUtil;
import de.jutzig.jabylon.common.util.PreferencesUtil;
import de.jutzig.jabylon.properties.Project;
import de.jutzig.jabylon.properties.ProjectVersion;
import de.jutzig.jabylon.properties.PropertiesPackage;
import de.jutzig.jabylon.properties.PropertyFileDiff;
import de.jutzig.jabylon.properties.ScanConfiguration;
import de.jutzig.jabylon.rest.ui.Activator;
import de.jutzig.jabylon.rest.ui.model.ComplexEObjectListDataProvider;
import de.jutzig.jabylon.rest.ui.model.ProgressionModel;
import de.jutzig.jabylon.rest.ui.util.WicketUtil;
import de.jutzig.jabylon.rest.ui.wicket.components.ProgressPanel;
import de.jutzig.jabylon.rest.ui.wicket.components.ProgressShowingAjaxButton;
import de.jutzig.jabylon.rest.ui.wicket.config.AbstractConfigSection;
import de.jutzig.jabylon.rest.ui.wicket.config.SettingsPage;
public class ProjectVersionsConfigSection extends GenericPanel<Project> {
private static final long serialVersionUID = 1L;
+ private static final Logger logger = LoggerFactory.getLogger(ProjectVersionsConfigSection.class);
public ProjectVersionsConfigSection(String id, IModel<Project> model, Preferences config) {
super(id, model);
add(buildAddNewLink(model));
ComplexEObjectListDataProvider<ProjectVersion> provider = new ComplexEObjectListDataProvider<ProjectVersion>(model,
PropertiesPackage.Literals.RESOLVABLE__CHILDREN);
ListView<ProjectVersion> project = new ListView<ProjectVersion>("versions", provider) {
private static final long serialVersionUID = 1L;
private ProgressionModel progressModel;
@Override
protected void populateItem(ListItem<ProjectVersion> item) {
item.setOutputMarkupId(true);
item.add(new Label("name", item.getModelObject().getName()));
item.add(new Label("summary", createSummaryModel(item.getModel())));
progressModel = new ProgressionModel(-1);
final ProgressPanel progressPanel = new ProgressPanel("progress", progressModel);
item.add(progressPanel);
ProjectVersion projectVersion = item.getModelObject();
item.add(new ExternalLink("edit",projectVersion.getParent().getName() + "/" + projectVersion.getName()));
item.add(createCheckoutAction(progressPanel, item.getModel()));
item.add(createRescanAction(progressPanel, item.getModel()));
item.add(createUpdateAction(progressPanel, item.getModel()));
item.add(createCommitAction(progressPanel, item.getModel()));
item.add(createDeleteAction(progressPanel, item.getModel()));
}
};
project.setOutputMarkupId(true);
add(project);
}
private Component buildAddNewLink(IModel<Project> model) {
PageParameters params = new PageParameters();
Project project = model.getObject();
if (project.cdoState() == CDOState.NEW || project.cdoState() == CDOState.TRANSIENT) {
// it's a new project, we can't add anything yet
Button link = new Button("addNew");
link.setEnabled(false);
return link;
}
params.set(0, project.getName());
params.add(SettingsPage.QUERY_PARAM_CREATE, PropertiesPackage.Literals.PROJECT_VERSION.getName());
return new BookmarkablePageLink<Void>("addNew", SettingsPage.class, params);
}
private IModel<String> createSummaryModel(final IModel<ProjectVersion> modelObject) {
return new AbstractReadOnlyModel<String>() {
private static final long serialVersionUID = 1L;
public String getObject() {
int size = modelObject.getObject().getChildren().size();
String message = "Translations available in {0} languages";
return MessageFormat.format(message, size);
};
};
}
protected Component createDeleteAction(ProgressPanel progressPanel, final IModel<ProjectVersion> model) {
Button button = new IndicatingAjaxButton("delete") {
private static final long serialVersionUID = 1L;
@Override
protected void onAfterSubmit(AjaxRequestTarget target, Form<?> form) {
ProjectVersion version = model.getObject();
CDOTransaction transaction = Activator.getDefault().getRepositoryConnector().openTransaction();
version = transaction.getObject(version);
try {
File directory = new File(version.absolutPath().toFileString());
FileUtil.delete(directory);
Project project = version.getParent();
project.getChildren().remove(version);
transaction.commit();
setResponsePage(SettingsPage.class, WicketUtil.buildPageParametersFor(project));
} catch (CommitException e) {
- // TODO Auto-generated catch block
+ logger.error("Commit failed",e);
getSession().error(e.getMessage());
- e.printStackTrace();
} finally {
transaction.close();
}
}
};
// button.add(new AttributeModifier("onclick",
// "return confirm('Are you sure you want to delete this version?');"));
button.setDefaultFormProcessing(false);
return button;
}
protected Component createUpdateAction(ProgressPanel progressPanel, final IModel<ProjectVersion> model) {
RunnableWithProgress runnable = new RunnableWithProgress() {
private static final long serialVersionUID = 1L;
@Override
public IStatus run(IProgressMonitor monitor) {
ProjectVersion version = model.getObject();
TeamProvider provider = TeamProviderUtil.getTeamProvider(version.getParent().getTeamProvider());
CDOTransaction transaction = Activator.getDefault().getRepositoryConnector().openTransaction();
try {
version = transaction.getObject(version);
SubMonitor subMonitor = SubMonitor.convert(monitor, "Updating", 100);
Collection<PropertyFileDiff> updates = provider.update(version, subMonitor.newChild(50));
subMonitor.setWorkRemaining(updates.size() * 2);
subMonitor.subTask("Processing updates");
for (PropertyFileDiff updatedFile : updates) {
version.partialScan(PreferencesUtil.getScanConfigForProject(getModelObject()), updatedFile);
subMonitor.worked(1);
}
subMonitor.setTaskName("Database Sync");
transaction.commit(subMonitor.newChild(updates.size()));
} catch (TeamProviderException e) {
+ logger.error("Update failed",e);
return new Status(IStatus.ERROR, Activator.BUNDLE_ID, "Update failed",e);
} catch (CommitException e) {
+ logger.error("Failed to commit the transaction",e);
return new Status(IStatus.ERROR, Activator.BUNDLE_ID, "Failed to commit the transaction",e);
} finally {
transaction.close();
}
return Status.OK_STATUS;
}
};
return new ProgressShowingAjaxButton("update", progressPanel, runnable) {
private static final long serialVersionUID = 1L;
public boolean isVisible() {
ProjectVersion version = model.getObject();
TeamProvider provider = TeamProviderUtil.getTeamProvider(version.getParent().getTeamProvider());
if (provider == null)
return false;
File file = new File(version.absoluteFilePath().toFileString());
return (file.isDirectory());
};
};
}
protected Component createCommitAction(ProgressPanel progressPanel, final IModel<ProjectVersion> model) {
RunnableWithProgress runnable = new RunnableWithProgress() {
private static final long serialVersionUID = 1L;
@Override
public IStatus run(IProgressMonitor monitor) {
ProjectVersion version = model.getObject();
TeamProvider provider = TeamProviderUtil.getTeamProvider(version.getParent().getTeamProvider());
SubMonitor subMonitor = SubMonitor.convert(monitor, "Committing", 100);
try {
provider.commit(version, subMonitor.newChild(100));
} catch (TeamProviderException e) {
return new Status(IStatus.ERROR, Activator.BUNDLE_ID, "Commit Failed",e);
}
return Status.OK_STATUS;
}
};
return new ProgressShowingAjaxButton("commit", progressPanel, runnable) {
private static final long serialVersionUID = 1L;
public boolean isVisible() {
ProjectVersion version = model.getObject();
TeamProvider provider = TeamProviderUtil.getTeamProvider(version.getParent().getTeamProvider());
if (provider == null)
return false;
File file = new File(version.absoluteFilePath().toFileString());
return (file.isDirectory());
};
};
}
private Component createCheckoutAction(ProgressPanel progressPanel, final IModel<ProjectVersion> model) {
RunnableWithProgress runnable = new RunnableWithProgress() {
private static final long serialVersionUID = 1L;
@Override
public IStatus run(IProgressMonitor monitor) {
- ProjectVersion version = model.getObject();
- TeamProvider provider = TeamProviderUtil.getTeamProvider(version.getParent().getTeamProvider());
+ CDOTransaction transaction = Activator.getDefault().getRepositoryConnector().openTransaction();
try {
+ ProjectVersion version = model.getObject();
+ version = transaction.getObject(version);
+ TeamProvider provider = TeamProviderUtil.getTeamProvider(version.getParent().getTeamProvider());
provider.checkout(version, monitor);
} catch (TeamProviderException e) {
+ logger.error("Checkout failed",e);
return new Status(IStatus.ERROR, Activator.BUNDLE_ID, "Checkout failed",e);
}
+ finally{
+ try {
+ transaction.commit();
+ } catch (CommitException e) {
+ logger.error("Failed to commit the transaction",e);
+ return new Status(IStatus.ERROR, Activator.BUNDLE_ID, "Failed to commit the transaction",e);
+ }
+ transaction.close();
+ }
return Status.OK_STATUS;
}
};
return new ProgressShowingAjaxButton("checkout", progressPanel, runnable) {
private static final long serialVersionUID = 1L;
public boolean isVisible() {
ProjectVersion version = model.getObject();
TeamProvider provider = TeamProviderUtil.getTeamProvider(version.getParent().getTeamProvider());
if (provider == null)
return false;
File file = new File(version.absoluteFilePath().toFileString());
return (!file.isDirectory());
};
};
}
private Component createRescanAction(ProgressPanel progressPanel, final IModel<ProjectVersion> model) {
RunnableWithProgress runnable = new RunnableWithProgress() {
private static final long serialVersionUID = 1L;
@Override
public IStatus run(IProgressMonitor monitor) {
ScanConfiguration scanConfiguration = PreferencesUtil.getScanConfigForProject(getModelObject());
ProjectVersion version = model.getObject();
SubMonitor subMonitor = SubMonitor.convert(monitor, "Scanning", 100);
CDOTransaction transaction = Activator.getDefault().getRepositoryConnector().openTransaction();
version = transaction.getObject(version);
version.fullScan(scanConfiguration, subMonitor.newChild(50));
subMonitor.setTaskName("Database Sync");
try {
transaction.commit(subMonitor.newChild(50));
} catch (CommitException e) {
return new Status(IStatus.ERROR, Activator.BUNDLE_ID, "Transaction commit failed",e);
} finally {
transaction.close();
}
monitor.done();
return Status.OK_STATUS;
}
};
return new ProgressShowingAjaxButton("rescan", progressPanel, runnable) {
private static final long serialVersionUID = 1L;
public boolean isVisible() {
// ProjectVersion version = model.getObject();
// File file = new
// File(version.absoluteFilePath().toFileString());
// return (file.isDirectory());
return true;
};
};
}
public static class VersionsConfig extends AbstractConfigSection<Project> {
private static final long serialVersionUID = 1L;
@Override
public WebMarkupContainer createContents(String id, IModel<Project> input, Preferences prefs) {
return new ProjectVersionsConfigSection(id, input, prefs);
}
@Override
public void commit(IModel<Project> input, Preferences config) {
// TODO Auto-generated method stub
}
@Override
public boolean hasFormComponents() {
return false;
}
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/src/main/java/lamprey/seprphase3/GUI/Screens/GameplayScreen.java b/src/main/java/lamprey/seprphase3/GUI/Screens/GameplayScreen.java
index 61bbdcd..ff116a6 100644
--- a/src/main/java/lamprey/seprphase3/GUI/Screens/GameplayScreen.java
+++ b/src/main/java/lamprey/seprphase3/GUI/Screens/GameplayScreen.java
@@ -1,188 +1,182 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package lamprey.seprphase3.GUI.Screens;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import eel.seprphase2.Simulator.GameManager;
import eel.seprphase2.Simulator.PlantController;
import eel.seprphase2.Simulator.PlantStatus;
import lamprey.seprphase3.GUI.BackyardReactor;
+import lamprey.seprphase3.GUI.GameplayListeners;
import lamprey.seprphase3.GUI.Images.HoverButton;
import lamprey.seprphase3.GUI.Images.MechanicImage;
-import lamprey.seprphase3.GUI.GameplayListeners;
import lamprey.seprphase3.GUI.Images.TurbineImage;
/**
*
* @author Simeon
*/
public class GameplayScreen extends AbstractScreen {
GameplayListeners listeners;
Texture gamebgTexture;
Texture borderTexture;
Texture condenserTexture;
Texture coolerTexture;
Texture pipesTexture;
Texture poweroutTexture;
Texture reactorbackTexture;
Texture pauseTexture;
Texture consolebackTexture;
Texture crUpTexture;
Texture crDownTexture;
Texture pump1Texture;
Texture pump2Texture;
Texture valve1Texture;
Texture valve2Texture;
Texture sErrorTexture;
Image gamebgImage;
Image borderImage;
HoverButton condenserImage;
Image coolerImage;
Image pipesImage;
Image poweroutImage;
HoverButton reactorImage;
TurbineImage turbineImage;
MechanicImage mechanicImage;
HoverButton pauseImage;
Image consolebackImage;
HoverButton crUpImage;
HoverButton crDownImage;
HoverButton pump1Image;
HoverButton pump2Image;
HoverButton valve1Image;
HoverButton valve2Image;
Image sErrorImage;
public GameplayScreen(BackyardReactor game, PlantController controller, PlantStatus status, GameManager manager) {
super(game, controller, status, manager);
listeners = new GameplayListeners(this, controller, status, manager);
gamebgTexture = new Texture(Gdx.files.internal("assets\\game\\bg.png"));
borderTexture = new Texture(Gdx.files.internal("assets\\game\\border.png"));
condenserTexture = new Texture(Gdx.files.internal("assets\\game\\condenser.png"));
coolerTexture = new Texture(Gdx.files.internal("assets\\game\\cooler.png"));
pipesTexture = new Texture(Gdx.files.internal("assets\\game\\pipes.png"));
poweroutTexture = new Texture(Gdx.files.internal("assets\\game\\powerout.png"));
reactorbackTexture = new Texture(Gdx.files.internal("assets\\game\\reactor_back.png"));
- pauseTexture = new Texture(Gdx.files.internal("assets\\game\\pausebutton.png"));
+ pauseTexture = new Texture(Gdx.files.internal("assets\\game\\pause.png"));
consolebackTexture = new Texture(Gdx.files.internal("assets\\game\\consoleback.png"));
crUpTexture = new Texture(Gdx.files.internal("assets\\game\\controlrodup.png"));
crDownTexture = new Texture(Gdx.files.internal("assets\\game\\controlroddown.png"));
pump1Texture = new Texture(Gdx.files.internal("assets\\game\\pump1.png"));
pump2Texture = new Texture(Gdx.files.internal("assets\\game\\pump2.png"));
valve1Texture = new Texture(Gdx.files.internal("assets\\game\\valve1.png"));
valve2Texture = new Texture(Gdx.files.internal("assets\\game\\valve2.png"));
sErrorTexture = new Texture(Gdx.files.internal("assets\\game\\softwareError.png"));
gamebgImage = new Image(gamebgTexture);
borderImage = new Image(borderTexture);
condenserImage = new HoverButton(condenserTexture, false);
coolerImage = new HoverButton(coolerTexture, false);
pipesImage = new Image(pipesTexture);
poweroutImage = new Image(poweroutTexture);
reactorImage = new HoverButton(reactorbackTexture, false);
- turbineImage = new TurbineImage(this.getPlantStatus());
+ turbineImage = new TurbineImage(this.getPlantStatus());
mechanicImage = new MechanicImage();
pauseImage = new HoverButton(pauseTexture, true);
consolebackImage = new Image(consolebackTexture);
crUpImage = new HoverButton(crUpTexture, false);
crDownImage = new HoverButton(crDownTexture, false);
pump1Image = new HoverButton(pump1Texture, false);
pump2Image = new HoverButton(pump2Texture, false);
valve1Image = new HoverButton(valve1Texture, false);
valve2Image = new HoverButton(valve2Texture, false);
sErrorImage = new Image(sErrorTexture);
gamebgImage.setPosition(0, 0);
borderImage.setPosition(0, 0);
- condenserImage.setPosition(522, 110);
- coolerImage.setPosition(804, 122);
- pipesImage.setPosition(131, 149);
+ condenserImage.setPosition(523, 110);
+ coolerImage.setPosition(803, 122);
+ pipesImage.setPosition(132, 149);
poweroutImage.setPosition(703, 405);
- reactorImage.setPosition(32, 113);
+ reactorImage.setPosition(33, 113);
turbineImage.setPosition(435, 405);
mechanicImage.setPosition(630, 75);
mechanicImage.moveMechanicTo(630f); //ensures the mechanic is initially not moving
- pauseImage.setPosition(20, 458);
+ pauseImage.setPosition(17, 15);
consolebackImage.setPosition(260, 0);
crUpImage.setPosition(545, 75);
crDownImage.setPosition(560, 21);
pump1Image.setPosition(323, 71);
pump2Image.setPosition(373, 76);
valve1Image.setPosition(300, 22);
valve2Image.setPosition(353, 22);
sErrorImage.setPosition(433, 18);
-
- //Makes image semi-transparent
- pauseImage.setColor(1f, 1f, 1f, 0.75f);
- //Makes image three times smaller
- pauseImage.setScale(0.33f);
-
condenserImage.addListener(listeners.getCondenserListener());
// coolerImage.addListener(listeners.getCoolerListener());
reactorImage.addListener(listeners.getReactorListener());
pauseImage.addListener(listeners.getPauseListener());
crUpImage.addListener(listeners.getConrolRodsUpListener());
crDownImage.addListener(listeners.getConrolRodsDownListener());
valve1Image.addListener(listeners.getValve1Listener());
valve2Image.addListener(listeners.getValve2Listener());
pump1Image.addListener(listeners.getPump1Listener());
pump2Image.addListener(listeners.getPump2Listener());
}
@Override
public void show() {
super.show();
stage.addActor(gamebgImage);
stage.addActor(borderImage);
stage.addActor(pipesImage);
stage.addActor(coolerImage);
stage.addActor(poweroutImage);
stage.addActor(reactorImage);
stage.addActor(turbineImage);
stage.addActor(condenserImage);
stage.addActor(mechanicImage);
stage.addActor(pauseImage);
stage.addActor(consolebackImage);
stage.addActor(crUpImage);
stage.addActor(crDownImage);
stage.addActor(pump1Image);
stage.addActor(pump2Image);
stage.addActor(valve1Image);
stage.addActor(valve2Image);
stage.addActor(sErrorImage);
}
@Override
public void resize(int width, int height) {
super.resize(width, height);
}
@Override
public void render(float delta) {
super.render(delta);
}
@Override
public void hide() {
stage.clear();
}
public void moveMechanicTo(float destination) {
mechanicImage.moveMechanicTo(destination);
}
public BackyardReactor getGame() {
return this.game;
}
}
| false | false | null | null |
diff --git a/org.eclipse.mylyn.bugzilla.ui/src/org/eclipse/mylyn/internal/bugzilla/ui/TaskAttachmentTableEditorHyperlink.java b/org.eclipse.mylyn.bugzilla.ui/src/org/eclipse/mylyn/internal/bugzilla/ui/TaskAttachmentTableEditorHyperlink.java
index f1cee49d4..385b49886 100644
--- a/org.eclipse.mylyn.bugzilla.ui/src/org/eclipse/mylyn/internal/bugzilla/ui/TaskAttachmentTableEditorHyperlink.java
+++ b/org.eclipse.mylyn.bugzilla.ui/src/org/eclipse/mylyn/internal/bugzilla/ui/TaskAttachmentTableEditorHyperlink.java
@@ -1,140 +1,139 @@
/*******************************************************************************
* Copyright (c) 2010 Frank Becker and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Frank Becker - initial API and implementation
*******************************************************************************/
package org.eclipse.mylyn.internal.bugzilla.ui;
import java.text.MessageFormat;
import org.eclipse.core.runtime.Assert;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.hyperlink.IHyperlink;
import org.eclipse.mylyn.internal.bugzilla.core.IBugzillaConstants;
import org.eclipse.mylyn.tasks.core.TaskRepository;
import org.eclipse.mylyn.tasks.core.data.TaskAttribute;
import org.eclipse.mylyn.tasks.ui.TasksUiUtil;
import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPage;
import org.eclipse.mylyn.tasks.ui.editors.TaskEditor;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.forms.editor.IFormPage;
/**
* @since 3.2
*/
public final class TaskAttachmentTableEditorHyperlink implements IHyperlink {
private final IRegion region;
private final TaskRepository repository;
private final String attachmentId;
public TaskAttachmentTableEditorHyperlink(IRegion region, TaskRepository repository, String attachmentId) {
Assert.isNotNull(repository);
this.region = region;
this.repository = repository;
this.attachmentId = attachmentId;
}
public IRegion getHyperlinkRegion() {
return region;
}
public String getHyperlinkText() {
- return MessageFormat.format(Messages.TaskAttachmentTableEditorHyperlink_Show_Attachment_X_in_Y, attachmentId,
- repository.getRepositoryLabel());
+ return MessageFormat.format(Messages.TaskAttachmentTableEditorHyperlink_Show_Attachment_X_in_Y, attachmentId);
}
public String getTypeLabel() {
return null;
}
public void open() {
AbstractTaskEditorPage page = getTaskEditorPage();
if (page != null) {
if (!page.selectReveal(TaskAttribute.PREFIX_ATTACHMENT + attachmentId)) {
String url = repository.getUrl() + IBugzillaConstants.URL_GET_ATTACHMENT_SUFFIX + attachmentId;
TasksUiUtil.openUrl(url);
}
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((attachmentId == null) ? 0 : attachmentId.hashCode());
result = prime * result + ((region == null) ? 0 : region.hashCode());
result = prime * result + ((repository == null) ? 0 : repository.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
TaskAttachmentTableEditorHyperlink other = (TaskAttachmentTableEditorHyperlink) obj;
if (attachmentId == null) {
if (other.attachmentId != null) {
return false;
}
} else if (!attachmentId.equals(other.attachmentId)) {
return false;
}
if (region == null) {
if (other.region != null) {
return false;
}
} else if (!region.equals(other.region)) {
return false;
}
if (repository == null) {
if (other.repository != null) {
return false;
}
} else if (!repository.equals(other.repository)) {
return false;
}
return true;
}
@Override
public String toString() {
return "TaskAttachmentHyperlink [attachmentId=" + attachmentId + ", region=" + region + ", repository=" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ repository + "]"; //$NON-NLS-1$
}
protected AbstractTaskEditorPage getTaskEditorPage() {
IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
if (activePage == null) {
return null;
}
IEditorPart editorPart = activePage.getActiveEditor();
AbstractTaskEditorPage taskEditorPage = null;
if (editorPart instanceof TaskEditor) {
TaskEditor taskEditor = (TaskEditor) editorPart;
IFormPage formPage = taskEditor.getActivePageInstance();
if (formPage instanceof AbstractTaskEditorPage) {
taskEditorPage = (AbstractTaskEditorPage) formPage;
}
}
return taskEditorPage;
}
}
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/editors/TaskEditorAttachmentPart.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/editors/TaskEditorAttachmentPart.java
index bfd68b70a..dbeb1053b 100644
--- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/editors/TaskEditorAttachmentPart.java
+++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/editors/TaskEditorAttachmentPart.java
@@ -1,367 +1,366 @@
/*******************************************************************************
* Copyright (c) 2004, 2010 Tasktop Technologies and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Tasktop Technologies - initial API and implementation
* Jeff Pound - attachment support
* Frank Becker - improvements for bug 204051
*******************************************************************************/
package org.eclipse.mylyn.internal.tasks.ui.editors;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ColumnViewerToolTipSupport;
import org.eclipse.jface.viewers.IOpenListener;
import org.eclipse.jface.viewers.OpenEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.window.ToolTip;
import org.eclipse.mylyn.internal.provisional.commons.ui.CommonFormUtil;
import org.eclipse.mylyn.internal.provisional.commons.ui.CommonImages;
import org.eclipse.mylyn.internal.provisional.commons.ui.TableSorter;
import org.eclipse.mylyn.internal.provisional.commons.ui.TableViewerSupport;
import org.eclipse.mylyn.internal.tasks.core.TaskAttachment;
import org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin;
import org.eclipse.mylyn.internal.tasks.ui.commands.OpenTaskAttachmentHandler;
import org.eclipse.mylyn.internal.tasks.ui.util.TasksUiMenus;
import org.eclipse.mylyn.internal.tasks.ui.views.TaskKeyComparator;
import org.eclipse.mylyn.internal.tasks.ui.wizards.TaskAttachmentWizard.Mode;
import org.eclipse.mylyn.tasks.core.ITaskAttachment;
import org.eclipse.mylyn.tasks.core.data.TaskAttribute;
import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPart;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.forms.IManagedForm;
import org.eclipse.ui.forms.events.ExpansionAdapter;
import org.eclipse.ui.forms.events.ExpansionEvent;
import org.eclipse.ui.forms.widgets.ExpandableComposite;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ScrolledForm;
import org.eclipse.ui.forms.widgets.Section;
/**
* @author Mik Kersten
* @author Rob Elves
* @author Steffen Pingel
*/
public class TaskEditorAttachmentPart extends AbstractTaskEditorPart {
private class AttachmentTableSorter extends TableSorter {
TaskKeyComparator keyComparator = new TaskKeyComparator();
@Override
public int compare(TableViewer viewer, Object e1, Object e2, int columnIndex) {
ITaskAttachment attachment1 = (ITaskAttachment) e1;
ITaskAttachment attachment2 = (ITaskAttachment) e2;
switch (columnIndex) {
case 0:
return compare(attachment1.getFileName(), attachment2.getFileName());
case 1:
String description1 = attachment1.getDescription();
String description2 = attachment2.getDescription();
return compare(description1, description2);
case 2:
return compare(attachment1.getLength(), attachment2.getLength());
case 3:
return compare(attachment1.getAuthor().toString(), attachment2.getAuthor().toString());
case 4:
return compare(attachment1.getCreationDate(), attachment2.getCreationDate());
case 5:
String key1 = AttachmentTableLabelProvider.getAttachmentId(attachment1);
String key2 = AttachmentTableLabelProvider.getAttachmentId(attachment2);
return keyComparator.compare2(key1, key2);
}
return super.compare(viewer, e1, e2, columnIndex);
}
}
private static final String ID_POPUP_MENU = "org.eclipse.mylyn.tasks.ui.editor.menu.attachments"; //$NON-NLS-1$
private final String[] attachmentsColumns = { Messages.TaskEditorAttachmentPart_Name,
Messages.TaskEditorAttachmentPart_Description, /*"Type", */Messages.TaskEditorAttachmentPart_Size,
Messages.TaskEditorAttachmentPart_Creator, Messages.TaskEditorAttachmentPart_Created,
Messages.TaskEditorAttachmentPart_ID };
private final int[] attachmentsColumnWidths = { 130, 150, /*100,*/70, 100, 100, 0 };
private List<TaskAttribute> attachments;
private boolean hasIncoming;
private MenuManager menuManager;
private Composite attachmentsComposite;
private Table attachmentsTable;
public TaskEditorAttachmentPart() {
setPartName(Messages.TaskEditorAttachmentPart_Attachments);
}
private void createAttachmentTable(FormToolkit toolkit, final Composite attachmentsComposite) {
attachmentsTable = toolkit.createTable(attachmentsComposite, SWT.MULTI | SWT.FULL_SELECTION);
attachmentsTable.setLinesVisible(true);
attachmentsTable.setHeaderVisible(true);
attachmentsTable.setLayout(new GridLayout());
GridDataFactory.fillDefaults()
.align(SWT.FILL, SWT.FILL)
.grab(true, false)
.hint(500, SWT.DEFAULT)
.applyTo(attachmentsTable);
attachmentsTable.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TREE_BORDER);
for (int i = 0; i < attachmentsColumns.length; i++) {
TableColumn column = new TableColumn(attachmentsTable, SWT.LEFT, i);
column.setText(attachmentsColumns[i]);
column.setWidth(attachmentsColumnWidths[i]);
column.setMoveable(true);
if (i == 4) {
attachmentsTable.setSortColumn(column);
attachmentsTable.setSortDirection(SWT.DOWN);
}
}
// size column
attachmentsTable.getColumn(2).setAlignment(SWT.RIGHT);
TableViewer attachmentsViewer = new TableViewer(attachmentsTable);
attachmentsViewer.setUseHashlookup(true);
attachmentsViewer.setColumnProperties(attachmentsColumns);
ColumnViewerToolTipSupport.enableFor(attachmentsViewer, ToolTip.NO_RECREATE);
attachmentsViewer.setSorter(new AttachmentTableSorter());
List<ITaskAttachment> attachmentList = new ArrayList<ITaskAttachment>(attachments.size());
for (TaskAttribute attribute : attachments) {
TaskAttachment taskAttachment = new TaskAttachment(getModel().getTaskRepository(), getModel().getTask(),
attribute);
getTaskData().getAttributeMapper().updateTaskAttachment(taskAttachment, attribute);
attachmentList.add(taskAttachment);
}
attachmentsViewer.setContentProvider(new ArrayContentProvider());
attachmentsViewer.setLabelProvider(new AttachmentTableLabelProvider(getModel(),
getTaskEditorPage().getAttributeEditorToolkit()));
attachmentsViewer.addOpenListener(new IOpenListener() {
public void open(OpenEvent event) {
openAttachments(event);
}
});
attachmentsViewer.addSelectionChangedListener(getTaskEditorPage());
attachmentsViewer.setInput(attachmentList.toArray());
menuManager = new MenuManager();
menuManager.setRemoveAllWhenShown(true);
menuManager.addMenuListener(new IMenuListener() {
public void menuAboutToShow(IMenuManager manager) {
TasksUiMenus.fillTaskAttachmentMenu(manager);
}
});
getTaskEditorPage().getEditorSite().registerContextMenu(ID_POPUP_MENU, menuManager, attachmentsViewer, true);
Menu menu = menuManager.createContextMenu(attachmentsTable);
attachmentsTable.setMenu(menu);
new TableViewerSupport(attachmentsViewer, getStateFile());
}
private File getStateFile() {
IPath stateLocation = Platform.getStateLocation(TasksUiPlugin.getDefault().getBundle());
return stateLocation.append("TaskEditorAttachmentPart.xml").toFile(); //$NON-NLS-1$
}
private void createButtons(Composite attachmentsComposite, FormToolkit toolkit) {
final Composite attachmentControlsComposite = toolkit.createComposite(attachmentsComposite);
attachmentControlsComposite.setLayout(new GridLayout(2, false));
attachmentControlsComposite.setLayoutData(new GridData(GridData.BEGINNING));
Button attachFileButton = toolkit.createButton(attachmentControlsComposite,
Messages.TaskEditorAttachmentPart_Attach_, SWT.PUSH);
attachFileButton.setImage(CommonImages.getImage(CommonImages.FILE_PLAIN));
attachFileButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
EditorUtil.openNewAttachmentWizard(getTaskEditorPage(), Mode.DEFAULT, null);
}
});
getTaskEditorPage().registerDefaultDropListener(attachFileButton);
Button attachScreenshotButton = toolkit.createButton(attachmentControlsComposite,
Messages.TaskEditorAttachmentPart_Attach__Screenshot, SWT.PUSH);
attachScreenshotButton.setImage(CommonImages.getImage(CommonImages.IMAGE_CAPTURE));
attachScreenshotButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
EditorUtil.openNewAttachmentWizard(getTaskEditorPage(), Mode.SCREENSHOT, null);
}
});
getTaskEditorPage().registerDefaultDropListener(attachScreenshotButton);
}
@Override
public void createControl(Composite parent, final FormToolkit toolkit) {
initialize();
final Section section = createSection(parent, toolkit, hasIncoming);
section.setText(getPartName() + " (" + attachments.size() + ")"); //$NON-NLS-1$ //$NON-NLS-2$
if (hasIncoming) {
expandSection(toolkit, section);
} else {
section.addExpansionListener(new ExpansionAdapter() {
@Override
public void expansionStateChanged(ExpansionEvent event) {
if (attachmentsComposite == null) {
expandSection(toolkit, section);
getTaskEditorPage().reflow();
}
}
});
}
setSection(toolkit, section);
}
private void expandSection(FormToolkit toolkit, Section section) {
attachmentsComposite = toolkit.createComposite(section);
attachmentsComposite.setLayout(EditorUtil.createSectionClientLayout());
attachmentsComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
getTaskEditorPage().registerDefaultDropListener(section);
if (attachments.size() > 0) {
createAttachmentTable(toolkit, attachmentsComposite);
} else {
Label label = toolkit.createLabel(attachmentsComposite, Messages.TaskEditorAttachmentPart_No_attachments);
getTaskEditorPage().registerDefaultDropListener(label);
}
createButtons(attachmentsComposite, toolkit);
toolkit.paintBordersFor(attachmentsComposite);
section.setClient(attachmentsComposite);
}
@Override
public void dispose() {
if (menuManager != null) {
menuManager.dispose();
}
super.dispose();
}
private void initialize() {
attachments = getTaskData().getAttributeMapper().getAttributesByType(getTaskData(),
TaskAttribute.TYPE_ATTACHMENT);
for (TaskAttribute attachmentAttribute : attachments) {
if (getModel().hasIncomingChanges(attachmentAttribute)) {
hasIncoming = true;
break;
}
}
}
@Override
protected void fillToolBar(ToolBarManager toolBarManager) {
Action attachFileAction = new Action() {
@Override
public void run() {
EditorUtil.openNewAttachmentWizard(getTaskEditorPage(), Mode.DEFAULT, null);
}
};
attachFileAction.setToolTipText(Messages.TaskEditorAttachmentPart_Attach_);
attachFileAction.setImageDescriptor(CommonImages.FILE_PLAIN_SMALL);
toolBarManager.add(attachFileAction);
}
protected void openAttachments(OpenEvent event) {
List<ITaskAttachment> attachments = new ArrayList<ITaskAttachment>();
StructuredSelection selection = (StructuredSelection) event.getSelection();
List<?> items = selection.toList();
for (Object item : items) {
if (item instanceof ITaskAttachment) {
attachments.add((ITaskAttachment) item);
}
}
if (attachments.isEmpty()) {
return;
}
IWorkbenchPage page = getTaskEditorPage().getSite().getWorkbenchWindow().getActivePage();
try {
OpenTaskAttachmentHandler.openAttachments(page, attachments);
} catch (OperationCanceledException e) {
// canceled
}
}
@Override
public boolean setFormInput(Object input) {
if (input instanceof String) {
String text = (String) input;
if (attachments != null) {
for (TaskAttribute attachmentAttribute : attachments) {
if (text.equals(attachmentAttribute.getId())) {
CommonFormUtil.setExpanded((ExpandableComposite) getControl(), true);
-
return selectReveal(attachmentAttribute);
}
}
}
}
return super.setFormInput(input);
}
public boolean selectReveal(TaskAttribute attachmentAttribute) {
if (attachmentAttribute == null || attachmentsTable == null) {
return false;
}
TableItem[] attachments = attachmentsTable.getItems();
int index = 0;
for (TableItem attachment : attachments) {
Object data = attachment.getData();
if (data instanceof ITaskAttachment) {
ITaskAttachment attachmentData = ((ITaskAttachment) data);
if (attachmentData.getTaskAttribute().getValue().equals(attachmentAttribute.getValue())) {
attachmentsTable.deselectAll();
attachmentsTable.select(index);
IManagedForm mform = getManagedForm();
ScrolledForm form = mform.getForm();
EditorUtil.focusOn(form, attachmentsTable);
return true;
}
}
index++;
}
return false;
}
}
| false | false | null | null |
diff --git a/src/io/github/sanbeg/flashlight/FlashLightActivity.java b/src/io/github/sanbeg/flashlight/FlashLightActivity.java
index 7f732ff..cdc2782 100644
--- a/src/io/github/sanbeg/flashlight/FlashLightActivity.java
+++ b/src/io/github/sanbeg/flashlight/FlashLightActivity.java
@@ -1,60 +1,68 @@
package io.github.sanbeg.flashlight;
import android.app.Activity;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.View;
import android.widget.ToggleButton;
import io.github.sanbeg.flashlight.R;
public class FlashLightActivity extends Activity {
private Camera camera=null;
private Camera.Parameters camera_parameters;
private String flash_mode;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
public void onResume(){
super.onResume();
if (camera==null)
camera=Camera.open();
camera_parameters = camera.getParameters();
flash_mode = camera_parameters.getFlashMode();
camera_parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(camera_parameters);
ToggleButton the_button = (ToggleButton) findViewById(R.id.flashlightButton);
if (the_button.isChecked()){
camera.startPreview();
the_button.setKeepScreenOn(true);
}
}
@Override
public void onPause(){
super.onPause();
- camera_parameters.setFlashMode(flash_mode);
- camera.setParameters(camera_parameters);
- camera.release();
- camera=null;
+
+ if (flash_mode != null){
+ //could be null if no flash, i.e. emulator
+ camera_parameters.setFlashMode(flash_mode);
+ } else {
+ camera_parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
+ }
+ if (camera != null) {
+ camera.setParameters(camera_parameters);
+ camera.release();
+ camera=null;
+ }
}
public void onToggleClicked(View v) {
if (((ToggleButton) v).isChecked()) {
camera.setParameters(camera_parameters);
camera.startPreview();
v.setKeepScreenOn(true);
} else {
camera.stopPreview();
v.setKeepScreenOn(false);
}
}
}
\ No newline at end of file
| true | false | null | null |
diff --git a/lang/java/src/java/org/apache/avro/generic/GenericDatumReader.java b/lang/java/src/java/org/apache/avro/generic/GenericDatumReader.java
index a69fa54d..d8b4dc0a 100644
--- a/lang/java/src/java/org/apache/avro/generic/GenericDatumReader.java
+++ b/lang/java/src/java/org/apache/avro/generic/GenericDatumReader.java
@@ -1,389 +1,396 @@
/**
* 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.avro.generic;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Collection;
import java.nio.ByteBuffer;
import org.apache.avro.AvroRuntimeException;
import org.apache.avro.Schema;
import org.apache.avro.Schema.Field;
import org.apache.avro.io.DatumReader;
import org.apache.avro.io.Decoder;
import org.apache.avro.io.ResolvingDecoder;
import org.apache.avro.util.Utf8;
import org.apache.avro.util.WeakIdentityHashMap;
/** {@link DatumReader} for generic Java objects. */
public class GenericDatumReader<D> implements DatumReader<D> {
private Schema actual;
private Schema expected;
- private ResolvingDecoder resolver;
public GenericDatumReader() {}
/** Construct where the writer's and reader's schemas are the same. */
public GenericDatumReader(Schema schema) {
this.actual = schema;
this.expected = schema;
}
/** Construct given writer's and reader's schema. */
public GenericDatumReader(Schema writer, Schema reader) {
this.actual = writer;
this.expected = reader;
}
@Override
public void setSchema(Schema writer) {
this.actual = writer;
if (expected == null) {
expected = actual;
}
- resolver = null;
+ threadResolver.set(null);
}
/** Set the reader's schema. */
public void setExpected(Schema reader) throws IOException {
this.expected = reader;
+ threadResolver.set(null);
}
+ private final ThreadLocal<ResolvingDecoder> threadResolver =
+ new ThreadLocal<ResolvingDecoder>();
+
private static final ThreadLocal<Map<Schema,Map<Schema,ResolvingDecoder>>>
RESOLVER_CACHE =
new ThreadLocal<Map<Schema,Map<Schema,ResolvingDecoder>>>() {
protected Map<Schema,Map<Schema,ResolvingDecoder>> initialValue() {
return new WeakIdentityHashMap<Schema,Map<Schema,ResolvingDecoder>>();
}
};
- private static ResolvingDecoder getResolver(Schema actual, Schema expected)
+ private ResolvingDecoder getResolver(Schema actual, Schema expected)
throws IOException {
+ ResolvingDecoder resolver = threadResolver.get();
+ if (resolver != null)
+ return resolver;
+
Map<Schema,ResolvingDecoder> cache = RESOLVER_CACHE.get().get(actual);
if (cache == null) {
cache = new WeakIdentityHashMap<Schema,ResolvingDecoder>();
RESOLVER_CACHE.get().put(actual, cache);
}
- ResolvingDecoder resolver = cache.get(expected);
+ resolver = cache.get(expected);
if (resolver == null) {
resolver = new ResolvingDecoder(Schema.applyAliases(actual, expected),
expected, null);
cache.put(expected, resolver);
}
+ threadResolver.set(resolver);
return resolver;
}
@SuppressWarnings("unchecked")
public D read(D reuse, Decoder in) throws IOException {
- if (resolver == null)
- resolver = getResolver(actual, expected);
+ ResolvingDecoder resolver = getResolver(actual, expected);
resolver.init(in);
D result = (D) read(reuse, expected, resolver);
resolver.drain();
return result;
}
/** Called to read data.*/
protected Object read(Object old, Schema expected,
ResolvingDecoder in) throws IOException {
switch (expected.getType()) {
case RECORD: return readRecord(old, expected, in);
case ENUM: return readEnum(expected, in);
case ARRAY: return readArray(old, expected, in);
case MAP: return readMap(old, expected, in);
case UNION: return read(old, expected.getTypes().get(in.readIndex()), in);
case FIXED: return readFixed(old, expected, in);
case STRING: return readString(old, expected, in);
case BYTES: return readBytes(old, in);
case INT: return readInt(old, expected, in);
case LONG: return in.readLong();
case FLOAT: return in.readFloat();
case DOUBLE: return in.readDouble();
case BOOLEAN: return in.readBoolean();
case NULL: in.readNull(); return null;
default: throw new AvroRuntimeException("Unknown type: " + expected);
}
}
/** Called to read a record instance. May be overridden for alternate record
* representations.*/
protected Object readRecord(Object old, Schema expected,
ResolvingDecoder in) throws IOException {
Object record = newRecord(old, expected);
for (Field f : in.readFieldOrder()) {
int pos = f.pos();
String name = f.name();
Object oldDatum = (old != null) ? getField(record, name, pos) : null;
setField(record, name, pos, read(oldDatum, f.schema(), in));
}
return record;
}
/** Called by the default implementation of {@link #readRecord} to set a
* record fields value to a record instance. The default implementation is
* for {@link IndexedRecord}.*/
protected void setField(Object record, String name, int position, Object o) {
((IndexedRecord)record).put(position, o);
}
/** Called by the default implementation of {@link #readRecord} to retrieve a
* record field value from a reused instance. The default implementation is
* for {@link IndexedRecord}.*/
protected Object getField(Object record, String name, int position) {
return ((IndexedRecord)record).get(position);
}
/** Called by the default implementation of {@link #readRecord} to remove a
* record field value from a reused instance. The default implementation is
* for {@link GenericRecord}.*/
protected void removeField(Object record, String field, int position) {
((GenericRecord)record).put(position, null);
}
/** Called to read an enum value. May be overridden for alternate enum
* representations. By default, returns a GenericEnumSymbol. */
protected Object readEnum(Schema expected, Decoder in) throws IOException {
return createEnum(expected.getEnumSymbols().get(in.readEnum()), expected);
}
/** Called to create an enum value. May be overridden for alternate enum
* representations. By default, returns a GenericEnumSymbol. */
protected Object createEnum(String symbol, Schema schema) {
return new GenericData.EnumSymbol(symbol);
}
/** Called to read an array instance. May be overridden for alternate array
* representations.*/
protected Object readArray(Object old, Schema expected,
ResolvingDecoder in) throws IOException {
Schema expectedType = expected.getElementType();
long l = in.readArrayStart();
long base = 0;
if (l > 0) {
Object array = newArray(old, (int) l, expected);
do {
for (long i = 0; i < l; i++) {
addToArray(array, base + i, read(peekArray(array), expectedType, in));
}
base += l;
} while ((l = in.arrayNext()) > 0);
return array;
} else {
return newArray(old, 0, expected);
}
}
/** Called by the default implementation of {@link #readArray} to retrieve a
* value from a reused instance. The default implementation is for {@link
* GenericArray}.*/
@SuppressWarnings("unchecked")
protected Object peekArray(Object array) {
return (array instanceof GenericArray)
? ((GenericArray)array).peek()
: null;
}
/** Called by the default implementation of {@link #readArray} to add a
* value. The default implementation is for {@link Collection}.*/
@SuppressWarnings("unchecked")
protected void addToArray(Object array, long pos, Object e) {
((Collection) array).add(e);
}
/** Called to read a map instance. May be overridden for alternate map
* representations.*/
protected Object readMap(Object old, Schema expected,
ResolvingDecoder in) throws IOException {
Schema eValue = expected.getValueType();
long l = in.readMapStart();
Object map = newMap(old, (int) l);
if (l > 0) {
do {
for (int i = 0; i < l; i++) {
addToMap(map, readString(null, in), read(null, eValue, in));
}
} while ((l = in.mapNext()) > 0);
}
return map;
}
/** Called by the default implementation of {@link #readMap} to add a
* key/value pair. The default implementation is for {@link Map}.*/
@SuppressWarnings("unchecked")
protected void addToMap(Object map, Object key, Object value) {
((Map) map).put(key, value);
}
/** Called to read a fixed value. May be overridden for alternate fixed
* representations. By default, returns {@link GenericFixed}. */
protected Object readFixed(Object old, Schema expected, Decoder in)
throws IOException {
GenericFixed fixed = (GenericFixed)createFixed(old, expected);
in.readFixed(fixed.bytes(), 0, expected.getFixedSize());
return fixed;
}
/** Called to create an fixed value. May be overridden for alternate fixed
* representations. By default, returns {@link GenericFixed}. */
protected Object createFixed(Object old, Schema schema) {
if ((old instanceof GenericFixed)
&& ((GenericFixed)old).bytes().length == schema.getFixedSize())
return old;
return new GenericData.Fixed(schema);
}
/** Called to create an fixed value. May be overridden for alternate fixed
* representations. By default, returns {@link GenericFixed}. */
protected Object createFixed(Object old, byte[] bytes, Schema schema) {
GenericFixed fixed = (GenericFixed)createFixed(old, schema);
System.arraycopy(bytes, 0, fixed.bytes(), 0, schema.getFixedSize());
return fixed;
}
/**
* Called to create new record instances. Subclasses may override to use a
* different record implementation. The returned instance must conform to the
* schema provided. If the old object contains fields not present in the
* schema, they should either be removed from the old object, or it should
* create a new instance that conforms to the schema. By default, this returns
* a {@link GenericData.Record}.
*/
protected Object newRecord(Object old, Schema schema) {
if (old instanceof IndexedRecord) {
IndexedRecord record = (IndexedRecord)old;
if (record.getSchema() == schema)
return record;
}
return new GenericData.Record(schema);
}
/** Called to create new array instances. Subclasses may override to use a
* different array implementation. By default, this returns a {@link
* GenericData.Array}.*/
@SuppressWarnings("unchecked")
protected Object newArray(Object old, int size, Schema schema) {
if (old instanceof Collection) {
((Collection) old).clear();
return old;
} else return new GenericData.Array(size, schema);
}
/** Called to create new array instances. Subclasses may override to use a
* different map implementation. By default, this returns a {@link
* HashMap}.*/
@SuppressWarnings("unchecked")
protected Object newMap(Object old, int size) {
if (old instanceof Map) {
((Map) old).clear();
return old;
} else return new HashMap<Object, Object>(size);
}
/** Called to read strings. Subclasses may override to use a different
* string representation. By default, this calls {@link
* #readString(Object,Decoder)}.*/
protected Object readString(Object old, Schema expected,
Decoder in) throws IOException {
return readString(old, in);
}
/** Called to read strings. Subclasses may override to use a different
* string representation. By default, this calls {@link
* Decoder#readString(Utf8)}.*/
protected Object readString(Object old, Decoder in) throws IOException {
return in.readString(old instanceof Utf8 ? (Utf8)old : null);
}
/** Called to create a string from a default value. Subclasses may override
* to use a different string representation. By default, this calls {@link
* Utf8#Utf8(String)}.*/
protected Object createString(String value) { return new Utf8(value); }
/** Called to read byte arrays. Subclasses may override to use a different
* byte array representation. By default, this calls {@link
* Decoder#readBytes(ByteBuffer)}.*/
protected Object readBytes(Object old, Decoder in) throws IOException {
return in.readBytes((ByteBuffer)old);
}
/** Called to read integers. Subclasses may override to use a different
* integer representation. By default, this calls {@link
* Decoder#readInt()}.*/
protected Object readInt(Object old, Schema expected, Decoder in)
throws IOException {
return in.readInt();
}
/** Called to create byte arrays from default values. Subclasses may
* override to use a different byte array representation. By default, this
* calls {@link ByteBuffer#wrap(byte[])}.*/
protected Object createBytes(byte[] value) { return ByteBuffer.wrap(value); }
/** Skip an instance of a schema. */
public static void skip(Schema schema, Decoder in) throws IOException {
switch (schema.getType()) {
case RECORD:
for (Field field : schema.getFields())
skip(field.schema(), in);
break;
case ENUM:
in.readInt();
break;
case ARRAY:
Schema elementType = schema.getElementType();
for (long l = in.skipArray(); l > 0; l = in.skipArray()) {
for (long i = 0; i < l; i++) {
skip(elementType, in);
}
}
break;
case MAP:
Schema value = schema.getValueType();
for (long l = in.skipMap(); l > 0; l = in.skipMap()) {
for (long i = 0; i < l; i++) {
in.skipString();
skip(value, in);
}
}
break;
case UNION:
skip(schema.getTypes().get((int)in.readIndex()), in);
break;
case FIXED:
in.skipFixed(schema.getFixedSize());
break;
case STRING:
in.skipString();
break;
case BYTES:
in.skipBytes();
break;
case INT: in.readInt(); break;
case LONG: in.readLong(); break;
case FLOAT: in.readFloat(); break;
case DOUBLE: in.readDouble(); break;
case BOOLEAN: in.readBoolean(); break;
case NULL: break;
default: throw new RuntimeException("Unknown type: "+schema);
}
}
}
| false | false | null | null |
diff --git a/src/main/java/com/googlecode/mgwt/ui/client/widget/Carousel.java b/src/main/java/com/googlecode/mgwt/ui/client/widget/Carousel.java
index 696f6fdc..c3b5a42a 100644
--- a/src/main/java/com/googlecode/mgwt/ui/client/widget/Carousel.java
+++ b/src/main/java/com/googlecode/mgwt/ui/client/widget/Carousel.java
@@ -1,429 +1,434 @@
/*
* Copyright 2012 Daniel Kurka
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.googlecode.mgwt.ui.client.widget;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Set;
-
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.event.logical.shared.HasSelectionHandlers;
import com.google.gwt.event.logical.shared.ResizeEvent;
import com.google.gwt.event.logical.shared.ResizeHandler;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;
+
import com.googlecode.mgwt.collection.shared.LightArrayInt;
import com.googlecode.mgwt.dom.client.event.orientation.OrientationChangeEvent;
import com.googlecode.mgwt.dom.client.event.orientation.OrientationChangeHandler;
import com.googlecode.mgwt.ui.client.MGWT;
import com.googlecode.mgwt.ui.client.MGWTStyle;
import com.googlecode.mgwt.ui.client.theme.base.CarouselCss;
import com.googlecode.mgwt.ui.client.widget.event.scroll.ScrollEndEvent;
import com.googlecode.mgwt.ui.client.widget.event.scroll.ScrollRefreshEvent;
import com.googlecode.mgwt.ui.client.widget.touch.TouchWidget;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+
/**
* the carousel widget renders its children in a horizontal row. users can select a different child
* by swiping between them
*
* @author Daniel Kurka
*
*/
public class Carousel extends Composite implements HasWidgets, HasSelectionHandlers<Integer> {
private static class CarouselIndicatorContainer extends Composite {
private FlowPanel main;
private final CarouselCss css;
private ArrayList<CarouselIndicator> indicators;
private int selectedIndex;
public CarouselIndicatorContainer(CarouselCss css, int numberOfPages) {
if (numberOfPages < 0) {
throw new IllegalArgumentException();
}
this.css = css;
main = new FlowPanel();
initWidget(main);
main.addStyleName(this.css.indicatorContainer());
indicators = new ArrayList<Carousel.CarouselIndicator>(numberOfPages);
selectedIndex = 0;
for (int i = 0; i < numberOfPages; i++) {
CarouselIndicator indicator = new CarouselIndicator(css);
indicators.add(indicator);
main.add(indicator);
}
setSelectedIndex(selectedIndex);
}
public void setSelectedIndex(int index) {
if (indicators.isEmpty()) {
selectedIndex = -1;
return;
}
if (selectedIndex != -1) {
indicators.get(selectedIndex).setActive(false);
}
selectedIndex = index;
if (selectedIndex != -1) {
indicators.get(selectedIndex).setActive(true);
}
}
}
private static class CarouselIndicator extends TouchWidget {
private final CarouselCss css;
public CarouselIndicator(CarouselCss css) {
this.css = css;
setElement(DOM.createDiv());
addStyleName(css.indicator());
}
public void setActive(boolean active) {
if (active) {
addStyleName(css.indicatorActive());
} else {
removeStyleName(css.indicatorActive());
}
}
}
private static class WidgetHolder extends FlowPanel {
public WidgetHolder(CarouselCss css) {
addStyleName(css.carouselHolder());
}
@Override
public void add(Widget w) {
super.add(w);
if (w instanceof ScrollPanel) {
w.addStyleName(MGWTStyle.getTheme().getMGWTClientBundle().getLayoutCss().fillPanelExpandChild());
}
}
}
private FlowPanel main;
private final CarouselCss css;
private ScrollPanel scrollPanel;
private FlowPanel container;
private CarouselIndicatorContainer carouselIndicatorContainer;
private boolean isVisibleCarouselIndicator = true;
private int currentPage;
private Map<Widget, Widget> childToHolder;
private com.google.web.bindery.event.shared.HandlerRegistration refreshHandler;
private static final CarouselImpl IMPL = GWT.create(CarouselImpl.class);
/**
* Construct a carousel widget with the default css
*/
public Carousel() {
this(MGWTStyle.getTheme().getMGWTClientBundle().getCarouselCss());
}
/**
* Construct a carousel widget with a given css
*
* @param css the css to use
*/
public Carousel(CarouselCss css) {
this.css = css;
this.css.ensureInjected();
childToHolder = new HashMap<Widget, Widget>();
main = new FlowPanel();
initWidget(main);
main.addStyleName(css.carousel());
scrollPanel = new ScrollPanel();
scrollPanel.addStyleName(css.carouselScroller());
main.add(scrollPanel);
container = new FlowPanel();
container.addStyleName(css.carouselContainer());
scrollPanel.setWidget(container);
scrollPanel.setSnap(true);
scrollPanel.setMomentum(false);
scrollPanel.setShowScrollBarX(false);
scrollPanel.setShowScrollBarY(false);
scrollPanel.setScrollingEnabledY(true);
scrollPanel.setAutoHandleResize(false);
currentPage = 0;
scrollPanel.addScrollEndHandler(new ScrollEndEvent.Handler() {
@Override
public void onScrollEnd(ScrollEndEvent event) {
int page = scrollPanel.getCurrentPageX();
carouselIndicatorContainer.setSelectedIndex(page);
currentPage = page;
SelectionEvent.fire(Carousel.this, currentPage);
}
});
MGWT.addOrientationChangeHandler(new OrientationChangeHandler() {
@Override
public void onOrientationChanged(OrientationChangeEvent event) {
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
refresh();
}
});
}
});
addSelectionHandler(new SelectionHandler<Integer>() {
@Override
public void onSelection(SelectionEvent<Integer> event) {
carouselIndicatorContainer.setSelectedIndex(currentPage);
}
});
if (MGWT.getOsDetection().isDesktop()) {
Window.addResizeHandler(new ResizeHandler() {
@Override
public void onResize(ResizeEvent event) {
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
refresh();
}
});
}
});
}
}
@Override
public void add(Widget w) {
WidgetHolder widgetHolder = new WidgetHolder(css);
widgetHolder.add(w);
childToHolder.put(w, widgetHolder);
container.add(widgetHolder);
}
@Override
public void clear() {
container.clear();
childToHolder.clear();
}
@Override
public Iterator<Widget> iterator() {
Set<Widget> keySet = childToHolder.keySet();
return keySet.iterator();
}
@Override
public boolean remove(Widget w) {
Widget holder = childToHolder.remove(w);
if (holder != null) {
return container.remove(holder);
}
return false;
}
@Override
protected void onAttach() {
super.onAttach();
refresh();
}
/**
* refresh the carousel widget, this is necessary after changing child elements
*/
public void refresh() {
IMPL.adjust(main, container);
scrollPanel.setScrollingEnabledX(true);
scrollPanel.setScrollingEnabledY(false);
scrollPanel.setShowScrollBarX(false);
scrollPanel.setShowScrollBarY(false);
if (carouselIndicatorContainer != null) {
carouselIndicatorContainer.removeFromParent();
}
int widgetCount = container.getWidgetCount();
carouselIndicatorContainer = new CarouselIndicatorContainer(css, widgetCount);
if(isVisibleCarouselIndicator){
main.add(carouselIndicatorContainer);
}
if (currentPage >= widgetCount) {
currentPage = widgetCount - 1;
}
carouselIndicatorContainer.setSelectedIndex(currentPage);
scrollPanel.refresh();
refreshHandler = scrollPanel.addScrollRefreshHandler(new ScrollRefreshEvent.Handler() {
@Override
public void onScrollRefresh(ScrollRefreshEvent event) {
refreshHandler.removeHandler();
refreshHandler = null;
scrollPanel.scrollToPage(currentPage, 0, 0);
}
});
}
public void setSelectedPage(int index) {
LightArrayInt pagesX = scrollPanel.getPagesX();
if (index < 0 || index >= pagesX.length()) {
throw new IllegalArgumentException("invalid value for index: " + index);
}
currentPage = index;
scrollPanel.scrollToPage(index, 0, 300);
}
+ public int getSelectedPage() {
+ return currentPage;
+ }
+
@Override
public HandlerRegistration addSelectionHandler(SelectionHandler<Integer> handler) {
return addHandler(handler, SelectionEvent.getType());
}
public ScrollPanel getScrollPanel() {
return scrollPanel;
}
/**
*
* @author Daniel Kurka
*
*/
public static interface CarouselImpl {
/**
*
* @param main
* @param container
*/
void adjust(FlowPanel main, FlowPanel container);
}
/**
*
* @author Daniel Kurka
*
*/
public static class CarouselImplSafari implements CarouselImpl {
@Override
public void adjust(FlowPanel main, FlowPanel container) {
int widgetCount = container.getWidgetCount();
double sizeFactor = 100d / widgetCount;
for (int i = 0; i < widgetCount; i++) {
container.getWidget(i).setWidth(sizeFactor + "%");
}
container.setWidth((widgetCount * 100) + "%");
}
}
/**
*
* @author Daniel Kurka
*
*/
public static class CarouselImplGecko implements CarouselImpl {
@Override
public void adjust(FlowPanel main, FlowPanel container) {
int widgetCount = container.getWidgetCount();
int offsetWidth = main.getOffsetWidth();
container.setWidth(widgetCount * offsetWidth + "px");
for (int i = 0; i < widgetCount; i++) {
container.getWidget(i).setWidth(offsetWidth + "px");
}
}
}
/**
* Set if carousel indicator is displayed.
*/
public void setShowCarouselIndicator(boolean isVisibleCarouselIndicator) {
if (!isVisibleCarouselIndicator && carouselIndicatorContainer != null) {
carouselIndicatorContainer.removeFromParent();
}
this.isVisibleCarouselIndicator = isVisibleCarouselIndicator;
}
}
| false | false | null | null |
diff --git a/org.eclipse.mylyn.reviews.r4e.ui/src/org/eclipse/mylyn/reviews/r4e/ui/internal/model/R4EUIAnomalyBasic.java b/org.eclipse.mylyn.reviews.r4e.ui/src/org/eclipse/mylyn/reviews/r4e/ui/internal/model/R4EUIAnomalyBasic.java
index c24093a3..1843744d 100644
--- a/org.eclipse.mylyn.reviews.r4e.ui/src/org/eclipse/mylyn/reviews/r4e/ui/internal/model/R4EUIAnomalyBasic.java
+++ b/org.eclipse.mylyn.reviews.r4e.ui/src/org/eclipse/mylyn/reviews/r4e/ui/internal/model/R4EUIAnomalyBasic.java
@@ -1,1006 +1,1008 @@
// $codepro.audit.disable com.instantiations.assist.eclipse.analysis.audit.rule.effectivejava.alwaysOverridetoString.alwaysOverrideToString, com.instantiations.assist.eclipse.analysis.deserializeabilitySecurity, com.instantiations.assist.eclipse.analysis.disallowReturnMutable, com.instantiations.assist.eclipse.analysis.enforceCloneableUsageSecurity, com.instantiations.assist.eclipse.analysis.mutabilityOfArrays
/*******************************************************************************
* Copyright (c) 2010, 2012 Ericsson AB and others.
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Description:
*
* This class implements the Anomaly element of the UI model
*
* Contributors:
* Sebastien Dubois - Created for Mylyn Review R4E project
*
*******************************************************************************/
package org.eclipse.mylyn.reviews.r4e.ui.internal.model;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.util.LocalSelectionTransfer;
import org.eclipse.jface.viewers.AbstractTreeViewer;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.window.Window;
import org.eclipse.mylyn.reviews.frame.core.model.Comment;
import org.eclipse.mylyn.reviews.frame.core.model.ReviewComponent;
import org.eclipse.mylyn.reviews.r4e.core.model.R4EAnomaly;
import org.eclipse.mylyn.reviews.r4e.core.model.R4EComment;
import org.eclipse.mylyn.reviews.r4e.core.model.R4ECommentType;
import org.eclipse.mylyn.reviews.r4e.core.model.R4EParticipant;
import org.eclipse.mylyn.reviews.r4e.core.model.R4EReviewComponent;
import org.eclipse.mylyn.reviews.r4e.core.model.R4EReviewPhase;
import org.eclipse.mylyn.reviews.r4e.core.model.R4EReviewState;
import org.eclipse.mylyn.reviews.r4e.core.model.RModelFactory;
import org.eclipse.mylyn.reviews.r4e.core.model.serial.impl.CompatibilityException;
import org.eclipse.mylyn.reviews.r4e.core.model.serial.impl.OutOfSyncException;
import org.eclipse.mylyn.reviews.r4e.core.model.serial.impl.ResourceHandlingException;
import org.eclipse.mylyn.reviews.r4e.ui.R4EUIPlugin;
import org.eclipse.mylyn.reviews.r4e.ui.internal.dialogs.ICommentInputDialog;
import org.eclipse.mylyn.reviews.r4e.ui.internal.dialogs.R4EUIDialogFactory;
import org.eclipse.mylyn.reviews.r4e.ui.internal.preferences.PreferenceConstants;
import org.eclipse.mylyn.reviews.r4e.ui.internal.properties.general.AnomalyBasicProperties;
import org.eclipse.mylyn.reviews.r4e.ui.internal.utils.R4EUIConstants;
import org.eclipse.mylyn.reviews.r4e.ui.internal.utils.UIUtils;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.views.properties.IPropertySource;
/**
* @author Sebastien Dubois
* @version $Revision: 1.0 $
*/
public class R4EUIAnomalyBasic extends R4EUIModelElement {
// ------------------------------------------------------------------------
// Constants
// ------------------------------------------------------------------------
/**
* Field fAnomalyFile. (value is ""icons/obj16/anmly_obj.gif"")
*/
public static final String ANOMALY_ICON_FILE = "icons/obj16/anmly_obj.gif";
/**
* Field NEW_CHILD_ELEMENT_COMMAND_NAME. (value is ""New Comment..."")
*/
private static final String NEW_CHILD_ELEMENT_COMMAND_NAME = "New Comment...";
/**
* Field NEW_CHILD_ELEMENT_COMMAND_TOOLTIP. (value is ""Add a New comment to the current anomaly"")
*/
private static final String NEW_CHILD_ELEMENT_COMMAND_TOOLTIP = "Add a New Comment to the Current Anomaly";
/**
* Field COPY_ELEMENT_COMMAND_NAME. (value is ""Copy Anomalies"")
*/
private static final String COPY_ELEMENT_COMMAND_NAME = "Copy Anomalies";
/**
* Field COPY_ELEMENT_COMMAND_TOOLTIP. (value is ""Copy Anomalies to Clipboard"")
*/
private static final String COPY_ELEMENT_COMMAND_TOOLTIP = "Copy Anomalies to Clipboard";
/**
* Field PASTE_ELEMENT_COMMAND_NAME. (value is ""Paste Comments"")
*/
private static final String PASTE_ELEMENT_COMMAND_NAME = "Paste Comments";
/**
* Field PASTE_ELEMENT_COMMAND_TOOLTIP. (value is ""Clone Comments in Clipboard to this Anomaly" +
* " from its Parent Container"")
*/
private static final String PASTE_ELEMENT_COMMAND_TOOLTIP = "Clone Comments in Clipboard to this Anomaly";
/**
* Field REMOVE_ELEMENT_ACTION_NAME. (value is ""Delete Anomaly"")
*/
private static final String REMOVE_ELEMENT_COMMAND_NAME = "Disable Anomaly";
/**
* Field REMOVE_ELEMENT_ACTION_TOOLTIP. (value is ""Remove this anomaly from its parent file or review item"")
*/
private static final String REMOVE_ELEMENT_COMMAND_TOOLTIP = "Remove this Anomaly "
+ "from its parent file or review";
/**
* Field RESTORE_ELEMENT_COMMAND_NAME. (value is ""Restore Anomaly"")
*/
private static final String RESTORE_ELEMENT_COMMAND_NAME = "Restore Anomaly";
/**
* Field RESTORE_ELEMENT_ACTION_TOOLTIP. (value is ""Restore this disabled Anomaly"")
*/
private static final String RESTORE_ELEMENT_COMMAND_TOOLTIP = "Restore this disabled Anomaly";
/**
* Field ANOMALY_LABEL_TITLE_LENGTH. (value is 20)
*/
private static final int ANOMALY_LABEL_TITLE_LENGTH = 20;
/**
* Field CREATE_COMMENT_MESSAGE. (value is ""Creating New Comment..."")
*/
private static final String CREATE_COMMENT_MESSAGE = "Creating New Comment...";
// ------------------------------------------------------------------------
// Member variables
// ------------------------------------------------------------------------
/**
* Field fAnomaly.
*/
protected final R4EAnomaly fAnomaly;
/**
* Field fComments.
*/
private final List<R4EUIComment> fComments;
/**
* Field fPosition.
*/
private final IR4EUIPosition fPosition;
// ------------------------------------------------------------------------
// Constructors
// ------------------------------------------------------------------------
/**
* Constructor for R4EUIAnomaly.
*
* @param aParent
* IR4EUIModelElement
* @param aAnomaly
* R4EAnomaly
* @param aPosition
* IR4EUIPosition
*/
public R4EUIAnomalyBasic(IR4EUIModelElement aParent, R4EAnomaly aAnomaly, IR4EUIPosition aPosition) {
super(aParent, buildAnomalyName(aAnomaly, aPosition));
fReadOnly = aParent.isReadOnly();
fAnomaly = aAnomaly;
fComments = new ArrayList<R4EUIComment>();
fPosition = aPosition;
}
// ------------------------------------------------------------------------
// Methods
// ------------------------------------------------------------------------
/**
* Method isSameAs. Used to avoid duplicated in collections
*
* @param aSource
* - R4EUIAnomalyBasic
* @return boolean
* @see lang.java.Object#equals(Object)
*/
public boolean isSameAs(R4EUIAnomalyBasic aSource) {
if (aSource instanceof R4EUIAnomalyBasic) {
if (this.getAnomaly().getTitle().equals(aSource.getAnomaly().getTitle())
&& this.getAnomaly().getDescription().equals(aSource.getAnomaly().getDescription())) {
return true;
}
}
return false;
}
/**
* Method getImageLocation.
*
* @return String
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.model.IR4EUIModelElement#getImageLocation()
*/
public String getImageLocation() {
return ANOMALY_ICON_FILE;
}
/**
* Method getToolTip.
*
* @return String
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.model.IR4EUIModelElement#getToolTip()
*/
@Override
public String getToolTip() {
if (isDueDatePassed()) {
return R4EUIConstants.DUE_DATE_PASSED_MSG + buildAnomalyToolTip(fAnomaly);
}
return buildAnomalyToolTip(fAnomaly);
}
/**
* Method getToolTipColor.
*
* @return Color
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.model.IR4EUIModelElement#getToolTipColor()
*/
@Override
public Color getToolTipColor() {
if (isDueDatePassed()) {
return Display.getCurrent().getSystemColor(SWT.COLOR_DARK_RED);
}
return Display.getCurrent().getSystemColor(SWT.COLOR_BLACK);
}
/**
* Method getAdapter.
*
* @param adapter
* Class
* @return Object
* @see org.eclipse.core.runtime.IAdaptable#getAdapter(Class)
*/
@Override
public Object getAdapter(@SuppressWarnings("rawtypes")
Class adapter) {
if (IR4EUIModelElement.class.equals(adapter)) {
return this;
}
if (IPropertySource.class.equals(adapter)) {
return new AnomalyBasicProperties(this);
}
return null;
}
//Attributes
/**
* Method getAnomaly.
*
* @return R4EAnomaly
*/
public R4EAnomaly getAnomaly() {
return fAnomaly;
}
/**
* Method getPosition.
*
* @return IR4EPosition
*/
public IR4EUIPosition getPosition() {
return fPosition;
}
/**
* Create a serialization model element object
*
* @return the new serialization element object
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.model.IR4EUIModelElement#createChildModelDataElement()
*/
@Override
public List<ReviewComponent> createChildModelDataElement() {
//Get Comment from user and set it in model data
final List<ReviewComponent> tempComments = new ArrayList<ReviewComponent>();
R4EUIModelController.setJobInProgress(true);
final ICommentInputDialog dialog = R4EUIDialogFactory.getInstance().getCommentInputDialog();
final int result = dialog.open();
if (result == Window.OK) {
final R4EComment tempComment = RModelFactory.eINSTANCE.createR4EComment();
tempComment.setDescription(dialog.getCommentValue());
tempComments.add(tempComment);
}
R4EUIModelController.setJobInProgress(false);
return tempComments;
}
/**
* Set serialization model data by copying it from the passed-in object
*
* @param aModelComponent
* - a serialization model element to copy information from
* @throws ResourceHandlingException
* @throws OutOfSyncException
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.model.IR4EUIModelElement#setModelData(R4EReviewComponent)
*/
@Override
public void setModelData(ReviewComponent aModelComponent) throws ResourceHandlingException, OutOfSyncException {
//Set data in model element
final Long bookNum = R4EUIModelController.FResourceUpdater.checkOut(fAnomaly,
R4EUIModelController.getReviewer());
fAnomaly.setTitle(((R4EAnomaly) aModelComponent).getTitle());
fAnomaly.setDescription(((R4EAnomaly) aModelComponent).getDescription());
if (null != ((R4EAnomaly) aModelComponent).getType()) {
final R4ECommentType commentType = RModelFactory.eINSTANCE.createR4ECommentType();
commentType.setType(((R4ECommentType) ((R4EAnomaly) aModelComponent).getType()).getType());
fAnomaly.setType(commentType);
}
fAnomaly.setRank(((R4EAnomaly) aModelComponent).getRank());
fAnomaly.setRuleID(((R4EAnomaly) aModelComponent).getRuleID());
R4EUIModelController.FResourceUpdater.checkIn(bookNum);
}
/**
* Set extra serialization model data by copying it from the passed-in object
*
* @param aModelComponent
* - a serialization model element to copy information from
* @throws ResourceHandlingException
* @throws OutOfSyncException
*/
public void setExtraModelData(ReviewComponent aModelComponent) throws ResourceHandlingException, OutOfSyncException {
final Long bookNum = R4EUIModelController.FResourceUpdater.checkOut(fAnomaly,
R4EUIModelController.getReviewer());
fAnomaly.setDueDate(((R4EAnomaly) aModelComponent).getDueDate());
fAnomaly.getAssignedTo().addAll(((R4EAnomaly) aModelComponent).getAssignedTo());
R4EUIModelController.FResourceUpdater.checkIn(bookNum);
}
/**
* Method buildAnomalyName.
*
* @param aAnomaly
* - the anomaly to use
* @param aPosition
* IR4EUIPosition
* @return String - the new name
*/
public static String buildAnomalyName(R4EAnomaly aAnomaly, IR4EUIPosition aPosition) {
return (null == aPosition) ? adjustTitleLength(aAnomaly) : aPosition.toString() + "->"
+ adjustTitleLength(aAnomaly);
}
/**
* Method adjustTitleLength.
*
* @param aAnomaly
* R4EAnomaly
* @return String
*/
protected static String adjustTitleLength(R4EAnomaly aAnomaly) {
String anomalyTitle = aAnomaly.getTitle();
if (anomalyTitle == null) {
return ""; //return an empty string for the null title
}
if (anomalyTitle.length() > ANOMALY_LABEL_TITLE_LENGTH) {
return anomalyTitle.substring(0, ANOMALY_LABEL_TITLE_LENGTH) + R4EUIConstants.ELLIPSIS_STR;
} else {
return anomalyTitle;
}
}
/**
* Method buildAnomalyToolTip.
*
* @param aAnomaly
* - the anomaly to use
* @return String - the new tooltip
*/
public static String buildAnomalyToolTip(R4EAnomaly aAnomaly) {
return aAnomaly.getUser().getId() + ": " + aAnomaly.getDescription();
}
/**
* Method setEnabled.
*
* @param aEnabled
* boolean
* @throws ResourceHandlingException
* @throws OutOfSyncException
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.model.IR4EUIModelElement#setEnabled(boolean)
*/
@Override
public void setEnabled(boolean aEnabled) throws ResourceHandlingException, OutOfSyncException {
final Long bookNum = R4EUIModelController.FResourceUpdater.checkOut(fAnomaly,
R4EUIModelController.getReviewer());
fAnomaly.setEnabled(true);
R4EUIModelController.FResourceUpdater.checkIn(bookNum);
}
/**
* Method isEnabled.
*
* @return boolean
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.model.IR4EUIModelElement#isEnabled()
*/
@Override
public boolean isEnabled() {
return fAnomaly.isEnabled();
}
//Hierarchy
/**
* Method getChildren.
*
* @return IR4EUIModelElement[]
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.model.IR4EUIModelElement#getChildren()
*/
@Override
public IR4EUIModelElement[] getChildren() {
return fComments.toArray(new R4EUIComment[fComments.size()]);
}
/**
* Method hasChildren.
*
* @return boolean
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.model.IR4EUIModelElement#hasChildren()
*/
@Override
public boolean hasChildren() {
if (fComments.size() > 0) {
return true;
}
return false;
}
/**
* Close the model element (i.e. disable it)
*
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.model.IR4EUIModelElement#close()
*/
@Override
public void close() {
//Remove all children references
R4EUIComment comment = null;
final int commentsSize = fComments.size();
for (int i = 0; i < commentsSize; i++) {
comment = fComments.get(i);
comment.close();
}
fComments.clear();
fOpen = false;
}
/**
* Method open. Load the serialization model data into UI model
*
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.model.IR4EUIModelElement#open()
*/
@Override
public void open() {
final List<Comment> comments = fAnomaly.getComments();
if (null != comments) {
R4EComment r4eComment = null;
final int commentsSize = comments.size();
for (int i = 0; i < commentsSize; i++) {
r4eComment = (R4EComment) comments.get(i);
if (r4eComment.isEnabled()
|| R4EUIPlugin.getDefault()
.getPreferenceStore()
.getBoolean(PreferenceConstants.P_SHOW_DISABLED)) {
addChildren(new R4EUIComment(this, r4eComment));
}
}
}
fOpen = true;
}
/**
* Method addChildren.
*
* @param aChildToAdd
* IR4EUIModelElement
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.model.IR4EUIModelElement#addChildren(IR4EUIModelElement)
*/
@Override
public void addChildren(IR4EUIModelElement aChildToAdd) {
fComments.add((R4EUIComment) aChildToAdd);
}
/**
* Method addChildren.
*
* @param aModelComponent
* - the serialization model component object
* @return IR4EUIModelElement
* @throws ResourceHandlingException
* @throws OutOfSyncException
* @throws CompatibilityException
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.model.IR4EUIModelElement#createChildren(R4EReviewComponent)
*/
@Override
public IR4EUIModelElement createChildren(ReviewComponent aModelComponent) throws ResourceHandlingException,
OutOfSyncException, CompatibilityException {
final String user = R4EUIModelController.getReviewer();
R4EParticipant participant = null;
if (getParent().getParent().getParent().getParent() instanceof R4EUIReviewBasic) { // $codepro.audit.disable methodChainLength
participant = ((R4EUIReviewBasic) getParent().getParent().getParent().getParent()).getParticipant(user,
true); // $codepro.audit.disable methodChainLength
} else {
//Global anomaly
participant = ((R4EUIReviewBasic) getParent().getParent()).getParticipant(user, true);
}
final R4EComment comment = R4EUIModelController.FModelExt.createR4EComment(participant, fAnomaly);
final Long bookNum = R4EUIModelController.FResourceUpdater.checkOut(comment, R4EUIModelController.getReviewer());
comment.setDescription(((Comment) aModelComponent).getDescription());
R4EUIModelController.FResourceUpdater.checkIn(bookNum);
final R4EUIComment addedChild = new R4EUIComment(this, comment);
addChildren(addedChild);
return addedChild;
}
/**
* Method createComment.
*
* @param aRejectionComment
* - boolean
* @return boolean
*/
public boolean createComment(boolean aRejectionComment) {
//Get comment details from user
final ICommentInputDialog dialog = R4EUIDialogFactory.getInstance().getCommentInputDialog();
final IR4EUIModelElement commentParent = this;
final int[] result = new int[1]; //We need this to be able to pass the result value outside. This is safe as we are using SyncExec
Display.getDefault().syncExec(new Runnable() {
public void run() {
result[0] = dialog.open();
}
});
if (result[0] == Window.OK) {
final Job job = new Job(CREATE_COMMENT_MESSAGE) {
public String familyName = R4EUIConstants.R4E_UI_JOB_FAMILY;
@Override
public boolean belongsTo(Object family) {
return familyName.equals(family);
}
@Override
public IStatus run(IProgressMonitor monitor) {
try {
//Create comment model element
final R4EUIReviewBasic uiReview = R4EUIModelController.getActiveReview();
final R4EParticipant participant = uiReview.getParticipant(R4EUIModelController.getReviewer(),
true);
final R4EComment comment = R4EUIModelController.FModelExt.createR4EComment(participant,
fAnomaly);
final Long bookNum = R4EUIModelController.FResourceUpdater.checkOut(comment,
R4EUIModelController.getReviewer());
comment.setDescription(dialog.getCommentValue());
R4EUIModelController.FResourceUpdater.checkIn(bookNum);
//Create and set UI model element
final R4EUIComment uiComment = new R4EUIComment(commentParent, comment);
addChildren(uiComment);
R4EUIModelController.setJobInProgress(false);
UIUtils.setNavigatorViewFocus(uiComment, AbstractTreeViewer.ALL_LEVELS);
} catch (ResourceHandlingException e) {
UIUtils.displayResourceErrorDialog(e);
} catch (OutOfSyncException e) {
UIUtils.displaySyncErrorDialog(e);
}
monitor.done();
return Status.OK_STATUS;
}
};
job.setUser(true);
job.schedule();
} else {
if (aRejectionComment) {
return false;
}
}
return true;
}
/**
* Method removeChildren.
*
* @param aChildToRemove
* IR4EUIModelElement
* @param aFileRemove
* - also remove from file (hard remove)
* @throws ResourceHandlingException
* @throws OutOfSyncException
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.model.IR4EUIModelElement#removeChildren(IR4EUIModelElement)
*/
@Override
public void removeChildren(IR4EUIModelElement aChildToRemove, boolean aFileRemove)
throws ResourceHandlingException, OutOfSyncException {
final R4EUIComment removedElement = fComments.get(fComments.indexOf(aChildToRemove));
/* TODO uncomment when core model supports hard-removing of elements
if (aFileRemove) removedElement.getComment().remove());
else */
final R4EComment modelComment = removedElement.getComment();
final Long bookNum = R4EUIModelController.FResourceUpdater.checkOut(modelComment,
R4EUIModelController.getReviewer());
modelComment.setEnabled(false);
R4EUIModelController.FResourceUpdater.checkIn(bookNum);
//Remove element from UI if the show disabled element option is off
if (!(R4EUIPlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.P_SHOW_DISABLED))) {
fComments.remove(removedElement);
}
}
/**
* Method removeAllChildren.
*
* @param aFileRemove
* boolean
* @throws ResourceHandlingException
* @throws OutOfSyncException
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.model.IR4EUIModelElement#removeAllChildren(boolean)
*/
@Override
public void removeAllChildren(boolean aFileRemove) throws ResourceHandlingException, OutOfSyncException {
//Recursively remove all children
for (R4EUIComment comment : fComments) {
removeChildren(comment, aFileRemove);
}
}
/**
* Method restore.
*
* @throws CompatibilityException
* @throws OutOfSyncException
* @throws ResourceHandlingException
*/
@Override
public void restore() throws ResourceHandlingException, OutOfSyncException, CompatibilityException {
super.restore();
//Update inline markings (local anomalies only)
if (getParent().getParent() instanceof R4EUIFileContext) {
final R4EUIAnomalyBasic currentAnomaly = this;
Display.getDefault().syncExec(new Runnable() {
public void run() {
UIUtils.updateAnnotation(currentAnomaly, (R4EUIFileContext) getParent().getParent());
}
});
}
//Also restore any participant assigned to this element
for (String participant : fAnomaly.getAssignedTo()) {
- R4EUIModelController.getActiveReview().getParticipant(participant, true);
+ if (!(null == participant || participant.equals(""))) { //Filter out invalid participants
+ R4EUIModelController.getActiveReview().getParticipant(participant, true);
+ }
}
}
//Commands
/**
* Method isOpenEditorCmd.
*
* @return boolean
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.model.IR4EUIModelElement#isOpenEditorCmd()
*/
@Override
public boolean isOpenEditorCmd() {
if (!(getParent().getParent() instanceof R4EUIFileContext)) {
return false;
}
if (isEnabled() && null != R4EUIModelController.getActiveReview()
&& null != ((R4EUIFileContext) getParent().getParent()).getTargetFileVersion()) {
return true;
}
return false;
}
/**
* Method isCopyElementCmd.
*
* @return boolean
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.model.IR4EUIModelElement#isCopyElementCmd()
*/
@Override
public boolean isCopyElementCmd() {
if (isEnabled()
&& !isReadOnly()
&& null != R4EUIModelController.getActiveReview()
&& !(((R4EReviewState) R4EUIModelController.getActiveReview().getReview().getState()).getState().equals(R4EReviewPhase.R4E_REVIEW_PHASE_COMPLETED))
&& getParent().getParent() instanceof R4EUIFileContext) {
return true;
}
return false;
}
/**
* Method getCopyElementCmdName.
*
* @return String
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.model.IR4EUIModelElement#getCopyElementCmdName()
*/
@Override
public String getCopyElementCmdName() {
return COPY_ELEMENT_COMMAND_NAME;
}
/**
* Method getCopyElementCmdTooltip.
*
* @return String
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.model.IR4EUIModelElement#getCopyElementCmdTooltip()
*/
@Override
public String getCopyElementCmdTooltip() {
return COPY_ELEMENT_COMMAND_TOOLTIP;
}
/**
* Method isPasteElementCmd.
*
* @return boolean
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.model.IR4EUIModelElement#isPasteElementCmd()
*/
@Override
public boolean isPasteElementCmd() {
if (isEnabled()
&& !isReadOnly()
&& null != R4EUIModelController.getActiveReview()
&& !(((R4EReviewState) R4EUIModelController.getActiveReview().getReview().getState()).getState().equals(R4EReviewPhase.R4E_REVIEW_PHASE_COMPLETED))) {
//We can only paste if there is a least 1 Comment in the clipboard
Object element = null;
ISelection selection = LocalSelectionTransfer.getTransfer().getSelection();
if (selection instanceof IStructuredSelection) {
for (final Iterator<?> iterator = ((IStructuredSelection) selection).iterator(); iterator.hasNext();) {
element = iterator.next();
if (element instanceof R4EUIComment) {
return true;
}
}
}
}
return false;
}
/**
* Method getPasteElementCmdName.
*
* @return String
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.model.IR4EUIModelElement#getPasteElementCmdName()
*/
@Override
public String getPasteElementCmdName() {
return PASTE_ELEMENT_COMMAND_NAME;
}
/**
* Method getPasteElementCmdTooltip.
*
* @return String
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.model.IR4EUIModelElement#getPasteElementCmdTooltip()
*/
@Override
public String getPasteElementCmdTooltip() {
return PASTE_ELEMENT_COMMAND_TOOLTIP;
}
/**
* Method isAddChildElementCmd.
*
* @return boolean
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.model.IR4EUIModelElement#isNewChildElementCmd()
*/
@Override
public boolean isNewChildElementCmd() {
if (isEnabled()
&& !isReadOnly()
&& null != R4EUIModelController.getActiveReview()
&& !(((R4EReviewState) R4EUIModelController.getActiveReview().getReview().getState()).getState().equals(R4EReviewPhase.R4E_REVIEW_PHASE_COMPLETED))) {
return true;
}
return false;
}
/**
* Method getAddChildElementCmdName.
*
* @return String
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.model.IR4EUIModelElement#getNewChildElementCmdName()
*/
@Override
public String getNewChildElementCmdName() {
return NEW_CHILD_ELEMENT_COMMAND_NAME;
}
/**
* Method getAddChildElementCmdTooltip.
*
* @return String
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.model.IR4EUIModelElement#getNewChildElementCmdTooltip()
*/
@Override
public String getNewChildElementCmdTooltip() {
return NEW_CHILD_ELEMENT_COMMAND_TOOLTIP;
}
/**
* Method isRemoveElementCmd.
*
* @return boolean
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.model.IR4EUIModelElement#isRemoveElementCmd()
*/
@Override
public boolean isRemoveElementCmd() {
if (isEnabled()
&& !isReadOnly()
&& null != R4EUIModelController.getActiveReview()
&& !(((R4EReviewState) R4EUIModelController.getActiveReview().getReview().getState()).getState().equals(R4EReviewPhase.R4E_REVIEW_PHASE_COMPLETED))) {
return true;
}
return false;
}
/**
* Method getRemoveElementCmdName.
*
* @return String
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.model.IR4EUIModelElement#getRemoveElementCmdName()
*/
@Override
public String getRemoveElementCmdName() {
return REMOVE_ELEMENT_COMMAND_NAME;
}
/**
* Method getRemoveElementCmdTooltip.
*
* @return String
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.model.IR4EUIModelElement#getRemoveElementCmdTooltip()
*/
@Override
public String getRemoveElementCmdTooltip() {
return REMOVE_ELEMENT_COMMAND_TOOLTIP;
}
/**
* Method isRestoreElementCmd.
*
* @return boolean
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.model.IR4EUIModelElement#iisRestoreElementCmd()
*/
@Override
public boolean isRestoreElementCmd() {
if (!(getParent().getParent().isEnabled())) {
return false;
}
R4EReviewPhase phase = ((R4EReviewState) R4EUIModelController.getActiveReview().getReview().getState()).getState();
if (isEnabled() || isReadOnly() || phase.equals(R4EReviewPhase.R4E_REVIEW_PHASE_COMPLETED)
|| phase.equals(R4EReviewPhase.R4E_REVIEW_PHASE_REWORK)) {
return false;
}
return true;
}
/**
* Method getRestoreElementCmdName.
*
* @return String
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.model.IR4EUIModelElement#getRestoreElementCmdName()
*/
@Override
public String getRestoreElementCmdName() {
return RESTORE_ELEMENT_COMMAND_NAME;
}
/**
* Method getRestoreElementCmdTooltip.
*
* @return String
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.model.IR4EUIModelElement#getRestoreElementCmdTooltip()
*/
@Override
public String getRestoreElementCmdTooltip() {
return RESTORE_ELEMENT_COMMAND_TOOLTIP;
}
/**
* Method isSendEmailCmd.
*
* @return boolean
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.model.IR4EUIModelElement#isSendEmailCmd()
*/
@Override
public boolean isSendEmailCmd() {
if (isEnabled() && null != R4EUIModelController.getActiveReview()) {
return true;
}
return false;
}
/**
* Method isTitleEnabled.
*
* @return boolean
*/
public boolean isTitleEnabled() {
if (null != R4EUIModelController.getActiveReview()) {
if (null == fAnomaly.getRuleID() || fAnomaly.getRuleID().equals("")) {
return true;
}
}
return false;
}
/**
* Method isClassEnabled.
*
* @return boolean
*/
public boolean isClassEnabled() {
if (null != R4EUIModelController.getActiveReview()) {
if (null == fAnomaly.getRuleID() || fAnomaly.getRuleID().equals("")) {
return true;
}
}
return false;
}
/**
* Method isRankEnabled.
*
* @return boolean
*/
public boolean isRankEnabled() {
if (null != R4EUIModelController.getActiveReview()) {
if (null == fAnomaly.getRuleID() || fAnomaly.getRuleID().equals("")) {
return true;
}
}
return false;
}
/**
* Method isDueDateEnabled.
*
* @return boolean
*/
public boolean isDueDateEnabled() {
return true;
}
/**
* Method isTerminalState.
*
* @return boolean
*/
public boolean isTerminalState() {
return false;
}
/**
* Method isDueDatePassed.
*
* @return boolean
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.model.IR4EUIModelElement#isDueDatePassed()
*/
@Override
public boolean isDueDatePassed() {
if (isEnabled()) {
if (null != fAnomaly.getDueDate()) {
IR4EUIModelElement element = getParent().getParent().getParent().getParent();
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.add(Calendar.DAY_OF_YEAR, -1);
if (fAnomaly.getDueDate().before(cal.getTime())) {
if (!(element instanceof R4EUIReviewBasic)) {
//Assume global anomaly
element = getParent().getParent();
}
if (!((R4EReviewState) ((R4EUIReviewBasic) element).getReview().getState()).getState().equals(
R4EReviewPhase.R4E_REVIEW_PHASE_COMPLETED)) {
return true;
}
}
}
}
return false;
}
}
| true | false | null | null |
diff --git a/src/main/java/com/worldofzaar/service/CertainTableService.java b/src/main/java/com/worldofzaar/service/CertainTableService.java
index 4cb4779..aa74c95 100644
--- a/src/main/java/com/worldofzaar/service/CertainTableService.java
+++ b/src/main/java/com/worldofzaar/service/CertainTableService.java
@@ -1,125 +1,127 @@
package com.worldofzaar.service;
import com.worldofzaar.adapter.TablesAdapter;
import com.worldofzaar.dao.CertainTableDao;
import com.worldofzaar.dao.UserDao;
import com.worldofzaar.entity.CertainTable;
import com.worldofzaar.entity.User;
import com.worldofzaar.modelAttribute.ApiTable;
import com.worldofzaar.util.UserInformation;
import com.worldofzaar.util.WOZConsts;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: Дмитрий
* Date: 30.11.13
* Time: 9:47
* To change this template use File | Settings | File Templates.
*/
public class CertainTableService {
HashMap<Integer, CertainTable> tableMap = new HashMap<Integer, CertainTable>();
private int getMinLevel(int level) {
if (level >= 1 && level < 5)
return 1;
if (level >= 5 && level < 10)
return 5;
if (level >= 10 && level < 20)
return 10;
return 1;
}
private int getMaxLevel(int level) {
if (level >= 1 && level < 5)
return 4;
if (level >= 5 && level < 10)
return 9;
if (level >= 10 && level < 20)
return 19;
return 4;
}
public boolean getIn(ApiTable table, HttpServletRequest request) {
- if (!table.valid())
- return false;
UserInformation userInformation = new UserInformation(request);
CertainTableDao certainTableDao = new CertainTableDao();
+ table.setLevel(userInformation.getUser().getGameProfile().getLevel());
+ if (!table.valid())
+ return false;
+
List<CertainTable> tables = certainTableDao.getCertainTables(table.getSize(), table.getCost(),
getMinLevel(userInformation.getUser().getGameProfile().getLevel()),
getMaxLevel(userInformation.getUser().getGameProfile().getLevel()));
if (tables.size() == table.getSize())
return false;
else if (tables.size() < table.getSize()) {
return getIn(tables, table, userInformation);
}
return false;
}
public boolean getOut(HttpServletRequest request) {
UserInformation userInformation = new UserInformation(request);
CertainTableDao certainTableDao = new CertainTableDao();
return certainTableDao.deleteCertainTable(userInformation);
}
//Get in table if position is empty.
private boolean getIn(List<CertainTable> tables, ApiTable table, UserInformation userInformation) {
CardInDeckService cardInDeckService = new CardInDeckService();
int userCardsCount = cardInDeckService.getCountOfActiveDeckCards(userInformation);
if (userCardsCount != WOZConsts.MINIMUM_CARDS_COUNT)
return false;
if (tables.size() < table.getSize()) {
for (CertainTable ct : tables) {
tableMap.put(ct.getSeatPosition(), ct);
}
CertainTable ct = tableMap.get(table.getPosition());
if (ct != null) {
return false;
} else {
UserDao userDao = new UserDao();
User user = userDao.find(userInformation.getUserId());
CertainTable newCT = new CertainTable();
newCT.setSeatPosition(table.getPosition());
newCT.setTableCost(table.getCost());
newCT.setTableSize(table.getSize());
newCT.setUser(user);
newCT.setLevel(user.getGameProfile().getLevel());
CertainTableDao certainTableDao = new CertainTableDao();
certainTableDao.add(newCT);
//Create table if table full/
if (tables.size() + 1 == table.getSize()) {
tables = certainTableDao.getCertainTables(table.getSize(), table.getCost(), getMinLevel(table.getLevel()), getMaxLevel(table.getLevel()));
startTable(tables, userInformation);
}
return true;
}
}
return false;
}
private boolean startTable(List<CertainTable> tables, UserInformation userInformation) {
if (tables == null)
return false;
if (tables.get(0).getTableSize() != tables.size())
return false;
GameService gameService = new GameService();
gameService.createNewGame(tables);
return false;
}
//Get tables
public TablesAdapter getTables(int cost, HttpServletRequest request) {
UserInformation userInformation = new UserInformation(request);
CertainTableDao certainTableDao = new CertainTableDao();
List<CertainTable> tables = certainTableDao.getCertainTables(cost, getMinLevel(userInformation.getUser().getGameProfile().getLevel()),
getMaxLevel(userInformation.getUser().getGameProfile().getLevel()));
TablesAdapter tablesAdapter = new TablesAdapter(tables);
return tablesAdapter;
}
}
| false | false | null | null |
diff --git a/src/com/android/contacts/list/ContactListFilterController.java b/src/com/android/contacts/list/ContactListFilterController.java
index 051c9a074..8bcd48884 100644
--- a/src/com/android/contacts/list/ContactListFilterController.java
+++ b/src/com/android/contacts/list/ContactListFilterController.java
@@ -1,330 +1,330 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.contacts.list;
import com.android.contacts.R;
import android.app.Activity;
import android.app.LoaderManager;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.Context;
import android.content.Loader;
import android.content.SharedPreferences;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListPopupWindow;
import java.util.ArrayList;
import java.util.List;
/**
* Controls a list of {@link ContactListFilter}'s.
*/
public class ContactListFilterController
implements LoaderCallbacks<List<ContactListFilter>>, OnClickListener, OnItemClickListener {
public interface ContactListFilterListener {
void onContactListFiltersLoaded();
void onContactListFilterChanged();
void onContactListFilterCustomizationRequest();
}
private static final int MESSAGE_REFRESH_FILTERS = 0;
/**
* The delay before the contact filter list is refreshed. This is needed because
* during contact sync we will get lots of notifications in rapid succession. This
* delay will prevent the slowly changing list of filters from reloading too often.
*/
private static final int FILTER_SPINNER_REFRESH_DELAY_MILLIS = 5000;
private Context mContext;
private LoaderManager mLoaderManager;
private ContactListFilterListener mListener;
private ListPopupWindow mPopup;
private int mPopupWidth = -1;
private SparseArray<ContactListFilter> mFilters;
private ArrayList<ContactListFilter> mFilterList;
private int mNextFilterId = 1;
private ContactListFilterView mFilterView;
private FilterListAdapter mFilterListAdapter;
private ContactListFilter mFilter;
private boolean mFiltersLoaded;
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == MESSAGE_REFRESH_FILTERS) {
loadFilters();
}
}
};
public ContactListFilterController(Activity activity) {
mContext = activity;
mLoaderManager = activity.getLoaderManager();
}
public void setListener(ContactListFilterListener listener) {
mListener = listener;
}
public void setFilterSpinner(ContactListFilterView filterSpinner) {
mFilterView = filterSpinner;
mFilterView.setOnClickListener(this);
}
public ContactListFilter getFilter() {
return mFilter;
}
public List<ContactListFilter> getFilterList() {
return mFilterList;
}
public boolean isLoaded() {
return mFiltersLoaded;
}
public void startLoading() {
// Set the "ready" flag right away - we only want to start the loader once
mFiltersLoaded = false;
mFilter = ContactListFilter.restoreFromPreferences(getSharedPreferences());
loadFilters();
}
private SharedPreferences getSharedPreferences() {
return PreferenceManager.getDefaultSharedPreferences(mContext);
}
private void loadFilters() {
mLoaderManager.restartLoader(R.id.contact_list_filter_loader, null, this);
}
@Override
public ContactListFilterLoader onCreateLoader(int id, Bundle args) {
return new ContactListFilterLoader(mContext);
}
@Override
public void onLoadFinished(
Loader<List<ContactListFilter>> loader, List<ContactListFilter> filters) {
if (mFilters == null) {
mFilters = new SparseArray<ContactListFilter>(filters.size());
mFilterList = new ArrayList<ContactListFilter>();
} else {
mFilters.clear();
mFilterList.clear();
}
boolean filterValid = mFilter != null
&& (mFilter.filterType == ContactListFilter.FILTER_TYPE_ALL_ACCOUNTS
|| mFilter.filterType == ContactListFilter.FILTER_TYPE_CUSTOM
|| mFilter.filterType == ContactListFilter.FILTER_TYPE_STARRED);
int accountCount = 0;
int count = filters.size();
for (int index = 0; index < count; index++) {
if (filters.get(index).filterType == ContactListFilter.FILTER_TYPE_ACCOUNT) {
accountCount++;
}
}
if (accountCount > 1) {
mFilters.append(mNextFilterId++,
new ContactListFilter(ContactListFilter.FILTER_TYPE_ALL_ACCOUNTS));
mFilters.append(mNextFilterId++,
new ContactListFilter(ContactListFilter.FILTER_TYPE_STARRED));
mFilters.append(mNextFilterId++,
new ContactListFilter(ContactListFilter.FILTER_TYPE_CUSTOM));
}
for (int index = 0; index < count; index++) {
ContactListFilter filter = filters.get(index);
boolean firstAndOnly = accountCount == 1
&& filter.filterType == ContactListFilter.FILTER_TYPE_ACCOUNT;
// If we only have one account, don't show it as "account", instead show it as "all"
if (firstAndOnly) {
filter = new ContactListFilter(ContactListFilter.FILTER_TYPE_ALL_ACCOUNTS);
}
mFilters.append(mNextFilterId++, filter);
mFilterList.add(filter);
filterValid |= filter.equals(mFilter);
if (firstAndOnly) {
mFilters.append(mNextFilterId++,
new ContactListFilter(ContactListFilter.FILTER_TYPE_STARRED));
mFilters.append(mNextFilterId++,
new ContactListFilter(ContactListFilter.FILTER_TYPE_CUSTOM));
}
}
boolean filterChanged = false;
if (mFilter == null || !filterValid) {
filterChanged = mFilter != null;
mFilter = getDefaultFilter();
}
if (mFilterListAdapter == null) {
mFilterListAdapter = new FilterListAdapter();
} else {
mFilterListAdapter.notifyDataSetChanged();
}
if (filterChanged) {
mFiltersLoaded = true;
mListener.onContactListFilterChanged();
} else if (!mFiltersLoaded) {
mFiltersLoaded = true;
mListener.onContactListFiltersLoaded();
}
updateFilterView();
}
public void postDelayedRefresh() {
if (!mHandler.hasMessages(MESSAGE_REFRESH_FILTERS)) {
mHandler.sendEmptyMessageDelayed(
MESSAGE_REFRESH_FILTERS, FILTER_SPINNER_REFRESH_DELAY_MILLIS);
}
}
protected void setContactListFilter(int filterId) {
ContactListFilter filter;
if (filterId == ContactListFilter.FILTER_TYPE_ALL_ACCOUNTS) {
filter = new ContactListFilter(ContactListFilter.FILTER_TYPE_ALL_ACCOUNTS);
} else if (filterId == ContactListFilter.FILTER_TYPE_CUSTOM) {
filter = new ContactListFilter(ContactListFilter.FILTER_TYPE_CUSTOM);
} else if (filterId == ContactListFilter.FILTER_TYPE_STARRED) {
filter = new ContactListFilter(ContactListFilter.FILTER_TYPE_STARRED);
} else {
filter = mFilters.get(filterId);
if (filter == null) {
filter = getDefaultFilter();
}
}
if (!filter.equals(mFilter)) {
mFilter = filter;
ContactListFilter.storeToPreferences(getSharedPreferences(), mFilter);
updateFilterView();
mListener.onContactListFilterChanged();
}
}
@Override
public void onClick(View v) {
if (!mFiltersLoaded) {
return;
}
if (mPopupWidth == -1) {
TypedArray a = mContext.obtainStyledAttributes(null, R.styleable.ContactBrowser);
mPopupWidth = a.getDimensionPixelSize(
R.styleable.ContactBrowser_contact_filter_popup_width, -1);
a.recycle();
if (mPopupWidth == -1) {
mPopupWidth = mFilterView.getWidth();
}
}
mPopup = new ListPopupWindow(mContext, null);
mPopup.setWidth(mPopupWidth);
mPopup.setAdapter(mFilterListAdapter);
mPopup.setAnchorView(mFilterView);
mPopup.setOnItemClickListener(this);
mPopup.setModal(true);
mPopup.show();
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mPopup.dismiss();
if (mFilters.get((int) id).filterType == ContactListFilter.FILTER_TYPE_CUSTOM) {
mListener.onContactListFilterCustomizationRequest();
} else {
setContactListFilter((int) id);
}
}
public void selectCustomFilter() {
mFilter = new ContactListFilter(ContactListFilter.FILTER_TYPE_CUSTOM);
updateFilterView();
mListener.onContactListFilterChanged();
}
private ContactListFilter getDefaultFilter() {
- return mFilters.valueAt(0);
+ return mFilters.size() > 0 ? mFilters.valueAt(0) : null;
}
protected void updateFilterView() {
if (mFiltersLoaded) {
mFilterView.setContactListFilter(mFilter);
mFilterView.bindView(false);
}
}
private class FilterListAdapter extends BaseAdapter {
private LayoutInflater mLayoutInflater;
public FilterListAdapter() {
mLayoutInflater = LayoutInflater.from(mContext);
}
@Override
public int getCount() {
return mFilters.size();
}
@Override
public long getItemId(int position) {
return mFilters.keyAt(position);
}
@Override
public Object getItem(int position) {
return mFilters.valueAt(position);
}
public View getView(int position, View convertView, ViewGroup parent) {
ContactListFilterView view;
if (convertView != null) {
view = (ContactListFilterView) convertView;
} else {
view = (ContactListFilterView) mLayoutInflater.inflate(
R.layout.filter_spinner_item, parent, false);
}
view.setContactListFilter(mFilters.valueAt(position));
view.bindView(true);
return view;
}
}
}
diff --git a/src/com/android/contacts/list/ContactListFilterView.java b/src/com/android/contacts/list/ContactListFilterView.java
index 744de05f8..c9a04721a 100644
--- a/src/com/android/contacts/list/ContactListFilterView.java
+++ b/src/com/android/contacts/list/ContactListFilterView.java
@@ -1,132 +1,138 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.contacts.list;
import com.android.contacts.R;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* Contact list filter parameters.
*/
public class ContactListFilterView extends LinearLayout {
private ImageView mIcon;
private TextView mLabel;
private TextView mIndentedLabel;
private ContactListFilter mFilter;
public ContactListFilterView(Context context) {
super(context);
}
public ContactListFilterView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setContactListFilter(ContactListFilter filter) {
mFilter = filter;
}
public ContactListFilter getContactListFilter() {
return mFilter;
}
public void bindView(boolean dropdown) {
if (mLabel == null) {
mIcon = (ImageView) findViewById(R.id.icon);
mLabel = (TextView) findViewById(R.id.label);
mIndentedLabel = (TextView) findViewById(R.id.indented_label);
}
+ if (mFilter == null) {
+ mLabel.setText(R.string.contactsList);
+ mLabel.setVisibility(View.VISIBLE);
+ return;
+ }
+
switch (mFilter.filterType) {
case ContactListFilter.FILTER_TYPE_ALL_ACCOUNTS: {
if (mIcon != null) {
mIcon.setVisibility(View.VISIBLE);
mIcon.setImageResource(R.drawable.ic_contact_list_filter_all);
}
mLabel.setText(R.string.list_filter_all_accounts);
mLabel.setVisibility(View.VISIBLE);
if (dropdown) {
mIndentedLabel.setVisibility(View.GONE);
}
break;
}
case ContactListFilter.FILTER_TYPE_STARRED: {
if (mIcon != null) {
mIcon.setVisibility(View.VISIBLE);
mIcon.setImageResource(R.drawable.ic_contact_list_filter_starred);
}
mLabel.setText(R.string.list_filter_all_starred);
mLabel.setVisibility(View.VISIBLE);
if (dropdown) {
mIndentedLabel.setVisibility(View.GONE);
}
break;
}
case ContactListFilter.FILTER_TYPE_CUSTOM: {
if (mIcon != null) {
mIcon.setVisibility(View.VISIBLE);
mIcon.setImageResource(R.drawable.ic_contact_list_filter_custom);
}
mLabel.setText(dropdown
? R.string.list_filter_customize
: R.string.list_filter_custom);
mLabel.setVisibility(View.VISIBLE);
if (dropdown) {
mIndentedLabel.setVisibility(View.GONE);
}
break;
}
case ContactListFilter.FILTER_TYPE_ACCOUNT: {
if (mIcon != null) {
mIcon.setVisibility(View.VISIBLE);
if (mFilter.icon != null) {
mIcon.setImageDrawable(mFilter.icon);
} else {
mIcon.setImageResource(R.drawable.unknown_source);
}
}
mLabel.setText(mFilter.accountName);
mLabel.setVisibility(View.VISIBLE);
if (dropdown) {
mIndentedLabel.setVisibility(View.GONE);
}
break;
}
case ContactListFilter.FILTER_TYPE_GROUP: {
if (mIcon != null) {
mIcon.setVisibility(View.GONE);
}
if (dropdown) {
mLabel.setVisibility(View.GONE);
mIndentedLabel.setText(mFilter.title);
mIndentedLabel.setVisibility(View.VISIBLE);
} else {
mLabel.setText(mFilter.title);
mLabel.setVisibility(View.VISIBLE);
}
break;
}
}
}
}
| false | false | null | null |
diff --git a/archetype-creator/src/main/java/org/apache/maven/archetype/creator/FilesetArchetypeCreator.java b/archetype-creator/src/main/java/org/apache/maven/archetype/creator/FilesetArchetypeCreator.java
index d6fe69e4..5aa82295 100644
--- a/archetype-creator/src/main/java/org/apache/maven/archetype/creator/FilesetArchetypeCreator.java
+++ b/archetype-creator/src/main/java/org/apache/maven/archetype/creator/FilesetArchetypeCreator.java
@@ -1,1648 +1,1649 @@
/*
* 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.maven.archetype.creator;
import java.io.FileNotFoundException;
import org.apache.maven.archetype.common.ArchetypeConfiguration;
import org.apache.maven.archetype.common.ArchetypeDefinition;
import org.apache.maven.archetype.common.ArchetypeFactory;
import org.apache.maven.archetype.common.ArchetypeFilesResolver;
import org.apache.maven.archetype.common.ArchetypePropertiesManager;
import org.apache.maven.archetype.common.Constants;
import org.apache.maven.archetype.common.FileCharsetDetector;
import org.apache.maven.archetype.common.ListScanner;
import org.apache.maven.archetype.common.PathUtils;
import org.apache.maven.archetype.common.PomManager;
import org.apache.maven.archetype.creator.olddescriptor.OldArchetypeDescriptor;
import org.apache.maven.archetype.creator.olddescriptor.OldArchetypeDescriptorXpp3Writer;
import org.apache.maven.archetype.exception.ArchetypeNotConfigured;
import org.apache.maven.archetype.exception.ArchetypeNotDefined;
import org.apache.maven.archetype.exception.TemplateCreationException;
import org.apache.maven.archetype.metadata.ArchetypeDescriptor;
import org.apache.maven.archetype.metadata.FileSet;
import org.apache.maven.archetype.metadata.ModuleDescriptor;
import org.apache.maven.archetype.metadata.RequiredProperty;
import org.apache.maven.archetype.metadata.io.xpp3.ArchetypeDescriptorXpp3Writer;
import org.apache.maven.model.Build;
import org.apache.maven.model.Extension;
import org.apache.maven.model.Model;
import org.apache.maven.model.Plugin;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.logging.AbstractLogEnabled;
import org.codehaus.plexus.util.DirectoryScanner;
import org.codehaus.plexus.util.FileUtils;
import org.codehaus.plexus.util.StringUtils;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.apache.maven.archetype.common.ArchetypeRegistryManager;
import org.apache.maven.archetype.registry.ArchetypeRegistry;
/**
* @plexus.component role-hint="fileset"
*/
public class FilesetArchetypeCreator
extends AbstractLogEnabled
implements ArchetypeCreator
{
/**
* @plexus.requirement
*/
private ArchetypeFactory archetypeFactory;
/**
* @plexus.requirement
*/
private ArchetypeFilesResolver archetypeFilesResolver;
/**
* @plexus.requirement
*/
private ArchetypePropertiesManager archetypePropertiesManager;
/**
* @plexus.requirement
*/
private PomManager pomManager;
/**
* @plexus.requirement
*/
private ArchetypeRegistryManager archetypeRegistryManager;
public void createArchetype (
MavenProject project,
File propertyFile,
List languages,
List filtereds,
String defaultEncoding,
boolean ignoreReplica,
File archetypeRegistryFile
)
throws IOException,
ArchetypeNotDefined,
ArchetypeNotConfigured,
TemplateCreationException,
XmlPullParserException
{
Properties properties = initialiseArchetypeProperties ( propertyFile );
ArchetypeDefinition archetypeDefinition =
archetypeFactory.createArchetypeDefinition ( properties );
if ( !archetypeDefinition.isDefined () )
{
throw new ArchetypeNotDefined ( "The archetype is not defined" );
}
ArchetypeConfiguration archetypeConfiguration =
archetypeFactory.createArchetypeConfiguration ( archetypeDefinition, properties );
if ( !archetypeConfiguration.isConfigured () )
{
throw new ArchetypeNotConfigured ( "The archetype is not configured" );
}
File basedir = project.getBasedir ();
File generatedSourcesDirectory =
FileUtils.resolveFile ( basedir, getGeneratedSourcesDirectory () );
generatedSourcesDirectory.mkdirs ();
getLogger ().debug ( "Creating archetype in " + generatedSourcesDirectory );
Model model = new Model ();
model.setModelVersion ( "4.0.0" );
model.setGroupId ( archetypeDefinition.getGroupId () );
model.setArtifactId ( archetypeDefinition.getArtifactId () );
model.setVersion ( archetypeDefinition.getVersion () );
model.setPackaging ( "maven-archetype" );
+ model.setName( archetypeDefinition.getArtifactId () );
Build build = new Build ();
model.setBuild ( build );
Extension extension = new Extension ();
extension.setGroupId ( "org.apache.maven.archetype" );
extension.setArtifactId ( "archetypeng-packaging" );
extension.setVersion ( "1.0-SNAPSHOT" );
model.getBuild ().addExtension ( extension );
Plugin plugin = new Plugin ();
plugin.setGroupId ( "org.apache.maven.plugins" );
plugin.setArtifactId ( "maven-archetypeng-plugin" );
plugin.setVersion ( "1.0-SNAPSHOT" );
plugin.setExtensions ( true );
model.getBuild ().addPlugin ( plugin );
getLogger ().debug ( "Creating archetype's pom" );
File archetypePomFile = FileUtils.resolveFile ( basedir, getArchetypePom () );
archetypePomFile.getParentFile ().mkdirs ();
pomManager.writePom ( model, archetypePomFile );
File archetypeResourcesDirectory =
FileUtils.resolveFile ( generatedSourcesDirectory, getTemplateOutputDirectory () );
archetypeResourcesDirectory.mkdirs ();
File archetypeFilesDirectory =
FileUtils.resolveFile ( archetypeResourcesDirectory, Constants.ARCHETYPE_RESOURCES );
archetypeFilesDirectory.mkdirs ();
getLogger ().debug ( "Archetype's files output directory " + archetypeFilesDirectory );
File replicaMainDirectory =
FileUtils.resolveFile (
generatedSourcesDirectory,
getReplicaOutputDirectory () + File.separator
+ archetypeDefinition.getArtifactId ()
);
if ( !ignoreReplica )
{
replicaMainDirectory.mkdirs ();
}
File replicaFilesDirectory = FileUtils.resolveFile ( replicaMainDirectory, "reference" );
if ( !ignoreReplica )
{
replicaFilesDirectory.mkdirs ();
}
File archetypeDescriptorFile =
FileUtils.resolveFile ( archetypeResourcesDirectory, Constants.ARCHETYPE_DESCRIPTOR );
archetypeDescriptorFile.getParentFile ().mkdirs ();
ArchetypeDescriptor archetypeDescriptor = new ArchetypeDescriptor ();
archetypeDescriptor.setId ( archetypeDefinition.getArtifactId () );
getLogger ().debug (
"Starting archetype's descriptor " + archetypeDefinition.getArtifactId ()
);
archetypeDescriptor.setPartial ( false );
addRequiredProperties ( archetypeDescriptor, properties );
// TODO ensure reversedproperties contains NO dotted properties
Properties reverseProperties = getRequiredProperties ( archetypeDescriptor, properties );
reverseProperties.remove ( Constants.GROUP_ID );
// TODO ensure pomReversedProperties contains NO dotted properties
Properties pomReversedProperties =
getRequiredProperties ( archetypeDescriptor, properties );
pomReversedProperties.remove ( Constants.PACKAGE );
String packageName = archetypeConfiguration.getProperty ( Constants.PACKAGE );
Model pom =
pomManager.readPom ( FileUtils.resolveFile ( basedir, Constants.ARCHETYPE_POM ) );
List fileNames = resolveFileNames ( pom, basedir );
getLogger ().debug ( "Scanned for files " + fileNames.size () );
Iterator names = fileNames.iterator ();
while ( names.hasNext () )
{
getLogger ().debug ( "- " + names.next ().toString () );
}
List filesets =
resolveFileSets ( packageName, fileNames, languages, filtereds, defaultEncoding );
getLogger ().debug ( "Resolved filesets for " + archetypeDescriptor.getId () );
archetypeDescriptor.setFileSets ( filesets );
createArchetypeFiles (
reverseProperties,
filesets,
packageName,
basedir,
archetypeFilesDirectory,
defaultEncoding
);
getLogger ().debug ( "Created files for " + archetypeDescriptor.getId () );
if ( !ignoreReplica )
{
createReplicaFiles ( filesets, basedir, replicaFilesDirectory );
getLogger ().debug ( "Created replica files for " + archetypeDescriptor.getId () );
FileUtils.copyFile (
propertyFile,
new File ( replicaMainDirectory, "archetype.properties" )
);
new File ( replicaMainDirectory, "goal.txt" ).createNewFile ();
}
setParentArtifactId (
reverseProperties,
pomReversedProperties,
archetypeConfiguration.getProperty ( Constants.ARTIFACT_ID )
);
Iterator modules = pom.getModules ().iterator ();
while ( modules.hasNext () )
{
String moduleId = (String) modules.next ();
setArtifactId ( reverseProperties, pomReversedProperties, moduleId );
getLogger ().debug ( "Creating module " + moduleId );
ModuleDescriptor moduleDescriptor =
createModule (
reverseProperties,
pomReversedProperties,
moduleId,
packageName,
FileUtils.resolveFile ( basedir, moduleId ),
FileUtils.resolveFile ( archetypeFilesDirectory, moduleId ),
FileUtils.resolveFile ( replicaFilesDirectory, moduleId ),
languages,
filtereds,
defaultEncoding,
ignoreReplica
);
archetypeDescriptor.addModule ( moduleDescriptor );
getLogger ().debug (
"Added module " + moduleDescriptor.getId () + " in "
+ archetypeDescriptor.getId ()
);
}
restoreParentArtifactId ( reverseProperties, pomReversedProperties, null );
restoreArtifactId (
reverseProperties,
pomReversedProperties,
archetypeConfiguration.getProperty ( Constants.ARTIFACT_ID )
);
createArchetypePom (
pom,
archetypeFilesDirectory,
pomReversedProperties,
FileUtils.resolveFile ( basedir, Constants.ARCHETYPE_POM )
);
getLogger ().debug ( "Created Archetype " + archetypeDescriptor.getId () + " pom" );
ArchetypeDescriptorXpp3Writer writer = new ArchetypeDescriptorXpp3Writer ();
writer.write ( new FileWriter ( archetypeDescriptorFile ), archetypeDescriptor );
getLogger ().debug ( "Archetype " + archetypeDescriptor.getId () + " descriptor written" );
OldArchetypeDescriptor oldDescriptor =
convertToOldDescriptor ( archetypeDescriptor.getId (), packageName, basedir );
File oldDescriptorFile =
FileUtils.resolveFile (
archetypeResourcesDirectory,
Constants.OLD_ARCHETYPE_DESCRIPTOR
);
archetypeDescriptorFile.getParentFile ().mkdirs ();
writeOldDescriptor ( oldDescriptor, oldDescriptorFile );
getLogger ().debug (
"Archetype " + archetypeDescriptor.getId () + " old descriptor written"
);
- archetypeRegistryManager.addGroup ( archetypeConfiguration.getProperty ( Constants.GROUP_ID ), archetypeRegistryFile );
+ archetypeRegistryManager.addGroup ( archetypeConfiguration.getGroupId(), archetypeRegistryFile );
}
private void addRequiredProperties (
ArchetypeDescriptor archetypeDescriptor,
Properties properties
)
{
Properties requiredProperties = new Properties ();
requiredProperties.putAll ( properties );
requiredProperties.remove ( Constants.ARCHETYPE_GROUP_ID );
requiredProperties.remove ( Constants.ARCHETYPE_ARTIFACT_ID );
requiredProperties.remove ( Constants.ARCHETYPE_VERSION );
requiredProperties.remove ( Constants.GROUP_ID );
requiredProperties.remove ( Constants.ARTIFACT_ID );
requiredProperties.remove ( Constants.VERSION );
requiredProperties.remove ( Constants.PACKAGE );
Iterator propertiesIterator = requiredProperties.keySet ().iterator ();
while ( propertiesIterator.hasNext () )
{
String propertyKey = (String) propertiesIterator.next ();
RequiredProperty requiredProperty = new RequiredProperty ();
requiredProperty.setKey ( propertyKey );
requiredProperty.setDefaultValue ( requiredProperties.getProperty ( propertyKey ) );
archetypeDescriptor.addRequiredProperty ( requiredProperty );
getLogger ().debug (
"Adding requiredProperty " + propertyKey + "="
+ requiredProperties.getProperty ( propertyKey ) + " to archetype's descriptor"
);
}
}
private String getArchetypePom ()
{
return getGeneratedSourcesDirectory () + File.separator + Constants.ARCHETYPE_POM;
}
private void setArtifactId (
Properties reverseProperties,
Properties pomReversedProperties,
String artifactId
)
{
reverseProperties.setProperty ( Constants.ARTIFACT_ID, artifactId );
pomReversedProperties.setProperty ( Constants.ARTIFACT_ID, artifactId );
}
private List concatenateToList ( List toConcatenate, String with )
{
List result = new ArrayList ( toConcatenate.size () );
Iterator iterator = toConcatenate.iterator ();
while ( iterator.hasNext () )
{
String concatenate = (String) iterator.next ();
result.add ( ( ( with.length () > 0 ) ? ( with + "/" + concatenate ) : concatenate ) );
}
return result;
}
private OldArchetypeDescriptor convertToOldDescriptor (
String id,
String packageName,
File basedir
)
throws IOException
{
getLogger ().debug ( "Resolving OldArchetypeDescriptor files in " + basedir );
String excludes = "pom.xml,archetype.properties*,**/target/**";
Iterator defaultExcludes = Arrays.asList ( ListScanner.DEFAULTEXCLUDES ).iterator ();
while ( defaultExcludes.hasNext () )
{
excludes += "," + (String) defaultExcludes.next () + "/**";
}
List fileNames = FileUtils.getFileNames ( basedir, "**", excludes, false );
getLogger ().debug ( "Resolved " + fileNames.size () + " files" );
String packageAsDirectory = StringUtils.replace ( packageName, '.', '/' ) + "/";
List sources = archetypeFilesResolver.findSourcesMainFiles ( fileNames, "java/**" );
fileNames.removeAll ( sources );
sources = removePackage ( sources, packageAsDirectory );
List testSources = archetypeFilesResolver.findSourcesTestFiles ( fileNames, "java/**" );
fileNames.removeAll ( testSources );
testSources = removePackage ( testSources, packageAsDirectory );
List resources = archetypeFilesResolver.findResourcesMainFiles ( fileNames, "java/**" );
fileNames.removeAll ( resources );
List testResources = archetypeFilesResolver.findResourcesTestFiles ( fileNames, "java/**" );
fileNames.removeAll ( testResources );
List siteResources = archetypeFilesResolver.findSiteFiles ( fileNames, null );
fileNames.removeAll ( siteResources );
resources.addAll ( fileNames );
OldArchetypeDescriptor descriptor = new OldArchetypeDescriptor ();
descriptor.setId ( id );
descriptor.setSources ( sources );
descriptor.setTestSources ( testSources );
descriptor.setResources ( resources );
descriptor.setTestResources ( testResources );
descriptor.setSiteResources ( siteResources );
return descriptor;
}
private void copyFiles (
File basedir,
File archetypeFilesDirectory,
String directory,
List fileSetResources,
boolean packaged,
String packageName
)
throws IOException
{
String packageAsDirectory = StringUtils.replace ( packageName, ".", File.separator );
getLogger ().debug (
"Package as Directory: Package:" + packageName + "->" + packageAsDirectory
);
Iterator iterator = fileSetResources.iterator ();
while ( iterator.hasNext () )
{
String inputFileName = (String) iterator.next ();
String outputFileName =
packaged
? StringUtils.replace ( inputFileName, packageAsDirectory + File.separator, "" )
: inputFileName;
getLogger ().debug ( "InputFileName:" + inputFileName );
getLogger ().debug ( "OutputFileName:" + outputFileName );
File outputFile = new File ( archetypeFilesDirectory, outputFileName );
File inputFile = new File ( basedir, inputFileName );
outputFile.getParentFile ().mkdirs ();
FileUtils.copyFile ( inputFile, outputFile );
} // end while
}
private void copyPom ( File basedir, File replicaFilesDirectory )
throws IOException
{
FileUtils.copyFileToDirectory (
new File ( basedir, Constants.ARCHETYPE_POM ),
replicaFilesDirectory
);
}
private void createArchetypeFiles (
Properties reverseProperties,
List fileSets,
String packageName,
File basedir,
File archetypeFilesDirectory,
String defaultEncoding
)
throws IOException
{
getLogger ().debug (
"Creating Archetype/Module files from " + basedir + " to " + archetypeFilesDirectory
);
Iterator iterator = fileSets.iterator ();
while ( iterator.hasNext () )
{
FileSet fileSet = (FileSet) iterator.next ();
DirectoryScanner scanner = new DirectoryScanner ();
scanner.setBasedir ( basedir );
scanner.setIncludes (
(String[]) concatenateToList ( fileSet.getIncludes (), fileSet.getDirectory () )
.toArray ( new String[fileSet.getIncludes ().size ()] )
);
scanner.setExcludes (
(String[]) fileSet.getExcludes ().toArray (
new String[fileSet.getExcludes ().size ()]
)
);
scanner.addDefaultExcludes ();
getLogger ().debug ( "Using fileset " + fileSet );
scanner.scan ();
List fileSetResources = Arrays.asList ( scanner.getIncludedFiles () );
getLogger ().debug ( "Scanned " + fileSetResources.size () + " resources" );
if ( fileSet.isFiltered () )
{
processFileSet (
basedir,
archetypeFilesDirectory,
fileSet.getDirectory (),
fileSetResources,
fileSet.isPackaged (),
packageName,
reverseProperties,
defaultEncoding
);
getLogger ().debug ( "Processed " + fileSet.getDirectory () + " files" );
}
else
{
copyFiles (
basedir,
archetypeFilesDirectory,
fileSet.getDirectory (),
fileSetResources,
fileSet.isPackaged (),
packageName
);
getLogger ().debug ( "Copied " + fileSet.getDirectory () + " files" );
}
} // end while
}
private void createArchetypePom (
Model pom,
File archetypeFilesDirectory,
Properties pomReversedProperties,
File initialPomFile
)
throws IOException
{
// pom.setParent ( null );
// pom.setModules ( null );
// pom.setGroupId ( "${" + Constants.GROUP_ID + "}" );
// pom.setArtifactId ( "${" + Constants.ARTIFACT_ID + "}" );
// pom.setVersion ( "${" + Constants.VERSION + "}" );
File outputFile =
FileUtils.resolveFile ( archetypeFilesDirectory, Constants.ARCHETYPE_POM );
File inputFile =
FileUtils.resolveFile ( archetypeFilesDirectory, Constants.ARCHETYPE_POM + ".tmp" );
FileUtils.copyFile ( initialPomFile, inputFile );
// pomManager.writePom ( pom, inputFile );
String initialcontent = FileUtils.fileRead ( inputFile );
String content = getReversedContent ( initialcontent, pomReversedProperties );
outputFile.getParentFile ().mkdirs ();
FileUtils.fileWrite ( outputFile.getAbsolutePath (), content );
inputFile.delete ();
}
private FileSet createFileSet (
final List excludes,
final boolean packaged,
final boolean filtered,
final String group,
final List includes,
String defaultEncoding
)
{
FileSet fileSet = new FileSet ();
fileSet.setDirectory ( group );
fileSet.setPackaged ( packaged );
fileSet.setFiltered ( filtered );
fileSet.setIncludes ( includes );
fileSet.setExcludes ( excludes );
fileSet.setEncoding ( defaultEncoding );
getLogger ().debug ( "Created Fileset " + fileSet );
return fileSet;
}
private List createFileSets (
List files,
int level,
boolean packaged,
String packageName,
boolean filtered,
String defaultEncoding
)
{
List fileSets = new ArrayList ();
if ( !files.isEmpty () )
{
getLogger ().debug (
"Creating filesets" + ( packaged ? ( " packaged (" + packageName + ")" ) : "" )
+ ( filtered ? " filtered" : "" ) + " at level " + level
);
if ( level == 0 )
{
List includes = new ArrayList ();
List excludes = new ArrayList ();
Iterator filesIterator = files.iterator ();
while ( filesIterator.hasNext () )
{
String file = (String) filesIterator.next ();
includes.add ( file );
}
if ( !includes.isEmpty () )
{
fileSets.add (
createFileSet (
excludes,
packaged,
filtered,
"",
includes,
defaultEncoding
)
);
}
}
else
{
Map groups = getGroupsMap ( files, level );
Iterator groupIterator = groups.keySet ().iterator ();
while ( groupIterator.hasNext () )
{
String group = (String) groupIterator.next ();
getLogger ().debug ( "Creating filesets for group " + group );
if ( !packaged )
{
fileSets.add (
getUnpackagedFileSet (
filtered,
group,
(List) groups.get ( group ),
defaultEncoding
)
);
}
else
{
fileSets.addAll (
getPackagedFileSets (
filtered,
group,
(List) groups.get ( group ),
packageName,
defaultEncoding
)
);
}
}
} // end if
getLogger ().debug ( "Resolved fileSets " + fileSets );
} // end if
return fileSets;
}
private ModuleDescriptor createModule (
Properties reverseProperties,
Properties pomReversedProperties,
String moduleId,
String packageName,
File basedir,
File archetypeFilesDirectory,
File replicaFilesDirectory,
List languages,
List filtereds,
String defaultEncoding,
boolean ignoreReplica
)
throws IOException, XmlPullParserException
{
ModuleDescriptor archetypeDescriptor = new ModuleDescriptor ();
archetypeDescriptor.setId ( moduleId );
getLogger ().debug ( "Starting module's descriptor " + moduleId );
archetypeFilesDirectory.mkdirs ();
getLogger ().debug ( "Module's files output directory " + archetypeFilesDirectory );
Model pom =
pomManager.readPom ( FileUtils.resolveFile ( basedir, Constants.ARCHETYPE_POM ) );
List fileNames = resolveFileNames ( pom, basedir );
List filesets =
resolveFileSets ( packageName, fileNames, languages, filtereds, defaultEncoding );
getLogger ().debug ( "Resolved filesets for module " + archetypeDescriptor.getId () );
archetypeDescriptor.setFileSets ( filesets );
createArchetypeFiles (
reverseProperties,
filesets,
packageName,
basedir,
archetypeFilesDirectory,
defaultEncoding
);
getLogger ().debug ( "Created files for module " + archetypeDescriptor.getId () );
if ( !ignoreReplica )
{
createReplicaFiles ( filesets, basedir, replicaFilesDirectory );
getLogger ().debug ( "Created replica files for " + archetypeDescriptor.getId () );
}
String parentArtifactId = reverseProperties.getProperty ( Constants.PARENT_ARTIFACT_ID );
setParentArtifactId ( reverseProperties, pomReversedProperties, moduleId );
Iterator modules = pom.getModules ().iterator ();
while ( modules.hasNext () )
{
String subModuleId = (String) modules.next ();
setArtifactId ( reverseProperties, pomReversedProperties, subModuleId );
getLogger ().debug ( "Creating module " + subModuleId );
ModuleDescriptor moduleDescriptor =
createModule (
reverseProperties,
pomReversedProperties,
subModuleId,
packageName,
FileUtils.resolveFile ( basedir, subModuleId ),
FileUtils.resolveFile ( archetypeFilesDirectory, subModuleId ),
FileUtils.resolveFile ( replicaFilesDirectory, subModuleId ),
languages,
filtereds,
defaultEncoding,
ignoreReplica
);
archetypeDescriptor.addModule ( moduleDescriptor );
getLogger ().debug (
"Added module " + moduleDescriptor.getId () + " in "
+ archetypeDescriptor.getId ()
);
}
restoreParentArtifactId ( reverseProperties, pomReversedProperties, parentArtifactId );
restoreArtifactId ( reverseProperties, pomReversedProperties, moduleId );
createModulePom (
pom,
archetypeFilesDirectory,
pomReversedProperties,
FileUtils.resolveFile ( basedir, Constants.ARCHETYPE_POM )
);
getLogger ().debug ( "Created Module " + archetypeDescriptor.getId () + " pom" );
return archetypeDescriptor;
}
private void createModulePom (
Model pom,
File archetypeFilesDirectory,
Properties pomReversedProperties,
File initialPomFile
)
throws IOException
{
// pom.setParent ( null );
// pom.setModules ( null );
// pom.setGroupId ( "${" + Constants.GROUP_ID + "}" );
// pom.setArtifactId ( "${" + Constants.ARTIFACT_ID + "}" );
// pom.setVersion ( "${" + Constants.VERSION + "}" );
File outputFile =
FileUtils.resolveFile ( archetypeFilesDirectory, Constants.ARCHETYPE_POM );
File inputFile =
FileUtils.resolveFile ( archetypeFilesDirectory, Constants.ARCHETYPE_POM + ".tmp" );
FileUtils.copyFile ( initialPomFile, inputFile );
// pomManager.writePom ( pom, inputFile );
String initialcontent = FileUtils.fileRead ( inputFile );
String content = getReversedContent ( initialcontent, pomReversedProperties );
outputFile.getParentFile ().mkdirs ();
FileUtils.fileWrite ( outputFile.getAbsolutePath (), content );
inputFile.delete ();
}
private void createReplicaFiles ( List filesets, File basedir, File replicaFilesDirectory )
throws IOException
{
getLogger ().debug (
"Creating Archetype/Module replica files from " + basedir + " to "
+ replicaFilesDirectory
);
copyPom ( basedir, replicaFilesDirectory );
Iterator iterator = filesets.iterator ();
while ( iterator.hasNext () )
{
FileSet fileset = (FileSet) iterator.next ();
DirectoryScanner scanner = new DirectoryScanner ();
scanner.setBasedir ( basedir );
scanner.setIncludes (
(String[]) concatenateToList ( fileset.getIncludes (), fileset.getDirectory () )
.toArray ( new String[fileset.getIncludes ().size ()] )
);
scanner.setExcludes (
(String[]) fileset.getExcludes ().toArray (
new String[fileset.getExcludes ().size ()]
)
);
scanner.addDefaultExcludes ();
getLogger ().debug ( "Using fileset " + fileset );
scanner.scan ();
List fileSetResources = Arrays.asList ( scanner.getIncludedFiles () );
copyFiles (
basedir,
replicaFilesDirectory,
fileset.getDirectory (),
fileSetResources,
false,
null
);
getLogger ().debug ( "Copied " + fileset.getDirectory () + " files" );
}
}
private Set getExtensions ( List files )
{
Set extensions = new HashSet ();
Iterator filesIterator = files.iterator ();
while ( filesIterator.hasNext () )
{
String file = (String) filesIterator.next ();
extensions.add ( FileUtils.extension ( file ) );
}
return extensions;
}
private String getGeneratedSourcesDirectory ()
{
return "target" + File.separator + "generated-sources" + File.separator + "archetypeng";
}
private Map getGroupsMap ( final List files, final int level )
{
Map groups = new HashMap ();
Iterator fileIterator = files.iterator ();
while ( fileIterator.hasNext () )
{
String file = (String) fileIterator.next ();
String directory = PathUtils.getDirectory ( file, level );
// make all groups have unix style
directory = StringUtils.replace ( directory, File.separator, "/" );
if ( !groups.containsKey ( directory ) )
{
groups.put ( directory, new ArrayList () );
}
List group = (List) groups.get ( directory );
String innerPath = file.substring ( directory.length () + 1 );
// make all groups have unix style
innerPath = StringUtils.replace ( innerPath, File.separator, "/" );
group.add ( innerPath );
}
getLogger ().debug (
"Sorted " + groups.size () + " groups in " + files.size () + " files"
);
getLogger ().debug ( "Sorted Files:" + files );
return groups;
}
private Properties initialiseArchetypeProperties ( File propertyFile )
throws IOException
{
Properties properties = new Properties ();
archetypePropertiesManager.readProperties ( properties, propertyFile );
return properties;
}
private FileSet getPackagedFileSet (
final boolean filtered,
final Set packagedExtensions,
final String group,
final Set unpackagedExtensions,
final List unpackagedFiles,
String defaultEncoding
)
{
List includes = new ArrayList ();
List excludes = new ArrayList ();
Iterator extensionsIterator = packagedExtensions.iterator ();
while ( extensionsIterator.hasNext () )
{
String extension = (String) extensionsIterator.next ();
includes.add ( "**/*." + extension );
if ( unpackagedExtensions.contains ( extension ) )
{
excludes.addAll (
archetypeFilesResolver.getFilesWithExtension ( unpackagedFiles, extension )
);
}
}
FileSet fileset =
createFileSet ( excludes, true, filtered, group, includes, defaultEncoding );
return fileset;
}
private List getPackagedFileSets (
final boolean filtered,
final String group,
final List groupFiles,
final String packageName,
String defaultEncoding
)
{
String packageAsDir = StringUtils.replace ( packageName, ".", "/" );
List packagedFileSets = new ArrayList ();
List packagedFiles = archetypeFilesResolver.getPackagedFiles ( groupFiles, packageAsDir );
getLogger ().debug ( "Found packaged Files:" + packagedFiles );
List unpackagedFiles =
archetypeFilesResolver.getUnpackagedFiles ( groupFiles, packageAsDir );
getLogger ().debug ( "Found unpackaged Files:" + unpackagedFiles );
Set packagedExtensions = getExtensions ( packagedFiles );
getLogger ().debug ( "Found packaged extensions " + packagedExtensions );
Set unpackagedExtensions = getExtensions ( unpackagedFiles );
if ( !packagedExtensions.isEmpty () )
{
packagedFileSets.add (
getPackagedFileSet (
filtered,
packagedExtensions,
group,
unpackagedExtensions,
unpackagedFiles,
defaultEncoding
)
);
}
if ( !unpackagedExtensions.isEmpty () )
{
getLogger ().debug ( "Found unpackaged extensions " + unpackagedExtensions );
packagedFileSets.add (
getUnpackagedFileSet (
filtered,
unpackagedExtensions,
unpackagedFiles,
group,
packagedExtensions,
defaultEncoding
)
);
}
return packagedFileSets;
}
private void setParentArtifactId (
Properties reverseProperties,
Properties pomReversedProperties,
String parentArtifactId
)
{
reverseProperties.setProperty ( Constants.PARENT_ARTIFACT_ID, parentArtifactId );
pomReversedProperties.setProperty ( Constants.PARENT_ARTIFACT_ID, parentArtifactId );
}
private void processFileSet (
File basedir,
File archetypeFilesDirectory,
String directory,
List fileSetResources,
boolean packaged,
String packageName,
Properties reverseProperties,
String defaultEncoding
)
throws IOException
{
String packageAsDirectory = StringUtils.replace ( packageName, ".", File.separator );
getLogger ().debug (
"Package as Directory: Package:" + packageName + "->" + packageAsDirectory
);
Iterator iterator = fileSetResources.iterator ();
while ( iterator.hasNext () )
{
String inputFileName = (String) iterator.next ();
String outputFileName =
packaged
? StringUtils.replace ( inputFileName, packageAsDirectory + File.separator, "" )
: inputFileName;
getLogger ().debug ( "InputFileName:" + inputFileName );
getLogger ().debug ( "OutputFileName:" + outputFileName );
File outputFile = new File ( archetypeFilesDirectory, outputFileName );
File inputFile = new File ( basedir, inputFileName );
FileCharsetDetector detector = new FileCharsetDetector ( inputFile );
String fileEncoding = detector.isFound () ? detector.getCharset () : defaultEncoding;
String initialcontent =
org.apache.commons.io.IOUtils.toString (
new FileInputStream ( inputFile ),
fileEncoding
);
// String initialcontent = FileUtils.fileRead ( inputFile );
String content = getReversedContent ( initialcontent, reverseProperties );
outputFile.getParentFile ().mkdirs ();
org.apache.commons.io.IOUtils.write (
content,
new FileOutputStream ( outputFile ),
fileEncoding
);
// FileUtils.fileWrite ( outputFile.getAbsolutePath (), content );
} // end while
}
private List removePackage ( List sources, String packageAsDirectory )
{
if ( sources == null )
{
return null;
}
List unpackagedSources = new ArrayList ( sources.size () );
Iterator sourcesIterator = sources.iterator ();
while ( sourcesIterator.hasNext () )
{
String source = (String) sourcesIterator.next ();
String unpackagedSource = StringUtils.replace ( source, packageAsDirectory, "" );
unpackagedSources.add ( unpackagedSource );
}
return unpackagedSources;
}
private String getReplicaOutputDirectory ()
{
return
Constants.SRC + File.separator + Constants.TEST + File.separator + Constants.RESOURCES
+ File.separator + "projects";
}
private Properties getRequiredProperties (
ArchetypeDescriptor archetypeDescriptor,
Properties properties
)
{
Properties reversedProperties = new Properties ();
reversedProperties.putAll ( properties );
reversedProperties.remove ( Constants.ARCHETYPE_GROUP_ID );
reversedProperties.remove ( Constants.ARCHETYPE_ARTIFACT_ID );
reversedProperties.remove ( Constants.ARCHETYPE_VERSION );
// reversedProperties.remove ( Constants.GROUP_ID );
// reversedProperties.remove ( Constants.ARTIFACT_ID );
// reversedProperties.remove ( Constants.VERSION );
return reversedProperties;
}
private List resolveFileNames ( final Model pom, final File basedir )
throws IOException
{
getLogger ().debug ( "Resolving files for " + pom.getId () + " in " + basedir );
Iterator modules = pom.getModules ().iterator ();
String excludes = "pom.xml*,archetype.properties*,target/**,";
while ( modules.hasNext () )
{
excludes += "," + (String) modules.next () + "/**";
}
Iterator defaultExcludes = Arrays.asList ( ListScanner.DEFAULTEXCLUDES ).iterator ();
while ( defaultExcludes.hasNext () )
{
excludes += "," + (String) defaultExcludes.next () + "/**";
}
excludes = PathUtils.convertPathForOS ( excludes );
List fileNames = FileUtils.getFileNames ( basedir, "**", excludes, false );
getLogger ().debug ( "Resolved " + fileNames.size () + " files" );
getLogger ().debug ( "Resolved Files:" + fileNames );
return fileNames;
}
private List resolveFileSets (
String packageName,
List fileNames,
List languages,
List filtereds,
String defaultEncoding
)
{
List resolvedFileSets = new ArrayList ();
getLogger ().debug (
"Resolving filesets with package=" + packageName + ", languages=" + languages
+ " and extentions=" + filtereds
);
List files = new ArrayList ( fileNames );
String languageIncludes = "";
Iterator languagesIterator = languages.iterator ();
while ( languagesIterator.hasNext () )
{
String language = (String) languagesIterator.next ();
languageIncludes +=
( ( languageIncludes.length () == 0 ) ? "" : "," ) + language + "/**";
}
getLogger ().debug ( "Using languages includes " + languageIncludes );
String filteredIncludes = "";
Iterator filteredsIterator = filtereds.iterator ();
while ( filteredsIterator.hasNext () )
{
String filtered = (String) filteredsIterator.next ();
filteredIncludes +=
( ( filteredIncludes.length () == 0 ) ? "" : "," ) + "**/"
+ ( filtered.startsWith ( "." ) ? "" : "*." ) + filtered;
}
getLogger ().debug ( "Using filtered includes " + filteredIncludes );
/*sourcesMainFiles*/
List sourcesMainFiles =
archetypeFilesResolver.findSourcesMainFiles ( files, languageIncludes );
if ( !sourcesMainFiles.isEmpty () )
{
files.removeAll ( sourcesMainFiles );
List filteredFiles =
archetypeFilesResolver.getFilteredFiles ( sourcesMainFiles, filteredIncludes );
sourcesMainFiles.removeAll ( filteredFiles );
List unfilteredFiles = sourcesMainFiles;
if ( !filteredFiles.isEmpty () )
{
resolvedFileSets.addAll (
createFileSets ( filteredFiles, 3, true, packageName, true, defaultEncoding )
);
}
if ( !unfilteredFiles.isEmpty () )
{
resolvedFileSets.addAll (
createFileSets ( unfilteredFiles, 3, true, packageName, false, defaultEncoding )
);
}
}
/*resourcesMainFiles*/
List resourcesMainFiles =
archetypeFilesResolver.findResourcesMainFiles ( files, languageIncludes );
if ( !resourcesMainFiles.isEmpty () )
{
files.removeAll ( resourcesMainFiles );
List filteredFiles =
archetypeFilesResolver.getFilteredFiles ( resourcesMainFiles, filteredIncludes );
resourcesMainFiles.removeAll ( filteredFiles );
List unfilteredFiles = resourcesMainFiles;
if ( !filteredFiles.isEmpty () )
{
resolvedFileSets.addAll (
createFileSets ( filteredFiles, 3, false, packageName, true, defaultEncoding )
);
}
if ( !unfilteredFiles.isEmpty () )
{
resolvedFileSets.addAll (
createFileSets (
unfilteredFiles,
3,
false,
packageName,
false,
defaultEncoding
)
);
}
}
/*sourcesTestFiles*/
List sourcesTestFiles =
archetypeFilesResolver.findSourcesTestFiles ( files, languageIncludes );
if ( !sourcesTestFiles.isEmpty () )
{
files.removeAll ( sourcesTestFiles );
List filteredFiles =
archetypeFilesResolver.getFilteredFiles ( sourcesTestFiles, filteredIncludes );
sourcesTestFiles.removeAll ( filteredFiles );
List unfilteredFiles = sourcesTestFiles;
if ( !filteredFiles.isEmpty () )
{
resolvedFileSets.addAll (
createFileSets ( filteredFiles, 3, true, packageName, true, defaultEncoding )
);
}
if ( !unfilteredFiles.isEmpty () )
{
resolvedFileSets.addAll (
createFileSets ( unfilteredFiles, 3, true, packageName, false, defaultEncoding )
);
}
}
/*ressourcesTestFiles*/
List resourcesTestFiles =
archetypeFilesResolver.findResourcesTestFiles ( files, languageIncludes );
if ( !resourcesTestFiles.isEmpty () )
{
files.removeAll ( resourcesTestFiles );
List filteredFiles =
archetypeFilesResolver.getFilteredFiles ( resourcesTestFiles, filteredIncludes );
resourcesTestFiles.removeAll ( filteredFiles );
List unfilteredFiles = resourcesTestFiles;
if ( !filteredFiles.isEmpty () )
{
resolvedFileSets.addAll (
createFileSets ( filteredFiles, 3, false, packageName, true, defaultEncoding )
);
}
if ( !unfilteredFiles.isEmpty () )
{
resolvedFileSets.addAll (
createFileSets (
unfilteredFiles,
3,
false,
packageName,
false,
defaultEncoding
)
);
}
}
/*siteFiles*/
List siteFiles = archetypeFilesResolver.findSiteFiles ( files, languageIncludes );
if ( !siteFiles.isEmpty () )
{
files.removeAll ( siteFiles );
List filteredFiles =
archetypeFilesResolver.getFilteredFiles ( siteFiles, filteredIncludes );
siteFiles.removeAll ( filteredFiles );
List unfilteredFiles = siteFiles;
if ( !filteredFiles.isEmpty () )
{
resolvedFileSets.addAll (
createFileSets ( filteredFiles, 2, false, packageName, true, defaultEncoding )
);
}
if ( !unfilteredFiles.isEmpty () )
{
resolvedFileSets.addAll (
createFileSets (
unfilteredFiles,
2,
false,
packageName,
false,
defaultEncoding
)
);
}
}
/*thirdLevelSourcesfiles*/
List thirdLevelSourcesfiles =
archetypeFilesResolver.findOtherSources ( 3, files, languageIncludes );
if ( !thirdLevelSourcesfiles.isEmpty () )
{
files.removeAll ( thirdLevelSourcesfiles );
List filteredFiles =
archetypeFilesResolver.getFilteredFiles (
thirdLevelSourcesfiles,
filteredIncludes
);
thirdLevelSourcesfiles.removeAll ( filteredFiles );
List unfilteredFiles = thirdLevelSourcesfiles;
if ( !filteredFiles.isEmpty () )
{
resolvedFileSets.addAll (
createFileSets ( filteredFiles, 3, true, packageName, true, defaultEncoding )
);
}
if ( !unfilteredFiles.isEmpty () )
{
resolvedFileSets.addAll (
createFileSets ( unfilteredFiles, 3, true, packageName, false, defaultEncoding )
);
}
/*thirdLevelResourcesfiles*/
List thirdLevelResourcesfiles =
archetypeFilesResolver.findOtherResources (
3,
files,
thirdLevelSourcesfiles,
languageIncludes
);
if ( !thirdLevelResourcesfiles.isEmpty () )
{
files.removeAll ( thirdLevelResourcesfiles );
filteredFiles =
archetypeFilesResolver.getFilteredFiles (
thirdLevelResourcesfiles,
filteredIncludes
);
thirdLevelResourcesfiles.removeAll ( filteredFiles );
unfilteredFiles = thirdLevelResourcesfiles;
if ( !filteredFiles.isEmpty () )
{
resolvedFileSets.addAll (
createFileSets (
filteredFiles,
3,
false,
packageName,
true,
defaultEncoding
)
);
}
if ( !unfilteredFiles.isEmpty () )
{
resolvedFileSets.addAll (
createFileSets (
unfilteredFiles,
3,
false,
packageName,
false,
defaultEncoding
)
);
}
}
} // end if
/*secondLevelSourcesfiles*/
List secondLevelSourcesfiles =
archetypeFilesResolver.findOtherSources ( 2, files, languageIncludes );
if ( !secondLevelSourcesfiles.isEmpty () )
{
files.removeAll ( secondLevelSourcesfiles );
List filteredFiles =
archetypeFilesResolver.getFilteredFiles (
secondLevelSourcesfiles,
filteredIncludes
);
secondLevelSourcesfiles.removeAll ( filteredFiles );
List unfilteredFiles = secondLevelSourcesfiles;
if ( !filteredFiles.isEmpty () )
{
resolvedFileSets.addAll (
createFileSets ( filteredFiles, 2, true, packageName, true, defaultEncoding )
);
}
if ( !unfilteredFiles.isEmpty () )
{
resolvedFileSets.addAll (
createFileSets ( unfilteredFiles, 2, true, packageName, false, defaultEncoding )
);
}
}
/*secondLevelResourcesfiles*/
List secondLevelResourcesfiles =
archetypeFilesResolver.findOtherResources ( 2, files, languageIncludes );
if ( !secondLevelResourcesfiles.isEmpty () )
{
files.removeAll ( secondLevelResourcesfiles );
List filteredFiles =
archetypeFilesResolver.getFilteredFiles (
secondLevelResourcesfiles,
filteredIncludes
);
secondLevelResourcesfiles.removeAll ( filteredFiles );
List unfilteredFiles = secondLevelResourcesfiles;
if ( !filteredFiles.isEmpty () )
{
resolvedFileSets.addAll (
createFileSets ( filteredFiles, 2, false, packageName, true, defaultEncoding )
);
}
if ( !unfilteredFiles.isEmpty () )
{
resolvedFileSets.addAll (
createFileSets (
unfilteredFiles,
2,
false,
packageName,
false,
defaultEncoding
)
);
}
}
/*rootResourcesfiles*/
List rootResourcesfiles =
archetypeFilesResolver.findOtherResources ( 0, files, languageIncludes );
if ( !rootResourcesfiles.isEmpty () )
{
files.removeAll ( rootResourcesfiles );
List filteredFiles =
archetypeFilesResolver.getFilteredFiles ( rootResourcesfiles, filteredIncludes );
rootResourcesfiles.removeAll ( filteredFiles );
List unfilteredFiles = rootResourcesfiles;
if ( !filteredFiles.isEmpty () )
{
resolvedFileSets.addAll (
createFileSets ( filteredFiles, 0, false, packageName, true, defaultEncoding )
);
}
if ( !unfilteredFiles.isEmpty () )
{
resolvedFileSets.addAll (
createFileSets (
unfilteredFiles,
0,
false,
packageName,
false,
defaultEncoding
)
);
}
}
/**/
if ( !files.isEmpty () )
{
getLogger ().info ( "Ignored files: " + files );
}
return resolvedFileSets;
}
private void restoreArtifactId (
Properties reverseProperties,
Properties pomReversedProperties,
String artifactId
)
{
if ( StringUtils.isEmpty ( artifactId ) )
{
reverseProperties.remove ( Constants.ARTIFACT_ID );
pomReversedProperties.remove ( Constants.ARTIFACT_ID );
}
else
{
reverseProperties.setProperty ( Constants.ARTIFACT_ID, artifactId );
pomReversedProperties.setProperty ( Constants.ARTIFACT_ID, artifactId );
}
}
private void restoreParentArtifactId (
Properties reverseProperties,
Properties pomReversedProperties,
String parentArtifactId
)
{
if ( StringUtils.isEmpty ( parentArtifactId ) )
{
reverseProperties.remove ( Constants.PARENT_ARTIFACT_ID );
pomReversedProperties.remove ( Constants.PARENT_ARTIFACT_ID );
}
else
{
reverseProperties.setProperty ( Constants.PARENT_ARTIFACT_ID, parentArtifactId );
pomReversedProperties.setProperty ( Constants.PARENT_ARTIFACT_ID, parentArtifactId );
}
}
private String getReversedContent ( String content, final Properties properties )
{
String result = content;
Iterator propertyIterator = properties.keySet ().iterator ();
while ( propertyIterator.hasNext () )
{
String propertyKey = (String) propertyIterator.next ();
result =
StringUtils.replace (
result,
properties.getProperty ( propertyKey ),
"${" + propertyKey + "}"
);
}
return result;
}
private String getTemplateOutputDirectory ()
{
return
Constants.SRC + File.separator + Constants.MAIN + File.separator + Constants.RESOURCES;
}
private FileSet getUnpackagedFileSet (
final boolean filtered,
final String group,
final List groupFiles,
String defaultEncoding
)
{
Set extensions = getExtensions ( groupFiles );
List includes = new ArrayList ();
List excludes = new ArrayList ();
Iterator extensionsIterator = extensions.iterator ();
while ( extensionsIterator.hasNext () )
{
String extension = (String) extensionsIterator.next ();
includes.add ( "**/*." + extension );
}
return createFileSet ( excludes, false, filtered, group, includes, defaultEncoding );
}
private FileSet getUnpackagedFileSet (
final boolean filtered,
final Set unpackagedExtensions,
final List unpackagedFiles,
final String group,
final Set packagedExtensions,
String defaultEncoding
)
{
List includes = new ArrayList ();
List excludes = new ArrayList ();
Iterator extensionsIterator = unpackagedExtensions.iterator ();
while ( extensionsIterator.hasNext () )
{
String extension = (String) extensionsIterator.next ();
if ( packagedExtensions.contains ( extension ) )
{
includes.addAll (
archetypeFilesResolver.getFilesWithExtension ( unpackagedFiles, extension )
);
}
else
{
includes.add ( "**/*." + extension );
}
}
return createFileSet ( excludes, false, filtered, group, includes, defaultEncoding );
}
private void writeOldDescriptor ( OldArchetypeDescriptor oldDescriptor, File oldDescriptorFile )
throws IOException
{
OldArchetypeDescriptorXpp3Writer writer = new OldArchetypeDescriptorXpp3Writer ();
writer.write ( new FileWriter ( oldDescriptorFile ), oldDescriptor );
}
}
diff --git a/archetype-plugin/src/main/java/org/apache/maven/archetype/mojos/AddArchetypeMetadataMojo.java b/archetype-plugin/src/main/java/org/apache/maven/archetype/mojos/AddArchetypeMetadataMojo.java
index b59d7791..70018fcb 100644
--- a/archetype-plugin/src/main/java/org/apache/maven/archetype/mojos/AddArchetypeMetadataMojo.java
+++ b/archetype-plugin/src/main/java/org/apache/maven/archetype/mojos/AddArchetypeMetadataMojo.java
@@ -1,111 +1,111 @@
/*
* 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.maven.archetype.mojos;
/*
* 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.
*/
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.repository.metadata.ArtifactRepositoryMetadata;
import org.apache.maven.artifact.repository.metadata.GroupRepositoryMetadata;
import org.apache.maven.artifact.repository.metadata.Versioning;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
//import org.apache.maven.plugin.descriptor.PluginDescriptor;
import org.apache.maven.project.MavenProject;
/**
* Inject any plugin-specific artifact metadata to the project's artifact, for subsequent
* installation and deployment. The first use-case for this is to add the LATEST metadata (which is
* plugin-specific) for shipping alongside the plugin's artifact.
*
* @phase package
* @goal add-archetype-metadata
*/
public class AddArchetypeMetadataMojo
extends AbstractMojo
{
/**
* The prefix for the plugin goal.
*
* @parameter
*/
private String goalPrefix;
/**
* The project artifact, which should have the LATEST metadata added to it.
*
* @parameter expression="${project}"
* @required
* @readonly
*/
private MavenProject project;
public void execute ()
throws MojoExecutionException
{
Artifact projectArtifact = project.getArtifact ();
Versioning versioning = new Versioning ();
versioning.setLatest ( projectArtifact.getVersion () );
versioning.updateTimestamp ();
ArtifactRepositoryMetadata metadata =
new ArtifactRepositoryMetadata ( projectArtifact, versioning );
projectArtifact.addMetadata ( metadata );
GroupRepositoryMetadata groupMetadata =
new GroupRepositoryMetadata ( project.getGroupId () );
groupMetadata.addPluginMapping (
getGoalPrefix (),
project.getArtifactId (),
project.getName ()
);
projectArtifact.addMetadata ( groupMetadata );
}
private String getGoalPrefix ()
{
if ( goalPrefix == null )
{
-// goalPrefix = PluginDescriptor.getGoalPrefixFromArtifactId( project.getArtifactId() );
- goalPrefix = "archetypeng";
+// goalPrefix = PluginDescriptor.getGoalPrefixFromArtifactId( project.getArtifactId () );
+ goalPrefix = project.getArtifactId ();
}
return goalPrefix;
}
}
| false | false | null | null |
diff --git a/src/uk/co/jasonfry/android/tools/ui/SwipeView.java b/src/uk/co/jasonfry/android/tools/ui/SwipeView.java
index e0fbfd3..6e2b7fc 100644
--- a/src/uk/co/jasonfry/android/tools/ui/SwipeView.java
+++ b/src/uk/co/jasonfry/android/tools/ui/SwipeView.java
@@ -1,589 +1,588 @@
/*
* Copyright (C) 2011 Jason Fry
*
* 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.
*/
/**
* @author Jason Fry - jasonfry.co.uk
* @version 1.1.1
*
*/
package uk.co.jasonfry.android.tools.ui;
import uk.co.jasonfry.android.tools.ui.PageControl.OnPageControlClickListener;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
public class SwipeView extends HorizontalScrollView
{
private static int DEFAULT_SWIPE_THRESHOLD = 60;
private LinearLayout mLinearLayout;
private Context mContext;
private int SCREEN_WIDTH;
private int mMotionStartX;
private int mMotionStartY;
private boolean mMostlyScrollingInX = false;
private boolean mMostlyScrollingInY = false;
private boolean mJustInterceptedAndIgnored = false;
private boolean mSendingDummyMotionEvent = false;
private int mDistanceX;
private int mPreviousDirection;
private int mCurrentPage = 0;
private int mPageWidth = 0;
private boolean mFirstMotionEvent = true;
private OnPageChangedListener mOnPageChangedListener = null;
private SwipeOnTouchListener mSwipeOnTouchListener;
private View.OnTouchListener mOnTouchListener;
private PageControl mPageControl = null;
/**
* {@inheritDoc}
*/
public SwipeView(Context context)
{
super(context);
mContext = context;
initSwipeView();
}
/**
* {@inheritDoc}
*/
public SwipeView(Context context, AttributeSet attrs)
{
super(context, attrs);
mContext = context;
initSwipeView();
}
/**
* {@inheritDoc}
*/
public SwipeView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs,defStyle);
mContext = context;
initSwipeView();
}
private void initSwipeView()
{
Log.i("uk.co.jasonfry.android.tools.ui.SwipeView","Initialising SwipeView");
mLinearLayout = new LinearLayout(mContext);
mLinearLayout.setOrientation(LinearLayout.HORIZONTAL);
super.addView(mLinearLayout, -1, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
setSmoothScrollingEnabled(true);
setHorizontalFadingEdgeEnabled(false);
setHorizontalScrollBarEnabled(false);
Display display = ((WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
SCREEN_WIDTH = (int) (display.getWidth());
mPageWidth = SCREEN_WIDTH;
mCurrentPage = 0;
mSwipeOnTouchListener = new SwipeOnTouchListener();
super.setOnTouchListener(mSwipeOnTouchListener);
}
/**
* {@inheritDoc}
*/
@Override
public boolean onTrackballEvent(MotionEvent event)
{
return true;
}
/**
* {@inheritDoc}
*/
@Override
public void addView(View child)
{
this.addView(child,-1);
}
/**
* {@inheritDoc}
*/
@Override
public void addView (View child, int index)
{
ViewGroup.LayoutParams params;
if(child.getLayoutParams()==null)
{
params = new LayoutParams(mPageWidth, LayoutParams.FILL_PARENT);
}
else
{
params = child.getLayoutParams();
params.width = mPageWidth;
}
this.addView(child, index, params);
}
/**
* {@inheritDoc}
*/
@Override
public void addView (View child, ViewGroup.LayoutParams params)
{
params.width = mPageWidth;
this.addView (child, -1, params);
}
/**
* {@inheritDoc}
*/
@Override
public void addView (View child, int index, ViewGroup.LayoutParams params)
{
requestLayout();
invalidate();
mLinearLayout.addView(child, index, params);
}
/**
* {@inheritDoc}
*/
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b)
{
super.onLayout(changed, l, t, r, b);
if(changed)
{
scrollToPage(mCurrentPage);
}
}
/**
* {@inheritDoc}
*/
@Override
public void setOnTouchListener(View.OnTouchListener onTouchListener)
{
mOnTouchListener = onTouchListener;
}
/**
* Get the View object that contains all the children of this SwipeView. The same as calling getChildAt(0)
* A SwipeView behaves slightly differently from a normal ViewGroup, all the children of a SwipeView
* sit within a LinearLayout, which then sits within the SwipeView object.
*
* @return linearLayout The View object that contains all the children of this view
*/
public LinearLayout getChildContainer()
{
return mLinearLayout;
}
/**
* Get the swiping threshold distance to make the screens change
*
* @return swipeThreshold The minimum distance the finger should move to allow the screens to change
*/
public int getSwipeThreshold()
{
return DEFAULT_SWIPE_THRESHOLD;
}
/**
* Set the swiping threshold distance to make the screens change
*
* @param swipeThreshold The minimum distance the finger should move to allow the screens to change
*/
public void setSwipeThreshold(int swipeThreshold)
{
DEFAULT_SWIPE_THRESHOLD = swipeThreshold;
}
/**
* Get the current page the SwipeView is on
*
* @return The current page the SwipeView is on
*/
public int getCurrentPage()
{
return mCurrentPage;
}
/**
* Return the number of pages in this SwipeView
*
* @return Returns the number of pages in this SwipeView
*/
public int getPageCount()
{
return mLinearLayout.getChildCount();
}
/**
* Go directly to the specified page
*
* @param page The page to scroll to
*/
public void scrollToPage(int page)
{
scrollToPage(page,false);
}
/**
* Animate a scroll to the specified page
*
* @param page The page to animate to
*/
public void smoothScrollToPage(int page)
{
scrollToPage(page,true);
}
private void scrollToPage(int page, boolean smooth)
{
int oldPage = mCurrentPage;
if(page>=getPageCount() && getPageCount()>0)
{
page--;
}
else if(page<0)
{
page=0;
}
if(smooth)
{
smoothScrollTo(page*mPageWidth,0);
}
else
{
scrollTo(page*mPageWidth,0);
}
mCurrentPage = page;
if(mOnPageChangedListener!=null && oldPage!=page)
{
mOnPageChangedListener.onPageChanged(oldPage, page);
}
if(mPageControl!=null && oldPage!=page)
{
mPageControl.setCurrentPage(page);
}
}
/**
* Set the width of each page. This function returns an integer that should be added to the left margin of
* the first child and the right margin of the last child. This enables all the children to appear to be
* central
*
* @param pageWidth The width you wish to assign for each page
* @return An integer to add to the left margin of the first child and the right margin of the last child
*/
public int setPageWidth(int pageWidth)
{
mPageWidth = pageWidth;
return (SCREEN_WIDTH - mPageWidth)/2;
}
/**
* Set the width of each page by using the layout parameters of a child. Call this function before you add
* the child to the SwipeView to maintain the child's size. This function returns an integer that should
* be added to the left margin of the first child and the right margin of the last child. This enables all
* the children to appear to be central
*
* @param childLayoutParams A child view that you have added / will add to the SwipeView
* @return An integer to add to the left margin of the first child and the right margin of the last child
*/
public int calculatePageSize(MarginLayoutParams childLayoutParams)
{
return setPageWidth(childLayoutParams.leftMargin + childLayoutParams.width + childLayoutParams.rightMargin);
}
/**
* Return the current width of each page
*
* @return Returns the width of each page
*/
public int getPageWidth()
{
return mPageWidth;
}
/**
* Assign a PageControl object to this SwipeView. Call after adding all the children
*
* @param pageControl The PageControl object to assign
*/
public void setPageControl(PageControl pageControl)
{
mPageControl = pageControl;
pageControl.setPageCount(getPageCount());
pageControl.setCurrentPage(mCurrentPage);
pageControl.setOnPageControlClickListener(new OnPageControlClickListener()
{
public void goForwards()
{
smoothScrollToPage(mCurrentPage+1);
}
public void goBackwards()
{
smoothScrollToPage(mCurrentPage-1);
}
});
}
/**
* Return the current PageControl object
*
* @return Returns the current PageControl object
*/
public PageControl getPageControl()
{
return mPageControl;
}
/**
* Implement this listener to listen for page change events
*
* @author Jason Fry - jasonfry.co.uk
*
*/
public interface OnPageChangedListener
{
/**
* Event for when a page changes
*
* @param oldPage The page the view was on previously
* @param newPage The page the view has moved to
*/
public abstract void onPageChanged(int oldPage, int newPage);
}
/**
* Set the current OnPageChangedListsner
*
* @param onPageChangedListener The OnPageChangedListener object
*/
public void setOnPageChangedListener(OnPageChangedListener onPageChangedListener)
{
mOnPageChangedListener = onPageChangedListener;
}
/**
* Get the current OnPageChangeListsner
*
* @return The current OnPageChangedListener
*/
public OnPageChangedListener getOnPageChangedListener()
{
return mOnPageChangedListener;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev)
{
boolean result = super.onInterceptTouchEvent(ev);
if(ev.getAction() == MotionEvent.ACTION_DOWN)
{
mMotionStartX = (int) ev.getX();
mMotionStartY = (int) ev.getY();
- }
- else if(ev.getAction() == MotionEvent.ACTION_UP)
- {
- mMostlyScrollingInX = false;
- mMostlyScrollingInY = false;
-
+ if(!mJustInterceptedAndIgnored)
+ {
+ mMostlyScrollingInX = false;
+ mMostlyScrollingInY = false;
+ }
}
else if(ev.getAction()==MotionEvent.ACTION_MOVE)
{
detectMostlyScrollingDirection(ev);
}
if(mMostlyScrollingInY)
{
return false;
}
if(mMostlyScrollingInX)
{
mJustInterceptedAndIgnored = true;
return true;
}
return result;
}
private void detectMostlyScrollingDirection(MotionEvent ev)
{
if(!mMostlyScrollingInX && !mMostlyScrollingInY) //if we dont know which direction we're going yet
{
float xDistance = Math.abs(mMotionStartX - ev.getX());
float yDistance = Math.abs(mMotionStartY - ev.getY());
if(yDistance>xDistance+5)
{
mMostlyScrollingInY = true;
}
else if(xDistance>yDistance+5)
{
mMostlyScrollingInX = true;
}
}
}
private class SwipeOnTouchListener implements View.OnTouchListener
{
public boolean onTouch(View v, MotionEvent event)
{
if(mOnTouchListener!=null && !mJustInterceptedAndIgnored || mOnTouchListener!=null && mSendingDummyMotionEvent) //send on touch event to onTouchListener set by an application implementing a SwipeView and setting their own onTouchListener
{
if(mOnTouchListener.onTouch(v, event))
{
return true;
}
}
if(mSendingDummyMotionEvent)//if sending the fake action down event (to do with vertical scrolling within this horizontalscrollview) then just ignore it
{
mSendingDummyMotionEvent = false;
return false;
}
switch(event.getAction())
{
case MotionEvent.ACTION_DOWN :
mMotionStartX = (int) event.getX();
mMotionStartY = (int) event.getY();
mFirstMotionEvent = false;
return false;
case MotionEvent.ACTION_MOVE :
int newDistance = mMotionStartX - (int) event.getX();
int newDirection;
if(newDistance<0) //backwards
{
newDirection = (mDistanceX+4 <= newDistance) ? 1 : -1; //the distance +4 is to allow for jitter
}
else //forwards
{
newDirection = (mDistanceX-4 <= newDistance) ? 1 : -1; //the distance -4 is to allow for jitter
}
if(newDirection != mPreviousDirection && !mFirstMotionEvent)//changed direction, so reset start point
{
mMotionStartX = (int) event.getX();
mDistanceX = mMotionStartX - (int) event.getX();
}
else
{
mDistanceX = newDistance;
}
mPreviousDirection = newDirection; //backwards -1, forwards is 1,
if(mJustInterceptedAndIgnored)//if the intercept picked it up first, we need to give the horizontalscrollview ontouch an action down to enable it to scroll and follow your finger
{
mSendingDummyMotionEvent = true;
dispatchTouchEvent(MotionEvent.obtain(event.getDownTime(), event.getEventTime(), MotionEvent.ACTION_DOWN, mMotionStartX, mMotionStartY, event.getPressure(), event.getSize(), event.getMetaState(), event.getXPrecision(), event.getYPrecision(), event.getDeviceId(), event.getEdgeFlags()));
mJustInterceptedAndIgnored = false;
return true;
}
return false;
case MotionEvent.ACTION_UP :
float fingerUpPosition = getScrollX();
float numberOfPages = mLinearLayout.getMeasuredWidth() / mPageWidth;
float fingerUpPage = fingerUpPosition/mPageWidth;
float edgePosition = 0;
if(mPreviousDirection == 1) //forwards
{
if(mDistanceX > DEFAULT_SWIPE_THRESHOLD)//if over then go forwards
{
if(mCurrentPage<(numberOfPages-1))//if not at the end of the pages, you don't want to try and advance into nothing!
{
edgePosition = (int)(fingerUpPage+1)*mPageWidth;
}
else
{
edgePosition = (int)(fingerUpPage)*mPageWidth;
}
}
else //return to start position
{
if(Math.round(fingerUpPage)==numberOfPages-1)//if at the end
{
//need to correct for when user starts to scroll into
//nothing then pulls it back a bit, this becomes a
//kind of forwards scroll instead
edgePosition = (int)(fingerUpPage+1)*mPageWidth;
}
else //carry on as normal
{
edgePosition = mCurrentPage*mPageWidth;
}
}
}
else //backwards
{
if(mDistanceX < -DEFAULT_SWIPE_THRESHOLD)//go backwards
{
edgePosition = (int)(fingerUpPage)*mPageWidth;
}
else //return to start position
{
if(Math.round(fingerUpPage)==0)//if at beginning, correct
{
//need to correct for when user starts to scroll into
//nothing then pulls it back a bit, this becomes a
//kind of backwards scroll instead
edgePosition = (int)(fingerUpPage)*mPageWidth;
}
else //carry on as normal
{
edgePosition = mCurrentPage*mPageWidth;
}
}
}
smoothScrollToPage((int)edgePosition/mPageWidth);
mFirstMotionEvent = true;
mMostlyScrollingInX = false;
mMostlyScrollingInY = false;
return true;
}
return false;
}
}
}
\ No newline at end of file
| true | false | null | null |
diff --git a/src/framework/java/com/flexive/core/storage/genericSQL/GenericHierarchicalStorage.java b/src/framework/java/com/flexive/core/storage/genericSQL/GenericHierarchicalStorage.java
index ea8dbce0..9aab0bd2 100644
--- a/src/framework/java/com/flexive/core/storage/genericSQL/GenericHierarchicalStorage.java
+++ b/src/framework/java/com/flexive/core/storage/genericSQL/GenericHierarchicalStorage.java
@@ -1,3514 +1,3514 @@
/***************************************************************
* This file is part of the [fleXive](R) framework.
*
* Copyright (c) 1999-2010
* UCS - unique computing solutions gmbh (http://www.ucs.at)
* All rights reserved
*
* The [fleXive](R) project is free software; you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public
* License version 2.1 or higher as published by the Free Software Foundation.
*
* The GNU Lesser General Public License can be found at
* http://www.gnu.org/licenses/lgpl.html.
* A copy is found in the textfile LGPL.txt and important notices to the
* license from the author are found in LICENSE.txt distributed with
* these libraries.
*
* 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 General Public License for more details.
*
* For further information about UCS - unique computing solutions gmbh,
* please see the company website: http://www.ucs.at
*
* For further information about [fleXive](R), please see the
* project website: http://www.flexive.org
*
*
* This copyright notice MUST APPEAR in all copies of the file!
***************************************************************/
package com.flexive.core.storage.genericSQL;
import com.flexive.core.Database;
import com.flexive.core.DatabaseConst;
import com.flexive.core.LifeCycleInfoImpl;
import com.flexive.core.conversion.ConversionEngine;
import com.flexive.core.flatstorage.FxFlatStorage;
import com.flexive.core.flatstorage.FxFlatStorageLoadColumn;
import com.flexive.core.flatstorage.FxFlatStorageLoadContainer;
import com.flexive.core.flatstorage.FxFlatStorageManager;
import com.flexive.core.storage.ContentStorage;
import com.flexive.core.storage.FulltextIndexer;
import com.flexive.core.storage.StorageManager;
import com.flexive.core.storage.binary.BinaryInputStream;
import com.flexive.core.storage.binary.BinaryStorage;
import com.flexive.extractor.htmlExtractor.HtmlExtractor;
import com.flexive.shared.*;
import com.flexive.shared.configuration.SystemParameters;
import com.flexive.shared.content.*;
import com.flexive.shared.exceptions.*;
import com.flexive.shared.interfaces.HistoryTrackerEngine;
import com.flexive.shared.interfaces.ScriptingEngine;
import com.flexive.shared.scripting.FxScriptBinding;
import com.flexive.shared.scripting.FxScriptEvent;
import com.flexive.shared.security.ACL;
import com.flexive.shared.security.ACLPermission;
import com.flexive.shared.security.Mandator;
import com.flexive.shared.security.UserTicket;
import com.flexive.shared.structure.*;
import com.flexive.shared.value.*;
import com.flexive.shared.workflow.Step;
import com.flexive.shared.workflow.StepDefinition;
import com.flexive.shared.workflow.Workflow;
import com.flexive.stream.ServerLocation;
import com.google.common.collect.Lists;
import com.thoughtworks.xstream.XStream;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.tidy.Tidy;
import java.io.*;
import java.sql.*;
import java.util.*;
import java.util.Date;
import static com.flexive.core.DatabaseConst.*;
/**
* Generic implementation of hierarchical content handling.
* Concrete implementation have to derive from this class and
* provide a singleton hook for the Database class (static getInstance() method)
*
* @author Markus Plesser ([email protected]), UCS - unique computing solutions gmbh (http://www.ucs.at)
*/
public abstract class GenericHierarchicalStorage implements ContentStorage {
private static final Log LOG = LogFactory.getLog(GenericHierarchicalStorage.class);
protected static final String CONTENT_MAIN_INSERT = "INSERT INTO " + TBL_CONTENT +
// 1 2 3 4 5 6 7 8
" (ID,VER,TDEF,ACL,STEP,MAX_VER,LIVE_VER,ISMAX_VER," +
//9 10 11 12 13 14 15 16 17 18
"ISLIVE_VER,ISACTIVE,MAINLANG,RELSRC_ID,RELSRC_VER,RELDST_ID,RELDST_VER,RELSRC_POS,RELDST_POS,CREATED_BY," +
//19 20 21 22
"CREATED_AT,MODIFIED_BY,MODIFIED_AT,MANDATOR,DBIN_ID,DBIN_VER,DBIN_QUALITY,DBIN_ACL)" +
"VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,-1,1,1,1)";
protected static final String CONTENT_MAIN_UPDATE = "UPDATE " + TBL_CONTENT + " SET " +
// 1 2 3 4 5 6 7 8 9
"TDEF=?,ACL=?,STEP=?,MAX_VER=?,LIVE_VER=?,ISMAX_VER=?,ISLIVE_VER=?,ISACTIVE=?,MAINLANG=?," +
// 10 11 12 13 14 15 16 17
"RELSRC_ID=?,RELSRC_VER=?,RELDST_ID=?,RELDST_VER=?,RELSRC_POS=?,RELDST_POS=?,MODIFIED_BY=?,MODIFIED_AT=? " +
// 18 19
"WHERE ID=? AND VER=?";
// 1 2 3 4 5 6 7 8 9
protected static final String CONTENT_MAIN_LOAD = "SELECT ID,VER,TDEF,ACL,STEP,MAX_VER,LIVE_VER,ISMAX_VER,ISLIVE_VER," +
//10 11 12 13 14 15 16 17 18 19
"ISACTIVE,MAINLANG,RELSRC_ID,RELSRC_VER,RELDST_ID,RELDST_VER,RELSRC_POS,RELDST_POS,CREATED_BY,CREATED_AT," +
//20 21 22 23 24
"MODIFIED_BY,MODIFIED_AT,MANDATOR,DBIN_ID,DBIN_ACL FROM " + TBL_CONTENT;
// 1 2 3 4 5 6
protected static final String CONTENT_DATA_LOAD = "SELECT POS,LANG,ASSIGN,XMULT,ISGROUP,ISMLDEF," +
//7 8 9 10 11 12 13 14 15 16 17 18
"FDATE1,FDATE2,FBLOB,FCLOB,FINT,FBIGINT,FTEXT1024,FDOUBLE,FFLOAT,FBOOL,FSELECT,FREF FROM " + TBL_CONTENT_DATA +
// 1 2
" WHERE ID=? AND VER=? ORDER BY XDEPTH ASC, POS ASC, ASSIGN ASC, XMULT ASC";
//single insert statement for content data
protected static final String CONTENT_DATA_INSERT = "INSERT INTO " + TBL_CONTENT_DATA +
//1 2 3 4 5 6 7 8 9 10 11 12 13 14
"(ID,VER,POS,LANG,ASSIGN,XMULT,XINDEX,PARENTXMULT,ISMAX_VER,ISLIVE_VER,ISGROUP,ISMLDEF,TPROP,XDEPTH," +
//15 16 17 18 19 20 21 22 23 24
"FSELECT,FREF,FDATE1,FDATE2,FDOUBLE,FFLOAT,FBOOL,FINT,FBIGINT,FTEXT1024," +
//25 26 27 28
"UFTEXT1024,FBLOB,FCLOB,UFCLOB)" +
"VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?," +
"?,?,?,?,?,?,?,?,?,?," +
"?,?,?,?)";
//single update statement for content data
protected static final String CONTENT_DATA_UPDATE = "UPDATE " + TBL_CONTENT_DATA +
// 1 2
" SET POS=?,ISMLDEF=?," +
// 3 4 5 6 7 8 9
"FSELECT=?,FREF=?,FDATE1=?,FDATE2=?,FDOUBLE=?,FFLOAT=?,FBOOL=?," +
// 10 11 12 13 14 15 16
"FINT=?,FBIGINT=?,FTEXT1024=?,UFTEXT1024=?,FBLOB=?,FCLOB=?,UFCLOB=? " +
// 17 18 19 20 21
"WHERE ID=? AND VER=? AND LANG=? AND ASSIGN=? AND XMULT=?";
/**
* update statements for content type conversion
*/
protected static final String CONTENT_CONVERT_ALL_VERSIONS_UPDATE = "UPDATE " + TBL_CONTENT + " SET " +
// 1 2 3 4
"TDEF=?, MODIFIED_BY=?, MODIFIED_AT=? WHERE ID=?";
protected static final String CONTENT_CONVERT_SINGLE_VERSION_UPDATE = "UPDATE " + TBL_CONTENT + " SET " +
// 1 2 3 4 5
"TDEF=?, MODIFIED_BY=?, MODIFIED_AT=? WHERE ID=? AND VER=?";
protected static final String CONTENT_DATA_CONVERT_ALL_VERSIONS_UPDATE = "UPDATE " + TBL_CONTENT_DATA + " SET " +
// 1 2 3
"ASSIGN=? WHERE ID=? AND ASSIGN=?";
protected static final String CONTENT_DATA_CONVERT_SINGLE_VERSION_UPDATE = "UPDATE " + TBL_CONTENT_DATA + " SET " +
// 1 2 3 4
"ASSIGN=? WHERE ID=? AND ASSIGN=? AND VER=?";
protected static final String CONTENT_DATA_FT_CONVERT_ALL_VERSIONS_UPDATE = "UPDATE " + TBL_CONTENT_DATA_FT + " SET " +
// 1 2 3
"ASSIGN=? WHERE ID=? AND ASSIGN=?";
protected static final String CONTENT_DATA_FT_CONVERT_SINGLE_VERSION_UPDATE = "UPDATE " + TBL_CONTENT_DATA_FT + " SET " +
// 1 2 3 4
"ASSIGN=? WHERE ID=? AND ASSIGN=? AND VER=?";
// 1 2
// protected static final String CONTENT_DATA_REMOVE_VERSION = "DELETE FROM " + TBL_CONTENT_DATA + " WHERE ID=? AND VER=?";
//security info main query
protected static final String SECURITY_INFO_MAIN = "SELECT DISTINCT c.ACL, t.ACL, s.ACL, t.SECURITY_MODE, t.ID, c.DBIN_ID, c.DBIN_ACL, c.CREATED_BY, c.MANDATOR, c.ver FROM " +
TBL_CONTENT + " c, " + TBL_STRUCT_TYPES + " t, " + TBL_WORKFLOW_STEP + " s WHERE c.ID=? AND ";
protected static final String SECURITY_INFO_WHERE = " AND t.ID=c.TDEF AND s.ID=c.STEP";
protected static final String SECURITY_INFO_VER = SECURITY_INFO_MAIN + "c.VER=?" + SECURITY_INFO_WHERE;
protected static final String SECURITY_INFO_MAXVER = SECURITY_INFO_MAIN + "c.VER=c.MAX_VER" + SECURITY_INFO_WHERE;
protected static final String SECURITY_INFO_LIVEVER = SECURITY_INFO_MAIN + "c.VER=c.LIVE_VER" + SECURITY_INFO_WHERE;
//calculate max_ver and live_ver for a content instance
protected static final String CONTENT_VER_CALC = "SELECT MAX(VER) AS MAX_VER, COALESCE((SELECT s.VER FROM " +
TBL_CONTENT + " s WHERE s.STEP=(SELECT w.ID FROM " + TBL_WORKFLOW_STEP + " w, " + TBL_STRUCT_TYPES + " t WHERE w.STEPDEF=" +
StepDefinition.LIVE_STEP_ID + " AND w.WORKFLOW=t.WORKFLOW AND t.ID=c.TDEF) AND s.ID=c.ID),-1) AS LIVE_VER FROM " + TBL_CONTENT +
" c WHERE c.ID=? GROUP BY c.ID,c.TDEF";
protected static final String CONTENT_VER_UPDATE_1 = "UPDATE " + TBL_CONTENT + " SET MAX_VER=?, LIVE_VER=?, ISMAX_VER=(VER=?), ISLIVE_VER=(VER=?) WHERE ID=?";
// protected static final String CONTENT_VER_UPDATE_2 = "UPDATE " + TBL_CONTENT + " SET ISMAX_VER=(MAX_VER=VER), ISLIVE_VER=(LIVE_VER=VER) WHERE ID=?";
protected static final String CONTENT_VER_UPDATE_3 = "UPDATE " + TBL_CONTENT_DATA + " SET ISMAX_VER=(VER=?), ISLIVE_VER=(VER=?) WHERE ID=?";
protected static final String CONTENT_STEP_GETVERSIONS = "SELECT VER FROM " + TBL_CONTENT + " WHERE STEP=? AND ID=? AND VER<>?";
protected static final String CONTENT_STEP_DEPENDENCIES = "UPDATE " + TBL_CONTENT + " SET STEP=? WHERE STEP=? AND ID=? AND VER<>?";
protected static final String CONTENT_REFERENCE_LIVE = "SELECT VER, ACL, STEP, TDEF, CREATED_BY FROM " + TBL_CONTENT + " WHERE ID=? AND ISLIVE_VER=?";
protected static final String CONTENT_REFERENCE_MAX = "SELECT VER, ACL, STEP, TDEF, CREATED_BY FROM " + TBL_CONTENT + " WHERE ID=? AND ISMAX_VER=?";
protected static final String CONTENT_REFERENCE_CAPTION = "SELECT FTEXT1024 FROM " + TBL_CONTENT_DATA + " WHERE ID=? AND VER=? AND TPROP=?";
protected static final String CONTENT_REFERENCE_BYTYPE = "SELECT COUNT(DISTINCT d.ID) FROM " + TBL_CONTENT + " c, " +
TBL_CONTENT_DATA + " d, " + TBL_STRUCT_ASSIGNMENTS + " a, " + TBL_STRUCT_PROPERTIES + " p " +
"WHERE c.TDEF=a.TYPEDEF AND a.APROPERTY=p.ID AND p.REFTYPE=? AND d.ASSIGN=a.ID AND d.TPROP=p.ID AND d.FREF<>d.ID";
//getContentVersionInfo() statement
protected static final String CONTENT_VER_INFO = "SELECT ID, VER, MAX_VER, LIVE_VER, CREATED_BY, CREATED_AT, MODIFIED_BY, MODIFIED_AT, STEP FROM " + TBL_CONTENT + " WHERE ID=?";
protected static final String CONTENT_MAIN_REMOVE = "DELETE FROM " + TBL_CONTENT + " WHERE ID=?";
protected static final String CONTENT_DATA_REMOVE = "DELETE FROM " + TBL_CONTENT_DATA + " WHERE ID=?";
protected static final String SQL_WHERE_VER = " AND VER=?";
protected static final String CONTENT_MAIN_REMOVE_VER = CONTENT_MAIN_REMOVE + SQL_WHERE_VER;
protected static final String CONTENT_DATA_REMOVE_VER = CONTENT_DATA_REMOVE + SQL_WHERE_VER;
protected static final String CONTENT_MAIN_REMOVE_TYPE = "DELETE FROM " + TBL_CONTENT + " WHERE TDEF=?";
protected static final String CONTENT_DATA_REMOVE_TYPE = "DELETE FROM " + TBL_CONTENT_DATA + " WHERE ID IN (SELECT DISTINCT ID FROM " + TBL_CONTENT + " WHERE TDEF=?)";
protected static final String CONTENT_TYPE_PK_RETRIEVE_VERSIONS = "SELECT DISTINCT ID,VER FROM " + TBL_CONTENT + " WHERE TDEF=? ORDER BY ID,VER";
protected static final String CONTENT_TYPE_PK_RETRIEVE_IDS = "SELECT DISTINCT ID FROM " + TBL_CONTENT + " WHERE TDEF=? ORDER BY ID";
protected static final String CONTENT_GET_TYPE = "SELECT DISTINCT TDEF FROM " + TBL_CONTENT + " WHERE ID=?";
protected static final String CONTENT_ACLS_LOAD = "SELECT ACL FROM " + TBL_CONTENT_ACLS + " WHERE ID=? AND VER=?";
protected static final String CONTENT_ACLS_CLEAR = "DELETE FROM " + TBL_CONTENT_ACLS + " WHERE ID=? AND VER=?";
protected static final String CONTENT_ACL_INSERT = "INSERT INTO " + TBL_CONTENT_ACLS + "(ID, VER, ACL) VALUES (?, ?, ?)";
// 1 2 3 4
protected static final String CONTENT_MAIN_UPDATE_CREATED_AT = "UPDATE " + TBL_CONTENT + " SET CREATED_AT=?, CREATED_BY=? WHERE ID=? AND VER=?";
//prepared statement positions
protected final static int INSERT_LANG_POS = 4;
protected final static int INSERT_ISDEF_LANG_POS = 12;
//position of first value
protected final static int INSERT_VALUE_POS = 14;
//position of last value
protected final static int INSERT_END_POS = 28;
//position of the id field (start of the where clause) for detail updates
protected final static int UPDATE_ID_POS = 17;
protected final static int UPDATE_POS_POS = 1;
protected final static int UPDATE_MLDEF_POS = 2;
// propertyId -> column names
protected static final HashMap<Long, String[]> mainColumnHash;
// dataType -> column names
protected static final HashMap<FxDataType, String[]> detailColumnNameHash;
// dataType -> column insert positions
protected static final HashMap<FxDataType, int[]> detailColumnInsertPosHash;
// dataType -> column update positions
protected static final HashMap<FxDataType, int[]> detailColumnUpdatePosHash;
static {
detailColumnNameHash = new HashMap<FxDataType, String[]>(20);
detailColumnInsertPosHash = new HashMap<FxDataType, int[]>(20);
detailColumnUpdatePosHash = new HashMap<FxDataType, int[]>(20);
detailColumnNameHash.put(FxDataType.Binary, array("FBLOB"));
detailColumnInsertPosHash.put(FxDataType.Binary, array(26));
detailColumnUpdatePosHash.put(FxDataType.Binary, array(14));
detailColumnNameHash.put(FxDataType.Boolean, array("FBOOL"));
detailColumnInsertPosHash.put(FxDataType.Boolean, array(21));
detailColumnUpdatePosHash.put(FxDataType.Boolean, array(9));
detailColumnNameHash.put(FxDataType.Date, array("FDATE1"));
detailColumnInsertPosHash.put(FxDataType.Date, array(17));
detailColumnUpdatePosHash.put(FxDataType.Date, array(5));
detailColumnNameHash.put(FxDataType.DateRange, array("FDATE1", "FDATE2"));
detailColumnInsertPosHash.put(FxDataType.DateRange, array(17, 18));
detailColumnUpdatePosHash.put(FxDataType.DateRange, array(5, 6));
detailColumnNameHash.put(FxDataType.DateTime, array("FDATE1"));
detailColumnInsertPosHash.put(FxDataType.DateTime, array(17));
detailColumnUpdatePosHash.put(FxDataType.DateTime, array(5));
detailColumnNameHash.put(FxDataType.DateTimeRange, array("FDATE1", "FDATE2"));
detailColumnInsertPosHash.put(FxDataType.DateTimeRange, array(17, 18));
detailColumnUpdatePosHash.put(FxDataType.DateTimeRange, array(5, 6));
detailColumnNameHash.put(FxDataType.Double, array("FDOUBLE"));
detailColumnInsertPosHash.put(FxDataType.Double, array(19));
detailColumnUpdatePosHash.put(FxDataType.Double, array(7));
detailColumnNameHash.put(FxDataType.Float, array("FFLOAT"));
detailColumnInsertPosHash.put(FxDataType.Float, array(20));
detailColumnUpdatePosHash.put(FxDataType.Float, array(8));
detailColumnNameHash.put(FxDataType.LargeNumber, array("FBIGINT"));
detailColumnInsertPosHash.put(FxDataType.LargeNumber, array(23));
detailColumnUpdatePosHash.put(FxDataType.LargeNumber, array(11));
detailColumnNameHash.put(FxDataType.Number, array("FINT"));
detailColumnInsertPosHash.put(FxDataType.Number, array(22));
detailColumnUpdatePosHash.put(FxDataType.Number, array(10));
detailColumnNameHash.put(FxDataType.Reference, array("FREF"));
detailColumnInsertPosHash.put(FxDataType.Reference, array(16));
detailColumnUpdatePosHash.put(FxDataType.Reference, array(4));
detailColumnNameHash.put(FxDataType.String1024, array("FTEXT1024"));
detailColumnInsertPosHash.put(FxDataType.String1024, array(24));
detailColumnUpdatePosHash.put(FxDataType.String1024, array(12));
detailColumnNameHash.put(FxDataType.Text, array("FCLOB"));
detailColumnInsertPosHash.put(FxDataType.Text, array(27));
detailColumnUpdatePosHash.put(FxDataType.Text, array(15));
detailColumnNameHash.put(FxDataType.HTML, array("FCLOB", "FBOOL", "UFCLOB"));
detailColumnInsertPosHash.put(FxDataType.HTML, array(27, 21, 28));
detailColumnUpdatePosHash.put(FxDataType.HTML, array(15, 9, 16));
detailColumnNameHash.put(FxDataType.SelectOne, array("FSELECT"));
detailColumnInsertPosHash.put(FxDataType.SelectOne, array(15));
detailColumnUpdatePosHash.put(FxDataType.SelectOne, array(3));
detailColumnNameHash.put(FxDataType.SelectMany, array("FSELECT", "FTEXT1024"/*comma separated list of selected id's*/, "FINT" /*number of selected options*/));
detailColumnInsertPosHash.put(FxDataType.SelectMany, array(15, 24/*comma separated list of selected id's*/, 22/*number of selected options*/));
detailColumnUpdatePosHash.put(FxDataType.SelectMany, array(3, 12/*comma separated list of selected id's*/, 10/*number of selected options*/));
mainColumnHash = new HashMap<Long, String[]>(20);
mainColumnHash.put(0L, array("ID"));
mainColumnHash.put(1L, array("VER"));
mainColumnHash.put(2L, array("TDEF"));
mainColumnHash.put(3L, array("MANDATOR"));
mainColumnHash.put(4L, array("ACL"));
mainColumnHash.put(5L, array("STEP"));
mainColumnHash.put(6L, array("MAX_VER"));
mainColumnHash.put(7L, array("LIVE_VER"));
mainColumnHash.put(8L, array("ISMAX_VER"));
mainColumnHash.put(9L, array("ISLIVE_VER"));
mainColumnHash.put(10L, array("ISACTIVE"));
mainColumnHash.put(11L, array("MAINLANG"));
mainColumnHash.put(12L, array("RELSRC"));
mainColumnHash.put(13L, array("RELDST"));
mainColumnHash.put(14L, array("RELPOS_SRC"));
mainColumnHash.put(15L, array("RELPOS_DST"));
mainColumnHash.put(16L, array("CREATED_BY"));
mainColumnHash.put(17L, array("CREATED_AT"));
mainColumnHash.put(18L, array("MODIFIED_BY"));
mainColumnHash.put(19L, array("MODIFIED_AT"));
mainColumnHash.put(20L, array("CAPTION"));
}
protected BinaryStorage binaryStorage;
protected GenericHierarchicalStorage(BinaryStorage binaryStorage) {
this.binaryStorage = binaryStorage;
}
/**
* {@inheritDoc}
*/
public String getTableName(FxProperty prop) {
if (prop.isSystemInternal())
return DatabaseConst.TBL_CONTENT;
return DatabaseConst.TBL_CONTENT_DATA;
}
/**
* Helper to convert a var array of string to a 'real' string array
*
* @param data strings to put into an array
* @return string array from parameters
*/
protected static String[] array(String... data) {
return data;
}
/**
* Helper to convert a var array of int to a 'real' int array
*
* @param data ints to put into an array
* @return int array from parameters
*/
protected static int[] array(int... data) {
return data;
}
/**
* Set a prepared statements values to <code>NULL</code> from startPos to endPos
*
* @param ps prepared statement
* @param startPos start position
* @param endPos end position
* @throws SQLException on errors
*/
protected static void clearPreparedStatement(PreparedStatement ps, int startPos, int endPos) throws SQLException {
for (int i = startPos; i <= endPos; i++)
ps.setNull(i, Types.NULL);
}
/**
* Lock table needed for update operations for a content
*
* @param con an open and valid connection
* @param id id of the content
* @param version optional version, if <=0 all versions will be locked
* @throws FxRuntimeException containing a FxDbException
*/
public abstract void lockTables(Connection con, long id, int version) throws FxRuntimeException;
/**
* Use batch updates for changes in content data entries?
*
* @return if batch updates should be used for changes in content data entries
*/
protected boolean batchContentDataChanges() {
return true;
}
/**
* Set a big(long) string value, implementations may differ by used database
*
* @param ps the prepared statement to operate on
* @param pos argument position
* @param data the big string to set
* @throws SQLException on errors
*/
protected void setBigString(PreparedStatement ps, int pos, String data) throws SQLException {
//default implementation using PreparedStatement#setString
ps.setString(pos, data);
}
/**
* {@inheritDoc}
*/
public String getUppercaseColumn(FxProperty prop) {
if (prop.isSystemInternal())
return null;
switch (prop.getDataType()) {
case String1024:
return "UFTEXT1024";
case Text:
return "UFCLOB";
default:
return null;
}
}
/**
* Get the insert position of the uppercase column for a detail property or <code>-1</code> if no uppercase column exists
*
* @param prop detail property
* @param insert get column pos for an insert or update?
* @return insert position of the uppercase column for a detail property or <code>-1</code> if no uppercase column exists
*/
public int getUppercaseColumnPos(FxProperty prop, boolean insert) {
if (prop.isSystemInternal())
return -1;
switch (prop.getDataType()) {
case String1024:
return insert ? 25 : 13; //UFTEXT1024
case Text:
return insert ? 28 : 16; //UFCLOB
default:
return -1;
}
}
/**
* Get the value data column position for a given data type for loading
*
* @param dataType requested data type
* @return value column position
* @since 3.1.4
*/
protected int getValueDataLoadPos(FxDataType dataType) {
if (dataType == FxDataType.Number || dataType == FxDataType.SelectMany)
return 12; //FBIGINT
return 11; //FINT
}
/**
* Get the value data column position for a given data type for inserting
*
* @param dataType requested data type
* @return value column position
* @since 3.1.4
*/
protected int getValueDataInsertPos(FxDataType dataType) {
if (dataType == FxDataType.Number || dataType == FxDataType.SelectMany)
return 23; //FBIGINT
return 22; //FINT
}
/**
* Get the value data column position for a given data type for updating
*
* @param dataType requested data type
* @return value column position
* @since 3.1.4
*/
protected int getValueDataUpdatePos(FxDataType dataType) {
if (dataType == FxDataType.Number || dataType == FxDataType.SelectMany)
return 11; //FBIGINT
return 10; //FINT
}
/**
* {@inheritDoc}
*/
public String getQueryUppercaseColumn(FxProperty property) {
if (!property.isSystemInternal() && property.getDataType() == FxDataType.HTML)
return "UPPER(UFCLOB)";
return getUppercaseColumn(property);
}
/**
* {@inheritDoc}
*/
public String[] getColumns(FxProperty prop) {
if (prop.isSystemInternal())
return mainColumnHash.get(prop.getId());
return detailColumnNameHash.get(prop.getDataType());
}
/**
* {@inheritDoc}
*/
public String[] getColumns(long propertyId, boolean systemInternalProperty, FxDataType dataType) {
if (systemInternalProperty)
return mainColumnHash.get(propertyId);
return detailColumnNameHash.get(dataType);
}
/**
* Get the insert positions for the given detail properties
*
* @param prop property
* @return insert positions for the prepared statement
*/
protected int[] getColumnPosInsert(FxProperty prop) {
return detailColumnInsertPosHash.get(prop.getDataType());
}
/**
* Get the insert positions for the given detail properties
*
* @param prop property
* @return insert positions for the prepared statement
*/
protected int[] getColumnPosUpdate(FxProperty prop) {
return detailColumnUpdatePosHash.get(prop.getDataType());
}
/**
* {@inheritDoc}
*/
public FulltextIndexer getFulltextIndexer(FxPK pk, Connection con) {
FulltextIndexer indexer = new GenericSQLFulltextIndexer();
indexer.init(pk, con);
return indexer;
}
/**
* {@inheritDoc}
*/
public FxPK contentCreate(Connection con, FxEnvironment env, StringBuilder sql, long newId, FxContent content) throws FxCreateException, FxInvalidParameterException {
content.getRootGroup().removeEmptyEntries();
content.getRootGroup().compactPositions(true);
content.checkValidity();
final Integer contentVersionValue = content.getValue(FxNumber.class, "/version").getBestTranslation();
final Long contentIdValue = content.getValue(FxLargeNumber.class, "/id").getBestTranslation();
final int version = content.isForcePkOnCreate() && contentVersionValue != -1 ? contentVersionValue : 1;
if (content.isForcePkOnCreate() && contentIdValue != -1) {
// if a specific ID was set, other versions of this content may exist and we need to process the
// workflow as if creating a new version of an existing content
try {
updateStepDependencies(con, contentIdValue, version, env, env.getType(content.getTypeId()), content.getStepId());
} catch (FxApplicationException e) {
throw new FxCreateException(LOG, e);
}
}
FxPK pk = createMainEntry(con, newId, version, content);
FxType type = env.getType(content.getTypeId());
PreparedStatement ps;
FulltextIndexer ft = getFulltextIndexer(pk, con);
try {
if (sql == null)
sql = new StringBuilder(2000);
ps = con.prepareStatement(CONTENT_DATA_INSERT);
createDetailEntries(con, ps, ft, sql, pk, content.isMaxVersion(), content.isLiveVersion(), content.getData("/"));
if (batchContentDataChanges())
ps.executeBatch();
ft.commitChanges();
if (CacheAdmin.getEnvironment().getType(content.getTypeId()).isContainsFlatStorageAssignments()) {
FxFlatStorage flatStorage = FxFlatStorageManager.getInstance();
flatStorage.setPropertyData(con, pk, content.getTypeId(), content.getStepId(),
content.isMaxVersion(), content.isLiveVersion(), flatStorage.getFlatPropertyData(content.getRootGroup()));
}
if (content.isForcePkOnCreate()) {
// we must fix the MAX_VER/LIVE_VER columns now, since they may not have been set correctly in the insert
fixContentVersionStats(con, type, pk.getId());
}
checkUniqueConstraints(con, env, sql, pk, content.getTypeId());
content.resolveBinaryPreview();
binaryStorage.updateContentBinaryEntry(con, pk, content.getBinaryPreviewId(), content.getBinaryPreviewACL());
if (type.isTrackHistory())
EJBLookup.getHistoryTrackerEngine().track(type, pk, ConversionEngine.getXStream().toXML(content),
"history.content.created");
} catch (FxApplicationException e) {
if (e instanceof FxCreateException)
throw (FxCreateException) e;
if (e instanceof FxInvalidParameterException)
throw (FxInvalidParameterException) e;
throw new FxCreateException(LOG, e);
} catch (SQLException e) {
throw new FxCreateException(LOG, e, "ex.db.sqlError", e.getMessage());
} finally {
ft.cleanup();
}
return pk;
}
/**
* Assign correct MAX_VER, LIVE_VER, ISMAX_VER and ISLIVE_VER values for a given content instance
*
* @param con an open and valid connection
* @param type the contents type
* @param id the id to fix the version statistics for
* @throws FxUpdateException if a sql error occurs
*/
protected void fixContentVersionStats(Connection con, FxType type, long id) throws FxUpdateException {
PreparedStatement ps = null;
try {
//lock needed columns
ps = con.prepareStatement("SELECT MAX_VER, LIVE_VER, ISMAX_VER, ISLIVE_VER FROM " + TBL_CONTENT + " WHERE ID=? FOR UPDATE");
ps.setLong(1, id);
ps.execute();
ps.close();
ps = con.prepareStatement("SELECT ISMAX_VER, ISLIVE_VER FROM " + TBL_CONTENT_DATA + " WHERE ID=? FOR UPDATE");
ps.setLong(1, id);
ps.execute();
ps = con.prepareStatement(CONTENT_VER_CALC);
ps.setLong(1, id);
ResultSet rs = ps.executeQuery();
if (rs == null || !rs.next())
return;
int max_ver = rs.getInt(1);
if (rs.wasNull())
return;
int live_ver = rs.getInt(2);
if (rs.wasNull() || live_ver < 0)
live_ver = 0;
ps.close();
if (live_ver == 0) //deactivate in live tree
StorageManager.getTreeStorage().contentRemoved(con, id, true);
ps = con.prepareStatement(CONTENT_VER_UPDATE_1);
ps.setInt(1, max_ver);
ps.setInt(2, live_ver);
ps.setInt(3, max_ver);
ps.setInt(4, live_ver);
- ps.setLong(3, id);
+ ps.setLong(5, id);
ps.executeUpdate();
ps.close();
/*ps = con.prepareStatement(CONTENT_VER_UPDATE_2);
ps.setLong(1, id);
ps.executeUpdate();
ps.close();*/
ps = con.prepareStatement(CONTENT_VER_UPDATE_3);
ps.setInt(1, max_ver);
ps.setInt(2, live_ver);
ps.setLong(3, id);
ps.executeUpdate();
if (type.isContainsFlatStorageAssignments())
syncContentStats(con, type.getId(), id, max_ver, live_ver);
} catch (SQLException e) {
throw new FxUpdateException(LOG, e, "ex.db.sqlError", e.getMessage());
} catch (FxNotFoundException e) {
throw new FxUpdateException(e);
} catch (FxApplicationException e) {
throw new FxUpdateException(e);
} finally {
if (ps != null)
try {
ps.close();
} catch (SQLException e) {
//ignore
}
}
}
/**
* Synchronize content stats to flat storage
*
* @param con an open and valid Connection
* @param typeId type id
* @param id content id
* @param max_ver max. version
* @param live_ver live version
* @throws SQLException on errors
*/
protected void syncContentStats(Connection con, long typeId, long id, int max_ver, int live_ver) throws SQLException {
FxFlatStorageManager.getInstance().syncContentStats(con, typeId, id, max_ver, live_ver);
}
/**
* {@inheritDoc}
*/
public FxPK contentCreateVersion(Connection con, FxEnvironment env, StringBuilder sql, FxContent content) throws FxCreateException, FxInvalidParameterException {
if (content.getPk().isNew())
throw new FxInvalidParameterException("content", "ex.content.pk.invalid.newVersion", content.getPk());
if (content.isForcePkOnCreate()) {
throw new FxInvalidParameterException("content", "ex.content.save.force.pk.update");
}
content.getRootGroup().removeEmptyEntries();
content.getRootGroup().compactPositions(true);
content.checkValidity();
final FxType type = CacheAdmin.getEnvironment().getType(content.getTypeId());
FxPK pk;
PreparedStatement ps = null;
FulltextIndexer ft = null;
try {
int new_version = getContentVersionInfo(con, content.getPk().getId()).getMaxVersion() + 1;
updateStepDependencies(con, content.getPk().getId(), new_version, env, env.getType(content.getTypeId()), content.getStepId());
pk = createMainEntry(con, content.getPk().getId(), new_version, content);
ft = getFulltextIndexer(pk, con);
if (sql == null)
sql = new StringBuilder(2000);
ps = con.prepareStatement(CONTENT_DATA_INSERT);
createDetailEntries(con, ps, ft, sql, pk, content.isMaxVersion(), content.isLiveVersion(), content.getData("/"));
if (batchContentDataChanges())
ps.executeBatch();
if (type.isContainsFlatStorageAssignments()) {
FxFlatStorage flatStorage = FxFlatStorageManager.getInstance();
flatStorage.setPropertyData(con, pk, content.getTypeId(), content.getStepId(),
content.isMaxVersion(), content.isLiveVersion(), flatStorage.getFlatPropertyData(content.getRootGroup()));
}
checkUniqueConstraints(con, env, sql, pk, content.getTypeId());
binaryStorage.updateContentBinaryEntry(con, pk, content.getBinaryPreviewId(), content.getBinaryPreviewACL());
ft.commitChanges();
ps.close();
fixContentVersionStats(con, type, content.getPk().getId());
} catch (FxApplicationException e) {
if (e instanceof FxCreateException)
throw (FxCreateException) e;
if (e instanceof FxInvalidParameterException)
throw (FxInvalidParameterException) e;
throw new FxCreateException(e);
} catch (SQLException e) {
throw new FxCreateException(LOG, e, "ex.db.sqlError", e.getMessage());
} finally {
Database.closeObjects(GenericHierarchicalStorage.class, null, ps);
if (ft != null)
ft.cleanup();
}
final FxContent newVersion;
try {
sql.setLength(0);
newVersion = contentLoad(con, pk, env, sql);
syncFQNName(con, newVersion, pk, null);
} catch (FxApplicationException e) {
throw new FxCreateException(e);
}
if (type.isTrackHistory())
EJBLookup.getHistoryTrackerEngine().track(type, pk,
ConversionEngine.getXStream().toXML(newVersion),
"history.content.created.version", pk.getVersion());
return pk;
}
/**
* Handle unique steps and make sure only one unique step per content instance exists
*
* @param con open and valid connection
* @param id content id
* @param ignoreVersion the version to ignore on changes (=current version)
* @param env FxEnvironment
* @param type FxType
* @param stepId the step id @throws FxNotFoundException on errors
* @throws FxUpdateException on errors
* @throws FxNotFoundException on errors
*/
protected void updateStepDependencies(Connection con, long id, int ignoreVersion, FxEnvironment env, FxType type, long stepId) throws FxNotFoundException, FxUpdateException {
Step step = env.getStep(stepId);
StepDefinition stepDef = env.getStepDefinition(step.getStepDefinitionId());
if (stepDef.isUnique()) {
Step fallBackStep = env.getStepByDefinition(step.getWorkflowId(), stepDef.getUniqueTargetId());
updateStepDependencies(con, id, ignoreVersion, env, type, fallBackStep.getId()); //handle chained unique steps recursively
PreparedStatement ps = null;
try {
if (type.isTrackHistory()) {
ps = con.prepareStatement(CONTENT_STEP_GETVERSIONS);
ps.setLong(1, stepId);
ps.setLong(2, id);
ps.setInt(3, ignoreVersion);
ResultSet rs = ps.executeQuery();
HistoryTrackerEngine tracker = null;
String orgStep = null, newStep = null;
while (rs != null && rs.next()) {
if (tracker == null) {
tracker = EJBLookup.getHistoryTrackerEngine();
orgStep = env.getStepDefinition(env.getStep(stepId).getStepDefinitionId()).getName();
newStep = env.getStepDefinition(fallBackStep.getStepDefinitionId()).getName();
}
tracker.track(type, new FxPK(id, rs.getInt(1)), null, "history.content.step.change", orgStep, newStep);
}
ps.close();
}
ps = con.prepareStatement(CONTENT_STEP_DEPENDENCIES);
ps.setLong(1, fallBackStep.getId());
ps.setLong(2, stepId);
ps.setLong(3, id);
ps.setInt(4, ignoreVersion);
ps.executeUpdate();
} catch (SQLException e) {
throw new FxUpdateException(e, "ex.content.step.dependencies.update.failed", id, e.getMessage());
} finally {
try {
if (ps != null)
ps.close();
} catch (SQLException e) {
LOG.error(e, e);
}
}
}
}
/**
* {@inheritDoc}
*/
public FxContentVersionInfo getContentVersionInfo(Connection con, long id) throws FxNotFoundException {
PreparedStatement ps = null;
int min_ver = -1, max_ver = 0, live_ver = 0, lastMod_ver = 0;
long lastMod_time;
Map<Integer, FxContentVersionInfo.VersionData> versions = new HashMap<Integer, FxContentVersionInfo.VersionData>(5);
try {
ps = con.prepareStatement(CONTENT_VER_INFO);
ps.setLong(1, id);
ResultSet rs = ps.executeQuery();
if (rs == null || !rs.next())
throw new FxNotFoundException("ex.content.notFound", new FxPK(id));
max_ver = rs.getInt(3);
live_ver = rs.getInt(4);
versions.put(rs.getInt(2),
new FxContentVersionInfo.VersionData(LifeCycleInfoImpl.load(rs, 5, 6, 7, 8), rs.getLong(9)));
min_ver = rs.getInt(2);
lastMod_ver = rs.getInt(2);
lastMod_time = versions.get(rs.getInt(2)).getLifeCycleInfo().getModificationTime();
while (rs.next()) {
if (rs.getInt(2) < min_ver)
min_ver = rs.getInt(2);
versions.put(rs.getInt(2),
new FxContentVersionInfo.VersionData(LifeCycleInfoImpl.load(rs, 5, 6, 7, 8), rs.getLong(9)));
if (versions.get(rs.getInt(2)).getLifeCycleInfo().getModificationTime() >= lastMod_time) {
lastMod_ver = rs.getInt(2);
lastMod_time = versions.get(rs.getInt(2)).getLifeCycleInfo().getModificationTime();
}
}
} catch (SQLException e) {
throw new FxNotFoundException(e, "ex.content.versionInfo.sqlError", id, e.getMessage());
} finally {
try {
if (ps != null)
ps.close();
} catch (SQLException e) {
LOG.error(e, e);
}
}
return new FxContentVersionInfo(id, min_ver, max_ver, live_ver, lastMod_ver, versions);
}
/**
* Create a new main entry
*
* @param con an open and valid connection
* @param newId the id to use
* @param version the version to use
* @param content content to create
* @return primary key of the created content
* @throws FxCreateException on errors
*/
protected FxPK createMainEntry(Connection con, long newId, int version, FxContent content) throws FxCreateException {
PreparedStatement ps = null;
FxPK pk = new FxPK(newId, version);
try {
ps = con.prepareStatement(CONTENT_MAIN_INSERT);
ps.setLong(1, newId);
ps.setInt(2, version);
ps.setLong(3, content.getTypeId());
ps.setLong(4, content.getAclIds().size() > 1 ? ACL.NULL_ACL_ID : content.getAclIds().get(0));
ps.setLong(5, content.getStepId());
ps.setInt(6, 1); //if creating a new version, max_ver will be fixed in a later step
ps.setInt(7, content.isLiveVersion() ? 1 : 0);
ps.setBoolean(8, content.isMaxVersion());
ps.setBoolean(9, content.isLiveVersion());
ps.setBoolean(10, content.isActive());
ps.setInt(11, (int) content.getMainLanguage());
if (content.isRelation()) {
ps.setLong(12, content.getRelatedSource().getId());
ps.setInt(13, content.getRelatedSource().getVersion());
ps.setLong(14, content.getRelatedDestination().getId());
ps.setInt(15, content.getRelatedDestination().getVersion());
ps.setLong(16, content.getRelatedSourcePosition());
ps.setLong(17, content.getRelatedDestinationPosition());
} else {
ps.setNull(12, java.sql.Types.NUMERIC);
ps.setNull(13, java.sql.Types.NUMERIC);
ps.setNull(14, java.sql.Types.NUMERIC);
ps.setNull(15, java.sql.Types.NUMERIC);
ps.setNull(16, java.sql.Types.NUMERIC);
ps.setNull(17, java.sql.Types.NUMERIC);
}
if (!content.isForceLifeCycle()) {
final long userId = FxContext.getUserTicket().getUserId();
final long now = System.currentTimeMillis();
ps.setLong(18, userId);
ps.setLong(19, now);
ps.setLong(20, userId);
ps.setLong(21, now);
} else {
ps.setLong(18, content.getValue(FxLargeNumber.class, "/CREATED_BY").getBestTranslation());
ps.setLong(19, content.getValue(FxDateTime.class, "/CREATED_AT").getBestTranslation().getTime());
ps.setLong(20, content.getValue(FxLargeNumber.class, "/MODIFIED_BY").getBestTranslation());
ps.setLong(21, content.getValue(FxDateTime.class, "/MODIFIED_AT").getBestTranslation().getTime());
}
ps.setLong(22, content.getMandatorId());
ps.executeUpdate();
updateACLEntries(con, content, pk, true);
} catch (SQLException e) {
throw new FxCreateException(LOG, e, "ex.db.sqlError", e.getMessage());
} catch (FxUpdateException e) {
throw new FxCreateException(e);
} finally {
if (ps != null)
try {
ps.close();
} catch (SQLException e) {
//ignore
}
}
return pk;
}
/**
* Update all (multiple) ACL entries for a content instance
*
* @param con an open and valid connection
* @param content the content containing the ACL'S
* @param pk primary key of the content
* @param newEntry is this a new entry?
* @throws SQLException on errors
* @throws FxCreateException on errors
* @throws FxUpdateException on errors
*/
protected void updateACLEntries(Connection con, FxContent content, FxPK pk, boolean newEntry) throws SQLException, FxCreateException, FxUpdateException {
PreparedStatement ps = null;
try {
if (content.getAclIds().isEmpty() || (content.getAclIds().size() == 1 && content.getAclIds().get(0) == ACL.NULL_ACL_ID)) {
if (newEntry) {
throw new FxCreateException(LOG, "ex.content.noACL", pk);
} else {
throw new FxUpdateException(LOG, "ex.content.noACL", pk);
}
}
if (!newEntry) {
// first remove all ACLs, then update them
ps = con.prepareStatement(CONTENT_ACLS_CLEAR);
ps.setLong(1, pk.getId());
ps.setInt(2, pk.getVersion());
ps.executeUpdate();
}
final List<Long> aclIds = content.getAclIds();
if (aclIds.size() <= 1) {
return; // ACL saved in main table
}
//insert ACLs
ps = con.prepareStatement(CONTENT_ACL_INSERT);
for (long aclId : aclIds) {
ps.setLong(1, pk.getId());
ps.setInt(2, pk.getVersion());
ps.setLong(3, aclId);
ps.addBatch();
}
ps.executeBatch();
} finally {
Database.closeObjects(GenericHierarchicalStorage.class, null, ps);
}
}
/**
* Create all detail entries for a content instance
*
* @param con an open and valid connection
* @param ps batch prepared statement for detail inserts
* @param ft fulltext indexer
* @param sql an optional StringBuffer
* @param pk primary key of the content
* @param maxVersion is this content the maximum available version?
* @param liveVersion is this content the live version?
* @param data FxData to create
* @throws FxNotFoundException on errors
* @throws FxDbException on errors
* @throws FxCreateException on errors
*/
protected void createDetailEntries(Connection con, PreparedStatement ps, FulltextIndexer ft, StringBuilder sql,
FxPK pk, boolean maxVersion, boolean liveVersion, List<FxData> data)
throws FxNotFoundException, FxDbException, FxCreateException {
createDetailEntries(con, ps, ft, sql, pk, maxVersion, liveVersion, data, false);
}
/**
* Create all detail entries for a content instance
*
* @param con an open and valid connection
* @param ps batch prepared statement for detail inserts
* @param ft fulltext indexer
* @param sql an optional StringBuffer
* @param pk primary key of the content
* @param maxVersion is this content the maximum available version?
* @param liveVersion is this content the live version?
* @param data FxData to create
* @param disregardFlatStorageEntry true = do not check if the data is in the flatstorage (contentTypeConversion)
* @throws FxNotFoundException on errors
* @throws FxDbException on errors
* @throws FxCreateException on errors
*/
private void createDetailEntries(Connection con, PreparedStatement ps, FulltextIndexer ft, StringBuilder sql,
FxPK pk, boolean maxVersion, boolean liveVersion, List<FxData> data,
boolean disregardFlatStorageEntry) throws FxNotFoundException, FxDbException, FxCreateException {
try {
FxProperty prop;
for (FxData curr : data) {
if (curr.isProperty()) {
FxPropertyData pdata = ((FxPropertyData) curr);
prop = pdata.getPropertyAssignment().getProperty();
if (!prop.isSystemInternal())
insertPropertyData(prop, data, con, ps, ft, pk, pdata, maxVersion, liveVersion, disregardFlatStorageEntry);
} else {
insertGroupData(con, sql, pk, ((FxGroupData) curr), maxVersion, liveVersion);
createDetailEntries(con, ps, ft, sql, pk, maxVersion, liveVersion, ((FxGroupData) curr).getChildren());
}
}
} catch (SQLException e) {
throw new FxDbException(LOG, e, "ex.db.sqlError", e.getMessage());
} catch (FxNoAccessException e) {
throw new FxCreateException(e);
} catch (FxUpdateException e) {
throw new FxCreateException(e);
}
}
/**
* Get the parent group multiplicity for a given XMult
*
* @param xMult multiplicity of the element
* @return parent group xmult
*/
protected String getParentGroupXMult(String xMult) {
if (StringUtils.isEmpty(xMult))
return "1"; //this SHOULD not happen!
int idx = xMult.lastIndexOf(",");
if (idx > 0)
return "1," + xMult.substring(0, idx); //root+parent group
return "1"; //attached to root
}
/**
* Insert property detail data into the database
*
* @param prop thepropery
* @param allData List of all data belonging to this property (for cascaded updates like binaries to avoid duplicates)
* @param con an open and valid connection
* @param ps batch prepared statement for detail inserts
* @param ft fulltext indexer
* @param pk primary key of the content
* @param data the value
* @param isMaxVer is this content in the max. version?
* @param isLiveVer is this content in the live version? @throws SQLException on errors
* @throws FxDbException on errors
* @throws FxUpdateException on errors
* @throws FxNoAccessException for FxNoAccess values
* @throws SQLException on SQL errors
*/
protected void insertPropertyData(FxProperty prop, List<FxData> allData, Connection con,
PreparedStatement ps, FulltextIndexer ft, FxPK pk,
FxPropertyData data, boolean isMaxVer, boolean isLiveVer) throws SQLException, FxDbException, FxUpdateException, FxNoAccessException {
insertPropertyData(prop, allData, con, ps, ft, pk, data, isMaxVer, isLiveVer, false);
}
/**
* Insert property detail data into the database
*
* @param prop thepropery
* @param allData List of all data belonging to this property (for cascaded updates like binaries to avoid duplicates)
* @param con an open and valid connection
* @param ps batch prepared statement for detail inserts
* @param ft fulltext indexer
* @param pk primary key of the content
* @param data the value
* @param isMaxVer is this content in the max. version?
* @param isLiveVer is this content in the live version?
* @param disregardFlatStorageEntry true = do not check if the data is in the flatstorage (contentTypeConversion)
* @throws FxDbException on errors
* @throws FxUpdateException on errors
* @throws FxNoAccessException for FxNoAccess values
* @throws SQLException on SQL errors
*/
private void insertPropertyData(FxProperty prop, List<FxData> allData, Connection con, PreparedStatement ps,
FulltextIndexer ft, FxPK pk, FxPropertyData data, boolean isMaxVer, boolean isLiveVer,
boolean disregardFlatStorageEntry) throws SQLException, FxDbException, FxUpdateException, FxNoAccessException {
if (data == null || data.isEmpty())
return;
if (!disregardFlatStorageEntry) {
if (data.getPropertyAssignment().isFlatStorageEntry()) {
if (ft != null && prop.isFulltextIndexed())
ft.index(data);
return;
}
}
clearPreparedStatement(ps, INSERT_VALUE_POS, INSERT_END_POS);
ps.setLong(15, 0); //FSELECT has to be set to 0 and not null
ps.setLong(1, pk.getId());
ps.setInt(2, pk.getVersion());
ps.setInt(3, data.getPos());
ps.setLong(5, data.getAssignmentId());
// ps.setString(6, "dummy"/*XPathElement.stripType(data.getXPath())*/);
// ps.setString(7, "dummyfull"/*XPathElement.stripType(data.getXPathFull())*/);
String xmult = StringUtils.join(ArrayUtils.toObject(data.getIndices()), ',');
ps.setString(6, xmult);
ps.setInt(7, data.getIndex());
ps.setString(8, getParentGroupXMult(xmult));
ps.setBoolean(9, isMaxVer);
ps.setBoolean(10, isLiveVer);
ps.setBoolean(11, false); //ISGROUP
ps.setLong(13, prop.getId());
// ps.setString(16, "dummyParent"/*XPathElement.stripType(data.getParent().getXPathFull())*/);
ps.setInt(14, data.getIndices().length);
if (!data.getValue().isMultiLanguage()) {
ps.setBoolean(INSERT_LANG_POS, true);
} else
ps.setBoolean(INSERT_ISDEF_LANG_POS, false);
setPropertyData(true, prop, allData, con, data, ps, ft, getUppercaseColumnPos(prop, true), true);
}
/**
* Update a properties data and/or position or a groups position
*
* @param change the change applied
* @param prop the property unless change is a group change
* @param allData all content data unless change is a group change
* @param con an open and valid connection
* @param ps batch prepared statement for detail updates
* @param pk primary key
* @param data property data unless change is a group change
* @throws SQLException on errors
* @throws FxDbException on errors
* @throws FxUpdateException on errors
* @throws FxNoAccessException for FxNoAccess values
*/
protected void updatePropertyData(FxDelta.FxDeltaChange change, FxProperty prop, List<FxData> allData,
Connection con, PreparedStatement ps, FxPK pk, FxPropertyData data)
throws SQLException, FxDbException, FxUpdateException, FxNoAccessException {
if ((change.isProperty() && (data == null || data.isEmpty() || data.getPropertyAssignment().isFlatStorageEntry())) ||
!(change.isDataChange() || change.isPositionChange()))
return;
clearPreparedStatement(ps, 1, UPDATE_ID_POS);
ps.setLong(3, 0); //FSELECT has to be set to 0 and not null!
if (change.isPositionChange())
ps.setInt(UPDATE_POS_POS, change.getNewData().getPos());
else
ps.setInt(UPDATE_POS_POS, change.getOriginalData().getPos());
ps.setLong(UPDATE_ID_POS, pk.getId());
ps.setInt(UPDATE_ID_POS + 1, pk.getVersion());
ps.setLong(UPDATE_ID_POS + 3, change.getNewData().getAssignmentId());
ps.setString(UPDATE_ID_POS + 4, FxArrayUtils.toStringArray(change.getNewData().getIndices(), ','));
if (change.isGroup()) {
ps.setInt(UPDATE_ID_POS + 2, (int) FxLanguage.SYSTEM_ID);
ps.setBoolean(UPDATE_MLDEF_POS, true);
if (batchContentDataChanges())
ps.addBatch();
else
ps.executeUpdate();
return;
}
if (change.isPositionChange() && !change.isDataChange()) {
//just update positions
assert data != null;
for (long lang : data.getValue().getTranslatedLanguages()) {
ps.setInt(UPDATE_ID_POS + 2, (int) lang);
setPropertyData(false, prop, allData, con, data, ps, null, getUppercaseColumnPos(prop, false), false);
}
return;
}
setPropertyData(false, prop, allData, con, data, ps, null, getUppercaseColumnPos(prop, false), true);
}
/**
* Set a properties data for inserts or updates
*
* @param insert perform insert or update?
* @param prop current property
* @param allData all data of the instance (might be needed to buld references, etc.)
* @param con an open and valid connection
* @param data current property data
* @param ps prepared statement for the data table
* @param ft fulltext indexer
* @param upperColumnPos position of the uppercase column (if present, else <code>-1</code>)
* @param includeFullText add fulltext entries? Will be skipped for position only changes
* @throws SQLException on errors
* @throws FxUpdateException on errors
* @throws FxDbException on errors
* @throws FxNoAccessException for FxNoAccess values
*/
private void setPropertyData(boolean insert, FxProperty prop, List<FxData> allData,
Connection con, FxPropertyData data, PreparedStatement ps, FulltextIndexer ft,
int upperColumnPos, boolean includeFullText) throws SQLException, FxUpdateException, FxDbException, FxNoAccessException {
FxValue value = data.getValue();
if (value instanceof FxNoAccess)
throw new FxNoAccessException("ex.content.value.noaccess");
if (value.isMultiLanguage() != ((FxPropertyAssignment) data.getAssignment()).isMultiLang()) {
if (((FxPropertyAssignment) data.getAssignment()).isMultiLang())
throw new FxUpdateException("ex.content.value.invalid.multilanguage.ass.multi", data.getXPathFull());
else
throw new FxUpdateException("ex.content.value.invalid.multilanguage.ass.single", data.getXPathFull());
}
int pos_lang = insert ? INSERT_LANG_POS : UPDATE_ID_POS + 2;
int pos_isdef_lang = insert ? INSERT_ISDEF_LANG_POS : UPDATE_MLDEF_POS;
if (prop.getDataType().isSingleRowStorage()) {
//Data types that just use one db row can be handled in a very similar way
Object translatedValue;
GregorianCalendar gc = null;
for (int i = 0; i < value.getTranslatedLanguages().length; i++) {
translatedValue = value.getTranslation(value.getTranslatedLanguages()[i]);
if (translatedValue == null) {
LOG.warn("Translation for " + data.getXPath() + " is null!");
}
ps.setLong(pos_lang, value.getTranslatedLanguages()[i]);
if (!value.isMultiLanguage())
ps.setBoolean(pos_isdef_lang, true);
else
ps.setBoolean(pos_isdef_lang, value.isDefaultLanguage(value.getTranslatedLanguages()[i]));
if (upperColumnPos != -1)
ps.setString(upperColumnPos, translatedValue.toString().toUpperCase());
int[] pos = insert ? getColumnPosInsert(prop) : getColumnPosUpdate(prop);
switch (prop.getDataType()) {
case Double:
checkDataType(FxDouble.class, value, data.getXPathFull());
ps.setDouble(pos[0], (Double) translatedValue);
break;
case Float:
checkDataType(FxFloat.class, value, data.getXPathFull());
ps.setFloat(pos[0], (Float) translatedValue);
break;
case LargeNumber:
checkDataType(FxLargeNumber.class, value, data.getXPathFull());
ps.setLong(pos[0], (Long) translatedValue);
break;
case Number:
checkDataType(FxNumber.class, value, data.getXPathFull());
ps.setInt(pos[0], (Integer) translatedValue);
break;
case HTML:
checkDataType(FxHTML.class, value, data.getXPathFull());
boolean useTidy = ((FxHTML) value).isTidyHTML();
ps.setBoolean(pos[1], useTidy);
final String extractorInput = doTidy(data.getXPathFull(), (String) translatedValue);
if (useTidy) {
translatedValue = extractorInput;
}
final HtmlExtractor result = new HtmlExtractor(
extractorInput,
true
);
setBigString(ps, pos[2], result.getText());
setBigString(ps, pos[0], (String) translatedValue);
break;
case String1024:
case Text:
checkDataType(FxString.class, value, data.getXPathFull());
setBigString(ps, pos[0], (String) translatedValue);
break;
case Boolean:
checkDataType(FxBoolean.class, value, data.getXPathFull());
ps.setBoolean(pos[0], (Boolean) translatedValue);
break;
case Date:
checkDataType(FxDate.class, value, data.getXPathFull());
if (gc == null) gc = new GregorianCalendar();
gc.setTime((java.util.Date) translatedValue);
//strip all time information, this might not be necessary since ps.setDate() strips them
//for most databases but won't hurt either ;)
gc.set(GregorianCalendar.HOUR, 0);
gc.set(GregorianCalendar.MINUTE, 0);
gc.set(GregorianCalendar.SECOND, 0);
gc.set(GregorianCalendar.MILLISECOND, 0);
ps.setDate(pos[0], new java.sql.Date(gc.getTimeInMillis()));
break;
case DateTime:
checkDataType(FxDateTime.class, value, data.getXPathFull());
if (gc == null) gc = new GregorianCalendar();
gc.setTime((java.util.Date) translatedValue);
ps.setTimestamp(pos[0], new Timestamp(gc.getTimeInMillis()));
break;
case DateRange:
checkDataType(FxDateRange.class, value, data.getXPathFull());
if (gc == null) gc = new GregorianCalendar();
gc.setTime(((DateRange) translatedValue).getLower());
gc.set(GregorianCalendar.HOUR, 0);
gc.set(GregorianCalendar.MINUTE, 0);
gc.set(GregorianCalendar.SECOND, 0);
gc.set(GregorianCalendar.MILLISECOND, 0);
ps.setDate(pos[0], new java.sql.Date(gc.getTimeInMillis()));
gc.setTime(((DateRange) translatedValue).getUpper());
gc.set(GregorianCalendar.HOUR, 0);
gc.set(GregorianCalendar.MINUTE, 0);
gc.set(GregorianCalendar.SECOND, 0);
gc.set(GregorianCalendar.MILLISECOND, 0);
ps.setDate(pos[1], new java.sql.Date(gc.getTimeInMillis()));
break;
case DateTimeRange:
checkDataType(FxDateTimeRange.class, value, data.getXPathFull());
if (gc == null) gc = new GregorianCalendar();
gc.setTime(((DateRange) translatedValue).getLower());
ps.setTimestamp(pos[0], new Timestamp(gc.getTimeInMillis()));
gc.setTime(((DateRange) translatedValue).getUpper());
ps.setTimestamp(pos[1], new Timestamp(gc.getTimeInMillis()));
break;
case Binary:
checkDataType(FxBinary.class, value, data.getXPathFull());
BinaryDescriptor binary = (BinaryDescriptor) translatedValue;
if (!binary.isNewBinary()) {
ps.setLong(pos[0], binary.getId());
} else {
try {
//transfer the binary from the transit table to the binary table
BinaryDescriptor created = binaryStorage.binaryTransit(con, binary);
ps.setLong(pos[0], created.getId());
//check all other properties if they contain the same handle
//and replace with the data of the new binary
for (FxData _curr : allData) {
if (_curr instanceof FxPropertyData && !_curr.isEmpty() &&
((FxPropertyData) _curr).getValue() instanceof FxBinary) {
FxBinary _val = (FxBinary) ((FxPropertyData) _curr).getValue();
_val._replaceHandle(binary.getHandle(), created);
}
}
} catch (FxApplicationException e) {
throw new FxDbException(e);
}
}
break;
case SelectOne:
checkDataType(FxSelectOne.class, value, data.getXPathFull());
ps.setLong(pos[0], ((FxSelectListItem) translatedValue).getId());
break;
case SelectMany:
checkDataType(FxSelectMany.class, value, data.getXPathFull());
SelectMany sm = (SelectMany) translatedValue;
for (int i1 = 0; i1 < sm.getSelected().size(); i1++) {
FxSelectListItem item = sm.getSelected().get(i1);
if (i1 > 0) {
if (batchContentDataChanges())
ps.addBatch();
else
ps.executeUpdate();
}
ps.setLong(pos[0], item.getId());
ps.setString(pos[1], sm.getSelectedIdsList());
ps.setLong(pos[2], sm.getSelectedIds().size());
}
if (sm.getSelected().size() == 0)
ps.setLong(pos[0], 0); //write the virtual item as a marker to have a valid row
break;
case Reference:
//reference integrity check is done prior to saving
ps.setLong(pos[0], ((FxPK) translatedValue).getId());
break;
case InlineReference:
default:
throw new FxDbException(LOG, "ex.db.notImplemented.store", prop.getDataType().getName());
}
int valueDataPos = insert ? getValueDataInsertPos(prop.getDataType()) : getValueDataUpdatePos(prop.getDataType());
if (value.hasValueData()) {
ps.setInt(valueDataPos, value.getValueDataRaw());
} else
ps.setNull(valueDataPos, java.sql.Types.NUMERIC);
if (batchContentDataChanges())
ps.addBatch();
else {
try {
ps.executeUpdate();
} catch (SQLException e) {
LOG.error(prop.getName(), e);
throw e;
}
}
}
} else {
switch (prop.getDataType()) {
//TODO: implement datatype specific insert
default:
throw new FxDbException(LOG, "ex.db.notImplemented.store", prop.getDataType().getName());
}
}
if (ft != null && prop.isFulltextIndexed() && includeFullText)
ft.index(data);
}
/**
* Check if a referenced id is of an expected type and exists
*
* @param con an open and valid connection
* @param expectedType the expected type
* @param ref referenced content
* @param xpath the XPath this reference is for (used for error messages only)
* @throws FxDbException if not exists or wrong type
*/
private static void checkReference(Connection con, FxType expectedType, FxPK ref, String xpath) throws FxDbException {
PreparedStatement ps = null;
try {
ps = con.prepareStatement(CONTENT_GET_TYPE);
ps.setLong(1, ref.getId());
ResultSet rs = ps.executeQuery();
if (rs == null || !rs.next())
throw new FxDbException("ex.content.reference.notFound", ref, xpath);
long type = rs.getLong(1);
if (type != expectedType.getId())
throw new FxDbException("ex.content.value.invalid.reftype", expectedType, CacheAdmin.getEnvironment().getType(type));
} catch (SQLException e) {
throw new FxDbException(e, "ex.db.sqlError", e.getMessage());
} finally {
if (ps != null)
try {
ps.close();
} catch (SQLException e) {
//ignore
}
}
}
/**
* Check if the given value is of the expected class
*
* @param dataClass expected class
* @param value value to check
* @param XPath xpath with full indices for error message
* @throws FxDbException if the class does not match
*/
private static void checkDataType(Class dataClass, FxValue value, String XPath) throws FxDbException {
if (!(value.getClass().getSimpleName().equals(dataClass.getSimpleName()))) {
throw new FxDbException("ex.content.value.invalid.class", value.getClass().getSimpleName(), XPath, dataClass.getSimpleName());
}
}
/**
* Run tidy on the given content
*
* @param XPath XPath with full indices for error messages
* @param content the string to tidy
* @return tidied string
* @throws FxUpdateException if tidy failed
*/
protected static String doTidy(String XPath, String content) throws FxUpdateException {
Tidy tidy = new Tidy();
ByteArrayOutputStream out = new ByteArrayOutputStream();
tidy.setDropEmptyParas(true);
tidy.setMakeClean(true);
tidy.setHideEndTags(true);
tidy.setTidyMark(false);
tidy.setMakeBare(true);
tidy.setXHTML(true);
// tidy.setOnlyErrors(true);
tidy.setShowWarnings(false);
tidy.setQuiet(true);
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
tidy.setErrout(pw);
tidy.parse(new StringReader(content), out);
if (tidy.getParseErrors() > 0) {
String error = sw.getBuffer().toString();
throw new FxUpdateException("ex.content.value.tidy.failed", XPath, error);
}
content = out.toString();
return content;
}
/**
* Insert group detail data into the database
*
* @param con an open and valid connection
* @param sql an optional StringBuffer
* @param pk primary key of the content
* @param groupData the group
* @param isMaxVer is this content in the max. version?
* @param isLiveVer is this content in the live version?
* @throws SQLException on errors
*/
protected void insertGroupData(Connection con, StringBuilder sql, FxPK pk, FxGroupData groupData,
boolean isMaxVer, boolean isLiveVer) throws SQLException {
if (groupData == null || (groupData.isEmpty() && groupData.isRemoveable()))
return;
PreparedStatement ps = null;
if (sql == null)
sql = new StringBuilder(500);
else
sql.setLength(0);
try {
sql.append("INSERT INTO ").append(TBL_CONTENT_DATA).
// 1 2 3 4 5 6 7 8 9 10 11 12 13 14
append(" (ID,VER,POS,LANG,ASSIGN,XMULT,XINDEX,PARENTXMULT,ISMAX_VER,ISLIVE_VER,ISGROUP,ISMLDEF,XDEPTH,FSELECT");
sql.append(")VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
ps = con.prepareStatement(sql.toString());
ps.setLong(1, pk.getId());
ps.setInt(2, pk.getVersion());
ps.setInt(3, groupData.getPos());
ps.setInt(4, (int) FxLanguage.SYSTEM_ID);
ps.setLong(5, groupData.getAssignmentId());
// ps.setString(6, "dummyGrp"/*groupData.getXPath() + "/"*/);
// ps.setString(7, "dummyGrpFull"/*groupData.getXPathFull() + "/"*/);
final String xmult = StringUtils.join(ArrayUtils.toObject(groupData.getIndices()), ',');
ps.setString(6, xmult);
ps.setInt(7, groupData.getIndex());
ps.setString(8, getParentGroupXMult(xmult));
ps.setBoolean(9, isMaxVer);
ps.setBoolean(10, isLiveVer);
// ps.setString(13, "dummyGrpParent"/*groupData.getParent().getXPathFull()*/);
ps.setBoolean(11, true);
ps.setBoolean(12, false);
ps.setInt(13, groupData.getIndices().length);
ps.setLong(14, 0); //FSELECT
ps.executeUpdate();
} finally {
if (ps != null)
ps.close();
}
}
/**
* Remove a detail data entry (group or property, in all existing languages)
*
* @param con an open and valid Connection
* @param sql sql
* @param pk primary key
* @param data the entry to remove
* @throws SQLException on errors
*/
private void deleteDetailData(Connection con, StringBuilder sql, FxPK pk, FxData data) throws SQLException {
if (data == null || data.isEmpty())
return;
if (data.isProperty())
if (((FxPropertyData) data).getPropertyAssignment().isFlatStorageEntry()) {
FxFlatStorageManager.getInstance().deletePropertyData(con, pk, ((FxPropertyData) data));
return;
}
PreparedStatement ps = null;
if (sql == null)
sql = new StringBuilder(500);
else
sql.setLength(0);
try {
// 1 2 3 4
sql.append("DELETE FROM ").append(TBL_CONTENT_DATA).append(" WHERE ID=? AND VER=? AND ASSIGN=? AND XMULT=?");
ps = con.prepareStatement(sql.toString());
ps.setLong(1, pk.getId());
ps.setInt(2, pk.getVersion());
ps.setLong(3, data.getAssignmentId());
ps.setString(4, FxArrayUtils.toStringArray(data.getIndices(), ','));
ps.executeUpdate();
} finally {
if (ps != null)
ps.close();
}
}
/**
* {@inheritDoc}
*/
public FxContent contentLoad(Connection con, FxPK pk, FxEnvironment env, StringBuilder sql) throws FxLoadException, FxInvalidParameterException, FxNotFoundException {
if (pk.isNew())
throw new FxInvalidParameterException("pk", "ex.content.load.newPK");
if (sql == null)
sql = new StringBuilder(1000);
sql.append(CONTENT_MAIN_LOAD);
sql.append(" WHERE ID=? AND ");
if (pk.isDistinctVersion())
sql.append(" VER=?");
else if (pk.getVersion() == FxPK.LIVE)
sql.append(" ISLIVE_VER=?");
else if (pk.getVersion() == FxPK.MAX)
sql.append(" ISMAX_VER=?");
PreparedStatement ps = null;
FxPK contentPK, sourcePK = null, destinationPK = null;
int srcPos = 0, dstPos = 0;
Connection conNoTX = null;
try {
ps = con.prepareStatement(sql.toString());
ps.setLong(1, pk.getId());
if (pk.isDistinctVersion())
ps.setInt(2, pk.getVersion());
else
ps.setBoolean(2, true);
ResultSet rs = ps.executeQuery();
if (rs == null || !rs.next())
throw new FxNotFoundException("ex.content.notFound", pk);
contentPK = new FxPK(rs.getLong(1), rs.getInt(2));
FxType type = env.getType(rs.getLong(3));
final long aclId = rs.getLong(4);
Step step = env.getStep(rs.getLong(5));
Mandator mand = env.getMandator(rs.getInt(22));
if (!type.getAssignmentsForDataType(FxDataType.Binary).isEmpty()) {
conNoTX = Database.getNonTXDataSource().getConnection();
}
FxGroupData root = loadDetails(con, conNoTX, type, env, contentPK, pk.getVersion());
rs.getLong(12);
if (!rs.wasNull()) {
sourcePK = new FxPK(rs.getLong(12), rs.getInt(13));
destinationPK = new FxPK(rs.getLong(14), rs.getInt(15));
srcPos = rs.getInt(16);
dstPos = rs.getInt(17);
}
FxLock lock = StorageManager.getLockStorage().getLock(con, contentPK);
FxContent content = new FxContent(contentPK, lock, type.getId(), type.isRelation(), mand.getId(),
aclId != ACL.NULL_ACL_ID ? aclId : -1,
step.getId(), rs.getInt(6),
rs.getInt(7), rs.getBoolean(10), rs.getInt(11), sourcePK, destinationPK, srcPos, dstPos,
LifeCycleInfoImpl.load(rs, 18, 19, 20, 21), root, rs.getLong(23), rs.getLong(24)).initSystemProperties();
if (rs.next())
throw new FxLoadException("ex.content.load.notDistinct", pk);
if (type.isMultipleContentACLs() && aclId == ACL.NULL_ACL_ID) {
content.setAclIds(loadContentAclTable(con, content.getPk()));
}
return content;
} catch (SQLException e) {
throw new FxLoadException(LOG, e, "ex.db.sqlError", e.getMessage());
} catch (FxDbException e) {
throw new FxLoadException(e);
} catch (FxLockException e) {
throw new FxLoadException(e);
} finally {
Database.closeObjects(GenericHierarchicalStorage.class, conNoTX, ps);
}
}
protected List<Long> loadContentAclTable(Connection con, FxPK pk) throws SQLException {
if (pk.getVersion() < 0) {
throw new IllegalArgumentException("No distinct version number given in PK " + pk);
}
PreparedStatement ps = null;
try {
ps = con.prepareStatement(CONTENT_ACLS_LOAD);
ps.setLong(1, pk.getId());
ps.setInt(2, pk.getVersion());
final ResultSet rs = ps.executeQuery();
final List<Long> aclIds = Lists.newArrayList();
while (rs.next()) {
aclIds.add(rs.getLong(1));
}
return aclIds;
} finally {
Database.closeObjects(GenericHierarchicalStorage.class, null, ps);
}
}
/**
* Load all detail entries for a content instance
*
* @param con open and valid(!) connection
* @param conNoTX a non-transactional connection (only used if the content contains binary properties)
* @param type FxType used
* @param env FxEnvironment
* @param pk primary key of the content data to load
* @param requestedVersion the originally requested version (LIVE, MAX or specific version number, needed to resolve references since the pk's version is resolved already)
* @return a (root) group containing all data
* @throws com.flexive.shared.exceptions.FxLoadException
* on errors
* @throws SQLException on errors
* @throws FxInvalidParameterException on errors
* @throws FxDbException on errors
*/
@SuppressWarnings("unchecked")
protected FxGroupData loadDetails(Connection con, Connection conNoTX, FxType type, FxEnvironment env, FxPK pk, int requestedVersion) throws FxLoadException, SQLException, FxInvalidParameterException, FxDbException {
FxGroupData root;
PreparedStatement ps = null;
try {
root = type.createEmptyData(type.buildXPathPrefix(pk));
// root.removeEmptyEntries(true);
// root.compactPositions(true);
root.removeNonInternalData();
ps = con.prepareStatement(CONTENT_DATA_LOAD);
ps.setLong(1, pk.getId());
ps.setInt(2, pk.getVersion());
ResultSet rs = ps.executeQuery();
String currXPath = null;
int currXDepth = 0;
FxAssignment currAssignment = null, thisAssignment = null;
int currPos = -1;
long currLang;
long defLang = FxLanguage.SYSTEM_ID;
boolean isGroup = true;
boolean isMLDef;
boolean multiLang = false;
String currXMult;
FxValue currValue = null;
String[] columns = null;
List<ServerLocation> server = CacheAdmin.getStreamServers();
//load flat columns
FxFlatStorageLoadContainer flatContainer = type.isContainsFlatStorageAssignments()
? FxFlatStorageManager.getInstance().loadContent(this, con, type.getId(), pk, requestedVersion)
: null;
while (rs != null && rs.next()) {
if (thisAssignment == null || thisAssignment.getId() != rs.getLong(3)) {
//new data type
thisAssignment = env.getAssignment(rs.getLong(3));
}
currXMult = rs.getString(4);
if (currXPath != null && !currXPath.equals(XPathElement.toXPathMult(thisAssignment.getXPath(), currXMult))) {
//add this property
if (!isGroup) {
currValue.setDefaultLanguage(defLang);
if (flatContainer != null) {
//add flat entries that are positioned before the current entry
FxFlatStorageLoadColumn flatColumn;
while ((flatColumn = flatContainer.pop(currXPath.substring(0, currXPath.lastIndexOf('/') + 1), currXDepth, currPos)) != null) {
addValue(root, flatColumn.getXPath(), flatColumn.getAssignment(), flatColumn.getPos(),
flatColumn.getValue());
}
}
}
addValue(root, currXPath, currAssignment, currPos, currValue);
currValue = null;
defLang = FxLanguage.SYSTEM_ID;
}
//read next row
currPos = rs.getInt(1);
currLang = rs.getInt(2);
isMLDef = rs.getBoolean(6);
isGroup = rs.getBoolean(5);
if( currAssignment == null || currAssignment.getId() != thisAssignment.getId()) {
currAssignment = thisAssignment;
if (!isGroup)
columns = getColumns(((FxPropertyAssignment) currAssignment).getProperty());
}
currXPath = XPathElement.toXPathMult(currAssignment.getXPath(), currXMult);
if (flatContainer != null) {
//calculate xdepth
currXDepth = 1;
for (char c : currXMult.toCharArray())
if (c == ',') currXDepth++;
}
if (!isGroup) {
final FxPropertyAssignment propAssignment = (FxPropertyAssignment) currAssignment;
FxDataType dataType = propAssignment.getProperty().getDataType();
if (currValue == null)
multiLang = propAssignment.isMultiLang();
switch (dataType) {
case Float:
if (currValue == null)
currValue = new FxFloat(multiLang, currLang, rs.getFloat(columns[0]));
else
currValue.setTranslation(currLang, rs.getFloat(columns[0]));
break;
case Double:
if (currValue == null)
currValue = new FxDouble(multiLang, currLang, rs.getDouble(columns[0]));
else
currValue.setTranslation(currLang, rs.getDouble(columns[0]));
break;
case LargeNumber:
if (currValue == null)
currValue = new FxLargeNumber(multiLang, currLang, rs.getLong(columns[0]));
else
currValue.setTranslation(currLang, rs.getLong(columns[0]));
break;
case Number:
if (currValue == null)
currValue = new FxNumber(multiLang, currLang, rs.getInt(columns[0]));
else
currValue.setTranslation(currLang, rs.getInt(columns[0]));
break;
case HTML:
if (currValue == null) {
currValue = new FxHTML(multiLang, currLang, rs.getString(columns[0]));
((FxHTML) currValue).setTidyHTML(rs.getBoolean(columns[1]));
} else
currValue.setTranslation(currLang, rs.getString(columns[0]));
break;
case String1024:
case Text:
if (currValue == null) {
currValue = new FxString(multiLang, currLang, rs.getString(columns[0]));
if (propAssignment.hasMaxLength()) {
currValue.setMaxInputLength(propAssignment.getMaxLength());
if (dataType == FxDataType.String1024 && currValue.getMaxInputLength() > 1024)
currValue.setMaxInputLength(1024);
} else if (dataType == FxDataType.String1024)
currValue.setMaxInputLength(1024);
} else
currValue.setTranslation(currLang, rs.getString(columns[0]));
break;
case Boolean:
if (currValue == null)
currValue = new FxBoolean(multiLang, currLang, rs.getBoolean(columns[0]));
else
currValue.setTranslation(currLang, rs.getBoolean(columns[0]));
break;
case Date:
if (currValue == null)
currValue = new FxDate(multiLang, currLang, rs.getDate(columns[0]));
else
currValue.setTranslation(currLang, rs.getDate(columns[0]));
break;
case DateTime:
if (currValue == null)
currValue = new FxDateTime(multiLang, currLang, new Date(rs.getTimestamp(columns[0]).getTime()));
else
currValue.setTranslation(currLang, new Date(rs.getTimestamp(columns[0]).getTime()));
break;
case DateRange:
if (currValue == null)
currValue = new FxDateRange(multiLang, currLang,
new DateRange(
rs.getDate(columns[0]),
rs.getDate(getColumns(((FxPropertyAssignment) currAssignment).getProperty())[1]))
);
else
currValue.setTranslation(currLang,
new DateRange(
rs.getDate(columns[0]),
rs.getDate(getColumns(((FxPropertyAssignment) currAssignment).getProperty())[1]))
);
break;
case DateTimeRange:
if (currValue == null)
currValue = new FxDateTimeRange(multiLang, currLang,
new DateRange(
new Date(rs.getTimestamp(columns[0]).getTime()),
new Date(rs.getTimestamp(getColumns(((FxPropertyAssignment) currAssignment).getProperty())[1]).getTime()))
);
else
currValue.setTranslation(currLang,
new DateRange(
new Date(rs.getTimestamp(columns[0]).getTime()),
new Date(rs.getTimestamp(getColumns(((FxPropertyAssignment) currAssignment).getProperty())[1]).getTime()))
);
break;
case Binary:
BinaryDescriptor desc = binaryStorage.loadBinaryDescriptor(server, conNoTX, rs.getLong(columns[0]));
if (currValue == null)
currValue = new FxBinary(multiLang, currLang, desc);
else
currValue.setTranslation(currLang, desc);
break;
case SelectOne:
FxSelectListItem singleItem = env.getSelectListItem(rs.getLong(columns[0]));
if (currValue == null)
currValue = new FxSelectOne(multiLang, currLang, singleItem);
else
currValue.setTranslation(currLang, singleItem);
break;
case SelectMany:
long itemId = rs.getLong(columns[0]);
FxSelectList list = ((FxPropertyAssignment) currAssignment).getProperty().getReferencedList();
if (currValue == null)
currValue = new FxSelectMany(multiLang, currLang, new SelectMany(list));
FxSelectMany sm = (FxSelectMany) currValue;
if (sm.isTranslationEmpty(currLang))
sm.setTranslation(currLang, new SelectMany(list));
if (itemId > 0)
sm.getTranslation(currLang).selectItem(list.getItem(itemId));
break;
case Reference:
if (currValue == null)
// currValue = new FxReference(multiLang, currLang, new ReferencedContent(rs.getLong(columns[0])));
currValue = new FxReference(multiLang, currLang, resolveReference(con, requestedVersion, rs.getLong(columns[0])));
else
currValue.setTranslation(currLang, resolveReference(con, requestedVersion, rs.getLong(columns[0])));
break;
default:
throw new FxDbException(LOG, "ex.db.notImplemented.load", dataType.getName());
}
if (currValue != null) {
int valueData = rs.getInt(getValueDataLoadPos(dataType));
if (rs.wasNull())
currValue.clearValueData();
else
currValue.setValueData(valueData);
}
if (isMLDef)
defLang = currLang;
}
}
if (currValue != null) {
if (flatContainer != null) {
//add flat entries that are positioned before the current entry
FxFlatStorageLoadColumn flatColumn;
while ((flatColumn = flatContainer.pop(currXPath.substring(0, currXPath.lastIndexOf('/') + 1), currXDepth, currPos)) != null) {
addValue(root, flatColumn.getXPath(), flatColumn.getAssignment(), flatColumn.getPos(),
flatColumn.getValue());
}
}
//add last property
if (!isGroup)
currValue.setDefaultLanguage(defLang);
addValue(root, currXPath, currAssignment, currPos, currValue);
} else {
if (flatContainer == null && isGroup && currAssignment != null) //make sure to add the last assignment if it is a group and no flat storage is enabled
addValue(root, currXPath, currAssignment, currPos, currValue);
}
if (flatContainer != null) {
if (isGroup && currAssignment != null) //if the last value was a group, add it (can only happen when using a flat storage)
addValue(root, currXPath, currAssignment, currPos, currValue);
//add remaining flat entries
FxFlatStorageLoadColumn flatColumn;
while ((flatColumn = flatContainer.pop()) != null) {
addValue(root, flatColumn.getXPath(), flatColumn.getAssignment(), flatColumn.getPos(),
flatColumn.getValue());
}
}
} catch (FxCreateException e) {
throw new FxLoadException(e);
} catch (FxNotFoundException e) {
throw new FxLoadException(e);
} finally {
if (ps != null)
ps.close();
}
return root;
}
/**
* {@inheritDoc}
*/
public ReferencedContent resolveReference(Connection con, int contentVersion, long referencedId) throws SQLException {
String sql = contentVersion == FxPK.LIVE ? CONTENT_REFERENCE_LIVE : CONTENT_REFERENCE_MAX;
PreparedStatement ps = null;
int referencedVersion;
long stepId, aclId, typeId, ownerId;
String caption;
try {
ps = con.prepareStatement(sql);
ps.setLong(1, referencedId);
ps.setBoolean(2, true);
ResultSet rs = ps.executeQuery();
if (rs != null && rs.next()) {
referencedVersion = rs.getInt(1);
aclId = rs.getLong(2);
stepId = rs.getLong(3);
typeId = rs.getLong(4);
ownerId = rs.getLong(5);
} else if (contentVersion == FxPK.LIVE) {
ps.close();
ps = con.prepareStatement(CONTENT_REFERENCE_MAX);
ps.setLong(1, referencedId);
ps.setBoolean(2, true);
rs = ps.executeQuery();
if (rs != null && rs.next()) {
referencedVersion = rs.getInt(1);
aclId = rs.getLong(2);
stepId = rs.getLong(3);
typeId = rs.getLong(4);
ownerId = rs.getLong(5);
} else {
LOG.error("Failed to resolve a reference with id " + referencedId + ": no max. version found! (in fallback already!)");
return new ReferencedContent(referencedId);
}
} else {
LOG.error("Failed to resolve a reference with id " + referencedId + ": no max. version found!");
return new ReferencedContent(referencedId);
}
ps.close();
ps = con.prepareStatement(CONTENT_REFERENCE_CAPTION);
ps.setLong(1, referencedId);
ps.setInt(2, referencedVersion);
try {
ps.setLong(3, EJBLookup.getConfigurationEngine().get(SystemParameters.TREE_CAPTION_PROPERTY));
} catch (FxApplicationException e) {
throw e.asRuntimeException();
}
rs = ps.executeQuery();
if (rs != null && rs.next())
caption = rs.getString(1);
else
caption = "";
// resolve ACLs from ACL table, if necessary
FxEnvironment env = CacheAdmin.getEnvironment();
final FxPK pk = new FxPK(referencedId, referencedVersion);
final List<ACL> acls;
if (aclId == ACL.NULL_ACL_ID) {
// multiple ACLs for this content instance
acls = FxSharedUtils.filterSelectableObjectsById(env.getACLs(), loadContentAclTable(con, pk));
} else {
// only one ACL
acls = Arrays.asList(env.getACL(aclId));
}
ReferencedContent ref = new ReferencedContent(pk, caption, env.getStep(stepId), acls);
try {
ref.setAccessGranted(
FxPermissionUtils.checkPermission(
FxContext.getUserTicket(),
ownerId, ACLPermission.READ,
env.getType(typeId),
ref.getStep().getAclId(),
FxSharedUtils.getSelectableObjectIdList(acls),
false));
} catch (FxNoAccessException e) {
ref.setAccessGranted(false);
}
if (LOG.isDebugEnabled()) {
LOG.debug("ReferencedContent: " + ref.toStringExtended());
}
return ref;
} finally {
if (ps != null)
ps.close();
}
}
/**
* {@inheritDoc}
*/
public long getContentTypeId(Connection con, FxPK pk) throws FxLoadException {
PreparedStatement ps = null;
try {
ps = con.prepareStatement("SELECT DISTINCT TDEF FROM " + TBL_CONTENT + " WHERE ID=?");
ps.setLong(1, pk.getId());
ResultSet rs = ps.executeQuery();
if (rs != null && rs.next())
return rs.getLong(1);
throw new FxLoadException("ex.content.notFound", pk);
} catch (SQLException e) {
throw new FxLoadException(e, "ex.db.sqlError", e.getMessage());
} finally {
try {
if (ps != null)
ps.close();
} catch (SQLException e) {
LOG.error(e);
}
}
}
/**
* {@inheritDoc}
*/
public String getBinaryMetaData(Connection con, long binaryId) {
return binaryStorage.getBinaryMetaData(con, binaryId);
}
/**
* Helper method to add a value of a detail entry with a given XPath to the instance being loaded
*
* @param root the root group
* @param xPath XPath of the entry
* @param assignment assignment used
* @param pos position in hierarchy
* @param value the value to add
* @throws FxInvalidParameterException on errors
* @throws FxNotFoundException on errors
* @throws FxCreateException if failed to create group entries
*/
protected void addValue(FxGroupData root, String xPath, FxAssignment assignment,
int pos, FxValue value) throws FxInvalidParameterException, FxNotFoundException, FxCreateException {
if (!assignment.isEnabled())
return;
if (assignment instanceof FxGroupAssignment) {
root.addGroup(xPath, (FxGroupAssignment) assignment, pos);
root.getGroup(xPath).removeNonInternalData();
} else {
root.addProperty(xPath, (FxPropertyAssignment) assignment, value, pos);
}
}
/**
* {@inheritDoc}
*/
public FxPK contentSave(Connection con, FxEnvironment env, StringBuilder sql, FxContent content, long fqnPropertyId) throws FxInvalidParameterException, FxUpdateException, FxNoAccessException {
content.getRootGroup().removeEmptyEntries();
content.getRootGroup().compactPositions(true);
content.checkValidity();
FxPK pk = content.getPk();
if (pk.isNew() || !pk.isDistinctVersion())
throw new FxInvalidParameterException("PK", "ex.content.pk.invalid.save", pk);
FxDelta delta;
FxContent original;
final FxType type = env.getType(content.getTypeId());
final UserTicket ticket = FxContext.getUserTicket();
try {
original = contentLoad(con, content.getPk(), env, sql);
original.getRootGroup().removeEmptyEntries();
original.getRootGroup().compactPositions(true);
//unwrap all no access values so they can be saved
if (type.isUsePropertyPermissions() && !ticket.isGlobalSupervisor()) {
FxContext.get().runAsSystem();
try {
FxPermissionUtils.unwrapNoAccessValues(content, original);
} finally {
FxContext.get().stopRunAsSystem();
}
}
delta = FxDelta.processDelta(original, content);
} catch (FxLoadException e) {
throw new FxUpdateException(e);
} catch (FxNotFoundException e) {
throw new FxUpdateException(e);
}
if (original.getStepId() != content.getStepId()) {
Workflow wf = env.getWorkflow(env.getStep(content.getStepId()).getWorkflowId());
if (!wf.isRouteValid(original.getStepId(), content.getStepId())) {
throw new FxInvalidParameterException("STEP", "ex.content.step.noRoute",
env.getStepDefinition(env.getStep(original.getStepId()).getStepDefinitionId()).getLabel().getBestTranslation(),
env.getStepDefinition(env.getStep(content.getStepId()).getStepDefinitionId()).getLabel().getBestTranslation());
}
if (type.isTrackHistory())
EJBLookup.getHistoryTrackerEngine().track(type, content.getPk(), null, "history.content.step.change",
env.getStepDefinition(env.getStep(original.getStepId()).getStepDefinitionId()).getName(),
env.getStepDefinition(env.getStep(content.getStepId()).getStepDefinitionId()).getName());
}
if (!delta.changes()) {
if (LOG.isDebugEnabled()) {
LOG.debug("====== NO CHANGES =======");
}
return pk;
} else {
if (LOG.isDebugEnabled()) {
LOG.debug(delta.dump());
}
}
FulltextIndexer ft = getFulltextIndexer(pk, con);
FxFlatStorage fs = type.isContainsFlatStorageAssignments() ? FxFlatStorageManager.getInstance() : null;
if (type.isUsePropertyPermissions() && !ticket.isGlobalSupervisor())
FxPermissionUtils.checkPropertyPermissions(content.getLifeCycleInfo().getCreatorId(), delta, ACLPermission.EDIT);
lockTables(con, pk.getId(), pk.getVersion());
if (delta.isInternalPropertyChanged())
updateMainEntry(con, content);
try {
disableDetailUniqueChecks(con);
//full replace code start
// removeDetailEntriesVersion(con, pk);
// createDetailEntries(con, env, sql, pk, content.isMaxVersion(), content.isLiveVersion(), content.getData("/"));
//full replace code end
boolean checkScripting = type.hasScriptedAssignments();
FxScriptBinding binding = null;
ScriptingEngine scripting = null;
if (checkScripting) {
scripting = EJBLookup.getScriptingEngine();
binding = new FxScriptBinding();
binding.setVariable("content", content);
}
//before... scripts
if (checkScripting) {
//delta-deletes:
for (FxDelta.FxDeltaChange change : delta.getRemoves()) {
for (long scriptId : change.getOriginalData().getAssignment().
getScriptMapping(FxScriptEvent.BeforeDataChangeDelete)) {
binding.setVariable("change", change);
scripting.runScript(scriptId, binding);
}
}
//delta-updates:
for (FxDelta.FxDeltaChange change : delta.getUpdates()) {
for (long scriptId : change.getOriginalData().getAssignment().
getScriptMapping(FxScriptEvent.BeforeDataChangeUpdate)) {
binding.setVariable("change", change);
scripting.runScript(scriptId, binding);
}
}
//delta-adds:
for (FxDelta.FxDeltaChange change : delta.getAdds()) {
for (long scriptId : change.getNewData().getAssignment().
getScriptMapping(FxScriptEvent.BeforeDataChangeAdd)) {
binding.setVariable("change", change);
scripting.runScript(scriptId, binding);
}
}
//reprocess deltas incase scripts performed any changes to data
delta = FxDelta.processDelta(original, content);
}
//delta-deletes:
for (FxDelta.FxDeltaChange change : delta.getRemoves()) {
if (type.isUsePropertyPermissions() && change.isProperty()) {
final ACL deltaACL = type.getPropertyAssignment(change.getXPath()).getACL();
if (!ticket.mayDeleteACL(deltaACL.getId(), content.getLifeCycleInfo().getCreatorId()))
throw new FxNoAccessException("ex.acl.noAccess.property.delete", deltaACL.getDisplayName(), change.getXPath());
}
if (!change.getOriginalData().isSystemInternal()) {
deleteDetailData(con, sql, pk, change.getOriginalData());
if( change.isProperty() ) {
//check if the removed property is a FQN
if (((FxPropertyData) change.getOriginalData()).getPropertyId() == fqnPropertyId) {
syncFQNName(con, content, pk, change);
}
}
if (fs != null && change.isFlatStorageChange())
fs.deletePropertyData(con, pk, (FxPropertyData) change.getOriginalData());
ft.index(change);
}
}
//flatstorage adds/updates
if (fs != null && delta.getFlatStorageAddsUpdates().size() > 0)
fs.setPropertyData(con, pk, type.getId(), content.getStepId(), content.isMaxVersion(),
content.isLiveVersion(), delta.getFlatStorageAddsUpdates());
//delta-updates:
List<FxDelta.FxDeltaChange> updatesRemaining = new ArrayList<FxDelta.FxDeltaChange>(delta.getUpdates());
PreparedStatement ps_insert = null;
PreparedStatement ps_update = null;
try {
ps_insert = con.prepareStatement(CONTENT_DATA_INSERT);
ps_update = con.prepareStatement(CONTENT_DATA_UPDATE);
while (updatesRemaining.size() > 0) {
FxDelta.FxDeltaChange change = updatesRemaining.get(0);
//noinspection CaughtExceptionImmediatelyRethrown
try {
if (!change.getOriginalData().isSystemInternal()) {
if (change.isGroup()) {
if (change.isPositionChange() && !change.isDataChange()) {
//groups can only change position
updatePropertyData(change, null, null, con, ps_update, pk, null);
}
} else {
FxProperty prop = env.getProperty(((FxPropertyData) change.getNewData()).getPropertyId());
if (!change._isUpdateable()) {
deleteDetailData(con, sql, pk, change.getOriginalData());
insertPropertyData(prop, content.getData("/"), con, ps_insert, null, pk,
((FxPropertyData) change.getNewData()),
content.isMaxVersion(), content.isLiveVersion());
} else {
updatePropertyData(change, prop, content.getData("/"), con, ps_update, pk, ((FxPropertyData) change.getNewData()));
}
//check if the property changed is a FQN
if (prop.getId() == fqnPropertyId) {
syncFQNName(con, content, pk, change);
}
}
}
updatesRemaining.remove(0);
ft.index(change);
} catch (SQLException e) {
change._increaseRetries();
if (change._getRetryCount() > 100)
throw e;
updatesRemaining.remove(0);
updatesRemaining.add(change); //add as last
}
}
//delta-adds:
for (FxDelta.FxDeltaChange change : delta.getAdds()) {
if (type.isUsePropertyPermissions() && change.isProperty()) {
final ACL acl = type.getPropertyAssignment(change.getXPath()).getACL();
if (!ticket.mayCreateACL(acl.getId(), content.getLifeCycleInfo().getCreatorId()))
throw new FxNoAccessException("ex.acl.noAccess.property.create", acl.getDisplayName(), change.getXPath());
}
if (!change.getNewData().isSystemInternal()) {
if (change.isGroup())
insertGroupData(con, sql, pk, (FxGroupData) change.getNewData(), content.isMaxVersion(), content.isLiveVersion());
else {
final FxProperty prop = env.getProperty(((FxPropertyData) change.getNewData()).getPropertyId());
insertPropertyData(prop,
content.getData("/"), con, ps_insert, null, pk, ((FxPropertyData) change.getNewData()),
content.isMaxVersion(), content.isLiveVersion());
ft.index(change);
//check if the property changed is a FQN
if (prop.getId() == fqnPropertyId) {
syncFQNName(con, content, pk, change);
}
}
}
}
if (batchContentDataChanges()) {
ps_update.executeBatch();
ps_insert.executeBatch();
}
} finally {
if (ps_update != null) ps_update.close();
if (ps_insert != null) ps_insert.close();
}
checkUniqueConstraints(con, env, sql, pk, content.getTypeId());
if (delta.isInternalPropertyChanged()) {
updateStepDependencies(con, content.getPk().getId(), content.getPk().getVersion(), env, type, content.getStepId());
fixContentVersionStats(con, type, content.getPk().getId());
}
content.resolveBinaryPreview();
if (original.getBinaryPreviewId() != content.getBinaryPreviewId() ||
original.getBinaryPreviewACL() != content.getBinaryPreviewACL())
binaryStorage.updateContentBinaryEntry(con, pk, content.getBinaryPreviewId(), content.getBinaryPreviewACL());
enableDetailUniqueChecks(con);
LifeCycleInfoImpl.updateLifeCycleInfo(TBL_CONTENT, "ID", "VER",
content.getPk().getId(), content.getPk().getVersion(), false, false);
//after... scripts
if (checkScripting) {
//delta-deletes:
for (FxDelta.FxDeltaChange change : delta.getRemoves()) {
for (long scriptId : change.getOriginalData().getAssignment().
getScriptMapping(FxScriptEvent.AfterDataChangeDelete)) {
binding.setVariable("change", change);
scripting.runScript(scriptId, binding);
}
}
//delta-updates:
for (FxDelta.FxDeltaChange change : delta.getUpdates()) {
for (long scriptId : change.getOriginalData().getAssignment().
getScriptMapping(FxScriptEvent.AfterDataChangeUpdate)) {
binding.setVariable("change", change);
scripting.runScript(scriptId, binding);
}
}
//delta-adds:
for (FxDelta.FxDeltaChange change : delta.getAdds()) {
for (long scriptId : change.getNewData().getAssignment().
getScriptMapping(FxScriptEvent.AfterDataChangeAdd)) {
binding.setVariable("change", change);
scripting.runScript(scriptId, binding);
}
}
}
ft.commitChanges();
if (type.isTrackHistory()) {
HistoryTrackerEngine tracker = EJBLookup.getHistoryTrackerEngine();
XStream xs = ConversionEngine.getXStream();
for (FxDelta.FxDeltaChange add : delta.getAdds())
tracker.track(type, pk,
add.getNewData().isGroup() ? null :
xs.toXML(((FxPropertyData) add.getNewData()).getValue()),
"history.content.data.add", add.getXPath());
for (FxDelta.FxDeltaChange remove : delta.getRemoves())
tracker.track(type, pk,
remove.getOriginalData().isGroup() ? null :
xs.toXML(((FxPropertyData) remove.getOriginalData()).getValue()),
"history.content.data.removed", remove.getXPath());
for (FxDelta.FxDeltaChange update : delta.getUpdates()) {
if (update.isPositionChangeOnly())
tracker.track(type, pk,
null, "history.content.data.update.posOnly", update.getXPath(),
update.getOriginalData().getPos(), update.getNewData().getPos());
else if (update.isPositionChange())
tracker.track(type, pk,
update.getNewData().isGroup() ? null :
xs.toXML(((FxPropertyData) update.getNewData()).getValue()),
"history.content.data.update.pos", update.getXPath(),
update.getOriginalData().getPos(), update.getNewData().getPos());
else
tracker.track(type, pk,
update.getNewData().isGroup() ? null :
"<original>\n" + xs.toXML(((FxPropertyData) update.getOriginalData()).getValue()) + "\n</original>\n" +
"<new>\n" + xs.toXML(((FxPropertyData) update.getNewData()).getValue()) + "\n</new>\n",
"history.content.data.update", update.getXPath());
}
}
} catch (FxCreateException e) {
throw new FxUpdateException(e);
} catch (FxApplicationException e) {
throw new FxUpdateException(e);
} catch (SQLException e) {
throw new FxUpdateException(LOG, e, "ex.db.sqlError", e.getMessage());
} catch (Exception e) {
throw new FxUpdateException(LOG, e, "ex.content.save.error", pk, e);
} finally {
ft.cleanup();
}
return content.getPk();
}
private void syncFQNName(Connection con, FxContent content, FxPK pk, FxDelta.FxDeltaChange change) throws FxApplicationException {
FxValue val;
if (change != null) {
if (change.getChangeType() == FxDelta.FxDeltaChange.ChangeType.Remove) {
//sync to empty FQN (see FX-752)
StorageManager.getTreeStorage().syncFQNName(con, pk.getId(), content.isMaxVersion(), content.isLiveVersion(), null);
return;
}
val = ((FxPropertyData) change.getNewData()).getValue();
} else {
//check if there is a FQN property and sync that one (used when creating a new version)
long fqnPropertyId = EJBLookup.getConfigurationEngine().get(SystemParameters.TREE_FQN_PROPERTY);
List<FxPropertyData> pd = content.getPropertyData(fqnPropertyId, false);
if( pd.size() > 0 )
val = pd.get(0).getValue();
else
return;
}
if (/*!val.isEmpty() &&*/ val instanceof FxString) {
StorageManager.getTreeStorage().syncFQNName(con, pk.getId(), content.isMaxVersion(), content.isLiveVersion(), (String) val.getBestTranslation());
}
}
private void enableDetailUniqueChecks(Connection con) throws SQLException {
if (!StorageManager.isDisableIntegrityTransactional()) {
return; // not supported
}
Statement stmt = null;
try {
stmt = con.createStatement();
stmt.executeUpdate(StorageManager.getReferentialIntegrityChecksStatement(true));
} finally {
if (stmt != null)
stmt.close();
}
}
private void disableDetailUniqueChecks(Connection con) throws SQLException {
if (!StorageManager.isDisableIntegrityTransactional()) {
return;
}
Statement stmt = null;
try {
stmt = con.createStatement();
stmt.executeUpdate(StorageManager.getReferentialIntegrityChecksStatement(false));
} finally {
if (stmt != null)
stmt.close();
}
}
/**
* Update the main entry
*
* @param con an open and valid connection
* @param content content to create
* @throws FxUpdateException on errors
*/
protected void updateMainEntry(Connection con, FxContent content) throws FxUpdateException {
PreparedStatement ps = null;
try {
ps = con.prepareStatement(CONTENT_MAIN_UPDATE);
ps.setLong(18, content.getPk().getId());
ps.setInt(19, content.getPk().getVersion());
ps.setLong(1, content.getTypeId());
ps.setLong(2, content.getAclIds().size() > 1 ? ACL.NULL_ACL_ID : content.getAclIds().get(0));
ps.setLong(3, content.getStepId());
ps.setInt(4, content.getVersion());
ps.setInt(5, content.isLiveVersion() ? 1 : 0);
ps.setBoolean(6, content.isMaxVersion());
ps.setBoolean(7, content.isLiveVersion());
ps.setBoolean(8, content.isActive());
ps.setInt(9, (int) content.getMainLanguage());
if (content.isRelation()) {
ps.setLong(10, content.getRelatedSource().getId());
ps.setInt(11, content.getRelatedSource().getVersion());
ps.setLong(12, content.getRelatedDestination().getId());
ps.setInt(13, content.getRelatedDestination().getVersion());
ps.setLong(14, content.getRelatedSourcePosition());
ps.setLong(15, content.getRelatedDestinationPosition());
} else {
ps.setNull(10, java.sql.Types.NUMERIC);
ps.setNull(11, java.sql.Types.NUMERIC);
ps.setNull(12, java.sql.Types.NUMERIC);
ps.setNull(13, java.sql.Types.NUMERIC);
ps.setNull(14, java.sql.Types.NUMERIC);
ps.setNull(15, java.sql.Types.NUMERIC);
}
if (content.isForceLifeCycle()) {
ps.setLong(16, content.getValue(FxLargeNumber.class, "/MODIFIED_BY").getBestTranslation());
ps.setLong(17, content.getValue(FxDateTime.class, "/MODIFIED_AT").getBestTranslation().getTime());
} else {
long userId = FxContext.getUserTicket().getUserId();
ps.setLong(16, userId);
ps.setLong(17, System.currentTimeMillis());
}
ps.executeUpdate();
if (content.isForceLifeCycle()) {
ps.close();
// update created_at/created_by
ps = con.prepareStatement(CONTENT_MAIN_UPDATE_CREATED_AT);
ps.setLong(1, content.getValue(FxDateTime.class, "/CREATED_AT").getBestTranslation().getTime());
ps.setLong(2, content.getValue(FxLargeNumber.class, "/CREATED_BY").getBestTranslation());
ps.setLong(3, content.getPk().getId());
ps.setInt(4, content.getPk().getVersion());
ps.executeUpdate();
}
updateACLEntries(con, content, content.getPk(), false);
} catch (SQLException e) {
throw new FxUpdateException(LOG, e, "ex.db.sqlError", e.getMessage());
} catch (FxCreateException e) {
throw new FxUpdateException(e);
} finally {
if (ps != null)
try {
ps.close();
} catch (SQLException e) {
//ignore
}
}
}
/**
* {@inheritDoc}
*/
public FxContentSecurityInfo getContentSecurityInfo(Connection con, FxPK pk, FxContent rawContent) throws FxLoadException, FxNotFoundException {
PreparedStatement ps = null;
try {
switch (pk.getVersion()) {
case FxPK.MAX:
ps = con.prepareStatement(SECURITY_INFO_MAXVER);
break;
case FxPK.LIVE:
ps = con.prepareStatement(SECURITY_INFO_LIVEVER);
break;
default:
ps = con.prepareStatement(SECURITY_INFO_VER);
ps.setInt(2, pk.getVersion());
}
ps.setLong(1, pk.getId());
byte typePerm;
long typeACL, contentACL, stepACL, previewACL;
long previewId, typeId, ownerId, mandatorId;
int version;
final Set<Long> propertyPerms = new HashSet<Long>();
ResultSet rs = ps.executeQuery();
if (rs == null || !rs.next())
throw new FxNotFoundException("ex.content.notFound", pk);
contentACL = rs.getLong(1);
typeACL = rs.getLong(2);
stepACL = rs.getLong(3);
typePerm = rs.getByte(4);
typeId = rs.getLong(5);
previewId = rs.getLong(6);
previewACL = rs.getLong(7);
ownerId = rs.getLong(8);
mandatorId = rs.getLong(9);
version = rs.getInt(10);
if (rs.next())
throw new FxLoadException("ex.db.resultSet.tooManyRows");
if ((typePerm & 0x02) == 0x02) {
//use property permissions
FxContent co = rawContent;
try {
if (co == null) {
FxCachedContent cachedContent = CacheAdmin.getCachedContent(pk);
if (cachedContent != null)
co = cachedContent.getContent();
else {
ContentStorage storage = StorageManager.getContentStorage(pk.getStorageMode());
StringBuilder sql = new StringBuilder(2000);
co = storage.contentLoad(con, pk, CacheAdmin.getEnvironment(), sql);
}
}
co = co.copy();
co.getRootGroup().removeEmptyEntries();
for (String xp : co.getAllPropertyXPaths()) {
final FxPropertyAssignment pa = co.getPropertyData(xp).getPropertyAssignment();
if (pa.isSystemInternal())
continue;
Long propACL = pa.getACL().getId();
propertyPerms.add(propACL);
}
} catch (FxInvalidParameterException e) {
throw new FxLoadException(e);
}
}
pk = new FxPK(pk.getId(), version);
final List<Long> acls = contentACL == ACL.NULL_ACL_ID ? loadContentAclTable(con, pk) : Arrays.asList(contentACL);
return new FxContentSecurityInfo(pk, ownerId, previewId, typeId, mandatorId, typePerm, typeACL, stepACL,
acls, previewACL, Lists.newArrayList(propertyPerms),
StorageManager.getLockStorage().getLock(con, pk));
} catch (SQLException e) {
throw new FxLoadException(LOG, e, "ex.db.sqlError", e.getMessage());
} catch (FxLockException e) {
throw new FxLoadException(e);
} finally {
if (ps != null)
try {
ps.close();
} catch (SQLException e) {
//ignore
}
}
}
/**
* Check if content(s) may be removed.
* This method handles referential integrity incase the used database does not support it
*
* @param con an open and valid connection
* @param typeId the contents structure type
* @param id id of the content (optional, used if allForType is <code>false</code>)
* @param version version of the content (optional, used if allForType is <code>false</code> and allVersions is <code>false</code>)
* @param allForType remove all instances of the given type?
* @param allVersions remove all versions or only the requested one?
* @throws FxRemoveException if referential integrity would be violated
*/
public void checkContentRemoval(Connection con, long typeId, long id, int version, boolean allForType, boolean allVersions) throws FxRemoveException {
//to be implemented/overwritten for specific database implementations
if (LOG.isDebugEnabled())
LOG.debug("Removing type:" + typeId + " id:" + id + " ver:" + version + " allForType:" + allForType + " allVersions:" + allVersions);
if (!allVersions && !allForType)
return; //specific version may be removed if not all of the type are removed
try {
PreparedStatement ps = null;
boolean refuse = false;
try {
if (allForType) {
ps = con.prepareStatement(CONTENT_REFERENCE_BYTYPE);
ps.setLong(1, typeId);
} else {
ps = con.prepareStatement("SELECT COUNT(*) FROM " + TBL_CONTENT_DATA + " WHERE FREF=? AND ID<>FREF");
ps.setLong(1, id);
}
ResultSet rs = ps.executeQuery();
if (rs.next() && rs.getLong(1) != 0)
refuse = true;
long refCount = refuse ? rs.getLong(1) : 0;
if (!refuse) {
refuse = FxFlatStorageManager.getInstance().checkContentRemoval(con, typeId, id, allForType);
if (refuse)
refCount += FxFlatStorageManager.getInstance().getReferencedContentCount(con, id);
}
if (refuse) {
if (allForType) {
throw new FxRemoveException("ex.content.reference.inUse.type", CacheAdmin.getEnvironment().getType(typeId), refCount);
} else
throw new FxRemoveException("ex.content.reference.inUse.instance", id, refCount);
}
} finally {
if (ps != null) ps.close();
}
} catch (SQLException e) {
throw new FxRemoveException(e, "ex.db.sqlError", e.getMessage());
}
}
/**
* {@inheritDoc}
*/
public void contentRemove(Connection con, FxType type, FxPK pk) throws FxRemoveException {
PreparedStatement ps = null;
FulltextIndexer ft = getFulltextIndexer(pk, con);
try {
checkContentRemoval(con, type.getId(), pk.getId(), -1, false, true);
lockTables(con, pk.getId(), -1);
//sync with tree
StorageManager.getTreeStorage().contentRemoved(con, pk.getId(), false);
ft.removeAllVersions();
binaryStorage.removeBinaries(con, BinaryStorage.SelectOperation.SelectId, pk, type);
ps = con.prepareStatement(CONTENT_DATA_REMOVE);
ps.setLong(1, pk.getId());
ps.executeUpdate();
ps.close();
FxFlatStorageManager.getInstance().removeContent(con, type.getId(), pk.getId());
ps = con.prepareStatement(CONTENT_MAIN_REMOVE);
ps.setLong(1, pk.getId());
ps.executeUpdate();
} catch (SQLException e) {
if (LOG.isWarnEnabled()) {
// log information about removed content
LOG.warn("Failed to remove " + pk + " due to a SQL error: " + e.getMessage());
}
throw new FxRemoveException(LOG, e, "ex.db.sqlError", e.getMessage());
} catch (FxApplicationException e) {
throw new FxRemoveException(e);
} finally {
if (ps != null)
try {
ps.close();
} catch (SQLException e) {
//ignore
}
ft.cleanup();
}
if (type.isTrackHistory())
EJBLookup.getHistoryTrackerEngine().track(type, pk, null, "history.content.removed");
}
/**
* {@inheritDoc}
*/
public void contentRemoveVersion(Connection con, FxType type, FxPK pk) throws FxRemoveException, FxNotFoundException {
FxContentVersionInfo cvi = getContentVersionInfo(con, pk.getId());
if (!cvi.containsVersion(pk))
return;
int ver = pk.getVersion();
if (!pk.isDistinctVersion())
ver = cvi.getDistinctVersion(pk.getVersion());
checkContentRemoval(con, type.getId(), pk.getId(), ver, false, false);
lockTables(con, pk.getId(), pk.getVersion());
PreparedStatement ps = null;
FulltextIndexer ft = getFulltextIndexer(new FxPK(pk.getId(), ver), con);
try {
//if its the live version - sync with live tree
if (cvi.hasLiveVersion() && cvi.getLiveVersion() == ver)
StorageManager.getTreeStorage().contentRemoved(con, pk.getId(), true);
ft.remove();
binaryStorage.removeBinaries(con, BinaryStorage.SelectOperation.SelectVersion, pk, type);
ps = con.prepareStatement(CONTENT_DATA_REMOVE_VER);
ps.setLong(1, pk.getId());
ps.setInt(2, ver);
ps.executeUpdate();
ps.close();
String[] nodes = StorageManager.getTreeStorage().beforeContentVersionRemoved(con, pk.getId(), ver, cvi);
FxFlatStorageManager.getInstance().removeContentVersion(con, type.getId(), pk.getId(), ver);
ps = con.prepareStatement(CONTENT_MAIN_REMOVE_VER);
ps.setLong(1, pk.getId());
ps.setInt(2, ver);
if (ps.executeUpdate() > 0)
fixContentVersionStats(con, type, pk.getId());
StorageManager.getTreeStorage().afterContentVersionRemoved(nodes, con, pk.getId(), ver, cvi);
} catch (SQLException e) {
throw new FxRemoveException(LOG, e, "ex.db.sqlError", e.getMessage());
} catch (FxApplicationException e) {
throw new FxRemoveException(e);
} finally {
ft.cleanup();
if (ps != null)
try {
ps.close();
} catch (SQLException e) {
//ignore
}
}
if (type.isTrackHistory())
EJBLookup.getHistoryTrackerEngine().track(type, pk, null, "history.content.removed.version", ver);
}
/**
* {@inheritDoc}
*/
public int contentRemoveForType(Connection con, FxType type) throws FxRemoveException {
PreparedStatement ps = null;
FulltextIndexer ft = getFulltextIndexer(null, con);
try {
checkContentRemoval(con, type.getId(), -1, -1, true, true);
//FX-96 - select all contents that are referenced from the tree
ps = con.prepareStatement("SELECT DISTINCT c.ID FROM " + DatabaseConst.TBL_CONTENT + " c, " +
DatabaseConst.TBL_TREE + " te, " + DatabaseConst.TBL_TREE +
"_LIVE tl WHERE (te.REF=c.ID or tl.REF=c.ID) AND c.TDEF=?");
ps.setLong(1, type.getId());
ResultSet rs = ps.executeQuery();
while (rs != null && rs.next())
StorageManager.getTreeStorage().contentRemoved(con, rs.getLong(1), false);
ps.close();
ft.removeType(type.getId());
binaryStorage.removeBinaries(con, BinaryStorage.SelectOperation.SelectType, null, type);
ps = con.prepareStatement(CONTENT_DATA_REMOVE_TYPE);
ps.setLong(1, type.getId());
ps.executeUpdate();
ps.close();
FxFlatStorageManager.getInstance().removeContentByType(con, type.getId());
ps = con.prepareStatement(CONTENT_MAIN_REMOVE_TYPE);
ps.setLong(1, type.getId());
return ps.executeUpdate();
} catch (SQLException e) {
throw new FxRemoveException(LOG, e, "ex.db.sqlError", e.getMessage());
} catch (FxApplicationException e) {
throw new FxRemoveException(e);
} finally {
ft.cleanup();
if (ps != null)
try {
ps.close();
} catch (SQLException e) {
//ignore
}
}
}
/**
* {@inheritDoc}
*/
public List<FxPK> getPKsForType(Connection con, FxType type, boolean onePkPerInstance) throws FxDbException {
PreparedStatement ps = null;
List<FxPK> pks = new ArrayList<FxPK>(50);
try {
if (onePkPerInstance)
ps = con.prepareStatement(CONTENT_TYPE_PK_RETRIEVE_IDS);
else
ps = con.prepareStatement(CONTENT_TYPE_PK_RETRIEVE_VERSIONS);
ps.setLong(1, type.getId());
ResultSet rs = ps.executeQuery();
while (rs != null && rs.next()) {
if (onePkPerInstance)
pks.add(new FxPK(rs.getLong(1)));
else
pks.add(new FxPK(rs.getLong(1), rs.getInt(2)));
}
return pks;
} catch (SQLException e) {
throw new FxDbException(LOG, e, "ex.db.sqlError", e.getMessage());
} finally {
if (ps != null)
try {
ps.close();
} catch (SQLException e) {
//ignore
}
}
}
/**
* {@inheritDoc}
*/
public void maintenance(Connection con) {
binaryStorage.removeExpiredTransitEntries(con);
try {
StorageManager.getLockStorage().removeExpiredLocks(con);
} catch (FxNotFoundException e) {
LOG.error(e);
}
}
/**
* Check all unique constraints for an instance
*
* @param con an open and valid connection
* @param env environment
* @param sql StringBuilder for performance
* @param pk primary key of the affected instance
* @param typeId affected FxType
* @throws FxApplicationException on errors
*/
private void checkUniqueConstraints(Connection con, FxEnvironment env, StringBuilder sql, FxPK pk, long typeId) throws FxApplicationException {
FxType type = env.getType(typeId);
if (!type.hasUniqueProperties())
return;
List<FxProperty> uniques = type.getUniqueProperties();
if (sql == null)
sql = new StringBuilder(500);
else
sql.setLength(0);
try {
for (FxProperty prop : uniques) {
sql.setLength(0);
uniqueConditionsMet(con, env, sql, prop.getUniqueMode(), prop, typeId, pk, true);
}
} catch (SQLException e) {
throw new FxDbException(LOG, e, "ex.db.sqlError", e.getMessage());
}
}
/**
* Check if unique constraints are met
*
* @param con an open and valid Connection
* @param env environment
* @param sql a StringBuilder instance
* @param mode UniqueMode
* @param prop the propery to check
* @param typeId type to check
* @param pk primary key (optional)
* @param throwException should an exception be thrown if conditions are not met?
* @return conditions met
* @throws SQLException on errors
* @throws FxApplicationException on errors
*/
private boolean uniqueConditionsMet(Connection con, FxEnvironment env, StringBuilder sql, UniqueMode mode,
FxProperty prop, long typeId, FxPK pk, boolean throwException)
throws SQLException, FxApplicationException {
/*List<FxPropertyAssignment> pa = CacheAdmin.getEnvironment().getPropertyAssignments(prop.getId(), true);
boolean hasFlat=false,hasHierarchical=false;
for (FxPropertyAssignment p : pa) {
if (hasFlat && hasHierarchical)
break;
if (p.isFlatStorageEntry())
hasFlat = true;
else
hasHierarchical = true;
}
if (hasHierarchical) {*/
String typeChecks = null;
sql.setLength(0);
switch (mode) {
case Global:
sql.append("SELECT tcd.ASSIGN,tcd.XMULT,COUNT(DISTINCT ccd.ID) FROM ").append(TBL_CONTENT_DATA).
append(" ccd, ").append(TBL_CONTENT_DATA).append(" tcd WHERE ccd.TPROP=").
append(prop.getId()).append(" AND ccd.TPROP=tcd.TPROP AND ccd.ID<>tcd.ID").
append(" AND ccd.LANG=tcd.LANG");
if (pk != null)
sql.append(" AND tcd.ID=").append(pk.getId());
else {
//prevent checks across versions
sql.append(" AND NOT(ccd.ID=tcd.ID AND ccd.VER<>tcd.VER)").
//prevent self-references
append(" AND NOT(ccd.ID=tcd.ID AND ccd.VER=tcd.VER AND ccd.ASSIGN=tcd.ASSIGN AND tcd.XMULT=ccd.XMULT)");
}
break;
case DerivedTypes:
//gen list of parent and derived types
typeChecks = buildTypeHierarchy(env.getType(typeId));
case Type:
if (typeChecks == null)
typeChecks = "" + typeId;
sql.append("SELECT tcd.ASSIGN,tcd.XMULT,COUNT(DISTINCT ccd.ID) FROM ").append(TBL_CONTENT_DATA).
append(" ccd, ").append(TBL_CONTENT_DATA).append(" tcd, ").append(TBL_CONTENT).
append(" cc, ").append(TBL_CONTENT).
append(" tc WHERE cc.ID=ccd.ID AND tc.ID=tcd.ID AND cc.TDEF IN (").
append(typeChecks).append(") AND tc.TDEF IN (").append(typeChecks).
append(") AND ccd.TPROP=").append(prop.getId()).
append(" AND ccd.TPROP=tcd.TPROP AND ccd.LANG=tcd.LANG").
//prevent checks across versions
append(" AND NOT(ccd.ID=tcd.ID AND ccd.VER<>tcd.VER)").
//prevent self-references
append(" AND NOT(ccd.ID=tcd.ID AND ccd.VER=tcd.VER AND ccd.ASSIGN=tcd.ASSIGN AND tcd.XMULT=ccd.XMULT)");
break;
case Instance:
sql.append("SELECT tcd.ASSIGN,tcd.XMULT FROM ").append(TBL_CONTENT_DATA).append(" ccd, ").
append(TBL_CONTENT_DATA).append(" tcd WHERE ccd.TPROP=").append(prop.getId()).
append(" AND ccd.TPROP=tcd.TPROP AND ccd.ID=tcd.ID AND ccd.VER=tcd.VER AND ccd.XMULT<>tcd.XMULT");
if (pk != null)
sql.append(" AND tcd.ID=").append(pk.getId());
sql.append(" AND ccd.LANG=tcd.LANG");
break;
}
if (sql.length() > 0) {
addColumnComparator(sql, prop, "ccd", "tcd");
sql.append(" GROUP BY tcd.ASSIGN,tcd.XMULT");
Statement s = null;
try {
s = con.createStatement();
ResultSet rs = s.executeQuery(sql.toString());
if (rs != null && rs.next()) {
if (mode == UniqueMode.Instance || rs.getInt(3) > 0) {
if (throwException) {
final String xpath = XPathElement.toXPathMult(CacheAdmin.getEnvironment().getAssignment(rs.getLong(1)).getXPath(), rs.getString(2));
//noinspection ThrowableInstanceNeverThrown
throw new FxConstraintViolationException("ex.content.contraint.unique.xpath", xpath, mode).setAffectedXPath(xpath, FxContentExceptionCause.UniqueConstraintViolated);
} else
return false;
}
}
} finally {
Database.closeObjects(GenericHierarchicalStorage.class, s);
}
}
// }
return true;
}
/**
* {@inheritDoc}
*/
public boolean uniqueConditionValid(Connection con, UniqueMode mode, FxProperty prop, long typeId, FxPK pk) {
try {
return uniqueConditionsMet(con, CacheAdmin.getEnvironment(), new StringBuilder(500), mode, prop, typeId, pk, false);
} catch (SQLException e) {
//noinspection ThrowableInstanceNeverThrown
throw new FxApplicationException(e, "ex.db.sqlError", e.getMessage()).asRuntimeException();
} catch (FxApplicationException e) {
throw e.asRuntimeException();
}
}
/**
* {@inheritDoc}
*/
public void updateMultilanguageSettings(Connection con, long assignmentId, boolean orgMultiLang,
boolean newMultiLang, long defaultLanguage)
throws FxUpdateException, SQLException {
if (orgMultiLang == newMultiLang)
return;
PreparedStatement ps = null;
FulltextIndexer ft = getFulltextIndexer(null, con);
try {
if (!orgMultiLang && newMultiLang) {
//Single to Multi: lang=default language
ps = con.prepareStatement("UPDATE " + TBL_CONTENT_DATA + " SET LANG=? WHERE ASSIGN=?");
ps.setLong(1, defaultLanguage);
ps.setLong(2, assignmentId);
ps.executeUpdate();
ft.setLanguage(assignmentId, defaultLanguage);
} else {
//Multi to Single: lang=system, values of the def. lang. are used, if other translations exist an exception will be raised
ps = con.prepareStatement("UPDATE " + TBL_CONTENT_DATA + " SET LANG=? WHERE LANG=? AND ASSIGN=?");
ps.setLong(1, FxLanguage.SYSTEM_ID);
ps.setLong(2, defaultLanguage);
ps.setLong(3, assignmentId);
ps.executeUpdate();
ft.changeLanguage(assignmentId, defaultLanguage, FxLanguage.SYSTEM_ID);
ps.close();
ps = con.prepareStatement("SELECT COUNT(*) FROM " + TBL_CONTENT_DATA + " WHERE ASSIGN=? AND LANG<>?");
ps.setLong(1, assignmentId);
ps.setLong(2, FxLanguage.SYSTEM_ID);
ResultSet rs = ps.executeQuery();
long count;
if (rs != null && rs.next())
if ((count = rs.getLong(1)) > 0)
throw new FxUpdateException("ex.content.update.multi2single.contentExist", CacheAdmin.getEnvironment().getAssignment(assignmentId).getXPath(), count);
}
} finally {
if (ps != null)
ps.close();
}
}
/**
* Helper to build a comma seperated list of all parent and child types and the current type
*
* @param type current type to examine
* @return comma seperated list of all parent and child types and the current type
*/
private String buildTypeHierarchy(FxType type) {
StringBuilder th = new StringBuilder(100);
FxType parent = type.getParent();
th.append(type.getId());
while (parent != null) {
th.append(",").append(parent.getId());
parent = parent.getParent();
}
buildTypeChildren(th, type);
return th.toString();
}
/**
* Build a list of all derived types and the current type
*
* @param th StringBuilder that should contain the result
* @param type current type
*/
private void buildTypeChildren(StringBuilder th, FxType type) {
for (FxType child : type.getDerivedTypes()) {
th.append(',').append(child.getId());
buildTypeChildren(th, child);
}
}
/**
* Compare a property for two database aliases
*
* @param sql StringBuilder to append the comparison to
* @param prop propery to compare
* @param compAlias compare alias
* @param ownAlias own alias
*/
private void addColumnComparator(StringBuilder sql, FxProperty prop, String compAlias, String ownAlias) {
String ucol = getUppercaseColumn(prop);
if (ucol == null)
for (String col : getColumns(prop))
sql.append(" AND ").append(compAlias).append(".").append(col).append("=").append(ownAlias).append(".").append(col);
else
sql.append(" AND ").append(compAlias).append(".").append(ucol).append("=").append(ownAlias).append(".").append(ucol);
}
/**
* {@inheritDoc}
*/
public int getReferencedContentCount(Connection con, long id) throws FxDbException {
Statement s = null;
int count = 0;
try {
s = con.createStatement();
//references within contents
ResultSet rs = s.executeQuery("SELECT COUNT(DISTINCT ID) FROM " + TBL_CONTENT_DATA + " WHERE FREF=" + id);
if (rs.next()) {
count += rs.getInt(1);
}
//Edit tree references
rs = s.executeQuery("SELECT COUNT(DISTINCT ID) FROM " + TBL_TREE + " WHERE REF=" + id);
if (rs.next()) {
count += rs.getInt(1);
}
//Live tree references
rs = s.executeQuery("SELECT COUNT(DISTINCT ID) FROM " + TBL_TREE + "_LIVE WHERE REF=" + id);
if (rs.next()) {
count += rs.getInt(1);
}
//Contact Data references
rs = s.executeQuery("SELECT COUNT(DISTINCT ID) FROM " + TBL_ACCOUNTS + " WHERE CONTACT_ID=" + id);
if (rs.next()) {
count += rs.getInt(1);
}
//Briefcase references
rs = s.executeQuery("SELECT COUNT(DISTINCT BRIEFCASE_ID) FROM " + TBL_BRIEFCASE_DATA + " WHERE ID=" + id);
if (rs.next()) {
count += rs.getInt(1);
}
return count;
} catch (SQLException e) {
throw new FxDbException(LOG, e, "ex.db.sqlError", e.getMessage());
} finally {
if (s != null)
try {
s.close();
} catch (SQLException e) {
//ignore
}
}
}
/**
* {@inheritDoc}
*/
public void updateXPath(Connection con, long assignmentId, String originalXPath, String newXPath) throws FxUpdateException, FxInvalidParameterException {
//mp: removed with FX-960!
/*LOG.info("Updating all instances from [" + originalXPath + "] to [" + newXPath + "]...");
PreparedStatement psRead = null, psWrite = null;
List<XPathElement> xorg = XPathElement.split(originalXPath);
List<XPathElement> xnew = XPathElement.split(newXPath);
if (xorg.size() != xnew.size())
throw new FxInvalidParameterException("newXPath", "ex.content.xpath.update.mismatch.size", originalXPath, newXPath);
try {
// 1 2 3 4 5 6
psRead = con.prepareStatement("SELECT XMULT,ID,VER,LANG,POS,TPROP FROM " + TBL_CONTENT_DATA + " WHERE ASSIGN=?");
// 1 2 3 4 5 6 7 8 9
psWrite = con.prepareStatement("UPDATE " + TBL_CONTENT_DATA + " SET XPATH=?,XPATHMULT=?,PARENTXPATH=? WHERE ID=? AND VER=? AND LANG=? AND POS=? AND XMULT=? AND ASSIGN=?");
psRead.setLong(1, assignmentId);
ResultSet rs = psRead.executeQuery();
boolean isGroup;
while (rs != null && rs.next()) {
rs.getLong(6);
isGroup = rs.wasNull();
int[] idx = FxArrayUtils.toIntArray(rs.getString(1), ',');
for (int i = 0; i < xnew.size(); i++)
xnew.get(i).setIndex(idx[i]);
String xm = XPathElement.toXPath(xnew);
psWrite.setString(1, newXPath + (isGroup ? "/" : ""));
psWrite.setString(2, xm + (isGroup ? "/" : ""));
String parentXP = xm.substring(0, xm.lastIndexOf('/'));
if ("".equals(parentXP))
parentXP = "/";
psWrite.setString(3, parentXP);
psWrite.setLong(4, rs.getLong(2));
psWrite.setInt(5, rs.getInt(3));
psWrite.setInt(6, rs.getInt(4));
psWrite.setInt(7, rs.getInt(5));
psWrite.setString(8, rs.getString(1));
psWrite.setLong(9, assignmentId);
psWrite.executeUpdate();
}
} catch (SQLException e) {
throw new FxUpdateException(LOG, e, "ex.db.sqlError", e.getMessage());
} finally {
try {
if (psRead != null)
psRead.close();
} catch (SQLException e) {
//ignore
}
try {
if (psWrite != null)
psWrite.close();
} catch (SQLException e) {
//ignore
}
}*/
}
/**
* {@inheritDoc}
*/
public long getTypeInstanceCount(Connection con, long typeId) throws SQLException {
PreparedStatement ps = null;
long count = 0;
try {
ps = con.prepareStatement("SELECT COUNT(*) FROM " + TBL_CONTENT + " WHERE TDEF=?");
ps.setLong(1, typeId);
ResultSet rs = ps.executeQuery();
rs.next();
count = rs.getLong(1);
} finally {
if (ps != null)
ps.close();
}
return count;
}
/**
* {@inheritDoc}
*/
public void prepareSave(Connection con, FxContent content) throws FxInvalidParameterException, FxDbException {
// key: handle, value: [mimeType,metaData]
Map<String, String[]> mimeMetaMap = new HashMap<String, String[]>(5);
try {
for (FxData data : content.getRootGroup().getChildren()) {
try {
_prepareBinaries(mimeMetaMap, con, data);
} catch (FxApplicationException e) {
LOG.error(e); //not supposed to be thrown if called with a mimeMetaMap
}
_checkReferences(con, data);
}
} catch (SQLException e) {
throw new FxDbException(LOG, e, "ex.db.sqlError", e.getMessage());
}
}
/**
* Internal prepare save that walks through all groups to discover binaries that are to be processed
*
* @param mimeMetaMap optional meta map to avoid duplicates, can be <code>null</code>
* @param con an open and valid connection
* @param data current FxData object to inspect
* @throws SQLException on errors
* @throws FxApplicationException on errors
*/
private void _prepareBinaries(Map<String, String[]> mimeMetaMap, Connection con, FxData data) throws SQLException, FxApplicationException {
if (data instanceof FxGroupData)
for (FxData sub : ((FxGroupData) data).getChildren())
_prepareBinaries(mimeMetaMap, con, sub);
else if (data instanceof FxPropertyData) {
FxPropertyData pdata = (FxPropertyData) data;
if (pdata.isContainsDefaultValue() && !pdata.isEmpty())
((FxPropertyData) data).setContainsDefaultValue(false);
if (!pdata.isEmpty() && pdata.getValue() instanceof FxBinary) {
FxBinary bin = (FxBinary) pdata.getValue();
binaryStorage.prepareBinary(con, mimeMetaMap, bin);
}
}
}
//Binary handling
/**
* Internal prepare save that walks through all groups to discover references that are not legal
*
* @param con an open and valid connection
* @param data current FxData object to inspect
* @throws FxDbException on errors
*/
private void _checkReferences(Connection con, FxData data) throws FxDbException {
if (data instanceof FxGroupData)
for (FxData sub : ((FxGroupData) data).getChildren())
_checkReferences(con, sub);
else if (data instanceof FxPropertyData) {
FxPropertyData pdata = (FxPropertyData) data;
if (!pdata.isEmpty() && pdata.getValue() instanceof FxReference) {
final FxPropertyAssignment pa = pdata.getPropertyAssignment();
if (!pa.isSystemInternal()) {
checkDataType(FxReference.class, pdata.getValue(), pdata.getXPathFull());
final FxType referencedType = pa.getProperty().getReferencedType();
for (long lang : pdata.getValue().getTranslatedLanguages())
checkReference(con, referencedType, ((FxPK) pdata.getValue().getTranslation(lang)), pdata.getXPathFull());
}
}
}
}
/**
* {@inheritDoc}
*/
public OutputStream receiveTransitBinary(int divisionId, String handle, String mimeType, long expectedSize, long ttl) throws SQLException, IOException {
return binaryStorage.receiveTransitBinary(divisionId, handle, mimeType, expectedSize, ttl);
}
/**
* {@inheritDoc}
*/
public BinaryInputStream fetchBinary(Connection con, int divisionId, BinaryDescriptor.PreviewSizes size, long binaryId, int binaryVersion, int binaryQuality) {
return binaryStorage.fetchBinary(con, divisionId, size, binaryId, binaryVersion, binaryQuality);
}
/**
* {@inheritDoc}
*/
public void storeBinary(Connection con, long id, int version, int quality, String name, long length, InputStream binary) throws FxApplicationException {
binaryStorage.storeBinary(con, id, version, quality, name, length, binary);
}
/**
* {@inheritDoc}
*/
public void updateBinaryPreview(Connection con, long id, int version, int quality, int preview, int width, int height, long length, InputStream binary) throws FxApplicationException {
binaryStorage.updateBinaryPreview(con, id, version, quality, preview, width, height, length, binary);
}
/**
* {@inheritDoc}
*/
public void prepareBinary(Connection con, FxBinary binary) throws SQLException, FxApplicationException {
binaryStorage.prepareBinary(con, null, binary);
}
/**
* {@inheritDoc}
*/
public void convertContentType(Connection con, FxPK pk, long sourceTypeId, long destinationTypeId, boolean allVersions,
Map<Long, Long> assignmentMap, List<Long> flatStoreAssignments, List<Long> nonFlatSourceAssignments,
List<Long> nonFlatDestinationAssignments, Map<Long, String> sourcePathsMap,
Map<Long, String> destPathsMap, Map<Long, String> sourceRemoveMap, FxEnvironment env)
throws SQLException, FxApplicationException {
PreparedStatement ps = null;
final long pkId = pk.getId();
final Integer[] versions;
// check if all versions should be converted or the current one only
if(allVersions) {
final FxContentVersionInfo versionInfo = getContentVersionInfo(con, pkId);
versions = versionInfo.getVersions();
} else {
versions = new Integer[]{pk.getVersion()};
}
// cache the content versions
final List<FxContent> contentVersions = new ArrayList<FxContent>(versions.length);
for(int v : versions) {
contentVersions.add(contentLoad(con, new FxPK(pkId, v), env, new StringBuilder(2000)));
}
long userId = FxContext.getUserTicket().getUserId();
FxFlatStorage flatStorage = FxFlatStorageManager.getInstance();
boolean flatRewrite = false;
// lossy conversion source remove map
if (sourceRemoveMap.size() > 0) {
final Set<Long> removeSet = sourceRemoveMap.keySet();
for (Long removeId : removeSet) {
for (FxContent content : contentVersions) {
List<FxData> data = content.getData(sourceRemoveMap.get(removeId));
FulltextIndexer ft = getFulltextIndexer(pk, con);
ft.remove(removeId);
for (FxData d : data) {
deleteDetailData(con, new StringBuilder(2000), content.getPk(), d);
}
}
}
// if no flatstorage assignments remain, delete all orphaned flat entries
final List<Long> compareRemoveList = new ArrayList<Long>(removeSet.size());
for (Long flatStoreId : flatStoreAssignments) {
for (Long removeId : removeSet) {
if (assignmentMap.containsKey(removeId)) {
final Long mappedItem = assignmentMap.get(removeId);
if (mappedItem == null || (mappedItem != null && mappedItem.equals(flatStoreId)))
compareRemoveList.add(flatStoreId);
}
}
}
Collections.sort(flatStoreAssignments);
Collections.sort(compareRemoveList);
// compare compareRemoveList & flatStoreAssignments, if no differences found, remove all source flat store content
final FxDiff diff = new FxDiff(compareRemoveList, flatStoreAssignments);
if(diff.diff().size() == 0) {
flatStorage.removeContent(con, sourceTypeId, pkId);
}
}
/**
* use cases:
* 1. hierarchical --> flat conversion
* 2. flat --> hierrarchical conversion
* 3. hierarchical --> hierarchical conversion
* 4. flat --> flat conversion
*/
try {
for (Long sourceId : assignmentMap.keySet()) {
// do not convert any removed source content assignments
if(sourceRemoveMap.containsKey(sourceId))
continue;
final String sourceXPath = sourcePathsMap.get(sourceId);
final Long destinationId = assignmentMap.get(sourceId);
final String destXPath = destPathsMap.get(destinationId);
for (FxContent content : contentVersions) {
if (destinationId == null) {
// delete from the source
if (nonFlatSourceAssignments.contains(sourceId) && content.getValue(destXPath) != null) { // source is hierarchical
final List<FxData> data = content.getData(destXPath);
for (FxData d : data) {
deleteDetailData(con, new StringBuilder(2000), content.getPk(), d);
}
}
continue; // goto next source id
}
// move on if no value was set
if(content.getValue(sourceXPath) == null)
continue;
final FxPropertyData propData = content.getPropertyData(destXPath);
final List<FxData> data = content.getData(destXPath);
// use case 1: hierarchical --> flat
if (nonFlatSourceAssignments.contains(sourceId) && flatStoreAssignments.contains(destinationId)) {
for (FxData d : data) {
deleteDetailData(con, new StringBuilder(2000), content.getPk(), d);
}
flatRewrite = true;
}
// use case 2: flat --> hierarchical
if (!nonFlatSourceAssignments.contains(sourceId) && nonFlatDestinationAssignments.contains(destinationId)) {
ps = con.prepareStatement(CONTENT_DATA_INSERT);
// data for the current xpath
createDetailEntries(con, ps, null, new StringBuilder(2000), content.getPk(), content.isMaxVersion(), content.isLiveVersion(), data, true);
ps.executeBatch();
ps.close();
// remove the old entry from the flatstorage
flatStorage.deletePropertyData(con, content.getPk(), propData);
flatRewrite = true;
}
}
}
if (flatRewrite || flatStoreAssignments.size() > 0) {
// re-create (remove old entries first) all flat storage entries with correct column settings
flatStorage.removeContent(con, sourceTypeId, pkId);
for (FxContent content : contentVersions) {
List<FxPropertyData> data = new ArrayList<FxPropertyData>(5);
for (Long id : flatStoreAssignments) {
final String destXPath = destPathsMap.get(id);
if (content.getValue(destXPath) != null)
data.add(content.getPropertyData(destXPath));
}
if (data.size() > 0) {
flatStorage.setConvertedPropertyData(con, content.getPk(), sourceTypeId, destinationTypeId, content.getStepId(), content.isMaxVersion(), content.isLiveVersion(), data);
}
}
}
// update tables w/ new assignment ids (valid for all use cases)
if (allVersions) {
ps = con.prepareStatement(CONTENT_CONVERT_ALL_VERSIONS_UPDATE);
ps.setLong(1, destinationTypeId);
ps.setLong(2, userId);
ps.setLong(3, System.currentTimeMillis());
ps.setLong(4, pkId);
ps.executeUpdate();
ps.close();
ps = con.prepareStatement(CONTENT_DATA_CONVERT_ALL_VERSIONS_UPDATE);
// perform one update per assignmentMap entry
for (Long sourceId : assignmentMap.keySet()) {
final Long destId = assignmentMap.get(sourceId);
if (destId != null) {
ps.setLong(1, destId);
ps.setLong(2, pkId);
ps.setLong(3, sourceId);
ps.executeUpdate();
}
}
ps.close();
ps = con.prepareStatement(CONTENT_DATA_FT_CONVERT_ALL_VERSIONS_UPDATE);
// perform one update per assignmentMap entry
for (Long sourceId : assignmentMap.keySet()) {
final Long destId = assignmentMap.get(sourceId);
if (destId != null) {
ps.setLong(1, destId);
ps.setLong(2, pkId);
ps.setLong(3, sourceId);
ps.executeUpdate();
}
}
ps.close();
} else { // convert single version
ps = con.prepareStatement(CONTENT_CONVERT_SINGLE_VERSION_UPDATE);
ps.setLong(1, destinationTypeId);
ps.setLong(2, userId);
ps.setLong(3, System.currentTimeMillis());
ps.setLong(4, pkId);
ps.setInt(5, pk.getVersion());
ps.executeUpdate();
ps.close();
ps = con.prepareStatement(CONTENT_DATA_CONVERT_SINGLE_VERSION_UPDATE);
// perform one update per assignmentMap entry
for (Long sourceId : assignmentMap.keySet()) {
final Long destId = assignmentMap.get(sourceId);
if (destId != null) {
ps.setLong(1, destId);
ps.setLong(2, pkId);
ps.setLong(3, sourceId);
ps.setInt(4, pk.getVersion());
ps.executeUpdate();
}
}
ps.close();
ps = con.prepareStatement(CONTENT_DATA_FT_CONVERT_SINGLE_VERSION_UPDATE);
// perform one update per assignmentMap entry
for (Long sourceId : assignmentMap.keySet()) {
final Long destId = assignmentMap.get(sourceId);
if (destId != null) {
ps.setLong(1, destId);
ps.setLong(2, pkId);
ps.setLong(3, sourceId);
ps.setInt(4, pk.getVersion());
ps.executeUpdate();
}
}
ps.close();
}
} catch (SQLException e) {
throw new FxUpdateException(LOG, e, "ex.db.sqlError", e.getMessage());
} finally {
if (ps != null)
ps.close();
}
}
}
\ No newline at end of file
| true | false | null | null |
diff --git a/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/olap/script/JSMeasureAccessor.java b/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/olap/script/JSMeasureAccessor.java
index 9577ebac7..06c11e562 100644
--- a/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/olap/script/JSMeasureAccessor.java
+++ b/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/olap/script/JSMeasureAccessor.java
@@ -1,62 +1,61 @@
/*******************************************************************************
* Copyright (c) 2004, 2005 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.data.engine.olap.script;
import javax.olap.OLAPException;
import javax.olap.cursor.CubeCursor;
-import org.eclipse.birt.data.engine.olap.api.query.ICubeQueryDefinition;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
/**
*
*/
public class JSMeasureAccessor extends ScriptableObject
{
private CubeCursor cursor;
- public JSMeasureAccessor( ICubeQueryDefinition defn, CubeCursor cursor )
+ public JSMeasureAccessor( CubeCursor cursor )
throws OLAPException
{
this.cursor = cursor;
}
/*
* (non-Javadoc)
* @see org.mozilla.javascript.ScriptableObject#getClassName()
*/
public String getClassName( )
{
// TODO Auto-generated method stub
return "JSMeasureAccessor";
}
/*
* @see org.mozilla.javascript.ScriptableObject#get(java.lang.String,
* org.mozilla.javascript.Scriptable)
*/
public Object get( String name, Scriptable start )
{
try
{
return this.cursor.getObject( name );
}
catch ( OLAPException e )
{
return null;
}
}
}
| false | false | null | null |
diff --git a/src/test/pleocmd/Testcases.java b/src/test/pleocmd/Testcases.java
index 3e27002..163900e 100644
--- a/src/test/pleocmd/Testcases.java
+++ b/src/test/pleocmd/Testcases.java
@@ -1,15 +1,16 @@
package test.pleocmd;
import org.junit.BeforeClass;
import pleocmd.Log;
import pleocmd.Log.Type;
public class Testcases { // CS_IGNORE not an utility class
@BeforeClass
public static void logOnlyWarnings() {
Log.setMinLogType(Type.Warn);
+ Log.setGUIStatusKnown();
}
}
| true | true | public static void logOnlyWarnings() {
Log.setMinLogType(Type.Warn);
}
| public static void logOnlyWarnings() {
Log.setMinLogType(Type.Warn);
Log.setGUIStatusKnown();
}
|
diff --git a/zico-core/src/main/java/com/jitlogic/zico/core/HostStore.java b/zico-core/src/main/java/com/jitlogic/zico/core/HostStore.java
index 893ec05d..3ee3022a 100644
--- a/zico-core/src/main/java/com/jitlogic/zico/core/HostStore.java
+++ b/zico-core/src/main/java/com/jitlogic/zico/core/HostStore.java
@@ -1,770 +1,770 @@
/**
* Copyright 2012-2013 Rafal Lewczuk <[email protected]>
* <p/>
* This is free software. You can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
* <p/>
* 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 General Public License for more details.
* <p/>
* You should have received a copy of the GNU General Public License
* along with this software. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jitlogic.zico.core;
import com.jitlogic.zico.core.eql.Parser;
import com.jitlogic.zico.core.model.KeyValuePair;
import com.jitlogic.zico.core.model.SymbolicExceptionInfo;
import com.jitlogic.zico.core.model.TraceInfo;
import com.jitlogic.zico.core.model.TraceInfoRecord;
import com.jitlogic.zico.core.model.TraceInfoSearchQuery;
import com.jitlogic.zico.core.model.TraceInfoSearchResult;
import com.jitlogic.zico.core.model.TraceRecordSearchQuery;
import com.jitlogic.zico.core.rds.RAGZInputStream;
import com.jitlogic.zico.core.rds.RAGZSegment;
import com.jitlogic.zico.core.rds.RDSCleanupListener;
import com.jitlogic.zico.core.rds.RDSStore;
import com.jitlogic.zico.core.search.EqlTraceRecordMatcher;
import com.jitlogic.zico.core.search.FullTextTraceRecordMatcher;
import com.jitlogic.zico.core.search.TraceRecordMatcher;
import com.jitlogic.zico.shared.data.HostProxy;
import com.jitlogic.zico.shared.data.TraceInfoSearchQueryProxy;
import com.jitlogic.zico.shared.data.TraceInfoSearchResultProxy;
import com.jitlogic.zorka.common.tracedata.FressianTraceFormat;
import com.jitlogic.zorka.common.tracedata.SymbolRegistry;
import com.jitlogic.zorka.common.tracedata.SymbolicException;
import com.jitlogic.zorka.common.tracedata.SymbolicStackElement;
import com.jitlogic.zorka.common.tracedata.TraceMarker;
import com.jitlogic.zorka.common.tracedata.TraceRecord;
import com.jitlogic.zorka.common.util.ZorkaUtil;
import org.fressian.FressianReader;
import org.mapdb.BTreeMap;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.*;
import java.util.concurrent.ConcurrentNavigableMap;
/**
* Represents performance data store for a single agent.
*/
public class HostStore implements Closeable, RDSCleanupListener {
private final static Logger log = LoggerFactory.getLogger(HostStore.class);
public final static String HOST_PROPERTIES = "host.properties";
private static final String PROP_ADDR = "addr";
private static final String PROP_PASS = "pass";
private static final String PROP_FLAGS = "flags";
private static final String PROP_SIZE = "size";
private static final String PROP_COMMENT = "comment";
private final String DB_INFO_MAP = "INFOS";
private final String DB_TIDS_MAP = "TIDS";
private PersistentSymbolRegistry symbolRegistry;
private String rootPath;
private TraceRecordStore traceDataStore;
private TraceRecordStore traceIndexStore;
private TraceTemplateManager templater; // TODO move this out to service object
private ZicoConfig config;
private DB db;
private BTreeMap<Long, TraceInfoRecord> infos;
private Map<Integer, String> tids;
private String name;
- private String addr = "127.0.0.1";
+ private String addr = "";
private String pass = "";
private int flags;
private long maxSize;
private String comment = "";
private static final long MAX_SEARCH_T1 = 2000000000L;
private static final long MAX_SEARCH_T2 = 5000000000L;
public HostStore(ZicoConfig config, TraceTemplateManager templater, String name) {
this.name = name;
this.config = config;
this.rootPath = ZorkaUtil.path(config.getDataDir(), ZicoUtil.safePath(name));
File hostDir = new File(rootPath);
if (!hostDir.exists()) {
this.maxSize = config.longCfg("rds.max.size", 1024L * 1024L * 1024L);
hostDir.mkdirs();
save();
} else {
load();
}
this.templater = templater;
if (!hasFlag(HostProxy.DISABLED)) {
open();
}
}
public synchronized void open() {
try {
load();
if (symbolRegistry == null) {
symbolRegistry = new PersistentSymbolRegistry(
new File(ZicoUtil.ensureDir(rootPath), "symbols.dat"));
}
if (traceDataStore == null) {
traceDataStore = new TraceRecordStore(config, this, "tdat", 1, this);
}
if (traceIndexStore == null) {
traceIndexStore = new TraceRecordStore(config, this, "tidx", 16);
}
db = DBMaker.newFileDB(new File(rootPath, "traces.db"))
.mmapFileEnable().asyncWriteEnable().closeOnJvmShutdown().make();
infos = db.getTreeMap(DB_INFO_MAP);
tids = db.getTreeMap(DB_TIDS_MAP);
} catch (IOException e) {
log.error("Cannot open host store " + name, e);
}
}
@Override
public synchronized void close() {
if (symbolRegistry != null) {
try {
symbolRegistry.close();
} catch (IOException e) {
log.error("Cannot close symbol registry for " + name, e);
}
symbolRegistry = null;
}
if (traceDataStore != null) {
try {
traceDataStore.close();
} catch (IOException e) {
log.error("Cannot close trace data store for " + name, e);
}
traceDataStore = null;
}
if (traceIndexStore != null) {
try {
traceIndexStore.close();
} catch (IOException e) {
log.error("Cannot close trace index store for " + name, e);
}
traceIndexStore = null;
}
if (db != null) {
db.close();
db = null;
infos = null;
}
}
public void export() {
if (symbolRegistry != null) {
symbolRegistry.export();
}
}
public int countTraces() {
BTreeMap<Long,TraceInfoRecord> infos = getInfos();
if (infos == null) {
throw new ZicoRuntimeException("Store " + getName() + " is closed.");
}
return infos.size();
}
public void processTraceRecord(TraceRecord rec) throws IOException {
TraceRecordStore traceDataStore = getTraceDataStore();
TraceRecordStore traceIndexStore = getTraceIndexStore();
BTreeMap<Long,TraceInfoRecord> infos = getInfos();
Map<Integer,String> tids = getTids();
if (traceDataStore == null || traceIndexStore == null || infos == null || tids == null
|| hasFlag(HostProxy.DISABLED|HostProxy.DELETED)) {
throw new ZicoRuntimeException("Store " + getName() + " is closed and cannot accept records.");
}
TraceRecordStore.ChunkInfo dchunk = traceDataStore.write(rec);
List<TraceRecord> tmp = rec.getChildren();
int numRecords = ZicoUtil.numRecords(rec);
rec.setChildren(null);
TraceRecordStore.ChunkInfo ichunk = traceIndexStore.write(rec);
rec.setChildren(tmp);
TraceInfoRecord tir = new TraceInfoRecord(rec,numRecords,
dchunk.getOffset(), dchunk.getLength(),
ichunk.getOffset(), ichunk.getLength());
infos.put(tir.getDataOffs(), tir);
int traceId = tir.getTraceId();
if (!tids.containsKey(traceId)) {
tids.put(traceId, symbolRegistry.symbolName(traceId));
}
}
public synchronized void rebuildIndex() throws IOException {
int[] stats = new int[2];
log.info("Start rebuildIndex() operation for host " + name);
boolean enabled = isEnabled();
flags |= HostProxy.CHK_IN_PROGRESS;
if (enabled) {
setEnabled(false);
}
// Remove old files (if any)
File fTidx = new File(rootPath, "tidx");
if (fTidx.exists()) {
ZorkaUtil.rmrf(fTidx);
}
for (String s : new File(rootPath).list()) {
if (s.startsWith("traces.db")) {
new File(rootPath, s).delete();
}
}
// Reopen and rebuild both db and idx
open();
File tdatDir = new File(rootPath, "tdat");
List<String> fnames = Arrays.asList(tdatDir.list());
Collections.sort(fnames);
for (String fname : fnames) {
log.info("Processing file " + name + "/tdat/" + fname);
if (RDSStore.RGZ_FILE.matcher(fname).matches()) {
File f = new File(tdatDir, fname);
try {
RAGZInputStream is = RAGZInputStream.fromFile(f);
long fileBasePos = Long.parseLong(fname.substring(0, 16), 16);
for (RAGZSegment seg : is.getSegments()) {
if (seg.getLogicalLen() > 0) {
byte[] buf = new byte[(int)seg.getLogicalLen()];
is.seek((int)seg.getLogicalPos());
is.read(buf);
try {
rebuildSegmentIndex(fileBasePos, seg, buf, stats);
} catch (Exception e) {
log.warn("Dropping rest of segment " + seg + " of " + name + "/tdat/"
+ fname + " due to error.", e);
}
}
}
} catch (Exception e) {
log.error("Error processing file " + f + " ; all traces saved in this file will be dropped.", e);
}
db.commit();
}
}
close();
flags &= ~HostProxy.CHK_IN_PROGRESS;
if (enabled) {
setEnabled(enabled);
}
save();
log.info("Operation rebuildIndex() for host " + name + " finished. "
+ stats[0] + " traces imported, " + stats[1] + " traces dropped.");
}
private void rebuildSegmentIndex(long fileBasePos, RAGZSegment seg, byte[] buf, int[] stats) throws IOException {
ByteArrayInputStream bis = new ByteArrayInputStream(buf);
Object obj;
long basePos = seg.getLogicalPos() + fileBasePos, lastPos = basePos;
while (bis.available() > 0) {
try {
FressianReader reader = new FressianReader(bis, FressianTraceFormat.READ_LOOKUP);
obj = reader.readObject();
long dataLen = basePos + buf.length - bis.available() - lastPos;
if (obj instanceof TraceRecord) {
TraceRecord tr = (TraceRecord)obj;
int numRecords = ZicoUtil.numRecords(tr);
tr.setChildren(null);
TraceRecordStore.ChunkInfo idxChunk = traceIndexStore.write(tr);
TraceInfoRecord tir = new TraceInfoRecord(tr, numRecords,
lastPos, (int)dataLen, idxChunk.getOffset(), idxChunk.getLength());
infos.put(lastPos, tir);
int traceId = tir.getTraceId();
if (!tids.containsKey(traceId)) {
tids.put(traceId, symbolRegistry.symbolName(traceId));
}
stats[0]++;
}
lastPos += dataLen;
} catch (EOFException e) {
// This is normal.
}
}
}
public synchronized void commit() {
if (db != null) {
db.commit();
}
}
private void checkEnabled() {
if (hasFlag(HostProxy.DISABLED)) {
throw new ZicoRuntimeException("Host " + name
+ " is disabled. Bring it back online before issuing operation.");
}
}
private synchronized BTreeMap<Long,TraceInfoRecord> getInfos() {
return infos;
}
public TraceInfoSearchResult search(TraceInfoSearchQuery query) throws IOException {
SymbolRegistry symbolRegistry = getSymbolRegistry();
BTreeMap<Long,TraceInfoRecord> infos = getInfos();
TraceRecordStore traceDataStore = getTraceDataStore();
TraceRecordStore traceIndexStore = getTraceIndexStore();
if (symbolRegistry == null || infos == null || traceDataStore == null || traceIndexStore == null) {
throw new ZicoRuntimeException("Host store " + getName() + " is closed.");
}
List<TraceInfo> lst = new ArrayList<TraceInfo>(query.getLimit());
TraceInfoSearchResult result = new TraceInfoSearchResult(query.getSeq(), lst);
TraceRecordMatcher matcher = null;
int traceId = query.getTraceName() != null ? symbolRegistry.symbolId(query.getTraceName()) : 0;
if (query.getSearchExpr() != null) {
if (query.hasFlag(TraceInfoSearchQueryProxy.EQL_QUERY)) {
matcher = new EqlTraceRecordMatcher(symbolRegistry,
Parser.expr(query.getSearchExpr()),
0, 0, getName());
} else {
matcher = new FullTextTraceRecordMatcher(symbolRegistry,
TraceRecordSearchQuery.SEARCH_ALL, query.getSearchExpr());
}
}
// TODO implement query execution time limit
int searchFlags = query.getFlags();
boolean asc = 0 == (searchFlags & TraceInfoSearchQueryProxy.ORDER_DESC);
Long initialKey = asc
? infos.higherKey(query.getOffset() != 0 ? query.getOffset() : Long.MIN_VALUE)
: infos.lowerKey(query.getOffset() != 0 ? query.getOffset() : Long.MAX_VALUE);
long tstart = System.nanoTime();
for (Long key = initialKey; key != null; key = asc ? infos.higherKey(key) : infos.lowerKey(key)) {
long t = System.nanoTime()-tstart;
if ((lst.size() >= query.getLimit()) || (t > MAX_SEARCH_T1 && lst.size() > 0) || (t > MAX_SEARCH_T2)) {
result.markFlag(TraceInfoSearchResultProxy.MORE_RESULTS);
return result;
}
TraceInfoRecord tir = infos.get(key);
result.setLastOffs(key);
if (query.hasFlag(TraceInfoSearchQueryProxy.ERRORS_ONLY) && 0 == (tir.getTflags() & TraceMarker.ERROR_MARK)) {
continue;
}
if (traceId != 0 && tir.getTraceId() != traceId) {
continue;
}
if (tir.getDuration() < query.getMinMethodTime()) {
continue;
}
TraceRecord idxtr = (query.hasFlag(TraceInfoSearchQueryProxy.DEEP_SEARCH) && matcher != null)
? traceDataStore.read(tir.getDataChunk())
: traceIndexStore.read(tir.getIndexChunk());
if (idxtr != null) {
if (matcher instanceof EqlTraceRecordMatcher) {
((EqlTraceRecordMatcher) matcher).setTotalTime(tir.getDuration());
}
if (matcher == null || recursiveMatch(matcher, idxtr)) {
lst.add(toTraceInfo(tir, idxtr));
}
}
}
return result;
}
private boolean recursiveMatch(TraceRecordMatcher matcher, TraceRecord tr) {
if (matcher.match(tr)) {
return true;
}
if (tr.numChildren() > 0) {
for (TraceRecord c : tr.getChildren()) {
if (matcher.match(c)) {
return true;
}
}
}
return false;
}
public TraceInfoRecord getInfoRecord(long offs) {
checkEnabled();
return infos.get(offs);
}
private TraceInfo toTraceInfo(TraceInfoRecord itr, TraceRecord tr) throws IOException {
if (tr == null) {
tr = traceIndexStore.read(itr.getIndexChunk());
}
TraceInfo ti = new TraceInfo();
ti.setHostName(name);
ti.setDataOffs(itr.getDataOffs());
ti.setTraceId(itr.getTraceId());
ti.setTraceType(symbolRegistry.symbolName(itr.getTraceId()));
ti.setMethodFlags(itr.getRflags());
ti.setTraceFlags(itr.getTflags());
ti.setClassId(tr.getClassId());
ti.setMethodId(tr.getMethodId());
ti.setSignatureId(tr.getSignatureId());
ti.setStatus(tr.getException() != null // TODO get rid of this field
|| tr.hasFlag(TraceRecord.EXCEPTION_PASS)
|| tr.getMarker().hasFlag(TraceMarker.ERROR_MARK) ? 1 : 0);
ti.setRecords(itr.getRecords());
ti.setDataLen(itr.getDataLen());
ti.setCalls(itr.getCalls());
ti.setErrors(itr.getErrors());
ti.setExecutionTime(itr.getDuration());
ti.setClock(tr.getMarker().getClock());
if (tr != null && tr.getAttrs() != null) {
List<KeyValuePair> keyvals = new ArrayList<KeyValuePair>(tr.getAttrs().size());
for (Map.Entry<Integer, Object> e : tr.getAttrs().entrySet()) {
keyvals.add(new KeyValuePair(symbolRegistry.symbolName(e.getKey()), "" + e.getValue()));
}
ti.setAttributes(ZicoUtil.sortKeyVals(keyvals));
} else {
ti.setAttributes(Collections.EMPTY_LIST);
}
if (tr.getException() != null) {
SymbolicExceptionInfo sei = new SymbolicExceptionInfo();
SymbolicException sex = (SymbolicException) tr.getException();
sei.setExClass(symbolRegistry.symbolName(sex.getClassId()));
sei.setMessage(sex.getMessage());
List<String> lst = new ArrayList<String>();
for (SymbolicStackElement sel : sex.getStackTrace()) {
lst.add(symbolRegistry.symbolName(sel.getClassId()) + ":" + sel.getLineNum());
if (lst.size() > 10) {
break;
}
}
sei.setStackTrace(lst);
ti.setExceptionInfo(sei);
}
ti.setDescription(templater.templateDescription(symbolRegistry, name, tr));
return ti;
}
public synchronized Map<Integer,String> getTids() {
return tids;
}
public Map<Integer, String> getTidMap() {
Map<Integer,String> tids = getTids();
if (tids == null) {
throw new ZicoRuntimeException("Host store " + getName() + " is closed");
}
Map<Integer,String> tidMap = new HashMap<Integer, String>();
for (Integer tid : tids.keySet()) {
tidMap.put(tid, symbolRegistry.symbolName(tid));
}
return tidMap;
}
public String toString() {
return "HostStore(" + getName() + ")";
}
public synchronized void load() {
File f = new File(rootPath, HOST_PROPERTIES);
Properties props = new Properties();
if (f.exists() && f.canRead()) {
InputStream is = null;
try {
is = new FileInputStream(f);
props.load(is);
} catch (IOException e) {
log.error("Cannot read " + f, e);
} finally {
if (is != null) {
try { is.close(); } catch (IOException _) { }
}
}
this.addr = props.getProperty(PROP_ADDR, "127.0.0.1");
this.pass = props.getProperty(PROP_PASS, "");
this.flags = Integer.parseInt(props.getProperty(PROP_FLAGS, "0"));
this.maxSize = Long.parseLong(props.getProperty(PROP_SIZE,
"" + config.kiloCfg("rds.max.size", 1024 * 1024 * 1024L)));
this.comment = props.getProperty(PROP_COMMENT, "");
}
}
public synchronized void save() {
Properties props = new Properties();
props.setProperty(PROP_ADDR, addr);
props.setProperty(PROP_PASS, pass);
props.setProperty(PROP_FLAGS, "" + flags);
props.setProperty(PROP_SIZE, "" + maxSize);
props.setProperty(PROP_COMMENT, comment);
File f = new File(rootPath, HOST_PROPERTIES);
OutputStream os = null;
try {
os = new FileOutputStream(f);
props.store(os, "ZICO Host Descriptor");
} catch (IOException e) {
log.error("Cannot write " + f, e);
} finally {
if (os != null) {
try { os.close(); } catch (IOException _) { }
}
}
if (traceDataStore != null && maxSize != traceDataStore.getRds().getMaxSize()) {
traceDataStore.getRds().setMaxSize(maxSize);
try {
traceDataStore.getRds().cleanup();
} catch (IOException e) {
log.error("Cannot perform cleanup for host store " + name, e);
}
}
}
public synchronized TraceRecordStore getTraceDataStore() {
return traceDataStore;
}
public synchronized TraceRecordStore getTraceIndexStore() {
return traceIndexStore;
}
public synchronized SymbolRegistry getSymbolRegistry() {
return symbolRegistry;
}
public synchronized String getRootPath() {
return rootPath;
}
private DB getDb() {
return db;
}
@Override
public void onChunkRemoved(RDSStore origin, Long start, Long length) {
TraceRecordStore traceIndexStore = getTraceIndexStore();
BTreeMap<Long,TraceInfoRecord> infos = getInfos();
DB db = getDb();
long end = start + length - 1;
long t0 = System.currentTimeMillis();
log.info("Removing old index entries for host " + name);
long idxOffs = -1;
int count = 0;
if (infos != null && db != null) {
Map.Entry<Long, TraceInfoRecord> nextEntry = infos.ceilingEntry(end);
idxOffs = nextEntry != null ? nextEntry.getValue().getIndexOffs()-1 : -1;
ConcurrentNavigableMap<Long, TraceInfoRecord> rmitems = infos.headMap(end);
count = rmitems.size();
rmitems.clear();
db.commit();
}
if (idxOffs > 0 && traceIndexStore != null) {
try {
log.info("Cleaning up index RDS for host " + name + " (idxOffs=" + idxOffs + ")");
traceIndexStore.getRds().cleanup(idxOffs);
} catch (IOException e) {
log.error("Problem cleaning up index store", e);
}
}
long t = System.currentTimeMillis() - t0;
log.info("Removing " + count + " entries from " + name + " took " + t + "ms.");
}
public synchronized String getName() {
return name;
}
public synchronized String getAddr() {
return addr;
}
public synchronized void setAddr(String addr) {
this.addr = addr;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
public synchronized int getFlags() {
return flags;
}
public synchronized boolean hasFlag(int flag) {
return 0 != (this.flags & flag);
}
public synchronized void markFlag(int flag) {
flags |= flag;
}
public synchronized long getMaxSize() {
return maxSize;
}
public synchronized void setMaxSize(long maxSize) {
this.maxSize = maxSize;
if (traceDataStore != null) {
traceDataStore.getRds().setMaxSize(maxSize);
}
if (traceIndexStore != null) {
traceIndexStore.getRds().setMaxSize(maxSize);
}
}
public synchronized String getComment() {
return comment;
}
public synchronized void setComment(String comment) {
this.comment = comment;
}
public synchronized boolean isEnabled() {
return !hasFlag(HostProxy.DISABLED);
}
public synchronized void setEnabled(boolean enabled) {
if (enabled) {
log.info("Bringing host " + name + " online.");
open();
flags &= ~HostProxy.DISABLED;
} else {
log.info("Taking host " + name + " offline.");
close();
flags |= HostProxy.DISABLED;
}
}
}
| true | false | null | null |
diff --git a/mes-plugins/mes-plugins-time-norms-for-operations/src/test/java/com/qcadoo/mes/timeNormsForOperations/NormServiceTest.java b/mes-plugins/mes-plugins-time-norms-for-operations/src/test/java/com/qcadoo/mes/timeNormsForOperations/NormServiceTest.java
index 7a175b45a2..9923376593 100644
--- a/mes-plugins/mes-plugins-time-norms-for-operations/src/test/java/com/qcadoo/mes/timeNormsForOperations/NormServiceTest.java
+++ b/mes-plugins/mes-plugins-time-norms-for-operations/src/test/java/com/qcadoo/mes/timeNormsForOperations/NormServiceTest.java
@@ -1,127 +1,126 @@
package com.qcadoo.mes.timeNormsForOperations;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.math.BigDecimal;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.test.util.ReflectionTestUtils;
import com.qcadoo.localization.api.TranslationService;
import com.qcadoo.mes.technologies.TechnologyService;
import com.qcadoo.model.api.Entity;
import com.qcadoo.model.api.EntityTree;
public class NormServiceTest {
private NormService normService;
@Mock
private TechnologyService technologyService;
@Mock
private TranslationService translationService;
@Mock
private Entity technology, operComp1;
private static EntityTree mockEntityTreeIterator(List<Entity> list) {
EntityTree entityTree = mock(EntityTree.class);
when(entityTree.iterator()).thenReturn(list.iterator());
return entityTree;
}
@Before
public void init() {
MockitoAnnotations.initMocks(this);
normService = new NormService();
ReflectionTestUtils.setField(normService, "technologyService", technologyService);
- ReflectionTestUtils.setField(normService, "translationService", translationService);
given(operComp1.getStringField("entityType")).willReturn("operation");
}
@Test
public void shouldOmmitCheckingIfTheTreeIsntCompleteYet() {
// given
EntityTree tree = mockEntityTreeIterator(new LinkedList<Entity>());
given(technology.getTreeField("operationComponents")).willReturn(tree);
// when
Map<String, String> messages = normService.checkOperationOutputQuantities(technology);
// then
assertTrue(messages.isEmpty());
}
@Test
public void shouldNotFreakOutIfItCantFindOutputProductForAnOperationComponent() {
// given
EntityTree tree = mockEntityTreeIterator(asList(operComp1));
given(technology.getTreeField("operationComponents")).willReturn(tree);
given(technologyService.getProductCountForOperationComponent(operComp1)).willThrow(new IllegalStateException());
// when
Map<String, String> messages = normService.checkOperationOutputQuantities(technology);
// then
assertTrue(messages.isEmpty());
}
@Ignore
@Test
public void shouldReturnAnErrorMessageIfTheQuantitiesDontMatch() {
// given
EntityTree tree = mockEntityTreeIterator(asList(operComp1));
given(technology.getTreeField("operationComponents")).willReturn(tree);
given(technologyService.getProductCountForOperationComponent(operComp1)).willReturn(new BigDecimal(13.5));
given(operComp1.getDecimalField("productionInOneCycle")).willReturn(new BigDecimal(13.51));
Locale locale = LocaleContextHolder.getLocale();
given(translationService.translate("technologies.technology.validate.error.invalidQuantity1", locale)).willReturn(
"message1");
given(operComp1.getStringField("nodeNumber")).willReturn("1");
given(translationService.translate("technologies.technology.validate.error.invalidQuantity2", locale)).willReturn(
"message2");
// when
Map<String, String> messages = normService.checkOperationOutputQuantities(technology);
// then
assertEquals(1, messages.size());
assertEquals("message1 1 message2", messages.get(0));
}
@Ignore
@Test
public void shouldReturnNoErrorsIfTheQuantitiesDoMatch() {
// given
EntityTree tree = mockEntityTreeIterator(asList(operComp1));
given(technology.getTreeField("operationComponents")).willReturn(tree);
given(technologyService.getProductCountForOperationComponent(operComp1)).willReturn(new BigDecimal(13.5));
given(operComp1.getDecimalField("productionInOneCycle")).willReturn(new BigDecimal(13.500));
// when
Map<String, String> messages = normService.checkOperationOutputQuantities(technology);
// then
assertEquals(0, messages.size());
}
}
| true | false | null | null |
diff --git a/core/src/processing/core/PGraphics.java b/core/src/processing/core/PGraphics.java
index 025cc3a61..c4856d068 100644
--- a/core/src/processing/core/PGraphics.java
+++ b/core/src/processing/core/PGraphics.java
@@ -1,7850 +1,7851 @@
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2004-11 Ben Fry and Casey Reas
Copyright (c) 2001-04 Massachusetts Institute of Technology
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General
Public License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA 02111-1307 USA
*/
package processing.core;
import java.awt.*;
import java.util.HashMap;
import java.util.WeakHashMap;
import processing.opengl.PGL;
import processing.opengl.PShader;
/**
* ( begin auto-generated from PGraphics.xml )
*
* Main graphics and rendering context, as well as the base API
* implementation for processing "core". Use this class if you need to draw
* into an off-screen graphics buffer. A PGraphics object can be
* constructed with the <b>createGraphics()</b> function. The
* <b>beginDraw()</b> and <b>endDraw()</b> methods (see above example) are
* necessary to set up the buffer and to finalize it. The fields and
* methods for this class are extensive. For a complete list, visit the <a
* href="http://processing.googlecode.com/svn/trunk/processing/build/javadoc/core/">developer's reference.</a>
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* Main graphics and rendering context, as well as the base API implementation.
*
* <h2>Subclassing and initializing PGraphics objects</h2>
* Starting in release 0149, subclasses of PGraphics are handled differently.
* The constructor for subclasses takes no parameters, instead a series of
* functions are called by the hosting PApplet to specify its attributes.
* <ul>
* <li>setParent(PApplet) - is called to specify the parent PApplet.
* <li>setPrimary(boolean) - called with true if this PGraphics will be the
* primary drawing surface used by the sketch, or false if not.
* <li>setPath(String) - called when the renderer needs a filename or output
* path, such as with the PDF or DXF renderers.
* <li>setSize(int, int) - this is called last, at which point it's safe for
* the renderer to complete its initialization routine.
* </ul>
* The functions were broken out because of the growing number of parameters
* such as these that might be used by a renderer, yet with the exception of
* setSize(), it's not clear which will be necessary. So while the size could
* be passed in to the constructor instead of a setSize() function, a function
* would still be needed that would notify the renderer that it was time to
* finish its initialization. Thus, setSize() simply does both.
*
* <h2>Know your rights: public vs. private methods</h2>
* Methods that are protected are often subclassed by other renderers, however
* they are not set 'public' because they shouldn't be part of the user-facing
* public API accessible from PApplet. That is, we don't want sketches calling
* textModeCheck() or vertexTexture() directly.
*
* <h2>Handling warnings and exceptions</h2>
* Methods that are unavailable generally show a warning, unless their lack of
* availability will soon cause another exception. For instance, if a method
* like getMatrix() returns null because it is unavailable, an exception will
* be thrown stating that the method is unavailable, rather than waiting for
* the NullPointerException that will occur when the sketch tries to use that
* method. As of release 0149, warnings will only be shown once, and exceptions
* have been changed to warnings where possible.
*
* <h2>Using xxxxImpl() for subclassing smoothness</h2>
* The xxxImpl() methods are generally renderer-specific handling for some
* subset if tasks for a particular function (vague enough for you?) For
* instance, imageImpl() handles drawing an image whose x/y/w/h and u/v coords
* have been specified, and screen placement (independent of imageMode) has
* been determined. There's no point in all renderers implementing the
* <tt>if (imageMode == BLAH)</tt> placement/sizing logic, so that's handled
* by PGraphics, which then calls imageImpl() once all that is figured out.
*
* <h2>His brother PImage</h2>
* PGraphics subclasses PImage so that it can be drawn and manipulated in a
* similar fashion. As such, many methods are inherited from PGraphics,
* though many are unavailable: for instance, resize() is not likely to be
* implemented; the same goes for mask(), depending on the situation.
*
* <h2>What's in PGraphics, what ain't</h2>
* For the benefit of subclasses, as much as possible has been placed inside
* PGraphics. For instance, bezier interpolation code and implementations of
* the strokeCap() method (that simply sets the strokeCap variable) are
* handled here. Features that will vary widely between renderers are located
* inside the subclasses themselves. For instance, all matrix handling code
* is per-renderer: Java 2D uses its own AffineTransform, P2D uses a PMatrix2D,
* and PGraphics3D needs to keep continually update forward and reverse
* transformations. A proper (future) OpenGL implementation will have all its
* matrix madness handled by the card. Lighting also falls under this
* category, however the base material property settings (emissive, specular,
* et al.) are handled in PGraphics because they use the standard colorMode()
* logic. Subclasses should override methods like emissiveFromCalc(), which
* is a point where a valid color has been defined internally, and can be
* applied in some manner based on the calcXxxx values.
*
* <h2>What's in the PGraphics documentation, what ain't</h2>
* Some things are noted here, some things are not. For public API, always
* refer to the <a href="http://processing.org/reference">reference</A>
* on Processing.org for proper explanations. <b>No attempt has been made to
* keep the javadoc up to date or complete.</b> It's an enormous task for
* which we simply do not have the time. That is, it's not something that
* to be done once—it's a matter of keeping the multiple references
* synchronized (to say nothing of the translation issues), while targeting
* them for their separate audiences. Ouch.
*
* We're working right now on synchronizing the two references, so the website reference
* is generated from the javadoc comments. Yay.
*
* @webref rendering
* @instanceName graphics any object of the type PGraphics
* @usage Web & Application
* @see PApplet#createGraphics(int, int, String)
*/
public class PGraphics extends PImage implements PConstants {
/// Canvas object that covers rendering this graphics on screen.
public Canvas canvas;
// ........................................................
// width and height are already inherited from PImage
// /// width minus one (useful for many calculations)
// protected int width1;
//
// /// height minus one (useful for many calculations)
// protected int height1;
/// width * height (useful for many calculations)
public int pixelCount;
/// true if smoothing is enabled (read-only)
public boolean smooth;
/// the anti-aliasing level for renderers that support it
public int quality;
// ........................................................
/// true if defaults() has been called a first time
protected boolean settingsInited;
/// true if defaults() has been called a first time
protected boolean reapplySettings;
/// set to a PGraphics object being used inside a beginRaw/endRaw() block
protected PGraphics raw;
// ........................................................
/** path to the file being saved for this renderer (if any) */
protected String path;
/**
* true if this is the main drawing surface for a particular sketch.
* This would be set to false for an offscreen buffer or if it were
* created any other way than size(). When this is set, the listeners
* are also added to the sketch.
*/
protected boolean primarySurface;
// ........................................................
/**
* Array of hint[] items. These are hacks to get around various
* temporary workarounds inside the environment.
* <p/>
* Note that this array cannot be static, as a hint() may result in a
* runtime change specific to a renderer. For instance, calling
* hint(DISABLE_DEPTH_TEST) has to call glDisable() right away on an
* instance of PGraphicsOpenGL.
* <p/>
* The hints[] array is allocated early on because it might
* be used inside beginDraw(), allocate(), etc.
*/
protected boolean[] hints = new boolean[HINT_COUNT];
// ........................................................
/**
* Storage for renderer-specific image data. In 1.x, renderers wrote cache
* data into the image object. In 2.x, the renderer has a weak-referenced
* map that points at any of the images it has worked on already. When the
* images go out of scope, they will be properly garbage collected.
*/
protected WeakHashMap<PImage, Object> cacheMap =
new WeakHashMap<PImage, Object>();
////////////////////////////////////////////////////////////
// Vertex fields, moved from PConstants (after 2.0a8) because they're too
// general to show up in all sketches as defined variables.
// X, Y and Z are still stored in PConstants because of their general
// usefulness, and that X we'll always want to be 0, etc.
static public final int R = 3; // actual rgb, after lighting
static public final int G = 4; // fill stored here, transform in place
static public final int B = 5; // TODO don't do that anymore (?)
static public final int A = 6;
static public final int U = 7; // texture
static public final int V = 8;
static public final int NX = 9; // normal
static public final int NY = 10;
static public final int NZ = 11;
static public final int EDGE = 12;
// stroke
/** stroke argb values */
static public final int SR = 13;
static public final int SG = 14;
static public final int SB = 15;
static public final int SA = 16;
/** stroke weight */
static public final int SW = 17;
// transformations (2D and 3D)
static public final int TX = 18; // transformed xyzw
static public final int TY = 19;
static public final int TZ = 20;
static public final int VX = 21; // view space coords
static public final int VY = 22;
static public final int VZ = 23;
static public final int VW = 24;
// material properties
// Ambient color (usually to be kept the same as diffuse)
// fill(_) sets both ambient and diffuse.
static public final int AR = 25;
static public final int AG = 26;
static public final int AB = 27;
// Diffuse is shared with fill.
static public final int DR = 3; // TODO needs to not be shared, this is a material property
static public final int DG = 4;
static public final int DB = 5;
static public final int DA = 6;
// specular (by default kept white)
static public final int SPR = 28;
static public final int SPG = 29;
static public final int SPB = 30;
static public final int SHINE = 31;
// emissive (by default kept black)
static public final int ER = 32;
static public final int EG = 33;
static public final int EB = 34;
// has this vertex been lit yet
static public final int BEEN_LIT = 35;
// has this vertex been assigned a normal yet
static public final int HAS_NORMAL = 36;
static public final int VERTEX_FIELD_COUNT = 37;
////////////////////////////////////////////////////////////
// STYLE PROPERTIES
// Also inherits imageMode() and smooth() (among others) from PImage.
/** The current colorMode */
public int colorMode; // = RGB;
/** Max value for red (or hue) set by colorMode */
public float colorModeX; // = 255;
/** Max value for green (or saturation) set by colorMode */
public float colorModeY; // = 255;
/** Max value for blue (or value) set by colorMode */
public float colorModeZ; // = 255;
/** Max value for alpha set by colorMode */
public float colorModeA; // = 255;
/** True if colors are not in the range 0..1 */
boolean colorModeScale; // = true;
/** True if colorMode(RGB, 255) */
boolean colorModeDefault; // = true;
// ........................................................
// Tint color for images
/**
* True if tint() is enabled (read-only).
*
* Using tint/tintColor seems a better option for naming than
* tintEnabled/tint because the latter seems ugly, even though
* g.tint as the actual color seems a little more intuitive,
* it's just that g.tintEnabled is even more unintuitive.
* Same goes for fill and stroke, et al.
*/
public boolean tint;
/** tint that was last set (read-only) */
public int tintColor;
protected boolean tintAlpha;
protected float tintR, tintG, tintB, tintA;
protected int tintRi, tintGi, tintBi, tintAi;
// ........................................................
// Fill color
/** true if fill() is enabled, (read-only) */
public boolean fill;
/** fill that was last set (read-only) */
public int fillColor = 0xffFFFFFF;
protected boolean fillAlpha;
protected float fillR, fillG, fillB, fillA;
protected int fillRi, fillGi, fillBi, fillAi;
// ........................................................
// Stroke color
/** true if stroke() is enabled, (read-only) */
public boolean stroke;
/** stroke that was last set (read-only) */
public int strokeColor = 0xff000000;
protected boolean strokeAlpha;
protected float strokeR, strokeG, strokeB, strokeA;
protected int strokeRi, strokeGi, strokeBi, strokeAi;
// ........................................................
// Additional stroke properties
static protected final float DEFAULT_STROKE_WEIGHT = 1;
static protected final int DEFAULT_STROKE_JOIN = MITER;
static protected final int DEFAULT_STROKE_CAP = ROUND;
/**
* Last value set by strokeWeight() (read-only). This has a default
* setting, rather than fighting with renderers about whether that
* renderer supports thick lines.
*/
public float strokeWeight = DEFAULT_STROKE_WEIGHT;
/**
* Set by strokeJoin() (read-only). This has a default setting
* so that strokeJoin() need not be called by defaults,
* because subclasses may not implement it (i.e. PGraphicsGL)
*/
public int strokeJoin = DEFAULT_STROKE_JOIN;
/**
* Set by strokeCap() (read-only). This has a default setting
* so that strokeCap() need not be called by defaults,
* because subclasses may not implement it (i.e. PGraphicsGL)
*/
public int strokeCap = DEFAULT_STROKE_CAP;
// ........................................................
// Shape placement properties
// imageMode() is inherited from PImage
/** The current rect mode (read-only) */
public int rectMode;
/** The current ellipse mode (read-only) */
public int ellipseMode;
/** The current shape alignment mode (read-only) */
public int shapeMode;
/** The current image alignment (read-only) */
public int imageMode = CORNER;
// ........................................................
// Text and font properties
/** The current text font (read-only) */
public PFont textFont;
/** The current text align (read-only) */
public int textAlign = LEFT;
/** The current vertical text alignment (read-only) */
public int textAlignY = BASELINE;
/** The current text mode (read-only) */
public int textMode = MODEL;
/** The current text size (read-only) */
public float textSize;
/** The current text leading (read-only) */
public float textLeading;
// ........................................................
// Material properties
// PMaterial material;
// PMaterial[] materialStack;
// int materialStackPointer;
public int ambientColor;
public float ambientR, ambientG, ambientB;
public boolean setAmbient;
public int specularColor;
public float specularR, specularG, specularB;
public int emissiveColor;
public float emissiveR, emissiveG, emissiveB;
public float shininess;
// Style stack
static final int STYLE_STACK_DEPTH = 64;
PStyle[] styleStack = new PStyle[STYLE_STACK_DEPTH];
int styleStackDepth;
////////////////////////////////////////////////////////////
/** Last background color that was set, zero if an image */
public int backgroundColor = 0xffCCCCCC;
protected boolean backgroundAlpha;
protected float backgroundR, backgroundG, backgroundB, backgroundA;
protected int backgroundRi, backgroundGi, backgroundBi, backgroundAi;
// ........................................................
/**
* Current model-view matrix transformation of the form m[row][column],
* which is a "column vector" (as opposed to "row vector") matrix.
*/
// PMatrix matrix;
// public float m00, m01, m02, m03;
// public float m10, m11, m12, m13;
// public float m20, m21, m22, m23;
// public float m30, m31, m32, m33;
// static final int MATRIX_STACK_DEPTH = 32;
// float[][] matrixStack = new float[MATRIX_STACK_DEPTH][16];
// float[][] matrixInvStack = new float[MATRIX_STACK_DEPTH][16];
// int matrixStackDepth;
static final int MATRIX_STACK_DEPTH = 32;
// ........................................................
/**
* Java AWT Image object associated with this renderer. For the 1.0 version
* of P2D and P3D, this was be associated with their MemoryImageSource.
* For PGraphicsJava2D, it will be the offscreen drawing buffer.
*/
public Image image;
// ........................................................
// internal color for setting/calculating
protected float calcR, calcG, calcB, calcA;
protected int calcRi, calcGi, calcBi, calcAi;
protected int calcColor;
protected boolean calcAlpha;
/** The last RGB value converted to HSB */
int cacheHsbKey;
/** Result of the last conversion to HSB */
float[] cacheHsbValue = new float[3];
// ........................................................
/**
* Type of shape passed to beginShape(),
* zero if no shape is currently being drawn.
*/
protected int shape;
// vertices
public static final int DEFAULT_VERTICES = 512;
protected float vertices[][] =
new float[DEFAULT_VERTICES][VERTEX_FIELD_COUNT];
protected int vertexCount; // total number of vertices
// ........................................................
protected boolean bezierInited = false;
public int bezierDetail = 20;
// used by both curve and bezier, so just init here
protected PMatrix3D bezierBasisMatrix =
new PMatrix3D(-1, 3, -3, 1,
3, -6, 3, 0,
-3, 3, 0, 0,
1, 0, 0, 0);
//protected PMatrix3D bezierForwardMatrix;
protected PMatrix3D bezierDrawMatrix;
// ........................................................
protected boolean curveInited = false;
public int curveDetail = 20;
public float curveTightness = 0;
// catmull-rom basis matrix, perhaps with optional s parameter
protected PMatrix3D curveBasisMatrix;
protected PMatrix3D curveDrawMatrix;
protected PMatrix3D bezierBasisInverse;
protected PMatrix3D curveToBezierMatrix;
// ........................................................
// spline vertices
protected float curveVertices[][];
protected int curveVertexCount;
// ........................................................
// precalculate sin/cos lookup tables [toxi]
// circle resolution is determined from the actual used radii
// passed to ellipse() method. this will automatically take any
// scale transformations into account too
// [toxi 031031]
// changed table's precision to 0.5 degree steps
// introduced new vars for more flexible code
static final protected float sinLUT[];
static final protected float cosLUT[];
static final protected float SINCOS_PRECISION = 0.5f;
static final protected int SINCOS_LENGTH = (int) (360f / SINCOS_PRECISION);
static {
sinLUT = new float[SINCOS_LENGTH];
cosLUT = new float[SINCOS_LENGTH];
for (int i = 0; i < SINCOS_LENGTH; i++) {
sinLUT[i] = (float) Math.sin(i * DEG_TO_RAD * SINCOS_PRECISION);
cosLUT[i] = (float) Math.cos(i * DEG_TO_RAD * SINCOS_PRECISION);
}
}
// ........................................................
/** The current font if a Java version of it is installed */
//protected Font textFontNative;
/** Metrics for the current native Java font */
//protected FontMetrics textFontNativeMetrics;
// /** Last text position, because text often mixed on lines together */
// protected float textX, textY, textZ;
/**
* Internal buffer used by the text() functions
* because the String object is slow
*/
protected char[] textBuffer = new char[8 * 1024];
protected char[] textWidthBuffer = new char[8 * 1024];
protected int textBreakCount;
protected int[] textBreakStart;
protected int[] textBreakStop;
// ........................................................
public boolean edge = true;
// ........................................................
/// normal calculated per triangle
static protected final int NORMAL_MODE_AUTO = 0;
/// one normal manually specified per shape
static protected final int NORMAL_MODE_SHAPE = 1;
/// normals specified for each shape vertex
static protected final int NORMAL_MODE_VERTEX = 2;
/// Current mode for normals, one of AUTO, SHAPE, or VERTEX
protected int normalMode;
/// Keep track of how many calls to normal, to determine the mode.
//protected int normalCount;
protected boolean autoNormal;
/** Current normal vector. */
public float normalX, normalY, normalZ;
// ........................................................
/**
* Sets whether texture coordinates passed to
* vertex() calls will be based on coordinates that are
* based on the IMAGE or NORMALIZED.
*/
public int textureMode = IMAGE;
/**
* Current horizontal coordinate for texture, will always
* be between 0 and 1, even if using textureMode(IMAGE).
*/
public float textureU;
/** Current vertical coordinate for texture, see above. */
public float textureV;
/** Current image being used as a texture */
public PImage textureImage;
// ........................................................
// [toxi031031] new & faster sphere code w/ support flexible resolutions
// will be set by sphereDetail() or 1st call to sphere()
protected float sphereX[], sphereY[], sphereZ[];
/// Number of U steps (aka "theta") around longitudinally spanning 2*pi
public int sphereDetailU = 0;
/// Number of V steps (aka "phi") along latitudinally top-to-bottom spanning pi
public int sphereDetailV = 0;
//////////////////////////////////////////////////////////////
// INTERNAL
/**
* Constructor for the PGraphics object. Use this to ensure that
* the defaults get set properly. In a subclass, use this(w, h)
* as the first line of a subclass' constructor to properly set
* the internal fields and defaults.
*
*/
public PGraphics() {
}
public void setParent(PApplet parent) { // ignore
this.parent = parent;
quality = parent.sketchQuality();
}
/**
* Set (or unset) this as the main drawing surface. Meaning that it can
* safely be set to opaque (and given a default gray background), or anything
* else that goes along with that.
*/
public void setPrimary(boolean primary) { // ignore
this.primarySurface = primary;
// base images must be opaque (for performance and general
// headache reasons.. argh, a semi-transparent opengl surface?)
// use createGraphics() if you want a transparent surface.
if (primarySurface) {
format = RGB;
}
}
public void setPath(String path) { // ignore
this.path = path;
}
// public void setQuality(int samples) { // ignore
// this.quality = samples;
// }
public void setFrameRate(float frameRate) { // ignore
}
/**
* The final step in setting up a renderer, set its size of this renderer.
* This was formerly handled by the constructor, but instead it's been broken
* out so that setParent/setPrimary/setPath can be handled differently.
*
* Important that this is ignored by preproc.pl because otherwise it will
* override setSize() in PApplet/Applet/Component, which will 1) not call
* super.setSize(), and 2) will cause the renderer to be resized from the
* event thread (EDT), causing a nasty crash as it collides with the
* animation thread.
*/
public void setSize(int w, int h) { // ignore
width = w;
height = h;
// width1 = width - 1;
// height1 = height - 1;
allocate();
reapplySettings();
}
/**
* Allocate memory for this renderer. Generally will need to be implemented
* for all renderers.
*/
protected void allocate() { }
/**
* Handle any takedown for this graphics context.
* <p>
* This is called when a sketch is shut down and this renderer was
* specified using the size() command, or inside endRecord() and
* endRaw(), in order to shut things off.
*/
public void dispose() { // ignore
}
//////////////////////////////////////////////////////////////
// IMAGE METADATA FOR THIS RENDERER
/**
* Store data of some kind for the renderer that requires extra metadata of
* some kind. Usually this is a renderer-specific representation of the
* image data, for instance a BufferedImage with tint() settings applied for
* PGraphicsJava2D, or resized image data and OpenGL texture indices for
* PGraphicsOpenGL.
* @param renderer The PGraphics renderer associated to the image
* @param storage The metadata required by the renderer
*/
public void setCache(PImage image, Object storage) {
cacheMap.put(image, storage);
}
/**
* Get cache storage data for the specified renderer. Because each renderer
* will cache data in different formats, it's necessary to store cache data
* keyed by the renderer object. Otherwise, attempting to draw the same
* image to both a PGraphicsJava2D and a PGraphicsOpenGL will cause errors.
* @param renderer The PGraphics renderer associated to the image
* @return metadata stored for the specified renderer
*/
public Object getCache(PImage image) {
return cacheMap.get(image);
}
/**
* Remove information associated with this renderer from the cache, if any.
* @param renderer The PGraphics renderer whose cache data should be removed
*/
public void removeCache(PImage image) {
cacheMap.remove(image);
}
//////////////////////////////////////////////////////////////
// FRAME
/**
* Some renderers have requirements re: when they are ready to draw.
*/
public boolean canDraw() { // ignore
return true;
}
/**
* Try to draw, or put a draw request on the queue.
*/
public void requestDraw() { // ignore
parent.handleDraw();
}
/**
* ( begin auto-generated from PGraphics_beginDraw.xml )
*
* Sets the default properties for a PGraphics object. It should be called
* before anything is drawn into the object.
*
* ( end auto-generated )
* <h3>Advanced</h3>
* When creating your own PGraphics, you should call this before
* drawing anything.
*
* @webref pgraphics:method
* @brief Sets the default properties for a PGraphics object
*/
public void beginDraw() { // ignore
}
/**
* ( begin auto-generated from PGraphics_endDraw.xml )
*
* Finalizes the rendering of a PGraphics object so that it can be shown on screen.
*
* ( end auto-generated )
* <h3>Advanced</h3>
* <p/>
* When creating your own PGraphics, you should call this when
* you're finished drawing.
*
* @webref pgraphics:method
* @brief Finalizes the rendering of a PGraphics object
*/
public void endDraw() { // ignore
}
public PGL beginPGL() {
showMethodWarning("beginGL");
return null;
}
public void endPGL() {
showMethodWarning("endGL");
}
public void flush() {
// no-op, mostly for P3D to write sorted stuff
}
protected void checkSettings() {
if (!settingsInited) defaultSettings();
if (reapplySettings) reapplySettings();
}
/**
* Set engine's default values. This has to be called by PApplet,
* somewhere inside setup() or draw() because it talks to the
* graphics buffer, meaning that for subclasses like OpenGL, there
* needs to be a valid graphics context to mess with otherwise
* you'll get some good crashing action.
*
* This is currently called by checkSettings(), during beginDraw().
*/
protected void defaultSettings() { // ignore
// System.out.println("PGraphics.defaultSettings() " + width + " " + height);
//smooth(); // 2.0a5
if (quality > 0) { // 2.0a5
smooth();
} else {
noSmooth();
}
colorMode(RGB, 255);
fill(255);
stroke(0);
// as of 0178, no longer relying on local versions of the variables
// being set, because subclasses may need to take extra action.
strokeWeight(DEFAULT_STROKE_WEIGHT);
strokeJoin(DEFAULT_STROKE_JOIN);
strokeCap(DEFAULT_STROKE_CAP);
// init shape stuff
shape = 0;
rectMode(CORNER);
ellipseMode(DIAMETER);
autoNormal = true;
// no current font
textFont = null;
textSize = 12;
textLeading = 14;
textAlign = LEFT;
textMode = MODEL;
// if this fella is associated with an applet, then clear its background.
// if it's been created by someone else through createGraphics,
// they have to call background() themselves, otherwise everything gets
// a gray background (when just a transparent surface or an empty pdf
// is what's desired).
// this background() call is for the Java 2D and OpenGL renderers.
if (primarySurface) {
//System.out.println("main drawing surface bg " + getClass().getName());
background(backgroundColor);
}
settingsInited = true;
// defaultSettings() overlaps reapplySettings(), don't do both
//reapplySettings = false;
}
/**
* Re-apply current settings. Some methods, such as textFont(), require that
* their methods be called (rather than simply setting the textFont variable)
* because they affect the graphics context, or they require parameters from
* the context (e.g. getting native fonts for text).
*
* This will only be called from an allocate(), which is only called from
* size(), which is safely called from inside beginDraw(). And it cannot be
* called before defaultSettings(), so we should be safe.
*/
protected void reapplySettings() {
// System.out.println("attempting reapplySettings()");
if (!settingsInited) return; // if this is the initial setup, no need to reapply
// System.out.println(" doing reapplySettings");
// new Exception().printStackTrace(System.out);
colorMode(colorMode, colorModeX, colorModeY, colorModeZ);
if (fill) {
// PApplet.println(" fill " + PApplet.hex(fillColor));
fill(fillColor);
} else {
noFill();
}
if (stroke) {
stroke(strokeColor);
// The if() statements should be handled inside the functions,
// otherwise an actual reset/revert won't work properly.
//if (strokeWeight != DEFAULT_STROKE_WEIGHT) {
strokeWeight(strokeWeight);
//}
// if (strokeCap != DEFAULT_STROKE_CAP) {
strokeCap(strokeCap);
// }
// if (strokeJoin != DEFAULT_STROKE_JOIN) {
strokeJoin(strokeJoin);
// }
} else {
noStroke();
}
if (tint) {
tint(tintColor);
} else {
noTint();
}
if (smooth) {
smooth();
} else {
// Don't bother setting this, cuz it'll anger P3D.
noSmooth();
}
if (textFont != null) {
// System.out.println(" textFont in reapply is " + textFont);
// textFont() resets the leading, so save it in case it's changed
float saveLeading = textLeading;
textFont(textFont, textSize);
textLeading(saveLeading);
}
textMode(textMode);
textAlign(textAlign, textAlignY);
background(backgroundColor);
reapplySettings = false;
}
// inherit from PImage
//public void resize(int wide, int high){ }
//////////////////////////////////////////////////////////////
// HINTS
/**
* ( begin auto-generated from hint.xml )
*
* Set various hints and hacks for the renderer. This is used to handle
* obscure rendering features that cannot be implemented in a consistent
* manner across renderers. Many options will often graduate to standard
* features instead of hints over time.
* <br/> <br/>
* hint(ENABLE_OPENGL_4X_SMOOTH) - Enable 4x anti-aliasing for P3D. This
* can help force anti-aliasing if it has not been enabled by the user. On
* some graphics cards, this can also be set by the graphics driver's
* control panel, however not all cards make this available. This hint must
* be called immediately after the size() command because it resets the
* renderer, obliterating any settings and anything drawn (and like size(),
* re-running the code that came before it again).
* <br/> <br/>
* hint(DISABLE_OPENGL_2X_SMOOTH) - In Processing 1.0, Processing always
* enables 2x smoothing when the P3D renderer is used. This hint disables
* the default 2x smoothing and returns the smoothing behavior found in
* earlier releases, where smooth() and noSmooth() could be used to enable
* and disable smoothing, though the quality was inferior.
* <br/> <br/>
* hint(ENABLE_NATIVE_FONTS) - Use the native version fonts when they are
* installed, rather than the bitmapped version from a .vlw file. This is
* useful with the default (or JAVA2D) renderer setting, as it will improve
* font rendering speed. This is not enabled by default, because it can be
* misleading while testing because the type will look great on your
* machine (because you have the font installed) but lousy on others'
* machines if the identical font is unavailable. This option can only be
* set per-sketch, and must be called before any use of textFont().
* <br/> <br/>
* hint(DISABLE_DEPTH_TEST) - Disable the zbuffer, allowing you to draw on
* top of everything at will. When depth testing is disabled, items will be
* drawn to the screen sequentially, like a painting. This hint is most
* often used to draw in 3D, then draw in 2D on top of it (for instance, to
* draw GUI controls in 2D on top of a 3D interface). Starting in release
* 0149, this will also clear the depth buffer. Restore the default with
* hint(ENABLE_DEPTH_TEST), but note that with the depth buffer cleared,
* any 3D drawing that happens later in draw() will ignore existing shapes
* on the screen.
* <br/> <br/>
* hint(ENABLE_DEPTH_SORT) - Enable primitive z-sorting of triangles and
* lines in P3D and OPENGL. This can slow performance considerably, and the
* algorithm is not yet perfect. Restore the default with hint(DISABLE_DEPTH_SORT).
* <br/> <br/>
* hint(DISABLE_OPENGL_ERROR_REPORT) - Speeds up the P3D renderer setting
* by not checking for errors while running. Undo with hint(ENABLE_OPENGL_ERROR_REPORT).
* <br/> <br/>
* As of release 0149, unhint() has been removed in favor of adding
* additional ENABLE/DISABLE constants to reset the default behavior. This
* prevents the double negatives, and also reinforces which hints can be
* enabled or disabled.
*
* ( end auto-generated )
* @webref rendering
* @param which name of the hint to be enabled or disabled
* @see PGraphics
* @see PApplet#createGraphics(int, int, String, String)
* @see PApplet#size(int, int)
*/
public void hint(int which) {
if (which > 0) {
hints[which] = true;
} else {
hints[-which] = false;
}
}
//////////////////////////////////////////////////////////////
// VERTEX SHAPES
/**
* Start a new shape of type POLYGON
*/
public void beginShape() {
beginShape(POLYGON);
}
/**
* ( begin auto-generated from beginShape.xml )
*
* Using the <b>beginShape()</b> and <b>endShape()</b> functions allow
* creating more complex forms. <b>beginShape()</b> begins recording
* vertices for a shape and <b>endShape()</b> stops recording. The value of
* the <b>MODE</b> parameter tells it which types of shapes to create from
* the provided vertices. With no mode specified, the shape can be any
* irregular polygon. The parameters available for beginShape() are POINTS,
* LINES, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, QUADS, and QUAD_STRIP.
* After calling the <b>beginShape()</b> function, a series of
* <b>vertex()</b> commands must follow. To stop drawing the shape, call
* <b>endShape()</b>. The <b>vertex()</b> function with two parameters
* specifies a position in 2D and the <b>vertex()</b> function with three
* parameters specifies a position in 3D. Each shape will be outlined with
* the current stroke color and filled with the fill color.
* <br/> <br/>
* Transformations such as <b>translate()</b>, <b>rotate()</b>, and
* <b>scale()</b> do not work within <b>beginShape()</b>. It is also not
* possible to use other shapes, such as <b>ellipse()</b> or <b>rect()</b>
* within <b>beginShape()</b>.
* <br/> <br/>
* The P3D renderer settings allow <b>stroke()</b> and <b>fill()</b>
* settings to be altered per-vertex, however the default P2D renderer does
* not. Settings such as <b>strokeWeight()</b>, <b>strokeCap()</b>, and
* <b>strokeJoin()</b> cannot be changed while inside a
* <b>beginShape()</b>/<b>endShape()</b> block with any renderer.
*
* ( end auto-generated )
* @webref shape:vertex
* @param kind Either POINTS, LINES, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, QUADS, or QUAD_STRIP
* @see PGraphics#endShape()
* @see PGraphics#vertex(float, float, float, float, float)
* @see PGraphics#curveVertex(float, float, float)
* @see PGraphics#bezierVertex(float, float, float, float, float, float, float, float, float)
*/
public void beginShape(int kind) {
shape = kind;
}
/**
* Sets whether the upcoming vertex is part of an edge.
* Equivalent to glEdgeFlag(), for people familiar with OpenGL.
*/
public void edge(boolean edge) {
this.edge = edge;
}
/**
* ( begin auto-generated from normal.xml )
*
* Sets the current normal vector. This is for drawing three dimensional
* shapes and surfaces and specifies a vector perpendicular to the surface
* of the shape which determines how lighting affects it. Processing
* attempts to automatically assign normals to shapes, but since that's
* imperfect, this is a better option when you want more control. This
* function is identical to glNormal3f() in OpenGL.
*
* ( end auto-generated )
* @webref lights_camera:lights
* @param nx x direction
* @param ny y direction
* @param nz z direction
* @see PGraphics#beginShape(int)
* @see PGraphics#endShape(int)
* @see PGraphics#lights()
*/
public void normal(float nx, float ny, float nz) {
normalX = nx;
normalY = ny;
normalZ = nz;
// if drawing a shape and the normal hasn't been set yet,
// then we need to set the normals for each vertex so far
if (shape != 0) {
if (normalMode == NORMAL_MODE_AUTO) {
// One normal per begin/end shape
normalMode = NORMAL_MODE_SHAPE;
} else if (normalMode == NORMAL_MODE_SHAPE) {
// a separate normal for each vertex
normalMode = NORMAL_MODE_VERTEX;
}
}
}
/**
* ( begin auto-generated from textureMode.xml )
*
* Sets the coordinate space for texture mapping. There are two options,
* IMAGE, which refers to the actual coordinates of the image, and
* NORMAL, which refers to a normalized space of values ranging from 0
* to 1. The default mode is IMAGE. In IMAGE, if an image is 100 x 200
* pixels, mapping the image onto the entire size of a quad would require
* the points (0,0) (0,100) (100,200) (0,200). The same mapping in
* NORMAL_SPACE is (0,0) (0,1) (1,1) (0,1).
*
* ( end auto-generated )
* @webref image:textures
* @param mode either IMAGE or NORMAL
* @see PGraphics#texture(PImage)
*/
public void textureMode(int mode) {
this.textureMode = mode;
}
/**
* ( begin auto-generated from textureWrap.xml )
*
* Description to come...
*
* ( end auto-generated from textureWrap.xml )
*
* @webref image:textures
* @param wrap Either CLAMP (default) or REPEAT
*/
public void textureWrap(int wrap) {
showMissingWarning("textureWrap");
}
/**
* ( begin auto-generated from texture.xml )
*
* Sets a texture to be applied to vertex points. The <b>texture()</b>
* function must be called between <b>beginShape()</b> and
* <b>endShape()</b> and before any calls to <b>vertex()</b>.
* <br/> <br/>
* When textures are in use, the fill color is ignored. Instead, use tint()
* to specify the color of the texture as it is applied to the shape.
*
* ( end auto-generated )
* @webref image:textures
* @param image reference to a PImage object
* @see PGraphics#textureMode(int)
* @see PGraphics#beginShape(int)
* @see PGraphics#endShape(int)
* @see PGraphics#vertex(float, float, float, float, float)
*/
public void texture(PImage image) {
textureImage = image;
}
/**
* Removes texture image for current shape.
* Needs to be called between beginShape and endShape
*
*/
public void noTexture() {
textureImage = null;
}
protected void vertexCheck() {
if (vertexCount == vertices.length) {
float temp[][] = new float[vertexCount << 1][VERTEX_FIELD_COUNT];
System.arraycopy(vertices, 0, temp, 0, vertexCount);
vertices = temp;
}
}
public void vertex(float x, float y) {
vertexCheck();
float[] vertex = vertices[vertexCount];
curveVertexCount = 0;
vertex[X] = x;
vertex[Y] = y;
vertex[Z] = 0;
vertex[EDGE] = edge ? 1 : 0;
// if (fill) {
// vertex[R] = fillR;
// vertex[G] = fillG;
// vertex[B] = fillB;
// vertex[A] = fillA;
// }
boolean textured = textureImage != null;
if (fill || textured) {
if (!textured) {
vertex[R] = fillR;
vertex[G] = fillG;
vertex[B] = fillB;
vertex[A] = fillA;
} else {
if (tint) {
vertex[R] = tintR;
vertex[G] = tintG;
vertex[B] = tintB;
vertex[A] = tintA;
} else {
vertex[R] = 1;
vertex[G] = 1;
vertex[B] = 1;
vertex[A] = 1;
}
}
}
if (stroke) {
vertex[SR] = strokeR;
vertex[SG] = strokeG;
vertex[SB] = strokeB;
vertex[SA] = strokeA;
vertex[SW] = strokeWeight;
}
if (textured) {
vertex[U] = textureU;
vertex[V] = textureV;
}
if (autoNormal) {
float norm2 = normalX * normalX + normalY * normalY + normalZ * normalZ;
if (norm2 < EPSILON) {
vertex[HAS_NORMAL] = 0;
} else {
if (Math.abs(norm2 - 1) > EPSILON) {
// The normal vector is not normalized.
float norm = PApplet.sqrt(norm2);
normalX /= norm;
normalY /= norm;
normalZ /= norm;
}
vertex[HAS_NORMAL] = 1;
}
} else {
vertex[HAS_NORMAL] = 1;
}
vertexCount++;
}
public void vertex(float x, float y, float z) {
vertexCheck();
float[] vertex = vertices[vertexCount];
// only do this if we're using an irregular (POLYGON) shape that
// will go through the triangulator. otherwise it'll do thinks like
// disappear in mathematically odd ways
// http://dev.processing.org/bugs/show_bug.cgi?id=444
if (shape == POLYGON) {
if (vertexCount > 0) {
float pvertex[] = vertices[vertexCount-1];
if ((Math.abs(pvertex[X] - x) < EPSILON) &&
(Math.abs(pvertex[Y] - y) < EPSILON) &&
(Math.abs(pvertex[Z] - z) < EPSILON)) {
// this vertex is identical, don't add it,
// because it will anger the triangulator
return;
}
}
}
// User called vertex(), so that invalidates anything queued up for curve
// vertices. If this is internally called by curveVertexSegment,
// then curveVertexCount will be saved and restored.
curveVertexCount = 0;
vertex[X] = x;
vertex[Y] = y;
vertex[Z] = z;
vertex[EDGE] = edge ? 1 : 0;
boolean textured = textureImage != null;
if (fill || textured) {
if (!textured) {
vertex[R] = fillR;
vertex[G] = fillG;
vertex[B] = fillB;
vertex[A] = fillA;
} else {
if (tint) {
vertex[R] = tintR;
vertex[G] = tintG;
vertex[B] = tintB;
vertex[A] = tintA;
} else {
vertex[R] = 1;
vertex[G] = 1;
vertex[B] = 1;
vertex[A] = 1;
}
}
vertex[AR] = ambientR;
vertex[AG] = ambientG;
vertex[AB] = ambientB;
vertex[SPR] = specularR;
vertex[SPG] = specularG;
vertex[SPB] = specularB;
//vertex[SPA] = specularA;
vertex[SHINE] = shininess;
vertex[ER] = emissiveR;
vertex[EG] = emissiveG;
vertex[EB] = emissiveB;
}
if (stroke) {
vertex[SR] = strokeR;
vertex[SG] = strokeG;
vertex[SB] = strokeB;
vertex[SA] = strokeA;
vertex[SW] = strokeWeight;
}
if (textured) {
vertex[U] = textureU;
vertex[V] = textureV;
}
if (autoNormal) {
float norm2 = normalX * normalX + normalY * normalY + normalZ * normalZ;
if (norm2 < EPSILON) {
vertex[HAS_NORMAL] = 0;
} else {
if (Math.abs(norm2 - 1) > EPSILON) {
// The normal vector is not normalized.
float norm = PApplet.sqrt(norm2);
normalX /= norm;
normalY /= norm;
normalZ /= norm;
}
vertex[HAS_NORMAL] = 1;
}
} else {
vertex[HAS_NORMAL] = 1;
}
vertex[NX] = normalX;
vertex[NY] = normalY;
vertex[NZ] = normalZ;
vertex[BEEN_LIT] = 0;
vertexCount++;
}
/**
* Used by renderer subclasses or PShape to efficiently pass in already
* formatted vertex information.
* @param v vertex parameters, as a float array of length VERTEX_FIELD_COUNT
*/
public void vertex(float[] v) {
vertexCheck();
curveVertexCount = 0;
float[] vertex = vertices[vertexCount];
System.arraycopy(v, 0, vertex, 0, VERTEX_FIELD_COUNT);
vertexCount++;
}
public void vertex(float x, float y, float u, float v) {
vertexTexture(u, v);
vertex(x, y);
}
/**
* ( begin auto-generated from vertex.xml )
*
* All shapes are constructed by connecting a series of vertices.
* <b>vertex()</b> is used to specify the vertex coordinates for points,
* lines, triangles, quads, and polygons and is used exclusively within the
* <b>beginShape()</b> and <b>endShape()</b> function.<br />
* <br />
* Drawing a vertex in 3D using the <b>z</b> parameter requires the P3D
* parameter in combination with size as shown in the above example.<br />
* <br />
* This function is also used to map a texture onto the geometry. The
* <b>texture()</b> function declares the texture to apply to the geometry
* and the <b>u</b> and <b>v</b> coordinates set define the mapping of this
* texture to the form. By default, the coordinates used for <b>u</b> and
* <b>v</b> are specified in relation to the image's size in pixels, but
* this relation can be changed with <b>textureMode()</b>.
*
* ( end auto-generated )
* @webref shape:vertex
* @param x x-coordinate of the vertex
* @param y y-coordinate of the vertex
* @param z z-coordinate of the vertex
* @param u horizontal coordinate for the texture mapping
* @param v vertical coordinate for the texture mapping
* @see PGraphics#beginShape(int)
* @see PGraphics#endShape(int)
* @see PGraphics#bezierVertex(float, float, float, float, float, float, float, float, float)
* @see PGraphics#quadraticVertex(float, float, float, float, float, float)
* @see PGraphics#curveVertex(float, float, float)
* @see PGraphics#texture(PImage)
*/
public void vertex(float x, float y, float z, float u, float v) {
vertexTexture(u, v);
vertex(x, y, z);
}
/**
* Internal method to copy all style information for the given vertex.
* Can be overridden by subclasses to handle only properties pertinent to
* that renderer. (e.g. no need to copy the emissive color in P2D)
*/
// protected void vertexStyle() {
// }
/**
* Set (U, V) coords for the next vertex in the current shape.
* This is ugly as its own function, and will (almost?) always be
* coincident with a call to vertex. As of beta, this was moved to
* the protected method you see here, and called from an optional
* param of and overloaded vertex().
* <p/>
* The parameters depend on the current textureMode. When using
* textureMode(IMAGE), the coordinates will be relative to the size
* of the image texture, when used with textureMode(NORMAL),
* they'll be in the range 0..1.
* <p/>
* Used by both PGraphics2D (for images) and PGraphics3D.
*/
protected void vertexTexture(float u, float v) {
if (textureImage == null) {
throw new RuntimeException("You must first call texture() before " +
"using u and v coordinates with vertex()");
}
if (textureMode == IMAGE) {
u /= textureImage.width;
v /= textureImage.height;
}
textureU = u;
textureV = v;
if (textureU < 0) textureU = 0;
else if (textureU > 1) textureU = 1;
if (textureV < 0) textureV = 0;
else if (textureV > 1) textureV = 1;
}
// /** This feature is in testing, do not use or rely upon its implementation */
// public void breakShape() {
// showWarning("This renderer cannot currently handle concave shapes, " +
// "or shapes with holes.");
// }
public void beginContour() {
showMissingWarning("beginContour");
}
public void endContour() {
showMissingWarning("endContour");
}
public void endShape() {
endShape(OPEN);
}
/**
* ( begin auto-generated from endShape.xml )
*
* The <b>endShape()</b> function is the companion to <b>beginShape()</b>
* and may only be called after <b>beginShape()</b>. When <b>endshape()</b>
* is called, all of image data defined since the previous call to
* <b>beginShape()</b> is written into the image buffer. The constant CLOSE
* as the value for the MODE parameter to close the shape (to connect the
* beginning and the end).
*
* ( end auto-generated )
* @webref shape:vertex
* @param mode use CLOSE to close the shape
* @see PGraphics#beginShape(int)
*/
public void endShape(int mode) {
}
//////////////////////////////////////////////////////////////
// SHAPE I/O
/**
* @webref shape
* @param filename name of file to load, can be .svg or .obj
*/
public PShape loadShape(String filename) {
showMissingWarning("loadShape");
return null;
}
//////////////////////////////////////////////////////////////
// SHAPE CREATION
/**
* @webref shape
*/
public PShape createShape() {
showMissingWarning("createShape");
return null;
}
public PShape createShape(PShape source) {
showMissingWarning("createShape");
return null;
}
/**
* @param type either POINTS, LINES, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, QUADS, QUAD_STRIP
*/
public PShape createShape(int type) {
showMissingWarning("createShape");
return null;
}
/**
* @param kind either LINE, TRIANGLE, RECT, ELLIPSE, ARC, SPHERE, BOX
* @param p parameters that match the kind of shape
*/
public PShape createShape(int kind, float... p) {
showMissingWarning("createShape");
return null;
}
//////////////////////////////////////////////////////////////
// SHADERS
/**
* ( begin auto-generated from loadShader.xml )
*
* This is a new reference entry for Processing 2.0. It will be updated shortly.
*
* ( end auto-generated )
*
* @webref rendering:shaders
* @param fragFilename name of fragment shader file
*/
public PShader loadShader(String fragFilename) {
showMissingWarning("loadShader");
return null;
}
/**
* @param vertFilename name of vertex shader file
*/
public PShader loadShader(String fragFilename, String vertFilename) {
showMissingWarning("loadShader");
return null;
}
/**
* ( begin auto-generated from shader.xml )
*
* This is a new reference entry for Processing 2.0. It will be updated shortly.
*
* ( end auto-generated )
*
* @webref rendering:shaders
* @param shader name of shader file
*/
public void shader(PShader shader) {
showMissingWarning("shader");
}
/**
* @param kind type of shader, either POINTS, LINES, or TRIANGLES
*/
public void shader(PShader shader, int kind) {
showMissingWarning("shader");
}
/**
* ( begin auto-generated from resetShader.xml )
*
* This is a new reference entry for Processing 2.0. It will be updated shortly.
*
* ( end auto-generated )
*
* @webref rendering:shaders
*/
public void resetShader() {
showMissingWarning("resetShader");
}
/**
* @param kind type of shader, either POINTS, LINES, or TRIANGLES
*/
public void resetShader(int kind) {
showMissingWarning("resetShader");
}
/**
* @param shader the fragment shader to apply
*/
public void filter(PShader shader) {
showMissingWarning("filter");
}
//////////////////////////////////////////////////////////////
// CLIPPING
/*
* @webref rendering:shaders
* @param a x-coordinate of the rectangle by default
* @param b y-coordinate of the rectangle by default
* @param c width of the rectangle by default
* @param d height of the rectangle by default
*/
public void clip(float a, float b, float c, float d) {
if (imageMode == CORNER) {
if (c < 0) { // reset a negative width
a += c; c = -c;
}
if (d < 0) { // reset a negative height
b += d; d = -d;
}
clipImpl(a, b, a + c, b + d);
} else if (imageMode == CORNERS) {
if (c < a) { // reverse because x2 < x1
float temp = a; a = c; c = temp;
}
if (d < b) { // reverse because y2 < y1
float temp = b; b = d; d = temp;
}
clipImpl(a, b, c, d);
} else if (imageMode == CENTER) {
// c and d are width/height
if (c < 0) c = -c;
if (d < 0) d = -d;
float x1 = a - c/2;
float y1 = b - d/2;
clipImpl(x1, y1, x1 + c, y1 + d);
}
}
protected void clipImpl(float x1, float y1, float x2, float y2) {
showMissingWarning("clip");
}
/*
* @webref rendering:shaders
*/
public void noClip() {
showMissingWarning("noClip");
}
//////////////////////////////////////////////////////////////
// BLEND
/**
* ( begin auto-generated from blendMode.xml )
*
* This is a new reference entry for Processing 2.0. It will be updated shortly.
*
* ( end auto-generated )
*
* @webref Rendering
* @param mode the blending mode to use
*/
public void blendMode(int mode) {
showMissingWarning("blendMode");
}
//////////////////////////////////////////////////////////////
// CURVE/BEZIER VERTEX HANDLING
protected void bezierVertexCheck() {
bezierVertexCheck(shape, vertexCount);
}
protected void bezierVertexCheck(int shape, int vertexCount) {
if (shape == 0 || shape != POLYGON) {
throw new RuntimeException("beginShape() or beginShape(POLYGON) " +
"must be used before bezierVertex() or quadraticVertex()");
}
if (vertexCount == 0) {
throw new RuntimeException("vertex() must be used at least once" +
"before bezierVertex() or quadraticVertex()");
}
}
public void bezierVertex(float x2, float y2,
float x3, float y3,
float x4, float y4) {
bezierInitCheck();
bezierVertexCheck();
PMatrix3D draw = bezierDrawMatrix;
float[] prev = vertices[vertexCount-1];
float x1 = prev[X];
float y1 = prev[Y];
float xplot1 = draw.m10*x1 + draw.m11*x2 + draw.m12*x3 + draw.m13*x4;
float xplot2 = draw.m20*x1 + draw.m21*x2 + draw.m22*x3 + draw.m23*x4;
float xplot3 = draw.m30*x1 + draw.m31*x2 + draw.m32*x3 + draw.m33*x4;
float yplot1 = draw.m10*y1 + draw.m11*y2 + draw.m12*y3 + draw.m13*y4;
float yplot2 = draw.m20*y1 + draw.m21*y2 + draw.m22*y3 + draw.m23*y4;
float yplot3 = draw.m30*y1 + draw.m31*y2 + draw.m32*y3 + draw.m33*y4;
for (int j = 0; j < bezierDetail; j++) {
x1 += xplot1; xplot1 += xplot2; xplot2 += xplot3;
y1 += yplot1; yplot1 += yplot2; yplot2 += yplot3;
vertex(x1, y1);
}
}
/**
* ( begin auto-generated from bezierVertex.xml )
*
* Specifies vertex coordinates for Bezier curves. Each call to
* <b>bezierVertex()</b> defines the position of two control points and one
* anchor point of a Bezier curve, adding a new segment to a line or shape.
* The first time <b>bezierVertex()</b> is used within a
* <b>beginShape()</b> call, it must be prefaced with a call to
* <b>vertex()</b> to set the first anchor point. This function must be
* used between <b>beginShape()</b> and <b>endShape()</b> and only when
* there is no MODE parameter specified to <b>beginShape()</b>. Using the
* 3D version requires rendering with P3D (see the Environment reference
* for more information).
*
* ( end auto-generated )
* @webref shape:vertex
* @param x2 the x-coordinate of the 1st control point
* @param y2 the y-coordinate of the 1st control point
* @param z2 the z-coordinate of the 1st control point
* @param x3 the x-coordinate of the 2nd control point
* @param y3 the y-coordinate of the 2nd control point
* @param z3 the z-coordinate of the 2nd control point
* @param x4 the x-coordinate of the anchor point
* @param y4 the y-coordinate of the anchor point
* @param z4 the z-coordinate of the anchor point
* @see PGraphics#curveVertex(float, float, float)
* @see PGraphics#vertex(float, float, float, float, float)
* @see PGraphics#quadraticVertex(float, float, float, float, float, float)
* @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float)
*/
public void bezierVertex(float x2, float y2, float z2,
float x3, float y3, float z3,
float x4, float y4, float z4) {
bezierInitCheck();
bezierVertexCheck();
PMatrix3D draw = bezierDrawMatrix;
float[] prev = vertices[vertexCount-1];
float x1 = prev[X];
float y1 = prev[Y];
float z1 = prev[Z];
float xplot1 = draw.m10*x1 + draw.m11*x2 + draw.m12*x3 + draw.m13*x4;
float xplot2 = draw.m20*x1 + draw.m21*x2 + draw.m22*x3 + draw.m23*x4;
float xplot3 = draw.m30*x1 + draw.m31*x2 + draw.m32*x3 + draw.m33*x4;
float yplot1 = draw.m10*y1 + draw.m11*y2 + draw.m12*y3 + draw.m13*y4;
float yplot2 = draw.m20*y1 + draw.m21*y2 + draw.m22*y3 + draw.m23*y4;
float yplot3 = draw.m30*y1 + draw.m31*y2 + draw.m32*y3 + draw.m33*y4;
float zplot1 = draw.m10*z1 + draw.m11*z2 + draw.m12*z3 + draw.m13*z4;
float zplot2 = draw.m20*z1 + draw.m21*z2 + draw.m22*z3 + draw.m23*z4;
float zplot3 = draw.m30*z1 + draw.m31*z2 + draw.m32*z3 + draw.m33*z4;
for (int j = 0; j < bezierDetail; j++) {
x1 += xplot1; xplot1 += xplot2; xplot2 += xplot3;
y1 += yplot1; yplot1 += yplot2; yplot2 += yplot3;
z1 += zplot1; zplot1 += zplot2; zplot2 += zplot3;
vertex(x1, y1, z1);
}
}
/**
* @webref shape:vertex
* @param cx the x-coordinate of the control point
* @param cy the y-coordinate of the control point
* @param x3 the x-coordinate of the anchor point
* @param y3 the y-coordinate of the anchor point
* @see PGraphics#curveVertex(float, float, float)
* @see PGraphics#vertex(float, float, float, float, float)
* @see PGraphics#bezierVertex(float, float, float, float, float, float)
* @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float)
*/
public void quadraticVertex(float cx, float cy,
float x3, float y3) {
float[] prev = vertices[vertexCount-1];
float x1 = prev[X];
float y1 = prev[Y];
bezierVertex(x1 + ((cx-x1)*2/3.0f), y1 + ((cy-y1)*2/3.0f),
x3 + ((cx-x3)*2/3.0f), y3 + ((cy-y3)*2/3.0f),
x3, y3);
}
/**
* @param cz the z-coordinate of the control point
* @param z3 the z-coordinate of the anchor point
*/
public void quadraticVertex(float cx, float cy, float cz,
float x3, float y3, float z3) {
float[] prev = vertices[vertexCount-1];
float x1 = prev[X];
float y1 = prev[Y];
float z1 = prev[Z];
bezierVertex(x1 + ((cx-x1)*2/3.0f), y1 + ((cy-y1)*2/3.0f), z1 + ((cz-z1)*2/3.0f),
x3 + ((cx-x3)*2/3.0f), y3 + ((cy-y3)*2/3.0f), z3 + ((cz-z3)*2/3.0f),
x3, y3, z3);
}
protected void curveVertexCheck() {
curveVertexCheck(shape);
}
/**
* Perform initialization specific to curveVertex(), and handle standard
* error modes. Can be overridden by subclasses that need the flexibility.
*/
protected void curveVertexCheck(int shape) {
if (shape != POLYGON) {
throw new RuntimeException("You must use beginShape() or " +
"beginShape(POLYGON) before curveVertex()");
}
// to improve code init time, allocate on first use.
if (curveVertices == null) {
curveVertices = new float[128][3];
}
if (curveVertexCount == curveVertices.length) {
// Can't use PApplet.expand() cuz it doesn't do the copy properly
float[][] temp = new float[curveVertexCount << 1][3];
System.arraycopy(curveVertices, 0, temp, 0, curveVertexCount);
curveVertices = temp;
}
curveInitCheck();
}
/**
* ( begin auto-generated from curveVertex.xml )
*
* Specifies vertex coordinates for curves. This function may only be used
* between <b>beginShape()</b> and <b>endShape()</b> and only when there is
* no MODE parameter specified to <b>beginShape()</b>. The first and last
* points in a series of <b>curveVertex()</b> lines will be used to guide
* the beginning and end of a the curve. A minimum of four points is
* required to draw a tiny curve between the second and third points.
* Adding a fifth point with <b>curveVertex()</b> will draw the curve
* between the second, third, and fourth points. The <b>curveVertex()</b>
* function is an implementation of Catmull-Rom splines. Using the 3D
* version requires rendering with P3D (see the Environment reference for
* more information).
*
* ( end auto-generated )
*
* @webref shape:vertex
* @param x the x-coordinate of the vertex
* @param y the y-coordinate of the vertex
* @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#beginShape(int)
* @see PGraphics#endShape(int)
* @see PGraphics#vertex(float, float, float, float, float)
* @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#quadraticVertex(float, float, float, float, float, float)
*/
public void curveVertex(float x, float y) {
curveVertexCheck();
float[] vertex = curveVertices[curveVertexCount];
vertex[X] = x;
vertex[Y] = y;
curveVertexCount++;
// draw a segment if there are enough points
if (curveVertexCount > 3) {
curveVertexSegment(curveVertices[curveVertexCount-4][X],
curveVertices[curveVertexCount-4][Y],
curveVertices[curveVertexCount-3][X],
curveVertices[curveVertexCount-3][Y],
curveVertices[curveVertexCount-2][X],
curveVertices[curveVertexCount-2][Y],
curveVertices[curveVertexCount-1][X],
curveVertices[curveVertexCount-1][Y]);
}
}
/**
* @param z the z-coordinate of the vertex
*/
public void curveVertex(float x, float y, float z) {
curveVertexCheck();
float[] vertex = curveVertices[curveVertexCount];
vertex[X] = x;
vertex[Y] = y;
vertex[Z] = z;
curveVertexCount++;
// draw a segment if there are enough points
if (curveVertexCount > 3) {
curveVertexSegment(curveVertices[curveVertexCount-4][X],
curveVertices[curveVertexCount-4][Y],
curveVertices[curveVertexCount-4][Z],
curveVertices[curveVertexCount-3][X],
curveVertices[curveVertexCount-3][Y],
curveVertices[curveVertexCount-3][Z],
curveVertices[curveVertexCount-2][X],
curveVertices[curveVertexCount-2][Y],
curveVertices[curveVertexCount-2][Z],
curveVertices[curveVertexCount-1][X],
curveVertices[curveVertexCount-1][Y],
curveVertices[curveVertexCount-1][Z]);
}
}
/**
* Handle emitting a specific segment of Catmull-Rom curve. This can be
* overridden by subclasses that need more efficient rendering options.
*/
protected void curveVertexSegment(float x1, float y1,
float x2, float y2,
float x3, float y3,
float x4, float y4) {
float x0 = x2;
float y0 = y2;
PMatrix3D draw = curveDrawMatrix;
float xplot1 = draw.m10*x1 + draw.m11*x2 + draw.m12*x3 + draw.m13*x4;
float xplot2 = draw.m20*x1 + draw.m21*x2 + draw.m22*x3 + draw.m23*x4;
float xplot3 = draw.m30*x1 + draw.m31*x2 + draw.m32*x3 + draw.m33*x4;
float yplot1 = draw.m10*y1 + draw.m11*y2 + draw.m12*y3 + draw.m13*y4;
float yplot2 = draw.m20*y1 + draw.m21*y2 + draw.m22*y3 + draw.m23*y4;
float yplot3 = draw.m30*y1 + draw.m31*y2 + draw.m32*y3 + draw.m33*y4;
// vertex() will reset splineVertexCount, so save it
int savedCount = curveVertexCount;
vertex(x0, y0);
for (int j = 0; j < curveDetail; j++) {
x0 += xplot1; xplot1 += xplot2; xplot2 += xplot3;
y0 += yplot1; yplot1 += yplot2; yplot2 += yplot3;
vertex(x0, y0);
}
curveVertexCount = savedCount;
}
/**
* Handle emitting a specific segment of Catmull-Rom curve. This can be
* overridden by subclasses that need more efficient rendering options.
*/
protected void curveVertexSegment(float x1, float y1, float z1,
float x2, float y2, float z2,
float x3, float y3, float z3,
float x4, float y4, float z4) {
float x0 = x2;
float y0 = y2;
float z0 = z2;
PMatrix3D draw = curveDrawMatrix;
float xplot1 = draw.m10*x1 + draw.m11*x2 + draw.m12*x3 + draw.m13*x4;
float xplot2 = draw.m20*x1 + draw.m21*x2 + draw.m22*x3 + draw.m23*x4;
float xplot3 = draw.m30*x1 + draw.m31*x2 + draw.m32*x3 + draw.m33*x4;
float yplot1 = draw.m10*y1 + draw.m11*y2 + draw.m12*y3 + draw.m13*y4;
float yplot2 = draw.m20*y1 + draw.m21*y2 + draw.m22*y3 + draw.m23*y4;
float yplot3 = draw.m30*y1 + draw.m31*y2 + draw.m32*y3 + draw.m33*y4;
// vertex() will reset splineVertexCount, so save it
int savedCount = curveVertexCount;
float zplot1 = draw.m10*z1 + draw.m11*z2 + draw.m12*z3 + draw.m13*z4;
float zplot2 = draw.m20*z1 + draw.m21*z2 + draw.m22*z3 + draw.m23*z4;
float zplot3 = draw.m30*z1 + draw.m31*z2 + draw.m32*z3 + draw.m33*z4;
vertex(x0, y0, z0);
for (int j = 0; j < curveDetail; j++) {
x0 += xplot1; xplot1 += xplot2; xplot2 += xplot3;
y0 += yplot1; yplot1 += yplot2; yplot2 += yplot3;
z0 += zplot1; zplot1 += zplot2; zplot2 += zplot3;
vertex(x0, y0, z0);
}
curveVertexCount = savedCount;
}
//////////////////////////////////////////////////////////////
// SIMPLE SHAPES WITH ANALOGUES IN beginShape()
/**
* ( begin auto-generated from point.xml )
*
* Draws a point, a coordinate in space at the dimension of one pixel. The
* first parameter is the horizontal value for the point, the second value
* is the vertical value for the point, and the optional third value is the
* depth value. Drawing this shape in 3D with the <b>z</b> parameter
* requires the P3D parameter in combination with <b>size()</b> as shown in
* the above example.
*
* ( end auto-generated )
*
* @webref shape:2d_primitives
* @param x x-coordinate of the point
* @param y y-coordinate of the point
*/
public void point(float x, float y) {
beginShape(POINTS);
vertex(x, y);
endShape();
}
/**
* @param z z-coordinate of the point
*/
public void point(float x, float y, float z) {
beginShape(POINTS);
vertex(x, y, z);
endShape();
}
/**
* ( begin auto-generated from line.xml )
*
* Draws a line (a direct path between two points) to the screen. The
* version of <b>line()</b> with four parameters draws the line in 2D. To
* color a line, use the <b>stroke()</b> function. A line cannot be filled,
* therefore the <b>fill()</b> function will not affect the color of a
* line. 2D lines are drawn with a width of one pixel by default, but this
* can be changed with the <b>strokeWeight()</b> function. The version with
* six parameters allows the line to be placed anywhere within XYZ space.
* Drawing this shape in 3D with the <b>z</b> parameter requires the P3D
* parameter in combination with <b>size()</b> as shown in the above example.
*
* ( end auto-generated )
* @webref shape:2d_primitives
* @param x1 x-coordinate of the first point
* @param y1 y-coordinate of the first point
* @param x2 x-coordinate of the second point
* @param y2 y-coordinate of the second point
* @see PGraphics#strokeWeight(float)
* @see PGraphics#strokeJoin(int)
* @see PGraphics#strokeCap(int)
* @see PGraphics#beginShape()
*/
public void line(float x1, float y1, float x2, float y2) {
beginShape(LINES);
vertex(x1, y1);
vertex(x2, y2);
endShape();
}
/**
* @param z1 z-coordinate of the first point
* @param z2 z-coordinate of the second point
*/
public void line(float x1, float y1, float z1,
float x2, float y2, float z2) {
beginShape(LINES);
vertex(x1, y1, z1);
vertex(x2, y2, z2);
endShape();
}
/**
* ( begin auto-generated from triangle.xml )
*
* A triangle is a plane created by connecting three points. The first two
* arguments specify the first point, the middle two arguments specify the
* second point, and the last two arguments specify the third point.
*
* ( end auto-generated )
* @webref shape:2d_primitives
* @param x1 x-coordinate of the first point
* @param y1 y-coordinate of the first point
* @param x2 x-coordinate of the second point
* @param y2 y-coordinate of the second point
* @param x3 x-coordinate of the third point
* @param y3 y-coordinate of the third point
* @see PApplet#beginShape()
*/
public void triangle(float x1, float y1, float x2, float y2,
float x3, float y3) {
beginShape(TRIANGLES);
vertex(x1, y1);
vertex(x2, y2);
vertex(x3, y3);
endShape();
}
/**
* ( begin auto-generated from quad.xml )
*
* A quad is a quadrilateral, a four sided polygon. It is similar to a
* rectangle, but the angles between its edges are not constrained to
* ninety degrees. The first pair of parameters (x1,y1) sets the first
* vertex and the subsequent pairs should proceed clockwise or
* counter-clockwise around the defined shape.
*
* ( end auto-generated )
* @webref shape:2d_primitives
* @param x1 x-coordinate of the first corner
* @param y1 y-coordinate of the first corner
* @param x2 x-coordinate of the second corner
* @param y2 y-coordinate of the second corner
* @param x3 x-coordinate of the third corner
* @param y3 y-coordinate of the third corner
* @param x4 x-coordinate of the fourth corner
* @param y4 y-coordinate of the fourth corner
*/
public void quad(float x1, float y1, float x2, float y2,
float x3, float y3, float x4, float y4) {
beginShape(QUADS);
vertex(x1, y1);
vertex(x2, y2);
vertex(x3, y3);
vertex(x4, y4);
endShape();
}
//////////////////////////////////////////////////////////////
// RECT
/**
* ( begin auto-generated from rectMode.xml )
*
* Modifies the location from which rectangles draw. The default mode is
* <b>rectMode(CORNER)</b>, which specifies the location to be the upper
* left corner of the shape and uses the third and fourth parameters of
* <b>rect()</b> to specify the width and height. The syntax
* <b>rectMode(CORNERS)</b> uses the first and second parameters of
* <b>rect()</b> to set the location of one corner and uses the third and
* fourth parameters to set the opposite corner. The syntax
* <b>rectMode(CENTER)</b> draws the image from its center point and uses
* the third and forth parameters of <b>rect()</b> to specify the image's
* width and height. The syntax <b>rectMode(RADIUS)</b> draws the image
* from its center point and uses the third and forth parameters of
* <b>rect()</b> to specify half of the image's width and height. The
* parameter must be written in ALL CAPS because Processing is a case
* sensitive language. Note: In version 125, the mode named CENTER_RADIUS
* was shortened to RADIUS.
*
* ( end auto-generated )
* @webref shape:attributes
* @param mode either CORNER, CORNERS, CENTER, or RADIUS
* @see PGraphics#rect(float, float, float, float)
*/
public void rectMode(int mode) {
rectMode = mode;
}
/**
* ( begin auto-generated from rect.xml )
*
* Draws a rectangle to the screen. A rectangle is a four-sided shape with
* every angle at ninety degrees. By default, the first two parameters set
* the location of the upper-left corner, the third sets the width, and the
* fourth sets the height. These parameters may be changed with the
* <b>rectMode()</b> function.
*
* ( end auto-generated )
*
* @webref shape:2d_primitives
* @param a x-coordinate of the rectangle by default
* @param b y-coordinate of the rectangle by default
* @param c width of the rectangle by default
* @param d height of the rectangle by default
* @see PGraphics#rectMode(int)
* @see PGraphics#quad(float, float, float, float, float, float, float, float)
*/
public void rect(float a, float b, float c, float d) {
float hradius, vradius;
switch (rectMode) {
case CORNERS:
break;
case CORNER:
c += a; d += b;
break;
case RADIUS:
hradius = c;
vradius = d;
c = a + hradius;
d = b + vradius;
a -= hradius;
b -= vradius;
break;
case CENTER:
hradius = c / 2.0f;
vradius = d / 2.0f;
c = a + hradius;
d = b + vradius;
a -= hradius;
b -= vradius;
}
if (a > c) {
float temp = a; a = c; c = temp;
}
if (b > d) {
float temp = b; b = d; d = temp;
}
rectImpl(a, b, c, d);
}
protected void rectImpl(float x1, float y1, float x2, float y2) {
quad(x1, y1, x2, y1, x2, y2, x1, y2);
}
// Still need to do a lot of work here to make it behave across renderers
// (e.g. not all renderers use the vertices array)
// Also seems to be some issues on quality here (too dense)
// http://code.google.com/p/processing/issues/detail?id=265
// private void quadraticVertex(float cpx, float cpy, float x, float y) {
// float[] prev = vertices[vertexCount - 1];
// float prevX = prev[X];
// float prevY = prev[Y];
// float cp1x = prevX + 2.0f/3.0f*(cpx - prevX);
// float cp1y = prevY + 2.0f/3.0f*(cpy - prevY);
// float cp2x = cp1x + (x - prevX)/3.0f;
// float cp2y = cp1y + (y - prevY)/3.0f;
// bezierVertex(cp1x, cp1y, cp2x, cp2y, x, y);
// }
/**
* @param r radii for all four corners
*/
public void rect(float a, float b, float c, float d, float r) {
rect(a, b, c, d, r, r, r, r);
}
/**
* @param tl radius for top-left corner
* @param tr radius for top-right corner
* @param br radius for bottom-right corner
* @param bl radius for bottom-left corner
*/
public void rect(float a, float b, float c, float d,
float tl, float tr, float br, float bl) {
float hradius, vradius;
switch (rectMode) {
case CORNERS:
break;
case CORNER:
c += a; d += b;
break;
case RADIUS:
hradius = c;
vradius = d;
c = a + hradius;
d = b + vradius;
a -= hradius;
b -= vradius;
break;
case CENTER:
hradius = c / 2.0f;
vradius = d / 2.0f;
c = a + hradius;
d = b + vradius;
a -= hradius;
b -= vradius;
}
if (a > c) {
float temp = a; a = c; c = temp;
}
if (b > d) {
float temp = b; b = d; d = temp;
}
float maxRounding = PApplet.min((c - a) / 2, (d - b) / 2);
if (tl > maxRounding) tl = maxRounding;
if (tr > maxRounding) tr = maxRounding;
if (br > maxRounding) br = maxRounding;
if (bl > maxRounding) bl = maxRounding;
rectImpl(a, b, c, d, tl, tr, br, bl);
}
protected void rectImpl(float x1, float y1, float x2, float y2,
float tl, float tr, float br, float bl) {
beginShape();
// vertex(x1+tl, y1);
if (tr != 0) {
vertex(x2-tr, y1);
quadraticVertex(x2, y1, x2, y1+tr);
} else {
vertex(x2, y1);
}
if (br != 0) {
vertex(x2, y2-br);
quadraticVertex(x2, y2, x2-br, y2);
} else {
vertex(x2, y2);
}
if (bl != 0) {
vertex(x1+bl, y2);
quadraticVertex(x1, y2, x1, y2-bl);
} else {
vertex(x1, y2);
}
if (tl != 0) {
vertex(x1, y1+tl);
quadraticVertex(x1, y1, x1+tl, y1);
} else {
vertex(x1, y1);
}
// endShape();
endShape(CLOSE);
}
//////////////////////////////////////////////////////////////
// ELLIPSE AND ARC
/**
* ( begin auto-generated from ellipseMode.xml )
*
* The origin of the ellipse is modified by the <b>ellipseMode()</b>
* function. The default configuration is <b>ellipseMode(CENTER)</b>, which
* specifies the location of the ellipse as the center of the shape. The
* <b>RADIUS</b> mode is the same, but the width and height parameters to
* <b>ellipse()</b> specify the radius of the ellipse, rather than the
* diameter. The <b>CORNER</b> mode draws the shape from the upper-left
* corner of its bounding box. The <b>CORNERS</b> mode uses the four
* parameters to <b>ellipse()</b> to set two opposing corners of the
* ellipse's bounding box. The parameter must be written in ALL CAPS
* because Processing is a case-sensitive language.
*
* ( end auto-generated )
* @webref shape:attributes
* @param mode either CENTER, RADIUS, CORNER, or CORNERS
* @see PApplet#ellipse(float, float, float, float)
* @see PApplet#arc(float, float, float, float, float, float)
*/
public void ellipseMode(int mode) {
ellipseMode = mode;
}
/**
* ( begin auto-generated from ellipse.xml )
*
* Draws an ellipse (oval) in the display window. An ellipse with an equal
* <b>width</b> and <b>height</b> is a circle. The first two parameters set
* the location, the third sets the width, and the fourth sets the height.
* The origin may be changed with the <b>ellipseMode()</b> function.
*
* ( end auto-generated )
* @webref shape:2d_primitives
* @param a x-coordinate of the ellipse
* @param b y-coordinate of the ellipse
* @param c width of the ellipse by default
* @param d height of the ellipse by default
* @see PApplet#ellipseMode(int)
* @see PApplet#arc(float, float, float, float, float, float)
*/
public void ellipse(float a, float b, float c, float d) {
float x = a;
float y = b;
float w = c;
float h = d;
if (ellipseMode == CORNERS) {
w = c - a;
h = d - b;
} else if (ellipseMode == RADIUS) {
x = a - c;
y = b - d;
w = c * 2;
h = d * 2;
} else if (ellipseMode == DIAMETER) {
x = a - c/2f;
y = b - d/2f;
}
if (w < 0) { // undo negative width
x += w;
w = -w;
}
if (h < 0) { // undo negative height
y += h;
h = -h;
}
ellipseImpl(x, y, w, h);
}
protected void ellipseImpl(float x, float y, float w, float h) {
}
/**
* ( begin auto-generated from arc.xml )
*
* Draws an arc in the display window. Arcs are drawn along the outer edge
* of an ellipse defined by the <b>x</b>, <b>y</b>, <b>width</b> and
* <b>height</b> parameters. The origin or the arc's ellipse may be changed
* with the <b>ellipseMode()</b> function. The <b>start</b> and <b>stop</b>
* parameters specify the angles at which to draw the arc.
*
* ( end auto-generated )
* @webref shape:2d_primitives
* @param a x-coordinate of the arc's ellipse
* @param b y-coordinate of the arc's ellipse
* @param c width of the arc's ellipse by default
* @param d height of the arc's ellipse by default
* @param start angle to start the arc, specified in radians
* @param stop angle to stop the arc, specified in radians
* @see PApplet#ellipse(float, float, float, float)
* @see PApplet#ellipseMode(int)
* @see PApplet#radians(float)
* @see PApplet#degrees(float)
*/
public void arc(float a, float b, float c, float d,
float start, float stop) {
arc(a, b, c, d, start, stop, 0);
}
/*
* @param mode either OPEN, CHORD, or PIE
*/
public void arc(float a, float b, float c, float d,
float start, float stop, int mode) {
float x = a;
float y = b;
float w = c;
float h = d;
if (ellipseMode == CORNERS) {
w = c - a;
h = d - b;
} else if (ellipseMode == RADIUS) {
x = a - c;
y = b - d;
w = c * 2;
h = d * 2;
} else if (ellipseMode == CENTER) {
x = a - c/2f;
y = b - d/2f;
}
// make sure the loop will exit before starting while
if (!Float.isInfinite(start) && !Float.isInfinite(stop)) {
// ignore equal and degenerate cases
if (stop > start) {
// make sure that we're starting at a useful point
while (start < 0) {
start += TWO_PI;
stop += TWO_PI;
}
if (stop - start > TWO_PI) {
start = 0;
stop = TWO_PI;
}
arcImpl(x, y, w, h, start, stop, mode);
}
}
}
// protected void arcImpl(float x, float y, float w, float h,
// float start, float stop) {
// }
/**
* Start and stop are in radians, converted by the parent function.
* Note that the radians can be greater (or less) than TWO_PI.
* This is so that an arc can be drawn that crosses zero mark,
* and the user will still collect $200.
*/
protected void arcImpl(float x, float y, float w, float h,
float start, float stop, int mode) {
showMissingWarning("arc");
}
//////////////////////////////////////////////////////////////
// BOX
/**
* ( begin auto-generated from box.xml )
*
* A box is an extruded rectangle. A box with equal dimension on all sides
* is a cube.
*
* ( end auto-generated )
*
* @webref shape:3d_primitives
* @param size dimension of the box in all dimensions (creates a cube)
* @see PGraphics#sphere(float)
*/
public void box(float size) {
box(size, size, size);
}
/**
* @param w dimension of the box in the x-dimension
* @param h dimension of the box in the y-dimension
* @param d dimension of the box in the z-dimension
*/
public void box(float w, float h, float d) {
float x1 = -w/2f; float x2 = w/2f;
float y1 = -h/2f; float y2 = h/2f;
float z1 = -d/2f; float z2 = d/2f;
// TODO not the least bit efficient, it even redraws lines
// along the vertices. ugly ugly ugly!
beginShape(QUADS);
// front
normal(0, 0, 1);
vertex(x1, y1, z1);
vertex(x2, y1, z1);
vertex(x2, y2, z1);
vertex(x1, y2, z1);
// right
normal(1, 0, 0);
vertex(x2, y1, z1);
vertex(x2, y1, z2);
vertex(x2, y2, z2);
vertex(x2, y2, z1);
// back
normal(0, 0, -1);
vertex(x2, y1, z2);
vertex(x1, y1, z2);
vertex(x1, y2, z2);
vertex(x2, y2, z2);
// left
normal(-1, 0, 0);
vertex(x1, y1, z2);
vertex(x1, y1, z1);
vertex(x1, y2, z1);
vertex(x1, y2, z2);
// top
normal(0, 1, 0);
vertex(x1, y1, z2);
vertex(x2, y1, z2);
vertex(x2, y1, z1);
vertex(x1, y1, z1);
// bottom
normal(0, -1, 0);
vertex(x1, y2, z1);
vertex(x2, y2, z1);
vertex(x2, y2, z2);
vertex(x1, y2, z2);
endShape();
}
//////////////////////////////////////////////////////////////
// SPHERE
/**
* ( begin auto-generated from sphereDetail.xml )
*
* Controls the detail used to render a sphere by adjusting the number of
* vertices of the sphere mesh. The default resolution is 30, which creates
* a fairly detailed sphere definition with vertices every 360/30 = 12
* degrees. If you're going to render a great number of spheres per frame,
* it is advised to reduce the level of detail using this function. The
* setting stays active until <b>sphereDetail()</b> is called again with a
* new parameter and so should <i>not</i> be called prior to every
* <b>sphere()</b> statement, unless you wish to render spheres with
* different settings, e.g. using less detail for smaller spheres or ones
* further away from the camera. To control the detail of the horizontal
* and vertical resolution independently, use the version of the functions
* with two parameters.
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* Code for sphereDetail() submitted by toxi [031031].
* Code for enhanced u/v version from davbol [080801].
*
* @param res number of segments (minimum 3) used per full circle revolution
* @webref shape:3d_primitives
* @see PGraphics#sphere(float)
*/
public void sphereDetail(int res) {
sphereDetail(res, res);
}
/**
* @param ures number of segments used longitudinally per full circle revolutoin
* @param vres number of segments used latitudinally from top to bottom
*/
public void sphereDetail(int ures, int vres) {
if (ures < 3) ures = 3; // force a minimum res
if (vres < 2) vres = 2; // force a minimum res
if ((ures == sphereDetailU) && (vres == sphereDetailV)) return;
float delta = (float)SINCOS_LENGTH/ures;
float[] cx = new float[ures];
float[] cz = new float[ures];
// calc unit circle in XZ plane
for (int i = 0; i < ures; i++) {
cx[i] = cosLUT[(int) (i*delta) % SINCOS_LENGTH];
cz[i] = sinLUT[(int) (i*delta) % SINCOS_LENGTH];
}
// computing vertexlist
// vertexlist starts at south pole
int vertCount = ures * (vres-1) + 2;
int currVert = 0;
// re-init arrays to store vertices
sphereX = new float[vertCount];
sphereY = new float[vertCount];
sphereZ = new float[vertCount];
float angle_step = (SINCOS_LENGTH*0.5f)/vres;
float angle = angle_step;
// step along Y axis
for (int i = 1; i < vres; i++) {
float curradius = sinLUT[(int) angle % SINCOS_LENGTH];
float currY = cosLUT[(int) angle % SINCOS_LENGTH];
for (int j = 0; j < ures; j++) {
sphereX[currVert] = cx[j] * curradius;
sphereY[currVert] = currY;
sphereZ[currVert++] = cz[j] * curradius;
}
angle += angle_step;
}
sphereDetailU = ures;
sphereDetailV = vres;
}
/**
* ( begin auto-generated from sphere.xml )
*
* A sphere is a hollow ball made from tessellated triangles.
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* <P>
* Implementation notes:
* <P>
* cache all the points of the sphere in a static array
* top and bottom are just a bunch of triangles that land
* in the center point
* <P>
* sphere is a series of concentric circles who radii vary
* along the shape, based on, er.. cos or something
* <PRE>
* [toxi 031031] new sphere code. removed all multiplies with
* radius, as scale() will take care of that anyway
*
* [toxi 031223] updated sphere code (removed modulos)
* and introduced sphereAt(x,y,z,r)
* to avoid additional translate()'s on the user/sketch side
*
* [davbol 080801] now using separate sphereDetailU/V
* </PRE>
*
* @webref shape:3d_primitives
* @param r the radius of the sphere
* @see PGraphics#sphereDetail(int)
*/
public void sphere(float r) {
if ((sphereDetailU < 3) || (sphereDetailV < 2)) {
sphereDetail(30);
}
edge(false);
// 1st ring from south pole
beginShape(TRIANGLE_STRIP);
for (int i = 0; i < sphereDetailU; i++) {
normal(0, -1, 0);
vertex(0, -r, 0);
normal(sphereX[i], sphereY[i], sphereZ[i]);
vertex(r * sphereX[i], r * sphereY[i], r * sphereZ[i]);
}
normal(0, -r, 0);
vertex(0, -r, 0);
normal(sphereX[0], sphereY[0], sphereZ[0]);
vertex(r * sphereX[0], r * sphereY[0], r * sphereZ[0]);
endShape();
int v1,v11,v2;
// middle rings
int voff = 0;
for (int i = 2; i < sphereDetailV; i++) {
v1 = v11 = voff;
voff += sphereDetailU;
v2 = voff;
beginShape(TRIANGLE_STRIP);
for (int j = 0; j < sphereDetailU; j++) {
normal(sphereX[v1], sphereY[v1], sphereZ[v1]);
vertex(r * sphereX[v1], r * sphereY[v1], r * sphereZ[v1++]);
normal(sphereX[v2], sphereY[v2], sphereZ[v2]);
vertex(r * sphereX[v2], r * sphereY[v2], r * sphereZ[v2++]);
}
// close each ring
v1 = v11;
v2 = voff;
normal(sphereX[v1], sphereY[v1], sphereZ[v1]);
vertex(r * sphereX[v1], r * sphereY[v1], r * sphereZ[v1]);
normal(sphereX[v2], sphereY[v2], sphereZ[v2]);
vertex(r * sphereX[v2], r * sphereY[v2], r * sphereZ[v2]);
endShape();
}
// add the northern cap
beginShape(TRIANGLE_STRIP);
for (int i = 0; i < sphereDetailU; i++) {
v2 = voff + i;
normal(sphereX[v2], sphereY[v2], sphereZ[v2]);
vertex(r * sphereX[v2], r * sphereY[v2], r * sphereZ[v2]);
normal(0, 1, 0);
vertex(0, r, 0);
}
normal(sphereX[voff], sphereY[voff], sphereZ[voff]);
vertex(r * sphereX[voff], r * sphereY[voff], r * sphereZ[voff]);
normal(0, 1, 0);
vertex(0, r, 0);
endShape();
edge(true);
}
//////////////////////////////////////////////////////////////
// BEZIER
/**
* ( begin auto-generated from bezierPoint.xml )
*
* Evaluates the Bezier at point t for points a, b, c, d. The parameter t
* varies between 0 and 1, a and d are points on the curve, and b and c are
* the control points. This can be done once with the x coordinates and a
* second time with the y coordinates to get the location of a bezier curve
* at t.
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* For instance, to convert the following example:<PRE>
* stroke(255, 102, 0);
* line(85, 20, 10, 10);
* line(90, 90, 15, 80);
* stroke(0, 0, 0);
* bezier(85, 20, 10, 10, 90, 90, 15, 80);
*
* // draw it in gray, using 10 steps instead of the default 20
* // this is a slower way to do it, but useful if you need
* // to do things with the coordinates at each step
* stroke(128);
* beginShape(LINE_STRIP);
* for (int i = 0; i <= 10; i++) {
* float t = i / 10.0f;
* float x = bezierPoint(85, 10, 90, 15, t);
* float y = bezierPoint(20, 10, 90, 80, t);
* vertex(x, y);
* }
* endShape();</PRE>
*
* @webref shape:curves
* @param a coordinate of first point on the curve
* @param b coordinate of first control point
* @param c coordinate of second control point
* @param d coordinate of second point on the curve
* @param t value between 0 and 1
* @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#bezierVertex(float, float, float, float, float, float)
* @see PGraphics#curvePoint(float, float, float, float, float)
*/
public float bezierPoint(float a, float b, float c, float d, float t) {
float t1 = 1.0f - t;
return a*t1*t1*t1 + 3*b*t*t1*t1 + 3*c*t*t*t1 + d*t*t*t;
}
/**
* ( begin auto-generated from bezierTangent.xml )
*
* Calculates the tangent of a point on a Bezier curve. There is a good
* definition of <a href="http://en.wikipedia.org/wiki/Tangent"
* target="new"><em>tangent</em> on Wikipedia</a>.
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* Code submitted by Dave Bollinger (davol) for release 0136.
*
* @webref shape:curves
* @param a coordinate of first point on the curve
* @param b coordinate of first control point
* @param c coordinate of second control point
* @param d coordinate of second point on the curve
* @param t value between 0 and 1
* @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#bezierVertex(float, float, float, float, float, float)
* @see PGraphics#curvePoint(float, float, float, float, float)
*/
public float bezierTangent(float a, float b, float c, float d, float t) {
return (3*t*t * (-a+3*b-3*c+d) +
6*t * (a-2*b+c) +
3 * (-a+b));
}
protected void bezierInitCheck() {
if (!bezierInited) {
bezierInit();
}
}
protected void bezierInit() {
// overkill to be broken out, but better parity with the curve stuff below
bezierDetail(bezierDetail);
bezierInited = true;
}
/**
* ( begin auto-generated from bezierDetail.xml )
*
* Sets the resolution at which Beziers display. The default value is 20.
* This function is only useful when using the P3D renderer as the default
* P2D renderer does not use this information.
*
* ( end auto-generated )
*
* @webref shape:curves
* @param detail resolution of the curves
* @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#curveVertex(float, float, float)
* @see PGraphics#curveTightness(float)
*/
public void bezierDetail(int detail) {
bezierDetail = detail;
if (bezierDrawMatrix == null) {
bezierDrawMatrix = new PMatrix3D();
}
// setup matrix for forward differencing to speed up drawing
splineForward(detail, bezierDrawMatrix);
// multiply the basis and forward diff matrices together
// saves much time since this needn't be done for each curve
//mult_spline_matrix(bezierForwardMatrix, bezier_basis, bezierDrawMatrix, 4);
//bezierDrawMatrix.set(bezierForwardMatrix);
bezierDrawMatrix.apply(bezierBasisMatrix);
}
public void bezier(float x1, float y1,
float x2, float y2,
float x3, float y3,
float x4, float y4) {
beginShape();
vertex(x1, y1);
bezierVertex(x2, y2, x3, y3, x4, y4);
endShape();
}
/**
* ( begin auto-generated from bezier.xml )
*
* Draws a Bezier curve on the screen. These curves are defined by a series
* of anchor and control points. The first two parameters specify the first
* anchor point and the last two parameters specify the other anchor point.
* The middle parameters specify the control points which define the shape
* of the curve. Bezier curves were developed by French engineer Pierre
* Bezier. Using the 3D version requires rendering with P3D (see the
* Environment reference for more information).
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* Draw a cubic bezier curve. The first and last points are
* the on-curve points. The middle two are the 'control' points,
* or 'handles' in an application like Illustrator.
* <P>
* Identical to typing:
* <PRE>beginShape();
* vertex(x1, y1);
* bezierVertex(x2, y2, x3, y3, x4, y4);
* endShape();
* </PRE>
* In Postscript-speak, this would be:
* <PRE>moveto(x1, y1);
* curveto(x2, y2, x3, y3, x4, y4);</PRE>
* If you were to try and continue that curve like so:
* <PRE>curveto(x5, y5, x6, y6, x7, y7);</PRE>
* This would be done in processing by adding these statements:
* <PRE>bezierVertex(x5, y5, x6, y6, x7, y7)
* </PRE>
* To draw a quadratic (instead of cubic) curve,
* use the control point twice by doubling it:
* <PRE>bezier(x1, y1, cx, cy, cx, cy, x2, y2);</PRE>
*
* @webref shape:curves
* @param x1 coordinates for the first anchor point
* @param y1 coordinates for the first anchor point
* @param z1 coordinates for the first anchor point
* @param x2 coordinates for the first control point
* @param y2 coordinates for the first control point
* @param z2 coordinates for the first control point
* @param x3 coordinates for the second control point
* @param y3 coordinates for the second control point
* @param z3 coordinates for the second control point
* @param x4 coordinates for the second anchor point
* @param y4 coordinates for the second anchor point
* @param z4 coordinates for the second anchor point
*
* @see PGraphics#bezierVertex(float, float, float, float, float, float)
* @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float)
*/
public void bezier(float x1, float y1, float z1,
float x2, float y2, float z2,
float x3, float y3, float z3,
float x4, float y4, float z4) {
beginShape();
vertex(x1, y1, z1);
bezierVertex(x2, y2, z2,
x3, y3, z3,
x4, y4, z4);
endShape();
}
//////////////////////////////////////////////////////////////
// CATMULL-ROM CURVE
/**
* ( begin auto-generated from curvePoint.xml )
*
* Evalutes the curve at point t for points a, b, c, d. The parameter t
* varies between 0 and 1, a and d are points on the curve, and b and c are
* the control points. This can be done once with the x coordinates and a
* second time with the y coordinates to get the location of a curve at t.
*
* ( end auto-generated )
*
* @webref shape:curves
* @param a coordinate of first point on the curve
* @param b coordinate of second point on the curve
* @param c coordinate of third point on the curve
* @param d coordinate of fourth point on the curve
* @param t value between 0 and 1
* @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#curveVertex(float, float)
* @see PGraphics#bezierPoint(float, float, float, float, float)
*/
public float curvePoint(float a, float b, float c, float d, float t) {
curveInitCheck();
float tt = t * t;
float ttt = t * tt;
PMatrix3D cb = curveBasisMatrix;
// not optimized (and probably need not be)
return (a * (ttt*cb.m00 + tt*cb.m10 + t*cb.m20 + cb.m30) +
b * (ttt*cb.m01 + tt*cb.m11 + t*cb.m21 + cb.m31) +
c * (ttt*cb.m02 + tt*cb.m12 + t*cb.m22 + cb.m32) +
d * (ttt*cb.m03 + tt*cb.m13 + t*cb.m23 + cb.m33));
}
/**
* ( begin auto-generated from curveTangent.xml )
*
* Calculates the tangent of a point on a curve. There's a good definition
* of <em><a href="http://en.wikipedia.org/wiki/Tangent"
* target="new">tangent</em> on Wikipedia</a>.
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* Code thanks to Dave Bollinger (Bug #715)
*
* @webref shape:curves
* @param a coordinate of first point on the curve
* @param b coordinate of first control point
* @param c coordinate of second control point
* @param d coordinate of second point on the curve
* @param t value between 0 and 1
* @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#curveVertex(float, float)
* @see PGraphics#curvePoint(float, float, float, float, float)
* @see PGraphics#bezierTangent(float, float, float, float, float)
*/
public float curveTangent(float a, float b, float c, float d, float t) {
curveInitCheck();
float tt3 = t * t * 3;
float t2 = t * 2;
PMatrix3D cb = curveBasisMatrix;
// not optimized (and probably need not be)
return (a * (tt3*cb.m00 + t2*cb.m10 + cb.m20) +
b * (tt3*cb.m01 + t2*cb.m11 + cb.m21) +
c * (tt3*cb.m02 + t2*cb.m12 + cb.m22) +
d * (tt3*cb.m03 + t2*cb.m13 + cb.m23) );
}
/**
* ( begin auto-generated from curveDetail.xml )
*
* Sets the resolution at which curves display. The default value is 20.
* This function is only useful when using the P3D renderer as the default
* P2D renderer does not use this information.
*
* ( end auto-generated )
*
* @webref shape:curves
* @param detail resolution of the curves
* @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#curveVertex(float, float)
* @see PGraphics#curveTightness(float)
*/
public void curveDetail(int detail) {
curveDetail = detail;
curveInit();
}
/**
* ( begin auto-generated from curveTightness.xml )
*
* Modifies the quality of forms created with <b>curve()</b> and
* <b>curveVertex()</b>. The parameter <b>squishy</b> determines how the
* curve fits to the vertex points. The value 0.0 is the default value for
* <b>squishy</b> (this value defines the curves to be Catmull-Rom splines)
* and the value 1.0 connects all the points with straight lines. Values
* within the range -5.0 and 5.0 will deform the curves but will leave them
* recognizable and as values increase in magnitude, they will continue to deform.
*
* ( end auto-generated )
*
* @webref shape:curves
* @param tightness amount of deformation from the original vertices
* @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#curveVertex(float, float)
*/
public void curveTightness(float tightness) {
curveTightness = tightness;
curveInit();
}
protected void curveInitCheck() {
if (!curveInited) {
curveInit();
}
}
/**
* Set the number of segments to use when drawing a Catmull-Rom
* curve, and setting the s parameter, which defines how tightly
* the curve fits to each vertex. Catmull-Rom curves are actually
* a subset of this curve type where the s is set to zero.
* <P>
* (This function is not optimized, since it's not expected to
* be called all that often. there are many juicy and obvious
* opimizations in here, but it's probably better to keep the
* code more readable)
*/
protected void curveInit() {
// allocate only if/when used to save startup time
if (curveDrawMatrix == null) {
curveBasisMatrix = new PMatrix3D();
curveDrawMatrix = new PMatrix3D();
curveInited = true;
}
float s = curveTightness;
curveBasisMatrix.set((s-1)/2f, (s+3)/2f, (-3-s)/2f, (1-s)/2f,
(1-s), (-5-s)/2f, (s+2), (s-1)/2f,
(s-1)/2f, 0, (1-s)/2f, 0,
0, 1, 0, 0);
//setup_spline_forward(segments, curveForwardMatrix);
splineForward(curveDetail, curveDrawMatrix);
if (bezierBasisInverse == null) {
bezierBasisInverse = bezierBasisMatrix.get();
bezierBasisInverse.invert();
curveToBezierMatrix = new PMatrix3D();
}
// TODO only needed for PGraphicsJava2D? if so, move it there
// actually, it's generally useful for other renderers, so keep it
// or hide the implementation elsewhere.
curveToBezierMatrix.set(curveBasisMatrix);
curveToBezierMatrix.preApply(bezierBasisInverse);
// multiply the basis and forward diff matrices together
// saves much time since this needn't be done for each curve
curveDrawMatrix.apply(curveBasisMatrix);
}
/**
* ( begin auto-generated from curve.xml )
*
* Draws a curved line on the screen. The first and second parameters
* specify the beginning control point and the last two parameters specify
* the ending control point. The middle parameters specify the start and
* stop of the curve. Longer curves can be created by putting a series of
* <b>curve()</b> functions together or using <b>curveVertex()</b>. An
* additional function called <b>curveTightness()</b> provides control for
* the visual quality of the curve. The <b>curve()</b> function is an
* implementation of Catmull-Rom splines. Using the 3D version requires
* rendering with P3D (see the Environment reference for more information).
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* As of revision 0070, this function no longer doubles the first
* and last points. The curves are a bit more boring, but it's more
* mathematically correct, and properly mirrored in curvePoint().
* <P>
* Identical to typing out:<PRE>
* beginShape();
* curveVertex(x1, y1);
* curveVertex(x2, y2);
* curveVertex(x3, y3);
* curveVertex(x4, y4);
* endShape();
* </PRE>
*
* @webref shape:curves
* @param x1 coordinates for the beginning control point
* @param y1 coordinates for the beginning control point
* @param x2 coordinates for the first point
* @param y2 coordinates for the first point
* @param x3 coordinates for the second point
* @param y3 coordinates for the second point
* @param x4 coordinates for the ending control point
* @param y4 coordinates for the ending control point
* @see PGraphics#curveVertex(float, float)
* @see PGraphics#curveTightness(float)
* @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float)
*/
public void curve(float x1, float y1,
float x2, float y2,
float x3, float y3,
float x4, float y4) {
beginShape();
curveVertex(x1, y1);
curveVertex(x2, y2);
curveVertex(x3, y3);
curveVertex(x4, y4);
endShape();
}
/**
* @param z1 coordinates for the beginning control point
* @param z2 coordinates for the first point
* @param z3 coordinates for the second point
* @param z4 coordinates for the ending control point
*/
public void curve(float x1, float y1, float z1,
float x2, float y2, float z2,
float x3, float y3, float z3,
float x4, float y4, float z4) {
beginShape();
curveVertex(x1, y1, z1);
curveVertex(x2, y2, z2);
curveVertex(x3, y3, z3);
curveVertex(x4, y4, z4);
endShape();
}
//////////////////////////////////////////////////////////////
// SPLINE UTILITY FUNCTIONS (used by both Bezier and Catmull-Rom)
/**
* Setup forward-differencing matrix to be used for speedy
* curve rendering. It's based on using a specific number
* of curve segments and just doing incremental adds for each
* vertex of the segment, rather than running the mathematically
* expensive cubic equation.
* @param segments number of curve segments to use when drawing
* @param matrix target object for the new matrix
*/
protected void splineForward(int segments, PMatrix3D matrix) {
float f = 1.0f / segments;
float ff = f * f;
float fff = ff * f;
matrix.set(0, 0, 0, 1,
fff, ff, f, 0,
6*fff, 2*ff, 0, 0,
6*fff, 0, 0, 0);
}
//////////////////////////////////////////////////////////////
// SMOOTHING
/**
* If true in PImage, use bilinear interpolation for copy()
* operations. When inherited by PGraphics, also controls shapes.
*/
/**
* ( begin auto-generated from smooth.xml )
*
* Draws all geometry with smooth (anti-aliased) edges. This will sometimes
* slow down the frame rate of the application, but will enhance the visual
* refinement. Note that <b>smooth()</b> will also improve image quality of
* resized images, and <b>noSmooth()</b> will disable image (and font)
* smoothing altogether.
*
* ( end auto-generated )
*
* @webref shape:attributes
* @see PGraphics#noSmooth()
* @see PGraphics#hint(int)
* @see PApplet#size(int, int, String)
*/
public void smooth() {
smooth = true;
}
/**
*
* @param level either 2, 4, or 8
*/
public void smooth(int level) {
smooth = true;
}
/**
* ( begin auto-generated from noSmooth.xml )
*
* Draws all geometry with jagged (aliased) edges.
*
* ( end auto-generated )
* @webref shape:attributes
* @see PGraphics#smooth()
*/
public void noSmooth() {
smooth = false;
}
//////////////////////////////////////////////////////////////
// IMAGE
/**
* ( begin auto-generated from imageMode.xml )
*
* Modifies the location from which images draw. The default mode is
* <b>imageMode(CORNER)</b>, which specifies the location to be the upper
* left corner and uses the fourth and fifth parameters of <b>image()</b>
* to set the image's width and height. The syntax
* <b>imageMode(CORNERS)</b> uses the second and third parameters of
* <b>image()</b> to set the location of one corner of the image and uses
* the fourth and fifth parameters to set the opposite corner. Use
* <b>imageMode(CENTER)</b> to draw images centered at the given x and y
* position.<br />
* <br />
* The parameter to <b>imageMode()</b> must be written in ALL CAPS because
* Processing is a case-sensitive language.
*
* ( end auto-generated )
*
* @webref image:loading_displaying
* @param mode either CORNER, CORNERS, or CENTER
* @see PApplet#loadImage(String, String)
* @see PImage
* @see PGraphics#image(PImage, float, float, float, float)
* @see PGraphics#background(float, float, float, float)
*/
public void imageMode(int mode) {
if ((mode == CORNER) || (mode == CORNERS) || (mode == CENTER)) {
imageMode = mode;
} else {
String msg =
"imageMode() only works with CORNER, CORNERS, or CENTER";
throw new RuntimeException(msg);
}
}
/**
* ( begin auto-generated from image.xml )
*
* Displays images to the screen. The images must be in the sketch's "data"
* directory to load correctly. Select "Add file..." from the "Sketch" menu
* to add the image. Processing currently works with GIF, JPEG, and Targa
* images. The <b>img</b> parameter specifies the image to display and the
* <b>x</b> and <b>y</b> parameters define the location of the image from
* its upper-left corner. The image is displayed at its original size
* unless the <b>width</b> and <b>height</b> parameters specify a different
* size.<br />
* <br />
* The <b>imageMode()</b> function changes the way the parameters work. For
* example, a call to <b>imageMode(CORNERS)</b> will change the
* <b>width</b> and <b>height</b> parameters to define the x and y values
* of the opposite corner of the image.<br />
* <br />
* The color of an image may be modified with the <b>tint()</b> function.
* This function will maintain transparency for GIF and PNG images.
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* Starting with release 0124, when using the default (JAVA2D) renderer,
* smooth() will also improve image quality of resized images.
*
* @webref image:loading_displaying
* @param img the image to display
* @param a x-coordinate of the image
* @param b y-coordinate of the image
* @see PApplet#loadImage(String, String)
* @see PImage
* @see PGraphics#imageMode(int)
* @see PGraphics#tint(float)
* @see PGraphics#background(float, float, float, float)
* @see PGraphics#alpha(int)
*/
public void image(PImage img, float a, float b) {
// Starting in release 0144, image errors are simply ignored.
// loadImageAsync() sets width and height to -1 when loading fails.
if (img.width == -1 || img.height == -1) return;
if (imageMode == CORNER || imageMode == CORNERS) {
imageImpl(img,
a, b, a+img.width, b+img.height,
0, 0, img.width, img.height);
} else if (imageMode == CENTER) {
float x1 = a - img.width/2;
float y1 = b - img.height/2;
imageImpl(img,
x1, y1, x1+img.width, y1+img.height,
0, 0, img.width, img.height);
}
}
/**
* @param c width to display the image
* @param d height to display the image
*/
public void image(PImage img, float a, float b, float c, float d) {
image(img, a, b, c, d, 0, 0, img.width, img.height);
}
/**
* Draw an image(), also specifying u/v coordinates.
* In this method, the u, v coordinates are always based on image space
* location, regardless of the current textureMode().
*
* @nowebref
*/
public void image(PImage img,
float a, float b, float c, float d,
int u1, int v1, int u2, int v2) {
// Starting in release 0144, image errors are simply ignored.
// loadImageAsync() sets width and height to -1 when loading fails.
if (img.width == -1 || img.height == -1) return;
if (imageMode == CORNER) {
if (c < 0) { // reset a negative width
a += c; c = -c;
}
if (d < 0) { // reset a negative height
b += d; d = -d;
}
imageImpl(img,
a, b, a + c, b + d,
u1, v1, u2, v2);
} else if (imageMode == CORNERS) {
if (c < a) { // reverse because x2 < x1
float temp = a; a = c; c = temp;
}
if (d < b) { // reverse because y2 < y1
float temp = b; b = d; d = temp;
}
imageImpl(img,
a, b, c, d,
u1, v1, u2, v2);
} else if (imageMode == CENTER) {
// c and d are width/height
if (c < 0) c = -c;
if (d < 0) d = -d;
float x1 = a - c/2;
float y1 = b - d/2;
imageImpl(img,
x1, y1, x1 + c, y1 + d,
u1, v1, u2, v2);
}
}
/**
* Expects x1, y1, x2, y2 coordinates where (x2 >= x1) and (y2 >= y1).
* If tint() has been called, the image will be colored.
* <p/>
* The default implementation draws an image as a textured quad.
* The (u, v) coordinates are in image space (they're ints, after all..)
*/
protected void imageImpl(PImage img,
float x1, float y1, float x2, float y2,
int u1, int v1, int u2, int v2) {
boolean savedStroke = stroke;
// boolean savedFill = fill;
int savedTextureMode = textureMode;
stroke = false;
// fill = true;
textureMode = IMAGE;
// float savedFillR = fillR;
// float savedFillG = fillG;
// float savedFillB = fillB;
// float savedFillA = fillA;
//
// if (tint) {
// fillR = tintR;
// fillG = tintG;
// fillB = tintB;
// fillA = tintA;
//
// } else {
// fillR = 1;
// fillG = 1;
// fillB = 1;
// fillA = 1;
// }
beginShape(QUADS);
texture(img);
vertex(x1, y1, u1, v1);
vertex(x1, y2, u1, v2);
vertex(x2, y2, u2, v2);
vertex(x2, y1, u2, v1);
endShape();
stroke = savedStroke;
// fill = savedFill;
textureMode = savedTextureMode;
// fillR = savedFillR;
// fillG = savedFillG;
// fillB = savedFillB;
// fillA = savedFillA;
}
public Object initCache(PImage img) { // ignore
return null;
}
//////////////////////////////////////////////////////////////
// SHAPE
/**
* ( begin auto-generated from shapeMode.xml )
*
* Modifies the location from which shapes draw. The default mode is
* <b>shapeMode(CORNER)</b>, which specifies the location to be the upper
* left corner of the shape and uses the third and fourth parameters of
* <b>shape()</b> to specify the width and height. The syntax
* <b>shapeMode(CORNERS)</b> uses the first and second parameters of
* <b>shape()</b> to set the location of one corner and uses the third and
* fourth parameters to set the opposite corner. The syntax
* <b>shapeMode(CENTER)</b> draws the shape from its center point and uses
* the third and forth parameters of <b>shape()</b> to specify the width
* and height. The parameter must be written in "ALL CAPS" because
* Processing is a case sensitive language.
*
* ( end auto-generated )
*
* @webref shape:loading_displaying
* @param mode either CORNER, CORNERS, CENTER
* @see PGraphics#shape(PShape)
* @see PGraphics#rectMode(int)
*/
public void shapeMode(int mode) {
this.shapeMode = mode;
}
public void shape(PShape shape) {
if (shape.isVisible()) { // don't do expensive matrix ops if invisible
// Flushing any remaining geometry generated in the immediate mode
// to avoid depth-sorting issues.
flush();
if (shapeMode == CENTER) {
pushMatrix();
translate(-shape.getWidth()/2, -shape.getHeight()/2);
}
shape.draw(this); // needs to handle recorder too
if (shapeMode == CENTER) {
popMatrix();
}
}
}
/**
* ( begin auto-generated from shape.xml )
*
* Displays shapes to the screen. The shapes must be in the sketch's "data"
* directory to load correctly. Select "Add file..." from the "Sketch" menu
* to add the shape. Processing currently works with SVG shapes only. The
* <b>sh</b> parameter specifies the shape to display and the <b>x</b> and
* <b>y</b> parameters define the location of the shape from its upper-left
* corner. The shape is displayed at its original size unless the
* <b>width</b> and <b>height</b> parameters specify a different size. The
* <b>shapeMode()</b> function changes the way the parameters work. A call
* to <b>shapeMode(CORNERS)</b>, for example, will change the width and
* height parameters to define the x and y values of the opposite corner of
* the shape.
* <br /><br />
* Note complex shapes may draw awkwardly with P3D. This renderer does not
* yet support shapes that have holes or complicated breaks.
*
* ( end auto-generated )
*
* @webref shape:loading_displaying
* @param shape the shape to display
* @param x x-coordinate of the shape
* @param y y-coordinate of the shape
* @see PShape
* @see PApplet#loadShape(String)
* @see PGraphics#shapeMode(int)
*
* Convenience method to draw at a particular location.
*/
public void shape(PShape shape, float x, float y) {
if (shape.isVisible()) { // don't do expensive matrix ops if invisible
flush();
pushMatrix();
if (shapeMode == CENTER) {
translate(x - shape.getWidth()/2, y - shape.getHeight()/2);
} else if ((shapeMode == CORNER) || (shapeMode == CORNERS)) {
translate(x, y);
}
shape.draw(this);
popMatrix();
}
}
// TODO unapproved
protected void shape(PShape shape, float x, float y, float z) {
showMissingWarning("shape");
}
/**
* @param a x-coordinate of the shape
* @param b y-coordinate of the shape
* @param c width to display the shape
* @param d height to display the shape
*/
public void shape(PShape shape, float a, float b, float c, float d) {
if (shape.isVisible()) { // don't do expensive matrix ops if invisible
flush();
pushMatrix();
if (shapeMode == CENTER) {
// x and y are center, c and d refer to a diameter
translate(a - c/2f, b - d/2f);
scale(c / shape.getWidth(), d / shape.getHeight());
} else if (shapeMode == CORNER) {
translate(a, b);
scale(c / shape.getWidth(), d / shape.getHeight());
} else if (shapeMode == CORNERS) {
// c and d are x2/y2, make them into width/height
c -= a;
d -= b;
// then same as above
translate(a, b);
scale(c / shape.getWidth(), d / shape.getHeight());
}
shape.draw(this);
popMatrix();
}
}
// TODO unapproved
protected void shape(PShape shape, float x, float y, float z, float c, float d, float e) {
showMissingWarning("shape");
}
//////////////////////////////////////////////////////////////
// TEXT/FONTS
public void textAlign(int alignX) {
textAlign(alignX, BASELINE);
}
/**
* ( begin auto-generated from textAlign.xml )
*
* Sets the current alignment for drawing text. The parameters LEFT,
* CENTER, and RIGHT set the display characteristics of the letters in
* relation to the values for the <b>x</b> and <b>y</b> parameters of the
* <b>text()</b> function.
* <br/> <br/>
* In Processing 0125 and later, an optional second parameter can be used
* to vertically align the text. BASELINE is the default, and the vertical
* alignment will be reset to BASELINE if the second parameter is not used.
* The TOP and CENTER parameters are straightforward. The BOTTOM parameter
* offsets the line based on the current <b>textDescent()</b>. For multiple
* lines, the final line will be aligned to the bottom, with the previous
* lines appearing above it.
* <br/> <br/>
* When using <b>text()</b> with width and height parameters, BASELINE is
* ignored, and treated as TOP. (Otherwise, text would by default draw
* outside the box, since BASELINE is the default setting. BASELINE is not
* a useful drawing mode for text drawn in a rectangle.)
* <br/> <br/>
* The vertical alignment is based on the value of <b>textAscent()</b>,
* which many fonts do not specify correctly. It may be necessary to use a
* hack and offset by a few pixels by hand so that the offset looks
* correct. To do this as less of a hack, use some percentage of
* <b>textAscent()</b> or <b>textDescent()</b> so that the hack works even
* if you change the size of the font.
*
* ( end auto-generated )
*
* @webref typography:attributes
* @param alignX horizontal alignment, either LEFT, CENTER, or RIGHT
* @param alignY vertical alignment, either TOP, BOTTOM, CENTER, or BASELINE
* @see PApplet#loadFont(String)
* @see PFont
* @see PGraphics#text(String, float, float)
*/
public void textAlign(int alignX, int alignY) {
textAlign = alignX;
textAlignY = alignY;
}
/**
* ( begin auto-generated from textAscent.xml )
*
* Returns ascent of the current font at its current size. This information
* is useful for determining the height of the font above the baseline. For
* example, adding the <b>textAscent()</b> and <b>textDescent()</b> values
* will give you the total height of the line.
*
* ( end auto-generated )
*
* @webref typography:metrics
* @see PGraphics#textDescent()
*/
public float textAscent() {
if (textFont == null) {
defaultFontOrDeath("textAscent");
}
return textFont.ascent() * textSize;
}
/**
* ( begin auto-generated from textDescent.xml )
*
* Returns descent of the current font at its current size. This
* information is useful for determining the height of the font below the
* baseline. For example, adding the <b>textAscent()</b> and
* <b>textDescent()</b> values will give you the total height of the line.
*
* ( end auto-generated )
*
* @webref typography:metrics
* @see PGraphics#textAscent()
*/
public float textDescent() {
if (textFont == null) {
defaultFontOrDeath("textDescent");
}
return textFont.descent() * textSize;
}
/**
* ( begin auto-generated from textFont.xml )
*
* Sets the current font that will be drawn with the <b>text()</b>
* function. Fonts must be loaded with <b>loadFont()</b> before it can be
* used. This font will be used in all subsequent calls to the
* <b>text()</b> function. If no <b>size</b> parameter is input, the font
* will appear at its original size (the size it was created at with the
* "Create Font..." tool) until it is changed with <b>textSize()</b>. <br
* /> <br /> Because fonts are usually bitmaped, you should create fonts at
* the sizes that will be used most commonly. Using <b>textFont()</b>
* without the size parameter will result in the cleanest-looking text. <br
* /><br /> With the default (JAVA2D) and PDF renderers, it's also possible
* to enable the use of native fonts via the command
* <b>hint(ENABLE_NATIVE_FONTS)</b>. This will produce vector text in
* JAVA2D sketches and PDF output in cases where the vector data is
* available: when the font is still installed, or the font is created via
* the <b>createFont()</b> function (rather than the Create Font tool).
*
* ( end auto-generated )
*
* @webref typography:loading_displaying
* @param which any variable of the type PFont
* @see PApplet#createFont(String, float, boolean)
* @see PApplet#loadFont(String)
* @see PFont#PFont
* @see PGraphics#text(String, float, float)
*/
public void textFont(PFont which) {
if (which != null) {
textFont = which;
if (hints[ENABLE_NATIVE_FONTS]) {
//if (which.font == null) {
which.findNative();
//}
}
/*
textFontNative = which.font;
//textFontNativeMetrics = null;
// changed for rev 0104 for textMode(SHAPE) in opengl
if (textFontNative != null) {
// TODO need a better way to handle this. could use reflection to get
// rid of the warning, but that'd be a little silly. supporting this is
// an artifact of supporting java 1.1, otherwise we'd use getLineMetrics,
// as recommended by the @deprecated flag.
textFontNativeMetrics =
Toolkit.getDefaultToolkit().getFontMetrics(textFontNative);
// The following is what needs to be done, however we need to be able
// to get the actual graphics context where the drawing is happening.
// For instance, parent.getGraphics() doesn't work for OpenGL since
// an OpenGL drawing surface is an embedded component.
// if (parent != null) {
// textFontNativeMetrics = parent.getGraphics().getFontMetrics(textFontNative);
// }
// float w = font.getStringBounds(text, g2.getFontRenderContext()).getWidth();
}
*/
textSize(which.size);
} else {
throw new RuntimeException(ERROR_TEXTFONT_NULL_PFONT);
}
}
/**
* @param size the size of the letters in units of pixels
*/
public void textFont(PFont which, float size) {
textFont(which);
textSize(size);
}
/**
* ( begin auto-generated from textLeading.xml )
*
* Sets the spacing between lines of text in units of pixels. This setting
* will be used in all subsequent calls to the <b>text()</b> function.
*
* ( end auto-generated )
*
* @webref typography:attributes
* @param leading the size in pixels for spacing between lines
* @see PApplet#loadFont(String)
* @see PFont#PFont
* @see PGraphics#text(String, float, float)
* @see PGraphics#textFont(PFont)
*/
public void textLeading(float leading) {
textLeading = leading;
}
/**
* ( begin auto-generated from textMode.xml )
*
* Sets the way text draws to the screen. In the default configuration, the
* <b>MODEL</b> mode, it's possible to rotate, scale, and place letters in
* two and three dimensional space.<br />
* <br />
* The <b>SHAPE</b> mode draws text using the the glyph outlines of
* individual characters rather than as textures. This mode is only
* supported with the <b>PDF</b> and <b>P3D</b> renderer settings. With the
* <b>PDF</b> renderer, you must call <b>textMode(SHAPE)</b> before any
* other drawing occurs. If the outlines are not available, then
* <b>textMode(SHAPE)</b> will be ignored and <b>textMode(MODEL)</b> will
* be used instead.<br />
* <br />
* The <b>textMode(SHAPE)</b> option in <b>P3D</b> can be combined with
* <b>beginRaw()</b> to write vector-accurate text to 2D and 3D output
* files, for instance <b>DXF</b> or <b>PDF</b>. The <b>SHAPE</b> mode is
* not currently optimized for <b>P3D</b>, so if recording shape data, use
* <b>textMode(MODEL)</b> until you're ready to capture the geometry with <b>beginRaw()</b>.
*
* ( end auto-generated )
*
* @webref typography:attributes
* @param mode either MODEL or SHAPE
* @see PApplet#loadFont(String)
* @see PFont#PFont
* @see PGraphics#text(String, float, float)
* @see PGraphics#textFont(PFont)
* @see PGraphics#beginRaw(PGraphics)
* @see PApplet#createFont(String, float, boolean)
*/
public void textMode(int mode) {
// CENTER and MODEL overlap (they're both 3)
if ((mode == LEFT) || (mode == RIGHT)) {
- showWarning("Since Processing beta, textMode() is now textAlign().");
+ showWarning("Since Processing 1.0 beta, textMode() is now textAlign().");
return;
}
if (mode == SCREEN) {
showWarning("textMode(SCREEN) has been removed from Processing 2.0.");
+ return;
}
if (textModeCheck(mode)) {
textMode = mode;
} else {
String modeStr = String.valueOf(mode);
switch (mode) {
case MODEL: modeStr = "MODEL"; break;
case SHAPE: modeStr = "SHAPE"; break;
}
showWarning("textMode(" + modeStr + ") is not supported by this renderer.");
}
}
protected boolean textModeCheck(int mode) {
return true;
}
/**
* ( begin auto-generated from textSize.xml )
*
* Sets the current font size. This size will be used in all subsequent
* calls to the <b>text()</b> function. Font size is measured in units of pixels.
*
* ( end auto-generated )
*
* @webref typography:attributes
* @param size the size of the letters in units of pixels
* @see PApplet#loadFont(String)
* @see PFont#PFont
* @see PGraphics#text(String, float, float)
* @see PGraphics#textFont(PFont)
*/
public void textSize(float size) {
if (textFont == null) {
defaultFontOrDeath("textSize", size);
}
textSize = size;
textLeading = (textAscent() + textDescent()) * 1.275f;
}
// ........................................................
/**
* @param c the character to measure
*/
public float textWidth(char c) {
textWidthBuffer[0] = c;
return textWidthImpl(textWidthBuffer, 0, 1);
}
/**
* ( begin auto-generated from textWidth.xml )
*
* Calculates and returns the width of any character or text string.
*
* ( end auto-generated )
*
* @webref typography:attributes
* @param str the String of characters to measure
* @see PApplet#loadFont(String)
* @see PFont#PFont
* @see PGraphics#text(String, float, float)
* @see PGraphics#textFont(PFont)
*/
public float textWidth(String str) {
if (textFont == null) {
defaultFontOrDeath("textWidth");
}
int length = str.length();
if (length > textWidthBuffer.length) {
textWidthBuffer = new char[length + 10];
}
str.getChars(0, length, textWidthBuffer, 0);
float wide = 0;
int index = 0;
int start = 0;
while (index < length) {
if (textWidthBuffer[index] == '\n') {
wide = Math.max(wide, textWidthImpl(textWidthBuffer, start, index));
start = index+1;
}
index++;
}
if (start < length) {
wide = Math.max(wide, textWidthImpl(textWidthBuffer, start, index));
}
return wide;
}
/**
* @nowebref
*/
public float textWidth(char[] chars, int start, int length) {
return textWidthImpl(chars, start, start + length);
}
/**
* Implementation of returning the text width of
* the chars [start, stop) in the buffer.
* Unlike the previous version that was inside PFont, this will
* return the size not of a 1 pixel font, but the actual current size.
*/
protected float textWidthImpl(char buffer[], int start, int stop) {
float wide = 0;
for (int i = start; i < stop; i++) {
// could add kerning here, but it just ain't implemented
wide += textFont.width(buffer[i]) * textSize;
}
return wide;
}
// ........................................................
/**
* ( begin auto-generated from text.xml )
*
* Draws text to the screen. Displays the information specified in the
* <b>data</b> or <b>stringdata</b> parameters on the screen in the
* position specified by the <b>x</b> and <b>y</b> parameters and the
* optional <b>z</b> parameter. A default font will be used unless a font
* is set with the <b>textFont()</b> function. Change the color of the text
* with the <b>fill()</b> function. The text displays in relation to the
* <b>textAlign()</b> function, which gives the option to draw to the left,
* right, and center of the coordinates.
* <br /><br />
* The <b>x2</b> and <b>y2</b> parameters define a rectangular area to
* display within and may only be used with string data. For text drawn
* inside a rectangle, the coordinates are interpreted based on the current
* <b>rectMode()</b> setting.
*
* ( end auto-generated )
*
* @webref typography:loading_displaying
* @param c the alphanumeric character to be displayed
* @param x x-coordinate of text
* @param y y-coordinate of text
* @see PGraphics#textAlign(int, int)
* @see PGraphics#textMode(int)
* @see PApplet#loadFont(String)
* @see PFont#PFont
* @see PGraphics#textFont(PFont)
* @see PGraphics#rectMode(int)
* @see PGraphics#fill(int, float)
* @see_external String
*/
public void text(char c, float x, float y) {
if (textFont == null) {
defaultFontOrDeath("text");
}
if (textAlignY == CENTER) {
y += textAscent() / 2;
} else if (textAlignY == TOP) {
y += textAscent();
} else if (textAlignY == BOTTOM) {
y -= textDescent();
//} else if (textAlignY == BASELINE) {
// do nothing
}
textBuffer[0] = c;
textLineAlignImpl(textBuffer, 0, 1, x, y);
}
/**
* @param z z-coordinate of text
*/
public void text(char c, float x, float y, float z) {
// if ((z != 0) && (textMode == SCREEN)) {
// String msg = "textMode(SCREEN) cannot have a z coordinate";
// throw new RuntimeException(msg);
// }
if (z != 0) translate(0, 0, z); // slowness, badness
text(c, x, y);
// textZ = z;
if (z != 0) translate(0, 0, -z);
}
/**
* @param str the alphanumeric symbols to be displayed
*/
// public void text(String str) {
// text(str, textX, textY, textZ);
// }
/**
* <h3>Advanced</h3>
* Draw a chunk of text.
* Newlines that are \n (Unix newline or linefeed char, ascii 10)
* are honored, but \r (carriage return, Windows and Mac OS) are
* ignored.
*/
public void text(String str, float x, float y) {
if (textFont == null) {
defaultFontOrDeath("text");
}
int length = str.length();
if (length > textBuffer.length) {
textBuffer = new char[length + 10];
}
str.getChars(0, length, textBuffer, 0);
text(textBuffer, 0, length, x, y);
}
/**
* <h3>Advanced</h3>
* Method to draw text from an array of chars. This method will usually be
* more efficient than drawing from a String object, because the String will
* not be converted to a char array before drawing.
* @param chars the alphanumberic symbols to be displayed
* @param start array index at which to start writing characters
* @param stop array index at which to stop writing characters
*/
public void text(char[] chars, int start, int stop, float x, float y) {
// If multiple lines, sum the height of the additional lines
float high = 0; //-textAscent();
for (int i = start; i < stop; i++) {
if (chars[i] == '\n') {
high += textLeading;
}
}
if (textAlignY == CENTER) {
// for a single line, this adds half the textAscent to y
// for multiple lines, subtract half the additional height
//y += (textAscent() - textDescent() - high)/2;
y += (textAscent() - high)/2;
} else if (textAlignY == TOP) {
// for a single line, need to add textAscent to y
// for multiple lines, no different
y += textAscent();
} else if (textAlignY == BOTTOM) {
// for a single line, this is just offset by the descent
// for multiple lines, subtract leading for each line
y -= textDescent() + high;
//} else if (textAlignY == BASELINE) {
// do nothing
}
// int start = 0;
int index = 0;
while (index < stop) { //length) {
if (chars[index] == '\n') {
textLineAlignImpl(chars, start, index, x, y);
start = index + 1;
y += textLeading;
}
index++;
}
if (start < stop) { //length) {
textLineAlignImpl(chars, start, index, x, y);
}
}
/**
* Same as above but with a z coordinate.
*/
public void text(String str, float x, float y, float z) {
if (z != 0) translate(0, 0, z); // slow!
text(str, x, y);
// textZ = z;
if (z != 0) translate(0, 0, -z); // inaccurate!
}
public void text(char[] chars, int start, int stop,
float x, float y, float z) {
if (z != 0) translate(0, 0, z); // slow!
text(chars, start, stop, x, y);
// textZ = z;
if (z != 0) translate(0, 0, -z); // inaccurate!
}
/**
* <h3>Advanced</h3>
* Draw text in a box that is constrained to a particular size.
* The current rectMode() determines what the coordinates mean
* (whether x1/y1/x2/y2 or x/y/w/h).
* <P/>
* Note that the x,y coords of the start of the box
* will align with the *ascent* of the text, not the baseline,
* as is the case for the other text() functions.
* <P/>
* Newlines that are \n (Unix newline or linefeed char, ascii 10)
* are honored, and \r (carriage return, Windows and Mac OS) are
* ignored.
*
* @param x1 by default, the x-coordinate of text, see rectMode() for more info
* @param y1 by default, the x-coordinate of text, see rectMode() for more info
* @param x2 by default, the width of the text box, see rectMode() for more info
* @param y2 by default, the height of the text box, see rectMode() for more info
*/
public void text(String str, float x1, float y1, float x2, float y2) {
if (textFont == null) {
defaultFontOrDeath("text");
}
float hradius, vradius;
switch (rectMode) {
case CORNER:
x2 += x1; y2 += y1;
break;
case RADIUS:
hradius = x2;
vradius = y2;
x2 = x1 + hradius;
y2 = y1 + vradius;
x1 -= hradius;
y1 -= vradius;
break;
case CENTER:
hradius = x2 / 2.0f;
vradius = y2 / 2.0f;
x2 = x1 + hradius;
y2 = y1 + vradius;
x1 -= hradius;
y1 -= vradius;
}
if (x2 < x1) {
float temp = x1; x1 = x2; x2 = temp;
}
if (y2 < y1) {
float temp = y1; y1 = y2; y2 = temp;
}
// float currentY = y1;
float boxWidth = x2 - x1;
// // ala illustrator, the text itself must fit inside the box
// currentY += textAscent(); //ascent() * textSize;
// // if the box is already too small, tell em to f off
// if (currentY > y2) return;
float spaceWidth = textWidth(' ');
if (textBreakStart == null) {
textBreakStart = new int[20];
textBreakStop = new int[20];
}
textBreakCount = 0;
int length = str.length();
if (length + 1 > textBuffer.length) {
textBuffer = new char[length + 1];
}
str.getChars(0, length, textBuffer, 0);
// add a fake newline to simplify calculations
textBuffer[length++] = '\n';
int sentenceStart = 0;
for (int i = 0; i < length; i++) {
if (textBuffer[i] == '\n') {
// currentY = textSentence(textBuffer, sentenceStart, i,
// lineX, boxWidth, currentY, y2, spaceWidth);
boolean legit =
textSentence(textBuffer, sentenceStart, i, boxWidth, spaceWidth);
if (!legit) break;
// if (Float.isNaN(currentY)) break; // word too big (or error)
// if (currentY > y2) break; // past the box
sentenceStart = i + 1;
}
}
// lineX is the position where the text starts, which is adjusted
// to left/center/right based on the current textAlign
float lineX = x1; //boxX1;
if (textAlign == CENTER) {
lineX = lineX + boxWidth/2f;
} else if (textAlign == RIGHT) {
lineX = x2; //boxX2;
}
float boxHeight = y2 - y1;
//int lineFitCount = 1 + PApplet.floor((boxHeight - textAscent()) / textLeading);
// incorporate textAscent() for the top (baseline will be y1 + ascent)
// and textDescent() for the bottom, so that lower parts of letters aren't
// outside the box. [0151]
float topAndBottom = textAscent() + textDescent();
int lineFitCount = 1 + PApplet.floor((boxHeight - topAndBottom) / textLeading);
int lineCount = Math.min(textBreakCount, lineFitCount);
if (textAlignY == CENTER) {
float lineHigh = textAscent() + textLeading * (lineCount - 1);
float y = y1 + textAscent() + (boxHeight - lineHigh) / 2;
for (int i = 0; i < lineCount; i++) {
textLineAlignImpl(textBuffer, textBreakStart[i], textBreakStop[i], lineX, y);
y += textLeading;
}
} else if (textAlignY == BOTTOM) {
float y = y2 - textDescent() - textLeading * (lineCount - 1);
for (int i = 0; i < lineCount; i++) {
textLineAlignImpl(textBuffer, textBreakStart[i], textBreakStop[i], lineX, y);
y += textLeading;
}
} else { // TOP or BASELINE just go to the default
float y = y1 + textAscent();
for (int i = 0; i < lineCount; i++) {
textLineAlignImpl(textBuffer, textBreakStart[i], textBreakStop[i], lineX, y);
y += textLeading;
}
}
}
/**
* Emit a sentence of text, defined as a chunk of text without any newlines.
* @param stop non-inclusive, the end of the text in question
*/
protected boolean textSentence(char[] buffer, int start, int stop,
float boxWidth, float spaceWidth) {
float runningX = 0;
// Keep track of this separately from index, since we'll need to back up
// from index when breaking words that are too long to fit.
int lineStart = start;
int wordStart = start;
int index = start;
while (index <= stop) {
// boundary of a word or end of this sentence
if ((buffer[index] == ' ') || (index == stop)) {
float wordWidth = textWidthImpl(buffer, wordStart, index);
if (runningX + wordWidth > boxWidth) {
if (runningX != 0) {
// Next word is too big, output the current line and advance
index = wordStart;
textSentenceBreak(lineStart, index);
// Eat whitespace because multiple spaces don't count for s*
// when they're at the end of a line.
while ((index < stop) && (buffer[index] == ' ')) {
index++;
}
} else { // (runningX == 0)
// If this is the first word on the line, and its width is greater
// than the width of the text box, then break the word where at the
// max width, and send the rest of the word to the next line.
do {
index--;
if (index == wordStart) {
// Not a single char will fit on this line. screw 'em.
//System.out.println("screw you");
return false; //Float.NaN;
}
wordWidth = textWidthImpl(buffer, wordStart, index);
} while (wordWidth > boxWidth);
//textLineImpl(buffer, lineStart, index, x, y);
textSentenceBreak(lineStart, index);
}
lineStart = index;
wordStart = index;
runningX = 0;
} else if (index == stop) {
// last line in the block, time to unload
//textLineImpl(buffer, lineStart, index, x, y);
textSentenceBreak(lineStart, index);
// y += textLeading;
index++;
} else { // this word will fit, just add it to the line
runningX += wordWidth + spaceWidth;
wordStart = index + 1; // move on to the next word
index++;
}
} else { // not a space or the last character
index++; // this is just another letter
}
}
// return y;
return true;
}
protected void textSentenceBreak(int start, int stop) {
if (textBreakCount == textBreakStart.length) {
textBreakStart = PApplet.expand(textBreakStart);
textBreakStop = PApplet.expand(textBreakStop);
}
textBreakStart[textBreakCount] = start;
textBreakStop[textBreakCount] = stop;
textBreakCount++;
}
// public void text(String s, float a, float b, float c, float d, float z) {
// if (z != 0) translate(0, 0, z); // slowness, badness
//
// text(s, a, b, c, d);
// textZ = z;
//
// if (z != 0) translate(0, 0, -z); // TEMPORARY HACK! SLOW!
// }
public void text(int num, float x, float y) {
text(String.valueOf(num), x, y);
}
public void text(int num, float x, float y, float z) {
text(String.valueOf(num), x, y, z);
}
/**
* This does a basic number formatting, to avoid the
* generally ugly appearance of printing floats.
* Users who want more control should use their own nf() cmmand,
* or if they want the long, ugly version of float,
* use String.valueOf() to convert the float to a String first.
*
* @param num the numeric value to be displayed
*/
public void text(float num, float x, float y) {
text(PApplet.nfs(num, 0, 3), x, y);
}
public void text(float num, float x, float y, float z) {
text(PApplet.nfs(num, 0, 3), x, y, z);
}
//////////////////////////////////////////////////////////////
// TEXT IMPL
// These are most likely to be overridden by subclasses, since the other
// (public) functions handle generic features like setting alignment.
/**
* Handles placement of a text line, then calls textLineImpl
* to actually render at the specific point.
*/
protected void textLineAlignImpl(char buffer[], int start, int stop,
float x, float y) {
if (textAlign == CENTER) {
x -= textWidthImpl(buffer, start, stop) / 2f;
} else if (textAlign == RIGHT) {
x -= textWidthImpl(buffer, start, stop);
}
textLineImpl(buffer, start, stop, x, y);
}
/**
* Implementation of actual drawing for a line of text.
*/
protected void textLineImpl(char buffer[], int start, int stop,
float x, float y) {
for (int index = start; index < stop; index++) {
textCharImpl(buffer[index], x, y);
// this doesn't account for kerning
x += textWidth(buffer[index]);
}
// textX = x;
// textY = y;
// textZ = 0; // this will get set by the caller if non-zero
}
protected void textCharImpl(char ch, float x, float y) { //, float z) {
PFont.Glyph glyph = textFont.getGlyph(ch);
if (glyph != null) {
if (textMode == MODEL) {
float high = glyph.height / (float) textFont.size;
float bwidth = glyph.width / (float) textFont.size;
float lextent = glyph.leftExtent / (float) textFont.size;
float textent = glyph.topExtent / (float) textFont.size;
float x1 = x + lextent * textSize;
float y1 = y - textent * textSize;
float x2 = x1 + bwidth * textSize;
float y2 = y1 + high * textSize;
textCharModelImpl(glyph.image,
x1, y1, x2, y2,
glyph.width, glyph.height);
}
} else if (ch != ' ' && ch != 127) {
showWarning("No glyph found for the " + ch + " (\\u" + PApplet.hex(ch, 4) + ") character");
}
}
protected void textCharModelImpl(PImage glyph,
float x1, float y1, //float z1,
float x2, float y2, //float z2,
int u2, int v2) {
boolean savedTint = tint;
int savedTintColor = tintColor;
float savedTintR = tintR;
float savedTintG = tintG;
float savedTintB = tintB;
float savedTintA = tintA;
boolean savedTintAlpha = tintAlpha;
tint = true;
tintColor = fillColor;
tintR = fillR;
tintG = fillG;
tintB = fillB;
tintA = fillA;
tintAlpha = fillAlpha;
imageImpl(glyph, x1, y1, x2, y2, 0, 0, u2, v2);
tint = savedTint;
tintColor = savedTintColor;
tintR = savedTintR;
tintG = savedTintG;
tintB = savedTintB;
tintA = savedTintA;
tintAlpha = savedTintAlpha;
}
protected void textCharScreenImpl(PImage glyph,
int xx, int yy,
int w0, int h0) {
int x0 = 0;
int y0 = 0;
if ((xx >= width) || (yy >= height) ||
(xx + w0 < 0) || (yy + h0 < 0)) return;
if (xx < 0) {
x0 -= xx;
w0 += xx;
xx = 0;
}
if (yy < 0) {
y0 -= yy;
h0 += yy;
yy = 0;
}
if (xx + w0 > width) {
w0 -= ((xx + w0) - width);
}
if (yy + h0 > height) {
h0 -= ((yy + h0) - height);
}
int fr = fillRi;
int fg = fillGi;
int fb = fillBi;
int fa = fillAi;
int pixels1[] = glyph.pixels; //images[glyph].pixels;
// TODO this can be optimized a bit
for (int row = y0; row < y0 + h0; row++) {
for (int col = x0; col < x0 + w0; col++) {
//int a1 = (fa * pixels1[row * textFont.twidth + col]) >> 8;
int a1 = (fa * pixels1[row * glyph.width + col]) >> 8;
int a2 = a1 ^ 0xff;
//int p1 = pixels1[row * glyph.width + col];
int p2 = pixels[(yy + row-y0)*width + (xx+col-x0)];
pixels[(yy + row-y0)*width + xx+col-x0] =
(0xff000000 |
(((a1 * fr + a2 * ((p2 >> 16) & 0xff)) & 0xff00) << 8) |
(( a1 * fg + a2 * ((p2 >> 8) & 0xff)) & 0xff00) |
(( a1 * fb + a2 * ( p2 & 0xff)) >> 8));
}
}
}
//////////////////////////////////////////////////////////////
// MATRIX STACK
/**
* ( begin auto-generated from pushMatrix.xml )
*
* Pushes the current transformation matrix onto the matrix stack.
* Understanding <b>pushMatrix()</b> and <b>popMatrix()</b> requires
* understanding the concept of a matrix stack. The <b>pushMatrix()</b>
* function saves the current coordinate system to the stack and
* <b>popMatrix()</b> restores the prior coordinate system.
* <b>pushMatrix()</b> and <b>popMatrix()</b> are used in conjuction with
* the other transformation functions and may be embedded to control the
* scope of the transformations.
*
* ( end auto-generated )
*
* @webref transform
* @see PGraphics#popMatrix()
* @see PGraphics#translate(float, float, float)
* @see PGraphics#rotate(float)
* @see PGraphics#rotateX(float)
* @see PGraphics#rotateY(float)
* @see PGraphics#rotateZ(float)
*/
public void pushMatrix() {
showMethodWarning("pushMatrix");
}
/**
* ( begin auto-generated from popMatrix.xml )
*
* Pops the current transformation matrix off the matrix stack.
* Understanding pushing and popping requires understanding the concept of
* a matrix stack. The <b>pushMatrix()</b> function saves the current
* coordinate system to the stack and <b>popMatrix()</b> restores the prior
* coordinate system. <b>pushMatrix()</b> and <b>popMatrix()</b> are used
* in conjuction with the other transformation functions and may be
* embedded to control the scope of the transformations.
*
* ( end auto-generated )
*
* @webref transform
* @see PGraphics#pushMatrix()
*/
public void popMatrix() {
showMethodWarning("popMatrix");
}
//////////////////////////////////////////////////////////////
// MATRIX TRANSFORMATIONS
/**
* ( begin auto-generated from translate.xml )
*
* Specifies an amount to displace objects within the display window. The
* <b>x</b> parameter specifies left/right translation, the <b>y</b>
* parameter specifies up/down translation, and the <b>z</b> parameter
* specifies translations toward/away from the screen. Using this function
* with the <b>z</b> parameter requires using P3D as a parameter in
* combination with size as shown in the above example. Transformations
* apply to everything that happens after and subsequent calls to the
* function accumulates the effect. For example, calling <b>translate(50,
* 0)</b> and then <b>translate(20, 0)</b> is the same as <b>translate(70,
* 0)</b>. If <b>translate()</b> is called within <b>draw()</b>, the
* transformation is reset when the loop begins again. This function can be
* further controlled by the <b>pushMatrix()</b> and <b>popMatrix()</b>.
*
* ( end auto-generated )
*
* @webref transform
* @param x left/right translation
* @param y up/down translation
* @see PGraphics#popMatrix()
* @see PGraphics#pushMatrix()
* @see PGraphics#rotate(float)
* @see PGraphics#rotateX(float)
* @see PGraphics#rotateY(float)
* @see PGraphics#rotateZ(float)
* @see PGraphics#scale(float, float, float)
*/
public void translate(float x, float y) {
showMissingWarning("translate");
}
/**
* @param z forward/backward translation
*/
public void translate(float x, float y, float z) {
showMissingWarning("translate");
}
/**
* ( begin auto-generated from rotate.xml )
*
* Rotates a shape the amount specified by the <b>angle</b> parameter.
* Angles should be specified in radians (values from 0 to TWO_PI) or
* converted to radians with the <b>radians()</b> function.
* <br/> <br/>
* Objects are always rotated around their relative position to the origin
* and positive numbers rotate objects in a clockwise direction.
* Transformations apply to everything that happens after and subsequent
* calls to the function accumulates the effect. For example, calling
* <b>rotate(HALF_PI)</b> and then <b>rotate(HALF_PI)</b> is the same as
* <b>rotate(PI)</b>. All tranformations are reset when <b>draw()</b>
* begins again.
* <br/> <br/>
* Technically, <b>rotate()</b> multiplies the current transformation
* matrix by a rotation matrix. This function can be further controlled by
* the <b>pushMatrix()</b> and <b>popMatrix()</b>.
*
* ( end auto-generated )
*
* @webref transform
* @param angle angle of rotation specified in radians
* @see PGraphics#popMatrix()
* @see PGraphics#pushMatrix()
* @see PGraphics#rotateX(float)
* @see PGraphics#rotateY(float)
* @see PGraphics#rotateZ(float)
* @see PGraphics#scale(float, float, float)
* @see PApplet#radians(float)
*/
public void rotate(float angle) {
showMissingWarning("rotate");
}
/**
* ( begin auto-generated from rotateX.xml )
*
* Rotates a shape around the x-axis the amount specified by the
* <b>angle</b> parameter. Angles should be specified in radians (values
* from 0 to PI*2) or converted to radians with the <b>radians()</b>
* function. Objects are always rotated around their relative position to
* the origin and positive numbers rotate objects in a counterclockwise
* direction. Transformations apply to everything that happens after and
* subsequent calls to the function accumulates the effect. For example,
* calling <b>rotateX(PI/2)</b> and then <b>rotateX(PI/2)</b> is the same
* as <b>rotateX(PI)</b>. If <b>rotateX()</b> is called within the
* <b>draw()</b>, the transformation is reset when the loop begins again.
* This function requires using P3D as a third parameter to <b>size()</b>
* as shown in the example above.
*
* ( end auto-generated )
*
* @webref transform
* @param angle angle of rotation specified in radians
* @see PGraphics#popMatrix()
* @see PGraphics#pushMatrix()
* @see PGraphics#rotate(float)
* @see PGraphics#rotateY(float)
* @see PGraphics#rotateZ(float)
* @see PGraphics#scale(float, float, float)
* @see PGraphics#translate(float, float, float)
*/
public void rotateX(float angle) {
showMethodWarning("rotateX");
}
/**
* ( begin auto-generated from rotateY.xml )
*
* Rotates a shape around the y-axis the amount specified by the
* <b>angle</b> parameter. Angles should be specified in radians (values
* from 0 to PI*2) or converted to radians with the <b>radians()</b>
* function. Objects are always rotated around their relative position to
* the origin and positive numbers rotate objects in a counterclockwise
* direction. Transformations apply to everything that happens after and
* subsequent calls to the function accumulates the effect. For example,
* calling <b>rotateY(PI/2)</b> and then <b>rotateY(PI/2)</b> is the same
* as <b>rotateY(PI)</b>. If <b>rotateY()</b> is called within the
* <b>draw()</b>, the transformation is reset when the loop begins again.
* This function requires using P3D as a third parameter to <b>size()</b>
* as shown in the examples above.
*
* ( end auto-generated )
*
* @webref transform
* @param angle angle of rotation specified in radians
* @see PGraphics#popMatrix()
* @see PGraphics#pushMatrix()
* @see PGraphics#rotate(float)
* @see PGraphics#rotateX(float)
* @see PGraphics#rotateZ(float)
* @see PGraphics#scale(float, float, float)
* @see PGraphics#translate(float, float, float)
*/
public void rotateY(float angle) {
showMethodWarning("rotateY");
}
/**
* ( begin auto-generated from rotateZ.xml )
*
* Rotates a shape around the z-axis the amount specified by the
* <b>angle</b> parameter. Angles should be specified in radians (values
* from 0 to PI*2) or converted to radians with the <b>radians()</b>
* function. Objects are always rotated around their relative position to
* the origin and positive numbers rotate objects in a counterclockwise
* direction. Transformations apply to everything that happens after and
* subsequent calls to the function accumulates the effect. For example,
* calling <b>rotateZ(PI/2)</b> and then <b>rotateZ(PI/2)</b> is the same
* as <b>rotateZ(PI)</b>. If <b>rotateZ()</b> is called within the
* <b>draw()</b>, the transformation is reset when the loop begins again.
* This function requires using P3D as a third parameter to <b>size()</b>
* as shown in the examples above.
*
* ( end auto-generated )
*
* @webref transform
* @param angle angle of rotation specified in radians
* @see PGraphics#popMatrix()
* @see PGraphics#pushMatrix()
* @see PGraphics#rotate(float)
* @see PGraphics#rotateX(float)
* @see PGraphics#rotateY(float)
* @see PGraphics#scale(float, float, float)
* @see PGraphics#translate(float, float, float)
*/
public void rotateZ(float angle) {
showMethodWarning("rotateZ");
}
/**
* <h3>Advanced</h3>
* Rotate about a vector in space. Same as the glRotatef() function.
* @param x
* @param y
* @param z
*/
public void rotate(float angle, float x, float y, float z) {
showMissingWarning("rotate");
}
/**
* ( begin auto-generated from scale.xml )
*
* Increases or decreases the size of a shape by expanding and contracting
* vertices. Objects always scale from their relative origin to the
* coordinate system. Scale values are specified as decimal percentages.
* For example, the function call <b>scale(2.0)</b> increases the dimension
* of a shape by 200%. Transformations apply to everything that happens
* after and subsequent calls to the function multiply the effect. For
* example, calling <b>scale(2.0)</b> and then <b>scale(1.5)</b> is the
* same as <b>scale(3.0)</b>. If <b>scale()</b> is called within
* <b>draw()</b>, the transformation is reset when the loop begins again.
* Using this fuction with the <b>z</b> parameter requires using P3D as a
* parameter for <b>size()</b> as shown in the example above. This function
* can be further controlled by <b>pushMatrix()</b> and <b>popMatrix()</b>.
*
* ( end auto-generated )
*
* @webref transform
* @param s percentage to scale the object
* @see PGraphics#pushMatrix()
* @see PGraphics#popMatrix()
* @see PGraphics#translate(float, float, float)
* @see PGraphics#rotate(float)
* @see PGraphics#rotateX(float)
* @see PGraphics#rotateY(float)
* @see PGraphics#rotateZ(float)
*/
public void scale(float s) {
showMissingWarning("scale");
}
/**
* <h3>Advanced</h3>
* Scale in X and Y. Equivalent to scale(sx, sy, 1).
*
* Not recommended for use in 3D, because the z-dimension is just
* scaled by 1, since there's no way to know what else to scale it by.
*
* @param x percentage to scale the object in the x-axis
* @param y percentage to scale the object in the y-axis
*/
public void scale(float x, float y) {
showMissingWarning("scale");
}
/**
* @param z percentage to scale the object in the z-axis
*/
public void scale(float x, float y, float z) {
showMissingWarning("scale");
}
/**
* ( begin auto-generated from shearX.xml )
*
* Shears a shape around the x-axis the amount specified by the
* <b>angle</b> parameter. Angles should be specified in radians (values
* from 0 to PI*2) or converted to radians with the <b>radians()</b>
* function. Objects are always sheared around their relative position to
* the origin and positive numbers shear objects in a clockwise direction.
* Transformations apply to everything that happens after and subsequent
* calls to the function accumulates the effect. For example, calling
* <b>shearX(PI/2)</b> and then <b>shearX(PI/2)</b> is the same as
* <b>shearX(PI)</b>. If <b>shearX()</b> is called within the
* <b>draw()</b>, the transformation is reset when the loop begins again.
* <br/> <br/>
* Technically, <b>shearX()</b> multiplies the current transformation
* matrix by a rotation matrix. This function can be further controlled by
* the <b>pushMatrix()</b> and <b>popMatrix()</b> functions.
*
* ( end auto-generated )
*
* @webref transform
* @param angle angle of shear specified in radians
* @see PGraphics#popMatrix()
* @see PGraphics#pushMatrix()
* @see PGraphics#shearY(float)
* @see PGraphics#scale(float, float, float)
* @see PGraphics#translate(float, float, float)
* @see PApplet#radians(float)
*/
public void shearX(float angle) {
showMissingWarning("shearX");
}
/**
* ( begin auto-generated from shearY.xml )
*
* Shears a shape around the y-axis the amount specified by the
* <b>angle</b> parameter. Angles should be specified in radians (values
* from 0 to PI*2) or converted to radians with the <b>radians()</b>
* function. Objects are always sheared around their relative position to
* the origin and positive numbers shear objects in a clockwise direction.
* Transformations apply to everything that happens after and subsequent
* calls to the function accumulates the effect. For example, calling
* <b>shearY(PI/2)</b> and then <b>shearY(PI/2)</b> is the same as
* <b>shearY(PI)</b>. If <b>shearY()</b> is called within the
* <b>draw()</b>, the transformation is reset when the loop begins again.
* <br/> <br/>
* Technically, <b>shearY()</b> multiplies the current transformation
* matrix by a rotation matrix. This function can be further controlled by
* the <b>pushMatrix()</b> and <b>popMatrix()</b> functions.
*
* ( end auto-generated )
*
* @webref transform
* @param angle angle of shear specified in radians
* @see PGraphics#popMatrix()
* @see PGraphics#pushMatrix()
* @see PGraphics#shearX(float)
* @see PGraphics#scale(float, float, float)
* @see PGraphics#translate(float, float, float)
* @see PApplet#radians(float)
*/
public void shearY(float angle) {
showMissingWarning("shearY");
}
//////////////////////////////////////////////////////////////
// MATRIX FULL MONTY
/**
* ( begin auto-generated from resetMatrix.xml )
*
* Replaces the current matrix with the identity matrix. The equivalent
* function in OpenGL is glLoadIdentity().
*
* ( end auto-generated )
*
* @webref transform
* @see PGraphics#pushMatrix()
* @see PGraphics#popMatrix()
* @see PGraphics#applyMatrix(PMatrix)
* @see PGraphics#printMatrix()
*/
public void resetMatrix() {
showMethodWarning("resetMatrix");
}
/**
* ( begin auto-generated from applyMatrix.xml )
*
* Multiplies the current matrix by the one specified through the
* parameters. This is very slow because it will try to calculate the
* inverse of the transform, so avoid it whenever possible. The equivalent
* function in OpenGL is glMultMatrix().
*
* ( end auto-generated )
*
* @webref transform
* @source
* @see PGraphics#pushMatrix()
* @see PGraphics#popMatrix()
* @see PGraphics#resetMatrix()
* @see PGraphics#printMatrix()
*/
public void applyMatrix(PMatrix source) {
if (source instanceof PMatrix2D) {
applyMatrix((PMatrix2D) source);
} else if (source instanceof PMatrix3D) {
applyMatrix((PMatrix3D) source);
}
}
public void applyMatrix(PMatrix2D source) {
applyMatrix(source.m00, source.m01, source.m02,
source.m10, source.m11, source.m12);
}
/**
* @param n00 numbers which define the 4x4 matrix to be multiplied
* @param n01 numbers which define the 4x4 matrix to be multiplied
* @param n02 numbers which define the 4x4 matrix to be multiplied
* @param n10 numbers which define the 4x4 matrix to be multiplied
* @param n11 numbers which define the 4x4 matrix to be multiplied
* @param n12 numbers which define the 4x4 matrix to be multiplied
*/
public void applyMatrix(float n00, float n01, float n02,
float n10, float n11, float n12) {
showMissingWarning("applyMatrix");
}
public void applyMatrix(PMatrix3D source) {
applyMatrix(source.m00, source.m01, source.m02, source.m03,
source.m10, source.m11, source.m12, source.m13,
source.m20, source.m21, source.m22, source.m23,
source.m30, source.m31, source.m32, source.m33);
}
/**
* @param n03 numbers which define the 4x4 matrix to be multiplied
* @param n13 numbers which define the 4x4 matrix to be multiplied
* @param n20 numbers which define the 4x4 matrix to be multiplied
* @param n21 numbers which define the 4x4 matrix to be multiplied
* @param n22 numbers which define the 4x4 matrix to be multiplied
* @param n23 numbers which define the 4x4 matrix to be multiplied
* @param n30 numbers which define the 4x4 matrix to be multiplied
* @param n31 numbers which define the 4x4 matrix to be multiplied
* @param n32 numbers which define the 4x4 matrix to be multiplied
* @param n33 numbers which define the 4x4 matrix to be multiplied
*/
public void applyMatrix(float n00, float n01, float n02, float n03,
float n10, float n11, float n12, float n13,
float n20, float n21, float n22, float n23,
float n30, float n31, float n32, float n33) {
showMissingWarning("applyMatrix");
}
//////////////////////////////////////////////////////////////
// MATRIX GET/SET/PRINT
public PMatrix getMatrix() {
showMissingWarning("getMatrix");
return null;
}
/**
* Copy the current transformation matrix into the specified target.
* Pass in null to create a new matrix.
*/
public PMatrix2D getMatrix(PMatrix2D target) {
showMissingWarning("getMatrix");
return null;
}
/**
* Copy the current transformation matrix into the specified target.
* Pass in null to create a new matrix.
*/
public PMatrix3D getMatrix(PMatrix3D target) {
showMissingWarning("getMatrix");
return null;
}
/**
* Set the current transformation matrix to the contents of another.
*/
public void setMatrix(PMatrix source) {
if (source instanceof PMatrix2D) {
setMatrix((PMatrix2D) source);
} else if (source instanceof PMatrix3D) {
setMatrix((PMatrix3D) source);
}
}
/**
* Set the current transformation to the contents of the specified source.
*/
public void setMatrix(PMatrix2D source) {
showMissingWarning("setMatrix");
}
/**
* Set the current transformation to the contents of the specified source.
*/
public void setMatrix(PMatrix3D source) {
showMissingWarning("setMatrix");
}
/**
* ( begin auto-generated from printMatrix.xml )
*
* Prints the current matrix to the Console (the text window at the bottom
* of Processing).
*
* ( end auto-generated )
*
* @webref transform
* @see PGraphics#pushMatrix()
* @see PGraphics#popMatrix()
* @see PGraphics#resetMatrix()
* @see PGraphics#applyMatrix(PMatrix)
*/
public void printMatrix() {
showMethodWarning("printMatrix");
}
//////////////////////////////////////////////////////////////
// CAMERA
/**
* ( begin auto-generated from beginCamera.xml )
*
* The <b>beginCamera()</b> and <b>endCamera()</b> functions enable
* advanced customization of the camera space. The functions are useful if
* you want to more control over camera movement, however for most users,
* the <b>camera()</b> function will be sufficient.<br /><br />The camera
* functions will replace any transformations (such as <b>rotate()</b> or
* <b>translate()</b>) that occur before them in <b>draw()</b>, but they
* will not automatically replace the camera transform itself. For this
* reason, camera functions should be placed at the beginning of
* <b>draw()</b> (so that transformations happen afterwards), and the
* <b>camera()</b> function can be used after <b>beginCamera()</b> if you
* want to reset the camera before applying transformations.<br /><br
* />This function sets the matrix mode to the camera matrix so calls such
* as <b>translate()</b>, <b>rotate()</b>, applyMatrix() and resetMatrix()
* affect the camera. <b>beginCamera()</b> should always be used with a
* following <b>endCamera()</b> and pairs of <b>beginCamera()</b> and
* <b>endCamera()</b> cannot be nested.
*
* ( end auto-generated )
*
* @webref lights_camera:camera
* @see PGraphics#camera()
* @see PGraphics#endCamera()
* @see PGraphics#applyMatrix(PMatrix)
* @see PGraphics#resetMatrix()
* @see PGraphics#translate(float, float, float)
* @see PGraphics#scale(float, float, float)
*/
public void beginCamera() {
showMethodWarning("beginCamera");
}
/**
* ( begin auto-generated from endCamera.xml )
*
* The <b>beginCamera()</b> and <b>endCamera()</b> functions enable
* advanced customization of the camera space. Please see the reference for
* <b>beginCamera()</b> for a description of how the functions are used.
*
* ( end auto-generated )
*
* @webref lights_camera:camera
* @see PGraphics#camera(float, float, float, float, float, float, float, float, float)
*/
public void endCamera() {
showMethodWarning("endCamera");
}
/**
* ( begin auto-generated from camera.xml )
*
* Sets the position of the camera through setting the eye position, the
* center of the scene, and which axis is facing upward. Moving the eye
* position and the direction it is pointing (the center of the scene)
* allows the images to be seen from different angles. The version without
* any parameters sets the camera to the default position, pointing to the
* center of the display window with the Y axis as up. The default values
* are <b>camera(width/2.0, height/2.0, (height/2.0) / tan(PI*30.0 /
* 180.0), width/2.0, height/2.0, 0, 0, 1, 0)</b>. This function is similar
* to <b>gluLookAt()</b> in OpenGL, but it first clears the current camera settings.
*
* ( end auto-generated )
*
* @webref lights_camera:camera
* @see PGraphics#endCamera()
* @see PGraphics#frustum(float, float, float, float, float, float)
*/
public void camera() {
showMissingWarning("camera");
}
/**
* @param eyeX x-coordinate for the eye
* @param eyeY y-coordinate for the eye
* @param eyeZ z-coordinate for the eye
* @param centerX x-coordinate for the center of the scene
* @param centerY y-coordinate for the center of the scene
* @param centerZ z-coordinate for the center of the scene
* @param upX usually 0.0, 1.0, or -1.0
* @param upY usually 0.0, 1.0, or -1.0
* @param upZ usually 0.0, 1.0, or -1.0
*/
public void camera(float eyeX, float eyeY, float eyeZ,
float centerX, float centerY, float centerZ,
float upX, float upY, float upZ) {
showMissingWarning("camera");
}
/**
* ( begin auto-generated from printCamera.xml )
*
* Prints the current camera matrix to the Console (the text window at the
* bottom of Processing).
*
* ( end auto-generated )
* @webref lights_camera:camera
* @see PGraphics#camera(float, float, float, float, float, float, float, float, float)
*/
public void printCamera() {
showMethodWarning("printCamera");
}
//////////////////////////////////////////////////////////////
// PROJECTION
/**
* ( begin auto-generated from ortho.xml )
*
* Sets an orthographic projection and defines a parallel clipping volume.
* All objects with the same dimension appear the same size, regardless of
* whether they are near or far from the camera. The parameters to this
* function specify the clipping volume where left and right are the
* minimum and maximum x values, top and bottom are the minimum and maximum
* y values, and near and far are the minimum and maximum z values. If no
* parameters are given, the default is used: ortho(0, width, 0, height,
* -10, 10).
*
* ( end auto-generated )
*
* @webref lights_camera:camera
*/
public void ortho() {
showMissingWarning("ortho");
}
/**
* @param left left plane of the clipping volume
* @param right right plane of the clipping volume
* @param bottom bottom plane of the clipping volume
* @param top top plane of the clipping volume
*/
public void ortho(float left, float right,
float bottom, float top) {
showMissingWarning("ortho");
}
/**
* @param near maximum distance from the origin to the viewer
* @param far maximum distance from the origin away from the viewer
*/
public void ortho(float left, float right,
float bottom, float top,
float near, float far) {
showMissingWarning("ortho");
}
/**
* ( begin auto-generated from perspective.xml )
*
* Sets a perspective projection applying foreshortening, making distant
* objects appear smaller than closer ones. The parameters define a viewing
* volume with the shape of truncated pyramid. Objects near to the front of
* the volume appear their actual size, while farther objects appear
* smaller. This projection simulates the perspective of the world more
* accurately than orthographic projection. The version of perspective
* without parameters sets the default perspective and the version with
* four parameters allows the programmer to set the area precisely. The
* default values are: perspective(PI/3.0, width/height, cameraZ/10.0,
* cameraZ*10.0) where cameraZ is ((height/2.0) / tan(PI*60.0/360.0));
*
* ( end auto-generated )
*
* @webref lights_camera:camera
*/
public void perspective() {
showMissingWarning("perspective");
}
/**
* @param fovy field-of-view angle (in radians) for vertical direction
* @param aspect ratio of width to height
* @param zNear z-position of nearest clipping plane
* @param zFar z-position of farthest clipping plane
*/
public void perspective(float fovy, float aspect, float zNear, float zFar) {
showMissingWarning("perspective");
}
/**
* ( begin auto-generated from frustum.xml )
*
* Sets a perspective matrix defined through the parameters. Works like
* glFrustum, except it wipes out the current perspective matrix rather
* than muliplying itself with it.
*
* ( end auto-generated )
*
* @webref lights_camera:camera
* @param left left coordinate of the clipping plane
* @param right right coordinate of the clipping plane
* @param bottom bottom coordinate of the clipping plane
* @param top top coordinate of the clipping plane
* @param near near component of the clipping plane; must be greater than zero
* @param far far component of the clipping plane; must be greater than the near value
* @see PGraphics#camera(float, float, float, float, float, float, float, float, float)
* @see PGraphics#endCamera()
* @see PGraphics#perspective(float, float, float, float)
*/
public void frustum(float left, float right,
float bottom, float top,
float near, float far) {
showMethodWarning("frustum");
}
/**
* ( begin auto-generated from printProjection.xml )
*
* Prints the current projection matrix to the Console (the text window at
* the bottom of Processing).
*
* ( end auto-generated )
*
* @webref lights_camera:camera
* @see PGraphics#camera(float, float, float, float, float, float, float, float, float)
*/
public void printProjection() {
showMethodWarning("printCamera");
}
//////////////////////////////////////////////////////////////
// SCREEN TRANSFORMS
/**
* ( begin auto-generated from screenX.xml )
*
* Takes a three-dimensional X, Y, Z position and returns the X value for
* where it will appear on a (two-dimensional) screen.
*
* ( end auto-generated )
*
* @webref lights_camera:coordinates
* @param x 3D x-coordinate to be mapped
* @param y 3D y-coordinate to be mapped
* @see PGraphics#screenY(float, float, float)
* @see PGraphics#screenZ(float, float, float)
*/
public float screenX(float x, float y) {
showMissingWarning("screenX");
return 0;
}
/**
* ( begin auto-generated from screenY.xml )
*
* Takes a three-dimensional X, Y, Z position and returns the Y value for
* where it will appear on a (two-dimensional) screen.
*
* ( end auto-generated )
*
* @webref lights_camera:coordinates
* @param x 3D x-coordinate to be mapped
* @param y 3D y-coordinate to be mapped
* @see PGraphics#screenX(float, float, float)
* @see PGraphics#screenZ(float, float, float)
*/
public float screenY(float x, float y) {
showMissingWarning("screenY");
return 0;
}
/**
* @param z 3D z-coordinate to be mapped
*/
public float screenX(float x, float y, float z) {
showMissingWarning("screenX");
return 0;
}
/**
* @param z 3D z-coordinate to be mapped
*/
public float screenY(float x, float y, float z) {
showMissingWarning("screenY");
return 0;
}
/**
* ( begin auto-generated from screenZ.xml )
*
* Takes a three-dimensional X, Y, Z position and returns the Z value for
* where it will appear on a (two-dimensional) screen.
*
* ( end auto-generated )
*
* @webref lights_camera:coordinates
* @param x 3D x-coordinate to be mapped
* @param y 3D y-coordinate to be mapped
* @param z 3D z-coordinate to be mapped
* @see PGraphics#screenX(float, float, float)
* @see PGraphics#screenY(float, float, float)
*/
public float screenZ(float x, float y, float z) {
showMissingWarning("screenZ");
return 0;
}
/**
* ( begin auto-generated from modelX.xml )
*
* Returns the three-dimensional X, Y, Z position in model space. This
* returns the X value for a given coordinate based on the current set of
* transformations (scale, rotate, translate, etc.) The X value can be used
* to place an object in space relative to the location of the original
* point once the transformations are no longer in use.
* <br/> <br/>
* In the example, the <b>modelX()</b>, <b>modelY()</b>, and
* <b>modelZ()</b> functions record the location of a box in space after
* being placed using a series of translate and rotate commands. After
* popMatrix() is called, those transformations no longer apply, but the
* (x, y, z) coordinate returned by the model functions is used to place
* another box in the same location.
*
* ( end auto-generated )
*
* @webref lights_camera:coordinates
* @param x 3D x-coordinate to be mapped
* @param y 3D y-coordinate to be mapped
* @param z 3D z-coordinate to be mapped
* @see PGraphics#modelY(float, float, float)
* @see PGraphics#modelZ(float, float, float)
*/
public float modelX(float x, float y, float z) {
showMissingWarning("modelX");
return 0;
}
/**
* ( begin auto-generated from modelY.xml )
*
* Returns the three-dimensional X, Y, Z position in model space. This
* returns the Y value for a given coordinate based on the current set of
* transformations (scale, rotate, translate, etc.) The Y value can be used
* to place an object in space relative to the location of the original
* point once the transformations are no longer in use.<br />
* <br />
* In the example, the <b>modelX()</b>, <b>modelY()</b>, and
* <b>modelZ()</b> functions record the location of a box in space after
* being placed using a series of translate and rotate commands. After
* popMatrix() is called, those transformations no longer apply, but the
* (x, y, z) coordinate returned by the model functions is used to place
* another box in the same location.
*
* ( end auto-generated )
*
* @webref lights_camera:coordinates
* @param x 3D x-coordinate to be mapped
* @param y 3D y-coordinate to be mapped
* @param z 3D z-coordinate to be mapped
* @see PGraphics#modelX(float, float, float)
* @see PGraphics#modelZ(float, float, float)
*/
public float modelY(float x, float y, float z) {
showMissingWarning("modelY");
return 0;
}
/**
* ( begin auto-generated from modelZ.xml )
*
* Returns the three-dimensional X, Y, Z position in model space. This
* returns the Z value for a given coordinate based on the current set of
* transformations (scale, rotate, translate, etc.) The Z value can be used
* to place an object in space relative to the location of the original
* point once the transformations are no longer in use.<br />
* <br />
* In the example, the <b>modelX()</b>, <b>modelY()</b>, and
* <b>modelZ()</b> functions record the location of a box in space after
* being placed using a series of translate and rotate commands. After
* popMatrix() is called, those transformations no longer apply, but the
* (x, y, z) coordinate returned by the model functions is used to place
* another box in the same location.
*
* ( end auto-generated )
*
* @webref lights_camera:coordinates
* @param x 3D x-coordinate to be mapped
* @param y 3D y-coordinate to be mapped
* @param z 3D z-coordinate to be mapped
* @see PGraphics#modelX(float, float, float)
* @see PGraphics#modelY(float, float, float)
*/
public float modelZ(float x, float y, float z) {
showMissingWarning("modelZ");
return 0;
}
//////////////////////////////////////////////////////////////
// STYLE
/**
* ( begin auto-generated from pushStyle.xml )
*
* The <b>pushStyle()</b> function saves the current style settings and
* <b>popStyle()</b> restores the prior settings. Note that these functions
* are always used together. They allow you to change the style settings
* and later return to what you had. When a new style is started with
* <b>pushStyle()</b>, it builds on the current style information. The
* <b>pushStyle()</b> and <b>popStyle()</b> functions can be embedded to
* provide more control (see the second example above for a demonstration.)
* <br /><br />
* The style information controlled by the following functions are included
* in the style:
* fill(), stroke(), tint(), strokeWeight(), strokeCap(), strokeJoin(),
* imageMode(), rectMode(), ellipseMode(), shapeMode(), colorMode(),
* textAlign(), textFont(), textMode(), textSize(), textLeading(),
* emissive(), specular(), shininess(), ambient()
*
* ( end auto-generated )
*
* @webref structure
* @see PGraphics#popStyle()
*/
public void pushStyle() {
if (styleStackDepth == styleStack.length) {
styleStack = (PStyle[]) PApplet.expand(styleStack);
}
if (styleStack[styleStackDepth] == null) {
styleStack[styleStackDepth] = new PStyle();
}
PStyle s = styleStack[styleStackDepth++];
getStyle(s);
}
/**
* ( begin auto-generated from popStyle.xml )
*
* The <b>pushStyle()</b> function saves the current style settings and
* <b>popStyle()</b> restores the prior settings; these functions are
* always used together. They allow you to change the style settings and
* later return to what you had. When a new style is started with
* <b>pushStyle()</b>, it builds on the current style information. The
* <b>pushStyle()</b> and <b>popStyle()</b> functions can be embedded to
* provide more control (see the second example above for a demonstration.)
*
* ( end auto-generated )
*
* @webref structure
* @see PGraphics#pushStyle()
*/
public void popStyle() {
if (styleStackDepth == 0) {
throw new RuntimeException("Too many popStyle() without enough pushStyle()");
}
styleStackDepth--;
style(styleStack[styleStackDepth]);
}
public void style(PStyle s) {
// if (s.smooth) {
// smooth();
// } else {
// noSmooth();
// }
imageMode(s.imageMode);
rectMode(s.rectMode);
ellipseMode(s.ellipseMode);
shapeMode(s.shapeMode);
if (s.tint) {
tint(s.tintColor);
} else {
noTint();
}
if (s.fill) {
fill(s.fillColor);
} else {
noFill();
}
if (s.stroke) {
stroke(s.strokeColor);
} else {
noStroke();
}
strokeWeight(s.strokeWeight);
strokeCap(s.strokeCap);
strokeJoin(s.strokeJoin);
// Set the colorMode() for the material properties.
// TODO this is really inefficient, need to just have a material() method,
// but this has the least impact to the API.
colorMode(RGB, 1);
ambient(s.ambientR, s.ambientG, s.ambientB);
emissive(s.emissiveR, s.emissiveG, s.emissiveB);
specular(s.specularR, s.specularG, s.specularB);
shininess(s.shininess);
/*
s.ambientR = ambientR;
s.ambientG = ambientG;
s.ambientB = ambientB;
s.specularR = specularR;
s.specularG = specularG;
s.specularB = specularB;
s.emissiveR = emissiveR;
s.emissiveG = emissiveG;
s.emissiveB = emissiveB;
s.shininess = shininess;
*/
// material(s.ambientR, s.ambientG, s.ambientB,
// s.emissiveR, s.emissiveG, s.emissiveB,
// s.specularR, s.specularG, s.specularB,
// s.shininess);
// Set this after the material properties.
colorMode(s.colorMode,
s.colorModeX, s.colorModeY, s.colorModeZ, s.colorModeA);
// This is a bit asymmetric, since there's no way to do "noFont()",
// and a null textFont will produce an error (since usually that means that
// the font couldn't load properly). So in some cases, the font won't be
// 'cleared' to null, even though that's technically correct.
if (s.textFont != null) {
textFont(s.textFont, s.textSize);
textLeading(s.textLeading);
}
// These don't require a font to be set.
textAlign(s.textAlign, s.textAlignY);
textMode(s.textMode);
}
public PStyle getStyle() { // ignore
return getStyle(null);
}
public PStyle getStyle(PStyle s) { // ignore
if (s == null) {
s = new PStyle();
}
s.imageMode = imageMode;
s.rectMode = rectMode;
s.ellipseMode = ellipseMode;
s.shapeMode = shapeMode;
s.colorMode = colorMode;
s.colorModeX = colorModeX;
s.colorModeY = colorModeY;
s.colorModeZ = colorModeZ;
s.colorModeA = colorModeA;
s.tint = tint;
s.tintColor = tintColor;
s.fill = fill;
s.fillColor = fillColor;
s.stroke = stroke;
s.strokeColor = strokeColor;
s.strokeWeight = strokeWeight;
s.strokeCap = strokeCap;
s.strokeJoin = strokeJoin;
s.ambientR = ambientR;
s.ambientG = ambientG;
s.ambientB = ambientB;
s.specularR = specularR;
s.specularG = specularG;
s.specularB = specularB;
s.emissiveR = emissiveR;
s.emissiveG = emissiveG;
s.emissiveB = emissiveB;
s.shininess = shininess;
s.textFont = textFont;
s.textAlign = textAlign;
s.textAlignY = textAlignY;
s.textMode = textMode;
s.textSize = textSize;
s.textLeading = textLeading;
return s;
}
//////////////////////////////////////////////////////////////
// STROKE CAP/JOIN/WEIGHT
/**
* ( begin auto-generated from strokeWeight.xml )
*
* Sets the width of the stroke used for lines, points, and the border
* around shapes. All widths are set in units of pixels.
* <br/> <br/>
* When drawing with P3D, series of connected lines (such as the stroke
* around a polygon, triangle, or ellipse) produce unattractive results
* when a thick stroke weight is set (<a
* href="http://code.google.com/p/processing/issues/detail?id=123">see
* Issue 123</a>). With P3D, the minimum and maximum values for
* <b>strokeWeight()</b> are controlled by the graphics card and the
* operating system's OpenGL implementation. For instance, the thickness
* may not go higher than 10 pixels.
*
* ( end auto-generated )
*
* @webref shape:attributes
* @param weight the weight (in pixels) of the stroke
* @see PGraphics#stroke(int, float)
* @see PGraphics#strokeJoin(int)
* @see PGraphics#strokeCap(int)
*/
public void strokeWeight(float weight) {
strokeWeight = weight;
}
/**
* ( begin auto-generated from strokeJoin.xml )
*
* Sets the style of the joints which connect line segments. These joints
* are either mitered, beveled, or rounded and specified with the
* corresponding parameters MITER, BEVEL, and ROUND. The default joint is
* MITER.
* <br/> <br/>
* This function is not available with the P3D renderer, (<a
* href="http://code.google.com/p/processing/issues/detail?id=123">see
* Issue 123</a>). More information about the renderers can be found in the
* <b>size()</b> reference.
*
* ( end auto-generated )
*
* @webref shape:attributes
* @param join either MITER, BEVEL, ROUND
* @see PGraphics#stroke(int, float)
* @see PGraphics#strokeWeight(float)
* @see PGraphics#strokeCap(int)
*/
public void strokeJoin(int join) {
strokeJoin = join;
}
/**
* ( begin auto-generated from strokeCap.xml )
*
* Sets the style for rendering line endings. These ends are either
* squared, extended, or rounded and specified with the corresponding
* parameters SQUARE, PROJECT, and ROUND. The default cap is ROUND.
* <br/> <br/>
* This function is not available with the P3D renderer (<a
* href="http://code.google.com/p/processing/issues/detail?id=123">see
* Issue 123</a>). More information about the renderers can be found in the
* <b>size()</b> reference.
*
* ( end auto-generated )
*
* @webref shape:attributes
* @param cap either SQUARE, PROJECT, or ROUND
* @see PGraphics#stroke(int, float)
* @see PGraphics#strokeWeight(float)
* @see PGraphics#strokeJoin(int)
* @see PApplet#size(int, int, String, String)
*/
public void strokeCap(int cap) {
strokeCap = cap;
}
//////////////////////////////////////////////////////////////
// STROKE COLOR
/**
* ( begin auto-generated from noStroke.xml )
*
* Disables drawing the stroke (outline). If both <b>noStroke()</b> and
* <b>noFill()</b> are called, nothing will be drawn to the screen.
*
* ( end auto-generated )
*
* @webref color:setting
* @see PGraphics#stroke(float, float, float, float)
*/
public void noStroke() {
stroke = false;
}
/**
* ( begin auto-generated from stroke.xml )
*
* Sets the color used to draw lines and borders around shapes. This color
* is either specified in terms of the RGB or HSB color depending on the
* current <b>colorMode()</b> (the default color space is RGB, with each
* value in the range from 0 to 255).
* <br/> <br/>
* When using hexadecimal notation to specify a color, use "#" or "0x"
* before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six
* digits to specify a color (the way colors are specified in HTML and
* CSS). When using the hexadecimal notation starting with "0x", the
* hexadecimal value must be specified with eight characters; the first two
* characters define the alpha component and the remainder the red, green,
* and blue components.
* <br/> <br/>
* The value for the parameter "gray" must be less than or equal to the
* current maximum value as specified by <b>colorMode()</b>. The default
* maximum value is 255.
*
* ( end auto-generated )
*
* @param rgb color value in hexadecimal notation
* @see PGraphics#noStroke()
* @see PGraphics#fill(int, float)
* @see PGraphics#tint(int, float)
* @see PGraphics#background(float, float, float, float)
* @see PGraphics#colorMode(int, float, float, float, float)
*/
public void stroke(int rgb) {
colorCalc(rgb);
strokeFromCalc();
}
/**
* @param alpha opacity of the stroke
*/
public void stroke(int rgb, float alpha) {
colorCalc(rgb, alpha);
strokeFromCalc();
}
/**
* @param gray specifies a value between white and black
*/
public void stroke(float gray) {
colorCalc(gray);
strokeFromCalc();
}
public void stroke(float gray, float alpha) {
colorCalc(gray, alpha);
strokeFromCalc();
}
/**
* @param v1 red or hue value (depending on current color mode)
* @param v2 green or saturation value (depending on current color mode)
* @param v3 blue or brightness value (depending on current color mode)
* @webref color:setting
*/
public void stroke(float v1, float v2, float v3) {
colorCalc(v1, v2, v3);
strokeFromCalc();
}
public void stroke(float v1, float v2, float v3, float alpha) {
colorCalc(v1, v2, v3, alpha);
strokeFromCalc();
}
protected void strokeFromCalc() {
stroke = true;
strokeR = calcR;
strokeG = calcG;
strokeB = calcB;
strokeA = calcA;
strokeRi = calcRi;
strokeGi = calcGi;
strokeBi = calcBi;
strokeAi = calcAi;
strokeColor = calcColor;
strokeAlpha = calcAlpha;
}
//////////////////////////////////////////////////////////////
// TINT COLOR
/**
* ( begin auto-generated from noTint.xml )
*
* Removes the current fill value for displaying images and reverts to
* displaying images with their original hues.
*
* ( end auto-generated )
*
* @webref image:loading_displaying
* @usage web_application
* @see PGraphics#tint(float, float, float, float)
* @see PGraphics#image(PImage, float, float, float, float)
*/
public void noTint() {
tint = false;
}
/**
* ( begin auto-generated from tint.xml )
*
* Sets the fill value for displaying images. Images can be tinted to
* specified colors or made transparent by setting the alpha.<br />
* <br />
* To make an image transparent, but not change it's color, use white as
* the tint color and specify an alpha value. For instance, tint(255, 128)
* will make an image 50% transparent (unless <b>colorMode()</b> has been
* used).<br />
* <br />
* When using hexadecimal notation to specify a color, use "#" or "0x"
* before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six
* digits to specify a color (the way colors are specified in HTML and
* CSS). When using the hexadecimal notation starting with "0x", the
* hexadecimal value must be specified with eight characters; the first two
* characters define the alpha component and the remainder the red, green,
* and blue components.<br />
* <br />
* The value for the parameter "gray" must be less than or equal to the
* current maximum value as specified by <b>colorMode()</b>. The default
* maximum value is 255.<br />
* <br />
* The <b>tint()</b> function is also used to control the coloring of
* textures in 3D.
*
* ( end auto-generated )
*
* @webref image:loading_displaying
* @usage web_application
* @param rgb color value in hexadecimal notation
* @see PGraphics#noTint()
* @see PGraphics#image(PImage, float, float, float, float)
*/
public void tint(int rgb) {
colorCalc(rgb);
tintFromCalc();
}
/**
* @param alpha opacity of the image
*/
public void tint(int rgb, float alpha) {
colorCalc(rgb, alpha);
tintFromCalc();
}
/**
* @param gray specifies a value between white and black
*/
public void tint(float gray) {
colorCalc(gray);
tintFromCalc();
}
public void tint(float gray, float alpha) {
colorCalc(gray, alpha);
tintFromCalc();
}
/**
* @param v1 red or hue value (depending on current color mode)
* @param v2 green or saturation value (depending on current color mode)
* @param v3 blue or brightness value (depending on current color mode)
*/
public void tint(float v1, float v2, float v3) {
colorCalc(v1, v2, v3);
tintFromCalc();
}
public void tint(float v1, float v2, float v3, float alpha) {
colorCalc(v1, v2, v3, alpha);
tintFromCalc();
}
protected void tintFromCalc() {
tint = true;
tintR = calcR;
tintG = calcG;
tintB = calcB;
tintA = calcA;
tintRi = calcRi;
tintGi = calcGi;
tintBi = calcBi;
tintAi = calcAi;
tintColor = calcColor;
tintAlpha = calcAlpha;
}
//////////////////////////////////////////////////////////////
// FILL COLOR
/**
* ( begin auto-generated from noFill.xml )
*
* Disables filling geometry. If both <b>noStroke()</b> and <b>noFill()</b>
* are called, nothing will be drawn to the screen.
*
* ( end auto-generated )
*
* @webref color:setting
* @usage web_application
* @see PGraphics#fill(float, float, float, float)
*/
public void noFill() {
fill = false;
}
/**
* ( begin auto-generated from fill.xml )
*
* Sets the color used to fill shapes. For example, if you run <b>fill(204,
* 102, 0)</b>, all subsequent shapes will be filled with orange. This
* color is either specified in terms of the RGB or HSB color depending on
* the current <b>colorMode()</b> (the default color space is RGB, with
* each value in the range from 0 to 255).
* <br/> <br/>
* When using hexadecimal notation to specify a color, use "#" or "0x"
* before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six
* digits to specify a color (the way colors are specified in HTML and
* CSS). When using the hexadecimal notation starting with "0x", the
* hexadecimal value must be specified with eight characters; the first two
* characters define the alpha component and the remainder the red, green,
* and blue components.
* <br/> <br/>
* The value for the parameter "gray" must be less than or equal to the
* current maximum value as specified by <b>colorMode()</b>. The default
* maximum value is 255.
* <br/> <br/>
* To change the color of an image (or a texture), use tint().
*
* ( end auto-generated )
*
* @webref color:setting
* @usage web_application
* @param rgb color variable or hex value
* @see PGraphics#noFill()
* @see PGraphics#stroke(int, float)
* @see PGraphics#tint(int, float)
* @see PGraphics#background(float, float, float, float)
* @see PGraphics#colorMode(int, float, float, float, float)
*/
public void fill(int rgb) {
colorCalc(rgb);
fillFromCalc();
}
/**
* @param alpha opacity of the fill
*/
public void fill(int rgb, float alpha) {
colorCalc(rgb, alpha);
fillFromCalc();
}
/**
* @param gray number specifying value between white and black
*/
public void fill(float gray) {
colorCalc(gray);
fillFromCalc();
}
public void fill(float gray, float alpha) {
colorCalc(gray, alpha);
fillFromCalc();
}
/**
* @param v1 red or hue value (depending on current color mode)
* @param v2 green or saturation value (depending on current color mode)
* @param v3 blue or brightness value (depending on current color mode)
*/
public void fill(float v1, float v2, float v3) {
colorCalc(v1, v2, v3);
fillFromCalc();
}
public void fill(float v1, float v2, float v3, float alpha) {
colorCalc(v1, v2, v3, alpha);
fillFromCalc();
}
protected void fillFromCalc() {
fill = true;
fillR = calcR;
fillG = calcG;
fillB = calcB;
fillA = calcA;
fillRi = calcRi;
fillGi = calcGi;
fillBi = calcBi;
fillAi = calcAi;
fillColor = calcColor;
fillAlpha = calcAlpha;
}
//////////////////////////////////////////////////////////////
// MATERIAL PROPERTIES
/**
* ( begin auto-generated from ambient.xml )
*
* Sets the ambient reflectance for shapes drawn to the screen. This is
* combined with the ambient light component of environment. The color
* components set through the parameters define the reflectance. For
* example in the default color mode, setting v1=255, v2=126, v3=0, would
* cause all the red light to reflect and half of the green light to
* reflect. Used in combination with <b>emissive()</b>, <b>specular()</b>,
* and <b>shininess()</b> in setting the material properties of shapes.
*
* ( end auto-generated )
*
* @webref lights_camera:material_properties
* @usage web_application
* @param rgb any value of the color datatype
* @see PGraphics#emissive(float, float, float)
* @see PGraphics#specular(float, float, float)
* @see PGraphics#shininess(float)
*/
public void ambient(int rgb) {
// if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) {
// ambient((float) rgb);
//
// } else {
// colorCalcARGB(rgb, colorModeA);
// ambientFromCalc();
// }
colorCalc(rgb);
ambientFromCalc();
}
/**
* @param gray number specifying value between white and black
*/
public void ambient(float gray) {
colorCalc(gray);
ambientFromCalc();
}
/**
* @param v1 red or hue value (depending on current color mode)
* @param v2 green or saturation value (depending on current color mode)
* @param v3 blue or brightness value (depending on current color mode)
*/
public void ambient(float v1, float v2, float v3) {
colorCalc(v1, v2, v3);
ambientFromCalc();
}
protected void ambientFromCalc() {
ambientColor = calcColor;
ambientR = calcR;
ambientG = calcG;
ambientB = calcB;
setAmbient = true;
}
/**
* ( begin auto-generated from specular.xml )
*
* Sets the specular color of the materials used for shapes drawn to the
* screen, which sets the color of hightlights. Specular refers to light
* which bounces off a surface in a perferred direction (rather than
* bouncing in all directions like a diffuse light). Used in combination
* with <b>emissive()</b>, <b>ambient()</b>, and <b>shininess()</b> in
* setting the material properties of shapes.
*
* ( end auto-generated )
*
* @webref lights_camera:material_properties
* @usage web_application
* @param rgb color to set
* @see PGraphics#lightSpecular(float, float, float)
* @see PGraphics#ambient(float, float, float)
* @see PGraphics#emissive(float, float, float)
* @see PGraphics#shininess(float)
*/
public void specular(int rgb) {
// if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) {
// specular((float) rgb);
//
// } else {
// colorCalcARGB(rgb, colorModeA);
// specularFromCalc();
// }
colorCalc(rgb);
specularFromCalc();
}
/**
* gray number specifying value between white and black
*/
public void specular(float gray) {
colorCalc(gray);
specularFromCalc();
}
/**
* @param v1 red or hue value (depending on current color mode)
* @param v2 green or saturation value (depending on current color mode)
* @param v3 blue or brightness value (depending on current color mode)
*/
public void specular(float v1, float v2, float v3) {
colorCalc(v1, v2, v3);
specularFromCalc();
}
protected void specularFromCalc() {
specularColor = calcColor;
specularR = calcR;
specularG = calcG;
specularB = calcB;
}
/**
* ( begin auto-generated from shininess.xml )
*
* Sets the amount of gloss in the surface of shapes. Used in combination
* with <b>ambient()</b>, <b>specular()</b>, and <b>emissive()</b> in
* setting the material properties of shapes.
*
* ( end auto-generated )
*
* @webref lights_camera:material_properties
* @usage web_application
* @param shine degree of shininess
* @see PGraphics#emissive(float, float, float)
* @see PGraphics#ambient(float, float, float)
* @see PGraphics#specular(float, float, float)
*/
public void shininess(float shine) {
shininess = shine;
}
/**
* ( begin auto-generated from emissive.xml )
*
* Sets the emissive color of the material used for drawing shapes drawn to
* the screen. Used in combination with <b>ambient()</b>,
* <b>specular()</b>, and <b>shininess()</b> in setting the material
* properties of shapes.
*
* ( end auto-generated )
*
* @webref lights_camera:material_properties
* @usage web_application
* @param rgb color to set
* @see PGraphics#ambient(float, float, float)
* @see PGraphics#specular(float, float, float)
* @see PGraphics#shininess(float)
*/
public void emissive(int rgb) {
// if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) {
// emissive((float) rgb);
//
// } else {
// colorCalcARGB(rgb, colorModeA);
// emissiveFromCalc();
// }
colorCalc(rgb);
emissiveFromCalc();
}
/**
* gray number specifying value between white and black
*/
public void emissive(float gray) {
colorCalc(gray);
emissiveFromCalc();
}
/**
* @param v1 red or hue value (depending on current color mode)
* @param v2 green or saturation value (depending on current color mode)
* @param v3 blue or brightness value (depending on current color mode)
*/
public void emissive(float v1, float v2, float v3) {
colorCalc(v1, v2, v3);
emissiveFromCalc();
}
protected void emissiveFromCalc() {
emissiveColor = calcColor;
emissiveR = calcR;
emissiveG = calcG;
emissiveB = calcB;
}
//////////////////////////////////////////////////////////////
// LIGHTS
// The details of lighting are very implementation-specific, so this base
// class does not handle any details of settings lights. It does however
// display warning messages that the functions are not available.
/**
* ( begin auto-generated from lights.xml )
*
* Sets the default ambient light, directional light, falloff, and specular
* values. The defaults are ambientLight(128, 128, 128) and
* directionalLight(128, 128, 128, 0, 0, -1), lightFalloff(1, 0, 0), and
* lightSpecular(0, 0, 0). Lights need to be included in the draw() to
* remain persistent in a looping program. Placing them in the setup() of a
* looping program will cause them to only have an effect the first time
* through the loop.
*
* ( end auto-generated )
*
* @webref lights_camera:lights
* @usage web_application
* @see PGraphics#ambientLight(float, float, float, float, float, float)
* @see PGraphics#directionalLight(float, float, float, float, float, float)
* @see PGraphics#pointLight(float, float, float, float, float, float)
* @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#noLights()
*/
public void lights() {
showMethodWarning("lights");
}
/**
* ( begin auto-generated from noLights.xml )
*
* Disable all lighting. Lighting is turned off by default and enabled with
* the <b>lights()</b> function. This function can be used to disable
* lighting so that 2D geometry (which does not require lighting) can be
* drawn after a set of lighted 3D geometry.
*
* ( end auto-generated )
*
* @webref lights_camera:lights
* @usage web_application
* @see PGraphics#lights()
*/
public void noLights() {
showMethodWarning("noLights");
}
/**
* ( begin auto-generated from ambientLight.xml )
*
* Adds an ambient light. Ambient light doesn't come from a specific
* direction, the rays have light have bounced around so much that objects
* are evenly lit from all sides. Ambient lights are almost always used in
* combination with other types of lights. Lights need to be included in
* the <b>draw()</b> to remain persistent in a looping program. Placing
* them in the <b>setup()</b> of a looping program will cause them to only
* have an effect the first time through the loop. The effect of the
* parameters is determined by the current color mode.
*
* ( end auto-generated )
*
* @webref lights_camera:lights
* @usage web_application
* @param v1 red or hue value (depending on current color mode)
* @param v2 green or saturation value (depending on current color mode)
* @param v3 blue or brightness value (depending on current color mode)
* @see PGraphics#lights()
* @see PGraphics#directionalLight(float, float, float, float, float, float)
* @see PGraphics#pointLight(float, float, float, float, float, float)
* @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float)
*/
public void ambientLight(float v1, float v2, float v3) {
showMethodWarning("ambientLight");
}
/**
* @param x x-coordinate of the light
* @param y y-coordinate of the light
* @param z z-coordinate of the light
*/
public void ambientLight(float v1, float v2, float v3,
float x, float y, float z) {
showMethodWarning("ambientLight");
}
/**
* ( begin auto-generated from directionalLight.xml )
*
* Adds a directional light. Directional light comes from one direction and
* is stronger when hitting a surface squarely and weaker if it hits at a a
* gentle angle. After hitting a surface, a directional lights scatters in
* all directions. Lights need to be included in the <b>draw()</b> to
* remain persistent in a looping program. Placing them in the
* <b>setup()</b> of a looping program will cause them to only have an
* effect the first time through the loop. The affect of the <b>v1</b>,
* <b>v2</b>, and <b>v3</b> parameters is determined by the current color
* mode. The <b>nx</b>, <b>ny</b>, and <b>nz</b> parameters specify the
* direction the light is facing. For example, setting <b>ny</b> to -1 will
* cause the geometry to be lit from below (the light is facing directly upward).
*
* ( end auto-generated )
*
* @webref lights_camera:lights
* @usage web_application
* @param v1 red or hue value (depending on current color mode)
* @param v2 green or saturation value (depending on current color mode)
* @param v3 blue or brightness value (depending on current color mode)
* @param nx direction along the x-axis
* @param ny direction along the y-axis
* @param nz direction along the z-axis
* @see PGraphics#lights()
* @see PGraphics#ambientLight(float, float, float, float, float, float)
* @see PGraphics#pointLight(float, float, float, float, float, float)
* @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float)
*/
public void directionalLight(float v1, float v2, float v3,
float nx, float ny, float nz) {
showMethodWarning("directionalLight");
}
/**
* ( begin auto-generated from pointLight.xml )
*
* Adds a point light. Lights need to be included in the <b>draw()</b> to
* remain persistent in a looping program. Placing them in the
* <b>setup()</b> of a looping program will cause them to only have an
* effect the first time through the loop. The affect of the <b>v1</b>,
* <b>v2</b>, and <b>v3</b> parameters is determined by the current color
* mode. The <b>x</b>, <b>y</b>, and <b>z</b> parameters set the position
* of the light.
*
* ( end auto-generated )
*
* @webref lights_camera:lights
* @usage web_application
* @param v1 red or hue value (depending on current color mode)
* @param v2 green or saturation value (depending on current color mode)
* @param v3 blue or brightness value (depending on current color mode)
* @param x x-coordinate of the light
* @param y y-coordinate of the light
* @param z z-coordinate of the light
* @see PGraphics#lights()
* @see PGraphics#directionalLight(float, float, float, float, float, float)
* @see PGraphics#ambientLight(float, float, float, float, float, float)
* @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float)
*/
public void pointLight(float v1, float v2, float v3,
float x, float y, float z) {
showMethodWarning("pointLight");
}
/**
* ( begin auto-generated from spotLight.xml )
*
* Adds a spot light. Lights need to be included in the <b>draw()</b> to
* remain persistent in a looping program. Placing them in the
* <b>setup()</b> of a looping program will cause them to only have an
* effect the first time through the loop. The affect of the <b>v1</b>,
* <b>v2</b>, and <b>v3</b> parameters is determined by the current color
* mode. The <b>x</b>, <b>y</b>, and <b>z</b> parameters specify the
* position of the light and <b>nx</b>, <b>ny</b>, <b>nz</b> specify the
* direction or light. The <b>angle</b> parameter affects angle of the
* spotlight cone.
*
* ( end auto-generated )
*
* @webref lights_camera:lights
* @usage web_application
* @param v1 red or hue value (depending on current color mode)
* @param v2 green or saturation value (depending on current color mode)
* @param v3 blue or brightness value (depending on current color mode)
* @param x x-coordinate of the light
* @param y y-coordinate of the light
* @param z z-coordinate of the light
* @param nx direction along the x axis
* @param ny direction along the y axis
* @param nz direction along the z axis
* @param angle angle of the spotlight cone
* @param concentration exponent determining the center bias of the cone
* @see PGraphics#lights()
* @see PGraphics#directionalLight(float, float, float, float, float, float)
* @see PGraphics#pointLight(float, float, float, float, float, float)
* @see PGraphics#ambientLight(float, float, float, float, float, float)
*/
public void spotLight(float v1, float v2, float v3,
float x, float y, float z,
float nx, float ny, float nz,
float angle, float concentration) {
showMethodWarning("spotLight");
}
/**
* ( begin auto-generated from lightFalloff.xml )
*
* Sets the falloff rates for point lights, spot lights, and ambient
* lights. The parameters are used to determine the falloff with the
* following equation:<br /><br />d = distance from light position to
* vertex position<br />falloff = 1 / (CONSTANT + d * LINEAR + (d*d) *
* QUADRATIC)<br /><br />Like <b>fill()</b>, it affects only the elements
* which are created after it in the code. The default value if
* <b>LightFalloff(1.0, 0.0, 0.0)</b>. Thinking about an ambient light with
* a falloff can be tricky. It is used, for example, if you wanted a region
* of your scene to be lit ambiently one color and another region to be lit
* ambiently by another color, you would use an ambient light with location
* and falloff. You can think of it as a point light that doesn't care
* which direction a surface is facing.
*
* ( end auto-generated )
*
* @webref lights_camera:lights
* @usage web_application
* @param constant constant value or determining falloff
* @param linear linear value for determining falloff
* @param quadratic quadratic value for determining falloff
* @see PGraphics#lights()
* @see PGraphics#ambientLight(float, float, float, float, float, float)
* @see PGraphics#pointLight(float, float, float, float, float, float)
* @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#lightSpecular(float, float, float)
*/
public void lightFalloff(float constant, float linear, float quadratic) {
showMethodWarning("lightFalloff");
}
/**
* ( begin auto-generated from lightSpecular.xml )
*
* Sets the specular color for lights. Like <b>fill()</b>, it affects only
* the elements which are created after it in the code. Specular refers to
* light which bounces off a surface in a perferred direction (rather than
* bouncing in all directions like a diffuse light) and is used for
* creating highlights. The specular quality of a light interacts with the
* specular material qualities set through the <b>specular()</b> and
* <b>shininess()</b> functions.
*
* ( end auto-generated )
*
* @webref lights_camera:lights
* @usage web_application
* @param v1 red or hue value (depending on current color mode)
* @param v2 green or saturation value (depending on current color mode)
* @param v3 blue or brightness value (depending on current color mode)
* @see PGraphics#specular(float, float, float)
* @see PGraphics#lights()
* @see PGraphics#ambientLight(float, float, float, float, float, float)
* @see PGraphics#pointLight(float, float, float, float, float, float)
* @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float)
*/
public void lightSpecular(float v1, float v2, float v3) {
showMethodWarning("lightSpecular");
}
//////////////////////////////////////////////////////////////
// BACKGROUND
/**
* ( begin auto-generated from background.xml )
*
* The <b>background()</b> function sets the color used for the background
* of the Processing window. The default background is light gray. In the
* <b>draw()</b> function, the background color is used to clear the
* display window at the beginning of each frame.
* <br/> <br/>
* An image can also be used as the background for a sketch, however its
* width and height must be the same size as the sketch window. To resize
* an image 'b' to the size of the sketch window, use b.resize(width, height).
* <br/> <br/>
* Images used as background will ignore the current <b>tint()</b> setting.
* <br/> <br/>
* It is not possible to use transparency (alpha) in background colors with
* the main drawing surface, however they will work properly with <b>createGraphics()</b>.
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* <p>Clear the background with a color that includes an alpha value. This can
* only be used with objects created by createGraphics(), because the main
* drawing surface cannot be set transparent.</p>
* <p>It might be tempting to use this function to partially clear the screen
* on each frame, however that's not how this function works. When calling
* background(), the pixels will be replaced with pixels that have that level
* of transparency. To do a semi-transparent overlay, use fill() with alpha
* and draw a rectangle.</p>
*
* @webref color:setting
* @usage web_application
* @param rgb any value of the color datatype
* @see PGraphics#stroke(float)
* @see PGraphics#fill(float)
* @see PGraphics#tint(float)
* @see PGraphics#colorMode(int)
*/
public void background(int rgb) {
// if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) {
// background((float) rgb);
//
// } else {
// if (format == RGB) {
// rgb |= 0xff000000; // ignore alpha for main drawing surface
// }
// colorCalcARGB(rgb, colorModeA);
// backgroundFromCalc();
// backgroundImpl();
// }
colorCalc(rgb);
backgroundFromCalc();
}
/**
* @param alpha opacity of the background
*/
public void background(int rgb, float alpha) {
// if (format == RGB) {
// background(rgb); // ignore alpha for main drawing surface
//
// } else {
// if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) {
// background((float) rgb, alpha);
//
// } else {
// colorCalcARGB(rgb, alpha);
// backgroundFromCalc();
// backgroundImpl();
// }
// }
colorCalc(rgb, alpha);
backgroundFromCalc();
}
/**
* @param gray specifies a value between white and black
*/
public void background(float gray) {
colorCalc(gray);
backgroundFromCalc();
// backgroundImpl();
}
public void background(float gray, float alpha) {
if (format == RGB) {
background(gray); // ignore alpha for main drawing surface
} else {
colorCalc(gray, alpha);
backgroundFromCalc();
// backgroundImpl();
}
}
/**
* @param v1 red or hue value (depending on the current color mode)
* @param v2 green or saturation value (depending on the current color mode)
* @param v3 blue or brightness value (depending on the current color mode)
*/
public void background(float v1, float v2, float v3) {
colorCalc(v1, v2, v3);
backgroundFromCalc();
// backgroundImpl();
}
public void background(float v1, float v2, float v3, float alpha) {
// if (format == RGB) {
// background(x, y, z); // don't allow people to set alpha
//
// } else {
// colorCalc(x, y, z, a);
// backgroundFromCalc();
// backgroundImpl();
// }
colorCalc(v1, v2, v3, alpha);
backgroundFromCalc();
}
protected void backgroundFromCalc() {
backgroundR = calcR;
backgroundG = calcG;
backgroundB = calcB;
backgroundA = (format == RGB) ? colorModeA : calcA;
backgroundRi = calcRi;
backgroundGi = calcGi;
backgroundBi = calcBi;
backgroundAi = (format == RGB) ? 255 : calcAi;
backgroundAlpha = (format == RGB) ? false : calcAlpha;
backgroundColor = calcColor;
backgroundImpl();
}
/**
* Takes an RGB or ARGB image and sets it as the background.
* The width and height of the image must be the same size as the sketch.
* Use image.resize(width, height) to make short work of such a task.<br/>
* <br/>
* Note that even if the image is set as RGB, the high 8 bits of each pixel
* should be set opaque (0xFF000000) because the image data will be copied
* directly to the screen, and non-opaque background images may have strange
* behavior. Use image.filter(OPAQUE) to handle this easily.<br/>
* <br/>
* When using 3D, this will also clear the zbuffer (if it exists).
*
* @param image PImage to set as background (must be same size as the sketch window)
*/
public void background(PImage image) {
if ((image.width != width) || (image.height != height)) {
throw new RuntimeException(ERROR_BACKGROUND_IMAGE_SIZE);
}
if ((image.format != RGB) && (image.format != ARGB)) {
throw new RuntimeException(ERROR_BACKGROUND_IMAGE_FORMAT);
}
backgroundColor = 0; // just zero it out for images
backgroundImpl(image);
}
/**
* Actually set the background image. This is separated from the error
* handling and other semantic goofiness that is shared across renderers.
*/
protected void backgroundImpl(PImage image) {
// blit image to the screen
set(0, 0, image);
}
/**
* Actual implementation of clearing the background, now that the
* internal variables for background color have been set. Called by the
* backgroundFromCalc() method, which is what all the other background()
* methods call once the work is done.
*/
protected void backgroundImpl() {
pushStyle();
pushMatrix();
resetMatrix();
fill(backgroundColor);
rect(0, 0, width, height);
popMatrix();
popStyle();
}
/**
* Callback to handle clearing the background when begin/endRaw is in use.
* Handled as separate function for OpenGL (or other) subclasses that
* override backgroundImpl() but still needs this to work properly.
*/
// protected void backgroundRawImpl() {
// if (raw != null) {
// raw.colorMode(RGB, 1);
// raw.noStroke();
// raw.fill(backgroundR, backgroundG, backgroundB);
// raw.beginShape(TRIANGLES);
//
// raw.vertex(0, 0);
// raw.vertex(width, 0);
// raw.vertex(0, height);
//
// raw.vertex(width, 0);
// raw.vertex(width, height);
// raw.vertex(0, height);
//
// raw.endShape();
// }
// }
//////////////////////////////////////////////////////////////
// COLOR MODE
/**
* ( begin auto-generated from colorMode.xml )
*
* Changes the way Processing interprets color data. By default, the
* parameters for <b>fill()</b>, <b>stroke()</b>, <b>background()</b>, and
* <b>color()</b> are defined by values between 0 and 255 using the RGB
* color model. The <b>colorMode()</b> function is used to change the
* numerical range used for specifying colors and to switch color systems.
* For example, calling <b>colorMode(RGB, 1.0)</b> will specify that values
* are specified between 0 and 1. The limits for defining colors are
* altered by setting the parameters range1, range2, range3, and range 4.
*
* ( end auto-generated )
*
* @webref color:setting
* @usage web_application
* @param mode Either RGB or HSB, corresponding to Red/Green/Blue and Hue/Saturation/Brightness
* @see PGraphics#background(float)
* @see PGraphics#fill(float)
* @see PGraphics#stroke(float)
*/
public void colorMode(int mode) {
colorMode(mode, colorModeX, colorModeY, colorModeZ, colorModeA);
}
/**
* @param max range for all color elements
*/
public void colorMode(int mode, float max) {
colorMode(mode, max, max, max, max);
}
/**
* @param max1 range for the red or hue depending on the current color mode
* @param max2 range for the green or saturation depending on the current color mode
* @param max3 range for the blue or brightness depending on the current color mode
*/
public void colorMode(int mode, float max1, float max2, float max3) {
colorMode(mode, max1, max2, max3, colorModeA);
}
/**
* @param maxA range for the alpha
*/
public void colorMode(int mode,
float max1, float max2, float max3, float maxA) {
colorMode = mode;
colorModeX = max1; // still needs to be set for hsb
colorModeY = max2;
colorModeZ = max3;
colorModeA = maxA;
// if color max values are all 1, then no need to scale
colorModeScale =
((maxA != 1) || (max1 != max2) || (max2 != max3) || (max3 != maxA));
// if color is rgb/0..255 this will make it easier for the
// red() green() etc functions
colorModeDefault = (colorMode == RGB) &&
(colorModeA == 255) && (colorModeX == 255) &&
(colorModeY == 255) && (colorModeZ == 255);
}
//////////////////////////////////////////////////////////////
// COLOR CALCULATIONS
// Given input values for coloring, these functions will fill the calcXxxx
// variables with values that have been properly filtered through the
// current colorMode settings.
// Renderers that need to subclass any drawing properties such as fill or
// stroke will usally want to override methods like fillFromCalc (or the
// same for stroke, ambient, etc.) That way the color calcuations are
// covered by this based PGraphics class, leaving only a single function
// to override/implement in the subclass.
/**
* Set the fill to either a grayscale value or an ARGB int.
* <P>
* The problem with this code is that it has to detect between these two
* situations automatically. This is done by checking to see if the high bits
* (the alpha for 0xAA000000) is set, and if not, whether the color value
* that follows is less than colorModeX (first param passed to colorMode).
* <P>
* This auto-detect would break in the following situation:
* <PRE>size(256, 256);
* for (int i = 0; i < 256; i++) {
* color c = color(0, 0, 0, i);
* stroke(c);
* line(i, 0, i, 256);
* }</PRE>
* ...on the first time through the loop, where (i == 0), since the color
* itself is zero (black) then it would appear indistinguishable from code
* that reads "fill(0)". The solution is to use the four parameter versions
* of stroke or fill to more directly specify the desired result.
*/
protected void colorCalc(int rgb) {
if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) {
colorCalc((float) rgb);
} else {
colorCalcARGB(rgb, colorModeA);
}
}
protected void colorCalc(int rgb, float alpha) {
if (((rgb & 0xff000000) == 0) && (rgb <= colorModeX)) { // see above
colorCalc((float) rgb, alpha);
} else {
colorCalcARGB(rgb, alpha);
}
}
protected void colorCalc(float gray) {
colorCalc(gray, colorModeA);
}
protected void colorCalc(float gray, float alpha) {
if (gray > colorModeX) gray = colorModeX;
if (alpha > colorModeA) alpha = colorModeA;
if (gray < 0) gray = 0;
if (alpha < 0) alpha = 0;
calcR = colorModeScale ? (gray / colorModeX) : gray;
calcG = calcR;
calcB = calcR;
calcA = colorModeScale ? (alpha / colorModeA) : alpha;
calcRi = (int)(calcR*255); calcGi = (int)(calcG*255);
calcBi = (int)(calcB*255); calcAi = (int)(calcA*255);
calcColor = (calcAi << 24) | (calcRi << 16) | (calcGi << 8) | calcBi;
calcAlpha = (calcAi != 255);
}
protected void colorCalc(float x, float y, float z) {
colorCalc(x, y, z, colorModeA);
}
protected void colorCalc(float x, float y, float z, float a) {
if (x > colorModeX) x = colorModeX;
if (y > colorModeY) y = colorModeY;
if (z > colorModeZ) z = colorModeZ;
if (a > colorModeA) a = colorModeA;
if (x < 0) x = 0;
if (y < 0) y = 0;
if (z < 0) z = 0;
if (a < 0) a = 0;
switch (colorMode) {
case RGB:
if (colorModeScale) {
calcR = x / colorModeX;
calcG = y / colorModeY;
calcB = z / colorModeZ;
calcA = a / colorModeA;
} else {
calcR = x; calcG = y; calcB = z; calcA = a;
}
break;
case HSB:
x /= colorModeX; // h
y /= colorModeY; // s
z /= colorModeZ; // b
calcA = colorModeScale ? (a/colorModeA) : a;
if (y == 0) { // saturation == 0
calcR = calcG = calcB = z;
} else {
float which = (x - (int)x) * 6.0f;
float f = which - (int)which;
float p = z * (1.0f - y);
float q = z * (1.0f - y * f);
float t = z * (1.0f - (y * (1.0f - f)));
switch ((int)which) {
case 0: calcR = z; calcG = t; calcB = p; break;
case 1: calcR = q; calcG = z; calcB = p; break;
case 2: calcR = p; calcG = z; calcB = t; break;
case 3: calcR = p; calcG = q; calcB = z; break;
case 4: calcR = t; calcG = p; calcB = z; break;
case 5: calcR = z; calcG = p; calcB = q; break;
}
}
break;
}
calcRi = (int)(255*calcR); calcGi = (int)(255*calcG);
calcBi = (int)(255*calcB); calcAi = (int)(255*calcA);
calcColor = (calcAi << 24) | (calcRi << 16) | (calcGi << 8) | calcBi;
calcAlpha = (calcAi != 255);
}
/**
* Unpacks AARRGGBB color for direct use with colorCalc.
* <P>
* Handled here with its own function since this is indepenent
* of the color mode.
* <P>
* Strangely the old version of this code ignored the alpha
* value. not sure if that was a bug or what.
* <P>
* Note, no need for a bounds check since it's a 32 bit number.
*/
protected void colorCalcARGB(int argb, float alpha) {
if (alpha == colorModeA) {
calcAi = (argb >> 24) & 0xff;
calcColor = argb;
} else {
calcAi = (int) (((argb >> 24) & 0xff) * (alpha / colorModeA));
calcColor = (calcAi << 24) | (argb & 0xFFFFFF);
}
calcRi = (argb >> 16) & 0xff;
calcGi = (argb >> 8) & 0xff;
calcBi = argb & 0xff;
calcA = calcAi / 255.0f;
calcR = calcRi / 255.0f;
calcG = calcGi / 255.0f;
calcB = calcBi / 255.0f;
calcAlpha = (calcAi != 255);
}
//////////////////////////////////////////////////////////////
// COLOR DATATYPE STUFFING
// The 'color' primitive type in Processing syntax is in fact a 32-bit int.
// These functions handle stuffing color values into a 32-bit cage based
// on the current colorMode settings.
// These functions are really slow (because they take the current colorMode
// into account), but they're easy to use. Advanced users can write their
// own bit shifting operations to setup 'color' data types.
public final int color(int c) { // ignore
// if (((c & 0xff000000) == 0) && (c <= colorModeX)) {
// if (colorModeDefault) {
// // bounds checking to make sure the numbers aren't to high or low
// if (c > 255) c = 255; else if (c < 0) c = 0;
// return 0xff000000 | (c << 16) | (c << 8) | c;
// } else {
// colorCalc(c);
// }
// } else {
// colorCalcARGB(c, colorModeA);
// }
colorCalc(c);
return calcColor;
}
public final int color(float gray) { // ignore
colorCalc(gray);
return calcColor;
}
/**
* @param c can be packed ARGB or a gray in this case
*/
public final int color(int c, int alpha) { // ignore
// if (colorModeDefault) {
// // bounds checking to make sure the numbers aren't to high or low
// if (c > 255) c = 255; else if (c < 0) c = 0;
// if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0;
//
// return ((alpha & 0xff) << 24) | (c << 16) | (c << 8) | c;
// }
colorCalc(c, alpha);
return calcColor;
}
/**
* @param c can be packed ARGB or a gray in this case
*/
public final int color(int c, float alpha) { // ignore
// if (((c & 0xff000000) == 0) && (c <= colorModeX)) {
colorCalc(c, alpha);
// } else {
// colorCalcARGB(c, alpha);
// }
return calcColor;
}
public final int color(float gray, float alpha) { // ignore
colorCalc(gray, alpha);
return calcColor;
}
public final int color(int v1, int v2, int v3) { // ignore
colorCalc(v1, v2, v3);
return calcColor;
}
public final int color(float v1, float v2, float v3) { // ignore
colorCalc(v1, v2, v3);
return calcColor;
}
public final int color(int v1, int v2, int v3, int a) { // ignore
colorCalc(v1, v2, v3, a);
return calcColor;
}
public final int color(float v1, float v2, float v3, float a) { // ignore
colorCalc(v1, v2, v3, a);
return calcColor;
}
//////////////////////////////////////////////////////////////
// COLOR DATATYPE EXTRACTION
// Vee have veys of making the colors talk.
/**
* ( begin auto-generated from alpha.xml )
*
* Extracts the alpha value from a color.
*
* ( end auto-generated )
* @webref color:creating_reading
* @usage web_application
* @param rgb any value of the color datatype
* @see PGraphics#red(int)
* @see PGraphics#green(int)
* @see PGraphics#blue(int)
* @see PGraphics#hue(int)
* @see PGraphics#saturation(int)
* @see PGraphics#brightness(int)
*/
public final float alpha(int rgb) {
float outgoing = (rgb >> 24) & 0xff;
if (colorModeA == 255) return outgoing;
return (outgoing / 255.0f) * colorModeA;
}
/**
* ( begin auto-generated from red.xml )
*
* Extracts the red value from a color, scaled to match current
* <b>colorMode()</b>. This value is always returned as a float so be
* careful not to assign it to an int value.<br /><br />The red() function
* is easy to use and undestand, but is slower than another technique. To
* achieve the same results when working in <b>colorMode(RGB, 255)</b>, but
* with greater speed, use the >> (right shift) operator with a bit
* mask. For example, the following two lines of code are equivalent:<br
* /><pre>float r1 = red(myColor);<br />float r2 = myColor >> 16
* & 0xFF;</pre>
*
* ( end auto-generated )
*
* @webref color:creating_reading
* @usage web_application
* @param rgb any value of the color datatype
* @see PGraphics#green(int)
* @see PGraphics#blue(int)
* @see PGraphics#alpha(int)
* @see PGraphics#hue(int)
* @see PGraphics#saturation(int)
* @see PGraphics#brightness(int)
* @see_external rightshift
*/
public final float red(int rgb) {
float c = (rgb >> 16) & 0xff;
if (colorModeDefault) return c;
return (c / 255.0f) * colorModeX;
}
/**
* ( begin auto-generated from green.xml )
*
* Extracts the green value from a color, scaled to match current
* <b>colorMode()</b>. This value is always returned as a float so be
* careful not to assign it to an int value.<br /><br />The <b>green()</b>
* function is easy to use and undestand, but is slower than another
* technique. To achieve the same results when working in <b>colorMode(RGB,
* 255)</b>, but with greater speed, use the >> (right shift)
* operator with a bit mask. For example, the following two lines of code
* are equivalent:<br /><pre>float r1 = green(myColor);<br />float r2 =
* myColor >> 8 & 0xFF;</pre>
*
* ( end auto-generated )
*
* @webref color:creating_reading
* @usage web_application
* @param rgb any value of the color datatype
* @see PGraphics#red(int)
* @see PGraphics#blue(int)
* @see PGraphics#alpha(int)
* @see PGraphics#hue(int)
* @see PGraphics#saturation(int)
* @see PGraphics#brightness(int)
* @see_external rightshift
*/
public final float green(int rgb) {
float c = (rgb >> 8) & 0xff;
if (colorModeDefault) return c;
return (c / 255.0f) * colorModeY;
}
/**
* ( begin auto-generated from blue.xml )
*
* Extracts the blue value from a color, scaled to match current
* <b>colorMode()</b>. This value is always returned as a float so be
* careful not to assign it to an int value.<br /><br />The <b>blue()</b>
* function is easy to use and undestand, but is slower than another
* technique. To achieve the same results when working in <b>colorMode(RGB,
* 255)</b>, but with greater speed, use a bit mask to remove the other
* color components. For example, the following two lines of code are
* equivalent:<br /><pre>float r1 = blue(myColor);<br />float r2 = myColor
* & 0xFF;</pre>
*
* ( end auto-generated )
*
* @webref color:creating_reading
* @usage web_application
* @param rgb any value of the color datatype
* @see PGraphics#red(int)
* @see PGraphics#green(int)
* @see PGraphics#alpha(int)
* @see PGraphics#hue(int)
* @see PGraphics#saturation(int)
* @see PGraphics#brightness(int)
* @see_external rightshift
*/
public final float blue(int rgb) {
float c = (rgb) & 0xff;
if (colorModeDefault) return c;
return (c / 255.0f) * colorModeZ;
}
/**
* ( begin auto-generated from hue.xml )
*
* Extracts the hue value from a color.
*
* ( end auto-generated )
* @webref color:creating_reading
* @usage web_application
* @param rgb any value of the color datatype
* @see PGraphics#red(int)
* @see PGraphics#green(int)
* @see PGraphics#blue(int)
* @see PGraphics#alpha(int)
* @see PGraphics#saturation(int)
* @see PGraphics#brightness(int)
*/
public final float hue(int rgb) {
if (rgb != cacheHsbKey) {
Color.RGBtoHSB((rgb >> 16) & 0xff, (rgb >> 8) & 0xff,
rgb & 0xff, cacheHsbValue);
cacheHsbKey = rgb;
}
return cacheHsbValue[0] * colorModeX;
}
/**
* ( begin auto-generated from saturation.xml )
*
* Extracts the saturation value from a color.
*
* ( end auto-generated )
* @webref color:creating_reading
* @usage web_application
* @param rgb any value of the color datatype
* @see PGraphics#red(int)
* @see PGraphics#green(int)
* @see PGraphics#blue(int)
* @see PGraphics#alpha(int)
* @see PGraphics#hue(int)
* @see PGraphics#brightness(int)
*/
public final float saturation(int rgb) {
if (rgb != cacheHsbKey) {
Color.RGBtoHSB((rgb >> 16) & 0xff, (rgb >> 8) & 0xff,
rgb & 0xff, cacheHsbValue);
cacheHsbKey = rgb;
}
return cacheHsbValue[1] * colorModeY;
}
/**
* ( begin auto-generated from brightness.xml )
*
* Extracts the brightness value from a color.
*
* ( end auto-generated )
*
* @webref color:creating_reading
* @usage web_application
* @param rgb any value of the color datatype
* @see PGraphics#red(int)
* @see PGraphics#green(int)
* @see PGraphics#blue(int)
* @see PGraphics#alpha(int)
* @see PGraphics#hue(int)
* @see PGraphics#saturation(int)
*/
public final float brightness(int rgb) {
if (rgb != cacheHsbKey) {
Color.RGBtoHSB((rgb >> 16) & 0xff, (rgb >> 8) & 0xff,
rgb & 0xff, cacheHsbValue);
cacheHsbKey = rgb;
}
return cacheHsbValue[2] * colorModeZ;
}
//////////////////////////////////////////////////////////////
// COLOR DATATYPE INTERPOLATION
// Against our better judgement.
/**
* ( begin auto-generated from lerpColor.xml )
*
* Calculates a color or colors between two color at a specific increment.
* The <b>amt</b> parameter is the amount to interpolate between the two
* values where 0.0 equal to the first point, 0.1 is very near the first
* point, 0.5 is half-way in between, etc.
*
* ( end auto-generated )
*
* @webref color:creating_reading
* @usage web_application
* @param c1 interpolate from this color
* @param c2 interpolate to this color
* @param amt between 0.0 and 1.0
* @see PImage#blendColor(int, int, int)
* @see PGraphics#color(float, float, float, float)
*/
public int lerpColor(int c1, int c2, float amt) {
return lerpColor(c1, c2, amt, colorMode);
}
static float[] lerpColorHSB1;
static float[] lerpColorHSB2;
/**
* @nowebref
* Interpolate between two colors. Like lerp(), but for the
* individual color components of a color supplied as an int value.
*/
static public int lerpColor(int c1, int c2, float amt, int mode) {
if (mode == RGB) {
float a1 = ((c1 >> 24) & 0xff);
float r1 = (c1 >> 16) & 0xff;
float g1 = (c1 >> 8) & 0xff;
float b1 = c1 & 0xff;
float a2 = (c2 >> 24) & 0xff;
float r2 = (c2 >> 16) & 0xff;
float g2 = (c2 >> 8) & 0xff;
float b2 = c2 & 0xff;
return (((int) (a1 + (a2-a1)*amt) << 24) |
((int) (r1 + (r2-r1)*amt) << 16) |
((int) (g1 + (g2-g1)*amt) << 8) |
((int) (b1 + (b2-b1)*amt)));
} else if (mode == HSB) {
if (lerpColorHSB1 == null) {
lerpColorHSB1 = new float[3];
lerpColorHSB2 = new float[3];
}
float a1 = (c1 >> 24) & 0xff;
float a2 = (c2 >> 24) & 0xff;
int alfa = ((int) (a1 + (a2-a1)*amt)) << 24;
Color.RGBtoHSB((c1 >> 16) & 0xff, (c1 >> 8) & 0xff, c1 & 0xff,
lerpColorHSB1);
Color.RGBtoHSB((c2 >> 16) & 0xff, (c2 >> 8) & 0xff, c2 & 0xff,
lerpColorHSB2);
/* If mode is HSB, this will take the shortest path around the
* color wheel to find the new color. For instance, red to blue
* will go red violet blue (backwards in hue space) rather than
* cycling through ROYGBIV.
*/
// Disabling rollover (wasn't working anyway) for 0126.
// Otherwise it makes full spectrum scale impossible for
// those who might want it...in spite of how despicable
// a full spectrum scale might be.
// roll around when 0.9 to 0.1
// more than 0.5 away means that it should roll in the other direction
/*
float h1 = lerpColorHSB1[0];
float h2 = lerpColorHSB2[0];
if (Math.abs(h1 - h2) > 0.5f) {
if (h1 > h2) {
// i.e. h1 is 0.7, h2 is 0.1
h2 += 1;
} else {
// i.e. h1 is 0.1, h2 is 0.7
h1 += 1;
}
}
float ho = (PApplet.lerp(lerpColorHSB1[0], lerpColorHSB2[0], amt)) % 1.0f;
*/
float ho = PApplet.lerp(lerpColorHSB1[0], lerpColorHSB2[0], amt);
float so = PApplet.lerp(lerpColorHSB1[1], lerpColorHSB2[1], amt);
float bo = PApplet.lerp(lerpColorHSB1[2], lerpColorHSB2[2], amt);
return alfa | (Color.HSBtoRGB(ho, so, bo) & 0xFFFFFF);
}
return 0;
}
//////////////////////////////////////////////////////////////
// BEGINRAW/ENDRAW
/**
* Record individual lines and triangles by echoing them to another renderer.
*/
public void beginRaw(PGraphics rawGraphics) { // ignore
this.raw = rawGraphics;
rawGraphics.beginDraw();
}
public void endRaw() { // ignore
if (raw != null) {
// for 3D, need to flush any geometry that's been stored for sorting
// (particularly if the ENABLE_DEPTH_SORT hint is set)
flush();
// just like beginDraw, this will have to be called because
// endDraw() will be happening outside of draw()
raw.endDraw();
raw.dispose();
raw = null;
}
}
public boolean haveRaw() { // ignore
return raw != null;
}
public PGraphics getRaw() { // ignore
return raw;
}
//////////////////////////////////////////////////////////////
// WARNINGS and EXCEPTIONS
static protected HashMap<String, Object> warnings;
/**
* Show a renderer error, and keep track of it so that it's only shown once.
* @param msg the error message (which will be stored for later comparison)
*/
static public void showWarning(String msg) { // ignore
if (warnings == null) {
warnings = new HashMap<String, Object>();
}
if (!warnings.containsKey(msg)) {
System.err.println(msg);
warnings.put(msg, new Object());
}
}
/**
* Version of showWarning() that takes a parsed String.
*/
static public void showWarning(String msg, Object... args) { // ignore
showWarning(String.format(msg, args));
}
/**
* Display a warning that the specified method is only available with 3D.
* @param method The method name (no parentheses)
*/
static public void showDepthWarning(String method) {
showWarning(method + "() can only be used with a renderer that " +
"supports 3D, such as P3D or OPENGL.");
}
/**
* Display a warning that the specified method that takes x, y, z parameters
* can only be used with x and y parameters in this renderer.
* @param method The method name (no parentheses)
*/
static public void showDepthWarningXYZ(String method) {
showWarning(method + "() with x, y, and z coordinates " +
"can only be used with a renderer that " +
"supports 3D, such as P3D or OPENGL. " +
"Use a version without a z-coordinate instead.");
}
/**
* Display a warning that the specified method is simply unavailable.
*/
static public void showMethodWarning(String method) {
showWarning(method + "() is not available with this renderer.");
}
/**
* Error that a particular variation of a method is unavailable (even though
* other variations are). For instance, if vertex(x, y, u, v) is not
* available, but vertex(x, y) is just fine.
*/
static public void showVariationWarning(String str) {
showWarning(str + " is not available with this renderer.");
}
/**
* Display a warning that the specified method is not implemented, meaning
* that it could be either a completely missing function, although other
* variations of it may still work properly.
*/
static public void showMissingWarning(String method) {
showWarning(method + "(), or this particular variation of it, " +
"is not available with this renderer.");
}
/**
* Show an renderer-related exception that halts the program. Currently just
* wraps the message as a RuntimeException and throws it, but might do
* something more specific might be used in the future.
*/
static public void showException(String msg) { // ignore
throw new RuntimeException(msg);
}
/**
* Same as below, but defaults to a 12 point font, just as MacWrite intended.
*/
protected void defaultFontOrDeath(String method) {
defaultFontOrDeath(method, 12);
}
/**
* First try to create a default font, but if that's not possible, throw
* an exception that halts the program because textFont() has not been used
* prior to the specified method.
*/
protected void defaultFontOrDeath(String method, float size) {
if (parent != null) {
textFont = parent.createDefaultFont(size);
} else {
throw new RuntimeException("Use textFont() before " + method + "()");
}
}
//////////////////////////////////////////////////////////////
// RENDERER SUPPORT QUERIES
/**
* Return true if this renderer should be drawn to the screen. Defaults to
* returning true, since nearly all renderers are on-screen beasts. But can
* be overridden for subclasses like PDF so that a window doesn't open up.
* <br/> <br/>
* A better name? showFrame, displayable, isVisible, visible, shouldDisplay,
* what to call this?
*/
public boolean displayable() {
return true;
}
/**
* Return true if this renderer supports 2D drawing. Defaults to true.
*/
public boolean is2D() {
return true;
}
/**
* Return true if this renderer supports 3D drawing. Defaults to false.
*/
public boolean is3D() {
return false;
}
/**
* Return true if this renderer does rendering through OpenGL. Defaults to false.
*/
public boolean isGL() {
return false;
}
}
| false | false | null | null |
diff --git a/CelticKnot/src/nz/gen/mi6/celticknot/DrawingView.java b/CelticKnot/src/nz/gen/mi6/celticknot/DrawingView.java
index 808f098..26b0664 100644
--- a/CelticKnot/src/nz/gen/mi6/celticknot/DrawingView.java
+++ b/CelticKnot/src/nz/gen/mi6/celticknot/DrawingView.java
@@ -1,684 +1,679 @@
package nz.gen.mi6.celticknot;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Matrix.ScaleToFit;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.util.FloatMath;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.ScaleGestureDetector.OnScaleGestureListener;
import android.view.View;
public class DrawingView extends View {
private class ScaleGestureListener implements OnScaleGestureListener {
@Override
public boolean onScaleBegin(final ScaleGestureDetector detector)
{
return true;
}
@Override
public boolean onScale(final ScaleGestureDetector detector)
{
final float worldFocusX = screenToWorldX(detector.getFocusX());
final float worldFocusY = screenToWorldY(detector.getFocusY());
DrawingView.this.worldToScreen *= detector.getScaleFactor();
DrawingView.this.xScroll -= screenToWorldX(detector.getFocusX()) - worldFocusX;
DrawingView.this.yScroll -= screenToWorldY(detector.getFocusY()) - worldFocusY;
setUpPaints();
invalidate();
return true;
}
@Override
public void onScaleEnd(final ScaleGestureDetector detector)
{
}
}
private final class GestureListener implements GestureDetector.OnGestureListener {
@Override
public boolean onSingleTapUp(final MotionEvent e)
{
// TODO Auto-generated method stub
return false;
}
@Override
public void onShowPress(final MotionEvent e)
{
// TODO Auto-generated method stub
}
@Override
public boolean onScroll(final MotionEvent e1, final MotionEvent e2, final float distanceX, final float distanceY)
{
final float worldDX = distanceX / DrawingView.this.worldToScreen;
final float worldDY = distanceY / DrawingView.this.worldToScreen;
DrawingView.this.xScroll += worldDX;
DrawingView.this.yScroll += worldDY;
invalidate();
return true;
}
@Override
public void onLongPress(final MotionEvent e)
{
// TODO Auto-generated method stub
}
@Override
public boolean onFling(final MotionEvent e1, final MotionEvent e2, final float velocityX, final float velocityY)
{
// TODO Auto-generated method stub
return false;
}
@Override
public boolean onDown(final MotionEvent e)
{
// TODO Auto-generated method stub
return false;
}
}
private static final String LOG_TAG = DrawingView.class.getName();
private static final int DEFAULT_HEIGHT = 100;
private static final int DEFAULT_WIDTH = DEFAULT_HEIGHT;
private final boolean drawGrid = true;
private float xScroll;
private float yScroll;
private float worldToScreen = 10;
private DrawingModel model;
private final GestureDetector gestureDetector;
-
- private final GestureDetector gestureDetector;
private final ScaleGestureDetector scaleGestureDetector;
/** World height of the grid */
private final float gridWidth = 20.f;
/** World width of the grid */
private final float gridHeight = 20.f;
- /** World width of the grid */
- private final float gridHeight = 20.f;
-
private Handle mStartHandle;
private Handle mEndHandle;
private static final float[] handlePropX = { 0.f, .5f, 1.f, 1.f, 1.f, .5f, 0.f, 0.f };
private static final float[] handlePropY = { 0.f, 0.f, 0.f, .5f, 1.f, 1.f, 1.f, .5f };
private final Paint frameratePaint;
private final Paint knotPaint;
private final Paint proposedSegmentPaint;
private final Paint selectedHandlePaint;
private final Paint gridPaint;
private final Paint knotBackgroundPaint;
public DrawingView(final Context context, final AttributeSet attrs)
{
this(context, attrs, 0);
}
public DrawingView(final Context context, final AttributeSet attrs, final int defStyle)
{
super(context, attrs, defStyle);
this.gestureDetector = new GestureDetector(context, new GestureListener());
this.scaleGestureDetector = new ScaleGestureDetector(context, new ScaleGestureListener());
this.knotBackgroundPaint = new Paint();
this.frameratePaint = new Paint();
this.knotPaint = new Paint();
this.proposedSegmentPaint = new Paint();
this.selectedHandlePaint = new Paint();
this.gridPaint = new Paint();
setUpPaints();
}
private void setUpPaints()
{
this.frameratePaint.setARGB(127, 0, 0, 0);
this.frameratePaint.setStyle(Paint.Style.STROKE);
this.frameratePaint.setTypeface(Typeface.DEFAULT);
this.frameratePaint.setTextAlign(Align.LEFT);
this.knotPaint.setARGB(0xFF, 0xFF, 0x00, 0x00);
this.knotPaint.setStyle(Paint.Style.STROKE);
this.knotPaint.setStrokeWidth(0.25f);
this.knotBackgroundPaint.setARGB(0xFF, 0x00, 0x00, 0x00);
this.knotBackgroundPaint.setStyle(Paint.Style.STROKE);
this.knotBackgroundPaint.setStrokeWidth(0.3f);
this.proposedSegmentPaint.setARGB(0xFF, 0xFF, 0x00, 0xFF);
this.proposedSegmentPaint.setStyle(Paint.Style.STROKE);
this.proposedSegmentPaint.setAntiAlias(true);
this.proposedSegmentPaint.setStrokeWidth(5 * this.worldToScreen);
this.selectedHandlePaint.setARGB(0xFF, 0xFF, 0x00, 0xFF);
this.selectedHandlePaint.setStyle(Paint.Style.STROKE);
this.selectedHandlePaint.setAntiAlias(true);
this.gridPaint.setARGB(0xFF, 0, 0, 0);
this.gridPaint.setStyle(Paint.Style.STROKE);
this.gridPaint.setAntiAlias(false);
}
public void setModel(final DrawingModel model)
{
this.model = model;
invalidate();
}
@Override
protected void onDraw(final Canvas canvas)
{
final long startNanos = System.nanoTime();
int saveCount;
canvas.drawColor(0xFFFFFFFF);
saveCount = canvas.save();
drawKnot(canvas);
canvas.restoreToCount(saveCount);
if (this.drawGrid) {
saveCount = canvas.save();
drawGrid(canvas);
canvas.restoreToCount(saveCount);
}
if (this.mStartHandle != null) {
drawSelectedHandle(canvas, this.mStartHandle);
if (this.mEndHandle != null) {
drawSelectedHandle(canvas, this.mEndHandle);
drawProposedSegment(canvas);
}
}
final long frameNanos = System.nanoTime() - startNanos;
canvas.drawText(String.format("%fms/frame", frameNanos / 1000. / 1000.), 10, 10, this.frameratePaint);
}
private void drawKnot(final Canvas canvas)
{
final Path path = new Path();
for (int column = 0; column < this.model.getNumColumns() + 2; ++column) {
for (int row = 0; row < this.model.getNumRows() + 2; ++row) {
final Cell cell = this.model.getCell(column, row);
final Matrix matrix = new Matrix();
final RectF dst = new RectF(worldToScreenX(column * this.gridWidth), worldToScreenY(row
* this.gridHeight), worldToScreenX((column + 1) * this.gridWidth), worldToScreenY((row + 1)
* this.gridHeight));
final RectF src = new RectF(0, 0, 1, 1);
matrix.setRectToRect(src, dst, ScaleToFit.FILL);
canvas.save();
canvas.concat(matrix);
final int[] spinwise = { 4, 5, 6, 7, 0, 1, 2, 3 };
for (int i = 0; i < 8; ++i) {
final int from = spinwise[i];
final int to = cell.getConnectionFrom(from);
if (to != -1 && to > from) {
if (from == 2) {
// canvas.clipRect(src);
}
drawKnotSegment(canvas, path, from, to);
}
}
canvas.restore();
}
}
}
private void drawKnotSegment(final Canvas canvas, final Path path, final int from, final int to)
{
final float startWorldX = handlePropX[from];
final float stopWorldX = handlePropX[to];
final float startWorldY = handlePropY[from];
final float stopWorldY = handlePropY[to];
final float sqrt8 = FloatMath.sqrt(2) * 2;
final float adjustStartX;
final float adjustStopX;
final float adjustStartY;
final float adjustStopY;
if (from == 2) {
adjustStartX = -.3f / sqrt8;
adjustStopX = .3f / sqrt8;
adjustStartY = .3f / sqrt8;
adjustStopY = -.3f / sqrt8;
} else {
adjustStartX = 0.f;
adjustStopX = 0.f;
adjustStartY = 0.f;
adjustStopY = 0.f;
}
if ((to - from == 2 || from == 0 && to == 6) && (to & 1) == 0) {
final float radius = FloatMath.sqrt(2) / 2;
final float cx, cy;
final float startAngle;
switch (from) {
case 0:
if (to == 2) {
cx = .5f;
cy = -.5f;
startAngle = 45.f;
} else {
cx = -.5f;
cy = .5f;
startAngle = 315.f;
}
break;
case 2:
cx = 1.5f;
cy = .5f;
startAngle = 135.f;
break;
case 4:
cx = .5f;
cy = 1.5f;
startAngle = 225.f;
break;
default:
throw new AssertionError();
}
final RectF oval = new RectF(cx - radius, cy - radius, cx + radius, cy + radius);
final float sweepAngle = 90.f;
// path.reset();
// path.addArc(oval, startAngle, sweepAngle);
// canvas.drawPath(path, this.knotBackgroundPaint);
// canvas.drawPath(path, this.knotPaint);
canvas.drawArc(oval, startAngle, sweepAngle, false, this.knotBackgroundPaint);
canvas.drawArc(oval, startAngle, sweepAngle, false, this.knotPaint);
} else if (from == 0 && to == 3 || from == 2 && to == 7 || from == 3 && to == 6 || from == 4 && to == 7) {
final float startX, startY;
final float stopX, stopY;
final float radius = FloatMath.sqrt(2) / 2;
final float cx, cy;
final float startAngle;
final float sweepAngle = 45.f;
switch (from) {
case 0:
startX = 1.f;
startY = radius;
cx = 1.f;
cy = 0.f;
startAngle = 90.f;
stopX = 0.f;
stopY = 0.f;
break;
case 2:
startX = 1.f;
startY = 0.f;
cx = 0.f;
cy = 0.f;
startAngle = 45.f;
stopX = 0.f;
stopY = radius;
break;
case 3:
startX = 0.f;
startY = 1.f;
cx = 1.f;
cy = 1.f;
startAngle = 225.f;
stopX = 1.f;
stopY = 1.f - radius;
break;
case 4:
startX = 0.f;
startY = 1.f - radius;
cx = 0.f;
cy = 1.f;
startAngle = 270.f;
stopX = 1.f;
stopY = 1.f;
break;
default:
throw new AssertionError();
}
final RectF oval = new RectF(cx - radius, cy - radius, cx + radius, cy + radius);
path.reset();
path.moveTo(startX, startY);
// path.lineTo(.5f, .5f);
path.arcTo(oval, startAngle, sweepAngle);
path.lineTo(stopX, stopY);
canvas.drawPath(path, this.knotBackgroundPaint);
canvas.drawPath(path, this.knotPaint);
} else if ((from & 1) == 0 && to == from + 4) {
path.reset();
path.moveTo(startWorldX + adjustStartX, startWorldY + adjustStartY);
path.lineTo(stopWorldX + adjustStopX, stopWorldY + adjustStopY);
canvas.drawPath(path, this.knotBackgroundPaint);
canvas.drawPath(path, this.knotPaint);
} else {
}
}
private void drawProposedSegment(final Canvas canvas)
{
canvas.drawLine(
worldToScreenX(this.mStartHandle.worldX),
worldToScreenY(this.mStartHandle.worldY),
worldToScreenX(this.mEndHandle.worldX),
worldToScreenY(this.mEndHandle.worldY),
this.proposedSegmentPaint);
}
private void drawSelectedHandle(final Canvas canvas, final Handle handle)
{
final float screenX = worldToScreenX(handle.worldX);
final float screenY = worldToScreenY(handle.worldY);
canvas.drawCircle(screenX, screenY, 20, this.selectedHandlePaint);
}
private void drawGrid(final Canvas canvas)
{
final int height = canvas.getHeight();
final int width = canvas.getWidth();
final float minScreenX = Math.max(worldToScreenX(this.gridWidth / 2), 0);
final float maxScreenX = Math.min(worldToScreenX((this.model.getNumColumns() + 1)
* this.gridWidth
+ this.gridWidth
/ 2), width);
final float minScreenY = Math.max(worldToScreenY(this.gridHeight / 2), 0);
final float maxScreenY = Math.min(worldToScreenY((this.model.getNumRows() + 1)
* this.gridHeight
+ this.gridHeight
/ 2), height);
final int firstHorizGridIndex = clamp(
1,
this.model.getNumRows() + 2,
(int) FloatMath.floor(this.yScroll / this.gridHeight));
final int lastHorizGridIndex = clamp(
1,
this.model.getNumRows() + 2,
(int) FloatMath.floor(screenToWorldY(height)));
final int firstVertGridIndex = clamp(
1,
this.model.getNumColumns() + 2,
(int) FloatMath.floor(this.xScroll / this.gridWidth));
final int lastVertGridIndex = clamp(
1,
this.model.getNumColumns() + 2,
(int) FloatMath.floor(screenToWorldX(width)));
for (int yi = firstHorizGridIndex; yi < lastHorizGridIndex; ++yi) {
final float y = worldToScreenY(yi * this.gridHeight);
canvas.drawLine(minScreenX, y, maxScreenX, y, this.gridPaint);
}
for (int xi = firstVertGridIndex; xi < lastVertGridIndex; ++xi) {
final float x = worldToScreenX(xi * this.gridWidth);
canvas.drawLine(x, minScreenY, x, maxScreenY, this.gridPaint);
}
}
private float worldToScreenX(final float x)
{
return (x - this.xScroll) * this.worldToScreen;
}
private float screenToWorldX(final float x)
{
return x / this.worldToScreen + this.xScroll;
}
private float worldToScreenY(final float y)
{
return (y - this.yScroll) * this.worldToScreen;
}
private float screenToWorldY(final float y)
{
return y / this.worldToScreen + this.yScroll;
}
@Override
protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec)
{
final int measuredWidth;
final int measuredHeight;
{
final int widthMeasureSpecMode = MeasureSpec.getMode(widthMeasureSpec);
switch (widthMeasureSpecMode) {
case MeasureSpec.EXACTLY:
case MeasureSpec.AT_MOST:
measuredWidth = MeasureSpec.getSize(widthMeasureSpec);
break;
case MeasureSpec.UNSPECIFIED:
measuredWidth = DEFAULT_WIDTH;
break;
default:
Log.e(LOG_TAG, "Unexpected width measure spec mode: " + widthMeasureSpecMode);
measuredWidth = DEFAULT_WIDTH;
}
}
{
final int heightMeasureSpecMode = MeasureSpec.getMode(heightMeasureSpec);
switch (heightMeasureSpecMode) {
case MeasureSpec.EXACTLY:
case MeasureSpec.AT_MOST:
measuredHeight = MeasureSpec.getSize(heightMeasureSpec);
break;
case MeasureSpec.UNSPECIFIED:
measuredHeight = DEFAULT_HEIGHT;
break;
default:
Log.e(LOG_TAG, "Unexpected height measure spec mode: " + heightMeasureSpecMode);
measuredHeight = DEFAULT_HEIGHT;
}
}
setMeasuredDimension(measuredWidth, measuredHeight);
}
@Override
public boolean onTouchEvent(final MotionEvent event)
{
this.scaleGestureDetector.onTouchEvent(event);
if (this.mStartHandle == null) {
this.gestureDetector.onTouchEvent(event);
}
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
final float worldX = screenToWorldX(event.getX());
final float worldY = screenToWorldY(event.getY());
this.mStartHandle = getNearestHandle(worldX, worldY, null);
invalidate();
break;
}
case MotionEvent.ACTION_UP:
if (this.mStartHandle != null) {
if (this.mEndHandle != null) {
final int column = this.mEndHandle.column;
final int row = this.mEndHandle.row;
final int from;
if (this.mStartHandle.column != column) {
// 2 -> 7
// 3 -> 6
// 7 -> 2
// 6 -> 3
from = 9 - this.mStartHandle.handleIndex;
} else if (this.mStartHandle.row != row) {
// 0 -> 5
// 1 -> 4
// 5 -> 0
// 4 -> 1
from = 5 - this.mStartHandle.handleIndex;
} else {
from = this.mStartHandle.handleIndex;
}
final int to = this.mEndHandle.handleIndex;
this.model.getCell(column, row).connect(from, to);
}
this.mStartHandle = null;
this.mEndHandle = null;
invalidate();
}
break;
case MotionEvent.ACTION_CANCEL:
this.mStartHandle = null;
this.mEndHandle = null;
invalidate();
break;
case MotionEvent.ACTION_MOVE:
if (this.mStartHandle != null) {
final float worldX = screenToWorldX(event.getX());
final float worldY = screenToWorldY(event.getY());
this.mEndHandle = getNearestHandle(worldX, worldY, this.mStartHandle);
invalidate();
}
break;
}
return true;
}
private int clamp(final int min, final int max, final int i)
{
return i < min ? min : i > max ? max : i;
}
private Handle getNearestHandle(final float worldX, final float worldY, final Handle adjacentHandle)
{
// Find the cell in which the touch occurred.
final int minColumn;
final int maxColumn;
final int minRow;
final int maxRow;
if (adjacentHandle == null) {
minColumn = 0;
maxColumn = this.model.getNumColumns() + 1;
minRow = 0;
maxRow = this.model.getNumRows() + 1;
} else {
switch (adjacentHandle.handleIndex) {
case 0:
case 1:
case 4:
case 5:
minColumn = adjacentHandle.column;
maxColumn = adjacentHandle.column;
break;
case 2:
case 3:
minColumn = adjacentHandle.column;
maxColumn = adjacentHandle.column + 1;
break;
case 6:
case 7:
minColumn = adjacentHandle.column - 1;
maxColumn = adjacentHandle.column;
break;
default:
minColumn = adjacentHandle.column;
maxColumn = adjacentHandle.column;
}
switch (adjacentHandle.handleIndex) {
case 0:
case 1:
minRow = adjacentHandle.row - 1;
maxRow = adjacentHandle.row;
break;
case 2:
case 3:
case 6:
case 7:
minRow = adjacentHandle.row;
maxRow = adjacentHandle.row;
break;
case 4:
case 5:
minRow = adjacentHandle.row;
maxRow = adjacentHandle.row + 1;
break;
default:
minRow = adjacentHandle.row;
maxRow = adjacentHandle.row;
}
}
final int column = clamp(minColumn, maxColumn, (int) FloatMath.floor(worldX / this.gridWidth));
final int row = clamp(minRow, maxRow, (int) FloatMath.floor(worldY / this.gridHeight));
// Calculate the cell-relative coordinates of the touch, from 0 to 1.
final float cellPropX = (worldX - column * this.gridWidth) / this.gridWidth;
final float cellPropY = (worldY - row * this.gridHeight) / this.gridHeight;
// Figure out the nearest handle in the cell
final int handleIndex;
if (cellPropX < 0.5 && column != 0 || column == this.model.getNumColumns() + 1) {
// Handle index 0, 5, 6, 7
if (cellPropY < 0.5 && row != 0 || row == this.model.getNumRows() + 1) {
// Handle index 0, 7
if (cellPropX < cellPropY) {
handleIndex = 7;
} else {
handleIndex = 0;
}
} else {
// Handle index 5, 6
if (cellPropX > 1 - cellPropY) {
handleIndex = 5;
} else {
handleIndex = 6;
}
}
} else {
// Handle index 1, 2, 3, 4
if (cellPropY < 0.5 && row != 0 || row == this.model.getNumRows() + 1) {
// Handle index 1, 2
if (1 - cellPropX > cellPropY) {
handleIndex = 1;
} else {
handleIndex = 2;
}
} else {
// Handle index 3, 4
if (cellPropX < cellPropY) {
handleIndex = 4;
} else {
handleIndex = 3;
}
}
}
final Handle handle = new Handle();
handle.worldX = column * this.gridWidth + handlePropX[handleIndex] * this.gridWidth;
handle.worldY = row * this.gridHeight + handlePropY[handleIndex] * this.gridHeight;
handle.column = column;
handle.row = row;
handle.handleIndex = handleIndex;
final float dx = worldX - handle.worldX;
final float dy = worldY - handle.worldY;
final float sqrdist = (dx * dx) + (dy * dy);
if (sqrdist < this.gridWidth * this.gridHeight / 9
&& (adjacentHandle == null || adjacentHandle.adjacentTo(handle))) {
return handle;
} else {
return null;
}
}
}
| false | false | null | null |
diff --git a/concourse-server/src/main/java/org/cinchapi/concourse/util/Logger.java b/concourse-server/src/main/java/org/cinchapi/concourse/util/Logger.java
index 227f23d67..73d17f060 100644
--- a/concourse-server/src/main/java/org/cinchapi/concourse/util/Logger.java
+++ b/concourse-server/src/main/java/org/cinchapi/concourse/util/Logger.java
@@ -1,154 +1,158 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jeff Nelson, Cinchapi Software Collective
*
* 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.cinchapi.concourse.util;
import java.io.File;
+import org.apache.thrift.ProcessFunction;
import org.cinchapi.concourse.server.GlobalState;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.ConsoleAppender;
import ch.qos.logback.core.FileAppender;
/**
* Contains methods to print log messages in the appropriate files.
*
* @author jnelson
*/
public final class Logger {
/**
* Print {@code message} with {@code params} to the INFO log.
*
* @param message
* @param params
*/
public static void info(String message, Object... params) {
INFO.info(message, params);
}
/**
* Print {@code message} with {@code params} to the ERROR log.
*
* @param message
* @param params
*/
public static void error(String message, Object... params) {
ERROR.error(message, params);
}
/**
* Print {@code message} with {@code params} to the WARN log.
*
* @param message
* @param params
*/
public static void warn(String message, Object... params) {
WARN.warn(message, params);
}
/**
* Print {@code message} with {@code params} to the DEBUG log.
*
* @param message
* @param params
*/
public static void debug(String message, Object... params) {
DEBUG.debug(message, params);
}
private static final String LOG_DIRECTORY = "log";
private static final ch.qos.logback.classic.Logger ERROR = setup(
"org.cinchapi.concourse.server.ErrorLogger", "error.log");
private static final ch.qos.logback.classic.Logger WARN = setup(
"org.cinchapi.concourse.server.WarnLogger", "warn.log");
private static final ch.qos.logback.classic.Logger INFO = setup(
"org.cinchapi.concourse.server.InfoLogger", "info.log");
private static final ch.qos.logback.classic.Logger DEBUG = setup(
"org.cinchapi.concourse.server.DebugLogger", "debug.log");
+ static {
+ setup(ProcessFunction.class.getName(), "error.log");
+ }
/**
* Setup logger {@code name} that prints to {@code file}.
*
* @param name
* @param file
* @return the logger
*/
private static ch.qos.logback.classic.Logger setup(String name, String file) {
if(!GlobalState.ENABLE_CONSOLE_LOGGING) {
ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory
.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
root.detachAndStopAllAppenders();
}
LoggerContext context = (LoggerContext) LoggerFactory
.getILoggerFactory();
// Configure Pattern
PatternLayoutEncoder encoder = new PatternLayoutEncoder();
encoder.setPattern("%date [%thread] %level %class{36} - %msg%n");
encoder.setContext(context);
encoder.start();
// Configure File Appender
FileAppender<ILoggingEvent> appender = new FileAppender<ILoggingEvent>();
appender.setFile(LOG_DIRECTORY + File.separator + file);
appender.setEncoder(encoder);
appender.setContext(context);
appender.start();
// Get Logger
ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory
.getLogger(name);
logger.addAppender(appender);
logger.setLevel(GlobalState.LOG_LEVEL);
logger.setAdditive(true);
return logger;
}
/**
* Update the configuration of {@code logger} based on changes in the
* underlying prefs file.
*
* @param logger
*/
@SuppressWarnings("unused")
private static void update(ch.qos.logback.classic.Logger logger) {
// TODO I need to actually reload the file from disk and check for
// changes
ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory
.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
if(!GlobalState.ENABLE_CONSOLE_LOGGING) {
root.detachAndStopAllAppenders();
}
else {
root.addAppender(new ConsoleAppender<ILoggingEvent>());
}
logger.setLevel(GlobalState.LOG_LEVEL);
}
private Logger() {} /* utility class */
}
diff --git a/concourse/src/main/java/org/cinchapi/concourse/config/ConcourseConfiguration.java b/concourse/src/main/java/org/cinchapi/concourse/config/ConcourseConfiguration.java
index b28740458..52b6630ec 100644
--- a/concourse/src/main/java/org/cinchapi/concourse/config/ConcourseConfiguration.java
+++ b/concourse/src/main/java/org/cinchapi/concourse/config/ConcourseConfiguration.java
@@ -1,152 +1,165 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jeff Nelson, Cinchapi Software Collective
*
* 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.cinchapi.concourse.config;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.configuration.ConfigurationException;
+import org.apache.commons.configuration.ConfigurationUtils;
+import org.apache.commons.configuration.DefaultFileSystem;
import org.apache.commons.configuration.PropertiesConfiguration;
+import org.slf4j.LoggerFactory;
+
+import ch.qos.logback.classic.Level;
import com.google.common.base.Throwables;
/**
* A {@link PropertiesConfiguration} loader with additional methods.
*
* @author jnelson
*/
public class ConcourseConfiguration extends PropertiesConfiguration {
/*
* This implementation uses lower case strings when putting and getting from
* the map in order to facilitate case insensitivity. DO NOT use any other
* methods beyond #get and #put because those have not been overridden to
* account for the case insensitivity.
*/
private static Map<String, Integer> multipliers = new HashMap<String, Integer>() {
private static final long serialVersionUID = 1L;
@Override
public Integer get(Object key) {
if(key instanceof String) {
key = ((String) key).toLowerCase();
}
return super.get(key);
}
@Override
public Integer put(String key, Integer value) {
key = key.toLowerCase();
return super.put(key, value);
}
};
static {
multipliers.put("b", (int) Math.pow(1024, 0));
multipliers.put("k", (int) Math.pow(1024, 1));
multipliers.put("kb", (int) Math.pow(1024, 1));
multipliers.put("m", (int) Math.pow(1024, 2));
multipliers.put("mb", (int) Math.pow(1024, 2));
multipliers.put("g", (int) Math.pow(1024, 3));
multipliers.put("gb", (int) Math.pow(1024, 3));
+
+ // Prevent logging from showing up in the console
+ ((ch.qos.logback.classic.Logger) LoggerFactory
+ .getLogger(ConcourseConfiguration.class)).setLevel(Level.OFF);
+ ((ch.qos.logback.classic.Logger) LoggerFactory
+ .getLogger(ConfigurationUtils.class)).setLevel(Level.OFF);
+ ((ch.qos.logback.classic.Logger) LoggerFactory
+ .getLogger(DefaultFileSystem.class)).setLevel(Level.OFF);
}
/**
* Load the configuration from {@code file}.
*
* @param file
* @return the configuration
*/
public static ConcourseConfiguration loadConfig(String file) {
try {
return new ConcourseConfiguration(file);
}
catch (ConfigurationException e) {
throw Throwables.propagate(e);
}
}
/**
* Construct a new instance.
*
* @param file
* @throws ConfigurationException
*/
private ConcourseConfiguration(String file) throws ConfigurationException {
super(file);
}
/**
* Get the size description associated with the given key. If the key
* doesn't map to an existing object, the defaultValue is returned.
*
* @param key
* @param defaultValue
* @return the associated size description if key is found, defaultValue
* otherwise
*/
public long getSize(String key, long defaultValue) {
String value = getString(key, null);
if(value != null) {
String[] parts = value.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
long base = Long.parseLong(parts[0]);
int multiplier;
if(parts.length > 1) {
multiplier = multipliers.get(parts[1]);
}
else {
multiplier = multipliers.get("b");
}
return base * multiplier;
}
else {
return defaultValue;
}
}
/**
* Get the enum value associated with the given key. If the key doesn't map
* to an existing object or the mapped value is not a valid enum, the
* defaultValue is returned
*
* @param key
* @param defaultValue
* @return the associated enum if key is found, defaultValue
* otherwise
*/
@SuppressWarnings("unchecked")
public <T extends Enum<T>> T getEnum(String key, T defaultValue) {
String value = getString(key, null);
if(value != null) {
try {
defaultValue = (T) Enum.valueOf(defaultValue.getClass(), value);
}
catch (IllegalArgumentException e) {
// ignore
}
}
return defaultValue;
}
}
| false | false | null | null |
diff --git a/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Workspace.java b/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Workspace.java
index 467a63334..f148ab23a 100644
--- a/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Workspace.java
+++ b/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Workspace.java
@@ -1,2101 +1,2101 @@
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM - Initial API and implementation
******************************************************************************/
package org.eclipse.core.internal.resources;
import java.io.IOException;
import java.util.*;
import org.eclipse.core.internal.events.*;
import org.eclipse.core.internal.localstore.CoreFileSystemLibrary;
import org.eclipse.core.internal.localstore.FileSystemResourceManager;
import org.eclipse.core.internal.properties.PropertyManager;
import org.eclipse.core.internal.utils.Assert;
import org.eclipse.core.internal.utils.Policy;
import org.eclipse.core.internal.watson.*;
import org.eclipse.core.resources.*;
import org.eclipse.core.resources.team.IMoveDeleteHook;
import org.eclipse.core.resources.team.TeamHook;
import org.eclipse.core.runtime.*;
public class Workspace extends PlatformObject implements IWorkspace, ICoreConstants {
protected WorkspacePreferences description;
protected LocalMetaArea localMetaArea;
protected boolean openFlag = false;
protected ElementTree tree;
protected ElementTree operationTree; // tree at the start of the current operation
protected SaveManager saveManager;
protected BuildManager buildManager;
protected NatureManager natureManager;
protected NotificationManager notificationManager;
protected FileSystemResourceManager fileSystemManager;
protected PathVariableManager pathVariableManager;
protected PropertyManager propertyManager;
protected MarkerManager markerManager;
protected WorkManager workManager;
protected AliasManager aliasManager;
protected long nextNodeId = 1;
protected long nextModificationStamp = 0;
protected long nextMarkerId = 0;
protected Synchronizer synchronizer;
protected IProject[] buildOrder = null;
protected boolean forceBuild = false;
protected IWorkspaceRoot defaultRoot = new WorkspaceRoot(Path.ROOT, this);
protected final HashSet lifecycleListeners = new HashSet(10);
protected static final String REFRESH_ON_STARTUP = "-refresh"; //$NON-NLS-1$
/**
* File modification validation. If it is true and validator is null, we try/initialize
* validator first time through. If false, there is no validator.
*/
protected boolean shouldValidate = true;
/**
* The currently installed file modification validator.
*/
protected IFileModificationValidator validator = null;
/**
* The currently installed Move/Delete hook.
*/
protected IMoveDeleteHook moveDeleteHook = null;
/**
* The currently installed team hook.
*/
protected TeamHook teamHook = null;
// whether the resources plugin is in debug mode.
public static boolean DEBUG = false;
/**
* This field is used to control the access to the workspace tree inside
* operations. It is useful when calling alien code. Since we usually are in
* the same thread as the alien code we are calling, our concurrency model
* would allow the alien code to run operations that could change the tree.
* If this field is true, a beginOperation(true) fails, so the alien code
* would fail and be logged in our SafeRunnable wrappers, not affecting the
* normal workspace operation.
*/
protected boolean treeLocked;
/**
* We need to override the tree lock mechanism when synchronizing the tree
* to create a workspace tree visitor. In this case we need the tree to be
* unlocked, but we know that nothing will modify the tree.
*/
protected volatile boolean overrideTreeLock = false;
/** indicates if the workspace crashed in a previous session */
protected boolean crashed = false;
public Workspace() {
super();
localMetaArea = new LocalMetaArea();
tree = new ElementTree();
/* tree should only be modified during operations */
tree.immutable();
treeLocked = true;
tree.setTreeData(newElement(IResource.ROOT));
}
/**
* Adds a listener for internal workspace lifecycle events. There is no way to
* remove lifecycle listeners.
*/
public void addLifecycleListener(ILifecycleListener listener) {
lifecycleListeners.add(listener);
}
/**
* @see IWorkspace
*/
public void addResourceChangeListener(IResourceChangeListener listener) {
notificationManager.addListener(listener, IResourceChangeEvent.PRE_CLOSE | IResourceChangeEvent.PRE_DELETE | IResourceChangeEvent.POST_CHANGE);
}
/**
* @see IWorkspace
*/
public void addResourceChangeListener(IResourceChangeListener listener, int eventMask) {
notificationManager.addListener(listener, eventMask);
}
/**
* @see IWorkspace
*/
public ISavedState addSaveParticipant(Plugin plugin, ISaveParticipant participant) throws CoreException {
Assert.isNotNull(plugin, "Plugin must not be null"); //$NON-NLS-1$
Assert.isNotNull(participant, "Participant must not be null"); //$NON-NLS-1$
return saveManager.addParticipant(plugin, participant);
}
public void beginOperation(boolean createNewTree) throws CoreException {
WorkManager workManager = getWorkManager();
workManager.incrementNestedOperations();
if (!workManager.isBalanced())
Assert.isTrue(false, "Operation was not prepared."); //$NON-NLS-1$
if (isTreeLocked() && createNewTree) {
String message = Policy.bind("resources.cannotModify"); //$NON-NLS-1$
throw new ResourceException(IResourceStatus.WORKSPACE_LOCKED, null, message, null);
}
if (workManager.getPreparedOperationDepth() > 1) {
if (createNewTree && tree.isImmutable())
newWorkingTree();
return;
}
if (createNewTree) {
// stash the current tree as the basis for this operation.
operationTree = tree;
newWorkingTree();
}
}
private void broadcastChanges(ElementTree currentTree, int type, boolean lockTree, boolean updateState, IProgressMonitor monitor) {
if (operationTree == null)
return;
monitor.subTask(MSG_RESOURCES_UPDATING);
notificationManager.broadcastChanges(currentTree, type, lockTree, updateState);
}
/**
* Broadcasts an internal workspace lifecycle event to interested
* internal listeners.
*/
protected void broadcastEvent(LifecycleEvent event) throws CoreException {
for (Iterator it = lifecycleListeners.iterator(); it.hasNext();) {
ILifecycleListener listener = (ILifecycleListener) it.next();
listener.handleEvent(event);
}
}
public void build(int trigger, IProgressMonitor monitor) throws CoreException {
monitor = Policy.monitorFor(monitor);
try {
monitor.beginTask(null, Policy.opWork);
try {
prepareOperation();
beginOperation(true);
getBuildManager().build(trigger, Policy.subMonitorFor(monitor, Policy.opWork));
} finally {
//building may close the tree, but we are still inside an operation so open it
if (tree.isImmutable())
newWorkingTree();
getWorkManager().avoidAutoBuild();
endOperation(false, Policy.subMonitorFor(monitor, Policy.buildWork));
}
} finally {
monitor.done();
}
}
/**
* @see IWorkspace#checkpoint
*/
public void checkpoint(boolean build) {
boolean immutable = true;
try {
/* if it was not called by the current operation, just ignore */
if (!getWorkManager().isCurrentOperation())
return;
immutable = tree.isImmutable();
broadcastChanges(tree, IResourceChangeEvent.PRE_AUTO_BUILD, false, false, Policy.monitorFor(null));
if (build && isAutoBuilding())
getBuildManager().build(IncrementalProjectBuilder.AUTO_BUILD, Policy.monitorFor(null));
broadcastChanges(tree, IResourceChangeEvent.POST_AUTO_BUILD, false, false, Policy.monitorFor(null));
broadcastChanges(tree, IResourceChangeEvent.POST_CHANGE, true, true, Policy.monitorFor(null));
getMarkerManager().resetMarkerDeltas();
} catch (CoreException e) {
// ignore any CoreException. There shouldn't be any as the buildmanager and notification manager
// should be catching and logging...
} finally {
if (!immutable)
newWorkingTree();
}
}
/**
* Deletes all the files and directories from the given root down (inclusive).
* Returns false if we could not delete some file or an exception occurred
* at any point in the deletion.
* Even if an exception occurs, a best effort is made to continue deleting.
*/
public static boolean clear(java.io.File root) {
boolean result = clearChildren(root);
try {
if (root.exists())
result &= root.delete();
} catch (Exception e) {
result = false;
}
return result;
}
/**
* Deletes all the files and directories from the given root down, except for
* the root itself.
* Returns false if we could not delete some file or an exception occurred
* at any point in the deletion.
* Even if an exception occurs, a best effort is made to continue deleting.
*/
public static boolean clearChildren(java.io.File root) {
boolean result = true;
if (root.isDirectory()) {
String[] list = root.list();
// for some unknown reason, list() can return null.
// Just skip the children If it does.
if (list != null)
for (int i = 0; i < list.length; i++)
result &= clear(new java.io.File(root, list[i]));
}
return result;
}
/**
* Closes this workspace; ignored if this workspace is not open.
* The state of this workspace is not saved before the workspace
* is shut down.
* <p>
* If the workspace was saved immediately prior to closing,
* it will have the same set of projects
* (open or closed) when reopened for a subsequent session.
* Otherwise, closing a workspace may lose some or all of the
* changes made since the last save or snapshot.
* </p>
* <p>
* Note that session properties are discarded when a workspace is closed.
* </p>
* <p>
* This method is long-running; progress and cancellation are provided
* by the given progress monitor.
* </p>
*
* @param monitor a progress monitor, or <code>null</code> if progress
* reporting and cancellation are not desired
* @exception CoreException if the workspace could not be shutdown.
*/
public void close(IProgressMonitor monitor) throws CoreException {
monitor = Policy.monitorFor(monitor);
try {
String msg = Policy.bind("resources.closing.0"); //$NON-NLS-1$
int rootCount = tree.getChildCount(Path.ROOT);
monitor.beginTask(msg, rootCount + 2);
monitor.subTask(msg);
//this operation will never end because the world is going away
try {
prepareOperation();
if (isOpen()) {
beginOperation(true);
IProject[] projects = getRoot().getProjects();
for (int i = 0; i < projects.length; i++) {
//notify managers of closing so they can cleanup
broadcastEvent(LifecycleEvent.newEvent(LifecycleEvent.PRE_PROJECT_CLOSE, projects[i]));
monitor.worked(1);
}
//empty the workspace tree so we leave in a clean state
deleteResource(getRoot());
openFlag = false;
}
// endOperation not needed here
} finally {
// Shutdown needs to be executed anyway. Doesn't matter if the workspace was not open.
shutdown(Policy.subMonitorFor(monitor, 2, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
}
} finally {
monitor.done();
}
}
/**
* Implementation of API method declared on IWorkspace.
*
* @deprecated Replaced by <code>IWorkspace.computeProjectOrder</code>, which
* produces a more usable result when there are cycles in project reference
* graph.
*/
public IProject[][] computePrerequisiteOrder(IProject[] targets) {
return computePrerequisiteOrder1(targets);
}
/*
* Compatible reimplementation of
* <code>IWorkspace.computePrerequisiteOrder</code> using
* <code>IWorkspace.computeProjectOrder</code>.
*
* @since 2.1
*/
private IProject[][] computePrerequisiteOrder1(IProject[] projects) {
IWorkspace.ProjectOrder r = computeProjectOrder(projects);
if (!r.hasCycles) {
return new IProject[][] {r.projects, new IProject[0]};
}
// when there are cycles, we need to remove all knotted projects from
// r.projects to form result[0] and merge all knots to form result[1]
// Set<IProject> bad
Set bad = new HashSet();
// Set<IProject> bad
Set keepers = new HashSet(Arrays.asList(r.projects));
for (int i = 0; i < r.knots.length; i++) {
IProject[] knot = r.knots[i];
for (int j = 0; j < knot.length; j++) {
IProject project = knot[j];
// keep only selected projects in knot
if (keepers.contains(project)) {
bad.add(project);
}
}
}
IProject[] result2 = new IProject[bad.size()];
bad.toArray(result2);
// List<IProject> p
List p = new LinkedList();
p.addAll(Arrays.asList(r.projects));
for (Iterator it = p.listIterator(); it.hasNext(); ) {
IProject project = (IProject) it.next();
if (bad.contains(project)) {
// remove knotted projects from the main answer
it.remove();
}
}
IProject[] result1 = new IProject[p.size()];
p.toArray(result1);
return new IProject[][] {result1, result2};
}
/**
* Implementation of API method declared on IWorkspace.
*
* @since 2.1
*/
public ProjectOrder computeProjectOrder(IProject[] projects) {
// compute the full project order for all accessible projects
ProjectOrder fullProjectOrder = computeFullProjectOrder();
// "fullProjectOrder.projects" contains no inaccessible projects
// but might contain accessible projects omitted from "projects"
// optimize common case where "projects" includes everything
int accessibleCount = 0;
for (int i = 0; i < projects.length; i++) {
if (projects[i].isAccessible()) {
accessibleCount++;
}
}
// no filtering required if the subset accounts for the full list
if (accessibleCount == fullProjectOrder.projects.length) {
return fullProjectOrder;
}
// otherwise we need to eliminate mention of other projects...
// ... from "fullProjectOrder.projects"...
// Set<IProject> keepers
Set keepers = new HashSet(Arrays.asList(projects));
// List<IProject> p
List reducedProjects = new ArrayList(fullProjectOrder.projects.length);
for (int i = 0; i < fullProjectOrder.projects.length; i++) {
IProject project = fullProjectOrder.projects[i];
if (keepers.contains(project)) {
// remove projects not in the initial subset
reducedProjects.add(project);
}
}
IProject[] p1 = new IProject[reducedProjects.size()];
reducedProjects.toArray(p1);
// ... and from "fullProjectOrder.knots"
// List<IProject[]> k
List reducedKnots = new ArrayList(fullProjectOrder.knots.length);
for (int i = 0; i < fullProjectOrder.knots.length; i++) {
IProject[] knot = fullProjectOrder.knots[i];
List x = new ArrayList(knot.length);
for (int j = 0; j < knot.length; j++) {
IProject project = knot[j];
if (keepers.contains(project)) {
x.add(project);
}
}
// keep knots containing 2 or more projects in the specified subset
if (x.size() > 1) {
reducedKnots.add(x.toArray(new IProject[x.size()]));
}
}
IProject[][] k1 = new IProject[reducedKnots.size()][];
// okay to use toArray here because reducedKnots elements are IProject[]
reducedKnots.toArray(k1);
return new ProjectOrder(p1, (k1.length > 0), k1);
}
/**
* Computes the global total ordering of all open projects in the
* workspace based on project references. If an existing and open project P
* references another existing and open project Q also included in the list,
* then Q should come before P in the resulting ordering. Closed and non-
* existent projects are ignored, and will not appear in the result. References
* to non-existent or closed projects are also ignored, as are any self-
* references.
* <p>
* When there are choices, the choice is made in a reasonably stable way. For
* example, given an arbitrary choice between two projects, the one with the
* lower collating project name is usually selected.
* </p>
* <p>
* When the project reference graph contains cyclic references, it is
* impossible to honor all of the relationships. In this case, the result
* ignores as few relationships as possible. For example, if P2 references P1,
* P4 references P3, and P2 and P3 reference each other, then exactly one of the
* relationships between P2 and P3 will have to be ignored. The outcome will be
* either [P1, P2, P3, P4] or [P1, P3, P2, P4]. The result also contains
* complete details of any cycles present.
* </p>
*
* @return result describing the global project order
* @since 2.1
*/
private ProjectOrder computeFullProjectOrder() {
// determine the full set of accessible projects in the workspace
// order the set in descending alphabetical order of project name
SortedSet allAccessibleProjects = new TreeSet(new Comparator() {
public int compare(Object x, Object y) {
IProject px = (IProject) x;
IProject py = (IProject) y;
return py.getName().compareTo(px.getName());
}});
IProject[] allProjects = getRoot().getProjects();
// List<IProject[]> edges
List edges = new ArrayList(allProjects.length);
for (int i = 0; i < allProjects.length; i++) {
IProject project = allProjects[i];
// ignore projects that are not accessible
if (project.isAccessible()) {
allAccessibleProjects.add(project);
IProject[] refs= null;
try {
refs = project.getReferencedProjects();
} catch (CoreException e) {
// can't happen - project is accessible
}
for (int j = 0; j < refs.length; j++) {
IProject ref = refs[j];
// ignore self references and references to projects that are
// not accessible
if (ref.isAccessible() && !ref.equals(project)) {
edges.add(new IProject[] {project, ref});
}
}
}
}
ProjectOrder fullProjectOrder =
ComputeProjectOrder.computeProjectOrder(allAccessibleProjects, edges);
return fullProjectOrder;
}
/*
* @see IWorkspace#copy
*/
public IStatus copy(IResource[] resources, IPath destination, int updateFlags, IProgressMonitor monitor) throws CoreException {
monitor = Policy.monitorFor(monitor);
try {
int opWork = Math.max(resources.length, 1);
int totalWork = Policy.totalWork * opWork / Policy.opWork;
String message = Policy.bind("resources.copying.0"); //$NON-NLS-1$
monitor.beginTask(message, totalWork);
Assert.isLegal(resources != null);
if (resources.length == 0)
return ResourceStatus.OK_STATUS;
// to avoid concurrent changes to this array
resources = (IResource[]) resources.clone();
IPath parentPath = null;
message = Policy.bind("resources.copyProblem"); //$NON-NLS-1$
MultiStatus status = new MultiStatus(ResourcesPlugin.PI_RESOURCES, IResourceStatus.INTERNAL_ERROR, message, null);
try {
prepareOperation();
beginOperation(true);
for (int i = 0; i < resources.length; i++) {
Policy.checkCanceled(monitor);
IResource resource = resources[i];
if (resource == null || isDuplicate(resources, i)) {
monitor.worked(1);
continue;
}
// test siblings
if (parentPath == null)
parentPath = resource.getFullPath().removeLastSegments(1);
if (parentPath.equals(resource.getFullPath().removeLastSegments(1))) {
// test copy requirements
try {
IPath destinationPath = destination.append(resource.getName());
IStatus requirements = ((Resource) resource).checkCopyRequirements(destinationPath, resource.getType(), updateFlags);
if (requirements.isOK()) {
try {
resource.copy(destinationPath, updateFlags, Policy.subMonitorFor(monitor, 1));
} catch (CoreException e) {
status.merge(e.getStatus());
}
} else {
monitor.worked(1);
status.merge(requirements);
}
} catch (CoreException e) {
monitor.worked(1);
status.merge(e.getStatus());
}
} else {
monitor.worked(1);
message = Policy.bind("resources.notChild", resources[i].getFullPath().toString(), parentPath.toString()); //$NON-NLS-1$
status.merge(new ResourceStatus(IResourceStatus.OPERATION_FAILED, resources[i].getFullPath(), message));
}
}
} catch (OperationCanceledException e) {
getWorkManager().operationCanceled();
throw e;
} finally {
endOperation(true, Policy.subMonitorFor(monitor, totalWork - opWork));
}
if (status.matches(IStatus.ERROR))
throw new ResourceException(status);
return status.isOK() ? ResourceStatus.OK_STATUS : (IStatus) status;
} finally {
monitor.done();
}
}
/**
* @see IWorkspace#copy
*/
public IStatus copy(IResource[] resources, IPath destination, boolean force, IProgressMonitor monitor) throws CoreException {
int updateFlags = force ? IResource.FORCE : IResource.NONE;
return copy(resources, destination, updateFlags , monitor);
}
protected void copyTree(IResource source, IPath destination, int depth, int updateFlags, boolean keepSyncInfo) throws CoreException {
// retrieve the resource at the destination if there is one (phantoms included).
// if there isn't one, then create a new handle based on the type that we are
// trying to copy
IResource destinationResource = getRoot().findMember(destination, true);
if (destinationResource == null) {
int destinationType;
if (source.getType() == IResource.FILE)
destinationType = IResource.FILE;
else
if (destination.segmentCount() == 1)
destinationType = IResource.PROJECT;
else
destinationType = IResource.FOLDER;
destinationResource = newResource(destination, destinationType);
}
// create the resource at the destination
ResourceInfo sourceInfo = ((Resource) source).getResourceInfo(true, false);
if (destinationResource.getType() != source.getType()) {
sourceInfo = (ResourceInfo) sourceInfo.clone();
sourceInfo.setType(destinationResource.getType());
}
ResourceInfo newInfo = createResource(destinationResource, sourceInfo, false, false, keepSyncInfo);
// get/set the node id from the source's resource info so we can later put it in the
// info for the destination resource. This will help us generate the proper deltas,
// indicating a move rather than a add/delete
long nodeid = ((Resource) source).getResourceInfo(true, false).getNodeId();
newInfo.setNodeId(nodeid);
// preserve local sync info
ResourceInfo oldInfo = ((Resource) source).getResourceInfo(true, false);
newInfo.setFlags(newInfo.getFlags() | (oldInfo.getFlags() & M_LOCAL_EXISTS));
// update link locations in project descriptions
if (source.isLinked()) {
LinkDescription linkDescription;
if ((updateFlags & IResource.SHALLOW) != 0) {
//for shallow move the destination is also a linked resource
newInfo.set(ICoreConstants.M_LINK);
linkDescription = new LinkDescription(destinationResource, source.getLocation());
} else {
//for deep move the destination is not a linked resource
newInfo.clear(ICoreConstants.M_LINK);
linkDescription = null;
}
Project project = (Project)destinationResource.getProject();
project.internalGetDescription().setLinkLocation(destinationResource.getName(), linkDescription);
project.writeDescription(IResource.NONE);
}
// do the recursion. if we have a file then it has no members so return. otherwise
// recursively call this method on the container's members if the depth tells us to
if (depth == IResource.DEPTH_ZERO || source.getType() == IResource.FILE)
return;
if (depth == IResource.DEPTH_ONE)
depth = IResource.DEPTH_ZERO;
IResource[] children = ((IContainer) source).members(IContainer.INCLUDE_TEAM_PRIVATE_MEMBERS);
for (int i = 0; i < children.length; i++) {
IResource child = children[i];
IPath childPath = destination.append(child.getName());
copyTree(child, childPath, depth, updateFlags, keepSyncInfo);
}
}
/**
* Returns the number of resources in a subtree of the resource tree.
* @param path The subtree to count resources for
* @param depth The depth of the subtree to count
* @param phantom If true, phantoms are included, otherwise they are ignored.
*/
public int countResources(IPath root, int depth, final boolean phantom) {
if (!tree.includes(root))
return 0;
switch (depth) {
case IResource.DEPTH_ZERO:
return 1;
case IResource.DEPTH_ONE:
return 1 + tree.getChildCount(root);
case IResource.DEPTH_INFINITE:
final int[] count = new int[1];
IElementContentVisitor visitor = new IElementContentVisitor() {
public boolean visitElement(ElementTree tree, IPathRequestor requestor, Object elementContents) {
if (phantom || !((ResourceInfo)elementContents).isSet(M_PHANTOM))
count[0]++;
return true;
}
};
new ElementTreeIterator(tree, root).iterate(visitor);
return count[0];
}
return 0;
}
public ResourceInfo createResource(IResource resource, ResourceInfo info, boolean phantom, boolean overwrite) throws CoreException {
return createResource(resource, info, phantom, overwrite, false);
}
/*
* Creates the given resource in the tree and returns the new resource info object.
* If phantom is true, the created element is marked as a phantom.
* If there is already be an element in the tree for the given resource
* in the given state (i.e., phantom), a CoreException is thrown.
* If there is already a phantom in the tree and the phantom flag is false,
* the element is overwritten with the new element. (but the synchronization
* information is preserved) If the specified resource info is null, then create
* a new one.
*
* If keepSyncInfo is set to be true, the sync info in the given ResourceInfo is NOT
* cleared before being created and thus any sync info already existing at that namespace
* (as indicated by an already existing phantom resource) will be lost.
*/
public ResourceInfo createResource(IResource resource, ResourceInfo info, boolean phantom, boolean overwrite, boolean keepSyncInfo) throws CoreException {
info = info == null ? newElement(resource.getType()) : (ResourceInfo) info.clone();
ResourceInfo original = getResourceInfo(resource.getFullPath(), true, false);
if (phantom) {
info.set(M_PHANTOM);
info.setModificationStamp(IResource.NULL_STAMP);
}
// if nothing existed at the destination then just create the resource in the tree
if (original == null) {
// we got here from a copy/move. we don't want to copy over any sync info
// from the source so clear it.
if (!keepSyncInfo)
info.setSyncInfo(null);
tree.createElement(resource.getFullPath(), info);
} else {
// if overwrite==true then slam the new info into the tree even if one existed before
if (overwrite || (!phantom && original.isSet(M_PHANTOM))) {
// copy over the sync info and flags from the old resource info
// since we are replacing a phantom with a real resource
// DO NOT set the sync info dirty flag because we want to
// preserve the old sync info so its not dirty
// XXX: must copy over the generic sync info from the old info to the new
// XXX: do we really need to clone the sync info here?
if (!keepSyncInfo)
info.setSyncInfo(original.getSyncInfo(true));
// mark the markers bit as dirty so we snapshot an empty marker set for
// the new resource
info.set(ICoreConstants.M_MARKERS_SNAP_DIRTY);
tree.setElementData(resource.getFullPath(), info);
} else {
String message = Policy.bind("resources.mustNotExist", resource.getFullPath().toString()); //$NON-NLS-1$
throw new ResourceException(IResourceStatus.RESOURCE_EXISTS, resource.getFullPath(), message, null);
}
}
return info;
}
/*
* Creates the given resource in the tree and returns the new resource info object.
* If phantom is true, the created element is marked as a phantom.
* If there is already be an element in the tree for the given resource
* in the given state (i.e., phantom), a CoreException is thrown.
* If there is already a phantom in the tree and the phantom flag is false,
* the element is overwritten with the new element. (but the synchronization
* information is preserved)
*/
public ResourceInfo createResource(IResource resource, boolean phantom) throws CoreException {
return createResource(resource, null, phantom, false);
}
public ResourceInfo createResource(IResource resource, boolean phantom, boolean overwrite) throws CoreException {
return createResource(resource, null, phantom, overwrite);
}
public static WorkspaceDescription defaultWorkspaceDescription() {
return new WorkspaceDescription("Workspace"); //$NON-NLS-1$
}
/*
* @see IWorkspace#delete
*/
public IStatus delete(IResource[] resources, int updateFlags, IProgressMonitor monitor) throws CoreException {
monitor = Policy.monitorFor(monitor);
try {
int opWork = Math.max(resources.length, 1);
int totalWork = Policy.totalWork * opWork / Policy.opWork;
String message = Policy.bind("resources.deleting.0"); //$NON-NLS-1$
monitor.beginTask(message, totalWork);
message = Policy.bind("resources.deleteProblem"); //$NON-NLS-1$
MultiStatus result = new MultiStatus(ResourcesPlugin.PI_RESOURCES, IResourceStatus.INTERNAL_ERROR, message, null);
if (resources.length == 0)
return result;
resources = (IResource[]) resources.clone(); // to avoid concurrent changes to this array
try {
prepareOperation();
beginOperation(true);
for (int i = 0; i < resources.length; i++) {
Policy.checkCanceled(monitor);
Resource resource = (Resource) resources[i];
if (resource == null) {
monitor.worked(1);
continue;
}
try {
resource.delete(updateFlags, Policy.subMonitorFor(monitor, 1));
} catch (CoreException e) {
// Don't really care about the exception unless the resource is still around.
ResourceInfo info = resource.getResourceInfo(false, false);
if (resource.exists(resource.getFlags(info), false)) {
message = Policy.bind("resources.couldnotDelete", resource.getFullPath().toString()); //$NON-NLS-1$
result.merge(new ResourceStatus(IResourceStatus.FAILED_DELETE_LOCAL, resource.getFullPath(), message));
result.merge(e.getStatus());
}
}
}
if (result.matches(IStatus.ERROR))
throw new ResourceException(result);
return result;
} catch (OperationCanceledException e) {
getWorkManager().operationCanceled();
throw e;
} finally {
endOperation(true, Policy.subMonitorFor(monitor, totalWork - opWork));
}
} finally {
monitor.done();
}
}
/*
* @see IWorkspace#delete
*/
public IStatus delete(IResource[] resources, boolean force, IProgressMonitor monitor) throws CoreException {
int updateFlags = force ? IResource.FORCE : IResource.NONE;
updateFlags |= IResource.KEEP_HISTORY;
return delete(resources, updateFlags, monitor);
}
/**
* @see IWorkspace
*/
public void deleteMarkers(IMarker[] markers) throws CoreException {
Assert.isNotNull(markers);
if (markers.length == 0)
return;
// clone to avoid outside changes
markers = (IMarker[]) markers.clone();
try {
prepareOperation();
beginOperation(true);
for (int i = 0; i < markers.length; ++i)
if (markers[i] != null && markers[i].getResource() != null)
markerManager.removeMarker(markers[i].getResource(), markers[i].getId());
} finally {
endOperation(false, null);
}
}
/**
* Delete the given resource from the current tree of the receiver.
* This method simply removes the resource from the tree. No cleanup or
* other management is done. Use IResource.delete for proper deletion.
* If the given resource is the root, all of its children (i.e., all projects) are
* deleted but the root is left.
*/
void deleteResource(IResource resource) {
IPath path = resource.getFullPath();
if (path.equals(Path.ROOT)) {
IProject[] children = getRoot().getProjects();
for (int i = 0; i < children.length; i++)
tree.deleteElement(children[i].getFullPath());
} else
tree.deleteElement(path);
}
/**
* For debugging purposes only. Dumps plugin stats to console
*/
public void dumpStats() {
EventStats.dumpStats();
}
/**
* End an operation (group of resource changes).
* Notify interested parties that resource changes have taken place. All
* registered resource change listeners are notified. If autobuilding is
* enabled, a build is run.
*/
public void endOperation(boolean build, IProgressMonitor monitor) throws CoreException {
WorkManager workManager = getWorkManager();
try {
workManager.setBuild(build);
// if we are not exiting a top level operation then just decrement the count and return
if (workManager.getPreparedOperationDepth() > 1)
return;
// do the following in a try/finally to ensure that the operation tree is null'd at the end
// as we are completing a top level operation.
try {
// if the tree is locked we likely got here in some finally block after a failed begin.
// Since the tree is locked, nothing could have been done so there is nothing to do.
Assert.isTrue(!(isTreeLocked() && workManager.shouldBuild()), "The tree should not be locked."); //$NON-NLS-1$
// check for a programming error on using beginOperation/endOperation
Assert.isTrue(workManager.getPreparedOperationDepth() > 0, "Mismatched begin/endOperation"); //$NON-NLS-1$
// At this time we need to rebalance the nested operations. It is necessary because
// build() and snapshot() should not fail if they are called.
workManager.rebalanceNestedOperations();
// If autobuild is on, give each open project a chance to build. We have to tell each one
// because there is no way of knowing whether or not there is a relevant change
// for the project without computing the delta for each builder in each project relative
// to its last built state. If we have guaranteed corelation between the notification delta
// and the last time autobuild was done, then we could look at the notification delta and
// see which projects had changed and only build them. Currently there is no such
// guarantee.
// Note that building a project when there is actually nothing to do is not free but
// is should not be too expensive. The computed delta will be empty and so the builder itself
// will not actually be run. This does require however the delta computation.
//
// This is done in a try finally to ensure that we always decrement the operation count.
// The operationCount cannot be decremented before this as the build must be done
// inside an operation. Note that we only ever get here if we are at a top level operation.
// As such, the operationCount will always be 0 (zero) after this.
OperationCanceledException cancel = null;
CoreException signal = null;
monitor = Policy.monitorFor(monitor);
monitor.subTask(MSG_RESOURCES_UPDATING); //$NON-NLS-1$
- boolean hasTreeChanges = ElementTree.hasChanges(tree, operationTree, ResourceComparator.getComparator(false), true);
+ boolean hasTreeChanges = operationTree != null && ElementTree.hasChanges(tree, operationTree, ResourceComparator.getComparator(false), true);
broadcastChanges(tree, IResourceChangeEvent.PRE_AUTO_BUILD, false, false, Policy.monitorFor(null));
if (isAutoBuilding() && shouldBuild(hasTreeChanges)) {
try {
getBuildManager().build(IncrementalProjectBuilder.AUTO_BUILD, monitor);
} catch (OperationCanceledException e) {
cancel = e;
} catch (CoreException sig) {
signal = sig;
}
}
broadcastChanges(tree, IResourceChangeEvent.POST_AUTO_BUILD, false, false, Policy.monitorFor(null));
broadcastChanges(tree, IResourceChangeEvent.POST_CHANGE, true, true, Policy.monitorFor(null));
getMarkerManager().resetMarkerDeltas();
// Perform a snapshot if we are sufficiently out of date. Be sure to make the tree immutable first
tree.immutable();
saveManager.snapshotIfNeeded(hasTreeChanges);
//make sure the monitor subtask message is cleared.
monitor.subTask(""); //$NON-NLS-1$
if (cancel != null)
throw cancel;
if (signal != null)
throw signal;
} finally {
// make sure that the tree is immutable. Only do this if we are ending a top-level operation.
tree.immutable();
operationTree = null;
}
} finally {
workManager.checkOut();
}
}
/**
* Flush the build order cache for the workspace. Only needed if the
* description does not already have a build order. That is, if this
* is really a cache.
*/
protected void flushBuildOrder() {
if (description.getBuildOrder(false) == null)
buildOrder = null;
}
/**
* @see IWorkspace
*/
public void forgetSavedTree(String pluginId) {
Assert.isNotNull(pluginId, "PluginId must not be null"); //$NON-NLS-1$
saveManager.forgetSavedTree(pluginId);
}
public AliasManager getAliasManager() {
return aliasManager;
}
/**
* Returns this workspace's build manager
*/
public BuildManager getBuildManager() {
return buildManager;
}
/**
* Returns the order in which open projects in this workspace will be built.
* <p>
* The project build order is based on information specified in the workspace
* description. The projects are built in the order specified by
* <code>IWorkspaceDescription.getBuildOrder</code>; closed or non-existent
* projects are ignored and not included in the result. If
* <code>IWorkspaceDescription.getBuildOrder</code> is non-null, the default
* build order is used; again, only open projects are included in the result.
* </p>
* <p>
* The returned value is cached in the <code>buildOrder</code> field.
* </p>
*
* @return the list of currently open projects in the workspace in the order in
* which they would be built by <code>IWorkspace.build</code>.
* @see IWorkspace#build
* @see IWorkspaceDescription#getBuildOrder
* @since 2.1
*/
public IProject[] getBuildOrder() {
if (buildOrder != null) {
// return previously-computed and cached project build order
return buildOrder;
}
// see if a particular build order is specified
String[] order = description.getBuildOrder(false);
if (order != null) {
// convert from project names to project handles
// and eliminate non-existent and closed projects
List projectList = new ArrayList(order.length);
for (int i = 0; i < order.length; i++) {
IProject project = getRoot().getProject(order[i]);
if (project.isAccessible()) {
projectList.add(project);
}
}
buildOrder = new IProject[projectList.size()];
projectList.toArray(buildOrder);
} else {
// use default project build order
// computed for all accessible projects in workspace
buildOrder = computeFullProjectOrder().projects;
}
return buildOrder;
}
/**
* @see IWorkspace#getDanglingReferences
*/
public Map getDanglingReferences() {
IProject[] projects = getRoot().getProjects();
Map result = new HashMap(projects.length);
for (int i = 0; i < projects.length; i++) {
Project project = (Project) projects[i];
if (!project.isAccessible())
continue;
IProject[] refs = project.internalGetDescription().getReferencedProjects(false);
List dangling = new ArrayList(refs.length);
for (int j = 0; j < refs.length; j++)
if (!refs[i].exists())
dangling.add(refs[i]);
if (!dangling.isEmpty())
result.put(projects[i], dangling.toArray(new IProject[dangling.size()]));
}
return result;
}
/**
* @see IWorkspace
*/
public IWorkspaceDescription getDescription() {
WorkspaceDescription workingCopy = defaultWorkspaceDescription();
description.copyTo(workingCopy);
return workingCopy;
}
/**
* Returns the current element tree for this workspace
*/
public ElementTree getElementTree() {
return tree;
}
public FileSystemResourceManager getFileSystemManager() {
return fileSystemManager;
}
/**
* Returns the marker manager for this workspace
*/
public MarkerManager getMarkerManager() {
return markerManager;
}
public LocalMetaArea getMetaArea() {
return localMetaArea;
}
protected IMoveDeleteHook getMoveDeleteHook() {
if (moveDeleteHook == null)
initializeMoveDeleteHook();
return moveDeleteHook;
}
/**
* @see IWorkspace#getNatureDescriptor(String)
*/
public IProjectNatureDescriptor getNatureDescriptor(String natureId) {
return natureManager.getNatureDescriptor(natureId);
}
/**
* @see IWorkspace#getNatureDescriptors()
*/
public IProjectNatureDescriptor[] getNatureDescriptors() {
return natureManager.getNatureDescriptors();
}
/**
* Returns the nature manager for this workspace.
*/
public NatureManager getNatureManager() {
return natureManager;
}
public NotificationManager getNotificationManager() {
return notificationManager;
}
/**
* @see org.eclipse.core.resources.IWorkspace#getPathVariableManager()
*/
public IPathVariableManager getPathVariableManager() {
return pathVariableManager;
}
public PropertyManager getPropertyManager() {
return propertyManager;
}
/**
* Returns the resource info for the identified resource.
* null is returned if no such resource can be found.
* If the phantom flag is true, phantom resources are considered.
* If the mutable flag is true, the info is opened for change.
*
* This method DOES NOT throw an exception if the resource is not found.
*/
public ResourceInfo getResourceInfo(IPath path, boolean phantom, boolean mutable) {
try {
if (path.segmentCount() == 0) {
ResourceInfo info = (ResourceInfo)tree.getTreeData();
Assert.isNotNull(info, "Tree root info must never be null"); //$NON-NLS-1$
return info;
}
ResourceInfo result = null;
if (!tree.includes(path))
return null;
if (mutable)
result = (ResourceInfo) tree.openElementData(path);
else
result = (ResourceInfo) tree.getElementData(path);
if (result != null && (!phantom && result.isSet(M_PHANTOM)))
return null;
return result;
} catch (IllegalArgumentException e) {
return null;
}
}
/**
* @see IWorkspace#getRoot
*/
public IWorkspaceRoot getRoot() {
return defaultRoot;
}
public SaveManager getSaveManager() {
return saveManager;
}
/**
* @see IWorkspace#getSynchronizer
*/
public ISynchronizer getSynchronizer() {
return synchronizer;
}
/**
* Returns the installed team hook. Never returns null.
*/
protected TeamHook getTeamHook() {
if (teamHook == null)
initializeTeamHook();
return teamHook;
}
/**
* We should not have direct references to this field. All references should go through
* this method.
*/
public WorkManager getWorkManager() throws CoreException {
if (workManager == null) {
String message = Policy.bind("resources.shutdown"); //$NON-NLS-1$
throw new ResourceException(new ResourceStatus(IResourceStatus.INTERNAL_ERROR, null, message));
}
return workManager;
}
/**
* A file modification validator hasn't been initialized. Check the extension point and
* try to create a new validator if a user has one defined as an extension.
*/
protected void initializeValidator() {
shouldValidate = false;
IConfigurationElement[] configs = Platform.getPluginRegistry().getConfigurationElementsFor(ResourcesPlugin.PI_RESOURCES, ResourcesPlugin.PT_FILE_MODIFICATION_VALIDATOR);
// no-one is plugged into the extension point so disable validation
if (configs == null || configs.length == 0) {
return;
}
// can only have one defined at a time. log a warning, disable validation, but continue with
// the #setContents (e.g. don't throw an exception)
if (configs.length > 1) {
//XXX: shoud provide a meaningful status code
IStatus status = new ResourceStatus(IResourceStatus.ERROR, 1, null, Policy.bind("resources.oneValidator"), null); //$NON-NLS-1$
ResourcesPlugin.getPlugin().getLog().log(status);
return;
}
// otherwise we have exactly one validator extension. Try to create a new instance
// from the user-specified class.
try {
IConfigurationElement config = configs[0];
validator = (IFileModificationValidator) config.createExecutableExtension("class"); //$NON-NLS-1$
shouldValidate = true;
} catch (CoreException e) {
//XXX: shoud provide a meaningful status code
IStatus status = new ResourceStatus(IResourceStatus.ERROR, 1, null, Policy.bind("resources.initValidator"), e); //$NON-NLS-1$
ResourcesPlugin.getPlugin().getLog().log(status);
}
}
/**
* A move/delete hook hasn't been initialized. Check the extension point and
* try to create a new hook if a user has one defined as an extension. Otherwise
* use the Core's implementation as the default.
*/
protected void initializeMoveDeleteHook() {
try {
IConfigurationElement[] configs = Platform.getPluginRegistry().getConfigurationElementsFor(ResourcesPlugin.PI_RESOURCES, ResourcesPlugin.PT_MOVE_DELETE_HOOK);
// no-one is plugged into the extension point so disable validation
if (configs == null || configs.length == 0) {
return;
}
// can only have one defined at a time. log a warning
if (configs.length > 1) {
//XXX: shoud provide a meaningful status code
IStatus status = new ResourceStatus(IResourceStatus.ERROR, 1, null, Policy.bind("resources.oneHook"), null); //$NON-NLS-1$
ResourcesPlugin.getPlugin().getLog().log(status);
return;
}
// otherwise we have exactly one hook extension. Try to create a new instance
// from the user-specified class.
try {
IConfigurationElement config = configs[0];
moveDeleteHook = (IMoveDeleteHook) config.createExecutableExtension("class"); //$NON-NLS-1$
} catch (CoreException e) {
//XXX: shoud provide a meaningful status code
IStatus status = new ResourceStatus(IResourceStatus.ERROR, 1, null, Policy.bind("resources.initHook"), e); //$NON-NLS-1$
ResourcesPlugin.getPlugin().getLog().log(status);
}
} finally {
// for now just use Core's implementation
if (moveDeleteHook == null)
moveDeleteHook = new MoveDeleteHook();
}
}
/**
* A team hook hasn't been initialized. Check the extension point and
* try to create a new hook if a user has one defined as an extension.
* Otherwise use the Core's implementation as the default.
*/
protected void initializeTeamHook() {
try {
IConfigurationElement[] configs = Platform.getPluginRegistry().getConfigurationElementsFor(ResourcesPlugin.PI_RESOURCES, ResourcesPlugin.PT_TEAM_HOOK);
// no-one is plugged into the extension point so disable validation
if (configs == null || configs.length == 0) {
return;
}
// can only have one defined at a time. log a warning
if (configs.length > 1) {
//XXX: shoud provide a meaningful status code
IStatus status = new ResourceStatus(IResourceStatus.ERROR, 1, null, Policy.bind("resources.oneTeamHook"), null); //$NON-NLS-1$
ResourcesPlugin.getPlugin().getLog().log(status);
return;
}
// otherwise we have exactly one hook extension. Try to create a new instance
// from the user-specified class.
try {
IConfigurationElement config = configs[0];
teamHook = (TeamHook) config.createExecutableExtension("class"); //$NON-NLS-1$
} catch (CoreException e) {
//XXX: shoud provide a meaningful status code
IStatus status = new ResourceStatus(IResourceStatus.ERROR, 1, null, Policy.bind("resources.initTeamHook"), e); //$NON-NLS-1$
ResourcesPlugin.getPlugin().getLog().log(status);
}
} finally {
// default to use Core's implementation
if (teamHook == null)
teamHook = new TeamHook();
}
}
public WorkspaceDescription internalGetDescription() {
return description;
}
/**
* @see IWorkspace
*/
public boolean isAutoBuilding() {
return description.isAutoBuilding();
}
/**
* Returns true if the object at the specified position has any
* other copy in the given array.
*/
private static boolean isDuplicate(Object[] array, int position) {
if (array == null || position >= array.length)
return false;
for (int j = position - 1; j >= 0; j--)
if (array[j].equals(array[position]))
return true;
return false;
}
/**
* @see IWorkspace#isOpen
*/
public boolean isOpen() {
return openFlag;
}
/**
* Returns true if the given file system locations overlap (they are the same,
* or one is a proper prefix of the other), and false otherwise.
* Does the right thing with respect to case insensitive platforms.
*/
protected boolean isOverlapping(IPath location1, IPath location2) {
IPath one = location1;
IPath two = location2;
// If we are on a case-insensitive file system then convert to all lowercase.
if (!CoreFileSystemLibrary.isCaseSensitive()) {
one = new Path(location1.toOSString().toLowerCase());
two = new Path(location2.toOSString().toLowerCase());
}
return one.isPrefixOf(two) || two.isPrefixOf(one);
}
public boolean isTreeLocked() {
if (overrideTreeLock)
return false;
return treeLocked;
}
/**
* Link the given tree into the receiver's tree at the specified resource.
*/
protected void linkTrees(IPath path, ElementTree[] newTrees) throws CoreException {
tree = tree.mergeDeltaChain(path, newTrees);
}
/**
* @see IWorkspace#loadProjectDescription
* @since 2.0
*/
public IProjectDescription loadProjectDescription(IPath path) throws CoreException {
IProjectDescription result = null;
IOException e = null;
try {
result = (IProjectDescription) new ModelObjectReader().read(path);
if (result != null) {
// check to see if we are using in the default area or not. use java.io.File for
// testing equality because it knows better w.r.t. drives and case sensitivity
IPath user = path.removeLastSegments(1);
IPath platform = Platform.getLocation().append(result.getName());
if (!user.toFile().equals(platform.toFile()))
result.setLocation(user);
}
} catch (IOException ex) {
e = ex;
}
if (result == null || e != null) {
String message = Policy.bind("resources.errorReadProject", path.toOSString());//$NON-NLS1 //$NON-NLS-1$
IStatus status = new Status(IStatus.ERROR, ResourcesPlugin.PI_RESOURCES, IResourceStatus.FAILED_READ_METADATA, message, e);
throw new ResourceException(status);
}
return result;
}
/*
* @see IWorkspace#move
*/
public IStatus move(IResource[] resources, IPath destination, int updateFlags, IProgressMonitor monitor) throws CoreException {
monitor = Policy.monitorFor(monitor);
try {
int opWork = Math.max(resources.length, 1);
int totalWork = Policy.totalWork * opWork / Policy.opWork;
String message = Policy.bind("resources.moving.0"); //$NON-NLS-1$
monitor.beginTask(message, totalWork);
Assert.isLegal(resources != null);
if (resources.length == 0)
return ResourceStatus.OK_STATUS;
resources = (IResource[]) resources.clone(); // to avoid concurrent changes to this array
IPath parentPath = null;
message = Policy.bind("resources.moveProblem"); //$NON-NLS-1$
MultiStatus status = new MultiStatus(ResourcesPlugin.PI_RESOURCES, IResourceStatus.INTERNAL_ERROR, message, null);
try {
prepareOperation();
beginOperation(true);
for (int i = 0; i < resources.length; i++) {
Policy.checkCanceled(monitor);
Resource resource = (Resource) resources[i];
if (resource == null || isDuplicate(resources, i)) {
monitor.worked(1);
continue;
}
// test siblings
if (parentPath == null)
parentPath = resource.getFullPath().removeLastSegments(1);
if (parentPath.equals(resource.getFullPath().removeLastSegments(1))) {
// test move requirements
try {
IStatus requirements = resource.checkMoveRequirements(destination.append(resource.getName()), resource.getType(), updateFlags);
if (requirements.isOK()) {
try {
resource.move(destination.append(resource.getName()), updateFlags, Policy.subMonitorFor(monitor, 1));
} catch (CoreException e) {
status.merge(e.getStatus());
}
} else {
monitor.worked(1);
status.merge(requirements);
}
} catch (CoreException e) {
monitor.worked(1);
status.merge(e.getStatus());
}
} else {
monitor.worked(1);
message = Policy.bind("resources.notChild", resource.getFullPath().toString(), parentPath.toString()); //$NON-NLS-1$
status.merge(new ResourceStatus(IResourceStatus.OPERATION_FAILED, resource.getFullPath(), message));
}
}
} catch (OperationCanceledException e) {
getWorkManager().operationCanceled();
throw e;
} finally {
endOperation(true, Policy.subMonitorFor(monitor, totalWork - opWork));
}
if (status.matches(IStatus.ERROR))
throw new ResourceException(status);
return status.isOK() ? (IStatus) ResourceStatus.OK_STATUS : (IStatus) status;
} finally {
monitor.done();
}
}
/**
* @see IWorkspace#move
*/
public IStatus move(IResource[] resources, IPath destination, boolean force, IProgressMonitor monitor) throws CoreException {
int updateFlags = force ? IResource.FORCE : IResource.NONE;
updateFlags |= IResource.KEEP_HISTORY;
return move(resources, destination, updateFlags, monitor);
}
/**
* Moves this resource's subtree to the destination. This operation should only be
* used by move methods. Destination must be a valid destination for this resource.
* The keepSyncInfo boolean is used to indicated whether or not the sync info should
* be moved from the source to the destination.
*/
/* package */ void move(Resource source, IPath destination, int depth, int updateFlags, boolean keepSyncInfo) throws CoreException {
// overlay the tree at the destination path, preserving any important info
// in any already existing resource infos
copyTree(source, destination, depth, updateFlags, keepSyncInfo);
source.fixupAfterMoveSource();
}
/**
* Create and return a new tree element of the given type.
*/
protected ResourceInfo newElement(int type) {
ResourceInfo result = null;
switch (type) {
case IResource.FILE :
case IResource.FOLDER :
result = new ResourceInfo();
break;
case IResource.PROJECT :
result = new ProjectInfo();
break;
case IResource.ROOT :
result = new RootInfo();
break;
}
result.setNodeId(nextNodeId());
result.setModificationStamp(nextModificationStamp());
result.setType(type);
return result;
}
/**
* @see IWorkspace#newProjectDescription
*/
public IProjectDescription newProjectDescription(String projectName) {
IProjectDescription result = new ProjectDescription();
result.setName(projectName);
return result;
}
public Resource newResource(IPath path, int type) {
String message;
switch (type) {
case IResource.FOLDER :
message = "Path must include project and resource name."; //$NON-NLS-1$
Assert.isLegal(path.segmentCount() >= ICoreConstants.MINIMUM_FOLDER_SEGMENT_LENGTH , message);
return new Folder(path.makeAbsolute(), this);
case IResource.FILE :
message = "Path must include project and resource name."; //$NON-NLS-1$
Assert.isLegal(path.segmentCount() >= ICoreConstants.MINIMUM_FILE_SEGMENT_LENGTH, message);
return new File(path.makeAbsolute(), this);
case IResource.PROJECT :
return (Resource) getRoot().getProject(path.lastSegment());
case IResource.ROOT :
return (Resource) getRoot();
}
Assert.isLegal(false);
// will never get here because of assertion.
return null;
}
/**
* Opens a new mutable element tree layer, thus allowing
* modifications to the tree.
*/
public ElementTree newWorkingTree() {
tree = tree.newEmptyDelta();
return tree;
}
/**
* Returns the next, previously unassigned, marker id.
*/
protected long nextMarkerId() {
return nextMarkerId++;
}
public long nextModificationStamp() {
return nextModificationStamp++;
}
public long nextNodeId() {
return nextNodeId++;
}
/**
* Opens this workspace using the data at its location in the local file system.
* This workspace must not be open.
* If the operation succeeds, the result will detail any serious
* (but non-fatal) problems encountered while opening the workspace.
* The status code will be <code>OK</code> if there were no problems.
* An exception is thrown if there are fatal problems opening the workspace,
* in which case the workspace is left closed.
* <p>
* This method is long-running; progress and cancellation are provided
* by the given progress monitor.
* </p>
*
* @param monitor a progress monitor, or <code>null</code> if progress
* reporting and cancellation are not desired
* @return status with code <code>OK</code> if no problems;
* otherwise status describing any serious but non-fatal problems.
*
* @exception CoreException if the workspace could not be opened.
* Reasons include:
* <ul>
* <li> There is no valid workspace structure at the given location
* in the local file system.</li>
* <li> The workspace structure on disk appears to be hopelessly corrupt.</li>
* </ul>
* @see IWorkspace#getLocation
* @see ResourcePlugin#containsWorkspace
*/
public IStatus open(IProgressMonitor monitor) throws CoreException {
// This method is not inside an operation because it is the one responsible for
// creating the WorkManager object (who takes care of operations).
String message = Policy.bind("resources.workspaceOpen"); //$NON-NLS-1$
Assert.isTrue(!isOpen(), message);
if (!getMetaArea().hasSavedWorkspace()) {
message = Policy.bind("resources.readWorkspaceMeta"); //$NON-NLS-1$
throw new ResourceException(IResourceStatus.FAILED_READ_METADATA, Platform.getLocation(), message, null);
}
description = new WorkspacePreferences();
description.setDefaults(Workspace.defaultWorkspaceDescription());
// if we have an old description file, read it (getting rid of it)
WorkspaceDescription oldDescription = getMetaArea().readOldWorkspace();
if (oldDescription != null) {
description.copyFrom(oldDescription);
ResourcesPlugin.getPlugin().savePluginPreferences();
}
// create root location
localMetaArea.locationFor(getRoot()).toFile().mkdirs();
// turn off autobuilding while we open the workspace. This is in
// case an operation is triggered. We don't want to do an autobuild
// just yet. Any changes will be reported the next time we build.
boolean oldBuildFlag = description.isAutoBuilding();
try {
description.setAutoBuilding(false);
IProgressMonitor nullMonitor = Policy.monitorFor(null);
startup(nullMonitor);
//restart the notification manager so it is initialized with the right tree
notificationManager.startup(null);
openFlag = true;
if (crashed || refreshRequested()) {
try {
getRoot().refreshLocal(IResource.DEPTH_INFINITE, null);
} catch (CoreException e) {
//don't fail entire open if refresh failed, just report as minor warning
return e.getStatus();
}
}
return ResourceStatus.OK_STATUS;
} finally {
description.setAutoBuilding(oldBuildFlag);
}
}
/**
* Called before checking the pre-conditions of an operation.
*/
public void prepareOperation() throws CoreException {
getWorkManager().checkIn();
if (!isOpen()) {
String message = Policy.bind("resources.workspaceClosed"); //$NON-NLS-1$
throw new ResourceException(IResourceStatus.OPERATION_FAILED, null, message, null);
}
}
protected boolean refreshRequested() {
String[] args = Platform.getCommandLineArgs();
for (int i = 0; i < args.length; i++)
if (args[i].equalsIgnoreCase(REFRESH_ON_STARTUP))
return true;
return false;
}
/**
* @see IWorkspace
*/
public void removeResourceChangeListener(IResourceChangeListener listener) {
notificationManager.removeListener(listener);
}
/**
* @see IWorkspace
*/
public void removeSaveParticipant(Plugin plugin) {
Assert.isNotNull(plugin, "Plugin must not be null"); //$NON-NLS-1$
saveManager.removeParticipant(plugin);
}
/**
* @see IWorkspace#run
*/
public void run(IWorkspaceRunnable job, IProgressMonitor monitor) throws CoreException {
monitor = Policy.monitorFor(monitor);
try {
monitor.beginTask(null, Policy.totalWork);
try {
prepareOperation();
beginOperation(true);
job.run(Policy.subMonitorFor(monitor, Policy.opWork, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK));
} catch (OperationCanceledException e) {
getWorkManager().operationCanceled();
throw e;
} finally {
endOperation(false, Policy.subMonitorFor(monitor, Policy.buildWork));
}
} finally {
monitor.done();
}
}
/**
* @see IWorkspace
*/
public IStatus save(boolean full, IProgressMonitor monitor) throws CoreException {
String message;
// if a full save was requested, and this is a top-level op, try the save. Otherwise
// fail the operation.
if (full) {
// If the workmanager thread is null or is different than this thread
// it is OK to start the save because it will wait until the other thread
// is finished. Otherwise, someone in this thread has tried to do a save
// inside of an operation (which is not allowed by the spec).
if (getWorkManager().getCurrentOperationThread() == Thread.currentThread()) {
message = Policy.bind("resources.saveOp"); //$NON-NLS-1$
throw new ResourceException(IResourceStatus.OPERATION_FAILED, null, message, null);
}
return saveManager.save(ISaveContext.FULL_SAVE, null, monitor);
}
// A snapshot was requested. Start an operation (if not already started) and
// signal that a snapshot should be done at the end.
try {
prepareOperation();
beginOperation(false);
saveManager.requestSnapshot();
message = Policy.bind("resources.snapRequest"); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.OK, message);
} finally {
endOperation(false, null);
}
}
public void setCrashed(boolean value) {
crashed = value;
}
/**
* @see IWorkspace
*/
public void setDescription(IWorkspaceDescription value) throws CoreException {
// if both the old and new description's build orders are null, leave the
// workspace's build order slot because it is caching the computed order.
// Otherwise, set the slot to null to force recomputation or building from the description.
WorkspaceDescription newDescription = (WorkspaceDescription) value;
String[] newOrder = newDescription.getBuildOrder(false);
if (description.getBuildOrder(false) != null || newOrder != null)
buildOrder = null;
//if autobuild has just been turned on, indicate that a build is necessary
if (!description.isAutoBuilding() && newDescription.isAutoBuilding())
forceBuild = true;
description.copyFrom(newDescription);
Policy.setupAutoBuildProgress(description.isAutoBuilding());
ResourcesPlugin.getPlugin().savePluginPreferences();
}
public void setTreeLocked(boolean locked) {
treeLocked = locked;
}
public void setWorkspaceLock(WorkspaceLock lock) {
workManager.setWorkspaceLock(lock);
}
private boolean shouldBuild(boolean hasTreeChanges) throws CoreException {
//check if workspace description changes necessitate a build
if (forceBuild) {
forceBuild = false;
return true;
}
return hasTreeChanges && getWorkManager().shouldBuild();
}
protected void shutdown(IProgressMonitor monitor) throws CoreException {
monitor = Policy.monitorFor(monitor);
try {
IManager[] managers = { buildManager, notificationManager, propertyManager, pathVariableManager, fileSystemManager, markerManager, saveManager, workManager, aliasManager};
monitor.beginTask(null, managers.length);
String message = Policy.bind("resources.shutdownProblems"); //$NON-NLS-1$
MultiStatus status = new MultiStatus(ResourcesPlugin.PI_RESOURCES, IResourceStatus.INTERNAL_ERROR, message, null);
// best effort to shutdown every object and free resources
for (int i = 0; i < managers.length; i++) {
IManager manager = managers[i];
if (manager == null)
monitor.worked(1);
else {
try {
manager.shutdown(Policy.subMonitorFor(monitor, 1));
} catch (Exception e) {
message = Policy.bind("resources.shutdownProblems"); //$NON-NLS-1$
status.add(new Status(Status.ERROR, ResourcesPlugin.PI_RESOURCES, IResourceStatus.INTERNAL_ERROR, message, e));
}
}
}
buildManager = null;
notificationManager = null;
propertyManager = null;
pathVariableManager = null;
fileSystemManager = null;
markerManager = null;
synchronizer = null;
saveManager = null;
workManager = null;
if (!status.isOK())
throw new CoreException(status);
} finally {
monitor.done();
}
}
/**
* @see IWorkspace#sortNatureSet(String[])
*/
public String[] sortNatureSet(String[] natureIds) {
return natureManager.sortNatureSet(natureIds);
}
protected void startup(IProgressMonitor monitor) throws CoreException {
// ensure the tree is locked during the startup notification
workManager = new WorkManager(this);
workManager.startup(null);
fileSystemManager = new FileSystemResourceManager(this);
fileSystemManager.startup(monitor);
propertyManager = new PropertyManager(this);
propertyManager.startup(monitor);
pathVariableManager = new PathVariableManager(this);
pathVariableManager.startup(null);
natureManager = new NatureManager();
natureManager.startup(null);
buildManager = new BuildManager(this);
buildManager.startup(null);
notificationManager = new NotificationManager(this);
notificationManager.startup(null);
markerManager = new MarkerManager(this);
markerManager.startup(null);
synchronizer = new Synchronizer(this);
saveManager = new SaveManager(this);
saveManager.startup(null);
//must start after save manager, because (read) access to tree is needed
aliasManager = new AliasManager(this);
aliasManager.startup(null);
treeLocked = false; // unlock the tree.
}
/**
* Returns a string representation of this working state's
* structure suitable for debug purposes.
*/
public String toDebugString() {
final StringBuffer buffer = new StringBuffer("\nDump of " + toString() + ":\n"); //$NON-NLS-1$ //$NON-NLS-2$
buffer.append(" parent: " + tree.getParent()); //$NON-NLS-1$
IElementContentVisitor visitor = new IElementContentVisitor() {
public boolean visitElement(ElementTree tree, IPathRequestor requestor, Object elementContents) {
buffer.append("\n " + requestor.requestPath() + ": " + elementContents); //$NON-NLS-1$ //$NON-NLS-2$
return true;
}
};
new ElementTreeIterator(tree, Path.ROOT).iterate(visitor);
return buffer.toString();
}
public void updateModificationStamp(ResourceInfo info) {
info.setModificationStamp(nextModificationStamp());
}
/* (non-javadoc)
* Method declared on IWorkspace.
*/
public IStatus validateEdit(final IFile[] files, final Object context) {
// if validation is turned off then just return
if (!shouldValidate) {
String message = Policy.bind("resources.readOnly2"); //$NON-NLS-1$
MultiStatus result = new MultiStatus(ResourcesPlugin.PI_RESOURCES, IStatus.OK, message, null);
for (int i=0; i<files.length; i++) {
if (files[i].isReadOnly()) {
IPath filePath = files[i].getFullPath();
message = Policy.bind("resources.readOnly", filePath.toString()); //$NON-NLS-1$
result.add(new ResourceStatus(IResourceStatus.FAILED_WRITE_LOCAL, filePath, message));
}
}
return result.isOK() ? ResourceStatus.OK_STATUS : (IStatus) result;
}
// first time through the validator hasn't been initialized so try and create it
if (validator == null)
initializeValidator();
// we were unable to initialize the validator. Validation has been turned off and
// a warning has already been logged so just return.
if (validator == null)
return ResourceStatus.OK_STATUS;
// otherwise call the API and throw an exception if appropriate
final IStatus[] status = new IStatus[1];
ISafeRunnable body = new ISafeRunnable() {
public void run() throws Exception {
status[0] = validator.validateEdit(files, context);
}
public void handleException(Throwable exception) {
status[0] = new ResourceStatus(IResourceStatus.ERROR, null, Policy.bind("resources.errorValidator"), exception); //$NON-NLS-1$
}
};
Platform.run(body);
return status[0];
}
/* (non-javadoc)
* Method declared on IWorkspace.
*/
public IStatus validateLinkLocation(IResource resource, IPath unresolvedLocation) {
String message;
//check if resource linking is disabled
if (ResourcesPlugin.getPlugin().getPluginPreferences().getBoolean(ResourcesPlugin.PREF_DISABLE_LINKING)) {
message = Policy.bind("links.workspaceVeto", resource.getName());//$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, resource.getFullPath(), message);
}
//check that the resource has a project as its parent
IContainer parent = resource.getParent();
if (parent == null || parent.getType() != IResource.PROJECT) {
message = Policy.bind("links.parentNotProject", resource.getName());//$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, resource.getFullPath(), message);
}
if (!parent.isAccessible()) {
message = Policy.bind("links.parentNotAccessible", resource.getFullPath().toString());//$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, resource.getFullPath(), message);
}
IPath location = getPathVariableManager().resolvePath(unresolvedLocation);
//check nature veto
String[] natureIds = ((Project)parent).internalGetDescription().getNatureIds();
IStatus result = getNatureManager().validateLinkCreation(natureIds);
if (!result.isOK())
return result;
//check team provider veto
if (resource.getType() == IResource.FILE)
result = getTeamHook().validateCreateLink((IFile)resource, IResource.NONE, location);
else
result = getTeamHook().validateCreateLink((IFolder)resource, IResource.NONE, location);
if (!result.isOK())
return result;
//check the standard path name restrictions
int segmentCount = location.segmentCount();
for (int i = 0; i < segmentCount; i++) {
result = validateName(location.segment(i), resource.getType());
if (!result.isOK())
return result;
}
//if the location doesn't have a device, see if the OS will assign one
if (location.isAbsolute() && location.getDevice() == null)
location = new Path(location.toFile().getAbsolutePath());
// test if the given location overlaps the platform metadata location
IPath testLocation = getMetaArea().getLocation();
if (isOverlapping(location, testLocation)) {
message = Policy.bind("links.invalidLocation", location.toOSString()); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, resource.getFullPath(), message);
}
//test if the given path overlaps the location of the given project
testLocation = resource.getProject().getLocation();
if (isOverlapping(location, testLocation)) {
message = Policy.bind("links.locationOverlapsProject", location.toOSString()); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, resource.getFullPath(), message);
}
if (location.isEmpty()) {
message = Policy.bind("links.noPath");//$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, resource.getFullPath(), message);
}
//warnings (all errors must be checked before all warnings)
//check that the location is absolute
if (!location.isAbsolute()) {
//we know there is at least one segment, because of previous isEmpty check
message = Policy.bind("pathvar.undefined", location.toOSString(), location.segment(0));//$NON-NLS-1$
return new ResourceStatus(IResourceStatus.VARIABLE_NOT_DEFINED_WARNING, resource.getFullPath(), message);
}
// Iterate over each known project and ensure that the location does not
// conflict with any project locations or linked resource locations
IProject[] projects = getRoot().getProjects();
for (int i = 0; i < projects.length; i++) {
IProject project = (IProject) projects[i];
// since we are iterating over the project in the workspace, we
// know that they have been created before and must have a description
IProjectDescription desc = ((Project) project).internalGetDescription();
testLocation = desc.getLocation();
if (testLocation != null && isOverlapping(location, testLocation)) {
message = Policy.bind("links.overlappingResource", location.toOSString()); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.OVERLAPPING_LOCATION, resource.getFullPath(), message);
}
//iterate over linked resources and check for overlap
if (!project.isOpen())
continue;
IResource[] children = null;
try {
children = project.members();
} catch (CoreException e) {
//ignore projects that cannot be accessed
}
if (children == null)
continue;
for (int j = 0; j < children.length; j++) {
if (children[j].isLinked()) {
testLocation = children[j].getLocation();
if (testLocation != null && isOverlapping(location, testLocation)) {
message = Policy.bind("links.overlappingResource", location.toOSString()); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.OVERLAPPING_LOCATION, resource.getFullPath(), message);
}
}
}
}
return ResourceStatus.OK_STATUS;
}
/**
* @see IWorkspace#validateName
*/
public IStatus validateName(String segment, int type) {
String message;
/* segment must not be null */
if (segment == null) {
message = Policy.bind("resources.nameNull"); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message);
}
// cannot be an empty string
if (segment.length() == 0) {
message = Policy.bind("resources.nameEmpty"); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message);
}
/* segment must not begin or end with a whitespace */
if (Character.isWhitespace(segment.charAt(0)) || Character.isWhitespace(segment.charAt(segment.length() - 1))) {
message = Policy.bind("resources.invalidWhitespace",segment); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message);
}
/* segment must not end with a dot */
if (segment.endsWith(".")) { //$NON-NLS-1$
message = Policy.bind("resources.invalidDot", segment); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message);
}
/* test invalid characters */
char[] chars = OS.INVALID_RESOURCE_CHARACTERS;
for (int i = 0; i < chars.length; i++)
if (segment.indexOf(chars[i]) != -1) {
message = Policy.bind("resources.invalidCharInName", String.valueOf(chars[i]), segment); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message);
}
/* test invalid OS names */
if (!OS.isNameValid(segment)) {
message = Policy.bind("resources.invalidName", segment); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message);
}
return ResourceStatus.OK_STATUS;
}
/**
* @see IWorkspace#validateNatureSet(String[])
*/
public IStatus validateNatureSet(String[] natureIds) {
return natureManager.validateNatureSet(natureIds);
}
/**
* @see IWorkspace#validatePath
*/
public IStatus validatePath(String path, int type) {
String message;
/* path must not be null */
if (path == null) {
message = Policy.bind("resources.pathNull"); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message);
}
/* path must not have a device separator */
if (path.indexOf(IPath.DEVICE_SEPARATOR) != -1) {
message = Policy.bind("resources.invalidCharInPath", String.valueOf(IPath.DEVICE_SEPARATOR), path); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message);
}
/* path must not be the root path */
IPath testPath = new Path(path);
if (testPath.isRoot()) {
message = Policy.bind("resources.invalidRoot"); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message);
}
/* path must be absolute */
if (!testPath.isAbsolute()) {
message = Policy.bind("resources.mustBeAbsolute", path); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message);
}
/* validate segments */
int numberOfSegments = testPath.segmentCount();
if ((type & IResource.PROJECT) != 0) {
if (numberOfSegments == ICoreConstants.PROJECT_SEGMENT_LENGTH) {
return validateName(testPath.segment(0), IResource.PROJECT);
} else
if (type == IResource.PROJECT) {
message = Policy.bind("resources.projectPath",path); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message);
}
}
if ((type & (IResource.FILE | IResource.FOLDER)) != 0)
if (numberOfSegments >= ICoreConstants.MINIMUM_FILE_SEGMENT_LENGTH) {
IStatus status = validateName(testPath.segment(0), IResource.PROJECT);
if (!status.isOK())
return status;
int fileFolderType = type &= ~IResource.PROJECT;
int segmentCount = testPath.segmentCount();
// ignore first segment (the project)
for (int i = 1; i < segmentCount; i++) {
status = validateName(testPath.segment(i), fileFolderType);
if (!status.isOK())
return status;
}
return ResourceStatus.OK_STATUS;
} else {
message = Policy.bind("resources.resourcePath",path); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message);
}
message = Policy.bind("resources.invalidPath", path); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message);
}
/**
* @see IWorkspace#validateProjectLocation
*/
public IStatus validateProjectLocation(IProject context, IPath unresolvedLocation) {
String message;
// the default default is ok for all projects
if (unresolvedLocation == null) {
return ResourceStatus.OK_STATUS;
}
//check the standard path name restrictions
IPath location = getPathVariableManager().resolvePath(unresolvedLocation);
int segmentCount = location.segmentCount();
for (int i = 0; i < segmentCount; i++) {
IStatus result = validateName(location.segment(i), IResource.PROJECT);
if (!result.isOK())
return result;
}
//check that the location is absolute
if (!location.isAbsolute()) {
if (location.segmentCount() > 0)
message = Policy.bind("pathvar.undefined", location.toOSString(), location.segment(0));//$NON-NLS-1$
else
message = Policy.bind("links.noPath");//$NON-NLS-1$
return new ResourceStatus(IResourceStatus.VARIABLE_NOT_DEFINED, null, message);
}
//if the location doesn't have a device, see if the OS will assign one
if (location.getDevice() == null)
location = new Path(location.toFile().getAbsolutePath());
// test if the given location overlaps the default default location
IPath defaultDefaultLocation = Platform.getLocation();
if (isOverlapping(location, defaultDefaultLocation)) {
message = Policy.bind("resources.overlapLocal", location.toString(), defaultDefaultLocation.toString()); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message);
}
// Iterate over each known project and ensure that the location does not
// conflict with any of their already defined locations.
IProject[] projects = getRoot().getProjects();
for (int j = 0; j < projects.length; j++) {
IProject project = (IProject) projects[j];
// since we are iterating over the project in the workspace, we
// know that they have been created before and must have a description
IProjectDescription desc = ((Project) project).internalGetDescription();
IPath definedLocalLocation = desc.getLocation();
// if the project uses the default location then continue
if (definedLocalLocation == null)
continue;
//tolerate locations being the same if this is the project being tested
if (project.equals(context) && definedLocalLocation.equals(location))
continue;
if (isOverlapping(location, definedLocalLocation)) {
message = Policy.bind("resources.overlapLocal", location.toString(), definedLocalLocation.toString()); //$NON-NLS-1$
return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message);
}
}
return ResourceStatus.OK_STATUS;
}
/**
* Internal method. To be called only from the following methods:
* <ul>
* <li><code>IFile#appendContents</code></li>
* <li><code>IFile#setContents(InputStream, boolean, boolean, IProgressMonitor)</code></li>
* <li><code>IFile#setContents(IFileState, boolean, boolean, IProgressMonitor)</code></li>
* </ul>
*
* @see IFileModificationValidator#validateSave
*/
protected void validateSave(final IFile file) throws CoreException {
// if validation is turned off then just return
if (!shouldValidate)
return;
// first time through the validator hasn't been initialized so try and create it
if (validator == null)
initializeValidator();
// we were unable to initialize the validator. Validation has been turned off and
// a warning has already been logged so just return.
if (validator == null)
return;
// otherwise call the API and throw an exception if appropriate
final IStatus[] status = new IStatus[1];
ISafeRunnable body = new ISafeRunnable() {
public void run() throws Exception {
status[0] = validator.validateSave(file);
}
public void handleException(Throwable exception) {
status[0] = new ResourceStatus(IResourceStatus.ERROR, null, Policy.bind("resources.errorValidator"), exception); //$NON-NLS-1$
}
};
Platform.run(body);
if (!status[0].isOK())
throw new ResourceException(status[0]);
}
}
| true | false | null | null |
diff --git a/Sparx/src/java/main/com/netspective/sparx/form/field/type/CurrencyField.java b/Sparx/src/java/main/com/netspective/sparx/form/field/type/CurrencyField.java
index 585ed9da..430b4b95 100644
--- a/Sparx/src/java/main/com/netspective/sparx/form/field/type/CurrencyField.java
+++ b/Sparx/src/java/main/com/netspective/sparx/form/field/type/CurrencyField.java
@@ -1,294 +1,294 @@
/*
* Copyright (c) 2000-2002 Netspective Corporation -- all rights reserved
*
* Netspective Corporation permits redistribution, modification and use
* of this file in source and binary form ("The Software") under the
* Netspective Source License ("NSL" or "The License"). The following
* conditions are provided as a summary of the NSL but the NSL remains the
* canonical license and must be accepted before using The Software. Any use of
* The Software indicates agreement with the NSL.
*
* 1. Each copy or derived work of The Software must preserve the copyright
* notice and this notice unmodified.
*
* 2. Redistribution of The Software is allowed in object code form only
* (as Java .class files or a .jar file containing the .class files) and only
* as part of an application that uses The Software as part of its primary
* functionality. No distribution of the package is allowed as part of a software
* development kit, other library, or development tool without written consent of
* Netspective Corporation. Any modified form of The Software is bound by
* these same restrictions.
*
* 3. Redistributions of The Software in any form must include an unmodified copy of
* The License, normally in a plain ASCII text file unless otherwise agreed to,
* in writing, by Netspective Corporation.
*
* 4. The names "Sparx" and "Netspective" are trademarks of Netspective
* Corporation and may not be used to endorse products derived from The
* Software without without written consent of Netspective Corporation. "Sparx"
* and "Netspective" may not appear in the names of products derived from The
* Software without written consent of Netspective Corporation.
*
* 5. Please attribute functionality to Sparx where possible. We suggest using the
* "powered by Sparx" button or creating a "powered by Sparx(tm)" link to
* http://www.netspective.com for each application using Sparx.
*
* The Software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
* IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY DISCLAIMED.
*
* NETSPECTIVE CORPORATION AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES
* SUFFERED BY LICENSEE OR ANY THIRD PARTY AS A RESULT OF USING OR DISTRIBUTING
* THE SOFTWARE. IN NO EVENT WILL NETSPECTIVE OR ITS LICENSORS BE LIABLE
* FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
* CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
* REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
* INABILITY TO USE THE SOFTWARE, EVEN IF HE HAS BEEN ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGES.
*
* @author Shahid N. Shah
*/
/**
- * $Id: CurrencyField.java,v 1.9 2004-03-23 17:49:48 aye.thu Exp $
+ * $Id: CurrencyField.java,v 1.10 2004-03-23 18:15:15 aye.thu Exp $
*/
package com.netspective.sparx.form.field.type;
import com.netspective.commons.value.exception.ValueException;
import com.netspective.commons.xdm.XdmEnumeratedAttribute;
import com.netspective.sparx.form.DialogContext;
import com.netspective.sparx.form.field.DialogField;
import com.netspective.sparx.form.field.DialogFieldValue;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.Locale;
/**
* NOTE: JSDK 1.4 and above supports the java.util.Currency class. Right now, we're not using it
* but we might want to use it.
*/
public class CurrencyField extends TextField
{
public static class NegativePosLocation extends XdmEnumeratedAttribute
{
public static final String[] VALUES = new String[] { "before-symbol", "after-symbol" };
public static final int BEFORE_SYMBOL = 0;
public static final int AFTER_SYMBOL = 1;
public NegativePosLocation()
{
}
public NegativePosLocation(int valueIndex)
{
super(valueIndex);
}
public String[] getValues()
{
return VALUES;
}
}
public class CurrencyFieldState extends State
{
public class CurrencyFieldValue extends BasicStateValue
{
public Class getValueHolderClass()
{
return Double.class;
}
public String getTextValue()
{
if (!isValid())
return getInvalidText();
if (getValue() instanceof Double)
{
// sets the format for the currency value bacause toString() of a double produces
// exponential formats when the value is large
- DecimalFormat format = new DecimalFormat("###0.0#");
+ DecimalFormat format = new DecimalFormat("###0.##");
return format.format(((Double)getValue()).doubleValue());
}
return getValue() != null ? getValue().toString() : null;
}
/**
*
* @param value the value passed here should have been verified already using either the display pattern or the submit pattern
* @throws ValueException
*/
public void setTextValue(String value) throws ValueException
{
if(value == null || value.length() == 0)
{
setValue((Double) null);
return;
}
try
{
// NumberFormat's parse() method can be used if the 'value' was already in the Locale's format.
// e.g. English in US Locale dictates that a currency value format is in $123.11 for
// positive values and ($123.11) for negative values. So, the following values -$123.11, $-123.11,
// 123.11, and -123.11 will not work and will throw a ParseException.
//Number number = format.parse(value);
if (value.indexOf(currencySymbol) >= 0)
{
// display value can contain the currency symbol
setValue(value);
}
else
{
// submit value does not contain the currency symbol
setValue(new Double(value));
}
}
catch (Exception e)
{
setInvalidText(value);
invalidate(getDialogContext(), getErrorCaption().getTextValue(getDialogContext()) + " requires a value in currency format ("+ e.getMessage() +").");
}
}
}
public CurrencyFieldState(DialogContext dc, DialogField field)
{
super(dc, field);
}
public DialogFieldValue constructValueInstance()
{
return new CurrencyFieldValue();
}
}
private Locale locale = Locale.getDefault() != null ? Locale.getDefault() : Locale.US;
private NumberFormat format;
private String currencySymbol;
private char decimalSymbol;
private int decimalsRequired = -1;
private NegativePosLocation negativePos = new NegativePosLocation(NegativePosLocation.BEFORE_SYMBOL);
public CurrencyField()
{
setDecimalsRequired(2);
setLocale(Locale.getDefault());
setNegativePos(new NegativePosLocation(NegativePosLocation.BEFORE_SYMBOL));
}
public DialogField.State constructStateInstance(DialogContext dc)
{
return new CurrencyFieldState(dc, this);
}
public Class getStateClass()
{
return CurrencyFieldState.class;
}
public Class getStateValueClass()
{
return CurrencyFieldState.CurrencyFieldValue.class;
}
protected void setupPatterns()
{
if(decimalsRequired < 0)
setDecimalsRequired(0);
format = NumberFormat.getCurrencyInstance(locale);
if(decimalsRequired >= 0)
{
format.setMinimumFractionDigits(decimalsRequired);
format.setMaximumFractionDigits(decimalsRequired);
}
DecimalFormatSymbols cSymbol = new DecimalFormatSymbols(locale);
currencySymbol = cSymbol.getCurrencySymbol();
decimalSymbol = cSymbol.getDecimalSeparator();
String decimalExpr = "";
if(decimalsRequired > 0)
decimalExpr = "(["+ decimalSymbol +"][\\d]{1," + decimalsRequired + "})?";
else
decimalExpr = "";
if(negativePos == null || negativePos.getValueIndex() == NegativePosLocation.BEFORE_SYMBOL)
{
setRegExpr("^([-])?([\\" + currencySymbol + "])?([\\d]+)" + decimalExpr + "$");
setDisplayPattern("s/^([-])?([\\" + currencySymbol +
"])?([\\d]+)" + decimalExpr + "$/$1\\" + currencySymbol + "$3$4/g");
setSubmitPattern("s/" + "^([-])?([\\" + currencySymbol + "])?([\\d]+)" + decimalExpr +
"$/$1$3$4/g");
setInvalidRegExMessage("Currency values must have the format " +
currencySymbol + "xxx.xx for positive values and " +
- "-" + currencySymbol + "xxx.xx for negative values.");
+ "-" + currencySymbol + "xxx.xx for negative values. (decimals = " + decimalsRequired + ")");
}
else if(negativePos.getValueIndex() == NegativePosLocation.AFTER_SYMBOL)
{
setRegExpr("^([\\" + currencySymbol + "])?([-]?[\\d]+)" + decimalExpr + "$");
setDisplayPattern("s/" + "^([\\" + currencySymbol + "])?([-]?[\\d]+)" + decimalExpr + "$/\\" + currencySymbol + "$2$3/g");
setSubmitPattern("s/" + "^([\\" + currencySymbol + "])?([-]?[\\d]+)" + decimalExpr + "$" + "/$2$3/g");
setInvalidRegExMessage("Currency values must have the format " +
currencySymbol + "xxx.xx for positive values and " +
- currencySymbol + "-xxx.xx for negative values.");
+ currencySymbol + "-xxx.xx for negative values. (decimals = " + decimalsRequired + ")");
}
}
public Locale getLocale()
{
return locale;
}
public void setLocale(Locale locale)
{
this.locale = locale;
setupPatterns();
}
/**
* Gets the number of decimal places allowed
*/
public int getDecimalsRequired()
{
return decimalsRequired;
}
/**
* Sets the number of decimal places allowed
*/
public void setDecimalsRequired(int decimalsRequired)
{
this.decimalsRequired = decimalsRequired;
setupPatterns();
}
public NegativePosLocation getNegativePos()
{
return negativePos;
}
public void setNegativePos(NegativePosLocation negativePos)
{
this.negativePos = negativePos;
setupPatterns();
}
/**
* Passes on the phone format to the client side validations
*/
public String getCustomJavaScriptDefn(DialogContext dc)
{
StringBuffer buf = new StringBuffer(super.getCustomJavaScriptDefn(dc));
buf.append("field.currency_symbol = '" + this.currencySymbol + "';\n");
buf.append("field.negative_pos = '" + this.negativePos + "';\n");
buf.append("field.decimal = '" + this.decimalsRequired + "';\n");
return buf.toString();
}
}
| false | false | null | null |
diff --git a/Project/src/projectrts/view/GameView.java b/Project/src/projectrts/view/GameView.java
index 623b4d2..10c82c0 100644
--- a/Project/src/projectrts/view/GameView.java
+++ b/Project/src/projectrts/view/GameView.java
@@ -1,313 +1,311 @@
package projectrts.view;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;
import projectrts.controller.InGameState;
import projectrts.io.MaterialManager;
import projectrts.io.TextureManager;
import projectrts.model.IGame;
import projectrts.model.entities.IEntity;
import projectrts.model.world.INode;
import projectrts.view.controls.MoveControl;
import projectrts.view.spatials.AbstractSpatial;
import projectrts.view.spatials.DebugNodeSpatial;
import projectrts.view.spatials.SpatialFactory;
import com.jme3.app.SimpleApplication;
import com.jme3.material.Material;
import com.jme3.math.Vector3f;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import com.jme3.scene.shape.Box;
import com.jme3.terrain.geomipmap.TerrainLodControl;
import com.jme3.terrain.geomipmap.TerrainQuad;
import com.jme3.terrain.heightmap.AbstractHeightMap;
import com.jme3.terrain.heightmap.ImageBasedHeightMap;
import com.jme3.texture.Texture;
import com.jme3.texture.Texture.WrapMode;
/**
* The in-game view, creating and managing the scene.
* @author Markus Ekstr�m
*
*/
// TODO Markus: PMD: This class has too many methods, consider refactoring it.
public class GameView implements PropertyChangeListener{
private final SimpleApplication app;
private final IGame game;
private final Node entities = new Node("entities"); // The node for all entities
private final Node selected = new Node("selected"); // The node for the selected graphics
private final Node debug = new Node("debug"); // The node for the debugging graphics
private Node terrainNode = new Node("terrain"); // The node for all terrain
private Node mouseEffects = new Node("mouseEffects"); // The node for mouseEffects
// TODO Markus: PMD: Perhaps 'matTerrain' could be replaced by a local variable.
private Material matTerrain;
// TODO Markus: PMD: Perhaps 'terrain' could be replaced by a local variable.
private TerrainQuad terrain;
private float mod = InGameState.MODEL_TO_WORLD; // The modifier value for converting lengths between model and world.
private boolean debugNodes = false;
//TODO Markus: Add javadoc
public GameView(SimpleApplication app, IGame game) {
this.app = app;
this.game = game;
game.getEntityManager().addListener(this);
}
/**
* Initializes the scene.
* @param entitiesList A list containing the initial entities.
* @param controlList The controls for the initial entities.
*/
public void initialize() {
initializeWorld();
initializeDebug();
initializeEntities();
initializeMouseEffects();
this.app.getRootNode().attachChild(selected);
}
/**
* Based on Jmonkey terrain example code
* http://jmonkeyengine.org/wiki/doku.php/jme3:beginner:hello_terrain
*/
private void initializeWorld() {
/** 1. Create terrain material and load four textures into it. */
matTerrain = MaterialManager.INSTANCE.getMaterial("Terrain");
/** 1.1) Add ALPHA map (for red-blue-green coded splat textures) */
matTerrain.setTexture("Alpha",TextureManager.INSTANCE.getTexture("Alpha"));
/** 1.2) Add GRASS texture into the red layer (Tex1). */
Texture grass = TextureManager.INSTANCE.getTexture("Grass");
grass.setWrap(WrapMode.Repeat);
matTerrain.setTexture("Tex1", grass);
matTerrain.setFloat("Tex1Scale", 64f);
/** 1.3) Add WATER texture into the green layer (Tex2) */
Texture water = TextureManager.INSTANCE.getTexture("Water");
water.setWrap(WrapMode.Repeat);
matTerrain.setTexture("Tex2", water);
matTerrain.setFloat("Tex2Scale", 32f);
/** 1.4) Add ROAD texture into the blue layer (Tex3) */
Texture rock = TextureManager.INSTANCE.getTexture("Rock");
rock.setWrap(WrapMode.Repeat);
matTerrain.setTexture("Tex3", rock);
matTerrain.setFloat("Tex3Scale", 128f);
/** 2. Create the height map */
- // TODO Jakob: Move declaration of 'heightmap' to where it actually gets a value
- AbstractHeightMap heightmap = null;
Texture heightMapImage = TextureManager.INSTANCE.getTexture("HeightMap");
- heightmap = new ImageBasedHeightMap(heightMapImage.getImage());
+ AbstractHeightMap heightmap = new ImageBasedHeightMap(heightMapImage.getImage());
heightmap.load();
/** 3. We have prepared material and heightmap.
* Now we create the actual terrain:
* 3.1) Create a TerrainQuad and name it "my terrain".
* 3.2) A good value for terrain tiles is 64x64 -- so we supply 64+1=65.
* 3.3) We prepared a heightmap of size 512x512 -- so we supply 512+1=513.
* 3.4) As LOD step scale we supply Vector3f(1,1,1).
* 3.5) We supply the prepared heightmap itself.
*/
int patchSize = 65;
terrain = new TerrainQuad("my terrain", patchSize, 513, heightmap.getHeightMap());
/** 4. We give the terrain its material, position & scale it, and attach it. */
terrain.setMaterial(matTerrain);
terrain.setLocalTranslation(0, 0, 0);
terrain.setLocalScale(.02f, .01f, .02f);
terrainNode.attachChild(terrain);
app.getRootNode().attachChild(terrainNode);
terrainNode.setLocalTranslation(2, -2, -100);
terrainNode.rotateUpTo(new Vector3f(0f,0f,1f));
/** 5. The LOD (level of detail) depends on were the camera is: */
TerrainLodControl control = new TerrainLodControl(terrain, app.getCamera());
terrain.addControl(control);
}
private void initializeDebug() {
if (debugNodes)
{
integrateNodes(game.getWorld().getNodes());
}
this.app.getRootNode().attachChild(debug);
}
private void initializeEntities() {
integrateNewEntities(game.getEntityManager().getAllEntities());
//Attach the entities node to the root node, connecting it to the world.
this.app.getRootNode().attachChild(entities);
}
private void initializeMouseEffects() {
//Attach the entities node to the root node, connecting it to the world.
this.app.getRootNode().attachChild(mouseEffects);
}
private void integrateNodes(INode[][] nodes)
{
Box[][] nodeShapes = new Box[nodes.length][];
for (int i=0; i<nodes.length; i++)
{
nodeShapes[i] = new Box[nodes[i].length];
for (int j=0; j<nodes[i].length; j++)
{
nodeShapes[i][j] = new Box(
new Vector3f((float)nodes[i][j].getPosition().getX()*mod,
-(float)nodes[i][j].getPosition().getY()*mod,
1),
(0.1f * mod)/2,
(0.1f * mod)/2,
0);
AbstractSpatial nodeSpatial = SpatialFactory.INSTANCE.createNodeSpatial("DebugNodeSpatial",
nodes[i][j].getClass().getSimpleName(), nodeShapes[i][j], nodes[i][j]);
debug.attachChild(nodeSpatial);
}
}
}
private void integrateNewEntities(List<IEntity> newEntities) {
for(int i = 0; i < newEntities.size(); i++) {
integrateNewEntity(newEntities.get(i));
}
}
private void integrateNewEntity(IEntity newEntity) {
// Create shape.
// The location of the entity is initialized to (0, 0, 0) but is then instantly translated to the correct place by moveControl.
// Gets the size from the model and converts it to world size.
Box shape = new Box(new Vector3f(0, 0, 0),
(newEntity.getSize() * mod)/2, (newEntity.getSize() * mod)/2, 0);
// Create spatial.
AbstractSpatial entitySpatial = SpatialFactory.INSTANCE.createEntitySpatial(newEntity.getClass().getSimpleName() + "Spatial",
newEntity.getClass().getSimpleName(), shape, newEntity);
// Attach spatial to the entities node.
entities.attachChild(entitySpatial);
}
private void removeDeadEntity(IEntity entity) {
for(Spatial spatial : entities.getChildren()) {
if(spatial.getControl(MoveControl.class).getEntity().equals(entity)) {
spatial.removeFromParent();
}
}
}
/**
* Draws the selected graphics for all entities in the passed list.
* @param selectedEntities A list of selected entities.
* @param controlList A list of controls for the select-spatials, one for each spatial.
*/
public void drawSelected(List<IEntity> selectedEntities) {
// Remove all previously selected graphics
selected.detachAllChildren();
for(int i = 0; i < selectedEntities.size(); i++) {
// Sets the location of the spatial to (0, 0, -1) to make sure it's behind the entities that use (x, y, 0).
// The control will instantly translate it to the correct location.
Box circle = new Box(new Vector3f(0, 0, -1),
(selectedEntities.get(i).getSize() + 0.3f)/2 * mod, (selectedEntities.get(i).getSize() + 0.3f)/2 * mod, 0);
AbstractSpatial circleSpatial = SpatialFactory.INSTANCE.createEntitySpatial("SelectSpatial", selectedEntities.get(i).getName(), circle, selectedEntities.get(i));
// Attach spatial to the selected node, connecting it to the world.
selected.attachChild(circleSpatial);
}
}
//TODO Jakob: Add javadoc
public void drawNodes(List<projectrts.model.world.INode> coveredNodes){
List<INode> oldNodes = getNodes(mouseEffects.getChildren());
for (INode node : coveredNodes){
if (!oldNodes.contains(node)){
addNodeSpatial(node);
}
}
for (INode node : oldNodes){
if (!coveredNodes.contains(node)){
removeNodeSpatial(node);
}
}
}
private List<INode> getNodes(List<Spatial> coveredNodes){
List<INode> output = new ArrayList<INode>();
DebugNodeSpatial dSpatial;
for (Spatial spatial : coveredNodes){
if(spatial instanceof DebugNodeSpatial){
dSpatial = (DebugNodeSpatial) spatial;
output.add(dSpatial.getNode());
}
}
return output;
}
private void removeNodeSpatial(INode node){
DebugNodeSpatial dSpatial;
for(Spatial spatial: mouseEffects.getChildren()){
if(spatial instanceof DebugNodeSpatial){
dSpatial = (DebugNodeSpatial)spatial;
if(node.equals(dSpatial.getNode())){
mouseEffects.detachChild(dSpatial);
}
}
}
}
private void addNodeSpatial(INode node){
Box nodeBox = new Box(new Vector3f((float)node.getPosition().getX()*mod,
-(float)node.getPosition().getY()*mod,1),
(1f * mod)/2,(1f * mod)/2,0);
AbstractSpatial nodeSpatial =
SpatialFactory.INSTANCE.createNodeSpatial("DebugNodeSpatial",
node.getClass().getSimpleName(), nodeBox, node);
mouseEffects.attachChild(nodeSpatial);
}
//TODO Jakob: Add javadoc
public void clearNodes(){
mouseEffects.detachAllChildren();
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
if(evt.getPropertyName().equals("entityCreated")) {
if(evt.getNewValue() instanceof IEntity) {
integrateNewEntity((IEntity)evt.getNewValue());
}
} else if (evt.getPropertyName().equals("entityRemoved")) {
// TODO Markus: PMD: These nested if statements could be combined
if(evt.getOldValue() instanceof IEntity) {
removeDeadEntity((IEntity)evt.getOldValue());
drawSelected(game.getEntityManager().getSelectedEntities());
}
}
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/src/com/android/gallery3d/data/DecodeUtils.java b/src/com/android/gallery3d/data/DecodeUtils.java
index 29b2aa7..b205576 100644
--- a/src/com/android/gallery3d/data/DecodeUtils.java
+++ b/src/com/android/gallery3d/data/DecodeUtils.java
@@ -1,209 +1,222 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.gallery3d.data;
import com.android.gallery3d.common.BitmapUtils;
import com.android.gallery3d.common.Utils;
import com.android.gallery3d.util.ThreadPool.CancelListener;
import com.android.gallery3d.util.ThreadPool.JobContext;
import android.content.ContentResolver;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.BitmapRegionDecoder;
import android.graphics.Rect;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import java.io.FileDescriptor;
import java.io.FileInputStream;
+import java.io.InputStream;
public class DecodeUtils {
private static final String TAG = "DecodeService";
private static class DecodeCanceller implements CancelListener {
Options mOptions;
public DecodeCanceller(Options options) {
mOptions = options;
}
public void onCancel() {
mOptions.requestCancelDecode();
}
}
public static Bitmap requestDecode(JobContext jc, final String filePath,
Options options) {
if (options == null) options = new Options();
jc.setCancelListener(new DecodeCanceller(options));
return ensureGLCompatibleBitmap(
BitmapFactory.decodeFile(filePath, options));
}
public static Bitmap requestDecode(JobContext jc, FileDescriptor fd, Options options) {
if (options == null) options = new Options();
jc.setCancelListener(new DecodeCanceller(options));
return ensureGLCompatibleBitmap(
BitmapFactory.decodeFileDescriptor(fd, null, options));
}
public static Bitmap requestDecode(JobContext jc, byte[] bytes,
Options options) {
return requestDecode(jc, bytes, 0, bytes.length, options);
}
public static Bitmap requestDecode(JobContext jc, byte[] bytes, int offset,
int length, Options options) {
if (options == null) options = new Options();
jc.setCancelListener(new DecodeCanceller(options));
return ensureGLCompatibleBitmap(
BitmapFactory.decodeByteArray(bytes, offset, length, options));
}
public static Bitmap requestDecode(JobContext jc, final String filePath,
Options options, int targetSize) {
FileInputStream fis = null;
try {
fis = new FileInputStream(filePath);
FileDescriptor fd = fis.getFD();
return requestDecode(jc, fd, options, targetSize);
} catch (Exception ex) {
Log.w(TAG, ex);
return null;
} finally {
Utils.closeSilently(fis);
}
}
public static Bitmap requestDecode(JobContext jc, FileDescriptor fd,
Options options, int targetSize) {
if (options == null) options = new Options();
jc.setCancelListener(new DecodeCanceller(options));
options.inJustDecodeBounds = true;
BitmapFactory.decodeFileDescriptor(fd, null, options);
if (jc.isCancelled()) return null;
options.inSampleSize = BitmapUtils.computeSampleSizeLarger(
options.outWidth, options.outHeight, targetSize);
options.inJustDecodeBounds = false;
Bitmap result = BitmapFactory.decodeFileDescriptor(fd, null, options);
// We need to resize down if the decoder does not support inSampleSize.
// (For example, GIF images.)
result = BitmapUtils.resizeDownIfTooBig(result, targetSize, true);
return ensureGLCompatibleBitmap(result);
}
/**
* Decodes the bitmap from the given byte array if the image size is larger than the given
* requirement.
*
* Note: The returned image may be resized down. However, both width and height must be
* larger than the <code>targetSize</code>.
*/
public static Bitmap requestDecodeIfBigEnough(JobContext jc, byte[] data,
Options options, int targetSize) {
if (options == null) options = new Options();
jc.setCancelListener(new DecodeCanceller(options));
options.inJustDecodeBounds = true;
BitmapFactory.decodeByteArray(data, 0, data.length, options);
if (jc.isCancelled()) return null;
if (options.outWidth < targetSize || options.outHeight < targetSize) {
return null;
}
options.inSampleSize = BitmapUtils.computeSampleSizeLarger(
options.outWidth, options.outHeight, targetSize);
options.inJustDecodeBounds = false;
return ensureGLCompatibleBitmap(
BitmapFactory.decodeByteArray(data, 0, data.length, options));
}
public static Bitmap requestDecode(JobContext jc,
FileDescriptor fileDescriptor, Rect paddings, Options options) {
if (options == null) options = new Options();
jc.setCancelListener(new DecodeCanceller(options));
return ensureGLCompatibleBitmap(BitmapFactory.decodeFileDescriptor
(fileDescriptor, paddings, options));
}
// TODO: This function should not be called directly from
// DecodeUtils.requestDecode(...), since we don't have the knowledge
// if the bitmap will be uploaded to GL.
public static Bitmap ensureGLCompatibleBitmap(Bitmap bitmap) {
if (bitmap == null || bitmap.getConfig() != null) return bitmap;
Bitmap newBitmap = bitmap.copy(Config.ARGB_8888, false);
bitmap.recycle();
return newBitmap;
}
public static BitmapRegionDecoder requestCreateBitmapRegionDecoder(
JobContext jc, byte[] bytes, int offset, int length,
boolean shareable) {
if (offset < 0 || length <= 0 || offset + length > bytes.length) {
throw new IllegalArgumentException(String.format(
"offset = %s, length = %s, bytes = %s",
offset, length, bytes.length));
}
try {
return BitmapRegionDecoder.newInstance(
bytes, offset, length, shareable);
} catch (Throwable t) {
Log.w(TAG, t);
return null;
}
}
public static BitmapRegionDecoder requestCreateBitmapRegionDecoder(
JobContext jc, String filePath, boolean shareable) {
try {
return BitmapRegionDecoder.newInstance(filePath, shareable);
} catch (Throwable t) {
Log.w(TAG, t);
return null;
}
}
public static BitmapRegionDecoder requestCreateBitmapRegionDecoder(
JobContext jc, FileDescriptor fd, boolean shareable) {
try {
return BitmapRegionDecoder.newInstance(fd, shareable);
} catch (Throwable t) {
Log.w(TAG, t);
return null;
}
}
public static BitmapRegionDecoder requestCreateBitmapRegionDecoder(
+ JobContext jc, InputStream is, boolean shareable) {
+ try {
+ return BitmapRegionDecoder.newInstance(is, shareable);
+ } catch (Throwable t) {
+ // We often cancel the creating of bitmap region decoder,
+ // so just log one line.
+ Log.w(TAG, "requestCreateBitmapRegionDecoder: " + t);
+ return null;
+ }
+ }
+
+ public static BitmapRegionDecoder requestCreateBitmapRegionDecoder(
JobContext jc, Uri uri, ContentResolver resolver,
boolean shareable) {
ParcelFileDescriptor pfd = null;
try {
pfd = resolver.openFileDescriptor(uri, "r");
return BitmapRegionDecoder.newInstance(
pfd.getFileDescriptor(), shareable);
} catch (Throwable t) {
Log.w(TAG, t);
return null;
} finally {
Utils.closeSilently(pfd);
}
}
}
| false | false | null | null |
diff --git a/src/org/nutz/mvc/NutFilter.java b/src/org/nutz/mvc/NutFilter.java
index 4f5f4d957..1f9b39116 100644
--- a/src/org/nutz/mvc/NutFilter.java
+++ b/src/org/nutz/mvc/NutFilter.java
@@ -1,71 +1,77 @@
package org.nutz.mvc;
import java.io.IOException;
import java.util.regex.Pattern;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.nutz.lang.Strings;
import org.nutz.mvc.config.FilterNutConfig;
/**
* 同 JSP/Serlvet 容器的挂接点
*
* @author zozoh([email protected])
* @author juqkai([email protected])
* @author wendal([email protected])
*/
public class NutFilter implements Filter {
private ActionHandler handler;
private static final String IGNORE = "^.+\\.(jsp|png|gif|jpg|js|css|jspx|jpeg|swf)$";
private Pattern ignorePtn;
private boolean skipMode;
+
+ //请求有对应的Action,处理完成后,是否继续执行下一个Filter
+ private boolean doNextFilter;
public void init(FilterConfig conf) throws ServletException {
FilterNutConfig config = new FilterNutConfig(conf);
// 如果仅仅是用来更新 Message 字符串的,不加载 Nutz.Mvc 设定
// @see Issue 301
String skipMode = Strings.sNull(conf.getInitParameter("skip-mode"), "false").toLowerCase();
if (!"true".equals(skipMode)) {
handler = new ActionHandler(config);
String regx = Strings.sNull(config.getInitParameter("ignore"), IGNORE);
if (!"null".equalsIgnoreCase(regx)) {
ignorePtn = Pattern.compile(regx, Pattern.CASE_INSENSITIVE);
}
} else
this.skipMode = true;
+
+ String doNextFilter = Strings.sNull(conf.getInitParameter("do-next"), "false").toLowerCase();
+ this.doNextFilter = "true".equals(doNextFilter);
}
public void destroy() {
if(handler !=null)
handler.depose();
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException {
if (!skipMode) {
RequestPath path = Mvcs.getRequestPathObject((HttpServletRequest) req);
if (null == ignorePtn || !ignorePtn.matcher(path.getUrl()).find()) {
if (handler.handle((HttpServletRequest) req, (HttpServletResponse) resp))
- return;
+ if (!doNextFilter)
+ return;
}
}
- // 更新 Request 必要的属性
- else {
- Mvcs.updateRequestAttributes((HttpServletRequest) req);
- }
+ // 如果已经找到对应的action,而且正确处理,并且不是donext模式,那么不会走到这里
+ //更新 Request 必要的属性
+ Mvcs.updateRequestAttributes((HttpServletRequest) req);
// 本过滤器没有找到入口函数,继续其他的过滤器
chain.doFilter(req, resp);
}
}
| false | false | null | null |
diff --git a/web/common/src/main/java/org/appfuse/webapp/listener/UserCounterListener.java b/web/common/src/main/java/org/appfuse/webapp/listener/UserCounterListener.java
index ec5e43e3..d2f2d087 100644
--- a/web/common/src/main/java/org/appfuse/webapp/listener/UserCounterListener.java
+++ b/web/common/src/main/java/org/appfuse/webapp/listener/UserCounterListener.java
@@ -1,172 +1,167 @@
package org.appfuse.webapp.listener;
import java.util.Set;
import java.util.LinkedHashSet;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import org.appfuse.model.User;
import org.springframework.security.context.HttpSessionContextIntegrationFilter;
import org.springframework.security.context.SecurityContext;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationTrustResolverImpl;
import org.springframework.security.AuthenticationTrustResolver;
import org.springframework.security.ui.webapp.AuthenticationProcessingFilter;
/**
* UserCounterListener class used to count the current number
* of active users for the applications. Does this by counting
- * how many user objects are stuffed into the session. It Also grabs
+ * how many user objects are stuffed into the session. It also grabs
* these users and exposes them in the servlet context.
*
* @author <a href="mailto:[email protected]">Matt Raible</a>
*/
public class UserCounterListener implements ServletContextListener, HttpSessionAttributeListener {
/**
* Name of user counter variable
*/
public static final String COUNT_KEY = "userCounter";
/**
* Name of users Set in the ServletContext
*/
public static final String USERS_KEY = "userNames";
/**
* The default event we're looking to trap.
*/
public static final String EVENT_KEY = HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY;
private transient ServletContext servletContext;
private int counter;
private Set<User> users;
/**
* Initialize the context
* @param sce the event
*/
public synchronized void contextInitialized(ServletContextEvent sce) {
servletContext = sce.getServletContext();
servletContext.setAttribute((COUNT_KEY), Integer.toString(counter));
}
/**
* Set the servletContext, users and counter to null
* @param event The servletContextEvent
*/
public synchronized void contextDestroyed(ServletContextEvent event) {
servletContext = null;
users = null;
counter = 0;
}
synchronized void incrementUserCounter() {
counter = Integer.parseInt((String) servletContext.getAttribute(COUNT_KEY));
counter++;
servletContext.setAttribute(COUNT_KEY, Integer.toString(counter));
}
synchronized void decrementUserCounter() {
int counter = Integer.parseInt((String) servletContext.getAttribute(COUNT_KEY));
counter--;
if (counter < 0) {
counter = 0;
}
servletContext.setAttribute(COUNT_KEY, Integer.toString(counter));
}
@SuppressWarnings("unchecked")
synchronized void addUsername(User user) {
users = (Set) servletContext.getAttribute(USERS_KEY);
if (users == null) {
users = new LinkedHashSet<User>();
}
if (!users.contains(user)) {
users.add(user);
servletContext.setAttribute(USERS_KEY, users);
incrementUserCounter();
}
}
synchronized void removeUsername(User user) {
users = (Set) servletContext.getAttribute(USERS_KEY);
if (users != null) {
users.remove(user);
}
servletContext.setAttribute(USERS_KEY, users);
decrementUserCounter();
}
/**
* This method is designed to catch when user's login and record their name
* @see javax.servlet.http.HttpSessionAttributeListener#attributeAdded(javax.servlet.http.HttpSessionBindingEvent)
* @param event the event to process
*/
public void attributeAdded(HttpSessionBindingEvent event) {
if (event.getName().equals(EVENT_KEY) && !isAnonymous()) {
SecurityContext securityContext = (SecurityContext) event.getValue();
if (securityContext.getAuthentication().getPrincipal() instanceof User) {
User user = (User) securityContext.getAuthentication().getPrincipal();
addUsername(user);
}
- // Workaround for Jetty bug (http://www.nabble.com/current-user-count-incorrect-tf3550268.html#a9919134)
- } else if (event.getName().equals(AuthenticationProcessingFilter.SPRING_SECURITY_LAST_USERNAME_KEY)) {
- String username = (String) event.getValue();
- User user = new User(username);
- addUsername(user);
}
}
private boolean isAnonymous() {
AuthenticationTrustResolver resolver = new AuthenticationTrustResolverImpl();
SecurityContext ctx = SecurityContextHolder.getContext();
if (ctx != null) {
Authentication auth = ctx.getAuthentication();
return resolver.isAnonymous(auth);
}
return true;
}
/**
* When user's logout, remove their name from the hashMap
* @see javax.servlet.http.HttpSessionAttributeListener#attributeRemoved(javax.servlet.http.HttpSessionBindingEvent)
* @param event the session binding event
*/
public void attributeRemoved(HttpSessionBindingEvent event) {
if (event.getName().equals(EVENT_KEY) && !isAnonymous()) {
SecurityContext securityContext = (SecurityContext) event.getValue();
Authentication auth = securityContext.getAuthentication();
if (auth != null && (auth.getPrincipal() instanceof User)) {
User user = (User) auth.getPrincipal();
removeUsername(user);
}
}
}
/**
* Needed for Acegi Security 1.0, as it adds an anonymous user to the session and
* then replaces it after authentication. http://forum.springframework.org/showthread.php?p=63593
* @see javax.servlet.http.HttpSessionAttributeListener#attributeReplaced(javax.servlet.http.HttpSessionBindingEvent)
* @param event the session binding event
*/
public void attributeReplaced(HttpSessionBindingEvent event) {
if (event.getName().equals(EVENT_KEY) && !isAnonymous()) {
SecurityContext securityContext = (SecurityContext) event.getValue();
if (securityContext.getAuthentication() != null) {
if (securityContext.getAuthentication().getPrincipal() instanceof User) {
User user = (User) securityContext.getAuthentication().getPrincipal();
addUsername(user);
}
}
}
}
}
| false | false | null | null |
diff --git a/core/src/main/java/org/apache/commons/vfs2/operations/AbstractFileOperationProvider.java b/core/src/main/java/org/apache/commons/vfs2/operations/AbstractFileOperationProvider.java
index 88b435e0..587aa9eb 100644
--- a/core/src/main/java/org/apache/commons/vfs2/operations/AbstractFileOperationProvider.java
+++ b/core/src/main/java/org/apache/commons/vfs2/operations/AbstractFileOperationProvider.java
@@ -1,152 +1,152 @@
/*
* 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.vfs2.operations;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
/**
*
* @since 0.1
*/
public abstract class AbstractFileOperationProvider implements FileOperationProvider
{
/**
* Available operations. Operations could be registered for different schemes.
* Some operations can work only for "file" scheme, other - for "svnhttp(s)",
* "svn", "svnssh", but not for "file", etc. The Map has scheme as a key and
- * Colleaction of operations that are available for that scheme.
+ * Collection of operations that are available for that scheme.
*/
private final Collection<Class<? extends FileOperation>> operations =
new ArrayList<Class<? extends FileOperation>>();
/**
* Gather available operations for the specified FileObject and put them into
* specified operationsList.
*
* @param operationsList
- * the list of available operations for the specivied FileObject.
+ * the list of available operations for the specified FileObject.
* The operationList contains classes of available operations, e.g.
* Class objects.
* @param file
* the FileObject for which we want to get the list of available
* operations.
* @throws org.apache.commons.vfs2.FileSystemException
* if list of operations cannot be retrieved.
*/
public final void collectOperations(final Collection<Class<? extends FileOperation>> operationsList,
final FileObject file) throws FileSystemException
{
doCollectOperations(operations, operationsList, file);
}
/**
*
* @throws FileSystemException
*/
protected abstract void doCollectOperations(
final Collection<Class<? extends FileOperation>> availableOperations,
final Collection<Class<? extends FileOperation>> resultList,
final FileObject file) throws FileSystemException;
/**
* @param file
* the FileObject for which we need a operation.
* @param operationClass
* the Class which instance we are needed.
* @return the required operation instance.
* @throws org.apache.commons.vfs2.FileSystemException
* if operation cannot be retrieved.
*/
public final FileOperation getOperation(FileObject file, Class<? extends FileOperation> operationClass)
throws FileSystemException
{
Class<? extends FileOperation> implementation = lookupOperation(operationClass);
FileOperation operationInstance = instantiateOperation(file, implementation);
return operationInstance;
}
/**
*
* @param operationClass
* @return
* @throws FileSystemException
*/
protected abstract FileOperation instantiateOperation(final FileObject file,
final Class<? extends FileOperation> operationClass) throws FileSystemException;
/**
*
* @param operationClass
* @return never returns null
*/
protected final Class<? extends FileOperation> lookupOperation(final Class<? extends FileOperation> operationClass)
throws FileSystemException
{
// check validity of passed class
if (!FileOperation.class.isAssignableFrom(operationClass))
{
throw new FileSystemException("vfs.operation/wrong-type.error", operationClass);
}
// find appropriate class
Class<? extends FileOperation> foundClass = null;
Iterator<Class<? extends FileOperation>> iterator = operations.iterator();
while (iterator.hasNext())
{
Class<? extends FileOperation> operation = iterator.next();
if (operationClass.isAssignableFrom(operation))
{
foundClass = operation;
break;
}
}
if (foundClass == null)
{
throw new FileSystemException("vfs.operation/not-found.error", operationClass);
}
return foundClass;
}
/**
*
* @param operationClass
* @throws FileSystemException
*/
protected final void addOperation(final Class<? extends FileOperation> operationClass)
throws FileSystemException
{
// check validity of passed class
if (!FileOperation.class.isAssignableFrom(operationClass))
{
throw new FileSystemException("vfs.operation/cant-register.error", operationClass);
}
// ok, lets add it to the list
operations.add(operationClass);
}
}
| false | false | null | null |
diff --git a/talk/examples/android/src/org/appspot/apprtc/AppRTCDemoActivity.java b/talk/examples/android/src/org/appspot/apprtc/AppRTCDemoActivity.java
index f75c7c965..46b61696a 100644
--- a/talk/examples/android/src/org/appspot/apprtc/AppRTCDemoActivity.java
+++ b/talk/examples/android/src/org/appspot/apprtc/AppRTCDemoActivity.java
@@ -1,605 +1,615 @@
/*
* libjingle
* Copyright 2013, Google Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.appspot.apprtc;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Point;
import android.media.AudioManager;
import android.os.Bundle;
import android.util.Log;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.widget.EditText;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import org.webrtc.DataChannel;
import org.webrtc.IceCandidate;
import org.webrtc.Logging;
import org.webrtc.MediaConstraints;
import org.webrtc.MediaStream;
import org.webrtc.PeerConnection;
import org.webrtc.PeerConnectionFactory;
import org.webrtc.SdpObserver;
import org.webrtc.SessionDescription;
import org.webrtc.StatsObserver;
import org.webrtc.StatsReport;
import org.webrtc.VideoCapturer;
import org.webrtc.VideoRenderer;
import org.webrtc.VideoRenderer.I420Frame;
import org.webrtc.VideoSource;
import org.webrtc.VideoTrack;
import java.util.EnumSet;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Main Activity of the AppRTCDemo Android app demonstrating interoperability
* between the Android/Java implementation of PeerConnection and the
* apprtc.appspot.com demo webapp.
*/
public class AppRTCDemoActivity extends Activity
implements AppRTCClient.IceServersObserver {
private static final String TAG = "AppRTCDemoActivity";
private PeerConnectionFactory factory;
private VideoSource videoSource;
private boolean videoSourceStopped;
private PeerConnection pc;
private final PCObserver pcObserver = new PCObserver();
private final SDPObserver sdpObserver = new SDPObserver();
private final GAEChannelClient.MessageHandler gaeHandler = new GAEHandler();
private AppRTCClient appRtcClient = new AppRTCClient(this, gaeHandler, this);
private VideoStreamsView vsv;
private Toast logToast;
private LinkedList<IceCandidate> queuedRemoteCandidates =
new LinkedList<IceCandidate>();
// Synchronize on quit[0] to avoid teardown-related crashes.
private final Boolean[] quit = new Boolean[] { false };
private MediaConstraints sdpMediaConstraints;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Thread.setDefaultUncaughtExceptionHandler(
new UnhandledExceptionHandler(this));
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Point displaySize = new Point();
getWindowManager().getDefaultDisplay().getSize(displaySize);
vsv = new VideoStreamsView(this, displaySize);
setContentView(vsv);
abortUnless(PeerConnectionFactory.initializeAndroidGlobals(this),
"Failed to initializeAndroidGlobals");
AudioManager audioManager =
((AudioManager) getSystemService(AUDIO_SERVICE));
// TODO(fischman): figure out how to do this Right(tm) and remove the
// suppression.
@SuppressWarnings("deprecation")
boolean isWiredHeadsetOn = audioManager.isWiredHeadsetOn();
audioManager.setMode(isWiredHeadsetOn ?
AudioManager.MODE_IN_CALL : AudioManager.MODE_IN_COMMUNICATION);
audioManager.setSpeakerphoneOn(!isWiredHeadsetOn);
sdpMediaConstraints = new MediaConstraints();
sdpMediaConstraints.mandatory.add(new MediaConstraints.KeyValuePair(
"OfferToReceiveAudio", "true"));
sdpMediaConstraints.mandatory.add(new MediaConstraints.KeyValuePair(
"OfferToReceiveVideo", "true"));
final Intent intent = getIntent();
if ("android.intent.action.VIEW".equals(intent.getAction())) {
connectToRoom(intent.getData().toString());
return;
}
showGetRoomUI();
}
private void showGetRoomUI() {
final EditText roomInput = new EditText(this);
roomInput.setText("https://apprtc.appspot.com/?r=");
roomInput.setSelection(roomInput.getText().length());
DialogInterface.OnClickListener listener =
new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface dialog, int which) {
abortUnless(which == DialogInterface.BUTTON_POSITIVE, "lolwat?");
dialog.dismiss();
connectToRoom(roomInput.getText().toString());
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder
.setMessage("Enter room URL").setView(roomInput)
.setPositiveButton("Go!", listener).show();
}
private void connectToRoom(String roomUrl) {
logAndToast("Connecting to room...");
appRtcClient.connectToRoom(roomUrl);
}
@Override
public void onPause() {
super.onPause();
vsv.onPause();
if (videoSource != null) {
videoSource.stop();
videoSourceStopped = true;
}
}
@Override
public void onResume() {
super.onResume();
vsv.onResume();
if (videoSource != null && videoSourceStopped) {
videoSource.restart();
}
}
// Just for fun (and to regression-test bug 2302) make sure that DataChannels
// can be created, queried, and disposed.
private static void createDataChannelToRegressionTestBug2302(
PeerConnection pc) {
DataChannel dc = pc.createDataChannel("dcLabel", new DataChannel.Init());
abortUnless("dcLabel".equals(dc.label()), "WTF?");
dc.close();
dc.dispose();
}
@Override
public void onIceServers(List<PeerConnection.IceServer> iceServers) {
factory = new PeerConnectionFactory();
MediaConstraints pcConstraints = appRtcClient.pcConstraints();
pcConstraints.optional.add(
new MediaConstraints.KeyValuePair("RtpDataChannels", "true"));
pc = factory.createPeerConnection(iceServers, pcConstraints, pcObserver);
createDataChannelToRegressionTestBug2302(pc); // See method comment.
// Uncomment to get ALL WebRTC tracing and SENSITIVE libjingle logging.
// NOTE: this _must_ happen while |factory| is alive!
// Logging.enableTracing(
// "logcat:",
// EnumSet.of(Logging.TraceLevel.TRACE_ALL),
// Logging.Severity.LS_SENSITIVE);
{
final PeerConnection finalPC = pc;
final Runnable repeatedStatsLogger = new Runnable() {
public void run() {
synchronized (quit[0]) {
if (quit[0]) {
return;
}
final Runnable runnableThis = this;
boolean success = finalPC.getStats(new StatsObserver() {
public void onComplete(StatsReport[] reports) {
for (StatsReport report : reports) {
Log.d(TAG, "Stats: " + report.toString());
}
vsv.postDelayed(runnableThis, 10000);
}
}, null);
if (!success) {
throw new RuntimeException("getStats() return false!");
}
}
}
};
vsv.postDelayed(repeatedStatsLogger, 10000);
}
{
logAndToast("Creating local video source...");
MediaStream lMS = factory.createLocalMediaStream("ARDAMS");
if (appRtcClient.videoConstraints() != null) {
VideoCapturer capturer = getVideoCapturer();
videoSource = factory.createVideoSource(
capturer, appRtcClient.videoConstraints());
VideoTrack videoTrack =
factory.createVideoTrack("ARDAMSv0", videoSource);
videoTrack.addRenderer(new VideoRenderer(new VideoCallbacks(
vsv, VideoStreamsView.Endpoint.LOCAL)));
lMS.addTrack(videoTrack);
}
if (appRtcClient.audioConstraints() != null) {
lMS.addTrack(factory.createAudioTrack(
"ARDAMSa0",
factory.createAudioSource(appRtcClient.audioConstraints())));
}
pc.addStream(lMS, new MediaConstraints());
}
logAndToast("Waiting for ICE candidates...");
}
// Cycle through likely device names for the camera and return the first
// capturer that works, or crash if none do.
private VideoCapturer getVideoCapturer() {
String[] cameraFacing = { "front", "back" };
int[] cameraIndex = { 0, 1 };
int[] cameraOrientation = { 0, 90, 180, 270 };
for (String facing : cameraFacing) {
for (int index : cameraIndex) {
for (int orientation : cameraOrientation) {
String name = "Camera " + index + ", Facing " + facing +
", Orientation " + orientation;
VideoCapturer capturer = VideoCapturer.create(name);
if (capturer != null) {
logAndToast("Using camera: " + name);
return capturer;
}
}
}
}
throw new RuntimeException("Failed to open capturer");
}
@Override
protected void onDestroy() {
disconnectAndExit();
super.onDestroy();
}
// Poor-man's assert(): die with |msg| unless |condition| is true.
private static void abortUnless(boolean condition, String msg) {
if (!condition) {
throw new RuntimeException(msg);
}
}
// Log |msg| and Toast about it.
private void logAndToast(String msg) {
Log.d(TAG, msg);
if (logToast != null) {
logToast.cancel();
}
logToast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
logToast.show();
}
// Send |json| to the underlying AppEngine Channel.
private void sendMessage(JSONObject json) {
appRtcClient.sendMessage(json.toString());
}
// Put a |key|->|value| mapping in |json|.
private static void jsonPut(JSONObject json, String key, Object value) {
try {
json.put(key, value);
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
// Mangle SDP to prefer ISAC/16000 over any other audio codec.
private String preferISAC(String sdpDescription) {
String[] lines = sdpDescription.split("\n");
int mLineIndex = -1;
String isac16kRtpMap = null;
Pattern isac16kPattern =
Pattern.compile("^a=rtpmap:(\\d+) ISAC/16000[\r]?$");
for (int i = 0;
(i < lines.length) && (mLineIndex == -1 || isac16kRtpMap == null);
++i) {
if (lines[i].startsWith("m=audio ")) {
mLineIndex = i;
continue;
}
Matcher isac16kMatcher = isac16kPattern.matcher(lines[i]);
if (isac16kMatcher.matches()) {
isac16kRtpMap = isac16kMatcher.group(1);
continue;
}
}
if (mLineIndex == -1) {
Log.d(TAG, "No m=audio line, so can't prefer iSAC");
return sdpDescription;
}
if (isac16kRtpMap == null) {
Log.d(TAG, "No ISAC/16000 line, so can't prefer iSAC");
return sdpDescription;
}
String[] origMLineParts = lines[mLineIndex].split(" ");
StringBuilder newMLine = new StringBuilder();
int origPartIndex = 0;
// Format is: m=<media> <port> <proto> <fmt> ...
newMLine.append(origMLineParts[origPartIndex++]).append(" ");
newMLine.append(origMLineParts[origPartIndex++]).append(" ");
newMLine.append(origMLineParts[origPartIndex++]).append(" ");
newMLine.append(isac16kRtpMap).append(" ");
for (; origPartIndex < origMLineParts.length; ++origPartIndex) {
if (!origMLineParts[origPartIndex].equals(isac16kRtpMap)) {
newMLine.append(origMLineParts[origPartIndex]).append(" ");
}
}
lines[mLineIndex] = newMLine.toString();
StringBuilder newSdpDescription = new StringBuilder();
for (String line : lines) {
newSdpDescription.append(line).append("\n");
}
return newSdpDescription.toString();
}
// Implementation detail: observe ICE & stream changes and react accordingly.
private class PCObserver implements PeerConnection.Observer {
@Override public void onIceCandidate(final IceCandidate candidate){
runOnUiThread(new Runnable() {
public void run() {
JSONObject json = new JSONObject();
jsonPut(json, "type", "candidate");
jsonPut(json, "label", candidate.sdpMLineIndex);
jsonPut(json, "id", candidate.sdpMid);
jsonPut(json, "candidate", candidate.sdp);
sendMessage(json);
}
});
}
@Override public void onError(){
runOnUiThread(new Runnable() {
public void run() {
throw new RuntimeException("PeerConnection error!");
}
});
}
@Override public void onSignalingChange(
PeerConnection.SignalingState newState) {
}
@Override public void onIceConnectionChange(
PeerConnection.IceConnectionState newState) {
}
@Override public void onIceGatheringChange(
PeerConnection.IceGatheringState newState) {
}
@Override public void onAddStream(final MediaStream stream){
runOnUiThread(new Runnable() {
public void run() {
abortUnless(stream.audioTracks.size() <= 1 &&
stream.videoTracks.size() <= 1,
"Weird-looking stream: " + stream);
if (stream.videoTracks.size() == 1) {
stream.videoTracks.get(0).addRenderer(new VideoRenderer(
new VideoCallbacks(vsv, VideoStreamsView.Endpoint.REMOTE)));
}
}
});
}
@Override public void onRemoveStream(final MediaStream stream){
runOnUiThread(new Runnable() {
public void run() {
stream.videoTracks.get(0).dispose();
}
});
}
@Override public void onDataChannel(final DataChannel dc) {
runOnUiThread(new Runnable() {
public void run() {
throw new RuntimeException(
"AppRTC doesn't use data channels, but got: " + dc.label() +
" anyway!");
}
});
}
@Override public void onRenegotiationNeeded() {
// No need to do anything; AppRTC follows a pre-agreed-upon
// signaling/negotiation protocol.
}
}
// Implementation detail: handle offer creation/signaling and answer setting,
// as well as adding remote ICE candidates once the answer SDP is set.
private class SDPObserver implements SdpObserver {
@Override public void onCreateSuccess(final SessionDescription origSdp) {
runOnUiThread(new Runnable() {
public void run() {
- logAndToast("Sending " + origSdp.type);
SessionDescription sdp = new SessionDescription(
origSdp.type, preferISAC(origSdp.description));
- JSONObject json = new JSONObject();
- jsonPut(json, "type", sdp.type.canonicalForm());
- jsonPut(json, "sdp", sdp.description);
- sendMessage(json);
pc.setLocalDescription(sdpObserver, sdp);
}
});
}
+ // Helper for sending local SDP (offer or answer, depending on role) to the
+ // other participant.
+ private void sendLocalDescription(PeerConnection pc) {
+ SessionDescription sdp = pc.getLocalDescription();
+ logAndToast("Sending " + sdp.type);
+ JSONObject json = new JSONObject();
+ jsonPut(json, "type", sdp.type.canonicalForm());
+ jsonPut(json, "sdp", sdp.description);
+ sendMessage(json);
+ }
+
@Override public void onSetSuccess() {
runOnUiThread(new Runnable() {
public void run() {
if (appRtcClient.isInitiator()) {
if (pc.getRemoteDescription() != null) {
// We've set our local offer and received & set the remote
// answer, so drain candidates.
drainRemoteCandidates();
+ } else {
+ // We've just set our local description so time to send it.
+ sendLocalDescription(pc);
}
} else {
if (pc.getLocalDescription() == null) {
// We just set the remote offer, time to create our answer.
logAndToast("Creating answer");
pc.createAnswer(SDPObserver.this, sdpMediaConstraints);
} else {
- // Sent our answer and set it as local description; drain
+ // Answer now set as local description; send it and drain
// candidates.
+ sendLocalDescription(pc);
drainRemoteCandidates();
}
}
}
});
}
@Override public void onCreateFailure(final String error) {
runOnUiThread(new Runnable() {
public void run() {
throw new RuntimeException("createSDP error: " + error);
}
});
}
@Override public void onSetFailure(final String error) {
runOnUiThread(new Runnable() {
public void run() {
throw new RuntimeException("setSDP error: " + error);
}
});
}
private void drainRemoteCandidates() {
for (IceCandidate candidate : queuedRemoteCandidates) {
pc.addIceCandidate(candidate);
}
queuedRemoteCandidates = null;
}
}
// Implementation detail: handler for receiving GAE messages and dispatching
// them appropriately.
private class GAEHandler implements GAEChannelClient.MessageHandler {
@JavascriptInterface public void onOpen() {
if (!appRtcClient.isInitiator()) {
return;
}
logAndToast("Creating offer...");
pc.createOffer(sdpObserver, sdpMediaConstraints);
}
@JavascriptInterface public void onMessage(String data) {
try {
JSONObject json = new JSONObject(data);
String type = (String) json.get("type");
if (type.equals("candidate")) {
IceCandidate candidate = new IceCandidate(
(String) json.get("id"),
json.getInt("label"),
(String) json.get("candidate"));
if (queuedRemoteCandidates != null) {
queuedRemoteCandidates.add(candidate);
} else {
pc.addIceCandidate(candidate);
}
} else if (type.equals("answer") || type.equals("offer")) {
SessionDescription sdp = new SessionDescription(
SessionDescription.Type.fromCanonicalForm(type),
preferISAC((String) json.get("sdp")));
pc.setRemoteDescription(sdpObserver, sdp);
} else if (type.equals("bye")) {
logAndToast("Remote end hung up; dropping PeerConnection");
disconnectAndExit();
} else {
throw new RuntimeException("Unexpected message: " + data);
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
@JavascriptInterface public void onClose() {
disconnectAndExit();
}
@JavascriptInterface public void onError(int code, String description) {
disconnectAndExit();
}
}
// Disconnect from remote resources, dispose of local resources, and exit.
private void disconnectAndExit() {
synchronized (quit[0]) {
if (quit[0]) {
return;
}
quit[0] = true;
if (pc != null) {
pc.dispose();
pc = null;
}
if (appRtcClient != null) {
appRtcClient.sendMessage("{\"type\": \"bye\"}");
appRtcClient.disconnect();
appRtcClient = null;
}
if (videoSource != null) {
videoSource.dispose();
videoSource = null;
}
if (factory != null) {
factory.dispose();
factory = null;
}
finish();
}
}
// Implementation detail: bridge the VideoRenderer.Callbacks interface to the
// VideoStreamsView implementation.
private class VideoCallbacks implements VideoRenderer.Callbacks {
private final VideoStreamsView view;
private final VideoStreamsView.Endpoint stream;
public VideoCallbacks(
VideoStreamsView view, VideoStreamsView.Endpoint stream) {
this.view = view;
this.stream = stream;
}
@Override
public void setSize(final int width, final int height) {
view.queueEvent(new Runnable() {
public void run() {
view.setSize(stream, width, height);
}
});
}
@Override
public void renderFrame(I420Frame frame) {
view.queueFrame(stream, frame);
}
}
}
| false | false | null | null |
diff --git a/wicket-jquery-ui-calendar/src/main/java/com/googlecode/wicket/jquery/ui/calendar/Calendar.java b/wicket-jquery-ui-calendar/src/main/java/com/googlecode/wicket/jquery/ui/calendar/Calendar.java
index a2c92ea49..726cc7c7b 100644
--- a/wicket-jquery-ui-calendar/src/main/java/com/googlecode/wicket/jquery/ui/calendar/Calendar.java
+++ b/wicket-jquery-ui-calendar/src/main/java/com/googlecode/wicket/jquery/ui/calendar/Calendar.java
@@ -1,722 +1,724 @@
/*
* 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 com.googlecode.wicket.jquery.ui.calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.event.IEvent;
import org.apache.wicket.util.time.Duration;
import com.googlecode.wicket.jquery.ui.JQueryBehavior;
import com.googlecode.wicket.jquery.ui.JQueryContainer;
import com.googlecode.wicket.jquery.ui.JQueryEvent;
import com.googlecode.wicket.jquery.ui.Options;
import com.googlecode.wicket.jquery.ui.ajax.JQueryAjaxBehavior;
import com.googlecode.wicket.jquery.ui.utils.RequestCycleUtils;
/**
* Provides calendar widget, based on the jQuery fullcalendar plugin.
*
* @author Sebastien Briquet - sebfz1
* @author Martin Grigorov - martin-g
*
*/
public class Calendar extends JQueryContainer
{
private static final long serialVersionUID = 1L;
private final Options options;
private Map<CharSequence, String> gcals;
private CalendarModelBehavior modelBehavior; // events load
private JQueryAjaxBehavior onDayClickBehavior; // day click
private JQueryAjaxBehavior onSelectBehavior; // date range-select behavior;
private JQueryAjaxBehavior onEventClickBehavior; // event click
private JQueryAjaxBehavior onEventDropBehavior; // event drop
private JQueryAjaxBehavior onEventResizeBehavior; // event resize
/**
* Constructor
* @param id the markup id
* @param options {@link Options}. Note that 'selectable' and 'selectHelper' options are set by overriding {@link #isSelectable()} (default is false)
*/
public Calendar(String id, Options options)
{
super(id);
this.options = options;
}
/**
* Constructor
* @param id the markup id
* @param model the {@link CalendarModel}
*/
public Calendar(String id, CalendarModel model)
{
this(id, model, new Options());
}
/**
* Constructor
* @param id the markup id
* @param model the {@link CalendarModel}
* @param options {@link Options}. Note that 'selectable' and 'selectHelper' options are set by overriding {@link #isSelectable()} (default is false)
*/
public Calendar(String id, CalendarModel model, Options options)
{
super(id, model);
this.options = options;
}
/**
* Gets the calendar's model
* @return a {@link CalendarModel}
*/
public CalendarModel getModel()
{
return (CalendarModel) this.getDefaultModel();
}
// Methods //
/**
* Adds a Google Calendar Feed
* @param gcal url to xml feed
*/
public void addFeed(CharSequence gcal)
{
this.addFeed(gcal, "");
}
/**
* Adds a Google Calendar Feed
* @param gcal url to xml feed
* @param className css class to be used
*/
public void addFeed(CharSequence gcal, String className)
{
if (this.gcals == null)
{
this.gcals = new HashMap<CharSequence, String>();
}
this.gcals.put(gcal, className);
}
/**
* Refreshes the events currently available in the selected view.
*
* @param target the {@link AjaxRequestTarget}
*/
public void refresh(AjaxRequestTarget target)
{
target.appendJavaScript(String.format("$('%s').fullCalendar('refetchEvents');", JQueryWidget.getSelector(this)));
}
// Properties //
/**
* Indicated whether a cell can be selected.<br />
* If true, the {@link #onSelect(AjaxRequestTarget, Date, Date, boolean)} event will be triggered
*
* @return false by default
*/
protected boolean isSelectable()
{
return false;
}
/**
* Indicates whether the event can be edited (ie, clicked).<br/>
* IIF true, an event can override this global setting to false by using CalendarEvent#setEditable(boolean);<br/>
* If true, the {@link #onEventClick(AjaxRequestTarget, int)} event and {@link #onDayClick(AjaxRequestTarget, Date)} event will be triggered<br/>
*
* @return false by default
*/
protected boolean isEditable()
{
return false;
}
/**
* Indicates whether the event can be dragged & dropped.
* If true, the {@link #onEventDrop(AjaxRequestTarget, int, long, boolean)} event will be triggered
*
* @return false by default
*/
protected boolean isEventDropEnabled()
{
return false;
}
/**
* Indicates whether the event can be resized.
* If true, the {@link #onEventResize(AjaxRequestTarget, int, long)} event will be triggered
*
* @return false by default
*/
protected boolean isEventResizeEnabled()
{
return false;
}
// Events //
@Override
protected void onInitialize()
{
super.onInitialize();
this.add(this.modelBehavior = new CalendarModelBehavior(this.getModel()));
// event behaviors //
this.add(this.onDayClickBehavior = this.newOnDayClickBehavior());
this.add(this.onSelectBehavior = this.newOnSelectBehavior());
this.add(this.onEventClickBehavior = this.newOnEventClickBehavior());
this.add(this.onEventDropBehavior = this.newOnEventDropBehavior());
this.add(this.onEventResizeBehavior = this.newOnEventResizeBehavior());
}
/**
* Called immediately after the onConfigure method in a behavior. Since this is before the rendering
* cycle has begun, the behavior can modify the configuration of the component (i.e. {@link Options})
*
* @param behavior the {@link JQueryBehavior}
*/
protected void onConfigure(JQueryBehavior behavior)
{
this.options.set("editable", this.isEditable());
this.options.set("selectable", this.isSelectable());
this.options.set("selectHelper", this.isSelectable());
this.options.set("disableDragging", !this.isEventDropEnabled());
this.options.set("disableResizing", !this.isEventResizeEnabled());
behavior.setOptions(this.options);
}
@Override
public void onEvent(IEvent<?> event)
{
Object payload = event.getPayload();
if (payload instanceof DayClickEvent)
{
DayClickEvent dayClickEvent = (DayClickEvent) payload;
this.onDayClick(dayClickEvent.getTarget(), dayClickEvent.getDate());
}
else if (payload instanceof SelectEvent)
{
SelectEvent selectEvent = (SelectEvent) payload;
this.onSelect(selectEvent.getTarget(), selectEvent.getStart(), selectEvent.getEnd(), selectEvent.isAllDay());
}
else if (payload instanceof ClickEvent)
{
ClickEvent clickEvent = (ClickEvent) payload;
this.onEventClick(clickEvent.getTarget(), clickEvent.getEventId());
}
else if (payload instanceof DropEvent)
{
DropEvent dropEvent = (DropEvent) payload;
this.onEventDrop(dropEvent.getTarget(), dropEvent.getEventId(), dropEvent.getDelta(), dropEvent.isAllDay());
}
else if (payload instanceof ResizeEvent)
{
ResizeEvent resizeEvent = (ResizeEvent) payload;
this.onEventResize(resizeEvent.getTarget(), resizeEvent.getEventId(), resizeEvent.getDelta());
}
}
/**
* Triggered when a calendar day is clicked
* @param target the {@link AjaxRequestTarget}
* @param date the day
*/
protected void onDayClick(AjaxRequestTarget target, Date date)
{
}
/**
* Triggered when an cell is selected.<br/>
* {@link #isSelectable()} should return true for this event to be triggered.
*
* @param target the {@link AjaxRequestTarget}
* @param start the event start {@link Date}
* @param end the event end {@link Date}
* @param allDay the event all-day property
*/
protected void onSelect(AjaxRequestTarget target, Date start, Date end, boolean allDay)
{
}
/**
* Triggered when an event is clicked.<br/>
* {@link #isEditable()} should return true for this event to be triggered.
*
* @param target the {@link AjaxRequestTarget}
* @param eventId the {@link CalendarEvent} id
*/
protected void onEventClick(AjaxRequestTarget target, int eventId)
{
}
/**
* Triggered when an event is dropped (after being dragged).<br/>
* {@link #isEventDropEnabled()} should return true for this event to be triggered.
*
* @param target the {@link AjaxRequestTarget}
* @param eventId the {@link CalendarEvent} id
* @param delta the delta (time) with the original event date
* @param allDay the event all-day property
*/
protected void onEventDrop(AjaxRequestTarget target, int eventId, long delta, boolean allDay)
{
}
/**
* Triggered when an event is dropped (after being dragged).<br/>
* {@link #isEventResizeEnabled()} should return true for this event to be triggered.
*
* @param target the {@link AjaxRequestTarget}
* @param eventId the {@link CalendarEvent} id
* @param delta the delta (time) with the original event date
*/
protected void onEventResize(AjaxRequestTarget target, int eventId, long delta)
{
}
// IJQueryWidget //
/**
* see {@link JQueryContainer#newWidgetBehavior(String)}
*/
@Override
public JQueryBehavior newWidgetBehavior(String selector)
{
return new CalendarBehavior(selector) {
private static final long serialVersionUID = 1L;
@Override
public void onConfigure(Component component)
{
Calendar.this.onConfigure(this); //set options
// builds sources //
StringBuilder sourceBuilder = new StringBuilder();
sourceBuilder.append("'").append(Calendar.this.modelBehavior.getCallbackUrl()).append("'");
if (Calendar.this.gcals != null)
{
for (Entry<CharSequence, String> gcal : Calendar.this.gcals.entrySet())
{
sourceBuilder.append(", ");
sourceBuilder.append("$.fullCalendar.gcalFeed('").append(gcal.getKey()).append("', { className: '").append(gcal.getValue()).append("' })");
}
}
this.setOption("eventSources", String.format("[%s]", sourceBuilder.toString()));
// behaviors //
if (Calendar.this.isEditable())
{
this.setOption("dayClick", Calendar.this.onDayClickBehavior.getCallbackFunction());
this.setOption("eventClick", Calendar.this.onEventClickBehavior.getCallbackFunction());
}
if (Calendar.this.isSelectable())
{
this.setOption("select", Calendar.this.onSelectBehavior.getCallbackFunction());
}
if (Calendar.this.isEventDropEnabled())
{
this.setOption("eventDrop", Calendar.this.onEventDropBehavior.getCallbackFunction());
}
if (Calendar.this.isEventResizeEnabled())
{
this.setOption("eventResize", Calendar.this.onEventResizeBehavior.getCallbackFunction());
}
}
};
}
// Factories //
/**
* Gets the ajax behavior that will be triggered when the user clicks on a day cell
*
* @return the {@link JQueryAjaxBehavior}
*/
private JQueryAjaxBehavior newOnDayClickBehavior()
{
return new JQueryAjaxBehavior(this) {
private static final long serialVersionUID = 1L;
@Override
public String getCallbackFunction()
{
return "function(date, allDay, jsEvent, view) { " + this.getCallbackScript() + " }";
}
@Override
public CharSequence getCallbackScript()
{
return this.generateCallbackScript("wicketAjaxGet('" + this.getCallbackUrl() + "&date=' + date.getTime()");
}
@Override
protected JQueryEvent newEvent(AjaxRequestTarget target)
{
return new DayClickEvent(target);
}
};
}
/**
* Gets the ajax behavior that will be triggered when the user select a cell range
*
* @return the {@link JQueryAjaxBehavior}
*/
private JQueryAjaxBehavior newOnSelectBehavior()
{
return new JQueryAjaxBehavior(this) {
private static final long serialVersionUID = 1L;
@Override
public String getCallbackFunction()
{
- return "function(start, end, allDay) { " + this.getCallbackScript() + " $.fullCalendar('unselect'); }";
+ return "function(start, end, allDay) { " + this.getCallbackScript() + " }";
+ //TODO: remove this comment
+ //$('%s').fullCalendar('unselect'); JQueryWidget.getSelector(Calendar.this)
}
@Override
public CharSequence getCallbackScript()
{
return this.generateCallbackScript("wicketAjaxGet('" + this.getCallbackUrl() + "&start=' + start.getTime() + '&end=' + end.getTime() + '&allDay=' + allDay");
}
@Override
protected JQueryEvent newEvent(AjaxRequestTarget target)
{
return new SelectEvent(target);
}
};
}
/**
* Gets the ajax behavior that will be triggered when the user clicks on an event
*
* @return the {@link JQueryAjaxBehavior}
*/
private JQueryAjaxBehavior newOnEventClickBehavior()
{
return new JQueryAjaxBehavior(this) {
private static final long serialVersionUID = 1L;
@Override
public String getCallbackFunction()
{
return "function(event, jsEvent, view) { " + this.getCallbackScript() + " }";
}
@Override
public CharSequence getCallbackScript()
{
return this.generateCallbackScript("wicketAjaxGet('" + this.getCallbackUrl() + "&eventId=' + event.id");
}
@Override
protected JQueryEvent newEvent(AjaxRequestTarget target)
{
return new ClickEvent(target);
}
};
}
/**
* Gets the ajax behavior that will be triggered when the user moves (drag & drop) an event
*
* @return the {@link JQueryAjaxBehavior}
*/
private JQueryAjaxBehavior newOnEventDropBehavior()
{
return new EventDeltaBehavior(this) {
private static final long serialVersionUID = 1L;
@Override
protected JQueryEvent newEvent(AjaxRequestTarget target)
{
return new DropEvent(target);
}
};
}
/**
* Gets the ajax behavior that will be triggered when the user resizes an event
*
* @return the {@link JQueryAjaxBehavior}
*/
private JQueryAjaxBehavior newOnEventResizeBehavior()
{
return new EventDeltaBehavior(this) {
private static final long serialVersionUID = 1L;
@Override
protected JQueryEvent newEvent(AjaxRequestTarget target)
{
return new ResizeEvent(target);
}
};
}
// Behavior classes //
/**
* Base class for {@link JQueryAjaxBehavior} that will broadcast delta-based events
*/
private abstract class EventDeltaBehavior extends JQueryAjaxBehavior
{
private static final long serialVersionUID = 1L;
public EventDeltaBehavior(Component source)
{
super(source);
}
@Override
public String getCallbackFunction()
{
return "function(event, dayDelta, minuteDelta, allDay, revertFunc, jsEvent, ui, view) { " + this.getCallbackScript() + " }";
}
@Override
public CharSequence getCallbackScript()
{
return this.generateCallbackScript("wicketAjaxGet('" + this.getCallbackUrl() + "&eventId=' + event.id + '&dayDelta=' + dayDelta + '&minuteDelta=' + minuteDelta + '&allDay=' + allDay");
}
}
// Event classes //
/**
* An event object that will be broadcasted when the user clicks on a day cell
*/
private class DayClickEvent extends JQueryEvent
{
private final Date day;
/**
* Constructor
* @param target the {@link AjaxRequestTarget}
*/
public DayClickEvent(AjaxRequestTarget target)
{
super(target);
long date = RequestCycleUtils.getQueryParameterValue("date").toLong();
this.day = new Date(date);
}
/**
* Gets the event date
* @return the date
*/
public Date getDate()
{
return this.day;
}
}
/**
* An event object that will be broadcasted when the user select a cell range
*/
private class SelectEvent extends JQueryEvent
{
private final boolean isAllDay;
private final Date start;
private final Date end;
public SelectEvent(AjaxRequestTarget target)
{
super(target);
long start = RequestCycleUtils.getQueryParameterValue("start").toLong();
this.start = new Date(start);
long end = RequestCycleUtils.getQueryParameterValue("end").toLong();
this.end = new Date(end);
this.isAllDay = RequestCycleUtils.getQueryParameterValue("allDay").toBoolean();
}
/**
* Gets the event start date
* @return the start date
*/
public Date getStart()
{
return this.start;
}
/**
* Gets the end date
* @return the end date
*/
public Date getEnd()
{
return this.end;
}
/**
* Indicated whether this event is an 'all-day' event
* @return true or false
*/
public boolean isAllDay()
{
return this.isAllDay;
}
}
/**
* An event object that will be broadcasted when the user clicks on an event
*/
private class ClickEvent extends JQueryEvent
{
private final int eventId;
/**
* Constructor
* @param target the {@link AjaxRequestTarget}
*/
public ClickEvent(AjaxRequestTarget target)
{
super(target);
this.eventId = RequestCycleUtils.getQueryParameterValue("eventId").toInt();
}
/**
* Gets the event's id
* @return the event's id
*/
public int getEventId()
{
return this.eventId;
}
}
/**
* A base event object that contains a delta time
*/
private abstract class DeltaEvent extends JQueryEvent
{
private final int eventId;
private long delta;
/**
* Constructor
* @param target the {@link AjaxRequestTarget}
*/
public DeltaEvent(AjaxRequestTarget target)
{
super(target);
this.eventId = RequestCycleUtils.getQueryParameterValue("eventId").toInt();
int dayDelta = RequestCycleUtils.getQueryParameterValue("dayDelta").toInt();
int minuteDelta = RequestCycleUtils.getQueryParameterValue("minuteDelta").toInt();
this.delta = (dayDelta * Duration.ONE_DAY.getMilliseconds()) + (minuteDelta * Duration.ONE_MINUTE.getMilliseconds());
}
/**
* Gets the event's id
* @return the event's id
*/
public int getEventId()
{
return this.eventId;
}
/**
* Gets the event's delta time in milliseconds
* @return the event's delta time
*/
public long getDelta()
{
return this.delta;
}
}
/**
* An event object that will be broadcasted when the user moves (drag & drop) an event
*/
private class DropEvent extends DeltaEvent
{
private final boolean isAllDay;
/**
* Constructor
* @param target the {@link AjaxRequestTarget}
*/
public DropEvent(AjaxRequestTarget target)
{
super(target);
this.isAllDay = RequestCycleUtils.getQueryParameterValue("allDay").toBoolean();
}
/**
* Indicated whether this event is an 'all-day' event
* @return true or false
*/
public boolean isAllDay()
{
return this.isAllDay;
}
}
/**
* An event object that will be broadcasted when the user resizes an event
*/
private class ResizeEvent extends DeltaEvent
{
/**
* Constructor
* @param target the {@link AjaxRequestTarget}
*/
public ResizeEvent(AjaxRequestTarget target)
{
super(target);
}
}
}
diff --git a/wicket-jquery-ui-samples/src/main/java/com/googlecode/wicket/jquery/ui/samples/pages/calendar/ExtendedCalendarPage.java b/wicket-jquery-ui-samples/src/main/java/com/googlecode/wicket/jquery/ui/samples/pages/calendar/ExtendedCalendarPage.java
index 24045c314..a55e99681 100644
--- a/wicket-jquery-ui-samples/src/main/java/com/googlecode/wicket/jquery/ui/samples/pages/calendar/ExtendedCalendarPage.java
+++ b/wicket-jquery-ui-samples/src/main/java/com/googlecode/wicket/jquery/ui/samples/pages/calendar/ExtendedCalendarPage.java
@@ -1,158 +1,158 @@
package com.googlecode.wicket.jquery.ui.samples.pages.calendar;
import java.util.Date;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import com.googlecode.wicket.jquery.ui.Options;
import com.googlecode.wicket.jquery.ui.calendar.Calendar;
import com.googlecode.wicket.jquery.ui.panel.JQueryFeedbackPanel;
import com.googlecode.wicket.jquery.ui.samples.component.DemoCalendarDialog;
import com.googlecode.wicket.jquery.ui.samples.data.DemoCalendarDAO;
import com.googlecode.wicket.jquery.ui.samples.data.DemoCalendarEvent;
import com.googlecode.wicket.jquery.ui.samples.data.DemoCalendarModel;
public class ExtendedCalendarPage extends AbstractCalendarPage
{
private static final long serialVersionUID = 1L;
private Calendar calendar;
public ExtendedCalendarPage()
{
this.init();
}
private void init()
{
// Form //
final Form<Date> form = new Form<Date>("form");
this.add(form);
// FeedbackPanel //
final FeedbackPanel feedback = new JQueryFeedbackPanel("feedback");
form.add(feedback.setOutputMarkupId(true));
// Dialog //
final DemoCalendarDialog dialog = new DemoCalendarDialog("dialog", "Event details") {
private static final long serialVersionUID = 1L;
@Override
public void onSubmit(AjaxRequestTarget target)
{
DemoCalendarEvent event = this.getModelObject();
// new event //
- if (DemoCalendarDAO.isNew(event))
+ if (DemoCalendarDAO.isNew(event))
{
DemoCalendarDAO.addEvent(event);
}
- calendar.refresh(target); //use calendar.refresh() instead of target.add(calendar)
+ calendar.refresh(target); //use calendar.refresh(target) instead of target.add(calendar)
}
};
this.add(dialog);
// Calendar //
Options options = new Options();
options.set("theme", true);
options.set("header", "{ left: 'title', right: 'month,agendaWeek,agendaDay, today, prev,next' }");
this.calendar = new Calendar("calendar", new DemoCalendarModel(), options) {
private static final long serialVersionUID = 1L;
@Override
protected boolean isSelectable()
{
return true;
}
-
+
@Override
protected boolean isEditable()
{
return true;
}
-
+
@Override
protected boolean isEventDropEnabled()
{
return true;
}
-
+
@Override
protected boolean isEventResizeEnabled()
{
return true;
}
-
+
@Override
protected void onDayClick(AjaxRequestTarget target, Date date)
{
DemoCalendarEvent event = DemoCalendarDAO.emptyEvent(date);
-
+
dialog.setModelObject(event);
dialog.open(target);
}
@Override
protected void onSelect(AjaxRequestTarget target, Date start, Date end, boolean allDay)
{
DemoCalendarEvent event = DemoCalendarDAO.emptyEvent(start, end);
event.setAllDay(allDay);
dialog.setModelObject(event);
dialog.open(target);
}
@Override
protected void onEventClick(AjaxRequestTarget target, int eventId)
{
DemoCalendarEvent event = DemoCalendarDAO.getEvent(eventId);
if (event != null)
{
dialog.setModelObject(event);
dialog.open(target);
}
}
@Override
protected void onEventDrop(AjaxRequestTarget target, int eventId, long delta, boolean allDay)
{
DemoCalendarEvent event = DemoCalendarDAO.getEvent(eventId);
if (event != null)
{
event.setStart(event.getStart() != null ? new Date(event.getStart().getTime() + delta) : null); //recompute start date
event.setEnd(event.getEnd() != null ? new Date(event.getEnd().getTime() + delta) : null); // recompute end date
event.setAllDay(allDay);
this.info(String.format("%s changed to %s", event.getTitle(), event.getStart()));
target.add(feedback);
}
}
@Override
protected void onEventResize(AjaxRequestTarget target, int eventId, long delta)
{
DemoCalendarEvent event = DemoCalendarDAO.getEvent(eventId);
if (event != null)
{
Date date = (event.getEnd() == null ? event.getStart() : event.getEnd());
event.setEnd(new Date(date.getTime() + delta));
this.info(String.format("%s now ends the %s", event.getTitle(), event.getEnd()));
target.add(feedback);
}
}
};
form.add(this.calendar);
}
}
| false | false | null | null |
diff --git a/branches/TekkitConverter/src/pfaeff/CBRenderer.java b/branches/TekkitConverter/src/pfaeff/CBRenderer.java
index 0b26cda..6966aca 100644
--- a/branches/TekkitConverter/src/pfaeff/CBRenderer.java
+++ b/branches/TekkitConverter/src/pfaeff/CBRenderer.java
@@ -1,61 +1,62 @@
/*
* Copyright 2011 Kai R�hr
*
*
* This file is part of mIDas.
*
* mIDas is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* mIDas is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with mIDas. If not, see <http://www.gnu.org/licenses/>.
*/
package pfaeff;
import java.awt.Color;
import java.awt.Component;
import java.io.File;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
public class CBRenderer extends JLabel implements ListCellRenderer {
/**
*
*/
private static final long serialVersionUID = -646755438286846622L;
public int maxIndex = -1;
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
- setText(((File)value).getName());
+ if (value==null)setText("");
+ else setText(((File)value).getName());
setOpaque(true);
if ((index % 2) == 1) {
setBackground(new Color(0.6f, 1.0f, 0.6f));
} else {
setBackground(Color.white);
}
if (isSelected) {
setBackground(new Color(0.6f, 0.6f, 1.0f));
}
if (index > maxIndex) {
setForeground(Color.red);
} else {
setForeground(Color.black);
}
return this;
}
}
| true | true | public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
setText(((File)value).getName());
setOpaque(true);
if ((index % 2) == 1) {
setBackground(new Color(0.6f, 1.0f, 0.6f));
} else {
setBackground(Color.white);
}
if (isSelected) {
setBackground(new Color(0.6f, 0.6f, 1.0f));
}
if (index > maxIndex) {
setForeground(Color.red);
} else {
setForeground(Color.black);
}
return this;
}
| public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
if (value==null)setText("");
else setText(((File)value).getName());
setOpaque(true);
if ((index % 2) == 1) {
setBackground(new Color(0.6f, 1.0f, 0.6f));
} else {
setBackground(Color.white);
}
if (isSelected) {
setBackground(new Color(0.6f, 0.6f, 1.0f));
}
if (index > maxIndex) {
setForeground(Color.red);
} else {
setForeground(Color.black);
}
return this;
}
|
diff --git a/src/edu/berkeley/cs160/theccertservice/splist/FriendsActivity.java b/src/edu/berkeley/cs160/theccertservice/splist/FriendsActivity.java
index d3d03e2..f31af1d 100644
--- a/src/edu/berkeley/cs160/theccertservice/splist/FriendsActivity.java
+++ b/src/edu/berkeley/cs160/theccertservice/splist/FriendsActivity.java
@@ -1,272 +1,272 @@
package edu.berkeley.cs160.theccertservice.splist;
import java.util.HashMap;
import edu.berkeley.cs160.theccertservice.splist.FeedActivity.CreateFeedDialog;
import android.app.Activity;
import android.app.DialogFragment;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ExpandableListView.OnChildClickListener;
public class FriendsActivity extends Activity {
static ExpandableListView exv;
Button addFriend;
EditText friendEmail;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.friends);
displayFeeds();
addFriend = (Button) findViewById(R.id.AddFriend);
friendEmail = (EditText) findViewById(R.id.friendEmail);
addFriend.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
HashMap<String, String> data = new HashMap<String, String>();
data.put("auth_token",MainActivity.authToken);
data.put("email",friendEmail.getText().toString());
MainActivity.server.requestFriend(data, v);
friendEmail.setText("");
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.activity_main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId())
{
case R.id.logout:
//MainActivity.authToken = null;
HashMap<String, String> data = new HashMap<String, String>();
data.put("auth_token", MainActivity.authToken);
MainActivity.server.logout(data);
SharedPreferences.Editor editor = MainActivity.settings.edit();
editor.putString("token", null);
editor.commit();
MainActivity.authToken = null;
Intent intent = new Intent(FriendsActivity.this, MainActivity.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void friendRequest(View view) {
}
private void displayFeeds(){
exv = (ExpandableListView)findViewById(R.id.expandableListView2);
exv.setAdapter(new FriendAdapter(this));
exv.setOnChildClickListener(new OnChildClickListener(){
@Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
if(groupPosition==0){
showFeedDialog(groupPosition, childPosition);
exv.collapseGroup(groupPosition);
exv.expandGroup(groupPosition);
exv.collapseGroup(groupPosition+1);
exv.expandGroup(groupPosition+1);
}
if(groupPosition ==1){
showFeedDialog2(groupPosition, childPosition);
//exv.collapseGroup(groupPosition);
//exv.expandGroup(groupPosition);
}
return false;
}
});
}
public void showFeedDialog(int groupPosition, int childPosition) {
DialogFragment newFragment = new CreateFeedDialog(groupPosition, childPosition);
newFragment.show(getFragmentManager(), "createFeedDialog");
}
public void showFeedDialog2(int groupPosition, int childPosition) {
DialogFragment newFragment1 = new CreateFeedDialog2(groupPosition, childPosition);
newFragment1.show(getFragmentManager(), "createFeedDialog");
}
public static void refreshEXV() {
if (exv != null) {
FriendsActivity.exv.collapseGroup(0);
FriendsActivity.exv.expandGroup(0);
FriendsActivity.exv.collapseGroup(1);
FriendsActivity.exv.expandGroup(1);
}
}
public class CreateFeedDialog extends DialogFragment {
int groupPosition;
int childPosition;
TextView requestEmail;
Button requestAccept;
Button requestReject;
public CreateFeedDialog(int groupPosition, int childPosition) {
// Empty constructor required for DialogFragment
this.groupPosition = groupPosition;
this.childPosition = childPosition;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.friend_request, container);
requestEmail = (TextView) view.findViewById(R.id.requestEmail);
requestEmail.setText(FriendAdapter.friendsRequest.get(childPosition).email);
requestAccept = (Button) view.findViewById(R.id.requestAccept);
requestReject = (Button) view.findViewById(R.id.requestReject);
requestAccept.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
HashMap<String, String> data = new HashMap<String, String>();
data.put("auth_token",MainActivity.authToken);
data.put("email", FriendAdapter.friendsRequest.get(childPosition).email);
MainActivity.server.acceptFriend(data);
Friend f = FriendAdapter.friendsRequest.get(childPosition);
FriendAdapter.friendsRequest.remove(f);
FriendAdapter.friends.add(f);
exv.collapseGroup(groupPosition);
exv.expandGroup(groupPosition);
exv.collapseGroup(groupPosition+1);
exv.expandGroup(groupPosition+1);
done();
}
});
requestReject.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
HashMap<String, String> data = new HashMap<String, String>();
data.put("auth_token",MainActivity.authToken);
data.put("id", String.valueOf(FriendAdapter.friendsRequest.get(childPosition).id));
MainActivity.server.removeFriend(data);
FriendAdapter.friendsRequest.remove(FriendAdapter.friendsRequest.get(childPosition));
done();
exv.collapseGroup(groupPosition);
exv.expandGroup(groupPosition);
}
});
return view;
}
public void done() {
this.dismiss();
}
}
public class CreateFeedDialog2 extends DialogFragment {
int groupPosition;
int childPosition;
TextView friend_name;
TextView friend_email;
Button friend_delete;
Button friend_cancel;
public CreateFeedDialog2(int groupPosition, int childPosition) {
// Empty constructor required for DialogFragment
this.groupPosition = groupPosition;
this.childPosition = childPosition;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.delete_friend, container);
friend_name = (TextView) view.findViewById(R.id.friend_name);
friend_name.setText(FriendAdapter.friends.get(childPosition).name);
//System.out.print("hello I am here");
friend_email = (TextView) view.findViewById(R.id.friend_email);
friend_email.setText(FriendAdapter.friends.get(childPosition).email);
friend_delete = (Button) view.findViewById(R.id.friend_delete);
friend_delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
HashMap<String, String> data = new HashMap<String, String>();
data.put("auth_token",MainActivity.authToken);
- data.put("id", String.valueOf(FriendAdapter.friends.get(childPosition).id));
+ data.put("friend_id", String.valueOf(FriendAdapter.friends.get(childPosition).id));
MainActivity.server.removeFriend(data);
FriendAdapter.friends.remove(FriendAdapter.friends.get(childPosition));
done();
exv.collapseGroup(groupPosition);
exv.expandGroup(groupPosition);
}
});
friend_cancel = (Button) view.findViewById(R.id.friend_cancel);
friend_cancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
done();
}
});
return view;
}
//
public void done() {
this.dismiss();
}
}
}
diff --git a/src/edu/berkeley/cs160/theccertservice/splist/Server.java b/src/edu/berkeley/cs160/theccertservice/splist/Server.java
index 2935ca6..3c7659a 100644
--- a/src/edu/berkeley/cs160/theccertservice/splist/Server.java
+++ b/src/edu/berkeley/cs160/theccertservice/splist/Server.java
@@ -1,435 +1,436 @@
package edu.berkeley.cs160.theccertservice.splist;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
public class Server {
public String SERVER;
public Server(String server) {
this.SERVER = server;
}
public void createAccount(Map p, final SignUpActivity a) {
class CreateAcct extends JsonTask {
public CreateAcct(String _path) {
super(SERVER + _path);
}
@Override
public void onPostExecute(JSONObject data) {
if (data != null) {
Log.d("Json data", data.toString());
}
a.onUserCreation();
}
}
CreateAcct c = new CreateAcct("/users");
c.execute(p);
}
public void login(Map p, final MainActivity a) {
class AcctLogin extends JsonTask {
public AcctLogin(String _path) {
super(SERVER + _path);
}
@Override
public void onPostExecute(JSONObject data) {
if (data != null) {
//Log.d("Json data", data.toString());
String token = null;
int id = -1;
String name = null;
String message = null;
try {
message = data.getString("message");
} catch (JSONException e1) {
e1.printStackTrace();
}
if (message.compareTo("success") == 0) {
try {
token = (String) data.get("token");
id = data.getInt("id");
name = data.getString("name");
} catch (JSONException e) {
// The login request failed so we can do something here if needed
e.printStackTrace();
}
SharedPreferences.Editor editor = MainActivity.settings.edit();
editor.putString("token", token);
editor.putInt("id", id);
editor.commit();
MainActivity.authToken = token;
MainActivity.userId = id;
MainActivity.userName = name;
a.afterLoginAttempt(true);
return;
}
}
a.afterLoginAttempt(false);
Log.d("Json data", "Request failed");
}
}
AcctLogin c = new AcctLogin("/tokens/create");
c.execute(p);
}
public void logout(Map p) {
class AcctLogout extends JsonTask {
public AcctLogout(String _path) {
super(SERVER + _path);
}
@Override
public void onPostExecute(JSONObject data) {
if (data != null) {
Log.d("Json data", data.toString());
}
}
}
AcctLogout c = new AcctLogout("/tokens/delete");
c.execute(p);
}
public void getItems(Map p) {
class gItems extends JsonTask {
public gItems(String _path) {
super(SERVER + _path);
}
@Override
public void onPostExecute(JSONObject data) {
if (data != null) {
//Log.d("Json data getItems", data.toString());
JSONArray items = null;
if (MainActivity.firstUpdate)
ShoppingList.hm = new HashMap<String, ShoppingList>();
ArrayList<ShoppingList> lists = new ArrayList<ShoppingList>();
ArrayList<Item> itemsFriendsWillSplit = new ArrayList<Item>();
try {
items = (JSONArray) data.get("items");
for (int i = 0; i < items.length(); i++) {
JSONObject item = (JSONObject) items.get(i);
Item sItem = new Item(item);
sItem._list.addItem(sItem);
if (!lists.contains(sItem._list))
lists.add(sItem._list);
if (sItem._shareAccepted) {
itemsFriendsWillSplit.add(sItem);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
synchronized (FeedAdapter.itemsIWillSplit) {
FeedAdapter.itemsFriendsWillSplit = itemsFriendsWillSplit;
}
if (MainActivity.firstUpdate && ListActivity.mainListActivity != null) {
ListActivity.mainListActivity.updateListNames();
ListActivity.mainListActivity.updateItemsList();
MainActivity.firstUpdate = false;
}
}
}
}
gItems c = new gItems("/item/getItems");
c.execute(p);
}
public void getSharedItems(Map p) {
class gSharedItems extends JsonTask {
public gSharedItems(String _path) {
super(SERVER + _path);
}
@Override
public void onPostExecute(JSONObject data) {
if (data != null) {
//Log.d("Json data getSharedItems", data.toString());
JSONArray items = null;
ArrayList<Item> itemsIWillSplit = new ArrayList<Item>();
ArrayList<Item> itemsFriendsWantToSplit = new ArrayList<Item>();
try {
items = (JSONArray) data.get("items");
for (int i = 0; i < items.length(); i++) {
JSONObject item = (JSONObject) items.get(i);
Item sItem = new Item(item);
sItem._list.addItem(sItem);
if (sItem._shareAccepted) {
itemsIWillSplit.add(sItem);
} else {
itemsFriendsWantToSplit.add(sItem);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
synchronized (FeedAdapter.itemsIWillSplit) {
FeedAdapter.itemsIWillSplit = itemsIWillSplit;
}
synchronized (FeedAdapter.itemsFriendsWantToSplit) {
FeedAdapter.itemsFriendsWantToSplit = itemsFriendsWantToSplit;
}
if (CalcBillActivity.mainCalcBillAct != null) {
CalcBillActivity.mainCalcBillAct.updateListNames();
}
}
}
}
gSharedItems c = new gSharedItems("/item/getSharedItems");
c.execute(p);
}
public void getFriends(Map p) {
class gFriend extends JsonTask {
public gFriend(String _path) {
super(SERVER + _path);
}
@Override
public void onPostExecute(JSONObject data) {
if (data != null) {
Log.d("Json data", data.toString());
JSONArray friends = null;
try {
friends = (JSONArray) data.get("friends");
} catch (JSONException e) {
//something happened!
e.printStackTrace();
}
Friend.allFriends = new ArrayList<Friend>();
ArrayList<Friend> friendsRequest = new ArrayList<Friend>();
ArrayList<Friend> myfriends = new ArrayList<Friend>();
for (int i = 0; i < friends.length(); i++) {
JSONObject f = null;
try {
f = friends.getJSONObject(i);
} catch (JSONException e) {
//Oh noes!
e.printStackTrace();
}
if (f != null) {
try {
Friend fr = new Friend( f.getString("name"),
f.getString("email"),
f.getInt("id"),
f.getBoolean("accepted"),
f.getString("asker"));
if (fr.haveAcceptedRequest) {
myfriends.add(fr);
} else {
if (fr.asker.compareTo("them") == 0){
friendsRequest.add(fr);
}
}
} catch (NumberFormatException e) {
//It done go wrong
e.printStackTrace();
} catch (JSONException e) {
//It be even more wrong
e.printStackTrace();
}
}
}
FriendAdapter.friends = myfriends;
FriendAdapter.friendsRequest = friendsRequest;
FriendsActivity.refreshEXV();
}
}
}
gFriend c = new gFriend("/user/getFriends");
c.execute(p);
}
public void requestFriend(Map p, final View v) {
class rFriend extends JsonTask {
public rFriend(String _path) {
super(SERVER + _path);
}
@Override
public void onPostExecute(JSONObject data) {
if (data != null) {
Log.d("Json data", data.toString());
try {
String message = data.getString("status");
if (message.contains("success")) {
Toast.makeText(v.getContext(),"Your friend request has been sent sucessfully!",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(v.getContext(), "Friend Request Failed. " + message + ".", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
}
} else {
Toast.makeText(v.getContext(),"Not Connected to the Interwebz",Toast.LENGTH_SHORT).show();
}
}
}
rFriend c = new rFriend("/user/makeFriendReq");
c.execute(p);
}
public void acceptFriend(Map p) {
class aFriend extends JsonTask {
public aFriend(String _path) {
super(SERVER + _path);
}
@Override
public void onPostExecute(JSONObject data) {
if (data != null)
Log.d("Json data", data.toString());
//a.onUserCreation();
}
}
aFriend c = new aFriend("/user/acceptFriendReq");
c.execute(p);
}
public void addItem(Map p) {
class aItem extends JsonTask {
public aItem(String _path) {
super(SERVER + _path);
}
@Override
public void onPostExecute(JSONObject data) {
if (data != null) {
Log.d("Json data", data.toString());
int id = -1;
String list = null;
String name = null;
String price = null;
boolean shared = false;
try {
id = data.getInt("id");
name = data.getString("name");
price = data.getString("price");
list = data.getString("list");
shared = data.getBoolean("shared");
for (Item i : ShoppingList.getShoppingList(list)._items) {
if (i._shared == shared && i._name == name &&
i._price.toString() == price && i._id == -1) {
i._id = id;
break;
}
}
} catch (JSONException e) {
Log.d("Json data parsing", "Failed...");
}
}
}
}
aItem c = new aItem("/item/add");
c.execute(p);
}
public void editItem(Map p) {
class eItem extends JsonTask {
public eItem(String _path) {
super(SERVER + _path);
}
@Override
public void onPostExecute(JSONObject data) {
if (data != null) {
Log.d("Json data", data.toString());
}
}
}
eItem c = new eItem("/item/edit");
c.execute(p);
}
public void deleteItem(Map p) {
class dItem extends JsonTask {
public dItem(String _path) {
super(SERVER + _path);
}
@Override
public void onPostExecute(JSONObject data) {
if (data != null) {
Log.d("Json data", data.toString());
}
}
}
dItem c = new dItem("/item/delete");
c.execute(p);
+ //
}
public void removeFriend(Map p) {
class dItem extends JsonTask {
public dItem(String _path) {
super(SERVER + _path);
}
@Override
public void onPostExecute(JSONObject data) {
if (data != null) {
Log.d("Json data", data.toString());
}
}
}
dItem c = new dItem("/user/removeFriend");
c.execute(p);
}
public void acceptShare(Map p) {
class dItem extends JsonTask {
public dItem(String _path) {
super(SERVER + _path);
}
@Override
public void onPostExecute(JSONObject data) {
if (data != null) {
Log.d("Json data", data.toString());
}
}
}
dItem c = new dItem("/item/acceptShare");
c.execute(p);
}
}
| false | false | null | null |
diff --git a/osmdroid-android/src/org/andnav/osm/views/OpenStreetMapView.java b/osmdroid-android/src/org/andnav/osm/views/OpenStreetMapView.java
index 407d257..73d7878 100644
--- a/osmdroid-android/src/org/andnav/osm/views/OpenStreetMapView.java
+++ b/osmdroid-android/src/org/andnav/osm/views/OpenStreetMapView.java
@@ -1,1246 +1,1246 @@
// Created by plusminus on 17:45:56 - 25.09.2008
package org.andnav.osm.views;
import java.util.ArrayList;
import java.util.List;
import net.wigle.wigleandroid.ZoomButtonsController;
import net.wigle.wigleandroid.ZoomButtonsController.OnZoomListener;
import org.andnav.osm.DefaultResourceProxyImpl;
import org.andnav.osm.ResourceProxy;
import org.andnav.osm.events.MapListener;
import org.andnav.osm.events.ScrollEvent;
import org.andnav.osm.events.ZoomEvent;
import org.andnav.osm.tileprovider.IRegisterReceiver;
import org.andnav.osm.tileprovider.OpenStreetMapTile;
import org.andnav.osm.tileprovider.util.CloudmadeUtil;
import org.andnav.osm.util.BoundingBoxE6;
import org.andnav.osm.util.GeoPoint;
import org.andnav.osm.util.constants.GeoConstants;
import org.andnav.osm.views.overlay.OpenStreetMapTilesOverlay;
import org.andnav.osm.views.overlay.OpenStreetMapViewOverlay;
import org.andnav.osm.views.overlay.OpenStreetMapViewOverlay.Snappable;
import org.andnav.osm.views.util.IOpenStreetMapRendererInfo;
import org.andnav.osm.views.util.Mercator;
import org.andnav.osm.views.util.OpenStreetMapRendererFactory;
import org.andnav.osm.views.util.OpenStreetMapTileProvider;
import org.andnav.osm.views.util.OpenStreetMapTileProviderDirect;
import org.andnav.osm.views.util.constants.OpenStreetMapViewConstants;
import org.metalev.multitouch.controller.MultiTouchController;
import org.metalev.multitouch.controller.MultiTouchController.MultiTouchObjectCanvas;
import org.metalev.multitouch.controller.MultiTouchController.PointInfo;
import org.metalev.multitouch.controller.MultiTouchController.PositionAndScale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.ScaleAnimation;
import android.widget.Scroller;
public class OpenStreetMapView extends View implements OpenStreetMapViewConstants, MultiTouchObjectCanvas<Object> {
// ===========================================================
// Constants
// ===========================================================
private static final Logger logger = LoggerFactory.getLogger(OpenStreetMapView.class);
final static String BUNDLE_RENDERER = "org.andnav.osm.views.OpenStreetMapView.RENDERER";
final static String BUNDLE_SCROLL_X = "org.andnav.osm.views.OpenStreetMapView.SCROLL_X";
final static String BUNDLE_SCROLL_Y = "org.andnav.osm.views.OpenStreetMapView.SCROLL_Y";
final static String BUNDLE_ZOOM_LEVEL = "org.andnav.osm.views.OpenStreetMapView.ZOOM";
private static final double ZOOM_SENSITIVITY = 1.3;
private static final double ZOOM_LOG_BASE_INV = 1.0 / Math.log(2.0 / ZOOM_SENSITIVITY);
// ===========================================================
// Fields
// ===========================================================
/** Current zoom level for map tiles. */
private int mZoomLevel = 0;
private final ArrayList<OpenStreetMapViewOverlay> mOverlays = new ArrayList<OpenStreetMapViewOverlay>();
private final Paint mPaint = new Paint();
private OpenStreetMapViewProjection mProjection;
private OpenStreetMapView mMiniMap, mMaxiMap;
private final OpenStreetMapTilesOverlay mMapOverlay;
private final GestureDetector mGestureDetector;
/** Handles map scrolling */
private final Scroller mScroller;
private final ScaleAnimation mZoomInAnimation;
private final ScaleAnimation mZoomOutAnimation;
private final MyAnimationListener mAnimationListener = new MyAnimationListener();
private OpenStreetMapViewController mController;
private int mMiniMapOverriddenVisibility = NOT_SET;
private int mMiniMapZoomDiff = NOT_SET;
// XXX we can use android.widget.ZoomButtonsController if we upgrade the dependency to Android 1.6
private ZoomButtonsController mZoomController;
private boolean mEnableZoomController = false;
private ResourceProxy mResourceProxy;
private MultiTouchController<Object> mMultiTouchController;
private float mMultiTouchScale = 1.0f;
protected MapListener mListener;
// for speed (avoiding allocations)
private Matrix mMatrix = new Matrix();
private BoundingBoxE6 mBoundingBox = new BoundingBoxE6(0,0,0,0);
private int[] mIntArray = new int[2];
// ===========================================================
// Constructors
// ===========================================================
private OpenStreetMapView(
final Context context,
final AttributeSet attrs,
final IOpenStreetMapRendererInfo rendererInfo,
OpenStreetMapTileProvider tileProvider)
{
super(context, attrs);
mResourceProxy = new DefaultResourceProxyImpl(context);
this.mController = new OpenStreetMapViewController(this);
this.mScroller = new Scroller(context);
if(tileProvider == null) {
final Context applicationContext = context.getApplicationContext();
final String cloudmadeKey = getCloudmadeKey(applicationContext);
final IRegisterReceiver registerReceiver = new IRegisterReceiver() {
@Override
public Intent registerReceiver(final BroadcastReceiver aReceiver, final IntentFilter aFilter) {
return applicationContext.registerReceiver(aReceiver, aFilter);
}
@Override
public void unregisterReceiver(final BroadcastReceiver aReceiver) {
applicationContext.unregisterReceiver(aReceiver);
}
};
tileProvider = new OpenStreetMapTileProviderDirect(new SimpleInvalidationHandler(), cloudmadeKey, registerReceiver);
}
this.mMapOverlay = new OpenStreetMapTilesOverlay(this, OpenStreetMapRendererFactory.getRenderer(rendererInfo, attrs), tileProvider, mResourceProxy);
mOverlays.add(this.mMapOverlay);
this.mZoomController = new ZoomButtonsController(this);
this.mZoomController.setOnZoomListener(new OpenStreetMapViewZoomListener());
mZoomInAnimation = new ScaleAnimation(1, 2, 1, 2, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
mZoomOutAnimation = new ScaleAnimation(1, 0.5f, 1, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
mZoomInAnimation.setDuration(ANIMATION_DURATION_SHORT);
mZoomOutAnimation.setDuration(ANIMATION_DURATION_SHORT);
mZoomInAnimation.setAnimationListener(mAnimationListener);
mZoomOutAnimation.setAnimationListener(mAnimationListener);
mGestureDetector = new GestureDetector(context, new OpenStreetMapViewGestureDetectorListener());
mGestureDetector.setOnDoubleTapListener(new OpenStreetMapViewDoubleClickListener());
}
public void detach() {
mMapOverlay.detach();
}
/**
* Constructor used by XML layout resource (uses default renderer).
*/
public OpenStreetMapView(Context context, AttributeSet attrs) {
this(context, attrs, null, null);
}
/**
* Standard Constructor.
*/
public OpenStreetMapView(final Context context, final IOpenStreetMapRendererInfo aRendererInfo) {
this(context, null, aRendererInfo, null);
}
/**
* Standard Constructor (uses default renderer).
*/
public OpenStreetMapView(final Context context) {
this(context, null, null, null);
}
/**
* Standard Constructor.
*/
public OpenStreetMapView(
final Context context,
final IOpenStreetMapRendererInfo aRendererInfo,
final OpenStreetMapTileProvider aTileProvider) {
this(context, null, aRendererInfo, aTileProvider);
}
/**
*
* @param context
* @param aRendererInfo
* pass a {@link IOpenStreetMapRendererInfo} you like.
* @param osmv
* another {@link OpenStreetMapView}, to share the TileProvider
* with.<br/>
* May significantly improve the render speed, when using the
* same {@link IOpenStreetMapRendererInfo}.
*/
public OpenStreetMapView(final Context context,
final IOpenStreetMapRendererInfo aRendererInfo,
final OpenStreetMapView aMapToShareTheTileProviderWith) {
this(context, null, aRendererInfo, /* TODO aMapToShareTheTileProviderWith.mTileProvider */ null);
}
// ===========================================================
// Getter & Setter
// ===========================================================
/**
* This MapView takes control of the {@link OpenStreetMapView} passed as
* parameter.<br />
* I.e. it zooms it to x levels less than itself and centers it the same
* coords.<br />
* Its pretty useful when the MiniMap uses the same TileProvider.
*
* @see OpenStreetMapView.OpenStreetMapView(
* @param aOsmvMinimap
* @param aZoomDiff
* 3 is a good Value. Pass {@link OpenStreetMapViewConstants}
* .NOT_SET to disable autozooming of the minimap.
*/
public void setMiniMap(final OpenStreetMapView aOsmvMinimap, final int aZoomDiff) {
this.mMiniMapZoomDiff = aZoomDiff;
this.mMiniMap = aOsmvMinimap;
aOsmvMinimap.setMaxiMap(this);
// make sure that the zoom level of the minimap is set correctly. this is done when
// setting the zoom level of the main map
this.setZoomLevel(this.getZoomLevel());
// Set identical map renderer
this.mMiniMap.setRenderer(this.getRenderer());
// Note the "false" parameter at the end - do NOT pass it further to other maps here
// this.mMiniMap.setMapCenter(this.getMapCenterLatitudeE6(), this.getMapCenterLongitudeE6(), false);
this.mMiniMap.getController().setCenter(this.getMapCenter());
}
public boolean hasMiniMap() {
return this.mMiniMap != null;
}
/**
* @return {@link View}.GONE or {@link View}.VISIBLE or {@link View}
* .INVISIBLE or {@link OpenStreetMapViewConstants}.NOT_SET
* */
public int getOverrideMiniMapVisiblity() {
return this.mMiniMapOverriddenVisibility;
}
/**
* Use this method if you want to make the MiniMap visible i.e.: always or
* never. Use {@link View}.GONE , {@link View}.VISIBLE, {@link View}
* .INVISIBLE. Use {@link OpenStreetMapViewConstants}.NOT_SET to reset this
* feature.
*
* @param aVisiblity
*/
public void setOverrideMiniMapVisiblity(final int aVisiblity) {
switch (aVisiblity) {
case View.GONE:
case View.VISIBLE:
case View.INVISIBLE:
if (this.mMiniMap != null)
this.mMiniMap.setVisibility(aVisiblity);
case NOT_SET:
this.setZoomLevel(this.mZoomLevel);
break;
default:
throw new IllegalArgumentException("See javadoc of this method !!!");
}
this.mMiniMapOverriddenVisibility = aVisiblity;
}
private void setMaxiMap(final OpenStreetMapView aOsmvMaxiMap) {
this.mMaxiMap = aOsmvMaxiMap;
}
public OpenStreetMapViewController getController() {
return this.mController;
}
/**
* You can add/remove/reorder your Overlays using the List of
* {@link OpenStreetMapViewOverlay}. The first (index 0) Overlay gets drawn
* first, the one with the highest as the last one.
*/
public List<OpenStreetMapViewOverlay> getOverlays() {
return this.mOverlays;
}
public Scroller getScroller() {
return mScroller;
}
public double getLatitudeSpan() {
- return this.getDrawnBoundingBoxE6().getLongitudeSpanE6() / 1E6;
+ return this.getDrawnBoundingBoxE6().getLatitudeSpanE6() / 1E6;
}
public int getLatitudeSpanE6() {
return this.getDrawnBoundingBoxE6().getLatitudeSpanE6();
}
public double getLongitudeSpan() {
return this.getDrawnBoundingBoxE6().getLongitudeSpanE6() / 1E6;
}
public int getLongitudeSpanE6() {
return this.getDrawnBoundingBoxE6().getLatitudeSpanE6();
}
public BoundingBoxE6 getDrawnBoundingBoxE6() {
return getBoundingBox(this.getWidth(), this.getHeight());
}
public BoundingBoxE6 getVisibleBoundingBoxE6() {
return getBoundingBox(this.getWidth(), this.getHeight());
}
private BoundingBoxE6 getBoundingBox(final int pViewWidth, final int pViewHeight){
final int mapTileZoom = mMapOverlay.getRendererInfo().maptileZoom();
final int world_2 = (1 << mZoomLevel + mapTileZoom - 1);
final int north = world_2 + getScrollY() - getHeight()/2;
final int south = world_2 + getScrollY() + getHeight()/2;
final int west = world_2 + getScrollX() - getWidth()/2;
final int east = world_2 + getScrollX() + getWidth()/2;
return Mercator.getBoundingBoxFromCoords(west, north, east, south, mZoomLevel + mapTileZoom);
}
/**
* This class is only meant to be used during on call of onDraw(). Otherwise
* it may produce strange results.
*
* @return
*/
public OpenStreetMapViewProjection getProjection() {
return mProjection;
}
void setMapCenter(final GeoPoint aCenter) {
this.setMapCenter(aCenter.getLatitudeE6(), aCenter.getLongitudeE6());
}
void setMapCenter(final int aLatitudeE6, final int aLongitudeE6) {
this.setMapCenter(aLatitudeE6, aLongitudeE6, true);
}
void setMapCenter(final int aLatitudeE6, final int aLongitudeE6,
final boolean doPassFurther) {
if (doPassFurther && this.mMiniMap != null)
this.mMiniMap.setMapCenter(aLatitudeE6, aLongitudeE6, false);
else if (doPassFurther && this.mMaxiMap != null)
this.mMaxiMap.setMapCenter(aLatitudeE6, aLongitudeE6, false);
final int[] coords = Mercator.projectGeoPoint(aLatitudeE6, aLongitudeE6, getPixelZoomLevel(), null);
final int worldSize_2 = getWorldSizePx()/2;
if (getAnimation() == null || getAnimation().hasEnded()) {
logger.debug("StartScroll");
mScroller.startScroll(getScrollX(), getScrollY(),
coords[MAPTILE_LONGITUDE_INDEX] - worldSize_2 - getScrollX(),
coords[MAPTILE_LATITUDE_INDEX] - worldSize_2 - getScrollY(), 500);
postInvalidate();
}
}
public IOpenStreetMapRendererInfo getRenderer() {
return this.mMapOverlay.getRendererInfo();
}
public void setRenderer(final IOpenStreetMapRendererInfo aRenderer) {
this.mMapOverlay.setRendererInfo(aRenderer);
if (this.mMiniMap != null)
this.mMiniMap.setRenderer(aRenderer);
this.checkZoomButtons();
this.setZoomLevel(mZoomLevel); // revalidate zoom level
postInvalidate();
}
/**
* @param aZoomLevel
* between 0 (equator) and 18/19(closest), depending on the
* Renderer chosen.
*/
int setZoomLevel(final int aZoomLevel) {
final int minZoomLevel = this.mMapOverlay.getRendererInfo().zoomMinLevel();
final int maxZoomLevel = this.mMapOverlay.getRendererInfo().zoomMaxLevel();
final int newZoomLevel = Math.max(minZoomLevel, Math.min(maxZoomLevel, aZoomLevel));
final int curZoomLevel = this.mZoomLevel;
if (this.mMiniMap != null) {
if (this.mZoomLevel < this.mMiniMapZoomDiff) {
if (this.mMiniMapOverriddenVisibility == NOT_SET)
this.mMiniMap.setVisibility(View.INVISIBLE);
} else {
if (this.mMiniMapOverriddenVisibility == NOT_SET
&& this.mMiniMap.getVisibility() != View.VISIBLE) {
this.mMiniMap.setVisibility(View.VISIBLE);
}
if (this.mMiniMapZoomDiff != NOT_SET)
this.mMiniMap.setZoomLevel(this.mZoomLevel - this.mMiniMapZoomDiff);
}
}
this.mZoomLevel = newZoomLevel;
this.checkZoomButtons();
if(newZoomLevel > curZoomLevel)
scrollTo(getScrollX()<<(newZoomLevel-curZoomLevel), getScrollY()<<(newZoomLevel-curZoomLevel));
else if(newZoomLevel < curZoomLevel)
scrollTo(getScrollX()>>(curZoomLevel-newZoomLevel), getScrollY()>>(curZoomLevel-newZoomLevel));
// snap for all snappables
final Point snapPoint = new Point();
mProjection = new OpenStreetMapViewProjection(); // XXX why do we need a new projection here?
for (OpenStreetMapViewOverlay osmvo : this.mOverlays) {
if (osmvo instanceof Snappable &&
((Snappable)osmvo).onSnapToItem(getScrollX(), getScrollY(), snapPoint, this)) {
scrollTo(snapPoint.x, snapPoint.y);
}
}
// do callback on listener
if (newZoomLevel != curZoomLevel && mListener != null) {
final ZoomEvent event = new ZoomEvent(this, newZoomLevel);
mListener.onZoom(event);
}
return this.mZoomLevel;
}
/**
* Get the current ZoomLevel for the map tiles.
* @return the current ZoomLevel between 0 (equator) and 18/19(closest),
* depending on the Renderer chosen.
*/
public int getZoomLevel() {
return getZoomLevel(true);
}
/**
* Get the current ZoomLevel for the map tiles.
* @param aPending if true and we're animating then return the zoom level
* that we're animating towards, otherwise return the current
* zoom level
* @return the current ZoomLevel between 0 (equator) and 18/19(closest),
* depending on the Renderer chosen.
*/
public int getZoomLevel(final boolean aPending) {
if (aPending && mAnimationListener.animating) {
return mAnimationListener.targetZoomLevel;
} else {
return mZoomLevel;
}
}
/*
* Returns the maximum zoom level for the point currently at the center.
* @return The maximum zoom level for the map's current center.
*/
public int getMaxZoomLevel() {
return getRenderer().zoomMaxLevel();
}
/*
* Returns the minimum zoom level for the point currently at the center.
* @return The minimum zoom level for the map's current center.
*/
public int getMinZoomLevel() {
return getRenderer().zoomMinLevel();
}
public boolean canZoomIn() {
final int maxZoomLevel = getMaxZoomLevel();
if (mZoomLevel >= maxZoomLevel) {
return false;
}
if (mAnimationListener.animating && mAnimationListener.targetZoomLevel >= maxZoomLevel) {
return false;
}
return true;
}
public boolean canZoomOut() {
final int minZoomLevel = getMinZoomLevel();
if (mZoomLevel <= minZoomLevel) {
return false;
}
if (mAnimationListener.animating && mAnimationListener.targetZoomLevel <= minZoomLevel) {
return false;
}
return true;
}
/**
* Zoom in by one zoom level.
*/
boolean zoomIn() {
if (canZoomIn()) {
if (mAnimationListener.animating) {
// TODO extend zoom (and return true)
return false;
} else {
mAnimationListener.targetZoomLevel = mZoomLevel + 1;
mAnimationListener.animating = true;
startAnimation(mZoomInAnimation);
return true;
}
} else {
return false;
}
}
boolean zoomInFixing(final GeoPoint point) {
setMapCenter(point); // TODO should fix on point, not center on it
return zoomIn();
}
/**
* Zoom out by one zoom level.
*/
boolean zoomOut() {
if (canZoomOut()) {
if (mAnimationListener.animating) {
// TODO extend zoom (and return true)
return false;
} else {
mAnimationListener.targetZoomLevel = mZoomLevel - 1;
mAnimationListener.animating = true;
startAnimation(mZoomOutAnimation);
return true;
}
} else {
return false;
}
}
boolean zoomOutFixing(final GeoPoint point) {
setMapCenter(point); // TODO should fix on point, not center on it
return zoomOut();
}
public GeoPoint getMapCenter() {
return new GeoPoint(getMapCenterLatitudeE6(), getMapCenterLongitudeE6());
}
public int getMapCenterLatitudeE6() {
return (int)(Mercator.tile2lat(getScrollY() + getWorldSizePx()/2, getPixelZoomLevel()) * 1E6);
}
public int getMapCenterLongitudeE6() {
return (int)(Mercator.tile2lon(getScrollX() + getWorldSizePx()/2, getPixelZoomLevel()) * 1E6);
}
public void setResourceProxy(final ResourceProxy pResourceProxy) {
mResourceProxy = pResourceProxy;
}
public void onSaveInstanceState(Bundle state) {
state.putString(BUNDLE_RENDERER, getRenderer().name());
state.putInt(BUNDLE_SCROLL_X, getScrollX());
state.putInt(BUNDLE_SCROLL_Y, getScrollY());
state.putInt(BUNDLE_ZOOM_LEVEL, getZoomLevel());
}
public void onRestoreInstanceState(Bundle state) {
final String rendererName = state.containsKey(BUNDLE_RENDERER) ?
state.getString(BUNDLE_RENDERER) :
OpenStreetMapRendererFactory.DEFAULT_RENDERER.name();
final IOpenStreetMapRendererInfo renderer = OpenStreetMapRendererFactory.getRenderer(rendererName);
setRenderer(renderer);
setZoomLevel(state.getInt(BUNDLE_ZOOM_LEVEL, 1));
scrollTo(state.getInt(BUNDLE_SCROLL_X, 0), state.getInt(BUNDLE_SCROLL_Y, 0));
}
/**
* Whether to use the network connection if it's available.
*/
public boolean useDataConnection() {
return mMapOverlay.useDataConnection();
}
/**
* Set whether to use the network connection if it's available.
* @param aMode
* if true use the network connection if it's available.
* if false don't use the network connection even if it's available.
*/
public void setUseDataConnection(boolean aMode) {
mMapOverlay.setUseDataConnection(aMode);
}
// ===========================================================
// Methods from SuperClass/Interfaces
// ===========================================================
public void onLongPress(MotionEvent e) {
for (OpenStreetMapViewOverlay osmvo : this.mOverlays)
if (osmvo.onLongPress(e, this))
return;
}
public boolean onSingleTapUp(MotionEvent e) {
for (OpenStreetMapViewOverlay osmvo : this.mOverlays)
if (osmvo.onSingleTapUp(e, this)) {
postInvalidate();
return true;
}
return false;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
for (OpenStreetMapViewOverlay osmvo : this.mOverlays)
if (osmvo.onKeyDown(keyCode, event, this))
return true;
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
for (OpenStreetMapViewOverlay osmvo : this.mOverlays)
if (osmvo.onKeyUp(keyCode, event, this))
return true;
return super.onKeyUp(keyCode, event);
}
@Override
public boolean onTrackballEvent(MotionEvent event) {
for (OpenStreetMapViewOverlay osmvo : this.mOverlays)
if (osmvo.onTrackballEvent(event, this))
return true;
scrollBy((int)(event.getX() * 25), (int)(event.getY() * 25));
return super.onTrackballEvent(event);
}
@Override
public boolean onTouchEvent(final MotionEvent event) {
if (DEBUGMODE)
logger.debug("onTouchEvent(" + event + ")");
for (OpenStreetMapViewOverlay osmvo : this.mOverlays)
if (osmvo.onTouchEvent(event, this))
{
if (DEBUGMODE)
logger.debug("overlay handled onTouchEvent");
return true;
}
if (mMultiTouchController != null && mMultiTouchController.onTouchEvent(event)) {
if (DEBUGMODE)
logger.debug("mMultiTouchController handled onTouchEvent");
return true;
}
if (mGestureDetector.onTouchEvent(event)) {
if (DEBUGMODE)
logger.debug("mGestureDetector handled onTouchEvent");
return true;
}
boolean r = super.onTouchEvent(event);
if (r) {
if (DEBUGMODE)
logger.debug("super handled onTouchEvent");
} else {
if (DEBUGMODE)
logger.debug("no-one handled onTouchEvent");
}
return r;
}
@Override
public void computeScroll() {
if (mScroller.computeScrollOffset()) {
if (mScroller.isFinished())
setZoomLevel(mZoomLevel);
else
scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
postInvalidate(); // Keep on drawing until the animation has finished.
}
}
@Override
public void scrollTo(int x, int y) {
final int worldSize = getWorldSizePx();
x %= worldSize;
y %= worldSize;
super.scrollTo(x, y);
// do callback on listener
if (mListener != null) {
final ScrollEvent event = new ScrollEvent(this, x, y);
mListener.onScroll(event);
}
}
@Override
public void onDraw(final Canvas c) {
final long startMs = System.currentTimeMillis();
mProjection = new OpenStreetMapViewProjection();
if (mMultiTouchScale == 1.0f) {
c.translate(getWidth() / 2, getHeight() / 2);
} else {
c.getMatrix(mMatrix);
mMatrix.postTranslate(getWidth() / 2, getHeight() / 2);
mMatrix.preScale(mMultiTouchScale, mMultiTouchScale, getScrollX(), getScrollY());
c.setMatrix(mMatrix);
}
/* Draw background */
c.drawColor(Color.LTGRAY);
// This is to slow:
// final Rect r = c.getClipBounds();
// mPaint.setColor(Color.GRAY);
// mPaint.setPathEffect(new DashPathEffect(new float[] {1, 1}, 0));
// for (int x = r.left; x < r.right; x += 20)
// c.drawLine(x, r.top, x, r.bottom, mPaint);
// for (int y = r.top; y < r.bottom; y += 20)
// c.drawLine(r.left, y, r.right, y, mPaint);
/* Draw all Overlays. Avoid allocation by not doing enhanced loop. */
for (int i = 0; i < mOverlays.size(); i++) {
mOverlays.get(i).onManagedDraw(c, this);
}
if (this.mMaxiMap != null) { // If this is a MiniMap
this.mPaint.setColor(Color.RED);
this.mPaint.setStyle(Style.STROKE);
final int viewWidth = this.getWidth();
final int viewHeight = this.getHeight();
c.drawRect(0, 0, viewWidth, viewHeight, this.mPaint);
}
final long endMs = System.currentTimeMillis();
if (DEBUGMODE)
logger.debug("Rendering overall: " + (endMs - startMs) + "ms");
}
@Override
protected void onDetachedFromWindow() {
this.mZoomController.setVisible(false);
this.mMapOverlay.detach();
super.onDetachedFromWindow();
}
// ===========================================================
// Implementation of MultiTouchObjectCanvas
// ===========================================================
@Override
public Object getDraggableObjectAtPoint(final PointInfo pt) {
return this;
}
@Override
public void getPositionAndScale(final Object obj, final PositionAndScale objPosAndScaleOut) {
objPosAndScaleOut.set(0, 0, true, mMultiTouchScale, false, 0, 0, false, 0);
}
@Override
public void selectObject(final Object obj, final PointInfo pt) {
// if obj is null it means we released the pointers
// if scale is not 1 it means we pinched
if (obj == null && mMultiTouchScale != 1.0f) {
float scaleDiffFloat = (float) (Math.log(mMultiTouchScale) * ZOOM_LOG_BASE_INV);
int scaleDiffInt = (int) Math.round(scaleDiffFloat);
setZoomLevel(mZoomLevel + scaleDiffInt);
// XXX maybe zoom in/out instead of zooming direct to zoom level
// - probably not a good idea because you'll repeat the animation
}
// reset scale
mMultiTouchScale = 1.0f;
}
@Override
public boolean setPositionAndScale(final Object obj, final PositionAndScale aNewObjPosAndScale, final PointInfo aTouchPoint) {
mMultiTouchScale = aNewObjPosAndScale.getScale();
invalidate(); // redraw
return true;
}
/*
* Set the MapListener for this view
*/
public void setMapListener(MapListener ml) {
mListener = ml;
}
// ===========================================================
// Package Methods
// ===========================================================
/**
* Get the world size in pixels.
*/
int getWorldSizePx() {
return (1 << getPixelZoomLevel());
}
/**
* Get the equivalent zoom level on pixel scale
*/
int getPixelZoomLevel() {
return this.mZoomLevel + this.mMapOverlay.getRendererInfo().maptileZoom();
}
// ===========================================================
// Methods
// ===========================================================
// NB: this method will be called even if we don't use Cloudmade
// because we only have the context in the constructor
// the alternative would be to only get it when needed,
// but that would mean keeping a handle on the context
private String getCloudmadeKey(final Context aContext) {
return CloudmadeUtil.getCloudmadeKey(aContext);
}
private void checkZoomButtons() {
this.mZoomController.setZoomInEnabled(canZoomIn());
this.mZoomController.setZoomOutEnabled(canZoomOut());
}
private int[] getCenterMapTileCoords() {
final int mapTileZoom = this.mMapOverlay.getRendererInfo().maptileZoom();
final int worldTiles_2 = 1 << (mZoomLevel-1);
// convert to tile coordinate and make positive
return new int[] { (getScrollY() >> mapTileZoom) + worldTiles_2,
(getScrollX() >> mapTileZoom) + worldTiles_2 };
}
/**
* @param centerMapTileCoords
* @param tileSizePx
* @param reuse
* just pass null if you do not have a Point to be 'recycled'.
*/
private Point getUpperLeftCornerOfCenterMapTileInScreen(final int[] centerMapTileCoords,
final int tileSizePx, final Point reuse) {
final Point out = (reuse != null) ? reuse : new Point();
final int worldTiles_2 = 1 << (mZoomLevel-1);
final int centerMapTileScreenLeft = (centerMapTileCoords[MAPTILE_LONGITUDE_INDEX] - worldTiles_2) * tileSizePx - tileSizePx/2;
final int centerMapTileScreenTop = (centerMapTileCoords[MAPTILE_LATITUDE_INDEX] - worldTiles_2) * tileSizePx - tileSizePx/2;
out.set(centerMapTileScreenLeft, centerMapTileScreenTop);
return out;
}
public void setBuiltInZoomControls(boolean on) {
this.mEnableZoomController = on;
this.checkZoomButtons();
}
public void setMultiTouchControls(boolean on) {
mMultiTouchController = on ? new MultiTouchController<Object>(this, false) : null;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
/**
* This class may return valid results until the underlying
* {@link OpenStreetMapView} gets modified in any way (i.e. new center).
*
* @author Nicolas Gramlich
* @author Manuel Stahl
*/
public class OpenStreetMapViewProjection implements GeoConstants {
private final int viewWidth_2 = getWidth() / 2;
private final int viewHeight_2 = getHeight() / 2;
private final int worldSize_2 = getWorldSizePx()/2;
private final int offsetX = - worldSize_2;
private final int offsetY = - worldSize_2;
private final BoundingBoxE6 bb;
private final int zoomLevel;
private final int tileSizePx;
private final int[] centerMapTileCoords;
private final Point upperLeftCornerOfCenterMapTile;
private final int[] reuseInt2 = new int[2];
private OpenStreetMapViewProjection() {
/*
* Do some calculations and drag attributes to local variables to
* save some performance.
*/
zoomLevel = OpenStreetMapView.this.mZoomLevel; // TODO Draw to
// attributes and so
// make it only
// 'valid' for a
// short time.
tileSizePx = getRenderer().maptileSizePx();
/*
* Get the center MapTile which is above this.mLatitudeE6 and
* this.mLongitudeE6 .
*/
centerMapTileCoords = getCenterMapTileCoords();
upperLeftCornerOfCenterMapTile = getUpperLeftCornerOfCenterMapTileInScreen(
centerMapTileCoords, tileSizePx, null);
bb = OpenStreetMapView.this.getDrawnBoundingBoxE6();
}
/**
* Converts x/y ScreenCoordinates to the underlying GeoPoint.
*
* @param x
* @param y
* @return GeoPoint under x/y.
*/
public GeoPoint fromPixels(float x, float y) {
return bb.getGeoPointOfRelativePositionWithLinearInterpolation(x / getWidth(), y / getHeight());
}
public Point fromMapPixels(int x, int y, Point reuse) {
final Point out = (reuse != null) ? reuse : new Point();
out.set(x - viewWidth_2, y - viewHeight_2);
out.offset(getScrollX(), getScrollY());
return out;
}
public float metersToEquatorPixels(final float aMeters) {
return aMeters / EQUATORCIRCUMFENCE * getWorldSizePx();
}
/**
* Converts a GeoPoint to its ScreenCoordinates. <br/>
* <br/>
* <b>CAUTION</b> ! Conversion currently has a large error on
* <code>zoomLevels <= 7</code>.<br/>
* The Error on ZoomLevels higher than 7, the error is below
* <code>1px</code>.<br/>
* TODO: Add a linear interpolation to minimize this error.
*
* <PRE>
* Zoom Error(m) Error(px)
* 11 6m 1/12px
* 10 24m 1/6px
* 8 384m 1/2px
* 6 6144m 3px
* 4 98304m 10px
* </PRE>
*
* @param in
* the GeoPoint you want the onScreenCoordinates of.
* @param reuse
* just pass null if you do not have a Point to be
* 'recycled'.
* @return the Point containing the approximated ScreenCoordinates of
* the GeoPoint passed.
*/
public Point toMapPixels(final GeoPoint in, final Point reuse) {
final Point out = (reuse != null) ? reuse : new Point();
final int[] coords = Mercator.projectGeoPoint(in.getLatitudeE6(), in.getLongitudeE6(), getPixelZoomLevel(), null);
out.set(coords[MAPTILE_LONGITUDE_INDEX], coords[MAPTILE_LATITUDE_INDEX]);
out.offset(offsetX, offsetY);
return out;
}
/**
* Performs only the first computationally heavy part of the projection, needToCall toMapPixelsTranslated to get final position.
* @param latituteE6
* the latitute of the point
* @param longitudeE6
* the longitude of the point
* @param reuse
* just pass null if you do not have a Point to be
* 'recycled'.
* @return intermediate value to be stored and passed to toMapPixelsTranslated on paint.
*/
public Point toMapPixelsProjected(final int latituteE6, final int longitudeE6, final Point reuse) {
final Point out = (reuse != null) ? reuse : new Point();
//26 is the biggest zoomlevel we can project
final int[] coords = Mercator.projectGeoPoint(latituteE6, longitudeE6, 28, this.reuseInt2);
out.set(coords[MAPTILE_LONGITUDE_INDEX], coords[MAPTILE_LATITUDE_INDEX]);
return out;
}
/**
* Performs the second computationally light part of the projection.
* @param in
* the Point calculated by the toMapPixelsProjected
* @param reuse
* just pass null if you do not have a Point to be
* 'recycled'.
* @return the Point containing the approximated ScreenCoordinates of
* the initial GeoPoint passed to the toMapPixelsProjected.
*/
public Point toMapPixelsTranslated(final Point in, final Point reuse) {
final Point out = (reuse != null) ? reuse : new Point();
//26 is the biggest zoomlevel we can project
int zoomDifference = 28 - getPixelZoomLevel();
out.set((in.x >> zoomDifference) + offsetX , (in.y >> zoomDifference) + offsetY );
return out;
}
/**
* Translates a rectangle from screen coordinates to intermediate coordinates.
* @param in the rectangle in screen coordinates
* @return a rectangle in intermediate coords.
*/
public Rect fromPixelsToProjected(final Rect in)
{
Rect result = new Rect();
//26 is the biggest zoomlevel we can project
int zoomDifference = 28 - getPixelZoomLevel();
int x0 = (in.left - offsetX) << zoomDifference;
int x1 = (in.right - offsetX) << zoomDifference;
int y0 = (in.bottom - offsetX) << zoomDifference;
int y1 = (in.top - offsetX) << zoomDifference;
result.set(Math.min(x0,x1), Math.min(y0,y1), Math.max(x0,x1), Math.max(y0,y1));
return result;
}
public Point toPixels(final int[] tileCoords, final Point reuse) {
return toPixels(tileCoords[MAPTILE_LONGITUDE_INDEX], tileCoords[MAPTILE_LATITUDE_INDEX], reuse);
}
public Point toPixels(int tileX, int tileY, final Point reuse) {
final Point out = (reuse != null) ? reuse : new Point();
out.set(tileX * tileSizePx, tileY * tileSizePx);
out.offset(offsetX, offsetY);
return out;
}
public Path toPixels(final List<? extends GeoPoint> in, final Path reuse) {
return toPixels(in, reuse, true);
}
public Rect toPixels(final BoundingBoxE6 pBoundingBoxE6) {
final Rect rect = new Rect();
final Point reuse = new Point();
toMapPixels(new GeoPoint(pBoundingBoxE6.getLatNorthE6(), pBoundingBoxE6.getLonWestE6()), reuse);
rect.left = reuse.x;
rect.top = reuse.y;
toMapPixels(new GeoPoint(pBoundingBoxE6.getLatSouthE6(), pBoundingBoxE6.getLonEastE6()), reuse);
rect.right = reuse.x;
rect.bottom = reuse.y;
return rect;
}
protected Path toPixels(final List<? extends GeoPoint> in, final Path reuse, final boolean doGudermann)
throws IllegalArgumentException {
if (in.size() < 2)
throw new IllegalArgumentException("List of GeoPoints needs to be at least 2.");
final Path out = (reuse != null) ? reuse : new Path();
out.incReserve(in.size());
boolean first = true;
for (GeoPoint gp : in) {
final int[] underGeopointTileCoords = Mercator.projectGeoPoint(gp
.getLatitudeE6(), gp.getLongitudeE6(), zoomLevel, null);
/*
* Calculate the Latitude/Longitude on the left-upper
* ScreenCoords of the MapTile.
*/
final BoundingBoxE6 bb = Mercator.getBoundingBoxFromMapTile(underGeopointTileCoords,
zoomLevel);
final float[] relativePositionInCenterMapTile;
if (doGudermann && zoomLevel < 7)
relativePositionInCenterMapTile = bb
.getRelativePositionOfGeoPointInBoundingBoxWithExactGudermannInterpolation(
gp.getLatitudeE6(), gp.getLongitudeE6(), null);
else
relativePositionInCenterMapTile = bb
.getRelativePositionOfGeoPointInBoundingBoxWithLinearInterpolation(gp
.getLatitudeE6(), gp.getLongitudeE6(), null);
final int tileDiffX = centerMapTileCoords[MAPTILE_LONGITUDE_INDEX]
- underGeopointTileCoords[MAPTILE_LONGITUDE_INDEX];
final int tileDiffY = centerMapTileCoords[MAPTILE_LATITUDE_INDEX]
- underGeopointTileCoords[MAPTILE_LATITUDE_INDEX];
final int underGeopointTileScreenLeft = upperLeftCornerOfCenterMapTile.x
- (tileSizePx * tileDiffX);
final int underGeopointTileScreenTop = upperLeftCornerOfCenterMapTile.y
- (tileSizePx * tileDiffY);
final int x = underGeopointTileScreenLeft
+ (int) (relativePositionInCenterMapTile[MAPTILE_LONGITUDE_INDEX] * tileSizePx);
final int y = underGeopointTileScreenTop
+ (int) (relativePositionInCenterMapTile[MAPTILE_LATITUDE_INDEX] * tileSizePx);
/* Add up the offset caused by touch. */
if (first)
out.moveTo(x, y);
// out.moveTo(x + OpenStreetMapView.this.mTouchMapOffsetX, y
// + OpenStreetMapView.this.mTouchMapOffsetY);
else
out.lineTo(x, y);
first = false;
}
return out;
}
}
private class OpenStreetMapViewGestureDetectorListener implements OnGestureListener {
@Override
public boolean onDown(MotionEvent e) {
mZoomController.setVisible(mEnableZoomController);
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
final int worldSize = getWorldSizePx();
mScroller.fling(getScrollX(), getScrollY(), (int)-velocityX, (int)-velocityY, -worldSize, worldSize, -worldSize, worldSize);
return true;
}
@Override
public void onLongPress(MotionEvent e) {
OpenStreetMapView.this.onLongPress(e);
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
scrollBy((int)distanceX, (int)distanceY);
return true;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return OpenStreetMapView.this.onSingleTapUp(e);
}
}
private class OpenStreetMapViewDoubleClickListener implements GestureDetector.OnDoubleTapListener {
@Override
public boolean onDoubleTap(final MotionEvent e) {
final GeoPoint center = getProjection().fromPixels(e.getX(), e.getY());
return zoomInFixing(center);
}
@Override
public boolean onDoubleTapEvent(final MotionEvent e) {
return false;
}
@Override
public boolean onSingleTapConfirmed(final MotionEvent e) {
return false;
}
}
private class OpenStreetMapViewZoomListener implements OnZoomListener {
@Override
public void onZoom(boolean zoomIn) {
if(zoomIn)
getController().zoomIn();
else
getController().zoomOut();
}
@Override
public void onVisibilityChanged(boolean visible) {}
}
private class MyAnimationListener implements AnimationListener {
private int targetZoomLevel;
private boolean animating;
@Override
public void onAnimationEnd(Animation aAnimation) {
animating = false;
setZoomLevel(targetZoomLevel);
}
@Override
public void onAnimationRepeat(Animation aAnimation) {
}
@Override
public void onAnimationStart(Animation aAnimation) {
animating = true;
}
}
private class SimpleInvalidationHandler extends Handler {
@Override
public void handleMessage(final Message msg) {
switch (msg.what) {
case OpenStreetMapTile.MAPTILE_SUCCESS_ID:
invalidate();
break;
}
}
}
}
| true | false | null | null |
diff --git a/org/wargamer2010/signshop/util/itemUtil.java b/org/wargamer2010/signshop/util/itemUtil.java
index 3e14810..81c7567 100644
--- a/org/wargamer2010/signshop/util/itemUtil.java
+++ b/org/wargamer2010/signshop/util/itemUtil.java
@@ -1,621 +1,623 @@
package org.wargamer2010.signshop.util;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.Inventory;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.ChatColor;
import org.bukkit.block.Block;
import org.bukkit.Chunk;
import org.bukkit.block.Sign;
import org.bukkit.material.MaterialData;
import org.bukkit.Material;
import org.bukkit.material.SimpleAttachableMaterialData;
import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import org.bukkit.Bukkit;
import org.bukkit.inventory.InventoryHolder;
import org.wargamer2010.signshop.Seller;
import org.wargamer2010.signshop.blocks.BookFactory;
import org.wargamer2010.signshop.blocks.IBookItem;
import org.wargamer2010.signshop.blocks.IItemTags;
import org.wargamer2010.signshop.blocks.SignShopBooks;
import org.wargamer2010.signshop.blocks.SignShopItemMeta;
import org.wargamer2010.signshop.configuration.SignShopConfig;
import org.wargamer2010.signshop.configuration.Storage;
import org.wargamer2010.signshop.operations.SignShopArguments;
import org.wargamer2010.signshop.operations.SignShopArgumentsType;
import org.wargamer2010.signshop.operations.SignShopOperationListItem;
public class itemUtil {
private static HashMap<Integer, String> discs;
private itemUtil() {
}
public static void initDiscs() {
// This is pretty ugly but I really couldn't find another way in
// bukkit's source to get this via a native function
// Source: http://www.minecraftwiki.net/wiki/Data_values
discs = new HashMap<Integer, String>();
discs.put(2256, "13 Disc");
discs.put(2257, "Cat Disc");
discs.put(2258, "Blocks Disc");
discs.put(2259, "Chirp Disc");
discs.put(2260, "Far Disc");
discs.put(2261, "Mall Disc");
discs.put(2262, "Mellohi Disc");
discs.put(2263, "Stal Disc");
discs.put(2264, "Strad Disc");
discs.put(2265, "Ward Disc");
discs.put(2266, "11 Disc");
discs.put(2267, "Wait Disc");
}
public static ItemStack[] getSingleAmount(ItemStack[] isItems) {
List<ItemStack> items = new ArrayList<ItemStack>();
IItemTags tags = BookFactory.getItemTags();
for(ItemStack item: isItems) {
ItemStack isBackup = getSingleAmountOfStack(item);
if(!items.contains(isBackup))
items.add(isBackup);
}
ItemStack[] isBackupToTake = new ItemStack[items.size()];
int i = 0;
for(ItemStack entry : items) {
isBackupToTake[i] = entry;
i++;
}
return isBackupToTake;
}
public static ItemStack[] getAllItemStacksForContainables(List<Block> containables) {
List<ItemStack> tempItems = new LinkedList<ItemStack>();
for(Block bHolder : containables) {
if(bHolder.getState() instanceof InventoryHolder) {
InventoryHolder Holder = (InventoryHolder)bHolder.getState();
for(ItemStack item : Holder.getInventory().getContents()) {
if(item != null && item.getAmount() > 0) {
tempItems.add(item);
}
}
}
}
return tempItems.toArray(new ItemStack[tempItems.size()]);
}
public static boolean stockOKForContainables(List<Block> containables, ItemStack[] items, boolean bTakeOrGive) {
return (getFirstStockOKForContainables(containables, items, bTakeOrGive) != null);
}
public static InventoryHolder getFirstStockOKForContainables(List<Block> containables, ItemStack[] items, boolean bTakeOrGive) {
for(Block bHolder : containables) {
if(bHolder.getState() instanceof InventoryHolder) {
InventoryHolder Holder = (InventoryHolder)bHolder.getState();
if(isStockOK(Holder.getInventory(), items, bTakeOrGive))
return Holder;
}
}
return null;
}
public static Boolean singeAmountStockOK(Inventory iiInventory, ItemStack[] isItemsToTake, boolean bTakeOrGive) {
return isStockOK(iiInventory, getSingleAmount(isItemsToTake), bTakeOrGive);
}
public static Boolean isStockOK(Inventory iiInventory, ItemStack[] isItemsToTake, boolean bTakeOrGive) {
try {
ItemStack[] isChestItems = iiInventory.getContents();
ItemStack[] isBackup = getBackupItemStack(isChestItems);
ItemStack[] isBackupToTake = getBackupItemStack(isItemsToTake);
HashMap<Integer, ItemStack> leftOver;
if(bTakeOrGive)
leftOver = iiInventory.removeItem(isBackupToTake);
else
leftOver = iiInventory.addItem(isBackupToTake);
Boolean bStockOK = true;
if(!leftOver.isEmpty())
bStockOK = false;
iiInventory.setContents(isBackup);
return bStockOK;
} catch(NullPointerException ex) {
// Chest is not available, contents are NULL. So let's assume the Stock is not OK
return false;
}
}
public static String binaryToRoman(int binary) {
final String[] RCODE = {"M", "CM", "D", "CD", "C", "XC", "L",
"XL", "X", "IX", "V", "IV", "I"};
final int[] BVAL = {1000, 900, 500, 400, 100, 90, 50,
40, 10, 9, 5, 4, 1};
if (binary <= 0 || binary >= 4000) {
return "";
}
String roman = "";
for (int i = 0; i < RCODE.length; i++) {
while (binary >= BVAL[i]) {
binary -= BVAL[i];
roman += RCODE[i];
}
}
return roman;
}
private static String lookupDisc(int id) {
if(discs.containsKey(id))
return discs.get(id);
else
return "";
}
public static boolean isDisc(int id) {
return (discs.containsKey(id) || id > 2267);
}
public static String formatData(MaterialData data) {
short s = 0;
return formatData(data, s);
}
public static String formatData(MaterialData data, short durability) {
String sData;
// Lookup spout custom material
if(Bukkit.getServer().getPluginManager().isPluginEnabled("Spout")) {
sData = spoutUtil.getName(data, durability);
if(sData != null)
return sData;
}
// For some reason running tostring on data when it's from an attachable material
// will cause a NullPointerException, thus if we're dealing with an attachable, go the easy way :)
if(data instanceof SimpleAttachableMaterialData)
return stringFormat(data.getItemType().name());
if(!(sData = lookupDisc(data.getItemTypeId())).isEmpty())
return sData;
else
sData = data.toString().toLowerCase();
Pattern p = Pattern.compile("\\(-?[0-9]+\\)");
Matcher m = p.matcher(sData);
sData = m.replaceAll("");
sData = sData.replace("_", " ");
StringBuffer sb = new StringBuffer(sData.length());
p = Pattern.compile("(^|\\W)([a-z])");
m = p.matcher(sData);
while(m.find()) {
m.appendReplacement(sb, m.group(1) + m.group(2).toUpperCase() );
}
m.appendTail(sb);
return sb.toString();
}
private static String stringFormat(String sMaterial){
sMaterial = sMaterial.replace("_"," ");
Pattern p = Pattern.compile("(^|\\W)([a-z])");
Matcher m = p.matcher(sMaterial.toLowerCase());
StringBuffer sb = new StringBuffer(sMaterial.length());
while(m.find()){
m.appendReplacement(sb, m.group(1) + m.group(2).toUpperCase() );
}
m.appendTail(sb);
return sb.toString();
}
private static ItemStack getSingleAmountOfStack(ItemStack item) {
if(item == null)
return null;
IItemTags tags = BookFactory.getItemTags();
ItemStack isBackup = tags.getCraftItemstack(
item.getType(),
1,
item.getDurability()
);
safelyAddEnchantments(isBackup, item.getEnchantments());
if(item.getData() != null){
isBackup.setData(item.getData());
}
return tags.copyTags(item, isBackup);
}
public static String itemStackToString(ItemStack[] isStacks) {
HashMap<ItemStack, Integer> items = new HashMap<ItemStack, Integer>();
HashMap<ItemStack, Map<Enchantment,Integer>> enchantments = new HashMap<ItemStack, Map<Enchantment,Integer>>();
String sItems = "";
Boolean first = true;
Integer tempAmount;
IItemTags tags = BookFactory.getItemTags();
for(ItemStack item: isStacks) {
if(item == null)
continue;
ItemStack isBackup = getSingleAmountOfStack(item);
if(item.getEnchantments().size() > 0)
enchantments.put(isBackup, item.getEnchantments());
if(items.containsKey(isBackup)) {
tempAmount = (items.get(isBackup) + item.getAmount());
items.put(isBackup, tempAmount);
} else
items.put(isBackup, item.getAmount());
}
for(Map.Entry<ItemStack, Integer> entry : items.entrySet()) {
if(first) first = false;
else sItems += ", ";
String newItemMeta = SignShopItemMeta.getName(entry.getKey());
String count = (SignShopItemMeta.getTextColor() + entry.getValue().toString() + " ");
if(newItemMeta.isEmpty())
sItems += (count + formatData(entry.getKey().getData(), entry.getKey().getDurability()));
else
sItems += (count + newItemMeta);
if(itemUtil.isWriteableBook(entry.getKey())) {
IBookItem book = BookFactory.getBookItem(entry.getKey());
if(book != null && (book.getAuthor() != null || book.getTitle() != null))
sItems += (" (" + (book.getTitle() == null ? "Unknown" : book.getTitle()) + " by " + (book.getAuthor() == null ? "Unknown" : book.getAuthor()) + ")");
}
sItems += ChatColor.WHITE;
}
return sItems;
}
public static String enchantmentsToMessageFormat(Map<Enchantment,Integer> enchantments) {
String enchantmentMessage = "";
Boolean eFirst = true;
enchantmentMessage += "(";
for(Map.Entry<Enchantment,Integer> eEntry : enchantments.entrySet()) {
if(eFirst) eFirst = false;
else enchantmentMessage += ", ";
enchantmentMessage += (stringFormat(eEntry.getKey().getName()) + " " + binaryToRoman(eEntry.getValue()));
}
enchantmentMessage += ")";
return enchantmentMessage;
}
public static void setSignStatus(Block sign, ChatColor color) {
if(clickedSign(sign)) {
Sign signblock = ((Sign) sign.getState());
String[] sLines = signblock.getLines();
if(ChatColor.stripColor(sLines[0]).length() < 14) {
signblock.setLine(0, (color + ChatColor.stripColor(sLines[0])));
signblock.update();
}
}
}
public static Boolean safelyAddEnchantments(ItemStack isEnchantMe, Map<Enchantment, Integer> enchantments) {
if(enchantments.isEmpty())
return true;
try {
isEnchantMe.addEnchantments(enchantments);
} catch(IllegalArgumentException ex) {
if(SignShopConfig.getAllowUnsafeEnchantments()) {
try {
isEnchantMe.addUnsafeEnchantments(enchantments);
} catch(IllegalArgumentException exfinal) {
return false;
}
} else
return false;
}
return true;
}
public static HashMap<ItemStack, Integer> StackToMap(ItemStack[] isStacks) {
ItemStack[] isBackup = getBackupItemStack(isStacks);
HashMap<ItemStack, Integer> mReturn = new HashMap<ItemStack, Integer>();
int tempAmount;
for(int i = 0; i < isBackup.length; i++) {
if(isBackup[i] == null) continue;
tempAmount = isBackup[i].getAmount();
isBackup[i].setAmount(1);
if(mReturn.containsKey(isBackup[i])) {
tempAmount += mReturn.get(isBackup[i]);
mReturn.remove(isBackup[i]);
mReturn.put(isBackup[i], tempAmount);
} else
mReturn.put(isBackup[i], tempAmount);
}
return mReturn;
}
public static ItemStack[] getBackupItemStack(ItemStack[] isOriginal) {
if(isOriginal == null)
return null;
ItemStack[] isBackup = new ItemStack[isOriginal.length];
for(int i = 0; i < isOriginal.length; i++){
if(isOriginal[i] != null) {
isBackup[i] = getBackupSingleItemStack(isOriginal[i]);
}
}
return isBackup;
}
public static ItemStack getBackupSingleItemStack(ItemStack isOriginal) {
+ if(isOriginal == null)
+ return isOriginal;
// Calls to Bukkit's inventory modifiers like "removeItem" and such used to modify the incoming stack
// Hence, it was decided to backup all stacks before attempting to do anything with it to prevent the shop's or player's inventory
// from being modified. The bugs have been solved at some point and especially from 1.4.5 onward. Which is why we version-check now
// and take a shortcut if we can. Clone always does a shallow copy here.
if(versionUtil.getBukkitVersionType() == SSBukkitVersion.Post145)
return isOriginal.clone();
IItemTags tags = BookFactory.getItemTags();
ItemStack isBackup = tags.getCraftItemstack(
isOriginal.getType(),
isOriginal.getAmount(),
isOriginal.getDurability()
);
itemUtil.safelyAddEnchantments(isBackup, isOriginal.getEnchantments());
isBackup = tags.copyTags(isOriginal, isBackup);
if(isOriginal.getData() != null) {
isBackup.setData(isOriginal.getData());
}
return isBackup;
}
public static ItemStack[] filterStacks(ItemStack[] all, ItemStack[] filterby) {
ItemStack[] filtered = new ItemStack[all.length];
List<ItemStack> tempFiltered = new LinkedList<ItemStack>();
HashMap<ItemStack, Integer> mFilter = StackToMap(filterby);
for(ItemStack stack : all) {
ItemStack temp = getBackupSingleItemStack(stack);
temp.setAmount(1);
if(mFilter.containsKey(temp)) {
tempFiltered.add(stack);
}
}
return tempFiltered.toArray(filtered);
}
public static HashMap<ItemStack[], Float> variableAmount(Inventory iiFrom, ItemStack[] isItemsToTake) {
ItemStack[] isBackup = getBackupItemStack(isItemsToTake);
HashMap<ItemStack[], Float> returnMap = new HashMap<ItemStack[], Float>();
returnMap.put(isItemsToTake, 1.0f);
Boolean fromOK = itemUtil.isStockOK(iiFrom, isBackup, true);
IItemTags tags = BookFactory.getItemTags();
if(fromOK) {
returnMap.put(isItemsToTake, 1.0f);
return returnMap;
} else if(!SignShopConfig.getAllowVariableAmounts() && !fromOK) {
returnMap.put(isItemsToTake, 0.0f);
return returnMap;
}
returnMap.put(isItemsToTake, 0.0f);
float iCount = 0;
float tempCount;
int i = 0;
HashMap<ItemStack, Integer> mItemsToTake = StackToMap(isBackup);
HashMap<ItemStack, Integer> mInventory = StackToMap(iiFrom.getContents());
ItemStack[] isActual = new ItemStack[mItemsToTake.size()];
for(Map.Entry<ItemStack, Integer> entry : mItemsToTake.entrySet()) {
if(iCount == 0 && mInventory.containsKey(entry.getKey()))
iCount = ((float)mInventory.get(entry.getKey()) / (float)entry.getValue());
else if(iCount != 0 && mInventory.containsKey(entry.getKey())) {
tempCount = ((float)mInventory.get(entry.getKey()) / (float)entry.getValue());
if(tempCount != iCount)
return returnMap;
} else
return returnMap;
isActual[i] = itemUtil.getBackupSingleItemStack(entry.getKey());
isActual[i].setAmount(mInventory.get(entry.getKey()));
i++;
}
returnMap.clear();
returnMap.put(isActual, iCount);
return returnMap;
}
public static void updateStockStatusPerChest(Block bHolder, Block bIgnore) {
List<Block> signs = Storage.get().getSignsFromHolder(bHolder);
if(signs != null) {
for (Block temp : signs) {
if(temp == bIgnore)
continue;
if(!clickedSign(temp))
continue;
Seller seller = Storage.get().getSeller(temp.getLocation());
updateStockStatusPerShop(seller);
}
}
}
public static void updateStockStatusPerShop(Seller pSeller) {
if(pSeller != null) {
Block pSign = pSeller.getSign();
if(pSign == null || !(pSign.getState() instanceof Sign))
return;
String[] sLines = ((Sign) pSign.getState()).getLines();
if(SignShopConfig.getBlocks(signshopUtil.getOperation(sLines[0])).isEmpty())
return;
List<String> operation = SignShopConfig.getBlocks(signshopUtil.getOperation(sLines[0]));
List<SignShopOperationListItem> SignShopOperations = signshopUtil.getSignShopOps(operation);
if(SignShopOperations == null)
return;
SignShopArguments ssArgs = new SignShopArguments(economyUtil.parsePrice(sLines[3]), pSeller.getItems(), pSeller.getContainables(), pSeller.getActivatables(),
null, null, pSign, signshopUtil.getOperation(sLines[0]), null, SignShopArgumentsType.Check);
if(pSeller.getMisc() != null)
ssArgs.miscSettings = pSeller.getMisc();
Boolean reqOK = true;
for(SignShopOperationListItem ssOperation : SignShopOperations) {
ssArgs.setOperationParameters(ssOperation.getParameters());
reqOK = ssOperation.getOperation().checkRequirements(ssArgs, false);
if(!reqOK) {
itemUtil.setSignStatus(pSign, ChatColor.DARK_RED);
break;
}
}
if(reqOK)
itemUtil.setSignStatus(pSign, ChatColor.DARK_BLUE);
}
}
public static void updateStockStatus(Block bSign, ChatColor ccColor) {
Seller seTemp = Storage.get().getSeller(bSign.getLocation());
if(seTemp != null) {
List<Block> iChests = seTemp.getContainables();
for(Block bHolder : iChests)
updateStockStatusPerChest(bHolder, bSign);
}
setSignStatus(bSign, ccColor);
}
public static Boolean clickedSign(Block bBlock) {
return (bBlock.getType() == Material.getMaterial("SIGN") || bBlock.getType() == Material.getMaterial("WALL_SIGN") || bBlock.getType() == Material.getMaterial("SIGN_POST"));
}
public static Boolean clickedDoor(Block bBlock) {
return (bBlock.getType() == Material.getMaterial("WOODEN_DOOR") || bBlock.getType() == Material.getMaterial("IRON_DOOR") || bBlock.getType() == Material.getMaterial("IRON_DOOR_BLOCK"));
}
private static boolean isTopHalf(byte data) {
return ((data & 0x8) == 0x8);
}
public static Block getOtherDoorPart(Block bBlock) {
if(!clickedDoor(bBlock))
return null;
Block up = bBlock.getWorld().getBlockAt(bBlock.getX(), bBlock.getY()+1, bBlock.getZ());
Block down = bBlock.getWorld().getBlockAt(bBlock.getX(), bBlock.getY()-1, bBlock.getZ());
Block otherpart = isTopHalf(bBlock.getData()) ? down : up;
if(clickedDoor(otherpart))
return otherpart;
return null;
}
public static ItemStack[] convertStringtoItemStacks(List<String> sItems) {
IItemTags tags = BookFactory.getItemTags();
ItemStack isItems[] = new ItemStack[sItems.size()];
for(int i = 0; i < sItems.size(); i++) {
try {
String[] sItemprops = sItems.get(i).split(Storage.getItemSeperator());
if(sItemprops.length < 4)
continue;
isItems[i] = tags.getCraftItemstack(
Material.getMaterial(Integer.parseInt(sItemprops[1])),
Integer.parseInt(sItemprops[0]),
Short.parseShort(sItemprops[2])
);
isItems[i].getData().setData(new Byte(sItemprops[3]));
if(sItemprops.length > 4)
safelyAddEnchantments(isItems[i], signshopUtil.convertStringToEnchantments(sItemprops[4]));
if(sItemprops.length > 5) {
try {
isItems[i] = SignShopBooks.addBooksProps(isItems[i], Integer.parseInt(sItemprops[5]));
} catch(NumberFormatException ex) {
}
}
if(sItemprops.length > 6) {
try {
SignShopItemMeta.setMetaForID(isItems[i], Integer.parseInt(sItemprops[6]));
} catch(NumberFormatException ex) {
}
}
} catch(Exception ex) {
continue;
}
}
return isItems;
}
public static boolean isWriteableBook(ItemStack item) {
if(item == null) return false;
return (item.getType() == Material.getMaterial("WRITTEN_BOOK") || item.getType() == Material.getMaterial("BOOK_AND_QUILL"));
}
public static String[] convertItemStacksToString(ItemStack[] isItems) {
List<String> sItems = new ArrayList<String>();
if(isItems == null)
return new String[1];
ItemStack isCurrent;
for(int i = 0; i < isItems.length; i++) {
if(isItems[i] != null) {
isCurrent = isItems[i];
String ID = "";
if(itemUtil.isWriteableBook(isCurrent))
ID = SignShopBooks.getBookID(isCurrent).toString();
String metaID = SignShopItemMeta.getMetaID(isCurrent).toString();
if(metaID.equals("-1"))
metaID = "";
sItems.add((isCurrent.getAmount() + Storage.getItemSeperator()
+ isCurrent.getTypeId() + Storage.getItemSeperator()
+ isCurrent.getDurability() + Storage.getItemSeperator()
+ isCurrent.getData().getData() + Storage.getItemSeperator()
+ signshopUtil.convertEnchantmentsToString(isCurrent.getEnchantments()) + Storage.getItemSeperator()
+ ID + Storage.getItemSeperator()
+ metaID));
}
}
String[] items = new String[sItems.size()];
sItems.toArray(items);
return items;
}
public static boolean itemstackEqual(ItemStack a, ItemStack b, boolean ignoredur) {
if(a.getType() != b.getType())
return false;
if(!ignoredur && a.getData().getData() != b.getData().getData())
return false;
if(!ignoredur && a.getDurability() != b.getDurability())
return false;
if(a.getEnchantments() != b.getEnchantments())
return false;
if(!SignShopItemMeta.isLegacy() && !SignShopItemMeta.getMetaAsMap(a.getItemMeta()).equals(SignShopItemMeta.getMetaAsMap(b.getItemMeta())))
return false;
if(a.getMaxStackSize() != b.getMaxStackSize())
return false;
return true;
}
public static boolean loadChunkByBlock(Block block, int radius) {
boolean OK = true;
int chunksize = 12;
for(int x = -radius; x <= radius; x++) {
for(int y = -radius; y <= radius; y++) {
for(int z = -radius; z <= radius; z++) {
OK = (OK ? loadChunkByBlock(
block.getWorld().getBlockAt(
block.getX()+(x*chunksize),
block.getY()+(y*chunksize),
block.getZ()+(z*chunksize)))
: true);
}
}
}
return OK;
}
public static boolean loadChunkByBlock(Block block) {
if(block == null)
return false;
Chunk chunk = block.getChunk();
if (!chunk.isLoaded())
return chunk.load();
return true; // Chunk already loaded
}
}
| true | false | null | null |
diff --git a/src/com/android/exchange/adapter/CalendarSyncAdapter.java b/src/com/android/exchange/adapter/CalendarSyncAdapter.java
index 1d1059f..b467eb7 100644
--- a/src/com/android/exchange/adapter/CalendarSyncAdapter.java
+++ b/src/com/android/exchange/adapter/CalendarSyncAdapter.java
@@ -1,2172 +1,2174 @@
/*
* Copyright (C) 2008-2009 Marc Blank
* Licensed to The Android Open Source Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.exchange.adapter;
import android.content.ContentProviderClient;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Entity;
import android.content.Entity.NamedContentValues;
import android.content.EntityIterator;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.net.Uri;
import android.os.RemoteException;
import android.provider.CalendarContract;
import android.provider.CalendarContract.Attendees;
import android.provider.CalendarContract.Calendars;
import android.provider.CalendarContract.Events;
import android.provider.CalendarContract.EventsEntity;
import android.provider.CalendarContract.ExtendedProperties;
import android.provider.CalendarContract.Reminders;
import android.provider.CalendarContract.SyncState;
import android.provider.ContactsContract.RawContacts;
import android.provider.SyncStateContract;
import android.text.TextUtils;
import android.util.Log;
import com.android.emailcommon.AccountManagerTypes;
import com.android.emailcommon.provider.EmailContent;
import com.android.emailcommon.provider.EmailContent.Message;
import com.android.emailcommon.utility.Utility;
import com.android.exchange.CommandStatusException;
import com.android.exchange.Eas;
import com.android.exchange.EasOutboxService;
import com.android.exchange.EasSyncService;
import com.android.exchange.ExchangeService;
import com.android.exchange.utility.CalendarUtilities;
import com.android.exchange.utility.Duration;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.Map.Entry;
import java.util.StringTokenizer;
import java.util.TimeZone;
import java.util.UUID;
/**
* Sync adapter class for EAS calendars
*
*/
public class CalendarSyncAdapter extends AbstractSyncAdapter {
private static final String TAG = "EasCalendarSyncAdapter";
private static final String EVENT_SAVED_TIMEZONE_COLUMN = Events.SYNC_DATA1;
/**
* Used to keep track of exception vs parent event dirtiness.
*/
private static final String EVENT_SYNC_MARK = Events.SYNC_DATA8;
private static final String EVENT_SYNC_VERSION = Events.SYNC_DATA4;
// Since exceptions will have the same _SYNC_ID as the original event we have to check that
// there's no original event when finding an item by _SYNC_ID
private static final String SERVER_ID_AND_CALENDAR_ID = Events._SYNC_ID + "=? AND " +
Events.ORIGINAL_SYNC_ID + " ISNULL AND " + Events.CALENDAR_ID + "=?";
private static final String EVENT_ID_AND_CALENDAR_ID = Events._ID + "=? AND " +
Events.ORIGINAL_SYNC_ID + " ISNULL AND " + Events.CALENDAR_ID + "=?";
private static final String DIRTY_OR_MARKED_TOP_LEVEL_IN_CALENDAR = "(" + Events.DIRTY
+ "=1 OR " + EVENT_SYNC_MARK + "= 1) AND " +
Events.ORIGINAL_ID + " ISNULL AND " + Events.CALENDAR_ID + "=?";
private static final String DIRTY_EXCEPTION_IN_CALENDAR =
Events.DIRTY + "=1 AND " + Events.ORIGINAL_ID + " NOTNULL AND " +
Events.CALENDAR_ID + "=?";
private static final String CLIENT_ID_SELECTION = Events.SYNC_DATA2 + "=?";
private static final String ORIGINAL_EVENT_AND_CALENDAR =
Events.ORIGINAL_SYNC_ID + "=? AND " + Events.CALENDAR_ID + "=?";
private static final String ATTENDEES_EXCEPT_ORGANIZER = Attendees.EVENT_ID + "=? AND " +
Attendees.ATTENDEE_RELATIONSHIP + "!=" + Attendees.RELATIONSHIP_ORGANIZER;
private static final String[] ID_PROJECTION = new String[] {Events._ID};
private static final String[] ORIGINAL_EVENT_PROJECTION =
new String[] {Events.ORIGINAL_ID, Events._ID};
private static final String EVENT_ID_AND_NAME =
ExtendedProperties.EVENT_ID + "=? AND " + ExtendedProperties.NAME + "=?";
// Note that we use LIKE below for its case insensitivity
private static final String EVENT_AND_EMAIL =
Attendees.EVENT_ID + "=? AND "+ Attendees.ATTENDEE_EMAIL + " LIKE ?";
private static final int ATTENDEE_STATUS_COLUMN_STATUS = 0;
private static final String[] ATTENDEE_STATUS_PROJECTION =
new String[] {Attendees.ATTENDEE_STATUS};
public static final String CALENDAR_SELECTION =
Calendars.ACCOUNT_NAME + "=? AND " + Calendars.ACCOUNT_TYPE + "=?";
private static final int CALENDAR_SELECTION_ID = 0;
private static final String[] EXTENDED_PROPERTY_PROJECTION =
new String[] {ExtendedProperties._ID};
private static final int EXTENDED_PROPERTY_ID = 0;
private static final String CATEGORY_TOKENIZER_DELIMITER = "\\";
private static final String ATTENDEE_TOKENIZER_DELIMITER = CATEGORY_TOKENIZER_DELIMITER;
private static final String EXTENDED_PROPERTY_USER_ATTENDEE_STATUS = "userAttendeeStatus";
private static final String EXTENDED_PROPERTY_ATTENDEES = "attendees";
private static final String EXTENDED_PROPERTY_DTSTAMP = "dtstamp";
private static final String EXTENDED_PROPERTY_MEETING_STATUS = "meeting_status";
private static final String EXTENDED_PROPERTY_CATEGORIES = "categories";
// Used to indicate that we removed the attendee list because it was too large
private static final String EXTENDED_PROPERTY_ATTENDEES_REDACTED = "attendeesRedacted";
// Used to indicate that upsyncs aren't allowed (we catch this in sendLocalChanges)
private static final String EXTENDED_PROPERTY_UPSYNC_PROHIBITED = "upsyncProhibited";
private static final ContentProviderOperation PLACEHOLDER_OPERATION =
ContentProviderOperation.newInsert(Uri.EMPTY).build();
private static final Object sSyncKeyLock = new Object();
private static final TimeZone UTC_TIMEZONE = TimeZone.getTimeZone("UTC");
private final TimeZone mLocalTimeZone = TimeZone.getDefault();
// Maximum number of allowed attendees; above this number, we mark the Event with the
// attendeesRedacted extended property and don't allow the event to be upsynced to the server
private static final int MAX_SYNCED_ATTENDEES = 50;
// We set the organizer to this when the user is the organizer and we've redacted the
// attendee list. By making the meeting organizer OTHER than the user, we cause the UI to
// prevent edits to this event (except local changes like reminder).
private static final String BOGUS_ORGANIZER_EMAIL = "[email protected]";
// Maximum number of CPO's before we start redacting attendees in exceptions
// The number 500 has been determined empirically; 1500 CPOs appears to be the limit before
// binder failures occur, but we need room at any point for additional events/exceptions so
// we set our limit at 1/3 of the apparent maximum for extra safety
// TODO Find a better solution to this workaround
private static final int MAX_OPS_BEFORE_EXCEPTION_ATTENDEE_REDACTION = 500;
private long mCalendarId = -1;
private String mCalendarIdString;
private String[] mCalendarIdArgument;
/*package*/ String mEmailAddress;
private ArrayList<Long> mDeletedIdList = new ArrayList<Long>();
private ArrayList<Long> mUploadedIdList = new ArrayList<Long>();
private ArrayList<Long> mSendCancelIdList = new ArrayList<Long>();
private ArrayList<Message> mOutgoingMailList = new ArrayList<Message>();
public CalendarSyncAdapter(EasSyncService service) {
super(service);
mEmailAddress = mAccount.mEmailAddress;
Cursor c = mService.mContentResolver.query(Calendars.CONTENT_URI,
new String[] {Calendars._ID}, CALENDAR_SELECTION,
new String[] {mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE}, null);
if (c == null) return;
try {
if (c.moveToFirst()) {
mCalendarId = c.getLong(CALENDAR_SELECTION_ID);
} else {
mCalendarId = CalendarUtilities.createCalendar(mService, mAccount, mMailbox);
}
mCalendarIdString = Long.toString(mCalendarId);
mCalendarIdArgument = new String[] {mCalendarIdString};
} finally {
c.close();
}
}
@Override
public String getCollectionName() {
return "Calendar";
}
@Override
public void cleanup() {
}
@Override
public void wipe() {
// Delete the calendar associated with this account
// CalendarProvider2 does NOT handle selection arguments in deletions
mContentResolver.delete(
asSyncAdapter(Calendars.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE),
Calendars.ACCOUNT_NAME + "=" + DatabaseUtils.sqlEscapeString(mEmailAddress)
+ " AND " + Calendars.ACCOUNT_TYPE + "="
+ DatabaseUtils.sqlEscapeString(AccountManagerTypes.TYPE_EXCHANGE), null);
// Invalidate our calendar observers
ExchangeService.unregisterCalendarObservers();
}
@Override
public void sendSyncOptions(Double protocolVersion, Serializer s) throws IOException {
setPimSyncOptions(protocolVersion, Eas.FILTER_2_WEEKS, s);
}
@Override
public boolean isSyncable() {
return ContentResolver.getSyncAutomatically(mAccountManagerAccount,
CalendarContract.AUTHORITY);
}
@Override
public boolean parse(InputStream is) throws IOException, CommandStatusException {
EasCalendarSyncParser p = new EasCalendarSyncParser(is, this);
return p.parse();
}
public static Uri asSyncAdapter(Uri uri, String account, String accountType) {
return uri.buildUpon().appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true")
.appendQueryParameter(Calendars.ACCOUNT_NAME, account)
.appendQueryParameter(Calendars.ACCOUNT_TYPE, accountType).build();
}
/**
* Generate the uri for the data row associated with this NamedContentValues object
* @param ncv the NamedContentValues object
* @return a uri that can be used to refer to this row
*/
public Uri dataUriFromNamedContentValues(NamedContentValues ncv) {
long id = ncv.values.getAsLong(RawContacts._ID);
Uri dataUri = ContentUris.withAppendedId(ncv.uri, id);
return dataUri;
}
/**
* We get our SyncKey from CalendarProvider. If there's not one, we set it to "0" (the reset
* state) and save that away.
*/
@Override
public String getSyncKey() throws IOException {
synchronized (sSyncKeyLock) {
ContentProviderClient client = mService.mContentResolver
.acquireContentProviderClient(CalendarContract.CONTENT_URI);
try {
byte[] data = SyncStateContract.Helpers.get(
client,
asSyncAdapter(SyncState.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), mAccountManagerAccount);
if (data == null || data.length == 0) {
// Initialize the SyncKey
setSyncKey("0", false);
return "0";
} else {
String syncKey = new String(data);
userLog("SyncKey retrieved as ", syncKey, " from CalendarProvider");
return syncKey;
}
} catch (RemoteException e) {
throw new IOException("Can't get SyncKey from CalendarProvider");
}
}
}
/**
* We only need to set this when we're forced to make the SyncKey "0" (a reset). In all other
* cases, the SyncKey is set within Calendar
*/
@Override
public void setSyncKey(String syncKey, boolean inCommands) throws IOException {
synchronized (sSyncKeyLock) {
if ("0".equals(syncKey) || !inCommands) {
ContentProviderClient client = mService.mContentResolver
.acquireContentProviderClient(CalendarContract.CONTENT_URI);
try {
SyncStateContract.Helpers.set(
client,
asSyncAdapter(SyncState.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), mAccountManagerAccount,
syncKey.getBytes());
userLog("SyncKey set to ", syncKey, " in CalendarProvider");
} catch (RemoteException e) {
throw new IOException("Can't set SyncKey in CalendarProvider");
}
}
mMailbox.mSyncKey = syncKey;
}
}
public class EasCalendarSyncParser extends AbstractSyncParser {
String[] mBindArgument = new String[1];
Uri mAccountUri;
CalendarOperations mOps = new CalendarOperations();
public EasCalendarSyncParser(InputStream in, CalendarSyncAdapter adapter)
throws IOException {
super(in, adapter);
setLoggingTag("CalendarParser");
mAccountUri = Events.CONTENT_URI;
}
private void addOrganizerToAttendees(CalendarOperations ops, long eventId,
String organizerName, String organizerEmail) {
// Handle the organizer (who IS an attendee on device, but NOT in EAS)
if (organizerName != null || organizerEmail != null) {
ContentValues attendeeCv = new ContentValues();
if (organizerName != null) {
attendeeCv.put(Attendees.ATTENDEE_NAME, organizerName);
}
if (organizerEmail != null) {
attendeeCv.put(Attendees.ATTENDEE_EMAIL, organizerEmail);
}
attendeeCv.put(Attendees.ATTENDEE_RELATIONSHIP, Attendees.RELATIONSHIP_ORGANIZER);
attendeeCv.put(Attendees.ATTENDEE_TYPE, Attendees.TYPE_REQUIRED);
attendeeCv.put(Attendees.ATTENDEE_STATUS, Attendees.ATTENDEE_STATUS_ACCEPTED);
if (eventId < 0) {
ops.newAttendee(attendeeCv);
} else {
ops.updatedAttendee(attendeeCv, eventId);
}
}
}
/**
* Set DTSTART, DTEND, DURATION and EVENT_TIMEZONE as appropriate for the given Event
* The follow rules are enforced by CalendarProvider2:
* Events that aren't exceptions MUST have either 1) a DTEND or 2) a DURATION
* Recurring events (i.e. events with RRULE) must have a DURATION
* All-day recurring events MUST have a DURATION that is in the form P<n>D
* Other events MAY have a DURATION in any valid form (we use P<n>M)
* All-day events MUST have hour, minute, and second = 0; in addition, they must have
* the EVENT_TIMEZONE set to UTC
* Also, exceptions to all-day events need to have an ORIGINAL_INSTANCE_TIME that has
* hour, minute, and second = 0 and be set in UTC
* @param cv the ContentValues for the Event
* @param startTime the start time for the Event
* @param endTime the end time for the Event
* @param allDayEvent whether this is an all day event (1) or not (0)
*/
/*package*/ void setTimeRelatedValues(ContentValues cv, long startTime, long endTime,
int allDayEvent) {
// If there's no startTime, the event will be found to be invalid, so return
if (startTime < 0) return;
// EAS events can arrive without an end time, but CalendarProvider requires them
// so we'll default to 30 minutes; this will be superceded if this is an all-day event
if (endTime < 0) endTime = startTime + (30*MINUTES);
// If this is an all-day event, set hour, minute, and second to zero, and use UTC
if (allDayEvent != 0) {
startTime = CalendarUtilities.getUtcAllDayCalendarTime(startTime, mLocalTimeZone);
endTime = CalendarUtilities.getUtcAllDayCalendarTime(endTime, mLocalTimeZone);
String originalTimeZone = cv.getAsString(Events.EVENT_TIMEZONE);
cv.put(EVENT_SAVED_TIMEZONE_COLUMN, originalTimeZone);
cv.put(Events.EVENT_TIMEZONE, UTC_TIMEZONE.getID());
}
// If this is an exception, and the original was an all-day event, make sure the
// original instance time has hour, minute, and second set to zero, and is in UTC
if (cv.containsKey(Events.ORIGINAL_INSTANCE_TIME) &&
cv.containsKey(Events.ORIGINAL_ALL_DAY)) {
Integer ade = cv.getAsInteger(Events.ORIGINAL_ALL_DAY);
if (ade != null && ade != 0) {
long exceptionTime = cv.getAsLong(Events.ORIGINAL_INSTANCE_TIME);
GregorianCalendar cal = new GregorianCalendar(UTC_TIMEZONE);
cal.setTimeInMillis(exceptionTime);
cal.set(GregorianCalendar.HOUR_OF_DAY, 0);
cal.set(GregorianCalendar.MINUTE, 0);
cal.set(GregorianCalendar.SECOND, 0);
cv.put(Events.ORIGINAL_INSTANCE_TIME, cal.getTimeInMillis());
}
}
// Always set DTSTART
cv.put(Events.DTSTART, startTime);
// For recurring events, set DURATION. Use P<n>D format for all day events
if (cv.containsKey(Events.RRULE)) {
if (allDayEvent != 0) {
cv.put(Events.DURATION, "P" + ((endTime - startTime) / DAYS) + "D");
}
else {
cv.put(Events.DURATION, "P" + ((endTime - startTime) / MINUTES) + "M");
}
// For other events, set DTEND and LAST_DATE
} else {
cv.put(Events.DTEND, endTime);
cv.put(Events.LAST_DATE, endTime);
}
}
public void addEvent(CalendarOperations ops, String serverId, boolean update)
throws IOException {
ContentValues cv = new ContentValues();
cv.put(Events.CALENDAR_ID, mCalendarId);
cv.put(Events._SYNC_ID, serverId);
cv.put(Events.HAS_ATTENDEE_DATA, 1);
cv.put(Events.SYNC_DATA2, "0");
int allDayEvent = 0;
String organizerName = null;
String organizerEmail = null;
int eventOffset = -1;
int deleteOffset = -1;
int busyStatus = CalendarUtilities.BUSY_STATUS_TENTATIVE;
int responseType = CalendarUtilities.RESPONSE_TYPE_NONE;
boolean firstTag = true;
long eventId = -1;
long startTime = -1;
long endTime = -1;
TimeZone timeZone = null;
// Keep track of the attendees; exceptions will need them
ArrayList<ContentValues> attendeeValues = new ArrayList<ContentValues>();
int reminderMins = -1;
String dtStamp = null;
boolean organizerAdded = false;
while (nextTag(Tags.SYNC_APPLICATION_DATA) != END) {
if (update && firstTag) {
// Find the event that's being updated
Cursor c = getServerIdCursor(serverId);
long id = -1;
try {
if (c != null && c.moveToFirst()) {
id = c.getLong(0);
}
} finally {
if (c != null) c.close();
}
if (id > 0) {
// DTSTAMP can come first, and we simply need to track it
if (tag == Tags.CALENDAR_DTSTAMP) {
dtStamp = getValue();
continue;
} else if (tag == Tags.CALENDAR_ATTENDEES) {
// This is an attendees-only update; just
// delete/re-add attendees
mBindArgument[0] = Long.toString(id);
ops.add(ContentProviderOperation
.newDelete(
asSyncAdapter(Attendees.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE))
.withSelection(ATTENDEES_EXCEPT_ORGANIZER, mBindArgument)
.build());
eventId = id;
} else {
// Otherwise, delete the original event and recreate it
userLog("Changing (delete/add) event ", serverId);
deleteOffset = ops.newDelete(id, serverId);
// Add a placeholder event so that associated tables can reference
// this as a back reference. We add the event at the end of the method
eventOffset = ops.newEvent(PLACEHOLDER_OPERATION);
}
} else {
// The changed item isn't found. We'll treat this as a new item
eventOffset = ops.newEvent(PLACEHOLDER_OPERATION);
userLog(TAG, "Changed item not found; treating as new.");
}
} else if (firstTag) {
// Add a placeholder event so that associated tables can reference
// this as a back reference. We add the event at the end of the method
eventOffset = ops.newEvent(PLACEHOLDER_OPERATION);
}
firstTag = false;
switch (tag) {
case Tags.CALENDAR_ALL_DAY_EVENT:
allDayEvent = getValueInt();
if (allDayEvent != 0 && timeZone != null) {
// If the event doesn't start at midnight local time, we won't consider
// this an all-day event in the local time zone (this is what OWA does)
GregorianCalendar cal = new GregorianCalendar(mLocalTimeZone);
cal.setTimeInMillis(startTime);
userLog("All-day event arrived in: " + timeZone.getID());
if (cal.get(GregorianCalendar.HOUR_OF_DAY) != 0 ||
cal.get(GregorianCalendar.MINUTE) != 0) {
allDayEvent = 0;
userLog("Not an all-day event locally: " + mLocalTimeZone.getID());
}
}
cv.put(Events.ALL_DAY, allDayEvent);
break;
case Tags.CALENDAR_ATTACHMENTS:
attachmentsParser();
break;
case Tags.CALENDAR_ATTENDEES:
// If eventId >= 0, this is an update; otherwise, a new Event
attendeeValues = attendeesParser(ops, eventId);
break;
case Tags.BASE_BODY:
cv.put(Events.DESCRIPTION, bodyParser());
break;
case Tags.CALENDAR_BODY:
cv.put(Events.DESCRIPTION, getValue());
break;
case Tags.CALENDAR_TIME_ZONE:
timeZone = CalendarUtilities.tziStringToTimeZone(getValue());
if (timeZone == null) {
timeZone = mLocalTimeZone;
}
cv.put(Events.EVENT_TIMEZONE, timeZone.getID());
break;
case Tags.CALENDAR_START_TIME:
startTime = Utility.parseDateTimeToMillis(getValue());
break;
case Tags.CALENDAR_END_TIME:
endTime = Utility.parseDateTimeToMillis(getValue());
break;
case Tags.CALENDAR_EXCEPTIONS:
// For exceptions to show the organizer, the organizer must be added before
// we call exceptionsParser
addOrganizerToAttendees(ops, eventId, organizerName, organizerEmail);
organizerAdded = true;
exceptionsParser(ops, cv, attendeeValues, reminderMins, busyStatus,
startTime, endTime);
break;
case Tags.CALENDAR_LOCATION:
cv.put(Events.EVENT_LOCATION, getValue());
break;
case Tags.CALENDAR_RECURRENCE:
String rrule = recurrenceParser();
if (rrule != null) {
cv.put(Events.RRULE, rrule);
}
break;
case Tags.CALENDAR_ORGANIZER_EMAIL:
organizerEmail = getValue();
cv.put(Events.ORGANIZER, organizerEmail);
break;
case Tags.CALENDAR_SUBJECT:
cv.put(Events.TITLE, getValue());
break;
case Tags.CALENDAR_SENSITIVITY:
cv.put(Events.ACCESS_LEVEL, encodeVisibility(getValueInt()));
break;
case Tags.CALENDAR_ORGANIZER_NAME:
organizerName = getValue();
break;
case Tags.CALENDAR_REMINDER_MINS_BEFORE:
reminderMins = getValueInt();
ops.newReminder(reminderMins);
cv.put(Events.HAS_ALARM, 1);
break;
// The following are fields we should save (for changes), though they don't
// relate to data used by CalendarProvider at this point
case Tags.CALENDAR_UID:
cv.put(Events.SYNC_DATA2, getValue());
break;
case Tags.CALENDAR_DTSTAMP:
dtStamp = getValue();
break;
case Tags.CALENDAR_MEETING_STATUS:
ops.newExtendedProperty(EXTENDED_PROPERTY_MEETING_STATUS, getValue());
break;
case Tags.CALENDAR_BUSY_STATUS:
// We'll set the user's status in the Attendees table below
// Don't set selfAttendeeStatus or CalendarProvider will create a duplicate
// attendee!
busyStatus = getValueInt();
break;
case Tags.CALENDAR_RESPONSE_TYPE:
// EAS 14+ uses this for the user's response status; we'll use this instead
// of busy status, if it appears
responseType = getValueInt();
break;
case Tags.CALENDAR_CATEGORIES:
String categories = categoriesParser(ops);
if (categories.length() > 0) {
ops.newExtendedProperty(EXTENDED_PROPERTY_CATEGORIES, categories);
}
break;
default:
skipTag();
}
}
// Enforce CalendarProvider required properties
setTimeRelatedValues(cv, startTime, endTime, allDayEvent);
// If we haven't added the organizer to attendees, do it now
if (!organizerAdded) {
addOrganizerToAttendees(ops, eventId, organizerName, organizerEmail);
}
// Note that organizerEmail can be null with a DTSTAMP only change from the server
boolean selfOrganizer = (mEmailAddress.equals(organizerEmail));
// Store email addresses of attendees (in a tokenizable string) in ExtendedProperties
// If the user is an attendee, set the attendee status using busyStatus (note that the
// busyStatus is inherited from the parent unless it's specified in the exception)
// Add the insert/update operation for each attendee (based on whether it's add/change)
int numAttendees = attendeeValues.size();
if (numAttendees > MAX_SYNCED_ATTENDEES) {
// Indicate that we've redacted attendees. If we're the organizer, disable edit
// by setting organizerEmail to a bogus value and by setting the upsync prohibited
// extended properly.
// Note that we don't set ANY attendees if we're in this branch; however, the
// organizer has already been included above, and WILL show up (which is good)
if (eventId < 0) {
ops.newExtendedProperty(EXTENDED_PROPERTY_ATTENDEES_REDACTED, "1");
if (selfOrganizer) {
ops.newExtendedProperty(EXTENDED_PROPERTY_UPSYNC_PROHIBITED, "1");
}
} else {
ops.updatedExtendedProperty(EXTENDED_PROPERTY_ATTENDEES_REDACTED, "1", eventId);
if (selfOrganizer) {
ops.updatedExtendedProperty(EXTENDED_PROPERTY_UPSYNC_PROHIBITED, "1",
eventId);
}
}
if (selfOrganizer) {
organizerEmail = BOGUS_ORGANIZER_EMAIL;
cv.put(Events.ORGANIZER, organizerEmail);
}
// Tell UI that we don't have any attendees
cv.put(Events.HAS_ATTENDEE_DATA, "0");
mService.userLog("Maximum number of attendees exceeded; redacting");
} else if (numAttendees > 0) {
StringBuilder sb = new StringBuilder();
for (ContentValues attendee: attendeeValues) {
String attendeeEmail = attendee.getAsString(Attendees.ATTENDEE_EMAIL);
sb.append(attendeeEmail);
sb.append(ATTENDEE_TOKENIZER_DELIMITER);
if (mEmailAddress.equalsIgnoreCase(attendeeEmail)) {
int attendeeStatus;
// We'll use the response type (EAS 14), if we've got one; otherwise, we'll
// try to infer it from busy status
if (responseType != CalendarUtilities.RESPONSE_TYPE_NONE) {
attendeeStatus =
CalendarUtilities.attendeeStatusFromResponseType(responseType);
} else if (!update) {
// For new events in EAS < 14, we have no idea what the busy status
// means, so we show "none", allowing the user to select an option.
attendeeStatus = Attendees.ATTENDEE_STATUS_NONE;
} else {
// For updated events, we'll try to infer the attendee status from the
// busy status
attendeeStatus =
CalendarUtilities.attendeeStatusFromBusyStatus(busyStatus);
}
attendee.put(Attendees.ATTENDEE_STATUS, attendeeStatus);
// If we're an attendee, save away our initial attendee status in the
// event's ExtendedProperties (we look for differences between this and
// the user's current attendee status to determine whether an email needs
// to be sent to the organizer)
// organizerEmail will be null in the case that this is an attendees-only
// change from the server
if (organizerEmail == null ||
!organizerEmail.equalsIgnoreCase(attendeeEmail)) {
if (eventId < 0) {
ops.newExtendedProperty(EXTENDED_PROPERTY_USER_ATTENDEE_STATUS,
Integer.toString(attendeeStatus));
} else {
ops.updatedExtendedProperty(EXTENDED_PROPERTY_USER_ATTENDEE_STATUS,
Integer.toString(attendeeStatus), eventId);
}
}
}
if (eventId < 0) {
ops.newAttendee(attendee);
} else {
ops.updatedAttendee(attendee, eventId);
}
}
if (eventId < 0) {
ops.newExtendedProperty(EXTENDED_PROPERTY_ATTENDEES, sb.toString());
ops.newExtendedProperty(EXTENDED_PROPERTY_ATTENDEES_REDACTED, "0");
ops.newExtendedProperty(EXTENDED_PROPERTY_UPSYNC_PROHIBITED, "0");
} else {
ops.updatedExtendedProperty(EXTENDED_PROPERTY_ATTENDEES, sb.toString(),
eventId);
ops.updatedExtendedProperty(EXTENDED_PROPERTY_ATTENDEES_REDACTED, "0", eventId);
ops.updatedExtendedProperty(EXTENDED_PROPERTY_UPSYNC_PROHIBITED, "0", eventId);
}
}
// Put the real event in the proper place in the ops ArrayList
if (eventOffset >= 0) {
// Store away the DTSTAMP here
if (dtStamp != null) {
ops.newExtendedProperty(EXTENDED_PROPERTY_DTSTAMP, dtStamp);
}
if (isValidEventValues(cv)) {
ops.set(eventOffset,
ContentProviderOperation
.newInsert(
asSyncAdapter(Events.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE))
.withValues(cv).build());
} else {
// If we can't add this event (it's invalid), remove all of the inserts
// we've built for it
int cnt = ops.mCount - eventOffset;
userLog(TAG, "Removing " + cnt + " inserts from mOps");
for (int i = 0; i < cnt; i++) {
ops.remove(eventOffset);
}
ops.mCount = eventOffset;
// If this is a change, we need to also remove the deletion that comes
// before the addition
if (deleteOffset >= 0) {
// Remove the deletion
ops.remove(deleteOffset);
// And the deletion of exceptions
ops.remove(deleteOffset);
userLog(TAG, "Removing deletion ops from mOps");
ops.mCount = deleteOffset;
}
}
}
}
private void logEventColumns(ContentValues cv, String reason) {
if (Eas.USER_LOG) {
StringBuilder sb =
new StringBuilder("Event invalid, " + reason + ", skipping: Columns = ");
for (Entry<String, Object> entry: cv.valueSet()) {
sb.append(entry.getKey());
sb.append('/');
}
userLog(TAG, sb.toString());
}
}
/*package*/ boolean isValidEventValues(ContentValues cv) {
boolean isException = cv.containsKey(Events.ORIGINAL_INSTANCE_TIME);
// All events require DTSTART
if (!cv.containsKey(Events.DTSTART)) {
logEventColumns(cv, "DTSTART missing");
return false;
// If we're a top-level event, we must have _SYNC_DATA (uid)
} else if (!isException && !cv.containsKey(Events.SYNC_DATA2)) {
logEventColumns(cv, "_SYNC_DATA missing");
return false;
// We must also have DTEND or DURATION if we're not an exception
} else if (!isException && !cv.containsKey(Events.DTEND) &&
!cv.containsKey(Events.DURATION)) {
logEventColumns(cv, "DTEND/DURATION missing");
return false;
// Exceptions require DTEND
} else if (isException && !cv.containsKey(Events.DTEND)) {
logEventColumns(cv, "Exception missing DTEND");
return false;
// If this is a recurrence, we need a DURATION (in days if an all-day event)
} else if (cv.containsKey(Events.RRULE)) {
String duration = cv.getAsString(Events.DURATION);
if (duration == null) return false;
if (cv.containsKey(Events.ALL_DAY)) {
Integer ade = cv.getAsInteger(Events.ALL_DAY);
if (ade != null && ade != 0 && !duration.endsWith("D")) {
return false;
}
}
}
return true;
}
public String recurrenceParser() throws IOException {
// Turn this information into an RRULE
int type = -1;
int occurrences = -1;
int interval = -1;
int dow = -1;
int dom = -1;
int wom = -1;
int moy = -1;
String until = null;
while (nextTag(Tags.CALENDAR_RECURRENCE) != END) {
switch (tag) {
case Tags.CALENDAR_RECURRENCE_TYPE:
type = getValueInt();
break;
case Tags.CALENDAR_RECURRENCE_INTERVAL:
interval = getValueInt();
break;
case Tags.CALENDAR_RECURRENCE_OCCURRENCES:
occurrences = getValueInt();
break;
case Tags.CALENDAR_RECURRENCE_DAYOFWEEK:
dow = getValueInt();
break;
case Tags.CALENDAR_RECURRENCE_DAYOFMONTH:
dom = getValueInt();
break;
case Tags.CALENDAR_RECURRENCE_WEEKOFMONTH:
wom = getValueInt();
break;
case Tags.CALENDAR_RECURRENCE_MONTHOFYEAR:
moy = getValueInt();
break;
case Tags.CALENDAR_RECURRENCE_UNTIL:
until = getValue();
break;
default:
skipTag();
}
}
return CalendarUtilities.rruleFromRecurrence(type, occurrences, interval,
dow, dom, wom, moy, until);
}
private void exceptionParser(CalendarOperations ops, ContentValues parentCv,
ArrayList<ContentValues> attendeeValues, int reminderMins, int busyStatus,
long startTime, long endTime) throws IOException {
ContentValues cv = new ContentValues();
cv.put(Events.CALENDAR_ID, mCalendarId);
// It appears that these values have to be copied from the parent if they are to appear
// Note that they can be overridden below
cv.put(Events.ORGANIZER, parentCv.getAsString(Events.ORGANIZER));
cv.put(Events.TITLE, parentCv.getAsString(Events.TITLE));
cv.put(Events.DESCRIPTION, parentCv.getAsString(Events.DESCRIPTION));
cv.put(Events.ORIGINAL_ALL_DAY, parentCv.getAsInteger(Events.ALL_DAY));
cv.put(Events.EVENT_LOCATION, parentCv.getAsString(Events.EVENT_LOCATION));
cv.put(Events.ACCESS_LEVEL, parentCv.getAsString(Events.ACCESS_LEVEL));
cv.put(Events.EVENT_TIMEZONE, parentCv.getAsString(Events.EVENT_TIMEZONE));
// Exceptions should always have this set to zero, since EAS has no concept of
// separate attendee lists for exceptions; if we fail to do this, then the UI will
// allow the user to change attendee data, and this change would never get reflected
// on the server.
cv.put(Events.HAS_ATTENDEE_DATA, 0);
int allDayEvent = 0;
// This column is the key that links the exception to the serverId
cv.put(Events.ORIGINAL_SYNC_ID, parentCv.getAsString(Events._SYNC_ID));
String exceptionStartTime = "_noStartTime";
while (nextTag(Tags.SYNC_APPLICATION_DATA) != END) {
switch (tag) {
case Tags.CALENDAR_ATTACHMENTS:
attachmentsParser();
break;
case Tags.CALENDAR_EXCEPTION_START_TIME:
exceptionStartTime = getValue();
cv.put(Events.ORIGINAL_INSTANCE_TIME,
Utility.parseDateTimeToMillis(exceptionStartTime));
break;
case Tags.CALENDAR_EXCEPTION_IS_DELETED:
if (getValueInt() == 1) {
cv.put(Events.STATUS, Events.STATUS_CANCELED);
}
break;
case Tags.CALENDAR_ALL_DAY_EVENT:
allDayEvent = getValueInt();
cv.put(Events.ALL_DAY, allDayEvent);
break;
case Tags.BASE_BODY:
cv.put(Events.DESCRIPTION, bodyParser());
break;
case Tags.CALENDAR_BODY:
cv.put(Events.DESCRIPTION, getValue());
break;
case Tags.CALENDAR_START_TIME:
startTime = Utility.parseDateTimeToMillis(getValue());
break;
case Tags.CALENDAR_END_TIME:
endTime = Utility.parseDateTimeToMillis(getValue());
break;
case Tags.CALENDAR_LOCATION:
cv.put(Events.EVENT_LOCATION, getValue());
break;
case Tags.CALENDAR_RECURRENCE:
String rrule = recurrenceParser();
if (rrule != null) {
cv.put(Events.RRULE, rrule);
}
break;
case Tags.CALENDAR_SUBJECT:
cv.put(Events.TITLE, getValue());
break;
case Tags.CALENDAR_SENSITIVITY:
cv.put(Events.ACCESS_LEVEL, encodeVisibility(getValueInt()));
break;
case Tags.CALENDAR_BUSY_STATUS:
busyStatus = getValueInt();
// Don't set selfAttendeeStatus or CalendarProvider will create a duplicate
// attendee!
break;
// TODO How to handle these items that are linked to event id!
// case Tags.CALENDAR_DTSTAMP:
// ops.newExtendedProperty("dtstamp", getValue());
// break;
// case Tags.CALENDAR_REMINDER_MINS_BEFORE:
// ops.newReminder(getValueInt());
// break;
default:
skipTag();
}
}
// We need a _sync_id, but it can't be the parent's id, so we generate one
cv.put(Events._SYNC_ID, parentCv.getAsString(Events._SYNC_ID) + '_' +
exceptionStartTime);
// Enforce CalendarProvider required properties
setTimeRelatedValues(cv, startTime, endTime, allDayEvent);
// Don't insert an invalid exception event
if (!isValidEventValues(cv)) return;
// Add the exception insert
int exceptionStart = ops.mCount;
ops.newException(cv);
// Also add the attendees, because they need to be copied over from the parent event
boolean attendeesRedacted = false;
if (attendeeValues != null) {
for (ContentValues attValues: attendeeValues) {
// If this is the user, use his busy status for attendee status
String attendeeEmail = attValues.getAsString(Attendees.ATTENDEE_EMAIL);
// Note that the exception at which we surpass the redaction limit might have
// any number of attendees shown; since this is an edge case and a workaround,
// it seems to be an acceptable implementation
if (mEmailAddress.equalsIgnoreCase(attendeeEmail)) {
attValues.put(Attendees.ATTENDEE_STATUS,
CalendarUtilities.attendeeStatusFromBusyStatus(busyStatus));
ops.newAttendee(attValues, exceptionStart);
} else if (ops.size() < MAX_OPS_BEFORE_EXCEPTION_ATTENDEE_REDACTION) {
ops.newAttendee(attValues, exceptionStart);
} else {
attendeesRedacted = true;
}
}
}
// And add the parent's reminder value
if (reminderMins > 0) {
ops.newReminder(reminderMins, exceptionStart);
}
if (attendeesRedacted) {
mService.userLog("Attendees redacted in this exception");
}
}
private int encodeVisibility(int easVisibility) {
int visibility = 0;
switch(easVisibility) {
case 0:
visibility = Events.ACCESS_DEFAULT;
break;
case 1:
visibility = Events.ACCESS_PUBLIC;
break;
case 2:
visibility = Events.ACCESS_PRIVATE;
break;
case 3:
visibility = Events.ACCESS_CONFIDENTIAL;
break;
}
return visibility;
}
private void exceptionsParser(CalendarOperations ops, ContentValues cv,
ArrayList<ContentValues> attendeeValues, int reminderMins, int busyStatus,
long startTime, long endTime) throws IOException {
while (nextTag(Tags.CALENDAR_EXCEPTIONS) != END) {
switch (tag) {
case Tags.CALENDAR_EXCEPTION:
exceptionParser(ops, cv, attendeeValues, reminderMins, busyStatus,
startTime, endTime);
break;
default:
skipTag();
}
}
}
private String categoriesParser(CalendarOperations ops) throws IOException {
StringBuilder categories = new StringBuilder();
while (nextTag(Tags.CALENDAR_CATEGORIES) != END) {
switch (tag) {
case Tags.CALENDAR_CATEGORY:
// TODO Handle categories (there's no similar concept for gdata AFAIK)
// We need to save them and spit them back when we update the event
categories.append(getValue());
categories.append(CATEGORY_TOKENIZER_DELIMITER);
break;
default:
skipTag();
}
}
return categories.toString();
}
/**
* For now, we ignore (but still have to parse) event attachments; these are new in EAS 14
*/
private void attachmentsParser() throws IOException {
while (nextTag(Tags.CALENDAR_ATTACHMENTS) != END) {
switch (tag) {
case Tags.CALENDAR_ATTACHMENT:
skipParser(Tags.CALENDAR_ATTACHMENT);
break;
default:
skipTag();
}
}
}
private ArrayList<ContentValues> attendeesParser(CalendarOperations ops, long eventId)
throws IOException {
int attendeeCount = 0;
ArrayList<ContentValues> attendeeValues = new ArrayList<ContentValues>();
while (nextTag(Tags.CALENDAR_ATTENDEES) != END) {
switch (tag) {
case Tags.CALENDAR_ATTENDEE:
ContentValues cv = attendeeParser(ops, eventId);
// If we're going to redact these attendees anyway, let's avoid unnecessary
// memory pressure, and not keep them around
// We still need to parse them all, however
attendeeCount++;
// Allow one more than MAX_ATTENDEES, so that the check for "too many" will
// succeed in addEvent
if (attendeeCount <= (MAX_SYNCED_ATTENDEES+1)) {
attendeeValues.add(cv);
}
break;
default:
skipTag();
}
}
return attendeeValues;
}
private ContentValues attendeeParser(CalendarOperations ops, long eventId)
throws IOException {
ContentValues cv = new ContentValues();
while (nextTag(Tags.CALENDAR_ATTENDEE) != END) {
switch (tag) {
case Tags.CALENDAR_ATTENDEE_EMAIL:
cv.put(Attendees.ATTENDEE_EMAIL, getValue());
break;
case Tags.CALENDAR_ATTENDEE_NAME:
cv.put(Attendees.ATTENDEE_NAME, getValue());
break;
case Tags.CALENDAR_ATTENDEE_STATUS:
int status = getValueInt();
cv.put(Attendees.ATTENDEE_STATUS,
(status == 2) ? Attendees.ATTENDEE_STATUS_TENTATIVE :
(status == 3) ? Attendees.ATTENDEE_STATUS_ACCEPTED :
(status == 4) ? Attendees.ATTENDEE_STATUS_DECLINED :
(status == 5) ? Attendees.ATTENDEE_STATUS_INVITED :
Attendees.ATTENDEE_STATUS_NONE);
break;
case Tags.CALENDAR_ATTENDEE_TYPE:
int type = Attendees.TYPE_NONE;
// EAS types: 1 = req'd, 2 = opt, 3 = resource
switch (getValueInt()) {
case 1:
type = Attendees.TYPE_REQUIRED;
break;
case 2:
type = Attendees.TYPE_OPTIONAL;
break;
}
cv.put(Attendees.ATTENDEE_TYPE, type);
break;
default:
skipTag();
}
}
cv.put(Attendees.ATTENDEE_RELATIONSHIP, Attendees.RELATIONSHIP_ATTENDEE);
return cv;
}
private String bodyParser() throws IOException {
String body = null;
while (nextTag(Tags.BASE_BODY) != END) {
switch (tag) {
case Tags.BASE_DATA:
body = getValue();
break;
default:
skipTag();
}
}
// Handle null data without error
if (body == null) return "";
// Remove \r's from any body text
return body.replace("\r\n", "\n");
}
public void addParser(CalendarOperations ops) throws IOException {
String serverId = null;
while (nextTag(Tags.SYNC_ADD) != END) {
switch (tag) {
case Tags.SYNC_SERVER_ID: // same as
serverId = getValue();
break;
case Tags.SYNC_APPLICATION_DATA:
addEvent(ops, serverId, false);
break;
default:
skipTag();
}
}
}
private Cursor getServerIdCursor(String serverId) {
return mContentResolver.query(mAccountUri, ID_PROJECTION, SERVER_ID_AND_CALENDAR_ID,
new String[] {serverId, mCalendarIdString}, null);
}
private Cursor getClientIdCursor(String clientId) {
mBindArgument[0] = clientId;
return mContentResolver.query(mAccountUri, ID_PROJECTION, CLIENT_ID_SELECTION,
mBindArgument, null);
}
public void deleteParser(CalendarOperations ops) throws IOException {
while (nextTag(Tags.SYNC_DELETE) != END) {
switch (tag) {
case Tags.SYNC_SERVER_ID:
String serverId = getValue();
// Find the event with the given serverId
Cursor c = getServerIdCursor(serverId);
try {
if (c.moveToFirst()) {
userLog("Deleting ", serverId);
ops.delete(c.getLong(0), serverId);
}
} finally {
c.close();
}
break;
default:
skipTag();
}
}
}
/**
* A change is handled as a delete (including all exceptions) and an add
* This isn't as efficient as attempting to traverse the original and all of its exceptions,
* but changes happen infrequently and this code is both simpler and easier to maintain
* @param ops the array of pending ContactProviderOperations.
* @throws IOException
*/
public void changeParser(CalendarOperations ops) throws IOException {
String serverId = null;
while (nextTag(Tags.SYNC_CHANGE) != END) {
switch (tag) {
case Tags.SYNC_SERVER_ID:
serverId = getValue();
break;
case Tags.SYNC_APPLICATION_DATA:
userLog("Changing " + serverId);
addEvent(ops, serverId, true);
break;
default:
skipTag();
}
}
}
@Override
public void commandsParser() throws IOException {
while (nextTag(Tags.SYNC_COMMANDS) != END) {
if (tag == Tags.SYNC_ADD) {
addParser(mOps);
incrementChangeCount();
} else if (tag == Tags.SYNC_DELETE) {
deleteParser(mOps);
incrementChangeCount();
} else if (tag == Tags.SYNC_CHANGE) {
changeParser(mOps);
incrementChangeCount();
} else
skipTag();
}
}
@Override
public void commit() throws IOException {
userLog("Calendar SyncKey saved as: ", mMailbox.mSyncKey);
// Save the syncKey here, using the Helper provider by Calendar provider
mOps.add(SyncStateContract.Helpers.newSetOperation(
asSyncAdapter(SyncState.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE),
mAccountManagerAccount,
mMailbox.mSyncKey.getBytes()));
// We need to send cancellations now, because the Event won't exist after the commit
for (long eventId: mSendCancelIdList) {
EmailContent.Message msg;
try {
msg = CalendarUtilities.createMessageForEventId(mContext, eventId,
EmailContent.Message.FLAG_OUTGOING_MEETING_CANCEL, null,
mAccount);
} catch (RemoteException e) {
// Nothing to do here; the Event may no longer exist
continue;
}
if (msg != null) {
EasOutboxService.sendMessage(mContext, mAccount.mId, msg);
}
}
// Execute these all at once...
mOps.execute();
if (mOps.mResults != null) {
// Clear dirty and mark flags for updates sent to server
if (!mUploadedIdList.isEmpty()) {
ContentValues cv = new ContentValues();
cv.put(Events.DIRTY, 0);
cv.put(EVENT_SYNC_MARK, "0");
for (long eventId : mUploadedIdList) {
mContentResolver.update(
asSyncAdapter(
ContentUris.withAppendedId(Events.CONTENT_URI, eventId),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cv,
null, null);
}
}
// Delete events marked for deletion
if (!mDeletedIdList.isEmpty()) {
for (long eventId : mDeletedIdList) {
mContentResolver.delete(
asSyncAdapter(
ContentUris.withAppendedId(Events.CONTENT_URI, eventId),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null,
null);
}
}
// Send any queued up email (invitations replies, etc.)
for (Message msg: mOutgoingMailList) {
EasOutboxService.sendMessage(mContext, mAccount.mId, msg);
}
}
}
public void addResponsesParser() throws IOException {
String serverId = null;
String clientId = null;
int status = -1;
ContentValues cv = new ContentValues();
while (nextTag(Tags.SYNC_ADD) != END) {
switch (tag) {
case Tags.SYNC_SERVER_ID:
serverId = getValue();
break;
case Tags.SYNC_CLIENT_ID:
clientId = getValue();
break;
case Tags.SYNC_STATUS:
status = getValueInt();
if (status != 1) {
userLog("Attempt to add event failed with status: " + status);
}
break;
default:
skipTag();
}
}
if (clientId == null) return;
if (serverId == null) {
// TODO Reconsider how to handle this
serverId = "FAIL:" + status;
}
Cursor c = getClientIdCursor(clientId);
try {
if (c.moveToFirst()) {
cv.put(Events._SYNC_ID, serverId);
cv.put(Events.SYNC_DATA2, clientId);
long id = c.getLong(0);
// Write the serverId into the Event
mOps.add(ContentProviderOperation
.newUpdate(
asSyncAdapter(
ContentUris.withAppendedId(Events.CONTENT_URI, id),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE))
.withValues(cv).build());
userLog("New event " + clientId + " was given serverId: " + serverId);
}
} finally {
c.close();
}
}
public void changeResponsesParser() throws IOException {
String serverId = null;
String status = null;
while (nextTag(Tags.SYNC_CHANGE) != END) {
switch (tag) {
case Tags.SYNC_SERVER_ID:
serverId = getValue();
break;
case Tags.SYNC_STATUS:
status = getValue();
break;
default:
skipTag();
}
}
if (serverId != null && status != null) {
userLog("Changed event " + serverId + " failed with status: " + status);
}
}
@Override
public void responsesParser() throws IOException {
// Handle server responses here (for Add and Change)
while (nextTag(Tags.SYNC_RESPONSES) != END) {
if (tag == Tags.SYNC_ADD) {
addResponsesParser();
} else if (tag == Tags.SYNC_CHANGE) {
changeResponsesParser();
} else
skipTag();
}
}
}
protected class CalendarOperations extends ArrayList<ContentProviderOperation> {
private static final long serialVersionUID = 1L;
public int mCount = 0;
private ContentProviderResult[] mResults = null;
private int mEventStart = 0;
@Override
public boolean add(ContentProviderOperation op) {
super.add(op);
mCount++;
return true;
}
public int newEvent(ContentProviderOperation op) {
mEventStart = mCount;
add(op);
return mEventStart;
}
public int newDelete(long id, String serverId) {
int offset = mCount;
delete(id, serverId);
return offset;
}
public void newAttendee(ContentValues cv) {
newAttendee(cv, mEventStart);
}
public void newAttendee(ContentValues cv, int eventStart) {
add(ContentProviderOperation
.newInsert(asSyncAdapter(Attendees.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE)).withValues(cv)
.withValueBackReference(Attendees.EVENT_ID, eventStart).build());
}
public void updatedAttendee(ContentValues cv, long id) {
cv.put(Attendees.EVENT_ID, id);
add(ContentProviderOperation.newInsert(asSyncAdapter(Attendees.CONTENT_URI,
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE)).withValues(cv).build());
}
public void newException(ContentValues cv) {
add(ContentProviderOperation.newInsert(
asSyncAdapter(Events.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE)).withValues(cv).build());
}
public void newExtendedProperty(String name, String value) {
add(ContentProviderOperation
.newInsert(asSyncAdapter(ExtendedProperties.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE))
.withValue(ExtendedProperties.NAME, name)
.withValue(ExtendedProperties.VALUE, value)
.withValueBackReference(ExtendedProperties.EVENT_ID, mEventStart).build());
}
public void updatedExtendedProperty(String name, String value, long id) {
// Find an existing ExtendedProperties row for this event and property name
Cursor c = mService.mContentResolver.query(ExtendedProperties.CONTENT_URI,
EXTENDED_PROPERTY_PROJECTION, EVENT_ID_AND_NAME,
new String[] {Long.toString(id), name}, null);
long extendedPropertyId = -1;
// If there is one, capture its _id
if (c != null) {
try {
if (c.moveToFirst()) {
extendedPropertyId = c.getLong(EXTENDED_PROPERTY_ID);
}
} finally {
c.close();
}
}
// Either do an update or an insert, depending on whether one
// already exists
if (extendedPropertyId >= 0) {
add(ContentProviderOperation
.newUpdate(
ContentUris.withAppendedId(
asSyncAdapter(ExtendedProperties.CONTENT_URI,
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE),
extendedPropertyId))
.withValue(ExtendedProperties.VALUE, value).build());
} else {
newExtendedProperty(name, value);
}
}
public void newReminder(int mins, int eventStart) {
add(ContentProviderOperation
.newInsert(asSyncAdapter(Reminders.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE))
.withValue(Reminders.MINUTES, mins)
.withValue(Reminders.METHOD, Reminders.METHOD_ALERT)
.withValueBackReference(ExtendedProperties.EVENT_ID, eventStart).build());
}
public void newReminder(int mins) {
newReminder(mins, mEventStart);
}
public void delete(long id, String syncId) {
add(ContentProviderOperation.newDelete(
asSyncAdapter(ContentUris.withAppendedId(Events.CONTENT_URI, id),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE)).build());
// Delete the exceptions for this Event (CalendarProvider doesn't do
// this)
add(ContentProviderOperation
.newDelete(asSyncAdapter(Events.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE))
.withSelection(Events.ORIGINAL_SYNC_ID + "=?", new String[] {syncId}).build());
}
public void execute() {
synchronized (mService.getSynchronizer()) {
if (!mService.isStopped()) {
try {
if (!isEmpty()) {
mService.userLog("Executing ", size(), " CPO's");
mResults = mContext.getContentResolver().applyBatch(
CalendarContract.AUTHORITY, this);
}
} catch (RemoteException e) {
// There is nothing sensible to be done here
Log.e(TAG, "problem inserting event during server update", e);
} catch (OperationApplicationException e) {
// There is nothing sensible to be done here
Log.e(TAG, "problem inserting event during server update", e);
}
}
}
}
}
private String decodeVisibility(int visibility) {
int easVisibility = 0;
switch(visibility) {
case Events.ACCESS_DEFAULT:
easVisibility = 0;
break;
case Events.ACCESS_PUBLIC:
easVisibility = 1;
break;
case Events.ACCESS_PRIVATE:
easVisibility = 2;
break;
case Events.ACCESS_CONFIDENTIAL:
easVisibility = 3;
break;
}
return Integer.toString(easVisibility);
}
private int getInt(ContentValues cv, String column) {
Integer i = cv.getAsInteger(column);
if (i == null) return 0;
return i;
}
private void sendEvent(Entity entity, String clientId, Serializer s)
throws IOException {
// Serialize for EAS here
// Set uid with the client id we created
// 1) Serialize the top-level event
// 2) Serialize attendees and reminders from subvalues
// 3) Look for exceptions and serialize with the top-level event
ContentValues entityValues = entity.getEntityValues();
final boolean isException = (clientId == null);
boolean hasAttendees = false;
final boolean isChange = entityValues.containsKey(Events._SYNC_ID);
final Double version = mService.mProtocolVersionDouble;
final boolean allDay =
CalendarUtilities.getIntegerValueAsBoolean(entityValues, Events.ALL_DAY);
// NOTE: Exchange 2003 (EAS 2.5) seems to require the "exception deleted" and "exception
// start time" data before other data in exceptions. Failure to do so results in a
// status 6 error during sync
if (isException) {
// Send exception deleted flag if necessary
Integer deleted = entityValues.getAsInteger(Events.DELETED);
boolean isDeleted = deleted != null && deleted == 1;
Integer eventStatus = entityValues.getAsInteger(Events.STATUS);
boolean isCanceled = eventStatus != null && eventStatus.equals(Events.STATUS_CANCELED);
if (isDeleted || isCanceled) {
s.data(Tags.CALENDAR_EXCEPTION_IS_DELETED, "1");
// If we're deleted, the UI will continue to show this exception until we mark
// it canceled, so we'll do that here...
if (isDeleted && !isCanceled) {
final long eventId = entityValues.getAsLong(Events._ID);
ContentValues cv = new ContentValues();
cv.put(Events.STATUS, Events.STATUS_CANCELED);
mService.mContentResolver.update(
asSyncAdapter(ContentUris.withAppendedId(Events.CONTENT_URI, eventId),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cv, null,
null);
}
} else {
s.data(Tags.CALENDAR_EXCEPTION_IS_DELETED, "0");
}
// TODO Add reminders to exceptions (allow them to be specified!)
Long originalTime = entityValues.getAsLong(Events.ORIGINAL_INSTANCE_TIME);
if (originalTime != null) {
final boolean originalAllDay =
CalendarUtilities.getIntegerValueAsBoolean(entityValues,
Events.ORIGINAL_ALL_DAY);
if (originalAllDay) {
// For all day events, we need our local all-day time
originalTime =
CalendarUtilities.getLocalAllDayCalendarTime(originalTime, mLocalTimeZone);
}
s.data(Tags.CALENDAR_EXCEPTION_START_TIME,
CalendarUtilities.millisToEasDateTime(originalTime));
} else {
// Illegal; what should we do?
}
}
// Get the event's time zone
String timeZoneName =
entityValues.getAsString(allDay ? EVENT_SAVED_TIMEZONE_COLUMN : Events.EVENT_TIMEZONE);
if (timeZoneName == null) {
timeZoneName = mLocalTimeZone.getID();
}
TimeZone eventTimeZone = TimeZone.getTimeZone(timeZoneName);
if (!isException) {
// A time zone is required in all EAS events; we'll use the default if none is set
// Exchange 2003 seems to require this first... :-)
String timeZone = CalendarUtilities.timeZoneToTziString(eventTimeZone);
s.data(Tags.CALENDAR_TIME_ZONE, timeZone);
}
s.data(Tags.CALENDAR_ALL_DAY_EVENT, allDay ? "1" : "0");
// DTSTART is always supplied
long startTime = entityValues.getAsLong(Events.DTSTART);
// Determine endTime; it's either provided as DTEND or we calculate using DURATION
// If no DURATION is provided, we default to one hour
long endTime;
if (entityValues.containsKey(Events.DTEND)) {
endTime = entityValues.getAsLong(Events.DTEND);
} else {
long durationMillis = HOURS;
if (entityValues.containsKey(Events.DURATION)) {
Duration duration = new Duration();
try {
duration.parse(entityValues.getAsString(Events.DURATION));
durationMillis = duration.getMillis();
} catch (ParseException e) {
// Can't do much about this; use the default (1 hour)
}
}
endTime = startTime + durationMillis;
}
if (allDay) {
TimeZone tz = mLocalTimeZone;
startTime = CalendarUtilities.getLocalAllDayCalendarTime(startTime, tz);
endTime = CalendarUtilities.getLocalAllDayCalendarTime(endTime, tz);
}
s.data(Tags.CALENDAR_START_TIME, CalendarUtilities.millisToEasDateTime(startTime));
s.data(Tags.CALENDAR_END_TIME, CalendarUtilities.millisToEasDateTime(endTime));
s.data(Tags.CALENDAR_DTSTAMP,
CalendarUtilities.millisToEasDateTime(System.currentTimeMillis()));
String loc = entityValues.getAsString(Events.EVENT_LOCATION);
if (!TextUtils.isEmpty(loc)) {
if (version < Eas.SUPPORTED_PROTOCOL_EX2007_DOUBLE) {
// EAS 2.5 doesn't like bare line feeds
loc = Utility.replaceBareLfWithCrlf(loc);
}
s.data(Tags.CALENDAR_LOCATION, loc);
}
s.writeStringValue(entityValues, Events.TITLE, Tags.CALENDAR_SUBJECT);
if (version >= Eas.SUPPORTED_PROTOCOL_EX2007_DOUBLE) {
s.start(Tags.BASE_BODY);
s.data(Tags.BASE_TYPE, "1");
s.writeStringValue(entityValues, Events.DESCRIPTION, Tags.BASE_DATA);
s.end();
} else {
// EAS 2.5 doesn't like bare line feeds
s.writeStringValue(entityValues, Events.DESCRIPTION, Tags.CALENDAR_BODY);
}
if (!isException) {
// For Exchange 2003, only upsync if the event is new
if ((version >= Eas.SUPPORTED_PROTOCOL_EX2007_DOUBLE) || !isChange) {
s.writeStringValue(entityValues, Events.ORGANIZER, Tags.CALENDAR_ORGANIZER_EMAIL);
}
String rrule = entityValues.getAsString(Events.RRULE);
if (rrule != null) {
CalendarUtilities.recurrenceFromRrule(rrule, startTime, s);
}
// Handle associated data EXCEPT for attendees, which have to be grouped
ArrayList<NamedContentValues> subValues = entity.getSubValues();
// The earliest of the reminders for this Event; we can only send one reminder...
int earliestReminder = -1;
for (NamedContentValues ncv: subValues) {
Uri ncvUri = ncv.uri;
ContentValues ncvValues = ncv.values;
if (ncvUri.equals(ExtendedProperties.CONTENT_URI)) {
String propertyName =
ncvValues.getAsString(ExtendedProperties.NAME);
String propertyValue =
ncvValues.getAsString(ExtendedProperties.VALUE);
if (TextUtils.isEmpty(propertyValue)) {
continue;
}
if (propertyName.equals(EXTENDED_PROPERTY_CATEGORIES)) {
// Send all the categories back to the server
// We've saved them as a String of delimited tokens
StringTokenizer st =
new StringTokenizer(propertyValue, CATEGORY_TOKENIZER_DELIMITER);
if (st.countTokens() > 0) {
s.start(Tags.CALENDAR_CATEGORIES);
while (st.hasMoreTokens()) {
String category = st.nextToken();
s.data(Tags.CALENDAR_CATEGORY, category);
}
s.end();
}
}
} else if (ncvUri.equals(Reminders.CONTENT_URI)) {
Integer mins = ncvValues.getAsInteger(Reminders.MINUTES);
if (mins != null) {
// -1 means "default", which for Exchange, is 30
if (mins < 0) {
mins = 30;
}
// Save this away if it's the earliest reminder (greatest minutes)
if (mins > earliestReminder) {
earliestReminder = mins;
}
}
}
}
// If we have a reminder, send it to the server
if (earliestReminder >= 0) {
s.data(Tags.CALENDAR_REMINDER_MINS_BEFORE, Integer.toString(earliestReminder));
}
// We've got to send a UID, unless this is an exception. If the event is new, we've
// generated one; if not, we should have gotten one from extended properties.
if (clientId != null) {
s.data(Tags.CALENDAR_UID, clientId);
}
// Handle attendee data here; keep track of organizer and stream it afterward
String organizerName = null;
String organizerEmail = null;
for (NamedContentValues ncv: subValues) {
Uri ncvUri = ncv.uri;
ContentValues ncvValues = ncv.values;
if (ncvUri.equals(Attendees.CONTENT_URI)) {
Integer relationship = ncvValues.getAsInteger(Attendees.ATTENDEE_RELATIONSHIP);
// If there's no relationship, we can't create this for EAS
// Similarly, we need an attendee email for each invitee
if (relationship != null && ncvValues.containsKey(Attendees.ATTENDEE_EMAIL)) {
// Organizer isn't among attendees in EAS
if (relationship == Attendees.RELATIONSHIP_ORGANIZER) {
organizerName = ncvValues.getAsString(Attendees.ATTENDEE_NAME);
organizerEmail = ncvValues.getAsString(Attendees.ATTENDEE_EMAIL);
continue;
}
if (!hasAttendees) {
s.start(Tags.CALENDAR_ATTENDEES);
hasAttendees = true;
}
s.start(Tags.CALENDAR_ATTENDEE);
String attendeeEmail = ncvValues.getAsString(Attendees.ATTENDEE_EMAIL);
String attendeeName = ncvValues.getAsString(Attendees.ATTENDEE_NAME);
if (attendeeName == null) {
attendeeName = attendeeEmail;
}
s.data(Tags.CALENDAR_ATTENDEE_NAME, attendeeName);
s.data(Tags.CALENDAR_ATTENDEE_EMAIL, attendeeEmail);
if (version >= Eas.SUPPORTED_PROTOCOL_EX2007_DOUBLE) {
s.data(Tags.CALENDAR_ATTENDEE_TYPE, "1"); // Required
}
s.end(); // Attendee
}
}
}
if (hasAttendees) {
s.end(); // Attendees
}
// Get busy status from Attendees table
long eventId = entityValues.getAsLong(Events._ID);
int busyStatus = CalendarUtilities.BUSY_STATUS_TENTATIVE;
Cursor c = mService.mContentResolver.query(
asSyncAdapter(Attendees.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE),
ATTENDEE_STATUS_PROJECTION, EVENT_AND_EMAIL,
new String[] {Long.toString(eventId), mEmailAddress}, null);
if (c != null) {
try {
if (c.moveToFirst()) {
busyStatus = CalendarUtilities.busyStatusFromAttendeeStatus(
c.getInt(ATTENDEE_STATUS_COLUMN_STATUS));
}
} finally {
c.close();
}
}
s.data(Tags.CALENDAR_BUSY_STATUS, Integer.toString(busyStatus));
// Meeting status, 0 = appointment, 1 = meeting, 3 = attendee
if (mEmailAddress.equalsIgnoreCase(organizerEmail)) {
s.data(Tags.CALENDAR_MEETING_STATUS, hasAttendees ? "1" : "0");
} else {
s.data(Tags.CALENDAR_MEETING_STATUS, "3");
}
// For Exchange 2003, only upsync if the event is new
if (((version >= Eas.SUPPORTED_PROTOCOL_EX2007_DOUBLE) || !isChange) &&
organizerName != null) {
s.data(Tags.CALENDAR_ORGANIZER_NAME, organizerName);
}
// NOTE: Sensitivity must NOT be sent to the server for exceptions in Exchange 2003
// The result will be a status 6 failure during sync
Integer visibility = entityValues.getAsInteger(Events.ACCESS_LEVEL);
if (visibility != null) {
s.data(Tags.CALENDAR_SENSITIVITY, decodeVisibility(visibility));
} else {
// Default to private if not set
s.data(Tags.CALENDAR_SENSITIVITY, "1");
}
}
}
/**
* Convenience method for sending an email to the organizer declining the meeting
* @param entity
* @param clientId
*/
private void sendDeclinedEmail(Entity entity, String clientId) {
Message msg =
CalendarUtilities.createMessageForEntity(mContext, entity,
Message.FLAG_OUTGOING_MEETING_DECLINE, clientId, mAccount);
if (msg != null) {
userLog("Queueing declined response to " + msg.mTo);
mOutgoingMailList.add(msg);
}
}
@Override
public boolean sendLocalChanges(Serializer s) throws IOException {
ContentResolver cr = mService.mContentResolver;
if (getSyncKey().equals("0")) {
return false;
}
try {
// We've got to handle exceptions as part of the parent when changes occur, so we need
// to find new/changed exceptions and mark the parent dirty
ArrayList<Long> orphanedExceptions = new ArrayList<Long>();
Cursor c = cr.query(Events.CONTENT_URI, ORIGINAL_EVENT_PROJECTION,
DIRTY_EXCEPTION_IN_CALENDAR, mCalendarIdArgument, null);
try {
ContentValues cv = new ContentValues();
// We use _sync_mark here to distinguish dirty parents from parents with dirty
// exceptions
cv.put(EVENT_SYNC_MARK, "1");
while (c.moveToNext()) {
// Mark the parents of dirty exceptions
long parentId = c.getLong(0);
int cnt = cr.update(
asSyncAdapter(Events.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cv,
EVENT_ID_AND_CALENDAR_ID, new String[] {
Long.toString(parentId), mCalendarIdString
});
// Keep track of any orphaned exceptions
if (cnt == 0) {
orphanedExceptions.add(c.getLong(1));
}
}
} finally {
c.close();
}
// Delete any orphaned exceptions
for (long orphan : orphanedExceptions) {
userLog(TAG, "Deleted orphaned exception: " + orphan);
cr.delete(
asSyncAdapter(ContentUris.withAppendedId(Events.CONTENT_URI, orphan),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null, null);
}
orphanedExceptions.clear();
// Now we can go through dirty/marked top-level events and send them
// back to the server
EntityIterator eventIterator = EventsEntity.newEntityIterator(cr.query(
asSyncAdapter(Events.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null,
DIRTY_OR_MARKED_TOP_LEVEL_IN_CALENDAR, mCalendarIdArgument, null), cr);
ContentValues cidValues = new ContentValues();
try {
boolean first = true;
while (eventIterator.hasNext()) {
Entity entity = eventIterator.next();
// For each of these entities, create the change commands
ContentValues entityValues = entity.getEntityValues();
String serverId = entityValues.getAsString(Events._SYNC_ID);
// We first need to check whether we can upsync this event; our test for this
// is currently the value of EXTENDED_PROPERTY_ATTENDEES_REDACTED
// If this is set to "1", we can't upsync the event
for (NamedContentValues ncv: entity.getSubValues()) {
if (ncv.uri.equals(ExtendedProperties.CONTENT_URI)) {
ContentValues ncvValues = ncv.values;
if (ncvValues.getAsString(ExtendedProperties.NAME).equals(
EXTENDED_PROPERTY_UPSYNC_PROHIBITED)) {
if ("1".equals(ncvValues.getAsString(ExtendedProperties.VALUE))) {
// Make sure we mark this to clear the dirty flag
mUploadedIdList.add(entityValues.getAsLong(Events._ID));
continue;
}
}
}
}
// Find our uid in the entity; otherwise create one
String clientId = entityValues.getAsString(Events.SYNC_DATA2);
if (clientId == null) {
clientId = UUID.randomUUID().toString();
}
// EAS 2.5 needs: BusyStatus DtStamp EndTime Sensitivity StartTime TimeZone UID
// We can generate all but what we're testing for below
String organizerEmail = entityValues.getAsString(Events.ORGANIZER);
boolean selfOrganizer = organizerEmail.equalsIgnoreCase(mEmailAddress);
if (!entityValues.containsKey(Events.DTSTART)
|| (!entityValues.containsKey(Events.DURATION) &&
!entityValues.containsKey(Events.DTEND))
|| organizerEmail == null) {
continue;
}
if (first) {
s.start(Tags.SYNC_COMMANDS);
userLog("Sending Calendar changes to the server");
first = false;
}
long eventId = entityValues.getAsLong(Events._ID);
if (serverId == null) {
// This is a new event; create a clientId
userLog("Creating new event with clientId: ", clientId);
s.start(Tags.SYNC_ADD).data(Tags.SYNC_CLIENT_ID, clientId);
// And save it in the Event as the local id
cidValues.put(Events.SYNC_DATA2, clientId);
cidValues.put(EVENT_SYNC_VERSION, "0");
cr.update(
asSyncAdapter(
ContentUris.withAppendedId(Events.CONTENT_URI, eventId),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE),
cidValues, null, null);
} else {
if (entityValues.getAsInteger(Events.DELETED) == 1) {
userLog("Deleting event with serverId: ", serverId);
s.start(Tags.SYNC_DELETE).data(Tags.SYNC_SERVER_ID, serverId).end();
mDeletedIdList.add(eventId);
if (selfOrganizer) {
mSendCancelIdList.add(eventId);
} else {
sendDeclinedEmail(entity, clientId);
}
continue;
}
userLog("Upsync change to event with serverId: " + serverId);
// Get the current version
String version = entityValues.getAsString(EVENT_SYNC_VERSION);
// This should never be null, but catch this error anyway
// Version should be "0" when we create the event, so use that
if (version == null) {
version = "0";
} else {
// Increment and save
try {
version = Integer.toString((Integer.parseInt(version) + 1));
} catch (Exception e) {
// Handle the case in which someone writes a non-integer here;
// shouldn't happen, but we don't want to kill the sync for his
version = "0";
}
}
cidValues.put(EVENT_SYNC_VERSION, version);
// Also save in entityValues so that we send it this time around
entityValues.put(EVENT_SYNC_VERSION, version);
cr.update(
asSyncAdapter(
ContentUris.withAppendedId(Events.CONTENT_URI, eventId),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE),
cidValues, null, null);
s.start(Tags.SYNC_CHANGE).data(Tags.SYNC_SERVER_ID, serverId);
}
s.start(Tags.SYNC_APPLICATION_DATA);
sendEvent(entity, clientId, s);
// Now, the hard part; find exceptions for this event
if (serverId != null) {
EntityIterator exIterator = EventsEntity.newEntityIterator(cr.query(
asSyncAdapter(Events.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null,
ORIGINAL_EVENT_AND_CALENDAR, new String[] {
serverId, mCalendarIdString
}, null), cr);
boolean exFirst = true;
while (exIterator.hasNext()) {
Entity exEntity = exIterator.next();
if (exFirst) {
s.start(Tags.CALENDAR_EXCEPTIONS);
exFirst = false;
}
s.start(Tags.CALENDAR_EXCEPTION);
sendEvent(exEntity, null, s);
ContentValues exValues = exEntity.getEntityValues();
if (getInt(exValues, Events.DIRTY) == 1) {
// This is a new/updated exception, so we've got to notify our
// attendees about it
long exEventId = exValues.getAsLong(Events._ID);
int flag;
// Copy subvalues into the exception; otherwise, we won't see the
// attendees when preparing the message
for (NamedContentValues ncv: entity.getSubValues()) {
exEntity.addSubValue(ncv.uri, ncv.values);
}
if ((getInt(exValues, Events.DELETED) == 1) ||
(getInt(exValues, Events.STATUS) ==
Events.STATUS_CANCELED)) {
flag = Message.FLAG_OUTGOING_MEETING_CANCEL;
if (!selfOrganizer) {
// Send a cancellation notice to the organizer
// Since CalendarProvider2 sets the organizer of exceptions
// to the user, we have to reset it first to the original
// organizer
exValues.put(Events.ORGANIZER,
entityValues.getAsString(Events.ORGANIZER));
sendDeclinedEmail(exEntity, clientId);
}
} else {
flag = Message.FLAG_OUTGOING_MEETING_INVITE;
}
// Add the eventId of the exception to the uploaded id list, so that
// the dirty/mark bits are cleared
mUploadedIdList.add(exEventId);
// Copy version so the ics attachment shows the proper sequence #
exValues.put(EVENT_SYNC_VERSION,
entityValues.getAsString(EVENT_SYNC_VERSION));
// Copy location so that it's included in the outgoing email
if (entityValues.containsKey(Events.EVENT_LOCATION)) {
exValues.put(Events.EVENT_LOCATION,
entityValues.getAsString(Events.EVENT_LOCATION));
}
if (selfOrganizer) {
Message msg =
CalendarUtilities.createMessageForEntity(mContext,
exEntity, flag, clientId, mAccount);
if (msg != null) {
userLog("Queueing exception update to " + msg.mTo);
mOutgoingMailList.add(msg);
}
}
}
s.end(); // EXCEPTION
}
if (!exFirst) {
s.end(); // EXCEPTIONS
}
}
s.end().end(); // ApplicationData & Change
mUploadedIdList.add(eventId);
// Go through the extended properties of this Event and pull out our tokenized
// attendees list and the user attendee status; we will need them later
String attendeeString = null;
long attendeeStringId = -1;
String userAttendeeStatus = null;
long userAttendeeStatusId = -1;
for (NamedContentValues ncv: entity.getSubValues()) {
if (ncv.uri.equals(ExtendedProperties.CONTENT_URI)) {
ContentValues ncvValues = ncv.values;
String propertyName =
ncvValues.getAsString(ExtendedProperties.NAME);
if (propertyName.equals(EXTENDED_PROPERTY_ATTENDEES)) {
attendeeString =
ncvValues.getAsString(ExtendedProperties.VALUE);
attendeeStringId =
ncvValues.getAsLong(ExtendedProperties._ID);
} else if (propertyName.equals(
EXTENDED_PROPERTY_USER_ATTENDEE_STATUS)) {
userAttendeeStatus =
ncvValues.getAsString(ExtendedProperties.VALUE);
userAttendeeStatusId =
ncvValues.getAsLong(ExtendedProperties._ID);
}
}
}
// Send the meeting invite if there are attendees and we're the organizer AND
// if the Event itself is dirty (we might be syncing only because an exception
// is dirty, in which case we DON'T send email about the Event)
if (selfOrganizer &&
(getInt(entityValues, Events.DIRTY) == 1)) {
EmailContent.Message msg =
CalendarUtilities.createMessageForEventId(mContext, eventId,
EmailContent.Message.FLAG_OUTGOING_MEETING_INVITE, clientId,
mAccount);
if (msg != null) {
userLog("Queueing invitation to ", msg.mTo);
mOutgoingMailList.add(msg);
}
// Make a list out of our tokenized attendees, if we have any
ArrayList<String> originalAttendeeList = new ArrayList<String>();
if (attendeeString != null) {
StringTokenizer st =
new StringTokenizer(attendeeString, ATTENDEE_TOKENIZER_DELIMITER);
while (st.hasMoreTokens()) {
originalAttendeeList.add(st.nextToken());
}
}
StringBuilder newTokenizedAttendees = new StringBuilder();
// See if any attendees have been dropped and while we're at it, build
// an updated String with tokenized attendee addresses
for (NamedContentValues ncv: entity.getSubValues()) {
if (ncv.uri.equals(Attendees.CONTENT_URI)) {
String attendeeEmail =
ncv.values.getAsString(Attendees.ATTENDEE_EMAIL);
// Remove all found attendees
originalAttendeeList.remove(attendeeEmail);
newTokenizedAttendees.append(attendeeEmail);
newTokenizedAttendees.append(ATTENDEE_TOKENIZER_DELIMITER);
}
}
// Update extended properties with the new attendee list, if we have one
// Otherwise, create one (this would be the case for Events created on
// device or "legacy" events (before this code was added)
ContentValues cv = new ContentValues();
cv.put(ExtendedProperties.VALUE, newTokenizedAttendees.toString());
if (attendeeString != null) {
cr.update(asSyncAdapter(ContentUris.withAppendedId(
ExtendedProperties.CONTENT_URI, attendeeStringId),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE),
cv, null, null);
} else {
// If there wasn't an "attendees" property, insert one
cv.put(ExtendedProperties.NAME, EXTENDED_PROPERTY_ATTENDEES);
cv.put(ExtendedProperties.EVENT_ID, eventId);
cr.insert(asSyncAdapter(ExtendedProperties.CONTENT_URI,
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cv);
}
// Whoever is left has been removed from the attendee list; send them
// a cancellation
for (String removedAttendee: originalAttendeeList) {
// Send a cancellation message to each of them
msg = CalendarUtilities.createMessageForEventId(mContext, eventId,
Message.FLAG_OUTGOING_MEETING_CANCEL, clientId, mAccount,
removedAttendee);
if (msg != null) {
// Just send it to the removed attendee
userLog("Queueing cancellation to removed attendee " + msg.mTo);
mOutgoingMailList.add(msg);
}
}
} else if (!selfOrganizer) {
// If we're not the organizer, see if we've changed our attendee status
// Our last synced attendee status is in ExtendedProperties, and we've
// retrieved it above as userAttendeeStatus
int currentStatus = entityValues.getAsInteger(Events.SELF_ATTENDEE_STATUS);
int syncStatus = Attendees.ATTENDEE_STATUS_NONE;
if (userAttendeeStatus != null) {
try {
syncStatus = Integer.parseInt(userAttendeeStatus);
} catch (NumberFormatException e) {
// Just in case somebody else mucked with this and it's not Integer
}
}
if ((currentStatus != syncStatus) &&
(currentStatus != Attendees.ATTENDEE_STATUS_NONE)) {
// If so, send a meeting reply
int messageFlag = 0;
switch (currentStatus) {
case Attendees.ATTENDEE_STATUS_ACCEPTED:
messageFlag = Message.FLAG_OUTGOING_MEETING_ACCEPT;
break;
case Attendees.ATTENDEE_STATUS_DECLINED:
messageFlag = Message.FLAG_OUTGOING_MEETING_DECLINE;
break;
case Attendees.ATTENDEE_STATUS_TENTATIVE:
messageFlag = Message.FLAG_OUTGOING_MEETING_TENTATIVE;
break;
}
// Make sure we have a valid status (messageFlag should never be zero)
if (messageFlag != 0 && userAttendeeStatusId >= 0) {
// Save away the new status
cidValues.clear();
cidValues.put(ExtendedProperties.VALUE,
Integer.toString(currentStatus));
- cr.update(ContentUris.withAppendedId(ExtendedProperties.CONTENT_URI,
- userAttendeeStatusId), cidValues, null, null);
+ cr.update(asSyncAdapter(ContentUris.withAppendedId(
+ ExtendedProperties.CONTENT_URI, userAttendeeStatusId),
+ mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE),
+ cidValues, null, null);
// Send mail to the organizer advising of the new status
EmailContent.Message msg =
CalendarUtilities.createMessageForEventId(mContext, eventId,
messageFlag, clientId, mAccount);
if (msg != null) {
userLog("Queueing invitation reply to " + msg.mTo);
mOutgoingMailList.add(msg);
}
}
}
}
}
if (!first) {
s.end(); // Commands
}
} finally {
eventIterator.close();
}
} catch (RemoteException e) {
Log.e(TAG, "Could not read dirty events.");
}
return false;
}
}
| true | true | public boolean sendLocalChanges(Serializer s) throws IOException {
ContentResolver cr = mService.mContentResolver;
if (getSyncKey().equals("0")) {
return false;
}
try {
// We've got to handle exceptions as part of the parent when changes occur, so we need
// to find new/changed exceptions and mark the parent dirty
ArrayList<Long> orphanedExceptions = new ArrayList<Long>();
Cursor c = cr.query(Events.CONTENT_URI, ORIGINAL_EVENT_PROJECTION,
DIRTY_EXCEPTION_IN_CALENDAR, mCalendarIdArgument, null);
try {
ContentValues cv = new ContentValues();
// We use _sync_mark here to distinguish dirty parents from parents with dirty
// exceptions
cv.put(EVENT_SYNC_MARK, "1");
while (c.moveToNext()) {
// Mark the parents of dirty exceptions
long parentId = c.getLong(0);
int cnt = cr.update(
asSyncAdapter(Events.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cv,
EVENT_ID_AND_CALENDAR_ID, new String[] {
Long.toString(parentId), mCalendarIdString
});
// Keep track of any orphaned exceptions
if (cnt == 0) {
orphanedExceptions.add(c.getLong(1));
}
}
} finally {
c.close();
}
// Delete any orphaned exceptions
for (long orphan : orphanedExceptions) {
userLog(TAG, "Deleted orphaned exception: " + orphan);
cr.delete(
asSyncAdapter(ContentUris.withAppendedId(Events.CONTENT_URI, orphan),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null, null);
}
orphanedExceptions.clear();
// Now we can go through dirty/marked top-level events and send them
// back to the server
EntityIterator eventIterator = EventsEntity.newEntityIterator(cr.query(
asSyncAdapter(Events.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null,
DIRTY_OR_MARKED_TOP_LEVEL_IN_CALENDAR, mCalendarIdArgument, null), cr);
ContentValues cidValues = new ContentValues();
try {
boolean first = true;
while (eventIterator.hasNext()) {
Entity entity = eventIterator.next();
// For each of these entities, create the change commands
ContentValues entityValues = entity.getEntityValues();
String serverId = entityValues.getAsString(Events._SYNC_ID);
// We first need to check whether we can upsync this event; our test for this
// is currently the value of EXTENDED_PROPERTY_ATTENDEES_REDACTED
// If this is set to "1", we can't upsync the event
for (NamedContentValues ncv: entity.getSubValues()) {
if (ncv.uri.equals(ExtendedProperties.CONTENT_URI)) {
ContentValues ncvValues = ncv.values;
if (ncvValues.getAsString(ExtendedProperties.NAME).equals(
EXTENDED_PROPERTY_UPSYNC_PROHIBITED)) {
if ("1".equals(ncvValues.getAsString(ExtendedProperties.VALUE))) {
// Make sure we mark this to clear the dirty flag
mUploadedIdList.add(entityValues.getAsLong(Events._ID));
continue;
}
}
}
}
// Find our uid in the entity; otherwise create one
String clientId = entityValues.getAsString(Events.SYNC_DATA2);
if (clientId == null) {
clientId = UUID.randomUUID().toString();
}
// EAS 2.5 needs: BusyStatus DtStamp EndTime Sensitivity StartTime TimeZone UID
// We can generate all but what we're testing for below
String organizerEmail = entityValues.getAsString(Events.ORGANIZER);
boolean selfOrganizer = organizerEmail.equalsIgnoreCase(mEmailAddress);
if (!entityValues.containsKey(Events.DTSTART)
|| (!entityValues.containsKey(Events.DURATION) &&
!entityValues.containsKey(Events.DTEND))
|| organizerEmail == null) {
continue;
}
if (first) {
s.start(Tags.SYNC_COMMANDS);
userLog("Sending Calendar changes to the server");
first = false;
}
long eventId = entityValues.getAsLong(Events._ID);
if (serverId == null) {
// This is a new event; create a clientId
userLog("Creating new event with clientId: ", clientId);
s.start(Tags.SYNC_ADD).data(Tags.SYNC_CLIENT_ID, clientId);
// And save it in the Event as the local id
cidValues.put(Events.SYNC_DATA2, clientId);
cidValues.put(EVENT_SYNC_VERSION, "0");
cr.update(
asSyncAdapter(
ContentUris.withAppendedId(Events.CONTENT_URI, eventId),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE),
cidValues, null, null);
} else {
if (entityValues.getAsInteger(Events.DELETED) == 1) {
userLog("Deleting event with serverId: ", serverId);
s.start(Tags.SYNC_DELETE).data(Tags.SYNC_SERVER_ID, serverId).end();
mDeletedIdList.add(eventId);
if (selfOrganizer) {
mSendCancelIdList.add(eventId);
} else {
sendDeclinedEmail(entity, clientId);
}
continue;
}
userLog("Upsync change to event with serverId: " + serverId);
// Get the current version
String version = entityValues.getAsString(EVENT_SYNC_VERSION);
// This should never be null, but catch this error anyway
// Version should be "0" when we create the event, so use that
if (version == null) {
version = "0";
} else {
// Increment and save
try {
version = Integer.toString((Integer.parseInt(version) + 1));
} catch (Exception e) {
// Handle the case in which someone writes a non-integer here;
// shouldn't happen, but we don't want to kill the sync for his
version = "0";
}
}
cidValues.put(EVENT_SYNC_VERSION, version);
// Also save in entityValues so that we send it this time around
entityValues.put(EVENT_SYNC_VERSION, version);
cr.update(
asSyncAdapter(
ContentUris.withAppendedId(Events.CONTENT_URI, eventId),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE),
cidValues, null, null);
s.start(Tags.SYNC_CHANGE).data(Tags.SYNC_SERVER_ID, serverId);
}
s.start(Tags.SYNC_APPLICATION_DATA);
sendEvent(entity, clientId, s);
// Now, the hard part; find exceptions for this event
if (serverId != null) {
EntityIterator exIterator = EventsEntity.newEntityIterator(cr.query(
asSyncAdapter(Events.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null,
ORIGINAL_EVENT_AND_CALENDAR, new String[] {
serverId, mCalendarIdString
}, null), cr);
boolean exFirst = true;
while (exIterator.hasNext()) {
Entity exEntity = exIterator.next();
if (exFirst) {
s.start(Tags.CALENDAR_EXCEPTIONS);
exFirst = false;
}
s.start(Tags.CALENDAR_EXCEPTION);
sendEvent(exEntity, null, s);
ContentValues exValues = exEntity.getEntityValues();
if (getInt(exValues, Events.DIRTY) == 1) {
// This is a new/updated exception, so we've got to notify our
// attendees about it
long exEventId = exValues.getAsLong(Events._ID);
int flag;
// Copy subvalues into the exception; otherwise, we won't see the
// attendees when preparing the message
for (NamedContentValues ncv: entity.getSubValues()) {
exEntity.addSubValue(ncv.uri, ncv.values);
}
if ((getInt(exValues, Events.DELETED) == 1) ||
(getInt(exValues, Events.STATUS) ==
Events.STATUS_CANCELED)) {
flag = Message.FLAG_OUTGOING_MEETING_CANCEL;
if (!selfOrganizer) {
// Send a cancellation notice to the organizer
// Since CalendarProvider2 sets the organizer of exceptions
// to the user, we have to reset it first to the original
// organizer
exValues.put(Events.ORGANIZER,
entityValues.getAsString(Events.ORGANIZER));
sendDeclinedEmail(exEntity, clientId);
}
} else {
flag = Message.FLAG_OUTGOING_MEETING_INVITE;
}
// Add the eventId of the exception to the uploaded id list, so that
// the dirty/mark bits are cleared
mUploadedIdList.add(exEventId);
// Copy version so the ics attachment shows the proper sequence #
exValues.put(EVENT_SYNC_VERSION,
entityValues.getAsString(EVENT_SYNC_VERSION));
// Copy location so that it's included in the outgoing email
if (entityValues.containsKey(Events.EVENT_LOCATION)) {
exValues.put(Events.EVENT_LOCATION,
entityValues.getAsString(Events.EVENT_LOCATION));
}
if (selfOrganizer) {
Message msg =
CalendarUtilities.createMessageForEntity(mContext,
exEntity, flag, clientId, mAccount);
if (msg != null) {
userLog("Queueing exception update to " + msg.mTo);
mOutgoingMailList.add(msg);
}
}
}
s.end(); // EXCEPTION
}
if (!exFirst) {
s.end(); // EXCEPTIONS
}
}
s.end().end(); // ApplicationData & Change
mUploadedIdList.add(eventId);
// Go through the extended properties of this Event and pull out our tokenized
// attendees list and the user attendee status; we will need them later
String attendeeString = null;
long attendeeStringId = -1;
String userAttendeeStatus = null;
long userAttendeeStatusId = -1;
for (NamedContentValues ncv: entity.getSubValues()) {
if (ncv.uri.equals(ExtendedProperties.CONTENT_URI)) {
ContentValues ncvValues = ncv.values;
String propertyName =
ncvValues.getAsString(ExtendedProperties.NAME);
if (propertyName.equals(EXTENDED_PROPERTY_ATTENDEES)) {
attendeeString =
ncvValues.getAsString(ExtendedProperties.VALUE);
attendeeStringId =
ncvValues.getAsLong(ExtendedProperties._ID);
} else if (propertyName.equals(
EXTENDED_PROPERTY_USER_ATTENDEE_STATUS)) {
userAttendeeStatus =
ncvValues.getAsString(ExtendedProperties.VALUE);
userAttendeeStatusId =
ncvValues.getAsLong(ExtendedProperties._ID);
}
}
}
// Send the meeting invite if there are attendees and we're the organizer AND
// if the Event itself is dirty (we might be syncing only because an exception
// is dirty, in which case we DON'T send email about the Event)
if (selfOrganizer &&
(getInt(entityValues, Events.DIRTY) == 1)) {
EmailContent.Message msg =
CalendarUtilities.createMessageForEventId(mContext, eventId,
EmailContent.Message.FLAG_OUTGOING_MEETING_INVITE, clientId,
mAccount);
if (msg != null) {
userLog("Queueing invitation to ", msg.mTo);
mOutgoingMailList.add(msg);
}
// Make a list out of our tokenized attendees, if we have any
ArrayList<String> originalAttendeeList = new ArrayList<String>();
if (attendeeString != null) {
StringTokenizer st =
new StringTokenizer(attendeeString, ATTENDEE_TOKENIZER_DELIMITER);
while (st.hasMoreTokens()) {
originalAttendeeList.add(st.nextToken());
}
}
StringBuilder newTokenizedAttendees = new StringBuilder();
// See if any attendees have been dropped and while we're at it, build
// an updated String with tokenized attendee addresses
for (NamedContentValues ncv: entity.getSubValues()) {
if (ncv.uri.equals(Attendees.CONTENT_URI)) {
String attendeeEmail =
ncv.values.getAsString(Attendees.ATTENDEE_EMAIL);
// Remove all found attendees
originalAttendeeList.remove(attendeeEmail);
newTokenizedAttendees.append(attendeeEmail);
newTokenizedAttendees.append(ATTENDEE_TOKENIZER_DELIMITER);
}
}
// Update extended properties with the new attendee list, if we have one
// Otherwise, create one (this would be the case for Events created on
// device or "legacy" events (before this code was added)
ContentValues cv = new ContentValues();
cv.put(ExtendedProperties.VALUE, newTokenizedAttendees.toString());
if (attendeeString != null) {
cr.update(asSyncAdapter(ContentUris.withAppendedId(
ExtendedProperties.CONTENT_URI, attendeeStringId),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE),
cv, null, null);
} else {
// If there wasn't an "attendees" property, insert one
cv.put(ExtendedProperties.NAME, EXTENDED_PROPERTY_ATTENDEES);
cv.put(ExtendedProperties.EVENT_ID, eventId);
cr.insert(asSyncAdapter(ExtendedProperties.CONTENT_URI,
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cv);
}
// Whoever is left has been removed from the attendee list; send them
// a cancellation
for (String removedAttendee: originalAttendeeList) {
// Send a cancellation message to each of them
msg = CalendarUtilities.createMessageForEventId(mContext, eventId,
Message.FLAG_OUTGOING_MEETING_CANCEL, clientId, mAccount,
removedAttendee);
if (msg != null) {
// Just send it to the removed attendee
userLog("Queueing cancellation to removed attendee " + msg.mTo);
mOutgoingMailList.add(msg);
}
}
} else if (!selfOrganizer) {
// If we're not the organizer, see if we've changed our attendee status
// Our last synced attendee status is in ExtendedProperties, and we've
// retrieved it above as userAttendeeStatus
int currentStatus = entityValues.getAsInteger(Events.SELF_ATTENDEE_STATUS);
int syncStatus = Attendees.ATTENDEE_STATUS_NONE;
if (userAttendeeStatus != null) {
try {
syncStatus = Integer.parseInt(userAttendeeStatus);
} catch (NumberFormatException e) {
// Just in case somebody else mucked with this and it's not Integer
}
}
if ((currentStatus != syncStatus) &&
(currentStatus != Attendees.ATTENDEE_STATUS_NONE)) {
// If so, send a meeting reply
int messageFlag = 0;
switch (currentStatus) {
case Attendees.ATTENDEE_STATUS_ACCEPTED:
messageFlag = Message.FLAG_OUTGOING_MEETING_ACCEPT;
break;
case Attendees.ATTENDEE_STATUS_DECLINED:
messageFlag = Message.FLAG_OUTGOING_MEETING_DECLINE;
break;
case Attendees.ATTENDEE_STATUS_TENTATIVE:
messageFlag = Message.FLAG_OUTGOING_MEETING_TENTATIVE;
break;
}
// Make sure we have a valid status (messageFlag should never be zero)
if (messageFlag != 0 && userAttendeeStatusId >= 0) {
// Save away the new status
cidValues.clear();
cidValues.put(ExtendedProperties.VALUE,
Integer.toString(currentStatus));
cr.update(ContentUris.withAppendedId(ExtendedProperties.CONTENT_URI,
userAttendeeStatusId), cidValues, null, null);
// Send mail to the organizer advising of the new status
EmailContent.Message msg =
CalendarUtilities.createMessageForEventId(mContext, eventId,
messageFlag, clientId, mAccount);
if (msg != null) {
userLog("Queueing invitation reply to " + msg.mTo);
mOutgoingMailList.add(msg);
}
}
}
}
}
if (!first) {
s.end(); // Commands
}
} finally {
eventIterator.close();
}
} catch (RemoteException e) {
Log.e(TAG, "Could not read dirty events.");
}
return false;
}
| public boolean sendLocalChanges(Serializer s) throws IOException {
ContentResolver cr = mService.mContentResolver;
if (getSyncKey().equals("0")) {
return false;
}
try {
// We've got to handle exceptions as part of the parent when changes occur, so we need
// to find new/changed exceptions and mark the parent dirty
ArrayList<Long> orphanedExceptions = new ArrayList<Long>();
Cursor c = cr.query(Events.CONTENT_URI, ORIGINAL_EVENT_PROJECTION,
DIRTY_EXCEPTION_IN_CALENDAR, mCalendarIdArgument, null);
try {
ContentValues cv = new ContentValues();
// We use _sync_mark here to distinguish dirty parents from parents with dirty
// exceptions
cv.put(EVENT_SYNC_MARK, "1");
while (c.moveToNext()) {
// Mark the parents of dirty exceptions
long parentId = c.getLong(0);
int cnt = cr.update(
asSyncAdapter(Events.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cv,
EVENT_ID_AND_CALENDAR_ID, new String[] {
Long.toString(parentId), mCalendarIdString
});
// Keep track of any orphaned exceptions
if (cnt == 0) {
orphanedExceptions.add(c.getLong(1));
}
}
} finally {
c.close();
}
// Delete any orphaned exceptions
for (long orphan : orphanedExceptions) {
userLog(TAG, "Deleted orphaned exception: " + orphan);
cr.delete(
asSyncAdapter(ContentUris.withAppendedId(Events.CONTENT_URI, orphan),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null, null);
}
orphanedExceptions.clear();
// Now we can go through dirty/marked top-level events and send them
// back to the server
EntityIterator eventIterator = EventsEntity.newEntityIterator(cr.query(
asSyncAdapter(Events.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null,
DIRTY_OR_MARKED_TOP_LEVEL_IN_CALENDAR, mCalendarIdArgument, null), cr);
ContentValues cidValues = new ContentValues();
try {
boolean first = true;
while (eventIterator.hasNext()) {
Entity entity = eventIterator.next();
// For each of these entities, create the change commands
ContentValues entityValues = entity.getEntityValues();
String serverId = entityValues.getAsString(Events._SYNC_ID);
// We first need to check whether we can upsync this event; our test for this
// is currently the value of EXTENDED_PROPERTY_ATTENDEES_REDACTED
// If this is set to "1", we can't upsync the event
for (NamedContentValues ncv: entity.getSubValues()) {
if (ncv.uri.equals(ExtendedProperties.CONTENT_URI)) {
ContentValues ncvValues = ncv.values;
if (ncvValues.getAsString(ExtendedProperties.NAME).equals(
EXTENDED_PROPERTY_UPSYNC_PROHIBITED)) {
if ("1".equals(ncvValues.getAsString(ExtendedProperties.VALUE))) {
// Make sure we mark this to clear the dirty flag
mUploadedIdList.add(entityValues.getAsLong(Events._ID));
continue;
}
}
}
}
// Find our uid in the entity; otherwise create one
String clientId = entityValues.getAsString(Events.SYNC_DATA2);
if (clientId == null) {
clientId = UUID.randomUUID().toString();
}
// EAS 2.5 needs: BusyStatus DtStamp EndTime Sensitivity StartTime TimeZone UID
// We can generate all but what we're testing for below
String organizerEmail = entityValues.getAsString(Events.ORGANIZER);
boolean selfOrganizer = organizerEmail.equalsIgnoreCase(mEmailAddress);
if (!entityValues.containsKey(Events.DTSTART)
|| (!entityValues.containsKey(Events.DURATION) &&
!entityValues.containsKey(Events.DTEND))
|| organizerEmail == null) {
continue;
}
if (first) {
s.start(Tags.SYNC_COMMANDS);
userLog("Sending Calendar changes to the server");
first = false;
}
long eventId = entityValues.getAsLong(Events._ID);
if (serverId == null) {
// This is a new event; create a clientId
userLog("Creating new event with clientId: ", clientId);
s.start(Tags.SYNC_ADD).data(Tags.SYNC_CLIENT_ID, clientId);
// And save it in the Event as the local id
cidValues.put(Events.SYNC_DATA2, clientId);
cidValues.put(EVENT_SYNC_VERSION, "0");
cr.update(
asSyncAdapter(
ContentUris.withAppendedId(Events.CONTENT_URI, eventId),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE),
cidValues, null, null);
} else {
if (entityValues.getAsInteger(Events.DELETED) == 1) {
userLog("Deleting event with serverId: ", serverId);
s.start(Tags.SYNC_DELETE).data(Tags.SYNC_SERVER_ID, serverId).end();
mDeletedIdList.add(eventId);
if (selfOrganizer) {
mSendCancelIdList.add(eventId);
} else {
sendDeclinedEmail(entity, clientId);
}
continue;
}
userLog("Upsync change to event with serverId: " + serverId);
// Get the current version
String version = entityValues.getAsString(EVENT_SYNC_VERSION);
// This should never be null, but catch this error anyway
// Version should be "0" when we create the event, so use that
if (version == null) {
version = "0";
} else {
// Increment and save
try {
version = Integer.toString((Integer.parseInt(version) + 1));
} catch (Exception e) {
// Handle the case in which someone writes a non-integer here;
// shouldn't happen, but we don't want to kill the sync for his
version = "0";
}
}
cidValues.put(EVENT_SYNC_VERSION, version);
// Also save in entityValues so that we send it this time around
entityValues.put(EVENT_SYNC_VERSION, version);
cr.update(
asSyncAdapter(
ContentUris.withAppendedId(Events.CONTENT_URI, eventId),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE),
cidValues, null, null);
s.start(Tags.SYNC_CHANGE).data(Tags.SYNC_SERVER_ID, serverId);
}
s.start(Tags.SYNC_APPLICATION_DATA);
sendEvent(entity, clientId, s);
// Now, the hard part; find exceptions for this event
if (serverId != null) {
EntityIterator exIterator = EventsEntity.newEntityIterator(cr.query(
asSyncAdapter(Events.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null,
ORIGINAL_EVENT_AND_CALENDAR, new String[] {
serverId, mCalendarIdString
}, null), cr);
boolean exFirst = true;
while (exIterator.hasNext()) {
Entity exEntity = exIterator.next();
if (exFirst) {
s.start(Tags.CALENDAR_EXCEPTIONS);
exFirst = false;
}
s.start(Tags.CALENDAR_EXCEPTION);
sendEvent(exEntity, null, s);
ContentValues exValues = exEntity.getEntityValues();
if (getInt(exValues, Events.DIRTY) == 1) {
// This is a new/updated exception, so we've got to notify our
// attendees about it
long exEventId = exValues.getAsLong(Events._ID);
int flag;
// Copy subvalues into the exception; otherwise, we won't see the
// attendees when preparing the message
for (NamedContentValues ncv: entity.getSubValues()) {
exEntity.addSubValue(ncv.uri, ncv.values);
}
if ((getInt(exValues, Events.DELETED) == 1) ||
(getInt(exValues, Events.STATUS) ==
Events.STATUS_CANCELED)) {
flag = Message.FLAG_OUTGOING_MEETING_CANCEL;
if (!selfOrganizer) {
// Send a cancellation notice to the organizer
// Since CalendarProvider2 sets the organizer of exceptions
// to the user, we have to reset it first to the original
// organizer
exValues.put(Events.ORGANIZER,
entityValues.getAsString(Events.ORGANIZER));
sendDeclinedEmail(exEntity, clientId);
}
} else {
flag = Message.FLAG_OUTGOING_MEETING_INVITE;
}
// Add the eventId of the exception to the uploaded id list, so that
// the dirty/mark bits are cleared
mUploadedIdList.add(exEventId);
// Copy version so the ics attachment shows the proper sequence #
exValues.put(EVENT_SYNC_VERSION,
entityValues.getAsString(EVENT_SYNC_VERSION));
// Copy location so that it's included in the outgoing email
if (entityValues.containsKey(Events.EVENT_LOCATION)) {
exValues.put(Events.EVENT_LOCATION,
entityValues.getAsString(Events.EVENT_LOCATION));
}
if (selfOrganizer) {
Message msg =
CalendarUtilities.createMessageForEntity(mContext,
exEntity, flag, clientId, mAccount);
if (msg != null) {
userLog("Queueing exception update to " + msg.mTo);
mOutgoingMailList.add(msg);
}
}
}
s.end(); // EXCEPTION
}
if (!exFirst) {
s.end(); // EXCEPTIONS
}
}
s.end().end(); // ApplicationData & Change
mUploadedIdList.add(eventId);
// Go through the extended properties of this Event and pull out our tokenized
// attendees list and the user attendee status; we will need them later
String attendeeString = null;
long attendeeStringId = -1;
String userAttendeeStatus = null;
long userAttendeeStatusId = -1;
for (NamedContentValues ncv: entity.getSubValues()) {
if (ncv.uri.equals(ExtendedProperties.CONTENT_URI)) {
ContentValues ncvValues = ncv.values;
String propertyName =
ncvValues.getAsString(ExtendedProperties.NAME);
if (propertyName.equals(EXTENDED_PROPERTY_ATTENDEES)) {
attendeeString =
ncvValues.getAsString(ExtendedProperties.VALUE);
attendeeStringId =
ncvValues.getAsLong(ExtendedProperties._ID);
} else if (propertyName.equals(
EXTENDED_PROPERTY_USER_ATTENDEE_STATUS)) {
userAttendeeStatus =
ncvValues.getAsString(ExtendedProperties.VALUE);
userAttendeeStatusId =
ncvValues.getAsLong(ExtendedProperties._ID);
}
}
}
// Send the meeting invite if there are attendees and we're the organizer AND
// if the Event itself is dirty (we might be syncing only because an exception
// is dirty, in which case we DON'T send email about the Event)
if (selfOrganizer &&
(getInt(entityValues, Events.DIRTY) == 1)) {
EmailContent.Message msg =
CalendarUtilities.createMessageForEventId(mContext, eventId,
EmailContent.Message.FLAG_OUTGOING_MEETING_INVITE, clientId,
mAccount);
if (msg != null) {
userLog("Queueing invitation to ", msg.mTo);
mOutgoingMailList.add(msg);
}
// Make a list out of our tokenized attendees, if we have any
ArrayList<String> originalAttendeeList = new ArrayList<String>();
if (attendeeString != null) {
StringTokenizer st =
new StringTokenizer(attendeeString, ATTENDEE_TOKENIZER_DELIMITER);
while (st.hasMoreTokens()) {
originalAttendeeList.add(st.nextToken());
}
}
StringBuilder newTokenizedAttendees = new StringBuilder();
// See if any attendees have been dropped and while we're at it, build
// an updated String with tokenized attendee addresses
for (NamedContentValues ncv: entity.getSubValues()) {
if (ncv.uri.equals(Attendees.CONTENT_URI)) {
String attendeeEmail =
ncv.values.getAsString(Attendees.ATTENDEE_EMAIL);
// Remove all found attendees
originalAttendeeList.remove(attendeeEmail);
newTokenizedAttendees.append(attendeeEmail);
newTokenizedAttendees.append(ATTENDEE_TOKENIZER_DELIMITER);
}
}
// Update extended properties with the new attendee list, if we have one
// Otherwise, create one (this would be the case for Events created on
// device or "legacy" events (before this code was added)
ContentValues cv = new ContentValues();
cv.put(ExtendedProperties.VALUE, newTokenizedAttendees.toString());
if (attendeeString != null) {
cr.update(asSyncAdapter(ContentUris.withAppendedId(
ExtendedProperties.CONTENT_URI, attendeeStringId),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE),
cv, null, null);
} else {
// If there wasn't an "attendees" property, insert one
cv.put(ExtendedProperties.NAME, EXTENDED_PROPERTY_ATTENDEES);
cv.put(ExtendedProperties.EVENT_ID, eventId);
cr.insert(asSyncAdapter(ExtendedProperties.CONTENT_URI,
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cv);
}
// Whoever is left has been removed from the attendee list; send them
// a cancellation
for (String removedAttendee: originalAttendeeList) {
// Send a cancellation message to each of them
msg = CalendarUtilities.createMessageForEventId(mContext, eventId,
Message.FLAG_OUTGOING_MEETING_CANCEL, clientId, mAccount,
removedAttendee);
if (msg != null) {
// Just send it to the removed attendee
userLog("Queueing cancellation to removed attendee " + msg.mTo);
mOutgoingMailList.add(msg);
}
}
} else if (!selfOrganizer) {
// If we're not the organizer, see if we've changed our attendee status
// Our last synced attendee status is in ExtendedProperties, and we've
// retrieved it above as userAttendeeStatus
int currentStatus = entityValues.getAsInteger(Events.SELF_ATTENDEE_STATUS);
int syncStatus = Attendees.ATTENDEE_STATUS_NONE;
if (userAttendeeStatus != null) {
try {
syncStatus = Integer.parseInt(userAttendeeStatus);
} catch (NumberFormatException e) {
// Just in case somebody else mucked with this and it's not Integer
}
}
if ((currentStatus != syncStatus) &&
(currentStatus != Attendees.ATTENDEE_STATUS_NONE)) {
// If so, send a meeting reply
int messageFlag = 0;
switch (currentStatus) {
case Attendees.ATTENDEE_STATUS_ACCEPTED:
messageFlag = Message.FLAG_OUTGOING_MEETING_ACCEPT;
break;
case Attendees.ATTENDEE_STATUS_DECLINED:
messageFlag = Message.FLAG_OUTGOING_MEETING_DECLINE;
break;
case Attendees.ATTENDEE_STATUS_TENTATIVE:
messageFlag = Message.FLAG_OUTGOING_MEETING_TENTATIVE;
break;
}
// Make sure we have a valid status (messageFlag should never be zero)
if (messageFlag != 0 && userAttendeeStatusId >= 0) {
// Save away the new status
cidValues.clear();
cidValues.put(ExtendedProperties.VALUE,
Integer.toString(currentStatus));
cr.update(asSyncAdapter(ContentUris.withAppendedId(
ExtendedProperties.CONTENT_URI, userAttendeeStatusId),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE),
cidValues, null, null);
// Send mail to the organizer advising of the new status
EmailContent.Message msg =
CalendarUtilities.createMessageForEventId(mContext, eventId,
messageFlag, clientId, mAccount);
if (msg != null) {
userLog("Queueing invitation reply to " + msg.mTo);
mOutgoingMailList.add(msg);
}
}
}
}
}
if (!first) {
s.end(); // Commands
}
} finally {
eventIterator.close();
}
} catch (RemoteException e) {
Log.e(TAG, "Could not read dirty events.");
}
return false;
}
|
diff --git a/src/main/java/net/md_5/bungee/BungeeCord.java b/src/main/java/net/md_5/bungee/BungeeCord.java
index bf801b48..3e13505b 100644
--- a/src/main/java/net/md_5/bungee/BungeeCord.java
+++ b/src/main/java/net/md_5/bungee/BungeeCord.java
@@ -1,219 +1,222 @@
package net.md_5.bungee;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import static net.md_5.bungee.Logger.$;
import net.md_5.bungee.command.Command;
import net.md_5.bungee.command.CommandAlert;
import net.md_5.bungee.command.CommandEnd;
import net.md_5.bungee.command.CommandIP;
import net.md_5.bungee.command.CommandList;
import net.md_5.bungee.command.CommandMotd;
import net.md_5.bungee.command.CommandSender;
import net.md_5.bungee.command.CommandServer;
import net.md_5.bungee.command.ConsoleCommandSender;
import net.md_5.bungee.plugin.JavaPluginManager;
/**
* Main BungeeCord proxy class.
*/
public class BungeeCord
{
/**
* Current software instance.
*/
public static BungeeCord instance;
/**
* Current operation state.
*/
public volatile boolean isRunning;
/**
* Configuration.
*/
public final Configuration config = new Configuration();
/**
* Thread pool.
*/
public final ExecutorService threadPool = Executors.newCachedThreadPool();
/**
* locations.yml save thread.
*/
private final ReconnectSaveThread saveThread = new ReconnectSaveThread();
/**
* Server socket listener.
*/
private ListenThread listener;
/**
* Current version.
*/
public String version = (getClass().getPackage().getImplementationVersion() == null) ? "unknown" : getClass().getPackage().getImplementationVersion();
/**
* Fully qualified connections.
*/
public Map<String, UserConnection> connections = new ConcurrentHashMap<>();
/**
* Registered commands.
*/
public Map<String, Command> commandMap = new HashMap<>();
/**
* Plugin manager.
*/
public final JavaPluginManager pluginManager = new JavaPluginManager();
{
commandMap.put("end", new CommandEnd());
commandMap.put("glist", new CommandList());
commandMap.put("server", new CommandServer());
commandMap.put("ip", new CommandIP());
commandMap.put("alert", new CommandAlert());
commandMap.put("motd", new CommandMotd());
}
/**
* Starts a new instance of BungeeCord.
*
* @param args command line arguments, currently none are used
* @throws IOException when the server cannot be started
*/
public static void main(String[] args) throws IOException
{
instance = new BungeeCord();
$().info("Enabled BungeeCord version " + instance.version);
instance.start();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (instance.isRunning)
{
String line = br.readLine();
if (line != null)
{
boolean handled = instance.dispatchCommand(line, ConsoleCommandSender.instance);
if (!handled)
{
System.err.println("Command not found");
}
}
}
}
/**
* Dispatch a command by formatting the arguments and then executing it.
*
* @param commandLine the entire command and arguments string
* @param sender which executed the command
* @return whether the command was handled or not.
*/
public boolean dispatchCommand(String commandLine, CommandSender sender)
{
String[] split = commandLine.trim().split(" ");
String commandName = split[0].toLowerCase();
Command command = commandMap.get(commandName);
- if (command != null && (config.disabledCommands == null || !config.disabledCommands.contains(commandName)))
+ if (config.disabledCommands == null || !config.disabledCommands.contains(commandName))
+ {
+ return false;
+ } else if (command != null)
{
String[] args = Arrays.copyOfRange(split, 1, split.length);
try
{
command.execute(sender, args);
} catch (Exception ex)
{
sender.sendMessage(ChatColor.RED + "An error occurred while executing this command!");
$().severe("----------------------- [Start of command error] -----------------------");
$().log(Level.SEVERE, "", ex);
$().severe("----------------------- [End of command error] -----------------------");
}
}
return command != null;
}
/**
* Start this proxy instance by loading the configuration, plugins and
* starting the connect thread.
*
* @throws IOException
*/
public void start() throws IOException
{
config.load();
isRunning = true;
pluginManager.loadPlugins();
InetSocketAddress addr = Util.getAddr(config.bindHost);
listener = new ListenThread(addr);
listener.start();
saveThread.start();
$().info("Listening on " + addr);
new Metrics().start();
}
/**
* Destroy this proxy instance cleanly by kicking all users, saving the
* configuration and closing all sockets.
*/
public void stop()
{
this.isRunning = false;
$().info("Disabling plugin");
pluginManager.onDisable();
$().info("Closing listen thread");
try
{
listener.socket.close();
listener.join();
} catch (InterruptedException | IOException ex)
{
$().severe("Could not close listen thread");
}
$().info("Closing pending connections");
threadPool.shutdown();
$().info("Disconnecting " + connections.size() + " connections");
for (UserConnection user : connections.values())
{
user.disconnect("Proxy restarting, brb.");
}
$().info("Saving reconnect locations");
saveThread.interrupt();
try
{
saveThread.join();
} catch (InterruptedException ex)
{
}
$().info("Thank you and goodbye");
System.exit(0);
}
/**
* Miscellaneous method to set options on a socket based on those in the
* configuration.
*
* @param socket to set the options on
* @throws IOException when the underlying set methods thrown an exception
*/
public void setSocketOptions(Socket socket) throws IOException
{
socket.setSoTimeout(config.timeout);
socket.setTrafficClass(0x18);
socket.setTcpNoDelay(true);
}
}
| true | false | null | null |
diff --git a/src/com/urbanairship/octobot/QueueConsumer.java b/src/com/urbanairship/octobot/QueueConsumer.java
index 5b1baa3..0327dc5 100644
--- a/src/com/urbanairship/octobot/QueueConsumer.java
+++ b/src/com/urbanairship/octobot/QueueConsumer.java
@@ -1,274 +1,274 @@
package com.urbanairship.octobot;
// AMQP Support
import java.io.IOException;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.QueueingConsumer;
// Beanstalk Support
import com.surftools.BeanstalkClient.BeanstalkException;
import com.surftools.BeanstalkClient.Job;
import com.surftools.BeanstalkClientImpl.ClientImpl;
import java.io.PrintWriter;
import java.io.StringWriter;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.apache.log4j.Logger;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub;
// This thread opens a streaming connection to a queue, which continually
// pushes messages to Octobot queue workers. The tasks contained within these
// messages are invoked, then acknowledged and removed from the queue.
public class QueueConsumer implements Runnable {
Queue queue = null;
Channel channel = null;
Connection connection = null;
QueueingConsumer consumer = null;
private final Logger logger = Logger.getLogger("Queue Consumer");
private boolean enableEmailErrors = Settings.getAsBoolean("Octobot", "email_enabled");
// Initialize the consumer with a queue object (AMQP, Beanstalk, or Redis).
public QueueConsumer(Queue queue) {
this.queue = queue;
}
// Fire up the appropriate queue listener and begin invoking tasks!.
public void run() {
if (queue.queueType.equals("amqp")) {
channel = getAMQPChannel(queue);
consumeFromAMQP();
} else if (queue.queueType.equals("beanstalk")) {
consumeFromBeanstalk();
} else if (queue.queueType.equals("redis")) {
consumeFromRedis();
} else {
logger.error("Invalid queue type specified: " + queue.queueType);
}
}
// Attempts to register to receive streaming messages from RabbitMQ.
// In the event that RabbitMQ is unavailable the call to getChannel()
// will attempt to reconnect. If it fails, the loop simply repeats.
private void consumeFromAMQP() {
while (true) {
QueueingConsumer.Delivery task = null;
try { task = consumer.nextDelivery(); }
catch (Exception e){
logger.error("Error in AMQP connection; reconnecting.", e);
channel = getAMQPChannel(queue);
continue;
}
// If we've got a message, fetch the body and invoke the task.
// Then, send an acknowledgement back to RabbitMQ that we got it.
if (task != null && task.getBody() != null) {
invokeTask(new String(task.getBody()));
try { channel.basicAck(task.getEnvelope().getDeliveryTag(), false); }
catch (IOException e) { logger.error("Error ack'ing message.", e); }
}
}
}
// Attempt to register to receive messages from Beanstalk and invoke tasks.
private void consumeFromBeanstalk() {
ClientImpl beanstalkClient = new ClientImpl(queue.host, queue.port);
beanstalkClient.watch(queue.queueName);
beanstalkClient.useTube(queue.queueName);
logger.info("Connected to Beanstalk; waiting for jobs.");
while (true) {
Job job = null;
try { job = beanstalkClient.reserve(1); }
catch (BeanstalkException e) {
logger.error("Beanstalk connection error.", e);
beanstalkClient = Beanstalk.getBeanstalkChannel(queue.host,
queue.port, queue.queueName);
continue;
}
if (job != null) {
String message = new String(job.getData());
try { invokeTask(message); }
catch (Exception e) { logger.error("Error handling message.", e); }
try { beanstalkClient.delete(job.getJobId()); }
catch (BeanstalkException e) {
logger.error("Error sending message receipt.", e);
beanstalkClient = Beanstalk.getBeanstalkChannel(queue.host,
queue.port, queue.queueName);
}
}
}
}
private void consumeFromRedis() {
logger.info("Connecting to Redis...");
Jedis jedis = new Jedis(queue.host, queue.port);
try {
jedis.connect();
} catch (IOException e) {
logger.error("Unable to connect to Redis.", e);
}
logger.info("Connected to Redis.");
jedis.subscribe(new JedisPubSub() {
@Override
public void onMessage(String channel, String message) {
invokeTask(message);
}
@Override
public void onPMessage(String string, String string1, String string2) {
logger.info("onPMessage Triggered - Not implemented.");
}
@Override
public void onSubscribe(String string, int i) {
logger.info("onSubscribe called - Not implemented.");
}
@Override
public void onUnsubscribe(String string, int i) {
logger.info("onUnsubscribe Called - Not implemented.");
}
@Override
public void onPUnsubscribe(String string, int i) {
logger.info("onPUnsubscribe called - Not implemented.");
}
@Override
public void onPSubscribe(String string, int i) {
logger.info("onPSubscribe Triggered - Not implemented.");
}
}, queue.queueName);
}
// Invokes a task based on the name of the task passed in the message via
// reflection, accounting for non-existent tasks and errors while running.
public boolean invokeTask(String rawMessage) {
String taskName = "";
JSONObject message;
int retryCount = 0;
long retryTimes = 0;
long startedAt = System.nanoTime();
String errorMessage = null;
Throwable lastException = null;
boolean executedSuccessfully = false;
while (retryCount < retryTimes + 1) {
if (retryCount > 0)
logger.info("Retrying task. Attempt " + retryCount + " of " + retryTimes);
try {
message = (JSONObject) JSONValue.parse(rawMessage);
taskName = (String) message.get("task");
if (message.containsKey("retries"))
retryTimes = (Long) message.get("retries");
} catch (Exception e) {
logger.error("Error: Invalid message received: " + rawMessage);
return executedSuccessfully;
}
// Locate the task, then invoke it, supplying our message.
// Cache methods after lookup to avoid unnecessary reflection lookups.
try {
TaskExecutor.execute(taskName, message);
executedSuccessfully = true;
} catch (ClassNotFoundException e) {
lastException = e;
errorMessage = "Error: Task requested not found: " + taskName;
logger.error(errorMessage);
} catch (NoClassDefFoundError e) {
lastException = e;
errorMessage = "Error: Task requested not found: " + taskName;
logger.error(errorMessage, e);
} catch (NoSuchMethodException e) {
lastException = e;
errorMessage = "Error: Task requested does not have a static run method.";
logger.error(errorMessage);
- } catch (Exception e) {
+ } catch (Throwable e) {
lastException = e;
errorMessage = "An error occurred while running the task.";
logger.error(errorMessage, e);
}
if (executedSuccessfully) break;
else retryCount++;
}
// Deliver an e-mail error notification if enabled.
if (enableEmailErrors && !executedSuccessfully) {
String email = "Error running task: " + taskName + ".\n\n"
+ "Attempted executing " + retryCount + " times as specified.\n\n"
+ "The original input was: \n\n" + rawMessage + "\n\n"
+ "Here's the error that resulted while running the task:\n\n"
+ stackToString(lastException);
try { MailQueue.put(email); }
catch (InterruptedException e) { }
}
long finishedAt = System.nanoTime();
Metrics.update(taskName, finishedAt - startedAt, executedSuccessfully, retryCount);
return executedSuccessfully;
}
// Opens up a connection to RabbitMQ, retrying every five seconds
// if the queue server is unavailable.
private Channel getAMQPChannel(Queue queue) {
int attempts = 0;
logger.info("Opening connection to AMQP / " + queue.queueName + "...");
while (true) {
attempts++;
logger.debug("Attempt #" + attempts);
try {
connection = new RabbitMQ(queue).getConnection();
channel = connection.createChannel();
consumer = new QueueingConsumer(channel);
channel.exchangeDeclare(queue.queueName, "direct", true);
channel.queueDeclare(queue.queueName, true, false, false, null);
channel.queueBind(queue.queueName, queue.queueName, queue.queueName);
channel.basicConsume(queue.queueName, false, consumer);
logger.info("Connected to RabbitMQ");
return channel;
} catch (Exception e) {
logger.error("Cannot connect to AMQP. Retrying in 5 sec.", e);
try { Thread.sleep(1000 * 5); }
catch (InterruptedException ex) { }
}
}
}
// Converts a stacktrace from task invocation to a string for error logging.
public String stackToString(Throwable e) {
if (e == null) return "(Null)";
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
e.printStackTrace(printWriter);
return stringWriter.toString();
}
}
| true | true | public boolean invokeTask(String rawMessage) {
String taskName = "";
JSONObject message;
int retryCount = 0;
long retryTimes = 0;
long startedAt = System.nanoTime();
String errorMessage = null;
Throwable lastException = null;
boolean executedSuccessfully = false;
while (retryCount < retryTimes + 1) {
if (retryCount > 0)
logger.info("Retrying task. Attempt " + retryCount + " of " + retryTimes);
try {
message = (JSONObject) JSONValue.parse(rawMessage);
taskName = (String) message.get("task");
if (message.containsKey("retries"))
retryTimes = (Long) message.get("retries");
} catch (Exception e) {
logger.error("Error: Invalid message received: " + rawMessage);
return executedSuccessfully;
}
// Locate the task, then invoke it, supplying our message.
// Cache methods after lookup to avoid unnecessary reflection lookups.
try {
TaskExecutor.execute(taskName, message);
executedSuccessfully = true;
} catch (ClassNotFoundException e) {
lastException = e;
errorMessage = "Error: Task requested not found: " + taskName;
logger.error(errorMessage);
} catch (NoClassDefFoundError e) {
lastException = e;
errorMessage = "Error: Task requested not found: " + taskName;
logger.error(errorMessage, e);
} catch (NoSuchMethodException e) {
lastException = e;
errorMessage = "Error: Task requested does not have a static run method.";
logger.error(errorMessage);
} catch (Exception e) {
lastException = e;
errorMessage = "An error occurred while running the task.";
logger.error(errorMessage, e);
}
if (executedSuccessfully) break;
else retryCount++;
}
// Deliver an e-mail error notification if enabled.
if (enableEmailErrors && !executedSuccessfully) {
String email = "Error running task: " + taskName + ".\n\n"
+ "Attempted executing " + retryCount + " times as specified.\n\n"
+ "The original input was: \n\n" + rawMessage + "\n\n"
+ "Here's the error that resulted while running the task:\n\n"
+ stackToString(lastException);
try { MailQueue.put(email); }
catch (InterruptedException e) { }
}
long finishedAt = System.nanoTime();
Metrics.update(taskName, finishedAt - startedAt, executedSuccessfully, retryCount);
return executedSuccessfully;
}
| public boolean invokeTask(String rawMessage) {
String taskName = "";
JSONObject message;
int retryCount = 0;
long retryTimes = 0;
long startedAt = System.nanoTime();
String errorMessage = null;
Throwable lastException = null;
boolean executedSuccessfully = false;
while (retryCount < retryTimes + 1) {
if (retryCount > 0)
logger.info("Retrying task. Attempt " + retryCount + " of " + retryTimes);
try {
message = (JSONObject) JSONValue.parse(rawMessage);
taskName = (String) message.get("task");
if (message.containsKey("retries"))
retryTimes = (Long) message.get("retries");
} catch (Exception e) {
logger.error("Error: Invalid message received: " + rawMessage);
return executedSuccessfully;
}
// Locate the task, then invoke it, supplying our message.
// Cache methods after lookup to avoid unnecessary reflection lookups.
try {
TaskExecutor.execute(taskName, message);
executedSuccessfully = true;
} catch (ClassNotFoundException e) {
lastException = e;
errorMessage = "Error: Task requested not found: " + taskName;
logger.error(errorMessage);
} catch (NoClassDefFoundError e) {
lastException = e;
errorMessage = "Error: Task requested not found: " + taskName;
logger.error(errorMessage, e);
} catch (NoSuchMethodException e) {
lastException = e;
errorMessage = "Error: Task requested does not have a static run method.";
logger.error(errorMessage);
} catch (Throwable e) {
lastException = e;
errorMessage = "An error occurred while running the task.";
logger.error(errorMessage, e);
}
if (executedSuccessfully) break;
else retryCount++;
}
// Deliver an e-mail error notification if enabled.
if (enableEmailErrors && !executedSuccessfully) {
String email = "Error running task: " + taskName + ".\n\n"
+ "Attempted executing " + retryCount + " times as specified.\n\n"
+ "The original input was: \n\n" + rawMessage + "\n\n"
+ "Here's the error that resulted while running the task:\n\n"
+ stackToString(lastException);
try { MailQueue.put(email); }
catch (InterruptedException e) { }
}
long finishedAt = System.nanoTime();
Metrics.update(taskName, finishedAt - startedAt, executedSuccessfully, retryCount);
return executedSuccessfully;
}
|