diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/src/main/java/com/salesforce/saml/SAMLFilter.java b/src/main/java/com/salesforce/saml/SAMLFilter.java
index dbb98a6..1a00ba6 100644
--- a/src/main/java/com/salesforce/saml/SAMLFilter.java
+++ b/src/main/java/com/salesforce/saml/SAMLFilter.java
@@ -1,160 +1,162 @@
/*
* Copyright (c) 2012, Salesforce.com
* All rights reserved.
*
* Derived from
* Copyright (c) 2009, Chuck Mortimore
* 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 names salesforce, salesforce.com xmldap, xmldap.org, nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE 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 com.salesforce.saml;
import com.salesforce.util.XSDDateTime;
import org.apache.commons.codec.binary.Base64;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.text.MessageFormat;
import java.util.UUID;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;
public class SAMLFilter implements Filter {
private static final String IDENTITY = "IDENTITY";
private static final String requestTemplate = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><samlp:AuthnRequest xmlns:samlp=\"urn:oasis:names:tc:SAML:2.0:protocol\" AssertionConsumerServiceURL=\"{0}\" Destination=\"{1}\" ID=\"_{2}\" IssueInstant=\"{3}\" ProtocolBinding=\"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST\" Version=\"2.0\"><saml:Issuer xmlns:saml=\"urn:oasis:names:tc:SAML:2.0:assertion\">{4}</saml:Issuer></samlp:AuthnRequest>";
private FilterConfig config;
private static String issuer;
private static String idpurl;
private static PublicKey publicKey;
private static String recipient;
private static String audience;
private static String samlendpoint;
public void init(FilterConfig filterConfig) throws ServletException {
config = filterConfig;
issuer = config.getInitParameter("issuer");
idpurl = config.getInitParameter("idpurl");
recipient = config.getInitParameter("recipient");
audience = config.getInitParameter("audience");
samlendpoint = config.getInitParameter("samlendpoint");
String cert = config.getInitParameter("cert");
try {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate certificate = cf.generateCertificate(new ByteArrayInputStream(cert.getBytes("UTF-8")));
publicKey = certificate.getPublicKey();
} catch (Exception e) {
throw new ServletException("Error getting PublicKey from Cert", e);
}
}
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest)request;
HttpServletResponse httpResponse = (HttpServletResponse)response;
HttpSession session = httpRequest.getSession(true);
Identity identity = (Identity)session.getAttribute(IDENTITY);
if (identity == null) {
//see if this is a SAML Message
if (httpRequest.getRequestURI().equals(samlendpoint)) {
//Get the request and relaystate
String encodedResponse = httpRequest.getParameter("SAMLResponse");
String relayState = request.getParameter("RelayState");
if ((relayState == null) || ( relayState.equals(""))) relayState = "/";
//validate the response
SAMLValidator sv = new SAMLValidator();
try {
identity = sv.validate(encodedResponse, publicKey, issuer, recipient, audience);
session.setAttribute(IDENTITY, identity);
} catch (Exception e) {
httpResponse.sendError(401, "Access Denied: " + e.getMessage());
return;
}
httpResponse.sendRedirect(relayState);
return;
} else {
//Lazy version of building a SAML Request...
String[] args = new String[5];
args[0] = recipient;
args[1] = idpurl;
args[2] = UUID.randomUUID().toString();
args[3] = new XSDDateTime().getDateTime();
args[4] = audience;
MessageFormat html;
html = new MessageFormat(requestTemplate);
String requestXml = html.format(args);
byte[] input = requestXml.getBytes("UTF-8");
//Deflate
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Deflater d = new Deflater(Deflater.DEFLATED, true);
DeflaterOutputStream dout = new DeflaterOutputStream(baos, d);
dout.write(input);
dout.close();
//B64
String encodedRequest = Base64.encodeBase64String(baos.toByteArray());
//URLEncode
String SAMLRequest = URLEncoder.encode(encodedRequest,"UTF-8");
//Redirect
- String rs = URLEncoder.encode(httpRequest.getRequestURI() + "?" + httpRequest.getQueryString(),"UTF-8");;
- httpResponse.sendRedirect(idpurl + "?SAMLRequest=" + SAMLRequest + "&RelayState=" + rs);
+ String rs = httpRequest.getRequestURI();
+ String qs = httpRequest.getQueryString();
+ if ((qs != null) && (!qs.equals(""))) rs += "?" + qs;
+ httpResponse.sendRedirect(idpurl + "?SAMLRequest=" + SAMLRequest + "&RelayState=" + URLEncoder.encode(rs,"UTF-8"));
return;
}
}
chain.doFilter (request, response);
}
}
| true | true | public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest)request;
HttpServletResponse httpResponse = (HttpServletResponse)response;
HttpSession session = httpRequest.getSession(true);
Identity identity = (Identity)session.getAttribute(IDENTITY);
if (identity == null) {
//see if this is a SAML Message
if (httpRequest.getRequestURI().equals(samlendpoint)) {
//Get the request and relaystate
String encodedResponse = httpRequest.getParameter("SAMLResponse");
String relayState = request.getParameter("RelayState");
if ((relayState == null) || ( relayState.equals(""))) relayState = "/";
//validate the response
SAMLValidator sv = new SAMLValidator();
try {
identity = sv.validate(encodedResponse, publicKey, issuer, recipient, audience);
session.setAttribute(IDENTITY, identity);
} catch (Exception e) {
httpResponse.sendError(401, "Access Denied: " + e.getMessage());
return;
}
httpResponse.sendRedirect(relayState);
return;
} else {
//Lazy version of building a SAML Request...
String[] args = new String[5];
args[0] = recipient;
args[1] = idpurl;
args[2] = UUID.randomUUID().toString();
args[3] = new XSDDateTime().getDateTime();
args[4] = audience;
MessageFormat html;
html = new MessageFormat(requestTemplate);
String requestXml = html.format(args);
byte[] input = requestXml.getBytes("UTF-8");
//Deflate
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Deflater d = new Deflater(Deflater.DEFLATED, true);
DeflaterOutputStream dout = new DeflaterOutputStream(baos, d);
dout.write(input);
dout.close();
//B64
String encodedRequest = Base64.encodeBase64String(baos.toByteArray());
//URLEncode
String SAMLRequest = URLEncoder.encode(encodedRequest,"UTF-8");
//Redirect
String rs = URLEncoder.encode(httpRequest.getRequestURI() + "?" + httpRequest.getQueryString(),"UTF-8");;
httpResponse.sendRedirect(idpurl + "?SAMLRequest=" + SAMLRequest + "&RelayState=" + rs);
return;
}
}
chain.doFilter (request, response);
}
| public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest)request;
HttpServletResponse httpResponse = (HttpServletResponse)response;
HttpSession session = httpRequest.getSession(true);
Identity identity = (Identity)session.getAttribute(IDENTITY);
if (identity == null) {
//see if this is a SAML Message
if (httpRequest.getRequestURI().equals(samlendpoint)) {
//Get the request and relaystate
String encodedResponse = httpRequest.getParameter("SAMLResponse");
String relayState = request.getParameter("RelayState");
if ((relayState == null) || ( relayState.equals(""))) relayState = "/";
//validate the response
SAMLValidator sv = new SAMLValidator();
try {
identity = sv.validate(encodedResponse, publicKey, issuer, recipient, audience);
session.setAttribute(IDENTITY, identity);
} catch (Exception e) {
httpResponse.sendError(401, "Access Denied: " + e.getMessage());
return;
}
httpResponse.sendRedirect(relayState);
return;
} else {
//Lazy version of building a SAML Request...
String[] args = new String[5];
args[0] = recipient;
args[1] = idpurl;
args[2] = UUID.randomUUID().toString();
args[3] = new XSDDateTime().getDateTime();
args[4] = audience;
MessageFormat html;
html = new MessageFormat(requestTemplate);
String requestXml = html.format(args);
byte[] input = requestXml.getBytes("UTF-8");
//Deflate
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Deflater d = new Deflater(Deflater.DEFLATED, true);
DeflaterOutputStream dout = new DeflaterOutputStream(baos, d);
dout.write(input);
dout.close();
//B64
String encodedRequest = Base64.encodeBase64String(baos.toByteArray());
//URLEncode
String SAMLRequest = URLEncoder.encode(encodedRequest,"UTF-8");
//Redirect
String rs = httpRequest.getRequestURI();
String qs = httpRequest.getQueryString();
if ((qs != null) && (!qs.equals(""))) rs += "?" + qs;
httpResponse.sendRedirect(idpurl + "?SAMLRequest=" + SAMLRequest + "&RelayState=" + URLEncoder.encode(rs,"UTF-8"));
return;
}
}
chain.doFilter (request, response);
}
|
diff --git a/src/test/java/mock/VoteActionHandlerMockTest.java b/src/test/java/mock/VoteActionHandlerMockTest.java
index 3834c60..56b562d 100644
--- a/src/test/java/mock/VoteActionHandlerMockTest.java
+++ b/src/test/java/mock/VoteActionHandlerMockTest.java
@@ -1,112 +1,111 @@
package mock;
import junit.framework.TestCase;
import org.drools.runtime.StatefulKnowledgeSession;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JMock;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.jmock.lib.legacy.ClassImposteriser;
import org.junit.Test;
import org.junit.runner.RunWith;
import services.NomicService;
import uk.ac.imperial.presage2.core.Action;
import uk.ac.imperial.presage2.core.environment.ActionHandlingException;
import uk.ac.imperial.presage2.core.environment.EnvironmentServiceProvider;
import uk.ac.imperial.presage2.core.environment.EnvironmentSharedStateAccess;
import uk.ac.imperial.presage2.core.environment.UnavailableServiceException;
import uk.ac.imperial.presage2.core.event.EventBus;
import uk.ac.imperial.presage2.core.util.random.Random;
import actionHandlers.VoteActionHandler;
import actions.Vote;
import agents.NomicAgent;
import enums.VoteType;
@RunWith(JMock.class)
public class VoteActionHandlerMockTest extends TestCase {
Mockery context = new JUnit4Mockery();
final StatefulKnowledgeSession session = context.mock(StatefulKnowledgeSession.class);
final EnvironmentServiceProvider serviceProvider = context.mock(EnvironmentServiceProvider.class);
final EventBus e = context.mock(EventBus.class);
final EnvironmentSharedStateAccess sharedState = context.mock(EnvironmentSharedStateAccess.class);
@Test
public void canHandleTest() {
context.setImposteriser(ClassImposteriser.INSTANCE);
final NomicAgent mockAgent = context.mock(NomicAgent.class);
VoteActionHandler handler = new VoteActionHandler(serviceProvider);
Vote yes = new Vote(mockAgent, VoteType.YES);
Vote no = new Vote(mockAgent, VoteType.NO);
Action genericAction = context.mock(Action.class);
assertTrue(handler.canHandle(yes));
assertTrue(handler.canHandle(no));
assertFalse(handler.canHandle(genericAction));
}
@Test
public void handleTest() throws UnavailableServiceException {
context.setImposteriser(ClassImposteriser.INSTANCE);
final NomicAgent mockAgent = context.mock(NomicAgent.class);
final NomicService service = context.mock(NomicService.class);
final Vote yes = new Vote(mockAgent, VoteType.YES);
final Vote no = new Vote(mockAgent, VoteType.NO);
final Action genericAction = context.mock(Action.class);
VoteActionHandler handler = new VoteActionHandler(serviceProvider);
context.checking(new Expectations() {{
oneOf(serviceProvider).getEnvironmentService(with(NomicService.class));
will(returnValue(service));
oneOf(service).Vote(yes);
oneOf(service).getTurnNumber();
exactly(2).of(service).getSimTime();
oneOf(mockAgent).getName();
oneOf(service).getActiveStatefulKnowledgeSession(); will(returnValue(session));
oneOf(session).insert(yes);
}});
try {
handler.handle(yes, Random.randomUUID());
} catch (ActionHandlingException e) {
fail("Failed to handle yes vote");
}
context.assertIsSatisfied();
context.checking(new Expectations() {{
oneOf(service).Vote(no);
oneOf(service).getTurnNumber();
exactly(2).of(service).getSimTime();
oneOf(mockAgent).getName();
- oneOf(service).getActiveStatefulKnowledgeSession(); will(returnValue(session));
oneOf(session).insert(no);
}});
try {
handler.handle(no, Random.randomUUID());
} catch (ActionHandlingException e) {
fail("Failed to handle no vote");
}
context.assertIsSatisfied();
try {
handler.handle(genericAction, Random.randomUUID());
fail("Ate exception for invalid action");
} catch (ActionHandlingException e) {
}
}
}
| true | true | public void handleTest() throws UnavailableServiceException {
context.setImposteriser(ClassImposteriser.INSTANCE);
final NomicAgent mockAgent = context.mock(NomicAgent.class);
final NomicService service = context.mock(NomicService.class);
final Vote yes = new Vote(mockAgent, VoteType.YES);
final Vote no = new Vote(mockAgent, VoteType.NO);
final Action genericAction = context.mock(Action.class);
VoteActionHandler handler = new VoteActionHandler(serviceProvider);
context.checking(new Expectations() {{
oneOf(serviceProvider).getEnvironmentService(with(NomicService.class));
will(returnValue(service));
oneOf(service).Vote(yes);
oneOf(service).getTurnNumber();
exactly(2).of(service).getSimTime();
oneOf(mockAgent).getName();
oneOf(service).getActiveStatefulKnowledgeSession(); will(returnValue(session));
oneOf(session).insert(yes);
}});
try {
handler.handle(yes, Random.randomUUID());
} catch (ActionHandlingException e) {
fail("Failed to handle yes vote");
}
context.assertIsSatisfied();
context.checking(new Expectations() {{
oneOf(service).Vote(no);
oneOf(service).getTurnNumber();
exactly(2).of(service).getSimTime();
oneOf(mockAgent).getName();
oneOf(service).getActiveStatefulKnowledgeSession(); will(returnValue(session));
oneOf(session).insert(no);
}});
try {
handler.handle(no, Random.randomUUID());
} catch (ActionHandlingException e) {
fail("Failed to handle no vote");
}
context.assertIsSatisfied();
try {
handler.handle(genericAction, Random.randomUUID());
fail("Ate exception for invalid action");
} catch (ActionHandlingException e) {
}
}
| public void handleTest() throws UnavailableServiceException {
context.setImposteriser(ClassImposteriser.INSTANCE);
final NomicAgent mockAgent = context.mock(NomicAgent.class);
final NomicService service = context.mock(NomicService.class);
final Vote yes = new Vote(mockAgent, VoteType.YES);
final Vote no = new Vote(mockAgent, VoteType.NO);
final Action genericAction = context.mock(Action.class);
VoteActionHandler handler = new VoteActionHandler(serviceProvider);
context.checking(new Expectations() {{
oneOf(serviceProvider).getEnvironmentService(with(NomicService.class));
will(returnValue(service));
oneOf(service).Vote(yes);
oneOf(service).getTurnNumber();
exactly(2).of(service).getSimTime();
oneOf(mockAgent).getName();
oneOf(service).getActiveStatefulKnowledgeSession(); will(returnValue(session));
oneOf(session).insert(yes);
}});
try {
handler.handle(yes, Random.randomUUID());
} catch (ActionHandlingException e) {
fail("Failed to handle yes vote");
}
context.assertIsSatisfied();
context.checking(new Expectations() {{
oneOf(service).Vote(no);
oneOf(service).getTurnNumber();
exactly(2).of(service).getSimTime();
oneOf(mockAgent).getName();
oneOf(session).insert(no);
}});
try {
handler.handle(no, Random.randomUUID());
} catch (ActionHandlingException e) {
fail("Failed to handle no vote");
}
context.assertIsSatisfied();
try {
handler.handle(genericAction, Random.randomUUID());
fail("Ate exception for invalid action");
} catch (ActionHandlingException e) {
}
}
|
diff --git a/kundera-core/src/main/java/com/impetus/kundera/configure/PersistenceUnitConfiguration.java b/kundera-core/src/main/java/com/impetus/kundera/configure/PersistenceUnitConfiguration.java
index 336123c03..988439e51 100644
--- a/kundera-core/src/main/java/com/impetus/kundera/configure/PersistenceUnitConfiguration.java
+++ b/kundera-core/src/main/java/com/impetus/kundera/configure/PersistenceUnitConfiguration.java
@@ -1,169 +1,169 @@
/*******************************************************************************
* * Copyright 2012 Impetus Infotech.
* *
* * 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.impetus.kundera.configure;
import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.persistence.spi.PersistenceUnitTransactionType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.impetus.kundera.KunderaPersistence;
import com.impetus.kundera.loader.PersistenceLoaderException;
import com.impetus.kundera.loader.PersistenceXMLLoader;
import com.impetus.kundera.metadata.model.ApplicationMetadata;
import com.impetus.kundera.metadata.model.KunderaMetadata;
import com.impetus.kundera.metadata.model.PersistenceUnitMetadata;
import com.impetus.kundera.utils.InvalidConfigurationException;
/**
* The Class PersistenceUnitConfiguration: 1) Find and load/configure
* persistence unit meta data. Earlier it was PersistenceUnitLoader.
*
* @author vivek.mishra
*/
public class PersistenceUnitConfiguration implements Configuration
{
/** The log instance. */
private static Logger log = LoggerFactory.getLogger(PersistenceUnitConfiguration.class);
/** The Constant PROVIDER_IMPLEMENTATION_NAME. */
private static final String PROVIDER_IMPLEMENTATION_NAME = KunderaPersistence.class.getName();
/** Holding instance for persistence units. */
protected String[] persistenceUnits;
/**
* Constructor parameterised with persistence units.
*
* @param persistenceUnits
* persistence units.
*/
public PersistenceUnitConfiguration(String... persistenceUnits)
{
this.persistenceUnits = persistenceUnits;
}
/*
* (non-Javadoc)
*
* @see com.impetus.kundera.configure.Configuration#configure()
*/
@Override
public void configure()
{
log.info("Loading Metadata from persistence.xml ...");
KunderaMetadata kunderaMetadata = KunderaMetadata.INSTANCE;
ApplicationMetadata appMetadata = kunderaMetadata.getApplicationMetadata();
Map<String, PersistenceUnitMetadata> metadatas;
try
{
metadatas = findPersistenceMetadatas();
for (String persistenceUnit : persistenceUnits)
{
if (!metadatas.containsKey(persistenceUnit))
{
log.error("Unconfigured persistence unit: " + persistenceUnit
+ " please validate with persistence.xml");
throw new PersistenceUnitConfigurationException("Invalid persistence unit: " + persistenceUnit
+ " provided");
}
// metadatas.get(persistenceUnit);
}
log.info("Finishing persistence unit metadata configuration ...");
appMetadata.addPersistenceUnitMetadata(metadatas);
}
catch (InvalidConfigurationException icex)
{
log.error("Error occurred during persistence unit configuration, Caused by:" + icex.getMessage());
throw new PersistenceLoaderException(icex);
}
}
/**
* Find persistence meta data. Loads configured persistence.xml and load all
* provided configurations within persistence meta data as per @see JPA 2.0
* specifications.
*
* @return the list configure persistence unit meta data.
*/
private Map<String, PersistenceUnitMetadata> findPersistenceMetadatas() throws InvalidConfigurationException
{
Enumeration<URL> xmls = null;
try
{
xmls = Thread.currentThread().getContextClassLoader().getResources("META-INF/persistence.xml");
}
catch (IOException ioex)
{
log.warn("Error while loading persistence.xml Caused by:" + ioex.getMessage());
}
if (xmls == null || !xmls.hasMoreElements())
{
log.info("Could not find any META-INF/persistence.xml " + " file in the classpath");
throw new InvalidConfigurationException("Could not find any META-INF/persistence.xml "
+ " file in the classpath");
}
Set<String> persistenceUnitNames = new HashSet<String>();
Map<String, PersistenceUnitMetadata> persistenceUnitMap = new HashMap<String, PersistenceUnitMetadata>();
while (xmls.hasMoreElements())
{
URL url = xmls.nextElement();
log.trace("Analysing persistence.xml: " + url);
List<PersistenceUnitMetadata> metadataFiles = PersistenceXMLLoader.findPersistenceUnits(url,
PersistenceUnitTransactionType.RESOURCE_LOCAL);
// Pick only those that have Kundera Provider
for (PersistenceUnitMetadata metadata : metadataFiles)
{
// check for unique names
if (persistenceUnitNames.contains(metadata.getPersistenceUnitName()))
{
- throw new InvalidConfigurationException("Duplicate persistence-units for name: "
+ log.warn("Duplicate persistence-units for name: "
+ metadata.getPersistenceUnitName() + ". verify your persistence.xml file");
}
// check for provider
if (metadata.getPersistenceProviderClassName() == null
|| PROVIDER_IMPLEMENTATION_NAME.equalsIgnoreCase(metadata.getPersistenceProviderClassName()))
{
persistenceUnitMap.put(metadata.getPersistenceUnitName(), metadata);
}
// add to check for duplicate persistence unit.
persistenceUnitNames.add(metadata.getPersistenceUnitName());
}
}
return persistenceUnitMap;
}
}
| true | true | private Map<String, PersistenceUnitMetadata> findPersistenceMetadatas() throws InvalidConfigurationException
{
Enumeration<URL> xmls = null;
try
{
xmls = Thread.currentThread().getContextClassLoader().getResources("META-INF/persistence.xml");
}
catch (IOException ioex)
{
log.warn("Error while loading persistence.xml Caused by:" + ioex.getMessage());
}
if (xmls == null || !xmls.hasMoreElements())
{
log.info("Could not find any META-INF/persistence.xml " + " file in the classpath");
throw new InvalidConfigurationException("Could not find any META-INF/persistence.xml "
+ " file in the classpath");
}
Set<String> persistenceUnitNames = new HashSet<String>();
Map<String, PersistenceUnitMetadata> persistenceUnitMap = new HashMap<String, PersistenceUnitMetadata>();
while (xmls.hasMoreElements())
{
URL url = xmls.nextElement();
log.trace("Analysing persistence.xml: " + url);
List<PersistenceUnitMetadata> metadataFiles = PersistenceXMLLoader.findPersistenceUnits(url,
PersistenceUnitTransactionType.RESOURCE_LOCAL);
// Pick only those that have Kundera Provider
for (PersistenceUnitMetadata metadata : metadataFiles)
{
// check for unique names
if (persistenceUnitNames.contains(metadata.getPersistenceUnitName()))
{
throw new InvalidConfigurationException("Duplicate persistence-units for name: "
+ metadata.getPersistenceUnitName() + ". verify your persistence.xml file");
}
// check for provider
if (metadata.getPersistenceProviderClassName() == null
|| PROVIDER_IMPLEMENTATION_NAME.equalsIgnoreCase(metadata.getPersistenceProviderClassName()))
{
persistenceUnitMap.put(metadata.getPersistenceUnitName(), metadata);
}
// add to check for duplicate persistence unit.
persistenceUnitNames.add(metadata.getPersistenceUnitName());
}
}
return persistenceUnitMap;
}
| private Map<String, PersistenceUnitMetadata> findPersistenceMetadatas() throws InvalidConfigurationException
{
Enumeration<URL> xmls = null;
try
{
xmls = Thread.currentThread().getContextClassLoader().getResources("META-INF/persistence.xml");
}
catch (IOException ioex)
{
log.warn("Error while loading persistence.xml Caused by:" + ioex.getMessage());
}
if (xmls == null || !xmls.hasMoreElements())
{
log.info("Could not find any META-INF/persistence.xml " + " file in the classpath");
throw new InvalidConfigurationException("Could not find any META-INF/persistence.xml "
+ " file in the classpath");
}
Set<String> persistenceUnitNames = new HashSet<String>();
Map<String, PersistenceUnitMetadata> persistenceUnitMap = new HashMap<String, PersistenceUnitMetadata>();
while (xmls.hasMoreElements())
{
URL url = xmls.nextElement();
log.trace("Analysing persistence.xml: " + url);
List<PersistenceUnitMetadata> metadataFiles = PersistenceXMLLoader.findPersistenceUnits(url,
PersistenceUnitTransactionType.RESOURCE_LOCAL);
// Pick only those that have Kundera Provider
for (PersistenceUnitMetadata metadata : metadataFiles)
{
// check for unique names
if (persistenceUnitNames.contains(metadata.getPersistenceUnitName()))
{
log.warn("Duplicate persistence-units for name: "
+ metadata.getPersistenceUnitName() + ". verify your persistence.xml file");
}
// check for provider
if (metadata.getPersistenceProviderClassName() == null
|| PROVIDER_IMPLEMENTATION_NAME.equalsIgnoreCase(metadata.getPersistenceProviderClassName()))
{
persistenceUnitMap.put(metadata.getPersistenceUnitName(), metadata);
}
// add to check for duplicate persistence unit.
persistenceUnitNames.add(metadata.getPersistenceUnitName());
}
}
return persistenceUnitMap;
}
|
diff --git a/src/com/dynamobi/ws/util/DBDao.java b/src/com/dynamobi/ws/util/DBDao.java
index e451bf3..4a4a0b6 100644
--- a/src/com/dynamobi/ws/util/DBDao.java
+++ b/src/com/dynamobi/ws/util/DBDao.java
@@ -1,84 +1,85 @@
/*
Dynamo Web Services is a web service project for administering LucidDB
Copyright (C) 2010 Dynamo Business Intelligence Corporation
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 approved by Dynamo Business Intelligence Corporation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.dynamobi.ws.util;
import java.sql.SQLException;
import javax.sql.DataSource;
import java.lang.ClassNotFoundException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.io.InputStream;
import java.io.IOException;
// Base class
import org.springframework.security.userdetails.jdbc.JdbcDaoImpl;
// Factory class to construct our pooled datasource
import com.mchange.v2.c3p0.DataSources;
import com.dynamobi.ws.util.DBAccess;
import com.dynamobi.ws.util.DB;
public class DBDao extends JdbcDaoImpl {
private DataSource ds_pooled = null;
public DBDao() throws ClassNotFoundException, SQLException, IOException {
super();
Properties pro = new Properties();
InputStream user_props = this.getClass().getResourceAsStream("/luciddb-jdbc.properties");
if (user_props != null) {
pro.load(user_props);
} else {
pro.load(this.getClass().getResourceAsStream("/luciddb-jdbc-default.properties"));
}
Class.forName(pro.getProperty("jdbc.driver"));
String username = pro.getProperty("jdbc.username");
String password = pro.getProperty("jdbc.password");
String url = pro.getProperty("jdbc.url");
DataSource ds_unpooled = DataSources.unpooledDataSource(
url,
username,
password);
Map<String,String> overrides = new HashMap<String,String>();
- //causes problems when DB server is not running
- //overrides.put("minPoolSize", "3");
+ overrides.put("minPoolSize", "3");
overrides.put("maxIdleTimeExcessConnections", "600");
- overrides.put("breakAfterAcquireFailure", "true");
- overrides.put("acquireRetryAttempts", "15");
+ // breaking marks the datasource as broken if we tried to acquire
+ // a connection before LucidDB started, so make sure this is false.
+ overrides.put("breakAfterAcquireFailure", "false");
+ overrides.put("acquireRetryAttempts", "5");
ds_pooled = DataSources.pooledDataSource(ds_unpooled, overrides);
setDataSource(ds_pooled);
DBAccess.connDataSource = ds_pooled;
DB.connDataSource = ds_pooled;
}
public void cleanup() throws SQLException {
DataSources.destroy(ds_pooled);
}
}
| false | true | public DBDao() throws ClassNotFoundException, SQLException, IOException {
super();
Properties pro = new Properties();
InputStream user_props = this.getClass().getResourceAsStream("/luciddb-jdbc.properties");
if (user_props != null) {
pro.load(user_props);
} else {
pro.load(this.getClass().getResourceAsStream("/luciddb-jdbc-default.properties"));
}
Class.forName(pro.getProperty("jdbc.driver"));
String username = pro.getProperty("jdbc.username");
String password = pro.getProperty("jdbc.password");
String url = pro.getProperty("jdbc.url");
DataSource ds_unpooled = DataSources.unpooledDataSource(
url,
username,
password);
Map<String,String> overrides = new HashMap<String,String>();
//causes problems when DB server is not running
//overrides.put("minPoolSize", "3");
overrides.put("maxIdleTimeExcessConnections", "600");
overrides.put("breakAfterAcquireFailure", "true");
overrides.put("acquireRetryAttempts", "15");
ds_pooled = DataSources.pooledDataSource(ds_unpooled, overrides);
setDataSource(ds_pooled);
DBAccess.connDataSource = ds_pooled;
DB.connDataSource = ds_pooled;
}
| public DBDao() throws ClassNotFoundException, SQLException, IOException {
super();
Properties pro = new Properties();
InputStream user_props = this.getClass().getResourceAsStream("/luciddb-jdbc.properties");
if (user_props != null) {
pro.load(user_props);
} else {
pro.load(this.getClass().getResourceAsStream("/luciddb-jdbc-default.properties"));
}
Class.forName(pro.getProperty("jdbc.driver"));
String username = pro.getProperty("jdbc.username");
String password = pro.getProperty("jdbc.password");
String url = pro.getProperty("jdbc.url");
DataSource ds_unpooled = DataSources.unpooledDataSource(
url,
username,
password);
Map<String,String> overrides = new HashMap<String,String>();
overrides.put("minPoolSize", "3");
overrides.put("maxIdleTimeExcessConnections", "600");
// breaking marks the datasource as broken if we tried to acquire
// a connection before LucidDB started, so make sure this is false.
overrides.put("breakAfterAcquireFailure", "false");
overrides.put("acquireRetryAttempts", "5");
ds_pooled = DataSources.pooledDataSource(ds_unpooled, overrides);
setDataSource(ds_pooled);
DBAccess.connDataSource = ds_pooled;
DB.connDataSource = ds_pooled;
}
|
diff --git a/src/main/java/uk/ac/ic/doc/campusProject/web/servlet/PlacesApi.java b/src/main/java/uk/ac/ic/doc/campusProject/web/servlet/PlacesApi.java
index eca7e24..da75855 100644
--- a/src/main/java/uk/ac/ic/doc/campusProject/web/servlet/PlacesApi.java
+++ b/src/main/java/uk/ac/ic/doc/campusProject/web/servlet/PlacesApi.java
@@ -1,160 +1,154 @@
package uk.ac.ic.doc.campusProject.web.servlet;
import java.io.IOException;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;
import uk.ac.ic.doc.campusProject.utils.db.DatabaseConnectionManager;
public class PlacesApi extends HttpServlet {
private static final long serialVersionUID = 1L;
Logger log = Logger.getLogger(PlacesApi.class);
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
Connection conn = DatabaseConnectionManager.getConnection("live");
PreparedStatement stmt;
String verbose = request.getParameter("verbose");
String building = request.getParameter("building");
String floor = request.getParameter("floor");
String room = request.getParameter("room");
String left = request.getParameter("left");
String right = request.getParameter("right");
String top = request.getParameter("top");
String bottom = request.getParameter("bottom");
try {
if (verbose.equals("F")) {
if (left == null || right == null || top == null || bottom == null) {
stmt = conn.prepareStatement("SELECT Number, Xpixel, Ypixel FROM Room LEFT JOIN Floor_Contains ON Number=Room AND Room.Building=Floor_Contains.Building LEFT JOIN Building ON Floor_Contains.Building=Building.Name WHERE Building.ShortCode=? AND Floor=?");
stmt.setString(1, building);
stmt.setString(2, floor);
if (stmt.execute()) {
ResultSet rs = stmt.getResultSet();
response.setContentType("application/json");
ServletOutputStream os = response.getOutputStream();
StringBuilder jsonArray = new StringBuilder();
jsonArray.append("[");
while(rs.next()) {
JSONObject jsonObject = new JSONObject();
String number = rs.getString("Number");
jsonObject.put("room", number);
jsonObject.put("x", rs.getInt("Xpixel"));
jsonObject.put("y", rs.getInt("Ypixel"));
jsonArray.append(jsonObject.toString());
jsonArray.append(",");
}
jsonArray = jsonArray.replace(jsonArray.length() - 1, jsonArray.length(), "");
jsonArray.append("]");
os.write(jsonArray.toString().getBytes());
response.setStatus(HttpServletResponse.SC_OK);
os.flush();
}
conn.close();
}
else {
}
}
else if (verbose.equals("T")) {
if ((left == null || right == null || top == null || bottom == null) && room != null) {
stmt = conn.prepareStatement("SELECT Number, Type, Description, Image FROM Room LEFT JOIN Floor_Contains ON Room.Number=Floor_Contains.Room AND Room.Building=Floor_Contains.Building LEFT JOIN Building ON Floor_Contains.Building=Building.Name WHERE Building.ShortCode=? AND Floor=?" +
" AND Room.Number= ?");
stmt.setString(1, building);
stmt.setString(2, floor);
stmt.setString(3, room);
log.info(building + "," + floor + "," + room);
if (stmt.execute()) {
ResultSet rs = stmt.getResultSet();
response.setContentType("application/json");
ServletOutputStream os = response.getOutputStream();
- StringBuilder jsonArray = new StringBuilder();
- jsonArray.append("[");
+ JSONObject jsonObject = new JSONObject();
while(rs.next()) {
- JSONObject jsonObject = new JSONObject();
String number = rs.getString("Number");
jsonObject.put("number", number);
jsonObject.put("type", rs.getString("Type"));
jsonObject.put("description", rs.getString("Description"));
Blob blob = rs.getBlob("Image");
if (blob == null) {
jsonObject.put("image", new byte[]{});
}
else {
jsonObject.put("image", blob.getBytes(1, (int)blob.length()));
}
- jsonArray.append(jsonObject.toString());
- jsonArray.append(",");
}
- jsonArray = jsonArray.replace(jsonArray.length() - 1, jsonArray.length(), "");
- jsonArray.append("]");
- os.write(jsonArray.toString().getBytes());
+ os.write(jsonObject.toString().getBytes());
response.setStatus(HttpServletResponse.SC_OK);
os.flush();
}
conn.close();
}
else if (room == null){
stmt = conn.prepareStatement("SELECT Number, Type, Description, Image FROM Room LEFT JOIN Floor_Contains ON Number=Room AND Room.Building=Floor_Contains.Building LEFT JOIN Building ON Floor_Contains.Building=Building.Name WHERE Building.ShortCode=? AND Floor=?" +
" AND Xpixel <= ? AND Xpixel >= ? AND Ypixel <= ? AND Ypixel >= ?");
stmt.setString(1, building);
stmt.setString(2, floor);
stmt.setString(3, right);
stmt.setString(4, left);
stmt.setString(5, bottom);
stmt.setString(6, top);
if (stmt.execute()) {
ResultSet rs = stmt.getResultSet();
response.setContentType("application/json");
ServletOutputStream os = response.getOutputStream();
StringBuilder jsonArray = new StringBuilder();
jsonArray.append("[");
while(rs.next()) {
JSONObject jsonObject = new JSONObject();
String number = rs.getString("Number");
jsonObject.put("number", number);
jsonObject.put("type", rs.getString("Type"));
jsonObject.put("description", rs.getString("Description"));
Blob blob = rs.getBlob("Image");
if (blob == null) {
jsonObject.put("image", new byte[]{});
}
else {
jsonObject.put("image", blob.getBytes(1, (int)blob.length()));
}
jsonArray.append(jsonObject.toString());
jsonArray.append(",");
}
jsonArray = jsonArray.replace(jsonArray.length() - 1, jsonArray.length(), "");
jsonArray.append("]");
os.write(jsonArray.toString().getBytes());
response.setStatus(HttpServletResponse.SC_OK);
os.flush();
}
conn.close();
}
}
} catch (SQLException | IOException | JSONException e) {
e.printStackTrace();
}
}
}
| false | true | protected void doGet(HttpServletRequest request, HttpServletResponse response) {
Connection conn = DatabaseConnectionManager.getConnection("live");
PreparedStatement stmt;
String verbose = request.getParameter("verbose");
String building = request.getParameter("building");
String floor = request.getParameter("floor");
String room = request.getParameter("room");
String left = request.getParameter("left");
String right = request.getParameter("right");
String top = request.getParameter("top");
String bottom = request.getParameter("bottom");
try {
if (verbose.equals("F")) {
if (left == null || right == null || top == null || bottom == null) {
stmt = conn.prepareStatement("SELECT Number, Xpixel, Ypixel FROM Room LEFT JOIN Floor_Contains ON Number=Room AND Room.Building=Floor_Contains.Building LEFT JOIN Building ON Floor_Contains.Building=Building.Name WHERE Building.ShortCode=? AND Floor=?");
stmt.setString(1, building);
stmt.setString(2, floor);
if (stmt.execute()) {
ResultSet rs = stmt.getResultSet();
response.setContentType("application/json");
ServletOutputStream os = response.getOutputStream();
StringBuilder jsonArray = new StringBuilder();
jsonArray.append("[");
while(rs.next()) {
JSONObject jsonObject = new JSONObject();
String number = rs.getString("Number");
jsonObject.put("room", number);
jsonObject.put("x", rs.getInt("Xpixel"));
jsonObject.put("y", rs.getInt("Ypixel"));
jsonArray.append(jsonObject.toString());
jsonArray.append(",");
}
jsonArray = jsonArray.replace(jsonArray.length() - 1, jsonArray.length(), "");
jsonArray.append("]");
os.write(jsonArray.toString().getBytes());
response.setStatus(HttpServletResponse.SC_OK);
os.flush();
}
conn.close();
}
else {
}
}
else if (verbose.equals("T")) {
if ((left == null || right == null || top == null || bottom == null) && room != null) {
stmt = conn.prepareStatement("SELECT Number, Type, Description, Image FROM Room LEFT JOIN Floor_Contains ON Room.Number=Floor_Contains.Room AND Room.Building=Floor_Contains.Building LEFT JOIN Building ON Floor_Contains.Building=Building.Name WHERE Building.ShortCode=? AND Floor=?" +
" AND Room.Number= ?");
stmt.setString(1, building);
stmt.setString(2, floor);
stmt.setString(3, room);
log.info(building + "," + floor + "," + room);
if (stmt.execute()) {
ResultSet rs = stmt.getResultSet();
response.setContentType("application/json");
ServletOutputStream os = response.getOutputStream();
StringBuilder jsonArray = new StringBuilder();
jsonArray.append("[");
while(rs.next()) {
JSONObject jsonObject = new JSONObject();
String number = rs.getString("Number");
jsonObject.put("number", number);
jsonObject.put("type", rs.getString("Type"));
jsonObject.put("description", rs.getString("Description"));
Blob blob = rs.getBlob("Image");
if (blob == null) {
jsonObject.put("image", new byte[]{});
}
else {
jsonObject.put("image", blob.getBytes(1, (int)blob.length()));
}
jsonArray.append(jsonObject.toString());
jsonArray.append(",");
}
jsonArray = jsonArray.replace(jsonArray.length() - 1, jsonArray.length(), "");
jsonArray.append("]");
os.write(jsonArray.toString().getBytes());
response.setStatus(HttpServletResponse.SC_OK);
os.flush();
}
conn.close();
}
else if (room == null){
stmt = conn.prepareStatement("SELECT Number, Type, Description, Image FROM Room LEFT JOIN Floor_Contains ON Number=Room AND Room.Building=Floor_Contains.Building LEFT JOIN Building ON Floor_Contains.Building=Building.Name WHERE Building.ShortCode=? AND Floor=?" +
" AND Xpixel <= ? AND Xpixel >= ? AND Ypixel <= ? AND Ypixel >= ?");
stmt.setString(1, building);
stmt.setString(2, floor);
stmt.setString(3, right);
stmt.setString(4, left);
stmt.setString(5, bottom);
stmt.setString(6, top);
if (stmt.execute()) {
ResultSet rs = stmt.getResultSet();
response.setContentType("application/json");
ServletOutputStream os = response.getOutputStream();
StringBuilder jsonArray = new StringBuilder();
jsonArray.append("[");
while(rs.next()) {
JSONObject jsonObject = new JSONObject();
String number = rs.getString("Number");
jsonObject.put("number", number);
jsonObject.put("type", rs.getString("Type"));
jsonObject.put("description", rs.getString("Description"));
Blob blob = rs.getBlob("Image");
if (blob == null) {
jsonObject.put("image", new byte[]{});
}
else {
jsonObject.put("image", blob.getBytes(1, (int)blob.length()));
}
jsonArray.append(jsonObject.toString());
jsonArray.append(",");
}
jsonArray = jsonArray.replace(jsonArray.length() - 1, jsonArray.length(), "");
jsonArray.append("]");
os.write(jsonArray.toString().getBytes());
response.setStatus(HttpServletResponse.SC_OK);
os.flush();
}
conn.close();
}
}
} catch (SQLException | IOException | JSONException e) {
e.printStackTrace();
}
}
| protected void doGet(HttpServletRequest request, HttpServletResponse response) {
Connection conn = DatabaseConnectionManager.getConnection("live");
PreparedStatement stmt;
String verbose = request.getParameter("verbose");
String building = request.getParameter("building");
String floor = request.getParameter("floor");
String room = request.getParameter("room");
String left = request.getParameter("left");
String right = request.getParameter("right");
String top = request.getParameter("top");
String bottom = request.getParameter("bottom");
try {
if (verbose.equals("F")) {
if (left == null || right == null || top == null || bottom == null) {
stmt = conn.prepareStatement("SELECT Number, Xpixel, Ypixel FROM Room LEFT JOIN Floor_Contains ON Number=Room AND Room.Building=Floor_Contains.Building LEFT JOIN Building ON Floor_Contains.Building=Building.Name WHERE Building.ShortCode=? AND Floor=?");
stmt.setString(1, building);
stmt.setString(2, floor);
if (stmt.execute()) {
ResultSet rs = stmt.getResultSet();
response.setContentType("application/json");
ServletOutputStream os = response.getOutputStream();
StringBuilder jsonArray = new StringBuilder();
jsonArray.append("[");
while(rs.next()) {
JSONObject jsonObject = new JSONObject();
String number = rs.getString("Number");
jsonObject.put("room", number);
jsonObject.put("x", rs.getInt("Xpixel"));
jsonObject.put("y", rs.getInt("Ypixel"));
jsonArray.append(jsonObject.toString());
jsonArray.append(",");
}
jsonArray = jsonArray.replace(jsonArray.length() - 1, jsonArray.length(), "");
jsonArray.append("]");
os.write(jsonArray.toString().getBytes());
response.setStatus(HttpServletResponse.SC_OK);
os.flush();
}
conn.close();
}
else {
}
}
else if (verbose.equals("T")) {
if ((left == null || right == null || top == null || bottom == null) && room != null) {
stmt = conn.prepareStatement("SELECT Number, Type, Description, Image FROM Room LEFT JOIN Floor_Contains ON Room.Number=Floor_Contains.Room AND Room.Building=Floor_Contains.Building LEFT JOIN Building ON Floor_Contains.Building=Building.Name WHERE Building.ShortCode=? AND Floor=?" +
" AND Room.Number= ?");
stmt.setString(1, building);
stmt.setString(2, floor);
stmt.setString(3, room);
log.info(building + "," + floor + "," + room);
if (stmt.execute()) {
ResultSet rs = stmt.getResultSet();
response.setContentType("application/json");
ServletOutputStream os = response.getOutputStream();
JSONObject jsonObject = new JSONObject();
while(rs.next()) {
String number = rs.getString("Number");
jsonObject.put("number", number);
jsonObject.put("type", rs.getString("Type"));
jsonObject.put("description", rs.getString("Description"));
Blob blob = rs.getBlob("Image");
if (blob == null) {
jsonObject.put("image", new byte[]{});
}
else {
jsonObject.put("image", blob.getBytes(1, (int)blob.length()));
}
}
os.write(jsonObject.toString().getBytes());
response.setStatus(HttpServletResponse.SC_OK);
os.flush();
}
conn.close();
}
else if (room == null){
stmt = conn.prepareStatement("SELECT Number, Type, Description, Image FROM Room LEFT JOIN Floor_Contains ON Number=Room AND Room.Building=Floor_Contains.Building LEFT JOIN Building ON Floor_Contains.Building=Building.Name WHERE Building.ShortCode=? AND Floor=?" +
" AND Xpixel <= ? AND Xpixel >= ? AND Ypixel <= ? AND Ypixel >= ?");
stmt.setString(1, building);
stmt.setString(2, floor);
stmt.setString(3, right);
stmt.setString(4, left);
stmt.setString(5, bottom);
stmt.setString(6, top);
if (stmt.execute()) {
ResultSet rs = stmt.getResultSet();
response.setContentType("application/json");
ServletOutputStream os = response.getOutputStream();
StringBuilder jsonArray = new StringBuilder();
jsonArray.append("[");
while(rs.next()) {
JSONObject jsonObject = new JSONObject();
String number = rs.getString("Number");
jsonObject.put("number", number);
jsonObject.put("type", rs.getString("Type"));
jsonObject.put("description", rs.getString("Description"));
Blob blob = rs.getBlob("Image");
if (blob == null) {
jsonObject.put("image", new byte[]{});
}
else {
jsonObject.put("image", blob.getBytes(1, (int)blob.length()));
}
jsonArray.append(jsonObject.toString());
jsonArray.append(",");
}
jsonArray = jsonArray.replace(jsonArray.length() - 1, jsonArray.length(), "");
jsonArray.append("]");
os.write(jsonArray.toString().getBytes());
response.setStatus(HttpServletResponse.SC_OK);
os.flush();
}
conn.close();
}
}
} catch (SQLException | IOException | JSONException e) {
e.printStackTrace();
}
}
|
diff --git a/wiki-service/src/main/java/org/exoplatform/wiki/service/impl/SessionDestroyedListener.java b/wiki-service/src/main/java/org/exoplatform/wiki/service/impl/SessionDestroyedListener.java
index fcbbd774..e8b9586e 100644
--- a/wiki-service/src/main/java/org/exoplatform/wiki/service/impl/SessionDestroyedListener.java
+++ b/wiki-service/src/main/java/org/exoplatform/wiki/service/impl/SessionDestroyedListener.java
@@ -1,58 +1,57 @@
/*
* Copyright (C) 2003-2010 eXo Platform SAS.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU 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 org.exoplatform.wiki.service.impl;
import javax.servlet.http.HttpSessionEvent;
import org.exoplatform.container.PortalContainer;
import org.exoplatform.container.component.RequestLifeCycle;
import org.exoplatform.services.listener.Event;
import org.exoplatform.services.listener.Listener;
import org.exoplatform.services.log.ExoLogger;
import org.exoplatform.services.log.Log;
import org.exoplatform.services.security.ConversationState;
import org.exoplatform.wiki.service.WikiService;
public class SessionDestroyedListener extends Listener<PortalContainer, HttpSessionEvent> {
private static Log LOG = ExoLogger.getLogger("SessionDestroyedListener");
@Override
public void onEvent(Event<PortalContainer, HttpSessionEvent> event) throws Exception {
PortalContainer container = event.getSource();
String sessionId = event.getData().getSession().getId();
if (LOG.isTraceEnabled()) {
LOG.trace("Removing the key: " + sessionId);
}
try {
SessionManager sessionManager = (SessionManager) container.getComponentInstanceOfType(SessionManager.class);
sessionManager.removeSessionContainer(sessionId);
- sessionManager.removeSessionContainer(ConversationState.getCurrent().getIdentity().getUserId());
} catch (Exception e) {
LOG.warn("Can't remove the key: " + sessionId, e);
}
if (LOG.isTraceEnabled()) {
LOG.trace("Removed the key: " + sessionId);
}
if (container.isStarted()) {
WikiService wikiService = (WikiService) container.getComponentInstanceOfType(WikiService.class);
RequestLifeCycle.begin(PortalContainer.getInstance());
wikiService.deleteDraftNewPage(sessionId);
RequestLifeCycle.end();
}
}
}
| true | true | public void onEvent(Event<PortalContainer, HttpSessionEvent> event) throws Exception {
PortalContainer container = event.getSource();
String sessionId = event.getData().getSession().getId();
if (LOG.isTraceEnabled()) {
LOG.trace("Removing the key: " + sessionId);
}
try {
SessionManager sessionManager = (SessionManager) container.getComponentInstanceOfType(SessionManager.class);
sessionManager.removeSessionContainer(sessionId);
sessionManager.removeSessionContainer(ConversationState.getCurrent().getIdentity().getUserId());
} catch (Exception e) {
LOG.warn("Can't remove the key: " + sessionId, e);
}
if (LOG.isTraceEnabled()) {
LOG.trace("Removed the key: " + sessionId);
}
if (container.isStarted()) {
WikiService wikiService = (WikiService) container.getComponentInstanceOfType(WikiService.class);
RequestLifeCycle.begin(PortalContainer.getInstance());
wikiService.deleteDraftNewPage(sessionId);
RequestLifeCycle.end();
}
}
| public void onEvent(Event<PortalContainer, HttpSessionEvent> event) throws Exception {
PortalContainer container = event.getSource();
String sessionId = event.getData().getSession().getId();
if (LOG.isTraceEnabled()) {
LOG.trace("Removing the key: " + sessionId);
}
try {
SessionManager sessionManager = (SessionManager) container.getComponentInstanceOfType(SessionManager.class);
sessionManager.removeSessionContainer(sessionId);
} catch (Exception e) {
LOG.warn("Can't remove the key: " + sessionId, e);
}
if (LOG.isTraceEnabled()) {
LOG.trace("Removed the key: " + sessionId);
}
if (container.isStarted()) {
WikiService wikiService = (WikiService) container.getComponentInstanceOfType(WikiService.class);
RequestLifeCycle.begin(PortalContainer.getInstance());
wikiService.deleteDraftNewPage(sessionId);
RequestLifeCycle.end();
}
}
|
diff --git a/activemq-core/src/main/java/org/activemq/transport/failover/FailoverTransport.java b/activemq-core/src/main/java/org/activemq/transport/failover/FailoverTransport.java
index 16a8fdb9c..7b0c21dfa 100755
--- a/activemq-core/src/main/java/org/activemq/transport/failover/FailoverTransport.java
+++ b/activemq-core/src/main/java/org/activemq/transport/failover/FailoverTransport.java
@@ -1,399 +1,400 @@
/**
* <a href="http://activemq.org">ActiveMQ: The Open Source Message Fabric</a>
*
* Copyright 2005 (C) LogicBlaze, Inc. http://www.logicblaze.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.activemq.transport.failover;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;
import org.activemq.command.Command;
import org.activemq.command.Response;
import org.activemq.state.ConnectionStateTracker;
import org.activemq.thread.DefaultThreadPools;
import org.activemq.thread.Task;
import org.activemq.thread.TaskRunner;
import org.activemq.transport.CompositeTransport;
import org.activemq.transport.FutureResponse;
import org.activemq.transport.Transport;
import org.activemq.transport.TransportFactory;
import org.activemq.transport.TransportListener;
import org.activemq.util.IOExceptionSupport;
import org.activemq.util.ServiceSupport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.emory.mathcs.backport.java.util.concurrent.ConcurrentHashMap;
import edu.emory.mathcs.backport.java.util.concurrent.CopyOnWriteArrayList;
/**
* A Transport that is made reliable by being able to fail over to another
* transport when a transport failure is detected.
*
* @version $Revision$
*/
public class FailoverTransport implements CompositeTransport {
private static final Log log = LogFactory.getLog(FailoverTransport.class);
private TransportListener transportListener;
private boolean disposed;
private final CopyOnWriteArrayList uris = new CopyOnWriteArrayList();
private final Object reconnectMutex = new Object();
private final ConnectionStateTracker stateTracker = new ConnectionStateTracker();
private final ConcurrentHashMap requestMap = new ConcurrentHashMap();
private URI connectedTransportURI;
private Transport connectedTransport;
private final TaskRunner reconnectTask;
private boolean started;
private long initialReconnectDelay = 10;
private long maxReconnectDelay = 1000 * 30;
private long backOffMultiplier = 2;
private boolean useExponentialBackOff = true;
private int maxReconnectAttempts;
private int connectFailures;
private long reconnectDelay = initialReconnectDelay;
private Exception connectionFailure;
private final TransportListener myTransportListener = new TransportListener() {
public void onCommand(Command command) {
if (command.isResponse()) {
requestMap.remove(new Short(((Response) command).getCorrelationId()));
}
transportListener.onCommand(command);
}
public void onException(IOException error) {
try {
handleTransportFailure(error);
}
catch (InterruptedException e) {
transportListener.onException(new InterruptedIOException());
}
}
};
public FailoverTransport() throws InterruptedIOException {
// Setup a task that is used to reconnect the a connection async.
reconnectTask = DefaultThreadPools.getDefaultTaskRunnerFactory().createTaskRunner(new Task() {
public boolean iterate() {
Exception failure=null;
synchronized (reconnectMutex) {
if (disposed || connectionFailure!=null) {
reconnectMutex.notifyAll();
}
if (connectedTransport != null || disposed || connectionFailure!=null) {
return false;
} else {
ArrayList connectList = getConnectList();
if( connectList.isEmpty() ) {
failure = new IOException("No uris available to connect to.");
} else {
+ reconnectDelay = initialReconnectDelay;
Iterator iter = connectList.iterator();
for (int i = 0; iter.hasNext() && connectedTransport == null && !disposed; i++) {
URI uri = (URI) iter.next();
try {
log.debug("Attempting connect to: " + uri);
Transport t = TransportFactory.compositeConnect(uri);
t.setTransportListener(myTransportListener);
if (started) {
restoreTransport(t);
}
log.debug("Connection established");
- reconnectDelay = 10;
+ reconnectDelay = initialReconnectDelay;
connectedTransportURI = uri;
connectedTransport = t;
reconnectMutex.notifyAll();
connectFailures = 0;
return false;
}
catch (Exception e) {
failure = e;
log.debug("Connect fail to: " + uri + ", reason: " + e);
}
}
}
}
if (maxReconnectAttempts > 0 && ++connectFailures >= maxReconnectAttempts) {
log.error("Failed to connect to transport after: " + connectFailures + " attempt(s)");
connectionFailure = failure;
reconnectMutex.notifyAll();
return false;
}
}
try {
log.debug("Waiting " + reconnectDelay + " ms before attempting connection. ");
Thread.sleep(reconnectDelay);
}
catch (InterruptedException e1) {
Thread.currentThread().interrupt();
}
if (useExponentialBackOff) {
// Exponential increment of reconnect delay.
reconnectDelay *= backOffMultiplier;
if (reconnectDelay > maxReconnectDelay)
reconnectDelay = maxReconnectDelay;
}
return true;
}
});
}
private void handleTransportFailure(IOException e) throws InterruptedException {
synchronized (reconnectMutex) {
log.debug("Transport failed, starting up reconnect task", e);
if (connectedTransport != null) {
ServiceSupport.dispose(connectedTransport);
connectedTransport = null;
connectedTransportURI = null;
reconnectTask.wakeup();
}
}
}
public void start() throws Exception {
synchronized (reconnectMutex) {
log.debug("Started.");
if (started)
return;
started = true;
if (connectedTransport != null) {
connectedTransport.start();
stateTracker.restore(connectedTransport);
}
}
}
public void stop() throws Exception {
synchronized (reconnectMutex) {
log.debug("Stopped.");
if (!started)
return;
started = false;
disposed = true;
if (connectedTransport != null) {
connectedTransport.stop();
}
}
}
public long getInitialReconnectDelay() {
return initialReconnectDelay;
}
public void setInitialReconnectDelay(long initialReconnectDelay) {
this.initialReconnectDelay = initialReconnectDelay;
}
public long getMaxReconnectDelay() {
return maxReconnectDelay;
}
public void setMaxReconnectDelay(long maxReconnectDelay) {
this.maxReconnectDelay = maxReconnectDelay;
}
public long getReconnectDelay() {
return reconnectDelay;
}
public void setReconnectDelay(long reconnectDelay) {
this.reconnectDelay = reconnectDelay;
}
public long getReconnectDelayExponent() {
return backOffMultiplier;
}
public void setReconnectDelayExponent(long reconnectDelayExponent) {
this.backOffMultiplier = reconnectDelayExponent;
}
public Transport getConnectedTransport() {
return connectedTransport;
}
public URI getConnectedTransportURI() {
return connectedTransportURI;
}
public int getMaxReconnectAttempts() {
return maxReconnectAttempts;
}
public void setMaxReconnectAttempts(int maxReconnectAttempts) {
this.maxReconnectAttempts = maxReconnectAttempts;
}
public void oneway(Command command) throws IOException {
Exception error = null;
try {
synchronized (reconnectMutex) {
// Keep trying until the message is sent.
for (int i = 0;; i++) {
try {
// Wait for transport to be connected.
while (connectedTransport == null && !disposed && connectionFailure==null ) {
log.debug("Waiting for transport to reconnect.");
reconnectMutex.wait(1000);
}
if( connectedTransport==null ) {
// Previous loop may have exited due to use being
// disposed.
if (disposed) {
error = new IOException("Transport disposed.");
} else if (connectionFailure!=null) {
error = connectionFailure;
} else {
error = new IOException("Unexpected failure.");
}
break;
}
// Send the message.
connectedTransport.oneway(command);
// If it was a request and it was not being tracked by
// the state tracker,
// then hold it in the requestMap so that we can replay
// it later.
if (!stateTracker.track(command) && command.isResponseRequired()) {
requestMap.put(new Short(command.getCommandId()), command);
}
return;
}
catch (IOException e) {
log.debug("Send oneway attempt: " + i + " failed.");
handleTransportFailure(e);
}
}
}
}
catch (InterruptedException e) {
// Some one may be trying to stop our thread.
throw new InterruptedIOException();
}
if( error instanceof IOException )
throw (IOException)error;
throw IOExceptionSupport.create(error);
}
public FutureResponse asyncRequest(Command command) throws IOException {
throw new AssertionError("Unsupported Method");
}
public Response request(Command command) throws IOException {
throw new AssertionError("Unsupported Method");
}
public void add(URI u[]) {
for (int i = 0; i < u.length; i++) {
if( !uris.contains(u[i]) )
uris.add(u[i]);
}
reconnect();
}
public void remove(URI u[]) {
for (int i = 0; i < u.length; i++) {
uris.remove(u[i]);
}
reconnect();
}
public void reconnect() {
log.debug("Waking up reconnect task");
try {
reconnectTask.wakeup();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
private ArrayList getConnectList() {
ArrayList l = new ArrayList(uris);
// Randomly, reorder the list by random swapping
Random r = new Random();
r.setSeed(System.currentTimeMillis());
for (int i = 0; i < l.size(); i++) {
int p = r.nextInt(l.size());
Object t = l.get(p);
l.set(p, l.get(i));
l.set(i, t);
}
return l;
}
public void setTransportListener(TransportListener commandListener) {
this.transportListener = commandListener;
}
public Object narrow(Class target) {
if (target.isAssignableFrom(getClass())) {
return this;
}
synchronized (reconnectMutex) {
if (connectedTransport != null) {
return connectedTransport.narrow(target);
}
}
return null;
}
protected void restoreTransport(Transport t) throws Exception, IOException {
t.start();
stateTracker.restore(t);
for (Iterator iter2 = requestMap.values().iterator(); iter2.hasNext();) {
Command command = (Command) iter2.next();
t.oneway(command);
}
}
public boolean isUseExponentialBackOff() {
return useExponentialBackOff;
}
public void setUseExponentialBackOff(boolean useExponentialBackOff) {
this.useExponentialBackOff = useExponentialBackOff;
}
}
| false | true | public FailoverTransport() throws InterruptedIOException {
// Setup a task that is used to reconnect the a connection async.
reconnectTask = DefaultThreadPools.getDefaultTaskRunnerFactory().createTaskRunner(new Task() {
public boolean iterate() {
Exception failure=null;
synchronized (reconnectMutex) {
if (disposed || connectionFailure!=null) {
reconnectMutex.notifyAll();
}
if (connectedTransport != null || disposed || connectionFailure!=null) {
return false;
} else {
ArrayList connectList = getConnectList();
if( connectList.isEmpty() ) {
failure = new IOException("No uris available to connect to.");
} else {
Iterator iter = connectList.iterator();
for (int i = 0; iter.hasNext() && connectedTransport == null && !disposed; i++) {
URI uri = (URI) iter.next();
try {
log.debug("Attempting connect to: " + uri);
Transport t = TransportFactory.compositeConnect(uri);
t.setTransportListener(myTransportListener);
if (started) {
restoreTransport(t);
}
log.debug("Connection established");
reconnectDelay = 10;
connectedTransportURI = uri;
connectedTransport = t;
reconnectMutex.notifyAll();
connectFailures = 0;
return false;
}
catch (Exception e) {
failure = e;
log.debug("Connect fail to: " + uri + ", reason: " + e);
}
}
}
}
if (maxReconnectAttempts > 0 && ++connectFailures >= maxReconnectAttempts) {
log.error("Failed to connect to transport after: " + connectFailures + " attempt(s)");
connectionFailure = failure;
reconnectMutex.notifyAll();
return false;
}
}
try {
log.debug("Waiting " + reconnectDelay + " ms before attempting connection. ");
Thread.sleep(reconnectDelay);
}
catch (InterruptedException e1) {
Thread.currentThread().interrupt();
}
if (useExponentialBackOff) {
// Exponential increment of reconnect delay.
reconnectDelay *= backOffMultiplier;
if (reconnectDelay > maxReconnectDelay)
reconnectDelay = maxReconnectDelay;
}
return true;
}
});
}
| public FailoverTransport() throws InterruptedIOException {
// Setup a task that is used to reconnect the a connection async.
reconnectTask = DefaultThreadPools.getDefaultTaskRunnerFactory().createTaskRunner(new Task() {
public boolean iterate() {
Exception failure=null;
synchronized (reconnectMutex) {
if (disposed || connectionFailure!=null) {
reconnectMutex.notifyAll();
}
if (connectedTransport != null || disposed || connectionFailure!=null) {
return false;
} else {
ArrayList connectList = getConnectList();
if( connectList.isEmpty() ) {
failure = new IOException("No uris available to connect to.");
} else {
reconnectDelay = initialReconnectDelay;
Iterator iter = connectList.iterator();
for (int i = 0; iter.hasNext() && connectedTransport == null && !disposed; i++) {
URI uri = (URI) iter.next();
try {
log.debug("Attempting connect to: " + uri);
Transport t = TransportFactory.compositeConnect(uri);
t.setTransportListener(myTransportListener);
if (started) {
restoreTransport(t);
}
log.debug("Connection established");
reconnectDelay = initialReconnectDelay;
connectedTransportURI = uri;
connectedTransport = t;
reconnectMutex.notifyAll();
connectFailures = 0;
return false;
}
catch (Exception e) {
failure = e;
log.debug("Connect fail to: " + uri + ", reason: " + e);
}
}
}
}
if (maxReconnectAttempts > 0 && ++connectFailures >= maxReconnectAttempts) {
log.error("Failed to connect to transport after: " + connectFailures + " attempt(s)");
connectionFailure = failure;
reconnectMutex.notifyAll();
return false;
}
}
try {
log.debug("Waiting " + reconnectDelay + " ms before attempting connection. ");
Thread.sleep(reconnectDelay);
}
catch (InterruptedException e1) {
Thread.currentThread().interrupt();
}
if (useExponentialBackOff) {
// Exponential increment of reconnect delay.
reconnectDelay *= backOffMultiplier;
if (reconnectDelay > maxReconnectDelay)
reconnectDelay = maxReconnectDelay;
}
return true;
}
});
}
|
diff --git a/src/mecard/customer/BImportFormatter.java b/src/mecard/customer/BImportFormatter.java
index 74e9539..db1c9c6 100644
--- a/src/mecard/customer/BImportFormatter.java
+++ b/src/mecard/customer/BImportFormatter.java
@@ -1,233 +1,233 @@
/*
* Metro allows customers from any affiliate library to join any other member library.
* Copyright (C) 2013 Andrew Nisbet
*
* 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 mecard.customer;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import mecard.util.BImportDBFields;
import mecard.util.City;
import mecard.util.DateComparer;
import mecard.util.Phone;
/**
* This class creates the data and header files.
* @author metro
*/
public class BImportFormatter
{
public final static String BORROWER_TABLE = "borrower";
public final static String BORROWER_PHONE_TABLE = "borrower_phone";
public final static String BORROWER_ADDRESS_TABLE = "borrower_address";
public final static String BORROWER_BARCODE_TABLE = "borrower_barcode";
public static class Builder
{
private final String headerName;
private final String dataName;
private String name;
private String expiry;
private String pin;
private String phoneType = "h-noTC";
private String phone;
private String address1;
private String address2 = "";
private String city;
private String postalCode;
private String email;
private String barcode;
private String emailName;
public Builder(String headerPath, String dataPath)
{
this.headerName = headerPath;
this.dataName = dataPath;
}
public Builder emailName(String e)
{
this.emailName = e;
return this;
}
public Builder name(String n)
{
this.name = n;
return this;
}
public Builder barcode(String b)
{
this.barcode = b;
return this;
}
public Builder expire(String e)
{
this.expiry = e;
return this;
}
public Builder pin(String p)
{
this.pin = p;
return this;
}
public Builder pType(String p)
{
this.phoneType = p;
return this;
}
public Builder pNumber(String p)
{
this.phone = p;
return this;
}
public Builder address1(String a)
{
this.address1 = a;
return this;
}
public Builder city(String c)
{
this.city = c;
return this;
}
public Builder postalCode(String p)
{
this.postalCode = p;
return this;
}
public Builder email(String e)
{
this.email = e;
return this;
}
public BImportFormatter build()
{
return new BImportFormatter(this);
}
}
private BImportFormatter(Builder b)
{
StringBuilder headerContent = new StringBuilder();
StringBuilder dataContent = new StringBuilder();
File header = createFile(b.headerName);
File data = createFile(b.dataName);
// These fields need to be formatted
String expiryDate = DateComparer.convertToConfigDate(b.expiry);
// Phone
String phone = Phone.formatPhone(b.phone);
// City needs to be mapped.
String cityCode = City.getCity(b.city);
// Table borrower
headerContent.append("x- "); // add or modify if exists
headerContent.append(BORROWER_TABLE + ": "); // add or modify if exists
headerContent.append(BImportDBFields.SECOND_ID + "; ");
headerContent.append(BImportDBFields.NAME + "; ");
headerContent.append(BImportDBFields.EXPIRY + "; ");
- headerContent.append(BImportDBFields.PIN + "\n\r");
+ headerContent.append(BImportDBFields.PIN + "\r\n");
dataContent.append("M- "); // add or modify if exists
dataContent.append(BORROWER_TABLE + ": "); // add or modify if exists
dataContent.append(b.barcode + "; ");
dataContent.append(b.name + "; ");
dataContent.append(expiryDate + "; "); // see above for computation
- dataContent.append(b.pin + "\n\r");
+ dataContent.append(b.pin + "\r\n");
// Table borrower_phone
headerContent.append(BORROWER_PHONE_TABLE + ": "); // add or modify if exists
headerContent.append(BImportDBFields.PHONE_TYPE + "; ");
- headerContent.append(BImportDBFields.PHONE_NUMBER + "\n\r");
+ headerContent.append(BImportDBFields.PHONE_NUMBER + "\r\n");
dataContent.append(BORROWER_PHONE_TABLE + ": "); // add or modify if exists
dataContent.append(b.phoneType + "; ");
- dataContent.append(phone + "\n\r"); // see computation above.
+ dataContent.append(phone + "\r\n"); // see computation above.
// Table borrower_address
headerContent.append(BORROWER_ADDRESS_TABLE + ": "); // add or modify if exists
headerContent.append(BImportDBFields.ADDRESS_1 + "; ");
headerContent.append(BImportDBFields.ADDRESS_2 + "; ");
headerContent.append(BImportDBFields.CITY + "; ");
headerContent.append(BImportDBFields.POSTAL_CODE + "; ");
headerContent.append(BImportDBFields.EMAIL_NAME + "; ");
- headerContent.append(BImportDBFields.EMAIL_ADDRESS + "\n\r");
+ headerContent.append(BImportDBFields.EMAIL_ADDRESS + "\r\n");
dataContent.append(BORROWER_ADDRESS_TABLE + ": "); // add or modify if exists
dataContent.append(b.address1 + "; ");
dataContent.append(b.address2 + "; ");
dataContent.append(cityCode + "; ");
dataContent.append(b.postalCode + "; ");
dataContent.append(b.emailName + "; ");
- dataContent.append(b.email + "\n\r");
+ dataContent.append(b.email + "\r\n");
// Table borrower_barcode
headerContent.append(BORROWER_BARCODE_TABLE + ": "); // add or modify if exists
- headerContent.append(BImportDBFields.BARCODE + "\n\r");
+ headerContent.append(BImportDBFields.BARCODE + "\r\n");
dataContent.append(BORROWER_BARCODE_TABLE + ": "); // add or modify if exists
- dataContent.append(b.barcode + "\n\r");
+ dataContent.append(b.barcode + "\r\n");
writeContent(headerContent, header);
writeContent(dataContent, data);
}
private void writeContent(StringBuilder content, File file)
{
BufferedWriter bWriter;
try
{
// write the builder contents to the file with the correct switches.
bWriter = new BufferedWriter(new FileWriter(file));
bWriter.write(content.toString());
bWriter.close();
}
catch (IOException ex)
{
String msg = "unable to create '"+file.getName()+"' file.";
Logger.getLogger(BImportFormatter.class.getName()).log(Level.SEVERE, msg, ex);
}
}
private File createFile(String name)
{
File file = new File(name);
if (file.exists())
{
file.delete();
}
// create a new one.
file = new File(name);
return file;
}
}
| false | true | private BImportFormatter(Builder b)
{
StringBuilder headerContent = new StringBuilder();
StringBuilder dataContent = new StringBuilder();
File header = createFile(b.headerName);
File data = createFile(b.dataName);
// These fields need to be formatted
String expiryDate = DateComparer.convertToConfigDate(b.expiry);
// Phone
String phone = Phone.formatPhone(b.phone);
// City needs to be mapped.
String cityCode = City.getCity(b.city);
// Table borrower
headerContent.append("x- "); // add or modify if exists
headerContent.append(BORROWER_TABLE + ": "); // add or modify if exists
headerContent.append(BImportDBFields.SECOND_ID + "; ");
headerContent.append(BImportDBFields.NAME + "; ");
headerContent.append(BImportDBFields.EXPIRY + "; ");
headerContent.append(BImportDBFields.PIN + "\n\r");
dataContent.append("M- "); // add or modify if exists
dataContent.append(BORROWER_TABLE + ": "); // add or modify if exists
dataContent.append(b.barcode + "; ");
dataContent.append(b.name + "; ");
dataContent.append(expiryDate + "; "); // see above for computation
dataContent.append(b.pin + "\n\r");
// Table borrower_phone
headerContent.append(BORROWER_PHONE_TABLE + ": "); // add or modify if exists
headerContent.append(BImportDBFields.PHONE_TYPE + "; ");
headerContent.append(BImportDBFields.PHONE_NUMBER + "\n\r");
dataContent.append(BORROWER_PHONE_TABLE + ": "); // add or modify if exists
dataContent.append(b.phoneType + "; ");
dataContent.append(phone + "\n\r"); // see computation above.
// Table borrower_address
headerContent.append(BORROWER_ADDRESS_TABLE + ": "); // add or modify if exists
headerContent.append(BImportDBFields.ADDRESS_1 + "; ");
headerContent.append(BImportDBFields.ADDRESS_2 + "; ");
headerContent.append(BImportDBFields.CITY + "; ");
headerContent.append(BImportDBFields.POSTAL_CODE + "; ");
headerContent.append(BImportDBFields.EMAIL_NAME + "; ");
headerContent.append(BImportDBFields.EMAIL_ADDRESS + "\n\r");
dataContent.append(BORROWER_ADDRESS_TABLE + ": "); // add or modify if exists
dataContent.append(b.address1 + "; ");
dataContent.append(b.address2 + "; ");
dataContent.append(cityCode + "; ");
dataContent.append(b.postalCode + "; ");
dataContent.append(b.emailName + "; ");
dataContent.append(b.email + "\n\r");
// Table borrower_barcode
headerContent.append(BORROWER_BARCODE_TABLE + ": "); // add or modify if exists
headerContent.append(BImportDBFields.BARCODE + "\n\r");
dataContent.append(BORROWER_BARCODE_TABLE + ": "); // add or modify if exists
dataContent.append(b.barcode + "\n\r");
writeContent(headerContent, header);
writeContent(dataContent, data);
}
| private BImportFormatter(Builder b)
{
StringBuilder headerContent = new StringBuilder();
StringBuilder dataContent = new StringBuilder();
File header = createFile(b.headerName);
File data = createFile(b.dataName);
// These fields need to be formatted
String expiryDate = DateComparer.convertToConfigDate(b.expiry);
// Phone
String phone = Phone.formatPhone(b.phone);
// City needs to be mapped.
String cityCode = City.getCity(b.city);
// Table borrower
headerContent.append("x- "); // add or modify if exists
headerContent.append(BORROWER_TABLE + ": "); // add or modify if exists
headerContent.append(BImportDBFields.SECOND_ID + "; ");
headerContent.append(BImportDBFields.NAME + "; ");
headerContent.append(BImportDBFields.EXPIRY + "; ");
headerContent.append(BImportDBFields.PIN + "\r\n");
dataContent.append("M- "); // add or modify if exists
dataContent.append(BORROWER_TABLE + ": "); // add or modify if exists
dataContent.append(b.barcode + "; ");
dataContent.append(b.name + "; ");
dataContent.append(expiryDate + "; "); // see above for computation
dataContent.append(b.pin + "\r\n");
// Table borrower_phone
headerContent.append(BORROWER_PHONE_TABLE + ": "); // add or modify if exists
headerContent.append(BImportDBFields.PHONE_TYPE + "; ");
headerContent.append(BImportDBFields.PHONE_NUMBER + "\r\n");
dataContent.append(BORROWER_PHONE_TABLE + ": "); // add or modify if exists
dataContent.append(b.phoneType + "; ");
dataContent.append(phone + "\r\n"); // see computation above.
// Table borrower_address
headerContent.append(BORROWER_ADDRESS_TABLE + ": "); // add or modify if exists
headerContent.append(BImportDBFields.ADDRESS_1 + "; ");
headerContent.append(BImportDBFields.ADDRESS_2 + "; ");
headerContent.append(BImportDBFields.CITY + "; ");
headerContent.append(BImportDBFields.POSTAL_CODE + "; ");
headerContent.append(BImportDBFields.EMAIL_NAME + "; ");
headerContent.append(BImportDBFields.EMAIL_ADDRESS + "\r\n");
dataContent.append(BORROWER_ADDRESS_TABLE + ": "); // add or modify if exists
dataContent.append(b.address1 + "; ");
dataContent.append(b.address2 + "; ");
dataContent.append(cityCode + "; ");
dataContent.append(b.postalCode + "; ");
dataContent.append(b.emailName + "; ");
dataContent.append(b.email + "\r\n");
// Table borrower_barcode
headerContent.append(BORROWER_BARCODE_TABLE + ": "); // add or modify if exists
headerContent.append(BImportDBFields.BARCODE + "\r\n");
dataContent.append(BORROWER_BARCODE_TABLE + ": "); // add or modify if exists
dataContent.append(b.barcode + "\r\n");
writeContent(headerContent, header);
writeContent(dataContent, data);
}
|
diff --git a/src/main/java/com/financial/pyramid/service/impl/AccountServiceImpl.java b/src/main/java/com/financial/pyramid/service/impl/AccountServiceImpl.java
index 566fa67..b43dcbd 100644
--- a/src/main/java/com/financial/pyramid/service/impl/AccountServiceImpl.java
+++ b/src/main/java/com/financial/pyramid/service/impl/AccountServiceImpl.java
@@ -1,61 +1,61 @@
package com.financial.pyramid.service.impl;
import com.financial.pyramid.dao.AccountDao;
import com.financial.pyramid.domain.Account;
import com.financial.pyramid.service.AccountService;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
/**
* User: dbudunov
* Date: 29.08.13
* Time: 14:31
*/
@Service("accountService")
@Transactional
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
@Override
public void activate(Account account) {
Date currentDate = new Date();
Date newActivationDate = null;
if (account.getDateExpired().before(currentDate)){
newActivationDate = currentDate;
} else {
newActivationDate = account.getDateExpired();
}
account.setLocked(false);
account.setDateActivated(newActivationDate);
- account.setDateExpired(new DateTime(newActivationDate).plusMonths(1).toDate());
+ account.setDateExpired(new DateTime(newActivationDate).plusMonths(1).plusDays(1).toDate());
update(account);
}
@Override
public void deactivate(Account account) {
account.setLocked(true);
update(account);
}
@Override
public void calculateSum(Account account, Double sum) {
account.setEarningsSum(account.getEarningsSum() + sum);
update(account);
}
@Override
public void update(Account account) {
accountDao.saveOrUpdate(account);
}
@Override
public Account findById(Long id) {
return accountDao.findById(id);
}
}
| true | true | public void activate(Account account) {
Date currentDate = new Date();
Date newActivationDate = null;
if (account.getDateExpired().before(currentDate)){
newActivationDate = currentDate;
} else {
newActivationDate = account.getDateExpired();
}
account.setLocked(false);
account.setDateActivated(newActivationDate);
account.setDateExpired(new DateTime(newActivationDate).plusMonths(1).toDate());
update(account);
}
| public void activate(Account account) {
Date currentDate = new Date();
Date newActivationDate = null;
if (account.getDateExpired().before(currentDate)){
newActivationDate = currentDate;
} else {
newActivationDate = account.getDateExpired();
}
account.setLocked(false);
account.setDateActivated(newActivationDate);
account.setDateExpired(new DateTime(newActivationDate).plusMonths(1).plusDays(1).toDate());
update(account);
}
|
diff --git a/src/main/java/com/concursive/connect/web/controller/hooks/SecurityHook.java b/src/main/java/com/concursive/connect/web/controller/hooks/SecurityHook.java
index 8702f6b..ff96342 100644
--- a/src/main/java/com/concursive/connect/web/controller/hooks/SecurityHook.java
+++ b/src/main/java/com/concursive/connect/web/controller/hooks/SecurityHook.java
@@ -1,404 +1,404 @@
/*
* ConcourseConnect
* Copyright 2009 Concursive Corporation
* http://www.concursive.com
*
* This file is part of ConcourseConnect, an open source social business
* software and community platform.
*
* Concursive ConcourseConnect is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, version 3 of the License.
*
* Under the terms of the GNU Affero General Public License you must release the
* complete source code for any application that uses any part of ConcourseConnect
* (system header files and libraries used by the operating system are excluded).
* These terms must be included in any work that has ConcourseConnect components.
* If you are developing and distributing open source applications under the
* GNU Affero General Public License, then you are free to use ConcourseConnect
* under the GNU Affero General Public License.
*
* If you are deploying a web site in which users interact with any portion of
* ConcourseConnect over a network, the complete source code changes must be made
* available. For example, include a link to the source archive directly from
* your web site.
*
* For OEMs, ISVs, SIs and VARs who distribute ConcourseConnect with their
* products, and do not license and distribute their source code under the GNU
* Affero General Public License, Concursive provides a flexible commercial
* license.
*
* To anyone in doubt, we recommend the commercial license. Our commercial license
* is competitively priced and will eliminate any confusion about how
* ConcourseConnect can be used and distributed.
*
* ConcourseConnect is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License
* along with ConcourseConnect. If not, see <http://www.gnu.org/licenses/>.
*
* Attribution Notice: ConcourseConnect is an Original Work of software created
* by Concursive Corporation
*/
package com.concursive.connect.web.controller.hooks;
import com.concursive.commons.db.ConnectionElement;
import com.concursive.commons.db.ConnectionPool;
import com.concursive.commons.http.CookieUtils;
import com.concursive.commons.web.mvc.servlets.ControllerHook;
import com.concursive.connect.Constants;
import com.concursive.connect.cms.portal.beans.PortalBean;
import com.concursive.connect.config.ApplicationPrefs;
import com.concursive.connect.config.ApplicationVersion;
import com.concursive.connect.web.modules.login.auth.session.ISessionValidator;
import com.concursive.connect.web.modules.login.auth.session.SessionValidatorFactory;
import com.concursive.connect.web.modules.login.beans.LoginBean;
import com.concursive.connect.web.modules.login.dao.User;
import com.concursive.connect.web.modules.login.utils.UserUtils;
import com.concursive.connect.web.modules.members.dao.InvitationList;
import com.concursive.connect.web.modules.messages.dao.PrivateMessageList;
import com.concursive.connect.web.modules.profile.dao.Project;
import com.concursive.connect.web.modules.profile.dao.ProjectCategory;
import com.concursive.connect.web.modules.profile.dao.ProjectCategoryList;
import com.concursive.connect.web.modules.profile.dao.ProjectList;
import com.concursive.connect.web.modules.profile.utils.ProjectUtils;
import com.concursive.connect.web.modules.search.beans.SearchBean;
import com.concursive.connect.web.modules.translation.dao.WebSiteLanguageList;
import com.concursive.connect.web.utils.ClientType;
import com.concursive.connect.web.utils.HtmlSelect;
import com.concursive.connect.web.utils.PagedListInfo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import java.sql.SQLException;
/**
* Executed on every request to verify user is logged in, and that system
* resources are ready, also prepares portlets
*
* @author matt rajkowski
* @version $Id$
* @created May 7, 2003
*/
public class SecurityHook implements ControllerHook {
private static Log LOG = LogFactory.getLog(SecurityHook.class);
public final static String fs = System.getProperty("file.separator");
private ISessionValidator sessionValidator = null;
/**
* Checks to see if a User session object exists, if not then the security
* check fails.
*
* @param servlet Description of the Parameter
* @param request Description of the Parameter
* @param response Description of the Parameter
* @return Description of the Return Value
*/
public String beginRequest(Servlet servlet, HttpServletRequest request, HttpServletResponse response) {
LOG.debug("Security request made");
ServletConfig config = servlet.getServletConfig();
ServletContext context = config.getServletContext();
// Application wide preferences
ApplicationPrefs prefs = (ApplicationPrefs) context.getAttribute("applicationPrefs");
// Get the intended action, if going to the login module, then let it proceed
String s = request.getServletPath();
int slash = s.lastIndexOf("/");
s = s.substring(slash + 1);
// If not setup then go to setup
if (!s.startsWith("Setup") && !prefs.isConfigured()) {
return "NotSetupError";
}
// External calls
if (s.startsWith("Service")) {
return null;
}
// Set the layout relevant to this request
if ("text".equals(request.getParameter("out")) ||
"text".equals(request.getAttribute("out"))) {
} else if ("true".equals(request.getParameter("popup"))) {
request.setAttribute("PageLayout", "/layout1.jsp");
} else if ("true".equals(request.getParameter("style"))) {
request.setAttribute("PageLayout", "/layout1.jsp");
} else {
request.setAttribute("PageLayout", context.getAttribute("Template"));
}
// If going to Setup then allow
if (s.startsWith("Setup")) {
request.setAttribute("PageLayout", "/layout1.jsp");
return null;
}
// If going to Upgrade then allow
if (s.startsWith("Upgrade")) {
request.setAttribute("PageLayout", "/layout1.jsp");
return null;
}
// Detect mobile users and mobile formatting
ClientType clientType = (ClientType) request.getSession().getAttribute("clientType");
if (clientType == null) {
clientType = new ClientType(request);
request.getSession().setAttribute("clientType", clientType);
}
if (clientType.getMobile()) {
request.setAttribute("PageLayout", "/layoutMobile.jsp");
}
// URL forwarding
String requestedURL = (String) request.getAttribute("requestedURL");
if (requestedURL == null && "GET".equals(request.getMethod()) && request.getParameter("redirectTo") == null) {
// Save the requestURI to be used downstream
String contextPath = request.getContextPath();
String uri = request.getRequestURI();
String queryString = request.getQueryString();
requestedURL = uri.substring(contextPath.length()) + (queryString == null ? "" : "?" + queryString);
request.setAttribute("requestedURL", requestedURL);
// The portal has it's own redirect scheme, this is a general catch all
if (!s.startsWith("Portal") && uri.indexOf(".shtml") == -1) {
// Check to see if an old domain name is used
PortalBean bean = new PortalBean(request);
String expectedURL = prefs.get("URL");
if (expectedURL != null && requestedURL != null &&
!"127.0.0.1".equals(bean.getServerName()) &&
!"localhost".equals(bean.getServerName()) &&
!bean.getServerName().equals(expectedURL)) {
if (uri != null && !uri.substring(1).equals(prefs.get("PORTAL.INDEX"))) {
request.setAttribute("redirectTo", requestedURL.substring(requestedURL.lastIndexOf("/")));
}
request.removeAttribute("PageLayout");
return "Redirect301";
}
}
}
// Version check
if (!s.startsWith("Login") && ApplicationVersion.isOutOfDate(prefs)) {
return "UpgradeCheck";
}
// Get the user object from the Session Validation...
if (sessionValidator == null) {
sessionValidator = SessionValidatorFactory.getInstance().getSessionValidator(servlet.getServletConfig().getServletContext(), request);
LOG.debug("Found sessionValidator? " + (sessionValidator != null));
}
// Check cookie for user's previous location info
SearchBean searchBean = (SearchBean) request.getSession().getAttribute(Constants.SESSION_SEARCH_BEAN);
if (searchBean == null) {
String searchLocation = CookieUtils.getCookieValue(request, Constants.COOKIE_USER_SEARCH_LOCATION);
if (searchLocation != null) {
LOG.debug("Setting search location from cookie: " + searchLocation);
searchBean = new SearchBean();
searchBean.setLocation(searchLocation);
request.getSession().setAttribute(Constants.SESSION_SEARCH_BEAN, searchBean);
}
}
// Continue with session creation...
User userSession = sessionValidator.validateSession(context, request, response);
ConnectionElement ceSession = (ConnectionElement) request.getSession().getAttribute("ConnectionElement");
// The user is going to the portal so get them guest credentials if they need them
if ("true".equals(prefs.get("PORTAL")) ||
s.startsWith("Register") ||
s.startsWith("ResetPassword") ||
s.startsWith("LoginAccept") ||
s.startsWith("LoginReject") ||
s.startsWith("Search") ||
s.startsWith("ContactUs")) {
if (userSession == null || ceSession == null) {
// Allow portal mode to create a default session with guest capabilities
userSession = UserUtils.createGuestUser();
request.getSession().setAttribute("User", userSession);
// Give them a connection element
ceSession = new ConnectionElement();
ceSession.setDriver(prefs.get("SITE.DRIVER"));
ceSession.setUrl(prefs.get("SITE.URL"));
ceSession.setUsername(prefs.get("SITE.USER"));
ceSession.setPassword(prefs.get("SITE.PASSWORD"));
request.getSession().setAttribute("ConnectionElement", ceSession);
}
// Make sure SSL is being used for this connection
if (userSession.getId() > 0 && "true".equals(prefs.get("SSL")) && !"https".equals(request.getScheme())) {
LOG.info("Redirecting to..." + requestedURL);
request.setAttribute("redirectTo", "https://" + request.getServerName() + request.getContextPath() + requestedURL);
request.removeAttribute("PageLayout");
return "Redirect301";
}
// Generate global items
Connection db = null;
try {
db = getConnection(context, request);
// TODO: Implement cache since every hit needs this list
if (db != null) {
// Load the project languages
WebSiteLanguageList webSiteLanguageList = new WebSiteLanguageList();
webSiteLanguageList.setEnabled(Constants.TRUE);
webSiteLanguageList.buildList(db);
// If an admin of a language, enable it...
webSiteLanguageList.add(userSession.getWebSiteLanguageList());
request.setAttribute("webSiteLanguageList", webSiteLanguageList);
// Load the menu list
ProjectList menu = new ProjectList();
PagedListInfo menuListInfo = new PagedListInfo();
menuListInfo.setColumnToSortBy("p.portal_default desc, p.level asc, p.title asc");
menuListInfo.setItemsPerPage(-1);
menu.setPagedListInfo(menuListInfo);
menu.setIncludeGuestProjects(false);
menu.setPortalState(Constants.TRUE);
menu.setOpenProjectsOnly(true);
menu.setApprovedOnly(true);
menu.setBuildLink(true);
menu.setLanguageId(webSiteLanguageList.getLanguageId(request));
menu.buildList(db);
request.setAttribute("menuList", menu);
// Load the main profile to use throughout
Project mainProfile = ProjectUtils.loadProject(prefs.get("MAIN_PROFILE"));
request.setAttribute(Constants.REQUEST_MAIN_PROFILE, mainProfile);
// Load the project categories for search and tab menus
ProjectCategoryList categoryList = new ProjectCategoryList();
categoryList.setEnabled(Constants.TRUE);
categoryList.setTopLevelOnly(true);
if (!userSession.isLoggedIn()) {
categoryList.setSensitive(Constants.FALSE);
}
categoryList.buildList(db);
request.setAttribute(Constants.REQUEST_TAB_CATEGORY_LIST, categoryList);
// Category drop-down for search
HtmlSelect thisSelect = categoryList.getHtmlSelect();
thisSelect.addItem(-1, prefs.get("TITLE"), 0);
request.setAttribute(Constants.REQUEST_MENU_CATEGORY_LIST, thisSelect);
//Determine the tab that needs to be highlighted
if (requestedURL != null) {
boolean foundChosenTab = false;
String chosenCategory = null;
String chosenTab = null;
if (requestedURL.length() > 0) {
chosenTab = requestedURL.substring(1);
}
if (chosenTab == null || chosenTab.indexOf(".shtml") == -1) {
chosenTab = "home.shtml";
} else {
for (ProjectCategory projectCategory : categoryList) {
String categoryName = projectCategory.getDescription();
String normalizedCategoryTab = projectCategory.getNormalizedCategoryName().concat(".shtml");
if (normalizedCategoryTab.equals(chosenTab)) {
foundChosenTab = true;
chosenCategory = categoryName;
}
}
}
if (!foundChosenTab) {
chosenTab = "home.shtml";
}
request.setAttribute("chosenTab", chosenTab);
request.setAttribute("chosenCategory", chosenCategory);
}
}
} catch (Exception e) {
LOG.error("Global items error", e);
} finally {
this.freeConnection(context, db);
}
}
// The user is not going to login, so verify login
if (!s.startsWith("Login")) {
if (userSession == null || ceSession == null) {
// boot them off now
LOG.debug("Security failed.");
LoginBean failedSession = new LoginBean();
failedSession.addError("actionError", "* Please login, your session has expired");
failedSession.checkURL(request);
request.setAttribute("LoginBean", failedSession);
request.removeAttribute("PageLayout");
return "SecurityCheck";
} else {
// The user should have a valid login now, so let them proceed
LOG.debug("Security passed.");
}
}
// Generate user's global items
if (userSession != null && userSession.getId() > 0) {
Connection db = null;
try {
db = getConnection(context, request);
// TODO: Implement cache since every hit needs this list
if (db != null) {
// Check the # of invitations
int invitationCount = InvitationList.queryCount(db, userSession.getId());
request.setAttribute(Constants.REQUEST_INVITATION_COUNT, String.valueOf(invitationCount));
- int newMailCount = PrivateMessageList.queryRolledupUnreadCountForUser(db, userSession.getId());
+ int newMailCount = PrivateMessageList.queryUnreadCountForUser(db, userSession.getId());
request.setAttribute(Constants.REQUEST_PRIVATE_MESSAGE_COUNT, String.valueOf(newMailCount));
// NOTE: removed because not currently used
// Check the number of what's new
// int whatsNewCount = ProjectUtils.queryWhatsNewCount(db, userSession.getId());
// request.setAttribute(Constants.REQUEST_WHATS_NEW_COUNT, String.valueOf(whatsNewCount));
// Check the number of assignments
// int whatsAssignedCount = ProjectUtils.queryWhatsAssignedCount(db, userSession.getId());
// request.setAttribute(Constants.REQUEST_WHATS_ASSIGNED_COUNT, String.valueOf(whatsAssignedCount));
// int projectCount = ProjectUtils.queryMyProjectCount(db, userSession.getId());
// request.setAttribute(Constants.REQUEST_MY_PROJECT_COUNT, String.valueOf(projectCount));
}
} catch (Exception e) {
LOG.error("User's global items error", e);
} finally {
this.freeConnection(context, db);
}
}
return null;
}
/**
* Description of the Method
*
* @param servlet Description of the Parameter
* @param request Description of the Parameter
* @param response Description of the Parameter
* @return Description of the Return Value
*/
public String endRequest(Servlet servlet, HttpServletRequest request, HttpServletResponse response) {
return null;
}
/**
* Gets the connection attribute of the SecurityHook object
*
* @param context Description of the Parameter
* @param request Description of the Parameter
* @return The connection value
* @throws SQLException Description of the Exception
*/
protected Connection getConnection(ServletContext context, HttpServletRequest request) throws SQLException {
ConnectionPool sqlDriver = (ConnectionPool) context.getAttribute("ConnectionPool");
ConnectionElement ce = (ConnectionElement) request.getSession().getAttribute("ConnectionElement");
if (sqlDriver == null || ce == null) {
return null;
}
return sqlDriver.getConnection(ce);
}
/**
* Description of the Method
*
* @param context Description of the Parameter
* @param db Description of the Parameter
*/
protected void freeConnection(ServletContext context, Connection db) {
if (db != null) {
ConnectionPool sqlDriver = (ConnectionPool) context.getAttribute("ConnectionPool");
sqlDriver.free(db);
}
db = null;
}
}
| true | true | public String beginRequest(Servlet servlet, HttpServletRequest request, HttpServletResponse response) {
LOG.debug("Security request made");
ServletConfig config = servlet.getServletConfig();
ServletContext context = config.getServletContext();
// Application wide preferences
ApplicationPrefs prefs = (ApplicationPrefs) context.getAttribute("applicationPrefs");
// Get the intended action, if going to the login module, then let it proceed
String s = request.getServletPath();
int slash = s.lastIndexOf("/");
s = s.substring(slash + 1);
// If not setup then go to setup
if (!s.startsWith("Setup") && !prefs.isConfigured()) {
return "NotSetupError";
}
// External calls
if (s.startsWith("Service")) {
return null;
}
// Set the layout relevant to this request
if ("text".equals(request.getParameter("out")) ||
"text".equals(request.getAttribute("out"))) {
} else if ("true".equals(request.getParameter("popup"))) {
request.setAttribute("PageLayout", "/layout1.jsp");
} else if ("true".equals(request.getParameter("style"))) {
request.setAttribute("PageLayout", "/layout1.jsp");
} else {
request.setAttribute("PageLayout", context.getAttribute("Template"));
}
// If going to Setup then allow
if (s.startsWith("Setup")) {
request.setAttribute("PageLayout", "/layout1.jsp");
return null;
}
// If going to Upgrade then allow
if (s.startsWith("Upgrade")) {
request.setAttribute("PageLayout", "/layout1.jsp");
return null;
}
// Detect mobile users and mobile formatting
ClientType clientType = (ClientType) request.getSession().getAttribute("clientType");
if (clientType == null) {
clientType = new ClientType(request);
request.getSession().setAttribute("clientType", clientType);
}
if (clientType.getMobile()) {
request.setAttribute("PageLayout", "/layoutMobile.jsp");
}
// URL forwarding
String requestedURL = (String) request.getAttribute("requestedURL");
if (requestedURL == null && "GET".equals(request.getMethod()) && request.getParameter("redirectTo") == null) {
// Save the requestURI to be used downstream
String contextPath = request.getContextPath();
String uri = request.getRequestURI();
String queryString = request.getQueryString();
requestedURL = uri.substring(contextPath.length()) + (queryString == null ? "" : "?" + queryString);
request.setAttribute("requestedURL", requestedURL);
// The portal has it's own redirect scheme, this is a general catch all
if (!s.startsWith("Portal") && uri.indexOf(".shtml") == -1) {
// Check to see if an old domain name is used
PortalBean bean = new PortalBean(request);
String expectedURL = prefs.get("URL");
if (expectedURL != null && requestedURL != null &&
!"127.0.0.1".equals(bean.getServerName()) &&
!"localhost".equals(bean.getServerName()) &&
!bean.getServerName().equals(expectedURL)) {
if (uri != null && !uri.substring(1).equals(prefs.get("PORTAL.INDEX"))) {
request.setAttribute("redirectTo", requestedURL.substring(requestedURL.lastIndexOf("/")));
}
request.removeAttribute("PageLayout");
return "Redirect301";
}
}
}
// Version check
if (!s.startsWith("Login") && ApplicationVersion.isOutOfDate(prefs)) {
return "UpgradeCheck";
}
// Get the user object from the Session Validation...
if (sessionValidator == null) {
sessionValidator = SessionValidatorFactory.getInstance().getSessionValidator(servlet.getServletConfig().getServletContext(), request);
LOG.debug("Found sessionValidator? " + (sessionValidator != null));
}
// Check cookie for user's previous location info
SearchBean searchBean = (SearchBean) request.getSession().getAttribute(Constants.SESSION_SEARCH_BEAN);
if (searchBean == null) {
String searchLocation = CookieUtils.getCookieValue(request, Constants.COOKIE_USER_SEARCH_LOCATION);
if (searchLocation != null) {
LOG.debug("Setting search location from cookie: " + searchLocation);
searchBean = new SearchBean();
searchBean.setLocation(searchLocation);
request.getSession().setAttribute(Constants.SESSION_SEARCH_BEAN, searchBean);
}
}
// Continue with session creation...
User userSession = sessionValidator.validateSession(context, request, response);
ConnectionElement ceSession = (ConnectionElement) request.getSession().getAttribute("ConnectionElement");
// The user is going to the portal so get them guest credentials if they need them
if ("true".equals(prefs.get("PORTAL")) ||
s.startsWith("Register") ||
s.startsWith("ResetPassword") ||
s.startsWith("LoginAccept") ||
s.startsWith("LoginReject") ||
s.startsWith("Search") ||
s.startsWith("ContactUs")) {
if (userSession == null || ceSession == null) {
// Allow portal mode to create a default session with guest capabilities
userSession = UserUtils.createGuestUser();
request.getSession().setAttribute("User", userSession);
// Give them a connection element
ceSession = new ConnectionElement();
ceSession.setDriver(prefs.get("SITE.DRIVER"));
ceSession.setUrl(prefs.get("SITE.URL"));
ceSession.setUsername(prefs.get("SITE.USER"));
ceSession.setPassword(prefs.get("SITE.PASSWORD"));
request.getSession().setAttribute("ConnectionElement", ceSession);
}
// Make sure SSL is being used for this connection
if (userSession.getId() > 0 && "true".equals(prefs.get("SSL")) && !"https".equals(request.getScheme())) {
LOG.info("Redirecting to..." + requestedURL);
request.setAttribute("redirectTo", "https://" + request.getServerName() + request.getContextPath() + requestedURL);
request.removeAttribute("PageLayout");
return "Redirect301";
}
// Generate global items
Connection db = null;
try {
db = getConnection(context, request);
// TODO: Implement cache since every hit needs this list
if (db != null) {
// Load the project languages
WebSiteLanguageList webSiteLanguageList = new WebSiteLanguageList();
webSiteLanguageList.setEnabled(Constants.TRUE);
webSiteLanguageList.buildList(db);
// If an admin of a language, enable it...
webSiteLanguageList.add(userSession.getWebSiteLanguageList());
request.setAttribute("webSiteLanguageList", webSiteLanguageList);
// Load the menu list
ProjectList menu = new ProjectList();
PagedListInfo menuListInfo = new PagedListInfo();
menuListInfo.setColumnToSortBy("p.portal_default desc, p.level asc, p.title asc");
menuListInfo.setItemsPerPage(-1);
menu.setPagedListInfo(menuListInfo);
menu.setIncludeGuestProjects(false);
menu.setPortalState(Constants.TRUE);
menu.setOpenProjectsOnly(true);
menu.setApprovedOnly(true);
menu.setBuildLink(true);
menu.setLanguageId(webSiteLanguageList.getLanguageId(request));
menu.buildList(db);
request.setAttribute("menuList", menu);
// Load the main profile to use throughout
Project mainProfile = ProjectUtils.loadProject(prefs.get("MAIN_PROFILE"));
request.setAttribute(Constants.REQUEST_MAIN_PROFILE, mainProfile);
// Load the project categories for search and tab menus
ProjectCategoryList categoryList = new ProjectCategoryList();
categoryList.setEnabled(Constants.TRUE);
categoryList.setTopLevelOnly(true);
if (!userSession.isLoggedIn()) {
categoryList.setSensitive(Constants.FALSE);
}
categoryList.buildList(db);
request.setAttribute(Constants.REQUEST_TAB_CATEGORY_LIST, categoryList);
// Category drop-down for search
HtmlSelect thisSelect = categoryList.getHtmlSelect();
thisSelect.addItem(-1, prefs.get("TITLE"), 0);
request.setAttribute(Constants.REQUEST_MENU_CATEGORY_LIST, thisSelect);
//Determine the tab that needs to be highlighted
if (requestedURL != null) {
boolean foundChosenTab = false;
String chosenCategory = null;
String chosenTab = null;
if (requestedURL.length() > 0) {
chosenTab = requestedURL.substring(1);
}
if (chosenTab == null || chosenTab.indexOf(".shtml") == -1) {
chosenTab = "home.shtml";
} else {
for (ProjectCategory projectCategory : categoryList) {
String categoryName = projectCategory.getDescription();
String normalizedCategoryTab = projectCategory.getNormalizedCategoryName().concat(".shtml");
if (normalizedCategoryTab.equals(chosenTab)) {
foundChosenTab = true;
chosenCategory = categoryName;
}
}
}
if (!foundChosenTab) {
chosenTab = "home.shtml";
}
request.setAttribute("chosenTab", chosenTab);
request.setAttribute("chosenCategory", chosenCategory);
}
}
} catch (Exception e) {
LOG.error("Global items error", e);
} finally {
this.freeConnection(context, db);
}
}
// The user is not going to login, so verify login
if (!s.startsWith("Login")) {
if (userSession == null || ceSession == null) {
// boot them off now
LOG.debug("Security failed.");
LoginBean failedSession = new LoginBean();
failedSession.addError("actionError", "* Please login, your session has expired");
failedSession.checkURL(request);
request.setAttribute("LoginBean", failedSession);
request.removeAttribute("PageLayout");
return "SecurityCheck";
} else {
// The user should have a valid login now, so let them proceed
LOG.debug("Security passed.");
}
}
// Generate user's global items
if (userSession != null && userSession.getId() > 0) {
Connection db = null;
try {
db = getConnection(context, request);
// TODO: Implement cache since every hit needs this list
if (db != null) {
// Check the # of invitations
int invitationCount = InvitationList.queryCount(db, userSession.getId());
request.setAttribute(Constants.REQUEST_INVITATION_COUNT, String.valueOf(invitationCount));
int newMailCount = PrivateMessageList.queryRolledupUnreadCountForUser(db, userSession.getId());
request.setAttribute(Constants.REQUEST_PRIVATE_MESSAGE_COUNT, String.valueOf(newMailCount));
// NOTE: removed because not currently used
// Check the number of what's new
// int whatsNewCount = ProjectUtils.queryWhatsNewCount(db, userSession.getId());
// request.setAttribute(Constants.REQUEST_WHATS_NEW_COUNT, String.valueOf(whatsNewCount));
// Check the number of assignments
// int whatsAssignedCount = ProjectUtils.queryWhatsAssignedCount(db, userSession.getId());
// request.setAttribute(Constants.REQUEST_WHATS_ASSIGNED_COUNT, String.valueOf(whatsAssignedCount));
// int projectCount = ProjectUtils.queryMyProjectCount(db, userSession.getId());
// request.setAttribute(Constants.REQUEST_MY_PROJECT_COUNT, String.valueOf(projectCount));
}
} catch (Exception e) {
LOG.error("User's global items error", e);
} finally {
this.freeConnection(context, db);
}
}
return null;
}
| public String beginRequest(Servlet servlet, HttpServletRequest request, HttpServletResponse response) {
LOG.debug("Security request made");
ServletConfig config = servlet.getServletConfig();
ServletContext context = config.getServletContext();
// Application wide preferences
ApplicationPrefs prefs = (ApplicationPrefs) context.getAttribute("applicationPrefs");
// Get the intended action, if going to the login module, then let it proceed
String s = request.getServletPath();
int slash = s.lastIndexOf("/");
s = s.substring(slash + 1);
// If not setup then go to setup
if (!s.startsWith("Setup") && !prefs.isConfigured()) {
return "NotSetupError";
}
// External calls
if (s.startsWith("Service")) {
return null;
}
// Set the layout relevant to this request
if ("text".equals(request.getParameter("out")) ||
"text".equals(request.getAttribute("out"))) {
} else if ("true".equals(request.getParameter("popup"))) {
request.setAttribute("PageLayout", "/layout1.jsp");
} else if ("true".equals(request.getParameter("style"))) {
request.setAttribute("PageLayout", "/layout1.jsp");
} else {
request.setAttribute("PageLayout", context.getAttribute("Template"));
}
// If going to Setup then allow
if (s.startsWith("Setup")) {
request.setAttribute("PageLayout", "/layout1.jsp");
return null;
}
// If going to Upgrade then allow
if (s.startsWith("Upgrade")) {
request.setAttribute("PageLayout", "/layout1.jsp");
return null;
}
// Detect mobile users and mobile formatting
ClientType clientType = (ClientType) request.getSession().getAttribute("clientType");
if (clientType == null) {
clientType = new ClientType(request);
request.getSession().setAttribute("clientType", clientType);
}
if (clientType.getMobile()) {
request.setAttribute("PageLayout", "/layoutMobile.jsp");
}
// URL forwarding
String requestedURL = (String) request.getAttribute("requestedURL");
if (requestedURL == null && "GET".equals(request.getMethod()) && request.getParameter("redirectTo") == null) {
// Save the requestURI to be used downstream
String contextPath = request.getContextPath();
String uri = request.getRequestURI();
String queryString = request.getQueryString();
requestedURL = uri.substring(contextPath.length()) + (queryString == null ? "" : "?" + queryString);
request.setAttribute("requestedURL", requestedURL);
// The portal has it's own redirect scheme, this is a general catch all
if (!s.startsWith("Portal") && uri.indexOf(".shtml") == -1) {
// Check to see if an old domain name is used
PortalBean bean = new PortalBean(request);
String expectedURL = prefs.get("URL");
if (expectedURL != null && requestedURL != null &&
!"127.0.0.1".equals(bean.getServerName()) &&
!"localhost".equals(bean.getServerName()) &&
!bean.getServerName().equals(expectedURL)) {
if (uri != null && !uri.substring(1).equals(prefs.get("PORTAL.INDEX"))) {
request.setAttribute("redirectTo", requestedURL.substring(requestedURL.lastIndexOf("/")));
}
request.removeAttribute("PageLayout");
return "Redirect301";
}
}
}
// Version check
if (!s.startsWith("Login") && ApplicationVersion.isOutOfDate(prefs)) {
return "UpgradeCheck";
}
// Get the user object from the Session Validation...
if (sessionValidator == null) {
sessionValidator = SessionValidatorFactory.getInstance().getSessionValidator(servlet.getServletConfig().getServletContext(), request);
LOG.debug("Found sessionValidator? " + (sessionValidator != null));
}
// Check cookie for user's previous location info
SearchBean searchBean = (SearchBean) request.getSession().getAttribute(Constants.SESSION_SEARCH_BEAN);
if (searchBean == null) {
String searchLocation = CookieUtils.getCookieValue(request, Constants.COOKIE_USER_SEARCH_LOCATION);
if (searchLocation != null) {
LOG.debug("Setting search location from cookie: " + searchLocation);
searchBean = new SearchBean();
searchBean.setLocation(searchLocation);
request.getSession().setAttribute(Constants.SESSION_SEARCH_BEAN, searchBean);
}
}
// Continue with session creation...
User userSession = sessionValidator.validateSession(context, request, response);
ConnectionElement ceSession = (ConnectionElement) request.getSession().getAttribute("ConnectionElement");
// The user is going to the portal so get them guest credentials if they need them
if ("true".equals(prefs.get("PORTAL")) ||
s.startsWith("Register") ||
s.startsWith("ResetPassword") ||
s.startsWith("LoginAccept") ||
s.startsWith("LoginReject") ||
s.startsWith("Search") ||
s.startsWith("ContactUs")) {
if (userSession == null || ceSession == null) {
// Allow portal mode to create a default session with guest capabilities
userSession = UserUtils.createGuestUser();
request.getSession().setAttribute("User", userSession);
// Give them a connection element
ceSession = new ConnectionElement();
ceSession.setDriver(prefs.get("SITE.DRIVER"));
ceSession.setUrl(prefs.get("SITE.URL"));
ceSession.setUsername(prefs.get("SITE.USER"));
ceSession.setPassword(prefs.get("SITE.PASSWORD"));
request.getSession().setAttribute("ConnectionElement", ceSession);
}
// Make sure SSL is being used for this connection
if (userSession.getId() > 0 && "true".equals(prefs.get("SSL")) && !"https".equals(request.getScheme())) {
LOG.info("Redirecting to..." + requestedURL);
request.setAttribute("redirectTo", "https://" + request.getServerName() + request.getContextPath() + requestedURL);
request.removeAttribute("PageLayout");
return "Redirect301";
}
// Generate global items
Connection db = null;
try {
db = getConnection(context, request);
// TODO: Implement cache since every hit needs this list
if (db != null) {
// Load the project languages
WebSiteLanguageList webSiteLanguageList = new WebSiteLanguageList();
webSiteLanguageList.setEnabled(Constants.TRUE);
webSiteLanguageList.buildList(db);
// If an admin of a language, enable it...
webSiteLanguageList.add(userSession.getWebSiteLanguageList());
request.setAttribute("webSiteLanguageList", webSiteLanguageList);
// Load the menu list
ProjectList menu = new ProjectList();
PagedListInfo menuListInfo = new PagedListInfo();
menuListInfo.setColumnToSortBy("p.portal_default desc, p.level asc, p.title asc");
menuListInfo.setItemsPerPage(-1);
menu.setPagedListInfo(menuListInfo);
menu.setIncludeGuestProjects(false);
menu.setPortalState(Constants.TRUE);
menu.setOpenProjectsOnly(true);
menu.setApprovedOnly(true);
menu.setBuildLink(true);
menu.setLanguageId(webSiteLanguageList.getLanguageId(request));
menu.buildList(db);
request.setAttribute("menuList", menu);
// Load the main profile to use throughout
Project mainProfile = ProjectUtils.loadProject(prefs.get("MAIN_PROFILE"));
request.setAttribute(Constants.REQUEST_MAIN_PROFILE, mainProfile);
// Load the project categories for search and tab menus
ProjectCategoryList categoryList = new ProjectCategoryList();
categoryList.setEnabled(Constants.TRUE);
categoryList.setTopLevelOnly(true);
if (!userSession.isLoggedIn()) {
categoryList.setSensitive(Constants.FALSE);
}
categoryList.buildList(db);
request.setAttribute(Constants.REQUEST_TAB_CATEGORY_LIST, categoryList);
// Category drop-down for search
HtmlSelect thisSelect = categoryList.getHtmlSelect();
thisSelect.addItem(-1, prefs.get("TITLE"), 0);
request.setAttribute(Constants.REQUEST_MENU_CATEGORY_LIST, thisSelect);
//Determine the tab that needs to be highlighted
if (requestedURL != null) {
boolean foundChosenTab = false;
String chosenCategory = null;
String chosenTab = null;
if (requestedURL.length() > 0) {
chosenTab = requestedURL.substring(1);
}
if (chosenTab == null || chosenTab.indexOf(".shtml") == -1) {
chosenTab = "home.shtml";
} else {
for (ProjectCategory projectCategory : categoryList) {
String categoryName = projectCategory.getDescription();
String normalizedCategoryTab = projectCategory.getNormalizedCategoryName().concat(".shtml");
if (normalizedCategoryTab.equals(chosenTab)) {
foundChosenTab = true;
chosenCategory = categoryName;
}
}
}
if (!foundChosenTab) {
chosenTab = "home.shtml";
}
request.setAttribute("chosenTab", chosenTab);
request.setAttribute("chosenCategory", chosenCategory);
}
}
} catch (Exception e) {
LOG.error("Global items error", e);
} finally {
this.freeConnection(context, db);
}
}
// The user is not going to login, so verify login
if (!s.startsWith("Login")) {
if (userSession == null || ceSession == null) {
// boot them off now
LOG.debug("Security failed.");
LoginBean failedSession = new LoginBean();
failedSession.addError("actionError", "* Please login, your session has expired");
failedSession.checkURL(request);
request.setAttribute("LoginBean", failedSession);
request.removeAttribute("PageLayout");
return "SecurityCheck";
} else {
// The user should have a valid login now, so let them proceed
LOG.debug("Security passed.");
}
}
// Generate user's global items
if (userSession != null && userSession.getId() > 0) {
Connection db = null;
try {
db = getConnection(context, request);
// TODO: Implement cache since every hit needs this list
if (db != null) {
// Check the # of invitations
int invitationCount = InvitationList.queryCount(db, userSession.getId());
request.setAttribute(Constants.REQUEST_INVITATION_COUNT, String.valueOf(invitationCount));
int newMailCount = PrivateMessageList.queryUnreadCountForUser(db, userSession.getId());
request.setAttribute(Constants.REQUEST_PRIVATE_MESSAGE_COUNT, String.valueOf(newMailCount));
// NOTE: removed because not currently used
// Check the number of what's new
// int whatsNewCount = ProjectUtils.queryWhatsNewCount(db, userSession.getId());
// request.setAttribute(Constants.REQUEST_WHATS_NEW_COUNT, String.valueOf(whatsNewCount));
// Check the number of assignments
// int whatsAssignedCount = ProjectUtils.queryWhatsAssignedCount(db, userSession.getId());
// request.setAttribute(Constants.REQUEST_WHATS_ASSIGNED_COUNT, String.valueOf(whatsAssignedCount));
// int projectCount = ProjectUtils.queryMyProjectCount(db, userSession.getId());
// request.setAttribute(Constants.REQUEST_MY_PROJECT_COUNT, String.valueOf(projectCount));
}
} catch (Exception e) {
LOG.error("User's global items error", e);
} finally {
this.freeConnection(context, db);
}
}
return null;
}
|
diff --git a/src/nl/giantit/minecraft/GiantShop/core/Commands/check.java b/src/nl/giantit/minecraft/GiantShop/core/Commands/check.java
index 5a8e4b3..d79ea23 100644
--- a/src/nl/giantit/minecraft/GiantShop/core/Commands/check.java
+++ b/src/nl/giantit/minecraft/GiantShop/core/Commands/check.java
@@ -1,134 +1,134 @@
package nl.giantit.minecraft.GiantShop.core.Commands;
import nl.giantit.minecraft.GiantShop.GiantShop;
import nl.giantit.minecraft.GiantShop.Misc.Heraut;
import nl.giantit.minecraft.GiantShop.Misc.Messages;
import nl.giantit.minecraft.GiantShop.core.config;
import nl.giantit.minecraft.GiantShop.core.perm;
import nl.giantit.minecraft.GiantShop.core.Database.db;
import nl.giantit.minecraft.GiantShop.core.Items.Items;
import nl.giantit.minecraft.GiantShop.core.Items.ItemID;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;
/**
*
* @author Giant
*/
public class check {
public static void check(Player player, String[] args) {
Messages msgs = GiantShop.getPlugin().getMsgHandler();
Items iH = GiantShop.getPlugin().getItemHandler();
perm perms = perm.Obtain();
config conf = config.Obtain();
if(perms.has(player, "giantshop.shop.check")) {
db DB = db.Obtain();
int itemID;
Integer itemType = -1;
if(!args[1].matches("[0-9]+:[0-9]+")) {
try {
itemID = Integer.parseInt(args[1]);
itemType = -1;
}catch(NumberFormatException e) {
ItemID key = iH.getItemIDByName(args[1]);
if(key != null) {
itemID = key.getId();
itemType = key.getType();
}else{
Heraut.say(player, msgs.getMsg(Messages.msgType.ERROR, "itemNotFound"));
return;
}
}catch(Exception e) {
if(conf.getBoolean("GiantShop.global.debug") == true) {
GiantShop.log.log(Level.SEVERE, "GiantShop Error: " + e.getMessage());
GiantShop.log.log(Level.INFO, "Stacktrace: " + e.getStackTrace());
}
Heraut.say(player, msgs.getMsg(Messages.msgType.ERROR, "unknown"));
return;
}
}else{
try {
String[] data = args[1].split(":");
itemID = Integer.parseInt(data[0]);
itemType = Integer.parseInt(data[1]);
}catch(NumberFormatException e) {
HashMap<String, String> data = new HashMap<String, String>();
data.put("command", "check");
Heraut.say(player, msgs.getMsg(Messages.msgType.ERROR, "syntaxError", data));
return;
}catch(Exception e) {
if(conf.getBoolean("GiantShop.global.debug") == true) {
GiantShop.log.log(Level.SEVERE, "GiantShop Error: " + e.getMessage());
GiantShop.log.log(Level.INFO, "Stacktrace: " + e.getStackTrace());
}
Heraut.say(player, msgs.getMsg(Messages.msgType.ERROR, "unknown"));
return;
}
}
- itemType = itemType == 0 ? -1 : itemType;
+ itemType = (itemType == null || itemType == 0) ? -1 : itemType;
ArrayList<String> fields = new ArrayList<String>();
fields.add("perStack");
fields.add("sellFor");
fields.add("buyFor");
fields.add("stock");
fields.add("shops");
HashMap<String, HashMap<String, String>> where = new HashMap<String, HashMap<String, String>>();
HashMap<String, String> d = new HashMap<String, String>();
d.put("type", "INT");
d.put("value", String.valueOf(itemID));
where.put("itemID", d);
d.put("value", String.valueOf(itemType));
where.put("type", d);
ArrayList<HashMap<String, String>> resSet = DB.select(fields).where(where, true).execQuery();
if(resSet.size() == 1) {
String name = iH.getItemNameByID(itemID, itemType);
HashMap<String, String> res = resSet.get(0);
Heraut.say(player, "Here's the result for " + name + "!");
Heraut.say(player, "ID: " + itemID);
Heraut.say(player, "Type: " + itemType);
Heraut.say(player, "Quantity per amount: " + res.get("perStack"));
Heraut.say(player, "Leaves shop for: " + res.get("sellFor"));
Heraut.say(player, "Retursns to shop for: " + res.get("buyFor"));
Heraut.say(player, "Amount of items in he shop: " + (!res.get("stock").equals("-1") ? res.get("stock") : "unlimited"));
//More future stuff
/*if(conf.getBoolean("GiantShop.Location.useGiantShopLocation") == true) {
* ArrayList<Indaface> shops = GiantShop.getPlugin().getLocationHandler().parseShops(res.get("shops"));
* for(Indaface shop : shops) {
* if(shop.inShop(player.getLocation())) {
* Heraut.say(player, "Something about what shops these items are in or something like that!");
* break;
* }
* }
* }
*/
}else{
Heraut.say(player, msgs.getMsg(Messages.msgType.ERROR, "noneOrMoreResults"));
}
}else{
HashMap<String, String> data = new HashMap<String, String>();
data.put("command", "check");
Heraut.say(player, msgs.getMsg(Messages.msgType.ERROR, "noPermissions", data));
}
}
public static void check(CommandSender sender, String[] args) {
Messages msgs = GiantShop.getPlugin().getMsgHandler();
Items iH = GiantShop.getPlugin().getItemHandler();
config conf = config.Obtain();
}
}
| true | true | public static void check(Player player, String[] args) {
Messages msgs = GiantShop.getPlugin().getMsgHandler();
Items iH = GiantShop.getPlugin().getItemHandler();
perm perms = perm.Obtain();
config conf = config.Obtain();
if(perms.has(player, "giantshop.shop.check")) {
db DB = db.Obtain();
int itemID;
Integer itemType = -1;
if(!args[1].matches("[0-9]+:[0-9]+")) {
try {
itemID = Integer.parseInt(args[1]);
itemType = -1;
}catch(NumberFormatException e) {
ItemID key = iH.getItemIDByName(args[1]);
if(key != null) {
itemID = key.getId();
itemType = key.getType();
}else{
Heraut.say(player, msgs.getMsg(Messages.msgType.ERROR, "itemNotFound"));
return;
}
}catch(Exception e) {
if(conf.getBoolean("GiantShop.global.debug") == true) {
GiantShop.log.log(Level.SEVERE, "GiantShop Error: " + e.getMessage());
GiantShop.log.log(Level.INFO, "Stacktrace: " + e.getStackTrace());
}
Heraut.say(player, msgs.getMsg(Messages.msgType.ERROR, "unknown"));
return;
}
}else{
try {
String[] data = args[1].split(":");
itemID = Integer.parseInt(data[0]);
itemType = Integer.parseInt(data[1]);
}catch(NumberFormatException e) {
HashMap<String, String> data = new HashMap<String, String>();
data.put("command", "check");
Heraut.say(player, msgs.getMsg(Messages.msgType.ERROR, "syntaxError", data));
return;
}catch(Exception e) {
if(conf.getBoolean("GiantShop.global.debug") == true) {
GiantShop.log.log(Level.SEVERE, "GiantShop Error: " + e.getMessage());
GiantShop.log.log(Level.INFO, "Stacktrace: " + e.getStackTrace());
}
Heraut.say(player, msgs.getMsg(Messages.msgType.ERROR, "unknown"));
return;
}
}
itemType = itemType == 0 ? -1 : itemType;
ArrayList<String> fields = new ArrayList<String>();
fields.add("perStack");
fields.add("sellFor");
fields.add("buyFor");
fields.add("stock");
fields.add("shops");
HashMap<String, HashMap<String, String>> where = new HashMap<String, HashMap<String, String>>();
HashMap<String, String> d = new HashMap<String, String>();
d.put("type", "INT");
d.put("value", String.valueOf(itemID));
where.put("itemID", d);
d.put("value", String.valueOf(itemType));
where.put("type", d);
ArrayList<HashMap<String, String>> resSet = DB.select(fields).where(where, true).execQuery();
if(resSet.size() == 1) {
String name = iH.getItemNameByID(itemID, itemType);
HashMap<String, String> res = resSet.get(0);
Heraut.say(player, "Here's the result for " + name + "!");
Heraut.say(player, "ID: " + itemID);
Heraut.say(player, "Type: " + itemType);
Heraut.say(player, "Quantity per amount: " + res.get("perStack"));
Heraut.say(player, "Leaves shop for: " + res.get("sellFor"));
Heraut.say(player, "Retursns to shop for: " + res.get("buyFor"));
Heraut.say(player, "Amount of items in he shop: " + (!res.get("stock").equals("-1") ? res.get("stock") : "unlimited"));
//More future stuff
/*if(conf.getBoolean("GiantShop.Location.useGiantShopLocation") == true) {
* ArrayList<Indaface> shops = GiantShop.getPlugin().getLocationHandler().parseShops(res.get("shops"));
* for(Indaface shop : shops) {
* if(shop.inShop(player.getLocation())) {
* Heraut.say(player, "Something about what shops these items are in or something like that!");
* break;
* }
* }
* }
*/
}else{
Heraut.say(player, msgs.getMsg(Messages.msgType.ERROR, "noneOrMoreResults"));
}
}else{
HashMap<String, String> data = new HashMap<String, String>();
data.put("command", "check");
Heraut.say(player, msgs.getMsg(Messages.msgType.ERROR, "noPermissions", data));
}
}
| public static void check(Player player, String[] args) {
Messages msgs = GiantShop.getPlugin().getMsgHandler();
Items iH = GiantShop.getPlugin().getItemHandler();
perm perms = perm.Obtain();
config conf = config.Obtain();
if(perms.has(player, "giantshop.shop.check")) {
db DB = db.Obtain();
int itemID;
Integer itemType = -1;
if(!args[1].matches("[0-9]+:[0-9]+")) {
try {
itemID = Integer.parseInt(args[1]);
itemType = -1;
}catch(NumberFormatException e) {
ItemID key = iH.getItemIDByName(args[1]);
if(key != null) {
itemID = key.getId();
itemType = key.getType();
}else{
Heraut.say(player, msgs.getMsg(Messages.msgType.ERROR, "itemNotFound"));
return;
}
}catch(Exception e) {
if(conf.getBoolean("GiantShop.global.debug") == true) {
GiantShop.log.log(Level.SEVERE, "GiantShop Error: " + e.getMessage());
GiantShop.log.log(Level.INFO, "Stacktrace: " + e.getStackTrace());
}
Heraut.say(player, msgs.getMsg(Messages.msgType.ERROR, "unknown"));
return;
}
}else{
try {
String[] data = args[1].split(":");
itemID = Integer.parseInt(data[0]);
itemType = Integer.parseInt(data[1]);
}catch(NumberFormatException e) {
HashMap<String, String> data = new HashMap<String, String>();
data.put("command", "check");
Heraut.say(player, msgs.getMsg(Messages.msgType.ERROR, "syntaxError", data));
return;
}catch(Exception e) {
if(conf.getBoolean("GiantShop.global.debug") == true) {
GiantShop.log.log(Level.SEVERE, "GiantShop Error: " + e.getMessage());
GiantShop.log.log(Level.INFO, "Stacktrace: " + e.getStackTrace());
}
Heraut.say(player, msgs.getMsg(Messages.msgType.ERROR, "unknown"));
return;
}
}
itemType = (itemType == null || itemType == 0) ? -1 : itemType;
ArrayList<String> fields = new ArrayList<String>();
fields.add("perStack");
fields.add("sellFor");
fields.add("buyFor");
fields.add("stock");
fields.add("shops");
HashMap<String, HashMap<String, String>> where = new HashMap<String, HashMap<String, String>>();
HashMap<String, String> d = new HashMap<String, String>();
d.put("type", "INT");
d.put("value", String.valueOf(itemID));
where.put("itemID", d);
d.put("value", String.valueOf(itemType));
where.put("type", d);
ArrayList<HashMap<String, String>> resSet = DB.select(fields).where(where, true).execQuery();
if(resSet.size() == 1) {
String name = iH.getItemNameByID(itemID, itemType);
HashMap<String, String> res = resSet.get(0);
Heraut.say(player, "Here's the result for " + name + "!");
Heraut.say(player, "ID: " + itemID);
Heraut.say(player, "Type: " + itemType);
Heraut.say(player, "Quantity per amount: " + res.get("perStack"));
Heraut.say(player, "Leaves shop for: " + res.get("sellFor"));
Heraut.say(player, "Retursns to shop for: " + res.get("buyFor"));
Heraut.say(player, "Amount of items in he shop: " + (!res.get("stock").equals("-1") ? res.get("stock") : "unlimited"));
//More future stuff
/*if(conf.getBoolean("GiantShop.Location.useGiantShopLocation") == true) {
* ArrayList<Indaface> shops = GiantShop.getPlugin().getLocationHandler().parseShops(res.get("shops"));
* for(Indaface shop : shops) {
* if(shop.inShop(player.getLocation())) {
* Heraut.say(player, "Something about what shops these items are in or something like that!");
* break;
* }
* }
* }
*/
}else{
Heraut.say(player, msgs.getMsg(Messages.msgType.ERROR, "noneOrMoreResults"));
}
}else{
HashMap<String, String> data = new HashMap<String, String>();
data.put("command", "check");
Heraut.say(player, msgs.getMsg(Messages.msgType.ERROR, "noPermissions", data));
}
}
|
diff --git a/loci/formats/in/OMETiffReader.java b/loci/formats/in/OMETiffReader.java
index c23b2f467..e22cf2f28 100644
--- a/loci/formats/in/OMETiffReader.java
+++ b/loci/formats/in/OMETiffReader.java
@@ -1,525 +1,526 @@
//
// OMETiffReader.java
//
/*
LOCI Bio-Formats package for reading and converting biological file formats.
Copyright (C) 2005-@year@ Melissa Linkert, Curtis Rueden, Chris Allan,
Eric Kjellman and Brian Loranger.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Library 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 Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package loci.formats.in;
import java.io.*;
import java.util.*;
import javax.xml.parsers.*;
import loci.formats.*;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
/**
* OMETiffReader is the file format reader for
* <a href="http://www.loci.wisc.edu/ome/ome-tiff-spec.html">OME-TIFF</a>
* files.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="https://skyking.microscopy.wisc.edu/trac/java/browser/trunk/loci/formats/in/OMETiffReader.java">Trac</a>,
* <a href="https://skyking.microscopy.wisc.edu/svn/java/trunk/loci/formats/in/OMETiffReader.java">SVN</a></dd></dl>
*/
public class OMETiffReader extends BaseTiffReader {
// -- Fields --
/** List of used files. */
private String[] used;
private Hashtable[] coordinateMap;
// -- Constructor --
public OMETiffReader() {
super("OME-TIFF", new String[] {"tif", "tiff"});
}
// -- IFormatHandler API methods --
/* @see loci.formats.IFormatHandler#isThisType(String, boolean) */
public boolean isThisType(String name, boolean open) {
if (!super.isThisType(name, open)) return false; // check extension
if (!open) return true; // not allowed to check the file contents
// just checking the filename isn't enough to differentiate between
// OME-TIFF and regular TIFF; open the file and check more thoroughly
try {
RandomAccessStream ras = new RandomAccessStream(name);
Hashtable ifd = TiffTools.getFirstIFD(ras);
ras.close();
if (ifd == null) return false;
String comment = (String)
ifd.get(new Integer(TiffTools.IMAGE_DESCRIPTION));
if (comment == null) return false;
return comment.indexOf("ome.xsd") >= 0;
}
catch (IOException e) { return false; }
}
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#getUsedFiles() */
public String[] getUsedFiles() {
FormatTools.assertId(currentId, true, 1);
return used;
}
/* @see loci.formats.IFormatReader#openBytes(int, byte[]) */
public byte[] openBytes(int no, byte[] buf)
throws FormatException, IOException
{
FormatTools.assertId(currentId, true, 1);
FormatTools.checkPlaneNumber(this, no);
FormatTools.checkBufferSize(this, buf.length);
if (used.length == 1) {
TiffTools.getSamples(ifds[no], in, buf);
return swapIfRequired(buf);
}
int[] zct = getZCTCoords(no);
int fileIndex = -1;
int[] savedCoords = new int[] {-1, -1, -1};
Integer[] keys =
(Integer[]) coordinateMap[series].keySet().toArray(new Integer[0]);
for (int i=0; i<keys.length; i++) {
int[] firstZCT = (int[]) coordinateMap[series].get(keys[i]);
if (firstZCT[0] <= zct[0] && firstZCT[1] <= zct[1] &&
firstZCT[2] <= zct[2] && firstZCT[0] >= savedCoords[0] &&
firstZCT[1] >= savedCoords[1] && firstZCT[2] >= savedCoords[2])
{
savedCoords = firstZCT;
fileIndex = keys[i].intValue();
}
}
in = new RandomAccessStream(used[fileIndex]);
ifds = TiffTools.getIFDs(in);
int firstIFD = ((int[]) coordinateMap[series].get(keys[fileIndex]))[3];
TiffTools.getSamples(ifds[firstIFD + (no % ifds.length)], in, buf);
in.close();
return swapIfRequired(buf);
}
// -- Internal BaseTiffReader API methods --
/* @see BaseTiffReader#initStandardMetadata() */
protected void initStandardMetadata() throws FormatException, IOException {
super.initStandardMetadata();
String comment = (String) getMeta("Comment");
boolean lsids = true;
// find list of Image IDs
Vector v = new Vector();
String check = "<Image ";
int ndx = comment.indexOf(check);
while (ndx >= 0) {
int ii = comment.indexOf("ID=\"", ndx);
v.add(comment.substring(ii + 4, comment.indexOf("\"", ii + 5)));
ndx = comment.indexOf(check, ndx + 1);
}
String[] imageIds = (String[]) v.toArray(new String[0]);
for (int i=0; i<imageIds.length; i++) {
if (!imageIds[i].toLowerCase().startsWith("urn:lsid")) {
lsids = false;
break;
}
}
// find list of Pixels IDs
v.clear();
check = "<Pixels ";
ndx = comment.indexOf(check);
while (ndx >= 0) {
int ii = comment.indexOf("ID=\"", ndx);
v.add(comment.substring(ii + 4, comment.indexOf("\"", ii + 5)));
ndx = comment.indexOf(check, ndx + 1);
}
String[] pixelsIds = (String[]) v.toArray(new String[0]);
for (int i=0; i<pixelsIds.length; i++) {
if (!pixelsIds[i].toLowerCase().startsWith("urn:lsid")) {
lsids = false;
break;
}
}
int numSeries = pixelsIds.length;
int[] numIFDs = new int[numSeries];
// only look for files in the same dataset if LSIDs are present
if (lsids) {
Vector files = new Vector();
Location l = new Location(currentId);
l = l.getAbsoluteFile().getParentFile();
String[] fileList = l.list();
coordinateMap = new Hashtable[numSeries];
for (int i=0; i<numSeries; i++) {
coordinateMap[i] = new Hashtable();
}
for (int i=0; i<fileList.length; i++) {
check = fileList[i].toLowerCase();
if (check.endsWith(".tif") || check.endsWith(".tiff")) {
Hashtable ifd = TiffTools.getFirstIFD(new RandomAccessStream(
l.getAbsolutePath() + File.separator + fileList[i]));
if (ifd == null) continue;
comment =
(String) TiffTools.getIFDValue(ifd, TiffTools.IMAGE_DESCRIPTION);
boolean addToList = true;
for (int s=0; s<imageIds.length; s++) {
if (comment.indexOf(imageIds[s]) == -1) {
addToList = false;
break;
}
}
if (addToList) {
for (int s=0; s<pixelsIds.length; s++) {
if (comment.indexOf(pixelsIds[s]) == -1) {
addToList = false;
}
}
}
if (addToList) {
files.add(l.getAbsolutePath() + File.separator + fileList[i]);
ByteArrayInputStream is =
new ByteArrayInputStream(comment.getBytes());
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
Document doc = null;
try {
DocumentBuilder builder = factory.newDocumentBuilder();
doc = builder.parse(is);
}
catch (ParserConfigurationException exc) { }
catch (SAXException exc) { }
catch (IOException exc) { }
if (doc != null) {
NodeList pixelsList = doc.getElementsByTagName("Pixels");
for (int j=0; j<numSeries; j++) {
NodeList list = ((Element) pixelsList.item(j)).getChildNodes();
// if there are multiple TiffData elements, find the one with
// the smallest ZCT coordinates
v = new Vector();
for (int q=0; q<list.getLength(); q++) {
if (((Node) list.item(q)).getNodeName().equals("TiffData")) {
v.add(list.item(q));
}
}
Element[] tiffData = (Element[]) v.toArray(new Element[0]);
int[] smallestCoords = new int[4];
+ Arrays.fill(smallestCoords, Integer.MAX_VALUE);
for (int q=0; q<tiffData.length; q++) {
String firstZ = tiffData[q].getAttribute("FirstZ");
String firstC = tiffData[q].getAttribute("FirstC");
String firstT = tiffData[q].getAttribute("FirstT");
String firstIFD = tiffData[q].getAttribute("IFD");
if (firstZ == null || firstZ.equals("")) firstZ = "0";
if (firstC == null || firstC.equals("")) firstC = "0";
if (firstT == null || firstT.equals("")) firstT = "0";
if (firstIFD == null || firstIFD.equals("")) firstIFD = "0";
int z = Integer.parseInt(firstZ);
int c = Integer.parseInt(firstC);
int t = Integer.parseInt(firstT);
if (z <= smallestCoords[0] && c <= smallestCoords[1] &&
t <= smallestCoords[2])
{
smallestCoords[0] = z;
smallestCoords[1] = c;
smallestCoords[2] = t;
smallestCoords[3] = Integer.parseInt(firstIFD);
}
}
coordinateMap[j].put(new Integer(files.size() - 1),
smallestCoords);
numIFDs[j] += TiffTools.getIFDs(new RandomAccessStream(
(String) files.get(files.size() - 1))).length;
}
}
}
}
}
used = (String[]) files.toArray(new String[0]);
}
else {
used = new String[] {currentId};
LogTools.println("Not searching for other files - " +
"Image LSID not present.");
numIFDs[0] = ifds.length;
}
int oldX = core.sizeX[0];
int oldY = core.sizeY[0];
comment = (String) getMeta("Comment");
// convert string to DOM
ByteArrayInputStream is = new ByteArrayInputStream(comment.getBytes());
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
Document doc = null;
try {
DocumentBuilder builder = factory.newDocumentBuilder();
doc = builder.parse(is);
}
catch (ParserConfigurationException exc) { }
catch (SAXException exc) { }
catch (IOException exc) { }
// extract TiffData elements from XML
Element[] pixels = null;
Element[][] tiffData = null;
if (doc != null) {
NodeList pixelsList = doc.getElementsByTagName("Pixels");
int nSeries = pixelsList.getLength();
v = new Vector();
pixels = new Element[nSeries];
tiffData = new Element[nSeries][];
for (int i=0; i<nSeries; i++) {
pixels[i] = (Element) pixelsList.item(i);
NodeList list = pixels[i].getChildNodes();
int size = list.getLength();
v.clear();
for (int j=0; j<size; j++) {
Node node = list.item(j);
if (!(node instanceof Element)) continue;
if ("TiffData".equals(node.getNodeName())) v.add(node);
}
tiffData[i] = new Element[v.size()];
v.copyInto(tiffData[i]);
}
}
// MAJOR HACK : check for OME-XML in the comment of the second IFD
// There is a version of WiscScan which writes OME-XML to every IFD,
// but with SizeZ and SizeT equal to 1.
String s = null;
if (ifds.length > 1) {
s = (String) TiffTools.getIFDValue(ifds[1], TiffTools.IMAGE_DESCRIPTION);
}
boolean isWiscScan = s != null && s.indexOf("ome.xsd") != -1;
// extract SizeZ, SizeC and SizeT from XML block
if (tiffData != null) {
boolean rgb = isRGB();
boolean indexed = isIndexed();
boolean falseColor = isFalseColor();
core = new CoreMetadata(tiffData.length);
Arrays.fill(core.orderCertain, true);
Arrays.fill(core.indexed, indexed);
Arrays.fill(core.falseColor, falseColor);
for (int i=0; i<tiffData.length; i++) {
core.sizeX[i] = Integer.parseInt(pixels[i].getAttribute("SizeX"));
if (core.sizeX[i] != oldX) {
LogTools.println("Mismatched width: OME-XML reports SizeX=" +
core.sizeX[i] + "; expecting " + oldX);
core.sizeX[i] = oldX;
}
core.sizeY[i] = Integer.parseInt(pixels[i].getAttribute("SizeY"));
if (core.sizeY[i] != oldY) {
LogTools.println("Mismatched height: OME-XML reports SizeY=" +
core.sizeY[i] + "; expecting " + oldY);
core.sizeY[i] = oldY;
}
core.sizeZ[i] = Integer.parseInt(pixels[i].getAttribute("SizeZ"));
core.sizeC[i] = Integer.parseInt(pixels[i].getAttribute("SizeC"));
core.sizeT[i] = Integer.parseInt(pixels[i].getAttribute("SizeT"));
// HACK: correct for erroneous negative size values
if (core.sizeZ[i] < 1) core.sizeZ[i] = 1;
if (core.sizeC[i] < 1) core.sizeC[i] = 1;
if (core.sizeT[i] < 1) core.sizeT[i] = 1;
if (rgb && indexed && core.sizeC[i] == 3) {
rgb = false;
core.indexed[i] = false;
core.falseColor[i] = false;
}
int sc = core.sizeC[i];
if (rgb && sc > 1) sc /= 3;
core.imageCount[i] = core.sizeZ[i] * sc * core.sizeT[i];
core.rgb[i] = rgb;
core.pixelType[i] = FormatTools.pixelTypeFromString(
pixels[i].getAttribute("PixelType"));
if (core.pixelType[i] == FormatTools.INT8 ||
core.pixelType[i] == FormatTools.INT16 ||
core.pixelType[i] == FormatTools.INT32)
{
core.pixelType[i]++;
}
// MAJOR HACK: adjust SizeT to match the number of IFDs, if this file
// was written by a buggy version of WiscScan
if (isWiscScan) core.sizeT[i] = core.imageCount[0];
core.currentOrder[i] = pixels[i].getAttribute("DimensionOrder");
core.orderCertain[i] = true;
if (numIFDs != null && lsids) {
if (numIFDs[i] < core.imageCount[i]) {
LogTools.println("Too few IFDs; got " + numIFDs[i] + ", expected " +
core.imageCount[i]);
}
else if (numIFDs[i] > core.imageCount[i]) {
LogTools.println("Too many IFDs; got " + numIFDs[i] +
", expected " + core.imageCount[i]);
}
}
else if (core.imageCount[i] > ifds.length) {
core.imageCount[i] = ifds.length;
if (core.sizeZ[i] > ifds.length) {
core.sizeZ[i] = ifds.length / (rgb ? core.sizeC[i] : 1);
core.sizeT[i] = 1;
if (!rgb) core.sizeC[i] = 1;
}
else if (core.sizeT[i] > ifds.length) {
core.sizeT[i] = ifds.length / (rgb ? core.sizeC[i] : 1);
core.sizeZ[i] = 1;
if (!rgb) core.sizeC[i] = 1;
}
}
boolean[][][] zct = new boolean[core.sizeZ[i]][sc][core.sizeT[i]];
for (int j=0; j<tiffData[i].length; j++) {
String aIfd = tiffData[i][j].getAttribute("IFD");
String aFirstZ = tiffData[i][j].getAttribute("FirstZ");
String aFirstT = tiffData[i][j].getAttribute("FirstT");
String aFirstC = tiffData[i][j].getAttribute("FirstC");
String aNumPlanes = tiffData[i][j].getAttribute("NumPlanes");
boolean nullIfd = aIfd == null || aIfd.equals("");
boolean nullFirstZ = aFirstZ == null || aFirstZ.equals("");
boolean nullFirstC = aFirstC == null || aFirstC.equals("");
boolean nullFirstT = aFirstT == null || aFirstT.equals("");
boolean nullNumPlanes = aNumPlanes == null || aNumPlanes.equals("");
int firstZ = nullFirstZ ? 0 : Integer.parseInt(aFirstZ);
int firstC = nullFirstC ? 0 : Integer.parseInt(aFirstC);
int firstT = nullFirstT ? 0 : Integer.parseInt(aFirstT);
int numPlanes = nullNumPlanes ? (nullIfd ? core.imageCount[0] : 1) :
Integer.parseInt(aNumPlanes);
// HACK: adjust first values, if this file
// was written by a buggy version of WiscScan
if (firstZ >= core.sizeZ[0]) firstZ = core.sizeZ[0] - 1;
if (firstC >= core.sizeC[0]) firstC = core.sizeC[0] - 1;
if (firstT >= core.sizeT[0]) firstT = core.sizeT[0] - 1;
// populate ZCT matrix
char d1st = core.currentOrder[i].charAt(2);
char d2nd = core.currentOrder[i].charAt(3);
int z = firstZ, t = firstT, c = firstC;
for (int k=0; k<numPlanes; k++) {
zct[z][c][t] = true;
switch (d1st) {
case 'Z':
z++;
if (z >= core.sizeZ[i]) {
z = 0;
switch (d2nd) {
case 'T':
t++;
if (t >= core.sizeT[i]) {
t = 0;
c++;
}
break;
case 'C':
c++;
if (c >= sc) {
c = 0;
t++;
}
break;
}
}
break;
case 'T':
t++;
if (t >= core.sizeT[i]) {
t = 0;
switch (d2nd) {
case 'Z':
z++;
if (z >= core.sizeZ[i]) {
z = 0;
c++;
}
break;
case 'C':
c++;
if (c >= sc) {
c = 0;
z++;
}
break;
}
}
break;
case 'C':
c++;
if (c >= sc) {
c = 0;
switch (d2nd) {
case 'Z':
z++;
if (z >= core.sizeZ[i]) {
z = 0;
t++;
}
break;
case 'T':
t++;
if (t >= core.sizeT[i]) {
t = 0;
z++;
}
break;
}
}
break;
}
}
}
}
}
}
/* @see BaseTiffReader#initMetadataStore() */
protected void initMetadataStore() {
String comment = (String) getMeta("Comment");
metadata.remove("Comment");
MetadataStore store = getMetadataStore();
MetadataTools.convertMetadata(comment, store);
}
}
| true | true | protected void initStandardMetadata() throws FormatException, IOException {
super.initStandardMetadata();
String comment = (String) getMeta("Comment");
boolean lsids = true;
// find list of Image IDs
Vector v = new Vector();
String check = "<Image ";
int ndx = comment.indexOf(check);
while (ndx >= 0) {
int ii = comment.indexOf("ID=\"", ndx);
v.add(comment.substring(ii + 4, comment.indexOf("\"", ii + 5)));
ndx = comment.indexOf(check, ndx + 1);
}
String[] imageIds = (String[]) v.toArray(new String[0]);
for (int i=0; i<imageIds.length; i++) {
if (!imageIds[i].toLowerCase().startsWith("urn:lsid")) {
lsids = false;
break;
}
}
// find list of Pixels IDs
v.clear();
check = "<Pixels ";
ndx = comment.indexOf(check);
while (ndx >= 0) {
int ii = comment.indexOf("ID=\"", ndx);
v.add(comment.substring(ii + 4, comment.indexOf("\"", ii + 5)));
ndx = comment.indexOf(check, ndx + 1);
}
String[] pixelsIds = (String[]) v.toArray(new String[0]);
for (int i=0; i<pixelsIds.length; i++) {
if (!pixelsIds[i].toLowerCase().startsWith("urn:lsid")) {
lsids = false;
break;
}
}
int numSeries = pixelsIds.length;
int[] numIFDs = new int[numSeries];
// only look for files in the same dataset if LSIDs are present
if (lsids) {
Vector files = new Vector();
Location l = new Location(currentId);
l = l.getAbsoluteFile().getParentFile();
String[] fileList = l.list();
coordinateMap = new Hashtable[numSeries];
for (int i=0; i<numSeries; i++) {
coordinateMap[i] = new Hashtable();
}
for (int i=0; i<fileList.length; i++) {
check = fileList[i].toLowerCase();
if (check.endsWith(".tif") || check.endsWith(".tiff")) {
Hashtable ifd = TiffTools.getFirstIFD(new RandomAccessStream(
l.getAbsolutePath() + File.separator + fileList[i]));
if (ifd == null) continue;
comment =
(String) TiffTools.getIFDValue(ifd, TiffTools.IMAGE_DESCRIPTION);
boolean addToList = true;
for (int s=0; s<imageIds.length; s++) {
if (comment.indexOf(imageIds[s]) == -1) {
addToList = false;
break;
}
}
if (addToList) {
for (int s=0; s<pixelsIds.length; s++) {
if (comment.indexOf(pixelsIds[s]) == -1) {
addToList = false;
}
}
}
if (addToList) {
files.add(l.getAbsolutePath() + File.separator + fileList[i]);
ByteArrayInputStream is =
new ByteArrayInputStream(comment.getBytes());
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
Document doc = null;
try {
DocumentBuilder builder = factory.newDocumentBuilder();
doc = builder.parse(is);
}
catch (ParserConfigurationException exc) { }
catch (SAXException exc) { }
catch (IOException exc) { }
if (doc != null) {
NodeList pixelsList = doc.getElementsByTagName("Pixels");
for (int j=0; j<numSeries; j++) {
NodeList list = ((Element) pixelsList.item(j)).getChildNodes();
// if there are multiple TiffData elements, find the one with
// the smallest ZCT coordinates
v = new Vector();
for (int q=0; q<list.getLength(); q++) {
if (((Node) list.item(q)).getNodeName().equals("TiffData")) {
v.add(list.item(q));
}
}
Element[] tiffData = (Element[]) v.toArray(new Element[0]);
int[] smallestCoords = new int[4];
for (int q=0; q<tiffData.length; q++) {
String firstZ = tiffData[q].getAttribute("FirstZ");
String firstC = tiffData[q].getAttribute("FirstC");
String firstT = tiffData[q].getAttribute("FirstT");
String firstIFD = tiffData[q].getAttribute("IFD");
if (firstZ == null || firstZ.equals("")) firstZ = "0";
if (firstC == null || firstC.equals("")) firstC = "0";
if (firstT == null || firstT.equals("")) firstT = "0";
if (firstIFD == null || firstIFD.equals("")) firstIFD = "0";
int z = Integer.parseInt(firstZ);
int c = Integer.parseInt(firstC);
int t = Integer.parseInt(firstT);
if (z <= smallestCoords[0] && c <= smallestCoords[1] &&
t <= smallestCoords[2])
{
smallestCoords[0] = z;
smallestCoords[1] = c;
smallestCoords[2] = t;
smallestCoords[3] = Integer.parseInt(firstIFD);
}
}
coordinateMap[j].put(new Integer(files.size() - 1),
smallestCoords);
numIFDs[j] += TiffTools.getIFDs(new RandomAccessStream(
(String) files.get(files.size() - 1))).length;
}
}
}
}
}
used = (String[]) files.toArray(new String[0]);
}
else {
used = new String[] {currentId};
LogTools.println("Not searching for other files - " +
"Image LSID not present.");
numIFDs[0] = ifds.length;
}
int oldX = core.sizeX[0];
int oldY = core.sizeY[0];
comment = (String) getMeta("Comment");
// convert string to DOM
ByteArrayInputStream is = new ByteArrayInputStream(comment.getBytes());
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
Document doc = null;
try {
DocumentBuilder builder = factory.newDocumentBuilder();
doc = builder.parse(is);
}
catch (ParserConfigurationException exc) { }
catch (SAXException exc) { }
catch (IOException exc) { }
// extract TiffData elements from XML
Element[] pixels = null;
Element[][] tiffData = null;
if (doc != null) {
NodeList pixelsList = doc.getElementsByTagName("Pixels");
int nSeries = pixelsList.getLength();
v = new Vector();
pixels = new Element[nSeries];
tiffData = new Element[nSeries][];
for (int i=0; i<nSeries; i++) {
pixels[i] = (Element) pixelsList.item(i);
NodeList list = pixels[i].getChildNodes();
int size = list.getLength();
v.clear();
for (int j=0; j<size; j++) {
Node node = list.item(j);
if (!(node instanceof Element)) continue;
if ("TiffData".equals(node.getNodeName())) v.add(node);
}
tiffData[i] = new Element[v.size()];
v.copyInto(tiffData[i]);
}
}
// MAJOR HACK : check for OME-XML in the comment of the second IFD
// There is a version of WiscScan which writes OME-XML to every IFD,
// but with SizeZ and SizeT equal to 1.
String s = null;
if (ifds.length > 1) {
s = (String) TiffTools.getIFDValue(ifds[1], TiffTools.IMAGE_DESCRIPTION);
}
boolean isWiscScan = s != null && s.indexOf("ome.xsd") != -1;
// extract SizeZ, SizeC and SizeT from XML block
if (tiffData != null) {
boolean rgb = isRGB();
boolean indexed = isIndexed();
boolean falseColor = isFalseColor();
core = new CoreMetadata(tiffData.length);
Arrays.fill(core.orderCertain, true);
Arrays.fill(core.indexed, indexed);
Arrays.fill(core.falseColor, falseColor);
for (int i=0; i<tiffData.length; i++) {
core.sizeX[i] = Integer.parseInt(pixels[i].getAttribute("SizeX"));
if (core.sizeX[i] != oldX) {
LogTools.println("Mismatched width: OME-XML reports SizeX=" +
core.sizeX[i] + "; expecting " + oldX);
core.sizeX[i] = oldX;
}
core.sizeY[i] = Integer.parseInt(pixels[i].getAttribute("SizeY"));
if (core.sizeY[i] != oldY) {
LogTools.println("Mismatched height: OME-XML reports SizeY=" +
core.sizeY[i] + "; expecting " + oldY);
core.sizeY[i] = oldY;
}
core.sizeZ[i] = Integer.parseInt(pixels[i].getAttribute("SizeZ"));
core.sizeC[i] = Integer.parseInt(pixels[i].getAttribute("SizeC"));
core.sizeT[i] = Integer.parseInt(pixels[i].getAttribute("SizeT"));
// HACK: correct for erroneous negative size values
if (core.sizeZ[i] < 1) core.sizeZ[i] = 1;
if (core.sizeC[i] < 1) core.sizeC[i] = 1;
if (core.sizeT[i] < 1) core.sizeT[i] = 1;
if (rgb && indexed && core.sizeC[i] == 3) {
rgb = false;
core.indexed[i] = false;
core.falseColor[i] = false;
}
int sc = core.sizeC[i];
if (rgb && sc > 1) sc /= 3;
core.imageCount[i] = core.sizeZ[i] * sc * core.sizeT[i];
core.rgb[i] = rgb;
core.pixelType[i] = FormatTools.pixelTypeFromString(
pixels[i].getAttribute("PixelType"));
if (core.pixelType[i] == FormatTools.INT8 ||
core.pixelType[i] == FormatTools.INT16 ||
core.pixelType[i] == FormatTools.INT32)
{
core.pixelType[i]++;
}
// MAJOR HACK: adjust SizeT to match the number of IFDs, if this file
// was written by a buggy version of WiscScan
if (isWiscScan) core.sizeT[i] = core.imageCount[0];
core.currentOrder[i] = pixels[i].getAttribute("DimensionOrder");
core.orderCertain[i] = true;
if (numIFDs != null && lsids) {
if (numIFDs[i] < core.imageCount[i]) {
LogTools.println("Too few IFDs; got " + numIFDs[i] + ", expected " +
core.imageCount[i]);
}
else if (numIFDs[i] > core.imageCount[i]) {
LogTools.println("Too many IFDs; got " + numIFDs[i] +
", expected " + core.imageCount[i]);
}
}
else if (core.imageCount[i] > ifds.length) {
core.imageCount[i] = ifds.length;
if (core.sizeZ[i] > ifds.length) {
core.sizeZ[i] = ifds.length / (rgb ? core.sizeC[i] : 1);
core.sizeT[i] = 1;
if (!rgb) core.sizeC[i] = 1;
}
else if (core.sizeT[i] > ifds.length) {
core.sizeT[i] = ifds.length / (rgb ? core.sizeC[i] : 1);
core.sizeZ[i] = 1;
if (!rgb) core.sizeC[i] = 1;
}
}
boolean[][][] zct = new boolean[core.sizeZ[i]][sc][core.sizeT[i]];
for (int j=0; j<tiffData[i].length; j++) {
String aIfd = tiffData[i][j].getAttribute("IFD");
String aFirstZ = tiffData[i][j].getAttribute("FirstZ");
String aFirstT = tiffData[i][j].getAttribute("FirstT");
String aFirstC = tiffData[i][j].getAttribute("FirstC");
String aNumPlanes = tiffData[i][j].getAttribute("NumPlanes");
boolean nullIfd = aIfd == null || aIfd.equals("");
boolean nullFirstZ = aFirstZ == null || aFirstZ.equals("");
boolean nullFirstC = aFirstC == null || aFirstC.equals("");
boolean nullFirstT = aFirstT == null || aFirstT.equals("");
boolean nullNumPlanes = aNumPlanes == null || aNumPlanes.equals("");
int firstZ = nullFirstZ ? 0 : Integer.parseInt(aFirstZ);
int firstC = nullFirstC ? 0 : Integer.parseInt(aFirstC);
int firstT = nullFirstT ? 0 : Integer.parseInt(aFirstT);
int numPlanes = nullNumPlanes ? (nullIfd ? core.imageCount[0] : 1) :
Integer.parseInt(aNumPlanes);
// HACK: adjust first values, if this file
// was written by a buggy version of WiscScan
if (firstZ >= core.sizeZ[0]) firstZ = core.sizeZ[0] - 1;
if (firstC >= core.sizeC[0]) firstC = core.sizeC[0] - 1;
if (firstT >= core.sizeT[0]) firstT = core.sizeT[0] - 1;
// populate ZCT matrix
char d1st = core.currentOrder[i].charAt(2);
char d2nd = core.currentOrder[i].charAt(3);
int z = firstZ, t = firstT, c = firstC;
for (int k=0; k<numPlanes; k++) {
zct[z][c][t] = true;
switch (d1st) {
case 'Z':
z++;
if (z >= core.sizeZ[i]) {
z = 0;
switch (d2nd) {
case 'T':
t++;
if (t >= core.sizeT[i]) {
t = 0;
c++;
}
break;
case 'C':
c++;
if (c >= sc) {
c = 0;
t++;
}
break;
}
}
break;
case 'T':
t++;
if (t >= core.sizeT[i]) {
t = 0;
switch (d2nd) {
case 'Z':
z++;
if (z >= core.sizeZ[i]) {
z = 0;
c++;
}
break;
case 'C':
c++;
if (c >= sc) {
c = 0;
z++;
}
break;
}
}
break;
case 'C':
c++;
if (c >= sc) {
c = 0;
switch (d2nd) {
case 'Z':
z++;
if (z >= core.sizeZ[i]) {
z = 0;
t++;
}
break;
case 'T':
t++;
if (t >= core.sizeT[i]) {
t = 0;
z++;
}
break;
}
}
break;
}
}
}
}
}
}
| protected void initStandardMetadata() throws FormatException, IOException {
super.initStandardMetadata();
String comment = (String) getMeta("Comment");
boolean lsids = true;
// find list of Image IDs
Vector v = new Vector();
String check = "<Image ";
int ndx = comment.indexOf(check);
while (ndx >= 0) {
int ii = comment.indexOf("ID=\"", ndx);
v.add(comment.substring(ii + 4, comment.indexOf("\"", ii + 5)));
ndx = comment.indexOf(check, ndx + 1);
}
String[] imageIds = (String[]) v.toArray(new String[0]);
for (int i=0; i<imageIds.length; i++) {
if (!imageIds[i].toLowerCase().startsWith("urn:lsid")) {
lsids = false;
break;
}
}
// find list of Pixels IDs
v.clear();
check = "<Pixels ";
ndx = comment.indexOf(check);
while (ndx >= 0) {
int ii = comment.indexOf("ID=\"", ndx);
v.add(comment.substring(ii + 4, comment.indexOf("\"", ii + 5)));
ndx = comment.indexOf(check, ndx + 1);
}
String[] pixelsIds = (String[]) v.toArray(new String[0]);
for (int i=0; i<pixelsIds.length; i++) {
if (!pixelsIds[i].toLowerCase().startsWith("urn:lsid")) {
lsids = false;
break;
}
}
int numSeries = pixelsIds.length;
int[] numIFDs = new int[numSeries];
// only look for files in the same dataset if LSIDs are present
if (lsids) {
Vector files = new Vector();
Location l = new Location(currentId);
l = l.getAbsoluteFile().getParentFile();
String[] fileList = l.list();
coordinateMap = new Hashtable[numSeries];
for (int i=0; i<numSeries; i++) {
coordinateMap[i] = new Hashtable();
}
for (int i=0; i<fileList.length; i++) {
check = fileList[i].toLowerCase();
if (check.endsWith(".tif") || check.endsWith(".tiff")) {
Hashtable ifd = TiffTools.getFirstIFD(new RandomAccessStream(
l.getAbsolutePath() + File.separator + fileList[i]));
if (ifd == null) continue;
comment =
(String) TiffTools.getIFDValue(ifd, TiffTools.IMAGE_DESCRIPTION);
boolean addToList = true;
for (int s=0; s<imageIds.length; s++) {
if (comment.indexOf(imageIds[s]) == -1) {
addToList = false;
break;
}
}
if (addToList) {
for (int s=0; s<pixelsIds.length; s++) {
if (comment.indexOf(pixelsIds[s]) == -1) {
addToList = false;
}
}
}
if (addToList) {
files.add(l.getAbsolutePath() + File.separator + fileList[i]);
ByteArrayInputStream is =
new ByteArrayInputStream(comment.getBytes());
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
Document doc = null;
try {
DocumentBuilder builder = factory.newDocumentBuilder();
doc = builder.parse(is);
}
catch (ParserConfigurationException exc) { }
catch (SAXException exc) { }
catch (IOException exc) { }
if (doc != null) {
NodeList pixelsList = doc.getElementsByTagName("Pixels");
for (int j=0; j<numSeries; j++) {
NodeList list = ((Element) pixelsList.item(j)).getChildNodes();
// if there are multiple TiffData elements, find the one with
// the smallest ZCT coordinates
v = new Vector();
for (int q=0; q<list.getLength(); q++) {
if (((Node) list.item(q)).getNodeName().equals("TiffData")) {
v.add(list.item(q));
}
}
Element[] tiffData = (Element[]) v.toArray(new Element[0]);
int[] smallestCoords = new int[4];
Arrays.fill(smallestCoords, Integer.MAX_VALUE);
for (int q=0; q<tiffData.length; q++) {
String firstZ = tiffData[q].getAttribute("FirstZ");
String firstC = tiffData[q].getAttribute("FirstC");
String firstT = tiffData[q].getAttribute("FirstT");
String firstIFD = tiffData[q].getAttribute("IFD");
if (firstZ == null || firstZ.equals("")) firstZ = "0";
if (firstC == null || firstC.equals("")) firstC = "0";
if (firstT == null || firstT.equals("")) firstT = "0";
if (firstIFD == null || firstIFD.equals("")) firstIFD = "0";
int z = Integer.parseInt(firstZ);
int c = Integer.parseInt(firstC);
int t = Integer.parseInt(firstT);
if (z <= smallestCoords[0] && c <= smallestCoords[1] &&
t <= smallestCoords[2])
{
smallestCoords[0] = z;
smallestCoords[1] = c;
smallestCoords[2] = t;
smallestCoords[3] = Integer.parseInt(firstIFD);
}
}
coordinateMap[j].put(new Integer(files.size() - 1),
smallestCoords);
numIFDs[j] += TiffTools.getIFDs(new RandomAccessStream(
(String) files.get(files.size() - 1))).length;
}
}
}
}
}
used = (String[]) files.toArray(new String[0]);
}
else {
used = new String[] {currentId};
LogTools.println("Not searching for other files - " +
"Image LSID not present.");
numIFDs[0] = ifds.length;
}
int oldX = core.sizeX[0];
int oldY = core.sizeY[0];
comment = (String) getMeta("Comment");
// convert string to DOM
ByteArrayInputStream is = new ByteArrayInputStream(comment.getBytes());
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
Document doc = null;
try {
DocumentBuilder builder = factory.newDocumentBuilder();
doc = builder.parse(is);
}
catch (ParserConfigurationException exc) { }
catch (SAXException exc) { }
catch (IOException exc) { }
// extract TiffData elements from XML
Element[] pixels = null;
Element[][] tiffData = null;
if (doc != null) {
NodeList pixelsList = doc.getElementsByTagName("Pixels");
int nSeries = pixelsList.getLength();
v = new Vector();
pixels = new Element[nSeries];
tiffData = new Element[nSeries][];
for (int i=0; i<nSeries; i++) {
pixels[i] = (Element) pixelsList.item(i);
NodeList list = pixels[i].getChildNodes();
int size = list.getLength();
v.clear();
for (int j=0; j<size; j++) {
Node node = list.item(j);
if (!(node instanceof Element)) continue;
if ("TiffData".equals(node.getNodeName())) v.add(node);
}
tiffData[i] = new Element[v.size()];
v.copyInto(tiffData[i]);
}
}
// MAJOR HACK : check for OME-XML in the comment of the second IFD
// There is a version of WiscScan which writes OME-XML to every IFD,
// but with SizeZ and SizeT equal to 1.
String s = null;
if (ifds.length > 1) {
s = (String) TiffTools.getIFDValue(ifds[1], TiffTools.IMAGE_DESCRIPTION);
}
boolean isWiscScan = s != null && s.indexOf("ome.xsd") != -1;
// extract SizeZ, SizeC and SizeT from XML block
if (tiffData != null) {
boolean rgb = isRGB();
boolean indexed = isIndexed();
boolean falseColor = isFalseColor();
core = new CoreMetadata(tiffData.length);
Arrays.fill(core.orderCertain, true);
Arrays.fill(core.indexed, indexed);
Arrays.fill(core.falseColor, falseColor);
for (int i=0; i<tiffData.length; i++) {
core.sizeX[i] = Integer.parseInt(pixels[i].getAttribute("SizeX"));
if (core.sizeX[i] != oldX) {
LogTools.println("Mismatched width: OME-XML reports SizeX=" +
core.sizeX[i] + "; expecting " + oldX);
core.sizeX[i] = oldX;
}
core.sizeY[i] = Integer.parseInt(pixels[i].getAttribute("SizeY"));
if (core.sizeY[i] != oldY) {
LogTools.println("Mismatched height: OME-XML reports SizeY=" +
core.sizeY[i] + "; expecting " + oldY);
core.sizeY[i] = oldY;
}
core.sizeZ[i] = Integer.parseInt(pixels[i].getAttribute("SizeZ"));
core.sizeC[i] = Integer.parseInt(pixels[i].getAttribute("SizeC"));
core.sizeT[i] = Integer.parseInt(pixels[i].getAttribute("SizeT"));
// HACK: correct for erroneous negative size values
if (core.sizeZ[i] < 1) core.sizeZ[i] = 1;
if (core.sizeC[i] < 1) core.sizeC[i] = 1;
if (core.sizeT[i] < 1) core.sizeT[i] = 1;
if (rgb && indexed && core.sizeC[i] == 3) {
rgb = false;
core.indexed[i] = false;
core.falseColor[i] = false;
}
int sc = core.sizeC[i];
if (rgb && sc > 1) sc /= 3;
core.imageCount[i] = core.sizeZ[i] * sc * core.sizeT[i];
core.rgb[i] = rgb;
core.pixelType[i] = FormatTools.pixelTypeFromString(
pixels[i].getAttribute("PixelType"));
if (core.pixelType[i] == FormatTools.INT8 ||
core.pixelType[i] == FormatTools.INT16 ||
core.pixelType[i] == FormatTools.INT32)
{
core.pixelType[i]++;
}
// MAJOR HACK: adjust SizeT to match the number of IFDs, if this file
// was written by a buggy version of WiscScan
if (isWiscScan) core.sizeT[i] = core.imageCount[0];
core.currentOrder[i] = pixels[i].getAttribute("DimensionOrder");
core.orderCertain[i] = true;
if (numIFDs != null && lsids) {
if (numIFDs[i] < core.imageCount[i]) {
LogTools.println("Too few IFDs; got " + numIFDs[i] + ", expected " +
core.imageCount[i]);
}
else if (numIFDs[i] > core.imageCount[i]) {
LogTools.println("Too many IFDs; got " + numIFDs[i] +
", expected " + core.imageCount[i]);
}
}
else if (core.imageCount[i] > ifds.length) {
core.imageCount[i] = ifds.length;
if (core.sizeZ[i] > ifds.length) {
core.sizeZ[i] = ifds.length / (rgb ? core.sizeC[i] : 1);
core.sizeT[i] = 1;
if (!rgb) core.sizeC[i] = 1;
}
else if (core.sizeT[i] > ifds.length) {
core.sizeT[i] = ifds.length / (rgb ? core.sizeC[i] : 1);
core.sizeZ[i] = 1;
if (!rgb) core.sizeC[i] = 1;
}
}
boolean[][][] zct = new boolean[core.sizeZ[i]][sc][core.sizeT[i]];
for (int j=0; j<tiffData[i].length; j++) {
String aIfd = tiffData[i][j].getAttribute("IFD");
String aFirstZ = tiffData[i][j].getAttribute("FirstZ");
String aFirstT = tiffData[i][j].getAttribute("FirstT");
String aFirstC = tiffData[i][j].getAttribute("FirstC");
String aNumPlanes = tiffData[i][j].getAttribute("NumPlanes");
boolean nullIfd = aIfd == null || aIfd.equals("");
boolean nullFirstZ = aFirstZ == null || aFirstZ.equals("");
boolean nullFirstC = aFirstC == null || aFirstC.equals("");
boolean nullFirstT = aFirstT == null || aFirstT.equals("");
boolean nullNumPlanes = aNumPlanes == null || aNumPlanes.equals("");
int firstZ = nullFirstZ ? 0 : Integer.parseInt(aFirstZ);
int firstC = nullFirstC ? 0 : Integer.parseInt(aFirstC);
int firstT = nullFirstT ? 0 : Integer.parseInt(aFirstT);
int numPlanes = nullNumPlanes ? (nullIfd ? core.imageCount[0] : 1) :
Integer.parseInt(aNumPlanes);
// HACK: adjust first values, if this file
// was written by a buggy version of WiscScan
if (firstZ >= core.sizeZ[0]) firstZ = core.sizeZ[0] - 1;
if (firstC >= core.sizeC[0]) firstC = core.sizeC[0] - 1;
if (firstT >= core.sizeT[0]) firstT = core.sizeT[0] - 1;
// populate ZCT matrix
char d1st = core.currentOrder[i].charAt(2);
char d2nd = core.currentOrder[i].charAt(3);
int z = firstZ, t = firstT, c = firstC;
for (int k=0; k<numPlanes; k++) {
zct[z][c][t] = true;
switch (d1st) {
case 'Z':
z++;
if (z >= core.sizeZ[i]) {
z = 0;
switch (d2nd) {
case 'T':
t++;
if (t >= core.sizeT[i]) {
t = 0;
c++;
}
break;
case 'C':
c++;
if (c >= sc) {
c = 0;
t++;
}
break;
}
}
break;
case 'T':
t++;
if (t >= core.sizeT[i]) {
t = 0;
switch (d2nd) {
case 'Z':
z++;
if (z >= core.sizeZ[i]) {
z = 0;
c++;
}
break;
case 'C':
c++;
if (c >= sc) {
c = 0;
z++;
}
break;
}
}
break;
case 'C':
c++;
if (c >= sc) {
c = 0;
switch (d2nd) {
case 'Z':
z++;
if (z >= core.sizeZ[i]) {
z = 0;
t++;
}
break;
case 'T':
t++;
if (t >= core.sizeT[i]) {
t = 0;
z++;
}
break;
}
}
break;
}
}
}
}
}
}
|
diff --git a/src/com/google/javascript/jscomp/ant/CompileTask.java b/src/com/google/javascript/jscomp/ant/CompileTask.java
index 4e636a39..38741720 100644
--- a/src/com/google/javascript/jscomp/ant/CompileTask.java
+++ b/src/com/google/javascript/jscomp/ant/CompileTask.java
@@ -1,279 +1,281 @@
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp.ant;
import com.google.common.collect.Lists;
import com.google.javascript.jscomp.CommandLineRunner;
import com.google.javascript.jscomp.CompilationLevel;
import com.google.javascript.jscomp.Compiler;
import com.google.javascript.jscomp.CompilerOptions;
import com.google.javascript.jscomp.JSSourceFile;
import com.google.javascript.jscomp.MessageFormatter;
import com.google.javascript.jscomp.Result;
import com.google.javascript.jscomp.WarningLevel;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.FileList;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.util.List;
import java.util.logging.Level;
/**
* This class implements a simple Ant task to do almost the same as
* CommandLineRunner.
*
* Most of the public methods of this class are entry points for the
* Ant code to hook into.
*
*
*/
public final class CompileTask
extends Task {
private WarningLevel warningLevel;
private boolean debugOptions;
private String encoding = "UTF-8";
private String outputEncoding = "UTF-8";
private CompilationLevel compilationLevel;
private boolean customExternsOnly;
private boolean manageDependencies;
private File outputFile;
private final List<FileList> externFileLists;
private final List<FileList> sourceFileLists;
public CompileTask() {
this.warningLevel = WarningLevel.DEFAULT;
this.debugOptions = false;
this.compilationLevel = CompilationLevel.SIMPLE_OPTIMIZATIONS;
this.customExternsOnly = false;
this.manageDependencies = false;
this.externFileLists = Lists.newLinkedList();
this.sourceFileLists = Lists.newLinkedList();
}
/**
* Set the warning level.
* @param value The warning level by string name. (default, quiet, verbose).
*/
public void setWarning(String value) {
if ("default".equalsIgnoreCase(value)) {
this.warningLevel = WarningLevel.DEFAULT;
} else if ("quiet".equalsIgnoreCase(value)) {
this.warningLevel = WarningLevel.QUIET;
} else if ("verbose".equalsIgnoreCase(value)) {
this.warningLevel = WarningLevel.VERBOSE;
} else {
throw new BuildException(
"Unrecognized 'warning' option value (" + value + ")");
}
}
/**
* Enable debugging options.
* @param value True if debug mode is enabled.
*/
public void setDebug(boolean value) {
this.debugOptions = value;
}
/**
* Set the compilation level.
* @param value The optimization level by string name.
* (whitespace, simple, advanced).
*/
public void setCompilationLevel(String value) {
if ("simple".equalsIgnoreCase(value)) {
this.compilationLevel = CompilationLevel.SIMPLE_OPTIMIZATIONS;
} else if ("advanced".equalsIgnoreCase(value)) {
this.compilationLevel = CompilationLevel.ADVANCED_OPTIMIZATIONS;
} else if ("whitespace".equalsIgnoreCase(value)) {
this.compilationLevel = CompilationLevel.WHITESPACE_ONLY;
} else {
throw new BuildException(
"Unrecognized 'compilation' option value (" + value + ")");
}
}
public void setManageDependencies(boolean value) {
this.manageDependencies = value;
}
/**
* Use only custom externs.
*/
public void setCustomExternsOnly(boolean value) {
this.customExternsOnly = value;
}
/**
* Set output file.
*/
public void setOutput(File value) {
this.outputFile = value;
}
/**
* Set input file encoding
*/
public void setEncoding(String encoding) {
this.encoding = encoding;
}
/**
* Set output file encoding
*/
public void setOutputEncoding(String outputEncoding) {
this.outputEncoding = outputEncoding;
}
/**
* Sets the externs file.
*/
public void addExterns(FileList list) {
this.externFileLists.add(list);
}
/**
* Sets the source files.
*/
public void addSources(FileList list) {
this.sourceFileLists.add(list);
}
public void execute() {
if (this.outputFile == null) {
throw new BuildException("outputFile attribute must be set");
}
Compiler.setLoggingLevel(Level.OFF);
CompilerOptions options = createCompilerOptions();
Compiler compiler = createCompiler(options);
JSSourceFile[] externs = findExternFiles();
JSSourceFile[] sources = findSourceFiles();
log("Compiling " + sources.length + " file(s) with " +
externs.length + " extern(s)");
Result result = compiler.compile(externs, sources, options);
if (result.success) {
writeResult(compiler.toSource());
+ } else {
+ throw new BuildException("Compilation failed.");
}
}
private CompilerOptions createCompilerOptions() {
CompilerOptions options = new CompilerOptions();
if (this.debugOptions) {
this.compilationLevel.setDebugOptionsForCompilationLevel(options);
} else {
this.compilationLevel.setOptionsForCompilationLevel(options);
}
this.warningLevel.setOptionsForWarningLevel(options);
options.setManageClosureDependencies(manageDependencies);
return options;
}
private Compiler createCompiler(CompilerOptions options) {
Compiler compiler = new Compiler();
MessageFormatter formatter =
options.errorFormat.toFormatter(compiler, false);
AntErrorManager errorManager = new AntErrorManager(formatter, this);
compiler.setErrorManager(errorManager);
return compiler;
}
private JSSourceFile[] findExternFiles() {
List<JSSourceFile> files = Lists.newLinkedList();
if (!this.customExternsOnly) {
files.addAll(getDefaultExterns());
}
for (FileList list : this.externFileLists) {
files.addAll(findJavaScriptFiles(list));
}
return files.toArray(new JSSourceFile[files.size()]);
}
private JSSourceFile[] findSourceFiles() {
List<JSSourceFile> files = Lists.newLinkedList();
for (FileList list : this.sourceFileLists) {
files.addAll(findJavaScriptFiles(list));
}
return files.toArray(new JSSourceFile[files.size()]);
}
/**
* Translates an Ant file list into the file format that the compiler
* expects.
*/
private List<JSSourceFile> findJavaScriptFiles(FileList fileList) {
List<JSSourceFile> files = Lists.newLinkedList();
File baseDir = fileList.getDir(getProject());
for (String included : fileList.getFiles(getProject())) {
files.add(JSSourceFile.fromFile(new File(baseDir, included),
Charset.forName(encoding)));
}
return files;
}
/**
* Gets the default externs set.
*
* Adapted from {@link CommandLineRunner}.
*/
private List<JSSourceFile> getDefaultExterns() {
try {
return CommandLineRunner.getDefaultExterns();
} catch (IOException e) {
throw new BuildException(e);
}
}
private void writeResult(String source) {
if (this.outputFile.getParentFile().mkdirs()) {
log("Created missing parent directory " +
this.outputFile.getParentFile(), Project.MSG_DEBUG);
}
try {
OutputStreamWriter out = new OutputStreamWriter(
new FileOutputStream(this.outputFile), outputEncoding);
out.append(source);
out.flush();
out.close();
} catch (IOException e) {
throw new BuildException(e);
}
log("Compiled javascript written to " + this.outputFile.getAbsolutePath(),
Project.MSG_DEBUG);
}
}
| true | true | public void execute() {
if (this.outputFile == null) {
throw new BuildException("outputFile attribute must be set");
}
Compiler.setLoggingLevel(Level.OFF);
CompilerOptions options = createCompilerOptions();
Compiler compiler = createCompiler(options);
JSSourceFile[] externs = findExternFiles();
JSSourceFile[] sources = findSourceFiles();
log("Compiling " + sources.length + " file(s) with " +
externs.length + " extern(s)");
Result result = compiler.compile(externs, sources, options);
if (result.success) {
writeResult(compiler.toSource());
}
}
| public void execute() {
if (this.outputFile == null) {
throw new BuildException("outputFile attribute must be set");
}
Compiler.setLoggingLevel(Level.OFF);
CompilerOptions options = createCompilerOptions();
Compiler compiler = createCompiler(options);
JSSourceFile[] externs = findExternFiles();
JSSourceFile[] sources = findSourceFiles();
log("Compiling " + sources.length + " file(s) with " +
externs.length + " extern(s)");
Result result = compiler.compile(externs, sources, options);
if (result.success) {
writeResult(compiler.toSource());
} else {
throw new BuildException("Compilation failed.");
}
}
|
diff --git a/mes-plugins/mes-plugins-operational-tasks-for-orders/src/main/java/com/qcadoo/mes/operationalTasksForOrders/hooks/OrderHooksOTFO.java b/mes-plugins/mes-plugins-operational-tasks-for-orders/src/main/java/com/qcadoo/mes/operationalTasksForOrders/hooks/OrderHooksOTFO.java
index ca454ad657..76bd6aa71e 100644
--- a/mes-plugins/mes-plugins-operational-tasks-for-orders/src/main/java/com/qcadoo/mes/operationalTasksForOrders/hooks/OrderHooksOTFO.java
+++ b/mes-plugins/mes-plugins-operational-tasks-for-orders/src/main/java/com/qcadoo/mes/operationalTasksForOrders/hooks/OrderHooksOTFO.java
@@ -1,46 +1,46 @@
package com.qcadoo.mes.operationalTasksForOrders.hooks;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.qcadoo.mes.operationalTasks.constants.OperationalTasksConstants;
import com.qcadoo.mes.operationalTasks.constants.OperationalTasksFields;
import com.qcadoo.mes.orders.constants.OrderFields;
import com.qcadoo.model.api.DataDefinition;
import com.qcadoo.model.api.DataDefinitionService;
import com.qcadoo.model.api.Entity;
import com.qcadoo.model.api.search.SearchRestrictions;
@Service
public class OrderHooksOTFO {
@Autowired
private DataDefinitionService dataDefinitionService;
public void changedProductionLine(final DataDefinition dataDefinition, final Entity entity) {
if (entity.getId() == null) {
return;
}
Entity order = dataDefinition.get(entity.getId());
Entity productionLine = entity.getBelongsToField(OrderFields.PRODUCTION_LINE);
Entity orderProductionLine = order.getBelongsToField(OrderFields.PRODUCTION_LINE);
- if ((orderProductionLine == null && productionLine == null) || orderProductionLine.equals(productionLine)) {
+ if (orderProductionLine.equals(productionLine)) {
return;
} else {
changedProductionLineInOperationalTasks(order, productionLine);
}
}
private void changedProductionLineInOperationalTasks(final Entity order, final Entity productionLine) {
DataDefinition operationalTasksDD = dataDefinitionService.get(OperationalTasksConstants.PLUGIN_IDENTIFIER,
OperationalTasksConstants.MODEL_OPERATIONAL_TASK);
List<Entity> operationalTasksList = operationalTasksDD.find().add(SearchRestrictions.belongsTo("order", order)).list()
.getEntities();
for (Entity operationalTask : operationalTasksList) {
operationalTask.setField(OperationalTasksFields.PRODUCTION_LINE, productionLine);
operationalTasksDD.save(operationalTask);
}
}
}
| true | true | public void changedProductionLine(final DataDefinition dataDefinition, final Entity entity) {
if (entity.getId() == null) {
return;
}
Entity order = dataDefinition.get(entity.getId());
Entity productionLine = entity.getBelongsToField(OrderFields.PRODUCTION_LINE);
Entity orderProductionLine = order.getBelongsToField(OrderFields.PRODUCTION_LINE);
if ((orderProductionLine == null && productionLine == null) || orderProductionLine.equals(productionLine)) {
return;
} else {
changedProductionLineInOperationalTasks(order, productionLine);
}
}
| public void changedProductionLine(final DataDefinition dataDefinition, final Entity entity) {
if (entity.getId() == null) {
return;
}
Entity order = dataDefinition.get(entity.getId());
Entity productionLine = entity.getBelongsToField(OrderFields.PRODUCTION_LINE);
Entity orderProductionLine = order.getBelongsToField(OrderFields.PRODUCTION_LINE);
if (orderProductionLine.equals(productionLine)) {
return;
} else {
changedProductionLineInOperationalTasks(order, productionLine);
}
}
|
diff --git a/src/com/csipsimple/ui/outgoingcall/OutgoingCallChooser.java b/src/com/csipsimple/ui/outgoingcall/OutgoingCallChooser.java
index 8016f671..99aa6b15 100644
--- a/src/com/csipsimple/ui/outgoingcall/OutgoingCallChooser.java
+++ b/src/com/csipsimple/ui/outgoingcall/OutgoingCallChooser.java
@@ -1,238 +1,238 @@
/**
* Copyright (C) 2010-2012 Regis Montoya (aka r3gis - www.r3gis.fr)
* This file is part of CSipSimple.
*
* CSipSimple 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.
* If you own a pjsip commercial license you can also redistribute it
* and/or modify it under the terms of the GNU Lesser General Public License
* as an android library.
*
* CSipSimple 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 CSipSimple. If not, see <http://www.gnu.org/licenses/>.
*/
package com.csipsimple.ui.outgoingcall;
import android.annotation.TargetApi;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.telephony.PhoneNumberUtils;
import android.text.TextUtils;
import android.view.KeyEvent;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.csipsimple.R;
import com.csipsimple.api.ISipService;
import com.csipsimple.api.SipManager;
import com.csipsimple.api.SipProfile;
import com.csipsimple.utils.Compatibility;
import com.csipsimple.utils.Log;
import com.csipsimple.utils.PreferencesProviderWrapper;
public class OutgoingCallChooser extends SherlockFragmentActivity {
private static final String THIS_FILE = "OutgoingCallChooser";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
resetInternals();
// Sanity check
if (TextUtils.isEmpty(getPhoneNumber())) {
Log.e(THIS_FILE, "No number detected for : " + getIntent().getAction());
finish();
return;
}
setContentView(R.layout.outgoing_call_view);
connectService();
}
private String phoneNumber = null;
private boolean ignoreRewritingRules = false;
private Long accountToCallTo = null;
private final static String SCHEME_CSIP = "csip";
private final static String SCHEME_IMTO = "imto";
private final static String SCHEME_SMSTO = "smsto";
private final static String AUTHORITY_CSIP = "csip";
private final static String AUTHORITY_SIP = "sip";
private final static String AUTHORITY_SKYPE = "skype";
/**
* Get the phone number that raised this activity.
* @return The phone number we are trying to call with this activity
*/
public String getPhoneNumber() {
if(phoneNumber == null) {
Intent it = getIntent();
// First step is to retrieve the number that was asked to us.
phoneNumber = PhoneNumberUtils.getNumberFromIntent(getIntent(), this);
if (phoneNumber == null) {
String action = it.getAction();
Uri data = it.getData();
if (action != null && data != null) {
String scheme = data.getScheme();
if(scheme != null) {
scheme = scheme.toLowerCase();
}
- if (action.equalsIgnoreCase(Intent.ACTION_CALL)) {
- // Simple call intent
- phoneNumber = data.getSchemeSpecificPart();
- if(SCHEME_CSIP.equals(scheme)) {
- ignoreRewritingRules = true;
- }
- }else if (action.equalsIgnoreCase(Intent.ACTION_SENDTO)) {
+ if (action.equalsIgnoreCase(Intent.ACTION_SENDTO)) {
// Send to action -- could be im or sms
if (SCHEME_IMTO.equals(scheme)) {
// Im sent
String auth = data.getAuthority();
if (AUTHORITY_CSIP.equals(auth) ||
AUTHORITY_SIP.equals(auth) ||
AUTHORITY_SKYPE.equals(auth) ) {
phoneNumber = data.getLastPathSegment();
}
}else if (SCHEME_SMSTO.equals(scheme)) {
phoneNumber = PhoneNumberUtils.stripSeparators(data.getSchemeSpecificPart());
}
- }
+ } else {
+ // Simple call intent
+ phoneNumber = data.getSchemeSpecificPart();
+ if(SCHEME_CSIP.equals(scheme)) {
+ ignoreRewritingRules = true;
+ }
+ }
}
} else {
String action = it.getAction();
Uri data = it.getData();
if (action != null && data != null) {
String scheme = data.getScheme();
if(scheme != null) {
scheme = scheme.toLowerCase();
if(SCHEME_SMSTO.equals(scheme) || "tel".equals(scheme)) {
phoneNumber = PhoneNumberUtils.stripSeparators(phoneNumber);
}
}
}
}
// Still null ... well make it empty.
if(phoneNumber == null) {
phoneNumber = "";
}
return phoneNumber;
}
return phoneNumber;
}
/**
* Should we ignore rewriting rules
* @return True if rewriting rules are not taken into account for this outgoing call.
*/
public boolean shouldIgnoreRewritingRules() {
// Ignore rewriting rule is get once phone number is retrieved
getPhoneNumber();
return ignoreRewritingRules;
}
/**
* Get the account to force use for outgoing.
* @return The account id to use for outgoing. {@link SipProfile#INVALID_ID} if no account should be used.
*/
public long getAccountToCallTo() {
if(accountToCallTo == null) {
accountToCallTo = getIntent().getLongExtra(SipProfile.FIELD_ACC_ID, SipProfile.INVALID_ID);
}
return accountToCallTo;
}
/* Service connection */
/**
* Connect to sip service by flagging itself as the component to consider as outgoing activity
*/
private void connectService() {
PreferencesProviderWrapper prefsWrapper = new PreferencesProviderWrapper(this);
Intent sipService = new Intent(SipManager.INTENT_SIP_SERVICE);
if (prefsWrapper.isValidConnectionForOutgoing()) {
sipService.putExtra(SipManager.EXTRA_OUTGOING_ACTIVITY, getComponentName());
startService(sipService);
}
bindService(sipService, connection, Context.BIND_AUTO_CREATE);
}
/**
* Get connected sip service.
* @return connected sip service from the activity if already connected. Null else.
*/
public ISipService getConnectedService() {
return service;
}
private ISipService service = null;
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName component, IBinder binder) {
service = ISipService.Stub.asInterface(binder);
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
service = null;
}
};
@TargetApi(5)
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK
&& event.getRepeatCount() == 0
&& !Compatibility.isCompatible(5)) {
onBackPressed();
}
return super.onKeyDown(keyCode, event);
}
public void onBackPressed() {
finishServiceIfNeeded(false);
}
/**
* Finish the activity and send unregistration to service as outgoing activity.
* @param defer If true the activity will ask sip service to remain active until end of next call (because it will iniate a call).
* If false, ask sip service to consider outgoing mode as not anymore valid right now. Usually cause call will be managed another way than a sip way.
*/
public void finishServiceIfNeeded(boolean defer) {
Intent intent = new Intent(defer ? SipManager.ACTION_DEFER_OUTGOING_UNREGISTER : SipManager.ACTION_OUTGOING_UNREGISTER);
intent.putExtra(SipManager.EXTRA_OUTGOING_ACTIVITY, getComponentName());
sendBroadcast(intent);
finish();
}
@Override
protected void onDestroy() {
super.onDestroy();
resetInternals();
try {
unbindService(connection);
} catch (Exception e) {
}
}
private void resetInternals() {
phoneNumber = null;
accountToCallTo = null;
ignoreRewritingRules = false;
}
}
| false | true | public String getPhoneNumber() {
if(phoneNumber == null) {
Intent it = getIntent();
// First step is to retrieve the number that was asked to us.
phoneNumber = PhoneNumberUtils.getNumberFromIntent(getIntent(), this);
if (phoneNumber == null) {
String action = it.getAction();
Uri data = it.getData();
if (action != null && data != null) {
String scheme = data.getScheme();
if(scheme != null) {
scheme = scheme.toLowerCase();
}
if (action.equalsIgnoreCase(Intent.ACTION_CALL)) {
// Simple call intent
phoneNumber = data.getSchemeSpecificPart();
if(SCHEME_CSIP.equals(scheme)) {
ignoreRewritingRules = true;
}
}else if (action.equalsIgnoreCase(Intent.ACTION_SENDTO)) {
// Send to action -- could be im or sms
if (SCHEME_IMTO.equals(scheme)) {
// Im sent
String auth = data.getAuthority();
if (AUTHORITY_CSIP.equals(auth) ||
AUTHORITY_SIP.equals(auth) ||
AUTHORITY_SKYPE.equals(auth) ) {
phoneNumber = data.getLastPathSegment();
}
}else if (SCHEME_SMSTO.equals(scheme)) {
phoneNumber = PhoneNumberUtils.stripSeparators(data.getSchemeSpecificPart());
}
}
}
} else {
String action = it.getAction();
Uri data = it.getData();
if (action != null && data != null) {
String scheme = data.getScheme();
if(scheme != null) {
scheme = scheme.toLowerCase();
if(SCHEME_SMSTO.equals(scheme) || "tel".equals(scheme)) {
phoneNumber = PhoneNumberUtils.stripSeparators(phoneNumber);
}
}
}
}
// Still null ... well make it empty.
if(phoneNumber == null) {
phoneNumber = "";
}
return phoneNumber;
}
return phoneNumber;
}
| public String getPhoneNumber() {
if(phoneNumber == null) {
Intent it = getIntent();
// First step is to retrieve the number that was asked to us.
phoneNumber = PhoneNumberUtils.getNumberFromIntent(getIntent(), this);
if (phoneNumber == null) {
String action = it.getAction();
Uri data = it.getData();
if (action != null && data != null) {
String scheme = data.getScheme();
if(scheme != null) {
scheme = scheme.toLowerCase();
}
if (action.equalsIgnoreCase(Intent.ACTION_SENDTO)) {
// Send to action -- could be im or sms
if (SCHEME_IMTO.equals(scheme)) {
// Im sent
String auth = data.getAuthority();
if (AUTHORITY_CSIP.equals(auth) ||
AUTHORITY_SIP.equals(auth) ||
AUTHORITY_SKYPE.equals(auth) ) {
phoneNumber = data.getLastPathSegment();
}
}else if (SCHEME_SMSTO.equals(scheme)) {
phoneNumber = PhoneNumberUtils.stripSeparators(data.getSchemeSpecificPart());
}
} else {
// Simple call intent
phoneNumber = data.getSchemeSpecificPart();
if(SCHEME_CSIP.equals(scheme)) {
ignoreRewritingRules = true;
}
}
}
} else {
String action = it.getAction();
Uri data = it.getData();
if (action != null && data != null) {
String scheme = data.getScheme();
if(scheme != null) {
scheme = scheme.toLowerCase();
if(SCHEME_SMSTO.equals(scheme) || "tel".equals(scheme)) {
phoneNumber = PhoneNumberUtils.stripSeparators(phoneNumber);
}
}
}
}
// Still null ... well make it empty.
if(phoneNumber == null) {
phoneNumber = "";
}
return phoneNumber;
}
return phoneNumber;
}
|
diff --git a/Zed-Eclipse/src/zed/Level_Manager.java b/Zed-Eclipse/src/zed/Level_Manager.java
index c3e090e..8146097 100644
--- a/Zed-Eclipse/src/zed/Level_Manager.java
+++ b/Zed-Eclipse/src/zed/Level_Manager.java
@@ -1,453 +1,453 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package zed;
// java for file input
import java.io.File;
import java.io.FileNotFoundException;
// Slick for drawing to screen and input
import org.newdawn.slick.Animation;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.Sound;
import org.newdawn.slick.SpriteSheet;
/**
*
* @author Richard Barella Jr.
* @author Adam Bennett
* @author Ryan Slyter
*/
// TODO: Edit Level Manager
public class Level_Manager {
private static final int TILE_SIZE = 16;
private static final int ZOMBIE = 0;
private SpriteSheet tileset; // data for tiles
private SpriteSheet character_sprites; // data for character sprites
GObject[] objectlist; //this is going to be the array that the Level_Manager instance uses to hold all the objects
GCharacter[] npclist; // array to hold NPCs in particular TODO:make into list
GPortal[] portallist; // array to hold portals of the level
Image Full_Heart; //full heart image
Image Empty_Heart; //empty heart image
int maxHealth; //players maximum hp
boolean[] lifeBar; //array representing which HUD images are full hearts or empty hearts
int width; // Number of tile columns
int height; // Number of tile rows
int xpos; // x position of top-left of tiles
int ypos; // y position of top-left of tiles
int scale; // By how many times is the pixels larger?
int[][] bot_tile_x; // tileset x index of bot_tile[x][y]
int[][] bot_tile_y; // tileset y index of bot_tile[x][y]
//int[][] top_tile_x; // tileset x index of top_tile[x][y]
//int[][] top_tile_y; // tileset y index of top_tile[x][y]
File_Manager Files;
Player_Character player; // data for player character
int current_level_index;
// Default instantiation for Level_Manager
public Level_Manager() throws SlickException {
Init(0, 10, 5);
}
public void Init(int level_index, int player_x, int player_y) throws SlickException{
current_level_index = level_index;
objectlist = null;
npclist = null;
portallist = null;
tileset = new SpriteSheet("images/tileset.png", 16, 16);
character_sprites = new SpriteSheet("images/spritesheet.png", 16, 32);
Files = new File_Manager();
Initialize_Player_Information(player_x, player_y);
Init_NPC(null);
//start of initializing heart images and life bar for HUD display
Full_Heart = new Image("images/fullheart.png", false, Image.FILTER_NEAREST);
Empty_Heart = new Image("images/emptyheart.png", false, Image.FILTER_NEAREST);
Full_Heart.setAlpha(0.5f);
Empty_Heart.setAlpha(0.5f);
maxHealth = player.Get_Health(); //change from "final" if '+ heart containers' added to the game as a feature!
lifeBar = new boolean[maxHealth];
for (int i = 0; i < maxHealth; i++){
lifeBar[i] = true;
}
//initialize level
width = 20;
height = 15;
xpos = 0;
ypos = 0;
scale = 2;
bot_tile_x = new int[height][width];
bot_tile_y = new int[height][width];
File level = new File("levels/" + String.valueOf(level_index) + ".lvl");
short Tile_List[][] = null;
short Field_Types = 4;
try {
Tile_List = Files.Scan_LVL(level, Field_Types);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// load tiles
int k = 0;
for (int i = 0; i < height; i++ ){
for(int j = 0; j < width; j++){
bot_tile_x[i][j] = Tile_List[0][k];
bot_tile_y[i][j] = Tile_List[0][++k];
k++;
}
}
// load GObjects
if (Tile_List[1] != null)
{
int number_of_1s = 0;
for (int i = 0; i < Tile_List[1].length; i++)
{
if (Tile_List[1][i] == 1)
{
number_of_1s++;
}
}
objectlist = new GObject[number_of_1s];
int current_object = 0;
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
if (Tile_List[1][j + width*i] == 1)
{
objectlist[current_object++] = new GObject(
j, i, // tell which tile to start in
false, // tell whether the object is visible
true, // tell whether the object is solid for collision
null, null, // number of pixels each animation is shifted by
16, // give size of a tile in pixels
null, // give preinitialized animations
0 // tell which animation to start with
);
}
}
}
}
if (Tile_List[2] != null)
{
portallist = new GPortal[Tile_List[2].length/5];
for (int i = 0; i < Tile_List[2].length/5; i++)
{
- portallist[0] = new GPortal(Tile_List[2][5*i],
+ portallist[i] = new GPortal(Tile_List[2][5*i],
Tile_List[2][5*i+1], 16, Tile_List[2][5*i+4],
Tile_List[2][5*i+2], Tile_List[2][5*i+3]);
}
}
if (Tile_List[3] != null)
{
npclist = new GCharacter[Tile_List[3].length/3];
for (int i = 0; i < Tile_List[3].length/3; i++)
{
if (Tile_List[3][i*3] == ZOMBIE)
npclist[i] = new Zombie(Tile_List[3][i*3+1],
Tile_List[3][i*3+2], character_sprites);
}
/*
npclist = new GCharacter[10];
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 2; j++)
{
npclist[i + 5*j] = new Zombie(8+i, 5+j, character_sprites);//make sure to add new files to the repository.
}
}
*/
}
}
// default initialization for the player's animations, position, attack speed, animation speed
// within the level
public void Initialize_Player_Information(int player_x, int player_y) throws SlickException
{
// spritesheet information for standing and walking animations
int[] player_spritesheet_index_y = {0, 1, 2, 3, 0, 1, 2, 3}; // row in spritesheet for each animation
int[] player_spritesheet_index_x = {1, 1, 1, 1, 0, 0, 0, 0}; // starting frame in each animation
int[] player_animation_length = {1, 1, 1, 1, 3, 3, 3, 3}; // length for each animation
// sprite information for all animations
int[] player_sprite_shift_x = {0, 0, 0, 0, 0, 0, 0, 0, 16, 16, 16, 16}; // how many pixels to shift animation in x direction
int[] player_sprite_shift_y = {16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16}; // how many pixels to shift animation in y direction
boolean[] player_looping = {false, false, false, false, true, true, true, true}; // whether each animation is looping or not
int player_animation_speed = 200; // speed in milliseconds for the walking animations
int player_attack_animation_speed = 50; // speed in milliseconds for the attack animations
// start intializing array values for each animation
Animation[] player_animation_list = new Animation[12]; // intialize animation array length
for (int i = 0; i < 8; i++) // initialize walking and standing animations
{
player_animation_list[i] = new Animation(character_sprites, // spritesheet to use
// location of first sprite in spritesheet
player_spritesheet_index_x[i], player_spritesheet_index_y[i],
// location of last sprite in spritesheet
player_spritesheet_index_x[i] + player_animation_length[i] - 1, player_spritesheet_index_y[i],
false, // horizontalScan value
player_animation_speed, // speed value for animation
true // autoupdate value
);
player_animation_list[i].setLooping(player_looping[i]); // intialize whether animation loops
player_animation_list[i].setPingPong(true); // initialize whether animation ping-pongs between last and first frame
}
for (int i = 0; i < 4 ; i++) // initialize each attack animation
{
Image[] frames = new Image[3]; // initialize length of attack animation in frames
for (int j = 0; j < 3; j++)
{
// intialize each frame in attackanimation
frames[j] = character_sprites.getSubImage(j*48, 4*32 + i*48, 48, 48);
}
// initialize animation with created frames
player_animation_list[i + 8] = new Animation(frames, player_attack_animation_speed, true);
player_animation_list[i + 8].setLooping(false); // set animation to not loop automatically
player_animation_list[i + 8].setPingPong(true); // set whether the animation ping-pongs between first and last frame
}
player = new Player_Character(
player_x, // intialize character's x position w.r.t. tiles
player_y, // initialize character's y position w.r.t. tiles
true, // character is visible
true, // character is solid
player_sprite_shift_x, // give character sprite shift value in the x axis
player_sprite_shift_y, // give character sprite shift value in the y axis
16, // give player_character the size of a tile
player_animation_list, // give the created list of animations
0, // give which animation to start with
5, // give health of character
8.0f, // give speed in tiles per second of character
0, // set initial x_movement value to 0
0 // set initial y_movement value to 0
);
}
// made this for testing initialization for NPCs
public void Init_NPC(int[] npc_data) throws SlickException{
npclist = new GCharacter[0];
/*
npclist = new GCharacter[10];
SpriteSheet enemysheet = new SpriteSheet("images/enemies.png", 16, 24);
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 2; j++)
{
npclist[i + 5*j] = new Zombie(8+i, 5+j, character_sprites);//make sure to add new files to the repository.
}
}
*/
}
public void Init_GObject(){
objectlist = new GObject[0];
}
// Edit class variables
public void setwidth(int newwidth){
width = newwidth;
}
public void setheight(int newheight){
height = newheight;
}
public void setxpos(int newxpos){
xpos = newxpos;
}
public void setypos(int newypos){
ypos = newypos;
}
public void setscale(int newscale){
scale = newscale;
}
public void settile(Image newtile, int x, int y){
tileset.equals(newtile);
}
//method update_HUD takes boolean array representing player_character's health,
//the fixed maximum health of said characters, the hero itself to get its current health,
//and the full and empty hearts so that they can be drawn on the screen; the method
//is meant to be called every time the game updates so as to check if the player
//has been hurt/killed or not so that the HUD in the top left can reflect that
public void update_HUD(boolean[] lifebar, int maxhealth, Player_Character hero, Image full, Image empty, Graphics g){
int current_Health = hero.Get_Health();
if (maxhealth == current_Health){
for (int i = 0; i < maxhealth; i++){
lifebar[i] = true; //supports getting full-health potions this way
}
}
else if (current_Health == 0){
for (int i = 0; i < maxhealth; i++){
lifebar[i] = false;
/**
* code here to handle telling level manager that game is over
* possibly setting a flag so empty hearts can be drawn first
*/
}
}
else{
for (int i = 0; i <current_Health; i++){
lifebar[i] = true;
}
for (int i = current_Health; i < maxhealth; i++){
lifebar[i] = false;
}
}
//I'm *guessing* here (for the sake of performance) that drawing the objects
//to the screen is more costly than having more for-loops
for (int i = 0; i < maxhealth; i++){
if (lifebar[i] == true)
{
g.drawImage(
full, // image
i*full.getWidth()*scale, // x pos
0, // y pos
(i + 1)*full.getWidth()*scale, // x2 pos
full.getHeight()*scale, // y2 pos
0, 0, // ???
full.getWidth(), // width
full.getHeight()); // height
}
else
{
g.drawImage(
empty,
i*empty.getWidth()*scale,
0,
(i + 1)*empty.getWidth()*scale,
empty.getHeight()*scale,
0, 0,
empty.getWidth(),
empty.getHeight());
}
}
}
// the display function for the Level_Manager that is called every frame
// to render the level
public void display(GameContainer gc, Graphics g){
for (int i = 0; i < height; i++) // display each row
{
for (int j = 0; j < width; j++) // display each column
{
g.drawImage(tileset.getSubImage(bot_tile_x[i][j], bot_tile_y[i][j]),
xpos + j*TILE_SIZE*scale,
ypos + i*TILE_SIZE*scale,
xpos + j*TILE_SIZE*scale + TILE_SIZE*scale,
ypos + i*TILE_SIZE*scale + TILE_SIZE*scale,
0, 0,
TILE_SIZE, TILE_SIZE);
}
}
sort_render_order(npclist); // sort main list for efficiency
GObject[] objlist = new GObject[npclist.length + 1]; // create temp list
for (int i = 0; i < npclist.length; i++)
{
objlist[i + 1] = npclist[i]; // put npcs in temp list
}
objlist[0] = player; // put player inside of temp list
sort_render_order(objlist); // sort temp list for render order
for (int i = 0; i < objlist.length; i++)
{
objlist[i].Render(scale, xpos, ypos, gc, g); // render in order
}
update_HUD(lifeBar, maxHealth, player, Full_Heart, Empty_Heart, g);
}
// the update funciton that is called each time Slick updates to update the information
// in the level
boolean has_ported = false;
public void update() throws SlickException
{
player.Update(objectlist, npclist);
for (int i = 0; i < npclist.length; i++)
{
npclist[i].Update(objectlist, npclist, player);
}
GObject activeportal;
if ((activeportal = player.Collision(portallist)) != null)
{
if (!has_ported)
{
for (int i = 0; i < portallist.length; i++)
{
if (portallist[i] == activeportal)
{
Init(portallist[i].Get_Dest_Level(),
portallist[i].Get_Dest_X_Tile(),
portallist[i].Get_Dest_Y_Tile());
}
}
has_ported = true;
}
}
else
{
has_ported = false;
}
}
// change the player's X_Movement and Y_Movement values within Zed.java
public void move_player(int new_x_mov, int new_y_mov)
{
player.New_Movement(new_x_mov, new_y_mov);
}
private void sort_render_order(GObject[] list)
{
GObject temp;
boolean flag = true;
while (flag)
{
flag = false;
for (int i = 0; i < list.length - 1; i++)
{
if (list[i].Get_Y_Position() > list[i + 1].Get_Y_Position())
{
temp = list[i];
list[i] = list[i + 1];
list[i + 1] = temp;
flag = true;
}
}
}
}
}
| true | true | public void Init(int level_index, int player_x, int player_y) throws SlickException{
current_level_index = level_index;
objectlist = null;
npclist = null;
portallist = null;
tileset = new SpriteSheet("images/tileset.png", 16, 16);
character_sprites = new SpriteSheet("images/spritesheet.png", 16, 32);
Files = new File_Manager();
Initialize_Player_Information(player_x, player_y);
Init_NPC(null);
//start of initializing heart images and life bar for HUD display
Full_Heart = new Image("images/fullheart.png", false, Image.FILTER_NEAREST);
Empty_Heart = new Image("images/emptyheart.png", false, Image.FILTER_NEAREST);
Full_Heart.setAlpha(0.5f);
Empty_Heart.setAlpha(0.5f);
maxHealth = player.Get_Health(); //change from "final" if '+ heart containers' added to the game as a feature!
lifeBar = new boolean[maxHealth];
for (int i = 0; i < maxHealth; i++){
lifeBar[i] = true;
}
//initialize level
width = 20;
height = 15;
xpos = 0;
ypos = 0;
scale = 2;
bot_tile_x = new int[height][width];
bot_tile_y = new int[height][width];
File level = new File("levels/" + String.valueOf(level_index) + ".lvl");
short Tile_List[][] = null;
short Field_Types = 4;
try {
Tile_List = Files.Scan_LVL(level, Field_Types);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// load tiles
int k = 0;
for (int i = 0; i < height; i++ ){
for(int j = 0; j < width; j++){
bot_tile_x[i][j] = Tile_List[0][k];
bot_tile_y[i][j] = Tile_List[0][++k];
k++;
}
}
// load GObjects
if (Tile_List[1] != null)
{
int number_of_1s = 0;
for (int i = 0; i < Tile_List[1].length; i++)
{
if (Tile_List[1][i] == 1)
{
number_of_1s++;
}
}
objectlist = new GObject[number_of_1s];
int current_object = 0;
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
if (Tile_List[1][j + width*i] == 1)
{
objectlist[current_object++] = new GObject(
j, i, // tell which tile to start in
false, // tell whether the object is visible
true, // tell whether the object is solid for collision
null, null, // number of pixels each animation is shifted by
16, // give size of a tile in pixels
null, // give preinitialized animations
0 // tell which animation to start with
);
}
}
}
}
if (Tile_List[2] != null)
{
portallist = new GPortal[Tile_List[2].length/5];
for (int i = 0; i < Tile_List[2].length/5; i++)
{
portallist[0] = new GPortal(Tile_List[2][5*i],
Tile_List[2][5*i+1], 16, Tile_List[2][5*i+4],
Tile_List[2][5*i+2], Tile_List[2][5*i+3]);
}
}
if (Tile_List[3] != null)
{
npclist = new GCharacter[Tile_List[3].length/3];
for (int i = 0; i < Tile_List[3].length/3; i++)
{
if (Tile_List[3][i*3] == ZOMBIE)
npclist[i] = new Zombie(Tile_List[3][i*3+1],
Tile_List[3][i*3+2], character_sprites);
}
/*
npclist = new GCharacter[10];
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 2; j++)
{
npclist[i + 5*j] = new Zombie(8+i, 5+j, character_sprites);//make sure to add new files to the repository.
}
}
*/
}
}
| public void Init(int level_index, int player_x, int player_y) throws SlickException{
current_level_index = level_index;
objectlist = null;
npclist = null;
portallist = null;
tileset = new SpriteSheet("images/tileset.png", 16, 16);
character_sprites = new SpriteSheet("images/spritesheet.png", 16, 32);
Files = new File_Manager();
Initialize_Player_Information(player_x, player_y);
Init_NPC(null);
//start of initializing heart images and life bar for HUD display
Full_Heart = new Image("images/fullheart.png", false, Image.FILTER_NEAREST);
Empty_Heart = new Image("images/emptyheart.png", false, Image.FILTER_NEAREST);
Full_Heart.setAlpha(0.5f);
Empty_Heart.setAlpha(0.5f);
maxHealth = player.Get_Health(); //change from "final" if '+ heart containers' added to the game as a feature!
lifeBar = new boolean[maxHealth];
for (int i = 0; i < maxHealth; i++){
lifeBar[i] = true;
}
//initialize level
width = 20;
height = 15;
xpos = 0;
ypos = 0;
scale = 2;
bot_tile_x = new int[height][width];
bot_tile_y = new int[height][width];
File level = new File("levels/" + String.valueOf(level_index) + ".lvl");
short Tile_List[][] = null;
short Field_Types = 4;
try {
Tile_List = Files.Scan_LVL(level, Field_Types);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// load tiles
int k = 0;
for (int i = 0; i < height; i++ ){
for(int j = 0; j < width; j++){
bot_tile_x[i][j] = Tile_List[0][k];
bot_tile_y[i][j] = Tile_List[0][++k];
k++;
}
}
// load GObjects
if (Tile_List[1] != null)
{
int number_of_1s = 0;
for (int i = 0; i < Tile_List[1].length; i++)
{
if (Tile_List[1][i] == 1)
{
number_of_1s++;
}
}
objectlist = new GObject[number_of_1s];
int current_object = 0;
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
if (Tile_List[1][j + width*i] == 1)
{
objectlist[current_object++] = new GObject(
j, i, // tell which tile to start in
false, // tell whether the object is visible
true, // tell whether the object is solid for collision
null, null, // number of pixels each animation is shifted by
16, // give size of a tile in pixels
null, // give preinitialized animations
0 // tell which animation to start with
);
}
}
}
}
if (Tile_List[2] != null)
{
portallist = new GPortal[Tile_List[2].length/5];
for (int i = 0; i < Tile_List[2].length/5; i++)
{
portallist[i] = new GPortal(Tile_List[2][5*i],
Tile_List[2][5*i+1], 16, Tile_List[2][5*i+4],
Tile_List[2][5*i+2], Tile_List[2][5*i+3]);
}
}
if (Tile_List[3] != null)
{
npclist = new GCharacter[Tile_List[3].length/3];
for (int i = 0; i < Tile_List[3].length/3; i++)
{
if (Tile_List[3][i*3] == ZOMBIE)
npclist[i] = new Zombie(Tile_List[3][i*3+1],
Tile_List[3][i*3+2], character_sprites);
}
/*
npclist = new GCharacter[10];
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 2; j++)
{
npclist[i + 5*j] = new Zombie(8+i, 5+j, character_sprites);//make sure to add new files to the repository.
}
}
*/
}
}
|
diff --git a/taedium/src/me/taedium/android/add/WizardActivity.java b/taedium/src/me/taedium/android/add/WizardActivity.java
index 454c6ea..15be9ce 100644
--- a/taedium/src/me/taedium/android/add/WizardActivity.java
+++ b/taedium/src/me/taedium/android/add/WizardActivity.java
@@ -1,105 +1,108 @@
package me.taedium.android.add;
import me.taedium.android.HeaderActivity;
import me.taedium.android.R;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
public abstract class WizardActivity extends HeaderActivity {
protected final static int ACTIVITY_ADD_PEOPLE = 550;
protected final static int ACTIVITY_ADD_TIME = 551;
protected final static int ACTIVITY_ADD_ENVIRONMENT = 552;
protected final static int ACTIVITY_ADD_LOCATION = 553;
protected final static int ACTIVITY_ADD_TAGS = 554;
protected final static int ACTIVITY_FIRST_START = 555;
protected final static int DIALOG_HELP = 1001;
protected String title = "";
protected String helpText = "";
protected Bundle data;
protected Button bBack, bNext;
protected void initializeWizard(final Context context, final Class<?> cls, final int requestCode) {
// Initialize the header and help button
initializeHeader(new View.OnClickListener() {
@Override
public void onClick(View v) {
showDialog(DIALOG_HELP);
}
});
// Initialize the back and previous buttons
bNext = (Button)findViewById(R.id.bAddNext);
bNext.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
fillData();
Intent i = new Intent(context, cls);
i.putExtras(data);
startActivityForResult(i, requestCode);
}
});
bBack = (Button)findViewById(R.id.bAddBack);
bBack.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
fillData();
Intent i = new Intent();
i.putExtras(data);
setResult(RESULT_OK, i);
finish();
}
});
+ // Hopefully this fixes Issue #39
+ bNext.setBackgroundDrawable(getResources().getDrawable(R.drawable.b_add_nav_button));
+ bBack.setBackgroundDrawable(getResources().getDrawable(R.drawable.b_add_nav_button));
}
// Helper to format string correctly when adding them to the data bundle
// Inserts newlines correctly and removes tabs
protected String escapeString(String text) {
return text.replace("\n", "\\n").replace("\t", "");
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent i) {
if (resultCode == RESULT_OK) {
data = i.getExtras();
}
}
@Override
protected Dialog onCreateDialog(int id) {
Button bOk;
final Dialog dialog;
dialog = new Dialog(this, R.style.Dialog);
WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
lp.dimAmount = 0.0f;
dialog.getWindow().setAttributes(lp);
dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
switch(id) {
case DIALOG_HELP:
dialog.setContentView(R.layout.dialog_help);
dialog.setTitle(title);
TextView text = (TextView)dialog.findViewById(R.id.tvHelpText);
text.setText(helpText);
bOk = (Button)dialog.findViewById(R.id.bOk);
bOk.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dismissDialog(DIALOG_HELP);
}
});
break;
default:
// This activity dialog not known to this activity
return super.onCreateDialog(id);
}
return dialog;
}
protected abstract void fillData();
protected abstract void restoreData();
}
| true | true | protected void initializeWizard(final Context context, final Class<?> cls, final int requestCode) {
// Initialize the header and help button
initializeHeader(new View.OnClickListener() {
@Override
public void onClick(View v) {
showDialog(DIALOG_HELP);
}
});
// Initialize the back and previous buttons
bNext = (Button)findViewById(R.id.bAddNext);
bNext.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
fillData();
Intent i = new Intent(context, cls);
i.putExtras(data);
startActivityForResult(i, requestCode);
}
});
bBack = (Button)findViewById(R.id.bAddBack);
bBack.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
fillData();
Intent i = new Intent();
i.putExtras(data);
setResult(RESULT_OK, i);
finish();
}
});
}
| protected void initializeWizard(final Context context, final Class<?> cls, final int requestCode) {
// Initialize the header and help button
initializeHeader(new View.OnClickListener() {
@Override
public void onClick(View v) {
showDialog(DIALOG_HELP);
}
});
// Initialize the back and previous buttons
bNext = (Button)findViewById(R.id.bAddNext);
bNext.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
fillData();
Intent i = new Intent(context, cls);
i.putExtras(data);
startActivityForResult(i, requestCode);
}
});
bBack = (Button)findViewById(R.id.bAddBack);
bBack.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
fillData();
Intent i = new Intent();
i.putExtras(data);
setResult(RESULT_OK, i);
finish();
}
});
// Hopefully this fixes Issue #39
bNext.setBackgroundDrawable(getResources().getDrawable(R.drawable.b_add_nav_button));
bBack.setBackgroundDrawable(getResources().getDrawable(R.drawable.b_add_nav_button));
}
|
diff --git a/examples/org.eclipse.ocl.examples.xtext.base/src/org/eclipse/ocl/examples/xtext/base/scoping/cs/BaseScopeProvider.java b/examples/org.eclipse.ocl.examples.xtext.base/src/org/eclipse/ocl/examples/xtext/base/scoping/cs/BaseScopeProvider.java
index e4705e4813..2e19fdd6db 100644
--- a/examples/org.eclipse.ocl.examples.xtext.base/src/org/eclipse/ocl/examples/xtext/base/scoping/cs/BaseScopeProvider.java
+++ b/examples/org.eclipse.ocl.examples.xtext.base/src/org/eclipse/ocl/examples/xtext/base/scoping/cs/BaseScopeProvider.java
@@ -1,68 +1,68 @@
/**
* <copyright>
*
* Copyright (c) 2010 E.D.Willink 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:
* E.D.Willink - initial API and implementation
*
* </copyright>
*
* $Id: BaseScopeProvider.java,v 1.4 2011/04/20 19:02:27 ewillink Exp $
*/
package org.eclipse.ocl.examples.xtext.base.scoping.cs;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.ocl.examples.common.utils.TracingOption;
import org.eclipse.ocl.examples.pivot.manager.MetaModelManager;
import org.eclipse.ocl.examples.pivot.manager.MetaModelManagerResourceAdapter;
import org.eclipse.ocl.examples.xtext.base.baseCST.ElementCS;
import org.eclipse.ocl.examples.xtext.base.scope.BaseScopeView;
import org.eclipse.ocl.examples.xtext.base.utilities.ElementUtil;
import org.eclipse.xtext.common.types.TypesPackage;
import org.eclipse.xtext.scoping.IGlobalScopeProvider;
import org.eclipse.xtext.scoping.IScope;
import org.eclipse.xtext.scoping.impl.AbstractDeclarativeScopeProvider;
import com.google.inject.Inject;
/**
* This class contains custom scoping description.
*
* see : http://www.eclipse.org/Xtext/documentation/latest/xtext.html#scoping on
* how and when to use it
*
*/
public class BaseScopeProvider extends AbstractDeclarativeScopeProvider
{
@Inject
private IGlobalScopeProvider globalScopeProvider;
public static final TracingOption LOOKUP = new TracingOption(
"org.eclipse.ocl.examples.xtext.base", "lookup"); //$NON-NLS-1$//$NON-NLS-2$
@Override
public IScope getScope(EObject context, EReference reference) {
Resource csResource = context.eResource();
if (reference.getEReferenceType().getEPackage().getNsURI().equals(TypesPackage.eNS_URI)) {
return globalScopeProvider.getScope(csResource, reference, null);
}
MetaModelManagerResourceAdapter adapter = MetaModelManagerResourceAdapter.findAdapter(csResource);
if (adapter == null) {
- return null;
+ return IScope.NULLSCOPE;
}
MetaModelManager metaModelManager = adapter.getMetaModelManager();
ElementCS csElement = (ElementCS) context;
CSScopeAdapter scopeAdapter = ElementUtil.getScopeAdapter(csElement);
if (scopeAdapter == null) {
- return null;
+ return IScope.NULLSCOPE;
}
return new BaseScopeView(metaModelManager, csElement, scopeAdapter, null, reference, reference);
}
}
| false | true | public IScope getScope(EObject context, EReference reference) {
Resource csResource = context.eResource();
if (reference.getEReferenceType().getEPackage().getNsURI().equals(TypesPackage.eNS_URI)) {
return globalScopeProvider.getScope(csResource, reference, null);
}
MetaModelManagerResourceAdapter adapter = MetaModelManagerResourceAdapter.findAdapter(csResource);
if (adapter == null) {
return null;
}
MetaModelManager metaModelManager = adapter.getMetaModelManager();
ElementCS csElement = (ElementCS) context;
CSScopeAdapter scopeAdapter = ElementUtil.getScopeAdapter(csElement);
if (scopeAdapter == null) {
return null;
}
return new BaseScopeView(metaModelManager, csElement, scopeAdapter, null, reference, reference);
}
| public IScope getScope(EObject context, EReference reference) {
Resource csResource = context.eResource();
if (reference.getEReferenceType().getEPackage().getNsURI().equals(TypesPackage.eNS_URI)) {
return globalScopeProvider.getScope(csResource, reference, null);
}
MetaModelManagerResourceAdapter adapter = MetaModelManagerResourceAdapter.findAdapter(csResource);
if (adapter == null) {
return IScope.NULLSCOPE;
}
MetaModelManager metaModelManager = adapter.getMetaModelManager();
ElementCS csElement = (ElementCS) context;
CSScopeAdapter scopeAdapter = ElementUtil.getScopeAdapter(csElement);
if (scopeAdapter == null) {
return IScope.NULLSCOPE;
}
return new BaseScopeView(metaModelManager, csElement, scopeAdapter, null, reference, reference);
}
|
diff --git a/test-fabric-node/src/test/java/org/fabric3/test/node/FabricBindingTestCase.java b/test-fabric-node/src/test/java/org/fabric3/test/node/FabricBindingTestCase.java
index 0ee8377..edd40fb 100644
--- a/test-fabric-node/src/test/java/org/fabric3/test/node/FabricBindingTestCase.java
+++ b/test-fabric-node/src/test/java/org/fabric3/test/node/FabricBindingTestCase.java
@@ -1,82 +1,82 @@
/*
* Fabric3
* Copyright (c) 2009-2013 Metaform Systems
*
* Fabric3 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, with the
* following exception:
*
* Linking this software statically or dynamically with other
* modules is making a combined work based on this software.
* Thus, the terms and conditions of the GNU General Public
* License cover the whole combination.
*
* As a special exception, the copyright holders of this software
* give you permission to link this software 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 software. If you modify this software, you may
* extend this exception to your version of the software, but
* you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version.
*
* Fabric3 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 Fabric3.
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.fabric3.test.node;
import junit.framework.TestCase;
import org.fabric3.api.node.Bootstrap;
import org.fabric3.api.node.Domain;
import org.fabric3.api.node.Fabric;
import org.oasisopen.sca.ServiceRuntimeException;
/**
*
*/
public class FabricBindingTestCase extends TestCase {
public void testDeployServiceEndpoint() throws Exception {
- Fabric fabric = Bootstrap.initialize();
+ Fabric fabric = Bootstrap.initialize(getClass().getResource("/testConfig.xml"));
fabric.addProfile("rs").addExtension("fabric3-databinding-json").addExtension("fabric3-jetty");
fabric.start();
Domain domain = fabric.getDomain();
TestRsServiceImpl instance = new TestRsServiceImpl();
domain.deploy("TestRsService", instance);
-// ComponentDefinitionBuilder builder = ComponentDefinitionBuilder.newBuilder("TestRsService", instance);
-// BindingDefinition bindingDefinition = new RsBindingDefinition("TestRsService", URI.create("/service"));
-// builder.binding("TestRsService", bindingDefinition);
-//
-// ComponentDefinition definition = builder.build();
-//
-// domain.deploy(definition);
+ // ComponentDefinitionBuilder builder = ComponentDefinitionBuilder.newBuilder("TestRsService", instance);
+ // BindingDefinition bindingDefinition = new RsBindingDefinition("TestRsService", URI.create("/service"));
+ // builder.binding("TestRsService", bindingDefinition);
+ //
+ // ComponentDefinition definition = builder.build();
+ //
+ // domain.deploy(definition);
TestRsService service = domain.getService(TestRsService.class);
assertEquals("test", service.test());
domain.undeploy("TestRsService");
try {
domain.getService(TestService.class);
fail();
} catch (ServiceRuntimeException e) {
// expected
}
fabric.stop();
}
}
| false | true | public void testDeployServiceEndpoint() throws Exception {
Fabric fabric = Bootstrap.initialize();
fabric.addProfile("rs").addExtension("fabric3-databinding-json").addExtension("fabric3-jetty");
fabric.start();
Domain domain = fabric.getDomain();
TestRsServiceImpl instance = new TestRsServiceImpl();
domain.deploy("TestRsService", instance);
// ComponentDefinitionBuilder builder = ComponentDefinitionBuilder.newBuilder("TestRsService", instance);
// BindingDefinition bindingDefinition = new RsBindingDefinition("TestRsService", URI.create("/service"));
// builder.binding("TestRsService", bindingDefinition);
//
// ComponentDefinition definition = builder.build();
//
// domain.deploy(definition);
TestRsService service = domain.getService(TestRsService.class);
assertEquals("test", service.test());
domain.undeploy("TestRsService");
try {
domain.getService(TestService.class);
fail();
} catch (ServiceRuntimeException e) {
// expected
}
fabric.stop();
}
| public void testDeployServiceEndpoint() throws Exception {
Fabric fabric = Bootstrap.initialize(getClass().getResource("/testConfig.xml"));
fabric.addProfile("rs").addExtension("fabric3-databinding-json").addExtension("fabric3-jetty");
fabric.start();
Domain domain = fabric.getDomain();
TestRsServiceImpl instance = new TestRsServiceImpl();
domain.deploy("TestRsService", instance);
// ComponentDefinitionBuilder builder = ComponentDefinitionBuilder.newBuilder("TestRsService", instance);
// BindingDefinition bindingDefinition = new RsBindingDefinition("TestRsService", URI.create("/service"));
// builder.binding("TestRsService", bindingDefinition);
//
// ComponentDefinition definition = builder.build();
//
// domain.deploy(definition);
TestRsService service = domain.getService(TestRsService.class);
assertEquals("test", service.test());
domain.undeploy("TestRsService");
try {
domain.getService(TestService.class);
fail();
} catch (ServiceRuntimeException e) {
// expected
}
fabric.stop();
}
|
diff --git a/src/main/java/me/arno/blocklog/schedules/AliveSchedule.java b/src/main/java/me/arno/blocklog/schedules/AliveSchedule.java
index fa7d087..8efc695 100644
--- a/src/main/java/me/arno/blocklog/schedules/AliveSchedule.java
+++ b/src/main/java/me/arno/blocklog/schedules/AliveSchedule.java
@@ -1,18 +1,18 @@
package me.arno.blocklog.schedules;
import java.sql.SQLException;
import me.arno.blocklog.BlockLog;
import me.arno.blocklog.util.Util;
public class AliveSchedule implements Runnable {
@Override
public void run() {
try {
- BlockLog.getInstance().getConnection().createStatement().executeUpdate("UPDATE blocklog_data SET `id`=1 WHERE `id`=1");
+ BlockLog.getInstance().getConnection().createStatement().executeUpdate("UPDATE " + BlockLog.getInstance().getDatabaseManager().getPrefix() + "data SET `id`=1 WHERE `id`=1");
} catch(SQLException e) {
Util.sendNotice("Something went wrong while sending the alive query");
}
}
}
| true | true | public void run() {
try {
BlockLog.getInstance().getConnection().createStatement().executeUpdate("UPDATE blocklog_data SET `id`=1 WHERE `id`=1");
} catch(SQLException e) {
Util.sendNotice("Something went wrong while sending the alive query");
}
}
| public void run() {
try {
BlockLog.getInstance().getConnection().createStatement().executeUpdate("UPDATE " + BlockLog.getInstance().getDatabaseManager().getPrefix() + "data SET `id`=1 WHERE `id`=1");
} catch(SQLException e) {
Util.sendNotice("Something went wrong while sending the alive query");
}
}
|
diff --git a/src/com/vaadin/terminal/gwt/client/ApplicationConnection.java b/src/com/vaadin/terminal/gwt/client/ApplicationConnection.java
index 5f71183c2..be11dc361 100755
--- a/src/com/vaadin/terminal/gwt/client/ApplicationConnection.java
+++ b/src/com/vaadin/terminal/gwt/client/ApplicationConnection.java
@@ -1,2269 +1,2273 @@
/*
@ITMillApache2LicenseForJavaFiles@
*/
package com.vaadin.terminal.gwt.client;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.core.client.JsArrayString;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.DeferredCommand;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.FocusWidget;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;
import com.vaadin.terminal.gwt.client.RenderInformation.FloatSize;
import com.vaadin.terminal.gwt.client.RenderInformation.Size;
import com.vaadin.terminal.gwt.client.ui.Field;
import com.vaadin.terminal.gwt.client.ui.VContextMenu;
import com.vaadin.terminal.gwt.client.ui.VNotification;
import com.vaadin.terminal.gwt.client.ui.VView;
import com.vaadin.terminal.gwt.client.ui.VNotification.HideEvent;
import com.vaadin.terminal.gwt.client.ui.dd.VDragAndDropManager;
import com.vaadin.terminal.gwt.server.AbstractCommunicationManager;
/**
* This is the client side communication "engine", managing client-server
* communication with its server side counterpart
* {@link AbstractCommunicationManager}.
*
* Client-side widgets receive updates from the corresponding server-side
* components as calls to
* {@link Paintable#updateFromUIDL(UIDL, ApplicationConnection)} (not to be
* confused with the server side interface {@link com.vaadin.terminal.Paintable}
* ). Any client-side changes (typically resulting from user actions) are sent
* back to the server as variable changes (see {@link #updateVariable()}).
*
* TODO document better
*
* Entry point classes (widgetsets) define <code>onModuleLoad()</code>.
*/
public class ApplicationConnection {
// This indicates the whole page is generated by us (not embedded)
public static final String GENERATED_BODY_CLASSNAME = "v-generated-body";
private static final String MODIFIED_CLASSNAME = "v-modified";
private static final String REQUIRED_CLASSNAME_EXT = "-required";
private static final String ERROR_CLASSNAME_EXT = "-error";
public static final String VAR_RECORD_SEPARATOR = "\u001e";
public static final String VAR_FIELD_SEPARATOR = "\u001f";
public static final String VAR_BURST_SEPARATOR = "\u001d";
public static final String VAR_ARRAYITEM_SEPARATOR = "\u001c";
public static final String UIDL_SECURITY_TOKEN_ID = "Vaadin-Security-Key";
/**
* @deprecated use UIDL_SECURITY_TOKEN_ID instead
*/
@Deprecated
public static final String UIDL_SECURITY_HEADER = UIDL_SECURITY_TOKEN_ID;
public static final String PARAM_UNLOADBURST = "onunloadburst";
public static final String ATTRIBUTE_DESCRIPTION = "description";
public static final String ATTRIBUTE_ERROR = "error";
// will hold the UIDL security key (for XSS protection) once received
private String uidl_security_key = "init";
private final HashMap<String, String> resourcesMap = new HashMap<String, String>();
private static Console console;
private final ArrayList<String> pendingVariables = new ArrayList<String>();
private final ComponentDetailMap idToPaintableDetail = ComponentDetailMap
.create();
private final WidgetSet widgetSet;
private VContextMenu contextMenu = null;
private Timer loadTimer;
private Timer loadTimer2;
private Timer loadTimer3;
private Element loadElement;
private final VView view;
private boolean applicationRunning = false;
private int activeRequests = 0;
/** Parameters for this application connection loaded from the web-page */
private final ApplicationConfiguration configuration;
/** List of pending variable change bursts that must be submitted in order */
private final ArrayList<ArrayList<String>> pendingVariableBursts = new ArrayList<ArrayList<String>>();
/** Timer for automatic refirect to SessionExpiredURL */
private Timer redirectTimer;
/** redirectTimer scheduling interval in seconds */
private int sessionExpirationInterval;
private ArrayList<Paintable> relativeSizeChanges = new ArrayList<Paintable>();;
private ArrayList<Paintable> componentCaptionSizeChanges = new ArrayList<Paintable>();;
private Date requestStartTime;
private boolean validatingLayouts = false;
private Set<Paintable> zeroWidthComponents = null;
private Set<Paintable> zeroHeightComponents = null;
/**
* Keeps track of if there are (potentially) {@link DeferredCommand}s that
* are being executed. 0 == no DeferredCommands currently in progress, > 0
* otherwise.
*/
private int deferredCommandTrackers = 0;
public ApplicationConnection(WidgetSet widgetSet,
ApplicationConfiguration cnf) {
this.widgetSet = widgetSet;
configuration = cnf;
windowName = configuration.getInitialWindowName();
if (isDebugMode()) {
console = new VDebugConsole(this, cnf, !isQuietDebugMode());
} else {
console = new NullConsole();
}
ComponentLocator componentLocator = new ComponentLocator(this);
String appRootPanelName = cnf.getRootPanelId();
// remove the end (window name) of autogenerated rootpanel id
appRootPanelName = appRootPanelName.replaceFirst("-\\d+$", "");
initializeTestbenchHooks(componentLocator, appRootPanelName);
initializeClientHooks();
view = new VView(cnf.getRootPanelId());
showLoadingIndicator();
}
/**
* Starts this application. Don't call this method directly - it's called by
* {@link ApplicationConfiguration#startNextApplication()}, which should be
* called once this application has started (first response received) or
* failed to start. This ensures that the applications are started in order,
* to avoid session-id problems.
*/
void start() {
makeUidlRequest("", true, false, false);
}
private native void initializeTestbenchHooks(
ComponentLocator componentLocator, String TTAppId)
/*-{
var ap = this;
var client = {};
client.isActive = function() {
return [email protected]::hasActiveRequest()() || [email protected]::isExecutingDeferredCommands()();
}
var vi = [email protected]::getVersionInfo()();
if (vi) {
client.getVersionInfo = function() {
return vi;
}
}
client.getElementByPath = function(id) {
return componentLocator.@com.vaadin.terminal.gwt.client.ComponentLocator::getElementByPath(Ljava/lang/String;)(id);
}
client.getPathForElement = function(element) {
return componentLocator.@com.vaadin.terminal.gwt.client.ComponentLocator::getPathForElement(Lcom/google/gwt/user/client/Element;)(element);
}
if(!$wnd.vaadin.clients) {
$wnd.vaadin.clients = {};
}
$wnd.vaadin.clients[TTAppId] = client;
}-*/;
/**
* Helper for tt initialization
*/
@SuppressWarnings("unused")
private JavaScriptObject getVersionInfo() {
return configuration.getVersionInfoJSObject();
}
/**
* Publishes a JavaScript API for mash-up applications.
* <ul>
* <li><code>vaadin.forceSync()</code> sends pending variable changes, in
* effect synchronizing the server and client state. This is done for all
* applications on host page.</li>
* <li><code>vaadin.postRequestHooks</code> is a map of functions which gets
* called after each XHR made by vaadin application. Note, that it is
* attaching js functions responsibility to create the variable like this:
*
* <code><pre>
* if(!vaadin.postRequestHooks) {vaadin.postRequestHooks = new Object();}
* postRequestHooks.myHook = function(appId) {
* if(appId == "MyAppOfInterest") {
* // do the staff you need on xhr activity
* }
* }
* </pre></code> First parameter passed to these functions is the identifier
* of Vaadin application that made the request.
* </ul>
*
* TODO make this multi-app aware
*/
private native void initializeClientHooks()
/*-{
var app = this;
var oldSync;
if($wnd.vaadin.forceSync) {
oldSync = $wnd.vaadin.forceSync;
}
$wnd.vaadin.forceSync = function() {
if(oldSync) {
oldSync();
}
[email protected]::sendPendingVariableChanges()();
}
var oldForceLayout;
if($wnd.vaadin.forceLayout) {
oldForceLayout = $wnd.vaadin.forceLayout;
}
$wnd.vaadin.forceLayout = function() {
if(oldForceLayout) {
oldForceLayout();
}
[email protected]::forceLayout()();
}
}-*/;
/**
* Runs possibly registered client side post request hooks. This is expected
* to be run after each uidl request made by Vaadin application.
*
* @param appId
*/
private static native void runPostRequestHooks(String appId)
/*-{
if($wnd.vaadin.postRequestHooks) {
for(var hook in $wnd.vaadin.postRequestHooks) {
if(typeof($wnd.vaadin.postRequestHooks[hook]) == "function") {
try {
$wnd.vaadin.postRequestHooks[hook](appId);
} catch(e) {}
}
}
}
}-*/;
/**
* Get the active Console for writing debug messages. May return an actual
* logging console, or the NullConsole if debugging is not turned on.
*
* @return the active Console
*/
public static Console getConsole() {
return console;
}
/**
* Checks if client side is in debug mode. Practically this is invoked by
* adding ?debug parameter to URI.
*
* @return true if client side is currently been debugged
*/
public native static boolean isDebugMode()
/*-{
if($wnd.vaadin.debug) {
var parameters = $wnd.location.search;
var re = /debug[^\/]*$/;
return re.test(parameters);
} else {
return false;
}
}-*/;
private native static boolean isQuietDebugMode()
/*-{
var uri = $wnd.location;
var re = /debug=q[^\/]*$/;
return re.test(uri);
}-*/;
/**
* Gets the application base URI. Using this other than as the download
* action URI can cause problems in Portlet 2.0 deployments.
*
* @return application base URI
*/
public String getAppUri() {
return configuration.getApplicationUri();
};
/**
* Indicates whether or not there are currently active UIDL requests. Used
* internally to squence requests properly, seldom needed in Widgets.
*
* @return true if there are active requests
*/
public boolean hasActiveRequest() {
return (activeRequests > 0);
}
private void makeUidlRequest(final String requestData,
final boolean repaintAll, final boolean forceSync,
final boolean analyzeLayouts) {
startRequest();
// Security: double cookie submission pattern
final String rd = uidl_security_key + VAR_BURST_SEPARATOR + requestData;
console.log("Making UIDL Request with params: " + rd);
String uri;
if (configuration.usePortletURLs()) {
uri = configuration.getPortletUidlURLBase();
} else {
uri = getAppUri() + "UIDL" + configuration.getPathInfo();
}
if (repaintAll) {
// collect some client side data that will be sent to server on
// initial uidl request
int clientHeight = Window.getClientHeight();
int clientWidth = Window.getClientWidth();
com.google.gwt.dom.client.Element pe = view.getElement()
.getParentElement();
int offsetHeight = pe.getOffsetHeight();
int offsetWidth = pe.getOffsetWidth();
int screenWidth = BrowserInfo.get().getScreenWidth();
int screenHeight = BrowserInfo.get().getScreenHeight();
String token = History.getToken();
// TODO figure out how client and view size could be used better on
// server. screen size can be accessed via Browser object, but other
// values currently only via transaction listener.
if (configuration.usePortletURLs()) {
uri += "&";
} else {
uri += "?";
}
uri += "repaintAll=1&" + "sh=" + screenHeight + "&sw="
+ screenWidth + "&cw=" + clientWidth + "&ch="
+ clientHeight + "&vw=" + offsetWidth + "&vh="
+ offsetHeight + "&fr=" + token;
if (analyzeLayouts) {
uri += "&analyzeLayouts=1";
}
}
if (windowName != null && windowName.length() > 0) {
uri += (repaintAll || configuration.usePortletURLs() ? "&" : "?")
+ "windowName=" + windowName;
}
if (!forceSync) {
final RequestBuilder rb = new RequestBuilder(RequestBuilder.POST,
uri);
// TODO enable timeout
// rb.setTimeoutMillis(timeoutMillis);
rb.setHeader("Content-Type", "text/plain;charset=utf-8");
try {
rb.sendRequest(rd, new RequestCallback() {
public void onError(Request request, Throwable exception) {
showCommunicationError(exception.getMessage());
endRequest();
if (!applicationRunning) {
// start failed, let's try to start the next app
ApplicationConfiguration.startNextApplication();
}
}
public void onResponseReceived(Request request,
Response response) {
console.log("Server visit took "
+ String.valueOf((new Date()).getTime()
- requestStartTime.getTime()) + "ms");
int statusCode = response.getStatusCode();
if ((statusCode / 100) == 4) {
// Handle all 4xx errors the same way as (they are
// all permanent errors)
showCommunicationError("UIDL could not be read from server. Check servlets mappings. Error code: "
+ statusCode);
endRequest();
return;
}
switch (statusCode) {
case 0:
showCommunicationError("Invalid status code 0 (server down?)");
endRequest();
return;
case 503:
// We'll assume msec instead of the usual seconds
int delay = Integer.parseInt(response
.getHeader("Retry-After"));
console.log("503, retrying in " + delay + "msec");
(new Timer() {
@Override
public void run() {
activeRequests--;
makeUidlRequest(requestData, repaintAll,
forceSync, analyzeLayouts);
}
}).schedule(delay);
return;
}
if (applicationRunning) {
handleReceivedJSONMessage(response);
} else {
applicationRunning = true;
handleWhenCSSLoaded(response);
ApplicationConfiguration.startNextApplication();
}
}
int cssWaits = 0;
static final int MAX_CSS_WAITS = 20;
private void handleWhenCSSLoaded(final Response response) {
int heightOfLoadElement = DOM.getElementPropertyInt(
loadElement, "offsetHeight");
if (heightOfLoadElement == 0
&& cssWaits < MAX_CSS_WAITS) {
(new Timer() {
@Override
public void run() {
handleWhenCSSLoaded(response);
}
}).schedule(50);
console
.log("Assuming CSS loading is not complete, "
+ "postponing render phase. "
+ "(.v-loading-indicator height == 0)");
cssWaits++;
} else {
handleReceivedJSONMessage(response);
if (cssWaits >= MAX_CSS_WAITS) {
console
.error("CSS files may have not loaded properly.");
}
}
}
});
} catch (final RequestException e) {
ClientExceptionHandler.displayError(e);
endRequest();
}
} else {
// Synchronized call, discarded response (leaving the page)
SynchronousXHR syncXHR = (SynchronousXHR) SynchronousXHR.create();
syncXHR.synchronousPost(uri + "&" + PARAM_UNLOADBURST + "=1", rd);
/*
* Although we are in theory leaving the page, the page may still
* stay open. End request properly here too. See #3289
*/
endRequest();
}
}
/**
* Shows the communication error notification.
*
* @param details
* Optional details for debugging.
*/
private void showCommunicationError(String details) {
console.error("Communication error: " + details);
StringBuilder html = new StringBuilder();
if (configuration.getCommunicationErrorCaption() != null) {
html.append("<h1>");
html.append(configuration.getCommunicationErrorCaption());
html.append("</h1>");
}
if (configuration.getCommunicationErrorMessage() != null) {
html.append("<p>");
html.append(configuration.getCommunicationErrorMessage());
html.append("</p>");
}
if (html.length() > 0) {
// Add error description
html.append("<br/><p><I style=\"font-size:0.7em\">");
html.append(details);
html.append("</I></p>");
VNotification n = new VNotification(1000 * 60 * 45);
n.addEventListener(new NotificationRedirect(configuration
.getCommunicationErrorUrl()));
n.show(html.toString(), VNotification.CENTERED_TOP,
VNotification.STYLE_SYSTEM);
} else {
redirect(configuration.getCommunicationErrorUrl());
}
}
private void startRequest() {
activeRequests++;
requestStartTime = new Date();
// show initial throbber
if (loadTimer == null) {
loadTimer = new Timer() {
@Override
public void run() {
/*
* IE7 does not properly cancel the event with
* loadTimer.cancel() so we have to check that we really
* should make it visible
*/
if (loadTimer != null) {
showLoadingIndicator();
}
}
};
// First one kicks in at 300ms
}
loadTimer.schedule(300);
}
private void endRequest() {
if (applicationRunning) {
checkForPendingVariableBursts();
runPostRequestHooks(configuration.getRootPanelId());
}
activeRequests--;
// deferring to avoid flickering
DeferredCommand.addCommand(new Command() {
public void execute() {
if (activeRequests == 0) {
hideLoadingIndicator();
}
}
});
addDeferredCommandTracker();
}
/**
* Adds a {@link DeferredCommand} tracker. Increments the tracker count when
* called and decrements in a DeferredCommand that is executed after all
* other DeferredCommands have executed.
*
*/
private void addDeferredCommandTracker() {
deferredCommandTrackers++;
DeferredCommand.addCommand(new Command() {
public void execute() {
deferredCommandTrackers--;
}
});
}
/**
* This method is called after applying uidl change set to application.
*
* It will clean current and queued variable change sets. And send next
* change set if it exists.
*/
private void checkForPendingVariableBursts() {
cleanVariableBurst(pendingVariables);
if (pendingVariableBursts.size() > 0) {
for (Iterator<ArrayList<String>> iterator = pendingVariableBursts
.iterator(); iterator.hasNext();) {
cleanVariableBurst(iterator.next());
}
ArrayList<String> nextBurst = pendingVariableBursts.get(0);
pendingVariableBursts.remove(0);
buildAndSendVariableBurst(nextBurst, false);
}
}
/**
* Cleans given queue of variable changes of such changes that came from
* components that do not exist anymore.
*
* @param variableBurst
*/
private void cleanVariableBurst(ArrayList<String> variableBurst) {
for (int i = 1; i < variableBurst.size(); i += 2) {
String id = variableBurst.get(i);
id = id.substring(0, id.indexOf(VAR_FIELD_SEPARATOR));
if (!idToPaintableDetail.containsKey(id) && !id.startsWith("DD")) {
// variable owner does not exist anymore
variableBurst.remove(i - 1);
variableBurst.remove(i - 1);
i -= 2;
ApplicationConnection.getConsole().log(
"Removed variable from removed component: " + id);
}
}
}
private void showLoadingIndicator() {
// show initial throbber
if (loadElement == null) {
loadElement = DOM.createDiv();
DOM.setStyleAttribute(loadElement, "position", "absolute");
DOM.appendChild(view.getElement(), loadElement);
ApplicationConnection.getConsole().log("inserting load indicator");
}
DOM.setElementProperty(loadElement, "className", "v-loading-indicator");
DOM.setStyleAttribute(loadElement, "display", "block");
// Initialize other timers
loadTimer2 = new Timer() {
@Override
public void run() {
DOM.setElementProperty(loadElement, "className",
"v-loading-indicator-delay");
}
};
// Second one kicks in at 1500ms from request start
loadTimer2.schedule(1200);
loadTimer3 = new Timer() {
@Override
public void run() {
DOM.setElementProperty(loadElement, "className",
"v-loading-indicator-wait");
}
};
// Third one kicks in at 5000ms from request start
loadTimer3.schedule(4700);
}
private void hideLoadingIndicator() {
if (loadTimer != null) {
loadTimer.cancel();
if (loadTimer2 != null) {
loadTimer2.cancel();
loadTimer3.cancel();
}
loadTimer = null;
}
if (loadElement != null) {
DOM.setStyleAttribute(loadElement, "display", "none");
}
}
/**
* Checks if {@link DeferredCommand}s are (potentially) still being executed
* as a result of an update from the server. Returns true if a
* DeferredCommand might still be executing, false otherwise. This will fail
* if a DeferredCommand adds another DeferredCommand.
* <p>
* Called by the native "client.isActive" function.
* </p>
*
* @return
*/
@SuppressWarnings("unused")
private boolean isExecutingDeferredCommands() {
return (deferredCommandTrackers > 0);
}
/**
* Determines whether or not the loading indicator is showing.
*
* @return true if the loading indicator is visible
*/
public boolean isLoadingIndicatorVisible() {
if (loadElement == null) {
return false;
}
if (loadElement.getStyle().getProperty("display").equals("none")) {
return false;
}
return true;
}
private static native ValueMap parseJSONResponse(String jsonText)
/*-{
try {
return JSON.parse(jsonText);
} catch(ignored) {
return eval('(' + jsonText + ')');
}
}-*/;
private void handleReceivedJSONMessage(Response response) {
final Date start = new Date();
// for(;;);[realjson]
final String jsonText = response.getText().substring(9,
response.getText().length() - 1);
final ValueMap json;
try {
json = parseJSONResponse(jsonText);
} catch (final Exception e) {
endRequest();
showCommunicationError(e.getMessage() + " - Original JSON-text:");
console.log(jsonText);
return;
}
ApplicationConnection.getConsole().log(
"JSON parsing took " + (new Date().getTime() - start.getTime())
+ "ms");
// Handle redirect
if (json.containsKey("redirect")) {
String url = json.getValueMap("redirect").getString("url");
console.log("redirecting to " + url);
redirect(url);
return;
}
// Get security key
if (json.containsKey(UIDL_SECURITY_TOKEN_ID)) {
uidl_security_key = json.getString(UIDL_SECURITY_TOKEN_ID);
}
if (json.containsKey("resources")) {
ValueMap resources = json.getValueMap("resources");
JsArrayString keyArray = resources.getKeyArray();
int l = keyArray.length();
for (int i = 0; i < l; i++) {
String key = keyArray.get(i);
resourcesMap.put(key, resources.getAsString(key));
}
}
if (json.containsKey("typeMappings")) {
configuration.addComponentMappings(
json.getValueMap("typeMappings"), widgetSet);
}
Command c = new Command() {
public void execute() {
if (json.containsKey("locales")) {
// Store locale data
JsArray<ValueMap> valueMapArray = json
.getJSValueMapArray("locales");
LocaleService.addLocales(valueMapArray);
}
ValueMap meta = null;
if (json.containsKey("meta")) {
meta = json.getValueMap("meta");
if (meta.containsKey("repaintAll")) {
view.clear();
idToPaintableDetail.clear();
if (meta.containsKey("invalidLayouts")) {
validatingLayouts = true;
zeroWidthComponents = new HashSet<Paintable>();
zeroHeightComponents = new HashSet<Paintable>();
}
}
if (meta.containsKey("timedRedirect")) {
final ValueMap timedRedirect = meta
.getValueMap("timedRedirect");
redirectTimer = new Timer() {
@Override
public void run() {
redirect(timedRedirect.getString("url"));
}
};
sessionExpirationInterval = timedRedirect
.getInt("interval");
}
}
if (redirectTimer != null) {
redirectTimer.schedule(1000 * sessionExpirationInterval);
}
// Process changes
JsArray<ValueMap> changes = json.getJSValueMapArray("changes");
ArrayList<Paintable> updatedWidgets = new ArrayList<Paintable>();
relativeSizeChanges.clear();
componentCaptionSizeChanges.clear();
int length = changes.length();
for (int i = 0; i < length; i++) {
try {
final UIDL change = changes.get(i).cast();
try {
console.dirUIDL(change);
} catch (final Exception e) {
ClientExceptionHandler.displayError(e);
// TODO: dir doesn't work in any browser although it
// should
// work (works in hosted mode)
// it partially did at some part but now broken.
}
final UIDL uidl = change.getChildUIDL(0);
// TODO optimize
final Paintable paintable = getPaintable(uidl.getId());
if (paintable != null) {
paintable.updateFromUIDL(uidl,
ApplicationConnection.this);
// paintable may have changed during render to
// another
// implementation, use the new one for updated
// widgets map
updatedWidgets.add(idToPaintableDetail.get(
uidl.getId()).getComponent());
} else {
if (!uidl.getTag().equals(
configuration.getEncodedWindowTag())) {
ClientExceptionHandler
.displayError("Received update for "
+ uidl.getTag()
+ ", but there is no such paintable ("
+ uidl.getId() + ") rendered.");
} else {
+ if (!idToPaintableDetail.containsKey(uidl
+ .getId())) {
+ registerPaintable(uidl.getId(), view);
+ }
view.updateFromUIDL(uidl,
ApplicationConnection.this);
}
}
} catch (final Throwable e) {
ClientExceptionHandler.displayError(e);
}
}
if (json.containsKey("dd")) {
// response contains data for drag and drop service
VDragAndDropManager.get().handleServerResponse(
json.getValueMap("dd"));
}
// Check which widgets' size has been updated
Set<Paintable> sizeUpdatedWidgets = new HashSet<Paintable>();
updatedWidgets.addAll(relativeSizeChanges);
sizeUpdatedWidgets.addAll(componentCaptionSizeChanges);
for (Paintable paintable : updatedWidgets) {
ComponentDetail detail = idToPaintableDetail
.get(getPid(paintable));
Widget widget = (Widget) paintable;
Size oldSize = detail.getOffsetSize();
Size newSize = new Size(widget.getOffsetWidth(), widget
.getOffsetHeight());
if (oldSize == null || !oldSize.equals(newSize)) {
sizeUpdatedWidgets.add(paintable);
detail.setOffsetSize(newSize);
}
}
Util.componentSizeUpdated(sizeUpdatedWidgets);
if (meta != null) {
if (meta.containsKey("appError")) {
ValueMap error = meta.getValueMap("appError");
String html = "";
if (error.containsKey("caption")
&& error.getString("caption") != null) {
html += "<h1>" + error.getAsString("caption")
+ "</h1>";
}
if (error.containsKey("message")
&& error.getString("message") != null) {
html += "<p>" + error.getAsString("message")
+ "</p>";
}
String url = null;
if (error.containsKey("url")) {
url = error.getString("url");
}
if (html.length() != 0) {
/* 45 min */
VNotification n = new VNotification(1000 * 60 * 45);
n.addEventListener(new NotificationRedirect(url));
n.show(html, VNotification.CENTERED_TOP,
VNotification.STYLE_SYSTEM);
} else {
redirect(url);
}
applicationRunning = false;
}
if (validatingLayouts) {
getConsole().printLayoutProblems(meta,
ApplicationConnection.this,
zeroHeightComponents, zeroWidthComponents);
zeroHeightComponents = null;
zeroWidthComponents = null;
validatingLayouts = false;
}
}
// TODO build profiling for widget impl loading time
final long prosessingTime = (new Date().getTime())
- start.getTime();
console.log(" Processing time was "
+ String.valueOf(prosessingTime) + "ms for "
+ jsonText.length() + " characters of JSON");
console.log("Referenced paintables: "
+ idToPaintableDetail.size());
endRequest();
}
};
ApplicationConfiguration.runWhenWidgetsLoaded(c);
}
/**
* This method assures that all pending variable changes are sent to server.
* Method uses synchronized xmlhttprequest and does not return before the
* changes are sent. No UIDL updates are processed and thus UI is left in
* inconsistent state. This method should be called only when closing
* windows - normally sendPendingVariableChanges() should be used.
*/
public void sendPendingVariableChangesSync() {
if (applicationRunning) {
pendingVariableBursts.add(pendingVariables);
ArrayList<String> nextBurst = pendingVariableBursts.get(0);
pendingVariableBursts.remove(0);
buildAndSendVariableBurst(nextBurst, true);
}
}
// Redirect browser, null reloads current page
private static native void redirect(String url)
/*-{
if (url) {
$wnd.location = url;
} else {
$wnd.location.reload(false);
}
}-*/;
public void registerPaintable(String pid, Paintable paintable) {
ComponentDetail componentDetail = new ComponentDetail(this, pid,
paintable);
idToPaintableDetail.put(pid, componentDetail);
setPid(((Widget) paintable).getElement(), pid);
}
private native void setPid(Element el, String pid)
/*-{
el.tkPid = pid;
}-*/;
/**
* Gets the paintableId for a specific paintable (a.k.a Vaadin Widget).
* <p>
* The paintableId is used in the UIDL to identify a specific widget
* instance, effectively linking the widget with it's server side Component.
* </p>
*
* @param paintable
* the paintable who's id is needed
* @return the id for the given paintable
*/
public String getPid(Paintable paintable) {
return getPid(((Widget) paintable).getElement());
}
/**
* Gets the paintableId using a DOM element - the element should be the main
* element for a paintable otherwise no id will be found. Use
* {@link #getPid(Paintable)} instead whenever possible.
*
* @see #getPid(Paintable)
* @param el
* element of the paintable whose pid is desired
* @return the pid of the element's paintable, if it's a paintable
*/
public native String getPid(Element el)
/*-{
return el.tkPid;
}-*/;
/**
* Gets the main element for the paintable with the given id. The revers of
* {@link #getPid(Element)}.
*
* @param pid
* the pid of the widget whose element is desired
* @return the element for the paintable corresponding to the pid
*/
public Element getElementByPid(String pid) {
return ((Widget) getPaintable(pid)).getElement();
}
/**
* Unregisters the given paintable; always use after removing a paintable.
* Does not actually remove the paintable from the DOM.
*
* @param p
* the paintable to remove
*/
public void unregisterPaintable(Paintable p) {
if (p == null) {
ApplicationConnection.getConsole().error(
"WARN: Trying to unregister null paintable");
return;
}
String id = getPid(p);
idToPaintableDetail.remove(id);
if (p instanceof HasWidgets) {
unregisterChildPaintables((HasWidgets) p);
}
}
/**
* Unregisters a paintable and all it's child paintables recursively. Use
* when after removing a paintable that contains other paintables. Does not
* unregister the given container itself. Does not actually remove the
* paintable from the DOM.
*
* @see #unregisterPaintable(Paintable)
* @param container
*/
public void unregisterChildPaintables(HasWidgets container) {
final Iterator<Widget> it = container.iterator();
while (it.hasNext()) {
final Widget w = it.next();
if (w instanceof Paintable) {
unregisterPaintable((Paintable) w);
} else if (w instanceof HasWidgets) {
unregisterChildPaintables((HasWidgets) w);
}
}
}
/**
* Returns Paintable element by its id
*
* @param id
* Paintable ID
*/
public Paintable getPaintable(String id) {
ComponentDetail componentDetail = idToPaintableDetail.get(id);
if (componentDetail == null) {
return null;
} else {
return componentDetail.getComponent();
}
}
private void addVariableToQueue(String paintableId, String variableName,
String encodedValue, boolean immediate, char type) {
final String id = paintableId + VAR_FIELD_SEPARATOR + variableName
+ VAR_FIELD_SEPARATOR + type;
for (int i = 1; i < pendingVariables.size(); i += 2) {
if ((pendingVariables.get(i)).equals(id)) {
pendingVariables.remove(i - 1);
pendingVariables.remove(i - 1);
break;
}
}
pendingVariables.add(encodedValue);
pendingVariables.add(id);
if (immediate) {
sendPendingVariableChanges();
}
}
/**
* This method sends currently queued variable changes to server. It is
* called when immediate variable update must happen.
*
* To ensure correct order for variable changes (due servers multithreading
* or network), we always wait for active request to be handler before
* sending a new one. If there is an active request, we will put varible
* "burst" to queue that will be purged after current request is handled.
*
*/
@SuppressWarnings("unchecked")
public void sendPendingVariableChanges() {
if (applicationRunning) {
if (hasActiveRequest()) {
// skip empty queues if there are pending bursts to be sent
if (pendingVariables.size() > 0
|| pendingVariableBursts.size() == 0) {
ArrayList<String> burst = (ArrayList<String>) pendingVariables
.clone();
pendingVariableBursts.add(burst);
pendingVariables.clear();
}
} else {
buildAndSendVariableBurst(pendingVariables, false);
}
}
}
/**
* Build the variable burst and send it to server.
*
* When sync is forced, we also force sending of all pending variable-bursts
* at the same time. This is ok as we can assume that DOM will never be
* updated after this.
*
* @param pendingVariables
* Vector of variable changes to send
* @param forceSync
* Should we use synchronous request?
*/
private void buildAndSendVariableBurst(ArrayList<String> pendingVariables,
boolean forceSync) {
final StringBuffer req = new StringBuffer();
while (!pendingVariables.isEmpty()) {
for (int i = 0; i < pendingVariables.size(); i++) {
if (i > 0) {
if (i % 2 == 0) {
req.append(VAR_RECORD_SEPARATOR);
} else {
req.append(VAR_FIELD_SEPARATOR);
}
}
req.append(pendingVariables.get(i));
}
pendingVariables.clear();
// Append all the busts to this synchronous request
if (forceSync && !pendingVariableBursts.isEmpty()) {
pendingVariables = pendingVariableBursts.get(0);
pendingVariableBursts.remove(0);
req.append(VAR_BURST_SEPARATOR);
}
}
makeUidlRequest(req.toString(), false, forceSync, false);
}
/**
* Sends a new value for the given paintables given variable to the server.
* <p>
* The update is actually queued to be sent at a suitable time. If immediate
* is true, the update is sent as soon as possible. If immediate is false,
* the update will be sent along with the next immediate update.
* </p>
*
* @param paintableId
* the id of the paintable that owns the variable
* @param variableName
* the name of the variable
* @param newValue
* the new value to be sent
* @param immediate
* true if the update is to be sent as soon as possible
*/
public void updateVariable(String paintableId, String variableName,
Paintable newValue, boolean immediate) {
String pid = (newValue != null) ? getPid(newValue) : null;
addVariableToQueue(paintableId, variableName, pid, immediate, 'p');
}
/**
* Sends a new value for the given paintables given variable to the server.
* <p>
* The update is actually queued to be sent at a suitable time. If immediate
* is true, the update is sent as soon as possible. If immediate is false,
* the update will be sent along with the next immediate update.
* </p>
*
* @param paintableId
* the id of the paintable that owns the variable
* @param variableName
* the name of the variable
* @param newValue
* the new value to be sent
* @param immediate
* true if the update is to be sent as soon as possible
*/
public void updateVariable(String paintableId, String variableName,
String newValue, boolean immediate) {
addVariableToQueue(paintableId, variableName, newValue, immediate, 's');
}
/**
* Sends a new value for the given paintables given variable to the server.
* <p>
* The update is actually queued to be sent at a suitable time. If immediate
* is true, the update is sent as soon as possible. If immediate is false,
* the update will be sent along with the next immediate update.
* </p>
*
* @param paintableId
* the id of the paintable that owns the variable
* @param variableName
* the name of the variable
* @param newValue
* the new value to be sent
* @param immediate
* true if the update is to be sent as soon as possible
*/
public void updateVariable(String paintableId, String variableName,
int newValue, boolean immediate) {
addVariableToQueue(paintableId, variableName, "" + newValue, immediate,
'i');
}
/**
* Sends a new value for the given paintables given variable to the server.
* <p>
* The update is actually queued to be sent at a suitable time. If immediate
* is true, the update is sent as soon as possible. If immediate is false,
* the update will be sent along with the next immediate update.
* </p>
*
* @param paintableId
* the id of the paintable that owns the variable
* @param variableName
* the name of the variable
* @param newValue
* the new value to be sent
* @param immediate
* true if the update is to be sent as soon as possible
*/
public void updateVariable(String paintableId, String variableName,
long newValue, boolean immediate) {
addVariableToQueue(paintableId, variableName, "" + newValue, immediate,
'l');
}
/**
* Sends a new value for the given paintables given variable to the server.
* <p>
* The update is actually queued to be sent at a suitable time. If immediate
* is true, the update is sent as soon as possible. If immediate is false,
* the update will be sent along with the next immediate update.
* </p>
*
* @param paintableId
* the id of the paintable that owns the variable
* @param variableName
* the name of the variable
* @param newValue
* the new value to be sent
* @param immediate
* true if the update is to be sent as soon as possible
*/
public void updateVariable(String paintableId, String variableName,
float newValue, boolean immediate) {
addVariableToQueue(paintableId, variableName, "" + newValue, immediate,
'f');
}
/**
* Sends a new value for the given paintables given variable to the server.
* <p>
* The update is actually queued to be sent at a suitable time. If immediate
* is true, the update is sent as soon as possible. If immediate is false,
* the update will be sent along with the next immediate update.
* </p>
*
* @param paintableId
* the id of the paintable that owns the variable
* @param variableName
* the name of the variable
* @param newValue
* the new value to be sent
* @param immediate
* true if the update is to be sent as soon as possible
*/
public void updateVariable(String paintableId, String variableName,
double newValue, boolean immediate) {
addVariableToQueue(paintableId, variableName, "" + newValue, immediate,
'd');
}
/**
* Sends a new value for the given paintables given variable to the server.
* <p>
* The update is actually queued to be sent at a suitable time. If immediate
* is true, the update is sent as soon as possible. If immediate is false,
* the update will be sent along with the next immediate update.
* </p>
*
* @param paintableId
* the id of the paintable that owns the variable
* @param variableName
* the name of the variable
* @param newValue
* the new value to be sent
* @param immediate
* true if the update is to be sent as soon as possible
*/
public void updateVariable(String paintableId, String variableName,
boolean newValue, boolean immediate) {
addVariableToQueue(paintableId, variableName, newValue ? "true"
: "false", immediate, 'b');
}
/**
* Sends a new value for the given paintables given variable to the server.
* <p>
* The update is actually queued to be sent at a suitable time. If immediate
* is true, the update is sent as soon as possible. If immediate is false,
* the update will be sent along with the next immediate update.
* </p>
*
* @param paintableId
* the id of the paintable that owns the variable
* @param variableName
* the name of the variable
* @param newValue
* the new value to be sent
* @param immediate
* true if the update is to be sent as soon as possible
*/
public void updateVariable(String paintableId, String variableName,
Map<String, Object> map, boolean immediate) {
final StringBuffer buf = new StringBuffer();
Iterator<String> iterator = map.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
Object value = map.get(key);
char transportType = getTransportType(value);
buf.append(transportType);
buf.append(key);
buf.append(VAR_ARRAYITEM_SEPARATOR);
if (transportType == 'p') {
buf.append(getPid((Paintable) value));
} else {
buf.append(value);
}
if (iterator.hasNext()) {
buf.append(VAR_ARRAYITEM_SEPARATOR);
}
}
addVariableToQueue(paintableId, variableName, buf.toString(),
immediate, 'm');
}
private char getTransportType(Object value) {
if (value instanceof String) {
return 's';
} else if (value instanceof Paintable) {
return 'p';
} else if (value instanceof Boolean) {
return 'b';
} else if (value instanceof Integer) {
return 'i';
} else if (value instanceof Float) {
return 'f';
} else if (value instanceof Double) {
return 'd';
} else if (value instanceof Long) {
return 'l';
} else if (value instanceof Enum) {
return 's'; // transported as string representation
}
return 'u';
}
/**
* Sends a new value for the given paintables given variable to the server.
*
* The update is actually queued to be sent at a suitable time. If immediate
* is true, the update is sent as soon as possible. If immediate is false,
* the update will be sent along with the next immediate update.
*
* A null array is sent as an empty array.
*
* @param paintableId
* the id of the paintable that owns the variable
* @param variableName
* the name of the variable
* @param newValue
* the new value to be sent
* @param immediate
* true if the update is to be sent as soon as possible
*/
public void updateVariable(String paintableId, String variableName,
String[] values, boolean immediate) {
final StringBuffer buf = new StringBuffer();
if (values != null) {
for (int i = 0; i < values.length; i++) {
buf.append(values[i]);
// there will be an extra separator at the end to differentiate
// between an empty array and one containing an empty string
// only
buf.append(VAR_ARRAYITEM_SEPARATOR);
}
}
addVariableToQueue(paintableId, variableName, buf.toString(),
immediate, 'c');
}
/**
* Sends a new value for the given paintables given variable to the server.
*
* The update is actually queued to be sent at a suitable time. If immediate
* is true, the update is sent as soon as possible. If immediate is false,
* the update will be sent along with the next immediate update. </p>
*
* A null array is sent as an empty array.
*
*
* @param paintableId
* the id of the paintable that owns the variable
* @param variableName
* the name of the variable
* @param newValue
* the new value to be sent
* @param immediate
* true if the update is to be sent as soon as possible
*/
public void updateVariable(String paintableId, String variableName,
Object[] values, boolean immediate) {
final StringBuffer buf = new StringBuffer();
if (values != null) {
for (int i = 0; i < values.length; i++) {
if (i > 0) {
buf.append(VAR_ARRAYITEM_SEPARATOR);
}
Object value = values[i];
char transportType = getTransportType(value);
// first char tells the type in array
buf.append(transportType);
if (transportType == 'p') {
buf.append(getPid((Paintable) value));
} else {
buf.append(value);
}
}
}
addVariableToQueue(paintableId, variableName, buf.toString(),
immediate, 'a');
}
/**
* Update generic component features.
*
* <h2>Selecting correct implementation</h2>
*
* <p>
* The implementation of a component depends on many properties, including
* styles, component features, etc. Sometimes the user changes those
* properties after the component has been created. Calling this method in
* the beginning of your updateFromUIDL -method automatically replaces your
* component with more appropriate if the requested implementation changes.
* </p>
*
* <h2>Caption, icon, error messages and description</h2>
*
* <p>
* Component can delegate management of caption, icon, error messages and
* description to parent layout. This is optional an should be decided by
* component author
* </p>
*
* <h2>Component visibility and disabling</h2>
*
* This method will manage component visibility automatically and if
* component is an instanceof FocusWidget, also handle component disabling
* when needed.
*
* @param component
* Widget to be updated, expected to implement an instance of
* Paintable
* @param uidl
* UIDL to be painted
* @param manageCaption
* True if you want to delegate caption, icon, description and
* error message management to parent.
*
* @return Returns true iff no further painting is needed by caller
*/
public boolean updateComponent(Widget component, UIDL uidl,
boolean manageCaption) {
String pid = getPid(component.getElement());
if (pid == null) {
getConsole().error(
"Trying to update an unregistered component: "
+ Util.getSimpleName(component));
return true;
}
ComponentDetail componentDetail = idToPaintableDetail.get(pid);
if (componentDetail == null) {
getConsole().error(
"ComponentDetail not found for "
+ Util.getSimpleName(component) + " with PID "
+ pid + ". This should not happen.");
return true;
}
// If the server request that a cached instance should be used, do
// nothing
if (uidl.getBooleanAttribute("cached")) {
return true;
}
// register the listened events by the server-side to the event-handler
// of the component
componentDetail.registerEventListenersFromUIDL(uidl);
// Visibility
boolean visible = !uidl.getBooleanAttribute("invisible");
boolean wasVisible = component.isVisible();
component.setVisible(visible);
if (wasVisible != visible) {
// Changed invisibile <-> visible
if (wasVisible && manageCaption) {
// Must hide caption when component is hidden
final Container parent = Util.getLayout(component);
if (parent != null) {
parent.updateCaption((Paintable) component, uidl);
}
}
}
if (configuration.useDebugIdInDOM() && uidl.getId().startsWith("PID_S")) {
DOM.setElementProperty(component.getElement(), "id", uidl.getId()
.substring(5));
}
if (!visible) {
// component is invisible, delete old size to notify parent, if
// later make visible
componentDetail.setOffsetSize(null);
return true;
}
// Switch to correct implementation if needed
if (!widgetSet.isCorrectImplementation(component, uidl, configuration)) {
final Container parent = Util.getLayout(component);
if (parent != null) {
final Widget w = (Widget) widgetSet.createWidget(uidl,
configuration);
parent.replaceChildComponent(component, w);
unregisterPaintable((Paintable) component);
registerPaintable(uidl.getId(), (Paintable) w);
((Paintable) w).updateFromUIDL(uidl, this);
return true;
}
}
boolean enabled = !uidl.getBooleanAttribute("disabled");
if (component instanceof FocusWidget) {
FocusWidget fw = (FocusWidget) component;
if (uidl.hasAttribute("tabindex")) {
fw.setTabIndex(uidl.getIntAttribute("tabindex"));
}
// Disabled state may affect tabindex
fw.setEnabled(enabled);
}
StringBuffer styleBuf = new StringBuffer();
final String primaryName = component.getStylePrimaryName();
styleBuf.append(primaryName);
// first disabling and read-only status
if (!enabled) {
styleBuf.append(" ");
styleBuf.append("v-disabled");
}
if (uidl.getBooleanAttribute("readonly")) {
styleBuf.append(" ");
styleBuf.append("v-readonly");
}
// add additional styles as css classes, prefixed with component default
// stylename
if (uidl.hasAttribute("style")) {
final String[] styles = uidl.getStringAttribute("style").split(" ");
for (int i = 0; i < styles.length; i++) {
styleBuf.append(" ");
styleBuf.append(primaryName);
styleBuf.append("-");
styleBuf.append(styles[i]);
styleBuf.append(" ");
styleBuf.append(styles[i]);
}
}
// add modified classname to Fields
if (uidl.hasAttribute("modified") && component instanceof Field) {
styleBuf.append(" ");
styleBuf.append(MODIFIED_CLASSNAME);
}
TooltipInfo tooltipInfo = componentDetail.getTooltipInfo(null);
// Update tooltip
if (uidl.hasAttribute(ATTRIBUTE_DESCRIPTION)) {
tooltipInfo
.setTitle(uidl.getStringAttribute(ATTRIBUTE_DESCRIPTION));
} else {
tooltipInfo.setTitle(null);
}
// add error classname to components w/ error
if (uidl.hasAttribute(ATTRIBUTE_ERROR)) {
tooltipInfo.setErrorUidl(uidl.getErrors());
styleBuf.append(" ");
styleBuf.append(primaryName);
styleBuf.append(ERROR_CLASSNAME_EXT);
} else {
tooltipInfo.setErrorUidl(null);
}
// add required style to required components
if (uidl.hasAttribute("required")) {
styleBuf.append(" ");
styleBuf.append(primaryName);
styleBuf.append(REQUIRED_CLASSNAME_EXT);
}
// Styles + disabled & readonly
component.setStyleName(styleBuf.toString());
// Set captions
if (manageCaption) {
final Container parent = Util.getLayout(component);
if (parent != null) {
parent.updateCaption((Paintable) component, uidl);
}
}
/*
* updateComponentSize need to be after caption update so caption can be
* taken into account
*/
updateComponentSize(componentDetail, uidl);
return false;
}
private void updateComponentSize(ComponentDetail cd, UIDL uidl) {
String w = uidl.hasAttribute("width") ? uidl
.getStringAttribute("width") : "";
String h = uidl.hasAttribute("height") ? uidl
.getStringAttribute("height") : "";
float relativeWidth = Util.parseRelativeSize(w);
float relativeHeight = Util.parseRelativeSize(h);
// First update maps so they are correct in the setHeight/setWidth calls
if (relativeHeight >= 0.0 || relativeWidth >= 0.0) {
// One or both is relative
FloatSize relativeSize = new FloatSize(relativeWidth,
relativeHeight);
if (cd.getRelativeSize() == null && cd.getOffsetSize() != null) {
// The component has changed from absolute size to relative size
relativeSizeChanges.add(cd.getComponent());
}
cd.setRelativeSize(relativeSize);
} else if (relativeHeight < 0.0 && relativeWidth < 0.0) {
if (cd.getRelativeSize() != null) {
// The component has changed from relative size to absolute size
relativeSizeChanges.add(cd.getComponent());
}
cd.setRelativeSize(null);
}
Widget component = (Widget) cd.getComponent();
// Set absolute sizes
if (relativeHeight < 0.0) {
component.setHeight(h);
}
if (relativeWidth < 0.0) {
component.setWidth(w);
}
// Set relative sizes
if (relativeHeight >= 0.0 || relativeWidth >= 0.0) {
// One or both is relative
handleComponentRelativeSize(cd);
}
}
/**
* Traverses recursively child widgets until ContainerResizedListener child
* widget is found. They will delegate it further if needed.
*
* @param container
*/
private boolean runningLayout = false;
/**
* Causes a re-calculation/re-layout of all paintables in a container.
*
* @param container
*/
public void runDescendentsLayout(HasWidgets container) {
if (runningLayout) {
return;
}
runningLayout = true;
internalRunDescendentsLayout(container);
runningLayout = false;
}
/**
* This will cause re-layouting of all components. Mainly used for
* development. Published to JavaScript.
*/
public void forceLayout() {
Set<Paintable> set = new HashSet<Paintable>();
for (ComponentDetail cd : idToPaintableDetail.values()) {
set.add(cd.getComponent());
}
Util.componentSizeUpdated(set);
}
private void internalRunDescendentsLayout(HasWidgets container) {
// getConsole().log(
// "runDescendentsLayout(" + Util.getSimpleName(container) + ")");
final Iterator<Widget> childWidgets = container.iterator();
while (childWidgets.hasNext()) {
final Widget child = childWidgets.next();
if (child instanceof Paintable) {
if (handleComponentRelativeSize(child)) {
/*
* Only need to propagate event if "child" has a relative
* size
*/
if (child instanceof ContainerResizedListener) {
((ContainerResizedListener) child).iLayout();
}
if (child instanceof HasWidgets) {
final HasWidgets childContainer = (HasWidgets) child;
internalRunDescendentsLayout(childContainer);
}
}
} else if (child instanceof HasWidgets) {
// propagate over non Paintable HasWidgets
internalRunDescendentsLayout((HasWidgets) child);
}
}
}
/**
* Converts relative sizes into pixel sizes.
*
* @param child
* @return true if the child has a relative size
*/
private boolean handleComponentRelativeSize(ComponentDetail cd) {
if (cd == null) {
return false;
}
boolean debugSizes = false;
FloatSize relativeSize = cd.getRelativeSize();
if (relativeSize == null) {
return false;
}
Widget widget = (Widget) cd.getComponent();
boolean horizontalScrollBar = false;
boolean verticalScrollBar = false;
Container parent = Util.getLayout(widget);
RenderSpace renderSpace;
// Parent-less components (like sub-windows) are relative to browser
// window.
if (parent == null) {
renderSpace = new RenderSpace(Window.getClientWidth(), Window
.getClientHeight());
} else {
renderSpace = parent.getAllocatedSpace(widget);
}
if (relativeSize.getHeight() >= 0) {
if (renderSpace != null) {
if (renderSpace.getScrollbarSize() > 0) {
if (relativeSize.getWidth() > 100) {
horizontalScrollBar = true;
} else if (relativeSize.getWidth() < 0
&& renderSpace.getWidth() > 0) {
int offsetWidth = widget.getOffsetWidth();
int width = renderSpace.getWidth();
if (offsetWidth > width) {
horizontalScrollBar = true;
}
}
}
int height = renderSpace.getHeight();
if (horizontalScrollBar) {
height -= renderSpace.getScrollbarSize();
}
if (validatingLayouts && height <= 0) {
zeroHeightComponents.add(cd.getComponent());
}
height = (int) (height * relativeSize.getHeight() / 100.0);
if (height < 0) {
height = 0;
}
if (debugSizes) {
getConsole()
.log(
"Widget "
+ Util.getSimpleName(widget)
+ "/"
+ getPid(widget.getElement())
+ " relative height "
+ relativeSize.getHeight()
+ "% of "
+ renderSpace.getHeight()
+ "px (reported by "
+ Util.getSimpleName(parent)
+ "/"
+ (parent == null ? "?" : parent
.hashCode()) + ") : "
+ height + "px");
}
widget.setHeight(height + "px");
} else {
widget.setHeight(relativeSize.getHeight() + "%");
ApplicationConnection.getConsole().error(
Util.getLayout(widget).getClass().getName()
+ " did not produce allocatedSpace for "
+ widget.getClass().getName());
}
}
if (relativeSize.getWidth() >= 0) {
if (renderSpace != null) {
int width = renderSpace.getWidth();
if (renderSpace.getScrollbarSize() > 0) {
if (relativeSize.getHeight() > 100) {
verticalScrollBar = true;
} else if (relativeSize.getHeight() < 0
&& renderSpace.getHeight() > 0
&& widget.getOffsetHeight() > renderSpace
.getHeight()) {
verticalScrollBar = true;
}
}
if (verticalScrollBar) {
width -= renderSpace.getScrollbarSize();
}
if (validatingLayouts && width <= 0) {
zeroWidthComponents.add(cd.getComponent());
}
width = (int) (width * relativeSize.getWidth() / 100.0);
if (width < 0) {
width = 0;
}
if (debugSizes) {
getConsole().log(
"Widget " + Util.getSimpleName(widget) + "/"
+ getPid(widget.getElement())
+ " relative width "
+ relativeSize.getWidth() + "% of "
+ renderSpace.getWidth()
+ "px (reported by "
+ Util.getSimpleName(parent) + "/"
+ (parent == null ? "?" : getPid(parent))
+ ") : " + width + "px");
}
widget.setWidth(width + "px");
} else {
widget.setWidth(relativeSize.getWidth() + "%");
ApplicationConnection.getConsole().error(
Util.getLayout(widget).getClass().getName()
+ " did not produce allocatedSpace for "
+ widget.getClass().getName());
}
}
return true;
}
/**
* Converts relative sizes into pixel sizes.
*
* @param child
* @return true if the child has a relative size
*/
public boolean handleComponentRelativeSize(Widget child) {
return handleComponentRelativeSize(idToPaintableDetail.get(getPid(child
.getElement())));
}
/**
* Gets the specified Paintables relative size (percent).
*
* @param widget
* the paintable whose size is needed
* @return the the size if the paintable is relatively sized, -1 otherwise
*/
public FloatSize getRelativeSize(Widget widget) {
return idToPaintableDetail.get(getPid(widget.getElement()))
.getRelativeSize();
}
/**
* Get either existing or new Paintable for given UIDL.
*
* If corresponding Paintable has been previously painted, return it.
* Otherwise create and register a new Paintable from UIDL. Caller must
* update the returned Paintable from UIDL after it has been connected to
* parent.
*
* @param uidl
* UIDL to create Paintable from.
* @return Either existing or new Paintable corresponding to UIDL.
*/
public Paintable getPaintable(UIDL uidl) {
final String id = uidl.getId();
Paintable w = getPaintable(id);
if (w != null) {
return w;
} else {
w = widgetSet.createWidget(uidl, configuration);
registerPaintable(id, w);
return w;
}
}
/**
* Returns a Paintable element by its root element
*
* @param element
* Root element of the paintable
*/
public Paintable getPaintable(Element element) {
return getPaintable(getPid(element));
}
/**
* Gets a recource that has been pre-loaded via UIDL, such as custom
* layouts.
*
* @param name
* identifier of the resource to get
* @return the resource
*/
public String getResource(String name) {
return resourcesMap.get(name);
}
/**
* Singleton method to get instance of app's context menu.
*
* @return VContextMenu object
*/
public VContextMenu getContextMenu() {
if (contextMenu == null) {
contextMenu = new VContextMenu();
DOM.setElementProperty(contextMenu.getElement(), "id",
"PID_VAADIN_CM");
}
return contextMenu;
}
/**
* Translates custom protocols in UIDL URI's to be recognizable by browser.
* All uri's from UIDL should be routed via this method before giving them
* to browser due URI's in UIDL may contain custom protocols like theme://.
*
* @param uidlUri
* Vaadin URI from uidl
* @return translated URI ready for browser
*/
public String translateVaadinUri(String uidlUri) {
if (uidlUri == null) {
return null;
}
if (uidlUri.startsWith("theme://")) {
final String themeUri = configuration.getThemeUri();
if (themeUri == null) {
console
.error("Theme not set: ThemeResource will not be found. ("
+ uidlUri + ")");
}
uidlUri = themeUri + uidlUri.substring(7);
}
return uidlUri;
}
/**
* Gets the URI for the current theme. Can be used to reference theme
* resources.
*
* @return URI to the current theme
*/
public String getThemeUri() {
return configuration.getThemeUri();
}
/**
* Listens for Notification hide event, and redirects. Used for system
* messages, such as session expired.
*
*/
private class NotificationRedirect implements VNotification.EventListener {
String url;
NotificationRedirect(String url) {
this.url = url;
}
public void notificationHidden(HideEvent event) {
redirect(url);
}
}
/* Extended title handling */
/**
* Data showed in tooltips are stored centrilized as it may be needed in
* varios place: caption, layouts, and in owner components themselves.
*
* Updating TooltipInfo is done in updateComponent method.
*
*/
public TooltipInfo getTooltipTitleInfo(Paintable titleOwner, Object key) {
if (null == titleOwner) {
return null;
}
ComponentDetail cd = idToPaintableDetail.get(getPid(titleOwner));
if (null != cd) {
return cd.getTooltipInfo(key);
} else {
return null;
}
}
private final VTooltip tooltip = new VTooltip(this);
/**
* Component may want to delegate Tooltip handling to client. Layouts add
* Tooltip (description, errors) to caption, but some components may want
* them to appear one other elements too.
*
* Events wanted by this handler are same as in Tooltip.TOOLTIP_EVENTS
*
* @param event
* @param owner
*/
public void handleTooltipEvent(Event event, Paintable owner) {
tooltip.handleTooltipEvent(event, owner, null);
}
/**
* Component may want to delegate Tooltip handling to client. Layouts add
* Tooltip (description, errors) to caption, but some components may want
* them to appear one other elements too.
*
* Events wanted by this handler are same as in Tooltip.TOOLTIP_EVENTS
*
* @param event
* @param owner
* @param key
* the key for tooltip if this is "additional" tooltip, null for
* components "main tooltip"
*/
public void handleTooltipEvent(Event event, Paintable owner, Object key) {
tooltip.handleTooltipEvent(event, owner, key);
}
/**
* Adds PNG-fix conditionally (only for IE6) to the specified IMG -element.
*
* @param el
* the IMG element to fix
*/
public void addPngFix(Element el) {
BrowserInfo b = BrowserInfo.get();
if (b.isIE6()) {
Util.addPngFix(el, getThemeUri() + "/../runo/common/img/blank.gif");
}
}
/*
* Helper to run layout functions triggered by child components with a
* decent interval.
*/
private final Timer layoutTimer = new Timer() {
private boolean isPending = false;
@Override
public void schedule(int delayMillis) {
if (!isPending) {
super.schedule(delayMillis);
isPending = true;
}
}
@Override
public void run() {
getConsole().log(
"Running re-layout of " + view.getClass().getName());
runDescendentsLayout(view);
isPending = false;
}
};
/**
* Components can call this function to run all layout functions. This is
* usually done, when component knows that its size has changed.
*/
public void requestLayoutPhase() {
layoutTimer.schedule(500);
}
private String windowName = null;
/**
* Reset the name of the current browser-window. This should reflect the
* window-name used in the server, but might be different from the
* window-object target-name on client.
*
* @param stringAttribute
* New name for the window.
*/
public void setWindowName(String newName) {
windowName = newName;
}
/**
* Use to notify that the given component's caption has changed; layouts may
* have to be recalculated.
*
* @param component
* the Paintable whose caption has changed
*/
public void captionSizeUpdated(Paintable component) {
componentCaptionSizeChanges.add(component);
}
/**
* Requests an analyze of layouts, to find inconsistensies. Exclusively used
* for debugging during develpoment.
*/
public void analyzeLayouts() {
makeUidlRequest("", true, false, true);
}
/**
* Gets the main view, a.k.a top-level window.
*
* @return the main view
*/
public VView getView() {
return view;
}
/**
* If component has several tooltips in addition to the one provided by
* {@link com.vaadin.ui.AbstractComponent}, component can register them with
* this method.
* <p>
* Component must also pipe events to
* {@link #handleTooltipEvent(Event, Paintable, Object)} method.
* <p>
* This method can also be used to deregister tooltips by using null as
* tooltip
*
* @param paintable
* Paintable "owning" this tooltip
* @param key
* key assosiated with given tooltip. Can be any object. For
* example a related dom element. Same key must be given for
* {@link #handleTooltipEvent(Event, Paintable, Object)} method.
*
* @param tooltip
* the TooltipInfo object containing details shown in tooltip,
* null if deregistering tooltip
*/
public void registerTooltip(Paintable paintable, Object key,
TooltipInfo tooltip) {
ComponentDetail componentDetail = idToPaintableDetail
.get(getPid(paintable));
componentDetail.putAdditionalTooltip(key, tooltip);
}
/**
* Gets the {@link ApplicationConfiguration} for the current application.
*
* @see ApplicationConfiguration
* @return the configuration for this application
*/
public ApplicationConfiguration getConfiguration() {
return configuration;
}
/**
* Checks if there is a registered server side listener for the event. The
* list of events which has server side listeners is updated automatically
* before the component is updated so the value is correct if called from
* updatedFromUIDL.
*
* @param eventIdentifier
* The identifier for the event
* @return true if at least one listener has been registered on server side
* for the event identified by eventIdentifier.
*/
public boolean hasEventListeners(Paintable paintable, String eventIdentifier) {
return idToPaintableDetail.get(getPid(paintable)).hasEventListeners(
eventIdentifier);
}
}
| true | true | private void handleReceivedJSONMessage(Response response) {
final Date start = new Date();
// for(;;);[realjson]
final String jsonText = response.getText().substring(9,
response.getText().length() - 1);
final ValueMap json;
try {
json = parseJSONResponse(jsonText);
} catch (final Exception e) {
endRequest();
showCommunicationError(e.getMessage() + " - Original JSON-text:");
console.log(jsonText);
return;
}
ApplicationConnection.getConsole().log(
"JSON parsing took " + (new Date().getTime() - start.getTime())
+ "ms");
// Handle redirect
if (json.containsKey("redirect")) {
String url = json.getValueMap("redirect").getString("url");
console.log("redirecting to " + url);
redirect(url);
return;
}
// Get security key
if (json.containsKey(UIDL_SECURITY_TOKEN_ID)) {
uidl_security_key = json.getString(UIDL_SECURITY_TOKEN_ID);
}
if (json.containsKey("resources")) {
ValueMap resources = json.getValueMap("resources");
JsArrayString keyArray = resources.getKeyArray();
int l = keyArray.length();
for (int i = 0; i < l; i++) {
String key = keyArray.get(i);
resourcesMap.put(key, resources.getAsString(key));
}
}
if (json.containsKey("typeMappings")) {
configuration.addComponentMappings(
json.getValueMap("typeMappings"), widgetSet);
}
Command c = new Command() {
public void execute() {
if (json.containsKey("locales")) {
// Store locale data
JsArray<ValueMap> valueMapArray = json
.getJSValueMapArray("locales");
LocaleService.addLocales(valueMapArray);
}
ValueMap meta = null;
if (json.containsKey("meta")) {
meta = json.getValueMap("meta");
if (meta.containsKey("repaintAll")) {
view.clear();
idToPaintableDetail.clear();
if (meta.containsKey("invalidLayouts")) {
validatingLayouts = true;
zeroWidthComponents = new HashSet<Paintable>();
zeroHeightComponents = new HashSet<Paintable>();
}
}
if (meta.containsKey("timedRedirect")) {
final ValueMap timedRedirect = meta
.getValueMap("timedRedirect");
redirectTimer = new Timer() {
@Override
public void run() {
redirect(timedRedirect.getString("url"));
}
};
sessionExpirationInterval = timedRedirect
.getInt("interval");
}
}
if (redirectTimer != null) {
redirectTimer.schedule(1000 * sessionExpirationInterval);
}
// Process changes
JsArray<ValueMap> changes = json.getJSValueMapArray("changes");
ArrayList<Paintable> updatedWidgets = new ArrayList<Paintable>();
relativeSizeChanges.clear();
componentCaptionSizeChanges.clear();
int length = changes.length();
for (int i = 0; i < length; i++) {
try {
final UIDL change = changes.get(i).cast();
try {
console.dirUIDL(change);
} catch (final Exception e) {
ClientExceptionHandler.displayError(e);
// TODO: dir doesn't work in any browser although it
// should
// work (works in hosted mode)
// it partially did at some part but now broken.
}
final UIDL uidl = change.getChildUIDL(0);
// TODO optimize
final Paintable paintable = getPaintable(uidl.getId());
if (paintable != null) {
paintable.updateFromUIDL(uidl,
ApplicationConnection.this);
// paintable may have changed during render to
// another
// implementation, use the new one for updated
// widgets map
updatedWidgets.add(idToPaintableDetail.get(
uidl.getId()).getComponent());
} else {
if (!uidl.getTag().equals(
configuration.getEncodedWindowTag())) {
ClientExceptionHandler
.displayError("Received update for "
+ uidl.getTag()
+ ", but there is no such paintable ("
+ uidl.getId() + ") rendered.");
} else {
view.updateFromUIDL(uidl,
ApplicationConnection.this);
}
}
} catch (final Throwable e) {
ClientExceptionHandler.displayError(e);
}
}
if (json.containsKey("dd")) {
// response contains data for drag and drop service
VDragAndDropManager.get().handleServerResponse(
json.getValueMap("dd"));
}
// Check which widgets' size has been updated
Set<Paintable> sizeUpdatedWidgets = new HashSet<Paintable>();
updatedWidgets.addAll(relativeSizeChanges);
sizeUpdatedWidgets.addAll(componentCaptionSizeChanges);
for (Paintable paintable : updatedWidgets) {
ComponentDetail detail = idToPaintableDetail
.get(getPid(paintable));
Widget widget = (Widget) paintable;
Size oldSize = detail.getOffsetSize();
Size newSize = new Size(widget.getOffsetWidth(), widget
.getOffsetHeight());
if (oldSize == null || !oldSize.equals(newSize)) {
sizeUpdatedWidgets.add(paintable);
detail.setOffsetSize(newSize);
}
}
Util.componentSizeUpdated(sizeUpdatedWidgets);
if (meta != null) {
if (meta.containsKey("appError")) {
ValueMap error = meta.getValueMap("appError");
String html = "";
if (error.containsKey("caption")
&& error.getString("caption") != null) {
html += "<h1>" + error.getAsString("caption")
+ "</h1>";
}
if (error.containsKey("message")
&& error.getString("message") != null) {
html += "<p>" + error.getAsString("message")
+ "</p>";
}
String url = null;
if (error.containsKey("url")) {
url = error.getString("url");
}
if (html.length() != 0) {
/* 45 min */
VNotification n = new VNotification(1000 * 60 * 45);
n.addEventListener(new NotificationRedirect(url));
n.show(html, VNotification.CENTERED_TOP,
VNotification.STYLE_SYSTEM);
} else {
redirect(url);
}
applicationRunning = false;
}
if (validatingLayouts) {
getConsole().printLayoutProblems(meta,
ApplicationConnection.this,
zeroHeightComponents, zeroWidthComponents);
zeroHeightComponents = null;
zeroWidthComponents = null;
validatingLayouts = false;
}
}
// TODO build profiling for widget impl loading time
final long prosessingTime = (new Date().getTime())
- start.getTime();
console.log(" Processing time was "
+ String.valueOf(prosessingTime) + "ms for "
+ jsonText.length() + " characters of JSON");
console.log("Referenced paintables: "
+ idToPaintableDetail.size());
endRequest();
}
};
ApplicationConfiguration.runWhenWidgetsLoaded(c);
}
| private void handleReceivedJSONMessage(Response response) {
final Date start = new Date();
// for(;;);[realjson]
final String jsonText = response.getText().substring(9,
response.getText().length() - 1);
final ValueMap json;
try {
json = parseJSONResponse(jsonText);
} catch (final Exception e) {
endRequest();
showCommunicationError(e.getMessage() + " - Original JSON-text:");
console.log(jsonText);
return;
}
ApplicationConnection.getConsole().log(
"JSON parsing took " + (new Date().getTime() - start.getTime())
+ "ms");
// Handle redirect
if (json.containsKey("redirect")) {
String url = json.getValueMap("redirect").getString("url");
console.log("redirecting to " + url);
redirect(url);
return;
}
// Get security key
if (json.containsKey(UIDL_SECURITY_TOKEN_ID)) {
uidl_security_key = json.getString(UIDL_SECURITY_TOKEN_ID);
}
if (json.containsKey("resources")) {
ValueMap resources = json.getValueMap("resources");
JsArrayString keyArray = resources.getKeyArray();
int l = keyArray.length();
for (int i = 0; i < l; i++) {
String key = keyArray.get(i);
resourcesMap.put(key, resources.getAsString(key));
}
}
if (json.containsKey("typeMappings")) {
configuration.addComponentMappings(
json.getValueMap("typeMappings"), widgetSet);
}
Command c = new Command() {
public void execute() {
if (json.containsKey("locales")) {
// Store locale data
JsArray<ValueMap> valueMapArray = json
.getJSValueMapArray("locales");
LocaleService.addLocales(valueMapArray);
}
ValueMap meta = null;
if (json.containsKey("meta")) {
meta = json.getValueMap("meta");
if (meta.containsKey("repaintAll")) {
view.clear();
idToPaintableDetail.clear();
if (meta.containsKey("invalidLayouts")) {
validatingLayouts = true;
zeroWidthComponents = new HashSet<Paintable>();
zeroHeightComponents = new HashSet<Paintable>();
}
}
if (meta.containsKey("timedRedirect")) {
final ValueMap timedRedirect = meta
.getValueMap("timedRedirect");
redirectTimer = new Timer() {
@Override
public void run() {
redirect(timedRedirect.getString("url"));
}
};
sessionExpirationInterval = timedRedirect
.getInt("interval");
}
}
if (redirectTimer != null) {
redirectTimer.schedule(1000 * sessionExpirationInterval);
}
// Process changes
JsArray<ValueMap> changes = json.getJSValueMapArray("changes");
ArrayList<Paintable> updatedWidgets = new ArrayList<Paintable>();
relativeSizeChanges.clear();
componentCaptionSizeChanges.clear();
int length = changes.length();
for (int i = 0; i < length; i++) {
try {
final UIDL change = changes.get(i).cast();
try {
console.dirUIDL(change);
} catch (final Exception e) {
ClientExceptionHandler.displayError(e);
// TODO: dir doesn't work in any browser although it
// should
// work (works in hosted mode)
// it partially did at some part but now broken.
}
final UIDL uidl = change.getChildUIDL(0);
// TODO optimize
final Paintable paintable = getPaintable(uidl.getId());
if (paintable != null) {
paintable.updateFromUIDL(uidl,
ApplicationConnection.this);
// paintable may have changed during render to
// another
// implementation, use the new one for updated
// widgets map
updatedWidgets.add(idToPaintableDetail.get(
uidl.getId()).getComponent());
} else {
if (!uidl.getTag().equals(
configuration.getEncodedWindowTag())) {
ClientExceptionHandler
.displayError("Received update for "
+ uidl.getTag()
+ ", but there is no such paintable ("
+ uidl.getId() + ") rendered.");
} else {
if (!idToPaintableDetail.containsKey(uidl
.getId())) {
registerPaintable(uidl.getId(), view);
}
view.updateFromUIDL(uidl,
ApplicationConnection.this);
}
}
} catch (final Throwable e) {
ClientExceptionHandler.displayError(e);
}
}
if (json.containsKey("dd")) {
// response contains data for drag and drop service
VDragAndDropManager.get().handleServerResponse(
json.getValueMap("dd"));
}
// Check which widgets' size has been updated
Set<Paintable> sizeUpdatedWidgets = new HashSet<Paintable>();
updatedWidgets.addAll(relativeSizeChanges);
sizeUpdatedWidgets.addAll(componentCaptionSizeChanges);
for (Paintable paintable : updatedWidgets) {
ComponentDetail detail = idToPaintableDetail
.get(getPid(paintable));
Widget widget = (Widget) paintable;
Size oldSize = detail.getOffsetSize();
Size newSize = new Size(widget.getOffsetWidth(), widget
.getOffsetHeight());
if (oldSize == null || !oldSize.equals(newSize)) {
sizeUpdatedWidgets.add(paintable);
detail.setOffsetSize(newSize);
}
}
Util.componentSizeUpdated(sizeUpdatedWidgets);
if (meta != null) {
if (meta.containsKey("appError")) {
ValueMap error = meta.getValueMap("appError");
String html = "";
if (error.containsKey("caption")
&& error.getString("caption") != null) {
html += "<h1>" + error.getAsString("caption")
+ "</h1>";
}
if (error.containsKey("message")
&& error.getString("message") != null) {
html += "<p>" + error.getAsString("message")
+ "</p>";
}
String url = null;
if (error.containsKey("url")) {
url = error.getString("url");
}
if (html.length() != 0) {
/* 45 min */
VNotification n = new VNotification(1000 * 60 * 45);
n.addEventListener(new NotificationRedirect(url));
n.show(html, VNotification.CENTERED_TOP,
VNotification.STYLE_SYSTEM);
} else {
redirect(url);
}
applicationRunning = false;
}
if (validatingLayouts) {
getConsole().printLayoutProblems(meta,
ApplicationConnection.this,
zeroHeightComponents, zeroWidthComponents);
zeroHeightComponents = null;
zeroWidthComponents = null;
validatingLayouts = false;
}
}
// TODO build profiling for widget impl loading time
final long prosessingTime = (new Date().getTime())
- start.getTime();
console.log(" Processing time was "
+ String.valueOf(prosessingTime) + "ms for "
+ jsonText.length() + " characters of JSON");
console.log("Referenced paintables: "
+ idToPaintableDetail.size());
endRequest();
}
};
ApplicationConfiguration.runWhenWidgetsLoaded(c);
}
|
diff --git a/src/main/java/com/griefcraft/modules/doors/DoorsModule.java b/src/main/java/com/griefcraft/modules/doors/DoorsModule.java
index 49bb2a30..bb524662 100644
--- a/src/main/java/com/griefcraft/modules/doors/DoorsModule.java
+++ b/src/main/java/com/griefcraft/modules/doors/DoorsModule.java
@@ -1,295 +1,295 @@
/*
* Copyright 2011 Tyler Blair. 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.
*
* 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 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.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and contributors and should not be interpreted as representing official policies,
* either expressed or implied, of anybody else.
*/
package com.griefcraft.modules.doors;
import com.griefcraft.lwc.LWC;
import com.griefcraft.model.Flag;
import com.griefcraft.model.Protection;
import com.griefcraft.scripting.JavaModule;
import com.griefcraft.scripting.event.LWCProtectionInteractEvent;
import com.griefcraft.util.config.Configuration;
import org.bukkit.Effect;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Player;
public class DoorsModule extends JavaModule {
/**
* The amount of server ticks there usually are per second
*/
private final static int TICKS_PER_SECOND = 20;
/**
* The course of action for opening doors
*/
private enum Action {
/**
* The door should automatically open and then close
*/
OPEN_AND_CLOSE,
/**
* The doors should just be opened, not closed after a set amount of time
*/
TOGGLE;
/**
* Resolve an Action using its case insensitive name
*
* @param name
* @return
*/
public static Action resolve(String name) {
for (Action action : values()) {
if (action.toString().equalsIgnoreCase(name)) {
return action;
}
}
return null;
}
}
/**
* The configuration file
*/
private final Configuration configuration = Configuration.load("doors.yml");
/**
* The LWC object, set by load ()
*/
private LWC lwc;
/**
* The current action to use, default to toggling the door open and closed
*/
private Action action = Action.TOGGLE;
@Override
public void load(LWC lwc) {
this.lwc = lwc;
loadAction();
}
@Override
public void onProtectionInteract(LWCProtectionInteractEvent event) {
if (event.getResult() == Result.CANCEL || !isEnabled()) {
return;
}
// The more important check
if (!event.canAccess()) {
return;
}
Protection protection = event.getProtection();
Block block = event.getEvent().getClickedBlock(); // The block they actually clicked :)
Player player = event.getPlayer();
// Check if the block is even something that should be opened
if (!isValid(block.getType())) {
return;
}
// Are we looking at the top half?
// If we are, we need to get the bottom half instead
- if ((block.getData() & 0x8) == 0x8) {
+ if (block.getType() != Material.TRAP_DOOR && (block.getData() & 0x8) == 0x8) {
// Inspect the bottom half instead, fool!
block = block.getRelative(BlockFace.DOWN);
}
// Should we look for double doors?
boolean doubleDoors = usingDoubleDoors();
// The BOTTOM half of the other side of the double door
Block doubleDoorBlock = null;
// Only waste CPU if we need the double door block
if (doubleDoors) {
doubleDoorBlock = getDoubleDoor(block);
if (doubleDoorBlock != null) {
Protection other = lwc.findProtection(doubleDoorBlock.getLocation());
if (!lwc.canAccessProtection(player, other)) {
doubleDoorBlock = null; // don't open the other door :-)
}
}
}
// Either way we are going to be toggling the door open
// So toggle both doors to be open. We can safely pass null values to changeDoorStates
changeDoorStates(true, ((block.getType() == Material.WOODEN_DOOR || block.getType() == Material.FENCE_GATE || block.getType() == Material.TRAP_DOOR) ? null : block) /* They clicked it so it auto opens already */,
doubleDoorBlock);
if (action == Action.OPEN_AND_CLOSE || protection.hasFlag(Flag.Type.AUTOCLOSE)) {
// Abuse the fact that we still use final variables inside the task
// The double door block object is initially only assigned if we need
// it, so we just create a second variable ^^
final Block finalBlock = block;
final Block finalDoubleDoorBlock = doubleDoorBlock;
// Calculate the wait time
// This is basically Interval * TICKS_PER_SECOND
int wait = getAutoCloseInterval() * TICKS_PER_SECOND;
// Create the task
// If we are set to close the door after a set period, let's create a sync task for it
lwc.getPlugin().getServer().getScheduler().scheduleSyncDelayedTask(lwc.getPlugin(), new Runnable() {
public void run() {
// Essentially all we need to do is reset the door states
// But DO NOT open the door if it's closed !
changeDoorStates(false, finalBlock, finalDoubleDoorBlock);
}
}, wait);
}
}
/**
* Change all of the given door states to be inverse; that is, if a door is open, it will be closed afterwards.
* If the door is closed, it will become open.
* <p/>
* Note that the blocks given must be the bottom block of the door.
*
* @param allowDoorToOpen If FALSE, and the door is currently CLOSED, it will NOT be opened!
* @param doors Blocks given must be the bottom block of the door
*/
private void changeDoorStates(boolean allowDoorToOpen, Block... doors) {
for (Block door : doors) {
if (door == null) {
continue;
}
// If we aren't allowing the door to open, check if it's already closed
if (!allowDoorToOpen && (door.getData() & 0x4) == 0) {
// The door is already closed and we don't want to open it
// the bit 0x4 is set when the door is open
continue;
}
// Get the top half of the door
Block topHalf = door.getRelative(BlockFace.UP);
// Now xor both data values with 0x4, the flag that states if the door is open
door.setData((byte) (door.getData() ^ 0x4));
// Play the door open/close sound
door.getWorld().playEffect(door.getLocation(), Effect.DOOR_TOGGLE, 0);
// Only change the block above it if it is something we can open or close
if (isValid(topHalf.getType())) {
topHalf.setData((byte) (topHalf.getData() ^ 0x4));
}
}
}
/**
* Get the double door for the given block
*
* @param block
* @return
*/
private Block getDoubleDoor(Block block) {
if (!isValid(block.getType())) {
return null;
}
Block found;
// Try a wooden door
if ((found = lwc.findAdjacentBlock(block, Material.WOODEN_DOOR)) != null) {
return found;
}
// Now an iron door
if ((found = lwc.findAdjacentBlock(block, Material.IRON_DOOR_BLOCK)) != null) {
return found;
}
// Nothing at all :-(
return null;
}
/**
* Check if automatic door opening is enabled
*
* @return
*/
public boolean isEnabled() {
return configuration.getBoolean("doors.enabled", true);
}
/**
* Check if the material is auto openable/closable
*
* @param material
* @return
*/
private boolean isValid(Material material) {
return material == Material.IRON_DOOR_BLOCK || material == Material.WOODEN_DOOR || material == Material.FENCE_GATE || material == Material.TRAP_DOOR;
}
/**
* Get the amount of seconds after opening a door it should be closed
*
* @return
*/
private int getAutoCloseInterval() {
return configuration.getInt("doors.interval", 3);
}
/**
* Get if we are allowing double doors to be used
*
* @return
*/
private boolean usingDoubleDoors() {
return configuration.getBoolean("doors.doubleDoors", true);
}
/**
* Load the action from the configuration
*/
private void loadAction() {
String strAction = configuration.getString("doors.action");
if (strAction.equalsIgnoreCase("openAndClose")) {
this.action = Action.OPEN_AND_CLOSE;
} else {
this.action = Action.TOGGLE;
}
}
}
| true | true | public void onProtectionInteract(LWCProtectionInteractEvent event) {
if (event.getResult() == Result.CANCEL || !isEnabled()) {
return;
}
// The more important check
if (!event.canAccess()) {
return;
}
Protection protection = event.getProtection();
Block block = event.getEvent().getClickedBlock(); // The block they actually clicked :)
Player player = event.getPlayer();
// Check if the block is even something that should be opened
if (!isValid(block.getType())) {
return;
}
// Are we looking at the top half?
// If we are, we need to get the bottom half instead
if ((block.getData() & 0x8) == 0x8) {
// Inspect the bottom half instead, fool!
block = block.getRelative(BlockFace.DOWN);
}
// Should we look for double doors?
boolean doubleDoors = usingDoubleDoors();
// The BOTTOM half of the other side of the double door
Block doubleDoorBlock = null;
// Only waste CPU if we need the double door block
if (doubleDoors) {
doubleDoorBlock = getDoubleDoor(block);
if (doubleDoorBlock != null) {
Protection other = lwc.findProtection(doubleDoorBlock.getLocation());
if (!lwc.canAccessProtection(player, other)) {
doubleDoorBlock = null; // don't open the other door :-)
}
}
}
// Either way we are going to be toggling the door open
// So toggle both doors to be open. We can safely pass null values to changeDoorStates
changeDoorStates(true, ((block.getType() == Material.WOODEN_DOOR || block.getType() == Material.FENCE_GATE || block.getType() == Material.TRAP_DOOR) ? null : block) /* They clicked it so it auto opens already */,
doubleDoorBlock);
if (action == Action.OPEN_AND_CLOSE || protection.hasFlag(Flag.Type.AUTOCLOSE)) {
// Abuse the fact that we still use final variables inside the task
// The double door block object is initially only assigned if we need
// it, so we just create a second variable ^^
final Block finalBlock = block;
final Block finalDoubleDoorBlock = doubleDoorBlock;
// Calculate the wait time
// This is basically Interval * TICKS_PER_SECOND
int wait = getAutoCloseInterval() * TICKS_PER_SECOND;
// Create the task
// If we are set to close the door after a set period, let's create a sync task for it
lwc.getPlugin().getServer().getScheduler().scheduleSyncDelayedTask(lwc.getPlugin(), new Runnable() {
public void run() {
// Essentially all we need to do is reset the door states
// But DO NOT open the door if it's closed !
changeDoorStates(false, finalBlock, finalDoubleDoorBlock);
}
}, wait);
}
}
| public void onProtectionInteract(LWCProtectionInteractEvent event) {
if (event.getResult() == Result.CANCEL || !isEnabled()) {
return;
}
// The more important check
if (!event.canAccess()) {
return;
}
Protection protection = event.getProtection();
Block block = event.getEvent().getClickedBlock(); // The block they actually clicked :)
Player player = event.getPlayer();
// Check if the block is even something that should be opened
if (!isValid(block.getType())) {
return;
}
// Are we looking at the top half?
// If we are, we need to get the bottom half instead
if (block.getType() != Material.TRAP_DOOR && (block.getData() & 0x8) == 0x8) {
// Inspect the bottom half instead, fool!
block = block.getRelative(BlockFace.DOWN);
}
// Should we look for double doors?
boolean doubleDoors = usingDoubleDoors();
// The BOTTOM half of the other side of the double door
Block doubleDoorBlock = null;
// Only waste CPU if we need the double door block
if (doubleDoors) {
doubleDoorBlock = getDoubleDoor(block);
if (doubleDoorBlock != null) {
Protection other = lwc.findProtection(doubleDoorBlock.getLocation());
if (!lwc.canAccessProtection(player, other)) {
doubleDoorBlock = null; // don't open the other door :-)
}
}
}
// Either way we are going to be toggling the door open
// So toggle both doors to be open. We can safely pass null values to changeDoorStates
changeDoorStates(true, ((block.getType() == Material.WOODEN_DOOR || block.getType() == Material.FENCE_GATE || block.getType() == Material.TRAP_DOOR) ? null : block) /* They clicked it so it auto opens already */,
doubleDoorBlock);
if (action == Action.OPEN_AND_CLOSE || protection.hasFlag(Flag.Type.AUTOCLOSE)) {
// Abuse the fact that we still use final variables inside the task
// The double door block object is initially only assigned if we need
// it, so we just create a second variable ^^
final Block finalBlock = block;
final Block finalDoubleDoorBlock = doubleDoorBlock;
// Calculate the wait time
// This is basically Interval * TICKS_PER_SECOND
int wait = getAutoCloseInterval() * TICKS_PER_SECOND;
// Create the task
// If we are set to close the door after a set period, let's create a sync task for it
lwc.getPlugin().getServer().getScheduler().scheduleSyncDelayedTask(lwc.getPlugin(), new Runnable() {
public void run() {
// Essentially all we need to do is reset the door states
// But DO NOT open the door if it's closed !
changeDoorStates(false, finalBlock, finalDoubleDoorBlock);
}
}, wait);
}
}
|
diff --git a/src/com/sleazyweasel/pandora/JsonPandoraRadio.java b/src/com/sleazyweasel/pandora/JsonPandoraRadio.java
index b68f057..98da09e 100644
--- a/src/com/sleazyweasel/pandora/JsonPandoraRadio.java
+++ b/src/com/sleazyweasel/pandora/JsonPandoraRadio.java
@@ -1,303 +1,301 @@
package com.sleazyweasel.pandora;
import com.google.gson.*;
import com.sleazyweasel.applescriptifier.BadPandoraPasswordException;
import de.felixbruns.jotify.util.Hex;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class JsonPandoraRadio implements PandoraRadio {
private static final String BLOWFISH_ECB_PKCS5_PADDING = "Blowfish/ECB/PKCS5Padding";
private Long syncTime;
private Long clientStartTime;
private Integer partnerId;
private String partnerAuthToken;
private String userAuthToken;
private Long userId;
private String user;
private String password;
private PandoraAuthConfiguration authConfiguration = PandoraAuthConfiguration.PANDORAONE_CONFIG;
private List<Station> stations;
@Override
public void connect(String user, String password) throws BadPandoraPasswordException {
clientStartTime = System.currentTimeMillis() / 1000L;
partnerLogin();
userLogin(user, password);
this.user = user;
this.password = password;
}
private void userLogin(String user, String password) {
Map<String, Object> userLoginInputs = new HashMap<String, Object>();
userLoginInputs.put("loginType", "user");
userLoginInputs.put("username", user);
userLoginInputs.put("password", password);
userLoginInputs.put("partnerAuthToken", partnerAuthToken);
userLoginInputs.put("syncTime", getPandoraTime());
String userLoginData = new Gson().toJson(userLoginInputs);
String encryptedUserLoginData = encrypt(userLoginData);
String urlEncodedPartnerAuthToken = urlEncode(partnerAuthToken);
String userLoginUrl = String.format(authConfiguration.getBaseUrl() + "method=auth.userLogin&auth_token=%s&partner_id=%d", urlEncodedPartnerAuthToken, partnerId);
JsonObject jsonElement = doPost(userLoginUrl, encryptedUserLoginData).getAsJsonObject();
String loginStatus = jsonElement.get("stat").getAsString();
if ("ok".equals(loginStatus)) {
JsonObject userLoginResult = jsonElement.get("result").getAsJsonObject();
userAuthToken = userLoginResult.get("userAuthToken").getAsString();
userId = userLoginResult.get("userId").getAsLong();
} else {
throw new BadPandoraPasswordException();
}
}
private String urlEncode(String f) {
try {
return URLEncoder.encode(f, "ISO-8859-1");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("This better not happen, because ISO-8859-1 is a valid encoding", e);
}
}
private long getPandoraTime() {
return syncTime + ((System.currentTimeMillis() / 1000) - clientStartTime);
}
private void partnerLogin() {
JsonElement partnerLoginData = doPartnerLogin();
JsonObject asJsonObject = partnerLoginData.getAsJsonObject();
checkForError(asJsonObject, "Failed at Partner Login");
JsonObject result = asJsonObject.getAsJsonObject("result");
String encryptedSyncTime = result.get("syncTime").getAsString();
partnerAuthToken = result.get("partnerAuthToken").getAsString();
syncTime = Long.valueOf(decrypt(encryptedSyncTime));
partnerId = result.get("partnerId").getAsInt();
}
@Override
public void sync() {
//don't think we need to do this, since it's a part of the core json APIs.
}
@Override
public void disconnect() {
syncTime = null;
clientStartTime = null;
partnerId = null;
partnerAuthToken = null;
userAuthToken = null;
stations = null;
}
@Override
public List<Station> getStations() {
JsonObject result = doStandardCall("user.getStationList", new HashMap<String, Object>(), false);
checkForError(result, "Failed to get Stations");
JsonArray stationArray = result.get("result").getAsJsonObject().getAsJsonArray("stations");
stations = new ArrayList<Station>();
for (JsonElement jsonStationElement : stationArray) {
JsonObject jsonStation = jsonStationElement.getAsJsonObject();
String stationId = jsonStation.get("stationId").getAsString();
String stationIdToken = jsonStation.get("stationToken").getAsString();
boolean isQuickMix = jsonStation.getAsJsonPrimitive("isQuickMix").getAsBoolean();
String stationName = jsonStation.get("stationName").getAsString();
stations.add(new Station(stationId, stationIdToken, false, isQuickMix, stationName));
}
return stations;
}
private JsonObject doStandardCall(String method, Map<String, Object> postData, boolean useSsl) {
String url = String.format((useSsl ? authConfiguration.getBaseUrl() : authConfiguration.getNonTlsBaseUrl()) + "method=%s&auth_token=%s&partner_id=%d&user_id=%s", method, urlEncode(userAuthToken), partnerId, userId);
System.out.println("url = " + url);
postData.put("userAuthToken", userAuthToken);
postData.put("syncTime", getPandoraTime());
String jsonData = new Gson().toJson(postData);
System.out.println("jsonData = " + jsonData);
return doPost(url, encrypt(jsonData)).getAsJsonObject();
}
@Override
public Station getStationById(long sid) {
if (stations == null) {
getStations();
}
for (Station station : stations) {
if (sid == station.getId()) {
return station;
}
}
return null;
}
@Override
public void rate(Song song, boolean rating) {
String method = "station.addFeedback";
Map<String, Object> data = new HashMap<String, Object>();
data.put("trackToken", song.getTrackToken());
data.put("isPositive", rating);
JsonObject ratingResult = doStandardCall(method, data, false);
checkForError(ratingResult, "failed to rate song");
}
@Override
public boolean isAlive() {
return userAuthToken != null;
}
@Override
public Song[] getPlaylist(Station station, String format) {
Map<String, Object> data = new HashMap<String, Object>();
data.put("stationToken", station.getStationIdToken());
data.put("additionalAudioUrl", "HTTP_192_MP3,HTTP_128_MP3");
JsonObject songResult = doStandardCall("station.getPlaylist", data, true);
try {
checkForError(songResult, "Failed to get playlist from station");
} catch (RuntimeException e) {
String errorCode = songResult.get("code").getAsString();
if ("1003".equals(errorCode) && authConfiguration == PandoraAuthConfiguration.PANDORAONE_CONFIG) {
authConfiguration = PandoraAuthConfiguration.ANDROID_CONFIG;
reLogin();
return getPlaylist(station, format);
- }
- else {
+ } else {
throw e;
}
}
JsonArray songsArray = songResult.get("result").getAsJsonObject().get("items").getAsJsonArray();
List<Song> results = new ArrayList<Song>();
for (JsonElement songElement : songsArray) {
JsonObject songData = songElement.getAsJsonObject();
//it is completely retarded that pandora leaves this up to the client. Come on, Pandora! Use your brains!
if (songData.get("adToken") != null) {
continue;
}
String album = songData.get("albumName").getAsString();
String artist = songData.get("artistName").getAsString();
JsonElement additionalAudioUrlElement = songData.get("additionalAudioUrl");
String additionalAudioUrl = additionalAudioUrlElement != null ? additionalAudioUrlElement.getAsString() : null;
JsonObject audioUrlMap = songData.get("audioUrlMap").getAsJsonObject();
JsonObject highQuality = audioUrlMap.get("highQuality").getAsJsonObject();
String audioUrl = highQuality.get("audioUrl").getAsString();
System.out.println("audioUrl = " + audioUrl);
System.out.println("additionalAudioUrl = " + additionalAudioUrl);
String title = songData.get("songName").getAsString();
String albumDetailUrl = songData.get("albumDetailUrl").getAsString();
String artRadio = songData.get("albumArtUrl").getAsString();
String trackToken = songData.get("trackToken").getAsString();
Integer rating = songData.get("songRating").getAsInt();
- if (audioUrl != null) {
+ if (audioUrl != null && authConfiguration == PandoraAuthConfiguration.PANDORAONE_CONFIG) {
results.add(new Song(album, artist, audioUrl, station.getStationId(), title, albumDetailUrl, artRadio, trackToken, rating));
- }
- else if (additionalAudioUrl != null) {
+ } else if (additionalAudioUrl != null) {
results.add(new Song(album, artist, additionalAudioUrl, station.getStationId(), title, albumDetailUrl, artRadio, trackToken, rating));
}
}
return results.toArray(new Song[results.size()]);
}
private void reLogin() {
partnerLogin();
userLogin(user, password);
}
private void checkForError(JsonObject songResult, String errorMessage) {
String stat = songResult.get("stat").getAsString();
if (!"ok".equals(stat)) {
throw new RuntimeException(errorMessage);
}
}
private JsonElement doPartnerLogin() {
String partnerLoginUrl = authConfiguration.getBaseUrl() + "method=auth.partnerLogin";
Map<String, Object> data = new HashMap<String, Object>();
data.put("username", authConfiguration.getUserName());
data.put("password", authConfiguration.getPassword());
data.put("deviceModel", authConfiguration.getDeviceModel());
data.put("version", "5");
data.put("includeUrls", true);
String stringData = new Gson().toJson(data);
return doPost(partnerLoginUrl, stringData);
}
private static JsonElement doPost(String urlInput, String stringData) {
try {
URL url = new URL(urlInput);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
setRequestHeaders(urlConnection);
urlConnection.setRequestProperty("Content-length", String.valueOf(stringData.length()));
urlConnection.connect();
DataOutputStream out = new DataOutputStream(urlConnection.getOutputStream());
out.writeBytes(stringData);
out.flush();
out.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println("response = " + line);
JsonParser parser = new JsonParser();
return parser.parse(line);
}
} catch (IOException e) {
throw new RuntimeException("Failed to connect to Pandora", e);
}
throw new RuntimeException("Failed to get a response from Pandora");
}
private static void setRequestHeaders(HttpURLConnection conn) {
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");
conn.setRequestProperty("Content-Type", "text/plain");
conn.setRequestProperty("Accept", "*/*");
}
private String encrypt(String input) {
try {
Cipher encryptionCipher = Cipher.getInstance(BLOWFISH_ECB_PKCS5_PADDING);
encryptionCipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(authConfiguration.getEncryptionKey().getBytes(), "Blowfish"));
byte[] bytes = encryptionCipher.doFinal(input.getBytes());
return Hex.toHex(bytes);
} catch (Exception e) {
throw new RuntimeException("Failed to properly encrypt data", e);
}
}
private String decrypt(String input) {
byte[] result;
try {
Cipher decryptionCipher = Cipher.getInstance(BLOWFISH_ECB_PKCS5_PADDING);
decryptionCipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(authConfiguration.getDecriptionKey().getBytes(), "Blowfish"));
result = decryptionCipher.doFinal(Hex.toBytes(input));
} catch (Exception e) {
throw new RuntimeException("Failed to properly decrypt data", e);
}
byte[] chopped = new byte[result.length - 4];
System.arraycopy(result, 4, chopped, 0, chopped.length);
return new String(chopped);
}
}
| false | true | public Song[] getPlaylist(Station station, String format) {
Map<String, Object> data = new HashMap<String, Object>();
data.put("stationToken", station.getStationIdToken());
data.put("additionalAudioUrl", "HTTP_192_MP3,HTTP_128_MP3");
JsonObject songResult = doStandardCall("station.getPlaylist", data, true);
try {
checkForError(songResult, "Failed to get playlist from station");
} catch (RuntimeException e) {
String errorCode = songResult.get("code").getAsString();
if ("1003".equals(errorCode) && authConfiguration == PandoraAuthConfiguration.PANDORAONE_CONFIG) {
authConfiguration = PandoraAuthConfiguration.ANDROID_CONFIG;
reLogin();
return getPlaylist(station, format);
}
else {
throw e;
}
}
JsonArray songsArray = songResult.get("result").getAsJsonObject().get("items").getAsJsonArray();
List<Song> results = new ArrayList<Song>();
for (JsonElement songElement : songsArray) {
JsonObject songData = songElement.getAsJsonObject();
//it is completely retarded that pandora leaves this up to the client. Come on, Pandora! Use your brains!
if (songData.get("adToken") != null) {
continue;
}
String album = songData.get("albumName").getAsString();
String artist = songData.get("artistName").getAsString();
JsonElement additionalAudioUrlElement = songData.get("additionalAudioUrl");
String additionalAudioUrl = additionalAudioUrlElement != null ? additionalAudioUrlElement.getAsString() : null;
JsonObject audioUrlMap = songData.get("audioUrlMap").getAsJsonObject();
JsonObject highQuality = audioUrlMap.get("highQuality").getAsJsonObject();
String audioUrl = highQuality.get("audioUrl").getAsString();
System.out.println("audioUrl = " + audioUrl);
System.out.println("additionalAudioUrl = " + additionalAudioUrl);
String title = songData.get("songName").getAsString();
String albumDetailUrl = songData.get("albumDetailUrl").getAsString();
String artRadio = songData.get("albumArtUrl").getAsString();
String trackToken = songData.get("trackToken").getAsString();
Integer rating = songData.get("songRating").getAsInt();
if (audioUrl != null) {
results.add(new Song(album, artist, audioUrl, station.getStationId(), title, albumDetailUrl, artRadio, trackToken, rating));
}
else if (additionalAudioUrl != null) {
results.add(new Song(album, artist, additionalAudioUrl, station.getStationId(), title, albumDetailUrl, artRadio, trackToken, rating));
}
}
return results.toArray(new Song[results.size()]);
}
| public Song[] getPlaylist(Station station, String format) {
Map<String, Object> data = new HashMap<String, Object>();
data.put("stationToken", station.getStationIdToken());
data.put("additionalAudioUrl", "HTTP_192_MP3,HTTP_128_MP3");
JsonObject songResult = doStandardCall("station.getPlaylist", data, true);
try {
checkForError(songResult, "Failed to get playlist from station");
} catch (RuntimeException e) {
String errorCode = songResult.get("code").getAsString();
if ("1003".equals(errorCode) && authConfiguration == PandoraAuthConfiguration.PANDORAONE_CONFIG) {
authConfiguration = PandoraAuthConfiguration.ANDROID_CONFIG;
reLogin();
return getPlaylist(station, format);
} else {
throw e;
}
}
JsonArray songsArray = songResult.get("result").getAsJsonObject().get("items").getAsJsonArray();
List<Song> results = new ArrayList<Song>();
for (JsonElement songElement : songsArray) {
JsonObject songData = songElement.getAsJsonObject();
//it is completely retarded that pandora leaves this up to the client. Come on, Pandora! Use your brains!
if (songData.get("adToken") != null) {
continue;
}
String album = songData.get("albumName").getAsString();
String artist = songData.get("artistName").getAsString();
JsonElement additionalAudioUrlElement = songData.get("additionalAudioUrl");
String additionalAudioUrl = additionalAudioUrlElement != null ? additionalAudioUrlElement.getAsString() : null;
JsonObject audioUrlMap = songData.get("audioUrlMap").getAsJsonObject();
JsonObject highQuality = audioUrlMap.get("highQuality").getAsJsonObject();
String audioUrl = highQuality.get("audioUrl").getAsString();
System.out.println("audioUrl = " + audioUrl);
System.out.println("additionalAudioUrl = " + additionalAudioUrl);
String title = songData.get("songName").getAsString();
String albumDetailUrl = songData.get("albumDetailUrl").getAsString();
String artRadio = songData.get("albumArtUrl").getAsString();
String trackToken = songData.get("trackToken").getAsString();
Integer rating = songData.get("songRating").getAsInt();
if (audioUrl != null && authConfiguration == PandoraAuthConfiguration.PANDORAONE_CONFIG) {
results.add(new Song(album, artist, audioUrl, station.getStationId(), title, albumDetailUrl, artRadio, trackToken, rating));
} else if (additionalAudioUrl != null) {
results.add(new Song(album, artist, additionalAudioUrl, station.getStationId(), title, albumDetailUrl, artRadio, trackToken, rating));
}
}
return results.toArray(new Song[results.size()]);
}
|
diff --git a/src/main/java/hudson/plugins/jacoco/model/CoverageObject.java b/src/main/java/hudson/plugins/jacoco/model/CoverageObject.java
index 4bcac00..6321269 100644
--- a/src/main/java/hudson/plugins/jacoco/model/CoverageObject.java
+++ b/src/main/java/hudson/plugins/jacoco/model/CoverageObject.java
@@ -1,492 +1,489 @@
package hudson.plugins.jacoco.model;
import hudson.Util;
import hudson.model.AbstractBuild;
import hudson.model.Api;
import hudson.plugins.jacoco.Messages;
import hudson.plugins.jacoco.Rule;
import hudson.plugins.jacoco.report.AggregatedReport;
import hudson.util.ChartUtil;
import hudson.util.ChartUtil.NumberOnlyBuildLabel;
import hudson.util.DataSetBuilder;
import hudson.util.Graph;
import hudson.util.ShiftedCategoryAxis;
import java.awt.BasicStroke;
import java.awt.Color;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.Calendar;
import java.util.Locale;
import java.util.logging.Logger;
import org.jacoco.core.analysis.ICoverageNode;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.chart.title.LegendTitle;
import org.jfree.data.category.CategoryDataset;
import org.jfree.ui.RectangleEdge;
import org.jfree.ui.RectangleInsets;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
/**
* Base class of all coverage objects.
*
* @author Kohsuke Kawaguchi
*/
@ExportedBean
public abstract class CoverageObject<SELF extends CoverageObject<SELF>> {
public Coverage clazz = new Coverage();
public Coverage method = new Coverage();
public Coverage line = new Coverage();
public Coverage complexity = new Coverage();
public Coverage instruction = new Coverage();
public Coverage branch = new Coverage();
/**
* Variables used to store which child has to highest coverage for each coverage type.
*/
public int maxClazz=1;
public int maxMethod=1;
public int maxLine=1;
public int maxComplexity=1;
public int maxInstruction=1;
public int maxBranch=1;
private volatile boolean failed = false;
/**
* @return the maxClazz
*/
public int getMaxClazz() {
return maxClazz;
}
/**
* @param maxClazz the maxClazz to set
*/
public void setMaxClazz(int maxClazz) {
this.maxClazz = maxClazz;
}
/**
* @return the maxMethod
*/
public int getMaxMethod() {
return maxMethod;
}
/**
* @param maxMethod the maxMethod to set
*/
public void setMaxMethod(int maxMethod) {
this.maxMethod = maxMethod;
}
/**
* @return the maxLine
*/
public int getMaxLine() {
return maxLine;
}
/**
* @param maxLine the maxLine to set
*/
public void setMaxLine(int maxLine) {
this.maxLine = maxLine;
}
/**
* @return the maxComplexity
*/
public int getMaxComplexity() {
return maxComplexity;
}
/**
* @param maxComplexity the maxComplexity to set
*/
public void setMaxComplexity(int maxComplexity) {
this.maxComplexity = maxComplexity;
}
/**
* @return the maxInstruction
*/
public int getMaxInstruction() {
return maxInstruction;
}
/**
* @param maxInstruction the maxInstruction to set
*/
public void setMaxInstruction(int maxInstruction) {
this.maxInstruction = maxInstruction;
}
/**
* @return the maxBranch
*/
public int getMaxBranch() {
return maxBranch;
}
/**
* @param maxBranch the maxBranch to set
*/
public void setMaxBranch(int maxBranch) {
this.maxBranch = maxBranch;
}
public boolean isFailed() {
return failed;
}
/**
* Marks this coverage object as failed.
* @see Rule
*/
public void setFailed() {
failed = true;
}
@Exported(inline=true)
public Coverage getClassCoverage() {
return clazz;
}
@Exported(inline=true)
public Coverage getMethodCoverage() {
return method;
}
@Exported(inline=true)
public Coverage getComplexityScore() {
return complexity;
}
@Exported(inline=true)
public Coverage getInstructionCoverage() {
return instruction;
}
@Exported(inline=true)
public Coverage getBranchCoverage() {
return branch;
}
/**
* Line coverage. Can be null if this information is not collected.
*/
@Exported(inline=true)
public Coverage getLineCoverage() {
return line;
}
/**
* Gets the build object that owns the whole coverage report tree.
*/
public abstract AbstractBuild<?,?> getBuild();
/**
* Gets the corresponding coverage report object in the previous
* run that has the record.
*
* @return
* null if no earlier record was found.
*/
@Exported
public abstract SELF getPreviousResult();
public CoverageObject<?> getParent() {return null;}
/**
* Used in the view to print out four table columns with the coverage info.
*/
public String printFourCoverageColumns() {
StringBuilder buf = new StringBuilder();
instruction.setType(CoverageElement.Type.INSTRUCTION);
clazz.setType(CoverageElement.Type.CLASS);
complexity.setType(CoverageElement.Type.COMPLEXITY);
branch.setType(CoverageElement.Type.BRANCH);
line.setType(CoverageElement.Type.LINE);
method.setType(CoverageElement.Type.METHOD);
printRatioCell(isFailed(), instruction, buf);
printRatioCell(isFailed(), branch, buf);
printRatioCell(isFailed(), complexity, buf);
printRatioCell(isFailed(), line, buf);
printRatioCell(isFailed(), method, buf);
printRatioCell(isFailed(), clazz, buf);
return buf.toString();
}
public boolean hasLineCoverage() {
return line.isInitialized();
}
public boolean hasClassCoverage() {
return clazz.isInitialized();
}
static NumberFormat dataFormat = new DecimalFormat("000.00", new DecimalFormatSymbols(Locale.US));
static NumberFormat percentFormat = new DecimalFormat("0.0", new DecimalFormatSymbols(Locale.US));
static NumberFormat intFormat = new DecimalFormat("0", new DecimalFormatSymbols(Locale.US));
protected void printRatioCell(boolean failed, Coverage ratio, StringBuilder buf) {
if (ratio != null && ratio.isInitialized()) {
//String className = "nowrap" + (failed ? " red" : "");
buf.append("<td class='").append("").append("'");
buf.append(" data='").append(dataFormat.format(ratio.getPercentageFloat()));
buf.append("'>\n");
printRatioTable(ratio, buf);
buf.append("</td>\n");
}
}
protected void printRatioTable(Coverage ratio, StringBuilder buf){
//String percent = percentFormat.format(ratio.getPercentageFloat());
String numerator = intFormat.format(ratio.getMissed());
String denominator = intFormat.format(ratio.getCovered());
int maximum = 1;
if (ratio.getType().equals(CoverageElement.Type.INSTRUCTION)) {
maximum = getParent().maxInstruction;
} else if (ratio.getType().equals(CoverageElement.Type.BRANCH)) {
maximum = getParent().maxBranch;
} else if (ratio.getType().equals(CoverageElement.Type.COMPLEXITY)) {
maximum = getParent().maxComplexity;
} else if (ratio.getType().equals(CoverageElement.Type.LINE)) {
maximum = getParent().maxLine;
} else if (ratio.getType().equals(CoverageElement.Type.METHOD)) {
maximum = getParent().maxMethod;
} else if (ratio.getType().equals(CoverageElement.Type.CLASS)) {
maximum = getParent().maxClazz;
}
float redBar = ((float) ratio.getMissed())/maximum*100;
float greenBar = ((float)ratio.getTotal())/maximum*100;
buf.append("<table class='percentgraph' cellpadding='0px' cellspacing='0px'>")
.append("<tr>" +
"<td class='percentgraph' colspan='2'>").append("<span class='text'>").append("<b>M:</b> "+numerator).append(" ").append("<b>C:</b> "+ denominator).append("</span></td></tr>")
.append("<tr>")
.append("<td width='40px' class='data'>").append(ratio.getPercentage()).append("%</td>")
.append("<td>")
.append("<div class='percentgraph' style='width: ").append(greenBar).append("px;'>")
.append("<div class='redbar' style='width: ").append(redBar).append("px;'>")
.append("</td></tr>")
.append("</table>");
}
protected <ReportLevel extends AggregatedReport > void setAllCovTypes( ReportLevel reportToSet, ICoverageNode covReport) {
Coverage tempCov = new Coverage();
tempCov.accumulate(covReport.getClassCounter().getMissedCount(), covReport.getClassCounter().getCoveredCount());
reportToSet.clazz = tempCov;
tempCov = new Coverage();
tempCov.accumulate(covReport.getBranchCounter().getMissedCount(), covReport.getBranchCounter().getCoveredCount());
reportToSet.branch = tempCov;
tempCov = new Coverage();
tempCov.accumulate(covReport.getLineCounter().getMissedCount(), covReport.getLineCounter().getCoveredCount());
reportToSet.line = tempCov;
tempCov = new Coverage();
tempCov.accumulate(covReport.getInstructionCounter().getMissedCount(), covReport.getInstructionCounter().getCoveredCount());
reportToSet.instruction = tempCov;
tempCov = new Coverage();
tempCov.accumulate(covReport.getMethodCounter().getMissedCount(), covReport.getMethodCounter().getCoveredCount());
reportToSet.method = tempCov;
tempCov = new Coverage();
tempCov.accumulate(covReport.getComplexityCounter().getMissedCount(), covReport.getComplexityCounter().getCoveredCount());
reportToSet.complexity = tempCov;
}
public < ReportLevel extends AggregatedReport > void setCoverage( ReportLevel reportToSet, ICoverageNode covReport) {
setAllCovTypes(reportToSet, covReport);
if (this.maxClazz < reportToSet.clazz.getTotal()) {
this.maxClazz = reportToSet.clazz.getTotal();
}
if (this.maxBranch < reportToSet.branch.getTotal()) {
this.maxBranch = reportToSet.branch.getTotal();
}
if (this.maxLine < reportToSet.line.getTotal()) {
this.maxLine = reportToSet.line.getTotal();
}
if (this.maxInstruction < reportToSet.instruction.getTotal()) {
this.maxInstruction = reportToSet.instruction.getTotal();
}
if (this.maxMethod < reportToSet.method.getTotal()) {
this.maxMethod = reportToSet.method.getTotal();
}
if (this.maxComplexity < reportToSet.complexity.getTotal()) {
this.maxComplexity = reportToSet.complexity.getTotal();
}
}
/**
* Generates the graph that shows the coverage trend up to this report.
*/
public void doGraph(StaplerRequest req, StaplerResponse rsp) throws IOException {
if(ChartUtil.awtProblemCause != null) {
// not available. send out error message
rsp.sendRedirect2(req.getContextPath()+"/images/headless.png");
return;
}
AbstractBuild<?,?> build = getBuild();
Calendar t = build.getTimestamp();
String w = Util.fixEmptyAndTrim(req.getParameter("width"));
String h = Util.fixEmptyAndTrim(req.getParameter("height"));
int width = (w != null) ? Integer.valueOf(w) : 500;
int height = (h != null) ? Integer.valueOf(h) : 200;
new GraphImpl(this, t, width, height) {
@Override
protected DataSetBuilder<String, NumberOnlyBuildLabel> createDataSet(CoverageObject<SELF> obj) {
DataSetBuilder<String, NumberOnlyBuildLabel> dsb = new DataSetBuilder<String, NumberOnlyBuildLabel>();
for (CoverageObject<SELF> a = obj; a != null; a = a.getPreviousResult()) {
NumberOnlyBuildLabel label = new NumberOnlyBuildLabel(a.getBuild());
/*dsb.add(a.instruction.getPercentageFloat(), Messages.CoverageObject_Legend_Instructions(), label);
dsb.add(a.branch.getPercentageFloat(), Messages.CoverageObject_Legend_Branch(), label);
dsb.add(a.complexity.getPercentageFloat(), Messages.CoverageObject_Legend_Complexity(), label);
dsb.add(a.method.getPercentageFloat(), Messages.CoverageObject_Legend_Method(), label);
dsb.add(a.clazz.getPercentageFloat(), Messages.CoverageObject_Legend_Class(), label);*/
if (a.line != null) {
dsb.add(a.line.getCovered(), Messages.CoverageObject_Legend_LineCovered(), label);
dsb.add(a.line.getMissed(), Messages.CoverageObject_Legend_LineMissed(), label);
} else {
dsb.add(0, Messages.CoverageObject_Legend_LineCovered(), label);
dsb.add(0, Messages.CoverageObject_Legend_LineMissed(), label);
}
}
return dsb;
}
}.doPng(req, rsp);
}
public Api getApi() {
return new Api(this);
}
private abstract class GraphImpl extends Graph {
private CoverageObject<SELF> obj;
public GraphImpl(CoverageObject<SELF> obj, Calendar timestamp, int defaultW, int defaultH) {
super(timestamp, defaultW, defaultH);
this.obj = obj;
}
protected abstract DataSetBuilder<String, NumberOnlyBuildLabel> createDataSet(CoverageObject<SELF> obj);
@Override
protected JFreeChart createGraph() {
final CategoryDataset dataset = createDataSet(obj).build();
final JFreeChart chart = ChartFactory.createLineChart(
null, // chart title
null, // unused
"", // range axis label
dataset, // data
PlotOrientation.VERTICAL, // orientation
true, // include legend
true, // tooltips
false // urls
);
// NOW DO SOME OPTIONAL CUSTOMISATION OF THE CHART...
final LegendTitle legend = chart.getLegend();
legend.setPosition(RectangleEdge.RIGHT);
chart.setBackgroundPaint(Color.white);
final CategoryPlot plot = chart.getCategoryPlot();
// plot.setAxisOffset(new Spacer(Spacer.ABSOLUTE, 5.0, 5.0, 5.0, 5.0));
plot.setBackgroundPaint(Color.WHITE);
plot.setOutlinePaint(null);
plot.setRangeGridlinesVisible(true);
plot.setRangeGridlinePaint(Color.black);
CategoryAxis domainAxis = new ShiftedCategoryAxis(null);
plot.setDomainAxis(domainAxis);
domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_90);
domainAxis.setLowerMargin(0.0);
domainAxis.setUpperMargin(0.0);
domainAxis.setCategoryMargin(0.0);
final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
- if (line!=null) {
- rangeAxis.setUpperBound(line.getCovered() > line.getMissed() ? line.getCovered() + 5 : line.getMissed() + 5);
- }
rangeAxis.setLowerBound(0);
final LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot.getRenderer();
renderer.setSeriesPaint(0, Color.green);
renderer.setSeriesPaint(1, Color.red);
renderer.setSeriesItemLabelPaint(0, Color.green);
renderer.setSeriesItemLabelPaint(1, Color.red);
renderer.setSeriesFillPaint(0, Color.green);
renderer.setSeriesFillPaint(1, Color.red);
renderer.setBaseStroke(new BasicStroke(4.0f));
//ColorPalette.apply(renderer);
// crop extra space around the graph
plot.setInsets(new RectangleInsets(5.0, 0, 0, 5.0));
return chart;
}
}
@Override
public String toString() {
return getClass().getSimpleName() + ":"
+ " instruction=" + instruction
+ " branch=" + branch
+ " complexity=" + complexity
+ " line=" + line
+ " method=" + method
+ " class=" + clazz;
}
private static final Logger logger = Logger.getLogger(CoverageObject.class.getName());
}
| true | true | protected JFreeChart createGraph() {
final CategoryDataset dataset = createDataSet(obj).build();
final JFreeChart chart = ChartFactory.createLineChart(
null, // chart title
null, // unused
"", // range axis label
dataset, // data
PlotOrientation.VERTICAL, // orientation
true, // include legend
true, // tooltips
false // urls
);
// NOW DO SOME OPTIONAL CUSTOMISATION OF THE CHART...
final LegendTitle legend = chart.getLegend();
legend.setPosition(RectangleEdge.RIGHT);
chart.setBackgroundPaint(Color.white);
final CategoryPlot plot = chart.getCategoryPlot();
// plot.setAxisOffset(new Spacer(Spacer.ABSOLUTE, 5.0, 5.0, 5.0, 5.0));
plot.setBackgroundPaint(Color.WHITE);
plot.setOutlinePaint(null);
plot.setRangeGridlinesVisible(true);
plot.setRangeGridlinePaint(Color.black);
CategoryAxis domainAxis = new ShiftedCategoryAxis(null);
plot.setDomainAxis(domainAxis);
domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_90);
domainAxis.setLowerMargin(0.0);
domainAxis.setUpperMargin(0.0);
domainAxis.setCategoryMargin(0.0);
final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
if (line!=null) {
rangeAxis.setUpperBound(line.getCovered() > line.getMissed() ? line.getCovered() + 5 : line.getMissed() + 5);
}
rangeAxis.setLowerBound(0);
final LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot.getRenderer();
renderer.setSeriesPaint(0, Color.green);
renderer.setSeriesPaint(1, Color.red);
renderer.setSeriesItemLabelPaint(0, Color.green);
renderer.setSeriesItemLabelPaint(1, Color.red);
renderer.setSeriesFillPaint(0, Color.green);
renderer.setSeriesFillPaint(1, Color.red);
renderer.setBaseStroke(new BasicStroke(4.0f));
//ColorPalette.apply(renderer);
// crop extra space around the graph
plot.setInsets(new RectangleInsets(5.0, 0, 0, 5.0));
return chart;
}
| protected JFreeChart createGraph() {
final CategoryDataset dataset = createDataSet(obj).build();
final JFreeChart chart = ChartFactory.createLineChart(
null, // chart title
null, // unused
"", // range axis label
dataset, // data
PlotOrientation.VERTICAL, // orientation
true, // include legend
true, // tooltips
false // urls
);
// NOW DO SOME OPTIONAL CUSTOMISATION OF THE CHART...
final LegendTitle legend = chart.getLegend();
legend.setPosition(RectangleEdge.RIGHT);
chart.setBackgroundPaint(Color.white);
final CategoryPlot plot = chart.getCategoryPlot();
// plot.setAxisOffset(new Spacer(Spacer.ABSOLUTE, 5.0, 5.0, 5.0, 5.0));
plot.setBackgroundPaint(Color.WHITE);
plot.setOutlinePaint(null);
plot.setRangeGridlinesVisible(true);
plot.setRangeGridlinePaint(Color.black);
CategoryAxis domainAxis = new ShiftedCategoryAxis(null);
plot.setDomainAxis(domainAxis);
domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_90);
domainAxis.setLowerMargin(0.0);
domainAxis.setUpperMargin(0.0);
domainAxis.setCategoryMargin(0.0);
final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
rangeAxis.setLowerBound(0);
final LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot.getRenderer();
renderer.setSeriesPaint(0, Color.green);
renderer.setSeriesPaint(1, Color.red);
renderer.setSeriesItemLabelPaint(0, Color.green);
renderer.setSeriesItemLabelPaint(1, Color.red);
renderer.setSeriesFillPaint(0, Color.green);
renderer.setSeriesFillPaint(1, Color.red);
renderer.setBaseStroke(new BasicStroke(4.0f));
//ColorPalette.apply(renderer);
// crop extra space around the graph
plot.setInsets(new RectangleInsets(5.0, 0, 0, 5.0));
return chart;
}
|
diff --git a/src/tux2/spoutlwc/SpoutLWC.java b/src/tux2/spoutlwc/SpoutLWC.java
index 0424f1a..b00e225 100644
--- a/src/tux2/spoutlwc/SpoutLWC.java
+++ b/src/tux2/spoutlwc/SpoutLWC.java
@@ -1,102 +1,102 @@
package tux2.spoutlwc;
import java.util.HashSet;
import java.util.concurrent.ConcurrentHashMap;
import org.bukkit.entity.Player;
import org.bukkit.event.Event.Priority;
import org.bukkit.event.Event.Type;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.PluginManager;
import org.getspout.spoutapi.player.SpoutPlayer;
import com.griefcraft.lwc.*;
import com.nijiko.permissions.PermissionHandler;
import com.nijikokun.bukkit.Permissions.Permissions;
/**
* spoutlwc for Bukkit
*
* @author tux2
*/
public class SpoutLWC extends JavaPlugin {
private static PermissionHandler Permissions;
LWC lwc = null;
public HashSet<Byte> transparentBlocks = new HashSet<Byte>();
ConcurrentHashMap<SpoutPlayer, PlayerLwcGUI> guiscreens = new ConcurrentHashMap<SpoutPlayer, PlayerLwcGUI>();
ConcurrentHashMap<SpoutPlayer, UnlockGUI> unlockscreens = new ConcurrentHashMap<SpoutPlayer, UnlockGUI>();
public SpoutLWC() {
super();
//Setting transparent blocks.
transparentBlocks.add((byte) 0); // Air
transparentBlocks.add((byte) 8); // Water
transparentBlocks.add((byte) 9); // Stationary Water
transparentBlocks.add((byte) 20); // Glass
transparentBlocks.add((byte) 30); // Cobweb
transparentBlocks.add((byte) 65); // Ladder
transparentBlocks.add((byte) 66); // Rail
transparentBlocks.add((byte) 78); // Snow
transparentBlocks.add((byte) 83); // Sugar Cane
transparentBlocks.add((byte) 101); // Iron Bars
transparentBlocks.add((byte) 102); // Glass Pane
transparentBlocks.add((byte) 106); // Vines
}
public void onEnable() {
setupPermissions();
Plugin lwcPlugin = getServer().getPluginManager().getPlugin("LWC");
if(lwcPlugin != null) {
lwc = ((LWCPlugin) lwcPlugin).getLWC();
- LWCScreenListener serverListener = new LWCScreenListener(this);
+ LWCServerListener serverListener = new LWCServerListener(this);
// Register our events
PluginManager pm = getServer().getPluginManager();
pm.registerEvent(Type.CUSTOM_EVENT, new LWCScreenListener(this), Priority.Normal, this);
pm.registerEvent(Type.CUSTOM_EVENT, new LWCInputListener(this), Priority.Normal, this);
pm.registerEvent(Type.PLUGIN_ENABLE, serverListener, Priority.Monitor, this);
pm.registerEvent(Type.PLUGIN_DISABLE, serverListener, Priority.Monitor, this);
// EXAMPLE: Custom code, here we just output some info so we can check all is well
PluginDescriptionFile pdfFile = this.getDescription();
System.out.println( pdfFile.getName() + " version " + pdfFile.getVersion() + " is enabled!" );
}else {
System.out.println("[SpoutLWC] Lightweight chest not found! This plugin will not work!");
}
}
public void onDisable() {
// NOTE: All registered events are automatically unregistered when a plugin is disabled
// EXAMPLE: Custom code, here we just output some info so we can check all is well
System.out.println("Goodbye world!");
}
public boolean hasPermissions(Player player, String node) {
if (Permissions != null) {
return Permissions.has(player, node);
} else {
return player.hasPermission(node);
}
}
private void setupPermissions() {
Plugin permissions = this.getServer().getPluginManager().getPlugin("Permissions");
if (Permissions == null) {
if (permissions != null) {
Permissions = ((Permissions)permissions).getHandler();
} else {
}
}
}
}
| true | true | public void onEnable() {
setupPermissions();
Plugin lwcPlugin = getServer().getPluginManager().getPlugin("LWC");
if(lwcPlugin != null) {
lwc = ((LWCPlugin) lwcPlugin).getLWC();
LWCScreenListener serverListener = new LWCScreenListener(this);
// Register our events
PluginManager pm = getServer().getPluginManager();
pm.registerEvent(Type.CUSTOM_EVENT, new LWCScreenListener(this), Priority.Normal, this);
pm.registerEvent(Type.CUSTOM_EVENT, new LWCInputListener(this), Priority.Normal, this);
pm.registerEvent(Type.PLUGIN_ENABLE, serverListener, Priority.Monitor, this);
pm.registerEvent(Type.PLUGIN_DISABLE, serverListener, Priority.Monitor, this);
// EXAMPLE: Custom code, here we just output some info so we can check all is well
PluginDescriptionFile pdfFile = this.getDescription();
System.out.println( pdfFile.getName() + " version " + pdfFile.getVersion() + " is enabled!" );
}else {
System.out.println("[SpoutLWC] Lightweight chest not found! This plugin will not work!");
}
}
| public void onEnable() {
setupPermissions();
Plugin lwcPlugin = getServer().getPluginManager().getPlugin("LWC");
if(lwcPlugin != null) {
lwc = ((LWCPlugin) lwcPlugin).getLWC();
LWCServerListener serverListener = new LWCServerListener(this);
// Register our events
PluginManager pm = getServer().getPluginManager();
pm.registerEvent(Type.CUSTOM_EVENT, new LWCScreenListener(this), Priority.Normal, this);
pm.registerEvent(Type.CUSTOM_EVENT, new LWCInputListener(this), Priority.Normal, this);
pm.registerEvent(Type.PLUGIN_ENABLE, serverListener, Priority.Monitor, this);
pm.registerEvent(Type.PLUGIN_DISABLE, serverListener, Priority.Monitor, this);
// EXAMPLE: Custom code, here we just output some info so we can check all is well
PluginDescriptionFile pdfFile = this.getDescription();
System.out.println( pdfFile.getName() + " version " + pdfFile.getVersion() + " is enabled!" );
}else {
System.out.println("[SpoutLWC] Lightweight chest not found! This plugin will not work!");
}
}
|
diff --git a/activemq-core/src/test/java/org/apache/activemq/usecases/TwoBrokerQueueSendReceiveTest.java b/activemq-core/src/test/java/org/apache/activemq/usecases/TwoBrokerQueueSendReceiveTest.java
index 6d01da5ef..d463c14cf 100644
--- a/activemq-core/src/test/java/org/apache/activemq/usecases/TwoBrokerQueueSendReceiveTest.java
+++ b/activemq-core/src/test/java/org/apache/activemq/usecases/TwoBrokerQueueSendReceiveTest.java
@@ -1,60 +1,60 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.network.DemandForwardingBridgeSupport;
import org.apache.activemq.util.Wait;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
*/
public class TwoBrokerQueueSendReceiveTest extends TwoBrokerTopicSendReceiveTest {
private static final Logger LOG = LoggerFactory.getLogger(TwoBrokerQueueSendReceiveTest.class);
protected void setUp() throws Exception {
topic = false;
super.setUp();
}
public void testReceiveOnXConsumersNoLeak() throws Exception {
consumer.close();
sendMessages();
for (int i=0; i<data.length; i++) {
consumer = createConsumer();
onMessage(consumer.receive(10000));
consumer.close();
}
waitForMessagesToBeDelivered();
assertEquals("Got all messages", data.length, messages.size());
BrokerService broker = (BrokerService) brokers.get("receiver");
final DemandForwardingBridgeSupport bridge = (DemandForwardingBridgeSupport) broker.getNetworkConnectors().get(0).activeBridges().toArray()[0];
assertTrue("No extra, size:" + bridge.getLocalSubscriptionMap().size(), Wait.waitFor(new Wait.Condition() {
@Override
public boolean isSatisified() throws Exception {
LOG.info("local subs map size = " + bridge.getLocalSubscriptionMap().size());
- return 1 == bridge.getLocalSubscriptionMap().size();
+ return 0 == bridge.getLocalSubscriptionMap().size();
}
}));
}
}
| true | true | public void testReceiveOnXConsumersNoLeak() throws Exception {
consumer.close();
sendMessages();
for (int i=0; i<data.length; i++) {
consumer = createConsumer();
onMessage(consumer.receive(10000));
consumer.close();
}
waitForMessagesToBeDelivered();
assertEquals("Got all messages", data.length, messages.size());
BrokerService broker = (BrokerService) brokers.get("receiver");
final DemandForwardingBridgeSupport bridge = (DemandForwardingBridgeSupport) broker.getNetworkConnectors().get(0).activeBridges().toArray()[0];
assertTrue("No extra, size:" + bridge.getLocalSubscriptionMap().size(), Wait.waitFor(new Wait.Condition() {
@Override
public boolean isSatisified() throws Exception {
LOG.info("local subs map size = " + bridge.getLocalSubscriptionMap().size());
return 1 == bridge.getLocalSubscriptionMap().size();
}
}));
}
| public void testReceiveOnXConsumersNoLeak() throws Exception {
consumer.close();
sendMessages();
for (int i=0; i<data.length; i++) {
consumer = createConsumer();
onMessage(consumer.receive(10000));
consumer.close();
}
waitForMessagesToBeDelivered();
assertEquals("Got all messages", data.length, messages.size());
BrokerService broker = (BrokerService) brokers.get("receiver");
final DemandForwardingBridgeSupport bridge = (DemandForwardingBridgeSupport) broker.getNetworkConnectors().get(0).activeBridges().toArray()[0];
assertTrue("No extra, size:" + bridge.getLocalSubscriptionMap().size(), Wait.waitFor(new Wait.Condition() {
@Override
public boolean isSatisified() throws Exception {
LOG.info("local subs map size = " + bridge.getLocalSubscriptionMap().size());
return 0 == bridge.getLocalSubscriptionMap().size();
}
}));
}
|
diff --git a/src/test/java/javax/time/format/TestStringLiteralParser.java b/src/test/java/javax/time/format/TestStringLiteralParser.java
index bc2677bf..aa069a04 100644
--- a/src/test/java/javax/time/format/TestStringLiteralParser.java
+++ b/src/test/java/javax/time/format/TestStringLiteralParser.java
@@ -1,101 +1,102 @@
/*
* Copyright (c) 2008-2012, Stephen Colebourne & Michael Nascimento Santos
*
* 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 JSR-310 nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package javax.time.format;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import javax.time.format.DateTimeFormatterBuilder.StringLiteralPrinterParser;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
/**
* Test StringLiteralPrinterParser.
*/
@Test(groups={"implementation"})
public class TestStringLiteralParser extends AbstractTestPrinterParser {
@DataProvider(name="success")
Object[][] data_success() {
return new Object[][] {
// match
{new StringLiteralPrinterParser("hello"), true, "hello", 0, 5},
{new StringLiteralPrinterParser("hello"), true, "helloOTHER", 0, 5},
{new StringLiteralPrinterParser("hello"), true, "OTHERhelloOTHER", 5, 10},
{new StringLiteralPrinterParser("hello"), true, "OTHERhello", 5, 10},
// no match
{new StringLiteralPrinterParser("hello"), true, "", 0, ~0},
{new StringLiteralPrinterParser("hello"), true, "a", 1, ~1},
{new StringLiteralPrinterParser("hello"), true, "HELLO", 0, ~0},
{new StringLiteralPrinterParser("hello"), true, "hlloo", 0, ~0},
{new StringLiteralPrinterParser("hello"), true, "OTHERhllooOTHER", 5, ~5},
{new StringLiteralPrinterParser("hello"), true, "OTHERhlloo", 5, ~5},
{new StringLiteralPrinterParser("hello"), true, "h", 0, ~0},
{new StringLiteralPrinterParser("hello"), true, "OTHERh", 5, ~5},
// case insensitive
{new StringLiteralPrinterParser("hello"), false, "hello", 0, 5},
{new StringLiteralPrinterParser("hello"), false, "HELLO", 0, 5},
{new StringLiteralPrinterParser("hello"), false, "HelLo", 0, 5},
+ {new StringLiteralPrinterParser("hello"), false, "HelLO", 0, 5},
};
}
@Test(dataProvider="success")
public void test_parse_success(StringLiteralPrinterParser pp, boolean caseSensitive, String text, int pos, int expectedPos) {
parseContext.setCaseSensitive(caseSensitive);
int result = pp.parse(parseContext, text, pos);
assertEquals(result, expectedPos);
assertEquals(parseContext.getParsed().size(), 0);
}
//-----------------------------------------------------------------------
@DataProvider(name="error")
Object[][] data_error() {
return new Object[][] {
{new StringLiteralPrinterParser("hello"), "hello", -1, IndexOutOfBoundsException.class},
{new StringLiteralPrinterParser("hello"), "hello", 6, IndexOutOfBoundsException.class},
};
}
@Test(dataProvider="error")
public void test_parse_error(StringLiteralPrinterParser pp, String text, int pos, Class<?> expected) {
try {
pp.parse(parseContext, text, pos);
} catch (RuntimeException ex) {
assertTrue(expected.isInstance(ex));
assertEquals(parseContext.getParsed().size(), 0);
}
}
}
| true | true | Object[][] data_success() {
return new Object[][] {
// match
{new StringLiteralPrinterParser("hello"), true, "hello", 0, 5},
{new StringLiteralPrinterParser("hello"), true, "helloOTHER", 0, 5},
{new StringLiteralPrinterParser("hello"), true, "OTHERhelloOTHER", 5, 10},
{new StringLiteralPrinterParser("hello"), true, "OTHERhello", 5, 10},
// no match
{new StringLiteralPrinterParser("hello"), true, "", 0, ~0},
{new StringLiteralPrinterParser("hello"), true, "a", 1, ~1},
{new StringLiteralPrinterParser("hello"), true, "HELLO", 0, ~0},
{new StringLiteralPrinterParser("hello"), true, "hlloo", 0, ~0},
{new StringLiteralPrinterParser("hello"), true, "OTHERhllooOTHER", 5, ~5},
{new StringLiteralPrinterParser("hello"), true, "OTHERhlloo", 5, ~5},
{new StringLiteralPrinterParser("hello"), true, "h", 0, ~0},
{new StringLiteralPrinterParser("hello"), true, "OTHERh", 5, ~5},
// case insensitive
{new StringLiteralPrinterParser("hello"), false, "hello", 0, 5},
{new StringLiteralPrinterParser("hello"), false, "HELLO", 0, 5},
{new StringLiteralPrinterParser("hello"), false, "HelLo", 0, 5},
};
}
| Object[][] data_success() {
return new Object[][] {
// match
{new StringLiteralPrinterParser("hello"), true, "hello", 0, 5},
{new StringLiteralPrinterParser("hello"), true, "helloOTHER", 0, 5},
{new StringLiteralPrinterParser("hello"), true, "OTHERhelloOTHER", 5, 10},
{new StringLiteralPrinterParser("hello"), true, "OTHERhello", 5, 10},
// no match
{new StringLiteralPrinterParser("hello"), true, "", 0, ~0},
{new StringLiteralPrinterParser("hello"), true, "a", 1, ~1},
{new StringLiteralPrinterParser("hello"), true, "HELLO", 0, ~0},
{new StringLiteralPrinterParser("hello"), true, "hlloo", 0, ~0},
{new StringLiteralPrinterParser("hello"), true, "OTHERhllooOTHER", 5, ~5},
{new StringLiteralPrinterParser("hello"), true, "OTHERhlloo", 5, ~5},
{new StringLiteralPrinterParser("hello"), true, "h", 0, ~0},
{new StringLiteralPrinterParser("hello"), true, "OTHERh", 5, ~5},
// case insensitive
{new StringLiteralPrinterParser("hello"), false, "hello", 0, 5},
{new StringLiteralPrinterParser("hello"), false, "HELLO", 0, 5},
{new StringLiteralPrinterParser("hello"), false, "HelLo", 0, 5},
{new StringLiteralPrinterParser("hello"), false, "HelLO", 0, 5},
};
}
|
diff --git a/src/com/android/calendar/DayFragment.java b/src/com/android/calendar/DayFragment.java
index e3ef6946..2ba8dbfe 100644
--- a/src/com/android/calendar/DayFragment.java
+++ b/src/com/android/calendar/DayFragment.java
@@ -1,271 +1,272 @@
/*
* 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.calendar;
import com.android.calendar.CalendarController.EventInfo;
import com.android.calendar.CalendarController.EventType;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.text.format.Time;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ProgressBar;
import android.widget.ViewSwitcher;
import android.widget.ViewSwitcher.ViewFactory;
/**
* This is the base class for Day and Week Activities.
*/
public class DayFragment extends Fragment implements CalendarController.EventHandler, ViewFactory {
/**
* The view id used for all the views we create. It's OK to have all child
* views have the same ID. This ID is used to pick which view receives
* focus when a view hierarchy is saved / restore
*/
private static final int VIEW_ID = 1;
protected static final String BUNDLE_KEY_RESTORE_TIME = "key_restore_time";
protected ProgressBar mProgressBar;
protected ViewSwitcher mViewSwitcher;
protected Animation mInAnimationForward;
protected Animation mOutAnimationForward;
protected Animation mInAnimationBackward;
protected Animation mOutAnimationBackward;
EventLoader mEventLoader;
Time mSelectedDay = new Time();
private Runnable mTZUpdater = new Runnable() {
@Override
public void run() {
if (!DayFragment.this.isAdded()) {
return;
}
String tz = Utils.getTimeZone(getActivity(), mTZUpdater);
mSelectedDay.timezone = tz;
mSelectedDay.normalize(true);
}
};
private int mNumDays;
public DayFragment() {
mSelectedDay.setToNow();
}
public DayFragment(long timeMillis, int numOfDays) {
mNumDays = numOfDays;
if (timeMillis == 0) {
mSelectedDay.setToNow();
} else {
mSelectedDay.set(timeMillis);
}
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
Context context = getActivity();
mInAnimationForward = AnimationUtils.loadAnimation(context, R.anim.slide_left_in);
mOutAnimationForward = AnimationUtils.loadAnimation(context, R.anim.slide_left_out);
mInAnimationBackward = AnimationUtils.loadAnimation(context, R.anim.slide_right_in);
mOutAnimationBackward = AnimationUtils.loadAnimation(context, R.anim.slide_right_out);
mEventLoader = new EventLoader(context);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.day_activity, null);
mViewSwitcher = (ViewSwitcher) v.findViewById(R.id.switcher);
mViewSwitcher.setFactory(this);
mViewSwitcher.getCurrentView().requestFocus();
((DayView) mViewSwitcher.getCurrentView()).updateTitle();
return v;
}
public View makeView() {
mTZUpdater.run();
DayView view = new DayView(getActivity(), CalendarController
.getInstance(getActivity()), mViewSwitcher, mEventLoader, mNumDays);
view.setId(VIEW_ID);
view.setLayoutParams(new ViewSwitcher.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
view.setSelected(mSelectedDay, false, false);
return view;
}
@Override
public void onResume() {
super.onResume();
mEventLoader.startBackgroundThread();
mTZUpdater.run();
eventsChanged();
DayView view = (DayView) mViewSwitcher.getCurrentView();
view.handleOnResume();
view.restartCurrentTimeUpdates();
view = (DayView) mViewSwitcher.getNextView();
view.handleOnResume();
view.restartCurrentTimeUpdates();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
long time = getSelectedTimeInMillis();
if (time != -1) {
outState.putLong(BUNDLE_KEY_RESTORE_TIME, time);
}
}
@Override
public void onPause() {
super.onPause();
DayView view = (DayView) mViewSwitcher.getCurrentView();
view.cleanup();
view = (DayView) mViewSwitcher.getNextView();
view.cleanup();
mEventLoader.stopBackgroundThread();
}
void startProgressSpinner() {
// start the progress spinner
mProgressBar.setVisibility(View.VISIBLE);
}
void stopProgressSpinner() {
// stop the progress spinner
mProgressBar.setVisibility(View.GONE);
}
private void goTo(Time goToTime, boolean ignoreTime, boolean animateToday) {
if (mViewSwitcher == null) {
// The view hasn't been set yet. Just save the time and use it later.
mSelectedDay.set(goToTime);
return;
}
DayView currentView = (DayView) mViewSwitcher.getCurrentView();
// How does goTo time compared to what's already displaying?
int diff = currentView.compareToVisibleTimeRange(goToTime);
if (diff == 0) {
// In visible range. No need to switch view
currentView.setSelected(goToTime, ignoreTime, animateToday);
} else {
// Figure out which way to animate
if (diff > 0) {
mViewSwitcher.setInAnimation(mInAnimationForward);
mViewSwitcher.setOutAnimation(mOutAnimationForward);
} else {
mViewSwitcher.setInAnimation(mInAnimationBackward);
mViewSwitcher.setOutAnimation(mOutAnimationBackward);
}
DayView next = (DayView) mViewSwitcher.getNextView();
if (ignoreTime) {
next.setFirstVisibleHour(currentView.getFirstVisibleHour());
}
next.setSelected(goToTime, ignoreTime, animateToday);
next.reloadEvents();
mViewSwitcher.showNext();
next.requestFocus();
next.updateTitle();
+ next.restartCurrentTimeUpdates();
}
}
/**
* Returns the selected time in milliseconds. The milliseconds are measured
* in UTC milliseconds from the epoch and uniquely specifies any selectable
* time.
*
* @return the selected time in milliseconds
*/
public long getSelectedTimeInMillis() {
if (mViewSwitcher == null) {
return -1;
}
DayView view = (DayView) mViewSwitcher.getCurrentView();
if (view == null) {
return -1;
}
return view.getSelectedTimeInMillis();
}
public void eventsChanged() {
if (mViewSwitcher == null) {
return;
}
DayView view = (DayView) mViewSwitcher.getCurrentView();
view.clearCachedEvents();
view.reloadEvents();
view = (DayView) mViewSwitcher.getNextView();
view.clearCachedEvents();
}
Event getSelectedEvent() {
DayView view = (DayView) mViewSwitcher.getCurrentView();
return view.getSelectedEvent();
}
boolean isEventSelected() {
DayView view = (DayView) mViewSwitcher.getCurrentView();
return view.isEventSelected();
}
Event getNewEvent() {
DayView view = (DayView) mViewSwitcher.getCurrentView();
return view.getNewEvent();
}
public DayView getNextView() {
return (DayView) mViewSwitcher.getNextView();
}
public long getSupportedEventTypes() {
return EventType.GO_TO | EventType.EVENTS_CHANGED;
}
public void handleEvent(EventInfo msg) {
if (msg.eventType == EventType.GO_TO) {
// TODO support a range of time
// TODO support event_id
// TODO support select message
goTo(msg.selectedTime, (msg.extraLong & CalendarController.EXTRA_GOTO_DATE) != 0,
(msg.extraLong & CalendarController.EXTRA_GOTO_TODAY) != 0);
} else if (msg.eventType == EventType.EVENTS_CHANGED) {
eventsChanged();
}
}
}
| true | true | private void goTo(Time goToTime, boolean ignoreTime, boolean animateToday) {
if (mViewSwitcher == null) {
// The view hasn't been set yet. Just save the time and use it later.
mSelectedDay.set(goToTime);
return;
}
DayView currentView = (DayView) mViewSwitcher.getCurrentView();
// How does goTo time compared to what's already displaying?
int diff = currentView.compareToVisibleTimeRange(goToTime);
if (diff == 0) {
// In visible range. No need to switch view
currentView.setSelected(goToTime, ignoreTime, animateToday);
} else {
// Figure out which way to animate
if (diff > 0) {
mViewSwitcher.setInAnimation(mInAnimationForward);
mViewSwitcher.setOutAnimation(mOutAnimationForward);
} else {
mViewSwitcher.setInAnimation(mInAnimationBackward);
mViewSwitcher.setOutAnimation(mOutAnimationBackward);
}
DayView next = (DayView) mViewSwitcher.getNextView();
if (ignoreTime) {
next.setFirstVisibleHour(currentView.getFirstVisibleHour());
}
next.setSelected(goToTime, ignoreTime, animateToday);
next.reloadEvents();
mViewSwitcher.showNext();
next.requestFocus();
next.updateTitle();
}
}
| private void goTo(Time goToTime, boolean ignoreTime, boolean animateToday) {
if (mViewSwitcher == null) {
// The view hasn't been set yet. Just save the time and use it later.
mSelectedDay.set(goToTime);
return;
}
DayView currentView = (DayView) mViewSwitcher.getCurrentView();
// How does goTo time compared to what's already displaying?
int diff = currentView.compareToVisibleTimeRange(goToTime);
if (diff == 0) {
// In visible range. No need to switch view
currentView.setSelected(goToTime, ignoreTime, animateToday);
} else {
// Figure out which way to animate
if (diff > 0) {
mViewSwitcher.setInAnimation(mInAnimationForward);
mViewSwitcher.setOutAnimation(mOutAnimationForward);
} else {
mViewSwitcher.setInAnimation(mInAnimationBackward);
mViewSwitcher.setOutAnimation(mOutAnimationBackward);
}
DayView next = (DayView) mViewSwitcher.getNextView();
if (ignoreTime) {
next.setFirstVisibleHour(currentView.getFirstVisibleHour());
}
next.setSelected(goToTime, ignoreTime, animateToday);
next.reloadEvents();
mViewSwitcher.showNext();
next.requestFocus();
next.updateTitle();
next.restartCurrentTimeUpdates();
}
}
|
diff --git a/java/src/org/pocketworkstation/pckeyboard/LatinKeyboardBaseView.java b/java/src/org/pocketworkstation/pckeyboard/LatinKeyboardBaseView.java
index 6e1487f..327cf90 100644
--- a/java/src/org/pocketworkstation/pckeyboard/LatinKeyboardBaseView.java
+++ b/java/src/org/pocketworkstation/pckeyboard/LatinKeyboardBaseView.java
@@ -1,1619 +1,1619 @@
/*
* 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 org.pocketworkstation.pckeyboard;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.Region.Op;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import org.pocketworkstation.pckeyboard.Keyboard.Key;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.PopupWindow;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.WeakHashMap;
/**
* A view that renders a virtual {@link LatinKeyboard}. It handles rendering of keys and
* detecting key presses and touch movements.
*
* TODO: References to LatinKeyboard in this class should be replaced with ones to its base class.
*
* @attr ref R.styleable#LatinKeyboardBaseView_keyBackground
* @attr ref R.styleable#LatinKeyboardBaseView_keyPreviewLayout
* @attr ref R.styleable#LatinKeyboardBaseView_keyPreviewOffset
* @attr ref R.styleable#LatinKeyboardBaseView_labelTextSize
* @attr ref R.styleable#LatinKeyboardBaseView_keyTextSize
* @attr ref R.styleable#LatinKeyboardBaseView_keyTextColor
* @attr ref R.styleable#LatinKeyboardBaseView_verticalCorrection
* @attr ref R.styleable#LatinKeyboardBaseView_popupLayout
*/
public class LatinKeyboardBaseView extends View implements PointerTracker.UIProxy {
private static final String TAG = "LatinKeyboardBaseView";
private static final boolean DEBUG = false;
public static final int NOT_A_TOUCH_COORDINATE = -1;
public interface OnKeyboardActionListener {
/**
* Called when the user presses a key. This is sent before the
* {@link #onKey} is called. For keys that repeat, this is only
* called once.
*
* @param primaryCode
* the unicode of the key being pressed. If the touch is
* not on a valid key, the value will be zero.
*/
void onPress(int primaryCode);
/**
* Called when the user releases a key. This is sent after the
* {@link #onKey} is called. For keys that repeat, this is only
* called once.
*
* @param primaryCode
* the code of the key that was released
*/
void onRelease(int primaryCode);
/**
* Send a key press to the listener.
*
* @param primaryCode
* this is the key that was pressed
* @param keyCodes
* the codes for all the possible alternative keys with
* the primary code being the first. If the primary key
* code is a single character such as an alphabet or
* number or symbol, the alternatives will include other
* characters that may be on the same key or adjacent
* keys. These codes are useful to correct for
* accidental presses of a key adjacent to the intended
* key.
* @param x
* x-coordinate pixel of touched event. If onKey is not called by onTouchEvent,
* the value should be NOT_A_TOUCH_COORDINATE.
* @param y
* y-coordinate pixel of touched event. If onKey is not called by onTouchEvent,
* the value should be NOT_A_TOUCH_COORDINATE.
*/
void onKey(int primaryCode, int[] keyCodes, int x, int y);
/**
* Sends a sequence of characters to the listener.
*
* @param text
* the sequence of characters to be displayed.
*/
void onText(CharSequence text);
/**
* Called when user released a finger outside any key.
*/
void onCancel();
/**
* Called when the user quickly moves the finger from right to
* left.
*/
void swipeLeft();
/**
* Called when the user quickly moves the finger from left to
* right.
*/
void swipeRight();
/**
* Called when the user quickly moves the finger from up to down.
*/
void swipeDown();
/**
* Called when the user quickly moves the finger from down to up.
*/
void swipeUp();
}
// Timing constants
private final int mKeyRepeatInterval;
// Miscellaneous constants
/* package */ static final int NOT_A_KEY = -1;
private static final int[] LONG_PRESSABLE_STATE_SET = { android.R.attr.state_long_pressable };
private static final int NUMBER_HINT_VERTICAL_ADJUSTMENT_PIXEL = -1;
// XML attribute
private float mKeyTextSize;
private int mKeyTextColor;
private int mKeyCursorColor;
private Typeface mKeyTextStyle = Typeface.DEFAULT;
private float mLabelTextSize;
private int mSymbolColorScheme = 0;
private int mShadowColor;
private float mShadowRadius;
private Drawable mKeyBackground;
private float mBackgroundDimAmount;
private float mKeyHysteresisDistance;
private float mVerticalCorrection;
private float mLabelScale = 1.0f;
private int mPreviewOffset;
private int mPreviewHeight;
private int mPopupLayout;
// Main keyboard
private Keyboard mKeyboard;
private Key[] mKeys;
// TODO this attribute should be gotten from Keyboard.
private int mKeyboardVerticalGap;
// Key preview popup
private TextView mPreviewText;
private PopupWindow mPreviewPopup;
private int mPreviewTextSizeLarge;
private int[] mOffsetInWindow;
private int mOldPreviewKeyIndex = NOT_A_KEY;
private boolean mShowPreview = true;
private boolean mShowTouchPoints = true;
private int mPopupPreviewOffsetX;
private int mPopupPreviewOffsetY;
private int mWindowY;
private int mPopupPreviewDisplayedY;
private final int mDelayBeforePreview;
private final int mDelayBeforeSpacePreview;
private final int mDelayAfterPreview;
// Popup mini keyboard
private PopupWindow mMiniKeyboardPopup;
private LatinKeyboardBaseView mMiniKeyboard;
private View mMiniKeyboardParent;
private final WeakHashMap<Key, View> mMiniKeyboardCache = new WeakHashMap<Key, View>();
private int mMiniKeyboardOriginX;
private int mMiniKeyboardOriginY;
private long mMiniKeyboardPopupTime;
private int[] mWindowOffset;
private final float mMiniKeyboardSlideAllowance;
private int mMiniKeyboardTrackerId;
/** Listener for {@link OnKeyboardActionListener}. */
private OnKeyboardActionListener mKeyboardActionListener;
private final ArrayList<PointerTracker> mPointerTrackers = new ArrayList<PointerTracker>();
// TODO: Let the PointerTracker class manage this pointer queue
private final PointerQueue mPointerQueue = new PointerQueue();
private final boolean mHasDistinctMultitouch;
private int mOldPointerCount = 1;
protected KeyDetector mKeyDetector = new ProximityKeyDetector();
// Swipe gesture detector
private GestureDetector mGestureDetector;
private final SwipeTracker mSwipeTracker = new SwipeTracker();
private final int mSwipeThreshold;
private final boolean mDisambiguateSwipe;
// Configuration
private boolean mHintsOnOtherKeys = true;
private boolean mHintsOnLetters = true;
// Drawing
/** Whether the keyboard bitmap needs to be redrawn before it's blitted. **/
private boolean mDrawPending;
/** The dirty region in the keyboard bitmap */
private final Rect mDirtyRect = new Rect();
/** The keyboard bitmap for faster updates */
private Bitmap mBuffer;
/** Notes if the keyboard just changed, so that we could possibly reallocate the mBuffer. */
private boolean mKeyboardChanged;
private Key mInvalidatedKey;
/** The canvas for the above mutable keyboard bitmap */
private Canvas mCanvas;
private final Paint mPaint;
private final Paint mPaintHint;
private final Rect mPadding;
private final Rect mClipRegion = new Rect(0, 0, 0, 0);
private int mViewWidth;
// This map caches key label text height in pixel as value and key label text size as map key.
private final HashMap<Integer, Integer> mTextHeightCache = new HashMap<Integer, Integer>();
// Distance from horizontal center of the key, proportional to key label text height.
private final float KEY_LABEL_VERTICAL_ADJUSTMENT_FACTOR = 0.55f;
private final String KEY_LABEL_HEIGHT_REFERENCE_CHAR = "H";
private final UIHandler mHandler = new UIHandler();
class UIHandler extends Handler {
private static final int MSG_POPUP_PREVIEW = 1;
private static final int MSG_DISMISS_PREVIEW = 2;
private static final int MSG_REPEAT_KEY = 3;
private static final int MSG_LONGPRESS_KEY = 4;
private boolean mInKeyRepeat;
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_POPUP_PREVIEW:
showKey(msg.arg1, (PointerTracker)msg.obj);
break;
case MSG_DISMISS_PREVIEW:
mPreviewPopup.dismiss();
break;
case MSG_REPEAT_KEY: {
final PointerTracker tracker = (PointerTracker)msg.obj;
tracker.repeatKey(msg.arg1);
startKeyRepeatTimer(mKeyRepeatInterval, msg.arg1, tracker);
break;
}
case MSG_LONGPRESS_KEY: {
final PointerTracker tracker = (PointerTracker)msg.obj;
openPopupIfRequired(msg.arg1, tracker);
break;
}
}
}
public void popupPreview(long delay, int keyIndex, PointerTracker tracker) {
removeMessages(MSG_POPUP_PREVIEW);
if (mPreviewPopup.isShowing() && mPreviewText.getVisibility() == VISIBLE) {
// Show right away, if it's already visible and finger is moving around
showKey(keyIndex, tracker);
} else {
sendMessageDelayed(obtainMessage(MSG_POPUP_PREVIEW, keyIndex, 0, tracker),
delay);
}
}
public void cancelPopupPreview() {
removeMessages(MSG_POPUP_PREVIEW);
}
public void dismissPreview(long delay) {
if (mPreviewPopup.isShowing()) {
sendMessageDelayed(obtainMessage(MSG_DISMISS_PREVIEW), delay);
}
}
public void cancelDismissPreview() {
removeMessages(MSG_DISMISS_PREVIEW);
}
public void startKeyRepeatTimer(long delay, int keyIndex, PointerTracker tracker) {
mInKeyRepeat = true;
sendMessageDelayed(obtainMessage(MSG_REPEAT_KEY, keyIndex, 0, tracker), delay);
}
public void cancelKeyRepeatTimer() {
mInKeyRepeat = false;
removeMessages(MSG_REPEAT_KEY);
}
public boolean isInKeyRepeat() {
return mInKeyRepeat;
}
public void startLongPressTimer(long delay, int keyIndex, PointerTracker tracker) {
removeMessages(MSG_LONGPRESS_KEY);
sendMessageDelayed(obtainMessage(MSG_LONGPRESS_KEY, keyIndex, 0, tracker), delay);
}
public void cancelLongPressTimer() {
removeMessages(MSG_LONGPRESS_KEY);
}
public void cancelKeyTimers() {
cancelKeyRepeatTimer();
cancelLongPressTimer();
}
public void cancelAllMessages() {
cancelKeyTimers();
cancelPopupPreview();
cancelDismissPreview();
}
}
static class PointerQueue {
private LinkedList<PointerTracker> mQueue = new LinkedList<PointerTracker>();
public void add(PointerTracker tracker) {
mQueue.add(tracker);
}
public int lastIndexOf(PointerTracker tracker) {
LinkedList<PointerTracker> queue = mQueue;
for (int index = queue.size() - 1; index >= 0; index--) {
PointerTracker t = queue.get(index);
if (t == tracker)
return index;
}
return -1;
}
public void releaseAllPointersOlderThan(PointerTracker tracker, long eventTime) {
LinkedList<PointerTracker> queue = mQueue;
int oldestPos = 0;
for (PointerTracker t = queue.get(oldestPos); t != tracker; t = queue.get(oldestPos)) {
if (t.isModifier()) {
oldestPos++;
} else {
t.onUpEvent(t.getLastX(), t.getLastY(), eventTime);
t.setAlreadyProcessed();
queue.remove(oldestPos);
}
}
}
public void releaseAllPointersExcept(PointerTracker tracker, long eventTime) {
for (PointerTracker t : mQueue) {
if (t == tracker)
continue;
t.onUpEvent(t.getLastX(), t.getLastY(), eventTime);
t.setAlreadyProcessed();
}
mQueue.clear();
if (tracker != null)
mQueue.add(tracker);
}
public void remove(PointerTracker tracker) {
mQueue.remove(tracker);
}
public boolean isInSlidingKeyInput() {
for (final PointerTracker tracker : mQueue) {
if (tracker.isInSlidingKeyInput())
return true;
}
return false;
}
}
public LatinKeyboardBaseView(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.keyboardViewStyle);
}
public LatinKeyboardBaseView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.LatinKeyboardBaseView, defStyle, R.style.LatinKeyboardBaseView);
LayoutInflater inflate =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int previewLayout = 0;
int keyTextSize = 0;
int n = a.getIndexCount();
for (int i = 0; i < n; i++) {
int attr = a.getIndex(i);
switch (attr) {
case R.styleable.LatinKeyboardBaseView_keyBackground:
mKeyBackground = a.getDrawable(attr);
break;
case R.styleable.LatinKeyboardBaseView_keyHysteresisDistance:
mKeyHysteresisDistance = a.getDimensionPixelOffset(attr, 0);
break;
case R.styleable.LatinKeyboardBaseView_verticalCorrection:
mVerticalCorrection = a.getDimensionPixelOffset(attr, 0);
break;
case R.styleable.LatinKeyboardBaseView_keyPreviewLayout:
previewLayout = a.getResourceId(attr, 0);
break;
case R.styleable.LatinKeyboardBaseView_keyPreviewOffset:
mPreviewOffset = a.getDimensionPixelOffset(attr, 0);
break;
case R.styleable.LatinKeyboardBaseView_keyPreviewHeight:
mPreviewHeight = a.getDimensionPixelSize(attr, 80);
break;
case R.styleable.LatinKeyboardBaseView_keyTextSize:
mKeyTextSize = a.getDimensionPixelSize(attr, 18);
break;
case R.styleable.LatinKeyboardBaseView_keyTextColor:
mKeyTextColor = a.getColor(attr, 0xFF000000);
break;
case R.styleable.LatinKeyboardBaseView_keyCursorColor:
mKeyCursorColor = a.getColor(attr, 0xFF000000);
break;
case R.styleable.LatinKeyboardBaseView_labelTextSize:
mLabelTextSize = a.getDimensionPixelSize(attr, 14);
break;
case R.styleable.LatinKeyboardBaseView_popupLayout:
mPopupLayout = a.getResourceId(attr, 0);
break;
case R.styleable.LatinKeyboardBaseView_shadowColor:
mShadowColor = a.getColor(attr, 0);
break;
case R.styleable.LatinKeyboardBaseView_shadowRadius:
mShadowRadius = a.getFloat(attr, 0f);
break;
// TODO: Use Theme (android.R.styleable.Theme_backgroundDimAmount)
case R.styleable.LatinKeyboardBaseView_backgroundDimAmount:
mBackgroundDimAmount = a.getFloat(attr, 0.5f);
break;
//case android.R.styleable.
case R.styleable.LatinKeyboardBaseView_keyTextStyle:
int textStyle = a.getInt(attr, 0);
switch (textStyle) {
case 0:
mKeyTextStyle = Typeface.DEFAULT;
break;
case 1:
mKeyTextStyle = Typeface.DEFAULT_BOLD;
break;
default:
mKeyTextStyle = Typeface.defaultFromStyle(textStyle);
break;
}
break;
case R.styleable.LatinKeyboardBaseView_symbolColorScheme:
mSymbolColorScheme = a.getInt(attr, 0);
break;
}
}
final Resources res = getResources();
mPreviewPopup = new PopupWindow(context);
if (previewLayout != 0) {
mPreviewText = (TextView) inflate.inflate(previewLayout, null);
mPreviewTextSizeLarge = (int) res.getDimension(R.dimen.key_preview_text_size_large);
mPreviewPopup.setContentView(mPreviewText);
mPreviewPopup.setBackgroundDrawable(null);
} else {
mShowPreview = false;
}
mPreviewPopup.setTouchable(false);
mPreviewPopup.setAnimationStyle(R.style.KeyPreviewAnimation);
mDelayBeforePreview = res.getInteger(R.integer.config_delay_before_preview);
mDelayBeforeSpacePreview = res.getInteger(R.integer.config_delay_before_space_preview);
mDelayAfterPreview = res.getInteger(R.integer.config_delay_after_preview);
mMiniKeyboardParent = this;
mMiniKeyboardPopup = new PopupWindow(context);
mMiniKeyboardPopup.setBackgroundDrawable(null);
mMiniKeyboardPopup.setAnimationStyle(R.style.MiniKeyboardAnimation);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setTextAlign(Align.CENTER);
mPaint.setAlpha(255);
mPaintHint = new Paint();
mPaintHint.setAntiAlias(true);
mPaintHint.setTextAlign(Align.RIGHT);
mPaintHint.setAlpha(255);
mPaintHint.setTypeface(Typeface.DEFAULT_BOLD);
mPadding = new Rect(0, 0, 0, 0);
mKeyBackground.getPadding(mPadding);
mSwipeThreshold = (int) (500 * res.getDisplayMetrics().density);
// TODO: Refer frameworks/base/core/res/res/values/config.xml
mDisambiguateSwipe = res.getBoolean(R.bool.config_swipeDisambiguation);
mMiniKeyboardSlideAllowance = res.getDimension(R.dimen.mini_keyboard_slide_allowance);
GestureDetector.SimpleOnGestureListener listener =
new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onFling(MotionEvent me1, MotionEvent me2, float velocityX,
float velocityY) {
final float absX = Math.abs(velocityX);
final float absY = Math.abs(velocityY);
float deltaX = me2.getX() - me1.getX();
float deltaY = me2.getY() - me1.getY();
int travelX = getWidth() / 2; // Half the keyboard width
int travelY = getHeight() / 2; // Half the keyboard height
mSwipeTracker.computeCurrentVelocity(1000);
final float endingVelocityX = mSwipeTracker.getXVelocity();
final float endingVelocityY = mSwipeTracker.getYVelocity();
if (velocityX > mSwipeThreshold && absY < absX && deltaX > travelX) {
if (mDisambiguateSwipe && endingVelocityX >= velocityX / 4) {
swipeRight();
return true;
}
} else if (velocityX < -mSwipeThreshold && absY < absX && deltaX < -travelX) {
if (mDisambiguateSwipe && endingVelocityX <= velocityX / 4) {
swipeLeft();
return true;
}
} else if (velocityY < -mSwipeThreshold && absX < absY && deltaY < -travelY) {
if (mDisambiguateSwipe && endingVelocityY <= velocityY / 4) {
swipeUp();
return true;
}
} else if (velocityY > mSwipeThreshold && absX < absY / 2 && deltaY > travelY) {
if (mDisambiguateSwipe && endingVelocityY >= velocityY / 4) {
swipeDown();
return true;
}
}
return false;
}
};
final boolean ignoreMultitouch = true;
mGestureDetector = new GestureDetector(getContext(), listener, null, ignoreMultitouch);
mGestureDetector.setIsLongpressEnabled(false);
mHasDistinctMultitouch = context.getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT);
mKeyRepeatInterval = res.getInteger(R.integer.config_key_repeat_interval);
}
public void setHintMode(int hintMode) {
//Log.i("PCKeyboard", "set hintMode=" + hintMode);
mHintsOnOtherKeys = (hintMode >= 1);
mHintsOnLetters = (hintMode >= 2);
}
public void setOnKeyboardActionListener(OnKeyboardActionListener listener) {
mKeyboardActionListener = listener;
for (PointerTracker tracker : mPointerTrackers) {
tracker.setOnKeyboardActionListener(listener);
}
}
/**
* Returns the {@link OnKeyboardActionListener} object.
* @return the listener attached to this keyboard
*/
protected OnKeyboardActionListener getOnKeyboardActionListener() {
return mKeyboardActionListener;
}
/**
* Attaches a keyboard to this view. The keyboard can be switched at any time and the
* view will re-layout itself to accommodate the keyboard.
* @see Keyboard
* @see #getKeyboard()
* @param keyboard the keyboard to display in this view
*/
public void setKeyboard(Keyboard keyboard) {
if (mKeyboard != null) {
dismissKeyPreview();
}
// Remove any pending messages, except dismissing preview
mHandler.cancelKeyTimers();
mHandler.cancelPopupPreview();
mKeyboard = keyboard;
LatinImeLogger.onSetKeyboard(keyboard);
mKeys = mKeyDetector.setKeyboard(keyboard, -getPaddingLeft(),
-getPaddingTop() + mVerticalCorrection);
mKeyboardVerticalGap = (int)getResources().getDimension(R.dimen.key_bottom_gap);
for (PointerTracker tracker : mPointerTrackers) {
tracker.setKeyboard(mKeys, mKeyHysteresisDistance);
}
requestLayout();
// Hint to reallocate the buffer if the size changed
mKeyboardChanged = true;
invalidateAllKeys();
computeProximityThreshold(keyboard);
mMiniKeyboardCache.clear();
}
public void setLabelScale(float scale) {
mLabelScale = scale;
}
/**
* Returns the current keyboard being displayed by this view.
* @return the currently attached keyboard
* @see #setKeyboard(Keyboard)
*/
public Keyboard getKeyboard() {
return mKeyboard;
}
/**
* Return whether the device has distinct multi-touch panel.
* @return true if the device has distinct multi-touch panel.
*/
public boolean hasDistinctMultitouch() {
return mHasDistinctMultitouch;
}
/**
* Sets the state of the shift key of the keyboard, if any.
* @param shifted whether or not to enable the state of the shift key
* @return true if the shift key state changed, false if there was no change
*/
public boolean setShifted(boolean shifted) {
if (mKeyboard != null) {
if (mKeyboard.setShifted(shifted)) {
// The whole keyboard probably needs to be redrawn
invalidateAllKeys();
return true;
}
}
return false;
}
/**
* Returns the state of the shift key of the keyboard, if any.
* @return true if the shift is in a pressed state, false otherwise. If there is
* no shift key on the keyboard or there is no keyboard attached, it returns false.
*/
public boolean isShifted() {
if (mKeyboard != null) {
return mKeyboard.isShifted();
}
return false;
}
/**
* Enables or disables the key feedback popup. This is a popup that shows a magnified
* version of the depressed key. By default the preview is enabled.
* @param previewEnabled whether or not to enable the key feedback popup
* @see #isPreviewEnabled()
*/
public void setPreviewEnabled(boolean previewEnabled) {
mShowPreview = previewEnabled;
}
/**
* Returns the enabled state of the key feedback popup.
* @return whether or not the key feedback popup is enabled
* @see #setPreviewEnabled(boolean)
*/
public boolean isPreviewEnabled() {
return mShowPreview;
}
public int getSymbolColorScheme() {
return mSymbolColorScheme;
}
public void setPopupParent(View v) {
mMiniKeyboardParent = v;
}
public void setPopupOffset(int x, int y) {
mPopupPreviewOffsetX = x;
mPopupPreviewOffsetY = y;
mPreviewPopup.dismiss();
}
/**
* When enabled, calls to {@link OnKeyboardActionListener#onKey} will include key
* codes for adjacent keys. When disabled, only the primary key code will be
* reported.
* @param enabled whether or not the proximity correction is enabled
*/
public void setProximityCorrectionEnabled(boolean enabled) {
mKeyDetector.setProximityCorrectionEnabled(enabled);
}
/**
* Returns true if proximity correction is enabled.
*/
public boolean isProximityCorrectionEnabled() {
return mKeyDetector.isProximityCorrectionEnabled();
}
protected CharSequence adjustCase(CharSequence label) {
if (mKeyboard.isShifted() && label != null && label.length() < 3
&& Character.isLowerCase(label.charAt(0))) {
label = label.toString().toUpperCase();
}
return label;
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// Round up a little
if (mKeyboard == null) {
setMeasuredDimension(
getPaddingLeft() + getPaddingRight(), getPaddingTop() + getPaddingBottom());
} else {
int width = mKeyboard.getMinWidth() + getPaddingLeft() + getPaddingRight();
if (MeasureSpec.getSize(widthMeasureSpec) < width + 10) {
width = MeasureSpec.getSize(widthMeasureSpec);
}
setMeasuredDimension(
width, mKeyboard.getHeight() + getPaddingTop() + getPaddingBottom());
}
}
/**
* Compute the average distance between adjacent keys (horizontally and vertically)
* and square it to get the proximity threshold. We use a square here and in computing
* the touch distance from a key's center to avoid taking a square root.
* @param keyboard
*/
private void computeProximityThreshold(Keyboard keyboard) {
if (keyboard == null) return;
final Key[] keys = mKeys;
if (keys == null) return;
int length = keys.length;
int dimensionSum = 0;
for (int i = 0; i < length; i++) {
Key key = keys[i];
dimensionSum += Math.min(key.width, key.height + mKeyboardVerticalGap) + key.gap;
}
if (dimensionSum < 0 || length == 0) return;
mKeyDetector.setProximityThreshold((int) (dimensionSum * 1.4f / length));
}
@Override
public void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mViewWidth = w;
// Release the buffer, if any and it will be reallocated on the next draw
mBuffer = null;
}
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mDrawPending || mBuffer == null || mKeyboardChanged) {
onBufferDraw();
}
canvas.drawBitmap(mBuffer, 0, 0, null);
}
private int getLabelHeight(Paint paint, int labelSize) {
Integer labelHeightValue = mTextHeightCache.get(labelSize);
if (labelHeightValue != null) {
return labelHeightValue;
} else {
Rect textBounds = new Rect();
paint.getTextBounds(KEY_LABEL_HEIGHT_REFERENCE_CHAR, 0, 1, textBounds);
int labelHeight = textBounds.height();
mTextHeightCache.put(labelSize, labelHeight);
return labelHeight;
}
}
private void onBufferDraw() {
if (mBuffer == null || mKeyboardChanged) {
mKeyboard.setKeyboardWidth(mViewWidth);
if (mBuffer == null || mKeyboardChanged &&
(mBuffer.getWidth() != getWidth() || mBuffer.getHeight() != getHeight())) {
// Make sure our bitmap is at least 1x1
final int width = Math.max(1, getWidth());
final int height = Math.max(1, getHeight());
mBuffer = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBuffer);
}
invalidateAllKeys();
mKeyboardChanged = false;
}
final Canvas canvas = mCanvas;
canvas.clipRect(mDirtyRect, Op.REPLACE);
if (mKeyboard == null) return;
final Paint paint = mPaint;
final Paint paintHint = mPaintHint;
final Drawable keyBackground = mKeyBackground;
final Rect clipRegion = mClipRegion;
final Rect padding = mPadding;
final int kbdPaddingLeft = getPaddingLeft();
final int kbdPaddingTop = getPaddingTop();
final Key[] keys = mKeys;
final Key invalidKey = mInvalidatedKey;
boolean drawSingleKey = false;
if (invalidKey != null && canvas.getClipBounds(clipRegion)) {
// TODO we should use Rect.inset and Rect.contains here.
// Is clipRegion completely contained within the invalidated key?
if (invalidKey.x + kbdPaddingLeft - 1 <= clipRegion.left &&
invalidKey.y + kbdPaddingTop - 1 <= clipRegion.top &&
invalidKey.x + invalidKey.width + kbdPaddingLeft + 1 >= clipRegion.right &&
invalidKey.y + invalidKey.height + kbdPaddingTop + 1 >= clipRegion.bottom) {
drawSingleKey = true;
}
}
canvas.drawColor(0x00000000, PorterDuff.Mode.CLEAR);
final int keyCount = keys.length;
for (int i = 0; i < keyCount; i++) {
final Key key = keys[i];
if (drawSingleKey && invalidKey != key) {
continue;
}
paint.setColor(key.isCursor ? mKeyCursorColor : mKeyTextColor);
int[] drawableState = key.getCurrentDrawableState();
keyBackground.setState(drawableState);
// Switch the character to uppercase if shift is pressed
String label = key.label == null? null : adjustCase(key.label).toString();
float yscale = 1.0f;
final Rect bounds = keyBackground.getBounds();
if (key.width != bounds.right || key.height != bounds.bottom) {
int minHeight = keyBackground.getMinimumHeight();
if (minHeight > key.height) {
yscale = (float) key.height / minHeight;
keyBackground.setBounds(0, 0, key.width, minHeight);
} else {
keyBackground.setBounds(0, 0, key.width, key.height);
}
}
canvas.translate(key.x + kbdPaddingLeft, key.y + kbdPaddingTop);
if (yscale != 1.0f) {
canvas.save();
canvas.scale(1.0f, yscale);
}
keyBackground.draw(canvas);
if (yscale != 1.0f) canvas.restore();
boolean shouldDrawIcon = true;
if (label != null) {
// For characters, use large font. For labels like "Done", use small font.
final int labelSize;
if (label.length() > 1 && key.codes.length < 2) {
//Log.i(TAG, "mLabelTextSize=" + mLabelTextSize + " mLabelScale=" + mLabelScale);
labelSize = (int)(mLabelTextSize * mLabelScale);
paint.setTypeface(Typeface.DEFAULT);
} else {
labelSize = (int)(mKeyTextSize * mLabelScale);
paint.setTypeface(mKeyTextStyle);
- paint.setFakeBoldText(key.isCursor);
}
+ paint.setFakeBoldText(key.isCursor);
paint.setTextSize(labelSize);
final int labelHeight = getLabelHeight(paint, labelSize);
// Draw a drop shadow for the text
paint.setShadowLayer(mShadowRadius, 0, 0, mShadowColor);
// Draw hint label (if present) behind the main key
char hint = getHintLabel(key);
if (hint != 0) {
int hintTextSize = (int)(mKeyTextSize * 0.6 * mLabelScale);
paintHint.setTextSize(hintTextSize);
final int hintLabelHeight = getLabelHeight(paintHint, hintTextSize);
canvas.drawText(Character.toString(hint),
key.width - padding.right,
padding.top + hintLabelHeight * 11/10,
paintHint);
}
// Draw main key label
final int centerX = (key.width + padding.left - padding.right) / 2;
final int centerY = (key.height + padding.top - padding.bottom) / 2;
final float baseline = centerY
+ labelHeight * KEY_LABEL_VERTICAL_ADJUSTMENT_FACTOR;
canvas.drawText(label, centerX, baseline, paint);
if (key.isCursor) {
// poor man's bold
canvas.drawText(label, centerX+0.5f, baseline, paint);
canvas.drawText(label, centerX-0.5f, baseline, paint);
canvas.drawText(label, centerX, baseline+0.5f, paint);
canvas.drawText(label, centerX, baseline-0.5f, paint);
}
// Turn off drop shadow
paint.setShadowLayer(0, 0, 0, 0);
// Usually don't draw icon if label is not null, but we draw icon for the number
// hint and popup hint.
shouldDrawIcon = shouldDrawLabelAndIcon(key);
}
if (key.icon != null && shouldDrawIcon) {
// Special handing for the upper-right number hint icons
final int drawableWidth;
final int drawableHeight;
final int drawableX;
final int drawableY;
if (shouldDrawIconFully(key)) {
drawableWidth = key.width;
drawableHeight = key.height;
drawableX = 0;
drawableY = NUMBER_HINT_VERTICAL_ADJUSTMENT_PIXEL;
} else {
drawableWidth = key.icon.getIntrinsicWidth();
drawableHeight = key.icon.getIntrinsicHeight();
drawableX = (key.width + padding.left - padding.right - drawableWidth) / 2;
drawableY = (key.height + padding.top - padding.bottom - drawableHeight) / 2;
}
canvas.translate(drawableX, drawableY);
key.icon.setBounds(0, 0, drawableWidth, drawableHeight);
key.icon.draw(canvas);
canvas.translate(-drawableX, -drawableY);
}
canvas.translate(-key.x - kbdPaddingLeft, -key.y - kbdPaddingTop);
}
mInvalidatedKey = null;
// Overlay a dark rectangle to dim the keyboard
if (mMiniKeyboard != null) {
paint.setColor((int) (mBackgroundDimAmount * 0xFF) << 24);
canvas.drawRect(0, 0, getWidth(), getHeight(), paint);
}
if (DEBUG) {
if (mShowTouchPoints) {
for (PointerTracker tracker : mPointerTrackers) {
int startX = tracker.getStartX();
int startY = tracker.getStartY();
int lastX = tracker.getLastX();
int lastY = tracker.getLastY();
paint.setAlpha(128);
paint.setColor(0xFFFF0000);
canvas.drawCircle(startX, startY, 3, paint);
canvas.drawLine(startX, startY, lastX, lastY, paint);
paint.setColor(0xFF0000FF);
canvas.drawCircle(lastX, lastY, 3, paint);
paint.setColor(0xFF00FF00);
canvas.drawCircle((startX + lastX) / 2, (startY + lastY) / 2, 2, paint);
}
}
}
mDrawPending = false;
mDirtyRect.setEmpty();
}
// TODO: clean up this method.
private void dismissKeyPreview() {
for (PointerTracker tracker : mPointerTrackers)
tracker.updateKey(NOT_A_KEY);
showPreview(NOT_A_KEY, null);
}
public void showPreview(int keyIndex, PointerTracker tracker) {
int oldKeyIndex = mOldPreviewKeyIndex;
mOldPreviewKeyIndex = keyIndex;
final boolean isLanguageSwitchEnabled = (mKeyboard instanceof LatinKeyboard)
&& ((LatinKeyboard)mKeyboard).isLanguageSwitchEnabled();
// We should re-draw popup preview when 1) we need to hide the preview, 2) we will show
// the space key preview and 3) pointer moves off the space key to other letter key, we
// should hide the preview of the previous key.
final boolean hidePreviewOrShowSpaceKeyPreview = (tracker == null)
|| tracker.isSpaceKey(keyIndex) || tracker.isSpaceKey(oldKeyIndex);
// If key changed and preview is on or the key is space (language switch is enabled)
if (oldKeyIndex != keyIndex
&& (mShowPreview
|| (hidePreviewOrShowSpaceKeyPreview && isLanguageSwitchEnabled))) {
if (keyIndex == NOT_A_KEY) {
mHandler.cancelPopupPreview();
mHandler.dismissPreview(mDelayAfterPreview);
} else if (tracker != null) {
int delay = mShowPreview ? mDelayBeforePreview : mDelayBeforeSpacePreview;
mHandler.popupPreview(delay, keyIndex, tracker);
}
}
}
private void showKey(final int keyIndex, PointerTracker tracker) {
Key key = tracker.getKey(keyIndex);
if (key == null)
return;
// Should not draw hint icon in key preview
if (key.icon != null && !shouldDrawLabelAndIcon(key)) {
mPreviewText.setCompoundDrawables(null, null, null,
key.iconPreview != null ? key.iconPreview : key.icon);
mPreviewText.setText(null);
} else {
mPreviewText.setCompoundDrawables(null, null, null, null);
mPreviewText.setText(adjustCase(tracker.getPreviewText(key)));
if (key.label.length() > 1 && key.codes.length < 2) {
mPreviewText.setTextSize(TypedValue.COMPLEX_UNIT_PX, mKeyTextSize);
mPreviewText.setTypeface(Typeface.DEFAULT_BOLD);
} else {
mPreviewText.setTextSize(TypedValue.COMPLEX_UNIT_PX, mPreviewTextSizeLarge);
mPreviewText.setTypeface(mKeyTextStyle);
}
}
mPreviewText.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int popupWidth = Math.max(mPreviewText.getMeasuredWidth(), key.width
+ mPreviewText.getPaddingLeft() + mPreviewText.getPaddingRight());
final int popupHeight = mPreviewHeight;
LayoutParams lp = mPreviewText.getLayoutParams();
if (lp != null) {
lp.width = popupWidth;
lp.height = popupHeight;
}
int popupPreviewX = key.x - (popupWidth - key.width) / 2;
int popupPreviewY = key.y - popupHeight + mPreviewOffset;
mHandler.cancelDismissPreview();
if (mOffsetInWindow == null) {
mOffsetInWindow = new int[2];
getLocationInWindow(mOffsetInWindow);
mOffsetInWindow[0] += mPopupPreviewOffsetX; // Offset may be zero
mOffsetInWindow[1] += mPopupPreviewOffsetY; // Offset may be zero
int[] windowLocation = new int[2];
getLocationOnScreen(windowLocation);
mWindowY = windowLocation[1];
}
// Set the preview background state
mPreviewText.getBackground().setState(
key.popupResId != 0 ? LONG_PRESSABLE_STATE_SET : EMPTY_STATE_SET);
popupPreviewX += mOffsetInWindow[0];
popupPreviewY += mOffsetInWindow[1];
// If the popup cannot be shown above the key, put it on the side
if (popupPreviewY + mWindowY < 0) {
// If the key you're pressing is on the left side of the keyboard, show the popup on
// the right, offset by enough to see at least one key to the left/right.
if (key.x + key.width <= getWidth() / 2) {
popupPreviewX += (int) (key.width * 2.5);
} else {
popupPreviewX -= (int) (key.width * 2.5);
}
popupPreviewY += popupHeight;
}
if (mPreviewPopup.isShowing()) {
mPreviewPopup.update(popupPreviewX, popupPreviewY, popupWidth, popupHeight);
} else {
mPreviewPopup.setWidth(popupWidth);
mPreviewPopup.setHeight(popupHeight);
mPreviewPopup.showAtLocation(mMiniKeyboardParent, Gravity.NO_GRAVITY,
popupPreviewX, popupPreviewY);
}
// Record popup preview position to display mini-keyboard later at the same positon
mPopupPreviewDisplayedY = popupPreviewY;
mPreviewText.setVisibility(VISIBLE);
}
/**
* Requests a redraw of the entire keyboard. Calling {@link #invalidate} is not sufficient
* because the keyboard renders the keys to an off-screen buffer and an invalidate() only
* draws the cached buffer.
* @see #invalidateKey(Key)
*/
public void invalidateAllKeys() {
mDirtyRect.union(0, 0, getWidth(), getHeight());
mDrawPending = true;
invalidate();
}
/**
* Invalidates a key so that it will be redrawn on the next repaint. Use this method if only
* one key is changing it's content. Any changes that affect the position or size of the key
* may not be honored.
* @param key key in the attached {@link Keyboard}.
* @see #invalidateAllKeys
*/
public void invalidateKey(Key key) {
if (key == null)
return;
mInvalidatedKey = key;
// TODO we should clean up this and record key's region to use in onBufferDraw.
mDirtyRect.union(key.x + getPaddingLeft(), key.y + getPaddingTop(),
key.x + key.width + getPaddingLeft(), key.y + key.height + getPaddingTop());
onBufferDraw();
invalidate(key.x + getPaddingLeft(), key.y + getPaddingTop(),
key.x + key.width + getPaddingLeft(), key.y + key.height + getPaddingTop());
}
private boolean openPopupIfRequired(int keyIndex, PointerTracker tracker) {
// Check if we have a popup layout specified first.
if (mPopupLayout == 0) {
return false;
}
Key popupKey = tracker.getKey(keyIndex);
if (popupKey == null)
return false;
boolean result = onLongPress(popupKey);
if (result) {
dismissKeyPreview();
mMiniKeyboardTrackerId = tracker.mPointerId;
// Mark this tracker "already processed" and remove it from the pointer queue
tracker.setAlreadyProcessed();
mPointerQueue.remove(tracker);
}
return result;
}
private View inflateMiniKeyboardContainer(Key popupKey) {
int popupKeyboardId = popupKey.popupResId;
LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
View container = inflater.inflate(mPopupLayout, null);
if (container == null)
throw new NullPointerException();
LatinKeyboardBaseView miniKeyboard =
(LatinKeyboardBaseView)container.findViewById(R.id.LatinKeyboardBaseView);
miniKeyboard.setOnKeyboardActionListener(new OnKeyboardActionListener() {
public void onKey(int primaryCode, int[] keyCodes, int x, int y) {
mKeyboardActionListener.onKey(primaryCode, keyCodes, x, y);
dismissPopupKeyboard();
}
public void onText(CharSequence text) {
mKeyboardActionListener.onText(text);
dismissPopupKeyboard();
}
public void onCancel() {
mKeyboardActionListener.onCancel();
dismissPopupKeyboard();
}
public void swipeLeft() {
}
public void swipeRight() {
}
public void swipeUp() {
}
public void swipeDown() {
}
public void onPress(int primaryCode) {
mKeyboardActionListener.onPress(primaryCode);
}
public void onRelease(int primaryCode) {
mKeyboardActionListener.onRelease(primaryCode);
}
});
// Override default ProximityKeyDetector.
miniKeyboard.mKeyDetector = new MiniKeyboardKeyDetector(mMiniKeyboardSlideAllowance);
// Remove gesture detector on mini-keyboard
miniKeyboard.mGestureDetector = null;
Keyboard keyboard;
CharSequence popupChars = popupKey.popupCharacters;
if (popupChars != null) {
keyboard = new Keyboard(getContext(), popupKeyboardId, popupChars,
-1, getPaddingLeft() + getPaddingRight());
} else {
keyboard = new Keyboard(getContext(), popupKeyboardId);
}
miniKeyboard.setKeyboard(keyboard);
miniKeyboard.setPopupParent(this);
container.measure(MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.AT_MOST),
MeasureSpec.makeMeasureSpec(getHeight(), MeasureSpec.AT_MOST));
return container;
}
private static boolean isOneRowKeys(List<Key> keys) {
if (keys.size() == 0) return false;
final int edgeFlags = keys.get(0).edgeFlags;
// HACK: The first key of mini keyboard which was inflated from xml and has multiple rows,
// does not have both top and bottom edge flags on at the same time. On the other hand,
// the first key of mini keyboard that was created with popupCharacters must have both top
// and bottom edge flags on.
// When you want to use one row mini-keyboard from xml file, make sure that the row has
// both top and bottom edge flags set.
return (edgeFlags & Keyboard.EDGE_TOP) != 0 && (edgeFlags & Keyboard.EDGE_BOTTOM) != 0;
}
/**
* Called when a key is long pressed. By default this will open any popup keyboard associated
* with this key through the attributes popupLayout and popupCharacters.
* @param popupKey the key that was long pressed
* @return true if the long press is handled, false otherwise. Subclasses should call the
* method on the base class if the subclass doesn't wish to handle the call.
*/
protected boolean onLongPress(Key popupKey) {
// TODO if popupKey.popupCharacters has only one letter, send it as key without opening
// mini keyboard.
if (popupKey.popupResId == 0)
return false;
View container = mMiniKeyboardCache.get(popupKey);
if (container == null) {
container = inflateMiniKeyboardContainer(popupKey);
mMiniKeyboardCache.put(popupKey, container);
}
mMiniKeyboard = (LatinKeyboardBaseView)container.findViewById(R.id.LatinKeyboardBaseView);
mMiniKeyboard.setLabelScale(mLabelScale);
if (mWindowOffset == null) {
mWindowOffset = new int[2];
getLocationInWindow(mWindowOffset);
}
// Get width of a key in the mini popup keyboard = "miniKeyWidth".
// On the other hand, "popupKey.width" is width of the pressed key on the main keyboard.
// We adjust the position of mini popup keyboard with the edge key in it:
// a) When we have the leftmost key in popup keyboard directly above the pressed key
// Right edges of both keys should be aligned for consistent default selection
// b) When we have the rightmost key in popup keyboard directly above the pressed key
// Left edges of both keys should be aligned for consistent default selection
final List<Key> miniKeys = mMiniKeyboard.getKeyboard().getKeys();
final int miniKeyWidth = miniKeys.size() > 0 ? miniKeys.get(0).width : 0;
int popupX = popupKey.x + mWindowOffset[0];
popupX += getPaddingLeft();
if (shouldAlignLeftmost(popupKey)) {
popupX += popupKey.width - miniKeyWidth; // adjustment for a) described above
popupX -= container.getPaddingLeft();
} else {
popupX += miniKeyWidth; // adjustment for b) described above
popupX -= container.getMeasuredWidth();
popupX += container.getPaddingRight();
}
int popupY = popupKey.y + mWindowOffset[1];
popupY += getPaddingTop();
popupY -= container.getMeasuredHeight();
popupY += container.getPaddingBottom();
final int x = popupX;
final int y = mShowPreview && isOneRowKeys(miniKeys) ? mPopupPreviewDisplayedY : popupY;
int adjustedX = x;
if (x < 0) {
adjustedX = 0;
} else if (x > (getMeasuredWidth() - container.getMeasuredWidth())) {
adjustedX = getMeasuredWidth() - container.getMeasuredWidth();
}
mMiniKeyboardOriginX = adjustedX + container.getPaddingLeft() - mWindowOffset[0];
mMiniKeyboardOriginY = y + container.getPaddingTop() - mWindowOffset[1];
mMiniKeyboard.setPopupOffset(adjustedX, y);
mMiniKeyboard.setShifted(isShifted());
// Mini keyboard needs no pop-up key preview displayed.
mMiniKeyboard.setPreviewEnabled(false);
mMiniKeyboardPopup.setContentView(container);
mMiniKeyboardPopup.setWidth(container.getMeasuredWidth());
mMiniKeyboardPopup.setHeight(container.getMeasuredHeight());
mMiniKeyboardPopup.showAtLocation(this, Gravity.NO_GRAVITY, x, y);
// Inject down event on the key to mini keyboard.
long eventTime = SystemClock.uptimeMillis();
mMiniKeyboardPopupTime = eventTime;
MotionEvent downEvent = generateMiniKeyboardMotionEvent(MotionEvent.ACTION_DOWN, popupKey.x
+ popupKey.width / 2, popupKey.y + popupKey.height / 2, eventTime);
mMiniKeyboard.onTouchEvent(downEvent);
downEvent.recycle();
invalidateAllKeys();
return true;
}
private boolean shouldDrawIconFully(Key key) {
return isNumberAtEdgeOfPopupChars(key) || isLatinF1Key(key)
|| LatinKeyboard.hasPuncOrSmileysPopup(key);
}
private boolean shouldDrawLabelAndIcon(Key key) {
// isNumberAtEdgeOfPopupChars(key) ||
return isNonMicLatinF1Key(key)
|| LatinKeyboard.hasPuncOrSmileysPopup(key);
}
private boolean shouldAlignLeftmost(Key key) {
return !key.popupReversed;
}
private char getHintLabel(Key key) {
CharSequence popupChars = key.popupCharacters;
if (key.modifier || popupChars == null || popupChars.length() == 0) {
return 0;
}
// Must keep this algorithm in sync with onLongPress() method for consistency!
boolean alignLeftmost = shouldAlignLeftmost(key);
int popupLen = popupChars.length();
int pos = alignLeftmost ? 0 : popupLen - 1;
// Use the character at this position as the label?
char label = popupChars.charAt(pos);
boolean popupIsDigit = Character.isDigit(label);
boolean popupIs7BitAscii = label >= 32 && label < 127;
boolean letterKey = isLetterKey(key);
if (letterKey) {
// Always show number hints on 4-row keyboard, and show
// hints if the user wants some hints and the popup is an
// Ascii char such as '@' or '?'. Otherwise check the hint mode setting.
boolean show = false;
if (popupIsDigit) show = true;
if (mHintsOnLetters) show = true;
if (mHintsOnOtherKeys && popupIs7BitAscii) show = true;
if (!show) return 0;
} else {
if (!mHintsOnOtherKeys) return 0;
}
return label;
}
private boolean isLetterKey(Key key) {
if (key.label == null) return false;
if (key.label.length() != 1) return false;
return Character.isLetter(key.label.charAt(0));
}
private boolean isLatinF1Key(Key key) {
return (mKeyboard instanceof LatinKeyboard) && ((LatinKeyboard)mKeyboard).isF1Key(key);
}
private boolean isNonMicLatinF1Key(Key key) {
return isLatinF1Key(key) && key.label != null;
}
private static boolean isNumberAtEdgeOfPopupChars(Key key) {
return isNumberAtLeftmostPopupChar(key) || isNumberAtRightmostPopupChar(key);
}
/* package */ static boolean isNumberAtLeftmostPopupChar(Key key) {
if (key.popupCharacters != null && key.popupCharacters.length() > 0
&& isAsciiDigit(key.popupCharacters.charAt(0))) {
return true;
}
return false;
}
/* package */ static boolean isNumberAtRightmostPopupChar(Key key) {
if (key.popupCharacters != null && key.popupCharacters.length() > 0
&& isAsciiDigit(key.popupCharacters.charAt(key.popupCharacters.length() - 1))) {
return true;
}
return false;
}
private static boolean isAsciiDigit(char c) {
return (c < 0x80) && Character.isDigit(c);
}
private MotionEvent generateMiniKeyboardMotionEvent(int action, int x, int y, long eventTime) {
return MotionEvent.obtain(mMiniKeyboardPopupTime, eventTime, action,
x - mMiniKeyboardOriginX, y - mMiniKeyboardOriginY, 0);
}
private PointerTracker getPointerTracker(final int id) {
final ArrayList<PointerTracker> pointers = mPointerTrackers;
final Key[] keys = mKeys;
final OnKeyboardActionListener listener = mKeyboardActionListener;
// Create pointer trackers until we can get 'id+1'-th tracker, if needed.
for (int i = pointers.size(); i <= id; i++) {
final PointerTracker tracker =
new PointerTracker(i, mHandler, mKeyDetector, this, getResources());
if (keys != null)
tracker.setKeyboard(keys, mKeyHysteresisDistance);
if (listener != null)
tracker.setOnKeyboardActionListener(listener);
pointers.add(tracker);
}
return pointers.get(id);
}
public boolean isInSlidingKeyInput() {
if (mMiniKeyboard != null) {
return mMiniKeyboard.isInSlidingKeyInput();
} else {
return mPointerQueue.isInSlidingKeyInput();
}
}
public int getPointerCount() {
return mOldPointerCount;
}
@Override
public boolean onTouchEvent(MotionEvent me) {
final int action = me.getActionMasked();
final int pointerCount = me.getPointerCount();
final int oldPointerCount = mOldPointerCount;
mOldPointerCount = pointerCount;
// TODO: cleanup this code into a multi-touch to single-touch event converter class?
// If the device does not have distinct multi-touch support panel, ignore all multi-touch
// events except a transition from/to single-touch.
if (!mHasDistinctMultitouch && pointerCount > 1 && oldPointerCount > 1) {
return true;
}
// Track the last few movements to look for spurious swipes.
mSwipeTracker.addMovement(me);
// Gesture detector must be enabled only when mini-keyboard is not on the screen.
if (mMiniKeyboard == null
&& mGestureDetector != null && mGestureDetector.onTouchEvent(me)) {
dismissKeyPreview();
mHandler.cancelKeyTimers();
return true;
}
final long eventTime = me.getEventTime();
final int index = me.getActionIndex();
final int id = me.getPointerId(index);
final int x = (int)me.getX(index);
final int y = (int)me.getY(index);
// Needs to be called after the gesture detector gets a turn, as it may have
// displayed the mini keyboard
if (mMiniKeyboard != null) {
final int miniKeyboardPointerIndex = me.findPointerIndex(mMiniKeyboardTrackerId);
if (miniKeyboardPointerIndex >= 0 && miniKeyboardPointerIndex < pointerCount) {
final int miniKeyboardX = (int)me.getX(miniKeyboardPointerIndex);
final int miniKeyboardY = (int)me.getY(miniKeyboardPointerIndex);
MotionEvent translated = generateMiniKeyboardMotionEvent(action,
miniKeyboardX, miniKeyboardY, eventTime);
mMiniKeyboard.onTouchEvent(translated);
translated.recycle();
}
return true;
}
if (mHandler.isInKeyRepeat()) {
// It will keep being in the key repeating mode while the key is being pressed.
if (action == MotionEvent.ACTION_MOVE) {
return true;
}
final PointerTracker tracker = getPointerTracker(id);
// Key repeating timer will be canceled if 2 or more keys are in action, and current
// event (UP or DOWN) is non-modifier key.
if (pointerCount > 1 && !tracker.isModifier()) {
mHandler.cancelKeyRepeatTimer();
}
// Up event will pass through.
}
// TODO: cleanup this code into a multi-touch to single-touch event converter class?
// Translate mutli-touch event to single-touch events on the device that has no distinct
// multi-touch panel.
if (!mHasDistinctMultitouch) {
// Use only main (id=0) pointer tracker.
PointerTracker tracker = getPointerTracker(0);
if (pointerCount == 1 && oldPointerCount == 2) {
// Multi-touch to single touch transition.
// Send a down event for the latest pointer.
tracker.onDownEvent(x, y, eventTime);
} else if (pointerCount == 2 && oldPointerCount == 1) {
// Single-touch to multi-touch transition.
// Send an up event for the last pointer.
tracker.onUpEvent(tracker.getLastX(), tracker.getLastY(), eventTime);
} else if (pointerCount == 1 && oldPointerCount == 1) {
tracker.onTouchEvent(action, x, y, eventTime);
} else {
Log.w(TAG, "Unknown touch panel behavior: pointer count is " + pointerCount
+ " (old " + oldPointerCount + ")");
}
return true;
}
if (action == MotionEvent.ACTION_MOVE) {
for (int i = 0; i < pointerCount; i++) {
PointerTracker tracker = getPointerTracker(me.getPointerId(i));
tracker.onMoveEvent((int)me.getX(i), (int)me.getY(i), eventTime);
}
} else {
PointerTracker tracker = getPointerTracker(id);
switch (action) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_POINTER_DOWN:
onDownEvent(tracker, x, y, eventTime);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP:
onUpEvent(tracker, x, y, eventTime);
break;
case MotionEvent.ACTION_CANCEL:
onCancelEvent(tracker, x, y, eventTime);
break;
}
}
return true;
}
private void onDownEvent(PointerTracker tracker, int x, int y, long eventTime) {
if (tracker.isOnModifierKey(x, y)) {
// Before processing a down event of modifier key, all pointers already being tracked
// should be released.
mPointerQueue.releaseAllPointersExcept(null, eventTime);
}
tracker.onDownEvent(x, y, eventTime);
mPointerQueue.add(tracker);
}
private void onUpEvent(PointerTracker tracker, int x, int y, long eventTime) {
if (tracker.isModifier()) {
// Before processing an up event of modifier key, all pointers already being tracked
// should be released.
mPointerQueue.releaseAllPointersExcept(tracker, eventTime);
} else {
int index = mPointerQueue.lastIndexOf(tracker);
if (index >= 0) {
mPointerQueue.releaseAllPointersOlderThan(tracker, eventTime);
} else {
Log.w(TAG, "onUpEvent: corresponding down event not found for pointer "
+ tracker.mPointerId);
}
}
tracker.onUpEvent(x, y, eventTime);
mPointerQueue.remove(tracker);
}
private void onCancelEvent(PointerTracker tracker, int x, int y, long eventTime) {
tracker.onCancelEvent(x, y, eventTime);
mPointerQueue.remove(tracker);
}
protected void swipeRight() {
mKeyboardActionListener.swipeRight();
}
protected void swipeLeft() {
mKeyboardActionListener.swipeLeft();
}
protected void swipeUp() {
mKeyboardActionListener.swipeUp();
}
protected void swipeDown() {
mKeyboardActionListener.swipeDown();
}
public void closing() {
mPreviewPopup.dismiss();
mHandler.cancelAllMessages();
dismissPopupKeyboard();
mBuffer = null;
mCanvas = null;
mMiniKeyboardCache.clear();
}
@Override
public void onDetachedFromWindow() {
super.onDetachedFromWindow();
closing();
}
private void dismissPopupKeyboard() {
if (mMiniKeyboardPopup.isShowing()) {
mMiniKeyboardPopup.dismiss();
mMiniKeyboard = null;
mMiniKeyboardOriginX = 0;
mMiniKeyboardOriginY = 0;
invalidateAllKeys();
}
}
public boolean handleBack() {
if (mMiniKeyboardPopup.isShowing()) {
dismissPopupKeyboard();
return true;
}
return false;
}
}
| false | true | private void onBufferDraw() {
if (mBuffer == null || mKeyboardChanged) {
mKeyboard.setKeyboardWidth(mViewWidth);
if (mBuffer == null || mKeyboardChanged &&
(mBuffer.getWidth() != getWidth() || mBuffer.getHeight() != getHeight())) {
// Make sure our bitmap is at least 1x1
final int width = Math.max(1, getWidth());
final int height = Math.max(1, getHeight());
mBuffer = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBuffer);
}
invalidateAllKeys();
mKeyboardChanged = false;
}
final Canvas canvas = mCanvas;
canvas.clipRect(mDirtyRect, Op.REPLACE);
if (mKeyboard == null) return;
final Paint paint = mPaint;
final Paint paintHint = mPaintHint;
final Drawable keyBackground = mKeyBackground;
final Rect clipRegion = mClipRegion;
final Rect padding = mPadding;
final int kbdPaddingLeft = getPaddingLeft();
final int kbdPaddingTop = getPaddingTop();
final Key[] keys = mKeys;
final Key invalidKey = mInvalidatedKey;
boolean drawSingleKey = false;
if (invalidKey != null && canvas.getClipBounds(clipRegion)) {
// TODO we should use Rect.inset and Rect.contains here.
// Is clipRegion completely contained within the invalidated key?
if (invalidKey.x + kbdPaddingLeft - 1 <= clipRegion.left &&
invalidKey.y + kbdPaddingTop - 1 <= clipRegion.top &&
invalidKey.x + invalidKey.width + kbdPaddingLeft + 1 >= clipRegion.right &&
invalidKey.y + invalidKey.height + kbdPaddingTop + 1 >= clipRegion.bottom) {
drawSingleKey = true;
}
}
canvas.drawColor(0x00000000, PorterDuff.Mode.CLEAR);
final int keyCount = keys.length;
for (int i = 0; i < keyCount; i++) {
final Key key = keys[i];
if (drawSingleKey && invalidKey != key) {
continue;
}
paint.setColor(key.isCursor ? mKeyCursorColor : mKeyTextColor);
int[] drawableState = key.getCurrentDrawableState();
keyBackground.setState(drawableState);
// Switch the character to uppercase if shift is pressed
String label = key.label == null? null : adjustCase(key.label).toString();
float yscale = 1.0f;
final Rect bounds = keyBackground.getBounds();
if (key.width != bounds.right || key.height != bounds.bottom) {
int minHeight = keyBackground.getMinimumHeight();
if (minHeight > key.height) {
yscale = (float) key.height / minHeight;
keyBackground.setBounds(0, 0, key.width, minHeight);
} else {
keyBackground.setBounds(0, 0, key.width, key.height);
}
}
canvas.translate(key.x + kbdPaddingLeft, key.y + kbdPaddingTop);
if (yscale != 1.0f) {
canvas.save();
canvas.scale(1.0f, yscale);
}
keyBackground.draw(canvas);
if (yscale != 1.0f) canvas.restore();
boolean shouldDrawIcon = true;
if (label != null) {
// For characters, use large font. For labels like "Done", use small font.
final int labelSize;
if (label.length() > 1 && key.codes.length < 2) {
//Log.i(TAG, "mLabelTextSize=" + mLabelTextSize + " mLabelScale=" + mLabelScale);
labelSize = (int)(mLabelTextSize * mLabelScale);
paint.setTypeface(Typeface.DEFAULT);
} else {
labelSize = (int)(mKeyTextSize * mLabelScale);
paint.setTypeface(mKeyTextStyle);
paint.setFakeBoldText(key.isCursor);
}
paint.setTextSize(labelSize);
final int labelHeight = getLabelHeight(paint, labelSize);
// Draw a drop shadow for the text
paint.setShadowLayer(mShadowRadius, 0, 0, mShadowColor);
// Draw hint label (if present) behind the main key
char hint = getHintLabel(key);
if (hint != 0) {
int hintTextSize = (int)(mKeyTextSize * 0.6 * mLabelScale);
paintHint.setTextSize(hintTextSize);
final int hintLabelHeight = getLabelHeight(paintHint, hintTextSize);
canvas.drawText(Character.toString(hint),
key.width - padding.right,
padding.top + hintLabelHeight * 11/10,
paintHint);
}
// Draw main key label
final int centerX = (key.width + padding.left - padding.right) / 2;
final int centerY = (key.height + padding.top - padding.bottom) / 2;
final float baseline = centerY
+ labelHeight * KEY_LABEL_VERTICAL_ADJUSTMENT_FACTOR;
canvas.drawText(label, centerX, baseline, paint);
if (key.isCursor) {
// poor man's bold
canvas.drawText(label, centerX+0.5f, baseline, paint);
canvas.drawText(label, centerX-0.5f, baseline, paint);
canvas.drawText(label, centerX, baseline+0.5f, paint);
canvas.drawText(label, centerX, baseline-0.5f, paint);
}
// Turn off drop shadow
paint.setShadowLayer(0, 0, 0, 0);
// Usually don't draw icon if label is not null, but we draw icon for the number
// hint and popup hint.
shouldDrawIcon = shouldDrawLabelAndIcon(key);
}
if (key.icon != null && shouldDrawIcon) {
// Special handing for the upper-right number hint icons
final int drawableWidth;
final int drawableHeight;
final int drawableX;
final int drawableY;
if (shouldDrawIconFully(key)) {
drawableWidth = key.width;
drawableHeight = key.height;
drawableX = 0;
drawableY = NUMBER_HINT_VERTICAL_ADJUSTMENT_PIXEL;
} else {
drawableWidth = key.icon.getIntrinsicWidth();
drawableHeight = key.icon.getIntrinsicHeight();
drawableX = (key.width + padding.left - padding.right - drawableWidth) / 2;
drawableY = (key.height + padding.top - padding.bottom - drawableHeight) / 2;
}
canvas.translate(drawableX, drawableY);
key.icon.setBounds(0, 0, drawableWidth, drawableHeight);
key.icon.draw(canvas);
canvas.translate(-drawableX, -drawableY);
}
canvas.translate(-key.x - kbdPaddingLeft, -key.y - kbdPaddingTop);
}
mInvalidatedKey = null;
// Overlay a dark rectangle to dim the keyboard
if (mMiniKeyboard != null) {
paint.setColor((int) (mBackgroundDimAmount * 0xFF) << 24);
canvas.drawRect(0, 0, getWidth(), getHeight(), paint);
}
if (DEBUG) {
if (mShowTouchPoints) {
for (PointerTracker tracker : mPointerTrackers) {
int startX = tracker.getStartX();
int startY = tracker.getStartY();
int lastX = tracker.getLastX();
int lastY = tracker.getLastY();
paint.setAlpha(128);
paint.setColor(0xFFFF0000);
canvas.drawCircle(startX, startY, 3, paint);
canvas.drawLine(startX, startY, lastX, lastY, paint);
paint.setColor(0xFF0000FF);
canvas.drawCircle(lastX, lastY, 3, paint);
paint.setColor(0xFF00FF00);
canvas.drawCircle((startX + lastX) / 2, (startY + lastY) / 2, 2, paint);
}
}
}
mDrawPending = false;
mDirtyRect.setEmpty();
}
| private void onBufferDraw() {
if (mBuffer == null || mKeyboardChanged) {
mKeyboard.setKeyboardWidth(mViewWidth);
if (mBuffer == null || mKeyboardChanged &&
(mBuffer.getWidth() != getWidth() || mBuffer.getHeight() != getHeight())) {
// Make sure our bitmap is at least 1x1
final int width = Math.max(1, getWidth());
final int height = Math.max(1, getHeight());
mBuffer = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBuffer);
}
invalidateAllKeys();
mKeyboardChanged = false;
}
final Canvas canvas = mCanvas;
canvas.clipRect(mDirtyRect, Op.REPLACE);
if (mKeyboard == null) return;
final Paint paint = mPaint;
final Paint paintHint = mPaintHint;
final Drawable keyBackground = mKeyBackground;
final Rect clipRegion = mClipRegion;
final Rect padding = mPadding;
final int kbdPaddingLeft = getPaddingLeft();
final int kbdPaddingTop = getPaddingTop();
final Key[] keys = mKeys;
final Key invalidKey = mInvalidatedKey;
boolean drawSingleKey = false;
if (invalidKey != null && canvas.getClipBounds(clipRegion)) {
// TODO we should use Rect.inset and Rect.contains here.
// Is clipRegion completely contained within the invalidated key?
if (invalidKey.x + kbdPaddingLeft - 1 <= clipRegion.left &&
invalidKey.y + kbdPaddingTop - 1 <= clipRegion.top &&
invalidKey.x + invalidKey.width + kbdPaddingLeft + 1 >= clipRegion.right &&
invalidKey.y + invalidKey.height + kbdPaddingTop + 1 >= clipRegion.bottom) {
drawSingleKey = true;
}
}
canvas.drawColor(0x00000000, PorterDuff.Mode.CLEAR);
final int keyCount = keys.length;
for (int i = 0; i < keyCount; i++) {
final Key key = keys[i];
if (drawSingleKey && invalidKey != key) {
continue;
}
paint.setColor(key.isCursor ? mKeyCursorColor : mKeyTextColor);
int[] drawableState = key.getCurrentDrawableState();
keyBackground.setState(drawableState);
// Switch the character to uppercase if shift is pressed
String label = key.label == null? null : adjustCase(key.label).toString();
float yscale = 1.0f;
final Rect bounds = keyBackground.getBounds();
if (key.width != bounds.right || key.height != bounds.bottom) {
int minHeight = keyBackground.getMinimumHeight();
if (minHeight > key.height) {
yscale = (float) key.height / minHeight;
keyBackground.setBounds(0, 0, key.width, minHeight);
} else {
keyBackground.setBounds(0, 0, key.width, key.height);
}
}
canvas.translate(key.x + kbdPaddingLeft, key.y + kbdPaddingTop);
if (yscale != 1.0f) {
canvas.save();
canvas.scale(1.0f, yscale);
}
keyBackground.draw(canvas);
if (yscale != 1.0f) canvas.restore();
boolean shouldDrawIcon = true;
if (label != null) {
// For characters, use large font. For labels like "Done", use small font.
final int labelSize;
if (label.length() > 1 && key.codes.length < 2) {
//Log.i(TAG, "mLabelTextSize=" + mLabelTextSize + " mLabelScale=" + mLabelScale);
labelSize = (int)(mLabelTextSize * mLabelScale);
paint.setTypeface(Typeface.DEFAULT);
} else {
labelSize = (int)(mKeyTextSize * mLabelScale);
paint.setTypeface(mKeyTextStyle);
}
paint.setFakeBoldText(key.isCursor);
paint.setTextSize(labelSize);
final int labelHeight = getLabelHeight(paint, labelSize);
// Draw a drop shadow for the text
paint.setShadowLayer(mShadowRadius, 0, 0, mShadowColor);
// Draw hint label (if present) behind the main key
char hint = getHintLabel(key);
if (hint != 0) {
int hintTextSize = (int)(mKeyTextSize * 0.6 * mLabelScale);
paintHint.setTextSize(hintTextSize);
final int hintLabelHeight = getLabelHeight(paintHint, hintTextSize);
canvas.drawText(Character.toString(hint),
key.width - padding.right,
padding.top + hintLabelHeight * 11/10,
paintHint);
}
// Draw main key label
final int centerX = (key.width + padding.left - padding.right) / 2;
final int centerY = (key.height + padding.top - padding.bottom) / 2;
final float baseline = centerY
+ labelHeight * KEY_LABEL_VERTICAL_ADJUSTMENT_FACTOR;
canvas.drawText(label, centerX, baseline, paint);
if (key.isCursor) {
// poor man's bold
canvas.drawText(label, centerX+0.5f, baseline, paint);
canvas.drawText(label, centerX-0.5f, baseline, paint);
canvas.drawText(label, centerX, baseline+0.5f, paint);
canvas.drawText(label, centerX, baseline-0.5f, paint);
}
// Turn off drop shadow
paint.setShadowLayer(0, 0, 0, 0);
// Usually don't draw icon if label is not null, but we draw icon for the number
// hint and popup hint.
shouldDrawIcon = shouldDrawLabelAndIcon(key);
}
if (key.icon != null && shouldDrawIcon) {
// Special handing for the upper-right number hint icons
final int drawableWidth;
final int drawableHeight;
final int drawableX;
final int drawableY;
if (shouldDrawIconFully(key)) {
drawableWidth = key.width;
drawableHeight = key.height;
drawableX = 0;
drawableY = NUMBER_HINT_VERTICAL_ADJUSTMENT_PIXEL;
} else {
drawableWidth = key.icon.getIntrinsicWidth();
drawableHeight = key.icon.getIntrinsicHeight();
drawableX = (key.width + padding.left - padding.right - drawableWidth) / 2;
drawableY = (key.height + padding.top - padding.bottom - drawableHeight) / 2;
}
canvas.translate(drawableX, drawableY);
key.icon.setBounds(0, 0, drawableWidth, drawableHeight);
key.icon.draw(canvas);
canvas.translate(-drawableX, -drawableY);
}
canvas.translate(-key.x - kbdPaddingLeft, -key.y - kbdPaddingTop);
}
mInvalidatedKey = null;
// Overlay a dark rectangle to dim the keyboard
if (mMiniKeyboard != null) {
paint.setColor((int) (mBackgroundDimAmount * 0xFF) << 24);
canvas.drawRect(0, 0, getWidth(), getHeight(), paint);
}
if (DEBUG) {
if (mShowTouchPoints) {
for (PointerTracker tracker : mPointerTrackers) {
int startX = tracker.getStartX();
int startY = tracker.getStartY();
int lastX = tracker.getLastX();
int lastY = tracker.getLastY();
paint.setAlpha(128);
paint.setColor(0xFFFF0000);
canvas.drawCircle(startX, startY, 3, paint);
canvas.drawLine(startX, startY, lastX, lastY, paint);
paint.setColor(0xFF0000FF);
canvas.drawCircle(lastX, lastY, 3, paint);
paint.setColor(0xFF00FF00);
canvas.drawCircle((startX + lastX) / 2, (startY + lastY) / 2, 2, paint);
}
}
}
mDrawPending = false;
mDirtyRect.setEmpty();
}
|
diff --git a/src/gwt/src/org/rstudio/studio/client/workbench/views/vcs/common/model/VcsState.java b/src/gwt/src/org/rstudio/studio/client/workbench/views/vcs/common/model/VcsState.java
index 7582f5d86b..c43dede231 100644
--- a/src/gwt/src/org/rstudio/studio/client/workbench/views/vcs/common/model/VcsState.java
+++ b/src/gwt/src/org/rstudio/studio/client/workbench/views/vcs/common/model/VcsState.java
@@ -1,192 +1,192 @@
/*
* VcsState.java
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
package org.rstudio.studio.client.workbench.views.vcs.common.model;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.RepeatingCommand;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.Widget;
import org.rstudio.core.client.HandlerRegistrations;
import org.rstudio.core.client.StringUtil;
import org.rstudio.core.client.WidgetHandlerRegistration;
import org.rstudio.core.client.files.FileSystemItem;
import org.rstudio.studio.client.application.events.EventBus;
import org.rstudio.studio.client.common.GlobalDisplay;
import org.rstudio.studio.client.common.vcs.StatusAndPath;
import org.rstudio.studio.client.common.vcs.StatusAndPathInfo;
import org.rstudio.studio.client.workbench.model.Session;
import org.rstudio.studio.client.workbench.views.files.events.FileChangeEvent;
import org.rstudio.studio.client.workbench.views.files.events.FileChangeHandler;
import org.rstudio.studio.client.workbench.views.files.model.FileChange;
import org.rstudio.studio.client.workbench.views.vcs.common.events.VcsRefreshEvent;
import org.rstudio.studio.client.workbench.views.vcs.common.events.VcsRefreshEvent.Reason;
import org.rstudio.studio.client.workbench.views.vcs.common.events.VcsRefreshHandler;
import java.util.ArrayList;
public abstract class VcsState
{
public VcsState(EventBus eventBus,
GlobalDisplay globalDisplay,
final Session session)
{
eventBus_ = eventBus;
globalDisplay_ = globalDisplay;
session_ = session;
final HandlerRegistrations registrations = new HandlerRegistrations();
registrations.add(eventBus_.addHandler(VcsRefreshEvent.TYPE, new VcsRefreshHandler()
{
@Override
public void onVcsRefresh(VcsRefreshEvent event)
{
if (!session.getSessionInfo().isVcsEnabled())
registrations.removeHandler();
if (event.getDelayMs() > 0)
{
Scheduler.get().scheduleFixedDelay(new RepeatingCommand()
{
@Override
public boolean execute()
{
refresh(false);
return false;
}
}, event.getDelayMs());
}
else
{
Scheduler.get().scheduleDeferred(new ScheduledCommand()
{
@Override
public void execute()
{
refresh(false);
}
});
}
}
}));
registrations.add(eventBus_.addHandler(FileChangeEvent.TYPE, new FileChangeHandler()
{
@Override
public void onFileChange(FileChangeEvent event)
{
if (!session.getSessionInfo().isVcsEnabled())
registrations.removeHandler();
FileChange fileChange = event.getFileChange();
FileSystemItem file = fileChange.getFile();
StatusAndPath status = StatusAndPath.fromInfo(
getStatusFromFile(file));
if (needsFullRefresh(file))
{
refresh(false);
return;
}
- if (status_ != null)
+ if (status_ != null && status != null)
{
for (int i = 0; i < status_.size(); i++)
{
if (status.getRawPath().equals(status_.get(i).getRawPath()))
{
if (StringUtil.notNull(status.getStatus()).trim().length() == 0)
status_.remove(i);
else
status_.set(i, status);
handlers_.fireEvent(new VcsRefreshEvent(Reason.FileChange));
return;
}
}
if (status.getStatus().trim().length() != 0)
{
status_.add(status);
handlers_.fireEvent(new VcsRefreshEvent(Reason.FileChange));
return;
}
}
}
}));
Scheduler.get().scheduleDeferred(new ScheduledCommand()
{
@Override
public void execute()
{
refresh(false);
}
});
}
public void bindRefreshHandler(Widget owner,
final VcsRefreshHandler handler)
{
new WidgetHandlerRegistration(owner)
{
@Override
protected HandlerRegistration doRegister()
{
return addVcsRefreshHandler(handler);
}
};
}
public HandlerRegistration addVcsRefreshHandler(VcsRefreshHandler handler)
{
return addVcsRefreshHandler(handler, true);
}
public HandlerRegistration addVcsRefreshHandler(VcsRefreshHandler handler,
boolean fireOnAdd)
{
HandlerRegistration hreg = handlers_.addHandler(
VcsRefreshEvent.TYPE, handler);
if (fireOnAdd && isInitialized())
handler.onVcsRefresh(new VcsRefreshEvent(Reason.VcsOperation));
return hreg;
}
public ArrayList<StatusAndPath> getStatus()
{
return status_;
}
public void refresh()
{
if (session_.getSessionInfo().isVcsEnabled())
refresh(true);
}
protected abstract StatusAndPathInfo getStatusFromFile(FileSystemItem file);
protected abstract boolean needsFullRefresh(FileSystemItem file);
public abstract void refresh(final boolean showError);
protected abstract boolean isInitialized();
protected final HandlerManager handlers_ = new HandlerManager(this);
protected ArrayList<StatusAndPath> status_;
protected final EventBus eventBus_;
protected final GlobalDisplay globalDisplay_;
protected final Session session_;
}
| true | true | public VcsState(EventBus eventBus,
GlobalDisplay globalDisplay,
final Session session)
{
eventBus_ = eventBus;
globalDisplay_ = globalDisplay;
session_ = session;
final HandlerRegistrations registrations = new HandlerRegistrations();
registrations.add(eventBus_.addHandler(VcsRefreshEvent.TYPE, new VcsRefreshHandler()
{
@Override
public void onVcsRefresh(VcsRefreshEvent event)
{
if (!session.getSessionInfo().isVcsEnabled())
registrations.removeHandler();
if (event.getDelayMs() > 0)
{
Scheduler.get().scheduleFixedDelay(new RepeatingCommand()
{
@Override
public boolean execute()
{
refresh(false);
return false;
}
}, event.getDelayMs());
}
else
{
Scheduler.get().scheduleDeferred(new ScheduledCommand()
{
@Override
public void execute()
{
refresh(false);
}
});
}
}
}));
registrations.add(eventBus_.addHandler(FileChangeEvent.TYPE, new FileChangeHandler()
{
@Override
public void onFileChange(FileChangeEvent event)
{
if (!session.getSessionInfo().isVcsEnabled())
registrations.removeHandler();
FileChange fileChange = event.getFileChange();
FileSystemItem file = fileChange.getFile();
StatusAndPath status = StatusAndPath.fromInfo(
getStatusFromFile(file));
if (needsFullRefresh(file))
{
refresh(false);
return;
}
if (status_ != null)
{
for (int i = 0; i < status_.size(); i++)
{
if (status.getRawPath().equals(status_.get(i).getRawPath()))
{
if (StringUtil.notNull(status.getStatus()).trim().length() == 0)
status_.remove(i);
else
status_.set(i, status);
handlers_.fireEvent(new VcsRefreshEvent(Reason.FileChange));
return;
}
}
if (status.getStatus().trim().length() != 0)
{
status_.add(status);
handlers_.fireEvent(new VcsRefreshEvent(Reason.FileChange));
return;
}
}
}
}));
Scheduler.get().scheduleDeferred(new ScheduledCommand()
{
@Override
public void execute()
{
refresh(false);
}
});
}
| public VcsState(EventBus eventBus,
GlobalDisplay globalDisplay,
final Session session)
{
eventBus_ = eventBus;
globalDisplay_ = globalDisplay;
session_ = session;
final HandlerRegistrations registrations = new HandlerRegistrations();
registrations.add(eventBus_.addHandler(VcsRefreshEvent.TYPE, new VcsRefreshHandler()
{
@Override
public void onVcsRefresh(VcsRefreshEvent event)
{
if (!session.getSessionInfo().isVcsEnabled())
registrations.removeHandler();
if (event.getDelayMs() > 0)
{
Scheduler.get().scheduleFixedDelay(new RepeatingCommand()
{
@Override
public boolean execute()
{
refresh(false);
return false;
}
}, event.getDelayMs());
}
else
{
Scheduler.get().scheduleDeferred(new ScheduledCommand()
{
@Override
public void execute()
{
refresh(false);
}
});
}
}
}));
registrations.add(eventBus_.addHandler(FileChangeEvent.TYPE, new FileChangeHandler()
{
@Override
public void onFileChange(FileChangeEvent event)
{
if (!session.getSessionInfo().isVcsEnabled())
registrations.removeHandler();
FileChange fileChange = event.getFileChange();
FileSystemItem file = fileChange.getFile();
StatusAndPath status = StatusAndPath.fromInfo(
getStatusFromFile(file));
if (needsFullRefresh(file))
{
refresh(false);
return;
}
if (status_ != null && status != null)
{
for (int i = 0; i < status_.size(); i++)
{
if (status.getRawPath().equals(status_.get(i).getRawPath()))
{
if (StringUtil.notNull(status.getStatus()).trim().length() == 0)
status_.remove(i);
else
status_.set(i, status);
handlers_.fireEvent(new VcsRefreshEvent(Reason.FileChange));
return;
}
}
if (status.getStatus().trim().length() != 0)
{
status_.add(status);
handlers_.fireEvent(new VcsRefreshEvent(Reason.FileChange));
return;
}
}
}
}));
Scheduler.get().scheduleDeferred(new ScheduledCommand()
{
@Override
public void execute()
{
refresh(false);
}
});
}
|
diff --git a/xjc/src/com/sun/tools/xjc/model/CEnumLeafInfo.java b/xjc/src/com/sun/tools/xjc/model/CEnumLeafInfo.java
index 5056c08b..e8b9cb1c 100644
--- a/xjc/src/com/sun/tools/xjc/model/CEnumLeafInfo.java
+++ b/xjc/src/com/sun/tools/xjc/model/CEnumLeafInfo.java
@@ -1,271 +1,271 @@
/*
* The contents of this file are subject to the terms
* of the Common Development and Distribution License
* (the "License"). You may not use this file except
* in compliance with the License.
*
* You can obtain a copy of the license at
* https://jwsdp.dev.java.net/CDDLv1.0.html
* See the License for the specific language governing
* permissions and limitations under the License.
*
* When distributing Covered Code, include this CDDL
* HEADER in each file and include the License file at
* https://jwsdp.dev.java.net/CDDLv1.0.html If applicable,
* add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your
* own identifying information: Portions Copyright [yyyy]
* [name of copyright owner]
*/
package com.sun.tools.xjc.model;
import java.util.Collection;
import javax.activation.MimeType;
import javax.xml.namespace.QName;
import com.sun.codemodel.JClass;
import com.sun.codemodel.JExpression;
import com.sun.tools.xjc.model.nav.NClass;
import com.sun.tools.xjc.model.nav.NType;
import com.sun.tools.xjc.outline.Aspect;
import com.sun.tools.xjc.outline.Outline;
import com.sun.xml.bind.v2.model.annotation.Locatable;
import com.sun.xml.bind.v2.model.core.EnumLeafInfo;
import com.sun.xml.bind.v2.model.core.ID;
import com.sun.xml.bind.v2.model.core.NonElement;
import com.sun.xml.bind.v2.model.core.Element;
import com.sun.xml.bind.v2.runtime.Location;
import com.sun.xml.xsom.XSComponent;
import com.sun.xml.xsom.XmlString;
import org.xml.sax.Locator;
/**
* Transducer that converts a string into an "enumeration class."
*
* The structure of the generated class needs to precisely
* follow the JAXB spec.
*
* @author
* <a href="mailto:[email protected]">Kohsuke KAWAGUCHI</a>
*/
public final class CEnumLeafInfo implements EnumLeafInfo<NType,NClass>, NClass, CNonElement
{
/**
* The {@link Model} object to which this bean belongs.
*/
public final Model model;
/**
* The parent into which the enum class should be generated.
*/
public final CClassInfoParent parent;
/**
* Short name of the generated type-safe enum.
*/
public final String shortName;
private final QName typeName;
private final XSComponent source;
/**
* Represents the underlying type of this enumeration
* and its conversion.
*
* <p>
* To parse XML into a constant, we use the base type
* to do lexical -> value, then use a map to pick up the right one.
*
* <p>
* Hence this also represents the type of the Java value.
* For example, if this is an enumeration of xs:int,
* then this field will be Java int.
*/
public final CNonElement base;
/**
* List of enum members.
*/
public final Collection<CEnumConstant> members;
private final CCustomizations customizations;
/**
* @see #getLocator()
*/
private final Locator sourceLocator;
public String javadoc;
public CEnumLeafInfo(Model model,
QName typeName,
CClassInfoParent container,
String shortName,
CNonElement base,
Collection<CEnumConstant> _members,
XSComponent source,
CCustomizations customizations,
Locator _sourceLocator) {
this.model = model;
this.parent = container;
- this.shortName = shortName;
+ this.shortName = model.allocator.assignClassName(parent,shortName);
this.base = base;
this.members = _members;
this.source = source;
if(customizations==null)
customizations = CCustomizations.EMPTY;
this.customizations = customizations;
this.sourceLocator = _sourceLocator;
this.typeName = typeName;
for( CEnumConstant mem : members )
mem.setParent(this);
model.add(this);
// TODO: can we take advantage of the fact that enum can be XmlRootElement?
}
/**
* Source line information that points to the place
* where this type-safe enum is defined.
* Used to report error messages.
*/
public Locator getLocator() {
return sourceLocator;
}
public QName getTypeName() {
return typeName;
}
public NType getType() {
return this;
}
/**
* @deprecated
* why are you calling the method whose return value is known?
*/
public boolean canBeReferencedByIDREF() {
return false;
}
public boolean isElement() {
return false;
}
public QName getElementName() {
return null;
}
public Element<NType,NClass> asElement() {
return null;
}
public NClass getClazz() {
return this;
}
public XSComponent getSchemaComponent() {
return source;
}
public JClass toType(Outline o, Aspect aspect) {
return o.getEnum(this).clazz;
}
public boolean isAbstract() {
return false;
}
public boolean isBoxedType() {
return false;
}
public String fullName() {
return parent.fullName()+'.'+shortName;
}
public boolean isPrimitive() {
return false;
}
public boolean isSimpleType() {
return true;
}
/**
* The spec says the value field in the enum class will be generated
* only under certain circumstances.
*
* @return
* true if the generated enum class should have the value field.
*/
public boolean needsValueField() {
for (CEnumConstant cec : members) {
if(!cec.getName().equals(cec.getLexicalValue()))
return true;
}
return false;
}
public JExpression createConstant(Outline outline, XmlString literal) {
// correctly identifying which constant it maps to is hard, so
// here I'm cheating
JClass type = toType(outline,Aspect.EXPOSED);
for (CEnumConstant mem : members) {
if(mem.getLexicalValue().equals(literal.value))
return type.staticRef(mem.getName());
}
return null;
}
@Deprecated
public boolean isCollection() {
return false;
}
@Deprecated
public CAdapter getAdapterUse() {
return null;
}
@Deprecated
public CNonElement getInfo() {
return this;
}
public ID idUse() {
return ID.NONE;
}
public MimeType getExpectedMimeType() {
return null;
}
public Collection<CEnumConstant> getConstants() {
return members;
}
public NonElement<NType,NClass> getBaseType() {
return base;
}
public CCustomizations getCustomizations() {
return customizations;
}
public Locatable getUpstream() {
throw new UnsupportedOperationException();
}
public Location getLocation() {
throw new UnsupportedOperationException();
}
}
| true | true | public CEnumLeafInfo(Model model,
QName typeName,
CClassInfoParent container,
String shortName,
CNonElement base,
Collection<CEnumConstant> _members,
XSComponent source,
CCustomizations customizations,
Locator _sourceLocator) {
this.model = model;
this.parent = container;
this.shortName = shortName;
this.base = base;
this.members = _members;
this.source = source;
if(customizations==null)
customizations = CCustomizations.EMPTY;
this.customizations = customizations;
this.sourceLocator = _sourceLocator;
this.typeName = typeName;
for( CEnumConstant mem : members )
mem.setParent(this);
model.add(this);
// TODO: can we take advantage of the fact that enum can be XmlRootElement?
}
| public CEnumLeafInfo(Model model,
QName typeName,
CClassInfoParent container,
String shortName,
CNonElement base,
Collection<CEnumConstant> _members,
XSComponent source,
CCustomizations customizations,
Locator _sourceLocator) {
this.model = model;
this.parent = container;
this.shortName = model.allocator.assignClassName(parent,shortName);
this.base = base;
this.members = _members;
this.source = source;
if(customizations==null)
customizations = CCustomizations.EMPTY;
this.customizations = customizations;
this.sourceLocator = _sourceLocator;
this.typeName = typeName;
for( CEnumConstant mem : members )
mem.setParent(this);
model.add(this);
// TODO: can we take advantage of the fact that enum can be XmlRootElement?
}
|
diff --git a/src/java/org/apache/fop/apps/FOURIResolver.java b/src/java/org/apache/fop/apps/FOURIResolver.java
index 5b73a66fd..a2b70346f 100644
--- a/src/java/org/apache/fop/apps/FOURIResolver.java
+++ b/src/java/org/apache/fop/apps/FOURIResolver.java
@@ -1,151 +1,151 @@
/*
* Copyright 2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* $Id: $ */
package org.apache.fop.apps;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
// commons logging
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Provides FOP specific URI resolution.
* This is the default URIResolver {@link FOUserAgent} will use unless overidden.
* @see javax.xml.transform.URIResolver
*/
public class FOURIResolver
implements javax.xml.transform.URIResolver {
private Log log = LogFactory.getLog("FOP");
/**
* Called by the processor through {@link FOUserAgent} when it encounters an
* uri in an external-graphic element.
* (see also {@link javax.xml.transform.URIResolver#resolve(String, String)}
* This resolver will allow URLs without a scheme, i.e. it assumes 'file:' as
* the default scheme. It also allows relative URLs with scheme,
* e.g. file:../../abc.jpg which is not strictly RFC compliant as long as the
* scheme is the same as the scheme of the base URL. If the base URL is null
* a 'file:' URL referencing the current directory is used as the base URL.
* If the method is successful it will return a Source of type
* {@link javax.xml.transform.stream.StreamSource} with its SystemID set to
* the resolved URL used to open the underlying InputStream.
*
* @param href An href attribute, which may be relative or absolute.
* @param base The base URI against which the first argument will be made
* absolute if the absolute URI is required.
* @return A {@link javax.xml.transform.Source} object, or null if the href
* cannot be resolved.
* @throws javax.xml.transform.TransformerException Never thrown by this implementation.
* @see javax.xml.transform.URIResolver#resolve(String, String)
*/
public Source resolve(String href, String base)
throws javax.xml.transform.TransformerException {
URL absoluteURL = null;
File f = new File(href);
if (f.exists()) {
try {
absoluteURL = f.toURL();
} catch (MalformedURLException mfue) {
log.error("Could not convert filename to URL: " + mfue.getMessage(), mfue);
}
} else {
URL baseURL = toBaseURL(base);
if (baseURL == null) {
// We don't have a valid baseURL just use the URL as given
try {
absoluteURL = new URL(href);
} catch (MalformedURLException mue) {
try {
// the above failed, we give it another go in case
// the href contains only a path then file: is assumed
absoluteURL = new URL("file:" + href);
} catch (MalformedURLException mfue) {
log.error("Error with URL '" + href + "': " + mue.getMessage(), mue);
return null;
}
}
} else {
try {
/*
This piece of code is based on the following statement in RFC2396 section 5.2:
3) If the scheme component is defined, indicating that the reference
starts with a scheme name, then the reference is interpreted as an
absolute URI and we are done. Otherwise, the reference URI's
scheme is inherited from the base URI's scheme component.
Due to a loophole in prior specifications [RFC1630], some parsers
allow the scheme name to be present in a relative URI if it is the
same as the base URI scheme. Unfortunately, this can conflict
with the correct parsing of non-hierarchical URI. For backwards
compatibility, an implementation may work around such references
by removing the scheme if it matches that of the base URI and the
scheme is known to always use the <hier_part> syntax.
The URL class does not implement this work around, so we do.
*/
String scheme = baseURL.getProtocol() + ":";
if (href.startsWith(scheme)) {
href = href.substring(scheme.length());
- }
- if ("file:".equals(scheme) && href.indexOf(':') >= 0) {
- href = "/" + href; //Absolute file URL doesn't have a leading slash
+ if ("file:".equals(scheme) && href.indexOf(':') >= 0) {
+ href = "/" + href; //Absolute file URL doesn't have a leading slash
+ }
}
absoluteURL = new URL(baseURL, href);
} catch (MalformedURLException mfue) {
log.error("Error with URL '" + href + "': " + mfue.getMessage(), mfue);
return null;
}
}
}
try {
return new StreamSource(absoluteURL.openStream(), absoluteURL.toExternalForm());
} catch (java.io.IOException ioe) {
log.error("Error with opening URL '" + href + "': " + ioe.getMessage(), ioe);
}
return null;
}
/**
* Returns the base URL as a java.net.URL.
* If the base URL is not set a default URL pointing to the
* current directory is returned.
* @param baseURL the base URL
* @returns the base URL as java.net.URL
*/
private URL toBaseURL(String baseURL) {
try {
return new URL(baseURL == null
? new java.io.File("").toURL().toExternalForm()
: baseURL);
} catch (MalformedURLException mfue) {
log.error("Error with base URL: " + mfue.getMessage(), mfue);
}
return null;
}
}
| true | true | public Source resolve(String href, String base)
throws javax.xml.transform.TransformerException {
URL absoluteURL = null;
File f = new File(href);
if (f.exists()) {
try {
absoluteURL = f.toURL();
} catch (MalformedURLException mfue) {
log.error("Could not convert filename to URL: " + mfue.getMessage(), mfue);
}
} else {
URL baseURL = toBaseURL(base);
if (baseURL == null) {
// We don't have a valid baseURL just use the URL as given
try {
absoluteURL = new URL(href);
} catch (MalformedURLException mue) {
try {
// the above failed, we give it another go in case
// the href contains only a path then file: is assumed
absoluteURL = new URL("file:" + href);
} catch (MalformedURLException mfue) {
log.error("Error with URL '" + href + "': " + mue.getMessage(), mue);
return null;
}
}
} else {
try {
/*
This piece of code is based on the following statement in RFC2396 section 5.2:
3) If the scheme component is defined, indicating that the reference
starts with a scheme name, then the reference is interpreted as an
absolute URI and we are done. Otherwise, the reference URI's
scheme is inherited from the base URI's scheme component.
Due to a loophole in prior specifications [RFC1630], some parsers
allow the scheme name to be present in a relative URI if it is the
same as the base URI scheme. Unfortunately, this can conflict
with the correct parsing of non-hierarchical URI. For backwards
compatibility, an implementation may work around such references
by removing the scheme if it matches that of the base URI and the
scheme is known to always use the <hier_part> syntax.
The URL class does not implement this work around, so we do.
*/
String scheme = baseURL.getProtocol() + ":";
if (href.startsWith(scheme)) {
href = href.substring(scheme.length());
}
if ("file:".equals(scheme) && href.indexOf(':') >= 0) {
href = "/" + href; //Absolute file URL doesn't have a leading slash
}
absoluteURL = new URL(baseURL, href);
} catch (MalformedURLException mfue) {
log.error("Error with URL '" + href + "': " + mfue.getMessage(), mfue);
return null;
}
}
}
try {
return new StreamSource(absoluteURL.openStream(), absoluteURL.toExternalForm());
} catch (java.io.IOException ioe) {
log.error("Error with opening URL '" + href + "': " + ioe.getMessage(), ioe);
}
return null;
}
| public Source resolve(String href, String base)
throws javax.xml.transform.TransformerException {
URL absoluteURL = null;
File f = new File(href);
if (f.exists()) {
try {
absoluteURL = f.toURL();
} catch (MalformedURLException mfue) {
log.error("Could not convert filename to URL: " + mfue.getMessage(), mfue);
}
} else {
URL baseURL = toBaseURL(base);
if (baseURL == null) {
// We don't have a valid baseURL just use the URL as given
try {
absoluteURL = new URL(href);
} catch (MalformedURLException mue) {
try {
// the above failed, we give it another go in case
// the href contains only a path then file: is assumed
absoluteURL = new URL("file:" + href);
} catch (MalformedURLException mfue) {
log.error("Error with URL '" + href + "': " + mue.getMessage(), mue);
return null;
}
}
} else {
try {
/*
This piece of code is based on the following statement in RFC2396 section 5.2:
3) If the scheme component is defined, indicating that the reference
starts with a scheme name, then the reference is interpreted as an
absolute URI and we are done. Otherwise, the reference URI's
scheme is inherited from the base URI's scheme component.
Due to a loophole in prior specifications [RFC1630], some parsers
allow the scheme name to be present in a relative URI if it is the
same as the base URI scheme. Unfortunately, this can conflict
with the correct parsing of non-hierarchical URI. For backwards
compatibility, an implementation may work around such references
by removing the scheme if it matches that of the base URI and the
scheme is known to always use the <hier_part> syntax.
The URL class does not implement this work around, so we do.
*/
String scheme = baseURL.getProtocol() + ":";
if (href.startsWith(scheme)) {
href = href.substring(scheme.length());
if ("file:".equals(scheme) && href.indexOf(':') >= 0) {
href = "/" + href; //Absolute file URL doesn't have a leading slash
}
}
absoluteURL = new URL(baseURL, href);
} catch (MalformedURLException mfue) {
log.error("Error with URL '" + href + "': " + mfue.getMessage(), mfue);
return null;
}
}
}
try {
return new StreamSource(absoluteURL.openStream(), absoluteURL.toExternalForm());
} catch (java.io.IOException ioe) {
log.error("Error with opening URL '" + href + "': " + ioe.getMessage(), ioe);
}
return null;
}
|
diff --git a/plugins/org.eclipse.incquery.patternlanguage.emf/src/org/eclipse/incquery/patternlanguage/emf/validation/EMFPatternLanguageJavaValidator.java b/plugins/org.eclipse.incquery.patternlanguage.emf/src/org/eclipse/incquery/patternlanguage/emf/validation/EMFPatternLanguageJavaValidator.java
index aa9600c7..3818ad89 100644
--- a/plugins/org.eclipse.incquery.patternlanguage.emf/src/org/eclipse/incquery/patternlanguage/emf/validation/EMFPatternLanguageJavaValidator.java
+++ b/plugins/org.eclipse.incquery.patternlanguage.emf/src/org/eclipse/incquery/patternlanguage/emf/validation/EMFPatternLanguageJavaValidator.java
@@ -1,597 +1,605 @@
/*******************************************************************************
* Copyright (c) 2010-2012, Zoltan Ujhelyi, Istvan Rath and Daniel Varro
* 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:
* Mark Czotter, Zoltan Ujhelyi - initial API and implementation
* Andras Okros - new validators added
*******************************************************************************/
package org.eclipse.incquery.patternlanguage.emf.validation;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EClassifier;
import org.eclipse.emf.ecore.EDataType;
import org.eclipse.emf.ecore.EEnum;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.incquery.patternlanguage.emf.EMFPatternLanguageScopeHelper;
import org.eclipse.incquery.patternlanguage.emf.ResolutionException;
import org.eclipse.incquery.patternlanguage.emf.eMFPatternLanguage.EMFPatternLanguagePackage;
import org.eclipse.incquery.patternlanguage.emf.eMFPatternLanguage.EnumValue;
import org.eclipse.incquery.patternlanguage.emf.eMFPatternLanguage.PackageImport;
import org.eclipse.incquery.patternlanguage.emf.eMFPatternLanguage.PatternModel;
import org.eclipse.incquery.patternlanguage.emf.helper.EMFPatternLanguageHelper;
import org.eclipse.incquery.patternlanguage.emf.scoping.IMetamodelProvider;
import org.eclipse.incquery.patternlanguage.emf.types.EMFPatternTypeUtil;
import org.eclipse.incquery.patternlanguage.emf.types.IEMFTypeProvider;
import org.eclipse.incquery.patternlanguage.helper.CorePatternLanguageHelper;
import org.eclipse.incquery.patternlanguage.patternLanguage.AggregatedValue;
import org.eclipse.incquery.patternlanguage.patternLanguage.CheckConstraint;
import org.eclipse.incquery.patternlanguage.patternLanguage.CompareConstraint;
import org.eclipse.incquery.patternlanguage.patternLanguage.CompareFeature;
import org.eclipse.incquery.patternlanguage.patternLanguage.ComputationValue;
import org.eclipse.incquery.patternlanguage.patternLanguage.Constraint;
import org.eclipse.incquery.patternlanguage.patternLanguage.LiteralValueReference;
import org.eclipse.incquery.patternlanguage.patternLanguage.PathExpressionConstraint;
import org.eclipse.incquery.patternlanguage.patternLanguage.PathExpressionHead;
import org.eclipse.incquery.patternlanguage.patternLanguage.Pattern;
import org.eclipse.incquery.patternlanguage.patternLanguage.PatternBody;
import org.eclipse.incquery.patternlanguage.patternLanguage.PatternCall;
import org.eclipse.incquery.patternlanguage.patternLanguage.PatternCompositionConstraint;
import org.eclipse.incquery.patternlanguage.patternLanguage.PatternLanguagePackage;
import org.eclipse.incquery.patternlanguage.patternLanguage.ValueReference;
import org.eclipse.incquery.patternlanguage.patternLanguage.Variable;
import org.eclipse.incquery.patternlanguage.patternLanguage.VariableValue;
import org.eclipse.incquery.patternlanguage.validation.UnionFindForVariables;
import org.eclipse.xtext.validation.Check;
import com.google.inject.Inject;
/**
* Validators for EMFPattern Language:
* <ul>
* <li>Duplicate import of EPackages</li>
* <li>Enum types</li>
* <li>Unused variables</li>
* <li>Type checking for parameters and body variables</li>
* <li>Type checking for literal and computational values in pattern calls, path expressions and compare constraints
* <li>Pattern body searching for isolated constraints (cartesian products)</li>
* <li>Non-EDataTypes in check expression</li>
* </ul>
*/
public class EMFPatternLanguageJavaValidator extends AbstractEMFPatternLanguageJavaValidator {
@Inject
private IMetamodelProvider metamodelProvider;
@Inject
private IEMFTypeProvider emfTypeProvider;
@Override
protected List<EPackage> getEPackages() {
// PatternLanguagePackage must be added to the defaults, otherwise the core language validators not used in the
// validation process
List<EPackage> result = super.getEPackages();
result.add(PatternLanguagePackage.eINSTANCE);
return result;
}
@Check
public void checkDuplicatePackageImports(PatternModel patternModel) {
List<PackageImport> importPackages = EMFPatternLanguageHelper.getAllPackageImports(patternModel);
for (int i = 0; i < importPackages.size(); ++i) {
EPackage leftPackage = importPackages.get(i).getEPackage();
for (int j = i + 1; j < importPackages.size(); ++j) {
EPackage rightPackage = importPackages.get(j).getEPackage();
if (leftPackage.equals(rightPackage)) {
warning("Duplicate import of " + leftPackage.getNsURI(),
EMFPatternLanguagePackage.Literals.PATTERN_MODEL__IMPORT_PACKAGES, i,
EMFIssueCodes.DUPLICATE_IMPORT);
warning("Duplicate import of " + rightPackage.getNsURI(),
EMFPatternLanguagePackage.Literals.PATTERN_MODEL__IMPORT_PACKAGES, j,
EMFIssueCodes.DUPLICATE_IMPORT);
}
}
}
}
@Check
public void checkPackageImportGeneratedCode(PackageImport packageImport) {
if (packageImport.getEPackage() != null
&& packageImport.getEPackage().getNsURI() != null
&& !metamodelProvider.isGeneratedCodeAvailable(packageImport.getEPackage(), packageImport.eResource()
.getResourceSet())) {
warning(String.format(
"The generated code of the Ecore model %s cannot be found. Check the org.eclipse.emf.ecore.generated_package extension in the model project or consider setting up a generator model for the generated code to work.",
packageImport.getEPackage().getNsURI()),
EMFPatternLanguagePackage.Literals.PACKAGE_IMPORT__EPACKAGE,
EMFIssueCodes.IMPORT_WITH_GENERATEDCODE);
}
}
@Check
public void checkParametersNamed(Pattern pattern) {
for (Variable var : pattern.getParameters()) {
if (var.getName().startsWith("_")) {
error("Parameter name must not start with _", var, PatternLanguagePackage.Literals.VARIABLE__NAME,
EMFIssueCodes.SINGLEUSE_PARAMETER);
}
}
}
@Check
public void checkEnumValues(EnumValue value) {
if (value.eContainer() instanceof PathExpressionHead) {
// If container is PathExpression check for enum type assignability
EEnum enumType = value.getEnumeration();
if (enumType == null && value.getLiteral() != null) {
enumType = value.getLiteral().getEEnum();
}
PathExpressionHead expression = (PathExpressionHead) value.eContainer();
try {
EEnum expectedType = EMFPatternLanguageScopeHelper.calculateEnumerationType(expression);
if (enumType != null && !expectedType.equals(enumType)) {
error(String.format("Inconsistent enumeration types: found %s but expected %s", enumType.getName(),
expectedType.getName()), value, EMFPatternLanguagePackage.Literals.ENUM_VALUE__ENUMERATION,
EMFIssueCodes.INVALID_ENUM_LITERAL);
}
} catch (ResolutionException e) {
// EClassifier type = EMFPatternLanguageScopeHelper.calculateExpressionType(expression);
error(String.format("Invalid enumeration constant %s", enumType.getName()), value,
EMFPatternLanguagePackage.Literals.ENUM_VALUE__ENUMERATION, EMFIssueCodes.INVALID_ENUM_LITERAL);
}
}
}
/**
* The parameter's type must be the same or more specific than the type inferred from the pattern's body. This
* warning usually arises when we have more pattern bodies, which contains different type definitions for the same
* parameter. In a case like this the common parameter's type is the most specific common supertype of the
* respective calculated types in the bodies.
*
* @param pattern
*/
@Check
public void checkPatternParametersType(Pattern pattern) {
for (Variable variable : pattern.getParameters()) {
EClassifier classifierCorrect = emfTypeProvider.getClassifierForVariable(variable);
EClassifier classifierDefined = emfTypeProvider.getClassifierForType(variable.getType());
if (classifierCorrect == null || classifierDefined == null || classifierDefined.equals(classifierCorrect)) {
// Either correct - they are the same, or other validator returns the type error
return;
} else {
if (classifierCorrect instanceof EClass && classifierDefined instanceof EClass) {
if (((EClass) classifierDefined).getEAllSuperTypes().contains(classifierCorrect)) {
// Correct the defined is more specific than what the pattern needs
return;
}
}
// OK, issue warning now
warning(String.format(
"Inconsistent parameter type definition, should be %s based on the pattern definition",
classifierCorrect.getName()), variable, null, EMFIssueCodes.PARAMETER_TYPE_INVALID);
}
}
}
/**
* A variable's type can come from different sources: parameter's type definition, type definitions in the pattern
* bodies or calculated from path expression constraints or find calls. In these situations one variable might have
* conflicting type definitions. In conflicting situations if a variable's multiple types have a common subtype
* (which would ensure a pattern match runtime) and has a type defined as a parameter, than this type will be
* selected. In other cases we don't select a random type from the possibilities, the validator returns with an
* error. Note, if the multiple type definitions are related in subtype-supertype relations than the most specific
* is selected naturally (this is not even a warning).
*
* @param pattern
*/
@Check
public void checkPatternVariablesType(Pattern pattern) {
for (PatternBody patternBody : pattern.getBodies()) {
for (Variable variable : patternBody.getVariables()) {
Set<EClassifier> possibleClassifiers = emfTypeProvider.getPossibleClassifiersForVariableInBody(
patternBody, variable);
// We only need to give warnings/errors if there is more possible classifiers
if (possibleClassifiers.size() > 1) {
Set<String> classifierNamesSet = new HashSet<String>();
Set<String> classifierPackagesSet = new HashSet<String>();
for (EClassifier classifier : possibleClassifiers) {
classifierNamesSet.add(classifier.getName());
if (classifier.getEPackage() != null) {
classifierPackagesSet.add(classifier.getEPackage().getName());
}
}
// If the String sets contains only 1 elements than it is an error
// There is some element which is defined multiple types within the ecores
if (classifierNamesSet.size() == 1 && classifierPackagesSet.size() <= 1) {
error("Variable has a type which has multiple definitions: " + classifierNamesSet, variable
.getReferences().get(0), null, EMFIssueCodes.VARIABLE_TYPE_MULTIPLE_DECLARATION);
} else {
EClassifier classifier = emfTypeProvider.getClassifierForPatternParameterVariable(variable);
PatternModel patternModel = (PatternModel) patternBody.eContainer().eContainer();
if (classifier != null && possibleClassifiers.contains(classifier)
&& hasCommonSubType(patternModel, possibleClassifiers)) {
warning("Ambiguous variable type defintions: " + classifierNamesSet
+ ", the parameter type (" + classifier.getName() + ") is used now.", variable
.getReferences().get(0), null, EMFIssueCodes.VARIABLE_TYPE_INVALID_WARNING);
} else {
boolean isParameter = false;
for (Variable parameter : pattern.getParameters()) {
if (parameter.getName().equals(variable.getName())) {
isParameter = true;
}
}
if (isParameter) {
error("Ambiguous variable type defintions: "
+ classifierNamesSet
+ ", type cannot be selected. Please specify the one to be used as the parameter type"
+ " by adding it to the parameter definition.",
variable.getReferences().get(0), null,
EMFIssueCodes.VARIABLE_TYPE_INVALID_ERROR);
} else {
error("Inconsistent variable type defintions: " + classifierNamesSet
+ ", type cannot be selected.", variable.getReferences().get(0), null,
EMFIssueCodes.VARIABLE_TYPE_INVALID_ERROR);
}
}
}
}
}
}
}
/**
* @param patternModel
* @param classifiers
* @return True if the given classifiers has a common subtype. The {@link PatternModel} is needed for focusing the
* search, all ecore packages referenced from the patternmodel's head, and it's subpackages will be searched
* for common subtype elements.
*/
private boolean hasCommonSubType(PatternModel patternModel, Set<EClassifier> classifiers) {
Set<EClass> realSubTypes = new HashSet<EClass>();
Set<EClassifier> probableSubTypes = new HashSet<EClassifier>();
for (PackageImport packageImport : EMFPatternLanguageHelper.getPackageImportsIterable(patternModel)) {
probableSubTypes.addAll(getAllEClassifiers(packageImport.getEPackage()));
}
for (EClassifier classifier : probableSubTypes) {
if (classifier instanceof EClass) {
EClass eClass = (EClass) classifier;
if (eClass.getEAllSuperTypes().containsAll(classifiers)) {
realSubTypes.add(eClass);
}
}
}
return !realSubTypes.isEmpty();
}
/**
* @param ePackage
* @return all EClassifiers contained in the ePackage, and in the subpackages as well
*/
private static Set<EClassifier> getAllEClassifiers(EPackage ePackage) {
Set<EClassifier> resultSet = new HashSet<EClassifier>();
resultSet.addAll(ePackage.getEClassifiers());
for (EPackage subEPackage : ePackage.getESubpackages()) {
resultSet.addAll(subEPackage.getEClassifiers());
}
return resultSet;
}
/**
* A validator for cartesian products (isolated constraints) in pattern bodies. There are two types of warnings:
* strict and soft. Strict warning means that there are constraints in the body which has no connection at all, in
* soft cases they connected at least with a count find. The validator's result always just a warning, however a
* strict warning usually a modeling design flaw which should be corrected.
*
* @param patternBody
*/
@Check
public void checkForCartesianProduct(PatternBody patternBody) {
List<Variable> variables = patternBody.getVariables();
variables.removeAll(CorePatternLanguageHelper.getUnnamedRunningVariables(patternBody));
UnionFindForVariables justPositiveUnionFindForVariables = new UnionFindForVariables(variables);
UnionFindForVariables generalUnionFindForVariables = new UnionFindForVariables(variables);
boolean isSecondRunNeeded = false;
// First run
// Just put together the real positive connections, and all of the general connections first
for (Constraint constraint : patternBody.getConstraints()) {
Set<Variable> positiveVariables = new HashSet<Variable>();
Set<Variable> generalVariables = new HashSet<Variable>();
if (constraint instanceof CompareConstraint) {
// Equality and inequality (==, !=)
CompareConstraint compareConstraint = (CompareConstraint) constraint;
ValueReference leftValueReference = compareConstraint.getLeftOperand();
ValueReference rightValueReference = compareConstraint.getRightOperand();
Set<Variable> leftVariables = CorePatternLanguageHelper
.getVariablesFromValueReference(leftValueReference);
Set<Variable> rightVariables = CorePatternLanguageHelper
.getVariablesFromValueReference(rightValueReference);
if (CompareFeature.EQUALITY.equals(compareConstraint.getFeature())) {
// Equality ==
if (!isValueReferenceAggregated(leftValueReference)
&& !isValueReferenceAggregated(rightValueReference)) {
positiveVariables.addAll(leftVariables);
positiveVariables.addAll(rightVariables);
generalVariables.addAll(leftVariables);
generalVariables.addAll(rightVariables);
} else {
isSecondRunNeeded = true;
generalVariables.addAll(leftVariables);
generalVariables.addAll(rightVariables);
}
} else if (CompareFeature.INEQUALITY.equals(compareConstraint.getFeature())) {
// Inequality !=
generalVariables.addAll(leftVariables);
generalVariables.addAll(rightVariables);
}
} else if (constraint instanceof PatternCompositionConstraint) {
// Find and neg-find constructs
PatternCompositionConstraint patternCompositionConstraint = (PatternCompositionConstraint) constraint;
if (!patternCompositionConstraint.isNegative()) {
// Positive composition (find)
for (ValueReference valueReference : patternCompositionConstraint.getCall().getParameters()) {
if (!isValueReferenceAggregated(valueReference)) {
positiveVariables.addAll(CorePatternLanguageHelper
.getVariablesFromValueReference(valueReference));
generalVariables.addAll(CorePatternLanguageHelper
.getVariablesFromValueReference(valueReference));
} else {
isSecondRunNeeded = true;
generalVariables.addAll(CorePatternLanguageHelper
.getVariablesFromValueReference(valueReference));
}
}
} else {
// Negative composition (neg find)
for (ValueReference valueReference : patternCompositionConstraint.getCall().getParameters()) {
generalVariables.addAll(CorePatternLanguageHelper
.getVariablesFromValueReference(valueReference));
}
}
} else if (constraint instanceof PathExpressionConstraint) {
// Normal attribute-reference constraint
PathExpressionConstraint pathExpressionConstraint = (PathExpressionConstraint) constraint;
PathExpressionHead pathExpressionHead = pathExpressionConstraint.getHead();
ValueReference valueReference = pathExpressionHead.getDst();
+ Variable pathExpressionHeadSourceVariable = null;
+ if (pathExpressionHead.getSrc() != null) {
+ pathExpressionHeadSourceVariable = pathExpressionHead.getSrc().getVariable();
+ }
if (!isValueReferenceAggregated(valueReference)) {
positiveVariables.addAll(CorePatternLanguageHelper.getVariablesFromValueReference(valueReference));
- positiveVariables.add(pathExpressionHead.getSrc().getVariable());
+ positiveVariables.add(pathExpressionHeadSourceVariable);
generalVariables.addAll(CorePatternLanguageHelper.getVariablesFromValueReference(valueReference));
- generalVariables.add(pathExpressionHead.getSrc().getVariable());
+ generalVariables.add(pathExpressionHeadSourceVariable);
} else {
isSecondRunNeeded = true;
generalVariables.addAll(CorePatternLanguageHelper.getVariablesFromValueReference(valueReference));
- generalVariables.add(pathExpressionHead.getSrc().getVariable());
+ generalVariables.add(pathExpressionHeadSourceVariable);
}
} else if (constraint instanceof CheckConstraint) {
// Variables used together in check expression, always negative
CheckConstraint checkConstraint = (CheckConstraint) constraint;
generalVariables.addAll(CorePatternLanguageHelper
.getReferencedPatternVariablesOfXExpression(checkConstraint.getExpression()));
}
justPositiveUnionFindForVariables.unite(positiveVariables);
generalUnionFindForVariables.unite(generalVariables);
}
// Second run
// If variables in an aggregated formula (e.g.: count find Pattern(X,Y)) are in the same union in the positive
// case then they are considered to be in a positive relation with the respective target as well
// M == count find Pattern(X,Y), so M with X and Y is positive if X and Y is positive
// If the aggregated contains unnamed/running vars it should be omitted during the positive relation checking
if (isSecondRunNeeded) {
for (Constraint constraint : patternBody.getConstraints()) {
Set<Variable> positiveVariables = new HashSet<Variable>();
if (constraint instanceof CompareConstraint) {
CompareConstraint compareConstraint = (CompareConstraint) constraint;
if (CompareFeature.EQUALITY.equals(compareConstraint.getFeature())) {
// Equality (==), with aggregates in it
ValueReference leftValueReference = compareConstraint.getLeftOperand();
ValueReference rightValueReference = compareConstraint.getRightOperand();
if (isValueReferenceAggregated(leftValueReference)
|| isValueReferenceAggregated(rightValueReference)) {
Set<Variable> leftVariables = CorePatternLanguageHelper
.getVariablesFromValueReference(leftValueReference);
Set<Variable> rightVariables = CorePatternLanguageHelper
.getVariablesFromValueReference(rightValueReference);
if (justPositiveUnionFindForVariables.isSameUnion(leftVariables)) {
positiveVariables.addAll(leftVariables);
}
if (justPositiveUnionFindForVariables.isSameUnion(rightVariables)) {
positiveVariables.addAll(rightVariables);
}
}
}
} else if (constraint instanceof PatternCompositionConstraint) {
PatternCompositionConstraint patternCompositionConstraint = (PatternCompositionConstraint) constraint;
if (!patternCompositionConstraint.isNegative()) {
// Positive composition (find), with aggregates in it
for (ValueReference valueReference : patternCompositionConstraint.getCall().getParameters()) {
Set<Variable> actualVariables = CorePatternLanguageHelper
.getVariablesFromValueReference(valueReference);
if (justPositiveUnionFindForVariables.isSameUnion(actualVariables)) {
positiveVariables.addAll(actualVariables);
}
}
}
} else if (constraint instanceof PathExpressionConstraint) {
// Normal attribute-reference constraint, with aggregates in it
PathExpressionConstraint pathExpressionConstraint = (PathExpressionConstraint) constraint;
PathExpressionHead pathExpressionHead = pathExpressionConstraint.getHead();
- positiveVariables.add(pathExpressionHead.getSrc().getVariable());
+ Variable pathExpressionHeadSourceVariable = null;
+ if (pathExpressionHead.getSrc() != null) {
+ pathExpressionHeadSourceVariable = pathExpressionHead.getSrc().getVariable();
+ }
+ positiveVariables.add(pathExpressionHeadSourceVariable);
ValueReference valueReference = pathExpressionHead.getDst();
Set<Variable> actualVariables = CorePatternLanguageHelper
.getVariablesFromValueReference(valueReference);
if (justPositiveUnionFindForVariables.isSameUnion(actualVariables)) {
positiveVariables.addAll(actualVariables);
}
}
justPositiveUnionFindForVariables.unite(positiveVariables);
}
}
if (generalUnionFindForVariables.isMoreThanOneUnion()) {
// Giving strict warning in this case
warning("The pattern body contains isolated constraints (\"cartesian products\") that can lead to severe performance and memory footprint issues. The independent partitions are: "
+ generalUnionFindForVariables.getCurrentPartitionsFormatted() + ".", patternBody, null,
EMFIssueCodes.CARTESIAN_STRICT_WARNING);
} else if (justPositiveUnionFindForVariables.isMoreThanOneUnion()) {
// Giving soft warning in this case
warning("The pattern body contains constraints which are only loosely connected. This may negatively impact performance. The weakly dependent partitions are: "
+ justPositiveUnionFindForVariables.getCurrentPartitionsFormatted(), patternBody, null,
EMFIssueCodes.CARTESIAN_SOFT_WARNING);
}
}
private static boolean isValueReferenceAggregated(ValueReference valueReference) {
return valueReference instanceof AggregatedValue;
}
/**
* This validator checks if the literal or computational values match the other side's type in a compare constraint
* (equality/inequality). Both sides can be literal, we will do the check if at least on side is that.
*
* @param compareConstraint
*/
@Check
public void checkForWrongLiteralAndComputationValuesInCompareConstraints(CompareConstraint compareConstraint) {
// Equality and inequality (==, !=)
ValueReference leftValueReference = compareConstraint.getLeftOperand();
ValueReference rightValueReference = compareConstraint.getRightOperand();
if ((leftValueReference instanceof LiteralValueReference || leftValueReference instanceof ComputationValue
|| rightValueReference instanceof LiteralValueReference || rightValueReference instanceof ComputationValue)
&& !(leftValueReference instanceof VariableValue) && !(rightValueReference instanceof VariableValue)) {
EClassifier leftClassifier = EMFPatternTypeUtil
.getClassifierForLiteralComputationEnumValueReference(leftValueReference);
EClassifier rightClassifier = EMFPatternTypeUtil
.getClassifierForLiteralComputationEnumValueReference(rightValueReference);
if (!isCompatibleClassifiers(leftClassifier, rightClassifier)) {
error("The types of the literal/computational values are different: "
+ leftClassifier.getInstanceClassName() + ", " + rightClassifier.getInstanceClassName() + ".",
compareConstraint, null, EMFIssueCodes.LITERAL_OR_COMPUTATION_TYPE_MISMATCH_IN_COMPARE);
}
}
}
/**
* This validator checks if the literal or computational values match the path expression's type.
*
* @param pathExpressionConstraint
*/
@Check
public void checkForWrongLiteralAndComputationValuesInPathExpressionConstraints(
PathExpressionConstraint pathExpressionConstraint) {
// Normal attribute-reference constraint
PathExpressionHead pathExpressionHead = pathExpressionConstraint.getHead();
ValueReference valueReference = pathExpressionHead.getDst();
if (valueReference instanceof LiteralValueReference || valueReference instanceof ComputationValue) {
EClassifier inputClassifier = EMFPatternTypeUtil
.getClassifierForLiteralComputationEnumValueReference(valueReference);
EClassifier typeClassifier = EMFPatternTypeUtil.getClassifierForType(EMFPatternTypeUtil
.getTypeFromPathExpressionTail(pathExpressionHead.getTail()));
if (!isCompatibleClassifiers(typeClassifier, inputClassifier)) {
error("The type infered from the path expression (" + typeClassifier.getInstanceClassName()
+ ") is different from the input literal/computational value ("
+ inputClassifier.getInstanceClassName() + ").", pathExpressionConstraint, null,
EMFIssueCodes.LITERAL_OR_COMPUTATION_TYPE_MISMATCH_IN_PATH_EXPRESSION);
}
}
}
/**
* This validator checks if the literal or computational values match the pattern call's type.
*
* @param patternCall
*/
@Check
public void checkForWrongLiteralAndComputationValuesInPatternCalls(PatternCall patternCall) {
// Find and neg find (including count find as well)
for (ValueReference valueReference : patternCall.getParameters()) {
if (valueReference instanceof LiteralValueReference || valueReference instanceof ComputationValue) {
Pattern pattern = patternCall.getPatternRef();
Variable variable = pattern.getParameters().get(patternCall.getParameters().indexOf(valueReference));
EClassifier typeClassifier = emfTypeProvider.getClassifierForVariable(variable);
EClassifier inputClassifier = EMFPatternTypeUtil
.getClassifierForLiteralComputationEnumValueReference(valueReference);
if (!isCompatibleClassifiers(typeClassifier, inputClassifier)) {
error("The type infered from the called pattern (" + typeClassifier.getInstanceClassName()
+ ") is different from the input literal/computational value ("
+ inputClassifier.getInstanceClassName() + ").", patternCall, null,
EMFIssueCodes.LITERAL_OR_COMPUTATION_TYPE_MISMATCH_IN_PATTERN_CALL);
}
}
}
}
private static boolean isCompatibleClassifiers(EClassifier classifierFirst, EClassifier classifierSecond) {
if (classifierFirst != null && classifierSecond != null) {
Class<?> firstInstanceClass = classifierFirst.getInstanceClass();
Class<?> secondInstanceClass = classifierSecond.getInstanceClass();
if (firstInstanceClass.equals(secondInstanceClass)) {
return true;
} else if (firstInstanceClass.isPrimitive() || secondInstanceClass.isPrimitive()) {
Class<?> firstWrapperClass = getWrapperClassForType(firstInstanceClass);
Class<?> secondWrapperClass = getWrapperClassForType(secondInstanceClass);
if (firstWrapperClass.equals(secondWrapperClass)) {
return true;
}
}
}
return false;
}
/**
* @param typeClass
* @return The wrapper class if the input is primitive. If it is not, it returns with the input unchanged.
*/
private static Class<?> getWrapperClassForType(Class<?> typeClass) {
if (typeClass != null && typeClass.isPrimitive()) {
if (typeClass == boolean.class) {
return java.lang.Boolean.class;
} else if (typeClass == byte.class) {
return java.lang.Byte.class;
} else if (typeClass == char.class) {
return java.lang.Character.class;
} else if (typeClass == double.class) {
return java.lang.Double.class;
} else if (typeClass == float.class) {
return java.lang.Float.class;
} else if (typeClass == int.class) {
return java.lang.Integer.class;
} else if (typeClass == long.class) {
return java.lang.Long.class;
} else if (typeClass == short.class) {
return java.lang.Short.class;
}
}
return typeClass;
}
/**
* This validator looks up all variables in the {@link CheckConstraint} and reports an error if one them is not an
* {@link EDataType} instance. We do not allow arbitrary EMF elements in, so the checks are less likely to have
* side-effects.
*
* @param checkConstraint
*/
@Check
public void checkForWrongVariablesInXExpressions(CheckConstraint checkConstraint) {
for (Variable variable : CorePatternLanguageHelper.getReferencedPatternVariablesOfXExpression(checkConstraint
.getExpression())) {
EClassifier classifier = emfTypeProvider.getClassifierForVariable(variable);
if (classifier != null && !(classifier instanceof EDataType)) {// null-check needed, otherwise code throws
// NPE for classifier.getName()
error("Only simple EDataTypes are allowed in check expressions. The variable " + variable.getName()
+ "has a type of " + classifier.getName() + ".", checkConstraint, null,
EMFIssueCodes.CHECK_CONSTRAINT_SCALAR_VARIABLE_ERROR);
}
}
}
}
| false | true | public void checkForCartesianProduct(PatternBody patternBody) {
List<Variable> variables = patternBody.getVariables();
variables.removeAll(CorePatternLanguageHelper.getUnnamedRunningVariables(patternBody));
UnionFindForVariables justPositiveUnionFindForVariables = new UnionFindForVariables(variables);
UnionFindForVariables generalUnionFindForVariables = new UnionFindForVariables(variables);
boolean isSecondRunNeeded = false;
// First run
// Just put together the real positive connections, and all of the general connections first
for (Constraint constraint : patternBody.getConstraints()) {
Set<Variable> positiveVariables = new HashSet<Variable>();
Set<Variable> generalVariables = new HashSet<Variable>();
if (constraint instanceof CompareConstraint) {
// Equality and inequality (==, !=)
CompareConstraint compareConstraint = (CompareConstraint) constraint;
ValueReference leftValueReference = compareConstraint.getLeftOperand();
ValueReference rightValueReference = compareConstraint.getRightOperand();
Set<Variable> leftVariables = CorePatternLanguageHelper
.getVariablesFromValueReference(leftValueReference);
Set<Variable> rightVariables = CorePatternLanguageHelper
.getVariablesFromValueReference(rightValueReference);
if (CompareFeature.EQUALITY.equals(compareConstraint.getFeature())) {
// Equality ==
if (!isValueReferenceAggregated(leftValueReference)
&& !isValueReferenceAggregated(rightValueReference)) {
positiveVariables.addAll(leftVariables);
positiveVariables.addAll(rightVariables);
generalVariables.addAll(leftVariables);
generalVariables.addAll(rightVariables);
} else {
isSecondRunNeeded = true;
generalVariables.addAll(leftVariables);
generalVariables.addAll(rightVariables);
}
} else if (CompareFeature.INEQUALITY.equals(compareConstraint.getFeature())) {
// Inequality !=
generalVariables.addAll(leftVariables);
generalVariables.addAll(rightVariables);
}
} else if (constraint instanceof PatternCompositionConstraint) {
// Find and neg-find constructs
PatternCompositionConstraint patternCompositionConstraint = (PatternCompositionConstraint) constraint;
if (!patternCompositionConstraint.isNegative()) {
// Positive composition (find)
for (ValueReference valueReference : patternCompositionConstraint.getCall().getParameters()) {
if (!isValueReferenceAggregated(valueReference)) {
positiveVariables.addAll(CorePatternLanguageHelper
.getVariablesFromValueReference(valueReference));
generalVariables.addAll(CorePatternLanguageHelper
.getVariablesFromValueReference(valueReference));
} else {
isSecondRunNeeded = true;
generalVariables.addAll(CorePatternLanguageHelper
.getVariablesFromValueReference(valueReference));
}
}
} else {
// Negative composition (neg find)
for (ValueReference valueReference : patternCompositionConstraint.getCall().getParameters()) {
generalVariables.addAll(CorePatternLanguageHelper
.getVariablesFromValueReference(valueReference));
}
}
} else if (constraint instanceof PathExpressionConstraint) {
// Normal attribute-reference constraint
PathExpressionConstraint pathExpressionConstraint = (PathExpressionConstraint) constraint;
PathExpressionHead pathExpressionHead = pathExpressionConstraint.getHead();
ValueReference valueReference = pathExpressionHead.getDst();
if (!isValueReferenceAggregated(valueReference)) {
positiveVariables.addAll(CorePatternLanguageHelper.getVariablesFromValueReference(valueReference));
positiveVariables.add(pathExpressionHead.getSrc().getVariable());
generalVariables.addAll(CorePatternLanguageHelper.getVariablesFromValueReference(valueReference));
generalVariables.add(pathExpressionHead.getSrc().getVariable());
} else {
isSecondRunNeeded = true;
generalVariables.addAll(CorePatternLanguageHelper.getVariablesFromValueReference(valueReference));
generalVariables.add(pathExpressionHead.getSrc().getVariable());
}
} else if (constraint instanceof CheckConstraint) {
// Variables used together in check expression, always negative
CheckConstraint checkConstraint = (CheckConstraint) constraint;
generalVariables.addAll(CorePatternLanguageHelper
.getReferencedPatternVariablesOfXExpression(checkConstraint.getExpression()));
}
justPositiveUnionFindForVariables.unite(positiveVariables);
generalUnionFindForVariables.unite(generalVariables);
}
// Second run
// If variables in an aggregated formula (e.g.: count find Pattern(X,Y)) are in the same union in the positive
// case then they are considered to be in a positive relation with the respective target as well
// M == count find Pattern(X,Y), so M with X and Y is positive if X and Y is positive
// If the aggregated contains unnamed/running vars it should be omitted during the positive relation checking
if (isSecondRunNeeded) {
for (Constraint constraint : patternBody.getConstraints()) {
Set<Variable> positiveVariables = new HashSet<Variable>();
if (constraint instanceof CompareConstraint) {
CompareConstraint compareConstraint = (CompareConstraint) constraint;
if (CompareFeature.EQUALITY.equals(compareConstraint.getFeature())) {
// Equality (==), with aggregates in it
ValueReference leftValueReference = compareConstraint.getLeftOperand();
ValueReference rightValueReference = compareConstraint.getRightOperand();
if (isValueReferenceAggregated(leftValueReference)
|| isValueReferenceAggregated(rightValueReference)) {
Set<Variable> leftVariables = CorePatternLanguageHelper
.getVariablesFromValueReference(leftValueReference);
Set<Variable> rightVariables = CorePatternLanguageHelper
.getVariablesFromValueReference(rightValueReference);
if (justPositiveUnionFindForVariables.isSameUnion(leftVariables)) {
positiveVariables.addAll(leftVariables);
}
if (justPositiveUnionFindForVariables.isSameUnion(rightVariables)) {
positiveVariables.addAll(rightVariables);
}
}
}
} else if (constraint instanceof PatternCompositionConstraint) {
PatternCompositionConstraint patternCompositionConstraint = (PatternCompositionConstraint) constraint;
if (!patternCompositionConstraint.isNegative()) {
// Positive composition (find), with aggregates in it
for (ValueReference valueReference : patternCompositionConstraint.getCall().getParameters()) {
Set<Variable> actualVariables = CorePatternLanguageHelper
.getVariablesFromValueReference(valueReference);
if (justPositiveUnionFindForVariables.isSameUnion(actualVariables)) {
positiveVariables.addAll(actualVariables);
}
}
}
} else if (constraint instanceof PathExpressionConstraint) {
// Normal attribute-reference constraint, with aggregates in it
PathExpressionConstraint pathExpressionConstraint = (PathExpressionConstraint) constraint;
PathExpressionHead pathExpressionHead = pathExpressionConstraint.getHead();
positiveVariables.add(pathExpressionHead.getSrc().getVariable());
ValueReference valueReference = pathExpressionHead.getDst();
Set<Variable> actualVariables = CorePatternLanguageHelper
.getVariablesFromValueReference(valueReference);
if (justPositiveUnionFindForVariables.isSameUnion(actualVariables)) {
positiveVariables.addAll(actualVariables);
}
}
justPositiveUnionFindForVariables.unite(positiveVariables);
}
}
if (generalUnionFindForVariables.isMoreThanOneUnion()) {
// Giving strict warning in this case
warning("The pattern body contains isolated constraints (\"cartesian products\") that can lead to severe performance and memory footprint issues. The independent partitions are: "
+ generalUnionFindForVariables.getCurrentPartitionsFormatted() + ".", patternBody, null,
EMFIssueCodes.CARTESIAN_STRICT_WARNING);
} else if (justPositiveUnionFindForVariables.isMoreThanOneUnion()) {
// Giving soft warning in this case
warning("The pattern body contains constraints which are only loosely connected. This may negatively impact performance. The weakly dependent partitions are: "
+ justPositiveUnionFindForVariables.getCurrentPartitionsFormatted(), patternBody, null,
EMFIssueCodes.CARTESIAN_SOFT_WARNING);
}
}
| public void checkForCartesianProduct(PatternBody patternBody) {
List<Variable> variables = patternBody.getVariables();
variables.removeAll(CorePatternLanguageHelper.getUnnamedRunningVariables(patternBody));
UnionFindForVariables justPositiveUnionFindForVariables = new UnionFindForVariables(variables);
UnionFindForVariables generalUnionFindForVariables = new UnionFindForVariables(variables);
boolean isSecondRunNeeded = false;
// First run
// Just put together the real positive connections, and all of the general connections first
for (Constraint constraint : patternBody.getConstraints()) {
Set<Variable> positiveVariables = new HashSet<Variable>();
Set<Variable> generalVariables = new HashSet<Variable>();
if (constraint instanceof CompareConstraint) {
// Equality and inequality (==, !=)
CompareConstraint compareConstraint = (CompareConstraint) constraint;
ValueReference leftValueReference = compareConstraint.getLeftOperand();
ValueReference rightValueReference = compareConstraint.getRightOperand();
Set<Variable> leftVariables = CorePatternLanguageHelper
.getVariablesFromValueReference(leftValueReference);
Set<Variable> rightVariables = CorePatternLanguageHelper
.getVariablesFromValueReference(rightValueReference);
if (CompareFeature.EQUALITY.equals(compareConstraint.getFeature())) {
// Equality ==
if (!isValueReferenceAggregated(leftValueReference)
&& !isValueReferenceAggregated(rightValueReference)) {
positiveVariables.addAll(leftVariables);
positiveVariables.addAll(rightVariables);
generalVariables.addAll(leftVariables);
generalVariables.addAll(rightVariables);
} else {
isSecondRunNeeded = true;
generalVariables.addAll(leftVariables);
generalVariables.addAll(rightVariables);
}
} else if (CompareFeature.INEQUALITY.equals(compareConstraint.getFeature())) {
// Inequality !=
generalVariables.addAll(leftVariables);
generalVariables.addAll(rightVariables);
}
} else if (constraint instanceof PatternCompositionConstraint) {
// Find and neg-find constructs
PatternCompositionConstraint patternCompositionConstraint = (PatternCompositionConstraint) constraint;
if (!patternCompositionConstraint.isNegative()) {
// Positive composition (find)
for (ValueReference valueReference : patternCompositionConstraint.getCall().getParameters()) {
if (!isValueReferenceAggregated(valueReference)) {
positiveVariables.addAll(CorePatternLanguageHelper
.getVariablesFromValueReference(valueReference));
generalVariables.addAll(CorePatternLanguageHelper
.getVariablesFromValueReference(valueReference));
} else {
isSecondRunNeeded = true;
generalVariables.addAll(CorePatternLanguageHelper
.getVariablesFromValueReference(valueReference));
}
}
} else {
// Negative composition (neg find)
for (ValueReference valueReference : patternCompositionConstraint.getCall().getParameters()) {
generalVariables.addAll(CorePatternLanguageHelper
.getVariablesFromValueReference(valueReference));
}
}
} else if (constraint instanceof PathExpressionConstraint) {
// Normal attribute-reference constraint
PathExpressionConstraint pathExpressionConstraint = (PathExpressionConstraint) constraint;
PathExpressionHead pathExpressionHead = pathExpressionConstraint.getHead();
ValueReference valueReference = pathExpressionHead.getDst();
Variable pathExpressionHeadSourceVariable = null;
if (pathExpressionHead.getSrc() != null) {
pathExpressionHeadSourceVariable = pathExpressionHead.getSrc().getVariable();
}
if (!isValueReferenceAggregated(valueReference)) {
positiveVariables.addAll(CorePatternLanguageHelper.getVariablesFromValueReference(valueReference));
positiveVariables.add(pathExpressionHeadSourceVariable);
generalVariables.addAll(CorePatternLanguageHelper.getVariablesFromValueReference(valueReference));
generalVariables.add(pathExpressionHeadSourceVariable);
} else {
isSecondRunNeeded = true;
generalVariables.addAll(CorePatternLanguageHelper.getVariablesFromValueReference(valueReference));
generalVariables.add(pathExpressionHeadSourceVariable);
}
} else if (constraint instanceof CheckConstraint) {
// Variables used together in check expression, always negative
CheckConstraint checkConstraint = (CheckConstraint) constraint;
generalVariables.addAll(CorePatternLanguageHelper
.getReferencedPatternVariablesOfXExpression(checkConstraint.getExpression()));
}
justPositiveUnionFindForVariables.unite(positiveVariables);
generalUnionFindForVariables.unite(generalVariables);
}
// Second run
// If variables in an aggregated formula (e.g.: count find Pattern(X,Y)) are in the same union in the positive
// case then they are considered to be in a positive relation with the respective target as well
// M == count find Pattern(X,Y), so M with X and Y is positive if X and Y is positive
// If the aggregated contains unnamed/running vars it should be omitted during the positive relation checking
if (isSecondRunNeeded) {
for (Constraint constraint : patternBody.getConstraints()) {
Set<Variable> positiveVariables = new HashSet<Variable>();
if (constraint instanceof CompareConstraint) {
CompareConstraint compareConstraint = (CompareConstraint) constraint;
if (CompareFeature.EQUALITY.equals(compareConstraint.getFeature())) {
// Equality (==), with aggregates in it
ValueReference leftValueReference = compareConstraint.getLeftOperand();
ValueReference rightValueReference = compareConstraint.getRightOperand();
if (isValueReferenceAggregated(leftValueReference)
|| isValueReferenceAggregated(rightValueReference)) {
Set<Variable> leftVariables = CorePatternLanguageHelper
.getVariablesFromValueReference(leftValueReference);
Set<Variable> rightVariables = CorePatternLanguageHelper
.getVariablesFromValueReference(rightValueReference);
if (justPositiveUnionFindForVariables.isSameUnion(leftVariables)) {
positiveVariables.addAll(leftVariables);
}
if (justPositiveUnionFindForVariables.isSameUnion(rightVariables)) {
positiveVariables.addAll(rightVariables);
}
}
}
} else if (constraint instanceof PatternCompositionConstraint) {
PatternCompositionConstraint patternCompositionConstraint = (PatternCompositionConstraint) constraint;
if (!patternCompositionConstraint.isNegative()) {
// Positive composition (find), with aggregates in it
for (ValueReference valueReference : patternCompositionConstraint.getCall().getParameters()) {
Set<Variable> actualVariables = CorePatternLanguageHelper
.getVariablesFromValueReference(valueReference);
if (justPositiveUnionFindForVariables.isSameUnion(actualVariables)) {
positiveVariables.addAll(actualVariables);
}
}
}
} else if (constraint instanceof PathExpressionConstraint) {
// Normal attribute-reference constraint, with aggregates in it
PathExpressionConstraint pathExpressionConstraint = (PathExpressionConstraint) constraint;
PathExpressionHead pathExpressionHead = pathExpressionConstraint.getHead();
Variable pathExpressionHeadSourceVariable = null;
if (pathExpressionHead.getSrc() != null) {
pathExpressionHeadSourceVariable = pathExpressionHead.getSrc().getVariable();
}
positiveVariables.add(pathExpressionHeadSourceVariable);
ValueReference valueReference = pathExpressionHead.getDst();
Set<Variable> actualVariables = CorePatternLanguageHelper
.getVariablesFromValueReference(valueReference);
if (justPositiveUnionFindForVariables.isSameUnion(actualVariables)) {
positiveVariables.addAll(actualVariables);
}
}
justPositiveUnionFindForVariables.unite(positiveVariables);
}
}
if (generalUnionFindForVariables.isMoreThanOneUnion()) {
// Giving strict warning in this case
warning("The pattern body contains isolated constraints (\"cartesian products\") that can lead to severe performance and memory footprint issues. The independent partitions are: "
+ generalUnionFindForVariables.getCurrentPartitionsFormatted() + ".", patternBody, null,
EMFIssueCodes.CARTESIAN_STRICT_WARNING);
} else if (justPositiveUnionFindForVariables.isMoreThanOneUnion()) {
// Giving soft warning in this case
warning("The pattern body contains constraints which are only loosely connected. This may negatively impact performance. The weakly dependent partitions are: "
+ justPositiveUnionFindForVariables.getCurrentPartitionsFormatted(), patternBody, null,
EMFIssueCodes.CARTESIAN_SOFT_WARNING);
}
}
|
diff --git a/src/it/fahner/mywapi/http/HttpRequest.java b/src/it/fahner/mywapi/http/HttpRequest.java
index 37cab23..fe5ff80 100644
--- a/src/it/fahner/mywapi/http/HttpRequest.java
+++ b/src/it/fahner/mywapi/http/HttpRequest.java
@@ -1,211 +1,213 @@
/*
Copyright 2013 FahnerIT
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 it.fahner.mywapi.http;
import it.fahner.mywapi.http.types.HttpContentType;
import it.fahner.mywapi.http.types.HttpRequestMethod;
import it.fahner.mywapi.http.types.HttpStatusCode;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Locale;
/**
* Represents a simplified HTTP request, that can be resolved.
* @since MyWebApi 1.0
* @author C. Fahner <[email protected]>
*/
public final class HttpRequest {
/**
* Constant that represents the string encoding method used for all requests.
* @since MyWebApi 1.0
*/
public static final String CHARSET = "UTF-8";
/**
* Constant that represents the content type for all requests sent.
* @since MyWebApi 1.0
*/
public static final String CONTENT_TYPE = "application/x-www-form-urlencoded";
/** The internal connection used to resolve this request. */
private HttpURLConnection connection;
/** Stores the request body. */
private String body;
/** The timestamp of when this request was created. */
private long created;
/** Contains the response. */
private HttpResponse response;
/**
* Creates a new (unresolved) HTTP-GET request.
* @param url The URL that points to the remote resource to retrieve
*/
public HttpRequest(String url) {
this(url, HttpRequestMethod.GET);
}
/**
* Creates a new (unresolved) HTTP request and specifies a {@link HttpRequestMethod}.
* @since MyWebApi 1.0
* @param url The URL that points to the remote resource to retrieve
* @param method The {@link HttpRequestMethod} to use
*/
public HttpRequest(String url, HttpRequestMethod method) {
this.body = "";
this.created = System.currentTimeMillis();
try {
this.connection = (HttpURLConnection) new URL(url).openConnection();
// Set the connection's request properties
connection.setRequestProperty("Accept-Charset", CHARSET);
connection.setRequestProperty("Content-Type", CONTENT_TYPE + "; charset="
+ CHARSET.toLowerCase(Locale.ENGLISH));
connection.setRequestMethod(method.name());
connection.setDoInput(true); // get data FROM the URL, should always be TRUE
HttpURLConnection.setFollowRedirects(true);
// we will implement our own caching since this is not reliable on every platform
connection.setUseCaches(false);
} catch (IOException e) {
throw new RuntimeException("HttpRequest: " + e.getMessage());
}
}
@Override
public String toString() {
return "{HttpRequest => URL('" + connection.getURL().toString() + "') }";
}
/**
* Returns a string that uniquely represents the remote resource being resolved by this HTTP request.
* <p>Requests with the same resource identity value are likely the same requests.</p>
* <p>Only the hashCode of the body is used, since the body may contain large amounts of binary data.</p>
* @since MyWebApi 1.0
* @return A string that uniquely identifies the remote resource
*/
public String getResourceIdentity() {
return connection.getRequestMethod() + connection.getURL().toExternalForm() + System.identityHashCode(body);
}
/**
* Sets the body of this HTTP request.
* @since MyWebApi 1.0
* @param body The contents of the body of this HTTP request (in UTF-8)
*/
public void setBody(String body) {
ensureUnresolved();
this.body = body;
}
/**
* Returns the current body set for this request.
* @since MyWebApi 1.0
* @return The current body (if set), <code>null</code> otherwise
*/
public String getBody() {
return this.body;
}
/**
* Returns the time when this request was created.
* @since MyWebApi 1.0
* @return Amount of milliseconds since January 1, 1970 GMT when this request was instantiated
*/
public long getCreateTime() {
return created;
}
/**
* Tries to retrieve the remote resource that this HTTP request points to.
* <p>Note: This is a synchronous operation (and blocks the current thread).</p>
* <p>This object will become immutable after it's response has been retrieved.</p>
* @since MyWebApi 1.0
* @param timeout The time in milliseconds this method can last at most
* @throws HttpRequestTimeoutException When the request took longer than the timeout value specified
* @return The simplified HTTP response to this HTTP request
*/
public HttpResponse getResponse(int timeout) throws HttpRequestTimeoutException {
if (response != null) { return response; }
connection.setRequestProperty("Content-Length", "" + Integer.toString(body.getBytes().length));
connection.setConnectTimeout(timeout);
try {
// Send the request body (if a body content was specified)
if (body.length() > 0) {
connection.setDoOutput(true); // send data TO the URL
DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
writer.writeBytes(body);
writer.flush();
writer.close();
}
// Get response
connection.connect(); // call connect just to be sure, will be ignored if already called anyways
String responseEnctype = connection.getContentEncoding();
if (responseEnctype == null) { responseEnctype = CHARSET; }
- BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), responseEnctype));
+ BufferedReader reader = new BufferedReader(
+ new InputStreamReader(connection.getInputStream(), responseEnctype), 8192
+ );
String line;
StringBuilder responseBody = connection.getContentLength() > 0
? new StringBuilder(connection.getContentLength()) : new StringBuilder();
while ((line = reader.readLine()) != null) {
responseBody.append(line);
responseBody.append('\r').append('\n');
}
reader.close();
// Build the response and return it
return new HttpResponse(
this,
HttpStatusCode.fromCode(connection.getResponseCode()),
responseBody.toString(),
new HttpContentType(
connection.getContentType() != null ? connection.getContentType() : "text/plain",
responseEnctype
), connection.getExpiration()
);
} catch (FileNotFoundException fnfe) {
return new HttpResponse(this, HttpStatusCode.NotFound);
} catch (IOException ioe) { throw new HttpRequestTimeoutException(); }
}
/**
* Checks if this HTTP request has been resolved.
* @since MyWebApi 1.0
* @return The resolved state of this request, <code>true</code> if the response is available,
* <code>false</code> otherwise
*/
public boolean isResolved() {
return response != null;
}
/**
* Ensures the consistency of this request.
* @throws HttpConsistencyException When this request has already been resolved
*/
private void ensureUnresolved() {
if (isResolved()) { throw new HttpConsistencyException(); }
}
}
| true | true | public HttpResponse getResponse(int timeout) throws HttpRequestTimeoutException {
if (response != null) { return response; }
connection.setRequestProperty("Content-Length", "" + Integer.toString(body.getBytes().length));
connection.setConnectTimeout(timeout);
try {
// Send the request body (if a body content was specified)
if (body.length() > 0) {
connection.setDoOutput(true); // send data TO the URL
DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
writer.writeBytes(body);
writer.flush();
writer.close();
}
// Get response
connection.connect(); // call connect just to be sure, will be ignored if already called anyways
String responseEnctype = connection.getContentEncoding();
if (responseEnctype == null) { responseEnctype = CHARSET; }
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), responseEnctype));
String line;
StringBuilder responseBody = connection.getContentLength() > 0
? new StringBuilder(connection.getContentLength()) : new StringBuilder();
while ((line = reader.readLine()) != null) {
responseBody.append(line);
responseBody.append('\r').append('\n');
}
reader.close();
// Build the response and return it
return new HttpResponse(
this,
HttpStatusCode.fromCode(connection.getResponseCode()),
responseBody.toString(),
new HttpContentType(
connection.getContentType() != null ? connection.getContentType() : "text/plain",
responseEnctype
), connection.getExpiration()
);
} catch (FileNotFoundException fnfe) {
return new HttpResponse(this, HttpStatusCode.NotFound);
} catch (IOException ioe) { throw new HttpRequestTimeoutException(); }
}
| public HttpResponse getResponse(int timeout) throws HttpRequestTimeoutException {
if (response != null) { return response; }
connection.setRequestProperty("Content-Length", "" + Integer.toString(body.getBytes().length));
connection.setConnectTimeout(timeout);
try {
// Send the request body (if a body content was specified)
if (body.length() > 0) {
connection.setDoOutput(true); // send data TO the URL
DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
writer.writeBytes(body);
writer.flush();
writer.close();
}
// Get response
connection.connect(); // call connect just to be sure, will be ignored if already called anyways
String responseEnctype = connection.getContentEncoding();
if (responseEnctype == null) { responseEnctype = CHARSET; }
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream(), responseEnctype), 8192
);
String line;
StringBuilder responseBody = connection.getContentLength() > 0
? new StringBuilder(connection.getContentLength()) : new StringBuilder();
while ((line = reader.readLine()) != null) {
responseBody.append(line);
responseBody.append('\r').append('\n');
}
reader.close();
// Build the response and return it
return new HttpResponse(
this,
HttpStatusCode.fromCode(connection.getResponseCode()),
responseBody.toString(),
new HttpContentType(
connection.getContentType() != null ? connection.getContentType() : "text/plain",
responseEnctype
), connection.getExpiration()
);
} catch (FileNotFoundException fnfe) {
return new HttpResponse(this, HttpStatusCode.NotFound);
} catch (IOException ioe) { throw new HttpRequestTimeoutException(); }
}
|
diff --git a/src/org/openstreetmap/josm/gui/dialogs/RelationListDialog.java b/src/org/openstreetmap/josm/gui/dialogs/RelationListDialog.java
index 2dceb691..09467f70 100644
--- a/src/org/openstreetmap/josm/gui/dialogs/RelationListDialog.java
+++ b/src/org/openstreetmap/josm/gui/dialogs/RelationListDialog.java
@@ -1,303 +1,296 @@
package org.openstreetmap.josm.gui.dialogs;
import static org.openstreetmap.josm.tools.I18n.marktr;
import static org.openstreetmap.josm.tools.I18n.tr;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Collections;
import javax.swing.AbstractAction;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.openstreetmap.josm.Main;
import org.openstreetmap.josm.command.DeleteCommand;
import org.openstreetmap.josm.data.osm.DataSet;
import org.openstreetmap.josm.data.osm.OsmPrimitive;
import org.openstreetmap.josm.data.osm.Relation;
import org.openstreetmap.josm.gui.OsmPrimitivRenderer;
import org.openstreetmap.josm.gui.SideButton;
import org.openstreetmap.josm.gui.dialogs.relation.RelationEditor;
import org.openstreetmap.josm.gui.layer.DataChangeListener;
import org.openstreetmap.josm.gui.layer.Layer;
import org.openstreetmap.josm.gui.layer.OsmDataLayer;
import org.openstreetmap.josm.gui.layer.Layer.LayerChangeListener;
import org.openstreetmap.josm.tools.GBC;
import org.openstreetmap.josm.tools.ImageProvider;
import org.openstreetmap.josm.tools.Shortcut;
/**
* A dialog showing all known relations, with buttons to add, edit, and
* delete them.
*
* We don't have such dialogs for nodes, segments, and ways, because those
* objects are visible on the map and can be selected there. Relations are not.
*/
public class RelationListDialog extends ToggleDialog implements LayerChangeListener, DataChangeListener {
/**
* The selection's list data.
*/
private final DefaultListModel list = new DefaultListModel();
/**
* The display list.
*/
private JList displaylist = new JList(list);
/** the edit action */
private EditAction editAction;
/** the delete action */
private DeleteAction deleteAction;
/**
* constructor
*/
public RelationListDialog() {
super(tr("Relations"), "relationlist", tr("Open a list of all relations."),
Shortcut.registerShortcut("subwindow:relations", tr("Toggle: {0}", tr("Relations")), KeyEvent.VK_R, Shortcut.GROUP_LAYER), 150);
// create the list of relations
//
displaylist.setCellRenderer(new OsmPrimitivRenderer());
displaylist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
displaylist.addMouseListener(new MouseAdapter(){
@Override public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2 && e.getButton() == MouseEvent.BUTTON1) {
Main.main.getCurrentDataSet().setSelected((Relation)displaylist.getSelectedValue());
}
}
});
add(new JScrollPane(displaylist), BorderLayout.CENTER);
// create the panel with buttons
//
JPanel buttonPanel = new JPanel(new GridLayout(1,3));
buttonPanel.add(new SideButton(marktr("New"), "addrelation", "Selection", tr("Create a new relation"), new ActionListener() {
public void actionPerformed(ActionEvent e) {
// call relation editor with null argument to create new relation
RelationEditor.getEditor(Main.map.mapView.getEditLayer(),null, null).setVisible(true);
}
}), GBC.std());
// the edit action
//
editAction = new EditAction();
displaylist.addListSelectionListener(editAction);
- displaylist.addMouseListener(new MouseAdapter(){
- @Override public void mouseClicked(MouseEvent e) {
- if (e.getClickCount() == 2 && e.getButton() == MouseEvent.BUTTON1) {
- editAction.run();
- }
- }
- });
buttonPanel.add(new SideButton(editAction), GBC.std());
// the delete action
//
deleteAction = new DeleteAction();
displaylist.addListSelectionListener(deleteAction);
buttonPanel.add(new SideButton(deleteAction), GBC.eol());
add(buttonPanel, BorderLayout.SOUTH);
// register as layer listener
//
Layer.listeners.add(this);
}
@Override public void setVisible(boolean b) {
super.setVisible(b);
if (b) {
updateList();
}
}
protected int getNumRelations() {
if (Main.main.getCurrentDataSet() == null) return 0;
return Main.main.getCurrentDataSet().relations.size();
}
public void updateList() {
Relation selected = getSelected();
list.setSize(getNumRelations());
if (getNumRelations() > 0 ) {
int i = 0;
for (OsmPrimitive e : DataSet.sort(Main.main.getCurrentDataSet().relations)) {
if (!e.deleted && !e.incomplete) {
list.setElementAt(e, i++);
}
}
list.setSize(i);
}
if(getNumRelations() != 0) {
setTitle(tr("Relations: {0}", Main.main.getCurrentDataSet().relations.size()), true);
} else {
setTitle(tr("Relations"), false);
}
selectRelation(selected);
}
public void activeLayerChange(Layer a, Layer b) {
if ((a == null || a instanceof OsmDataLayer) && b instanceof OsmDataLayer) {
if (a != null) {
((OsmDataLayer)a).listenerDataChanged.remove(this);
}
((OsmDataLayer)b).listenerDataChanged.add(this);
updateList();
repaint();
}
}
public void layerRemoved(Layer a) {
if (a instanceof OsmDataLayer) {
((OsmDataLayer)a).listenerDataChanged.remove(this);
}
}
public void layerAdded(Layer a) {
if (a instanceof OsmDataLayer) {
((OsmDataLayer)a).listenerDataChanged.add(this);
}
}
public void dataChanged(OsmDataLayer l) {
updateList();
repaint();
}
/**
* Returns the currently selected relation, or null.
*
* @return the currently selected relation, or null
*/
public Relation getCurrentRelation() {
return (Relation) displaylist.getSelectedValue();
}
/**
* Adds a selection listener to the relation list.
*
* @param listener the listener to add
*/
public void addListSelectionListener(ListSelectionListener listener) {
displaylist.addListSelectionListener(listener);
}
/**
* Removes a selection listener from the relation list.
*
* @param listener the listener to remove
*/
public void removeListSelectionListener(ListSelectionListener listener) {
displaylist.removeListSelectionListener(listener);
}
/**
* @return The selected relation in the list
*/
private Relation getSelected() {
if(list.size() == 1) {
displaylist.setSelectedIndex(0);
}
return (Relation) displaylist.getSelectedValue();
}
/**
* Selects the relation <code>relation</code> in the list of relations.
*
* @param relation the relation
*/
public void selectRelation(Relation relation) {
if (relation == null)
{
displaylist.clearSelection();
return;
}
int i = -1;
for (i=0; i < list.getSize(); i++) {
Relation r = (Relation)list.get(i);
if (r == relation) {
break;
}
}
if (i >= 0 && i < list.getSize()) {
displaylist.setSelectedIndex(i);
displaylist.ensureIndexIsVisible(i);
}
else
{
displaylist.clearSelection();
}
}
/**
* The edit action
*
*/
class EditAction extends AbstractAction implements ListSelectionListener, Runnable{
public EditAction() {
putValue(SHORT_DESCRIPTION,tr( "Open an editor for the selected relation"));
putValue(NAME, tr("Edit"));
putValue(SMALL_ICON, ImageProvider.get("dialogs", "edit"));
setEnabled(false);
}
public void run() {
if (!isEnabled()) return;
Relation toEdit = getSelected();
if (toEdit == null)
return;
RelationEditor.getEditor(Main.map.mapView.getEditLayer(),toEdit, null).setVisible(true);
}
public void actionPerformed(ActionEvent e) {
run();
}
public void valueChanged(ListSelectionEvent e) {
setEnabled(displaylist.getSelectedIndices() != null && displaylist.getSelectedIndices().length > 0);
}
}
/**
* The delete action
*
*/
class DeleteAction extends AbstractAction implements ListSelectionListener, Runnable {
public DeleteAction() {
putValue(SHORT_DESCRIPTION,tr("Delete the selected relation"));
putValue(NAME, tr("Delete"));
putValue(SMALL_ICON, ImageProvider.get("dialogs", "delete"));
setEnabled(false);
}
public void run() {
if (!isEnabled()) return;
Relation toDelete = getSelected();
if (toDelete == null)
return;
Main.main.undoRedo.add(
new DeleteCommand(Collections.singleton(toDelete)));
}
public void actionPerformed(ActionEvent e) {
run();
}
public void valueChanged(ListSelectionEvent e) {
setEnabled(displaylist.getSelectedIndices() != null && displaylist.getSelectedIndices().length > 0);
}
}
}
| true | true | public RelationListDialog() {
super(tr("Relations"), "relationlist", tr("Open a list of all relations."),
Shortcut.registerShortcut("subwindow:relations", tr("Toggle: {0}", tr("Relations")), KeyEvent.VK_R, Shortcut.GROUP_LAYER), 150);
// create the list of relations
//
displaylist.setCellRenderer(new OsmPrimitivRenderer());
displaylist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
displaylist.addMouseListener(new MouseAdapter(){
@Override public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2 && e.getButton() == MouseEvent.BUTTON1) {
Main.main.getCurrentDataSet().setSelected((Relation)displaylist.getSelectedValue());
}
}
});
add(new JScrollPane(displaylist), BorderLayout.CENTER);
// create the panel with buttons
//
JPanel buttonPanel = new JPanel(new GridLayout(1,3));
buttonPanel.add(new SideButton(marktr("New"), "addrelation", "Selection", tr("Create a new relation"), new ActionListener() {
public void actionPerformed(ActionEvent e) {
// call relation editor with null argument to create new relation
RelationEditor.getEditor(Main.map.mapView.getEditLayer(),null, null).setVisible(true);
}
}), GBC.std());
// the edit action
//
editAction = new EditAction();
displaylist.addListSelectionListener(editAction);
displaylist.addMouseListener(new MouseAdapter(){
@Override public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2 && e.getButton() == MouseEvent.BUTTON1) {
editAction.run();
}
}
});
buttonPanel.add(new SideButton(editAction), GBC.std());
// the delete action
//
deleteAction = new DeleteAction();
displaylist.addListSelectionListener(deleteAction);
buttonPanel.add(new SideButton(deleteAction), GBC.eol());
add(buttonPanel, BorderLayout.SOUTH);
// register as layer listener
//
Layer.listeners.add(this);
}
| public RelationListDialog() {
super(tr("Relations"), "relationlist", tr("Open a list of all relations."),
Shortcut.registerShortcut("subwindow:relations", tr("Toggle: {0}", tr("Relations")), KeyEvent.VK_R, Shortcut.GROUP_LAYER), 150);
// create the list of relations
//
displaylist.setCellRenderer(new OsmPrimitivRenderer());
displaylist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
displaylist.addMouseListener(new MouseAdapter(){
@Override public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2 && e.getButton() == MouseEvent.BUTTON1) {
Main.main.getCurrentDataSet().setSelected((Relation)displaylist.getSelectedValue());
}
}
});
add(new JScrollPane(displaylist), BorderLayout.CENTER);
// create the panel with buttons
//
JPanel buttonPanel = new JPanel(new GridLayout(1,3));
buttonPanel.add(new SideButton(marktr("New"), "addrelation", "Selection", tr("Create a new relation"), new ActionListener() {
public void actionPerformed(ActionEvent e) {
// call relation editor with null argument to create new relation
RelationEditor.getEditor(Main.map.mapView.getEditLayer(),null, null).setVisible(true);
}
}), GBC.std());
// the edit action
//
editAction = new EditAction();
displaylist.addListSelectionListener(editAction);
buttonPanel.add(new SideButton(editAction), GBC.std());
// the delete action
//
deleteAction = new DeleteAction();
displaylist.addListSelectionListener(deleteAction);
buttonPanel.add(new SideButton(deleteAction), GBC.eol());
add(buttonPanel, BorderLayout.SOUTH);
// register as layer listener
//
Layer.listeners.add(this);
}
|
diff --git a/url-shortener-domain/src/test/java/com/repaskys/domain/ShortUrlTest.java b/url-shortener-domain/src/test/java/com/repaskys/domain/ShortUrlTest.java
index fad2f9c..2d60076 100644
--- a/url-shortener-domain/src/test/java/com/repaskys/domain/ShortUrlTest.java
+++ b/url-shortener-domain/src/test/java/com/repaskys/domain/ShortUrlTest.java
@@ -1,207 +1,210 @@
/*
* Copyright 2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.repaskys.domain;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.junit.After;
import org.junit.BeforeClass;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import com.repaskys.domain.ShortUrl;
/**
* Unit tests for the ShortUrl entity class.
*
* @author Drew Repasky
*/
public class ShortUrlTest {
private static Validator validator;
private ShortUrl shortUrl;
private ConstraintViolation<ShortUrl> violation;
private Set<ConstraintViolation<ShortUrl>> constraintViolations;
@Before
public void setUp() {
shortUrl = new ShortUrl();
}
@After
public void tearDown() {
shortUrl = null;
}
@BeforeClass
public static void oneTimeSetUp() {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
}
@Test
public void testValidShortUrl() {
shortUrl.setFullUrl("http://www.google.com");
assertEquals("http://www.google.com", shortUrl.getFullUrl());
constraintViolations = validator.validate(shortUrl);
assertTrue(constraintViolations.isEmpty());
}
@Test
public void fullUrlCannotBeNull() {
constraintViolations = validator.validate(shortUrl);
assertEquals(1, constraintViolations.size());
violation = constraintViolations.iterator().next();
assertEquals("Full URL cannot be blank", violation.getMessage());
assertEquals("fullUrl", violation.getPropertyPath().toString());
}
@Test
public void fullUrlCannotBeBlank() {
shortUrl.setFullUrl("");
constraintViolations = validator.validate(shortUrl);
assertEquals(1, constraintViolations.size());
violation = constraintViolations.iterator().next();
assertEquals("Full URL cannot be blank", violation.getMessage());
assertEquals("fullUrl", violation.getPropertyPath().toString());
}
@Test
public void fullUrlCannotBeOnlySpaces() {
- Set<String> expectedErrors = new HashSet<String>() {{
- add("Full URL cannot be blank");
- add("Expected a URL (example: http://www.google.com)");
- }};
+ Set<String> expectedErrors = new HashSet<String>() {
+ private static final long serialVersionUID = 6480942588471789481L;
+ {
+ add("Full URL cannot be blank");
+ add("Expected a URL (example: http://www.google.com)");
+ }
+ };
shortUrl.setFullUrl(" ");
// this is unordered, so we compare 2 HashSets of only the error messages
constraintViolations = validator.validate(shortUrl);
Set<String> actualErrors = new HashSet<String>();
for(ConstraintViolation<ShortUrl> violation: constraintViolations) {
actualErrors.add(violation.getMessage());
assertEquals("fullUrl", violation.getPropertyPath().toString());
}
assertEquals(expectedErrors, actualErrors);
}
@Test
public void fullUrlTooLong() {
shortUrl.setFullUrl("http://www." + StringUtils.repeat("B", 486) + ".com");
constraintViolations = validator.validate(shortUrl);
assertEquals(1, constraintViolations.size());
violation = constraintViolations.iterator().next();
assertEquals("Full URL must be less than 500 characters long", violation.getMessage());
assertEquals("fullUrl", violation.getPropertyPath().toString());
}
@Test
public void fullUrlMustHaveHttpPrefix() {
shortUrl.setFullUrl("www.google.com");
constraintViolations = validator.validate(shortUrl);
assertEquals(1, constraintViolations.size());
violation = constraintViolations.iterator().next();
assertEquals("Expected a URL (example: http://www.google.com)", violation.getMessage());
assertEquals("fullUrl", violation.getPropertyPath().toString());
}
@Test
public void fullUrlCannotAllowXSSChars() {
shortUrl.setFullUrl("www.g<script>oogle.com");
constraintViolations = validator.validate(shortUrl);
assertEquals(1, constraintViolations.size());
violation = constraintViolations.iterator().next();
assertEquals("Expected a URL (example: http://www.google.com)", violation.getMessage());
assertEquals("fullUrl", violation.getPropertyPath().toString());
}
@Test
public void fullUrlCannotAllowSQLInjectionChars() {
shortUrl.setFullUrl("www.goo'gle.com");
constraintViolations = validator.validate(shortUrl);
assertEquals(1, constraintViolations.size());
violation = constraintViolations.iterator().next();
assertEquals("Expected a URL (example: http://www.google.com)", violation.getMessage());
assertEquals("fullUrl", violation.getPropertyPath().toString());
}
@Test
public void fullUrlStillValidWithoutWWW() {
shortUrl.setFullUrl("http://google.com");
constraintViolations = validator.validate(shortUrl);
assertEquals(0, constraintViolations.size());
}
@Test
public void fullUrlStillValidWithParameters() {
shortUrl.setFullUrl("http://google.com?q=repasky");
constraintViolations = validator.validate(shortUrl);
assertEquals(0, constraintViolations.size());
}
// TODO The @URL validation doesn't require a domain postfix (such as ".com"). We may want to add a regexp to check for the case where a user leaves it off.
@Test
public void fullUrlMustHaveDomainPostfix() {
shortUrl.setFullUrl("http://www.google");
constraintViolations = validator.validate(shortUrl);
assertEquals(0, constraintViolations.size());
}
@Test
public void fullUrlCanHaveUncommonDomainPostfixBiz() {
shortUrl.setFullUrl("http://repasky.biz");
constraintViolations = validator.validate(shortUrl);
assertEquals(0, constraintViolations.size());
}
@Test
public void fullUrlCanHaveUncommonDomainPostfixInfo() {
shortUrl.setFullUrl("http://repasky.info");
constraintViolations = validator.validate(shortUrl);
assertEquals(0, constraintViolations.size());
}
@Test
public void fullUrlCanHaveUncommonDomainPostfixName() {
shortUrl.setFullUrl("http://repasky.name");
constraintViolations = validator.validate(shortUrl);
assertEquals(0, constraintViolations.size());
}
@Test
public void fullUrlCanHaveUncommonDomainPostfixLy() {
shortUrl.setFullUrl("http://bit.ly");
constraintViolations = validator.validate(shortUrl);
assertEquals(0, constraintViolations.size());
}
@Test
public void shortCodeGenerated() {
Long id = new Long(125);
shortUrl.setId(id);
assertEquals(id, shortUrl.getId());
assertEquals("cb", shortUrl.getShortUrl());
}
}
| true | true | public void fullUrlCannotBeOnlySpaces() {
Set<String> expectedErrors = new HashSet<String>() {{
add("Full URL cannot be blank");
add("Expected a URL (example: http://www.google.com)");
}};
shortUrl.setFullUrl(" ");
// this is unordered, so we compare 2 HashSets of only the error messages
constraintViolations = validator.validate(shortUrl);
Set<String> actualErrors = new HashSet<String>();
for(ConstraintViolation<ShortUrl> violation: constraintViolations) {
actualErrors.add(violation.getMessage());
assertEquals("fullUrl", violation.getPropertyPath().toString());
}
assertEquals(expectedErrors, actualErrors);
}
| public void fullUrlCannotBeOnlySpaces() {
Set<String> expectedErrors = new HashSet<String>() {
private static final long serialVersionUID = 6480942588471789481L;
{
add("Full URL cannot be blank");
add("Expected a URL (example: http://www.google.com)");
}
};
shortUrl.setFullUrl(" ");
// this is unordered, so we compare 2 HashSets of only the error messages
constraintViolations = validator.validate(shortUrl);
Set<String> actualErrors = new HashSet<String>();
for(ConstraintViolation<ShortUrl> violation: constraintViolations) {
actualErrors.add(violation.getMessage());
assertEquals("fullUrl", violation.getPropertyPath().toString());
}
assertEquals(expectedErrors, actualErrors);
}
|
diff --git a/gwtN/src/cz/incad/kramerius/ngwt/client/panels/ImageContainerParent.java b/gwtN/src/cz/incad/kramerius/ngwt/client/panels/ImageContainerParent.java
index f9fa64bbe..fdf6795ea 100644
--- a/gwtN/src/cz/incad/kramerius/ngwt/client/panels/ImageContainerParent.java
+++ b/gwtN/src/cz/incad/kramerius/ngwt/client/panels/ImageContainerParent.java
@@ -1,71 +1,72 @@
package cz.incad.kramerius.ngwt.client.panels;
import java.util.HashMap;
import java.util.Hashtable;
import com.google.gwt.core.client.JsArrayString;
import com.google.gwt.dom.client.Style.Overflow;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import cz.incad.kramerius.ngwt.client.panels.fx.CustomMove;
public class ImageContainerParent extends Composite{
private FlowPanel fPanel = new FlowPanel();
private ImageContainer imageContainer = null;
private int left;
private HashMap<String, Integer> id2Index = new HashMap<String, Integer>();
private HashMap<Integer, String> index2Id = new HashMap<Integer, String>();
public ImageContainerParent(JsArrayString jsArrayString) {
super();
- Window.alert("jsArray : "+jsArrayString);
+ if (jsArrayString == null) Window.alert("error in data !");
+ if (jsArrayString.length() == 0) Window.alert("error in data !");
this.imageContainer = new ImageContainer(jsArrayString);
for (int i = 0; i < jsArrayString.length(); i++) {
id2Index.put(jsArrayString.get(i), new Integer(i));
index2Id.put(new Integer(i),jsArrayString.get(i));
}
this.fPanel.add(this.imageContainer);
this.fPanel.getElement().setId("container_view");
this.fPanel.setWidth(jsniGetWidth());
this.fPanel.getElement().getStyle().setOverflow(Overflow.HIDDEN);
initWidget(this.fPanel);
}
public ImageContainer getImageContainer() {
return imageContainer;
}
public FlowPanel getContent() {
return this.fPanel;
}
public void position(int left) {
this.left = left;
this.imageContainer.getElement().getStyle().setLeft(this.left, Unit.PX);
}
public String getId(Integer index) {
return this.index2Id.get(index);
}
public void animatePosition(int left) {
CustomMove custMove = new CustomMove(this.left, 0, left, 0);
custMove.addEffectElement(this.imageContainer.getElement());
custMove.setDuration(0.3);
custMove.play();
this.left = left;
}
public static native String jsniGetWidth() /*-{
return $wnd.getImgContainerWidth();
}-*/;
}
| true | true | public ImageContainerParent(JsArrayString jsArrayString) {
super();
Window.alert("jsArray : "+jsArrayString);
this.imageContainer = new ImageContainer(jsArrayString);
for (int i = 0; i < jsArrayString.length(); i++) {
id2Index.put(jsArrayString.get(i), new Integer(i));
index2Id.put(new Integer(i),jsArrayString.get(i));
}
this.fPanel.add(this.imageContainer);
this.fPanel.getElement().setId("container_view");
this.fPanel.setWidth(jsniGetWidth());
this.fPanel.getElement().getStyle().setOverflow(Overflow.HIDDEN);
initWidget(this.fPanel);
}
| public ImageContainerParent(JsArrayString jsArrayString) {
super();
if (jsArrayString == null) Window.alert("error in data !");
if (jsArrayString.length() == 0) Window.alert("error in data !");
this.imageContainer = new ImageContainer(jsArrayString);
for (int i = 0; i < jsArrayString.length(); i++) {
id2Index.put(jsArrayString.get(i), new Integer(i));
index2Id.put(new Integer(i),jsArrayString.get(i));
}
this.fPanel.add(this.imageContainer);
this.fPanel.getElement().setId("container_view");
this.fPanel.setWidth(jsniGetWidth());
this.fPanel.getElement().getStyle().setOverflow(Overflow.HIDDEN);
initWidget(this.fPanel);
}
|
diff --git a/datasource-spss/src/main/java/org/obiba/magma/datasource/spss/support/SpssVariableTypeMapper.java b/datasource-spss/src/main/java/org/obiba/magma/datasource/spss/support/SpssVariableTypeMapper.java
index 58d6b81f..82a8f3cd 100644
--- a/datasource-spss/src/main/java/org/obiba/magma/datasource/spss/support/SpssVariableTypeMapper.java
+++ b/datasource-spss/src/main/java/org/obiba/magma/datasource/spss/support/SpssVariableTypeMapper.java
@@ -1,76 +1,76 @@
/*
* Copyright (c) 2012 OBiBa. All rights reserved.
*
* This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0.
*
* 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 org.obiba.magma.datasource.spss.support;
import org.obiba.magma.type.AbstractValueType;
import org.obiba.magma.type.DateTimeType;
import org.obiba.magma.type.DateType;
import org.obiba.magma.type.DecimalType;
import org.obiba.magma.type.IntegerType;
import org.obiba.magma.type.TextType;
import org.opendatafoundation.data.spss.SPSSNumericVariable;
import org.opendatafoundation.data.spss.SPSSRecordType2;
import org.opendatafoundation.data.spss.SPSSVariable;
public class SpssVariableTypeMapper {
private SpssVariableTypeMapper() {
}
public static AbstractValueType map(SPSSVariable variable) {
return variable instanceof SPSSNumericVariable ? mapNumericType(variable) : TextType.get();
}
public static SpssNumericDataType getSpssNumericDataType(SPSSVariable variable) {
if(!(variable instanceof SPSSNumericVariable)) {
throw new IllegalArgumentException("Variable must be of type " + SPSSNumericVariable.class);
}
SPSSRecordType2 variableRecord = variable.variableRecord;
return SpssNumericDataType.fromInt(variableRecord.getWriteFormatType());
}
private static AbstractValueType mapNumericType(SPSSVariable variable) {
switch(getSpssNumericDataType(variable)) {
case COMMA: // comma
case DOLLAR: // dollar
case DOT: // dot
case FIXED: // fixed format (default)
case SCIENTIFIC: // scientific notation
return variable.getDecimals() > 0 ? DecimalType.get() : IntegerType.get();
- case DATE: // Date dd-mmm-yyyy or dd-mmm-yy
case ADATE: // Date in mm/dd/yy or mm/dd/yyyy
case EDATE: // Date in dd.mm.yy or dd.mm.yyyy
case SDATE: // Date in yyyy/mm/dd or yy/mm/dd (?)
return DateType.get();
case DATETIME: // DateTime in dd-mmm-yyyy hh:mm, dd-mmm-yyyy hh:mm:ss or dd-mmm-yyyy hh:mm:ss.ss
return DateTimeType.get();
+ case DATE: // Date dd-mmm-yyyy or dd-mmm-yy
case TIME: // Time in hh:mm, hh:mm:ss or hh:mm:ss.ss
case JDATE: // Date in yyyyddd or yyddd
case DTIME: // DateTime in ddd:hh:mm, ddd:hh:mm:ss or ddd:hh:mm:ss.ss
case WEEK_DAY: // Date as day of the week, full name or 3-letter
case MONTH: // Date 3-letter month
case MONTH_YEAR: // Date in mmm yyyy or mmm yy
case QUARTERLY_YEAR: // Date in q Q yyyy or q Q yy
case WEEK_YEAR: // Date in wk WK yyyy or wk WK yy
case CUSTOM_CURRENCY_A: // Custom currency A
case CUSTOM_CURRENCY_B: // Custom currency B
case CUSTOM_CURRENCY_C: // Custom currency C
case CUSTOM_CURRENCY_D: // Custom currency D
case CUSTOM_CURRENCY_E: // Custom currency E
default:
return TextType.get();
}
}
}
| false | true | private static AbstractValueType mapNumericType(SPSSVariable variable) {
switch(getSpssNumericDataType(variable)) {
case COMMA: // comma
case DOLLAR: // dollar
case DOT: // dot
case FIXED: // fixed format (default)
case SCIENTIFIC: // scientific notation
return variable.getDecimals() > 0 ? DecimalType.get() : IntegerType.get();
case DATE: // Date dd-mmm-yyyy or dd-mmm-yy
case ADATE: // Date in mm/dd/yy or mm/dd/yyyy
case EDATE: // Date in dd.mm.yy or dd.mm.yyyy
case SDATE: // Date in yyyy/mm/dd or yy/mm/dd (?)
return DateType.get();
case DATETIME: // DateTime in dd-mmm-yyyy hh:mm, dd-mmm-yyyy hh:mm:ss or dd-mmm-yyyy hh:mm:ss.ss
return DateTimeType.get();
case TIME: // Time in hh:mm, hh:mm:ss or hh:mm:ss.ss
case JDATE: // Date in yyyyddd or yyddd
case DTIME: // DateTime in ddd:hh:mm, ddd:hh:mm:ss or ddd:hh:mm:ss.ss
case WEEK_DAY: // Date as day of the week, full name or 3-letter
case MONTH: // Date 3-letter month
case MONTH_YEAR: // Date in mmm yyyy or mmm yy
case QUARTERLY_YEAR: // Date in q Q yyyy or q Q yy
case WEEK_YEAR: // Date in wk WK yyyy or wk WK yy
case CUSTOM_CURRENCY_A: // Custom currency A
case CUSTOM_CURRENCY_B: // Custom currency B
case CUSTOM_CURRENCY_C: // Custom currency C
case CUSTOM_CURRENCY_D: // Custom currency D
case CUSTOM_CURRENCY_E: // Custom currency E
default:
return TextType.get();
}
}
| private static AbstractValueType mapNumericType(SPSSVariable variable) {
switch(getSpssNumericDataType(variable)) {
case COMMA: // comma
case DOLLAR: // dollar
case DOT: // dot
case FIXED: // fixed format (default)
case SCIENTIFIC: // scientific notation
return variable.getDecimals() > 0 ? DecimalType.get() : IntegerType.get();
case ADATE: // Date in mm/dd/yy or mm/dd/yyyy
case EDATE: // Date in dd.mm.yy or dd.mm.yyyy
case SDATE: // Date in yyyy/mm/dd or yy/mm/dd (?)
return DateType.get();
case DATETIME: // DateTime in dd-mmm-yyyy hh:mm, dd-mmm-yyyy hh:mm:ss or dd-mmm-yyyy hh:mm:ss.ss
return DateTimeType.get();
case DATE: // Date dd-mmm-yyyy or dd-mmm-yy
case TIME: // Time in hh:mm, hh:mm:ss or hh:mm:ss.ss
case JDATE: // Date in yyyyddd or yyddd
case DTIME: // DateTime in ddd:hh:mm, ddd:hh:mm:ss or ddd:hh:mm:ss.ss
case WEEK_DAY: // Date as day of the week, full name or 3-letter
case MONTH: // Date 3-letter month
case MONTH_YEAR: // Date in mmm yyyy or mmm yy
case QUARTERLY_YEAR: // Date in q Q yyyy or q Q yy
case WEEK_YEAR: // Date in wk WK yyyy or wk WK yy
case CUSTOM_CURRENCY_A: // Custom currency A
case CUSTOM_CURRENCY_B: // Custom currency B
case CUSTOM_CURRENCY_C: // Custom currency C
case CUSTOM_CURRENCY_D: // Custom currency D
case CUSTOM_CURRENCY_E: // Custom currency E
default:
return TextType.get();
}
}
|
diff --git a/src-pos/com/openbravo/pos/scripting/ScriptFactory.java b/src-pos/com/openbravo/pos/scripting/ScriptFactory.java
index 8e7b90b..cbae05f 100644
--- a/src-pos/com/openbravo/pos/scripting/ScriptFactory.java
+++ b/src-pos/com/openbravo/pos/scripting/ScriptFactory.java
@@ -1,51 +1,50 @@
// Openbravo POS is a point of sales application designed for touch screens.
// Copyright (C) 2007 Openbravo, S.L.
// http://sourceforge.net/projects/openbravopos
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.openbravo.pos.scripting;
/**
*
* @author adrianromero
* Created on 5 de marzo de 2007, 19:56
*
*/
public class ScriptFactory {
public static final String VELOCITY = "velocity";
public static final String BEANSHELL = "beanshell";
public static final String RHINO = "rhino";
/** Creates a new instance of ScriptFactory */
private ScriptFactory() {
}
public static ScriptEngine getScriptEngine(String name) throws ScriptException {
if (VELOCITY.equals(name)) {
return new ScriptEngineVelocity();
} else if (BEANSHELL.equals(name)) {
-// return new ScriptEngineBeanshell();
- return new ScriptEngineRhino();
- } else if (RHINO.equals(name)) {
- return new ScriptEngineRhino();
+ return new ScriptEngineBeanshell();
+// } else if (RHINO.equals(name)) {
+// return new ScriptEngineRhino();
// } else if (name.startsWith("generic:")) {
// return new ScriptEngineGeneric(name.substring(8));
} else {
throw new ScriptException("Script engine not found: " + name);
}
}
}
| true | true | public static ScriptEngine getScriptEngine(String name) throws ScriptException {
if (VELOCITY.equals(name)) {
return new ScriptEngineVelocity();
} else if (BEANSHELL.equals(name)) {
// return new ScriptEngineBeanshell();
return new ScriptEngineRhino();
} else if (RHINO.equals(name)) {
return new ScriptEngineRhino();
// } else if (name.startsWith("generic:")) {
// return new ScriptEngineGeneric(name.substring(8));
} else {
throw new ScriptException("Script engine not found: " + name);
}
}
| public static ScriptEngine getScriptEngine(String name) throws ScriptException {
if (VELOCITY.equals(name)) {
return new ScriptEngineVelocity();
} else if (BEANSHELL.equals(name)) {
return new ScriptEngineBeanshell();
// } else if (RHINO.equals(name)) {
// return new ScriptEngineRhino();
// } else if (name.startsWith("generic:")) {
// return new ScriptEngineGeneric(name.substring(8));
} else {
throw new ScriptException("Script engine not found: " + name);
}
}
|
diff --git a/spring-integration-mail/src/test/java/org/springframework/integration/mail/config/MessageWithContentTypeTests.java b/spring-integration-mail/src/test/java/org/springframework/integration/mail/config/MessageWithContentTypeTests.java
index ae220dbc8d..3d7caeb04f 100644
--- a/spring-integration-mail/src/test/java/org/springframework/integration/mail/config/MessageWithContentTypeTests.java
+++ b/spring-integration-mail/src/test/java/org/springframework/integration/mail/config/MessageWithContentTypeTests.java
@@ -1,100 +1,100 @@
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.mail.config;
import static junit.framework.Assert.assertEquals;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.FileReader;
import java.io.StringWriter;
import java.util.Properties;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import org.junit.Ignore;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.integration.Message;
import org.springframework.integration.MessageChannel;
import org.springframework.integration.mail.MailHeaders;
import org.springframework.integration.mail.MailSendingMessageHandler;
import org.springframework.integration.message.GenericMessage;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.util.FileCopyUtils;
/**
* @author Oleg Zhurakousky
*
*/
public class MessageWithContentTypeTests {
@Test
@Ignore
public void testSendEmail() throws Exception{
ApplicationContext ac = new ClassPathXmlApplicationContext("MessageWithContentTypeTests-context.xml", this.getClass());
MessageChannel inputChannel = ac.getBean("inputChannel", MessageChannel.class);
StringWriter writer = new StringWriter();
FileReader reader = new FileReader("src/test/java/org/springframework/integration/mail/config/test.html");
FileCopyUtils.copy(reader, writer);
inputChannel.send(new GenericMessage<String>(writer.getBuffer().toString()));
}
@Test
public void testMessageConversionWithHtmlAndContentType() throws Exception{
JavaMailSender sender = mock(JavaMailSender.class);
MailSendingMessageHandler handler = new MailSendingMessageHandler(sender);
StringWriter writer = new StringWriter();
- FileReader reader = new FileReader("test.html");
+ FileReader reader = new FileReader("src/test/java/org/springframework/integration/mail/config/test.html");
FileCopyUtils.copy(reader, writer);
Message<String> message = MessageBuilder.withPayload(writer.getBuffer().toString())
.setHeader(MailHeaders.TO, "to")
.setHeader(MailHeaders.FROM, "from")
.setHeader(MailHeaders.CONTENT_TYPE, "text/html")
.build();
MimeMessage mMessage = new TestMimeMessage();
// MOCKS
when(sender.createMimeMessage()).thenReturn(mMessage);
doAnswer(new Answer<Object>() {
public Object answer(InvocationOnMock invocation) throws Throwable {
MimeMessage mimeMessage = (MimeMessage) invocation.getArguments()[0];
assertEquals("text/html", mimeMessage.getDataHandler().getContentType());
return null;
}
}).when(sender).send(Mockito.any(MimeMessage.class));
// handle message
handler.handleMessage(message);
verify(sender, times(1)).send(Mockito.any(MimeMessage.class));
}
private static class TestMimeMessage extends MimeMessage{
public TestMimeMessage() {
super(Session.getDefaultInstance(new Properties()));
}
}
}
| true | true | public void testMessageConversionWithHtmlAndContentType() throws Exception{
JavaMailSender sender = mock(JavaMailSender.class);
MailSendingMessageHandler handler = new MailSendingMessageHandler(sender);
StringWriter writer = new StringWriter();
FileReader reader = new FileReader("test.html");
FileCopyUtils.copy(reader, writer);
Message<String> message = MessageBuilder.withPayload(writer.getBuffer().toString())
.setHeader(MailHeaders.TO, "to")
.setHeader(MailHeaders.FROM, "from")
.setHeader(MailHeaders.CONTENT_TYPE, "text/html")
.build();
MimeMessage mMessage = new TestMimeMessage();
// MOCKS
when(sender.createMimeMessage()).thenReturn(mMessage);
doAnswer(new Answer<Object>() {
public Object answer(InvocationOnMock invocation) throws Throwable {
MimeMessage mimeMessage = (MimeMessage) invocation.getArguments()[0];
assertEquals("text/html", mimeMessage.getDataHandler().getContentType());
return null;
}
}).when(sender).send(Mockito.any(MimeMessage.class));
// handle message
handler.handleMessage(message);
verify(sender, times(1)).send(Mockito.any(MimeMessage.class));
}
| public void testMessageConversionWithHtmlAndContentType() throws Exception{
JavaMailSender sender = mock(JavaMailSender.class);
MailSendingMessageHandler handler = new MailSendingMessageHandler(sender);
StringWriter writer = new StringWriter();
FileReader reader = new FileReader("src/test/java/org/springframework/integration/mail/config/test.html");
FileCopyUtils.copy(reader, writer);
Message<String> message = MessageBuilder.withPayload(writer.getBuffer().toString())
.setHeader(MailHeaders.TO, "to")
.setHeader(MailHeaders.FROM, "from")
.setHeader(MailHeaders.CONTENT_TYPE, "text/html")
.build();
MimeMessage mMessage = new TestMimeMessage();
// MOCKS
when(sender.createMimeMessage()).thenReturn(mMessage);
doAnswer(new Answer<Object>() {
public Object answer(InvocationOnMock invocation) throws Throwable {
MimeMessage mimeMessage = (MimeMessage) invocation.getArguments()[0];
assertEquals("text/html", mimeMessage.getDataHandler().getContentType());
return null;
}
}).when(sender).send(Mockito.any(MimeMessage.class));
// handle message
handler.handleMessage(message);
verify(sender, times(1)).send(Mockito.any(MimeMessage.class));
}
|
diff --git a/src/name/gano/file/SaveImageFile.java b/src/name/gano/file/SaveImageFile.java
index 93e00c9..fedea10 100644
--- a/src/name/gano/file/SaveImageFile.java
+++ b/src/name/gano/file/SaveImageFile.java
@@ -1,96 +1,97 @@
/*
* SaveImageFile.java
* Utility class to help save images to a file -- lets you specify compression if the format supports it
*
* =====================================================================
* Copyright (C) 2008 Shawn E. Gano
*
* This file is part of JSatTrak.
*
* JSatTrak 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.
*
* JSatTrak 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 JSatTrak. If not, see <http://www.gnu.org/licenses/>.
* =====================================================================
*/
package name.gano.file;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Iterator;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.FileImageOutputStream;
/**
*
* @author Shawn Gano, 13 November 2008
*/
public class SaveImageFile
{
public static float DEFAULT_COMPRESSION = 0.75f;
/**
* saves image, returns Eception if everything went fine this is null, otherwise it is the exception
* @param format image type, e.g.: jpg, jpeg, gif, png
* @param file what to save the image as
* @param buff image
* @return
*/
public static Exception saveImage(String format,File file, BufferedImage buff)
{
return saveImage(format,file, buff, SaveImageFile.DEFAULT_COMPRESSION);
}
/**
* saves image, returns Eception if everything went fine this is null, otherwise it is the exception
* @param format image type, e.g.: jpg, jpeg, gif, png
* @param file what to save the image as
* @param buff image
* @param compressionQuality 0.0f-1.0f , 1 = best quality
* @return
*/
public static Exception saveImage(String format,File file, BufferedImage buff, float compressionQuality)
{
Iterator iter = ImageIO.getImageWritersByFormatName(format);
ImageWriter writer = (ImageWriter)iter.next();
// instantiate an ImageWriteParam object with default compression options
ImageWriteParam iwp = writer.getDefaultWriteParam();
if(format.equalsIgnoreCase("jpg") || format.equalsIgnoreCase("JPEG") )
{
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionQuality(compressionQuality); // an integer between 0 and 1
// 1 specifies minimum compression and maximum quality
}
// write file
try
{
FileImageOutputStream output = new FileImageOutputStream(file);
writer.setOutput(output);
IIOImage image = new IIOImage(buff, null, null);
writer.write(null, image, iwp);
+ output.close(); // Fixed SEG - 22 Dec 2008
}
catch(Exception e)
{
return e;
}
// everything went smoothly
return null;
}
}
| true | true | public static Exception saveImage(String format,File file, BufferedImage buff, float compressionQuality)
{
Iterator iter = ImageIO.getImageWritersByFormatName(format);
ImageWriter writer = (ImageWriter)iter.next();
// instantiate an ImageWriteParam object with default compression options
ImageWriteParam iwp = writer.getDefaultWriteParam();
if(format.equalsIgnoreCase("jpg") || format.equalsIgnoreCase("JPEG") )
{
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionQuality(compressionQuality); // an integer between 0 and 1
// 1 specifies minimum compression and maximum quality
}
// write file
try
{
FileImageOutputStream output = new FileImageOutputStream(file);
writer.setOutput(output);
IIOImage image = new IIOImage(buff, null, null);
writer.write(null, image, iwp);
}
catch(Exception e)
{
return e;
}
// everything went smoothly
return null;
}
| public static Exception saveImage(String format,File file, BufferedImage buff, float compressionQuality)
{
Iterator iter = ImageIO.getImageWritersByFormatName(format);
ImageWriter writer = (ImageWriter)iter.next();
// instantiate an ImageWriteParam object with default compression options
ImageWriteParam iwp = writer.getDefaultWriteParam();
if(format.equalsIgnoreCase("jpg") || format.equalsIgnoreCase("JPEG") )
{
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionQuality(compressionQuality); // an integer between 0 and 1
// 1 specifies minimum compression and maximum quality
}
// write file
try
{
FileImageOutputStream output = new FileImageOutputStream(file);
writer.setOutput(output);
IIOImage image = new IIOImage(buff, null, null);
writer.write(null, image, iwp);
output.close(); // Fixed SEG - 22 Dec 2008
}
catch(Exception e)
{
return e;
}
// everything went smoothly
return null;
}
|
diff --git a/WEB-INF/src/org/cdlib/xtf/saxonExt/mail/SendElement.java b/WEB-INF/src/org/cdlib/xtf/saxonExt/mail/SendElement.java
index c523e97c..ad4ded9a 100644
--- a/WEB-INF/src/org/cdlib/xtf/saxonExt/mail/SendElement.java
+++ b/WEB-INF/src/org/cdlib/xtf/saxonExt/mail/SendElement.java
@@ -1,218 +1,218 @@
package org.cdlib.xtf.saxonExt.mail;
/*
* Copyright (c) 2007, Regents of the University of California
* 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 University of California nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.cdlib.xtf.saxonExt.InstructionWithContent;
import net.sf.saxon.expr.Expression;
import net.sf.saxon.expr.XPathContext;
import net.sf.saxon.instruct.Executable;
import net.sf.saxon.instruct.TailCall;
import net.sf.saxon.om.AttributeCollection;
import net.sf.saxon.om.Axis;
import net.sf.saxon.style.ExtensionInstruction;
import net.sf.saxon.trans.DynamicError;
import net.sf.saxon.trans.XPathException;
/**
* Implements a Saxon instruction that reads an image from the filesystem,
* optionally modifies it in various ways, and outputs it directly via the
* current HttpServletResponse.
*
* @author Martin Haye
*/
public class SendElement extends ExtensionInstruction
{
HashMap<String, Expression> outAtts = new HashMap<String, Expression>();
public void prepareAttributes()
throws XPathException
{
// Parse the attributes.
String[] mandatoryAtts = { "smtpHost", "from", "to", "subject" };
String[] optionalAtts = { "smtpUser", "smtpPassword", "useSSL" };
AttributeCollection inAtts = getAttributeList();
for (int i = 0; i < inAtts.getLength(); i++)
{
String attName = inAtts.getLocalName(i);
for (String m : mandatoryAtts) {
if (m.equals(attName))
outAtts.put(attName, makeAttributeValueTemplate(inAtts.getValue(i)));
}
for (String m : optionalAtts) {
if (m.equals(attName))
outAtts.put(attName, makeAttributeValueTemplate(inAtts.getValue(i)));
}
}
// Make sure all manditory attributes were specified
for (String m : mandatoryAtts) {
if (!outAtts.containsKey(m)) {
reportAbsence(m);
return;
}
}
} // prepareAttributes()
/**
* Determine whether this type of element is allowed to contain a template-body
*/
public boolean mayContainSequenceConstructor() {
return true;
}
public Expression compile(Executable exec)
throws XPathException
{
Expression content = compileSequenceConstructor(exec, iterateAxis(Axis.CHILD), true);
return new SendInstruction(outAtts, content);
}
private static class SendInstruction extends InstructionWithContent
{
public SendInstruction(HashMap<String, Expression> attribs, Expression content)
{
super("mail:send", attribs, content);
}
public TailCall processLeavingTail(final XPathContext context) throws XPathException
{
boolean debug = false;
try
{
// Determine the proper protocol
String protocol = "";
String useSSL = attribs.get("useSSL").evaluateAsString(context);
if (useSSL != null && useSSL.matches("^(yes|Yes|true|True|1)$"))
protocol = "smtps";
else
protocol = "smtp";
// If user name and password were specified, do authentication.
boolean doAuth = attribs.containsKey("smtpUser") && attribs.containsKey("smtpPassword");
// Set up SMTP host and authentication information
Properties props = new Properties();
String server = attribs.get("smtpHost").evaluateAsString(context);
props.put("mail." + protocol + ".host", server);
props.put("mail." + protocol + ".auth", doAuth ? "true" : "false");
// Create the mail session, with authentication if appropriate.
Session session;
if (doAuth)
{
Authenticator auth = new Authenticator()
{
public PasswordAuthentication getPasswordAuthentication()
{
try {
String username = attribs.get("smtpUser").evaluateAsString(context);
String password = attribs.get("smtpPassword").evaluateAsString(context);
return new PasswordAuthentication(username, password);
}
catch (XPathException e) {
throw new RuntimeException(e);
}
}
};
session = Session.getInstance(props, auth);
}
else
session = Session.getInstance(props);
// Set the debug mode on the session.
session.setDebug(debug);
// Create a message and specify who it's from
- Message msg = new MimeMessage(session);
+ MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(attribs.get("from").evaluateAsString(context)));
// Parse a list of recipients, separated by commas.
String recips = attribs.get("to").evaluateAsString(context).trim();
ArrayList<InternetAddress> addressTo = new ArrayList<InternetAddress>();
for (String recip : recips.split(",")) {
recip = recip.trim();
if (recip.length() > 0)
addressTo.add(new InternetAddress(recip));
}
// Add the recipient list to the message
msg.setRecipients(Message.RecipientType.TO,
addressTo.toArray(new InternetAddress[addressTo.size()]));
// Set the subject
msg.setSubject(attribs.get("subject").evaluateAsString(context));
// Convert the content to a string (we can't use evaluateAsString() since
// it only pays attention to the first item in a sequence.)
//
- msg.setContent(sequenceToString(content, context), "text/plain");
+ msg.setText(sequenceToString(content, context), "UTF-8");
msg.saveChanges();
// Finally, send the message.
Transport tr = session.getTransport(protocol);
tr.connect();
tr.sendMessage(msg, msg.getAllRecipients());
try {
tr.close();
}
catch (MessagingException e) {
// ignore errors during close()
}
}
catch (MessagingException e) {
throw new DynamicError(e);
}
catch (XPathException e) {
throw e;
}
return null;
}
}
} // class SendElement
| false | true | public TailCall processLeavingTail(final XPathContext context) throws XPathException
{
boolean debug = false;
try
{
// Determine the proper protocol
String protocol = "";
String useSSL = attribs.get("useSSL").evaluateAsString(context);
if (useSSL != null && useSSL.matches("^(yes|Yes|true|True|1)$"))
protocol = "smtps";
else
protocol = "smtp";
// If user name and password were specified, do authentication.
boolean doAuth = attribs.containsKey("smtpUser") && attribs.containsKey("smtpPassword");
// Set up SMTP host and authentication information
Properties props = new Properties();
String server = attribs.get("smtpHost").evaluateAsString(context);
props.put("mail." + protocol + ".host", server);
props.put("mail." + protocol + ".auth", doAuth ? "true" : "false");
// Create the mail session, with authentication if appropriate.
Session session;
if (doAuth)
{
Authenticator auth = new Authenticator()
{
public PasswordAuthentication getPasswordAuthentication()
{
try {
String username = attribs.get("smtpUser").evaluateAsString(context);
String password = attribs.get("smtpPassword").evaluateAsString(context);
return new PasswordAuthentication(username, password);
}
catch (XPathException e) {
throw new RuntimeException(e);
}
}
};
session = Session.getInstance(props, auth);
}
else
session = Session.getInstance(props);
// Set the debug mode on the session.
session.setDebug(debug);
// Create a message and specify who it's from
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(attribs.get("from").evaluateAsString(context)));
// Parse a list of recipients, separated by commas.
String recips = attribs.get("to").evaluateAsString(context).trim();
ArrayList<InternetAddress> addressTo = new ArrayList<InternetAddress>();
for (String recip : recips.split(",")) {
recip = recip.trim();
if (recip.length() > 0)
addressTo.add(new InternetAddress(recip));
}
// Add the recipient list to the message
msg.setRecipients(Message.RecipientType.TO,
addressTo.toArray(new InternetAddress[addressTo.size()]));
// Set the subject
msg.setSubject(attribs.get("subject").evaluateAsString(context));
// Convert the content to a string (we can't use evaluateAsString() since
// it only pays attention to the first item in a sequence.)
//
msg.setContent(sequenceToString(content, context), "text/plain");
msg.saveChanges();
// Finally, send the message.
Transport tr = session.getTransport(protocol);
tr.connect();
tr.sendMessage(msg, msg.getAllRecipients());
try {
tr.close();
}
catch (MessagingException e) {
// ignore errors during close()
}
}
catch (MessagingException e) {
throw new DynamicError(e);
}
catch (XPathException e) {
throw e;
}
return null;
}
| public TailCall processLeavingTail(final XPathContext context) throws XPathException
{
boolean debug = false;
try
{
// Determine the proper protocol
String protocol = "";
String useSSL = attribs.get("useSSL").evaluateAsString(context);
if (useSSL != null && useSSL.matches("^(yes|Yes|true|True|1)$"))
protocol = "smtps";
else
protocol = "smtp";
// If user name and password were specified, do authentication.
boolean doAuth = attribs.containsKey("smtpUser") && attribs.containsKey("smtpPassword");
// Set up SMTP host and authentication information
Properties props = new Properties();
String server = attribs.get("smtpHost").evaluateAsString(context);
props.put("mail." + protocol + ".host", server);
props.put("mail." + protocol + ".auth", doAuth ? "true" : "false");
// Create the mail session, with authentication if appropriate.
Session session;
if (doAuth)
{
Authenticator auth = new Authenticator()
{
public PasswordAuthentication getPasswordAuthentication()
{
try {
String username = attribs.get("smtpUser").evaluateAsString(context);
String password = attribs.get("smtpPassword").evaluateAsString(context);
return new PasswordAuthentication(username, password);
}
catch (XPathException e) {
throw new RuntimeException(e);
}
}
};
session = Session.getInstance(props, auth);
}
else
session = Session.getInstance(props);
// Set the debug mode on the session.
session.setDebug(debug);
// Create a message and specify who it's from
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(attribs.get("from").evaluateAsString(context)));
// Parse a list of recipients, separated by commas.
String recips = attribs.get("to").evaluateAsString(context).trim();
ArrayList<InternetAddress> addressTo = new ArrayList<InternetAddress>();
for (String recip : recips.split(",")) {
recip = recip.trim();
if (recip.length() > 0)
addressTo.add(new InternetAddress(recip));
}
// Add the recipient list to the message
msg.setRecipients(Message.RecipientType.TO,
addressTo.toArray(new InternetAddress[addressTo.size()]));
// Set the subject
msg.setSubject(attribs.get("subject").evaluateAsString(context));
// Convert the content to a string (we can't use evaluateAsString() since
// it only pays attention to the first item in a sequence.)
//
msg.setText(sequenceToString(content, context), "UTF-8");
msg.saveChanges();
// Finally, send the message.
Transport tr = session.getTransport(protocol);
tr.connect();
tr.sendMessage(msg, msg.getAllRecipients());
try {
tr.close();
}
catch (MessagingException e) {
// ignore errors during close()
}
}
catch (MessagingException e) {
throw new DynamicError(e);
}
catch (XPathException e) {
throw e;
}
return null;
}
|
diff --git a/tools/KeggConverter/src/org/pathvisio/kegg/Converter.java b/tools/KeggConverter/src/org/pathvisio/kegg/Converter.java
index 4f1b5308..37abae4b 100644
--- a/tools/KeggConverter/src/org/pathvisio/kegg/Converter.java
+++ b/tools/KeggConverter/src/org/pathvisio/kegg/Converter.java
@@ -1,378 +1,378 @@
//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.kegg;
import java.awt.Color;
import java.io.File;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.xml.rpc.ServiceException;
import keggapi.KEGGLocator;
import keggapi.KEGGPortType;
import keggapi.LinkDBRelation;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.pathvisio.debug.Logger;
import org.pathvisio.model.DataNodeType;
import org.pathvisio.model.DataSource;
import org.pathvisio.model.GpmlFormat;
import org.pathvisio.model.ObjectType;
import org.pathvisio.model.Pathway;
import org.pathvisio.model.PathwayElement;
public class Converter {
static HashMap<String, List<PathwayElement>> reaction2element =
new HashMap<String, List<PathwayElement>>();
static HashMap<String, PathwayElement> compound2element =
new HashMap<String, PathwayElement>();
static KEGGLocator locator = new KEGGLocator();
static KEGGPortType serv = null;
/**
* @param args
*/
public static void main(String[] args) {
String filename = "examples/map00031.xml";
String specie = "hsa";
//Some progress logging
Logger.log.setStream(System.out);
Logger.log.setLogLevel(true, true, true, true, true, true);
Logger.log.trace("Start converting pathway " + filename);
SAXBuilder builder = new SAXBuilder();
try {
//Setup a connection to KEGG
serv = locator.getKEGGPort();
Document doc = builder.build(new File(filename));
Element rootelement = doc.getRootElement();
List<Element> keggElements = rootelement.getChildren();
Pathway pathway = new Pathway();
int progress = 0;
for(Element child : keggElements) {
String elementName = child.getName();
String childName = child.getAttributeValue("name");
String type = child.getAttributeValue("type");
Logger.log.trace(
"Processing element " + ++progress + " out of " +
keggElements.size() + ": " + childName + ", " + type);
System.out.println("element naam = " + elementName);
//Trouwens, wil je zeker dat alle elementen zonder graphics overgeslagen worden?
if("entry".equals(elementName))
{
// Start converting elements
Element graphics = child.getChild("graphics");
/** types: map, enzyme, compound **/
if(type.equals("enzyme") && graphics != null)
{
String enzymeCode = child.getAttributeValue("name");
String[] genes = getGenes(enzymeCode, specie);
List<PathwayElement> pwElms = new ArrayList<PathwayElement>();
String[] reactions = child.getAttributeValue("reaction").split(" ");
if (genes != null && genes.length > 0)
{
for(int i = 0; i < genes.length; i++) {
String geneId = genes[i];
List<String> ncbi = getNcbiByGene(geneId);
for(int j=0; j<ncbi.size(); j++ )
{
// Name of gene j from online NCBI database
String textlabelGPML = getGeneSymbol(geneId);
// Fetch pathwayElement
PathwayElement element = createPathwayElement(child, graphics, ObjectType.DATANODE, i, textlabelGPML);
element.setDataSource(DataSource.ENTREZ_GENE);
element.setGeneID(ncbi.get(j));
element.setDataNodeType(DataNodeType.GENEPRODUCT);
pathway.add(element);
pwElms.add(element);
}
}
List<PathwayElement> reactionElements = getReactionElements(child);
for(PathwayElement e : pwElms) {
reactionElements.add(e);
}
}
else {
String textlabelGPML = enzymeCode;
int i = 0;
// Fetch pathwayElement
PathwayElement element = createPathwayElement(child, graphics, ObjectType.DATANODE, i, textlabelGPML);
pathway.add(element);
getReactionElements(child).add(element);
}
}
else if(type.equals("compound"))
{
String compoundName = child.getAttributeValue("name");
int i = 0;
// Fetch pathwayElement
PathwayElement element = createPathwayElement(child, graphics, ObjectType.DATANODE, i, compoundName);
element.setDataNodeType(DataNodeType.METABOLITE);
pathway.add(element);
compound2element.put(compoundName, element);
}
else if(type.equals("map"))
{
String textlabelGPML = graphics.getAttributeValue("name");
String typeGPML = null;
int i = 0;
// Fetch pathwayElement
PathwayElement element = createPathwayElement(child, graphics, ObjectType.LABEL, i, textlabelGPML);
element.setMFontSize(150);
pathway.add(element);
}
else if(type.equals("ortholog"))
{
String textlabelGPML = graphics.getAttributeValue("name");
int i = 0;
// Fetch pathwayElement
PathwayElement element = createPathwayElement(child, graphics, ObjectType.DATANODE, i, textlabelGPML);
element.setDataNodeType(DataNodeType.UNKOWN);
pathway.add(element);
getReactionElements(child).add(element);
}
}
// End converting elements
// Start converting lines
else if ("reaction".equals(elementName)){
String reactionName = child.getAttributeValue("name");
- System.out.println("reaction " +reactionName+ " found");
+ System.err.println("reaction " +reactionName+ " found");
// Create a list of elements in relations with reaction
List<Element> reactionElements = child.getChildren();
List<PathwayElement> dataNodes = reaction2element.get(reactionName);
for(Element relation : reactionElements) {
String compoundName = relation.getAttributeValue("name");
PathwayElement start = null;
PathwayElement end = null;
if (relation.getName().equals("substrate")){
PathwayElement substrate = compound2element.get(compoundName);
start = substrate;
end = dataNodes.get(0);
}
else {
PathwayElement product = compound2element.get(compoundName);
start = dataNodes.get(0);
end = product;
}
if (start!=null && end!=null){
// Fetch pathwayLine
PathwayElement line = createPathwayLine(start, end);
pathway.add(line);
} else {
Logger.log.error("No DataNodes to connect to for reaction " + reactionName + " in " + relation.getName());
}
}
}
}
pathway.writeToXml(new File("C:/Documents and Settings/s030478/Desktop/" + filename.substring(9,17) + ".gpml"), false);
/*
//Also write to png for more convenient testing:
ImageExporter imgExport = new BatikImageExporter(ImageExporter.TYPE_PNG);
imgExport.doExport(new File(filename + ".png"), pathway);
*/
Logger.log.trace("Finished converting pathway " + filename);
} catch(Exception e) {
e.printStackTrace();
}
}
public static String[] getGenes(String ec, String species) throws RemoteException
{
//Fetch the gene IDs
return serv.get_genes_by_enzyme(ec, species);
}
public static List <String> getNcbiByGene(String gene) throws ServiceException, RemoteException
{
//KEGG code --> NCBI code
List <String> result = new ArrayList <String>();
LinkDBRelation[] links = serv.get_linkdb_by_entry(gene, "NCBI-GeneID", 1, 100);
for(LinkDBRelation ldb : links) {
result.add(ldb.getEntry_id2().substring(12));
}
return result;
}
public static String[] getCompoundsByEnzyme(String ec) throws ServiceException, RemoteException
{
//Setup a connection to KEGG
KEGGLocator locator = new KEGGLocator();
KEGGPortType serv;
serv = locator.getKEGGPort();
//Fetch the compounds names
String[] compounds = serv.get_compounds_by_enzyme(ec);
//Distinguish substrate from product
// dependent on outcome get_compounds_by_enzyme
//KEGG code --> chemical name
// no direct way @ http://www.genome.jp/kegg/soap/doc/keggapi_javadoc/keggapi/KEGGPortType.html
// though via versa is possible
return new String[] {};
}
public static PathwayElement createPathwayElement(Element entry, Element graphics, int objectType, int i, String textlabelGPML)
{
// Create new pathway element
PathwayElement element = new PathwayElement(objectType);
// Set Color
// Convert a hexadecimal color into an awt.Color object
// Remove the # before converting
String colorStringGPML = graphics.getAttributeValue("fgcolor");
Color colorGPML;
if (colorStringGPML != null)
{
colorGPML = GpmlFormat.gmmlString2Color(colorStringGPML.substring(1));
}
else
{
colorGPML = Color.BLACK;
}
element.setColor(colorGPML);
// Set x, y, width, height
String centerXGPML = graphics.getAttributeValue("x");
String centerYGPML = graphics.getAttributeValue("y");
String widthGPML = graphics.getAttributeValue("width");
String heightGPML = graphics.getAttributeValue("height");
double height = Double.parseDouble(heightGPML);
double width = Double.parseDouble(widthGPML);
double centerY = Double.parseDouble(centerYGPML) - i*height;
double centerX = Double.parseDouble(centerXGPML);
element.setMCenterX(centerX*GpmlFormat.pixel2model);
element.setMCenterY(centerY*GpmlFormat.pixel2model);
//To prevent strange gene box sized,
//try using the default
element.setMWidth(width*GpmlFormat.pixel2model);
element.setMHeight(height*GpmlFormat.pixel2model);
// Set textlabel
element.setTextLabel(textlabelGPML);
return element;
}
public static PathwayElement createPathwayLine(PathwayElement start, PathwayElement end)
{
// Create new pathway line
PathwayElement line = new PathwayElement(ObjectType.LINE);
line.setColor(Color.BLACK);
// Setting start coordinates
line.setMStartX(start.getMCenterX());
line.setMStartY(start.getMCenterY());
//TK: Quick hack, GraphId is not automatically generated,
//so set one explicitly...FIXME!
String startId = start.getGraphId();
if(startId == null) {
start.setGraphId(start.getParent().getUniqueId());
}
line.setStartGraphRef(start.getGraphId());
// Setting end coordinates
line.setMEndX(end.getMCenterX());
line.setMEndY(end.getMCenterY());
//TK: Quick hack, GraphId is not automatically generated,
//so set one explicitly...FIXME!
String endId = end.getGraphId();
if(endId == null) {
end.setGraphId(end.getParent().getUniqueId());
}
line.setEndGraphRef(end.getGraphId());
return line;
}
public static List<PathwayElement> getReactionElements(Element entry)
{
String[] reactions = entry.getAttributeValue("reaction").split(" ");
List<PathwayElement> genes = new ArrayList <PathwayElement>();
for(String reaction : reactions) {
genes = reaction2element.get(reaction);
if(genes == null) {
reaction2element.put(reaction, genes = new ArrayList<PathwayElement>());
}
}
return genes;
}
public static String getGeneSymbol(String geneId) throws RemoteException
{
String result = serv.btit(geneId);
result = result.split(" ")[1];
result = result.substring(0, result.length()-1);
return result;
}
}
| true | true | public static void main(String[] args) {
String filename = "examples/map00031.xml";
String specie = "hsa";
//Some progress logging
Logger.log.setStream(System.out);
Logger.log.setLogLevel(true, true, true, true, true, true);
Logger.log.trace("Start converting pathway " + filename);
SAXBuilder builder = new SAXBuilder();
try {
//Setup a connection to KEGG
serv = locator.getKEGGPort();
Document doc = builder.build(new File(filename));
Element rootelement = doc.getRootElement();
List<Element> keggElements = rootelement.getChildren();
Pathway pathway = new Pathway();
int progress = 0;
for(Element child : keggElements) {
String elementName = child.getName();
String childName = child.getAttributeValue("name");
String type = child.getAttributeValue("type");
Logger.log.trace(
"Processing element " + ++progress + " out of " +
keggElements.size() + ": " + childName + ", " + type);
System.out.println("element naam = " + elementName);
//Trouwens, wil je zeker dat alle elementen zonder graphics overgeslagen worden?
if("entry".equals(elementName))
{
// Start converting elements
Element graphics = child.getChild("graphics");
/** types: map, enzyme, compound **/
if(type.equals("enzyme") && graphics != null)
{
String enzymeCode = child.getAttributeValue("name");
String[] genes = getGenes(enzymeCode, specie);
List<PathwayElement> pwElms = new ArrayList<PathwayElement>();
String[] reactions = child.getAttributeValue("reaction").split(" ");
if (genes != null && genes.length > 0)
{
for(int i = 0; i < genes.length; i++) {
String geneId = genes[i];
List<String> ncbi = getNcbiByGene(geneId);
for(int j=0; j<ncbi.size(); j++ )
{
// Name of gene j from online NCBI database
String textlabelGPML = getGeneSymbol(geneId);
// Fetch pathwayElement
PathwayElement element = createPathwayElement(child, graphics, ObjectType.DATANODE, i, textlabelGPML);
element.setDataSource(DataSource.ENTREZ_GENE);
element.setGeneID(ncbi.get(j));
element.setDataNodeType(DataNodeType.GENEPRODUCT);
pathway.add(element);
pwElms.add(element);
}
}
List<PathwayElement> reactionElements = getReactionElements(child);
for(PathwayElement e : pwElms) {
reactionElements.add(e);
}
}
else {
String textlabelGPML = enzymeCode;
int i = 0;
// Fetch pathwayElement
PathwayElement element = createPathwayElement(child, graphics, ObjectType.DATANODE, i, textlabelGPML);
pathway.add(element);
getReactionElements(child).add(element);
}
}
else if(type.equals("compound"))
{
String compoundName = child.getAttributeValue("name");
int i = 0;
// Fetch pathwayElement
PathwayElement element = createPathwayElement(child, graphics, ObjectType.DATANODE, i, compoundName);
element.setDataNodeType(DataNodeType.METABOLITE);
pathway.add(element);
compound2element.put(compoundName, element);
}
else if(type.equals("map"))
{
String textlabelGPML = graphics.getAttributeValue("name");
String typeGPML = null;
int i = 0;
// Fetch pathwayElement
PathwayElement element = createPathwayElement(child, graphics, ObjectType.LABEL, i, textlabelGPML);
element.setMFontSize(150);
pathway.add(element);
}
else if(type.equals("ortholog"))
{
String textlabelGPML = graphics.getAttributeValue("name");
int i = 0;
// Fetch pathwayElement
PathwayElement element = createPathwayElement(child, graphics, ObjectType.DATANODE, i, textlabelGPML);
element.setDataNodeType(DataNodeType.UNKOWN);
pathway.add(element);
getReactionElements(child).add(element);
}
}
// End converting elements
// Start converting lines
else if ("reaction".equals(elementName)){
String reactionName = child.getAttributeValue("name");
System.out.println("reaction " +reactionName+ " found");
// Create a list of elements in relations with reaction
List<Element> reactionElements = child.getChildren();
List<PathwayElement> dataNodes = reaction2element.get(reactionName);
for(Element relation : reactionElements) {
String compoundName = relation.getAttributeValue("name");
PathwayElement start = null;
PathwayElement end = null;
if (relation.getName().equals("substrate")){
PathwayElement substrate = compound2element.get(compoundName);
start = substrate;
end = dataNodes.get(0);
}
else {
PathwayElement product = compound2element.get(compoundName);
start = dataNodes.get(0);
end = product;
}
if (start!=null && end!=null){
// Fetch pathwayLine
PathwayElement line = createPathwayLine(start, end);
pathway.add(line);
} else {
Logger.log.error("No DataNodes to connect to for reaction " + reactionName + " in " + relation.getName());
}
}
}
}
pathway.writeToXml(new File("C:/Documents and Settings/s030478/Desktop/" + filename.substring(9,17) + ".gpml"), false);
/*
//Also write to png for more convenient testing:
ImageExporter imgExport = new BatikImageExporter(ImageExporter.TYPE_PNG);
imgExport.doExport(new File(filename + ".png"), pathway);
*/
Logger.log.trace("Finished converting pathway " + filename);
} catch(Exception e) {
e.printStackTrace();
}
}
| public static void main(String[] args) {
String filename = "examples/map00031.xml";
String specie = "hsa";
//Some progress logging
Logger.log.setStream(System.out);
Logger.log.setLogLevel(true, true, true, true, true, true);
Logger.log.trace("Start converting pathway " + filename);
SAXBuilder builder = new SAXBuilder();
try {
//Setup a connection to KEGG
serv = locator.getKEGGPort();
Document doc = builder.build(new File(filename));
Element rootelement = doc.getRootElement();
List<Element> keggElements = rootelement.getChildren();
Pathway pathway = new Pathway();
int progress = 0;
for(Element child : keggElements) {
String elementName = child.getName();
String childName = child.getAttributeValue("name");
String type = child.getAttributeValue("type");
Logger.log.trace(
"Processing element " + ++progress + " out of " +
keggElements.size() + ": " + childName + ", " + type);
System.out.println("element naam = " + elementName);
//Trouwens, wil je zeker dat alle elementen zonder graphics overgeslagen worden?
if("entry".equals(elementName))
{
// Start converting elements
Element graphics = child.getChild("graphics");
/** types: map, enzyme, compound **/
if(type.equals("enzyme") && graphics != null)
{
String enzymeCode = child.getAttributeValue("name");
String[] genes = getGenes(enzymeCode, specie);
List<PathwayElement> pwElms = new ArrayList<PathwayElement>();
String[] reactions = child.getAttributeValue("reaction").split(" ");
if (genes != null && genes.length > 0)
{
for(int i = 0; i < genes.length; i++) {
String geneId = genes[i];
List<String> ncbi = getNcbiByGene(geneId);
for(int j=0; j<ncbi.size(); j++ )
{
// Name of gene j from online NCBI database
String textlabelGPML = getGeneSymbol(geneId);
// Fetch pathwayElement
PathwayElement element = createPathwayElement(child, graphics, ObjectType.DATANODE, i, textlabelGPML);
element.setDataSource(DataSource.ENTREZ_GENE);
element.setGeneID(ncbi.get(j));
element.setDataNodeType(DataNodeType.GENEPRODUCT);
pathway.add(element);
pwElms.add(element);
}
}
List<PathwayElement> reactionElements = getReactionElements(child);
for(PathwayElement e : pwElms) {
reactionElements.add(e);
}
}
else {
String textlabelGPML = enzymeCode;
int i = 0;
// Fetch pathwayElement
PathwayElement element = createPathwayElement(child, graphics, ObjectType.DATANODE, i, textlabelGPML);
pathway.add(element);
getReactionElements(child).add(element);
}
}
else if(type.equals("compound"))
{
String compoundName = child.getAttributeValue("name");
int i = 0;
// Fetch pathwayElement
PathwayElement element = createPathwayElement(child, graphics, ObjectType.DATANODE, i, compoundName);
element.setDataNodeType(DataNodeType.METABOLITE);
pathway.add(element);
compound2element.put(compoundName, element);
}
else if(type.equals("map"))
{
String textlabelGPML = graphics.getAttributeValue("name");
String typeGPML = null;
int i = 0;
// Fetch pathwayElement
PathwayElement element = createPathwayElement(child, graphics, ObjectType.LABEL, i, textlabelGPML);
element.setMFontSize(150);
pathway.add(element);
}
else if(type.equals("ortholog"))
{
String textlabelGPML = graphics.getAttributeValue("name");
int i = 0;
// Fetch pathwayElement
PathwayElement element = createPathwayElement(child, graphics, ObjectType.DATANODE, i, textlabelGPML);
element.setDataNodeType(DataNodeType.UNKOWN);
pathway.add(element);
getReactionElements(child).add(element);
}
}
// End converting elements
// Start converting lines
else if ("reaction".equals(elementName)){
String reactionName = child.getAttributeValue("name");
System.err.println("reaction " +reactionName+ " found");
// Create a list of elements in relations with reaction
List<Element> reactionElements = child.getChildren();
List<PathwayElement> dataNodes = reaction2element.get(reactionName);
for(Element relation : reactionElements) {
String compoundName = relation.getAttributeValue("name");
PathwayElement start = null;
PathwayElement end = null;
if (relation.getName().equals("substrate")){
PathwayElement substrate = compound2element.get(compoundName);
start = substrate;
end = dataNodes.get(0);
}
else {
PathwayElement product = compound2element.get(compoundName);
start = dataNodes.get(0);
end = product;
}
if (start!=null && end!=null){
// Fetch pathwayLine
PathwayElement line = createPathwayLine(start, end);
pathway.add(line);
} else {
Logger.log.error("No DataNodes to connect to for reaction " + reactionName + " in " + relation.getName());
}
}
}
}
pathway.writeToXml(new File("C:/Documents and Settings/s030478/Desktop/" + filename.substring(9,17) + ".gpml"), false);
/*
//Also write to png for more convenient testing:
ImageExporter imgExport = new BatikImageExporter(ImageExporter.TYPE_PNG);
imgExport.doExport(new File(filename + ".png"), pathway);
*/
Logger.log.trace("Finished converting pathway " + filename);
} catch(Exception e) {
e.printStackTrace();
}
}
|
diff --git a/infra/src/de/zib/gndms/infra/action/SetupUpdatingConfigletAction.java b/infra/src/de/zib/gndms/infra/action/SetupUpdatingConfigletAction.java
index 829ed35b..918c9267 100644
--- a/infra/src/de/zib/gndms/infra/action/SetupUpdatingConfigletAction.java
+++ b/infra/src/de/zib/gndms/infra/action/SetupUpdatingConfigletAction.java
@@ -1,55 +1,56 @@
package de.zib.gndms.infra.action;
/*
* Copyright 2008-2011 Zuse Institute Berlin (ZIB)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import de.zib.gndms.kit.configlet.Configlet;
import de.zib.gndms.logic.model.config.ConfigActionResult;
import de.zib.gndms.model.common.ConfigletState;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetbrains.annotations.NotNull;
import javax.persistence.EntityManager;
import java.io.PrintWriter;
import java.text.ParseException;
/**
* @author try ma ik jo rr a zib
* @date 13.04.11 14:24
* @brief Delegates the update to the configlet class.
*/
public class SetupUpdatingConfigletAction extends SetupDefaultConfigletAction {
protected Log logger = LogFactory.getLog( this.getClass() );
@Override
protected ConfigActionResult update( ConfigletState state, EntityManager emParam, PrintWriter writerParam ) {
ConfigActionResult res = super.update( state, emParam, writerParam );
try {
Class clazz = Class.forName( state.getClassName() );
Configlet conf = Configlet.class.cast( clazz.newInstance() ); // todo find class from system dict
+ conf.init( logger, state.getName(), state.getState() );
conf.update( state.getState() );
} catch ( ClassNotFoundException e ) {
logger.warn( e );
} catch ( InstantiationException e ) {
logger.warn( e );
} catch ( IllegalAccessException e ) {
logger.warn( e );
}
return res;
}
}
| true | true | protected ConfigActionResult update( ConfigletState state, EntityManager emParam, PrintWriter writerParam ) {
ConfigActionResult res = super.update( state, emParam, writerParam );
try {
Class clazz = Class.forName( state.getClassName() );
Configlet conf = Configlet.class.cast( clazz.newInstance() ); // todo find class from system dict
conf.update( state.getState() );
} catch ( ClassNotFoundException e ) {
logger.warn( e );
} catch ( InstantiationException e ) {
logger.warn( e );
} catch ( IllegalAccessException e ) {
logger.warn( e );
}
return res;
}
| protected ConfigActionResult update( ConfigletState state, EntityManager emParam, PrintWriter writerParam ) {
ConfigActionResult res = super.update( state, emParam, writerParam );
try {
Class clazz = Class.forName( state.getClassName() );
Configlet conf = Configlet.class.cast( clazz.newInstance() ); // todo find class from system dict
conf.init( logger, state.getName(), state.getState() );
conf.update( state.getState() );
} catch ( ClassNotFoundException e ) {
logger.warn( e );
} catch ( InstantiationException e ) {
logger.warn( e );
} catch ( IllegalAccessException e ) {
logger.warn( e );
}
return res;
}
|
diff --git a/src/com/xforj/productions/AbstractVariableDeclaration.java b/src/com/xforj/productions/AbstractVariableDeclaration.java
index 394e9a8..3812c70 100644
--- a/src/com/xforj/productions/AbstractVariableDeclaration.java
+++ b/src/com/xforj/productions/AbstractVariableDeclaration.java
@@ -1,84 +1,84 @@
/*
* Copyright 2012 Joseph Spencer.
*
* 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.xforj.productions;
import com.xforj.Output;
import com.xforj.CharWrapper;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
* @author Joseph Spencer
*/
public abstract class AbstractVariableDeclaration extends Production {
public AbstractVariableDeclaration(Output output) {
super(output);
}
private boolean hasValue;
@Override
public final void execute(CharWrapper characters, ProductionContext context) throws Exception {
characters.removeSpace();
String extraExcMsg="";
if(!hasValue){
+ hasValue=true;
Matcher match = characters.match(getPattern());
if(match.find()){
characters.shift(match.group(1).length());
characters.removeSpace();
Matcher nameMatch = characters.match(NAME);
if(nameMatch.find()){
String name = nameMatch.group(1);
characters.shift(name.length());
if(characters.removeSpace()){
- hasValue=true;
Output assignmentOutput = new Output();
doAssignment(name, assignmentOutput);
context.getCurrentVariableOutput().add(name, assignmentOutput);
context.addProduction(getProduction(assignmentOutput));
} else {
doNoAssignment(name, context);
}
return;
}
}
extraExcMsg=" No Name found.";
} else if(characters.charAt(0) == close){
characters.shift(1);
context.removeProduction();
return;
}
throw new Exception("Invalid "+getClassName()+"."+extraExcMsg);
}
protected abstract Pattern getPattern();
protected abstract Production getProduction(Output output);
/**
* This gives the instances a chance to add something special to the assignment.
*
* For instance, in the case of ParamDeclarations, we want the following to be
* prepended to the assignment: 'params.d||'.
*
* @param name
* @param output The Assignment Output.
* @throws Exception
*/
protected abstract void doAssignment(String name, Output output) throws Exception;
protected abstract void doNoAssignment(String name, ProductionContext context) throws Exception;
}
| false | true | public final void execute(CharWrapper characters, ProductionContext context) throws Exception {
characters.removeSpace();
String extraExcMsg="";
if(!hasValue){
Matcher match = characters.match(getPattern());
if(match.find()){
characters.shift(match.group(1).length());
characters.removeSpace();
Matcher nameMatch = characters.match(NAME);
if(nameMatch.find()){
String name = nameMatch.group(1);
characters.shift(name.length());
if(characters.removeSpace()){
hasValue=true;
Output assignmentOutput = new Output();
doAssignment(name, assignmentOutput);
context.getCurrentVariableOutput().add(name, assignmentOutput);
context.addProduction(getProduction(assignmentOutput));
} else {
doNoAssignment(name, context);
}
return;
}
}
extraExcMsg=" No Name found.";
} else if(characters.charAt(0) == close){
characters.shift(1);
context.removeProduction();
return;
}
throw new Exception("Invalid "+getClassName()+"."+extraExcMsg);
}
| public final void execute(CharWrapper characters, ProductionContext context) throws Exception {
characters.removeSpace();
String extraExcMsg="";
if(!hasValue){
hasValue=true;
Matcher match = characters.match(getPattern());
if(match.find()){
characters.shift(match.group(1).length());
characters.removeSpace();
Matcher nameMatch = characters.match(NAME);
if(nameMatch.find()){
String name = nameMatch.group(1);
characters.shift(name.length());
if(characters.removeSpace()){
Output assignmentOutput = new Output();
doAssignment(name, assignmentOutput);
context.getCurrentVariableOutput().add(name, assignmentOutput);
context.addProduction(getProduction(assignmentOutput));
} else {
doNoAssignment(name, context);
}
return;
}
}
extraExcMsg=" No Name found.";
} else if(characters.charAt(0) == close){
characters.shift(1);
context.removeProduction();
return;
}
throw new Exception("Invalid "+getClassName()+"."+extraExcMsg);
}
|
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/NdbRMStateStore.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/NdbRMStateStore.java
index a459c23..910adfd 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/NdbRMStateStore.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/NdbRMStateStore.java
@@ -1,272 +1,272 @@
/*
* Copyright 2012 Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.yarn.server.resourcemanager.recovery;
import com.google.protobuf.InvalidProtocolBufferException;
import com.mysql.clusterj.ClusterJHelper;
import com.mysql.clusterj.Query;
import com.mysql.clusterj.Session;
import com.mysql.clusterj.SessionFactory;
import com.mysql.clusterj.annotation.PersistenceCapable;
import com.mysql.clusterj.annotation.PrimaryKey;
import com.mysql.clusterj.annotation.Lob;
import com.mysql.clusterj.query.QueryBuilder;
import com.mysql.clusterj.query.QueryDomainType;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.hadoop.yarn.api.records.ApplicationAttemptId;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.ApplicationSubmissionContext;
import org.apache.hadoop.yarn.api.records.Container;
import org.apache.hadoop.yarn.api.records.impl.pb.ApplicationAttemptIdPBImpl;
import org.apache.hadoop.yarn.api.records.impl.pb.ApplicationIdPBImpl;
import org.apache.hadoop.yarn.api.records.impl.pb.ApplicationSubmissionContextPBImpl;
import org.apache.hadoop.yarn.api.records.impl.pb.ContainerPBImpl;
import org.apache.hadoop.yarn.event.Dispatcher;
import org.apache.hadoop.yarn.proto.YarnProtos;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttempt;
/**
*
* @author aknahs
*/
public class NdbRMStateStore implements RMStateStore {
Dispatcher dispatcher;
private SessionFactory factory;
private Session session;
public NdbRMStateStore() {
// Load the properties from the clusterj.properties file
File propsFile = new File("src/test/java/org/apache/hadoop/yarn/server/resourcemanager/clusterj.properties");
InputStream inStream;
try {
inStream = new FileInputStream(propsFile);
Properties props = new Properties();
props.load(inStream);
// Create a session (connection to the database)
factory = ClusterJHelper.getSessionFactory(props);
session = factory.getSession();
} catch (FileNotFoundException ex) {
//TODO : Do better log
Logger.getLogger(NdbRMStateStore.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(NdbRMStateStore.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
public void setDispatcher(Dispatcher dispatcher) {
this.dispatcher = dispatcher;
}
@Override
public RMState loadState() {
return new NdbRMState(); //TODO : needs arguments?
//return state;
}
public class NdbRMState implements RMState {
private HashMap<ApplicationId, ApplicationState> appState = null;
//new HashMap<ApplicationId, ApplicationState>();
public NdbRMState() {
appState = new HashMap<ApplicationId, ApplicationState>();
QueryDomainType<NdbApplicationStateCJ> domainApp;
QueryDomainType<NdbAttemptStateCJ> domainAttempt;
Query<NdbApplicationStateCJ> queryApp;
Query<NdbAttemptStateCJ> queryAttempt;
List<NdbApplicationStateCJ> resultsApp;
List<NdbAttemptStateCJ> resultsAttempt;
//Retrieve applicationstate table
QueryBuilder builder = session.getQueryBuilder();
domainApp = builder.createQueryDefinition(NdbApplicationStateCJ.class);
domainAttempt = builder.createQueryDefinition(NdbAttemptStateCJ.class);
queryApp = session.createQuery(domainApp);
resultsApp = queryApp.getResultList();
//Populate appState
for (NdbApplicationStateCJ storedApp : resultsApp) {
try {
ApplicationId id = new ApplicationIdPBImpl();
id.setId(storedApp.getId());
id.setClusterTimestamp(storedApp.getClusterTimeStamp());
NdbApplicationState state = new NdbApplicationState();
state.appId = id;
state.submitTime = storedApp.getSubmitTime();
state.applicationSubmissionContext =
new ApplicationSubmissionContextPBImpl(
YarnProtos.ApplicationSubmissionContextProto.parseFrom(
storedApp.getAppContext()));
state.attempts = new HashMap<ApplicationAttemptId, NdbApplicationAttemptState>();
//Populate AppAttempState in each appState
//TODO : make sure name is case sensitive
- domainAttempt.where(domainAttempt.get("ApplicationId").equal(domainAttempt.param("ApplicationId")));
+ domainAttempt.where(domainAttempt.get("applicationId").equal(domainAttempt.param("applicationId")));
queryAttempt = session.createQuery(domainAttempt);
- queryAttempt.setParameter("ApplicationId",storedApp.getId());
+ queryAttempt.setParameter("applicationId",storedApp.getId());
resultsAttempt = queryAttempt.getResultList();
for (NdbAttemptStateCJ storedAttempt : resultsAttempt) {
ApplicationAttemptId attemptId = new ApplicationAttemptIdPBImpl();
attemptId.setApplicationId(id);
attemptId.setAttemptId(storedAttempt.getAttemptId());
NdbApplicationAttemptState attemptState = new NdbApplicationAttemptState();
attemptState.masterContainer = new ContainerPBImpl(
YarnProtos.ContainerProto.parseFrom(
storedAttempt.getMasterContainer()));
state.attempts.put(attemptId, attemptState);
}
appState.put(id, state);
} catch (InvalidProtocolBufferException ex) {
//TODO : Make a more beatiful exception!
Logger.getLogger(NdbRMStateStore.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
@Override
public Map<ApplicationId, ApplicationState> getApplicationState() {
return appState;
}
}
@Override
public void storeApplication(RMApp app) {
// Create and initialise an NdbApplicationState
NdbApplicationStateCJ storedApp =
session.newInstance(NdbApplicationStateCJ.class);
storedApp.setId(app.getApplicationId().getId());
storedApp.setClusterTimeStamp(app.getApplicationId().getClusterTimestamp());
storedApp.setSubmitTime(app.getSubmitTime());
byte[] context = ((ApplicationSubmissionContextPBImpl) app.getApplicationSubmissionContext()).getProto().toByteArray();
storedApp.setAppContext(context);
//Write NdbApplicationState to ndb database
session.persist(storedApp);
}
@Override
public void storeApplicationAttempt(RMAppAttempt appAttempt) {
//TODO : check if the app is already in the ndb applicationstate table
NdbAttemptStateCJ storedAttempt =
session.newInstance(NdbAttemptStateCJ.class);
storedAttempt.setAttemptId(appAttempt.getAppAttemptId().getAttemptId());
storedAttempt.setApplicationId(
appAttempt.getAppAttemptId().getApplicationId().getId());
byte[] container = ((ContainerPBImpl) appAttempt.getMasterContainer()).getProto().toByteArray();
storedAttempt.setMasterContainer(container);
//Write NdbAttemptState to ndb database
session.persist(storedAttempt);
}
public class NdbApplicationAttemptState implements ApplicationAttemptState {
Container masterContainer;
@Override
public Container getMasterContainer() {
return masterContainer;
}
}
public class NdbApplicationState implements ApplicationState {
ApplicationId appId;
long submitTime;
ApplicationSubmissionContext applicationSubmissionContext;
HashMap<ApplicationAttemptId, NdbApplicationAttemptState> attempts =
new HashMap<ApplicationAttemptId, NdbApplicationAttemptState>();
@Override
public ApplicationId getId() {
return appId;
}
@Override
public long getSubmitTime() {
return submitTime;
}
@Override
public ApplicationSubmissionContext getApplicationSubmissionContext() {
return applicationSubmissionContext;
}
@Override
public int getAttemptCount() {
return attempts.size();
}
@Override
public ApplicationAttemptState getAttempt(ApplicationAttemptId attemptId) {
NdbApplicationAttemptState attemptState = attempts.get(attemptId);
return attemptState;
}
}
@PersistenceCapable(table = "applicationstate")
public interface NdbApplicationStateCJ {
@PrimaryKey
int getId();
void setId(int id);
long getClusterTimeStamp();
void setClusterTimeStamp(long time);
long getSubmitTime();
void setSubmitTime(long time);
@Lob
byte[] getAppContext();
void setAppContext(byte[] context);
}
@PersistenceCapable(table = "attemptstate")
public interface NdbAttemptStateCJ {
@PrimaryKey
int getAttemptId();
void setAttemptId(int id);
@PrimaryKey
int getApplicationId();
void setApplicationId(int id);
@Lob
byte[] getMasterContainer();
void setMasterContainer(byte[] state);
}
}
| false | true | public NdbRMState() {
appState = new HashMap<ApplicationId, ApplicationState>();
QueryDomainType<NdbApplicationStateCJ> domainApp;
QueryDomainType<NdbAttemptStateCJ> domainAttempt;
Query<NdbApplicationStateCJ> queryApp;
Query<NdbAttemptStateCJ> queryAttempt;
List<NdbApplicationStateCJ> resultsApp;
List<NdbAttemptStateCJ> resultsAttempt;
//Retrieve applicationstate table
QueryBuilder builder = session.getQueryBuilder();
domainApp = builder.createQueryDefinition(NdbApplicationStateCJ.class);
domainAttempt = builder.createQueryDefinition(NdbAttemptStateCJ.class);
queryApp = session.createQuery(domainApp);
resultsApp = queryApp.getResultList();
//Populate appState
for (NdbApplicationStateCJ storedApp : resultsApp) {
try {
ApplicationId id = new ApplicationIdPBImpl();
id.setId(storedApp.getId());
id.setClusterTimestamp(storedApp.getClusterTimeStamp());
NdbApplicationState state = new NdbApplicationState();
state.appId = id;
state.submitTime = storedApp.getSubmitTime();
state.applicationSubmissionContext =
new ApplicationSubmissionContextPBImpl(
YarnProtos.ApplicationSubmissionContextProto.parseFrom(
storedApp.getAppContext()));
state.attempts = new HashMap<ApplicationAttemptId, NdbApplicationAttemptState>();
//Populate AppAttempState in each appState
//TODO : make sure name is case sensitive
domainAttempt.where(domainAttempt.get("ApplicationId").equal(domainAttempt.param("ApplicationId")));
queryAttempt = session.createQuery(domainAttempt);
queryAttempt.setParameter("ApplicationId",storedApp.getId());
resultsAttempt = queryAttempt.getResultList();
for (NdbAttemptStateCJ storedAttempt : resultsAttempt) {
ApplicationAttemptId attemptId = new ApplicationAttemptIdPBImpl();
attemptId.setApplicationId(id);
attemptId.setAttemptId(storedAttempt.getAttemptId());
NdbApplicationAttemptState attemptState = new NdbApplicationAttemptState();
attemptState.masterContainer = new ContainerPBImpl(
YarnProtos.ContainerProto.parseFrom(
storedAttempt.getMasterContainer()));
state.attempts.put(attemptId, attemptState);
}
appState.put(id, state);
} catch (InvalidProtocolBufferException ex) {
//TODO : Make a more beatiful exception!
Logger.getLogger(NdbRMStateStore.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
| public NdbRMState() {
appState = new HashMap<ApplicationId, ApplicationState>();
QueryDomainType<NdbApplicationStateCJ> domainApp;
QueryDomainType<NdbAttemptStateCJ> domainAttempt;
Query<NdbApplicationStateCJ> queryApp;
Query<NdbAttemptStateCJ> queryAttempt;
List<NdbApplicationStateCJ> resultsApp;
List<NdbAttemptStateCJ> resultsAttempt;
//Retrieve applicationstate table
QueryBuilder builder = session.getQueryBuilder();
domainApp = builder.createQueryDefinition(NdbApplicationStateCJ.class);
domainAttempt = builder.createQueryDefinition(NdbAttemptStateCJ.class);
queryApp = session.createQuery(domainApp);
resultsApp = queryApp.getResultList();
//Populate appState
for (NdbApplicationStateCJ storedApp : resultsApp) {
try {
ApplicationId id = new ApplicationIdPBImpl();
id.setId(storedApp.getId());
id.setClusterTimestamp(storedApp.getClusterTimeStamp());
NdbApplicationState state = new NdbApplicationState();
state.appId = id;
state.submitTime = storedApp.getSubmitTime();
state.applicationSubmissionContext =
new ApplicationSubmissionContextPBImpl(
YarnProtos.ApplicationSubmissionContextProto.parseFrom(
storedApp.getAppContext()));
state.attempts = new HashMap<ApplicationAttemptId, NdbApplicationAttemptState>();
//Populate AppAttempState in each appState
//TODO : make sure name is case sensitive
domainAttempt.where(domainAttempt.get("applicationId").equal(domainAttempt.param("applicationId")));
queryAttempt = session.createQuery(domainAttempt);
queryAttempt.setParameter("applicationId",storedApp.getId());
resultsAttempt = queryAttempt.getResultList();
for (NdbAttemptStateCJ storedAttempt : resultsAttempt) {
ApplicationAttemptId attemptId = new ApplicationAttemptIdPBImpl();
attemptId.setApplicationId(id);
attemptId.setAttemptId(storedAttempt.getAttemptId());
NdbApplicationAttemptState attemptState = new NdbApplicationAttemptState();
attemptState.masterContainer = new ContainerPBImpl(
YarnProtos.ContainerProto.parseFrom(
storedAttempt.getMasterContainer()));
state.attempts.put(attemptId, attemptState);
}
appState.put(id, state);
} catch (InvalidProtocolBufferException ex) {
//TODO : Make a more beatiful exception!
Logger.getLogger(NdbRMStateStore.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
|
diff --git a/src/java/fedora/server/access/dissemination/DatastreamResolverServlet.java b/src/java/fedora/server/access/dissemination/DatastreamResolverServlet.java
index ee19e342d..25e4c06fd 100755
--- a/src/java/fedora/server/access/dissemination/DatastreamResolverServlet.java
+++ b/src/java/fedora/server/access/dissemination/DatastreamResolverServlet.java
@@ -1,532 +1,535 @@
package fedora.server.access.dissemination;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.security.Principal;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import fedora.common.Constants;
import fedora.server.Context;
import fedora.server.ReadOnlyContext;
import fedora.server.Server;
import fedora.server.errors.InitializationException;
import fedora.server.errors.authorization.AuthzDeniedException;
import fedora.server.errors.authorization.AuthzException;
import fedora.server.errors.authorization.AuthzOperationalException;
import fedora.server.errors.servletExceptionExtensions.RootException;
import fedora.server.security.Authorization;
import fedora.server.security.BackendPolicies;
import fedora.server.security.servletfilters.ExtendedHttpServletRequest;
import fedora.server.storage.DOManager;
import fedora.server.storage.DOReader;
import fedora.server.storage.ExternalContentManager;
import fedora.server.storage.types.Datastream;
import fedora.server.storage.types.DatastreamMediation;
import fedora.server.storage.types.MIMETypedStream;
import fedora.server.storage.types.Property;
import fedora.server.utilities.ServerUtility;
/**
* <p>
* <b>Title: </b>DatastreamResolverServlet.java
* </p>
* <p>
* <b>Description: </b>This servlet acts as a proxy to resolve the physical
* location of datastreams. It requires a single parameter named <code>id</code>
* that denotes the temporary id of the requested datastresm. This id is in the
* form of a DateTime stamp. The servlet will perform an in-memory hashtable
* lookup using the temporary id to obtain the actual physical location of the
* datastream and then return the contents of the datastream as a MIME-typed
* stream. This servlet is invoked primarily by external mechanisms needing to
* retrieve the contents of a datastream.
* </p>
* <p>
* The servlet also requires that an external mechanism request a datastream
* within a finite time interval of the tempID's creation. This is to lessen the
* risk of unauthorized access. The time interval within which a mechanism must
* repond is set by the Fedora configuration parameter named
* datastreamMediationLimit and is speci207fied in milliseconds. If this
* parameter is not supplied it defaults to 5000 miliseconds.
* </p>
*
* @author [email protected]
* @version $Id: DatastreamResolverServlet.java,v 1.50 2006/09/29 20:29:12 wdn5e
* Exp $
*/
public class DatastreamResolverServlet extends HttpServlet {
/** Logger for this class. */
private static final Logger LOG = Logger.getLogger(
DatastreamResolverServlet.class.getName());
private static final long serialVersionUID = 1L;
private static Server s_server;
private static DOManager m_manager;
private static Hashtable dsRegistry;
private static int datastreamMediationLimit;
private static final String HTML_CONTENT_TYPE = "text/html";
private static String fedoraServerHost;
private static String fedoraServerPort;
private static String fedoraServerRedirectPort;
/**
* <p>
* Initialize servlet.
* </p>
*
* @throws ServletException
* If the servet cannot be initialized.
*/
public void init() throws ServletException {
try {
s_server = Server.getInstance(new File(Constants.FEDORA_HOME),
false);
fedoraServerPort = s_server.getParameter("fedoraServerPort");
fedoraServerRedirectPort = s_server
.getParameter("fedoraRedirectPort");
fedoraServerHost = s_server.getParameter("fedoraServerHost");
m_manager = (DOManager) s_server
.getModule("fedora.server.storage.DOManager");
String expireLimit = s_server
.getParameter("datastreamMediationLimit");
if (expireLimit == null || expireLimit.equalsIgnoreCase("")) {
LOG.info("datastreamMediationLimit unspecified, using default "
+ "of 5 seconds");
datastreamMediationLimit = 5000;
} else {
datastreamMediationLimit = new Integer(expireLimit).intValue();
LOG.info("datastreamMediationLimit: "
+ datastreamMediationLimit);
}
} catch (InitializationException ie) {
throw new ServletException(
"Unable to get an instance of Fedora server " + "-- "
+ ie.getMessage());
} catch (Throwable th) {
LOG.error("Error initializing servlet", th);
}
}
private static final boolean contains(String[] array, String item) {
boolean contains = false;
for (int i = 0; i < array.length; i++) {
if (array[i].equals(item)) {
contains = true;
break;
}
}
return contains;
}
public static final String ACTION_LABEL = "Resolve Datastream";
/**
* <p>
* Processes the servlet request and resolves the physical location of the
* specified datastream.
* </p>
*
* @param request
* The servlet request.
* @param response
* servlet The servlet response.
* @throws ServletException
* If an error occurs that effects the servlet's basic
* operation.
* @throws IOException
* If an error occurrs with an input or output operation.
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String id = null;
String dsPhysicalLocation = null;
String dsControlGroupType = null;
String user = null;
String pass = null;
MIMETypedStream mimeTypedStream = null;
DisseminationService ds = null;
Timestamp keyTimestamp = null;
Timestamp currentTimestamp = null;
PrintWriter out = null;
ServletOutputStream outStream = null;
String requestURI = request.getRequestURL().toString() + "?"
+ request.getQueryString();
id = request.getParameter("id").replaceAll("T", " ");
LOG.debug("Datastream tempID=" + id);
LOG.debug("DRS doGet()");
try {
// Check for required id parameter.
if (id == null || id.equalsIgnoreCase("")) {
String message = "[DatastreamResolverServlet] No datastream ID "
+ "specified in servlet request: "
+ request.getRequestURI();
LOG.error(message);
response
.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.sendError(
HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
return;
}
id = id.replaceAll("T", " ").replaceAll("/", "").trim();
// Get in-memory hashtable of mappings from Fedora server.
ds = new DisseminationService();
dsRegistry = DisseminationService.dsRegistry;
DatastreamMediation dm = (DatastreamMediation) dsRegistry.get(id);
if (dm == null) {
StringBuffer entries = new StringBuffer();
Iterator eIter = dsRegistry.keySet().iterator();
while (eIter.hasNext()) {
entries.append("'" + (String) eIter.next() + "' ");
}
throw new IOException(
"Cannot find datastream in temp registry by key: " + id
+ "\n" + "Reg entries: " + entries.toString());
}
dsPhysicalLocation = dm.dsLocation;
dsControlGroupType = dm.dsControlGroupType;
user = dm.callUsername;
pass = dm.callPassword;
if (LOG.isDebugEnabled()) {
LOG.debug("**************************** DatastreamResolverServlet dm.dsLocation: "
+ dm.dsLocation);
LOG.debug("**************************** DatastreamResolverServlet dm.dsControlGroupType: "
+ dm.dsControlGroupType);
LOG.debug("**************************** DatastreamResolverServlet dm.callUsername: "
+ dm.callUsername);
LOG.debug("**************************** DatastreamResolverServlet dm.Password: "
+ dm.callPassword);
LOG.debug("**************************** DatastreamResolverServlet dm.callbackRole: "
+ dm.callbackRole);
LOG.debug("**************************** DatastreamResolverServlet dm.callbackBasicAuth: "
+ dm.callbackBasicAuth);
LOG.debug("**************************** DatastreamResolverServlet dm.callBasicAuth: "
+ dm.callBasicAuth);
LOG.debug("**************************** DatastreamResolverServlet dm.callbackSSl: "
+ dm.callbackSSL);
LOG.debug("**************************** DatastreamResolverServlet dm.callSSl: "
+ dm.callSSL);
LOG.debug("**************************** DatastreamResolverServlet non ssl port: "
+ fedoraServerPort);
LOG.debug("**************************** DatastreamResolverServlet ssl port: "
+ fedoraServerRedirectPort);
}
// DatastreamResolverServlet maps to two distinct servlet mappings
// in fedora web.xml.
// getDS - is used when the backend service is incapable of
// basicAuth or SSL
// getDSAuthenticated - is used when the backend service has
// basicAuth and SSL enabled
// Since both the getDS and getDSAuthenticated servlet targets map
// to the same servlet
// code and the Context used to initialize policy enforcement is
// based on the incoming
// HTTPRequest, the code must provide special handling for requests
// using the getDS
// target. When the incoming URL to DatastreamResolverServlet
// contains the getDS target,
// there are several conditions that must be checked to insure that
// the correct role is
// assigned to the request before policy enforcement occurs.
// 1) if the mapped dsPhysicalLocation of the request is actually a
// callback to the
// Fedora server itself, then assign the role as
// BACKEND_SERVICE_CALL_UNSECURE so
// the basicAuth and SSL constraints will match those of the getDS
// target.
// 2) if the mapped dsPhysicalLocation of the request is actually a
// Managed Content
// or Inline XML Content datastream, then assign the role as
// BACKEND_SERVICE_CALL_UNSECURE so
// the basicAuth and SSL constraints will match the getDS target.
// 3) Otherwise, leave the targetrole unchanged.
if (request.getRequestURI().endsWith("getDS")
&& (ServerUtility.isURLFedoraServer(dsPhysicalLocation)
|| dsControlGroupType.equals("M") || dsControlGroupType
.equals("X"))) {
if (LOG.isDebugEnabled())
LOG.debug("*********************** Changed role from: "
+ dm.callbackRole
+ " to: "
+ BackendPolicies.BACKEND_SERVICE_CALL_UNSECURE);
dm.callbackRole = BackendPolicies.BACKEND_SERVICE_CALL_UNSECURE;
}
// If callback is to fedora server itself and callback is over SSL,
// adjust the protocol and port
// on the URL to match settings of Fedora server. This is necessary
// since the SSL settings for the
// backend service may have specified basicAuth=false, but contained
// datastreams that are callbacks
// to the local Fedora server which requires SSL. The version of
// HttpClient currently in use does
// not handle autoredirecting from http to https so it is necessary
// to set the protocol and port
// to the appropriate secure port.
if (dm.callbackRole.equals(BackendPolicies.FEDORA_INTERNAL_CALL)) {
if (dm.callbackSSL) {
dsPhysicalLocation = dsPhysicalLocation.replaceFirst(
"http:", "https:");
dsPhysicalLocation = dsPhysicalLocation.replaceFirst(
fedoraServerPort, fedoraServerRedirectPort);
if (LOG.isDebugEnabled())
LOG.debug("*********************** DatastreamResolverServlet -- Was Fedora-to-Fedora call -- modified dsPhysicalLocation: "
+ dsPhysicalLocation);
}
}
keyTimestamp = Timestamp.valueOf(ds.extractTimestamp(id));
currentTimestamp = new Timestamp(new Date().getTime());
LOG.debug("dsPhysicalLocation=" + dsPhysicalLocation
+ "dsControlGroupType=" + dsControlGroupType);
// Deny mechanism requests that fall outside the specified time
// interval.
// The expiration limit can be adjusted using the Fedora config
// parameter
// named "datastreamMediationLimit" which is in milliseconds.
long diff = currentTimestamp.getTime() - keyTimestamp.getTime();
LOG.debug("Timestamp diff for mechanism's reponse: "
+ diff + " ms.");
if (diff > (long) datastreamMediationLimit) {
out = response.getWriter();
response.setContentType(HTML_CONTENT_TYPE);
out
.println("<br><b>[DatastreamResolverServlet] Error:</b>"
+ "<font color=\"red\"> Mechanism has failed to respond "
+ "to the DatastreamResolverServlet within the specified "
+ "time limit of \""
+ datastreamMediationLimit
+ "\""
+ "milliseconds. Datastream access denied.");
LOG.error("Mechanism failed to respond to "
+ "DatastreamResolverServlet within time limit of "
+ datastreamMediationLimit);
out.close();
return;
}
if (dm.callbackRole == null) {
throw new AuthzOperationalException(
"no callbackRole for this ticket");
}
String targetRole = //Authorization.FEDORA_ROLE_KEY + "=" +
dm.callbackRole; // restrict access to role of this
// ticket
String[] targetRoles = { targetRole };
Context context = ReadOnlyContext.getContext(
Constants.HTTP_REQUEST.REST.uri, request); // , targetRoles);
if (request.getRemoteUser() == null) {
// non-authn: must accept target role of ticket
LOG.debug("DatastreamResolverServlet: unAuthenticated request");
} else {
// authn: check user roles for target role of ticket
/*
LOG.debug("DatastreamResolverServlet: Authenticated request getting user");
String[] roles = null;
Principal principal = request.getUserPrincipal();
if (principal == null) {
// no principal to grok roles from!!
} else {
try {
roles = ReadOnlyContext.getRoles(principal);
} catch (Throwable t) {
}
}
if (roles == null) {
roles = new String[0];
}
*/
//XXXXXXXXXXXXXXXXXXXXXXxif (contains(roles, targetRole)) {
+ LOG.debug("DatastreamResolverServlet: user==" + request.getRemoteUser());
+ /*
if (((ExtendedHttpServletRequest)request).isUserInRole(targetRole)) {
LOG.debug("DatastreamResolverServlet: user has required role");
} else {
LOG.debug("DatastreamResolverServlet: authZ exception in validating user");
throw new AuthzDeniedException("wrong user for this ticket");
}
+ */
}
if (LOG.isDebugEnabled()) {
LOG.debug("debugging backendService role");
LOG.debug("targetRole=" + targetRole);
int targetRolesLength = targetRoles.length;
LOG.debug("targetRolesLength=" + targetRolesLength);
if (targetRolesLength > 0) {
LOG.debug("targetRoles[0]=" + targetRoles[0]);
}
int nSubjectValues = context.nSubjectValues(targetRole);
LOG.debug("nSubjectValues=" + nSubjectValues);
if (nSubjectValues > 0) {
LOG.debug("context.getSubjectValue(targetRole)="
+ context.getSubjectValue(targetRole));
}
Iterator it = context.subjectAttributes();
while (it.hasNext()) {
String name = (String) it.next();
String value = context.getSubjectValue(name);
LOG.debug("another subject attribute from context "
+ name + "=" + value);
}
it = context.environmentAttributes();
while (it.hasNext()) {
String name = (String) it.next();
String value = context.getEnvironmentValue(name);
LOG.debug("another environment attribute from context "
+ name + "=" + value);
}
}
LOG.debug("DatastreamResolverServlet: about to do final authZ check");
Authorization authorization = (Authorization) s_server
.getModule("fedora.server.security.Authorization");
authorization.enforceResolveDatastream(context, keyTimestamp);
LOG.debug("DatastreamResolverServlet: final authZ check suceeded.....");
if (dsControlGroupType.equalsIgnoreCase("E")) {
// testing to see what's in request header that might be of
// interest
if (LOG.isDebugEnabled()) {
for (Enumeration e = request.getHeaderNames(); e
.hasMoreElements();) {
String name = (String) e.nextElement();
Enumeration headerValues = request.getHeaders(name);
StringBuffer sb = new StringBuffer();
while (headerValues.hasMoreElements()) {
sb.append((String) headerValues.nextElement());
}
String value = sb.toString();
LOG.debug("DATASTREAMRESOLVERSERVLET REQUEST HEADER CONTAINED: "
+ name + " : " + value);
}
}
// Datastream is ReferencedExternalContent so dsLocation is a
// URL string
ExternalContentManager externalContentManager = (ExternalContentManager) s_server
.getModule("fedora.server.storage.ExternalContentManager");
mimeTypedStream = externalContentManager.getExternalContent(
dsPhysicalLocation, context);
// had substituted context:
// ReadOnlyContext.getContext(Constants.HTTP_REQUEST.REST.uri,
// request));
outStream = response.getOutputStream();
response.setContentType(mimeTypedStream.MIMEType);
Property[] headerArray = mimeTypedStream.header;
if (headerArray != null) {
for (int i = 0; i < headerArray.length; i++) {
if (headerArray[i].name != null
&& !(headerArray[i].name
.equalsIgnoreCase("content-type"))) {
response.addHeader(headerArray[i].name,
headerArray[i].value);
LOG.debug("THIS WAS ADDED TO DATASTREAMRESOLVERSERVLET RESPONSE HEADER FROM ORIGINATING PROVIDER "
+ headerArray[i].name
+ " : " + headerArray[i].value);
}
}
}
int byteStream = 0;
byte[] buffer = new byte[255];
while ((byteStream = mimeTypedStream.getStream().read(buffer)) != -1) {
outStream.write(buffer, 0, byteStream);
}
buffer = null;
outStream.flush();
} else if (dsControlGroupType.equalsIgnoreCase("M")
|| dsControlGroupType.equalsIgnoreCase("X")) {
// Datastream is either XMLMetadata or ManagedContent so
// dsLocation
// is in the form of an internal Fedora ID using the syntax:
// PID+DSID+DSVersID; parse the ID and get the datastream
// content.
String PID = null;
String dsVersionID = null;
String dsID = null;
String[] s = dsPhysicalLocation.split("\\+");
if (s.length != 3) {
String message = "[DatastreamResolverServlet] The "
+ "internal Fedora datastream id: \""
+ dsPhysicalLocation + "\" is invalid.";
LOG.error(message);
throw new ServletException(message);
}
PID = s[0];
dsID = s[1];
dsVersionID = s[2];
LOG.debug("PID=" + PID + ", dsID=" + dsID + ", dsVersionID="
+ dsVersionID);
DOReader doReader = m_manager.getReader(
Server.USE_DEFINITIVE_STORE, context, PID);
Datastream d = (Datastream) doReader.getDatastream(dsID,
dsVersionID);
LOG.debug("Got datastream: " + d.DatastreamID);
InputStream is = d.getContentStream();
int bytestream = 0;
response.setContentType(d.DSMIME);
outStream = response.getOutputStream();
byte[] buffer = new byte[255];
while ((bytestream = is.read(buffer)) != -1) {
outStream.write(buffer, 0, bytestream);
}
buffer = null;
is.close();
} else {
out = response.getWriter();
response.setContentType(HTML_CONTENT_TYPE);
out.println("<br>[DatastreamResolverServlet] Unknown "
+ "dsControlGroupType: " + dsControlGroupType
+ "</br>");
LOG.error("Unknown dsControlGroupType: " + dsControlGroupType);
}
} catch (AuthzException ae) {
LOG.error("Authorization failure resolving datastream"
+ " (actionLabel=" + ACTION_LABEL + ")", ae);
throw RootException.getServletException(ae, request, ACTION_LABEL,
new String[0]);
} catch (Throwable th) {
LOG.error("Error resolving datastream", th);
String message = "[DatastreamResolverServlet] returned an error. The "
+ "underlying error was a \""
+ th.getClass().getName()
+ " The message was \"" + th.getMessage() + "\". ";
throw new ServletException(message);
} finally {
if (out != null)
out.close();
if (outStream != null)
outStream.close();
dsRegistry.remove(id);
}
}
// Clean up resources
public void destroy() {
}
}
| false | true | public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String id = null;
String dsPhysicalLocation = null;
String dsControlGroupType = null;
String user = null;
String pass = null;
MIMETypedStream mimeTypedStream = null;
DisseminationService ds = null;
Timestamp keyTimestamp = null;
Timestamp currentTimestamp = null;
PrintWriter out = null;
ServletOutputStream outStream = null;
String requestURI = request.getRequestURL().toString() + "?"
+ request.getQueryString();
id = request.getParameter("id").replaceAll("T", " ");
LOG.debug("Datastream tempID=" + id);
LOG.debug("DRS doGet()");
try {
// Check for required id parameter.
if (id == null || id.equalsIgnoreCase("")) {
String message = "[DatastreamResolverServlet] No datastream ID "
+ "specified in servlet request: "
+ request.getRequestURI();
LOG.error(message);
response
.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.sendError(
HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
return;
}
id = id.replaceAll("T", " ").replaceAll("/", "").trim();
// Get in-memory hashtable of mappings from Fedora server.
ds = new DisseminationService();
dsRegistry = DisseminationService.dsRegistry;
DatastreamMediation dm = (DatastreamMediation) dsRegistry.get(id);
if (dm == null) {
StringBuffer entries = new StringBuffer();
Iterator eIter = dsRegistry.keySet().iterator();
while (eIter.hasNext()) {
entries.append("'" + (String) eIter.next() + "' ");
}
throw new IOException(
"Cannot find datastream in temp registry by key: " + id
+ "\n" + "Reg entries: " + entries.toString());
}
dsPhysicalLocation = dm.dsLocation;
dsControlGroupType = dm.dsControlGroupType;
user = dm.callUsername;
pass = dm.callPassword;
if (LOG.isDebugEnabled()) {
LOG.debug("**************************** DatastreamResolverServlet dm.dsLocation: "
+ dm.dsLocation);
LOG.debug("**************************** DatastreamResolverServlet dm.dsControlGroupType: "
+ dm.dsControlGroupType);
LOG.debug("**************************** DatastreamResolverServlet dm.callUsername: "
+ dm.callUsername);
LOG.debug("**************************** DatastreamResolverServlet dm.Password: "
+ dm.callPassword);
LOG.debug("**************************** DatastreamResolverServlet dm.callbackRole: "
+ dm.callbackRole);
LOG.debug("**************************** DatastreamResolverServlet dm.callbackBasicAuth: "
+ dm.callbackBasicAuth);
LOG.debug("**************************** DatastreamResolverServlet dm.callBasicAuth: "
+ dm.callBasicAuth);
LOG.debug("**************************** DatastreamResolverServlet dm.callbackSSl: "
+ dm.callbackSSL);
LOG.debug("**************************** DatastreamResolverServlet dm.callSSl: "
+ dm.callSSL);
LOG.debug("**************************** DatastreamResolverServlet non ssl port: "
+ fedoraServerPort);
LOG.debug("**************************** DatastreamResolverServlet ssl port: "
+ fedoraServerRedirectPort);
}
// DatastreamResolverServlet maps to two distinct servlet mappings
// in fedora web.xml.
// getDS - is used when the backend service is incapable of
// basicAuth or SSL
// getDSAuthenticated - is used when the backend service has
// basicAuth and SSL enabled
// Since both the getDS and getDSAuthenticated servlet targets map
// to the same servlet
// code and the Context used to initialize policy enforcement is
// based on the incoming
// HTTPRequest, the code must provide special handling for requests
// using the getDS
// target. When the incoming URL to DatastreamResolverServlet
// contains the getDS target,
// there are several conditions that must be checked to insure that
// the correct role is
// assigned to the request before policy enforcement occurs.
// 1) if the mapped dsPhysicalLocation of the request is actually a
// callback to the
// Fedora server itself, then assign the role as
// BACKEND_SERVICE_CALL_UNSECURE so
// the basicAuth and SSL constraints will match those of the getDS
// target.
// 2) if the mapped dsPhysicalLocation of the request is actually a
// Managed Content
// or Inline XML Content datastream, then assign the role as
// BACKEND_SERVICE_CALL_UNSECURE so
// the basicAuth and SSL constraints will match the getDS target.
// 3) Otherwise, leave the targetrole unchanged.
if (request.getRequestURI().endsWith("getDS")
&& (ServerUtility.isURLFedoraServer(dsPhysicalLocation)
|| dsControlGroupType.equals("M") || dsControlGroupType
.equals("X"))) {
if (LOG.isDebugEnabled())
LOG.debug("*********************** Changed role from: "
+ dm.callbackRole
+ " to: "
+ BackendPolicies.BACKEND_SERVICE_CALL_UNSECURE);
dm.callbackRole = BackendPolicies.BACKEND_SERVICE_CALL_UNSECURE;
}
// If callback is to fedora server itself and callback is over SSL,
// adjust the protocol and port
// on the URL to match settings of Fedora server. This is necessary
// since the SSL settings for the
// backend service may have specified basicAuth=false, but contained
// datastreams that are callbacks
// to the local Fedora server which requires SSL. The version of
// HttpClient currently in use does
// not handle autoredirecting from http to https so it is necessary
// to set the protocol and port
// to the appropriate secure port.
if (dm.callbackRole.equals(BackendPolicies.FEDORA_INTERNAL_CALL)) {
if (dm.callbackSSL) {
dsPhysicalLocation = dsPhysicalLocation.replaceFirst(
"http:", "https:");
dsPhysicalLocation = dsPhysicalLocation.replaceFirst(
fedoraServerPort, fedoraServerRedirectPort);
if (LOG.isDebugEnabled())
LOG.debug("*********************** DatastreamResolverServlet -- Was Fedora-to-Fedora call -- modified dsPhysicalLocation: "
+ dsPhysicalLocation);
}
}
keyTimestamp = Timestamp.valueOf(ds.extractTimestamp(id));
currentTimestamp = new Timestamp(new Date().getTime());
LOG.debug("dsPhysicalLocation=" + dsPhysicalLocation
+ "dsControlGroupType=" + dsControlGroupType);
// Deny mechanism requests that fall outside the specified time
// interval.
// The expiration limit can be adjusted using the Fedora config
// parameter
// named "datastreamMediationLimit" which is in milliseconds.
long diff = currentTimestamp.getTime() - keyTimestamp.getTime();
LOG.debug("Timestamp diff for mechanism's reponse: "
+ diff + " ms.");
if (diff > (long) datastreamMediationLimit) {
out = response.getWriter();
response.setContentType(HTML_CONTENT_TYPE);
out
.println("<br><b>[DatastreamResolverServlet] Error:</b>"
+ "<font color=\"red\"> Mechanism has failed to respond "
+ "to the DatastreamResolverServlet within the specified "
+ "time limit of \""
+ datastreamMediationLimit
+ "\""
+ "milliseconds. Datastream access denied.");
LOG.error("Mechanism failed to respond to "
+ "DatastreamResolverServlet within time limit of "
+ datastreamMediationLimit);
out.close();
return;
}
if (dm.callbackRole == null) {
throw new AuthzOperationalException(
"no callbackRole for this ticket");
}
String targetRole = //Authorization.FEDORA_ROLE_KEY + "=" +
dm.callbackRole; // restrict access to role of this
// ticket
String[] targetRoles = { targetRole };
Context context = ReadOnlyContext.getContext(
Constants.HTTP_REQUEST.REST.uri, request); // , targetRoles);
if (request.getRemoteUser() == null) {
// non-authn: must accept target role of ticket
LOG.debug("DatastreamResolverServlet: unAuthenticated request");
} else {
// authn: check user roles for target role of ticket
/*
LOG.debug("DatastreamResolverServlet: Authenticated request getting user");
String[] roles = null;
Principal principal = request.getUserPrincipal();
if (principal == null) {
// no principal to grok roles from!!
} else {
try {
roles = ReadOnlyContext.getRoles(principal);
} catch (Throwable t) {
}
}
if (roles == null) {
roles = new String[0];
}
*/
//XXXXXXXXXXXXXXXXXXXXXXxif (contains(roles, targetRole)) {
if (((ExtendedHttpServletRequest)request).isUserInRole(targetRole)) {
LOG.debug("DatastreamResolverServlet: user has required role");
} else {
LOG.debug("DatastreamResolverServlet: authZ exception in validating user");
throw new AuthzDeniedException("wrong user for this ticket");
}
}
if (LOG.isDebugEnabled()) {
LOG.debug("debugging backendService role");
LOG.debug("targetRole=" + targetRole);
int targetRolesLength = targetRoles.length;
LOG.debug("targetRolesLength=" + targetRolesLength);
if (targetRolesLength > 0) {
LOG.debug("targetRoles[0]=" + targetRoles[0]);
}
int nSubjectValues = context.nSubjectValues(targetRole);
LOG.debug("nSubjectValues=" + nSubjectValues);
if (nSubjectValues > 0) {
LOG.debug("context.getSubjectValue(targetRole)="
+ context.getSubjectValue(targetRole));
}
Iterator it = context.subjectAttributes();
while (it.hasNext()) {
String name = (String) it.next();
String value = context.getSubjectValue(name);
LOG.debug("another subject attribute from context "
+ name + "=" + value);
}
it = context.environmentAttributes();
while (it.hasNext()) {
String name = (String) it.next();
String value = context.getEnvironmentValue(name);
LOG.debug("another environment attribute from context "
+ name + "=" + value);
}
}
LOG.debug("DatastreamResolverServlet: about to do final authZ check");
Authorization authorization = (Authorization) s_server
.getModule("fedora.server.security.Authorization");
authorization.enforceResolveDatastream(context, keyTimestamp);
LOG.debug("DatastreamResolverServlet: final authZ check suceeded.....");
if (dsControlGroupType.equalsIgnoreCase("E")) {
// testing to see what's in request header that might be of
// interest
if (LOG.isDebugEnabled()) {
for (Enumeration e = request.getHeaderNames(); e
.hasMoreElements();) {
String name = (String) e.nextElement();
Enumeration headerValues = request.getHeaders(name);
StringBuffer sb = new StringBuffer();
while (headerValues.hasMoreElements()) {
sb.append((String) headerValues.nextElement());
}
String value = sb.toString();
LOG.debug("DATASTREAMRESOLVERSERVLET REQUEST HEADER CONTAINED: "
+ name + " : " + value);
}
}
// Datastream is ReferencedExternalContent so dsLocation is a
// URL string
ExternalContentManager externalContentManager = (ExternalContentManager) s_server
.getModule("fedora.server.storage.ExternalContentManager");
mimeTypedStream = externalContentManager.getExternalContent(
dsPhysicalLocation, context);
// had substituted context:
// ReadOnlyContext.getContext(Constants.HTTP_REQUEST.REST.uri,
// request));
outStream = response.getOutputStream();
response.setContentType(mimeTypedStream.MIMEType);
Property[] headerArray = mimeTypedStream.header;
if (headerArray != null) {
for (int i = 0; i < headerArray.length; i++) {
if (headerArray[i].name != null
&& !(headerArray[i].name
.equalsIgnoreCase("content-type"))) {
response.addHeader(headerArray[i].name,
headerArray[i].value);
LOG.debug("THIS WAS ADDED TO DATASTREAMRESOLVERSERVLET RESPONSE HEADER FROM ORIGINATING PROVIDER "
+ headerArray[i].name
+ " : " + headerArray[i].value);
}
}
}
int byteStream = 0;
byte[] buffer = new byte[255];
while ((byteStream = mimeTypedStream.getStream().read(buffer)) != -1) {
outStream.write(buffer, 0, byteStream);
}
buffer = null;
outStream.flush();
} else if (dsControlGroupType.equalsIgnoreCase("M")
|| dsControlGroupType.equalsIgnoreCase("X")) {
// Datastream is either XMLMetadata or ManagedContent so
// dsLocation
// is in the form of an internal Fedora ID using the syntax:
// PID+DSID+DSVersID; parse the ID and get the datastream
// content.
String PID = null;
String dsVersionID = null;
String dsID = null;
String[] s = dsPhysicalLocation.split("\\+");
if (s.length != 3) {
String message = "[DatastreamResolverServlet] The "
+ "internal Fedora datastream id: \""
+ dsPhysicalLocation + "\" is invalid.";
LOG.error(message);
throw new ServletException(message);
}
PID = s[0];
dsID = s[1];
dsVersionID = s[2];
LOG.debug("PID=" + PID + ", dsID=" + dsID + ", dsVersionID="
+ dsVersionID);
DOReader doReader = m_manager.getReader(
Server.USE_DEFINITIVE_STORE, context, PID);
Datastream d = (Datastream) doReader.getDatastream(dsID,
dsVersionID);
LOG.debug("Got datastream: " + d.DatastreamID);
InputStream is = d.getContentStream();
int bytestream = 0;
response.setContentType(d.DSMIME);
outStream = response.getOutputStream();
byte[] buffer = new byte[255];
while ((bytestream = is.read(buffer)) != -1) {
outStream.write(buffer, 0, bytestream);
}
buffer = null;
is.close();
} else {
out = response.getWriter();
response.setContentType(HTML_CONTENT_TYPE);
out.println("<br>[DatastreamResolverServlet] Unknown "
+ "dsControlGroupType: " + dsControlGroupType
+ "</br>");
LOG.error("Unknown dsControlGroupType: " + dsControlGroupType);
}
} catch (AuthzException ae) {
LOG.error("Authorization failure resolving datastream"
+ " (actionLabel=" + ACTION_LABEL + ")", ae);
throw RootException.getServletException(ae, request, ACTION_LABEL,
new String[0]);
} catch (Throwable th) {
LOG.error("Error resolving datastream", th);
String message = "[DatastreamResolverServlet] returned an error. The "
+ "underlying error was a \""
+ th.getClass().getName()
+ " The message was \"" + th.getMessage() + "\". ";
throw new ServletException(message);
} finally {
if (out != null)
out.close();
if (outStream != null)
outStream.close();
dsRegistry.remove(id);
}
}
| public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String id = null;
String dsPhysicalLocation = null;
String dsControlGroupType = null;
String user = null;
String pass = null;
MIMETypedStream mimeTypedStream = null;
DisseminationService ds = null;
Timestamp keyTimestamp = null;
Timestamp currentTimestamp = null;
PrintWriter out = null;
ServletOutputStream outStream = null;
String requestURI = request.getRequestURL().toString() + "?"
+ request.getQueryString();
id = request.getParameter("id").replaceAll("T", " ");
LOG.debug("Datastream tempID=" + id);
LOG.debug("DRS doGet()");
try {
// Check for required id parameter.
if (id == null || id.equalsIgnoreCase("")) {
String message = "[DatastreamResolverServlet] No datastream ID "
+ "specified in servlet request: "
+ request.getRequestURI();
LOG.error(message);
response
.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.sendError(
HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
return;
}
id = id.replaceAll("T", " ").replaceAll("/", "").trim();
// Get in-memory hashtable of mappings from Fedora server.
ds = new DisseminationService();
dsRegistry = DisseminationService.dsRegistry;
DatastreamMediation dm = (DatastreamMediation) dsRegistry.get(id);
if (dm == null) {
StringBuffer entries = new StringBuffer();
Iterator eIter = dsRegistry.keySet().iterator();
while (eIter.hasNext()) {
entries.append("'" + (String) eIter.next() + "' ");
}
throw new IOException(
"Cannot find datastream in temp registry by key: " + id
+ "\n" + "Reg entries: " + entries.toString());
}
dsPhysicalLocation = dm.dsLocation;
dsControlGroupType = dm.dsControlGroupType;
user = dm.callUsername;
pass = dm.callPassword;
if (LOG.isDebugEnabled()) {
LOG.debug("**************************** DatastreamResolverServlet dm.dsLocation: "
+ dm.dsLocation);
LOG.debug("**************************** DatastreamResolverServlet dm.dsControlGroupType: "
+ dm.dsControlGroupType);
LOG.debug("**************************** DatastreamResolverServlet dm.callUsername: "
+ dm.callUsername);
LOG.debug("**************************** DatastreamResolverServlet dm.Password: "
+ dm.callPassword);
LOG.debug("**************************** DatastreamResolverServlet dm.callbackRole: "
+ dm.callbackRole);
LOG.debug("**************************** DatastreamResolverServlet dm.callbackBasicAuth: "
+ dm.callbackBasicAuth);
LOG.debug("**************************** DatastreamResolverServlet dm.callBasicAuth: "
+ dm.callBasicAuth);
LOG.debug("**************************** DatastreamResolverServlet dm.callbackSSl: "
+ dm.callbackSSL);
LOG.debug("**************************** DatastreamResolverServlet dm.callSSl: "
+ dm.callSSL);
LOG.debug("**************************** DatastreamResolverServlet non ssl port: "
+ fedoraServerPort);
LOG.debug("**************************** DatastreamResolverServlet ssl port: "
+ fedoraServerRedirectPort);
}
// DatastreamResolverServlet maps to two distinct servlet mappings
// in fedora web.xml.
// getDS - is used when the backend service is incapable of
// basicAuth or SSL
// getDSAuthenticated - is used when the backend service has
// basicAuth and SSL enabled
// Since both the getDS and getDSAuthenticated servlet targets map
// to the same servlet
// code and the Context used to initialize policy enforcement is
// based on the incoming
// HTTPRequest, the code must provide special handling for requests
// using the getDS
// target. When the incoming URL to DatastreamResolverServlet
// contains the getDS target,
// there are several conditions that must be checked to insure that
// the correct role is
// assigned to the request before policy enforcement occurs.
// 1) if the mapped dsPhysicalLocation of the request is actually a
// callback to the
// Fedora server itself, then assign the role as
// BACKEND_SERVICE_CALL_UNSECURE so
// the basicAuth and SSL constraints will match those of the getDS
// target.
// 2) if the mapped dsPhysicalLocation of the request is actually a
// Managed Content
// or Inline XML Content datastream, then assign the role as
// BACKEND_SERVICE_CALL_UNSECURE so
// the basicAuth and SSL constraints will match the getDS target.
// 3) Otherwise, leave the targetrole unchanged.
if (request.getRequestURI().endsWith("getDS")
&& (ServerUtility.isURLFedoraServer(dsPhysicalLocation)
|| dsControlGroupType.equals("M") || dsControlGroupType
.equals("X"))) {
if (LOG.isDebugEnabled())
LOG.debug("*********************** Changed role from: "
+ dm.callbackRole
+ " to: "
+ BackendPolicies.BACKEND_SERVICE_CALL_UNSECURE);
dm.callbackRole = BackendPolicies.BACKEND_SERVICE_CALL_UNSECURE;
}
// If callback is to fedora server itself and callback is over SSL,
// adjust the protocol and port
// on the URL to match settings of Fedora server. This is necessary
// since the SSL settings for the
// backend service may have specified basicAuth=false, but contained
// datastreams that are callbacks
// to the local Fedora server which requires SSL. The version of
// HttpClient currently in use does
// not handle autoredirecting from http to https so it is necessary
// to set the protocol and port
// to the appropriate secure port.
if (dm.callbackRole.equals(BackendPolicies.FEDORA_INTERNAL_CALL)) {
if (dm.callbackSSL) {
dsPhysicalLocation = dsPhysicalLocation.replaceFirst(
"http:", "https:");
dsPhysicalLocation = dsPhysicalLocation.replaceFirst(
fedoraServerPort, fedoraServerRedirectPort);
if (LOG.isDebugEnabled())
LOG.debug("*********************** DatastreamResolverServlet -- Was Fedora-to-Fedora call -- modified dsPhysicalLocation: "
+ dsPhysicalLocation);
}
}
keyTimestamp = Timestamp.valueOf(ds.extractTimestamp(id));
currentTimestamp = new Timestamp(new Date().getTime());
LOG.debug("dsPhysicalLocation=" + dsPhysicalLocation
+ "dsControlGroupType=" + dsControlGroupType);
// Deny mechanism requests that fall outside the specified time
// interval.
// The expiration limit can be adjusted using the Fedora config
// parameter
// named "datastreamMediationLimit" which is in milliseconds.
long diff = currentTimestamp.getTime() - keyTimestamp.getTime();
LOG.debug("Timestamp diff for mechanism's reponse: "
+ diff + " ms.");
if (diff > (long) datastreamMediationLimit) {
out = response.getWriter();
response.setContentType(HTML_CONTENT_TYPE);
out
.println("<br><b>[DatastreamResolverServlet] Error:</b>"
+ "<font color=\"red\"> Mechanism has failed to respond "
+ "to the DatastreamResolverServlet within the specified "
+ "time limit of \""
+ datastreamMediationLimit
+ "\""
+ "milliseconds. Datastream access denied.");
LOG.error("Mechanism failed to respond to "
+ "DatastreamResolverServlet within time limit of "
+ datastreamMediationLimit);
out.close();
return;
}
if (dm.callbackRole == null) {
throw new AuthzOperationalException(
"no callbackRole for this ticket");
}
String targetRole = //Authorization.FEDORA_ROLE_KEY + "=" +
dm.callbackRole; // restrict access to role of this
// ticket
String[] targetRoles = { targetRole };
Context context = ReadOnlyContext.getContext(
Constants.HTTP_REQUEST.REST.uri, request); // , targetRoles);
if (request.getRemoteUser() == null) {
// non-authn: must accept target role of ticket
LOG.debug("DatastreamResolverServlet: unAuthenticated request");
} else {
// authn: check user roles for target role of ticket
/*
LOG.debug("DatastreamResolverServlet: Authenticated request getting user");
String[] roles = null;
Principal principal = request.getUserPrincipal();
if (principal == null) {
// no principal to grok roles from!!
} else {
try {
roles = ReadOnlyContext.getRoles(principal);
} catch (Throwable t) {
}
}
if (roles == null) {
roles = new String[0];
}
*/
//XXXXXXXXXXXXXXXXXXXXXXxif (contains(roles, targetRole)) {
LOG.debug("DatastreamResolverServlet: user==" + request.getRemoteUser());
/*
if (((ExtendedHttpServletRequest)request).isUserInRole(targetRole)) {
LOG.debug("DatastreamResolverServlet: user has required role");
} else {
LOG.debug("DatastreamResolverServlet: authZ exception in validating user");
throw new AuthzDeniedException("wrong user for this ticket");
}
*/
}
if (LOG.isDebugEnabled()) {
LOG.debug("debugging backendService role");
LOG.debug("targetRole=" + targetRole);
int targetRolesLength = targetRoles.length;
LOG.debug("targetRolesLength=" + targetRolesLength);
if (targetRolesLength > 0) {
LOG.debug("targetRoles[0]=" + targetRoles[0]);
}
int nSubjectValues = context.nSubjectValues(targetRole);
LOG.debug("nSubjectValues=" + nSubjectValues);
if (nSubjectValues > 0) {
LOG.debug("context.getSubjectValue(targetRole)="
+ context.getSubjectValue(targetRole));
}
Iterator it = context.subjectAttributes();
while (it.hasNext()) {
String name = (String) it.next();
String value = context.getSubjectValue(name);
LOG.debug("another subject attribute from context "
+ name + "=" + value);
}
it = context.environmentAttributes();
while (it.hasNext()) {
String name = (String) it.next();
String value = context.getEnvironmentValue(name);
LOG.debug("another environment attribute from context "
+ name + "=" + value);
}
}
LOG.debug("DatastreamResolverServlet: about to do final authZ check");
Authorization authorization = (Authorization) s_server
.getModule("fedora.server.security.Authorization");
authorization.enforceResolveDatastream(context, keyTimestamp);
LOG.debug("DatastreamResolverServlet: final authZ check suceeded.....");
if (dsControlGroupType.equalsIgnoreCase("E")) {
// testing to see what's in request header that might be of
// interest
if (LOG.isDebugEnabled()) {
for (Enumeration e = request.getHeaderNames(); e
.hasMoreElements();) {
String name = (String) e.nextElement();
Enumeration headerValues = request.getHeaders(name);
StringBuffer sb = new StringBuffer();
while (headerValues.hasMoreElements()) {
sb.append((String) headerValues.nextElement());
}
String value = sb.toString();
LOG.debug("DATASTREAMRESOLVERSERVLET REQUEST HEADER CONTAINED: "
+ name + " : " + value);
}
}
// Datastream is ReferencedExternalContent so dsLocation is a
// URL string
ExternalContentManager externalContentManager = (ExternalContentManager) s_server
.getModule("fedora.server.storage.ExternalContentManager");
mimeTypedStream = externalContentManager.getExternalContent(
dsPhysicalLocation, context);
// had substituted context:
// ReadOnlyContext.getContext(Constants.HTTP_REQUEST.REST.uri,
// request));
outStream = response.getOutputStream();
response.setContentType(mimeTypedStream.MIMEType);
Property[] headerArray = mimeTypedStream.header;
if (headerArray != null) {
for (int i = 0; i < headerArray.length; i++) {
if (headerArray[i].name != null
&& !(headerArray[i].name
.equalsIgnoreCase("content-type"))) {
response.addHeader(headerArray[i].name,
headerArray[i].value);
LOG.debug("THIS WAS ADDED TO DATASTREAMRESOLVERSERVLET RESPONSE HEADER FROM ORIGINATING PROVIDER "
+ headerArray[i].name
+ " : " + headerArray[i].value);
}
}
}
int byteStream = 0;
byte[] buffer = new byte[255];
while ((byteStream = mimeTypedStream.getStream().read(buffer)) != -1) {
outStream.write(buffer, 0, byteStream);
}
buffer = null;
outStream.flush();
} else if (dsControlGroupType.equalsIgnoreCase("M")
|| dsControlGroupType.equalsIgnoreCase("X")) {
// Datastream is either XMLMetadata or ManagedContent so
// dsLocation
// is in the form of an internal Fedora ID using the syntax:
// PID+DSID+DSVersID; parse the ID and get the datastream
// content.
String PID = null;
String dsVersionID = null;
String dsID = null;
String[] s = dsPhysicalLocation.split("\\+");
if (s.length != 3) {
String message = "[DatastreamResolverServlet] The "
+ "internal Fedora datastream id: \""
+ dsPhysicalLocation + "\" is invalid.";
LOG.error(message);
throw new ServletException(message);
}
PID = s[0];
dsID = s[1];
dsVersionID = s[2];
LOG.debug("PID=" + PID + ", dsID=" + dsID + ", dsVersionID="
+ dsVersionID);
DOReader doReader = m_manager.getReader(
Server.USE_DEFINITIVE_STORE, context, PID);
Datastream d = (Datastream) doReader.getDatastream(dsID,
dsVersionID);
LOG.debug("Got datastream: " + d.DatastreamID);
InputStream is = d.getContentStream();
int bytestream = 0;
response.setContentType(d.DSMIME);
outStream = response.getOutputStream();
byte[] buffer = new byte[255];
while ((bytestream = is.read(buffer)) != -1) {
outStream.write(buffer, 0, bytestream);
}
buffer = null;
is.close();
} else {
out = response.getWriter();
response.setContentType(HTML_CONTENT_TYPE);
out.println("<br>[DatastreamResolverServlet] Unknown "
+ "dsControlGroupType: " + dsControlGroupType
+ "</br>");
LOG.error("Unknown dsControlGroupType: " + dsControlGroupType);
}
} catch (AuthzException ae) {
LOG.error("Authorization failure resolving datastream"
+ " (actionLabel=" + ACTION_LABEL + ")", ae);
throw RootException.getServletException(ae, request, ACTION_LABEL,
new String[0]);
} catch (Throwable th) {
LOG.error("Error resolving datastream", th);
String message = "[DatastreamResolverServlet] returned an error. The "
+ "underlying error was a \""
+ th.getClass().getName()
+ " The message was \"" + th.getMessage() + "\". ";
throw new ServletException(message);
} finally {
if (out != null)
out.close();
if (outStream != null)
outStream.close();
dsRegistry.remove(id);
}
}
|
diff --git a/src/com/willluongo/asbestos/gui/AsbestosWindow.java b/src/com/willluongo/asbestos/gui/AsbestosWindow.java
index 9048fd0..a79d2a3 100644
--- a/src/com/willluongo/asbestos/gui/AsbestosWindow.java
+++ b/src/com/willluongo/asbestos/gui/AsbestosWindow.java
@@ -1,199 +1,200 @@
package com.willluongo.asbestos.gui;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Text;
import com.madhackerdesigns.jinder.Campfire;
import com.madhackerdesigns.jinder.Room;
import com.madhackerdesigns.jinder.models.Message;
import com.madhackerdesigns.jinder.models.User;
import org.eclipse.swt.events.TraverseListener;
import org.eclipse.swt.events.TraverseEvent;
public class AsbestosWindow {
protected Shell shlAsbestos;
private static Campfire campfire;
private static String SUBDOMAIN = null;
private static String TOKEN = null;
private static final Logger log = LogManager.getLogger(AsbestosWindow.class
.getName());
private Text text_messages;
private Room room = null;
private SortedSet<User> users = null;
private SortedSet<Long> userIds = new TreeSet<Long>();
private Text text;
private Message lastMessage = new Message();
private Hashtable<Long, User> userCache = new Hashtable<Long, User>();
private static final int UPDATERATE = 1000;
/**
* Launch the application.
*
* @param args
*/
public static void main(String[] args) {
initialize();
try {
AsbestosWindow window = new AsbestosWindow();
window.open();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void initialize() {
log.debug("Loading properties from file...");
Properties prop = new Properties();
try {
prop.load(new FileInputStream("asbestos.properties"));
SUBDOMAIN = prop.getProperty("campfire.subdomain");
TOKEN = prop.getProperty("campfire.token");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
log.debug("Campfire subdomain: ".concat(SUBDOMAIN));
log.debug("Campfire token: ".concat(TOKEN));
campfire = new Campfire(SUBDOMAIN, TOKEN);
}
private void updateMessages() {
List<Message> lastUpdate = null;
try {
if (lastMessage.id == null)
lastUpdate = room.recent();
else
lastUpdate = room.recent(lastMessage.id);
for (Message msg : lastUpdate) {
log.debug(msg.created_at + " " + msg.type);
if (msg.type.equals("TextMessage")) {
if (!(msg.equals(lastMessage))) {
if (!(userCache.containsKey(msg.user_id))) {
userCache.put(msg.user_id, room.user(msg.user_id));
}
text_messages.append(userCache.get(msg.user_id).name
.concat(": ").concat(msg.body.concat("\n")));
lastMessage = msg;
}
}
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
/**
* Open the window.
*/
public void open() {
final Display display = Display.getDefault();
createContents();
shlAsbestos.open();
shlAsbestos.layout();
Runnable timer = new Runnable() {
@Override
public void run() {
updateMessages();
display.timerExec(UPDATERATE, this);
}
};
display.timerExec(UPDATERATE, timer);
while (!shlAsbestos.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
/**
* Create contents of the window.
*/
protected void createContents() {
try {
users = campfire.users();
log.debug(users);
room = campfire.rooms().get(2);
+ room.join();
for (User user : users) {
log.debug(user.name);
log.debug(user.id);
userIds.add(user.id);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
shlAsbestos = new Shell();
shlAsbestos.setSize(450, 300);
shlAsbestos.setText("Asbestos");
TabFolder tabFolder = new TabFolder(shlAsbestos, SWT.NONE);
tabFolder.setBounds(0, 0, 450, 299);
TabItem tbtmGeneralChat = new TabItem(tabFolder, SWT.NONE);
tbtmGeneralChat.setText(room.name);
Composite composite = new Composite(tabFolder, SWT.NONE);
tbtmGeneralChat.setControl(composite);
text_messages = new Text(composite, SWT.READ_ONLY | SWT.WRAP
| SWT.V_SCROLL | SWT.MULTI);
text_messages.setBounds(0, 0, 430, 217);
text = new Text(composite, SWT.BORDER);
text.addTraverseListener(new TraverseListener() {
public void keyTraversed(TraverseEvent e) {
try {
room.speak(text.getText());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
text.setText("");
updateMessages();
}
});
text.setBounds(0, 223, 430, 19);
updateMessages();
}
}
| true | true | protected void createContents() {
try {
users = campfire.users();
log.debug(users);
room = campfire.rooms().get(2);
for (User user : users) {
log.debug(user.name);
log.debug(user.id);
userIds.add(user.id);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
shlAsbestos = new Shell();
shlAsbestos.setSize(450, 300);
shlAsbestos.setText("Asbestos");
TabFolder tabFolder = new TabFolder(shlAsbestos, SWT.NONE);
tabFolder.setBounds(0, 0, 450, 299);
TabItem tbtmGeneralChat = new TabItem(tabFolder, SWT.NONE);
tbtmGeneralChat.setText(room.name);
Composite composite = new Composite(tabFolder, SWT.NONE);
tbtmGeneralChat.setControl(composite);
text_messages = new Text(composite, SWT.READ_ONLY | SWT.WRAP
| SWT.V_SCROLL | SWT.MULTI);
text_messages.setBounds(0, 0, 430, 217);
text = new Text(composite, SWT.BORDER);
text.addTraverseListener(new TraverseListener() {
public void keyTraversed(TraverseEvent e) {
try {
room.speak(text.getText());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
text.setText("");
updateMessages();
}
});
text.setBounds(0, 223, 430, 19);
updateMessages();
}
| protected void createContents() {
try {
users = campfire.users();
log.debug(users);
room = campfire.rooms().get(2);
room.join();
for (User user : users) {
log.debug(user.name);
log.debug(user.id);
userIds.add(user.id);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
shlAsbestos = new Shell();
shlAsbestos.setSize(450, 300);
shlAsbestos.setText("Asbestos");
TabFolder tabFolder = new TabFolder(shlAsbestos, SWT.NONE);
tabFolder.setBounds(0, 0, 450, 299);
TabItem tbtmGeneralChat = new TabItem(tabFolder, SWT.NONE);
tbtmGeneralChat.setText(room.name);
Composite composite = new Composite(tabFolder, SWT.NONE);
tbtmGeneralChat.setControl(composite);
text_messages = new Text(composite, SWT.READ_ONLY | SWT.WRAP
| SWT.V_SCROLL | SWT.MULTI);
text_messages.setBounds(0, 0, 430, 217);
text = new Text(composite, SWT.BORDER);
text.addTraverseListener(new TraverseListener() {
public void keyTraversed(TraverseEvent e) {
try {
room.speak(text.getText());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
text.setText("");
updateMessages();
}
});
text.setBounds(0, 223, 430, 19);
updateMessages();
}
|
diff --git a/compass2/core/src/main/java/no/ovitas/compass2/config/KnowledgeBases.java b/compass2/core/src/main/java/no/ovitas/compass2/config/KnowledgeBases.java
index 663e7ea..5d0a316 100644
--- a/compass2/core/src/main/java/no/ovitas/compass2/config/KnowledgeBases.java
+++ b/compass2/core/src/main/java/no/ovitas/compass2/config/KnowledgeBases.java
@@ -1,41 +1,41 @@
package no.ovitas.compass2.config;
import org.apache.log4j.Logger;
/**
* @author csanyi
*
*/
public class KnowledgeBases extends BaseConfigContainer<KnowledgeBase> {
// Attributes
private Logger logger = Logger.getLogger(this.getClass());
// Constructors
public KnowledgeBases() {
super();
}
// Methods
public KnowledgeBase getKnowledgeBase(String name) {
if (name != null && elements.containsKey(name)) {
return elements.get(name);
} else {
- logger.error("The " + name + " KnowledgeBase is not exists!");
+ logger.error("The " + name + " KnowledgeBase is not exist!");
return null;
}
}
public String dumpOut(String indent) {
String ind = indent + " ";
String toDumpOut = ind + "KnowledgeBases\n";
toDumpOut += super.dumpOut(ind);
return toDumpOut;
}
}
| true | true | public KnowledgeBase getKnowledgeBase(String name) {
if (name != null && elements.containsKey(name)) {
return elements.get(name);
} else {
logger.error("The " + name + " KnowledgeBase is not exists!");
return null;
}
}
| public KnowledgeBase getKnowledgeBase(String name) {
if (name != null && elements.containsKey(name)) {
return elements.get(name);
} else {
logger.error("The " + name + " KnowledgeBase is not exist!");
return null;
}
}
|
diff --git a/JavaSource/org/unitime/timetable/action/ChameleonAction.java b/JavaSource/org/unitime/timetable/action/ChameleonAction.java
index 7e3e84c7..b4886967 100644
--- a/JavaSource/org/unitime/timetable/action/ChameleonAction.java
+++ b/JavaSource/org/unitime/timetable/action/ChameleonAction.java
@@ -1,182 +1,182 @@
/*
* UniTime 3.1 (University Timetabling Application)
* Copyright (C) 2008, UniTime LLC, and individual contributors
* as indicated by the @authors tag.
*
* 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.unitime.timetable.action;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
import java.util.Vector;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.util.MessageResources;
import org.unitime.commons.Debug;
import org.unitime.commons.User;
import org.unitime.commons.web.Web;
import org.unitime.timetable.form.ChameleonForm;
import org.unitime.timetable.model.Department;
import org.unitime.timetable.model.ManagerRole;
import org.unitime.timetable.model.Roles;
import org.unitime.timetable.model.TimetableManager;
import org.unitime.timetable.util.Constants;
import org.unitime.timetable.util.LookupTables;
/**
* MyEclipse Struts
* Creation date: 10-23-2006
*
* XDoclet definition:
* @struts:action path="/chameleon" name="chameleonForm" input="/admin/chameleon.jsp" scope="request"
*/
public class ChameleonAction extends Action {
// --------------------------------------------------------- Instance Variables
// --------------------------------------------------------- Methods
/**
* Method execute
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
*/
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception {
HttpSession httpSession = request.getSession();
if(!Web.isLoggedIn( httpSession )
|| ( !Web.isAdmin(httpSession)
&& ( httpSession.getAttribute("hdnAdminAlias")==null || !httpSession.getAttribute("hdnAdminAlias").toString().equals("1") ))) {
throw new Exception ("Access Denied.");
}
MessageResources rsc = getResources(request);
User user = Web.getUser(request.getSession());
ChameleonForm frm = (ChameleonForm) form;
- ActionMessages errors = null;
+ ActionMessages errors = new ActionMessages();
String op = (request.getParameter("op")==null)
? (frm.getOp()==null || frm.getOp().length()==0)
? (request.getAttribute("op")==null)
? null
: request.getAttribute("op").toString()
: frm.getOp()
: request.getParameter("op");
if(op==null || op.trim().length()==0)
op = rsc.getMessage("op.view");
frm.setOp(op);
// First Access - display blank form
if ( op.equals(rsc.getMessage("op.view")) ) {
LookupTables.setupTimetableManagers(request);
}
// Change User
if ( op.equals(rsc.getMessage("button.changeUser")) ) {
try {
doSwitch(request, frm, user);
return mapping.findForward("reload");
}
catch(Exception e) {
Debug.error(e);
errors.add("exception",
new ActionMessage("errors.generic", e.getMessage()) );
saveErrors(request, errors);
LookupTables.setupTimetableManagers(request);
return mapping.findForward("displayForm");
}
}
return mapping.findForward("displayForm");
}
/**
* Reads in new user attributes and reloads Timetabling for the new user
* @param request
* @param frm
* @param u
*/
private void doSwitch(
HttpServletRequest request,
ChameleonForm frm,
User u ) throws Exception {
TimetableManager tm = TimetableManager.findByExternalId(frm.getPuid());
if (tm == null)
throw new Exception ("User is not a Timetable Manager");
String puid = frm.getPuid();
//while (puid.startsWith("0")) puid = puid.substring(1);
u.setId(puid);
u.setName(tm.getName() + " (A)");
u.setAdmin(false);
u.setRole("");
u.setOtherAttributes(new Properties());
u.setAttribute(Constants.TMTBL_MGR_ID_ATTR_NAME, tm.getUniqueId().toString());
Vector roles = new Vector();
if (tm.getManagerRoles() != null){
Iterator it2 = tm.getManagerRoles().iterator();
while (it2.hasNext()){
ManagerRole mr = (ManagerRole) it2.next();
Roles r = mr.getRole();
String role1 = r.getReference();
roles.addElement(role1);
if(role1.equals(Roles.ADMIN_ROLE))
u.setAdmin(true);
}
}
u.setRoles(roles);
HashSet depts = new HashSet();
Set dp = tm.getDepartments();
for (Iterator i = dp.iterator(); i.hasNext(); ) {
Department d = (Department) i.next();
depts.add(d.getDeptCode());
}
u.setDepartments(new Vector(depts));
// Set Session Variables
HttpSession session = request.getSession();
session.setAttribute("loggedOn", "true");
session.setAttribute("hdnCallingScreen", "main.jsp");
session.setAttribute("hdnAdminAlias", "1");
Constants.resetSessionAttributes(session);
Web.setUser(session, u);
}
}
| true | true | public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception {
HttpSession httpSession = request.getSession();
if(!Web.isLoggedIn( httpSession )
|| ( !Web.isAdmin(httpSession)
&& ( httpSession.getAttribute("hdnAdminAlias")==null || !httpSession.getAttribute("hdnAdminAlias").toString().equals("1") ))) {
throw new Exception ("Access Denied.");
}
MessageResources rsc = getResources(request);
User user = Web.getUser(request.getSession());
ChameleonForm frm = (ChameleonForm) form;
ActionMessages errors = null;
String op = (request.getParameter("op")==null)
? (frm.getOp()==null || frm.getOp().length()==0)
? (request.getAttribute("op")==null)
? null
: request.getAttribute("op").toString()
: frm.getOp()
: request.getParameter("op");
if(op==null || op.trim().length()==0)
op = rsc.getMessage("op.view");
frm.setOp(op);
// First Access - display blank form
if ( op.equals(rsc.getMessage("op.view")) ) {
LookupTables.setupTimetableManagers(request);
}
// Change User
if ( op.equals(rsc.getMessage("button.changeUser")) ) {
try {
doSwitch(request, frm, user);
return mapping.findForward("reload");
}
catch(Exception e) {
Debug.error(e);
errors.add("exception",
new ActionMessage("errors.generic", e.getMessage()) );
saveErrors(request, errors);
LookupTables.setupTimetableManagers(request);
return mapping.findForward("displayForm");
}
}
return mapping.findForward("displayForm");
}
| public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception {
HttpSession httpSession = request.getSession();
if(!Web.isLoggedIn( httpSession )
|| ( !Web.isAdmin(httpSession)
&& ( httpSession.getAttribute("hdnAdminAlias")==null || !httpSession.getAttribute("hdnAdminAlias").toString().equals("1") ))) {
throw new Exception ("Access Denied.");
}
MessageResources rsc = getResources(request);
User user = Web.getUser(request.getSession());
ChameleonForm frm = (ChameleonForm) form;
ActionMessages errors = new ActionMessages();
String op = (request.getParameter("op")==null)
? (frm.getOp()==null || frm.getOp().length()==0)
? (request.getAttribute("op")==null)
? null
: request.getAttribute("op").toString()
: frm.getOp()
: request.getParameter("op");
if(op==null || op.trim().length()==0)
op = rsc.getMessage("op.view");
frm.setOp(op);
// First Access - display blank form
if ( op.equals(rsc.getMessage("op.view")) ) {
LookupTables.setupTimetableManagers(request);
}
// Change User
if ( op.equals(rsc.getMessage("button.changeUser")) ) {
try {
doSwitch(request, frm, user);
return mapping.findForward("reload");
}
catch(Exception e) {
Debug.error(e);
errors.add("exception",
new ActionMessage("errors.generic", e.getMessage()) );
saveErrors(request, errors);
LookupTables.setupTimetableManagers(request);
return mapping.findForward("displayForm");
}
}
return mapping.findForward("displayForm");
}
|
diff --git a/src/bspkrs/mmv/version/AppVersionChecker.java b/src/bspkrs/mmv/version/AppVersionChecker.java
index 02b0c9c..fbc4020 100644
--- a/src/bspkrs/mmv/version/AppVersionChecker.java
+++ b/src/bspkrs/mmv/version/AppVersionChecker.java
@@ -1,157 +1,160 @@
/*
* Copyright (C) 2013 bspkrs
*
* 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 bspkrs.mmv.version;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
import java.util.prefs.Preferences;
public class AppVersionChecker
{
private URL versionURL;
private final String appName;
private final String newVer;
private final String oldVer;
private String updateURL;
private String[] logMsg;
private String[] dialogMsg;
private Preferences versionCheckTracker = Preferences.userNodeForPackage(AppVersionChecker.class);
private final String LAST_VERSION_FOUND = "lastversionfound";
private final String lastNewVersionFound;
public AppVersionChecker(String appName, String oldVer, String versionURL, String updateURL, String[] logMsg, String[] dialogMsg, int timeoutMS)
{
this.appName = appName;
this.oldVer = oldVer;
this.updateURL = updateURL;
this.logMsg = logMsg;
this.dialogMsg = dialogMsg;
try
{
this.versionURL = new URL(versionURL);
}
catch (Throwable ignore)
{}
String[] versionLines = loadTextFromURL(this.versionURL, new String[] { oldVer }, timeoutMS);
newVer = versionLines[0].trim();
- // Keep track of the versions we've seen to keep from nagging users with new version notifications beyond the first time
- lastNewVersionFound = versionCheckTracker.get(LAST_VERSION_FOUND, oldVer);
+ // Keep track of the versions we've seen to keep from nagging users with new version notifications beyond the first time
+ if (isCurrentVersion(oldVer, newVer))
+ lastNewVersionFound = newVer;
+ else
+ lastNewVersionFound = versionCheckTracker.get(LAST_VERSION_FOUND, oldVer);
if (!isCurrentVersion(lastNewVersionFound, newVer))
versionCheckTracker.put(LAST_VERSION_FOUND, newVer);
else
versionCheckTracker.put(LAST_VERSION_FOUND, lastNewVersionFound);
// Override instantiated updateURL with second line of version file if
// it exists and is non-blank
if (versionLines.length > 1 && versionLines[1].trim().length() != 0)
this.updateURL = versionLines[1];
setLogMessage(logMsg);
setDialogMessage(dialogMsg);
}
public AppVersionChecker(String appName, String oldVer, String versionURL, String updateURL)
{
this(appName, oldVer, versionURL, updateURL, new String[] { "{appName} {oldVer} is out of date! Visit {updateURL} to download the latest release ({newVer})." }, new String[] { "{appName} {newVer} is out! Download the latest from {updateURL}" }, 5000);
}
public void checkVersionWithLogging()
{
if (!isCurrentVersion(oldVer, newVer))
for (String msg : logMsg)
System.out.println(msg);
}
public void setLogMessage(String[] logMsg)
{
this.logMsg = logMsg;
for (int i = 0; i < this.logMsg.length; i++)
this.logMsg[i] = replaceAllTags(this.logMsg[i]);
}
public void setDialogMessage(String[] dialogMsg)
{
this.dialogMsg = dialogMsg;
for (int i = 0; i < this.dialogMsg.length; i++)
this.dialogMsg[i] = replaceAllTags(this.dialogMsg[i]);
}
public String[] getLogMessage()
{
return logMsg;
}
public String[] getDialogMessage()
{
return dialogMsg;
}
public boolean isCurrentVersion()
{
return isCurrentVersion(lastNewVersionFound, newVer);
}
public static boolean isCurrentVersion(String oldVer, String newVer)
{
List<String> list = new ArrayList<String>();
list.add(oldVer);
list.add(newVer);
Collections.sort(list, new NaturalOrderComparator());
return list.get(1).equals(oldVer);
}
private String replaceAllTags(String s)
{
return s.replace("{oldVer}", oldVer).replace("{newVer}", newVer).replace("{appName}", appName).replace("{updateURL}", updateURL);
}
private String[] loadTextFromURL(URL url, String[] defaultValue, int timeoutMS)
{
List<String> arraylist = new ArrayList<String>();
Scanner scanner = null;
try
{
URLConnection uc = url.openConnection();
uc.setReadTimeout(timeoutMS);
uc.setConnectTimeout(timeoutMS);
scanner = new Scanner(uc.getInputStream(), "UTF-8");
}
catch (Throwable e)
{
return defaultValue;
}
while (scanner.hasNextLine())
{
arraylist.add(scanner.nextLine());
}
scanner.close();
return arraylist.toArray(new String[arraylist.size()]);
}
}
| true | true | public AppVersionChecker(String appName, String oldVer, String versionURL, String updateURL, String[] logMsg, String[] dialogMsg, int timeoutMS)
{
this.appName = appName;
this.oldVer = oldVer;
this.updateURL = updateURL;
this.logMsg = logMsg;
this.dialogMsg = dialogMsg;
try
{
this.versionURL = new URL(versionURL);
}
catch (Throwable ignore)
{}
String[] versionLines = loadTextFromURL(this.versionURL, new String[] { oldVer }, timeoutMS);
newVer = versionLines[0].trim();
// Keep track of the versions we've seen to keep from nagging users with new version notifications beyond the first time
lastNewVersionFound = versionCheckTracker.get(LAST_VERSION_FOUND, oldVer);
if (!isCurrentVersion(lastNewVersionFound, newVer))
versionCheckTracker.put(LAST_VERSION_FOUND, newVer);
else
versionCheckTracker.put(LAST_VERSION_FOUND, lastNewVersionFound);
// Override instantiated updateURL with second line of version file if
// it exists and is non-blank
if (versionLines.length > 1 && versionLines[1].trim().length() != 0)
this.updateURL = versionLines[1];
setLogMessage(logMsg);
setDialogMessage(dialogMsg);
}
| public AppVersionChecker(String appName, String oldVer, String versionURL, String updateURL, String[] logMsg, String[] dialogMsg, int timeoutMS)
{
this.appName = appName;
this.oldVer = oldVer;
this.updateURL = updateURL;
this.logMsg = logMsg;
this.dialogMsg = dialogMsg;
try
{
this.versionURL = new URL(versionURL);
}
catch (Throwable ignore)
{}
String[] versionLines = loadTextFromURL(this.versionURL, new String[] { oldVer }, timeoutMS);
newVer = versionLines[0].trim();
// Keep track of the versions we've seen to keep from nagging users with new version notifications beyond the first time
if (isCurrentVersion(oldVer, newVer))
lastNewVersionFound = newVer;
else
lastNewVersionFound = versionCheckTracker.get(LAST_VERSION_FOUND, oldVer);
if (!isCurrentVersion(lastNewVersionFound, newVer))
versionCheckTracker.put(LAST_VERSION_FOUND, newVer);
else
versionCheckTracker.put(LAST_VERSION_FOUND, lastNewVersionFound);
// Override instantiated updateURL with second line of version file if
// it exists and is non-blank
if (versionLines.length > 1 && versionLines[1].trim().length() != 0)
this.updateURL = versionLines[1];
setLogMessage(logMsg);
setDialogMessage(dialogMsg);
}
|
diff --git a/target_explorer/plugins/org.eclipse.tcf.te.tests/src/org/eclipse/tcf/te/tests/tcf/processes/model/ProcessModelTestCase.java b/target_explorer/plugins/org.eclipse.tcf.te.tests/src/org/eclipse/tcf/te/tests/tcf/processes/model/ProcessModelTestCase.java
index 72ae606e7..48ff6a3cc 100644
--- a/target_explorer/plugins/org.eclipse.tcf.te.tests/src/org/eclipse/tcf/te/tests/tcf/processes/model/ProcessModelTestCase.java
+++ b/target_explorer/plugins/org.eclipse.tcf.te.tests/src/org/eclipse/tcf/te/tests/tcf/processes/model/ProcessModelTestCase.java
@@ -1,125 +1,126 @@
/*******************************************************************************
* Copyright (c) 2012 Wind River Systems, Inc. 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:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.tcf.te.tests.tcf.processes.model;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.tcf.protocol.Protocol;
import org.eclipse.tcf.te.core.async.AsyncCallbackCollector;
import org.eclipse.tcf.te.core.async.AsyncCallbackHandler;
import org.eclipse.tcf.te.runtime.callback.Callback;
import org.eclipse.tcf.te.runtime.interfaces.callback.ICallback;
import org.eclipse.tcf.te.tcf.core.async.CallbackInvocationDelegate;
import org.eclipse.tcf.te.tcf.core.model.interfaces.services.IModelRefreshService;
import org.eclipse.tcf.te.tcf.processes.core.model.ModelManager;
import org.eclipse.tcf.te.tcf.processes.core.model.interfaces.IProcessContextNode;
import org.eclipse.tcf.te.tcf.processes.core.model.interfaces.runtime.IRuntimeModel;
import org.eclipse.tcf.te.tests.tcf.TcfTestCase;
/**
* Process model test cases.
*/
public class ProcessModelTestCase extends TcfTestCase {
/**
* Provides a test suite to the caller which combines all single
* test bundled within this category.
*
* @return Test suite containing all test for this test category.
*/
public static Test getTestSuite() {
TestSuite testSuite = new TestSuite("Test TCF process monitor model"); //$NON-NLS-1$
// add ourself to the test suite
testSuite.addTestSuite(ProcessModelTestCase.class);
return testSuite;
}
//***** BEGIN SECTION: Single test methods *****
//NOTE: All method which represents a single test case must
// start with 'test'!
public void testProcessModel() {
assertNotNull("Test peer missing.", peer); //$NON-NLS-1$
assertNotNull("Test peer model missing.", peerModel); //$NON-NLS-1$
// Get the process model for the test peer model
final IRuntimeModel model = ModelManager.getRuntimeModel(peerModel);
assertNotNull("Failed to get runtime model for peer model.", model); //$NON-NLS-1$
// Create a callback handler to receive all callbacks necessary to
// traverse through the model
final AsyncCallbackHandler handler = new AsyncCallbackHandler();
assertNotNull("Failed to create asynchronous callback handler.", handler); //$NON-NLS-1$
final AtomicReference<IStatus> statusRef = new AtomicReference<IStatus>();
final Callback callback = new Callback() {
@Override
protected void internalDone(Object caller, IStatus status) {
statusRef.set(status);
handler.removeCallback(this);
}
};
+ handler.addCallback(callback);
Runnable runnable = new Runnable() {
@Override
public void run() {
final AsyncCallbackCollector collector = new AsyncCallbackCollector(new Callback() {
@Override
protected void internalDone(Object caller, IStatus status) {
callback.done(caller, status != null ? status : Status.OK_STATUS);
}
}, new CallbackInvocationDelegate());
// Refresh the whole model from the top
final ICallback c1 = new AsyncCallbackCollector.SimpleCollectorCallback(collector);
model.getService(IModelRefreshService.class).refresh(new Callback() {
/* (non-Javadoc)
* @see org.eclipse.tcf.te.runtime.callback.Callback#internalDone(java.lang.Object, org.eclipse.core.runtime.IStatus)
*/
@Override
protected void internalDone(Object caller, IStatus status) {
if (status.getSeverity() != IStatus.ERROR) {
// Get all processes, loop over them and refresh each of it
List<IProcessContextNode> processes = model.getChildren(IProcessContextNode.class);
for (IProcessContextNode process : processes) {
final ICallback c2 = new AsyncCallbackCollector.SimpleCollectorCallback(collector);
model.getService(IModelRefreshService.class).refresh(process, c2);
}
}
c1.done(caller, status);
}
});
collector.initDone();
}
};
Protocol.invokeLater(runnable);
waitAndDispatch(0, handler.getConditionTester());
IStatus status = statusRef.get();
assertNotNull("Missing return status.", status); //$NON-NLS-1$
assertFalse("Process runtime model refresh failed. Possible cause: " + status.getMessage(), status.getSeverity() == IStatus.ERROR); //$NON-NLS-1$
ModelManager.disposeRuntimeModel(peerModel);
}
//***** END SECTION: Single test methods *****
}
| true | true | public void testProcessModel() {
assertNotNull("Test peer missing.", peer); //$NON-NLS-1$
assertNotNull("Test peer model missing.", peerModel); //$NON-NLS-1$
// Get the process model for the test peer model
final IRuntimeModel model = ModelManager.getRuntimeModel(peerModel);
assertNotNull("Failed to get runtime model for peer model.", model); //$NON-NLS-1$
// Create a callback handler to receive all callbacks necessary to
// traverse through the model
final AsyncCallbackHandler handler = new AsyncCallbackHandler();
assertNotNull("Failed to create asynchronous callback handler.", handler); //$NON-NLS-1$
final AtomicReference<IStatus> statusRef = new AtomicReference<IStatus>();
final Callback callback = new Callback() {
@Override
protected void internalDone(Object caller, IStatus status) {
statusRef.set(status);
handler.removeCallback(this);
}
};
Runnable runnable = new Runnable() {
@Override
public void run() {
final AsyncCallbackCollector collector = new AsyncCallbackCollector(new Callback() {
@Override
protected void internalDone(Object caller, IStatus status) {
callback.done(caller, status != null ? status : Status.OK_STATUS);
}
}, new CallbackInvocationDelegate());
// Refresh the whole model from the top
final ICallback c1 = new AsyncCallbackCollector.SimpleCollectorCallback(collector);
model.getService(IModelRefreshService.class).refresh(new Callback() {
/* (non-Javadoc)
* @see org.eclipse.tcf.te.runtime.callback.Callback#internalDone(java.lang.Object, org.eclipse.core.runtime.IStatus)
*/
@Override
protected void internalDone(Object caller, IStatus status) {
if (status.getSeverity() != IStatus.ERROR) {
// Get all processes, loop over them and refresh each of it
List<IProcessContextNode> processes = model.getChildren(IProcessContextNode.class);
for (IProcessContextNode process : processes) {
final ICallback c2 = new AsyncCallbackCollector.SimpleCollectorCallback(collector);
model.getService(IModelRefreshService.class).refresh(process, c2);
}
}
c1.done(caller, status);
}
});
collector.initDone();
}
};
Protocol.invokeLater(runnable);
waitAndDispatch(0, handler.getConditionTester());
IStatus status = statusRef.get();
assertNotNull("Missing return status.", status); //$NON-NLS-1$
assertFalse("Process runtime model refresh failed. Possible cause: " + status.getMessage(), status.getSeverity() == IStatus.ERROR); //$NON-NLS-1$
ModelManager.disposeRuntimeModel(peerModel);
}
| public void testProcessModel() {
assertNotNull("Test peer missing.", peer); //$NON-NLS-1$
assertNotNull("Test peer model missing.", peerModel); //$NON-NLS-1$
// Get the process model for the test peer model
final IRuntimeModel model = ModelManager.getRuntimeModel(peerModel);
assertNotNull("Failed to get runtime model for peer model.", model); //$NON-NLS-1$
// Create a callback handler to receive all callbacks necessary to
// traverse through the model
final AsyncCallbackHandler handler = new AsyncCallbackHandler();
assertNotNull("Failed to create asynchronous callback handler.", handler); //$NON-NLS-1$
final AtomicReference<IStatus> statusRef = new AtomicReference<IStatus>();
final Callback callback = new Callback() {
@Override
protected void internalDone(Object caller, IStatus status) {
statusRef.set(status);
handler.removeCallback(this);
}
};
handler.addCallback(callback);
Runnable runnable = new Runnable() {
@Override
public void run() {
final AsyncCallbackCollector collector = new AsyncCallbackCollector(new Callback() {
@Override
protected void internalDone(Object caller, IStatus status) {
callback.done(caller, status != null ? status : Status.OK_STATUS);
}
}, new CallbackInvocationDelegate());
// Refresh the whole model from the top
final ICallback c1 = new AsyncCallbackCollector.SimpleCollectorCallback(collector);
model.getService(IModelRefreshService.class).refresh(new Callback() {
/* (non-Javadoc)
* @see org.eclipse.tcf.te.runtime.callback.Callback#internalDone(java.lang.Object, org.eclipse.core.runtime.IStatus)
*/
@Override
protected void internalDone(Object caller, IStatus status) {
if (status.getSeverity() != IStatus.ERROR) {
// Get all processes, loop over them and refresh each of it
List<IProcessContextNode> processes = model.getChildren(IProcessContextNode.class);
for (IProcessContextNode process : processes) {
final ICallback c2 = new AsyncCallbackCollector.SimpleCollectorCallback(collector);
model.getService(IModelRefreshService.class).refresh(process, c2);
}
}
c1.done(caller, status);
}
});
collector.initDone();
}
};
Protocol.invokeLater(runnable);
waitAndDispatch(0, handler.getConditionTester());
IStatus status = statusRef.get();
assertNotNull("Missing return status.", status); //$NON-NLS-1$
assertFalse("Process runtime model refresh failed. Possible cause: " + status.getMessage(), status.getSeverity() == IStatus.ERROR); //$NON-NLS-1$
ModelManager.disposeRuntimeModel(peerModel);
}
|
diff --git a/src/main/java/org/jbei/ice/lib/bulkupload/BulkUploadController.java b/src/main/java/org/jbei/ice/lib/bulkupload/BulkUploadController.java
index e52a108e6..0dcc3a682 100755
--- a/src/main/java/org/jbei/ice/lib/bulkupload/BulkUploadController.java
+++ b/src/main/java/org/jbei/ice/lib/bulkupload/BulkUploadController.java
@@ -1,837 +1,837 @@
package org.jbei.ice.lib.bulkupload;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.jbei.ice.client.entry.display.model.SampleStorage;
import org.jbei.ice.controllers.ControllerFactory;
import org.jbei.ice.controllers.common.ControllerException;
import org.jbei.ice.lib.account.AccountController;
import org.jbei.ice.lib.account.PreferencesController;
import org.jbei.ice.lib.account.model.Account;
import org.jbei.ice.lib.account.model.Preference;
import org.jbei.ice.lib.dao.DAOException;
import org.jbei.ice.lib.entry.EntryController;
import org.jbei.ice.lib.entry.EntryUtil;
import org.jbei.ice.lib.entry.attachment.Attachment;
import org.jbei.ice.lib.entry.attachment.AttachmentController;
import org.jbei.ice.lib.entry.model.Entry;
import org.jbei.ice.lib.entry.model.Plasmid;
import org.jbei.ice.lib.entry.model.Strain;
import org.jbei.ice.lib.entry.sample.SampleController;
import org.jbei.ice.lib.entry.sample.model.Sample;
import org.jbei.ice.lib.entry.sequence.SequenceController;
import org.jbei.ice.lib.group.Group;
import org.jbei.ice.lib.logging.Logger;
import org.jbei.ice.lib.models.Storage;
import org.jbei.ice.lib.permissions.PermissionException;
import org.jbei.ice.lib.permissions.model.Permission;
import org.jbei.ice.lib.shared.EntryAddType;
import org.jbei.ice.lib.shared.dto.ConfigurationKey;
import org.jbei.ice.lib.shared.dto.PartSample;
import org.jbei.ice.lib.shared.dto.bulkupload.BulkUploadAutoUpdate;
import org.jbei.ice.lib.shared.dto.bulkupload.BulkUploadInfo;
import org.jbei.ice.lib.shared.dto.bulkupload.BulkUploadStatus;
import org.jbei.ice.lib.shared.dto.bulkupload.EditMode;
import org.jbei.ice.lib.shared.dto.bulkupload.EntryField;
import org.jbei.ice.lib.shared.dto.bulkupload.PreferenceInfo;
import org.jbei.ice.lib.shared.dto.entry.AttachmentInfo;
import org.jbei.ice.lib.shared.dto.entry.EntryType;
import org.jbei.ice.lib.shared.dto.entry.PartData;
import org.jbei.ice.lib.shared.dto.entry.Visibility;
import org.jbei.ice.lib.shared.dto.group.UserGroup;
import org.jbei.ice.lib.shared.dto.permission.AccessPermission;
import org.jbei.ice.lib.shared.dto.user.AccountType;
import org.jbei.ice.lib.shared.dto.user.PreferenceKey;
import org.jbei.ice.lib.shared.dto.user.User;
import org.jbei.ice.lib.utils.Emailer;
import org.jbei.ice.lib.utils.Utils;
import org.jbei.ice.server.InfoToModelFactory;
import org.jbei.ice.server.ModelToInfoFactory;
/**
* Controller for dealing with bulk imports (including drafts)
*
* @author Hector Plahar
*/
public class BulkUploadController {
private BulkUploadDAO dao;
private AccountController accountController;
private EntryController entryController;
private AttachmentController attachmentController;
private SequenceController sequenceController;
private SampleController sampleController;
private PreferencesController preferencesController;
/**
* Initialises dao and controller dependencies. These need be injected
*/
public BulkUploadController() {
dao = new BulkUploadDAO();
accountController = ControllerFactory.getAccountController();
entryController = ControllerFactory.getEntryController();
attachmentController = ControllerFactory.getAttachmentController();
sequenceController = ControllerFactory.getSequenceController();
sampleController = ControllerFactory.getSampleController();
preferencesController = ControllerFactory.getPreferencesController();
}
/**
* Retrieves list of bulk imports that are owned by the system. System ownership is assigned to
* all bulk imports that are submitted by non-admins and indicates that it is pending approval.
* <p>Administrative privileges are required for making this call
*
* @param account account for user making call. expected to be an administrator
* @return list of bulk imports pending verification
* @throws ControllerException
* @throws PermissionException
*/
public ArrayList<BulkUploadInfo> retrievePendingImports(Account account)
throws ControllerException, PermissionException {
// check for admin privileges
if (!accountController.isAdministrator(account))
throw new PermissionException("Administrative privileges are required!");
ArrayList<BulkUploadInfo> infoList = new ArrayList<>();
ArrayList<BulkUpload> results;
try {
results = dao.retrieveByStatus(BulkUploadStatus.PENDING_APPROVAL);
if (results == null || results.isEmpty())
return infoList;
} catch (DAOException e) {
throw new ControllerException(e);
}
for (BulkUpload draft : results) {
BulkUploadInfo info = new BulkUploadInfo();
Account draftAccount = draft.getAccount();
User user = new User();
user.setEmail(draftAccount.getEmail());
user.setFirstName(draftAccount.getFirstName());
user.setLastName(draftAccount.getLastName());
info.setAccount(user);
info.setId(draft.getId());
info.setLastUpdate(draft.getLastUpdateTime());
int count = draft.getContents().size();
info.setCount(count);
info.setType(EntryAddType.stringToType(draft.getImportType()));
info.setCreated(draft.getCreationTime());
info.setName(draft.getName());
infoList.add(info);
}
return infoList;
}
/**
* Retrieves bulk import and entries associated with it that are referenced by the id in the parameter. Only
* owners or administrators are allowed to retrieve bulk imports
*
* @param account account for user requesting
* @param id unique identifier for bulk import
* @return data transfer object with the retrieved bulk import data and associated entries
* @throws ControllerException
* @throws PermissionException
*/
public BulkUploadInfo retrieveById(Account account, long id, int start, int limit)
throws ControllerException, PermissionException {
BulkUpload draft;
try {
draft = dao.retrieveById(id);
if (draft == null)
return null;
} catch (DAOException e) {
throw new ControllerException(e);
}
boolean isModerator = accountController.isAdministrator(account);
boolean isOwner = account.equals(draft.getAccount());
// check for permissions to retrieve this bulk import
if (!isModerator && !isOwner) {
throw new PermissionException("Insufficient privileges by " + account.getEmail()
+ " to view bulk import for " + draft.getAccount().getEmail());
}
// convert bulk import db object to data transfer object
int size = 0;
try {
size = dao.retrieveSavedDraftCount(id);
} catch (DAOException e) {
Logger.error(e);
}
BulkUploadInfo draftInfo = BulkUpload.toDTO(draft);
draftInfo.setCount(size);
EntryAddType type = EntryAddType.stringToType(draft.getImportType());
EntryType retrieveType = type == EntryAddType.STRAIN_WITH_PLASMID ? EntryType.STRAIN : null;
// retrieve the entries associated with the bulk import
ArrayList<Entry> contents;
try {
contents = dao.retrieveDraftEntries(retrieveType, id, start, limit);
} catch (DAOException e) {
Logger.error(e);
throw new ControllerException(e);
}
// convert
draftInfo.getEntryList().addAll(convertParts(account, type, contents));
HashMap<PreferenceKey, String> userSaved = null;
try {
ArrayList<PreferenceKey> keys = new ArrayList<>();
keys.add(PreferenceKey.FUNDING_SOURCE);
keys.add(PreferenceKey.PRINCIPAL_INVESTIGATOR);
userSaved = preferencesController.retrieveAccountPreferences(account, keys);
} catch (ControllerException ce) {
// bulk upload should continue to work in the event of this exception
Logger.warn(ce.getMessage());
}
// retrieve preferences (if any: this is where you also add user's saved preferences if it does not exist)
for (Preference preference : draft.getPreferences()) {
PreferenceKey preferenceKey = PreferenceKey.fromString(preference.getKey());
if (preferenceKey != null && userSaved != null && userSaved.containsKey(preferenceKey))
userSaved.remove(preferenceKey); // bulk preferences has precedence over user saved
PreferenceInfo preferenceInfo = Preference.toDTO(preference);
if (preferenceInfo != null)
draftInfo.getPreferences().add(preferenceInfo);
}
if (userSaved != null && !userSaved.isEmpty()) {
for (Map.Entry<PreferenceKey, String> entry : userSaved.entrySet()) {
PreferenceInfo preferenceInfo = new PreferenceInfo(true, entry.getKey().toString(), entry.getValue());
draftInfo.getPreferences().add(preferenceInfo);
}
}
return draftInfo;
}
protected ArrayList<PartData> convertParts(Account account, EntryAddType type, ArrayList<Entry> contents)
throws ControllerException {
ArrayList<PartData> addList = new ArrayList<>();
for (Entry entry : contents) {
ArrayList<Attachment> attachments = attachmentController.getByEntry(account, entry);
boolean hasSequence = sequenceController.hasSequence(entry.getId());
boolean hasOriginalSequence = sequenceController.hasOriginalSequence(entry.getId());
PartData info = ModelToInfoFactory.getInfo(entry);
ArrayList<AttachmentInfo> attachmentInfos = ModelToInfoFactory.getAttachments(attachments);
info.setAttachments(attachmentInfos);
info.setHasAttachment(!attachmentInfos.isEmpty());
info.setHasSequence(hasSequence);
info.setHasOriginalSequence(hasOriginalSequence);
// retrieve permission
Set<Permission> entryPermissions = entry.getPermissions();
if (entryPermissions != null && !entryPermissions.isEmpty()) {
for (Permission permission : entryPermissions) {
info.getAccessPermissions().add(Permission.toDTO(permission));
}
}
// this conditional statement makes sure that plasmids are ignored if we are dealing
// with strain with plasmid
if (type != null && type == EntryAddType.STRAIN_WITH_PLASMID) {
if (entry.getRecordType().equalsIgnoreCase(EntryType.STRAIN.getName()) &&
!entry.getLinkedEntries().isEmpty()) {
// get plasmids
Entry plasmid = (Entry) entry.getLinkedEntries().toArray()[0];
attachments = attachmentController.getByEntry(account, plasmid);
hasSequence = sequenceController.hasSequence(plasmid.getId());
hasOriginalSequence = sequenceController.hasOriginalSequence(plasmid.getId());
PartData plasmidInfo = ModelToInfoFactory.getInfo(plasmid);
ArrayList<AttachmentInfo> partAttachments = ModelToInfoFactory.getAttachments(attachments);
plasmidInfo.setAttachments(partAttachments);
plasmidInfo.setHasAttachment(!partAttachments.isEmpty());
plasmidInfo.setHasSequence(hasSequence);
plasmidInfo.setHasOriginalSequence(hasOriginalSequence);
Set<Permission> permissions = plasmid.getPermissions();
if (permissions != null && !permissions.isEmpty()) {
for (Permission permission : permissions) {
plasmidInfo.getAccessPermissions().add(Permission.toDTO(permission));
}
}
info.setInfo(plasmidInfo);
} else
continue;
}
SampleStorage sampleStorage = retrieveSampleStorage(entry);
if (sampleStorage != null) {
ArrayList<SampleStorage> sampleStorageArrayList = new ArrayList<>();
sampleStorageArrayList.add(sampleStorage);
info.setSampleMap(sampleStorageArrayList);
}
addList.add(info);
}
return addList;
}
/**
* Retrieves list of parts that are intended to be edited in bulk. User must
* have write permissions on all parts
*
* @param account user account making request. Should have write permissions on all accounts
* @param partIds unique part identifiers
* @return list of retrieved part data wrapped in the bulk upload data transfer object
* @throws ControllerException
*/
public BulkUploadInfo getPartsForBulkEdit(Account account, ArrayList<Long> partIds) throws ControllerException {
ArrayList<Entry> parts = entryController.getEntriesByIdSet(account, partIds);
BulkUploadInfo bulkUploadInfo = new BulkUploadInfo();
bulkUploadInfo.getEntryList().addAll(convertParts(account, null, parts));
return bulkUploadInfo;
}
protected SampleStorage retrieveSampleStorage(Entry entry) {
ArrayList<Sample> samples = null;
try {
if (!sampleController.hasSample(entry))
return null;
// samples = sampleController.getSamples(entry);
} catch (ControllerException e) {
return null;
}
if (samples != null && !samples.isEmpty()) {
Sample sample = samples.get(0);
SampleStorage sampleStorage = new SampleStorage();
// convert sample to info
PartSample partSample = new PartSample();
partSample.setCreationTime(sample.getCreationTime());
partSample.setLabel(sample.getLabel());
partSample.setNotes(sample.getNotes());
partSample.setDepositor(sample.getDepositor());
sampleStorage.setPartSample(partSample);
// convert sample to info
Storage storage = sample.getStorage();
while (storage != null) {
if (storage.getStorageType() == Storage.StorageType.SCHEME) {
partSample.setLocationId(storage.getId() + "");
partSample.setLocation(storage.getName());
break;
}
sampleStorage.getStorageList().add(ModelToInfoFactory.getStorageInfo(storage));
storage = storage.getParent();
}
return sampleStorage;
}
return null;
}
/**
* Retrieves list of user saved bulk imports
*
* @param account account of requesting user
* @param userAccount account whose saved drafts are being requested
* @return list of draft infos representing saved drafts.
* @throws ControllerException
*/
public ArrayList<BulkUploadInfo> retrieveByUser(Account account, Account userAccount)
throws ControllerException {
ArrayList<BulkUpload> results;
try {
results = dao.retrieveByAccount(userAccount);
} catch (DAOException e) {
throw new ControllerException(e);
}
ArrayList<BulkUploadInfo> infoArrayList = new ArrayList<>();
for (BulkUpload draft : results) {
Account draftAccount = draft.getAccount();
boolean isOwner = account.equals(draftAccount);
boolean isAdmin = accountController.isAdministrator(account);
if (!isOwner && !isAdmin)
continue;
BulkUploadInfo draftInfo = new BulkUploadInfo();
draftInfo.setCreated(draft.getCreationTime());
draftInfo.setLastUpdate(draft.getLastUpdateTime());
draftInfo.setId(draft.getId());
draftInfo.setName(draft.getName());
draftInfo.setType(EntryAddType.stringToType(draft.getImportType()));
draftInfo.setCount(draft.getContents().size());
// set the account info
User user = new User();
user.setEmail(draftAccount.getEmail());
user.setFirstName(draftAccount.getFirstName());
user.setLastName(draftAccount.getLastName());
draftInfo.setAccount(user);
infoArrayList.add(draftInfo);
}
return infoArrayList;
}
/**
* Deletes a bulk import draft referenced by a unique identifier. only owners of the bulk import
* or administrators are permitted to delete bulk imports
*
* @param requesting account of user making the request
* @param draftId unique identifier for bulk import
* @return deleted bulk import
* @throws ControllerException
* @throws PermissionException
*/
public BulkUploadInfo deleteDraftById(Account requesting, long draftId)
throws ControllerException, PermissionException {
BulkUpload draft;
try {
draft = dao.retrieveById(draftId);
if (draft == null)
throw new ControllerException("Could not retrieve draft with id \"" + draftId + "\"");
Account draftAccount = draft.getAccount();
if (!requesting.equals(draftAccount) && !accountController.isAdministrator(requesting))
throw new PermissionException("No permissions to delete draft " + draftId);
// delete all associated entries. for strain with plasmids both are returned
for (Entry entry : draft.getContents()) {
try {
entryController.delete(requesting, entry.getId());
} catch (PermissionException pe) {
Logger.warn("Could not delete entry " + entry.getRecordId() + " for bulk upload " + draftId);
}
}
dao.delete(draft);
} catch (DAOException e) {
throw new ControllerException(e);
}
BulkUploadInfo draftInfo = BulkUpload.toDTO(draft);
User user = Account.toDTO(draft.getAccount());
draftInfo.setAccount(user);
return draftInfo;
}
public BulkUploadAutoUpdate autoUpdateBulkUpload(Account account, BulkUploadAutoUpdate autoUpdate,
EntryAddType addType) throws ControllerException {
BulkUpload draft = null;
if (autoUpdate.getEditMode() != EditMode.BULK_EDIT) {
// deal with bulk upload
try {
draft = dao.retrieveById(autoUpdate.getBulkUploadId());
if (draft == null) {
- // validate add type and entrytype
+ // validate add type and entry type
if (addType != EntryAddType.STRAIN_WITH_PLASMID && EntryType.nameToType(
- addType.name()) != autoUpdate
- .getType()) {
+ addType.name()) != autoUpdate.getType()) {
throw new ControllerException("Incompatible add type [" + addType.toString()
+ "] and auto update entry type ["
+ autoUpdate.getType().toString() + "]");
}
draft = new BulkUpload();
draft.setName("Untitled");
draft.setAccount(account);
draft.setStatus(BulkUploadStatus.IN_PROGRESS);
draft.setImportType(addType.toString());
draft.setCreationTime(new Date(System.currentTimeMillis()));
draft.setLastUpdateTime(draft.getCreationTime());
dao.save(draft);
autoUpdate.setBulkUploadId(draft.getId());
}
} catch (DAOException de) {
throw new ControllerException(de);
}
}
// for strain with plasmid this is the strain
Entry entry = entryController.get(account, autoUpdate.getEntryId());
Entry otherEntry = null; // for strain with plasmid this is the entry
// if entry is null, create entry
if (entry == null) {
entry = EntryUtil.createEntryFromType(autoUpdate.getType(), account.getFullName(), account.getEmail());
if (entry == null)
throw new ControllerException("Don't know what to do with entry type");
entry = entryController.createEntry(account, entry, null);
// creates strain/plasmid at the same time for strain with plasmid
if (addType == EntryAddType.STRAIN_WITH_PLASMID) {
if (autoUpdate.getType() == EntryType.STRAIN) {
// created strain, now create plasmid
otherEntry = new Plasmid();
otherEntry.setOwner(account.getFullName());
otherEntry.setOwnerEmail(account.getEmail());
otherEntry.setCreator(account.getFullName());
otherEntry.setCreatorEmail(account.getEmail());
otherEntry.setVisibility(Visibility.DRAFT.getValue());
entryController.createEntry(account, otherEntry, null);
// link the plasmid to strain (strain gets updated later on)
entry.getLinkedEntries().add(otherEntry);
} else {
// created plasmid, now create strain and link
otherEntry = entry;
entry = new Strain();
entry.setOwner(account.getFullName());
entry.setOwnerEmail(account.getEmail());
entry.setCreator(account.getFullName());
entry.setCreatorEmail(account.getEmail());
entry.getLinkedEntries().add(otherEntry);
entry.setVisibility(Visibility.DRAFT.getValue());
entryController.createEntry(account, entry, null);
}
}
autoUpdate.setEntryId(entry.getId());
if (draft != null) {
draft.getContents().add(entry);
}
} else {
// entry not null (fetch plasmid for strain) if this is a strain with plasmid
if (addType == EntryAddType.STRAIN_WITH_PLASMID && !entry.getLinkedEntries().isEmpty()) {
otherEntry = (Entry) entry.getLinkedEntries().toArray()[0];
}
}
try {
// now update the values (for strain with plasmid, some values are for both
for (Map.Entry<EntryField, String> set : autoUpdate.getKeyValue().entrySet()) {
String value = set.getValue();
EntryField field = set.getKey();
Entry[] ret = InfoToModelFactory.infoToEntryForField(entry, otherEntry, value, field);
entry = ret[0];
if (ret.length == 2) {
otherEntry = ret[1];
}
}
if (otherEntry != null && autoUpdate.getEditMode() != EditMode.BULK_EDIT) {
if (otherEntry.getVisibility() == null || otherEntry.getVisibility() != Visibility.DRAFT.getValue())
otherEntry.setVisibility(Visibility.DRAFT.getValue());
entryController.update(account, otherEntry);
}
if ((entry.getVisibility() == null || entry.getVisibility() != Visibility.DRAFT.getValue())
&& autoUpdate.getEditMode() != EditMode.BULK_EDIT)
entry.setVisibility(Visibility.DRAFT.getValue());
// set the plasmids and update
- if (entry.getRecordType().equalsIgnoreCase(EntryType.STRAIN.toString())) {
+ if (entry.getRecordType().equalsIgnoreCase(EntryType.STRAIN.toString())
+ && entry.getLinkedEntries().isEmpty()) {
Strain strain = (Strain) entry;
entryController.setStrainPlasmids(account, strain, strain.getPlasmids());
}
entryController.update(account, entry);
} catch (PermissionException e) {
throw new ControllerException(e);
}
// update bulk upload. even if no new entry was created, entries belonging to it was updated
if (draft != null) {
try {
draft.setLastUpdateTime(new Date(System.currentTimeMillis()));
autoUpdate.setLastUpdate(draft.getLastUpdateTime());
dao.update(draft);
} catch (DAOException de) {
throw new ControllerException(de);
}
}
return autoUpdate;
}
/**
* Submits a bulk import that has been saved. This action is restricted to the owner of the
* draft or to administrators.
*
* @param account Account of user performing save
* @param draftId unique identifier for saved bulk import
* @return true, if draft was sa
*/
public boolean submitBulkImportDraft(Account account, long draftId, ArrayList<UserGroup> readGroups)
throws ControllerException, PermissionException {
// retrieve draft
BulkUpload draft;
try {
draft = dao.retrieveById(draftId);
} catch (DAOException e) {
throw new ControllerException(e);
}
if (draft == null)
throw new ControllerException("Could not retrieve draft by id " + draftId);
// check permissions
if (!draft.getAccount().equals(account) && !accountController.isAdministrator(account))
throw new PermissionException("User " + account.getEmail()
+ " does not have permission to update draft " + draftId);
// update permissions
if (readGroups != null && !readGroups.isEmpty()) {
updatePermissions(draft, readGroups);
}
// set preferences
Set<Preference> bulkUploadPreferences = new HashSet<>(draft.getPreferences());
if (!bulkUploadPreferences.isEmpty()) {
for (Entry entry : draft.getContents()) {
for (Preference preference : bulkUploadPreferences) {
EntryField field = EntryField.fromString(preference.getKey());
InfoToModelFactory.infoToEntryForField(entry, null, preference.getValue(), field);
}
}
}
if (!BulkUploadUtil.validate(draft)) {
Logger.warn("Attempting to submit a bulk upload draft (" + draftId + ") which does not validate");
return false;
}
boolean isStrainWithPlasmid = EntryAddType.STRAIN_WITH_PLASMID.getDisplay().equalsIgnoreCase(
draft.getImportType());
draft.setStatus(BulkUploadStatus.PENDING_APPROVAL);
draft.setLastUpdateTime(new Date(System.currentTimeMillis()));
draft.setName(account.getEmail());
try {
boolean success = dao.update(draft) != null;
if (success) {
// convert entries to pending
for (Entry entry : draft.getContents()) {
entry.setVisibility(Visibility.PENDING.getValue());
entryController.update(account, entry);
if (isStrainWithPlasmid && entry.getRecordType().equalsIgnoreCase(EntryType.STRAIN.getName())
&& !entry.getLinkedEntries().isEmpty()) {
Entry plasmid = (Entry) entry.getLinkedEntries().toArray()[0];
plasmid.setVisibility(Visibility.PENDING.getValue());
entryController.update(account, plasmid);
}
}
String email = Utils.getConfigValue(ConfigurationKey.BULK_UPLOAD_APPROVER_EMAIL);
if (email != null && !email.isEmpty()) {
String subject = Utils.getConfigValue(ConfigurationKey.PROJECT_NAME) + " Bulk Upload Notification";
String body = "A bulk upload has been submitted and is pending verification.\n\n";
body += "Please go to the following link to verify.\n\n";
body += Utils.getConfigValue(ConfigurationKey.URI_PREFIX) + "/#page=bulk";
Emailer.send(email, subject, body);
}
}
return success;
} catch (DAOException e) {
throw new ControllerException("Could not assign draft " + draftId + " to system", e);
}
}
public boolean revertSubmitted(Account account, long uploadId) throws ControllerException {
boolean isAdmin = accountController.isAdministrator(account);
if (!isAdmin) {
Logger.warn(account.getEmail() + " attempting to revert submitted bulk upload "
+ uploadId + " without admin privs");
return false;
}
try {
BulkUpload upload = dao.retrieveById(uploadId);
if (upload == null) {
Logger.warn("Could not retrieve bulk upload " + uploadId + " for reversal");
return false;
}
String previousOwner = upload.getName();
Account prevOwnerAccount = accountController.getByEmail(previousOwner);
if (prevOwnerAccount == null)
return false;
upload.setStatus(BulkUploadStatus.IN_PROGRESS);
upload.setName("Returned Upload");
upload.setLastUpdateTime(new Date());
dao.update(upload);
} catch (DAOException e) {
throw new ControllerException(e);
}
return true;
}
public boolean approveBulkImport(Account account, long id) throws ControllerException, PermissionException {
// only admins allowed
if (!accountController.isAdministrator(account)) {
throw new PermissionException("Only administrators can approve bulk imports");
}
// retrieve bulk upload in question (at this point it is owned by system)
BulkUpload bulkUpload;
try {
bulkUpload = dao.retrieveById(id);
if (bulkUpload == null)
throw new ControllerException("Could not retrieve bulk upload with id \"" + id + "\" for approval");
} catch (DAOException e) {
throw new ControllerException(e);
}
// go through passed contents
// TODO : this needs to go into a task that auto updates
for (Entry entry : bulkUpload.getContents()) {
entry.setVisibility(Visibility.OK.getValue());
Set<Entry> linked = entry.getLinkedEntries();
Entry plasmid = null;
if (linked != null && !linked.isEmpty()) {
plasmid = (Entry) linked.toArray()[0];
plasmid.setVisibility(Visibility.OK.getValue());
}
// set permissions
for (Permission permission : bulkUpload.getPermissions()) {
// add permission for entry
AccessPermission access = new AccessPermission();
access.setType(AccessPermission.Type.READ_ENTRY);
access.setTypeId(entry.getId());
access.setArticleId(permission.getGroup().getId());
access.setArticle(AccessPermission.Article.GROUP);
ControllerFactory.getPermissionController().addPermission(account, access);
if (plasmid != null) {
access.setTypeId(plasmid.getId());
ControllerFactory.getPermissionController().addPermission(account, access);
}
}
entryController.update(account, entry);
if (plasmid != null)
entryController.update(account, plasmid);
}
// when done approving, delete the bulk upload record but not the entries associated with it.
try {
bulkUpload.getContents().clear();
dao.delete(bulkUpload);
return true;
} catch (DAOException e) {
throw new ControllerException("Could not delete bulk upload " + bulkUpload.getId()
+ ". Contents were approved so please delete manually.", e);
}
}
public boolean renameDraft(Account account, long id, String draftName) throws ControllerException {
BulkUpload upload;
try {
upload = dao.retrieveById(id);
} catch (DAOException e) {
throw new ControllerException(e);
}
if (!upload.getAccount().equals(account) && account.getType() != AccountType.ADMIN)
throw new ControllerException("No permissions to rename");
upload.setName(draftName);
try {
return dao.update(upload) != null;
} catch (DAOException e) {
throw new ControllerException(e);
}
}
void updatePermissions(BulkUpload upload, ArrayList<UserGroup> groups) throws ControllerException {
try {
ArrayList<Permission> existingPermissions = new ArrayList<>(upload.getPermissions());
upload.getPermissions().clear();
// update permissions
for (UserGroup userGroup : groups) {
Group group = ControllerFactory.getGroupController().getGroupById(userGroup.getId());
if (group == null)
continue;
long startSize = upload.getPermissions().size();
// article is not unique to each permission, but the combination will be unique
// currently, permissions for bulk upload is restricted to read permissions by groups
for (Permission permission : existingPermissions) {
if (permission.getGroup().getId() == group.getId()) {
upload.getPermissions().add(permission);
break;
}
}
// existing permission was found
if (upload.getPermissions().size() > startSize)
continue;
// new permission
AccessPermission access = new AccessPermission();
access.setArticle(AccessPermission.Article.GROUP);
access.setType(AccessPermission.Type.READ_ENTRY);
access.setArticleId(group.getId());
Permission permission = ControllerFactory.getPermissionController().recordGroupPermission(access);
upload.getPermissions().add(permission);
}
dao.update(upload);
} catch (DAOException e) {
throw new ControllerException(e);
}
}
public long updatePreference(Account account, long bulkUploadId, EntryAddType addType, PreferenceInfo info)
throws ControllerException {
BulkUpload upload;
try {
upload = dao.retrieveById(bulkUploadId);
if (upload == null) {
upload = BulkUploadUtil.createNewBulkUpload(addType);
upload.setAccount(account);
upload = dao.save(upload);
}
} catch (DAOException e) {
throw new ControllerException(e);
}
if (!upload.getAccount().equals(account) && account.getType() != AccountType.ADMIN)
throw new ControllerException("No permissions");
if (info.isAdd()) {
Preference preference = preferencesController.createPreference(account, info.getKey(), info.getValue());
upload.getPreferences().add(preference);
} else {
Preference preference = preferencesController.retrievePreference(account, info.getKey(), info.getValue());
if (preference != null)
upload.getPreferences().remove(preference);
}
upload.setLastUpdateTime(new Date(System.currentTimeMillis()));
try {
dao.update(upload);
return upload.getId();
} catch (DAOException e) {
throw new ControllerException(e);
}
}
}
| false | true | public BulkUploadAutoUpdate autoUpdateBulkUpload(Account account, BulkUploadAutoUpdate autoUpdate,
EntryAddType addType) throws ControllerException {
BulkUpload draft = null;
if (autoUpdate.getEditMode() != EditMode.BULK_EDIT) {
// deal with bulk upload
try {
draft = dao.retrieveById(autoUpdate.getBulkUploadId());
if (draft == null) {
// validate add type and entrytype
if (addType != EntryAddType.STRAIN_WITH_PLASMID && EntryType.nameToType(
addType.name()) != autoUpdate
.getType()) {
throw new ControllerException("Incompatible add type [" + addType.toString()
+ "] and auto update entry type ["
+ autoUpdate.getType().toString() + "]");
}
draft = new BulkUpload();
draft.setName("Untitled");
draft.setAccount(account);
draft.setStatus(BulkUploadStatus.IN_PROGRESS);
draft.setImportType(addType.toString());
draft.setCreationTime(new Date(System.currentTimeMillis()));
draft.setLastUpdateTime(draft.getCreationTime());
dao.save(draft);
autoUpdate.setBulkUploadId(draft.getId());
}
} catch (DAOException de) {
throw new ControllerException(de);
}
}
// for strain with plasmid this is the strain
Entry entry = entryController.get(account, autoUpdate.getEntryId());
Entry otherEntry = null; // for strain with plasmid this is the entry
// if entry is null, create entry
if (entry == null) {
entry = EntryUtil.createEntryFromType(autoUpdate.getType(), account.getFullName(), account.getEmail());
if (entry == null)
throw new ControllerException("Don't know what to do with entry type");
entry = entryController.createEntry(account, entry, null);
// creates strain/plasmid at the same time for strain with plasmid
if (addType == EntryAddType.STRAIN_WITH_PLASMID) {
if (autoUpdate.getType() == EntryType.STRAIN) {
// created strain, now create plasmid
otherEntry = new Plasmid();
otherEntry.setOwner(account.getFullName());
otherEntry.setOwnerEmail(account.getEmail());
otherEntry.setCreator(account.getFullName());
otherEntry.setCreatorEmail(account.getEmail());
otherEntry.setVisibility(Visibility.DRAFT.getValue());
entryController.createEntry(account, otherEntry, null);
// link the plasmid to strain (strain gets updated later on)
entry.getLinkedEntries().add(otherEntry);
} else {
// created plasmid, now create strain and link
otherEntry = entry;
entry = new Strain();
entry.setOwner(account.getFullName());
entry.setOwnerEmail(account.getEmail());
entry.setCreator(account.getFullName());
entry.setCreatorEmail(account.getEmail());
entry.getLinkedEntries().add(otherEntry);
entry.setVisibility(Visibility.DRAFT.getValue());
entryController.createEntry(account, entry, null);
}
}
autoUpdate.setEntryId(entry.getId());
if (draft != null) {
draft.getContents().add(entry);
}
} else {
// entry not null (fetch plasmid for strain) if this is a strain with plasmid
if (addType == EntryAddType.STRAIN_WITH_PLASMID && !entry.getLinkedEntries().isEmpty()) {
otherEntry = (Entry) entry.getLinkedEntries().toArray()[0];
}
}
try {
// now update the values (for strain with plasmid, some values are for both
for (Map.Entry<EntryField, String> set : autoUpdate.getKeyValue().entrySet()) {
String value = set.getValue();
EntryField field = set.getKey();
Entry[] ret = InfoToModelFactory.infoToEntryForField(entry, otherEntry, value, field);
entry = ret[0];
if (ret.length == 2) {
otherEntry = ret[1];
}
}
if (otherEntry != null && autoUpdate.getEditMode() != EditMode.BULK_EDIT) {
if (otherEntry.getVisibility() == null || otherEntry.getVisibility() != Visibility.DRAFT.getValue())
otherEntry.setVisibility(Visibility.DRAFT.getValue());
entryController.update(account, otherEntry);
}
if ((entry.getVisibility() == null || entry.getVisibility() != Visibility.DRAFT.getValue())
&& autoUpdate.getEditMode() != EditMode.BULK_EDIT)
entry.setVisibility(Visibility.DRAFT.getValue());
// set the plasmids and update
if (entry.getRecordType().equalsIgnoreCase(EntryType.STRAIN.toString())) {
Strain strain = (Strain) entry;
entryController.setStrainPlasmids(account, strain, strain.getPlasmids());
}
entryController.update(account, entry);
} catch (PermissionException e) {
throw new ControllerException(e);
}
// update bulk upload. even if no new entry was created, entries belonging to it was updated
if (draft != null) {
try {
draft.setLastUpdateTime(new Date(System.currentTimeMillis()));
autoUpdate.setLastUpdate(draft.getLastUpdateTime());
dao.update(draft);
} catch (DAOException de) {
throw new ControllerException(de);
}
}
return autoUpdate;
}
| public BulkUploadAutoUpdate autoUpdateBulkUpload(Account account, BulkUploadAutoUpdate autoUpdate,
EntryAddType addType) throws ControllerException {
BulkUpload draft = null;
if (autoUpdate.getEditMode() != EditMode.BULK_EDIT) {
// deal with bulk upload
try {
draft = dao.retrieveById(autoUpdate.getBulkUploadId());
if (draft == null) {
// validate add type and entry type
if (addType != EntryAddType.STRAIN_WITH_PLASMID && EntryType.nameToType(
addType.name()) != autoUpdate.getType()) {
throw new ControllerException("Incompatible add type [" + addType.toString()
+ "] and auto update entry type ["
+ autoUpdate.getType().toString() + "]");
}
draft = new BulkUpload();
draft.setName("Untitled");
draft.setAccount(account);
draft.setStatus(BulkUploadStatus.IN_PROGRESS);
draft.setImportType(addType.toString());
draft.setCreationTime(new Date(System.currentTimeMillis()));
draft.setLastUpdateTime(draft.getCreationTime());
dao.save(draft);
autoUpdate.setBulkUploadId(draft.getId());
}
} catch (DAOException de) {
throw new ControllerException(de);
}
}
// for strain with plasmid this is the strain
Entry entry = entryController.get(account, autoUpdate.getEntryId());
Entry otherEntry = null; // for strain with plasmid this is the entry
// if entry is null, create entry
if (entry == null) {
entry = EntryUtil.createEntryFromType(autoUpdate.getType(), account.getFullName(), account.getEmail());
if (entry == null)
throw new ControllerException("Don't know what to do with entry type");
entry = entryController.createEntry(account, entry, null);
// creates strain/plasmid at the same time for strain with plasmid
if (addType == EntryAddType.STRAIN_WITH_PLASMID) {
if (autoUpdate.getType() == EntryType.STRAIN) {
// created strain, now create plasmid
otherEntry = new Plasmid();
otherEntry.setOwner(account.getFullName());
otherEntry.setOwnerEmail(account.getEmail());
otherEntry.setCreator(account.getFullName());
otherEntry.setCreatorEmail(account.getEmail());
otherEntry.setVisibility(Visibility.DRAFT.getValue());
entryController.createEntry(account, otherEntry, null);
// link the plasmid to strain (strain gets updated later on)
entry.getLinkedEntries().add(otherEntry);
} else {
// created plasmid, now create strain and link
otherEntry = entry;
entry = new Strain();
entry.setOwner(account.getFullName());
entry.setOwnerEmail(account.getEmail());
entry.setCreator(account.getFullName());
entry.setCreatorEmail(account.getEmail());
entry.getLinkedEntries().add(otherEntry);
entry.setVisibility(Visibility.DRAFT.getValue());
entryController.createEntry(account, entry, null);
}
}
autoUpdate.setEntryId(entry.getId());
if (draft != null) {
draft.getContents().add(entry);
}
} else {
// entry not null (fetch plasmid for strain) if this is a strain with plasmid
if (addType == EntryAddType.STRAIN_WITH_PLASMID && !entry.getLinkedEntries().isEmpty()) {
otherEntry = (Entry) entry.getLinkedEntries().toArray()[0];
}
}
try {
// now update the values (for strain with plasmid, some values are for both
for (Map.Entry<EntryField, String> set : autoUpdate.getKeyValue().entrySet()) {
String value = set.getValue();
EntryField field = set.getKey();
Entry[] ret = InfoToModelFactory.infoToEntryForField(entry, otherEntry, value, field);
entry = ret[0];
if (ret.length == 2) {
otherEntry = ret[1];
}
}
if (otherEntry != null && autoUpdate.getEditMode() != EditMode.BULK_EDIT) {
if (otherEntry.getVisibility() == null || otherEntry.getVisibility() != Visibility.DRAFT.getValue())
otherEntry.setVisibility(Visibility.DRAFT.getValue());
entryController.update(account, otherEntry);
}
if ((entry.getVisibility() == null || entry.getVisibility() != Visibility.DRAFT.getValue())
&& autoUpdate.getEditMode() != EditMode.BULK_EDIT)
entry.setVisibility(Visibility.DRAFT.getValue());
// set the plasmids and update
if (entry.getRecordType().equalsIgnoreCase(EntryType.STRAIN.toString())
&& entry.getLinkedEntries().isEmpty()) {
Strain strain = (Strain) entry;
entryController.setStrainPlasmids(account, strain, strain.getPlasmids());
}
entryController.update(account, entry);
} catch (PermissionException e) {
throw new ControllerException(e);
}
// update bulk upload. even if no new entry was created, entries belonging to it was updated
if (draft != null) {
try {
draft.setLastUpdateTime(new Date(System.currentTimeMillis()));
autoUpdate.setLastUpdate(draft.getLastUpdateTime());
dao.update(draft);
} catch (DAOException de) {
throw new ControllerException(de);
}
}
return autoUpdate;
}
|
diff --git a/core/plugins/org.eclipse.dltk.core/search/org/eclipse/dltk/core/search/indexing/core/ExternalProjectFragmentRequest.java b/core/plugins/org.eclipse.dltk.core/search/org/eclipse/dltk/core/search/indexing/core/ExternalProjectFragmentRequest.java
index d75572be4..21431d30f 100644
--- a/core/plugins/org.eclipse.dltk.core/search/org/eclipse/dltk/core/search/indexing/core/ExternalProjectFragmentRequest.java
+++ b/core/plugins/org.eclipse.dltk.core/search/org/eclipse/dltk/core/search/indexing/core/ExternalProjectFragmentRequest.java
@@ -1,164 +1,165 @@
/*******************************************************************************
* Copyright (c) 2008 xored software, Inc.
*
* 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:
* xored software, Inc. - initial API and Implementation (Alex Panchenko)
*******************************************************************************/
package org.eclipse.dltk.core.search.indexing.core;
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.dltk.core.DLTKCore;
import org.eclipse.dltk.core.IDLTKLanguageToolkit;
import org.eclipse.dltk.core.IModelElement;
import org.eclipse.dltk.core.IModelElementVisitor;
import org.eclipse.dltk.core.IProjectFragment;
import org.eclipse.dltk.core.ISourceModule;
import org.eclipse.dltk.core.ModelException;
import org.eclipse.dltk.core.environment.EnvironmentManager;
import org.eclipse.dltk.core.environment.EnvironmentPathUtils;
import org.eclipse.dltk.core.environment.IEnvironment;
import org.eclipse.dltk.core.environment.IFileHandle;
import org.eclipse.dltk.core.search.index.Index;
import org.eclipse.dltk.core.search.indexing.IProjectIndexer;
import org.eclipse.dltk.core.search.indexing.ReadWriteMonitor;
import org.eclipse.dltk.internal.core.BuiltinSourceModule;
import org.eclipse.dltk.internal.core.ExternalSourceModule;
import org.eclipse.dltk.internal.core.ModelManager;
public class ExternalProjectFragmentRequest extends IndexRequest {
protected final IProjectFragment fragment;
protected final IDLTKLanguageToolkit toolkit;
public ExternalProjectFragmentRequest(IProjectIndexer indexer,
IProjectFragment fragment, IDLTKLanguageToolkit toolkit) {
super(indexer);
this.fragment = fragment;
this.toolkit = toolkit;
}
protected String getName() {
return fragment.getElementName();
}
protected void run() throws CoreException, IOException {
IEnvironment environment = EnvironmentManager.getEnvironment(fragment
.getScriptProject());
if (environment == null || !environment.connect()) {
return;
}
final Set<ISourceModule> modules = getExternalSourceModules();
final Index index = getIndexer().getProjectFragmentIndex(fragment);
if (index == null) {
return;
}
final IPath containerPath = fragment.getPath();
Set<IFileHandle> parentFolders = new HashSet<IFileHandle>();
final List<Object> changes = checkChanges(index, modules,
containerPath, getEnvironment(), parentFolders);
if (DEBUG) {
log("changes.size=" + changes.size()); //$NON-NLS-1$
}
if (changes.isEmpty()) {
return;
}
final ReadWriteMonitor imon = index.monitor;
imon.enterWrite();
try {
for (Iterator<Object> i = changes.iterator(); !isCancelled
&& i.hasNext();) {
final Object change = i.next();
if (change instanceof String) {
index.remove((String) change);
} else if (change instanceof ISourceModule) {
ISourceModule module = (ISourceModule) change;
IFileHandle file = EnvironmentPathUtils.getFile(module,
false);
if (file != null && changes.size() > 1) {
IFileHandle parentHandle = file.getParent();
- if (parentFolders.add(parentHandle.getParent())) {
+ if (parentHandle != null
+ && parentFolders.add(parentHandle.getParent())) {
ModelManager.getModelManager().getCoreCache()
.updateFolderTimestamps(parentHandle);
}
}
getIndexer().indexSourceModule(index, toolkit, module,
containerPath);
}
}
} catch (Throwable e) {
e.printStackTrace();
} finally {
try {
index.save();
} catch (IOException e) {
DLTKCore.error("error saving index", e); //$NON-NLS-1$
} finally {
imon.exitWrite();
}
}
}
protected IEnvironment getEnvironment() {
return EnvironmentManager.getEnvironment(fragment);
}
static class ExternalModuleVisitor implements IModelElementVisitor {
final Set<ISourceModule> modules = new HashSet<ISourceModule>();
public boolean visit(IModelElement element) {
if (element.getElementType() == IModelElement.SOURCE_MODULE) {
if (element instanceof ExternalSourceModule
|| element instanceof BuiltinSourceModule) {
modules.add((ISourceModule) element);
}
return false;
}
return true;
}
}
private Set<ISourceModule> getExternalSourceModules() throws ModelException {
final ExternalModuleVisitor visitor = new ExternalModuleVisitor();
fragment.accept(visitor);
return visitor.modules;
}
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((fragment == null) ? 0 : fragment.hashCode());
return result;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
ExternalProjectFragmentRequest other = (ExternalProjectFragmentRequest) obj;
if (fragment == null) {
if (other.fragment != null)
return false;
} else if (!fragment.equals(other.fragment))
return false;
return true;
}
}
| true | true | protected void run() throws CoreException, IOException {
IEnvironment environment = EnvironmentManager.getEnvironment(fragment
.getScriptProject());
if (environment == null || !environment.connect()) {
return;
}
final Set<ISourceModule> modules = getExternalSourceModules();
final Index index = getIndexer().getProjectFragmentIndex(fragment);
if (index == null) {
return;
}
final IPath containerPath = fragment.getPath();
Set<IFileHandle> parentFolders = new HashSet<IFileHandle>();
final List<Object> changes = checkChanges(index, modules,
containerPath, getEnvironment(), parentFolders);
if (DEBUG) {
log("changes.size=" + changes.size()); //$NON-NLS-1$
}
if (changes.isEmpty()) {
return;
}
final ReadWriteMonitor imon = index.monitor;
imon.enterWrite();
try {
for (Iterator<Object> i = changes.iterator(); !isCancelled
&& i.hasNext();) {
final Object change = i.next();
if (change instanceof String) {
index.remove((String) change);
} else if (change instanceof ISourceModule) {
ISourceModule module = (ISourceModule) change;
IFileHandle file = EnvironmentPathUtils.getFile(module,
false);
if (file != null && changes.size() > 1) {
IFileHandle parentHandle = file.getParent();
if (parentFolders.add(parentHandle.getParent())) {
ModelManager.getModelManager().getCoreCache()
.updateFolderTimestamps(parentHandle);
}
}
getIndexer().indexSourceModule(index, toolkit, module,
containerPath);
}
}
} catch (Throwable e) {
e.printStackTrace();
} finally {
try {
index.save();
} catch (IOException e) {
DLTKCore.error("error saving index", e); //$NON-NLS-1$
} finally {
imon.exitWrite();
}
}
}
| protected void run() throws CoreException, IOException {
IEnvironment environment = EnvironmentManager.getEnvironment(fragment
.getScriptProject());
if (environment == null || !environment.connect()) {
return;
}
final Set<ISourceModule> modules = getExternalSourceModules();
final Index index = getIndexer().getProjectFragmentIndex(fragment);
if (index == null) {
return;
}
final IPath containerPath = fragment.getPath();
Set<IFileHandle> parentFolders = new HashSet<IFileHandle>();
final List<Object> changes = checkChanges(index, modules,
containerPath, getEnvironment(), parentFolders);
if (DEBUG) {
log("changes.size=" + changes.size()); //$NON-NLS-1$
}
if (changes.isEmpty()) {
return;
}
final ReadWriteMonitor imon = index.monitor;
imon.enterWrite();
try {
for (Iterator<Object> i = changes.iterator(); !isCancelled
&& i.hasNext();) {
final Object change = i.next();
if (change instanceof String) {
index.remove((String) change);
} else if (change instanceof ISourceModule) {
ISourceModule module = (ISourceModule) change;
IFileHandle file = EnvironmentPathUtils.getFile(module,
false);
if (file != null && changes.size() > 1) {
IFileHandle parentHandle = file.getParent();
if (parentHandle != null
&& parentFolders.add(parentHandle.getParent())) {
ModelManager.getModelManager().getCoreCache()
.updateFolderTimestamps(parentHandle);
}
}
getIndexer().indexSourceModule(index, toolkit, module,
containerPath);
}
}
} catch (Throwable e) {
e.printStackTrace();
} finally {
try {
index.save();
} catch (IOException e) {
DLTKCore.error("error saving index", e); //$NON-NLS-1$
} finally {
imon.exitWrite();
}
}
}
|
diff --git a/src/java/nl/b3p/viewer/admin/stripes/ApplicationStartMapActionBean.java b/src/java/nl/b3p/viewer/admin/stripes/ApplicationStartMapActionBean.java
index 25659bd4b..e42ed3b99 100644
--- a/src/java/nl/b3p/viewer/admin/stripes/ApplicationStartMapActionBean.java
+++ b/src/java/nl/b3p/viewer/admin/stripes/ApplicationStartMapActionBean.java
@@ -1,269 +1,271 @@
/*
* Copyright (C) 2012 B3Partners B.V.
*
* 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 nl.b3p.viewer.admin.stripes;
import java.util.*;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletResponse;
import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.validation.*;
import nl.b3p.viewer.config.app.*;
import org.json.*;
import org.stripesstuff.stripersist.Stripersist;
/**
*
* @author Jytte Schaeffer
*/
@UrlBinding("/action/applicationstartmap/{$event}")
@StrictBinding
public class ApplicationStartMapActionBean extends ApplicationActionBean {
private static final String JSP = "/WEB-INF/jsp/application/applicationStartMap.jsp";
@Validate
private String selectedlayers;
@Validate
private String checkedlayers;
@Validate
private String nodeId;
private Level rootlevel;
@DefaultHandler
@HandlesEvent("default")
@DontValidate
public Resolution view() {
if (application == null) {
getContext().getMessages().add(new SimpleError("Er moet eerst een bestaande applicatie geactiveerd of een nieuwe applicatie gemaakt worden."));
return new ForwardResolution("/WEB-INF/jsp/application/chooseApplication.jsp");
} else {
rootlevel = application.getRoot();
}
return new ForwardResolution(JSP);
}
public Resolution save() {
rootlevel = application.getRoot();
List selectedMaps = getSelectedLayers(rootlevel);
if(selectedMaps != null){
for (Iterator it = selectedMaps.iterator(); it.hasNext();) {
Object map = it.next();
if(map instanceof ApplicationLayer){
ApplicationLayer layer = (ApplicationLayer) map;
layer.setToc(false);
layer.setChecked(false);
Stripersist.getEntityManager().persist(layer);
}else if(map instanceof Level){
Level level = (Level) map;
level.setToc(false);
Stripersist.getEntityManager().persist(level);
}
}
}
- String[] checked = checkedlayers.split(",");
List<String> checkedMaps = new ArrayList();
- for(int i = 0; i < checked.length; i++){
- checkedMaps.add(checked[i]);
+ if(checkedlayers != null) {
+ String[] checked = checkedlayers.split(",");
+ for(int i = 0; i < checked.length; i++){
+ checkedMaps.add(checked[i]);
+ }
}
if(selectedlayers != null && selectedlayers.length() > 0){
String[] layers = selectedlayers.split(",");
for(int i = 0; i < layers.length; i++){
if(layers[i].startsWith("n")){
Long id = new Long(layers[i].substring(1));
Level level = Stripersist.getEntityManager().find(Level.class, id);
/*
* Levels without layers can not be saved in te start map
*/
if(level.getLayers() != null && level.getLayers().size() > 0){
level.setToc(true);
Stripersist.getEntityManager().persist(level);
}
}else if(layers[i].startsWith("s")){
Long id = new Long(layers[i].substring(1));
ApplicationLayer appLayer = Stripersist.getEntityManager().find(ApplicationLayer.class, id);
appLayer.setToc(true);
if(checkedMaps.contains(layers[i])){
appLayer.setChecked(true);
}
Stripersist.getEntityManager().persist(appLayer);
}
}
}
Stripersist.getEntityManager().getTransaction().commit();
getContext().getMessages().add(new SimpleMessage("Het startkaartbeeld is opgeslagen"));
return new ForwardResolution(JSP);
}
public Resolution loadApplicationTree() throws JSONException {
EntityManager em = Stripersist.getEntityManager();
final JSONArray children = new JSONArray();
if (!nodeId.equals("n")) {
String type = nodeId.substring(0, 1);
int id = Integer.parseInt(nodeId.substring(1));
if (type.equals("n")) {
Level l = em.find(Level.class, new Long(id));
for (Level sub : l.getChildren()) {
JSONObject j = new JSONObject();
j.put("id", "n" + sub.getId());
j.put("name", sub.getName());
j.put("type", "level");
j.put("isLeaf", sub.getChildren().isEmpty() && sub.getLayers().isEmpty());
if (sub.getParent() != null) {
j.put("parentid", sub.getParent().getId());
}
children.put(j);
}
for (ApplicationLayer layer : l.getLayers()) {
JSONObject j = new JSONObject();
j.put("id", "s" + layer.getId());
j.put("name", layer.getLayerName());
j.put("type", "layer");
j.put("isLeaf", true);
j.put("parentid", nodeId);
children.put(j);
}
}
}
return new StreamingResolution("application/json") {
@Override
public void stream(HttpServletResponse response) throws Exception {
response.getWriter().print(children.toString());
}
};
}
public Resolution loadSelectedLayers() throws JSONException {
EntityManager em = Stripersist.getEntityManager();
final JSONArray children = new JSONArray();
rootlevel = application.getRoot();
List maps = getSelectedLayers(rootlevel);
if(maps != null){
for (Iterator it = maps.iterator(); it.hasNext();) {
Object map = it.next();
if(map instanceof ApplicationLayer){
ApplicationLayer layer = (ApplicationLayer) map;
JSONObject j = new JSONObject();
j.put("id", "s" + layer.getId());
j.put("name", layer.getLayerName());
j.put("type", "layer");
j.put("isLeaf", true);
j.put("parentid", nodeId);
j.put("checked", layer.isChecked());
children.put(j);
}else if(map instanceof Level){
Level level = (Level) map;
JSONObject j = new JSONObject();
j.put("id", "n" + level.getId());
j.put("name", level.getName());
j.put("type", "category");
j.put("isLeaf", true);
j.put("parentid", nodeId);
children.put(j);
}
}
}
return new StreamingResolution("application/json") {
@Override
public void stream(HttpServletResponse response) throws Exception {
response.getWriter().print(children.toString());
}
};
}
private List getSelectedLayers(Level level) {
List children = new ArrayList();
if (level.getLayers() != null) {
List<ApplicationLayer> appLayers = level.getLayers();
for (Iterator it = appLayers.iterator(); it.hasNext();) {
ApplicationLayer layer = (ApplicationLayer) it.next();
if(layer.isToc()){
children.add(layer);
}
}
}
if(level.getChildren() != null){
List<Level> childLevels = level.getChildren();
for(Iterator it = childLevels.iterator(); it.hasNext();){
Level childLevel = (Level)it.next();
if(childLevel.isToc()){
children.add(childLevel);
}
children.addAll(getSelectedLayers(childLevel));
}
}
return children;
}
//<editor-fold defaultstate="collapsed" desc="getters & setters">
public String getSelectedlayers() {
return selectedlayers;
}
public void setSelectedlayers(String selectedlayers) {
this.selectedlayers = selectedlayers;
}
public String getCheckedlayers() {
return checkedlayers;
}
public void setCheckedlayers(String checkedlayers) {
this.checkedlayers = checkedlayers;
}
public Level getRootlevel() {
return rootlevel;
}
public void setRootlevel(Level rootlevel) {
this.rootlevel = rootlevel;
}
public String getNodeId() {
return nodeId;
}
public void setNodeId(String nodeId) {
this.nodeId = nodeId;
}
//</editor-fold>
}
| false | true | public Resolution save() {
rootlevel = application.getRoot();
List selectedMaps = getSelectedLayers(rootlevel);
if(selectedMaps != null){
for (Iterator it = selectedMaps.iterator(); it.hasNext();) {
Object map = it.next();
if(map instanceof ApplicationLayer){
ApplicationLayer layer = (ApplicationLayer) map;
layer.setToc(false);
layer.setChecked(false);
Stripersist.getEntityManager().persist(layer);
}else if(map instanceof Level){
Level level = (Level) map;
level.setToc(false);
Stripersist.getEntityManager().persist(level);
}
}
}
String[] checked = checkedlayers.split(",");
List<String> checkedMaps = new ArrayList();
for(int i = 0; i < checked.length; i++){
checkedMaps.add(checked[i]);
}
if(selectedlayers != null && selectedlayers.length() > 0){
String[] layers = selectedlayers.split(",");
for(int i = 0; i < layers.length; i++){
if(layers[i].startsWith("n")){
Long id = new Long(layers[i].substring(1));
Level level = Stripersist.getEntityManager().find(Level.class, id);
/*
* Levels without layers can not be saved in te start map
*/
if(level.getLayers() != null && level.getLayers().size() > 0){
level.setToc(true);
Stripersist.getEntityManager().persist(level);
}
}else if(layers[i].startsWith("s")){
Long id = new Long(layers[i].substring(1));
ApplicationLayer appLayer = Stripersist.getEntityManager().find(ApplicationLayer.class, id);
appLayer.setToc(true);
if(checkedMaps.contains(layers[i])){
appLayer.setChecked(true);
}
Stripersist.getEntityManager().persist(appLayer);
}
}
}
Stripersist.getEntityManager().getTransaction().commit();
getContext().getMessages().add(new SimpleMessage("Het startkaartbeeld is opgeslagen"));
return new ForwardResolution(JSP);
}
| public Resolution save() {
rootlevel = application.getRoot();
List selectedMaps = getSelectedLayers(rootlevel);
if(selectedMaps != null){
for (Iterator it = selectedMaps.iterator(); it.hasNext();) {
Object map = it.next();
if(map instanceof ApplicationLayer){
ApplicationLayer layer = (ApplicationLayer) map;
layer.setToc(false);
layer.setChecked(false);
Stripersist.getEntityManager().persist(layer);
}else if(map instanceof Level){
Level level = (Level) map;
level.setToc(false);
Stripersist.getEntityManager().persist(level);
}
}
}
List<String> checkedMaps = new ArrayList();
if(checkedlayers != null) {
String[] checked = checkedlayers.split(",");
for(int i = 0; i < checked.length; i++){
checkedMaps.add(checked[i]);
}
}
if(selectedlayers != null && selectedlayers.length() > 0){
String[] layers = selectedlayers.split(",");
for(int i = 0; i < layers.length; i++){
if(layers[i].startsWith("n")){
Long id = new Long(layers[i].substring(1));
Level level = Stripersist.getEntityManager().find(Level.class, id);
/*
* Levels without layers can not be saved in te start map
*/
if(level.getLayers() != null && level.getLayers().size() > 0){
level.setToc(true);
Stripersist.getEntityManager().persist(level);
}
}else if(layers[i].startsWith("s")){
Long id = new Long(layers[i].substring(1));
ApplicationLayer appLayer = Stripersist.getEntityManager().find(ApplicationLayer.class, id);
appLayer.setToc(true);
if(checkedMaps.contains(layers[i])){
appLayer.setChecked(true);
}
Stripersist.getEntityManager().persist(appLayer);
}
}
}
Stripersist.getEntityManager().getTransaction().commit();
getContext().getMessages().add(new SimpleMessage("Het startkaartbeeld is opgeslagen"));
return new ForwardResolution(JSP);
}
|
diff --git a/src/server/Game.java b/src/server/Game.java
index 4fe72b8..0a7d247 100644
--- a/src/server/Game.java
+++ b/src/server/Game.java
@@ -1,164 +1,167 @@
package server;
import commonlib.D2vector;
import commonlib.GameSituationSerialized;
import commonlib.Random_2Dcoord_generator;
import commonlib.gameObjects.Map;
import commonlib.gameObjects2.game_map;
import commonlib.gameObjects2.nutrient;
import commonlib.network.GameServerResponseGameOver;
import server.network.GameServer;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
*
*/
public class Game
{
//30 updates per 1000 millisecond
private final int TIME_BETWEEN_UPDATES = 1000/30;
private GameServer gameServer;
private NetworkController networkController;
private MovementController movementController;
private GameStateController gameStateController;
private Player player1;
private Player player2;
private String player1Name;
private String player2Name;
private String player1Password;
private String player2Password;
private List<nutrient> nutrients;
private game_map mygamemap;
//private Random_2Dcoord_generator rand_generator;
public Game(String player1Name, String player1Password, String player2Name, String player2Password)
{
this.player1Name = player1Name;
this.player1Password = player1Password;
this.player2Name = player2Name;
this.player2Password = player2Password;
nutrients = new ArrayList<nutrient>();
mygamemap = new game_map(Map.WIDTH, Map.HEIGHT);
generateNutrients(3);
}
public NetworkController getNetworkController()
{
return networkController;
}
void start()
{
System.out.println("Starting game server");
try
{
gameServer = new GameServer(this);
}
catch (IOException e)
{
e.printStackTrace();
}
- mygamemap = new game_map(1000,1000);
+ mygamemap = new game_map(Map.WIDTH,Map.HEIGHT);
mygamemap.initialize_map(0);
//mygamemap.generate_new_nutrient(30);
int i =0;
movementController = new MovementController();
networkController = new NetworkController(this);
gameStateController = new GameStateController();
player1 = new Player(player1Name, player1Password, 50, Map.HEIGHT/2);
player2 = new Player(player2Name, player2Password, Map.WIDTH-50, Map.HEIGHT/2);
// The game starts here, looping until a player wins
int timeout = 0;
int nutrientCounter = 0;
while (true)
{
GameSituationSerialized gameSituation = new GameSituationSerialized();
try
{
timeout++;
nutrientCounter++;
Thread.sleep(TIME_BETWEEN_UPDATES);
//mygamemap.generate_new_nutrient(1);
//mygamemap.remove_last_item();
movementController.moveSwarm(player1);
movementController.moveSwarm(player2);
gameSituation.setSwarm1(player1.getSwarm());
gameSituation.setSwarm2(player2.getSwarm());
gameStateController.calculatePowerups(player1.getSwarm(), nutrients);
gameStateController.calculatePowerups(player2.getSwarm(), nutrients);
String winner = gameStateController.calculateDamage(player1, player2);
gameSituation.setWinner(winner);
if(nutrientCounter % 100 == 0)
{
- generateNutrients(1);
+ if(nutrients.size() < 5)
+ {
+ generateNutrients(1);
+ }
}
gameSituation.setNutrients(nutrients);
gameServer.sendToAll(gameSituation);
if(winner != null)
{
gameServer.sendToAll(new GameServerResponseGameOver(winner));
break;
}
//the server times out if it is taking too long to update
if(timeout == 10000)
{
gameServer.sendToAll(new GameServerResponseGameOver("Disconnect"));
timeout = 0;
}
}
catch (InterruptedException e)
{
// Exception can be generated if signal is received by thread
// Just ignore it
// e.printStackTrace();
}
}
}
public Player verifyPlayer(String name, String password)
{
if (this.player1.getName().equals(name) && this.player1.getPassword().equals(password))
return this.player1;
else if (this.player2.getName().equals(name) && this.player2.getPassword().equals(password))
return this.player2;
else
return null;
}
public void generateNutrients(int i)
{
List<D2vector> vectors = mygamemap.generate_corarray_for_newnutrient(i);
for(D2vector vector : vectors)
{
nutrients.add(new nutrient(vector));
}
}
public void disconnectPlayer(Player player)
{
return;
}
}
| false | true | void start()
{
System.out.println("Starting game server");
try
{
gameServer = new GameServer(this);
}
catch (IOException e)
{
e.printStackTrace();
}
mygamemap = new game_map(1000,1000);
mygamemap.initialize_map(0);
//mygamemap.generate_new_nutrient(30);
int i =0;
movementController = new MovementController();
networkController = new NetworkController(this);
gameStateController = new GameStateController();
player1 = new Player(player1Name, player1Password, 50, Map.HEIGHT/2);
player2 = new Player(player2Name, player2Password, Map.WIDTH-50, Map.HEIGHT/2);
// The game starts here, looping until a player wins
int timeout = 0;
int nutrientCounter = 0;
while (true)
{
GameSituationSerialized gameSituation = new GameSituationSerialized();
try
{
timeout++;
nutrientCounter++;
Thread.sleep(TIME_BETWEEN_UPDATES);
//mygamemap.generate_new_nutrient(1);
//mygamemap.remove_last_item();
movementController.moveSwarm(player1);
movementController.moveSwarm(player2);
gameSituation.setSwarm1(player1.getSwarm());
gameSituation.setSwarm2(player2.getSwarm());
gameStateController.calculatePowerups(player1.getSwarm(), nutrients);
gameStateController.calculatePowerups(player2.getSwarm(), nutrients);
String winner = gameStateController.calculateDamage(player1, player2);
gameSituation.setWinner(winner);
if(nutrientCounter % 100 == 0)
{
generateNutrients(1);
}
gameSituation.setNutrients(nutrients);
gameServer.sendToAll(gameSituation);
if(winner != null)
{
gameServer.sendToAll(new GameServerResponseGameOver(winner));
break;
}
//the server times out if it is taking too long to update
if(timeout == 10000)
{
gameServer.sendToAll(new GameServerResponseGameOver("Disconnect"));
timeout = 0;
}
}
catch (InterruptedException e)
{
// Exception can be generated if signal is received by thread
// Just ignore it
// e.printStackTrace();
}
}
}
| void start()
{
System.out.println("Starting game server");
try
{
gameServer = new GameServer(this);
}
catch (IOException e)
{
e.printStackTrace();
}
mygamemap = new game_map(Map.WIDTH,Map.HEIGHT);
mygamemap.initialize_map(0);
//mygamemap.generate_new_nutrient(30);
int i =0;
movementController = new MovementController();
networkController = new NetworkController(this);
gameStateController = new GameStateController();
player1 = new Player(player1Name, player1Password, 50, Map.HEIGHT/2);
player2 = new Player(player2Name, player2Password, Map.WIDTH-50, Map.HEIGHT/2);
// The game starts here, looping until a player wins
int timeout = 0;
int nutrientCounter = 0;
while (true)
{
GameSituationSerialized gameSituation = new GameSituationSerialized();
try
{
timeout++;
nutrientCounter++;
Thread.sleep(TIME_BETWEEN_UPDATES);
//mygamemap.generate_new_nutrient(1);
//mygamemap.remove_last_item();
movementController.moveSwarm(player1);
movementController.moveSwarm(player2);
gameSituation.setSwarm1(player1.getSwarm());
gameSituation.setSwarm2(player2.getSwarm());
gameStateController.calculatePowerups(player1.getSwarm(), nutrients);
gameStateController.calculatePowerups(player2.getSwarm(), nutrients);
String winner = gameStateController.calculateDamage(player1, player2);
gameSituation.setWinner(winner);
if(nutrientCounter % 100 == 0)
{
if(nutrients.size() < 5)
{
generateNutrients(1);
}
}
gameSituation.setNutrients(nutrients);
gameServer.sendToAll(gameSituation);
if(winner != null)
{
gameServer.sendToAll(new GameServerResponseGameOver(winner));
break;
}
//the server times out if it is taking too long to update
if(timeout == 10000)
{
gameServer.sendToAll(new GameServerResponseGameOver("Disconnect"));
timeout = 0;
}
}
catch (InterruptedException e)
{
// Exception can be generated if signal is received by thread
// Just ignore it
// e.printStackTrace();
}
}
}
|
diff --git a/end-to-end-tests/src/test/java/fi/jumi/test/AppRunner.java b/end-to-end-tests/src/test/java/fi/jumi/test/AppRunner.java
index df5d8155..6d5ce1a6 100644
--- a/end-to-end-tests/src/test/java/fi/jumi/test/AppRunner.java
+++ b/end-to-end-tests/src/test/java/fi/jumi/test/AppRunner.java
@@ -1,287 +1,287 @@
// Copyright © 2011-2013, Esko Luontola <www.orfjackal.net>
// This software is released under the Apache License 2.0.
// The license text is at http://www.apache.org/licenses/LICENSE-2.0
package fi.jumi.test;
import fi.jumi.core.config.*;
import fi.jumi.core.network.*;
import fi.jumi.core.runs.RunId;
import fi.jumi.core.util.Strings;
import fi.jumi.launcher.*;
import fi.jumi.launcher.process.*;
import fi.jumi.launcher.ui.*;
import fi.jumi.test.util.CloseAwaitableStringWriter;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.output.*;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import java.io.*;
import java.nio.charset.*;
import java.nio.file.*;
import java.util.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertNotNull;
public class AppRunner implements TestRule {
// TODO: use a proper sandbox utility
private final Path sandboxDir = TestEnvironment.getSandboxDir().resolve(UUID.randomUUID().toString());
private final SpyProcessStarter processStarter = new SpyProcessStarter(new SystemProcessStarter());
private final CloseAwaitableStringWriter daemonOutput = new CloseAwaitableStringWriter();
private NetworkServer mockNetworkServer = null;
private Charset daemonDefaultCharset = StandardCharsets.UTF_8;
private JumiLauncher launcher;
private TextUIParser ui;
public Path workingDirectory = Paths.get(SuiteConfiguration.DEFAULTS.workingDirectory());
public final DaemonConfigurationBuilder daemon = new DaemonConfigurationBuilder();
public void setMockNetworkServer(NetworkServer mockNetworkServer) {
this.mockNetworkServer = mockNetworkServer;
}
public void setDaemonDefaultCharset(Charset daemonDefaultCharset) {
this.daemonDefaultCharset = daemonDefaultCharset;
}
public JumiLauncher getLauncher() {
if (launcher == null) {
launcher = createLauncher();
}
return launcher;
}
private JumiLauncher createLauncher() {
class CustomJumiLauncherBuilder extends JumiLauncherBuilder {
@Override
protected ProcessStarter createProcessStarter() {
return processStarter;
}
@Override
protected NetworkServer createNetworkServer() {
if (mockNetworkServer != null) {
return mockNetworkServer;
}
return super.createNetworkServer();
}
@Override
protected OutputStream createDaemonOutputListener() {
return new TeeOutputStream(
new CloseShieldOutputStream(System.out),
- new WriterOutputStream(daemonOutput, daemonDefaultCharset));
+ new WriterOutputStream(daemonOutput, daemonDefaultCharset, 1024, true));
}
}
JumiLauncherBuilder builder = new CustomJumiLauncherBuilder();
return builder.build();
}
public Process getDaemonProcess() throws Exception {
return processStarter.lastProcess.get();
}
public String getFinishedDaemonOutput() throws InterruptedException {
daemonOutput.await();
return getCurrentDaemonOutput();
}
public String getCurrentDaemonOutput() throws InterruptedException {
return daemonOutput.toString();
}
public void runTests(Class<?>... testClasses) throws Exception {
startSuite(new SuiteConfigurationBuilder()
.testClasses(toClassNames(testClasses))
.freeze());
receiveTestOutput();
}
private static String[] toClassNames(Class<?>[] classes) {
String[] names = new String[classes.length];
for (int i = 0; i < classes.length; i++) {
names[i] = classes[i].getName();
}
return names;
}
public void runTestsMatching(String syntaxAndPattern) throws Exception {
startSuite(new SuiteConfigurationBuilder()
.includedTestsPattern(syntaxAndPattern)
.freeze());
receiveTestOutput();
}
public void startSuite(SuiteConfiguration suite) throws IOException {
getLauncher().start(configure(suite), configure(daemon.freeze()));
}
private SuiteConfiguration configure(SuiteConfiguration suite) throws IOException {
SuiteConfigurationBuilder builder = suite.melt();
builder.workingDirectory(workingDirectory);
builder.addJvmOptions("-Dfile.encoding=" + daemonDefaultCharset.name());
builder.addToClassPath(TestEnvironment.getProjectJar("simpleunit"));
builder.addToClassPath(TestEnvironment.getSampleClassesDir());
builder.addToClassPath(TestEnvironment.getExtraClasspath());
if (TestSystemProperties.useThreadSafetyAgent()) {
builder.addJvmOptions("-javaagent:" + TestEnvironment.getProjectJar("thread-safety-agent"));
}
return builder.freeze();
}
private DaemonConfiguration configure(DaemonConfiguration daemon) {
return daemon.melt()
.jumiHome(sandboxDir.resolve("jumi-home"))
.logActorMessages(true)
.freeze();
}
private void receiveTestOutput() throws InterruptedException {
StringBuilder outputBuffer = new StringBuilder();
TextUI ui = new TextUI(launcher.getEventStream(), new PlainTextPrinter(outputBuffer));
ui.updateUntilFinished();
String output = outputBuffer.toString();
printTextUIOutput(output);
this.ui = new TextUIParser(output);
}
private static void printTextUIOutput(String output) {
synchronized (System.out) {
System.out.println("--- TEXT UI OUTPUT ----");
System.out.println(output);
System.out.println("--- / TEXT UI OUTPUT ----");
}
}
// assertions
public void checkPassingAndFailingTests(int expectedPassing, int expectedFailing) {
assertThat("total tests", ui.getTotalCount(), is(expectedPassing + expectedFailing));
assertThat("passing tests", ui.getPassingCount(), is(expectedPassing));
assertThat("failing tests", ui.getFailingCount(), is(expectedFailing));
}
public void checkTotalTestRuns(int expectedRunCount) {
assertThat("total test runs", ui.getRunCount(), is(expectedRunCount));
}
public void checkContainsRun(String... startAndEndEvents) {
assertNotNull("did not contain a run with the expected events", findRun(startAndEndEvents));
}
public String getRunOutput(Class<?> testClass, String testName) {
RunId runId = findRun(testClass.getSimpleName(), testName, "/", "/");
assertNotNull("run not found", runId);
return getRunOutput(runId);
}
public RunId findRun(String... startAndEndEvents) {
List<String> expectedEvents = Arrays.asList(startAndEndEvents);
for (RunId runId : ui.getRunIds()) {
List<String> actualEvents = ui.getTestStartAndEndEvents(runId);
if (actualEvents.equals(expectedEvents)) {
return runId;
}
}
return null;
}
public String getRunOutput(RunId runId) {
return ui.getRunOutput(runId);
}
public void checkHasStackTrace(String... expectedElements) {
for (RunId id : ui.getRunIds()) {
String output = ui.getRunOutput(id);
if (Strings.containsSubStrings(output, expectedElements)) {
return;
}
}
throw new AssertionError("stack trace not found");
}
// JUnit integration
@Override
public Statement apply(final Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
setup();
try {
base.evaluate();
} finally {
tearDown();
}
}
};
}
private void setup() throws IOException {
Files.createDirectories(sandboxDir);
}
private void tearDown() {
if (launcher != null) {
try {
launcher.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (processStarter.lastProcess.isDone()) {
try {
Process process = processStarter.lastProcess.get();
kill(process);
} catch (Exception e) {
e.printStackTrace();
}
}
try {
FileUtils.forceDelete(sandboxDir.toFile());
} catch (IOException e) {
System.err.println("WARNING: " + e.getMessage());
}
}
private static void kill(Process process) {
process.destroy();
try {
process.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
// helpers
public static class SpyProcessStarter implements ProcessStarter {
private final ProcessStarter processStarter;
public final FutureValue<Process> lastProcess = new FutureValue<>();
public SpyProcessStarter(ProcessStarter processStarter) {
this.processStarter = processStarter;
}
@Override
public Process startJavaProcess(JvmArgs jvmArgs) throws IOException {
Process process = processStarter.startJavaProcess(jvmArgs);
lastProcess.set(process);
return process;
}
}
}
| true | true | private JumiLauncher createLauncher() {
class CustomJumiLauncherBuilder extends JumiLauncherBuilder {
@Override
protected ProcessStarter createProcessStarter() {
return processStarter;
}
@Override
protected NetworkServer createNetworkServer() {
if (mockNetworkServer != null) {
return mockNetworkServer;
}
return super.createNetworkServer();
}
@Override
protected OutputStream createDaemonOutputListener() {
return new TeeOutputStream(
new CloseShieldOutputStream(System.out),
new WriterOutputStream(daemonOutput, daemonDefaultCharset));
}
}
JumiLauncherBuilder builder = new CustomJumiLauncherBuilder();
return builder.build();
}
| private JumiLauncher createLauncher() {
class CustomJumiLauncherBuilder extends JumiLauncherBuilder {
@Override
protected ProcessStarter createProcessStarter() {
return processStarter;
}
@Override
protected NetworkServer createNetworkServer() {
if (mockNetworkServer != null) {
return mockNetworkServer;
}
return super.createNetworkServer();
}
@Override
protected OutputStream createDaemonOutputListener() {
return new TeeOutputStream(
new CloseShieldOutputStream(System.out),
new WriterOutputStream(daemonOutput, daemonDefaultCharset, 1024, true));
}
}
JumiLauncherBuilder builder = new CustomJumiLauncherBuilder();
return builder.build();
}
|
diff --git a/src/java/org/jamwiki/utils/ImageUtil.java b/src/java/org/jamwiki/utils/ImageUtil.java
index 6ccb503b..04b5948b 100644
--- a/src/java/org/jamwiki/utils/ImageUtil.java
+++ b/src/java/org/jamwiki/utils/ImageUtil.java
@@ -1,187 +1,188 @@
/**
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, version 2.1, dated February 1999.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the latest version of the GNU Lesser General
* Public License as published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program (LICENSE.txt); if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.jamwiki.utils;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import javax.imageio.ImageIO;
import org.apache.log4j.Logger;
import org.jamwiki.Environment;
import org.jamwiki.WikiBase;
import org.jamwiki.model.WikiImage;
import org.jamwiki.model.WikiFile;
import org.springframework.util.StringUtils;
/**
*
*/
public class ImageUtil {
private static final Logger logger = Logger.getLogger(ImageUtil.class);
/**
*
*/
public static int calculateImageIncrement(int maxDimension) {
int increment = Environment.getIntValue(Environment.PROP_IMAGE_RESIZE_INCREMENT);
double result = Math.ceil((double)maxDimension / (double)increment) * increment;
return (int)result;
}
/**
* Convert a Java Image object to a Java BufferedImage object.
*/
public static BufferedImage imageToBufferedImage(Image image) throws Exception {
BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB );
Graphics2D graphics = bufferedImage.createGraphics();
graphics.drawImage(image, 0, 0, null);
graphics.dispose();
return bufferedImage;
}
/**
* Given a virtualWiki and topicName that correspond to an existing image,
* return the WikiImage object. In addition, an optional maxDimension
* parameter may be specified, in which case a resized version of the image
* may be created.
*/
public static WikiImage initializeImage(String virtualWiki, String topicName, int maxDimension) throws Exception {
WikiFile wikiFile = WikiBase.getHandler().lookupWikiFile(virtualWiki, topicName);
if (wikiFile == null) {
logger.warn("No image found for " + virtualWiki + " / " + topicName);
return null;
}
WikiImage wikiImage = new WikiImage(wikiFile);
BufferedImage imageObject = null;
if (maxDimension > 0) {
imageObject = ImageUtil.resizeImage(wikiImage, maxDimension);
setScaledDimensions(imageObject, wikiImage, maxDimension);
} else {
File imageFile = new File(Environment.getValue(Environment.PROP_FILE_DIR_FULL_PATH), wikiImage.getUrl());
imageObject = ImageUtil.loadImage(imageFile);
wikiImage.setWidth(imageObject.getWidth());
wikiImage.setHeight(imageObject.getHeight());
}
return wikiImage;
}
/**
* Given a file that corresponds to an existing image, return a
* BufferedImage object.
*/
public static BufferedImage loadImage(File file) throws Exception {
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
return ImageIO.read(fis);
} finally {
if (fis != null) {
try {
fis.close();
} catch (Exception e) {}
}
}
}
/**
* Resize an image, using a maximum dimension value. Image dimensions will
* be constrained so that the proportions are the same, but neither the width
* or height exceeds the value specified.
*/
public static BufferedImage resizeImage(WikiImage wikiImage, int maxDimension) throws Exception {
File imageFile = new File(Environment.getValue(Environment.PROP_FILE_DIR_FULL_PATH), wikiImage.getUrl());
BufferedImage original = ImageUtil.loadImage(imageFile);
maxDimension = calculateImageIncrement(maxDimension);
- if (maxDimension > original.getWidth() && maxDimension > original.getHeight()) {
+ int increment = Environment.getIntValue(Environment.PROP_IMAGE_RESIZE_INCREMENT);
+ if (increment < 0 || (maxDimension > original.getWidth() && maxDimension > original.getHeight())) {
// let the browser scale the image
return original;
}
String newUrl = wikiImage.getUrl();
int pos = newUrl.lastIndexOf(".");
if (pos > -1) {
newUrl = newUrl.substring(0, pos) + "-" + maxDimension + "px" + newUrl.substring(pos);
} else {
newUrl += "-" + maxDimension + "px";
}
wikiImage.setUrl(newUrl);
File newImageFile = new File(Environment.getValue(Environment.PROP_FILE_DIR_FULL_PATH), newUrl);
if (newImageFile.exists()) {
return ImageUtil.loadImage(newImageFile);
}
int width = -1;
int height = -1;
if (original.getWidth() >= original.getHeight()) {
width = maxDimension;
} else {
height = maxDimension;
}
Image resized = original.getScaledInstance(width, height, Image.SCALE_AREA_AVERAGING);
BufferedImage bufferedImage = null;
if (resized instanceof BufferedImage) {
bufferedImage = (BufferedImage)resized;
} else {
bufferedImage = ImageUtil.imageToBufferedImage(resized);
}
ImageUtil.saveImage(bufferedImage, newImageFile);
return bufferedImage;
}
/**
* Save an image to a specified file.
*/
public static void saveImage(BufferedImage image, File file) throws Exception {
String filename = file.getName();
int pos = filename.lastIndexOf(".");
if (pos == -1 || (pos + 1) >= filename.length()) {
throw new Exception("Unknown image type " + filename);
}
String imageType = filename.substring(pos + 1);
File imageFile = new File(file.getParent(), filename);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(imageFile);
ImageIO.write(image, imageType, fos);
} finally {
if (fos != null) {
try {
fos.close();
} catch (Exception e) {}
}
}
}
/**
*
*/
private static void setScaledDimensions(BufferedImage bufferedImage, WikiImage wikiImage, int maxDimension) {
int width = bufferedImage.getWidth();
int height = bufferedImage.getHeight();
if (width >= height) {
height = (int)Math.floor(((double)maxDimension / (double)width) * (double)height);
width = maxDimension;
} else {
width = (int)Math.floor(((double)maxDimension / (double)height) * (double)width);
height = maxDimension;
}
wikiImage.setWidth(width);
wikiImage.setHeight(height);
}
}
| true | true | public static BufferedImage resizeImage(WikiImage wikiImage, int maxDimension) throws Exception {
File imageFile = new File(Environment.getValue(Environment.PROP_FILE_DIR_FULL_PATH), wikiImage.getUrl());
BufferedImage original = ImageUtil.loadImage(imageFile);
maxDimension = calculateImageIncrement(maxDimension);
if (maxDimension > original.getWidth() && maxDimension > original.getHeight()) {
// let the browser scale the image
return original;
}
String newUrl = wikiImage.getUrl();
int pos = newUrl.lastIndexOf(".");
if (pos > -1) {
newUrl = newUrl.substring(0, pos) + "-" + maxDimension + "px" + newUrl.substring(pos);
} else {
newUrl += "-" + maxDimension + "px";
}
wikiImage.setUrl(newUrl);
File newImageFile = new File(Environment.getValue(Environment.PROP_FILE_DIR_FULL_PATH), newUrl);
if (newImageFile.exists()) {
return ImageUtil.loadImage(newImageFile);
}
int width = -1;
int height = -1;
if (original.getWidth() >= original.getHeight()) {
width = maxDimension;
} else {
height = maxDimension;
}
Image resized = original.getScaledInstance(width, height, Image.SCALE_AREA_AVERAGING);
BufferedImage bufferedImage = null;
if (resized instanceof BufferedImage) {
bufferedImage = (BufferedImage)resized;
} else {
bufferedImage = ImageUtil.imageToBufferedImage(resized);
}
ImageUtil.saveImage(bufferedImage, newImageFile);
return bufferedImage;
}
| public static BufferedImage resizeImage(WikiImage wikiImage, int maxDimension) throws Exception {
File imageFile = new File(Environment.getValue(Environment.PROP_FILE_DIR_FULL_PATH), wikiImage.getUrl());
BufferedImage original = ImageUtil.loadImage(imageFile);
maxDimension = calculateImageIncrement(maxDimension);
int increment = Environment.getIntValue(Environment.PROP_IMAGE_RESIZE_INCREMENT);
if (increment < 0 || (maxDimension > original.getWidth() && maxDimension > original.getHeight())) {
// let the browser scale the image
return original;
}
String newUrl = wikiImage.getUrl();
int pos = newUrl.lastIndexOf(".");
if (pos > -1) {
newUrl = newUrl.substring(0, pos) + "-" + maxDimension + "px" + newUrl.substring(pos);
} else {
newUrl += "-" + maxDimension + "px";
}
wikiImage.setUrl(newUrl);
File newImageFile = new File(Environment.getValue(Environment.PROP_FILE_DIR_FULL_PATH), newUrl);
if (newImageFile.exists()) {
return ImageUtil.loadImage(newImageFile);
}
int width = -1;
int height = -1;
if (original.getWidth() >= original.getHeight()) {
width = maxDimension;
} else {
height = maxDimension;
}
Image resized = original.getScaledInstance(width, height, Image.SCALE_AREA_AVERAGING);
BufferedImage bufferedImage = null;
if (resized instanceof BufferedImage) {
bufferedImage = (BufferedImage)resized;
} else {
bufferedImage = ImageUtil.imageToBufferedImage(resized);
}
ImageUtil.saveImage(bufferedImage, newImageFile);
return bufferedImage;
}
|
diff --git a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/adaptor/EclipseClassLoader.java b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/adaptor/EclipseClassLoader.java
index 9f3cc66c..830f4289 100644
--- a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/adaptor/EclipseClassLoader.java
+++ b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/adaptor/EclipseClassLoader.java
@@ -1,160 +1,163 @@
/*******************************************************************************
* Copyright (c) 2003,2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.core.runtime.adaptor;
import java.net.URL;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import org.eclipse.osgi.framework.adaptor.BundleData;
import org.eclipse.osgi.framework.adaptor.ClassLoaderDelegate;
import org.eclipse.osgi.framework.internal.core.Msg;
import org.eclipse.osgi.framework.internal.defaultadaptor.*;
import org.eclipse.osgi.framework.internal.defaultadaptor.DefaultBundleData;
import org.eclipse.osgi.framework.internal.defaultadaptor.DefaultClassLoader;
import org.eclipse.osgi.framework.stats.ClassloaderStats;
import org.eclipse.osgi.framework.stats.ResourceBundleStats;
import org.osgi.framework.*;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleException;
public class EclipseClassLoader extends DefaultClassLoader {
private static String[] NL_JAR_VARIANTS = buildNLJarVariants(System.getProperties().getProperty("osgi.nl"));
// TODO do we want to have autoActivate on all the time or just for Legacy plugins?
private boolean autoActivate = true;
public EclipseClassLoader(ClassLoaderDelegate delegate, ProtectionDomain domain, String[] classpath, BundleData bundledata) {
super(delegate, domain, classpath, (org.eclipse.osgi.framework.internal.defaultadaptor.DefaultBundleData) bundledata);
}
public Class findLocalClass(String name) throws ClassNotFoundException {
// See if we need to do autoactivation. We don't if autoActivation is turned off
// or if we have already activated this bundle.
if (EclipseAdaptor.MONITOR_CLASSES)
ClassloaderStats.startLoadingClass(getClassloaderId(), name);
boolean found = true;
try {
if (autoActivate) {
int state = hostdata.getBundle().getState();
// Assume that if we get to this point the bundle is installed, resolved, ... so
// we just need to check that it is not already started or being started. There is a
// small window where two thread race to start. One will make it first, the other will
// throw an exception. Below we catch the exception and ignore it if it is
// of this nature.
// Ensure that we do the activation outside of any synchronized blocks to avoid deadlock.
if (state != Bundle.STARTING && state != Bundle.ACTIVE)
try {
hostdata.getBundle().start();
} catch (BundleException e) {
// TODO do nothing for now but we need to filter the type of exception here and
// sort the bad from the ok. Basically, failing to start the bundle should not be damning.
// Automagic activation is currently a best effort deal.
+ //TODO: log when a log service is available
e.printStackTrace(); //Note add this to help debugging
+ if (e.getNestedException() != null)
+ e.getNestedException().printStackTrace();
}
// once we have tried, there is no need to try again.
// TODO revisit this when considering what happens when a bundle is stopped
// and then subsequently accessed. That is, should it be restarted?
autoActivate = false;
}
return super.findLocalClass(name);
} catch (ClassNotFoundException e) {
found = false;
throw e;
} finally {
if (EclipseAdaptor.MONITOR_CLASSES)
ClassloaderStats.endLoadingClass(getClassloaderId(), name, found);
}
}
/**
* Override defineClass to allow for package defining.
*/
protected Class defineClass(String name, byte[] classbytes, int off, int len, ProtectionDomain bundledomain, BundleFile bundlefile) throws ClassFormatError {
// Define the package if it is not the default package.
int lastIndex = name.lastIndexOf('.');
if (lastIndex != -1) {
String packageName = name.substring(0,lastIndex);
Package pkg = getPackage(packageName);
if (pkg == null) {
// The package is not defined yet define it before we define the class.
// TODO need to parse code manifest located in the bundlefile to find
// implementation/specification information for the package here.
definePackage(packageName,null,null,null,null,null,null,null);
}
}
return super.defineClass(name,classbytes,off,len,bundledomain,bundlefile);
}
private String getClassloaderId() {
return hostdata.getBundle().getGlobalName();
}
public URL getResouce(String name) {
URL result = super.getResource(name);
if (EclipseAdaptor.MONITOR_RESOURCE_BUNDLES) {
if (result != null && name.endsWith(".properties")) { //$NON-NLS-1$
ClassloaderStats.loadedBundle(getClassloaderId(), new ResourceBundleStats(getClassloaderId(), name, result));
}
}
return result;
}
protected void findClassPathEntry(ArrayList result, String entry, DefaultBundleData bundledata, ProtectionDomain domain) {
String var = hasPrefix(entry);
if (var == null) {
super.findClassPathEntry(result, entry, bundledata, domain);
return;
}
if (var.equals("ws")) { //$NON-NLS-1$
super.findClassPathEntry(result, "ws/" + System.getProperties().getProperty("osgi.ws") + "/" + entry.substring(4), bundledata, domain); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
return;
}
if (var.equals("os")) { //$NON-NLS-1$
super.findClassPathEntry(result, "os/" + System.getProperties().getProperty("osgi.os") + "/" + entry.substring(4), bundledata, domain); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
return;
}
if (var.equals("nl")) { //$NON-NLS-1$
entry = entry.substring(4);
for (int i = 0; i < NL_JAR_VARIANTS.length; i++) {
if (addClassPathEntry(result, "nl/" + NL_JAR_VARIANTS[i] + "/" + entry, bundledata, domain)) //$NON-NLS-1$ //$NON-NLS-2$
return;
}
BundleException be = new BundleException(Msg.formatter.getString("BUNDLE_CLASSPATH_ENTRY_NOT_FOUND_EXCEPTION", entry)); //$NON-NLS-1$
bundledata.getAdaptor().getEventPublisher().publishFrameworkEvent(FrameworkEvent.ERROR,bundledata.getBundle(),be);
}
}
private static String[] buildNLJarVariants(String nl) {
ArrayList result = new ArrayList();
nl = nl.replace('_', '/');
while (nl.length() > 0) {
result.add("nl/" + nl + "/"); //$NON-NLS-1$ //$NON-NLS-2$
int i = nl.lastIndexOf('/'); //$NON-NLS-1$
nl = (i < 0) ? "" : nl.substring(0, i); //$NON-NLS-1$
}
result.add(""); //$NON-NLS-1$
return (String[])result.toArray(new String[result.size()]);
}
//return a String representing the string found between the $s
private String hasPrefix(String libPath) {
if (libPath.startsWith("$ws$")) //$NON-NLS-1$
return "ws"; //$NON-NLS-1$
if (libPath.startsWith("$os$")) //$NON-NLS-1$
return "os"; //$NON-NLS-1$
if (libPath.startsWith("$nl$")) //$NON-NLS-1$
return "nl"; //$NON-NLS-1$
return null;
}
}
| false | true | public Class findLocalClass(String name) throws ClassNotFoundException {
// See if we need to do autoactivation. We don't if autoActivation is turned off
// or if we have already activated this bundle.
if (EclipseAdaptor.MONITOR_CLASSES)
ClassloaderStats.startLoadingClass(getClassloaderId(), name);
boolean found = true;
try {
if (autoActivate) {
int state = hostdata.getBundle().getState();
// Assume that if we get to this point the bundle is installed, resolved, ... so
// we just need to check that it is not already started or being started. There is a
// small window where two thread race to start. One will make it first, the other will
// throw an exception. Below we catch the exception and ignore it if it is
// of this nature.
// Ensure that we do the activation outside of any synchronized blocks to avoid deadlock.
if (state != Bundle.STARTING && state != Bundle.ACTIVE)
try {
hostdata.getBundle().start();
} catch (BundleException e) {
// TODO do nothing for now but we need to filter the type of exception here and
// sort the bad from the ok. Basically, failing to start the bundle should not be damning.
// Automagic activation is currently a best effort deal.
e.printStackTrace(); //Note add this to help debugging
}
// once we have tried, there is no need to try again.
// TODO revisit this when considering what happens when a bundle is stopped
// and then subsequently accessed. That is, should it be restarted?
autoActivate = false;
}
return super.findLocalClass(name);
} catch (ClassNotFoundException e) {
found = false;
throw e;
} finally {
if (EclipseAdaptor.MONITOR_CLASSES)
ClassloaderStats.endLoadingClass(getClassloaderId(), name, found);
}
}
| public Class findLocalClass(String name) throws ClassNotFoundException {
// See if we need to do autoactivation. We don't if autoActivation is turned off
// or if we have already activated this bundle.
if (EclipseAdaptor.MONITOR_CLASSES)
ClassloaderStats.startLoadingClass(getClassloaderId(), name);
boolean found = true;
try {
if (autoActivate) {
int state = hostdata.getBundle().getState();
// Assume that if we get to this point the bundle is installed, resolved, ... so
// we just need to check that it is not already started or being started. There is a
// small window where two thread race to start. One will make it first, the other will
// throw an exception. Below we catch the exception and ignore it if it is
// of this nature.
// Ensure that we do the activation outside of any synchronized blocks to avoid deadlock.
if (state != Bundle.STARTING && state != Bundle.ACTIVE)
try {
hostdata.getBundle().start();
} catch (BundleException e) {
// TODO do nothing for now but we need to filter the type of exception here and
// sort the bad from the ok. Basically, failing to start the bundle should not be damning.
// Automagic activation is currently a best effort deal.
//TODO: log when a log service is available
e.printStackTrace(); //Note add this to help debugging
if (e.getNestedException() != null)
e.getNestedException().printStackTrace();
}
// once we have tried, there is no need to try again.
// TODO revisit this when considering what happens when a bundle is stopped
// and then subsequently accessed. That is, should it be restarted?
autoActivate = false;
}
return super.findLocalClass(name);
} catch (ClassNotFoundException e) {
found = false;
throw e;
} finally {
if (EclipseAdaptor.MONITOR_CLASSES)
ClassloaderStats.endLoadingClass(getClassloaderId(), name, found);
}
}
|
diff --git a/rpmstubby/org.eclipse.linuxtools.packaging.rpmstubby/src/org/eclipse/linuxtools/rpmstubby/StubbyGenerator.java b/rpmstubby/org.eclipse.linuxtools.packaging.rpmstubby/src/org/eclipse/linuxtools/rpmstubby/StubbyGenerator.java
index 069cf8020..12a7aeba3 100644
--- a/rpmstubby/org.eclipse.linuxtools.packaging.rpmstubby/src/org/eclipse/linuxtools/rpmstubby/StubbyGenerator.java
+++ b/rpmstubby/org.eclipse.linuxtools.packaging.rpmstubby/src/org/eclipse/linuxtools/rpmstubby/StubbyGenerator.java
@@ -1,318 +1,318 @@
/*******************************************************************************
* Copyright (c) 2007 Alphonse Van Assche.
* 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:
* Alphonse Van Assche - initial API and implementation
*******************************************************************************/
package org.eclipse.linuxtools.rpmstubby;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
import java.util.List;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.linuxtools.rpmstubby.model.MainPackage;
import org.eclipse.linuxtools.rpmstubby.model.PackageItem;
import org.eclipse.linuxtools.rpmstubby.model.SubPackage;
import org.eclipse.linuxtools.rpmstubby.preferences.PreferenceConstants;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;
public class StubbyGenerator {
private MainPackage mainPackage;
private List<SubPackage> subPackages;
private boolean withGCJSupport;
private boolean withFetchScript;
private boolean usePdebuildScript;
private IPreferenceStore store;
public StubbyGenerator(MainPackage mainPackage, List<SubPackage> subPackages) {
this.mainPackage = mainPackage;
this.subPackages = subPackages;
store = StubbyPlugin.getDefault().getPreferenceStore();
this.withGCJSupport = store.getBoolean(PreferenceConstants.P_STUBBY_WITH_GCJ);
this.withFetchScript = store.getBoolean(PreferenceConstants.P_STUBBY_WITH_FETCH_SCRIPT);
this.usePdebuildScript = store.getBoolean(PreferenceConstants.P_STUBBY_USE_PDEBUILD_SCRIPT);
}
public String generateSpecfile() {
StringBuffer buffer = new StringBuffer();
String simplePackageName = getPackageName(mainPackage.getName());
String packageName = "eclipse-" + simplePackageName;
if (withGCJSupport)
buffer.append("%define gcj_support 1\n");
if (withFetchScript)
buffer.append("%define src_repo_tag FIXME\n");
buffer.append("%define eclipse_base %{_libdir}/eclipse\n");
buffer.append("%define install_loc %{_datadir}/eclipse/dropins/"+simplePackageName+"\n\n");
buffer.append("Name: " + packageName + "\n");
buffer.append("Version: " + mainPackage.getVersion().replaceAll("\\.qualifier","") + "\n");
buffer.append("Release: 1%{?dist}" + "\n");
buffer.append("Summary: " + mainPackage.getSummary() + "\n\n");
buffer.append("Group: Development/Tools\n");
buffer.append("License: " + mainPackage.getLicense()+ "\n");
buffer.append("URL: " + mainPackage.getURL() + "\n");
if (withFetchScript) {
buffer.append("Source0: %{name}-fetched-src-%{src_repo_tag}.tar.bz2\n");
buffer.append("Source1: "+ packageName +"-fetch-src.sh\n");
} else {
buffer.append("Source0: FIXME\n");
}
buffer.append("BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-root-%(%{__id_u} -n)\n\n");
if (withGCJSupport) {
buffer.append("%if %{gcj_support}\n");
buffer.append("BuildRequires: gcc-java\n");
buffer.append("BuildRequires: java-gcj-compat-devel\n");
buffer.append("Requires(post): java-gcj-compat\n");
buffer.append("Requires(postun): java-gcj-compat\n");
buffer.append("%else\n");
buffer.append("BuildRequires: java-devel >= 1.5.0\n");
buffer.append("%endif\n");
buffer.append("%if ! %{gcj_support}\n");
buffer.append("BuildArch: noarch\n");
buffer.append("%endif\n\n");
} else
buffer.append("BuildArch: noarch\n\n");
- buffer.append("BuildRequires: eclipse-pde >= 1:3.3.0\n");
- buffer.append("Requires: eclipse-platform >= 3.3.1\n");
+ buffer.append("BuildRequires: eclipse-pde >= 1:3.4.0\n");
+ buffer.append("Requires: eclipse-platform >= 3.4.0\n");
buffer.append(getDepsOrReqs("Requires: ", mainPackage.getRequires()));
buffer.append("\n%description\n" + mainPackage.getDescription() + "\n");
for (SubPackage subPackage: subPackages) {
String subPackageName = getPackageName(subPackage.getName());
buffer.append("\n%package " + subPackageName + "\n");
buffer.append("Summary: "+ subPackage.getSummary() +"\n");
buffer.append("Requires: %{name} = %{version}-%{release}\n");
buffer.append(getDepsOrReqs("Requires: ", subPackage.getRequires()));
buffer.append(getDepsOrReqs("Provides: ", subPackage.getProvides()));
buffer.append("Group: Development/Tools\n\n");
buffer.append("%description " + subPackageName + "\n");
buffer.append(subPackage.getDescription() + "\n");
}
generatePrepSection(buffer);
generateBuildSection(buffer);
buffer.append("%install\n");
buffer.append("%{__rm} -rf %{buildroot}\n");
buffer.append("install -d -m 755 $RPM_BUILD_ROOT%{install_loc}\n\n");
buffer.append("%{__unzip} -q -d $RPM_BUILD_ROOT%{install_loc} \\\n");
buffer.append(" build/rpmBuild/" + mainPackage.getName() + ".zip \n\n");
if (withGCJSupport) {
buffer.append("%if %{gcj_support}\n");
buffer.append(" %{_bindir}/aot-compile-rpm\n");
buffer.append("%endif\n\n");
}
buffer.append("%clean\n");
buffer.append("%{__rm} -rf %{buildroot}\n\n");
if (withGCJSupport) {
buffer.append("%if %{gcj_support}\n");
buffer.append("%post\n");
buffer.append("if [ -x %{_bindir}/rebuild-gcj-db ]; then\n");
buffer.append(" %{_bindir}/rebuild-gcj-db\n");
buffer.append("fi\n\n");
buffer.append("%preun\n");
buffer.append("if [ -x %{_bindir}/rebuild-gcj-db ]; then\n");
buffer.append(" %{_bindir}/rebuild-gcj-db\n");
buffer.append("fi\n");
buffer.append("%endif\n\n");
}
buffer.append("%files\n");
buffer.append("%defattr(-,root,root,-)\n");
buffer.append("%{install_loc}\n\n");
for (SubPackage subPackage: subPackages) {
buffer.append("%files " + getPackageName(subPackage.getName()) + "\n");
buffer.append("%dir %{eclipse_base}/features/" + subPackage.getName() + "_*/\n");
buffer.append("%doc %{eclipse_base}/features/" + subPackage.getName() + "_*/*.html\n");
buffer.append("%{eclipse_base}/features/" + subPackage.getName() + "_*/feature.*\n");
buffer.append(getPackageFiles(subPackage.getProvides(), withGCJSupport) + "\n");
}
buffer.append("%changelog\n\n");
buffer.append("FIXME\n");
return buffer.toString();
}
private void generatePrepSection(StringBuffer buffer) {
buffer.append("\n%prep\n%setup -q -n FIXME\n\n");
if (!usePdebuildScript) {
buffer
.append("/bin/sh -x %{eclipse_base}/buildscripts/copy-platform SDK %{eclipse_base}\n");
buffer.append("mkdir home\n\n");
}
}
private void generateBuildSection(StringBuffer buffer) {
buffer.append("%build\n");
if (!usePdebuildScript) {
buffer.append("SDK=$(cd SDK > /dev/null && pwd)\n");
buffer.append("homedir=$(cd home > /dev/null && pwd)\n");
buffer.append("java -cp $SDK/startup.jar \\\n");
buffer
.append(" -Dosgi.sharedConfiguration.area=%{_libdir}/eclipse/configuration \\\n");
buffer.append(" org.eclipse.core.launcher.Main \\\n");
buffer
.append(" -application org.eclipse.ant.core.antRunner \\\n");
buffer.append(" -Dtype=feature \\\n");
buffer.append(" -Did=" + mainPackage.getName() + "\\\n");
buffer.append(" -DbaseLocation=$SDK \\\n");
buffer.append(" -DsourceDirectory=$(pwd) \\\n");
buffer.append(" -DbuildDirectory=$(pwd)/build \\\n");
buffer
.append(" -Dbuilder=%{eclipse_base}/plugins/org.eclipse.pde.build/templates/package-build \\\n");
buffer
.append(" -f %{eclipse_base}/plugins/org.eclipse.pde.build/scripts/build.xml \\\n");
buffer.append(" -vmargs -Duser.home=$homedir");
} else {
buffer.append("%{eclipse_base}/buildscripts/pdebuild -f ").append(mainPackage.getName());
}
buffer.append("\n\n");
}
public String generateFetchScript() {
StringBuffer buffer = new StringBuffer();
buffer.append("#!/bin/sh\n");
buffer.append("usage='usage: $0 <tag>'\n");
buffer.append("name=eclipse-" + getPackageName(mainPackage.getName()) + "\n");
buffer.append("tag=$1\n");
buffer.append("tar_name=$name-fetched-src-$tag\n\n");
buffer.append("# example of fetch command:\n");
buffer.append("# fetch_cmd=cvs -d:pserver:[email protected]:/cvsroot/dsdp \\\n");
buffer.append("# export -r $tag org.eclipse.tm.rse/features/$f;\n\n");
buffer.append("fetch_cmd=FIXME\n\n");
buffer.append("if [ 'x$tag'x = 'xx' ]; then\n");
buffer.append(" echo >&2 '$usage'\n");
buffer.append(" exit 1\n");
buffer.append("fi\n\n");
buffer.append("rm -fr $tar_name && mkdir $tar_name\n");
buffer.append("pushd $tar_name\n\n");
buffer.append("# Fetch plugins\n");
buffer.append("for f in \\\n");
buffer.append(getProvidesBundlesString(mainPackage.getProvides()));
HashSet<String> uniqueProvides = new HashSet<String>();
for (SubPackage subPackage: subPackages) {
uniqueProvides = getProvidesBundles(subPackage.getProvides(), uniqueProvides);
}
buffer.append(getProvidesBundlesString(uniqueProvides));
buffer.append("; do\n");
buffer.append("$fetch_cmd\n");
buffer.append("done\n\n");
buffer.append("popd\n");
buffer.append("# create archive\n");
buffer.append("tar -cjf $tar_name.tar.bz2 $tar_name\n");
return buffer.toString();
}
public String getPackageName(String packageName) {
String[] packageItems = packageName.split("\\.");
String name = packageItems[packageItems.length - 1];
if (name.equalsIgnoreCase("feature")){
name = packageItems[packageItems.length - 2];
}
return name;
}
public void writeContent(String projectName, String fileName, String contents) throws CoreException {
InputStream contentInputStream = new ByteArrayInputStream(contents.getBytes());
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IResource resource = root.findMember(new Path(projectName));
if (!resource.exists() || !(resource instanceof IContainer)) {
throwCoreException("Project \"" + projectName
+ "\" does not exist.");
}
IContainer container = (IContainer) resource;
final IFile file = container.getFile(new Path(fileName));
try {
InputStream stream = contentInputStream;
if (file.exists()) {
file.setContents(stream, true, true, null);
} else {
file.create(stream, true, null);
}
stream.close();
} catch (IOException e) {
StubbyLog.logError(e);
}
StubbyPlugin.getActiveWorkbenchShell().getDisplay().asyncExec(new Runnable() {
public void run() {
IWorkbenchPage page = PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getActivePage();
try {
IDE.openEditor(page, file, true);
} catch (PartInitException e) {
StubbyLog.logError(e);
}
}
});
}
private void throwCoreException(String message) throws CoreException {
IStatus status = new Status(IStatus.ERROR,
"org.eclipse.linuxtools.rpm.ui.editor", IStatus.OK, message,
null);
throw new CoreException(status);
}
private String getDepsOrReqs(String preString, List<PackageItem> packageItems) {
String toRet = "";
for (PackageItem packageItem: packageItems) {
toRet += preString + packageItem.getName() + " "
+ packageItem.getOperator() + " "
+ packageItem.getVersion() + "\n";
}
return toRet;
}
private String getProvidesBundlesString(List<PackageItem> packageItems) {
String toRet = "";
for (PackageItem packageItem: packageItems) {
toRet += packageItem.getName() + "\n";
}
return toRet;
}
private String getProvidesBundlesString(HashSet<String> uniqueProvides) {
String toRet = "";
for (String provideName: uniqueProvides) {
toRet += provideName + "\n";
}
return toRet;
}
private HashSet<String> getProvidesBundles(List<PackageItem> packageItems, HashSet<String> uniqueProvides) {
for (PackageItem packageItem : packageItems) {
uniqueProvides.add(packageItem.getName());
}
return uniqueProvides;
}
private String getPackageFiles(List<PackageItem> packageItems, boolean withGCJSupport) {
String toRet = "";
for (PackageItem packageItem: packageItems) {
toRet += "%{eclipse_base}/plugins/" + packageItem.getName() + "_*.jar\n";
}
if (withGCJSupport) {
toRet += "%if %{gcj_support}\n";
for (PackageItem packageItem: packageItems) {
toRet += "%{_libdir}/gcj/%{name}/" + packageItem.getName() + "_*\n";
}
toRet += "%endif\n";
}
return toRet;
}
}
| true | true | public String generateSpecfile() {
StringBuffer buffer = new StringBuffer();
String simplePackageName = getPackageName(mainPackage.getName());
String packageName = "eclipse-" + simplePackageName;
if (withGCJSupport)
buffer.append("%define gcj_support 1\n");
if (withFetchScript)
buffer.append("%define src_repo_tag FIXME\n");
buffer.append("%define eclipse_base %{_libdir}/eclipse\n");
buffer.append("%define install_loc %{_datadir}/eclipse/dropins/"+simplePackageName+"\n\n");
buffer.append("Name: " + packageName + "\n");
buffer.append("Version: " + mainPackage.getVersion().replaceAll("\\.qualifier","") + "\n");
buffer.append("Release: 1%{?dist}" + "\n");
buffer.append("Summary: " + mainPackage.getSummary() + "\n\n");
buffer.append("Group: Development/Tools\n");
buffer.append("License: " + mainPackage.getLicense()+ "\n");
buffer.append("URL: " + mainPackage.getURL() + "\n");
if (withFetchScript) {
buffer.append("Source0: %{name}-fetched-src-%{src_repo_tag}.tar.bz2\n");
buffer.append("Source1: "+ packageName +"-fetch-src.sh\n");
} else {
buffer.append("Source0: FIXME\n");
}
buffer.append("BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-root-%(%{__id_u} -n)\n\n");
if (withGCJSupport) {
buffer.append("%if %{gcj_support}\n");
buffer.append("BuildRequires: gcc-java\n");
buffer.append("BuildRequires: java-gcj-compat-devel\n");
buffer.append("Requires(post): java-gcj-compat\n");
buffer.append("Requires(postun): java-gcj-compat\n");
buffer.append("%else\n");
buffer.append("BuildRequires: java-devel >= 1.5.0\n");
buffer.append("%endif\n");
buffer.append("%if ! %{gcj_support}\n");
buffer.append("BuildArch: noarch\n");
buffer.append("%endif\n\n");
} else
buffer.append("BuildArch: noarch\n\n");
buffer.append("BuildRequires: eclipse-pde >= 1:3.3.0\n");
buffer.append("Requires: eclipse-platform >= 3.3.1\n");
buffer.append(getDepsOrReqs("Requires: ", mainPackage.getRequires()));
buffer.append("\n%description\n" + mainPackage.getDescription() + "\n");
for (SubPackage subPackage: subPackages) {
String subPackageName = getPackageName(subPackage.getName());
buffer.append("\n%package " + subPackageName + "\n");
buffer.append("Summary: "+ subPackage.getSummary() +"\n");
buffer.append("Requires: %{name} = %{version}-%{release}\n");
buffer.append(getDepsOrReqs("Requires: ", subPackage.getRequires()));
buffer.append(getDepsOrReqs("Provides: ", subPackage.getProvides()));
buffer.append("Group: Development/Tools\n\n");
buffer.append("%description " + subPackageName + "\n");
buffer.append(subPackage.getDescription() + "\n");
}
generatePrepSection(buffer);
generateBuildSection(buffer);
buffer.append("%install\n");
buffer.append("%{__rm} -rf %{buildroot}\n");
buffer.append("install -d -m 755 $RPM_BUILD_ROOT%{install_loc}\n\n");
buffer.append("%{__unzip} -q -d $RPM_BUILD_ROOT%{install_loc} \\\n");
buffer.append(" build/rpmBuild/" + mainPackage.getName() + ".zip \n\n");
if (withGCJSupport) {
buffer.append("%if %{gcj_support}\n");
buffer.append(" %{_bindir}/aot-compile-rpm\n");
buffer.append("%endif\n\n");
}
buffer.append("%clean\n");
buffer.append("%{__rm} -rf %{buildroot}\n\n");
if (withGCJSupport) {
buffer.append("%if %{gcj_support}\n");
buffer.append("%post\n");
buffer.append("if [ -x %{_bindir}/rebuild-gcj-db ]; then\n");
buffer.append(" %{_bindir}/rebuild-gcj-db\n");
buffer.append("fi\n\n");
buffer.append("%preun\n");
buffer.append("if [ -x %{_bindir}/rebuild-gcj-db ]; then\n");
buffer.append(" %{_bindir}/rebuild-gcj-db\n");
buffer.append("fi\n");
buffer.append("%endif\n\n");
}
buffer.append("%files\n");
buffer.append("%defattr(-,root,root,-)\n");
buffer.append("%{install_loc}\n\n");
for (SubPackage subPackage: subPackages) {
buffer.append("%files " + getPackageName(subPackage.getName()) + "\n");
buffer.append("%dir %{eclipse_base}/features/" + subPackage.getName() + "_*/\n");
buffer.append("%doc %{eclipse_base}/features/" + subPackage.getName() + "_*/*.html\n");
buffer.append("%{eclipse_base}/features/" + subPackage.getName() + "_*/feature.*\n");
buffer.append(getPackageFiles(subPackage.getProvides(), withGCJSupport) + "\n");
}
buffer.append("%changelog\n\n");
buffer.append("FIXME\n");
return buffer.toString();
}
| public String generateSpecfile() {
StringBuffer buffer = new StringBuffer();
String simplePackageName = getPackageName(mainPackage.getName());
String packageName = "eclipse-" + simplePackageName;
if (withGCJSupport)
buffer.append("%define gcj_support 1\n");
if (withFetchScript)
buffer.append("%define src_repo_tag FIXME\n");
buffer.append("%define eclipse_base %{_libdir}/eclipse\n");
buffer.append("%define install_loc %{_datadir}/eclipse/dropins/"+simplePackageName+"\n\n");
buffer.append("Name: " + packageName + "\n");
buffer.append("Version: " + mainPackage.getVersion().replaceAll("\\.qualifier","") + "\n");
buffer.append("Release: 1%{?dist}" + "\n");
buffer.append("Summary: " + mainPackage.getSummary() + "\n\n");
buffer.append("Group: Development/Tools\n");
buffer.append("License: " + mainPackage.getLicense()+ "\n");
buffer.append("URL: " + mainPackage.getURL() + "\n");
if (withFetchScript) {
buffer.append("Source0: %{name}-fetched-src-%{src_repo_tag}.tar.bz2\n");
buffer.append("Source1: "+ packageName +"-fetch-src.sh\n");
} else {
buffer.append("Source0: FIXME\n");
}
buffer.append("BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-root-%(%{__id_u} -n)\n\n");
if (withGCJSupport) {
buffer.append("%if %{gcj_support}\n");
buffer.append("BuildRequires: gcc-java\n");
buffer.append("BuildRequires: java-gcj-compat-devel\n");
buffer.append("Requires(post): java-gcj-compat\n");
buffer.append("Requires(postun): java-gcj-compat\n");
buffer.append("%else\n");
buffer.append("BuildRequires: java-devel >= 1.5.0\n");
buffer.append("%endif\n");
buffer.append("%if ! %{gcj_support}\n");
buffer.append("BuildArch: noarch\n");
buffer.append("%endif\n\n");
} else
buffer.append("BuildArch: noarch\n\n");
buffer.append("BuildRequires: eclipse-pde >= 1:3.4.0\n");
buffer.append("Requires: eclipse-platform >= 3.4.0\n");
buffer.append(getDepsOrReqs("Requires: ", mainPackage.getRequires()));
buffer.append("\n%description\n" + mainPackage.getDescription() + "\n");
for (SubPackage subPackage: subPackages) {
String subPackageName = getPackageName(subPackage.getName());
buffer.append("\n%package " + subPackageName + "\n");
buffer.append("Summary: "+ subPackage.getSummary() +"\n");
buffer.append("Requires: %{name} = %{version}-%{release}\n");
buffer.append(getDepsOrReqs("Requires: ", subPackage.getRequires()));
buffer.append(getDepsOrReqs("Provides: ", subPackage.getProvides()));
buffer.append("Group: Development/Tools\n\n");
buffer.append("%description " + subPackageName + "\n");
buffer.append(subPackage.getDescription() + "\n");
}
generatePrepSection(buffer);
generateBuildSection(buffer);
buffer.append("%install\n");
buffer.append("%{__rm} -rf %{buildroot}\n");
buffer.append("install -d -m 755 $RPM_BUILD_ROOT%{install_loc}\n\n");
buffer.append("%{__unzip} -q -d $RPM_BUILD_ROOT%{install_loc} \\\n");
buffer.append(" build/rpmBuild/" + mainPackage.getName() + ".zip \n\n");
if (withGCJSupport) {
buffer.append("%if %{gcj_support}\n");
buffer.append(" %{_bindir}/aot-compile-rpm\n");
buffer.append("%endif\n\n");
}
buffer.append("%clean\n");
buffer.append("%{__rm} -rf %{buildroot}\n\n");
if (withGCJSupport) {
buffer.append("%if %{gcj_support}\n");
buffer.append("%post\n");
buffer.append("if [ -x %{_bindir}/rebuild-gcj-db ]; then\n");
buffer.append(" %{_bindir}/rebuild-gcj-db\n");
buffer.append("fi\n\n");
buffer.append("%preun\n");
buffer.append("if [ -x %{_bindir}/rebuild-gcj-db ]; then\n");
buffer.append(" %{_bindir}/rebuild-gcj-db\n");
buffer.append("fi\n");
buffer.append("%endif\n\n");
}
buffer.append("%files\n");
buffer.append("%defattr(-,root,root,-)\n");
buffer.append("%{install_loc}\n\n");
for (SubPackage subPackage: subPackages) {
buffer.append("%files " + getPackageName(subPackage.getName()) + "\n");
buffer.append("%dir %{eclipse_base}/features/" + subPackage.getName() + "_*/\n");
buffer.append("%doc %{eclipse_base}/features/" + subPackage.getName() + "_*/*.html\n");
buffer.append("%{eclipse_base}/features/" + subPackage.getName() + "_*/feature.*\n");
buffer.append(getPackageFiles(subPackage.getProvides(), withGCJSupport) + "\n");
}
buffer.append("%changelog\n\n");
buffer.append("FIXME\n");
return buffer.toString();
}
|
diff --git a/Pineapple/src/com/example/pineapple/Protagonist.java b/Pineapple/src/com/example/pineapple/Protagonist.java
index a83f057..59f80b2 100644
--- a/Pineapple/src/com/example/pineapple/Protagonist.java
+++ b/Pineapple/src/com/example/pineapple/Protagonist.java
@@ -1,243 +1,244 @@
package com.example.pineapple;
import java.util.*;
import android.util.Log;
public class Protagonist {
private static final String TAG = Protagonist.class.getSimpleName();
private double xPos;
private double yPos;
private double xVel;
private double yVel;
private double xAcc;
private double yAcc;
private int health;
private int angleAim;
private double jumpVel = -6;
private double jumpAcc = 0.4;
private double maxSpeed = 3;
private double slideCoefficient = 0.8;
private final int height = 20;
private final int width = (int)(20/1.42); //Change 1.42 to ratio of bitmap
private boolean touchingGround;
private GamePanel gp;
// CONSTRUCTOR
public Protagonist(double i, double j, GamePanel gp) {
this.setXPos(i);
this.setYPos(j);
this.health = 100;
this.gp = gp;
}
// GET AND SET METHODS
// getmethods for pos, vel, acc
public double getXPos() {
return xPos;
}
public double getYPos() {
return yPos;
}
public double getXVel() {
return xVel;
}
public double getYVel() {
return yVel;
}
public double getXAcc() {
return xAcc;
}
public double getYAcc() {
return yAcc;
}
//setmethods for pos, vel, acc
public void setXPos(double n) {
xPos = n;
}
public void setYPos(double n) {
yPos = n;
}
public void setXVel(double n) {
xVel = n;
}
public void setYVel(double n) {
yVel = n;
}
public void setXAcc(double n) {
xAcc = n;
}
public void setYAcc(double n) {
yAcc = n;
}
// get and setmethods for actionproperties
public void setAim(int angle) {
angleAim = angle;
}
public double getAim() {
return angleAim;
}
public int getHealth() {
return health;
}
public void setHealth(int health) {
this.health = health;
}
private double getJumpVel() {
return jumpVel;
}
private void setJumpVel(double jumpVel) {
this.jumpVel = jumpVel;
}
private double getJumpAcc() {
return jumpAcc;
}
private void setJumpAcc(double jumpAcc) {
this.jumpAcc = jumpAcc;
}
private double getMaxSpeed() {
return maxSpeed;
}
private void setMaxSpeed(double maxSpeed) {
this.maxSpeed = maxSpeed;
}
private double getSlideCoefficient() {
return slideCoefficient;
}
private void setSlideCoefficient(double slideCoefficient) {
this.slideCoefficient = slideCoefficient;
}
public int getHeight() {
return height;
}
public int getWidth() {
return width;
}
public boolean isTouchingGround() {
return touchingGround;
}
public void setTouchingGround(boolean touchingGround) {
this.touchingGround = touchingGround;
}
// ACTIONS
//Protagonist is aiming
public void aim(int angle) {
this.angleAim = (int)angle;
}
//Protagonist lose health
public int reduceHealth(int n) {
this.setHealth(n-1);
return health;
}
//Protagonist jump
public void jump() {
touchingGround = false;
this.setYVel(this.getYVel() + this.getJumpVel() + this.getJumpAcc());
Log.d(TAG, "Jump!!");
}
// ------------- KEEPING FEET ON THE GROUND (just for now)--------------- //
//Protagonist down
public void down(Ground g) {
this.setYPos(g.getYFromX(this.getXPos()));
this.setYVel(0);
this.setYAcc(0);
Log.d(TAG, "Come down!!");
}
// ---------------------------------------------------------------------- //
//Accelerating protagonist
public void accelerate(double acc) { // acc = 0.2?
this.setXVel(this.getXVel() + acc);
if(Math.abs(this.getXVel()) > this.getMaxSpeed() && this.getXVel() > 0) {
this.setXVel(this.getMaxSpeed());
} else if (Math.abs(this.getXVel()) > this.getMaxSpeed() && this.getXVel() < 0) {
this.setXVel(-this.getMaxSpeed());
}
}
//Moving protagonist
public void move() {
this.setXPos(this.getXPos() + this.getXVel());
this.setYPos(this.getYPos() + this.getYVel());
}
//Deaccelerate protagonist (if stick is not pointed)
public void slowDown() {
this.setXVel(this.getXVel()*slideCoefficient);
}
//Make action from stickAngle
public void handleLeftStick(double angle, double acc) {
if (angle <= 45 || angle >= 315) {
this.accelerate(acc);
} else if (angle >= 135 && angle <= 225) {
this.accelerate(-acc);
} else if (angle > 45 && angle < 135 && this.isTouchingGround()) {
this.jump();
} else if (angle > 225 && angle < 315)
this.down(gp.getGround());
}
//Check if the protagonist is under the ground
//If he is, then set him on top of it
public void checkGround(Ground g){
if(this.yPos + height/2 > g.getYFromX(this.xPos)){
this.yPos = g.getYFromX(this.xPos)-height/2;
this.yVel = 0;
this.yAcc = 0;
touchingGround = true;
}
}
//Check if protagonist hit platform
public void checkPlatform(ArrayList<Platform> al) {
for (int i = 0; i < al.size(); i++) {
if(al.get(i).spans(this.getXPos())) {
- if(this.getYPos() - this.getHeight()/2 > al.get(i).getLowerYFromX(this.getXPos())) {
+ //if head is in platform
+ if(this.getYPos() - this.getHeight()/2 < al.get(i).getLowerYFromX(this.getXPos()) && this.getYPos() - this.getHeight()/2 > al.get(i).getUpperYFromX(this.getXPos())) {
this.setYVel(-this.getYVel());
- this.setYAcc(0);
}
- if(this.getYPos() + this.getHeight()/2 < al.get(i).getUpperYFromX(this.getXPos())) {
+ //if feet is in platform
+ if(this.getYPos() + this.getHeight()/2 > al.get(i).getUpperYFromX(this.getXPos()) && this.getYPos() + this.getHeight() < al.get(i).getLowerYFromX(this.getXPos())) {
this.setYVel(0);
this.setYAcc(0);
touchingGround = true;
}
}
}
}
//Let gravity work on protagonist
public void gravity(){
this.setYVel(this.getYVel()+this.getJumpAcc());
}
}
| false | true | public void checkPlatform(ArrayList<Platform> al) {
for (int i = 0; i < al.size(); i++) {
if(al.get(i).spans(this.getXPos())) {
if(this.getYPos() - this.getHeight()/2 > al.get(i).getLowerYFromX(this.getXPos())) {
this.setYVel(-this.getYVel());
this.setYAcc(0);
}
if(this.getYPos() + this.getHeight()/2 < al.get(i).getUpperYFromX(this.getXPos())) {
this.setYVel(0);
this.setYAcc(0);
touchingGround = true;
}
}
}
}
| public void checkPlatform(ArrayList<Platform> al) {
for (int i = 0; i < al.size(); i++) {
if(al.get(i).spans(this.getXPos())) {
//if head is in platform
if(this.getYPos() - this.getHeight()/2 < al.get(i).getLowerYFromX(this.getXPos()) && this.getYPos() - this.getHeight()/2 > al.get(i).getUpperYFromX(this.getXPos())) {
this.setYVel(-this.getYVel());
}
//if feet is in platform
if(this.getYPos() + this.getHeight()/2 > al.get(i).getUpperYFromX(this.getXPos()) && this.getYPos() + this.getHeight() < al.get(i).getLowerYFromX(this.getXPos())) {
this.setYVel(0);
this.setYAcc(0);
touchingGround = true;
}
}
}
}
|
diff --git a/src/haven/RootWidget.java b/src/haven/RootWidget.java
index 058ef5f6..bcacade2 100644
--- a/src/haven/RootWidget.java
+++ b/src/haven/RootWidget.java
@@ -1,71 +1,71 @@
/*
* This file is part of the Haven & Hearth game client.
* Copyright (C) 2009 Fredrik Tolf <[email protected]>, and
* Björn Johannessen <[email protected]>
*
* Redistribution and/or modification of this file is subject to the
* terms of the GNU Lesser General Public License, version 3, as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* Other parts of this source tree adhere to other copying
* rights. Please see the file `COPYING' in the root directory of the
* source tree for details.
*
* A copy the GNU Lesser General Public License is distributed along
* with the source tree of which this file is a part in the file
* `doc/LPGL-3'. If it is missing for any reason, please see the Free
* Software Foundation's website at <http://www.fsf.org/>, or write
* to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307 USA
*/
package haven;
import java.awt.event.KeyEvent;
public class RootWidget extends ConsoleHost {
public static Resource defcurs = Resource.load("gfx/hud/curs/arw");
Logout logout = null;
Profile gprof;
boolean afk = false;
public RootWidget(UI ui, Coord sz) {
super(ui, new Coord(0, 0), sz);
setfocusctl(true);
cursor = defcurs;
}
public boolean globtype(char key, KeyEvent ev) {
if(!super.globtype(key, ev)) {
if(Config.profile && (key == '`')) {
new Profwnd(findchild(SlenHud.class), gprof, "Glob prof");
- } else if(Config.profile && (key == '!')) {
+ } else if(key == ':') {
entercmd();
} else if(key != 0) {
wdgmsg("gk", (int)key);
}
}
return(true);
}
public void draw(GOut g) {
super.draw(g);
drawcmd(g, new Coord(20, 580));
if(!afk && (System.currentTimeMillis() - ui.lastevent > 300000)) {
afk = true;
Widget slen = findchild(SlenHud.class);
if(slen != null)
slen.wdgmsg("afk");
} else if(afk && (System.currentTimeMillis() - ui.lastevent < 300000)) {
afk = false;
}
}
public void error(String msg) {
}
}
| true | true | public boolean globtype(char key, KeyEvent ev) {
if(!super.globtype(key, ev)) {
if(Config.profile && (key == '`')) {
new Profwnd(findchild(SlenHud.class), gprof, "Glob prof");
} else if(Config.profile && (key == '!')) {
entercmd();
} else if(key != 0) {
wdgmsg("gk", (int)key);
}
}
return(true);
}
| public boolean globtype(char key, KeyEvent ev) {
if(!super.globtype(key, ev)) {
if(Config.profile && (key == '`')) {
new Profwnd(findchild(SlenHud.class), gprof, "Glob prof");
} else if(key == ':') {
entercmd();
} else if(key != 0) {
wdgmsg("gk", (int)key);
}
}
return(true);
}
|
diff --git a/remote/src/main/java/ch/ethz/iks/r_osgi/impl/ChannelEndpointImpl.java b/remote/src/main/java/ch/ethz/iks/r_osgi/impl/ChannelEndpointImpl.java
index 6e87002..380ba33 100644
--- a/remote/src/main/java/ch/ethz/iks/r_osgi/impl/ChannelEndpointImpl.java
+++ b/remote/src/main/java/ch/ethz/iks/r_osgi/impl/ChannelEndpointImpl.java
@@ -1,760 +1,759 @@
/* Copyright (c) 2006-2007 Jan S. Rellermeyer
* Information and Communication Systems Research Group (IKS),
* Department of Computer Science, ETH Zurich.
* 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 ETH Zurich nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package ch.ethz.iks.r_osgi.impl;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleException;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventConstants;
import org.osgi.service.event.EventHandler;
import ch.ethz.iks.r_osgi.ChannelEndpoint;
import ch.ethz.iks.r_osgi.NetworkChannelFactory;
import ch.ethz.iks.r_osgi.RemoteOSGiMessage;
import ch.ethz.iks.r_osgi.RemoteOSGiException;
import ch.ethz.iks.r_osgi.RemoteOSGiService;
import ch.ethz.iks.r_osgi.NetworkChannel;
import ch.ethz.iks.slp.ServiceLocationException;
import ch.ethz.iks.slp.ServiceURL;
/**
* <p>
* The endpoint of a network channel encapsulates most of the communication
* logic like sending of messages, service method invocation, timestamp
* synchronization, and event delivery.
* </p>
* <p>
* Endpoints exchange symmetric leases when they are established. These leases
* contain the statements of supply and demand. The peer states the services it
* offers and the event topics it is interested in. Whenever one of these
* statements undergo a change, the lease has to be renewed. Leases expire with
* the closing of the network channel and the two bound endpoints.
* </p>
* <p>
* The network transport of channels is modular and exchangeable. Services can
* state the supported protocols in their service url. R-OSGi maintains a list
* of network channel factories and the protocols they support. Each channel
* uses exactly one protocol.
* <p>
* <p>
* When the network channel breaks down, the channel endpoint tries to reconnect
* and to restore the connection. If this is not possible (for instance, because
* the other endpoint is not available any more, the endpoint is unregistered.
* </p>
*
* @author Jan S. Rellermeyer, ETH Zurich
*/
public final class ChannelEndpointImpl implements ChannelEndpoint {
/**
* the channel.
*/
private NetworkChannel networkChannel;
/**
* the services provided by the OSGi framework holding the remote channel
* endpoint.
*/
private String[] remoteServices;
/**
* the topics of interest of the OSGi framework holding the remote channel
* endpoint.
*/
private String[] remoteTopics;
/**
* the time offset between this peer's local time and the local time of the
* remote channel endpoint.
*/
private TimeOffset timeOffset;
/**
* Timeout.
*/
private static final int TIMEOUT = 120000;
/**
* the receiver queue.
*/
private final Map receiveQueue = new HashMap(0);
/**
* map of service url -> attribute dictionary.
*/
private final HashMap attributes = new HashMap(0);
/**
* map of service url -> service object.
*/
private final HashMap services = new HashMap(2);
/**
* a list of all registered proxy bundle. If the endpoint is closed, the
* proxies are unregistered.
*/
private final List proxies = new ArrayList(0);
/**
*
*/
private ServiceRegistration handlerReg = null;
/**
* keeps track if the channel endpoint has lost its connection to the other
* endpoint.
*/
private boolean lostConnection = false;
/**
* dummy object used for blocking method calls until the result message has
* arrived.
*/
private static final Object WAITING = new Object();
/**
* filter for events to prevent loops in the remote delivery if the peers
* connected by this channel have non-disjoint topic spaces.
*/
private static final String NO_LOOPS = "(!("
+ RemoteOSGiServiceImpl.EVENT_SENDER_URL + "=*))";
/**
* the TCPChannel factory.
*/
private static final TCPChannelFactory TCP_FACTORY = new TCPChannelFactory();
/**
* create a new channel endpoint.
*
* @param connection
* the transport channel.
* @throws RemoteOSGiException
* @throws IOException
*/
ChannelEndpointImpl(final NetworkChannelFactory factory,
final InetAddress address, final int port, final String protocol)
throws RemoteOSGiException, IOException {
this.networkChannel = (factory == null ? TCP_FACTORY : factory)
.getConnection(this, address, port, protocol);
renewLease(RemoteOSGiServiceImpl.getServices(), RemoteOSGiServiceImpl
.getTopics());
RemoteOSGiServiceImpl.registerChannel(this);
}
ChannelEndpointImpl(Socket socket) throws IOException {
System.out.println("GOING TO ACCEPT NEW CONNECTION "
+ socket.getInetAddress() + ":" + socket.getPort());
this.networkChannel = TCP_FACTORY.bind(this, socket);
System.out.println("HAVE ACCEPTED CONNECTION " + networkChannel);
RemoteOSGiServiceImpl.registerChannel(this);
}
/**
* get the channel ID.
*
* @return the channel ID.
*/
public String getID() {
final String protocol = networkChannel.getProtocol();
return (protocol != null ? protocol : "r-osgi") + "://"
+ networkChannel.getInetAddress().getHostAddress() + ":"
+ networkChannel.getPort();
}
/**
* renew the lease.
*
* @param services
* the (local) services.
* @param topics
* the (local) topics.
* @throws RemoteOSGiException
* if the channel cannot be established.
*/
void renewLease(final String[] services, final String[] topics)
throws RemoteOSGiException {
final LeaseMessage lease = (LeaseMessage) sendMessage(new LeaseMessage(
services, topics));
updateStatements(lease);
}
/**
* update the statements of suppy and demand.
*
* @param lease
* the original lease.
*/
private void updateStatements(final LeaseMessage lease) {
final String[] remoteServices = lease.getServices();
if (remoteServices != null) {
this.remoteServices = remoteServices;
}
final String[] theTopics = lease.getTopics();
if (theTopics != null) {
remoteTopics = theTopics;
if (handlerReg == null) {
if (theTopics.length == 0) {
// no change
} else {
// register handler
final Dictionary properties = new Hashtable();
properties.put(EventConstants.EVENT_TOPIC, theTopics);
properties.put(EventConstants.EVENT_FILTER, NO_LOOPS);
properties.put(RemoteOSGiServiceImpl.R_OSGi_INTERNAL,
Boolean.TRUE);
handlerReg = RemoteOSGiServiceImpl.context.registerService(
EventHandler.class.getName(), new EventForwarder(),
properties);
}
} else {
if (theTopics.length == 0) {
// unregister handler
handlerReg.unregister();
handlerReg = null;
} else {
// update topics
final Dictionary properties = new Hashtable();
properties.put(EventConstants.EVENT_TOPIC, theTopics);
properties.put(EventConstants.EVENT_FILTER, NO_LOOPS);
properties.put(RemoteOSGiServiceImpl.R_OSGi_INTERNAL,
Boolean.TRUE);
handlerReg.setProperties(properties);
}
}
}
System.out.println();
System.out.println("NEW REMOTE TOPIC SPACE "
+ java.util.Arrays.asList(theTopics));
}
/**
* get the services of the remote channel endpoint.
*
* @return the services.
*/
String[] getRemoteServices() {
return remoteServices;
}
/**
* get the remote topics that the remote channel endpoint is interested in.
*
* @return the topics.
*/
String[] getRemoteTopics() {
return remoteTopics;
}
/**
* invoke a method on the remote host. This function is used by all proxy
* bundles.
*
* @param service
* the service URL.
* @param methodSignature
* the method signature.
* @param args
* the method parameter.
* @return the result of the remote method invokation.
* @see ch.ethz.iks.r_osgi.Remoting#invokeMethod(java.lang.String,
* java.lang.String, java.lang.String, java.lang.Object[])
* @since 0.2
* @category Remoting
*/
public Object invokeMethod(final String service,
final String methodSignature, final Object[] args) throws Throwable {
final InvokeMethodMessage invokeMsg = new InvokeMethodMessage(service
.toString(), methodSignature, args);
try {
// send the message and get a MethodResultMessage in return
final MethodResultMessage result = (MethodResultMessage) sendMessage(invokeMsg);
if (result.causedException()) {
throw result.getException();
}
return result.getResult();
} catch (RemoteOSGiException e) {
throw new RemoteOSGiException("Method invocation of "
+ methodSignature + " failed.", e);
}
}
/**
* fetch the service from the remote peer.
*
* @param service
* the service url.
* @throws IOException
* in case of network errors.
* @throws BundleException
* if the installation of the proxy or the migrated bundle
* fails.
*/
void fetchService(final ServiceURL service) throws IOException,
BundleException {
// build the FetchServiceMessage
final FetchServiceMessage fetchReq = new FetchServiceMessage(service);
// send the FetchServiceMessage and get a DeliverServiceMessage in
// return
final RemoteOSGiMessageImpl msg = sendMessage(fetchReq);
if (msg instanceof DeliverServiceMessage) {
final DeliverServiceMessage deliv = (DeliverServiceMessage) msg;
try {
final ServiceURL url = new ServiceURL(deliv.getServiceURL(), 0);
// set the REMOTE_HOST_PROPERTY
final Dictionary attribs = deliv.getAttributes();
attribs.put(RemoteOSGiServiceImpl.REMOTE_HOST, service
.getHost());
// remove the service PID, if set
attribs.remove("service.pid");
// remove the R-OSGi registration property
attribs.remove(RemoteOSGiService.R_OSGi_REGISTRATION);
attributes.put(url.toString(), attribs);
// generate a proxy bundle for the service
// TODO: redesign ProxyGenerator to be static
final String bundleLocation = new ProxyGenerator()
.generateProxyBundle(url, deliv);
// install the proxy bundle
final Bundle bundle = RemoteOSGiServiceImpl.context
.installBundle("file:" + bundleLocation);
// store the bundle for cleanup
proxies.add(bundle);
// start the bundle
bundle.start();
} catch (ServiceLocationException sle) {
throw new RemoteOSGiException("ServiceURL "
+ deliv.getServiceURL() + " is not valid.");
}
} else {
final DeliverBundleMessage delivB = (DeliverBundleMessage) msg;
Bundle bundle = RemoteOSGiServiceImpl.context.installBundle(
"r-osgi://" + service.toString(), new ByteArrayInputStream(
delivB.getBundle()));
bundle.start();
}
}
/**
* send a RemoteOSGiMessage.
*
* @param msg
* the message.
* @return the reply message.
* @throws RemoteOSGiException
* in case of network errors.
*/
RemoteOSGiMessageImpl sendMessage(final RemoteOSGiMessageImpl msg)
throws RemoteOSGiException {
Throwable lastException = null;
// TODO think of setting retry count by property ?
int retryCounter = 3;
// if this is a reply message, the xid is
// the same as the incoming message. Otherwise
// we assign the next xid.
if (msg.xid == 0) {
msg.xid = RemoteOSGiServiceImpl.nextXid();
}
final Integer xid = new Integer(msg.xid);
if (!(msg instanceof RemoteEventMessage)) {
synchronized (receiveQueue) {
receiveQueue.put(xid, WAITING);
}
}
while (retryCounter > 0) {
try {
// send the message
dispatchMessage(msg);
if (msg instanceof RemoteEventMessage) {
return null;
}
Object reply;
synchronized (receiveQueue) {
reply = receiveQueue.get(xid);
final long timeout = System.currentTimeMillis() + TIMEOUT;
while (!lostConnection && reply == WAITING
&& System.currentTimeMillis() < timeout) {
receiveQueue.wait(TIMEOUT);
reply = receiveQueue.get(xid);
}
receiveQueue.remove(xid);
if (lostConnection) {
throw new RemoteOSGiException(
"Method Incovation failed, lost connection");
}
if (reply == WAITING) {
throw new RemoteOSGiException(
"Method Invocation failed.");
} else {
return (RemoteOSGiMessageImpl) reply;
}
}
} catch (Throwable t) {
// TODO: remove
t.printStackTrace();
lastException = t;
recoverConnection();
// TimeOffsetMessages have to be handled differently
// must send a new message with a new timestamp and XID instead
// of sending the same message again
if (msg instanceof TimeOffsetMessage) {
((TimeOffsetMessage) msg).restamp(RemoteOSGiServiceImpl
.nextXid());
} else {
// send / receive reply failed
retryCounter--;
// reset connection
}
}
}
if (lastException != null) {
throw new RemoteOSGiException("Network error", lastException);
}
return null;
}
/**
* get the temporal offset of a remote peer.
*
* @return the TimeOffset.
* @throws RemoteOSGiException
* in case of network errors.
*/
TimeOffset getOffset() throws RemoteOSGiException {
if (timeOffset == null) {
// if unknown, perform a initial offset measurement round of 4
// messages
TimeOffsetMessage timeMsg = new TimeOffsetMessage();
for (int i = 0; i < 4; i++) {
timeMsg.timestamp();
timeMsg = (TimeOffsetMessage) sendMessage(timeMsg);
}
timeOffset = new TimeOffset(timeMsg.getTimeSeries());
} else if (timeOffset.isExpired()) {
// if offset has expired, start a new measurement round
TimeOffsetMessage timeMsg = new TimeOffsetMessage();
for (int i = 0; i < timeOffset.seriesLength(); i += 2) {
timeMsg.timestamp();
timeMsg = (TimeOffsetMessage) sendMessage(timeMsg);
}
timeOffset.update(timeMsg.getTimeSeries());
}
return timeOffset;
}
/**
* message handler method.
*
* @param msg
* the incoming message.
* @return if reply is created, null otherwise.
* @throws RemoteOSGiException
* if something goes wrong.
*/
private RemoteOSGiMessage handleMessage(final RemoteOSGiMessage msg)
throws RemoteOSGiException {
switch (msg.getFuncID()) {
// requests
case RemoteOSGiMessageImpl.LEASE: {
final LeaseMessage lease = (LeaseMessage) msg;
updateStatements(lease);
if (lease.getXID() == 0) {
return null;
}
- // TODO: somehow the protocol has to be included ...
return lease.replyWith(RemoteOSGiServiceImpl.getServices(),
RemoteOSGiServiceImpl.getTopics());
}
case RemoteOSGiMessageImpl.FETCH_SERVICE: {
try {
final FetchServiceMessage fetchReq = (FetchServiceMessage) msg;
final ServiceURL url = new ServiceURL(fetchReq.getServiceURL(),
0);
final RemoteServiceRegistration reg;
if (!"".equals(url.getURLPath())) {
reg = RemoteOSGiServiceImpl.getService(url);
} else {
reg = RemoteOSGiServiceImpl.getAnyService(url);
}
if (reg == null) {
throw new IllegalStateException("Could not get "
+ fetchReq.getServiceURL());
}
if (reg instanceof ProxiedServiceRegistration) {
services.put(url.toString(), reg);
return ((ProxiedServiceRegistration) reg)
.getMessage(fetchReq);
} else if (reg instanceof BundledServiceRegistration) {
return new DeliverBundleMessage(fetchReq,
(BundledServiceRegistration) reg);
}
} catch (ServiceLocationException sle) {
sle.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
case RemoteOSGiMessageImpl.INVOKE_METHOD: {
final InvokeMethodMessage invMsg = (InvokeMethodMessage) msg;
try {
final ProxiedServiceRegistration serv = (ProxiedServiceRegistration) services
.get(invMsg.getServiceURL());
if (serv == null) {
System.err.println("REQUESTED " + invMsg.getServiceURL());
System.err.println("IN CACHE: " + services);
throw new IllegalStateException("Could not get "
+ invMsg.getServiceURL());
}
// get the invokation arguments and the local method
final Object[] arguments = invMsg.getArgs();
final Method method = serv.getMethod(invMsg
.getMethodSignature());
// invoke method
try {
final Object result = method.invoke(
serv.getServiceObject(), arguments);
return new MethodResultMessage(invMsg, result);
} catch (InvocationTargetException t) {
throw t.getTargetException();
}
} catch (Throwable t) {
return new MethodResultMessage(invMsg, t);
}
}
case RemoteOSGiMessageImpl.REMOTE_EVENT: {
final RemoteEventMessage eventMsg = (RemoteEventMessage) msg;
final Event event = eventMsg.getEvent(this);
System.out.println("RECEIVED REMOTE EVENT " + event);
// and deliver the event to the local framework
if (RemoteOSGiServiceImpl.eventAdmin != null) {
RemoteOSGiServiceImpl.eventAdmin.postEvent(event);
} else {
System.err.println("Could not deliver received event: " + event
+ ". No EventAdmin available.");
}
return null;
}
case RemoteOSGiMessageImpl.TIME_OFFSET: {
// add timestamp to the message and return the message to sender
((TimeOffsetMessage) msg).timestamp();
return msg;
}
default:
throw new RemoteOSGiException("Unimplemented message " + msg);
}
}
/**
* send a message over the channel.
*
* @param msg
* the message.
* @throws IOException
*/
void dispatchMessage(final RemoteOSGiMessage msg) throws IOException {
networkChannel.sendMessage(msg);
}
/**
* dispose the channel.
*/
public void dispose() {
System.out.println("DISPOSING ENDPOINT " + getID());
RemoteOSGiServiceImpl.unregisterChannel(this);
Bundle[] bundles = (Bundle[]) proxies
.toArray(new Bundle[proxies.size()]);
for (int i = 0; i < bundles.length; i++) {
try {
if (bundles[i].getState() == Bundle.ACTIVE) {
bundles[i].uninstall();
}
} catch (BundleException e) {
// don't care
}
}
}
/**
* Try to recover a broken-down connection.
*
* @return true, if the connection could be recovered.
*/
boolean recoverConnection() {
lostConnection = true;
try {
networkChannel.reconnect();
lostConnection = false;
System.out.println("Channel " + getID() + " recovery successful");
} catch (IOException ioe) {
System.err.println("Recovery failed: " + ioe.getMessage());
dispose();
return true;
} finally {
synchronized (receiveQueue) {
receiveQueue.notifyAll();
}
}
return false;
}
/**
* process a recieved message. Called by the channel.
*
* @param msg
* the received message.
*/
public void receivedMessage(final RemoteOSGiMessage msg) {
if (msg == null) {
System.out.println("RECEIVED POISONED INPUT MESSAGE");
System.out.println("STARTING RECOVERY ...");
recoverConnection();
return;
}
final Integer xid = new Integer(msg.getXID());
synchronized (receiveQueue) {
final Object state = receiveQueue.get(xid);
if (state == WAITING) {
receiveQueue.put(xid, msg);
receiveQueue.notifyAll();
return;
} else {
RemoteOSGiMessage reply = handleMessage(msg);
if (reply != null) {
try {
dispatchMessage(reply);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
/**
* get the attributes of a service. This function is used to simplify proxy
* bundle generation.
*
* @param serviceURL
* the serviceURL of the remote service.
* @return the service attributes.
* @see ch.ethz.iks.r_osgi.Remoting#getAttributes(java.lang.String)
* @since 0.2
* @category Remoting
*/
public Dictionary getAttributes(final String serviceURL) {
return (Dictionary) attributes.get(serviceURL);
}
/**
* get the attributes for the presentation of the service. This function is
* used by proxies that support ServiceUI presentations.
*
* @param serviceURL
* the serviceURL of the remote service.
* @return the presentation attributes.
* @see ch.ethz.iks.r_osgi.Remoting#getPresentationAttributes(java.lang.String)
* @since 0.4
* @category Remoting
*/
public Dictionary getPresentationAttributes(final String serviceURL) {
final Dictionary attribs = new Hashtable();
try {
attribs.put(RemoteOSGiServiceImpl.REMOTE_HOST, new ServiceURL(
serviceURL, 0).getHost());
attribs.put(RemoteOSGiService.PRESENTATION,
((Dictionary) attributes.get(serviceURL))
.get(RemoteOSGiService.PRESENTATION));
} catch (ServiceLocationException sle) {
throw new IllegalArgumentException("ServiceURL " + serviceURL
+ " is invalid.");
}
return attribs;
}
/**
* forwards events over the channel to the remote peer.
*
* @author Jan S. Rellermeyer, ETH Zurich
* @category EventHandler
*/
private final class EventForwarder implements EventHandler {
public void handleEvent(Event event) {
try {
sendMessage(new RemoteEventMessage(event, getID()));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
| true | true | private RemoteOSGiMessage handleMessage(final RemoteOSGiMessage msg)
throws RemoteOSGiException {
switch (msg.getFuncID()) {
// requests
case RemoteOSGiMessageImpl.LEASE: {
final LeaseMessage lease = (LeaseMessage) msg;
updateStatements(lease);
if (lease.getXID() == 0) {
return null;
}
// TODO: somehow the protocol has to be included ...
return lease.replyWith(RemoteOSGiServiceImpl.getServices(),
RemoteOSGiServiceImpl.getTopics());
}
case RemoteOSGiMessageImpl.FETCH_SERVICE: {
try {
final FetchServiceMessage fetchReq = (FetchServiceMessage) msg;
final ServiceURL url = new ServiceURL(fetchReq.getServiceURL(),
0);
final RemoteServiceRegistration reg;
if (!"".equals(url.getURLPath())) {
reg = RemoteOSGiServiceImpl.getService(url);
} else {
reg = RemoteOSGiServiceImpl.getAnyService(url);
}
if (reg == null) {
throw new IllegalStateException("Could not get "
+ fetchReq.getServiceURL());
}
if (reg instanceof ProxiedServiceRegistration) {
services.put(url.toString(), reg);
return ((ProxiedServiceRegistration) reg)
.getMessage(fetchReq);
} else if (reg instanceof BundledServiceRegistration) {
return new DeliverBundleMessage(fetchReq,
(BundledServiceRegistration) reg);
}
} catch (ServiceLocationException sle) {
sle.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
case RemoteOSGiMessageImpl.INVOKE_METHOD: {
final InvokeMethodMessage invMsg = (InvokeMethodMessage) msg;
try {
final ProxiedServiceRegistration serv = (ProxiedServiceRegistration) services
.get(invMsg.getServiceURL());
if (serv == null) {
System.err.println("REQUESTED " + invMsg.getServiceURL());
System.err.println("IN CACHE: " + services);
throw new IllegalStateException("Could not get "
+ invMsg.getServiceURL());
}
// get the invokation arguments and the local method
final Object[] arguments = invMsg.getArgs();
final Method method = serv.getMethod(invMsg
.getMethodSignature());
// invoke method
try {
final Object result = method.invoke(
serv.getServiceObject(), arguments);
return new MethodResultMessage(invMsg, result);
} catch (InvocationTargetException t) {
throw t.getTargetException();
}
} catch (Throwable t) {
return new MethodResultMessage(invMsg, t);
}
}
case RemoteOSGiMessageImpl.REMOTE_EVENT: {
final RemoteEventMessage eventMsg = (RemoteEventMessage) msg;
final Event event = eventMsg.getEvent(this);
System.out.println("RECEIVED REMOTE EVENT " + event);
// and deliver the event to the local framework
if (RemoteOSGiServiceImpl.eventAdmin != null) {
RemoteOSGiServiceImpl.eventAdmin.postEvent(event);
} else {
System.err.println("Could not deliver received event: " + event
+ ". No EventAdmin available.");
}
return null;
}
case RemoteOSGiMessageImpl.TIME_OFFSET: {
// add timestamp to the message and return the message to sender
((TimeOffsetMessage) msg).timestamp();
return msg;
}
default:
throw new RemoteOSGiException("Unimplemented message " + msg);
}
}
| private RemoteOSGiMessage handleMessage(final RemoteOSGiMessage msg)
throws RemoteOSGiException {
switch (msg.getFuncID()) {
// requests
case RemoteOSGiMessageImpl.LEASE: {
final LeaseMessage lease = (LeaseMessage) msg;
updateStatements(lease);
if (lease.getXID() == 0) {
return null;
}
return lease.replyWith(RemoteOSGiServiceImpl.getServices(),
RemoteOSGiServiceImpl.getTopics());
}
case RemoteOSGiMessageImpl.FETCH_SERVICE: {
try {
final FetchServiceMessage fetchReq = (FetchServiceMessage) msg;
final ServiceURL url = new ServiceURL(fetchReq.getServiceURL(),
0);
final RemoteServiceRegistration reg;
if (!"".equals(url.getURLPath())) {
reg = RemoteOSGiServiceImpl.getService(url);
} else {
reg = RemoteOSGiServiceImpl.getAnyService(url);
}
if (reg == null) {
throw new IllegalStateException("Could not get "
+ fetchReq.getServiceURL());
}
if (reg instanceof ProxiedServiceRegistration) {
services.put(url.toString(), reg);
return ((ProxiedServiceRegistration) reg)
.getMessage(fetchReq);
} else if (reg instanceof BundledServiceRegistration) {
return new DeliverBundleMessage(fetchReq,
(BundledServiceRegistration) reg);
}
} catch (ServiceLocationException sle) {
sle.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
case RemoteOSGiMessageImpl.INVOKE_METHOD: {
final InvokeMethodMessage invMsg = (InvokeMethodMessage) msg;
try {
final ProxiedServiceRegistration serv = (ProxiedServiceRegistration) services
.get(invMsg.getServiceURL());
if (serv == null) {
System.err.println("REQUESTED " + invMsg.getServiceURL());
System.err.println("IN CACHE: " + services);
throw new IllegalStateException("Could not get "
+ invMsg.getServiceURL());
}
// get the invokation arguments and the local method
final Object[] arguments = invMsg.getArgs();
final Method method = serv.getMethod(invMsg
.getMethodSignature());
// invoke method
try {
final Object result = method.invoke(
serv.getServiceObject(), arguments);
return new MethodResultMessage(invMsg, result);
} catch (InvocationTargetException t) {
throw t.getTargetException();
}
} catch (Throwable t) {
return new MethodResultMessage(invMsg, t);
}
}
case RemoteOSGiMessageImpl.REMOTE_EVENT: {
final RemoteEventMessage eventMsg = (RemoteEventMessage) msg;
final Event event = eventMsg.getEvent(this);
System.out.println("RECEIVED REMOTE EVENT " + event);
// and deliver the event to the local framework
if (RemoteOSGiServiceImpl.eventAdmin != null) {
RemoteOSGiServiceImpl.eventAdmin.postEvent(event);
} else {
System.err.println("Could not deliver received event: " + event
+ ". No EventAdmin available.");
}
return null;
}
case RemoteOSGiMessageImpl.TIME_OFFSET: {
// add timestamp to the message and return the message to sender
((TimeOffsetMessage) msg).timestamp();
return msg;
}
default:
throw new RemoteOSGiException("Unimplemented message " + msg);
}
}
|
diff --git a/res-pos/src/main/java/com/res/controller/MenuController.java b/res-pos/src/main/java/com/res/controller/MenuController.java
index 01f5624..112efa7 100644
--- a/res-pos/src/main/java/com/res/controller/MenuController.java
+++ b/res-pos/src/main/java/com/res/controller/MenuController.java
@@ -1,54 +1,54 @@
package com.res.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import com.res.exception.ServiceException;
import com.res.model.FoodCategory;
import com.res.service.MenuService;
import com.res.util.MessageLoader;
@Controller
@SessionAttributes
public class MenuController {
private static Logger logger = Logger.getLogger(MenuController.class);
@Autowired private MenuService menuService;
@Autowired private MessageLoader messageLoader;
@RequestMapping(value="/menu", method=RequestMethod.GET)
public ModelAndView showMenu(HttpServletRequest req, HttpServletResponse res) throws ServiceException{
HttpSession session = req.getSession();
String resId = (String)session.getAttribute("restaurantId");
if(StringUtils.isEmpty(resId)){
throw new ServiceException(messageLoader.getMessage("restaurantid.not.set"));
}
Long restaurantId = Long.parseLong(resId);
ModelAndView mav = new ModelAndView("menu");
logger.info("restaurantId = " + restaurantId);
- List<FoodCategory> foodCategories = menuService.getFoodCategoriesFromMenu(restaurantId); //TODO: change to real resid
+ List<FoodCategory> foodCategories = menuService.getFoodCategoriesFromMenu(restaurantId);
mav.addObject("restaurantId", restaurantId);
mav.addObject("foodCategories", foodCategories);
mav.addObject("foodCategoriesSize", foodCategories.size());
return mav;
}
}
| true | true | public ModelAndView showMenu(HttpServletRequest req, HttpServletResponse res) throws ServiceException{
HttpSession session = req.getSession();
String resId = (String)session.getAttribute("restaurantId");
if(StringUtils.isEmpty(resId)){
throw new ServiceException(messageLoader.getMessage("restaurantid.not.set"));
}
Long restaurantId = Long.parseLong(resId);
ModelAndView mav = new ModelAndView("menu");
logger.info("restaurantId = " + restaurantId);
List<FoodCategory> foodCategories = menuService.getFoodCategoriesFromMenu(restaurantId); //TODO: change to real resid
mav.addObject("restaurantId", restaurantId);
mav.addObject("foodCategories", foodCategories);
mav.addObject("foodCategoriesSize", foodCategories.size());
return mav;
}
| public ModelAndView showMenu(HttpServletRequest req, HttpServletResponse res) throws ServiceException{
HttpSession session = req.getSession();
String resId = (String)session.getAttribute("restaurantId");
if(StringUtils.isEmpty(resId)){
throw new ServiceException(messageLoader.getMessage("restaurantid.not.set"));
}
Long restaurantId = Long.parseLong(resId);
ModelAndView mav = new ModelAndView("menu");
logger.info("restaurantId = " + restaurantId);
List<FoodCategory> foodCategories = menuService.getFoodCategoriesFromMenu(restaurantId);
mav.addObject("restaurantId", restaurantId);
mav.addObject("foodCategories", foodCategories);
mav.addObject("foodCategoriesSize", foodCategories.size());
return mav;
}
|
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickSettings.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickSettings.java
index 5a1eaf81..f849cafa 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickSettings.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickSettings.java
@@ -1,1619 +1,1623 @@
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.systemui.statusbar.phone;
import com.android.internal.view.RotationPolicy;
import com.android.internal.widget.LockPatternUtils;
import com.android.systemui.R;
import com.android.systemui.statusbar.phone.QuickSettingsModel.BluetoothState;
import com.android.systemui.statusbar.phone.QuickSettingsModel.RSSIState;
import com.android.systemui.statusbar.phone.QuickSettingsModel.State;
import com.android.systemui.statusbar.phone.QuickSettingsModel.UserState;
import com.android.systemui.statusbar.phone.QuickSettingsModel.WifiState;
import com.android.systemui.statusbar.policy.BatteryController;
import com.android.systemui.statusbar.policy.BluetoothController;
import com.android.systemui.statusbar.policy.BrightnessController;
import com.android.systemui.statusbar.policy.LocationController;
import com.android.systemui.statusbar.policy.NetworkController;
import com.android.systemui.statusbar.policy.ToggleSlider;
import android.app.ActivityManagerNative;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.CursorLoader;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.UserInfo;
import android.content.res.Resources;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LevelListDrawable;
import android.hardware.display.DisplayManager;
import android.hardware.display.WifiDisplayStatus;
import android.location.LocationManager;
import android.nfc.NfcAdapter;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.RemoteException;
import android.os.UserHandle;
import android.os.UserManager;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Profile;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowManagerGlobal;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.internal.telephony.PhoneConstants;
import com.android.systemui.aokp.AokpTarget;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
/**
*
*/
class QuickSettings {
private static final String TAG = "QuickSettings";
public static final boolean SHOW_IME_TILE = false;
private static final String TOGGLE_PIPE = "|";
private static final int USER_TILE = 0;
private static final int BRIGHTNESS_TILE = 1;
private static final int SETTINGS_TILE = 2;
private static final int WIFI_TILE = 3;
private static final int SIGNAL_TILE = 4;
private static final int ROTATE_TILE = 5;
private static final int CLOCK_TILE = 6;
private static final int GPS_TILE = 7;
private static final int IME_TILE = 8;
private static final int BATTERY_TILE = 9;
private static final int AIRPLANE_TILE = 10;
private static final int BLUETOOTH_TILE = 11;
private static final int SWAGGER_TILE = 12;
private static final int VIBRATE_TILE = 13;
private static final int SILENT_TILE = 14;
private static final int FCHARGE_TILE = 15;
private static final int SYNC_TILE = 16;
private static final int NFC_TILE = 17;
private static final int TORCH_TILE = 18;
private static final int WIFI_TETHER_TILE = 19;
private static final int USB_TETHER_TILE = 20;
private static final int TWOG_TILE = 21;
private static final int LTE_TILE = 22;
// private static final int BT_TETHER_TILE = 23;
public static final String USER_TOGGLE = "USER";
public static final String BRIGHTNESS_TOGGLE = "BRIGHTNESS";
public static final String SETTINGS_TOGGLE = "SETTINGS";
public static final String WIFI_TOGGLE = "WIFI";
public static final String SIGNAL_TOGGLE = "SIGNAL";
public static final String ROTATE_TOGGLE = "ROTATE";
public static final String CLOCK_TOGGLE = "CLOCK";
public static final String GPS_TOGGLE = "GPS";
public static final String IME_TOGGLE = "IME";
public static final String BATTERY_TOGGLE = "BATTERY";
public static final String AIRPLANE_TOGGLE = "AIRPLANE_MODE";
public static final String BLUETOOTH_TOGGLE = "BLUETOOTH";
public static final String SWAGGER_TOGGLE = "SWAGGER";
public static final String VIBRATE_TOGGLE = "VIBRATE";
public static final String SILENT_TOGGLE = "SILENT";
public static final String FCHARGE_TOGGLE = "FCHARGE";
public static final String SYNC_TOGGLE = "SYNC";
public static final String NFC_TOGGLE = "NFC";
public static final String TORCH_TOGGLE = "TORCH";
public static final String WIFI_TETHER_TOGGLE = "WIFITETHER";
// public static final String BT_TETHER_TOGGLE = "BTTETHER";
public static final String USB_TETHER_TOGGLE = "USBTETHER";
public static final String TWOG_TOGGLE = "2G";
public static final String LTE_TOGGLE = "LTE";
private static final String DEFAULT_TOGGLES = "default";
public static final String FAST_CHARGE_DIR = "/sys/kernel/fast_charge";
public static final String FAST_CHARGE_FILE = "force_fast_charge";
private int mWifiApState = WifiManager.WIFI_AP_STATE_DISABLED;
private int mDataState = -1;
private boolean usbTethered;
// at some point we need to move these to string for translation.... dont let me forget
public String strGPSoff = "GPS Off";
public String strGPSon = "GPS On";
public String strDataoff = "Mobile Data Off";
public String strDataon = "Mobile Data On";
private Context mContext;
private PanelBar mBar;
private QuickSettingsModel mModel;
private ViewGroup mContainerView;
private DisplayManager mDisplayManager;
private WifiDisplayStatus mWifiDisplayStatus;
private WifiManager wifiManager;
private ConnectivityManager connManager;
private LocationManager locationManager;
private PhoneStatusBar mStatusBarService;
private BluetoothState mBluetoothState;
private TelephonyManager tm;
private ConnectivityManager mConnService;
private AokpTarget mAokpTarget;
private BrightnessController mBrightnessController;
private BluetoothController mBluetoothController;
private Dialog mBrightnessDialog;
private int mBrightnessDialogShortTimeout;
private int mBrightnessDialogLongTimeout;
private AsyncTask<Void, Void, Pair<String, Drawable>> mUserInfoTask;
private LevelListDrawable mBatteryLevels;
private LevelListDrawable mChargingBatteryLevels;
boolean mTilesSetUp = false;
private Handler mHandler;
private ArrayList<String> toggles;
private String userToggles = null;
private long tacoSwagger = 0;
private boolean tacoToggle = false;
private int mTileTextSize = 12;
private HashMap<String, Integer> toggleMap;
private HashMap<String, Integer> getToggleMap() {
if (toggleMap == null) {
toggleMap = new HashMap<String, Integer>();
toggleMap.put(USER_TOGGLE, USER_TILE);
toggleMap.put(BRIGHTNESS_TOGGLE, BRIGHTNESS_TILE);
toggleMap.put(SETTINGS_TOGGLE, SETTINGS_TILE);
toggleMap.put(WIFI_TOGGLE, WIFI_TILE);
toggleMap.put(SIGNAL_TOGGLE, SIGNAL_TILE);
toggleMap.put(ROTATE_TOGGLE, ROTATE_TILE);
toggleMap.put(CLOCK_TOGGLE, CLOCK_TILE);
toggleMap.put(GPS_TOGGLE, GPS_TILE);
toggleMap.put(IME_TOGGLE, IME_TILE);
toggleMap.put(BATTERY_TOGGLE, BATTERY_TILE);
toggleMap.put(AIRPLANE_TOGGLE, AIRPLANE_TILE);
toggleMap.put(BLUETOOTH_TOGGLE, BLUETOOTH_TILE);
toggleMap.put(VIBRATE_TOGGLE, VIBRATE_TILE);
toggleMap.put(SILENT_TOGGLE, SILENT_TILE);
toggleMap.put(FCHARGE_TOGGLE, FCHARGE_TILE);
toggleMap.put(SYNC_TOGGLE, SYNC_TILE);
toggleMap.put(NFC_TOGGLE, NFC_TILE);
toggleMap.put(TORCH_TOGGLE, TORCH_TILE);
toggleMap.put(WIFI_TETHER_TOGGLE, WIFI_TETHER_TILE);
toggleMap.put(USB_TETHER_TOGGLE, USB_TETHER_TILE);
toggleMap.put(TWOG_TOGGLE, TWOG_TILE);
toggleMap.put(LTE_TOGGLE, LTE_TILE);
//toggleMap.put(BT_TETHER_TOGGLE, BT_TETHER_TILE);
}
return toggleMap;
}
// The set of QuickSettingsTiles that have dynamic spans (and need to be
// updated on
// configuration change)
private final ArrayList<QuickSettingsTileView> mDynamicSpannedTiles =
new ArrayList<QuickSettingsTileView>();
private final RotationPolicy.RotationPolicyListener mRotationPolicyListener =
new RotationPolicy.RotationPolicyListener() {
@Override
public void onChange() {
mModel.onRotationLockChanged();
}
};
public QuickSettings(Context context, QuickSettingsContainerView container) {
mDisplayManager = (DisplayManager) context.getSystemService(Context.DISPLAY_SERVICE);
mContext = context;
mContainerView = container;
mModel = new QuickSettingsModel(context);
mWifiDisplayStatus = new WifiDisplayStatus();
wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
connManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
mBluetoothState = new QuickSettingsModel.BluetoothState();
mHandler = new Handler();
mAokpTarget = new AokpTarget(mContext);
Resources r = mContext.getResources();
mBatteryLevels = (LevelListDrawable) r.getDrawable(R.drawable.qs_sys_battery);
mChargingBatteryLevels =
(LevelListDrawable) r.getDrawable(R.drawable.qs_sys_battery_charging);
mBrightnessDialogLongTimeout =
r.getInteger(R.integer.quick_settings_brightness_dialog_long_timeout);
mBrightnessDialogShortTimeout =
r.getInteger(R.integer.quick_settings_brightness_dialog_short_timeout);
IntentFilter filter = new IntentFilter();
filter.addAction(DisplayManager.ACTION_WIFI_DISPLAY_STATUS_CHANGED);
filter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
filter.addAction(Intent.ACTION_USER_SWITCHED);
mContext.registerReceiver(mReceiver, filter);
IntentFilter profileFilter = new IntentFilter();
profileFilter.addAction(ContactsContract.Intents.ACTION_PROFILE_CHANGED);
profileFilter.addAction(Intent.ACTION_USER_INFO_CHANGED);
mContext.registerReceiverAsUser(mProfileReceiver, UserHandle.ALL, profileFilter,
null, null);
new SettingsObserver(new Handler()).observe();
}
void setBar(PanelBar bar) {
mBar = bar;
}
public void setService(PhoneStatusBar phoneStatusBar) {
mStatusBarService = phoneStatusBar;
}
public PhoneStatusBar getService() {
return mStatusBarService;
}
public void setImeWindowStatus(boolean visible) {
mModel.onImeWindowStatusChanged(visible);
}
void setup(NetworkController networkController, BluetoothController bluetoothController,
BatteryController batteryController, LocationController locationController) {
mBluetoothController = bluetoothController;
setupQuickSettings();
updateWifiDisplayStatus();
updateResources();
if (getCustomUserTiles().contains(SIGNAL_TOGGLE))
networkController.addNetworkSignalChangedCallback(mModel);
if (getCustomUserTiles().contains(BLUETOOTH_TOGGLE))
bluetoothController.addStateChangedCallback(mModel);
if (getCustomUserTiles().contains(BATTERY_TOGGLE))
batteryController.addStateChangedCallback(mModel);
if (getCustomUserTiles().contains(GPS_TOGGLE))
locationController.addStateChangedCallback(mModel);
if (getCustomUserTiles().contains(ROTATE_TOGGLE))
RotationPolicy.registerRotationPolicyListener(mContext, mRotationPolicyListener,
UserHandle.USER_ALL);
}
private void queryForUserInformation() {
Context currentUserContext = null;
UserInfo userInfo = null;
try {
userInfo = ActivityManagerNative.getDefault().getCurrentUser();
currentUserContext = mContext.createPackageContextAsUser("android", 0,
new UserHandle(userInfo.id));
} catch (NameNotFoundException e) {
Log.e(TAG, "Couldn't create user context", e);
throw new RuntimeException(e);
} catch (RemoteException e) {
Log.e(TAG, "Couldn't get user info", e);
}
final int userId = userInfo.id;
final String userName = userInfo.name;
final Context context = currentUserContext;
mUserInfoTask = new AsyncTask<Void, Void, Pair<String, Drawable>>() {
@Override
protected Pair<String, Drawable> doInBackground(Void... params) {
final UserManager um =
(UserManager) mContext.getSystemService(Context.USER_SERVICE);
// Fall back to the UserManager nickname if we can't read the
// name from the local
// profile below.
String name = userName;
Drawable avatar = null;
Bitmap rawAvatar = um.getUserIcon(userId);
if (rawAvatar != null) {
avatar = new BitmapDrawable(mContext.getResources(), rawAvatar);
} else {
avatar = mContext.getResources().getDrawable(R.drawable.ic_qs_default_user);
}
// If it's a single-user device, get the profile name, since the
// nickname is not
// usually valid
if (um.getUsers().size() <= 1) {
// Try and read the display name from the local profile
final Cursor cursor = context.getContentResolver().query(
Profile.CONTENT_URI, new String[] {
Phone._ID, Phone.DISPLAY_NAME
},
null, null, null);
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
name = cursor.getString(cursor.getColumnIndex(Phone.DISPLAY_NAME));
}
} finally {
cursor.close();
}
}
}
return new Pair<String, Drawable>(name, avatar);
}
@Override
protected void onPostExecute(Pair<String, Drawable> result) {
super.onPostExecute(result);
mModel.setUserTileInfo(result.first, result.second);
mUserInfoTask = null;
}
};
mUserInfoTask.execute();
}
private void setupQuickSettings() {
// Setup the tiles that we are going to be showing (including the
// temporary ones)
LayoutInflater inflater = LayoutInflater.from(mContext);
addUserTiles(mContainerView, inflater);
addTemporaryTiles(mContainerView, inflater);
queryForUserInformation();
mTilesSetUp = true;
}
private void startSettingsActivity(String action) {
Intent intent = new Intent(action);
startSettingsActivity(intent);
}
private void startSettingsActivity(Intent intent) {
startSettingsActivity(intent, true);
}
private void startSettingsActivity(Intent intent, boolean onlyProvisioned) {
if (onlyProvisioned && !getService().isDeviceProvisioned())
return;
try {
// Dismiss the lock screen when Settings starts.
ActivityManagerNative.getDefault().dismissKeyguardOnNextActivity();
} catch (RemoteException e) {
}
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
mContext.startActivityAsUser(intent, new UserHandle(UserHandle.USER_CURRENT));
getService().animateCollapsePanels();
}
private QuickSettingsTileView getTile(int tile, ViewGroup parent, LayoutInflater inflater) {
QuickSettingsTileView quick = null;
switch (tile) {
case USER_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_user, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mBar.collapseAllPanels(true);
final UserManager um =
(UserManager) mContext.getSystemService(Context.USER_SERVICE);
if (um.getUsers(true).size() > 1) {
try {
WindowManagerGlobal.getWindowManagerService().lockNow(
LockPatternUtils.USER_SWITCH_LOCK_OPTIONS);
} catch (RemoteException e) {
Log.e(TAG, "Couldn't show user switcher", e);
}
} else {
Intent intent = ContactsContract.QuickContact.composeQuickContactsIntent(
mContext, v, ContactsContract.Profile.CONTENT_URI,
ContactsContract.QuickContact.MODE_LARGE, null);
mContext.startActivityAsUser(intent, new UserHandle(UserHandle.USER_CURRENT));
}
}
});
mModel.addUserTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
UserState us = (UserState) state;
ImageView iv = (ImageView) view.findViewById(R.id.user_imageview);
TextView tv = (TextView) view.findViewById(R.id.user_textview);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
iv.setImageDrawable(us.avatar);
view.setContentDescription(mContext.getString(
R.string.accessibility_quick_settings_user, state.label));
}
});
mDynamicSpannedTiles.add(quick);
break;
case CLOCK_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_time, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("android.intent.action.MAIN");
intent.setComponent(ComponentName.unflattenFromString("com.android.deskclock.AlarmProvider"));
intent.addCategory("android.intent.category.LAUNCHER");
startSettingsActivity(intent);
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(Intent.ACTION_QUICK_CLOCK);
return true;
}
});
mModel.addTimeTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State alarmState) {
+ TextView tv = (TextView) view.findViewById(R.id.clock_textview);
+ tv.setTextSize(1, mTileTextSize);
}
});
mDynamicSpannedTiles.add(quick);
break;
case SIGNAL_TILE:
if (mModel.deviceSupportsTelephony()) {
// Mobile Network state
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_rssi, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
connManager.setMobileDataEnabled(connManager.getMobileDataEnabled() ? false : true);
String strData = connManager.getMobileDataEnabled() ? strDataoff : strDataon;
Toast.makeText(mContext, strData, Toast.LENGTH_SHORT).show();
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Intent intent = new Intent();
intent.setComponent(new ComponentName(
"com.android.settings",
"com.android.settings.Settings$DataUsageSummaryActivity"));
startSettingsActivity(intent);
return true;
}
});
mModel.addRSSITile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
RSSIState rssiState = (RSSIState) state;
ImageView iv = (ImageView) view.findViewById(R.id.rssi_image);
ImageView iov = (ImageView) view.findViewById(R.id.rssi_overlay_image);
TextView tv = (TextView) view.findViewById(R.id.rssi_textview);
iv.setImageResource(rssiState.signalIconId);
if (rssiState.dataTypeIconId > 0) {
iov.setImageResource(rssiState.dataTypeIconId);
} else {
iov.setImageDrawable(null);
}
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
view.setContentDescription(mContext.getResources().getString(
R.string.accessibility_quick_settings_mobile,
rssiState.signalContentDescription, rssiState.dataContentDescription,
state.label));
}
});
}
break;
case BRIGHTNESS_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_brightness, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mBar.collapseAllPanels(true);
showBrightnessDialog();
}
});
mModel.addBrightnessTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.brightness_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
dismissBrightnessDialog(mBrightnessDialogShortTimeout);
}
});
mDynamicSpannedTiles.add(quick);
break;
case SETTINGS_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_settings, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_SETTINGS);
}
});
mModel.addSettingsTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.settings_tileview);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
mDynamicSpannedTiles.add(quick);
break;
case WIFI_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_wifi, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
wifiManager.setWifiEnabled(wifiManager.isWifiEnabled() ? false : true);
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_WIFI_SETTINGS);
return true;
}
});
mModel.addWifiTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
WifiState wifiState = (WifiState) state;
TextView tv = (TextView) view.findViewById(R.id.wifi_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, wifiState.iconId, 0, 0);
tv.setText(wifiState.label);
tv.setTextSize(1, mTileTextSize);
view.setContentDescription(mContext.getString(
R.string.accessibility_quick_settings_wifi,
wifiState.signalContentDescription,
(wifiState.connected) ? wifiState.label : ""));
}
});
break;
case TWOG_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_twog, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
mDataState = Settings.Global.getInt(mContext.getContentResolver(), Settings.Global.PREFERRED_NETWORK_MODE);
} catch (SettingNotFoundException e) {
e.printStackTrace();
}
if (mDataState == PhoneConstants.NT_MODE_GSM_ONLY) {
tm.toggle2G(false);
} else {
tm.toggle2G(true);
}
mModel.refresh2gTile();
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
return true;
}
});
mModel.add2gTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.twog_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case LTE_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_lte, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
mDataState = Settings.Global.getInt(mContext.getContentResolver(), Settings.Global.PREFERRED_NETWORK_MODE);
} catch (SettingNotFoundException e) {
e.printStackTrace();
}
if (mDataState == PhoneConstants.NT_MODE_LTE_CDMA_EVDO || mDataState == PhoneConstants.NT_MODE_GLOBAL) {
tm.toggleLTE(false);
} else {
tm.toggleLTE(true);
}
mModel.refreshLTETile();
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
return true;
}
});
mModel.addLTETile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.lte_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case VIBRATE_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_vibrate, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mAokpTarget.launchAction(mAokpTarget.ACTION_VIB);
mModel.refreshVibrateTile();
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_SOUND_SETTINGS);
return true;
}
});
mModel.addVibrateTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.vibrate_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case SILENT_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_silent, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mAokpTarget.launchAction(mAokpTarget.ACTION_SILENT);
mModel.refreshSilentTile();
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_SOUND_SETTINGS);
return true;
}
});
mModel.addSilentTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.silent_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case TORCH_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_torch, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mAokpTarget.launchAction(mAokpTarget.ACTION_TORCH);
mHandler.postDelayed(delayedRefresh, 1000);
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
// maybe something here?
return true;
}
});
mModel.addTorchTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.torch_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case FCHARGE_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_fcharge, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
updateFastCharge(isFastChargeOn() ? false : true);
mModel.refreshFChargeTile();
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
// What do we put here?
return true;
}
});
mModel.addFChargeTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.fcharge_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case WIFI_TETHER_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_wifi_tether, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mWifiApState = wifiManager.getWifiApState();
if (mWifiApState == WifiManager.WIFI_AP_STATE_DISABLED || mWifiApState == WifiManager.WIFI_AP_STATE_DISABLING) {
changeWifiState(true);
} else {
changeWifiState(false);
}
mHandler.postDelayed(delayedRefresh, 1000);
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
return true;
}
});
mModel.addWifiTetherTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.wifi_tether_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case USB_TETHER_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_usb_tether, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean enabled = updateUsbState() ? false : true;
if (connManager.setUsbTethering(enabled) == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
mHandler.postDelayed(delayedRefresh, 1000);
}
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
return true;
}
});
mModel.addUSBTetherTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.usb_tether_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case SYNC_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_sync, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean enabled = ContentResolver.getMasterSyncAutomatically();
ContentResolver.setMasterSyncAutomatically(enabled ? false : true);
mModel.refreshSyncTile();
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_SYNC_SETTINGS);
return true;
}
});
mModel.addSyncTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.sync_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case NFC_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_nfc, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
NfcAdapter mNfcAdapter = NfcAdapter.getDefaultAdapter(mContext);
boolean enabled = false;
if (mNfcAdapter != null) {
enabled = mNfcAdapter.isEnabled();
}
if (enabled) {
mNfcAdapter.disable();
} else {
mNfcAdapter.enable();
}
mHandler.postDelayed(delayedRefresh, 1000);
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
return true;
}
});
mModel.addNFCTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.nfc_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case ROTATE_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_rotation_lock, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean locked = RotationPolicy.isRotationLocked(mContext);
RotationPolicy.setRotationLock(mContext, !locked);
}
});
mModel.addRotationLockTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.rotation_lock_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case BATTERY_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_battery, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startSettingsActivity(Intent.ACTION_POWER_USAGE_SUMMARY);
}
});
mModel.addBatteryTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
QuickSettingsModel.BatteryState batteryState =
(QuickSettingsModel.BatteryState) state;
TextView tv = (TextView) view.findViewById(R.id.battery_textview);
ImageView iv = (ImageView) view.findViewById(R.id.battery_image);
Drawable d = batteryState.pluggedIn
? mChargingBatteryLevels
: mBatteryLevels;
String t;
if (batteryState.batteryLevel == 100) {
t = mContext.getString(R.string.quick_settings_battery_charged_label);
} else {
t = batteryState.pluggedIn
? mContext.getString(R.string.quick_settings_battery_charging_label,
batteryState.batteryLevel)
: mContext.getString(R.string.status_bar_settings_battery_meter_format,
batteryState.batteryLevel);
}
iv.setImageDrawable(d);
iv.setImageLevel(batteryState.batteryLevel);
tv.setText(t);
tv.setTextSize(1, mTileTextSize);
view.setContentDescription(
mContext.getString(R.string.accessibility_quick_settings_battery, t));
}
});
break;
case AIRPLANE_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_airplane, inflater);
mModel.addAirplaneModeTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.airplane_mode_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
String airplaneState = mContext.getString(
(state.enabled) ? R.string.accessibility_desc_on
: R.string.accessibility_desc_off);
view.setContentDescription(
mContext.getString(R.string.accessibility_quick_settings_airplane, airplaneState));
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case BLUETOOTH_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_bluetooth, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if (adapter.isEnabled()) {
adapter.disable();
} else {
adapter.enable();
}
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_BLUETOOTH_SETTINGS);
return true;
}
});
mModel.addBluetoothTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
BluetoothState bluetoothState = (BluetoothState) state;
TextView tv = (TextView) view.findViewById(R.id.bluetooth_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
Resources r = mContext.getResources();
String label = state.label;
/*
* //TODO: Show connected bluetooth device label
* Set<BluetoothDevice> btDevices =
* mBluetoothController.getBondedBluetoothDevices(); if
* (btDevices.size() == 1) { // Show the name of the
* bluetooth device you are connected to label =
* btDevices.iterator().next().getName(); } else if
* (btDevices.size() > 1) { // Show a generic label
* about the number of bluetooth devices label =
* r.getString(R.string
* .quick_settings_bluetooth_multiple_devices_label,
* btDevices.size()); }
*/
view.setContentDescription(mContext.getString(
R.string.accessibility_quick_settings_bluetooth,
bluetoothState.stateContentDescription));
tv.setText(label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case GPS_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_location, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean gpsEnabled = Settings.Secure.isLocationProviderEnabled(
mContext.getContentResolver(), LocationManager.GPS_PROVIDER);
Settings.Secure.setLocationProviderEnabled(mContext.getContentResolver(),
LocationManager.GPS_PROVIDER, gpsEnabled ? false : true);
TextView tv = (TextView) v.findViewById(R.id.location_textview);
tv.setText(gpsEnabled ? strGPSoff : strGPSon);
tv.setTextSize(1, mTileTextSize);
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
return true;
}
});
mModel.addLocationTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
boolean gpsEnabled = Settings.Secure.isLocationProviderEnabled(
mContext.getContentResolver(), LocationManager.GPS_PROVIDER);
TextView tv = (TextView) view.findViewById(R.id.location_textview);
String newString = state.label;
if ((newString == null) || (newString.equals(""))) {
tv.setText(gpsEnabled ? strGPSon : strGPSoff);
} else {
tv.setText(state.label);
}
tv.setTextSize(1, mTileTextSize);
}
});
break;
case IME_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_ime, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
mBar.collapseAllPanels(true);
Intent intent = new Intent(Settings.ACTION_SHOW_INPUT_METHOD_PICKER);
PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
pendingIntent.send();
} catch (Exception e) {
}
}
});
mModel.addImeTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.ime_textview);
if (state.label != null) {
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
}
});
break;
case SWAGGER_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_swagger, inflater);
+ TextView tv = (TextView) quick.findViewById(R.id.swagger_textview);
+ tv.setTextSize(1, mTileTextSize);
quick.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (tacoToggle) {
TextView tv = (TextView) v.findViewById(R.id.swagger_textview);
tv.setText(R.string.quick_settings_swagger);
tv.setTextSize(1, mTileTextSize);
tv.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_qs_swagger, 0, 0);
tacoSwagger = event.getEventTime();
tacoToggle = false;
} else {
tacoSwagger = event.getEventTime();
}
break;
case MotionEvent.ACTION_UP:
if ((event.getEventTime() - tacoSwagger) > 5000) {
TextView tv = (TextView) v.findViewById(R.id.swagger_textview);
tv.setText(R.string.quick_settings_fbgt);
tv.setTextSize(1, mTileTextSize);
tv.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_qs_fbgt_on, 0, 0);
tacoToggle = true;
}
break;
}
return true;
}
});
break;
}
return quick;
}
private ArrayList<String> getCustomUserTiles() {
ArrayList<String> tiles = new ArrayList<String>();
if (userToggles == null)
return getDefaultTiles();
String[] splitter = userToggles.split("\\" + TOGGLE_PIPE);
for (String toggle : splitter) {
tiles.add(toggle);
}
return tiles;
}
private ArrayList<String> getDefaultTiles() {
ArrayList<String> tiles = new ArrayList<String>();
tiles.add(USER_TOGGLE);
tiles.add(BRIGHTNESS_TOGGLE);
tiles.add(SETTINGS_TOGGLE);
tiles.add(WIFI_TOGGLE);
if (mModel.deviceSupportsTelephony()) {
tiles.add(SIGNAL_TOGGLE);
}
if (mContext.getResources().getBoolean(R.bool.quick_settings_show_rotation_lock)) {
tiles.add(ROTATE_TOGGLE);
}
tiles.add(BATTERY_TOGGLE);
tiles.add(AIRPLANE_TOGGLE);
if (mModel.deviceSupportsBluetooth()) {
tiles.add(BLUETOOTH_TOGGLE);
}
return tiles;
}
private void addUserTiles(ViewGroup parent, LayoutInflater inflater) {
if (parent.getChildCount() > 0)
parent.removeAllViews();
toggles = getCustomUserTiles();
if (mDynamicSpannedTiles.size() > 0)
mDynamicSpannedTiles.clear();
if (!toggles.get(0).equals("")) {
for (String toggle : toggles) {
parent.addView(getTile(getToggleMap().get(toggle), parent, inflater));
}
}
}
private void addTemporaryTiles(final ViewGroup parent, final LayoutInflater inflater) {
// Alarm tile
QuickSettingsTileView alarmTile = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
alarmTile.setContent(R.layout.quick_settings_tile_alarm, inflater);
alarmTile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO: Jump into the alarm application
Intent intent = new Intent();
intent.setComponent(new ComponentName(
"com.android.deskclock",
"com.android.deskclock.AlarmClock"));
startSettingsActivity(intent);
}
});
mModel.addAlarmTile(alarmTile, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State alarmState) {
TextView tv = (TextView) view.findViewById(R.id.alarm_textview);
tv.setText(alarmState.label);
tv.setTextSize(1, mTileTextSize);
view.setVisibility(alarmState.enabled ? View.VISIBLE : View.GONE);
view.setContentDescription(mContext.getString(
R.string.accessibility_quick_settings_alarm, alarmState.label));
}
});
parent.addView(alarmTile);
// Wifi Display
QuickSettingsTileView wifiDisplayTile = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
wifiDisplayTile.setContent(R.layout.quick_settings_tile_wifi_display, inflater);
wifiDisplayTile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_WIFI_DISPLAY_SETTINGS);
}
});
mModel.addWifiDisplayTile(wifiDisplayTile, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.wifi_display_textview);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
view.setVisibility(state.enabled ? View.VISIBLE : View.GONE);
}
});
parent.addView(wifiDisplayTile);
// Bug reports
QuickSettingsTileView bugreportTile = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
bugreportTile.setContent(R.layout.quick_settings_tile_bugreport, inflater);
bugreportTile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mBar.collapseAllPanels(true);
showBugreportDialog();
}
});
mModel.addBugreportTile(bugreportTile, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
view.setVisibility(state.enabled ? View.VISIBLE : View.GONE);
}
});
parent.addView(bugreportTile);
/*
* QuickSettingsTileView mediaTile = (QuickSettingsTileView)
* inflater.inflate(R.layout.quick_settings_tile, parent, false);
* mediaTile.setContent(R.layout.quick_settings_tile_media, inflater);
* parent.addView(mediaTile); QuickSettingsTileView imeTile =
* (QuickSettingsTileView)
* inflater.inflate(R.layout.quick_settings_tile, parent, false);
* imeTile.setContent(R.layout.quick_settings_tile_ime, inflater);
* imeTile.setOnClickListener(new View.OnClickListener() {
* @Override public void onClick(View v) { parent.removeViewAt(0); } });
* parent.addView(imeTile);
*/
}
void updateResources() {
Resources r = mContext.getResources();
// Update the model
mModel.updateResources(getCustomUserTiles());
// Update the User, Time, and Settings tiles spans, and reset everything
// else
int span = r.getInteger(R.integer.quick_settings_user_time_settings_tile_span);
for (QuickSettingsTileView v : mDynamicSpannedTiles) {
v.setColumnSpan(span);
}
((QuickSettingsContainerView) mContainerView).updateResources();
mContainerView.requestLayout();
// Reset the dialog
boolean isBrightnessDialogVisible = false;
if (mBrightnessDialog != null) {
removeAllBrightnessDialogCallbacks();
isBrightnessDialogVisible = mBrightnessDialog.isShowing();
mBrightnessDialog.dismiss();
}
mBrightnessDialog = null;
if (isBrightnessDialogVisible) {
showBrightnessDialog();
}
}
private void removeAllBrightnessDialogCallbacks() {
mHandler.removeCallbacks(mDismissBrightnessDialogRunnable);
}
private Runnable mDismissBrightnessDialogRunnable = new Runnable() {
public void run() {
if (mBrightnessDialog != null && mBrightnessDialog.isShowing()) {
mBrightnessDialog.dismiss();
}
removeAllBrightnessDialogCallbacks();
};
};
private void showBrightnessDialog() {
if (mBrightnessDialog == null) {
mBrightnessDialog = new Dialog(mContext);
mBrightnessDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
mBrightnessDialog.setContentView(R.layout.quick_settings_brightness_dialog);
mBrightnessDialog.setCanceledOnTouchOutside(true);
mBrightnessController = new BrightnessController(mContext,
(ImageView) mBrightnessDialog.findViewById(R.id.brightness_icon),
(ToggleSlider) mBrightnessDialog.findViewById(R.id.brightness_slider));
mBrightnessController.addStateChangedCallback(mModel);
mBrightnessDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
mBrightnessController = null;
}
});
mBrightnessDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
mBrightnessDialog.getWindow().getAttributes().privateFlags |=
WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS;
mBrightnessDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
}
if (!mBrightnessDialog.isShowing()) {
try {
WindowManagerGlobal.getWindowManagerService().dismissKeyguard();
} catch (RemoteException e) {
}
mBrightnessDialog.show();
dismissBrightnessDialog(mBrightnessDialogLongTimeout);
}
}
private void dismissBrightnessDialog(int timeout) {
removeAllBrightnessDialogCallbacks();
if (mBrightnessDialog != null) {
mHandler.postDelayed(mDismissBrightnessDialogRunnable, timeout);
}
}
private void showBugreportDialog() {
final AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setPositiveButton(com.android.internal.R.string.report, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_POSITIVE) {
// Add a little delay before executing, to give the
// dialog a chance to go away before it takes a
// screenshot.
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
try {
ActivityManagerNative.getDefault()
.requestBugReport();
} catch (RemoteException e) {
}
}
}, 500);
}
}
});
builder.setMessage(com.android.internal.R.string.bugreport_message);
builder.setTitle(com.android.internal.R.string.bugreport_title);
builder.setCancelable(true);
final Dialog dialog = builder.create();
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
try {
WindowManagerGlobal.getWindowManagerService().dismissKeyguard();
} catch (RemoteException e) {
}
dialog.show();
}
private void updateWifiDisplayStatus() {
mWifiDisplayStatus = mDisplayManager.getWifiDisplayStatus();
applyWifiDisplayStatus();
}
private void applyWifiDisplayStatus() {
mModel.onWifiDisplayStateChanged(mWifiDisplayStatus);
}
private void applyBluetoothStatus() {
mModel.onBluetoothStateChange(mBluetoothState);
}
void reloadUserInfo() {
if (mUserInfoTask != null) {
mUserInfoTask.cancel(false);
mUserInfoTask = null;
}
if (mTilesSetUp) {
queryForUserInformation();
}
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (DisplayManager.ACTION_WIFI_DISPLAY_STATUS_CHANGED.equals(action)) {
WifiDisplayStatus status = (WifiDisplayStatus) intent.getParcelableExtra(
DisplayManager.EXTRA_WIFI_DISPLAY_STATUS);
mWifiDisplayStatus = status;
applyWifiDisplayStatus();
} else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
BluetoothAdapter.ERROR);
mBluetoothState.enabled = (state == BluetoothAdapter.STATE_ON);
applyBluetoothStatus();
} else if (BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED.equals(action)) {
int status = intent.getIntExtra(BluetoothAdapter.EXTRA_CONNECTION_STATE,
BluetoothAdapter.STATE_DISCONNECTED);
mBluetoothState.connected = (status == BluetoothAdapter.STATE_CONNECTED);
applyBluetoothStatus();
} else if (Intent.ACTION_USER_SWITCHED.equals(action)) {
reloadUserInfo();
}
}
};
private final BroadcastReceiver mProfileReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (ContactsContract.Intents.ACTION_PROFILE_CHANGED.equals(action) ||
Intent.ACTION_USER_INFO_CHANGED.equals(action)) {
try {
final int userId = ActivityManagerNative.getDefault().getCurrentUser().id;
if (getSendingUserId() == userId) {
reloadUserInfo();
}
} catch (RemoteException e) {
Log.e(TAG, "Couldn't get current user id for profile change", e);
}
}
}
};
public boolean isFastChargeOn() {
try {
File fastcharge = new File(FAST_CHARGE_DIR, FAST_CHARGE_FILE);
FileReader reader = new FileReader(fastcharge);
BufferedReader breader = new BufferedReader(reader);
return (breader.readLine().equals("1"));
} catch (IOException e) {
Log.e("FChargeToggle", "Couldn't read fast_charge file");
return false;
}
}
public void updateFastCharge(boolean on) {
try {
File fastcharge = new File(FAST_CHARGE_DIR, FAST_CHARGE_FILE);
FileWriter fwriter = new FileWriter(fastcharge);
BufferedWriter bwriter = new BufferedWriter(fwriter);
bwriter.write(on ? "1" : "0");
bwriter.close();
} catch (IOException e) {
Log.e("FChargeToggle", "Couldn't write fast_charge file");
}
}
private void changeWifiState(final boolean desiredState) {
if (wifiManager == null) {
Log.d("WifiButton", "No wifiManager.");
return;
}
AsyncTask.execute(new Runnable() {
public void run() {
int wifiState = wifiManager.getWifiState();
if (desiredState
&& ((wifiState == WifiManager.WIFI_STATE_ENABLING) || (wifiState == WifiManager.WIFI_STATE_ENABLED))) {
wifiManager.setWifiEnabled(false);
}
wifiManager.setWifiApEnabled(null, desiredState);
return;
}
});
}
public boolean updateUsbState() {
String[] mUsbRegexs = connManager.getTetherableUsbRegexs();
String[] tethered = connManager.getTetheredIfaces();
usbTethered = false;
for (String s : tethered) {
for (String regex : mUsbRegexs) {
if (s.matches(regex)) {
return true;
} else {
return false;
}
}
}
return false;
}
final Runnable delayedRefresh = new Runnable () {
public void run() {
mModel.refreshWifiTetherTile();
mModel.refreshUSBTetherTile();
mModel.refreshNFCTile();
mModel.refreshTorchTile();
}
};
void updateTileTextSize(int colnum) {
// adjust Tile Text Size based on column count
switch (colnum) {
case 5:
mTileTextSize = 8;
break;
case 4:
mTileTextSize = 10;
break;
case 3:
default:
mTileTextSize = 12;
break;
}
}
private void updateSettings() {
ContentResolver resolver = mContext.getContentResolver();
userToggles = Settings.System.getString(resolver, Settings.System.QUICK_TOGGLES);
int columnCount = Settings.System.getInt(resolver, Settings.System.QUICK_TOGGLES_PER_ROW,
mContext.getResources().getInteger(R.integer.quick_settings_num_columns));
((QuickSettingsContainerView) mContainerView).setColumnCount(columnCount);
updateTileTextSize(columnCount);
setupQuickSettings();
updateWifiDisplayStatus();
updateResources();
}
class SettingsObserver extends ContentObserver {
SettingsObserver(Handler handler) {
super(handler);
}
void observe() {
ContentResolver resolver = mContext.getContentResolver();
resolver.registerContentObserver(Settings.System
.getUriFor(Settings.System.QUICK_TOGGLES),
false, this);
resolver.registerContentObserver(Settings.System
.getUriFor(Settings.System.QUICK_TOGGLES_PER_ROW),
false, this);
updateSettings();
}
@Override
public void onChange(boolean selfChange) {
updateSettings();
}
}
}
| false | true | private QuickSettingsTileView getTile(int tile, ViewGroup parent, LayoutInflater inflater) {
QuickSettingsTileView quick = null;
switch (tile) {
case USER_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_user, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mBar.collapseAllPanels(true);
final UserManager um =
(UserManager) mContext.getSystemService(Context.USER_SERVICE);
if (um.getUsers(true).size() > 1) {
try {
WindowManagerGlobal.getWindowManagerService().lockNow(
LockPatternUtils.USER_SWITCH_LOCK_OPTIONS);
} catch (RemoteException e) {
Log.e(TAG, "Couldn't show user switcher", e);
}
} else {
Intent intent = ContactsContract.QuickContact.composeQuickContactsIntent(
mContext, v, ContactsContract.Profile.CONTENT_URI,
ContactsContract.QuickContact.MODE_LARGE, null);
mContext.startActivityAsUser(intent, new UserHandle(UserHandle.USER_CURRENT));
}
}
});
mModel.addUserTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
UserState us = (UserState) state;
ImageView iv = (ImageView) view.findViewById(R.id.user_imageview);
TextView tv = (TextView) view.findViewById(R.id.user_textview);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
iv.setImageDrawable(us.avatar);
view.setContentDescription(mContext.getString(
R.string.accessibility_quick_settings_user, state.label));
}
});
mDynamicSpannedTiles.add(quick);
break;
case CLOCK_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_time, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("android.intent.action.MAIN");
intent.setComponent(ComponentName.unflattenFromString("com.android.deskclock.AlarmProvider"));
intent.addCategory("android.intent.category.LAUNCHER");
startSettingsActivity(intent);
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(Intent.ACTION_QUICK_CLOCK);
return true;
}
});
mModel.addTimeTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State alarmState) {
}
});
mDynamicSpannedTiles.add(quick);
break;
case SIGNAL_TILE:
if (mModel.deviceSupportsTelephony()) {
// Mobile Network state
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_rssi, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
connManager.setMobileDataEnabled(connManager.getMobileDataEnabled() ? false : true);
String strData = connManager.getMobileDataEnabled() ? strDataoff : strDataon;
Toast.makeText(mContext, strData, Toast.LENGTH_SHORT).show();
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Intent intent = new Intent();
intent.setComponent(new ComponentName(
"com.android.settings",
"com.android.settings.Settings$DataUsageSummaryActivity"));
startSettingsActivity(intent);
return true;
}
});
mModel.addRSSITile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
RSSIState rssiState = (RSSIState) state;
ImageView iv = (ImageView) view.findViewById(R.id.rssi_image);
ImageView iov = (ImageView) view.findViewById(R.id.rssi_overlay_image);
TextView tv = (TextView) view.findViewById(R.id.rssi_textview);
iv.setImageResource(rssiState.signalIconId);
if (rssiState.dataTypeIconId > 0) {
iov.setImageResource(rssiState.dataTypeIconId);
} else {
iov.setImageDrawable(null);
}
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
view.setContentDescription(mContext.getResources().getString(
R.string.accessibility_quick_settings_mobile,
rssiState.signalContentDescription, rssiState.dataContentDescription,
state.label));
}
});
}
break;
case BRIGHTNESS_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_brightness, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mBar.collapseAllPanels(true);
showBrightnessDialog();
}
});
mModel.addBrightnessTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.brightness_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
dismissBrightnessDialog(mBrightnessDialogShortTimeout);
}
});
mDynamicSpannedTiles.add(quick);
break;
case SETTINGS_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_settings, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_SETTINGS);
}
});
mModel.addSettingsTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.settings_tileview);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
mDynamicSpannedTiles.add(quick);
break;
case WIFI_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_wifi, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
wifiManager.setWifiEnabled(wifiManager.isWifiEnabled() ? false : true);
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_WIFI_SETTINGS);
return true;
}
});
mModel.addWifiTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
WifiState wifiState = (WifiState) state;
TextView tv = (TextView) view.findViewById(R.id.wifi_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, wifiState.iconId, 0, 0);
tv.setText(wifiState.label);
tv.setTextSize(1, mTileTextSize);
view.setContentDescription(mContext.getString(
R.string.accessibility_quick_settings_wifi,
wifiState.signalContentDescription,
(wifiState.connected) ? wifiState.label : ""));
}
});
break;
case TWOG_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_twog, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
mDataState = Settings.Global.getInt(mContext.getContentResolver(), Settings.Global.PREFERRED_NETWORK_MODE);
} catch (SettingNotFoundException e) {
e.printStackTrace();
}
if (mDataState == PhoneConstants.NT_MODE_GSM_ONLY) {
tm.toggle2G(false);
} else {
tm.toggle2G(true);
}
mModel.refresh2gTile();
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
return true;
}
});
mModel.add2gTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.twog_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case LTE_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_lte, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
mDataState = Settings.Global.getInt(mContext.getContentResolver(), Settings.Global.PREFERRED_NETWORK_MODE);
} catch (SettingNotFoundException e) {
e.printStackTrace();
}
if (mDataState == PhoneConstants.NT_MODE_LTE_CDMA_EVDO || mDataState == PhoneConstants.NT_MODE_GLOBAL) {
tm.toggleLTE(false);
} else {
tm.toggleLTE(true);
}
mModel.refreshLTETile();
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
return true;
}
});
mModel.addLTETile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.lte_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case VIBRATE_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_vibrate, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mAokpTarget.launchAction(mAokpTarget.ACTION_VIB);
mModel.refreshVibrateTile();
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_SOUND_SETTINGS);
return true;
}
});
mModel.addVibrateTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.vibrate_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case SILENT_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_silent, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mAokpTarget.launchAction(mAokpTarget.ACTION_SILENT);
mModel.refreshSilentTile();
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_SOUND_SETTINGS);
return true;
}
});
mModel.addSilentTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.silent_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case TORCH_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_torch, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mAokpTarget.launchAction(mAokpTarget.ACTION_TORCH);
mHandler.postDelayed(delayedRefresh, 1000);
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
// maybe something here?
return true;
}
});
mModel.addTorchTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.torch_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case FCHARGE_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_fcharge, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
updateFastCharge(isFastChargeOn() ? false : true);
mModel.refreshFChargeTile();
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
// What do we put here?
return true;
}
});
mModel.addFChargeTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.fcharge_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case WIFI_TETHER_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_wifi_tether, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mWifiApState = wifiManager.getWifiApState();
if (mWifiApState == WifiManager.WIFI_AP_STATE_DISABLED || mWifiApState == WifiManager.WIFI_AP_STATE_DISABLING) {
changeWifiState(true);
} else {
changeWifiState(false);
}
mHandler.postDelayed(delayedRefresh, 1000);
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
return true;
}
});
mModel.addWifiTetherTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.wifi_tether_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case USB_TETHER_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_usb_tether, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean enabled = updateUsbState() ? false : true;
if (connManager.setUsbTethering(enabled) == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
mHandler.postDelayed(delayedRefresh, 1000);
}
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
return true;
}
});
mModel.addUSBTetherTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.usb_tether_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case SYNC_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_sync, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean enabled = ContentResolver.getMasterSyncAutomatically();
ContentResolver.setMasterSyncAutomatically(enabled ? false : true);
mModel.refreshSyncTile();
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_SYNC_SETTINGS);
return true;
}
});
mModel.addSyncTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.sync_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case NFC_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_nfc, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
NfcAdapter mNfcAdapter = NfcAdapter.getDefaultAdapter(mContext);
boolean enabled = false;
if (mNfcAdapter != null) {
enabled = mNfcAdapter.isEnabled();
}
if (enabled) {
mNfcAdapter.disable();
} else {
mNfcAdapter.enable();
}
mHandler.postDelayed(delayedRefresh, 1000);
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
return true;
}
});
mModel.addNFCTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.nfc_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case ROTATE_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_rotation_lock, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean locked = RotationPolicy.isRotationLocked(mContext);
RotationPolicy.setRotationLock(mContext, !locked);
}
});
mModel.addRotationLockTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.rotation_lock_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case BATTERY_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_battery, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startSettingsActivity(Intent.ACTION_POWER_USAGE_SUMMARY);
}
});
mModel.addBatteryTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
QuickSettingsModel.BatteryState batteryState =
(QuickSettingsModel.BatteryState) state;
TextView tv = (TextView) view.findViewById(R.id.battery_textview);
ImageView iv = (ImageView) view.findViewById(R.id.battery_image);
Drawable d = batteryState.pluggedIn
? mChargingBatteryLevels
: mBatteryLevels;
String t;
if (batteryState.batteryLevel == 100) {
t = mContext.getString(R.string.quick_settings_battery_charged_label);
} else {
t = batteryState.pluggedIn
? mContext.getString(R.string.quick_settings_battery_charging_label,
batteryState.batteryLevel)
: mContext.getString(R.string.status_bar_settings_battery_meter_format,
batteryState.batteryLevel);
}
iv.setImageDrawable(d);
iv.setImageLevel(batteryState.batteryLevel);
tv.setText(t);
tv.setTextSize(1, mTileTextSize);
view.setContentDescription(
mContext.getString(R.string.accessibility_quick_settings_battery, t));
}
});
break;
case AIRPLANE_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_airplane, inflater);
mModel.addAirplaneModeTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.airplane_mode_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
String airplaneState = mContext.getString(
(state.enabled) ? R.string.accessibility_desc_on
: R.string.accessibility_desc_off);
view.setContentDescription(
mContext.getString(R.string.accessibility_quick_settings_airplane, airplaneState));
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case BLUETOOTH_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_bluetooth, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if (adapter.isEnabled()) {
adapter.disable();
} else {
adapter.enable();
}
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_BLUETOOTH_SETTINGS);
return true;
}
});
mModel.addBluetoothTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
BluetoothState bluetoothState = (BluetoothState) state;
TextView tv = (TextView) view.findViewById(R.id.bluetooth_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
Resources r = mContext.getResources();
String label = state.label;
/*
* //TODO: Show connected bluetooth device label
* Set<BluetoothDevice> btDevices =
* mBluetoothController.getBondedBluetoothDevices(); if
* (btDevices.size() == 1) { // Show the name of the
* bluetooth device you are connected to label =
* btDevices.iterator().next().getName(); } else if
* (btDevices.size() > 1) { // Show a generic label
* about the number of bluetooth devices label =
* r.getString(R.string
* .quick_settings_bluetooth_multiple_devices_label,
* btDevices.size()); }
*/
view.setContentDescription(mContext.getString(
R.string.accessibility_quick_settings_bluetooth,
bluetoothState.stateContentDescription));
tv.setText(label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case GPS_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_location, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean gpsEnabled = Settings.Secure.isLocationProviderEnabled(
mContext.getContentResolver(), LocationManager.GPS_PROVIDER);
Settings.Secure.setLocationProviderEnabled(mContext.getContentResolver(),
LocationManager.GPS_PROVIDER, gpsEnabled ? false : true);
TextView tv = (TextView) v.findViewById(R.id.location_textview);
tv.setText(gpsEnabled ? strGPSoff : strGPSon);
tv.setTextSize(1, mTileTextSize);
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
return true;
}
});
mModel.addLocationTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
boolean gpsEnabled = Settings.Secure.isLocationProviderEnabled(
mContext.getContentResolver(), LocationManager.GPS_PROVIDER);
TextView tv = (TextView) view.findViewById(R.id.location_textview);
String newString = state.label;
if ((newString == null) || (newString.equals(""))) {
tv.setText(gpsEnabled ? strGPSon : strGPSoff);
} else {
tv.setText(state.label);
}
tv.setTextSize(1, mTileTextSize);
}
});
break;
case IME_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_ime, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
mBar.collapseAllPanels(true);
Intent intent = new Intent(Settings.ACTION_SHOW_INPUT_METHOD_PICKER);
PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
pendingIntent.send();
} catch (Exception e) {
}
}
});
mModel.addImeTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.ime_textview);
if (state.label != null) {
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
}
});
break;
case SWAGGER_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_swagger, inflater);
quick.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (tacoToggle) {
TextView tv = (TextView) v.findViewById(R.id.swagger_textview);
tv.setText(R.string.quick_settings_swagger);
tv.setTextSize(1, mTileTextSize);
tv.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_qs_swagger, 0, 0);
tacoSwagger = event.getEventTime();
tacoToggle = false;
} else {
tacoSwagger = event.getEventTime();
}
break;
case MotionEvent.ACTION_UP:
if ((event.getEventTime() - tacoSwagger) > 5000) {
TextView tv = (TextView) v.findViewById(R.id.swagger_textview);
tv.setText(R.string.quick_settings_fbgt);
tv.setTextSize(1, mTileTextSize);
tv.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_qs_fbgt_on, 0, 0);
tacoToggle = true;
}
break;
}
return true;
}
});
break;
}
return quick;
}
| private QuickSettingsTileView getTile(int tile, ViewGroup parent, LayoutInflater inflater) {
QuickSettingsTileView quick = null;
switch (tile) {
case USER_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_user, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mBar.collapseAllPanels(true);
final UserManager um =
(UserManager) mContext.getSystemService(Context.USER_SERVICE);
if (um.getUsers(true).size() > 1) {
try {
WindowManagerGlobal.getWindowManagerService().lockNow(
LockPatternUtils.USER_SWITCH_LOCK_OPTIONS);
} catch (RemoteException e) {
Log.e(TAG, "Couldn't show user switcher", e);
}
} else {
Intent intent = ContactsContract.QuickContact.composeQuickContactsIntent(
mContext, v, ContactsContract.Profile.CONTENT_URI,
ContactsContract.QuickContact.MODE_LARGE, null);
mContext.startActivityAsUser(intent, new UserHandle(UserHandle.USER_CURRENT));
}
}
});
mModel.addUserTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
UserState us = (UserState) state;
ImageView iv = (ImageView) view.findViewById(R.id.user_imageview);
TextView tv = (TextView) view.findViewById(R.id.user_textview);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
iv.setImageDrawable(us.avatar);
view.setContentDescription(mContext.getString(
R.string.accessibility_quick_settings_user, state.label));
}
});
mDynamicSpannedTiles.add(quick);
break;
case CLOCK_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_time, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("android.intent.action.MAIN");
intent.setComponent(ComponentName.unflattenFromString("com.android.deskclock.AlarmProvider"));
intent.addCategory("android.intent.category.LAUNCHER");
startSettingsActivity(intent);
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(Intent.ACTION_QUICK_CLOCK);
return true;
}
});
mModel.addTimeTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State alarmState) {
TextView tv = (TextView) view.findViewById(R.id.clock_textview);
tv.setTextSize(1, mTileTextSize);
}
});
mDynamicSpannedTiles.add(quick);
break;
case SIGNAL_TILE:
if (mModel.deviceSupportsTelephony()) {
// Mobile Network state
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_rssi, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
connManager.setMobileDataEnabled(connManager.getMobileDataEnabled() ? false : true);
String strData = connManager.getMobileDataEnabled() ? strDataoff : strDataon;
Toast.makeText(mContext, strData, Toast.LENGTH_SHORT).show();
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Intent intent = new Intent();
intent.setComponent(new ComponentName(
"com.android.settings",
"com.android.settings.Settings$DataUsageSummaryActivity"));
startSettingsActivity(intent);
return true;
}
});
mModel.addRSSITile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
RSSIState rssiState = (RSSIState) state;
ImageView iv = (ImageView) view.findViewById(R.id.rssi_image);
ImageView iov = (ImageView) view.findViewById(R.id.rssi_overlay_image);
TextView tv = (TextView) view.findViewById(R.id.rssi_textview);
iv.setImageResource(rssiState.signalIconId);
if (rssiState.dataTypeIconId > 0) {
iov.setImageResource(rssiState.dataTypeIconId);
} else {
iov.setImageDrawable(null);
}
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
view.setContentDescription(mContext.getResources().getString(
R.string.accessibility_quick_settings_mobile,
rssiState.signalContentDescription, rssiState.dataContentDescription,
state.label));
}
});
}
break;
case BRIGHTNESS_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_brightness, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mBar.collapseAllPanels(true);
showBrightnessDialog();
}
});
mModel.addBrightnessTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.brightness_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
dismissBrightnessDialog(mBrightnessDialogShortTimeout);
}
});
mDynamicSpannedTiles.add(quick);
break;
case SETTINGS_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_settings, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_SETTINGS);
}
});
mModel.addSettingsTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.settings_tileview);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
mDynamicSpannedTiles.add(quick);
break;
case WIFI_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_wifi, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
wifiManager.setWifiEnabled(wifiManager.isWifiEnabled() ? false : true);
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_WIFI_SETTINGS);
return true;
}
});
mModel.addWifiTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
WifiState wifiState = (WifiState) state;
TextView tv = (TextView) view.findViewById(R.id.wifi_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, wifiState.iconId, 0, 0);
tv.setText(wifiState.label);
tv.setTextSize(1, mTileTextSize);
view.setContentDescription(mContext.getString(
R.string.accessibility_quick_settings_wifi,
wifiState.signalContentDescription,
(wifiState.connected) ? wifiState.label : ""));
}
});
break;
case TWOG_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_twog, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
mDataState = Settings.Global.getInt(mContext.getContentResolver(), Settings.Global.PREFERRED_NETWORK_MODE);
} catch (SettingNotFoundException e) {
e.printStackTrace();
}
if (mDataState == PhoneConstants.NT_MODE_GSM_ONLY) {
tm.toggle2G(false);
} else {
tm.toggle2G(true);
}
mModel.refresh2gTile();
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
return true;
}
});
mModel.add2gTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.twog_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case LTE_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_lte, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
mDataState = Settings.Global.getInt(mContext.getContentResolver(), Settings.Global.PREFERRED_NETWORK_MODE);
} catch (SettingNotFoundException e) {
e.printStackTrace();
}
if (mDataState == PhoneConstants.NT_MODE_LTE_CDMA_EVDO || mDataState == PhoneConstants.NT_MODE_GLOBAL) {
tm.toggleLTE(false);
} else {
tm.toggleLTE(true);
}
mModel.refreshLTETile();
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
return true;
}
});
mModel.addLTETile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.lte_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case VIBRATE_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_vibrate, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mAokpTarget.launchAction(mAokpTarget.ACTION_VIB);
mModel.refreshVibrateTile();
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_SOUND_SETTINGS);
return true;
}
});
mModel.addVibrateTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.vibrate_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case SILENT_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_silent, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mAokpTarget.launchAction(mAokpTarget.ACTION_SILENT);
mModel.refreshSilentTile();
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_SOUND_SETTINGS);
return true;
}
});
mModel.addSilentTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.silent_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case TORCH_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_torch, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mAokpTarget.launchAction(mAokpTarget.ACTION_TORCH);
mHandler.postDelayed(delayedRefresh, 1000);
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
// maybe something here?
return true;
}
});
mModel.addTorchTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.torch_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case FCHARGE_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_fcharge, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
updateFastCharge(isFastChargeOn() ? false : true);
mModel.refreshFChargeTile();
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
// What do we put here?
return true;
}
});
mModel.addFChargeTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.fcharge_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case WIFI_TETHER_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_wifi_tether, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mWifiApState = wifiManager.getWifiApState();
if (mWifiApState == WifiManager.WIFI_AP_STATE_DISABLED || mWifiApState == WifiManager.WIFI_AP_STATE_DISABLING) {
changeWifiState(true);
} else {
changeWifiState(false);
}
mHandler.postDelayed(delayedRefresh, 1000);
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
return true;
}
});
mModel.addWifiTetherTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.wifi_tether_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case USB_TETHER_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_usb_tether, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean enabled = updateUsbState() ? false : true;
if (connManager.setUsbTethering(enabled) == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
mHandler.postDelayed(delayedRefresh, 1000);
}
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
return true;
}
});
mModel.addUSBTetherTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.usb_tether_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case SYNC_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_sync, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean enabled = ContentResolver.getMasterSyncAutomatically();
ContentResolver.setMasterSyncAutomatically(enabled ? false : true);
mModel.refreshSyncTile();
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_SYNC_SETTINGS);
return true;
}
});
mModel.addSyncTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.sync_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case NFC_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_nfc, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
NfcAdapter mNfcAdapter = NfcAdapter.getDefaultAdapter(mContext);
boolean enabled = false;
if (mNfcAdapter != null) {
enabled = mNfcAdapter.isEnabled();
}
if (enabled) {
mNfcAdapter.disable();
} else {
mNfcAdapter.enable();
}
mHandler.postDelayed(delayedRefresh, 1000);
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
return true;
}
});
mModel.addNFCTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.nfc_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case ROTATE_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_rotation_lock, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean locked = RotationPolicy.isRotationLocked(mContext);
RotationPolicy.setRotationLock(mContext, !locked);
}
});
mModel.addRotationLockTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.rotation_lock_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case BATTERY_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_battery, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startSettingsActivity(Intent.ACTION_POWER_USAGE_SUMMARY);
}
});
mModel.addBatteryTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
QuickSettingsModel.BatteryState batteryState =
(QuickSettingsModel.BatteryState) state;
TextView tv = (TextView) view.findViewById(R.id.battery_textview);
ImageView iv = (ImageView) view.findViewById(R.id.battery_image);
Drawable d = batteryState.pluggedIn
? mChargingBatteryLevels
: mBatteryLevels;
String t;
if (batteryState.batteryLevel == 100) {
t = mContext.getString(R.string.quick_settings_battery_charged_label);
} else {
t = batteryState.pluggedIn
? mContext.getString(R.string.quick_settings_battery_charging_label,
batteryState.batteryLevel)
: mContext.getString(R.string.status_bar_settings_battery_meter_format,
batteryState.batteryLevel);
}
iv.setImageDrawable(d);
iv.setImageLevel(batteryState.batteryLevel);
tv.setText(t);
tv.setTextSize(1, mTileTextSize);
view.setContentDescription(
mContext.getString(R.string.accessibility_quick_settings_battery, t));
}
});
break;
case AIRPLANE_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_airplane, inflater);
mModel.addAirplaneModeTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.airplane_mode_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
String airplaneState = mContext.getString(
(state.enabled) ? R.string.accessibility_desc_on
: R.string.accessibility_desc_off);
view.setContentDescription(
mContext.getString(R.string.accessibility_quick_settings_airplane, airplaneState));
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case BLUETOOTH_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_bluetooth, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if (adapter.isEnabled()) {
adapter.disable();
} else {
adapter.enable();
}
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_BLUETOOTH_SETTINGS);
return true;
}
});
mModel.addBluetoothTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
BluetoothState bluetoothState = (BluetoothState) state;
TextView tv = (TextView) view.findViewById(R.id.bluetooth_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
Resources r = mContext.getResources();
String label = state.label;
/*
* //TODO: Show connected bluetooth device label
* Set<BluetoothDevice> btDevices =
* mBluetoothController.getBondedBluetoothDevices(); if
* (btDevices.size() == 1) { // Show the name of the
* bluetooth device you are connected to label =
* btDevices.iterator().next().getName(); } else if
* (btDevices.size() > 1) { // Show a generic label
* about the number of bluetooth devices label =
* r.getString(R.string
* .quick_settings_bluetooth_multiple_devices_label,
* btDevices.size()); }
*/
view.setContentDescription(mContext.getString(
R.string.accessibility_quick_settings_bluetooth,
bluetoothState.stateContentDescription));
tv.setText(label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case GPS_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_location, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean gpsEnabled = Settings.Secure.isLocationProviderEnabled(
mContext.getContentResolver(), LocationManager.GPS_PROVIDER);
Settings.Secure.setLocationProviderEnabled(mContext.getContentResolver(),
LocationManager.GPS_PROVIDER, gpsEnabled ? false : true);
TextView tv = (TextView) v.findViewById(R.id.location_textview);
tv.setText(gpsEnabled ? strGPSoff : strGPSon);
tv.setTextSize(1, mTileTextSize);
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
return true;
}
});
mModel.addLocationTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
boolean gpsEnabled = Settings.Secure.isLocationProviderEnabled(
mContext.getContentResolver(), LocationManager.GPS_PROVIDER);
TextView tv = (TextView) view.findViewById(R.id.location_textview);
String newString = state.label;
if ((newString == null) || (newString.equals(""))) {
tv.setText(gpsEnabled ? strGPSon : strGPSoff);
} else {
tv.setText(state.label);
}
tv.setTextSize(1, mTileTextSize);
}
});
break;
case IME_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_ime, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
mBar.collapseAllPanels(true);
Intent intent = new Intent(Settings.ACTION_SHOW_INPUT_METHOD_PICKER);
PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
pendingIntent.send();
} catch (Exception e) {
}
}
});
mModel.addImeTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.ime_textview);
if (state.label != null) {
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
}
});
break;
case SWAGGER_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_swagger, inflater);
TextView tv = (TextView) quick.findViewById(R.id.swagger_textview);
tv.setTextSize(1, mTileTextSize);
quick.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (tacoToggle) {
TextView tv = (TextView) v.findViewById(R.id.swagger_textview);
tv.setText(R.string.quick_settings_swagger);
tv.setTextSize(1, mTileTextSize);
tv.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_qs_swagger, 0, 0);
tacoSwagger = event.getEventTime();
tacoToggle = false;
} else {
tacoSwagger = event.getEventTime();
}
break;
case MotionEvent.ACTION_UP:
if ((event.getEventTime() - tacoSwagger) > 5000) {
TextView tv = (TextView) v.findViewById(R.id.swagger_textview);
tv.setText(R.string.quick_settings_fbgt);
tv.setTextSize(1, mTileTextSize);
tv.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_qs_fbgt_on, 0, 0);
tacoToggle = true;
}
break;
}
return true;
}
});
break;
}
return quick;
}
|
diff --git a/src/main/java/at/ac/tuwien/sepm/ui/startUp/First.java b/src/main/java/at/ac/tuwien/sepm/ui/startUp/First.java
index 6c0eb65..9fbf0f4 100644
--- a/src/main/java/at/ac/tuwien/sepm/ui/startUp/First.java
+++ b/src/main/java/at/ac/tuwien/sepm/ui/startUp/First.java
@@ -1,178 +1,178 @@
package at.ac.tuwien.sepm.ui.startUp;
import at.ac.tuwien.sepm.entity.Curriculum;
import at.ac.tuwien.sepm.entity.Module;
import at.ac.tuwien.sepm.service.EscapeException;
import at.ac.tuwien.sepm.service.ServiceException;
import at.ac.tuwien.sepm.ui.SmallInfoPanel;
import at.ac.tuwien.sepm.ui.template.PanelTube;
import at.ac.tuwien.sepm.ui.template.WideComboBox;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.LinkedList;
import java.util.List;
/**
* Author: Georg Plaz
*/
public class First extends StartRowPanel {
private static Logger logger = LogManager.getLogger(First.class);
private JTextField tissUsername = new JTextField();
private JPasswordField tissPassword = new JPasswordField();
private WideComboBox studyDrop;
private JButton progressFurther;
private JProgressBar progressBar = new JProgressBar();
private boolean confirmed = false;
//academicPrograms.setMinimumSize(new Dimension((int)this.getBounds().getWidth()-145, 20));
public First(double width, double height,ViewStartUp parent) {
super(width, height,parent);
subInit();
}
public void subInit(){
- tissUsername.setText(getStartUp().propertyService.getProperty("user.user",""));
- tissPassword.setText(getStartUp().propertyService.getProperty("user.password",""));
+ tissUsername.setText(getStartUp().propertyService.getProperty("tiss.user",""));
+ tissPassword.setText(getStartUp().propertyService.getProperty("tiss.password",""));
studyDrop = new WideComboBox();
studyDrop.addItem(new CurriculumContainer());
try {
for(Curriculum c : getStartUp().lvaFetcherService.getAcademicPrograms()){
if (((c.getName().startsWith("Bachelor")) || (c.getName().startsWith("Master"))) && ((c.getName().contains("nformatik") || c.getName().contains("Software")) && !c.getName().contains("Geod"))){
studyDrop.addItem(new CurriculumContainer(c));
}
}
} catch (ServiceException e) {
logger.error(e);
PanelTube.backgroundPanel.viewInfoText("Es ist ein Fehler beim Lesen der Daten aufgetreten.",SmallInfoPanel.Error);
}
studyDrop.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if(studyDrop.getSelectedIndex()==0){
progressFurther.setText("Weiter");
}else{
progressFurther.setText("Importieren");
}
}
});
progressFurther = new JButton("weiter");
progressFurther.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try{
if(studyDrop.getSelectedIndex()== 0 && !confirmed){
PanelTube.backgroundPanel.viewInfoText("Wollen sie wirklich fortfahren, ohne ein Studium zu importieren?", SmallInfoPanel.Warning);
confirmed=true;
throw new EscapeException();
}
int un = tissUsername.getText().length();
int pw = tissPassword.getPassword().length;
if(un>0 && pw>0){
getStartUp().propertyService.setProperty("tiss.user",tissUsername.getText());
getStartUp().propertyService.setProperty("tiss.password",new String(tissPassword.getPassword()));
}else if((un==0)!=(pw==0)){
PanelTube.backgroundPanel.viewInfoText("Die TISS-Daten sind ungültig!", SmallInfoPanel.Warning);
throw new EscapeException();
}
if(studyDrop.getSelectedIndex()==0){
getStartUp().next();
}else{
setWaiting(true);
PanelTube.backgroundPanel.viewInfoText("Studium wird geladen. Bitte um etwas Geduld.", SmallInfoPanel.Info);
FetcherTask task = new FetcherTask();
task.execute();
}
}catch(EscapeException ignore){ }
}
});
allLabels = new LinkedList<JComponent>();
- addText("Hallo!\n\nHerzlich willkommen im sTUdiumsmanager!.\nDies ist ein kurzer Startup-Wizard, " +
+ addText("Hallo!\n\nHerzlich willkommen im sTUdiumsmanager!\nDies ist ein kurzer Startup-Wizard, " +
"der dir die wichtigsten Dinge im Programm kurz erklärt. Damit das Programm richtig funktioniert," +
"brauchen wir ein paar Informationen, die du auch gleich hier eingeben kannst!",true);
addText("Alle Daten werden nur lokal gespeichert und eventuell zum Anmelden bei " +
"dem jeweiligen Dienst genutzt.",true);
addText("Wenn du dich automatisch für Prüfungen anmelden lassen willst, musst du hier deine " +
"Tiss-Zugangsdaten eingeben. Du kannst sie aber auch jederzeit in den Einstellungen " +
"setzen oder ändern.\n",true);
addRow(new JTextArea("TISS-Username"), tissUsername,true);
addRow(new JTextArea("TISS-Passwort"), tissPassword,true);
addText("\n\nUm dir LVAs für dein aktuelles Semester einzutragen (was du für alle Funktionen in dieser App brauchst), " +
"musst du vorher ein Studium importieren. Wähle hier dein Studium aus. Die Daten werden aus dem TISS ausgelesen." +
"Du kannst auch diesen Schritt auch erst später unter Lehrangebot -> Importieren " +
"ausführen\n.",false);
addRow(new JTextArea("Studium"), studyDrop, false);
addText("", false);
addRow(null, progressFurther, false);
progressBar.setIndeterminate(true);
progressBar.setVisible(false);
addText("",false);
addRow(null, progressBar, false);
logger.info("finished initializing");
}
private void setWaiting(boolean b){
progressFurther.setEnabled(!b);
progressBar.setVisible(b);
tissPassword.setEnabled(!b);
tissUsername.setEnabled(!b);
studyDrop.setEnabled(!b);
}
private class CurriculumContainer{
private Curriculum curriculum;
private CurriculumContainer(Curriculum curriculum){
this.curriculum = curriculum;
}
private CurriculumContainer(){
}
public String toString(){
if(curriculum!=null){
return curriculum.getName();
}
return "Kein Studium augewählt";
}
public Curriculum get(){
return curriculum;
}
}
private class FetcherTask extends SwingWorker<Void, Void> {
@Override
protected Void doInBackground() throws Exception {
try {
Curriculum curriculum = ((CurriculumContainer) studyDrop.getSelectedItem()).get();
//DefaultMutableTreeNode top = new DefaultMutableTreeNode(new CurriculumSelectItem(curriculum));
List<Module> currentModules = getStartUp().lvaFetcherService.getModules(curriculum.getStudyNumber(), true);
for(Module m : currentModules) {
getStartUp().moduleService.create(m);
}
PanelTube.backgroundPanel.viewInfoText("Gratuliere, das Studium wurde fertig geladen und importiert!", SmallInfoPanel.Success);
getStartUp().next();
} catch (ServiceException e) {
logger.info("couldn't load LVAs", e);
PanelTube.backgroundPanel.viewInfoText("Die LVAs konnten leider nicht geladen werden.", SmallInfoPanel.Error);
}
setWaiting(false);
//setWaiting(false);
return null;
}
}
}
| false | true | public void subInit(){
tissUsername.setText(getStartUp().propertyService.getProperty("user.user",""));
tissPassword.setText(getStartUp().propertyService.getProperty("user.password",""));
studyDrop = new WideComboBox();
studyDrop.addItem(new CurriculumContainer());
try {
for(Curriculum c : getStartUp().lvaFetcherService.getAcademicPrograms()){
if (((c.getName().startsWith("Bachelor")) || (c.getName().startsWith("Master"))) && ((c.getName().contains("nformatik") || c.getName().contains("Software")) && !c.getName().contains("Geod"))){
studyDrop.addItem(new CurriculumContainer(c));
}
}
} catch (ServiceException e) {
logger.error(e);
PanelTube.backgroundPanel.viewInfoText("Es ist ein Fehler beim Lesen der Daten aufgetreten.",SmallInfoPanel.Error);
}
studyDrop.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if(studyDrop.getSelectedIndex()==0){
progressFurther.setText("Weiter");
}else{
progressFurther.setText("Importieren");
}
}
});
progressFurther = new JButton("weiter");
progressFurther.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try{
if(studyDrop.getSelectedIndex()== 0 && !confirmed){
PanelTube.backgroundPanel.viewInfoText("Wollen sie wirklich fortfahren, ohne ein Studium zu importieren?", SmallInfoPanel.Warning);
confirmed=true;
throw new EscapeException();
}
int un = tissUsername.getText().length();
int pw = tissPassword.getPassword().length;
if(un>0 && pw>0){
getStartUp().propertyService.setProperty("tiss.user",tissUsername.getText());
getStartUp().propertyService.setProperty("tiss.password",new String(tissPassword.getPassword()));
}else if((un==0)!=(pw==0)){
PanelTube.backgroundPanel.viewInfoText("Die TISS-Daten sind ungültig!", SmallInfoPanel.Warning);
throw new EscapeException();
}
if(studyDrop.getSelectedIndex()==0){
getStartUp().next();
}else{
setWaiting(true);
PanelTube.backgroundPanel.viewInfoText("Studium wird geladen. Bitte um etwas Geduld.", SmallInfoPanel.Info);
FetcherTask task = new FetcherTask();
task.execute();
}
}catch(EscapeException ignore){ }
}
});
allLabels = new LinkedList<JComponent>();
addText("Hallo!\n\nHerzlich willkommen im sTUdiumsmanager!.\nDies ist ein kurzer Startup-Wizard, " +
"der dir die wichtigsten Dinge im Programm kurz erklärt. Damit das Programm richtig funktioniert," +
"brauchen wir ein paar Informationen, die du auch gleich hier eingeben kannst!",true);
addText("Alle Daten werden nur lokal gespeichert und eventuell zum Anmelden bei " +
"dem jeweiligen Dienst genutzt.",true);
addText("Wenn du dich automatisch für Prüfungen anmelden lassen willst, musst du hier deine " +
"Tiss-Zugangsdaten eingeben. Du kannst sie aber auch jederzeit in den Einstellungen " +
"setzen oder ändern.\n",true);
addRow(new JTextArea("TISS-Username"), tissUsername,true);
addRow(new JTextArea("TISS-Passwort"), tissPassword,true);
addText("\n\nUm dir LVAs für dein aktuelles Semester einzutragen (was du für alle Funktionen in dieser App brauchst), " +
"musst du vorher ein Studium importieren. Wähle hier dein Studium aus. Die Daten werden aus dem TISS ausgelesen." +
"Du kannst auch diesen Schritt auch erst später unter Lehrangebot -> Importieren " +
"ausführen\n.",false);
addRow(new JTextArea("Studium"), studyDrop, false);
addText("", false);
addRow(null, progressFurther, false);
progressBar.setIndeterminate(true);
progressBar.setVisible(false);
addText("",false);
addRow(null, progressBar, false);
logger.info("finished initializing");
}
| public void subInit(){
tissUsername.setText(getStartUp().propertyService.getProperty("tiss.user",""));
tissPassword.setText(getStartUp().propertyService.getProperty("tiss.password",""));
studyDrop = new WideComboBox();
studyDrop.addItem(new CurriculumContainer());
try {
for(Curriculum c : getStartUp().lvaFetcherService.getAcademicPrograms()){
if (((c.getName().startsWith("Bachelor")) || (c.getName().startsWith("Master"))) && ((c.getName().contains("nformatik") || c.getName().contains("Software")) && !c.getName().contains("Geod"))){
studyDrop.addItem(new CurriculumContainer(c));
}
}
} catch (ServiceException e) {
logger.error(e);
PanelTube.backgroundPanel.viewInfoText("Es ist ein Fehler beim Lesen der Daten aufgetreten.",SmallInfoPanel.Error);
}
studyDrop.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if(studyDrop.getSelectedIndex()==0){
progressFurther.setText("Weiter");
}else{
progressFurther.setText("Importieren");
}
}
});
progressFurther = new JButton("weiter");
progressFurther.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try{
if(studyDrop.getSelectedIndex()== 0 && !confirmed){
PanelTube.backgroundPanel.viewInfoText("Wollen sie wirklich fortfahren, ohne ein Studium zu importieren?", SmallInfoPanel.Warning);
confirmed=true;
throw new EscapeException();
}
int un = tissUsername.getText().length();
int pw = tissPassword.getPassword().length;
if(un>0 && pw>0){
getStartUp().propertyService.setProperty("tiss.user",tissUsername.getText());
getStartUp().propertyService.setProperty("tiss.password",new String(tissPassword.getPassword()));
}else if((un==0)!=(pw==0)){
PanelTube.backgroundPanel.viewInfoText("Die TISS-Daten sind ungültig!", SmallInfoPanel.Warning);
throw new EscapeException();
}
if(studyDrop.getSelectedIndex()==0){
getStartUp().next();
}else{
setWaiting(true);
PanelTube.backgroundPanel.viewInfoText("Studium wird geladen. Bitte um etwas Geduld.", SmallInfoPanel.Info);
FetcherTask task = new FetcherTask();
task.execute();
}
}catch(EscapeException ignore){ }
}
});
allLabels = new LinkedList<JComponent>();
addText("Hallo!\n\nHerzlich willkommen im sTUdiumsmanager!\nDies ist ein kurzer Startup-Wizard, " +
"der dir die wichtigsten Dinge im Programm kurz erklärt. Damit das Programm richtig funktioniert," +
"brauchen wir ein paar Informationen, die du auch gleich hier eingeben kannst!",true);
addText("Alle Daten werden nur lokal gespeichert und eventuell zum Anmelden bei " +
"dem jeweiligen Dienst genutzt.",true);
addText("Wenn du dich automatisch für Prüfungen anmelden lassen willst, musst du hier deine " +
"Tiss-Zugangsdaten eingeben. Du kannst sie aber auch jederzeit in den Einstellungen " +
"setzen oder ändern.\n",true);
addRow(new JTextArea("TISS-Username"), tissUsername,true);
addRow(new JTextArea("TISS-Passwort"), tissPassword,true);
addText("\n\nUm dir LVAs für dein aktuelles Semester einzutragen (was du für alle Funktionen in dieser App brauchst), " +
"musst du vorher ein Studium importieren. Wähle hier dein Studium aus. Die Daten werden aus dem TISS ausgelesen." +
"Du kannst auch diesen Schritt auch erst später unter Lehrangebot -> Importieren " +
"ausführen\n.",false);
addRow(new JTextArea("Studium"), studyDrop, false);
addText("", false);
addRow(null, progressFurther, false);
progressBar.setIndeterminate(true);
progressBar.setVisible(false);
addText("",false);
addRow(null, progressBar, false);
logger.info("finished initializing");
}
|
diff --git a/src/net/armooo/locationlog/LocationActivity.java b/src/net/armooo/locationlog/LocationActivity.java
index 684333e..dc7fabf 100644
--- a/src/net/armooo/locationlog/LocationActivity.java
+++ b/src/net/armooo/locationlog/LocationActivity.java
@@ -1,177 +1,180 @@
package net.armooo.locationlog;
import net.armooo.locationlog.util.LocationDatabase;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class LocationActivity extends Activity implements LocationListener{
public final static String LOCATION_ID = "location_id";
private long location_id;
private EditText name;
private EditText latitude;
private EditText longitude;
private TextView current_latitude;
private TextView current_longitude;
private TextView current_source;
private TextView current_accuracy;
private LocationDatabase db;
private BestLocationProxy best_location_proxy;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db = new LocationDatabase(this);
best_location_proxy = new BestLocationProxy(this);
if (savedInstanceState != null) {
location_id = savedInstanceState.getLong(LOCATION_ID);
}
Intent intent = getIntent();
location_id = intent.getLongExtra(LOCATION_ID, -1);
setContentView(R.layout.location);
name = (EditText) findViewById(R.id.name);
latitude = (EditText) findViewById(R.id.latitude);
longitude = (EditText) findViewById(R.id.longitude);
current_latitude = (TextView) findViewById(R.id.current_latitude);
current_longitude = (TextView) findViewById(R.id.current_longitude);
current_source = (TextView) findViewById(R.id.current_source);
current_accuracy = (TextView) findViewById(R.id.current_accuracy);
updateLocation(best_location_proxy.getLastKnownLocation());
Button set_location = (Button) findViewById(R.id.set_location);
set_location.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
Location l = best_location_proxy.getLastKnownLocation();
+ if (l == null) {
+ return;
+ }
latitude.setText(Double.toString(l.getLatitude()));
longitude.setText(Double.toString(l.getLongitude()));
}
});
Button closeButton = (Button) findViewById(R.id.close_location_window);
closeButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
if (location_id != -1) {
Cursor c = db.getLocation(location_id);
if (c.getCount() != 1) {
finish();
return;
}
c.moveToFirst();
int name_id = c.getColumnIndex(LocationDatabase.FIELD_LOCATIONS_NAME);
int latitude_id = c.getColumnIndex(LocationDatabase.FIELD_LOCATIONS_LATITUDE);
int longitude_id = c.getColumnIndex(LocationDatabase.FIELD_LOCATIONS_LONGITUDE);
name.setText(c.getString(name_id));
latitude.setText(Double.toString(c.getDouble(latitude_id)));
longitude.setText(Double.toString(c.getDouble(longitude_id)));
c.close();
}
}
@Override
protected void onResume() {
super.onResume();
best_location_proxy.requestLocationUpdates(100000, 0, this);
}
@Override
protected void onPause() {
super.onPause();
best_location_proxy.removeUpdates(this);
String s_name = name.getText().toString();
if (s_name.equals("")) {
return;
}
Double d_latitude = null;
String s_latitude = latitude.getText().toString();
if (!s_latitude.equals("")) {
d_latitude = Double.parseDouble(s_latitude);
}
Double d_longitude = null;
String s_longitude = longitude.getText().toString();
if (!s_longitude.equals("")) {
d_longitude = Double.parseDouble(s_longitude);
}
if (location_id != -1) {
db.updateLocation(location_id, s_name, d_latitude, d_longitude);
} else {
location_id = db.createLocation(s_name, d_latitude, d_longitude);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putLong(LOCATION_ID, location_id);
}
private void updateLocation(Location l){
if (l == null){
current_source.setText(R.string.no_provider);
current_latitude.setText(R.string.unavailable);
current_longitude.setText(R.string.unavailable);
current_accuracy.setText(R.string.unavailable);
return;
}
String source;
if (l.getProvider().equals(LocationManager.GPS_PROVIDER)){
source = getString(R.string.gps);
} else if (l.getProvider().equals(LocationManager.NETWORK_PROVIDER)){
source = getString(R.string.cell);
} else {
source = getString(R.string.unknown);
}
current_source.setText(source);
current_latitude.setText(Double.toString(l.getLatitude()));
current_longitude.setText(Double.toString(l.getLongitude()));
current_accuracy.setText(Float.toString(l.getAccuracy()));
}
@Override
public void onLocationChanged(Location location) {
updateLocation(location);
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
| true | true | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db = new LocationDatabase(this);
best_location_proxy = new BestLocationProxy(this);
if (savedInstanceState != null) {
location_id = savedInstanceState.getLong(LOCATION_ID);
}
Intent intent = getIntent();
location_id = intent.getLongExtra(LOCATION_ID, -1);
setContentView(R.layout.location);
name = (EditText) findViewById(R.id.name);
latitude = (EditText) findViewById(R.id.latitude);
longitude = (EditText) findViewById(R.id.longitude);
current_latitude = (TextView) findViewById(R.id.current_latitude);
current_longitude = (TextView) findViewById(R.id.current_longitude);
current_source = (TextView) findViewById(R.id.current_source);
current_accuracy = (TextView) findViewById(R.id.current_accuracy);
updateLocation(best_location_proxy.getLastKnownLocation());
Button set_location = (Button) findViewById(R.id.set_location);
set_location.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
Location l = best_location_proxy.getLastKnownLocation();
latitude.setText(Double.toString(l.getLatitude()));
longitude.setText(Double.toString(l.getLongitude()));
}
});
Button closeButton = (Button) findViewById(R.id.close_location_window);
closeButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
if (location_id != -1) {
Cursor c = db.getLocation(location_id);
if (c.getCount() != 1) {
finish();
return;
}
c.moveToFirst();
int name_id = c.getColumnIndex(LocationDatabase.FIELD_LOCATIONS_NAME);
int latitude_id = c.getColumnIndex(LocationDatabase.FIELD_LOCATIONS_LATITUDE);
int longitude_id = c.getColumnIndex(LocationDatabase.FIELD_LOCATIONS_LONGITUDE);
name.setText(c.getString(name_id));
latitude.setText(Double.toString(c.getDouble(latitude_id)));
longitude.setText(Double.toString(c.getDouble(longitude_id)));
c.close();
}
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db = new LocationDatabase(this);
best_location_proxy = new BestLocationProxy(this);
if (savedInstanceState != null) {
location_id = savedInstanceState.getLong(LOCATION_ID);
}
Intent intent = getIntent();
location_id = intent.getLongExtra(LOCATION_ID, -1);
setContentView(R.layout.location);
name = (EditText) findViewById(R.id.name);
latitude = (EditText) findViewById(R.id.latitude);
longitude = (EditText) findViewById(R.id.longitude);
current_latitude = (TextView) findViewById(R.id.current_latitude);
current_longitude = (TextView) findViewById(R.id.current_longitude);
current_source = (TextView) findViewById(R.id.current_source);
current_accuracy = (TextView) findViewById(R.id.current_accuracy);
updateLocation(best_location_proxy.getLastKnownLocation());
Button set_location = (Button) findViewById(R.id.set_location);
set_location.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
Location l = best_location_proxy.getLastKnownLocation();
if (l == null) {
return;
}
latitude.setText(Double.toString(l.getLatitude()));
longitude.setText(Double.toString(l.getLongitude()));
}
});
Button closeButton = (Button) findViewById(R.id.close_location_window);
closeButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
if (location_id != -1) {
Cursor c = db.getLocation(location_id);
if (c.getCount() != 1) {
finish();
return;
}
c.moveToFirst();
int name_id = c.getColumnIndex(LocationDatabase.FIELD_LOCATIONS_NAME);
int latitude_id = c.getColumnIndex(LocationDatabase.FIELD_LOCATIONS_LATITUDE);
int longitude_id = c.getColumnIndex(LocationDatabase.FIELD_LOCATIONS_LONGITUDE);
name.setText(c.getString(name_id));
latitude.setText(Double.toString(c.getDouble(latitude_id)));
longitude.setText(Double.toString(c.getDouble(longitude_id)));
c.close();
}
}
|
diff --git a/core/src/main/java/org/mule/galaxy/config/CustomListenersBeanDefinitionParser.java b/core/src/main/java/org/mule/galaxy/config/CustomListenersBeanDefinitionParser.java
index b660492f..171b8fdf 100644
--- a/core/src/main/java/org/mule/galaxy/config/CustomListenersBeanDefinitionParser.java
+++ b/core/src/main/java/org/mule/galaxy/config/CustomListenersBeanDefinitionParser.java
@@ -1,66 +1,66 @@
package org.mule.galaxy.config;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.ManagedList;
import org.springframework.beans.factory.xml.AbstractBeanDefinitionParser;
import org.springframework.beans.factory.xml.BeanDefinitionParserDelegate;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.util.xml.DomUtils;
import org.w3c.dom.Element;
/**
* Bean definition parser for the <g:custom-listeners> configuration element in Galaxy.
*/
public class CustomListenersBeanDefinitionParser extends AbstractBeanDefinitionParser {
@SuppressWarnings("unchecked")
protected AbstractBeanDefinition parseInternal(final Element element, final ParserContext parserContext) {
// this is the bean peforming the registration of custom listeners
BeanDefinitionBuilder listenerRegBean = BeanDefinitionBuilder.rootBeanDefinition(CustomListenersBean.class);
Element emElement = DomUtils.getChildElementByTagName(element, "eventManager");
if (emElement != null) {
// if the user overrides the default eventManager
final String beanName = emElement.getAttribute("ref");
listenerRegBean.addDependsOn(beanName);
listenerRegBean.addPropertyReference("eventManager", beanName);
}
List<Element> listenerElements = DomUtils.getChildElementsByTagName(element, "listener");
ManagedList listeners = new ManagedList(listenerElements.size());
for (Element listenerElement : listenerElements) {
final BeanDefinitionParserDelegate beanParserDelegate = new BeanDefinitionParserDelegate(parserContext.getReaderContext());
// parse nested spring bean definitions
Element bean = DomUtils.getChildElementByTagName(listenerElement, "bean");
// it could be a ref to an existing bean too
if (bean == null) {
Element ref = DomUtils.getChildElementByTagName(listenerElement, "ref");
String beanName = StringUtils.defaultString(ref.getAttribute("bean"), ref.getAttribute("local"));
if (StringUtils.isBlank(beanName)) {
throw new IllegalArgumentException("A listener ref element has neither 'bean' nor 'local' attributes");
}
listeners.add(new RuntimeBeanReference(beanName));
} else {
- BeanDefinitionHolder listener = beanParserDelegate.parseBeanDefinitionElement(bean);
// need to init defaults
beanParserDelegate.initDefaults(bean);
+ BeanDefinitionHolder listener = beanParserDelegate.parseBeanDefinitionElement(bean);
listeners.add(listener);
}
}
listenerRegBean.addPropertyValue("customListeners", listeners);
return listenerRegBean.getBeanDefinition();
}
@Override
protected boolean shouldGenerateId() {
// auto-generate a unique bean id
return true;
}
}
| false | true | protected AbstractBeanDefinition parseInternal(final Element element, final ParserContext parserContext) {
// this is the bean peforming the registration of custom listeners
BeanDefinitionBuilder listenerRegBean = BeanDefinitionBuilder.rootBeanDefinition(CustomListenersBean.class);
Element emElement = DomUtils.getChildElementByTagName(element, "eventManager");
if (emElement != null) {
// if the user overrides the default eventManager
final String beanName = emElement.getAttribute("ref");
listenerRegBean.addDependsOn(beanName);
listenerRegBean.addPropertyReference("eventManager", beanName);
}
List<Element> listenerElements = DomUtils.getChildElementsByTagName(element, "listener");
ManagedList listeners = new ManagedList(listenerElements.size());
for (Element listenerElement : listenerElements) {
final BeanDefinitionParserDelegate beanParserDelegate = new BeanDefinitionParserDelegate(parserContext.getReaderContext());
// parse nested spring bean definitions
Element bean = DomUtils.getChildElementByTagName(listenerElement, "bean");
// it could be a ref to an existing bean too
if (bean == null) {
Element ref = DomUtils.getChildElementByTagName(listenerElement, "ref");
String beanName = StringUtils.defaultString(ref.getAttribute("bean"), ref.getAttribute("local"));
if (StringUtils.isBlank(beanName)) {
throw new IllegalArgumentException("A listener ref element has neither 'bean' nor 'local' attributes");
}
listeners.add(new RuntimeBeanReference(beanName));
} else {
BeanDefinitionHolder listener = beanParserDelegate.parseBeanDefinitionElement(bean);
// need to init defaults
beanParserDelegate.initDefaults(bean);
listeners.add(listener);
}
}
listenerRegBean.addPropertyValue("customListeners", listeners);
return listenerRegBean.getBeanDefinition();
}
| protected AbstractBeanDefinition parseInternal(final Element element, final ParserContext parserContext) {
// this is the bean peforming the registration of custom listeners
BeanDefinitionBuilder listenerRegBean = BeanDefinitionBuilder.rootBeanDefinition(CustomListenersBean.class);
Element emElement = DomUtils.getChildElementByTagName(element, "eventManager");
if (emElement != null) {
// if the user overrides the default eventManager
final String beanName = emElement.getAttribute("ref");
listenerRegBean.addDependsOn(beanName);
listenerRegBean.addPropertyReference("eventManager", beanName);
}
List<Element> listenerElements = DomUtils.getChildElementsByTagName(element, "listener");
ManagedList listeners = new ManagedList(listenerElements.size());
for (Element listenerElement : listenerElements) {
final BeanDefinitionParserDelegate beanParserDelegate = new BeanDefinitionParserDelegate(parserContext.getReaderContext());
// parse nested spring bean definitions
Element bean = DomUtils.getChildElementByTagName(listenerElement, "bean");
// it could be a ref to an existing bean too
if (bean == null) {
Element ref = DomUtils.getChildElementByTagName(listenerElement, "ref");
String beanName = StringUtils.defaultString(ref.getAttribute("bean"), ref.getAttribute("local"));
if (StringUtils.isBlank(beanName)) {
throw new IllegalArgumentException("A listener ref element has neither 'bean' nor 'local' attributes");
}
listeners.add(new RuntimeBeanReference(beanName));
} else {
// need to init defaults
beanParserDelegate.initDefaults(bean);
BeanDefinitionHolder listener = beanParserDelegate.parseBeanDefinitionElement(bean);
listeners.add(listener);
}
}
listenerRegBean.addPropertyValue("customListeners", listeners);
return listenerRegBean.getBeanDefinition();
}
|
diff --git a/src/org/geometerplus/zlibrary/core/util/RationalNumber.java b/src/org/geometerplus/zlibrary/core/util/RationalNumber.java
index 3900ce64e..7ea99be5c 100644
--- a/src/org/geometerplus/zlibrary/core/util/RationalNumber.java
+++ b/src/org/geometerplus/zlibrary/core/util/RationalNumber.java
@@ -1,37 +1,37 @@
/*
* Copyright (C) 2007-2013 Geometer Plus <[email protected]>
*
* 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.geometerplus.zlibrary.core.util;
public class RationalNumber {
public static RationalNumber create(long numerator, long denominator) {
- if (denominator == null) {
+ if (denominator == 0) {
return null;
}
return new RationalNumber(numerator, denominator);
}
public final long Numerator;
public final long Denominator;
private RationalNumber(long numerator, long denominator) {
Numerator = numerator;
Denominator = denominator;
}
}
| true | true | public static RationalNumber create(long numerator, long denominator) {
if (denominator == null) {
return null;
}
return new RationalNumber(numerator, denominator);
}
| public static RationalNumber create(long numerator, long denominator) {
if (denominator == 0) {
return null;
}
return new RationalNumber(numerator, denominator);
}
|
diff --git a/dev/core/src/com/google/gwt/dev/jdt/TypeOracleBuilder.java b/dev/core/src/com/google/gwt/dev/jdt/TypeOracleBuilder.java
index b8b813678..12056ea48 100644
--- a/dev/core/src/com/google/gwt/dev/jdt/TypeOracleBuilder.java
+++ b/dev/core/src/com/google/gwt/dev/jdt/TypeOracleBuilder.java
@@ -1,1678 +1,1677 @@
/*
* Copyright 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.gwt.dev.jdt;
import com.google.gwt.core.ext.TreeLogger;
import com.google.gwt.core.ext.UnableToCompleteException;
import com.google.gwt.core.ext.typeinfo.CompilationUnitProvider;
import com.google.gwt.core.ext.typeinfo.HasMetaData;
import com.google.gwt.core.ext.typeinfo.HasTypeParameters;
import com.google.gwt.core.ext.typeinfo.JAbstractMethod;
import com.google.gwt.core.ext.typeinfo.JAnnotationMethod;
import com.google.gwt.core.ext.typeinfo.JAnnotationType;
import com.google.gwt.core.ext.typeinfo.JArrayType;
import com.google.gwt.core.ext.typeinfo.JBound;
import com.google.gwt.core.ext.typeinfo.JClassType;
import com.google.gwt.core.ext.typeinfo.JConstructor;
import com.google.gwt.core.ext.typeinfo.JEnumConstant;
import com.google.gwt.core.ext.typeinfo.JEnumType;
import com.google.gwt.core.ext.typeinfo.JField;
import com.google.gwt.core.ext.typeinfo.JGenericType;
import com.google.gwt.core.ext.typeinfo.JLowerBound;
import com.google.gwt.core.ext.typeinfo.JMethod;
import com.google.gwt.core.ext.typeinfo.JPackage;
import com.google.gwt.core.ext.typeinfo.JParameter;
import com.google.gwt.core.ext.typeinfo.JParameterizedType;
import com.google.gwt.core.ext.typeinfo.JPrimitiveType;
import com.google.gwt.core.ext.typeinfo.JRealClassType;
import com.google.gwt.core.ext.typeinfo.JType;
import com.google.gwt.core.ext.typeinfo.JTypeParameter;
import com.google.gwt.core.ext.typeinfo.JUpperBound;
import com.google.gwt.core.ext.typeinfo.TypeOracle;
import com.google.gwt.dev.jdt.CacheManager.Mapper;
import com.google.gwt.dev.util.Empty;
import com.google.gwt.dev.util.Util;
import com.google.gwt.dev.util.PerfLogger;
import org.eclipse.jdt.core.compiler.CharOperation;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.internal.compiler.ASTVisitor;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.AbstractVariableDeclaration;
import org.eclipse.jdt.internal.compiler.ast.Annotation;
import org.eclipse.jdt.internal.compiler.ast.AnnotationMethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.Argument;
import org.eclipse.jdt.internal.compiler.ast.ArrayInitializer;
import org.eclipse.jdt.internal.compiler.ast.ClassLiteralAccess;
import org.eclipse.jdt.internal.compiler.ast.Clinit;
import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
import org.eclipse.jdt.internal.compiler.ast.ConditionalExpression;
import org.eclipse.jdt.internal.compiler.ast.Expression;
import org.eclipse.jdt.internal.compiler.ast.FalseLiteral;
import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration;
import org.eclipse.jdt.internal.compiler.ast.Initializer;
import org.eclipse.jdt.internal.compiler.ast.Javadoc;
import org.eclipse.jdt.internal.compiler.ast.MagicLiteral;
import org.eclipse.jdt.internal.compiler.ast.MemberValuePair;
import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.NameReference;
import org.eclipse.jdt.internal.compiler.ast.NullLiteral;
import org.eclipse.jdt.internal.compiler.ast.NumberLiteral;
import org.eclipse.jdt.internal.compiler.ast.SingleMemberAnnotation;
import org.eclipse.jdt.internal.compiler.ast.StringLiteral;
import org.eclipse.jdt.internal.compiler.ast.TrueLiteral;
import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.eclipse.jdt.internal.compiler.ast.TypeParameter;
import org.eclipse.jdt.internal.compiler.ast.TypeReference;
import org.eclipse.jdt.internal.compiler.ast.Wildcard;
import org.eclipse.jdt.internal.compiler.env.ICompilationUnit;
import org.eclipse.jdt.internal.compiler.env.IGenericType;
import org.eclipse.jdt.internal.compiler.impl.Constant;
import org.eclipse.jdt.internal.compiler.lookup.ArrayBinding;
import org.eclipse.jdt.internal.compiler.lookup.BaseTypeBinding;
import org.eclipse.jdt.internal.compiler.lookup.BinaryTypeBinding;
import org.eclipse.jdt.internal.compiler.lookup.BlockScope;
import org.eclipse.jdt.internal.compiler.lookup.ClassScope;
import org.eclipse.jdt.internal.compiler.lookup.CompilationUnitScope;
import org.eclipse.jdt.internal.compiler.lookup.LocalTypeBinding;
import org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
import org.eclipse.jdt.internal.compiler.lookup.ParameterizedTypeBinding;
import org.eclipse.jdt.internal.compiler.lookup.RawTypeBinding;
import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding;
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
import org.eclipse.jdt.internal.compiler.lookup.TypeIds;
import org.eclipse.jdt.internal.compiler.lookup.TypeVariableBinding;
import org.eclipse.jdt.internal.compiler.lookup.WildcardBinding;
import java.io.BufferedReader;
import java.io.CharArrayReader;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
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.Set;
import java.util.regex.Pattern;
/**
* Builds a {@link com.google.gwt.core.ext.typeinfo.TypeOracle} from a set of
* compilation units.
* <p>
* For example,
*
* <pre>
* TypeOracleBuilder b = new TypeOracleBuilder();
* b.addCompilationUnit(unit1);
* b.addCompilationUnit(unit2);
* b.addCompilationUnit(unit3);
* b.excludePackage("example.pkg");
* TypeOracle oracle = b.build(logger);
* JClassType[] allTypes = oracle.getTypes();
* </pre>
*/
public class TypeOracleBuilder {
private static final JClassType[] NO_JCLASSES = new JClassType[0];
private static final Pattern PATTERN_WHITESPACE = Pattern.compile("\\s");
public static String computeBinaryClassName(JType type) {
JPrimitiveType primitiveType = type.isPrimitive();
if (primitiveType != null) {
return primitiveType.getJNISignature();
}
JArrayType arrayType = type.isArray();
if (arrayType != null) {
JType component = arrayType.getComponentType();
if (component.isClassOrInterface() != null) {
return "[L" + computeBinaryClassName(arrayType.getComponentType())
+ ";";
} else {
return "[" + computeBinaryClassName(arrayType.getComponentType());
}
}
JParameterizedType parameterizedType = type.isParameterized();
if (parameterizedType != null) {
return computeBinaryClassName(parameterizedType.getBaseType());
}
JClassType classType = type.isClassOrInterface();
assert (classType != null);
JClassType enclosingType = classType.getEnclosingType();
if (enclosingType != null) {
return computeBinaryClassName(enclosingType) + "$"
+ classType.getSimpleSourceName();
}
return classType.getQualifiedSourceName();
}
static boolean parseMetaDataTags(char[] unitSource, HasMetaData hasMetaData,
Javadoc javadoc) {
int start = javadoc.sourceStart;
int end = javadoc.sourceEnd;
char[] comment = CharOperation.subarray(unitSource, start, end + 1);
if (comment == null) {
comment = new char[0];
}
BufferedReader reader = new BufferedReader(new CharArrayReader(comment));
String activeTag = null;
final List<String> tagValues = new ArrayList<String>();
try {
String line = reader.readLine();
boolean firstLine = true;
while (line != null) {
if (firstLine) {
firstLine = false;
int commentStart = line.indexOf("/**");
if (commentStart == -1) {
// Malformed.
return false;
}
line = line.substring(commentStart + 3);
}
String[] tokens = PATTERN_WHITESPACE.split(line);
boolean canIgnoreStar = true;
for (int i = 0; i < tokens.length; i++) {
String token = tokens[i];
// Check for the end.
//
if (token.endsWith("*/")) {
token = token.substring(0, token.length() - 2);
}
// Check for an ignored leading star.
//
if (canIgnoreStar && token.startsWith("*")) {
token = token.substring(1);
canIgnoreStar = false;
}
// Decide what to do with whatever is left.
//
if (token.length() > 0) {
canIgnoreStar = false;
if (token.startsWith("@")) {
// A new tag has been introduced.
// Subsequent tokens will attach to it.
// Make sure we finish the previously active tag before moving on.
//
if (activeTag != null) {
finishTag(hasMetaData, activeTag, tagValues);
}
activeTag = token.substring(1);
} else if (activeTag != null) {
// Attach this item to the active tag.
//
tagValues.add(token);
} else {
// Just ignore it.
//
}
}
}
line = reader.readLine();
}
} catch (IOException e) {
return false;
}
// To catch the last batch of values, if any.
//
finishTag(hasMetaData, activeTag, tagValues);
return true;
}
private static void finishTag(HasMetaData hasMetaData, String tagName,
List<String> tagValues) {
// Add the values even if the list is empty, because the presence of the
// tag itself might be important.
//
String[] values = tagValues.toArray(Empty.STRINGS);
hasMetaData.addMetaData(tagName, values);
tagValues.clear();
}
/**
* Returns the value associated with a JDT constant.
*/
private static Object getConstantValue(Constant constant) {
switch (constant.typeID()) {
case TypeIds.T_char:
return constant.charValue();
case TypeIds.T_byte:
return constant.byteValue();
case TypeIds.T_short:
return constant.shortValue();
case TypeIds.T_boolean:
return constant.booleanValue();
case TypeIds.T_long:
return constant.longValue();
case TypeIds.T_double:
return constant.doubleValue();
case TypeIds.T_float:
return constant.floatValue();
case TypeIds.T_int:
return constant.intValue();
case TypeIds.T_JavaLangString:
return constant.stringValue();
case TypeIds.T_null:
return null;
default:
break;
}
assert false : "Unknown constant type";
return null;
}
private static String getMethodName(JClassType enclosingType,
AbstractMethodDeclaration jmethod) {
if (jmethod.isConstructor()) {
return String.valueOf(enclosingType.getSimpleSourceName());
} else {
return String.valueOf(jmethod.binding.selector);
}
}
/**
* Returns the number associated with a JDT numeric literal.
*/
private static Object getNumericLiteralValue(NumberLiteral expression) {
return getConstantValue(expression.constant);
}
private static boolean isAnnotation(TypeDeclaration typeDecl) {
if (typeDecl.kind() == IGenericType.ANNOTATION_TYPE_DECL) {
return true;
} else {
return false;
}
}
/**
* Returns <code>true</code> if this name is the special package-info type
* name.
*
* @return <code>true</code> if this name is the special package-info type
* name
*/
private static boolean isPackageInfoTypeName(String qname) {
return "package-info".equals(qname);
}
private static boolean maybeGeneric(TypeDeclaration typeDecl,
JClassType enclosingType) {
if (enclosingType != null && enclosingType.isGenericType() != null) {
if (!typeDecl.binding.isStatic()) {
/*
* This non-static, inner class can reference the type parameters of its
* enclosing generic type, so we will treat it as a generic type.
*/
return true;
}
}
if (typeDecl.binding.isLocalType()) {
LocalTypeBinding localTypeBinding = (LocalTypeBinding) typeDecl.binding;
MethodBinding enclosingMethod = localTypeBinding.enclosingMethod;
if (enclosingMethod != null) {
if (enclosingMethod.typeVariables != null
&& enclosingMethod.typeVariables.length != 0) {
/*
* This local type can reference the type parameters of its enclosing
* method, so we will treat is as a generic type.
*/
return true;
}
}
}
if (typeDecl.typeParameters != null) {
// Definitely generic since it has type parameters.
return true;
}
return false;
}
// TODO: move into the Annotations class or create an AnnotationsUtil class?
private static HashMap<Class<? extends java.lang.annotation.Annotation>, java.lang.annotation.Annotation> newAnnotationMap() {
return new HashMap<Class<? extends java.lang.annotation.Annotation>, java.lang.annotation.Annotation>();
}
private static void removeInfectedUnits(final TreeLogger logger,
final Map<String, CompilationUnitDeclaration> cudsByFileName) {
final Set<String> pendingRemovals = new HashSet<String>();
TypeRefVisitor trv = new TypeRefVisitor() {
@Override
protected void onTypeRef(SourceTypeBinding referencedType,
CompilationUnitDeclaration unitOfReferrer) {
// If the referenced type belongs to a compilation unit that is
// not in the list of valid units, then the unit in which it
// is referenced must also be removed.
//
String referencedFn = String.valueOf(referencedType.getFileName());
CompilationUnitDeclaration referencedCud = cudsByFileName.get(referencedFn);
if (referencedCud == null) {
// This is a referenced to a bad or non-existent unit.
// So, remove the referrer's unit if it hasn't been already.
//
String referrerFn = String.valueOf(unitOfReferrer.getFileName());
if (cudsByFileName.containsKey(referrerFn)
&& !pendingRemovals.contains(referrerFn)) {
TreeLogger branch = logger.branch(TreeLogger.TRACE,
"Cascaded removal of compilation unit '" + referrerFn + "'",
null);
final String badTypeName = CharOperation.toString(referencedType.compoundName);
branch.branch(TreeLogger.TRACE,
"Due to reference to unavailable type: " + badTypeName, null);
pendingRemovals.add(referrerFn);
}
}
}
};
do {
// Perform any pending removals.
//
for (Iterator<String> iter = pendingRemovals.iterator(); iter.hasNext();) {
String fnToRemove = iter.next();
Object removed = cudsByFileName.remove(fnToRemove);
assert (removed != null);
}
// Start fresh for this iteration.
//
pendingRemovals.clear();
// Find references to type in units that aren't valid.
//
for (Iterator<CompilationUnitDeclaration> iter = cudsByFileName.values().iterator(); iter.hasNext();) {
CompilationUnitDeclaration cud = iter.next();
cud.traverse(trv, cud.scope);
}
} while (!pendingRemovals.isEmpty());
}
private static void removeUnitsWithErrors(TreeLogger logger,
Map<String, CompilationUnitDeclaration> cudsByFileName) {
// Start by removing units with a known problem.
//
boolean anyRemoved = false;
for (Iterator<CompilationUnitDeclaration> iter = cudsByFileName.values().iterator(); iter.hasNext();) {
CompilationUnitDeclaration cud = iter.next();
CompilationResult result = cud.compilationResult;
IProblem[] errors = result.getErrors();
if (errors != null && errors.length > 0) {
anyRemoved = true;
iter.remove();
String fileName = CharOperation.charToString(cud.getFileName());
char[] source = cud.compilationResult.compilationUnit.getContents();
Util.maybeDumpSource(logger, fileName, source, null);
logger.log(TreeLogger.TRACE, "Removing problematic compilation unit '"
+ fileName + "'", null);
}
}
if (anyRemoved) {
// Then removing anything else that won't compile as a result.
//
removeInfectedUnits(logger, cudsByFileName);
}
}
private final CacheManager cacheManager;
/**
* Constructs a default instance, with a default cacheManager. This is not to
* be used in Hosted Mode, as caching will then not work.
*/
public TypeOracleBuilder() {
cacheManager = new CacheManager();
}
/**
* Constructs an instance from the supplied cacheManager, using the
* <code>TypeOracle</code> contained therein. This is to be used in Hosted
* Mode, so that caching will work, assuming the cacheManager has a cache
* directory.
*/
public TypeOracleBuilder(CacheManager cacheManager) {
this.cacheManager = cacheManager;
}
/**
* Constructs an instance from the supplied typeOracle, with a cacheManager
* using the same typeOracle. This is not to be used in Hosted Mode, as
* caching will then not work.
*/
public TypeOracleBuilder(TypeOracle typeOracle) {
cacheManager = new CacheManager(typeOracle);
}
/**
* Includes the specified logical compilation unit into the set of units this
* builder will parse and analyze. If a previous compilation unit was
* specified in the same location, it will be replaced if it is older.
*/
public void addCompilationUnit(CompilationUnitProvider cup)
throws UnableToCompleteException {
cacheManager.addCompilationUnit(cup);
}
public TypeOracle build(final TreeLogger logger)
throws UnableToCompleteException {
PerfLogger.start("TypeOracleBuilder.build");
Set<CompilationUnitProvider> addedCups = cacheManager.getAddedCups();
TypeOracle oracle = cacheManager.getTypeOracle();
// Make a copy that we can sort.
//
for (Iterator<CompilationUnitProvider> iter = addedCups.iterator(); iter.hasNext();) {
CompilationUnitProvider cup = iter.next();
String location = cup.getLocation();
if (!((location.indexOf("http://") != -1) || (location.indexOf("ftp://") != -1))) {
location = Util.findFileName(location);
if (!(new File(location).exists() || cup.isTransient())) {
iter.remove();
logger.log(
TreeLogger.TRACE,
"The file "
+ location
+ " was removed by the user. All types therein are now unavailable.",
null);
}
}
}
CompilationUnitProvider[] cups = Util.toArray(
CompilationUnitProvider.class, addedCups);
Arrays.sort(cups, CompilationUnitProvider.LOCATION_COMPARATOR);
// Make sure we can find the java.lang.Object compilation unit.
//
boolean foundJavaLangPackage = oracle.findPackage("java.lang") != null;
// Adapt to JDT idioms.
//
ICompilationUnit[] units = new ICompilationUnit[cups.length];
for (int i = 0; i < cups.length; i++) {
if (!foundJavaLangPackage && cups[i].getPackageName().equals("java.lang")) {
foundJavaLangPackage = true;
}
units[i] = cacheManager.findUnitForCup(cups[i]);
}
// Error if no java.lang.
if (!foundJavaLangPackage) {
Util.logMissingTypeErrorWithHints(logger, "java.lang.Object");
throw new UnableToCompleteException();
}
PerfLogger.start("TypeOracleBuilder.build (compile)");
CompilationUnitDeclaration[] cuds = cacheManager.getAstCompiler().getChangedCompilationUnitDeclarations(
logger, units);
PerfLogger.end();
// Build a list that makes it easy to remove problems.
//
final Map<String, CompilationUnitDeclaration> cudsByFileName = new HashMap<String, CompilationUnitDeclaration>();
for (int i = 0; i < cuds.length; i++) {
CompilationUnitDeclaration cud = cuds[i];
char[] location = cud.getFileName();
cudsByFileName.put(String.valueOf(location), cud);
}
cacheManager.getCudsByFileName().putAll(cudsByFileName);
// Remove bad cuds and all the other cuds that are affected.
//
removeUnitsWithErrors(logger, cudsByFileName);
// Perform a shallow pass to establish identity for new types.
//
final CacheManager.Mapper identityMapper = cacheManager.getIdentityMapper();
for (Iterator<CompilationUnitDeclaration> iter = cudsByFileName.values().iterator(); iter.hasNext();) {
CompilationUnitDeclaration cud = iter.next();
cud.traverse(new ASTVisitor() {
@Override
public boolean visit(TypeDeclaration typeDecl, BlockScope scope) {
JClassType enclosingType = identityMapper.get(typeDecl.binding.enclosingType());
processType(typeDecl, enclosingType, true);
return true;
}
@Override
public boolean visit(TypeDeclaration typeDecl, ClassScope scope) {
JClassType enclosingType = identityMapper.get(typeDecl.binding.enclosingType());
processType(typeDecl, enclosingType, false);
return true;
}
@Override
public boolean visit(TypeDeclaration typeDecl,
CompilationUnitScope scope) {
processType(typeDecl, null, false);
return true;
}
}, cud.scope);
}
// Perform a deep pass to resolve all types in terms of our types.
//
for (Iterator<CompilationUnitDeclaration> iter = cudsByFileName.values().iterator(); iter.hasNext();) {
CompilationUnitDeclaration cud = iter.next();
String loc = String.valueOf(cud.getFileName());
String processing = "Processing types in compilation unit: " + loc;
final TreeLogger cudLogger = logger.branch(TreeLogger.SPAM, processing,
null);
final char[] source = cud.compilationResult.compilationUnit.getContents();
cud.traverse(new ASTVisitor() {
@Override
public boolean visit(TypeDeclaration typeDecl, BlockScope scope) {
if (!resolveTypeDeclaration(cudLogger, source, typeDecl)) {
String name = String.valueOf(typeDecl.binding.readableName());
String msg = "Unexpectedly unable to fully resolve type " + name;
logger.log(TreeLogger.WARN, msg, null);
}
return true;
}
@Override
public boolean visit(TypeDeclaration typeDecl, ClassScope scope) {
if (!resolveTypeDeclaration(cudLogger, source, typeDecl)) {
String name = String.valueOf(typeDecl.binding.readableName());
String msg = "Unexpectedly unable to fully resolve type " + name;
logger.log(TreeLogger.WARN, msg, null);
}
return true;
}
@Override
public boolean visit(TypeDeclaration typeDecl,
CompilationUnitScope scope) {
if (!resolveTypeDeclaration(cudLogger, source, typeDecl)) {
String name = String.valueOf(typeDecl.binding.readableName());
String msg = "Unexpectedly unable to fully resolve type " + name;
logger.log(TreeLogger.WARN, msg, null);
}
return true;
}
}, cud.scope);
}
Util.invokeInaccessableMethod(TypeOracle.class, "refresh",
new Class[] {TreeLogger.class}, oracle, new Object[] {logger});
PerfLogger.end();
return oracle;
}
private Object createAnnotationInstance(TreeLogger logger,
Expression expression) {
Annotation annotation = (Annotation) expression;
// Determine the annotation class
TypeBinding resolvedType = annotation.resolvedType;
Class<?> classLiteral = getClassLiteral(logger, resolvedType);
if (classLiteral == null) {
return null;
}
Class<? extends java.lang.annotation.Annotation> clazz = classLiteral.asSubclass(java.lang.annotation.Annotation.class);
// Build the map of identifiers to values.
Map<String, Object> identifierToValue = new HashMap<String, Object>();
for (MemberValuePair mvp : annotation.memberValuePairs()) {
// Method name
String identifier = String.valueOf(mvp.name);
// Value
Expression expressionValue = mvp.value;
Object value = evaluateConstantExpression(logger, expressionValue);
if (value == null) {
return null;
}
try {
Method method = clazz.getMethod(identifier, new Class[0]);
Class<?> expectedClass = method.getReturnType();
Class<? extends Object> actualClass = value.getClass();
if (expectedClass.isArray() && !actualClass.isArray()) {
/*
* JSL3 Section 9.7 single element annotations can skip the curly
* braces; means we do not get an array
*/
assert (expression instanceof SingleMemberAnnotation);
Object array = Array.newInstance(expectedClass.getComponentType(), 1);
Array.set(array, 0, value);
value = array;
}
} catch (SecurityException e) {
return null;
} catch (NoSuchMethodException e) {
return null;
}
identifierToValue.put(identifier, value);
}
// Create the Annotation proxy
JClassType annotationType = (JClassType) resolveType(logger, resolvedType);
if (annotationType == null) {
return null;
}
return AnnotationProxyFactory.create(clazz, annotationType,
identifierToValue);
}
private Object createArrayConstant(TreeLogger logger,
ArrayInitializer arrayInitializer) {
Class<?> leafComponentClass = getClassLiteral(logger,
arrayInitializer.binding.leafComponentType);
if (leafComponentClass == null) {
return null;
}
int[] dimensions = new int[arrayInitializer.binding.dimensions];
Expression[] initExpressions = arrayInitializer.expressions;
if (initExpressions != null) {
dimensions[0] = initExpressions.length;
}
Object array = Array.newInstance(leafComponentClass, dimensions);
boolean failed = false;
if (initExpressions != null) {
for (int i = 0; i < initExpressions.length; ++i) {
Expression arrayInitExp = initExpressions[i];
Object value = evaluateConstantExpression(logger, arrayInitExp);
if (value != null) {
Array.set(array, i, value);
} else {
failed = true;
break;
}
}
}
if (!failed) {
return array;
}
return null;
}
private JUpperBound createTypeParameterBounds(TreeLogger logger,
TypeVariableBinding tvBinding) {
TypeBinding firstBound = tvBinding.firstBound;
if (firstBound == null) {
// No bounds were specified, so we default to Object. We assume that the
// superclass field of a TypeVariableBinding object is a Binding
// for a java.lang.Object, and we use this binding to find the
// JClassType for java.lang.Object. To be sure that our assumption
// about the superclass field is valid, we perform a runtime check
// against the name of the resolved type.
// You may wonder why we have to go this roundabout way to find a
// JClassType for java.lang.Object. The reason is that the TypeOracle
// has not been constructed as yet, so we cannot simply call
// TypeOracle.getJavaLangObject().
JClassType jupperBound = (JClassType) resolveType(logger,
tvBinding.superclass);
if (Object.class.getName().equals(jupperBound.getQualifiedSourceName())) {
return new JUpperBound(jupperBound);
} else {
return null;
}
}
List<JClassType> bounds = new ArrayList<JClassType>();
JClassType jfirstBound = (JClassType) resolveType(logger, firstBound);
if (jfirstBound == null) {
return null;
}
if (jfirstBound.isClass() != null) {
bounds.add(jfirstBound);
}
ReferenceBinding[] superInterfaces = tvBinding.superInterfaces();
for (ReferenceBinding superInterface : superInterfaces) {
JClassType jsuperInterface = (JClassType) resolveType(logger,
superInterface);
if (jsuperInterface == null || jsuperInterface.isInterface() == null) {
return null;
}
bounds.add(jsuperInterface);
}
return new JUpperBound(bounds.toArray(NO_JCLASSES));
}
/**
* Declares TypeParameters declared on a JGenericType or a JAbstractMethod by
* mapping the TypeParameters into JTypeParameters. <p/> This mapping has to
* be done on the first pass through the AST in order to handle declarations
* of the form: <<C exends GenericClass<T>, T extends SimpleClass> <p/> JDT
* already knows that GenericClass<T> is a parameterized type with a type
* argument of <T extends SimpleClass>. Therefore, in order to resolve
* GenericClass<T>, we must have knowledge of <T extends SimpleClass>. <p/>
* By calling this method on the first pass through the AST, a JTypeParameter
* for <T extends SimpleClass> will be created.
*/
private JTypeParameter[] declareTypeParameters(TypeParameter[] typeParameters) {
if (typeParameters == null || typeParameters.length == 0) {
return null;
}
JTypeParameter[] jtypeParamArray = new JTypeParameter[typeParameters.length];
Mapper identityMapper = cacheManager.getIdentityMapper();
for (int i = 0; i < typeParameters.length; i++) {
TypeParameter typeParam = typeParameters[i];
jtypeParamArray[i] = new JTypeParameter(String.valueOf(typeParam.name), i);
identityMapper.put(typeParam.binding, jtypeParamArray[i]);
}
return jtypeParamArray;
}
private Object evaluateConstantExpression(TreeLogger logger,
Expression expression) {
if (expression instanceof MagicLiteral) {
if (expression instanceof FalseLiteral) {
return Boolean.FALSE;
} else if (expression instanceof NullLiteral) {
// null is not a valid annotation value; JLS Third Ed. Section 9.7
} else if (expression instanceof TrueLiteral) {
return Boolean.TRUE;
}
} else if (expression instanceof NumberLiteral) {
Object value = getNumericLiteralValue((NumberLiteral) expression);
if (value != null) {
return value;
}
} else if (expression instanceof StringLiteral) {
StringLiteral stringLiteral = (StringLiteral) expression;
return stringLiteral.constant.stringValue();
} else if (expression instanceof ClassLiteralAccess) {
ClassLiteralAccess classLiteral = (ClassLiteralAccess) expression;
Class<?> clazz = getClassLiteral(logger, classLiteral.targetType);
if (clazz != null) {
return clazz;
}
} else if (expression instanceof ArrayInitializer) {
Object value = createArrayConstant(logger, (ArrayInitializer) expression);
if (value != null) {
return value;
}
} else if (expression instanceof NameReference) {
/*
* This name reference can only be to something that is a constant value,
* or an enumerated type since annotation values must be constants.
*/
NameReference nameRef = (NameReference) expression;
if (nameRef.constant != Constant.NotAConstant) {
return getConstantValue(nameRef.constant);
} else {
Class clazz = getClassLiteral(logger, nameRef.actualReceiverType);
if (clazz.isEnum()) {
String enumName = String.valueOf(nameRef.fieldBinding().name);
return Enum.valueOf(clazz, enumName);
} else {
/*
* If this is not an enumeration, then fall through to failure case
* below.
*/
}
}
} else if (expression instanceof Annotation) {
Object annotationInstance = createAnnotationInstance(logger, expression);
if (annotationInstance != null) {
return annotationInstance;
}
} else if (expression instanceof ConditionalExpression) {
ConditionalExpression condExpression = (ConditionalExpression) expression;
assert (condExpression.constant != Constant.NotAConstant);
return getConstantValue(condExpression.constant);
}
assert (false);
return null;
}
private Class<?> getClassLiteral(TreeLogger logger, TypeBinding resolvedType) {
JType type = resolveType(logger, resolvedType);
if (type == null) {
return null;
}
if (type.isPrimitive() != null) {
return getClassLiteralForPrimitive(type.isPrimitive());
} else {
try {
String className = computeBinaryClassName(type);
Class<?> clazz = Class.forName(className);
return clazz;
} catch (ClassNotFoundException e) {
logger.log(TreeLogger.ERROR, "", e);
return null;
}
}
}
private Class<?> getClassLiteralForPrimitive(JPrimitiveType type) {
if (type == JPrimitiveType.BOOLEAN) {
return boolean.class;
} else if (type == JPrimitiveType.BYTE) {
return byte.class;
} else if (type == JPrimitiveType.CHAR) {
return char.class;
} else if (type == JPrimitiveType.DOUBLE) {
return double.class;
} else if (type == JPrimitiveType.FLOAT) {
return float.class;
} else if (type == JPrimitiveType.INT) {
return int.class;
} else if (type == JPrimitiveType.LONG) {
return long.class;
} else if (type == JPrimitiveType.SHORT) {
return short.class;
}
assert (false);
return null;
}
private CompilationUnitProvider getCup(TypeDeclaration typeDecl) {
ICompilationUnit icu = typeDecl.compilationResult.compilationUnit;
ICompilationUnitAdapter icua = (ICompilationUnitAdapter) icu;
return icua.getCompilationUnitProvider();
}
private String getPackage(TypeDeclaration typeDecl) {
final char[][] pkgParts = typeDecl.compilationResult.compilationUnit.getPackageName();
return String.valueOf(CharOperation.concatWith(pkgParts, '.'));
}
/**
* Returns the qualified name of the binding, excluding any type parameter
* information.
*/
private String getQualifiedName(ReferenceBinding binding) {
String qualifiedName = CharOperation.toString(binding.compoundName);
if (binding instanceof LocalTypeBinding) {
// The real name of a local type is its constant pool name.
qualifiedName = CharOperation.charToString(binding.constantPoolName());
qualifiedName = qualifiedName.replace('/', '.');
} else {
/*
* All other types have their fully qualified name as part of its compound
* name.
*/
qualifiedName = CharOperation.toString(binding.compoundName);
}
qualifiedName = qualifiedName.replace('$', '.');
return qualifiedName;
}
private String getSimpleName(TypeDeclaration typeDecl) {
return String.valueOf(typeDecl.name);
}
private boolean isInterface(TypeDeclaration typeDecl) {
if (typeDecl.kind() == IGenericType.INTERFACE_DECL) {
return true;
} else {
return false;
}
}
/**
* Maps a TypeDeclaration into a JClassType. If the TypeDeclaration has
* TypeParameters (i.e, it is a generic type or method), then the
* TypeParameters are mapped into JTypeParameters by
* {@link TypeOracleBuilder#declareTypeParameters(org.eclipse.jdt.internal.compiler.ast.TypeParameter[])}
*/
private void processType(TypeDeclaration typeDecl, JClassType jenclosingType,
boolean isLocalType) {
TypeOracle oracle = cacheManager.getTypeOracle();
// Create our version of the type structure unless it already exists in the
// type oracle.
//
SourceTypeBinding binding = typeDecl.binding;
if (binding.constantPoolName() == null) {
/*
* Weird case: if JDT determines that this local class is totally
* uninstantiable, it won't bother allocating a local name.
*/
return;
}
String qname = getQualifiedName(binding);
String className;
if (binding instanceof LocalTypeBinding) {
className = qname.substring(qname.lastIndexOf('.') + 1);
} else {
className = getSimpleName(typeDecl);
}
if (oracle.findType(qname) != null) {
return;
}
String jpkgName = getPackage(typeDecl);
JPackage pkg = oracle.getOrCreatePackage(jpkgName);
final boolean jclassIsIntf = isInterface(typeDecl);
boolean jclassIsAnnonation = isAnnotation(typeDecl);
CompilationUnitProvider cup = getCup(typeDecl);
int declStart = typeDecl.declarationSourceStart;
int declEnd = typeDecl.declarationSourceEnd;
int bodyStart = typeDecl.bodyStart;
int bodyEnd = typeDecl.bodyEnd;
JRealClassType jrealClassType;
if (jclassIsAnnonation) {
jrealClassType = new JAnnotationType(oracle, cup, pkg, jenclosingType,
isLocalType, className, declStart, declEnd, bodyStart, bodyEnd,
jclassIsIntf);
} else if (maybeGeneric(typeDecl, jenclosingType)) {
// Go through and create declarations for each of the type parameters on
// the generic class or method
JTypeParameter[] jtypeParameters = declareTypeParameters(typeDecl.typeParameters);
JGenericType jgenericType = new JGenericType(oracle, cup, pkg,
jenclosingType, isLocalType, className, declStart, declEnd,
bodyStart, bodyEnd, jclassIsIntf, jtypeParameters);
jrealClassType = jgenericType;
} else if (binding.isEnum()) {
jrealClassType = new JEnumType(oracle, cup, pkg, jenclosingType,
isLocalType, className, declStart, declEnd, bodyStart, bodyEnd,
jclassIsIntf);
} else {
jrealClassType = new JRealClassType(oracle, cup, pkg, jenclosingType,
isLocalType, className, declStart, declEnd, bodyStart, bodyEnd,
jclassIsIntf);
}
cacheManager.setTypeForBinding(binding, jrealClassType);
}
private boolean resolveAnnotation(
TreeLogger logger,
Annotation jannotation,
Map<Class<? extends java.lang.annotation.Annotation>, java.lang.annotation.Annotation> declaredAnnotations) {
logger = logger.branch(TreeLogger.SPAM, "Resolving annotation '"
+ jannotation.printExpression(0, new StringBuffer()).toString() + "'",
null);
// Determine the annotation class
TypeBinding resolvedType = jannotation.resolvedType;
Class<? extends java.lang.annotation.Annotation> clazz = (Class<? extends java.lang.annotation.Annotation>) getClassLiteral(
logger, resolvedType);
if (clazz == null) {
return false;
}
java.lang.annotation.Annotation annotation = (java.lang.annotation.Annotation) createAnnotationInstance(
logger, jannotation);
if (annotation == null) {
return false;
}
declaredAnnotations.put(clazz, annotation);
return true;
}
private boolean resolveAnnotations(
TreeLogger logger,
Annotation[] annotations,
Map<Class<? extends java.lang.annotation.Annotation>, java.lang.annotation.Annotation> declaredAnnotations) {
boolean succeeded = true;
if (annotations != null) {
for (Annotation annotation : annotations) {
succeeded &= resolveAnnotation(logger, annotation, declaredAnnotations);
}
}
return succeeded;
}
private boolean resolveBoundForTypeParameter(TreeLogger logger,
HasTypeParameters genericElement, TypeParameter typeParameter, int ordinal) {
JBound jbounds = createTypeParameterBounds(logger, typeParameter.binding);
if (jbounds == null) {
return false;
}
genericElement.getTypeParameters()[ordinal].setBounds(jbounds);
return true;
}
private boolean resolveBoundsForTypeParameters(TreeLogger logger,
HasTypeParameters genericElement, TypeParameter[] typeParameters) {
if (typeParameters != null) {
for (int i = 0; i < typeParameters.length; ++i) {
if (!resolveBoundForTypeParameter(logger, genericElement,
typeParameters[i], i)) {
return false;
}
}
}
return true;
}
private boolean resolveField(TreeLogger logger, char[] unitSource,
JClassType enclosingType, FieldDeclaration jfield) {
if (jfield instanceof Initializer) {
// Pretend we didn't see this.
//
return true;
}
// Try to resolve annotations, ignore any that fail.
Map<Class<? extends java.lang.annotation.Annotation>, java.lang.annotation.Annotation> declaredAnnotations = newAnnotationMap();
resolveAnnotations(logger, jfield.annotations, declaredAnnotations);
String name = String.valueOf(jfield.name);
JField field;
if (jfield.getKind() == AbstractVariableDeclaration.ENUM_CONSTANT) {
assert (enclosingType.isEnum() != null);
field = new JEnumConstant(enclosingType, name, declaredAnnotations,
jfield.binding.original().id);
} else {
field = new JField(enclosingType, name, declaredAnnotations);
}
// Get modifiers.
//
field.addModifierBits(Shared.bindingToModifierBits(jfield.binding));
// Set the field type.
//
TypeBinding jfieldType = jfield.binding.type;
JType fieldType = resolveType(logger, jfieldType);
if (fieldType == null) {
// Unresolved type.
//
return false;
}
field.setType(fieldType);
// Get tags.
//
if (jfield.javadoc != null) {
if (!parseMetaDataTags(unitSource, field, jfield.javadoc)) {
return false;
}
}
return true;
}
private boolean resolveFields(TreeLogger logger, char[] unitSource,
JClassType type, FieldDeclaration[] jfields) {
if (jfields != null) {
for (int i = 0; i < jfields.length; i++) {
FieldDeclaration jfield = jfields[i];
if (!resolveField(logger, unitSource, type, jfield)) {
return false;
}
}
}
return true;
}
private boolean resolveMethod(TreeLogger logger, char[] unitSource,
JClassType enclosingType, AbstractMethodDeclaration jmethod) {
if (jmethod instanceof Clinit) {
// Pretend we didn't see this.
//
return true;
}
int declStart = jmethod.declarationSourceStart;
int declEnd = jmethod.declarationSourceEnd;
int bodyStart = jmethod.bodyStart;
int bodyEnd = jmethod.bodyEnd;
String name = getMethodName(enclosingType, jmethod);
// Try to resolve annotations, ignore any that fail.
Map<Class<? extends java.lang.annotation.Annotation>, java.lang.annotation.Annotation> declaredAnnotations = newAnnotationMap();
resolveAnnotations(logger, jmethod.annotations, declaredAnnotations);
JAbstractMethod method;
// Declare the type parameters. We will pass them into the constructors for
// JConstructor/JMethod/JAnnotatedMethod. Then, we'll do a second pass to
// resolve the bounds on each JTypeParameter object.
JTypeParameter[] jtypeParameters = declareTypeParameters(jmethod.typeParameters());
if (jmethod.isConstructor()) {
method = new JConstructor(enclosingType, name, declStart, declEnd,
bodyStart, bodyEnd, declaredAnnotations, jtypeParameters);
// Do a second pass to resolve the bounds on each JTypeParameter.
if (!resolveBoundsForTypeParameters(logger, method,
jmethod.typeParameters())) {
return false;
}
} else {
if (jmethod.isAnnotationMethod()) {
AnnotationMethodDeclaration annotationMethod = (AnnotationMethodDeclaration) jmethod;
Object defaultValue = null;
if (annotationMethod.defaultValue != null) {
defaultValue = evaluateConstantExpression(logger,
annotationMethod.defaultValue);
}
method = new JAnnotationMethod(enclosingType, name, declStart, declEnd,
bodyStart, bodyEnd, defaultValue, declaredAnnotations);
} else {
method = new JMethod(enclosingType, name, declStart, declEnd,
bodyStart, bodyEnd, declaredAnnotations, jtypeParameters);
}
// Do a second pass to resolve the bounds on each JTypeParameter.
// The type parameters must be resolved at this point, because they may
// be used in the resolution of the method's return type.
if (!resolveBoundsForTypeParameters(logger, method,
jmethod.typeParameters())) {
return false;
}
TypeBinding jreturnType = ((MethodDeclaration) jmethod).returnType.resolvedType;
JType returnType = resolveType(logger, jreturnType);
if (returnType == null) {
// Unresolved type.
//
return false;
}
((JMethod) method).setReturnType(returnType);
}
// Parse modifiers.
//
method.addModifierBits(Shared.bindingToModifierBits(jmethod.binding));
if (enclosingType.isInterface() != null) {
// Always add implicit modifiers on interface methods.
//
method.addModifierBits(Shared.MOD_PUBLIC | Shared.MOD_ABSTRACT);
}
// Add the parameters.
//
Argument[] jparams = jmethod.arguments;
if (!resolveParameters(logger, method, jparams)) {
return false;
}
// Add throws.
//
TypeReference[] jthrows = jmethod.thrownExceptions;
if (!resolveThrownTypes(logger, method, jthrows)) {
return false;
}
// Get tags.
//
if (jmethod.javadoc != null) {
if (!parseMetaDataTags(unitSource, method, jmethod.javadoc)) {
return false;
}
}
return true;
}
private boolean resolveMethods(TreeLogger logger, char[] unitSource,
JClassType type, AbstractMethodDeclaration[] jmethods) {
if (jmethods != null) {
for (int i = 0; i < jmethods.length; i++) {
AbstractMethodDeclaration jmethod = jmethods[i];
if (!resolveMethod(logger, unitSource, type, jmethod)) {
return false;
}
}
}
return true;
}
private boolean resolvePackage(TreeLogger logger, TypeDeclaration jclass) {
SourceTypeBinding binding = jclass.binding;
TypeOracle oracle = cacheManager.getTypeOracle();
String packageName = String.valueOf(binding.fPackage.readableName());
JPackage pkg = oracle.getOrCreatePackage(packageName);
assert (pkg != null);
CompilationUnitScope cus = (CompilationUnitScope) jclass.scope.parent;
assert (cus != null);
// Try to resolve annotations, ignore any that fail.
Map<Class<? extends java.lang.annotation.Annotation>, java.lang.annotation.Annotation> declaredAnnotations = newAnnotationMap();
resolveAnnotations(logger, cus.referenceContext.currentPackage.annotations,
declaredAnnotations);
pkg.addAnnotations(declaredAnnotations);
return true;
}
private boolean resolveParameter(TreeLogger logger, JAbstractMethod method,
Argument jparam) {
TypeBinding jtype = jparam.binding.type;
JType type = resolveType(logger, jtype);
if (type == null) {
// Unresolved.
//
return false;
}
// Try to resolve annotations, ignore any that fail.
Map<Class<? extends java.lang.annotation.Annotation>, java.lang.annotation.Annotation> declaredAnnotations = newAnnotationMap();
resolveAnnotations(logger, jparam.annotations, declaredAnnotations);
String name = String.valueOf(jparam.name);
new JParameter(method, type, name, declaredAnnotations);
if (jparam.isVarArgs()) {
method.setVarArgs();
}
return true;
}
private boolean resolveParameters(TreeLogger logger, JAbstractMethod method,
Argument[] jparams) {
if (jparams != null) {
for (int i = 0; i < jparams.length; i++) {
Argument jparam = jparams[i];
if (!resolveParameter(logger, method, jparam)) {
return false;
}
}
}
return true;
}
private boolean resolveThrownType(TreeLogger logger, JAbstractMethod method,
TypeReference jthrown) {
JType type = resolveType(logger, jthrown.resolvedType);
if (type == null) {
// Not resolved.
//
return false;
}
method.addThrows(type);
return true;
}
private boolean resolveThrownTypes(TreeLogger logger, JAbstractMethod method,
TypeReference[] jthrows) {
if (jthrows != null) {
for (int i = 0; i < jthrows.length; i++) {
TypeReference jthrown = jthrows[i];
if (!resolveThrownType(logger, method, jthrown)) {
return false;
}
}
}
return true;
}
private JType resolveType(TreeLogger logger, TypeBinding binding) {
TypeOracle oracle = cacheManager.getTypeOracle();
// Check for primitives.
//
if (binding instanceof BaseTypeBinding) {
switch (binding.id) {
case TypeIds.T_boolean:
return JPrimitiveType.BOOLEAN;
case TypeIds.T_byte:
return JPrimitiveType.BYTE;
case TypeIds.T_char:
return JPrimitiveType.CHAR;
case TypeIds.T_short:
return JPrimitiveType.SHORT;
case TypeIds.T_int:
return JPrimitiveType.INT;
case TypeIds.T_long:
return JPrimitiveType.LONG;
case TypeIds.T_float:
return JPrimitiveType.FLOAT;
case TypeIds.T_double:
return JPrimitiveType.DOUBLE;
case TypeIds.T_void:
return JPrimitiveType.VOID;
default:
assert false : "Unexpected base type id " + binding.id;
}
}
/*
* Check for a user-defined type, which may be either a SourceTypeBinding or
* a RawTypeBinding. Both of these are subclasses of ReferenceBinding and
* all the functionality we need is on ReferenceBinding, so we cast it to
* that and deal with them in common code.
*
* TODO: do we need to do anything more with raw types?
*/
if (binding instanceof SourceTypeBinding
|| binding instanceof RawTypeBinding) {
ReferenceBinding referenceBinding = (ReferenceBinding) binding;
// First check the type oracle to prefer type identity with the type
// oracle we're assimilating into.
//
String typeName = getQualifiedName(referenceBinding);
JType resolvedType = oracle.findType(typeName);
if (resolvedType == null) {
// Otherwise, it should be something we've mapped during this build.
resolvedType = cacheManager.getTypeForBinding(referenceBinding);
}
if (resolvedType != null) {
if (binding instanceof RawTypeBinding) {
// Use the raw type instead of the generic type.
JGenericType genericType = (JGenericType) resolvedType;
resolvedType = genericType.getRawType();
}
return resolvedType;
}
}
// Check for an array.
//
if (binding instanceof ArrayBinding) {
ArrayBinding arrayBinding = (ArrayBinding) binding;
// Start by resolving the leaf type.
//
TypeBinding leafBinding = arrayBinding.leafComponentType;
JType resolvedType = resolveType(logger, leafBinding);
if (resolvedType != null) {
int dims = arrayBinding.dimensions;
for (int i = 0; i < dims; ++i) {
// By using the oracle to intern, we guarantee correct identity
// mapping of lazily-created array types.
//
resolvedType = oracle.getArrayType(resolvedType);
}
return resolvedType;
} else {
// Fall-through to failure.
//
}
}
// Check for parameterized.
if (binding instanceof ParameterizedTypeBinding) {
ParameterizedTypeBinding ptBinding = (ParameterizedTypeBinding) binding;
/*
* NOTE: it is possible for ParameterizedTypeBinding.arguments to be null.
* This can happen if a generic class has a non-static, non-generic, inner
* class that references a TypeParameter from its enclosing generic type.
* You would think that typeVariables() would do the right thing but it
* does not.
*/
TypeBinding[] arguments = ptBinding.arguments;
int nArguments = arguments != null ? arguments.length : 0;
JClassType[] typeArguments = new JClassType[nArguments];
boolean failed = false;
for (int i = 0; i < typeArguments.length; ++i) {
typeArguments[i] = (JClassType) resolveType(logger, arguments[i]);
if (typeArguments[i] == null) {
failed = true;
}
}
JClassType enclosingType = null;
if (ptBinding.enclosingType() != null) {
enclosingType = (JClassType) resolveType(logger,
ptBinding.enclosingType());
if (enclosingType == null) {
failed = true;
}
}
/*
* NOTE: In the case where a generic type has a nested, non-static,
* non-generic type. The type for the binding will not be a generic type.
*/
JType resolveType = resolveType(logger, ptBinding.type);
if (resolveType == null) {
failed = true;
}
if (!failed) {
if (resolveType.isGenericType() != null) {
return oracle.getParameterizedType(resolveType.isGenericType(),
enclosingType, typeArguments);
} else {
/*
* A static type (enum or class) that does not declare any type
* parameters that is nested within a generic type might be referenced
* via a parameterized type by JDT. In this case we just return the
* type and don't treat it as a parameterized.
*/
return resolveType;
}
} else {
// Fall-through to failure
}
}
if (binding instanceof TypeVariableBinding) {
TypeVariableBinding tvBinding = (TypeVariableBinding) binding;
JTypeParameter typeParameter = (JTypeParameter) cacheManager.getTypeForBinding(tvBinding);
assert (typeParameter != null);
return typeParameter;
}
if (binding instanceof WildcardBinding) {
WildcardBinding wcBinding = (WildcardBinding) binding;
assert (wcBinding.otherBounds == null);
JBound bounds;
switch (wcBinding.boundKind) {
case Wildcard.EXTENDS: {
assert (wcBinding.bound != null);
JClassType upperBound = (JClassType) resolveType(logger,
wcBinding.bound);
bounds = new JUpperBound(new JClassType[] {upperBound});
}
break;
case Wildcard.SUPER: {
assert (wcBinding.bound != null);
JClassType lowerBound = (JClassType) resolveType(logger,
wcBinding.bound);
bounds = new JLowerBound(new JClassType[] {lowerBound});
}
break;
case Wildcard.UNBOUND: {
JClassType upperBound = (JClassType) resolveType(logger,
wcBinding.erasure());
bounds = new JUpperBound(new JClassType[] {upperBound});
- assert (bounds.getFirstBound().getQualifiedSourceName().equals("java.lang.Object"));
}
break;
default:
assert false : "WildcardBinding of unknown boundKind???";
return null;
}
return oracle.getWildcardType(bounds);
}
// Log other cases we know about that don't make sense.
//
String name = String.valueOf(binding.readableName());
logger = logger.branch(TreeLogger.WARN, "Unable to resolve type: " + name
+ " binding: " + binding.getClass().getCanonicalName(), null);
if (binding instanceof BinaryTypeBinding) {
logger.log(TreeLogger.WARN,
"Source not available for this type, so it cannot be resolved", null);
}
return null;
}
private boolean resolveTypeDeclaration(TreeLogger logger, char[] unitSource,
TypeDeclaration clazz) {
SourceTypeBinding binding = clazz.binding;
if (binding.constantPoolName() == null) {
/*
* Weird case: if JDT determines that this local class is totally
* uninstantiable, it won't bother allocating a local name.
*/
return true;
}
String qname = String.valueOf(binding.qualifiedSourceName());
logger = logger.branch(TreeLogger.SPAM, "Found type '" + qname + "'", null);
// Handle package-info classes.
if (isPackageInfoTypeName(qname)) {
return resolvePackage(logger, clazz);
}
// Just resolve the type.
JRealClassType jtype = (JRealClassType) resolveType(logger, binding);
if (jtype == null) {
// Failed to resolve.
//
return false;
}
// Add modifiers.
//
jtype.addModifierBits(Shared.bindingToModifierBits(clazz.binding));
// Try to resolve annotations, ignore any that fail.
Map<Class<? extends java.lang.annotation.Annotation>, java.lang.annotation.Annotation> declaredAnnotations = newAnnotationMap();
resolveAnnotations(logger, clazz.annotations, declaredAnnotations);
jtype.addAnnotations(declaredAnnotations);
// Resolve bounds for type parameters on generic types. Note that this
// step does not apply to type parameters on generic methods; that
// occurs during the method resolution stage.
JGenericType jGenericType = jtype.isGenericType();
if (jGenericType != null
&& !resolveBoundsForTypeParameters(logger, jtype.isGenericType(),
clazz.typeParameters)) {
// Failed to resolve
return false;
}
// Resolve superclass (for classes only).
//
if (jtype.isInterface() == null) {
ReferenceBinding superclassRef = binding.superclass;
if (superclassRef != null) {
JClassType jsuperClass = (JClassType) resolveType(logger, superclassRef);
if (jsuperClass == null) {
return false;
}
jtype.setSuperclass(jsuperClass);
}
}
// Resolve superinterfaces.
//
ReferenceBinding[] superintfRefs = binding.superInterfaces;
for (int i = 0; i < superintfRefs.length; i++) {
ReferenceBinding superintfRef = superintfRefs[i];
JClassType jinterface = (JClassType) resolveType(logger, superintfRef);
if (jinterface == null) {
// Failed to resolve.
//
return false;
}
jtype.addImplementedInterface(jinterface);
}
// Resolve fields.
//
FieldDeclaration[] fields = clazz.fields;
if (!resolveFields(logger, unitSource, jtype, fields)) {
return false;
}
// Resolve methods. This also involves the declaration of type
// variables on generic methods, and the resolution of the bounds
// on these type variables.
// One would think that it would be better to perform the declaration
// of type variables on methods at the time when we are processing
// all of the classes. Unfortunately, when we are processing classes,
// we do not have enough information about their methods to analyze
// their type variables. Hence, the type variable declaration and
// bounds resolution for generic methods must happen after the resolution
// of methods is complete.
AbstractMethodDeclaration[] methods = clazz.methods;
if (!resolveMethods(logger, unitSource, jtype, methods)) {
return false;
}
// Get tags.
//
if (clazz.javadoc != null) {
if (!parseMetaDataTags(unitSource, jtype, clazz.javadoc)) {
return false;
}
}
return true;
}
}
| true | true | private JType resolveType(TreeLogger logger, TypeBinding binding) {
TypeOracle oracle = cacheManager.getTypeOracle();
// Check for primitives.
//
if (binding instanceof BaseTypeBinding) {
switch (binding.id) {
case TypeIds.T_boolean:
return JPrimitiveType.BOOLEAN;
case TypeIds.T_byte:
return JPrimitiveType.BYTE;
case TypeIds.T_char:
return JPrimitiveType.CHAR;
case TypeIds.T_short:
return JPrimitiveType.SHORT;
case TypeIds.T_int:
return JPrimitiveType.INT;
case TypeIds.T_long:
return JPrimitiveType.LONG;
case TypeIds.T_float:
return JPrimitiveType.FLOAT;
case TypeIds.T_double:
return JPrimitiveType.DOUBLE;
case TypeIds.T_void:
return JPrimitiveType.VOID;
default:
assert false : "Unexpected base type id " + binding.id;
}
}
/*
* Check for a user-defined type, which may be either a SourceTypeBinding or
* a RawTypeBinding. Both of these are subclasses of ReferenceBinding and
* all the functionality we need is on ReferenceBinding, so we cast it to
* that and deal with them in common code.
*
* TODO: do we need to do anything more with raw types?
*/
if (binding instanceof SourceTypeBinding
|| binding instanceof RawTypeBinding) {
ReferenceBinding referenceBinding = (ReferenceBinding) binding;
// First check the type oracle to prefer type identity with the type
// oracle we're assimilating into.
//
String typeName = getQualifiedName(referenceBinding);
JType resolvedType = oracle.findType(typeName);
if (resolvedType == null) {
// Otherwise, it should be something we've mapped during this build.
resolvedType = cacheManager.getTypeForBinding(referenceBinding);
}
if (resolvedType != null) {
if (binding instanceof RawTypeBinding) {
// Use the raw type instead of the generic type.
JGenericType genericType = (JGenericType) resolvedType;
resolvedType = genericType.getRawType();
}
return resolvedType;
}
}
// Check for an array.
//
if (binding instanceof ArrayBinding) {
ArrayBinding arrayBinding = (ArrayBinding) binding;
// Start by resolving the leaf type.
//
TypeBinding leafBinding = arrayBinding.leafComponentType;
JType resolvedType = resolveType(logger, leafBinding);
if (resolvedType != null) {
int dims = arrayBinding.dimensions;
for (int i = 0; i < dims; ++i) {
// By using the oracle to intern, we guarantee correct identity
// mapping of lazily-created array types.
//
resolvedType = oracle.getArrayType(resolvedType);
}
return resolvedType;
} else {
// Fall-through to failure.
//
}
}
// Check for parameterized.
if (binding instanceof ParameterizedTypeBinding) {
ParameterizedTypeBinding ptBinding = (ParameterizedTypeBinding) binding;
/*
* NOTE: it is possible for ParameterizedTypeBinding.arguments to be null.
* This can happen if a generic class has a non-static, non-generic, inner
* class that references a TypeParameter from its enclosing generic type.
* You would think that typeVariables() would do the right thing but it
* does not.
*/
TypeBinding[] arguments = ptBinding.arguments;
int nArguments = arguments != null ? arguments.length : 0;
JClassType[] typeArguments = new JClassType[nArguments];
boolean failed = false;
for (int i = 0; i < typeArguments.length; ++i) {
typeArguments[i] = (JClassType) resolveType(logger, arguments[i]);
if (typeArguments[i] == null) {
failed = true;
}
}
JClassType enclosingType = null;
if (ptBinding.enclosingType() != null) {
enclosingType = (JClassType) resolveType(logger,
ptBinding.enclosingType());
if (enclosingType == null) {
failed = true;
}
}
/*
* NOTE: In the case where a generic type has a nested, non-static,
* non-generic type. The type for the binding will not be a generic type.
*/
JType resolveType = resolveType(logger, ptBinding.type);
if (resolveType == null) {
failed = true;
}
if (!failed) {
if (resolveType.isGenericType() != null) {
return oracle.getParameterizedType(resolveType.isGenericType(),
enclosingType, typeArguments);
} else {
/*
* A static type (enum or class) that does not declare any type
* parameters that is nested within a generic type might be referenced
* via a parameterized type by JDT. In this case we just return the
* type and don't treat it as a parameterized.
*/
return resolveType;
}
} else {
// Fall-through to failure
}
}
if (binding instanceof TypeVariableBinding) {
TypeVariableBinding tvBinding = (TypeVariableBinding) binding;
JTypeParameter typeParameter = (JTypeParameter) cacheManager.getTypeForBinding(tvBinding);
assert (typeParameter != null);
return typeParameter;
}
if (binding instanceof WildcardBinding) {
WildcardBinding wcBinding = (WildcardBinding) binding;
assert (wcBinding.otherBounds == null);
JBound bounds;
switch (wcBinding.boundKind) {
case Wildcard.EXTENDS: {
assert (wcBinding.bound != null);
JClassType upperBound = (JClassType) resolveType(logger,
wcBinding.bound);
bounds = new JUpperBound(new JClassType[] {upperBound});
}
break;
case Wildcard.SUPER: {
assert (wcBinding.bound != null);
JClassType lowerBound = (JClassType) resolveType(logger,
wcBinding.bound);
bounds = new JLowerBound(new JClassType[] {lowerBound});
}
break;
case Wildcard.UNBOUND: {
JClassType upperBound = (JClassType) resolveType(logger,
wcBinding.erasure());
bounds = new JUpperBound(new JClassType[] {upperBound});
assert (bounds.getFirstBound().getQualifiedSourceName().equals("java.lang.Object"));
}
break;
default:
assert false : "WildcardBinding of unknown boundKind???";
return null;
}
return oracle.getWildcardType(bounds);
}
// Log other cases we know about that don't make sense.
//
String name = String.valueOf(binding.readableName());
logger = logger.branch(TreeLogger.WARN, "Unable to resolve type: " + name
+ " binding: " + binding.getClass().getCanonicalName(), null);
if (binding instanceof BinaryTypeBinding) {
logger.log(TreeLogger.WARN,
"Source not available for this type, so it cannot be resolved", null);
}
return null;
}
| private JType resolveType(TreeLogger logger, TypeBinding binding) {
TypeOracle oracle = cacheManager.getTypeOracle();
// Check for primitives.
//
if (binding instanceof BaseTypeBinding) {
switch (binding.id) {
case TypeIds.T_boolean:
return JPrimitiveType.BOOLEAN;
case TypeIds.T_byte:
return JPrimitiveType.BYTE;
case TypeIds.T_char:
return JPrimitiveType.CHAR;
case TypeIds.T_short:
return JPrimitiveType.SHORT;
case TypeIds.T_int:
return JPrimitiveType.INT;
case TypeIds.T_long:
return JPrimitiveType.LONG;
case TypeIds.T_float:
return JPrimitiveType.FLOAT;
case TypeIds.T_double:
return JPrimitiveType.DOUBLE;
case TypeIds.T_void:
return JPrimitiveType.VOID;
default:
assert false : "Unexpected base type id " + binding.id;
}
}
/*
* Check for a user-defined type, which may be either a SourceTypeBinding or
* a RawTypeBinding. Both of these are subclasses of ReferenceBinding and
* all the functionality we need is on ReferenceBinding, so we cast it to
* that and deal with them in common code.
*
* TODO: do we need to do anything more with raw types?
*/
if (binding instanceof SourceTypeBinding
|| binding instanceof RawTypeBinding) {
ReferenceBinding referenceBinding = (ReferenceBinding) binding;
// First check the type oracle to prefer type identity with the type
// oracle we're assimilating into.
//
String typeName = getQualifiedName(referenceBinding);
JType resolvedType = oracle.findType(typeName);
if (resolvedType == null) {
// Otherwise, it should be something we've mapped during this build.
resolvedType = cacheManager.getTypeForBinding(referenceBinding);
}
if (resolvedType != null) {
if (binding instanceof RawTypeBinding) {
// Use the raw type instead of the generic type.
JGenericType genericType = (JGenericType) resolvedType;
resolvedType = genericType.getRawType();
}
return resolvedType;
}
}
// Check for an array.
//
if (binding instanceof ArrayBinding) {
ArrayBinding arrayBinding = (ArrayBinding) binding;
// Start by resolving the leaf type.
//
TypeBinding leafBinding = arrayBinding.leafComponentType;
JType resolvedType = resolveType(logger, leafBinding);
if (resolvedType != null) {
int dims = arrayBinding.dimensions;
for (int i = 0; i < dims; ++i) {
// By using the oracle to intern, we guarantee correct identity
// mapping of lazily-created array types.
//
resolvedType = oracle.getArrayType(resolvedType);
}
return resolvedType;
} else {
// Fall-through to failure.
//
}
}
// Check for parameterized.
if (binding instanceof ParameterizedTypeBinding) {
ParameterizedTypeBinding ptBinding = (ParameterizedTypeBinding) binding;
/*
* NOTE: it is possible for ParameterizedTypeBinding.arguments to be null.
* This can happen if a generic class has a non-static, non-generic, inner
* class that references a TypeParameter from its enclosing generic type.
* You would think that typeVariables() would do the right thing but it
* does not.
*/
TypeBinding[] arguments = ptBinding.arguments;
int nArguments = arguments != null ? arguments.length : 0;
JClassType[] typeArguments = new JClassType[nArguments];
boolean failed = false;
for (int i = 0; i < typeArguments.length; ++i) {
typeArguments[i] = (JClassType) resolveType(logger, arguments[i]);
if (typeArguments[i] == null) {
failed = true;
}
}
JClassType enclosingType = null;
if (ptBinding.enclosingType() != null) {
enclosingType = (JClassType) resolveType(logger,
ptBinding.enclosingType());
if (enclosingType == null) {
failed = true;
}
}
/*
* NOTE: In the case where a generic type has a nested, non-static,
* non-generic type. The type for the binding will not be a generic type.
*/
JType resolveType = resolveType(logger, ptBinding.type);
if (resolveType == null) {
failed = true;
}
if (!failed) {
if (resolveType.isGenericType() != null) {
return oracle.getParameterizedType(resolveType.isGenericType(),
enclosingType, typeArguments);
} else {
/*
* A static type (enum or class) that does not declare any type
* parameters that is nested within a generic type might be referenced
* via a parameterized type by JDT. In this case we just return the
* type and don't treat it as a parameterized.
*/
return resolveType;
}
} else {
// Fall-through to failure
}
}
if (binding instanceof TypeVariableBinding) {
TypeVariableBinding tvBinding = (TypeVariableBinding) binding;
JTypeParameter typeParameter = (JTypeParameter) cacheManager.getTypeForBinding(tvBinding);
assert (typeParameter != null);
return typeParameter;
}
if (binding instanceof WildcardBinding) {
WildcardBinding wcBinding = (WildcardBinding) binding;
assert (wcBinding.otherBounds == null);
JBound bounds;
switch (wcBinding.boundKind) {
case Wildcard.EXTENDS: {
assert (wcBinding.bound != null);
JClassType upperBound = (JClassType) resolveType(logger,
wcBinding.bound);
bounds = new JUpperBound(new JClassType[] {upperBound});
}
break;
case Wildcard.SUPER: {
assert (wcBinding.bound != null);
JClassType lowerBound = (JClassType) resolveType(logger,
wcBinding.bound);
bounds = new JLowerBound(new JClassType[] {lowerBound});
}
break;
case Wildcard.UNBOUND: {
JClassType upperBound = (JClassType) resolveType(logger,
wcBinding.erasure());
bounds = new JUpperBound(new JClassType[] {upperBound});
}
break;
default:
assert false : "WildcardBinding of unknown boundKind???";
return null;
}
return oracle.getWildcardType(bounds);
}
// Log other cases we know about that don't make sense.
//
String name = String.valueOf(binding.readableName());
logger = logger.branch(TreeLogger.WARN, "Unable to resolve type: " + name
+ " binding: " + binding.getClass().getCanonicalName(), null);
if (binding instanceof BinaryTypeBinding) {
logger.log(TreeLogger.WARN,
"Source not available for this type, so it cannot be resolved", null);
}
return null;
}
|
diff --git a/jsword/src/main/java/org/crosswire/jsword/book/filter/gbf/GBFTagBuilders.java b/jsword/src/main/java/org/crosswire/jsword/book/filter/gbf/GBFTagBuilders.java
index 01f7daef..44f14135 100644
--- a/jsword/src/main/java/org/crosswire/jsword/book/filter/gbf/GBFTagBuilders.java
+++ b/jsword/src/main/java/org/crosswire/jsword/book/filter/gbf/GBFTagBuilders.java
@@ -1,493 +1,492 @@
/**
* Distribution License:
* JSword is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License, version 2.1 as published by
* the Free Software Foundation. This 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.
*
* The License is available on the internet at:
* http://www.gnu.org/copyleft/lgpl.html
* or by writing to:
* Free Software Foundation, Inc.
* 59 Temple Place - Suite 330
* Boston, MA 02111-1307, USA
*
* Copyright: 2005
* The copyright to this program is held by it's authors.
*
* ID: $Id$
*/
package org.crosswire.jsword.book.filter.gbf;
import java.util.HashMap;
import java.util.Map;
import org.crosswire.common.util.Logger;
import org.crosswire.jsword.book.Book;
import org.crosswire.jsword.book.filter.gbf.GBFTags.BoldStartTag;
import org.crosswire.jsword.book.filter.gbf.GBFTags.CrossRefStartTag;
import org.crosswire.jsword.book.filter.gbf.GBFTags.DefaultEndTag;
import org.crosswire.jsword.book.filter.gbf.GBFTags.EOLTag;
import org.crosswire.jsword.book.filter.gbf.GBFTags.FootnoteEndTag;
import org.crosswire.jsword.book.filter.gbf.GBFTags.FootnoteStartTag;
import org.crosswire.jsword.book.filter.gbf.GBFTags.HeaderStartTag;
import org.crosswire.jsword.book.filter.gbf.GBFTags.IgnoredTag;
import org.crosswire.jsword.book.filter.gbf.GBFTags.ItalicStartTag;
import org.crosswire.jsword.book.filter.gbf.GBFTags.JustifyRightTag;
import org.crosswire.jsword.book.filter.gbf.GBFTags.OTQuoteStartTag;
import org.crosswire.jsword.book.filter.gbf.GBFTags.ParagraphTag;
import org.crosswire.jsword.book.filter.gbf.GBFTags.PoetryStartTag;
import org.crosswire.jsword.book.filter.gbf.GBFTags.PsalmStartTag;
import org.crosswire.jsword.book.filter.gbf.GBFTags.RedLetterStartTag;
import org.crosswire.jsword.book.filter.gbf.GBFTags.StrongsMorphTag;
import org.crosswire.jsword.book.filter.gbf.GBFTags.StrongsWordTag;
import org.crosswire.jsword.book.filter.gbf.GBFTags.TextFootnoteTag;
import org.crosswire.jsword.book.filter.gbf.GBFTags.TextTag;
import org.crosswire.jsword.book.filter.gbf.GBFTags.TitleStartTag;
import org.crosswire.jsword.book.filter.gbf.GBFTags.UnderlineStartTag;
import org.crosswire.jsword.passage.Key;
/**
* This class is a convienence to get GBF Tags.
*
* The best place to go for more information about the GBF spec that I have
* found is: <a href="http://ebible.org/bible/gbf.htm">http://ebible.org/bible/gbf.htm</a>
*
* @see gnu.lgpl.License for license details.
* The copyright to this program is held by it's authors.
* @author Joe Walker [joe at eireneh dot com]
* @author DM Smith [dmsmith555 at yahoo dot com]
*/
public final class GBFTagBuilders
{
/**
*
*/
private GBFTagBuilders()
{
}
/**
* @param name
* @return return a GBF Tag for the given tag name
*/
public static Tag getTag(Book book, Key key, String name)
{
Tag tag = null;
int length = name.length();
if (length > 0)
{
// Only the first two letters of the tag are indicative of the tag
// The rest, if present, is data.
TagBuilder builder = null;
if (length == 2)
{
builder = (TagBuilder) BUILDERS.get(name);
}
else
{
builder = (TagBuilder) BUILDERS.get(name.substring(0, 2));
}
- Tag reply = null;
if (builder != null)
{
- reply = builder.createTag(name);
+ tag = builder.createTag(name);
}
- if (reply == null)
+ if (tag == null)
{
// I'm not confident enough that we handle all the GBF tags
// that I will blame the book instead of the program
log.warn("In " + book.getInitials() + "(" + key.getName() + ") ignoring tag of <" + name + ">"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
//DataPolice.report("Ignoring tag of <" + name + ">");
}
}
return tag;
}
/**
* @param text
* @return get a Text Tag object containing the text
*/
public static Tag getTextTag(String text)
{
return new TextTag(text);
}
/**
*
*/
static final class BoldStartTagBuilder implements TagBuilder
{
/* (non-Javadoc)
* @see org.crosswire.jsword.book.filter.gbf.TagBuilder#createTag(java.lang.String)
*/
public Tag createTag(String name)
{
return new BoldStartTag(name);
}
}
/**
*
*/
static final class CrossRefStartTagBuilder implements TagBuilder
{
/* (non-Javadoc)
* @see org.crosswire.jsword.book.filter.gbf.TagBuilder#createTag(java.lang.String)
*/
public Tag createTag(final String name)
{
return new CrossRefStartTag(name);
}
}
/**
*
*/
static final class DefaultEndTagBuilder implements TagBuilder
{
/* (non-Javadoc)
* @see org.crosswire.jsword.book.filter.gbf.TagBuilder#createTag(java.lang.String)
*/
public Tag createTag(String name)
{
return new DefaultEndTag(name);
}
}
/**
*
*/
static final class EndOfLineTagBuilder implements TagBuilder
{
/* (non-Javadoc)
* @see org.crosswire.jsword.book.filter.gbf.TagBuilder#createTag(java.lang.String)
*/
public Tag createTag(final String name)
{
return new EOLTag(name);
}
}
/**
*
*/
static final class EscapeTagBuilder implements TagBuilder
{
/* (non-Javadoc)
* @see org.crosswire.jsword.book.filter.gbf.TagBuilder#createTag(java.lang.String)
*/
public Tag createTag(final String name)
{
if ("CG".equals(name)) //$NON-NLS-1$
{
return new TextTag(">"); //$NON-NLS-1$
}
// else "CT"
return new TextTag("<"); //$NON-NLS-1$
}
}
/**
*
*/
static final class FootnoteStartTagBuilder implements TagBuilder
{
/* (non-Javadoc)
* @see org.crosswire.jsword.book.filter.gbf.TagBuilder#createTag(java.lang.String)
*/
public Tag createTag(String name)
{
return new FootnoteStartTag(name);
}
}
/**
*
*/
static final class FootnoteEndTagBuilder implements TagBuilder
{
/* (non-Javadoc)
* @see org.crosswire.jsword.book.filter.gbf.TagBuilder#createTag(java.lang.String)
*/
public Tag createTag(String name)
{
return new FootnoteEndTag(name);
}
}
/**
*
*/
static final class HeaderStartTagBuilder implements TagBuilder
{
/* (non-Javadoc)
* @see org.crosswire.jsword.book.filter.gbf.TagBuilder#createTag(java.lang.String)
*/
public Tag createTag(String name)
{
return new HeaderStartTag(name);
}
}
/**
*
*/
static final class IgnoredTagBuilder implements TagBuilder
{
/* (non-Javadoc)
* @see org.crosswire.jsword.book.filter.gbf.TagBuilder#createTag(java.lang.String)
*/
public Tag createTag(final String name)
{
return new IgnoredTag(name);
}
}
/**
*
*/
static final class ItalicStartTagBuilder implements TagBuilder
{
/* (non-Javadoc)
* @see org.crosswire.jsword.book.filter.gbf.TagBuilder#createTag(java.lang.String)
*/
public Tag createTag(String name)
{
return new ItalicStartTag(name);
}
}
/**
*
*/
static final class JustifyRightTagBuilder implements TagBuilder
{
/* (non-Javadoc)
* @see org.crosswire.jsword.book.filter.gbf.TagBuilder#createTag(java.lang.String)
*/
public Tag createTag(String name)
{
return new JustifyRightTag(name);
}
}
/**
*
*/
static final class OTQuoteStartTagBuilder implements TagBuilder
{
/* (non-Javadoc)
* @see org.crosswire.jsword.book.filter.gbf.TagBuilder#createTag(java.lang.String)
*/
public Tag createTag(String name)
{
return new OTQuoteStartTag(name);
}
}
/**
*
*/
static final class ParagraphTagBuilder implements TagBuilder
{
/* (non-Javadoc)
* @see org.crosswire.jsword.book.filter.gbf.TagBuilder#createTag(java.lang.String)
*/
public Tag createTag(String name)
{
return new ParagraphTag(name);
}
}
/**
*
*/
static final class PoetryStartTagBuilder implements TagBuilder
{
/* (non-Javadoc)
* @see org.crosswire.jsword.book.filter.gbf.TagBuilder#createTag(java.lang.String)
*/
public Tag createTag(String name)
{
return new PoetryStartTag(name);
}
}
/**
*
*/
static final class PsalmTitleStartTagBuilder implements TagBuilder
{
/* (non-Javadoc)
* @see org.crosswire.jsword.book.filter.gbf.TagBuilder#createTag(java.lang.String)
*/
public Tag createTag(String name)
{
return new PsalmStartTag(name);
}
}
/**
*
*/
static final class RedLetterStartTagBuilder implements TagBuilder
{
/* (non-Javadoc)
* @see org.crosswire.jsword.book.filter.gbf.TagBuilder#createTag(java.lang.String)
*/
public Tag createTag(String name)
{
return new RedLetterStartTag(name);
}
}
/**
*
*/
static final class StrongsMorphTagBuilder implements TagBuilder
{
/* (non-Javadoc)
* @see org.crosswire.jsword.book.filter.gbf.TagBuilder#createTag(java.lang.String)
*/
public Tag createTag(final String name)
{
return new StrongsMorphTag(name);
}
}
/**
*
*/
static final class StrongsWordTagBuilder implements TagBuilder
{
/* (non-Javadoc)
* @see org.crosswire.jsword.book.filter.gbf.TagBuilder#createTag(java.lang.String)
*/
public Tag createTag(final String name)
{
return new StrongsWordTag(name);
}
}
/**
*
*/
static final class TextFootnoteTagBuilder implements TagBuilder
{
/* (non-Javadoc)
* @see org.crosswire.jsword.book.filter.gbf.TagBuilder#createTag(java.lang.String)
*/
public Tag createTag(String name)
{
return new TextFootnoteTag(name);
}
}
/**
*
*/
static final class TitleStartTagBuilder implements TagBuilder
{
/* (non-Javadoc)
* @see org.crosswire.jsword.book.filter.gbf.TagBuilder#createTag(java.lang.String)
*/
public Tag createTag(String name)
{
return new TitleStartTag(name);
}
}
/**
*
*/
static final class UnderlineStartTagBuilder implements TagBuilder
{
/* (non-Javadoc)
* @see org.crosswire.jsword.book.filter.gbf.TagBuilder#createTag(java.lang.String)
*/
public Tag createTag(String name)
{
return new UnderlineStartTag(name);
}
}
/**
* The log stream
*/
private static final Logger log = Logger.getLogger(GBFTagBuilders.class);
/**
* The <code>BUILDERS</code> maps the 2 letter GBF tag to a class that proxies for the tag.
*/
private static final Map BUILDERS = new HashMap();
static
{
TagBuilder defaultEndTagBuilder = new DefaultEndTagBuilder();
TagBuilder ignoreTagBuilder = new IgnoredTagBuilder();
BUILDERS.put("FB", new BoldStartTagBuilder()); //$NON-NLS-1$
BUILDERS.put("Fb", defaultEndTagBuilder); //$NON-NLS-1$
BUILDERS.put("FI", new ItalicStartTagBuilder()); //$NON-NLS-1$
BUILDERS.put("Fi", defaultEndTagBuilder); //$NON-NLS-1$
BUILDERS.put("FR", new RedLetterStartTagBuilder()); //$NON-NLS-1$
BUILDERS.put("Fr", defaultEndTagBuilder); //$NON-NLS-1$
BUILDERS.put("FU", new UnderlineStartTagBuilder()); //$NON-NLS-1$
BUILDERS.put("Fu", defaultEndTagBuilder); //$NON-NLS-1$
BUILDERS.put("RX", new CrossRefStartTagBuilder()); //$NON-NLS-1$
BUILDERS.put("Rx", defaultEndTagBuilder); //$NON-NLS-1$
BUILDERS.put("CL", new EndOfLineTagBuilder()); //$NON-NLS-1$
BUILDERS.put("CM", new ParagraphTagBuilder()); //$NON-NLS-1$
BUILDERS.put("RF", new FootnoteStartTagBuilder()); //$NON-NLS-1$
BUILDERS.put("Rf", new FootnoteEndTagBuilder()); //$NON-NLS-1$
BUILDERS.put("RB", new TextFootnoteTagBuilder()); //$NON-NLS-1$
BUILDERS.put("TS", new HeaderStartTagBuilder()); //$NON-NLS-1$
BUILDERS.put("Ts", defaultEndTagBuilder); //$NON-NLS-1$
BUILDERS.put("TB", new PsalmTitleStartTagBuilder()); //$NON-NLS-1$
BUILDERS.put("Tb", defaultEndTagBuilder); //$NON-NLS-1$
BUILDERS.put("TH", new TitleStartTagBuilder()); //$NON-NLS-1$
BUILDERS.put("Th", defaultEndTagBuilder); //$NON-NLS-1$
BUILDERS.put("BA", ignoreTagBuilder); //$NON-NLS-1$
BUILDERS.put("BC", ignoreTagBuilder); //$NON-NLS-1$
BUILDERS.put("BI", ignoreTagBuilder); //$NON-NLS-1$
BUILDERS.put("BN", ignoreTagBuilder); //$NON-NLS-1$
BUILDERS.put("BO", ignoreTagBuilder); //$NON-NLS-1$
BUILDERS.put("BP", ignoreTagBuilder); //$NON-NLS-1$
BUILDERS.put("JR", new JustifyRightTagBuilder()); //$NON-NLS-1$
BUILDERS.put("JL", ignoreTagBuilder); //$NON-NLS-1$
BUILDERS.put("FO", new OTQuoteStartTagBuilder()); //$NON-NLS-1$
BUILDERS.put("Fo", defaultEndTagBuilder); //$NON-NLS-1$
BUILDERS.put("PP", new PoetryStartTagBuilder()); //$NON-NLS-1$
BUILDERS.put("Pp", defaultEndTagBuilder); //$NON-NLS-1$
TagBuilder builder = new StrongsWordTagBuilder();
BUILDERS.put("WH", builder); //$NON-NLS-1$
BUILDERS.put("WG", builder); //$NON-NLS-1$
BUILDERS.put("WT", new StrongsMorphTagBuilder()); //$NON-NLS-1$
BUILDERS.put("CG", new EscapeTagBuilder()); //$NON-NLS-1$
BUILDERS.put("CT", new EscapeTagBuilder()); //$NON-NLS-1$
}
}
| false | true | public static Tag getTag(Book book, Key key, String name)
{
Tag tag = null;
int length = name.length();
if (length > 0)
{
// Only the first two letters of the tag are indicative of the tag
// The rest, if present, is data.
TagBuilder builder = null;
if (length == 2)
{
builder = (TagBuilder) BUILDERS.get(name);
}
else
{
builder = (TagBuilder) BUILDERS.get(name.substring(0, 2));
}
Tag reply = null;
if (builder != null)
{
reply = builder.createTag(name);
}
if (reply == null)
{
// I'm not confident enough that we handle all the GBF tags
// that I will blame the book instead of the program
log.warn("In " + book.getInitials() + "(" + key.getName() + ") ignoring tag of <" + name + ">"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
//DataPolice.report("Ignoring tag of <" + name + ">");
}
}
return tag;
}
| public static Tag getTag(Book book, Key key, String name)
{
Tag tag = null;
int length = name.length();
if (length > 0)
{
// Only the first two letters of the tag are indicative of the tag
// The rest, if present, is data.
TagBuilder builder = null;
if (length == 2)
{
builder = (TagBuilder) BUILDERS.get(name);
}
else
{
builder = (TagBuilder) BUILDERS.get(name.substring(0, 2));
}
if (builder != null)
{
tag = builder.createTag(name);
}
if (tag == null)
{
// I'm not confident enough that we handle all the GBF tags
// that I will blame the book instead of the program
log.warn("In " + book.getInitials() + "(" + key.getName() + ") ignoring tag of <" + name + ">"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
//DataPolice.report("Ignoring tag of <" + name + ">");
}
}
return tag;
}
|
diff --git a/ExtractFlexMetdata.java b/ExtractFlexMetdata.java
index 185af55..46969ad 100644
--- a/ExtractFlexMetdata.java
+++ b/ExtractFlexMetdata.java
@@ -1,36 +1,36 @@
//
// ExtractFlexMetdata.java
//
import java.io.File;
import java.io.FileWriter;
import loci.common.RandomAccessInputStream;
import loci.formats.TiffTools;
/** Convenience method to extract the metadat from all the Flex files present in a directory. */
public class ExtractFlexMetdata {
public static void main(String[] args) throws Exception {
File dir;
if (args.length != 1 || !(dir=new File(args[0])).canRead()) {
System.out.println("Usage: java ExtractFlexMetdata dir");
return;
}
for(File file:dir.listFiles()) {
- if(file.getName().endsWith(".flex"));{
+ if(file.getName().endsWith(".flex")){
String id=file.getPath();
int dot = id.lastIndexOf(".");
String outId = (dot >= 0 ? id.substring(0, dot) : id) + ".xml";
String xml = (String) TiffTools.getIFDValue(TiffTools.getIFDs(new RandomAccessInputStream(id))[0],
65200, true, String.class);
FileWriter writer =new FileWriter(new File(outId));
writer.write(xml);
writer.close();
System.out.println("Writing header of: "+id);
}
}
System.out.println("Done");
}
}
| true | true | public static void main(String[] args) throws Exception {
File dir;
if (args.length != 1 || !(dir=new File(args[0])).canRead()) {
System.out.println("Usage: java ExtractFlexMetdata dir");
return;
}
for(File file:dir.listFiles()) {
if(file.getName().endsWith(".flex"));{
String id=file.getPath();
int dot = id.lastIndexOf(".");
String outId = (dot >= 0 ? id.substring(0, dot) : id) + ".xml";
String xml = (String) TiffTools.getIFDValue(TiffTools.getIFDs(new RandomAccessInputStream(id))[0],
65200, true, String.class);
FileWriter writer =new FileWriter(new File(outId));
writer.write(xml);
writer.close();
System.out.println("Writing header of: "+id);
}
}
System.out.println("Done");
}
| public static void main(String[] args) throws Exception {
File dir;
if (args.length != 1 || !(dir=new File(args[0])).canRead()) {
System.out.println("Usage: java ExtractFlexMetdata dir");
return;
}
for(File file:dir.listFiles()) {
if(file.getName().endsWith(".flex")){
String id=file.getPath();
int dot = id.lastIndexOf(".");
String outId = (dot >= 0 ? id.substring(0, dot) : id) + ".xml";
String xml = (String) TiffTools.getIFDValue(TiffTools.getIFDs(new RandomAccessInputStream(id))[0],
65200, true, String.class);
FileWriter writer =new FileWriter(new File(outId));
writer.write(xml);
writer.close();
System.out.println("Writing header of: "+id);
}
}
System.out.println("Done");
}
|
diff --git a/src/test/java/com/wikia/webdriver/TestCases/SignUpTests/SignUpTests_account_creation.java b/src/test/java/com/wikia/webdriver/TestCases/SignUpTests/SignUpTests_account_creation.java
index 861ca48..a1864ff 100644
--- a/src/test/java/com/wikia/webdriver/TestCases/SignUpTests/SignUpTests_account_creation.java
+++ b/src/test/java/com/wikia/webdriver/TestCases/SignUpTests/SignUpTests_account_creation.java
@@ -1,252 +1,252 @@
package com.wikia.webdriver.TestCases.SignUpTests;
import org.apache.commons.lang.RandomStringUtils;
import org.testng.annotations.Test;
import com.wikia.webdriver.Common.Core.CommonFunctions;
import com.wikia.webdriver.Common.Core.MailFunctions;
import com.wikia.webdriver.Common.Properties.Properties;
import com.wikia.webdriver.Common.Templates.TestTemplate;
import com.wikia.webdriver.PageObjectsFactory.ComponentObject.CustomizedToolbar.CustomizedToolbarComponentObject;
import com.wikia.webdriver.PageObjectsFactory.PageObject.SignUp.AlmostTherePageObject;
import com.wikia.webdriver.PageObjectsFactory.PageObject.SignUp.ConfirmationPageObject;
import com.wikia.webdriver.PageObjectsFactory.PageObject.SignUp.SignUpPageObject;
import com.wikia.webdriver.PageObjectsFactory.PageObject.SignUp.UserProfilePageObject;
import com.wikia.webdriver.PageObjectsFactory.PageObject.Special.Login.SpecialUserLoginPageObject;
public class SignUpTests_account_creation extends TestTemplate
{
private String timeStamp, userName, userNameEnc, password, tempPassword, userNameEmail, passwordEmail;
/*
* 3.30 Test Case 2.3.01 Sign up page: Account creation Non latin username
* https://internal.wikia-inc.com/wiki/Global_Log_in_and_Sign_up/Test_Cases:_Sign_up
* */
@Test(groups = {"SignUp_account_creation_TC_001", "SignUp", "Smoke"})
public void SignUp_account_creation_TC_001_non_latin_user_name()
{
userNameEmail = Properties.emailQaart1;
passwordEmail = Properties.emailPasswordQaart1;
SignUpPageObject signUp = new SignUpPageObject(driver);
timeStamp = signUp.getTimeStamp();
userName = Properties.userNameNonLatin+timeStamp;
userNameEnc = Properties.userNameNonLatinEncoded+timeStamp;
password = "QAPassword"+timeStamp;
signUp.openSignUpPage();
signUp.typeInEmail(userNameEmail);
signUp.typeInUserName(userName);
signUp.typeInPassword(password);
signUp.enterBirthDate("11", "11", "1954");
signUp.enterBlurryWord();
AlmostTherePageObject almostTherePage = signUp.submit(userNameEmail, passwordEmail);
almostTherePage.verifyAlmostTherePage();
ConfirmationPageObject confirmPageAlmostThere = almostTherePage.enterActivationLink(userNameEmail, passwordEmail);
confirmPageAlmostThere.typeInUserName(userName);
confirmPageAlmostThere.typeInPassword(password);
UserProfilePageObject userProfile = confirmPageAlmostThere.clickSubmitButton(userNameEmail, passwordEmail);
userProfile.verifyUserLoggedIn(userNameEnc);
CustomizedToolbarComponentObject toolbar = new CustomizedToolbarComponentObject(driver);
toolbar.verifyUserToolBar();
userProfile.verifyWelcomeEmail(userNameEnc, userNameEmail, passwordEmail);
}
/*
* 3.32 Test Case 2.3.03 Sign up page: Account creation Fifty character Username
* https://internal.wikia-inc.com/wiki/Global_Log_in_and_Sign_up/Test_Cases:_Sign_up
* */
@Test(groups = {"SignUp_account_creation_TC_002", "SignUp"})
public void SignUp_account_creation_TC_002_fifty_character_user_name()
{
userNameEmail = Properties.emailQaart2;
passwordEmail = Properties.emailPasswordQaart2;
SignUpPageObject signUp = new SignUpPageObject(driver);
timeStamp = signUp.getTimeStamp();
userName = "Qweasdzxcvqweasdzxcvqweasdzxcvqweasdz"+timeStamp;
password = "QAPassword"+timeStamp;
signUp.openSignUpPage();
signUp.typeInEmail(userNameEmail);
signUp.typeInUserName(userName);
signUp.typeInPassword(password);
signUp.enterBirthDate("11", "11", "1954");
signUp.enterBlurryWord();
AlmostTherePageObject almostTherePage = signUp.submit(userNameEmail, passwordEmail);
almostTherePage.verifyAlmostTherePage();
ConfirmationPageObject confirmPageAlmostThere = almostTherePage.enterActivationLink(userNameEmail, passwordEmail);
confirmPageAlmostThere.typeInUserName(userName);
confirmPageAlmostThere.typeInPassword(password);
UserProfilePageObject userProfile = confirmPageAlmostThere.clickSubmitButton(userNameEmail, passwordEmail);
userProfile.verifyUserLoggedIn(userName);
CustomizedToolbarComponentObject toolbar = new CustomizedToolbarComponentObject(driver);
toolbar.verifyUserToolBar();
userProfile.verifyWelcomeEmail(userName, userNameEmail, passwordEmail);
}
/*
* 3.33 Test Case 2.3.04 Sign up page: Account creation Username contains a backward slash
* https://internal.wikia-inc.com/wiki/Global_Log_in_and_Sign_up/Test_Cases:_Sign_up
* */
@Test(groups = {"SignUp_account_creation_TC_003", "SignUp"})
public void SignUp_account_creation_TC_003_backward_slash_user_name()
{
userNameEmail = Properties.emailQaart3;
passwordEmail = Properties.emailPasswordQaart3;
SignUpPageObject signUp = new SignUpPageObject(driver);
timeStamp = signUp.getTimeStamp();
userName = Properties.userNameWithBackwardSlash+timeStamp;
userNameEnc = Properties.userNameWithBackwardSlashEncoded+timeStamp;
password = "QAPassword"+timeStamp;
signUp.openSignUpPage();
signUp.typeInEmail(userNameEmail);
signUp.typeInUserName(userName);
signUp.typeInPassword(password);
signUp.enterBirthDate("11", "11", "1954");
signUp.enterBlurryWord();
AlmostTherePageObject almostTherePage = signUp.submit(userNameEmail, passwordEmail);
almostTherePage.verifyAlmostTherePage();
ConfirmationPageObject confirmPageAlmostThere = almostTherePage.enterActivationLink(userNameEmail, passwordEmail);
confirmPageAlmostThere.typeInUserName(userName);
confirmPageAlmostThere.typeInPassword(password);
UserProfilePageObject userProfile = confirmPageAlmostThere.clickSubmitButton(userNameEmail, passwordEmail);
userProfile.verifyUserLoggedIn(userNameEnc);
CustomizedToolbarComponentObject toolbar = new CustomizedToolbarComponentObject(driver);
toolbar.verifyUserToolBar();
userProfile.verifyWelcomeEmail(userNameEnc, userNameEmail, passwordEmail);
}
/*
* 3.34 Test Case 2.3.05 Sign up page: Account creation Username contains an underscore
* 3.36 Test Case 2.3.07 Sign up page: Account creation Password is 1 character
* https://internal.wikia-inc.com/wiki/Global_Log_in_and_Sign_up/Test_Cases:_Sign_up
* */
@Test(groups = {"SignUp_account_creation_TC_004", "SignUp"})
public void SignUp_account_creation_TC_004_one_char_password()
{
userNameEmail = Properties.emailQaart4;
passwordEmail = Properties.emailPasswordQaart4;
SignUpPageObject signUp = new SignUpPageObject(driver);
timeStamp = signUp.getTimeStamp();
userName = Properties.userNameWithUnderScore+timeStamp;
password = RandomStringUtils.randomAscii(1);
signUp.openSignUpPage();
signUp.typeInEmail(userNameEmail);
signUp.typeInUserName(userName);
signUp.typeInPassword(password);
signUp.enterBirthDate("11", "11", "1954");
signUp.enterBlurryWord();
AlmostTherePageObject almostTherePage = signUp.submit(userNameEmail, passwordEmail);
almostTherePage.verifyAlmostTherePage();
ConfirmationPageObject confirmPageAlmostThere = almostTherePage.enterActivationLink(userNameEmail, passwordEmail);
confirmPageAlmostThere.typeInUserName(userName);
confirmPageAlmostThere.typeInPassword(password);
UserProfilePageObject userProfile = confirmPageAlmostThere.clickSubmitButton(userNameEmail, passwordEmail);
userProfile.verifyUserLoggedIn(userName);
CustomizedToolbarComponentObject toolbar = new CustomizedToolbarComponentObject(driver);
toolbar.verifyUserToolBar();
userProfile.verifyWelcomeEmail(userName, userNameEmail, passwordEmail);
}
/*
* 3.37 Test Case 2.3.08 Sign up page: Account creation Password is 50 characters
* https://internal.wikia-inc.com/wiki/Global_Log_in_and_Sign_up/Test_Cases:_Sign_up
* */
@Test(groups = {"SignUp_account_creation__005", "SignUp", "Smoke"})
public void SignUp_account_creation_TC_005_fifty_character_password()
{
userNameEmail = Properties.emailQaart1;
passwordEmail = Properties.emailPasswordQaart1;
SignUpPageObject signUp = new SignUpPageObject(driver);
timeStamp = signUp.getTimeStamp();
userName = Properties.userName+timeStamp;
password = RandomStringUtils.randomAscii(50);
signUp.openSignUpPage();
signUp.typeInEmail(userNameEmail);
signUp.typeInUserName(userName);
signUp.typeInPassword(password);
signUp.enterBirthDate("11", "11", "1954");
signUp.enterBlurryWord();
AlmostTherePageObject almostTherePage = signUp.submit(userNameEmail, passwordEmail);
almostTherePage.verifyAlmostTherePage();
ConfirmationPageObject confirmPageAlmostThere = almostTherePage.enterActivationLink(userNameEmail, passwordEmail);
confirmPageAlmostThere.typeInUserName(userName);
confirmPageAlmostThere.typeInPassword(password);
UserProfilePageObject userProfile = confirmPageAlmostThere.clickSubmitButton(userNameEmail, passwordEmail);
userProfile.verifyUserLoggedIn(userName);
CustomizedToolbarComponentObject toolbar = new CustomizedToolbarComponentObject(driver);
toolbar.verifyUserToolBar();
userProfile.verifyWelcomeEmail(userName, userNameEmail, passwordEmail);
}
/*
* 3.38 Test Case 2.3.09 Sign up page: Account creation Birthdate 29-Feb and leap year
* https://internal.wikia-inc.com/wiki/Global_Log_in_and_Sign_up/Test_Cases:_Sign_up
* */
@Test(groups = {"SignUp_account_creation_TC_006", "SignUp"})
public void SignUp_account_creation_TC_006_lap_year()
{
userNameEmail = Properties.emailQaart2;
passwordEmail = Properties.emailPasswordQaart2;
SignUpPageObject signUp = new SignUpPageObject(driver);
timeStamp = signUp.getTimeStamp();
userName = Properties.userName+timeStamp;
password = Properties.password+timeStamp;
signUp.openSignUpPage();
signUp.typeInEmail(userNameEmail);
signUp.typeInUserName(userName);
signUp.typeInPassword(password);
signUp.enterBirthDate("2", "29", "1988");
signUp.enterBlurryWord();
AlmostTherePageObject almostTherePage = signUp.submit(userNameEmail, passwordEmail);
almostTherePage.verifyAlmostTherePage();
ConfirmationPageObject confirmPageAlmostThere = almostTherePage.enterActivationLink(userNameEmail, passwordEmail);
confirmPageAlmostThere.typeInUserName(userName);
confirmPageAlmostThere.typeInPassword(password);
UserProfilePageObject userProfile = confirmPageAlmostThere.clickSubmitButton(userNameEmail, passwordEmail);
userProfile.verifyUserLoggedIn(userName);
CustomizedToolbarComponentObject toolbar = new CustomizedToolbarComponentObject(driver);
toolbar.verifyUserToolBar();
userProfile.verifyWelcomeEmail(userName, userNameEmail, passwordEmail);
}
@Test(groups = {"SignUp_account_creation_TC_007", "SignUp"})
public void SignUp_account_creation_TC_007_forgotYourPassword()
{
userNameEmail = Properties.emailQaart3;
passwordEmail = Properties.emailPasswordQaart3;
SignUpPageObject signUp = new SignUpPageObject(driver);
timeStamp = signUp.getTimeStamp();
userName = Properties.userName+timeStamp;
password = Properties.password+timeStamp;
signUp.openSignUpPage();
signUp.typeInEmail(userNameEmail);
signUp.typeInUserName(userName);
signUp.typeInPassword(password);
signUp.enterBirthDate("2", "29", "1988");
signUp.enterBlurryWord();
AlmostTherePageObject almostTherePage = signUp.submit(userNameEmail, passwordEmail);
almostTherePage.verifyAlmostTherePage();
ConfirmationPageObject confirmPageAlmostThere = almostTherePage.enterActivationLink(userNameEmail, passwordEmail);
confirmPageAlmostThere.typeInUserName(userName);
confirmPageAlmostThere.typeInPassword(password);
UserProfilePageObject userProfile = confirmPageAlmostThere.clickSubmitButton(userNameEmail, passwordEmail);
userProfile.verifyUserLoggedIn(userName);
CustomizedToolbarComponentObject toolbar = new CustomizedToolbarComponentObject(driver);
toolbar.verifyUserToolBar();
userProfile.verifyWelcomeEmail(userName, userNameEmail, passwordEmail);
CommonFunctions.logOut(driver);
SpecialUserLoginPageObject login = new SpecialUserLoginPageObject(driver);
login.openSpecialUserLogin();
login.forgotPassword(userName);
- MailFunctions.deleteAllMails(Properties.email, Properties.emailPassword);
+ MailFunctions.deleteAllMails(userNameEmail, passwordEmail);
tempPassword = MailFunctions.getPasswordFromMailContent((MailFunctions.getFirstMailContent(userNameEmail, passwordEmail)));
login.login(userName, tempPassword);
password = Properties.password+timeStamp;
login.resetPassword(password);
login.verifyUserLoggedIn(userName);
CommonFunctions.logOut(driver);
login.loginAndVerify(userName, password);
CommonFunctions.logOut(driver);
}
}
| true | true | public void SignUp_account_creation_TC_007_forgotYourPassword()
{
userNameEmail = Properties.emailQaart3;
passwordEmail = Properties.emailPasswordQaart3;
SignUpPageObject signUp = new SignUpPageObject(driver);
timeStamp = signUp.getTimeStamp();
userName = Properties.userName+timeStamp;
password = Properties.password+timeStamp;
signUp.openSignUpPage();
signUp.typeInEmail(userNameEmail);
signUp.typeInUserName(userName);
signUp.typeInPassword(password);
signUp.enterBirthDate("2", "29", "1988");
signUp.enterBlurryWord();
AlmostTherePageObject almostTherePage = signUp.submit(userNameEmail, passwordEmail);
almostTherePage.verifyAlmostTherePage();
ConfirmationPageObject confirmPageAlmostThere = almostTherePage.enterActivationLink(userNameEmail, passwordEmail);
confirmPageAlmostThere.typeInUserName(userName);
confirmPageAlmostThere.typeInPassword(password);
UserProfilePageObject userProfile = confirmPageAlmostThere.clickSubmitButton(userNameEmail, passwordEmail);
userProfile.verifyUserLoggedIn(userName);
CustomizedToolbarComponentObject toolbar = new CustomizedToolbarComponentObject(driver);
toolbar.verifyUserToolBar();
userProfile.verifyWelcomeEmail(userName, userNameEmail, passwordEmail);
CommonFunctions.logOut(driver);
SpecialUserLoginPageObject login = new SpecialUserLoginPageObject(driver);
login.openSpecialUserLogin();
login.forgotPassword(userName);
MailFunctions.deleteAllMails(Properties.email, Properties.emailPassword);
tempPassword = MailFunctions.getPasswordFromMailContent((MailFunctions.getFirstMailContent(userNameEmail, passwordEmail)));
login.login(userName, tempPassword);
password = Properties.password+timeStamp;
login.resetPassword(password);
login.verifyUserLoggedIn(userName);
CommonFunctions.logOut(driver);
login.loginAndVerify(userName, password);
CommonFunctions.logOut(driver);
}
| public void SignUp_account_creation_TC_007_forgotYourPassword()
{
userNameEmail = Properties.emailQaart3;
passwordEmail = Properties.emailPasswordQaart3;
SignUpPageObject signUp = new SignUpPageObject(driver);
timeStamp = signUp.getTimeStamp();
userName = Properties.userName+timeStamp;
password = Properties.password+timeStamp;
signUp.openSignUpPage();
signUp.typeInEmail(userNameEmail);
signUp.typeInUserName(userName);
signUp.typeInPassword(password);
signUp.enterBirthDate("2", "29", "1988");
signUp.enterBlurryWord();
AlmostTherePageObject almostTherePage = signUp.submit(userNameEmail, passwordEmail);
almostTherePage.verifyAlmostTherePage();
ConfirmationPageObject confirmPageAlmostThere = almostTherePage.enterActivationLink(userNameEmail, passwordEmail);
confirmPageAlmostThere.typeInUserName(userName);
confirmPageAlmostThere.typeInPassword(password);
UserProfilePageObject userProfile = confirmPageAlmostThere.clickSubmitButton(userNameEmail, passwordEmail);
userProfile.verifyUserLoggedIn(userName);
CustomizedToolbarComponentObject toolbar = new CustomizedToolbarComponentObject(driver);
toolbar.verifyUserToolBar();
userProfile.verifyWelcomeEmail(userName, userNameEmail, passwordEmail);
CommonFunctions.logOut(driver);
SpecialUserLoginPageObject login = new SpecialUserLoginPageObject(driver);
login.openSpecialUserLogin();
login.forgotPassword(userName);
MailFunctions.deleteAllMails(userNameEmail, passwordEmail);
tempPassword = MailFunctions.getPasswordFromMailContent((MailFunctions.getFirstMailContent(userNameEmail, passwordEmail)));
login.login(userName, tempPassword);
password = Properties.password+timeStamp;
login.resetPassword(password);
login.verifyUserLoggedIn(userName);
CommonFunctions.logOut(driver);
login.loginAndVerify(userName, password);
CommonFunctions.logOut(driver);
}
|
diff --git a/jkit/compiler/ClassLoader.java b/jkit/compiler/ClassLoader.java
index c2c9d2c..131147c 100755
--- a/jkit/compiler/ClassLoader.java
+++ b/jkit/compiler/ClassLoader.java
@@ -1,615 +1,615 @@
package jkit.compiler;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.io.*;
import jkit.bytecode.ClassFileReader;
import jkit.jil.tree.Type;
import jkit.util.Pair;
/**
* A ClassLoader is responsible for loading classes from the filesystem. Classes
* are located in either jar files or directories; furthermore, classes may be
* in source or binary (i.e. compiled) form. The ClassLoader will search the
* classpath and/or sourcepath to find classes and (if necessary) compile them.
*
* @author djp
*/
public class ClassLoader {
/**
* The class path is a list of directories and Jar files which must be
* searched in ascending order for *class files*.
*/
private ArrayList<String> classpath = new ArrayList<String>();
/**
* The source path is a list of directories and Jar files which must be
* search in ascending order for *source files*. By default, it is the same
* as the classpath, although this can be overriden (e.g. by using the
* "-sourcepath <path>" command-line option in jkit or javac).
*/
private ArrayList<String> sourcepath;
/**
* A map from class names in the form "xxx.yyy$zzz to Clazz objects. This is
* the master cache of classes which have been loaded during the compilation
* process. Once a class has been entered into the classtable, it will not
* be loaded again.
*/
private HashMap<String,Clazz> classtable = new HashMap<String,Clazz>();
/**
* A PackageInfo object contains information about a particular package,
* including the following information:
*
* 1) where it can be found on the file system (either a directory, or a
* jar file).
*
* 2) what classes it contains.
*
*/
private class PackageInfo {
/**
* The classes field contains those classes contained in this package.
* Class names are represented as strings of the form "xxx$yyy".
*/
public HashSet<String> classes = new HashSet<String>();
/**
* The compiledClasses indicates which classes are definitely compiled.
* This is useful for detecting classes that need to be compiled in
* order to correctly resolve types.
*/
public HashSet<String> compiledClasses = new HashSet<String>();
/**
* The locations list contains the list of locations that have been
* identified for a particular package. Each location identifies either
* a jar file, or a directory. The order of locations found is
* important --- those which come first have higher priority.
*/
public ArrayList<File> locations = new ArrayList<File>();
}
/**
* The packages map maps each package to the classes they contain. For
* example, "java.lang" will map to "String", "Integer" etc. Inner classes
* are appended to their enclosing class using "$" and located in their
* package accordingly. Therefore, for the class "java.util.Map.Entry" there
* will be an entry "Map$Entry" in the "java.util" package.
*/
private HashMap<String, PackageInfo> packages = new HashMap<String, PackageInfo>();
/**
* The ClassCompiler is needed for compiling source files found on the
* sourcepath which are needed to identify inner classes appropriately.
*/
private Compiler compiler = null;
/**
* Construct a ClassLoader with a given classpath. The classpath is a list
* of directory and/or jar file locations (specified according to the local
* file system) which is to be searched for class files. The sourcepath
* (which is used for finding source files) is set the same as the
* classpath.
*
* @param classpath
* A list of directory and/or jar file locations.
* @param compiler
* A class compiler
*/
public ClassLoader(List<String> classpath, Compiler compiler) {
this.sourcepath = new ArrayList<String>(classpath);
this.classpath = new ArrayList<String>(classpath);
this.compiler = compiler;
buildPackageMap();
}
/**
* Construct a ClassLoader with a given classpath and sourcepath. The
* classpath is a list of directory and/or jar file locations (specified
* according to the local file system) which is to be searched for class
* files. The sourcepath is, likewise, a list of directory and/or jar file
* locations which is used for finding source files.
*
* @param sourcepath
* a list of directory and/or jar file locations.
* @param classpath
* a list of directory and/or jar file locations.
* @param compiler
* A class compiler
*/
public ClassLoader(List<String> sourcepath, List<String> classpath,
Compiler compiler) {
this.sourcepath = new ArrayList<String>(sourcepath);
this.classpath = new ArrayList<String>(classpath);
this.compiler = compiler;
buildPackageMap();
}
/**
* This function checks whether the supplied package exists or not.
*
* @param pkg
* The package whose existence we want to check for.
*
* @return true if the package exists, false otherwise.
*/
public boolean isPackage(String pkg) {
// I'm a little suspect about this method. I think it at least needs to
// take an import list
return packages.keySet().contains(pkg);
}
/**
* This methods attempts to resolve the correct package for a class, given a
* list of imports. Resolving the correct package may require loading
* classes as necessary from the classpath and/or compiling classes for
* which only source code is currently available.
*
* @param className
* A class name without package specifier. Inner classes are
* indicated by a "$" separator.
* @param imports
* A list of packages to search through. Packages are searched in
* order of appearance. Note, "java.lang.*" must be included in
* imports if it is to be searched.
* @return A Type.Reference representing the fully qualified class.
* @throws ClassNotFoundException
* if it couldn't resolve the class
*/
public Type.Clazz resolve(String className, List<String> imports)
throws ClassNotFoundException {
if(className.contains(".")) {
throw new IllegalArgumentException("className cannot contain \".\"");
}
for (String imp : imports) {
Type.Clazz ref = null;
if (imp.endsWith(".*")) {
// try and resolve the class
ref = resolveClassName(imp.substring(0, imp.length() - 2),className);
} else {
// The aim of this piece of code is to replicate the way javac
// works.
String impName = imp.substring(imp.lastIndexOf('.') + 1, imp
.length());
String tmp = className.replace('$', '.');
while(tmp.length() > 0) {
if (impName.equals(tmp)) {
// strip off class name itself
String pkg = imp.substring(0, imp.length()
- (1 + tmp.length()));
// now try and resolve it.
ref = resolveClassName(pkg,className);
break;
}
tmp = tmp.substring(0,Math.max(0,tmp.lastIndexOf('.')));
}
}
if(ref != null) { return ref; }
}
throw new ClassNotFoundException(className);
}
/**
* This method attempts to resolve a classname; that is, determine the
* proper package and inner class scope for the class in question. An
* initial package (e.g. "xxx.yyy") suggestion is provided, along with an
* appropriate class name (e.g. "zzz"). If the given package contains "zzz",
* then "xxx.yyy.zzz" is returned. Otherwise, we assume that the package is
* not, in fact, a proper package; rather, it is a package with an inner
* class appended on. Therefore, we transform "xxx.yyy" and "zzz" into "xxx"
* and "yyy$zzz" and check to see whether "xxx.yyy$zzz" exists. If not, we
* recursively check for class "xxx$yyy$zzz" in the default package.
*
* @param pkg
* the package suggestion provided, in the form "xxx.yyy.zzz"
* @param className
* the class name provided, in the form "xxx$yyy"
* @return
*/
protected Type.Clazz resolveClassName(String pkg, String className) {
ArrayList<Pair<String, List<Type.Reference>>> classes = new ArrayList<Pair<String, List<Type.Reference>>>();
String fullClassName = className;
String outerClassName = fullClassName;
boolean firstTime = true;
for (String c : className.split("\\$")) {
if(firstTime) {
outerClassName = c;
}
firstTime=false;
classes.add(new Pair<String, List<Type.Reference>>(c,
new ArrayList<Type.Reference>()));
}
while(pkg != null) {
PackageInfo pkgInfo = packages.get(pkg);
if (pkgInfo != null) {
if(pkgInfo.classes.contains(fullClassName)) {
// Found the class!!
return new Type.Clazz(pkg,classes);
} else if (pkgInfo.classes.contains(outerClassName)
&& !pkgInfo.compiledClasses.contains(outerClassName)) {
// If we get here, then we may have a source file for the
// outer class which has not been compiled yet. Therefore,
// we need to check for this and, if so, compile it to check
// whether or not the inner class we're after is actually
// contain therein.
String ocn = pkg.equals("") ? outerClassName : pkg + "." + outerClassName;
loadClass(ocn,pkgInfo); // this will force a compile
continue; // try again for the same class/pkg combination
} else {
break;
}
} else {
// This import does not correspond to a valid package.
// Therefore, it may be specifying an inner class and we need to check.
outerClassName = pathChild(pkg);
fullClassName = outerClassName + "$" + fullClassName;
classes.add(0, new Pair<String, List<Type.Reference>>(
pathChild(pkg), new ArrayList<Type.Reference>()));
pkg = pathParent(pkg);
}
}
return null;
}
/**
* Load a class from the classpath by searching for it in the sourcepath,
* then in the classpath. If the class has already been loaded, then this is
* returned immediately. Otherwise, the cache of package locations is
* consulted in an effort to find a class or source file representing the
* class in question.
*
* @param ref
* details of class to load
* @throws ClassNotFoundException
* If it couldn't load the class
*/
public Clazz loadClass(Type.Clazz ref) throws ClassNotFoundException {
String name = refName(ref);
// First, look in the classtable to see whether we have loaded this
// class before.
Clazz c = classtable.get(name);
if(c != null) { return c; }
// Second, locate the information we know about the classes package and
// then attempt to locate either a source or class file.
PackageInfo pkgInfo = packages.get(ref.pkg());
if (pkgInfo == null) { throw new ClassNotFoundException("Unable to load class " + name); }
c = loadClass(name,pkgInfo);
if(c == null) { throw new ClassNotFoundException("Unable to load class " + name); }
return c;
}
/**
* This method attempts to read a classfile from a given package.
*
* @param name
* The name of the class to load, in the format
* "xxx.yyy$zzz"
* @param pkgIngo
* Information about the including package, in particular where
* it can be located on the file system.
* @return
*/
private Clazz loadClass(String name, PackageInfo pkgInfo) {
long time = System.currentTimeMillis();
String jarname = name.replace('.','/') + ".class";
String filename = name.replace('.',File.separatorChar);
// The srcFilename gives the filename of the source file. So, if the
// class we're looking for is an inner class, then we need to strip off
// the inner class name(s) to obtain the source file name.
int tmpIndex = filename.indexOf('$');
String srcFilename = tmpIndex >= 0 ? filename.substring(0, tmpIndex) : filename;
for(File location : pkgInfo.locations) {
try {
if (location.getName().endsWith(".jar")) {
// location is a jar file
JarFile jf = new JarFile(location);
JarEntry je = jf.getJarEntry(jarname);
if (je == null) {
return null;
}
ClassFileReader r = new ClassFileReader(jf.getInputStream(je));
compiler.logTimedMessage("Loaded " + location + ":"
+ jarname, System.currentTimeMillis() - time);
Clazz clazz = r.readClass();
// Update our knowledge base of classes.
classtable.put(refName(clazz.type()), clazz);
return clazz;
- } else {
- File classFile = new File(filename + ".class");
- File srcFile = new File(srcFilename + ".java");
+ } else {
+ File classFile = new File(location.getPath(),filename + ".class");
+ File srcFile = new File(location.getPath(),srcFilename + ".java");
if (srcFile.exists()
&& !compiler.isCompiling(srcFile)
&& (!classFile.exists() || classFile.lastModified() < srcFile
.lastModified())) {
// Here, there is a source file, and either there is no class
// file, or the class file is older than the source file.
// Therefore, we need to (re)compile the source file.
List<? extends Clazz> cs = compiler.compile(srcFile);
compiler.logTimedMessage("Compiled " + srcFile, System
.currentTimeMillis()
- time);
for(Clazz c : cs) {
if(refName(c.type()).equals(name)) {
return c;
}
}
throw new RuntimeException(
"internal failure (unreachable code reached!)");
} else if(classFile.exists()) {
// Here, there is no sourcefile, but there is a classfile.
// So, no need to compile --- just load the class file!
ClassFileReader r = new ClassFileReader(new FileInputStream(classFile));
Clazz clazz = r.readClass();
compiler.logTimedMessage("Loaded " + classFile, System
.currentTimeMillis()
- time);
// Update our knowledge base of classes.
classtable.put(refName(clazz.type()), clazz);
return clazz;
} else if(compiler.isCompiling(srcFile)) {
}
}
} catch(IOException e) {
// could possibly report stuff back to user here.
}
}
return null;
}
/**
* This method simply adds a class definition to the classtable. This is
* needed for when a class is being compiled, since we cannot simply load
* the class details from the bytecode as this doesn't exist!
*
* @param jilClasses -
* The classes being added.
*/
public void register(List<? extends Clazz> jilClasses) {
for(Clazz f : jilClasses) {
register(f);
}
}
/**
* This method simply adds a class definition to the classtable. This is
* needed for when a class is being compiled, since we cannot simply load
* the class details from the bytecode as this doesn't exist!
*
* @param jilClasses -
* The classes being added.
*/
public void register(Clazz jilClass) {
PackageInfo pkgInfo = packages.get(jilClass.type().pkg());
String rn = refName(jilClass.type());
String pc = pathChild(rn);
classtable.put(rn, jilClass);
// Need to do this to indicate that the source file in question has
// being compiled. Otherwise, we end up with an infinite loop of
// class loading.
pkgInfo.classes.add(pc);
pkgInfo.compiledClasses.add(pc);
}
/**
* Given a path string of the form "xxx.yyy.zzz" this returns the parent
* component (i.e. "xxx.yyy"). If you supply "xxx", then the path parent is
* "". However, the path parent of "" is null.
*
* @param pkg
* @return
*/
private String pathParent(String pkg) {
if(pkg.equals("")) {
return null;
}
int idx = pkg.lastIndexOf('.');
if(idx == -1) {
return "";
} else {
return pkg.substring(0,idx);
}
}
/**
* Given a path string of the form "xxx.yyy.zzz" this returns the child
* component (i.e. "zzz")
*
* @param pkg
* @return
*/
private String pathChild(String pkg) {
int idx = pkg.lastIndexOf('.');
if(idx == -1) {
return pkg;
} else {
return pkg.substring(idx+1);
}
}
/**
* This builds a list of all the known packages and the classes they
* contain.
*/
private void buildPackageMap() {
// BUG: there's a bug here, since the sourcepath is not considered.
for (String dir : classpath) {
// check if classpath entry is a jarfile or a directory
if (dir.endsWith(".jar")) {
try {
JarFile jf = new JarFile(dir);
for (Enumeration<JarEntry> e = jf.entries(); e.hasMoreElements();) {
JarEntry je = e.nextElement();
String tmp = je.getName().replace("/", ".");
// i'm not sure what should happen if a jarfile contains
// a source file which is older than the classfile!
addPackageItem(pathParent(tmp),new File(dir), true);
}
} catch (IOException e) {
// jarfile listed on classpath doesn't exist!
// So, silently ignore it (this is what javac does).
}
} else {
// dir is not a Jar file, so I assume it's a directory.
recurseDirectoryForClasses(dir, "");
}
}
}
/**
* This traverses the directory tree, starting from dir, looking for class
* or java files. There's probably a bug if the directory tree is cyclic!
*/
private void recurseDirectoryForClasses(String root, String dir) {
File f = new File(root + File.separatorChar + dir);
if (f.isDirectory()) {
for (String file : f.list()) {
if(file.endsWith(".class") || file.endsWith(".java")) {
if (dir.length() == 0) {
addPackageItem(pathParent(file), new File(root),
isCompiled(new File(f.getPath()
+ File.separatorChar + file)));
} else {
addPackageItem(dir.replace(File.separatorChar, '.')
+ "." + pathParent(file), new File(root),
isCompiled(new File(f.getPath()
+ File.separatorChar + file)));
}
} else {
if (dir.length() == 0) {
recurseDirectoryForClasses(root,
file);
} else {
recurseDirectoryForClasses(root,
dir + File.separatorChar + file);
}
}
}
}
}
/**
* This adds a class to the list of known classes. The class name is given
* in the form "xxx.yyy$zzz". Here, "xxx" is the package name, "yyy" is the
* outerclass name and "zzz" is the inner class name.
*
* @param name
* The name of the class to be added
* @param location
* The location of the enclosing package. This is either a jar
* file, or a directory.
*/
private void addPackageItem(String name, File pkgLocation, boolean isCompiled) {
if(name == null) return;
// this is a class file.
String pkg = pathParent(name);
String clazz = pathChild(name);
if(pkg == null) { pkg = ""; } // default package
PackageInfo items = packages.get(pkg);
if (items == null) {
items = new PackageInfo();
packages.put(pkg, items);
}
// add the class in question
if(items.classes.add(clazz)) {
// The first time that we find this class, we need to check whether
// or not it is compiled.
if(isCompiled) {
items.compiledClasses.add(clazz);
}
}
// now, add the location (if it wasn't already added)
if(!items.locations.contains(pkgLocation)) {
items.locations.add(pkgLocation);
}
// Finally, add all enclosing packages of this package as
// well. Otherwise, isPackage("java") can fails even when we know about
// a particular package.
pkg = pathParent(pkg);
while (pkg != null) {
if (packages.get(pkg) == null) {
packages.put(pkg, new PackageInfo());
}
pkg = pathParent(pkg);
}
}
/**
* Convert a class reference type into a proper name.
*/
String refName(Type.Clazz ref) {
String descriptor = ref.pkg();
if(!descriptor.equals("")) {
descriptor += ".";
}
boolean firstTime=true;
for(Pair<String,List<Type.Reference>> c : ref.components()) {
if(!firstTime) {
descriptor += "$";
}
firstTime=false;
descriptor += c.first();
}
return descriptor;
}
/**
* This method simply checks whether or not a given file is "compiled". The
* file is either a source or class file, and this method checks whether the
* corresponding class file exists or not; furthermore, if it does exist
* then it checks whether or not it is older than the source file (if there
* is one).
*
* @param file
* @return
*/
private static boolean isCompiled(File file) {
String filename = file.getPath();
if(filename.endsWith(".class")) {
// class file. construct source file by stripping off extension and
// inner class identifiers
filename = filename.substring(0,filename.length()-6);
int idx = filename.indexOf('$');
if(idx > 0) { filename = filename.substring(0,idx); }
File srcFile = new File(filename + ".java");
return !srcFile.exists() || (srcFile.lastModified() < file.lastModified());
} else if(filename.endsWith(".java")){
// source file
File classFile = new File(filename.substring(0,filename.length()-5) + ".class");
return file.lastModified() < classFile.lastModified();
} else {
throw new RuntimeException("Unknown file type encountered: " + file);
}
}
}
| true | true | private Clazz loadClass(String name, PackageInfo pkgInfo) {
long time = System.currentTimeMillis();
String jarname = name.replace('.','/') + ".class";
String filename = name.replace('.',File.separatorChar);
// The srcFilename gives the filename of the source file. So, if the
// class we're looking for is an inner class, then we need to strip off
// the inner class name(s) to obtain the source file name.
int tmpIndex = filename.indexOf('$');
String srcFilename = tmpIndex >= 0 ? filename.substring(0, tmpIndex) : filename;
for(File location : pkgInfo.locations) {
try {
if (location.getName().endsWith(".jar")) {
// location is a jar file
JarFile jf = new JarFile(location);
JarEntry je = jf.getJarEntry(jarname);
if (je == null) {
return null;
}
ClassFileReader r = new ClassFileReader(jf.getInputStream(je));
compiler.logTimedMessage("Loaded " + location + ":"
+ jarname, System.currentTimeMillis() - time);
Clazz clazz = r.readClass();
// Update our knowledge base of classes.
classtable.put(refName(clazz.type()), clazz);
return clazz;
} else {
File classFile = new File(filename + ".class");
File srcFile = new File(srcFilename + ".java");
if (srcFile.exists()
&& !compiler.isCompiling(srcFile)
&& (!classFile.exists() || classFile.lastModified() < srcFile
.lastModified())) {
// Here, there is a source file, and either there is no class
// file, or the class file is older than the source file.
// Therefore, we need to (re)compile the source file.
List<? extends Clazz> cs = compiler.compile(srcFile);
compiler.logTimedMessage("Compiled " + srcFile, System
.currentTimeMillis()
- time);
for(Clazz c : cs) {
if(refName(c.type()).equals(name)) {
return c;
}
}
throw new RuntimeException(
"internal failure (unreachable code reached!)");
} else if(classFile.exists()) {
// Here, there is no sourcefile, but there is a classfile.
// So, no need to compile --- just load the class file!
ClassFileReader r = new ClassFileReader(new FileInputStream(classFile));
Clazz clazz = r.readClass();
compiler.logTimedMessage("Loaded " + classFile, System
.currentTimeMillis()
- time);
// Update our knowledge base of classes.
classtable.put(refName(clazz.type()), clazz);
return clazz;
} else if(compiler.isCompiling(srcFile)) {
}
}
} catch(IOException e) {
// could possibly report stuff back to user here.
}
}
return null;
}
| private Clazz loadClass(String name, PackageInfo pkgInfo) {
long time = System.currentTimeMillis();
String jarname = name.replace('.','/') + ".class";
String filename = name.replace('.',File.separatorChar);
// The srcFilename gives the filename of the source file. So, if the
// class we're looking for is an inner class, then we need to strip off
// the inner class name(s) to obtain the source file name.
int tmpIndex = filename.indexOf('$');
String srcFilename = tmpIndex >= 0 ? filename.substring(0, tmpIndex) : filename;
for(File location : pkgInfo.locations) {
try {
if (location.getName().endsWith(".jar")) {
// location is a jar file
JarFile jf = new JarFile(location);
JarEntry je = jf.getJarEntry(jarname);
if (je == null) {
return null;
}
ClassFileReader r = new ClassFileReader(jf.getInputStream(je));
compiler.logTimedMessage("Loaded " + location + ":"
+ jarname, System.currentTimeMillis() - time);
Clazz clazz = r.readClass();
// Update our knowledge base of classes.
classtable.put(refName(clazz.type()), clazz);
return clazz;
} else {
File classFile = new File(location.getPath(),filename + ".class");
File srcFile = new File(location.getPath(),srcFilename + ".java");
if (srcFile.exists()
&& !compiler.isCompiling(srcFile)
&& (!classFile.exists() || classFile.lastModified() < srcFile
.lastModified())) {
// Here, there is a source file, and either there is no class
// file, or the class file is older than the source file.
// Therefore, we need to (re)compile the source file.
List<? extends Clazz> cs = compiler.compile(srcFile);
compiler.logTimedMessage("Compiled " + srcFile, System
.currentTimeMillis()
- time);
for(Clazz c : cs) {
if(refName(c.type()).equals(name)) {
return c;
}
}
throw new RuntimeException(
"internal failure (unreachable code reached!)");
} else if(classFile.exists()) {
// Here, there is no sourcefile, but there is a classfile.
// So, no need to compile --- just load the class file!
ClassFileReader r = new ClassFileReader(new FileInputStream(classFile));
Clazz clazz = r.readClass();
compiler.logTimedMessage("Loaded " + classFile, System
.currentTimeMillis()
- time);
// Update our knowledge base of classes.
classtable.put(refName(clazz.type()), clazz);
return clazz;
} else if(compiler.isCompiling(srcFile)) {
}
}
} catch(IOException e) {
// could possibly report stuff back to user here.
}
}
return null;
}
|
diff --git a/code/android/src/main/java/no/kantega/android/afp/controllers/Transactions.java b/code/android/src/main/java/no/kantega/android/afp/controllers/Transactions.java
index b2aae21..cba0500 100644
--- a/code/android/src/main/java/no/kantega/android/afp/controllers/Transactions.java
+++ b/code/android/src/main/java/no/kantega/android/afp/controllers/Transactions.java
@@ -1,449 +1,450 @@
package no.kantega.android.afp.controllers;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.util.Log;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.GenericRawResults;
import com.j256.ormlite.stmt.QueryBuilder;
import no.kantega.android.afp.models.*;
import no.kantega.android.afp.utils.DatabaseHelper;
import no.kantega.android.afp.utils.FmtUtil;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
public class Transactions {
private static final String TAG = Transactions.class.getSimpleName();
private static final String SQLITE_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
private final DatabaseHelper helper;
private final Dao<Transaction, Integer> transactionDao;
private final Dao<TransactionTag, Integer> transactionTagDao;
private final Dao<TransactionType, Integer> transactionTypeDao;
public Transactions(Context context) {
this.helper = new DatabaseHelper(context);
this.transactionDao = helper.getTransactionDao();
this.transactionTagDao = helper.getTransactionTagDao();
this.transactionTypeDao = helper.getTransactionTypeDao();
}
public Transactions(Context context, DatabaseHelper helper) {
this.helper = helper;
this.transactionDao = helper.getTransactionDao();
this.transactionTagDao = helper.getTransactionTagDao();
this.transactionTypeDao = helper.getTransactionTypeDao();
}
/**
* Add a new transaction tag
*
* @param tag Transaction tag to save
* @return The newly added tag or the existing one
*/
private TransactionTag insertIgnore(TransactionTag tag) {
if (tag == null) {
return null;
}
try {
QueryBuilder<TransactionTag, Integer> queryBuilder = transactionTagDao.queryBuilder();
queryBuilder.where().eq("name", tag.getName());
List<TransactionTag> tags = transactionTagDao.query(queryBuilder.prepare());
if (tags.size() > 0) {
return tags.get(0);
} else {
transactionTagDao.create(tag);
tags = transactionTagDao.query(queryBuilder.prepare());
return tags.get(0);
}
} catch (SQLException e) {
Log.e(TAG, "Failed to add transaction tag", e);
}
return null;
}
/**
* Add a new transaction type
*
* @param type Transaction type to save
* @return The newly added tag or the existing one
*/
private TransactionType insertIgnore(TransactionType type) {
if (type == null) {
return null;
}
try {
QueryBuilder<TransactionType, Integer> queryBuilder = transactionTypeDao.queryBuilder();
queryBuilder.where().eq("name", type.getName());
List<TransactionType> types = transactionTypeDao.query(queryBuilder.prepare());
if (types.size() > 0) {
return types.get(0);
} else {
transactionTypeDao.create(type);
types = transactionTypeDao.query(queryBuilder.prepare());
return types.get(0);
}
} catch (SQLException e) {
Log.e(TAG, "Failed to add transaction type", e);
}
return null;
}
/**
* Add a new transaction
*
* @param t Transaction to save
*/
public void add(Transaction t) {
t.setTag(insertIgnore(t.getTag()));
t.setType(insertIgnore(t.getType()));
try {
transactionDao.create(t);
} catch (SQLException e) {
Log.e(TAG, "Failed to add transaction", e);
}
}
/**
* Add a new tag
*
* @param t Transaction tag to save
*/
public void add(TransactionTag t) {
insertIgnore(t);
}
/**
* Update a transaction
*
* @param t Transaction tag to save
*/
public void update(Transaction t) {
t.setTag(insertIgnore(t.getTag()));
t.setType(insertIgnore(t.getType()));
try {
transactionDao.update(t);
} catch (SQLException e) {
Log.e(TAG, "Failed to update transaction", e);
}
}
/**
* Retrieve a list of transactions ordered descending by date
*
* @param limit Max number of transactions to retrieve
* @return List of transactions
*/
public List<Transaction> get(final int limit) {
QueryBuilder<Transaction, Integer> queryBuilder = transactionDao.
queryBuilder();
queryBuilder.limit(limit);
return get(queryBuilder);
}
/**
* Get transaction by id
*
* @param id ID of transaction
* @return The transaction or null if not found
*/
public Transaction getById(final int id) {
List<Transaction> transactions = Collections.emptyList();
QueryBuilder<Transaction, Integer> queryBuilder = transactionDao.
queryBuilder();
queryBuilder.limit(1);
try {
queryBuilder.setWhere(queryBuilder.where().eq("_id", id));
transactions = transactionDao.query(queryBuilder.prepare());
} catch (SQLException e) {
Log.e(TAG, "Failed to find transaction", e);
}
return transactions.isEmpty() ? null : transactions.get(0);
}
/**
* Retrieve a list of changed transactions
*
* @return List of transactions
*/
@Deprecated
public List<Transaction> getChanged() {
QueryBuilder<Transaction, Integer> queryBuilder = transactionDao.queryBuilder();
try {
queryBuilder.setWhere(queryBuilder.where().eq("changed", true));
} catch (SQLException e) {
Log.e(TAG, "Failed to set where condition", e);
}
return get(queryBuilder);
}
/**
* Retrieve a list of dirty transactions (which should be synchronized)
*
* @return List of transactions
*/
public List<Transaction> getDirty() {
QueryBuilder<Transaction, Integer> queryBuilder = transactionDao.
queryBuilder();
try {
queryBuilder.setWhere(queryBuilder.where().eq("dirty", true));
} catch (SQLException e) {
Log.e(TAG, "Failed to set where condition", e);
}
return get(queryBuilder);
}
/**
* Get the latest external transaction
*
* @return Transaction
*/
public Transaction getLatestExternal() {
final QueryBuilder<Transaction, Integer> queryBuilder = transactionDao.
queryBuilder();
try {
queryBuilder.setWhere(queryBuilder.where().eq("internal", false));
} catch (SQLException e) {
Log.e(TAG, "Failed to set where condition", e);
}
final List<Transaction> transactions = get(queryBuilder);
return transactions.isEmpty() ? null : transactions.get(0);
}
/**
* Retrieve a list of transactions using the given query builder
*
* @param queryBuilder Query builder
* @return List of transactions
*/
private List<Transaction> get(QueryBuilder<Transaction, Integer> queryBuilder) {
List<Transaction> transactions = Collections.emptyList();
try {
queryBuilder.orderBy("accountingDate", false).
orderBy("timestamp", false);
transactions = transactionDao.query(queryBuilder.prepare());
} catch (SQLException e) {
Log.e(TAG, "Failed to retrieve transactions", e);
}
return transactions;
}
/**
* Get a cursor for transactions
*
* @return Cursor
*/
public Cursor getCursor() {
final Cursor cursor = helper.getReadableDatabase().query(
"transactions " +
"LEFT JOIN transactiontypes " +
"ON transactiontypes.id = transactions.type_id " +
"LEFT JOIN transactiontags " +
"ON transactiontags.id = transactions.tag_id"
, new String[]{"*", "transactiontypes.name AS type",
"transactiontags.name AS tag",
"transactiontags.imageId as imageId"}, null,
null, null, null,
"accountingdate DESC, timestamp DESC", null);
return cursor;
}
/**
* Get a cursor that only returns non-internal transactions after the given timestamp
*
* @param timestamp Timestamp
* @return External transactions after timestamp
*/
public Cursor getCursorAfterTimestamp(long timestamp) {
final String selection = "internal = ? AND timestamp > ?";
final String[] selectionArgs = new String[]{"0",
String.valueOf(timestamp)};
final Cursor cursor = helper.getReadableDatabase().query(
"transactions " +
"LEFT JOIN transactiontypes " +
"ON transactiontypes.id = transactions.type_id " +
"LEFT JOIN transactiontags " +
"ON transactiontags.id = transactions.tag_id"
, new String[]{"*", "transactiontypes.name AS type",
"transactiontags.name AS tag",
"transactiontags.imageId as imageId"}, selection,
selectionArgs, null, null,
"accountingdate DESC, timestamp DESC", null);
return cursor;
}
/**
* Retrieve total transaction count
*
* @return Transaction count
*/
public long getCount() {
return DatabaseUtils.queryNumEntries(helper.getReadableDatabase(), "transactions");
}
/**
* Retrieve total transaction tag count
*
* @return Transaction tag count
*/
public long getTagCount() {
return DatabaseUtils.queryNumEntries(helper.getReadableDatabase(), "transactiontags");
}
/**
* Retrieve number of dirty (unsynced) transactions
*
* @return Number of unsynced transactions
*/
public int getDirtyCount() {
try {
final GenericRawResults<String[]> rawResults = transactionDao.
queryRaw("SELECT COUNT(*) FROM transactions WHERE dirty = 1 LIMIT 1");
return Integer.parseInt(rawResults.getResults().get(0)[0]);
} catch (SQLException e) {
Log.e(TAG, "Failed to retrieve transaction count", e);
}
return 0;
}
/**
* Retrieve number of untagged transactions
*
* @return Untagged count
*/
public int getUntaggedCount() {
try {
final GenericRawResults<String[]> rawResults = transactionDao.
queryRaw("SELECT COUNT(*) FROM transactions " +
"WHERE tag_id IS NULL LIMIT 1");
return Integer.parseInt(rawResults.getResults().get(0)[0]);
} catch (SQLException e) {
Log.e(TAG, "Failed to retrieve transaction count", e);
}
return 0;
}
/**
* Retrieve a list of aggregated tags sorted by sum of all transactions in that tag
*
* @param limit Max number of aggregated tags to retrieve
* @return List of aggregated tags
*/
public List<AggregatedTag> getAggregatedTags(final int limit) {
final List<AggregatedTag> aggregatedTags = new ArrayList<AggregatedTag>();
try {
final GenericRawResults<String[]> rawResults = transactionDao.queryRaw(
"SELECT transactiontags.name, SUM(amountOut) AS sum " +
"FROM transactions " +
"INNER JOIN transactiontags ON transactiontags.id = transactions.tag_id " +
"GROUP BY transactiontags.name " +
"ORDER BY sum DESC LIMIT ?", String.valueOf(limit));
for (String[] row : rawResults) {
AggregatedTag aggregatedTag = new AggregatedTag();
aggregatedTag.setName(row[0]);
aggregatedTag.setAmount(Double.parseDouble(row[1]));
aggregatedTags.add(aggregatedTag);
}
rawResults.close();
} catch (SQLException e) {
Log.e(TAG, "Failed to retrieve aggregated tags", e);
}
return aggregatedTags;
}
/**
* Get all transaction tags ordered descending by usage count
*
* @return List of transaction tags
*/
public List<TransactionTag> getTags() {
final List<TransactionTag> transactionTags = new ArrayList<TransactionTag>();
try {
final GenericRawResults<String[]> rawResults = transactionDao.queryRaw(
"SELECT name, COUNT(*) AS count FROM transactiontags GROUP BY name ORDER BY count DESC");
for (String[] row : rawResults) {
TransactionTag tag = new TransactionTag();
tag.setName(row[0]);
transactionTags.add(tag);
}
} catch (SQLException e) {
Log.e(TAG, "Failed to retrieve all tags", e);
}
return transactionTags;
}
/**
* Calculate the average per day using the oldest and newest transaction date
*
* @return Average consumption per day
*/
private double getAvgDay() {
try {
GenericRawResults<String[]> rawResults = transactionDao.
queryRaw("SELECT accountingDate FROM transactions ORDER BY accountingDate ASC LIMIT 1");
final List<String[]> results = rawResults.getResults();
if (results.size() > 0) {
final Date start = FmtUtil.stringToDate(SQLITE_DATE_FORMAT, results.get(0)[0]);
rawResults.close();
rawResults = transactionDao.
queryRaw("SELECT accountingDate FROM transactions ORDER BY accountingDate DESC LIMIT 1");
final Date stop = FmtUtil.stringToDate(SQLITE_DATE_FORMAT, rawResults.getResults().get(0)[0]);
rawResults.close();
final int days =
(int) ((stop.getTime() - start.getTime()) / 1000) / 86400;
if (days > 0) {
rawResults = transactionDao.
queryRaw("SELECT SUM(amountOut) FROM transactions LIMIT 1");
final double avg = Double.parseDouble(
rawResults.getResults().get(0)[0]) / days;
rawResults.close();
+ return avg;
}
}
} catch (SQLException e) {
Log.e(TAG, "Failed to retrieve average consumption");
}
return 0;
}
/**
* Calculate average consumption per day, week and month
*
* @return Average consumption
*/
public AverageConsumption getAvg() {
final double avgPerDay = getAvgDay();
final AverageConsumption avg = new AverageConsumption();
avg.setDay(avgPerDay);
avg.setWeek(avgPerDay * 7);
avg.setMonth(avgPerDay * 30.4368499);
return avg;
}
/**
* Empty all tables
*/
public void emptyTables() {
try {
transactionDao.queryRaw("DELETE FROM transactions");
transactionDao.queryRaw("DELETE FROM transactiontags");
transactionDao.queryRaw("DELETE FROM transactiontypes");
} catch (SQLException e) {
Log.e(TAG, "Could not empty tables", e);
}
}
/**
* Close open database connections
*/
public void close() {
if (helper != null) {
helper.close();
Log.d(TAG, "Closed database connection");
}
}
}
| true | true | private double getAvgDay() {
try {
GenericRawResults<String[]> rawResults = transactionDao.
queryRaw("SELECT accountingDate FROM transactions ORDER BY accountingDate ASC LIMIT 1");
final List<String[]> results = rawResults.getResults();
if (results.size() > 0) {
final Date start = FmtUtil.stringToDate(SQLITE_DATE_FORMAT, results.get(0)[0]);
rawResults.close();
rawResults = transactionDao.
queryRaw("SELECT accountingDate FROM transactions ORDER BY accountingDate DESC LIMIT 1");
final Date stop = FmtUtil.stringToDate(SQLITE_DATE_FORMAT, rawResults.getResults().get(0)[0]);
rawResults.close();
final int days =
(int) ((stop.getTime() - start.getTime()) / 1000) / 86400;
if (days > 0) {
rawResults = transactionDao.
queryRaw("SELECT SUM(amountOut) FROM transactions LIMIT 1");
final double avg = Double.parseDouble(
rawResults.getResults().get(0)[0]) / days;
rawResults.close();
}
}
} catch (SQLException e) {
Log.e(TAG, "Failed to retrieve average consumption");
}
return 0;
}
| private double getAvgDay() {
try {
GenericRawResults<String[]> rawResults = transactionDao.
queryRaw("SELECT accountingDate FROM transactions ORDER BY accountingDate ASC LIMIT 1");
final List<String[]> results = rawResults.getResults();
if (results.size() > 0) {
final Date start = FmtUtil.stringToDate(SQLITE_DATE_FORMAT, results.get(0)[0]);
rawResults.close();
rawResults = transactionDao.
queryRaw("SELECT accountingDate FROM transactions ORDER BY accountingDate DESC LIMIT 1");
final Date stop = FmtUtil.stringToDate(SQLITE_DATE_FORMAT, rawResults.getResults().get(0)[0]);
rawResults.close();
final int days =
(int) ((stop.getTime() - start.getTime()) / 1000) / 86400;
if (days > 0) {
rawResults = transactionDao.
queryRaw("SELECT SUM(amountOut) FROM transactions LIMIT 1");
final double avg = Double.parseDouble(
rawResults.getResults().get(0)[0]) / days;
rawResults.close();
return avg;
}
}
} catch (SQLException e) {
Log.e(TAG, "Failed to retrieve average consumption");
}
return 0;
}
|
diff --git a/test/unit/org/apache/cassandra/db/TimeSortTest.java b/test/unit/org/apache/cassandra/db/TimeSortTest.java
index c96d1d51..3731d284 100644
--- a/test/unit/org/apache/cassandra/db/TimeSortTest.java
+++ b/test/unit/org/apache/cassandra/db/TimeSortTest.java
@@ -1,112 +1,110 @@
/*
* 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.cassandra.db;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.SortedSet;
import java.util.Iterator;
import org.apache.commons.lang.ArrayUtils;
import org.junit.Test;
import org.apache.cassandra.CleanupHelper;
public class TimeSortTest extends CleanupHelper
{
@Test
public void testTimeSort() throws IOException, ExecutionException, InterruptedException
{
Table table = Table.open("Table1");
for (int i = 900; i < 1000; ++i)
{
String key = Integer.toString(i);
- RowMutation rm;
+ RowMutation rm = new RowMutation("Table1", key);
for (int j = 0; j < 8; ++j)
{
byte[] bytes = j % 2 == 0 ? "a".getBytes() : "b".getBytes();
- rm = new RowMutation("Table1", key);
rm.add("StandardByTime1:" + "Column-" + j, bytes, j * 2);
- rm.apply();
}
+ rm.apply();
}
validateTimeSort(table);
table.getColumnFamilyStore("StandardByTime1").forceBlockingFlush();
validateTimeSort(table);
// interleave some new data to test memtable + sstable
String key = "900";
- RowMutation rm;
+ RowMutation rm = new RowMutation("Table1", key);
for (int j = 0; j < 4; ++j)
{
- rm = new RowMutation("Table1", key);
rm.add("StandardByTime1:" + "Column+" + j, ArrayUtils.EMPTY_BYTE_ARRAY, j * 2 + 1);
- rm.apply();
}
+ rm.apply();
// and some overwrites
+ rm = new RowMutation("Table1", key);
for (int j = 4; j < 8; ++j)
{
- rm = new RowMutation("Table1", key);
rm.add("StandardByTime1:" + "Column-" + j, ArrayUtils.EMPTY_BYTE_ARRAY, j * 3);
- rm.apply();
}
+ rm.apply();
// verify
ColumnFamily cf = table.getRow(key, "StandardByTime1", 0).getColumnFamilies().iterator().next();
SortedSet<IColumn> columns = cf.getAllColumns();
assert columns.size() == 12;
Iterator<IColumn> iter = columns.iterator();
IColumn column;
for (int j = 7; j >= 4; j--)
{
column = iter.next();
assert column.name().equals("Column-" + j);
assert column.timestamp() == j * 3;
assert column.value().length == 0;
}
for (int j = 3; j >= 0; j--)
{
column = iter.next();
assert column.name().equals("Column+" + j);
column = iter.next();
assert column.name().equals("Column-" + j);
}
}
private void validateTimeSort(Table table) throws IOException
{
for (int i = 900; i < 1000; ++i)
{
String key = Integer.toString(i);
for (int j = 0; j < 8; j += 3)
{
ColumnFamily cf = table.getRow(key, "StandardByTime1", j * 2).getColumnFamilies().iterator().next();
SortedSet<IColumn> columns = cf.getAllColumns();
assert columns.size() == 8 - j;
int k = 7;
for (IColumn c : columns)
{
assert c.timestamp() == (k--) * 2;
}
}
}
}
}
| false | true | public void testTimeSort() throws IOException, ExecutionException, InterruptedException
{
Table table = Table.open("Table1");
for (int i = 900; i < 1000; ++i)
{
String key = Integer.toString(i);
RowMutation rm;
for (int j = 0; j < 8; ++j)
{
byte[] bytes = j % 2 == 0 ? "a".getBytes() : "b".getBytes();
rm = new RowMutation("Table1", key);
rm.add("StandardByTime1:" + "Column-" + j, bytes, j * 2);
rm.apply();
}
}
validateTimeSort(table);
table.getColumnFamilyStore("StandardByTime1").forceBlockingFlush();
validateTimeSort(table);
// interleave some new data to test memtable + sstable
String key = "900";
RowMutation rm;
for (int j = 0; j < 4; ++j)
{
rm = new RowMutation("Table1", key);
rm.add("StandardByTime1:" + "Column+" + j, ArrayUtils.EMPTY_BYTE_ARRAY, j * 2 + 1);
rm.apply();
}
// and some overwrites
for (int j = 4; j < 8; ++j)
{
rm = new RowMutation("Table1", key);
rm.add("StandardByTime1:" + "Column-" + j, ArrayUtils.EMPTY_BYTE_ARRAY, j * 3);
rm.apply();
}
// verify
ColumnFamily cf = table.getRow(key, "StandardByTime1", 0).getColumnFamilies().iterator().next();
SortedSet<IColumn> columns = cf.getAllColumns();
assert columns.size() == 12;
Iterator<IColumn> iter = columns.iterator();
IColumn column;
for (int j = 7; j >= 4; j--)
{
column = iter.next();
assert column.name().equals("Column-" + j);
assert column.timestamp() == j * 3;
assert column.value().length == 0;
}
for (int j = 3; j >= 0; j--)
{
column = iter.next();
assert column.name().equals("Column+" + j);
column = iter.next();
assert column.name().equals("Column-" + j);
}
}
| public void testTimeSort() throws IOException, ExecutionException, InterruptedException
{
Table table = Table.open("Table1");
for (int i = 900; i < 1000; ++i)
{
String key = Integer.toString(i);
RowMutation rm = new RowMutation("Table1", key);
for (int j = 0; j < 8; ++j)
{
byte[] bytes = j % 2 == 0 ? "a".getBytes() : "b".getBytes();
rm.add("StandardByTime1:" + "Column-" + j, bytes, j * 2);
}
rm.apply();
}
validateTimeSort(table);
table.getColumnFamilyStore("StandardByTime1").forceBlockingFlush();
validateTimeSort(table);
// interleave some new data to test memtable + sstable
String key = "900";
RowMutation rm = new RowMutation("Table1", key);
for (int j = 0; j < 4; ++j)
{
rm.add("StandardByTime1:" + "Column+" + j, ArrayUtils.EMPTY_BYTE_ARRAY, j * 2 + 1);
}
rm.apply();
// and some overwrites
rm = new RowMutation("Table1", key);
for (int j = 4; j < 8; ++j)
{
rm.add("StandardByTime1:" + "Column-" + j, ArrayUtils.EMPTY_BYTE_ARRAY, j * 3);
}
rm.apply();
// verify
ColumnFamily cf = table.getRow(key, "StandardByTime1", 0).getColumnFamilies().iterator().next();
SortedSet<IColumn> columns = cf.getAllColumns();
assert columns.size() == 12;
Iterator<IColumn> iter = columns.iterator();
IColumn column;
for (int j = 7; j >= 4; j--)
{
column = iter.next();
assert column.name().equals("Column-" + j);
assert column.timestamp() == j * 3;
assert column.value().length == 0;
}
for (int j = 3; j >= 0; j--)
{
column = iter.next();
assert column.name().equals("Column+" + j);
column = iter.next();
assert column.name().equals("Column-" + j);
}
}
|
diff --git a/orbisgis-view/src/main/java/org/orbisgis/view/map/MapStatusBar.java b/orbisgis-view/src/main/java/org/orbisgis/view/map/MapStatusBar.java
index 47ae48c70..fd93334c8 100644
--- a/orbisgis-view/src/main/java/org/orbisgis/view/map/MapStatusBar.java
+++ b/orbisgis-view/src/main/java/org/orbisgis/view/map/MapStatusBar.java
@@ -1,224 +1,223 @@
/*
* OrbisGIS is a GIS application dedicated to scientific spatial simulation.
* This cross-platform GIS is developed at French IRSTV institute and is able to
* manipulate and create vector and raster spatial information. OrbisGIS is
* distributed under GPL 3 license. It is produced by the "Atelier SIG" team of
* the IRSTV Institute <http://www.irstv.cnrs.fr/> CNRS FR 2488.
*
*
*
* This file is part of OrbisGIS.
*
* OrbisGIS 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.
*
* OrbisGIS 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
* OrbisGIS. If not, see <http://www.gnu.org/licenses/>.
*
* For more information, please consult: <http://www.orbisgis.org/>
*
* or contact directly:
* info _at_ orbisgis.org
*/
package org.orbisgis.view.map;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.geom.Point2D;
import java.beans.EventHandler;
import java.beans.PropertyVetoException;
import java.beans.VetoableChangeListener;
import java.beans.VetoableChangeSupport;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
import javax.swing.*;
import org.apache.log4j.Logger;
import org.jproj.CRSFactory;
import org.jproj.CoordinateReferenceSystem;
import org.orbisgis.view.components.button.CustomButton;
import org.orbisgis.view.components.statusbar.StatusBar;
import org.orbisgis.view.icons.OrbisGISIcon;
import org.xnap.commons.i18n.I18n;
import org.xnap.commons.i18n.I18nFactory;
/**
* @brief Area at the bottom of the MapEditor
* This is an area in the bottom of the map that contain :
* - A scale information label
* - A projection information label
* - A projection selection button
*/
public class MapStatusBar extends StatusBar {
protected final static I18n I18N = I18nFactory.getI18n(MapStatusBar.class);
private static final Logger LOGGER = Logger.getLogger(MapStatusBar.class);
public static final String PROP_USER_DEFINED_SCALE_DENOMINATOR = "userDefinedScaleDenominator";
protected VetoableChangeSupport vetoableChangeSupport = new VetoableChangeSupport(this);
//Scale
private JLabel scaleLabel;
private JTextField scaleField;
private double scaleValue=1; //Valid scale defined by the MapEditor
private long userDefinedScaleDenominator=1; //Last User scale set
//CRS
private JLabel projectionLabel;
//Coordinates
private JLabel mouseCoordinatesLabel;
private Point2D mouseCoordinates = new Point2D.Double();
//Layout parameters
private final static int OUTER_BAR_BORDER = 1;
private final static int HORIZONTAL_EMPTY_BORDER = 4;
public MapStatusBar() {
super(OUTER_BAR_BORDER,HORIZONTAL_EMPTY_BORDER);
////////
//Add bar components
//Coordinates
mouseCoordinatesLabel = new JLabel();
addComponent(mouseCoordinatesLabel);
// Projection
projectionLabel = new JLabel();
addComponent(projectionLabel);
JButton changeProjection = new CustomButton(OrbisGISIcon.getIcon("world"));
changeProjection.setToolTipText(I18N.tr("Change coordinate reference system"));
//changeProjection.setContentAreaFilled(false);
addComponent(changeProjection,false);
// Scale
scaleLabel = new JLabel(I18N.tr("Scale :"));
scaleField = new JTextField();
scaleField.addActionListener(EventHandler.create(ActionListener.class,this,"validateInputScale"));
scaleField.setInputVerifier(new FormattedTextFieldVerifier());
//scaleField.setEditable(false);
//scaleField.setColumns(SCALE_FIELD_COLUMNS);
addComponent(scaleLabel);
addComponent(scaleField,false);
//Set initial value
setScaleDenominator(1);
setProjection(new CRSFactory().createFromName("EPSG:4326"));
setCursorCoordinates(new Point2D.Double());
}
/**
* Called by the VK_ENTER of the textField
*/
public void validateInputScale() {
scaleField.getInputVerifier().verify(scaleField);
}
/**
* Set the value of userDefinedScaleDenominator
*
* @param userDefinedScaleDenominator new value of
* userDefinedScaleDenominator
* @throws java.beans.PropertyVetoException
*/
public void setUserDefinedScaleDenominator(long userDefinedScaleDenominator) throws PropertyVetoException {
long oldUserDefinedScaleDenominator = this.userDefinedScaleDenominator;
try {
vetoableChangeSupport.fireVetoableChange(PROP_USER_DEFINED_SCALE_DENOMINATOR, oldUserDefinedScaleDenominator, userDefinedScaleDenominator);
fireVetoableChange(PROP_USER_DEFINED_SCALE_DENOMINATOR, oldUserDefinedScaleDenominator, userDefinedScaleDenominator);
} catch( RuntimeException ex) {
//Something has converted the PropertyVetoException into a runtime exception
throw (PropertyVetoException)ex.getCause();
}
this.userDefinedScaleDenominator = userDefinedScaleDenominator;
firePropertyChange(PROP_USER_DEFINED_SCALE_DENOMINATOR, oldUserDefinedScaleDenominator, userDefinedScaleDenominator);
}
/**
* Set the new Projection of the Map
* @param projection
*/
public final void setProjection(CoordinateReferenceSystem projection) {
String projectLabel = projection.toString();
//projectLabel = "TODO"; //TODO read map context project
projectionLabel.setText(I18N.tr("Projection : {0}",projectLabel));
}
/**
* Add a VetoableChangeListener for a specific property.
* @param listener
*/
public void addVetoableChangeListener(String property, VetoableChangeListener listener )
{
vetoableChangeSupport.addVetoableChangeListener(property, listener );
}
/**
* Set the mouse coordinate in the Coordinate reference system
* @param coordinate
*/
public final void setCursorCoordinates(Point2D cursorCoordinate) {
if(!mouseCoordinates.equals(cursorCoordinate)) {
mouseCoordinates=cursorCoordinate;
NumberFormat f = DecimalFormat.getInstance(new Locale("en"));
f.setGroupingUsed(false);
mouseCoordinatesLabel.setText(I18N.tr("X:{0} Y:{1}",f.format(cursorCoordinate.getX()),f.format(cursorCoordinate.getY())));
}
}
/**
* Set the value of scaleDenominator
*
* @param scaleDenominator new value of scaleDenominator
*/
public final void setScaleDenominator(double scaleDenominator) {
scaleValue = scaleDenominator;
scaleField.setText(I18N.tr("1:{0}",Math.round(scaleDenominator)));
validate(); // Resize and layout controls
}
private class FormattedTextFieldVerifier extends InputVerifier {
private void invalidateUserInput() {
setScaleDenominator(scaleValue);
}
@Override
public boolean verify(JComponent input) {
if (input instanceof JTextField) {
LOGGER.debug("Verify scale user input..");
JTextField ftf = (JTextField) input;
String text = ftf.getText();
NumberFormat ft = NumberFormat.getIntegerInstance(); //Use default locale
String[] scaleParts = text.split(":");
if(scaleParts.length!=2) {
//More or Less than a single ':' character
LOGGER.error(I18N.tr("The format of a scale is 1:number"));
invalidateUserInput();
} else {
try {
if(ft.parse(scaleParts[0]).intValue()==1) {
setUserDefinedScaleDenominator(ft.parse(scaleParts[1]).longValue());
LOGGER.debug("User scale input accepted..");
} else {
- invalidateUserInput();
throw new ParseException(I18N.tr("The only accepted value on nominator is 1"), 0);
}
} catch( ParseException ex) {
//Do not send the exception, the user has not to see the traceback
LOGGER.error(ex.getLocalizedMessage());
invalidateUserInput();
} catch (PropertyVetoException ex) {
//Don't know why but something catch the
//Vetoed by the MapEditor
LOGGER.error(ex.getLocalizedMessage());
invalidateUserInput();
}
}
}
return true;
}
@Override
public boolean shouldYieldFocus(JComponent input) {
return verify(input);
}
}
}
| true | true | public boolean verify(JComponent input) {
if (input instanceof JTextField) {
LOGGER.debug("Verify scale user input..");
JTextField ftf = (JTextField) input;
String text = ftf.getText();
NumberFormat ft = NumberFormat.getIntegerInstance(); //Use default locale
String[] scaleParts = text.split(":");
if(scaleParts.length!=2) {
//More or Less than a single ':' character
LOGGER.error(I18N.tr("The format of a scale is 1:number"));
invalidateUserInput();
} else {
try {
if(ft.parse(scaleParts[0]).intValue()==1) {
setUserDefinedScaleDenominator(ft.parse(scaleParts[1]).longValue());
LOGGER.debug("User scale input accepted..");
} else {
invalidateUserInput();
throw new ParseException(I18N.tr("The only accepted value on nominator is 1"), 0);
}
} catch( ParseException ex) {
//Do not send the exception, the user has not to see the traceback
LOGGER.error(ex.getLocalizedMessage());
invalidateUserInput();
} catch (PropertyVetoException ex) {
//Don't know why but something catch the
//Vetoed by the MapEditor
LOGGER.error(ex.getLocalizedMessage());
invalidateUserInput();
}
}
}
return true;
}
| public boolean verify(JComponent input) {
if (input instanceof JTextField) {
LOGGER.debug("Verify scale user input..");
JTextField ftf = (JTextField) input;
String text = ftf.getText();
NumberFormat ft = NumberFormat.getIntegerInstance(); //Use default locale
String[] scaleParts = text.split(":");
if(scaleParts.length!=2) {
//More or Less than a single ':' character
LOGGER.error(I18N.tr("The format of a scale is 1:number"));
invalidateUserInput();
} else {
try {
if(ft.parse(scaleParts[0]).intValue()==1) {
setUserDefinedScaleDenominator(ft.parse(scaleParts[1]).longValue());
LOGGER.debug("User scale input accepted..");
} else {
throw new ParseException(I18N.tr("The only accepted value on nominator is 1"), 0);
}
} catch( ParseException ex) {
//Do not send the exception, the user has not to see the traceback
LOGGER.error(ex.getLocalizedMessage());
invalidateUserInput();
} catch (PropertyVetoException ex) {
//Don't know why but something catch the
//Vetoed by the MapEditor
LOGGER.error(ex.getLocalizedMessage());
invalidateUserInput();
}
}
}
return true;
}
|
diff --git a/src/fr/utc/nf28/moka/agents/itemcreation/ItemCreationAgent.java b/src/fr/utc/nf28/moka/agents/itemcreation/ItemCreationAgent.java
index e2cc58d..9734fdb 100644
--- a/src/fr/utc/nf28/moka/agents/itemcreation/ItemCreationAgent.java
+++ b/src/fr/utc/nf28/moka/agents/itemcreation/ItemCreationAgent.java
@@ -1,126 +1,126 @@
package fr.utc.nf28.moka.agents.itemcreation;
import fr.utc.nf28.moka.agents.A2ATransaction;
import fr.utc.nf28.moka.agents.MokaAgent;
import fr.utc.nf28.moka.environment.MokaEnvironment;
import fr.utc.nf28.moka.environment.items.*;
import fr.utc.nf28.moka.environment.users.User;
import fr.utc.nf28.moka.util.JSONParserUtils;
import fr.utc.nf28.moka.util.JadeUtils;
import jade.core.AID;
import jade.lang.acl.ACLMessage;
import java.io.IOException;
import java.util.HashMap;
/**
* An agent that creates items. Send a REQUEST with a creation JSON to this agent to ad an item
*/
public class ItemCreationAgent extends MokaAgent {
public void setup() {
super.setup();
registerSkill(JadeUtils.JADE_SKILL_NAME_CREATION);
addBehaviour(new ItemCreationBehaviour());
}
/**
* create new item
*
* @param type typeof this new item
* @param response use to communicate item id to androidAgent which
* request this item creation
* @throws IOException
*/
public void create(final String type, final ACLMessage response, final AID creator) throws IOException {
MokaItem newItem = null;
final MokaEnvironment environment = getEnvironment();
final int newItemId = environment.generateNewId();
if (type.equals("UML")) {
newItem = new UmlClass("MyClass", 200, 350, "UmlClass");
} else if (type.equals("post-it")) {
newItem = new PostIt("Post-it", 300, 350, "Post-it", "Post-it content");
} else if (type.equals("image")) {
newItem = new ImageLink("Image", 400, 450, "http://i1.cdnds.net/13/12/618x959/bill-gates-mugshot.jpg");
} else if (type.equals("video")) {
- newItem = new VideoLink("Video", 500, 500, "http://http://www.youtube.com/watch?v=anwy2MPT5RE");
+ newItem = new VideoLink("Video", 500, 500, "http://www.youtube.com/watch?v=anwy2MPT5RE");
}
if (newItem == null) {
//server side creation failed
//TODO implement callback error in order to warn AndroidDevice which has requested this creation
return;
}
//set creator as Locker
newItem.lock(environment.getUserByAID(creator.toString()));
//set item id
newItem.setId(newItemId);
environment.addItem(newItem);
//send back item id to the creator
sendBackItemId(response, newItemId);
//propagate creation to Ui platform
propagateCreation(newItem, environment.getUserByAID(creator.toString()));
//request refreshing current item list for all android device
requestAndroidCurrentItemsListRefresh();
}
/**
* Use to send back id of the new created item
*
* @param response ACL response for AndroidAgent which send the creation request
* @param newItemId item id
* @throws IOException
*/
public void sendBackItemId(final ACLMessage response, final int newItemId) throws IOException {
final A2ATransaction responseTransaction =
new A2ATransaction(JadeUtils.TRANSACTION_TYPE_ITEM_CREATION_SUCCESS, newItemId);
response.setPerformative(ACLMessage.REQUEST);
response.setContent(JSONParserUtils.serializeToJson(responseTransaction));
send(response);
}
/**
* Propagate item creation to the WebsocketAgent
*
* @param newItem item created
* @throws IOException
*/
public void propagateCreation(MokaItem newItem, User user) throws IOException {
final A2ATransaction transaction =
new A2ATransaction(JadeUtils.TRANSACTION_TYPE_ADD_ITEM, newItem);
sendMessage(getAgentsWithSkill(JadeUtils.JADE_SKILL_NAME_WEBSOCKET_SERVER),
JSONParserUtils.serializeToJson(transaction),
ACLMessage.PROPAGATE);
//TODO do it in one request ? create an item directly with a locker
final HashMap<String, String> info = new HashMap<String, String>();
info.put("itemId", String.valueOf(newItem.getId()));
info.put("userId", user.getIp());
final A2ATransaction transactionToWebSocketAgent = new A2ATransaction(JadeUtils.TRANSACTION_TYPE_LOCK_ITEM_SUCCESS, info);
sendMessage(getAgentsWithSkill(JadeUtils.JADE_SKILL_NAME_WEBSOCKET_SERVER),
JSONParserUtils.serializeToJson(transactionToWebSocketAgent),
jade.lang.acl.ACLMessage.PROPAGATE);
}
/**
* delete an item
*
* @param itemId
* @throws IOException
*/
public void deleteItem(int itemId) throws IOException {
getEnvironment().removeItem(itemId);
final A2ATransaction transaction = new A2ATransaction(JadeUtils.TRANSACTION_TYPE_DELETE_ITEM, itemId);
sendMessage(getAgentsWithSkill(JadeUtils.JADE_SKILL_NAME_WEBSOCKET_SERVER),
JSONParserUtils.serializeToJson(transaction),
jade.lang.acl.ACLMessage.PROPAGATE);
requestAndroidHistoryRefresh();
}
}
| true | true | public void create(final String type, final ACLMessage response, final AID creator) throws IOException {
MokaItem newItem = null;
final MokaEnvironment environment = getEnvironment();
final int newItemId = environment.generateNewId();
if (type.equals("UML")) {
newItem = new UmlClass("MyClass", 200, 350, "UmlClass");
} else if (type.equals("post-it")) {
newItem = new PostIt("Post-it", 300, 350, "Post-it", "Post-it content");
} else if (type.equals("image")) {
newItem = new ImageLink("Image", 400, 450, "http://i1.cdnds.net/13/12/618x959/bill-gates-mugshot.jpg");
} else if (type.equals("video")) {
newItem = new VideoLink("Video", 500, 500, "http://http://www.youtube.com/watch?v=anwy2MPT5RE");
}
if (newItem == null) {
//server side creation failed
//TODO implement callback error in order to warn AndroidDevice which has requested this creation
return;
}
//set creator as Locker
newItem.lock(environment.getUserByAID(creator.toString()));
//set item id
newItem.setId(newItemId);
environment.addItem(newItem);
//send back item id to the creator
sendBackItemId(response, newItemId);
//propagate creation to Ui platform
propagateCreation(newItem, environment.getUserByAID(creator.toString()));
//request refreshing current item list for all android device
requestAndroidCurrentItemsListRefresh();
}
| public void create(final String type, final ACLMessage response, final AID creator) throws IOException {
MokaItem newItem = null;
final MokaEnvironment environment = getEnvironment();
final int newItemId = environment.generateNewId();
if (type.equals("UML")) {
newItem = new UmlClass("MyClass", 200, 350, "UmlClass");
} else if (type.equals("post-it")) {
newItem = new PostIt("Post-it", 300, 350, "Post-it", "Post-it content");
} else if (type.equals("image")) {
newItem = new ImageLink("Image", 400, 450, "http://i1.cdnds.net/13/12/618x959/bill-gates-mugshot.jpg");
} else if (type.equals("video")) {
newItem = new VideoLink("Video", 500, 500, "http://www.youtube.com/watch?v=anwy2MPT5RE");
}
if (newItem == null) {
//server side creation failed
//TODO implement callback error in order to warn AndroidDevice which has requested this creation
return;
}
//set creator as Locker
newItem.lock(environment.getUserByAID(creator.toString()));
//set item id
newItem.setId(newItemId);
environment.addItem(newItem);
//send back item id to the creator
sendBackItemId(response, newItemId);
//propagate creation to Ui platform
propagateCreation(newItem, environment.getUserByAID(creator.toString()));
//request refreshing current item list for all android device
requestAndroidCurrentItemsListRefresh();
}
|
diff --git a/src/main/java/com/almuradev/sprout/plugin/task/GrowthTask.java b/src/main/java/com/almuradev/sprout/plugin/task/GrowthTask.java
index 9eff8df..0e21c76 100644
--- a/src/main/java/com/almuradev/sprout/plugin/task/GrowthTask.java
+++ b/src/main/java/com/almuradev/sprout/plugin/task/GrowthTask.java
@@ -1,177 +1,179 @@
/*
* This file is part of Sprout.
*
* © 2013 AlmuraDev <http://www.almuradev.com/>
* Sprout is licensed under the GNU General Public License.
*
* Sprout 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.
*
* Sprout 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. If not,
* see <http://www.gnu.org/licenses/> for the GNU General Public License.
*/
package com.almuradev.sprout.plugin.task;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import com.almuradev.sprout.api.crop.Sprout;
import com.almuradev.sprout.api.crop.Stage;
import com.almuradev.sprout.api.io.WorldRegistry;
import com.almuradev.sprout.api.mech.Light;
import com.almuradev.sprout.api.util.Int21TripleHashed;
import com.almuradev.sprout.api.util.TInt21TripleObjectHashMap;
import com.almuradev.sprout.plugin.SproutPlugin;
import com.almuradev.sprout.plugin.crop.SimpleSprout;
import com.almuradev.sprout.plugin.thread.SaveThread;
import com.almuradev.sprout.plugin.thread.ThreadRegistry;
import gnu.trove.procedure.TLongObjectProcedure;
import org.getspout.spoutapi.block.SpoutBlock;
import org.getspout.spoutapi.material.CustomBlock;
import org.getspout.spoutapi.material.MaterialData;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.plugin.Plugin;
public class GrowthTask implements Runnable {
private static final Map<String, Integer> WORLD_ID_MAP = new HashMap<>();
private static final Random RANDOM = new Random();
private final SproutPlugin plugin;
private final WorldRegistry worldRegistry;
private final String world;
private long pastTime;
public GrowthTask(SproutPlugin plugin, String world) {
this.plugin = plugin;
this.world = world;
worldRegistry = plugin.getWorldRegistry();
}
public static void schedule(Plugin plugin, boolean log, World... worlds) {
final SproutPlugin sproutPlugin = (SproutPlugin) plugin;
for (World world : worlds) {
if (world == null) {
continue;
}
final Long l = sproutPlugin.getConfiguration().getGrowthIntervalFor(world.getName());
if (l == null) {
continue;
}
if (log) {
plugin.getLogger().info("Growth is scheduled for [" + world.getName() + "] every ~" + l / 20 + " second(s).");
}
WORLD_ID_MAP.put(world.getName(), Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, new GrowthTask(sproutPlugin, world.getName()), 0, l));
//Async saving
ThreadRegistry.add(new SaveThread((SproutPlugin) plugin, world.getName())).start();
}
}
public static void schedule(Plugin plugin, World... worlds) {
schedule(plugin, true, worlds);
}
public static void unschedule(World... worlds) {
for (World world : worlds) {
final Integer id = WORLD_ID_MAP.remove(world.getName());
if (id != null) {
Bukkit.getScheduler().cancelTask(id);
}
ThreadRegistry.remove(world.getName());
}
}
public static void stop(Plugin plugin) {
Bukkit.getScheduler().cancelTasks(plugin);
}
@Override
public void run() {
final TInt21TripleObjectHashMap<?> worldRegistry = this.worldRegistry.get(world);
if (worldRegistry == null) {
return;
}
//First tick
if (pastTime == 0) {
pastTime = System.currentTimeMillis() / 1000;
}
final long localTime = System.currentTimeMillis() / 1000;
final long delta = localTime - pastTime;
pastTime = localTime;
worldRegistry.getInternalMap().forEachEntry(new TLongObjectProcedure<Object>() {
@Override
public boolean execute(long l, Object o) {
final SimpleSprout sprout = (SimpleSprout) o;
final int x = Int21TripleHashed.key1(l);
final int y = Int21TripleHashed.key2(l);
final int z = Int21TripleHashed.key3(l);
+ final int chunkX = x >> 4;
+ final int chunkZ = z >> 4;
final Sprout live = plugin.getWorldRegistry().get(world, x, y, z);
if (!sprout.equals(live)) {
return true;
}
if (!sprout.isFullyGrown()) {
final Stage current = sprout.getCurrentStage();
if (current != null) {
- if (RANDOM.nextInt(current.getGrowthChance() - 1 + 1) + 1 == current.getGrowthChance()) {
- final Block block = Bukkit.getWorld(world).getBlockAt(x, y, z);
- if (block.getChunk().isLoaded()) {
+ if (RANDOM.nextInt((current.getGrowthChance() - 0) + 1) + 0 == current.getGrowthChance()) {
+ if (Bukkit.getWorld(world).isChunkLoaded(chunkX, chunkZ)) {
+ final Block block = Bukkit.getWorld(world).getBlockAt(x, y, z);
final CustomBlock customBlock = MaterialData.getCustomBlock(current.getName());
final Material material = Material.getMaterial(current.getName());
if (customBlock == null) {
if (material == null) {
return true;
}
}
boolean lightPassed = true;
final Light light = current.getLight();
// (A <= B <= C) block inclusive
if (!sprout.getVariables().ignoreLight() && !(light.getMinimumLight() <= block.getLightLevel() && block.getLightLevel() <= light.getMaximumLight())) {
lightPassed = false;
}
if (!lightPassed) {
// not enough light to continue growth task
return true;
}
if (customBlock != null) {
if (((SpoutBlock) block).getCustomBlock() != customBlock) {
((SpoutBlock) block).setCustomBlock(customBlock);
}
} else {
((SpoutBlock) block).setCustomBlock(null);
block.setType(material);
}
if (sprout.isOnLastStage()) {
((SaveThread) ThreadRegistry.get(world)).add(x, y, z, sprout);
sprout.setFullyGrown(true);
} else {
sprout.grow((int) delta);
}
}
}
}
}
return true;
}
}
);
}
}
| false | true | public void run() {
final TInt21TripleObjectHashMap<?> worldRegistry = this.worldRegistry.get(world);
if (worldRegistry == null) {
return;
}
//First tick
if (pastTime == 0) {
pastTime = System.currentTimeMillis() / 1000;
}
final long localTime = System.currentTimeMillis() / 1000;
final long delta = localTime - pastTime;
pastTime = localTime;
worldRegistry.getInternalMap().forEachEntry(new TLongObjectProcedure<Object>() {
@Override
public boolean execute(long l, Object o) {
final SimpleSprout sprout = (SimpleSprout) o;
final int x = Int21TripleHashed.key1(l);
final int y = Int21TripleHashed.key2(l);
final int z = Int21TripleHashed.key3(l);
final Sprout live = plugin.getWorldRegistry().get(world, x, y, z);
if (!sprout.equals(live)) {
return true;
}
if (!sprout.isFullyGrown()) {
final Stage current = sprout.getCurrentStage();
if (current != null) {
if (RANDOM.nextInt(current.getGrowthChance() - 1 + 1) + 1 == current.getGrowthChance()) {
final Block block = Bukkit.getWorld(world).getBlockAt(x, y, z);
if (block.getChunk().isLoaded()) {
final CustomBlock customBlock = MaterialData.getCustomBlock(current.getName());
final Material material = Material.getMaterial(current.getName());
if (customBlock == null) {
if (material == null) {
return true;
}
}
boolean lightPassed = true;
final Light light = current.getLight();
// (A <= B <= C) block inclusive
if (!sprout.getVariables().ignoreLight() && !(light.getMinimumLight() <= block.getLightLevel() && block.getLightLevel() <= light.getMaximumLight())) {
lightPassed = false;
}
if (!lightPassed) {
// not enough light to continue growth task
return true;
}
if (customBlock != null) {
if (((SpoutBlock) block).getCustomBlock() != customBlock) {
((SpoutBlock) block).setCustomBlock(customBlock);
}
} else {
((SpoutBlock) block).setCustomBlock(null);
block.setType(material);
}
if (sprout.isOnLastStage()) {
((SaveThread) ThreadRegistry.get(world)).add(x, y, z, sprout);
sprout.setFullyGrown(true);
} else {
sprout.grow((int) delta);
}
}
}
}
}
return true;
}
}
);
}
| public void run() {
final TInt21TripleObjectHashMap<?> worldRegistry = this.worldRegistry.get(world);
if (worldRegistry == null) {
return;
}
//First tick
if (pastTime == 0) {
pastTime = System.currentTimeMillis() / 1000;
}
final long localTime = System.currentTimeMillis() / 1000;
final long delta = localTime - pastTime;
pastTime = localTime;
worldRegistry.getInternalMap().forEachEntry(new TLongObjectProcedure<Object>() {
@Override
public boolean execute(long l, Object o) {
final SimpleSprout sprout = (SimpleSprout) o;
final int x = Int21TripleHashed.key1(l);
final int y = Int21TripleHashed.key2(l);
final int z = Int21TripleHashed.key3(l);
final int chunkX = x >> 4;
final int chunkZ = z >> 4;
final Sprout live = plugin.getWorldRegistry().get(world, x, y, z);
if (!sprout.equals(live)) {
return true;
}
if (!sprout.isFullyGrown()) {
final Stage current = sprout.getCurrentStage();
if (current != null) {
if (RANDOM.nextInt((current.getGrowthChance() - 0) + 1) + 0 == current.getGrowthChance()) {
if (Bukkit.getWorld(world).isChunkLoaded(chunkX, chunkZ)) {
final Block block = Bukkit.getWorld(world).getBlockAt(x, y, z);
final CustomBlock customBlock = MaterialData.getCustomBlock(current.getName());
final Material material = Material.getMaterial(current.getName());
if (customBlock == null) {
if (material == null) {
return true;
}
}
boolean lightPassed = true;
final Light light = current.getLight();
// (A <= B <= C) block inclusive
if (!sprout.getVariables().ignoreLight() && !(light.getMinimumLight() <= block.getLightLevel() && block.getLightLevel() <= light.getMaximumLight())) {
lightPassed = false;
}
if (!lightPassed) {
// not enough light to continue growth task
return true;
}
if (customBlock != null) {
if (((SpoutBlock) block).getCustomBlock() != customBlock) {
((SpoutBlock) block).setCustomBlock(customBlock);
}
} else {
((SpoutBlock) block).setCustomBlock(null);
block.setType(material);
}
if (sprout.isOnLastStage()) {
((SaveThread) ThreadRegistry.get(world)).add(x, y, z, sprout);
sprout.setFullyGrown(true);
} else {
sprout.grow((int) delta);
}
}
}
}
}
return true;
}
}
);
}
|
diff --git a/src/simple/home/jtbuaa/simpleHome.java b/src/simple/home/jtbuaa/simpleHome.java
index f44a4e5..4795ca8 100755
--- a/src/simple/home/jtbuaa/simpleHome.java
+++ b/src/simple/home/jtbuaa/simpleHome.java
@@ -1,1415 +1,1415 @@
package simple.home.jtbuaa;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import base.lib.HanziToPinyin;
import base.lib.util;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.WallpaperManager;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.IPackageStatsObserver;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageStats;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Parcelable;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.provider.CallLog.Calls;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.telephony.TelephonyManager;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class simpleHome extends Activity implements SensorEventListener, sizedRelativeLayout.OnResizeChangeListener {
int homeTab = 1;
AlertDialog restartDialog = null;
AlertDialog hintDialog = null;
//wall paper related
String downloadPath;
SensorManager sensorMgr;
Sensor mSensor;
float last_x, last_y, last_z;
long lastUpdate, lastSet;
ArrayList<String> picList, picList_selected;
boolean shakeWallpaper = false;
boolean busy;
SharedPreferences perferences;
String wallpaperFile = "";
AppAlphaList sysAlphaList, userAlphaList;
//alpha list related
TextView radioText;
RadioGroup radioGroup;
//app list related
private List<View> mListViews;
GridView favoAppList;
ListView sysAppList, userAppList, shortAppList;
ImageView homeBar, shortBar;
String version, myPackageName;
ViewPager mainlayout;
MyPagerAdapter myPagerAdapter;
RelativeLayout home;
ResolveInfo appDetail;
List<ResolveInfo> mAllApps, mFavoApps, mSysApps, mUserApps, mShortApps;
PackageManager pm;
favoAppAdapter favoAdapter;
shortAppAdapter shortAdapter;
ResolveInfo ri_phone, ri_sms, ri_contact;
CallObserver callObserver;
SmsChangeObserver smsObserver;
ImageView shortcut_phone, shortcut_sms, shortcut_contact;
sizedRelativeLayout base;
RelativeLayout apps;
appHandler mAppHandler = new appHandler();
final static int UPDATE_RI_PHONE = 0, UPDATE_RI_SMS = 1, UPDATE_RI_CONTACT = 2, UPDATE_USER = 3, UPDATE_SPLASH = 4;
ContextMenu mMenu;
ricase selected_case;
boolean canRoot;
DisplayMetrics dm;
IBinder token;
//package size related
HashMap<String, Object> packagesSize;
Method getPackageSizeInfo;
IPackageStatsObserver sizeObserver;
static int sizeM = 1024*1024;
static public com.android.internal.telephony.ITelephony getITelephony(TelephonyManager telMgr) throws Exception {
Method getITelephonyMethod = telMgr.getClass().getDeclaredMethod("getITelephony");
getITelephonyMethod.setAccessible(true);//even private function can use this
return (com.android.internal.telephony.ITelephony)getITelephonyMethod.invoke(telMgr);
}
WallpaperManager mWallpaperManager;
class MyPagerAdapter extends PagerAdapter{
@Override
public void destroyItem(View collection, int arg1, Object view) {
((ViewPager) collection).removeView((View) view);
}
@Override
public void finishUpdate(View arg0) {
}
@Override
public int getCount() {
return mListViews.size();
}
@Override
public Object instantiateItem(View arg0, int arg1) {
((ViewPager) arg0).addView(mListViews.get(arg1), 0);
return mListViews.get(arg1);
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0==(arg1);
}
@Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {
}
@Override
public Parcelable saveState() {
return null;
}
@Override
public void startUpdate(View arg0) {
}
@Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
@Override
protected void onResume() {
if (sysAlphaList.appToDel != null) {
String apkToDel = sysAlphaList.appToDel.activityInfo.applicationInfo.sourceDir;
String res = ShellInterface.doExec(new String[] {"ls /data/data/" + sysAlphaList.appToDel.activityInfo.packageName}, true);
if (res.contains("No such file or directory")) {//uninstalled
String[] cmds = {
"rm " + apkToDel + ".bak",
"rm " + apkToDel.replace(".apk", ".odex")};
//ShellInterface.doExec(cmds);// not really delete.
}
else ShellInterface.doExec(new String[] {"mv " + apkToDel + ".bak " + apkToDel});
sysAlphaList.appToDel = null;
}
shakeWallpaper = perferences.getBoolean("shake", false);
if (shakeWallpaper) {
sensorMgr.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_UI);
busy = false;
}
else {
sensorMgr.unregisterListener(this);
}
super.onResume();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, 0, 0, R.string.wallpaper).setIcon(android.R.drawable.ic_menu_gallery).setAlphabeticShortcut('W');
menu.add(0, 1, 0, R.string.settings).setIcon(android.R.drawable.ic_menu_preferences)
.setIntent(new Intent(android.provider.Settings.ACTION_SETTINGS));
menu.add(0, 2, 0, R.string.help).setIcon(android.R.drawable.ic_menu_help).setAlphabeticShortcut('H');
return true;
}
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
case 0://wallpaper
final Intent pickWallpaper = new Intent(Intent.ACTION_SET_WALLPAPER);
util.startActivity(Intent.createChooser(pickWallpaper, getString(R.string.wallpaper)), true, getBaseContext());
break;
case 1://settings
return super.onOptionsItemSelected(item);
case 2://help dialog
Intent intent = new Intent("about");
intent.setClassName(getPackageName(), About.class.getName());
intent.putExtra("version", version);
intent.putExtra("filename", wallpaperFile);
util.startActivity(intent, false, getBaseContext());
break;
}
return true;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
selected_case = (ricase) v.getTag();
switch (selected_case.mCase) {
case 0://on home
menu.add(0, 0, 0, getString(R.string.removeFromFavo));
break;
case 1://on shortcut
menu.add(0, 1, 0, getString(R.string.removeFromShort));
break;
case 2://on app list
if (mainlayout.getCurrentItem() == 0) {
if (sysAlphaList.mIsGrid)
menu.add(0, 8, 0, getString(R.string.list_view));
else
menu.add(0, 8, 0, getString(R.string.grid_view));
}
else if (mainlayout.getCurrentItem() == 2) {
if (userAlphaList.mIsGrid)
menu.add(0, 8, 0, getString(R.string.list_view));
else
menu.add(0, 8, 0, getString(R.string.grid_view));
}
menu.add(0, 7, 0, getString(R.string.hideapp));
menu.add(0, 4, 0, getString(R.string.appdetail));
menu.add(0, 5, 0, getString(R.string.addtoFavo));
menu.add(0, 6, 0, getString(R.string.addtoShort));
mMenu = menu;
break;
}
}
void writeFile(String name) {
try {
FileOutputStream fo = this.openFileOutput(name, 0);
ObjectOutputStream oos = new ObjectOutputStream(fo);
if (name.equals("short")) {
for (int i = 0; i < mShortApps.size(); i++)
oos.writeObject(((ResolveInfo)mShortApps.get(i)).activityInfo.name);
}
else if (name.equals("favo")) {
for (int i = 0; i < mFavoApps.size(); i++)
oos.writeObject(((ResolveInfo)mFavoApps.get(i)).activityInfo.name);
}
oos.flush();
oos.close();
fo.close();
} catch (Exception e) {}
}
boolean backup(String sourceDir) {//copy file to sdcard
String apk = sourceDir.split("/")[sourceDir.split("/").length-1];
FileOutputStream fos;
FileInputStream fis;
String filename = downloadPath + "apk/" + apk;
try {
File target = new File(filename);
fos = new FileOutputStream(target, false);
fis = new FileInputStream(sourceDir);
byte buf[] = new byte[10240];
int readLength = 0;
while((readLength = fis.read(buf))>0){
fos.write(buf, 0, readLength);
}
fos.close();
fis.close();
} catch (Exception e) {
hintDialog.setMessage(e.toString());
hintDialog.show();
return false;
}
return true;
}
public boolean onContextItemSelected(MenuItem item){
super.onContextItemSelected(item);
ResolveInfo info = null;
if (item.getItemId() < 8) info = (ResolveInfo) selected_case.mRi;
switch (item.getItemId()) {
case 0://remove from home
favoAdapter.remove(info);
writeFile("favo");
break;
case 1://remove from shortcut
shortAdapter.remove(info);
writeFile("short"); //save shortcut to file
break;
case 4://get app detail info
showDetail(info.activityInfo.applicationInfo.sourceDir, info.activityInfo.packageName, info.loadLabel(pm), info.loadIcon(pm));
break;
case 5://add to home
if (favoAdapter.getPosition(info) < 0) {
favoAdapter.add(info);
writeFile("favo");
}
break;
case 6://add to shortcut
if (shortAdapter.getPosition(info) < 0) {
shortAdapter.insert(info, 0);
writeFile("short"); //save shortcut to file
}
break;
case 7://hide the ri
if (mainlayout.getCurrentItem() == 0) {
sysAlphaList.remove(info.activityInfo.packageName);
}
else {
userAlphaList.remove(info.activityInfo.packageName);
}
refreshRadioButton();
break;
case 8://switch view
restartDialog.show();
return true;//break can't finish on some device?
case 9://get package detail info
PackageInfo pi = (PackageInfo) selected_case.mRi;
showDetail(pi.applicationInfo.sourceDir, pi.packageName, pi.applicationInfo.loadLabel(pm), pi.applicationInfo.loadIcon(pm));
break;
}
return false;
}
void showDetail(final String sourceDir, final String packageName, final CharSequence label, Drawable icon) {
AlertDialog detailDlg = new AlertDialog.Builder(this).
setTitle(label).
setIcon(icon).
setMessage(packageName + "\n\n" + sourceDir).
setPositiveButton(R.string.share, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, R.string.share);
String text = label + getString(R.string.app_share_text)
+ "http://bpc.borqs.com/market.html?id=" + packageName;
intent.putExtra(Intent.EXTRA_TEXT, text);
util.startActivity(Intent.createChooser(intent, getString(R.string.sharemode)), true, getBaseContext());
}
}).setNeutralButton(R.string.backapp, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String apk = sourceDir.split("/")[sourceDir.split("/").length-1];
if (backup(sourceDir)) {
String odex = sourceDir.replace(".apk", ".odex");
File target = new File(odex);
boolean backupOdex = true;
if (target.exists())
if (!backup(odex)) backupOdex = false;//backup odex if any
if (backupOdex) {
hintDialog.setMessage(getString(R.string.backapp) + " " +
label + " to " +
downloadPath + "apk/" + apk);
hintDialog.show();
}
}
}
}).
setNegativeButton(R.string.more, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
Intent intent;
if (appDetail != null) {
intent = new Intent(Intent.ACTION_VIEW);
intent.setClassName(appDetail.activityInfo.packageName, appDetail.activityInfo.name);
intent.putExtra("pkg", packageName);
intent.putExtra("com.android.settings.ApplicationPkgName", packageName);
}
else {//2.6 tahiti change the action.
intent = new Intent("android.settings.APPLICATION_DETAILS_SETTINGS", Uri.fromParts("package", packageName, null));
}
util.startActivity(intent, true, getBaseContext());
}
}).create();
boolean canBackup = !downloadPath.startsWith(getFilesDir().getPath());
detailDlg.show();
detailDlg.getButton(DialogInterface.BUTTON_NEUTRAL).setEnabled(canBackup);//not backup if no SDcard.
}
@SuppressWarnings("unchecked")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myPackageName = this.getPackageName();
pm = getPackageManager();
version = util.getVersion(this);
try {
getPackageSizeInfo = PackageManager.class.getMethod(
"getPackageSizeInfo", new Class[] {String.class, IPackageStatsObserver.class});
} catch (Exception e) {
e.printStackTrace();
}
sizeObserver = new IPackageStatsObserver.Stub() {
@Override
public void onGetStatsCompleted(PackageStats pStats,
boolean succeeded) throws RemoteException {
long size = pStats.codeSize;
String ssize = new String();
if (size > 10 * sizeM) ssize = size / sizeM + "M";
else if (size > 10 * 1024) ssize = size / 1024 + "K";
else if (size > 0) ssize = size + "B";
else ssize = "";
packagesSize.put(pStats.packageName, ssize);
}
};
packagesSize = new HashMap<String, Object>();
sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);
mSensor = sensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
perferences = PreferenceManager.getDefaultSharedPreferences(this);
dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
//1,2,3,4 are integer value of small, normal, large and XLARGE screen respectively.
//int screen_size = getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK;
//if (screen_size < Configuration.SCREENLAYOUT_SIZE_LARGE)//disable auto rotate screen for small and normal screen.
//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
requestWindowFeature(Window.FEATURE_NO_TITLE); //hide titlebar of application, must be before setting the layout
setContentView(R.layout.ads);
home = (RelativeLayout) getLayoutInflater().inflate(R.layout.home, null);
//favorite app tab
favoAppList = (GridView) home.findViewById(R.id.favos);
favoAppList.setVerticalScrollBarEnabled(false);
favoAppList.inflate(this, R.layout.app_list, null);
favoAppList.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
shortAppList.setVisibility(View.INVISIBLE);
return false;
}
});
shortAppList = (ListView) home.findViewById(R.id.business);
shortAppList.bringToFront();
shortAppList.setVisibility(View.INVISIBLE);
boolean isGrid = perferences.getBoolean("system", true);
sysAlphaList = new AppAlphaList(this, pm, packagesSize, isGrid, dm.widthPixels > 480);
isGrid = perferences.getBoolean("user", false);
userAlphaList = new AppAlphaList(this, pm, packagesSize, isGrid, dm.widthPixels > 480);
mListViews = new ArrayList<View>();
mListViews.add(sysAlphaList.view);
mListViews.add(home);
mListViews.add(userAlphaList.view);
radioText = (TextView) findViewById(R.id.radio_text);
radioGroup = (RadioGroup) findViewById(R.id.radio_hint);
radioGroup.removeViewAt(0);
mWallpaperManager = WallpaperManager.getInstance(this);
mainlayout = (ViewPager)findViewById(R.id.mainFrame);
mainlayout.setLongClickable(true);
myPagerAdapter = new MyPagerAdapter();
mainlayout.setAdapter(myPagerAdapter);
mainlayout.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageScrollStateChanged(int state) {
if (state == ViewPager.SCROLL_STATE_SETTLING) {
refreshRadioButton();
}
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (!shakeWallpaper) {//don't move wallpaper if change wallpaper by shake
if (token == null) token = mainlayout.getWindowToken();//any token from a component is ok
mWallpaperManager.setWallpaperOffsets(token,
//when slide from home to systems or from systems to home, the "position" is 0,
//when slide from home to users or from users to home, it is 1.
//positionOffset is from 0 to 1. sometime it will jump from 1 to 0, we just omit it if it is 0.
//so we can unify it to (0, 1) by (positionOffset+position)/2
(positionOffset+position)/(mListViews.size()-1), 0);
}
}
@Override
public void onPageSelected(int arg0) {
}
});
mainlayout.setCurrentItem(homeTab);
mSysApps = new ArrayList<ResolveInfo>();
mUserApps = new ArrayList<ResolveInfo>();
mFavoApps = new ArrayList<ResolveInfo>();
mShortApps = new ArrayList<ResolveInfo>();
favoAdapter = new favoAppAdapter(getBaseContext(), mFavoApps);
favoAppList.setAdapter(favoAdapter);
base = (sizedRelativeLayout) home.findViewById(R.id.base);
base.setResizeListener(this);
homeBar = (ImageView) home.findViewById(R.id.home_bar);
homeBar.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent(Intent.ACTION_MAIN);
- intent.setClassName("harley.browsers", "easy.lib.SimpleBrowser");
+ intent.setClassName("harley.browsers", "harley.lib.HarleyBrowser");
if (!util.startActivity(intent, false, getBaseContext())) {
intent.setClassName("easy.browser", "easy.lib.SimpleBrowser");
if (!util.startActivity(intent, false, getBaseContext())) {
//intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=harley.browsers"));
intent.setClassName(myPackageName, "easy.lib.SimpleBrowser");// runtime error. VFY: unable to resolve static field
util.startActivity(intent, true, getBaseContext());
}
}
}
});
shortBar = (ImageView) home.findViewById(R.id.business_bar);
shortBar.setOnClickListener(new OnClickListener() {//by click this bar to show/hide mainlayout
@Override
public void onClick(View arg0) {
if ((shortAppList.getVisibility() == View.INVISIBLE) && !mShortApps.isEmpty())
shortAppList.setVisibility(View.VISIBLE);
else shortAppList.setVisibility(View.INVISIBLE);
}
});
shortcut_phone = (ImageView) home.findViewById(R.id.shortcut_phone);
shortcut_sms = (ImageView) home.findViewById(R.id.shortcut_sms);
//shortcut_contact = (ImageView) findViewById(R.id.shortcut_contact);
//for package add/remove
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_PACKAGE_ADDED);
filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
filter.addDataScheme("package");
registerReceiver(packageReceiver, filter);
//for wall paper changed
filter = new IntentFilter(Intent.ACTION_WALLPAPER_CHANGED);
registerReceiver(wallpaperReceiver, filter);
filter = new IntentFilter("simpleHome.action.HOME_CHANGED");
registerReceiver(homeChangeReceiver, filter);
filter = new IntentFilter("simpleHome.action.PIC_ADDED");
registerReceiver(picAddReceiver, filter);
filter = new IntentFilter("simpleHome.action.SHARE_DESKTOP");
registerReceiver(deskShareReceiver, filter);
filter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);
filter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED);
filter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
filter.addAction(Intent.ACTION_MEDIA_REMOVED);
filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
filter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL);
filter.addDataScheme("file");
registerReceiver(sdcardListener, filter);
apps = (RelativeLayout) findViewById(R.id.apps);
//mWallpaperManager.setWallpaperOffsets(apps.getWindowToken(), 0.5f, 0);//move wallpaper to center, but null pointer?
//TelephonyManager tm = (TelephonyManager) getSystemService(Service.TELEPHONY_SERVICE);
//getITelephony(tm).getActivePhoneType();
ContentResolver cr = getContentResolver();
callObserver = new CallObserver(cr, mAppHandler);
smsObserver = new SmsChangeObserver(cr, mAppHandler);
getContentResolver().registerContentObserver(Calls.CONTENT_URI, true, callObserver);
cr.registerContentObserver(Uri.parse("content://mms-sms/"), true, smsObserver);
//task for init, such as load webview, load package list
InitTask initTask = new InitTask();
initTask.execute("");
restartDialog = new AlertDialog.Builder(this).
setTitle(R.string.app_name).
setIcon(R.drawable.icon).
setMessage(R.string.restart).
setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//save the layout
SharedPreferences.Editor editor = perferences.edit();
if (mainlayout.getCurrentItem() == 0)
editor.putBoolean("system", !sysAlphaList.mIsGrid);
else if (mainlayout.getCurrentItem() == 2)
editor.putBoolean("user", !userAlphaList.mIsGrid);
editor.commit();
//restart the activity. note if set singleinstance or singletask of activity, below will not work on some device.
Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}
}).
setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).create();
hintDialog = new AlertDialog.Builder(this).
setNegativeButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).create();
}
@Override
protected void onDestroy() {
unregisterReceiver(packageReceiver);
unregisterReceiver(wallpaperReceiver);
unregisterReceiver(picAddReceiver);
unregisterReceiver(deskShareReceiver);
unregisterReceiver(homeChangeReceiver);
unregisterReceiver(sdcardListener);
super.onDestroy();
}
BroadcastReceiver sdcardListener = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(Intent.ACTION_MEDIA_MOUNTED.equals(action)
|| Intent.ACTION_MEDIA_SCANNER_STARTED.equals(action)
|| Intent.ACTION_MEDIA_SCANNER_FINISHED.equals(action)
){// mount sd card success
if (downloadPath != null)
downloadPath = Environment.getExternalStorageDirectory() + "/simpleHome/";
if (mMenu != null) mMenu.getItem(3).setEnabled(true);
} else if(Intent.ACTION_MEDIA_REMOVED.equals(action)
|| Intent.ACTION_MEDIA_UNMOUNTED.equals(action)
|| Intent.ACTION_MEDIA_BAD_REMOVAL.equals(action)
){// fail to mount sd card
if (downloadPath != null)
downloadPath = getFilesDir().getPath() + "/";
if (mMenu != null) mMenu.getItem(3).setEnabled(false);
}
}
};
BroadcastReceiver wallpaperReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
apps.setBackgroundColor(0);//set back ground to transparent to show wallpaper
wallpaperFile = "";
}
};
BroadcastReceiver picAddReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String picName = intent.getStringExtra("picFile");
picList.add(picName);//add to picture list
SharedPreferences.Editor editor = perferences.edit();
editor.putBoolean("shake_enabled", true);
editor.commit();
}
};
BroadcastReceiver deskShareReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String snap = downloadPath + "snap/snap.png";
FileOutputStream fos;
try {//prepare for share desktop
fos = new FileOutputStream(snap);
apps.setDrawingCacheEnabled(true);
Bitmap bmp = apps.getDrawingCache();
bmp.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
apps.destroyDrawingCache();
} catch (Exception e) {
}
Intent intentSend = new Intent(Intent.ACTION_SEND);
intentSend.setType("image/*");
intentSend.putExtra(Intent.EXTRA_SUBJECT, R.string.share);
intentSend.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(downloadPath + "snap/snap.png")));
util.startActivity(Intent.createChooser(intentSend, getString(R.string.sharemode)), true, getBaseContext());
}
};
BroadcastReceiver homeChangeReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String homeName = intent.getStringExtra("old_home");
if(homeName.equals(myPackageName)) finish();
}
};
void refreshRadioButton() {
int current = mainlayout.getCurrentItem();
radioGroup.clearCheck();
if (current < radioGroup.getChildCount()) ((RadioButton) radioGroup.getChildAt(current)).setChecked(true);// crash once for C lassCastException.
if (current == 0)
radioText.setText(getString(R.string.systemapps) + "(" + sysAlphaList.getCount() + ")");
else if (current == 2)
radioText.setText(getString(R.string.userapps) + "(" + userAlphaList.getCount() + ")");
else radioText.setText("Home");
}
BroadcastReceiver packageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String packageName = intent.getDataString().split(":")[1];//it always in the format of package:x.y.z
if (action.equals(Intent.ACTION_PACKAGE_REMOVED)) {
ResolveInfo info = userAlphaList.remove(packageName);
if (info == null) info = sysAlphaList.remove(packageName);
refreshRadioButton();
if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {//not remove shortcut if it is just replace
for (int i = 0; i < favoAdapter.getCount(); i++) {
info = favoAdapter.getItem(i);
if (info.activityInfo.packageName.equals(packageName)) {
favoAdapter.remove(info);
writeFile("favo");
break;
}
}
for (int i = 0; i < shortAdapter.getCount(); i++) {
info = shortAdapter.getItem(i);
if (info.activityInfo.packageName.equals(packageName)) {
shortAdapter.remove(info);
writeFile("short");
break;
}
}
}
}
else if (action.equals(Intent.ACTION_PACKAGE_ADDED)) {
try {//get size of new installed package
getPackageSizeInfo.invoke(pm, packageName, sizeObserver);
} catch (Exception e) {
e.printStackTrace();
}
Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
mainIntent.setPackage(packageName);
List<ResolveInfo> targetApps = pm.queryIntentActivities(mainIntent, 0);
for (int i = 0; i < targetApps.size(); i++) {
if (targetApps.get(i).activityInfo.packageName.equals(packageName) ) {//the new package may not support Launcher category, we will omit it.
ResolveInfo ri = targetApps.get(i);
CharSequence sa = ri.loadLabel(pm);
if (sa == null) sa = ri.activityInfo.name;
ri.activityInfo.applicationInfo.dataDir = getToken(sa);//we borrow dataDir to store the Pinyin of the label.
String tmp = ri.activityInfo.applicationInfo.dataDir.substring(0, 1);
if ((ri.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == ApplicationInfo.FLAG_SYSTEM) {
sysAlphaList.add(ri);
break;
}
else {
userAlphaList.add(ri);
break;
}
}
}
refreshRadioButton();
}
}
};
private class favoAppAdapter extends ArrayAdapter<ResolveInfo> {
ArrayList<ResolveInfo> localApplist;
public favoAppAdapter(Context context, List<ResolveInfo> apps) {
super(context, 0, apps);
localApplist = (ArrayList<ResolveInfo>) apps;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ResolveInfo info = (ResolveInfo) localApplist.get(position);
if (convertView == null) {
final LayoutInflater inflater = getLayoutInflater();
convertView = inflater.inflate(R.layout.favo_list, parent, false);
}
convertView.setBackgroundColor(0);
final ImageView btnIcon = (ImageView) convertView.findViewById(R.id.favoappicon);
btnIcon.setImageDrawable(info.loadIcon(pm));
btnIcon.setOnClickListener(new OnClickListener() {//start app
@Override
public void onClick(View arg0) {
util.startApp(info, getBaseContext());
}
});
btnIcon.setTag(new ricase(info, 0));
registerForContextMenu(btnIcon);
return convertView;
}
}
private class shortAppAdapter extends ArrayAdapter<ResolveInfo> {
ArrayList<ResolveInfo> localApplist;
public shortAppAdapter(Context context, List<ResolveInfo> apps) {
super(context, 0, apps);
localApplist = (ArrayList<ResolveInfo>) apps;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ResolveInfo info = (ResolveInfo) localApplist.get(position);
if (convertView == null) {
final LayoutInflater inflater = getLayoutInflater();
convertView = inflater.inflate(R.layout.favo_list, parent, false);
}
final ImageView btnIcon = (ImageView) convertView.findViewById(R.id.favoappicon);
btnIcon.setImageDrawable(info.loadIcon(pm));
TextView appname = (TextView) convertView.findViewById(R.id.favoappname);
appname.setText(info.loadLabel(pm));
convertView.setOnClickListener(new OnClickListener() {//launch app
@Override
public void onClick(View arg0) {
util.startApp(info, getBaseContext());
shortAppList.setVisibility(View.INVISIBLE);
}
});
convertView.setTag(new ricase(info, 1));
registerForContextMenu(convertView);
return convertView;
}
}
void readFile(String name)
{
FileInputStream fi = null;
ObjectInputStream ois = null;
try {//read favorite or shortcut data
fi = openFileInput(name);
ois = new ObjectInputStream(fi);
String activityName;
while ((activityName = (String) ois.readObject()) != null) {
for (int i = 0; i < mAllApps.size(); i++)
if (mAllApps.get(i).activityInfo.name.equals(activityName)) {
if (name.equals("favo")) mFavoApps.add(mAllApps.get(i));
else if (name.equals("short")) mShortApps.add(mAllApps.get(i));
break;
}
}
} catch (EOFException e) {//only when read eof need send out msg.
try {
ois.close();
fi.close();
} catch (IOException e1) {
e1.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public String getToken(CharSequence sa) {
String sa1 = sa.toString().trim();
String sa2 = sa1;
if (sa1.length() > 0) {
try {//this is to fix a bug report by market
sa2 = HanziToPinyin.getInstance().getToken(sa1.charAt(0)).target.trim();
if (sa2.length() > 1) sa2 = sa2.substring(0, 1);
} catch(Exception e) {
e.printStackTrace();
}
}
sa2 = sa2.toUpperCase();
if ((sa2.compareTo("A") < 0) || (sa2.compareTo("Z") > 0)) sa2 = "#";//for space or number, we change to #
return sa2;
}
class InitTask extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... params) {//do all time consuming work here
canRoot = false;
String res = ShellInterface.doExec(new String[] {"id"}, true);
if (res.contains("root")) {
res = ShellInterface.doExec(new String[] {"mount -o rw,remount -t yaffs2 /dev/block/mtdblock3 /system"}, true);
if (res.contains("Error")) canRoot = false;
else canRoot = true;
}
Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
mAllApps = pm.queryIntentActivities(mainIntent, 0);
readFile("favo");
readFile("short");
boolean shortEmpty = mShortApps.isEmpty();
//read all resolveinfo
String label_sms = "簡訊 Messaging Messages メッセージ 信息 消息 短信 메시지 Mensajes Messaggi Berichten SMS a MMS SMS/MMS"; //use label name to get short cut
String label_phone = "電話 Phone 电话 电话和联系人 拨号键盘 키패드 Telefon Teléfono Téléphone Telefono Telefoon Телефон 휴대전화 Dialer";
String label_contact = "聯絡人 联系人 Contacts People 連絡先 通讯录 전화번호부 Kontakty Kontakte Contactos Contatti Contacten Контакты 주소록";
int match = 0;
for (int i = 0; i < mAllApps.size(); i++) {
ResolveInfo ri = mAllApps.get(i);
CharSequence sa = ri.loadLabel(pm);
if (sa == null) sa = ri.activityInfo.name;
ri.activityInfo.applicationInfo.dataDir = getToken(sa);//we borrow dataDir to store the Pinyin of the label.
if ((ri.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == ApplicationInfo.FLAG_SYSTEM) {
sysAlphaList.add(ri, false, false);
if (match < 3) {//only find 3 match: sms, phone, contact
String name = sa.toString() ;
//Log.d("===============", name);
if (label_phone.contains(name)) {
if (ri_phone == null) {
ri_phone = ri;
Message msgphone = mAppHandler.obtainMessage();
msgphone.what = UPDATE_RI_PHONE;
mAppHandler.sendMessage(msgphone);//inform UI thread to update UI.
match += 1;
}
}
else if (label_sms.contains(name)) {
if ((ri_sms == null) && (!name.equals("MM"))) {
ri_sms = ri;
Message msgsms = mAppHandler.obtainMessage();
msgsms.what = UPDATE_RI_SMS;
mAppHandler.sendMessage(msgsms);//inform UI thread to update UI.
match += 1;
}
}
else if ((shortEmpty) && label_contact.contains(name)) {//only add contact to shortcut if shortcut is empty.
if (ri_contact == null) {
mShortApps.add(ri);
/*ri_contact = ri;
Message msgcontact = mAppHandler.obtainMessage();
msgcontact.what = UPDATE_RI_CONTACT;
mAppHandler.sendMessage(msgcontact);//inform UI thread to update UI.*/
match += 1;
}
}
}
}
else userAlphaList.add(ri, false, false);
try {
getPackageSizeInfo.invoke(pm, ri.activityInfo.packageName, sizeObserver);
} catch (Exception e) {
e.printStackTrace();
}
}
sysAlphaList.sortAlpha();
userAlphaList.sortAlpha();
Message msguser = mAppHandler.obtainMessage();
msguser.what = UPDATE_USER;
mAppHandler.sendMessage(msguser);//inform UI thread to update UI.
downloadPath = util.preparePath(getBaseContext());
picList = new ArrayList();
picList_selected = new ArrayList();
new File(downloadPath).list(new OnlyPic());
if (picList.size() > 0) {
SharedPreferences.Editor editor = perferences.edit();
editor.putBoolean("shake_enabled", true);
editor.commit();
}
mainIntent = new Intent(Intent.ACTION_VIEW, null);
mainIntent.addCategory(Intent.CATEGORY_DEFAULT);
List<ResolveInfo> viewApps = pm.queryIntentActivities(mainIntent, 0);
appDetail = null;
for (int i = 0; i < viewApps.size(); i++) {
if (viewApps.get(i).activityInfo.name.contains("InstalledAppDetails")) {
appDetail = viewApps.get(i);//get the activity for app detail setting
break;
}
}
return null;
}
}
class OnlyPic implements FilenameFilter {
public boolean accept(File dir, String s) {
String name = s.toLowerCase();
if (s.endsWith(".png") || s.endsWith(".jpg")) {
picList.add(s);
return true;
}
else return false;
}
}
class appHandler extends Handler {
public void handleMessage(Message msg) {
switch (msg.what) {
case UPDATE_USER:
sysAlphaList.setAdapter();
userAlphaList.setAdapter();
refreshRadioButton();//this will update the radio button with correct app number. only for very slow phone
shortAdapter = new shortAppAdapter(getBaseContext(), mShortApps);
shortAppList.setAdapter(shortAdapter);
break;
case UPDATE_RI_PHONE:
int missCallCount = callObserver.countUnread();
if (missCallCount > 0) {
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.phone);
shortcut_phone.setImageBitmap(util.generatorCountIcon(bm, missCallCount, 1, 1, getBaseContext()));
}
else shortcut_phone.setImageResource(R.drawable.phone);
shortcut_phone.setOnClickListener(new OnClickListener() {//start app
@Override
public void onClick(View arg0) {
util.startApp(ri_phone, getBaseContext());
}
});
break;
case UPDATE_RI_SMS:
int unreadCount = smsObserver.countUnread();
if (unreadCount > 0) {
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.sms);
shortcut_sms.setImageBitmap(util.generatorCountIcon(bm, unreadCount, 1, 1, getBaseContext()));
}
else shortcut_sms.setImageResource(R.drawable.sms);
shortcut_sms.setOnClickListener(new OnClickListener() {//start app
@Override
public void onClick(View arg0) {
util.startApp(ri_sms, getBaseContext());
}
});
break;
case UPDATE_RI_CONTACT:
shortcut_contact.setImageDrawable(ri_contact.loadIcon(pm));
shortcut_contact.setOnClickListener(new OnClickListener() {//start app
@Override
public void onClick(View arg0) {
util.startApp(ri_contact, getBaseContext());
}
});
break;
}
}
};
@Override
protected void onNewIntent(Intent intent) {//go back to home if press Home key.
if ((intent.getAction().equals(Intent.ACTION_MAIN)) && (intent.hasCategory(Intent.CATEGORY_HOME))) {
if (mainlayout.getCurrentItem() != homeTab) mainlayout.setCurrentItem(homeTab);
else if (shortAppList.getVisibility() == View.VISIBLE) shortBar.performClick();
}
super.onNewIntent(intent);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getRepeatCount() == 0) {
if (keyCode == KeyEvent.KEYCODE_BACK) {//press Back key in webview will go backword.
if (mainlayout.getCurrentItem() != homeTab) mainlayout.setCurrentItem(homeTab);
else if (shortAppList.getVisibility() == View.VISIBLE) shortBar.performClick();
else this.openOptionsMenu();
return true;
}
}
return false;
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig); //not restart activity each time screen orientation changes
getWindowManager().getDefaultDisplay().getMetrics(dm);
if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO)
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
@Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
}
@Override
public void onSensorChanged(SensorEvent arg0) {
if (arg0.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
long curTime = System.currentTimeMillis();
// detect every 100ms
if ((curTime - lastUpdate) > 100) {
long timeInterval = (curTime - lastUpdate);
lastUpdate = curTime;
float x = arg0.values[SensorManager.DATA_X];
float y = arg0.values[SensorManager.DATA_Y];
float z = arg0.values[SensorManager.DATA_Z];
float deltaX = x - last_x;
float deltaY = y - last_y;
float deltaZ = z - last_z;
double speed = Math.sqrt(deltaX*deltaX + deltaY*deltaY + deltaZ*deltaZ)/timeInterval * 100;
//condition to change wallpaper: speed is enough; frequency is not too high; picList is not empty.
if ((!busy) && (speed > 8) && (curTime - lastSet > 500) && (picList != null) && (picList.size() > 0)) {
busy = true;
Random random = new Random();
int id = random.nextInt(picList.size());
try {
wallpaperFile = downloadPath + picList.get(id);
BitmapDrawable bd = (BitmapDrawable) BitmapDrawable.createFromPath(wallpaperFile);
double factor = 1.0 * bd.getIntrinsicWidth() / bd.getIntrinsicHeight();
if (factor >= 1.2) {//if too wide, we want use setWallpaperOffsets to move it, so we need set it to wallpaper
int tmpWidth = (int) (dm.heightPixels * factor);
mWallpaperManager.setBitmap(Bitmap.createScaledBitmap(bd.getBitmap(), tmpWidth, dm.heightPixels, false));
mWallpaperManager.suggestDesiredDimensions(tmpWidth, dm.heightPixels);
sensorMgr.unregisterListener(this);
SharedPreferences.Editor editor = perferences.edit();
shakeWallpaper = false;
editor.putBoolean("shake", false);
editor.commit();
}
else {//otherwise just change the background is ok.
ClippedDrawable cd = new ClippedDrawable(bd, apps.getWidth(), apps.getHeight());
apps.setBackgroundDrawable(cd);
}
picList_selected.add(picList.get(id));
picList.remove(id);//prevent it be selected again before a full cycle
lastSet = System.currentTimeMillis();
} catch (Exception e) {
e.printStackTrace();
picList.remove(id);
wallpaperFile = "";
}
if (picList.isEmpty()) {
if (picList_selected.isEmpty()) {
sensorMgr.unregisterListener(this);
SharedPreferences.Editor editor = perferences.edit();
editor.putBoolean("shake_enabled", false);
shakeWallpaper = false;
editor.putBoolean("shake", false);
editor.commit();
}
else {
picList = (ArrayList<String>) picList_selected.clone();
picList_selected.clear();
}
}
busy = false;
}
last_x = x;
last_y = y;
last_z = z;
}
}
}
@Override
public void onSizeChanged(int w, int h, int oldW, int oldH) {
//setLayout(oldW);
}
}
/** from Android Home sample
* When a drawable is attached to a View, the View gives the Drawable its dimensions
* by calling Drawable.setBounds(). In this application, the View that draws the
* wallpaper has the same size as the screen. However, the wallpaper might be larger
* that the screen which means it will be automatically stretched. Because stretching
* a bitmap while drawing it is very expensive, we use a ClippedDrawable instead.
* This drawable simply draws another wallpaper but makes sure it is not stretched
* by always giving it its intrinsic dimensions. If the wallpaper is larger than the
* screen, it will simply get clipped but it won't impact performance.
*/
class ClippedDrawable extends Drawable {
private final Drawable mWallpaper;
int screenWidth, screenHeight;
boolean tooWide = false;
public ClippedDrawable(Drawable wallpaper, int sw, int sh) {
mWallpaper = wallpaper;
screenWidth = sw;
screenHeight = sh;
}
@Override
public void setBounds(int left, int top, int right, int bottom) {
super.setBounds(left, top, right, bottom);
// Ensure the wallpaper is as large as it really is, to avoid stretching it at drawing time
int tmpHeight = mWallpaper.getIntrinsicHeight() * screenWidth / mWallpaper.getIntrinsicWidth();
int tmpWidth = mWallpaper.getIntrinsicWidth() * screenHeight / mWallpaper.getIntrinsicHeight();
if (tmpHeight >= screenHeight) {
top -= (tmpHeight - screenHeight)/2;
mWallpaper.setBounds(left, top, left + screenWidth, top + tmpHeight);
}
else {//if the pic width is wider than screen width, then we need show part of the pic.
tooWide = true;
left -= (tmpWidth - screenWidth)/2;
mWallpaper.setBounds(left, top, left + tmpWidth, top + screenHeight);
}
}
public void draw(Canvas canvas) {
mWallpaper.draw(canvas);
}
public void setAlpha(int alpha) {
mWallpaper.setAlpha(alpha);
}
public void setColorFilter(ColorFilter cf) {
mWallpaper.setColorFilter(cf);
}
public int getOpacity() {
return mWallpaper.getOpacity();
}
}
class sizedRelativeLayout extends RelativeLayout {
public sizedRelativeLayout(Context context) {
super(context);
}
public sizedRelativeLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
private OnResizeChangeListener mOnResizeChangeListener;
protected void onSizeChanged(int w, int h, int oldW, int oldH) {
if(mOnResizeChangeListener!=null){
mOnResizeChangeListener.onSizeChanged(w,h,oldW,oldH);
}
super.onSizeChanged(w,h,oldW,oldH);
}
public void setResizeListener(OnResizeChangeListener l) {
mOnResizeChangeListener = l;
}
public interface OnResizeChangeListener{
void onSizeChanged(int w,int h,int oldW,int oldH);
}
}
class SmsChangeObserver extends ContentObserver {
ContentResolver mCR;
Handler mHandler;
public SmsChangeObserver(ContentResolver cr, Handler handler) {
super(handler);
mCR = cr;
mHandler = handler;
}
public int countUnread() {
//get sms unread count
int ret = 0;
Cursor csr = mCR.query(Uri.parse("content://sms"),
new String[] {"thread_id"},
"read=0",
null,
null);
if (csr != null) ret = csr.getCount();
//get mms unread count
csr = mCR.query(Uri.parse("content://mms"),
new String[] {"thread_id"},
"read=0",
null,
null);
if (csr != null) ret += csr.getCount();
return ret;
}
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
Message msgsms = mHandler.obtainMessage();
msgsms.what = 1;//UPDATE_RI_SMS;
mHandler.sendMessage(msgsms);//inform UI thread to update UI.
}
}
class CallObserver extends ContentObserver {
ContentResolver mCR;
Handler mHandler;
public CallObserver(ContentResolver cr, Handler handler) {
super(handler);
mHandler = handler;
mCR = cr;
}
public int countUnread() {
//get missed call number
Cursor csr = mCR.query(Calls.CONTENT_URI,
new String[] {Calls.NUMBER, Calls.TYPE, Calls.NEW},
Calls.TYPE + "=" + Calls.MISSED_TYPE + " AND " + Calls.NEW + "=1",
null, Calls.DEFAULT_SORT_ORDER);
if (csr != null) return csr.getCount();
else return 0;
}
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
Message msgphone = mHandler.obtainMessage();
msgphone.what = 0;//UPDATE_RI_PHONE;
mHandler.sendMessage(msgphone);//inform UI thread to update UI.
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myPackageName = this.getPackageName();
pm = getPackageManager();
version = util.getVersion(this);
try {
getPackageSizeInfo = PackageManager.class.getMethod(
"getPackageSizeInfo", new Class[] {String.class, IPackageStatsObserver.class});
} catch (Exception e) {
e.printStackTrace();
}
sizeObserver = new IPackageStatsObserver.Stub() {
@Override
public void onGetStatsCompleted(PackageStats pStats,
boolean succeeded) throws RemoteException {
long size = pStats.codeSize;
String ssize = new String();
if (size > 10 * sizeM) ssize = size / sizeM + "M";
else if (size > 10 * 1024) ssize = size / 1024 + "K";
else if (size > 0) ssize = size + "B";
else ssize = "";
packagesSize.put(pStats.packageName, ssize);
}
};
packagesSize = new HashMap<String, Object>();
sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);
mSensor = sensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
perferences = PreferenceManager.getDefaultSharedPreferences(this);
dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
//1,2,3,4 are integer value of small, normal, large and XLARGE screen respectively.
//int screen_size = getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK;
//if (screen_size < Configuration.SCREENLAYOUT_SIZE_LARGE)//disable auto rotate screen for small and normal screen.
//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
requestWindowFeature(Window.FEATURE_NO_TITLE); //hide titlebar of application, must be before setting the layout
setContentView(R.layout.ads);
home = (RelativeLayout) getLayoutInflater().inflate(R.layout.home, null);
//favorite app tab
favoAppList = (GridView) home.findViewById(R.id.favos);
favoAppList.setVerticalScrollBarEnabled(false);
favoAppList.inflate(this, R.layout.app_list, null);
favoAppList.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
shortAppList.setVisibility(View.INVISIBLE);
return false;
}
});
shortAppList = (ListView) home.findViewById(R.id.business);
shortAppList.bringToFront();
shortAppList.setVisibility(View.INVISIBLE);
boolean isGrid = perferences.getBoolean("system", true);
sysAlphaList = new AppAlphaList(this, pm, packagesSize, isGrid, dm.widthPixels > 480);
isGrid = perferences.getBoolean("user", false);
userAlphaList = new AppAlphaList(this, pm, packagesSize, isGrid, dm.widthPixels > 480);
mListViews = new ArrayList<View>();
mListViews.add(sysAlphaList.view);
mListViews.add(home);
mListViews.add(userAlphaList.view);
radioText = (TextView) findViewById(R.id.radio_text);
radioGroup = (RadioGroup) findViewById(R.id.radio_hint);
radioGroup.removeViewAt(0);
mWallpaperManager = WallpaperManager.getInstance(this);
mainlayout = (ViewPager)findViewById(R.id.mainFrame);
mainlayout.setLongClickable(true);
myPagerAdapter = new MyPagerAdapter();
mainlayout.setAdapter(myPagerAdapter);
mainlayout.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageScrollStateChanged(int state) {
if (state == ViewPager.SCROLL_STATE_SETTLING) {
refreshRadioButton();
}
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (!shakeWallpaper) {//don't move wallpaper if change wallpaper by shake
if (token == null) token = mainlayout.getWindowToken();//any token from a component is ok
mWallpaperManager.setWallpaperOffsets(token,
//when slide from home to systems or from systems to home, the "position" is 0,
//when slide from home to users or from users to home, it is 1.
//positionOffset is from 0 to 1. sometime it will jump from 1 to 0, we just omit it if it is 0.
//so we can unify it to (0, 1) by (positionOffset+position)/2
(positionOffset+position)/(mListViews.size()-1), 0);
}
}
@Override
public void onPageSelected(int arg0) {
}
});
mainlayout.setCurrentItem(homeTab);
mSysApps = new ArrayList<ResolveInfo>();
mUserApps = new ArrayList<ResolveInfo>();
mFavoApps = new ArrayList<ResolveInfo>();
mShortApps = new ArrayList<ResolveInfo>();
favoAdapter = new favoAppAdapter(getBaseContext(), mFavoApps);
favoAppList.setAdapter(favoAdapter);
base = (sizedRelativeLayout) home.findViewById(R.id.base);
base.setResizeListener(this);
homeBar = (ImageView) home.findViewById(R.id.home_bar);
homeBar.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClassName("harley.browsers", "easy.lib.SimpleBrowser");
if (!util.startActivity(intent, false, getBaseContext())) {
intent.setClassName("easy.browser", "easy.lib.SimpleBrowser");
if (!util.startActivity(intent, false, getBaseContext())) {
//intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=harley.browsers"));
intent.setClassName(myPackageName, "easy.lib.SimpleBrowser");// runtime error. VFY: unable to resolve static field
util.startActivity(intent, true, getBaseContext());
}
}
}
});
shortBar = (ImageView) home.findViewById(R.id.business_bar);
shortBar.setOnClickListener(new OnClickListener() {//by click this bar to show/hide mainlayout
@Override
public void onClick(View arg0) {
if ((shortAppList.getVisibility() == View.INVISIBLE) && !mShortApps.isEmpty())
shortAppList.setVisibility(View.VISIBLE);
else shortAppList.setVisibility(View.INVISIBLE);
}
});
shortcut_phone = (ImageView) home.findViewById(R.id.shortcut_phone);
shortcut_sms = (ImageView) home.findViewById(R.id.shortcut_sms);
//shortcut_contact = (ImageView) findViewById(R.id.shortcut_contact);
//for package add/remove
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_PACKAGE_ADDED);
filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
filter.addDataScheme("package");
registerReceiver(packageReceiver, filter);
//for wall paper changed
filter = new IntentFilter(Intent.ACTION_WALLPAPER_CHANGED);
registerReceiver(wallpaperReceiver, filter);
filter = new IntentFilter("simpleHome.action.HOME_CHANGED");
registerReceiver(homeChangeReceiver, filter);
filter = new IntentFilter("simpleHome.action.PIC_ADDED");
registerReceiver(picAddReceiver, filter);
filter = new IntentFilter("simpleHome.action.SHARE_DESKTOP");
registerReceiver(deskShareReceiver, filter);
filter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);
filter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED);
filter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
filter.addAction(Intent.ACTION_MEDIA_REMOVED);
filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
filter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL);
filter.addDataScheme("file");
registerReceiver(sdcardListener, filter);
apps = (RelativeLayout) findViewById(R.id.apps);
//mWallpaperManager.setWallpaperOffsets(apps.getWindowToken(), 0.5f, 0);//move wallpaper to center, but null pointer?
//TelephonyManager tm = (TelephonyManager) getSystemService(Service.TELEPHONY_SERVICE);
//getITelephony(tm).getActivePhoneType();
ContentResolver cr = getContentResolver();
callObserver = new CallObserver(cr, mAppHandler);
smsObserver = new SmsChangeObserver(cr, mAppHandler);
getContentResolver().registerContentObserver(Calls.CONTENT_URI, true, callObserver);
cr.registerContentObserver(Uri.parse("content://mms-sms/"), true, smsObserver);
//task for init, such as load webview, load package list
InitTask initTask = new InitTask();
initTask.execute("");
restartDialog = new AlertDialog.Builder(this).
setTitle(R.string.app_name).
setIcon(R.drawable.icon).
setMessage(R.string.restart).
setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//save the layout
SharedPreferences.Editor editor = perferences.edit();
if (mainlayout.getCurrentItem() == 0)
editor.putBoolean("system", !sysAlphaList.mIsGrid);
else if (mainlayout.getCurrentItem() == 2)
editor.putBoolean("user", !userAlphaList.mIsGrid);
editor.commit();
//restart the activity. note if set singleinstance or singletask of activity, below will not work on some device.
Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}
}).
setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).create();
hintDialog = new AlertDialog.Builder(this).
setNegativeButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).create();
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myPackageName = this.getPackageName();
pm = getPackageManager();
version = util.getVersion(this);
try {
getPackageSizeInfo = PackageManager.class.getMethod(
"getPackageSizeInfo", new Class[] {String.class, IPackageStatsObserver.class});
} catch (Exception e) {
e.printStackTrace();
}
sizeObserver = new IPackageStatsObserver.Stub() {
@Override
public void onGetStatsCompleted(PackageStats pStats,
boolean succeeded) throws RemoteException {
long size = pStats.codeSize;
String ssize = new String();
if (size > 10 * sizeM) ssize = size / sizeM + "M";
else if (size > 10 * 1024) ssize = size / 1024 + "K";
else if (size > 0) ssize = size + "B";
else ssize = "";
packagesSize.put(pStats.packageName, ssize);
}
};
packagesSize = new HashMap<String, Object>();
sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);
mSensor = sensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
perferences = PreferenceManager.getDefaultSharedPreferences(this);
dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
//1,2,3,4 are integer value of small, normal, large and XLARGE screen respectively.
//int screen_size = getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK;
//if (screen_size < Configuration.SCREENLAYOUT_SIZE_LARGE)//disable auto rotate screen for small and normal screen.
//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
requestWindowFeature(Window.FEATURE_NO_TITLE); //hide titlebar of application, must be before setting the layout
setContentView(R.layout.ads);
home = (RelativeLayout) getLayoutInflater().inflate(R.layout.home, null);
//favorite app tab
favoAppList = (GridView) home.findViewById(R.id.favos);
favoAppList.setVerticalScrollBarEnabled(false);
favoAppList.inflate(this, R.layout.app_list, null);
favoAppList.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
shortAppList.setVisibility(View.INVISIBLE);
return false;
}
});
shortAppList = (ListView) home.findViewById(R.id.business);
shortAppList.bringToFront();
shortAppList.setVisibility(View.INVISIBLE);
boolean isGrid = perferences.getBoolean("system", true);
sysAlphaList = new AppAlphaList(this, pm, packagesSize, isGrid, dm.widthPixels > 480);
isGrid = perferences.getBoolean("user", false);
userAlphaList = new AppAlphaList(this, pm, packagesSize, isGrid, dm.widthPixels > 480);
mListViews = new ArrayList<View>();
mListViews.add(sysAlphaList.view);
mListViews.add(home);
mListViews.add(userAlphaList.view);
radioText = (TextView) findViewById(R.id.radio_text);
radioGroup = (RadioGroup) findViewById(R.id.radio_hint);
radioGroup.removeViewAt(0);
mWallpaperManager = WallpaperManager.getInstance(this);
mainlayout = (ViewPager)findViewById(R.id.mainFrame);
mainlayout.setLongClickable(true);
myPagerAdapter = new MyPagerAdapter();
mainlayout.setAdapter(myPagerAdapter);
mainlayout.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageScrollStateChanged(int state) {
if (state == ViewPager.SCROLL_STATE_SETTLING) {
refreshRadioButton();
}
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (!shakeWallpaper) {//don't move wallpaper if change wallpaper by shake
if (token == null) token = mainlayout.getWindowToken();//any token from a component is ok
mWallpaperManager.setWallpaperOffsets(token,
//when slide from home to systems or from systems to home, the "position" is 0,
//when slide from home to users or from users to home, it is 1.
//positionOffset is from 0 to 1. sometime it will jump from 1 to 0, we just omit it if it is 0.
//so we can unify it to (0, 1) by (positionOffset+position)/2
(positionOffset+position)/(mListViews.size()-1), 0);
}
}
@Override
public void onPageSelected(int arg0) {
}
});
mainlayout.setCurrentItem(homeTab);
mSysApps = new ArrayList<ResolveInfo>();
mUserApps = new ArrayList<ResolveInfo>();
mFavoApps = new ArrayList<ResolveInfo>();
mShortApps = new ArrayList<ResolveInfo>();
favoAdapter = new favoAppAdapter(getBaseContext(), mFavoApps);
favoAppList.setAdapter(favoAdapter);
base = (sizedRelativeLayout) home.findViewById(R.id.base);
base.setResizeListener(this);
homeBar = (ImageView) home.findViewById(R.id.home_bar);
homeBar.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClassName("harley.browsers", "harley.lib.HarleyBrowser");
if (!util.startActivity(intent, false, getBaseContext())) {
intent.setClassName("easy.browser", "easy.lib.SimpleBrowser");
if (!util.startActivity(intent, false, getBaseContext())) {
//intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=harley.browsers"));
intent.setClassName(myPackageName, "easy.lib.SimpleBrowser");// runtime error. VFY: unable to resolve static field
util.startActivity(intent, true, getBaseContext());
}
}
}
});
shortBar = (ImageView) home.findViewById(R.id.business_bar);
shortBar.setOnClickListener(new OnClickListener() {//by click this bar to show/hide mainlayout
@Override
public void onClick(View arg0) {
if ((shortAppList.getVisibility() == View.INVISIBLE) && !mShortApps.isEmpty())
shortAppList.setVisibility(View.VISIBLE);
else shortAppList.setVisibility(View.INVISIBLE);
}
});
shortcut_phone = (ImageView) home.findViewById(R.id.shortcut_phone);
shortcut_sms = (ImageView) home.findViewById(R.id.shortcut_sms);
//shortcut_contact = (ImageView) findViewById(R.id.shortcut_contact);
//for package add/remove
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_PACKAGE_ADDED);
filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
filter.addDataScheme("package");
registerReceiver(packageReceiver, filter);
//for wall paper changed
filter = new IntentFilter(Intent.ACTION_WALLPAPER_CHANGED);
registerReceiver(wallpaperReceiver, filter);
filter = new IntentFilter("simpleHome.action.HOME_CHANGED");
registerReceiver(homeChangeReceiver, filter);
filter = new IntentFilter("simpleHome.action.PIC_ADDED");
registerReceiver(picAddReceiver, filter);
filter = new IntentFilter("simpleHome.action.SHARE_DESKTOP");
registerReceiver(deskShareReceiver, filter);
filter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);
filter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED);
filter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
filter.addAction(Intent.ACTION_MEDIA_REMOVED);
filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
filter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL);
filter.addDataScheme("file");
registerReceiver(sdcardListener, filter);
apps = (RelativeLayout) findViewById(R.id.apps);
//mWallpaperManager.setWallpaperOffsets(apps.getWindowToken(), 0.5f, 0);//move wallpaper to center, but null pointer?
//TelephonyManager tm = (TelephonyManager) getSystemService(Service.TELEPHONY_SERVICE);
//getITelephony(tm).getActivePhoneType();
ContentResolver cr = getContentResolver();
callObserver = new CallObserver(cr, mAppHandler);
smsObserver = new SmsChangeObserver(cr, mAppHandler);
getContentResolver().registerContentObserver(Calls.CONTENT_URI, true, callObserver);
cr.registerContentObserver(Uri.parse("content://mms-sms/"), true, smsObserver);
//task for init, such as load webview, load package list
InitTask initTask = new InitTask();
initTask.execute("");
restartDialog = new AlertDialog.Builder(this).
setTitle(R.string.app_name).
setIcon(R.drawable.icon).
setMessage(R.string.restart).
setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//save the layout
SharedPreferences.Editor editor = perferences.edit();
if (mainlayout.getCurrentItem() == 0)
editor.putBoolean("system", !sysAlphaList.mIsGrid);
else if (mainlayout.getCurrentItem() == 2)
editor.putBoolean("user", !userAlphaList.mIsGrid);
editor.commit();
//restart the activity. note if set singleinstance or singletask of activity, below will not work on some device.
Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}
}).
setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).create();
hintDialog = new AlertDialog.Builder(this).
setNegativeButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).create();
}
|
diff --git a/astrid/plugin-src/com/todoroo/astrid/gtasks/api/GtasksService.java b/astrid/plugin-src/com/todoroo/astrid/gtasks/api/GtasksService.java
index 550e7d570..fbd250bd7 100644
--- a/astrid/plugin-src/com/todoroo/astrid/gtasks/api/GtasksService.java
+++ b/astrid/plugin-src/com/todoroo/astrid/gtasks/api/GtasksService.java
@@ -1,279 +1,284 @@
package com.todoroo.astrid.gtasks.api;
import java.io.IOException;
import android.content.Context;
import com.google.api.client.extensions.android2.AndroidHttp;
import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAccessProtectedResource;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.util.DateTime;
import com.google.api.services.tasks.Tasks;
import com.google.api.services.tasks.Tasks.TasksOperations.Insert;
import com.google.api.services.tasks.Tasks.TasksOperations.List;
import com.google.api.services.tasks.Tasks.TasksOperations.Move;
import com.google.api.services.tasks.model.Task;
import com.google.api.services.tasks.model.TaskList;
import com.google.api.services.tasks.model.TaskLists;
import com.timsu.astrid.R;
import com.todoroo.andlib.service.Autowired;
import com.todoroo.andlib.service.ContextManager;
import com.todoroo.andlib.service.DependencyInjectionService;
import com.todoroo.andlib.service.ExceptionService;
import com.todoroo.astrid.gtasks.auth.GtasksTokenValidator;
/**
* Wrapper around the official Google Tasks API to simplify common operations. In the case
* of an exception, each request is tried twice in case of a timeout.
* @author Sam Bosley
*
*/
@SuppressWarnings("nls")
public class GtasksService {
private Tasks service;
private GoogleAccessProtectedResource accessProtectedResource;
private String token;
private JsonFactory jsonFactory;
@Autowired ExceptionService exceptionService;
private static final String API_KEY = "AIzaSyCIYZTBo6haRHxmiplZsfYdagFEpaiFnAk"; // non-production API key
public static final String AUTH_TOKEN_TYPE = "Manage your tasks"; //"oauth2:https://www.googleapis.com/auth/tasks";
public GtasksService(String authToken) {
DependencyInjectionService.getInstance().inject(this);
authenticate(authToken);
}
public void authenticate(String authToken) {
this.token = authToken;
accessProtectedResource = new GoogleAccessProtectedResource(authToken);
jsonFactory = new GsonFactory();
service = new Tasks(AndroidHttp.newCompatibleTransport(), accessProtectedResource, jsonFactory);
service.setKey(API_KEY);
service.setApplicationName("Astrid");
}
//If we get a 401 or 403, try revalidating the auth token before bailing
private synchronized void handleException(IOException e) throws IOException {
if (e instanceof HttpResponseException) {
HttpResponseException h = (HttpResponseException)e;
int statusCode = h.getResponse().getStatusCode();
if (statusCode == 401 || statusCode == 403) {
System.err.println("Encountered " + statusCode + " error");
token = GtasksTokenValidator.validateAuthToken(ContextManager.getContext(), token);
if (token != null) {
accessProtectedResource.setAccessToken(token);
}
} else if (statusCode == 503) { // 503 errors are generally either 1) quota limit reached or 2) problems on Google's end
System.err.println("Encountered 503 error");
final Context context = ContextManager.getContext();
String message = context.getString(R.string.gtasks_error_backend);
exceptionService.reportError(message, h);
throw h;
+ } else if (statusCode == 400 || statusCode == 500) {
+ System.err.println("Encountered " + statusCode + " error");
+ System.err.println(h.getResponse().getStatusMessage());
+ h.printStackTrace();
+ throw h;
}
}
}
private static void log(String method, Object result) {
System.err.println("QUERY: " + method + ", RESULT: " + result);
}
/**
* A simple service query that will throw an exception if anything goes wrong.
* Useful for checking if token needs revalidating or if there are network problems--
* no exception means all is well
* @throws IOException
*/
public void ping() throws IOException {
service.tasklists.get("@default").execute();
}
public TaskLists allGtaskLists() throws IOException {
TaskLists toReturn = null;
try {
toReturn = service.tasklists.list().execute();
} catch (IOException e) {
handleException(e);
toReturn = service.tasklists.list().execute();
} finally {
log("All gtasks lists", toReturn);
}
return toReturn;
}
public TaskList getGtaskList(String id) throws IOException {
TaskList toReturn = null;
try {
toReturn = service.tasklists.get(id).execute();
} catch (IOException e) {
handleException(e);
toReturn = service.tasklists.get(id).execute();
} finally {
log("Get gtask list, id: " + id, toReturn);
}
return toReturn;
}
public TaskList createGtaskList(String title) throws IOException {
TaskList newList = new TaskList();
newList.setTitle(title);
TaskList toReturn = null;
try {
toReturn = service.tasklists.insert(newList).execute();
} catch (IOException e) {
handleException(e);
toReturn = service.tasklists.insert(newList).execute();
} finally {
log("Create gtask list, title: " + title, toReturn);
}
return toReturn;
}
public TaskList updateGtaskList(TaskList list) throws IOException {
TaskList toReturn = null;
try {
toReturn = service.tasklists.update(list.getId(), list).execute();
} catch (IOException e) {
handleException(e);
toReturn = service.tasklists.update(list.getId(), list).execute();
} finally {
log("Update list, id: " + list.getId(), toReturn);
}
return toReturn;
}
public void deleteGtaskList(String listId) throws IOException {
try {
service.tasklists.delete(listId).execute();
} catch (IOException e) {
handleException(e);
service.tasklists.delete(listId).execute();
} finally {
log("Delete list, id: " + listId, null);
}
}
public com.google.api.services.tasks.model.Tasks getAllGtasksFromTaskList(TaskList list, boolean includeDeleted, boolean includeHidden) throws IOException {
return getAllGtasksFromListId(list.getId(), includeDeleted, includeHidden);
}
public com.google.api.services.tasks.model.Tasks getAllGtasksFromListId(String listId, boolean includeDeleted, boolean includeHidden) throws IOException {
com.google.api.services.tasks.model.Tasks toReturn = null;
List request = service.tasks.list(listId);
request.setShowDeleted(includeDeleted);
request.setShowHidden(includeHidden);
try {
toReturn = request.execute();
} catch (IOException e) {
handleException(e);
toReturn = request.execute();
} finally {
log("Get all tasks, list: " + listId + ", include deleted: " + includeDeleted, toReturn);
}
return toReturn;
}
public Task getGtask(String listId, String taskId) throws IOException {
Task toReturn = null;
try {
toReturn = service.tasks.get(listId, taskId).execute();
} catch (IOException e) {
handleException(e);
toReturn = service.tasks.get(listId, taskId).execute();
} finally {
log("Get gtask, id: " + taskId, toReturn);
}
return toReturn;
}
public Task createGtask(String listId, String title, String notes, DateTime due) throws IOException {
Task newGtask = new Task();
newGtask.setTitle(title);
newGtask.setNotes(notes);
newGtask.setDue(due);
return createGtask(listId, newGtask);
}
public Task createGtask(String listId, Task task) throws IOException {
return createGtask(listId, task, null, null);
}
public Task createGtask(String listId, Task task, String parent, String priorSiblingId) throws IOException {
Insert insertOp = service.tasks.insert(listId, task);
insertOp.setParent(parent);
insertOp.setPrevious(priorSiblingId);
Task toReturn = null;
try {
toReturn = insertOp.execute();
} catch (IOException e) {
handleException(e);
toReturn = insertOp.execute();
} finally {
log("Creating gtask, title: " + task.getTitle(), toReturn);
}
return toReturn;
}
public Task updateGtask(String listId, Task task) throws IOException {
Task toReturn = null;
try {
toReturn = service.tasks.update(listId, task.getId(), task).execute();
} catch (IOException e) {
handleException(e);
toReturn = service.tasks.update(listId, task.getId(), task).execute();
} finally {
log("Update gtask, title: " + task.getTitle(), toReturn);
}
return toReturn;
}
public Task moveGtask(String listId, String taskId, String parentId, String previousId) throws IOException {
Move move = service.tasks.move(listId, taskId);
move.setParent(parentId);
move.setPrevious(previousId);
Task toReturn = null;
try {
toReturn = move.execute();
} catch (IOException e) {
handleException(e);
toReturn = move.execute();
} finally {
log("Move task " + taskId + "to parent: " + parentId + ", prior sibling: " + previousId, toReturn);
}
return toReturn;
}
public void deleteGtask(String listId, String taskId) throws IOException {
try {
service.tasks.delete(listId, taskId).execute();
} catch (IOException e) {
handleException(e);
service.tasks.delete(listId, taskId).execute();
} finally {
log("Delete task, id: " + taskId, null);
}
}
public void clearCompletedTasks(String listId) throws IOException {
try {
service.tasks.clear(listId).execute();
} catch (IOException e) {
handleException(e);
service.tasks.clear(listId).execute();
} finally {
log("Clear completed tasks, list id: " + listId, null);
}
}
public JsonFactory getJsonFactory() {
return jsonFactory;
}
}
| true | true | private synchronized void handleException(IOException e) throws IOException {
if (e instanceof HttpResponseException) {
HttpResponseException h = (HttpResponseException)e;
int statusCode = h.getResponse().getStatusCode();
if (statusCode == 401 || statusCode == 403) {
System.err.println("Encountered " + statusCode + " error");
token = GtasksTokenValidator.validateAuthToken(ContextManager.getContext(), token);
if (token != null) {
accessProtectedResource.setAccessToken(token);
}
} else if (statusCode == 503) { // 503 errors are generally either 1) quota limit reached or 2) problems on Google's end
System.err.println("Encountered 503 error");
final Context context = ContextManager.getContext();
String message = context.getString(R.string.gtasks_error_backend);
exceptionService.reportError(message, h);
throw h;
}
}
}
| private synchronized void handleException(IOException e) throws IOException {
if (e instanceof HttpResponseException) {
HttpResponseException h = (HttpResponseException)e;
int statusCode = h.getResponse().getStatusCode();
if (statusCode == 401 || statusCode == 403) {
System.err.println("Encountered " + statusCode + " error");
token = GtasksTokenValidator.validateAuthToken(ContextManager.getContext(), token);
if (token != null) {
accessProtectedResource.setAccessToken(token);
}
} else if (statusCode == 503) { // 503 errors are generally either 1) quota limit reached or 2) problems on Google's end
System.err.println("Encountered 503 error");
final Context context = ContextManager.getContext();
String message = context.getString(R.string.gtasks_error_backend);
exceptionService.reportError(message, h);
throw h;
} else if (statusCode == 400 || statusCode == 500) {
System.err.println("Encountered " + statusCode + " error");
System.err.println(h.getResponse().getStatusMessage());
h.printStackTrace();
throw h;
}
}
}
|
diff --git a/src/be/ibridge/kettle/trans/step/xmloutput/XMLOutputDialog.java b/src/be/ibridge/kettle/trans/step/xmloutput/XMLOutputDialog.java
index 8ba45524..f1b167b7 100644
--- a/src/be/ibridge/kettle/trans/step/xmloutput/XMLOutputDialog.java
+++ b/src/be/ibridge/kettle/trans/step/xmloutput/XMLOutputDialog.java
@@ -1,914 +1,914 @@
/**********************************************************************
** **
** This code belongs to the KETTLE project. **
** **
** Kettle, from version 2.2 on, is released into the public domain **
** under the Lesser GNU Public License (LGPL). **
** **
** For more details, please read the document LICENSE.txt, included **
** in this project **
** **
** http://www.kettle.be **
** [email protected] **
** **
**********************************************************************/
/*
* Created on 18-mei-2003
*
*/
package be.ibridge.kettle.trans.step.xmloutput;
import java.nio.charset.Charset;
import java.util.ArrayList;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
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 be.ibridge.kettle.core.ColumnInfo;
import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.Props;
import be.ibridge.kettle.core.Row;
import be.ibridge.kettle.core.dialog.EnterSelectionDialog;
import be.ibridge.kettle.core.dialog.ErrorDialog;
import be.ibridge.kettle.core.exception.KettleException;
import be.ibridge.kettle.core.util.StringUtil;
import be.ibridge.kettle.core.value.Value;
import be.ibridge.kettle.core.widget.TableView;
import be.ibridge.kettle.trans.TransMeta;
import be.ibridge.kettle.trans.step.BaseStepDialog;
import be.ibridge.kettle.trans.step.BaseStepMeta;
import be.ibridge.kettle.trans.step.StepDialogInterface;
import be.ibridge.kettle.trans.step.textfileinput.VariableButtonListenerFactory;
public class XMLOutputDialog extends BaseStepDialog implements StepDialogInterface
{
private CTabFolder wTabFolder;
private FormData fdTabFolder;
private CTabItem wFileTab, wContentTab, wFieldsTab;
private FormData fdFileComp, fdContentComp, fdFieldsComp;
private Label wlFilename;
private Button wbFilename;
private Button wbcFilename;
private Text wFilename;
private FormData fdlFilename, fdbFilename, fdbcFilename, fdFilename;
private Label wlExtension;
private Text wExtension;
private FormData fdlExtension, fdExtension;
private Label wlAddStepnr;
private Button wAddStepnr;
private FormData fdlAddStepnr, fdAddStepnr;
private Label wlAddDate;
private Button wAddDate;
private FormData fdlAddDate, fdAddDate;
private Label wlAddTime;
private Button wAddTime;
private FormData fdlAddTime, fdAddTime;
private Button wbShowFiles;
private FormData fdbShowFiles;
private Label wlZipped;
private Button wZipped;
private FormData fdlZipped, fdZipped;
private Label wlEncoding;
private CCombo wEncoding;
private FormData fdlEncoding, fdEncoding;
private Label wlMainElement;
private CCombo wMainElement;
private FormData fdlMainElement, fdMainElement;
private Label wlRepeatElement;
private CCombo wRepeatElement;
private FormData fdlRepeatElement, fdRepeatElement;
private Label wlSplitEvery;
private Text wSplitEvery;
private FormData fdlSplitEvery, fdSplitEvery;
private TableView wFields;
private FormData fdFields;
private XMLOutputMeta input;
private Button wMinWidth;
private Listener lsMinWidth;
private boolean gotEncodings = false;
public XMLOutputDialog(Shell parent, Object in, TransMeta transMeta, String sname)
{
super(parent, (BaseStepMeta)in, transMeta, sname);
input=(XMLOutputMeta)in;
}
public String open()
{
Shell parent = getParent();
Display display = parent.getDisplay();
shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN);
props.setLook(shell);
ModifyListener lsMod = new ModifyListener()
{
public void modifyText(ModifyEvent e)
{
input.setChanged();
}
};
changed = input.hasChanged();
FormLayout formLayout = new FormLayout ();
formLayout.marginWidth = Const.FORM_MARGIN;
formLayout.marginHeight = Const.FORM_MARGIN;
shell.setLayout(formLayout);
shell.setText(Messages.getString("XMLOutputDialog.DialogTitle"));
int middle = props.getMiddlePct();
int margin = Const.MARGIN;
// Stepname line
wlStepname=new Label(shell, SWT.RIGHT);
wlStepname.setText(Messages.getString("System.Label.StepName"));
props.setLook(wlStepname);
fdlStepname=new FormData();
fdlStepname.left = new FormAttachment(0, 0);
fdlStepname.top = new FormAttachment(0, margin);
fdlStepname.right = new FormAttachment(middle, -margin);
wlStepname.setLayoutData(fdlStepname);
wStepname=new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wStepname.setText(stepname);
props.setLook(wStepname);
wStepname.addModifyListener(lsMod);
fdStepname=new FormData();
fdStepname.left = new FormAttachment(middle, 0);
fdStepname.top = new FormAttachment(0, margin);
fdStepname.right= new FormAttachment(100, 0);
wStepname.setLayoutData(fdStepname);
wTabFolder = new CTabFolder(shell, SWT.BORDER);
props.setLook(wTabFolder, Props.WIDGET_STYLE_TAB);
//////////////////////////
// START OF FILE TAB///
///
wFileTab=new CTabItem(wTabFolder, SWT.NONE);
wFileTab.setText(Messages.getString("XMLOutputDialog.FileTab.Tab"));
Composite wFileComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wFileComp);
FormLayout fileLayout = new FormLayout();
fileLayout.marginWidth = 3;
fileLayout.marginHeight = 3;
wFileComp.setLayout(fileLayout);
// Filename line
wlFilename=new Label(wFileComp, SWT.RIGHT);
wlFilename.setText(Messages.getString("XMLOutputDialog.Filename.Label"));
props.setLook(wlFilename);
fdlFilename=new FormData();
fdlFilename.left = new FormAttachment(0, 0);
fdlFilename.top = new FormAttachment(0, margin);
fdlFilename.right= new FormAttachment(middle, -margin);
wlFilename.setLayoutData(fdlFilename);
wbFilename=new Button(wFileComp, SWT.PUSH| SWT.CENTER);
props.setLook(wbFilename);
wbFilename.setText(Messages.getString("XMLOutputDialog.Browse.Button"));
fdbFilename=new FormData();
fdbFilename.right= new FormAttachment(100, 0);
fdbFilename.top = new FormAttachment(0, 0);
wbFilename.setLayoutData(fdbFilename);
wbcFilename=new Button(wFileComp, SWT.PUSH| SWT.CENTER);
props.setLook(wbcFilename);
wbcFilename.setText(Messages.getString("XMLOutputDialog.Variable.Button"));
fdbcFilename=new FormData();
fdbcFilename.right= new FormAttachment(wbFilename, -margin);
fdbcFilename.top = new FormAttachment(0, 0);
wbcFilename.setLayoutData(fdbcFilename);
wFilename=new Text(wFileComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wFilename);
wFilename.addModifyListener(lsMod);
fdFilename=new FormData();
fdFilename.left = new FormAttachment(middle, 0);
fdFilename.top = new FormAttachment(0, margin);
fdFilename.right= new FormAttachment(wbcFilename, -margin);
wFilename.setLayoutData(fdFilename);
// Whenever something changes, set the tooltip to the expanded version:
wFilename.addModifyListener(new ModifyListener()
{
public void modifyText(ModifyEvent e)
{
wFilename.setToolTipText(StringUtil.environmentSubstitute( wFilename.getText() ) );
}
}
);
// Extension line
wlExtension=new Label(wFileComp, SWT.RIGHT);
wlExtension.setText(Messages.getString("XMLOutputDialog.Extension.Label"));
props.setLook(wlExtension);
fdlExtension=new FormData();
fdlExtension.left = new FormAttachment(0, 0);
fdlExtension.top = new FormAttachment(wFilename, margin);
fdlExtension.right= new FormAttachment(middle, -margin);
wlExtension.setLayoutData(fdlExtension);
wExtension=new Text(wFileComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wExtension.setText("");
props.setLook(wExtension);
wExtension.addModifyListener(lsMod);
fdExtension=new FormData();
fdExtension.left = new FormAttachment(middle, 0);
fdExtension.top = new FormAttachment(wFilename, margin);
fdExtension.right= new FormAttachment(100, 0);
wExtension.setLayoutData(fdExtension);
// Create multi-part file?
wlAddStepnr=new Label(wFileComp, SWT.RIGHT);
- wlAddStepnr.setText("Include stepnr in filename? ");
+ wlAddStepnr.setText(Messages.getString("XMLOutputDialog.AddStepNr.Label"));
props.setLook(wlAddStepnr);
fdlAddStepnr=new FormData();
fdlAddStepnr.left = new FormAttachment(0, 0);
fdlAddStepnr.top = new FormAttachment(wExtension, margin);
fdlAddStepnr.right= new FormAttachment(middle, -margin);
wlAddStepnr.setLayoutData(fdlAddStepnr);
wAddStepnr=new Button(wFileComp, SWT.CHECK);
props.setLook(wAddStepnr);
fdAddStepnr=new FormData();
fdAddStepnr.left = new FormAttachment(middle, 0);
fdAddStepnr.top = new FormAttachment(wExtension, margin);
fdAddStepnr.right= new FormAttachment(100, 0);
wAddStepnr.setLayoutData(fdAddStepnr);
wAddStepnr.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
input.setChanged();
}
}
);
// Create multi-part file?
wlAddDate=new Label(wFileComp, SWT.RIGHT);
wlAddDate.setText(Messages.getString("XMLOutputDialog.AddDate.Label"));
props.setLook(wlAddDate);
fdlAddDate=new FormData();
fdlAddDate.left = new FormAttachment(0, 0);
fdlAddDate.top = new FormAttachment(wAddStepnr, margin);
fdlAddDate.right= new FormAttachment(middle, -margin);
wlAddDate.setLayoutData(fdlAddDate);
wAddDate=new Button(wFileComp, SWT.CHECK);
props.setLook(wAddDate);
fdAddDate=new FormData();
fdAddDate.left = new FormAttachment(middle, 0);
fdAddDate.top = new FormAttachment(wAddStepnr, margin);
fdAddDate.right= new FormAttachment(100, 0);
wAddDate.setLayoutData(fdAddDate);
wAddDate.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
input.setChanged();
}
}
);
// Create multi-part file?
wlAddTime=new Label(wFileComp, SWT.RIGHT);
wlAddTime.setText(Messages.getString("XMLOutputDialog.AddTime.Label"));
props.setLook(wlAddTime);
fdlAddTime=new FormData();
fdlAddTime.left = new FormAttachment(0, 0);
fdlAddTime.top = new FormAttachment(wAddDate, margin);
fdlAddTime.right= new FormAttachment(middle, -margin);
wlAddTime.setLayoutData(fdlAddTime);
wAddTime=new Button(wFileComp, SWT.CHECK);
props.setLook(wAddTime);
fdAddTime=new FormData();
fdAddTime.left = new FormAttachment(middle, 0);
fdAddTime.top = new FormAttachment(wAddDate, margin);
fdAddTime.right= new FormAttachment(100, 0);
wAddTime.setLayoutData(fdAddTime);
wAddTime.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
input.setChanged();
}
}
);
wbShowFiles=new Button(wFileComp, SWT.PUSH| SWT.CENTER);
props.setLook(wbShowFiles);
wbShowFiles.setText(Messages.getString("XMLOutputDialog.ShowFiles.Button"));
fdbShowFiles=new FormData();
fdbShowFiles.left = new FormAttachment(middle, 0);
fdbShowFiles.top = new FormAttachment(wAddTime, margin*2);
wbShowFiles.setLayoutData(fdbShowFiles);
wbShowFiles.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
XMLOutputMeta tfoi = new XMLOutputMeta();
getInfo(tfoi);
String files[] = tfoi.getFiles();
if (files!=null && files.length>0)
{
EnterSelectionDialog esd = new EnterSelectionDialog(shell, props, files, Messages.getString("XMLOutputDialog.OutputFiles.DialogTitle"), Messages.getString("XMLOutputDialog.OutputFiles.DialogMessage"));
esd.setViewOnly();
esd.open();
}
else
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR );
mb.setMessage(Messages.getString("XMLOutputDialog.NoFilesFound.DialogMessage"));
mb.setText(Messages.getString("System.Dialog.Error.Title"));
mb.open();
}
}
}
);
fdFileComp=new FormData();
fdFileComp.left = new FormAttachment(0, 0);
fdFileComp.top = new FormAttachment(0, 0);
fdFileComp.right = new FormAttachment(100, 0);
fdFileComp.bottom= new FormAttachment(100, 0);
wFileComp.setLayoutData(fdFileComp);
wFileComp.layout();
wFileTab.setControl(wFileComp);
/////////////////////////////////////////////////////////////
/// END OF FILE TAB
/////////////////////////////////////////////////////////////
//////////////////////////
// START OF CONTENT TAB///
///
wContentTab=new CTabItem(wTabFolder, SWT.NONE);
wContentTab.setText(Messages.getString("XMLOutputDialog.ContentTab.TabTitle"));
FormLayout contentLayout = new FormLayout ();
contentLayout.marginWidth = 3;
contentLayout.marginHeight = 3;
Composite wContentComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wContentComp);
wContentComp.setLayout(contentLayout);
wlZipped=new Label(wContentComp, SWT.RIGHT);
wlZipped.setText(Messages.getString("XMLOutputDialog.Zipped.Label"));
props.setLook(wlZipped);
fdlZipped=new FormData();
fdlZipped.left = new FormAttachment(0, 0);
fdlZipped.top = new FormAttachment(0, 0);
fdlZipped.right= new FormAttachment(middle, -margin);
wlZipped.setLayoutData(fdlZipped);
wZipped=new Button(wContentComp, SWT.CHECK );
props.setLook(wZipped);
fdZipped=new FormData();
fdZipped.left = new FormAttachment(middle, 0);
fdZipped.top = new FormAttachment(0, 0);
fdZipped.right= new FormAttachment(100, 0);
wZipped.setLayoutData(fdZipped);
wZipped.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
input.setChanged();
}
}
);
wlEncoding=new Label(wContentComp, SWT.RIGHT);
wlEncoding.setText(Messages.getString("XMLOutputDialog.Encoding.Label"));
props.setLook(wlEncoding);
fdlEncoding=new FormData();
fdlEncoding.left = new FormAttachment(0, 0);
fdlEncoding.top = new FormAttachment(wZipped, margin);
fdlEncoding.right= new FormAttachment(middle, -margin);
wlEncoding.setLayoutData(fdlEncoding);
wEncoding=new CCombo(wContentComp, SWT.BORDER | SWT.READ_ONLY);
wEncoding.setEditable(true);
props.setLook(wEncoding);
wEncoding.addModifyListener(lsMod);
fdEncoding=new FormData();
fdEncoding.left = new FormAttachment(middle, 0);
fdEncoding.top = new FormAttachment(wZipped, margin);
fdEncoding.right= new FormAttachment(100, 0);
wEncoding.setLayoutData(fdEncoding);
wEncoding.addFocusListener(new FocusListener()
{
public void focusLost(org.eclipse.swt.events.FocusEvent e)
{
}
public void focusGained(org.eclipse.swt.events.FocusEvent e)
{
Cursor busy = new Cursor(shell.getDisplay(), SWT.CURSOR_WAIT);
shell.setCursor(busy);
setEncodings();
shell.setCursor(null);
busy.dispose();
}
}
);
wlMainElement=new Label(wContentComp, SWT.RIGHT);
wlMainElement.setText(Messages.getString("XMLOutputDialog.MainElement.Label"));
props.setLook(wlMainElement);
fdlMainElement=new FormData();
fdlMainElement.left = new FormAttachment(0, 0);
fdlMainElement.top = new FormAttachment(wEncoding, margin);
fdlMainElement.right= new FormAttachment(middle, -margin);
wlMainElement.setLayoutData(fdlMainElement);
wMainElement=new CCombo(wContentComp, SWT.BORDER | SWT.READ_ONLY);
wMainElement.setEditable(true);
props.setLook(wMainElement);
wMainElement.addModifyListener(lsMod);
fdMainElement=new FormData();
fdMainElement.left = new FormAttachment(middle, 0);
fdMainElement.top = new FormAttachment(wEncoding, margin);
fdMainElement.right= new FormAttachment(100, 0);
wMainElement.setLayoutData(fdMainElement);
wlRepeatElement=new Label(wContentComp, SWT.RIGHT);
wlRepeatElement.setText(Messages.getString("XMLOutputDialog.RepeatElement.Label"));
props.setLook(wlRepeatElement);
fdlRepeatElement=new FormData();
fdlRepeatElement.left = new FormAttachment(0, 0);
fdlRepeatElement.top = new FormAttachment(wMainElement, margin);
fdlRepeatElement.right= new FormAttachment(middle, -margin);
wlRepeatElement.setLayoutData(fdlRepeatElement);
wRepeatElement=new CCombo(wContentComp, SWT.BORDER | SWT.READ_ONLY);
wRepeatElement.setEditable(true);
props.setLook(wRepeatElement);
wRepeatElement.addModifyListener(lsMod);
fdRepeatElement=new FormData();
fdRepeatElement.left = new FormAttachment(middle, 0);
fdRepeatElement.top = new FormAttachment(wMainElement, margin);
fdRepeatElement.right= new FormAttachment(100, 0);
wRepeatElement.setLayoutData(fdRepeatElement);
wlSplitEvery=new Label(wContentComp, SWT.RIGHT);
wlSplitEvery.setText(Messages.getString("XMLOutputDialog.SplitEvery.Label"));
props.setLook(wlSplitEvery);
fdlSplitEvery=new FormData();
fdlSplitEvery.left = new FormAttachment(0, 0);
fdlSplitEvery.top = new FormAttachment(wRepeatElement, margin);
fdlSplitEvery.right= new FormAttachment(middle, -margin);
wlSplitEvery.setLayoutData(fdlSplitEvery);
wSplitEvery=new Text(wContentComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wSplitEvery);
wSplitEvery.addModifyListener(lsMod);
fdSplitEvery=new FormData();
fdSplitEvery.left = new FormAttachment(middle, 0);
fdSplitEvery.top = new FormAttachment(wRepeatElement, margin);
fdSplitEvery.right= new FormAttachment(100, 0);
wSplitEvery.setLayoutData(fdSplitEvery);
fdContentComp = new FormData();
fdContentComp.left = new FormAttachment(0, 0);
fdContentComp.top = new FormAttachment(0, 0);
fdContentComp.right = new FormAttachment(100, 0);
fdContentComp.bottom= new FormAttachment(100, 0);
wContentComp.setLayoutData(fdContentComp);
wContentComp.layout();
wContentTab.setControl(wContentComp);
/////////////////////////////////////////////////////////////
/// END OF CONTENT TAB
/////////////////////////////////////////////////////////////
// Fields tab...
//
wFieldsTab = new CTabItem(wTabFolder, SWT.NONE);
wFieldsTab.setText(Messages.getString("XMLOutputDialog.FieldsTab.TabTitle"));
FormLayout fieldsLayout = new FormLayout ();
fieldsLayout.marginWidth = Const.FORM_MARGIN;
fieldsLayout.marginHeight = Const.FORM_MARGIN;
Composite wFieldsComp = new Composite(wTabFolder, SWT.NONE);
wFieldsComp.setLayout(fieldsLayout);
props.setLook(wFieldsComp);
wGet=new Button(wFieldsComp, SWT.PUSH);
- wGet.setText(Messages.getString("XMLOutputDialog.SplitEvery.Label"));
+ wGet.setText(Messages.getString("XMLOutputDialog.Get.Button"));
wGet.setToolTipText(Messages.getString("XMLOutputDialog.Get.Tooltip"));
wMinWidth =new Button(wFieldsComp, SWT.PUSH);
- wMinWidth.setText(Messages.getString("XMLOutputDialog.Get.Button"));
- wMinWidth.setToolTipText(Messages.getString("XMLOutputDialog.Get.Tooltip"));
+ wMinWidth.setText(Messages.getString("XMLOutputDialog.MinWidth.Label"));
+ wMinWidth.setToolTipText(Messages.getString("XMLOutputDialog.MinWidth.Tooltip"));
setButtonPositions(new Button[] { wGet, wMinWidth}, margin, null);
final int FieldsRows=input.getOutputFields().length;
// Prepare a list of possible formats...
String dats[] = Const.dateFormats;
String nums[] = Const.numberFormats;
int totsize = dats.length + nums.length;
String formats[] = new String[totsize];
for (int x=0;x<dats.length;x++) formats[x] = dats[x];
for (int x=0;x<nums.length;x++) formats[dats.length+x] = nums[x];
ColumnInfo[] colinf=new ColumnInfo[]
{
new ColumnInfo(Messages.getString("XMLOutputDialog.Fieldname.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false),
new ColumnInfo(Messages.getString("XMLOutputDialog.Fieldname.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false),
new ColumnInfo(Messages.getString("XMLOutputDialog.Type.Column"), ColumnInfo.COLUMN_TYPE_CCOMBO, Value.getTypes() ),
new ColumnInfo(Messages.getString("XMLOutputDialog.Format.Column"), ColumnInfo.COLUMN_TYPE_CCOMBO, formats),
new ColumnInfo(Messages.getString("XMLOutputDialog.Length.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false),
new ColumnInfo(Messages.getString("XMLOutputDialog.Precision.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false),
new ColumnInfo(Messages.getString("XMLOutputDialog.Currency.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false),
new ColumnInfo(Messages.getString("XMLOutputDialog.Decimal.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false),
new ColumnInfo(Messages.getString("XMLOutputDialog.Group.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false),
new ColumnInfo(Messages.getString("XMLOutputDialog.Null.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false)
};
wFields=new TableView(wFieldsComp,
SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI,
colinf,
FieldsRows,
lsMod,
props
);
fdFields=new FormData();
fdFields.left = new FormAttachment(0, 0);
fdFields.top = new FormAttachment(0, 0);
fdFields.right = new FormAttachment(100, 0);
fdFields.bottom= new FormAttachment(wGet, -margin);
wFields.setLayoutData(fdFields);
fdFieldsComp=new FormData();
fdFieldsComp.left = new FormAttachment(0, 0);
fdFieldsComp.top = new FormAttachment(0, 0);
fdFieldsComp.right = new FormAttachment(100, 0);
fdFieldsComp.bottom= new FormAttachment(100, 0);
wFieldsComp.setLayoutData(fdFieldsComp);
wFieldsComp.layout();
wFieldsTab.setControl(wFieldsComp);
fdTabFolder = new FormData();
fdTabFolder.left = new FormAttachment(0, 0);
fdTabFolder.top = new FormAttachment(wStepname, margin);
fdTabFolder.right = new FormAttachment(100, 0);
fdTabFolder.bottom= new FormAttachment(100, -50);
wTabFolder.setLayoutData(fdTabFolder);
wOK=new Button(shell, SWT.PUSH);
wOK.setText(Messages.getString("System.Button.OK"));
wCancel=new Button(shell, SWT.PUSH);
wCancel.setText(Messages.getString("System.Button.Cancel"));
setButtonPositions(new Button[] { wOK, wCancel }, margin, wTabFolder);
// Add listeners
lsOK = new Listener() { public void handleEvent(Event e) { ok(); } };
lsGet = new Listener() { public void handleEvent(Event e) { get(); } };
lsMinWidth = new Listener() { public void handleEvent(Event e) { setMinimalWidth(); } };
lsCancel = new Listener() { public void handleEvent(Event e) { cancel(); } };
wOK.addListener (SWT.Selection, lsOK );
wGet.addListener (SWT.Selection, lsGet );
wMinWidth.addListener (SWT.Selection, lsMinWidth );
wCancel.addListener(SWT.Selection, lsCancel);
lsDef=new SelectionAdapter() { public void widgetDefaultSelected(SelectionEvent e) { ok(); } };
wStepname.addSelectionListener( lsDef );
wFilename.addSelectionListener( lsDef );
// Whenever something changes, set the tooltip to the expanded version:
wFilename.addModifyListener(new ModifyListener()
{
public void modifyText(ModifyEvent e)
{
wFilename.setToolTipText(StringUtil.environmentSubstitute( wFilename.getText() ) );
}
}
);
// Listen to the Variable... button
wbcFilename.addSelectionListener(VariableButtonListenerFactory.getSelectionAdapter(shell, wFilename));
wbFilename.addSelectionListener
(
new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
FileDialog dialog = new FileDialog(shell, SWT.OPEN);
dialog.setFilterExtensions(new String[] {"*.txt", "*.csv", "*"});
if (wFilename.getText()!=null)
{
dialog.setFileName(StringUtil.environmentSubstitute(wFilename.getText()));
}
dialog.setFilterNames(new String[] {Messages.getString("System.FileType.TextFiles"), Messages.getString("System.FileType.CSVFiles"), Messages.getString("System.FileType.AllFiles")});
if (dialog.open()!=null)
{
wFilename.setText(dialog.getFilterPath()+System.getProperty("file.separator")+dialog.getFileName());
}
}
}
);
// Detect X or ALT-F4 or something that kills this window...
shell.addShellListener( new ShellAdapter() { public void shellClosed(ShellEvent e) { cancel(); } } );
lsResize = new Listener()
{
public void handleEvent(Event event)
{
Point size = shell.getSize();
wFields.setSize(size.x-10, size.y-50);
wFields.table.setSize(size.x-10, size.y-50);
wFields.redraw();
}
};
shell.addListener(SWT.Resize, lsResize);
wTabFolder.setSelection(0);
// Set the shell size, based upon previous time...
setSize();
getData();
input.setChanged(changed);
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch()) display.sleep();
}
return stepname;
}
private void setEncodings()
{
// Encoding of the text file:
if (!gotEncodings)
{
gotEncodings = true;
wEncoding.removeAll();
ArrayList values = new ArrayList(Charset.availableCharsets().values());
for (int i=0;i<values.size();i++)
{
Charset charSet = (Charset)values.get(i);
wEncoding.add( charSet.displayName() );
}
// Now select the default!
String defEncoding = Const.getEnvironmentVariable("file.encoding", "UTF-8");
int idx = Const.indexOfString(defEncoding, wEncoding.getItems() );
if (idx>=0) wEncoding.select( idx );
}
}
/**
* Copy information from the meta-data input to the dialog fields.
*/
public void getData()
{
if (input.getFileName() != null) wFilename.setText(input.getFileName());
if (input.getExtension() != null) wExtension.setText(input.getExtension());
if (input.getEncoding() != null) wEncoding.setText(input.getEncoding());
if (input.getMainElement() != null) wMainElement.setText(input.getMainElement());
if (input.getRepeatElement() != null) wRepeatElement.setText(input.getRepeatElement());
wSplitEvery.setText(""+input.getSplitEvery());
wZipped.setSelection(input.isZipped());
wAddDate.setSelection(input.isDateInFilename());
wAddTime.setSelection(input.isTimeInFilename());
wAddStepnr.setSelection(input.isStepNrInFilename());
log.logDebug(toString(), Messages.getString("XMLOutputDialog.Log.GettingFieldsInfo"));
for (int i=0;i<input.getOutputFields().length;i++)
{
XMLField field = input.getOutputFields()[i];
TableItem item = wFields.table.getItem(i);
if (field.getFieldName()!=null) item.setText(1, field.getFieldName());
if (field.getElementName()!=null) item.setText(2, field.getElementName());
item.setText(3, field.getTypeDesc());
if (field.getFormat()!=null) item.setText(4, field.getFormat());
if (field.getLength()!=-1) item.setText(5, ""+field.getLength());
if (field.getPrecision()!=-1) item.setText(6, ""+field.getPrecision());
if (field.getCurrencySymbol()!=null) item.setText(7, field.getCurrencySymbol());
if (field.getDecimalSymbol()!=null) item.setText(8, field.getDecimalSymbol());
if (field.getGroupingSymbol()!=null) item.setText(9, field.getGroupingSymbol());
if (field.getNullString()!=null) item.setText(10, field.getNullString());
}
wFields.optWidth(true);
wStepname.selectAll();
}
private void cancel()
{
stepname=null;
input.setChanged(backupChanged);
dispose();
}
private void getInfo(XMLOutputMeta tfoi)
{
tfoi.setFileName( wFilename.getText() );
tfoi.setEncoding( wEncoding.getText() );
tfoi.setMainElement( wMainElement.getText() );
tfoi.setRepeatElement( wRepeatElement.getText() );
tfoi.setExtension( wExtension.getText() );
tfoi.setSplitEvery( Const.toInt(wSplitEvery.getText(), 0) );
tfoi.setStepNrInFilename( wAddStepnr.getSelection() );
tfoi.setDateInFilename( wAddDate.getSelection() );
tfoi.setTimeInFilename( wAddTime.getSelection() );
tfoi.setZipped( wZipped.getSelection() );
//Table table = wFields.table;
int nrfields = wFields.nrNonEmpty();
tfoi.allocate(nrfields);
for (int i=0;i<nrfields;i++)
{
XMLField field = new XMLField();
TableItem item = wFields.getNonEmpty(i);
field.setFieldName( item.getText(1) );
field.setElementName( item.getText(2) );
if (field.getFieldName().equals(field.getElementName())) field.setElementName("");
field.setType( item.getText(3) );
field.setFormat( item.getText(4) );
field.setLength( Const.toInt(item.getText(5), -1) );
field.setPrecision( Const.toInt(item.getText(6), -1) );
field.setCurrencySymbol( item.getText(7) );
field.setDecimalSymbol( item.getText(8) );
field.setGroupingSymbol( item.getText(9) );
field.setNullString( item.getText(10) );
tfoi.getOutputFields()[i] = field;
}
}
private void ok()
{
stepname = wStepname.getText(); // return value
getInfo(input);
dispose();
}
private void get()
{
try
{
Row r = transMeta.getPrevStepFields(stepname);
if (r!=null)
{
Table table=wFields.table;
int count=table.getItemCount();
for (int i=0;i<r.size();i++)
{
Value v = r.getValue(i);
TableItem ti = new TableItem(table, SWT.NONE);
ti.setText(0, ""+(count+i+1));
ti.setText(1, v.getName());
ti.setText(2, v.getName());
ti.setText(3, v.getTypeDesc());
if (v.isNumber())
{
if (v.getLength()>0)
{
int le=v.getLength();
int pr=v.getPrecision();
if (v.getPrecision()<=0)
{
pr=0;
}
String mask=" ";
for (int m=0;m<le-pr;m++)
{
mask+="0";
}
if (pr>0) mask+=".";
for (int m=0;m<pr;m++)
{
mask+="0";
}
ti.setText(4, mask);
}
}
ti.setText(5, ""+v.getLength());
ti.setText(6, ""+v.getPrecision());
}
wFields.removeEmptyRows();
wFields.setRowNums();
wFields.optWidth(true);
}
}
catch(KettleException ke)
{
new ErrorDialog(shell, props, Messages.getString("System.Dialog.GetFieldsFailed.Title"), Messages.getString("XSystem.Dialog.GetFieldsFailed.Message"), ke);
}
}
/**
* Sets the output width to minimal width...
*
*/
public void setMinimalWidth()
{
for (int i=0;i<wFields.nrNonEmpty();i++)
{
TableItem item = wFields.getNonEmpty(i);
item.setText(5, "");
item.setText(6, "");
int type = Value.getType(item.getText(2));
switch(type)
{
case Value.VALUE_TYPE_STRING: item.setText(4, ""); break;
case Value.VALUE_TYPE_INTEGER: item.setText(4, "0"); break;
case Value.VALUE_TYPE_NUMBER: item.setText(4, "0.#####"); break;
case Value.VALUE_TYPE_DATE: break;
default: break;
}
}
wFields.optWidth(true);
}
public String toString()
{
return this.getClass().getName();
}
}
| false | true | public String open()
{
Shell parent = getParent();
Display display = parent.getDisplay();
shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN);
props.setLook(shell);
ModifyListener lsMod = new ModifyListener()
{
public void modifyText(ModifyEvent e)
{
input.setChanged();
}
};
changed = input.hasChanged();
FormLayout formLayout = new FormLayout ();
formLayout.marginWidth = Const.FORM_MARGIN;
formLayout.marginHeight = Const.FORM_MARGIN;
shell.setLayout(formLayout);
shell.setText(Messages.getString("XMLOutputDialog.DialogTitle"));
int middle = props.getMiddlePct();
int margin = Const.MARGIN;
// Stepname line
wlStepname=new Label(shell, SWT.RIGHT);
wlStepname.setText(Messages.getString("System.Label.StepName"));
props.setLook(wlStepname);
fdlStepname=new FormData();
fdlStepname.left = new FormAttachment(0, 0);
fdlStepname.top = new FormAttachment(0, margin);
fdlStepname.right = new FormAttachment(middle, -margin);
wlStepname.setLayoutData(fdlStepname);
wStepname=new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wStepname.setText(stepname);
props.setLook(wStepname);
wStepname.addModifyListener(lsMod);
fdStepname=new FormData();
fdStepname.left = new FormAttachment(middle, 0);
fdStepname.top = new FormAttachment(0, margin);
fdStepname.right= new FormAttachment(100, 0);
wStepname.setLayoutData(fdStepname);
wTabFolder = new CTabFolder(shell, SWT.BORDER);
props.setLook(wTabFolder, Props.WIDGET_STYLE_TAB);
//////////////////////////
// START OF FILE TAB///
///
wFileTab=new CTabItem(wTabFolder, SWT.NONE);
wFileTab.setText(Messages.getString("XMLOutputDialog.FileTab.Tab"));
Composite wFileComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wFileComp);
FormLayout fileLayout = new FormLayout();
fileLayout.marginWidth = 3;
fileLayout.marginHeight = 3;
wFileComp.setLayout(fileLayout);
// Filename line
wlFilename=new Label(wFileComp, SWT.RIGHT);
wlFilename.setText(Messages.getString("XMLOutputDialog.Filename.Label"));
props.setLook(wlFilename);
fdlFilename=new FormData();
fdlFilename.left = new FormAttachment(0, 0);
fdlFilename.top = new FormAttachment(0, margin);
fdlFilename.right= new FormAttachment(middle, -margin);
wlFilename.setLayoutData(fdlFilename);
wbFilename=new Button(wFileComp, SWT.PUSH| SWT.CENTER);
props.setLook(wbFilename);
wbFilename.setText(Messages.getString("XMLOutputDialog.Browse.Button"));
fdbFilename=new FormData();
fdbFilename.right= new FormAttachment(100, 0);
fdbFilename.top = new FormAttachment(0, 0);
wbFilename.setLayoutData(fdbFilename);
wbcFilename=new Button(wFileComp, SWT.PUSH| SWT.CENTER);
props.setLook(wbcFilename);
wbcFilename.setText(Messages.getString("XMLOutputDialog.Variable.Button"));
fdbcFilename=new FormData();
fdbcFilename.right= new FormAttachment(wbFilename, -margin);
fdbcFilename.top = new FormAttachment(0, 0);
wbcFilename.setLayoutData(fdbcFilename);
wFilename=new Text(wFileComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wFilename);
wFilename.addModifyListener(lsMod);
fdFilename=new FormData();
fdFilename.left = new FormAttachment(middle, 0);
fdFilename.top = new FormAttachment(0, margin);
fdFilename.right= new FormAttachment(wbcFilename, -margin);
wFilename.setLayoutData(fdFilename);
// Whenever something changes, set the tooltip to the expanded version:
wFilename.addModifyListener(new ModifyListener()
{
public void modifyText(ModifyEvent e)
{
wFilename.setToolTipText(StringUtil.environmentSubstitute( wFilename.getText() ) );
}
}
);
// Extension line
wlExtension=new Label(wFileComp, SWT.RIGHT);
wlExtension.setText(Messages.getString("XMLOutputDialog.Extension.Label"));
props.setLook(wlExtension);
fdlExtension=new FormData();
fdlExtension.left = new FormAttachment(0, 0);
fdlExtension.top = new FormAttachment(wFilename, margin);
fdlExtension.right= new FormAttachment(middle, -margin);
wlExtension.setLayoutData(fdlExtension);
wExtension=new Text(wFileComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wExtension.setText("");
props.setLook(wExtension);
wExtension.addModifyListener(lsMod);
fdExtension=new FormData();
fdExtension.left = new FormAttachment(middle, 0);
fdExtension.top = new FormAttachment(wFilename, margin);
fdExtension.right= new FormAttachment(100, 0);
wExtension.setLayoutData(fdExtension);
// Create multi-part file?
wlAddStepnr=new Label(wFileComp, SWT.RIGHT);
wlAddStepnr.setText("Include stepnr in filename? ");
props.setLook(wlAddStepnr);
fdlAddStepnr=new FormData();
fdlAddStepnr.left = new FormAttachment(0, 0);
fdlAddStepnr.top = new FormAttachment(wExtension, margin);
fdlAddStepnr.right= new FormAttachment(middle, -margin);
wlAddStepnr.setLayoutData(fdlAddStepnr);
wAddStepnr=new Button(wFileComp, SWT.CHECK);
props.setLook(wAddStepnr);
fdAddStepnr=new FormData();
fdAddStepnr.left = new FormAttachment(middle, 0);
fdAddStepnr.top = new FormAttachment(wExtension, margin);
fdAddStepnr.right= new FormAttachment(100, 0);
wAddStepnr.setLayoutData(fdAddStepnr);
wAddStepnr.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
input.setChanged();
}
}
);
// Create multi-part file?
wlAddDate=new Label(wFileComp, SWT.RIGHT);
wlAddDate.setText(Messages.getString("XMLOutputDialog.AddDate.Label"));
props.setLook(wlAddDate);
fdlAddDate=new FormData();
fdlAddDate.left = new FormAttachment(0, 0);
fdlAddDate.top = new FormAttachment(wAddStepnr, margin);
fdlAddDate.right= new FormAttachment(middle, -margin);
wlAddDate.setLayoutData(fdlAddDate);
wAddDate=new Button(wFileComp, SWT.CHECK);
props.setLook(wAddDate);
fdAddDate=new FormData();
fdAddDate.left = new FormAttachment(middle, 0);
fdAddDate.top = new FormAttachment(wAddStepnr, margin);
fdAddDate.right= new FormAttachment(100, 0);
wAddDate.setLayoutData(fdAddDate);
wAddDate.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
input.setChanged();
}
}
);
// Create multi-part file?
wlAddTime=new Label(wFileComp, SWT.RIGHT);
wlAddTime.setText(Messages.getString("XMLOutputDialog.AddTime.Label"));
props.setLook(wlAddTime);
fdlAddTime=new FormData();
fdlAddTime.left = new FormAttachment(0, 0);
fdlAddTime.top = new FormAttachment(wAddDate, margin);
fdlAddTime.right= new FormAttachment(middle, -margin);
wlAddTime.setLayoutData(fdlAddTime);
wAddTime=new Button(wFileComp, SWT.CHECK);
props.setLook(wAddTime);
fdAddTime=new FormData();
fdAddTime.left = new FormAttachment(middle, 0);
fdAddTime.top = new FormAttachment(wAddDate, margin);
fdAddTime.right= new FormAttachment(100, 0);
wAddTime.setLayoutData(fdAddTime);
wAddTime.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
input.setChanged();
}
}
);
wbShowFiles=new Button(wFileComp, SWT.PUSH| SWT.CENTER);
props.setLook(wbShowFiles);
wbShowFiles.setText(Messages.getString("XMLOutputDialog.ShowFiles.Button"));
fdbShowFiles=new FormData();
fdbShowFiles.left = new FormAttachment(middle, 0);
fdbShowFiles.top = new FormAttachment(wAddTime, margin*2);
wbShowFiles.setLayoutData(fdbShowFiles);
wbShowFiles.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
XMLOutputMeta tfoi = new XMLOutputMeta();
getInfo(tfoi);
String files[] = tfoi.getFiles();
if (files!=null && files.length>0)
{
EnterSelectionDialog esd = new EnterSelectionDialog(shell, props, files, Messages.getString("XMLOutputDialog.OutputFiles.DialogTitle"), Messages.getString("XMLOutputDialog.OutputFiles.DialogMessage"));
esd.setViewOnly();
esd.open();
}
else
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR );
mb.setMessage(Messages.getString("XMLOutputDialog.NoFilesFound.DialogMessage"));
mb.setText(Messages.getString("System.Dialog.Error.Title"));
mb.open();
}
}
}
);
fdFileComp=new FormData();
fdFileComp.left = new FormAttachment(0, 0);
fdFileComp.top = new FormAttachment(0, 0);
fdFileComp.right = new FormAttachment(100, 0);
fdFileComp.bottom= new FormAttachment(100, 0);
wFileComp.setLayoutData(fdFileComp);
wFileComp.layout();
wFileTab.setControl(wFileComp);
/////////////////////////////////////////////////////////////
/// END OF FILE TAB
/////////////////////////////////////////////////////////////
//////////////////////////
// START OF CONTENT TAB///
///
wContentTab=new CTabItem(wTabFolder, SWT.NONE);
wContentTab.setText(Messages.getString("XMLOutputDialog.ContentTab.TabTitle"));
FormLayout contentLayout = new FormLayout ();
contentLayout.marginWidth = 3;
contentLayout.marginHeight = 3;
Composite wContentComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wContentComp);
wContentComp.setLayout(contentLayout);
wlZipped=new Label(wContentComp, SWT.RIGHT);
wlZipped.setText(Messages.getString("XMLOutputDialog.Zipped.Label"));
props.setLook(wlZipped);
fdlZipped=new FormData();
fdlZipped.left = new FormAttachment(0, 0);
fdlZipped.top = new FormAttachment(0, 0);
fdlZipped.right= new FormAttachment(middle, -margin);
wlZipped.setLayoutData(fdlZipped);
wZipped=new Button(wContentComp, SWT.CHECK );
props.setLook(wZipped);
fdZipped=new FormData();
fdZipped.left = new FormAttachment(middle, 0);
fdZipped.top = new FormAttachment(0, 0);
fdZipped.right= new FormAttachment(100, 0);
wZipped.setLayoutData(fdZipped);
wZipped.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
input.setChanged();
}
}
);
wlEncoding=new Label(wContentComp, SWT.RIGHT);
wlEncoding.setText(Messages.getString("XMLOutputDialog.Encoding.Label"));
props.setLook(wlEncoding);
fdlEncoding=new FormData();
fdlEncoding.left = new FormAttachment(0, 0);
fdlEncoding.top = new FormAttachment(wZipped, margin);
fdlEncoding.right= new FormAttachment(middle, -margin);
wlEncoding.setLayoutData(fdlEncoding);
wEncoding=new CCombo(wContentComp, SWT.BORDER | SWT.READ_ONLY);
wEncoding.setEditable(true);
props.setLook(wEncoding);
wEncoding.addModifyListener(lsMod);
fdEncoding=new FormData();
fdEncoding.left = new FormAttachment(middle, 0);
fdEncoding.top = new FormAttachment(wZipped, margin);
fdEncoding.right= new FormAttachment(100, 0);
wEncoding.setLayoutData(fdEncoding);
wEncoding.addFocusListener(new FocusListener()
{
public void focusLost(org.eclipse.swt.events.FocusEvent e)
{
}
public void focusGained(org.eclipse.swt.events.FocusEvent e)
{
Cursor busy = new Cursor(shell.getDisplay(), SWT.CURSOR_WAIT);
shell.setCursor(busy);
setEncodings();
shell.setCursor(null);
busy.dispose();
}
}
);
wlMainElement=new Label(wContentComp, SWT.RIGHT);
wlMainElement.setText(Messages.getString("XMLOutputDialog.MainElement.Label"));
props.setLook(wlMainElement);
fdlMainElement=new FormData();
fdlMainElement.left = new FormAttachment(0, 0);
fdlMainElement.top = new FormAttachment(wEncoding, margin);
fdlMainElement.right= new FormAttachment(middle, -margin);
wlMainElement.setLayoutData(fdlMainElement);
wMainElement=new CCombo(wContentComp, SWT.BORDER | SWT.READ_ONLY);
wMainElement.setEditable(true);
props.setLook(wMainElement);
wMainElement.addModifyListener(lsMod);
fdMainElement=new FormData();
fdMainElement.left = new FormAttachment(middle, 0);
fdMainElement.top = new FormAttachment(wEncoding, margin);
fdMainElement.right= new FormAttachment(100, 0);
wMainElement.setLayoutData(fdMainElement);
wlRepeatElement=new Label(wContentComp, SWT.RIGHT);
wlRepeatElement.setText(Messages.getString("XMLOutputDialog.RepeatElement.Label"));
props.setLook(wlRepeatElement);
fdlRepeatElement=new FormData();
fdlRepeatElement.left = new FormAttachment(0, 0);
fdlRepeatElement.top = new FormAttachment(wMainElement, margin);
fdlRepeatElement.right= new FormAttachment(middle, -margin);
wlRepeatElement.setLayoutData(fdlRepeatElement);
wRepeatElement=new CCombo(wContentComp, SWT.BORDER | SWT.READ_ONLY);
wRepeatElement.setEditable(true);
props.setLook(wRepeatElement);
wRepeatElement.addModifyListener(lsMod);
fdRepeatElement=new FormData();
fdRepeatElement.left = new FormAttachment(middle, 0);
fdRepeatElement.top = new FormAttachment(wMainElement, margin);
fdRepeatElement.right= new FormAttachment(100, 0);
wRepeatElement.setLayoutData(fdRepeatElement);
wlSplitEvery=new Label(wContentComp, SWT.RIGHT);
wlSplitEvery.setText(Messages.getString("XMLOutputDialog.SplitEvery.Label"));
props.setLook(wlSplitEvery);
fdlSplitEvery=new FormData();
fdlSplitEvery.left = new FormAttachment(0, 0);
fdlSplitEvery.top = new FormAttachment(wRepeatElement, margin);
fdlSplitEvery.right= new FormAttachment(middle, -margin);
wlSplitEvery.setLayoutData(fdlSplitEvery);
wSplitEvery=new Text(wContentComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wSplitEvery);
wSplitEvery.addModifyListener(lsMod);
fdSplitEvery=new FormData();
fdSplitEvery.left = new FormAttachment(middle, 0);
fdSplitEvery.top = new FormAttachment(wRepeatElement, margin);
fdSplitEvery.right= new FormAttachment(100, 0);
wSplitEvery.setLayoutData(fdSplitEvery);
fdContentComp = new FormData();
fdContentComp.left = new FormAttachment(0, 0);
fdContentComp.top = new FormAttachment(0, 0);
fdContentComp.right = new FormAttachment(100, 0);
fdContentComp.bottom= new FormAttachment(100, 0);
wContentComp.setLayoutData(fdContentComp);
wContentComp.layout();
wContentTab.setControl(wContentComp);
/////////////////////////////////////////////////////////////
/// END OF CONTENT TAB
/////////////////////////////////////////////////////////////
// Fields tab...
//
wFieldsTab = new CTabItem(wTabFolder, SWT.NONE);
wFieldsTab.setText(Messages.getString("XMLOutputDialog.FieldsTab.TabTitle"));
FormLayout fieldsLayout = new FormLayout ();
fieldsLayout.marginWidth = Const.FORM_MARGIN;
fieldsLayout.marginHeight = Const.FORM_MARGIN;
Composite wFieldsComp = new Composite(wTabFolder, SWT.NONE);
wFieldsComp.setLayout(fieldsLayout);
props.setLook(wFieldsComp);
wGet=new Button(wFieldsComp, SWT.PUSH);
wGet.setText(Messages.getString("XMLOutputDialog.SplitEvery.Label"));
wGet.setToolTipText(Messages.getString("XMLOutputDialog.Get.Tooltip"));
wMinWidth =new Button(wFieldsComp, SWT.PUSH);
wMinWidth.setText(Messages.getString("XMLOutputDialog.Get.Button"));
wMinWidth.setToolTipText(Messages.getString("XMLOutputDialog.Get.Tooltip"));
setButtonPositions(new Button[] { wGet, wMinWidth}, margin, null);
final int FieldsRows=input.getOutputFields().length;
// Prepare a list of possible formats...
String dats[] = Const.dateFormats;
String nums[] = Const.numberFormats;
int totsize = dats.length + nums.length;
String formats[] = new String[totsize];
for (int x=0;x<dats.length;x++) formats[x] = dats[x];
for (int x=0;x<nums.length;x++) formats[dats.length+x] = nums[x];
ColumnInfo[] colinf=new ColumnInfo[]
{
new ColumnInfo(Messages.getString("XMLOutputDialog.Fieldname.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false),
new ColumnInfo(Messages.getString("XMLOutputDialog.Fieldname.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false),
new ColumnInfo(Messages.getString("XMLOutputDialog.Type.Column"), ColumnInfo.COLUMN_TYPE_CCOMBO, Value.getTypes() ),
new ColumnInfo(Messages.getString("XMLOutputDialog.Format.Column"), ColumnInfo.COLUMN_TYPE_CCOMBO, formats),
new ColumnInfo(Messages.getString("XMLOutputDialog.Length.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false),
new ColumnInfo(Messages.getString("XMLOutputDialog.Precision.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false),
new ColumnInfo(Messages.getString("XMLOutputDialog.Currency.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false),
new ColumnInfo(Messages.getString("XMLOutputDialog.Decimal.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false),
new ColumnInfo(Messages.getString("XMLOutputDialog.Group.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false),
new ColumnInfo(Messages.getString("XMLOutputDialog.Null.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false)
};
wFields=new TableView(wFieldsComp,
SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI,
colinf,
FieldsRows,
lsMod,
props
);
fdFields=new FormData();
fdFields.left = new FormAttachment(0, 0);
fdFields.top = new FormAttachment(0, 0);
fdFields.right = new FormAttachment(100, 0);
fdFields.bottom= new FormAttachment(wGet, -margin);
wFields.setLayoutData(fdFields);
fdFieldsComp=new FormData();
fdFieldsComp.left = new FormAttachment(0, 0);
fdFieldsComp.top = new FormAttachment(0, 0);
fdFieldsComp.right = new FormAttachment(100, 0);
fdFieldsComp.bottom= new FormAttachment(100, 0);
wFieldsComp.setLayoutData(fdFieldsComp);
wFieldsComp.layout();
wFieldsTab.setControl(wFieldsComp);
fdTabFolder = new FormData();
fdTabFolder.left = new FormAttachment(0, 0);
fdTabFolder.top = new FormAttachment(wStepname, margin);
fdTabFolder.right = new FormAttachment(100, 0);
fdTabFolder.bottom= new FormAttachment(100, -50);
wTabFolder.setLayoutData(fdTabFolder);
wOK=new Button(shell, SWT.PUSH);
wOK.setText(Messages.getString("System.Button.OK"));
wCancel=new Button(shell, SWT.PUSH);
wCancel.setText(Messages.getString("System.Button.Cancel"));
setButtonPositions(new Button[] { wOK, wCancel }, margin, wTabFolder);
// Add listeners
lsOK = new Listener() { public void handleEvent(Event e) { ok(); } };
lsGet = new Listener() { public void handleEvent(Event e) { get(); } };
lsMinWidth = new Listener() { public void handleEvent(Event e) { setMinimalWidth(); } };
lsCancel = new Listener() { public void handleEvent(Event e) { cancel(); } };
wOK.addListener (SWT.Selection, lsOK );
wGet.addListener (SWT.Selection, lsGet );
wMinWidth.addListener (SWT.Selection, lsMinWidth );
wCancel.addListener(SWT.Selection, lsCancel);
lsDef=new SelectionAdapter() { public void widgetDefaultSelected(SelectionEvent e) { ok(); } };
wStepname.addSelectionListener( lsDef );
wFilename.addSelectionListener( lsDef );
// Whenever something changes, set the tooltip to the expanded version:
wFilename.addModifyListener(new ModifyListener()
{
public void modifyText(ModifyEvent e)
{
wFilename.setToolTipText(StringUtil.environmentSubstitute( wFilename.getText() ) );
}
}
);
// Listen to the Variable... button
wbcFilename.addSelectionListener(VariableButtonListenerFactory.getSelectionAdapter(shell, wFilename));
wbFilename.addSelectionListener
(
new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
FileDialog dialog = new FileDialog(shell, SWT.OPEN);
dialog.setFilterExtensions(new String[] {"*.txt", "*.csv", "*"});
if (wFilename.getText()!=null)
{
dialog.setFileName(StringUtil.environmentSubstitute(wFilename.getText()));
}
dialog.setFilterNames(new String[] {Messages.getString("System.FileType.TextFiles"), Messages.getString("System.FileType.CSVFiles"), Messages.getString("System.FileType.AllFiles")});
if (dialog.open()!=null)
{
wFilename.setText(dialog.getFilterPath()+System.getProperty("file.separator")+dialog.getFileName());
}
}
}
);
// Detect X or ALT-F4 or something that kills this window...
shell.addShellListener( new ShellAdapter() { public void shellClosed(ShellEvent e) { cancel(); } } );
lsResize = new Listener()
{
public void handleEvent(Event event)
{
Point size = shell.getSize();
wFields.setSize(size.x-10, size.y-50);
wFields.table.setSize(size.x-10, size.y-50);
wFields.redraw();
}
};
shell.addListener(SWT.Resize, lsResize);
wTabFolder.setSelection(0);
// Set the shell size, based upon previous time...
setSize();
getData();
input.setChanged(changed);
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch()) display.sleep();
}
return stepname;
}
| public String open()
{
Shell parent = getParent();
Display display = parent.getDisplay();
shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN);
props.setLook(shell);
ModifyListener lsMod = new ModifyListener()
{
public void modifyText(ModifyEvent e)
{
input.setChanged();
}
};
changed = input.hasChanged();
FormLayout formLayout = new FormLayout ();
formLayout.marginWidth = Const.FORM_MARGIN;
formLayout.marginHeight = Const.FORM_MARGIN;
shell.setLayout(formLayout);
shell.setText(Messages.getString("XMLOutputDialog.DialogTitle"));
int middle = props.getMiddlePct();
int margin = Const.MARGIN;
// Stepname line
wlStepname=new Label(shell, SWT.RIGHT);
wlStepname.setText(Messages.getString("System.Label.StepName"));
props.setLook(wlStepname);
fdlStepname=new FormData();
fdlStepname.left = new FormAttachment(0, 0);
fdlStepname.top = new FormAttachment(0, margin);
fdlStepname.right = new FormAttachment(middle, -margin);
wlStepname.setLayoutData(fdlStepname);
wStepname=new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wStepname.setText(stepname);
props.setLook(wStepname);
wStepname.addModifyListener(lsMod);
fdStepname=new FormData();
fdStepname.left = new FormAttachment(middle, 0);
fdStepname.top = new FormAttachment(0, margin);
fdStepname.right= new FormAttachment(100, 0);
wStepname.setLayoutData(fdStepname);
wTabFolder = new CTabFolder(shell, SWT.BORDER);
props.setLook(wTabFolder, Props.WIDGET_STYLE_TAB);
//////////////////////////
// START OF FILE TAB///
///
wFileTab=new CTabItem(wTabFolder, SWT.NONE);
wFileTab.setText(Messages.getString("XMLOutputDialog.FileTab.Tab"));
Composite wFileComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wFileComp);
FormLayout fileLayout = new FormLayout();
fileLayout.marginWidth = 3;
fileLayout.marginHeight = 3;
wFileComp.setLayout(fileLayout);
// Filename line
wlFilename=new Label(wFileComp, SWT.RIGHT);
wlFilename.setText(Messages.getString("XMLOutputDialog.Filename.Label"));
props.setLook(wlFilename);
fdlFilename=new FormData();
fdlFilename.left = new FormAttachment(0, 0);
fdlFilename.top = new FormAttachment(0, margin);
fdlFilename.right= new FormAttachment(middle, -margin);
wlFilename.setLayoutData(fdlFilename);
wbFilename=new Button(wFileComp, SWT.PUSH| SWT.CENTER);
props.setLook(wbFilename);
wbFilename.setText(Messages.getString("XMLOutputDialog.Browse.Button"));
fdbFilename=new FormData();
fdbFilename.right= new FormAttachment(100, 0);
fdbFilename.top = new FormAttachment(0, 0);
wbFilename.setLayoutData(fdbFilename);
wbcFilename=new Button(wFileComp, SWT.PUSH| SWT.CENTER);
props.setLook(wbcFilename);
wbcFilename.setText(Messages.getString("XMLOutputDialog.Variable.Button"));
fdbcFilename=new FormData();
fdbcFilename.right= new FormAttachment(wbFilename, -margin);
fdbcFilename.top = new FormAttachment(0, 0);
wbcFilename.setLayoutData(fdbcFilename);
wFilename=new Text(wFileComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wFilename);
wFilename.addModifyListener(lsMod);
fdFilename=new FormData();
fdFilename.left = new FormAttachment(middle, 0);
fdFilename.top = new FormAttachment(0, margin);
fdFilename.right= new FormAttachment(wbcFilename, -margin);
wFilename.setLayoutData(fdFilename);
// Whenever something changes, set the tooltip to the expanded version:
wFilename.addModifyListener(new ModifyListener()
{
public void modifyText(ModifyEvent e)
{
wFilename.setToolTipText(StringUtil.environmentSubstitute( wFilename.getText() ) );
}
}
);
// Extension line
wlExtension=new Label(wFileComp, SWT.RIGHT);
wlExtension.setText(Messages.getString("XMLOutputDialog.Extension.Label"));
props.setLook(wlExtension);
fdlExtension=new FormData();
fdlExtension.left = new FormAttachment(0, 0);
fdlExtension.top = new FormAttachment(wFilename, margin);
fdlExtension.right= new FormAttachment(middle, -margin);
wlExtension.setLayoutData(fdlExtension);
wExtension=new Text(wFileComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wExtension.setText("");
props.setLook(wExtension);
wExtension.addModifyListener(lsMod);
fdExtension=new FormData();
fdExtension.left = new FormAttachment(middle, 0);
fdExtension.top = new FormAttachment(wFilename, margin);
fdExtension.right= new FormAttachment(100, 0);
wExtension.setLayoutData(fdExtension);
// Create multi-part file?
wlAddStepnr=new Label(wFileComp, SWT.RIGHT);
wlAddStepnr.setText(Messages.getString("XMLOutputDialog.AddStepNr.Label"));
props.setLook(wlAddStepnr);
fdlAddStepnr=new FormData();
fdlAddStepnr.left = new FormAttachment(0, 0);
fdlAddStepnr.top = new FormAttachment(wExtension, margin);
fdlAddStepnr.right= new FormAttachment(middle, -margin);
wlAddStepnr.setLayoutData(fdlAddStepnr);
wAddStepnr=new Button(wFileComp, SWT.CHECK);
props.setLook(wAddStepnr);
fdAddStepnr=new FormData();
fdAddStepnr.left = new FormAttachment(middle, 0);
fdAddStepnr.top = new FormAttachment(wExtension, margin);
fdAddStepnr.right= new FormAttachment(100, 0);
wAddStepnr.setLayoutData(fdAddStepnr);
wAddStepnr.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
input.setChanged();
}
}
);
// Create multi-part file?
wlAddDate=new Label(wFileComp, SWT.RIGHT);
wlAddDate.setText(Messages.getString("XMLOutputDialog.AddDate.Label"));
props.setLook(wlAddDate);
fdlAddDate=new FormData();
fdlAddDate.left = new FormAttachment(0, 0);
fdlAddDate.top = new FormAttachment(wAddStepnr, margin);
fdlAddDate.right= new FormAttachment(middle, -margin);
wlAddDate.setLayoutData(fdlAddDate);
wAddDate=new Button(wFileComp, SWT.CHECK);
props.setLook(wAddDate);
fdAddDate=new FormData();
fdAddDate.left = new FormAttachment(middle, 0);
fdAddDate.top = new FormAttachment(wAddStepnr, margin);
fdAddDate.right= new FormAttachment(100, 0);
wAddDate.setLayoutData(fdAddDate);
wAddDate.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
input.setChanged();
}
}
);
// Create multi-part file?
wlAddTime=new Label(wFileComp, SWT.RIGHT);
wlAddTime.setText(Messages.getString("XMLOutputDialog.AddTime.Label"));
props.setLook(wlAddTime);
fdlAddTime=new FormData();
fdlAddTime.left = new FormAttachment(0, 0);
fdlAddTime.top = new FormAttachment(wAddDate, margin);
fdlAddTime.right= new FormAttachment(middle, -margin);
wlAddTime.setLayoutData(fdlAddTime);
wAddTime=new Button(wFileComp, SWT.CHECK);
props.setLook(wAddTime);
fdAddTime=new FormData();
fdAddTime.left = new FormAttachment(middle, 0);
fdAddTime.top = new FormAttachment(wAddDate, margin);
fdAddTime.right= new FormAttachment(100, 0);
wAddTime.setLayoutData(fdAddTime);
wAddTime.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
input.setChanged();
}
}
);
wbShowFiles=new Button(wFileComp, SWT.PUSH| SWT.CENTER);
props.setLook(wbShowFiles);
wbShowFiles.setText(Messages.getString("XMLOutputDialog.ShowFiles.Button"));
fdbShowFiles=new FormData();
fdbShowFiles.left = new FormAttachment(middle, 0);
fdbShowFiles.top = new FormAttachment(wAddTime, margin*2);
wbShowFiles.setLayoutData(fdbShowFiles);
wbShowFiles.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
XMLOutputMeta tfoi = new XMLOutputMeta();
getInfo(tfoi);
String files[] = tfoi.getFiles();
if (files!=null && files.length>0)
{
EnterSelectionDialog esd = new EnterSelectionDialog(shell, props, files, Messages.getString("XMLOutputDialog.OutputFiles.DialogTitle"), Messages.getString("XMLOutputDialog.OutputFiles.DialogMessage"));
esd.setViewOnly();
esd.open();
}
else
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR );
mb.setMessage(Messages.getString("XMLOutputDialog.NoFilesFound.DialogMessage"));
mb.setText(Messages.getString("System.Dialog.Error.Title"));
mb.open();
}
}
}
);
fdFileComp=new FormData();
fdFileComp.left = new FormAttachment(0, 0);
fdFileComp.top = new FormAttachment(0, 0);
fdFileComp.right = new FormAttachment(100, 0);
fdFileComp.bottom= new FormAttachment(100, 0);
wFileComp.setLayoutData(fdFileComp);
wFileComp.layout();
wFileTab.setControl(wFileComp);
/////////////////////////////////////////////////////////////
/// END OF FILE TAB
/////////////////////////////////////////////////////////////
//////////////////////////
// START OF CONTENT TAB///
///
wContentTab=new CTabItem(wTabFolder, SWT.NONE);
wContentTab.setText(Messages.getString("XMLOutputDialog.ContentTab.TabTitle"));
FormLayout contentLayout = new FormLayout ();
contentLayout.marginWidth = 3;
contentLayout.marginHeight = 3;
Composite wContentComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wContentComp);
wContentComp.setLayout(contentLayout);
wlZipped=new Label(wContentComp, SWT.RIGHT);
wlZipped.setText(Messages.getString("XMLOutputDialog.Zipped.Label"));
props.setLook(wlZipped);
fdlZipped=new FormData();
fdlZipped.left = new FormAttachment(0, 0);
fdlZipped.top = new FormAttachment(0, 0);
fdlZipped.right= new FormAttachment(middle, -margin);
wlZipped.setLayoutData(fdlZipped);
wZipped=new Button(wContentComp, SWT.CHECK );
props.setLook(wZipped);
fdZipped=new FormData();
fdZipped.left = new FormAttachment(middle, 0);
fdZipped.top = new FormAttachment(0, 0);
fdZipped.right= new FormAttachment(100, 0);
wZipped.setLayoutData(fdZipped);
wZipped.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
input.setChanged();
}
}
);
wlEncoding=new Label(wContentComp, SWT.RIGHT);
wlEncoding.setText(Messages.getString("XMLOutputDialog.Encoding.Label"));
props.setLook(wlEncoding);
fdlEncoding=new FormData();
fdlEncoding.left = new FormAttachment(0, 0);
fdlEncoding.top = new FormAttachment(wZipped, margin);
fdlEncoding.right= new FormAttachment(middle, -margin);
wlEncoding.setLayoutData(fdlEncoding);
wEncoding=new CCombo(wContentComp, SWT.BORDER | SWT.READ_ONLY);
wEncoding.setEditable(true);
props.setLook(wEncoding);
wEncoding.addModifyListener(lsMod);
fdEncoding=new FormData();
fdEncoding.left = new FormAttachment(middle, 0);
fdEncoding.top = new FormAttachment(wZipped, margin);
fdEncoding.right= new FormAttachment(100, 0);
wEncoding.setLayoutData(fdEncoding);
wEncoding.addFocusListener(new FocusListener()
{
public void focusLost(org.eclipse.swt.events.FocusEvent e)
{
}
public void focusGained(org.eclipse.swt.events.FocusEvent e)
{
Cursor busy = new Cursor(shell.getDisplay(), SWT.CURSOR_WAIT);
shell.setCursor(busy);
setEncodings();
shell.setCursor(null);
busy.dispose();
}
}
);
wlMainElement=new Label(wContentComp, SWT.RIGHT);
wlMainElement.setText(Messages.getString("XMLOutputDialog.MainElement.Label"));
props.setLook(wlMainElement);
fdlMainElement=new FormData();
fdlMainElement.left = new FormAttachment(0, 0);
fdlMainElement.top = new FormAttachment(wEncoding, margin);
fdlMainElement.right= new FormAttachment(middle, -margin);
wlMainElement.setLayoutData(fdlMainElement);
wMainElement=new CCombo(wContentComp, SWT.BORDER | SWT.READ_ONLY);
wMainElement.setEditable(true);
props.setLook(wMainElement);
wMainElement.addModifyListener(lsMod);
fdMainElement=new FormData();
fdMainElement.left = new FormAttachment(middle, 0);
fdMainElement.top = new FormAttachment(wEncoding, margin);
fdMainElement.right= new FormAttachment(100, 0);
wMainElement.setLayoutData(fdMainElement);
wlRepeatElement=new Label(wContentComp, SWT.RIGHT);
wlRepeatElement.setText(Messages.getString("XMLOutputDialog.RepeatElement.Label"));
props.setLook(wlRepeatElement);
fdlRepeatElement=new FormData();
fdlRepeatElement.left = new FormAttachment(0, 0);
fdlRepeatElement.top = new FormAttachment(wMainElement, margin);
fdlRepeatElement.right= new FormAttachment(middle, -margin);
wlRepeatElement.setLayoutData(fdlRepeatElement);
wRepeatElement=new CCombo(wContentComp, SWT.BORDER | SWT.READ_ONLY);
wRepeatElement.setEditable(true);
props.setLook(wRepeatElement);
wRepeatElement.addModifyListener(lsMod);
fdRepeatElement=new FormData();
fdRepeatElement.left = new FormAttachment(middle, 0);
fdRepeatElement.top = new FormAttachment(wMainElement, margin);
fdRepeatElement.right= new FormAttachment(100, 0);
wRepeatElement.setLayoutData(fdRepeatElement);
wlSplitEvery=new Label(wContentComp, SWT.RIGHT);
wlSplitEvery.setText(Messages.getString("XMLOutputDialog.SplitEvery.Label"));
props.setLook(wlSplitEvery);
fdlSplitEvery=new FormData();
fdlSplitEvery.left = new FormAttachment(0, 0);
fdlSplitEvery.top = new FormAttachment(wRepeatElement, margin);
fdlSplitEvery.right= new FormAttachment(middle, -margin);
wlSplitEvery.setLayoutData(fdlSplitEvery);
wSplitEvery=new Text(wContentComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wSplitEvery);
wSplitEvery.addModifyListener(lsMod);
fdSplitEvery=new FormData();
fdSplitEvery.left = new FormAttachment(middle, 0);
fdSplitEvery.top = new FormAttachment(wRepeatElement, margin);
fdSplitEvery.right= new FormAttachment(100, 0);
wSplitEvery.setLayoutData(fdSplitEvery);
fdContentComp = new FormData();
fdContentComp.left = new FormAttachment(0, 0);
fdContentComp.top = new FormAttachment(0, 0);
fdContentComp.right = new FormAttachment(100, 0);
fdContentComp.bottom= new FormAttachment(100, 0);
wContentComp.setLayoutData(fdContentComp);
wContentComp.layout();
wContentTab.setControl(wContentComp);
/////////////////////////////////////////////////////////////
/// END OF CONTENT TAB
/////////////////////////////////////////////////////////////
// Fields tab...
//
wFieldsTab = new CTabItem(wTabFolder, SWT.NONE);
wFieldsTab.setText(Messages.getString("XMLOutputDialog.FieldsTab.TabTitle"));
FormLayout fieldsLayout = new FormLayout ();
fieldsLayout.marginWidth = Const.FORM_MARGIN;
fieldsLayout.marginHeight = Const.FORM_MARGIN;
Composite wFieldsComp = new Composite(wTabFolder, SWT.NONE);
wFieldsComp.setLayout(fieldsLayout);
props.setLook(wFieldsComp);
wGet=new Button(wFieldsComp, SWT.PUSH);
wGet.setText(Messages.getString("XMLOutputDialog.Get.Button"));
wGet.setToolTipText(Messages.getString("XMLOutputDialog.Get.Tooltip"));
wMinWidth =new Button(wFieldsComp, SWT.PUSH);
wMinWidth.setText(Messages.getString("XMLOutputDialog.MinWidth.Label"));
wMinWidth.setToolTipText(Messages.getString("XMLOutputDialog.MinWidth.Tooltip"));
setButtonPositions(new Button[] { wGet, wMinWidth}, margin, null);
final int FieldsRows=input.getOutputFields().length;
// Prepare a list of possible formats...
String dats[] = Const.dateFormats;
String nums[] = Const.numberFormats;
int totsize = dats.length + nums.length;
String formats[] = new String[totsize];
for (int x=0;x<dats.length;x++) formats[x] = dats[x];
for (int x=0;x<nums.length;x++) formats[dats.length+x] = nums[x];
ColumnInfo[] colinf=new ColumnInfo[]
{
new ColumnInfo(Messages.getString("XMLOutputDialog.Fieldname.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false),
new ColumnInfo(Messages.getString("XMLOutputDialog.Fieldname.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false),
new ColumnInfo(Messages.getString("XMLOutputDialog.Type.Column"), ColumnInfo.COLUMN_TYPE_CCOMBO, Value.getTypes() ),
new ColumnInfo(Messages.getString("XMLOutputDialog.Format.Column"), ColumnInfo.COLUMN_TYPE_CCOMBO, formats),
new ColumnInfo(Messages.getString("XMLOutputDialog.Length.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false),
new ColumnInfo(Messages.getString("XMLOutputDialog.Precision.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false),
new ColumnInfo(Messages.getString("XMLOutputDialog.Currency.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false),
new ColumnInfo(Messages.getString("XMLOutputDialog.Decimal.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false),
new ColumnInfo(Messages.getString("XMLOutputDialog.Group.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false),
new ColumnInfo(Messages.getString("XMLOutputDialog.Null.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false)
};
wFields=new TableView(wFieldsComp,
SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI,
colinf,
FieldsRows,
lsMod,
props
);
fdFields=new FormData();
fdFields.left = new FormAttachment(0, 0);
fdFields.top = new FormAttachment(0, 0);
fdFields.right = new FormAttachment(100, 0);
fdFields.bottom= new FormAttachment(wGet, -margin);
wFields.setLayoutData(fdFields);
fdFieldsComp=new FormData();
fdFieldsComp.left = new FormAttachment(0, 0);
fdFieldsComp.top = new FormAttachment(0, 0);
fdFieldsComp.right = new FormAttachment(100, 0);
fdFieldsComp.bottom= new FormAttachment(100, 0);
wFieldsComp.setLayoutData(fdFieldsComp);
wFieldsComp.layout();
wFieldsTab.setControl(wFieldsComp);
fdTabFolder = new FormData();
fdTabFolder.left = new FormAttachment(0, 0);
fdTabFolder.top = new FormAttachment(wStepname, margin);
fdTabFolder.right = new FormAttachment(100, 0);
fdTabFolder.bottom= new FormAttachment(100, -50);
wTabFolder.setLayoutData(fdTabFolder);
wOK=new Button(shell, SWT.PUSH);
wOK.setText(Messages.getString("System.Button.OK"));
wCancel=new Button(shell, SWT.PUSH);
wCancel.setText(Messages.getString("System.Button.Cancel"));
setButtonPositions(new Button[] { wOK, wCancel }, margin, wTabFolder);
// Add listeners
lsOK = new Listener() { public void handleEvent(Event e) { ok(); } };
lsGet = new Listener() { public void handleEvent(Event e) { get(); } };
lsMinWidth = new Listener() { public void handleEvent(Event e) { setMinimalWidth(); } };
lsCancel = new Listener() { public void handleEvent(Event e) { cancel(); } };
wOK.addListener (SWT.Selection, lsOK );
wGet.addListener (SWT.Selection, lsGet );
wMinWidth.addListener (SWT.Selection, lsMinWidth );
wCancel.addListener(SWT.Selection, lsCancel);
lsDef=new SelectionAdapter() { public void widgetDefaultSelected(SelectionEvent e) { ok(); } };
wStepname.addSelectionListener( lsDef );
wFilename.addSelectionListener( lsDef );
// Whenever something changes, set the tooltip to the expanded version:
wFilename.addModifyListener(new ModifyListener()
{
public void modifyText(ModifyEvent e)
{
wFilename.setToolTipText(StringUtil.environmentSubstitute( wFilename.getText() ) );
}
}
);
// Listen to the Variable... button
wbcFilename.addSelectionListener(VariableButtonListenerFactory.getSelectionAdapter(shell, wFilename));
wbFilename.addSelectionListener
(
new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
FileDialog dialog = new FileDialog(shell, SWT.OPEN);
dialog.setFilterExtensions(new String[] {"*.txt", "*.csv", "*"});
if (wFilename.getText()!=null)
{
dialog.setFileName(StringUtil.environmentSubstitute(wFilename.getText()));
}
dialog.setFilterNames(new String[] {Messages.getString("System.FileType.TextFiles"), Messages.getString("System.FileType.CSVFiles"), Messages.getString("System.FileType.AllFiles")});
if (dialog.open()!=null)
{
wFilename.setText(dialog.getFilterPath()+System.getProperty("file.separator")+dialog.getFileName());
}
}
}
);
// Detect X or ALT-F4 or something that kills this window...
shell.addShellListener( new ShellAdapter() { public void shellClosed(ShellEvent e) { cancel(); } } );
lsResize = new Listener()
{
public void handleEvent(Event event)
{
Point size = shell.getSize();
wFields.setSize(size.x-10, size.y-50);
wFields.table.setSize(size.x-10, size.y-50);
wFields.redraw();
}
};
shell.addListener(SWT.Resize, lsResize);
wTabFolder.setSelection(0);
// Set the shell size, based upon previous time...
setSize();
getData();
input.setChanged(changed);
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch()) display.sleep();
}
return stepname;
}
|
diff --git a/KalenderProsjekt/src/framePackage/SharedCalendarView.java b/KalenderProsjekt/src/framePackage/SharedCalendarView.java
index 56baf94..bb96d41 100644
--- a/KalenderProsjekt/src/framePackage/SharedCalendarView.java
+++ b/KalenderProsjekt/src/framePackage/SharedCalendarView.java
@@ -1,79 +1,80 @@
package framePackage;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import data.CalendarModel;
import data.Person;
public class SharedCalendarView implements PropertyChangeListener{
private JPanel sharedCPanel;
private CalendarModel calendarModel;
private JCheckBox checkBox;
private List<Person> personList;
private List<JCheckBox> checkBoxList;
public SharedCalendarView(CalendarModel calendarModel){
initialize(calendarModel);
}
private void initialize(CalendarModel calendarModel){
this.calendarModel = calendarModel;
calendarModel.addPropertyChangeListener(this);
sharedCPanel = new JPanel(new GridBagLayout());
sharedCPanel.setPreferredSize(new Dimension(250, 200));
sharedCPanel.setVisible(true);
sharedCPanel.setBorder(BorderFactory.createLineBorder(Color.black, 1));
checkBoxList = new ArrayList<JCheckBox>();
personList = new ArrayList<Person>();
}
private void setCheckBox(List<Person> list){
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.LINE_START;
for(int i = 0; i < list.size(); i++){
personList.add(list.get(i));
checkBox = new JCheckBox(list.get(i).getFirstName() + list.get(i).getLastName());
- checkBox.setBackground(calendarModel.getColorOfPerson(list.get(i)));
+ checkBox.setForeground(calendarModel.getColorOfPerson(list.get(i)));
c.gridx = 0;
c.gridy = i;
sharedCPanel.add(checkBox,c);
checkBoxList.add(checkBox);
checkBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
calendarModel.setSelected(personList.get(checkBoxList.indexOf(checkBox)),checkBox.isSelected());
}
});
}
+ sharedCPanel.validate();
}
public JPanel getPanel(){
return sharedCPanel;
}
public void propertyChange(PropertyChangeEvent evt) {
switch (evt.getPropertyName()) {
case CalendarModel.PERSONS_ADDED_Property:
setCheckBox(calendarModel.getPersons());
System.out.println("cookie " + calendarModel.getPersons());
break;
}
}
}
| false | true | private void setCheckBox(List<Person> list){
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.LINE_START;
for(int i = 0; i < list.size(); i++){
personList.add(list.get(i));
checkBox = new JCheckBox(list.get(i).getFirstName() + list.get(i).getLastName());
checkBox.setBackground(calendarModel.getColorOfPerson(list.get(i)));
c.gridx = 0;
c.gridy = i;
sharedCPanel.add(checkBox,c);
checkBoxList.add(checkBox);
checkBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
calendarModel.setSelected(personList.get(checkBoxList.indexOf(checkBox)),checkBox.isSelected());
}
});
}
}
| private void setCheckBox(List<Person> list){
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.LINE_START;
for(int i = 0; i < list.size(); i++){
personList.add(list.get(i));
checkBox = new JCheckBox(list.get(i).getFirstName() + list.get(i).getLastName());
checkBox.setForeground(calendarModel.getColorOfPerson(list.get(i)));
c.gridx = 0;
c.gridy = i;
sharedCPanel.add(checkBox,c);
checkBoxList.add(checkBox);
checkBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
calendarModel.setSelected(personList.get(checkBoxList.indexOf(checkBox)),checkBox.isSelected());
}
});
}
sharedCPanel.validate();
}
|
diff --git a/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/ast/databuilder/statement/LocalVariableDeclarationStatementBuilder.java b/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/ast/databuilder/statement/LocalVariableDeclarationStatementBuilder.java
index ff5c15af..927ac4f0 100644
--- a/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/ast/databuilder/statement/LocalVariableDeclarationStatementBuilder.java
+++ b/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/ast/databuilder/statement/LocalVariableDeclarationStatementBuilder.java
@@ -1,78 +1,82 @@
package jp.ac.osaka_u.ist.sel.metricstool.main.ast.databuilder.statement;
import jp.ac.osaka_u.ist.sel.metricstool.main.ast.databuilder.BuildDataManager;
import jp.ac.osaka_u.ist.sel.metricstool.main.ast.databuilder.CompoundDataBuilder;
import jp.ac.osaka_u.ist.sel.metricstool.main.ast.databuilder.LocalVariableBuilder;
import jp.ac.osaka_u.ist.sel.metricstool.main.ast.statemanager.LocalVariableStateManager;
import jp.ac.osaka_u.ist.sel.metricstool.main.ast.statemanager.StateChangeEvent;
import jp.ac.osaka_u.ist.sel.metricstool.main.ast.statemanager.StateChangeEvent.StateChangeEventType;
import jp.ac.osaka_u.ist.sel.metricstool.main.ast.statemanager.VariableDefinitionStateManager.VARIABLE_STATE;
import jp.ac.osaka_u.ist.sel.metricstool.main.ast.visitor.AstVisitEvent;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.ExpressionInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.LocalSpaceInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.unresolved.UnresolvedExpressionInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.unresolved.UnresolvedLocalSpaceInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.unresolved.UnresolvedLocalVariableUsageInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.unresolved.UnresolvedVariableDeclarationStatementInfo;
public class LocalVariableDeclarationStatementBuilder extends
CompoundDataBuilder<UnresolvedVariableDeclarationStatementInfo> {
public LocalVariableDeclarationStatementBuilder(final LocalVariableBuilder variableBuilder,
final BuildDataManager buildDataManager) {
if (null == variableBuilder) {
throw new IllegalArgumentException("variableBuilder is null.");
}
this.variableBuilder = variableBuilder;
this.buildDataManager = buildDataManager;
this.addStateManager(new LocalVariableStateManager());
}
@Override
public void stateChanged(StateChangeEvent<AstVisitEvent> event) {
final StateChangeEventType eventType = event.getType();
if (eventType.equals(VARIABLE_STATE.EXIT_VARIABLE_DEF)) {
final AstVisitEvent trigger = event.getTrigger();
final UnresolvedVariableDeclarationStatementInfo builtDeclarationStatement = this
.buildVariableDeclarationStatement(this.variableBuilder
.getLastDeclarationUsage(), this.variableBuilder
.getLastBuiltExpression(), trigger.getStartLine(), trigger
.getStartColumn(), trigger.getEndLine(), trigger.getEndColumn());
this.registBuiltData(builtDeclarationStatement);
}
}
private UnresolvedVariableDeclarationStatementInfo buildVariableDeclarationStatement(
final UnresolvedLocalVariableUsageInfo declarationUsage,
final UnresolvedExpressionInfo<? extends ExpressionInfo> initializerExpression,
final int fromLine, final int fromColumn, final int toLine, final int toColumn) {
final UnresolvedVariableDeclarationStatementInfo declarationStatement = new UnresolvedVariableDeclarationStatementInfo(
declarationUsage, initializerExpression);
declarationStatement.setOuterUnit(this.buildDataManager.getCurrentUnit());
// FIXME: this is temporal patch. fix ANTLR grammar file
- final int correctToLine = declarationUsage.getToLine();
- final int correctToColumn = declarationUsage.getToColumn();
+ int correctToLine = declarationUsage.getToLine();
+ int correctToColumn = declarationUsage.getToColumn();
+ if (initializerExpression != null){
+ correctToLine = initializerExpression.getToLine();
+ correctToColumn= initializerExpression.getToColumn();
+ }
declarationStatement.setFromLine(fromLine);
declarationStatement.setFromColumn(fromColumn);
declarationStatement.setToLine(correctToLine);
declarationStatement.setToColumn(correctToColumn);
final UnresolvedLocalSpaceInfo<? extends LocalSpaceInfo> currentLocal = this.buildDataManager
.getCurrentLocalSpace();
if (null != currentLocal) {
currentLocal.addStatement(declarationStatement);
}
return declarationStatement;
}
private final LocalVariableBuilder variableBuilder;
private final BuildDataManager buildDataManager;
}
| true | true | private UnresolvedVariableDeclarationStatementInfo buildVariableDeclarationStatement(
final UnresolvedLocalVariableUsageInfo declarationUsage,
final UnresolvedExpressionInfo<? extends ExpressionInfo> initializerExpression,
final int fromLine, final int fromColumn, final int toLine, final int toColumn) {
final UnresolvedVariableDeclarationStatementInfo declarationStatement = new UnresolvedVariableDeclarationStatementInfo(
declarationUsage, initializerExpression);
declarationStatement.setOuterUnit(this.buildDataManager.getCurrentUnit());
// FIXME: this is temporal patch. fix ANTLR grammar file
final int correctToLine = declarationUsage.getToLine();
final int correctToColumn = declarationUsage.getToColumn();
declarationStatement.setFromLine(fromLine);
declarationStatement.setFromColumn(fromColumn);
declarationStatement.setToLine(correctToLine);
declarationStatement.setToColumn(correctToColumn);
final UnresolvedLocalSpaceInfo<? extends LocalSpaceInfo> currentLocal = this.buildDataManager
.getCurrentLocalSpace();
if (null != currentLocal) {
currentLocal.addStatement(declarationStatement);
}
return declarationStatement;
}
| private UnresolvedVariableDeclarationStatementInfo buildVariableDeclarationStatement(
final UnresolvedLocalVariableUsageInfo declarationUsage,
final UnresolvedExpressionInfo<? extends ExpressionInfo> initializerExpression,
final int fromLine, final int fromColumn, final int toLine, final int toColumn) {
final UnresolvedVariableDeclarationStatementInfo declarationStatement = new UnresolvedVariableDeclarationStatementInfo(
declarationUsage, initializerExpression);
declarationStatement.setOuterUnit(this.buildDataManager.getCurrentUnit());
// FIXME: this is temporal patch. fix ANTLR grammar file
int correctToLine = declarationUsage.getToLine();
int correctToColumn = declarationUsage.getToColumn();
if (initializerExpression != null){
correctToLine = initializerExpression.getToLine();
correctToColumn= initializerExpression.getToColumn();
}
declarationStatement.setFromLine(fromLine);
declarationStatement.setFromColumn(fromColumn);
declarationStatement.setToLine(correctToLine);
declarationStatement.setToColumn(correctToColumn);
final UnresolvedLocalSpaceInfo<? extends LocalSpaceInfo> currentLocal = this.buildDataManager
.getCurrentLocalSpace();
if (null != currentLocal) {
currentLocal.addStatement(declarationStatement);
}
return declarationStatement;
}
|
diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/namepath/GlobalNameMapper.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/namepath/GlobalNameMapper.java
index 6e81cc7fcc..2c0e6682bf 100644
--- a/oak-core/src/main/java/org/apache/jackrabbit/oak/namepath/GlobalNameMapper.java
+++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/namepath/GlobalNameMapper.java
@@ -1,89 +1,91 @@
/*
* 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.jackrabbit.oak.namepath;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Map;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
/**
* Name mapper with no local prefix remappings. URI to prefix mappings
* are read from the repository when needed.
*/
public abstract class GlobalNameMapper implements NameMapper {
@Override @Nonnull
public String getJcrName(@Nonnull String oakName) {
checkNotNull(oakName);
checkArgument(!oakName.startsWith(":")); // hidden name
checkArgument(!oakName.startsWith("{")); // expanded name
return oakName;
}
@Override @CheckForNull
public String getOakName(@Nonnull String jcrName) {
if (jcrName.startsWith("{")) {
return getOakNameFromExpanded(jcrName);
}
return jcrName;
}
@Override
public boolean hasSessionLocalMappings() {
return false;
}
@CheckForNull
protected String getOakNameFromExpanded(String expandedName) {
checkArgument(expandedName.startsWith("{"));
int brace = expandedName.indexOf('}', 1);
if (brace > 0) {
String uri = expandedName.substring(1, brace);
if (uri.isEmpty()) {
return expandedName.substring(2); // special case: {}name
} else if (uri.indexOf(':') != -1) {
// It's an expanded name, look up the namespace prefix
String oakPrefix = getOakPrefixOrNull(uri);
if (oakPrefix != null) {
return oakPrefix + ':' + expandedName.substring(brace + 1);
+ } else {
+ return null; // no matching namespace prefix
}
}
}
- return null; // invalid or unmapped name
+ return expandedName; // not an expanded name
}
protected abstract Map<String, String> getNamespaceMap();
@CheckForNull
protected String getOakPrefixOrNull(String uri) {
Map<String, String> namespaces = getNamespaceMap();
for (Map.Entry<String, String> entry : namespaces.entrySet()) {
if (uri.equals(entry.getValue())) {
return entry.getKey();
}
}
return null;
}
}
| false | true | protected String getOakNameFromExpanded(String expandedName) {
checkArgument(expandedName.startsWith("{"));
int brace = expandedName.indexOf('}', 1);
if (brace > 0) {
String uri = expandedName.substring(1, brace);
if (uri.isEmpty()) {
return expandedName.substring(2); // special case: {}name
} else if (uri.indexOf(':') != -1) {
// It's an expanded name, look up the namespace prefix
String oakPrefix = getOakPrefixOrNull(uri);
if (oakPrefix != null) {
return oakPrefix + ':' + expandedName.substring(brace + 1);
}
}
}
return null; // invalid or unmapped name
}
| protected String getOakNameFromExpanded(String expandedName) {
checkArgument(expandedName.startsWith("{"));
int brace = expandedName.indexOf('}', 1);
if (brace > 0) {
String uri = expandedName.substring(1, brace);
if (uri.isEmpty()) {
return expandedName.substring(2); // special case: {}name
} else if (uri.indexOf(':') != -1) {
// It's an expanded name, look up the namespace prefix
String oakPrefix = getOakPrefixOrNull(uri);
if (oakPrefix != null) {
return oakPrefix + ':' + expandedName.substring(brace + 1);
} else {
return null; // no matching namespace prefix
}
}
}
return expandedName; // not an expanded name
}
|
diff --git a/modules/maven-plugin/src/main/java/org/cipango/plugin/CipangoPluginSipAppContext.java b/modules/maven-plugin/src/main/java/org/cipango/plugin/CipangoPluginSipAppContext.java
index 3e2bb83..8a4f671 100644
--- a/modules/maven-plugin/src/main/java/org/cipango/plugin/CipangoPluginSipAppContext.java
+++ b/modules/maven-plugin/src/main/java/org/cipango/plugin/CipangoPluginSipAppContext.java
@@ -1,115 +1,119 @@
package org.cipango.plugin;
import java.io.File;
import java.util.List;
import org.cipango.sipapp.SipAppContext;
import org.mortbay.jetty.plus.webapp.EnvConfiguration;
import org.mortbay.jetty.webapp.Configuration;
import org.mortbay.util.LazyList;
public class CipangoPluginSipAppContext extends SipAppContext
{
private List<File> classpathFiles;
private File jettyEnvXmlFile;
private File webXmlFile;
private boolean annotationsEnabled = true;
private String[] configs =
new String[]{
"org.mortbay.jetty.webapp.WebInfConfiguration",
"org.mortbay.jetty.plus.webapp.EnvConfiguration",
"org.mortbay.jetty.webapp.WebXmlConfiguration",
"org.cipango.plugin.CipangoMavenConfiguration",
"org.mortbay.jetty.webapp.JettyWebXmlConfiguration",
"org.mortbay.jetty.webapp.TagLibConfiguration"
};
public CipangoPluginSipAppContext()
{
super();
setConfigurationClasses(configs);
}
public void addConfiguration(String configuration)
{
if (isRunning())
throw new IllegalStateException("Running");
configs = (String[]) LazyList.addToArray(configs, configuration, String.class);
setConfigurationClasses(configs);
}
public void setClassPathFiles(List<File> classpathFiles)
{
this.classpathFiles = classpathFiles;
}
public List<File> getClassPathFiles()
{
return this.classpathFiles;
}
public void setWebXmlFile(File webXmlFile)
{
this.webXmlFile = webXmlFile;
}
public File getWebXmlFile()
{
return this.webXmlFile;
}
public void setJettyEnvXmlFile (File jettyEnvXmlFile)
{
this.jettyEnvXmlFile = jettyEnvXmlFile;
}
public File getJettyEnvXmlFile()
{
return this.jettyEnvXmlFile;
}
@SuppressWarnings("deprecation")
public void configure () throws Exception
{
loadConfigurations();
Configuration[] configurations = getConfigurations();
for (int i = 0; i < configurations.length; i++)
{
if (configurations[i] instanceof CipangoMavenConfiguration)
- ((CipangoMavenConfiguration) configurations[i]).setClassPathConfiguration(classpathFiles);
+ {
+ CipangoMavenConfiguration configuration = (CipangoMavenConfiguration) configurations[i];
+ configuration.setClassPathConfiguration(classpathFiles);
+ configuration.setAnnotationsEnabled(annotationsEnabled);
+ }
if (this.jettyEnvXmlFile != null && configurations[i] instanceof EnvConfiguration)
((EnvConfiguration) configurations[i]).setJettyEnvXml(this.jettyEnvXmlFile.toURL());
}
}
public void doStart () throws Exception
{
setShutdown(false);
super.doStart();
}
public void doStop () throws Exception
{
setShutdown(true);
//just wait a little while to ensure no requests are still being processed
Thread.sleep(500L);
super.doStop();
}
public boolean isAnnotationsEnabled()
{
return annotationsEnabled;
}
public void setAnnotationsEnabled(boolean annotationsEnabled)
{
this.annotationsEnabled = annotationsEnabled;
}
}
| true | true | public void configure () throws Exception
{
loadConfigurations();
Configuration[] configurations = getConfigurations();
for (int i = 0; i < configurations.length; i++)
{
if (configurations[i] instanceof CipangoMavenConfiguration)
((CipangoMavenConfiguration) configurations[i]).setClassPathConfiguration(classpathFiles);
if (this.jettyEnvXmlFile != null && configurations[i] instanceof EnvConfiguration)
((EnvConfiguration) configurations[i]).setJettyEnvXml(this.jettyEnvXmlFile.toURL());
}
}
| public void configure () throws Exception
{
loadConfigurations();
Configuration[] configurations = getConfigurations();
for (int i = 0; i < configurations.length; i++)
{
if (configurations[i] instanceof CipangoMavenConfiguration)
{
CipangoMavenConfiguration configuration = (CipangoMavenConfiguration) configurations[i];
configuration.setClassPathConfiguration(classpathFiles);
configuration.setAnnotationsEnabled(annotationsEnabled);
}
if (this.jettyEnvXmlFile != null && configurations[i] instanceof EnvConfiguration)
((EnvConfiguration) configurations[i]).setJettyEnvXml(this.jettyEnvXmlFile.toURL());
}
}
|
diff --git a/app/controllers/WebService.java b/app/controllers/WebService.java
index fd4252e..b1a9319 100755
--- a/app/controllers/WebService.java
+++ b/app/controllers/WebService.java
@@ -1,403 +1,403 @@
package controllers;
import static eu.play_project.play_commons.constants.Event.EVENT_ID_SUFFIX;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import models.BoyerMoore;
import models.ModelManager;
import models.PredefinedPatterns;
import models.PutGetClient;
import models.SupportedTopicsXML;
import models.eventstream.EventTopic;
import org.event_processing.events.types.FacebookStatusFeedEvent;
import org.jdom.input.SAXBuilder;
import org.ontoware.rdf2go.exception.ModelRuntimeException;
import org.ontoware.rdf2go.model.Model;
import org.ontoware.rdf2go.model.Statement;
import org.ontoware.rdf2go.model.Syntax;
import org.ontoware.rdf2go.model.node.Variable;
import org.ontoware.rdf2go.model.node.impl.URIImpl;
import org.ontoware.rdf2go.vocabulary.RDF;
import org.petalslink.dsb.notification.client.http.HTTPNotificationProducerRPClient;
import org.petalslink.dsb.notification.client.http.simple.HTTPProducerClient;
import org.petalslink.dsb.notification.client.http.simple.HTTPSubscriptionManagerClient;
import org.petalslink.dsb.notification.commons.NotificationException;
import org.w3c.dom.Document;
import play.Logger;
import play.Play;
import play.mvc.Controller;
import play.mvc.Router;
import play.mvc.Util;
import play.utils.HTML;
import com.ebmwebsourcing.easycommons.xml.XMLHelper;
import com.ebmwebsourcing.wsstar.basefaults.datatypes.impl.impl.WsrfbfModelFactoryImpl;
import com.ebmwebsourcing.wsstar.basenotification.datatypes.impl.impl.WsnbModelFactoryImpl;
import com.ebmwebsourcing.wsstar.resource.datatypes.impl.impl.WsrfrModelFactoryImpl;
import com.ebmwebsourcing.wsstar.resourcelifetime.datatypes.impl.impl.WsrfrlModelFactoryImpl;
import com.ebmwebsourcing.wsstar.resourceproperties.datatypes.impl.impl.WsrfrpModelFactoryImpl;
import com.ebmwebsourcing.wsstar.topics.datatypes.api.WstopConstants;
import com.ebmwebsourcing.wsstar.topics.datatypes.impl.impl.WstopModelFactoryImpl;
import com.ebmwebsourcing.wsstar.wsnb.services.INotificationProducerRP;
import com.ebmwebsourcing.wsstar.wsnb.services.impl.util.Wsnb4ServUtils;
import com.hp.hpl.jena.query.QuerySolution;
import eu.play_project.play_commons.constants.Constants;
import eu.play_project.play_commons.constants.Stream;
import eu.play_project.play_commons.eventformat.EventFormatHelpers;
import eu.play_project.play_commons.eventtypes.EventHelpers;
import eu.play_project.play_eventadapter.AbstractReceiver;
import eu.play_project.play_platformservices.api.QueryDispatchApi;
import fr.inria.eventcloud.api.responses.SparqlSelectResponse;
import fr.inria.eventcloud.api.wrappers.ResultSetWrapper;
/**
* The WebService controller is in charge of SOAP connection with the DSB.
*
* @author Alexandre Bourdin
*/
public class WebService extends Controller {
public static String DSB_RESOURCE_SERVICE = Constants.getProperties().getProperty("dsb.notify.endpoint");
public static String EC_PUTGET_SERVICE = Constants.getProperties().getProperty(
"eventcloud.default.putget.endpoint");
private static AbstractReceiver receiver = new AbstractReceiver() {};
static {
Wsnb4ServUtils.initModelFactories(new WsrfbfModelFactoryImpl(), new WsrfrModelFactoryImpl(),
new WsrfrlModelFactoryImpl(), new WsrfrpModelFactoryImpl(), new WstopModelFactoryImpl(),
new WsnbModelFactoryImpl());
}
/**
* SOAP endpoint to receive WS-Notifications from the DSB.
*
* @param topicId
* : necessary to have a unique endpoint for each topic.
*/
public static void soapNotifEndPoint(String topicId) {
String eventTitle;
String eventText;
String notifyMessage;
// A trick to read a Stream into to String:
try {
notifyMessage = new java.util.Scanner(request.body).useDelimiter("\\A").next();
} catch (java.util.NoSuchElementException e) {
notifyMessage = "";
}
- // Print some event to debug android output:
- if (ModelManager.get().getTopicById(topicId).getId().equals("s_FacebookCepResults")) {
- Logger.info(notifyMessage);
- }
+// // Print some event to debug android output:
+// if (ModelManager.get().getTopicById(topicId).getId().equals("s_FacebookCepResults")) {
+// Logger.info(notifyMessage);
+// }
Model rdf;
try {
/*
* Deal with RDF events:
*/
rdf = receiver.parseRdf(notifyMessage);
// If we found RDF
Iterator<Statement> it = rdf.findStatements(Variable.ANY, RDF.type,
Variable.ANY);
if (it.hasNext()) {
Statement stat = it.next();
eventTitle = stat.getObject().asURI().asJavaURI().getPath();
eventTitle = eventTitle.substring(eventTitle.lastIndexOf("/") + 1);
} else {
eventTitle = "RDF Event";
}
eventText = HTML.htmlEscape(rdf.serialize(Syntax.Turtle)).replaceAll("\n", "<br />").replaceAll("\\s{4}", " ");
ModelManager
.get()
.getTopicById(topicId)
.multicast(new models.eventstream.Event(eventTitle, eventText));
} catch (Exception e) {
/*
* Deal with non-RDF events:
*/
eventTitle = "Event";
eventText = HTML.htmlEscape(EventFormatHelpers.unwrapFromNativeMessageElement(notifyMessage)).replaceAll("\n", "<br />").replaceAll("\\s{4}", " ");
ModelManager
.get()
.getTopicById(topicId)
.multicast(
new models.eventstream.Event(eventTitle,
eventText));
}
}
/**
* Sends a request to the DSB to get the list of supported topics
*/
@Util
public static ArrayList<EventTopic> getSupportedTopics() {
Logger.info("Getting topics from DSB at %s", DSB_RESOURCE_SERVICE);
INotificationProducerRP resourceClient = new HTTPNotificationProducerRPClient(DSB_RESOURCE_SERVICE);
ArrayList<EventTopic> topics = new ArrayList<EventTopic>();
try {
QName qname = WstopConstants.TOPIC_SET_QNAME;
com.ebmwebsourcing.wsstar.resourceproperties.datatypes.api.abstraction.GetResourcePropertyResponse response = resourceClient
.getResourceProperty(qname);
Document dom = Wsnb4ServUtils.getWsrfrpWriter().writeGetResourcePropertyResponseAsDOM(response);
String topicsString = XMLHelper.createStringFromDOMDocument(dom);
Logger.info("TOPICS STRING: " + topicsString);
SAXBuilder sxb = new SAXBuilder();
org.jdom.Document xml = new org.jdom.Document();
org.jdom.Element root = null;
xml = sxb.build(new StringReader(topicsString));
root = xml.getRootElement();
SupportedTopicsXML.parseXMLTree(topics, root, "");
} catch (Exception e) {
Logger.warn(e, "A problem occurred while fetching the list of available topics from the DSB. Continuing with empty set of topics.");
}
return topics;
}
/**
* Subscription action, forwards the subscription to the DSB
*
* @param et
*/
@Util
public static int subscribe(EventTopic et) {
Logger.info("Subscribing to topic '%s%s' at broker '%s'", et.uri, et.name, DSB_RESOURCE_SERVICE);
HTTPProducerClient client = new HTTPProducerClient(DSB_RESOURCE_SERVICE);
QName topic = new QName(et.uri, et.name, et.namespace);
Map params = new HashMap<String, Object>();
params.put("topicId", et.getId());
String notificationsEndPoint = Router.getFullUrl("WebService.soapNotifEndPoint", params);
try {
et.subscriptionID = client.subscribe(topic, notificationsEndPoint);
et.alreadySubscribedDSB = true;
} catch (NotificationException e) {
e.printStackTrace();
}
return 1;
}
/**
* Unsubscription action, forwards the unsubscription to the DSB
*
* @param et
*/
@Util
public static int unsubscribe(EventTopic et) {
HTTPSubscriptionManagerClient subscriptionManagerClient = new HTTPSubscriptionManagerClient(
DSB_RESOURCE_SERVICE);
try {
subscriptionManagerClient.unsubscribe(et.subscriptionID);
et.alreadySubscribedDSB = false;
} catch (NotificationException e) {
e.printStackTrace();
return 0;
}
return 1;
}
/**
* Retreives historical events for a given topic
*
* @param et
* @return
*/
@Util
public static ArrayList<models.eventstream.Event> getHistorical(EventTopic et) {
ArrayList<models.eventstream.Event> events = new ArrayList<models.eventstream.Event>();
PutGetClient pgc = new PutGetClient(EC_PUTGET_SERVICE);
SparqlSelectResponse response = pgc
.executeSparqlSelect("SELECT ?g ?s ?p ?o WHERE { GRAPH ?g { <http://eventcloud.inria.fr/replace/me/with/a/correct/namespace/"
+ et.namespace + ":" + et.name + "> ?p ?o } } LIMIT 30");
String title = "-";
String content = "";
ResultSetWrapper result = response.getResult();
while (result.hasNext()) {
QuerySolution qs = result.next();
String predicate = qs.get("p").toString();
String object = qs.get("o").toString();
if (BoyerMoore.match("Topic", predicate).size() > 0) {
title = object;
} else {
content = et.namespace + ":" + et.name + " : " + predicate + " : " + object + "<br/>";
}
events.add(new models.eventstream.Event(title, content));
}
ArrayList<models.eventstream.Event> temp = new ArrayList<models.eventstream.Event>();
for (int i = 0; i < events.size(); i++) {
temp.add(events.get(events.size() - i - 1));
}
return temp;
}
@Util
public static boolean sendTokenPatternQuery(String token, String eventtopic) {
String defaultQueryString = PredefinedPatterns.getPattern("play-epsparql-m12-jeans-example-query.eprq");
String queryString = defaultQueryString.replaceAll("\"JEANS\"", "\"" + token + "\"");
URL wsdl = null;
try {
wsdl = new URL("http://demo.play-project.eu:8085/play/QueryDispatchApi?wsdl");
} catch (MalformedURLException e) {
e.printStackTrace();
}
QName serviceName = new QName("http://play_platformservices.play_project.eu/", "QueryDispatchApi");
Service service = Service.create(wsdl, serviceName);
QueryDispatchApi queryDispatchApi = service.getPort(QueryDispatchApi.class);
try {
String s = queryDispatchApi.registerQuery("patternId_" + Math.random(), queryString, eventtopic);
Logger.info(s);
} catch (Exception e) {
Logger.error(e.toString());
return false;
}
return true;
}
public static Boolean sendFullPatternQuery(String queryString, String eventtopic) throws com.hp.hpl.jena.query.QueryParseException{
URL wsdl = null;
try {
wsdl = new URL("http://demo.play-project.eu:8085/play/QueryDispatchApi?wsdl");
} catch (MalformedURLException e) {
e.printStackTrace();
}
QName serviceName = new QName("http://play_platformservices.play_project.eu/", "QueryDispatchApi");
Service service = Service.create(wsdl, serviceName);
QueryDispatchApi queryDispatchApi = service
.getPort(eu.play_project.play_platformservices.api.QueryDispatchApi.class);
String s = queryDispatchApi.registerQuery("patternId_" + Math.random(), queryString, eventtopic);
Logger.info(s);
return true;
}
/**
* Notify action triggered by buttons on the web interface Generates a
* Facebook status event event and sends it to the DSB
*/
public static void testFacebookStatusFeedEvent() throws ModelRuntimeException, IOException {
String eventId = Stream.FacebookStatusFeed.getUri() + new SecureRandom().nextLong();
FacebookStatusFeedEvent event = new FacebookStatusFeedEvent(EventHelpers.createEmptyModel(eventId),
eventId + EVENT_ID_SUFFIX, true);
event.setName("Roland Stühmer");
event.setId("100000058455726");
event.setLink(new URIImpl("http://graph.facebook.com/roland.stuehmer#"));
event.setStatus("I bought some JEANS this morning");
event.setUserLocation("Karlsruhe, Germany");
event.setEndTime(Calendar.getInstance());
event.setStream(new URIImpl(Stream.FacebookStatusFeed.getUri()));
event.getModel().writeTo(System.out, Syntax.Turtle);
System.out.println();
}
/**
* Puts the content of a file on an InputStream
*
* @param file
* @return
*/
@Util
private static InputStream inputStreamFrom(String file) {
InputStream is = null;
if (file != null) {
try {
is = new FileInputStream(Play.getFile(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
return is;
}
@Util
private static URI generateRandomUri() {
String legalChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
StringBuilder result = new StringBuilder("http://www.inria.fr/");
SecureRandom random = new SecureRandom();
for (int i = 0; i < 20; i++) {
result.append(random.nextInt(legalChars.length()));
}
try {
return new URI(result.toString());
} catch (URISyntaxException e) {
e.printStackTrace();
return null;
}
}
private String getSparqlQuerys(String queryFile){
try {
InputStream is = this.getClass().getClassLoader().getResourceAsStream(queryFile);
BufferedReader br =new BufferedReader(new InputStreamReader(is));
StringBuffer sb = new StringBuffer();
String line;
while (null != (line = br.readLine())) {
sb.append(line);
}
//System.out.println(sb.toString());
br.close();
is.close();
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
| true | true | public static void soapNotifEndPoint(String topicId) {
String eventTitle;
String eventText;
String notifyMessage;
// A trick to read a Stream into to String:
try {
notifyMessage = new java.util.Scanner(request.body).useDelimiter("\\A").next();
} catch (java.util.NoSuchElementException e) {
notifyMessage = "";
}
// Print some event to debug android output:
if (ModelManager.get().getTopicById(topicId).getId().equals("s_FacebookCepResults")) {
Logger.info(notifyMessage);
}
Model rdf;
try {
/*
* Deal with RDF events:
*/
rdf = receiver.parseRdf(notifyMessage);
// If we found RDF
Iterator<Statement> it = rdf.findStatements(Variable.ANY, RDF.type,
Variable.ANY);
if (it.hasNext()) {
Statement stat = it.next();
eventTitle = stat.getObject().asURI().asJavaURI().getPath();
eventTitle = eventTitle.substring(eventTitle.lastIndexOf("/") + 1);
} else {
eventTitle = "RDF Event";
}
eventText = HTML.htmlEscape(rdf.serialize(Syntax.Turtle)).replaceAll("\n", "<br />").replaceAll("\\s{4}", " ");
ModelManager
.get()
.getTopicById(topicId)
.multicast(new models.eventstream.Event(eventTitle, eventText));
} catch (Exception e) {
/*
* Deal with non-RDF events:
*/
eventTitle = "Event";
eventText = HTML.htmlEscape(EventFormatHelpers.unwrapFromNativeMessageElement(notifyMessage)).replaceAll("\n", "<br />").replaceAll("\\s{4}", " ");
ModelManager
.get()
.getTopicById(topicId)
.multicast(
new models.eventstream.Event(eventTitle,
eventText));
}
}
| public static void soapNotifEndPoint(String topicId) {
String eventTitle;
String eventText;
String notifyMessage;
// A trick to read a Stream into to String:
try {
notifyMessage = new java.util.Scanner(request.body).useDelimiter("\\A").next();
} catch (java.util.NoSuchElementException e) {
notifyMessage = "";
}
// // Print some event to debug android output:
// if (ModelManager.get().getTopicById(topicId).getId().equals("s_FacebookCepResults")) {
// Logger.info(notifyMessage);
// }
Model rdf;
try {
/*
* Deal with RDF events:
*/
rdf = receiver.parseRdf(notifyMessage);
// If we found RDF
Iterator<Statement> it = rdf.findStatements(Variable.ANY, RDF.type,
Variable.ANY);
if (it.hasNext()) {
Statement stat = it.next();
eventTitle = stat.getObject().asURI().asJavaURI().getPath();
eventTitle = eventTitle.substring(eventTitle.lastIndexOf("/") + 1);
} else {
eventTitle = "RDF Event";
}
eventText = HTML.htmlEscape(rdf.serialize(Syntax.Turtle)).replaceAll("\n", "<br />").replaceAll("\\s{4}", " ");
ModelManager
.get()
.getTopicById(topicId)
.multicast(new models.eventstream.Event(eventTitle, eventText));
} catch (Exception e) {
/*
* Deal with non-RDF events:
*/
eventTitle = "Event";
eventText = HTML.htmlEscape(EventFormatHelpers.unwrapFromNativeMessageElement(notifyMessage)).replaceAll("\n", "<br />").replaceAll("\\s{4}", " ");
ModelManager
.get()
.getTopicById(topicId)
.multicast(
new models.eventstream.Event(eventTitle,
eventText));
}
}
|
diff --git a/src/com/nedogeek/holdem/server/HoldemWebSocketHandler.java b/src/com/nedogeek/holdem/server/HoldemWebSocketHandler.java
index b3d3b63..e5b08b8 100644
--- a/src/com/nedogeek/holdem/server/HoldemWebSocketHandler.java
+++ b/src/com/nedogeek/holdem/server/HoldemWebSocketHandler.java
@@ -1,28 +1,29 @@
package com.nedogeek.holdem.server;
import org.eclipse.jetty.websocket.WebSocket;
import org.eclipse.jetty.websocket.WebSocketHandler;
import javax.servlet.http.HttpServletRequest;
/**
* User: Konstantin Demishev
* Date: 13.08.12
* Time: 14:25
*/
public class HoldemWebSocketHandler extends WebSocketHandler {
@Override
public WebSocket doWebSocketConnect(HttpServletRequest request, String protocol) {
String login = request.getParameter("user");
String password = request.getParameter("password");
if(login == null && password == null){
return new HoldemWebSocket();
}else{
- if(RegisterServlet.USER_LIST.containsKey(login) && RegisterServlet.USER_LIST.containsKey(password)){
+ if(RegisterServlet.USER_LIST.containsKey(login) &&
+ RegisterServlet.USER_LIST.get(login).equals(password)){
return new HoldemWebSocket(login);
}
}
return null;
}
}
| true | true | public WebSocket doWebSocketConnect(HttpServletRequest request, String protocol) {
String login = request.getParameter("user");
String password = request.getParameter("password");
if(login == null && password == null){
return new HoldemWebSocket();
}else{
if(RegisterServlet.USER_LIST.containsKey(login) && RegisterServlet.USER_LIST.containsKey(password)){
return new HoldemWebSocket(login);
}
}
return null;
}
| public WebSocket doWebSocketConnect(HttpServletRequest request, String protocol) {
String login = request.getParameter("user");
String password = request.getParameter("password");
if(login == null && password == null){
return new HoldemWebSocket();
}else{
if(RegisterServlet.USER_LIST.containsKey(login) &&
RegisterServlet.USER_LIST.get(login).equals(password)){
return new HoldemWebSocket(login);
}
}
return null;
}
|
diff --git a/src/java/com/stackframe/sarariman/ContactController.java b/src/java/com/stackframe/sarariman/ContactController.java
index 78f204f..4ca8c4f 100644
--- a/src/java/com/stackframe/sarariman/ContactController.java
+++ b/src/java/com/stackframe/sarariman/ContactController.java
@@ -1,118 +1,117 @@
/*
* Copyright (C) 2010-2013 StackFrame, LLC
* This code is licensed under GPLv2.
*/
package com.stackframe.sarariman;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author mcculley
*/
public class ContactController extends HttpServlet {
/**
* Handles the HTTP
* <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Employee user = (Employee)request.getAttribute("user");
if (!user.isAdministrator()) {
response.sendError(401);
return;
}
Sarariman sarariman = (Sarariman)getServletContext().getAttribute("sarariman");
if (request.getParameter("action").equals("create")) {
try {
Connection connection = sarariman.getDataSource().getConnection();
try {
PreparedStatement ps = connection.prepareStatement("INSERT INTO contacts (name, title, email, phone, fax, mobile, street, city, state, zip) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
try {
ps.setString(1, request.getParameter("name"));
ps.setString(2, request.getParameter("title"));
ps.setString(3, request.getParameter("email"));
ps.setString(4, request.getParameter("phone"));
ps.setString(5, request.getParameter("fax"));
ps.setString(6, request.getParameter("mobile"));
ps.setString(7, request.getParameter("street"));
ps.setString(8, request.getParameter("city"));
ps.setString(9, request.getParameter("state"));
ps.setString(10, request.getParameter("zip"));
ps.executeUpdate();
ResultSet rs = ps.getGeneratedKeys();
try {
rs.next();
long id = rs.getLong(1);
response.sendRedirect(String.format("contact?id=%d", id));
} finally {
rs.close();
}
} finally {
ps.close();
}
} finally {
connection.close();
}
} catch (SQLException se) {
throw new ServletException(se);
}
} else {
try {
Connection connection = sarariman.getDataSource().getConnection();
try {
PreparedStatement ps = connection.prepareStatement("UPDATE contacts SET name=?, title=?, email=?, phone=?, fax=?, mobile=?, street=?, city=?, state=?, zip=? WHERE id=?");
long id = Long.parseLong(request.getParameter("id"));
try {
ps.setString(1, request.getParameter("name"));
ps.setString(2, request.getParameter("title"));
ps.setString(3, request.getParameter("email"));
ps.setString(4, request.getParameter("phone"));
ps.setString(5, request.getParameter("fax"));
ps.setString(6, request.getParameter("mobile"));
ps.setString(7, request.getParameter("street"));
ps.setString(8, request.getParameter("city"));
ps.setString(9, request.getParameter("state"));
ps.setString(10, request.getParameter("zip"));
ps.setLong(11, id);
ps.executeUpdate();
response.sendRedirect(String.format("contact?id=%d", id));
} finally {
ps.close();
- connection.close();
}
} finally {
connection.close();
}
} catch (SQLException se) {
throw new ServletException(se);
}
}
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Creates or updates a contact";
}
}
| true | true | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Employee user = (Employee)request.getAttribute("user");
if (!user.isAdministrator()) {
response.sendError(401);
return;
}
Sarariman sarariman = (Sarariman)getServletContext().getAttribute("sarariman");
if (request.getParameter("action").equals("create")) {
try {
Connection connection = sarariman.getDataSource().getConnection();
try {
PreparedStatement ps = connection.prepareStatement("INSERT INTO contacts (name, title, email, phone, fax, mobile, street, city, state, zip) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
try {
ps.setString(1, request.getParameter("name"));
ps.setString(2, request.getParameter("title"));
ps.setString(3, request.getParameter("email"));
ps.setString(4, request.getParameter("phone"));
ps.setString(5, request.getParameter("fax"));
ps.setString(6, request.getParameter("mobile"));
ps.setString(7, request.getParameter("street"));
ps.setString(8, request.getParameter("city"));
ps.setString(9, request.getParameter("state"));
ps.setString(10, request.getParameter("zip"));
ps.executeUpdate();
ResultSet rs = ps.getGeneratedKeys();
try {
rs.next();
long id = rs.getLong(1);
response.sendRedirect(String.format("contact?id=%d", id));
} finally {
rs.close();
}
} finally {
ps.close();
}
} finally {
connection.close();
}
} catch (SQLException se) {
throw new ServletException(se);
}
} else {
try {
Connection connection = sarariman.getDataSource().getConnection();
try {
PreparedStatement ps = connection.prepareStatement("UPDATE contacts SET name=?, title=?, email=?, phone=?, fax=?, mobile=?, street=?, city=?, state=?, zip=? WHERE id=?");
long id = Long.parseLong(request.getParameter("id"));
try {
ps.setString(1, request.getParameter("name"));
ps.setString(2, request.getParameter("title"));
ps.setString(3, request.getParameter("email"));
ps.setString(4, request.getParameter("phone"));
ps.setString(5, request.getParameter("fax"));
ps.setString(6, request.getParameter("mobile"));
ps.setString(7, request.getParameter("street"));
ps.setString(8, request.getParameter("city"));
ps.setString(9, request.getParameter("state"));
ps.setString(10, request.getParameter("zip"));
ps.setLong(11, id);
ps.executeUpdate();
response.sendRedirect(String.format("contact?id=%d", id));
} finally {
ps.close();
connection.close();
}
} finally {
connection.close();
}
} catch (SQLException se) {
throw new ServletException(se);
}
}
}
| protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Employee user = (Employee)request.getAttribute("user");
if (!user.isAdministrator()) {
response.sendError(401);
return;
}
Sarariman sarariman = (Sarariman)getServletContext().getAttribute("sarariman");
if (request.getParameter("action").equals("create")) {
try {
Connection connection = sarariman.getDataSource().getConnection();
try {
PreparedStatement ps = connection.prepareStatement("INSERT INTO contacts (name, title, email, phone, fax, mobile, street, city, state, zip) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
try {
ps.setString(1, request.getParameter("name"));
ps.setString(2, request.getParameter("title"));
ps.setString(3, request.getParameter("email"));
ps.setString(4, request.getParameter("phone"));
ps.setString(5, request.getParameter("fax"));
ps.setString(6, request.getParameter("mobile"));
ps.setString(7, request.getParameter("street"));
ps.setString(8, request.getParameter("city"));
ps.setString(9, request.getParameter("state"));
ps.setString(10, request.getParameter("zip"));
ps.executeUpdate();
ResultSet rs = ps.getGeneratedKeys();
try {
rs.next();
long id = rs.getLong(1);
response.sendRedirect(String.format("contact?id=%d", id));
} finally {
rs.close();
}
} finally {
ps.close();
}
} finally {
connection.close();
}
} catch (SQLException se) {
throw new ServletException(se);
}
} else {
try {
Connection connection = sarariman.getDataSource().getConnection();
try {
PreparedStatement ps = connection.prepareStatement("UPDATE contacts SET name=?, title=?, email=?, phone=?, fax=?, mobile=?, street=?, city=?, state=?, zip=? WHERE id=?");
long id = Long.parseLong(request.getParameter("id"));
try {
ps.setString(1, request.getParameter("name"));
ps.setString(2, request.getParameter("title"));
ps.setString(3, request.getParameter("email"));
ps.setString(4, request.getParameter("phone"));
ps.setString(5, request.getParameter("fax"));
ps.setString(6, request.getParameter("mobile"));
ps.setString(7, request.getParameter("street"));
ps.setString(8, request.getParameter("city"));
ps.setString(9, request.getParameter("state"));
ps.setString(10, request.getParameter("zip"));
ps.setLong(11, id);
ps.executeUpdate();
response.sendRedirect(String.format("contact?id=%d", id));
} finally {
ps.close();
}
} finally {
connection.close();
}
} catch (SQLException se) {
throw new ServletException(se);
}
}
}
|
diff --git a/src/org/liberty/android/fantastischmemo/XMLConverter.java b/src/org/liberty/android/fantastischmemo/XMLConverter.java
index d2a422b5..86bbfa3b 100644
--- a/src/org/liberty/android/fantastischmemo/XMLConverter.java
+++ b/src/org/liberty/android/fantastischmemo/XMLConverter.java
@@ -1,282 +1,282 @@
/*
Copyright (C) 2010 Haowen Ning
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.liberty.android.fantastischmemo;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import android.database.SQLException;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Date;
import java.util.TimeZone;
import java.util.Calendar;
import java.text.SimpleDateFormat;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import android.content.Context;
import android.util.Log;
public class XMLConverter extends org.xml.sax.helpers.DefaultHandler{
private Context mContext;
private URL mXMLUrl;
private SAXParserFactory spf;
private SAXParser sp;
private XMLReader xr;
private String fileName;
private String filePath;
private long timeOfStart = 0L;
public Locator mLocator;
private List<String> questionList;
private List<String> answerList;
private List<String> categoryList;
private List<String> datelearnList;
private List<Integer> intervalList;
private List<Double> easinessList;
private List<Integer> gradeList;
private List<Integer> lapsesList;
private List<Integer> acrpList;
private List<Integer> rtrpList;
private List<Integer> arslList;
private List<Integer> rrslList;
private boolean inItem = false;
private boolean inQuestion = false;
private boolean inAnser = false;
private boolean inCategory = false;
private boolean isInv = false;
private boolean isReadCharacters = false;
private StringBuffer characterBuf;
private final long MILLSECS_PER_DAY = 24 * 60 * 60 * 1000;
private final String TAG = "org.liberty.android.fantastischmemo.XMLConverter";
public XMLConverter(Context context, String filePath, String fileName) throws MalformedURLException, SAXException, ParserConfigurationException, IOException{
mContext = context;
this.filePath = filePath;
this.fileName = fileName;
mXMLUrl = new URL("file:///" + filePath + "/" + fileName);
questionList = new LinkedList<String>();
answerList = new LinkedList<String>();
categoryList = new LinkedList<String>();
datelearnList = new LinkedList<String>();
intervalList = new LinkedList<Integer>();
easinessList = new LinkedList<Double>();
gradeList = new LinkedList<Integer>();
lapsesList = new LinkedList<Integer>();
acrpList = new LinkedList<Integer>();
rtrpList = new LinkedList<Integer>();
arslList = new LinkedList<Integer>();
rrslList = new LinkedList<Integer>();
spf = SAXParserFactory.newInstance();
sp = spf.newSAXParser();
xr = sp.getXMLReader();
xr.setContentHandler(this);
xr.parse(new InputSource(mXMLUrl.openStream()));
}
public void outputTabFile() throws IOException{
File file = new File(filePath + "/" + fileName);
file.createNewFile();
FileOutputStream fileOutStream = new FileOutputStream(file);
BufferedOutputStream buf = new BufferedOutputStream(fileOutStream, 8192);
OutputStreamWriter outStream = new OutputStreamWriter(buf);
ListIterator<String> liq = questionList.listIterator();
ListIterator<String> lia = answerList.listIterator();
ListIterator<String> lic = categoryList.listIterator();
while(liq.hasNext() && lia.hasNext()){
outStream.write("Q: " + liq.next() + "\n");
outStream.write("A: " + lia.next() + "\n");
}
outStream.close();
buf.close();
fileOutStream.close();
}
public void outputDB() throws IOException, SQLException{
String name = fileName.replaceAll(".xml", ".db");
DatabaseHelper.createEmptyDatabase(filePath, name);
DatabaseHelper dbHelper = new DatabaseHelper(mContext, filePath, name);
Log.v(TAG, "Counts: " + questionList.size() + " " + easinessList.size() + " " + acrpList.size() + " " + arslList.size());
dbHelper.createDatabaseFromList(questionList, answerList, categoryList, datelearnList, intervalList, easinessList, gradeList, lapsesList, acrpList, rtrpList, arslList, rrslList);
dbHelper.close();
}
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException{
if(localName.equals("mnemosyne")){
try{
timeOfStart = Long.parseLong(atts.getValue("time_of_start"));
/* Convert to local time */
- //Calendar nc = Calendar.getInstance();
- //TimeZone tz = nc.getTimeZone();
- //int offset = tz.getOffset(timeOfStart);
- //timeOfStart -= offset;
+ Calendar nc = Calendar.getInstance();
+ TimeZone tz = nc.getTimeZone();
+ int offset = tz.getOffset(timeOfStart);
+ timeOfStart -= offset;
Log.v(TAG, "Time of start: " + timeOfStart);
}
catch(Exception e){
Log.e(TAG, "parse time_of_start error", e);
}
}
if(localName.equals("item")){
this.inItem = true;
String idAttr = atts.getValue("id");
if(idAttr.endsWith("inv")){
this.isInv = true;
}
String grAttr = atts.getValue("gr");
if(grAttr != null){
gradeList.add(Integer.parseInt(grAttr));
}
String eAttr = atts.getValue("e");
if(eAttr != null){
easinessList.add(Double.parseDouble(eAttr));
}
String acrpAttr = atts.getValue("ac_rp");
String uAttr = atts.getValue("u");
String rtrpAttr = atts.getValue("rt_rp");
if(rtrpAttr != null){
rtrpList.add(Integer.valueOf(rtrpAttr));
}
if(acrpAttr != null){
int acrp = Integer.parseInt(acrpAttr);
if(uAttr != null){
if(Integer.parseInt(uAttr) == 1){
acrp = 0;
}
}
if(Integer.valueOf(rtrpAttr) != 0 && acrp == 0){
/* This is a workaround for the malformed
* XML file.
*/
acrp = Integer.valueOf(rtrpAttr) / 2 + 1;
}
acrpList.add(new Integer(acrp));
}
String lpsAttr = atts.getValue("lps");
if(lpsAttr != null){
lapsesList.add(Integer.valueOf(lpsAttr));
}
String acqrplAttr = atts.getValue("ac_rp_l");
if(acqrplAttr != null){
arslList.add(Integer.valueOf(acqrplAttr));
}
String rtrplAttr = atts.getValue("rt_rp_l");
if(rtrplAttr != null){
rrslList.add(Integer.valueOf(rtrplAttr));
}
String lrpAttr = atts.getValue("l_rp");
if(lrpAttr != null && timeOfStart != 0L){
long lrp = Math.round(Double.parseDouble(lrpAttr));
Date date = new Date(timeOfStart * 1000L + lrp * MILLSECS_PER_DAY);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String strDate = formatter.format(date);
datelearnList.add(strDate);
}
String nrpAttr = atts.getValue("n_rp");
if(nrpAttr != null && lrpAttr != null){
long lrp = Math.round(Double.parseDouble(lrpAttr));
long nrp = Math.round(Double.parseDouble(nrpAttr));
intervalList.add(new Integer((int)(nrp - lrp)));
}
}
characterBuf = new StringBuffer();
if(localName.equals("cat")){
this.inCategory = true;
}
if(localName.equals("Q") || localName.equals("Question")){
this.inQuestion = true;
}
if(localName.equals("A") || localName.equals("Answer")){
this.inAnser = true;
}
}
public void endElement(String namespaceURI, String localName, String qName) throws SAXException{
if(localName.equals("item")){
this.inItem = false;
this.isInv = false;
}
if(localName.equals("cat")){
categoryList.add(characterBuf.toString());
this.inCategory = false;
}
if(localName.equals("Q")|| localName.equals("Question")){
questionList.add(characterBuf.toString());
this.inQuestion = false;
}
if(localName.equals("A")|| localName.equals("Answer")){
answerList.add(characterBuf.toString());
this.inAnser = false;
}
}
public void setDocumentLocator(Locator locator){
mLocator = locator;
}
public void characters(char ch[], int start, int length){
characterBuf.append(ch, start, length);
}
public void startDocument() throws SAXException{
}
public void endDocument() throws SAXException{
}
}
| true | true | public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException{
if(localName.equals("mnemosyne")){
try{
timeOfStart = Long.parseLong(atts.getValue("time_of_start"));
/* Convert to local time */
//Calendar nc = Calendar.getInstance();
//TimeZone tz = nc.getTimeZone();
//int offset = tz.getOffset(timeOfStart);
//timeOfStart -= offset;
Log.v(TAG, "Time of start: " + timeOfStart);
}
catch(Exception e){
Log.e(TAG, "parse time_of_start error", e);
}
}
if(localName.equals("item")){
this.inItem = true;
String idAttr = atts.getValue("id");
if(idAttr.endsWith("inv")){
this.isInv = true;
}
String grAttr = atts.getValue("gr");
if(grAttr != null){
gradeList.add(Integer.parseInt(grAttr));
}
String eAttr = atts.getValue("e");
if(eAttr != null){
easinessList.add(Double.parseDouble(eAttr));
}
String acrpAttr = atts.getValue("ac_rp");
String uAttr = atts.getValue("u");
String rtrpAttr = atts.getValue("rt_rp");
if(rtrpAttr != null){
rtrpList.add(Integer.valueOf(rtrpAttr));
}
if(acrpAttr != null){
int acrp = Integer.parseInt(acrpAttr);
if(uAttr != null){
if(Integer.parseInt(uAttr) == 1){
acrp = 0;
}
}
if(Integer.valueOf(rtrpAttr) != 0 && acrp == 0){
/* This is a workaround for the malformed
* XML file.
*/
acrp = Integer.valueOf(rtrpAttr) / 2 + 1;
}
acrpList.add(new Integer(acrp));
}
String lpsAttr = atts.getValue("lps");
if(lpsAttr != null){
lapsesList.add(Integer.valueOf(lpsAttr));
}
String acqrplAttr = atts.getValue("ac_rp_l");
if(acqrplAttr != null){
arslList.add(Integer.valueOf(acqrplAttr));
}
String rtrplAttr = atts.getValue("rt_rp_l");
if(rtrplAttr != null){
rrslList.add(Integer.valueOf(rtrplAttr));
}
String lrpAttr = atts.getValue("l_rp");
if(lrpAttr != null && timeOfStart != 0L){
long lrp = Math.round(Double.parseDouble(lrpAttr));
Date date = new Date(timeOfStart * 1000L + lrp * MILLSECS_PER_DAY);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String strDate = formatter.format(date);
datelearnList.add(strDate);
}
String nrpAttr = atts.getValue("n_rp");
if(nrpAttr != null && lrpAttr != null){
long lrp = Math.round(Double.parseDouble(lrpAttr));
long nrp = Math.round(Double.parseDouble(nrpAttr));
intervalList.add(new Integer((int)(nrp - lrp)));
}
}
characterBuf = new StringBuffer();
if(localName.equals("cat")){
this.inCategory = true;
}
if(localName.equals("Q") || localName.equals("Question")){
this.inQuestion = true;
}
if(localName.equals("A") || localName.equals("Answer")){
this.inAnser = true;
}
}
| public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException{
if(localName.equals("mnemosyne")){
try{
timeOfStart = Long.parseLong(atts.getValue("time_of_start"));
/* Convert to local time */
Calendar nc = Calendar.getInstance();
TimeZone tz = nc.getTimeZone();
int offset = tz.getOffset(timeOfStart);
timeOfStart -= offset;
Log.v(TAG, "Time of start: " + timeOfStart);
}
catch(Exception e){
Log.e(TAG, "parse time_of_start error", e);
}
}
if(localName.equals("item")){
this.inItem = true;
String idAttr = atts.getValue("id");
if(idAttr.endsWith("inv")){
this.isInv = true;
}
String grAttr = atts.getValue("gr");
if(grAttr != null){
gradeList.add(Integer.parseInt(grAttr));
}
String eAttr = atts.getValue("e");
if(eAttr != null){
easinessList.add(Double.parseDouble(eAttr));
}
String acrpAttr = atts.getValue("ac_rp");
String uAttr = atts.getValue("u");
String rtrpAttr = atts.getValue("rt_rp");
if(rtrpAttr != null){
rtrpList.add(Integer.valueOf(rtrpAttr));
}
if(acrpAttr != null){
int acrp = Integer.parseInt(acrpAttr);
if(uAttr != null){
if(Integer.parseInt(uAttr) == 1){
acrp = 0;
}
}
if(Integer.valueOf(rtrpAttr) != 0 && acrp == 0){
/* This is a workaround for the malformed
* XML file.
*/
acrp = Integer.valueOf(rtrpAttr) / 2 + 1;
}
acrpList.add(new Integer(acrp));
}
String lpsAttr = atts.getValue("lps");
if(lpsAttr != null){
lapsesList.add(Integer.valueOf(lpsAttr));
}
String acqrplAttr = atts.getValue("ac_rp_l");
if(acqrplAttr != null){
arslList.add(Integer.valueOf(acqrplAttr));
}
String rtrplAttr = atts.getValue("rt_rp_l");
if(rtrplAttr != null){
rrslList.add(Integer.valueOf(rtrplAttr));
}
String lrpAttr = atts.getValue("l_rp");
if(lrpAttr != null && timeOfStart != 0L){
long lrp = Math.round(Double.parseDouble(lrpAttr));
Date date = new Date(timeOfStart * 1000L + lrp * MILLSECS_PER_DAY);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String strDate = formatter.format(date);
datelearnList.add(strDate);
}
String nrpAttr = atts.getValue("n_rp");
if(nrpAttr != null && lrpAttr != null){
long lrp = Math.round(Double.parseDouble(lrpAttr));
long nrp = Math.round(Double.parseDouble(nrpAttr));
intervalList.add(new Integer((int)(nrp - lrp)));
}
}
characterBuf = new StringBuffer();
if(localName.equals("cat")){
this.inCategory = true;
}
if(localName.equals("Q") || localName.equals("Question")){
this.inQuestion = true;
}
if(localName.equals("A") || localName.equals("Answer")){
this.inAnser = true;
}
}
|
diff --git a/src/fileserve/cz/vity/freerapid/plugins/services/fileserve/FileserveFilesRunner.java b/src/fileserve/cz/vity/freerapid/plugins/services/fileserve/FileserveFilesRunner.java
index b1d617d5..04d27cd3 100644
--- a/src/fileserve/cz/vity/freerapid/plugins/services/fileserve/FileserveFilesRunner.java
+++ b/src/fileserve/cz/vity/freerapid/plugins/services/fileserve/FileserveFilesRunner.java
@@ -1,159 +1,159 @@
package cz.vity.freerapid.plugins.services.fileserve;
import cz.vity.freerapid.plugins.exceptions.*;
import cz.vity.freerapid.plugins.webclient.AbstractRunner;
import cz.vity.freerapid.plugins.webclient.FileState;
import cz.vity.freerapid.plugins.webclient.MethodBuilder;
import cz.vity.freerapid.plugins.webclient.utils.PlugUtils;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.NameValuePair;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import java.util.regex.Matcher;
/**
* @author RickCL
*/
class FileserveFilesRunner extends AbstractRunner {
private final static Logger logger = Logger.getLogger(FileserveFilesRunner.class.getName());
@Override
public void runCheck() throws Exception {
super.runCheck();
final HttpMethod getMethod = getGetMethod(fileURL);
if (makeRedirectedRequest(getMethod)) {
checkProblems();
checkNameAndSize(getContentAsString());
} else {
checkProblems();
throw new ServiceConnectionProblemException();
}
}
@Override
public void run() throws Exception {
super.run();
HttpMethod getMethod = getGetMethod(fileURL);
if (makeRedirectedRequest(getMethod)) {
checkProblems();
checkNameAndSize(getContentAsString());
Matcher matcher = PlugUtils.matcher("http://(?:www\\.)?fileserve\\.com/[^/]*/(\\w+)", fileURL);
if (!matcher.find()) {
throw new PluginImplementationException("Error parsing download link");
}
final String fileKey = matcher.group(1);
matcher = getMatcherAgainstContent("reCAPTCHA_publickey='([\\w-]*)'");
if (!matcher.find()) {
throw new PluginImplementationException("ReCaptcha key not found");
}
String recaptcha = "http://www.google.com/recaptcha/api/challenge?k=" + matcher.group(1) + "&ajax=1&cachestop=0." + System.currentTimeMillis();
List<NameValuePair> extraHiddenParams = new ArrayList<NameValuePair>();
- matcher = PlugUtils.matcher("<input[^>]+name=\"([^\"]+)\"[^>]+value=\"([^\"]+)\"[^>]*>", getContentAsString().replaceFirst("(?s)^.*?(<input[^>]+id=\"recaptcha_[^\"]+_field\"[^>]*>.*?)<div[^>]+id=\"captchaAreaLabel\"[^>]*>.*$", "$1"));
+ matcher = PlugUtils.matcher("<input[^>]+name=\"([^\"]+)\"[^>]+value=\"([^\"]+)\"[^>]*>", getContentAsString().replaceFirst("(?s)^.*?<div[^>]+id=\"login_area\"[^>]*>(.*?)</table>.*$", "$1"));
while (matcher.find()) {
extraHiddenParams.add(new NameValuePair(matcher.group(1), matcher.group(2)));
}
logger.info("Captcha extra hidden params (" + extraHiddenParams.size() + "): " + extraHiddenParams);
do {
logger.info("Captcha URL: " + recaptcha);
getMethod = getGetMethod(recaptcha);
if (!makeRedirectedRequest(getMethod)) {
throw new ServiceConnectionProblemException();
}
matcher = getMatcherAgainstContent("(?s)challenge\\s*:\\s*'([\\w-]+)'.*?server\\s*:\\s*'([^']+)'");
if (!matcher.find()) {
throw new PluginImplementationException("Error parsing ReCaptcha response");
}
String recaptcha_challenge_field = matcher.group(1);
String captchaImg = matcher.group(2) + "image?c=" + recaptcha_challenge_field;
logger.info("Captcha URL: " + captchaImg);
String captcha = getCaptchaSupport().getCaptcha(captchaImg);
if (captcha == null) {
throw new CaptchaEntryInputMismatchException();
}
MethodBuilder mb = getMethodBuilder()
.setAction("/checkReCaptcha.php")
.setReferer(fileURL)
.setEncodePathAndQuery(true);
for (NameValuePair param : extraHiddenParams) {
mb.setParameter(param.getName(), param.getValue());
}
mb
.setParameter("recaptcha_challenge_field", recaptcha_challenge_field)
.setParameter("recaptcha_response_field", captcha)
.setParameter("recaptcha_shortencode_field", fileKey);
if (!makeRedirectedRequest(mb.toPostMethod())) {
throw new ServiceConnectionProblemException();
}
}
while (!getContentAsString().matches(".*?success\"?\\s*:\\s*1.*?")); // {"success":1} -> OK, {"success":0,"error": ... } -> try again
HttpMethod pMethod = getMethodBuilder().setAction(fileURL).setReferer(fileURL)
.setParameter("downloadLink", "wait")
.toPostMethod();
if (!makeRedirectedRequest(pMethod)) {
throw new ServiceConnectionProblemException();
}
matcher = getMatcherAgainstContent("(\\d+)");
if (!matcher.find()) {
throw new PluginImplementationException("Waiting time not found");
}
downloadTask.sleep(Integer.parseInt(matcher.group(1)) + 1);
pMethod = getMethodBuilder().setAction(fileURL).setReferer(fileURL)
.setParameter("downloadLink", "show")
.toPostMethod();
if (!makeRedirectedRequest(pMethod)) {
throw new ServiceConnectionProblemException();
}
pMethod = getMethodBuilder().setAction(fileURL).setReferer(fileURL).setParameter("download", "normal").toPostMethod();
setFileStreamContentTypes("X-LIGHTTPD-send-file");
if (!tryDownloadAndSaveFile(pMethod)) {
checkProblems();
throw new ServiceConnectionProblemException("Error starting download");
}
} else {
checkProblems();
throw new ServiceConnectionProblemException();
}
}
private void checkNameAndSize(String content) throws ErrorDuringDownloadingException {
PlugUtils.checkName(httpFile, content, "<h1>", "<");
final Matcher size = getMatcherAgainstContent("<strong>\\s*(\\d.+?)\\s*</strong>");
if (!size.find()) {
throw new PluginImplementationException("File size not found");
}
httpFile.setFileSize(PlugUtils.getFileSizeFromString(size.group(1)));
httpFile.setFileState(FileState.CHECKED_AND_EXISTING);
}
private void checkProblems() throws ErrorDuringDownloadingException {
if (getContentAsString().contains("The file could not be found") || getContentAsString().contains("Page not found") || getContentAsString().contains("File not available")) {
throw new URLNotAvailableAnymoreException("File not found");
}
if (getContentAsString().contains("/error.php")) {
throw new ServiceConnectionProblemException("Temporary server issue");
}
Matcher matcher = getMatcherAgainstContent("You (?:have|need) to wait (\\d+) seconds to start another download");
if (matcher.find()) {
throw new YouHaveToWaitException(matcher.group(), Integer.parseInt(matcher.group(1)));
}
}
}
| true | true | public void run() throws Exception {
super.run();
HttpMethod getMethod = getGetMethod(fileURL);
if (makeRedirectedRequest(getMethod)) {
checkProblems();
checkNameAndSize(getContentAsString());
Matcher matcher = PlugUtils.matcher("http://(?:www\\.)?fileserve\\.com/[^/]*/(\\w+)", fileURL);
if (!matcher.find()) {
throw new PluginImplementationException("Error parsing download link");
}
final String fileKey = matcher.group(1);
matcher = getMatcherAgainstContent("reCAPTCHA_publickey='([\\w-]*)'");
if (!matcher.find()) {
throw new PluginImplementationException("ReCaptcha key not found");
}
String recaptcha = "http://www.google.com/recaptcha/api/challenge?k=" + matcher.group(1) + "&ajax=1&cachestop=0." + System.currentTimeMillis();
List<NameValuePair> extraHiddenParams = new ArrayList<NameValuePair>();
matcher = PlugUtils.matcher("<input[^>]+name=\"([^\"]+)\"[^>]+value=\"([^\"]+)\"[^>]*>", getContentAsString().replaceFirst("(?s)^.*?(<input[^>]+id=\"recaptcha_[^\"]+_field\"[^>]*>.*?)<div[^>]+id=\"captchaAreaLabel\"[^>]*>.*$", "$1"));
while (matcher.find()) {
extraHiddenParams.add(new NameValuePair(matcher.group(1), matcher.group(2)));
}
logger.info("Captcha extra hidden params (" + extraHiddenParams.size() + "): " + extraHiddenParams);
do {
logger.info("Captcha URL: " + recaptcha);
getMethod = getGetMethod(recaptcha);
if (!makeRedirectedRequest(getMethod)) {
throw new ServiceConnectionProblemException();
}
matcher = getMatcherAgainstContent("(?s)challenge\\s*:\\s*'([\\w-]+)'.*?server\\s*:\\s*'([^']+)'");
if (!matcher.find()) {
throw new PluginImplementationException("Error parsing ReCaptcha response");
}
String recaptcha_challenge_field = matcher.group(1);
String captchaImg = matcher.group(2) + "image?c=" + recaptcha_challenge_field;
logger.info("Captcha URL: " + captchaImg);
String captcha = getCaptchaSupport().getCaptcha(captchaImg);
if (captcha == null) {
throw new CaptchaEntryInputMismatchException();
}
MethodBuilder mb = getMethodBuilder()
.setAction("/checkReCaptcha.php")
.setReferer(fileURL)
.setEncodePathAndQuery(true);
for (NameValuePair param : extraHiddenParams) {
mb.setParameter(param.getName(), param.getValue());
}
mb
.setParameter("recaptcha_challenge_field", recaptcha_challenge_field)
.setParameter("recaptcha_response_field", captcha)
.setParameter("recaptcha_shortencode_field", fileKey);
if (!makeRedirectedRequest(mb.toPostMethod())) {
throw new ServiceConnectionProblemException();
}
}
while (!getContentAsString().matches(".*?success\"?\\s*:\\s*1.*?")); // {"success":1} -> OK, {"success":0,"error": ... } -> try again
HttpMethod pMethod = getMethodBuilder().setAction(fileURL).setReferer(fileURL)
.setParameter("downloadLink", "wait")
.toPostMethod();
if (!makeRedirectedRequest(pMethod)) {
throw new ServiceConnectionProblemException();
}
matcher = getMatcherAgainstContent("(\\d+)");
if (!matcher.find()) {
throw new PluginImplementationException("Waiting time not found");
}
downloadTask.sleep(Integer.parseInt(matcher.group(1)) + 1);
pMethod = getMethodBuilder().setAction(fileURL).setReferer(fileURL)
.setParameter("downloadLink", "show")
.toPostMethod();
if (!makeRedirectedRequest(pMethod)) {
throw new ServiceConnectionProblemException();
}
pMethod = getMethodBuilder().setAction(fileURL).setReferer(fileURL).setParameter("download", "normal").toPostMethod();
setFileStreamContentTypes("X-LIGHTTPD-send-file");
if (!tryDownloadAndSaveFile(pMethod)) {
checkProblems();
throw new ServiceConnectionProblemException("Error starting download");
}
} else {
| public void run() throws Exception {
super.run();
HttpMethod getMethod = getGetMethod(fileURL);
if (makeRedirectedRequest(getMethod)) {
checkProblems();
checkNameAndSize(getContentAsString());
Matcher matcher = PlugUtils.matcher("http://(?:www\\.)?fileserve\\.com/[^/]*/(\\w+)", fileURL);
if (!matcher.find()) {
throw new PluginImplementationException("Error parsing download link");
}
final String fileKey = matcher.group(1);
matcher = getMatcherAgainstContent("reCAPTCHA_publickey='([\\w-]*)'");
if (!matcher.find()) {
throw new PluginImplementationException("ReCaptcha key not found");
}
String recaptcha = "http://www.google.com/recaptcha/api/challenge?k=" + matcher.group(1) + "&ajax=1&cachestop=0." + System.currentTimeMillis();
List<NameValuePair> extraHiddenParams = new ArrayList<NameValuePair>();
matcher = PlugUtils.matcher("<input[^>]+name=\"([^\"]+)\"[^>]+value=\"([^\"]+)\"[^>]*>", getContentAsString().replaceFirst("(?s)^.*?<div[^>]+id=\"login_area\"[^>]*>(.*?)</table>.*$", "$1"));
while (matcher.find()) {
extraHiddenParams.add(new NameValuePair(matcher.group(1), matcher.group(2)));
}
logger.info("Captcha extra hidden params (" + extraHiddenParams.size() + "): " + extraHiddenParams);
do {
logger.info("Captcha URL: " + recaptcha);
getMethod = getGetMethod(recaptcha);
if (!makeRedirectedRequest(getMethod)) {
throw new ServiceConnectionProblemException();
}
matcher = getMatcherAgainstContent("(?s)challenge\\s*:\\s*'([\\w-]+)'.*?server\\s*:\\s*'([^']+)'");
if (!matcher.find()) {
throw new PluginImplementationException("Error parsing ReCaptcha response");
}
String recaptcha_challenge_field = matcher.group(1);
String captchaImg = matcher.group(2) + "image?c=" + recaptcha_challenge_field;
logger.info("Captcha URL: " + captchaImg);
String captcha = getCaptchaSupport().getCaptcha(captchaImg);
if (captcha == null) {
throw new CaptchaEntryInputMismatchException();
}
MethodBuilder mb = getMethodBuilder()
.setAction("/checkReCaptcha.php")
.setReferer(fileURL)
.setEncodePathAndQuery(true);
for (NameValuePair param : extraHiddenParams) {
mb.setParameter(param.getName(), param.getValue());
}
mb
.setParameter("recaptcha_challenge_field", recaptcha_challenge_field)
.setParameter("recaptcha_response_field", captcha)
.setParameter("recaptcha_shortencode_field", fileKey);
if (!makeRedirectedRequest(mb.toPostMethod())) {
throw new ServiceConnectionProblemException();
}
}
while (!getContentAsString().matches(".*?success\"?\\s*:\\s*1.*?")); // {"success":1} -> OK, {"success":0,"error": ... } -> try again
HttpMethod pMethod = getMethodBuilder().setAction(fileURL).setReferer(fileURL)
.setParameter("downloadLink", "wait")
.toPostMethod();
if (!makeRedirectedRequest(pMethod)) {
throw new ServiceConnectionProblemException();
}
matcher = getMatcherAgainstContent("(\\d+)");
if (!matcher.find()) {
throw new PluginImplementationException("Waiting time not found");
}
downloadTask.sleep(Integer.parseInt(matcher.group(1)) + 1);
pMethod = getMethodBuilder().setAction(fileURL).setReferer(fileURL)
.setParameter("downloadLink", "show")
.toPostMethod();
if (!makeRedirectedRequest(pMethod)) {
throw new ServiceConnectionProblemException();
}
pMethod = getMethodBuilder().setAction(fileURL).setReferer(fileURL).setParameter("download", "normal").toPostMethod();
setFileStreamContentTypes("X-LIGHTTPD-send-file");
if (!tryDownloadAndSaveFile(pMethod)) {
checkProblems();
throw new ServiceConnectionProblemException("Error starting download");
}
} else {
|
diff --git a/VectorString/src/main/java/ini/trakem2/vector/VectorString2D.java b/VectorString/src/main/java/ini/trakem2/vector/VectorString2D.java
index 84cf9865..d2e07233 100644
--- a/VectorString/src/main/java/ini/trakem2/vector/VectorString2D.java
+++ b/VectorString/src/main/java/ini/trakem2/vector/VectorString2D.java
@@ -1,535 +1,535 @@
/**
TrakEM2 plugin for ImageJ(C).
Copyright (C) 2005-2009 Albert Cardona.
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 (http://www.gnu.org/licenses/gpl.txt )
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
You may contact Albert Cardona at acardona at ini.phys.ethz.ch
Institute of Neuroinformatics, University of Zurich / ETH, Switzerland.
**/
package ini.trakem2.vector;
import java.awt.Polygon;
import ij.gui.PolygonRoi;
import ij.io.RoiDecoder;
import ij.measure.Calibration;
/** String of vectors. */
public class VectorString2D implements VectorString {
// all private to the package: accessible from Editions class
private double[] x; // points
private double[] y;
private double[] v_x = null; // vectors, after resampling
private double[] v_y = null;
/** The length of the x,y and v_x, v_y resampled points (the actual arrays may be a bit longer) */
private int length;
/** The point interdistance after resampling. */
private double delta = 0; // the delta used for resampling
/** The Z coordinate of the entire planar curve represented by this VectorString2D. */
private double z;
private boolean closed;
private Calibration cal = null;
/** Construct a new String of Vectors from the given points and desired resampling point interdistance 'delta'. */
public VectorString2D(double[] x, double[] y, double z, boolean closed) throws Exception {
if (!(x.length == y.length)) {
throw new Exception("x and y must be of the same length.");
}
this.length = x.length;
this.x = x;
this.y = y;
this.z = z;
this.closed = closed;
}
/** Does NOT clone the vector arrays, which are initialized to NULL; only the x,y,delta,z. */
public Object clone() {
double[] x2 = new double[length];
double[] y2 = new double[length];
System.arraycopy(x, 0, x2, 0, length);
System.arraycopy(y, 0, y2, 0, length);
try {
return new VectorString2D(x2, y2, z, closed);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public int length() { return length; }
/** If not resampled, returns zero. */
public double getDelta() { return delta; }
public double[] getPoints(final int dim) {
switch (dim) {
case 0: return x;
case 1: return y;
}
return null;
}
public double[] getVectors(final int dim) {
switch (dim) {
case 0: return v_x;
case 1: return v_y;
}
return null;
}
public double getPoint(final int dim, final int i) {
switch (dim) {
case 0: return x[i];
case 1: return y[i];
case 2: return z;
}
return 0;
}
public double getVector(final int dim, final int i) {
switch (dim) {
case 0: return v_x[i];
case 1: return v_y[i];
}
return 0;
}
public boolean isClosed() { return closed; }
public double getAverageDelta() { // equivalent to C's getAndSetAveragePointInterdistance function
double d = 0;
for (int i=x.length -1; i>0; i--) {
d += Math.sqrt( (x[i] - x[i-1])*(x[i] - x[i-1]) + (y[i] - y[i-1])*(y[i] - y[i-1])); // pytagorian rule for 2D
}
return d / x.length;
}
/** Same as resample(delta). */
public void resample(double delta, boolean with_source) {
resample(delta);
}
/** Homogenize the average point interdistance to 'delta'. */ // There are problems with the last point.
public void resample(double delta) {
if (Math.abs(delta - this.delta) < 0.0000001) {
// delta is the same
return;
}
this.delta = delta; // store for checking purposes
this.resample();
}
static private class Sequence {
protected int i = -1;
protected int size;
public Sequence(final int size) {
this.size = size;
}
int next() {
++i;
return i == size ? -1 : i;
}
void setPosition(final int k) {
if (k < 0 || k >= size) throw new RuntimeException( k + " is out of bounds.");
this.i = k;
}
final int position() {
return i;
}
}
static private final class CircularSequence extends Sequence {
public CircularSequence(final int size) {
super(size);
}
@Override
final int next() {
++i;
i = i % size;
return i;
}
@Override
final void setPosition(final int k) {
i = k;
if (i < 0) i = size - ((-i) % size);
else i = i % size;
}
}
static private final class GrowablePolygon {
private double[] x, y;
private int last = -1, growth;
GrowablePolygon(final int initialSize, final int growth) {
this.growth = growth;
this.x = new double[initialSize];
this.y = new double[initialSize];
}
final void resize() {
final double[] x2 = new double[this.x.length + this.growth];
System.arraycopy(this.x, 0, x2, 0, x.length);
this.x = x2;
final double[] y2 = new double[x2.length];
System.arraycopy(this.y, 0, y2, 0, y.length);
this.y = y2;
}
final void append(final double px, final double py) {
this.last += 1;
if (this.last == this.x.length) resize();
this.x[last] = px;
this.y[last] = py;
}
final double lastX() { return this.x[last]; }
final double lastY() { return this.y[last]; }
final void remove(final int i) {
System.arraycopy(this.x, i+1, this.x, i, last - i);
System.arraycopy(this.y, i+1, this.y, i, last - i);
--this.last;
}
}
private final void reorderToCCW() {
// reorder to CCW if needed: (so all curves have the same orientation)
// find bounding box:
double x_max = 0; int x_max_i = 0;
double y_max = 0; int y_max_i = 0;
double x_min = Double.MAX_VALUE; int x_min_i = 0;
double y_min = Double.MAX_VALUE; int y_min_i = 0;
for (int i=0;i <this.length; i++) {
if (x[i] > x_max) { x_max = x[i]; x_max_i = i; } // this lines could be optimized, the p->x etc. are catched below
if (y[i] > y_max) { y_max = y[i]; y_max_i = i; }
if (x[i] < x_min) { x_min = x[i]; x_min_i = i; }
if (y[i] < y_min) { y_min = y[i]; y_min_i = i; }
}
int collect = 0;
if (y_min_i - x_max_i >= 0) collect++;
if (x_min_i - y_min_i >= 0) collect++;
if (y_max_i - x_min_i >= 0) collect++;
if (x_max_i - y_max_i >= 0) collect++;
//if (3 == collect)
if (3 != collect) { // this should be '3 == collect', but then we are looking at the curves from the other side relative to what ImageJ is showing. In any case as long as one or the other gets rearranged, they'll be fine.
// Clockwise! Reorder to CCW by reversing the arrays in place
int n = this.length;
double tmp;
for (int i=0; i< this.length /2; i++) {
tmp = x[i];
x[i] = x[n-i-1];
x[n-i-1] = tmp;
tmp = y[i];
y[i] = y[n-i-1];
y[n-i-1] = tmp;
}
}
}
static private final class DoubleArray {
private double[] a;
private int next = 0;
DoubleArray(final int initialCapacity) {
this.a = new double[initialCapacity];
}
final void append(final double d) {
this.a[next] = d;
++next;
if (this.a.length == next) {
final double[] b = new double[this.a.length + 1008];
System.arraycopy(this.a, 0, b, 0, this.a.length);
this.a = b;
}
}
final void reset() {
this.next = 0;
}
final int size() {
return next;
}
}
private void resample() {
reorderToCCW();
- final double MAX_DISTANCE = 4 * delta;
+ final double MAX_DISTANCE = 2.5 * delta;
final double MAX_DISTANCE_SQ = MAX_DISTANCE * MAX_DISTANCE;
final double deltaSq = delta * delta;
final Sequence seq = this.closed ? new CircularSequence(this.length) : new Sequence(this.length);
final GrowablePolygon gpol = new GrowablePolygon(this.length, 200);
final DoubleArray w = new DoubleArray(16);
boolean end_seen = false;
final int last = closed ? 0 : this.length -1;
// First resampled point is the same as zero
gpol.append(x[0], y[0]);
// Start using the first point for interpolations
seq.setPosition(1);
// Grow all the way to the last point
loop: while (true) {
final double lastX = gpol.lastX(),
lastY = gpol.lastY();
final int first_i = seq.position(); // the first point ahead to consider
double sumW = 0; // the sum of weights, for normalization
int i = first_i; // the index over the original sequence of points
int next_i = first_i; // the next index for the next iteration
w.reset(); // reset the array of weights: empty it
// Iterate the points from i onward that lay within MAX_DISTANCE to estimate the next gpol point
// and determine from which of the seen next points the estimation should start in the next iteration
// or use again the same i of not overtaken.
while (true) {
// Determine termination:
if (!end_seen) end_seen = i == last;
if (end_seen) {
double distToEndSq = Math.pow(this.x[last] - lastX, 2) + Math.pow(this.y[last] - lastY, 2);
if (distToEndSq > deltaSq) {
// Populate towards the end in a straight line
// While this may not be smooth, termination is otherwise a devilish issue.
final int n = (int)(Math.sqrt(distToEndSq) / delta);
final double angleXY = Util.getAngle(x[last] - lastX, y[last] - lastY);
double dX = Math.cos(angleXY) * delta,
dY = Math.sin(angleXY) * delta;
for (int k=1; k<=n; ++k) {
gpol.append(lastX + dX * k, lastY + dY * k);
}
}
break loop;
}
- // If i is within MAX_DISTANCE, include it in the estimation of the next gpol point
final double distSq = Math.pow(this.x[i] - lastX, 2) + Math.pow(this.y[i] - lastY, 2);
// Choose next i: the first one further than delta from lastX, lastY
// and if the same is to be used, then use the next one if there's another under MAX_DISTANCE
if (first_i == next_i && distSq > deltaSq) { // if not yet changed and distance is larger than delta
next_i = i;
}
+ // If i is within MAX_DISTANCE, include it in the estimation of the next gpol point
if (distSq < MAX_DISTANCE_SQ) {
final double dist = Math.sqrt(distSq);
sumW += dist;
w.append(dist);
// ... and advance to the next
i = seq.next();
} else {
break;
}
}
if (w.size() > 0) {
// Normalize weights so that their sum equals 1
double sumW2 = 0;
for (int j=w.size() -1; j > -1; --j) {
w.a[j] /= sumW;
sumW2 += w.a[j];
}
// Correct for floating-point issues: add error to first weight
if (sumW2 < 1.0) {
w.a[0] += 1.0 - sumW2;
}
// Create next interpolated point
seq.setPosition(first_i);
double dx = 0,
dy = 0;
for (int j=0, k = seq.position(); j<w.size(); ++j, k = seq.next()) {
final double angleXY = Util.getAngle(x[k] - lastX, y[k] - lastY);
dx += w.a[j] * Math.cos(angleXY);
dy += w.a[j] * Math.sin(angleXY);
}
gpol.append(lastX + dx * delta, lastY + dy * delta);
} else {
// Use the first_i, which was not yet overtaken
final double angleXY = Util.getAngle(x[first_i] - lastX, y[first_i] - lastY);
gpol.append(lastX + Math.cos(angleXY) * delta,
lastY + Math.sin(angleXY) * delta);
}
// Set next point:
seq.setPosition(next_i);
}
// Fix the junction between first and last point: check if second point suits best.
if (closed) {
final double distSq = Math.pow(gpol.x[1] - gpol.x[gpol.last], 2)
+ Math.pow(gpol.y[1] - gpol.y[gpol.last], 2);
if (distSq < delta) {
gpol.remove(0);
}
} else {
// When not closed, append the last point--regardless of its distance to lastX, lastY.
gpol.append(this.x[this.length -1], this.y[this.length -1]);
}
// Assign the new resampled points
this.length = gpol.last + 1;
this.x = gpol.x;
this.y = gpol.y;
// Assign the vectors
this.v_x = new double[this.length];
this.v_y = new double[this.length];
for (int k=1; k<this.length; ++k) {
this.v_x[k] = this.x[k] - this.x[k-1];
this.v_y[k] = this.y[k] - this.y[k-1];
}
// For non-closed this arrangement of vectors seems wrong, but IIRC the vector at zero is ignored.
this.v_x[0] = this.x[0] - this.x[this.length -1];
this.v_y[0] = this.y[0] - this.y[this.length -1];
}
public void reorder(final int new_zero) { // this function is optimized for speed: no array duplications beyond minimally necessary, and no superfluous method calls.
int i, j;
// copying
double[] tmp = new double[this.length];
double[] src;
// x
src = x;
for (i=0, j=new_zero; j<length; i++, j++) { tmp[i] = src[j]; }
for (j=0; j<new_zero; i++, j++) { tmp[i] = src[j]; }
x = tmp;
tmp = src;
// y
src = y;
for (i=0, j=new_zero; j<length; i++, j++) { tmp[i] = src[j]; }
for (j=0; j<new_zero; i++, j++) { tmp[i] = src[j]; }
y = tmp;
tmp = src;
// v_x
src = v_x;
for (i=0, j=new_zero; j<length; i++, j++) { tmp[i] = src[j]; }
for (j=0; j<new_zero; i++, j++) { tmp[i] = src[j]; }
v_x = tmp;
tmp = src;
// v_y
src = v_y;
for (i=0, j=new_zero; j<length; i++, j++) { tmp[i] = src[j]; }
for (j=0; j<new_zero; i++, j++) { tmp[i] = src[j]; }
v_y = tmp;
tmp = src;
// equivalent would be:
//System.arraycopy(src, new_zero, tmp, 0, m - new_zero);
//System.arraycopy(src, 0, tmp, m - new_zero, new_zero);
//sv2.x = tmp;
//tmp = src;
// release
tmp = null;
}
/** Subtracts vs2 vector j to this vector i and returns its length, without changing any data. */
public double getDiffVectorLength(final int i, final int j, final VectorString vs2) {
final VectorString2D vs = (VectorString2D)vs2;
final double dx = v_x[i] - vs.v_x[j];
final double dy = v_y[i] - vs.v_y[j];
return Math.sqrt(dx*dx + dy*dy);
}
/** Distance from point i in this to point j in vs2. */
public double distance(int i, VectorString vs, int j) {
VectorString2D vs2 = (VectorString2D)vs;
return distance(x[i], y[i],
vs2.x[i], vs2.y[i]);
}
static public double distance(double x1, double y1,
double x2, double y2) {
return Math.sqrt(Math.pow(x1 - x2, 2)
+ Math.pow(y1 - y2, 2));
}
/** Create a new VectorString for the given range. If last < first, it will be created as reversed. */
public VectorString subVectorString(int first, int last) throws Exception {
boolean reverse = false;
if (last < first) {
int tmp = first;
first = last;
last = tmp;
reverse = true;
}
int len = last - first + 1;
double[] x = new double[len];
double[] y = new double[len];
System.arraycopy(this.x, first, x, 0, len);
System.arraycopy(this.y, first, y, 0, len);
final VectorString2D vs = new VectorString2D(x, y, this.z, this.closed);
if (reverse) vs.reverse();
if (null != this.v_x) {
// this is resampled, so:
vs.delta = this.delta;
// create vectors
vs.v_x = new double[len];
vs.v_y = new double[len];
for (int i=1; i<len; i++) {
vs.v_x[i] = vs.x[i] - vs.x[i-1];
vs.v_y[i] = vs.y[i] - vs.y[i-1];
}
}
return vs;
}
/** Invert the order of points. Will clear all vector arrays if any! */
public void reverse() {
Util.reverse(x);
Util.reverse(y);
delta = 0;
if (null != v_x) v_x = v_y = null;
}
public int getDimensions() { return 2; }
/** Scale to match cal.pixelWidth, cal.pixelHeight and computed depth. If cal is null, returns immediately. Will make all vectors null, so you must call resample(delta) again after calibrating. So it brings all values to cal.units, such as microns. */
public void calibrate(final Calibration cal) {
if (null == cal) return;
this.cal = cal;
final int sign = cal.pixelDepth < 0 ? - 1 :1;
for (int i=0; i<x.length; i++) {
x[i] *= cal.pixelWidth;
y[i] *= cal.pixelHeight; // should be the same as pixelWidth
}
z *= cal.pixelWidth * sign; // since layer Z is in pixels.
// reset vectors
if (null != v_x) v_x = v_y = null;
delta = 0;
}
public boolean isCalibrated() {
return null != this.cal;
}
public Calibration getCalibrationCopy() {
return null == this.cal ? null : this.cal.copy();
}
static public final void main(String[] args) {
try {
RoiDecoder rd = new RoiDecoder("/home/albert/Desktop/t2/test-spline/1152-polygon.roi");
PolygonRoi sroi = (PolygonRoi)rd.getRoi();
Polygon pol = sroi.getPolygon();
double[] x = new double[pol.npoints];
double[] y = new double[pol.npoints];
for (int i=0; i<pol.npoints; ++i) {
x[i] = pol.xpoints[i];
y[i] = pol.ypoints[i];
}
VectorString2D v = new VectorString2D(x, y, 0, true);
v.resample(1);
StringBuffer sb = new StringBuffer();
sb.append("x = [");
for (int i=0; i<v.length; ++i) {
sb.append(v.x[i] + ",\n");
}
sb.setLength(sb.length() -2);
sb.append("]\n");
sb.append("\ny = [");
for (int i=0; i<v.length; ++i) {
sb.append(v.y[i] + ",\n");
}
sb.setLength(sb.length() -2);
sb.append("]\n");
System.out.println(sb.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
| false | true | private void resample() {
reorderToCCW();
final double MAX_DISTANCE = 4 * delta;
final double MAX_DISTANCE_SQ = MAX_DISTANCE * MAX_DISTANCE;
final double deltaSq = delta * delta;
final Sequence seq = this.closed ? new CircularSequence(this.length) : new Sequence(this.length);
final GrowablePolygon gpol = new GrowablePolygon(this.length, 200);
final DoubleArray w = new DoubleArray(16);
boolean end_seen = false;
final int last = closed ? 0 : this.length -1;
// First resampled point is the same as zero
gpol.append(x[0], y[0]);
// Start using the first point for interpolations
seq.setPosition(1);
// Grow all the way to the last point
loop: while (true) {
final double lastX = gpol.lastX(),
lastY = gpol.lastY();
final int first_i = seq.position(); // the first point ahead to consider
double sumW = 0; // the sum of weights, for normalization
int i = first_i; // the index over the original sequence of points
int next_i = first_i; // the next index for the next iteration
w.reset(); // reset the array of weights: empty it
// Iterate the points from i onward that lay within MAX_DISTANCE to estimate the next gpol point
// and determine from which of the seen next points the estimation should start in the next iteration
// or use again the same i of not overtaken.
while (true) {
// Determine termination:
if (!end_seen) end_seen = i == last;
if (end_seen) {
double distToEndSq = Math.pow(this.x[last] - lastX, 2) + Math.pow(this.y[last] - lastY, 2);
if (distToEndSq > deltaSq) {
// Populate towards the end in a straight line
// While this may not be smooth, termination is otherwise a devilish issue.
final int n = (int)(Math.sqrt(distToEndSq) / delta);
final double angleXY = Util.getAngle(x[last] - lastX, y[last] - lastY);
double dX = Math.cos(angleXY) * delta,
dY = Math.sin(angleXY) * delta;
for (int k=1; k<=n; ++k) {
gpol.append(lastX + dX * k, lastY + dY * k);
}
}
break loop;
}
// If i is within MAX_DISTANCE, include it in the estimation of the next gpol point
final double distSq = Math.pow(this.x[i] - lastX, 2) + Math.pow(this.y[i] - lastY, 2);
// Choose next i: the first one further than delta from lastX, lastY
// and if the same is to be used, then use the next one if there's another under MAX_DISTANCE
if (first_i == next_i && distSq > deltaSq) { // if not yet changed and distance is larger than delta
next_i = i;
}
if (distSq < MAX_DISTANCE_SQ) {
final double dist = Math.sqrt(distSq);
sumW += dist;
w.append(dist);
// ... and advance to the next
i = seq.next();
} else {
break;
}
}
if (w.size() > 0) {
// Normalize weights so that their sum equals 1
double sumW2 = 0;
for (int j=w.size() -1; j > -1; --j) {
w.a[j] /= sumW;
sumW2 += w.a[j];
}
// Correct for floating-point issues: add error to first weight
if (sumW2 < 1.0) {
w.a[0] += 1.0 - sumW2;
}
// Create next interpolated point
seq.setPosition(first_i);
double dx = 0,
dy = 0;
for (int j=0, k = seq.position(); j<w.size(); ++j, k = seq.next()) {
final double angleXY = Util.getAngle(x[k] - lastX, y[k] - lastY);
dx += w.a[j] * Math.cos(angleXY);
dy += w.a[j] * Math.sin(angleXY);
}
gpol.append(lastX + dx * delta, lastY + dy * delta);
} else {
// Use the first_i, which was not yet overtaken
final double angleXY = Util.getAngle(x[first_i] - lastX, y[first_i] - lastY);
gpol.append(lastX + Math.cos(angleXY) * delta,
lastY + Math.sin(angleXY) * delta);
}
// Set next point:
seq.setPosition(next_i);
}
// Fix the junction between first and last point: check if second point suits best.
if (closed) {
final double distSq = Math.pow(gpol.x[1] - gpol.x[gpol.last], 2)
+ Math.pow(gpol.y[1] - gpol.y[gpol.last], 2);
if (distSq < delta) {
gpol.remove(0);
}
} else {
// When not closed, append the last point--regardless of its distance to lastX, lastY.
gpol.append(this.x[this.length -1], this.y[this.length -1]);
}
// Assign the new resampled points
this.length = gpol.last + 1;
this.x = gpol.x;
this.y = gpol.y;
// Assign the vectors
this.v_x = new double[this.length];
this.v_y = new double[this.length];
for (int k=1; k<this.length; ++k) {
this.v_x[k] = this.x[k] - this.x[k-1];
this.v_y[k] = this.y[k] - this.y[k-1];
}
// For non-closed this arrangement of vectors seems wrong, but IIRC the vector at zero is ignored.
this.v_x[0] = this.x[0] - this.x[this.length -1];
this.v_y[0] = this.y[0] - this.y[this.length -1];
}
| private void resample() {
reorderToCCW();
final double MAX_DISTANCE = 2.5 * delta;
final double MAX_DISTANCE_SQ = MAX_DISTANCE * MAX_DISTANCE;
final double deltaSq = delta * delta;
final Sequence seq = this.closed ? new CircularSequence(this.length) : new Sequence(this.length);
final GrowablePolygon gpol = new GrowablePolygon(this.length, 200);
final DoubleArray w = new DoubleArray(16);
boolean end_seen = false;
final int last = closed ? 0 : this.length -1;
// First resampled point is the same as zero
gpol.append(x[0], y[0]);
// Start using the first point for interpolations
seq.setPosition(1);
// Grow all the way to the last point
loop: while (true) {
final double lastX = gpol.lastX(),
lastY = gpol.lastY();
final int first_i = seq.position(); // the first point ahead to consider
double sumW = 0; // the sum of weights, for normalization
int i = first_i; // the index over the original sequence of points
int next_i = first_i; // the next index for the next iteration
w.reset(); // reset the array of weights: empty it
// Iterate the points from i onward that lay within MAX_DISTANCE to estimate the next gpol point
// and determine from which of the seen next points the estimation should start in the next iteration
// or use again the same i of not overtaken.
while (true) {
// Determine termination:
if (!end_seen) end_seen = i == last;
if (end_seen) {
double distToEndSq = Math.pow(this.x[last] - lastX, 2) + Math.pow(this.y[last] - lastY, 2);
if (distToEndSq > deltaSq) {
// Populate towards the end in a straight line
// While this may not be smooth, termination is otherwise a devilish issue.
final int n = (int)(Math.sqrt(distToEndSq) / delta);
final double angleXY = Util.getAngle(x[last] - lastX, y[last] - lastY);
double dX = Math.cos(angleXY) * delta,
dY = Math.sin(angleXY) * delta;
for (int k=1; k<=n; ++k) {
gpol.append(lastX + dX * k, lastY + dY * k);
}
}
break loop;
}
final double distSq = Math.pow(this.x[i] - lastX, 2) + Math.pow(this.y[i] - lastY, 2);
// Choose next i: the first one further than delta from lastX, lastY
// and if the same is to be used, then use the next one if there's another under MAX_DISTANCE
if (first_i == next_i && distSq > deltaSq) { // if not yet changed and distance is larger than delta
next_i = i;
}
// If i is within MAX_DISTANCE, include it in the estimation of the next gpol point
if (distSq < MAX_DISTANCE_SQ) {
final double dist = Math.sqrt(distSq);
sumW += dist;
w.append(dist);
// ... and advance to the next
i = seq.next();
} else {
break;
}
}
if (w.size() > 0) {
// Normalize weights so that their sum equals 1
double sumW2 = 0;
for (int j=w.size() -1; j > -1; --j) {
w.a[j] /= sumW;
sumW2 += w.a[j];
}
// Correct for floating-point issues: add error to first weight
if (sumW2 < 1.0) {
w.a[0] += 1.0 - sumW2;
}
// Create next interpolated point
seq.setPosition(first_i);
double dx = 0,
dy = 0;
for (int j=0, k = seq.position(); j<w.size(); ++j, k = seq.next()) {
final double angleXY = Util.getAngle(x[k] - lastX, y[k] - lastY);
dx += w.a[j] * Math.cos(angleXY);
dy += w.a[j] * Math.sin(angleXY);
}
gpol.append(lastX + dx * delta, lastY + dy * delta);
} else {
// Use the first_i, which was not yet overtaken
final double angleXY = Util.getAngle(x[first_i] - lastX, y[first_i] - lastY);
gpol.append(lastX + Math.cos(angleXY) * delta,
lastY + Math.sin(angleXY) * delta);
}
// Set next point:
seq.setPosition(next_i);
}
// Fix the junction between first and last point: check if second point suits best.
if (closed) {
final double distSq = Math.pow(gpol.x[1] - gpol.x[gpol.last], 2)
+ Math.pow(gpol.y[1] - gpol.y[gpol.last], 2);
if (distSq < delta) {
gpol.remove(0);
}
} else {
// When not closed, append the last point--regardless of its distance to lastX, lastY.
gpol.append(this.x[this.length -1], this.y[this.length -1]);
}
// Assign the new resampled points
this.length = gpol.last + 1;
this.x = gpol.x;
this.y = gpol.y;
// Assign the vectors
this.v_x = new double[this.length];
this.v_y = new double[this.length];
for (int k=1; k<this.length; ++k) {
this.v_x[k] = this.x[k] - this.x[k-1];
this.v_y[k] = this.y[k] - this.y[k-1];
}
// For non-closed this arrangement of vectors seems wrong, but IIRC the vector at zero is ignored.
this.v_x[0] = this.x[0] - this.x[this.length -1];
this.v_y[0] = this.y[0] - this.y[this.length -1];
}
|
diff --git a/Essentials/src/com/earth2me/essentials/InventoryWorkaround.java b/Essentials/src/com/earth2me/essentials/InventoryWorkaround.java
index 4ce5cb52..0b8121f8 100644
--- a/Essentials/src/com/earth2me/essentials/InventoryWorkaround.java
+++ b/Essentials/src/com/earth2me/essentials/InventoryWorkaround.java
@@ -1,344 +1,358 @@
package com.earth2me.essentials;
import com.earth2me.essentials.craftbukkit.EnchantmentFix;
import java.util.HashMap;
import java.util.Map;
import org.bukkit.Location;
import org.bukkit.entity.Item;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
/*
* This class can be removed when
* https://github.com/Bukkit/CraftBukkit/pull/193
* is accepted to CraftBukkit
*/
public final class InventoryWorkaround
{
private InventoryWorkaround()
{
}
public static int first(final Inventory inventory, final ItemStack item, final boolean forceDurability, final boolean forceAmount)
{
return next(inventory, item, 0, forceDurability, forceAmount);
}
public static int next(final Inventory cinventory, final ItemStack item, final int start, final boolean forceDurability, final boolean forceAmount)
{
final ItemStack[] inventory = cinventory.getContents();
for (int i = start; i < inventory.length; i++)
{
final ItemStack cItem = inventory[i];
if (cItem == null)
{
continue;
}
if (item.getTypeId() == cItem.getTypeId() && (!forceAmount || item.getAmount() == cItem.getAmount()) && (!forceDurability || cItem.getDurability() == item.getDurability()) && cItem.getEnchantments().equals(item.getEnchantments()))
{
return i;
}
}
return -1;
}
public static int firstPartial(final Inventory cinventory, final ItemStack item, final boolean forceDurability)
{
if (item == null)
{
return -1;
}
final ItemStack[] inventory = cinventory.getContents();
for (int i = 0; i < inventory.length; i++)
{
final ItemStack cItem = inventory[i];
if (cItem == null)
{
continue;
}
if (item.getTypeId() == cItem.getTypeId() && cItem.getAmount() < cItem.getType().getMaxStackSize() && (!forceDurability || cItem.getDurability() == item.getDurability()) && cItem.getEnchantments().equals(item.getEnchantments()))
{
return i;
}
}
return -1;
}
public static boolean addAllItems(final Inventory cinventory, final boolean forceDurability, final ItemStack... items)
{
final Inventory fake = new FakeInventory(cinventory.getContents());
if (addItem(fake, forceDurability, items).isEmpty())
{
addItem(cinventory, forceDurability, items);
return true;
}
else
{
return false;
}
}
public static Map<Integer, ItemStack> addItem(final Inventory cinventory, final boolean forceDurability, final ItemStack... items)
{
return addItem(cinventory, forceDurability, false, null, items);
}
public static Map<Integer, ItemStack> addItem(final Inventory cinventory, final boolean forceDurability, final boolean dontBreakStacks, final IEssentials ess, final ItemStack... items)
{
final Map<Integer, ItemStack> leftover = new HashMap<Integer, ItemStack>();
/* TODO: some optimization
* - Create a 'firstPartial' with a 'fromIndex'
* - Record the lastPartial per Material
* - Cache firstEmpty result
*/
// combine items
ItemStack[] combined = new ItemStack[items.length];
for (int i = 0; i < items.length; i++)
{
if (items[i] == null || items[i].getAmount() < 1)
{
continue;
}
for (int j = 0; j < combined.length; j++)
{
if (combined[j] == null)
{
combined[j] = items[i].clone();
break;
}
if (combined[j].getTypeId() == items[i].getTypeId() && (!forceDurability || combined[j].getDurability() == items[i].getDurability()) && combined[j].getEnchantments().equals(items[i].getEnchantments()))
{
combined[j].setAmount(combined[j].getAmount() + items[i].getAmount());
break;
}
}
}
for (int i = 0; i < combined.length; i++)
{
final ItemStack item = combined[i];
if (item == null)
{
continue;
}
while (true)
{
// Do we already have a stack of it?
final int firstPartial = firstPartial(cinventory, item, forceDurability);
// Drat! no partial stack
if (firstPartial == -1)
{
// Find a free spot!
final int firstFree = cinventory.firstEmpty();
if (firstFree == -1)
{
// No space at all!
leftover.put(i, item);
break;
}
else
{
// More than a single stack!
if (item.getAmount() > (dontBreakStacks ? ess.getSettings().getDefaultStackSize() : item.getType().getMaxStackSize()))
{
ItemStack stack = item.clone();
stack.setAmount(dontBreakStacks ? ess.getSettings().getDefaultStackSize() : item.getType().getMaxStackSize());
- EnchantmentFix.setItem(cinventory, firstFree, stack);
+ if (cinventory instanceof FakeInventory)
+ {
+ cinventory.setItem(firstFree, stack);
+ }
+ else
+ {
+ EnchantmentFix.setItem(cinventory, firstFree, stack);
+ }
item.setAmount(item.getAmount() - item.getType().getMaxStackSize());
}
else
{
// Just store it
- EnchantmentFix.setItem(cinventory, firstFree, item);
+ if (cinventory instanceof FakeInventory)
+ {
+ cinventory.setItem(firstFree, item);
+ }
+ else
+ {
+ EnchantmentFix.setItem(cinventory, firstFree, item);
+ }
break;
}
}
}
else
{
// So, apparently it might only partially fit, well lets do just that
final ItemStack partialItem = cinventory.getItem(firstPartial);
final int amount = item.getAmount();
final int partialAmount = partialItem.getAmount();
final int maxAmount = dontBreakStacks ? ess.getSettings().getDefaultStackSize() : partialItem.getType().getMaxStackSize();
// Check if it fully fits
if (amount + partialAmount <= maxAmount)
{
partialItem.setAmount(amount + partialAmount);
break;
}
// It fits partially
partialItem.setAmount(maxAmount);
item.setAmount(amount + partialAmount - maxAmount);
}
}
}
return leftover;
}
public static Map<Integer, ItemStack> removeItem(final Inventory cinventory, final boolean forceDurability, final ItemStack... items)
{
final Map<Integer, ItemStack> leftover = new HashMap<Integer, ItemStack>();
// TODO: optimization
for (int i = 0; i < items.length; i++)
{
final ItemStack item = items[i];
if (item == null)
{
continue;
}
int toDelete = item.getAmount();
while (true)
{
// Bail when done
if (toDelete <= 0)
{
break;
}
// get first Item, ignore the amount
final int first = first(cinventory, item, forceDurability, false);
// Drat! we don't have this type in the inventory
if (first == -1)
{
item.setAmount(toDelete);
leftover.put(i, item);
break;
}
else
{
final ItemStack itemStack = cinventory.getItem(first);
final int amount = itemStack.getAmount();
if (amount <= toDelete)
{
toDelete -= amount;
// clear the slot, all used up
cinventory.clear(first);
}
else
{
// split the stack and store
itemStack.setAmount(amount - toDelete);
EnchantmentFix.setItem(cinventory, first, itemStack);
toDelete = 0;
}
}
}
}
return leftover;
}
public static boolean containsItem(final Inventory cinventory, final boolean forceDurability, final ItemStack... items)
{
final Map<Integer, ItemStack> leftover = new HashMap<Integer, ItemStack>();
// TODO: optimization
// combine items
ItemStack[] combined = new ItemStack[items.length];
for (int i = 0; i < items.length; i++)
{
if (items[i] == null)
{
continue;
}
for (int j = 0; j < combined.length; j++)
{
if (combined[j] == null)
{
combined[j] = items[i].clone();
break;
}
if (combined[j].getTypeId() == items[i].getTypeId() && (!forceDurability || combined[j].getDurability() == items[i].getDurability()) && combined[j].getEnchantments().equals(items[i].getEnchantments()))
{
combined[j].setAmount(combined[j].getAmount() + items[i].getAmount());
break;
}
}
}
for (int i = 0; i < combined.length; i++)
{
final ItemStack item = combined[i];
if (item == null)
{
continue;
}
int mustHave = item.getAmount();
int position = 0;
while (true)
{
// Bail when done
if (mustHave <= 0)
{
break;
}
final int slot = next(cinventory, item, position, forceDurability, false);
// Drat! we don't have this type in the inventory
if (slot == -1)
{
leftover.put(i, item);
break;
}
else
{
final ItemStack itemStack = cinventory.getItem(slot);
final int amount = itemStack.getAmount();
if (amount <= mustHave)
{
mustHave -= amount;
}
else
{
mustHave = 0;
}
position = slot + 1;
}
}
}
return leftover.isEmpty();
}
public static Item[] dropItem(final Location loc, final ItemStack itm)
{
final int maxStackSize = itm.getType().getMaxStackSize();
final int stacks = itm.getAmount() / maxStackSize;
final int leftover = itm.getAmount() % maxStackSize;
final Item[] itemStacks = new Item[stacks + (leftover > 0 ? 1 : 0)];
for (int i = 0; i < stacks; i++)
{
final ItemStack stack = itm.clone();
stack.setAmount(maxStackSize);
itemStacks[i] = loc.getWorld().dropItem(loc, stack);
}
if (leftover > 0)
{
final ItemStack stack = itm.clone();
stack.setAmount(leftover);
itemStacks[stacks] = loc.getWorld().dropItem(loc, stack);
}
return itemStacks;
}
}
| false | true | public static Map<Integer, ItemStack> addItem(final Inventory cinventory, final boolean forceDurability, final boolean dontBreakStacks, final IEssentials ess, final ItemStack... items)
{
final Map<Integer, ItemStack> leftover = new HashMap<Integer, ItemStack>();
/* TODO: some optimization
* - Create a 'firstPartial' with a 'fromIndex'
* - Record the lastPartial per Material
* - Cache firstEmpty result
*/
// combine items
ItemStack[] combined = new ItemStack[items.length];
for (int i = 0; i < items.length; i++)
{
if (items[i] == null || items[i].getAmount() < 1)
{
continue;
}
for (int j = 0; j < combined.length; j++)
{
if (combined[j] == null)
{
combined[j] = items[i].clone();
break;
}
if (combined[j].getTypeId() == items[i].getTypeId() && (!forceDurability || combined[j].getDurability() == items[i].getDurability()) && combined[j].getEnchantments().equals(items[i].getEnchantments()))
{
combined[j].setAmount(combined[j].getAmount() + items[i].getAmount());
break;
}
}
}
for (int i = 0; i < combined.length; i++)
{
final ItemStack item = combined[i];
if (item == null)
{
continue;
}
while (true)
{
// Do we already have a stack of it?
final int firstPartial = firstPartial(cinventory, item, forceDurability);
// Drat! no partial stack
if (firstPartial == -1)
{
// Find a free spot!
final int firstFree = cinventory.firstEmpty();
if (firstFree == -1)
{
// No space at all!
leftover.put(i, item);
break;
}
else
{
// More than a single stack!
if (item.getAmount() > (dontBreakStacks ? ess.getSettings().getDefaultStackSize() : item.getType().getMaxStackSize()))
{
ItemStack stack = item.clone();
stack.setAmount(dontBreakStacks ? ess.getSettings().getDefaultStackSize() : item.getType().getMaxStackSize());
EnchantmentFix.setItem(cinventory, firstFree, stack);
item.setAmount(item.getAmount() - item.getType().getMaxStackSize());
}
else
{
// Just store it
EnchantmentFix.setItem(cinventory, firstFree, item);
break;
}
}
}
else
{
// So, apparently it might only partially fit, well lets do just that
final ItemStack partialItem = cinventory.getItem(firstPartial);
final int amount = item.getAmount();
final int partialAmount = partialItem.getAmount();
final int maxAmount = dontBreakStacks ? ess.getSettings().getDefaultStackSize() : partialItem.getType().getMaxStackSize();
// Check if it fully fits
if (amount + partialAmount <= maxAmount)
{
partialItem.setAmount(amount + partialAmount);
break;
}
// It fits partially
partialItem.setAmount(maxAmount);
item.setAmount(amount + partialAmount - maxAmount);
}
}
}
return leftover;
}
| public static Map<Integer, ItemStack> addItem(final Inventory cinventory, final boolean forceDurability, final boolean dontBreakStacks, final IEssentials ess, final ItemStack... items)
{
final Map<Integer, ItemStack> leftover = new HashMap<Integer, ItemStack>();
/* TODO: some optimization
* - Create a 'firstPartial' with a 'fromIndex'
* - Record the lastPartial per Material
* - Cache firstEmpty result
*/
// combine items
ItemStack[] combined = new ItemStack[items.length];
for (int i = 0; i < items.length; i++)
{
if (items[i] == null || items[i].getAmount() < 1)
{
continue;
}
for (int j = 0; j < combined.length; j++)
{
if (combined[j] == null)
{
combined[j] = items[i].clone();
break;
}
if (combined[j].getTypeId() == items[i].getTypeId() && (!forceDurability || combined[j].getDurability() == items[i].getDurability()) && combined[j].getEnchantments().equals(items[i].getEnchantments()))
{
combined[j].setAmount(combined[j].getAmount() + items[i].getAmount());
break;
}
}
}
for (int i = 0; i < combined.length; i++)
{
final ItemStack item = combined[i];
if (item == null)
{
continue;
}
while (true)
{
// Do we already have a stack of it?
final int firstPartial = firstPartial(cinventory, item, forceDurability);
// Drat! no partial stack
if (firstPartial == -1)
{
// Find a free spot!
final int firstFree = cinventory.firstEmpty();
if (firstFree == -1)
{
// No space at all!
leftover.put(i, item);
break;
}
else
{
// More than a single stack!
if (item.getAmount() > (dontBreakStacks ? ess.getSettings().getDefaultStackSize() : item.getType().getMaxStackSize()))
{
ItemStack stack = item.clone();
stack.setAmount(dontBreakStacks ? ess.getSettings().getDefaultStackSize() : item.getType().getMaxStackSize());
if (cinventory instanceof FakeInventory)
{
cinventory.setItem(firstFree, stack);
}
else
{
EnchantmentFix.setItem(cinventory, firstFree, stack);
}
item.setAmount(item.getAmount() - item.getType().getMaxStackSize());
}
else
{
// Just store it
if (cinventory instanceof FakeInventory)
{
cinventory.setItem(firstFree, item);
}
else
{
EnchantmentFix.setItem(cinventory, firstFree, item);
}
break;
}
}
}
else
{
// So, apparently it might only partially fit, well lets do just that
final ItemStack partialItem = cinventory.getItem(firstPartial);
final int amount = item.getAmount();
final int partialAmount = partialItem.getAmount();
final int maxAmount = dontBreakStacks ? ess.getSettings().getDefaultStackSize() : partialItem.getType().getMaxStackSize();
// Check if it fully fits
if (amount + partialAmount <= maxAmount)
{
partialItem.setAmount(amount + partialAmount);
break;
}
// It fits partially
partialItem.setAmount(maxAmount);
item.setAmount(amount + partialAmount - maxAmount);
}
}
}
return leftover;
}
|
diff --git a/src-pos/com/openbravo/pos/config/JPanelConfigGeneral.java b/src-pos/com/openbravo/pos/config/JPanelConfigGeneral.java
index 64ecca3..89b89fc 100644
--- a/src-pos/com/openbravo/pos/config/JPanelConfigGeneral.java
+++ b/src-pos/com/openbravo/pos/config/JPanelConfigGeneral.java
@@ -1,1273 +1,1273 @@
// Openbravo POS is a point of sales application designed for touch screens.
// Copyright (C) 2007-2008 Openbravo, S.L.
// http://sourceforge.net/projects/openbravopos
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.openbravo.pos.config;
import com.openbravo.data.user.DirtyManager;
import java.awt.CardLayout;
import java.awt.Component;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import com.openbravo.pos.forms.AppConfig;
import com.openbravo.pos.forms.AppLocal;
import com.openbravo.pos.util.ReportUtils;
import com.openbravo.pos.util.StringParser;
import java.util.Map;
import javax.swing.LookAndFeel;
import javax.swing.SwingUtilities;
import org.jvnet.substance.SubstanceLookAndFeel;
import org.jvnet.substance.skin.SkinInfo;
import org.jvnet.substance.skin.SubstanceSkin;
/**
*
* @author adrianromero
*/
public class JPanelConfigGeneral extends javax.swing.JPanel implements PanelConfig {
private DirtyManager dirty = new DirtyManager();
/** Creates new form JPanelConfigGeneral */
public JPanelConfigGeneral() {
initComponents();
jtxtMachineHostname.getDocument().addDocumentListener(dirty);
jcboLAF.addActionListener(dirty);
jcboMachineScreenmode.addActionListener(dirty);
jcboTicketsBag.addActionListener(dirty);
jcboMachineDisplay.addActionListener(dirty);
jcboConnDisplay.addActionListener(dirty);
jcboSerialDisplay.addActionListener(dirty);
m_jtxtJPOSName.getDocument().addDocumentListener(dirty);
jcboMachinePrinter.addActionListener(dirty);
jcboConnPrinter.addActionListener(dirty);
jcboSerialPrinter.addActionListener(dirty);
m_jtxtJPOSPrinter.getDocument().addDocumentListener(dirty);
m_jtxtJPOSDrawer.getDocument().addDocumentListener(dirty);
jcboMachinePrinter2.addActionListener(dirty);
jcboConnPrinter2.addActionListener(dirty);
jcboSerialPrinter2.addActionListener(dirty);
m_jtxtJPOSPrinter2.getDocument().addDocumentListener(dirty);
m_jtxtJPOSDrawer2.getDocument().addDocumentListener(dirty);
jcboMachinePrinter3.addActionListener(dirty);
jcboConnPrinter3.addActionListener(dirty);
jcboSerialPrinter3.addActionListener(dirty);
m_jtxtJPOSPrinter3.getDocument().addDocumentListener(dirty);
m_jtxtJPOSDrawer3.getDocument().addDocumentListener(dirty);
jcboMachineScale.addActionListener(dirty);
jcboSerialScale.addActionListener(dirty);
jcboMachineScanner.addActionListener(dirty);
jcboSerialScanner.addActionListener(dirty);
cboPrinters.addActionListener(dirty);
m_ReceiptPrinter.addActionListener(dirty);
// // Openbravo Skin
// jcboLAF.addItem(new UIManager.LookAndFeelInfo("Openbravo", "com.openbravo.pos.skin.OpenbravoLookAndFeel"));
// Installed skins
LookAndFeelInfo[] lafs = UIManager.getInstalledLookAndFeels();
for (int i = 0; i < lafs.length; i++) {
jcboLAF.addItem(new LAFInfo(lafs[i].getName(), lafs[i].getClassName()));
}
// Substance skins
new SubstanceLookAndFeel(); // TODO: Remove in Substance 5.0. Workaround for Substance 4.3 to initialize static variables
Map<String, SkinInfo> skins = SubstanceLookAndFeel.getAllSkins();
for (SkinInfo skin : skins.values()) {
jcboLAF.addItem(new LAFInfo(skin.getDisplayName(), skin.getClassName()));
}
jcboLAF.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
changeLAF();
}
});
jcboMachineScreenmode.addItem("window");
jcboMachineScreenmode.addItem("fullscreen");
jcboTicketsBag.addItem("simple");
jcboTicketsBag.addItem("standard");
jcboTicketsBag.addItem("restaurant");
// Printer 1
jcboMachinePrinter.addItem("screen");
jcboMachinePrinter.addItem("printer");
jcboMachinePrinter.addItem("epson");
jcboMachinePrinter.addItem("tmu220");
jcboMachinePrinter.addItem("star");
jcboMachinePrinter.addItem("ithaca");
jcboMachinePrinter.addItem("surepos");
jcboMachinePrinter.addItem("plain");
jcboMachinePrinter.addItem("javapos");
jcboMachinePrinter.addItem("Not defined");
jcboConnPrinter.addItem("serial");
jcboConnPrinter.addItem("file");
jcboSerialPrinter.addItem("COM1");
jcboSerialPrinter.addItem("COM2");
jcboSerialPrinter.addItem("COM3");
jcboSerialPrinter.addItem("COM4");
jcboSerialPrinter.addItem("LPT1");
jcboSerialPrinter.addItem("/dev/ttyS0");
jcboSerialPrinter.addItem("/dev/ttyS1");
jcboSerialPrinter.addItem("/dev/ttyS2");
jcboSerialPrinter.addItem("/dev/ttyS3");
// Printer 2
jcboMachinePrinter2.addItem("screen");
jcboMachinePrinter2.addItem("printer");
jcboMachinePrinter2.addItem("epson");
jcboMachinePrinter2.addItem("tmu220");
jcboMachinePrinter2.addItem("star");
jcboMachinePrinter2.addItem("ithaca");
jcboMachinePrinter2.addItem("surepos");
jcboMachinePrinter2.addItem("plain");
jcboMachinePrinter2.addItem("javapos");
jcboMachinePrinter2.addItem("Not defined");
jcboConnPrinter2.addItem("serial");
jcboConnPrinter2.addItem("file");
jcboSerialPrinter2.addItem("COM1");
jcboSerialPrinter2.addItem("COM2");
jcboSerialPrinter2.addItem("COM3");
jcboSerialPrinter2.addItem("COM4");
jcboSerialPrinter2.addItem("LPT1");
jcboSerialPrinter2.addItem("/dev/ttyS0");
jcboSerialPrinter2.addItem("/dev/ttyS1");
jcboSerialPrinter2.addItem("/dev/ttyS2");
jcboSerialPrinter2.addItem("/dev/ttyS3");
// Printer 3
jcboMachinePrinter3.addItem("screen");
jcboMachinePrinter3.addItem("printer");
jcboMachinePrinter3.addItem("epson");
jcboMachinePrinter3.addItem("tmu220");
jcboMachinePrinter3.addItem("star");
jcboMachinePrinter3.addItem("ithaca");
jcboMachinePrinter3.addItem("surepos");
jcboMachinePrinter3.addItem("plain");
jcboMachinePrinter3.addItem("javapos");
jcboMachinePrinter3.addItem("Not defined");
jcboConnPrinter3.addItem("serial");
jcboConnPrinter3.addItem("file");
jcboSerialPrinter3.addItem("COM1");
jcboSerialPrinter3.addItem("COM2");
jcboSerialPrinter3.addItem("COM3");
jcboSerialPrinter3.addItem("COM4");
jcboSerialPrinter3.addItem("LPT1");
jcboSerialPrinter3.addItem("/dev/ttyS0");
jcboSerialPrinter3.addItem("/dev/ttyS1");
jcboSerialPrinter3.addItem("/dev/ttyS2");
jcboSerialPrinter3.addItem("/dev/ttyS3");
// Display
jcboMachineDisplay.addItem("screen");
jcboMachineDisplay.addItem("window");
jcboMachineDisplay.addItem("javapos");
jcboMachineDisplay.addItem("epson");
jcboMachineDisplay.addItem("ld200");
jcboMachineDisplay.addItem("surepos");
jcboMachineDisplay.addItem("Not defined");
jcboConnDisplay.addItem("serial");
jcboConnDisplay.addItem("file");
jcboSerialDisplay.addItem("COM1");
jcboSerialDisplay.addItem("COM2");
jcboSerialDisplay.addItem("COM3");
jcboSerialDisplay.addItem("COM4");
jcboSerialDisplay.addItem("LPT1");
jcboSerialDisplay.addItem("/dev/ttyS0");
jcboSerialDisplay.addItem("/dev/ttyS1");
jcboSerialDisplay.addItem("/dev/ttyS2");
jcboSerialDisplay.addItem("/dev/ttyS3");
// Scale
jcboMachineScale.addItem("screen");
jcboMachineScale.addItem("dialog1");
jcboMachineScale.addItem("samsungesp");
jcboMachineScale.addItem("Not defined");
jcboSerialScale.addItem("COM1");
jcboSerialScale.addItem("COM2");
jcboSerialScale.addItem("COM3");
jcboSerialScale.addItem("COM4");
jcboSerialScale.addItem("/dev/ttyS0");
jcboSerialScale.addItem("/dev/ttyS1");
jcboSerialScale.addItem("/dev/ttyS2");
jcboSerialScale.addItem("/dev/ttyS3");
// Scanner
jcboMachineScanner.addItem("scanpal2");
jcboMachineScanner.addItem("Not defined");
jcboSerialScanner.addItem("COM1");
jcboSerialScanner.addItem("COM2");
jcboSerialScanner.addItem("COM3");
jcboSerialScanner.addItem("COM4");
jcboSerialScanner.addItem("/dev/ttyS0");
jcboSerialScanner.addItem("/dev/ttyS1");
jcboSerialScanner.addItem("/dev/ttyS2");
jcboSerialScanner.addItem("/dev/ttyS3");
// Printers
cboPrinters.addItem("(Default)");
cboPrinters.addItem("(Show dialog)");
String[] printernames = ReportUtils.getPrintNames();
for (String name : printernames) {
cboPrinters.addItem(name);
}
}
public boolean hasChanged() {
return dirty.isDirty();
}
public Component getConfigComponent() {
return this;
}
public void loadProperties(AppConfig config) {
jtxtMachineHostname.setText(config.getProperty("machine.hostname"));
String lafclass = config.getProperty("swing.defaultlaf");
jcboLAF.setSelectedItem(null);
for (int i = 0; i < jcboLAF.getItemCount(); i++) {
LAFInfo lafinfo = (LAFInfo) jcboLAF.getItemAt(i);
if (lafinfo.getClassName().equals(lafclass)) {
jcboLAF.setSelectedIndex(i);
break;
}
}
// jcboLAF.setSelectedItem(new LookAndFeelInfo());
jcboMachineScreenmode.setSelectedItem(config.getProperty("machine.screenmode"));
jcboTicketsBag.setSelectedItem(config.getProperty("machine.ticketsbag"));
StringParser p = new StringParser(config.getProperty("machine.printer"));
String sparam = unifySerialInterface(p.nextToken(':'));
if ("serial".equals(sparam) || "file".equals(sparam)) {
jcboMachinePrinter.setSelectedItem("epson");
jcboConnPrinter.setSelectedItem(sparam);
jcboSerialPrinter.setSelectedItem(p.nextToken(','));
} else if ("javapos".equals(sparam)) {
jcboMachinePrinter.setSelectedItem(sparam);
m_jtxtJPOSPrinter.setText(p.nextToken(','));
m_jtxtJPOSDrawer.setText(p.nextToken(','));
} else {
jcboMachinePrinter.setSelectedItem(sparam);
jcboConnPrinter.setSelectedItem(unifySerialInterface(p.nextToken(',')));
jcboSerialPrinter.setSelectedItem(p.nextToken(','));
}
p = new StringParser(config.getProperty("machine.printer.2"));
sparam = unifySerialInterface(p.nextToken(':'));
if ("serial".equals(sparam) || "file".equals(sparam)) {
jcboMachinePrinter2.setSelectedItem("epson");
jcboConnPrinter2.setSelectedItem(sparam);
jcboSerialPrinter2.setSelectedItem(p.nextToken(','));
} else if ("javapos".equals(sparam)) {
jcboMachinePrinter2.setSelectedItem(sparam);
m_jtxtJPOSPrinter2.setText(p.nextToken(','));
m_jtxtJPOSDrawer2.setText(p.nextToken(','));
} else {
jcboMachinePrinter2.setSelectedItem(sparam);
jcboConnPrinter2.setSelectedItem(unifySerialInterface(p.nextToken(',')));
jcboSerialPrinter2.setSelectedItem(p.nextToken(','));
}
p = new StringParser(config.getProperty("machine.printer.3"));
sparam = unifySerialInterface(p.nextToken(':'));
if ("serial".equals(sparam) || "file".equals(sparam)) {
jcboMachinePrinter3.setSelectedItem("epson");
jcboConnPrinter3.setSelectedItem(sparam);
jcboSerialPrinter3.setSelectedItem(p.nextToken(','));
} else if ("javapos".equals(sparam)) {
jcboMachinePrinter3.setSelectedItem(sparam);
m_jtxtJPOSPrinter3.setText(p.nextToken(','));
m_jtxtJPOSDrawer3.setText(p.nextToken(','));
} else {
jcboMachinePrinter3.setSelectedItem(sparam);
jcboConnPrinter3.setSelectedItem(unifySerialInterface(p.nextToken(',')));
jcboSerialPrinter3.setSelectedItem(p.nextToken(','));
}
p = new StringParser(config.getProperty("machine.display"));
sparam = unifySerialInterface(p.nextToken(':'));
if ("serial".equals(sparam) || "file".equals(sparam)) {
jcboMachineDisplay.setSelectedItem("epson");
jcboConnDisplay.setSelectedItem(sparam);
jcboSerialDisplay.setSelectedItem(p.nextToken(','));
} else if ("javapos".equals(sparam)) {
jcboMachineDisplay.setSelectedItem(sparam);
m_jtxtJPOSName.setText(p.nextToken(','));
} else {
jcboMachineDisplay.setSelectedItem(sparam);
jcboConnDisplay.setSelectedItem(unifySerialInterface(p.nextToken(',')));
jcboSerialDisplay.setSelectedItem(p.nextToken(','));
}
p = new StringParser(config.getProperty("machine.scale"));
sparam = p.nextToken(':');
jcboMachineScale.setSelectedItem(sparam);
if ("dialog1".equals(sparam) || "samsungesp".equals(sparam)) {
jcboSerialScale.setSelectedItem(p.nextToken(','));
}
p = new StringParser(config.getProperty("machine.scanner"));
sparam = p.nextToken(':');
jcboMachineScanner.setSelectedItem(sparam);
if ("scanpal2".equals(sparam)) {
jcboSerialScanner.setSelectedItem(p.nextToken(','));
}
cboPrinters.setSelectedItem(config.getProperty("machine.printername"));
//is receipt printer
m_ReceiptPrinter.setSelected("true".equals(config.getProperty("machine.printer.receipt")));
dirty.setDirty(false);
}
public void saveProperties(AppConfig config) {
config.setProperty("machine.hostname", jtxtMachineHostname.getText());
LAFInfo laf = (LAFInfo) jcboLAF.getSelectedItem();
config.setProperty("swing.defaultlaf", laf == null
? System.getProperty("swing.defaultlaf", "javax.swing.plaf.metal.MetalLookAndFeel")
: laf.getClassName());
config.setProperty("machine.screenmode", comboValue(jcboMachineScreenmode.getSelectedItem()));
config.setProperty("machine.ticketsbag", comboValue(jcboTicketsBag.getSelectedItem()));
String sMachinePrinter = comboValue(jcboMachinePrinter.getSelectedItem());
if ("epson".equals(sMachinePrinter) || "tmu220".equals(sMachinePrinter) || "star".equals(sMachinePrinter) || "ithaca".equals(sMachinePrinter) || "surepos".equals(sMachinePrinter)) {
config.setProperty("machine.printer", sMachinePrinter + ":" + comboValue(jcboConnPrinter.getSelectedItem()) + "," + comboValue(jcboSerialPrinter.getSelectedItem()));
} else if ("javapos".equals(sMachinePrinter)) {
config.setProperty("machine.printer", sMachinePrinter + ":" + m_jtxtJPOSPrinter.getText() + "," + m_jtxtJPOSDrawer.getText());
} else {
config.setProperty("machine.printer", sMachinePrinter);
}
String sMachinePrinter2 = comboValue(jcboMachinePrinter2.getSelectedItem());
if ("epson".equals(sMachinePrinter2) || "tmu220".equals(sMachinePrinter2) || "star".equals(sMachinePrinter2) || "ithaca".equals(sMachinePrinter2) || "surepos".equals(sMachinePrinter2)) {
config.setProperty("machine.printer.2", sMachinePrinter2 + ":" + comboValue(jcboConnPrinter2.getSelectedItem()) + "," + comboValue(jcboSerialPrinter2.getSelectedItem()));
} else if ("javapos".equals(sMachinePrinter2)) {
config.setProperty("machine.printer.2", sMachinePrinter2 + ":" + m_jtxtJPOSPrinter2.getText() + "," + m_jtxtJPOSDrawer2.getText());
} else {
config.setProperty("machine.printer.2", sMachinePrinter2);
}
String sMachinePrinter3 = comboValue(jcboMachinePrinter3.getSelectedItem());
if ("epson".equals(sMachinePrinter3) || "tmu220".equals(sMachinePrinter3) || "star".equals(sMachinePrinter3) || "ithaca".equals(sMachinePrinter3) || "surepos".equals(sMachinePrinter3)) {
config.setProperty("machine.printer.3", sMachinePrinter3 + ":" + comboValue(jcboConnPrinter3.getSelectedItem()) + "," + comboValue(jcboSerialPrinter3.getSelectedItem()));
} else if ("javapos".equals(sMachinePrinter3)) {
config.setProperty("machine.printer.3", sMachinePrinter3 + ":" + m_jtxtJPOSPrinter3.getText() + "," + m_jtxtJPOSDrawer3.getText());
} else {
config.setProperty("machine.printer.3", sMachinePrinter3);
}
String sMachineDisplay = comboValue(jcboMachineDisplay.getSelectedItem());
if ("epson".equals(sMachineDisplay) || "ld200".equals(sMachineDisplay) || "surepos".equals(sMachineDisplay)) {
config.setProperty("machine.display", sMachineDisplay + ":" + comboValue(jcboConnDisplay.getSelectedItem()) + "," + comboValue(jcboSerialDisplay.getSelectedItem()));
} else if ("javapos".equals(sMachineDisplay)) {
config.setProperty("machine.display", sMachineDisplay + ":" + m_jtxtJPOSName.getText());
} else {
config.setProperty("machine.display", sMachineDisplay);
}
// La bascula
String sMachineScale = comboValue(jcboMachineScale.getSelectedItem());
if ("dialog1".equals(sMachineScale) || "samsungesp".equals(sMachineScale)) {
config.setProperty("machine.scale", sMachineScale + ":" + comboValue(jcboSerialScale.getSelectedItem()));
} else {
config.setProperty("machine.scale", sMachineScale);
}
// El scanner
String sMachineScanner = comboValue(jcboMachineScanner.getSelectedItem());
if ("scanpal2".equals(sMachineScanner)) {
config.setProperty("machine.scanner", sMachineScanner + ":" + comboValue(jcboSerialScanner.getSelectedItem()));
} else {
config.setProperty("machine.scanner", sMachineScanner);
}
config.setProperty("machine.printername", comboValue(cboPrinters.getSelectedItem()));
//is a receipt printer
config.setProperty("machine.printer.receipt", String.valueOf(m_ReceiptPrinter.isSelected()));
dirty.setDirty(false);
}
private String unifySerialInterface(String sparam) {
// for backward compatibility
return ("rxtx".equals(sparam))
? "serial"
: sparam;
}
private String comboValue(Object value) {
return value == null ? "" : value.toString();
}
private void changeLAF() {
final LAFInfo laf = (LAFInfo) jcboLAF.getSelectedItem();
if (laf != null && !laf.getClassName().equals(UIManager.getLookAndFeel().getClass().getName())) {
// The selected look and feel is different from the current look and feel.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
String lafname = laf.getClassName();
Object laf = Class.forName(lafname).newInstance();
if (laf instanceof LookAndFeel) {
UIManager.setLookAndFeel((LookAndFeel) laf);
} else if (laf instanceof SubstanceSkin) {
SubstanceLookAndFeel.setSkin((SubstanceSkin) laf);
}
SwingUtilities.updateComponentTreeUI(JPanelConfigGeneral.this.getTopLevelAncestor());
} catch (Exception e) {
}
}
});
}
}
private static class LAFInfo {
private String name;
private String classname;
public LAFInfo(String name, String classname) {
this.name = name;
this.classname = classname;
}
public String getName() {
return name;
}
public String getClassName() {
return classname;
}
@Override
public String toString() {
return name;
}
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel13 = new javax.swing.JPanel();
jLabel5 = new javax.swing.JLabel();
jtxtMachineHostname = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jcboLAF = new javax.swing.JComboBox();
jLabel6 = new javax.swing.JLabel();
jcboMachineScreenmode = new javax.swing.JComboBox();
jLabel16 = new javax.swing.JLabel();
jcboTicketsBag = new javax.swing.JComboBox();
jLabel15 = new javax.swing.JLabel();
jcboMachineDisplay = new javax.swing.JComboBox();
m_jDisplayParams = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
jPanel1 = new javax.swing.JPanel();
jlblConnDisplay = new javax.swing.JLabel();
jcboConnDisplay = new javax.swing.JComboBox();
jlblDisplayPort = new javax.swing.JLabel();
jcboSerialDisplay = new javax.swing.JComboBox();
jPanel3 = new javax.swing.JPanel();
jLabel20 = new javax.swing.JLabel();
m_jtxtJPOSName = new javax.swing.JTextField();
jLabel7 = new javax.swing.JLabel();
jcboMachinePrinter = new javax.swing.JComboBox();
m_jPrinterParams1 = new javax.swing.JPanel();
jPanel5 = new javax.swing.JPanel();
jPanel6 = new javax.swing.JPanel();
jlblConnPrinter = new javax.swing.JLabel();
jcboConnPrinter = new javax.swing.JComboBox();
jlblPrinterPort = new javax.swing.JLabel();
jcboSerialPrinter = new javax.swing.JComboBox();
jPanel4 = new javax.swing.JPanel();
jLabel21 = new javax.swing.JLabel();
m_jtxtJPOSPrinter = new javax.swing.JTextField();
m_jtxtJPOSDrawer = new javax.swing.JTextField();
jLabel24 = new javax.swing.JLabel();
jLabel18 = new javax.swing.JLabel();
jcboMachinePrinter2 = new javax.swing.JComboBox();
jLabel19 = new javax.swing.JLabel();
m_jPrinterParams2 = new javax.swing.JPanel();
jPanel7 = new javax.swing.JPanel();
jPanel8 = new javax.swing.JPanel();
jlblConnPrinter2 = new javax.swing.JLabel();
jcboConnPrinter2 = new javax.swing.JComboBox();
jlblPrinterPort2 = new javax.swing.JLabel();
jcboSerialPrinter2 = new javax.swing.JComboBox();
jPanel11 = new javax.swing.JPanel();
m_jtxtJPOSPrinter2 = new javax.swing.JTextField();
m_jtxtJPOSDrawer2 = new javax.swing.JTextField();
jLabel27 = new javax.swing.JLabel();
jLabel22 = new javax.swing.JLabel();
jcboMachinePrinter3 = new javax.swing.JComboBox();
jLabel25 = new javax.swing.JLabel();
jcboMachineScale = new javax.swing.JComboBox();
jLabel26 = new javax.swing.JLabel();
jcboMachineScanner = new javax.swing.JComboBox();
jLabel1 = new javax.swing.JLabel();
cboPrinters = new javax.swing.JComboBox();
m_jPrinterParams3 = new javax.swing.JPanel();
jPanel9 = new javax.swing.JPanel();
jPanel10 = new javax.swing.JPanel();
jlblConnPrinter3 = new javax.swing.JLabel();
jcboConnPrinter3 = new javax.swing.JComboBox();
jlblPrinterPort3 = new javax.swing.JLabel();
jcboSerialPrinter3 = new javax.swing.JComboBox();
jPanel12 = new javax.swing.JPanel();
m_jtxtJPOSPrinter3 = new javax.swing.JTextField();
m_jtxtJPOSDrawer3 = new javax.swing.JTextField();
jLabel28 = new javax.swing.JLabel();
jLabel23 = new javax.swing.JLabel();
m_jScaleParams = new javax.swing.JPanel();
jPanel16 = new javax.swing.JPanel();
jPanel17 = new javax.swing.JPanel();
jlblPrinterPort4 = new javax.swing.JLabel();
jcboSerialScale = new javax.swing.JComboBox();
m_jScannerParams = new javax.swing.JPanel();
jPanel24 = new javax.swing.JPanel();
jPanel19 = new javax.swing.JPanel();
jlblPrinterPort5 = new javax.swing.JLabel();
jcboSerialScanner = new javax.swing.JComboBox();
m_ReceiptPrinter = new javax.swing.JCheckBox();
jPanel13.setBorder(javax.swing.BorderFactory.createTitledBorder(AppLocal.getIntString("Label.CashMachine"))); // NOI18N
jLabel5.setText(AppLocal.getIntString("Label.MachineName")); // NOI18N
jLabel2.setText(AppLocal.getIntString("label.looknfeel")); // NOI18N
jLabel6.setText(AppLocal.getIntString("Label.MachineScreen")); // NOI18N
jLabel16.setText(AppLocal.getIntString("Label.Ticketsbag")); // NOI18N
jLabel15.setText(AppLocal.getIntString("Label.MachineDisplay")); // NOI18N
jcboMachineDisplay.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jcboMachineDisplayActionPerformed(evt);
}
});
m_jDisplayParams.setLayout(new java.awt.CardLayout());
m_jDisplayParams.add(jPanel2, "empty");
jlblConnDisplay.setText(AppLocal.getIntString("label.machinedisplayconn")); // NOI18N
jlblDisplayPort.setText(AppLocal.getIntString("label.machinedisplayport")); // NOI18N
jcboSerialDisplay.setEditable(true);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jlblConnDisplay, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboConnDisplay, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jlblDisplayPort, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboSerialDisplay, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(56, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jcboConnDisplay, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jlblDisplayPort)
.addComponent(jcboSerialDisplay, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jlblConnDisplay))
.addGap(59, 59, 59))
);
m_jDisplayParams.add(jPanel1, "comm");
jLabel20.setText(AppLocal.getIntString("Label.Name")); // NOI18N
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel20, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_jtxtJPOSName, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(270, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(m_jtxtJPOSName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel20))
.addGap(184, 184, 184))
);
m_jDisplayParams.add(jPanel3, "javapos");
jLabel7.setText(AppLocal.getIntString("Label.MachinePrinter")); // NOI18N
jcboMachinePrinter.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jcboMachinePrinterActionPerformed(evt);
}
});
m_jPrinterParams1.setLayout(new java.awt.CardLayout());
m_jPrinterParams1.add(jPanel5, "empty");
jlblConnPrinter.setText(AppLocal.getIntString("label.machinedisplayconn")); // NOI18N
jlblPrinterPort.setText(AppLocal.getIntString("label.machineprinterport")); // NOI18N
jcboSerialPrinter.setEditable(true);
javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
jPanel6.setLayout(jPanel6Layout);
jPanel6Layout.setHorizontalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jlblConnPrinter, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboConnPrinter, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jlblPrinterPort, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboSerialPrinter, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(56, Short.MAX_VALUE))
);
jPanel6Layout.setVerticalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jcboConnPrinter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jlblPrinterPort)
.addComponent(jcboSerialPrinter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jlblConnPrinter))
.addGap(195, 195, 195))
);
m_jPrinterParams1.add(jPanel6, "comm");
jLabel21.setText(AppLocal.getIntString("label.javapos.drawer")); // NOI18N
jLabel24.setText(AppLocal.getIntString("label.javapos.printer")); // NOI18N
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel24, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_jtxtJPOSPrinter, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel21, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_jtxtJPOSDrawer, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(56, Short.MAX_VALUE))
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(m_jtxtJPOSPrinter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel21)
.addComponent(m_jtxtJPOSDrawer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel24))
.addGap(184, 184, 184))
);
m_jPrinterParams1.add(jPanel4, "javapos");
jLabel18.setText(AppLocal.getIntString("Label.MachinePrinter2")); // NOI18N
jcboMachinePrinter2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jcboMachinePrinter2ActionPerformed(evt);
}
});
jLabel19.setText(AppLocal.getIntString("Label.MachinePrinter3")); // NOI18N
m_jPrinterParams2.setLayout(new java.awt.CardLayout());
m_jPrinterParams2.add(jPanel7, "empty");
jlblConnPrinter2.setText(AppLocal.getIntString("label.machinedisplayconn")); // NOI18N
jlblPrinterPort2.setText(AppLocal.getIntString("label.machineprinterport")); // NOI18N
jcboSerialPrinter2.setEditable(true);
javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8);
jPanel8.setLayout(jPanel8Layout);
jPanel8Layout.setHorizontalGroup(
jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jlblConnPrinter2, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboConnPrinter2, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jlblPrinterPort2, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboSerialPrinter2, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(56, Short.MAX_VALUE))
);
jPanel8Layout.setVerticalGroup(
jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jcboConnPrinter2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jlblPrinterPort2)
.addComponent(jcboSerialPrinter2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jlblConnPrinter2))
.addGap(205, 205, 205))
);
m_jPrinterParams2.add(jPanel8, "comm");
jLabel27.setText(AppLocal.getIntString("label.javapos.printer")); // NOI18N
jLabel22.setText(AppLocal.getIntString("label.javapos.drawer")); // NOI18N
javax.swing.GroupLayout jPanel11Layout = new javax.swing.GroupLayout(jPanel11);
jPanel11.setLayout(jPanel11Layout);
jPanel11Layout.setHorizontalGroup(
jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel11Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel27, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_jtxtJPOSPrinter2, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel22, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_jtxtJPOSDrawer2, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(56, Short.MAX_VALUE))
);
jPanel11Layout.setVerticalGroup(
jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel11Layout.createSequentialGroup()
.addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(m_jtxtJPOSPrinter2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel22)
.addComponent(m_jtxtJPOSDrawer2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel27))
.addGap(184, 184, 184))
);
m_jPrinterParams2.add(jPanel11, "javapos");
jcboMachinePrinter3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jcboMachinePrinter3ActionPerformed(evt);
}
});
jLabel25.setText(AppLocal.getIntString("label.scale")); // NOI18N
jcboMachineScale.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jcboMachineScaleActionPerformed(evt);
}
});
jLabel26.setText(AppLocal.getIntString("label.scanner")); // NOI18N
jcboMachineScanner.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jcboMachineScannerActionPerformed(evt);
}
});
jLabel1.setText(AppLocal.getIntString("label.reportsprinter")); // NOI18N
m_jPrinterParams3.setLayout(new java.awt.CardLayout());
m_jPrinterParams3.add(jPanel9, "empty");
jlblConnPrinter3.setText(AppLocal.getIntString("label.machinedisplayconn")); // NOI18N
jlblPrinterPort3.setText(AppLocal.getIntString("label.machineprinterport")); // NOI18N
jcboSerialPrinter3.setEditable(true);
javax.swing.GroupLayout jPanel10Layout = new javax.swing.GroupLayout(jPanel10);
jPanel10.setLayout(jPanel10Layout);
jPanel10Layout.setHorizontalGroup(
jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel10Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jlblConnPrinter3, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboConnPrinter3, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jlblPrinterPort3, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboSerialPrinter3, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(56, Short.MAX_VALUE))
);
jPanel10Layout.setVerticalGroup(
jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel10Layout.createSequentialGroup()
.addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jcboConnPrinter3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jlblPrinterPort3)
.addComponent(jcboSerialPrinter3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jlblConnPrinter3))
.addGap(125, 125, 125))
);
m_jPrinterParams3.add(jPanel10, "comm");
jLabel28.setText(AppLocal.getIntString("label.javapos.printer")); // NOI18N
jLabel23.setText(AppLocal.getIntString("label.javapos.drawer")); // NOI18N
javax.swing.GroupLayout jPanel12Layout = new javax.swing.GroupLayout(jPanel12);
jPanel12.setLayout(jPanel12Layout);
jPanel12Layout.setHorizontalGroup(
jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel12Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel28, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_jtxtJPOSPrinter3, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel23, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_jtxtJPOSDrawer3, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(36, Short.MAX_VALUE))
);
jPanel12Layout.setVerticalGroup(
jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel12Layout.createSequentialGroup()
.addGroup(jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(m_jtxtJPOSPrinter3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel23)
.addComponent(m_jtxtJPOSDrawer3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel28))
.addGap(224, 224, 224))
);
m_jPrinterParams3.add(jPanel12, "javapos");
m_jScaleParams.setLayout(new java.awt.CardLayout());
m_jScaleParams.add(jPanel16, "empty");
jlblPrinterPort4.setText(AppLocal.getIntString("label.machineprinterport")); // NOI18N
jcboSerialScale.setEditable(true);
javax.swing.GroupLayout jPanel17Layout = new javax.swing.GroupLayout(jPanel17);
jPanel17.setLayout(jPanel17Layout);
jPanel17Layout.setHorizontalGroup(
jPanel17Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel17Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jlblPrinterPort4, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboSerialScale, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(270, Short.MAX_VALUE))
);
jPanel17Layout.setVerticalGroup(
jPanel17Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel17Layout.createSequentialGroup()
.addGroup(jPanel17Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jcboSerialScale, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jlblPrinterPort4))
.addGap(135, 135, 135))
);
m_jScaleParams.add(jPanel17, "comm");
m_jScannerParams.setLayout(new java.awt.CardLayout());
m_jScannerParams.add(jPanel24, "empty");
jlblPrinterPort5.setText(AppLocal.getIntString("label.machineprinterport")); // NOI18N
jcboSerialScanner.setEditable(true);
javax.swing.GroupLayout jPanel19Layout = new javax.swing.GroupLayout(jPanel19);
jPanel19.setLayout(jPanel19Layout);
jPanel19Layout.setHorizontalGroup(
jPanel19Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel19Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jlblPrinterPort5, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboSerialScanner, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(270, Short.MAX_VALUE))
);
jPanel19Layout.setVerticalGroup(
jPanel19Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel19Layout.createSequentialGroup()
.addGroup(jPanel19Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jcboSerialScanner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jlblPrinterPort5))
.addGap(235, 235, 235))
);
m_jScannerParams.add(jPanel19, "comm");
- m_ReceiptPrinter.setText("Receipt printer");
+ m_ReceiptPrinter.setText(AppLocal.getIntString("label.receiptprinter")); // NOI18N
javax.swing.GroupLayout jPanel13Layout = new javax.swing.GroupLayout(jPanel13);
jPanel13.setLayout(jPanel13Layout);
jPanel13Layout.setHorizontalGroup(
jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jtxtMachineHostname, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboMachineScreenmode, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(jLabel16, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboTicketsBag, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(jLabel15, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboMachineDisplay, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_jDisplayParams, javax.swing.GroupLayout.DEFAULT_SIZE, 484, Short.MAX_VALUE))
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboLAF, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboMachinePrinter, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_jPrinterParams1, javax.swing.GroupLayout.DEFAULT_SIZE, 484, Short.MAX_VALUE))
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(jLabel18, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboMachinePrinter2, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_jPrinterParams2, javax.swing.GroupLayout.DEFAULT_SIZE, 484, Short.MAX_VALUE))
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(jLabel19, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboMachinePrinter3, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_jPrinterParams3, javax.swing.GroupLayout.DEFAULT_SIZE, 484, Short.MAX_VALUE))
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(jLabel25, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboMachineScale, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_jScaleParams, javax.swing.GroupLayout.DEFAULT_SIZE, 484, Short.MAX_VALUE))
.addGroup(jPanel13Layout.createSequentialGroup()
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(jLabel26, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboMachineScanner, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cboPrinters, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(m_ReceiptPrinter)
.addComponent(m_jScannerParams, javax.swing.GroupLayout.DEFAULT_SIZE, 484, Short.MAX_VALUE))))
.addContainerGap())
);
jPanel13Layout.setVerticalGroup(
jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(jtxtMachineHostname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(6, 6, 6)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jcboLAF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(jcboMachineScreenmode, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel16)
.addComponent(jcboTicketsBag, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel15)
.addComponent(jcboMachineDisplay, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(m_jDisplayParams, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(jcboMachinePrinter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(m_jPrinterParams1, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel18)
.addComponent(jcboMachinePrinter2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(m_jPrinterParams2, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel19)
.addComponent(jcboMachinePrinter3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(m_jPrinterParams3, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel25)
.addComponent(jcboMachineScale, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(m_jScaleParams, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createSequentialGroup()
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel26)
.addComponent(jcboMachineScanner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(cboPrinters, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(m_jScannerParams, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_ReceiptPrinter)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel13, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel13, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(20, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
private void jcboMachineScannerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcboMachineScannerActionPerformed
CardLayout cl = (CardLayout) (m_jScannerParams.getLayout());
if ("scanpal2".equals(jcboMachineScanner.getSelectedItem())) {
cl.show(m_jScannerParams, "comm");
} else {
cl.show(m_jScannerParams, "empty");
}
}//GEN-LAST:event_jcboMachineScannerActionPerformed
private void jcboMachineScaleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcboMachineScaleActionPerformed
CardLayout cl = (CardLayout) (m_jScaleParams.getLayout());
if ("dialog1".equals(jcboMachineScale.getSelectedItem()) || "samsungesp".equals(jcboMachineScale.getSelectedItem())) {
cl.show(m_jScaleParams, "comm");
} else {
cl.show(m_jScaleParams, "empty");
}
}//GEN-LAST:event_jcboMachineScaleActionPerformed
private void jcboMachinePrinter3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcboMachinePrinter3ActionPerformed
CardLayout cl = (CardLayout) (m_jPrinterParams3.getLayout());
if ("epson".equals(jcboMachinePrinter3.getSelectedItem()) || "tmu220".equals(jcboMachinePrinter3.getSelectedItem()) || "star".equals(jcboMachinePrinter3.getSelectedItem()) || "ithaca".equals(jcboMachinePrinter3.getSelectedItem()) || "surepos".equals(jcboMachinePrinter3.getSelectedItem())) {
cl.show(m_jPrinterParams3, "comm");
} else if ("javapos".equals(jcboMachinePrinter3.getSelectedItem())) {
cl.show(m_jPrinterParams3, "javapos");
} else {
cl.show(m_jPrinterParams3, "empty");
}
}//GEN-LAST:event_jcboMachinePrinter3ActionPerformed
private void jcboMachinePrinter2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcboMachinePrinter2ActionPerformed
CardLayout cl = (CardLayout) (m_jPrinterParams2.getLayout());
if ("epson".equals(jcboMachinePrinter2.getSelectedItem()) || "tmu220".equals(jcboMachinePrinter2.getSelectedItem()) || "star".equals(jcboMachinePrinter2.getSelectedItem()) || "ithaca".equals(jcboMachinePrinter2.getSelectedItem()) || "surepos".equals(jcboMachinePrinter2.getSelectedItem())) {
cl.show(m_jPrinterParams2, "comm");
} else if ("javapos".equals(jcboMachinePrinter2.getSelectedItem())) {
cl.show(m_jPrinterParams2, "javapos");
} else {
cl.show(m_jPrinterParams2, "empty");
}
}//GEN-LAST:event_jcboMachinePrinter2ActionPerformed
private void jcboMachineDisplayActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcboMachineDisplayActionPerformed
CardLayout cl = (CardLayout) (m_jDisplayParams.getLayout());
if ("epson".equals(jcboMachineDisplay.getSelectedItem()) || "ld200".equals(jcboMachineDisplay.getSelectedItem()) || "surepos".equals(jcboMachineDisplay.getSelectedItem())) {
cl.show(m_jDisplayParams, "comm");
} else if ("javapos".equals(jcboMachineDisplay.getSelectedItem())) {
cl.show(m_jDisplayParams, "javapos");
} else {
cl.show(m_jDisplayParams, "empty");
}
}//GEN-LAST:event_jcboMachineDisplayActionPerformed
private void jcboMachinePrinterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcboMachinePrinterActionPerformed
CardLayout cl = (CardLayout) (m_jPrinterParams1.getLayout());
if ("epson".equals(jcboMachinePrinter.getSelectedItem()) || "tmu220".equals(jcboMachinePrinter.getSelectedItem()) || "star".equals(jcboMachinePrinter.getSelectedItem()) || "ithaca".equals(jcboMachinePrinter.getSelectedItem()) || "surepos".equals(jcboMachinePrinter.getSelectedItem())) {
cl.show(m_jPrinterParams1, "comm");
} else if ("javapos".equals(jcboMachinePrinter.getSelectedItem())) {
cl.show(m_jPrinterParams1, "javapos");
} else {
cl.show(m_jPrinterParams1, "empty");
}
}//GEN-LAST:event_jcboMachinePrinterActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JComboBox cboPrinters;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel18;
private javax.swing.JLabel jLabel19;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel20;
private javax.swing.JLabel jLabel21;
private javax.swing.JLabel jLabel22;
private javax.swing.JLabel jLabel23;
private javax.swing.JLabel jLabel24;
private javax.swing.JLabel jLabel25;
private javax.swing.JLabel jLabel26;
private javax.swing.JLabel jLabel27;
private javax.swing.JLabel jLabel28;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel10;
private javax.swing.JPanel jPanel11;
private javax.swing.JPanel jPanel12;
private javax.swing.JPanel jPanel13;
private javax.swing.JPanel jPanel16;
private javax.swing.JPanel jPanel17;
private javax.swing.JPanel jPanel19;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel24;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JPanel jPanel6;
private javax.swing.JPanel jPanel7;
private javax.swing.JPanel jPanel8;
private javax.swing.JPanel jPanel9;
private javax.swing.JComboBox jcboConnDisplay;
private javax.swing.JComboBox jcboConnPrinter;
private javax.swing.JComboBox jcboConnPrinter2;
private javax.swing.JComboBox jcboConnPrinter3;
private javax.swing.JComboBox jcboLAF;
private javax.swing.JComboBox jcboMachineDisplay;
private javax.swing.JComboBox jcboMachinePrinter;
private javax.swing.JComboBox jcboMachinePrinter2;
private javax.swing.JComboBox jcboMachinePrinter3;
private javax.swing.JComboBox jcboMachineScale;
private javax.swing.JComboBox jcboMachineScanner;
private javax.swing.JComboBox jcboMachineScreenmode;
private javax.swing.JComboBox jcboSerialDisplay;
private javax.swing.JComboBox jcboSerialPrinter;
private javax.swing.JComboBox jcboSerialPrinter2;
private javax.swing.JComboBox jcboSerialPrinter3;
private javax.swing.JComboBox jcboSerialScale;
private javax.swing.JComboBox jcboSerialScanner;
private javax.swing.JComboBox jcboTicketsBag;
private javax.swing.JLabel jlblConnDisplay;
private javax.swing.JLabel jlblConnPrinter;
private javax.swing.JLabel jlblConnPrinter2;
private javax.swing.JLabel jlblConnPrinter3;
private javax.swing.JLabel jlblDisplayPort;
private javax.swing.JLabel jlblPrinterPort;
private javax.swing.JLabel jlblPrinterPort2;
private javax.swing.JLabel jlblPrinterPort3;
private javax.swing.JLabel jlblPrinterPort4;
private javax.swing.JLabel jlblPrinterPort5;
private javax.swing.JTextField jtxtMachineHostname;
private javax.swing.JCheckBox m_ReceiptPrinter;
private javax.swing.JPanel m_jDisplayParams;
private javax.swing.JPanel m_jPrinterParams1;
private javax.swing.JPanel m_jPrinterParams2;
private javax.swing.JPanel m_jPrinterParams3;
private javax.swing.JPanel m_jScaleParams;
private javax.swing.JPanel m_jScannerParams;
private javax.swing.JTextField m_jtxtJPOSDrawer;
private javax.swing.JTextField m_jtxtJPOSDrawer2;
private javax.swing.JTextField m_jtxtJPOSDrawer3;
private javax.swing.JTextField m_jtxtJPOSName;
private javax.swing.JTextField m_jtxtJPOSPrinter;
private javax.swing.JTextField m_jtxtJPOSPrinter2;
private javax.swing.JTextField m_jtxtJPOSPrinter3;
// End of variables declaration//GEN-END:variables
}
| true | true | private void initComponents() {
jPanel13 = new javax.swing.JPanel();
jLabel5 = new javax.swing.JLabel();
jtxtMachineHostname = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jcboLAF = new javax.swing.JComboBox();
jLabel6 = new javax.swing.JLabel();
jcboMachineScreenmode = new javax.swing.JComboBox();
jLabel16 = new javax.swing.JLabel();
jcboTicketsBag = new javax.swing.JComboBox();
jLabel15 = new javax.swing.JLabel();
jcboMachineDisplay = new javax.swing.JComboBox();
m_jDisplayParams = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
jPanel1 = new javax.swing.JPanel();
jlblConnDisplay = new javax.swing.JLabel();
jcboConnDisplay = new javax.swing.JComboBox();
jlblDisplayPort = new javax.swing.JLabel();
jcboSerialDisplay = new javax.swing.JComboBox();
jPanel3 = new javax.swing.JPanel();
jLabel20 = new javax.swing.JLabel();
m_jtxtJPOSName = new javax.swing.JTextField();
jLabel7 = new javax.swing.JLabel();
jcboMachinePrinter = new javax.swing.JComboBox();
m_jPrinterParams1 = new javax.swing.JPanel();
jPanel5 = new javax.swing.JPanel();
jPanel6 = new javax.swing.JPanel();
jlblConnPrinter = new javax.swing.JLabel();
jcboConnPrinter = new javax.swing.JComboBox();
jlblPrinterPort = new javax.swing.JLabel();
jcboSerialPrinter = new javax.swing.JComboBox();
jPanel4 = new javax.swing.JPanel();
jLabel21 = new javax.swing.JLabel();
m_jtxtJPOSPrinter = new javax.swing.JTextField();
m_jtxtJPOSDrawer = new javax.swing.JTextField();
jLabel24 = new javax.swing.JLabel();
jLabel18 = new javax.swing.JLabel();
jcboMachinePrinter2 = new javax.swing.JComboBox();
jLabel19 = new javax.swing.JLabel();
m_jPrinterParams2 = new javax.swing.JPanel();
jPanel7 = new javax.swing.JPanel();
jPanel8 = new javax.swing.JPanel();
jlblConnPrinter2 = new javax.swing.JLabel();
jcboConnPrinter2 = new javax.swing.JComboBox();
jlblPrinterPort2 = new javax.swing.JLabel();
jcboSerialPrinter2 = new javax.swing.JComboBox();
jPanel11 = new javax.swing.JPanel();
m_jtxtJPOSPrinter2 = new javax.swing.JTextField();
m_jtxtJPOSDrawer2 = new javax.swing.JTextField();
jLabel27 = new javax.swing.JLabel();
jLabel22 = new javax.swing.JLabel();
jcboMachinePrinter3 = new javax.swing.JComboBox();
jLabel25 = new javax.swing.JLabel();
jcboMachineScale = new javax.swing.JComboBox();
jLabel26 = new javax.swing.JLabel();
jcboMachineScanner = new javax.swing.JComboBox();
jLabel1 = new javax.swing.JLabel();
cboPrinters = new javax.swing.JComboBox();
m_jPrinterParams3 = new javax.swing.JPanel();
jPanel9 = new javax.swing.JPanel();
jPanel10 = new javax.swing.JPanel();
jlblConnPrinter3 = new javax.swing.JLabel();
jcboConnPrinter3 = new javax.swing.JComboBox();
jlblPrinterPort3 = new javax.swing.JLabel();
jcboSerialPrinter3 = new javax.swing.JComboBox();
jPanel12 = new javax.swing.JPanel();
m_jtxtJPOSPrinter3 = new javax.swing.JTextField();
m_jtxtJPOSDrawer3 = new javax.swing.JTextField();
jLabel28 = new javax.swing.JLabel();
jLabel23 = new javax.swing.JLabel();
m_jScaleParams = new javax.swing.JPanel();
jPanel16 = new javax.swing.JPanel();
jPanel17 = new javax.swing.JPanel();
jlblPrinterPort4 = new javax.swing.JLabel();
jcboSerialScale = new javax.swing.JComboBox();
m_jScannerParams = new javax.swing.JPanel();
jPanel24 = new javax.swing.JPanel();
jPanel19 = new javax.swing.JPanel();
jlblPrinterPort5 = new javax.swing.JLabel();
jcboSerialScanner = new javax.swing.JComboBox();
m_ReceiptPrinter = new javax.swing.JCheckBox();
jPanel13.setBorder(javax.swing.BorderFactory.createTitledBorder(AppLocal.getIntString("Label.CashMachine"))); // NOI18N
jLabel5.setText(AppLocal.getIntString("Label.MachineName")); // NOI18N
jLabel2.setText(AppLocal.getIntString("label.looknfeel")); // NOI18N
jLabel6.setText(AppLocal.getIntString("Label.MachineScreen")); // NOI18N
jLabel16.setText(AppLocal.getIntString("Label.Ticketsbag")); // NOI18N
jLabel15.setText(AppLocal.getIntString("Label.MachineDisplay")); // NOI18N
jcboMachineDisplay.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jcboMachineDisplayActionPerformed(evt);
}
});
m_jDisplayParams.setLayout(new java.awt.CardLayout());
m_jDisplayParams.add(jPanel2, "empty");
jlblConnDisplay.setText(AppLocal.getIntString("label.machinedisplayconn")); // NOI18N
jlblDisplayPort.setText(AppLocal.getIntString("label.machinedisplayport")); // NOI18N
jcboSerialDisplay.setEditable(true);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jlblConnDisplay, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboConnDisplay, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jlblDisplayPort, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboSerialDisplay, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(56, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jcboConnDisplay, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jlblDisplayPort)
.addComponent(jcboSerialDisplay, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jlblConnDisplay))
.addGap(59, 59, 59))
);
m_jDisplayParams.add(jPanel1, "comm");
jLabel20.setText(AppLocal.getIntString("Label.Name")); // NOI18N
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel20, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_jtxtJPOSName, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(270, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(m_jtxtJPOSName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel20))
.addGap(184, 184, 184))
);
m_jDisplayParams.add(jPanel3, "javapos");
jLabel7.setText(AppLocal.getIntString("Label.MachinePrinter")); // NOI18N
jcboMachinePrinter.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jcboMachinePrinterActionPerformed(evt);
}
});
m_jPrinterParams1.setLayout(new java.awt.CardLayout());
m_jPrinterParams1.add(jPanel5, "empty");
jlblConnPrinter.setText(AppLocal.getIntString("label.machinedisplayconn")); // NOI18N
jlblPrinterPort.setText(AppLocal.getIntString("label.machineprinterport")); // NOI18N
jcboSerialPrinter.setEditable(true);
javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
jPanel6.setLayout(jPanel6Layout);
jPanel6Layout.setHorizontalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jlblConnPrinter, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboConnPrinter, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jlblPrinterPort, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboSerialPrinter, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(56, Short.MAX_VALUE))
);
jPanel6Layout.setVerticalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jcboConnPrinter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jlblPrinterPort)
.addComponent(jcboSerialPrinter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jlblConnPrinter))
.addGap(195, 195, 195))
);
m_jPrinterParams1.add(jPanel6, "comm");
jLabel21.setText(AppLocal.getIntString("label.javapos.drawer")); // NOI18N
jLabel24.setText(AppLocal.getIntString("label.javapos.printer")); // NOI18N
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel24, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_jtxtJPOSPrinter, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel21, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_jtxtJPOSDrawer, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(56, Short.MAX_VALUE))
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(m_jtxtJPOSPrinter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel21)
.addComponent(m_jtxtJPOSDrawer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel24))
.addGap(184, 184, 184))
);
m_jPrinterParams1.add(jPanel4, "javapos");
jLabel18.setText(AppLocal.getIntString("Label.MachinePrinter2")); // NOI18N
jcboMachinePrinter2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jcboMachinePrinter2ActionPerformed(evt);
}
});
jLabel19.setText(AppLocal.getIntString("Label.MachinePrinter3")); // NOI18N
m_jPrinterParams2.setLayout(new java.awt.CardLayout());
m_jPrinterParams2.add(jPanel7, "empty");
jlblConnPrinter2.setText(AppLocal.getIntString("label.machinedisplayconn")); // NOI18N
jlblPrinterPort2.setText(AppLocal.getIntString("label.machineprinterport")); // NOI18N
jcboSerialPrinter2.setEditable(true);
javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8);
jPanel8.setLayout(jPanel8Layout);
jPanel8Layout.setHorizontalGroup(
jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jlblConnPrinter2, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboConnPrinter2, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jlblPrinterPort2, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboSerialPrinter2, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(56, Short.MAX_VALUE))
);
jPanel8Layout.setVerticalGroup(
jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jcboConnPrinter2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jlblPrinterPort2)
.addComponent(jcboSerialPrinter2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jlblConnPrinter2))
.addGap(205, 205, 205))
);
m_jPrinterParams2.add(jPanel8, "comm");
jLabel27.setText(AppLocal.getIntString("label.javapos.printer")); // NOI18N
jLabel22.setText(AppLocal.getIntString("label.javapos.drawer")); // NOI18N
javax.swing.GroupLayout jPanel11Layout = new javax.swing.GroupLayout(jPanel11);
jPanel11.setLayout(jPanel11Layout);
jPanel11Layout.setHorizontalGroup(
jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel11Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel27, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_jtxtJPOSPrinter2, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel22, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_jtxtJPOSDrawer2, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(56, Short.MAX_VALUE))
);
jPanel11Layout.setVerticalGroup(
jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel11Layout.createSequentialGroup()
.addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(m_jtxtJPOSPrinter2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel22)
.addComponent(m_jtxtJPOSDrawer2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel27))
.addGap(184, 184, 184))
);
m_jPrinterParams2.add(jPanel11, "javapos");
jcboMachinePrinter3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jcboMachinePrinter3ActionPerformed(evt);
}
});
jLabel25.setText(AppLocal.getIntString("label.scale")); // NOI18N
jcboMachineScale.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jcboMachineScaleActionPerformed(evt);
}
});
jLabel26.setText(AppLocal.getIntString("label.scanner")); // NOI18N
jcboMachineScanner.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jcboMachineScannerActionPerformed(evt);
}
});
jLabel1.setText(AppLocal.getIntString("label.reportsprinter")); // NOI18N
m_jPrinterParams3.setLayout(new java.awt.CardLayout());
m_jPrinterParams3.add(jPanel9, "empty");
jlblConnPrinter3.setText(AppLocal.getIntString("label.machinedisplayconn")); // NOI18N
jlblPrinterPort3.setText(AppLocal.getIntString("label.machineprinterport")); // NOI18N
jcboSerialPrinter3.setEditable(true);
javax.swing.GroupLayout jPanel10Layout = new javax.swing.GroupLayout(jPanel10);
jPanel10.setLayout(jPanel10Layout);
jPanel10Layout.setHorizontalGroup(
jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel10Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jlblConnPrinter3, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboConnPrinter3, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jlblPrinterPort3, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboSerialPrinter3, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(56, Short.MAX_VALUE))
);
jPanel10Layout.setVerticalGroup(
jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel10Layout.createSequentialGroup()
.addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jcboConnPrinter3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jlblPrinterPort3)
.addComponent(jcboSerialPrinter3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jlblConnPrinter3))
.addGap(125, 125, 125))
);
m_jPrinterParams3.add(jPanel10, "comm");
jLabel28.setText(AppLocal.getIntString("label.javapos.printer")); // NOI18N
jLabel23.setText(AppLocal.getIntString("label.javapos.drawer")); // NOI18N
javax.swing.GroupLayout jPanel12Layout = new javax.swing.GroupLayout(jPanel12);
jPanel12.setLayout(jPanel12Layout);
jPanel12Layout.setHorizontalGroup(
jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel12Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel28, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_jtxtJPOSPrinter3, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel23, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_jtxtJPOSDrawer3, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(36, Short.MAX_VALUE))
);
jPanel12Layout.setVerticalGroup(
jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel12Layout.createSequentialGroup()
.addGroup(jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(m_jtxtJPOSPrinter3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel23)
.addComponent(m_jtxtJPOSDrawer3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel28))
.addGap(224, 224, 224))
);
m_jPrinterParams3.add(jPanel12, "javapos");
m_jScaleParams.setLayout(new java.awt.CardLayout());
m_jScaleParams.add(jPanel16, "empty");
jlblPrinterPort4.setText(AppLocal.getIntString("label.machineprinterport")); // NOI18N
jcboSerialScale.setEditable(true);
javax.swing.GroupLayout jPanel17Layout = new javax.swing.GroupLayout(jPanel17);
jPanel17.setLayout(jPanel17Layout);
jPanel17Layout.setHorizontalGroup(
jPanel17Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel17Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jlblPrinterPort4, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboSerialScale, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(270, Short.MAX_VALUE))
);
jPanel17Layout.setVerticalGroup(
jPanel17Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel17Layout.createSequentialGroup()
.addGroup(jPanel17Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jcboSerialScale, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jlblPrinterPort4))
.addGap(135, 135, 135))
);
m_jScaleParams.add(jPanel17, "comm");
m_jScannerParams.setLayout(new java.awt.CardLayout());
m_jScannerParams.add(jPanel24, "empty");
jlblPrinterPort5.setText(AppLocal.getIntString("label.machineprinterport")); // NOI18N
jcboSerialScanner.setEditable(true);
javax.swing.GroupLayout jPanel19Layout = new javax.swing.GroupLayout(jPanel19);
jPanel19.setLayout(jPanel19Layout);
jPanel19Layout.setHorizontalGroup(
jPanel19Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel19Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jlblPrinterPort5, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboSerialScanner, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(270, Short.MAX_VALUE))
);
jPanel19Layout.setVerticalGroup(
jPanel19Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel19Layout.createSequentialGroup()
.addGroup(jPanel19Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jcboSerialScanner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jlblPrinterPort5))
.addGap(235, 235, 235))
);
m_jScannerParams.add(jPanel19, "comm");
m_ReceiptPrinter.setText("Receipt printer");
javax.swing.GroupLayout jPanel13Layout = new javax.swing.GroupLayout(jPanel13);
jPanel13.setLayout(jPanel13Layout);
jPanel13Layout.setHorizontalGroup(
jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jtxtMachineHostname, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboMachineScreenmode, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(jLabel16, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboTicketsBag, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(jLabel15, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboMachineDisplay, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_jDisplayParams, javax.swing.GroupLayout.DEFAULT_SIZE, 484, Short.MAX_VALUE))
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboLAF, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboMachinePrinter, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_jPrinterParams1, javax.swing.GroupLayout.DEFAULT_SIZE, 484, Short.MAX_VALUE))
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(jLabel18, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboMachinePrinter2, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_jPrinterParams2, javax.swing.GroupLayout.DEFAULT_SIZE, 484, Short.MAX_VALUE))
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(jLabel19, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboMachinePrinter3, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_jPrinterParams3, javax.swing.GroupLayout.DEFAULT_SIZE, 484, Short.MAX_VALUE))
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(jLabel25, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboMachineScale, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_jScaleParams, javax.swing.GroupLayout.DEFAULT_SIZE, 484, Short.MAX_VALUE))
.addGroup(jPanel13Layout.createSequentialGroup()
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(jLabel26, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboMachineScanner, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cboPrinters, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(m_ReceiptPrinter)
.addComponent(m_jScannerParams, javax.swing.GroupLayout.DEFAULT_SIZE, 484, Short.MAX_VALUE))))
.addContainerGap())
);
jPanel13Layout.setVerticalGroup(
jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(jtxtMachineHostname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(6, 6, 6)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jcboLAF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(jcboMachineScreenmode, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel16)
.addComponent(jcboTicketsBag, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel15)
.addComponent(jcboMachineDisplay, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(m_jDisplayParams, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(jcboMachinePrinter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(m_jPrinterParams1, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel18)
.addComponent(jcboMachinePrinter2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(m_jPrinterParams2, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel19)
.addComponent(jcboMachinePrinter3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(m_jPrinterParams3, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel25)
.addComponent(jcboMachineScale, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(m_jScaleParams, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createSequentialGroup()
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel26)
.addComponent(jcboMachineScanner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(cboPrinters, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(m_jScannerParams, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_ReceiptPrinter)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel13, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel13, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(20, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
| private void initComponents() {
jPanel13 = new javax.swing.JPanel();
jLabel5 = new javax.swing.JLabel();
jtxtMachineHostname = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jcboLAF = new javax.swing.JComboBox();
jLabel6 = new javax.swing.JLabel();
jcboMachineScreenmode = new javax.swing.JComboBox();
jLabel16 = new javax.swing.JLabel();
jcboTicketsBag = new javax.swing.JComboBox();
jLabel15 = new javax.swing.JLabel();
jcboMachineDisplay = new javax.swing.JComboBox();
m_jDisplayParams = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
jPanel1 = new javax.swing.JPanel();
jlblConnDisplay = new javax.swing.JLabel();
jcboConnDisplay = new javax.swing.JComboBox();
jlblDisplayPort = new javax.swing.JLabel();
jcboSerialDisplay = new javax.swing.JComboBox();
jPanel3 = new javax.swing.JPanel();
jLabel20 = new javax.swing.JLabel();
m_jtxtJPOSName = new javax.swing.JTextField();
jLabel7 = new javax.swing.JLabel();
jcboMachinePrinter = new javax.swing.JComboBox();
m_jPrinterParams1 = new javax.swing.JPanel();
jPanel5 = new javax.swing.JPanel();
jPanel6 = new javax.swing.JPanel();
jlblConnPrinter = new javax.swing.JLabel();
jcboConnPrinter = new javax.swing.JComboBox();
jlblPrinterPort = new javax.swing.JLabel();
jcboSerialPrinter = new javax.swing.JComboBox();
jPanel4 = new javax.swing.JPanel();
jLabel21 = new javax.swing.JLabel();
m_jtxtJPOSPrinter = new javax.swing.JTextField();
m_jtxtJPOSDrawer = new javax.swing.JTextField();
jLabel24 = new javax.swing.JLabel();
jLabel18 = new javax.swing.JLabel();
jcboMachinePrinter2 = new javax.swing.JComboBox();
jLabel19 = new javax.swing.JLabel();
m_jPrinterParams2 = new javax.swing.JPanel();
jPanel7 = new javax.swing.JPanel();
jPanel8 = new javax.swing.JPanel();
jlblConnPrinter2 = new javax.swing.JLabel();
jcboConnPrinter2 = new javax.swing.JComboBox();
jlblPrinterPort2 = new javax.swing.JLabel();
jcboSerialPrinter2 = new javax.swing.JComboBox();
jPanel11 = new javax.swing.JPanel();
m_jtxtJPOSPrinter2 = new javax.swing.JTextField();
m_jtxtJPOSDrawer2 = new javax.swing.JTextField();
jLabel27 = new javax.swing.JLabel();
jLabel22 = new javax.swing.JLabel();
jcboMachinePrinter3 = new javax.swing.JComboBox();
jLabel25 = new javax.swing.JLabel();
jcboMachineScale = new javax.swing.JComboBox();
jLabel26 = new javax.swing.JLabel();
jcboMachineScanner = new javax.swing.JComboBox();
jLabel1 = new javax.swing.JLabel();
cboPrinters = new javax.swing.JComboBox();
m_jPrinterParams3 = new javax.swing.JPanel();
jPanel9 = new javax.swing.JPanel();
jPanel10 = new javax.swing.JPanel();
jlblConnPrinter3 = new javax.swing.JLabel();
jcboConnPrinter3 = new javax.swing.JComboBox();
jlblPrinterPort3 = new javax.swing.JLabel();
jcboSerialPrinter3 = new javax.swing.JComboBox();
jPanel12 = new javax.swing.JPanel();
m_jtxtJPOSPrinter3 = new javax.swing.JTextField();
m_jtxtJPOSDrawer3 = new javax.swing.JTextField();
jLabel28 = new javax.swing.JLabel();
jLabel23 = new javax.swing.JLabel();
m_jScaleParams = new javax.swing.JPanel();
jPanel16 = new javax.swing.JPanel();
jPanel17 = new javax.swing.JPanel();
jlblPrinterPort4 = new javax.swing.JLabel();
jcboSerialScale = new javax.swing.JComboBox();
m_jScannerParams = new javax.swing.JPanel();
jPanel24 = new javax.swing.JPanel();
jPanel19 = new javax.swing.JPanel();
jlblPrinterPort5 = new javax.swing.JLabel();
jcboSerialScanner = new javax.swing.JComboBox();
m_ReceiptPrinter = new javax.swing.JCheckBox();
jPanel13.setBorder(javax.swing.BorderFactory.createTitledBorder(AppLocal.getIntString("Label.CashMachine"))); // NOI18N
jLabel5.setText(AppLocal.getIntString("Label.MachineName")); // NOI18N
jLabel2.setText(AppLocal.getIntString("label.looknfeel")); // NOI18N
jLabel6.setText(AppLocal.getIntString("Label.MachineScreen")); // NOI18N
jLabel16.setText(AppLocal.getIntString("Label.Ticketsbag")); // NOI18N
jLabel15.setText(AppLocal.getIntString("Label.MachineDisplay")); // NOI18N
jcboMachineDisplay.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jcboMachineDisplayActionPerformed(evt);
}
});
m_jDisplayParams.setLayout(new java.awt.CardLayout());
m_jDisplayParams.add(jPanel2, "empty");
jlblConnDisplay.setText(AppLocal.getIntString("label.machinedisplayconn")); // NOI18N
jlblDisplayPort.setText(AppLocal.getIntString("label.machinedisplayport")); // NOI18N
jcboSerialDisplay.setEditable(true);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jlblConnDisplay, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboConnDisplay, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jlblDisplayPort, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboSerialDisplay, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(56, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jcboConnDisplay, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jlblDisplayPort)
.addComponent(jcboSerialDisplay, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jlblConnDisplay))
.addGap(59, 59, 59))
);
m_jDisplayParams.add(jPanel1, "comm");
jLabel20.setText(AppLocal.getIntString("Label.Name")); // NOI18N
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel20, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_jtxtJPOSName, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(270, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(m_jtxtJPOSName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel20))
.addGap(184, 184, 184))
);
m_jDisplayParams.add(jPanel3, "javapos");
jLabel7.setText(AppLocal.getIntString("Label.MachinePrinter")); // NOI18N
jcboMachinePrinter.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jcboMachinePrinterActionPerformed(evt);
}
});
m_jPrinterParams1.setLayout(new java.awt.CardLayout());
m_jPrinterParams1.add(jPanel5, "empty");
jlblConnPrinter.setText(AppLocal.getIntString("label.machinedisplayconn")); // NOI18N
jlblPrinterPort.setText(AppLocal.getIntString("label.machineprinterport")); // NOI18N
jcboSerialPrinter.setEditable(true);
javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
jPanel6.setLayout(jPanel6Layout);
jPanel6Layout.setHorizontalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jlblConnPrinter, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboConnPrinter, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jlblPrinterPort, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboSerialPrinter, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(56, Short.MAX_VALUE))
);
jPanel6Layout.setVerticalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jcboConnPrinter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jlblPrinterPort)
.addComponent(jcboSerialPrinter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jlblConnPrinter))
.addGap(195, 195, 195))
);
m_jPrinterParams1.add(jPanel6, "comm");
jLabel21.setText(AppLocal.getIntString("label.javapos.drawer")); // NOI18N
jLabel24.setText(AppLocal.getIntString("label.javapos.printer")); // NOI18N
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel24, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_jtxtJPOSPrinter, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel21, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_jtxtJPOSDrawer, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(56, Short.MAX_VALUE))
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(m_jtxtJPOSPrinter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel21)
.addComponent(m_jtxtJPOSDrawer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel24))
.addGap(184, 184, 184))
);
m_jPrinterParams1.add(jPanel4, "javapos");
jLabel18.setText(AppLocal.getIntString("Label.MachinePrinter2")); // NOI18N
jcboMachinePrinter2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jcboMachinePrinter2ActionPerformed(evt);
}
});
jLabel19.setText(AppLocal.getIntString("Label.MachinePrinter3")); // NOI18N
m_jPrinterParams2.setLayout(new java.awt.CardLayout());
m_jPrinterParams2.add(jPanel7, "empty");
jlblConnPrinter2.setText(AppLocal.getIntString("label.machinedisplayconn")); // NOI18N
jlblPrinterPort2.setText(AppLocal.getIntString("label.machineprinterport")); // NOI18N
jcboSerialPrinter2.setEditable(true);
javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8);
jPanel8.setLayout(jPanel8Layout);
jPanel8Layout.setHorizontalGroup(
jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jlblConnPrinter2, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboConnPrinter2, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jlblPrinterPort2, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboSerialPrinter2, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(56, Short.MAX_VALUE))
);
jPanel8Layout.setVerticalGroup(
jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jcboConnPrinter2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jlblPrinterPort2)
.addComponent(jcboSerialPrinter2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jlblConnPrinter2))
.addGap(205, 205, 205))
);
m_jPrinterParams2.add(jPanel8, "comm");
jLabel27.setText(AppLocal.getIntString("label.javapos.printer")); // NOI18N
jLabel22.setText(AppLocal.getIntString("label.javapos.drawer")); // NOI18N
javax.swing.GroupLayout jPanel11Layout = new javax.swing.GroupLayout(jPanel11);
jPanel11.setLayout(jPanel11Layout);
jPanel11Layout.setHorizontalGroup(
jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel11Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel27, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_jtxtJPOSPrinter2, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel22, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_jtxtJPOSDrawer2, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(56, Short.MAX_VALUE))
);
jPanel11Layout.setVerticalGroup(
jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel11Layout.createSequentialGroup()
.addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(m_jtxtJPOSPrinter2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel22)
.addComponent(m_jtxtJPOSDrawer2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel27))
.addGap(184, 184, 184))
);
m_jPrinterParams2.add(jPanel11, "javapos");
jcboMachinePrinter3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jcboMachinePrinter3ActionPerformed(evt);
}
});
jLabel25.setText(AppLocal.getIntString("label.scale")); // NOI18N
jcboMachineScale.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jcboMachineScaleActionPerformed(evt);
}
});
jLabel26.setText(AppLocal.getIntString("label.scanner")); // NOI18N
jcboMachineScanner.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jcboMachineScannerActionPerformed(evt);
}
});
jLabel1.setText(AppLocal.getIntString("label.reportsprinter")); // NOI18N
m_jPrinterParams3.setLayout(new java.awt.CardLayout());
m_jPrinterParams3.add(jPanel9, "empty");
jlblConnPrinter3.setText(AppLocal.getIntString("label.machinedisplayconn")); // NOI18N
jlblPrinterPort3.setText(AppLocal.getIntString("label.machineprinterport")); // NOI18N
jcboSerialPrinter3.setEditable(true);
javax.swing.GroupLayout jPanel10Layout = new javax.swing.GroupLayout(jPanel10);
jPanel10.setLayout(jPanel10Layout);
jPanel10Layout.setHorizontalGroup(
jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel10Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jlblConnPrinter3, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboConnPrinter3, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jlblPrinterPort3, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboSerialPrinter3, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(56, Short.MAX_VALUE))
);
jPanel10Layout.setVerticalGroup(
jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel10Layout.createSequentialGroup()
.addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jcboConnPrinter3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jlblPrinterPort3)
.addComponent(jcboSerialPrinter3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jlblConnPrinter3))
.addGap(125, 125, 125))
);
m_jPrinterParams3.add(jPanel10, "comm");
jLabel28.setText(AppLocal.getIntString("label.javapos.printer")); // NOI18N
jLabel23.setText(AppLocal.getIntString("label.javapos.drawer")); // NOI18N
javax.swing.GroupLayout jPanel12Layout = new javax.swing.GroupLayout(jPanel12);
jPanel12.setLayout(jPanel12Layout);
jPanel12Layout.setHorizontalGroup(
jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel12Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel28, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_jtxtJPOSPrinter3, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel23, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_jtxtJPOSDrawer3, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(36, Short.MAX_VALUE))
);
jPanel12Layout.setVerticalGroup(
jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel12Layout.createSequentialGroup()
.addGroup(jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(m_jtxtJPOSPrinter3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel23)
.addComponent(m_jtxtJPOSDrawer3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel28))
.addGap(224, 224, 224))
);
m_jPrinterParams3.add(jPanel12, "javapos");
m_jScaleParams.setLayout(new java.awt.CardLayout());
m_jScaleParams.add(jPanel16, "empty");
jlblPrinterPort4.setText(AppLocal.getIntString("label.machineprinterport")); // NOI18N
jcboSerialScale.setEditable(true);
javax.swing.GroupLayout jPanel17Layout = new javax.swing.GroupLayout(jPanel17);
jPanel17.setLayout(jPanel17Layout);
jPanel17Layout.setHorizontalGroup(
jPanel17Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel17Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jlblPrinterPort4, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboSerialScale, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(270, Short.MAX_VALUE))
);
jPanel17Layout.setVerticalGroup(
jPanel17Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel17Layout.createSequentialGroup()
.addGroup(jPanel17Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jcboSerialScale, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jlblPrinterPort4))
.addGap(135, 135, 135))
);
m_jScaleParams.add(jPanel17, "comm");
m_jScannerParams.setLayout(new java.awt.CardLayout());
m_jScannerParams.add(jPanel24, "empty");
jlblPrinterPort5.setText(AppLocal.getIntString("label.machineprinterport")); // NOI18N
jcboSerialScanner.setEditable(true);
javax.swing.GroupLayout jPanel19Layout = new javax.swing.GroupLayout(jPanel19);
jPanel19.setLayout(jPanel19Layout);
jPanel19Layout.setHorizontalGroup(
jPanel19Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel19Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jlblPrinterPort5, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboSerialScanner, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(270, Short.MAX_VALUE))
);
jPanel19Layout.setVerticalGroup(
jPanel19Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel19Layout.createSequentialGroup()
.addGroup(jPanel19Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jcboSerialScanner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jlblPrinterPort5))
.addGap(235, 235, 235))
);
m_jScannerParams.add(jPanel19, "comm");
m_ReceiptPrinter.setText(AppLocal.getIntString("label.receiptprinter")); // NOI18N
javax.swing.GroupLayout jPanel13Layout = new javax.swing.GroupLayout(jPanel13);
jPanel13.setLayout(jPanel13Layout);
jPanel13Layout.setHorizontalGroup(
jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jtxtMachineHostname, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboMachineScreenmode, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(jLabel16, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboTicketsBag, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(jLabel15, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboMachineDisplay, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_jDisplayParams, javax.swing.GroupLayout.DEFAULT_SIZE, 484, Short.MAX_VALUE))
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboLAF, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboMachinePrinter, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_jPrinterParams1, javax.swing.GroupLayout.DEFAULT_SIZE, 484, Short.MAX_VALUE))
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(jLabel18, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboMachinePrinter2, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_jPrinterParams2, javax.swing.GroupLayout.DEFAULT_SIZE, 484, Short.MAX_VALUE))
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(jLabel19, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboMachinePrinter3, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_jPrinterParams3, javax.swing.GroupLayout.DEFAULT_SIZE, 484, Short.MAX_VALUE))
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(jLabel25, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboMachineScale, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_jScaleParams, javax.swing.GroupLayout.DEFAULT_SIZE, 484, Short.MAX_VALUE))
.addGroup(jPanel13Layout.createSequentialGroup()
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(jLabel26, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboMachineScanner, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cboPrinters, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(m_ReceiptPrinter)
.addComponent(m_jScannerParams, javax.swing.GroupLayout.DEFAULT_SIZE, 484, Short.MAX_VALUE))))
.addContainerGap())
);
jPanel13Layout.setVerticalGroup(
jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(jtxtMachineHostname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(6, 6, 6)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jcboLAF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(jcboMachineScreenmode, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel16)
.addComponent(jcboTicketsBag, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel15)
.addComponent(jcboMachineDisplay, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(m_jDisplayParams, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(jcboMachinePrinter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(m_jPrinterParams1, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel18)
.addComponent(jcboMachinePrinter2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(m_jPrinterParams2, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel19)
.addComponent(jcboMachinePrinter3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(m_jPrinterParams3, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel25)
.addComponent(jcboMachineScale, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(m_jScaleParams, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createSequentialGroup()
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel26)
.addComponent(jcboMachineScanner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(cboPrinters, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(m_jScannerParams, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_ReceiptPrinter)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel13, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel13, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(20, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
|
diff --git a/src/main/java/cz/cvut/fit/mi_mpr_dip/admission/dao/persistence/BaseUniqueConstraint.java b/src/main/java/cz/cvut/fit/mi_mpr_dip/admission/dao/persistence/BaseUniqueConstraint.java
index d4efb85..d180e3e 100644
--- a/src/main/java/cz/cvut/fit/mi_mpr_dip/admission/dao/persistence/BaseUniqueConstraint.java
+++ b/src/main/java/cz/cvut/fit/mi_mpr_dip/admission/dao/persistence/BaseUniqueConstraint.java
@@ -1,9 +1,9 @@
package cz.cvut.fit.mi_mpr_dip.admission.dao.persistence;
public abstract class BaseUniqueConstraint<T> implements UniqueConstraint<T> {
@Override
public Boolean isFound() {
- return !isFound();
+ return !isNotFound();
}
}
| true | true | public Boolean isFound() {
return !isFound();
}
| public Boolean isFound() {
return !isNotFound();
}
|
diff --git a/src/java-common/org/xins/common/spec/FunctionSpec.java b/src/java-common/org/xins/common/spec/FunctionSpec.java
index e120b89d6..c4672b4b6 100644
--- a/src/java-common/org/xins/common/spec/FunctionSpec.java
+++ b/src/java-common/org/xins/common/spec/FunctionSpec.java
@@ -1,713 +1,716 @@
/*
* $Id$
*
* Copyright 2003-2007 Orange Nederland Breedband B.V.
* See the COPYRIGHT file for redistribution and use restrictions.
*/
package org.xins.common.spec;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.xins.common.MandatoryArgumentChecker;
import org.xins.common.collections.ChainedMap;
import org.xins.common.text.ParseException;
import org.xins.common.xml.Element;
import org.xins.common.xml.ElementParser;
/**
* Specification of a function.
*
* @version $Revision$ $Date$
* @author <a href="mailto:[email protected]">Anthony Goubard</a>
*
* @since XINS 1.3.0
*/
public final class FunctionSpec extends Object {
//-------------------------------------------------------------------------
// Constructor
//-------------------------------------------------------------------------
/**
* Creates a new <code>Function</code> by parsing the function specification file.
*
* @param functionName
* the name of the function, cannot be <code>null</code>.
*
* @param reference
* the reference class used to get the defined type class, cannot be <code>null</code>.
*
* @param baseURL
* the base URL path where are located the specifications, cannot be <code>null</code>.
*
* @throws IllegalArgumentException
* if <code>functionName == null || reference == null || baseURL == null</code>.
*
* @throws InvalidSpecificationException
* if the specification is incorrect or cannot be found.
*/
FunctionSpec(String functionName, Class reference, String baseURL)
throws IllegalArgumentException, InvalidSpecificationException {
MandatoryArgumentChecker.check("functionName", functionName, "reference", reference, "baseURL", baseURL);
_functionName = functionName;
try {
Reader reader = APISpec.getReader(baseURL, functionName + ".fnc");
parseFunction(reader, reference, baseURL);
} catch (IOException ioe) {
throw new InvalidSpecificationException("[Function: " + functionName + "] Cannot read function.", ioe);
}
}
//-------------------------------------------------------------------------
// Fields
//-------------------------------------------------------------------------
/**
* Name of the function, cannot be <code>null</code>.
*/
private final String _functionName;
/**
* Description of the function, cannot be <code>null</code>.
*/
private String _description;
/**
* The input parameters of the function.
* The key is the name of the parameter, the value is the {@link FunctionSpec} object.
*/
private Map _inputParameters = new ChainedMap();
/**
* The input param combos of the function.
*/
private List _inputParamCombos = new ArrayList();
/**
* The input data section elements of the function.
*/
private Map _inputDataSectionElements = new ChainedMap();
/**
* The defined error code that the function can return.
*/
private Map _errorCodes = new ChainedMap();
/**
* The output parameters of the function.
* The key is the name of the parameter, the value is the <code>Parameter</code> object.
*/
private Map _outputParameters = new ChainedMap();
/**
* The output param combos of the function.
*/
private List _outputParamCombos = new ArrayList();
/**
* The output data section elements of the function.
*/
private Map _outputDataSectionElements = new ChainedMap();
//-------------------------------------------------------------------------
// Methods
//-------------------------------------------------------------------------
/**
* Gets the name of the function.
*
* @return
* the name of the function, never <code>null</code>.
*/
public String getName() {
return _functionName;
}
/**
* Gets the description of the function.
*
* @return
* the description of the function, never <code>null</code>.
*/
public String getDescription() {
return _description;
}
/**
* Gets the input parameter for the specified name.
*
* @param parameterName
* the name of the parameter, cannot be <code>null</code>.
*
* @return
* the parameter, never <code>null</code>.
*
* @throws EntityNotFoundException
* if the function does not contain any input parameter with the specified name.
*
* @throws IllegalArgumentException
* if <code>parameterName == null</code>.
*/
public ParameterSpec getInputParameter(String parameterName)
throws EntityNotFoundException, IllegalArgumentException {
MandatoryArgumentChecker.check("parameterName", parameterName);
ParameterSpec parameter = (ParameterSpec) _inputParameters.get(parameterName);
if (parameter == null) {
throw new EntityNotFoundException("Input parameter \"" + parameterName + "\" not found.");
}
return parameter;
}
/**
* Gets the input parameter specifications defined in the function.
* The key is the name of the parameter, the value is the {@link ParameterSpec} object.
*
* @return
* the input parameters, never <code>null</code>.
*/
public Map getInputParameters() {
return _inputParameters;
}
/**
* Gets the output parameter of the specified name.
*
* @param parameterName
* the name of the parameter, cannot be <code>null</code>.
*
* @return
* the parameter, never <code>null</code>.
*
* @throws IllegalArgumentException
* if <code>parameterName == null</code>.
*
* @throws EntityNotFoundException
* if the function does not contain any output parameter with the specified name.
*/
public ParameterSpec getOutputParameter(String parameterName)
throws IllegalArgumentException, EntityNotFoundException {
MandatoryArgumentChecker.check("parameterName", parameterName);
ParameterSpec parameter = (ParameterSpec) _outputParameters.get(parameterName);
if (parameter == null) {
throw new EntityNotFoundException("Output parameter \"" + parameterName + "\" not found.");
}
return parameter;
}
/**
* Gets the output parameter specifications defined in the function.
* The key is the name of the parameter, the value is the {@link ParameterSpec} object.
*
* @return
* the output parameters, never <code>null</code>.
*/
public Map getOutputParameters() {
return _outputParameters;
}
/**
* Gets the error code specification for the specified error code.
*
* @param errorCodeName
* the name of the error code, cannot be <code>null</code>.
*
* @return
* the error code specifications, never <code>null</code>.
*
* @throws IllegalArgumentException
* if <code>errorCodeName == null</code>.
*
* @throws EntityNotFoundException
* if the function does not define any error code with the specified name.
*/
public ErrorCodeSpec getErrorCode(String errorCodeName)
throws IllegalArgumentException, EntityNotFoundException {
MandatoryArgumentChecker.check("errorCodeName", errorCodeName);
ErrorCodeSpec errorCode = (ErrorCodeSpec) _errorCodes.get(errorCodeName);
if (errorCode == null) {
throw new EntityNotFoundException("Error code \"" + errorCodeName + "\" not found.");
}
return errorCode;
}
/**
* Gets the error code specifications defined in the function.
* The standard error codes are not included.
* The key is the name of the error code, the value is the {@link ErrorCodeSpec} object.
*
* @return
* The error code specifications, never <code>null</code>.
*/
public Map getErrorCodes() {
return _errorCodes;
}
/**
* Gets the specification of the element of the input data section with the
* specified name.
*
* @param elementName
* the name of the element, cannot be <code>null</code>.
*
* @return
* the specification of the input data section element, never <code>null</code>.
*
* @throws IllegalArgumentException
* if <code>elementName == null</code>.
*
* @throws EntityNotFoundException
* if the function does not define any input data element with the specified name.
*/
public DataSectionElementSpec getInputDataSectionElement(String elementName)
throws IllegalArgumentException, EntityNotFoundException {
MandatoryArgumentChecker.check("elementName", elementName);
DataSectionElementSpec element = (DataSectionElementSpec) _inputDataSectionElements.get(elementName);
if (element == null) {
throw new EntityNotFoundException("Input data section element \"" + elementName + "\" not found.");
}
return element;
}
/**
* Gets the specification of the elements of the input data section.
* The key is the name of the element, the value is the {@link DataSectionElementSpec} object.
*
* @return
* the input data section elements, never <code>null</code>.
*/
public Map getInputDataSectionElements() {
return _inputDataSectionElements;
}
/**
* Gets the specification of the element of the output data section with the
* specified name.
*
* @param elementName
* the name of the element, cannot be <code>null</code>.
*
* @return
* The specification of the output data section element, never <code>null</code>.
*
* @throws IllegalArgumentException
* if <code>elementName == null</code>.
*
* @throws EntityNotFoundException
* if the function does not define any output data element with the specified name.
*/
public DataSectionElementSpec getOutputDataSectionElement(String elementName)
throws IllegalArgumentException, EntityNotFoundException {
MandatoryArgumentChecker.check("elementName", elementName);
DataSectionElementSpec element = (DataSectionElementSpec) _outputDataSectionElements.get(elementName);
if (element == null) {
throw new EntityNotFoundException("Output data section element \"" + elementName + "\" not found.");
}
return element;
}
/**
* Gets the specification of the elements of the output data section.
* The key is the name of the element, the value is the {@link DataSectionElementSpec} object.
*
* @return
* the output data section elements, never <code>null</code>.
*/
public Map getOutputDataSectionElements() {
return _outputDataSectionElements;
}
/**
* Gets the input param combo specifications.
*
* @return
* the list of the input param combos specification
* ({@link ParamComboSpec}), never <code>null</code>.
*/
public List getInputParamCombos() {
return _inputParamCombos;
}
/**
* Gets the output param combo specifications.
*
* @return
* the list of the output param combos specification
* ({@link ParamComboSpec}), never <code>null</code>.
*/
public List getOutputParamCombos() {
return _outputParamCombos;
}
/**
* Parses the function specification file.
*
* @param reader
* the reader that contains the content of the result code file, cannot be <code>null</code>.
*
* @param reference
* the reference class used to get the defined type class, cannot be <code>null</code>.
*
* @param baseURL
* the base URL path where are located the specifications, cannot be <code>null</code>.
*
* @throws IllegalArgumentException
* if <code>reader == null || reference == null || baseURL == null</code>.
*
* @throws IOException
* if the parser cannot read the content.
*
* @throws InvalidSpecificationException
* if the result code file is incorrect.
*/
private void parseFunction(Reader reader, Class reference, String baseURL)
throws IllegalArgumentException, IOException, InvalidSpecificationException {
MandatoryArgumentChecker.check("reader", reader, "reference", reference, "baseURL", baseURL);
ElementParser parser = new ElementParser();
Element function = null;
try {
function = parser.parse(reader);
} catch (ParseException pe) {
throw new InvalidSpecificationException("[Function: " + _functionName + "] Cannot parse function.", pe);
}
List descriptionElementList = function.getChildElements("description");
if (descriptionElementList.isEmpty()) {
throw new InvalidSpecificationException("[Function: " + _functionName
+ "] No definition specified.");
}
Element descriptionElement = (Element) descriptionElementList.get(0);
_description = descriptionElement.getText();
List input = function.getChildElements("input");
if (input.size() > 0) {
// Input parameters
Element inputElement = (Element) input.get(0);
_inputParameters = parseParameters(reference, inputElement);
// Param combos
_inputParamCombos = parseCombos(inputElement, _inputParameters, true);
// Data section
List dataSections = inputElement.getChildElements("data");
if (dataSections.size() > 0) {
Element dataSection = (Element) dataSections.get(0);
_inputDataSectionElements = parseDataSectionElements(reference, dataSection, dataSection);
}
}
List output = function.getChildElements("output");
if (output.size() > 0) {
Element outputElement = (Element) output.get(0);
// Error codes
List errorCodesList = outputElement.getChildElements("resultcode-ref");
Iterator itErrorCodes = errorCodesList.iterator();
while (itErrorCodes.hasNext()) {
Element nextErrorCode = (Element) itErrorCodes.next();
String errorCodeName = nextErrorCode.getAttribute("name");
if (errorCodeName == null) {
throw new InvalidSpecificationException("[Function: " + _functionName
+ "] Missing name attribute for a error code.");
}
+ if (errorCodeName.indexOf('/') != -1) {
+ errorCodeName = errorCodeName.substring(errorCodeName.indexOf('/') + 1);
+ }
ErrorCodeSpec errorCodeSpec = new ErrorCodeSpec(errorCodeName, reference, baseURL);
_errorCodes.put(errorCodeName, errorCodeSpec);
}
// Output parameters
_outputParameters = parseParameters(reference, outputElement);
// Param combos
_outputParamCombos = parseCombos(outputElement, _outputParameters, true);
// Data section
List dataSections = outputElement.getChildElements("data");
if (dataSections.size() > 0) {
Element dataSection = (Element) dataSections.get(0);
_outputDataSectionElements = parseDataSectionElements(reference, dataSection, dataSection);
}
}
}
/**
* Parse an element in the data section.
*
* @param reference
* the reference class used to locate the files, cannot be <code>null</code>.
*
* @param topElement
* the element to parse, cannot be <code>null</code>.
*
* @param dataSection
* the data section, cannot be <code>null</code>.
*
* @return
* the top elements of the data section, or an empty array there is no
* data section.
*
* @throws IllegalArgumentException
* if <code>reference == null || topElement == null || dataSection == null</code>.
*
* @throws InvalidSpecificationException
* if the specification is incorrect.
*/
static Map parseDataSectionElements(Class reference, Element topElement, Element dataSection)
throws IllegalArgumentException, InvalidSpecificationException {
MandatoryArgumentChecker.check("reference", reference, "topElement", topElement, "dataSection", dataSection);
Map dataSectionElements = new ChainedMap();
// The <data> may have a "contains" attribute.
String dataContainsAttr = topElement.getAttribute("contains");
if (dataContainsAttr != null) {
DataSectionElementSpec dataSectionElement = getDataSectionElement(reference, dataContainsAttr, dataSection);
dataSectionElements.put(dataContainsAttr, dataSectionElement);
}
// Gets the sub elements of this element
List dataSectionContains = topElement.getChildElements("contains");
if (!dataSectionContains.isEmpty()) {
Element containsElement = (Element) dataSectionContains.get(0);
List contained = containsElement.getChildElements("contained");
Iterator itContained = contained.iterator();
while (itContained.hasNext()) {
Element containedElement = (Element) itContained.next();
String name = containedElement.getAttribute("element");
DataSectionElementSpec dataSectionElement = getDataSectionElement(reference, name, dataSection);
dataSectionElements.put(name, dataSectionElement);
}
}
return dataSectionElements;
}
/**
* Gets the specified element in the data section.
*
* @param reference
* the reference class used to locate the files, cannot be <code>null</code>.
*
* @param name
* the name of the element to retreive, cannot be <code>null</code>.
*
* @param dataSection
* the data section, cannot be <code>null</code>.
*
* @return
* the data section element or <code>null</code> if there is no element
* with the specified name.
*
* @throws IllegalArgumentException
* if <code>reference == null || name == null || dataSection == null</code>.
*
* @throws InvalidSpecificationException
* if the specification is incorrect.
*/
static DataSectionElementSpec getDataSectionElement(Class reference, String name, Element dataSection)
throws IllegalArgumentException, InvalidSpecificationException {
MandatoryArgumentChecker.check("reference", reference, "name", name, "dataSection", dataSection);
Iterator itElements = dataSection.getChildElements("element").iterator();
while (itElements.hasNext()) {
Element nextElement = (Element) itElements.next();
String nextName = nextElement.getAttribute("name");
if (name.equals(nextName)) {
String description = ((Element) nextElement.getChildElements("description").get(0)).getText();
Map subElements = parseDataSectionElements(reference, nextElement, dataSection);
boolean isPcdataEnable = false;
List dataSectionContains = nextElement.getChildElements("contains");
if (!dataSectionContains.isEmpty()) {
Element containsElement = (Element) dataSectionContains.get(0);
List pcdata = containsElement.getChildElements("pcdata");
if (!pcdata.isEmpty()) {
isPcdataEnable = true;
}
}
List attributesList = nextElement.getChildElements("attribute");
Map attributes = new ChainedMap();
Iterator itAttributes = attributesList.iterator();
while (itAttributes.hasNext()) {
ParameterSpec attribute = parseParameter(reference, (Element) itAttributes.next());
attributes.put(attribute.getName(), attribute);
}
List attributeCombos = parseCombos(nextElement, attributes, false);
DataSectionElementSpec result = new DataSectionElementSpec(nextName,
description, isPcdataEnable, subElements, attributes, attributeCombos);
return result;
}
}
return null;
}
/**
* Parses a function parameter or an attribute of a data section element.
*
* @param reference
* the reference class used to locate the files, cannot be <code>null</code>.
*
* @param paramElement
* the element that contains the specification of the parameter, cannot be <code>null</code>.
*
* @return
* the parameter, never <code>null</code>.
*
* @throws IllegalArgumentException
* if <code>reference == null || paramElement == null</code>.
*
* @throws InvalidSpecificationException
* if the specification is incorrect.
*/
static ParameterSpec parseParameter(Class reference, Element paramElement)
throws IllegalArgumentException, InvalidSpecificationException {
MandatoryArgumentChecker.check("reference", reference, "paramElement", paramElement);
String parameterName = paramElement.getAttribute("name");
if (parameterName == null) {
throw new InvalidSpecificationException("Missing name for a parameter.");
}
String parameterTypeName = paramElement.getAttribute("type");
boolean requiredParameter = "true".equals(paramElement.getAttribute("required"));
List descriptionElementList = paramElement.getChildElements("description");
if (descriptionElementList.isEmpty()) {
throw new InvalidSpecificationException("No definition specified for a parameter.");
}
String parameterDescription = ((Element) descriptionElementList.get(0)).getText();
ParameterSpec parameter = new ParameterSpec(reference ,parameterName,
parameterTypeName, requiredParameter, parameterDescription);
return parameter;
}
/**
* Parses the input or output parameters.
*
* @param reference
* the reference class used to locate the files, cannot be <code>null</code>.
*
* @param topElement
* the input or output element, cannot be <code>null</code>.
*
* @return
* a map containing the parameter names as keys, and the
* <code>Parameter</code> objects as value, never <code>null</code>.
*
* @throws IllegalArgumentException
* if <code>reference == null || topElement == null</code>.
*
* @throws InvalidSpecificationException
* if the specification is incorrect.
*/
static Map parseParameters(Class reference, Element topElement)
throws IllegalArgumentException, InvalidSpecificationException {
MandatoryArgumentChecker.check("reference", reference, "topElement", topElement);
List parametersList = topElement.getChildElements("param");
Map parameters = new ChainedMap();
Iterator itParameters = parametersList.iterator();
while (itParameters.hasNext()) {
Element nextParameter = (Element) itParameters.next();
ParameterSpec parameter = parseParameter(reference, nextParameter);
parameters.put(parameter.getName(), parameter);
}
return parameters;
}
/**
* Parses the param-combo element.
*
* @param topElement
* the input or output element, cannot be <code>null</code>.
*
* @param parameters
* the list of the input or output parameters or attributes, cannot be <code>null</code>.
*
* @param paramCombo
* <code>true</code> if a param-combo should be parsed, <code>false</code>
* if an attribute-combo should be parsed.
*
* @return
* the list of the param-combo elements or an empty array if no
* param-combo is defined, never <code>null</code>.
*
* @throws IllegalArgumentException
* if <code>topElement == null || parameters == null</code>.
*
* @throws InvalidSpecificationException
* if the format of the param-combo is incorrect.
*/
static List parseCombos(Element topElement, Map parameters, boolean paramCombo)
throws IllegalArgumentException, InvalidSpecificationException {
MandatoryArgumentChecker.check("topElement", topElement, "parameters", parameters);
String comboTag = paramCombo ? "param-combo" : "attribute-combo";
String referenceTag = paramCombo ? "param-ref" : "attribute-ref";
List paramCombosList = topElement.getChildElements(comboTag);
List paramCombos = new ArrayList(paramCombosList.size());
Iterator itParamCombos = paramCombosList.iterator();
while (itParamCombos.hasNext()) {
Element nextParamCombo = (Element) itParamCombos.next();
String type = nextParamCombo.getAttribute("type");
if (type == null) {
throw new InvalidSpecificationException("No type defined for " + comboTag + ".");
}
List paramDefs = nextParamCombo.getChildElements(referenceTag);
Iterator itParamDefs = paramDefs.iterator();
Map paramComboParameters = new ChainedMap();
while (itParamDefs.hasNext()) {
Element paramDef = (Element) itParamDefs.next();
String parameterName = paramDef.getAttribute("name");
if (parameterName == null) {
throw new InvalidSpecificationException("Missing name for a parameter in " + comboTag + ".");
}
ParameterSpec parameter = (ParameterSpec) parameters.get(parameterName);
if (parameter == null) {
throw new InvalidSpecificationException("Incorrect parameter name \"" +
parameterName + "\" in " + comboTag + ".");
}
paramComboParameters.put(parameterName, parameter);
}
if (paramCombo) {
ParamComboSpec paramComboSpec = new ParamComboSpec(type, paramComboParameters);
paramCombos.add(paramComboSpec);
} else {
AttributeComboSpec paramComboSpec = new AttributeComboSpec(type, paramComboParameters);
paramCombos.add(paramComboSpec);
}
}
return paramCombos;
}
}
| true | true | private void parseFunction(Reader reader, Class reference, String baseURL)
throws IllegalArgumentException, IOException, InvalidSpecificationException {
MandatoryArgumentChecker.check("reader", reader, "reference", reference, "baseURL", baseURL);
ElementParser parser = new ElementParser();
Element function = null;
try {
function = parser.parse(reader);
} catch (ParseException pe) {
throw new InvalidSpecificationException("[Function: " + _functionName + "] Cannot parse function.", pe);
}
List descriptionElementList = function.getChildElements("description");
if (descriptionElementList.isEmpty()) {
throw new InvalidSpecificationException("[Function: " + _functionName
+ "] No definition specified.");
}
Element descriptionElement = (Element) descriptionElementList.get(0);
_description = descriptionElement.getText();
List input = function.getChildElements("input");
if (input.size() > 0) {
// Input parameters
Element inputElement = (Element) input.get(0);
_inputParameters = parseParameters(reference, inputElement);
// Param combos
_inputParamCombos = parseCombos(inputElement, _inputParameters, true);
// Data section
List dataSections = inputElement.getChildElements("data");
if (dataSections.size() > 0) {
Element dataSection = (Element) dataSections.get(0);
_inputDataSectionElements = parseDataSectionElements(reference, dataSection, dataSection);
}
}
List output = function.getChildElements("output");
if (output.size() > 0) {
Element outputElement = (Element) output.get(0);
// Error codes
List errorCodesList = outputElement.getChildElements("resultcode-ref");
Iterator itErrorCodes = errorCodesList.iterator();
while (itErrorCodes.hasNext()) {
Element nextErrorCode = (Element) itErrorCodes.next();
String errorCodeName = nextErrorCode.getAttribute("name");
if (errorCodeName == null) {
throw new InvalidSpecificationException("[Function: " + _functionName
+ "] Missing name attribute for a error code.");
}
ErrorCodeSpec errorCodeSpec = new ErrorCodeSpec(errorCodeName, reference, baseURL);
_errorCodes.put(errorCodeName, errorCodeSpec);
}
// Output parameters
_outputParameters = parseParameters(reference, outputElement);
// Param combos
_outputParamCombos = parseCombos(outputElement, _outputParameters, true);
// Data section
List dataSections = outputElement.getChildElements("data");
if (dataSections.size() > 0) {
Element dataSection = (Element) dataSections.get(0);
_outputDataSectionElements = parseDataSectionElements(reference, dataSection, dataSection);
}
}
}
| private void parseFunction(Reader reader, Class reference, String baseURL)
throws IllegalArgumentException, IOException, InvalidSpecificationException {
MandatoryArgumentChecker.check("reader", reader, "reference", reference, "baseURL", baseURL);
ElementParser parser = new ElementParser();
Element function = null;
try {
function = parser.parse(reader);
} catch (ParseException pe) {
throw new InvalidSpecificationException("[Function: " + _functionName + "] Cannot parse function.", pe);
}
List descriptionElementList = function.getChildElements("description");
if (descriptionElementList.isEmpty()) {
throw new InvalidSpecificationException("[Function: " + _functionName
+ "] No definition specified.");
}
Element descriptionElement = (Element) descriptionElementList.get(0);
_description = descriptionElement.getText();
List input = function.getChildElements("input");
if (input.size() > 0) {
// Input parameters
Element inputElement = (Element) input.get(0);
_inputParameters = parseParameters(reference, inputElement);
// Param combos
_inputParamCombos = parseCombos(inputElement, _inputParameters, true);
// Data section
List dataSections = inputElement.getChildElements("data");
if (dataSections.size() > 0) {
Element dataSection = (Element) dataSections.get(0);
_inputDataSectionElements = parseDataSectionElements(reference, dataSection, dataSection);
}
}
List output = function.getChildElements("output");
if (output.size() > 0) {
Element outputElement = (Element) output.get(0);
// Error codes
List errorCodesList = outputElement.getChildElements("resultcode-ref");
Iterator itErrorCodes = errorCodesList.iterator();
while (itErrorCodes.hasNext()) {
Element nextErrorCode = (Element) itErrorCodes.next();
String errorCodeName = nextErrorCode.getAttribute("name");
if (errorCodeName == null) {
throw new InvalidSpecificationException("[Function: " + _functionName
+ "] Missing name attribute for a error code.");
}
if (errorCodeName.indexOf('/') != -1) {
errorCodeName = errorCodeName.substring(errorCodeName.indexOf('/') + 1);
}
ErrorCodeSpec errorCodeSpec = new ErrorCodeSpec(errorCodeName, reference, baseURL);
_errorCodes.put(errorCodeName, errorCodeSpec);
}
// Output parameters
_outputParameters = parseParameters(reference, outputElement);
// Param combos
_outputParamCombos = parseCombos(outputElement, _outputParameters, true);
// Data section
List dataSections = outputElement.getChildElements("data");
if (dataSections.size() > 0) {
Element dataSection = (Element) dataSections.get(0);
_outputDataSectionElements = parseDataSectionElements(reference, dataSection, dataSection);
}
}
}
|
diff --git a/tpc/src/serializers/BenchmarkRunner.java b/tpc/src/serializers/BenchmarkRunner.java
index 14a6aee..af03dce 100644
--- a/tpc/src/serializers/BenchmarkRunner.java
+++ b/tpc/src/serializers/BenchmarkRunner.java
@@ -1,119 +1,120 @@
package serializers;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;
import java.util.regex.Pattern;
import java.util.zip.DeflaterOutputStream;
import serializers.BenchmarkBase.Params;
import serializers.avro.AvroGeneric;
import serializers.avro.AvroSpecific;
import serializers.cks.CksBinary;
import serializers.cks.CksText;
import serializers.jackson.*;
import serializers.json.*;
import serializers.msgpack.MsgPack;
import serializers.protobuf.ActiveMQProtobuf;
import serializers.protobuf.Protobuf;
import serializers.protostuff.Protostuff;
import serializers.protostuff.ProtostuffJson;
import serializers.protostuff.ProtostuffSmile;
import serializers.xml.XmlJavolution;
import serializers.xml.XmlStax;
import serializers.xml.XmlXStream;
/**
* Full test of various codecs, using a single <code>MediaItem</code>
* as test data.
*/
public class BenchmarkRunner extends MediaItemBenchmark
{
public static void main(String[] args) {
new BenchmarkRunner().runBenchmark(args);
}
@Override
protected void addTests(TestGroups groups)
{
// Binary Formats; language-specific ones
JavaBuiltIn.register(groups);
JavaManual.register(groups);
// 06-May-2013, tatu: way too slow, commenting out for now, can add in slow section?
// Scala.register(groups);
// hessian, kryo and wobly are Java object serializations
Hessian.register(groups);
Kryo.register(groups);
Wobly.register(groups);
JBossSerialization.register(groups);
JBossMarshalling.register(groups);
// 06-May-2013, tatu: Fails on basic Java7, mismatch with Unsafe; commented out
// Obser.register(groups);
// Binary formats, generic: protobuf, thrift, avro, CKS, msgpack
Protobuf.register(groups);
// 16-May-2012, Nate: As discussed on mailing list, removed ActiveMQProtobuf as
// its lazy deserialization isn't comparable to other serializers.
// ActiveMQProtobuf.register(groups);
Protostuff.register(groups);
Thrift.register(groups);
AvroSpecific.register(groups);
AvroGeneric.register(groups);
CksBinary.register(groups);
MsgPack.register(groups);
// JSON
JacksonJsonManual.register(groups);
JacksonJsonDatabind.register(groups);
JacksonJsonAfterburner.register(groups); // databind with bytecode generation (faster)
// JacksonJsonTree.register(groups);
// 01-May-2012, tatu: not all that useful (IMO) for general comparisons
// JacksonJsonDatabindWithStrings.register(groups);
// JacksonJsonTreeWithStrings.register(groups);
JsonTwoLattes.register(groups);
ProtostuffJson.register(groups);
// too slow, why bother:
// ProtobufJson.register(groups);
JsonGsonManual.register(groups);
// JsonGsonTree.register(groups);
JsonGsonDatabind.register(groups);
JsonSvensonDatabind.register(groups);
FlexjsonDatabind.register(groups);
JsonLibJsonDatabind.register(groups);
FastJSONDatabind.register(groups);
JsonSimpleWithContentHandler.register(groups);
// JsonSimpleManualTree.register(groups);
JsonSmartManualTree.register(groups);
JsonDotOrgManualTree.register(groups);
JsonijJpath.register(groups);
// JsonijManualTree.register(groups);
JsonArgoTree.register(groups);
- JsonPathDeserializerOnly.register(groups);
+// 06-May-2013, tatu: Too slow (100x above fastest)
+// JsonPathDeserializerOnly.register(groups);
// Then JSON-like
// CKS text is textual JSON-like format
CksText.register(groups);
// then binary variants
// Smile is 1-to-1 binary JSON serialization
JacksonSmileManual.register(groups);
JacksonSmileDatabind.register(groups);
JacksonSmileAfterburner.register(groups); // databind with bytecode generation (faster)
// 06-May-2013, tatu: Unfortunately there is a version conflict
// here too -- commenting out, to let David fix it
// ProtostuffSmile.register(groups);
// BSON is JSON-like format with extended datatypes
JacksonBsonDatabind.register(groups);
MongoDB.register(groups);
// YAML (using Jackson module built on SnakeYAML)
JacksonYAMLDatabind.register(groups);
// XML-based formats.
XmlStax.register(groups, true, true, true); // woodstox/aalto/fast-infoset
XmlXStream.register(groups);
JacksonXmlDatabind.register(groups);
XmlJavolution.register(groups);
}
}
| true | true | protected void addTests(TestGroups groups)
{
// Binary Formats; language-specific ones
JavaBuiltIn.register(groups);
JavaManual.register(groups);
// 06-May-2013, tatu: way too slow, commenting out for now, can add in slow section?
// Scala.register(groups);
// hessian, kryo and wobly are Java object serializations
Hessian.register(groups);
Kryo.register(groups);
Wobly.register(groups);
JBossSerialization.register(groups);
JBossMarshalling.register(groups);
// 06-May-2013, tatu: Fails on basic Java7, mismatch with Unsafe; commented out
// Obser.register(groups);
// Binary formats, generic: protobuf, thrift, avro, CKS, msgpack
Protobuf.register(groups);
// 16-May-2012, Nate: As discussed on mailing list, removed ActiveMQProtobuf as
// its lazy deserialization isn't comparable to other serializers.
// ActiveMQProtobuf.register(groups);
Protostuff.register(groups);
Thrift.register(groups);
AvroSpecific.register(groups);
AvroGeneric.register(groups);
CksBinary.register(groups);
MsgPack.register(groups);
// JSON
JacksonJsonManual.register(groups);
JacksonJsonDatabind.register(groups);
JacksonJsonAfterburner.register(groups); // databind with bytecode generation (faster)
// JacksonJsonTree.register(groups);
// 01-May-2012, tatu: not all that useful (IMO) for general comparisons
// JacksonJsonDatabindWithStrings.register(groups);
// JacksonJsonTreeWithStrings.register(groups);
JsonTwoLattes.register(groups);
ProtostuffJson.register(groups);
// too slow, why bother:
// ProtobufJson.register(groups);
JsonGsonManual.register(groups);
// JsonGsonTree.register(groups);
JsonGsonDatabind.register(groups);
JsonSvensonDatabind.register(groups);
FlexjsonDatabind.register(groups);
JsonLibJsonDatabind.register(groups);
FastJSONDatabind.register(groups);
JsonSimpleWithContentHandler.register(groups);
// JsonSimpleManualTree.register(groups);
JsonSmartManualTree.register(groups);
JsonDotOrgManualTree.register(groups);
JsonijJpath.register(groups);
// JsonijManualTree.register(groups);
JsonArgoTree.register(groups);
JsonPathDeserializerOnly.register(groups);
// Then JSON-like
// CKS text is textual JSON-like format
CksText.register(groups);
// then binary variants
// Smile is 1-to-1 binary JSON serialization
JacksonSmileManual.register(groups);
JacksonSmileDatabind.register(groups);
JacksonSmileAfterburner.register(groups); // databind with bytecode generation (faster)
// 06-May-2013, tatu: Unfortunately there is a version conflict
// here too -- commenting out, to let David fix it
// ProtostuffSmile.register(groups);
// BSON is JSON-like format with extended datatypes
JacksonBsonDatabind.register(groups);
MongoDB.register(groups);
// YAML (using Jackson module built on SnakeYAML)
JacksonYAMLDatabind.register(groups);
// XML-based formats.
XmlStax.register(groups, true, true, true); // woodstox/aalto/fast-infoset
XmlXStream.register(groups);
JacksonXmlDatabind.register(groups);
XmlJavolution.register(groups);
}
| protected void addTests(TestGroups groups)
{
// Binary Formats; language-specific ones
JavaBuiltIn.register(groups);
JavaManual.register(groups);
// 06-May-2013, tatu: way too slow, commenting out for now, can add in slow section?
// Scala.register(groups);
// hessian, kryo and wobly are Java object serializations
Hessian.register(groups);
Kryo.register(groups);
Wobly.register(groups);
JBossSerialization.register(groups);
JBossMarshalling.register(groups);
// 06-May-2013, tatu: Fails on basic Java7, mismatch with Unsafe; commented out
// Obser.register(groups);
// Binary formats, generic: protobuf, thrift, avro, CKS, msgpack
Protobuf.register(groups);
// 16-May-2012, Nate: As discussed on mailing list, removed ActiveMQProtobuf as
// its lazy deserialization isn't comparable to other serializers.
// ActiveMQProtobuf.register(groups);
Protostuff.register(groups);
Thrift.register(groups);
AvroSpecific.register(groups);
AvroGeneric.register(groups);
CksBinary.register(groups);
MsgPack.register(groups);
// JSON
JacksonJsonManual.register(groups);
JacksonJsonDatabind.register(groups);
JacksonJsonAfterburner.register(groups); // databind with bytecode generation (faster)
// JacksonJsonTree.register(groups);
// 01-May-2012, tatu: not all that useful (IMO) for general comparisons
// JacksonJsonDatabindWithStrings.register(groups);
// JacksonJsonTreeWithStrings.register(groups);
JsonTwoLattes.register(groups);
ProtostuffJson.register(groups);
// too slow, why bother:
// ProtobufJson.register(groups);
JsonGsonManual.register(groups);
// JsonGsonTree.register(groups);
JsonGsonDatabind.register(groups);
JsonSvensonDatabind.register(groups);
FlexjsonDatabind.register(groups);
JsonLibJsonDatabind.register(groups);
FastJSONDatabind.register(groups);
JsonSimpleWithContentHandler.register(groups);
// JsonSimpleManualTree.register(groups);
JsonSmartManualTree.register(groups);
JsonDotOrgManualTree.register(groups);
JsonijJpath.register(groups);
// JsonijManualTree.register(groups);
JsonArgoTree.register(groups);
// 06-May-2013, tatu: Too slow (100x above fastest)
// JsonPathDeserializerOnly.register(groups);
// Then JSON-like
// CKS text is textual JSON-like format
CksText.register(groups);
// then binary variants
// Smile is 1-to-1 binary JSON serialization
JacksonSmileManual.register(groups);
JacksonSmileDatabind.register(groups);
JacksonSmileAfterburner.register(groups); // databind with bytecode generation (faster)
// 06-May-2013, tatu: Unfortunately there is a version conflict
// here too -- commenting out, to let David fix it
// ProtostuffSmile.register(groups);
// BSON is JSON-like format with extended datatypes
JacksonBsonDatabind.register(groups);
MongoDB.register(groups);
// YAML (using Jackson module built on SnakeYAML)
JacksonYAMLDatabind.register(groups);
// XML-based formats.
XmlStax.register(groups, true, true, true); // woodstox/aalto/fast-infoset
XmlXStream.register(groups);
JacksonXmlDatabind.register(groups);
XmlJavolution.register(groups);
}
|
diff --git a/activejdbc/src/test/java/org/javalite/activejdbc/Defect149Test.java b/activejdbc/src/test/java/org/javalite/activejdbc/Defect149Test.java
index 1eb04675..a085d2d0 100644
--- a/activejdbc/src/test/java/org/javalite/activejdbc/Defect149Test.java
+++ b/activejdbc/src/test/java/org/javalite/activejdbc/Defect149Test.java
@@ -1,26 +1,26 @@
package org.javalite.activejdbc;
import org.javalite.activejdbc.test.ActiveJDBCTest;
import org.javalite.activejdbc.test_models.User;
import org.javalite.test.SystemStreamUtil;
import org.junit.Test;
/**
* @author Igor Polevoy: 4/2/12 4:45 PM
*/
public class Defect149Test extends ActiveJDBCTest {
@Test
public void shouldNotIncludeNullValuesIntoInsertStatement(){
deleteAndPopulateTable("users");
User user = new User();
user.set("email", "[email protected]");
- SystemStreamUtil.replaceError();
+ SystemStreamUtil.replaceOut();
user.saveIt();
- a(SystemStreamUtil.getSystemErr()).shouldContain("INSERT INTO users (email) VALUES (?)");
+ //this is tested manually, for some reason, Maven does something stupid with streams, can't catch them
}
}
| false | true | public void shouldNotIncludeNullValuesIntoInsertStatement(){
deleteAndPopulateTable("users");
User user = new User();
user.set("email", "[email protected]");
SystemStreamUtil.replaceError();
user.saveIt();
a(SystemStreamUtil.getSystemErr()).shouldContain("INSERT INTO users (email) VALUES (?)");
}
| public void shouldNotIncludeNullValuesIntoInsertStatement(){
deleteAndPopulateTable("users");
User user = new User();
user.set("email", "[email protected]");
SystemStreamUtil.replaceOut();
user.saveIt();
//this is tested manually, for some reason, Maven does something stupid with streams, can't catch them
}
|
diff --git a/src/main/java/com/hmsonline/cassandra/triggers/TriggerTask.java b/src/main/java/com/hmsonline/cassandra/triggers/TriggerTask.java
index 02f6a15..e934c38 100644
--- a/src/main/java/com/hmsonline/cassandra/triggers/TriggerTask.java
+++ b/src/main/java/com/hmsonline/cassandra/triggers/TriggerTask.java
@@ -1,66 +1,66 @@
package com.hmsonline.cassandra.triggers;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TriggerTask implements Runnable {
private static int THREAD_POOL_SIZE = 20;
private static int MAX_QUEUE_SIZE = 500;
private List<Thread> threadPool = new ArrayList<Thread>();
private BlockingQueue<LogEntry> workQueue = null;
private ProcessingManager processing;
private static Logger logger = LoggerFactory.getLogger(TriggerTask.class);
public TriggerTask() {
processing = new ProcessingManager();
workQueue = new ArrayBlockingQueue<LogEntry>(MAX_QUEUE_SIZE);
// Spinning up new thread pool
logger.debug("Spawning [" + THREAD_POOL_SIZE + "] threads for commit log processing.");
for (int i = 0; i < THREAD_POOL_SIZE; i++) {
TriggerExecutionThread runnable = new TriggerExecutionThread(workQueue, processing);
Thread thread = new Thread(runnable);
threadPool.add(thread);
thread.start();
}
}
public void run() {
boolean gotUpdates = false;
while (true) {
gotUpdates = false;
try {
if (ConfigurationStore.getStore().isCommitLogEnabled()) {
List<LogEntry> logEntries = CommitLog.getCommitLog().getPending();
if (logger.isDebugEnabled() && logEntries != null) {
logger.debug("Processing [" + logEntries.size() + "] logEntries.");
}
for (LogEntry logEntry : logEntries) {
if (!processing.isAlreadyBeingProcessed(logEntry.getUuid())) {
gotUpdates = true;
workQueue.put(logEntry);
processing.add(logEntry.getUuid());
}
}
} else {
logger.debug("Skipping trigger execution because commit log is disabled.");
}
} catch (Throwable t) {
- logger.warn("Could not execute triggers.", t.getMessage());
+ logger.warn("Could not execute triggers [" + t.getMessage() + "]");
logger.debug("Cause for not executing triggers.", t);
}
if (!gotUpdates) {
try {
Thread.sleep(1000);
} catch (Exception e) {
logger.error("Couldn't sleep.", e);
}
}
}
}
}
| true | true | public void run() {
boolean gotUpdates = false;
while (true) {
gotUpdates = false;
try {
if (ConfigurationStore.getStore().isCommitLogEnabled()) {
List<LogEntry> logEntries = CommitLog.getCommitLog().getPending();
if (logger.isDebugEnabled() && logEntries != null) {
logger.debug("Processing [" + logEntries.size() + "] logEntries.");
}
for (LogEntry logEntry : logEntries) {
if (!processing.isAlreadyBeingProcessed(logEntry.getUuid())) {
gotUpdates = true;
workQueue.put(logEntry);
processing.add(logEntry.getUuid());
}
}
} else {
logger.debug("Skipping trigger execution because commit log is disabled.");
}
} catch (Throwable t) {
logger.warn("Could not execute triggers.", t.getMessage());
logger.debug("Cause for not executing triggers.", t);
}
if (!gotUpdates) {
try {
Thread.sleep(1000);
} catch (Exception e) {
logger.error("Couldn't sleep.", e);
}
}
}
}
| public void run() {
boolean gotUpdates = false;
while (true) {
gotUpdates = false;
try {
if (ConfigurationStore.getStore().isCommitLogEnabled()) {
List<LogEntry> logEntries = CommitLog.getCommitLog().getPending();
if (logger.isDebugEnabled() && logEntries != null) {
logger.debug("Processing [" + logEntries.size() + "] logEntries.");
}
for (LogEntry logEntry : logEntries) {
if (!processing.isAlreadyBeingProcessed(logEntry.getUuid())) {
gotUpdates = true;
workQueue.put(logEntry);
processing.add(logEntry.getUuid());
}
}
} else {
logger.debug("Skipping trigger execution because commit log is disabled.");
}
} catch (Throwable t) {
logger.warn("Could not execute triggers [" + t.getMessage() + "]");
logger.debug("Cause for not executing triggers.", t);
}
if (!gotUpdates) {
try {
Thread.sleep(1000);
} catch (Exception e) {
logger.error("Couldn't sleep.", e);
}
}
}
}
|
diff --git a/rultor-base/src/main/java/com/rultor/base/GetterOf.java b/rultor-base/src/main/java/com/rultor/base/GetterOf.java
index 02d4954d0..230b31a8e 100644
--- a/rultor-base/src/main/java/com/rultor/base/GetterOf.java
+++ b/rultor-base/src/main/java/com/rultor/base/GetterOf.java
@@ -1,144 +1,140 @@
/**
* Copyright (c) 2009-2013, rultor.com
* 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 the rultor.com nor
* the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.rultor.base;
import com.jcabi.aspects.Immutable;
import com.jcabi.aspects.Loggable;
import com.rultor.spi.Proxy;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.MethodDescriptor;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.validation.constraints.NotNull;
import lombok.EqualsAndHashCode;
/**
* Retrieves a string property from an object.
*
* @author Krzysztof Krason ([email protected])
* @version $Id$
* @since 1.0
*/
@Immutable
@EqualsAndHashCode(of = { "source", "property" })
@Loggable(Loggable.DEBUG)
public final class GetterOf implements Proxy<Object> {
/**
* Object from which to get property.
*/
private final transient Object source;
/**
* Name of the property to retrieve.
*/
private final transient String property;
/**
* Public ctor.
* @param src Source of the property.
* @param prop Property name.
*/
public GetterOf(
@NotNull(message = "object can't be null") final Object src,
@NotNull(message = "property can't be null") final String prop
) {
this.source = src;
this.property = prop;
}
/**
* Find method with getter.
* @param info Bean info.
* @return Found method.
*/
private Method find(final BeanInfo info) {
- Method foundMethod = null;
- boolean found = false;
+ Method found = null;
for (PropertyDescriptor descr : info.getPropertyDescriptors()) {
if (descr.getName().equals(this.property)
&& (descr.getReadMethod() != null)) {
- foundMethod = descr.getReadMethod();
- found = true;
+ found = descr.getReadMethod();
break;
}
}
- if (!found) {
+ if (found == null) {
for (MethodDescriptor descr : info.getMethodDescriptors()) {
if (descr.getName().equals(this.property)
&& (descr.getMethod().getParameterTypes().length == 0)) {
- foundMethod = descr.getMethod();
- found = true;
+ found = descr.getMethod();
break;
}
}
}
- if (found) {
- return foundMethod;
- } else {
+ if (found == null) {
throw new IllegalArgumentException(
String.format(
"Object should have a getter for property '%s'",
this.property
)
);
}
+ return found;
}
/**
* {@inheritDoc}
*/
@Override
public Object object() {
try {
return this.find(Introspector.getBeanInfo(this.source.getClass()))
.invoke(this.source);
} catch (IntrospectionException ex) {
throw new IllegalArgumentException(ex);
} catch (InvocationTargetException ex) {
throw new IllegalArgumentException(ex);
} catch (IllegalAccessException ex) {
throw new IllegalArgumentException(ex);
}
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return String.format(
"Gets '%s' property from %s", this.property, this.source
);
}
}
| false | true | private Method find(final BeanInfo info) {
Method foundMethod = null;
boolean found = false;
for (PropertyDescriptor descr : info.getPropertyDescriptors()) {
if (descr.getName().equals(this.property)
&& (descr.getReadMethod() != null)) {
foundMethod = descr.getReadMethod();
found = true;
break;
}
}
if (!found) {
for (MethodDescriptor descr : info.getMethodDescriptors()) {
if (descr.getName().equals(this.property)
&& (descr.getMethod().getParameterTypes().length == 0)) {
foundMethod = descr.getMethod();
found = true;
break;
}
}
}
if (found) {
return foundMethod;
} else {
throw new IllegalArgumentException(
String.format(
"Object should have a getter for property '%s'",
this.property
)
);
}
}
| private Method find(final BeanInfo info) {
Method found = null;
for (PropertyDescriptor descr : info.getPropertyDescriptors()) {
if (descr.getName().equals(this.property)
&& (descr.getReadMethod() != null)) {
found = descr.getReadMethod();
break;
}
}
if (found == null) {
for (MethodDescriptor descr : info.getMethodDescriptors()) {
if (descr.getName().equals(this.property)
&& (descr.getMethod().getParameterTypes().length == 0)) {
found = descr.getMethod();
break;
}
}
}
if (found == null) {
throw new IllegalArgumentException(
String.format(
"Object should have a getter for property '%s'",
this.property
)
);
}
return found;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.